diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/LICENSE-openai-math b/LICENSE-openai-math new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/LICENSE-openai-math @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/NOTICE b/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..fae4ff914b04978198c09723c58b315fa8733f0f --- /dev/null +++ b/NOTICE @@ -0,0 +1,38 @@ +openai-math-harbor +================== + +This dataset packages the Lean statements of OpenAI's "openai/math" release as Harbor tasks. + +Redistributed material +---------------------- +Each task's tests/Challenge.lean, and the Lean block quoted in its instruction.md, is the file +lean/ComparatorChallenges/.lean from https://github.com/openai/math at commit +adc7f1241b42e322a6451854ab7e4b4c146bf78a, copyright OpenAI, licensed under the Apache License, Version 2.0 (see +LICENSE-openai-math). The files are unchanged. + +Modified material +----------------- +The Comparator configuration of each task (tests/task.json) is derived from the corresponding +lean/ComparatorChallenges/.json in that repository. In eight tasks, definitions that the +original listed under "definition_names" although their bodies are written out were removed from +that list, so that Comparator requires them to match exactly; task.toml records them under +[metadata] fixed_definitions. + +Only statements whose official proof was verified in the environment are included; the README +lists the others and why each could not be validated. One challenge (DefocusingNLS) is left out +by design. + +Not included +------------ +OpenAI's proofs (the lean/OAI library) are not part of this dataset. + +Everything else in this dataset (task.toml, instruction.md apart from the quoted statement, +tests/grade.py, tests/test.sh, environment/, solution/, generator/) is licensed under the +Apache License, Version 2.0 (see LICENSE). + +Third-party software in the sandbox image +----------------------------------------- +Lean 4 and Mathlib (Apache-2.0); Comparator and lean4export by the Lean FRO (Apache-2.0), +Comparator built from leanprover/comparator@d03acab with a one-line patch that passes +LEAN_NUM_THREADS into its sandbox; landrun (MIT). The image is built from environment/ at run +time; none of this software is stored in the dataset. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e333acd8986f5a64603903794129fbf9607af2a0 --- /dev/null +++ b/README.md @@ -0,0 +1,202 @@ +--- +license: apache-2.0 +task_categories: +- other +tags: +- harbor +- rl-environment +- reinforcement-learning +- code-agent +- lean4 +- mathlib +- theorem-proving +- openai-math +pretty_name: "openai/math as Harbor environments" +--- + +# openai/math as Harbor environments + +> **Experimental.** Built on a research release that is itself new and not yet independently +> reviewed. Expect rough edges, and read any proof that scores 1 before relying on it. + +We ported the math problems from OpenAI's [openai/math](https://github.com/openai/math) release +(commit `adc7f12`) into [Harbor](https://github.com/harbor-framework/harbor) environments. +The release formalizes **405** of its results as Lean statements. This dataset contains +**355 environments**, the ones whose official proof we verified end to end in the environment, +covering 209 result families across 17 fields. The other 50 are listed +under [Validation](#validation) with the reason each could not be validated. + +## How a task works + +The agent gets a sandbox with Lean 4 and a prebuilt Mathlib, no internet, and one of OpenAI's +theorems written in Lean with `sorry` where the proof should be. + +**What `sorry` means.** In Lean, `sorry` is a placeholder for a missing proof: it lets the file +compile as if the step were proven, but nothing has actually been shown, and Lean flags it. The +statement is given exactly as OpenAI formalized it, and the agent's job is to replace every `sorry` +with a real proof. + +When the agent finishes, a separate, fresh sandbox checks its proof with +[Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker: + +- **reward 1** if the theorem has exactly the original statement, the proof uses only Lean's + standard axioms (`propext`, `Quot.sound`, `Classical.choice`, so no leftover `sorry` and no new + axioms), and the Lean kernel accepts it; +- **reward 0** otherwise. + +OpenAI's own proofs serve as the reference solutions: Harbor's oracle fetches them from GitHub at +run time. They are not included here and the agent never sees them. + +## A strict reward + +The grader only accepts a complete proof of the statement exactly as OpenAI formalized it. That +makes it hard to game, but it is also a real limitation for problems like these: + +- a correct proof of an equivalent statement, written with different definitions or a different + formulation, scores 0; +- partial progress (useful lemmas, a proof of a special case, a correct strategy with a gap) scores 0; +- nothing rewards a creative approach unless it ends in a complete proof of this exact statement. + +For open research problems, a more general reward function that recognizes any valid solution to the +underlying problem, including creative reformulations and partial progress, would be a better +training signal. We use the strict check here because it is precise and cannot be fooled; treat it +as one end of that design space. + +## What's included + +- `tasks/` — one Harbor task per validated problem: instruction, Lean statement, sandbox image recipe, + verifier and oracle +- `registry.json` — Harbor registry entry (`openai-math-harbor@1.0`) +- `manifest.parquet` — one row per task: field, family, theorem names, reference-proof size, oracle + result +- `generator/` — the code that builds the sandbox image and regenerates the tasks from openai/math +- `LICENSE`, `NOTICE`, `LICENSE-openai-math` — licensing and attribution + +## Run it with the Harbor CLI + +You need Harbor 0.24+ with the Daytona backend (`DAYTONA_API_KEY`, `DAYTONA_API_URL`) and +credentials for the agent you run. + +```bash +pip install "harbor[daytona]>=0.24" daytona +hf download FineEnvs/openai-math-harbor --repo-type dataset --local-dir openai-math-harbor +cd openai-math-harbor + +# Build the shared sandbox image once (Lean 4, Mathlib, Comparator; ~9 GB, about an hour). +(cd generator && python -m openai_math_harbor.snapshot) +SNAP=$(cd generator && python -m openai_math_harbor.snapshot --print-name) + +# Run any agent Harbor supports (`harbor agent list`) on a few tasks: +harbor run -p tasks -e daytona --ek snapshot_template_name=$SNAP \ + -a -m -i plane-coloring -i hilbert-crouzeix -n 2 + +# Check that the grader accepts OpenAI's own proof of a task: +harbor run -p tasks -e daytona --ek snapshot_template_name=$SNAP \ + -a oracle --allow-agent-host github.com -i plane-coloring +``` + +Each task asks for 4 CPUs, 8 GB of memory and 10 GB of disk, and gives the agent 4 hours. Task +names are the folder names under `tasks/`. + +## Validation + +We generated a task for every statement except one left out by design (`DefocusingNLS`, whose +statement has a `sorry` inside a definition its theorems depend on), and ran Harbor's oracle on each: +it submits OpenAI's own proof and has it graded by the same verifier an agent faces. Only tasks whose +official proof was accepted are included. + +| Oracle result | Tasks | Meaning | +|---|---|---| +| accepted | 355 | OpenAI's proof is accepted: the environment is verified end to end | +| missing-package | 16 | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| definition-mismatch | 2 | OpenAI's proof writes a definition with the same text but it compiles differently, so the exact-match check fails | +| memory | 5 | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | +| disk | 4 | OpenAI's proof is too large for the sandbox's 10 GB disk | +| not completed | 22 | grading did not complete in our run | + +Grading an accepted proof took 16 minutes at the median. Each task's result is in its `task.toml` (`oracle_result`) and in `manifest.parquet`. + +
50 statements not included (click to expand) + +| Statement | Why it could not be validated | +|---|---| +| `arnold-counterexample` | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | +| `atomic-gaussian` | grading did not complete in our run | +| `catalan` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `coarse-assembly` | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | +| `continuum-coulomb-hardness` | OpenAI's proof is too large for the sandbox's 10 GB disk | +| `cycle-clique-ramsey` | grading did not complete in our run | +| `defocusing-nls` | left out by design: OAI.DefocusingNLS.sobolevProduct: open definition the theorem statements depend on | +| `dirichlet-seven-eighths` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `duke-prime-degree` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `einstein-four` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `erdos-reciprocal` | OpenAI's proof is too large for the sandbox's 10 GB disk | +| `hecke-seven-eighths` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `invariant-ising` | grading did not complete in our run | +| `jacobsthal` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `jacobsthal-improved` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `joint-dickman` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `koebe-circle-domains` | OpenAI's proof is too large for the sandbox's 10 GB disk | +| `matrix-multiplication` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `mub-six` | grading did not complete in our run | +| `nuclear-ultrapower` | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | +| `occupied-overlap` | OpenAI's proof writes a definition with the same text but it compiles differently, so the exact-match check fails | +| `ordinary-two-point-correlations` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `ostmann-complete` | grading did not complete in our run | +| `ostmann-primes` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `patterson-first-moment` | OpenAI's proof is too large for the sandbox's 10 GB disk | +| `planar-packing` | grading did not complete in our run | +| `polycyclic-recognition` | grading did not complete in our run | +| `quasi-riemann-hypothesis` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `ramsey-five` | grading did not complete in our run | +| `riesz-quantitative` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `sat-computability` | grading did not complete in our run | +| `sharp-log-ramsey` | grading did not complete in our run | +| `siegel-zeros` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `simple-amenable` | grading did not complete in our run | +| `simple-overgroups` | grading did not complete in our run | +| `sk-barriers` | grading did not complete in our run | +| `sk-high-temperature` | grading did not complete in our run | +| `sk-ratio` | grading did not complete in our run | +| `smooth-yau` | grading did not complete in our run | +| `snaky-certificate` | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | +| `snaky-conditional` | grading did not complete in our run | +| `snaky-twenty-one` | grading did not complete in our run | +| `spin-angle` | OpenAI's proof writes a definition with the same text but it compiles differently, so the exact-match check fails | +| `standard-map-components` | grading did not complete in our run | +| `strong-kadison-kastler` | grading did not complete in our run | +| `surface-immersion` | grading did not complete in our run | +| `taming-compatibility` | grading did not complete in our run | +| `totient-asymptotic` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `totient-companion-zero` | OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include | +| `universal-tensor-squares` | OpenAI's proof needs more than the sandbox's 8 GB of memory to build | + +
+ +The verifier was also tested against submissions that try to cheat (`sorry` in several disguises, +fake axioms, `native_decide`, weakened statements, redefined definitions, planted reward files, code +that runs during grading). All scored 0. A no-op agent scores 0. + +## Notes + +- **Configs.** In eight of openai/math's Comparator configs, definitions written out in the statement + were listed as "holes" that Comparator does not check, so a solution could redefine them. Here they + must match exactly; affected tasks list them under `fixed_definitions` in `task.toml`. +- **Contamination.** The statements and proofs have been public since 6 October 2026. +- **Difficulty.** These are open research problems; expect reward 0 on almost every task. + +Technical details (grading design, threat model, image recipe) are in `generator/README.md`. + +## License + +- The Lean statements are copied unchanged from [openai/math](https://github.com/openai/math) + (© OpenAI), licensed under the + [Apache License 2.0](https://github.com/openai/math/blob/main/LICENSE); see `LICENSE-openai-math` + and `NOTICE`. OpenAI's proofs are not redistributed. +- The packaging, verifier and generator are Apache-2.0 (`LICENSE`). +- The sandbox image is built from [Lean 4](https://github.com/leanprover/lean4) and + [Mathlib](https://github.com/leanprover-community/mathlib4) (Apache-2.0), + [Comparator](https://github.com/leanprover/comparator) and + [lean4export](https://github.com/leanprover/lean4export) (Apache-2.0), and + [landrun](https://github.com/Zouuup/landrun) (MIT). +- If you use the results, cite the openai/math manuscripts as that repository asks. diff --git a/generator/README.md b/generator/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0f74bcd51fff2ec2f70390a4688caf3bd816f6ff --- /dev/null +++ b/generator/README.md @@ -0,0 +1,160 @@ +# Generator and verifier: technical notes + +This directory produces the Harbor tasks in `../tasks/` from a checkout of +[openai/math](https://github.com/openai/math), builds the sandbox image they run in, and contains +the verifier. The dataset card (`../README.md`) covers what the environment is and how to run it; +this file covers how the tasks are generated and graded, the threat model, and the checks behind +the validation. + +## Layout + +``` +openai_math_harbor/ + challenges.py reads the challenges, maps them to families, applies the hole policy + import_graph.py import graph of the openai/math Lean library (reference-proof closures) + oracle.py closure and packaging of the reference proofs + reference.py places a reference proof as a submission (copied into each task's solution/) + adapter.py writes tasks/, registry.json, manifest.parquet, the card and NOTICE + snapshot.py builds the shared Daytona snapshot from image/ + report.py turns a Harbor oracle job into per-task verdicts + attacks.py adversarial submissions used to test the verifier + templates/ instruction, verifier (tests/grade.py, test.sh), oracle (solve.sh), card +image/ Dockerfile and setup scripts for the shared image (= every task's environment/) +tests/ unit tests for the verifier's submission handling +``` + +## Regenerating the tasks + +```bash +# A sparse checkout of openai/math at the pinned commit: +git init openai-math && cd openai-math +git remote add origin https://github.com/openai/math.git +git sparse-checkout set --no-cone /lean/ComparatorChallenges/ /lean/docs/ /overview.tex /LICENSE +git fetch --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a && git checkout FETCH_HEAD +cd .. + +# Optional: the import graph, for reference-proof sizes and the oracle's file lists. Needs the full +# lean/ directory (about 1.8 GB checked out). +python -m openai_math_harbor.import_graph openai-math/lean graph.json + +python -m openai_math_harbor.adapter --openai-math openai-math --graph graph.json --out out/ +# Stamp oracle verdicts into the tasks after an oracle run: +python -m openai_math_harbor.report oracle_results.json +python -m openai_math_harbor.adapter ... --oracle-results oracle_results.json +``` + +Every challenge goes through the same code; no task is written by hand. Three things are decided +per challenge, all from the data: + +| What | Count | Handling | +|---|---|---| +| Definition holes | 9 configs | Comparator checks only the name and type of a `definition_names` entry, never its body, so a solution could redefine `ProperColoring := False` and prove the theorem trivially. A hole whose body is written out is removed from the config, so it must match exactly (8 configs). A hole whose body is `sorry` stays open only if its name appears nowhere else in the file (`ElementaryPositivity`, whose type is the claim). `DefocusingNLS` has a `sorry` inside a definition the theorems use and is excluded. | +| Reference proofs needing other Lean libraries | 23 | PrimeNumberTheoremAnd, StrongPNT, RellichKondrachov and others. Every statement imports only Mathlib, so agents are unaffected; only those official proofs cannot be built in this image. | +| Grading time | all | 1 h plus 15 min per MB of the reference proof, at most 6 h. | + +The 137 result families without Lean statements have no machine-checkable target and are not part +of the dataset. + +## How a trial runs + +``` +agent sandbox (snapshot) verifier sandbox (same snapshot, fresh) + /workspace Lake project, Mathlib never runs agent code + agent writes Submission.lean /tests: Challenge.lean, task.json, grade.py + (+ Submission/**.lean) /logs/artifacts/submission.tar <- only input + no network while the agent runs 1. accept regular Submission*.lean files only + | 2. fresh Lake project, prebuilt read-only Mathlib + collect hook: pack_submission.py 3. iptables: grader uid gets no sockets + -> /logs/artifacts/submission.tar ----------> 4. Comparator as `grader`: landrun builds, statement + (one plain file crosses) + axiom check, kernel replay + 5. kill grader processes, root writes reward.txt +``` + +Harbor's `[verifier] environment_mode = "separate"` (0.24+) provides the second sandbox. Both +sandboxes start from one Daytona snapshot built from `image/Dockerfile`; every task carries the +identical `environment/`, so the image is built once. Harbor's own Daytona auto-snapshot gives up +after 10 minutes, which is less than the image build takes, hence `snapshot.py`. + +## Threat model + +| Attempt | What stops it | Test | +|---|---|---| +| `sorry`, `admit`, a tactic macro that expands to `sorry` | `sorryAx` is not a permitted axiom | `sorry`, `sorry-macro` | +| Declare `axiom cheat : False` | only `propext`, `Quot.sound`, `Classical.choice` allowed | `axiom` | +| `implemented_by` + `native_decide` to prove `False` | `native_decide` introduces an axiom of its own | `native-decide-false` | +| Same theorem name, weaker statement | the statement must equal the challenge's exactly | `weaken-statement` | +| Redefine a definition the statement uses | every constant in the statement must match; openai/math's loose hole configs are tightened | `redefine-definition` | +| Keep a structure's name and type but drop a proof obligation from its fields | Comparator also compares the structure's constructor, whose type lists the fields | `tamper-structure` | +| Re-export the trusted Challenge module | its theorems are `sorry` | `import-challenge` | +| Plant `reward.txt` or a fake `comparator` in the agent sandbox | grading runs in a separate fresh sandbox | `agent-side-reward` | +| Lean code run while the verifier builds the proof (`run_cmd`, `#eval`, macros) writes `reward.txt`, runs a shell or opens a connection | landrun (read-only file system except `.lake`, execution limited to Lean and git, TCP denied), unprivileged `grader` user, iptables owner rule; root writes the reward only after killing every grader process | `compile-time-reward` | +| Symlinks, path traversal, device files, hard links, huge archives | the collect hook packs only regular files; `grade.py` accepts only regular `Submission.lean` and `Submission/**.lean` whose path components are Lean identifiers | `symlink`, `tests/test_grade_unpack.py` | +| Read OpenAI's proof | not in the image; the agent phase has no network | network probe (below) | +| A background process in the agent sandbox interfering with grading | Harbor stops the agent sandbox before the verifier starts and empties the verifier's log directory first; on Daytona the two sandboxes share no files | by construction | +| A Lean kernel soundness bug | not covered (Comparator's second kernel, nanoda, is off) | none | +| Memorized public proofs | not covered | none | + +Grading fails closed: a rejected or non-compiling submission scores 0. If the trusted side breaks +(the Challenge fails to build, or times out before the submission is reached, or the network block +cannot be installed), no reward is written and Harbor reports the trial as an error rather than 0. + +**What each isolation layer was shown to do** on Daytona's kernel (Linux 6.17): under landrun, the +grader's build cannot write outside the build directory and gets `EACCES` on TCP connects. Without +landrun, the grader user *can* reach Daytona's in-sandbox control service on port 2280, so +`grade.py` also installs an iptables rule for that user before Comparator runs and refuses to grade +if the rule does not take effect. + +**Trusted, not re-checked here:** the Lean kernel, Comparator's export parser and `lean4export` (a +crafted `.olean` written at build time is only accepted if the kernel replay accepts it), landrun, +and Daytona's sandbox boundary. + +## Checks behind the validation + +All through `harbor run` on Daytona with the separate verifier; none involves a language model. + +| Check | Expected | Result | +|---|---|---| +| Oracle over every task (official proofs) | 1 where the proof fits the image | see the dataset card and each task's `oracle_result` | +| All 405 statements built in one sandbox (`lake build`, 3 threads) | compile | 405 of 405; median 5 s, 90th percentile 7 s, slowest 220 s | +| No-op agent | 0 | 0, "no submission" | +| 11 adversarial submissions (`attacks.py`) | 0 | 0 on all eleven, each rejected for the intended reason; the build-time probe printed `write denied`, and neither a shell nor git's HTTP helper could be executed | +| Agent-phase view (oracle agent printing its environment) | no network | DNS fails, HTTPS to github.com times out, a direct-IP connection is refused; `LEAN_NUM_THREADS=3` is set; `/tests` is absent | +| Oracle with `--allow-agent-host github.com` | 1 | 1 (positive control for the network check) | +| landrun and iptables in a Daytona sandbox | both enforce | as described above | + +## The image + +`image/lean_setup.sh` installs Lean v4.34.1 and Mathlib at the commits openai/math pins, builds +Comparator (`leanprover/comparator@d03acab`) and lean4export with the same toolchain, builds landrun, +copies every challenge statement to `/opt/openai-math/challenges/`, and prepares `/workspace`. Three +details matter: + +- **Size.** Lean plus Mathlib is about 11 GB as installed, more than a 10 GB Daytona sandbox. The + script drops what importing Mathlib never reads: static libraries, LLVM and gcc (needed only to link + the executables built earlier in the script), and Mathlib's generated C and `.ilean` files, + truncated with their `.hash` files kept so Lake still treats Mathlib as built. A smoke test fails + the build if a second `lake build` still compiles any dependency. +- **Threads.** Lean sees every host CPU (64 on Daytona), not the sandbox's 4, so by default Lake + starts one Mathlib-loaded `lean` per module and runs out of memory. Agents get + `LEAN_NUM_THREADS=3` (`task.toml`); the verifier uses 2, which reaches Comparator's landrun + sandbox through a one-line `sed` patch to Comparator's `envPass` lists. +- **Permissions.** Mathlib's cache tool unpacks files as mode 0600. The script makes the toolchain + and packages world-readable (still root-owned), and a second smoke test builds as the `grader` user. + +## Limits + +- **Daytona's per-sandbox caps: 4 CPUs, 8 GB memory, 10 GB disk.** The 10 GB is working space on + top of the image. Compiled output of a large proof can exceed it: reference proofs up to about + 1.8 MB of Lean source grade fine, while 3.5 MB and 4.8 MB ones ran out of disk. The oracle results + record which tasks are affected. Higher per-sandbox limits remove the constraint. +- **The agent sandbox contains Comparator,** since agent and verifier share one image. Nothing in it + is secret: the statement and the rules are public, and `lake build` plus `#print axioms` already + tell an agent whether a proof is complete. +- **Difficulty.** These are open research problems; expect a reward of 0 on almost every task. + +## Licensing + +The statements are redistributed unchanged from openai/math (OpenAI, Apache-2.0); the dataset root +carries `LICENSE-openai-math` and a `NOTICE` describing what was copied, what was adapted (the +Comparator configs) and what is not included (the proofs). The image bundles Lean, Mathlib, +Comparator and lean4export (Apache-2.0) and landrun (MIT). This code is under the Apache License 2.0. diff --git a/generator/image/Dockerfile b/generator/image/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/generator/image/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/generator/image/fetch_mathlib.sh b/generator/image/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/generator/image/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/generator/image/lake-manifest.json b/generator/image/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/generator/image/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/generator/image/lakefile.lean b/generator/image/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/generator/image/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/generator/image/lean_setup.sh b/generator/image/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/generator/image/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/generator/image/pack_submission.py b/generator/image/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/generator/image/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/generator/openai_math_harbor/__init__.py b/generator/openai_math_harbor/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..3e78f438f48b13342fa6b6c0447d7783c9804930 --- /dev/null +++ b/generator/openai_math_harbor/__init__.py @@ -0,0 +1 @@ +"""Harbor adapter for the openai/math Lean challenges.""" diff --git a/generator/openai_math_harbor/adapter.py b/generator/openai_math_harbor/adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..b05639386100925930dabce82df20af7d7f497f9 --- /dev/null +++ b/generator/openai_math_harbor/adapter.py @@ -0,0 +1,358 @@ +"""Generate Harbor tasks from openai/math's Comparator challenges. + +One script covers every challenge: the statement, theorem names, axioms and definition holes all +come from the challenge's own files, so no task is written by hand. What varies per task is data +(see challenges.py for the hole policy that rewrites 8 configs and excludes 1). + + python -m openai_math_harbor.adapter \\ + --openai-math /path/to/openai-math # checkout with lean/ComparatorChallenges, lean/docs, overview.tex + --graph graph.json # import graph from import_graph.py (oracle closures) + --out datasets/openai-math + [--only TruffetCounterexample,PlaneColoring] + [--embed-reference] # bundle the reference proof into solution/ (needs lean/OAI) + +Output layout (the FineEnvs Harbor dataset convention): + + /registry.json Harbor registry: openai-math-harbor@ -> tasks/* + /README.md dataset card + /NOTICE, LICENSE-openai-math attribution for the redistributed statements + /manifest.json per-task metadata and the excluded challenges + /tasks// one Harbor task per challenge + +Every task gets the same environment/ directory, so Daytona builds one snapshot for all of them. +""" + +from __future__ import annotations + +import argparse +import json +import re +import shutil +from pathlib import Path +from string import Template + +from .challenges import Challenge, load_challenges +from .oracle import bundle, closure, external_packages + +PKG = Path(__file__).parent +IMAGE_DIR = PKG.parent / "image" +TEMPLATES = PKG / "templates" +SOURCE_COMMIT = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +DATASET_NAME = "openai-math-harbor" +DATASET_VERSION = "1.0" +IMAGE_FILES = ["Dockerfile", "lean_setup.sh", "fetch_mathlib.sh", "lakefile.lean", "lake-manifest.json", "pack_submission.py"] + + +def slug(name: str) -> str: + return re.sub(r"(?<=[a-z0-9])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])", "-", name).lower() + + +def toml_str(value: str) -> str: + return json.dumps(value, ensure_ascii=False) + + +def toml_list(values: list[str]) -> str: + return "[" + ", ".join(toml_str(v) for v in values) + "]" + + +def grade_timeout(reference_bytes: int) -> int: + """Seconds the verifier gets to build, export and kernel-replay a submission. + + Most proofs grade in 5 to 30 minutes, but a short file can still be slow (a few heavy + `nlinarith` calls took over 45 minutes in one 246-line module), so the floor is generous. + The limit only costs time when a proof actually needs it. + """ + return int(min(6 * 3600, 3 * 3600 + 900 * reference_bytes / 1e6)) + + +def targets_sentence(c: Challenge) -> str: + names = [f"`{n}`" for n in c.theorem_names] + if not names: + return "The definition below" + return ("The theorem " if len(names) == 1 else "The theorems ") + ", ".join(names) + + +def holes_sentence(c: Challenge) -> str: + if not c.definition_holes: + return "" + names = ", ".join(f"`{n}`" for n in c.definition_holes) + return (f", and the body of {names}, which you must supply: its type states the claim, so any " + "value of that type proves it") + + +def instruction(c: Challenge) -> str: + fam = c.family + return Template((TEMPLATES / "instruction.md").read_text()).substitute( + title=f"openai/math challenge `{c.name}` (family {fam.number})", + family_number=fam.number, family_title=fam.title, subject=fam.subject, + family_summary=fam.summary, challenge=c.name, lean=c.lean.rstrip(), + targets=targets_sentence(c), holes=holes_sentence(c), + ) + + +def task_toml(c: Challenge, ref: dict, agent_timeout: int, oracle: dict | None = None) -> str: + fam = c.family + verifier_timeout = ref["grade_timeout_sec"] + 900 + oracle_lines = "" + if oracle: + oracle_lines = f'oracle_result = {toml_str(oracle["cause"])}\n' + if oracle.get("grade_seconds") is not None: + oracle_lines += f'oracle_grade_seconds = {oracle["grade_seconds"]}\n' + return f"""schema_version = "1.4" + +[task] +name = "openai-math/{slug(c.name)}" +version = "1.0.0" +description = {toml_str(f"Prove {c.name} (openai/math family {fam.number}: {fam.title}) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox.")} +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", {toml_str(fam.subject.lower().replace(" ", "-"))}] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "{SOURCE_COMMIT}" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/{c.name}.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = {toml_str(c.name)} +family = {toml_str(fam.number)} +family_title = {toml_str(fam.title)} +subject = {toml_str(fam.subject)} +theorems = {toml_list(c.theorem_names)} +definition_holes = {toml_list(c.definition_holes)} +fixed_definitions = {toml_list(c.dropped_holes)} +reference_module = {toml_str(c.config["solution_module"])} +reference_modules = {ref["n_modules"]} +reference_lean_bytes = {ref["bytes"]} +reference_requires_packages = {toml_list(ref["packages"])} +{oracle_lines}difficulty = "research" + +[agent] +timeout_sec = {agent_timeout} +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = {{ LEAN_NUM_THREADS = "3" }} + +[verifier] +timeout_sec = {verifier_timeout} +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 +""" + + +def write_task(c: Challenge, out: Path, graph: dict | None, lean_dir: Path | None, + embed_reference: bool, agent_timeout: int, oracle: dict | None = None) -> dict: + task_dir = out / "tasks" / slug(c.name) + if task_dir.exists(): + shutil.rmtree(task_dir) + (task_dir / "environment").mkdir(parents=True) + (task_dir / "tests").mkdir() + (task_dir / "solution").mkdir() + + for name in IMAGE_FILES: + shutil.copy(IMAGE_DIR / name, task_dir / "environment" / name) + + solution_module = c.config["solution_module"] + modules = closure(graph, solution_module) if graph else [] + ref = { + "n_modules": len(modules), + "bytes": sum(graph[m]["bytes"] for m in modules) if graph else 0, + "packages": external_packages(graph, modules) if graph else [], + } + ref["grade_timeout_sec"] = grade_timeout(ref["bytes"]) + + (task_dir / "instruction.md").write_text(instruction(c)) + (task_dir / "task.toml").write_text(task_toml(c, ref, agent_timeout, oracle)) + + (task_dir / "tests" / "Challenge.lean").write_text(c.lean) + (task_dir / "tests" / "task.json").write_text(json.dumps({ + "challenge": c.name, + "comparator": c.comparator, + "grade_timeout_sec": ref["grade_timeout_sec"], + }, indent=2)) + for name in ("test.sh", "grade.py"): + shutil.copy(TEMPLATES / "tests" / name, task_dir / "tests" / name) + (task_dir / "tests" / "test.sh").chmod(0o755) + + (task_dir / "solution" / "closure.txt").write_text("\n".join(modules) + "\n") + shutil.copy(PKG / "reference.py", task_dir / "solution" / "reference.py") + solve = Template((TEMPLATES / "solution" / "solve.sh").read_text()).substitute( + challenge=c.name, solution_module=solution_module, n_modules=len(modules), + source_commit=SOURCE_COMMIT, + ) + (task_dir / "solution" / "solve.sh").write_text(solve) + (task_dir / "solution" / "solve.sh").chmod(0o755) + if embed_reference: + if not (lean_dir and (lean_dir / "OAI").is_dir()): + raise SystemExit("--embed-reference needs the openai/math checkout's lean/OAI directory") + (task_dir / "solution" / "reference.tar.gz").write_bytes(bundle(lean_dir, modules, solution_module)) + return { + "task": slug(c.name), "challenge": c.name, "family": c.family.number, + "family_title": c.family.title, "subject": c.family.subject, + "theorems": c.theorem_names, "definition_holes": c.definition_holes, + "fixed_definitions": c.dropped_holes, **ref, + "oracle_result": (oracle or {}).get("cause"), + "oracle_grade_seconds": (oracle or {}).get("grade_seconds"), + } + + +ORACLE_MEANING = { + "accepted": "OpenAI's proof is accepted: the environment is verified end to end", + "missing-package": "OpenAI's proof uses a Lean library beyond Mathlib that the sandbox does not include", + "definition-mismatch": "OpenAI's proof writes a definition with the same text but it compiles differently, so the exact-match check fails", + "memory": "OpenAI's proof needs more than the sandbox's 8 GB of memory to build", + "disk": "OpenAI's proof is too large for the sandbox's 10 GB disk", + "timeout": "grading OpenAI's proof exceeded the time limit", + "rejected": "Comparator rejected OpenAI's proof", +} + + +def validation_block(written: list[dict]) -> str: + """Markdown summary of the oracle run for the dataset card.""" + results = [w for w in written if w.get("oracle_result")] + if not results: + return "The oracle has not been run on this build of the dataset." + counts: dict[str, list[str]] = {} + for w in results: + counts.setdefault(w["oracle_result"], []).append(w["task"]) + order = [k for k in ORACLE_MEANING if k in counts] + sorted(k for k in counts if k not in ORACLE_MEANING) + rows = ["| Oracle result | Tasks | Meaning |", "|---|---|---|"] + for key in order: + rows.append(f"| {key} | {len(counts[key])} | {ORACLE_MEANING.get(key, 'grading did not complete')} |") + pending = [w["task"] for w in written if not w.get("oracle_result")] + if pending: + rows.append(f"| not completed | {len(pending)} | grading did not complete in our run |") + lines = ["\n".join(rows), ""] + secs = sorted(w["oracle_grade_seconds"] for w in results + if w["oracle_result"] == "accepted" and w.get("oracle_grade_seconds")) + if secs: + lines.append(f"Grading an accepted proof took {secs[len(secs) // 2] // 60} minutes at the median. " + "Each task's result is in its `task.toml` (`oracle_result`) and in `manifest.parquet`.") + unexplained = sorted(t for k in counts if k not in ORACLE_MEANING or k in ("rejected", "timeout") for t in counts[k]) + if unexplained: + lines.append("Other: " + ", ".join(f"`{t}`" for t in unexplained) + ".") + return "\n".join(lines) + + +def write_parquet_manifest(out: Path, written: list[dict]) -> None: + """manifest.parquet: one row per task, for filtering without walking tasks/.""" + try: + import pyarrow as pa + import pyarrow.parquet as pq + except ModuleNotFoundError: + print("pyarrow not installed; skipping manifest.parquet") + return + columns = ["task", "challenge", "family", "family_title", "subject", "theorems", "definition_holes", + "fixed_definitions", "n_modules", "bytes", "packages", "grade_timeout_sec", + "oracle_result", "oracle_grade_seconds"] + rename = {"n_modules": "reference_modules", "bytes": "reference_lean_bytes", + "packages": "reference_requires_packages"} + table = pa.table({rename.get(c, c): [w.get(c) for w in written] for c in columns}) + pq.write_table(table, out / "manifest.parquet") + + +def not_validated_block(not_validated: list[dict], excluded: list[dict]) -> str: + """Markdown list of the statements that are not in the dataset, with the reason for each.""" + rows = [*({"task": n["task"], "reason": ORACLE_MEANING.get(n["reason"], "grading did not complete in our run")} for n in not_validated), + *({"task": slug(e["challenge"]), "reason": "left out by design: " + e["reason"]} for e in excluded)] + if not rows: + return "None: every statement is included." + lines = ["
" + f"{len(rows)} statements not included (click to expand)" + "", "", + "| Statement | Why it could not be validated |", "|---|---|"] + lines += [f"| `{r['task']}` | {r['reason']} |" for r in sorted(rows, key=lambda r: r["task"])] + lines += ["", "
"] + return "\n".join(lines) + + +def write_dataset_files(out: Path, included: list[Challenge], written: list[dict], + not_validated: list[dict] | None = None, excluded: list[dict] | None = None, + n_statements: int | None = None) -> None: + """registry.json, the dataset card, NOTICE and the openai/math license copy.""" + registry = [{ + "name": DATASET_NAME, + "version": DATASET_VERSION, + "description": f"{len(written)} Lean 4 theorem-proving tasks from openai/math, graded by Comparator in a separate sandbox.", + "tasks": [{"name": w["task"], "path": f"tasks/{w['task']}"} for w in written], + }] + (out / "registry.json").write_text(json.dumps(registry, indent=2) + "\n") + families = {c.family.number for c in included} + subjects = sorted({c.family.subject for c in included}) + counts = {s: sum(1 for c in included if c.family.subject == s) for s in subjects} + card = Template((TEMPLATES / "dataset_README.md").read_text()).substitute( + validation=validation_block(written + [{"task": n["task"], "oracle_result": n["reason"]} + for n in (not_validated or []) if n["reason"] != "pending"] + + [{"task": n["task"]} for n in (not_validated or []) if n["reason"] == "pending"]), + not_validated=not_validated_block(not_validated or [], excluded or []), + n_statements=n_statements or len(written), + n_not_included=(n_statements or len(written)) - len(written), + n_tasks=len(written), n_families=len(families), n_subjects=len(subjects), + source_commit=SOURCE_COMMIT[:7], + subjects_line=", ".join(f"{s} ({counts[s]})" for s in sorted(subjects, key=lambda s: -counts[s])), + ) + (out / "README.md").write_text(card) + write_parquet_manifest(out, written) + (out / "NOTICE").write_text(Template((TEMPLATES / "NOTICE").read_text()).substitute(source_commit=SOURCE_COMMIT)) + shutil.copy(TEMPLATES / "LICENSE-openai-math", out / "LICENSE-openai-math") + shutil.copy(TEMPLATES / "LICENSE", out / "LICENSE") + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) + ap.add_argument("--openai-math", type=Path, required=True) + ap.add_argument("--graph", type=Path) + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--only", help="comma-separated challenge names") + ap.add_argument("--embed-reference", action="store_true") + ap.add_argument("--agent-timeout", type=int, default=4 * 3600) + ap.add_argument("--oracle-results", type=Path, + help="oracle verdicts from `python -m openai_math_harbor.report`, stamped into each task") + ap.add_argument("--only-validated", action="store_true", + help="keep only tasks whose official proof the oracle verified; list the rest in the card") + args = ap.parse_args() + + graph = json.loads(args.graph.read_text())["modules"] if args.graph else None + oracle = json.loads(args.oracle_results.read_text()) if args.oracle_results else {} + challenges = load_challenges(args.openai_math) + if args.only: + wanted = set(args.only.split(",")) + challenges = [c for c in challenges if c.name in wanted] + missing = wanted - {c.name for c in challenges} + if missing: + raise SystemExit(f"unknown challenges: {sorted(missing)}") + + args.out.mkdir(parents=True, exist_ok=True) + written, excluded, not_validated = [], [], [] + for c in challenges: + if c.excluded: + excluded.append({"challenge": c.name, "reason": c.excluded}) + continue + entry = write_task(c, args.out, graph, args.openai_math / "lean", args.embed_reference, + args.agent_timeout, oracle.get(slug(c.name))) + if args.only_validated and entry["oracle_result"] != "accepted": + shutil.rmtree(args.out / "tasks" / entry["task"]) + not_validated.append({"task": entry["task"], "challenge": c.name, "family": c.family.number, + "reason": entry["oracle_result"] or "pending"}) + continue + written.append(entry) + (args.out / "manifest.json").write_text(json.dumps({ + "source": "https://github.com/openai/math", "source_commit": SOURCE_COMMIT, + "tasks": written, "excluded": excluded, "not_validated": not_validated, + }, indent=2)) + kept = {w["task"] for w in written} + write_dataset_files(args.out, [c for c in challenges if slug(c.name) in kept], written, + not_validated=not_validated, excluded=excluded, n_statements=len(challenges)) + print(f"wrote {len(written)} tasks to {args.out / 'tasks'}; excluded {len(excluded)}") + for e in excluded: + print(f" excluded {e['challenge']}: {e['reason']}") + + +if __name__ == "__main__": + main() diff --git a/generator/openai_math_harbor/attacks.py b/generator/openai_math_harbor/attacks.py new file mode 100644 index 0000000000000000000000000000000000000000..74c8d301cf10a4731a078b324b5bda95d64288db --- /dev/null +++ b/generator/openai_math_harbor/attacks.py @@ -0,0 +1,207 @@ +"""Reward-hacking probes: copies of a generated task whose oracle submits a cheat. + +Each probe keeps the task's environment, tests and config unchanged and replaces solution/solve.sh +with a script that writes an invalid submission (or tampers with the agent sandbox). Run them with +Harbor's oracle agent; every probe must score 0. + + python -m openai_math_harbor.attacks --dataset datasets/openai-math-harbor/tasks --out datasets/attacks +""" + +from __future__ import annotations + +import argparse +import json +import re +import shutil +from pathlib import Path + + +def _challenge(task_dir: Path) -> str: + return (task_dir / "tests" / "Challenge.lean").read_text() + + +def _replace_sorry(lean: str, term: str, tactic: str | None = None) -> str: + """Replace each `sorry`: tactic-mode ones with ``tactic`` (default `exact term`), others with ``term``.""" + lean = re.sub(r"\bby(\s+)sorry\b", lambda m: f"by{m.group(1)}{tactic or f'exact ({term})'}", lean) + return re.sub(r"\bsorry\b", f"({term})", lean) + + +def _first_theorem(task_dir: Path) -> str: + return json.loads((task_dir / "tests" / "task.json").read_text())["comparator"]["theorem_names"][0] + + +def _write(path: str, content: str) -> str: + return f"mkdir -p \"$(dirname {path})\"\ncat > {path} <<'LEAN_EOF'\n{content}\nLEAN_EOF\n" + + +# Each attack: (name, description, function(task_dir) -> bash body run in the agent sandbox). +def attack_sorry(t: Path) -> str: + return _write("/workspace/Submission.lean", _challenge(t)) + + +def attack_axiom(t: Path) -> str: + lean = _challenge(t).replace("import Mathlib\n", "import Mathlib\n\naxiom openai_math_cheat : False\n", 1) + return _write("/workspace/Submission.lean", _replace_sorry(lean, "openai_math_cheat.elim")) + + +def attack_sorry_macro(t: Path) -> str: + lean = _replace_sorry(_challenge(t), "by trust_me", tactic="trust_me") + lean = lean.replace( + "import Mathlib\n", "import Mathlib\n\nmacro \"trust_me\" : tactic => `(tactic| sorry)\n", 1) + return _write("/workspace/Submission.lean", lean) + + +def attack_native_decide_false(t: Path) -> str: + # implemented_by makes compiled code disagree with the kernel, so native_decide proves False. + # The file elaborates with no errors and no sorry warning; only the axiom check catches it. + prelude = """ +def openaiMathTrue : Bool := true +@[implemented_by openaiMathTrue] def openaiMathFake : Bool := false +theorem openaiMathFake_eq : openaiMathFake = true := by native_decide +theorem openaiMathBoom : False := by + have h := openaiMathFake_eq + simp [openaiMathFake] at h +""" + lean = _challenge(t).replace("import Mathlib\n", "import Mathlib\n" + prelude, 1) + return _write("/workspace/Submission.lean", _replace_sorry(lean, "openaiMathBoom.elim")) + + +def attack_weaken_statement(t: Path) -> str: + # Keep the theorem's name, change its statement to `True`. + name = _first_theorem(t).split(".")[-1] + lean = _challenge(t) + lean = re.sub(r"(?ms)^(\s*theorem\s+" + re.escape(name) + r"\b).*?:=\s*by\s*\n\s*sorry", + r"\1 : True := by\n trivial", lean, count=1) + lean = re.sub(r"(?ms)^(\s*theorem\s+" + re.escape(name) + r"\b).*?:=\s*by\s+sorry", + r"\1 : True := by trivial", lean, count=1) + return _write("/workspace/Submission.lean", lean) + + +def attack_import_challenge(t: Path) -> str: + # The verifier's project also contains the trusted Challenge module; re-export its sorry'd theorem. + return _write("/workspace/Submission.lean", "import Challenge\n") + + +def attack_compile_time_reward(t: Path) -> str: + # Lean code that runs while the verifier builds the submission tries to plant a reward, to run a + # shell, and to open a TCP connection to the sandbox's control daemon (via git, one of the few + # binaries Comparator lets the build execute). All must fail: landrun (read-only file system + # except .lake, exec limited, TCP denied), the unprivileged grader user, and iptables. + probe = """ +def openaiMathProbeWrite : IO String := do + try + IO.FS.writeFile "/logs/verifier/reward.txt" "1\\n" + pure "WROTE reward.txt" + catch e => pure s!"write denied ({e})" + +def openaiMathProbeRun (cmd : String) (args : Array String) : IO String := do + try + let out ← IO.Process.output { cmd := cmd, args := args } + pure s!"exit {out.exitCode}: {out.stdout.trim} {out.stderr.trim}" + catch e => pure s!"spawn denied ({e})" + +#eval show IO Unit from do + IO.println s!"PROBE write: {← openaiMathProbeWrite}" + IO.println s!"PROBE bash: {← openaiMathProbeRun "bash" #["-c", "id"]}" + IO.println s!"PROBE tcp: {← openaiMathProbeRun "git" #["ls-remote", "http://127.0.0.1:2280/probe"]}" +""" + lean = _challenge(t).replace("import Mathlib\n", "import Mathlib\n" + probe, 1) + return _write("/workspace/Submission.lean", lean) + + +def attack_agent_side_reward(t: Path) -> str: + # Plant rewards and fake comparator output in the agent sandbox; the verifier runs elsewhere. + return ( + "mkdir -p /logs/verifier /logs/artifacts\n" + "echo 1 > /logs/verifier/reward.txt\n" + "echo '{\"reward\": 1}' > /logs/verifier/reward.json\n" + "printf '#!/bin/sh\\necho Your solution is okay!\\n' > /usr/local/bin/comparator\n" + + _write("/workspace/Submission.lean", _challenge(t)) + ) + + +def attack_symlink(t: Path) -> str: + # Submission.lean is a symlink to the challenge; Submission/ links to /. The packer skips links. + return ( + "ln -sf /opt/openai-math/challenges/$(python3 -c \"import json;print(json.load(open('/tests/task.json'))['challenge'])\" 2>/dev/null || echo X).lean /workspace/Submission.lean 2>/dev/null || ln -sf /etc/hostname /workspace/Submission.lean\n" + "ln -sfn / /workspace/Submission\n" + ) + + +def attack_redefine_definition(t: Path) -> str: + # EuclideanFiveColor: openai/math lists ProperColoring as a definition hole, so Comparator with the + # original config only checks its type. Redefining it as False makes the theorem trivial. + lean = _challenge(t) + lean, n = re.subn( + r"(def ProperColoring \(colorCount : ℕ\) \(coloring : ℂ → Fin colorCount\) : Prop :=)\n.*\n", + r"\1\n False\n", lean, count=1) + if n != 1: + raise SystemExit("redefine-definition targets EuclideanFiveColor's ProperColoring") + lean = _replace_sorry(lean, "fun ⟨_, h⟩ => h") + return _write("/workspace/Submission.lean", lean) + + +def attack_tamper_structure(t: Path) -> str: + # ElementaryPositivity: the open hole's type is the structure PermutationWitness, whose + # `expansion` field carries the claim. Keep the structure's name, parameters and type, but + # replace its fields with trivial ones, then fill the hole trivially. Comparator compares the + # structure's constructor too, so this must be rejected. + lean = _challenge(t) + lean, n = re.subn( + r"structure PermutationWitness where\n.*?(?=\n\nend NaturalUnitIntervalGraph)", + "structure PermutationWitness where\n" + " theta : {σ : Equiv.Perm (Fin n) // G.Nondescent σ} → Unit\n" + " expansion : True", + lean, count=1, flags=re.S) + if n != 1: + raise SystemExit("tamper-structure targets ElementaryPositivity's PermutationWitness") + lean = _replace_sorry(lean, "⟨fun _ => (), trivial⟩") + return _write("/workspace/Submission.lean", lean) + + +ATTACKS = { + "tamper-structure": (attack_tamper_structure, "keep a structure's name and type, drop the proof obligation from its fields"), + "redefine-definition": (attack_redefine_definition, "redefine a definition the statement uses (ProperColoring := False)"), + "sorry": (attack_sorry, "submit the challenge unchanged (every proof is sorry)"), + "axiom": (attack_axiom, "declare `axiom cheat : False` and use it"), + "sorry-macro": (attack_sorry_macro, "hide sorry behind a custom tactic macro"), + "native-decide-false": (attack_native_decide_false, "prove False via implemented_by + native_decide"), + "weaken-statement": (attack_weaken_statement, "same theorem name, statement changed to True"), + "import-challenge": (attack_import_challenge, "import the trusted Challenge module and re-export it"), + "compile-time-reward": (attack_compile_time_reward, "Lean code run at build time plants reward.txt and dials the daemon"), + "agent-side-reward": (attack_agent_side_reward, "plant reward files and a fake comparator in the agent sandbox"), + "symlink": (attack_symlink, "submit symlinks instead of files"), +} + + +def make_probe(task_dir: Path, out_dir: Path, name: str) -> Path: + fn, desc = ATTACKS[name] + dest = out_dir / f"{task_dir.name}--{name}" + if dest.exists(): + shutil.rmtree(dest) + shutil.copytree(task_dir, dest) + toml = (dest / "task.toml").read_text() + toml = re.sub(r'(?m)^name = "openai-math/(.*)"$', rf'name = "openai-math-attacks/\1--{name}"', toml, count=1) + (dest / "task.toml").write_text(toml) + for extra in ("reference.tar.gz",): + (dest / "solution" / extra).unlink(missing_ok=True) + solve = dest / "solution" / "solve.sh" + solve.write_text(f"#!/usr/bin/env bash\n# Attack probe: {desc}. Must score 0.\nset -u\n{fn(task_dir)}\necho 'attack {name} placed'\n") + solve.chmod(0o755) + return dest + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--dataset", type=Path, required=True) + ap.add_argument("--out", type=Path, required=True) + ap.add_argument("--task", default="truffet-counterexample") + ap.add_argument("--attacks", default=",".join(ATTACKS)) + args = ap.parse_args() + args.out.mkdir(parents=True, exist_ok=True) + for name in args.attacks.split(","): + print(make_probe(args.dataset / args.task, args.out, name)) + + +if __name__ == "__main__": + main() diff --git a/generator/openai_math_harbor/challenges.py b/generator/openai_math_harbor/challenges.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbd5fad5ec47419c4691743af17d217acde6721 --- /dev/null +++ b/generator/openai_math_harbor/challenges.py @@ -0,0 +1,178 @@ +"""Read openai/math's Comparator challenges and decide how each one is graded. + +Each challenge is ``lean/ComparatorChallenges/.lean`` (the statement, with ``sorry``) plus +``.json`` (Comparator's config). Two things are added here: + +* the family it belongs to (number, title, subject), from ``lean/docs/NNN.md`` and ``overview.tex``; +* a hole policy. Comparator checks only the name and type of a ``definition_names`` entry, never + its body (comparator ``Compare.lean``: ``definitionHoleMatches``). openai/math lists fixed + definitions as holes in 9 configs, so a solver could redefine e.g. ``ProperColoring := False`` and + prove the theorem trivially. Holes are therefore rewritten: + + - a definition with a complete body is removed from ``definition_names``, so Comparator requires + the solution's definition to be identical; + - a definition whose whole body is ``sorry`` and whose name appears nowhere else in the file stays + a hole: its type is the claim (e.g. a witness structure carrying the proof obligations); + - anything else (a ``sorry`` inside a body, or an open definition that statements depend on) cannot + be graded safely as written, and the challenge is excluded until it is restated. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from pathlib import Path + +_DECL_START = re.compile( + r"(?m)^[ \t]*(?:@\[[^\]]*\][ \t]*\n?[ \t]*)?(?:(?:noncomputable|private|protected|partial|unsafe)[ \t]+)*" + r"(?:def|abbrev|theorem|lemma|instance|structure|class|inductive|opaque|axiom|example)\b" +) +_BLOCK_END = re.compile( + r"(?m)^[ \t]*(?:end\b|namespace\b|section\b|run_cmd\b|open\b|variable\b|set_option\b|/--|#)" +) + + +@dataclass +class Family: + number: str + title: str + subject: str + summary: str + + +@dataclass +class Challenge: + name: str + lean: str + config: dict + family: Family | None + theorem_names: list[str] + definition_holes: list[str] + dropped_holes: list[str] = field(default_factory=list) + excluded: str | None = None + + @property + def comparator(self) -> dict: + return { + "theorem_names": self.theorem_names, + "definition_names": self.definition_holes, + "permitted_axioms": self.config["permitted_axioms"], + } + + +def _declaration_block(source: str, short_name: str) -> str | None: + """Text of the first ``def``-like declaration named ``short_name``, up to the next one.""" + pattern = re.compile( + r"(?m)^[ \t]*(?:@\[[^\]]*\][ \t]*\n?[ \t]*)?(?:(?:noncomputable|private|protected)[ \t]+)*" + r"(?:def|abbrev|structure|class|inductive|opaque|instance)[ \t]+" + re.escape(short_name) + r"\b" + ) + m = pattern.search(source) + if not m: + return None + rest = source[m.end():] + ends = [x.start() for x in (_DECL_START.search(rest), _BLOCK_END.search(rest)) if x] + return source[m.start(): m.end() + (min(ends) if ends else len(rest))] + + +def _mentions(source: str, short_name: str) -> int: + """Occurrences of ``short_name`` as a whole identifier anywhere in the file (comments included). + + Qualified uses count too (``RowColumn.Foo`` mentions ``Foo``): theorems often refer to a + definition through its namespace, and missing one would keep an unsafe hole open. + """ + return len(re.findall(r"(? tuple[list[str], list[str], str | None]: + """Return (kept holes, dropped holes, exclusion reason) for one challenge.""" + kept, dropped, problems = [], [], [] + for name in config.get("definition_names") or []: + short = name.split(".")[-1] + block = _declaration_block(source, short) + if block is None: + problems.append(f"{name}: definition not found in the challenge") + continue + body = block.split(":=", 1)[1] if ":=" in block else "" + has_sorry = re.search(r"\bsorry\b", block) is not None + if not has_sorry: + dropped.append(name) + elif re.fullmatch(r"\s*(?:by\s+)?sorry\s*", body) and _mentions(source, short) == 1: + # The hole's type is the claim and nothing else in the file refers to it. + kept.append(name) + else: + problems.append(f"{name}: open definition the theorem statements depend on") + return kept, dropped, ("; ".join(problems) or None) + + +def load_families(overview_tex: Path) -> dict[str, Family]: + src = overview_tex.read_text(encoding="utf-8") + + def group(i: int) -> tuple[str, int]: + depth, j = 0, i + while True: + c = src[j] + if c == "\\": + j += 2 + continue + if c == "{": + depth += 1 + elif c == "}": + depth -= 1 + if depth == 0: + return src[i + 1: j], j + 1 + j += 1 + + families, subject = {}, "" + for m in re.finditer(r"\\(cataloguesection|resultentry)\{", src): + if src[max(0, m.start() - 12): m.start()].endswith("newcommand{"): + continue + i = m.end() - 1 + if m.group(1) == "cataloguesection": + subject, _ = group(i) + continue + args = [] + for _ in range(3): + arg, i = group(i) + args.append(arg) + while src[i] in " \n%": + i += 1 + families[args[0]] = Family(args[0], _plain(args[1]), subject, _plain(args[2])) + return families + + +def _plain(tex: str) -> str: + """Light LaTeX cleanup for markdown: keep $math$, drop accents and \\-escapes.""" + tex = re.sub(r"\\[\"'`^~]\{?([A-Za-z])\}?", r"\1", tex) + tex = tex.replace("--", "–").replace("``", '"').replace("''", '"').replace("~", " ") + tex = re.sub(r"\\(?:emph|textit|textbf)\{([^{}]*)\}", r"\1", tex) + return re.sub(r"\s+", " ", tex).strip() + + +def family_links(docs_dir: Path) -> dict[str, str]: + """Challenge name -> family number, from the Comparator tables in lean/docs/NNN.md.""" + links = {} + for doc in sorted(docs_dir.glob("*.md")): + for m in re.finditer(r"\(\.\./ComparatorChallenges/([A-Za-z0-9_]+)\.lean\)", doc.read_text()): + links.setdefault(m.group(1), doc.stem) + return links + + +def load_challenges(openai_math: Path) -> list[Challenge]: + lean = openai_math / "lean" + families = load_families(openai_math / "overview.tex") + links = family_links(lean / "docs") + out = [] + for cfg_path in sorted((lean / "ComparatorChallenges").glob("*.json")): + name = cfg_path.stem + config = json.loads(cfg_path.read_text()) + source = (lean / "ComparatorChallenges" / f"{name}.lean").read_text(encoding="utf-8") + kept, dropped, excluded = hole_policy(source, config) + if not config["theorem_names"] and not kept: + excluded = excluded or "no theorem and no open definition to check" + out.append(Challenge( + name=name, lean=source, config=config, family=families.get(links.get(name, "")), + theorem_names=list(config["theorem_names"]), definition_holes=kept, + dropped_holes=dropped, excluded=excluded, + )) + return out diff --git a/generator/openai_math_harbor/import_graph.py b/generator/openai_math_harbor/import_graph.py new file mode 100644 index 0000000000000000000000000000000000000000..9282fe302f351dfaf5e0f1372a6f5fc5e1041f3e --- /dev/null +++ b/generator/openai_math_harbor/import_graph.py @@ -0,0 +1,54 @@ +"""Build the module import graph of the openai/math Lean library. + +Reads every ``.lean`` file under ``/lean`` (OAI library and ComparatorChallenges) and writes one +JSON object: ``{"modules": {module: {"imports": [...], "bytes": n, "lines": n}}}``. Only the import +header is parsed; Lean requires imports to come before any other command. + + python -m openai_math_harbor.import_graph /path/to/openai-math/lean graph.json +""" + +from __future__ import annotations + +import json +import re +import sys +from pathlib import Path + +# `import X`, plus the module-system forms `public import X`, `meta import X`, `import all X`. +_IMPORT = re.compile(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?([A-Za-z_«][^\s]*)") +_HEADER_ONLY = re.compile(r"^\s*(?:module\b|prelude\b|--|/-|$)") + + +def header_imports(text: str) -> list[str]: + imports, in_comment = [], False + for line in text.splitlines(): + if in_comment: + in_comment = "-/" not in line + continue + if line.lstrip().startswith("/-") and "-/" not in line: + in_comment = True + continue + m = _IMPORT.match(line) + if m: + imports.append(m.group(1).replace("«", "").replace("»", "")) + elif not _HEADER_ONLY.match(line): + break + return imports + + +def build(lean_root: Path) -> dict: + modules = {} + for path in sorted(lean_root.rglob("*.lean")): + rel = path.relative_to(lean_root) + if rel.parts[0] in (".lake", "lakefile.lean") or rel.name == "lakefile.lean": + continue + text = path.read_text(encoding="utf-8", errors="replace") + name = ".".join(rel.with_suffix("").parts) + modules[name] = {"imports": header_imports(text), "bytes": len(text.encode()), "lines": text.count("\n") + 1} + return {"modules": modules} + + +if __name__ == "__main__": + graph = build(Path(sys.argv[1])) + Path(sys.argv[2]).write_text(json.dumps(graph, separators=(",", ":"))) + print(len(graph["modules"]), "modules") diff --git a/generator/openai_math_harbor/oracle.py b/generator/openai_math_harbor/oracle.py new file mode 100644 index 0000000000000000000000000000000000000000..767d5a149d860c220a6000323a165085fd2ef73d --- /dev/null +++ b/generator/openai_math_harbor/oracle.py @@ -0,0 +1,47 @@ +"""Reference-proof closures for the oracle agent. + +A challenge's reference proof is ``solution_module`` plus every ``OAI.*`` module it imports, +transitively (from the import graph built by ``import_graph.py``). The oracle submits exactly those +files under the ``Submission`` root agents use (see ``reference.py``), so the verifier grades the +reference proof the same way it grades an agent. +""" + +from __future__ import annotations + +import io +import tarfile +import tempfile +from pathlib import Path + +from .reference import place + +CORE_ROOTS = {"Init", "Lean", "Std", "Lake", "Mathlib"} + + +def closure(graph: dict, root: str) -> list[str]: + """Every OAI module reachable from ``root`` through imports, sorted.""" + seen, stack = set(), [root] + while stack: + module = stack.pop() + if module in seen or module not in graph: + continue + seen.add(module) + stack.extend(i for i in graph[module]["imports"] if i == "OAI" or i.startswith("OAI.")) + return sorted(seen) + + +def external_packages(graph: dict, modules: list[str]) -> list[str]: + """Import roots outside OAI, Mathlib and the Lean core that the closure needs.""" + roots = {i.split(".")[0] for m in modules for i in graph[m]["imports"] if i not in graph} + return sorted(roots - CORE_ROOTS) + + +def bundle(lean_dir: Path, modules: list[str], solution_module: str) -> bytes: + """A .tar.gz of the placed reference submission (Submission.lean + Submission/OAI/**).""" + with tempfile.TemporaryDirectory() as tmp: + place(lean_dir, modules, solution_module, Path(tmp)) + buf = io.BytesIO() + with tarfile.open(fileobj=buf, mode="w:gz") as tar: + for path in sorted(Path(tmp).rglob("*.lean")): + tar.add(path, arcname=str(path.relative_to(tmp))) + return buf.getvalue() diff --git a/generator/openai_math_harbor/package.py b/generator/openai_math_harbor/package.py new file mode 100644 index 0000000000000000000000000000000000000000..1002fb199328a19f3463be5a0a159d3cab8fd268 --- /dev/null +++ b/generator/openai_math_harbor/package.py @@ -0,0 +1,36 @@ +"""Assemble the folder that is published as the Hugging Face dataset. + +Copies a generated dataset (adapter output) and adds the generator itself under generator/, so the +published repo can rebuild the image and regenerate the tasks on its own. + + python -m openai_math_harbor.package +""" + +from __future__ import annotations + +import shutil +import sys +from pathlib import Path + +GENERATOR_ROOT = Path(__file__).parents[1] +GENERATOR_PARTS = ["README.md", "openai_math_harbor", "image", "tests"] +IGNORE = shutil.ignore_patterns("__pycache__", "*.pyc", ".DS_Store") + + +def stage(dataset: Path, out: Path) -> None: + if out.exists(): + shutil.rmtree(out) + shutil.copytree(dataset, out, ignore=IGNORE) + for part in GENERATOR_PARTS: + src = GENERATOR_ROOT / part + dst = out / "generator" / part + if src.is_dir(): + shutil.copytree(src, dst, ignore=IGNORE) + else: + dst.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(src, dst) + + +if __name__ == "__main__": + stage(Path(sys.argv[1]), Path(sys.argv[2])) + print("staged", sys.argv[2]) diff --git a/generator/openai_math_harbor/reference.py b/generator/openai_math_harbor/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/generator/openai_math_harbor/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/generator/openai_math_harbor/report.py b/generator/openai_math_harbor/report.py new file mode 100644 index 0000000000000000000000000000000000000000..368fd71d2f38e2dbbcb2741b4c537285ea02ce11 --- /dev/null +++ b/generator/openai_math_harbor/report.py @@ -0,0 +1,80 @@ +"""Summarize a Harbor oracle job into one verdict per task. + +The oracle submits openai/math's own proof of each challenge, so its grade says whether the task is +verified end to end: the statement builds, the official proof compiles in the image, and Comparator +accepts it. Every non-accepted result gets a cause, so a reader can tell an environment limit (disk, +memory, a library the image does not ship) from a real disagreement between proof and statement. + + python -m openai_math_harbor.report [ ...] oracle_results.json +""" + +from __future__ import annotations + +import collections +import json +import sys +from pathlib import Path + +# Checked in order against grading.json's reason and the Comparator log. +CAUSES = [ + ("disk", ("no space left on device",)), + # The reference proof states a definition with the same text as the challenge, but compiled in + # its own library's context it elaborates to a different term, so exact matching fails. + ("definition-mismatch", ("Const does not match between challenge and target",)), + ("memory", ("most likely out of memory", "Child exited with 137", "Lean exited with code 137")), + ("missing-package", ("unknown module prefix", "bad import", "unknown package")), + ("timeout", ("timed out",)), +] + + +def classify(trial: Path) -> dict: + result = json.loads((trial / "result.json").read_text()) + grading = trial / "verifier" / "grading.json" + log = trial / "verifier" / "comparator.log" + g = json.loads(grading.read_text()) if grading.exists() else {} + text = (g.get("reason") or "") + "\n" + (log.read_text(errors="replace") if log.exists() else "") + reward = ((result.get("verifier_result") or {}).get("rewards") or {}).get("reward") + if reward == 1: + cause = "accepted" + elif reward is None: + cause = "error: " + str((result.get("exception_info") or {}).get("exception_type") or g.get("reason", "unknown")) + else: + cause = next((name for name, keys in CAUSES if any(k in text for k in keys)), "rejected") + return { + "reward": reward, + "cause": cause, + # Graders since the overlay copy-up fix record `permission_fixes`; earlier verdicts other + # than "accepted" may be artifacts of that bug and are re-graded. + "current_grader": "permission_fixes" in g, + "grade_seconds": round(g["finished_at"] - g["started_at"]) if g.get("finished_at") else None, + "reason": (g.get("reason") or "")[:500], + } + + +def summarize(job_dir: Path) -> dict[str, dict]: + """Task directory name -> verdict. A task attempted twice (a re-run) keeps its latest trial.""" + out, finished = {}, {} + for trial in sorted(p for p in job_dir.iterdir() if p.is_dir() and (p / "result.json").exists()): + result = json.loads((trial / "result.json").read_text()) + if not result.get("finished_at"): + continue + # Trial directory names are truncated; the task path is not. + name = Path(result["task_id"]["path"]).name + if name not in finished or result["finished_at"] > finished[name]: + out[name], finished[name] = classify(trial), result["finished_at"] + return out + + +def merge(*job_dirs: Path) -> dict[str, dict]: + """Verdicts from several jobs; later jobs (re-runs) override earlier ones.""" + merged = {} + for job_dir in job_dirs: + merged.update(summarize(job_dir)) + return merged + + +if __name__ == "__main__": + *jobs, out_path = sys.argv[1:] + results = merge(*(Path(j) for j in jobs)) + Path(out_path).write_text(json.dumps(results, indent=2, ensure_ascii=False)) + print(len(results), "tasks:", dict(collections.Counter(r["cause"] for r in results.values()))) diff --git a/generator/openai_math_harbor/snapshot.py b/generator/openai_math_harbor/snapshot.py new file mode 100644 index 0000000000000000000000000000000000000000..a95a2896ae6c6a4bbcb9cc2cce329f2b5b5db791 --- /dev/null +++ b/generator/openai_math_harbor/snapshot.py @@ -0,0 +1,55 @@ +"""Build the shared Daytona snapshot from image/Dockerfile. + +Harbor's own auto-snapshot waits only 10 minutes, and downloading Mathlib takes longer, so the +snapshot is built once up front and passed to Harbor with ``--ek snapshot_template_name=``. +The name carries a hash of image/, so a changed recipe gets a new snapshot. + + python -m openai_math_harbor.snapshot [--print-name] +""" + +from __future__ import annotations + +import argparse +import hashlib +from pathlib import Path + +IMAGE_DIR = Path(__file__).parents[1] / "image" + + +def snapshot_name() -> str: + h = hashlib.sha256() + # Regular files only: a stray __pycache__ or editor backup must not change or break the hash. + for path in sorted(IMAGE_DIR.iterdir()): + if path.is_file() and not path.name.startswith(".") and not path.name.endswith((".pyc", "~")): + h.update(path.name.encode() + b"\0" + path.read_bytes()) + return f"openai-math-lean-{h.hexdigest()[:12]}" + + +def main() -> None: + ap = argparse.ArgumentParser(description=__doc__) + ap.add_argument("--print-name", action="store_true") + args = ap.parse_args() + name = snapshot_name() + if args.print_name: + print(name) + return + from daytona import CreateSnapshotParams, Daytona, Image, Resources + + d = Daytona() + try: + snap = d.snapshot.get(name) + print(f"{name} already exists ({snap.state})") + return + except Exception: + pass + image = Image.from_dockerfile(IMAGE_DIR / "Dockerfile") + d.snapshot.create( + CreateSnapshotParams(name=name, image=image, resources=Resources(cpu=4, memory=8, disk=10)), + on_logs=lambda line: print(line, flush=True), + timeout=3 * 3600, + ) + print(f"created {name}") + + +if __name__ == "__main__": + main() diff --git a/generator/openai_math_harbor/templates/LICENSE b/generator/openai_math_harbor/templates/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/generator/openai_math_harbor/templates/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/generator/openai_math_harbor/templates/LICENSE-openai-math b/generator/openai_math_harbor/templates/LICENSE-openai-math new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/generator/openai_math_harbor/templates/LICENSE-openai-math @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/generator/openai_math_harbor/templates/NOTICE b/generator/openai_math_harbor/templates/NOTICE new file mode 100644 index 0000000000000000000000000000000000000000..71bd2ce85f148da60119540f670246d7308c76c2 --- /dev/null +++ b/generator/openai_math_harbor/templates/NOTICE @@ -0,0 +1,38 @@ +openai-math-harbor +================== + +This dataset packages the Lean statements of OpenAI's "openai/math" release as Harbor tasks. + +Redistributed material +---------------------- +Each task's tests/Challenge.lean, and the Lean block quoted in its instruction.md, is the file +lean/ComparatorChallenges/.lean from https://github.com/openai/math at commit +$source_commit, copyright OpenAI, licensed under the Apache License, Version 2.0 (see +LICENSE-openai-math). The files are unchanged. + +Modified material +----------------- +The Comparator configuration of each task (tests/task.json) is derived from the corresponding +lean/ComparatorChallenges/.json in that repository. In eight tasks, definitions that the +original listed under "definition_names" although their bodies are written out were removed from +that list, so that Comparator requires them to match exactly; task.toml records them under +[metadata] fixed_definitions. + +Only statements whose official proof was verified in the environment are included; the README +lists the others and why each could not be validated. One challenge (DefocusingNLS) is left out +by design. + +Not included +------------ +OpenAI's proofs (the lean/OAI library) are not part of this dataset. + +Everything else in this dataset (task.toml, instruction.md apart from the quoted statement, +tests/grade.py, tests/test.sh, environment/, solution/, generator/) is licensed under the +Apache License, Version 2.0 (see LICENSE). + +Third-party software in the sandbox image +----------------------------------------- +Lean 4 and Mathlib (Apache-2.0); Comparator and lean4export by the Lean FRO (Apache-2.0), +Comparator built from leanprover/comparator@d03acab with a one-line patch that passes +LEAN_NUM_THREADS into its sandbox; landrun (MIT). The image is built from environment/ at run +time; none of this software is stored in the dataset. diff --git a/generator/openai_math_harbor/templates/dataset_README.md b/generator/openai_math_harbor/templates/dataset_README.md new file mode 100644 index 0000000000000000000000000000000000000000..323c0795f91d4fa7a848f6d7f02d943de84b8f65 --- /dev/null +++ b/generator/openai_math_harbor/templates/dataset_README.md @@ -0,0 +1,138 @@ +--- +license: apache-2.0 +task_categories: +- other +tags: +- harbor +- rl-environment +- reinforcement-learning +- code-agent +- lean4 +- mathlib +- theorem-proving +- openai-math +pretty_name: "openai/math as Harbor environments" +--- + +# openai/math as Harbor environments + +> **Experimental.** Built on a research release that is itself new and not yet independently +> reviewed. Expect rough edges, and read any proof that scores 1 before relying on it. + +We ported the math problems from OpenAI's [openai/math](https://github.com/openai/math) release +(commit `$source_commit`) into [Harbor](https://github.com/harbor-framework/harbor) environments. +The release formalizes **$n_statements** of its results as Lean statements. This dataset contains +**$n_tasks environments**, the ones whose official proof we verified end to end in the environment, +covering $n_families result families across $n_subjects fields. The other $n_not_included are listed +under [Validation](#validation) with the reason each could not be validated. + +## How a task works + +The agent gets a sandbox with Lean 4 and a prebuilt Mathlib, no internet, and one of OpenAI's +theorems written in Lean with `sorry` where the proof should be. + +**What `sorry` means.** In Lean, `sorry` is a placeholder for a missing proof: it lets the file +compile as if the step were proven, but nothing has actually been shown, and Lean flags it. The +statement is given exactly as OpenAI formalized it, and the agent's job is to replace every `sorry` +with a real proof. + +When the agent finishes, a separate, fresh sandbox checks its proof with +[Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker: + +- **reward 1** if the theorem has exactly the original statement, the proof uses only Lean's + standard axioms (`propext`, `Quot.sound`, `Classical.choice`, so no leftover `sorry` and no new + axioms), and the Lean kernel accepts it; +- **reward 0** otherwise. + +OpenAI's own proofs serve as the reference solutions: Harbor's oracle fetches them from GitHub at +run time. They are not included here and the agent never sees them. + +## A strict reward + +The grader only accepts a complete proof of the statement exactly as OpenAI formalized it. That +makes it hard to game, but it is also a real limitation for problems like these: + +- a correct proof of an equivalent statement, written with different definitions or a different + formulation, scores 0; +- partial progress (useful lemmas, a proof of a special case, a correct strategy with a gap) scores 0; +- nothing rewards a creative approach unless it ends in a complete proof of this exact statement. + +For open research problems, a more general reward function that recognizes any valid solution to the +underlying problem, including creative reformulations and partial progress, would be a better +training signal. We use the strict check here because it is precise and cannot be fooled; treat it +as one end of that design space. + +## What's included + +- `tasks/` — one Harbor task per validated problem: instruction, Lean statement, sandbox image recipe, + verifier and oracle +- `registry.json` — Harbor registry entry (`openai-math-harbor@1.0`) +- `manifest.parquet` — one row per task: field, family, theorem names, reference-proof size, oracle + result +- `generator/` — the code that builds the sandbox image and regenerates the tasks from openai/math +- `LICENSE`, `NOTICE`, `LICENSE-openai-math` — licensing and attribution + +## Run it with the Harbor CLI + +You need Harbor 0.24+ with the Daytona backend (`DAYTONA_API_KEY`, `DAYTONA_API_URL`) and +credentials for the agent you run. + +```bash +pip install "harbor[daytona]>=0.24" daytona +hf download FineEnvs/openai-math-harbor --repo-type dataset --local-dir openai-math-harbor +cd openai-math-harbor + +# Build the shared sandbox image once (Lean 4, Mathlib, Comparator; ~9 GB, about an hour). +(cd generator && python -m openai_math_harbor.snapshot) +SNAP=$$(cd generator && python -m openai_math_harbor.snapshot --print-name) + +# Run any agent Harbor supports (`harbor agent list`) on a few tasks: +harbor run -p tasks -e daytona --ek snapshot_template_name=$$SNAP \ + -a -m -i plane-coloring -i hilbert-crouzeix -n 2 + +# Check that the grader accepts OpenAI's own proof of a task: +harbor run -p tasks -e daytona --ek snapshot_template_name=$$SNAP \ + -a oracle --allow-agent-host github.com -i plane-coloring +``` + +Each task asks for 4 CPUs, 8 GB of memory and 10 GB of disk, and gives the agent 4 hours. Task +names are the folder names under `tasks/`. + +## Validation + +We generated a task for every statement except one left out by design (`DefocusingNLS`, whose +statement has a `sorry` inside a definition its theorems depend on), and ran Harbor's oracle on each: +it submits OpenAI's own proof and has it graded by the same verifier an agent faces. Only tasks whose +official proof was accepted are included. + +$validation + +$not_validated + +The verifier was also tested against submissions that try to cheat (`sorry` in several disguises, +fake axioms, `native_decide`, weakened statements, redefined definitions, planted reward files, code +that runs during grading). All scored 0. A no-op agent scores 0. + +## Notes + +- **Configs.** In eight of openai/math's Comparator configs, definitions written out in the statement + were listed as "holes" that Comparator does not check, so a solution could redefine them. Here they + must match exactly; affected tasks list them under `fixed_definitions` in `task.toml`. +- **Contamination.** The statements and proofs have been public since 6 October 2026. +- **Difficulty.** These are open research problems; expect reward 0 on almost every task. + +Technical details (grading design, threat model, image recipe) are in `generator/README.md`. + +## License + +- The Lean statements are copied unchanged from [openai/math](https://github.com/openai/math) + (© OpenAI), licensed under the + [Apache License 2.0](https://github.com/openai/math/blob/main/LICENSE); see `LICENSE-openai-math` + and `NOTICE`. OpenAI's proofs are not redistributed. +- The packaging, verifier and generator are Apache-2.0 (`LICENSE`). +- The sandbox image is built from [Lean 4](https://github.com/leanprover/lean4) and + [Mathlib](https://github.com/leanprover-community/mathlib4) (Apache-2.0), + [Comparator](https://github.com/leanprover/comparator) and + [lean4export](https://github.com/leanprover/lean4export) (Apache-2.0), and + [landrun](https://github.com/Zouuup/landrun) (MIT). +- If you use the results, cite the openai/math manuscripts as that repository asks. diff --git a/generator/openai_math_harbor/templates/instruction.md b/generator/openai_math_harbor/templates/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d08cda955ecd3dc990269a89d373eeff1fcb313 --- /dev/null +++ b/generator/openai_math_harbor/templates/instruction.md @@ -0,0 +1,52 @@ +# $title + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family $family_number of the release, *$family_title* +($subject). The family as a whole: $family_summary + +The challenge is `$challenge`, also at `/opt/openai-math/challenges/$challenge.lean`: + +```lean +$lean +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/$challenge.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** $targets must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs$holes. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/generator/openai_math_harbor/templates/solution/solve.sh b/generator/openai_math_harbor/templates/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9ee2f23ee77d337ffcabd9f45e01adabf3393966 --- /dev/null +++ b/generator/openai_math_harbor/templates/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of $challenge, i.e. module $solution_module and the +# $n_modules OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$$(mktemp -d) + git -C "$$tmp" init -q + git -C "$$tmp" remote add origin https://github.com/openai/math.git + git -C "$$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$$#.lean#' /solution/closure.txt > "$$tmp/.git/info/sparse-checkout" + git -C "$$tmp" fetch -q --depth 1 --filter=blob:none origin $source_commit + git -C "$$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$$tmp/lean" /solution/closure.txt $solution_module /workspace + rm -rf "$$tmp" +fi +echo "placed the reference proof of $challenge" diff --git a/generator/openai_math_harbor/templates/tests/grade.py b/generator/openai_math_harbor/templates/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/generator/openai_math_harbor/templates/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/generator/openai_math_harbor/templates/tests/test.sh b/generator/openai_math_harbor/templates/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/generator/openai_math_harbor/templates/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/generator/tests/test_grade_unpack.py b/generator/tests/test_grade_unpack.py new file mode 100644 index 0000000000000000000000000000000000000000..c8eb8b143a0faba44b28ac1d9c2358f50f36b84a --- /dev/null +++ b/generator/tests/test_grade_unpack.py @@ -0,0 +1,150 @@ +"""The verifier's submission unpacking accepts only regular Submission*.lean files. + + python -m unittest discover -s tests +""" + +from __future__ import annotations + +import importlib.util +import io +import tarfile +import tempfile +import unittest +from pathlib import Path + +GRADE = Path(__file__).parents[1] / "openai_math_harbor" / "templates" / "tests" / "grade.py" +spec = importlib.util.spec_from_file_location("grade", GRADE) +grade = importlib.util.module_from_spec(spec) +spec.loader.exec_module(grade) + + +def make_tar(path: Path, entries: list[tuple[str, str, bytes]]) -> None: + """entries: (name, kind, data) with kind in reg/dir/sym/lnk/fifo.""" + with tarfile.open(path, "w") as tar: + for name, kind, data in entries: + info = tarfile.TarInfo(name) + if kind == "reg": + info.size = len(data) + tar.addfile(info, io.BytesIO(data)) + continue + info.type = {"dir": tarfile.DIRTYPE, "sym": tarfile.SYMTYPE, "lnk": tarfile.LNKTYPE, + "fifo": tarfile.FIFOTYPE}[kind] + info.linkname = data.decode() + tar.addfile(info) + + +class UnpackTest(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.tar = self.tmp / "submission.tar" + self.dest = self.tmp / "run" + self.dest.mkdir() + grade.SUBMISSION_TAR = self.tar + + def unpack(self, entries): + make_tar(self.tar, entries) + return grade.unpack_submission(self.dest) + + def test_accepts_root_and_modules(self): + info = self.unpack([ + ("Submission.lean", "reg", b"import Submission.A.B\n"), + ("Submission", "dir", b""), + ("Submission/A/B.lean", "reg", "theorem t : True := trivial -- ℕ\n".encode()), + ]) + self.assertEqual(info["files"], 2) + self.assertTrue((self.dest / "Submission" / "A" / "B.lean").is_file()) + + def test_accepts_unicode_identifiers(self): + info = self.unpack([ + ("Submission.lean", "reg", b"import Submission.Arith.Kappa\xe2\x82\x81\n"), + ("Submission/Arith/Kappa₁.lean", "reg", b"theorem k : True := trivial\n"), + ("Submission/αβ/Lemma'.lean", "reg", b""), + ]) + self.assertEqual(info["files"], 3) + + def test_rejections(self): + cases = { + "missing root": [("Submission/A.lean", "reg", b"")], + "path traversal": [("Submission.lean", "reg", b""), ("Submission/../../etc/x.lean", "reg", b"")], + "absolute path": [("Submission.lean", "reg", b""), ("/tmp/Submission.lean", "reg", b"")], + "symlink": [("Submission.lean", "sym", b"/tests/Challenge.lean")], + "hardlink": [("Submission.lean", "reg", b""), ("Submission/X.lean", "lnk", b"Submission.lean")], + "fifo": [("Submission.lean", "reg", b""), ("Submission/X.lean", "fifo", b"")], + "other root": [("Submission.lean", "reg", b""), ("Challenge.lean", "reg", b"")], + "lakefile": [("Submission.lean", "reg", b""), ("lakefile.lean", "reg", b"")], + "non-lean": [("Submission.lean", "reg", b""), ("Submission/x.olean", "reg", b"")], + "bad module name": [("Submission.lean", "reg", b""), ("Submission/a-b.lean", "reg", b"")], + "digit first": [("Submission.lean", "reg", b""), ("Submission/1x.lean", "reg", b"")], + "dot component": [("Submission.lean", "reg", b""), ("Submission/../x.lean", "reg", b"")], + "space": [("Submission.lean", "reg", b""), ("Submission/a b.lean", "reg", b"")], + "non-utf8": [("Submission.lean", "reg", b"\xff\xfe")], + "duplicate": [("Submission.lean", "reg", b"a"), ("Submission.lean", "reg", b"b")], + } + for label, entries in cases.items(): + with self.subTest(label): + for p in self.dest.iterdir(): + import shutil + shutil.rmtree(p) if p.is_dir() else p.unlink() + with self.assertRaises(grade.Rejected): + self.unpack(entries) + self.assertFalse((self.tmp / "etc").exists()) + + def test_missing_archive(self): + with self.assertRaises(grade.Rejected): + grade.unpack_submission(self.dest) + + def test_archive_symlink(self): + self.tar.symlink_to("/etc/hostname") + with self.assertRaises(grade.Rejected): + grade.unpack_submission(self.dest) + + def test_timeout_kills_grandchildren(self): + import time + # A grandchild holding stdout open is what made the old `timeout`-based call hang. + start = time.time() + code, out, _ = grade.run_with_timeout( + ["bash", "-c", "echo started; (sleep 120; echo late) & sleep 120"], + cwd=self.tmp, timeout_sec=2) + self.assertIsNone(code) + self.assertIn("started", out) + self.assertNotIn("late", out) + self.assertLess(time.time() - start, 15) + + def test_run_with_timeout_normal_exit(self): + code, out, _ = grade.run_with_timeout(["bash", "-c", "echo ok; exit 3"], cwd=self.tmp, timeout_sec=10) + self.assertEqual((code, out.strip()), (3, "ok")) + + def test_ensure_readable_touches_only_what_needs_it(self): + import os + root = self.tmp / "tree"; (root / "sub").mkdir(parents=True) + good, bad, writable = root / "good.olean", root / "sub" / "bad.olean", root / "w.olean" + for f in (good, bad, writable): f.write_text("x") + good.chmod(0o644); bad.chmod(0o600); writable.chmod(0o666) + before = os.stat(good).st_ctime_ns + changed = grade.ensure_readable((str(root),)) + self.assertEqual(changed, 2) + self.assertEqual(bad.stat().st_mode & 0o777, 0o644) + self.assertEqual(writable.stat().st_mode & 0o777, 0o644) + self.assertEqual(os.stat(good).st_ctime_ns, before) # untouched: no overlay copy-up + self.assertEqual(grade.ensure_readable((str(root),)), 0) + + def test_out_of_memory_detection(self): + self.assertTrue(grade.out_of_memory("✖ Building M\nerror: Lean exited with code 137\n")) + self.assertTrue(grade.out_of_memory("uncaught exception: Child exited with 137")) + self.assertFalse(grade.out_of_memory("uncaught exception: Child exited with 1")) + reward, reason = grade.classify(1, "Building Submission\nerror: Lean exited with code 137\n") + self.assertEqual(reward, 0) + self.assertIn("out of memory", reason) + + def test_classify(self): + ok = "Building Challenge\nBuilding Submission\nYour solution is okay!\n" + self.assertEqual(grade.classify(0, ok)[0], 1) + self.assertEqual(grade.classify(1, ok)[0], 0) # success line but nonzero exit + self.assertEqual(grade.classify(0, "Building Submission\n")[0], 0) # exit 0, no success line + self.assertEqual(grade.classify(None, ok)[0], 0) # timeout + self.assertIsNone(grade.classify(1, "Building Challenge\nerror\n")[0]) # trusted side broke + self.assertIsNone(grade.classify(None, "Building Challenge\n")[0]) # timed out before the submission + + +if __name__ == "__main__": + unittest.main() diff --git a/manifest.json b/manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..dca74664592ced2aae5607ce92b5d8743acb9844 --- /dev/null +++ b/manifest.json @@ -0,0 +1,6805 @@ +{ + "source": "https://github.com/openai/math", + "source_commit": "adc7f1241b42e322a6451854ab7e4b4c146bf78a", + "tasks": [ + { + "task": "abhyankar-sathaye", + "challenge": "AbhyankarSathaye", + "family": "049", + "family_title": "A stable-coordinate counterexample in four variables", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.AbhyankarSathaye.exists_noncoordinate_polynomial" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 55824, + "packages": [], + "grade_timeout_sec": 10850, + "oracle_result": "accepted", + "oracle_grade_seconds": 463 + }, + { + "task": "affine-bernstein", + "challenge": "AffineBernstein", + "family": "353", + "family_title": "The sharp dimension threshold for affine Bernstein rigidity", + "subject": "Differential geometry", + "theorems": [ + "OAI.AffineBernstein.affine_bernstein" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 322, + "bytes": 1998143, + "packages": [], + "grade_timeout_sec": 12598, + "oracle_result": "accepted", + "oracle_grade_seconds": 1091 + }, + { + "task": "algorithmic-thin-trees", + "challenge": "AlgorithmicThinTrees", + "family": "174", + "family_title": "Deterministic construction of strong thin spanning trees", + "subject": "Combinatorics", + "theorems": [ + "OAI.AlgorithmicThinTrees.algorithmic_strong_thin_trees" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 736, + "bytes": 4556988, + "packages": [], + "grade_timeout_sec": 14901, + "oracle_result": "accepted", + "oracle_grade_seconds": 2906 + }, + { + "task": "amplitude-damping", + "challenge": "AmplitudeDamping", + "family": "276", + "family_title": "The classical capacity of generalized amplitude damping", + "subject": "Mathematical physics", + "theorems": [ + "OAI.GAD.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 283452, + "packages": [], + "grade_timeout_sec": 11055, + "oracle_result": "accepted", + "oracle_grade_seconds": 1119 + }, + { + "task": "artin-cat0", + "challenge": "ArtinCAT0", + "family": "254", + "family_title": "Classifying spaces and geometric obstructions for Artin groups", + "subject": "Group theory", + "theorems": [ + "OAI.ArtinCAT0.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 20, + "bytes": 414894, + "packages": [], + "grade_timeout_sec": 11173, + "oracle_result": "accepted", + "oracle_grade_seconds": 792 + }, + { + "task": "artin-parabolic-intersections", + "challenge": "ArtinParabolicIntersections", + "family": "254", + "family_title": "Classifying spaces and geometric obstructions for Artin groups", + "subject": "Group theory", + "theorems": [ + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_intersections", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_arbitrary_intersections", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_closure", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_nonclique_dynamics" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 782, + "bytes": 3300665, + "packages": [], + "grade_timeout_sec": 13770, + "oracle_result": "accepted", + "oracle_grade_seconds": 1711 + }, + { + "task": "asymptotically-minimal-littlewood", + "challenge": "AsymptoticallyMinimalLittlewood", + "family": "076", + "family_title": "Ultraflat real Littlewood polynomials", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.AsymptoticallyMinimalLittlewood.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 24, + "bytes": 432620, + "packages": [], + "grade_timeout_sec": 11189, + "oracle_result": "accepted", + "oracle_grade_seconds": 919 + }, + { + "task": "auslander-reiten", + "challenge": "AuslanderReiten", + "family": "199", + "family_title": "Counterexamples to conjectures of Auslander\u2013Reiten, Tachikawa, and Nakayama", + "subject": "Algebra", + "theorems": [ + "OAI.ArExplicit.Statement.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 732, + "bytes": 2349871, + "packages": [], + "grade_timeout_sec": 12914, + "oracle_result": "accepted", + "oracle_grade_seconds": 2615 + }, + { + "task": "backward-intertwiners", + "challenge": "BackwardIntertwiners", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.BackwardIntertwiners.direct_algebra_corollary" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 23, + "bytes": 262844, + "packages": [], + "grade_timeout_sec": 11036, + "oracle_result": "accepted", + "oracle_grade_seconds": 823 + }, + { + "task": "balanced-box-routing", + "challenge": "BalancedBoxRouting", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.BoxTransport.Routing.balanced_box_routing" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 7, + "bytes": 164970, + "packages": [], + "grade_timeout_sec": 10948, + "oracle_result": "accepted", + "oracle_grade_seconds": 299 + }, + { + "task": "balanced-ryser", + "challenge": "BalancedRyser", + "family": "162", + "family_title": "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures", + "subject": "Combinatorics", + "theorems": [ + "OAI.Balanced.main_result" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 698, + "bytes": 3897149, + "packages": [], + "grade_timeout_sec": 14307, + "oracle_result": "accepted", + "oracle_grade_seconds": 1733 + }, + { + "task": "balanced-three-stack", + "challenge": "BalancedThreeStack", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.BalancedTransport.balanced_three_stack_realization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 60, + "bytes": 495983, + "packages": [], + "grade_timeout_sec": 11246, + "oracle_result": "accepted", + "oracle_grade_seconds": 1956 + }, + { + "task": "ball-packing", + "challenge": "BallPacking", + "family": "343", + "family_title": "Sharp symplectic ball-packing criteria in higher dimensions", + "subject": "Differential geometry", + "theorems": [ + "OAI.HigherDimensionalBallPacking.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 169, + "bytes": 4529811, + "packages": [], + "grade_timeout_sec": 14876, + "oracle_result": "accepted", + "oracle_grade_seconds": 4562 + }, + { + "task": "ball-packing-necessity", + "challenge": "BallPackingNecessity", + "family": "343", + "family_title": "Sharp symplectic ball-packing criteria in higher dimensions", + "subject": "Differential geometry", + "theorems": [ + "OAI.HigherDimensionalBallPacking.packing_necessity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 65, + "bytes": 1673682, + "packages": [], + "grade_timeout_sec": 12306, + "oracle_result": "accepted", + "oracle_grade_seconds": 1874 + }, + { + "task": "barnette-hamiltonian", + "challenge": "BarnetteHamiltonian", + "family": "180", + "family_title": "Barnette's Hamiltonian-cycle conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.Barnette.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 379455, + "packages": [], + "grade_timeout_sec": 11141, + "oracle_result": "accepted", + "oracle_grade_seconds": 752 + }, + { + "task": "bass-torsion-free", + "challenge": "BassTorsionFree", + "family": "207", + "family_title": "The $\\ell^1$-Bass and complex Bass trace conjectures", + "subject": "Algebra", + "theorems": [ + "OAI.TorsionFreeBass.torsion_free_corollary" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 73, + "bytes": 1022515, + "packages": [], + "grade_timeout_sec": 11720, + "oracle_result": "accepted", + "oracle_grade_seconds": 1087 + }, + { + "task": "bass-trace", + "challenge": "BassTrace", + "family": "207", + "family_title": "The $\\ell^1$-Bass and complex Bass trace conjectures", + "subject": "Algebra", + "theorems": [ + "OAI.BassTrace.RightProjective.bassTraceModules_vanishing_and_support" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 69, + "bytes": 997569, + "packages": [], + "grade_timeout_sec": 11697, + "oracle_result": "accepted", + "oracle_grade_seconds": 1120 + }, + { + "task": "benjamini-schramm", + "challenge": "BenjaminiSchramm", + "family": "214", + "family_title": "The Benjamini\u2013Schramm nonuniqueness conjecture", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Percolation.BenjaminiSchramm.full_main", + "OAI.Percolation.BenjaminiSchramm.cayley_main", + "OAI.Percolation.BenjaminiSchramm.critical_laws" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 970, + "bytes": 6834429, + "packages": [], + "grade_timeout_sec": 16950, + "oracle_result": "accepted", + "oracle_grade_seconds": 3592 + }, + { + "task": "bernoulli-nonflat-in-seven", + "challenge": "BernoulliNonflatInSeven", + "family": "367", + "family_title": "The critical dimension for the one-phase Bernoulli problem", + "subject": "Partial differential equations", + "theorems": [ + "OAI.Bernoulli.nonflat_in_seven" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 91, + "bytes": 640271, + "packages": [], + "grade_timeout_sec": 11376, + "oracle_result": "accepted", + "oracle_grade_seconds": 1160 + }, + { + "task": "biholder-transport", + "challenge": "BiholderTransport", + "family": "360", + "family_title": "Villani\u2019s convexity conjecture and regular optimal transport", + "subject": "Differential geometry", + "theorems": [ + "OAI.WeakMTWTransport.uniform_biHolder_transport" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 645, + "bytes": 3202559, + "packages": [], + "grade_timeout_sec": 13682, + "oracle_result": "accepted", + "oracle_grade_seconds": 3094 + }, + { + "task": "bin-packing-gap", + "challenge": "BinPackingGap", + "family": "118", + "family_title": "Unbounded bin-packing gaps and the modified integer round-up conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.BinPackingGap.main_results" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 284, + "bytes": 7557041, + "packages": [], + "grade_timeout_sec": 17601, + "oracle_result": "accepted", + "oracle_grade_seconds": 1412 + }, + { + "task": "binary-edit-lower", + "challenge": "BinaryEditLower", + "family": "099", + "family_title": "The sharp distortion of edit distance into $\\ell_1$", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.TreeEdit.binary_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 84, + "bytes": 464862, + "packages": [], + "grade_timeout_sec": 11218, + "oracle_result": "accepted", + "oracle_grade_seconds": 790 + }, + { + "task": "binary-matching", + "challenge": "BinaryMatching", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.BinaryMatching.deterministic_approximate_counting" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 112, + "bytes": 617632, + "packages": [], + "grade_timeout_sec": 11355, + "oracle_result": "accepted", + "oracle_grade_seconds": 1132 + }, + { + "task": "binary-sweep", + "challenge": "BinarySweep", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.binary_sweep_contraction_and_mixing" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 192, + "bytes": 1151658, + "packages": [], + "grade_timeout_sec": 11836, + "oracle_result": "accepted", + "oracle_grade_seconds": 1210 + }, + { + "task": "bipartite-crossing", + "challenge": "BipartiteCrossing", + "family": "165", + "family_title": "Exact crossing numbers of complete and complete bipartite graphs", + "subject": "Combinatorics", + "theorems": [ + "OAI.Zarankiewicz.mainTarget_proof" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 339, + "bytes": 893808, + "packages": [], + "grade_timeout_sec": 11604, + "oracle_result": "accepted", + "oracle_grade_seconds": 790 + }, + { + "task": "bogomolov-pop-injectivity", + "challenge": "BogomolovPopInjectivity", + "family": "009", + "family_title": "Bogomolov\u2013Pop and Milnor $K$-theoretic reconstruction", + "subject": "Number theory", + "theorems": [ + "OAI.BogomolovPop.main_graph_injective" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 5, + "bytes": 155277, + "packages": [], + "grade_timeout_sec": 10939, + "oracle_result": "accepted", + "oracle_grade_seconds": 445 + }, + { + "task": "boltzmann-nonuniqueness", + "challenge": "BoltzmannNonuniqueness", + "family": "363", + "family_title": "Boltzmann nonuniqueness with exact local conservation", + "subject": "Partial differential equations", + "theorems": [ + "OAI.BoltzmannNonuniqueness.nonuniqueness" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 525, + "bytes": 7330824, + "packages": [], + "grade_timeout_sec": 17397, + "oracle_result": "accepted", + "oracle_grade_seconds": 1584 + }, + { + "task": "boone-higman", + "challenge": "BooneHigman", + "family": "250", + "family_title": "The Boone\u2013Higman conjecture and higher finiteness", + "subject": "Group theory", + "theorems": [ + "OAI.FiniteAlgebraicEnvelopes.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 1687310, + "packages": [], + "grade_timeout_sec": 12318, + "oracle_result": "accepted", + "oracle_grade_seconds": 976 + }, + { + "task": "borsuk-nine", + "challenge": "BorsukNine", + "family": "156", + "family_title": "Borsuk's conjecture fails in dimension nine", + "subject": "Combinatorics", + "theorems": [ + "OAI.BorsukNine.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 269, + "bytes": 3525234, + "packages": [], + "grade_timeout_sec": 13972, + "oracle_result": "accepted", + "oracle_grade_seconds": 893 + }, + { + "task": "bounded-recovery", + "challenge": "BoundedRecovery", + "family": "290", + "family_title": "Connes' bicentralizer conjecture and relative bicentralizers", + "subject": "Operator algebras", + "theorems": [ + "OAI.BoundedRecovery.bounded_recovery" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 27, + "bytes": 368603, + "packages": [], + "grade_timeout_sec": 11131, + "oracle_result": "accepted", + "oracle_grade_seconds": 1002 + }, + { + "task": "bounded-tree-potentials", + "challenge": "BoundedTreePotentials", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.BoundedTreePotentials.TreeCalculus.main_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 46, + "bytes": 595707, + "packages": [], + "grade_timeout_sec": 11336, + "oracle_result": "accepted", + "oracle_grade_seconds": 758 + }, + { + "task": "bounded-treewidth-l1", + "challenge": "BoundedTreewidthL1", + "family": "089", + "family_title": "Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.BoundedTreewidthL1.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 33, + "bytes": 708126, + "packages": [], + "grade_timeout_sec": 11437, + "oracle_result": "accepted", + "oracle_grade_seconds": 791 + }, + { + "task": "brenier", + "challenge": "Brenier", + "family": "374", + "family_title": "Sharp one-third stability of optimal transport maps", + "subject": "Partial differential equations", + "theorems": [ + "OAI.Problem358.one_third_stability", + "OAI.Problem358.one_third_exponent_is_sharp" + ], + "definition_holes": [], + "fixed_definitions": [ + "OAI.Problem358.E", + "OAI.Problem358.uniformMeasure", + "OAI.Problem358.IsSupported", + "OAI.Problem358.IsCoupling", + "OAI.Problem358.quadraticPlanCost", + "OAI.Problem358.wasserstein2", + "OAI.Problem358.graphPlan", + "OAI.Problem358.IsQuadraticOptimalMap", + "OAI.Problem358.IsUniqueQuadraticOptimalMap", + "OAI.Problem358.mapL2Dist", + "OAI.Problem358.cube", + "OAI.Problem358.HasExactlyThreeAtoms" + ], + "n_modules": 89, + "bytes": 1532625, + "packages": [], + "grade_timeout_sec": 12179, + "oracle_result": "accepted", + "oracle_grade_seconds": 2528 + }, + { + "task": "brennan", + "challenge": "Brennan", + "family": "072", + "family_title": "Brennan's conjecture and a counterexample to Kraetzer's prediction", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.Brennan.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 38, + "bytes": 692980, + "packages": [], + "grade_timeout_sec": 11423, + "oracle_result": "accepted", + "oracle_grade_seconds": 1116 + }, + { + "task": "brennan-sharp", + "challenge": "BrennanSharp", + "family": "072", + "family_title": "Brennan's conjecture and a counterexample to Kraetzer's prediction", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.Brennan.Sharp.sharp_endpoints" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 711263, + "packages": [], + "grade_timeout_sec": 11440, + "oracle_result": "accepted", + "oracle_grade_seconds": 895 + }, + { + "task": "buffered-ising", + "challenge": "BufferedIsing", + "family": "218", + "family_title": "Conformal universality for weakly interacting and disordered Ising models", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.BufferedIsing.finite_graph_comparison" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 136460, + "packages": [], + "grade_timeout_sec": 10922, + "oracle_result": "accepted", + "oracle_grade_seconds": 2053 + }, + { + "task": "c0-absorption", + "challenge": "C0Absorption", + "family": "324", + "family_title": "Lipschitz equivalence without linear isomorphism", + "subject": "Functional analysis", + "theorems": [ + "OAI.C0Absorption.main_result" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 366161, + "packages": [], + "grade_timeout_sec": 11129, + "oracle_result": "accepted", + "oracle_grade_seconds": 1155 + }, + { + "task": "c1-entropy-counterexample", + "challenge": "C1EntropyCounterexample", + "family": "151", + "family_title": "A $C^1$ counterexample to Shub\u2019s entropy conjecture", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.Problem340.exists_C1_entropy_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 201, + "bytes": 965060, + "packages": [], + "grade_timeout_sec": 11668, + "oracle_result": "accepted", + "oracle_grade_seconds": 1331 + }, + { + "task": "ch-obstruction", + "challenge": "CHObstruction", + "family": "240", + "family_title": "Shelah's eventual categoricity conjecture", + "subject": "Mathematical logic", + "theorems": [ + "OAI.CHObstruction.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 199905, + "packages": [], + "grade_timeout_sec": 10979, + "oracle_result": "accepted", + "oracle_grade_seconds": 1476 + }, + { + "task": "cks-bondi-penrose", + "challenge": "CKSBondiPenrose", + "family": "260", + "family_title": "Spacetime Penrose inequalities and rigidity", + "subject": "Mathematical physics", + "theorems": [ + "OAI.CKSSourceExterior.area_controlled_end_replacement", + "OAI.CKSMain.schwarzschild_equality_examples" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 336, + "bytes": 2829003, + "packages": [], + "grade_timeout_sec": 13346, + "oracle_result": "accepted", + "oracle_grade_seconds": 1456 + }, + { + "task": "cannon-geometric-action", + "challenge": "CannonGeometricAction", + "family": "246", + "family_title": "Cannon's conjecture", + "subject": "Group theory", + "theorems": [ + "OAI.CannonRelease.cannon" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 299, + "bytes": 2904193, + "packages": [], + "grade_timeout_sec": 13413, + "oracle_result": "accepted", + "oracle_grade_seconds": 970 + }, + { + "task": "cayley-percolation", + "challenge": "CayleyPercolation", + "family": "214", + "family_title": "The Benjamini\u2013Schramm nonuniqueness conjecture", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Percolation.arbitrary_cayley" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 78, + "bytes": 2644104, + "packages": [], + "grade_timeout_sec": 13179, + "oracle_result": "accepted", + "oracle_grade_seconds": 1048 + }, + { + "task": "character-criterion", + "challenge": "CharacterCriterion", + "family": "299", + "family_title": "The Kirchberg\u2013R\\o rdam character criterion", + "subject": "Operator algebras", + "theorems": [ + "OAI.KirchbergRordam.character_criterion" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 62, + "bytes": 1147190, + "packages": [], + "grade_timeout_sec": 11832, + "oracle_result": "accepted", + "oracle_grade_seconds": 1889 + }, + { + "task": "choiceless-polynomial-time", + "challenge": "ChoicelessPolynomialTime", + "family": "243", + "family_title": "Choiceless counting does not capture polynomial time", + "subject": "Mathematical logic", + "theorems": [ + "OAI.CPTSeparation.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 26, + "bytes": 803577, + "packages": [], + "grade_timeout_sec": 11523, + "oracle_result": "accepted", + "oracle_grade_seconds": 574 + }, + { + "task": "circulant-hadamard", + "challenge": "CirculantHadamard", + "family": "179", + "family_title": "The circulant Hadamard conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.CirculantHadamard.exists_iff_order_one_or_four" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 68, + "bytes": 400871, + "packages": [], + "grade_timeout_sec": 11160, + "oracle_result": "accepted", + "oracle_grade_seconds": 1652 + }, + { + "task": "classical-on", + "challenge": "ClassicalON", + "family": "215", + "family_title": "Massive continuum limits and exact mass asymptotics for planar $O(n)$ models", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ClassicalON.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 117, + "bytes": 582811, + "packages": [], + "grade_timeout_sec": 11324, + "oracle_result": "accepted", + "oracle_grade_seconds": 1392 + }, + { + "task": "clique-free-log", + "challenge": "CliqueFreeLog", + "family": "184", + "family_title": "Coloring and independence in graphs with forbidden subgraphs", + "subject": "Combinatorics", + "theorems": [ + "OAI.CliqueFreeLog.logarithmic_independence_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 229474, + "packages": [], + "grade_timeout_sec": 11006, + "oracle_result": "accepted", + "oracle_grade_seconds": 794 + }, + { + "task": "coboundary-expanders", + "challenge": "CoboundaryExpanders", + "family": "177", + "family_title": "Bounded-degree coboundary expanders in every dimension", + "subject": "Combinatorics", + "theorems": [ + "OAI.CoboundaryExpanders.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 36, + "bytes": 1459141, + "packages": [], + "grade_timeout_sec": 12113, + "oracle_result": "accepted", + "oracle_grade_seconds": 1082 + }, + { + "task": "common-bases-fpras", + "challenge": "CommonBasesFPRAS", + "family": "114", + "family_title": "Approximate counting of common integer polymatroid bases", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.common_bases_fpras" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1, + "bytes": 1336009, + "packages": [], + "grade_timeout_sec": 12002, + "oracle_result": "accepted", + "oracle_grade_seconds": 950 + }, + { + "task": "commuting-derivations", + "challenge": "CommutingDerivations", + "family": "049", + "family_title": "A stable-coordinate counterexample in four variables", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.AbhyankarSathaye.CommutingDerivations.commuting_derivations_with_ordinary_extras" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 32, + "bytes": 135211, + "packages": [], + "grade_timeout_sec": 10921, + "oracle_result": "accepted", + "oracle_grade_seconds": 426 + }, + { + "task": "compact-banach", + "challenge": "CompactBanach", + "family": "098", + "family_title": "A negative answer to the Lang\u2013Plaut problem", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.CompactBanach.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 207061, + "packages": [], + "grade_timeout_sec": 10986, + "oracle_result": "accepted", + "oracle_grade_seconds": 1439 + }, + { + "task": "complete-crossing", + "challenge": "CompleteCrossing", + "family": "165", + "family_title": "Exact crossing numbers of complete and complete bipartite graphs", + "subject": "Combinatorics", + "theorems": [ + "OAI.Paper170.complete_graph_crossing_number" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 300, + "bytes": 1464297, + "packages": [], + "grade_timeout_sec": 12117, + "oracle_result": "accepted", + "oracle_grade_seconds": 800 + }, + { + "task": "complete-crouzeix", + "challenge": "CompleteCrouzeix", + "family": "325", + "family_title": "The complete Crouzeix conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.CompleteCrouzeix.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 48, + "bytes": 652138, + "packages": [], + "grade_timeout_sec": 11386, + "oracle_result": "accepted", + "oracle_grade_seconds": 1153 + }, + { + "task": "complex-cancellation", + "challenge": "ComplexCancellation", + "family": "047", + "family_title": "Complex counterexamples to cancellation and affine fibrations", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.ComplexCancellation.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 55, + "bytes": 242585, + "packages": [], + "grade_timeout_sec": 11018, + "oracle_result": "accepted", + "oracle_grade_seconds": 971 + }, + { + "task": "conductivity", + "challenge": "Conductivity", + "family": "365", + "family_title": "Joint metric and connection recovery from one boundary patch", + "subject": "Partial differential equations", + "theorems": [ + "OAI.ScalarConductivity.main_nonuniqueness" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 595, + "bytes": 3618863, + "packages": [], + "grade_timeout_sec": 14056, + "oracle_result": "accepted", + "oracle_grade_seconds": 1871 + }, + { + "task": "conjugate-points", + "challenge": "ConjugatePoints", + "family": "358", + "family_title": "A three-manifold with no conjugate points and no nonpositively curved metric", + "subject": "Differential geometry", + "theorems": [ + "OAI.ThreeManifold.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 19, + "bytes": 1279256, + "packages": [], + "grade_timeout_sec": 11951, + "oracle_result": "accepted", + "oracle_grade_seconds": 1609 + }, + { + "task": "contingency-tables", + "challenge": "ContingencyTables", + "family": "115", + "family_title": "Sampling and counting contingency tables with arbitrary margins", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.ContingencyTables.boundedSampling", + "OAI.ContingencyTables.exactSampling", + "OAI.ContingencyTables.counting" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1297, + "bytes": 9098638, + "packages": [], + "grade_timeout_sec": 18988, + "oracle_result": "accepted", + "oracle_grade_seconds": 3243 + }, + { + "task": "continuous-circle-weight", + "challenge": "ContinuousCircleWeight", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.ContinuousCircleWeight.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 908147, + "packages": [], + "grade_timeout_sec": 11617, + "oracle_result": "accepted", + "oracle_grade_seconds": 1217 + }, + { + "task": "continuum-transition", + "challenge": "ContinuumTransition", + "family": "228", + "family_title": "Continuum phase transitions for radial pair potentials", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ContinuumTemperature.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 161, + "bytes": 697604, + "packages": [], + "grade_timeout_sec": 11427, + "oracle_result": "accepted", + "oracle_grade_seconds": 1607 + }, + { + "task": "coordinate-sweeps", + "challenge": "CoordinateSweeps", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CoordinateSweeps.conditional_main", + "OAI.CoordinateSweeps.all_grid_moment" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 1085561, + "packages": [], + "grade_timeout_sec": 11777, + "oracle_result": "accepted", + "oracle_grade_seconds": 1051 + }, + { + "task": "coordinate-trace", + "challenge": "CoordinateTrace", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThorpNine.Harmonic.Thorp.LowPlanes.regular_trace_smoothing" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 974102, + "packages": [], + "grade_timeout_sec": 11676, + "oracle_result": "accepted", + "oracle_grade_seconds": 1254 + }, + { + "task": "cotype", + "challenge": "Cotype", + "family": "326", + "family_title": "The cotype\u2013cotype conjecture under the approximation property", + "subject": "Functional analysis", + "theorems": [ + "OAI.Cotype.mainTarget_proved" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 125, + "bytes": 503929, + "packages": [], + "grade_timeout_sec": 11253, + "oracle_result": "accepted", + "oracle_grade_seconds": 1088 + }, + { + "task": "coulomb-counterexample", + "challenge": "CoulombCounterexample", + "family": "373", + "family_title": "Nonattainment in three-marginal Coulomb transport", + "subject": "Partial differential equations", + "theorems": [ + "OAI.Problem356.coulomb_counterexample_and_equal_infima" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 97, + "bytes": 467629, + "packages": [], + "grade_timeout_sec": 11220, + "oracle_result": "accepted", + "oracle_grade_seconds": 891 + }, + { + "task": "coulomb-ionization", + "challenge": "CoulombIonization", + "family": "263", + "family_title": "The ionization and generalized ionization conjectures", + "subject": "Mathematical physics", + "theorems": [ + "OAI.CoulombAtom.generalized_ionization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 607, + "bytes": 4613552, + "packages": [], + "grade_timeout_sec": 14952, + "oracle_result": "accepted", + "oracle_grade_seconds": 2115 + }, + { + "task": "coulomb-radii", + "challenge": "CoulombRadii", + "family": "263", + "family_title": "The ionization and generalized ionization conjectures", + "subject": "Mathematical physics", + "theorems": [ + "OAI.NeutralAtom.generalized_outer_radii" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 428, + "bytes": 3858816, + "packages": [], + "grade_timeout_sec": 14272, + "oracle_result": "accepted", + "oracle_grade_seconds": 2054 + }, + { + "task": "courtade-kumar", + "challenge": "CourtadeKumar", + "family": "119", + "family_title": "The Courtade\u2013Kumar and Hellinger conjectures", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.LeanBlast.CourtadeKumar.courtadeKumarAndAttainment" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 43, + "bytes": 327942, + "packages": [], + "grade_timeout_sec": 11095, + "oracle_result": "accepted", + "oracle_grade_seconds": 468 + }, + { + "task": "covering-density", + "challenge": "CoveringDensity", + "family": "092", + "family_title": "The optimal order of convex-body covering density", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.CoveringOrder.optimal_order" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 143, + "bytes": 1760761, + "packages": [], + "grade_timeout_sec": 12384, + "oracle_result": "accepted", + "oracle_grade_seconds": 1458 + }, + { + "task": "critical-percolation", + "challenge": "CriticalPercolation", + "family": "213", + "family_title": "No infinite critical clusters on quasi-transitive graphs", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CriticalPercolation.BondGraph.no_percolation_at_criticality" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 627, + "bytes": 2911033, + "packages": [], + "grade_timeout_sec": 13419, + "oracle_result": "accepted", + "oracle_grade_seconds": 2360 + }, + { + "task": "critical-sk", + "challenge": "CriticalSK", + "family": "227", + "family_title": "The dynamical phase transition in the Sherrington\u2013Kirkpatrick model", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CriticalSK.realized_equilibrium_initial_states", + "OAI.CriticalSK.covariance_and_linear_tests", + "OAI.CriticalSK.critical_mixing_lower_bounds" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 890802, + "packages": [], + "grade_timeout_sec": 11601, + "oracle_result": "accepted", + "oracle_grade_seconds": 892 + }, + { + "task": "critical-sk-mixing", + "challenge": "CriticalSKMixing", + "family": "227", + "family_title": "The dynamical phase transition in the Sherrington\u2013Kirkpatrick model", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CriticalSK.critical_mixing_bounds" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 593, + "bytes": 5600145, + "packages": [], + "grade_timeout_sec": 15840, + "oracle_result": "accepted", + "oracle_grade_seconds": 2139 + }, + { + "task": "critical-strip-mass", + "challenge": "CriticalStripMass", + "family": "237", + "family_title": "The three-quarter diameter exponent for honeycomb walks", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CriticalStrip.critical_strip_mass" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 130, + "bytes": 2796916, + "packages": [], + "grade_timeout_sec": 13317, + "oracle_result": "accepted", + "oracle_grade_seconds": 1959 + }, + { + "task": "critical-z3", + "challenge": "CriticalZ3", + "family": "213", + "family_title": "No infinite critical clusters on quasi-transitive graphs", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CriticalZ3.critical_no_infinite" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 461840, + "packages": [], + "grade_timeout_sec": 11215, + "oracle_result": "accepted", + "oracle_grade_seconds": 859 + }, + { + "task": "crouzeix-hilbert", + "challenge": "CrouzeixHilbert", + "family": "325", + "family_title": "The complete Crouzeix conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.CrouzeixHilbert.hilbert" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 90, + "bytes": 723645, + "packages": [], + "grade_timeout_sec": 11451, + "oracle_result": "accepted", + "oracle_grade_seconds": 1215 + }, + { + "task": "cubic-torus", + "challenge": "CubicTorus", + "family": "354", + "family_title": "Isoperimetric regions in the cubic three-torus", + "subject": "Differential geometry", + "theorems": [ + "OAI.CubicTorus.unit_cubic_isoperimetric" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 162, + "bytes": 6992456, + "packages": [], + "grade_timeout_sec": 17093, + "oracle_result": "accepted", + "oracle_grade_seconds": 2541 + }, + { + "task": "cycle-decomposition", + "challenge": "CycleDecomposition", + "family": "181", + "family_title": "The Erd\\H{o}s\u2013Gallai cycle-decomposition conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.ErdosGallai.erdos_gallai" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 998368, + "packages": [], + "grade_timeout_sec": 11698, + "oracle_result": "accepted", + "oracle_grade_seconds": 827 + }, + { + "task": "cylinder-covering", + "challenge": "CylinderCovering", + "family": "100", + "family_title": "A counterexample to Bang's cylinder-covering bound", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.CylinderCovering.fourPaperMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 641, + "bytes": 3013309, + "packages": [], + "grade_timeout_sec": 13511, + "oracle_result": "accepted", + "oracle_grade_seconds": 2016 + }, + { + "task": "daugavet-moduli", + "challenge": "DaugavetModuli", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.ExactModuli.exact_main", + "OAI.ExactModuli.kadets_werner_existence", + "OAI.ExactModuli.exact_example" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 201678, + "packages": [], + "grade_timeout_sec": 10981, + "oracle_result": "accepted", + "oracle_grade_seconds": 462 + }, + { + "task": "degree-rigidity", + "challenge": "DegreeRigidity", + "family": "241", + "family_title": "Rigidity of the Turing degrees", + "subject": "Mathematical logic", + "theorems": [ + "OAI.TuringRigidity.ManuscriptMain.rigidity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 974, + "bytes": 3922761, + "packages": [], + "grade_timeout_sec": 14330, + "oracle_result": "accepted", + "oracle_grade_seconds": 1821 + }, + { + "task": "deligne-drinfeld", + "challenge": "DeligneDrinfeld", + "family": "008", + "family_title": "The Deligne\u2013Drinfeld conjecture", + "subject": "Number theory", + "theorems": [ + "OAI.DeligneDrinfeld.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 21, + "bytes": 1357966, + "packages": [], + "grade_timeout_sec": 12022, + "oracle_result": "accepted", + "oracle_grade_seconds": 921 + }, + { + "task": "depth-five", + "challenge": "DepthFive", + "family": "135", + "family_title": "Sharp homogeneous depth-five complexity of matrix products", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.Problem335.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 164, + "bytes": 880264, + "packages": [], + "grade_timeout_sec": 11592, + "oracle_result": "accepted", + "oracle_grade_seconds": 1051 + }, + { + "task": "depth-three", + "challenge": "DepthThree", + "family": "112", + "family_title": "Beyond the square-root exponent for depth-three circuits", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.DepthThreeLowerBound.exists_polynomial_time_language_depth_three_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 175, + "bytes": 1026594, + "packages": [], + "grade_timeout_sec": 11723, + "oracle_result": "accepted", + "oracle_grade_seconds": 776 + }, + { + "task": "diamond-distortion", + "challenge": "DiamondDistortion", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.DiamondDistortion.headline_all_pairs" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 32, + "bytes": 472861, + "packages": [], + "grade_timeout_sec": 11225, + "oracle_result": "accepted", + "oracle_grade_seconds": 771 + }, + { + "task": "diluted-spin", + "challenge": "DilutedSpin", + "family": "221", + "family_title": "The Mezard\u2013Parisi formula for diluted spin glasses", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.DilutedSpinGlass.mezard_parisi" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 405, + "bytes": 2760702, + "packages": [], + "grade_timeout_sec": 13284, + "oracle_result": "accepted", + "oracle_grade_seconds": 1537 + }, + { + "task": "dimension-ten-channel", + "challenge": "DimensionTenChannel", + "family": "272", + "family_title": "Entanglement without secret key and the PPT-square conjecture", + "subject": "Mathematical physics", + "theorems": [ + "OAI.DimensionTen.exists_channel_fin21" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 148, + "bytes": 3075057, + "packages": [], + "grade_timeout_sec": 13567, + "oracle_result": "accepted", + "oracle_grade_seconds": 2360 + }, + { + "task": "dimension-ten-pair", + "challenge": "DimensionTenPair", + "family": "272", + "family_title": "Entanglement without secret key and the PPT-square conjecture", + "subject": "Mathematical physics", + "theorems": [ + "OAI.DimensionTen.main_pair" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 129, + "bytes": 2413995, + "packages": [], + "grade_timeout_sec": 12972, + "oracle_result": "accepted", + "oracle_grade_seconds": 1766 + }, + { + "task": "direct-crouzeix", + "challenge": "DirectCrouzeix", + "family": "325", + "family_title": "The complete Crouzeix conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.DirectCrouzeix.complete_crouzeix", + "OAI.DirectCrouzeix.uniform_sharpness" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 42, + "bytes": 314025, + "packages": [], + "grade_timeout_sec": 11082, + "oracle_result": "accepted", + "oracle_grade_seconds": 1202 + }, + { + "task": "directed-feedback", + "challenge": "DirectedFeedback", + "family": "102", + "family_title": "The Unique Games Conjecture and optimal approximation thresholds", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.DirectedFeedback.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 224, + "bytes": 8506385, + "packages": [], + "grade_timeout_sec": 18455, + "oracle_result": "accepted", + "oracle_grade_seconds": 1662 + }, + { + "task": "directional-ballisticity", + "challenge": "DirectionalBallisticity", + "family": "220", + "family_title": "Directional zero\u2013one laws and ballisticity in random environments", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.DirectionalTransience.directional_transience_implies_ballisticity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 513, + "bytes": 5012403, + "packages": [], + "grade_timeout_sec": 15311, + "oracle_result": "accepted", + "oracle_grade_seconds": 1730 + }, + { + "task": "directional-walk", + "challenge": "DirectionalWalk", + "family": "220", + "family_title": "Directional zero\u2013one laws and ballisticity in random environments", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.DirectionalZeroOne.directional_zero_one" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 69, + "bytes": 951618, + "packages": [], + "grade_timeout_sec": 11656, + "oracle_result": "accepted", + "oracle_grade_seconds": 968 + }, + { + "task": "discrete-lipschitz-free", + "challenge": "DiscreteLipschitzFree", + "family": "330", + "family_title": "A negative answer to Kalton's Lipschitz-free approximation question", + "subject": "Functional analysis", + "theorems": [ + "OAI.DiscreteFree.source_endpoints" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 32, + "bytes": 173635, + "packages": [], + "grade_timeout_sec": 10956, + "oracle_result": "accepted", + "oracle_grade_seconds": 662 + }, + { + "task": "disk-maximal", + "challenge": "DiskMaximal", + "family": "085", + "family_title": "Endpoint regularity of the planar centered maximal function", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.CenteredDiskEndpoint.main_endpoint" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 30, + "bytes": 970308, + "packages": [], + "grade_timeout_sec": 11673, + "oracle_result": "accepted", + "oracle_grade_seconds": 756 + }, + { + "task": "dixmier", + "challenge": "Dixmier", + "family": "251", + "family_title": "Amenability, unitarizability, and Ulam stability", + "subject": "Group theory", + "theorems": [ + "OAI.Dixmier.main_theorem_all_universes" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 32, + "bytes": 158919, + "packages": [], + "grade_timeout_sec": 10943, + "oracle_result": "accepted", + "oracle_grade_seconds": 332 + }, + { + "task": "dixmier-all-discrete", + "challenge": "DixmierAllDiscrete", + "family": "251", + "family_title": "Amenability, unitarizability, and Ulam stability", + "subject": "Group theory", + "theorems": [ + "OAI.Dixmier.current_main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 39, + "bytes": 181502, + "packages": [], + "grade_timeout_sec": 10963, + "oracle_result": "accepted", + "oracle_grade_seconds": 471 + }, + { + "task": "doubling-hilbert", + "challenge": "DoublingHilbert", + "family": "098", + "family_title": "A negative answer to the Lang\u2013Plaut problem", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.DoublingHilbert.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 12, + "bytes": 157722, + "packages": [], + "grade_timeout_sec": 10941, + "oracle_result": "accepted", + "oracle_grade_seconds": 454 + }, + { + "task": "dutta-domain", + "challenge": "DuttaDomain", + "family": "194", + "family_title": "Lech's multiplicity conjecture", + "subject": "Algebra", + "theorems": [ + "OAI.Lech.dutta_domain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 278, + "bytes": 2409516, + "packages": [], + "grade_timeout_sec": 12968, + "oracle_result": "accepted", + "oracle_grade_seconds": 1913 + }, + { + "task": "dyadic-avoidance", + "challenge": "DyadicAvoidance", + "family": "084", + "family_title": "The geometric case of the Erd\\H{o}s similarity conjecture", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.Problem310.dyadic_affine_avoidance" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 75, + "bytes": 369234, + "packages": [], + "grade_timeout_sec": 11132, + "oracle_result": "accepted", + "oracle_grade_seconds": 796 + }, + { + "task": "edit-approximation", + "challenge": "EditApproximation", + "family": "121", + "family_title": "Almost-linear expected-time approximation of edit distance", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.EditApproximation.almostLinearEditDistanceRawBand" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1024, + "bytes": 7591774, + "packages": [], + "grade_timeout_sec": 17632, + "oracle_result": "accepted", + "oracle_grade_seconds": 3183 + }, + { + "task": "edit-distance", + "challenge": "EditDistance", + "family": "099", + "family_title": "The sharp distortion of edit distance into $\\ell_1$", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.edit_distance_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 46, + "bytes": 1686015, + "packages": [], + "grade_timeout_sec": 12317, + "oracle_result": "accepted", + "oracle_grade_seconds": 1069 + }, + { + "task": "egyptian-fractions", + "challenge": "EgyptianFractions", + "family": "025", + "family_title": "Erd\\H{o}s\u2019s short Egyptian-fraction conjecture", + "subject": "Number theory", + "theorems": [ + "OAI.Problem337.egyptian_length_is_minimum", + "OAI.Problem337.main_double_log_order", + "OAI.Problem337.one_expansions_finite_and_bounded", + "OAI.Problem337.counting_double_log_order", + "OAI.Problem337.exact_marker_padding", + "OAI.Problem337.every_exact_marker_occurs", + "OAI.Problem337.quantitative_marked_length", + "OAI.Problem337.missing_denominator_semantics", + "OAI.Problem337.prescribed_denominator_corollary" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 290, + "bytes": 1625178, + "packages": [], + "grade_timeout_sec": 12262, + "oracle_result": "accepted", + "oracle_grade_seconds": 763 + }, + { + "task": "eilenberg-ganea", + "challenge": "EilenbergGanea", + "family": "249", + "family_title": "A finitely generated counterexample to Eilenberg\u2013Ganea", + "subject": "Group theory", + "theorems": [ + "OAI.EilenbergGanea.source_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 40, + "bytes": 1718355, + "packages": [], + "grade_timeout_sec": 12346, + "oracle_result": "accepted", + "oracle_grade_seconds": 4559 + }, + { + "task": "elasticity-uniqueness", + "challenge": "ElasticityUniqueness", + "family": "372", + "family_title": "Global uniqueness in smooth isotropic elasticity", + "subject": "Partial differential equations", + "theorems": [ + "OAI.Elasticity.global_uniqueness" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 42, + "bytes": 1608239, + "packages": [], + "grade_timeout_sec": 12247, + "oracle_result": "accepted", + "oracle_grade_seconds": 1681 + }, + { + "task": "elementary-positivity", + "challenge": "ElementaryPositivity", + "family": "169", + "family_title": "The Shareshian\u2013Wachs $e$-positivity conjecture", + "subject": "Combinatorics", + "theorems": [], + "definition_holes": [ + "OAI.elementaryPositivityWitness" + ], + "fixed_definitions": [], + "n_modules": 549, + "bytes": 3473360, + "packages": [], + "grade_timeout_sec": 13926, + "oracle_result": "accepted", + "oracle_grade_seconds": 2371 + }, + { + "task": "entangled-games", + "challenge": "EntangledGames", + "family": "277", + "family_title": "Threshold repetition for entangled games", + "subject": "Mathematical physics", + "theorems": [ + "OAI.ThresholdParallelRepetition.threshold_parallel_repetition" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 30, + "bytes": 354352, + "packages": [], + "grade_timeout_sec": 11118, + "oracle_result": "accepted", + "oracle_grade_seconds": 786 + }, + { + "task": "entropy-photon-number", + "challenge": "EntropyPhotonNumber", + "family": "273", + "family_title": "The entropy photon-number inequality", + "subject": "Mathematical physics", + "theorems": [ + "OAI.EntropyPhotonNumber.entropy_photon_number_inequality" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 26, + "bytes": 1401086, + "packages": [], + "grade_timeout_sec": 12060, + "oracle_result": "accepted", + "oracle_grade_seconds": 998 + }, + { + "task": "euclidean-five-color", + "challenge": "EuclideanFiveColor", + "family": "158", + "family_title": "The Euclidean plane cannot be colored with five colors", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanFiveColor.no_proper_five_coloring" + ], + "definition_holes": [], + "fixed_definitions": [ + "OAI.EuclideanFiveColor.ProperColoring" + ], + "n_modules": 70, + "bytes": 1548431, + "packages": [], + "grade_timeout_sec": 12193, + "oracle_result": "accepted", + "oracle_grade_seconds": 1407 + }, + { + "task": "euclidean-ramsey", + "challenge": "EuclideanRamsey", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.classification" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 288245, + "packages": [], + "grade_timeout_sec": 11059, + "oracle_result": "accepted", + "oracle_grade_seconds": 1062 + }, + { + "task": "euclidean-ramsey-circle", + "challenge": "EuclideanRamseyCircle", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.CircleConsequence.at_most_five_circle_points_ramsey" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 318701, + "packages": [], + "grade_timeout_sec": 11086, + "oracle_result": "accepted", + "oracle_grade_seconds": 883 + }, + { + "task": "euclidean-ramsey-nine", + "challenge": "EuclideanRamseyNine", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.NineStatement.nine_circle_configuration" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 16, + "bytes": 77180, + "packages": [], + "grade_timeout_sec": 10869, + "oracle_result": "accepted", + "oracle_grade_seconds": 600 + }, + { + "task": "euclidean-ramsey-quadratic", + "challenge": "EuclideanRamseyQuadratic", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.spherical_quadraticIndependent_ramsey_all" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 29, + "bytes": 299442, + "packages": [], + "grade_timeout_sec": 11069, + "oracle_result": "accepted", + "oracle_grade_seconds": 672 + }, + { + "task": "euclidean-ramsey-spherical", + "challenge": "EuclideanRamseySpherical", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.ramsey_cospherical" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 294907, + "packages": [], + "grade_timeout_sec": 11065, + "oracle_result": "accepted", + "oracle_grade_seconds": 735 + }, + { + "task": "euclidean-ramsey-transitive", + "challenge": "EuclideanRamseyTransitive", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.EuclideanRamsey.TransitiveConsequence.subset_of_finite_transitive_ramsey" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 29, + "bytes": 294470, + "packages": [], + "grade_timeout_sec": 11065, + "oracle_result": "accepted", + "oracle_grade_seconds": 1235 + }, + { + "task": "even-barker", + "challenge": "EvenBarker", + "family": "179", + "family_title": "The circulant Hadamard conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.CirculantHadamard.Barker.even_length_eq_two_or_four" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 73, + "bytes": 410340, + "packages": [], + "grade_timeout_sec": 11169, + "oracle_result": "accepted", + "oracle_grade_seconds": 743 + }, + { + "task": "exact-fourier", + "challenge": "ExactFourier", + "family": "130", + "family_title": "Fourier transforms below $n\\log n$", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.ExactFourier.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 848415, + "packages": [], + "grade_timeout_sec": 11563, + "oracle_result": "accepted", + "oracle_grade_seconds": 765 + }, + { + "task": "exact-infiniteness", + "challenge": "ExactInfiniteness", + "family": "303", + "family_title": "From ordinary to strong pure infiniteness", + "subject": "Operator algebras", + "theorems": [ + "OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any", + "OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_stronglyPurelyInfinite" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1012, + "bytes": 6724441, + "packages": [], + "grade_timeout_sec": 16851, + "oracle_result": "accepted", + "oracle_grade_seconds": 4206 + }, + { + "task": "exact-quantum-factoring", + "challenge": "ExactQuantumFactoring", + "family": "279", + "family_title": "Exact quantum factoring over a fixed finite gate set", + "subject": "Mathematical physics", + "theorems": [ + "OAI.ExactQuantumFactoring.exact_quantum_factoring" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 546, + "bytes": 2420616, + "packages": [], + "grade_timeout_sec": 12978, + "oracle_result": "accepted", + "oracle_grade_seconds": 1227 + }, + { + "task": "fkcrt", + "challenge": "FKCRT", + "family": "211", + "family_title": "Geometry, diffusion, and spectra of random planar maps", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.FKCRT.finite_fk_maps_converge_to_brownian_crt" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 61, + "bytes": 1877777, + "packages": [], + "grade_timeout_sec": 12489, + "oracle_result": "accepted", + "oracle_grade_seconds": 1071 + }, + { + "task": "factor-generation", + "challenge": "FactorGeneration", + "family": "296", + "family_title": "The generator problem for finite factors", + "subject": "Operator algebras", + "theorems": [ + "OAI.Generator.single_generation_of_II1_separable_predual" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 93, + "bytes": 1679659, + "packages": [], + "grade_timeout_sec": 12311, + "oracle_result": "accepted", + "oracle_grade_seconds": 3699 + }, + { + "task": "falconer-all-dimensions", + "challenge": "FalconerAllDimensions", + "family": "073", + "family_title": "The Falconer distance conjecture", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.Falconer.falconer_distance_conjecture" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 2384, + "bytes": 8957826, + "packages": [], + "grade_timeout_sec": 18862, + "oracle_result": "accepted", + "oracle_grade_seconds": 4645 + }, + { + "task": "filling-coefficient", + "challenge": "FillingCoefficient", + "family": "337", + "family_title": "Cartan\u2013Hadamard isoperimetry and CAT$(0)$ fillings", + "subject": "Differential geometry", + "theorems": [ + "OAI.SharpIntegralFillings.coefficient_optimal" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 112, + "bytes": 696670, + "packages": [], + "grade_timeout_sec": 11427, + "oracle_result": "accepted", + "oracle_grade_seconds": 1115 + }, + { + "task": "finite-circle", + "challenge": "FiniteCircle", + "family": "099", + "family_title": "The sharp distortion of edit distance into $\\ell_1$", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.finiteCircle_fullMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 36, + "bytes": 458380, + "packages": [], + "grade_timeout_sec": 11212, + "oracle_result": "accepted", + "oracle_grade_seconds": 902 + }, + { + "task": "finite-congruence-graph", + "challenge": "FiniteCongruenceGraph", + "family": "206", + "family_title": "Finite lattice representation: counterexamples and undecidability", + "subject": "Algebra", + "theorems": [ + "OAI.FiniteCongruence.graph_criterion" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 2, + "bytes": 22706, + "packages": [], + "grade_timeout_sec": 10820, + "oracle_result": "accepted", + "oracle_grade_seconds": 466 + }, + { + "task": "finite-entropy-separation", + "challenge": "FiniteEntropySeparation", + "family": "298", + "family_title": "A counterexample to Voiculescu\u2019s free-entropy equality conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.FiniteEntropySeparation.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 153, + "bytes": 786027, + "packages": [], + "grade_timeout_sec": 11507, + "oracle_result": "accepted", + "oracle_grade_seconds": 1422 + }, + { + "task": "finite-factor", + "challenge": "FiniteFactor", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.FiniteFactor.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 271, + "bytes": 1113695, + "packages": [], + "grade_timeout_sec": 11802, + "oracle_result": "accepted", + "oracle_grade_seconds": 1338 + }, + { + "task": "finitistic-asymmetry", + "challenge": "FinitisticAsymmetry", + "family": "198", + "family_title": "A counterexample to the little finitistic-dimension conjecture", + "subject": "Algebra", + "theorems": [ + "OAI.LittleFinitistic.extreme_left_right_asymmetry" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 588, + "bytes": 2251227, + "packages": [], + "grade_timeout_sec": 12826, + "oracle_result": "accepted", + "oracle_grade_seconds": 2003 + }, + { + "task": "fixed-clause-threshold", + "challenge": "FixedClauseThreshold", + "family": "235", + "family_title": "Random-SAT thresholds, sharp variance and computability", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.FixedClauseThreshold.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 215586, + "packages": [], + "grade_timeout_sec": 10994, + "oracle_result": "accepted", + "oracle_grade_seconds": 655 + }, + { + "task": "forced-navier-stokes-computation", + "challenge": "ForcedNavierStokesComputation", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.BalancedTransport.balanced_three_stack_realization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 60, + "bytes": 495983, + "packages": [], + "grade_timeout_sec": 11246, + "oracle_result": "accepted", + "oracle_grade_seconds": 547 + }, + { + "task": "forest-space", + "challenge": "ForestSpace", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.ForestSpace.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 20, + "bytes": 195404, + "packages": [], + "grade_timeout_sec": 10975, + "oracle_result": "accepted", + "oracle_grade_seconds": 741 + }, + { + "task": "formula-hitting", + "challenge": "FormulaHitting", + "family": "116", + "family_title": "Uniform identity testing for noncommutative formulas", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.NCHitting.universal_hitting" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 24, + "bytes": 123728, + "packages": [], + "grade_timeout_sec": 10911, + "oracle_result": "accepted", + "oracle_grade_seconds": 637 + }, + { + "task": "foulkes-howe", + "challenge": "FoulkesHowe", + "family": "210", + "family_title": "Foulkes\u2019 conjecture for sixth powers and quadratic stabilization", + "subject": "Algebra", + "theorems": [ + "OAI.Problem346.canonical_foulkes_howe_surjective" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 63, + "bytes": 197207, + "packages": [], + "grade_timeout_sec": 10977, + "oracle_result": "accepted", + "oracle_grade_seconds": 1045 + }, + { + "task": "four-row-permanent", + "challenge": "FourRowPermanent", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.FourRow.robust_permanent" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 5, + "bytes": 24646, + "packages": [], + "grade_timeout_sec": 10822, + "oracle_result": "accepted", + "oracle_grade_seconds": 788 + }, + { + "task": "free-ising", + "challenge": "FreeIsing", + "family": "236", + "family_title": "The factor-of-IID threshold for free Ising states on trees", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Problem367.free_ising_factor_iff_threshold" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 891, + "bytes": 5530584, + "packages": [], + "grade_timeout_sec": 15777, + "oracle_result": "accepted", + "oracle_grade_seconds": 2215 + }, + { + "task": "free-uniform-spanning-forest", + "challenge": "FreeUniformSpanningForest", + "family": "231", + "family_title": "The free uniform spanning forest is a factor of IID", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Problem336.fusf_is_factor_iid" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 224, + "bytes": 1069516, + "packages": [], + "grade_timeout_sec": 11762, + "oracle_result": "accepted", + "oracle_grade_seconds": 1286 + }, + { + "task": "gamma-passage", + "challenge": "GammaPassage", + "family": "212", + "family_title": "No bigeodesics and smooth limit shapes in planar first-passage percolation", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.GammaFPP.gamma_differentiability" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 203, + "bytes": 947238, + "packages": [], + "grade_timeout_sec": 11652, + "oracle_result": "accepted", + "oracle_grade_seconds": 800 + }, + { + "task": "gaussian-finite-entropy", + "challenge": "GaussianFiniteEntropy", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.RepeatedLocalization.FiniteEntropy.finite_expected_regularization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 116875, + "packages": [], + "grade_timeout_sec": 10905, + "oracle_result": "accepted", + "oracle_grade_seconds": 870 + }, + { + "task": "gaussian-information", + "challenge": "GaussianInformation", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.RepeatedLocalization.repeated_localization", + "OAI.AllScaleInverseVolume.inverse_volume_without_support", + "OAI.KernelPotential.kernel_coercivity", + "OAI.KernelPotential.actual_row_drift" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 111, + "bytes": 782263, + "packages": [], + "grade_timeout_sec": 11504, + "oracle_result": "accepted", + "oracle_grade_seconds": 1216 + }, + { + "task": "gaussian-moat", + "challenge": "GaussianMoat", + "family": "028", + "family_title": "The Gaussian moat conjecture", + "subject": "Number theory", + "theorems": [ + "OAI.GaussianMoat.fullMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 41, + "bytes": 598190, + "packages": [], + "grade_timeout_sec": 11338, + "oracle_result": "accepted", + "oracle_grade_seconds": 1157 + }, + { + "task": "gaussian-propeller", + "challenge": "GaussianPropeller", + "family": "096", + "family_title": "The Gaussian propeller conjecture", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.GaussianPropeller.all_partitions" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 583488, + "packages": [], + "grade_timeout_sec": 11325, + "oracle_result": "accepted", + "oracle_grade_seconds": 1095 + }, + { + "task": "gaussian-replacement", + "challenge": "GaussianReplacement", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.CurrentProjection.mixedMomentMain", + "OAI.CurrentProjection.actualRowMain", + "OAI.CurrentProjection.actualRowRefinement", + "OAI.CurrentProjection.actualRowSourceMain", + "OAI.CurrentProjection.actualRowSourceRefinement", + "OAI.CurrentProjection.criticalComparisonMain", + "OAI.CurrentProjection.oneLevelComparisonMain", + "OAI.CurrentProjection.twoLabelComparisonMain", + "OAI.CurrentProjection.hybridBlockMain", + "OAI.CurrentProjection.fiberTwoPointMain", + "OAI.CurrentProjection.fiberBlockMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 760043, + "packages": [], + "grade_timeout_sec": 11484, + "oracle_result": "accepted", + "oracle_grade_seconds": 1104 + }, + { + "task": "general-mahler", + "challenge": "GeneralMahler", + "family": "087", + "family_title": "The Mahler conjectures and symplectic width", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.GeneralMahler.general_mahler" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 302, + "bytes": 2142572, + "packages": [], + "grade_timeout_sec": 12728, + "oracle_result": "accepted", + "oracle_grade_seconds": 5069 + }, + { + "task": "generalized-star-height", + "challenge": "GeneralizedStarHeight", + "family": "134", + "family_title": "Generalized star height at most three", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.GeneralizedStarHeight.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 37, + "bytes": 522626, + "packages": [], + "grade_timeout_sec": 11270, + "oracle_result": "accepted", + "oracle_grade_seconds": 852 + }, + { + "task": "gotsman-linial", + "challenge": "GotsmanLinial", + "family": "127", + "family_title": "The asymptotic Gotsman\u2013Linial conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.LeanBlast.GotsmanLinial.gotsmanLinialStatement" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 172016, + "packages": [], + "grade_timeout_sec": 10954, + "oracle_result": "accepted", + "oracle_grade_seconds": 728 + }, + { + "task": "graham-spherical", + "challenge": "GrahamSpherical", + "family": "172", + "family_title": "Classification of finite Euclidean Ramsey configurations", + "subject": "Combinatorics", + "theorems": [ + "OAI.GrahamSpherical.full_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 18, + "bytes": 38396, + "packages": [], + "grade_timeout_sec": 10834, + "oracle_result": "accepted", + "oracle_grade_seconds": 751 + }, + { + "task": "grothendieck-elementary-expansion", + "challenge": "GrothendieckElementaryExpansion", + "family": "312", + "family_title": "The Grothendieck homotopy hypothesis", + "subject": "Topology", + "theorems": [ + "OAI.Grothendieck.elementary_expansion" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 58, + "bytes": 580875, + "packages": [], + "grade_timeout_sec": 11322, + "oracle_result": "accepted", + "oracle_grade_seconds": 1113 + }, + { + "task": "group-ring-determinant", + "challenge": "GroupRingDeterminant", + "family": "197", + "family_title": "Nonsofic groups and group-ring counterexamples", + "subject": "Algebra", + "theorems": [ + "OAI.GroupRingDeterminant.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 155, + "bytes": 680917, + "packages": [], + "grade_timeout_sec": 11412, + "oracle_result": "accepted", + "oracle_grade_seconds": 1695 + }, + { + "task": "hadamard-cube-fiber", + "challenge": "HadamardCubeFiber", + "family": "266", + "family_title": "Exactly three mutually unbiased bases in dimension six", + "subject": "Mathematical physics", + "theorems": [ + "OAI.HadamardSix.rowRatio_cubeFiber_sum_zero" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 6, + "bytes": 39551, + "packages": [], + "grade_timeout_sec": 10835, + "oracle_result": "accepted", + "oracle_grade_seconds": 462 + }, + { + "task": "halving-lines", + "challenge": "HalvingLines", + "family": "183", + "family_title": "Power savings for planar halving lines and $k$-sets", + "subject": "Combinatorics", + "theorems": [ + "OAI.PlanarHalving.power_bounds" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 886978, + "packages": [], + "grade_timeout_sec": 11598, + "oracle_result": "accepted", + "oracle_grade_seconds": 894 + }, + { + "task": "hard-sphere", + "challenge": "HardSphere", + "family": "267", + "family_title": "Positive-temperature Bose\u2013Einstein condensation and quantum depletion", + "subject": "Mathematical physics", + "theorems": [ + "OAI.HardSphere.condensation_with_mixed" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 466, + "bytes": 3471981, + "packages": [], + "grade_timeout_sec": 13924, + "oracle_result": "accepted", + "oracle_grade_seconds": 1367 + }, + { + "task": "harmonic-artin", + "challenge": "HarmonicArtin", + "family": "254", + "family_title": "Classifying spaces and geometric obstructions for Artin groups", + "subject": "Group theory", + "theorems": [ + "OAI.HarmonicArtin.salvetti_cover_contractible" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 660, + "bytes": 2801461, + "packages": [], + "grade_timeout_sec": 13321, + "oracle_result": "accepted", + "oracle_grade_seconds": 1612 + }, + { + "task": "harmonic-growth", + "challenge": "HarmonicGrowth", + "family": "361", + "family_title": "Counterexamples to Yau's harmonic dimension bound", + "subject": "Differential geometry", + "theorems": [ + "OAI.HarmonicCounterexample.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 36, + "bytes": 1683568, + "packages": [], + "grade_timeout_sec": 12315, + "oracle_result": "accepted", + "oracle_grade_seconds": 1761 + }, + { + "task": "heilbronn-triangle", + "challenge": "HeilbronnTriangle", + "family": "191", + "family_title": "A power improvement in the Heilbronn triangle problem", + "subject": "Combinatorics", + "theorems": [ + "OAI.Problem355.heilbronn_power_lower_bound", + "OAI.Problem355.almost_n_minus_two_refuted" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 195, + "bytes": 1015459, + "packages": [], + "grade_timeout_sec": 11713, + "oracle_result": "accepted", + "oracle_grade_seconds": 1117 + }, + { + "task": "heisenberg", + "challenge": "Heisenberg", + "family": "271", + "family_title": "Bloch's law and spontaneous ferromagnetic order", + "subject": "Mathematical physics", + "theorems": [ + "OAI.Heisenberg.spontaneous_magnetization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 128, + "bytes": 1109282, + "packages": [], + "grade_timeout_sec": 11798, + "oracle_result": "accepted", + "oracle_grade_seconds": 1829 + }, + { + "task": "henon-emden", + "challenge": "HenonEmden", + "family": "370", + "family_title": "The subcritical Lane\u2013Emden and Henon\u2013Lane\u2013Emden conjectures", + "subject": "Partial differential equations", + "theorems": [ + "OAI.HenonLaneEmden.main_nonexistence" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 96, + "bytes": 645822, + "packages": [], + "grade_timeout_sec": 11381, + "oracle_result": "accepted", + "oracle_grade_seconds": 1094 + }, + { + "task": "hilbert-crouzeix", + "challenge": "HilbertCrouzeix", + "family": "325", + "family_title": "The complete Crouzeix conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.HilbertCrouzeix.numericalClosure_geometry", + "OAI.HilbertCrouzeix.exists_finite_compression", + "OAI.HilbertCrouzeix.rational_denominator_isUnit", + "OAI.HilbertCrouzeix.zeroConclusion" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 7, + "bytes": 36730, + "packages": [], + "grade_timeout_sec": 10833, + "oracle_result": "accepted", + "oracle_grade_seconds": 927 + }, + { + "task": "honeycomb-bridge-finiteness", + "challenge": "HoneycombBridgeFiniteness", + "family": "237", + "family_title": "The three-quarter diameter exponent for honeycomb walks", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.PolynomialVacuumBridge.Corridor.finite_bridge_sums" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 43, + "bytes": 322795, + "packages": [], + "grade_timeout_sec": 11090, + "oracle_result": "accepted", + "oracle_grade_seconds": 711 + }, + { + "task": "honeycomb-free-energy", + "challenge": "HoneycombFreeEnergy", + "family": "237", + "family_title": "The three-quarter diameter exponent for honeycomb walks", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.HoneycombForce.logPartition_tendsto" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1, + "bytes": 41826, + "packages": [], + "grade_timeout_sec": 10837, + "oracle_result": "accepted", + "oracle_grade_seconds": 812 + }, + { + "task": "hot-spots", + "challenge": "HotSpots", + "family": "369", + "family_title": "The hot spots conjecture for simply connected planar domains", + "subject": "Partial differential equations", + "theorems": [ + "OAI.StrictHotSpots.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 1382075, + "packages": [], + "grade_timeout_sec": 12043, + "oracle_result": "accepted", + "oracle_grade_seconds": 1437 + }, + { + "task": "hyperbolic-cones", + "challenge": "HyperbolicCones", + "family": "095", + "family_title": "Hyperbolicity cones without semidefinite lifts", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.Paper256.main_result" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 86, + "bytes": 217979, + "packages": [], + "grade_timeout_sec": 10996, + "oracle_result": "accepted", + "oracle_grade_seconds": 849 + }, + { + "task": "hyperbolic-obstruction", + "challenge": "HyperbolicObstruction", + "family": "257", + "family_title": "A hyperbolic group with no geometric CAT(0) action", + "subject": "Group theory", + "theorems": [ + "OAI.HyperbolicObstruction.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 417, + "bytes": 2430541, + "packages": [], + "grade_timeout_sec": 12987, + "oracle_result": "accepted", + "oracle_grade_seconds": 1194 + }, + { + "task": "hyperinvariant-subspaces", + "challenge": "HyperinvariantSubspaces", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.Hyperinvariant.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 277, + "bytes": 1129103, + "packages": [], + "grade_timeout_sec": 11816, + "oracle_result": "accepted", + "oracle_grade_seconds": 1437 + }, + { + "task": "independent-products", + "challenge": "IndependentProducts", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.IndependentProducts.main_general", + "OAI.IndependentProducts.main_exponential", + "OAI.IndependentProducts.main_gaussian_24", + "OAI.IndependentProducts.main_gaussian_12" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 178152, + "packages": [], + "grade_timeout_sec": 10960, + "oracle_result": "accepted", + "oracle_grade_seconds": 656 + }, + { + "task": "independent-sets", + "challenge": "IndependentSets", + "family": "106", + "family_title": "Hardness of coloring three-colorable graphs", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.LargeIndependentSets.mainTheoremReal" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 454, + "bytes": 4478613, + "packages": [], + "grade_timeout_sec": 14830, + "oracle_result": "accepted", + "oracle_grade_seconds": 1201 + }, + { + "task": "individual-strong-infiniteness", + "challenge": "IndividualStrongInfiniteness", + "family": "303", + "family_title": "From ordinary to strong pure infiniteness", + "subject": "Operator algebras", + "theorems": [ + "OAI.MainGap.Manuscript.individual_to_strong_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 25, + "bytes": 283030, + "packages": [], + "grade_timeout_sec": 11054, + "oracle_result": "accepted", + "oracle_grade_seconds": 965 + }, + { + "task": "infinite-matroid", + "challenge": "InfiniteMatroid", + "family": "185", + "family_title": "Counterexamples to infinite matroid intersection and packing/covering", + "subject": "Combinatorics", + "theorems": [ + "OAI.InfiniteMatroidCounterexample.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 25, + "bytes": 174500, + "packages": [], + "grade_timeout_sec": 10957, + "oracle_result": "accepted", + "oracle_grade_seconds": 667 + }, + { + "task": "infinite-matroid-corollaries", + "challenge": "InfiniteMatroidCorollaries", + "family": "185", + "family_title": "Counterexamples to infinite matroid intersection and packing/covering", + "subject": "Combinatorics", + "theorems": [ + "OAI.InfiniteMatroidCounterexample.partitional_intersection_counterexample", + "OAI.InfiniteMatroidCounterexample.separate_covering_packing_counterexamples" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 33, + "bytes": 193312, + "packages": [], + "grade_timeout_sec": 10973, + "oracle_result": "accepted", + "oracle_grade_seconds": 637 + }, + { + "task": "interpolated-factors", + "challenge": "InterpolatedFactors", + "family": "287", + "family_title": "All nonabelian free group factors are isomorphic", + "subject": "Operator algebras", + "theorems": [ + "OAI.FreeGroupFactorMain.Interpolation.allInterpolatedIsomorphic" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 77, + "bytes": 1249281, + "packages": [], + "grade_timeout_sec": 11924, + "oracle_result": "accepted", + "oracle_grade_seconds": 1971 + }, + { + "task": "irrational-rotation", + "challenge": "IrrationalRotation", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.Invariant233.Results.prescribed_irrational_counterexample", + "OAI.Invariant233.Results.product_realization" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 735, + "bytes": 3645017, + "packages": [], + "grade_timeout_sec": 14080, + "oracle_result": "accepted", + "oracle_grade_seconds": 1441 + }, + { + "task": "irrational-triangle-billiard", + "challenge": "IrrationalTriangleBilliard", + "family": "150", + "family_title": "Weak mixing of irrational triangular billiards", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.TriangularBilliards.irrational_triangle_billiard" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 39, + "bytes": 594085, + "packages": [], + "grade_timeout_sec": 11334, + "oracle_result": "accepted", + "oracle_grade_seconds": 820 + }, + { + "task": "ising-finiteness", + "challenge": "IsingFiniteness", + "family": "222", + "family_title": "Perceptron free energies and microscopic jamming", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.IsingPerceptron.variationalValue_real_of_continuous" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 45, + "bytes": 1494396, + "packages": [], + "grade_timeout_sec": 12144, + "oracle_result": "accepted", + "oracle_grade_seconds": 958 + }, + { + "task": "isometric-immersion", + "challenge": "IsometricImmersion", + "family": "334", + "family_title": "A smooth surface metric with no local immersion in $\\mathbb R^3$", + "subject": "Differential geometry", + "theorems": [ + "OAI.SmoothLocal.Geometry.exists_local_metric_without_local_immersion" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 446, + "bytes": 2824652, + "packages": [], + "grade_timeout_sec": 13342, + "oracle_result": "accepted", + "oracle_grade_seconds": 1242 + }, + { + "task": "kl-invariance", + "challenge": "KLInvariance", + "family": "168", + "family_title": "Combinatorial invariance of Kazhdan\u2013Lusztig polynomials", + "subject": "Combinatorics", + "theorems": [ + "OAI.KLInvariance.combinatorial_invariance" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 1831275, + "packages": [], + "grade_timeout_sec": 12448, + "oracle_result": "accepted", + "oracle_grade_seconds": 1717 + }, + { + "task": "k-median-recovery", + "challenge": "KMedianRecovery", + "family": "125", + "family_title": "The approximation threshold for metric $k$-median", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MetricKMedianRecovery.global_application" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 506, + "bytes": 3720803, + "packages": [], + "grade_timeout_sec": 14148, + "oracle_result": "accepted", + "oracle_grade_seconds": 1362 + }, + { + "task": "k-median-refined-recovery", + "challenge": "KMedianRefinedRecovery", + "family": "125", + "family_title": "The approximation threshold for metric $k$-median", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MetricKMedianRecovery.RefinedRecovery.refined_recovery" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 586, + "bytes": 2580016, + "packages": [], + "grade_timeout_sec": 13122, + "oracle_result": "accepted", + "oracle_grade_seconds": 1849 + }, + { + "task": "k-median-threshold", + "challenge": "KMedianThreshold", + "family": "125", + "family_title": "The approximation threshold for metric $k$-median", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MetricKMedian.threshold" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 765, + "bytes": 3236997, + "packages": [], + "grade_timeout_sec": 13713, + "oracle_result": "accepted", + "oracle_grade_seconds": 2259 + }, + { + "task": "k-server", + "challenge": "KServer", + "family": "110", + "family_title": "Optimal-order randomized $k$-server on arbitrary metrics", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.KServer.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [ + "OAI.KServer.Configuration", + "OAI.KServer.LabelDistribution", + "OAI.KServer.Policy", + "OAI.KServer.serve", + "OAI.KServer.serviceCost", + "OAI.KServer.pathProbability", + "OAI.KServer.expectedCost", + "OAI.KServer.optimalCost", + "OAI.KServer.MainStatement" + ], + "n_modules": 37, + "bytes": 1783312, + "packages": [], + "grade_timeout_sec": 12404, + "oracle_result": "accepted", + "oracle_grade_seconds": 587 + }, + { + "task": "kadison-ringrose", + "challenge": "KadisonRingrose", + "family": "295", + "family_title": "The Kadison\u2013Ringrose cohomology conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.BoundedHochschild.KadisonRingrose.main_result" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 372, + "bytes": 2793925, + "packages": [], + "grade_timeout_sec": 13314, + "oracle_result": "accepted", + "oracle_grade_seconds": 1352 + }, + { + "task": "kadison-similarity", + "challenge": "KadisonSimilarity", + "family": "288", + "family_title": "Kadison's similarity conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.KadisonSimilarity.universalCommutatorTheorem", + "OAI.KadisonSimilarity.universalHyperreflexivity", + "OAI.KadisonSimilarity.similarityTheorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 816, + "bytes": 5791602, + "packages": [], + "grade_timeout_sec": 16012, + "oracle_result": "accepted", + "oracle_grade_seconds": 3415 + }, + { + "task": "kahler-splitting", + "challenge": "KahlerSplitting", + "family": "052", + "family_title": "Tangent-bundle splittings and universal covers", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.UniversalCoverSplitting.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 46, + "bytes": 726796, + "packages": [], + "grade_timeout_sec": 11454, + "oracle_result": "accepted", + "oracle_grade_seconds": 1239 + }, + { + "task": "kaplansky-direct-finiteness", + "challenge": "KaplanskyDirectFiniteness", + "family": "197", + "family_title": "Nonsofic groups and group-ring counterexamples", + "subject": "Algebra", + "theorems": [ + "OAI.KaplanskyCounterexample.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 121, + "bytes": 544294, + "packages": [], + "grade_timeout_sec": 11289, + "oracle_result": "accepted", + "oracle_grade_seconds": 1170 + }, + { + "task": "kaplansky-finitely-presented", + "challenge": "KaplanskyFinitelyPresented", + "family": "197", + "family_title": "Nonsofic groups and group-ring counterexamples", + "subject": "Algebra", + "theorems": [ + "OAI.KaplanskyCounterexample.finitelyPresented_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 126, + "bytes": 556097, + "packages": [], + "grade_timeout_sec": 11300, + "oracle_result": "accepted", + "oracle_grade_seconds": 1470 + }, + { + "task": "kaplansky-quasitrace", + "challenge": "KaplanskyQuasitrace", + "family": "294", + "family_title": "A counterexample to Kaplansky's quasitrace conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.Kaplansky.kaplansky_quasitrace_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 123, + "bytes": 1501004, + "packages": [], + "grade_timeout_sec": 12150, + "oracle_result": "accepted", + "oracle_grade_seconds": 993 + }, + { + "task": "kaplansky-stable-finiteness", + "challenge": "KaplanskyStableFiniteness", + "family": "294", + "family_title": "A counterexample to Kaplansky's quasitrace conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.KaplanskyConsequences.stable_finiteness_bundle" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 181, + "bytes": 1739197, + "packages": [], + "grade_timeout_sec": 12365, + "oracle_result": "accepted", + "oracle_grade_seconds": 1007 + }, + { + "task": "kervaire", + "challenge": "Kervaire", + "family": "256", + "family_title": "Howie's conjecture on equations over groups", + "subject": "Group theory", + "theorems": [ + "OAI.Kervaire.coefficient_injective" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 508441, + "packages": [], + "grade_timeout_sec": 11257, + "oracle_result": "accepted", + "oracle_grade_seconds": 1057 + }, + { + "task": "laughlin", + "challenge": "Laughlin", + "family": "269", + "family_title": "The Laughlin gap and stability under scalar disorder", + "subject": "Mathematical physics", + "theorems": [ + "OAI.Laughlin.mainTarget_proved" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1258, + "bytes": 2971285, + "packages": [], + "grade_timeout_sec": 13474, + "oracle_result": "accepted", + "oracle_grade_seconds": 6718 + }, + { + "task": "laughlin-fock", + "challenge": "LaughlinFock", + "family": "269", + "family_title": "The Laughlin gap and stability under scalar disorder", + "subject": "Mathematical physics", + "theorems": [ + "OAI.LaughlinFock.thm_fock" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 293, + "bytes": 8419306, + "packages": [], + "grade_timeout_sec": 18377, + "oracle_result": "accepted", + "oracle_grade_seconds": 6546 + }, + { + "task": "laughlin-gap", + "challenge": "LaughlinGap", + "family": "269", + "family_title": "The Laughlin gap and stability under scalar disorder", + "subject": "Mathematical physics", + "theorems": [ + "OAI.LaughlinGap.thm_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 106, + "bytes": 2339387, + "packages": [], + "grade_timeout_sec": 12905, + "oracle_result": "accepted", + "oracle_grade_seconds": 5587 + }, + { + "task": "laughlin-planar", + "challenge": "LaughlinPlanar", + "family": "269", + "family_title": "The Laughlin gap and stability under scalar disorder", + "subject": "Mathematical physics", + "theorems": [ + "OAI.Laughlin.planar_gap" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1279, + "bytes": 3060235, + "packages": [], + "grade_timeout_sec": 13554, + "oracle_result": "accepted", + "oracle_grade_seconds": 7126 + }, + { + "task": "lieb-thirring", + "challenge": "LiebThirring", + "family": "262", + "family_title": "Sharp one-dimensional Lieb\u2013Thirring inequalities", + "subject": "Mathematical physics", + "theorems": [ + "OAI.SharpLiebThirring.sharp_lieb_thirring" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 38, + "bytes": 654331, + "packages": [], + "grade_timeout_sec": 11388, + "oracle_result": "accepted", + "oracle_grade_seconds": 1327 + }, + { + "task": "lipschitz-equivalence", + "challenge": "LipschitzEquivalence", + "family": "324", + "family_title": "Lipschitz equivalence without linear isomorphism", + "subject": "Functional analysis", + "theorems": [ + "OAI.LipschitzCounterexample.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 60, + "bytes": 475733, + "packages": [], + "grade_timeout_sec": 11228, + "oracle_result": "accepted", + "oracle_grade_seconds": 1251 + }, + { + "task": "lipschitz-hilbert", + "challenge": "LipschitzHilbert", + "family": "083", + "family_title": "Stein's conjecture for Hilbert transforms along Lipschitz directions", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.LipschitzHilbert.main", + "OAI.LipschitzHilbert.uniform_truncation" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1910, + "bytes": 9262948, + "packages": [], + "grade_timeout_sec": 19136, + "oracle_result": "accepted", + "oracle_grade_seconds": 2945 + }, + { + "task": "list-hadwiger", + "challenge": "ListHadwiger", + "family": "157", + "family_title": "Counterexamples to the Hadwiger and Colin de Verdiere conjectures", + "subject": "Combinatorics", + "theorems": [ + "OAI.LinearListHadwiger.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 53, + "bytes": 902720, + "packages": [], + "grade_timeout_sec": 11612, + "oracle_result": "accepted", + "oracle_grade_seconds": 715 + }, + { + "task": "little-finitistic", + "challenge": "LittleFinitistic", + "family": "198", + "family_title": "A counterexample to the little finitistic-dimension conjecture", + "subject": "Algebra", + "theorems": [ + "OAI.LittleFinitistic.Main.exists_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 546, + "bytes": 2050368, + "packages": [], + "grade_timeout_sec": 12645, + "oracle_result": "accepted", + "oracle_grade_seconds": 1694 + }, + { + "task": "littlewood-finite-flatness", + "challenge": "LittlewoodFiniteFlatness", + "family": "076", + "family_title": "Ultraflat real Littlewood polynomials", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.AsymptoticallyMinimalLittlewoodFiniteFlatness.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 449707, + "packages": [], + "grade_timeout_sec": 11204, + "oracle_result": "accepted", + "oracle_grade_seconds": 855 + }, + { + "task": "log-brunn-minkowski", + "challenge": "LogBrunnMinkowski", + "family": "091", + "family_title": "The logarithmic Brunn\u2013Minkowski conjecture", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.LogBrunnMinkowski.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1, + "bytes": 1228745, + "packages": [], + "grade_timeout_sec": 11905, + "oracle_result": "accepted", + "oracle_grade_seconds": 898 + }, + { + "task": "log-concave-query", + "challenge": "LogConcaveQuery", + "family": "139", + "family_title": "Subpolynomial queries for log-concave sampling", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.LogConcaveSampling.exact_source_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 326, + "bytes": 3000883, + "packages": [], + "grade_timeout_sec": 13500, + "oracle_result": "accepted", + "oracle_grade_seconds": 1278 + }, + { + "task": "log-kodaira-fiber-negative", + "challenge": "LogKodairaFiberNegative", + "family": "033", + "family_title": "Campana's orbifold Iitaka conjecture and logarithmic subadditivity", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.ReverseLogKodaira.SmoothProjectiveVariety.veryGenerally_fiber_negative_branch" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 14, + "bytes": 176794, + "packages": [], + "grade_timeout_sec": 10959, + "oracle_result": "accepted", + "oracle_grade_seconds": 813 + }, + { + "task": "mahler-conjecture", + "challenge": "MahlerConjecture", + "family": "087", + "family_title": "The Mahler conjectures and symplectic width", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.SymmetricMahler.symmetric_mahler" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 229, + "bytes": 995887, + "packages": [], + "grade_timeout_sec": 11696, + "oracle_result": "accepted", + "oracle_grade_seconds": 968 + }, + { + "task": "markov-type", + "challenge": "MarkovType", + "family": "327", + "family_title": "Markov type characterizes superreflexivity", + "subject": "Functional analysis", + "theorems": [ + "OAI.MarkovSuperreflexivity.hasNontrivialMarkovType_iff_hasEquivalentUCNorm" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 207, + "bytes": 1098511, + "packages": [], + "grade_timeout_sec": 11788, + "oracle_result": "accepted", + "oracle_grade_seconds": 926 + }, + { + "task": "mass-action", + "challenge": "MassAction", + "family": "149", + "family_title": "Permanence for weakly reversible reaction networks", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.Problem326.global_bounded_persistent_solution" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 71, + "bytes": 328720, + "packages": [], + "grade_timeout_sec": 11095, + "oracle_result": "accepted", + "oracle_grade_seconds": 751 + }, + { + "task": "matching-affine-lift", + "challenge": "MatchingAffineLift", + "family": "126", + "family_title": "Exponential semidefinite complexity of perfect matching", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PerfectMatchingPSD.affine_lift_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 66, + "bytes": 322172, + "packages": [], + "grade_timeout_sec": 11089, + "oracle_result": "accepted", + "oracle_grade_seconds": 905 + }, + { + "task": "matching-entropy", + "challenge": "MatchingEntropy", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatchingEntropy.entropy_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 18, + "bytes": 156848, + "packages": [], + "grade_timeout_sec": 10941, + "oracle_result": "accepted", + "oracle_grade_seconds": 607 + }, + { + "task": "matching-entropy-bounds", + "challenge": "MatchingEntropyBounds", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatchingEntropyBounds.Refined.pointwise_entropy" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 345956, + "packages": [], + "grade_timeout_sec": 11111, + "oracle_result": "accepted", + "oracle_grade_seconds": 808 + }, + { + "task": "matching-fpras", + "challenge": "MatchingFPRAS", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatchingFPRAS.thm_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 415, + "bytes": 3091883, + "packages": [], + "grade_timeout_sec": 13582, + "oracle_result": "accepted", + "oracle_grade_seconds": 1267 + }, + { + "task": "matching-psd", + "challenge": "MatchingPSD", + "family": "126", + "family_title": "Exponential semidefinite complexity of perfect matching", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PerfectMatchingPSD.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 53, + "bytes": 296495, + "packages": [], + "grade_timeout_sec": 11066, + "oracle_result": "accepted", + "oracle_grade_seconds": 855 + }, + { + "task": "matrix-fields", + "challenge": "MatrixFields", + "family": "107", + "family_title": "Matrix multiplication with exponent at most $9/4$", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatrixAllFields.MatrixMultiplication.AllFieldMain.omega_lt_source_constant" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 354, + "bytes": 12952806, + "packages": [], + "grade_timeout_sec": 21600, + "oracle_result": "accepted", + "oracle_grade_seconds": 4564 + }, + { + "task": "matrix-removal", + "challenge": "MatrixRemoval", + "family": "190", + "family_title": "Polynomial removal fails for ordered binary matrices", + "subject": "Combinatorics", + "theorems": [ + "OAI.Problem348.no_polynomial_removal_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 61, + "bytes": 322573, + "packages": [], + "grade_timeout_sec": 11090, + "oracle_result": "accepted", + "oracle_grade_seconds": 710 + }, + { + "task": "matroid-prophet", + "challenge": "MatroidProphet", + "family": "111", + "family_title": "One-sample matroid prophet inequalities against an almighty adversary", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatroidProphet.one_sample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 125, + "bytes": 666444, + "packages": [], + "grade_timeout_sec": 11399, + "oracle_result": "accepted", + "oracle_grade_seconds": 745 + }, + { + "task": "matroid-secretary", + "challenge": "MatroidSecretary", + "family": "111", + "family_title": "One-sample matroid prophet inequalities against an almighty adversary", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MatroidProphet.Assigned.one_sample", + "OAI.MatroidProphet.Assigned.hidden_vector", + "OAI.MatroidProphet.Assigned.secretary" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 243, + "bytes": 1175443, + "packages": [], + "grade_timeout_sec": 11857, + "oracle_result": "accepted", + "oracle_grade_seconds": 973 + }, + { + "task": "maximal-seshadri-constants", + "challenge": "MaximalSeshadriConstants", + "family": "039", + "family_title": "Nagata's conjecture and maximal Seshadri constants", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.MaximalSeshadri.Geometry.maximalSeshadriConstants" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 421, + "bytes": 2494022, + "packages": [], + "grade_timeout_sec": 13044, + "oracle_result": "accepted", + "oracle_grade_seconds": 2446 + }, + { + "task": "memory-precision", + "challenge": "MemoryPrecision", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MemoryPrecision.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 88, + "bytes": 780345, + "packages": [], + "grade_timeout_sec": 11502, + "oracle_result": "accepted", + "oracle_grade_seconds": 957 + }, + { + "task": "metric-entropy-duality", + "challenge": "MetricEntropyDuality", + "family": "329", + "family_title": "A counterexample to Pietsch's metric-entropy duality conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.MetricEntropyDuality.exists_entropy_duality_counterexample_with_covers" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 52, + "bytes": 267910, + "packages": [], + "grade_timeout_sec": 11041, + "oracle_result": "accepted", + "oracle_grade_seconds": 557 + }, + { + "task": "metric-k-median", + "challenge": "MetricKMedian", + "family": "125", + "family_title": "The approximation threshold for metric $k$-median", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MetricKMedian.main_finite_work" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 569, + "bytes": 2480461, + "packages": [], + "grade_timeout_sec": 13032, + "oracle_result": "accepted", + "oracle_grade_seconds": 1451 + }, + { + "task": "midpoint-lenses", + "challenge": "MidpointLenses", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.SegmentLenses.midpoint_lens_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 11, + "bytes": 129714, + "packages": [], + "grade_timeout_sec": 10916, + "oracle_result": "accepted", + "oracle_grade_seconds": 634 + }, + { + "task": "min-uncut", + "challenge": "MinUncut", + "family": "102", + "family_title": "The Unique Games Conjecture and optimal approximation thresholds", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.MinUncut.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 375, + "bytes": 5995678, + "packages": [], + "grade_timeout_sec": 16196, + "oracle_result": "accepted", + "oracle_grade_seconds": 1335 + }, + { + "task": "nagata", + "challenge": "Nagata", + "family": "039", + "family_title": "Nagata's conjecture and maximal Seshadri constants", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.Nagata.Workers.W30.exists_positive_degree_equation_of_homogeneous_cycle", + "OAI.Nagata.nagata_conjecture", + "OAI.Nagata.nagata_conjecture_coordinates" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 117, + "bytes": 1609242, + "packages": [], + "grade_timeout_sec": 12248, + "oracle_result": "accepted", + "oracle_grade_seconds": 505 + }, + { + "task": "naimark", + "challenge": "Naimark", + "family": "297", + "family_title": "A ZFC counterexample to Naimark's problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.NaimarkZFC.main" + ], + "definition_holes": [], + "fixed_definitions": [ + "OAI.NaimarkZFC.IsSimpleCStar", + "OAI.NaimarkZFC.IsState", + "OAI.NaimarkZFC.IsFaithfulTracialState", + "OAI.NaimarkZFC.IsIrreducible", + "OAI.NaimarkZFC.UnitarilyEquivalent", + "OAI.NaimarkZFC.HasUniqueIrreducibleRepresentation", + "OAI.NaimarkZFC.IsIsomorphicToCompacts" + ], + "n_modules": 16, + "bytes": 1208784, + "packages": [], + "grade_timeout_sec": 11887, + "oracle_result": "accepted", + "oracle_grade_seconds": 2857 + }, + { + "task": "navier-stokes-alternating", + "challenge": "NavierStokesAlternating", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.AlternatingNS.alternating" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 41, + "bytes": 385862, + "packages": [], + "grade_timeout_sec": 11147, + "oracle_result": "accepted", + "oracle_grade_seconds": 874 + }, + { + "task": "navier-stokes-velocity", + "challenge": "NavierStokesVelocity", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.VelocityDetection.main_result" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 152, + "bytes": 1031916, + "packages": [], + "grade_timeout_sec": 11728, + "oracle_result": "accepted", + "oracle_grade_seconds": 1274 + }, + { + "task": "nodal-length", + "challenge": "NodalLength", + "family": "350", + "family_title": "Yau's nodal conjecture: surfaces and counterexamples", + "subject": "Differential geometry", + "theorems": [ + "OAI.SharpNodal.Main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 59, + "bytes": 1484359, + "packages": [], + "grade_timeout_sec": 12135, + "oracle_result": "accepted", + "oracle_grade_seconds": 1261 + }, + { + "task": "noiseless-regression", + "challenge": "NoiselessRegression", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.NoiselessRegression.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 200854, + "packages": [], + "grade_timeout_sec": 10980, + "oracle_result": "accepted", + "oracle_grade_seconds": 758 + }, + { + "task": "odd-kaplansky", + "challenge": "OddKaplansky", + "family": "197", + "family_title": "Nonsofic groups and group-ring counterexamples", + "subject": "Algebra", + "theorems": [ + "OAI.OddKaplansky.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 138, + "bytes": 832311, + "packages": [], + "grade_timeout_sec": 11549, + "oracle_result": "accepted", + "oracle_grade_seconds": 1336 + }, + { + "task": "one-way-liveness", + "challenge": "OneWayLiveness", + "family": "129", + "family_title": "Exponential state costs for two-way automata", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.OneWayLiveness.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 16, + "bytes": 172519, + "packages": [], + "grade_timeout_sec": 10955, + "oracle_result": "accepted", + "oracle_grade_seconds": 624 + }, + { + "task": "optimal-max-cut", + "challenge": "OptimalMaxCut", + "family": "102", + "family_title": "The Unique Games Conjecture and optimal approximation thresholds", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.OptimalMaxCut.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 372, + "bytes": 8863088, + "packages": [], + "grade_timeout_sec": 18776, + "oracle_result": "accepted", + "oracle_grade_seconds": 1488 + }, + { + "task": "ordinary-elliott", + "challenge": "OrdinaryElliott", + "family": "007", + "family_title": "Two-point Chowla and the corrected binary Elliott conjecture", + "subject": "Number theory", + "theorems": [ + "OAI.OrdinaryCorrelations.binary_corrected_elliott" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 628, + "bytes": 3068303, + "packages": [], + "grade_timeout_sec": 13561, + "oracle_result": "accepted", + "oracle_grade_seconds": 1590 + }, + { + "task": "parity-lifts", + "challenge": "ParityLifts", + "family": "133", + "family_title": "The complexity of Weisfeiler\u2013Leman refinement", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.ParityWL.parity_reduction" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 181099, + "packages": [], + "grade_timeout_sec": 10962, + "oracle_result": "accepted", + "oracle_grade_seconds": 839 + }, + { + "task": "partial-permutation", + "challenge": "PartialPermutation", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.PartialPermutation.complementaryCosets_finite" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 62, + "bytes": 245598, + "packages": [], + "grade_timeout_sec": 11021, + "oracle_result": "accepted", + "oracle_grade_seconds": 802 + }, + { + "task": "partition-consistency", + "challenge": "PartitionConsistency", + "family": "244", + "family_title": "The partition principle does not imply choice", + "subject": "Mathematical logic", + "theorems": [ + "OAI.PartitionConsistency.main_consistency" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 75, + "bytes": 1501215, + "packages": [], + "grade_timeout_sec": 12151, + "oracle_result": "accepted", + "oracle_grade_seconds": 823 + }, + { + "task": "partition-principle", + "challenge": "PartitionPrinciple", + "family": "244", + "family_title": "The partition principle does not imply choice", + "subject": "Mathematical logic", + "theorems": [ + "OAI.PartitionPilot.Forcing.TransitiveGround.exists_model_partitionPrinciple_without_choice" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 943, + "bytes": 12843154, + "packages": [], + "grade_timeout_sec": 21600, + "oracle_result": "accepted", + "oracle_grade_seconds": 2843 + }, + { + "task": "perceptron-free-energy", + "challenge": "PerceptronFreeEnergy", + "family": "222", + "family_title": "Perceptron free energies and microscopic jamming", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.SphericalPerceptronFreeEnergy.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 411, + "bytes": 3856745, + "packages": [], + "grade_timeout_sec": 14271, + "oracle_result": "accepted", + "oracle_grade_seconds": 1268 + }, + { + "task": "perfect-completeness", + "challenge": "PerfectCompleteness", + "family": "105", + "family_title": "The 2-to-1 Games Conjecture with perfect completeness", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PerfectCompleteness.Theorem11.exists_reduction" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 863, + "bytes": 12353482, + "packages": [], + "grade_timeout_sec": 21600, + "oracle_result": "accepted", + "oracle_grade_seconds": 2380 + }, + { + "task": "periodic-group", + "challenge": "PeriodicGroup", + "family": "247", + "family_title": "An infinite finitely presented residually finite $2$-group", + "subject": "Group theory", + "theorems": [ + "OAI.SourceBurnside.thm_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 63, + "bytes": 1797133, + "packages": [], + "grade_timeout_sec": 12417, + "oracle_result": "accepted", + "oracle_grade_seconds": 1008 + }, + { + "task": "periodic-tiling-three", + "challenge": "PeriodicTilingThree", + "family": "155", + "family_title": "A counterexample to periodic tiling in dimension three", + "subject": "Combinatorics", + "theorems": [ + "OAI.PeriodicTilingThree.periodic_tiling_counterexample_and_minimality" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 122, + "bytes": 661551, + "packages": [], + "grade_timeout_sec": 11395, + "oracle_result": "accepted", + "oracle_grade_seconds": 928 + }, + { + "task": "permanent-cubic", + "challenge": "PermanentCubic", + "family": "108", + "family_title": "A cubic permanent\u2013determinant lower bound", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PermanentBorder.permanent_cubic_lower_bounds" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 915904, + "packages": [], + "grade_timeout_sec": 11624, + "oracle_result": "accepted", + "oracle_grade_seconds": 1031 + }, + { + "task": "petty-projection-volume", + "challenge": "PettyProjectionVolume", + "family": "088", + "family_title": "Petty's projection-volume conjecture and simplex counterexamples", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.PettyProjection.petty_projection_volume" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 33, + "bytes": 662308, + "packages": [], + "grade_timeout_sec": 11396, + "oracle_result": "accepted", + "oracle_grade_seconds": 979 + }, + { + "task": "pi-exponent", + "challenge": "PiExponent", + "family": "017", + "family_title": "The irrationality exponent of $\\pi$ is $2$", + "subject": "Number theory", + "theorems": [ + "OAI.PiExponent.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 869, + "bytes": 4321464, + "packages": [], + "grade_timeout_sec": 14689, + "oracle_result": "accepted", + "oracle_grade_seconds": 2882 + }, + { + "task": "pinched-kahler", + "challenge": "PinchedKahler", + "family": "359", + "family_title": "Negative Kahler curvature without bounded holomorphic coordinates", + "subject": "Differential geometry", + "theorems": [ + "OAI.PinchedHartogs.main_theorem", + "OAI.PinchedHartogs.controlled_potential", + "OAI.PinchedHartogs.metric_transfer" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 119, + "bytes": 921746, + "packages": [], + "grade_timeout_sec": 11629, + "oracle_result": "accepted", + "oracle_grade_seconds": 1351 + }, + { + "task": "pinned-distances", + "challenge": "PinnedDistances", + "family": "167", + "family_title": "Pinned distances and a power saving for planar unit distances", + "subject": "Combinatorics", + "theorems": [ + "OAI.WeakPinned.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 739601, + "packages": [], + "grade_timeout_sec": 11465, + "oracle_result": "accepted", + "oracle_grade_seconds": 926 + }, + { + "task": "planar-anderson-spectrum", + "challenge": "PlanarAndersonSpectrum", + "family": "261", + "family_title": "Localization and delocalization in the Anderson model", + "subject": "Mathematical physics", + "theorems": [ + "OAI.PlanarAnderson.anderson_spectrum_ae" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1, + "bytes": 35165, + "packages": [], + "grade_timeout_sec": 10831, + "oracle_result": "accepted", + "oracle_grade_seconds": 582 + }, + { + "task": "planar-falconer", + "challenge": "PlanarFalconer", + "family": "073", + "family_title": "The Falconer distance conjecture", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.PlanarFalconer.mainTarget_proved" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 719, + "bytes": 2640523, + "packages": [], + "grade_timeout_sec": 13176, + "oracle_result": "accepted", + "oracle_grade_seconds": 1803 + }, + { + "task": "planar-first-passage", + "challenge": "PlanarFirstPassage", + "family": "212", + "family_title": "No bigeodesics and smooth limit shapes in planar first-passage percolation", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.PlanarFPP.manuscriptMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 195, + "bytes": 854325, + "packages": [], + "grade_timeout_sec": 11568, + "oracle_result": "accepted", + "oracle_grade_seconds": 768 + }, + { + "task": "planar-l1", + "challenge": "PlanarL1", + "family": "089", + "family_title": "Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.PlanarL1.planar_graph_metrics_embed_L1" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 63, + "bytes": 1567179, + "packages": [], + "grade_timeout_sec": 12210, + "oracle_result": "accepted", + "oracle_grade_seconds": 713 + }, + { + "task": "planar-unit-distances", + "challenge": "PlanarUnitDistances", + "family": "167", + "family_title": "Pinned distances and a power saving for planar unit distances", + "subject": "Combinatorics", + "theorems": [ + "OAI.PlanarUnitDistances.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 40, + "bytes": 1344796, + "packages": [], + "grade_timeout_sec": 12010, + "oracle_result": "accepted", + "oracle_grade_seconds": 1123 + }, + { + "task": "plane-coloring", + "challenge": "PlaneColoring", + "family": "158", + "family_title": "The Euclidean plane cannot be colored with five colors", + "subject": "Combinatorics", + "theorems": [ + "OAI.Problem160.properColoring_seven" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 9, + "bytes": 17840, + "packages": [], + "grade_timeout_sec": 10816, + "oracle_result": "accepted", + "oracle_grade_seconds": 677 + }, + { + "task": "posterior-replicas", + "challenge": "PosteriorReplicas", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PosteriorReplicas.source_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 136, + "bytes": 716462, + "packages": [], + "grade_timeout_sec": 11444, + "oracle_result": "accepted", + "oracle_grade_seconds": 1090 + }, + { + "task": "power-free-values", + "challenge": "PowerFreeValues", + "family": "020", + "family_title": "Squarefree quartics and power-free polynomial values", + "subject": "Number theory", + "theorems": [ + "OAI.QuarticPowerFree.allDegrees" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 63, + "bytes": 1138297, + "packages": [], + "grade_timeout_sec": 11824, + "oracle_result": "accepted", + "oracle_grade_seconds": 1054 + }, + { + "task": "prime-gaps", + "challenge": "PrimeGaps", + "family": "026", + "family_title": "Positive lower density of large prime gaps", + "subject": "Number theory", + "theorems": [ + "OAI.Problem344.large_gaps_and_ratio_density" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 56, + "bytes": 1086346, + "packages": [], + "grade_timeout_sec": 11777, + "oracle_result": "accepted", + "oracle_grade_seconds": 727 + }, + { + "task": "product-brown", + "challenge": "ProductBrown", + "family": "293", + "family_title": "A counterexample to the hyperinvariant-subspace problem", + "subject": "Operator algebras", + "theorems": [ + "OAI.FiniteFactor.productBrown" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 292, + "bytes": 1198654, + "packages": [], + "grade_timeout_sec": 11878, + "oracle_result": "accepted", + "oracle_grade_seconds": 853 + }, + { + "task": "projection-counterexample", + "challenge": "ProjectionCounterexample", + "family": "088", + "family_title": "Petty's projection-volume conjecture and simplex counterexamples", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.ProjectionCounterexample.universal_simplex_upper_bound_false" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 41, + "bytes": 131947, + "packages": [], + "grade_timeout_sec": 10918, + "oracle_result": "accepted", + "oracle_grade_seconds": 576 + }, + { + "task": "projection-moments", + "challenge": "ProjectionMoments", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.ProjectionMoments.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 46, + "bytes": 515196, + "packages": [], + "grade_timeout_sec": 11263, + "oracle_result": "accepted", + "oracle_grade_seconds": 919 + }, + { + "task": "projection-volume", + "challenge": "ProjectionVolume", + "family": "088", + "family_title": "Petty's projection-volume conjecture and simplex counterexamples", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.Paper092.product_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 29, + "bytes": 128826, + "packages": [], + "grade_timeout_sec": 10915, + "oracle_result": "accepted", + "oracle_grade_seconds": 601 + }, + { + "task": "qac-parity", + "challenge": "QACParity", + "family": "274", + "family_title": "Moore's parity conjecture for $\\mathrm{QAC}^0$", + "subject": "Mathematical physics", + "theorems": [ + "OAI.QAC.parity_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 21, + "bytes": 152586, + "packages": [], + "grade_timeout_sec": 10937, + "oracle_result": "accepted", + "oracle_grade_seconds": 693 + }, + { + "task": "quadric-bundles", + "challenge": "QuadricBundles", + "family": "050", + "family_title": "A counterexample to Griffiths' positivity conjecture", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.QuadricCounterexample.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 604021, + "packages": [], + "grade_timeout_sec": 11343, + "oracle_result": "accepted", + "oracle_grade_seconds": 886 + }, + { + "task": "quantitative-van-der-waerden", + "challenge": "QuantitativeVanDerWaerden", + "family": "160", + "family_title": "Superexponential van der Waerden numbers", + "subject": "Combinatorics", + "theorems": [ + "OAI.QuantitativeVanDerWaerden.uniform_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 115, + "bytes": 643306, + "packages": [], + "grade_timeout_sec": 11378, + "oracle_result": "accepted", + "oracle_grade_seconds": 811 + }, + { + "task": "quintic-lienard", + "challenge": "QuinticLienard", + "family": "143", + "family_title": "Uniform limit-cycle bounds in Hilbert's sixteenth problem", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.QuinticLienard.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 146, + "bytes": 816084, + "packages": [], + "grade_timeout_sec": 11534, + "oracle_result": "accepted", + "oracle_grade_seconds": 1484 + }, + { + "task": "radial-density-interval", + "challenge": "RadialDensityInterval", + "family": "228", + "family_title": "Continuum phase transitions for radial pair potentials", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.RadialTransition.densityInterval" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 104, + "bytes": 698440, + "packages": [], + "grade_timeout_sec": 11428, + "oracle_result": "accepted", + "oracle_grade_seconds": 1163 + }, + { + "task": "radial-transition", + "challenge": "RadialTransition", + "family": "228", + "family_title": "Continuum phase transitions for radial pair potentials", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.RadialTransition.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 103, + "bytes": 693070, + "packages": [], + "grade_timeout_sec": 11423, + "oracle_result": "accepted", + "oracle_grade_seconds": 1222 + }, + { + "task": "randomized-mean-payoff", + "challenge": "RandomizedMeanPayoff", + "family": "104", + "family_title": "Quasipolynomial algorithms for mean-payoff, stochastic and parity games", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.randomized_quasipolynomial_mean_payoff" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 89, + "bytes": 1301045, + "packages": [], + "grade_timeout_sec": 11970, + "oracle_result": "accepted", + "oracle_grade_seconds": 1082 + }, + { + "task": "rational-hitting", + "challenge": "RationalHitting", + "family": "116", + "family_title": "Uniform identity testing for noncommutative formulas", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.RationalHitting.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 53, + "bytes": 700555, + "packages": [], + "grade_timeout_sec": 11430, + "oracle_result": "accepted", + "oracle_grade_seconds": 666 + }, + { + "task": "real-l1-renorming", + "challenge": "RealL1Renorming", + "family": "330", + "family_title": "A negative answer to Kalton's Lipschitz-free approximation question", + "subject": "Functional analysis", + "theorems": [ + "OAI.DiscreteFree.real_l1_quantitative_renorming" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 33, + "bytes": 179835, + "packages": [], + "grade_timeout_sec": 10961, + "oracle_result": "accepted", + "oracle_grade_seconds": 304 + }, + { + "task": "recursive-potentials", + "challenge": "RecursivePotentials", + "family": "331", + "family_title": "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming", + "subject": "Functional analysis", + "theorems": [ + "OAI.ComparatorModel.RecursivePotentials.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 12, + "bytes": 445768, + "packages": [], + "grade_timeout_sec": 11201, + "oracle_result": "accepted", + "oracle_grade_seconds": 617 + }, + { + "task": "reflexive-fixed-points", + "challenge": "ReflexiveFixedPoints", + "family": "328", + "family_title": "Fixed points of nonexpansive maps in reflexive Banach spaces", + "subject": "Functional analysis", + "theorems": [ + "OAI.ReflexiveFixedPoints.exists_fixedPoint_of_canonicallyReflexive" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 86, + "bytes": 480875, + "packages": [], + "grade_timeout_sec": 11232, + "oracle_result": "accepted", + "oracle_grade_seconds": 664 + }, + { + "task": "regular-parity", + "challenge": "RegularParity", + "family": "274", + "family_title": "Moore's parity conjecture for $\\mathrm{QAC}^0$", + "subject": "Mathematical physics", + "theorems": [ + "OAI.QAC.parity_lower_bound_polynomial_size" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 154244, + "packages": [], + "grade_timeout_sec": 10938, + "oracle_result": "accepted", + "oracle_grade_seconds": 623 + }, + { + "task": "relative-generation", + "challenge": "RelativeGeneration", + "family": "296", + "family_title": "The generator problem for finite factors", + "subject": "Operator algebras", + "theorems": [ + "OAI.RelativeGeneration.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 102, + "bytes": 1722505, + "packages": [], + "grade_timeout_sec": 12350, + "oracle_result": "accepted", + "oracle_grade_seconds": 3956 + }, + { + "task": "rokhlin", + "challenge": "Rokhlin", + "family": "145", + "family_title": "Rokhlin's multiple-mixing problem", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.Rokhlin.mixing_all_finite_orders" + ], + "definition_holes": [], + "fixed_definitions": [ + "OAI.Rokhlin.timeMap", + "OAI.Rokhlin.IsMixing", + "OAI.Rokhlin.layoutTime", + "OAI.Rokhlin.MixingOfOrder" + ], + "n_modules": 13, + "bytes": 1407449, + "packages": [], + "grade_timeout_sec": 12066, + "oracle_result": "accepted", + "oracle_grade_seconds": 1397 + }, + { + "task": "ruled-covering", + "challenge": "RuledCovering", + "family": "100", + "family_title": "A counterexample to Bang's cylinder-covering bound", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.RuledApproximation.fullMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 30, + "bytes": 195883, + "packages": [], + "grade_timeout_sec": 10976, + "oracle_result": "accepted", + "oracle_grade_seconds": 963 + }, + { + "task": "ryser-covering", + "challenge": "RyserCovering", + "family": "162", + "family_title": "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures", + "subject": "Combinatorics", + "theorems": [ + "OAI.RyserCoveringCounterexample.exists_prime_eventually_counterexampleRank" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 217, + "bytes": 1129016, + "packages": [], + "grade_timeout_sec": 11816, + "oracle_result": "accepted", + "oracle_grade_seconds": 702 + }, + { + "task": "ryser-odd-extensions", + "challenge": "RyserOddExtensions", + "family": "162", + "family_title": "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures", + "subject": "Combinatorics", + "theorems": [ + "OAI.RyserOdd.eventualOddFailures_and_infinite" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 219, + "bytes": 1140439, + "packages": [], + "grade_timeout_sec": 11826, + "oracle_result": "accepted", + "oracle_grade_seconds": 649 + }, + { + "task": "sat-sharpness", + "challenge": "SATSharpness", + "family": "235", + "family_title": "Random-SAT thresholds, sharp variance and computability", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.RandomKSAT.sharpness" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 26, + "bytes": 237426, + "packages": [], + "grade_timeout_sec": 11013, + "oracle_result": "accepted", + "oracle_grade_seconds": 561 + }, + { + "task": "sat-variance", + "challenge": "SATVariance", + "family": "235", + "family_title": "Random-SAT thresholds, sharp variance and computability", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.RandomKSAT.variance_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 299818, + "packages": [], + "grade_timeout_sec": 11069, + "oracle_result": "accepted", + "oracle_grade_seconds": 700 + }, + { + "task": "sk-full-support", + "challenge": "SKFullSupport", + "family": "281", + "family_title": "QAOA optimality for the SK model", + "subject": "Mathematical physics", + "theorems": [ + "OAI.ZeroTemperatureSK.full_support" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 135, + "bytes": 989995, + "packages": [], + "grade_timeout_sec": 11690, + "oracle_result": "accepted", + "oracle_grade_seconds": 964 + }, + { + "task": "sk-value", + "challenge": "SKValue", + "family": "281", + "family_title": "QAOA optimality for the SK model", + "subject": "Mathematical physics", + "theorems": [ + "OAI.SKValue.value_consequences" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 212, + "bytes": 1487979, + "packages": [], + "grade_timeout_sec": 12139, + "oracle_result": "accepted", + "oracle_grade_seconds": 1378 + }, + { + "task": "sle-lower-positivity", + "challenge": "SLELowerPositivity", + "family": "230", + "family_title": "Exact Hausdorff measure for SLE", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.SLEExactGauge.sourceLowerMain_proved" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 65, + "bytes": 2264389, + "packages": [], + "grade_timeout_sec": 12837, + "oracle_result": "accepted", + "oracle_grade_seconds": 1070 + }, + { + "task": "saxl", + "challenge": "Saxl", + "family": "205", + "family_title": "Saxl's conjecture and universal tensor squares", + "subject": "Algebra", + "theorems": [ + "OAI.Saxl.saxl_conjecture" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 38, + "bytes": 321190, + "packages": [], + "grade_timeout_sec": 11089, + "oracle_result": "accepted", + "oracle_grade_seconds": 943 + }, + { + "task": "second-kahn-kalai", + "challenge": "SecondKahnKalai", + "family": "176", + "family_title": "The second Kahn\u2013Kalai conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.LeanBlast.SecondKahnKalai.secondKahnKalaiBounds" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 37, + "bytes": 288343, + "packages": [], + "grade_timeout_sec": 11059, + "oracle_result": "accepted", + "oracle_grade_seconds": 573 + }, + { + "task": "self-similar", + "challenge": "SelfSimilar", + "family": "148", + "family_title": "The dimension formula for self-similar measures on the line", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.EntropyRateDimension.entropy_rate_dimension" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 57, + "bytes": 523984, + "packages": [], + "grade_timeout_sec": 11271, + "oracle_result": "accepted", + "oracle_grade_seconds": 832 + }, + { + "task": "self-similar-corollaries", + "challenge": "SelfSimilarCorollaries", + "family": "148", + "family_title": "The dimension formula for self-similar measures on the line", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.EntropyRateDimension.Extensions.homogeneous_dimension_direct", + "OAI.CorSetReference.cor_set" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 64, + "bytes": 559526, + "packages": [], + "grade_timeout_sec": 11303, + "oracle_result": "accepted", + "oracle_grade_seconds": 1090 + }, + { + "task": "sensitivity-separation", + "challenge": "SensitivitySeparation", + "family": "132", + "family_title": "A counterexample to the quadratic sensitivity conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.Paper320.quantitative_separation" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 42, + "bytes": 159617, + "packages": [], + "grade_timeout_sec": 10943, + "oracle_result": "accepted", + "oracle_grade_seconds": 787 + }, + { + "task": "separable-quotient-negative", + "challenge": "SeparableQuotientNegative", + "family": "323", + "family_title": "Relative independence of the separable quotient problem", + "subject": "Functional analysis", + "theorems": [ + "OAI.SeparableQuotient.negative_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 669194, + "packages": [], + "grade_timeout_sec": 11402, + "oracle_result": "accepted", + "oracle_grade_seconds": 974 + }, + { + "task": "seymour-second-neighborhood", + "challenge": "SeymourSecondNeighborhood", + "family": "173", + "family_title": "Seymour's second-neighborhood conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.SeymourSecondNeighborhood.exists_goodVertex" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 43, + "bytes": 190801, + "packages": [], + "grade_timeout_sec": 10971, + "oracle_result": "accepted", + "oracle_grade_seconds": 649 + }, + { + "task": "sharp-cat0-filling", + "challenge": "SharpCAT0Filling", + "family": "337", + "family_title": "Cartan\u2013Hadamard isoperimetry and CAT$(0)$ fillings", + "subject": "Differential geometry", + "theorems": [ + "OAI.CAT0Fillings.sharp_integral_filling" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 330, + "bytes": 2329103, + "packages": [], + "grade_timeout_sec": 12896, + "oracle_result": "accepted", + "oracle_grade_seconds": 1201 + }, + { + "task": "sharp-threshold", + "challenge": "SharpThreshold", + "family": "186", + "family_title": "The Friedgut\u2013Kalai graph and hypergraph threshold conjectures", + "subject": "Combinatorics", + "theorems": [ + "OAI.Problem313.sharp_threshold_width" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 78, + "bytes": 313943, + "packages": [], + "grade_timeout_sec": 11082, + "oracle_result": "accepted", + "oracle_grade_seconds": 662 + }, + { + "task": "short-egyptian-fractions", + "challenge": "ShortEgyptianFractions", + "family": "025", + "family_title": "Erd\\H{o}s\u2019s short Egyptian-fraction conjecture", + "subject": "Number theory", + "theorems": [ + "OAI.ShortEgyptian.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 58, + "bytes": 383383, + "packages": [], + "grade_timeout_sec": 11145, + "oracle_result": "accepted", + "oracle_grade_seconds": 818 + }, + { + "task": "sidorenko-counterexample", + "challenge": "SidorenkoCounterexample", + "family": "161", + "family_title": "Counterexamples to Sidorenko's conjecture and the forcing conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.SidorenkoCounterexample.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 35, + "bytes": 1216768, + "packages": [], + "grade_timeout_sec": 11895, + "oracle_result": "accepted", + "oracle_grade_seconds": 1285 + }, + { + "task": "signed-finite-band", + "challenge": "SignedFiniteBand", + "family": "085", + "family_title": "Endpoint regularity of the planar centered maximal function", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.SignedDisk.CenteredDiskEndpoint.main_signed_finite_band" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 39, + "bytes": 841812, + "packages": [], + "grade_timeout_sec": 11557, + "oracle_result": "accepted", + "oracle_grade_seconds": 785 + }, + { + "task": "signed-sweep-moment", + "challenge": "SignedSweepMoment", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.SignedSweeps.signed_occurrence_moment_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 174, + "bytes": 1198418, + "packages": [], + "grade_timeout_sec": 11878, + "oracle_result": "accepted", + "oracle_grade_seconds": 1266 + }, + { + "task": "single-fold", + "challenge": "SingleFold", + "family": "242", + "family_title": "Single-fold Diophantine representations", + "subject": "Mathematical logic", + "theorems": [ + "OAI.SingleFold.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 28, + "bytes": 336998, + "packages": [], + "grade_timeout_sec": 11103, + "oracle_result": "accepted", + "oracle_grade_seconds": 851 + }, + { + "task": "single-lattice-covering", + "challenge": "SingleLatticeCovering", + "family": "092", + "family_title": "The optimal order of convex-body covering density", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.SingleLatticeCovering.single_lattice_covering" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 41, + "bytes": 1145959, + "packages": [], + "grade_timeout_sec": 11831, + "oracle_result": "accepted", + "oracle_grade_seconds": 1015 + }, + { + "task": "singleton-loop-matching", + "challenge": "SingletonLoopMatching", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.LoopMatching.fullEndpoint" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 136, + "bytes": 719294, + "packages": [], + "grade_timeout_sec": 11447, + "oracle_result": "accepted", + "oracle_grade_seconds": 1239 + }, + { + "task": "smooth-initial-form", + "challenge": "SmoothInitialForm", + "family": "108", + "family_title": "A cubic permanent\u2013determinant lower bound", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.PermanentBorder.smooth_initial_form_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 17, + "bytes": 290725, + "packages": [], + "grade_timeout_sec": 11061, + "oracle_result": "accepted", + "oracle_grade_seconds": 852 + }, + { + "task": "smooth-obstruction", + "challenge": "SmoothObstruction", + "family": "152", + "family_title": "Zero entropy does not guarantee a smooth positive-volume model", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.SmoothObstruction.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 53, + "bytes": 1540084, + "packages": [], + "grade_timeout_sec": 12186, + "oracle_result": "accepted", + "oracle_grade_seconds": 1158 + }, + { + "task": "soft-channel204", + "challenge": "SoftChannel204", + "family": "119", + "family_title": "The Courtade\u2013Kumar and Hellinger conjectures", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.SoftChannel204.fullMain" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 70, + "bytes": 495679, + "packages": [], + "grade_timeout_sec": 11246, + "oracle_result": "accepted", + "oracle_grade_seconds": 775 + }, + { + "task": "solenoidal-sheet-programs", + "challenge": "SolenoidalSheetPrograms", + "family": "376", + "family_title": "Universal computation in forced Navier\u2013Stokes flows", + "subject": "Partial differential equations", + "theorems": [ + "OAI.Solenoidal.sheet_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 26, + "bytes": 295192, + "packages": [], + "grade_timeout_sec": 11065, + "oracle_result": "accepted", + "oracle_grade_seconds": 690 + }, + { + "task": "spherical-field", + "challenge": "SphericalField", + "family": "222", + "family_title": "Perceptron free energies and microscopic jamming", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.SphericalPerceptron.spherical_linear_field_formula" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 142, + "bytes": 1253471, + "packages": [], + "grade_timeout_sec": 11928, + "oracle_result": "accepted", + "oracle_grade_seconds": 1292 + }, + { + "task": "split-tangent-integrability", + "challenge": "SplitTangentIntegrability", + "family": "052", + "family_title": "Tangent-bundle splittings and universal covers", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.SplitTangent.integrability_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 15, + "bytes": 804852, + "packages": [], + "grade_timeout_sec": 11524, + "oracle_result": "accepted", + "oracle_grade_seconds": 529 + }, + { + "task": "square-difference", + "challenge": "SquareDifference", + "family": "182", + "family_title": "Power savings for polynomial-difference-free sets", + "subject": "Combinatorics", + "theorems": [ + "OAI.SquareDifference.power_saving" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 81, + "bytes": 1102925, + "packages": [], + "grade_timeout_sec": 11792, + "oracle_result": "accepted", + "oracle_grade_seconds": 978 + }, + { + "task": "square-root-degree", + "challenge": "SquareRootDegree", + "family": "192", + "family_title": "A counterexample to the Gopalan\u2013Servedio conjecture", + "subject": "Combinatorics", + "theorems": [ + "OAI.SquareRootDegree.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 21, + "bytes": 158632, + "packages": [], + "grade_timeout_sec": 10942, + "oracle_result": "accepted", + "oracle_grade_seconds": 316 + }, + { + "task": "standard-map-entropy", + "challenge": "StandardMapEntropy", + "family": "146", + "family_title": "Sinai's positive-entropy conjecture for the standard map", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.StandardMapEntropy.main_entropy" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 205, + "bytes": 1320589, + "packages": [], + "grade_timeout_sec": 11988, + "oracle_result": "accepted", + "oracle_grade_seconds": 1548 + }, + { + "task": "standard-map-lyapunov", + "challenge": "StandardMapLyapunov", + "family": "146", + "family_title": "Sinai's positive-entropy conjecture for the standard map", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.StandardMapEntropy.main_entropy_complete" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 211, + "bytes": 1383590, + "packages": [], + "grade_timeout_sec": 12045, + "oracle_result": "accepted", + "oracle_grade_seconds": 1561 + }, + { + "task": "steinitz-bergstrom", + "challenge": "SteinitzBergstrom", + "family": "097", + "family_title": "The Euclidean Steinitz\u2013Bergstrom conjecture", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.EuclideanSteinitzBergstrom.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 29, + "bytes": 716227, + "packages": [], + "grade_timeout_sec": 11444, + "oracle_result": "accepted", + "oracle_grade_seconds": 875 + }, + { + "task": "strict-means", + "challenge": "StrictMeans", + "family": "072", + "family_title": "Brennan's conjecture and a counterexample to Kraetzer's prediction", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.StrictInverseFirstPower.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 94, + "bytes": 718706, + "packages": [], + "grade_timeout_sec": 11446, + "oracle_result": "accepted", + "oracle_grade_seconds": 1180 + }, + { + "task": "strong-thin-tree", + "challenge": "StrongThinTree", + "family": "174", + "family_title": "Deterministic construction of strong thin spanning trees", + "subject": "Combinatorics", + "theorems": [ + "OAI.StrongThinTree.strongThinTree" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 72, + "bytes": 775264, + "packages": [], + "grade_timeout_sec": 11497, + "oracle_result": "accepted", + "oracle_grade_seconds": 974 + }, + { + "task": "strongly-rayleigh-dpp", + "challenge": "StronglyRayleighDPP", + "family": "231", + "family_title": "The free uniform spanning forest is a factor of IID", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Problem336AdditiveD139.finite_strongly_rayleigh_response", + "OAI.Problem336AdditiveD139.strongly_rayleigh_group_factor", + "OAI.Problem336AdditiveD139.finite_positive_contraction_dpp_is_strongly_rayleigh", + "OAI.Problem336AdditiveD139.countable_positive_contraction_dpp_exists_unique", + "OAI.Problem336AdditiveD139.invariant_positive_contraction_dpp_factor", + "OAI.Problem336AdditiveD139.translation_invariant_kernel_dpp_factor" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 107, + "bytes": 512357, + "packages": [], + "grade_timeout_sec": 11261, + "oracle_result": "accepted", + "oracle_grade_seconds": 889 + }, + { + "task": "structural-crouzeix", + "challenge": "StructuralCrouzeix", + "family": "325", + "family_title": "The complete Crouzeix conjecture", + "subject": "Functional analysis", + "theorems": [ + "OAI.StructuralCrouzeixReference.challenge" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 60, + "bytes": 698525, + "packages": [], + "grade_timeout_sec": 11428, + "oracle_result": "accepted", + "oracle_grade_seconds": 1228 + }, + { + "task": "subpolynomial-lp", + "challenge": "SubpolynomialLp", + "family": "094", + "family_title": "Subpolynomial dimension reduction in $L_p$", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.SubpolynomialLp.source_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 44, + "bytes": 369072, + "packages": [], + "grade_timeout_sec": 11132, + "oracle_result": "accepted", + "oracle_grade_seconds": 893 + }, + { + "task": "subsphere-current", + "challenge": "SubsphereCurrent", + "family": "140", + "family_title": "Memory\u2013sample lower bounds for noiseless Gaussian regression", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.SubsphereCurrent.full_current_main_scope" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 25, + "bytes": 477744, + "packages": [], + "grade_timeout_sec": 11229, + "oracle_result": "accepted", + "oracle_grade_seconds": 463 + }, + { + "task": "superstring", + "challenge": "Superstring", + "family": "128", + "family_title": "A factor-two approximation for shortest common superstring", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.Superstring.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 940918, + "packages": [], + "grade_timeout_sec": 11646, + "oracle_result": "accepted", + "oracle_grade_seconds": 784 + }, + { + "task": "switch-chain", + "challenge": "SwitchChain", + "family": "131", + "family_title": "Polynomial mixing of graph switches with prescribed degrees", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.Problem315.switch_chain_main", + "OAI.Problem315.switch_chain_tv_bound", + "OAI.Problem315.switch_connectivity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 165, + "bytes": 921825, + "packages": [], + "grade_timeout_sec": 11629, + "oracle_result": "accepted", + "oracle_grade_seconds": 924 + }, + { + "task": "symmetric-domains", + "challenge": "SymmetricDomains", + "family": "058", + "family_title": "The Kollar\u2013Pardon universal-cover conjecture", + "subject": "Algebraic and complex geometry", + "theorems": [ + "OAI.Release061.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 335, + "bytes": 2114940, + "packages": [], + "grade_timeout_sec": 12703, + "oracle_result": "accepted", + "oracle_grade_seconds": 1307 + }, + { + "task": "symmetric-mahler-equality", + "challenge": "SymmetricMahlerEquality", + "family": "087", + "family_title": "The Mahler conjectures and symplectic width", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.SymmetricMahler.symmetric_mahler_equality" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 237, + "bytes": 1330350, + "packages": [], + "grade_timeout_sec": 11997, + "oracle_result": "accepted", + "oracle_grade_seconds": 986 + }, + { + "task": "symmetric-polar", + "challenge": "SymmetricPolar", + "family": "087", + "family_title": "The Mahler conjectures and symplectic width", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.SymmetricPolar.symmetric_polar_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 46, + "bytes": 543383, + "packages": [], + "grade_timeout_sec": 11289, + "oracle_result": "accepted", + "oracle_grade_seconds": 1068 + }, + { + "task": "tachikawa", + "challenge": "Tachikawa", + "family": "199", + "family_title": "Counterexamples to conjectures of Auslander\u2013Reiten, Tachikawa, and Nakayama", + "subject": "Algebra", + "theorems": [ + "OAI.Tachikawa.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 1264529, + "packages": [], + "grade_timeout_sec": 11938, + "oracle_result": "accepted", + "oracle_grade_seconds": 1382 + }, + { + "task": "talagrand-discrete-convexity", + "challenge": "TalagrandDiscreteConvexity", + "family": "175", + "family_title": "Talagrand's conjectures and graph decompositions at expectation thresholds", + "subject": "Combinatorics", + "theorems": [ + "OAI.TalagrandDiscreteConvexity.talagrand_discrete_convexity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 36, + "bytes": 174257, + "packages": [], + "grade_timeout_sec": 10956, + "oracle_result": "accepted", + "oracle_grade_seconds": 439 + }, + { + "task": "talagrand-expectation-threshold", + "challenge": "TalagrandExpectationThreshold", + "family": "175", + "family_title": "Talagrand's conjectures and graph decompositions at expectation thresholds", + "subject": "Combinatorics", + "theorems": [ + "OAI.TalagrandThreshold.talagrand_expectation_threshold_equivalence" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 47, + "bytes": 192418, + "packages": [], + "grade_timeout_sec": 10973, + "oracle_result": "accepted", + "oracle_grade_seconds": 213 + }, + { + "task": "thomason-model-structures", + "challenge": "ThomasonModelStructures", + "family": "317", + "family_title": "Thomason model structures in every strict higher dimension", + "subject": "Topology", + "theorems": [ + "OAI.Thomason.main", + "OAI.Thomason.nerveDetection_allDimensions" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 85, + "bytes": 2875278, + "packages": [], + "grade_timeout_sec": 13387, + "oracle_result": "accepted", + "oracle_grade_seconds": 1608 + }, + { + "task": "thompson-nonamenability", + "challenge": "ThompsonNonamenability", + "family": "248", + "family_title": "Thompson's group $F$ is nonamenable", + "subject": "Group theory", + "theorems": [ + "OAI.ThompsonNonamenability.thompson_F_nonamenable_composition" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 68, + "bytes": 372798, + "packages": [], + "grade_timeout_sec": 11135, + "oracle_result": "accepted", + "oracle_grade_seconds": 146 + }, + { + "task": "thorp-first-reciprocal", + "challenge": "ThorpFirstReciprocal", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.Thorp.Current.first_reciprocal_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 367273, + "packages": [], + "grade_timeout_sec": 11130, + "oracle_result": "accepted", + "oracle_grade_seconds": 637 + }, + { + "task": "thorp-remaining", + "challenge": "ThorpRemaining", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThorpResults.remaining_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 92, + "bytes": 1378792, + "packages": [], + "grade_timeout_sec": 12040, + "oracle_result": "accepted", + "oracle_grade_seconds": 730 + }, + { + "task": "thorp-routing", + "challenge": "ThorpRouting", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThorpNine.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 170, + "bytes": 6581773, + "packages": [], + "grade_timeout_sec": 16723, + "oracle_result": "accepted", + "oracle_grade_seconds": 1374 + }, + { + "task": "thorp-weighted-compatibility", + "challenge": "ThorpWeightedCompatibility", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThorpCompatibility.weightedCompatibility_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 34, + "bytes": 135549, + "packages": [], + "grade_timeout_sec": 10921, + "oracle_result": "accepted", + "oracle_grade_seconds": 294 + }, + { + "task": "three-machine", + "challenge": "ThreeMachine", + "family": "124", + "family_title": "Polynomial-time scheduling on three identical machines", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.ThreeMachine.main_theorem" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 53, + "bytes": 851902, + "packages": [], + "grade_timeout_sec": 11566, + "oracle_result": "accepted", + "oracle_grade_seconds": 467 + }, + { + "task": "three-state-supercritical", + "challenge": "ThreeStateSupercritical", + "family": "229", + "family_title": "Sharp three- and four-state reconstruction thresholds", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThreeState.regular_supercritical", + "OAI.ThreeState.poisson_supercritical" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 27, + "bytes": 382667, + "packages": [], + "grade_timeout_sec": 11144, + "oracle_result": "accepted", + "oracle_grade_seconds": 212 + }, + { + "task": "three-state-tree-clauses", + "challenge": "ThreeStateTreeClauses", + "family": "229", + "family_title": "Sharp three- and four-state reconstruction thresholds", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.ThreeState.TreeClauses.Tree.regular_reconstructs_above_KS", + "OAI.ThreeState.TreeClauses.Tree.poisson_reconstructs_above_KS" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 383958, + "packages": [], + "grade_timeout_sec": 11145, + "oracle_result": "accepted", + "oracle_grade_seconds": 204 + }, + { + "task": "three-torus", + "challenge": "ThreeTorus", + "family": "144", + "family_title": "Banach's simple Lebesgue-spectrum problem", + "subject": "Dynamical systems and ergodic theory", + "theorems": [ + "OAI.ThreeTorus.simple_lebesgue_spectrum" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 37, + "bytes": 1720327, + "packages": [], + "grade_timeout_sec": 12348, + "oracle_result": "accepted", + "oracle_grade_seconds": 669 + }, + { + "task": "tingley-sphere-isometry", + "challenge": "TingleySphereIsometry", + "family": "322", + "family_title": "Tingley's sphere-isometry problem", + "subject": "Functional analysis", + "theorems": [ + "OAI.Tingley.tingley_sphere_isometry_full" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 67, + "bytes": 382424, + "packages": [], + "grade_timeout_sec": 11144, + "oracle_result": "accepted", + "oracle_grade_seconds": 129 + }, + { + "task": "torsion-free-hyperbolic", + "challenge": "TorsionFreeHyperbolic", + "family": "252", + "family_title": "A non-residually-finite torsion-free hyperbolic group", + "subject": "Group theory", + "theorems": [ + "OAI.Release075.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 29, + "bytes": 482151, + "packages": [], + "grade_timeout_sec": 11233, + "oracle_result": "accepted", + "oracle_grade_seconds": 289 + }, + { + "task": "torsion-free-zero-divisors", + "challenge": "TorsionFreeZeroDivisors", + "family": "196", + "family_title": "A counterexample to Kaplansky's zero-divisor conjecture", + "subject": "Algebra", + "theorems": [ + "OAI.TorsionFreeZeroDivisors.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 123, + "bytes": 2064427, + "packages": [], + "grade_timeout_sec": 12657, + "oracle_result": "accepted", + "oracle_grade_seconds": 805 + }, + { + "task": "trace-reconstruction", + "challenge": "TraceReconstruction", + "family": "122", + "family_title": "Superpolynomial lower bounds and quasipolynomial reconstruction from deletion traces", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.TraceReconstruction.quantitative_sample_lower_bound", + "OAI.TraceReconstruction.superpolynomial_one_trace", + "OAI.TraceReconstruction.superpolynomial_sample_complexity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 31, + "bytes": 1632943, + "packages": [], + "grade_timeout_sec": 12269, + "oracle_result": "accepted", + "oracle_grade_seconds": 415 + }, + { + "task": "tree-edit", + "challenge": "TreeEdit", + "family": "099", + "family_title": "The sharp distortion of edit distance into $\\ell_1$", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.TreeEdit.binary_torus" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 22, + "bytes": 243012, + "packages": [], + "grade_timeout_sec": 11018, + "oracle_result": "accepted", + "oracle_grade_seconds": 202 + }, + { + "task": "triangle-face", + "challenge": "TriangleFace", + "family": "113", + "family_title": "Approximate counting and the perfect-matching entropy conjecture", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.TriangleFace198.triangle_expansion_face" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 37, + "bytes": 326247, + "packages": [], + "grade_timeout_sec": 11093, + "oracle_result": "accepted", + "oracle_grade_seconds": 216 + }, + { + "task": "triangle-removal", + "challenge": "TriangleRemoval", + "family": "188", + "family_title": "The sharp constant in random triangle removal", + "subject": "Combinatorics", + "theorems": [ + "OAI.SharpTerminalLeave.sharp_terminal_leave" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 287, + "bytes": 1468947, + "packages": [], + "grade_timeout_sec": 12122, + "oracle_result": "accepted", + "oracle_grade_seconds": 935 + }, + { + "task": "triangular-covering", + "challenge": "TriangularCovering", + "family": "100", + "family_title": "A counterexample to Bang's cylinder-covering bound", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.TriangularCovering.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 9, + "bytes": 96114, + "packages": [], + "grade_timeout_sec": 10886, + "oracle_result": "accepted", + "oracle_grade_seconds": 203 + }, + { + "task": "triangular-energy", + "challenge": "TriangularEnergy", + "family": "090", + "family_title": "Universal optimality of the triangular lattice", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.AtomicTriangular.universal_energy_minimum" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 227, + "bytes": 8590367, + "packages": [], + "grade_timeout_sec": 18531, + "oracle_result": "accepted", + "oracle_grade_seconds": 10732 + }, + { + "task": "triangular-gaussian", + "challenge": "TriangularGaussian", + "family": "090", + "family_title": "Universal optimality of the triangular lattice", + "subject": "Convex and metric geometry", + "theorems": [ + "OAI.AtomicTriangular.sharp_gaussian_minorants_with_construction" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 216, + "bytes": 8531599, + "packages": [], + "grade_timeout_sec": 18478, + "oracle_result": "accepted", + "oracle_grade_seconds": 9985 + }, + { + "task": "triangular-hilbert", + "challenge": "TriangularHilbert", + "family": "082", + "family_title": "Maximal and variational bounds for the triangular Hilbert transform", + "subject": "Real and complex analysis", + "theorems": [ + "OAI.TriangularHilbert.main_estimate" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 105, + "bytes": 499653, + "packages": [], + "grade_timeout_sec": 11249, + "oracle_result": "accepted", + "oracle_grade_seconds": 630 + }, + { + "task": "truffet-counterexample", + "challenge": "TruffetCounterexample", + "family": "104", + "family_title": "Quasipolynomial algorithms for mean-payoff, stochastic and parity games", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.TruffetV4Counterexample.finite_execution_not_optimal" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 2, + "bytes": 11050, + "packages": [], + "grade_timeout_sec": 10809, + "oracle_result": "accepted", + "oracle_grade_seconds": 68 + }, + { + "task": "two-way-complementation", + "challenge": "TwoWayComplementation", + "family": "129", + "family_title": "Exponential state costs for two-way automata", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.TwoWayComplementation.complementation_lower_bound_finite" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 19, + "bytes": 192919, + "packages": [], + "grade_timeout_sec": 10973, + "oracle_result": "accepted", + "oracle_grade_seconds": 96 + }, + { + "task": "two-way-determinization", + "challenge": "TwoWayDeterminization", + "family": "129", + "family_title": "Exponential state costs for two-way automata", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.TwoWayComplementation.explicit_family_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 41, + "bytes": 378696, + "packages": [], + "grade_timeout_sec": 11140, + "oracle_result": "accepted", + "oracle_grade_seconds": 197 + }, + { + "task": "type-system-normalization", + "challenge": "TypeSystemNormalization", + "family": "245", + "family_title": "The $\\beta$-Barendregt\u2013Geuvers\u2013Klop conjecture", + "subject": "Mathematical logic", + "theorems": [ + "OAI.PureTypeSystem.weak_implies_strong" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 33, + "bytes": 1579764, + "packages": [], + "grade_timeout_sec": 12221, + "oracle_result": "accepted", + "oracle_grade_seconds": 186 + }, + { + "task": "uniform-commutator", + "challenge": "UniformCommutator", + "family": "288", + "family_title": "Kadison's similarity conjecture", + "subject": "Operator algebras", + "theorems": [ + "OAI.Kadison.uniform_commutator" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 656, + "bytes": 2642027, + "packages": [], + "grade_timeout_sec": 13177, + "oracle_result": "accepted", + "oracle_grade_seconds": 7060 + }, + { + "task": "uniform-gamma", + "challenge": "UniformGamma", + "family": "291", + "family_title": "Toms\u2013Winter and equivariant Jiang\u2013Su stability", + "subject": "Operator algebras", + "theorems": [ + "OAI.ComparatorModel.CurrentMain.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 51, + "bytes": 736242, + "packages": [], + "grade_timeout_sec": 11462, + "oracle_result": "accepted", + "oracle_grade_seconds": 520 + }, + { + "task": "uniform-k-server", + "challenge": "UniformKServer", + "family": "110", + "family_title": "Optimal-order randomized $k$-server on arbitrary metrics", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.UniformKServer.uniform_squared_logarithmic_main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 410, + "bytes": 2194822, + "packages": [], + "grade_timeout_sec": 12775, + "oracle_result": "accepted", + "oracle_grade_seconds": 1209 + }, + { + "task": "uniform-sparsest-cut", + "challenge": "UniformSparsestCut", + "family": "117", + "family_title": "Uniform sparsest cut: hardness and semidefinite gaps", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.UniformSparsestCut.mainGap" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 55, + "bytes": 488362, + "packages": [], + "grade_timeout_sec": 11239, + "oracle_result": "accepted", + "oracle_grade_seconds": 470 + }, + { + "task": "unique-games-theorem", + "challenge": "UniqueGamesTheorem", + "family": "102", + "family_title": "The Unique Games Conjecture and optimal approximation thresholds", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.UniqueGamesTheorem.theorem11" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 478, + "bytes": 8704327, + "packages": [], + "grade_timeout_sec": 18633, + "oracle_result": "accepted", + "oracle_grade_seconds": 1292 + }, + { + "task": "universal-f-infinity", + "challenge": "UniversalFInfinity", + "family": "250", + "family_title": "The Boone\u2013Higman conjecture and higher finiteness", + "subject": "Group theory", + "theorems": [ + "OAI.UniversalFInfinity.universal_group_of_type_FInfinity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 50, + "bytes": 884044, + "packages": [], + "grade_timeout_sec": 11595, + "oracle_result": "accepted", + "oracle_grade_seconds": 416 + }, + { + "task": "variable-wl", + "challenge": "VariableWL", + "family": "133", + "family_title": "The complexity of Weisfeiler\u2013Leman refinement", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.VariableWL.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 61, + "bytes": 1182668, + "packages": [], + "grade_timeout_sec": 11864, + "oracle_result": "accepted", + "oracle_grade_seconds": 429 + }, + { + "task": "velocity-hemisphere", + "challenge": "VelocityHemisphere", + "family": "220", + "family_title": "Directional zero\u2013one laws and ballisticity in random environments", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.DirectionalTransience.positive_probability_transience_velocity_hemisphere" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 585, + "bytes": 5974000, + "packages": [], + "grade_timeout_sec": 16176, + "oracle_result": "accepted", + "oracle_grade_seconds": 1928 + }, + { + "task": "vertex-algebra-net", + "challenge": "VertexAlgebraNet", + "family": "280", + "family_title": "Strong locality for strongly rational unitary vertex operator algebras", + "subject": "Mathematical physics", + "theorems": [ + "OAI.MinimalVertex.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 77, + "bytes": 1413292, + "packages": [], + "grade_timeout_sec": 12071, + "oracle_result": "accepted", + "oracle_grade_seconds": 696 + }, + { + "task": "vertex-cover", + "challenge": "VertexCover", + "family": "102", + "family_title": "The Unique Games Conjecture and optimal approximation thresholds", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.VertexCover.explicit_cover_gap", + "OAI.VertexCover.every_fixed_factor_below_two" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 351, + "bytes": 2275461, + "packages": [], + "grade_timeout_sec": 12847, + "oracle_result": "accepted", + "oracle_grade_seconds": 1027 + }, + { + "task": "vlasov-maxwell", + "challenge": "VlasovMaxwell", + "family": "362", + "family_title": "Global smoothness for relativistic Vlasov\u2013Maxwell", + "subject": "Partial differential equations", + "theorems": [ + "OAI.RVM.global_classical_solution" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 207, + "bytes": 4841359, + "packages": [], + "grade_timeout_sec": 15157, + "oracle_result": "accepted", + "oracle_grade_seconds": 1368 + }, + { + "task": "wl-identification", + "challenge": "WLIdentification", + "family": "133", + "family_title": "The complexity of Weisfeiler\u2013Leman refinement", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.WLIdentification.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 67, + "bytes": 765224, + "packages": [], + "grade_timeout_sec": 11488, + "oracle_result": "accepted", + "oracle_grade_seconds": 529 + }, + { + "task": "weak-hessian", + "challenge": "WeakHessian", + "family": "356", + "family_title": "Gigli's characterization of Alexandrov curvature", + "subject": "Differential geometry", + "theorems": [ + "OAI.WeakHessian.every_geodesic" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 542, + "bytes": 3136506, + "packages": [], + "grade_timeout_sec": 13622, + "oracle_result": "accepted", + "oracle_grade_seconds": 1565 + }, + { + "task": "weak-mtw-global-support", + "challenge": "WeakMTWGlobalSupport", + "family": "360", + "family_title": "Villani\u2019s convexity conjecture and regular optimal transport", + "subject": "Differential geometry", + "theorems": [ + "OAI.WeakMTWGlobalSupport.current_main_convexity" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 210, + "bytes": 903567, + "packages": [], + "grade_timeout_sec": 11613, + "oracle_result": "accepted", + "oracle_grade_seconds": 891 + }, + { + "task": "weighted-sweep-moments", + "challenge": "WeightedSweepMoments", + "family": "238", + "family_title": "Optimal logarithmic mixing of the Thorp shuffle", + "subject": "Probability and statistical mechanics", + "theorems": [ + "OAI.CubeShuffle.WeightedSweep.weighted_sweep_moments" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 40, + "bytes": 815310, + "packages": [], + "grade_timeout_sec": 11533, + "oracle_result": "accepted", + "oracle_grade_seconds": 338 + }, + { + "task": "weisfeiler-leman", + "challenge": "WeisfeilerLeman", + "family": "133", + "family_title": "The complexity of Weisfeiler\u2013Leman refinement", + "subject": "Theoretical computer science", + "theorems": [ + "OAI.WLTime.unconditional_time_lower_bound" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 43, + "bytes": 917937, + "packages": [], + "grade_timeout_sec": 11626, + "oracle_result": "accepted", + "oracle_grade_seconds": 401 + }, + { + "task": "witnessed-choice", + "challenge": "WitnessedChoice", + "family": "243", + "family_title": "Choiceless counting does not capture polynomial time", + "subject": "Mathematical logic", + "theorems": [ + "OAI.WitnessedChoice.main" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 27, + "bytes": 1118157, + "packages": [], + "grade_timeout_sec": 11806, + "oracle_result": "accepted", + "oracle_grade_seconds": 585 + }, + { + "task": "yau-counterexample", + "challenge": "YauCounterexample", + "family": "350", + "family_title": "Yau's nodal conjecture: surfaces and counterexamples", + "subject": "Differential geometry", + "theorems": [ + "OAI.Yau.Target.yau_nodal_set_upper_bound_counterexample" + ], + "definition_holes": [], + "fixed_definitions": [], + "n_modules": 1068, + "bytes": 3664066, + "packages": [], + "grade_timeout_sec": 14097, + "oracle_result": "accepted", + "oracle_grade_seconds": 2217 + } + ], + "excluded": [ + { + "challenge": "DefocusingNLS", + "reason": "OAI.DefocusingNLS.sobolevProduct: open definition the theorem statements depend on" + } + ], + "not_validated": [ + { + "task": "arnold-counterexample", + "challenge": "ArnoldCounterexample", + "family": "347", + "reason": "memory" + }, + { + "task": "atomic-gaussian", + "challenge": "AtomicGaussian", + "family": "090", + "reason": "pending" + }, + { + "task": "catalan", + "challenge": "Catalan", + "family": "005", + "reason": "missing-package" + }, + { + "task": "coarse-assembly", + "challenge": "CoarseAssembly", + "family": "307", + "reason": "memory" + }, + { + "task": "continuum-coulomb-hardness", + "challenge": "ContinuumCoulombHardness", + "family": "275", + "reason": "disk" + }, + { + "task": "cycle-clique-ramsey", + "challenge": "CycleCliqueRamsey", + "family": "189", + "reason": "pending" + }, + { + "task": "dirichlet-seven-eighths", + "challenge": "DirichletSevenEighths", + "family": "003", + "reason": "missing-package" + }, + { + "task": "duke-prime-degree", + "challenge": "DukePrimeDegree", + "family": "015", + "reason": "missing-package" + }, + { + "task": "einstein-four", + "challenge": "EinsteinFour", + "family": "348", + "reason": "missing-package" + }, + { + "task": "erdos-reciprocal", + "challenge": "ErdosReciprocal", + "family": "159", + "reason": "disk" + }, + { + "task": "hecke-seven-eighths", + "challenge": "HeckeSevenEighths", + "family": "003", + "reason": "missing-package" + }, + { + "task": "invariant-ising", + "challenge": "InvariantIsing", + "family": "234", + "reason": "pending" + }, + { + "task": "jacobsthal", + "challenge": "Jacobsthal", + "family": "021", + "reason": "missing-package" + }, + { + "task": "jacobsthal-improved", + "challenge": "JacobsthalImproved", + "family": "021", + "reason": "missing-package" + }, + { + "task": "joint-dickman", + "challenge": "JointDickman", + "family": "012", + "reason": "missing-package" + }, + { + "task": "koebe-circle-domains", + "challenge": "KoebeCircleDomains", + "family": "071", + "reason": "disk" + }, + { + "task": "mub-six", + "challenge": "MUBSix", + "family": "266", + "reason": "pending" + }, + { + "task": "matrix-multiplication", + "challenge": "MatrixMultiplication", + "family": "107", + "reason": "missing-package" + }, + { + "task": "nuclear-ultrapower", + "challenge": "NuclearUltrapower", + "family": "292", + "reason": "memory" + }, + { + "task": "occupied-overlap", + "challenge": "OccupiedOverlap", + "family": "238", + "reason": "definition-mismatch" + }, + { + "task": "ordinary-two-point-correlations", + "challenge": "OrdinaryTwoPointCorrelations", + "family": "007", + "reason": "missing-package" + }, + { + "task": "ostmann-complete", + "challenge": "OstmannComplete", + "family": "013", + "reason": "pending" + }, + { + "task": "ostmann-primes", + "challenge": "OstmannPrimes", + "family": "013", + "reason": "missing-package" + }, + { + "task": "patterson-first-moment", + "challenge": "PattersonFirstMoment", + "family": "023", + "reason": "disk" + }, + { + "task": "planar-packing", + "challenge": "PlanarPacking", + "family": "090", + "reason": "pending" + }, + { + "task": "polycyclic-recognition", + "challenge": "PolycyclicRecognition", + "family": "255", + "reason": "pending" + }, + { + "task": "quasi-riemann-hypothesis", + "challenge": "QuasiRiemannHypothesis", + "family": "003", + "reason": "missing-package" + }, + { + "task": "ramsey-five", + "challenge": "RamseyFive", + "family": "170", + "reason": "pending" + }, + { + "task": "riesz-quantitative", + "challenge": "RieszQuantitative", + "family": "081", + "reason": "missing-package" + }, + { + "task": "sat-computability", + "challenge": "SATComputability", + "family": "235", + "reason": "pending" + }, + { + "task": "sk-barriers", + "challenge": "SKBarriers", + "family": "227", + "reason": "pending" + }, + { + "task": "sk-high-temperature", + "challenge": "SKHighTemperature", + "family": "227", + "reason": "pending" + }, + { + "task": "sk-ratio", + "challenge": "SKRatio", + "family": "227", + "reason": "pending" + }, + { + "task": "sharp-log-ramsey", + "challenge": "SharpLogRamsey", + "family": "170", + "reason": "pending" + }, + { + "task": "siegel-zeros", + "challenge": "SiegelZeros", + "family": "003", + "reason": "missing-package" + }, + { + "task": "simple-amenable", + "challenge": "SimpleAmenable", + "family": "253", + "reason": "pending" + }, + { + "task": "simple-overgroups", + "challenge": "SimpleOvergroups", + "family": "250", + "reason": "pending" + }, + { + "task": "smooth-yau", + "challenge": "SmoothYau", + "family": "350", + "reason": "pending" + }, + { + "task": "snaky-certificate", + "challenge": "SnakyCertificate", + "family": "187", + "reason": "memory" + }, + { + "task": "snaky-conditional", + "challenge": "SnakyConditional", + "family": "187", + "reason": "pending" + }, + { + "task": "snaky-twenty-one", + "challenge": "SnakyTwentyOne", + "family": "187", + "reason": "pending" + }, + { + "task": "spin-angle", + "challenge": "SpinAngle", + "family": "238", + "reason": "definition-mismatch" + }, + { + "task": "standard-map-components", + "challenge": "StandardMapComponents", + "family": "146", + "reason": "pending" + }, + { + "task": "strong-kadison-kastler", + "challenge": "StrongKadisonKastler", + "family": "289", + "reason": "pending" + }, + { + "task": "surface-immersion", + "challenge": "SurfaceImmersion", + "family": "333", + "reason": "pending" + }, + { + "task": "taming-compatibility", + "challenge": "TamingCompatibility", + "family": "342", + "reason": "pending" + }, + { + "task": "totient-asymptotic", + "challenge": "TotientAsymptotic", + "family": "024", + "reason": "missing-package" + }, + { + "task": "totient-companion-zero", + "challenge": "TotientCompanionZero", + "family": "024", + "reason": "missing-package" + }, + { + "task": "universal-tensor-squares", + "challenge": "UniversalTensorSquares", + "family": "205", + "reason": "memory" + } + ] +} \ No newline at end of file diff --git a/manifest.parquet b/manifest.parquet new file mode 100644 index 0000000000000000000000000000000000000000..7cab14642b886b502548d65e115b94623c02ad01 --- /dev/null +++ b/manifest.parquet @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:3afe9e43520364a939417dd85aeec87f892c6c81fe54c6f9d0bb67650c4021d0 +size 44329 diff --git a/registry.json b/registry.json new file mode 100644 index 0000000000000000000000000000000000000000..6d98c637fd2ac9431cff39f1e313950229e37276 --- /dev/null +++ b/registry.json @@ -0,0 +1,1429 @@ +[ + { + "name": "openai-math-harbor", + "version": "1.0", + "description": "355 Lean 4 theorem-proving tasks from openai/math, graded by Comparator in a separate sandbox.", + "tasks": [ + { + "name": "abhyankar-sathaye", + "path": "tasks/abhyankar-sathaye" + }, + { + "name": "affine-bernstein", + "path": "tasks/affine-bernstein" + }, + { + "name": "algorithmic-thin-trees", + "path": "tasks/algorithmic-thin-trees" + }, + { + "name": "amplitude-damping", + "path": "tasks/amplitude-damping" + }, + { + "name": "artin-cat0", + "path": "tasks/artin-cat0" + }, + { + "name": "artin-parabolic-intersections", + "path": "tasks/artin-parabolic-intersections" + }, + { + "name": "asymptotically-minimal-littlewood", + "path": "tasks/asymptotically-minimal-littlewood" + }, + { + "name": "auslander-reiten", + "path": "tasks/auslander-reiten" + }, + { + "name": "backward-intertwiners", + "path": "tasks/backward-intertwiners" + }, + { + "name": "balanced-box-routing", + "path": "tasks/balanced-box-routing" + }, + { + "name": "balanced-ryser", + "path": "tasks/balanced-ryser" + }, + { + "name": "balanced-three-stack", + "path": "tasks/balanced-three-stack" + }, + { + "name": "ball-packing", + "path": "tasks/ball-packing" + }, + { + "name": "ball-packing-necessity", + "path": "tasks/ball-packing-necessity" + }, + { + "name": "barnette-hamiltonian", + "path": "tasks/barnette-hamiltonian" + }, + { + "name": "bass-torsion-free", + "path": "tasks/bass-torsion-free" + }, + { + "name": "bass-trace", + "path": "tasks/bass-trace" + }, + { + "name": "benjamini-schramm", + "path": "tasks/benjamini-schramm" + }, + { + "name": "bernoulli-nonflat-in-seven", + "path": "tasks/bernoulli-nonflat-in-seven" + }, + { + "name": "biholder-transport", + "path": "tasks/biholder-transport" + }, + { + "name": "bin-packing-gap", + "path": "tasks/bin-packing-gap" + }, + { + "name": "binary-edit-lower", + "path": "tasks/binary-edit-lower" + }, + { + "name": "binary-matching", + "path": "tasks/binary-matching" + }, + { + "name": "binary-sweep", + "path": "tasks/binary-sweep" + }, + { + "name": "bipartite-crossing", + "path": "tasks/bipartite-crossing" + }, + { + "name": "bogomolov-pop-injectivity", + "path": "tasks/bogomolov-pop-injectivity" + }, + { + "name": "boltzmann-nonuniqueness", + "path": "tasks/boltzmann-nonuniqueness" + }, + { + "name": "boone-higman", + "path": "tasks/boone-higman" + }, + { + "name": "borsuk-nine", + "path": "tasks/borsuk-nine" + }, + { + "name": "bounded-recovery", + "path": "tasks/bounded-recovery" + }, + { + "name": "bounded-tree-potentials", + "path": "tasks/bounded-tree-potentials" + }, + { + "name": "bounded-treewidth-l1", + "path": "tasks/bounded-treewidth-l1" + }, + { + "name": "brenier", + "path": "tasks/brenier" + }, + { + "name": "brennan", + "path": "tasks/brennan" + }, + { + "name": "brennan-sharp", + "path": "tasks/brennan-sharp" + }, + { + "name": "buffered-ising", + "path": "tasks/buffered-ising" + }, + { + "name": "c0-absorption", + "path": "tasks/c0-absorption" + }, + { + "name": "c1-entropy-counterexample", + "path": "tasks/c1-entropy-counterexample" + }, + { + "name": "ch-obstruction", + "path": "tasks/ch-obstruction" + }, + { + "name": "cks-bondi-penrose", + "path": "tasks/cks-bondi-penrose" + }, + { + "name": "cannon-geometric-action", + "path": "tasks/cannon-geometric-action" + }, + { + "name": "cayley-percolation", + "path": "tasks/cayley-percolation" + }, + { + "name": "character-criterion", + "path": "tasks/character-criterion" + }, + { + "name": "choiceless-polynomial-time", + "path": "tasks/choiceless-polynomial-time" + }, + { + "name": "circulant-hadamard", + "path": "tasks/circulant-hadamard" + }, + { + "name": "classical-on", + "path": "tasks/classical-on" + }, + { + "name": "clique-free-log", + "path": "tasks/clique-free-log" + }, + { + "name": "coboundary-expanders", + "path": "tasks/coboundary-expanders" + }, + { + "name": "common-bases-fpras", + "path": "tasks/common-bases-fpras" + }, + { + "name": "commuting-derivations", + "path": "tasks/commuting-derivations" + }, + { + "name": "compact-banach", + "path": "tasks/compact-banach" + }, + { + "name": "complete-crossing", + "path": "tasks/complete-crossing" + }, + { + "name": "complete-crouzeix", + "path": "tasks/complete-crouzeix" + }, + { + "name": "complex-cancellation", + "path": "tasks/complex-cancellation" + }, + { + "name": "conductivity", + "path": "tasks/conductivity" + }, + { + "name": "conjugate-points", + "path": "tasks/conjugate-points" + }, + { + "name": "contingency-tables", + "path": "tasks/contingency-tables" + }, + { + "name": "continuous-circle-weight", + "path": "tasks/continuous-circle-weight" + }, + { + "name": "continuum-transition", + "path": "tasks/continuum-transition" + }, + { + "name": "coordinate-sweeps", + "path": "tasks/coordinate-sweeps" + }, + { + "name": "coordinate-trace", + "path": "tasks/coordinate-trace" + }, + { + "name": "cotype", + "path": "tasks/cotype" + }, + { + "name": "coulomb-counterexample", + "path": "tasks/coulomb-counterexample" + }, + { + "name": "coulomb-ionization", + "path": "tasks/coulomb-ionization" + }, + { + "name": "coulomb-radii", + "path": "tasks/coulomb-radii" + }, + { + "name": "courtade-kumar", + "path": "tasks/courtade-kumar" + }, + { + "name": "covering-density", + "path": "tasks/covering-density" + }, + { + "name": "critical-percolation", + "path": "tasks/critical-percolation" + }, + { + "name": "critical-sk", + "path": "tasks/critical-sk" + }, + { + "name": "critical-sk-mixing", + "path": "tasks/critical-sk-mixing" + }, + { + "name": "critical-strip-mass", + "path": "tasks/critical-strip-mass" + }, + { + "name": "critical-z3", + "path": "tasks/critical-z3" + }, + { + "name": "crouzeix-hilbert", + "path": "tasks/crouzeix-hilbert" + }, + { + "name": "cubic-torus", + "path": "tasks/cubic-torus" + }, + { + "name": "cycle-decomposition", + "path": "tasks/cycle-decomposition" + }, + { + "name": "cylinder-covering", + "path": "tasks/cylinder-covering" + }, + { + "name": "daugavet-moduli", + "path": "tasks/daugavet-moduli" + }, + { + "name": "degree-rigidity", + "path": "tasks/degree-rigidity" + }, + { + "name": "deligne-drinfeld", + "path": "tasks/deligne-drinfeld" + }, + { + "name": "depth-five", + "path": "tasks/depth-five" + }, + { + "name": "depth-three", + "path": "tasks/depth-three" + }, + { + "name": "diamond-distortion", + "path": "tasks/diamond-distortion" + }, + { + "name": "diluted-spin", + "path": "tasks/diluted-spin" + }, + { + "name": "dimension-ten-channel", + "path": "tasks/dimension-ten-channel" + }, + { + "name": "dimension-ten-pair", + "path": "tasks/dimension-ten-pair" + }, + { + "name": "direct-crouzeix", + "path": "tasks/direct-crouzeix" + }, + { + "name": "directed-feedback", + "path": "tasks/directed-feedback" + }, + { + "name": "directional-ballisticity", + "path": "tasks/directional-ballisticity" + }, + { + "name": "directional-walk", + "path": "tasks/directional-walk" + }, + { + "name": "discrete-lipschitz-free", + "path": "tasks/discrete-lipschitz-free" + }, + { + "name": "disk-maximal", + "path": "tasks/disk-maximal" + }, + { + "name": "dixmier", + "path": "tasks/dixmier" + }, + { + "name": "dixmier-all-discrete", + "path": "tasks/dixmier-all-discrete" + }, + { + "name": "doubling-hilbert", + "path": "tasks/doubling-hilbert" + }, + { + "name": "dutta-domain", + "path": "tasks/dutta-domain" + }, + { + "name": "dyadic-avoidance", + "path": "tasks/dyadic-avoidance" + }, + { + "name": "edit-approximation", + "path": "tasks/edit-approximation" + }, + { + "name": "edit-distance", + "path": "tasks/edit-distance" + }, + { + "name": "egyptian-fractions", + "path": "tasks/egyptian-fractions" + }, + { + "name": "eilenberg-ganea", + "path": "tasks/eilenberg-ganea" + }, + { + "name": "elasticity-uniqueness", + "path": "tasks/elasticity-uniqueness" + }, + { + "name": "elementary-positivity", + "path": "tasks/elementary-positivity" + }, + { + "name": "entangled-games", + "path": "tasks/entangled-games" + }, + { + "name": "entropy-photon-number", + "path": "tasks/entropy-photon-number" + }, + { + "name": "euclidean-five-color", + "path": "tasks/euclidean-five-color" + }, + { + "name": "euclidean-ramsey", + "path": "tasks/euclidean-ramsey" + }, + { + "name": "euclidean-ramsey-circle", + "path": "tasks/euclidean-ramsey-circle" + }, + { + "name": "euclidean-ramsey-nine", + "path": "tasks/euclidean-ramsey-nine" + }, + { + "name": "euclidean-ramsey-quadratic", + "path": "tasks/euclidean-ramsey-quadratic" + }, + { + "name": "euclidean-ramsey-spherical", + "path": "tasks/euclidean-ramsey-spherical" + }, + { + "name": "euclidean-ramsey-transitive", + "path": "tasks/euclidean-ramsey-transitive" + }, + { + "name": "even-barker", + "path": "tasks/even-barker" + }, + { + "name": "exact-fourier", + "path": "tasks/exact-fourier" + }, + { + "name": "exact-infiniteness", + "path": "tasks/exact-infiniteness" + }, + { + "name": "exact-quantum-factoring", + "path": "tasks/exact-quantum-factoring" + }, + { + "name": "fkcrt", + "path": "tasks/fkcrt" + }, + { + "name": "factor-generation", + "path": "tasks/factor-generation" + }, + { + "name": "falconer-all-dimensions", + "path": "tasks/falconer-all-dimensions" + }, + { + "name": "filling-coefficient", + "path": "tasks/filling-coefficient" + }, + { + "name": "finite-circle", + "path": "tasks/finite-circle" + }, + { + "name": "finite-congruence-graph", + "path": "tasks/finite-congruence-graph" + }, + { + "name": "finite-entropy-separation", + "path": "tasks/finite-entropy-separation" + }, + { + "name": "finite-factor", + "path": "tasks/finite-factor" + }, + { + "name": "finitistic-asymmetry", + "path": "tasks/finitistic-asymmetry" + }, + { + "name": "fixed-clause-threshold", + "path": "tasks/fixed-clause-threshold" + }, + { + "name": "forced-navier-stokes-computation", + "path": "tasks/forced-navier-stokes-computation" + }, + { + "name": "forest-space", + "path": "tasks/forest-space" + }, + { + "name": "formula-hitting", + "path": "tasks/formula-hitting" + }, + { + "name": "foulkes-howe", + "path": "tasks/foulkes-howe" + }, + { + "name": "four-row-permanent", + "path": "tasks/four-row-permanent" + }, + { + "name": "free-ising", + "path": "tasks/free-ising" + }, + { + "name": "free-uniform-spanning-forest", + "path": "tasks/free-uniform-spanning-forest" + }, + { + "name": "gamma-passage", + "path": "tasks/gamma-passage" + }, + { + "name": "gaussian-finite-entropy", + "path": "tasks/gaussian-finite-entropy" + }, + { + "name": "gaussian-information", + "path": "tasks/gaussian-information" + }, + { + "name": "gaussian-moat", + "path": "tasks/gaussian-moat" + }, + { + "name": "gaussian-propeller", + "path": "tasks/gaussian-propeller" + }, + { + "name": "gaussian-replacement", + "path": "tasks/gaussian-replacement" + }, + { + "name": "general-mahler", + "path": "tasks/general-mahler" + }, + { + "name": "generalized-star-height", + "path": "tasks/generalized-star-height" + }, + { + "name": "gotsman-linial", + "path": "tasks/gotsman-linial" + }, + { + "name": "graham-spherical", + "path": "tasks/graham-spherical" + }, + { + "name": "grothendieck-elementary-expansion", + "path": "tasks/grothendieck-elementary-expansion" + }, + { + "name": "group-ring-determinant", + "path": "tasks/group-ring-determinant" + }, + { + "name": "hadamard-cube-fiber", + "path": "tasks/hadamard-cube-fiber" + }, + { + "name": "halving-lines", + "path": "tasks/halving-lines" + }, + { + "name": "hard-sphere", + "path": "tasks/hard-sphere" + }, + { + "name": "harmonic-artin", + "path": "tasks/harmonic-artin" + }, + { + "name": "harmonic-growth", + "path": "tasks/harmonic-growth" + }, + { + "name": "heilbronn-triangle", + "path": "tasks/heilbronn-triangle" + }, + { + "name": "heisenberg", + "path": "tasks/heisenberg" + }, + { + "name": "henon-emden", + "path": "tasks/henon-emden" + }, + { + "name": "hilbert-crouzeix", + "path": "tasks/hilbert-crouzeix" + }, + { + "name": "honeycomb-bridge-finiteness", + "path": "tasks/honeycomb-bridge-finiteness" + }, + { + "name": "honeycomb-free-energy", + "path": "tasks/honeycomb-free-energy" + }, + { + "name": "hot-spots", + "path": "tasks/hot-spots" + }, + { + "name": "hyperbolic-cones", + "path": "tasks/hyperbolic-cones" + }, + { + "name": "hyperbolic-obstruction", + "path": "tasks/hyperbolic-obstruction" + }, + { + "name": "hyperinvariant-subspaces", + "path": "tasks/hyperinvariant-subspaces" + }, + { + "name": "independent-products", + "path": "tasks/independent-products" + }, + { + "name": "independent-sets", + "path": "tasks/independent-sets" + }, + { + "name": "individual-strong-infiniteness", + "path": "tasks/individual-strong-infiniteness" + }, + { + "name": "infinite-matroid", + "path": "tasks/infinite-matroid" + }, + { + "name": "infinite-matroid-corollaries", + "path": "tasks/infinite-matroid-corollaries" + }, + { + "name": "interpolated-factors", + "path": "tasks/interpolated-factors" + }, + { + "name": "irrational-rotation", + "path": "tasks/irrational-rotation" + }, + { + "name": "irrational-triangle-billiard", + "path": "tasks/irrational-triangle-billiard" + }, + { + "name": "ising-finiteness", + "path": "tasks/ising-finiteness" + }, + { + "name": "isometric-immersion", + "path": "tasks/isometric-immersion" + }, + { + "name": "kl-invariance", + "path": "tasks/kl-invariance" + }, + { + "name": "k-median-recovery", + "path": "tasks/k-median-recovery" + }, + { + "name": "k-median-refined-recovery", + "path": "tasks/k-median-refined-recovery" + }, + { + "name": "k-median-threshold", + "path": "tasks/k-median-threshold" + }, + { + "name": "k-server", + "path": "tasks/k-server" + }, + { + "name": "kadison-ringrose", + "path": "tasks/kadison-ringrose" + }, + { + "name": "kadison-similarity", + "path": "tasks/kadison-similarity" + }, + { + "name": "kahler-splitting", + "path": "tasks/kahler-splitting" + }, + { + "name": "kaplansky-direct-finiteness", + "path": "tasks/kaplansky-direct-finiteness" + }, + { + "name": "kaplansky-finitely-presented", + "path": "tasks/kaplansky-finitely-presented" + }, + { + "name": "kaplansky-quasitrace", + "path": "tasks/kaplansky-quasitrace" + }, + { + "name": "kaplansky-stable-finiteness", + "path": "tasks/kaplansky-stable-finiteness" + }, + { + "name": "kervaire", + "path": "tasks/kervaire" + }, + { + "name": "laughlin", + "path": "tasks/laughlin" + }, + { + "name": "laughlin-fock", + "path": "tasks/laughlin-fock" + }, + { + "name": "laughlin-gap", + "path": "tasks/laughlin-gap" + }, + { + "name": "laughlin-planar", + "path": "tasks/laughlin-planar" + }, + { + "name": "lieb-thirring", + "path": "tasks/lieb-thirring" + }, + { + "name": "lipschitz-equivalence", + "path": "tasks/lipschitz-equivalence" + }, + { + "name": "lipschitz-hilbert", + "path": "tasks/lipschitz-hilbert" + }, + { + "name": "list-hadwiger", + "path": "tasks/list-hadwiger" + }, + { + "name": "little-finitistic", + "path": "tasks/little-finitistic" + }, + { + "name": "littlewood-finite-flatness", + "path": "tasks/littlewood-finite-flatness" + }, + { + "name": "log-brunn-minkowski", + "path": "tasks/log-brunn-minkowski" + }, + { + "name": "log-concave-query", + "path": "tasks/log-concave-query" + }, + { + "name": "log-kodaira-fiber-negative", + "path": "tasks/log-kodaira-fiber-negative" + }, + { + "name": "mahler-conjecture", + "path": "tasks/mahler-conjecture" + }, + { + "name": "markov-type", + "path": "tasks/markov-type" + }, + { + "name": "mass-action", + "path": "tasks/mass-action" + }, + { + "name": "matching-affine-lift", + "path": "tasks/matching-affine-lift" + }, + { + "name": "matching-entropy", + "path": "tasks/matching-entropy" + }, + { + "name": "matching-entropy-bounds", + "path": "tasks/matching-entropy-bounds" + }, + { + "name": "matching-fpras", + "path": "tasks/matching-fpras" + }, + { + "name": "matching-psd", + "path": "tasks/matching-psd" + }, + { + "name": "matrix-fields", + "path": "tasks/matrix-fields" + }, + { + "name": "matrix-removal", + "path": "tasks/matrix-removal" + }, + { + "name": "matroid-prophet", + "path": "tasks/matroid-prophet" + }, + { + "name": "matroid-secretary", + "path": "tasks/matroid-secretary" + }, + { + "name": "maximal-seshadri-constants", + "path": "tasks/maximal-seshadri-constants" + }, + { + "name": "memory-precision", + "path": "tasks/memory-precision" + }, + { + "name": "metric-entropy-duality", + "path": "tasks/metric-entropy-duality" + }, + { + "name": "metric-k-median", + "path": "tasks/metric-k-median" + }, + { + "name": "midpoint-lenses", + "path": "tasks/midpoint-lenses" + }, + { + "name": "min-uncut", + "path": "tasks/min-uncut" + }, + { + "name": "nagata", + "path": "tasks/nagata" + }, + { + "name": "naimark", + "path": "tasks/naimark" + }, + { + "name": "navier-stokes-alternating", + "path": "tasks/navier-stokes-alternating" + }, + { + "name": "navier-stokes-velocity", + "path": "tasks/navier-stokes-velocity" + }, + { + "name": "nodal-length", + "path": "tasks/nodal-length" + }, + { + "name": "noiseless-regression", + "path": "tasks/noiseless-regression" + }, + { + "name": "odd-kaplansky", + "path": "tasks/odd-kaplansky" + }, + { + "name": "one-way-liveness", + "path": "tasks/one-way-liveness" + }, + { + "name": "optimal-max-cut", + "path": "tasks/optimal-max-cut" + }, + { + "name": "ordinary-elliott", + "path": "tasks/ordinary-elliott" + }, + { + "name": "parity-lifts", + "path": "tasks/parity-lifts" + }, + { + "name": "partial-permutation", + "path": "tasks/partial-permutation" + }, + { + "name": "partition-consistency", + "path": "tasks/partition-consistency" + }, + { + "name": "partition-principle", + "path": "tasks/partition-principle" + }, + { + "name": "perceptron-free-energy", + "path": "tasks/perceptron-free-energy" + }, + { + "name": "perfect-completeness", + "path": "tasks/perfect-completeness" + }, + { + "name": "periodic-group", + "path": "tasks/periodic-group" + }, + { + "name": "periodic-tiling-three", + "path": "tasks/periodic-tiling-three" + }, + { + "name": "permanent-cubic", + "path": "tasks/permanent-cubic" + }, + { + "name": "petty-projection-volume", + "path": "tasks/petty-projection-volume" + }, + { + "name": "pi-exponent", + "path": "tasks/pi-exponent" + }, + { + "name": "pinched-kahler", + "path": "tasks/pinched-kahler" + }, + { + "name": "pinned-distances", + "path": "tasks/pinned-distances" + }, + { + "name": "planar-anderson-spectrum", + "path": "tasks/planar-anderson-spectrum" + }, + { + "name": "planar-falconer", + "path": "tasks/planar-falconer" + }, + { + "name": "planar-first-passage", + "path": "tasks/planar-first-passage" + }, + { + "name": "planar-l1", + "path": "tasks/planar-l1" + }, + { + "name": "planar-unit-distances", + "path": "tasks/planar-unit-distances" + }, + { + "name": "plane-coloring", + "path": "tasks/plane-coloring" + }, + { + "name": "posterior-replicas", + "path": "tasks/posterior-replicas" + }, + { + "name": "power-free-values", + "path": "tasks/power-free-values" + }, + { + "name": "prime-gaps", + "path": "tasks/prime-gaps" + }, + { + "name": "product-brown", + "path": "tasks/product-brown" + }, + { + "name": "projection-counterexample", + "path": "tasks/projection-counterexample" + }, + { + "name": "projection-moments", + "path": "tasks/projection-moments" + }, + { + "name": "projection-volume", + "path": "tasks/projection-volume" + }, + { + "name": "qac-parity", + "path": "tasks/qac-parity" + }, + { + "name": "quadric-bundles", + "path": "tasks/quadric-bundles" + }, + { + "name": "quantitative-van-der-waerden", + "path": "tasks/quantitative-van-der-waerden" + }, + { + "name": "quintic-lienard", + "path": "tasks/quintic-lienard" + }, + { + "name": "radial-density-interval", + "path": "tasks/radial-density-interval" + }, + { + "name": "radial-transition", + "path": "tasks/radial-transition" + }, + { + "name": "randomized-mean-payoff", + "path": "tasks/randomized-mean-payoff" + }, + { + "name": "rational-hitting", + "path": "tasks/rational-hitting" + }, + { + "name": "real-l1-renorming", + "path": "tasks/real-l1-renorming" + }, + { + "name": "recursive-potentials", + "path": "tasks/recursive-potentials" + }, + { + "name": "reflexive-fixed-points", + "path": "tasks/reflexive-fixed-points" + }, + { + "name": "regular-parity", + "path": "tasks/regular-parity" + }, + { + "name": "relative-generation", + "path": "tasks/relative-generation" + }, + { + "name": "rokhlin", + "path": "tasks/rokhlin" + }, + { + "name": "ruled-covering", + "path": "tasks/ruled-covering" + }, + { + "name": "ryser-covering", + "path": "tasks/ryser-covering" + }, + { + "name": "ryser-odd-extensions", + "path": "tasks/ryser-odd-extensions" + }, + { + "name": "sat-sharpness", + "path": "tasks/sat-sharpness" + }, + { + "name": "sat-variance", + "path": "tasks/sat-variance" + }, + { + "name": "sk-full-support", + "path": "tasks/sk-full-support" + }, + { + "name": "sk-value", + "path": "tasks/sk-value" + }, + { + "name": "sle-lower-positivity", + "path": "tasks/sle-lower-positivity" + }, + { + "name": "saxl", + "path": "tasks/saxl" + }, + { + "name": "second-kahn-kalai", + "path": "tasks/second-kahn-kalai" + }, + { + "name": "self-similar", + "path": "tasks/self-similar" + }, + { + "name": "self-similar-corollaries", + "path": "tasks/self-similar-corollaries" + }, + { + "name": "sensitivity-separation", + "path": "tasks/sensitivity-separation" + }, + { + "name": "separable-quotient-negative", + "path": "tasks/separable-quotient-negative" + }, + { + "name": "seymour-second-neighborhood", + "path": "tasks/seymour-second-neighborhood" + }, + { + "name": "sharp-cat0-filling", + "path": "tasks/sharp-cat0-filling" + }, + { + "name": "sharp-threshold", + "path": "tasks/sharp-threshold" + }, + { + "name": "short-egyptian-fractions", + "path": "tasks/short-egyptian-fractions" + }, + { + "name": "sidorenko-counterexample", + "path": "tasks/sidorenko-counterexample" + }, + { + "name": "signed-finite-band", + "path": "tasks/signed-finite-band" + }, + { + "name": "signed-sweep-moment", + "path": "tasks/signed-sweep-moment" + }, + { + "name": "single-fold", + "path": "tasks/single-fold" + }, + { + "name": "single-lattice-covering", + "path": "tasks/single-lattice-covering" + }, + { + "name": "singleton-loop-matching", + "path": "tasks/singleton-loop-matching" + }, + { + "name": "smooth-initial-form", + "path": "tasks/smooth-initial-form" + }, + { + "name": "smooth-obstruction", + "path": "tasks/smooth-obstruction" + }, + { + "name": "soft-channel204", + "path": "tasks/soft-channel204" + }, + { + "name": "solenoidal-sheet-programs", + "path": "tasks/solenoidal-sheet-programs" + }, + { + "name": "spherical-field", + "path": "tasks/spherical-field" + }, + { + "name": "split-tangent-integrability", + "path": "tasks/split-tangent-integrability" + }, + { + "name": "square-difference", + "path": "tasks/square-difference" + }, + { + "name": "square-root-degree", + "path": "tasks/square-root-degree" + }, + { + "name": "standard-map-entropy", + "path": "tasks/standard-map-entropy" + }, + { + "name": "standard-map-lyapunov", + "path": "tasks/standard-map-lyapunov" + }, + { + "name": "steinitz-bergstrom", + "path": "tasks/steinitz-bergstrom" + }, + { + "name": "strict-means", + "path": "tasks/strict-means" + }, + { + "name": "strong-thin-tree", + "path": "tasks/strong-thin-tree" + }, + { + "name": "strongly-rayleigh-dpp", + "path": "tasks/strongly-rayleigh-dpp" + }, + { + "name": "structural-crouzeix", + "path": "tasks/structural-crouzeix" + }, + { + "name": "subpolynomial-lp", + "path": "tasks/subpolynomial-lp" + }, + { + "name": "subsphere-current", + "path": "tasks/subsphere-current" + }, + { + "name": "superstring", + "path": "tasks/superstring" + }, + { + "name": "switch-chain", + "path": "tasks/switch-chain" + }, + { + "name": "symmetric-domains", + "path": "tasks/symmetric-domains" + }, + { + "name": "symmetric-mahler-equality", + "path": "tasks/symmetric-mahler-equality" + }, + { + "name": "symmetric-polar", + "path": "tasks/symmetric-polar" + }, + { + "name": "tachikawa", + "path": "tasks/tachikawa" + }, + { + "name": "talagrand-discrete-convexity", + "path": "tasks/talagrand-discrete-convexity" + }, + { + "name": "talagrand-expectation-threshold", + "path": "tasks/talagrand-expectation-threshold" + }, + { + "name": "thomason-model-structures", + "path": "tasks/thomason-model-structures" + }, + { + "name": "thompson-nonamenability", + "path": "tasks/thompson-nonamenability" + }, + { + "name": "thorp-first-reciprocal", + "path": "tasks/thorp-first-reciprocal" + }, + { + "name": "thorp-remaining", + "path": "tasks/thorp-remaining" + }, + { + "name": "thorp-routing", + "path": "tasks/thorp-routing" + }, + { + "name": "thorp-weighted-compatibility", + "path": "tasks/thorp-weighted-compatibility" + }, + { + "name": "three-machine", + "path": "tasks/three-machine" + }, + { + "name": "three-state-supercritical", + "path": "tasks/three-state-supercritical" + }, + { + "name": "three-state-tree-clauses", + "path": "tasks/three-state-tree-clauses" + }, + { + "name": "three-torus", + "path": "tasks/three-torus" + }, + { + "name": "tingley-sphere-isometry", + "path": "tasks/tingley-sphere-isometry" + }, + { + "name": "torsion-free-hyperbolic", + "path": "tasks/torsion-free-hyperbolic" + }, + { + "name": "torsion-free-zero-divisors", + "path": "tasks/torsion-free-zero-divisors" + }, + { + "name": "trace-reconstruction", + "path": "tasks/trace-reconstruction" + }, + { + "name": "tree-edit", + "path": "tasks/tree-edit" + }, + { + "name": "triangle-face", + "path": "tasks/triangle-face" + }, + { + "name": "triangle-removal", + "path": "tasks/triangle-removal" + }, + { + "name": "triangular-covering", + "path": "tasks/triangular-covering" + }, + { + "name": "triangular-energy", + "path": "tasks/triangular-energy" + }, + { + "name": "triangular-gaussian", + "path": "tasks/triangular-gaussian" + }, + { + "name": "triangular-hilbert", + "path": "tasks/triangular-hilbert" + }, + { + "name": "truffet-counterexample", + "path": "tasks/truffet-counterexample" + }, + { + "name": "two-way-complementation", + "path": "tasks/two-way-complementation" + }, + { + "name": "two-way-determinization", + "path": "tasks/two-way-determinization" + }, + { + "name": "type-system-normalization", + "path": "tasks/type-system-normalization" + }, + { + "name": "uniform-commutator", + "path": "tasks/uniform-commutator" + }, + { + "name": "uniform-gamma", + "path": "tasks/uniform-gamma" + }, + { + "name": "uniform-k-server", + "path": "tasks/uniform-k-server" + }, + { + "name": "uniform-sparsest-cut", + "path": "tasks/uniform-sparsest-cut" + }, + { + "name": "unique-games-theorem", + "path": "tasks/unique-games-theorem" + }, + { + "name": "universal-f-infinity", + "path": "tasks/universal-f-infinity" + }, + { + "name": "variable-wl", + "path": "tasks/variable-wl" + }, + { + "name": "velocity-hemisphere", + "path": "tasks/velocity-hemisphere" + }, + { + "name": "vertex-algebra-net", + "path": "tasks/vertex-algebra-net" + }, + { + "name": "vertex-cover", + "path": "tasks/vertex-cover" + }, + { + "name": "vlasov-maxwell", + "path": "tasks/vlasov-maxwell" + }, + { + "name": "wl-identification", + "path": "tasks/wl-identification" + }, + { + "name": "weak-hessian", + "path": "tasks/weak-hessian" + }, + { + "name": "weak-mtw-global-support", + "path": "tasks/weak-mtw-global-support" + }, + { + "name": "weighted-sweep-moments", + "path": "tasks/weighted-sweep-moments" + }, + { + "name": "weisfeiler-leman", + "path": "tasks/weisfeiler-leman" + }, + { + "name": "witnessed-choice", + "path": "tasks/witnessed-choice" + }, + { + "name": "yau-counterexample", + "path": "tasks/yau-counterexample" + } + ] + } +] diff --git a/tasks/abhyankar-sathaye/environment/Dockerfile b/tasks/abhyankar-sathaye/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/abhyankar-sathaye/environment/fetch_mathlib.sh b/tasks/abhyankar-sathaye/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/abhyankar-sathaye/environment/lake-manifest.json b/tasks/abhyankar-sathaye/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/abhyankar-sathaye/environment/lakefile.lean b/tasks/abhyankar-sathaye/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/abhyankar-sathaye/environment/lean_setup.sh b/tasks/abhyankar-sathaye/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/abhyankar-sathaye/environment/pack_submission.py b/tasks/abhyankar-sathaye/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/abhyankar-sathaye/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/abhyankar-sathaye/instruction.md b/tasks/abhyankar-sathaye/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..05d4b89293a0fcd7b19688ba8a4818d2e31fe65b --- /dev/null +++ b/tasks/abhyankar-sathaye/instruction.md @@ -0,0 +1,72 @@ +# openai/math challenge `AbhyankarSathaye` (family 049) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 049 of the release, *A stable-coordinate counterexample in four variables* +(Algebraic and complex geometry). The family as a whole: Constructs a polynomial in four complex variables that is not a coordinate but becomes one after adjoining a single variable, disproving the Stable Coordinate conjecture in four variables. Every fiber is affine three-space, yet none of its embeddings is rectifiable, also disproving the Abhyankar–Sathaye conjecture even when all fibers are affine spaces. + +The challenge is `AbhyankarSathaye`, also at `/opt/openai-math/challenges/AbhyankarSathaye.lean`: + +```lean +import Mathlib.Algebra.MvPolynomial.CommRing +import Mathlib.Basic.Complex.Basic +import Mathlib.RingTheory.Ideal.Quotient.Operations + +namespace OAI + +namespace AbhyankarSathaye + +/-- In every dimension at least four, a polynomial can define affine space +without being a coordinate of the ambient polynomial ring. -/ +theorem exists_noncoordinate_polynomial (n : ℕ) (hn : 4 ≤ n) : + ∃ F : MvPolynomial (Fin n) ℂ, + Nonempty ((MvPolynomial (Fin n) ℂ ⧸ Ideal.span {F}) ≃ₐ[ℂ] + MvPolynomial (Fin (n - 1)) ℂ) ∧ + ¬ ∃ (equiv : MvPolynomial (Fin n) ℂ ≃ₐ[ℂ] MvPolynomial (Fin n) ℂ) + (index : Fin n), equiv (MvPolynomial.X index) = F := by + sorry + +end AbhyankarSathaye + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AbhyankarSathaye.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AbhyankarSathaye.exists_noncoordinate_polynomial` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/abhyankar-sathaye/solution/closure.txt b/tasks/abhyankar-sathaye/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5f46b17143514b58d636d18229ef145c7237043e --- /dev/null +++ b/tasks/abhyankar-sathaye/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.AlgebraicGeometry.AbhyankarSathaye.Counterexample +OAI.AlgebraicGeometry.AbhyankarSathaye.CriticalPoint +OAI.AlgebraicGeometry.AbhyankarSathaye.Fiber +OAI.AlgebraicGeometry.AbhyankarSathaye.FiberFormulas +OAI.AlgebraicGeometry.AbhyankarSathaye.Identities +OAI.AlgebraicGeometry.AbhyankarSathaye.Lifting +OAI.AlgebraicGeometry.AbhyankarSathaye.LiftingIdentities +OAI.AlgebraicGeometry.AbhyankarSathaye.LinearElimination +OAI.AlgebraicGeometry.AbhyankarSathaye.LinearPresentation +OAI.AlgebraicGeometry.AbhyankarSathaye.NonCoordinate +OAI.AlgebraicGeometry.AbhyankarSathaye.Plane +OAI.AlgebraicGeometry.AbhyankarSathaye.Presentation +OAI.AlgebraicGeometry.AbhyankarSathaye.Quotient +OAI.AlgebraicGeometry.AbhyankarSathaye.Reconstruction +OAI.AlgebraicGeometry.AbhyankarSathaye.Stabilization diff --git a/tasks/abhyankar-sathaye/solution/reference.py b/tasks/abhyankar-sathaye/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/abhyankar-sathaye/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/abhyankar-sathaye/solution/solve.sh b/tasks/abhyankar-sathaye/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3268b6100fd41bbc4e9448a98c47bb2293599683 --- /dev/null +++ b/tasks/abhyankar-sathaye/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AbhyankarSathaye, i.e. module OAI.AlgebraicGeometry.AbhyankarSathaye.Counterexample and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.AlgebraicGeometry.AbhyankarSathaye.Counterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AbhyankarSathaye" diff --git a/tasks/abhyankar-sathaye/task.toml b/tasks/abhyankar-sathaye/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3b68e62f4686ddedaf29faae3aae57789ba0212d --- /dev/null +++ b/tasks/abhyankar-sathaye/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/abhyankar-sathaye" +version = "1.0.0" +description = "Prove AbhyankarSathaye (openai/math family 049: A stable-coordinate counterexample in four variables) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AbhyankarSathaye.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AbhyankarSathaye" +family = "049" +family_title = "A stable-coordinate counterexample in four variables" +subject = "Algebraic and complex geometry" +theorems = ["OAI.AbhyankarSathaye.exists_noncoordinate_polynomial"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.AlgebraicGeometry.AbhyankarSathaye.Counterexample" +reference_modules = 15 +reference_lean_bytes = 55824 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 463 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11750 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/abhyankar-sathaye/tests/Challenge.lean b/tasks/abhyankar-sathaye/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ae48f1b8a118307b7af85be71e1cfec0b4ab29d4 --- /dev/null +++ b/tasks/abhyankar-sathaye/tests/Challenge.lean @@ -0,0 +1,21 @@ +import Mathlib.Algebra.MvPolynomial.CommRing +import Mathlib.Basic.Complex.Basic +import Mathlib.RingTheory.Ideal.Quotient.Operations + +namespace OAI + +namespace AbhyankarSathaye + +/-- In every dimension at least four, a polynomial can define affine space +without being a coordinate of the ambient polynomial ring. -/ +theorem exists_noncoordinate_polynomial (n : ℕ) (hn : 4 ≤ n) : + ∃ F : MvPolynomial (Fin n) ℂ, + Nonempty ((MvPolynomial (Fin n) ℂ ⧸ Ideal.span {F}) ≃ₐ[ℂ] + MvPolynomial (Fin (n - 1)) ℂ) ∧ + ¬ ∃ (equiv : MvPolynomial (Fin n) ℂ ≃ₐ[ℂ] MvPolynomial (Fin n) ℂ) + (index : Fin n), equiv (MvPolynomial.X index) = F := by + sorry + +end AbhyankarSathaye + +end OAI diff --git a/tasks/abhyankar-sathaye/tests/grade.py b/tasks/abhyankar-sathaye/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/abhyankar-sathaye/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/abhyankar-sathaye/tests/task.json b/tasks/abhyankar-sathaye/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..790268ea7da7708e9cd222287d59694e40af5eb0 --- /dev/null +++ b/tasks/abhyankar-sathaye/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AbhyankarSathaye", + "comparator": { + "theorem_names": [ + "OAI.AbhyankarSathaye.exists_noncoordinate_polynomial" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10850 +} \ No newline at end of file diff --git a/tasks/abhyankar-sathaye/tests/test.sh b/tasks/abhyankar-sathaye/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/abhyankar-sathaye/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/affine-bernstein/environment/Dockerfile b/tasks/affine-bernstein/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/affine-bernstein/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/affine-bernstein/environment/fetch_mathlib.sh b/tasks/affine-bernstein/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/affine-bernstein/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/affine-bernstein/environment/lake-manifest.json b/tasks/affine-bernstein/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/affine-bernstein/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/affine-bernstein/environment/lakefile.lean b/tasks/affine-bernstein/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/affine-bernstein/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/affine-bernstein/environment/lean_setup.sh b/tasks/affine-bernstein/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/affine-bernstein/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/affine-bernstein/environment/pack_submission.py b/tasks/affine-bernstein/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/affine-bernstein/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/affine-bernstein/instruction.md b/tasks/affine-bernstein/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..618af5027c897213c4ca1ede509ef27365daa133 --- /dev/null +++ b/tasks/affine-bernstein/instruction.md @@ -0,0 +1,145 @@ +# openai/math challenge `AffineBernstein` (family 353) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 353 of the release, *The sharp dimension threshold for affine Bernstein rigidity* +(Differential geometry). The family as a whole: Proves that every smooth locally uniformly convex affine-maximal graph of dimension three through nine, complete for its induced Euclidean metric, is an elliptic paraboloid. A smooth entire nonquadratic example in dimension ten makes this range sharp. In dimensions three through nine, the paraboloid classification also holds for connected open locally uniformly convex affine-maximal hypersurfaces complete for the affine Berwald–Blaschke metric. + +The challenge is `AffineBernstein`, also at `/opt/openai-math/challenges/AffineBernstein.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped BigOperators ContDiff ENNReal + +namespace AffineBernstein + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def coordinateVector (n : ℕ) (i : Fin n) : Space n := + EuclideanSpace.single i 1 + +/-- Coordinate Hessian. On the open domain it depends only on the restriction of `u`. +The order of the two differentiations is immaterial under the smoothness hypothesis. -/ +def hessian {n : ℕ} (u : Space n → ℝ) (x : Space n) : Matrix (Fin n) (Fin n) ℝ := + fun i j => fderiv ℝ (fun y => fderiv ℝ u y (coordinateVector n j)) x + (coordinateVector n i) + +/-- The coefficient U^{ij} = det(D²u) (D²u)^{-1}_{ij}. -/ +def cofactorHessian {n : ℕ} (u : Space n → ℝ) (x : Space n) : + Matrix (Fin n) (Fin n) ℝ := + (hessian u x).det • (hessian u x)⁻¹ + +/-- The classical determinant weight; in particular, this is not a generalized exponent. -/ +def affineWeight {n : ℕ} (u : Space n → ℝ) (x : Space n) : ℝ := + Real.rpow (hessian u x).det (-(((n : ℝ) + 1) / ((n : ℝ) + 2))) + +def AffineMaximalOn {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Prop := + ∀ x ∈ Ω, ∑ i : Fin n, ∑ j : Fin n, + cofactorHessian u x i j * hessian (affineWeight u) x i j = 0 + +/-- Length on [0,1] for g_x(v,v) = ‖v‖² + (Du_x v)², the metric induced +by the Euclidean graph embedding x ↦ (x,u(x)). The product norm on Lean's ordinary +product type is NOT used (it would be the maximum norm). -/ +def graphPathLength {n : ℕ} (u : Space n → ℝ) (γ : ℝ → Space n) : ℝ≥0∞ := + ∫⁻ t in Icc (0 : ℝ) 1, + ENNReal.ofReal (Real.sqrt + (‖derivWithin γ (Icc (0 : ℝ) 1) t‖ ^ 2 + + (fderiv ℝ u (γ t) (derivWithin γ (Icc (0 : ℝ) 1) t)) ^ 2)) + +/-- The intrinsic extended distance: infimum of lengths of C¹ paths in the domain. +Using a single C¹ path gives the same intrinsic distance as piecewise C¹ paths, +by smooth endpoint reparameterization and concatenation. -/ +def graphEDist {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) + (x y : Space n) : ℝ≥0∞ := + ⨅ (γ : ℝ → Space n) + (_ : ContDiffOn ℝ 1 γ (Icc (0 : ℝ) 1)) + (_ : MapsTo γ (Icc (0 : ℝ) 1) Ω) + (_ : γ 0 = x) (_ : γ 1 = y), graphPathLength u γ + +/-- Sequential completeness for the induced Euclidean path metric. This states +that every intrinsic Cauchy sequence of points in Ω has an intrinsic limit in Ω. +It imposes no growth condition and no completeness condition on the affine metric. -/ +def EuclideanGraphComplete {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Prop := + ∀ x : ℕ → Space n, (∀ i, x i ∈ Ω) → + (∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ i ≥ N, ∀ j ≥ N, + graphEDist Ω u (x i) (x j) < ENNReal.ofReal ε) → + ∃ a ∈ Ω, ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ i ≥ N, + graphEDist Ω u (x i) a < ENNReal.ofReal ε + +/-- The graph, regarded as an affine subset of R^{n+1}. -/ +def graph {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Set (Space n × ℝ) := + {p | p.1 ∈ Ω ∧ p.2 = u p.1} + +def standardParaboloid (n : ℕ) : Set (Space n × ℝ) := + {p | p.2 = ∑ i : Fin n, (p.1 i) ^ 2} + +/-- Literal main theorem, with its stated affine-image consequence. -/ +theorem affine_bernstein + (n : ℕ) (hn₃ : 3 ≤ n) (hn₉ : n ≤ 9) + (Ω : Set (Space n)) (hΩne : Ω.Nonempty) (hΩopen : IsOpen Ω) + (hΩconvex : Convex ℝ Ω) (u : Space n → ℝ) + (hu : ContDiffOn ℝ ∞ u Ω) + (hpos : ∀ x ∈ Ω, (hessian u x).PosDef) + (hmax : AffineMaximalOn Ω u) + (hcomplete : EuclideanGraphComplete Ω u) : + Ω = univ ∧ + (∃ (A : Matrix (Fin n) (Fin n) ℝ) (b : Space n) (c : ℝ), + A.IsSymm ∧ A.PosDef ∧ + ∀ x, u x = (1 / 2 : ℝ) * (∑ i : Fin n, ∑ j : Fin n, x i * A i j * x j) + + (∑ i : Fin n, b i * x i) + c) ∧ + (∃ e : (Space n × ℝ) ≃ᵃ[ℝ] (Space n × ℝ), + e '' standardParaboloid n = graph Ω u) := by + sorry + +end AffineBernstein + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AffineBernstein.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AffineBernstein.affine_bernstein` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/affine-bernstein/solution/closure.txt b/tasks/affine-bernstein/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d10826364b14d06b9b82777fe4444514aa845f7 --- /dev/null +++ b/tasks/affine-bernstein/solution/closure.txt @@ -0,0 +1,322 @@ +OAI.Analysis.AffineBernstein.ABPCriticalDensity +OAI.Analysis.AffineBernstein.ABPMatrix +OAI.Analysis.AffineBernstein.ActualAmbientFEquation +OAI.Analysis.AffineBernstein.ActualAngularSupport +OAI.Analysis.AffineBernstein.ActualAreaMass +OAI.Analysis.AffineBernstein.ActualBaseCurvature +OAI.Analysis.AffineBernstein.ActualBaseMinors +OAI.Analysis.AffineBernstein.ActualChartArea +OAI.Analysis.AffineBernstein.ActualConormalScale +OAI.Analysis.AffineBernstein.ActualFiberArea +OAI.Analysis.AffineBernstein.ActualFlatFEquation +OAI.Analysis.AffineBernstein.ActualFlatInverse +OAI.Analysis.AffineBernstein.ActualFlatWeakEuler +OAI.Analysis.AffineBernstein.ActualGlobalAngular +OAI.Analysis.AffineBernstein.ActualGlobalBase +OAI.Analysis.AffineBernstein.ActualGlobalCoercive +OAI.Analysis.AffineBernstein.ActualGlobalD +OAI.Analysis.AffineBernstein.ActualGlobalP +OAI.Analysis.AffineBernstein.ActualInvariantTube +OAI.Analysis.AffineBernstein.ActualInverseMetric +OAI.Analysis.AffineBernstein.ActualLogCells +OAI.Analysis.AffineBernstein.ActualLogEnergy +OAI.Analysis.AffineBernstein.ActualLogGrowth +OAI.Analysis.AffineBernstein.ActualLogInequality +OAI.Analysis.AffineBernstein.ActualLogMeasure +OAI.Analysis.AffineBernstein.ActualLogMeasureEnergy +OAI.Analysis.AffineBernstein.ActualLogMeasureFurther +OAI.Analysis.AffineBernstein.ActualProductBounds +OAI.Analysis.AffineBernstein.ActualProjectiveAreaChart +OAI.Analysis.AffineBernstein.ActualProjectiveDensity +OAI.Analysis.AffineBernstein.ActualProjectiveInverse +OAI.Analysis.AffineBernstein.ActualRoundFEquation +OAI.Analysis.AffineBernstein.ActualSigmaInterpolation +OAI.Analysis.AffineBernstein.ActualSupportVariation +OAI.Analysis.AffineBernstein.ActualTubeArea +OAI.Analysis.AffineBernstein.ActualTubeEnergy +OAI.Analysis.AffineBernstein.ActualTubeMetricPositivity +OAI.Analysis.AffineBernstein.ActualTubeSecond +OAI.Analysis.AffineBernstein.ActualTubeWeights +OAI.Analysis.AffineBernstein.ActualWeightedAngular +OAI.Analysis.AffineBernstein.ActualWeightedAngularFurther +OAI.Analysis.AffineBernstein.ActualWeightedBase +OAI.Analysis.AffineBernstein.ActualWeightedG +OAI.Analysis.AffineBernstein.ActualWeightedLog +OAI.Analysis.AffineBernstein.AffineBoxArea +OAI.Analysis.AffineBernstein.AffineCapArea +OAI.Analysis.AffineBernstein.AffineCapGeometry +OAI.Analysis.AffineBernstein.AffineCapLIntegral +OAI.Analysis.AffineBernstein.AffineFamily +OAI.Analysis.AffineBernstein.AffineGaussSurjectivity +OAI.Analysis.AffineBernstein.AffineImageCoordinates +OAI.Analysis.AffineBernstein.AffineInvariantCap +OAI.Analysis.AffineBernstein.AffineParametricStationarity +OAI.Analysis.AffineBernstein.AffineStripArea +OAI.Analysis.AffineBernstein.AffineSupport +OAI.Analysis.AffineBernstein.AmbientImmersion +OAI.Analysis.AffineBernstein.AmbientStraightening +OAI.Analysis.AffineBernstein.AngularCalculus +OAI.Analysis.AffineBernstein.AngularCofactor +OAI.Analysis.AffineBernstein.BaseConcavity +OAI.Analysis.AffineBernstein.BaseExponentialIBP +OAI.Analysis.AffineBernstein.BaseLogIdentity +OAI.Analysis.AffineBernstein.BaseWeightedIBP +OAI.Analysis.AffineBernstein.BaseWeightedIntegral +OAI.Analysis.AffineBernstein.Basic +OAI.Analysis.AffineBernstein.BilinearNewton +OAI.Analysis.AffineBernstein.BlockNewton +OAI.Analysis.AffineBernstein.BoundedHarmonic +OAI.Analysis.AffineBernstein.CapArea +OAI.Analysis.AffineBernstein.CapChangeOfVariables +OAI.Analysis.AffineBernstein.CapCoordinates +OAI.Analysis.AffineBernstein.CapCovariance +OAI.Analysis.AffineBernstein.CapGeometry +OAI.Analysis.AffineBernstein.CapInverseBound +OAI.Analysis.AffineBernstein.CapPerturbation +OAI.Analysis.AffineBernstein.CofactorCodazzi +OAI.Analysis.AffineBernstein.CompactDifferentiation +OAI.Analysis.AffineBernstein.CompactIntegration +OAI.Analysis.AffineBernstein.CompletePositiveCap +OAI.Analysis.AffineBernstein.CompletePositiveCapFurther +OAI.Analysis.AffineBernstein.CompleteSphericalCaps +OAI.Analysis.AffineBernstein.ConjugationNewton +OAI.Analysis.AffineBernstein.ConstantDet +OAI.Analysis.AffineBernstein.ConstantDetCalculus +OAI.Analysis.AffineBernstein.ConstantHessianQuadratic +OAI.Analysis.AffineBernstein.ConvexGradientBound +OAI.Analysis.AffineBernstein.ConvexLocalLimits +OAI.Analysis.AffineBernstein.ConvexSmoothMax +OAI.Analysis.AffineBernstein.DensityTransform +OAI.Analysis.AffineBernstein.DetBarrierBound +OAI.Analysis.AffineBernstein.DetBarrierPhase +OAI.Analysis.AffineBernstein.DetCompactBound +OAI.Analysis.AffineBernstein.DetInteriorBall +OAI.Analysis.AffineBernstein.DeterminantVariation +OAI.Analysis.AffineBernstein.DirectionalJacobi +OAI.Analysis.AffineBernstein.DualDetBarrier +OAI.Analysis.AffineBernstein.DualDetBound +OAI.Analysis.AffineBernstein.DualDetCompact +OAI.Analysis.AffineBernstein.DualDetPhase +OAI.Analysis.AffineBernstein.DualHeightCalculus +OAI.Analysis.AffineBernstein.EllipticComparison +OAI.Analysis.AffineBernstein.EntireAndDoubling +OAI.Analysis.AffineBernstein.EntireGlobalDet +OAI.Analysis.AffineBernstein.EntireGraphComplete +OAI.Analysis.AffineBernstein.EuclideanChain +OAI.Analysis.AffineBernstein.FaceSigmaTransport +OAI.Analysis.AffineBernstein.FiberArea +OAI.Analysis.AffineBernstein.FiniteAreaCover +OAI.Analysis.AffineBernstein.FiniteProjectiveCharts +OAI.Analysis.AffineBernstein.FixedBasisCoordinates +OAI.Analysis.AffineBernstein.FlatBlockCalculus +OAI.Analysis.AffineBernstein.FlatChartInjective +OAI.Analysis.AffineBernstein.FlatEulerCore +OAI.Analysis.AffineBernstein.FlatFCalculus +OAI.Analysis.AffineBernstein.FlatFEquation +OAI.Analysis.AffineBernstein.FlatGraphCoverage +OAI.Analysis.AffineBernstein.FlatInverseMetric +OAI.Analysis.AffineBernstein.FlatLogCalculus +OAI.Analysis.AffineBernstein.FlatLogEuler +OAI.Analysis.AffineBernstein.FlatParametricArea +OAI.Analysis.AffineBernstein.FlatProductCoordinates +OAI.Analysis.AffineBernstein.FlatSupportImmersion +OAI.Analysis.AffineBernstein.FlatTestHessian +OAI.Analysis.AffineBernstein.FlatTubeArea +OAI.Analysis.AffineBernstein.FlatTubeChart +OAI.Analysis.AffineBernstein.FlatTubeEuler +OAI.Analysis.AffineBernstein.FlatTubePositive +OAI.Analysis.AffineBernstein.FlatWeightedEuler +OAI.Analysis.AffineBernstein.GaussCoordinates +OAI.Analysis.AffineBernstein.GaussSurjectivity +OAI.Analysis.AffineBernstein.GeneralCapCoordinates +OAI.Analysis.AffineBernstein.GeneralPositiveCap +OAI.Analysis.AffineBernstein.GlobalDetRatio +OAI.Analysis.AffineBernstein.GlobalFlatAreaLIntegral +OAI.Analysis.AffineBernstein.GlobalFlatInverseLIntegral +OAI.Analysis.AffineBernstein.GlobalGraphChart +OAI.Analysis.AffineBernstein.GlobalHessianBound +OAI.Analysis.AffineBernstein.GraphAreaCharts +OAI.Analysis.AffineBernstein.GraphBallArea +OAI.Analysis.AffineBernstein.GraphParametricArea +OAI.Analysis.AffineBernstein.GraphPatchArea +OAI.Analysis.AffineBernstein.HessianCompactness +OAI.Analysis.AffineBernstein.HessianDivergence +OAI.Analysis.AffineBernstein.HessianDominance +OAI.Analysis.AffineBernstein.HessianMinors +OAI.Analysis.AffineBernstein.HessianTraceIntegral +OAI.Analysis.AffineBernstein.HessianVariation +OAI.Analysis.AffineBernstein.HomogeneousSphere +OAI.Analysis.AffineBernstein.ImmersionStationary +OAI.Analysis.AffineBernstein.IntegratedParametricStationarity +OAI.Analysis.AffineBernstein.InteriorLimits +OAI.Analysis.AffineBernstein.InverseTracePullback +OAI.Analysis.AffineBernstein.JetCalculus +OAI.Analysis.AffineBernstein.JointAngularCalculus +OAI.Analysis.AffineBernstein.JointTubeMetrics +OAI.Analysis.AffineBernstein.LinearLogTrace +OAI.Analysis.AffineBernstein.LinearNormalizationCalculus +OAI.Analysis.AffineBernstein.LinearSphere +OAI.Analysis.AffineBernstein.LinearizedNormalization +OAI.Analysis.AffineBernstein.LocalAreaStationarity +OAI.Analysis.AffineBernstein.LocalDet +OAI.Analysis.AffineBernstein.LocalMaximumHessian +OAI.Analysis.AffineBernstein.LocalMaximumSecond +OAI.Analysis.AffineBernstein.LocalVelocity +OAI.Analysis.AffineBernstein.LogBarrierCalculus +OAI.Analysis.AffineBernstein.LogCaccioppoli +OAI.Analysis.AffineBernstein.LogCellBound +OAI.Analysis.AffineBernstein.LogDetGradientEnergy +OAI.Analysis.AffineBernstein.LogMassWeight +OAI.Analysis.AffineBernstein.LogTubeMeasure +OAI.Analysis.AffineBernstein.LogVariance +OAI.Analysis.AffineBernstein.Main +OAI.Analysis.AffineBernstein.MassIntegral +OAI.Analysis.AffineBernstein.MassInterpolation +OAI.Analysis.AffineBernstein.MassUpper +OAI.Analysis.AffineBernstein.MatrixCombination +OAI.Analysis.AffineBernstein.MatrixConcavity +OAI.Analysis.AffineBernstein.MatrixDetRigidity +OAI.Analysis.AffineBernstein.MatrixMetric +OAI.Analysis.AffineBernstein.MatrixShiftBound +OAI.Analysis.AffineBernstein.MatrixShiftDet +OAI.Analysis.AffineBernstein.MatrixUniformBounds +OAI.Analysis.AffineBernstein.MaximalModelExclusion +OAI.Analysis.AffineBernstein.ModelCentering +OAI.Analysis.AffineBernstein.ModelCenteringFurther +OAI.Analysis.AffineBernstein.ModelFaceMass +OAI.Analysis.AffineBernstein.ModelLimit +OAI.Analysis.AffineBernstein.ModelPositiveLogMass +OAI.Analysis.AffineBernstein.ModelPositiveSigma +OAI.Analysis.AffineBernstein.NewtonBasis +OAI.Analysis.AffineBernstein.NewtonBasisFurther +OAI.Analysis.AffineBernstein.NewtonField +OAI.Analysis.AffineBernstein.NewtonPiola +OAI.Analysis.AffineBernstein.NewtonTensor +OAI.Analysis.AffineBernstein.NoNormalizedMaximalModel +OAI.Analysis.AffineBernstein.NoOrthant +OAI.Analysis.AffineBernstein.NoZeroTransverse +OAI.Analysis.AffineBernstein.NormalizedCaps +OAI.Analysis.AffineBernstein.NormalizedCellGeometry +OAI.Analysis.AffineBernstein.NormalizedCriticalDensity +OAI.Analysis.AffineBernstein.NormalizedDet +OAI.Analysis.AffineBernstein.NormalizedFamilyDet +OAI.Analysis.AffineBernstein.NormalizedHessianUpper +OAI.Analysis.AffineBernstein.NormalizedLogVariance +OAI.Analysis.AffineBernstein.NormalizedSigma +OAI.Analysis.AffineBernstein.NormalizedSigmaTransport +OAI.Analysis.AffineBernstein.NormedCompactInterior +OAI.Analysis.AffineBernstein.NormedInteriorLimits +OAI.Analysis.AffineBernstein.OrthantGeometry +OAI.Analysis.AffineBernstein.OrthantHeight +OAI.Analysis.AffineBernstein.ParametricAffineArea +OAI.Analysis.AffineBernstein.ParametricBasis +OAI.Analysis.AffineBernstein.ParametricChangeOfCoordinates +OAI.Analysis.AffineBernstein.ParametricChartStationarity +OAI.Analysis.AffineBernstein.ParametricChoiceTransport +OAI.Analysis.AffineBernstein.ParametricChoices +OAI.Analysis.AffineBernstein.ParametricDensityCoordinates +OAI.Analysis.AffineBernstein.ParametricFirstVariation +OAI.Analysis.AffineBernstein.ParametricGraphJets +OAI.Analysis.AffineBernstein.ParametricInverseMetric +OAI.Analysis.AffineBernstein.ParametricNormalization +OAI.Analysis.AffineBernstein.ParametricSmoothness +OAI.Analysis.AffineBernstein.ParametricStationarity +OAI.Analysis.AffineBernstein.ParametricTransport +OAI.Analysis.AffineBernstein.ParametricVariationAlgebra +OAI.Analysis.AffineBernstein.PiolaAlgebra +OAI.Analysis.AffineBernstein.PiolaDifferential +OAI.Analysis.AffineBernstein.PositiveDerivative +OAI.Analysis.AffineBernstein.PositiveFaceLimit +OAI.Analysis.AffineBernstein.PositiveFaceMass +OAI.Analysis.AffineBernstein.PositiveLimitCap +OAI.Analysis.AffineBernstein.PositiveMassAlgebra +OAI.Analysis.AffineBernstein.PositiveMatrixTraceBound +OAI.Analysis.AffineBernstein.ProductAmbientCoordinates +OAI.Analysis.AffineBernstein.ProductAreaChart +OAI.Analysis.AffineBernstein.ProductEquator +OAI.Analysis.AffineBernstein.ProjectiveCone +OAI.Analysis.AffineBernstein.ProjectiveDensity +OAI.Analysis.AffineBernstein.ProjectiveEnergyContinuity +OAI.Analysis.AffineBernstein.ProjectiveHemisphere +OAI.Analysis.AffineBernstein.ProjectiveInverseWeight +OAI.Analysis.AffineBernstein.ProjectiveNormalized +OAI.Analysis.AffineBernstein.ProjectiveWeightContinuity +OAI.Analysis.AffineBernstein.QuadraticAffineImage +OAI.Analysis.AffineBernstein.QuadraticIntegration +OAI.Analysis.AffineBernstein.RadialAdjugate +OAI.Analysis.AffineBernstein.RadialAdjugateGL +OAI.Analysis.AffineBernstein.RegularFiberDomain +OAI.Analysis.AffineBernstein.RoundCofactorInverse +OAI.Analysis.AffineBernstein.RoundContractions +OAI.Analysis.AffineBernstein.RoundSliceContractions +OAI.Analysis.AffineBernstein.SectionNormalizationFamily +OAI.Analysis.AffineBernstein.SegmentEnergy +OAI.Analysis.AffineBernstein.SigmaBaseTransport +OAI.Analysis.AffineBernstein.SigmaCapHelpers +OAI.Analysis.AffineBernstein.SigmaNormalization +OAI.Analysis.AffineBernstein.SigmaTransform +OAI.Analysis.AffineBernstein.SimultaneousMinima +OAI.Analysis.AffineBernstein.SmoothCapTest +OAI.Analysis.AffineBernstein.SmoothCoefficients +OAI.Analysis.AffineBernstein.SmoothGraphChart +OAI.Analysis.AffineBernstein.SmoothParameter +OAI.Analysis.AffineBernstein.SmoothPositivePart +OAI.Analysis.AffineBernstein.SphereAlgebra +OAI.Analysis.AffineBernstein.SphereDivergence +OAI.Analysis.AffineBernstein.SphereIntegration +OAI.Analysis.AffineBernstein.SphereIsometry +OAI.Analysis.AffineBernstein.SphereTensorCalculus +OAI.Analysis.AffineBernstein.SphericalAreaContinuity +OAI.Analysis.AffineBernstein.SupersolutionHighSet +OAI.Analysis.AffineBernstein.SupportAnnulus +OAI.Analysis.AffineBernstein.SupportArea +OAI.Analysis.AffineBernstein.SupportCoordinates +OAI.Analysis.AffineBernstein.SupportGeometry +OAI.Analysis.AffineBernstein.SupportHomogeneity +OAI.Analysis.AffineBernstein.SupportOrientation +OAI.Analysis.AffineBernstein.SupportRadial +OAI.Analysis.AffineBernstein.SupportVariation +OAI.Analysis.AffineBernstein.SupportVariationJets +OAI.Analysis.AffineBernstein.TangentShiftCalculus +OAI.Analysis.AffineBernstein.TargetCapLIntegral +OAI.Analysis.AffineBernstein.TensorFlux +OAI.Analysis.AffineBernstein.TensorIntegration +OAI.Analysis.AffineBernstein.ThinSlices +OAI.Analysis.AffineBernstein.TiltedLIntegral +OAI.Analysis.AffineBernstein.TiltedTrace +OAI.Analysis.AffineBernstein.TracefreeMatrix +OAI.Analysis.AffineBernstein.TranslateDet +OAI.Analysis.AffineBernstein.TriangularGraph +OAI.Analysis.AffineBernstein.TubeChartConstruction +OAI.Analysis.AffineBernstein.TubeCombination +OAI.Analysis.AffineBernstein.TubeCompactIntegral +OAI.Analysis.AffineBernstein.TubeDensity +OAI.Analysis.AffineBernstein.TubeDensityIntegralCompact +OAI.Analysis.AffineBernstein.TubeDensityVariation +OAI.Analysis.AffineBernstein.TubeFrame +OAI.Analysis.AffineBernstein.TubeInvariantSmooth +OAI.Analysis.AffineBernstein.TubeLinearTransform +OAI.Analysis.AffineBernstein.TubeMetricPositivity +OAI.Analysis.AffineBernstein.TubeSecondForm +OAI.Analysis.AffineBernstein.TubeSumIntegral +OAI.Analysis.AffineBernstein.TubeSupportedIntegral +OAI.Analysis.AffineBernstein.TubeWeightAlgebra +OAI.Analysis.AffineBernstein.UniformActualCells +OAI.Analysis.AffineBernstein.UniformFlatCap +OAI.Analysis.AffineBernstein.UniformLogCells +OAI.Analysis.AffineBernstein.UniformProductCap +OAI.Analysis.AffineBernstein.UniformSigmaCaps +OAI.Analysis.AffineBernstein.UniformSphericalCap +OAI.Analysis.AffineBernstein.VarianceSeparation +OAI.Analysis.AffineBernstein.WeightTransform +OAI.Analysis.AffineBernstein.WeightedCapInverse +OAI.Analysis.AffineBernstein.WeightedChartLIntegral +OAI.Analysis.AffineBernstein.WeightedDivergence +OAI.Analysis.AffineBernstein.WeightedLogEnergy +OAI.Analysis.AffineBernstein.WeightedMassUpper +OAI.Analysis.AffineBernstein.WeightedPoincare +OAI.Analysis.AffineBernstein.WeightedTracefreeMatrix +OAI.Analysis.AffineBernstein.WeightedTubeEnergy +OAI.Analysis.AffineBernstein.WholeGraphAreaTransport +OAI.Analysis.AffineBernstein.WholeSphereInverse +OAI.Analysis.AffineBernstein.WholeSphereProjective diff --git a/tasks/affine-bernstein/solution/reference.py b/tasks/affine-bernstein/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/affine-bernstein/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/affine-bernstein/solution/solve.sh b/tasks/affine-bernstein/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a76ca8b2c42ca54490b4d9e1902a5d66381bdfbc --- /dev/null +++ b/tasks/affine-bernstein/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AffineBernstein, i.e. module OAI.Analysis.AffineBernstein.Main and the +# 322 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.AffineBernstein.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AffineBernstein" diff --git a/tasks/affine-bernstein/task.toml b/tasks/affine-bernstein/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5295f6c1f1fe7389d5f53910a8cc8556abe438c8 --- /dev/null +++ b/tasks/affine-bernstein/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/affine-bernstein" +version = "1.0.0" +description = "Prove AffineBernstein (openai/math family 353: The sharp dimension threshold for affine Bernstein rigidity) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AffineBernstein.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AffineBernstein" +family = "353" +family_title = "The sharp dimension threshold for affine Bernstein rigidity" +subject = "Differential geometry" +theorems = ["OAI.AffineBernstein.affine_bernstein"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.AffineBernstein.Main" +reference_modules = 322 +reference_lean_bytes = 1998143 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1091 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13498 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/affine-bernstein/tests/Challenge.lean b/tasks/affine-bernstein/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e9622dbdf0411591d6757ab5029296ebc43dd04 --- /dev/null +++ b/tasks/affine-bernstein/tests/Challenge.lean @@ -0,0 +1,94 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped BigOperators ContDiff ENNReal + +namespace AffineBernstein + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def coordinateVector (n : ℕ) (i : Fin n) : Space n := + EuclideanSpace.single i 1 + +/-- Coordinate Hessian. On the open domain it depends only on the restriction of `u`. +The order of the two differentiations is immaterial under the smoothness hypothesis. -/ +def hessian {n : ℕ} (u : Space n → ℝ) (x : Space n) : Matrix (Fin n) (Fin n) ℝ := + fun i j => fderiv ℝ (fun y => fderiv ℝ u y (coordinateVector n j)) x + (coordinateVector n i) + +/-- The coefficient U^{ij} = det(D²u) (D²u)^{-1}_{ij}. -/ +def cofactorHessian {n : ℕ} (u : Space n → ℝ) (x : Space n) : + Matrix (Fin n) (Fin n) ℝ := + (hessian u x).det • (hessian u x)⁻¹ + +/-- The classical determinant weight; in particular, this is not a generalized exponent. -/ +def affineWeight {n : ℕ} (u : Space n → ℝ) (x : Space n) : ℝ := + Real.rpow (hessian u x).det (-(((n : ℝ) + 1) / ((n : ℝ) + 2))) + +def AffineMaximalOn {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Prop := + ∀ x ∈ Ω, ∑ i : Fin n, ∑ j : Fin n, + cofactorHessian u x i j * hessian (affineWeight u) x i j = 0 + +/-- Length on [0,1] for g_x(v,v) = ‖v‖² + (Du_x v)², the metric induced +by the Euclidean graph embedding x ↦ (x,u(x)). The product norm on Lean's ordinary +product type is NOT used (it would be the maximum norm). -/ +def graphPathLength {n : ℕ} (u : Space n → ℝ) (γ : ℝ → Space n) : ℝ≥0∞ := + ∫⁻ t in Icc (0 : ℝ) 1, + ENNReal.ofReal (Real.sqrt + (‖derivWithin γ (Icc (0 : ℝ) 1) t‖ ^ 2 + + (fderiv ℝ u (γ t) (derivWithin γ (Icc (0 : ℝ) 1) t)) ^ 2)) + +/-- The intrinsic extended distance: infimum of lengths of C¹ paths in the domain. +Using a single C¹ path gives the same intrinsic distance as piecewise C¹ paths, +by smooth endpoint reparameterization and concatenation. -/ +def graphEDist {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) + (x y : Space n) : ℝ≥0∞ := + ⨅ (γ : ℝ → Space n) + (_ : ContDiffOn ℝ 1 γ (Icc (0 : ℝ) 1)) + (_ : MapsTo γ (Icc (0 : ℝ) 1) Ω) + (_ : γ 0 = x) (_ : γ 1 = y), graphPathLength u γ + +/-- Sequential completeness for the induced Euclidean path metric. This states +that every intrinsic Cauchy sequence of points in Ω has an intrinsic limit in Ω. +It imposes no growth condition and no completeness condition on the affine metric. -/ +def EuclideanGraphComplete {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Prop := + ∀ x : ℕ → Space n, (∀ i, x i ∈ Ω) → + (∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ i ≥ N, ∀ j ≥ N, + graphEDist Ω u (x i) (x j) < ENNReal.ofReal ε) → + ∃ a ∈ Ω, ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ i ≥ N, + graphEDist Ω u (x i) a < ENNReal.ofReal ε + +/-- The graph, regarded as an affine subset of R^{n+1}. -/ +def graph {n : ℕ} (Ω : Set (Space n)) (u : Space n → ℝ) : Set (Space n × ℝ) := + {p | p.1 ∈ Ω ∧ p.2 = u p.1} + +def standardParaboloid (n : ℕ) : Set (Space n × ℝ) := + {p | p.2 = ∑ i : Fin n, (p.1 i) ^ 2} + +/-- Literal main theorem, with its stated affine-image consequence. -/ +theorem affine_bernstein + (n : ℕ) (hn₃ : 3 ≤ n) (hn₉ : n ≤ 9) + (Ω : Set (Space n)) (hΩne : Ω.Nonempty) (hΩopen : IsOpen Ω) + (hΩconvex : Convex ℝ Ω) (u : Space n → ℝ) + (hu : ContDiffOn ℝ ∞ u Ω) + (hpos : ∀ x ∈ Ω, (hessian u x).PosDef) + (hmax : AffineMaximalOn Ω u) + (hcomplete : EuclideanGraphComplete Ω u) : + Ω = univ ∧ + (∃ (A : Matrix (Fin n) (Fin n) ℝ) (b : Space n) (c : ℝ), + A.IsSymm ∧ A.PosDef ∧ + ∀ x, u x = (1 / 2 : ℝ) * (∑ i : Fin n, ∑ j : Fin n, x i * A i j * x j) + + (∑ i : Fin n, b i * x i) + c) ∧ + (∃ e : (Space n × ℝ) ≃ᵃ[ℝ] (Space n × ℝ), + e '' standardParaboloid n = graph Ω u) := by + sorry + +end AffineBernstein + +end + +end OAI diff --git a/tasks/affine-bernstein/tests/grade.py b/tasks/affine-bernstein/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/affine-bernstein/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/affine-bernstein/tests/task.json b/tasks/affine-bernstein/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8dd1dc65c80bdf4b8b9cfb7629b7e8ad4081fc75 --- /dev/null +++ b/tasks/affine-bernstein/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AffineBernstein", + "comparator": { + "theorem_names": [ + "OAI.AffineBernstein.affine_bernstein" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12598 +} \ No newline at end of file diff --git a/tasks/affine-bernstein/tests/test.sh b/tasks/affine-bernstein/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/affine-bernstein/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/algorithmic-thin-trees/environment/Dockerfile b/tasks/algorithmic-thin-trees/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/algorithmic-thin-trees/environment/fetch_mathlib.sh b/tasks/algorithmic-thin-trees/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/algorithmic-thin-trees/environment/lake-manifest.json b/tasks/algorithmic-thin-trees/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/algorithmic-thin-trees/environment/lakefile.lean b/tasks/algorithmic-thin-trees/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/algorithmic-thin-trees/environment/lean_setup.sh b/tasks/algorithmic-thin-trees/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/algorithmic-thin-trees/environment/pack_submission.py b/tasks/algorithmic-thin-trees/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/algorithmic-thin-trees/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/algorithmic-thin-trees/instruction.md b/tasks/algorithmic-thin-trees/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39d57281e5da100297e6b89e85488b6862b3890a --- /dev/null +++ b/tasks/algorithmic-thin-trees/instruction.md @@ -0,0 +1,247 @@ +# openai/math challenge `AlgorithmicThinTrees` (family 174) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 174 of the release, *Deterministic construction of strong thin spanning trees* +(Combinatorics). The family as a whole: Resolves the strong thin-tree conjecture constructively. Every finite loopless $k$-edge-connected multigraph on at least two vertices has a spanning tree containing at most a universal $C/k$ fraction of the edges of every cut. Such a tree can be found deterministically in polynomial time, even with binary-encoded parallel-edge multiplicities. + +The challenge is `AlgorithmicThinTrees`, also at `/opt/openai-math/challenges/AlgorithmicThinTrees.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Deterministic polynomial-time construction of strong thin trees. -/ + +namespace StrongThinTree + +structure MultiGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + loopless : ∀ e, left e ≠ right e + +namespace MultiGraph + +def cut {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) + (S : Finset (Fin n)) : Finset (Fin m) := + T.filter fun e => (G.left e ∈ S ∧ G.right e ∉ S) ∨ + (G.right e ∈ S ∧ G.left e ∉ S) + +def Connected {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → (G.cut T S).Nonempty + +def SpanningTree {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + G.Connected T ∧ ∀ e ∈ T, ¬ G.Connected (T.erase e) + +def EdgeConnected {n m : ℕ} (G : MultiGraph n m) (k : ℕ) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + k ≤ (G.cut Finset.univ S).card + +end MultiGraph +end StrongThinTree + +namespace CurrentKS + +def frame : List Bool → List Bool + | [] => [true] + | b :: bs => false :: b :: frame bs + +def encodeNat (n : ℕ) : List Bool := frame (Computability.encodeNat n) + +inductive StackAction where + | stay + | pop + | push (bit : Bool) + deriving DecidableEq + +def StackAction.apply : StackAction → List Bool → List Bool + | .stay, xs => xs + | .pop, xs => xs.tail + | .push b, xs => b :: xs + +structure Instruction (k q : ℕ) where + next : Option (Fin q) + actions : Fin k → StackAction + +def Instruction.halt (k q : ℕ) : Instruction k q := ⟨none, fun _ => .stay⟩ + +structure Machine where + stackCount : ℕ + states : ℕ + initial : Fin states + inputStack : Fin stackCount + outputStack : Fin stackCount + table : List (Instruction stackCount states) + +structure Config (k q : ℕ) where + state : Option (Fin q) + «stacks» : Fin k → List Bool + +def topCode : List Bool → ℕ + | [] => 0 + | false :: _ => 1 + | true :: _ => 2 + +def headsCode : (k : ℕ) → (Fin k → List Bool) → ℕ + | 0, _ => 0 + | k + 1, s => topCode (s 0) + 3 * headsCode k (fun j => s j.succ) + +def Machine.step (M : Machine) (c : Config M.stackCount M.states) : + Config M.stackCount M.states := + match c.state with + | none => c + | some q => + let instruction := M.table.getD + (3 ^ M.stackCount * q.val + headsCode M.stackCount c.stacks) + (Instruction.halt M.stackCount M.states) + ⟨instruction.next, fun j => (instruction.actions j).apply (c.stacks j)⟩ + +def Machine.init (M : Machine) (input : List Bool) : Config M.stackCount M.states := + ⟨some M.initial, fun j => if j = M.inputStack then input else []⟩ + +def Machine.run (M : Machine) (input : List Bool) (fuel : ℕ) : + Config M.stackCount M.states := (M.step^[fuel]) (M.init input) + +end CurrentKS + +namespace AlgorithmicThinTrees +open StrongThinTree + +structure ExplicitInput where + n : ℕ + m : ℕ + k : ℕ + graph : MultiGraph n m + +structure BinaryInput where + n : ℕ + p : ℕ + k : ℕ + left : Fin p → Fin n + right : Fin p → Fin n + ordered : ∀ i, left i < right i + distinct : Function.Injective (fun i => (left i, right i)) + multiplicity : Fin p → ℕ + +abbrev BinaryInput.Edge (x : BinaryInput) := Σ i : Fin x.p, Fin (x.multiplicity i) + +noncomputable def BinaryInput.edgeEquiv (x : BinaryInput) : + x.Edge ≃ Fin (Fintype.card x.Edge) := Fintype.equivFin x.Edge + +noncomputable def BinaryInput.graph (x : BinaryInput) : + MultiGraph x.n (Fintype.card x.Edge) where + left e := x.left (x.edgeEquiv.symm e).1 + right e := x.right (x.edgeEquiv.symm e).1 + loopless e := ne_of_lt (x.ordered (x.edgeEquiv.symm e).1) + +inductive Input where + | explicit (x : ExplicitInput) + | binary (x : BinaryInput) + +def ExplicitInput.encode (x : ExplicitInput) : List Bool := + CurrentKS.encodeNat x.n ++ CurrentKS.encodeNat x.m ++ CurrentKS.encodeNat x.k ++ + (List.ofFn fun i : Fin x.m => + CurrentKS.encodeNat (x.graph.left i).val ++ + CurrentKS.encodeNat (x.graph.right i).val).flatten + +def BinaryInput.encode (x : BinaryInput) : List Bool := + CurrentKS.encodeNat x.n ++ CurrentKS.encodeNat x.p ++ CurrentKS.encodeNat x.k ++ + (List.ofFn fun i : Fin x.p => + CurrentKS.encodeNat (x.left i).val ++ CurrentKS.encodeNat (x.right i).val ++ + CurrentKS.encodeNat (x.multiplicity i)).flatten + +def Input.encode : Input → List Bool + | .explicit x => false :: x.encode + | .binary x => true :: x.encode + +def Input.length (x : Input) : ℕ := x.encode.length + +def Input.n : Input → ℕ + | .explicit x => x.n + | .binary x => x.n + +def Valid : Input → Prop + | .explicit x => 1 ≤ x.n ∧ 1 ≤ x.k ∧ x.graph.EdgeConnected x.k + | .binary x => 1 ≤ x.n ∧ 1 ≤ x.k ∧ x.graph.EdgeConnected x.k + +def ThinTree {n m : ℕ} (C : ℝ) (k : ℕ) (G : MultiGraph n m) + (T : Finset (Fin m)) : Prop := + G.SpanningTree T ∧ ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + ((G.cut T S).card : ℝ) ≤ C / (k : ℝ) * (G.cut Finset.univ S).card + +def ExplicitInput.encodeEdges (x : ExplicitInput) (edges : List (Fin x.m)) : List Bool := + edges.flatMap (fun e => CurrentKS.encodeNat e.val) + +def BinaryInput.encodeEdges (x : BinaryInput) (edges : List x.Edge) : List Bool := + edges.flatMap (fun e => CurrentKS.encodeNat e.1.val ++ CurrentKS.encodeNat e.2.val) + +noncomputable def BinaryInput.selected (x : BinaryInput) (edges : List x.Edge) : + Finset (Fin (Fintype.card x.Edge)) := edges.toFinset.map x.edgeEquiv.toEmbedding + +def TreeOutput (C : ℝ) : Input → List Bool → Prop + | .explicit x, bits => ∃ edges : List (Fin x.m), edges.Nodup ∧ + bits = x.encodeEdges edges ∧ ThinTree C x.k x.graph edges.toFinset + | .binary x, bits => ∃ edges : List x.Edge, edges.Nodup ∧ + bits = x.encodeEdges edges ∧ ThinTree C x.k x.graph (x.selected edges) + +def GoodOutput (C : ℝ) (x : Input) (bits : List Bool) : Prop := + TreeOutput C x bits ∧ (x.n = 1 → bits = []) + +def AlgorithmicStrongThinTrees : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ M : CurrentKS.Machine, ∃ a degree : ℕ, 0 < a ∧ + ∀ x : Input, Valid x → + let result := M.run x.encode (a * (x.length + 1) ^ degree) + result.state = none ∧ GoodOutput C x (result.stacks M.outputStack) + +end AlgorithmicThinTrees + +namespace AlgorithmicThinTrees + +theorem algorithmic_strong_thin_trees : AlgorithmicStrongThinTrees := by + sorry + +end AlgorithmicThinTrees + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AlgorithmicThinTrees.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AlgorithmicThinTrees.algorithmic_strong_thin_trees` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/algorithmic-thin-trees/solution/closure.txt b/tasks/algorithmic-thin-trees/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2284139ffa1490ef3d1ff4ffab8cbd8d3215f85a --- /dev/null +++ b/tasks/algorithmic-thin-trees/solution/closure.txt @@ -0,0 +1,736 @@ +OAI.Analysis.MatrixSigning.Arithmetic.Alpha +OAI.Analysis.MatrixSigning.Arithmetic.Alpha2 +OAI.Analysis.MatrixSigning.Arithmetic.ArithmeticBounds +OAI.Analysis.MatrixSigning.Arithmetic.ArithmeticEncodingSize +OAI.Analysis.MatrixSigning.Arithmetic.BinaryAdder +OAI.Analysis.MatrixSigning.Arithmetic.BinaryAdderCompose +OAI.Analysis.MatrixSigning.Arithmetic.BinaryAddressLookup +OAI.Analysis.MatrixSigning.Arithmetic.BinaryDivision +OAI.Analysis.MatrixSigning.Arithmetic.BinaryGCD +OAI.Analysis.MatrixSigning.Arithmetic.BinaryMultiply +OAI.Analysis.MatrixSigning.Arithmetic.BinaryMultiplySemantics +OAI.Analysis.MatrixSigning.Arithmetic.BinaryRationalAdd +OAI.Analysis.MatrixSigning.Arithmetic.BinaryRationalCanonical +OAI.Analysis.MatrixSigning.Arithmetic.BinaryRationalCore +OAI.Analysis.MatrixSigning.Arithmetic.BinaryRationalNormalize +OAI.Analysis.MatrixSigning.Arithmetic.BinarySubtractor +OAI.Analysis.MatrixSigning.Arithmetic.BisectionArithmetic +OAI.Analysis.MatrixSigning.Arithmetic.BorrowSubtractor +OAI.Analysis.MatrixSigning.Arithmetic.CanonicalRationalPairParser +OAI.Analysis.MatrixSigning.Arithmetic.CanonicalSubtraction +OAI.Analysis.MatrixSigning.Arithmetic.CleanRationalCompare +OAI.Analysis.MatrixSigning.Arithmetic.ComplexScalarNodes +OAI.Analysis.MatrixSigning.Arithmetic.ConvexInnerBall +OAI.Analysis.MatrixSigning.Arithmetic.CubeInterval +OAI.Analysis.MatrixSigning.Arithmetic.DivisionBodyTime +OAI.Analysis.MatrixSigning.Arithmetic.DivisionCompatibility +OAI.Analysis.MatrixSigning.Arithmetic.DivisionInput +OAI.Analysis.MatrixSigning.Arithmetic.DivisionLoopBridge +OAI.Analysis.MatrixSigning.Arithmetic.DivisionLoopModel +OAI.Analysis.MatrixSigning.Arithmetic.DivisionLoopRun +OAI.Analysis.MatrixSigning.Arithmetic.DivisionMachine +OAI.Analysis.MatrixSigning.Arithmetic.DivisionOutput +OAI.Analysis.MatrixSigning.Arithmetic.EncodedDivision +OAI.Analysis.MatrixSigning.Arithmetic.EventuallyInterior +OAI.Analysis.MatrixSigning.Arithmetic.ExactStepDecrease +OAI.Analysis.MatrixSigning.Arithmetic.FixedBinaryAdder +OAI.Analysis.MatrixSigning.Arithmetic.FixedSubtraction +OAI.Analysis.MatrixSigning.Arithmetic.FloorRationalMachine +OAI.Analysis.MatrixSigning.Arithmetic.GCDMachine +OAI.Analysis.MatrixSigning.Arithmetic.GCDMachineRun +OAI.Analysis.MatrixSigning.Arithmetic.GCDMachineStep +OAI.Analysis.MatrixSigning.Arithmetic.Kappa₁ +OAI.Analysis.MatrixSigning.Arithmetic.MixedYoungBound +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationBody +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationDeterministic +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationInitialize +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationLoop +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationMachine +OAI.Analysis.MatrixSigning.Arithmetic.MultiplicationNormalize +OAI.Analysis.MatrixSigning.Arithmetic.NegativeDivision +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddCorrect +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddModel +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddPorts +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddPrimitives +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddProducts +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddProgram +OAI.Analysis.MatrixSigning.Arithmetic.RationalAddSigned +OAI.Analysis.MatrixSigning.Arithmetic.RationalArithmetic +OAI.Analysis.MatrixSigning.Arithmetic.RationalArithmeticMeter +OAI.Analysis.MatrixSigning.Arithmetic.RationalBounds +OAI.Analysis.MatrixSigning.Arithmetic.RationalCompareBranch +OAI.Analysis.MatrixSigning.Arithmetic.RationalCompareCorrectness +OAI.Analysis.MatrixSigning.Arithmetic.RationalCompareDeterministic +OAI.Analysis.MatrixSigning.Arithmetic.RationalCompareParser +OAI.Analysis.MatrixSigning.Arithmetic.RationalComparePrimitives +OAI.Analysis.MatrixSigning.Arithmetic.RationalCompareProgram +OAI.Analysis.MatrixSigning.Arithmetic.RationalDivisionMachine +OAI.Analysis.MatrixSigning.Arithmetic.RationalDivisionStages +OAI.Analysis.MatrixSigning.Arithmetic.RationalExpressionHeight +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudeCorrect +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudeDivision +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudeMachine +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudePositive +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudeSetup +OAI.Analysis.MatrixSigning.Arithmetic.RationalMagnitudeSign +OAI.Analysis.MatrixSigning.Arithmetic.RationalMultiplicationMachine +OAI.Analysis.MatrixSigning.Arithmetic.RationalMultiplyNormalize +OAI.Analysis.MatrixSigning.Arithmetic.RationalMultiplyProducts +OAI.Analysis.MatrixSigning.Arithmetic.RationalReciprocalCore +OAI.Analysis.MatrixSigning.Arithmetic.RationalReciprocalMachine +OAI.Analysis.MatrixSigning.Arithmetic.RationalReciprocalSerialize +OAI.Analysis.MatrixSigning.Arithmetic.RationalReciprocalSwap +OAI.Analysis.MatrixSigning.Arithmetic.RationalSignAction +OAI.Analysis.MatrixSigning.Arithmetic.RationalSignClassifier +OAI.Analysis.MatrixSigning.Arithmetic.RationalSignPorts +OAI.Analysis.MatrixSigning.Arithmetic.RationalSubtractCorrect +OAI.Analysis.MatrixSigning.Arithmetic.RationalSubtractPorts +OAI.Analysis.MatrixSigning.Arithmetic.RationalSubtractProgram +OAI.Analysis.MatrixSigning.Arithmetic.RealifyAdd +OAI.Analysis.MatrixSigning.Arithmetic.ScalarPsi +OAI.Analysis.MatrixSigning.Arithmetic.SignedRationalSerializer +OAI.Analysis.MatrixSigning.Arithmetic.SingleRationalParser +OAI.Analysis.MatrixSigning.Arithmetic.SparseScalarNodes +OAI.Analysis.MatrixSigning.Arithmetic.SubtractionBorrow +OAI.Analysis.MatrixSigning.Arithmetic.SubtractorSequential +OAI.Analysis.MatrixSigning.Arithmetic.UnaryArithmetic +OAI.Analysis.MatrixSigning.Arithmetic.ZeroPaddedRow +OAI.Analysis.MatrixSigning.Calculus.BilinearIteratedBound +OAI.Analysis.MatrixSigning.Calculus.IteratedNormCompLinear +OAI.Analysis.MatrixSigning.Calculus.JetBound +OAI.Analysis.MatrixSigning.Calculus.LocalMinSecondNonnegative +OAI.Analysis.MatrixSigning.Calculus.NormMultilinearTwo +OAI.Analysis.MatrixSigning.Calculus.NormSmulRightId +OAI.Analysis.MatrixSigning.Calculus.Translate +OAI.Analysis.MatrixSigning.Complexity.BinaryGCDCost +OAI.Analysis.MatrixSigning.Complexity.BitSupport +OAI.Analysis.MatrixSigning.Complexity.ComplexScalarCosts +OAI.Analysis.MatrixSigning.Complexity.GCDMachinePolynomial +OAI.Analysis.MatrixSigning.Complexity.GlobalCounts +OAI.Analysis.MatrixSigning.Complexity.NaturalPolynomial +OAI.Analysis.MatrixSigning.Complexity.PSDControllerPolynomial +OAI.Analysis.MatrixSigning.Complexity.PolynomialArithmeticFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialArrays +OAI.Analysis.MatrixSigning.Complexity.PolynomialBranchFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialCeiling +OAI.Analysis.MatrixSigning.Complexity.PolynomialCoordinates +OAI.Analysis.MatrixSigning.Complexity.PolynomialCurvature +OAI.Analysis.MatrixSigning.Complexity.PolynomialExplicit +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceBasics +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceChoice +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceFuel +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceNext +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceOrbit +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceQuery +OAI.Analysis.MatrixSigning.Complexity.PolynomialFaceRun +OAI.Analysis.MatrixSigning.Complexity.PolynomialFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialFinFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialFind +OAI.Analysis.MatrixSigning.Complexity.PolynomialIterateFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialLists +OAI.Analysis.MatrixSigning.Complexity.PolynomialLoops +OAI.Analysis.MatrixSigning.Complexity.PolynomialMapFamilies +OAI.Analysis.MatrixSigning.Complexity.PolynomialMatrixFold +OAI.Analysis.MatrixSigning.Complexity.PolynomialMatrixSum +OAI.Analysis.MatrixSigning.Complexity.PolynomialMemberFamily +OAI.Analysis.MatrixSigning.Complexity.PolynomialOptimize +OAI.Analysis.MatrixSigning.Complexity.PolynomialOriginalFields +OAI.Analysis.MatrixSigning.Complexity.PolynomialOriginalOutput +OAI.Analysis.MatrixSigning.Complexity.PolynomialOriginalSigning +OAI.Analysis.MatrixSigning.Complexity.PolynomialPotential +OAI.Analysis.MatrixSigning.Complexity.PolynomialRoots +OAI.Analysis.MatrixSigning.Complexity.PolynomialRoundedStep +OAI.Analysis.MatrixSigning.Complexity.PolynomialRoutine +OAI.Analysis.MatrixSigning.Complexity.PolynomialScalar +OAI.Analysis.MatrixSigning.Complexity.PolynomialSchedule +OAI.Analysis.MatrixSigning.Complexity.PolynomialSearch +OAI.Analysis.MatrixSigning.Complexity.PolynomialStencil +OAI.Analysis.MatrixSigning.Complexity.PolynomialStored +OAI.Analysis.MatrixSigning.Complexity.PolynomialValueQuery +OAI.Analysis.MatrixSigning.Complexity.PolynomialVariance +OAI.Analysis.MatrixSigning.Complexity.QueryBits +OAI.Analysis.MatrixSigning.Complexity.RationalCost +OAI.Analysis.MatrixSigning.Complexity.RationalGridBits +OAI.Analysis.MatrixSigning.Complexity.SchurCellCost +OAI.Analysis.MatrixSigning.Complexity.SchurPolynomialBound +OAI.Analysis.MatrixSigning.Complexity.SparseScalarCost +OAI.Analysis.MatrixSigning.Complexity.StorageCost +OAI.Analysis.MatrixSigning.Complexity.StoredBits +OAI.Analysis.MatrixSigning.Complexity.TerminalWitnessCost +OAI.Analysis.MatrixSigning.Encoding.BinaryEncoding +OAI.Analysis.MatrixSigning.Encoding.DenseCanonicalParser +OAI.Analysis.MatrixSigning.Encoding.FixedPositiveSerializer +OAI.Analysis.MatrixSigning.Encoding.FlattenLookup +OAI.Analysis.MatrixSigning.Encoding.FrameActivity +OAI.Analysis.MatrixSigning.Encoding.FrameDecoder +OAI.Analysis.MatrixSigning.Encoding.FrameWireCodec +OAI.Analysis.MatrixSigning.Encoding.FramedArrayPorts +OAI.Analysis.MatrixSigning.Encoding.FramedArrayPrefix +OAI.Analysis.MatrixSigning.Encoding.FramedArrayReplacement +OAI.Analysis.MatrixSigning.Encoding.FramedArrayReplacementPorts +OAI.Analysis.MatrixSigning.Encoding.FramedArrayRetrieval +OAI.Analysis.MatrixSigning.Encoding.FramedArraySkip +OAI.Analysis.MatrixSigning.Encoding.InverseEncodingSize +OAI.Analysis.MatrixSigning.Encoding.PositiveWireSerializer +OAI.Analysis.MatrixSigning.Encoding.ReusableArrayLookup +OAI.Analysis.MatrixSigning.Encoding.SignedQuotientSerializer +OAI.Analysis.MatrixSigning.Encoding.SumEncodingSize +OAI.Analysis.MatrixSigning.Encoding.UnsignedPairSerializer +OAI.Analysis.MatrixSigning.Encoding.WireAppend +OAI.Analysis.MatrixSigning.Encoding.WireMagnitude +OAI.Analysis.MatrixSigning.Encoding.WirePrimitives +OAI.Analysis.MatrixSigning.Encoding.WireProgramPrimitives +OAI.Analysis.MatrixSigning.Encoding.WordOperations +OAI.Analysis.MatrixSigning.Encoding.ZeroArrayConstructor +OAI.Analysis.MatrixSigning.Machines.BinaryAccumulator +OAI.Analysis.MatrixSigning.Machines.BinaryExpressionEvaluator +OAI.Analysis.MatrixSigning.Machines.BinaryFloorBridge +OAI.Analysis.MatrixSigning.Machines.BinaryMachine +OAI.Analysis.MatrixSigning.Machines.BinaryNormalize +OAI.Analysis.MatrixSigning.Machines.BinaryStackDeterministic +OAI.Analysis.MatrixSigning.Machines.BinaryStackMoves +OAI.Analysis.MatrixSigning.Machines.BinaryToUnary +OAI.Analysis.MatrixSigning.Machines.BinaryToUnaryDeterministic +OAI.Analysis.MatrixSigning.Machines.BinaryToUnaryMachine +OAI.Analysis.MatrixSigning.Machines.BinaryToUnaryRun +OAI.Analysis.MatrixSigning.Machines.BinaryTrimMachine +OAI.Analysis.MatrixSigning.Machines.BisectionCommands +OAI.Analysis.MatrixSigning.Machines.BorrowActivity +OAI.Analysis.MatrixSigning.Machines.CanonicalUnarySpec +OAI.Analysis.MatrixSigning.Machines.CleanupDeterministic +OAI.Analysis.MatrixSigning.Machines.CommonDenominatorLift +OAI.Analysis.MatrixSigning.Machines.ComplexBridge +OAI.Analysis.MatrixSigning.Machines.ControllerReachable +OAI.Analysis.MatrixSigning.Machines.ControllerReplayBound +OAI.Analysis.MatrixSigning.Machines.ControllerRuntime +OAI.Analysis.MatrixSigning.Machines.ControllerTerminalBound +OAI.Analysis.MatrixSigning.Machines.CopyInput +OAI.Analysis.MatrixSigning.Machines.DenseFieldCounter +OAI.Analysis.MatrixSigning.Machines.Deterministic +OAI.Analysis.MatrixSigning.Machines.DeterministicCombinators +OAI.Analysis.MatrixSigning.Machines.DirectedRounding +OAI.Analysis.MatrixSigning.Machines.EntryPoint +OAI.Analysis.MatrixSigning.Machines.ExpressionPrimitives +OAI.Analysis.MatrixSigning.Machines.ExpressionSyntax +OAI.Analysis.MatrixSigning.Machines.FiniteControl +OAI.Analysis.MatrixSigning.Machines.FiniteDispatch +OAI.Analysis.MatrixSigning.Machines.FixedBranch +OAI.Analysis.MatrixSigning.Machines.FixedCanonicalize +OAI.Analysis.MatrixSigning.Machines.FixedCompare +OAI.Analysis.MatrixSigning.Machines.FixedCopyRestore +OAI.Analysis.MatrixSigning.Machines.FixedCopySpec +OAI.Analysis.MatrixSigning.Machines.FixedDotBody +OAI.Analysis.MatrixSigning.Machines.FixedDotBounds +OAI.Analysis.MatrixSigning.Machines.FixedDotControl +OAI.Analysis.MatrixSigning.Machines.FixedDotMachine +OAI.Analysis.MatrixSigning.Machines.FixedDotModel +OAI.Analysis.MatrixSigning.Machines.FixedDotPrimitives +OAI.Analysis.MatrixSigning.Machines.FixedLoop +OAI.Analysis.MatrixSigning.Machines.FixedPortRunSpec +OAI.Analysis.MatrixSigning.Machines.FixedRun +OAI.Analysis.MatrixSigning.Machines.FixedSequential +OAI.Analysis.MatrixSigning.Machines.FixedStackMachine +OAI.Analysis.MatrixSigning.Machines.FixedStackPortLift +OAI.Analysis.MatrixSigning.Machines.InputHeaderPrimitives +OAI.Analysis.MatrixSigning.Machines.InverseBounds +OAI.Analysis.MatrixSigning.Machines.InverseHeight +OAI.Analysis.MatrixSigning.Machines.LiteralProgram +OAI.Analysis.MatrixSigning.Machines.LittleEndianCompare +OAI.Analysis.MatrixSigning.Machines.MachineCombinators +OAI.Analysis.MatrixSigning.Machines.MachineRoundTrip +OAI.Analysis.MatrixSigning.Machines.MachineTransport +OAI.Analysis.MatrixSigning.Machines.MagnitudeProgram +OAI.Analysis.MatrixSigning.Machines.NestedSchur +OAI.Analysis.MatrixSigning.Machines.NormalizeOutput +OAI.Analysis.MatrixSigning.Machines.ProgramTable +OAI.Analysis.MatrixSigning.Machines.Realification +OAI.Analysis.MatrixSigning.Machines.RealificationSPD +OAI.Analysis.MatrixSigning.Machines.SchurBounds +OAI.Analysis.MatrixSigning.Machines.SchurCellMachine +OAI.Analysis.MatrixSigning.Machines.SchurColumnLoop +OAI.Analysis.MatrixSigning.Machines.SchurCounters +OAI.Analysis.MatrixSigning.Machines.SchurDimension +OAI.Analysis.MatrixSigning.Machines.SchurEntryMachine +OAI.Analysis.MatrixSigning.Machines.SchurInputLength +OAI.Analysis.MatrixSigning.Machines.SchurOperands +OAI.Analysis.MatrixSigning.Machines.SchurReadStage +OAI.Analysis.MatrixSigning.Machines.SchurRowLoop +OAI.Analysis.MatrixSigning.Machines.SchurTableCorrectness +OAI.Analysis.MatrixSigning.Machines.SchurTableInvariant +OAI.Analysis.MatrixSigning.Machines.SchurTableMachine +OAI.Analysis.MatrixSigning.Machines.SchurTablePorts +OAI.Analysis.MatrixSigning.Machines.Sequential +OAI.Analysis.MatrixSigning.Machines.SignedFloorMachine +OAI.Analysis.MatrixSigning.Machines.SignedFloorModel +OAI.Analysis.MatrixSigning.Machines.SignedFloorSize +OAI.Analysis.MatrixSigning.Machines.SignedSerializePrimitives +OAI.Analysis.MatrixSigning.Machines.SparseCoefficientStage +OAI.Analysis.MatrixSigning.Machines.StackTransfer +OAI.Analysis.MatrixSigning.Machines.StackTransferSpecs +OAI.Analysis.MatrixSigning.Machines.TerminalInputBounds +OAI.Analysis.MatrixSigning.Machines.TerminalReadStage +OAI.Analysis.MatrixSigning.Machines.TerminalSparseAssembly +OAI.Analysis.MatrixSigning.Machines.TerminalVectorReplace +OAI.Analysis.MatrixSigning.Machines.TerminalZeroVector +OAI.Analysis.MatrixSigning.Machines.UnaryLengthMachine +OAI.Analysis.MatrixSigning.Main +OAI.Analysis.MatrixSigning.Matrices.DenseElimination +OAI.Analysis.MatrixSigning.Matrices.DenseMatrixSerialization +OAI.Analysis.MatrixSigning.Matrices.DenseMatrixUpdate +OAI.Analysis.MatrixSigning.Matrices.DenseRatMatrix +OAI.Analysis.MatrixSigning.Matrices.DerivInvHPath +OAI.Analysis.MatrixSigning.Matrices.DeterminantBounds +OAI.Analysis.MatrixSigning.Matrices.EliminationCallBounds +OAI.Analysis.MatrixSigning.Matrices.EliminationCompleteness +OAI.Analysis.MatrixSigning.Matrices.EliminationSoundness +OAI.Analysis.MatrixSigning.Matrices.FDerivTightPart +OAI.Analysis.MatrixSigning.Matrices.FinPivot +OAI.Analysis.MatrixSigning.Matrices.FinPivotPSD +OAI.Analysis.MatrixSigning.Matrices.HermitianMat +OAI.Analysis.MatrixSigning.Matrices.InnerMonoRightPsd +OAI.Analysis.MatrixSigning.Matrices.InnerRight +OAI.Analysis.MatrixSigning.Matrices.InvH +OAI.Analysis.MatrixSigning.Matrices.JetBoundInverseSandwich +OAI.Analysis.MatrixSigning.Matrices.JetBoundTightPart +OAI.Analysis.MatrixSigning.Matrices.JordanCLM +OAI.Analysis.MatrixSigning.Matrices.JordanCLMStrictPos +OAI.Analysis.MatrixSigning.Matrices.MatrixAddressArithmetic +OAI.Analysis.MatrixSigning.Matrices.MatrixCursorPreparation +OAI.Analysis.MatrixSigning.Matrices.MatrixReadProgram +OAI.Analysis.MatrixSigning.Matrices.MatrixRealSmul +OAI.Analysis.MatrixSigning.Matrices.MatrixWriteBridge +OAI.Analysis.MatrixSigning.Matrices.NormRetractH +OAI.Analysis.MatrixSigning.Matrices.OperatorNorm +OAI.Analysis.MatrixSigning.Matrices.OperatorNormSquare +OAI.Analysis.MatrixSigning.Matrices.PSDSeparation +OAI.Analysis.MatrixSigning.Matrices.Pivot +OAI.Analysis.MatrixSigning.Matrices.PivotControllerBody +OAI.Analysis.MatrixSigning.Matrices.PivotControllerCorrectness +OAI.Analysis.MatrixSigning.Matrices.PivotControllerLoop +OAI.Analysis.MatrixSigning.Matrices.PivotDecisionCorrectness +OAI.Analysis.MatrixSigning.Matrices.PivotDecisionMachine +OAI.Analysis.MatrixSigning.Matrices.PivotDecisionPorts +OAI.Analysis.MatrixSigning.Matrices.PivotHistory +OAI.Analysis.MatrixSigning.Matrices.PivotHistoryBounds +OAI.Analysis.MatrixSigning.Matrices.PivotHistoryMachine +OAI.Analysis.MatrixSigning.Matrices.PivotHistoryRun +OAI.Analysis.MatrixSigning.Matrices.PivotPSD +OAI.Analysis.MatrixSigning.Matrices.PivotReachableBounds +OAI.Analysis.MatrixSigning.Matrices.PivotReplayLoop +OAI.Analysis.MatrixSigning.Matrices.PivotRowBody +OAI.Analysis.MatrixSigning.Matrices.PivotRowClassify +OAI.Analysis.MatrixSigning.Matrices.PivotRowCorrectness +OAI.Analysis.MatrixSigning.Matrices.PivotRowFinish +OAI.Analysis.MatrixSigning.Matrices.PivotRowInitialize +OAI.Analysis.MatrixSigning.Matrices.PivotRowLoop +OAI.Analysis.MatrixSigning.Matrices.PivotRowRead +OAI.Analysis.MatrixSigning.Matrices.PivotScannerBounds +OAI.Analysis.MatrixSigning.Matrices.PivotTerminalMachine +OAI.Analysis.MatrixSigning.Matrices.PosLower +OAI.Analysis.MatrixSigning.Matrices.PreservedMatrixRetrieval +OAI.Analysis.MatrixSigning.Matrices.RankFactor +OAI.Analysis.MatrixSigning.Matrices.RationalElimination +OAI.Analysis.MatrixSigning.Matrices.RationalPSDDecision +OAI.Analysis.MatrixSigning.Matrices.RealDecode +OAI.Analysis.MatrixSigning.Matrices.RealTrace +OAI.Analysis.MatrixSigning.Matrices.RealTraceSum +OAI.Analysis.MatrixSigning.Matrices.RealifyHermitian +OAI.Analysis.MatrixSigning.Matrices.RetractH +OAI.Analysis.MatrixSigning.Matrices.RowDotBody +OAI.Analysis.MatrixSigning.Matrices.RowDotBounds +OAI.Analysis.MatrixSigning.Matrices.RowDotControl +OAI.Analysis.MatrixSigning.Matrices.RowDotCounter +OAI.Analysis.MatrixSigning.Matrices.RowDotMachine +OAI.Analysis.MatrixSigning.Matrices.RowDotModel +OAI.Analysis.MatrixSigning.Matrices.RowDotPrimitives +OAI.Analysis.MatrixSigning.Matrices.RowDotRegisters +OAI.Analysis.MatrixSigning.Matrices.Sandwich +OAI.Analysis.MatrixSigning.Matrices.Sandwich2 +OAI.Analysis.MatrixSigning.Matrices.SandwichCLM +OAI.Analysis.MatrixSigning.Matrices.SandwichShiftInverse +OAI.Analysis.MatrixSigning.Matrices.SavedPivotPacketMachine +OAI.Analysis.MatrixSigning.Matrices.SavedPivotStack +OAI.Analysis.MatrixSigning.Matrices.Space +OAI.Analysis.MatrixSigning.Matrices.SquareScalarBound +OAI.Analysis.MatrixSigning.Matrices.SquareShift +OAI.Analysis.MatrixSigning.Matrices.TraceCLM +OAI.Analysis.MatrixSigning.Matrices.UniformElimination +OAI.Analysis.MatrixSigning.Matrices.UniformEliminationHeight +OAI.Analysis.MatrixSigning.Model +OAI.Analysis.MatrixSigning.Optimization.Affine +OAI.Analysis.MatrixSigning.Optimization.AffineRealEval +OAI.Analysis.MatrixSigning.Optimization.BlockScalar +OAI.Analysis.MatrixSigning.Optimization.ComplexValueProgram +OAI.Analysis.MatrixSigning.Optimization.Coordinates +OAI.Analysis.MatrixSigning.Optimization.EliminationWitnessHeight +OAI.Analysis.MatrixSigning.Optimization.EquivSymmetricMap +OAI.Analysis.MatrixSigning.Optimization.FaceStencil +OAI.Analysis.MatrixSigning.Optimization.Feasible +OAI.Analysis.MatrixSigning.Optimization.FinRealify +OAI.Analysis.MatrixSigning.Optimization.FixedPart +OAI.Analysis.MatrixSigning.Optimization.InverseEliminationBounds +OAI.Analysis.MatrixSigning.Optimization.Level +OAI.Analysis.MatrixSigning.Optimization.Lookup +OAI.Analysis.MatrixSigning.Optimization.MinList +OAI.Analysis.MatrixSigning.Optimization.NearestEndpoint +OAI.Analysis.MatrixSigning.Optimization.NegativeDirection +OAI.Analysis.MatrixSigning.Optimization.NegativeWitness +OAI.Analysis.MatrixSigning.Optimization.NormalizedRun +OAI.Analysis.MatrixSigning.Optimization.ObjectiveCLM +OAI.Analysis.MatrixSigning.Optimization.Outside +OAI.Analysis.MatrixSigning.Optimization.PackValue +OAI.Analysis.MatrixSigning.Optimization.PartialFderiv +OAI.Analysis.MatrixSigning.Optimization.Pencil +OAI.Analysis.MatrixSigning.Optimization.PivotDescentBounds +OAI.Analysis.MatrixSigning.Optimization.PivotDescentMachine +OAI.Analysis.MatrixSigning.Optimization.PivotWitnessMachine +OAI.Analysis.MatrixSigning.Optimization.RationalAtoms +OAI.Analysis.MatrixSigning.Optimization.RealExtendCube +OAI.Analysis.MatrixSigning.Optimization.RealVector +OAI.Analysis.MatrixSigning.Optimization.RootTolerance +OAI.Analysis.MatrixSigning.Optimization.SchurWitnessHead +OAI.Analysis.MatrixSigning.Optimization.SearchStep +OAI.Analysis.MatrixSigning.Optimization.Select +OAI.Analysis.MatrixSigning.Optimization.ShiftedHessian +OAI.Analysis.MatrixSigning.Optimization.SignedFloorInterface +OAI.Analysis.MatrixSigning.Optimization.Signing +OAI.Analysis.MatrixSigning.Optimization.SqSum +OAI.Analysis.MatrixSigning.Optimization.SquareInterval +OAI.Analysis.MatrixSigning.Optimization.StoredWitnessLift +OAI.Analysis.MatrixSigning.Optimization.TerminalWitnessBounds +OAI.Analysis.MatrixSigning.Optimization.TerminalWitnessMachine +OAI.Analysis.MatrixSigning.Optimization.TerminalWitnessTapes +OAI.Analysis.MatrixSigning.Optimization.Transition +OAI.Analysis.MatrixSigning.Optimization.UpperIndex +OAI.Analysis.MatrixSigning.Optimization.ValueDimension +OAI.Analysis.MatrixSigning.Optimization.ValueObjectiveCoeffs +OAI.Analysis.MatrixSigning.Optimization.ValueOuterRadius +OAI.Analysis.MatrixSigning.Optimization.Variables +OAI.Analysis.MatrixSigning.Potential.C1Rational +OAI.Analysis.MatrixSigning.Potential.ChooseCoordinate +OAI.Analysis.MatrixSigning.Potential.CoarseBudget +OAI.Analysis.MatrixSigning.Potential.Column +OAI.Analysis.MatrixSigning.Potential.Coordinates +OAI.Analysis.MatrixSigning.Potential.CovarianceE +OAI.Analysis.MatrixSigning.Potential.DerivLine +OAI.Analysis.MatrixSigning.Potential.DerivPathObjective +OAI.Analysis.MatrixSigning.Potential.DiagBlock +OAI.Analysis.MatrixSigning.Potential.Drift +OAI.Analysis.MatrixSigning.Potential.EndpointCandidates +OAI.Analysis.MatrixSigning.Potential.Energy +OAI.Analysis.MatrixSigning.Potential.EnergyMatrix +OAI.Analysis.MatrixSigning.Potential.EnsembleForcesNegative +OAI.Analysis.MatrixSigning.Potential.EuclideanForget +OAI.Analysis.MatrixSigning.Potential.FaceEndpointFeasible +OAI.Analysis.MatrixSigning.Potential.FacePotential +OAI.Analysis.MatrixSigning.Potential.FaceState +OAI.Analysis.MatrixSigning.Potential.FaceValueDirectionVariations +OAI.Analysis.MatrixSigning.Potential.FreezePotential +OAI.Analysis.MatrixSigning.Potential.Hessian +OAI.Analysis.MatrixSigning.Potential.Interaction +OAI.Analysis.MatrixSigning.Potential.InverseProductLeft +OAI.Analysis.MatrixSigning.Potential.IteratedDerivCompScale +OAI.Analysis.MatrixSigning.Potential.JetBoundProjection +OAI.Analysis.MatrixSigning.Potential.Lagrangian +OAI.Analysis.MatrixSigning.Potential.LagrangianObjective +OAI.Analysis.MatrixSigning.Potential.LightPoint +OAI.Analysis.MatrixSigning.Potential.Line +OAI.Analysis.MatrixSigning.Potential.LineShiftIteratedDeriv +OAI.Analysis.MatrixSigning.Potential.MovementBudget +OAI.Analysis.MatrixSigning.Potential.MovementMat +OAI.Analysis.MatrixSigning.Potential.NegativeWeight +OAI.Analysis.MatrixSigning.Potential.Norm +OAI.Analysis.MatrixSigning.Potential.NormCoordinate +OAI.Analysis.MatrixSigning.Potential.NormPotential +OAI.Analysis.MatrixSigning.Potential.NormPsdScalar +OAI.Analysis.MatrixSigning.Potential.NormSq +OAI.Analysis.MatrixSigning.Potential.NormTCoord +OAI.Analysis.MatrixSigning.Potential.NormalizedMinimizer +OAI.Analysis.MatrixSigning.Potential.Normalizer +OAI.Analysis.MatrixSigning.Potential.ObjectiveVarsCLM +OAI.Analysis.MatrixSigning.Potential.Pack +OAI.Analysis.MatrixSigning.Potential.Pair +OAI.Analysis.MatrixSigning.Potential.PairCone +OAI.Analysis.MatrixSigning.Potential.PairHilbert +OAI.Analysis.MatrixSigning.Potential.PairIndex +OAI.Analysis.MatrixSigning.Potential.PairVec +OAI.Analysis.MatrixSigning.Potential.ParameterCube +OAI.Analysis.MatrixSigning.Potential.Parameters +OAI.Analysis.MatrixSigning.Potential.Parameters2 +OAI.Analysis.MatrixSigning.Potential.PathObjectiveFirst +OAI.Analysis.MatrixSigning.Potential.PenaltyParameter +OAI.Analysis.MatrixSigning.Potential.Point +OAI.Analysis.MatrixSigning.Potential.PositiveMapMono +OAI.Analysis.MatrixSigning.Potential.Potential +OAI.Analysis.MatrixSigning.Potential.QuadGram +OAI.Analysis.MatrixSigning.Potential.QuadraticDifferenceBound +OAI.Analysis.MatrixSigning.Potential.QuadraticRemainder +OAI.Analysis.MatrixSigning.Potential.RationalBasis +OAI.Analysis.MatrixSigning.Potential.RealTraceVarianceRank +OAI.Analysis.MatrixSigning.Potential.ResponseInputSub +OAI.Analysis.MatrixSigning.Potential.ResponseMatrix +OAI.Analysis.MatrixSigning.Potential.RowSquareSum +OAI.Analysis.MatrixSigning.Potential.SchurBlock +OAI.Analysis.MatrixSigning.Potential.SchurLoopState +OAI.Analysis.MatrixSigning.Potential.ShiftFeasibleMap +OAI.Analysis.MatrixSigning.Potential.StateIA +OAI.Analysis.MatrixSigning.Potential.StatePsi +OAI.Analysis.MatrixSigning.Potential.StateR +OAI.Analysis.MatrixSigning.Potential.StationaryPairing +OAI.Analysis.MatrixSigning.Potential.StencilScalarBounds +OAI.Analysis.MatrixSigning.Potential.StrictEpigraph +OAI.Analysis.MatrixSigning.Potential.SymmetricMap +OAI.Analysis.MatrixSigning.Potential.SymmetricNormQuadratic +OAI.Analysis.MatrixSigning.Potential.TightComplementarity +OAI.Analysis.MatrixSigning.Potential.TightSystem +OAI.Analysis.MatrixSigning.Potential.UnpackKkt +OAI.Analysis.MatrixSigning.Potential.Value +OAI.Analysis.MatrixSigning.Potential.ValueBranch +OAI.Analysis.MatrixSigning.Potential.ValueFeasible +OAI.Analysis.MatrixSigning.Potential.VarianceH +OAI.Analysis.MatrixSigning.Potential.Vars +OAI.Analysis.MatrixSigning.Potential.WhitenWeighted +OAI.Analysis.MatrixSigning.Realization.ArithmeticRoutine +OAI.Analysis.MatrixSigning.Realization.ArrayRealization +OAI.Analysis.MatrixSigning.Realization.BinaryNaturalRealization +OAI.Analysis.MatrixSigning.Realization.CleanRoutine +OAI.Analysis.MatrixSigning.Realization.CompareRoutine +OAI.Analysis.MatrixSigning.Realization.ConditionalRoutine +OAI.Analysis.MatrixSigning.Realization.CoordinateRealization +OAI.Analysis.MatrixSigning.Realization.CurvatureRealization +OAI.Analysis.MatrixSigning.Realization.DenseInputArrays +OAI.Analysis.MatrixSigning.Realization.DenseInputMachine +OAI.Analysis.MatrixSigning.Realization.DependentBranchRealization +OAI.Analysis.MatrixSigning.Realization.DependentRealization +OAI.Analysis.MatrixSigning.Realization.EndpointRealization +OAI.Analysis.MatrixSigning.Realization.FaceArrayRealization +OAI.Analysis.MatrixSigning.Realization.FaceChoiceRealization +OAI.Analysis.MatrixSigning.Realization.FaceQueryRealization +OAI.Analysis.MatrixSigning.Realization.FaceRunRealization +OAI.Analysis.MatrixSigning.Realization.FilterRealization +OAI.Analysis.MatrixSigning.Realization.FixedSubroutineBridge +OAI.Analysis.MatrixSigning.Realization.FloorCleanRoutine +OAI.Analysis.MatrixSigning.Realization.FoldRoutine +OAI.Analysis.MatrixSigning.Realization.FramedMapRoutine +OAI.Analysis.MatrixSigning.Realization.IterateRoutine +OAI.Analysis.MatrixSigning.Realization.LevelPencilRealization +OAI.Analysis.MatrixSigning.Realization.ListRealization +OAI.Analysis.MatrixSigning.Realization.MachineAdapter +OAI.Analysis.MatrixSigning.Realization.MatrixStructureRealization +OAI.Analysis.MatrixSigning.Realization.NaturalRealization +OAI.Analysis.MatrixSigning.Realization.OptimizeRealization +OAI.Analysis.MatrixSigning.Realization.OriginalFieldsRealization +OAI.Analysis.MatrixSigning.Realization.OriginalMachine +OAI.Analysis.MatrixSigning.Realization.OriginalOutputRoutine +OAI.Analysis.MatrixSigning.Realization.OriginalParserRoutine +OAI.Analysis.MatrixSigning.Realization.OriginalSignRealization +OAI.Analysis.MatrixSigning.Realization.PSDCleanRoutine +OAI.Analysis.MatrixSigning.Realization.PairRoutine +OAI.Analysis.MatrixSigning.Realization.PencilArrayRealization +OAI.Analysis.MatrixSigning.Realization.PencilCompileRealization +OAI.Analysis.MatrixSigning.Realization.PotentialRealization +OAI.Analysis.MatrixSigning.Realization.RatFieldsRealization +OAI.Analysis.MatrixSigning.Realization.RawMatrixMachine +OAI.Analysis.MatrixSigning.Realization.RawRationalArrayMachine +OAI.Analysis.MatrixSigning.Realization.RawRationalBounds +OAI.Analysis.MatrixSigning.Realization.RawRationalMachine +OAI.Analysis.MatrixSigning.Realization.Realization +OAI.Analysis.MatrixSigning.Realization.RootRealization +OAI.Analysis.MatrixSigning.Realization.RoundedStepRealization +OAI.Analysis.MatrixSigning.Realization.RoutineLength +OAI.Analysis.MatrixSigning.Realization.ScalarRealization +OAI.Analysis.MatrixSigning.Realization.ScheduleRealization +OAI.Analysis.MatrixSigning.Realization.SearchRealization +OAI.Analysis.MatrixSigning.Realization.SelectionRealization +OAI.Analysis.MatrixSigning.Realization.StencilRealization +OAI.Analysis.MatrixSigning.Realization.StoredPSDRealization +OAI.Analysis.MatrixSigning.Realization.ValueDataRealization +OAI.Analysis.MatrixSigning.Realization.ValueEvalRealization +OAI.Analysis.MatrixSigning.Realization.ValueObjectiveRealization +OAI.Analysis.MatrixSigning.Realization.ValueQueryRealization +OAI.Analysis.MatrixSigning.Realization.VarianceRealization +OAI.Analysis.MatrixSigning.Realization.VectorRealization +OAI.Analysis.MatrixSigning.Realization.WitnessRealization +OAI.Combinatorics.ThinTrees.Affine +OAI.Combinatorics.ThinTrees.AlgorithmicMain +OAI.Combinatorics.ThinTrees.Arithmetic.ArraySums +OAI.Combinatorics.ThinTrees.Arithmetic.BinaryArithmetic +OAI.Combinatorics.ThinTrees.Arithmetic.BoolPrograms +OAI.Combinatorics.ThinTrees.Arithmetic.ScalarRealization +OAI.Combinatorics.ThinTrees.Arithmetic.UnaryArithmetic +OAI.Combinatorics.ThinTrees.Arithmetic.UnaryRoot +OAI.Combinatorics.ThinTrees.Arithmetic.WordHead +OAI.Combinatorics.ThinTrees.AssignedFamilies +OAI.Combinatorics.ThinTrees.Assignment +OAI.Combinatorics.ThinTrees.BagBounds +OAI.Combinatorics.ThinTrees.BagConstruction +OAI.Combinatorics.ThinTrees.BagGeometry +OAI.Combinatorics.ThinTrees.Barrier +OAI.Combinatorics.ThinTrees.BasePacking +OAI.Combinatorics.ThinTrees.Blocks +OAI.Combinatorics.ThinTrees.Capture +OAI.Combinatorics.ThinTrees.ChainEdges +OAI.Combinatorics.ThinTrees.Characteristic +OAI.Combinatorics.ThinTrees.Coarea +OAI.Combinatorics.ThinTrees.CompactPacking +OAI.Combinatorics.ThinTrees.Continuation.BitBound +OAI.Combinatorics.ThinTrees.Continuation.CenteredDomain +OAI.Combinatorics.ThinTrees.Continuation.ConcaveAlternative +OAI.Combinatorics.ThinTrees.Continuation.Coordinates +OAI.Combinatorics.ThinTrees.Continuation.Domain +OAI.Combinatorics.ThinTrees.Continuation.Encoding +OAI.Combinatorics.ThinTrees.Continuation.Feasibility +OAI.Combinatorics.ThinTrees.Continuation.FiniteContinuation +OAI.Combinatorics.ThinTrees.Continuation.Gains +OAI.Combinatorics.ThinTrees.Continuation.Grid +OAI.Combinatorics.ThinTrees.Continuation.Interior +OAI.Combinatorics.ThinTrees.Continuation.Iteration +OAI.Combinatorics.ThinTrees.Continuation.Loop +OAI.Combinatorics.ThinTrees.Continuation.Margin +OAI.Combinatorics.ThinTrees.Continuation.PartitionGeometry +OAI.Combinatorics.ThinTrees.Continuation.PartitionLattice +OAI.Combinatorics.ThinTrees.Continuation.PartitionLocalConnectivity +OAI.Combinatorics.ThinTrees.Continuation.PartitionResponse +OAI.Combinatorics.ThinTrees.Continuation.PartitionUncrossing +OAI.Combinatorics.ThinTrees.Continuation.Pencil +OAI.Combinatorics.ThinTrees.Continuation.PencilCorrectness +OAI.Combinatorics.ThinTrees.Continuation.Ramp +OAI.Combinatorics.ThinTrees.Continuation.Realization +OAI.Combinatorics.ThinTrees.Continuation.Schedule +OAI.Combinatorics.ThinTrees.Continuation.Search +OAI.Combinatorics.ThinTrees.Continuation.SpectralSize +OAI.Combinatorics.ThinTrees.Continuation.Start +OAI.Combinatorics.ThinTrees.Density +OAI.Combinatorics.ThinTrees.DeterminantCalculus +OAI.Combinatorics.ThinTrees.Duality +OAI.Combinatorics.ThinTrees.DyadicSelection +OAI.Combinatorics.ThinTrees.Encoding.AlgorithmicMain +OAI.Combinatorics.ThinTrees.Encoding.BinaryReduction +OAI.Combinatorics.ThinTrees.Encoding.BoundaryCases +OAI.Combinatorics.ThinTrees.Encoding.CanonicalExpansion +OAI.Combinatorics.ThinTrees.Encoding.GraphRealization +OAI.Combinatorics.ThinTrees.Encoding.GreedyRealization +OAI.Combinatorics.ThinTrees.Encoding.GreedyTree +OAI.Combinatorics.ThinTrees.Encoding.InputArrays +OAI.Combinatorics.ThinTrees.Encoding.InputDispatch +OAI.Combinatorics.ThinTrees.Encoding.InputExpansion +OAI.Combinatorics.ThinTrees.Encoding.InputOutput +OAI.Combinatorics.ThinTrees.Encoding.OrderedGraph +OAI.Combinatorics.ThinTrees.Encoding.SelectionRealization +OAI.Combinatorics.ThinTrees.Encoding.Specification +OAI.Combinatorics.ThinTrees.Expectation +OAI.Combinatorics.ThinTrees.Extraction +OAI.Combinatorics.ThinTrees.ExtractionBounds +OAI.Combinatorics.ThinTrees.ExtractionCriterion +OAI.Combinatorics.ThinTrees.ExtractionLimit +OAI.Combinatorics.ThinTrees.FiniteSelection +OAI.Combinatorics.ThinTrees.FixedPoint +OAI.Combinatorics.ThinTrees.Flow.FractionalOrientation +OAI.Combinatorics.ThinTrees.Flow.FractionalPackingMargin +OAI.Combinatorics.ThinTrees.Flow.Interior +OAI.Combinatorics.ThinTrees.Flow.ParallelCopies +OAI.Combinatorics.ThinTrees.Flow.RootedFlow +OAI.Combinatorics.ThinTrees.Flow.RootedOrientation +OAI.Combinatorics.ThinTrees.Flow.RootedRelaxation +OAI.Combinatorics.ThinTrees.GraphMatrix +OAI.Combinatorics.ThinTrees.Hierarchy +OAI.Combinatorics.ThinTrees.HierarchyBounds +OAI.Combinatorics.ThinTrees.HierarchyBuilder +OAI.Combinatorics.ThinTrees.HierarchyResponse +OAI.Combinatorics.ThinTrees.IndependentVectors +OAI.Combinatorics.ThinTrees.Interlacing +OAI.Combinatorics.ThinTrees.Iteration +OAI.Combinatorics.ThinTrees.IterationBounds +OAI.Combinatorics.ThinTrees.Main +OAI.Combinatorics.ThinTrees.Matrix +OAI.Combinatorics.ThinTrees.MatrixDomain +OAI.Combinatorics.ThinTrees.MatrixMixture +OAI.Combinatorics.ThinTrees.Metric.AssignedCharging +OAI.Combinatorics.ThinTrees.Metric.AssignedGeometry +OAI.Combinatorics.ThinTrees.Metric.BagExtraction +OAI.Combinatorics.ThinTrees.Metric.CenteredMatrices +OAI.Combinatorics.ThinTrees.Metric.CompactCharging +OAI.Combinatorics.ThinTrees.Metric.CompactDuality +OAI.Combinatorics.ThinTrees.Metric.ConeRepresentation +OAI.Combinatorics.ThinTrees.Metric.ConicDuality +OAI.Combinatorics.ThinTrees.Metric.Hierarchy +OAI.Combinatorics.ThinTrees.Metric.MatrixBound +OAI.Combinatorics.ThinTrees.Metric.Numerator +OAI.Combinatorics.ThinTrees.Metric.Profiles +OAI.Combinatorics.ThinTrees.Metric.Response +OAI.Combinatorics.ThinTrees.Metric.ScaleCharging +OAI.Combinatorics.ThinTrees.Metric.ShellCharging +OAI.Combinatorics.ThinTrees.Metric.SpectralMetricBridge +OAI.Combinatorics.ThinTrees.MixedPolynomial +OAI.Combinatorics.ThinTrees.Model +OAI.Combinatorics.ThinTrees.Monicity +OAI.Combinatorics.ThinTrees.Normalization +OAI.Combinatorics.ThinTrees.Normalization.Algorithm +OAI.Combinatorics.ThinTrees.Normalization.Descent +OAI.Combinatorics.ThinTrees.Normalization.Packing +OAI.Combinatorics.ThinTrees.Normalization.Parameters +OAI.Combinatorics.ThinTrees.Normalization.Realization +OAI.Combinatorics.ThinTrees.OptionalDirections +OAI.Combinatorics.ThinTrees.Padding +OAI.Combinatorics.ThinTrees.PartialFractions +OAI.Combinatorics.ThinTrees.PartitionHierarchy +OAI.Combinatorics.ThinTrees.PartitionRank +OAI.Combinatorics.ThinTrees.Partitions +OAI.Combinatorics.ThinTrees.Pencil.AffinePencil +OAI.Combinatorics.ThinTrees.Pencil.BlockAssembly +OAI.Combinatorics.ThinTrees.Pencil.FiniteFamilies +OAI.Combinatorics.ThinTrees.Pencil.MatrixConstraintRealization +OAI.Combinatorics.ThinTrees.Pencil.Parameters +OAI.Combinatorics.ThinTrees.Pencil.PointPrograms +OAI.Combinatorics.ThinTrees.Pencil.RationalAffineEval +OAI.Combinatorics.ThinTrees.Pencil.Realization +OAI.Combinatorics.ThinTrees.Pencil.ScalarConstraintRealization +OAI.Combinatorics.ThinTrees.Pencil.SearchRealization +OAI.Combinatorics.ThinTrees.Phases +OAI.Combinatorics.ThinTrees.RankOne +OAI.Combinatorics.ThinTrees.RationalMatrix.Gram +OAI.Combinatorics.ThinTrees.RationalMatrix.Inverse +OAI.Combinatorics.ThinTrees.RationalMatrix.InverseRealization +OAI.Combinatorics.ThinTrees.RationalMatrix.MatrixRealization +OAI.Combinatorics.ThinTrees.RationalMatrix.SchurHistory +OAI.Combinatorics.ThinTrees.RationalMatrix.Squares +OAI.Combinatorics.ThinTrees.RealRoots +OAI.Combinatorics.ThinTrees.Records +OAI.Combinatorics.ThinTrees.Representation +OAI.Combinatorics.ThinTrees.ResponseBounds +OAI.Combinatorics.ThinTrees.ResponseFixedPoint +OAI.Combinatorics.ThinTrees.Restriction +OAI.Combinatorics.ThinTrees.RootBound +OAI.Combinatorics.ThinTrees.Selection +OAI.Combinatorics.ThinTrees.Shells +OAI.Combinatorics.ThinTrees.ShortcutDuality +OAI.Combinatorics.ThinTrees.Signing.FormSigning +OAI.Combinatorics.ThinTrees.Signing.GramRealization +OAI.Combinatorics.ThinTrees.Signing.GramWhitening +OAI.Combinatorics.ThinTrees.Signing.RationalSigning +OAI.Combinatorics.ThinTrees.Signing.RealMatrixBridge +OAI.Combinatorics.ThinTrees.Signing.Realization +OAI.Combinatorics.ThinTrees.Signing.StackedSigning +OAI.Combinatorics.ThinTrees.SimultaneousResponse +OAI.Combinatorics.ThinTrees.Sparsification +OAI.Combinatorics.ThinTrees.Sparsification.ExplicitAlgorithm +OAI.Combinatorics.ThinTrees.Sparsification.GraphCertificates +OAI.Combinatorics.ThinTrees.Sparsification.GraphicHalf +OAI.Combinatorics.ThinTrees.Sparsification.GraphicNormalization +OAI.Combinatorics.ThinTrees.Sparsification.HalfNumeric +OAI.Combinatorics.ThinTrees.Sparsification.IterationPotential +OAI.Combinatorics.ThinTrees.Sparsification.IterationRealization +OAI.Combinatorics.ThinTrees.Sparsification.RationalIteration +OAI.Combinatorics.ThinTrees.Sparsification.Realization +OAI.Combinatorics.ThinTrees.Sparsification.ShortcutExtraction +OAI.Combinatorics.ThinTrees.Sparsification.Step +OAI.Combinatorics.ThinTrees.SparsifyGeometry +OAI.Combinatorics.ThinTrees.SpectralPacking +OAI.Combinatorics.ThinTrees.SpectralSplit +OAI.Combinatorics.ThinTrees.Stability +OAI.Combinatorics.ThinTrees.StepBounds +OAI.Combinatorics.ThinTrees.Subisotropic +OAI.Combinatorics.ThinTrees.ThresholdChain +OAI.Combinatorics.ThinTrees.Translation +OAI.Combinatorics.ThinTrees.Truncation +OAI.Combinatorics.ThinTrees.TwoSystems diff --git a/tasks/algorithmic-thin-trees/solution/reference.py b/tasks/algorithmic-thin-trees/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/algorithmic-thin-trees/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/algorithmic-thin-trees/solution/solve.sh b/tasks/algorithmic-thin-trees/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6969eec174eaebad7b6d3b65500e0f2a6a8d487b --- /dev/null +++ b/tasks/algorithmic-thin-trees/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AlgorithmicThinTrees, i.e. module OAI.Combinatorics.ThinTrees.AlgorithmicMain and the +# 736 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ThinTrees.AlgorithmicMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AlgorithmicThinTrees" diff --git a/tasks/algorithmic-thin-trees/task.toml b/tasks/algorithmic-thin-trees/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fa5b93b5b749e59beb5be3a2de94d6f8e46ab513 --- /dev/null +++ b/tasks/algorithmic-thin-trees/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/algorithmic-thin-trees" +version = "1.0.0" +description = "Prove AlgorithmicThinTrees (openai/math family 174: Deterministic construction of strong thin spanning trees) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AlgorithmicThinTrees.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AlgorithmicThinTrees" +family = "174" +family_title = "Deterministic construction of strong thin spanning trees" +subject = "Combinatorics" +theorems = ["OAI.AlgorithmicThinTrees.algorithmic_strong_thin_trees"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ThinTrees.AlgorithmicMain" +reference_modules = 736 +reference_lean_bytes = 4556988 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2906 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15801 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/algorithmic-thin-trees/tests/Challenge.lean b/tasks/algorithmic-thin-trees/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e1e65005f2bd42e099802071437459c1f1d6990 --- /dev/null +++ b/tasks/algorithmic-thin-trees/tests/Challenge.lean @@ -0,0 +1,196 @@ +import Mathlib + +namespace OAI + +/-! Deterministic polynomial-time construction of strong thin trees. -/ + +namespace StrongThinTree + +structure MultiGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + loopless : ∀ e, left e ≠ right e + +namespace MultiGraph + +def cut {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) + (S : Finset (Fin n)) : Finset (Fin m) := + T.filter fun e => (G.left e ∈ S ∧ G.right e ∉ S) ∨ + (G.right e ∈ S ∧ G.left e ∉ S) + +def Connected {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → (G.cut T S).Nonempty + +def SpanningTree {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + G.Connected T ∧ ∀ e ∈ T, ¬ G.Connected (T.erase e) + +def EdgeConnected {n m : ℕ} (G : MultiGraph n m) (k : ℕ) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + k ≤ (G.cut Finset.univ S).card + +end MultiGraph +end StrongThinTree + +namespace CurrentKS + +def frame : List Bool → List Bool + | [] => [true] + | b :: bs => false :: b :: frame bs + +def encodeNat (n : ℕ) : List Bool := frame (Computability.encodeNat n) + +inductive StackAction where + | stay + | pop + | push (bit : Bool) + deriving DecidableEq + +def StackAction.apply : StackAction → List Bool → List Bool + | .stay, xs => xs + | .pop, xs => xs.tail + | .push b, xs => b :: xs + +structure Instruction (k q : ℕ) where + next : Option (Fin q) + actions : Fin k → StackAction + +def Instruction.halt (k q : ℕ) : Instruction k q := ⟨none, fun _ => .stay⟩ + +structure Machine where + stackCount : ℕ + states : ℕ + initial : Fin states + inputStack : Fin stackCount + outputStack : Fin stackCount + table : List (Instruction stackCount states) + +structure Config (k q : ℕ) where + state : Option (Fin q) + «stacks» : Fin k → List Bool + +def topCode : List Bool → ℕ + | [] => 0 + | false :: _ => 1 + | true :: _ => 2 + +def headsCode : (k : ℕ) → (Fin k → List Bool) → ℕ + | 0, _ => 0 + | k + 1, s => topCode (s 0) + 3 * headsCode k (fun j => s j.succ) + +def Machine.step (M : Machine) (c : Config M.stackCount M.states) : + Config M.stackCount M.states := + match c.state with + | none => c + | some q => + let instruction := M.table.getD + (3 ^ M.stackCount * q.val + headsCode M.stackCount c.stacks) + (Instruction.halt M.stackCount M.states) + ⟨instruction.next, fun j => (instruction.actions j).apply (c.stacks j)⟩ + +def Machine.init (M : Machine) (input : List Bool) : Config M.stackCount M.states := + ⟨some M.initial, fun j => if j = M.inputStack then input else []⟩ + +def Machine.run (M : Machine) (input : List Bool) (fuel : ℕ) : + Config M.stackCount M.states := (M.step^[fuel]) (M.init input) + +end CurrentKS + +namespace AlgorithmicThinTrees +open StrongThinTree + +structure ExplicitInput where + n : ℕ + m : ℕ + k : ℕ + graph : MultiGraph n m + +structure BinaryInput where + n : ℕ + p : ℕ + k : ℕ + left : Fin p → Fin n + right : Fin p → Fin n + ordered : ∀ i, left i < right i + distinct : Function.Injective (fun i => (left i, right i)) + multiplicity : Fin p → ℕ + +abbrev BinaryInput.Edge (x : BinaryInput) := Σ i : Fin x.p, Fin (x.multiplicity i) + +noncomputable def BinaryInput.edgeEquiv (x : BinaryInput) : + x.Edge ≃ Fin (Fintype.card x.Edge) := Fintype.equivFin x.Edge + +noncomputable def BinaryInput.graph (x : BinaryInput) : + MultiGraph x.n (Fintype.card x.Edge) where + left e := x.left (x.edgeEquiv.symm e).1 + right e := x.right (x.edgeEquiv.symm e).1 + loopless e := ne_of_lt (x.ordered (x.edgeEquiv.symm e).1) + +inductive Input where + | explicit (x : ExplicitInput) + | binary (x : BinaryInput) + +def ExplicitInput.encode (x : ExplicitInput) : List Bool := + CurrentKS.encodeNat x.n ++ CurrentKS.encodeNat x.m ++ CurrentKS.encodeNat x.k ++ + (List.ofFn fun i : Fin x.m => + CurrentKS.encodeNat (x.graph.left i).val ++ + CurrentKS.encodeNat (x.graph.right i).val).flatten + +def BinaryInput.encode (x : BinaryInput) : List Bool := + CurrentKS.encodeNat x.n ++ CurrentKS.encodeNat x.p ++ CurrentKS.encodeNat x.k ++ + (List.ofFn fun i : Fin x.p => + CurrentKS.encodeNat (x.left i).val ++ CurrentKS.encodeNat (x.right i).val ++ + CurrentKS.encodeNat (x.multiplicity i)).flatten + +def Input.encode : Input → List Bool + | .explicit x => false :: x.encode + | .binary x => true :: x.encode + +def Input.length (x : Input) : ℕ := x.encode.length + +def Input.n : Input → ℕ + | .explicit x => x.n + | .binary x => x.n + +def Valid : Input → Prop + | .explicit x => 1 ≤ x.n ∧ 1 ≤ x.k ∧ x.graph.EdgeConnected x.k + | .binary x => 1 ≤ x.n ∧ 1 ≤ x.k ∧ x.graph.EdgeConnected x.k + +def ThinTree {n m : ℕ} (C : ℝ) (k : ℕ) (G : MultiGraph n m) + (T : Finset (Fin m)) : Prop := + G.SpanningTree T ∧ ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + ((G.cut T S).card : ℝ) ≤ C / (k : ℝ) * (G.cut Finset.univ S).card + +def ExplicitInput.encodeEdges (x : ExplicitInput) (edges : List (Fin x.m)) : List Bool := + edges.flatMap (fun e => CurrentKS.encodeNat e.val) + +def BinaryInput.encodeEdges (x : BinaryInput) (edges : List x.Edge) : List Bool := + edges.flatMap (fun e => CurrentKS.encodeNat e.1.val ++ CurrentKS.encodeNat e.2.val) + +noncomputable def BinaryInput.selected (x : BinaryInput) (edges : List x.Edge) : + Finset (Fin (Fintype.card x.Edge)) := edges.toFinset.map x.edgeEquiv.toEmbedding + +def TreeOutput (C : ℝ) : Input → List Bool → Prop + | .explicit x, bits => ∃ edges : List (Fin x.m), edges.Nodup ∧ + bits = x.encodeEdges edges ∧ ThinTree C x.k x.graph edges.toFinset + | .binary x, bits => ∃ edges : List x.Edge, edges.Nodup ∧ + bits = x.encodeEdges edges ∧ ThinTree C x.k x.graph (x.selected edges) + +def GoodOutput (C : ℝ) (x : Input) (bits : List Bool) : Prop := + TreeOutput C x bits ∧ (x.n = 1 → bits = []) + +def AlgorithmicStrongThinTrees : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ M : CurrentKS.Machine, ∃ a degree : ℕ, 0 < a ∧ + ∀ x : Input, Valid x → + let result := M.run x.encode (a * (x.length + 1) ^ degree) + result.state = none ∧ GoodOutput C x (result.stacks M.outputStack) + +end AlgorithmicThinTrees + +namespace AlgorithmicThinTrees + +theorem algorithmic_strong_thin_trees : AlgorithmicStrongThinTrees := by + sorry + +end AlgorithmicThinTrees + +end OAI diff --git a/tasks/algorithmic-thin-trees/tests/grade.py b/tasks/algorithmic-thin-trees/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/algorithmic-thin-trees/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/algorithmic-thin-trees/tests/task.json b/tasks/algorithmic-thin-trees/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..158e308e4a1df0ec23ec771b2c31cf1a2945b867 --- /dev/null +++ b/tasks/algorithmic-thin-trees/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AlgorithmicThinTrees", + "comparator": { + "theorem_names": [ + "OAI.AlgorithmicThinTrees.algorithmic_strong_thin_trees" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14901 +} \ No newline at end of file diff --git a/tasks/algorithmic-thin-trees/tests/test.sh b/tasks/algorithmic-thin-trees/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/algorithmic-thin-trees/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/amplitude-damping/environment/Dockerfile b/tasks/amplitude-damping/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/amplitude-damping/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/amplitude-damping/environment/fetch_mathlib.sh b/tasks/amplitude-damping/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/amplitude-damping/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/amplitude-damping/environment/lake-manifest.json b/tasks/amplitude-damping/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/amplitude-damping/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/amplitude-damping/environment/lakefile.lean b/tasks/amplitude-damping/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/amplitude-damping/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/amplitude-damping/environment/lean_setup.sh b/tasks/amplitude-damping/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/amplitude-damping/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/amplitude-damping/environment/pack_submission.py b/tasks/amplitude-damping/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/amplitude-damping/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/amplitude-damping/instruction.md b/tasks/amplitude-damping/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a7ab1f2661e4f005635cfad054a56f5c3d098108 --- /dev/null +++ b/tasks/amplitude-damping/instruction.md @@ -0,0 +1,178 @@ +# openai/math challenge `AmplitudeDamping` (family 276) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 276 of the release, *The classical capacity of generalized amplitude damping* +(Mathematical physics). The family as a whole: Determines the unassisted classical capacity of every qubit generalized amplitude-damping channel, including all damping and thermal parameters. An explicit one-variable optimization gives the capacity, attained by independent two-state signal ensembles with collective decoding. Holevo capacity, minimum output entropy and regularized classical capacity are additive when tensoring with any finite-dimensional quantum channel. + +The challenge is `AmplitudeDamping`, also at `/opt/openai-math/challenges/AmplitudeDamping.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u + +noncomputable section +open scoped BigOperators ComplexOrder +open Matrix Filter + +namespace GAD + +abbrev Basis (n : ℕ) := Fin n → Fin 2 +abbrev QMatrix (n : ℕ) := Matrix (Basis n) (Basis n) ℂ + +/-- The spectral definition of -Tr(P log P), with 0 log 0 = 0. -/ +def entropy {ι : Type u} [Fintype ι] [DecidableEq ι] (P : Matrix ι ι ℂ) : ℝ := + (Matrix.trace (cfc Real.negMulLog P)).re + +def IsState {ι : Type u} [Fintype ι] [DecidableEq ι] (P : Matrix ι ι ℂ) : Prop := + P.PosSemidef ∧ Matrix.trace P = 1 + + +def kraus (γ ν : ℝ) (r : Fin 4) : Matrix (Fin 2) (Fin 2) ℂ := + if r = 0 then + !![(Real.sqrt (1 - ν) : ℂ), 0; + 0, (Real.sqrt (1 - ν) * Real.sqrt (1 - γ) : ℂ)] + else if r = 1 then + !![0, (Real.sqrt (γ * (1 - ν)) : ℂ); 0, 0] + else if r = 2 then + !![(Real.sqrt ν * Real.sqrt (1 - γ) : ℂ), 0; 0, (Real.sqrt ν : ℂ)] + else + !![0, 0; (Real.sqrt (γ * ν) : ℂ), 0] + +/-- Tensor products of the single-site Kraus operators, with the full Kraus index. -/ +def tensorKraus (γ ν : ℝ) (n : ℕ) (r : Fin n → Fin 4) : QMatrix n := + fun i j ↦ ∏ k, kraus γ ν (r k) (i k) (j k) + +/-- The memoryless n-fold generalized amplitude-damping channel. -/ +def channel (γ ν : ℝ) (n : ℕ) (P : QMatrix n) : QMatrix n := + ∑ r : Fin n → Fin 4, + tensorKraus γ ν n r * P * (tensorKraus γ ν n r).conjTranspose + +/-- All finite ensembles, without any product or purity restriction. -/ +structure Ensemble (n : ℕ) where + size : ℕ + weight : Fin size → ℝ + weight_nonneg : ∀ a, 0 ≤ weight a + weight_sum : ∑ a, weight a = 1 + signal : Fin size → QMatrix n + signal_state : ∀ a, IsState (signal a) + +def ensembleValue (γ ν : ℝ) {n : ℕ} (E : Ensemble n) : ℝ := + (entropy (∑ a, (E.weight a : ℂ) • channel γ ν n (E.signal a)) - + ∑ a, E.weight a * entropy (channel γ ν n (E.signal a))) / Real.log 2 + + +def holevo (γ ν : ℝ) (n : ℕ) : ℝ := + sSup (Set.range (ensembleValue γ ν : Ensemble n → ℝ)) + +/-- An unrestricted n-use quantum code with one collective output POVM. -/ +structure Code (n : ℕ) where + messages : ℕ + messages_pos : 0 < messages + encoding : Fin messages → QMatrix n + encoding_state : ∀ a, IsState (encoding a) + decoding : Fin messages → QMatrix n + decoding_pos : ∀ a, (decoding a).PosSemidef + decoding_sum : ∑ a, decoding a = 1 + +def averageError (γ ν : ℝ) {n : ℕ} (C : Code n) : ℝ := + 1 - (∑ a, (Matrix.trace (C.decoding a * channel γ ν n (C.encoding a))).re) / + (C.messages : ℝ) + +/-- The liminf rate condition written as its eventual lower-bound characterization. +There is no preshared entanglement, feedback, or restriction on encodings/decoding. -/ +def Achievable (γ ν R : ℝ) : Prop := + ∃ C : (n : ℕ) → Code n, + Tendsto (fun n ↦ averageError γ ν (C n)) atTop (nhds 0) ∧ + ∀ ε : ℝ, 0 < ε → ∀ᶠ n : ℕ in atTop, + R - ε ≤ Real.log ((C n).messages : ℝ) / Real.log 2 / (n : ℝ) + +/-- Operational unassisted classical capacity, not a definition by regularization. -/ +def capacity (γ ν : ℝ) : ℝ := sSup {R : ℝ | Achievable γ ν R} + +def g (u : ℝ) : ℝ := Real.binEntropy ((1 + Real.sqrt (1 - 4 * u)) / 2) + +def v (γ ν p : ℝ) : ℝ := γ * ν * (1 - ν) + γ * (1 - γ) * (p - ν) ^ 2 + +def objective (γ ν p : ℝ) : ℝ := + Real.binEntropy ((1 - γ) * p + γ * ν) - g (v γ ν p) + +def Maximizes (γ ν p : ℝ) : Prop := + p ∈ Set.Icc (0 : ℝ) 1 ∧ ∀ q ∈ Set.Icc (0 : ℝ) 1, objective γ ν q ≤ objective γ ν p + + +def phaseSignal (p : ℝ) (s b : Fin 2) : ℂ := + if b = 0 then (Real.sqrt (1 - p) : ℂ) + else if s = 0 then (Real.sqrt p : ℂ) else -(Real.sqrt p : ℂ) + +def phaseProduct (p : ℝ) {n : ℕ} (s : Basis n) (i : Basis n) : ℂ := + ∏ k, phaseSignal p (s k) (i k) + +def phaseState (p : ℝ) {n : ℕ} (s : Basis n) : QMatrix n := + fun i j ↦ phaseProduct p s i * star (phaseProduct p s j) + +/-- Holevo value of the explicit 2^n equiprobable product signals. -/ +def phaseValue (γ ν p : ℝ) (n : ℕ) : ℝ := + (entropy (∑ s : Basis n, (((2 : ℝ) ^ n)⁻¹ : ℂ) • channel γ ν n (phaseState p s)) - + ∑ s : Basis n, ((2 : ℝ) ^ n)⁻¹ * entropy (channel γ ν n (phaseState p s))) / + Real.log 2 + +theorem main (γ ν : ℝ) (hγ : γ ∈ Set.Icc (0 : ℝ) 1) + (hν : ν ∈ Set.Icc (0 : ℝ) 1) : + (∀ n : ℕ, 1 ≤ n → holevo γ ν n = (n : ℝ) * holevo γ ν 1) ∧ + (∃ p : ℝ, Maximizes γ ν p ∧ + ∀ n : ℕ, 1 ≤ n → holevo γ ν n = (n : ℝ) / Real.log 2 * objective γ ν p) ∧ + capacity γ ν = holevo γ ν 1 ∧ + (∀ p : ℝ, Maximizes γ ν p → ∀ n : ℕ, 1 ≤ n → + (∀ s : Basis n, IsState (phaseState p s)) ∧ + holevo γ ν n = phaseValue γ ν p n) := by + sorry + +end GAD +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AmplitudeDamping.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GAD.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/amplitude-damping/solution/closure.txt b/tasks/amplitude-damping/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3eef79d75df9ee4f5364b985bfd9952f97d31d5 --- /dev/null +++ b/tasks/amplitude-damping/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.InformationTheory.AmplitudeDamping.BlockFactors +OAI.InformationTheory.AmplitudeDamping.CapacityAchievability +OAI.InformationTheory.AmplitudeDamping.CapacityConverse +OAI.InformationTheory.AmplitudeDamping.Channel +OAI.InformationTheory.AmplitudeDamping.CodingAsymptotics +OAI.InformationTheory.AmplitudeDamping.EnsembleBounds +OAI.InformationTheory.AmplitudeDamping.EntropyContinuity +OAI.InformationTheory.AmplitudeDamping.FinitePacking +OAI.InformationTheory.AmplitudeDamping.GramMatrices +OAI.InformationTheory.AmplitudeDamping.Holevo +OAI.InformationTheory.AmplitudeDamping.HolevoInformation +OAI.InformationTheory.AmplitudeDamping.LogDetConvexity +OAI.InformationTheory.AmplitudeDamping.LogDetEntropy +OAI.InformationTheory.AmplitudeDamping.Main +OAI.InformationTheory.AmplitudeDamping.MatrixDifferentiation +OAI.InformationTheory.AmplitudeDamping.Model +OAI.InformationTheory.AmplitudeDamping.Naimark +OAI.InformationTheory.AmplitudeDamping.OutputConvexity +OAI.InformationTheory.AmplitudeDamping.OutputEntropy +OAI.InformationTheory.AmplitudeDamping.PhaseCoding +OAI.InformationTheory.AmplitudeDamping.PhaseProducts +OAI.InformationTheory.AmplitudeDamping.PhaseStates +OAI.InformationTheory.AmplitudeDamping.Pinching +OAI.InformationTheory.AmplitudeDamping.PureRecursion +OAI.InformationTheory.AmplitudeDamping.ScalarDeficit +OAI.InformationTheory.AmplitudeDamping.SequentialDecoder +OAI.InformationTheory.AmplitudeDamping.SequentialMatrices +OAI.InformationTheory.AmplitudeDamping.SequentialProjections +OAI.InformationTheory.AmplitudeDamping.SpectralEntropy +OAI.InformationTheory.AmplitudeDamping.StateEntropy +OAI.InformationTheory.AmplitudeDamping.TensorEntropy +OAI.InformationTheory.AmplitudeDamping.ThermalEntropy +OAI.InformationTheory.AmplitudeDamping.TypicalProjectors +OAI.InformationTheory.AmplitudeDamping.TypicalSets +OAI.InformationTheory.AmplitudeDamping.ZeroBlockEntropy diff --git a/tasks/amplitude-damping/solution/reference.py b/tasks/amplitude-damping/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/amplitude-damping/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/amplitude-damping/solution/solve.sh b/tasks/amplitude-damping/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8f0120f69df5a319678f9775b67627d758580f8d --- /dev/null +++ b/tasks/amplitude-damping/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AmplitudeDamping, i.e. module OAI.InformationTheory.AmplitudeDamping.Main and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.AmplitudeDamping.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AmplitudeDamping" diff --git a/tasks/amplitude-damping/task.toml b/tasks/amplitude-damping/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7bc55f1ee5b2ed7419a34a684089e374aa4cb420 --- /dev/null +++ b/tasks/amplitude-damping/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/amplitude-damping" +version = "1.0.0" +description = "Prove AmplitudeDamping (openai/math family 276: The classical capacity of generalized amplitude damping) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AmplitudeDamping.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AmplitudeDamping" +family = "276" +family_title = "The classical capacity of generalized amplitude damping" +subject = "Mathematical physics" +theorems = ["OAI.GAD.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.AmplitudeDamping.Main" +reference_modules = 35 +reference_lean_bytes = 283452 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1119 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11955 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/amplitude-damping/tests/Challenge.lean b/tasks/amplitude-damping/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ac5f251c095417ac4a798d59959db85f6865fee8 --- /dev/null +++ b/tasks/amplitude-damping/tests/Challenge.lean @@ -0,0 +1,127 @@ +import Mathlib + +namespace OAI + +universe u + +noncomputable section +open scoped BigOperators ComplexOrder +open Matrix Filter + +namespace GAD + +abbrev Basis (n : ℕ) := Fin n → Fin 2 +abbrev QMatrix (n : ℕ) := Matrix (Basis n) (Basis n) ℂ + +/-- The spectral definition of -Tr(P log P), with 0 log 0 = 0. -/ +def entropy {ι : Type u} [Fintype ι] [DecidableEq ι] (P : Matrix ι ι ℂ) : ℝ := + (Matrix.trace (cfc Real.negMulLog P)).re + +def IsState {ι : Type u} [Fintype ι] [DecidableEq ι] (P : Matrix ι ι ℂ) : Prop := + P.PosSemidef ∧ Matrix.trace P = 1 + + +def kraus (γ ν : ℝ) (r : Fin 4) : Matrix (Fin 2) (Fin 2) ℂ := + if r = 0 then + !![(Real.sqrt (1 - ν) : ℂ), 0; + 0, (Real.sqrt (1 - ν) * Real.sqrt (1 - γ) : ℂ)] + else if r = 1 then + !![0, (Real.sqrt (γ * (1 - ν)) : ℂ); 0, 0] + else if r = 2 then + !![(Real.sqrt ν * Real.sqrt (1 - γ) : ℂ), 0; 0, (Real.sqrt ν : ℂ)] + else + !![0, 0; (Real.sqrt (γ * ν) : ℂ), 0] + +/-- Tensor products of the single-site Kraus operators, with the full Kraus index. -/ +def tensorKraus (γ ν : ℝ) (n : ℕ) (r : Fin n → Fin 4) : QMatrix n := + fun i j ↦ ∏ k, kraus γ ν (r k) (i k) (j k) + +/-- The memoryless n-fold generalized amplitude-damping channel. -/ +def channel (γ ν : ℝ) (n : ℕ) (P : QMatrix n) : QMatrix n := + ∑ r : Fin n → Fin 4, + tensorKraus γ ν n r * P * (tensorKraus γ ν n r).conjTranspose + +/-- All finite ensembles, without any product or purity restriction. -/ +structure Ensemble (n : ℕ) where + size : ℕ + weight : Fin size → ℝ + weight_nonneg : ∀ a, 0 ≤ weight a + weight_sum : ∑ a, weight a = 1 + signal : Fin size → QMatrix n + signal_state : ∀ a, IsState (signal a) + +def ensembleValue (γ ν : ℝ) {n : ℕ} (E : Ensemble n) : ℝ := + (entropy (∑ a, (E.weight a : ℂ) • channel γ ν n (E.signal a)) - + ∑ a, E.weight a * entropy (channel γ ν n (E.signal a))) / Real.log 2 + + +def holevo (γ ν : ℝ) (n : ℕ) : ℝ := + sSup (Set.range (ensembleValue γ ν : Ensemble n → ℝ)) + +/-- An unrestricted n-use quantum code with one collective output POVM. -/ +structure Code (n : ℕ) where + messages : ℕ + messages_pos : 0 < messages + encoding : Fin messages → QMatrix n + encoding_state : ∀ a, IsState (encoding a) + decoding : Fin messages → QMatrix n + decoding_pos : ∀ a, (decoding a).PosSemidef + decoding_sum : ∑ a, decoding a = 1 + +def averageError (γ ν : ℝ) {n : ℕ} (C : Code n) : ℝ := + 1 - (∑ a, (Matrix.trace (C.decoding a * channel γ ν n (C.encoding a))).re) / + (C.messages : ℝ) + +/-- The liminf rate condition written as its eventual lower-bound characterization. +There is no preshared entanglement, feedback, or restriction on encodings/decoding. -/ +def Achievable (γ ν R : ℝ) : Prop := + ∃ C : (n : ℕ) → Code n, + Tendsto (fun n ↦ averageError γ ν (C n)) atTop (nhds 0) ∧ + ∀ ε : ℝ, 0 < ε → ∀ᶠ n : ℕ in atTop, + R - ε ≤ Real.log ((C n).messages : ℝ) / Real.log 2 / (n : ℝ) + +/-- Operational unassisted classical capacity, not a definition by regularization. -/ +def capacity (γ ν : ℝ) : ℝ := sSup {R : ℝ | Achievable γ ν R} + +def g (u : ℝ) : ℝ := Real.binEntropy ((1 + Real.sqrt (1 - 4 * u)) / 2) + +def v (γ ν p : ℝ) : ℝ := γ * ν * (1 - ν) + γ * (1 - γ) * (p - ν) ^ 2 + +def objective (γ ν p : ℝ) : ℝ := + Real.binEntropy ((1 - γ) * p + γ * ν) - g (v γ ν p) + +def Maximizes (γ ν p : ℝ) : Prop := + p ∈ Set.Icc (0 : ℝ) 1 ∧ ∀ q ∈ Set.Icc (0 : ℝ) 1, objective γ ν q ≤ objective γ ν p + + +def phaseSignal (p : ℝ) (s b : Fin 2) : ℂ := + if b = 0 then (Real.sqrt (1 - p) : ℂ) + else if s = 0 then (Real.sqrt p : ℂ) else -(Real.sqrt p : ℂ) + +def phaseProduct (p : ℝ) {n : ℕ} (s : Basis n) (i : Basis n) : ℂ := + ∏ k, phaseSignal p (s k) (i k) + +def phaseState (p : ℝ) {n : ℕ} (s : Basis n) : QMatrix n := + fun i j ↦ phaseProduct p s i * star (phaseProduct p s j) + +/-- Holevo value of the explicit 2^n equiprobable product signals. -/ +def phaseValue (γ ν p : ℝ) (n : ℕ) : ℝ := + (entropy (∑ s : Basis n, (((2 : ℝ) ^ n)⁻¹ : ℂ) • channel γ ν n (phaseState p s)) - + ∑ s : Basis n, ((2 : ℝ) ^ n)⁻¹ * entropy (channel γ ν n (phaseState p s))) / + Real.log 2 + +theorem main (γ ν : ℝ) (hγ : γ ∈ Set.Icc (0 : ℝ) 1) + (hν : ν ∈ Set.Icc (0 : ℝ) 1) : + (∀ n : ℕ, 1 ≤ n → holevo γ ν n = (n : ℝ) * holevo γ ν 1) ∧ + (∃ p : ℝ, Maximizes γ ν p ∧ + ∀ n : ℕ, 1 ≤ n → holevo γ ν n = (n : ℝ) / Real.log 2 * objective γ ν p) ∧ + capacity γ ν = holevo γ ν 1 ∧ + (∀ p : ℝ, Maximizes γ ν p → ∀ n : ℕ, 1 ≤ n → + (∀ s : Basis n, IsState (phaseState p s)) ∧ + holevo γ ν n = phaseValue γ ν p n) := by + sorry + +end GAD +end + +end OAI diff --git a/tasks/amplitude-damping/tests/grade.py b/tasks/amplitude-damping/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/amplitude-damping/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/amplitude-damping/tests/task.json b/tasks/amplitude-damping/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fa75bcfcbae181c2d224e036931c846a0b547390 --- /dev/null +++ b/tasks/amplitude-damping/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AmplitudeDamping", + "comparator": { + "theorem_names": [ + "OAI.GAD.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11055 +} \ No newline at end of file diff --git a/tasks/amplitude-damping/tests/test.sh b/tasks/amplitude-damping/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/amplitude-damping/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/artin-cat0/environment/Dockerfile b/tasks/artin-cat0/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/artin-cat0/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/artin-cat0/environment/fetch_mathlib.sh b/tasks/artin-cat0/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/artin-cat0/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/artin-cat0/environment/lake-manifest.json b/tasks/artin-cat0/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/artin-cat0/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/artin-cat0/environment/lakefile.lean b/tasks/artin-cat0/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/artin-cat0/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/artin-cat0/environment/lean_setup.sh b/tasks/artin-cat0/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/artin-cat0/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/artin-cat0/environment/pack_submission.py b/tasks/artin-cat0/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/artin-cat0/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/artin-cat0/instruction.md b/tasks/artin-cat0/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7a6075cd38209fe69236a9daab1516b2704d581d --- /dev/null +++ b/tasks/artin-cat0/instruction.md @@ -0,0 +1,128 @@ +# openai/math challenge `ArtinCAT0` (family 254) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 254 of the release, *Classifying spaces and geometric obstructions for Artin groups* +(Group theory). The family as a whole: The Salvetti complex of every finite-rank Artin group is aspherical, proving the Artin $K(\pi,1)$ conjecture. Arbitrary intersections of its parabolic subgroups are parabolic, proving the Parabolic Intersection Conjecture. An explicit Artin group admits no proper cocompact isometric action on any nonempty proper CAT$(0)$ space. + +The challenge is `ArtinCAT0`, also at `/opt/openai-math/challenges/ArtinCAT0.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ArtinCAT0 + +universe uS uG uX + +abbrev Letters := Fin 116 +abbrev Label := WithTop ℕ + +def blockLetter (b : Fin 3) (i : Fin 39) : Letters := + if h₀ : i.val = 0 then ⟨b.val, by omega⟩ + else if h₁ : i.val = 1 then ⟨(b.val + 1) % 3, by omega⟩ + else ⟨5 + 37 * b.val + (i.val - 2), by omega⟩ + +def Adjacent (s t : Letters) : Prop := + ∃ (b : Fin 3) (i j : Fin 39), s = blockLetter b i ∧ t = blockLetter b j ∧ + (i.val + 1 = j.val ∨ j.val + 1 = i.val) + +def Distant (s t : Letters) : Prop := + ∃ (b : Fin 3) (i j : Fin 39), s = blockLetter b i ∧ t = blockLetter b j ∧ + (i.val + 2 ≤ j.val ∨ j.val + 2 ≤ i.val) + +def Sentinel (s t : Letters) : Prop := + ((s.val = 3 ∨ s.val = 4) ∧ t.val < 3) ∨ + ((t.val = 3 ∨ t.val = 4) ∧ s.val < 3) + +noncomputable def explicitMatrix (s t : Letters) : Label := by + classical + exact if s = t then 1 else if Adjacent s t then 3 + else if Distant s t ∨ Sentinel s t then 2 else ⊤ + +def alternating {S : Type uS} (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def artinRelators {S : Type uS} (M : S → S → Label) : Set (FreeGroup S) := + {w | ∃ (s t : S) (n : ℕ), M s t = (n : Label) ∧ + w = alternating s t n * (alternating t s n)⁻¹} + +abbrev ArtinGroup {S : Type uS} (M : S → S → Label) := PresentedGroup (artinRelators M) + +def Segment {X : Type uX} [MetricSpace X] (x y : X) (γ : ℝ → X) : Prop := + γ 0 = x ∧ γ 1 = y ∧ + ∀ s ∈ Set.Icc (0 : ℝ) 1, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist (γ s) (γ t) = |s - t| * dist x y + +def CAT0 (X : Type uX) [MetricSpace X] : Prop := + (∀ x y : X, ∃ γ : ℝ → X, Segment x y γ) ∧ + ∀ (x y z : X) (γ η : ℝ → X), Segment x y γ → Segment x z η → + ∀ t ∈ Set.Icc (0 : ℝ) 1, ∀ u ∈ Set.Icc (0 : ℝ) 1, + dist (γ t) (η u) ^ 2 ≤ + (t ^ 2 - t * u) * dist x y ^ 2 + + (u ^ 2 - t * u) * dist x z ^ 2 + t * u * dist y z ^ 2 + +def GeometricAction (G : Type uG) (X : Type uX) [Group G] [MetricSpace X] [MulAction G X] : Prop := + CAT0 X ∧ + (∀ g : G, Isometry (fun x : X => g • x)) ∧ + (∀ K : Set X, IsCompact K → {g : G | ((fun x : X => g • x) '' K ∩ K).Nonempty}.Finite) ∧ + ∃ K : Set X, IsCompact K ∧ ∀ x : X, ∃ g : G, ∃ k ∈ K, g • k = x + +universe u + +theorem main : + (∀ s t : Letters, explicitMatrix s t = explicitMatrix t s) ∧ + (∀ s : Letters, explicitMatrix s s = 1) ∧ + (∀ s t : Letters, s ≠ t → + explicitMatrix s t = 2 ∨ explicitMatrix s t = 3 ∨ explicitMatrix s t = ⊤) ∧ + (∀ (X : Type u) [MetricSpace X] [ProperSpace X] [Nonempty X] + [MulAction (ArtinGroup explicitMatrix) X], + ¬ GeometricAction (ArtinGroup explicitMatrix) X) := by + sorry + +end ArtinCAT0 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ArtinCAT0.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ArtinCAT0.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/artin-cat0/solution/closure.txt b/tasks/artin-cat0/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e72ff9362a2cfc9a409810779a46ce162301038 --- /dev/null +++ b/tasks/artin-cat0/solution/closure.txt @@ -0,0 +1,20 @@ +OAI.GroupTheory.ArtinCAT0.Braids +OAI.GroupTheory.ArtinCAT0.Cap +OAI.GroupTheory.ArtinCAT0.Centralizer +OAI.GroupTheory.ArtinCAT0.Detour +OAI.GroupTheory.ArtinCAT0.Embeddings +OAI.GroupTheory.ArtinCAT0.Folding +OAI.GroupTheory.ArtinCAT0.Grid +OAI.GroupTheory.ArtinCAT0.Main +OAI.GroupTheory.ArtinCAT0.Mirrors +OAI.GroupTheory.ArtinCAT0.Model +OAI.GroupTheory.ArtinCAT0.Pairing +OAI.GroupTheory.ArtinCAT0.Presentation +OAI.GroupTheory.ArtinCAT0.Refinement +OAI.GroupTheory.ArtinCAT0.SectorCharts +OAI.GroupTheory.ArtinCAT0.SectorMetric +OAI.GroupTheory.ArtinCAT0.StableLength +OAI.GroupTheory.ArtinCAT0.TriangleMesh +OAI.GroupTheory.ArtinCAT0.Winding +OAI.GroupTheory.ArtinCAT0.Wires +OAI.GroupTheory.ArtinCAT0.WordDiagram diff --git a/tasks/artin-cat0/solution/reference.py b/tasks/artin-cat0/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/artin-cat0/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/artin-cat0/solution/solve.sh b/tasks/artin-cat0/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ed618f870e5195ddbfcfb503b0eaf32ef91958e1 --- /dev/null +++ b/tasks/artin-cat0/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ArtinCAT0, i.e. module OAI.GroupTheory.ArtinCAT0.Main and the +# 20 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.ArtinCAT0.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ArtinCAT0" diff --git a/tasks/artin-cat0/task.toml b/tasks/artin-cat0/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..da64eb5d41d785287aafbfa77dca565ff591ee1f --- /dev/null +++ b/tasks/artin-cat0/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/artin-cat0" +version = "1.0.0" +description = "Prove ArtinCAT0 (openai/math family 254: Classifying spaces and geometric obstructions for Artin groups) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ArtinCAT0.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ArtinCAT0" +family = "254" +family_title = "Classifying spaces and geometric obstructions for Artin groups" +subject = "Group theory" +theorems = ["OAI.ArtinCAT0.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.ArtinCAT0.Main" +reference_modules = 20 +reference_lean_bytes = 414894 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 792 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12073 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/artin-cat0/tests/Challenge.lean b/tasks/artin-cat0/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..977b51e31e631e45dd709c847613dceedf45e50f --- /dev/null +++ b/tasks/artin-cat0/tests/Challenge.lean @@ -0,0 +1,77 @@ +import Mathlib + +namespace OAI + +namespace ArtinCAT0 + +universe uS uG uX + +abbrev Letters := Fin 116 +abbrev Label := WithTop ℕ + +def blockLetter (b : Fin 3) (i : Fin 39) : Letters := + if h₀ : i.val = 0 then ⟨b.val, by omega⟩ + else if h₁ : i.val = 1 then ⟨(b.val + 1) % 3, by omega⟩ + else ⟨5 + 37 * b.val + (i.val - 2), by omega⟩ + +def Adjacent (s t : Letters) : Prop := + ∃ (b : Fin 3) (i j : Fin 39), s = blockLetter b i ∧ t = blockLetter b j ∧ + (i.val + 1 = j.val ∨ j.val + 1 = i.val) + +def Distant (s t : Letters) : Prop := + ∃ (b : Fin 3) (i j : Fin 39), s = blockLetter b i ∧ t = blockLetter b j ∧ + (i.val + 2 ≤ j.val ∨ j.val + 2 ≤ i.val) + +def Sentinel (s t : Letters) : Prop := + ((s.val = 3 ∨ s.val = 4) ∧ t.val < 3) ∨ + ((t.val = 3 ∨ t.val = 4) ∧ s.val < 3) + +noncomputable def explicitMatrix (s t : Letters) : Label := by + classical + exact if s = t then 1 else if Adjacent s t then 3 + else if Distant s t ∨ Sentinel s t then 2 else ⊤ + +def alternating {S : Type uS} (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def artinRelators {S : Type uS} (M : S → S → Label) : Set (FreeGroup S) := + {w | ∃ (s t : S) (n : ℕ), M s t = (n : Label) ∧ + w = alternating s t n * (alternating t s n)⁻¹} + +abbrev ArtinGroup {S : Type uS} (M : S → S → Label) := PresentedGroup (artinRelators M) + +def Segment {X : Type uX} [MetricSpace X] (x y : X) (γ : ℝ → X) : Prop := + γ 0 = x ∧ γ 1 = y ∧ + ∀ s ∈ Set.Icc (0 : ℝ) 1, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist (γ s) (γ t) = |s - t| * dist x y + +def CAT0 (X : Type uX) [MetricSpace X] : Prop := + (∀ x y : X, ∃ γ : ℝ → X, Segment x y γ) ∧ + ∀ (x y z : X) (γ η : ℝ → X), Segment x y γ → Segment x z η → + ∀ t ∈ Set.Icc (0 : ℝ) 1, ∀ u ∈ Set.Icc (0 : ℝ) 1, + dist (γ t) (η u) ^ 2 ≤ + (t ^ 2 - t * u) * dist x y ^ 2 + + (u ^ 2 - t * u) * dist x z ^ 2 + t * u * dist y z ^ 2 + +def GeometricAction (G : Type uG) (X : Type uX) [Group G] [MetricSpace X] [MulAction G X] : Prop := + CAT0 X ∧ + (∀ g : G, Isometry (fun x : X => g • x)) ∧ + (∀ K : Set X, IsCompact K → {g : G | ((fun x : X => g • x) '' K ∩ K).Nonempty}.Finite) ∧ + ∃ K : Set X, IsCompact K ∧ ∀ x : X, ∃ g : G, ∃ k ∈ K, g • k = x + +universe u + +theorem main : + (∀ s t : Letters, explicitMatrix s t = explicitMatrix t s) ∧ + (∀ s : Letters, explicitMatrix s s = 1) ∧ + (∀ s t : Letters, s ≠ t → + explicitMatrix s t = 2 ∨ explicitMatrix s t = 3 ∨ explicitMatrix s t = ⊤) ∧ + (∀ (X : Type u) [MetricSpace X] [ProperSpace X] [Nonempty X] + [MulAction (ArtinGroup explicitMatrix) X], + ¬ GeometricAction (ArtinGroup explicitMatrix) X) := by + sorry + +end ArtinCAT0 + +end OAI diff --git a/tasks/artin-cat0/tests/grade.py b/tasks/artin-cat0/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/artin-cat0/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/artin-cat0/tests/task.json b/tasks/artin-cat0/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..275970b767e7ed89a2cc907fbc4a1826ae17fc44 --- /dev/null +++ b/tasks/artin-cat0/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ArtinCAT0", + "comparator": { + "theorem_names": [ + "OAI.ArtinCAT0.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11173 +} \ No newline at end of file diff --git a/tasks/artin-cat0/tests/test.sh b/tasks/artin-cat0/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/artin-cat0/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/artin-parabolic-intersections/environment/Dockerfile b/tasks/artin-parabolic-intersections/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/artin-parabolic-intersections/environment/fetch_mathlib.sh b/tasks/artin-parabolic-intersections/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/artin-parabolic-intersections/environment/lake-manifest.json b/tasks/artin-parabolic-intersections/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/artin-parabolic-intersections/environment/lakefile.lean b/tasks/artin-parabolic-intersections/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/artin-parabolic-intersections/environment/lean_setup.sh b/tasks/artin-parabolic-intersections/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/artin-parabolic-intersections/environment/pack_submission.py b/tasks/artin-parabolic-intersections/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/artin-parabolic-intersections/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/artin-parabolic-intersections/instruction.md b/tasks/artin-parabolic-intersections/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1ef9b80d1ce3daca623f744477a7c3fc84bb7502 --- /dev/null +++ b/tasks/artin-parabolic-intersections/instruction.md @@ -0,0 +1,180 @@ +# openai/math challenge `ArtinParabolicIntersections` (family 254) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 254 of the release, *Classifying spaces and geometric obstructions for Artin groups* +(Group theory). The family as a whole: The Salvetti complex of every finite-rank Artin group is aspherical, proving the Artin $K(\pi,1)$ conjecture. Arbitrary intersections of its parabolic subgroups are parabolic, proving the Parabolic Intersection Conjecture. An explicit Artin group admits no proper cocompact isometric action on any nonempty proper CAT$(0)$ space. + +The challenge is `ArtinParabolicIntersections`, also at `/opt/openai-math/challenges/ArtinParabolicIntersections.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Parabolic intersections, parabolic closure, and non-clique Artin-group dynamics. -/ + +namespace HarmonicArtin + +universe u + +variable {S : Type u} + +def alternating (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def braidRelators (M : CoxeterMatrix S) : Set (FreeGroup S) := + Set.range fun st : S × S => + alternating st.1 st.2 (M st.1 st.2) * + (alternating st.2 st.1 (M st.1 st.2))⁻¹ + +abbrev Artin (M : CoxeterMatrix S) := PresentedGroup (braidRelators M) + +def generator (M : CoxeterMatrix S) (s : S) : Artin M := PresentedGroup.of s + +def artinParabolic (M : CoxeterMatrix S) (T : Set S) : Subgroup (Artin M) := + Subgroup.closure (generator M '' T) + +end HarmonicArtin + +namespace HarmonicArtin.ParabolicIntersections + +variable {G : Type*} [Group G] + +/-- `g P g⁻¹`, with membership expressed without existential witnesses. -/ +def conjugate (g : G) (P : Subgroup G) : Subgroup G := + P.comap (MulAut.conj g⁻¹).toMonoidHom + +variable {S : Type*} (M : CoxeterMatrix S) + +/-- Conjugates of standard subgroups, with no spherical-type restriction. -/ +def IsParabolic (P : Subgroup (Artin M)) : Prop := + ∃ (X : Set S) (g : Artin M), P = conjugate g (artinParabolic M X) + +end HarmonicArtin.ParabolicIntersections + +namespace HarmonicArtin.ParabolicIntersections + +noncomputable def gromovProduct {X : Type} [MetricSpace X] (o x y : X) : ℝ := + (dist o x + dist o y - dist x y)/2 + +def IsGromovHyperbolic (X : Type) [MetricSpace X] : Prop := + ∃ δ : ℝ, 0 ≤ δ ∧ ∀ o x y z : X, + min (gromovProduct o x y) (gromovProduct o y z) ≤ gromovProduct o x z + δ + +def IsGeodesicMetric (X : Type) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ : Set.Icc (0 : ℝ) (dist x y) → X, + Isometry γ ∧ γ ⟨0,le_rfl,dist_nonneg⟩=x ∧ γ ⟨dist x y,dist_nonneg,le_rfl⟩=y + +def IsGromovSequence {X : Type} [MetricSpace X] (o : X) (u : ℕ → X) : Prop := + ∀ R : ℝ, ∃ N : ℕ, ∀ m, N ≤ m → ∀ n, N ≤ n → R ≤ gromovProduct o (u m) (u n) + +def IsAcylindrical (G X : Type) [Group G] [MetricSpace X] [MulAction G X] : Prop := + ∀ ε : ℝ, 0 < ε → ∃ R : ℝ, ∃ N : ℕ, ∀ x y : X, R ≤ dist x y → + {g : G | dist x (g • x) ≤ ε ∧ dist y (g • y) ≤ ε}.Finite ∧ + {g : G | dist x (g • x) ≤ ε ∧ dist y (g • y) ≤ ε}.ncard ≤ N + +def HasThreeOrbitLimitPoints (G X : Type) [Group G] [MetricSpace X] [MulAction G X] : Prop := + ∃ o : X, ∃ u : Fin 3 → ℕ → G, + (∀ i, IsGromovSequence o (fun n => u i n • o)) ∧ + ∀ i j, i ≠ j → ∃ B : ℝ, ∀ m n, gromovProduct o (u i m • o) (u j n • o) ≤ B + +/-- An isometric non-elementary acylindrical action on a geodesic +Gromov-hyperbolic metric space. -/ +def AcylindricallyHyperbolic (G : Type) [Group G] : Prop := + ∃ (X : Type) (metric : MetricSpace X) (action : MulAction G X), + @IsGeodesicMetric X metric ∧ @IsGromovHyperbolic X metric ∧ + (∀ g : G, @Isometry X X metric.toPseudoMetricSpace.toPseudoEMetricSpace metric.toPseudoMetricSpace.toPseudoEMetricSpace + (fun x => @SMul.smul G X action.toSMul g x)) ∧ + @IsAcylindrical G X _ metric action ∧ @HasThreeOrbitLimitPoints G X _ metric action + +def WeaklyMalnormal {G : Type} [Group G] (P : Subgroup G) : Prop := + ∃ g : G, (↑(P ⊓ conjugate g P) : Set G).Finite + +variable {S : Type} (M : CoxeterMatrix S) + +/-- No nontrivial partition has every cross label equal to two. -/ +def IsIrreducible : Prop := + ∀ Y : Set S, Y.Nonempty → Yᶜ.Nonempty → ∃ s ∈ Y, ∃ t ∉ Y, M s t ≠ 2 + +end HarmonicArtin.ParabolicIntersections + +namespace HarmonicArtin.ParabolicIntersections + +variable {S : Type} [Fintype S] [LinearOrder S] (M : CoxeterMatrix S) + +/-- The intersection of two conjugates of standard parabolics is parabolic. -/ +theorem unconditional_parabolic_intersections + (X Y : Set S) (g h : Artin M) : + ∃ (Z : Set S) (k : Artin M), + conjugate g (artinParabolic M X) ⊓ conjugate h (artinParabolic M Y) = + conjugate k (artinParabolic M Z) := by + sorry + +/-- An arbitrary parabolic intersection is obtained from at most the rank many members. -/ +theorem unconditional_arbitrary_intersections + (F : Set (Subgroup (Artin M))) (hF : ∀ P ∈ F, IsParabolic M P) : + (∃ F₀ : Finset (Subgroup (Artin M)), + (↑F₀ : Set (Subgroup (Artin M))) ⊆ F ∧ F₀.card ≤ Nat.card S ∧ + sInf F = sInf (↑F₀ : Set (Subgroup (Artin M)))) ∧ IsParabolic M (sInf F) := by + sorry + +/-- Every subset is contained in a unique smallest parabolic subgroup. -/ +theorem unconditional_parabolic_closure (E : Set (Artin M)) : + ∃! P : Subgroup (Artin M), IsParabolic M P ∧ E ⊆ P ∧ + ∀ Q : Subgroup (Artin M), IsParabolic M Q → E ⊆ Q → P ≤ Q := by + sorry + +/-- An irreducible non-clique Artin group has an acylindrical non-elementary +hyperbolic action and all its proper parabolics are weakly malnormal. -/ +theorem unconditional_nonclique_dynamics + (hIrred : IsIrreducible M) (hInf : ∃ s t : S, s ≠ t ∧ M s t = 0) : + AcylindricallyHyperbolic (Artin M) ∧ + ∀ P : Subgroup (Artin M), IsParabolic M P → P ≠ ⊤ → WeaklyMalnormal P := by + sorry + +end HarmonicArtin.ParabolicIntersections + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ArtinParabolicIntersections.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_intersections`, `OAI.HarmonicArtin.ParabolicIntersections.unconditional_arbitrary_intersections`, `OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_closure`, `OAI.HarmonicArtin.ParabolicIntersections.unconditional_nonclique_dynamics` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/artin-parabolic-intersections/solution/closure.txt b/tasks/artin-parabolic-intersections/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f190288e69eef49129ce8c1ab65a42828abd980 --- /dev/null +++ b/tasks/artin-parabolic-intersections/solution/closure.txt @@ -0,0 +1,782 @@ +OAI.Topology.ArtinGroups.Cancellation.BlockPivot +OAI.Topology.ArtinGroups.Cancellation.CornerRemainder +OAI.Topology.ArtinGroups.Cancellation.ReducedDifferential +OAI.Topology.ArtinGroups.Cancellation.ReducedDifferential2 +OAI.Topology.ArtinGroups.Cancellation.Retained +OAI.Topology.ArtinGroups.Cancellation.ScalarPivot +OAI.Topology.ArtinGroups.Cancellation.SphericalPositiveCancelLeft +OAI.Topology.ArtinGroups.Cancellation.SphericalPositiveCancelMonoid +OAI.Topology.ArtinGroups.Complexes.ActedIndex +OAI.Topology.ArtinGroups.Complexes.ArrowShift +OAI.Topology.ArtinGroups.Complexes.BasedComplexComplex +OAI.Topology.ArtinGroups.Complexes.BlockClosed +OAI.Topology.ArtinGroups.Complexes.BottomScalarCycleInjective +OAI.Topology.ArtinGroups.Complexes.BottomScalarCycleZero +OAI.Topology.ArtinGroups.Complexes.BottomSocleZero +OAI.Topology.ArtinGroups.Complexes.BottomSocleZeroTest +OAI.Topology.ArtinGroups.Complexes.CanonicalLowReflectedHigh +OAI.Topology.ArtinGroups.Complexes.CanonicalWordLow +OAI.Topology.ArtinGroups.Complexes.Capped +OAI.Topology.ArtinGroups.Complexes.CochainSignSubOne +OAI.Topology.ArtinGroups.Complexes.CoconePlacement +OAI.Topology.ArtinGroups.Complexes.CoefficientSocle +OAI.Topology.ArtinGroups.Complexes.CoefficientSocleRestrictLayer +OAI.Topology.ArtinGroups.Complexes.CoefficientTopDual +OAI.Topology.ArtinGroups.Complexes.CoefficientTopDualRestrict +OAI.Topology.ArtinGroups.Complexes.ColorBoundary +OAI.Topology.ArtinGroups.Complexes.ColorReduction +OAI.Topology.ArtinGroups.Complexes.ColorRestrictionTopZero +OAI.Topology.ArtinGroups.Complexes.ColorSupport +OAI.Topology.ArtinGroups.Complexes.CommuteTwistSwap +OAI.Topology.ArtinGroups.Complexes.ComplexPacketLowerBound +OAI.Topology.ArtinGroups.Complexes.ComplexPacketPreserves +OAI.Topology.ArtinGroups.Complexes.Cone +OAI.Topology.ArtinGroups.Complexes.Cone2 +OAI.Topology.ArtinGroups.Complexes.ConeMap +OAI.Topology.ArtinGroups.Complexes.ConePlacement +OAI.Topology.ArtinGroups.Complexes.CornerPath +OAI.Topology.ArtinGroups.Complexes.CorrectionBoundary +OAI.Topology.ArtinGroups.Complexes.DiagonalVertex +OAI.Topology.ArtinGroups.Complexes.DifferentialMulExtendLayer +OAI.Topology.ArtinGroups.Complexes.DownClosed +OAI.Topology.ArtinGroups.Complexes.EmptyTestIndex +OAI.Topology.ArtinGroups.Complexes.EqualColorPair +OAI.Topology.ArtinGroups.Complexes.ExtendLayer +OAI.Topology.ArtinGroups.Complexes.FamilySubobjectMiddleLower +OAI.Topology.ArtinGroups.Complexes.FiniteFamilyLevelSupport +OAI.Topology.ArtinGroups.Complexes.FiniteHomotopySetoid +OAI.Topology.ArtinGroups.Complexes.FiniteSum +OAI.Topology.ArtinGroups.Complexes.FiniteSum2 +OAI.Topology.ArtinGroups.Complexes.FrameModelLayerMiddle +OAI.Topology.ArtinGroups.Complexes.GeneratorArray +OAI.Topology.ArtinGroups.Complexes.GeneratorArray2 +OAI.Topology.ArtinGroups.Complexes.GeneratorArrayZeroCap +OAI.Topology.ArtinGroups.Complexes.GeneratorArrayZeroLevel +OAI.Topology.ArtinGroups.Complexes.GeneratorTokenTest +OAI.Topology.ArtinGroups.Complexes.GeneratorVector +OAI.Topology.ArtinGroups.Complexes.GeneratorVectorPos +OAI.Topology.ArtinGroups.Complexes.GeneratorVectorPureLayer +OAI.Topology.ArtinGroups.Complexes.HighConeIndex +OAI.Topology.ArtinGroups.Complexes.HighConeRetainedPure +OAI.Topology.ArtinGroups.Complexes.HighDualCycleZero +OAI.Topology.ArtinGroups.Complexes.HighestLocalGeneratorTest +OAI.Topology.ArtinGroups.Complexes.HomDetector +OAI.Topology.ArtinGroups.Complexes.HomDimension +OAI.Topology.ArtinGroups.Complexes.HomDimension2 +OAI.Topology.ArtinGroups.Complexes.HomDimensionDual +OAI.Topology.ArtinGroups.Complexes.HomDimensionRetract +OAI.Topology.ArtinGroups.Complexes.HomDimensionZeroCycles +OAI.Topology.ArtinGroups.Complexes.HomDimensionZeroHom +OAI.Topology.ArtinGroups.Complexes.HomInternalSupport +OAI.Topology.ArtinGroups.Complexes.HomMono +OAI.Topology.ArtinGroups.Complexes.HomOperator +OAI.Topology.ArtinGroups.Complexes.HomPath +OAI.Topology.ArtinGroups.Complexes.HomSpace +OAI.Topology.ArtinGroups.Complexes.HomSpaceDuality +OAI.Topology.ArtinGroups.Complexes.HomSpaceMul +OAI.Topology.ArtinGroups.Complexes.HomSpacePairing +OAI.Topology.ArtinGroups.Complexes.HomStep +OAI.Topology.ArtinGroups.Complexes.HomotopyConeMap +OAI.Topology.ArtinGroups.Complexes.Identity +OAI.Topology.ArtinGroups.Complexes.Initial +OAI.Topology.ArtinGroups.Complexes.InitialHomSpaceNegative +OAI.Topology.ArtinGroups.Complexes.InitialProbeTestUpper +OAI.Topology.ArtinGroups.Complexes.InitialProjective +OAI.Topology.ArtinGroups.Complexes.InverseHomMatrix +OAI.Topology.ArtinGroups.Complexes.InverseMatrix +OAI.Topology.ArtinGroups.Complexes.InverseTwistDifferential +OAI.Topology.ArtinGroups.Complexes.InverseTwistIdentity +OAI.Topology.ArtinGroups.Complexes.InverseTwistIndex +OAI.Topology.ArtinGroups.Complexes.InverseTwistPlacement +OAI.Topology.ArtinGroups.Complexes.InverseWordAction +OAI.Topology.ArtinGroups.Complexes.InverseWordActionAppend +OAI.Topology.ArtinGroups.Complexes.IsolatedIndexCycle +OAI.Topology.ArtinGroups.Complexes.LayerConeEquivalence +OAI.Topology.ArtinGroups.Complexes.LayerSocleDimensionLayer +OAI.Topology.ArtinGroups.Complexes.LayerSocleDimensionSum +OAI.Topology.ArtinGroups.Complexes.LayerTotalHomDimension +OAI.Topology.ArtinGroups.Complexes.LayerVector +OAI.Topology.ArtinGroups.Complexes.LeftMatrix +OAI.Topology.ArtinGroups.Complexes.LevelArrayBelow +OAI.Topology.ArtinGroups.Complexes.LevelArrayComplexMinimal +OAI.Topology.ArtinGroups.Complexes.LevelArrayMinimalApply +OAI.Topology.ArtinGroups.Complexes.LowMatrix +OAI.Topology.ArtinGroups.Complexes.LowerTruncation +OAI.Topology.ArtinGroups.Complexes.LowerTruncationLayerFloor +OAI.Topology.ArtinGroups.Complexes.LowerTruncationSum +OAI.Topology.ArtinGroups.Complexes.MatrixOneMulExtend +OAI.Topology.ArtinGroups.Complexes.MinimalEmbedding +OAI.Topology.ArtinGroups.Complexes.MinimalGeneratorDualCycle +OAI.Topology.ArtinGroups.Complexes.MinimalModel +OAI.Topology.ArtinGroups.Complexes.MinimalModelEquivalence +OAI.Topology.ArtinGroups.Complexes.NegativeAmplitudeCoreIndex +OAI.Topology.ArtinGroups.Complexes.NegativeConeIndex +OAI.Topology.ArtinGroups.Complexes.NegativeHomTransformReflect +OAI.Topology.ArtinGroups.Complexes.NegativeTwistCapDisjoint +OAI.Topology.ArtinGroups.Complexes.NegativeTwistLoweredGenerator +OAI.Topology.ArtinGroups.Complexes.NegativeTwistModern +OAI.Topology.ArtinGroups.Complexes.NormalizedInverseTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.NormalizedReverseTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.OptionSumEquiv +OAI.Topology.ArtinGroups.Complexes.OutsideCap +OAI.Topology.ArtinGroups.Complexes.PacketConsEquiv +OAI.Topology.ArtinGroups.Complexes.PacketLayerLowerTruncation +OAI.Topology.ArtinGroups.Complexes.PacketPermAction +OAI.Topology.ArtinGroups.Complexes.PacketPermEnumeration +OAI.Topology.ArtinGroups.Complexes.PacketPermExterior +OAI.Topology.ArtinGroups.Complexes.PacketPermPreservesOpen +OAI.Topology.ArtinGroups.Complexes.PacketPermReindex +OAI.Topology.ArtinGroups.Complexes.PacketTwistRaisedGenerator +OAI.Topology.ArtinGroups.Complexes.PacketTwistRaisedGenerator2 +OAI.Topology.ArtinGroups.Complexes.PacketTwistTopZero +OAI.Topology.ArtinGroups.Complexes.PlacedProjective +OAI.Topology.ArtinGroups.Complexes.PlacementSignedWeight +OAI.Topology.ArtinGroups.Complexes.PositiveConeIndex +OAI.Topology.ArtinGroups.Complexes.PositiveHomTransform +OAI.Topology.ArtinGroups.Complexes.PositiveTopDivisor +OAI.Topology.ArtinGroups.Complexes.PositiveTwistFiberEquiv +OAI.Topology.ArtinGroups.Complexes.PositiveTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.PositiveTwistLowerBound +OAI.Topology.ArtinGroups.Complexes.PositiveTwistModern +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest2 +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest3 +OAI.Topology.ArtinGroups.Complexes.PositiveTwistRaisedGenerator +OAI.Topology.ArtinGroups.Complexes.PositiveWord +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionAppend +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionOrthogonal +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionTest +OAI.Topology.ArtinGroups.Complexes.PositiveWordLowerBound +OAI.Topology.ArtinGroups.Complexes.ProbeFixedNoDiagonal +OAI.Topology.ArtinGroups.Complexes.ProbeHomDimensionGenerator +OAI.Topology.ArtinGroups.Complexes.PureCoefficientCohomology +OAI.Topology.ArtinGroups.Complexes.PureHomSpaceHomogeneous +OAI.Topology.ArtinGroups.Complexes.PureLayerSelf +OAI.Topology.ArtinGroups.Complexes.PureSupportedCycles +OAI.Topology.ArtinGroups.Complexes.PureTotalHomEuler +OAI.Topology.ArtinGroups.Complexes.PureUpperBoundariesZero +OAI.Topology.ArtinGroups.Complexes.ReducedAmplitudeTwistLevel +OAI.Topology.ArtinGroups.Complexes.ReducedNegativeAmplitudeTwist +OAI.Topology.ArtinGroups.Complexes.ReducedNoTopDivisor +OAI.Topology.ArtinGroups.Complexes.Refl +OAI.Topology.ArtinGroups.Complexes.Reindex +OAI.Topology.ArtinGroups.Complexes.ReindexConeIsomorphism +OAI.Topology.ArtinGroups.Complexes.ReindexHomOperator +OAI.Topology.ArtinGroups.Complexes.RestrictExtendLayerMul +OAI.Topology.ArtinGroups.Complexes.RestrictLayer +OAI.Topology.ArtinGroups.Complexes.ReverseTwistDifferential +OAI.Topology.ArtinGroups.Complexes.ReverseTwistIndexEquiv +OAI.Topology.ArtinGroups.Complexes.ReverseTwistProjection +OAI.Topology.ArtinGroups.Complexes.ReverseTwistProjectionCommute +OAI.Topology.ArtinGroups.Complexes.ScalarExactNotZero +OAI.Topology.ArtinGroups.Complexes.ScalarKernel +OAI.Topology.ArtinGroups.Complexes.ScalarSupported +OAI.Topology.ArtinGroups.Complexes.ScalarSupportedCochainShift +OAI.Topology.ArtinGroups.Complexes.ScalarSupportedTokenShift +OAI.Topology.ArtinGroups.Complexes.SecondaryLayer +OAI.Topology.ArtinGroups.Complexes.Shift +OAI.Topology.ArtinGroups.Complexes.SubobjectMiddleLowerBound +OAI.Topology.ArtinGroups.Complexes.Sum +OAI.Topology.ArtinGroups.Complexes.SumTestEquiv +OAI.Topology.ArtinGroups.Complexes.SumTruncationEquiv +OAI.Topology.ArtinGroups.Complexes.SummandSecondary +OAI.Topology.ArtinGroups.Complexes.SupportedCoefficientCycles +OAI.Topology.ArtinGroups.Complexes.TargetLow +OAI.Topology.ArtinGroups.Complexes.TermwiseSplitInjection +OAI.Topology.ArtinGroups.Complexes.Test +OAI.Topology.ArtinGroups.Complexes.TestComplexVertexDifferential +OAI.Topology.ArtinGroups.Complexes.TestExact +OAI.Topology.ArtinGroups.Complexes.TestUpperBound +OAI.Topology.ArtinGroups.Complexes.TokenShift +OAI.Topology.ArtinGroups.Complexes.TotalHomDimensionReading +OAI.Topology.ArtinGroups.Complexes.TotalVector +OAI.Topology.ArtinGroups.Complexes.TotalVectorLayer +OAI.Topology.ArtinGroups.Complexes.TwistNewTestIndex +OAI.Topology.ArtinGroups.Complexes.UnfoldedCartanSymm +OAI.Topology.ArtinGroups.Complexes.UnfoldedPresentation +OAI.Topology.ArtinGroups.Complexes.UpperBound +OAI.Topology.ArtinGroups.Complexes.WordInverseModel +OAI.Topology.ArtinGroups.Coxeter.AltList +OAI.Topology.ArtinGroups.Coxeter.AltListMap +OAI.Topology.ArtinGroups.Coxeter.AltListPairDescent +OAI.Topology.ArtinGroups.Coxeter.AltListReduced +OAI.Topology.ArtinGroups.Coxeter.AltNext +OAI.Topology.ArtinGroups.Coxeter.AlternatingLiftProd +OAI.Topology.ArtinGroups.Coxeter.AlternatingNextRoot +OAI.Topology.ArtinGroups.Coxeter.ArtinCoxeter +OAI.Topology.ArtinGroups.Coxeter.BraidCoreFirstTarget +OAI.Topology.ArtinGroups.Coxeter.BraidCoreIndex +OAI.Topology.ArtinGroups.Coxeter.BraidCorePlacement +OAI.Topology.ArtinGroups.Coxeter.BraidFirstPivot +OAI.Topology.ArtinGroups.Coxeter.BraidSecondPivot +OAI.Topology.ArtinGroups.Coxeter.CanonicalReducedWordLow +OAI.Topology.ArtinGroups.Coxeter.CommonWeakPrefixMaximal +OAI.Topology.ArtinGroups.Coxeter.InverseParabolicMinimum +OAI.Topology.ArtinGroups.Coxeter.OrdinaryCoxeterMatrix +OAI.Topology.ArtinGroups.Coxeter.OrdinaryTwistBraid +OAI.Topology.ArtinGroups.Coxeter.Parabolic +OAI.Topology.ArtinGroups.Coxeter.ParabolicLongest +OAI.Topology.ArtinGroups.Coxeter.ParabolicProductMap +OAI.Topology.ArtinGroups.Coxeter.PositiveBraidRel +OAI.Topology.ArtinGroups.Coxeter.PositiveBraidRelations +OAI.Topology.ArtinGroups.Coxeter.ReducedWordProperty +OAI.Topology.ArtinGroups.Coxeter.RestrictedMatrix +OAI.Topology.ArtinGroups.Coxeter.RightParabolicDecomposition +OAI.Topology.ArtinGroups.Coxeter.Signs +OAI.Topology.ArtinGroups.Coxeter.WeakPrefix +OAI.Topology.ArtinGroups.Coxeter.WordProdEquiv +OAI.Topology.ArtinGroups.DeligneDefinitions +OAI.Topology.ArtinGroups.Diagrams.CongrEquiv +OAI.Topology.ArtinGroups.Diagrams.Index +OAI.Topology.ArtinGroups.Diagrams.ReverseDifferential +OAI.Topology.ArtinGroups.Diagrams.SupportedKernel +OAI.Topology.ArtinGroups.Diagrams.TransposeConjugateEquiv +OAI.Topology.ArtinGroups.Functors.BasePath +OAI.Topology.ArtinGroups.Functors.ColorPacketPerm +OAI.Topology.ArtinGroups.Functors.ComplexInitial +OAI.Topology.ArtinGroups.Functors.ComplexLowerTruncation +OAI.Topology.ArtinGroups.Functors.ComplexPureLayer +OAI.Topology.ArtinGroups.Functors.ConeIndexEquiv +OAI.Topology.ArtinGroups.Functors.CoordinateExpansion +OAI.Topology.ArtinGroups.Functors.Evaluation +OAI.Topology.ArtinGroups.Functors.GeneratorVectorComplex +OAI.Topology.ArtinGroups.Functors.HomDimensionFlexible +OAI.Topology.ArtinGroups.Functors.HomDualSupportedCycles +OAI.Topology.ArtinGroups.Functors.HomSupportedCyclesEquiv +OAI.Topology.ArtinGroups.Functors.HomSwitchMap +OAI.Topology.ArtinGroups.Functors.Index +OAI.Topology.ArtinGroups.Functors.LayerIndexEquiv +OAI.Topology.ArtinGroups.Functors.LeftHomIndex +OAI.Topology.ArtinGroups.Functors.LeftHomPlacement +OAI.Topology.ArtinGroups.Functors.LeftPacketIndex +OAI.Topology.ArtinGroups.Functors.LeftSocleIndexEquiv +OAI.Topology.ArtinGroups.Functors.LevelGeneratorEquiv +OAI.Topology.ArtinGroups.Functors.PacketSwitchMatrix +OAI.Topology.ArtinGroups.Functors.PacketTwistComparison +OAI.Topology.ArtinGroups.Functors.Path +OAI.Topology.ArtinGroups.Functors.Path2 +OAI.Topology.ArtinGroups.Functors.PathImage +OAI.Topology.ArtinGroups.Functors.PathMarked +OAI.Topology.ArtinGroups.Functors.PathSwitchEquiv +OAI.Topology.ArtinGroups.Functors.Placement +OAI.Topology.ArtinGroups.Functors.ProbeEmbeddingMap +OAI.Topology.ArtinGroups.Functors.ReversibleQuiverMap +OAI.Topology.ArtinGroups.Functors.SectorInverse +OAI.Topology.ArtinGroups.Functors.SeedEquiv +OAI.Topology.ArtinGroups.Functors.SignedPacketPerm +OAI.Topology.ArtinGroups.Functors.SignedPerm +OAI.Topology.ArtinGroups.Functors.SupportedCycles +OAI.Topology.ArtinGroups.Functors.TermwiseSplitInjection +OAI.Topology.ArtinGroups.Functors.TestIndex +OAI.Topology.ArtinGroups.Functors.TestIndex2 +OAI.Topology.ArtinGroups.Functors.TopZeroProbeSocle +OAI.Topology.ArtinGroups.Functors.TruncationIndexEquiv +OAI.Topology.ArtinGroups.Functors.TwistProdGeneratorExterior +OAI.Topology.ArtinGroups.Functors.WordOrbitCountAdjacency +OAI.Topology.ArtinGroups.Functors.WordOrbitSocleAdjacency +OAI.Topology.ArtinGroups.Functors.WordPacketPermAppend +OAI.Topology.ArtinGroups.Functors.ZigzagLinear +OAI.Topology.ArtinGroups.Geometry.Cartan +OAI.Topology.ArtinGroups.Geometry.CartanForm +OAI.Topology.ArtinGroups.Geometry.CartanOffNonpos +OAI.Topology.ArtinGroups.Geometry.CartanRestricted +OAI.Topology.ArtinGroups.Geometry.ChamberInequalitiesConvexHull +OAI.Topology.ArtinGroups.Geometry.ConvexHullSupportedComp +OAI.Topology.ArtinGroups.Geometry.ConvexInclusion +OAI.Topology.ArtinGroups.Geometry.ConvexWord +OAI.Topology.ArtinGroups.Geometry.CoordinateExtension +OAI.Topology.ArtinGroups.Geometry.DihedralScalar +OAI.Topology.ArtinGroups.Geometry.Form +OAI.Topology.ArtinGroups.Geometry.InteriorConvexHullReindex +OAI.Topology.ArtinGroups.Geometry.InvariantForm +OAI.Topology.ArtinGroups.Geometry.LongestMulSelf +OAI.Topology.ArtinGroups.Geometry.ProbeConvexEuler +OAI.Topology.ArtinGroups.Geometry.Reflect +OAI.Topology.ArtinGroups.Geometry.RestrictionLength +OAI.Topology.ArtinGroups.Geometry.RootCoeffAltExtension +OAI.Topology.ArtinGroups.Geometry.RootNonnegAscent +OAI.Topology.ArtinGroups.Geometry.RootNonposDescent +OAI.Topology.ArtinGroups.Geometry.RootPair +OAI.Topology.ArtinGroups.Geometry.RootRowOrthogonalWord +OAI.Topology.ArtinGroups.Geometry.SphericalCartanPos +OAI.Topology.ArtinGroups.Geometry.SphericalCartanPos2 +OAI.Topology.ArtinGroups.Geometry.StrictChamber +OAI.Topology.ArtinGroups.Geometry.TrigPhasePower +OAI.Topology.ArtinGroups.Geometry.TrigPhaseSqPrimitive +OAI.Topology.ArtinGroups.Harmonic.ArtinAction +OAI.Topology.ArtinGroups.Harmonic.ArtinActionWordArtin +OAI.Topology.ArtinGroups.Harmonic.BinaryProductBoundary +OAI.Topology.ArtinGroups.Harmonic.Block +OAI.Topology.ArtinGroups.Harmonic.BottomWordNil +OAI.Topology.ArtinGroups.Harmonic.Candidate +OAI.Topology.ArtinGroups.Harmonic.CandidateBlockNonpos +OAI.Topology.ArtinGroups.Harmonic.CandidateCapped +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLow +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLowCount +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLowExpansion +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionMultiplicity +OAI.Topology.ArtinGroups.Harmonic.CanonicalLowSupport +OAI.Topology.ArtinGroups.Harmonic.CappedCandidate +OAI.Topology.ArtinGroups.Harmonic.CappedReflectedHigh +OAI.Topology.ArtinGroups.Harmonic.CartanCommutingZero +OAI.Topology.ArtinGroups.Harmonic.ConeAttachmentRel +OAI.Topology.ArtinGroups.Harmonic.Contradiction +OAI.Topology.ArtinGroups.Harmonic.Coset +OAI.Topology.ArtinGroups.Harmonic.CosetBelow +OAI.Topology.ArtinGroups.Harmonic.CosetExteriorCap +OAI.Topology.ArtinGroups.Harmonic.CosetOrbit +OAI.Topology.ArtinGroups.Harmonic.CosetOrbitCap +OAI.Topology.ArtinGroups.Harmonic.CosetProfile +OAI.Topology.ArtinGroups.Harmonic.CosetSum +OAI.Topology.ArtinGroups.Harmonic.CosetVectorNullPatch +OAI.Topology.ArtinGroups.Harmonic.CosetVertex +OAI.Topology.ArtinGroups.Harmonic.Crossing +OAI.Topology.ArtinGroups.Harmonic.DimensionNonneg +OAI.Topology.ArtinGroups.Harmonic.DimensionPosMultiplicityPos +OAI.Topology.ArtinGroups.Harmonic.EarlyDelay +OAI.Topology.ArtinGroups.Harmonic.EigenvectorProportional +OAI.Topology.ArtinGroups.Harmonic.Eligible +OAI.Topology.ArtinGroups.Harmonic.Extend +OAI.Topology.ArtinGroups.Harmonic.FamilySocleFiniteTermination +OAI.Topology.ArtinGroups.Harmonic.FiniteArtinPositiveLeft +OAI.Topology.ArtinGroups.Harmonic.FiniteChainEnum +OAI.Topology.ArtinGroups.Harmonic.FiniteFusionEdge +OAI.Topology.ArtinGroups.Harmonic.FinsuppMapDomainFiber +OAI.Topology.ArtinGroups.Harmonic.FoldedCartan +OAI.Topology.ArtinGroups.Harmonic.FoldedSphericalPos +OAI.Topology.ArtinGroups.Harmonic.FrameFamily +OAI.Topology.ArtinGroups.Harmonic.FrameFamilyCapTop +OAI.Topology.ArtinGroups.Harmonic.FrameFamilyTopProportional +OAI.Topology.ArtinGroups.Harmonic.FusionColorRegion +OAI.Topology.ArtinGroups.Harmonic.FusionColorWord +OAI.Topology.ArtinGroups.Harmonic.FusionExpandedWordAction +OAI.Topology.ArtinGroups.Harmonic.FusionExpandedWordPerm +OAI.Topology.ArtinGroups.Harmonic.FusionExpressionAction +OAI.Topology.ArtinGroups.Harmonic.FusionExpressionOrbit +OAI.Topology.ArtinGroups.Harmonic.FusionFactorStep +OAI.Topology.ArtinGroups.Harmonic.FusionFold +OAI.Topology.ArtinGroups.Harmonic.FusionLabel +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorSecondary +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorSubobject +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorTop +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitModel +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitMultiplicity +OAI.Topology.ArtinGroups.Harmonic.FusionPacketAction +OAI.Topology.ArtinGroups.Harmonic.FusionPacketLayerExterior +OAI.Topology.ArtinGroups.Harmonic.FusionPacketOrbit +OAI.Topology.ArtinGroups.Harmonic.FusionPacketPerm +OAI.Topology.ArtinGroups.Harmonic.FusionProfilePositiveEvery +OAI.Topology.ArtinGroups.Harmonic.FusionQuiverCartan +OAI.Topology.ArtinGroups.Harmonic.FusionQuiverSimpleEdge +OAI.Topology.ArtinGroups.Harmonic.FusionRest +OAI.Topology.ArtinGroups.Harmonic.FusionSignedPacketExterior +OAI.Topology.ArtinGroups.Harmonic.FusionSubobjectCartanInequality +OAI.Topology.ArtinGroups.Harmonic.FusionVertex +OAI.Topology.ArtinGroups.Harmonic.FusionZeroLabel +OAI.Topology.ArtinGroups.Harmonic.GeneratorPlacement +OAI.Topology.ArtinGroups.Harmonic.GroupProbeEuler +OAI.Topology.ArtinGroups.Harmonic.Harmonic +OAI.Topology.ArtinGroups.Harmonic.HarmonicExtension +OAI.Topology.ArtinGroups.Harmonic.HarmonicUpperAntitone +OAI.Topology.ArtinGroups.Harmonic.Incidence +OAI.Topology.ArtinGroups.Harmonic.Initial +OAI.Topology.ArtinGroups.Harmonic.InitialProbe +OAI.Topology.ArtinGroups.Harmonic.InjectiveFinrankOne +OAI.Topology.ArtinGroups.Harmonic.InsertOldIso +OAI.Topology.ArtinGroups.Harmonic.IntegerUpward +OAI.Topology.ArtinGroups.Harmonic.IsolatedBoundaryAbsent +OAI.Topology.ArtinGroups.Harmonic.IsolatedHarmonicLayer +OAI.Topology.ArtinGroups.Harmonic.IsolatedIterationData +OAI.Topology.ArtinGroups.Harmonic.LateDelay +OAI.Topology.ArtinGroups.Harmonic.LayerExpression +OAI.Topology.ArtinGroups.Harmonic.LeftSector +OAI.Topology.ArtinGroups.Harmonic.Level +OAI.Topology.ArtinGroups.Harmonic.LiftedDeck +OAI.Topology.ArtinGroups.Harmonic.MapPacket +OAI.Topology.ArtinGroups.Harmonic.MaximalReducedMonoidPrefix +OAI.Topology.ArtinGroups.Harmonic.MaximalReducedPositivePrefix +OAI.Topology.ArtinGroups.Harmonic.MultiplicitySum +OAI.Topology.ArtinGroups.Harmonic.MultiplicityZero +OAI.Topology.ArtinGroups.Harmonic.NegativePrepend +OAI.Topology.ArtinGroups.Harmonic.NeighborhoodProject +OAI.Topology.ArtinGroups.Harmonic.NullPatch +OAI.Topology.ArtinGroups.Harmonic.NullPatch2 +OAI.Topology.ArtinGroups.Harmonic.PacketWord +OAI.Topology.ArtinGroups.Harmonic.PeakSupport +OAI.Topology.ArtinGroups.Harmonic.PlacementLevelFiberSum +OAI.Topology.ArtinGroups.Harmonic.PositiveComponent +OAI.Topology.ArtinGroups.Harmonic.PositiveComponentPositive +OAI.Topology.ArtinGroups.Harmonic.PositiveDegreeHom +OAI.Topology.ArtinGroups.Harmonic.PositiveDegreeSublevelFinite +OAI.Topology.ArtinGroups.Harmonic.PositiveDescentSet +OAI.Topology.ArtinGroups.Harmonic.PositiveHead +OAI.Topology.ArtinGroups.Harmonic.PositiveLiftSimple +OAI.Topology.ArtinGroups.Harmonic.PositivePrefix +OAI.Topology.ArtinGroups.Harmonic.PositivePrefixMulLeft +OAI.Topology.ArtinGroups.Harmonic.PositiveReverseHom +OAI.Topology.ArtinGroups.Harmonic.PositiveSimpleLiftMul +OAI.Topology.ArtinGroups.Harmonic.PositiveSupportComponent +OAI.Topology.ArtinGroups.Harmonic.PositiveWord +OAI.Topology.ArtinGroups.Harmonic.PredAboveSuccSucc +OAI.Topology.ArtinGroups.Harmonic.PrismFlag +OAI.Topology.ArtinGroups.Harmonic.PrismGrid +OAI.Topology.ArtinGroups.Harmonic.PrismPrefix +OAI.Topology.ArtinGroups.Harmonic.PrismSimplexZero +OAI.Topology.ArtinGroups.Harmonic.ProbeActionEmbeddedHom +OAI.Topology.ArtinGroups.Harmonic.ProbeActionLevelExterior +OAI.Topology.ArtinGroups.Harmonic.ProbeCoreInclusion +OAI.Topology.ArtinGroups.Harmonic.ProbeCoreTermNonpos +OAI.Topology.ArtinGroups.Harmonic.ProbeFixedDiagonal +OAI.Topology.ArtinGroups.Harmonic.ProbeFixedOutside +OAI.Topology.ArtinGroups.Harmonic.ProbeOrbitAbsent +OAI.Topology.ArtinGroups.Harmonic.ProbePacket +OAI.Topology.ArtinGroups.Harmonic.ProbePacketExterior +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWord +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordAppend +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordInitial +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordLeft +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordMonoid +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordPositive +OAI.Topology.ArtinGroups.Harmonic.ProbeRaiseLower +OAI.Topology.ArtinGroups.Harmonic.ProductBoxSlice +OAI.Topology.ArtinGroups.Harmonic.QuantumNumber +OAI.Topology.ArtinGroups.Harmonic.ReducedExpression +OAI.Topology.ArtinGroups.Harmonic.ResidueActive +OAI.Topology.ArtinGroups.Harmonic.ResidueActiveEmpty +OAI.Topology.ArtinGroups.Harmonic.ResidueAllowed +OAI.Topology.ArtinGroups.Harmonic.ResidueEarlierLower +OAI.Topology.ArtinGroups.Harmonic.ResidueEarlierLowerIso +OAI.Topology.ArtinGroups.Harmonic.ResidueHeightZeroVector +OAI.Topology.ArtinGroups.Harmonic.ResidueRank +OAI.Topology.ArtinGroups.Harmonic.ResidueSingleOpen +OAI.Topology.ArtinGroups.Harmonic.ResidueZeroLowerIso +OAI.Topology.ArtinGroups.Harmonic.RestrictedArtinHom +OAI.Topology.ArtinGroups.Harmonic.RestrictionHomRange +OAI.Topology.ArtinGroups.Harmonic.RootExtension +OAI.Topology.ArtinGroups.Harmonic.RootInclusionRange +OAI.Topology.ArtinGroups.Harmonic.RowReflect +OAI.Topology.ArtinGroups.Harmonic.RowReflectWordReverse +OAI.Topology.ArtinGroups.Harmonic.SecondaryAsSum +OAI.Topology.ArtinGroups.Harmonic.SignedLetter +OAI.Topology.ArtinGroups.Harmonic.SimpleFrontLink +OAI.Topology.ArtinGroups.Harmonic.SimplexSupport +OAI.Topology.ArtinGroups.Harmonic.SphericalFoldedMatrix +OAI.Topology.ArtinGroups.Harmonic.SphericalLongest +OAI.Topology.ArtinGroups.Harmonic.SphericalPacketWordProperty +OAI.Topology.ArtinGroups.Harmonic.SphericalPair +OAI.Topology.ArtinGroups.Harmonic.Stage +OAI.Topology.ArtinGroups.Harmonic.StringAdjacent +OAI.Topology.ArtinGroups.Harmonic.SumNeighborsSubtype +OAI.Topology.ArtinGroups.Harmonic.TieCode +OAI.Topology.ArtinGroups.Harmonic.TypeComponent +OAI.Topology.ArtinGroups.Harmonic.UnfoldedColorOrthogonal +OAI.Topology.ArtinGroups.Harmonic.UnfoldedFullWordMem +OAI.Topology.ArtinGroups.Harmonic.UnfoldedHom +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusion +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusionRange +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusionRangeMono +OAI.Topology.ArtinGroups.Harmonic.UnfoldedMatrix +OAI.Topology.ArtinGroups.Harmonic.UnionCarrier +OAI.Topology.ArtinGroups.Harmonic.WordArtinSubtypeMem +OAI.Topology.ArtinGroups.Harmonic.WordFrontData +OAI.Topology.ArtinGroups.Model +OAI.Topology.ArtinGroups.ParabolicIntersections.ActiveColors +OAI.Topology.ArtinGroups.ParabolicIntersections.AcyclicTwist +OAI.Topology.ArtinGroups.ParabolicIntersections.AcyclicTwistInput +OAI.Topology.ArtinGroups.ParabolicIntersections.AmalgamAcyclic +OAI.Topology.ArtinGroups.ParabolicIntersections.AmalgamGraph +OAI.Topology.ArtinGroups.ParabolicIntersections.AmalgamNoncommuting +OAI.Topology.ArtinGroups.ParabolicIntersections.AmalgamReduced +OAI.Topology.ArtinGroups.ParabolicIntersections.ArtinRelabel +OAI.Topology.ArtinGroups.ParabolicIntersections.AvoidingBoundaryRays +OAI.Topology.ArtinGroups.ParabolicIntersections.AvoidingRealization +OAI.Topology.ArtinGroups.ParabolicIntersections.Basic +OAI.Topology.ArtinGroups.ParabolicIntersections.BoundaryWitness +OAI.Topology.ArtinGroups.ParabolicIntersections.BraidRestriction +OAI.Topology.ArtinGroups.ParabolicIntersections.CoefficientPaths +OAI.Topology.ArtinGroups.ParabolicIntersections.ConditionalMain +OAI.Topology.ArtinGroups.ParabolicIntersections.ConnectedMinima +OAI.Topology.ArtinGroups.ParabolicIntersections.ConnectedSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.Consequences +OAI.Topology.ArtinGroups.ParabolicIntersections.CosetContainment +OAI.Topology.ArtinGroups.ParabolicIntersections.CoxeterChainMinimum +OAI.Topology.ArtinGroups.ParabolicIntersections.CoxeterChainRoots +OAI.Topology.ArtinGroups.ParabolicIntersections.CoxeterProjectionSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.DynamicsDefinitions +OAI.Topology.ArtinGroups.ParabolicIntersections.DynamicsEquivalence +OAI.Topology.ArtinGroups.ParabolicIntersections.DynamicsMain +OAI.Topology.ArtinGroups.ParabolicIntersections.DynamicsUnconditional +OAI.Topology.ArtinGroups.ParabolicIntersections.EmptyPlacement +OAI.Topology.ArtinGroups.ParabolicIntersections.FixedFactor +OAI.Topology.ArtinGroups.ParabolicIntersections.FoldingGcd +OAI.Topology.ArtinGroups.ParabolicIntersections.FoldingGcdInput +OAI.Topology.ArtinGroups.ParabolicIntersections.FoldingHead +OAI.Topology.ArtinGroups.ParabolicIntersections.FoldingPositive +OAI.Topology.ArtinGroups.ParabolicIntersections.FoldingSimpleGcd +OAI.Topology.ArtinGroups.ParabolicIntersections.GeneratorPowers +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphMetric +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationAction +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationAcylindrical +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationDistance +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationGeodesic +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationHyperbolic +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphRealizationSpace +OAI.Topology.ArtinGroups.ParabolicIntersections.GraphWalkLevels +OAI.Topology.ArtinGroups.ParabolicIntersections.IncomingSpanning +OAI.Topology.ArtinGroups.ParabolicIntersections.InitialMinimum +OAI.Topology.ArtinGroups.ParabolicIntersections.LayerErasure +OAI.Topology.ArtinGroups.ParabolicIntersections.Main +OAI.Topology.ArtinGroups.ParabolicIntersections.MainIntersection +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshAdjacent +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshContraction +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshGraphNilpotence +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshGraphWeights +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshInsertionMatrix +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshMain +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshMatrixAction +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshNaturality +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshNilpotence +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshNormalization +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshPathEvaluation +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshPathSpaces +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshPerron +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshProjection +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshProjectionAlgebra +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshProjectionCutoff +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshProjectionInduction +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshQuantum +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshQuiver +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshQuiverAlgebra +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshQuiverWords +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshSpectralUpper +OAI.Topology.ArtinGroups.ParabolicIntersections.MeshTrace +OAI.Topology.ArtinGroups.ParabolicIntersections.MetricUnitCurves +OAI.Topology.ArtinGroups.ParabolicIntersections.NonCliqueDynamics +OAI.Topology.ArtinGroups.ParabolicIntersections.NoncommutingGraph +OAI.Topology.ArtinGroups.ParabolicIntersections.NormalParabolic +OAI.Topology.ArtinGroups.ParabolicIntersections.NormalizerAlgebra +OAI.Topology.ArtinGroups.ParabolicIntersections.NullBoundary +OAI.Topology.ArtinGroups.ParabolicIntersections.OrbitEdgeGraph +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicCore +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicCosetProjection +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicMinimal +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicMinimumStep +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicProductProper +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicRead +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicReadBraid +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicReadReduced +OAI.Topology.ArtinGroups.ParabolicIntersections.ParabolicRetractionAction +OAI.Topology.ArtinGroups.ParabolicIntersections.PathImages +OAI.Topology.ArtinGroups.ParabolicIntersections.PeriodicBoundary +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedBlockBoundary +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedBoundaryZero +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidate +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidateBlock +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidateCapped +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidateComparison +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidateFixed +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCandidateNumerical +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCap +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCapSaturation +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCappedCandidate +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCosetExteriorCap +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCosetGeometry +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedCosetProduct +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedFamily +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedGroupProbeEuler +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedInitialCounts +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedInitialStabilizer +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedMultiplicity +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedMultiplicityZero +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedNullObstruction +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedNullPatch +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedProbeCap +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedProbeRaiseLower +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedProfile +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueActive +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueActiveEmpty +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueAllowed +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueEarlierLower +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueEarlierLowerIso +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueHeightZero +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueRank +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueSingleOpen +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedResidueZeroLower +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedRows +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedSpecialResidue +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedSphericalNoChain +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedStrictResidue +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedTop +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedTypeComponent +OAI.Topology.ArtinGroups.ParabolicIntersections.PointedWeighted +OAI.Topology.ArtinGroups.ParabolicIntersections.PositiveHeadProduct +OAI.Topology.ArtinGroups.ParabolicIntersections.PositiveSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.PositiveTransport +OAI.Topology.ArtinGroups.ParabolicIntersections.ProperParabolicMalnormal +OAI.Topology.ArtinGroups.ParabolicIntersections.ProperPositiveSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.RankReduction +OAI.Topology.ArtinGroups.ParabolicIntersections.ReducedDynamicsMain +OAI.Topology.ArtinGroups.ParabolicIntersections.ReducedInputsMain +OAI.Topology.ArtinGroups.ParabolicIntersections.ReducedPositiveExtension +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeActive +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeAllEligible +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeDescending +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeDiagram +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeEligible +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeEligibleBlocks +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeEligibleFactor +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeEligibleWithin +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeEmbedding +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeFamily +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeHeight +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeInitialStabilizer +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeInvisibleFactor +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeLowerBasics +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeLowerComparison +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeLowerConnected +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeLowerContractible +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeLowerRetraction +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeMinimumContainment +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeNullBlockData +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeNullLayer +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativePeaks +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativePoset +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeTieLower +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeTiedDescent +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeTies +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeTranslation +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeUpperBasics +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeUpperComparison +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeUpperConnected +OAI.Topology.ArtinGroups.ParabolicIntersections.RelativeUpperSigns +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalCochain +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalCommonExtension +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalGap +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalMesh +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalNoChain +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalProperSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.SphericalReduction +OAI.Topology.ArtinGroups.ParabolicIntersections.StabilizerDescent +OAI.Topology.ArtinGroups.ParabolicIntersections.StandardEmbedding +OAI.Topology.ArtinGroups.ParabolicIntersections.TokenBoundary +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeActionDefinitions +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeAvoidingGraph +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeBallCount +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeBoundaryRays +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeBranch +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeBranchingHyperbolic +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeBridge +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeConvex +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeConvexSupport +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeFixedPaths +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeInteriorImage +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeInvariantTranslate +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeMinimalNormal +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeMinimalPair +OAI.Topology.ArtinGroups.ParabolicIntersections.TreePathMetric +OAI.Topology.ArtinGroups.ParabolicIntersections.TreePaths +OAI.Topology.ArtinGroups.ParabolicIntersections.TreePeriodicGrowth +OAI.Topology.ArtinGroups.ParabolicIntersections.TreePeriodicPaths +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeSegmentBallCount +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeSegmentCount +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeSegmentOccurrences +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeSeparatedPaths +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeShortcutAcylindrical +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeShortcutHyperbolic +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeShortcutMetric +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeShortcutPosition +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeTranslationSegment +OAI.Topology.ArtinGroups.ParabolicIntersections.TreeTripod +OAI.Topology.ArtinGroups.ParabolicIntersections.UnconditionalMain +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualAcylindrical +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualAmalgam +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualAmalgamProperties +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualEdgeMalnormal +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualEdgeTransitive +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualFactorMalnormal +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualInfiniteBranching +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualNonVirtuallyCyclic +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualParabolicSubtree +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualTree +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualTreeProperties +OAI.Topology.ArtinGroups.ParabolicIntersections.VisualTrivialSegment +OAI.Topology.ArtinGroups.ParabolicIntersections.WeakMalnormalAlgebra +OAI.Topology.ArtinGroups.Quivers.ClosedNeighborhood +OAI.Topology.ArtinGroups.Quivers.CoefficientMatrix +OAI.Topology.ArtinGroups.Quivers.CornerPath +OAI.Topology.ArtinGroups.Quivers.CornerScalar +OAI.Topology.ArtinGroups.Quivers.CotestPlacement +OAI.Topology.ArtinGroups.Quivers.Dual +OAI.Topology.ArtinGroups.Quivers.EdgeContraction +OAI.Topology.ArtinGroups.Quivers.ExtArrow +OAI.Topology.ArtinGroups.Quivers.Iso +OAI.Topology.ArtinGroups.Quivers.LengthCases +OAI.Topology.ArtinGroups.Quivers.Level +OAI.Topology.ArtinGroups.Quivers.LinearMatrix +OAI.Topology.ArtinGroups.Quivers.OffDiagonalVertexZero +OAI.Topology.ArtinGroups.Quivers.OrthogonalVertices +OAI.Topology.ArtinGroups.Quivers.PacketIndex +OAI.Topology.ArtinGroups.Quivers.Path +OAI.Topology.ArtinGroups.Quivers.PathTwo +OAI.Topology.ArtinGroups.Quivers.PathTwoSelf +OAI.Topology.ArtinGroups.Quivers.PathZero +OAI.Topology.ArtinGroups.Quivers.ProbeCartanCore +OAI.Topology.ArtinGroups.Quivers.ProbeLeaf +OAI.Topology.ArtinGroups.Quivers.ProbeSimpleEdge +OAI.Topology.ArtinGroups.Quivers.ProbeSwapIso +OAI.Topology.ArtinGroups.Quivers.ProbeVertex +OAI.Topology.ArtinGroups.Quivers.Reduction +OAI.Topology.ArtinGroups.Quivers.ReversibleQuiver +OAI.Topology.ArtinGroups.Quivers.ScalarCornerMatrixDegree +OAI.Topology.ArtinGroups.Quivers.SelfCornerEquiv +OAI.Topology.ArtinGroups.Quivers.SignDiagonal +OAI.Topology.ArtinGroups.Quivers.SimpleEdge +OAI.Topology.ArtinGroups.Quivers.SmulMul +OAI.Topology.ArtinGroups.Quivers.StringArrow +OAI.Topology.ArtinGroups.Quivers.TestIndex +OAI.Topology.ArtinGroups.Quivers.TestPlacement +OAI.Topology.ArtinGroups.Quivers.TestTransform +OAI.Topology.ArtinGroups.Quivers.TokenTestVector +OAI.Topology.ArtinGroups.Quivers.TraceLinear +OAI.Topology.ArtinGroups.Quivers.UnitTestVector +OAI.Topology.ArtinGroups.Quivers.VertexHom +OAI.Topology.ArtinGroups.Quivers.VertexIdMulPath +OAI.Topology.ArtinGroups.Quivers.VertexLinear +OAI.Topology.ArtinGroups.Quivers.VertexMinimal +OAI.Topology.ArtinGroups.Realizations.CellDeligne +OAI.Topology.ArtinGroups.Realizations.ConeWeights +OAI.Topology.ArtinGroups.Realizations.ContractionPoint +OAI.Topology.ArtinGroups.Realizations.DeligneRankBound +OAI.Topology.ArtinGroups.Realizations.FiniteWeightedNatSums +OAI.Topology.ArtinGroups.Realizations.FrameFamilyWeightedLevel +OAI.Topology.ArtinGroups.Realizations.FullSphericalCell +OAI.Topology.ArtinGroups.Realizations.FusionWeightSplit +OAI.Topology.ArtinGroups.Realizations.FusionWeightedHom +OAI.Topology.ArtinGroups.Realizations.MulBlockDiagonal'Entry +OAI.Topology.ArtinGroups.Realizations.NerveChain +OAI.Topology.ArtinGroups.Realizations.NerveOrderMap +OAI.Topology.ArtinGroups.Realizations.NerveOrderRetractionEquiv +OAI.Topology.ArtinGroups.Realizations.NervePrismPatch +OAI.Topology.ArtinGroups.Realizations.NervePrismValue +OAI.Topology.ArtinGroups.Realizations.OrderWeights +OAI.Topology.ArtinGroups.Realizations.OrderWeightsContractibleLower +OAI.Topology.ArtinGroups.Realizations.OrderWeightsContractibleUnique +OAI.Topology.ArtinGroups.Realizations.PositiveLiftedCell +OAI.Topology.ArtinGroups.Realizations.QuotientFinrankKer +OAI.Topology.ArtinGroups.Realizations.RealizeSimplex +OAI.Topology.ArtinGroups.Realizations.WeightAttach +OAI.Topology.ArtinGroups.Realizations.WeightCarrier +OAI.Topology.ArtinGroups.Realizations.WeightColor +OAI.Topology.ArtinGroups.Realizations.WeightDim +OAI.Topology.ArtinGroups.Realizations.WeightDual +OAI.Topology.ArtinGroups.Realizations.WeightEarlierLower +OAI.Topology.ArtinGroups.Realizations.WeightHomeomorph +OAI.Topology.ArtinGroups.Realizations.WeightInclusion +OAI.Topology.ArtinGroups.Realizations.WeightJoinKey +OAI.Topology.ArtinGroups.Realizations.WeightLinearLinkInverse +OAI.Topology.ArtinGroups.Realizations.WeightMap +OAI.Topology.ArtinGroups.Realizations.WeightMapCover +OAI.Topology.ArtinGroups.Realizations.WeightOld +OAI.Topology.ArtinGroups.Realizations.WeightVertexRetract +OAI.Topology.ArtinGroups.Realizations.WeightedCounts +OAI.Topology.ArtinGroups.Realizations.WeightedReflectedHigh diff --git a/tasks/artin-parabolic-intersections/solution/reference.py b/tasks/artin-parabolic-intersections/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/artin-parabolic-intersections/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/artin-parabolic-intersections/solution/solve.sh b/tasks/artin-parabolic-intersections/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..68fac93263e284024f7136545015d858731a03dc --- /dev/null +++ b/tasks/artin-parabolic-intersections/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ArtinParabolicIntersections, i.e. module OAI.Topology.ArtinGroups.ParabolicIntersections.Main and the +# 782 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Topology.ArtinGroups.ParabolicIntersections.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ArtinParabolicIntersections" diff --git a/tasks/artin-parabolic-intersections/task.toml b/tasks/artin-parabolic-intersections/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..15a0fed7c7d27654a8ecb8042a6fab98e43ec13b --- /dev/null +++ b/tasks/artin-parabolic-intersections/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/artin-parabolic-intersections" +version = "1.0.0" +description = "Prove ArtinParabolicIntersections (openai/math family 254: Classifying spaces and geometric obstructions for Artin groups) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ArtinParabolicIntersections.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ArtinParabolicIntersections" +family = "254" +family_title = "Classifying spaces and geometric obstructions for Artin groups" +subject = "Group theory" +theorems = ["OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_intersections", "OAI.HarmonicArtin.ParabolicIntersections.unconditional_arbitrary_intersections", "OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_closure", "OAI.HarmonicArtin.ParabolicIntersections.unconditional_nonclique_dynamics"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Topology.ArtinGroups.ParabolicIntersections.Main" +reference_modules = 782 +reference_lean_bytes = 3300665 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1711 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14670 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/artin-parabolic-intersections/tests/Challenge.lean b/tasks/artin-parabolic-intersections/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f113cc88c3802a78d3dcd5ae03229163f2fbec1b --- /dev/null +++ b/tasks/artin-parabolic-intersections/tests/Challenge.lean @@ -0,0 +1,129 @@ +import Mathlib + +namespace OAI + +/-! Parabolic intersections, parabolic closure, and non-clique Artin-group dynamics. -/ + +namespace HarmonicArtin + +universe u + +variable {S : Type u} + +def alternating (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def braidRelators (M : CoxeterMatrix S) : Set (FreeGroup S) := + Set.range fun st : S × S => + alternating st.1 st.2 (M st.1 st.2) * + (alternating st.2 st.1 (M st.1 st.2))⁻¹ + +abbrev Artin (M : CoxeterMatrix S) := PresentedGroup (braidRelators M) + +def generator (M : CoxeterMatrix S) (s : S) : Artin M := PresentedGroup.of s + +def artinParabolic (M : CoxeterMatrix S) (T : Set S) : Subgroup (Artin M) := + Subgroup.closure (generator M '' T) + +end HarmonicArtin + +namespace HarmonicArtin.ParabolicIntersections + +variable {G : Type*} [Group G] + +/-- `g P g⁻¹`, with membership expressed without existential witnesses. -/ +def conjugate (g : G) (P : Subgroup G) : Subgroup G := + P.comap (MulAut.conj g⁻¹).toMonoidHom + +variable {S : Type*} (M : CoxeterMatrix S) + +/-- Conjugates of standard subgroups, with no spherical-type restriction. -/ +def IsParabolic (P : Subgroup (Artin M)) : Prop := + ∃ (X : Set S) (g : Artin M), P = conjugate g (artinParabolic M X) + +end HarmonicArtin.ParabolicIntersections + +namespace HarmonicArtin.ParabolicIntersections + +noncomputable def gromovProduct {X : Type} [MetricSpace X] (o x y : X) : ℝ := + (dist o x + dist o y - dist x y)/2 + +def IsGromovHyperbolic (X : Type) [MetricSpace X] : Prop := + ∃ δ : ℝ, 0 ≤ δ ∧ ∀ o x y z : X, + min (gromovProduct o x y) (gromovProduct o y z) ≤ gromovProduct o x z + δ + +def IsGeodesicMetric (X : Type) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ : Set.Icc (0 : ℝ) (dist x y) → X, + Isometry γ ∧ γ ⟨0,le_rfl,dist_nonneg⟩=x ∧ γ ⟨dist x y,dist_nonneg,le_rfl⟩=y + +def IsGromovSequence {X : Type} [MetricSpace X] (o : X) (u : ℕ → X) : Prop := + ∀ R : ℝ, ∃ N : ℕ, ∀ m, N ≤ m → ∀ n, N ≤ n → R ≤ gromovProduct o (u m) (u n) + +def IsAcylindrical (G X : Type) [Group G] [MetricSpace X] [MulAction G X] : Prop := + ∀ ε : ℝ, 0 < ε → ∃ R : ℝ, ∃ N : ℕ, ∀ x y : X, R ≤ dist x y → + {g : G | dist x (g • x) ≤ ε ∧ dist y (g • y) ≤ ε}.Finite ∧ + {g : G | dist x (g • x) ≤ ε ∧ dist y (g • y) ≤ ε}.ncard ≤ N + +def HasThreeOrbitLimitPoints (G X : Type) [Group G] [MetricSpace X] [MulAction G X] : Prop := + ∃ o : X, ∃ u : Fin 3 → ℕ → G, + (∀ i, IsGromovSequence o (fun n => u i n • o)) ∧ + ∀ i j, i ≠ j → ∃ B : ℝ, ∀ m n, gromovProduct o (u i m • o) (u j n • o) ≤ B + +/-- An isometric non-elementary acylindrical action on a geodesic +Gromov-hyperbolic metric space. -/ +def AcylindricallyHyperbolic (G : Type) [Group G] : Prop := + ∃ (X : Type) (metric : MetricSpace X) (action : MulAction G X), + @IsGeodesicMetric X metric ∧ @IsGromovHyperbolic X metric ∧ + (∀ g : G, @Isometry X X metric.toPseudoMetricSpace.toPseudoEMetricSpace metric.toPseudoMetricSpace.toPseudoEMetricSpace + (fun x => @SMul.smul G X action.toSMul g x)) ∧ + @IsAcylindrical G X _ metric action ∧ @HasThreeOrbitLimitPoints G X _ metric action + +def WeaklyMalnormal {G : Type} [Group G] (P : Subgroup G) : Prop := + ∃ g : G, (↑(P ⊓ conjugate g P) : Set G).Finite + +variable {S : Type} (M : CoxeterMatrix S) + +/-- No nontrivial partition has every cross label equal to two. -/ +def IsIrreducible : Prop := + ∀ Y : Set S, Y.Nonempty → Yᶜ.Nonempty → ∃ s ∈ Y, ∃ t ∉ Y, M s t ≠ 2 + +end HarmonicArtin.ParabolicIntersections + +namespace HarmonicArtin.ParabolicIntersections + +variable {S : Type} [Fintype S] [LinearOrder S] (M : CoxeterMatrix S) + +/-- The intersection of two conjugates of standard parabolics is parabolic. -/ +theorem unconditional_parabolic_intersections + (X Y : Set S) (g h : Artin M) : + ∃ (Z : Set S) (k : Artin M), + conjugate g (artinParabolic M X) ⊓ conjugate h (artinParabolic M Y) = + conjugate k (artinParabolic M Z) := by + sorry + +/-- An arbitrary parabolic intersection is obtained from at most the rank many members. -/ +theorem unconditional_arbitrary_intersections + (F : Set (Subgroup (Artin M))) (hF : ∀ P ∈ F, IsParabolic M P) : + (∃ F₀ : Finset (Subgroup (Artin M)), + (↑F₀ : Set (Subgroup (Artin M))) ⊆ F ∧ F₀.card ≤ Nat.card S ∧ + sInf F = sInf (↑F₀ : Set (Subgroup (Artin M)))) ∧ IsParabolic M (sInf F) := by + sorry + +/-- Every subset is contained in a unique smallest parabolic subgroup. -/ +theorem unconditional_parabolic_closure (E : Set (Artin M)) : + ∃! P : Subgroup (Artin M), IsParabolic M P ∧ E ⊆ P ∧ + ∀ Q : Subgroup (Artin M), IsParabolic M Q → E ⊆ Q → P ≤ Q := by + sorry + +/-- An irreducible non-clique Artin group has an acylindrical non-elementary +hyperbolic action and all its proper parabolics are weakly malnormal. -/ +theorem unconditional_nonclique_dynamics + (hIrred : IsIrreducible M) (hInf : ∃ s t : S, s ≠ t ∧ M s t = 0) : + AcylindricallyHyperbolic (Artin M) ∧ + ∀ P : Subgroup (Artin M), IsParabolic M P → P ≠ ⊤ → WeaklyMalnormal P := by + sorry + +end HarmonicArtin.ParabolicIntersections + +end OAI diff --git a/tasks/artin-parabolic-intersections/tests/grade.py b/tasks/artin-parabolic-intersections/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/artin-parabolic-intersections/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/artin-parabolic-intersections/tests/task.json b/tasks/artin-parabolic-intersections/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cc613ca7fadc10533c6f9e5a5cd436735f377a2b --- /dev/null +++ b/tasks/artin-parabolic-intersections/tests/task.json @@ -0,0 +1,18 @@ +{ + "challenge": "ArtinParabolicIntersections", + "comparator": { + "theorem_names": [ + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_intersections", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_arbitrary_intersections", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_parabolic_closure", + "OAI.HarmonicArtin.ParabolicIntersections.unconditional_nonclique_dynamics" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13770 +} \ No newline at end of file diff --git a/tasks/artin-parabolic-intersections/tests/test.sh b/tasks/artin-parabolic-intersections/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/artin-parabolic-intersections/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/asymptotically-minimal-littlewood/environment/Dockerfile b/tasks/asymptotically-minimal-littlewood/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/asymptotically-minimal-littlewood/environment/fetch_mathlib.sh b/tasks/asymptotically-minimal-littlewood/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/asymptotically-minimal-littlewood/environment/lake-manifest.json b/tasks/asymptotically-minimal-littlewood/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/asymptotically-minimal-littlewood/environment/lakefile.lean b/tasks/asymptotically-minimal-littlewood/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/asymptotically-minimal-littlewood/environment/lean_setup.sh b/tasks/asymptotically-minimal-littlewood/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/asymptotically-minimal-littlewood/environment/pack_submission.py b/tasks/asymptotically-minimal-littlewood/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/asymptotically-minimal-littlewood/instruction.md b/tasks/asymptotically-minimal-littlewood/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44fb40fcc7f186bf5c674d5869b29e92d78efa5e --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/instruction.md @@ -0,0 +1,74 @@ +# openai/math challenge `AsymptoticallyMinimalLittlewood` (family 076) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 076 of the release, *Ultraflat real Littlewood polynomials* +(Real and complex analysis). The family as a whole: Constructs polynomials with $N$ consecutive coefficients in $\{-1,1\}$ whose modulus is $(1+o(1))\sqrt N$ uniformly on the entire unit circle, for every sufficiently large integer length $N$. Thus real Littlewood polynomials are ultraflat, including at the real endpoints. Their binary merit factors tend to infinity, disproving Turyn's bounded-merit-factor conjecture. + +The challenge is `AsymptoticallyMinimalLittlewood`, also at `/opt/openai-math/challenges/AsymptoticallyMinimalLittlewood.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace AsymptoticallyMinimalLittlewood + +def littlewoodValue {N : ℕ} (ε : Fin N → ℝ) (z : ℂ) : ℂ := + ∑ k : Fin N, (ε k : ℂ) * z ^ (k : ℕ) + +def IsRealSigning {N : ℕ} (ε : Fin N → ℝ) : Prop := + ∀ k, ε k = -1 ∨ ε k = 1 + +def MainStatement : Prop := + ∀ η : ℝ, 0 < η → ∃ N₀ : ℕ, 1 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∃ ε : Fin N → ℝ, IsRealSigning ε ∧ + ∀ z : ℂ, ‖z‖ = 1 → ‖littlewoodValue ε z‖ ≤ (1 + η) * Real.sqrt N + +theorem main : MainStatement := by + sorry + +end AsymptoticallyMinimalLittlewood + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AsymptoticallyMinimalLittlewood.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AsymptoticallyMinimalLittlewood.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/asymptotically-minimal-littlewood/solution/closure.txt b/tasks/asymptotically-minimal-littlewood/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..adb003bf1e511dc3def095a2c9d9dd6691e1b70a --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/solution/closure.txt @@ -0,0 +1,24 @@ +OAI.Analysis.Littlewood.AlmostSign +OAI.Analysis.Littlewood.Averages +OAI.Analysis.Littlewood.BinaryPacket +OAI.Analysis.Littlewood.BlockSampling +OAI.Analysis.Littlewood.Chunks +OAI.Analysis.Littlewood.Curvature +OAI.Analysis.Littlewood.Cutoff +OAI.Analysis.Littlewood.DependentMoments +OAI.Analysis.Littlewood.FiniteRank +OAI.Analysis.Littlewood.Gaussian +OAI.Analysis.Littlewood.IntervalPacking +OAI.Analysis.Littlewood.Main +OAI.Analysis.Littlewood.Matching +OAI.Analysis.Littlewood.ModeSampling +OAI.Analysis.Littlewood.Model +OAI.Analysis.Littlewood.Nibble +OAI.Analysis.Littlewood.ProductProbability +OAI.Analysis.Littlewood.QuadraticTail +OAI.Analysis.Littlewood.Rounding +OAI.Analysis.Littlewood.SamplingEnergy +OAI.Analysis.Littlewood.SamplingTail +OAI.Analysis.Littlewood.SlotGraph +OAI.Analysis.Littlewood.SlotParameters +OAI.Analysis.Littlewood.Spreading diff --git a/tasks/asymptotically-minimal-littlewood/solution/reference.py b/tasks/asymptotically-minimal-littlewood/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/asymptotically-minimal-littlewood/solution/solve.sh b/tasks/asymptotically-minimal-littlewood/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ddb5cc622bbd10b24251c50f5f98feeb517fbb9d --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AsymptoticallyMinimalLittlewood, i.e. module OAI.Analysis.Littlewood.Main and the +# 24 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Littlewood.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AsymptoticallyMinimalLittlewood" diff --git a/tasks/asymptotically-minimal-littlewood/task.toml b/tasks/asymptotically-minimal-littlewood/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1be341ffaa9f39da7ebd4db8914a55e3b25b19c3 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/asymptotically-minimal-littlewood" +version = "1.0.0" +description = "Prove AsymptoticallyMinimalLittlewood (openai/math family 076: Ultraflat real Littlewood polynomials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AsymptoticallyMinimalLittlewood.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AsymptoticallyMinimalLittlewood" +family = "076" +family_title = "Ultraflat real Littlewood polynomials" +subject = "Real and complex analysis" +theorems = ["OAI.AsymptoticallyMinimalLittlewood.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Littlewood.Main" +reference_modules = 24 +reference_lean_bytes = 432620 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 919 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12089 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/asymptotically-minimal-littlewood/tests/Challenge.lean b/tasks/asymptotically-minimal-littlewood/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7323fc6a4121e0c3686e312bb6e5c7720490c56d --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/tests/Challenge.lean @@ -0,0 +1,23 @@ +import Mathlib + +namespace OAI + +namespace AsymptoticallyMinimalLittlewood + +def littlewoodValue {N : ℕ} (ε : Fin N → ℝ) (z : ℂ) : ℂ := + ∑ k : Fin N, (ε k : ℂ) * z ^ (k : ℕ) + +def IsRealSigning {N : ℕ} (ε : Fin N → ℝ) : Prop := + ∀ k, ε k = -1 ∨ ε k = 1 + +def MainStatement : Prop := + ∀ η : ℝ, 0 < η → ∃ N₀ : ℕ, 1 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∃ ε : Fin N → ℝ, IsRealSigning ε ∧ + ∀ z : ℂ, ‖z‖ = 1 → ‖littlewoodValue ε z‖ ≤ (1 + η) * Real.sqrt N + +theorem main : MainStatement := by + sorry + +end AsymptoticallyMinimalLittlewood + +end OAI diff --git a/tasks/asymptotically-minimal-littlewood/tests/grade.py b/tasks/asymptotically-minimal-littlewood/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/asymptotically-minimal-littlewood/tests/task.json b/tasks/asymptotically-minimal-littlewood/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5e51965555218656556d086741f717002f89f00d --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AsymptoticallyMinimalLittlewood", + "comparator": { + "theorem_names": [ + "OAI.AsymptoticallyMinimalLittlewood.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11189 +} \ No newline at end of file diff --git a/tasks/asymptotically-minimal-littlewood/tests/test.sh b/tasks/asymptotically-minimal-littlewood/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/asymptotically-minimal-littlewood/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/auslander-reiten/environment/Dockerfile b/tasks/auslander-reiten/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/auslander-reiten/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/auslander-reiten/environment/fetch_mathlib.sh b/tasks/auslander-reiten/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/auslander-reiten/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/auslander-reiten/environment/lake-manifest.json b/tasks/auslander-reiten/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/auslander-reiten/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/auslander-reiten/environment/lakefile.lean b/tasks/auslander-reiten/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/auslander-reiten/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/auslander-reiten/environment/lean_setup.sh b/tasks/auslander-reiten/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/auslander-reiten/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/auslander-reiten/environment/pack_submission.py b/tasks/auslander-reiten/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/auslander-reiten/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/auslander-reiten/instruction.md b/tasks/auslander-reiten/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7f35087467ef2e576b68b6779bb4466ee9ba7e55 --- /dev/null +++ b/tasks/auslander-reiten/instruction.md @@ -0,0 +1,128 @@ +# openai/math challenge `AuslanderReiten` (family 199) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 199 of the release, *Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama* +(Algebra). The family as a whole: Constructs finite-dimensional algebras over a characteristic-two rational-function field that disprove the Auslander–Reiten and Gorenstein-projective conjectures, and Tachikawa's second conjecture. An associated endomorphism algebra also disproves the classical, generalized and strong Nakayama conjectures, the Auslander–Gorenstein conjecture, and the Wakamatsu tilting conjecture. The counterexamples persist under every extension of the base field. + +The challenge is `AuslanderReiten`, also at `/opt/openai-math/challenges/AuslanderReiten.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open CategoryTheory +open scoped TensorProduct +namespace ArExplicit.Statement +universe u v + +abbrev K := FractionRing (MvPolynomial (Fin 3) (ZMod 2)) + +def parameters (i : Fin 3) : K := + algebraMap (MvPolynomial (Fin 3) (ZMod 2)) K (MvPolynomial.X i) + +def TotallyAcyclicWitness (R : Type u) [Ring R] + (Z : Type u) [AddCommGroup Z] [Module R Z] : Prop := + ∃ P : ChainComplex (ModuleCat.{u} R) ℤ, + (∀ i : ℤ, Module.Finite R (P.X i) ∧ Module.Projective R (P.X i)) ∧ + (∀ i : ℤ, LinearMap.range (P.d (i+1) i).hom = LinearMap.ker (P.d i (i-1)).hom) ∧ + (∀ (Q : Type u) [AddCommGroup Q] [Module R Q] [Module.Projective R Q] + (i : ℤ) (f : P.X i →ₗ[R] Q), f.comp (P.d (i+1) i).hom = 0 → + ∃ g : P.X (i-1) →ₗ[R] Q, f = g.comp (P.d i (i-1)).hom) ∧ + Nonempty (Z ≃ₗ[R] (P.X 0 ⧸ LinearMap.range (P.d 1 0).hom)) + +def Conclusions (F R Z : Type u) [Field F] [Ring R] [Algebra F R] + [AddCommGroup Z] [Module R Z] [Module F Z] [IsScalarTower F R Z] : Prop := + FiniteDimensional F R ∧ + FiniteDimensional F Z ∧ + ¬ Module.Projective R Z ∧ + TotallyAcyclicWitness R Z ∧ + (∀ i : ℕ, 0 < i → + Subsingleton (Abelian.Ext (ModuleCat.of R Z) (ModuleCat.of R Z) i)) ∧ + (∀ i : ℕ, 0 < i → + Subsingleton (Abelian.Ext (ModuleCat.of R Z) (ModuleCat.of R R) i)) ∧ + Nonempty ((R ⧸ Ring.jacobson R) ≃ₐ[F] (Fin 8 → F)) ∧ + (Ring.jacobson R)^4 ≠ ⊥ + +structure System where + algebraCarrier : Type + [ring : Ring algebraCarrier] + [scalarAlgebra : Algebra K algebraCarrier] + moduleCarrier : Type + [additiveGroup : AddCommGroup moduleCarrier] + [action : Module algebraCarrier moduleCarrier] + [scalarAction : Module K moduleCarrier] + [actionTower : IsScalarTower K algebraCarrier moduleCarrier] + +attribute [instance] System.ring System.scalarAlgebra System.additiveGroup + System.action System.scalarAction System.actionTower + +def FullStatement : Prop := + AlgebraicIndependent (ZMod 2) parameters ∧ + ∃ s : System, + Conclusions K s.algebraCarrier s.moduleCarrier ∧ + ∀ (E : Type v) [Field E] [Algebra K E], + ∃ action : Module (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier), + letI := action + ∃ tower : IsScalarTower E (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier), + letI := tower + (∀ (a b : E) (r : s.algebraCarrier) (z : s.moduleCarrier), + (a ⊗ₜ[K] r) • (b ⊗ₜ[K] z) = (a*b) ⊗ₜ[K] (r • z)) ∧ + Conclusions E (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier) + +end ArExplicit.Statement + +namespace ArExplicit.Statement +universe v + +theorem main : FullStatement.{v} := by + sorry + +end ArExplicit.Statement + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/AuslanderReiten.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ArExplicit.Statement.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/auslander-reiten/solution/closure.txt b/tasks/auslander-reiten/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee785214bc25e0afa214bf53e2762c215673e039 --- /dev/null +++ b/tasks/auslander-reiten/solution/closure.txt @@ -0,0 +1,732 @@ +OAI.Algebra.AuslanderReiten.Algebras.BaseAlgebra +OAI.Algebra.AuslanderReiten.Algebras.BaseRadical +OAI.Algebra.AuslanderReiten.Algebras.FrobeniusOpposite +OAI.Algebra.AuslanderReiten.Algebras.FrobeniusTrace +OAI.Algebra.AuslanderReiten.Algebras.Radical +OAI.Algebra.AuslanderReiten.Algebras.SimpleDual +OAI.Algebra.AuslanderReiten.Algebras.SimpleHomScalars +OAI.Algebra.AuslanderReiten.Algebras.SimpleModule +OAI.Algebra.AuslanderReiten.Algebras.SymmetricSocle +OAI.Algebra.AuslanderReiten.Algebras.TCoordinates +OAI.Algebra.AuslanderReiten.Algebras.TMultiplication +OAI.Algebra.AuslanderReiten.Algebras.TSimple +OAI.Algebra.AuslanderReiten.Algebras.TSimpleEnd +OAI.Algebra.AuslanderReiten.Algebras.TSimpleTwist +OAI.Algebra.AuslanderReiten.Algebras.TSocle +OAI.Algebra.AuslanderReiten.Algebras.TensorFrobenius +OAI.Algebra.AuslanderReiten.Algebras.TensorRadical +OAI.Algebra.AuslanderReiten.Algebras.TensorSimple +OAI.Algebra.AuslanderReiten.Algebras.TensorStructure +OAI.Algebra.AuslanderReiten.Algebras.TrivialExtension +OAI.Algebra.AuslanderReiten.Algebras.TrivialExtensionRadical +OAI.Algebra.AuslanderReiten.All +OAI.Algebra.AuslanderReiten.Bar.AugmentedBarEvaluation +OAI.Algebra.AuslanderReiten.Bar.BarBalancedCanonical +OAI.Algebra.AuslanderReiten.Bar.BarBalancedCompatibility +OAI.Algebra.AuslanderReiten.Bar.BarBalancedEquiv +OAI.Algebra.AuslanderReiten.Bar.BarBalancedModule +OAI.Algebra.AuslanderReiten.Bar.BarBalancedRaw +OAI.Algebra.AuslanderReiten.Bar.BarBalancedSuffix +OAI.Algebra.AuslanderReiten.Bar.BarBimodule +OAI.Algebra.AuslanderReiten.Bar.BarCasimir +OAI.Algebra.AuslanderReiten.Bar.BarCochain +OAI.Algebra.AuslanderReiten.Bar.BarComplex +OAI.Algebra.AuslanderReiten.Bar.BarProjective +OAI.Algebra.AuslanderReiten.Bar.BarResolution +OAI.Algebra.AuslanderReiten.Bar.BarScalarCoordinates +OAI.Algebra.AuslanderReiten.Bar.BarSuffix +OAI.Algebra.AuslanderReiten.Bar.BarTensorRegular +OAI.Algebra.AuslanderReiten.Bar.BarTensorRegularCoordinates +OAI.Algebra.AuslanderReiten.Bar.BarTensorRegularIsoCoordinates +OAI.Algebra.AuslanderReiten.Bar.CanonicalBarEvaluation +OAI.Algebra.AuslanderReiten.Bar.CanonicalBarPure +OAI.Algebra.AuslanderReiten.Bar.CanonicalBarSquare +OAI.Algebra.AuslanderReiten.Bar.CanonicalBarTermValues +OAI.Algebra.AuslanderReiten.Bar.ConcreteBarFreeAugmentation +OAI.Algebra.AuslanderReiten.Bar.ConcreteNativeBar +OAI.Algebra.AuslanderReiten.Bar.ExternalBarCyclicCoordinate +OAI.Algebra.AuslanderReiten.Bar.ExternalBarEvaluation +OAI.Algebra.AuslanderReiten.Bar.ExternalBarFreeAugmentation +OAI.Algebra.AuslanderReiten.Bar.ExternalBarFreeCoordinate +OAI.Algebra.AuslanderReiten.Bar.ExternalBarFreePure +OAI.Algebra.AuslanderReiten.Bar.ExternalBarTotalFree +OAI.Algebra.AuslanderReiten.Bar.ModuleBar +OAI.Algebra.AuslanderReiten.Bar.ModuleBarAutomorphism +OAI.Algebra.AuslanderReiten.Bar.ModuleBarCochain +OAI.Algebra.AuslanderReiten.Bar.ModuleBarCubic +OAI.Algebra.AuslanderReiten.Bar.ModuleBarCubicConjugate +OAI.Algebra.AuslanderReiten.Bar.ModuleBarExtTwist +OAI.Algebra.AuslanderReiten.Bar.ModuleBarFreeAugmentation +OAI.Algebra.AuslanderReiten.Bar.ModuleBarFreeCoordinate +OAI.Algebra.AuslanderReiten.Bar.ModuleBarHomTwist +OAI.Algebra.AuslanderReiten.Bar.ModuleBarNative +OAI.Algebra.AuslanderReiten.Bar.ModuleBarNativeTransport +OAI.Algebra.AuslanderReiten.Bar.ModuleBarNativeTwist +OAI.Algebra.AuslanderReiten.Bar.ModuleBarPositiveModel +OAI.Algebra.AuslanderReiten.Bar.ModuleBarScalarClass +OAI.Algebra.AuslanderReiten.Bar.ModuleBarScalarTransport +OAI.Algebra.AuslanderReiten.Bar.ModuleBarSuffix +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorAction +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorAugmented +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorCentral +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorCentralAction +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorClass +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorEndpoint +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorEndpointCoordinates +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorExact +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorExt +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorGeneration +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorHom +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorProducts +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorTransport +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTensorTwist +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTwistAction +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTwistCocycle +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTwistExact +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTwistExtAction +OAI.Algebra.AuslanderReiten.Bar.ModuleBarTwistIdentity +OAI.Algebra.AuslanderReiten.Bar.NativeBarAugmentation +OAI.Algebra.AuslanderReiten.Bar.NativeBarCompositeValues +OAI.Algebra.AuslanderReiten.Bar.NativeBarEvaluation +OAI.Algebra.AuslanderReiten.Bar.NativeBarFreeEndpoint +OAI.Algebra.AuslanderReiten.Bar.TBarHomotopies +OAI.Algebra.AuslanderReiten.Bar.TBarLift +OAI.Algebra.AuslanderReiten.Bar.TCasimir +OAI.Algebra.AuslanderReiten.Bar.TCasimirAugmentation +OAI.Algebra.AuslanderReiten.Bar.TCasimirEvaluation +OAI.Algebra.AuslanderReiten.Bar.TCasimirSquare +OAI.Algebra.AuslanderReiten.Bar.TwistedBar +OAI.Algebra.AuslanderReiten.Bar.TwistedBarTensorRegular +OAI.Algebra.AuslanderReiten.BaseChange.MainScalarExtension +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtension +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionCokernel +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionComplete +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionDescent +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionExact +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionExt +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionHom +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionHomExact +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionPresentation +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionProjective +OAI.Algebra.AuslanderReiten.BaseChange.ScalarExtensionStructure +OAI.Algebra.AuslanderReiten.Basic +OAI.Algebra.AuslanderReiten.Cocycles.CocycleCertificate +OAI.Algebra.AuslanderReiten.Cocycles.CocycleClosure +OAI.Algebra.AuslanderReiten.Cocycles.CocycleCorners +OAI.Algebra.AuslanderReiten.Cocycles.CocycleData +OAI.Algebra.AuslanderReiten.Cocycles.CocycleDetector +OAI.Algebra.AuslanderReiten.Cocycles.CocycleDifferential +OAI.Algebra.AuslanderReiten.Cocycles.CocycleExt +OAI.Algebra.AuslanderReiten.Cocycles.CocycleFormula +OAI.Algebra.AuslanderReiten.Cocycles.CocycleFunctor +OAI.Algebra.AuslanderReiten.Cocycles.CocycleRelative +OAI.Algebra.AuslanderReiten.Cocycles.CocycleTwist +OAI.Algebra.AuslanderReiten.Cocycles.RawCocycleProducts +OAI.Algebra.AuslanderReiten.Cocycles.ReversedCocycleMap +OAI.Algebra.AuslanderReiten.Cocycles.SourceCocycleNaturality +OAI.Algebra.AuslanderReiten.Cocycles.SparseCocycle +OAI.Algebra.AuslanderReiten.Cocycles.SparseParity +OAI.Algebra.AuslanderReiten.Cocycles.TwistedBoundary +OAI.Algebra.AuslanderReiten.Cocycles.TwistedBoundaryData +OAI.Algebra.AuslanderReiten.Cocycles.TwistedBoundaryFormula +OAI.Algebra.AuslanderReiten.Complete.CompleteCokernelLifts +OAI.Algebra.AuslanderReiten.Complete.CompleteComparison +OAI.Algebra.AuslanderReiten.Complete.CompleteCone +OAI.Algebra.AuslanderReiten.Complete.CompleteFunctorCokernelAction +OAI.Algebra.AuslanderReiten.Complete.CompleteFunctorRawEndpoint +OAI.Algebra.AuslanderReiten.Complete.CompleteNullhomotopy +OAI.Algebra.AuslanderReiten.Complete.CompleteResolution +OAI.Algebra.AuslanderReiten.Complete.CompleteResolutionAllProjectives +OAI.Algebra.AuslanderReiten.Complete.CompleteResolutionTail +OAI.Algebra.AuslanderReiten.Complete.CompleteShift +OAI.Algebra.AuslanderReiten.Complete.CompleteShiftDual +OAI.Algebra.AuslanderReiten.Complete.CompleteStableComparison +OAI.Algebra.AuslanderReiten.Complete.CompleteStableDualityAt +OAI.Algebra.AuslanderReiten.Complete.CompleteStableSourceNaturality +OAI.Algebra.AuslanderReiten.Complete.CompleteTailCanonical +OAI.Algebra.AuslanderReiten.Complete.CompleteTailEndpoint +OAI.Algebra.AuslanderReiten.Complete.CompleteTailExt +OAI.Algebra.AuslanderReiten.Complete.CompleteTailFunctor +OAI.Algebra.AuslanderReiten.Complete.CompleteTailMap +OAI.Algebra.AuslanderReiten.Complete.ConcreteTateModel +OAI.Algebra.AuslanderReiten.Complete.FiniteCompleteResolution +OAI.Algebra.AuslanderReiten.Complete.FrobeniusGorenstein +OAI.Algebra.AuslanderReiten.Complete.FullTateModel +OAI.Algebra.AuslanderReiten.Complete.ProjectiveCompleteResolution +OAI.Algebra.AuslanderReiten.Complete.RestrictionComplete +OAI.Algebra.AuslanderReiten.Complete.SelfInjectiveComplex +OAI.Algebra.AuslanderReiten.Complete.TateKoszul +OAI.Algebra.AuslanderReiten.Cones.BimoduleTwoCone +OAI.Algebra.AuslanderReiten.Cones.BimoduleTwoConeExact +OAI.Algebra.AuslanderReiten.Cones.BimoduleTwoConeSides +OAI.Algebra.AuslanderReiten.Cones.ChainCokernelIso +OAI.Algebra.AuslanderReiten.Cones.CochainCokernel +OAI.Algebra.AuslanderReiten.Cones.CochainCokernelIso +OAI.Algebra.AuslanderReiten.Cones.CokernelLinearCongr +OAI.Algebra.AuslanderReiten.Cones.CokernelProduct +OAI.Algebra.AuslanderReiten.Cones.CokernelShift +OAI.Algebra.AuslanderReiten.Cones.CokernelShiftCoordinates +OAI.Algebra.AuslanderReiten.Cones.CokernelSyzygy +OAI.Algebra.AuslanderReiten.Cones.ConcreteTwoConeCoordinates +OAI.Algebra.AuslanderReiten.Cones.ConcreteTwoConeEvaluation +OAI.Algebra.AuslanderReiten.Cones.ConcreteTwoConeProfile +OAI.Algebra.AuslanderReiten.Cones.ConcreteTwoTwistRows +OAI.Algebra.AuslanderReiten.Cones.ConeCohomology +OAI.Algebra.AuslanderReiten.Cones.ConeCokernel +OAI.Algebra.AuslanderReiten.Cones.ConeComparison +OAI.Algebra.AuslanderReiten.Cones.ConeConnectingCoordinates +OAI.Algebra.AuslanderReiten.Cones.ConeCriterion +OAI.Algebra.AuslanderReiten.Cones.ConeEnd +OAI.Algebra.AuslanderReiten.Cones.ConeExactness +OAI.Algebra.AuslanderReiten.Cones.ConeQuotientMap +OAI.Algebra.AuslanderReiten.Cones.MappingConeCokernel +OAI.Algebra.AuslanderReiten.Cones.MappingConeModule +OAI.Algebra.AuslanderReiten.Cones.MappingConeNaturality +OAI.Algebra.AuslanderReiten.Cones.MappingConeTotal +OAI.Algebra.AuslanderReiten.Cones.ShortExactConeRaw +OAI.Algebra.AuslanderReiten.Cones.TwoCone +OAI.Algebra.AuslanderReiten.Cones.TwoConeBaseRestriction +OAI.Algebra.AuslanderReiten.Cones.TwoConeBoundaryIdentification +OAI.Algebra.AuslanderReiten.Cones.TwoConeCells +OAI.Algebra.AuslanderReiten.Cones.TwoConeConnectingMaps +OAI.Algebra.AuslanderReiten.Cones.TwoConeEvaluatedBoundary +OAI.Algebra.AuslanderReiten.Cones.TwoConeEvaluatedTriangles +OAI.Algebra.AuslanderReiten.Cones.TwoConeExtensionDiagrams +OAI.Algebra.AuslanderReiten.Cones.TwoConeFiltration +OAI.Algebra.AuslanderReiten.Cones.TwoConeIteration +OAI.Algebra.AuslanderReiten.Cones.TwoConeKoszulCoordinates +OAI.Algebra.AuslanderReiten.Cones.TwoConeModuleTriangles +OAI.Algebra.AuslanderReiten.Cones.TwoConeProjective +OAI.Algebra.AuslanderReiten.Cones.TwoConeRestriction +OAI.Algebra.AuslanderReiten.Cones.TwoConeShiftedMap +OAI.Algebra.AuslanderReiten.Cones.TwoConeSkeleton +OAI.Algebra.AuslanderReiten.Cones.TwoConeStableRepresentative +OAI.Algebra.AuslanderReiten.Cones.TwoConeTail +OAI.Algebra.AuslanderReiten.Cones.TwoConeTailRestriction +OAI.Algebra.AuslanderReiten.Cones.TwoConeTopCokernel +OAI.Algebra.AuslanderReiten.Cones.TwoTriangleFiltration +OAI.Algebra.AuslanderReiten.Coordinates.BranchHomCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.BranchHomProfile +OAI.Algebra.AuslanderReiten.Coordinates.CochainStableComparison +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteComparisonPositive +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteCubicAction +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteCubicClasses +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteCubicStepAction +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteMainCriterion +OAI.Algebra.AuslanderReiten.Coordinates.ConcreteParameters +OAI.Algebra.AuslanderReiten.Coordinates.CubicShiftNaturality +OAI.Algebra.AuslanderReiten.Coordinates.FiniteConnectingCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.FiniteConnectingProducts +OAI.Algebra.AuslanderReiten.Coordinates.FiniteExtSourceComparison +OAI.Algebra.AuslanderReiten.Coordinates.FiniteExtSourceCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.FiniteShiftedMap +OAI.Algebra.AuslanderReiten.Coordinates.FiniteSourceCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.FiniteTensorComparison +OAI.Algebra.AuslanderReiten.Coordinates.FiniteTensorComparisonEquiv +OAI.Algebra.AuslanderReiten.Coordinates.FiniteTensorProjection +OAI.Algebra.AuslanderReiten.Coordinates.GradedConjugate +OAI.Algebra.AuslanderReiten.Coordinates.GradedRowCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.IteratedCubicCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.IteratedShiftAddition +OAI.Algebra.AuslanderReiten.Coordinates.IteratedShiftNaturality +OAI.Algebra.AuslanderReiten.Coordinates.MapExtend +OAI.Algebra.AuslanderReiten.Coordinates.MappedBiproductHom +OAI.Algebra.AuslanderReiten.Coordinates.MappedBiproductRow +OAI.Algebra.AuslanderReiten.Coordinates.NormalizedBranchValue +OAI.Algebra.AuslanderReiten.Coordinates.ShiftedBoundaryComponents +OAI.Algebra.AuslanderReiten.Coordinates.ShiftedConjugateAction +OAI.Algebra.AuslanderReiten.Coordinates.ShiftedCoordinateProducts +OAI.Algebra.AuslanderReiten.Coordinates.ShiftedInverse +OAI.Algebra.AuslanderReiten.Coordinates.ShiftedObjectCoordinates +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonHomotopy +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonNaturality +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonProjectedRow +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonScalar +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonZero +OAI.Algebra.AuslanderReiten.Coordinates.TensorComparisonZeroTransport +OAI.Algebra.AuslanderReiten.Coordinates.TensorFiniteLift +OAI.Algebra.AuslanderReiten.Coordinates.TensorFiniteTop +OAI.Algebra.AuslanderReiten.Coordinates.TensorHighLift +OAI.Algebra.AuslanderReiten.Coordinates.TensorNormalizedTop +OAI.Algebra.AuslanderReiten.Coordinates.TensorRestriction +OAI.Algebra.AuslanderReiten.Coordinates.TensorTailMap +OAI.Algebra.AuslanderReiten.Coordinates.TensorTailTop +OAI.Algebra.AuslanderReiten.Coordinates.TensorTopComparison +OAI.Algebra.AuslanderReiten.Coordinates.TensorTopCoverSquares +OAI.Algebra.AuslanderReiten.Coordinates.TensorTopNaturality +OAI.Algebra.AuslanderReiten.Coordinates.TwoTwistLinear +OAI.Algebra.AuslanderReiten.Duality.DualResolution +OAI.Algebra.AuslanderReiten.Duality.DualTensorComplex +OAI.Algebra.AuslanderReiten.Duality.DualTensorEvaluation +OAI.Algebra.AuslanderReiten.Duality.DualTensorModule +OAI.Algebra.AuslanderReiten.Duality.FiniteStableDuality +OAI.Algebra.AuslanderReiten.Duality.FiniteStableResolutionIso +OAI.Algebra.AuslanderReiten.Duality.IdealDualComparison +OAI.Algebra.AuslanderReiten.Duality.IdealDualComplex +OAI.Algebra.AuslanderReiten.Duality.IdealDualHomology +OAI.Algebra.AuslanderReiten.Duality.LinearHomologyDuality +OAI.Algebra.AuslanderReiten.Duality.ProjectiveStableDuality +OAI.Algebra.AuslanderReiten.Duality.ProjectiveStablePairing +OAI.Algebra.AuslanderReiten.Duality.ProjectiveTraceDuality +OAI.Algebra.AuslanderReiten.Duality.RightDual +OAI.Algebra.AuslanderReiten.Duality.RightDualHomology +OAI.Algebra.AuslanderReiten.Duality.SymmetricHomology +OAI.Algebra.AuslanderReiten.Duality.SymmetricPairing +OAI.Algebra.AuslanderReiten.Duality.SymmetricStableDuality +OAI.Algebra.AuslanderReiten.Evaluation.CanonicalRegularEndpoint +OAI.Algebra.AuslanderReiten.Evaluation.CanonicalRegularMap +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBaseAugmentation +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBetaHom +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBetaTransfer +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBetaValue +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBranchBeta +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBranchDetector +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteBranchTop +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteEndpointCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteEndpointInsertion +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteEvaluatedBase +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteEvaluatedConeShift +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteEvaluationCoefficient +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreeCoefficient +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreeCoordinateMap +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreeExtension +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreeInput +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreePure +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteFreeValue +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteNativeAugmentation +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteTensorFiber +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteTensorFiberMaps +OAI.Algebra.AuslanderReiten.Evaluation.ConcreteTensorFiberProjection +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedAdjacentComponents +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedBaseQuotient +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedBaseShift +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedConnectingCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCosyzygyShift +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverCanonical +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverComparison +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverInitial +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverProducts +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCoverStep +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedCubicCover +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedMiddleCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedMiddleNaturality +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedMiddleShift +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedOrdinaryFunctor +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedQuotientCubic +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedTopConnecting +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedTopCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.EvaluatedTriangleArrows +OAI.Algebra.AuslanderReiten.Evaluation.RegularCoefficientNaturality +OAI.Algebra.AuslanderReiten.Evaluation.RegularEndpointFactor +OAI.Algebra.AuslanderReiten.Evaluation.RegularEvaluatedAugmentation +OAI.Algebra.AuslanderReiten.Evaluation.RegularEvaluationCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.TensorBeta +OAI.Algebra.AuslanderReiten.Evaluation.TensorBetaEvaluation +OAI.Algebra.AuslanderReiten.Evaluation.TensorEndpointEvaluation +OAI.Algebra.AuslanderReiten.Evaluation.TensorEvaluatedTop +OAI.Algebra.AuslanderReiten.Evaluation.TensorFreeEvaluationCoordinates +OAI.Algebra.AuslanderReiten.Evaluation.TensorSourceUnit +OAI.Algebra.AuslanderReiten.Evaluation.TensorTwistEvaluation +OAI.Algebra.AuslanderReiten.Ext.AExtActions +OAI.Algebra.AuslanderReiten.Ext.AExtCentral +OAI.Algebra.AuslanderReiten.Ext.AExtCoefficientCore +OAI.Algebra.AuslanderReiten.Ext.AExtCoefficientFunctions +OAI.Algebra.AuslanderReiten.Ext.AExtCoefficients +OAI.Algebra.AuslanderReiten.Ext.AExtCubicComm +OAI.Algebra.AuslanderReiten.Ext.AExtGeneration +OAI.Algebra.AuslanderReiten.Ext.AExtIdentity +OAI.Algebra.AuslanderReiten.Ext.AExtPolynomial +OAI.Algebra.AuslanderReiten.Ext.AExtRightActions +OAI.Algebra.AuslanderReiten.Ext.AExtZero +OAI.Algebra.AuslanderReiten.Ext.ATwistExt +OAI.Algebra.AuslanderReiten.Ext.ATwistedTensorExt +OAI.Algebra.AuslanderReiten.Ext.BaseExt +OAI.Algebra.AuslanderReiten.Ext.CubicExtAction +OAI.Algebra.AuslanderReiten.Ext.CubicExtCommute +OAI.Algebra.AuslanderReiten.Ext.ExactFunctorExtIso +OAI.Algebra.AuslanderReiten.Ext.ExactFunctorExtNaturality +OAI.Algebra.AuslanderReiten.Ext.ExceptionalExt +OAI.Algebra.AuslanderReiten.Ext.ExtBridge +OAI.Algebra.AuslanderReiten.Ext.ExtCentralGeneration +OAI.Algebra.AuslanderReiten.Ext.ExtFunctorScalar +OAI.Algebra.AuslanderReiten.Ext.ExtGenerationTransfer +OAI.Algebra.AuslanderReiten.Ext.ExtIsoCongr +OAI.Algebra.AuslanderReiten.Ext.ExtIsoFunctor +OAI.Algebra.AuslanderReiten.Ext.ExtKunneth +OAI.Algebra.AuslanderReiten.Ext.ExtKunnethActions +OAI.Algebra.AuslanderReiten.Ext.ExtKunnethClass +OAI.Algebra.AuslanderReiten.Ext.ExtKunnethIdentity +OAI.Algebra.AuslanderReiten.Ext.ExtKunnethMap +OAI.Algebra.AuslanderReiten.Ext.ExtPolynomialFunctions +OAI.Algebra.AuslanderReiten.Ext.ExtPolynomialTransfer +OAI.Algebra.AuslanderReiten.Ext.ExtTensorAction +OAI.Algebra.AuslanderReiten.Ext.ExtendShortExact +OAI.Algebra.AuslanderReiten.Ext.ExternalComplexCubicNatural +OAI.Algebra.AuslanderReiten.Ext.ExternalComplexIso +OAI.Algebra.AuslanderReiten.Ext.ExternalCubicInclusion +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluatedFreeCoordinate +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluatedFreeValues +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationAugmentation +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationComparison +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationCubic +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationCubicSquare +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationDifferential +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationNaturality +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationPure +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationSquare +OAI.Algebra.AuslanderReiten.Ext.ExternalEvaluationTerms +OAI.Algebra.AuslanderReiten.Ext.ExternalFreeEvaluation +OAI.Algebra.AuslanderReiten.Ext.ExternalFreeFactorization +OAI.Algebra.AuslanderReiten.Ext.ExternalNativeBarAugmentation +OAI.Algebra.AuslanderReiten.Ext.ExternalNativeBarInclusion +OAI.Algebra.AuslanderReiten.Ext.ExternalNativeRegularAugmentation +OAI.Algebra.AuslanderReiten.Ext.ExternalRegularEvaluation +OAI.Algebra.AuslanderReiten.Ext.ExternalRegularMapPure +OAI.Algebra.AuslanderReiten.Ext.NatComparisonExt +OAI.Algebra.AuslanderReiten.Ext.NatCubicExt +OAI.Algebra.AuslanderReiten.Ext.NativeExtZero +OAI.Algebra.AuslanderReiten.Ext.SimpleCoverExt +OAI.Algebra.AuslanderReiten.Ext.TExplicitGenerator +OAI.Algebra.AuslanderReiten.Ext.TExplicitPolynomial +OAI.Algebra.AuslanderReiten.Ext.TExtPolynomial +OAI.Algebra.AuslanderReiten.Ext.TExtRecurrence +OAI.Algebra.AuslanderReiten.Ext.TTensorActions +OAI.Algebra.AuslanderReiten.Ext.TTensorGeneration +OAI.Algebra.AuslanderReiten.Ext.TTensorIdentity +OAI.Algebra.AuslanderReiten.Ext.TTensorPolynomial +OAI.Algebra.AuslanderReiten.Ext.TTensorTwist +OAI.Algebra.AuslanderReiten.Ext.TTwistExtPolynomial +OAI.Algebra.AuslanderReiten.Ext.TensorExtCoefficients +OAI.Algebra.AuslanderReiten.Fibers.BimoduleFiber +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberComponentMaps +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberComponents +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberEvaluation +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberHomCoordinates +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberHomotopy +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberProfile +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberRow +OAI.Algebra.AuslanderReiten.Fibers.ConcreteFiberTriangle +OAI.Algebra.AuslanderReiten.Fibers.ExplicitBimoduleFiber +OAI.Algebra.AuslanderReiten.Fibers.ExplicitBimoduleProjective +OAI.Algebra.AuslanderReiten.Fibers.FiberBranchConsequences +OAI.Algebra.AuslanderReiten.Fibers.FiberDiagonalGenerator +OAI.Algebra.AuslanderReiten.Fibers.FiberEvaluationMap +OAI.Algebra.AuslanderReiten.Fibers.FiberExactness +OAI.Algebra.AuslanderReiten.Fibers.FiberFullHomCoordinates +OAI.Algebra.AuslanderReiten.Fibers.FiberProductCoordinates +OAI.Algebra.AuslanderReiten.Fibers.FiberProjectionProfile +OAI.Algebra.AuslanderReiten.Fibers.FiberProjectionZero +OAI.Algebra.AuslanderReiten.Fibers.FiberSequenceCoordinates +OAI.Algebra.AuslanderReiten.Fibers.FiniteEvaluatedFiber +OAI.Algebra.AuslanderReiten.Fibers.FiniteFiberComponents +OAI.Algebra.AuslanderReiten.Fibers.FiniteFiberSides +OAI.Algebra.AuslanderReiten.Fibers.FiniteModuleFiber +OAI.Algebra.AuslanderReiten.Fibers.TensorFiberCoordinateIso +OAI.Algebra.AuslanderReiten.HomComplex.FiniteFullHomExt +OAI.Algebra.AuslanderReiten.HomComplex.FiniteFullHomZero +OAI.Algebra.AuslanderReiten.HomComplex.FullCochainProducts +OAI.Algebra.AuslanderReiten.HomComplex.FullCochainTail +OAI.Algebra.AuslanderReiten.HomComplex.FullHomAugmentedExt +OAI.Algebra.AuslanderReiten.HomComplex.FullHomComparison +OAI.Algebra.AuslanderReiten.HomComplex.FullHomComposition +OAI.Algebra.AuslanderReiten.HomComplex.FullHomCompositionLinear +OAI.Algebra.AuslanderReiten.HomComplex.FullHomCompositionSquare +OAI.Algebra.AuslanderReiten.HomComplex.FullHomDegreeProducts +OAI.Algebra.AuslanderReiten.HomComplex.FullHomDuality +OAI.Algebra.AuslanderReiten.HomComplex.FullHomExt +OAI.Algebra.AuslanderReiten.HomComplex.FullHomFunctor +OAI.Algebra.AuslanderReiten.HomComplex.FullHomHomotopyMaps +OAI.Algebra.AuslanderReiten.HomComplex.FullHomLinear +OAI.Algebra.AuslanderReiten.HomComplex.FullHomMap +OAI.Algebra.AuslanderReiten.HomComplex.FullHomMapLinear +OAI.Algebra.AuslanderReiten.HomComplex.FullHomNaturality +OAI.Algebra.AuslanderReiten.HomComplex.FullHomPairing +OAI.Algebra.AuslanderReiten.HomComplex.FullHomPlainZero +OAI.Algebra.AuslanderReiten.HomComplex.FullHomProductCoordinate +OAI.Algebra.AuslanderReiten.HomComplex.FullHomProductLinear +OAI.Algebra.AuslanderReiten.HomComplex.FullHomProductReindex +OAI.Algebra.AuslanderReiten.HomComplex.FullHomProducts +OAI.Algebra.AuslanderReiten.HomComplex.FullHomShift +OAI.Algebra.AuslanderReiten.HomComplex.FullHomShiftedHomotopy +OAI.Algebra.AuslanderReiten.HomComplex.FullHomShiftedIdentity +OAI.Algebra.AuslanderReiten.HomComplex.FullHomShiftedMaps +OAI.Algebra.AuslanderReiten.HomComplex.FullHomShiftedProducts +OAI.Algebra.AuslanderReiten.HomComplex.FullHomSourceDuality +OAI.Algebra.AuslanderReiten.HomComplex.FullHomTransport +OAI.Algebra.AuslanderReiten.HomComplex.FullHomZeroProjection +OAI.Algebra.AuslanderReiten.HomComplex.FullHomZeroRepresentative +OAI.Algebra.AuslanderReiten.HomComplex.HomCochainExt +OAI.Algebra.AuslanderReiten.HomComplex.HomCochainExtClass +OAI.Algebra.AuslanderReiten.HomComplex.HomCochainNativeClass +OAI.Algebra.AuslanderReiten.HomComplex.HomCochainNaturality +OAI.Algebra.AuslanderReiten.HomComplex.HomCochainScalar +OAI.Algebra.AuslanderReiten.HomComplex.HomKunnethClass +OAI.Algebra.AuslanderReiten.HomComplex.NativeHomExtAction +OAI.Algebra.AuslanderReiten.HomComplex.PositiveFullHomExt +OAI.Algebra.AuslanderReiten.HomComplex.PositiveFullHomProducts +OAI.Algebra.AuslanderReiten.HomComplex.TensorFullHomPositive +OAI.Algebra.AuslanderReiten.HomComplex.TensorFullHomZero +OAI.Algebra.AuslanderReiten.Homology.AEndHomScalar +OAI.Algebra.AuslanderReiten.Homology.BifunctorHomotopyEquiv +OAI.Algebra.AuslanderReiten.Homology.ChainComparisonIso +OAI.Algebra.AuslanderReiten.Homology.CochainCycleClass +OAI.Algebra.AuslanderReiten.Homology.CochainNatTensorSigns +OAI.Algebra.AuslanderReiten.Homology.CochainNullhomotopy +OAI.Algebra.AuslanderReiten.Homology.CoefficientComplexValues +OAI.Algebra.AuslanderReiten.Homology.ConcentratedNatDerived +OAI.Algebra.AuslanderReiten.Homology.DerivedHomVanishing +OAI.Algebra.AuslanderReiten.Homology.DerivedSingle +OAI.Algebra.AuslanderReiten.Homology.DimensionOneDetector +OAI.Algebra.AuslanderReiten.Homology.ExceptionalHomology +OAI.Algebra.AuslanderReiten.Homology.FullPositiveComposite +OAI.Algebra.AuslanderReiten.Homology.FullPositiveFunctorAction +OAI.Algebra.AuslanderReiten.Homology.FullPositiveModel +OAI.Algebra.AuslanderReiten.Homology.FullPositiveNaturality +OAI.Algebra.AuslanderReiten.Homology.LinearCokernelMap +OAI.Algebra.AuslanderReiten.Homology.LinearEquivActionTransfer +OAI.Algebra.AuslanderReiten.Homology.LinearHomologyCongr +OAI.Algebra.AuslanderReiten.Homology.LinearHomotopy +OAI.Algebra.AuslanderReiten.Homology.LinearRetractEquiv +OAI.Algebra.AuslanderReiten.Homology.ModuleCatLinearCoherence +OAI.Algebra.AuslanderReiten.Homology.NatComparisonFunctor +OAI.Algebra.AuslanderReiten.Homology.ProjectiveNullhomotopyAbove +OAI.Algebra.AuslanderReiten.Homology.RestrictKernelCokernel +OAI.Algebra.AuslanderReiten.Homology.RestrictionProjective +OAI.Algebra.AuslanderReiten.Homology.ShortExactConnecting +OAI.Algebra.AuslanderReiten.Homology.ShortExactConnectingProducts +OAI.Algebra.AuslanderReiten.Homology.ShortExactNaturality +OAI.Algebra.AuslanderReiten.Homology.ShortExactTriangle +OAI.Algebra.AuslanderReiten.Homology.SplitQuotient +OAI.Algebra.AuslanderReiten.Homology.TBoundaryCochain +OAI.Algebra.AuslanderReiten.Homology.TNullhomotopy +OAI.Algebra.AuslanderReiten.Homology.TTwistCompatibility +OAI.Algebra.AuslanderReiten.Homology.TTwistFactor +OAI.Algebra.AuslanderReiten.Homology.TriangleConnectingProduct +OAI.Algebra.AuslanderReiten.Homology.TriangleGradedSequence +OAI.Algebra.AuslanderReiten.Homology.TriangleHomExact +OAI.Algebra.AuslanderReiten.Homology.TriangleMiddleTransport +OAI.Algebra.AuslanderReiten.Homology.TriangleRecurrence +OAI.Algebra.AuslanderReiten.Homology.VectorCochainKunneth +OAI.Algebra.AuslanderReiten.Homology.VectorCochainKunnethCycles +OAI.Algebra.AuslanderReiten.Homology.VectorCochainKunnethLiteral +OAI.Algebra.AuslanderReiten.Homology.VectorCochainKunnethMap +OAI.Algebra.AuslanderReiten.Homology.VectorCochainKunnethNaturality +OAI.Algebra.AuslanderReiten.Homology.VectorCochainNaturality +OAI.Algebra.AuslanderReiten.Homology.VectorCochainSplitting +OAI.Algebra.AuslanderReiten.Homology.VectorComplexSplitting +OAI.Algebra.AuslanderReiten.Homology.VectorTensorKunneth +OAI.Algebra.AuslanderReiten.Main +OAI.Algebra.AuslanderReiten.Modules.ATwistFunctor +OAI.Algebra.AuslanderReiten.Modules.ATwistedCompleteAction +OAI.Algebra.AuslanderReiten.Modules.BimoduleEnveloping +OAI.Algebra.AuslanderReiten.Modules.Coinduced +OAI.Algebra.AuslanderReiten.Modules.CoinducedBimodule +OAI.Algebra.AuslanderReiten.Modules.CoinducedEmbedding +OAI.Algebra.AuslanderReiten.Modules.CoinducedModule +OAI.Algebra.AuslanderReiten.Modules.FiniteModuleEvaluation +OAI.Algebra.AuslanderReiten.Modules.FiniteModuleNaturality +OAI.Algebra.AuslanderReiten.Modules.FiniteModuleTriangle +OAI.Algebra.AuslanderReiten.Modules.InductionAdjunction +OAI.Algebra.AuslanderReiten.Modules.InductionBimodule +OAI.Algebra.AuslanderReiten.Modules.ModuleRestriction +OAI.Algebra.AuslanderReiten.Modules.SplitModules +OAI.Algebra.AuslanderReiten.Modules.SupportedPi +OAI.Algebra.AuslanderReiten.Modules.TInducedHom +OAI.Algebra.AuslanderReiten.Modules.TInductionHomology +OAI.Algebra.AuslanderReiten.Modules.TInductionTriangle +OAI.Algebra.AuslanderReiten.Modules.TrivialInduction +OAI.Algebra.AuslanderReiten.Modules.Twist +OAI.Algebra.AuslanderReiten.Modules.TwistedBimodule +OAI.Algebra.AuslanderReiten.Modules.TwistedEvaluationNaturality +OAI.Algebra.AuslanderReiten.Modules.TwistedFiniteEndpoint +OAI.Algebra.AuslanderReiten.Modules.TwistedModuleEvaluation +OAI.Algebra.AuslanderReiten.Modules.TwistedOneCochain +OAI.Algebra.AuslanderReiten.Modules.TwoActions +OAI.Algebra.AuslanderReiten.Parameters +OAI.Algebra.AuslanderReiten.Resolutions.BinaryKoszul +OAI.Algebra.AuslanderReiten.Resolutions.BinaryKoszulDual +OAI.Algebra.AuslanderReiten.Resolutions.BinaryKoszulScalar +OAI.Algebra.AuslanderReiten.Resolutions.CProjectiveResolution +OAI.Algebra.AuslanderReiten.Resolutions.ConcreteKoszulColumn +OAI.Algebra.AuslanderReiten.Resolutions.ConcreteKoszulCoordinateLaws +OAI.Algebra.AuslanderReiten.Resolutions.ConcreteKoszulCoordinates +OAI.Algebra.AuslanderReiten.Resolutions.ConcreteKoszulRow +OAI.Algebra.AuslanderReiten.Resolutions.ConcreteNativeResolution +OAI.Algebra.AuslanderReiten.Resolutions.CoverFullHomAction +OAI.Algebra.AuslanderReiten.Resolutions.CoverStepCoordinates +OAI.Algebra.AuslanderReiten.Resolutions.CoverStepFullHom +OAI.Algebra.AuslanderReiten.Resolutions.CubicCoverSquares +OAI.Algebra.AuslanderReiten.Resolutions.EvaluatedOrdinaryResolution +OAI.Algebra.AuslanderReiten.Resolutions.EvaluatedResolutionTerms +OAI.Algebra.AuslanderReiten.Resolutions.FiniteCochainResolution +OAI.Algebra.AuslanderReiten.Resolutions.FiniteCoverProducts +OAI.Algebra.AuslanderReiten.Resolutions.FiniteCoverTransport +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionAdditive +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionEvaluation +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionIso +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionLinear +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionProduct +OAI.Algebra.AuslanderReiten.Resolutions.FiniteResolutionProductInclusions +OAI.Algebra.AuslanderReiten.Resolutions.MapResolutionCochain +OAI.Algebra.AuslanderReiten.Resolutions.MapResolutionExt +OAI.Algebra.AuslanderReiten.Resolutions.MapResolutionExtComparison +OAI.Algebra.AuslanderReiten.Resolutions.MapResolutionExtConjugate +OAI.Algebra.AuslanderReiten.Resolutions.MapResolutionExtMk +OAI.Algebra.AuslanderReiten.Resolutions.NatResolutionCochain +OAI.Algebra.AuslanderReiten.Resolutions.NatResolutionCubic +OAI.Algebra.AuslanderReiten.Resolutions.ProjectiveResolutionFunctor +OAI.Algebra.AuslanderReiten.Resolutions.Resolution +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionCokernel +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionCoverExt +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionCubicConjugate +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionEndpointIso +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionExtAction +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionExtIdentity +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionExtSquare +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionExtZero +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionHomology +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionProductCompatibility +OAI.Algebra.AuslanderReiten.Resolutions.ResolutionProducts +OAI.Algebra.AuslanderReiten.Resolutions.SimpleCoverClasses +OAI.Algebra.AuslanderReiten.Resolutions.SimpleCoverCubicConjugate +OAI.Algebra.AuslanderReiten.Resolutions.TrivialInductionComplex +OAI.Algebra.AuslanderReiten.Resolutions.TrivialInductionDual +OAI.Algebra.AuslanderReiten.Resolutions.TrivialInductionQuotient +OAI.Algebra.AuslanderReiten.Stable.CanonicalCosyzygy +OAI.Algebra.AuslanderReiten.Stable.CanonicalCosyzygyShift +OAI.Algebra.AuslanderReiten.Stable.RawSourceCoordinates +OAI.Algebra.AuslanderReiten.Stable.RawSourceDegrees +OAI.Algebra.AuslanderReiten.Stable.RawSourceStable +OAI.Algebra.AuslanderReiten.Stable.SourceStableCoordinates +OAI.Algebra.AuslanderReiten.Stable.SourceStableShift +OAI.Algebra.AuslanderReiten.Stable.StableConnecting +OAI.Algebra.AuslanderReiten.Stable.StableExt +OAI.Algebra.AuslanderReiten.Stable.StableExtEquiv +OAI.Algebra.AuslanderReiten.Stable.StableExtNaturality +OAI.Algebra.AuslanderReiten.Stable.StableExtPrecomp +OAI.Algebra.AuslanderReiten.Stable.StableHom +OAI.Algebra.AuslanderReiten.Stable.StableHomEquiv +OAI.Algebra.AuslanderReiten.Stable.StableHomology +OAI.Algebra.AuslanderReiten.Stable.StableHomotopyIso +OAI.Algebra.AuslanderReiten.Stable.StableIsomorphism +OAI.Algebra.AuslanderReiten.Stable.StableProjectiveSummand +OAI.Algebra.AuslanderReiten.Stable.StableTargetHomology +OAI.Algebra.AuslanderReiten.Stable.TargetStableCoordinates +OAI.Algebra.AuslanderReiten.Stable.TensorStableEnd +OAI.Algebra.AuslanderReiten.Statement +OAI.Algebra.AuslanderReiten.StatementEquivalence +OAI.Algebra.AuslanderReiten.Tensor.BalancedFourAddExt +OAI.Algebra.AuslanderReiten.Tensor.BalancedFourExt +OAI.Algebra.AuslanderReiten.Tensor.BalancedFourLinearExt +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensor +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorAction +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorCanonicalEndpoint +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorCategory +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorCokernel +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorComparisonMaps +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorComplete +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorCompleteAction +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorCompleteInverse +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorDoubleLift +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorEquiv +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorExact +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorFiniteEvaluation +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorFirst +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorFunctor +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorFunctorExt +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorLeftExact +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorLinear +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorMap +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorMapEquiv +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorNative +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorNativeEvaluation +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorPi +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorPositiveAction +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorProjective +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorResolution +OAI.Algebra.AuslanderReiten.Tensor.BalancedTensorUnit +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedEquiv +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedExact +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedMap +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedProduct +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedProjective +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBalancedRegular +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingBimodule +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingCoefficientComplex +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingEvaluationCoefficient +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingEvaluationFunctor +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingProducts +OAI.Algebra.AuslanderReiten.Tensor.EnvelopingStableEvaluation +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedCoordinates +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedCore +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedEquiv +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedHomExt +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedNaturality +OAI.Algebra.AuslanderReiten.Tensor.ExternalBalancedShuffle +OAI.Algebra.AuslanderReiten.Tensor.ExternalEnveloping +OAI.Algebra.AuslanderReiten.Tensor.ExternalEnvelopingScalar +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorAugmentation +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorBottom +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorBottomCubic +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorBottomDifferential +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorComplex +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCoordinates +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubic +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubicChain +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubicComm +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubicDifferential +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubicExt +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorCubicProducts +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorDegreeZero +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorDifferential +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorExact +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorForget +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorFunctor +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHom +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomComplex +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomCubic +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomDifferential +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomKunneth +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomPairTransport +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorHomTransport +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorModule +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorProjective +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorRegular +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorResolution +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorScalar +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorScalarExt +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorScalarIso +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorScalarProducts +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorScalarPure +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorSemilinear +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorSingle +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorTransport +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorTwoCone +OAI.Algebra.AuslanderReiten.Tensor.ExternalTensorZeroEquiv +OAI.Algebra.AuslanderReiten.Tensor.TwistedEnvelopingEndpoint +OAI.Algebra.AuslanderReiten.Tensor.TwistedEnvelopingFunctor +OAI.Algebra.AuslanderReiten.Tensor.TwistedEnvelopingProjective +OAI.Algebra.AuslanderReiten.Tensor.TwistedTensor +OAI.Algebra.AuslanderReiten.Tensor.TwistedTensorFunctor +OAI.Algebra.AuslanderReiten.Tensor.TwistedTensorResolution +OAI.Algebra.AuslanderReiten.Triangular.ConvertedCriterion +OAI.Algebra.AuslanderReiten.Triangular.ConvertedNoncommutative +OAI.Algebra.AuslanderReiten.Triangular.ConvertedScalarExtension +OAI.Algebra.AuslanderReiten.Triangular.ConvertedStructure +OAI.Algebra.AuslanderReiten.Triangular.ConvertedTensorCriterion +OAI.Algebra.AuslanderReiten.Triangular.Triangular +OAI.Algebra.AuslanderReiten.Triangular.TriangularCategory +OAI.Algebra.AuslanderReiten.Triangular.TriangularCochain +OAI.Algebra.AuslanderReiten.Triangular.TriangularComparison +OAI.Algebra.AuslanderReiten.Triangular.TriangularComparisonTransport +OAI.Algebra.AuslanderReiten.Triangular.TriangularComplete +OAI.Algebra.AuslanderReiten.Triangular.TriangularCrossHom +OAI.Algebra.AuslanderReiten.Triangular.TriangularDualExact +OAI.Algebra.AuslanderReiten.Triangular.TriangularExact +OAI.Algebra.AuslanderReiten.Triangular.TriangularFunctor +OAI.Algebra.AuslanderReiten.Triangular.TriangularHom +OAI.Algebra.AuslanderReiten.Triangular.TriangularInduction +OAI.Algebra.AuslanderReiten.Triangular.TriangularModule +OAI.Algebra.AuslanderReiten.Triangular.TriangularProjective +OAI.Algebra.AuslanderReiten.Triangular.TriangularRadical diff --git a/tasks/auslander-reiten/solution/reference.py b/tasks/auslander-reiten/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/auslander-reiten/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/auslander-reiten/solution/solve.sh b/tasks/auslander-reiten/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..faa3a3838b99cb847008080e66aba37f312c9ef7 --- /dev/null +++ b/tasks/auslander-reiten/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of AuslanderReiten, i.e. module OAI.Algebra.AuslanderReiten.All and the +# 732 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.AuslanderReiten.All /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of AuslanderReiten" diff --git a/tasks/auslander-reiten/task.toml b/tasks/auslander-reiten/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c705b4350a3e8a0040dec3a3224cc954c482f83 --- /dev/null +++ b/tasks/auslander-reiten/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/auslander-reiten" +version = "1.0.0" +description = "Prove AuslanderReiten (openai/math family 199: Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/AuslanderReiten.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "AuslanderReiten" +family = "199" +family_title = "Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama" +subject = "Algebra" +theorems = ["OAI.ArExplicit.Statement.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.AuslanderReiten.All" +reference_modules = 732 +reference_lean_bytes = 2349871 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2615 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13814 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/auslander-reiten/tests/Challenge.lean b/tasks/auslander-reiten/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2cc548312795233ecac8b25a768f7a5d8161aec7 --- /dev/null +++ b/tasks/auslander-reiten/tests/Challenge.lean @@ -0,0 +1,77 @@ +import Mathlib + +namespace OAI + +noncomputable section +open CategoryTheory +open scoped TensorProduct +namespace ArExplicit.Statement +universe u v + +abbrev K := FractionRing (MvPolynomial (Fin 3) (ZMod 2)) + +def parameters (i : Fin 3) : K := + algebraMap (MvPolynomial (Fin 3) (ZMod 2)) K (MvPolynomial.X i) + +def TotallyAcyclicWitness (R : Type u) [Ring R] + (Z : Type u) [AddCommGroup Z] [Module R Z] : Prop := + ∃ P : ChainComplex (ModuleCat.{u} R) ℤ, + (∀ i : ℤ, Module.Finite R (P.X i) ∧ Module.Projective R (P.X i)) ∧ + (∀ i : ℤ, LinearMap.range (P.d (i+1) i).hom = LinearMap.ker (P.d i (i-1)).hom) ∧ + (∀ (Q : Type u) [AddCommGroup Q] [Module R Q] [Module.Projective R Q] + (i : ℤ) (f : P.X i →ₗ[R] Q), f.comp (P.d (i+1) i).hom = 0 → + ∃ g : P.X (i-1) →ₗ[R] Q, f = g.comp (P.d i (i-1)).hom) ∧ + Nonempty (Z ≃ₗ[R] (P.X 0 ⧸ LinearMap.range (P.d 1 0).hom)) + +def Conclusions (F R Z : Type u) [Field F] [Ring R] [Algebra F R] + [AddCommGroup Z] [Module R Z] [Module F Z] [IsScalarTower F R Z] : Prop := + FiniteDimensional F R ∧ + FiniteDimensional F Z ∧ + ¬ Module.Projective R Z ∧ + TotallyAcyclicWitness R Z ∧ + (∀ i : ℕ, 0 < i → + Subsingleton (Abelian.Ext (ModuleCat.of R Z) (ModuleCat.of R Z) i)) ∧ + (∀ i : ℕ, 0 < i → + Subsingleton (Abelian.Ext (ModuleCat.of R Z) (ModuleCat.of R R) i)) ∧ + Nonempty ((R ⧸ Ring.jacobson R) ≃ₐ[F] (Fin 8 → F)) ∧ + (Ring.jacobson R)^4 ≠ ⊥ + +structure System where + algebraCarrier : Type + [ring : Ring algebraCarrier] + [scalarAlgebra : Algebra K algebraCarrier] + moduleCarrier : Type + [additiveGroup : AddCommGroup moduleCarrier] + [action : Module algebraCarrier moduleCarrier] + [scalarAction : Module K moduleCarrier] + [actionTower : IsScalarTower K algebraCarrier moduleCarrier] + +attribute [instance] System.ring System.scalarAlgebra System.additiveGroup + System.action System.scalarAction System.actionTower + +def FullStatement : Prop := + AlgebraicIndependent (ZMod 2) parameters ∧ + ∃ s : System, + Conclusions K s.algebraCarrier s.moduleCarrier ∧ + ∀ (E : Type v) [Field E] [Algebra K E], + ∃ action : Module (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier), + letI := action + ∃ tower : IsScalarTower E (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier), + letI := tower + (∀ (a b : E) (r : s.algebraCarrier) (z : s.moduleCarrier), + (a ⊗ₜ[K] r) • (b ⊗ₜ[K] z) = (a*b) ⊗ₜ[K] (r • z)) ∧ + Conclusions E (E ⊗[K] s.algebraCarrier) (E ⊗[K] s.moduleCarrier) + +end ArExplicit.Statement + +namespace ArExplicit.Statement +universe v + +theorem main : FullStatement.{v} := by + sorry + +end ArExplicit.Statement + +end + +end OAI diff --git a/tasks/auslander-reiten/tests/grade.py b/tasks/auslander-reiten/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/auslander-reiten/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/auslander-reiten/tests/task.json b/tasks/auslander-reiten/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..87eae058babddc300e6dd8031b531b7a8b380b24 --- /dev/null +++ b/tasks/auslander-reiten/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "AuslanderReiten", + "comparator": { + "theorem_names": [ + "OAI.ArExplicit.Statement.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12914 +} \ No newline at end of file diff --git a/tasks/auslander-reiten/tests/test.sh b/tasks/auslander-reiten/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/auslander-reiten/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/backward-intertwiners/environment/Dockerfile b/tasks/backward-intertwiners/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/backward-intertwiners/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/backward-intertwiners/environment/fetch_mathlib.sh b/tasks/backward-intertwiners/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/backward-intertwiners/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/backward-intertwiners/environment/lake-manifest.json b/tasks/backward-intertwiners/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/backward-intertwiners/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/backward-intertwiners/environment/lakefile.lean b/tasks/backward-intertwiners/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/backward-intertwiners/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/backward-intertwiners/environment/lean_setup.sh b/tasks/backward-intertwiners/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/backward-intertwiners/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/backward-intertwiners/environment/pack_submission.py b/tasks/backward-intertwiners/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/backward-intertwiners/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/backward-intertwiners/instruction.md b/tasks/backward-intertwiners/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2219e4c420fa69e7a202602e1baf95d6254d2291 --- /dev/null +++ b/tasks/backward-intertwiners/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `BackwardIntertwiners` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `BackwardIntertwiners`, also at `/opt/openai-math/challenges/BackwardIntertwiners.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Hyperinvariant233 +open Filter +open scoped Topology +universe u +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def commutant (T : H →L[ℂ] H) : Subalgebra ℂ (H →L[ℂ] H) := + Subalgebra.centralizer ℂ ({T} : Set (H →L[ℂ] H)) + +def TransitiveCommutant (T : H →L[ℂ] H) : Prop := + ∀ K : Submodule ℂ H, IsClosed (K : Set H) → + (∀ A : H →L[ℂ] H, A * T = T * A → ∀ x ∈ K, A x ∈ K) → + K = ⊥ ∨ K = ⊤ + +@[instance_reducible] +def strongOperatorTopology : TopologicalSpace (H →L[ℂ] H) := + TopologicalSpace.induced (fun A : H →L[ℂ] H => (fun x : H => A x)) inferInstance + +def FullClaim : Prop := + ∃ T : H →L[ℂ] H, T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + TransitiveCommutant T ∧ commutant T ≠ ⊤ ∧ + @IsClosed (H →L[ℂ] H) strongOperatorTopology (commutant T : Set (H →L[ℂ] H)) + +end Hyperinvariant233 + +namespace BackwardIntertwiners +open Filter Topology MeasureTheory Set +noncomputable section +open scoped ENNReal + +theorem direct_algebra_corollary (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] [TopologicalSpace.SeparableSpace H] (hInf : ¬FiniteDimensional ℂ H) : + Hyperinvariant233.FullClaim (H:=H) := by + sorry + +end +end BackwardIntertwiners + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BackwardIntertwiners.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BackwardIntertwiners.direct_algebra_corollary` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/backward-intertwiners/solution/closure.txt b/tasks/backward-intertwiners/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e64a2b098fd045d95765953db7e36717aa847e41 --- /dev/null +++ b/tasks/backward-intertwiners/solution/closure.txt @@ -0,0 +1,23 @@ +OAI.Analysis.BackwardIntertwiners.AlgebraCorollary +OAI.Analysis.BackwardIntertwiners.AtomicAlgebras +OAI.Analysis.BackwardIntertwiners.BackwardWeights +OAI.Analysis.BackwardIntertwiners.CoefficientSupport +OAI.Analysis.BackwardIntertwiners.ConvexEnvelope +OAI.Analysis.BackwardIntertwiners.ConvolutionBounds +OAI.Analysis.BackwardIntertwiners.DiagonalSymbols +OAI.Analysis.BackwardIntertwiners.ErgodicTransitivity +OAI.Analysis.BackwardIntertwiners.ExplicitWeights +OAI.Analysis.BackwardIntertwiners.FiberMaps +OAI.Analysis.BackwardIntertwiners.FiberTails +OAI.Analysis.BackwardIntertwiners.GlobalOperators +OAI.Analysis.BackwardIntertwiners.HaarBase +OAI.Analysis.BackwardIntertwiners.HilbertClassification +OAI.Analysis.BackwardIntertwiners.ModelProperties +OAI.Analysis.BackwardIntertwiners.OperatorTransport +OAI.Analysis.BackwardIntertwiners.OrdinaryStructure +OAI.Analysis.BackwardIntertwiners.PolarDiagonals +OAI.Analysis.BackwardIntertwiners.PolarFactors +OAI.Analysis.BackwardIntertwiners.ProductSymbols +OAI.Analysis.BackwardIntertwiners.SpectralProjections +OAI.Analysis.BackwardIntertwiners.StrongClosure +OAI.Analysis.BackwardIntertwiners.WeightSeparation diff --git a/tasks/backward-intertwiners/solution/reference.py b/tasks/backward-intertwiners/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/backward-intertwiners/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/backward-intertwiners/solution/solve.sh b/tasks/backward-intertwiners/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8c0770b956b52c01b7810441b5271cbdea96a26f --- /dev/null +++ b/tasks/backward-intertwiners/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BackwardIntertwiners, i.e. module OAI.Analysis.BackwardIntertwiners.AlgebraCorollary and the +# 23 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BackwardIntertwiners.AlgebraCorollary /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BackwardIntertwiners" diff --git a/tasks/backward-intertwiners/task.toml b/tasks/backward-intertwiners/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f62e01de2f250bccd5c31bf54e192eb199f8b5b7 --- /dev/null +++ b/tasks/backward-intertwiners/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/backward-intertwiners" +version = "1.0.0" +description = "Prove BackwardIntertwiners (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BackwardIntertwiners.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BackwardIntertwiners" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.BackwardIntertwiners.direct_algebra_corollary"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BackwardIntertwiners.AlgebraCorollary" +reference_modules = 23 +reference_lean_bytes = 262844 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 823 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11936 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/backward-intertwiners/tests/Challenge.lean b/tasks/backward-intertwiners/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5da4aafc87bfc798ef4033c2f0ff1da295b898c9 --- /dev/null +++ b/tasks/backward-intertwiners/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +namespace Hyperinvariant233 +open Filter +open scoped Topology +universe u +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def commutant (T : H →L[ℂ] H) : Subalgebra ℂ (H →L[ℂ] H) := + Subalgebra.centralizer ℂ ({T} : Set (H →L[ℂ] H)) + +def TransitiveCommutant (T : H →L[ℂ] H) : Prop := + ∀ K : Submodule ℂ H, IsClosed (K : Set H) → + (∀ A : H →L[ℂ] H, A * T = T * A → ∀ x ∈ K, A x ∈ K) → + K = ⊥ ∨ K = ⊤ + +@[instance_reducible] +def strongOperatorTopology : TopologicalSpace (H →L[ℂ] H) := + TopologicalSpace.induced (fun A : H →L[ℂ] H => (fun x : H => A x)) inferInstance + +def FullClaim : Prop := + ∃ T : H →L[ℂ] H, T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + TransitiveCommutant T ∧ commutant T ≠ ⊤ ∧ + @IsClosed (H →L[ℂ] H) strongOperatorTopology (commutant T : Set (H →L[ℂ] H)) + +end Hyperinvariant233 + +namespace BackwardIntertwiners +open Filter Topology MeasureTheory Set +noncomputable section +open scoped ENNReal + +theorem direct_algebra_corollary (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] [TopologicalSpace.SeparableSpace H] (hInf : ¬FiniteDimensional ℂ H) : + Hyperinvariant233.FullClaim (H:=H) := by + sorry + +end +end BackwardIntertwiners + +end OAI diff --git a/tasks/backward-intertwiners/tests/grade.py b/tasks/backward-intertwiners/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/backward-intertwiners/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/backward-intertwiners/tests/task.json b/tasks/backward-intertwiners/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e0a90f4b93969746ffb64c1cfc7c362f7e4e9e19 --- /dev/null +++ b/tasks/backward-intertwiners/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BackwardIntertwiners", + "comparator": { + "theorem_names": [ + "OAI.BackwardIntertwiners.direct_algebra_corollary" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11036 +} \ No newline at end of file diff --git a/tasks/backward-intertwiners/tests/test.sh b/tasks/backward-intertwiners/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/backward-intertwiners/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/balanced-box-routing/environment/Dockerfile b/tasks/balanced-box-routing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/balanced-box-routing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/balanced-box-routing/environment/fetch_mathlib.sh b/tasks/balanced-box-routing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/balanced-box-routing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/balanced-box-routing/environment/lake-manifest.json b/tasks/balanced-box-routing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/balanced-box-routing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/balanced-box-routing/environment/lakefile.lean b/tasks/balanced-box-routing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/balanced-box-routing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/balanced-box-routing/environment/lean_setup.sh b/tasks/balanced-box-routing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/balanced-box-routing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/balanced-box-routing/environment/pack_submission.py b/tasks/balanced-box-routing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/balanced-box-routing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/balanced-box-routing/instruction.md b/tasks/balanced-box-routing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0ee7ad9fd75214fd28a604fbe6bcbe428c3d235 --- /dev/null +++ b/tasks/balanced-box-routing/instruction.md @@ -0,0 +1,147 @@ +# openai/math challenge `BalancedBoxRouting` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `BalancedBoxRouting`, also at `/opt/openai-math/challenges/BalancedBoxRouting.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators ContDiff + +namespace BoxTransport.Routing + +abbrev Space := Fin 3 → ℝ +abbrev RationalSpace := Fin 3 → ℚ +abbrev SpaceTime := ℝ × Space +abbrev RationalSpaceTime := ℚ × RationalSpace +abbrev Field := SpaceTime → Space + +abbrev Axis := Option (Fin 3) + +def coordinateVector (j : Fin 3) : Space := Pi.single j 1 + +def coordinateDirection : Axis → SpaceTime + | none => (1, 0) + | some j => (0, coordinateVector j) + +def realPoint (q : RationalSpace) : Space := fun j => (q j : ℝ) + +def realSpaceTime (q : RationalSpaceTime) : SpaceTime := (q.1, realPoint q.2) + +def realBox (c r : Space) : Set Space := + {x | ∀ j, |x j - c j| ≤ r j} + +def solidBox (a h : RationalSpace) : Set Space := + realBox (realPoint a) (realPoint h) + +def prescribedAffine (a b h k : RationalSpace) (x : Space) : Space := + fun j => (b j : ℝ) + ((k j / h j : ℚ) : ℝ) * (x j - (a j : ℝ)) + +noncomputable def mixedDerivative : List Axis → Field → Field + | [], U => U + | j :: js, U => fun p => fderiv ℝ (mixedDerivative js U) p (coordinateDirection j) + +abbrev RationalCode := ℕ × ℕ × ℕ + +def rationalValue (q : RationalCode) : ℚ := ((q.1 : ℚ) - q.2.1) / (q.2.2 + 1) + +abbrev RationalPointCode := RationalCode × RationalCode × RationalCode × RationalCode + +def codeSpaceTime (q : RationalPointCode) : SpaceTime := + ((rationalValue q.1 : ℝ), ![(rationalValue q.2.1 : ℝ), + (rationalValue q.2.2.1 : ℝ), (rationalValue q.2.2.2 : ℝ)]) + +abbrev EvaluationRequest := List Axis × RationalPointCode × ℕ × Fin 3 + +def Effective (U : Field) : Prop := + ∃ eval : EvaluationRequest → RationalCode, + ∃ modulus : List Axis × ℕ → ℕ, + ∃ bound : List Axis → ℕ, + Computable eval ∧ Computable modulus ∧ Computable bound ∧ + (∀ (ds : List Axis) (q : RationalPointCode) (n : ℕ) (p : SpaceTime), + ‖p - codeSpaceTime q‖ ≤ ((modulus (ds, n) : ℝ) + 1)⁻¹ → + ∀ j : Fin 3, + |mixedDerivative ds U p j - (rationalValue (eval (ds, q, n, j)) : ℝ)| ≤ + ((n : ℝ) + 1)⁻¹) ∧ + (∀ (ds : List Axis) (p : SpaceTime) (j : Fin 3), + |mixedDerivative ds U p j| ≤ (bound ds : ℝ)) + +noncomputable def spatialDivergence (U : Field) (t : ℝ) (x : Space) : ℝ := + ∑ j : Fin 3, (fderiv ℝ (fun y => U (t, y)) x (coordinateVector j)) j + +def AdmissibleField (U : Field) : Prop := + ContDiff ℝ ∞ U ∧ HasCompactSupport U ∧ Effective U ∧ + (∀ t x, spatialDivergence U t x = 0) ∧ + (∀ (t : ℝ) (x : Space), t ∉ Set.Icc (1 / 4 : ℝ) (3 / 4 : ℝ) → U (t, x) = 0) + +def IsGlobalFlow (U : Field) (Φ : ℝ → Space → Space) : Prop := + (∀ x, Φ 0 x = x) ∧ + (∀ t x, HasDerivAt (fun s => Φ s x) (U (t, Φ t x)) t) ∧ + (∀ (x : Space) (γ : ℝ → Space), γ 0 = x → + (∀ t, HasDerivAt γ (U (t, γ t)) t) → ∀ t, γ t = Φ t x) + +def Delivers {n : ℕ} (a b h k : Fin n → RationalSpace) + (Φ : ℝ → Space → Space) : Prop := + ∀ i, ∃ O : Set Space, IsOpen O ∧ solidBox (a i) (h i) ⊆ O ∧ + ∀ x ∈ O, Φ 1 x = prescribedAffine (a i) (b i) (h i) (k i) x + +theorem balanced_box_routing + (n : ℕ) (a b h k : Fin n → RationalSpace) + (hh : ∀ i j, 0 < h i j) (hk : ∀ i j, 0 < k i j) + (ha : Pairwise fun i j => Disjoint (solidBox (a i) (h i)) (solidBox (a j) (h j))) + (hb : Pairwise fun i j => Disjoint (solidBox (b i) (k i)) (solidBox (b j) (k j))) + (hvol : ∀ i, ∏ j : Fin 3, k i j / h i j = 1) : + ∃ U : Field, ∃ Φ : ℝ → Space → Space, + AdmissibleField U ∧ IsGlobalFlow U Φ ∧ Delivers a b h k Φ := by + sorry + +end BoxTransport.Routing + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BalancedBoxRouting.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoxTransport.Routing.balanced_box_routing` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/balanced-box-routing/solution/closure.txt b/tasks/balanced-box-routing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1ff569f9117204064b4da167c69b71ace2180d53 --- /dev/null +++ b/tasks/balanced-box-routing/solution/closure.txt @@ -0,0 +1,7 @@ +OAI.Analysis.BoxTransport.Computation +OAI.Analysis.BoxTransport.Definitions +OAI.Analysis.BoxTransport.Expressions +OAI.Analysis.BoxTransport.Flow +OAI.Analysis.BoxTransport.Geometry +OAI.Analysis.BoxTransport.Motion +OAI.Analysis.BoxTransport.Routing diff --git a/tasks/balanced-box-routing/solution/reference.py b/tasks/balanced-box-routing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/balanced-box-routing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/balanced-box-routing/solution/solve.sh b/tasks/balanced-box-routing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e85b375338f1a24f4a9ef085ca1db37cb6b01366 --- /dev/null +++ b/tasks/balanced-box-routing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BalancedBoxRouting, i.e. module OAI.Analysis.BoxTransport.Routing and the +# 7 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BoxTransport.Routing /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BalancedBoxRouting" diff --git a/tasks/balanced-box-routing/task.toml b/tasks/balanced-box-routing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d45536988c10a57179803f38edaf6d89d3bd7fec --- /dev/null +++ b/tasks/balanced-box-routing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/balanced-box-routing" +version = "1.0.0" +description = "Prove BalancedBoxRouting (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BalancedBoxRouting.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BalancedBoxRouting" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.BoxTransport.Routing.balanced_box_routing"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BoxTransport.Routing" +reference_modules = 7 +reference_lean_bytes = 164970 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 299 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11848 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/balanced-box-routing/tests/Challenge.lean b/tasks/balanced-box-routing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..879b8a007271b04bdff18b4a16a73d2cf016b99a --- /dev/null +++ b/tasks/balanced-box-routing/tests/Challenge.lean @@ -0,0 +1,96 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators ContDiff + +namespace BoxTransport.Routing + +abbrev Space := Fin 3 → ℝ +abbrev RationalSpace := Fin 3 → ℚ +abbrev SpaceTime := ℝ × Space +abbrev RationalSpaceTime := ℚ × RationalSpace +abbrev Field := SpaceTime → Space + +abbrev Axis := Option (Fin 3) + +def coordinateVector (j : Fin 3) : Space := Pi.single j 1 + +def coordinateDirection : Axis → SpaceTime + | none => (1, 0) + | some j => (0, coordinateVector j) + +def realPoint (q : RationalSpace) : Space := fun j => (q j : ℝ) + +def realSpaceTime (q : RationalSpaceTime) : SpaceTime := (q.1, realPoint q.2) + +def realBox (c r : Space) : Set Space := + {x | ∀ j, |x j - c j| ≤ r j} + +def solidBox (a h : RationalSpace) : Set Space := + realBox (realPoint a) (realPoint h) + +def prescribedAffine (a b h k : RationalSpace) (x : Space) : Space := + fun j => (b j : ℝ) + ((k j / h j : ℚ) : ℝ) * (x j - (a j : ℝ)) + +noncomputable def mixedDerivative : List Axis → Field → Field + | [], U => U + | j :: js, U => fun p => fderiv ℝ (mixedDerivative js U) p (coordinateDirection j) + +abbrev RationalCode := ℕ × ℕ × ℕ + +def rationalValue (q : RationalCode) : ℚ := ((q.1 : ℚ) - q.2.1) / (q.2.2 + 1) + +abbrev RationalPointCode := RationalCode × RationalCode × RationalCode × RationalCode + +def codeSpaceTime (q : RationalPointCode) : SpaceTime := + ((rationalValue q.1 : ℝ), ![(rationalValue q.2.1 : ℝ), + (rationalValue q.2.2.1 : ℝ), (rationalValue q.2.2.2 : ℝ)]) + +abbrev EvaluationRequest := List Axis × RationalPointCode × ℕ × Fin 3 + +def Effective (U : Field) : Prop := + ∃ eval : EvaluationRequest → RationalCode, + ∃ modulus : List Axis × ℕ → ℕ, + ∃ bound : List Axis → ℕ, + Computable eval ∧ Computable modulus ∧ Computable bound ∧ + (∀ (ds : List Axis) (q : RationalPointCode) (n : ℕ) (p : SpaceTime), + ‖p - codeSpaceTime q‖ ≤ ((modulus (ds, n) : ℝ) + 1)⁻¹ → + ∀ j : Fin 3, + |mixedDerivative ds U p j - (rationalValue (eval (ds, q, n, j)) : ℝ)| ≤ + ((n : ℝ) + 1)⁻¹) ∧ + (∀ (ds : List Axis) (p : SpaceTime) (j : Fin 3), + |mixedDerivative ds U p j| ≤ (bound ds : ℝ)) + +noncomputable def spatialDivergence (U : Field) (t : ℝ) (x : Space) : ℝ := + ∑ j : Fin 3, (fderiv ℝ (fun y => U (t, y)) x (coordinateVector j)) j + +def AdmissibleField (U : Field) : Prop := + ContDiff ℝ ∞ U ∧ HasCompactSupport U ∧ Effective U ∧ + (∀ t x, spatialDivergence U t x = 0) ∧ + (∀ (t : ℝ) (x : Space), t ∉ Set.Icc (1 / 4 : ℝ) (3 / 4 : ℝ) → U (t, x) = 0) + +def IsGlobalFlow (U : Field) (Φ : ℝ → Space → Space) : Prop := + (∀ x, Φ 0 x = x) ∧ + (∀ t x, HasDerivAt (fun s => Φ s x) (U (t, Φ t x)) t) ∧ + (∀ (x : Space) (γ : ℝ → Space), γ 0 = x → + (∀ t, HasDerivAt γ (U (t, γ t)) t) → ∀ t, γ t = Φ t x) + +def Delivers {n : ℕ} (a b h k : Fin n → RationalSpace) + (Φ : ℝ → Space → Space) : Prop := + ∀ i, ∃ O : Set Space, IsOpen O ∧ solidBox (a i) (h i) ⊆ O ∧ + ∀ x ∈ O, Φ 1 x = prescribedAffine (a i) (b i) (h i) (k i) x + +theorem balanced_box_routing + (n : ℕ) (a b h k : Fin n → RationalSpace) + (hh : ∀ i j, 0 < h i j) (hk : ∀ i j, 0 < k i j) + (ha : Pairwise fun i j => Disjoint (solidBox (a i) (h i)) (solidBox (a j) (h j))) + (hb : Pairwise fun i j => Disjoint (solidBox (b i) (k i)) (solidBox (b j) (k j))) + (hvol : ∀ i, ∏ j : Fin 3, k i j / h i j = 1) : + ∃ U : Field, ∃ Φ : ℝ → Space → Space, + AdmissibleField U ∧ IsGlobalFlow U Φ ∧ Delivers a b h k Φ := by + sorry + +end BoxTransport.Routing + +end OAI diff --git a/tasks/balanced-box-routing/tests/grade.py b/tasks/balanced-box-routing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/balanced-box-routing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/balanced-box-routing/tests/task.json b/tasks/balanced-box-routing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..90c9e30bab98d707ec0dac7e1572cb83bc0dad89 --- /dev/null +++ b/tasks/balanced-box-routing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BalancedBoxRouting", + "comparator": { + "theorem_names": [ + "OAI.BoxTransport.Routing.balanced_box_routing" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10948 +} \ No newline at end of file diff --git a/tasks/balanced-box-routing/tests/test.sh b/tasks/balanced-box-routing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/balanced-box-routing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/balanced-ryser/environment/Dockerfile b/tasks/balanced-ryser/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/balanced-ryser/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/balanced-ryser/environment/fetch_mathlib.sh b/tasks/balanced-ryser/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/balanced-ryser/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/balanced-ryser/environment/lake-manifest.json b/tasks/balanced-ryser/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/balanced-ryser/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/balanced-ryser/environment/lakefile.lean b/tasks/balanced-ryser/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/balanced-ryser/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/balanced-ryser/environment/lean_setup.sh b/tasks/balanced-ryser/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/balanced-ryser/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/balanced-ryser/environment/pack_submission.py b/tasks/balanced-ryser/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/balanced-ryser/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/balanced-ryser/instruction.md b/tasks/balanced-ryser/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba137235e1b274a4f69b6d22a847f83647997697 --- /dev/null +++ b/tasks/balanced-ryser/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `BalancedRyser` (family 162) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 162 of the release, *Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures* +(Combinatorics). The family as a whole: Disproves Ryser's covering conjecture by constructing intersecting $(q+1)$-partite, $(q+1)$-uniform hypergraphs with covering number $q+1$, rather than the predicted bound $q$, for every sufficiently large prime $q$. A separate construction over extension fields also disproves Gyarfas's monochromatic tree-cover conjecture. + +The challenge is `BalancedRyser`, also at `/opt/openai-math/challenges/BalancedRyser.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Balanced +open scoped _root_.Balanced + +structure PartiteHypergraph (r n : ℕ) where + edges : Finset (Fin r → Fin n) + +namespace PartiteHypergraph + +variable {r n : ℕ} + +abbrev Vertex (r n : ℕ) := Fin r × Fin n + +def Covers (H : PartiteHypergraph r n) (C : Finset (Vertex r n)) : Prop := + ∀ e ∈ H.edges, ∃ i, (i, e i) ∈ C + +def Intersecting (H : PartiteHypergraph r n) : Prop := + H.edges.Nonempty ∧ ∀ e ∈ H.edges, ∀ f ∈ H.edges, ∃ i, e i = f i + +def Nonisolated (H : PartiteHypergraph r n) : Prop := + ∀ i v, ∃ e ∈ H.edges, e i = v + +def HasCoverNumber (H : PartiteHypergraph r n) (k : ℕ) : Prop := + (∃ C : Finset (Vertex r n), H.Covers C ∧ C.card = k) ∧ + ∀ C : Finset (Vertex r n), H.Covers C → k ≤ C.card + +end PartiteHypergraph + +def BalancedCounterexample (q : ℕ) : Prop := + ∃ H : PartiteHypergraph (q + 1) (q + 1), + H.Intersecting ∧ H.Nonisolated ∧ H.HasCoverNumber (q + 1) + +def MainResult : Prop := + ∃ q₀ : ℕ, ∀ q : ℕ, q₀ ≤ q → q.Prime → BalancedCounterexample q + +theorem main_result : MainResult := by + sorry + +end Balanced + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BalancedRyser.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Balanced.main_result` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/balanced-ryser/solution/closure.txt b/tasks/balanced-ryser/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..547a24828e950cc95824802e39fe09c09dc6abc2 --- /dev/null +++ b/tasks/balanced-ryser/solution/closure.txt @@ -0,0 +1,698 @@ +OAI.Combinatorics.BalancedRyser.Candidates.CandidateAbundance +OAI.Combinatorics.BalancedRyser.Candidates.CandidateAbundanceAssembly +OAI.Combinatorics.BalancedRyser.Candidates.CandidateAsymptotics +OAI.Combinatorics.BalancedRyser.Candidates.CandidateBasics +OAI.Combinatorics.BalancedRyser.Candidates.CandidateConditionalMean +OAI.Combinatorics.BalancedRyser.Candidates.CandidateConstituentMoments +OAI.Combinatorics.BalancedRyser.Candidates.CandidateConstituentTail +OAI.Combinatorics.BalancedRyser.Candidates.CandidateConstituentTarget +OAI.Combinatorics.BalancedRyser.Candidates.CandidateConstituentTargets +OAI.Combinatorics.BalancedRyser.Candidates.CandidateCountAssembly +OAI.Combinatorics.BalancedRyser.Candidates.CandidateDistinctLaw +OAI.Combinatorics.BalancedRyser.Candidates.CandidateExposedWitness +OAI.Combinatorics.BalancedRyser.Candidates.CandidateExposure +OAI.Combinatorics.BalancedRyser.Candidates.CandidateExternalTransport +OAI.Combinatorics.BalancedRyser.Candidates.CandidateExternalTransport2 +OAI.Combinatorics.BalancedRyser.Candidates.CandidateFirstMoment +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGeneratorPairFamily +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGeneratorPairModel +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGeneratorPairMoments +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGeneratorPairTail +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGeometricUniform +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGlobalLineMean +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGlobalLineModel +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGlobalLineTail +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGlobalLineTotals +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGraphEndpoint +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGraphProbabilityReduction +OAI.Combinatorics.BalancedRyser.Candidates.CandidateGraphReduction +OAI.Combinatorics.BalancedRyser.Candidates.CandidateHighMoments +OAI.Combinatorics.BalancedRyser.Candidates.CandidateLabelBridge +OAI.Combinatorics.BalancedRyser.Candidates.CandidateLineGate +OAI.Combinatorics.BalancedRyser.Candidates.CandidateLineHitFamily +OAI.Combinatorics.BalancedRyser.Candidates.CandidateMixedExternal +OAI.Combinatorics.BalancedRyser.Candidates.CandidateMultiplicity +OAI.Combinatorics.BalancedRyser.Candidates.CandidateOccupancyBridge +OAI.Combinatorics.BalancedRyser.Candidates.CandidateOldExternal +OAI.Combinatorics.BalancedRyser.Candidates.CandidateOldExternalOverlap +OAI.Combinatorics.BalancedRyser.Candidates.CandidateOldOppositeOverlap +OAI.Combinatorics.BalancedRyser.Candidates.CandidateOppositeTransport +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePairCounts +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePairFibers +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePairMoments +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePairPatternModel +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePointConsumer +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePointFamily +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePrescribedLine +OAI.Combinatorics.BalancedRyser.Candidates.CandidatePrescriptionTransport +OAI.Combinatorics.BalancedRyser.Candidates.CandidateProbabilityAssembly +OAI.Combinatorics.BalancedRyser.Candidates.CandidateRetention +OAI.Combinatorics.BalancedRyser.Candidates.CandidateRetentionBridge +OAI.Combinatorics.BalancedRyser.Candidates.CandidateRetentionTransport +OAI.Combinatorics.BalancedRyser.Candidates.CandidateRootCount +OAI.Combinatorics.BalancedRyser.Candidates.CandidateRootFibers +OAI.Combinatorics.BalancedRyser.Candidates.CandidateSecondary +OAI.Combinatorics.BalancedRyser.Candidates.CandidateSelectionBridge +OAI.Combinatorics.BalancedRyser.Candidates.CandidateSuccessfulAssembly +OAI.Combinatorics.BalancedRyser.Candidates.CandidateTwoLineFamily +OAI.Combinatorics.BalancedRyser.Candidates.CandidateTwoLineMoments +OAI.Combinatorics.BalancedRyser.Candidates.CandidateUniform +OAI.Combinatorics.BalancedRyser.Candidates.CandidateValidityAssembly +OAI.Combinatorics.BalancedRyser.Candidates.CandidateValidityWitness +OAI.Combinatorics.BalancedRyser.Candidates.CandidateWitnessProbability +OAI.Combinatorics.BalancedRyser.Candidates.Candidates +OAI.Combinatorics.BalancedRyser.Candidates.ConstituentMultiplicity +OAI.Combinatorics.BalancedRyser.Candidates.ConstituentOffsets +OAI.Combinatorics.BalancedRyser.Candidates.DeletedConstituentForcing +OAI.Combinatorics.BalancedRyser.Candidates.ExposedExternalFresh +OAI.Combinatorics.BalancedRyser.Candidates.ExposedExternalIndependent +OAI.Combinatorics.BalancedRyser.Candidates.ExposedExternalSum +OAI.Combinatorics.BalancedRyser.Candidates.ExposedOppositeSum +OAI.Combinatorics.BalancedRyser.Candidates.ExternalFreshGeneratorBound +OAI.Combinatorics.BalancedRyser.Candidates.ExternalModelIndependent +OAI.Combinatorics.BalancedRyser.Candidates.ExternalWitnessModel +OAI.Combinatorics.BalancedRyser.Candidates.ExternalWitnessModel2 +OAI.Combinatorics.BalancedRyser.Candidates.ExternalWitnessMoments +OAI.Combinatorics.BalancedRyser.Candidates.ExternalWitnessOldBridge +OAI.Combinatorics.BalancedRyser.Candidates.ExternalWitnessTail +OAI.Combinatorics.BalancedRyser.Candidates.FreshExternalCount +OAI.Combinatorics.BalancedRyser.Candidates.FreshExternalCountBound +OAI.Combinatorics.BalancedRyser.Candidates.FreshExternalCounting +OAI.Combinatorics.BalancedRyser.Candidates.FreshExternalReview +OAI.Combinatorics.BalancedRyser.Candidates.FreshExternalWitness +OAI.Combinatorics.BalancedRyser.Candidates.MixedExternalAssembly +OAI.Combinatorics.BalancedRyser.Candidates.OppositeAssembly +OAI.Combinatorics.BalancedRyser.Candidates.OppositeCases +OAI.Combinatorics.BalancedRyser.Candidates.OppositeFreshConditional +OAI.Combinatorics.BalancedRyser.Candidates.OppositeFreshMean +OAI.Combinatorics.BalancedRyser.Candidates.OppositeTail +OAI.Combinatorics.BalancedRyser.Candidates.SelectedCandidateFixedLaw +OAI.Combinatorics.BalancedRyser.Candidates.SelectionCandidateLaw +OAI.Combinatorics.BalancedRyser.Construction.BlockPartitions +OAI.Combinatorics.BalancedRyser.Construction.ConfigurationHypergraph +OAI.Combinatorics.BalancedRyser.Construction.ConfigurationHypergraphSemantics +OAI.Combinatorics.BalancedRyser.Construction.ConfigurationRealization +OAI.Combinatorics.BalancedRyser.Construction.ConfigurationRealizationBridge +OAI.Combinatorics.BalancedRyser.Construction.Construction +OAI.Combinatorics.BalancedRyser.Construction.ConstructionBlockCardinality +OAI.Combinatorics.BalancedRyser.Construction.ConstructionPartners +OAI.Combinatorics.BalancedRyser.Construction.ConstructionRepresentationLemmas +OAI.Combinatorics.BalancedRyser.Construction.ConstructionStructure +OAI.Combinatorics.BalancedRyser.Construction.CoverObstruction +OAI.Combinatorics.BalancedRyser.Construction.DeterministicReduction +OAI.Combinatorics.BalancedRyser.Construction.DeterministicReductionReview +OAI.Combinatorics.BalancedRyser.Construction.ExternalWitnessPartition +OAI.Combinatorics.BalancedRyser.Construction.Hypergraph +OAI.Combinatorics.BalancedRyser.Construction.HypergraphSemantics +OAI.Combinatorics.BalancedRyser.Construction.LocalCoverObstruction +OAI.Combinatorics.BalancedRyser.Construction.ParallelCoverObstruction +OAI.Combinatorics.BalancedRyser.Construction.PartitionEncoding +OAI.Combinatorics.BalancedRyser.Construction.PartitionHypergraph +OAI.Combinatorics.BalancedRyser.Construction.RootChildPartition +OAI.Combinatorics.BalancedRyser.Construction.TwoSplitCoverObstruction +OAI.Combinatorics.BalancedRyser.Construction.ValidChoice +OAI.Combinatorics.BalancedRyser.Deletion.ConfigurationDeletion +OAI.Combinatorics.BalancedRyser.Deletion.Deletion +OAI.Combinatorics.BalancedRyser.Deletion.DeletionAssignments +OAI.Combinatorics.BalancedRyser.Deletion.DeletionAsymptotics +OAI.Combinatorics.BalancedRyser.Deletion.DeletionConditionalAssembly +OAI.Combinatorics.BalancedRyser.Deletion.DeletionCoordinates +OAI.Combinatorics.BalancedRyser.Deletion.DeletionCountingExposure +OAI.Combinatorics.BalancedRyser.Deletion.DeletionDomination +OAI.Combinatorics.BalancedRyser.Deletion.DeletionDomination2 +OAI.Combinatorics.BalancedRyser.Deletion.DeletionFieldTransport +OAI.Combinatorics.BalancedRyser.Deletion.DeletionLawNormalization +OAI.Combinatorics.BalancedRyser.Deletion.DeletionLawPMF +OAI.Combinatorics.BalancedRyser.Deletion.DeletionLawTransport +OAI.Combinatorics.BalancedRyser.Deletion.DeletionMassBound +OAI.Combinatorics.BalancedRyser.Deletion.DeletionProbability +OAI.Combinatorics.BalancedRyser.Deletion.DeletionProbabilityBridge +OAI.Combinatorics.BalancedRyser.Deletion.DeletionSequential +OAI.Combinatorics.BalancedRyser.Deletion.DeletionVisibility +OAI.Combinatorics.BalancedRyser.Deletion.ExponentialDomination +OAI.Combinatorics.BalancedRyser.Deletion.GeometricDeletionCounting +OAI.Combinatorics.BalancedRyser.Deletion.RobustDeletionAssembly +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletion +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionAssembly +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionBound +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionCoordinates +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionEventsLemmas +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionFromSelection +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionKernel +OAI.Combinatorics.BalancedRyser.Deletion.SelectedDeletionPMF +OAI.Combinatorics.BalancedRyser.Deletion.UniformDeletionEnumeration +OAI.Combinatorics.BalancedRyser.Deletion.UniformDeletionMoments +OAI.Combinatorics.BalancedRyser.Deletion.UniformDeletionReview +OAI.Combinatorics.BalancedRyser.Deletion.UniformDeletionSurvival +OAI.Combinatorics.BalancedRyser.Deletion.UniformDeletionTolerance +OAI.Combinatorics.BalancedRyser.Hypergraph +OAI.Combinatorics.BalancedRyser.Incidence.Affine +OAI.Combinatorics.BalancedRyser.Incidence.AffineDirectionCounting +OAI.Combinatorics.BalancedRyser.Incidence.AffineDoubleCount +OAI.Combinatorics.BalancedRyser.Incidence.AffineIncidence +OAI.Combinatorics.BalancedRyser.Incidence.AffineInjectionExposure +OAI.Combinatorics.BalancedRyser.Incidence.AffineInjectionGuards +OAI.Combinatorics.BalancedRyser.Incidence.AffineMomentAlgebraLemmas +OAI.Combinatorics.BalancedRyser.Incidence.AffinePairEvaluation +OAI.Combinatorics.BalancedRyser.Incidence.AffinePencilForcing +OAI.Combinatorics.BalancedRyser.Incidence.AffinePermutationExposure +OAI.Combinatorics.BalancedRyser.Incidence.AffinePlaneInstance +OAI.Combinatorics.BalancedRyser.Incidence.AffinePlaneOrderExposure +OAI.Combinatorics.BalancedRyser.Incidence.AffineProfileExposure +OAI.Combinatorics.BalancedRyser.Incidence.AffineProfileIncidence +OAI.Combinatorics.BalancedRyser.Incidence.AffineProfileParameter +OAI.Combinatorics.BalancedRyser.Incidence.AffineSecondMoment +OAI.Combinatorics.BalancedRyser.Incidence.AffineTargetError +OAI.Combinatorics.BalancedRyser.Incidence.AffineUniformCoordinates +OAI.Combinatorics.BalancedRyser.Incidence.AlignedFreshIncidence +OAI.Combinatorics.BalancedRyser.Incidence.AlignedGeneratorIncidence +OAI.Combinatorics.BalancedRyser.Incidence.AlignedGlobalProjectedIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidateConditionalFreshIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidateFreshIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceCompletion +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceCountTransport +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceInitialSums +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceMean +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceModel +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceProbability +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceRootSums +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceTests +OAI.Combinatorics.BalancedRyser.Incidence.CandidateIncidenceTransport +OAI.Combinatorics.BalancedRyser.Incidence.CandidatePartialPointIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidatePointIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CandidatePointIncidenceMean +OAI.Combinatorics.BalancedRyser.Incidence.CandidateSmallIncidence +OAI.Combinatorics.BalancedRyser.Incidence.CorePencil +OAI.Combinatorics.BalancedRyser.Incidence.CorePencilAssembly +OAI.Combinatorics.BalancedRyser.Incidence.CorePencilFieldTransport +OAI.Combinatorics.BalancedRyser.Incidence.CorePencilReduction +OAI.Combinatorics.BalancedRyser.Incidence.ElementaryIncidence +OAI.Combinatorics.BalancedRyser.Incidence.FiniteAffinePlane +OAI.Combinatorics.BalancedRyser.Incidence.FiniteGridPolynomial +OAI.Combinatorics.BalancedRyser.Incidence.FiniteProfileIncidence +OAI.Combinatorics.BalancedRyser.Incidence.ForcedSinglePencil +OAI.Combinatorics.BalancedRyser.Incidence.LocalLargePencils +OAI.Combinatorics.BalancedRyser.Incidence.LocalOrderedPencils +OAI.Combinatorics.BalancedRyser.Incidence.ParallelPencilForcing +OAI.Combinatorics.BalancedRyser.Incidence.PartialIncidence +OAI.Combinatorics.BalancedRyser.Incidence.PartialIncidenceCounts +OAI.Combinatorics.BalancedRyser.Incidence.PencilOccupancy +OAI.Combinatorics.BalancedRyser.Incidence.PencilReuseEndpoint +OAI.Combinatorics.BalancedRyser.Incidence.PrimeStabilityEndpoint +OAI.Combinatorics.BalancedRyser.Incidence.PrimeStabilityReduction +OAI.Combinatorics.BalancedRyser.Incidence.ProfileEmpiricalIncidence +OAI.Combinatorics.BalancedRyser.Incidence.ProfileLimitIncidence +OAI.Combinatorics.BalancedRyser.Incidence.Projective +OAI.Combinatorics.BalancedRyser.Incidence.Projective2 +OAI.Combinatorics.BalancedRyser.Incidence.ProjectiveIncidence +OAI.Combinatorics.BalancedRyser.Incidence.ProjectiveModel +OAI.Combinatorics.BalancedRyser.Incidence.ProjectiveNormalization +OAI.Combinatorics.BalancedRyser.Incidence.ProjectiveSkewCounting +OAI.Combinatorics.BalancedRyser.Incidence.ProjectiveStability +OAI.Combinatorics.BalancedRyser.Incidence.RedeiPolynomial +OAI.Combinatorics.BalancedRyser.Incidence.RepeatedIncidences +OAI.Combinatorics.BalancedRyser.Incidence.SelectionAffineAdapter +OAI.Combinatorics.BalancedRyser.Incidence.SinglePencilObstruction +OAI.Combinatorics.BalancedRyser.Incidence.SmallProjectiveArithmetic +OAI.Combinatorics.BalancedRyser.Incidence.SmallProjectiveStability +OAI.Combinatorics.BalancedRyser.Incidence.SmallProjectiveStabilityReduction +OAI.Combinatorics.BalancedRyser.Incidence.Stability +OAI.Combinatorics.BalancedRyser.Incidence.StabilityAlgebraAssembly +OAI.Combinatorics.BalancedRyser.Incidence.StabilityBlocking +OAI.Combinatorics.BalancedRyser.Incidence.StabilityCoprimeReduction +OAI.Combinatorics.BalancedRyser.Incidence.StabilityDegreeBudget +OAI.Combinatorics.BalancedRyser.Incidence.StabilityFinalRefinement +OAI.Combinatorics.BalancedRyser.Incidence.StabilityGridDegree +OAI.Combinatorics.BalancedRyser.Incidence.StabilityLargeFiber +OAI.Combinatorics.BalancedRyser.Incidence.StabilityLeadingPart +OAI.Combinatorics.BalancedRyser.Incidence.StabilityPolynomial +OAI.Combinatorics.BalancedRyser.Incidence.StabilityPolynomial2 +OAI.Combinatorics.BalancedRyser.Incidence.StabilityRootDivisibility +OAI.Combinatorics.BalancedRyser.Incidence.StabilitySkewCountLemmas +OAI.Combinatorics.BalancedRyser.Incidence.StabilityTangents +OAI.Combinatorics.BalancedRyser.Incidence.UnusedOffsetIncidence +OAI.Combinatorics.BalancedRyser.Local.AlignedCoordinateAveraging +OAI.Combinatorics.BalancedRyser.Local.AlignedFreeCoordinates +OAI.Combinatorics.BalancedRyser.Local.AlignedFreeCylinders +OAI.Combinatorics.BalancedRyser.Local.AlignedFreshCoordinate +OAI.Combinatorics.BalancedRyser.Local.AlignedFreshHistory +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalCardinality +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalCurrentTuple +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalEarlyUsedTest +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalGeneratorTest +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalHistory +OAI.Combinatorics.BalancedRyser.Local.AlignedGlobalProduct +OAI.Combinatorics.BalancedRyser.Local.AlignedHistoryKernel +OAI.Combinatorics.BalancedRyser.Local.AlignedListProbability +OAI.Combinatorics.BalancedRyser.Local.AlignedPointExposure +OAI.Combinatorics.BalancedRyser.Local.AlignedPointLaw +OAI.Combinatorics.BalancedRyser.Local.AlignedProjectedCollinearTest +OAI.Combinatorics.BalancedRyser.Local.AlignedProjectedExposure +OAI.Combinatorics.BalancedRyser.Local.AlignedProjectedMean +OAI.Combinatorics.BalancedRyser.Local.AlignedStateTransition +OAI.Combinatorics.BalancedRyser.Local.AlignedTokenPointLaw +OAI.Combinatorics.BalancedRyser.Local.AlignedUnusedLaw +OAI.Combinatorics.BalancedRyser.Local.AlignedUnusedTripleBound +OAI.Combinatorics.BalancedRyser.Local.AlignedUsedObservable +OAI.Combinatorics.BalancedRyser.Local.AlignedUsedTestTransport +OAI.Combinatorics.BalancedRyser.Local.AlignmentNoBias +OAI.Combinatorics.BalancedRyser.Local.AlignmentNormalization +OAI.Combinatorics.BalancedRyser.Local.AlignmentStepLaw +OAI.Combinatorics.BalancedRyser.Local.ChildAlignment +OAI.Combinatorics.BalancedRyser.Local.ConfigurationReuse +OAI.Combinatorics.BalancedRyser.Local.FinalLocalEndpoint +OAI.Combinatorics.BalancedRyser.Local.FiniteLocalLemma +OAI.Combinatorics.BalancedRyser.Local.GlobalAlignedParentCoordinates +OAI.Combinatorics.BalancedRyser.Local.GlobalPartialAlignment +OAI.Combinatorics.BalancedRyser.Local.GlobalReuseTargetSum +OAI.Combinatorics.BalancedRyser.Local.HalfWeightLocalLemma +OAI.Combinatorics.BalancedRyser.Local.InjectionAuxiliaryExposure +OAI.Combinatorics.BalancedRyser.Local.InjectionConditioning +OAI.Combinatorics.BalancedRyser.Local.InjectionExposure +OAI.Combinatorics.BalancedRyser.Local.InjectionExposureLaw +OAI.Combinatorics.BalancedRyser.Local.InjectionExposureMixture +OAI.Combinatorics.BalancedRyser.Local.Local +OAI.Combinatorics.BalancedRyser.Local.LocalAcyclicSpecifications +OAI.Combinatorics.BalancedRyser.Local.LocalAlignedReuseCounting +OAI.Combinatorics.BalancedRyser.Local.LocalAnchorExclusion +OAI.Combinatorics.BalancedRyser.Local.LocalAsymptotics +OAI.Combinatorics.BalancedRyser.Local.LocalBadCoverSpecifications +OAI.Combinatorics.BalancedRyser.Local.LocalConditionFibers +OAI.Combinatorics.BalancedRyser.Local.LocalConditionSpec +OAI.Combinatorics.BalancedRyser.Local.LocalConditionUnusedSupport +OAI.Combinatorics.BalancedRyser.Local.LocalConfigurationPattern +OAI.Combinatorics.BalancedRyser.Local.LocalCoverMarking +OAI.Combinatorics.BalancedRyser.Local.LocalDirectionAssignments +OAI.Combinatorics.BalancedRyser.Local.LocalEndpointAssembly +OAI.Combinatorics.BalancedRyser.Local.LocalEndpointCompletion +OAI.Combinatorics.BalancedRyser.Local.LocalEndpointReduction +OAI.Combinatorics.BalancedRyser.Local.LocalExposureTiming +OAI.Combinatorics.BalancedRyser.Local.LocalFailureReduction +OAI.Combinatorics.BalancedRyser.Local.LocalFailureSummation +OAI.Combinatorics.BalancedRyser.Local.LocalFiberBounds +OAI.Combinatorics.BalancedRyser.Local.LocalFourEventProbability +OAI.Combinatorics.BalancedRyser.Local.LocalFourEventUnion +OAI.Combinatorics.BalancedRyser.Local.LocalFourEventWitnesses +OAI.Combinatorics.BalancedRyser.Local.LocalFourEvents +OAI.Combinatorics.BalancedRyser.Local.LocalHighReuse +OAI.Combinatorics.BalancedRyser.Local.LocalHighReuseEndpoint +OAI.Combinatorics.BalancedRyser.Local.LocalInjectionBudget +OAI.Combinatorics.BalancedRyser.Local.LocalInjectionFreeLaw +OAI.Combinatorics.BalancedRyser.Local.LocalInjectionLaw +OAI.Combinatorics.BalancedRyser.Local.LocalKernel +OAI.Combinatorics.BalancedRyser.Local.LocalLemma +OAI.Combinatorics.BalancedRyser.Local.LocalNoninjectiveContribution +OAI.Combinatorics.BalancedRyser.Local.LocalParentMap +OAI.Combinatorics.BalancedRyser.Local.LocalPatternCodes +OAI.Combinatorics.BalancedRyser.Local.LocalPatternEvents +OAI.Combinatorics.BalancedRyser.Local.LocalPatternTransport +OAI.Combinatorics.BalancedRyser.Local.LocalPrecoverageTransport +OAI.Combinatorics.BalancedRyser.Local.LocalPrescribedGeometry +OAI.Combinatorics.BalancedRyser.Local.LocalPrescriptionCounting +OAI.Combinatorics.BalancedRyser.Local.LocalQuantitativeAssembly +OAI.Combinatorics.BalancedRyser.Local.LocalSelectedKernel +OAI.Combinatorics.BalancedRyser.Local.LocalSmallReuseAssembly +OAI.Combinatorics.BalancedRyser.Local.LocalSpecificationEncoding +OAI.Combinatorics.BalancedRyser.Local.LocalSpecificationProbability +OAI.Combinatorics.BalancedRyser.Local.LocalSpecificationTransport +OAI.Combinatorics.BalancedRyser.Local.LocalSummationArithmetic +OAI.Combinatorics.BalancedRyser.Local.LocalSurplus +OAI.Combinatorics.BalancedRyser.Local.LocalTiming +OAI.Combinatorics.BalancedRyser.Local.LocalTupleReindex +OAI.Combinatorics.BalancedRyser.Local.LocalTwoReuseAssembly +OAI.Combinatorics.BalancedRyser.Local.LocalTwoReuseEndpoint +OAI.Combinatorics.BalancedRyser.Local.LocalTwoReuseMean +OAI.Combinatorics.BalancedRyser.Local.LocalTwoReuseUsedEvents +OAI.Combinatorics.BalancedRyser.Local.LocalUnusedEventBridge +OAI.Combinatorics.BalancedRyser.Local.LocalUnusedOffsetProbability +OAI.Combinatorics.BalancedRyser.Local.LocalUnusedTripleProbability +OAI.Combinatorics.BalancedRyser.Local.LocalUsedEventMean +OAI.Combinatorics.BalancedRyser.Local.LocalUsedEventTiming +OAI.Combinatorics.BalancedRyser.Local.LocalUsedEventUnion +OAI.Combinatorics.BalancedRyser.Local.LocalUsedFreshMean +OAI.Combinatorics.BalancedRyser.Local.LowReuseOrder +OAI.Combinatorics.BalancedRyser.Local.MeasureLocalLemma +OAI.Combinatorics.BalancedRyser.Local.OneReuseDecomposition +OAI.Combinatorics.BalancedRyser.Local.PartialAlignment +OAI.Combinatorics.BalancedRyser.Local.ReuseConditionalSum +OAI.Combinatorics.BalancedRyser.Local.ReuseExtensionArithmetic +OAI.Combinatorics.BalancedRyser.Local.ReuseExtensionSum +OAI.Combinatorics.BalancedRyser.Local.ReuseExtensionTable +OAI.Combinatorics.BalancedRyser.Local.ReuseGlobalExtension +OAI.Combinatorics.BalancedRyser.Local.ReuseOrdering +OAI.Combinatorics.BalancedRyser.Local.ReusePatternCounting +OAI.Combinatorics.BalancedRyser.Local.ReusePrefix +OAI.Combinatorics.BalancedRyser.Local.ReusePrefixExtension +OAI.Combinatorics.BalancedRyser.Local.ReusePrescriptions +OAI.Combinatorics.BalancedRyser.Local.ReuseSchedule +OAI.Combinatorics.BalancedRyser.Local.ReuseScheduleAggregation +OAI.Combinatorics.BalancedRyser.Local.ReuseScheduleBounds +OAI.Combinatorics.BalancedRyser.Local.ReuseScore +OAI.Combinatorics.BalancedRyser.Local.ReuseSourceWitness +OAI.Combinatorics.BalancedRyser.Local.ReuseTargetDirections +OAI.Combinatorics.BalancedRyser.Local.ReuseTargetSum +OAI.Combinatorics.BalancedRyser.Local.ReuseTower +OAI.Combinatorics.BalancedRyser.Local.ReuseWeightedBound +OAI.Combinatorics.BalancedRyser.Local.ReuseWitness +OAI.Combinatorics.BalancedRyser.Local.SmallReusePermutation +OAI.Combinatorics.BalancedRyser.Local.TupleAlignment +OAI.Combinatorics.BalancedRyser.Local.TwoReuseEndpoint +OAI.Combinatorics.BalancedRyser.Main +OAI.Combinatorics.BalancedRyser.Model +OAI.Combinatorics.BalancedRyser.Probability.AcyclicProductBound +OAI.Combinatorics.BalancedRyser.Probability.AlternateUsedEventUnion +OAI.Combinatorics.BalancedRyser.Probability.Assembly +OAI.Combinatorics.BalancedRyser.Probability.AtypicalLines +OAI.Combinatorics.BalancedRyser.Probability.BernoulliTail +OAI.Combinatorics.BalancedRyser.Probability.BlockCapacity +OAI.Combinatorics.BalancedRyser.Probability.BlockIntersection +OAI.Combinatorics.BalancedRyser.Probability.BoundedDrift +OAI.Combinatorics.BalancedRyser.Probability.BoundedDriftCore +OAI.Combinatorics.BalancedRyser.Probability.CenteredIncrements +OAI.Combinatorics.BalancedRyser.Probability.Concentration +OAI.Combinatorics.BalancedRyser.Probability.ConditionalMGFStep +OAI.Combinatorics.BalancedRyser.Probability.ConditionalMultiplicity +OAI.Combinatorics.BalancedRyser.Probability.ConditionalMultiplicity2 +OAI.Combinatorics.BalancedRyser.Probability.ConditionalOrderLaw +OAI.Combinatorics.BalancedRyser.Probability.ConditionalOrderVariance +OAI.Combinatorics.BalancedRyser.Probability.ConditionalRestriction +OAI.Combinatorics.BalancedRyser.Probability.ConfigurationBlockCardinality +OAI.Combinatorics.BalancedRyser.Probability.ConfigurationStructure +OAI.Combinatorics.BalancedRyser.Probability.CoreRepresentativeEquivalence +OAI.Combinatorics.BalancedRyser.Probability.CoreRepresentatives +OAI.Combinatorics.BalancedRyser.Probability.CountingExposureKernel +OAI.Combinatorics.BalancedRyser.Probability.CountingExposurePosterior +OAI.Combinatorics.BalancedRyser.Probability.CountingJointLaw +OAI.Combinatorics.BalancedRyser.Probability.CoverCountingExposure +OAI.Combinatorics.BalancedRyser.Probability.CrossEqualityRegression43d8 +OAI.Combinatorics.BalancedRyser.Probability.CylinderConditioning +OAI.Combinatorics.BalancedRyser.Probability.CylinderUnionBound +OAI.Combinatorics.BalancedRyser.Probability.DistinctPairs +OAI.Combinatorics.BalancedRyser.Probability.DistinctRoleLaw +OAI.Combinatorics.BalancedRyser.Probability.DriftUnionBound +OAI.Combinatorics.BalancedRyser.Probability.EqualityPatternOrdering +OAI.Combinatorics.BalancedRyser.Probability.ExactMultiplicity +OAI.Combinatorics.BalancedRyser.Probability.ExposedWitnessProbability +OAI.Combinatorics.BalancedRyser.Probability.ExposureInterleaving +OAI.Combinatorics.BalancedRyser.Probability.ExposureMeshLimits +OAI.Combinatorics.BalancedRyser.Probability.ExposurePrefixCard +OAI.Combinatorics.BalancedRyser.Probability.ExposureSchedule +OAI.Combinatorics.BalancedRyser.Probability.ExposureScheduleOrder +OAI.Combinatorics.BalancedRyser.Probability.FiniteCenteredPatternLemmas +OAI.Combinatorics.BalancedRyser.Probability.FiniteConditionalAveraging +OAI.Combinatorics.BalancedRyser.Probability.FiniteConditionalRatios +OAI.Combinatorics.BalancedRyser.Probability.FiniteDependencyRank +OAI.Combinatorics.BalancedRyser.Probability.FiniteExposureTower +OAI.Combinatorics.BalancedRyser.Probability.FiniteFixedLaw +OAI.Combinatorics.BalancedRyser.Probability.FiniteHistory +OAI.Combinatorics.BalancedRyser.Probability.FiniteHistoryAdditive +OAI.Combinatorics.BalancedRyser.Probability.FiniteHistoryInvariant +OAI.Combinatorics.BalancedRyser.Probability.FiniteKernelPotential +OAI.Combinatorics.BalancedRyser.Probability.FiniteMomentTail +OAI.Combinatorics.BalancedRyser.Probability.FiniteProbability +OAI.Combinatorics.BalancedRyser.Probability.FiniteUniformConcentration +OAI.Combinatorics.BalancedRyser.Probability.FiniteUniformConditioning +OAI.Combinatorics.BalancedRyser.Probability.FiniteUniformFibers +OAI.Combinatorics.BalancedRyser.Probability.FiniteUniformTower +OAI.Combinatorics.BalancedRyser.Probability.FiniteUniformVariance +OAI.Combinatorics.BalancedRyser.Probability.ForcedNonsplitLabels +OAI.Combinatorics.BalancedRyser.Probability.ForwardDependencyExtraction +OAI.Combinatorics.BalancedRyser.Probability.FourCycle +OAI.Combinatorics.BalancedRyser.Probability.FreshCoordinatePrescription +OAI.Combinatorics.BalancedRyser.Probability.FreshDoublePrescription +OAI.Combinatorics.BalancedRyser.Probability.FreshRandomWitness +OAI.Combinatorics.BalancedRyser.Probability.FreshTupleConstraints +OAI.Combinatorics.BalancedRyser.Probability.FreshTupleWitness +OAI.Combinatorics.BalancedRyser.Probability.FreshWitnessConditional +OAI.Combinatorics.BalancedRyser.Probability.FreshWitnessCounting +OAI.Combinatorics.BalancedRyser.Probability.FreshWitnessProbability +OAI.Combinatorics.BalancedRyser.Probability.FullyExposedTargets +OAI.Combinatorics.BalancedRyser.Probability.GeneratorEnumeration +OAI.Combinatorics.BalancedRyser.Probability.GlobalRootConditioning +OAI.Combinatorics.BalancedRyser.Probability.GlobalTupleLaw +OAI.Combinatorics.BalancedRyser.Probability.HypergeometricApproximation +OAI.Combinatorics.BalancedRyser.Probability.IndependentDoobGrouping +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialGrouping +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialIncrement +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialKernel +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialPrefix +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialReassembly +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrialStep +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrials +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrials2 +OAI.Combinatorics.BalancedRyser.Probability.IndependentTrials3 +OAI.Combinatorics.BalancedRyser.Probability.LogTail +OAI.Combinatorics.BalancedRyser.Probability.MainAssembly +OAI.Combinatorics.BalancedRyser.Probability.MultiplicityLimit +OAI.Combinatorics.BalancedRyser.Probability.NearCoverFinite +OAI.Combinatorics.BalancedRyser.Probability.NearCoverLimit +OAI.Combinatorics.BalancedRyser.Probability.NearCoverVisibility +OAI.Combinatorics.BalancedRyser.Probability.NoSmallBlockCover +OAI.Combinatorics.BalancedRyser.Probability.OrderedEventCounting +OAI.Combinatorics.BalancedRyser.Probability.OverlapOrdering +OAI.Combinatorics.BalancedRyser.Probability.PMFConditioningMap +OAI.Combinatorics.BalancedRyser.Probability.ParallelBlockCapacity +OAI.Combinatorics.BalancedRyser.Probability.PatternAllowedEventTails +OAI.Combinatorics.BalancedRyser.Probability.PatternAllowedGate +OAI.Combinatorics.BalancedRyser.Probability.PatternAllowedSourceTails +OAI.Combinatorics.BalancedRyser.Probability.PatternCancellation +OAI.Combinatorics.BalancedRyser.Probability.PatternCenteredAssembly +OAI.Combinatorics.BalancedRyser.Probability.PatternConditionalMean +OAI.Combinatorics.BalancedRyser.Probability.PatternExposure +OAI.Combinatorics.BalancedRyser.Probability.PatternExposureBoundary +OAI.Combinatorics.BalancedRyser.Probability.PatternExposureIdentities +OAI.Combinatorics.BalancedRyser.Probability.PatternExtension +OAI.Combinatorics.BalancedRyser.Probability.PatternFiniteExposure +OAI.Combinatorics.BalancedRyser.Probability.PatternFixedEventAveraging +OAI.Combinatorics.BalancedRyser.Probability.PatternGate +OAI.Combinatorics.BalancedRyser.Probability.PatternIntegrability +OAI.Combinatorics.BalancedRyser.Probability.PatternLabelRestriction +OAI.Combinatorics.BalancedRyser.Probability.PatternMarginals +OAI.Combinatorics.BalancedRyser.Probability.PatternModelCancellation +OAI.Combinatorics.BalancedRyser.Probability.PatternModelExpansion +OAI.Combinatorics.BalancedRyser.Probability.PatternMomentModel +OAI.Combinatorics.BalancedRyser.Probability.PatternMomentTails +OAI.Combinatorics.BalancedRyser.Probability.PatternMoments +OAI.Combinatorics.BalancedRyser.Probability.PatternMomentsLemmas +OAI.Combinatorics.BalancedRyser.Probability.PatternOrderingAdapter +OAI.Combinatorics.BalancedRyser.Probability.PatternPrefixSupport +OAI.Combinatorics.BalancedRyser.Probability.PatternSourceTails +OAI.Combinatorics.BalancedRyser.Probability.PatternSupportCompatibility +OAI.Combinatorics.BalancedRyser.Probability.PatternTailAsymptotics +OAI.Combinatorics.BalancedRyser.Probability.PatternWeightExtensions +OAI.Combinatorics.BalancedRyser.Probability.PatternWeights +OAI.Combinatorics.BalancedRyser.Probability.PermutationExposureMean +OAI.Combinatorics.BalancedRyser.Probability.PermutationHistoryLaw +OAI.Combinatorics.BalancedRyser.Probability.PermutationSubsetLaw +OAI.Combinatorics.BalancedRyser.Probability.PointEdgeInjective +OAI.Combinatorics.BalancedRyser.Probability.PointLabelInjective +OAI.Combinatorics.BalancedRyser.Probability.PrimeConfigurationAssembly +OAI.Combinatorics.BalancedRyser.Probability.ProbabilityPerturbation +OAI.Combinatorics.BalancedRyser.Probability.ProductSubsetVariance +OAI.Combinatorics.BalancedRyser.Probability.ProjectedGlobalIndependent +OAI.Combinatorics.BalancedRyser.Probability.ProjectionGuardRegression684a +OAI.Combinatorics.BalancedRyser.Probability.PurposefulIndices +OAI.Combinatorics.BalancedRyser.Probability.RescaledDrift +OAI.Combinatorics.BalancedRyser.Probability.RobustMultiplicity +OAI.Combinatorics.BalancedRyser.Probability.RobustNearCover +OAI.Combinatorics.BalancedRyser.Probability.RootChildCount +OAI.Combinatorics.BalancedRyser.Probability.RootChildDependence +OAI.Combinatorics.BalancedRyser.Probability.RootConditioning +OAI.Combinatorics.BalancedRyser.Probability.RootPatternModel +OAI.Combinatorics.BalancedRyser.Probability.RootSuccess +OAI.Combinatorics.BalancedRyser.Probability.RootSuccessAsymptotics +OAI.Combinatorics.BalancedRyser.Probability.ScheduledCountingExposure +OAI.Combinatorics.BalancedRyser.Probability.ScheduledCountingLaw +OAI.Combinatorics.BalancedRyser.Probability.ScheduledMarksBridge +OAI.Combinatorics.BalancedRyser.Probability.SectionAssembly +OAI.Combinatorics.BalancedRyser.Probability.SelectedExperimentLaw +OAI.Combinatorics.BalancedRyser.Probability.SelectedJointAssembly +OAI.Combinatorics.BalancedRyser.Probability.SelectedSuccessMass +OAI.Combinatorics.BalancedRyser.Probability.SimultaneousDrift +OAI.Combinatorics.BalancedRyser.Probability.SizeThreshold +OAI.Combinatorics.BalancedRyser.Probability.SlotConditionedLaw +OAI.Combinatorics.BalancedRyser.Probability.SlotEdges +OAI.Combinatorics.BalancedRyser.Probability.SlotEdges2 +OAI.Combinatorics.BalancedRyser.Probability.SlotProbability +OAI.Combinatorics.BalancedRyser.Probability.SlotProbability2 +OAI.Combinatorics.BalancedRyser.Probability.SlowThreshold +OAI.Combinatorics.BalancedRyser.Probability.SparsePatterns +OAI.Combinatorics.BalancedRyser.Probability.StoppedIncrements +OAI.Combinatorics.BalancedRyser.Probability.SubGaussianTail +OAI.Combinatorics.BalancedRyser.Probability.SurplusAcyclic +OAI.Combinatorics.BalancedRyser.Probability.TailConditioning +OAI.Combinatorics.BalancedRyser.Probability.TailConditioning2 +OAI.Combinatorics.BalancedRyser.Probability.TailEvents +OAI.Combinatorics.BalancedRyser.Probability.TailEvents2 +OAI.Combinatorics.BalancedRyser.Probability.TailGraph +OAI.Combinatorics.BalancedRyser.Probability.TailGraphWeights +OAI.Combinatorics.BalancedRyser.Probability.TailPrescriptions +OAI.Combinatorics.BalancedRyser.Probability.TailPrescriptions2 +OAI.Combinatorics.BalancedRyser.Probability.TailProductBounds +OAI.Combinatorics.BalancedRyser.Probability.TailWeights +OAI.Combinatorics.BalancedRyser.Probability.ThinningTail +OAI.Combinatorics.BalancedRyser.Probability.TupleExposure +OAI.Combinatorics.BalancedRyser.Probability.UncoveredExchange +OAI.Combinatorics.BalancedRyser.Probability.UncoveredSubsetVariance +OAI.Combinatorics.BalancedRyser.Probability.UnexposedTupleLaw +OAI.Combinatorics.BalancedRyser.Probability.UniformConditionalProduct +OAI.Combinatorics.BalancedRyser.Probability.UniformKernel +OAI.Combinatorics.BalancedRyser.Probability.UniformOrderedSubset +OAI.Combinatorics.BalancedRyser.Probability.UniformRestriction +OAI.Combinatorics.BalancedRyser.Probability.UniformSubsetExposure +OAI.Combinatorics.BalancedRyser.Probability.UniformThreshold +OAI.Combinatorics.BalancedRyser.Probability.UnusedOffsetAveraging +OAI.Combinatorics.BalancedRyser.Probability.VacantBins +OAI.Combinatorics.BalancedRyser.Probability.WithoutReplacementCoupling +OAI.Combinatorics.BalancedRyser.Probability.WitnessCounting +OAI.Combinatorics.BalancedRyser.Profiles.AnalyticDetection +OAI.Combinatorics.BalancedRyser.Profiles.ConditionalOrderDetection +OAI.Combinatorics.BalancedRyser.Profiles.DetectionThresholds +OAI.Combinatorics.BalancedRyser.Profiles.FiniteGridVanishing +OAI.Combinatorics.BalancedRyser.Profiles.LocalMarkedAnchors +OAI.Combinatorics.BalancedRyser.Profiles.MarkedExposure +OAI.Combinatorics.BalancedRyser.Profiles.MarkedExposureNumerics +OAI.Combinatorics.BalancedRyser.Profiles.PoissonProfile +OAI.Combinatorics.BalancedRyser.Profiles.PoissonProfile2 +OAI.Combinatorics.BalancedRyser.Profiles.Profile +OAI.Combinatorics.BalancedRyser.Profiles.ProfileAmbientCompactness +OAI.Combinatorics.BalancedRyser.Profiles.ProfileClassLimits +OAI.Combinatorics.BalancedRyser.Profiles.ProfileClassMargin +OAI.Combinatorics.BalancedRyser.Profiles.ProfileCoefficients +OAI.Combinatorics.BalancedRyser.Profiles.ProfileCompactness +OAI.Combinatorics.BalancedRyser.Profiles.ProfileContinuity +OAI.Combinatorics.BalancedRyser.Profiles.ProfileCoordinates +OAI.Combinatorics.BalancedRyser.Profiles.ProfileCountingAssembly +OAI.Combinatorics.BalancedRyser.Profiles.ProfileCountingEndpoint +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetection +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetectionBridge +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetectionConcentration +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetectionLimit +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetectionNull +OAI.Combinatorics.BalancedRyser.Profiles.ProfileDetectionSource +OAI.Combinatorics.BalancedRyser.Profiles.ProfileEmpirical +OAI.Combinatorics.BalancedRyser.Profiles.ProfileEmpiricalMeasure +OAI.Combinatorics.BalancedRyser.Profiles.ProfileEmpiricalSupport +OAI.Combinatorics.BalancedRyser.Profiles.ProfileFiniteMarks +OAI.Combinatorics.BalancedRyser.Profiles.ProfileFiniteScheduledLemmas +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridCounting +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridDensity +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridDetection +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridFiniteIdentity +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridMeasures +OAI.Combinatorics.BalancedRyser.Profiles.ProfileGridProducts +OAI.Combinatorics.BalancedRyser.Profiles.ProfileHypergeometric +OAI.Combinatorics.BalancedRyser.Profiles.ProfileIdentifiability +OAI.Combinatorics.BalancedRyser.Profiles.ProfileLimitLaws +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarginalContinuity +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarginalLimitTV +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarginalLimits +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarginalTV +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarkLimit +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarkedError +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarkedOrders +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMarksLimit +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMeans +OAI.Combinatorics.BalancedRyser.Profiles.ProfileMomentCompactness +OAI.Combinatorics.BalancedRyser.Profiles.ProfileOrderComplements +OAI.Combinatorics.BalancedRyser.Profiles.ProfileParameterGrids +OAI.Combinatorics.BalancedRyser.Profiles.ProfileParameterLaw +OAI.Combinatorics.BalancedRyser.Profiles.ProfilePoissonLemmas +OAI.Combinatorics.BalancedRyser.Profiles.ProfileScheduledApproximation +OAI.Combinatorics.BalancedRyser.Profiles.ProfileScheduledMargin +OAI.Combinatorics.BalancedRyser.Profiles.ProfileScheduledMarks +OAI.Combinatorics.BalancedRyser.Profiles.ProfileShrinkingExceptions +OAI.Combinatorics.BalancedRyser.Profiles.ProfileSourceMarkLiminf +OAI.Combinatorics.BalancedRyser.Profiles.ProfileSourceMarkLimit +OAI.Combinatorics.BalancedRyser.Profiles.ProfileTargetExclusion +OAI.Combinatorics.BalancedRyser.Profiles.ProfileVisibility +OAI.Combinatorics.BalancedRyser.Profiles.ProfileVisibilityConcrete +OAI.Combinatorics.BalancedRyser.Profiles.ProfileWeakCompactness +OAI.Combinatorics.BalancedRyser.Profiles.ProfileWeakDetection +OAI.Combinatorics.BalancedRyser.Profiles.ProfileWeakLimits +OAI.Combinatorics.BalancedRyser.Profiles.ProfileWitnessPayment +OAI.Combinatorics.BalancedRyser.Profiles.RobustFromProfileCounting +OAI.Combinatorics.BalancedRyser.Profiles.StrictOrderMarkedExposure +OAI.Combinatorics.BalancedRyser.Profiles.UniformDetectionMargin +OAI.Combinatorics.BalancedRyser.Profiles.WitnessDetection +OAI.Combinatorics.BalancedRyser.Results +OAI.Combinatorics.BalancedRyser.Selection.CensoredDrift +OAI.Combinatorics.BalancedRyser.Selection.DistinctInitialOccupancy +OAI.Combinatorics.BalancedRyser.Selection.InitialOccupancyUniform +OAI.Combinatorics.BalancedRyser.Selection.LineOccupancy +OAI.Combinatorics.BalancedRyser.Selection.LineOccupancyAsymptotics +OAI.Combinatorics.BalancedRyser.Selection.LineOccupancyConcentration +OAI.Combinatorics.BalancedRyser.Selection.OccupancyClassVisibility +OAI.Combinatorics.BalancedRyser.Selection.OccupancyFailureClass +OAI.Combinatorics.BalancedRyser.Selection.OccupancyRowIntegral +OAI.Combinatorics.BalancedRyser.Selection.OccupancyVisibility +OAI.Combinatorics.BalancedRyser.Selection.OccupancyWitness +OAI.Combinatorics.BalancedRyser.Selection.PlaneSelectionOccupancy +OAI.Combinatorics.BalancedRyser.Selection.ProfileOccupancy +OAI.Combinatorics.BalancedRyser.Selection.ProfileOccupancy2 +OAI.Combinatorics.BalancedRyser.Selection.RobustOccupancyAssembly +OAI.Combinatorics.BalancedRyser.Selection.Selection +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryBounds +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryConcentration +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryConditional +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryDrift +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryMeanBounds +OAI.Combinatorics.BalancedRyser.Selection.SelectionAuxiliaryTracks +OAI.Combinatorics.BalancedRyser.Selection.SelectionBarriers +OAI.Combinatorics.BalancedRyser.Selection.SelectionCensorMassBounds +OAI.Combinatorics.BalancedRyser.Selection.SelectionCensorProbability +OAI.Combinatorics.BalancedRyser.Selection.SelectionCensoredJumps +OAI.Combinatorics.BalancedRyser.Selection.SelectionCensoredMeans +OAI.Combinatorics.BalancedRyser.Selection.SelectionCensoring +OAI.Combinatorics.BalancedRyser.Selection.SelectionConcentrationAsymptotics +OAI.Combinatorics.BalancedRyser.Selection.SelectionConcentrationReview +OAI.Combinatorics.BalancedRyser.Selection.SelectionConcentrationUniform +OAI.Combinatorics.BalancedRyser.Selection.SelectionConditionedLaw +OAI.Combinatorics.BalancedRyser.Selection.SelectionCylinder +OAI.Combinatorics.BalancedRyser.Selection.SelectionDraw +OAI.Combinatorics.BalancedRyser.Selection.SelectionEndpoint +OAI.Combinatorics.BalancedRyser.Selection.SelectionEndpoint2 +OAI.Combinatorics.BalancedRyser.Selection.SelectionFinalLaw +OAI.Combinatorics.BalancedRyser.Selection.SelectionFirstAbort +OAI.Combinatorics.BalancedRyser.Selection.SelectionFirstAbortFinal +OAI.Combinatorics.BalancedRyser.Selection.SelectionFlagTail +OAI.Combinatorics.BalancedRyser.Selection.SelectionHistory +OAI.Combinatorics.BalancedRyser.Selection.SelectionHistoryFinalLaw +OAI.Combinatorics.BalancedRyser.Selection.SelectionHistoryInvariant +OAI.Combinatorics.BalancedRyser.Selection.SelectionHistoryMarginal +OAI.Combinatorics.BalancedRyser.Selection.SelectionKernel +OAI.Combinatorics.BalancedRyser.Selection.SelectionKernel2 +OAI.Combinatorics.BalancedRyser.Selection.SelectionLaw +OAI.Combinatorics.BalancedRyser.Selection.SelectionLineCylinder +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancy +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancy2 +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyAgreement +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyBound +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyFinal +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyTail +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyTrack +OAI.Combinatorics.BalancedRyser.Selection.SelectionOccupancyUniform +OAI.Combinatorics.BalancedRyser.Selection.SelectionPostabort +OAI.Combinatorics.BalancedRyser.Selection.SelectionPostcheckTail +OAI.Combinatorics.BalancedRyser.Selection.SelectionPrecheck +OAI.Combinatorics.BalancedRyser.Selection.SelectionProcess +OAI.Combinatorics.BalancedRyser.Selection.SelectionProcessLaw +OAI.Combinatorics.BalancedRyser.Selection.SelectionProcessOccupancy +OAI.Combinatorics.BalancedRyser.Selection.SelectionProcessScales +OAI.Combinatorics.BalancedRyser.Selection.SelectionProcessThinning +OAI.Combinatorics.BalancedRyser.Selection.SelectionPushforward +OAI.Combinatorics.BalancedRyser.Selection.SelectionPushforward2 +OAI.Combinatorics.BalancedRyser.Selection.SelectionScales +OAI.Combinatorics.BalancedRyser.Selection.SelectionSourceConcentration +OAI.Combinatorics.BalancedRyser.Selection.SelectionState +OAI.Combinatorics.BalancedRyser.Selection.SelectionSuccessBound +OAI.Combinatorics.BalancedRyser.Selection.SelectionSuccessUniform +OAI.Combinatorics.BalancedRyser.Selection.SelectionTailCheck +OAI.Combinatorics.BalancedRyser.Selection.SelectionTailCompletion +OAI.Combinatorics.BalancedRyser.Selection.SelectionTailCylinder +OAI.Combinatorics.BalancedRyser.Selection.SelectionTailNumerics +OAI.Combinatorics.BalancedRyser.Selection.SelectionTailPotential +OAI.Combinatorics.BalancedRyser.Selection.SelectionThinning +OAI.Combinatorics.BalancedRyser.Selection.SelectionTrueCountConcentration +OAI.Combinatorics.BalancedRyser.Selection.SelectionUniformAssembly diff --git a/tasks/balanced-ryser/solution/reference.py b/tasks/balanced-ryser/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/balanced-ryser/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/balanced-ryser/solution/solve.sh b/tasks/balanced-ryser/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8b1ff1472e5cd891f445e64ca0d3963c1e13eb18 --- /dev/null +++ b/tasks/balanced-ryser/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BalancedRyser, i.e. module OAI.Combinatorics.BalancedRyser.Main and the +# 698 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.BalancedRyser.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BalancedRyser" diff --git a/tasks/balanced-ryser/task.toml b/tasks/balanced-ryser/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5322f1252c09da27326521c2792424caa2ace634 --- /dev/null +++ b/tasks/balanced-ryser/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/balanced-ryser" +version = "1.0.0" +description = "Prove BalancedRyser (openai/math family 162: Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BalancedRyser.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BalancedRyser" +family = "162" +family_title = "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures" +subject = "Combinatorics" +theorems = ["OAI.Balanced.main_result"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.BalancedRyser.Main" +reference_modules = 698 +reference_lean_bytes = 3897149 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1733 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15207 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/balanced-ryser/tests/Challenge.lean b/tasks/balanced-ryser/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9461a2049eb0dc02707e78b049d482211ecc8aa0 --- /dev/null +++ b/tasks/balanced-ryser/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +namespace Balanced +open scoped _root_.Balanced + +structure PartiteHypergraph (r n : ℕ) where + edges : Finset (Fin r → Fin n) + +namespace PartiteHypergraph + +variable {r n : ℕ} + +abbrev Vertex (r n : ℕ) := Fin r × Fin n + +def Covers (H : PartiteHypergraph r n) (C : Finset (Vertex r n)) : Prop := + ∀ e ∈ H.edges, ∃ i, (i, e i) ∈ C + +def Intersecting (H : PartiteHypergraph r n) : Prop := + H.edges.Nonempty ∧ ∀ e ∈ H.edges, ∀ f ∈ H.edges, ∃ i, e i = f i + +def Nonisolated (H : PartiteHypergraph r n) : Prop := + ∀ i v, ∃ e ∈ H.edges, e i = v + +def HasCoverNumber (H : PartiteHypergraph r n) (k : ℕ) : Prop := + (∃ C : Finset (Vertex r n), H.Covers C ∧ C.card = k) ∧ + ∀ C : Finset (Vertex r n), H.Covers C → k ≤ C.card + +end PartiteHypergraph + +def BalancedCounterexample (q : ℕ) : Prop := + ∃ H : PartiteHypergraph (q + 1) (q + 1), + H.Intersecting ∧ H.Nonisolated ∧ H.HasCoverNumber (q + 1) + +def MainResult : Prop := + ∃ q₀ : ℕ, ∀ q : ℕ, q₀ ≤ q → q.Prime → BalancedCounterexample q + +theorem main_result : MainResult := by + sorry + +end Balanced + +end OAI diff --git a/tasks/balanced-ryser/tests/grade.py b/tasks/balanced-ryser/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/balanced-ryser/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/balanced-ryser/tests/task.json b/tasks/balanced-ryser/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..94e21a464bfecb9faa0df8df18a95092d3eb0c20 --- /dev/null +++ b/tasks/balanced-ryser/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BalancedRyser", + "comparator": { + "theorem_names": [ + "OAI.Balanced.main_result" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14307 +} \ No newline at end of file diff --git a/tasks/balanced-ryser/tests/test.sh b/tasks/balanced-ryser/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/balanced-ryser/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/balanced-three-stack/environment/Dockerfile b/tasks/balanced-three-stack/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/balanced-three-stack/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/balanced-three-stack/environment/fetch_mathlib.sh b/tasks/balanced-three-stack/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/balanced-three-stack/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/balanced-three-stack/environment/lake-manifest.json b/tasks/balanced-three-stack/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/balanced-three-stack/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/balanced-three-stack/environment/lakefile.lean b/tasks/balanced-three-stack/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/balanced-three-stack/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/balanced-three-stack/environment/lean_setup.sh b/tasks/balanced-three-stack/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/balanced-three-stack/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/balanced-three-stack/environment/pack_submission.py b/tasks/balanced-three-stack/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/balanced-three-stack/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/balanced-three-stack/instruction.md b/tasks/balanced-three-stack/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..003b38c1d56f519e275b8c309558cb0c4353ded3 --- /dev/null +++ b/tasks/balanced-three-stack/instruction.md @@ -0,0 +1,290 @@ +# openai/math challenge `BalancedThreeStack` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `BalancedThreeStack`, also at `/opt/openai-math/challenges/BalancedThreeStack.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace BalancedTransport +namespace Recorder +inductive Direction where + | stay | left | right + deriving DecidableEq + +instance : Fintype Direction := + ⟨{.stay, .left, .right}, by intro d; cases d <;> simp⟩ + +structure Transition (Q Γ : Type*) where + state : Q + write : Γ + move : Direction +end Recorder + +structure FiniteMachine where + states : ℕ + symbols : ℕ + initial : Fin (states + 1) + blank : Fin (symbols + 1) + transition : Fin (states + 1) → Fin (symbols + 1) → + Option (Recorder.Transition (Fin (states + 1)) (Fin (symbols + 1))) + +abbrev Input (M : FiniteMachine) := List (Fin (M.symbols + 1)) + +structure TapeConfiguration (M : FiniteMachine) where + state : Fin (M.states + 1) + head : ℤ + tape : ℤ → Fin (M.symbols + 1) + +def initialConfiguration (M : FiniteMachine) (w : Input M) : TapeConfiguration M := + ⟨M.initial, 0, fun z => if 0 ≤ z then w[z.toNat]?.getD M.blank else M.blank⟩ + +def machineStep (M : FiniteMachine) (c : TapeConfiguration M) : Option (TapeConfiguration M) := + (M.transition c.state (c.tape c.head)).map fun v => + ⟨v.state, c.head + (match v.move with | .stay => 0 | .left => -1 | .right => 1), + Function.update c.tape c.head v.write⟩ + +def Halts (M : FiniteMachine) (w : Input M) : Prop := + ∃ c, Relation.ReflTransGen (fun c d => machineStep M c = some d) + (initialConfiguration M w) c ∧ machineStep M c = none + +def Recorder.Direction.number : Recorder.Direction → ℕ + | .stay => 0 + | .left => 1 + | .right => 2 + +def FiniteMachine.code (M : FiniteMachine) : ℕ := + Encodable.encode (M.states, M.symbols, M.initial.val, M.blank.val, + (List.finRange (M.states + 1)).map fun q => + (List.finRange (M.symbols + 1)).map fun a => + (M.transition q a).map fun v => (v.state.val, v.write.val, v.move.number)) + +def inputCode (M : FiniteMachine) (w : Input M) : ℕ := + Encodable.encode (M.code, w.map Fin.val) + +abbrev Space := Fin 3 → ℝ +abbrev Field (F : Type*) := ℝ → Space → F +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev Family (F : Type*) := (M : FiniteMachine) → Input M → F +abbrev MaterialFlow := ℝ → Space → Space +abbrev MultiIndex := List (Option (Fin 3)) +abbrev RationalPoint := ℚ × (Fin 3 → ℚ) + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] + +def timeD (v : Field F) : Field F := + fun t x => derivWithin (fun s => v s x) (Set.Ici 0) t + +def spaceD (i : Fin 3) (v : Field F) : Field F := + fun t x => fderiv ℝ (v t) x (Pi.single i 1) + +def mixedD : MultiIndex → Field F → Field F + | [], v => v + | none :: a, v => timeD (mixedD a v) + | some i :: a, v => spaceD i (mixedD a v) + +def spatialD : List (Fin 3) → Field F → Field F + | [], v => v + | i :: a, v => spaceD i (spatialD a v) + +def Smooth (v : Field F) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) (fun z : ℝ × Space => v z.1 z.2) (Set.Ici 0 ×ˢ Set.univ) + +def BoundedMixed (v : Field F) : Prop := + ∀ a : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ ∀ t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ C + +def CH (k : ℕ) (v : Field F) : Prop := + ∀ a : List (Fin 3), a.length ≤ k → + ∃ V : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → (V t : Space → F) =ᵐ[volume] spatialD a v t + +def C1L2 (v : Field F) : Prop := + ∃ V W : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ ContinuousOn W (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → + (V t : Space → F) =ᵐ[volume] v t ∧ + (W t : Space → F) =ᵐ[volume] timeD v t ∧ + HasDerivWithinAt V (W t) (Set.Ici 0) t + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i, spaceD i u t x i + +def laplacian (u : Velocity) : Velocity := + fun t x => ∑ i, spaceD i (spaceD i u) t x + +def convection (u : Velocity) : Velocity := + fun t x => ∑ i, (u t x i) • spaceD i u t x + +def gradient (p : Pressure) (t : ℝ) (x : Space) : Space := + fun i => spaceD i p t x + +def affineForce (f₀ f₁ : Velocity) (ν : ℝ) : Velocity := + fun t x => f₀ t x + ν • f₁ t x + +def inertialCoefficient (u : Velocity) : Velocity := + fun t x => timeD u t x + convection u t x + +def viscousCoefficient (u : Velocity) : Velocity := + fun t x => -laplacian u t x + +def ZeroDataSolution (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + Smooth u ∧ Smooth p ∧ + (∀ x, u 0 x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, div u t x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, + timeD u t x + convection u t x = + -gradient p t x + ν • laplacian u t x + f t x) + +def BoundedOnFiniteSlabs (u : Velocity) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, 0 ≤ C ∧ + ∀ t ∈ Set.Icc (0 : ℝ) T, ∀ x, + ‖u t x‖ ≤ C ∧ ∀ i : Fin 3, ‖spaceD i u t x‖ ≤ C + +def ComparisonClass (u : Velocity) (p : Pressure) : Prop := + CH 2 u ∧ C1L2 u ∧ BoundedOnFiniteSlabs u ∧ + ∃ c : ℝ → ℝ, CH 1 (fun t x => p t x - c t) + +def UniqueInComparison (ν : ℝ) (f U : Velocity) : Prop := + ∀ u p, ZeroDataSolution ν f u p → ComparisonClass u p → + (∀ t, 0 ≤ t → ∀ x, u t x = U t x) ∧ + (∀ t, 0 ≤ t → ∀ x y, p t x = p t y) + +def CommonCompactSupport (U f₀ f₁ : Velocity) : Prop := + ∃ K : Set Space, IsCompact K ∧ + ∀ t, 0 ≤ t → ∀ x, x ∉ K → U t x = 0 ∧ f₀ t x = 0 ∧ f₁ t x = 0 + +def PeriodicAfterOne (v : Velocity) : Prop := + ∀ t, 1 ≤ t → ∀ x, v (t + 1) x = v t x + +def IsMaterialFlow (u : Velocity) (X : MaterialFlow) : Prop := + (∀ a, X 0 a = a) ∧ + ∀ a t, 0 ≤ t → HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t + +def fixedLabel : Space := ![4, 0, 0] + +def observer : Set Space := + Set.pi Set.univ (fun _ : Fin 3 => Set.Ioo (-1 : ℝ) 2) + +def rationalSpace (x : Fin 3 → ℚ) : Space := fun i => (x i : ℝ) + +def error (n : ℕ) : ℝ := (2 : ℝ)⁻¹ ^ n + +def EffectiveFamily (v : Family Velocity) : Prop := + ∃ E : (ℕ × MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : (ℕ × MultiIndex) → ℕ, + ∃ R : ℕ → ℕ, + Computable E ∧ Computable b ∧ Computable R ∧ + (∀ M w a z n, 0 ≤ z.1 → ∀ i, + |(E (inputCode M w, a, z, n) i : ℝ) - + mixedD a (v M w) (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ M w a t, 0 ≤ t → ∀ x, + ‖mixedD a (v M w) t x‖ ≤ (b (inputCode M w, a) : ℝ)) ∧ + (∀ M w t, 0 ≤ t → ∀ x, + (R (inputCode M w) : ℝ) < ‖x‖ → v M w t x = 0) + +def EffectiveFieldIn (O : Set (ℕ →. ℕ)) (v : Velocity) : Prop := + ∃ E : (MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : MultiIndex → ℕ, + ComputableIn O E ∧ ComputableIn O b ∧ + (∀ a z n, 0 ≤ z.1 → ∀ i, + |(E (a, z, n) i : ℝ) - + mixedD a v (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ a t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ (b a : ℝ)) + +def RealName (name : ℕ → ℚ) (x : ℝ) : Prop := + ∀ n, |(name n : ℝ) - x| ≤ error n + +def ComputableReal (x : ℝ) : Prop := + ∃ name : ℕ → ℚ, Computable name ∧ RealName name x + +def nameOracle (name : ℕ → ℚ) : ℕ →. ℕ := + fun n => Part.some (Encodable.encode (name n)) + +end +end BalancedTransport + +namespace BalancedTransport + +theorem balanced_three_stack_realization : + ∃ U f₀ f₁ : Family Velocity, + ∃ X : Family MaterialFlow, + ∃ repeated : FiniteMachine → Velocity, + EffectiveFamily U ∧ EffectiveFamily f₀ ∧ EffectiveFamily f₁ ∧ + (∀ M, Function.Periodic (repeated M) 1) ∧ + ∀ (M : FiniteMachine) (w : Input M), + Smooth (U M w) ∧ Smooth (f₀ M w) ∧ Smooth (f₁ M w) ∧ + f₀ M w = inertialCoefficient (U M w) ∧ + f₁ M w = viscousCoefficient (U M w) ∧ + CommonCompactSupport (U M w) (f₀ M w) (f₁ M w) ∧ + BoundedMixed (U M w) ∧ + PeriodicAfterOne (U M w) ∧ + (∀ t, 1 ≤ t → ∀ x, U M w t x = repeated M t x) ∧ + ComparisonClass (U M w) (fun _ _ => 0) ∧ + IsMaterialFlow (U M w) (X M w) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ X M w t fixedLabel ∈ observer) ↔ Halts M w) ∧ + ∀ ν : ℝ, 0 < ν → + let f := affineForce (f₀ M w) (f₁ M w) ν + ZeroDataSolution ν f (U M w) (fun _ _ => 0) ∧ + Smooth f ∧ BoundedMixed f ∧ PeriodicAfterOne f ∧ + UniqueInComparison ν f (U M w) ∧ + (ComputableReal ν → EffectiveFieldIn ∅ f) ∧ + (∀ name : ℕ → ℚ, RealName name ν → EffectiveFieldIn {nameOracle name} f) := by + sorry + +end BalancedTransport + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BalancedThreeStack.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BalancedTransport.balanced_three_stack_realization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/balanced-three-stack/solution/closure.txt b/tasks/balanced-three-stack/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d87f6d4892f06758dccc01aa579cbfcd6c64dd5 --- /dev/null +++ b/tasks/balanced-three-stack/solution/closure.txt @@ -0,0 +1,60 @@ +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.BoxCoding +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Bridge +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.CompactFamilies +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Comparison +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.CompiledGeometry +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ComputabilityRules +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ComputableInitial +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Deformation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveArithmetic +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveConstruction +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveExp +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveGluing +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveLog +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Elementary +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryCalculus +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryFields +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryMotion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryParking +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryRouting +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryTemplate +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Energy +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EnergyCurve +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EnergySlice +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FieldBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FiniteSimulator +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FlatBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Loading +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MachineHalting +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MachineRecursion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Material +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Model +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Motion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MotionField +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericAlgebra +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericDifferentiation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericEvaluation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericPrograms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericScopes +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.OracleComputability +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Parking +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Periodic +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.PrefixCoding +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RationalAlgorithms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Realization +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RecorderRules +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RecorderSimulation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RelativeForce +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ResidualRegularity +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RhoAlgorithms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Routing +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Sobolev +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.TemporalJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.TimeRegularity +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.UniversalInput +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.UniversalMachine +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Work diff --git a/tasks/balanced-three-stack/solution/reference.py b/tasks/balanced-three-stack/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/balanced-three-stack/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/balanced-three-stack/solution/solve.sh b/tasks/balanced-three-stack/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..064a88b94e9e0677ce61541867b020b8802dd039 --- /dev/null +++ b/tasks/balanced-three-stack/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BalancedThreeStack, i.e. module OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult and the +# 60 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BalancedThreeStack" diff --git a/tasks/balanced-three-stack/task.toml b/tasks/balanced-three-stack/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..375a51d06f12ebfac34332a204b3b32c94d7475a --- /dev/null +++ b/tasks/balanced-three-stack/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/balanced-three-stack" +version = "1.0.0" +description = "Prove BalancedThreeStack (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BalancedThreeStack.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BalancedThreeStack" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.BalancedTransport.balanced_three_stack_realization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult" +reference_modules = 60 +reference_lean_bytes = 495983 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1956 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12146 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/balanced-three-stack/tests/Challenge.lean b/tasks/balanced-three-stack/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9fb177acd0d4c5b6efc7cd6f460ca6289a950195 --- /dev/null +++ b/tasks/balanced-three-stack/tests/Challenge.lean @@ -0,0 +1,239 @@ +import Mathlib + +namespace OAI + +namespace BalancedTransport +namespace Recorder +inductive Direction where + | stay | left | right + deriving DecidableEq + +instance : Fintype Direction := + ⟨{.stay, .left, .right}, by intro d; cases d <;> simp⟩ + +structure Transition (Q Γ : Type*) where + state : Q + write : Γ + move : Direction +end Recorder + +structure FiniteMachine where + states : ℕ + symbols : ℕ + initial : Fin (states + 1) + blank : Fin (symbols + 1) + transition : Fin (states + 1) → Fin (symbols + 1) → + Option (Recorder.Transition (Fin (states + 1)) (Fin (symbols + 1))) + +abbrev Input (M : FiniteMachine) := List (Fin (M.symbols + 1)) + +structure TapeConfiguration (M : FiniteMachine) where + state : Fin (M.states + 1) + head : ℤ + tape : ℤ → Fin (M.symbols + 1) + +def initialConfiguration (M : FiniteMachine) (w : Input M) : TapeConfiguration M := + ⟨M.initial, 0, fun z => if 0 ≤ z then w[z.toNat]?.getD M.blank else M.blank⟩ + +def machineStep (M : FiniteMachine) (c : TapeConfiguration M) : Option (TapeConfiguration M) := + (M.transition c.state (c.tape c.head)).map fun v => + ⟨v.state, c.head + (match v.move with | .stay => 0 | .left => -1 | .right => 1), + Function.update c.tape c.head v.write⟩ + +def Halts (M : FiniteMachine) (w : Input M) : Prop := + ∃ c, Relation.ReflTransGen (fun c d => machineStep M c = some d) + (initialConfiguration M w) c ∧ machineStep M c = none + +def Recorder.Direction.number : Recorder.Direction → ℕ + | .stay => 0 + | .left => 1 + | .right => 2 + +def FiniteMachine.code (M : FiniteMachine) : ℕ := + Encodable.encode (M.states, M.symbols, M.initial.val, M.blank.val, + (List.finRange (M.states + 1)).map fun q => + (List.finRange (M.symbols + 1)).map fun a => + (M.transition q a).map fun v => (v.state.val, v.write.val, v.move.number)) + +def inputCode (M : FiniteMachine) (w : Input M) : ℕ := + Encodable.encode (M.code, w.map Fin.val) + +abbrev Space := Fin 3 → ℝ +abbrev Field (F : Type*) := ℝ → Space → F +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev Family (F : Type*) := (M : FiniteMachine) → Input M → F +abbrev MaterialFlow := ℝ → Space → Space +abbrev MultiIndex := List (Option (Fin 3)) +abbrev RationalPoint := ℚ × (Fin 3 → ℚ) + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] + +def timeD (v : Field F) : Field F := + fun t x => derivWithin (fun s => v s x) (Set.Ici 0) t + +def spaceD (i : Fin 3) (v : Field F) : Field F := + fun t x => fderiv ℝ (v t) x (Pi.single i 1) + +def mixedD : MultiIndex → Field F → Field F + | [], v => v + | none :: a, v => timeD (mixedD a v) + | some i :: a, v => spaceD i (mixedD a v) + +def spatialD : List (Fin 3) → Field F → Field F + | [], v => v + | i :: a, v => spaceD i (spatialD a v) + +def Smooth (v : Field F) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) (fun z : ℝ × Space => v z.1 z.2) (Set.Ici 0 ×ˢ Set.univ) + +def BoundedMixed (v : Field F) : Prop := + ∀ a : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ ∀ t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ C + +def CH (k : ℕ) (v : Field F) : Prop := + ∀ a : List (Fin 3), a.length ≤ k → + ∃ V : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → (V t : Space → F) =ᵐ[volume] spatialD a v t + +def C1L2 (v : Field F) : Prop := + ∃ V W : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ ContinuousOn W (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → + (V t : Space → F) =ᵐ[volume] v t ∧ + (W t : Space → F) =ᵐ[volume] timeD v t ∧ + HasDerivWithinAt V (W t) (Set.Ici 0) t + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i, spaceD i u t x i + +def laplacian (u : Velocity) : Velocity := + fun t x => ∑ i, spaceD i (spaceD i u) t x + +def convection (u : Velocity) : Velocity := + fun t x => ∑ i, (u t x i) • spaceD i u t x + +def gradient (p : Pressure) (t : ℝ) (x : Space) : Space := + fun i => spaceD i p t x + +def affineForce (f₀ f₁ : Velocity) (ν : ℝ) : Velocity := + fun t x => f₀ t x + ν • f₁ t x + +def inertialCoefficient (u : Velocity) : Velocity := + fun t x => timeD u t x + convection u t x + +def viscousCoefficient (u : Velocity) : Velocity := + fun t x => -laplacian u t x + +def ZeroDataSolution (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + Smooth u ∧ Smooth p ∧ + (∀ x, u 0 x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, div u t x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, + timeD u t x + convection u t x = + -gradient p t x + ν • laplacian u t x + f t x) + +def BoundedOnFiniteSlabs (u : Velocity) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, 0 ≤ C ∧ + ∀ t ∈ Set.Icc (0 : ℝ) T, ∀ x, + ‖u t x‖ ≤ C ∧ ∀ i : Fin 3, ‖spaceD i u t x‖ ≤ C + +def ComparisonClass (u : Velocity) (p : Pressure) : Prop := + CH 2 u ∧ C1L2 u ∧ BoundedOnFiniteSlabs u ∧ + ∃ c : ℝ → ℝ, CH 1 (fun t x => p t x - c t) + +def UniqueInComparison (ν : ℝ) (f U : Velocity) : Prop := + ∀ u p, ZeroDataSolution ν f u p → ComparisonClass u p → + (∀ t, 0 ≤ t → ∀ x, u t x = U t x) ∧ + (∀ t, 0 ≤ t → ∀ x y, p t x = p t y) + +def CommonCompactSupport (U f₀ f₁ : Velocity) : Prop := + ∃ K : Set Space, IsCompact K ∧ + ∀ t, 0 ≤ t → ∀ x, x ∉ K → U t x = 0 ∧ f₀ t x = 0 ∧ f₁ t x = 0 + +def PeriodicAfterOne (v : Velocity) : Prop := + ∀ t, 1 ≤ t → ∀ x, v (t + 1) x = v t x + +def IsMaterialFlow (u : Velocity) (X : MaterialFlow) : Prop := + (∀ a, X 0 a = a) ∧ + ∀ a t, 0 ≤ t → HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t + +def fixedLabel : Space := ![4, 0, 0] + +def observer : Set Space := + Set.pi Set.univ (fun _ : Fin 3 => Set.Ioo (-1 : ℝ) 2) + +def rationalSpace (x : Fin 3 → ℚ) : Space := fun i => (x i : ℝ) + +def error (n : ℕ) : ℝ := (2 : ℝ)⁻¹ ^ n + +def EffectiveFamily (v : Family Velocity) : Prop := + ∃ E : (ℕ × MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : (ℕ × MultiIndex) → ℕ, + ∃ R : ℕ → ℕ, + Computable E ∧ Computable b ∧ Computable R ∧ + (∀ M w a z n, 0 ≤ z.1 → ∀ i, + |(E (inputCode M w, a, z, n) i : ℝ) - + mixedD a (v M w) (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ M w a t, 0 ≤ t → ∀ x, + ‖mixedD a (v M w) t x‖ ≤ (b (inputCode M w, a) : ℝ)) ∧ + (∀ M w t, 0 ≤ t → ∀ x, + (R (inputCode M w) : ℝ) < ‖x‖ → v M w t x = 0) + +def EffectiveFieldIn (O : Set (ℕ →. ℕ)) (v : Velocity) : Prop := + ∃ E : (MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : MultiIndex → ℕ, + ComputableIn O E ∧ ComputableIn O b ∧ + (∀ a z n, 0 ≤ z.1 → ∀ i, + |(E (a, z, n) i : ℝ) - + mixedD a v (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ a t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ (b a : ℝ)) + +def RealName (name : ℕ → ℚ) (x : ℝ) : Prop := + ∀ n, |(name n : ℝ) - x| ≤ error n + +def ComputableReal (x : ℝ) : Prop := + ∃ name : ℕ → ℚ, Computable name ∧ RealName name x + +def nameOracle (name : ℕ → ℚ) : ℕ →. ℕ := + fun n => Part.some (Encodable.encode (name n)) + +end +end BalancedTransport + +namespace BalancedTransport + +theorem balanced_three_stack_realization : + ∃ U f₀ f₁ : Family Velocity, + ∃ X : Family MaterialFlow, + ∃ repeated : FiniteMachine → Velocity, + EffectiveFamily U ∧ EffectiveFamily f₀ ∧ EffectiveFamily f₁ ∧ + (∀ M, Function.Periodic (repeated M) 1) ∧ + ∀ (M : FiniteMachine) (w : Input M), + Smooth (U M w) ∧ Smooth (f₀ M w) ∧ Smooth (f₁ M w) ∧ + f₀ M w = inertialCoefficient (U M w) ∧ + f₁ M w = viscousCoefficient (U M w) ∧ + CommonCompactSupport (U M w) (f₀ M w) (f₁ M w) ∧ + BoundedMixed (U M w) ∧ + PeriodicAfterOne (U M w) ∧ + (∀ t, 1 ≤ t → ∀ x, U M w t x = repeated M t x) ∧ + ComparisonClass (U M w) (fun _ _ => 0) ∧ + IsMaterialFlow (U M w) (X M w) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ X M w t fixedLabel ∈ observer) ↔ Halts M w) ∧ + ∀ ν : ℝ, 0 < ν → + let f := affineForce (f₀ M w) (f₁ M w) ν + ZeroDataSolution ν f (U M w) (fun _ _ => 0) ∧ + Smooth f ∧ BoundedMixed f ∧ PeriodicAfterOne f ∧ + UniqueInComparison ν f (U M w) ∧ + (ComputableReal ν → EffectiveFieldIn ∅ f) ∧ + (∀ name : ℕ → ℚ, RealName name ν → EffectiveFieldIn {nameOracle name} f) := by + sorry + +end BalancedTransport + +end OAI diff --git a/tasks/balanced-three-stack/tests/grade.py b/tasks/balanced-three-stack/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/balanced-three-stack/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/balanced-three-stack/tests/task.json b/tasks/balanced-three-stack/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3e45874fabd58b210b83faec8ef52cc8c5e3519a --- /dev/null +++ b/tasks/balanced-three-stack/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BalancedThreeStack", + "comparator": { + "theorem_names": [ + "OAI.BalancedTransport.balanced_three_stack_realization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11246 +} \ No newline at end of file diff --git a/tasks/balanced-three-stack/tests/test.sh b/tasks/balanced-three-stack/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/balanced-three-stack/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ball-packing-necessity/environment/Dockerfile b/tasks/ball-packing-necessity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ball-packing-necessity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ball-packing-necessity/environment/fetch_mathlib.sh b/tasks/ball-packing-necessity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ball-packing-necessity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ball-packing-necessity/environment/lake-manifest.json b/tasks/ball-packing-necessity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ball-packing-necessity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ball-packing-necessity/environment/lakefile.lean b/tasks/ball-packing-necessity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ball-packing-necessity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ball-packing-necessity/environment/lean_setup.sh b/tasks/ball-packing-necessity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ball-packing-necessity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ball-packing-necessity/environment/pack_submission.py b/tasks/ball-packing-necessity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ball-packing-necessity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ball-packing-necessity/instruction.md b/tasks/ball-packing-necessity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37997bfa6cffc1a8c74b604f8897f537fddf7240 --- /dev/null +++ b/tasks/ball-packing-necessity/instruction.md @@ -0,0 +1,96 @@ +# openai/math challenge `BallPackingNecessity` (family 343) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 343 of the release, *Sharp symplectic ball-packing criteria in higher dimensions* +(Differential geometry). The family as a whole: Resolves the Siegel–Yao conjecture for arbitrary capacities in every dimension $2n\ge6$. Finitely many closed symplectic balls of capacities $R_1,\ldots,R_k$ embed disjointly into an open ball of capacity $R$ exactly when $\sum_iR_i^n f x) ∧ + ∀ x ∈ U, ∀ u v : Phase n, + standardForm (fderiv ℝ f x u) (fderiv ℝ f x v) = standardForm u v + + +def HasPacking (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + ∃ (U : Fin k → Set (Phase n)) (f : Fin k → Phase n → Phase n), + (∀ i, closedBall n (r i) ⊆ U i ∧ SymplecticOn (U i) (f i) ∧ + Set.MapsTo (f i) (closedBall n (r i)) (openBall n R)) ∧ + (∀ i j, i ≠ j → + Disjoint (f i '' closedBall n (r i)) (f j '' closedBall n (r j))) + +def PackingInequalities (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + (∑ i, r i ^ n) < R ^ n ∧ ∀ i j, i ≠ j → r i + r j < R + +theorem packing_necessity (n k : ℕ) (hn : 3 ≤ n) (hk : 1 ≤ k) + (R : ℝ) (r : Fin k → ℝ) (hR : 0 < R) (hr : ∀ i, 0 < r i) + (hp : HasPacking n k R r) : PackingInequalities n k R r := by + sorry + +end HigherDimensionalBallPacking + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BallPackingNecessity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HigherDimensionalBallPacking.packing_necessity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ball-packing-necessity/solution/closure.txt b/tasks/ball-packing-necessity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f70e16a0e21cf72f33e75542866877045ef3e7ba --- /dev/null +++ b/tasks/ball-packing-necessity/solution/closure.txt @@ -0,0 +1,65 @@ +OAI.Geometry.BallPacking.Cauchy.GreenFormula +OAI.Geometry.BallPacking.Compactness.AffineCorrectionInfinity +OAI.Geometry.BallPacking.Compactness.GradientBounds +OAI.Geometry.BallPacking.Compactness.JetCauchy +OAI.Geometry.BallPacking.Energy.CircularEnergy +OAI.Geometry.BallPacking.Energy.ResidualEnergy +OAI.Geometry.BallPacking.Fredholm.CompactFredholmAlternative +OAI.Geometry.BallPacking.Fredholm.FiniteExtensions +OAI.Geometry.BallPacking.Fredholm.FrameFredholm +OAI.Geometry.BallPacking.Fredholm.FreeLinearization +OAI.Geometry.BallPacking.Fredholm.PointwiseMarkedCR +OAI.Geometry.BallPacking.Fredholm.TranslationContinuity +OAI.Geometry.BallPacking.Holder.BanachSpace +OAI.Geometry.BallPacking.Holder.HolderTaylor +OAI.Geometry.BallPacking.Holder.KernelSchauder +OAI.Geometry.BallPacking.Holder.MarkedFrame +OAI.Geometry.BallPacking.Holder.MarkedJets +OAI.Geometry.BallPacking.Holder.NonlinearCR +OAI.Geometry.BallPacking.Holder.SchauderSplit +OAI.Geometry.BallPacking.Necessity.AffineBubble +OAI.Geometry.BallPacking.Necessity.AffineEnergy +OAI.Geometry.BallPacking.Necessity.AffineSlopes +OAI.Geometry.BallPacking.Necessity.C1Energy +OAI.Geometry.BallPacking.Necessity.CauchyDuality +OAI.Geometry.BallPacking.Necessity.CompactContinuation +OAI.Geometry.BallPacking.Necessity.DensityBounds +OAI.Geometry.BallPacking.Necessity.DensityExistence +OAI.Geometry.BallPacking.Necessity.DensityLimits +OAI.Geometry.BallPacking.Necessity.DensityMaps +OAI.Geometry.BallPacking.Necessity.DensityResidual +OAI.Geometry.BallPacking.Necessity.EqualDimension +OAI.Geometry.BallPacking.Necessity.FiniteContinuation +OAI.Geometry.BallPacking.Necessity.FiniteReduction +OAI.Geometry.BallPacking.Necessity.FrameFredholm +OAI.Geometry.BallPacking.Necessity.FramedCompactness +OAI.Geometry.BallPacking.Necessity.FreezeJ +OAI.Geometry.BallPacking.Necessity.FrozenInverse +OAI.Geometry.BallPacking.Necessity.FrozenOperators +OAI.Geometry.BallPacking.Necessity.FrozenResponse +OAI.Geometry.BallPacking.Necessity.GlobalArea +OAI.Geometry.BallPacking.Necessity.GradientLimits +OAI.Geometry.BallPacking.Necessity.HolderCalculus +OAI.Geometry.BallPacking.Necessity.HolderCompactness +OAI.Geometry.BallPacking.Necessity.HolderCompletion +OAI.Geometry.BallPacking.Necessity.KernelMoments +OAI.Geometry.BallPacking.Necessity.LocalCharts +OAI.Geometry.BallPacking.Necessity.Main +OAI.Geometry.BallPacking.Necessity.MarkedInverse +OAI.Geometry.BallPacking.Necessity.MarkedProfiles +OAI.Geometry.BallPacking.Necessity.NonlinearCR +OAI.Geometry.BallPacking.Necessity.OrbitRegularity +OAI.Geometry.BallPacking.Necessity.PackingNecessity +OAI.Geometry.BallPacking.Necessity.PlanarEnergy +OAI.Geometry.BallPacking.Necessity.Properness +OAI.Geometry.BallPacking.Necessity.SchauderBounds +OAI.Geometry.BallPacking.Necessity.SquareBounds +OAI.Geometry.BallPacking.Necessity.TangentLimits +OAI.Geometry.BallPacking.Rigidity.Adapted +OAI.Geometry.BallPacking.Rigidity.AngularPoles +OAI.Geometry.BallPacking.Rigidity.CompatibleStructures +OAI.Geometry.BallPacking.Rigidity.CorrectedInfinity +OAI.Geometry.BallPacking.Rigidity.Correction +OAI.Geometry.BallPacking.Rigidity.CurveArea +OAI.Geometry.BallPacking.Rigidity.PlanarResidueCutoff +OAI.Geometry.BallPacking.Rigidity.RadialForm diff --git a/tasks/ball-packing-necessity/solution/reference.py b/tasks/ball-packing-necessity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ball-packing-necessity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ball-packing-necessity/solution/solve.sh b/tasks/ball-packing-necessity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6a2d79d4cc0b9120681a93c328354c3621a9c13 --- /dev/null +++ b/tasks/ball-packing-necessity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BallPackingNecessity, i.e. module OAI.Geometry.BallPacking.Necessity.Main and the +# 65 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.BallPacking.Necessity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BallPackingNecessity" diff --git a/tasks/ball-packing-necessity/task.toml b/tasks/ball-packing-necessity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0d80a2c77583730165768d4db5b1ed7fa6282257 --- /dev/null +++ b/tasks/ball-packing-necessity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ball-packing-necessity" +version = "1.0.0" +description = "Prove BallPackingNecessity (openai/math family 343: Sharp symplectic ball-packing criteria in higher dimensions) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BallPackingNecessity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BallPackingNecessity" +family = "343" +family_title = "Sharp symplectic ball-packing criteria in higher dimensions" +subject = "Differential geometry" +theorems = ["OAI.HigherDimensionalBallPacking.packing_necessity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.BallPacking.Necessity.Main" +reference_modules = 65 +reference_lean_bytes = 1673682 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1874 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13206 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ball-packing-necessity/tests/Challenge.lean b/tasks/ball-packing-necessity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6925cc7c92af8b479faf5c89425e5da8998f4370 --- /dev/null +++ b/tasks/ball-packing-necessity/tests/Challenge.lean @@ -0,0 +1,45 @@ +import Mathlib + +namespace OAI + +namespace HigherDimensionalBallPacking +open scoped ContDiff + +abbrev Phase (n : ℕ) := Fin n → ℂ + +noncomputable def capacity {n : ℕ} (z : Phase n) : ℝ := + Real.pi * ∑ j, Complex.normSq (z j) + +def closedBall (n : ℕ) (r : ℝ) : Set (Phase n) := {z | capacity z ≤ r} + +def openBall (n : ℕ) (r : ℝ) : Set (Phase n) := {z | capacity z < r} + +noncomputable def standardForm {n : ℕ} (u v : Phase n) : ℝ := + ∑ j, ((u j).re * (v j).im - (u j).im * (v j).re) + + +def SymplecticOn {n : ℕ} (U : Set (Phase n)) (f : Phase n → Phase n) : Prop := + IsOpen U ∧ ContDiffOn ℝ ∞ f U ∧ + Topology.IsEmbedding (fun x : U => f x) ∧ + ∀ x ∈ U, ∀ u v : Phase n, + standardForm (fderiv ℝ f x u) (fderiv ℝ f x v) = standardForm u v + + +def HasPacking (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + ∃ (U : Fin k → Set (Phase n)) (f : Fin k → Phase n → Phase n), + (∀ i, closedBall n (r i) ⊆ U i ∧ SymplecticOn (U i) (f i) ∧ + Set.MapsTo (f i) (closedBall n (r i)) (openBall n R)) ∧ + (∀ i j, i ≠ j → + Disjoint (f i '' closedBall n (r i)) (f j '' closedBall n (r j))) + +def PackingInequalities (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + (∑ i, r i ^ n) < R ^ n ∧ ∀ i j, i ≠ j → r i + r j < R + +theorem packing_necessity (n k : ℕ) (hn : 3 ≤ n) (hk : 1 ≤ k) + (R : ℝ) (r : Fin k → ℝ) (hR : 0 < R) (hr : ∀ i, 0 < r i) + (hp : HasPacking n k R r) : PackingInequalities n k R r := by + sorry + +end HigherDimensionalBallPacking + +end OAI diff --git a/tasks/ball-packing-necessity/tests/grade.py b/tasks/ball-packing-necessity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ball-packing-necessity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ball-packing-necessity/tests/task.json b/tasks/ball-packing-necessity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b1d2c6c2dfada0301847e75a3ff1e253964bd205 --- /dev/null +++ b/tasks/ball-packing-necessity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BallPackingNecessity", + "comparator": { + "theorem_names": [ + "OAI.HigherDimensionalBallPacking.packing_necessity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12306 +} \ No newline at end of file diff --git a/tasks/ball-packing-necessity/tests/test.sh b/tasks/ball-packing-necessity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ball-packing-necessity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ball-packing/environment/Dockerfile b/tasks/ball-packing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ball-packing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ball-packing/environment/fetch_mathlib.sh b/tasks/ball-packing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ball-packing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ball-packing/environment/lake-manifest.json b/tasks/ball-packing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ball-packing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ball-packing/environment/lakefile.lean b/tasks/ball-packing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ball-packing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ball-packing/environment/lean_setup.sh b/tasks/ball-packing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ball-packing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ball-packing/environment/pack_submission.py b/tasks/ball-packing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ball-packing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ball-packing/instruction.md b/tasks/ball-packing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b065c4892a20999c25cdf016d6b55a10d448fc32 --- /dev/null +++ b/tasks/ball-packing/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `BallPacking` (family 343) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 343 of the release, *Sharp symplectic ball-packing criteria in higher dimensions* +(Differential geometry). The family as a whole: Resolves the Siegel–Yao conjecture for arbitrary capacities in every dimension $2n\ge6$. Finitely many closed symplectic balls of capacities $R_1,\ldots,R_k$ embed disjointly into an open ball of capacity $R$ exactly when $\sum_iR_i^n f x) ∧ + ∀ x ∈ U, ∀ u v : Phase n, + standardForm (fderiv ℝ f x u) (fderiv ℝ f x v) = standardForm u v + +def HasPacking (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + ∃ (U : Fin k → Set (Phase n)) (f : Fin k → Phase n → Phase n), + (∀ i, closedBall n (r i) ⊆ U i ∧ SymplecticOn (U i) (f i) ∧ + Set.MapsTo (f i) (closedBall n (r i)) (openBall n R)) ∧ + (∀ i j, i ≠ j → + Disjoint (f i '' closedBall n (r i)) (f j '' closedBall n (r j))) + +def PackingInequalities (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + (∑ i, r i ^ n) < R ^ n ∧ ∀ i j, i ≠ j → r i + r j < R + +theorem main_theorem (n k : ℕ) (hn : 3 ≤ n) (hk : 1 ≤ k) + (R : ℝ) (r : Fin k → ℝ) (hR : 0 < R) (hr : ∀ i, 0 < r i) : + HasPacking n k R r ↔ PackingInequalities n k R r := by + sorry + +end HigherDimensionalBallPacking + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BallPacking.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HigherDimensionalBallPacking.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ball-packing/solution/closure.txt b/tasks/ball-packing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..105560e0d2aca4b383c0288794e6b818a6960003 --- /dev/null +++ b/tasks/ball-packing/solution/closure.txt @@ -0,0 +1,169 @@ +OAI.Geometry.BallPacking.Annuli.AnnularChartNormalization +OAI.Geometry.BallPacking.Annuli.AnnularCurvaturePrimitive +OAI.Geometry.BallPacking.Annuli.AnnularEmbeddedChart +OAI.Geometry.BallPacking.Annuli.AnnularHandleCurvature +OAI.Geometry.BallPacking.Annuli.AnnularHandleDensity +OAI.Geometry.BallPacking.Annuli.AnnularMean +OAI.Geometry.BallPacking.Annuli.BaseHorizontalForms +OAI.Geometry.BallPacking.Annuli.CircleHandleBump +OAI.Geometry.BallPacking.Annuli.CylinderAnnularNormalization +OAI.Geometry.BallPacking.Annuli.LayerCoordinates +OAI.Geometry.BallPacking.Annuli.QuadricCylinderChart +OAI.Geometry.BallPacking.Annuli.QuadricNormalizedCycle +OAI.Geometry.BallPacking.Annuli.SurfacePathPositivity +OAI.Geometry.BallPacking.Annuli.SurfaceSuspensionCoefficients +OAI.Geometry.BallPacking.BallMaps.CubicBubbleSeparated +OAI.Geometry.BallPacking.BallMaps.QuadricLargeAmbientPacking +OAI.Geometry.BallPacking.BallMaps.QuadricRelativeShellFlow +OAI.Geometry.BallPacking.BallMaps.SixCubicInnerNormalPacking +OAI.Geometry.BallPacking.BallMaps.SphereCartesianDescent +OAI.Geometry.BallPacking.Campanato.MeasureEnergy +OAI.Geometry.BallPacking.Campanato.TranslatedSquare +OAI.Geometry.BallPacking.Cauchy.GreenFormula +OAI.Geometry.BallPacking.CircleAction.CircleRelativeOneForm +OAI.Geometry.BallPacking.CircleAction.CircleRelativeRadialMoser +OAI.Geometry.BallPacking.CircleAction.DegreeCircleCovariance +OAI.Geometry.BallPacking.Compactness.AffineCorrectionInfinity +OAI.Geometry.BallPacking.Compactness.FrozenCR +OAI.Geometry.BallPacking.Compactness.GradientBounds +OAI.Geometry.BallPacking.Compactness.JetCauchy +OAI.Geometry.BallPacking.Compactness.MarkedCurves +OAI.Geometry.BallPacking.Compactness.ResidualCauchy +OAI.Geometry.BallPacking.Continuation.CompatibleHomotopy +OAI.Geometry.BallPacking.Continuation.ParameterizedImplicit +OAI.Geometry.BallPacking.Continuation.ProperPaths +OAI.Geometry.BallPacking.Degree.BoxContinuation +OAI.Geometry.BallPacking.Degree.ChartFormZeroExtension +OAI.Geometry.BallPacking.Degree.EuclideanAtlasTransport +OAI.Geometry.BallPacking.Degree.HomotopyFlux +OAI.Geometry.BallPacking.DiskMaps.CompactEmbeddingIsotopy +OAI.Geometry.BallPacking.DiskMaps.CubicAreaExhaustion +OAI.Geometry.BallPacking.DiskMaps.FlatIsotopy +OAI.Geometry.BallPacking.DiskMaps.NormalizedRoundedBoxes +OAI.Geometry.BallPacking.DiskMaps.ParameterRelativeDiskMoser +OAI.Geometry.BallPacking.DiskMaps.SmoothConvexSelection +OAI.Geometry.BallPacking.DiskMaps.SmoothInverse +OAI.Geometry.BallPacking.Energy.CircularEnergy +OAI.Geometry.BallPacking.Energy.ResidualEnergy +OAI.Geometry.BallPacking.Flows.AnnularInverseDomain +OAI.Geometry.BallPacking.Flows.AnnularPathGerms +OAI.Geometry.BallPacking.Flows.FlowSmoothExtension +OAI.Geometry.BallPacking.Flows.ManifoldFormTransport +OAI.Geometry.BallPacking.Flows.NonautonomousManifoldFlow +OAI.Geometry.BallPacking.Flows.TimeSteps +OAI.Geometry.BallPacking.Forms.ChartSupportedDensity +OAI.Geometry.BallPacking.Forms.CubicFubiniStudy +OAI.Geometry.BallPacking.Forms.FixedSpatialIntegral +OAI.Geometry.BallPacking.Forms.HorizontalCoupling +OAI.Geometry.BallPacking.Forms.ManifoldExteriorAlgebra +OAI.Geometry.BallPacking.Forms.ManifoldFormTransport +OAI.Geometry.BallPacking.Forms.ManifoldMapDifferential +OAI.Geometry.BallPacking.Forms.QuadricInfinityPrimitive +OAI.Geometry.BallPacking.Forms.SpatialOneForm +OAI.Geometry.BallPacking.Fredholm.CompactFredholmAlternative +OAI.Geometry.BallPacking.Fredholm.FiniteExtensions +OAI.Geometry.BallPacking.Fredholm.FrameFredholm +OAI.Geometry.BallPacking.Fredholm.FreeLinearization +OAI.Geometry.BallPacking.Fredholm.NonlinearReduction +OAI.Geometry.BallPacking.Fredholm.PointwiseMarkedCR +OAI.Geometry.BallPacking.Fredholm.ProjectionTimeGrid +OAI.Geometry.BallPacking.Fredholm.SurjectiveParametricReduction +OAI.Geometry.BallPacking.Fredholm.TranslationContinuity +OAI.Geometry.BallPacking.Hamiltonian.AnnularDensityMass +OAI.Geometry.BallPacking.Hamiltonian.CartesianMomentSlices +OAI.Geometry.BallPacking.Hamiltonian.LiftedCompact +OAI.Geometry.BallPacking.Hamiltonian.ScaledPlanarMotion +OAI.Geometry.BallPacking.Holder.BanachSpace +OAI.Geometry.BallPacking.Holder.HolderTaylor +OAI.Geometry.BallPacking.Holder.KernelSchauder +OAI.Geometry.BallPacking.Holder.MarkedFrame +OAI.Geometry.BallPacking.Holder.MarkedJets +OAI.Geometry.BallPacking.Holder.NonlinearCR +OAI.Geometry.BallPacking.Holder.SchauderSplit +OAI.Geometry.BallPacking.Hopf.AffineHopfRestriction +OAI.Geometry.BallPacking.Hopf.DegreeHopfDeformation +OAI.Geometry.BallPacking.Hopf.DegreeRelativeShell +OAI.Geometry.BallPacking.Hopf.SixLargeQuadricPacking +OAI.Geometry.BallPacking.Kahler.PhaseArea +OAI.Geometry.BallPacking.Layers.ConstructedSurfaceLayers +OAI.Geometry.BallPacking.Layers.LayerAreaForm +OAI.Geometry.BallPacking.Layers.LayerBallEmbedding +OAI.Geometry.BallPacking.Layers.ParametricNestedDisks +OAI.Geometry.BallPacking.Layers.PlanarRotation +OAI.Geometry.BallPacking.Layers.SmoothFormTransport +OAI.Geometry.BallPacking.Main +OAI.Geometry.BallPacking.Models.BallVolume +OAI.Geometry.BallPacking.Models.CubicPhysicalLocality +OAI.Geometry.BallPacking.Models.DisjointClocks +OAI.Geometry.BallPacking.Models.EqualNormalModelConvergence +OAI.Geometry.BallPacking.Models.LiouvilleRadialCalculus +OAI.Geometry.BallPacking.Models.RationalSlack +OAI.Geometry.BallPacking.Models.SurfaceComparison +OAI.Geometry.BallPacking.Moduli.SmoothZeroCharts +OAI.Geometry.BallPacking.Moduli.ZeroCharts +OAI.Geometry.BallPacking.Moments.AnalyticBoundary +OAI.Geometry.BallPacking.Moments.ConvexRearrangement +OAI.Geometry.BallPacking.Moments.ConvexWeights +OAI.Geometry.BallPacking.Moments.ExponentialMoment +OAI.Geometry.BallPacking.Moments.PolytopeSlices +OAI.Geometry.BallPacking.Moments.RadialSlopes +OAI.Geometry.BallPacking.Moments.RadialSwap +OAI.Geometry.BallPacking.Moments.RearrangementBounds +OAI.Geometry.BallPacking.Moser.AnnularFinalPacking +OAI.Geometry.BallPacking.Moser.BackgroundDensity +OAI.Geometry.BallPacking.Moser.CircleCorrection +OAI.Geometry.BallPacking.Moser.DiskMoser +OAI.Geometry.BallPacking.Moser.ManifoldExteriorNaturality +OAI.Geometry.BallPacking.Moser.ManifoldMoserField +OAI.Geometry.BallPacking.Moser.ParametricMoser +OAI.Geometry.BallPacking.Moser.PlanarCorrection +OAI.Geometry.BallPacking.Moser.PlanarCovectorPrimitive +OAI.Geometry.BallPacking.Moser.RelativeForms +OAI.Geometry.BallPacking.Moser.SmoothManifoldIntegral +OAI.Geometry.BallPacking.Moser.SymplecticFamily +OAI.Geometry.BallPacking.Normal.CompactDegenerationTransfer +OAI.Geometry.BallPacking.Normal.CompactUniformCentral +OAI.Geometry.BallPacking.Normal.CubicToricAmbient +OAI.Geometry.BallPacking.Normal.MovingPrimitiveNaturality +OAI.Geometry.BallPacking.Normal.QuadricMovingCone +OAI.Geometry.BallPacking.Normal.TailLineCoordinates +OAI.Geometry.BallPacking.Packings.ComplementPacking +OAI.Geometry.BallPacking.Projective.AnnularChartHelpers +OAI.Geometry.BallPacking.Projective.CubicEndCoordinates +OAI.Geometry.BallPacking.Projective.SixLargeCubicPacking +OAI.Geometry.BallPacking.RelativeJets.EmbeddingAdaptedNeighborhood +OAI.Geometry.BallPacking.RelativeJets.SymplecticProjectionNaturality +OAI.Geometry.BallPacking.Residues.AreaPolarChart +OAI.Geometry.BallPacking.Rigidity.Adapted +OAI.Geometry.BallPacking.Rigidity.AngularPoles +OAI.Geometry.BallPacking.Rigidity.CompatibleStructures +OAI.Geometry.BallPacking.Rigidity.CorrectedInfinity +OAI.Geometry.BallPacking.Rigidity.Correction +OAI.Geometry.BallPacking.Rigidity.CurveArea +OAI.Geometry.BallPacking.Rigidity.PlanarResidueCutoff +OAI.Geometry.BallPacking.Rigidity.RadialForm +OAI.Geometry.BallPacking.Rigidity.TwoBallBound +OAI.Geometry.BallPacking.SurfaceArea.AnnularSecondPositivity +OAI.Geometry.BallPacking.SurfaceArea.BoundedPlanarResidue +OAI.Geometry.BallPacking.SurfaceArea.CubicRadialEndSmooth +OAI.Geometry.BallPacking.SurfaceArea.QuadricEndAnnuli +OAI.Geometry.BallPacking.SurfaceArea.QuadricEndResidueMass +OAI.Geometry.BallPacking.SurfaceArea.QuadricSmoothExhaustion +OAI.Geometry.BallPacking.SurfaceArea.SurfaceCutoffDefect +OAI.Geometry.BallPacking.SurfaceArea.SurfaceIntegralIndependence +OAI.Geometry.BallPacking.SurfaceArea.SurfaceInteriorBoxes +OAI.Geometry.BallPacking.SurfaceArea.SurfacePrimitiveOperator +OAI.Geometry.BallPacking.SurfaceArea.SurfaceRedistribution +OAI.Geometry.BallPacking.Surfaces.DiagonalQuadric +OAI.Geometry.BallPacking.Surfaces.QuadricAnnulusDomain +OAI.Geometry.BallPacking.Surfaces.QuadricCurveManifold +OAI.Geometry.BallPacking.Surfaces.QuadricInfinityDiffeomorph +OAI.Geometry.BallPacking.Surfaces.QuadricOrientation +OAI.Geometry.BallPacking.Toric.CubicCoefficientDifferential +OAI.Geometry.BallPacking.Toric.CubicRadialFamilyExtension +OAI.Geometry.BallPacking.Toric.CubicRadialProbability +OAI.Geometry.BallPacking.Toric.RadialDiskSmooth +OAI.Geometry.BallPacking.Toric.RestrictedMassIndependence +OAI.Geometry.BallPacking.Toric.SixModelComparisonData +OAI.Geometry.BallPacking.Toric.StationaryManifoldPullback +OAI.Geometry.BallPacking.Toric.ToricClosedShift diff --git a/tasks/ball-packing/solution/reference.py b/tasks/ball-packing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ball-packing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ball-packing/solution/solve.sh b/tasks/ball-packing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..63f7bb3f11adb843c09951c75e0d756f9e8da682 --- /dev/null +++ b/tasks/ball-packing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BallPacking, i.e. module OAI.Geometry.BallPacking.Main and the +# 169 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.BallPacking.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BallPacking" diff --git a/tasks/ball-packing/task.toml b/tasks/ball-packing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..318e817bb9e7b347e190550445e4dcb41e9570a7 --- /dev/null +++ b/tasks/ball-packing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ball-packing" +version = "1.0.0" +description = "Prove BallPacking (openai/math family 343: Sharp symplectic ball-packing criteria in higher dimensions) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BallPacking.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BallPacking" +family = "343" +family_title = "Sharp symplectic ball-packing criteria in higher dimensions" +subject = "Differential geometry" +theorems = ["OAI.HigherDimensionalBallPacking.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.BallPacking.Main" +reference_modules = 169 +reference_lean_bytes = 4529811 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 4562 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15776 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ball-packing/tests/Challenge.lean b/tasks/ball-packing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c4c5da5898545c1d98b50ffa8449b95f19d6b7ce --- /dev/null +++ b/tasks/ball-packing/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +namespace HigherDimensionalBallPacking +open scoped ContDiff + +abbrev Phase (n : ℕ) := Fin n → ℂ + +noncomputable def capacity {n : ℕ} (z : Phase n) : ℝ := + Real.pi * ∑ j, Complex.normSq (z j) + +def closedBall (n : ℕ) (r : ℝ) : Set (Phase n) := {z | capacity z ≤ r} + +def openBall (n : ℕ) (r : ℝ) : Set (Phase n) := {z | capacity z < r} + +noncomputable def standardForm {n : ℕ} (u v : Phase n) : ℝ := + ∑ j, ((u j).re * (v j).im - (u j).im * (v j).re) + +def SymplecticOn {n : ℕ} (U : Set (Phase n)) (f : Phase n → Phase n) : Prop := + IsOpen U ∧ ContDiffOn ℝ ∞ f U ∧ + Topology.IsEmbedding (fun x : U => f x) ∧ + ∀ x ∈ U, ∀ u v : Phase n, + standardForm (fderiv ℝ f x u) (fderiv ℝ f x v) = standardForm u v + +def HasPacking (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + ∃ (U : Fin k → Set (Phase n)) (f : Fin k → Phase n → Phase n), + (∀ i, closedBall n (r i) ⊆ U i ∧ SymplecticOn (U i) (f i) ∧ + Set.MapsTo (f i) (closedBall n (r i)) (openBall n R)) ∧ + (∀ i j, i ≠ j → + Disjoint (f i '' closedBall n (r i)) (f j '' closedBall n (r j))) + +def PackingInequalities (n k : ℕ) (R : ℝ) (r : Fin k → ℝ) : Prop := + (∑ i, r i ^ n) < R ^ n ∧ ∀ i j, i ≠ j → r i + r j < R + +theorem main_theorem (n k : ℕ) (hn : 3 ≤ n) (hk : 1 ≤ k) + (R : ℝ) (r : Fin k → ℝ) (hR : 0 < R) (hr : ∀ i, 0 < r i) : + HasPacking n k R r ↔ PackingInequalities n k R r := by + sorry + +end HigherDimensionalBallPacking + +end OAI diff --git a/tasks/ball-packing/tests/grade.py b/tasks/ball-packing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ball-packing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ball-packing/tests/task.json b/tasks/ball-packing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8a74dcda5df4cfce17c606016504d258da631914 --- /dev/null +++ b/tasks/ball-packing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BallPacking", + "comparator": { + "theorem_names": [ + "OAI.HigherDimensionalBallPacking.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14876 +} \ No newline at end of file diff --git a/tasks/ball-packing/tests/test.sh b/tasks/ball-packing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ball-packing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/barnette-hamiltonian/environment/Dockerfile b/tasks/barnette-hamiltonian/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/barnette-hamiltonian/environment/fetch_mathlib.sh b/tasks/barnette-hamiltonian/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/barnette-hamiltonian/environment/lake-manifest.json b/tasks/barnette-hamiltonian/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/barnette-hamiltonian/environment/lakefile.lean b/tasks/barnette-hamiltonian/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/barnette-hamiltonian/environment/lean_setup.sh b/tasks/barnette-hamiltonian/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/barnette-hamiltonian/environment/pack_submission.py b/tasks/barnette-hamiltonian/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/barnette-hamiltonian/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/barnette-hamiltonian/instruction.md b/tasks/barnette-hamiltonian/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c8e67bfb0090c1539cfaf58cfae7afd9eb6b07b3 --- /dev/null +++ b/tasks/barnette-hamiltonian/instruction.md @@ -0,0 +1,104 @@ +# openai/math challenge `BarnetteHamiltonian` (family 180) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 180 of the release, *Barnette's Hamiltonian-cycle conjecture* +(Combinatorics). The family as a whole: Proves that every finite simple cubic bipartite planar $3$-vertex-connected graph has a Hamiltonian cycle, resolving Barnette's conjecture. Equivalently, every three-edge path in a finite simple cubic $3$-vertex-connected bipartite Pfaffian graph lies in a Hamiltonian cycle. + +The challenge is `BarnetteHamiltonian`, also at `/opt/openai-math/challenges/BarnetteHamiltonian.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Barnette + +universe u + +/-- A topological plane drawing of a simple graph, with no crossings. -/ +structure PlaneEmbedding {V : Type u} (G : SimpleGraph V) where + point : V → ℝ × ℝ + point_injective : Function.Injective point + arc : ∀ (v w : V), G.Adj v w → Path (point v) (point w) + arc_injective : ∀ (v w : V) (h : G.Adj v w), + Function.Injective (arc v w h) + arc_reverse : ∀ (v w : V) (h : G.Adj v w), + arc w v h.symm = (arc v w h).symm + arc_avoids_vertices : ∀ (v w : V) (h : G.Adj v w) + (t : unitInterval) (z : V), + arc v w h t = point z → + (t = 0 ∧ z = v) ∨ (t = 1 ∧ z = w) + interiors_disjoint : ∀ (v w x y : V) (h : G.Adj v w) (k : G.Adj x y) + (t s : unitInterval), + t ≠ 0 → t ≠ 1 → s ≠ 0 → s ≠ 1 → + arc v w h t = arc x y k s → + (v = x ∧ w = y) ∨ (v = y ∧ w = x) + +/-- Planarity means existence of a crossing-free topological plane embedding. -/ +def Planar {V : Type u} (G : SimpleGraph V) : Prop := + Nonempty (PlaneEmbedding G) + +/-- Deleting any set of at most two vertices leaves a connected graph of order at least two. -/ +def ThreeVertexConnected {V : Type u} [Fintype V] (G : SimpleGraph V) : Prop := + 4 ≤ Fintype.card V ∧ + ∀ S : Finset V, S.card ≤ 2 → (G.induce {v | v ∉ S}).Connected + +/-- A single spanning cycle, not a possibly disconnected spanning 2-factor. -/ +def HasHamiltonianCycle {V : Type u} [DecidableEq V] (G : SimpleGraph V) : Prop := + ∃ v : V, ∃ p : G.Walk v v, p.IsHamiltonianCycle + +/-- Cubic bipartite three-vertex-connected plane graphs have a Hamiltonian cycle. -/ +def MainStatement : Prop := + ∀ (V : Type u) [Fintype V] [DecidableEq V] (G : SimpleGraph V) + [DecidableRel G.Adj], + G.IsRegularOfDegree 3 → G.IsBipartite → Planar G → + ThreeVertexConnected G → HasHamiltonianCycle G + +theorem main : MainStatement.{u} := by + sorry + +end Barnette + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BarnetteHamiltonian.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Barnette.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/barnette-hamiltonian/solution/closure.txt b/tasks/barnette-hamiltonian/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a6085aa83a8181e3b43271fe148776e7969b72b2 --- /dev/null +++ b/tasks/barnette-hamiltonian/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Combinatorics.Hamiltonian.BMatching +OAI.Combinatorics.Hamiltonian.Bonds +OAI.Combinatorics.Hamiltonian.BranchPartition +OAI.Combinatorics.Hamiltonian.CappedDuality +OAI.Combinatorics.Hamiltonian.Circulation +OAI.Combinatorics.Hamiltonian.ColoredDual +OAI.Combinatorics.Hamiltonian.Contraction +OAI.Combinatorics.Hamiltonian.Corridors +OAI.Combinatorics.Hamiltonian.CutSpaces +OAI.Combinatorics.Hamiltonian.CycleReversal +OAI.Combinatorics.Hamiltonian.DiskRegions +OAI.Combinatorics.Hamiltonian.ExactDual +OAI.Combinatorics.Hamiltonian.FlowCircuits +OAI.Combinatorics.Hamiltonian.Forest +OAI.Combinatorics.Hamiltonian.ForestMatching +OAI.Combinatorics.Hamiltonian.Gluing +OAI.Combinatorics.Hamiltonian.Main +OAI.Combinatorics.Hamiltonian.Matching +OAI.Combinatorics.Hamiltonian.MinorDuality +OAI.Combinatorics.Hamiltonian.MinorModel +OAI.Combinatorics.Hamiltonian.Model +OAI.Combinatorics.Hamiltonian.Network +OAI.Combinatorics.Hamiltonian.PairPhases +OAI.Combinatorics.Hamiltonian.PairPolynomials +OAI.Combinatorics.Hamiltonian.Quotients +OAI.Combinatorics.Hamiltonian.Rectangle +OAI.Combinatorics.Hamiltonian.SquareGrid +OAI.Combinatorics.Hamiltonian.StateDisk +OAI.Combinatorics.Hamiltonian.ThreeCuts +OAI.Combinatorics.Hamiltonian.Traces +OAI.Combinatorics.Hamiltonian.TriangleSystem diff --git a/tasks/barnette-hamiltonian/solution/reference.py b/tasks/barnette-hamiltonian/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/barnette-hamiltonian/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/barnette-hamiltonian/solution/solve.sh b/tasks/barnette-hamiltonian/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a9d677df323ab2cc338f9038617f61b78cf4c19f --- /dev/null +++ b/tasks/barnette-hamiltonian/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BarnetteHamiltonian, i.e. module OAI.Combinatorics.Hamiltonian.Main and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Hamiltonian.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BarnetteHamiltonian" diff --git a/tasks/barnette-hamiltonian/task.toml b/tasks/barnette-hamiltonian/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c2c672ac70805613b9b59b660b06650812739f03 --- /dev/null +++ b/tasks/barnette-hamiltonian/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/barnette-hamiltonian" +version = "1.0.0" +description = "Prove BarnetteHamiltonian (openai/math family 180: Barnette's Hamiltonian-cycle conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BarnetteHamiltonian.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BarnetteHamiltonian" +family = "180" +family_title = "Barnette's Hamiltonian-cycle conjecture" +subject = "Combinatorics" +theorems = ["OAI.Barnette.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Hamiltonian.Main" +reference_modules = 31 +reference_lean_bytes = 379455 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 752 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12041 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/barnette-hamiltonian/tests/Challenge.lean b/tasks/barnette-hamiltonian/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1027208daea504538ace4e9e9bf450b959477ad9 --- /dev/null +++ b/tasks/barnette-hamiltonian/tests/Challenge.lean @@ -0,0 +1,53 @@ +import Mathlib + +namespace OAI + +namespace Barnette + +universe u + +/-- A topological plane drawing of a simple graph, with no crossings. -/ +structure PlaneEmbedding {V : Type u} (G : SimpleGraph V) where + point : V → ℝ × ℝ + point_injective : Function.Injective point + arc : ∀ (v w : V), G.Adj v w → Path (point v) (point w) + arc_injective : ∀ (v w : V) (h : G.Adj v w), + Function.Injective (arc v w h) + arc_reverse : ∀ (v w : V) (h : G.Adj v w), + arc w v h.symm = (arc v w h).symm + arc_avoids_vertices : ∀ (v w : V) (h : G.Adj v w) + (t : unitInterval) (z : V), + arc v w h t = point z → + (t = 0 ∧ z = v) ∨ (t = 1 ∧ z = w) + interiors_disjoint : ∀ (v w x y : V) (h : G.Adj v w) (k : G.Adj x y) + (t s : unitInterval), + t ≠ 0 → t ≠ 1 → s ≠ 0 → s ≠ 1 → + arc v w h t = arc x y k s → + (v = x ∧ w = y) ∨ (v = y ∧ w = x) + +/-- Planarity means existence of a crossing-free topological plane embedding. -/ +def Planar {V : Type u} (G : SimpleGraph V) : Prop := + Nonempty (PlaneEmbedding G) + +/-- Deleting any set of at most two vertices leaves a connected graph of order at least two. -/ +def ThreeVertexConnected {V : Type u} [Fintype V] (G : SimpleGraph V) : Prop := + 4 ≤ Fintype.card V ∧ + ∀ S : Finset V, S.card ≤ 2 → (G.induce {v | v ∉ S}).Connected + +/-- A single spanning cycle, not a possibly disconnected spanning 2-factor. -/ +def HasHamiltonianCycle {V : Type u} [DecidableEq V] (G : SimpleGraph V) : Prop := + ∃ v : V, ∃ p : G.Walk v v, p.IsHamiltonianCycle + +/-- Cubic bipartite three-vertex-connected plane graphs have a Hamiltonian cycle. -/ +def MainStatement : Prop := + ∀ (V : Type u) [Fintype V] [DecidableEq V] (G : SimpleGraph V) + [DecidableRel G.Adj], + G.IsRegularOfDegree 3 → G.IsBipartite → Planar G → + ThreeVertexConnected G → HasHamiltonianCycle G + +theorem main : MainStatement.{u} := by + sorry + +end Barnette + +end OAI diff --git a/tasks/barnette-hamiltonian/tests/grade.py b/tasks/barnette-hamiltonian/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/barnette-hamiltonian/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/barnette-hamiltonian/tests/task.json b/tasks/barnette-hamiltonian/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..23ae68da7b4fc6f67f8221f999eca21faa9b80b3 --- /dev/null +++ b/tasks/barnette-hamiltonian/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BarnetteHamiltonian", + "comparator": { + "theorem_names": [ + "OAI.Barnette.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11141 +} \ No newline at end of file diff --git a/tasks/barnette-hamiltonian/tests/test.sh b/tasks/barnette-hamiltonian/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/barnette-hamiltonian/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bass-torsion-free/environment/Dockerfile b/tasks/bass-torsion-free/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bass-torsion-free/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bass-torsion-free/environment/fetch_mathlib.sh b/tasks/bass-torsion-free/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bass-torsion-free/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bass-torsion-free/environment/lake-manifest.json b/tasks/bass-torsion-free/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bass-torsion-free/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bass-torsion-free/environment/lakefile.lean b/tasks/bass-torsion-free/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bass-torsion-free/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bass-torsion-free/environment/lean_setup.sh b/tasks/bass-torsion-free/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bass-torsion-free/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bass-torsion-free/environment/pack_submission.py b/tasks/bass-torsion-free/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bass-torsion-free/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bass-torsion-free/instruction.md b/tasks/bass-torsion-free/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14122961c95985f22e8e0d36cbc19106cc793071 --- /dev/null +++ b/tasks/bass-torsion-free/instruction.md @@ -0,0 +1,363 @@ +# openai/math challenge `BassTorsionFree` (family 207) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 207 of the release, *The $\ell^1$-Bass and complex Bass trace conjectures* +(Algebra). The family as a whole: Proves the $\ell^1$-Bass conjecture for every discrete group: Hattori–Stallings traces of idempotent matrices over $\ell^1(G)$ are supported on finitely many finite-order conjugacy classes. The algebraic companion proves the integral Bass trace conjecture and Kaplansky's idempotent conjecture for torsion-free groups over every commutative unital characteristic-zero domain. + +The challenge is `BassTorsionFree`, also at `/opt/openai-math/challenges/BassTorsionFree.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Traces and augmentation rank on the idempotent presentation of algebraic K₀. -/ + +namespace BassTrace + +open scoped Classical + +noncomputable def classCoefficient {G : Type*} [Group G] + (g : G) (a : MonoidAlgebra ℂ G) : ℂ := by + classical + exact a.coeff.sum fun h z => if IsConj h g then z else 0 + +variable {G : Type*} [Group G] + +@[simp] theorem classCoefficient_zero (g : G) : + classCoefficient g 0 = 0 := by + simp [classCoefficient] + +@[simp] theorem classCoefficient_single (g h : G) (z : ℂ) : + classCoefficient g (MonoidAlgebra.single h z) = if IsConj h g then z else 0 := by + classical + simp [classCoefficient, Finsupp.sum_single_index] + +@[simp] theorem classCoefficient_add (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a + b) = classCoefficient g a + classCoefficient g b := by + classical + apply Finsupp.sum_add_index + · intro h _ + simp + · intro h _ z w + split_ifs <;> simp + +@[simp] theorem classCoefficient_smul (g : G) (z : ℂ) (a : MonoidAlgebra ℂ G) : + classCoefficient g (z • a) = z * classCoefficient g a := by + classical + unfold classCoefficient + rw [MonoidAlgebra.coeff_smul, Finsupp.sum_smul_index (fun _ => by simp)] + rw [Finsupp.sum, Finsupp.sum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro h _ + split_ifs <;> simp + +@[simp] theorem classCoefficient_sum {ι : Type*} (g : G) (s : Finset ι) + (f : ι → MonoidAlgebra ℂ G) : + classCoefficient g (∑ i ∈ s, f i) = ∑ i ∈ s, classCoefficient g (f i) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert a s ha ih => simp [ha, ih] + +theorem classCoefficient_mul_comm (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a * b) = classCoefficient g (b * a) := by + induction a using MonoidAlgebra.induction_on with + | of h => + induction b using MonoidAlgebra.induction_on with + | of k => + have hconj : IsConj (h * k) (k * h) := by + apply isConj_iff.mpr + exact ⟨k, by simp [mul_assoc]⟩ + have hiff : IsConj (h * k) g ↔ IsConj (k * h) g := + ⟨hconj.symm.trans, hconj.trans⟩ + change classCoefficient g (MonoidAlgebra.single h 1 * MonoidAlgebra.single k 1) = + classCoefficient g (MonoidAlgebra.single k 1 * MonoidAlgebra.single h 1) + simp only [MonoidAlgebra.single_mul_single, classCoefficient_single, hiff] + | add b c hb hc => simp only [mul_add, add_mul, classCoefficient_add, hb, hc] + | smul z b hb => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, hb] + | add a c ha hc => simp only [add_mul, mul_add, classCoefficient_add, ha, hc] + | smul z a ha => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, ha] + +theorem classCoefficient_matrix_mul_comm {ι κ : Type*} [Fintype ι] [Fintype κ] + (g : G) (a : Matrix ι κ (MonoidAlgebra ℂ G)) + (b : Matrix κ ι (MonoidAlgebra ℂ G)) : + classCoefficient g (Matrix.trace (a * b)) = + classCoefficient g (Matrix.trace (b * a)) := by + classical + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, classCoefficient_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + exact classCoefficient_mul_comm g _ _ + +end BassTrace + +noncomputable section + +namespace BassTrace + +open scoped Classical + +namespace K0 + +open scoped Classical BigOperators + +section + +structure Idempotent (R : Type*) [Ring R] where + size : ℕ + matrix : Matrix (Fin size) (Fin size) R + idem : matrix*matrix=matrix + +variable {R : Type*} [Ring R] + +def directSum (e f : Idempotent R) : Idempotent R where + size := e.size+f.size + matrix := Matrix.reindexRingEquiv R finSumFinEquiv (Matrix.fromBlocks e.matrix 0 0 f.matrix) + idem := by + rw [←map_mul,Matrix.fromBlocks_multiply] + simp only [Matrix.mul_zero,Matrix.zero_mul,add_zero,zero_add,e.idem,f.idem] + +def relationGenerators (R : Type*) [Ring R] : Set (FreeAbelianGroup (Idempotent R)) := + {x | (∃e f : Idempotent R,∃a : Matrix (Fin e.size) (Fin f.size) R, + ∃b : Matrix (Fin f.size) (Fin e.size) R, + a*b=e.matrix ∧ b*a=f.matrix ∧ x=FreeAbelianGroup.of e-FreeAbelianGroup.of f) ∨ + (∃e f : Idempotent R,x=FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)} + +def relations (R : Type*) [Ring R] : AddSubgroup (FreeAbelianGroup (Idempotent R)) := + AddSubgroup.closure (relationGenerators R) + +instance relations_normal (R : Type*) [Ring R] : (relations R).Normal := inferInstance + +abbrev Group (R : Type*) [Ring R] := FreeAbelianGroup (Idempotent R) ⧸ relations R + +variable {G : Type*} [_root_.Group G] + +instance groupRingRelations_normal : (relations (MonoidAlgebra ℂ G)).Normal := inferInstance + +def rawCoefficient (g : G) : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℂ := + FreeAbelianGroup.lift (fun e=>classCoefficient g (Matrix.trace e.matrix)) + +end + +end K0 + +end BassTrace + +end + +open Set MeasureTheory +open Finset MeasureTheory intervalIntegral +noncomputable section + +namespace BassTrace.K0 + +section + +open scoped Classical BigOperators + +variable {R : Type*} [Ring R] + +lemma trace_reindex {α β : Type*} [Fintype α] [Fintype β] + (j : α≃β) (a : Matrix α α R) : + Matrix.trace (Matrix.reindexRingEquiv R j a)=Matrix.trace a := by + change (∑i, a (j.symm i) (j.symm i))=∑i,a i i + exact Equiv.sum_comp j.symm (fun i=>a i i) + +lemma trace_directSum (e f : Idempotent R) : + Matrix.trace (directSum e f).matrix=Matrix.trace e.matrix+Matrix.trace f.matrix := by + rw [directSum,trace_reindex] + simp only [Matrix.trace,Matrix.diag,Fintype.sum_sum_type,Matrix.fromBlocks_apply₁₁,Matrix.fromBlocks_apply₂₂] + +variable {G : Type*} [_root_.Group G] + +lemma relations_in_kernel (g : G) : relations (MonoidAlgebra ℂ G)≤(rawCoefficient g).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩|⟨e,f,rfl⟩ + · change rawCoefficient g (FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of] + apply sub_eq_zero.mpr + rw [←hab,←hba] + exact classCoefficient_matrix_mul_comm g a b + · change rawCoefficient g (FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of,trace_directSum,classCoefficient_add] + abel + +def hsCoefficient (g : G) : Group (MonoidAlgebra ℂ G) →+ ℂ := + QuotientAddGroup.lift (relations (MonoidAlgebra ℂ G)) (rawCoefficient g) (relations_in_kernel g) + +end + +end BassTrace.K0 + +end + +open scoped Classical BigOperators +noncomputable section +namespace TorsionFreeBass + +/-- A group is torsion-free when its only finite-order element is the identity. +This is the usual group-theoretic condition, not the stronger unique-roots condition. -/ +def TorsionFree (G : Type*) [Group G] : Prop := ∀ g : G, IsOfFinOrder g → g = 1 + +variable {G : Type*} [Group G] + +/-- The sum of coefficients, or augmentation, of the complex group algebra. -/ +def augmentation : MonoidAlgebra ℂ G →+* ℂ := + (MonoidAlgebra.lift ℂ ℂ G (1 : G →* ℂ)).toRingHom + +/-- The canonical trace is the coefficient of the identity. -/ +def canonicalTrace (a : MonoidAlgebra ℂ G) : ℂ := a.coeff 1 + +/-- The matrix trace obtained by applying the canonical trace to each diagonal entry. -/ +def matrixTrace {q : ℕ} (e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G)) : ℂ := + ∑ i, canonicalTrace (e i i) + +/-- Entrywise augmentation. -/ +def augmentedMatrix {m n : ℕ} (e : Matrix (Fin m) (Fin n) (MonoidAlgebra ℂ G)) : + Matrix (Fin m) (Fin n) ℂ := e.map augmentation + +lemma augmentedMatrix_mul {m n p : ℕ} + (a : Matrix (Fin m) (Fin n) (MonoidAlgebra ℂ G)) + (b : Matrix (Fin n) (Fin p) (MonoidAlgebra ℂ G)) : + augmentedMatrix (a * b) = augmentedMatrix a * augmentedMatrix b := by + exact Matrix.map_mul + +lemma augmentedMatrix_trace {q : ℕ} + (e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G)) : + Matrix.trace (augmentedMatrix e) = augmentation (Matrix.trace e) := by + simp [augmentedMatrix, Matrix.trace, Matrix.diag] + +lemma idempotent_matrix_trace_eq_rank {q : ℕ} (a : Matrix (Fin q) (Fin q) ℂ) + (ha : a * a = a) : Matrix.trace a = (a.rank : ℂ) := by + have h : IsIdempotentElem a.toLin' := by + change a.toLin'.comp a.toLin' = a.toLin' + rw [← Matrix.toLin'_mul, ha] + rw [← Matrix.trace_toLin'_eq, (LinearMap.IsIdempotentElem.isProj_range _ h).trace] + rfl + +open BassTrace.K0 in +/-- The augmentation rank on the free abelian group of idempotents, before imposing +isomorphism and direct-sum relations. -/ +def rawAugmentationRank : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℤ := + FreeAbelianGroup.lift (fun e => ((augmentedMatrix e.matrix).rank : ℤ)) + +lemma rawAugmentationRank_of (e : BassTrace.K0.Idempotent (MonoidAlgebra ℂ G)) : + ((rawAugmentationRank (FreeAbelianGroup.of e) : ℤ) : ℂ) = + augmentation (Matrix.trace e.matrix) := by + change (((augmentedMatrix e.matrix).rank : ℤ) : ℂ) = _ + rw [Int.cast_natCast, ← idempotent_matrix_trace_eq_rank] + · exact augmentedMatrix_trace _ + · rw [← augmentedMatrix_mul, e.idem] + +lemma augmentationRank_relations : BassTrace.K0.relations (MonoidAlgebra ℂ G) ≤ + (rawAugmentationRank (G := G)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩ | ⟨e,f,rfl⟩ + · change rawAugmentationRank (FreeAbelianGroup.of e - FreeAbelianGroup.of f) = 0 + apply Int.cast_injective (α := ℂ) + rw [map_sub, Int.cast_sub, rawAugmentationRank_of, rawAugmentationRank_of, Int.cast_zero] + apply sub_eq_zero.mpr + rw [← augmentedMatrix_trace, ← augmentedMatrix_trace, ← hab, ← hba, + augmentedMatrix_mul, augmentedMatrix_mul] + exact Matrix.trace_mul_comm _ _ + · change rawAugmentationRank (FreeAbelianGroup.of (BassTrace.K0.directSum e f) - + FreeAbelianGroup.of e - FreeAbelianGroup.of f) = 0 + apply Int.cast_injective (α := ℂ) + simp only [map_sub, Int.cast_sub, rawAugmentationRank_of, Int.cast_zero, + BassTrace.K0.trace_directSum, map_add] + abel + +/-- The integer-valued augmentation rank on the usual idempotent presentation of +algebraic K₀: on a generator it is the complex dimension of the augmented image. -/ +def augmentationRank : BassTrace.K0.Group (MonoidAlgebra ℂ G) →+ ℤ := + QuotientAddGroup.lift (BassTrace.K0.relations (MonoidAlgebra ℂ G)) + rawAugmentationRank augmentationRank_relations + +open BassTrace.K0 in +lemma traceK0_relations : relations (MonoidAlgebra ℂ G) ≤ (rawCoefficient (1 : G)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro element membership + rcases membership with + ⟨idemLeft, idemRight, forward, backward, forward_backward, backward_forward, rfl⟩ | + ⟨idemLeft, idemRight, rfl⟩ + · change rawCoefficient 1 (FreeAbelianGroup.of idemLeft - FreeAbelianGroup.of idemRight) = 0 + rw [map_sub] + apply sub_eq_zero.mpr + simp only [rawCoefficient, FreeAbelianGroup.lift_apply_of] + rw [← forward_backward, ← backward_forward] + exact BassTrace.classCoefficient_matrix_mul_comm 1 forward backward + · change rawCoefficient 1 (FreeAbelianGroup.of (directSum idemLeft idemRight) - + FreeAbelianGroup.of idemLeft - FreeAbelianGroup.of idemRight) = 0 + rw [map_sub, map_sub] + simp only [rawCoefficient, FreeAbelianGroup.lift_apply_of] + rw [trace_directSum, BassTrace.classCoefficient_add, add_sub_cancel_left, sub_self] + +/-- Coefficient at the identity class of the Hattori--Stallings trace on K₀. -/ +def traceK0 : BassTrace.K0.Group (MonoidAlgebra ℂ G) →+ ℂ := + QuotientAddGroup.lift (BassTrace.K0.relations (MonoidAlgebra ℂ G)) + (BassTrace.K0.rawCoefficient 1) traceK0_relations + +/-- Trace/rank, equality and range on algebraic K₀, and characteristic-zero +scalar idempotents for torsion-free groups. -/ +theorem torsion_free_corollary (G : Type*) [Group G] (hG : TorsionFree G) : + ((∀ (q : ℕ), 1 ≤ q → + ∀ e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G), e ^ 2 = e → + matrixTrace e = ((augmentedMatrix e).rank : ℂ)) ∧ + traceK0 (G := G) = (Int.castAddHom ℂ).comp augmentationRank ∧ + Set.range (traceK0 (G := G)) = Set.range (fun z : ℤ => (z : ℂ))) ∧ + (∀ (R : Type*) [CommRing R] [IsDomain R] [CharZero R] + (e : MonoidAlgebra R G), e ^ 2 = e → e = 0 ∨ e = 1) := by + sorry + +end TorsionFreeBass +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BassTorsionFree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TorsionFreeBass.torsion_free_corollary` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bass-torsion-free/solution/closure.txt b/tasks/bass-torsion-free/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ac98ce69757ad9ecc80cb2484d7c4a59a137f94b --- /dev/null +++ b/tasks/bass-torsion-free/solution/closure.txt @@ -0,0 +1,73 @@ +OAI.RingTheory.BassTrace.ActivatedUnions +OAI.RingTheory.BassTrace.AdmissibleCuts +OAI.RingTheory.BassTrace.AffineCoarea +OAI.RingTheory.BassTrace.AffinePotentials +OAI.RingTheory.BassTrace.AreaSurgery +OAI.RingTheory.BassTrace.AveragedChains +OAI.RingTheory.BassTrace.BallComparison +OAI.RingTheory.BassTrace.BallGeometry +OAI.RingTheory.BassTrace.BallMass +OAI.RingTheory.BassTrace.BallReplacement +OAI.RingTheory.BassTrace.BarycentricBounds +OAI.RingTheory.BassTrace.BarycentricChains +OAI.RingTheory.BassTrace.CanonicalCells +OAI.RingTheory.BassTrace.CellTriangulation +OAI.RingTheory.BassTrace.CentralizerGeometry +OAI.RingTheory.BassTrace.ChainMaps +OAI.RingTheory.BassTrace.ClosedPaths +OAI.RingTheory.BassTrace.CoefficientDescent +OAI.RingTheory.BassTrace.Coning +OAI.RingTheory.BassTrace.CutNaturality +OAI.RingTheory.BassTrace.Definitions +OAI.RingTheory.BassTrace.DirectedCuts +OAI.RingTheory.BassTrace.EquivariantSurgery +OAI.RingTheory.BassTrace.ExteriorChains +OAI.RingTheory.BassTrace.ExteriorDetector +OAI.RingTheory.BassTrace.FaceFiltration +OAI.RingTheory.BassTrace.FacetGeometry +OAI.RingTheory.BassTrace.FiniteAverages +OAI.RingTheory.BassTrace.FiniteCells +OAI.RingTheory.BassTrace.FiniteGenerators +OAI.RingTheory.BassTrace.FreeParameters +OAI.RingTheory.BassTrace.FundamentalChains +OAI.RingTheory.BassTrace.GeometricSubcomplexes +OAI.RingTheory.BassTrace.GraphCounting +OAI.RingTheory.BassTrace.GraphRealization +OAI.RingTheory.BassTrace.HausdorffArea +OAI.RingTheory.BassTrace.Incidence +OAI.RingTheory.BassTrace.LocalCuts +OAI.RingTheory.BassTrace.Main +OAI.RingTheory.BassTrace.MarkedArea +OAI.RingTheory.BassTrace.MarkedSubdivisions +OAI.RingTheory.BassTrace.MatrixK0 +OAI.RingTheory.BassTrace.MatrixVanishing +OAI.RingTheory.BassTrace.MeasurableSlices +OAI.RingTheory.BassTrace.ModuleK0 +OAI.RingTheory.BassTrace.NormedVectors +OAI.RingTheory.BassTrace.OrbitAreas +OAI.RingTheory.BassTrace.OrbitForms +OAI.RingTheory.BassTrace.PathComplex +OAI.RingTheory.BassTrace.PathWeights +OAI.RingTheory.BassTrace.PfaffianDetector +OAI.RingTheory.BassTrace.ProbabilityGeometry +OAI.RingTheory.BassTrace.RegularRepresentation +OAI.RingTheory.BassTrace.RelativeExponents +OAI.RingTheory.BassTrace.RightRetractions +OAI.RingTheory.BassTrace.SimplexCoordinates +OAI.RingTheory.BassTrace.SimplexMeasures +OAI.RingTheory.BassTrace.SimplexVolume +OAI.RingTheory.BassTrace.SparseBounds +OAI.RingTheory.BassTrace.SparseChains +OAI.RingTheory.BassTrace.SubdivisionWeights +OAI.RingTheory.BassTrace.Subdivisions +OAI.RingTheory.BassTrace.SupportGeometry +OAI.RingTheory.BassTrace.TorsionFree +OAI.RingTheory.BassTrace.TraceCoefficients +OAI.RingTheory.BassTrace.TraceRank +OAI.RingTheory.BassTrace.TransportMetric +OAI.RingTheory.BassTrace.TreeArea +OAI.RingTheory.BassTrace.TreeDeterminants +OAI.RingTheory.BassTrace.TwistedPaths +OAI.RingTheory.BassTrace.VolumeBounds +OAI.RingTheory.BassTrace.ZeroCarriers +OAI.RingTheory.BassTrace.ZeroStrata diff --git a/tasks/bass-torsion-free/solution/reference.py b/tasks/bass-torsion-free/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bass-torsion-free/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bass-torsion-free/solution/solve.sh b/tasks/bass-torsion-free/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..64ea4dd93369684c6ffeae60f8bcafef34bdb7fc --- /dev/null +++ b/tasks/bass-torsion-free/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BassTorsionFree, i.e. module OAI.RingTheory.BassTrace.TorsionFree and the +# 73 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.BassTrace.TorsionFree /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BassTorsionFree" diff --git a/tasks/bass-torsion-free/task.toml b/tasks/bass-torsion-free/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7b8b3c7cca5d4a88c803ed3dc9c301992e51c840 --- /dev/null +++ b/tasks/bass-torsion-free/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bass-torsion-free" +version = "1.0.0" +description = "Prove BassTorsionFree (openai/math family 207: The $\\ell^1$-Bass and complex Bass trace conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BassTorsionFree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BassTorsionFree" +family = "207" +family_title = "The $\\ell^1$-Bass and complex Bass trace conjectures" +subject = "Algebra" +theorems = ["OAI.TorsionFreeBass.torsion_free_corollary"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.BassTrace.TorsionFree" +reference_modules = 73 +reference_lean_bytes = 1022515 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1087 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12620 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bass-torsion-free/tests/Challenge.lean b/tasks/bass-torsion-free/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..629ab0e1d7a65c700a4d41af4ab79bc4598c7c3f --- /dev/null +++ b/tasks/bass-torsion-free/tests/Challenge.lean @@ -0,0 +1,312 @@ +import Mathlib + +namespace OAI + +/-! Traces and augmentation rank on the idempotent presentation of algebraic K₀. -/ + +namespace BassTrace + +open scoped Classical + +noncomputable def classCoefficient {G : Type*} [Group G] + (g : G) (a : MonoidAlgebra ℂ G) : ℂ := by + classical + exact a.coeff.sum fun h z => if IsConj h g then z else 0 + +variable {G : Type*} [Group G] + +@[simp] theorem classCoefficient_zero (g : G) : + classCoefficient g 0 = 0 := by + simp [classCoefficient] + +@[simp] theorem classCoefficient_single (g h : G) (z : ℂ) : + classCoefficient g (MonoidAlgebra.single h z) = if IsConj h g then z else 0 := by + classical + simp [classCoefficient, Finsupp.sum_single_index] + +@[simp] theorem classCoefficient_add (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a + b) = classCoefficient g a + classCoefficient g b := by + classical + apply Finsupp.sum_add_index + · intro h _ + simp + · intro h _ z w + split_ifs <;> simp + +@[simp] theorem classCoefficient_smul (g : G) (z : ℂ) (a : MonoidAlgebra ℂ G) : + classCoefficient g (z • a) = z * classCoefficient g a := by + classical + unfold classCoefficient + rw [MonoidAlgebra.coeff_smul, Finsupp.sum_smul_index (fun _ => by simp)] + rw [Finsupp.sum, Finsupp.sum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro h _ + split_ifs <;> simp + +@[simp] theorem classCoefficient_sum {ι : Type*} (g : G) (s : Finset ι) + (f : ι → MonoidAlgebra ℂ G) : + classCoefficient g (∑ i ∈ s, f i) = ∑ i ∈ s, classCoefficient g (f i) := by + classical + induction s using Finset.induction_on with + | empty => simp + | @insert a s ha ih => simp [ha, ih] + +theorem classCoefficient_mul_comm (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a * b) = classCoefficient g (b * a) := by + induction a using MonoidAlgebra.induction_on with + | of h => + induction b using MonoidAlgebra.induction_on with + | of k => + have hconj : IsConj (h * k) (k * h) := by + apply isConj_iff.mpr + exact ⟨k, by simp [mul_assoc]⟩ + have hiff : IsConj (h * k) g ↔ IsConj (k * h) g := + ⟨hconj.symm.trans, hconj.trans⟩ + change classCoefficient g (MonoidAlgebra.single h 1 * MonoidAlgebra.single k 1) = + classCoefficient g (MonoidAlgebra.single k 1 * MonoidAlgebra.single h 1) + simp only [MonoidAlgebra.single_mul_single, classCoefficient_single, hiff] + | add b c hb hc => simp only [mul_add, add_mul, classCoefficient_add, hb, hc] + | smul z b hb => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, hb] + | add a c ha hc => simp only [add_mul, mul_add, classCoefficient_add, ha, hc] + | smul z a ha => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, ha] + +theorem classCoefficient_matrix_mul_comm {ι κ : Type*} [Fintype ι] [Fintype κ] + (g : G) (a : Matrix ι κ (MonoidAlgebra ℂ G)) + (b : Matrix κ ι (MonoidAlgebra ℂ G)) : + classCoefficient g (Matrix.trace (a * b)) = + classCoefficient g (Matrix.trace (b * a)) := by + classical + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, classCoefficient_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + exact classCoefficient_mul_comm g _ _ + +end BassTrace + +noncomputable section + +namespace BassTrace + +open scoped Classical + +namespace K0 + +open scoped Classical BigOperators + +section + +structure Idempotent (R : Type*) [Ring R] where + size : ℕ + matrix : Matrix (Fin size) (Fin size) R + idem : matrix*matrix=matrix + +variable {R : Type*} [Ring R] + +def directSum (e f : Idempotent R) : Idempotent R where + size := e.size+f.size + matrix := Matrix.reindexRingEquiv R finSumFinEquiv (Matrix.fromBlocks e.matrix 0 0 f.matrix) + idem := by + rw [←map_mul,Matrix.fromBlocks_multiply] + simp only [Matrix.mul_zero,Matrix.zero_mul,add_zero,zero_add,e.idem,f.idem] + +def relationGenerators (R : Type*) [Ring R] : Set (FreeAbelianGroup (Idempotent R)) := + {x | (∃e f : Idempotent R,∃a : Matrix (Fin e.size) (Fin f.size) R, + ∃b : Matrix (Fin f.size) (Fin e.size) R, + a*b=e.matrix ∧ b*a=f.matrix ∧ x=FreeAbelianGroup.of e-FreeAbelianGroup.of f) ∨ + (∃e f : Idempotent R,x=FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)} + +def relations (R : Type*) [Ring R] : AddSubgroup (FreeAbelianGroup (Idempotent R)) := + AddSubgroup.closure (relationGenerators R) + +instance relations_normal (R : Type*) [Ring R] : (relations R).Normal := inferInstance + +abbrev Group (R : Type*) [Ring R] := FreeAbelianGroup (Idempotent R) ⧸ relations R + +variable {G : Type*} [_root_.Group G] + +instance groupRingRelations_normal : (relations (MonoidAlgebra ℂ G)).Normal := inferInstance + +def rawCoefficient (g : G) : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℂ := + FreeAbelianGroup.lift (fun e=>classCoefficient g (Matrix.trace e.matrix)) + +end + +end K0 + +end BassTrace + +end + +open Set MeasureTheory +open Finset MeasureTheory intervalIntegral +noncomputable section + +namespace BassTrace.K0 + +section + +open scoped Classical BigOperators + +variable {R : Type*} [Ring R] + +lemma trace_reindex {α β : Type*} [Fintype α] [Fintype β] + (j : α≃β) (a : Matrix α α R) : + Matrix.trace (Matrix.reindexRingEquiv R j a)=Matrix.trace a := by + change (∑i, a (j.symm i) (j.symm i))=∑i,a i i + exact Equiv.sum_comp j.symm (fun i=>a i i) + +lemma trace_directSum (e f : Idempotent R) : + Matrix.trace (directSum e f).matrix=Matrix.trace e.matrix+Matrix.trace f.matrix := by + rw [directSum,trace_reindex] + simp only [Matrix.trace,Matrix.diag,Fintype.sum_sum_type,Matrix.fromBlocks_apply₁₁,Matrix.fromBlocks_apply₂₂] + +variable {G : Type*} [_root_.Group G] + +lemma relations_in_kernel (g : G) : relations (MonoidAlgebra ℂ G)≤(rawCoefficient g).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩|⟨e,f,rfl⟩ + · change rawCoefficient g (FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of] + apply sub_eq_zero.mpr + rw [←hab,←hba] + exact classCoefficient_matrix_mul_comm g a b + · change rawCoefficient g (FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of,trace_directSum,classCoefficient_add] + abel + +def hsCoefficient (g : G) : Group (MonoidAlgebra ℂ G) →+ ℂ := + QuotientAddGroup.lift (relations (MonoidAlgebra ℂ G)) (rawCoefficient g) (relations_in_kernel g) + +end + +end BassTrace.K0 + +end + +open scoped Classical BigOperators +noncomputable section +namespace TorsionFreeBass + +/-- A group is torsion-free when its only finite-order element is the identity. +This is the usual group-theoretic condition, not the stronger unique-roots condition. -/ +def TorsionFree (G : Type*) [Group G] : Prop := ∀ g : G, IsOfFinOrder g → g = 1 + +variable {G : Type*} [Group G] + +/-- The sum of coefficients, or augmentation, of the complex group algebra. -/ +def augmentation : MonoidAlgebra ℂ G →+* ℂ := + (MonoidAlgebra.lift ℂ ℂ G (1 : G →* ℂ)).toRingHom + +/-- The canonical trace is the coefficient of the identity. -/ +def canonicalTrace (a : MonoidAlgebra ℂ G) : ℂ := a.coeff 1 + +/-- The matrix trace obtained by applying the canonical trace to each diagonal entry. -/ +def matrixTrace {q : ℕ} (e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G)) : ℂ := + ∑ i, canonicalTrace (e i i) + +/-- Entrywise augmentation. -/ +def augmentedMatrix {m n : ℕ} (e : Matrix (Fin m) (Fin n) (MonoidAlgebra ℂ G)) : + Matrix (Fin m) (Fin n) ℂ := e.map augmentation + +lemma augmentedMatrix_mul {m n p : ℕ} + (a : Matrix (Fin m) (Fin n) (MonoidAlgebra ℂ G)) + (b : Matrix (Fin n) (Fin p) (MonoidAlgebra ℂ G)) : + augmentedMatrix (a * b) = augmentedMatrix a * augmentedMatrix b := by + exact Matrix.map_mul + +lemma augmentedMatrix_trace {q : ℕ} + (e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G)) : + Matrix.trace (augmentedMatrix e) = augmentation (Matrix.trace e) := by + simp [augmentedMatrix, Matrix.trace, Matrix.diag] + +lemma idempotent_matrix_trace_eq_rank {q : ℕ} (a : Matrix (Fin q) (Fin q) ℂ) + (ha : a * a = a) : Matrix.trace a = (a.rank : ℂ) := by + have h : IsIdempotentElem a.toLin' := by + change a.toLin'.comp a.toLin' = a.toLin' + rw [← Matrix.toLin'_mul, ha] + rw [← Matrix.trace_toLin'_eq, (LinearMap.IsIdempotentElem.isProj_range _ h).trace] + rfl + +open BassTrace.K0 in +/-- The augmentation rank on the free abelian group of idempotents, before imposing +isomorphism and direct-sum relations. -/ +def rawAugmentationRank : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℤ := + FreeAbelianGroup.lift (fun e => ((augmentedMatrix e.matrix).rank : ℤ)) + +lemma rawAugmentationRank_of (e : BassTrace.K0.Idempotent (MonoidAlgebra ℂ G)) : + ((rawAugmentationRank (FreeAbelianGroup.of e) : ℤ) : ℂ) = + augmentation (Matrix.trace e.matrix) := by + change (((augmentedMatrix e.matrix).rank : ℤ) : ℂ) = _ + rw [Int.cast_natCast, ← idempotent_matrix_trace_eq_rank] + · exact augmentedMatrix_trace _ + · rw [← augmentedMatrix_mul, e.idem] + +lemma augmentationRank_relations : BassTrace.K0.relations (MonoidAlgebra ℂ G) ≤ + (rawAugmentationRank (G := G)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩ | ⟨e,f,rfl⟩ + · change rawAugmentationRank (FreeAbelianGroup.of e - FreeAbelianGroup.of f) = 0 + apply Int.cast_injective (α := ℂ) + rw [map_sub, Int.cast_sub, rawAugmentationRank_of, rawAugmentationRank_of, Int.cast_zero] + apply sub_eq_zero.mpr + rw [← augmentedMatrix_trace, ← augmentedMatrix_trace, ← hab, ← hba, + augmentedMatrix_mul, augmentedMatrix_mul] + exact Matrix.trace_mul_comm _ _ + · change rawAugmentationRank (FreeAbelianGroup.of (BassTrace.K0.directSum e f) - + FreeAbelianGroup.of e - FreeAbelianGroup.of f) = 0 + apply Int.cast_injective (α := ℂ) + simp only [map_sub, Int.cast_sub, rawAugmentationRank_of, Int.cast_zero, + BassTrace.K0.trace_directSum, map_add] + abel + +/-- The integer-valued augmentation rank on the usual idempotent presentation of +algebraic K₀: on a generator it is the complex dimension of the augmented image. -/ +def augmentationRank : BassTrace.K0.Group (MonoidAlgebra ℂ G) →+ ℤ := + QuotientAddGroup.lift (BassTrace.K0.relations (MonoidAlgebra ℂ G)) + rawAugmentationRank augmentationRank_relations + +open BassTrace.K0 in +lemma traceK0_relations : relations (MonoidAlgebra ℂ G) ≤ (rawCoefficient (1 : G)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro element membership + rcases membership with + ⟨idemLeft, idemRight, forward, backward, forward_backward, backward_forward, rfl⟩ | + ⟨idemLeft, idemRight, rfl⟩ + · change rawCoefficient 1 (FreeAbelianGroup.of idemLeft - FreeAbelianGroup.of idemRight) = 0 + rw [map_sub] + apply sub_eq_zero.mpr + simp only [rawCoefficient, FreeAbelianGroup.lift_apply_of] + rw [← forward_backward, ← backward_forward] + exact BassTrace.classCoefficient_matrix_mul_comm 1 forward backward + · change rawCoefficient 1 (FreeAbelianGroup.of (directSum idemLeft idemRight) - + FreeAbelianGroup.of idemLeft - FreeAbelianGroup.of idemRight) = 0 + rw [map_sub, map_sub] + simp only [rawCoefficient, FreeAbelianGroup.lift_apply_of] + rw [trace_directSum, BassTrace.classCoefficient_add, add_sub_cancel_left, sub_self] + +/-- Coefficient at the identity class of the Hattori--Stallings trace on K₀. -/ +def traceK0 : BassTrace.K0.Group (MonoidAlgebra ℂ G) →+ ℂ := + QuotientAddGroup.lift (BassTrace.K0.relations (MonoidAlgebra ℂ G)) + (BassTrace.K0.rawCoefficient 1) traceK0_relations + +/-- Trace/rank, equality and range on algebraic K₀, and characteristic-zero +scalar idempotents for torsion-free groups. -/ +theorem torsion_free_corollary (G : Type*) [Group G] (hG : TorsionFree G) : + ((∀ (q : ℕ), 1 ≤ q → + ∀ e : Matrix (Fin q) (Fin q) (MonoidAlgebra ℂ G), e ^ 2 = e → + matrixTrace e = ((augmentedMatrix e).rank : ℂ)) ∧ + traceK0 (G := G) = (Int.castAddHom ℂ).comp augmentationRank ∧ + Set.range (traceK0 (G := G)) = Set.range (fun z : ℤ => (z : ℂ))) ∧ + (∀ (R : Type*) [CommRing R] [IsDomain R] [CharZero R] + (e : MonoidAlgebra R G), e ^ 2 = e → e = 0 ∨ e = 1) := by + sorry + +end TorsionFreeBass +end + +end OAI diff --git a/tasks/bass-torsion-free/tests/grade.py b/tasks/bass-torsion-free/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bass-torsion-free/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bass-torsion-free/tests/task.json b/tasks/bass-torsion-free/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..77f81eaf91a8dfc4047a397982defd731627521f --- /dev/null +++ b/tasks/bass-torsion-free/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BassTorsionFree", + "comparator": { + "theorem_names": [ + "OAI.TorsionFreeBass.torsion_free_corollary" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11720 +} \ No newline at end of file diff --git a/tasks/bass-torsion-free/tests/test.sh b/tasks/bass-torsion-free/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bass-torsion-free/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bass-trace/environment/Dockerfile b/tasks/bass-trace/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bass-trace/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bass-trace/environment/fetch_mathlib.sh b/tasks/bass-trace/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bass-trace/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bass-trace/environment/lake-manifest.json b/tasks/bass-trace/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bass-trace/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bass-trace/environment/lakefile.lean b/tasks/bass-trace/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bass-trace/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bass-trace/environment/lean_setup.sh b/tasks/bass-trace/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bass-trace/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bass-trace/environment/pack_submission.py b/tasks/bass-trace/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bass-trace/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bass-trace/instruction.md b/tasks/bass-trace/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5622da92d1a440cd5d00aa8bbd91180de02568b8 --- /dev/null +++ b/tasks/bass-trace/instruction.md @@ -0,0 +1,534 @@ +# openai/math challenge `BassTrace` (family 207) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 207 of the release, *The $\ell^1$-Bass and complex Bass trace conjectures* +(Algebra). The family as a whole: Proves the $\ell^1$-Bass conjecture for every discrete group: Hattori–Stallings traces of idempotent matrices over $\ell^1(G)$ are supported on finitely many finite-order conjugacy classes. The algebraic companion proves the integral Bass trace conjecture and Kaplansky's idempotent conjecture for torsion-free groups over every commutative unital characteristic-zero domain. + +The challenge is `BassTrace`, also at `/opt/openai-math/challenges/BassTrace.lean`: + +```lean +import Mathlib.Algebra.Group.Conj +import Mathlib.Algebra.MonoidAlgebra.Basic +import Mathlib.Basic.Complex.Basic +import Mathlib.GroupTheory.FreeAbelianGroup +import Mathlib.GroupTheory.OrderOfElement +import Mathlib.LinearAlgebra.Matrix.Trace +import Mathlib.LinearAlgebra.Matrix.ToLin +import Mathlib.RingTheory.Finiteness.Projective +import Mathlib.Tactic + +namespace OAI + +noncomputable section + +namespace BassTrace + +open scoped Classical + +noncomputable def classCoefficient {G : Type*} [Group G] + (g : G) (a : MonoidAlgebra ℂ G) : ℂ := by + classical + exact a.coeff.sum fun h z => if IsConj h g then z else 0 + +namespace K0 + +open scoped Classical BigOperators + +section + +structure Idempotent (R : Type*) [Ring R] where + size : ℕ + matrix : Matrix (Fin size) (Fin size) R + idem : matrix*matrix=matrix + +variable {R : Type*} [Ring R] + +def directSum (e f : Idempotent R) : Idempotent R where + size := e.size+f.size + matrix := Matrix.reindexRingEquiv R finSumFinEquiv (Matrix.fromBlocks e.matrix 0 0 f.matrix) + idem := by + rw [←map_mul,Matrix.fromBlocks_multiply] + simp only [Matrix.mul_zero,Matrix.zero_mul,add_zero,zero_add,e.idem,f.idem] + +def relationGenerators (R : Type*) [Ring R] : Set (FreeAbelianGroup (Idempotent R)) := + {x | (∃e f : Idempotent R,∃a : Matrix (Fin e.size) (Fin f.size) R, + ∃b : Matrix (Fin f.size) (Fin e.size) R, + a*b=e.matrix ∧ b*a=f.matrix ∧ x=FreeAbelianGroup.of e-FreeAbelianGroup.of f) ∨ + (∃e f : Idempotent R,x=FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)} + +def relations (R : Type*) [Ring R] : AddSubgroup (FreeAbelianGroup (Idempotent R)) := + AddSubgroup.closure (relationGenerators R) + +instance relations_normal (R : Type*) [Ring R] : (relations R).Normal := inferInstance + +abbrev Group (R : Type*) [Ring R] := FreeAbelianGroup (Idempotent R) ⧸ relations R + +def classOf (e : Idempotent R) : Group R := QuotientAddGroup.mk' (relations R) (FreeAbelianGroup.of e) + +variable {G : Type*} [_root_.Group G] + +instance groupRingRelations_normal : (relations (MonoidAlgebra ℂ G)).Normal := inferInstance + +def rawCoefficient (g : G) : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℂ := + FreeAbelianGroup.lift (fun e=>classCoefficient g (Matrix.trace e.matrix)) + +end + +variable {G : Type*} [_root_.Group G] + +def classTrace (a : MonoidAlgebra ℂ G) : ConjClasses G →₀ ℂ := + Finsupp.mapDomain ConjClasses.mk a.coeff + +def rawTrace : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ (ConjClasses G →₀ ℂ) := + FreeAbelianGroup.lift (fun e=>classTrace (Matrix.trace e.matrix)) + +def HattoriStallings : Group (MonoidAlgebra ℂ G) →+ (ConjClasses G →₀ ℂ) := by + have classCoefficient_zero (g : G) : + classCoefficient g 0 = 0 := by + simp [classCoefficient] + have classCoefficient_single (g h : G) (z : ℂ) : + classCoefficient g (MonoidAlgebra.single h z) = if IsConj h g then z else 0 := by + classical + simp [classCoefficient, Finsupp.sum_single_index] + have classCoefficient_add (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a + b) = classCoefficient g a + classCoefficient g b := by + classical + apply Finsupp.sum_add_index + · intro h _ + simp + · intro h _ z w + split_ifs <;> simp + have classCoefficient_smul (g : G) (z : ℂ) (a : MonoidAlgebra ℂ G) : + classCoefficient g (z • a) = z * classCoefficient g a := by + classical + unfold classCoefficient + rw [MonoidAlgebra.coeff_smul, Finsupp.sum_smul_index (fun _ => by simp)] + rw [Finsupp.sum, Finsupp.sum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro h _ + split_ifs <;> simp + have classCoefficient_sum {ι : Type} (g : G) (s : Finset ι) + (f : ι → MonoidAlgebra ℂ G) : + classCoefficient g (∑ i ∈ s, f i) = ∑ i ∈ s, classCoefficient g (f i) := by + classical + induction s using Finset.induction_on with + | empty => simp [classCoefficient_zero] + | @insert a s ha ih => simp [classCoefficient_add, ha, ih] + have classCoefficient_mul_comm (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a * b) = classCoefficient g (b * a) := by + induction a using MonoidAlgebra.induction_on with + | of h => + induction b using MonoidAlgebra.induction_on with + | of k => + have hconj : IsConj (h * k) (k * h) := by + apply isConj_iff.mpr + exact ⟨k, by simp [mul_assoc]⟩ + have hiff : IsConj (h * k) g ↔ IsConj (k * h) g := + ⟨hconj.symm.trans, hconj.trans⟩ + change classCoefficient g (MonoidAlgebra.single h 1 * MonoidAlgebra.single k 1) = + classCoefficient g (MonoidAlgebra.single k 1 * MonoidAlgebra.single h 1) + simp only [MonoidAlgebra.single_mul_single, classCoefficient_single, hiff] + | add b c hb hc => simp only [mul_add, add_mul, classCoefficient_add, hb, hc] + | smul z b hb => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, hb] + | add a c ha hc => simp only [add_mul, mul_add, classCoefficient_add, ha, hc] + | smul z a ha => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, ha] + have classCoefficient_matrix_mul_comm {ι κ : Type} [Fintype ι] [Fintype κ] + (g : G) (a : Matrix ι κ (MonoidAlgebra ℂ G)) + (b : Matrix κ ι (MonoidAlgebra ℂ G)) : + classCoefficient g (Matrix.trace (a * b)) = + classCoefficient g (Matrix.trace (b * a)) := by + classical + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, classCoefficient_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + exact classCoefficient_mul_comm g _ _ + have trace_reindex {α β : Type} [Fintype α] [Fintype β] + (j : α≃β) (a : Matrix α α (MonoidAlgebra ℂ G)) : + Matrix.trace (Matrix.reindexRingEquiv (MonoidAlgebra ℂ G) j a)=Matrix.trace a := by + change (∑i, a (j.symm i) (j.symm i))=∑i,a i i + exact Equiv.sum_comp j.symm (fun i=>a i i) + have trace_directSum (e f : Idempotent (MonoidAlgebra ℂ G)) : + Matrix.trace (directSum e f).matrix=Matrix.trace e.matrix+Matrix.trace f.matrix := by + rw [directSum,trace_reindex] + simp only [Matrix.trace,Matrix.diag,Fintype.sum_sum_type,Matrix.fromBlocks_apply₁₁,Matrix.fromBlocks_apply₂₂] + have relations_in_kernel (g : G) : relations (MonoidAlgebra ℂ G)≤(rawCoefficient g).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩|⟨e,f,rfl⟩ + · change rawCoefficient g (FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of] + apply sub_eq_zero.mpr + rw [←hab,←hba] + exact classCoefficient_matrix_mul_comm g a b + · change rawCoefficient g (FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of,trace_directSum,classCoefficient_add] + rw [add_sub_cancel_left, sub_self] + have classTrace_apply (a : MonoidAlgebra ℂ G) (g : G) : + classTrace a (ConjClasses.mk g)=classCoefficient g a := by + unfold classTrace classCoefficient + simp only [Finsupp.mapDomain,Finsupp.sum_apply,Finsupp.single_apply] + apply Finset.sum_congr rfl + intro h hh + dsimp only + by_cases hc : IsConj h g + · rw [ite_eq_left (ConjClasses.mk_eq_mk_iff_isConj.mpr hc), ite_eq_left hc] + · rw [ite_eq_right (mt ConjClasses.mk_eq_mk_iff_isConj.mp hc), ite_eq_right hc] + have rawTrace_apply (z : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G))) (g : G) : + rawTrace z (ConjClasses.mk g)=rawCoefficient g z := by + induction z using FreeAbelianGroup.induction_on with + | zero => simp only [map_zero,Finsupp.zero_apply] + | of e => + simp only [rawTrace,rawCoefficient,FreeAbelianGroup.lift_apply_of] + exact classTrace_apply _ g + | neg e he => simp only [map_neg,Finsupp.neg_apply,he] + | add x y hx hy => simp only [map_add,Finsupp.add_apply,hx,hy] + have relations_in_trace_kernel : relations (MonoidAlgebra ℂ G)≤(rawTrace (G := G)).ker := by + intro z hz + change rawTrace z=0 + ext c + obtain ⟨g,rfl⟩ := ConjClasses.mk_surjective c + rw [rawTrace_apply,Finsupp.zero_apply] + exact relations_in_kernel g hz + exact QuotientAddGroup.lift (relations (MonoidAlgebra ℂ G)) rawTrace relations_in_trace_kernel + +end K0 + +namespace RightProjective + +open scoped Classical BigOperators + +open MulOpposite + +section + +variable {R : Type*} [Ring R] + +instance rightModuleIdentityRingHomInvPair : + RingHomInvPair (RingHom.id Rᵐᵒᵖ) (RingHom.id Rᵐᵒᵖ) := RingHomInvPair.ids + +def unopTranspose {m n : Type*} (a : Matrix m n Rᵐᵒᵖ) : Matrix n m R := + fun i j=>unop (a j i) + +def rightMatrix {m n : ℕ} (f : (Fin m → Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n → Rᵐᵒᵖ)) : + Matrix (Fin n) (Fin m) R := unopTranspose (LinearMap.toMatrixRight' f) + +structure Retraction (R M : Type*) [Ring R] [AddCommGroup M] [Module Rᵐᵒᵖ M] where + size : ℕ + proj : (Fin size →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] M + inc : M →ₗ[Rᵐᵒᵖ] (Fin size →Rᵐᵒᵖ) + split : proj.comp inc=LinearMap.id + +variable {M N : Type*} [AddCommGroup M] [Module Rᵐᵒᵖ M] + [AddCommGroup N] [Module Rᵐᵒᵖ N] + +def Retraction.idempotent (r : Retraction R M) : K0.Idempotent R := by + have unopTranspose_mul {l m n : Type} [Fintype m] + (a : Matrix l m Rᵐᵒᵖ) (b : Matrix m n Rᵐᵒᵖ) : + unopTranspose (a*b)=unopTranspose b*unopTranspose a := by + ext i j + simp only [unopTranspose,Matrix.mul_apply] + change (opAddEquiv.symm : Rᵐᵒᵖ≃+R) (∑k,a j k*b k i)=_ + rw [map_sum] + rfl + have rightMatrix_comp {l m n : ℕ} + (f : (Fin l →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin m →Rᵐᵒᵖ)) + (g : (Fin m →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n →Rᵐᵒᵖ)) : + rightMatrix (g.comp f)=rightMatrix g*rightMatrix f := by + simp only [rightMatrix,LinearMap.toMatrixRight'_comp,unopTranspose_mul] + exact { + size := r.size + matrix := rightMatrix (r.inc.comp r.proj) + idem := by + rw [←rightMatrix_comp] + congr 1 + calc (r.inc.comp r.proj).comp (r.inc.comp r.proj) = + r.inc.comp ((r.proj.comp r.inc).comp r.proj) := by simp only [LinearMap.comp_assoc] + _ = r.inc.comp r.proj := by rw [r.split,LinearMap.id_comp] } + +def Retraction.transport (r : Retraction R M) (u : M≃ₗ[Rᵐᵒᵖ] N) : Retraction R N where + size := r.size + proj := u.toLinearMap.comp r.proj + inc := r.inc.comp u.symm.toLinearMap + split := by + calc (u.toLinearMap.comp r.proj).comp (r.inc.comp u.symm.toLinearMap) = + u.toLinearMap.comp ((r.proj.comp r.inc).comp u.symm.toLinearMap) := by simp only [LinearMap.comp_assoc] + _ = LinearMap.id := by rw [r.split,LinearMap.id_comp,LinearEquiv.comp_symm] + +def freeSplit (n m : ℕ) : (Fin (n+m)→Rᵐᵒᵖ) ≃ₗ[Rᵐᵒᵖ] (Fin n→Rᵐᵒᵖ) × (Fin m→Rᵐᵒᵖ) := + (LinearEquiv.piCongrLeft' Rᵐᵒᵖ (fun _ : Fin (n+m)=>Rᵐᵒᵖ) finSumFinEquiv.symm).trans + (LinearEquiv.sumArrowLequivProdArrow (Fin n) (Fin m) Rᵐᵒᵖ Rᵐᵒᵖ) + +def Retraction.prod (r : Retraction R M) (s : Retraction R N) : Retraction R (M×N) where + size := r.size+s.size + proj := (r.proj.prodMap s.proj).comp (freeSplit r.size s.size).toLinearMap + inc := (freeSplit r.size s.size).symm.toLinearMap.comp (r.inc.prodMap s.inc) + split := by + apply LinearMap.ext + intro x + change ((r.proj.prodMap s.proj) ((freeSplit r.size s.size) + ((freeSplit r.size s.size).symm ((r.inc.prodMap s.inc) x))))=x + rw [LinearEquiv.apply_symm_apply] + have hr := LinearMap.congr_fun r.split x.1 + have hs := LinearMap.congr_fun s.split x.2 + exact Prod.ext hr hs + +end + +open scoped Classical + +universe u v + +structure Object (R : Type u) [Ring R] where + carrier : Type v + [addCommGroup : AddCommGroup carrier] + [module : Module Rᵐᵒᵖ carrier] + [finite : Module.Finite Rᵐᵒᵖ carrier] + [projective : Module.Projective Rᵐᵒᵖ carrier] + +attribute [instance] Object.addCommGroup Object.module Object.finite Object.projective + +variable {R : Type u} [Ring R] + +def Object.prod (P Q : Object.{u,v} R) : Object.{u,v} R where + carrier := P.carrier × Q.carrier + +def Object.retraction (P : Object.{u,v} R) : Retraction R P.carrier := + Classical.choice (by + obtain ⟨n, f, g, _, _, h⟩ := Module.Finite.exists_comp_eq_id_of_projective Rᵐᵒᵖ P.carrier + exact ⟨⟨n, f, g, h⟩⟩) + +def Object.presentationClass (P : Object.{u,v} R) : K0.Group R := + K0.classOf P.retraction.idempotent + +def moduleRelationGenerators (R : Type u) [Ring R] : Set (FreeAbelianGroup (Object.{u,v} R)) := + {x | (∃P Q : Object.{u,v} R, Nonempty (P.carrier≃ₗ[Rᵐᵒᵖ] Q.carrier) ∧ + x=FreeAbelianGroup.of P-FreeAbelianGroup.of Q) ∨ + (∃P Q : Object.{u,v} R, + x=FreeAbelianGroup.of (P.prod Q)-FreeAbelianGroup.of P-FreeAbelianGroup.of Q)} + +def moduleRelations (R : Type u) [Ring R] : AddSubgroup (FreeAbelianGroup (Object.{u,v} R)) := + AddSubgroup.closure (moduleRelationGenerators R) + +abbrev ModuleK0 (R : Type u) [Ring R] := + FreeAbelianGroup (Object.{u,v} R) ⧸ moduleRelations R + +def rawPresentation : FreeAbelianGroup (Object.{u,v} R) →+ K0.Group R := + FreeAbelianGroup.lift Object.presentationClass + +def presentation : ModuleK0.{u,v} R →+ K0.Group R := by + have unopTranspose_mul {l m n : ℕ} + (a : Matrix (Fin l) (Fin m) Rᵐᵒᵖ) (b : Matrix (Fin m) (Fin n) Rᵐᵒᵖ) : + unopTranspose (a*b)=unopTranspose b*unopTranspose a := by + ext i j + simp only [unopTranspose,Matrix.mul_apply] + change (opAddEquiv.symm : Rᵐᵒᵖ≃+R) (∑k,a j k*b k i)=_ + rw [map_sum] + rfl + have rightMatrix_comp {l m n : ℕ} + (f : (Fin l →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin m →Rᵐᵒᵖ)) + (g : (Fin m →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n →Rᵐᵒᵖ)) : + rightMatrix (g.comp f)=rightMatrix g*rightMatrix f := by + simp only [rightMatrix,LinearMap.toMatrixRight'_comp,unopTranspose_mul] + have classOf_eq_of_rectangular (e f : K0.Idempotent R) + (a : Matrix (Fin e.size) (Fin f.size) R) + (b : Matrix (Fin f.size) (Fin e.size) R) (hab : a*b=e.matrix) (hba : b*a=f.matrix) : + K0.classOf e=K0.classOf f := by + apply sub_eq_zero.mp + change (QuotientAddGroup.mk' (K0.relations R)) (FreeAbelianGroup.of e)- + (QuotientAddGroup.mk' (K0.relations R)) (FreeAbelianGroup.of f)=0 + rw [←map_sub] + change (QuotientAddGroup.mk (FreeAbelianGroup.of e-FreeAbelianGroup.of f) : K0.Group R)=0 + apply (QuotientAddGroup.eq_zero_iff _).mpr + exact AddSubgroup.subset_closure (Or.inl ⟨e,f,a,b,hab,hba,rfl⟩) + have Retraction.class_eq {M : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] (r s : Retraction R M) : + K0.classOf r.idempotent=K0.classOf s.idempotent := by + apply classOf_eq_of_rectangular _ _ + (rightMatrix (r.inc.comp s.proj)) (rightMatrix (s.inc.comp r.proj)) + · change rightMatrix (r.inc.comp s.proj)*rightMatrix (s.inc.comp r.proj)= + rightMatrix (r.inc.comp r.proj) + rw [←rightMatrix_comp] + congr 1 + calc (r.inc.comp s.proj).comp (s.inc.comp r.proj) = + r.inc.comp ((s.proj.comp s.inc).comp r.proj) := by simp only [LinearMap.comp_assoc] + _ = r.inc.comp r.proj := by rw [s.split,LinearMap.id_comp] + · change rightMatrix (s.inc.comp r.proj)*rightMatrix (r.inc.comp s.proj)= + rightMatrix (s.inc.comp s.proj) + rw [←rightMatrix_comp] + congr 1 + calc (s.inc.comp r.proj).comp (r.inc.comp s.proj) = + s.inc.comp ((r.proj.comp r.inc).comp s.proj) := by simp only [LinearMap.comp_assoc] + _ = s.inc.comp s.proj := by rw [r.split,LinearMap.id_comp] + have Retraction.transport_idempotent {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (u : M≃ₗ[Rᵐᵒᵖ] N) : + (r.transport u).idempotent=r.idempotent := by + dsimp only [Retraction.idempotent] + congr 1 + change rightMatrix ((r.inc.comp u.symm.toLinearMap).comp (u.toLinearMap.comp r.proj))= + rightMatrix (r.inc.comp r.proj) + congr 1 + apply LinearMap.ext + intro x + change r.inc (u.symm (u (r.proj x)))=r.inc (r.proj x) + rw [u.symm_apply_apply] + have freeSplit_apply_left (n m : ℕ) (v : Fin (n+m)→Rᵐᵒᵖ) (i : Fin n) : + (freeSplit n m v).1 i=v (finSumFinEquiv (Sum.inl i)) := rfl + have freeSplit_apply_right (n m : ℕ) (v : Fin (n+m)→Rᵐᵒᵖ) (i : Fin m) : + (freeSplit n m v).2 i=v (finSumFinEquiv (Sum.inr i)) := rfl + have freeSplit_symm_left (n m : ℕ) (v : Fin n→Rᵐᵒᵖ) (w : Fin m→Rᵐᵒᵖ) (i : Fin n) : + (freeSplit n m).symm (v,w) (finSumFinEquiv (Sum.inl i))=v i := by + have h := congrArg (fun x=>(x.1 : Fin n→Rᵐᵒᵖ) i) ((freeSplit (R := R) n m).apply_symm_apply (v,w)) + exact h + have freeSplit_symm_right (n m : ℕ) (v : Fin n→Rᵐᵒᵖ) (w : Fin m→Rᵐᵒᵖ) (i : Fin m) : + (freeSplit n m).symm (v,w) (finSumFinEquiv (Sum.inr i))=w i := by + have h := congrArg (fun x=>(x.2 : Fin m→Rᵐᵒᵖ) i) ((freeSplit (R := R) n m).apply_symm_apply (v,w)) + exact h + have freeSplit_single_left (n m : ℕ) (i : Fin n) : + freeSplit (R := R) n m (Pi.single (finSumFinEquiv (Sum.inl i)) 1)=(Pi.single i 1,0) := by + apply Prod.ext + · ext j + rw [freeSplit_apply_left] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inl.injEq] + · ext j + rw [freeSplit_apply_right] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inr_ne_inl,ite_false,Pi.zero_apply] + have freeSplit_single_right (n m : ℕ) (i : Fin m) : + freeSplit (R := R) n m (Pi.single (finSumFinEquiv (Sum.inr i)) 1)=(0,Pi.single i 1) := by + apply Prod.ext + · ext j + rw [freeSplit_apply_left] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inl_ne_inr,ite_false,Pi.zero_apply] + · ext j + rw [freeSplit_apply_right] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inr.injEq] + have Retraction.prod_matrix {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (s : Retraction R N) : + (r.prod s).idempotent.matrix=(K0.directSum r.idempotent s.idempotent).matrix := by + ext i j + obtain ⟨i,rfl⟩ := finSumFinEquiv.surjective i + obtain ⟨j,rfl⟩ := finSumFinEquiv.surjective j + change unop ((freeSplit r.size s.size).symm ((r.inc.prodMap s.inc) + ((r.proj.prodMap s.proj) ((freeSplit r.size s.size) + (Pi.single (finSumFinEquiv j) 1)))) (finSumFinEquiv i))= + Matrix.fromBlocks (rightMatrix (r.inc.comp r.proj)) 0 0 (rightMatrix (s.inc.comp s.proj)) + (finSumFinEquiv.symm (finSumFinEquiv i)) (finSumFinEquiv.symm (finSumFinEquiv j)) + simp only [Equiv.symm_apply_apply] + cases i with | inl i => ?_ | inr i => ?_ + all_goals cases j with | inl j => ?_ | inr j => ?_ + · rw [freeSplit_single_left] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_left,Matrix.fromBlocks_apply₁₁] + rfl + · rw [freeSplit_single_right] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_left,Matrix.fromBlocks_apply₁₂, + Pi.zero_apply,unop_zero,Matrix.zero_apply] + · rw [freeSplit_single_left] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_right,Matrix.fromBlocks_apply₂₁, + Pi.zero_apply,unop_zero,Matrix.zero_apply] + · rw [freeSplit_single_right] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_right,Matrix.fromBlocks_apply₂₂] + rfl + have Retraction.prod_idempotent {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (s : Retraction R N) : + (r.prod s).idempotent=K0.directSum r.idempotent s.idempotent := by + dsimp only [Retraction.idempotent, K0.directSum] + congr 1 + exact Retraction.prod_matrix r s + have classOf_directSum (e f : K0.Idempotent R) : + K0.classOf (K0.directSum e f)=K0.classOf e+K0.classOf f := by + apply sub_eq_zero.mp + change QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of (K0.directSum e f))- + (QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of e)+ + QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of f))=0 + rw [←map_add,←map_sub] + change (QuotientAddGroup.mk (FreeAbelianGroup.of (K0.directSum e f)- + (FreeAbelianGroup.of e+FreeAbelianGroup.of f)) : K0.Group R)=0 + apply (QuotientAddGroup.eq_zero_iff _).mpr + rw [sub_add_eq_sub_sub] + exact AddSubgroup.subset_closure (Or.inr ⟨e,f,rfl⟩) + have Object.presentationClass_eq (P : Object.{u,v} R) (r : Retraction R P.carrier) : + P.presentationClass=K0.classOf r.idempotent := Retraction.class_eq P.retraction r + have Object.presentationClass_iso (P Q : Object.{u,v} R) + (i : P.carrier ≃ₗ[Rᵐᵒᵖ] Q.carrier) : P.presentationClass=Q.presentationClass := by + rw [Object.presentationClass_eq Q (P.retraction.transport i), Retraction.transport_idempotent] + rfl + have Object.presentationClass_prod (P Q : Object.{u,v} R) : + (P.prod Q).presentationClass=P.presentationClass+Q.presentationClass := by + calc + _ = K0.classOf (P.retraction.prod Q.retraction).idempotent := + Object.presentationClass_eq (P.prod Q) (P.retraction.prod Q.retraction) + _ = P.presentationClass+Q.presentationClass := by + rw [Retraction.prod_idempotent,classOf_directSum] + rfl + have moduleRelations_in_kernel : moduleRelations R≤(rawPresentation.{u,v} (R := R)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨P,Q,⟨i⟩,rfl⟩ | ⟨P,Q,rfl⟩ + · change rawPresentation (FreeAbelianGroup.of P-FreeAbelianGroup.of Q)=0 + simp only [map_sub,rawPresentation,FreeAbelianGroup.lift_apply_of] + exact sub_eq_zero.mpr (Object.presentationClass_iso P Q i) + · change rawPresentation + (FreeAbelianGroup.of (P.prod Q)-FreeAbelianGroup.of P-FreeAbelianGroup.of Q)=0 + simp only [map_sub,rawPresentation,FreeAbelianGroup.lift_apply_of,Object.presentationClass_prod] + abel + exact QuotientAddGroup.lift (moduleRelations R) rawPresentation moduleRelations_in_kernel + +variable {G : Type u} [_root_.Group G] + +def HattoriStallings : ModuleK0.{u,v} (MonoidAlgebra ℂ G) →+ (ConjClasses G →₀ ℂ) := + K0.HattoriStallings.comp presentation + +theorem bassTraceModules_vanishing_and_support {G : Type u} [_root_.Group G] + (x : ModuleK0.{u,v} (MonoidAlgebra ℂ G)) : + (∀ g : G, ¬IsOfFinOrder g → HattoriStallings x (ConjClasses.mk g) = 0) ∧ + ↑(HattoriStallings x).support ⊆ + {c | ∃ g : G, IsOfFinOrder g ∧ ConjClasses.mk g = c} := + by sorry + +end RightProjective + +end BassTrace + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BassTrace.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BassTrace.RightProjective.bassTraceModules_vanishing_and_support` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bass-trace/solution/closure.txt b/tasks/bass-trace/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f8b99ad001a6695ebe80fd7b65863614b05b13d6 --- /dev/null +++ b/tasks/bass-trace/solution/closure.txt @@ -0,0 +1,69 @@ +OAI.RingTheory.BassTrace.ActivatedUnions +OAI.RingTheory.BassTrace.AdmissibleCuts +OAI.RingTheory.BassTrace.AffineCoarea +OAI.RingTheory.BassTrace.AffinePotentials +OAI.RingTheory.BassTrace.AreaSurgery +OAI.RingTheory.BassTrace.AveragedChains +OAI.RingTheory.BassTrace.BallComparison +OAI.RingTheory.BassTrace.BallGeometry +OAI.RingTheory.BassTrace.BallMass +OAI.RingTheory.BassTrace.BallReplacement +OAI.RingTheory.BassTrace.BarycentricBounds +OAI.RingTheory.BassTrace.BarycentricChains +OAI.RingTheory.BassTrace.CanonicalCells +OAI.RingTheory.BassTrace.CellTriangulation +OAI.RingTheory.BassTrace.CentralizerGeometry +OAI.RingTheory.BassTrace.ChainMaps +OAI.RingTheory.BassTrace.ClosedPaths +OAI.RingTheory.BassTrace.Coning +OAI.RingTheory.BassTrace.CutNaturality +OAI.RingTheory.BassTrace.Definitions +OAI.RingTheory.BassTrace.DirectedCuts +OAI.RingTheory.BassTrace.EquivariantSurgery +OAI.RingTheory.BassTrace.ExteriorChains +OAI.RingTheory.BassTrace.ExteriorDetector +OAI.RingTheory.BassTrace.FaceFiltration +OAI.RingTheory.BassTrace.FacetGeometry +OAI.RingTheory.BassTrace.FiniteAverages +OAI.RingTheory.BassTrace.FiniteCells +OAI.RingTheory.BassTrace.FiniteGenerators +OAI.RingTheory.BassTrace.FreeParameters +OAI.RingTheory.BassTrace.FundamentalChains +OAI.RingTheory.BassTrace.GeometricSubcomplexes +OAI.RingTheory.BassTrace.GraphCounting +OAI.RingTheory.BassTrace.GraphRealization +OAI.RingTheory.BassTrace.HausdorffArea +OAI.RingTheory.BassTrace.Incidence +OAI.RingTheory.BassTrace.LocalCuts +OAI.RingTheory.BassTrace.Main +OAI.RingTheory.BassTrace.MarkedArea +OAI.RingTheory.BassTrace.MarkedSubdivisions +OAI.RingTheory.BassTrace.MatrixK0 +OAI.RingTheory.BassTrace.MatrixVanishing +OAI.RingTheory.BassTrace.MeasurableSlices +OAI.RingTheory.BassTrace.ModuleK0 +OAI.RingTheory.BassTrace.NormedVectors +OAI.RingTheory.BassTrace.OrbitAreas +OAI.RingTheory.BassTrace.OrbitForms +OAI.RingTheory.BassTrace.PathComplex +OAI.RingTheory.BassTrace.PathWeights +OAI.RingTheory.BassTrace.PfaffianDetector +OAI.RingTheory.BassTrace.ProbabilityGeometry +OAI.RingTheory.BassTrace.RelativeExponents +OAI.RingTheory.BassTrace.RightRetractions +OAI.RingTheory.BassTrace.SimplexCoordinates +OAI.RingTheory.BassTrace.SimplexMeasures +OAI.RingTheory.BassTrace.SimplexVolume +OAI.RingTheory.BassTrace.SparseBounds +OAI.RingTheory.BassTrace.SparseChains +OAI.RingTheory.BassTrace.SubdivisionWeights +OAI.RingTheory.BassTrace.Subdivisions +OAI.RingTheory.BassTrace.SupportGeometry +OAI.RingTheory.BassTrace.TraceCoefficients +OAI.RingTheory.BassTrace.TransportMetric +OAI.RingTheory.BassTrace.TreeArea +OAI.RingTheory.BassTrace.TreeDeterminants +OAI.RingTheory.BassTrace.TwistedPaths +OAI.RingTheory.BassTrace.VolumeBounds +OAI.RingTheory.BassTrace.ZeroCarriers +OAI.RingTheory.BassTrace.ZeroStrata diff --git a/tasks/bass-trace/solution/reference.py b/tasks/bass-trace/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bass-trace/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bass-trace/solution/solve.sh b/tasks/bass-trace/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d91238d9d2270ac65993473e11c0fe2f9c5a7a60 --- /dev/null +++ b/tasks/bass-trace/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BassTrace, i.e. module OAI.RingTheory.BassTrace.Main and the +# 69 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.BassTrace.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BassTrace" diff --git a/tasks/bass-trace/task.toml b/tasks/bass-trace/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7988d82a1edc7d0050ae95e5e5cbc1ab858375cb --- /dev/null +++ b/tasks/bass-trace/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bass-trace" +version = "1.0.0" +description = "Prove BassTrace (openai/math family 207: The $\\ell^1$-Bass and complex Bass trace conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BassTrace.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BassTrace" +family = "207" +family_title = "The $\\ell^1$-Bass and complex Bass trace conjectures" +subject = "Algebra" +theorems = ["OAI.BassTrace.RightProjective.bassTraceModules_vanishing_and_support"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.BassTrace.Main" +reference_modules = 69 +reference_lean_bytes = 997569 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1120 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12597 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bass-trace/tests/Challenge.lean b/tasks/bass-trace/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0393bdfd8cf50fd708574b4e89b06e00cb2750d4 --- /dev/null +++ b/tasks/bass-trace/tests/Challenge.lean @@ -0,0 +1,483 @@ +import Mathlib.Algebra.Group.Conj +import Mathlib.Algebra.MonoidAlgebra.Basic +import Mathlib.Basic.Complex.Basic +import Mathlib.GroupTheory.FreeAbelianGroup +import Mathlib.GroupTheory.OrderOfElement +import Mathlib.LinearAlgebra.Matrix.Trace +import Mathlib.LinearAlgebra.Matrix.ToLin +import Mathlib.RingTheory.Finiteness.Projective +import Mathlib.Tactic + +namespace OAI + +noncomputable section + +namespace BassTrace + +open scoped Classical + +noncomputable def classCoefficient {G : Type*} [Group G] + (g : G) (a : MonoidAlgebra ℂ G) : ℂ := by + classical + exact a.coeff.sum fun h z => if IsConj h g then z else 0 + +namespace K0 + +open scoped Classical BigOperators + +section + +structure Idempotent (R : Type*) [Ring R] where + size : ℕ + matrix : Matrix (Fin size) (Fin size) R + idem : matrix*matrix=matrix + +variable {R : Type*} [Ring R] + +def directSum (e f : Idempotent R) : Idempotent R where + size := e.size+f.size + matrix := Matrix.reindexRingEquiv R finSumFinEquiv (Matrix.fromBlocks e.matrix 0 0 f.matrix) + idem := by + rw [←map_mul,Matrix.fromBlocks_multiply] + simp only [Matrix.mul_zero,Matrix.zero_mul,add_zero,zero_add,e.idem,f.idem] + +def relationGenerators (R : Type*) [Ring R] : Set (FreeAbelianGroup (Idempotent R)) := + {x | (∃e f : Idempotent R,∃a : Matrix (Fin e.size) (Fin f.size) R, + ∃b : Matrix (Fin f.size) (Fin e.size) R, + a*b=e.matrix ∧ b*a=f.matrix ∧ x=FreeAbelianGroup.of e-FreeAbelianGroup.of f) ∨ + (∃e f : Idempotent R,x=FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)} + +def relations (R : Type*) [Ring R] : AddSubgroup (FreeAbelianGroup (Idempotent R)) := + AddSubgroup.closure (relationGenerators R) + +instance relations_normal (R : Type*) [Ring R] : (relations R).Normal := inferInstance + +abbrev Group (R : Type*) [Ring R] := FreeAbelianGroup (Idempotent R) ⧸ relations R + +def classOf (e : Idempotent R) : Group R := QuotientAddGroup.mk' (relations R) (FreeAbelianGroup.of e) + +variable {G : Type*} [_root_.Group G] + +instance groupRingRelations_normal : (relations (MonoidAlgebra ℂ G)).Normal := inferInstance + +def rawCoefficient (g : G) : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ ℂ := + FreeAbelianGroup.lift (fun e=>classCoefficient g (Matrix.trace e.matrix)) + +end + +variable {G : Type*} [_root_.Group G] + +def classTrace (a : MonoidAlgebra ℂ G) : ConjClasses G →₀ ℂ := + Finsupp.mapDomain ConjClasses.mk a.coeff + +def rawTrace : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G)) →+ (ConjClasses G →₀ ℂ) := + FreeAbelianGroup.lift (fun e=>classTrace (Matrix.trace e.matrix)) + +def HattoriStallings : Group (MonoidAlgebra ℂ G) →+ (ConjClasses G →₀ ℂ) := by + have classCoefficient_zero (g : G) : + classCoefficient g 0 = 0 := by + simp [classCoefficient] + have classCoefficient_single (g h : G) (z : ℂ) : + classCoefficient g (MonoidAlgebra.single h z) = if IsConj h g then z else 0 := by + classical + simp [classCoefficient, Finsupp.sum_single_index] + have classCoefficient_add (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a + b) = classCoefficient g a + classCoefficient g b := by + classical + apply Finsupp.sum_add_index + · intro h _ + simp + · intro h _ z w + split_ifs <;> simp + have classCoefficient_smul (g : G) (z : ℂ) (a : MonoidAlgebra ℂ G) : + classCoefficient g (z • a) = z * classCoefficient g a := by + classical + unfold classCoefficient + rw [MonoidAlgebra.coeff_smul, Finsupp.sum_smul_index (fun _ => by simp)] + rw [Finsupp.sum, Finsupp.sum, Finset.mul_sum] + apply Finset.sum_congr rfl + intro h _ + split_ifs <;> simp + have classCoefficient_sum {ι : Type} (g : G) (s : Finset ι) + (f : ι → MonoidAlgebra ℂ G) : + classCoefficient g (∑ i ∈ s, f i) = ∑ i ∈ s, classCoefficient g (f i) := by + classical + induction s using Finset.induction_on with + | empty => simp [classCoefficient_zero] + | @insert a s ha ih => simp [classCoefficient_add, ha, ih] + have classCoefficient_mul_comm (g : G) (a b : MonoidAlgebra ℂ G) : + classCoefficient g (a * b) = classCoefficient g (b * a) := by + induction a using MonoidAlgebra.induction_on with + | of h => + induction b using MonoidAlgebra.induction_on with + | of k => + have hconj : IsConj (h * k) (k * h) := by + apply isConj_iff.mpr + exact ⟨k, by simp [mul_assoc]⟩ + have hiff : IsConj (h * k) g ↔ IsConj (k * h) g := + ⟨hconj.symm.trans, hconj.trans⟩ + change classCoefficient g (MonoidAlgebra.single h 1 * MonoidAlgebra.single k 1) = + classCoefficient g (MonoidAlgebra.single k 1 * MonoidAlgebra.single h 1) + simp only [MonoidAlgebra.single_mul_single, classCoefficient_single, hiff] + | add b c hb hc => simp only [mul_add, add_mul, classCoefficient_add, hb, hc] + | smul z b hb => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, hb] + | add a c ha hc => simp only [add_mul, mul_add, classCoefficient_add, ha, hc] + | smul z a ha => simp only [mul_smul_comm, smul_mul_assoc, classCoefficient_smul, ha] + have classCoefficient_matrix_mul_comm {ι κ : Type} [Fintype ι] [Fintype κ] + (g : G) (a : Matrix ι κ (MonoidAlgebra ℂ G)) + (b : Matrix κ ι (MonoidAlgebra ℂ G)) : + classCoefficient g (Matrix.trace (a * b)) = + classCoefficient g (Matrix.trace (b * a)) := by + classical + simp only [Matrix.trace, Matrix.diag, Matrix.mul_apply, classCoefficient_sum] + rw [Finset.sum_comm] + apply Finset.sum_congr rfl + intro i _ + apply Finset.sum_congr rfl + intro j _ + exact classCoefficient_mul_comm g _ _ + have trace_reindex {α β : Type} [Fintype α] [Fintype β] + (j : α≃β) (a : Matrix α α (MonoidAlgebra ℂ G)) : + Matrix.trace (Matrix.reindexRingEquiv (MonoidAlgebra ℂ G) j a)=Matrix.trace a := by + change (∑i, a (j.symm i) (j.symm i))=∑i,a i i + exact Equiv.sum_comp j.symm (fun i=>a i i) + have trace_directSum (e f : Idempotent (MonoidAlgebra ℂ G)) : + Matrix.trace (directSum e f).matrix=Matrix.trace e.matrix+Matrix.trace f.matrix := by + rw [directSum,trace_reindex] + simp only [Matrix.trace,Matrix.diag,Fintype.sum_sum_type,Matrix.fromBlocks_apply₁₁,Matrix.fromBlocks_apply₂₂] + have relations_in_kernel (g : G) : relations (MonoidAlgebra ℂ G)≤(rawCoefficient g).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨e,f,a,b,hab,hba,rfl⟩|⟨e,f,rfl⟩ + · change rawCoefficient g (FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of] + apply sub_eq_zero.mpr + rw [←hab,←hba] + exact classCoefficient_matrix_mul_comm g a b + · change rawCoefficient g (FreeAbelianGroup.of (directSum e f)-FreeAbelianGroup.of e-FreeAbelianGroup.of f)=0 + simp only [map_sub,rawCoefficient,FreeAbelianGroup.lift_apply_of,trace_directSum,classCoefficient_add] + rw [add_sub_cancel_left, sub_self] + have classTrace_apply (a : MonoidAlgebra ℂ G) (g : G) : + classTrace a (ConjClasses.mk g)=classCoefficient g a := by + unfold classTrace classCoefficient + simp only [Finsupp.mapDomain,Finsupp.sum_apply,Finsupp.single_apply] + apply Finset.sum_congr rfl + intro h hh + dsimp only + by_cases hc : IsConj h g + · rw [ite_eq_left (ConjClasses.mk_eq_mk_iff_isConj.mpr hc), ite_eq_left hc] + · rw [ite_eq_right (mt ConjClasses.mk_eq_mk_iff_isConj.mp hc), ite_eq_right hc] + have rawTrace_apply (z : FreeAbelianGroup (Idempotent (MonoidAlgebra ℂ G))) (g : G) : + rawTrace z (ConjClasses.mk g)=rawCoefficient g z := by + induction z using FreeAbelianGroup.induction_on with + | zero => simp only [map_zero,Finsupp.zero_apply] + | of e => + simp only [rawTrace,rawCoefficient,FreeAbelianGroup.lift_apply_of] + exact classTrace_apply _ g + | neg e he => simp only [map_neg,Finsupp.neg_apply,he] + | add x y hx hy => simp only [map_add,Finsupp.add_apply,hx,hy] + have relations_in_trace_kernel : relations (MonoidAlgebra ℂ G)≤(rawTrace (G := G)).ker := by + intro z hz + change rawTrace z=0 + ext c + obtain ⟨g,rfl⟩ := ConjClasses.mk_surjective c + rw [rawTrace_apply,Finsupp.zero_apply] + exact relations_in_kernel g hz + exact QuotientAddGroup.lift (relations (MonoidAlgebra ℂ G)) rawTrace relations_in_trace_kernel + +end K0 + +namespace RightProjective + +open scoped Classical BigOperators + +open MulOpposite + +section + +variable {R : Type*} [Ring R] + +instance rightModuleIdentityRingHomInvPair : + RingHomInvPair (RingHom.id Rᵐᵒᵖ) (RingHom.id Rᵐᵒᵖ) := RingHomInvPair.ids + +def unopTranspose {m n : Type*} (a : Matrix m n Rᵐᵒᵖ) : Matrix n m R := + fun i j=>unop (a j i) + +def rightMatrix {m n : ℕ} (f : (Fin m → Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n → Rᵐᵒᵖ)) : + Matrix (Fin n) (Fin m) R := unopTranspose (LinearMap.toMatrixRight' f) + +structure Retraction (R M : Type*) [Ring R] [AddCommGroup M] [Module Rᵐᵒᵖ M] where + size : ℕ + proj : (Fin size →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] M + inc : M →ₗ[Rᵐᵒᵖ] (Fin size →Rᵐᵒᵖ) + split : proj.comp inc=LinearMap.id + +variable {M N : Type*} [AddCommGroup M] [Module Rᵐᵒᵖ M] + [AddCommGroup N] [Module Rᵐᵒᵖ N] + +def Retraction.idempotent (r : Retraction R M) : K0.Idempotent R := by + have unopTranspose_mul {l m n : Type} [Fintype m] + (a : Matrix l m Rᵐᵒᵖ) (b : Matrix m n Rᵐᵒᵖ) : + unopTranspose (a*b)=unopTranspose b*unopTranspose a := by + ext i j + simp only [unopTranspose,Matrix.mul_apply] + change (opAddEquiv.symm : Rᵐᵒᵖ≃+R) (∑k,a j k*b k i)=_ + rw [map_sum] + rfl + have rightMatrix_comp {l m n : ℕ} + (f : (Fin l →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin m →Rᵐᵒᵖ)) + (g : (Fin m →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n →Rᵐᵒᵖ)) : + rightMatrix (g.comp f)=rightMatrix g*rightMatrix f := by + simp only [rightMatrix,LinearMap.toMatrixRight'_comp,unopTranspose_mul] + exact { + size := r.size + matrix := rightMatrix (r.inc.comp r.proj) + idem := by + rw [←rightMatrix_comp] + congr 1 + calc (r.inc.comp r.proj).comp (r.inc.comp r.proj) = + r.inc.comp ((r.proj.comp r.inc).comp r.proj) := by simp only [LinearMap.comp_assoc] + _ = r.inc.comp r.proj := by rw [r.split,LinearMap.id_comp] } + +def Retraction.transport (r : Retraction R M) (u : M≃ₗ[Rᵐᵒᵖ] N) : Retraction R N where + size := r.size + proj := u.toLinearMap.comp r.proj + inc := r.inc.comp u.symm.toLinearMap + split := by + calc (u.toLinearMap.comp r.proj).comp (r.inc.comp u.symm.toLinearMap) = + u.toLinearMap.comp ((r.proj.comp r.inc).comp u.symm.toLinearMap) := by simp only [LinearMap.comp_assoc] + _ = LinearMap.id := by rw [r.split,LinearMap.id_comp,LinearEquiv.comp_symm] + +def freeSplit (n m : ℕ) : (Fin (n+m)→Rᵐᵒᵖ) ≃ₗ[Rᵐᵒᵖ] (Fin n→Rᵐᵒᵖ) × (Fin m→Rᵐᵒᵖ) := + (LinearEquiv.piCongrLeft' Rᵐᵒᵖ (fun _ : Fin (n+m)=>Rᵐᵒᵖ) finSumFinEquiv.symm).trans + (LinearEquiv.sumArrowLequivProdArrow (Fin n) (Fin m) Rᵐᵒᵖ Rᵐᵒᵖ) + +def Retraction.prod (r : Retraction R M) (s : Retraction R N) : Retraction R (M×N) where + size := r.size+s.size + proj := (r.proj.prodMap s.proj).comp (freeSplit r.size s.size).toLinearMap + inc := (freeSplit r.size s.size).symm.toLinearMap.comp (r.inc.prodMap s.inc) + split := by + apply LinearMap.ext + intro x + change ((r.proj.prodMap s.proj) ((freeSplit r.size s.size) + ((freeSplit r.size s.size).symm ((r.inc.prodMap s.inc) x))))=x + rw [LinearEquiv.apply_symm_apply] + have hr := LinearMap.congr_fun r.split x.1 + have hs := LinearMap.congr_fun s.split x.2 + exact Prod.ext hr hs + +end + +open scoped Classical + +universe u v + +structure Object (R : Type u) [Ring R] where + carrier : Type v + [addCommGroup : AddCommGroup carrier] + [module : Module Rᵐᵒᵖ carrier] + [finite : Module.Finite Rᵐᵒᵖ carrier] + [projective : Module.Projective Rᵐᵒᵖ carrier] + +attribute [instance] Object.addCommGroup Object.module Object.finite Object.projective + +variable {R : Type u} [Ring R] + +def Object.prod (P Q : Object.{u,v} R) : Object.{u,v} R where + carrier := P.carrier × Q.carrier + +def Object.retraction (P : Object.{u,v} R) : Retraction R P.carrier := + Classical.choice (by + obtain ⟨n, f, g, _, _, h⟩ := Module.Finite.exists_comp_eq_id_of_projective Rᵐᵒᵖ P.carrier + exact ⟨⟨n, f, g, h⟩⟩) + +def Object.presentationClass (P : Object.{u,v} R) : K0.Group R := + K0.classOf P.retraction.idempotent + +def moduleRelationGenerators (R : Type u) [Ring R] : Set (FreeAbelianGroup (Object.{u,v} R)) := + {x | (∃P Q : Object.{u,v} R, Nonempty (P.carrier≃ₗ[Rᵐᵒᵖ] Q.carrier) ∧ + x=FreeAbelianGroup.of P-FreeAbelianGroup.of Q) ∨ + (∃P Q : Object.{u,v} R, + x=FreeAbelianGroup.of (P.prod Q)-FreeAbelianGroup.of P-FreeAbelianGroup.of Q)} + +def moduleRelations (R : Type u) [Ring R] : AddSubgroup (FreeAbelianGroup (Object.{u,v} R)) := + AddSubgroup.closure (moduleRelationGenerators R) + +abbrev ModuleK0 (R : Type u) [Ring R] := + FreeAbelianGroup (Object.{u,v} R) ⧸ moduleRelations R + +def rawPresentation : FreeAbelianGroup (Object.{u,v} R) →+ K0.Group R := + FreeAbelianGroup.lift Object.presentationClass + +def presentation : ModuleK0.{u,v} R →+ K0.Group R := by + have unopTranspose_mul {l m n : ℕ} + (a : Matrix (Fin l) (Fin m) Rᵐᵒᵖ) (b : Matrix (Fin m) (Fin n) Rᵐᵒᵖ) : + unopTranspose (a*b)=unopTranspose b*unopTranspose a := by + ext i j + simp only [unopTranspose,Matrix.mul_apply] + change (opAddEquiv.symm : Rᵐᵒᵖ≃+R) (∑k,a j k*b k i)=_ + rw [map_sum] + rfl + have rightMatrix_comp {l m n : ℕ} + (f : (Fin l →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin m →Rᵐᵒᵖ)) + (g : (Fin m →Rᵐᵒᵖ) →ₗ[Rᵐᵒᵖ] (Fin n →Rᵐᵒᵖ)) : + rightMatrix (g.comp f)=rightMatrix g*rightMatrix f := by + simp only [rightMatrix,LinearMap.toMatrixRight'_comp,unopTranspose_mul] + have classOf_eq_of_rectangular (e f : K0.Idempotent R) + (a : Matrix (Fin e.size) (Fin f.size) R) + (b : Matrix (Fin f.size) (Fin e.size) R) (hab : a*b=e.matrix) (hba : b*a=f.matrix) : + K0.classOf e=K0.classOf f := by + apply sub_eq_zero.mp + change (QuotientAddGroup.mk' (K0.relations R)) (FreeAbelianGroup.of e)- + (QuotientAddGroup.mk' (K0.relations R)) (FreeAbelianGroup.of f)=0 + rw [←map_sub] + change (QuotientAddGroup.mk (FreeAbelianGroup.of e-FreeAbelianGroup.of f) : K0.Group R)=0 + apply (QuotientAddGroup.eq_zero_iff _).mpr + exact AddSubgroup.subset_closure (Or.inl ⟨e,f,a,b,hab,hba,rfl⟩) + have Retraction.class_eq {M : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] (r s : Retraction R M) : + K0.classOf r.idempotent=K0.classOf s.idempotent := by + apply classOf_eq_of_rectangular _ _ + (rightMatrix (r.inc.comp s.proj)) (rightMatrix (s.inc.comp r.proj)) + · change rightMatrix (r.inc.comp s.proj)*rightMatrix (s.inc.comp r.proj)= + rightMatrix (r.inc.comp r.proj) + rw [←rightMatrix_comp] + congr 1 + calc (r.inc.comp s.proj).comp (s.inc.comp r.proj) = + r.inc.comp ((s.proj.comp s.inc).comp r.proj) := by simp only [LinearMap.comp_assoc] + _ = r.inc.comp r.proj := by rw [s.split,LinearMap.id_comp] + · change rightMatrix (s.inc.comp r.proj)*rightMatrix (r.inc.comp s.proj)= + rightMatrix (s.inc.comp s.proj) + rw [←rightMatrix_comp] + congr 1 + calc (s.inc.comp r.proj).comp (r.inc.comp s.proj) = + s.inc.comp ((r.proj.comp r.inc).comp s.proj) := by simp only [LinearMap.comp_assoc] + _ = s.inc.comp s.proj := by rw [r.split,LinearMap.id_comp] + have Retraction.transport_idempotent {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (u : M≃ₗ[Rᵐᵒᵖ] N) : + (r.transport u).idempotent=r.idempotent := by + dsimp only [Retraction.idempotent] + congr 1 + change rightMatrix ((r.inc.comp u.symm.toLinearMap).comp (u.toLinearMap.comp r.proj))= + rightMatrix (r.inc.comp r.proj) + congr 1 + apply LinearMap.ext + intro x + change r.inc (u.symm (u (r.proj x)))=r.inc (r.proj x) + rw [u.symm_apply_apply] + have freeSplit_apply_left (n m : ℕ) (v : Fin (n+m)→Rᵐᵒᵖ) (i : Fin n) : + (freeSplit n m v).1 i=v (finSumFinEquiv (Sum.inl i)) := rfl + have freeSplit_apply_right (n m : ℕ) (v : Fin (n+m)→Rᵐᵒᵖ) (i : Fin m) : + (freeSplit n m v).2 i=v (finSumFinEquiv (Sum.inr i)) := rfl + have freeSplit_symm_left (n m : ℕ) (v : Fin n→Rᵐᵒᵖ) (w : Fin m→Rᵐᵒᵖ) (i : Fin n) : + (freeSplit n m).symm (v,w) (finSumFinEquiv (Sum.inl i))=v i := by + have h := congrArg (fun x=>(x.1 : Fin n→Rᵐᵒᵖ) i) ((freeSplit (R := R) n m).apply_symm_apply (v,w)) + exact h + have freeSplit_symm_right (n m : ℕ) (v : Fin n→Rᵐᵒᵖ) (w : Fin m→Rᵐᵒᵖ) (i : Fin m) : + (freeSplit n m).symm (v,w) (finSumFinEquiv (Sum.inr i))=w i := by + have h := congrArg (fun x=>(x.2 : Fin m→Rᵐᵒᵖ) i) ((freeSplit (R := R) n m).apply_symm_apply (v,w)) + exact h + have freeSplit_single_left (n m : ℕ) (i : Fin n) : + freeSplit (R := R) n m (Pi.single (finSumFinEquiv (Sum.inl i)) 1)=(Pi.single i 1,0) := by + apply Prod.ext + · ext j + rw [freeSplit_apply_left] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inl.injEq] + · ext j + rw [freeSplit_apply_right] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inr_ne_inl,ite_false,Pi.zero_apply] + have freeSplit_single_right (n m : ℕ) (i : Fin m) : + freeSplit (R := R) n m (Pi.single (finSumFinEquiv (Sum.inr i)) 1)=(0,Pi.single i 1) := by + apply Prod.ext + · ext j + rw [freeSplit_apply_left] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inl_ne_inr,ite_false,Pi.zero_apply] + · ext j + rw [freeSplit_apply_right] + simp only [Pi.single_apply,Equiv.apply_eq_iff_eq,Sum.inr.injEq] + have Retraction.prod_matrix {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (s : Retraction R N) : + (r.prod s).idempotent.matrix=(K0.directSum r.idempotent s.idempotent).matrix := by + ext i j + obtain ⟨i,rfl⟩ := finSumFinEquiv.surjective i + obtain ⟨j,rfl⟩ := finSumFinEquiv.surjective j + change unop ((freeSplit r.size s.size).symm ((r.inc.prodMap s.inc) + ((r.proj.prodMap s.proj) ((freeSplit r.size s.size) + (Pi.single (finSumFinEquiv j) 1)))) (finSumFinEquiv i))= + Matrix.fromBlocks (rightMatrix (r.inc.comp r.proj)) 0 0 (rightMatrix (s.inc.comp s.proj)) + (finSumFinEquiv.symm (finSumFinEquiv i)) (finSumFinEquiv.symm (finSumFinEquiv j)) + simp only [Equiv.symm_apply_apply] + cases i with | inl i => ?_ | inr i => ?_ + all_goals cases j with | inl j => ?_ | inr j => ?_ + · rw [freeSplit_single_left] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_left,Matrix.fromBlocks_apply₁₁] + rfl + · rw [freeSplit_single_right] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_left,Matrix.fromBlocks_apply₁₂, + Pi.zero_apply,unop_zero,Matrix.zero_apply] + · rw [freeSplit_single_left] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_right,Matrix.fromBlocks_apply₂₁, + Pi.zero_apply,unop_zero,Matrix.zero_apply] + · rw [freeSplit_single_right] + simp only [LinearMap.prodMap_apply,map_zero,freeSplit_symm_right,Matrix.fromBlocks_apply₂₂] + rfl + have Retraction.prod_idempotent {M N : Type v} [AddCommGroup M] [Module Rᵐᵒᵖ M] [AddCommGroup N] [Module Rᵐᵒᵖ N] (r : Retraction R M) (s : Retraction R N) : + (r.prod s).idempotent=K0.directSum r.idempotent s.idempotent := by + dsimp only [Retraction.idempotent, K0.directSum] + congr 1 + exact Retraction.prod_matrix r s + have classOf_directSum (e f : K0.Idempotent R) : + K0.classOf (K0.directSum e f)=K0.classOf e+K0.classOf f := by + apply sub_eq_zero.mp + change QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of (K0.directSum e f))- + (QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of e)+ + QuotientAddGroup.mk' (K0.relations R) (FreeAbelianGroup.of f))=0 + rw [←map_add,←map_sub] + change (QuotientAddGroup.mk (FreeAbelianGroup.of (K0.directSum e f)- + (FreeAbelianGroup.of e+FreeAbelianGroup.of f)) : K0.Group R)=0 + apply (QuotientAddGroup.eq_zero_iff _).mpr + rw [sub_add_eq_sub_sub] + exact AddSubgroup.subset_closure (Or.inr ⟨e,f,rfl⟩) + have Object.presentationClass_eq (P : Object.{u,v} R) (r : Retraction R P.carrier) : + P.presentationClass=K0.classOf r.idempotent := Retraction.class_eq P.retraction r + have Object.presentationClass_iso (P Q : Object.{u,v} R) + (i : P.carrier ≃ₗ[Rᵐᵒᵖ] Q.carrier) : P.presentationClass=Q.presentationClass := by + rw [Object.presentationClass_eq Q (P.retraction.transport i), Retraction.transport_idempotent] + rfl + have Object.presentationClass_prod (P Q : Object.{u,v} R) : + (P.prod Q).presentationClass=P.presentationClass+Q.presentationClass := by + calc + _ = K0.classOf (P.retraction.prod Q.retraction).idempotent := + Object.presentationClass_eq (P.prod Q) (P.retraction.prod Q.retraction) + _ = P.presentationClass+Q.presentationClass := by + rw [Retraction.prod_idempotent,classOf_directSum] + rfl + have moduleRelations_in_kernel : moduleRelations R≤(rawPresentation.{u,v} (R := R)).ker := by + apply (AddSubgroup.closure_le _).mpr + intro x hx + rcases hx with ⟨P,Q,⟨i⟩,rfl⟩ | ⟨P,Q,rfl⟩ + · change rawPresentation (FreeAbelianGroup.of P-FreeAbelianGroup.of Q)=0 + simp only [map_sub,rawPresentation,FreeAbelianGroup.lift_apply_of] + exact sub_eq_zero.mpr (Object.presentationClass_iso P Q i) + · change rawPresentation + (FreeAbelianGroup.of (P.prod Q)-FreeAbelianGroup.of P-FreeAbelianGroup.of Q)=0 + simp only [map_sub,rawPresentation,FreeAbelianGroup.lift_apply_of,Object.presentationClass_prod] + abel + exact QuotientAddGroup.lift (moduleRelations R) rawPresentation moduleRelations_in_kernel + +variable {G : Type u} [_root_.Group G] + +def HattoriStallings : ModuleK0.{u,v} (MonoidAlgebra ℂ G) →+ (ConjClasses G →₀ ℂ) := + K0.HattoriStallings.comp presentation + +theorem bassTraceModules_vanishing_and_support {G : Type u} [_root_.Group G] + (x : ModuleK0.{u,v} (MonoidAlgebra ℂ G)) : + (∀ g : G, ¬IsOfFinOrder g → HattoriStallings x (ConjClasses.mk g) = 0) ∧ + ↑(HattoriStallings x).support ⊆ + {c | ∃ g : G, IsOfFinOrder g ∧ ConjClasses.mk g = c} := + by sorry + +end RightProjective + +end BassTrace + +end + +end OAI diff --git a/tasks/bass-trace/tests/grade.py b/tasks/bass-trace/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bass-trace/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bass-trace/tests/task.json b/tasks/bass-trace/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..68785e4354b24b404384d020b9dfb0ace7403b90 --- /dev/null +++ b/tasks/bass-trace/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BassTrace", + "comparator": { + "theorem_names": [ + "OAI.BassTrace.RightProjective.bassTraceModules_vanishing_and_support" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11697 +} \ No newline at end of file diff --git a/tasks/bass-trace/tests/test.sh b/tasks/bass-trace/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bass-trace/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/benjamini-schramm/environment/Dockerfile b/tasks/benjamini-schramm/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/benjamini-schramm/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/benjamini-schramm/environment/fetch_mathlib.sh b/tasks/benjamini-schramm/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/benjamini-schramm/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/benjamini-schramm/environment/lake-manifest.json b/tasks/benjamini-schramm/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/benjamini-schramm/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/benjamini-schramm/environment/lakefile.lean b/tasks/benjamini-schramm/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/benjamini-schramm/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/benjamini-schramm/environment/lean_setup.sh b/tasks/benjamini-schramm/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/benjamini-schramm/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/benjamini-schramm/environment/pack_submission.py b/tasks/benjamini-schramm/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/benjamini-schramm/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/benjamini-schramm/instruction.md b/tasks/benjamini-schramm/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..08a34491244dbd152080be3cd6a1f58741c96d90 --- /dev/null +++ b/tasks/benjamini-schramm/instruction.md @@ -0,0 +1,291 @@ +# openai/math challenge `BenjaminiSchramm` (family 214) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 214 of the release, *The Benjamini–Schramm nonuniqueness conjecture* +(Probability and statistical mechanics). The family as a whole: Proves $p_c ∃ e ∈ ω, G e = s(a, b)) x y + +def cluster (G : BondGraph V E) (ω : Set E) (x : V) : Set V := + {y | Conn G ω x y} + +def infiniteClusters (G : BondGraph V E) (ω : Set E) : Set (Set V) := + {C | C.Infinite ∧ ∃ x, C = cluster G ω x} + +noncomputable def law (p : unitInterval) : Measure (Set E) := + setBernoulli Set.univ p + +noncomputable def pc (G : BondGraph V E) : unitInterval := + sInf {p | 0 < law p {ω | (infiniteClusters G ω).Nonempty}} + +noncomputable def pu (G : BondGraph V E) : unitInterval := + sInf {p | law p {ω | ∃! C, C ∈ infiniteClusters G ω} = 1} + +noncomputable def twoPoint (G : BondGraph V E) (p : unitInterval) (x y : V) : ℝ := + (law p {ω | Conn G ω x y}).toReal + +noncomputable abbrev Hilbert (V : Type u) := lp (fun _ : V => ℂ) 2 + +noncomputable def HasKernel [DecidableEq V] + (G : BondGraph V E) (p : unitInterval) + (A : Hilbert V →L[ℂ] Hilbert V) : Prop := + ∀ x y, (A (lp.single 2 y (1 : ℂ))) x = (twoPoint G p x y : ℂ) + +noncomputable def OperatorBounded (G : BondGraph V E) (p : unitInterval) : Prop := by + classical + exact ∃ A : Hilbert V →L[ℂ] Hilbert V, HasKernel G p A + +noncomputable def operatorNorm (G : BondGraph V E) (p : unitInterval) : ℝ≥0∞ := by + classical + exact sInf {r | ∃ A : Hilbert V →L[ℂ] Hilbert V, + HasKernel G p A ∧ r = ENNReal.ofReal ‖A‖} + +noncomputable def ptwo (G : BondGraph V E) : unitInterval := + sSup {p | OperatorBounded G p} + +noncomputable def labelLaw : Measure (E → unitInterval) := + Measure.infinitePi (fun _ => (volume : Measure unitInterval)) + +def openEdges (labels : E → unitInterval) (p : unitInterval) : Set E := + {e | labels e ≤ p} + +def MainConclusion (G : BondGraph V E) : Prop := + (sSup {r | ∃ p : unitInterval, p < pc G ∧ r = operatorNorm G p} = + operatorNorm G (pc G)) ∧ + operatorNorm G (pc G) < ⊤ ∧ + pc G < ptwo G ∧ ptwo G ≤ pu G ∧ + ∃ p₁ p₂ : unitInterval, pc G < p₁ ∧ p₁ < p₂ ∧ p₂ < 1 ∧ + ∀ᵐ labels ∂(labelLaw : Measure (E → unitInterval)), + ∀ p ∈ Set.Icc p₁ p₂, (infiniteClusters G (openEdges labels p)).Infinite + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.propDecidable + +def openSimpleGraph (G : BondGraph V E) (ω : Set E) : SimpleGraph V where + Adj x y := x ≠ y ∧ ∃ e ∈ ω, G e = s(x,y) + symm := ⟨by + rintro x y ⟨hxy, e, he, h⟩ + exact ⟨hxy.symm, e, he, h.trans (Sym2.eq_swap ..)⟩⟩ + loopless := ⟨by simp⟩ + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.propDecidable Classical.decEq + +noncomputable def susceptibility (G : BondGraph V E) (p : unitInterval) (x : V) : ℝ := + ∑' y, twoPoint G p x y + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.decEq + +noncomputable def triangleDiagram (G : BondGraph V E) (p : unitInterval) (x : V) : ℝ≥0∞ := + ∑' ab : V × V, ENNReal.ofReal + (twoPoint G p x ab.1 * twoPoint G p ab.1 ab.2 * twoPoint G p ab.2 x) + +noncomputable def graphDistance (G : BondGraph V E) (x y : V) : ℕ := + (openSimpleGraph G Set.univ).dist x y + +def ExponentialDecay (G : BondGraph V E) (p : unitInterval) : Prop := + ∃ A a : ℝ, 0 < A ∧ 0 < a ∧ ∀ x y, + twoPoint G p x y ≤ A * Real.exp (-a * graphDistance G x y) + +noncomputable def pexp (G : BondGraph V E) : unitInterval := + sSup {p | ExponentialDecay G p} + +def PowerTail (f : ℕ → ℝ) (exponent : ℝ) : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∀ n : ℕ, 0 < n → + c * (n : ℝ) ^ (-exponent) ≤ f n ∧ f n ≤ C * (n : ℝ) ^ (-exponent) + +def volumeEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | (n : ℕ∞) ≤ (cluster G ω x).encard} + +def intrinsicRadiusEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | ∃ y ∈ cluster G ω x, n ≤ (openSimpleGraph G ω).dist x y} + +def extrinsicRadiusEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | ∃ y ∈ cluster G ω x, n ≤ graphDistance G x y} + +noncomputable def criticalTail (G : BondGraph V E) + (A : V → ℕ → Set (Set E)) (x : V) (n : ℕ) : ℝ := + (law (pc G) (A x n)).toReal + +def CriticalTailLaws (G : BondGraph V E) : Prop := + ∀ x, PowerTail (criticalTail G (volumeEvent G) x) (1 / 2) ∧ + PowerTail (criticalTail G (intrinsicRadiusEvent G) x) 1 ∧ + PowerTail (criticalTail G (extrinsicRadiusEvent G) x) 1 + +def SusceptibilityLaw (G : BondGraph V E) : Prop := + ∀ x, ∃ c C δ : ℝ, 0 < c ∧ 0 < C ∧ 0 < δ ∧ + ∀ p : unitInterval, p < pc G → (pc G : ℝ) - p < δ → + c / ((pc G : ℝ) - p) ≤ susceptibility G p x ∧ + susceptibility G p x ≤ C / ((pc G : ℝ) - p) + +noncomputable def percolationProbability (G : BondGraph V E) (p : unitInterval) + (x : V) : ℝ := (law p {ω | (cluster G ω x).Infinite}).toReal + +def PercolationProbabilityLaw (G : BondGraph V E) : Prop := + ∀ x, ∃ c C δ : ℝ, 0 < c ∧ 0 < C ∧ 0 < δ ∧ + ∀ p : unitInterval, pc G < p → (p : ℝ) - pc G < δ → + c * ((p : ℝ) - pc G) ≤ percolationProbability G p x ∧ + percolationProbability G p x ≤ C * ((p : ℝ) - pc G) + +end Percolation.BenjaminiSchramm + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u v +variable {V : Type u} {E : Type v} + +def CriticalLawsConclusion (G : BondGraph V E) : Prop := + (∀ x, triangleDiagram G (pc G) x ≤ operatorNorm G (pc G) ^ 3 ∧ + triangleDiagram G (pc G) x < ⊤) ∧ + SusceptibilityLaw G ∧ PercolationProbabilityLaw G ∧ CriticalTailLaws G ∧ + (pc G < ptwo G ∧ ptwo G ≤ pexp G) ∧ + ∀ p : unitInterval, p < ptwo G → ExponentialDecay G p + +end Percolation.BenjaminiSchramm + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u +variable {Λ : Type u} [Group Λ] +attribute [local instance] Classical.decEq + +abbrev CayleyEdge (S : Finset Λ) := (SimpleGraph.mulCayley (S : Set Λ)).edgeSet + +def cayleyBond (S : Finset Λ) : BondGraph Λ (CayleyEdge S) := Subtype.val + +def FolnerAmenable (Λ : Type u) [Group Λ] : Prop := + ∀ K : Finset Λ, ∀ ε : ℝ, 0 < ε → ∃ A : Finset Λ, A.Nonempty ∧ + ∀ k ∈ K, (((A.image (fun x => x * k)) \ A).card : ℝ) < ε * A.card + +end Percolation.BenjaminiSchramm + +namespace Percolation.BenjaminiSchramm + +universe u v + +/-- Critical operator boundedness, the threshold gap, and simultaneous nonuniqueness. -/ +theorem full_main {V : Type u} {E : Type v} [Infinite V] + (G : BondGraph V E) (hc : Connected G) (hl : LocallyFinite G) + (hq : QuasiTransitive G) (hh : 0 < hV G) : MainConclusion G := by + sorry + +/-- Critical mean-field laws and uniform exponential connectivity below the operator threshold. -/ +theorem critical_laws {V : Type u} {E : Type v} [Infinite V] + (G : BondGraph V E) (hc : Connected G) (hl : LocallyFinite G) + (hq : QuasiTransitive G) (hh : 0 < hV G) : CriticalLawsConclusion G := by + sorry + +/-- Nonuniqueness for every prescribed finite symmetric Cayley generating set. -/ +theorem cayley_main {Λ : Type u} [Group Λ] + (S : Finset Λ) (hsym : ∀ s ∈ S, s⁻¹ ∈ S) (_hone : 1 ∉ S) + (hgen : Subgroup.closure (S : Set Λ) = ⊤) (hna : ¬ FolnerAmenable Λ) : + OperatorBounded (cayleyBond S) (pc (cayleyBond S)) ∧ + MainConclusion (cayleyBond S) ∧ + ∀ p : unitInterval, pc (cayleyBond S) < p → p < pu (cayleyBond S) → + ∀ᵐ ω ∂law p, (infiniteClusters (cayleyBond S) ω).Infinite := by + sorry + +end Percolation.BenjaminiSchramm + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BenjaminiSchramm.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Percolation.BenjaminiSchramm.full_main`, `OAI.Percolation.BenjaminiSchramm.cayley_main`, `OAI.Percolation.BenjaminiSchramm.critical_laws` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/benjamini-schramm/solution/closure.txt b/tasks/benjamini-schramm/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0cc2d4f040ccaf38350407e80c9256dc28b045d --- /dev/null +++ b/tasks/benjamini-schramm/solution/closure.txt @@ -0,0 +1,970 @@ +OAI.Probability.BenjaminiSchramm.AntitoneSurvivalHeight +OAI.Probability.BenjaminiSchramm.Application +OAI.Probability.BenjaminiSchramm.AvoidanceCostProfile +OAI.Probability.BenjaminiSchramm.AvoidanceProduct +OAI.Probability.BenjaminiSchramm.BallSnapshot +OAI.Probability.BenjaminiSchramm.BandMomentSummability +OAI.Probability.BenjaminiSchramm.BlockExposure +OAI.Probability.BenjaminiSchramm.BoundaryMultiplicity +OAI.Probability.BenjaminiSchramm.BoundedLayerShift +OAI.Probability.BenjaminiSchramm.BoundedOrbitDescent +OAI.Probability.BenjaminiSchramm.Cayley +OAI.Probability.BenjaminiSchramm.CayleyCritical +OAI.Probability.BenjaminiSchramm.CayleyInputs +OAI.Probability.BenjaminiSchramm.CayleyTheorem +OAI.Probability.BenjaminiSchramm.CeilingBandTransport +OAI.Probability.BenjaminiSchramm.CeilingBandUniform +OAI.Probability.BenjaminiSchramm.CeilingDownCrudeProfile +OAI.Probability.BenjaminiSchramm.CeilingZeroBand +OAI.Probability.BenjaminiSchramm.ClusterExposure +OAI.Probability.BenjaminiSchramm.CombinatorialUnimodularOperator +OAI.Probability.BenjaminiSchramm.Consequences +OAI.Probability.BenjaminiSchramm.ConsistentLayers +OAI.Probability.BenjaminiSchramm.CriticalCeilingProfile +OAI.Probability.BenjaminiSchramm.CriticalEndpointProfiles +OAI.Probability.BenjaminiSchramm.CriticalFiniteness +OAI.Probability.BenjaminiSchramm.CriticalFractionalSlab +OAI.Probability.BenjaminiSchramm.CriticalFullspaceProfiles +OAI.Probability.BenjaminiSchramm.CriticalHalfspaceDecay +OAI.Probability.BenjaminiSchramm.CriticalHalfspaceProfiles +OAI.Probability.BenjaminiSchramm.CriticalHeightHit +OAI.Probability.BenjaminiSchramm.CriticalNormalizedCrossing +OAI.Probability.BenjaminiSchramm.CriticalPeakBand +OAI.Probability.BenjaminiSchramm.CriticalPeakComparison +OAI.Probability.BenjaminiSchramm.CriticalPeakSurvival +OAI.Probability.BenjaminiSchramm.CriticalQuarterMoment +OAI.Probability.BenjaminiSchramm.CriticalSlabProfiles +OAI.Probability.BenjaminiSchramm.CriticalSusceptibility +OAI.Probability.BenjaminiSchramm.CriticalUpwardDecay +OAI.Probability.BenjaminiSchramm.CrossingExponent +OAI.Probability.BenjaminiSchramm.CrossingExponentContinuity +OAI.Probability.BenjaminiSchramm.CrossingPositivity +OAI.Probability.BenjaminiSchramm.DeletionBound +OAI.Probability.BenjaminiSchramm.DeletionLoss +OAI.Probability.BenjaminiSchramm.DownwardHalfspaceFromContinuation +OAI.Probability.BenjaminiSchramm.EdgeClosing +OAI.Probability.BenjaminiSchramm.EntropyEvent +OAI.Probability.BenjaminiSchramm.EventLeftContinuity +OAI.Probability.BenjaminiSchramm.EventMeasurability +OAI.Probability.BenjaminiSchramm.ExponentialDecay +OAI.Probability.BenjaminiSchramm.ExteriorConnection +OAI.Probability.BenjaminiSchramm.ExteriorContact +OAI.Probability.BenjaminiSchramm.ExteriorEscape +OAI.Probability.BenjaminiSchramm.ExteriorExposure +OAI.Probability.BenjaminiSchramm.FiniteClusterSums +OAI.Probability.BenjaminiSchramm.FiniteEnergyModification +OAI.Probability.BenjaminiSchramm.FiniteEnergyObservable +OAI.Probability.BenjaminiSchramm.FiniteOrbitStationary +OAI.Probability.BenjaminiSchramm.FirstHeightPeakWalk +OAI.Probability.BenjaminiSchramm.FloorDownProfile +OAI.Probability.BenjaminiSchramm.FractionalBandEstimate +OAI.Probability.BenjaminiSchramm.FractionalBandGeometry +OAI.Probability.BenjaminiSchramm.FractionalBandTransport +OAI.Probability.BenjaminiSchramm.FractionalExponentBootstrap +OAI.Probability.BenjaminiSchramm.FractionalHolder +OAI.Probability.BenjaminiSchramm.FractionalInterpolation +OAI.Probability.BenjaminiSchramm.FractionalSlabEstimate +OAI.Probability.BenjaminiSchramm.FractionalSlabFromTruncation +OAI.Probability.BenjaminiSchramm.FractionalSlabGeometry +OAI.Probability.BenjaminiSchramm.FractionalSlabTransport +OAI.Probability.BenjaminiSchramm.FreshSlabConcatenation +OAI.Probability.BenjaminiSchramm.FreshSlabCrossing +OAI.Probability.BenjaminiSchramm.FreshWhiteExposure +OAI.Probability.BenjaminiSchramm.FullConclusion +OAI.Probability.BenjaminiSchramm.FullLayerProfile +OAI.Probability.BenjaminiSchramm.FullNegativeLayerProfile +OAI.Probability.BenjaminiSchramm.FullspaceFractionalRecurrence +OAI.Probability.BenjaminiSchramm.GeneralCriticalFiniteness +OAI.Probability.BenjaminiSchramm.GeometricIncrement +OAI.Probability.BenjaminiSchramm.GhostAvoidance +OAI.Probability.BenjaminiSchramm.GhostBondBK +OAI.Probability.BenjaminiSchramm.GhostCluster +OAI.Probability.BenjaminiSchramm.GhostCritical +OAI.Probability.BenjaminiSchramm.GhostDerivative +OAI.Probability.BenjaminiSchramm.GhostDifferentialAssembly +OAI.Probability.BenjaminiSchramm.GhostDoubleConnection +OAI.Probability.BenjaminiSchramm.GhostEntropy +OAI.Probability.BenjaminiSchramm.GhostFan +OAI.Probability.BenjaminiSchramm.GhostFanBK +OAI.Probability.BenjaminiSchramm.GhostField +OAI.Probability.BenjaminiSchramm.GhostMomentBound +OAI.Probability.BenjaminiSchramm.GhostMomentDischarge +OAI.Probability.BenjaminiSchramm.GhostPivotalBound +OAI.Probability.BenjaminiSchramm.GhostPivotalBoundary +OAI.Probability.BenjaminiSchramm.GhostPivotalGeometry +OAI.Probability.BenjaminiSchramm.GhostPivotalIncidence +OAI.Probability.BenjaminiSchramm.GhostPivotalProbability +OAI.Probability.BenjaminiSchramm.GhostPivotalSum +OAI.Probability.BenjaminiSchramm.GhostPivotalUnion +OAI.Probability.BenjaminiSchramm.GhostPivotalWeight +OAI.Probability.BenjaminiSchramm.GhostTail +OAI.Probability.BenjaminiSchramm.GhostTiltedTransport +OAI.Probability.BenjaminiSchramm.GhostVolume +OAI.Probability.BenjaminiSchramm.HalfspaceConcatenation +OAI.Probability.BenjaminiSchramm.HalfspaceFiniteShift +OAI.Probability.BenjaminiSchramm.HalfspaceFiniteShiftProfile +OAI.Probability.BenjaminiSchramm.HalfspaceFractionalRecurrence +OAI.Probability.BenjaminiSchramm.HalfspaceProfileBootstrap +OAI.Probability.BenjaminiSchramm.HalfspaceRootComparison +OAI.Probability.BenjaminiSchramm.HarmonicHeightAscent +OAI.Probability.BenjaminiSchramm.HarmonicHeightDescent +OAI.Probability.BenjaminiSchramm.HeightMaximumSlices +OAI.Probability.BenjaminiSchramm.HeightOrbitConnection +OAI.Probability.BenjaminiSchramm.InputReduction +OAI.Probability.BenjaminiSchramm.IntegerFrontierCrossing +OAI.Probability.BenjaminiSchramm.IntegerLayerFirstVisit +OAI.Probability.BenjaminiSchramm.IntrinsicBallExposure +OAI.Probability.BenjaminiSchramm.IntrinsicBallGrowth +OAI.Probability.BenjaminiSchramm.IntrinsicBallisticity +OAI.Probability.BenjaminiSchramm.IntrinsicConnection +OAI.Probability.BenjaminiSchramm.IntrinsicConnectionAverage +OAI.Probability.BenjaminiSchramm.IntrinsicFreshPath +OAI.Probability.BenjaminiSchramm.IntrinsicRadiusLower +OAI.Probability.BenjaminiSchramm.IntrinsicRadiusUpper +OAI.Probability.BenjaminiSchramm.IntrinsicSphere +OAI.Probability.BenjaminiSchramm.KernelDeletionDiagram +OAI.Probability.BenjaminiSchramm.KernelDeletionOperator +OAI.Probability.BenjaminiSchramm.KernelExterior +OAI.Probability.BenjaminiSchramm.KernelExteriorBound +OAI.Probability.BenjaminiSchramm.LayerCrossingComparison +OAI.Probability.BenjaminiSchramm.LayerFirstMomentPositivity +OAI.Probability.BenjaminiSchramm.LayerFirstMomentRate +OAI.Probability.BenjaminiSchramm.LayerFirstMomentSubmultiplicative +OAI.Probability.BenjaminiSchramm.LayerFirstMoments +OAI.Probability.BenjaminiSchramm.LayerFreshSelection +OAI.Probability.BenjaminiSchramm.LayerFrontierExpectation +OAI.Probability.BenjaminiSchramm.LayerFrontierGeometry +OAI.Probability.BenjaminiSchramm.LayerFrontierLocalization +OAI.Probability.BenjaminiSchramm.LayerMaximumDecomposition +OAI.Probability.BenjaminiSchramm.LayerMomentCauchy +OAI.Probability.BenjaminiSchramm.LayerMomentDecomposition +OAI.Probability.BenjaminiSchramm.LayerMomentFekete +OAI.Probability.BenjaminiSchramm.LayerMonotoneLimit +OAI.Probability.BenjaminiSchramm.LayerPrefactorBootstrap +OAI.Probability.BenjaminiSchramm.LayerProfileAtRate +OAI.Probability.BenjaminiSchramm.LayerSecondMomentDecomposition +OAI.Probability.BenjaminiSchramm.Main +OAI.Probability.BenjaminiSchramm.MeanFieldReduction +OAI.Probability.BenjaminiSchramm.MinimumHeightHit +OAI.Probability.BenjaminiSchramm.MixedHeightMoment +OAI.Probability.BenjaminiSchramm.MixedRootPathComparison +OAI.Probability.BenjaminiSchramm.MixedRootSurgery +OAI.Probability.BenjaminiSchramm.ModularCrossingRate +OAI.Probability.BenjaminiSchramm.ModularSchur +OAI.Probability.BenjaminiSchramm.ModularSlabs +OAI.Probability.BenjaminiSchramm.NegativeMomentConvolution +OAI.Probability.BenjaminiSchramm.NeighborDegreeBound +OAI.Probability.BenjaminiSchramm.Nonunimodular +OAI.Probability.BenjaminiSchramm.NonunimodularMomentReduction +OAI.Probability.BenjaminiSchramm.NormalizedCrossingRate +OAI.Probability.BenjaminiSchramm.NormalizedEscapeRisk +OAI.Probability.BenjaminiSchramm.NormalizedExponentComparison +OAI.Probability.BenjaminiSchramm.NormalizedHalfspace +OAI.Probability.BenjaminiSchramm.NormalizedLayerTransport +OAI.Probability.BenjaminiSchramm.NormalizedPeakSurgery +OAI.Probability.BenjaminiSchramm.NormalizedQuarterMoment +OAI.Probability.BenjaminiSchramm.OpenTriangle +OAI.Probability.BenjaminiSchramm.OperatorGap +OAI.Probability.BenjaminiSchramm.OperatorMeanFieldReduction +OAI.Probability.BenjaminiSchramm.OperatorSusceptibility +OAI.Probability.BenjaminiSchramm.OrbitHeightComparison +OAI.Probability.BenjaminiSchramm.OrbitNeighborChain +OAI.Probability.BenjaminiSchramm.OrbitNormalization +OAI.Probability.BenjaminiSchramm.OrbitTransport +OAI.Probability.BenjaminiSchramm.PairedSprinkling +OAI.Probability.BenjaminiSchramm.PeakBandProbability +OAI.Probability.BenjaminiSchramm.PeakBandSecondMoment +OAI.Probability.BenjaminiSchramm.PeakBandTransport +OAI.Probability.BenjaminiSchramm.PeakClusterCorrelation +OAI.Probability.BenjaminiSchramm.PeakComparison +OAI.Probability.BenjaminiSchramm.PeakComparisonAveraging +OAI.Probability.BenjaminiSchramm.PeakComplementCorrelation +OAI.Probability.BenjaminiSchramm.PeakConditionalLayers +OAI.Probability.BenjaminiSchramm.PeakCorrelationAveraging +OAI.Probability.BenjaminiSchramm.PeakCostBound +OAI.Probability.BenjaminiSchramm.PeakCountComparison +OAI.Probability.BenjaminiSchramm.PeakExposureComparison +OAI.Probability.BenjaminiSchramm.PeakExposureGeometry +OAI.Probability.BenjaminiSchramm.PeakExtension +OAI.Probability.BenjaminiSchramm.PeakFiniteEnergy +OAI.Probability.BenjaminiSchramm.PeakFrontierTruncation +OAI.Probability.BenjaminiSchramm.PeakHalfspaceGeometry +OAI.Probability.BenjaminiSchramm.PeakHalfspaceTransport +OAI.Probability.BenjaminiSchramm.PeakLayerCost +OAI.Probability.BenjaminiSchramm.PeakLayerEstimate +OAI.Probability.BenjaminiSchramm.PeakOrbitComparison +OAI.Probability.BenjaminiSchramm.PeakRateCancellation +OAI.Probability.BenjaminiSchramm.PeakSlabComparison +OAI.Probability.BenjaminiSchramm.PeakSprinklingAverage +OAI.Probability.BenjaminiSchramm.PeakSprinklingCell +OAI.Probability.BenjaminiSchramm.PeakSprinklingCost +OAI.Probability.BenjaminiSchramm.PeakSprinklingSurvival +OAI.Probability.BenjaminiSchramm.PeakSurgeryAverage +OAI.Probability.BenjaminiSchramm.PeakSurgeryGeometry +OAI.Probability.BenjaminiSchramm.PeakSurgeryProbability +OAI.Probability.BenjaminiSchramm.PeakSurvivalCauchy +OAI.Probability.BenjaminiSchramm.PeakSurvivalRealHeight +OAI.Probability.BenjaminiSchramm.PeakUpperExposure +OAI.Probability.BenjaminiSchramm.PhaseInput +OAI.Probability.BenjaminiSchramm.PivotalExposure +OAI.Probability.BenjaminiSchramm.PrefixMaximumBootstrap +OAI.Probability.BenjaminiSchramm.ProbabilityLower +OAI.Probability.BenjaminiSchramm.ProbabilityUpper +OAI.Probability.BenjaminiSchramm.ProbeEntropy +OAI.Probability.BenjaminiSchramm.PublishedConsequences +OAI.Probability.BenjaminiSchramm.RadiusInputReduction +OAI.Probability.BenjaminiSchramm.RadiusTransfer +OAI.Probability.BenjaminiSchramm.ReciprocalDecay +OAI.Probability.BenjaminiSchramm.ReciprocalGrowth +OAI.Probability.BenjaminiSchramm.RestrictedMomentHolder +OAI.Probability.BenjaminiSchramm.RootGhostSums +OAI.Probability.BenjaminiSchramm.RootTiltedGhost +OAI.Probability.BenjaminiSchramm.SelectedLayerVertex +OAI.Probability.BenjaminiSchramm.SignedUpperConvolution +OAI.Probability.BenjaminiSchramm.SlabCountBasic +OAI.Probability.BenjaminiSchramm.SlabCrossing +OAI.Probability.BenjaminiSchramm.SlabExtensionGeometry +OAI.Probability.BenjaminiSchramm.SlabFirstVisit +OAI.Probability.BenjaminiSchramm.SlabFractionalProfileShift +OAI.Probability.BenjaminiSchramm.SlabFractionalRecurrence +OAI.Probability.BenjaminiSchramm.SlabHit +OAI.Probability.BenjaminiSchramm.SlabLastMaximum +OAI.Probability.BenjaminiSchramm.SlabRootShift +OAI.Probability.BenjaminiSchramm.SlabSecondMoment +OAI.Probability.BenjaminiSchramm.SmallWalkKernel +OAI.Probability.BenjaminiSchramm.SmallWitness +OAI.Probability.BenjaminiSchramm.SprinklingAvoidanceProfile +OAI.Probability.BenjaminiSchramm.SprinklingParameter +OAI.Probability.BenjaminiSchramm.SprinklingPeakGeometry +OAI.Probability.BenjaminiSchramm.SubcriticalCrossingBound +OAI.Probability.BenjaminiSchramm.SubcriticalFullLayerProfile +OAI.Probability.BenjaminiSchramm.SubcriticalLayerConvolution +OAI.Probability.BenjaminiSchramm.SubcriticalLayerPrefactor +OAI.Probability.BenjaminiSchramm.SubcriticalPeakConditional +OAI.Probability.BenjaminiSchramm.SubcriticalPeakProbability +OAI.Probability.BenjaminiSchramm.SubcriticalPeakSurvival +OAI.Probability.BenjaminiSchramm.SubcriticalUpperSecondMoment +OAI.Probability.BenjaminiSchramm.SubcriticalUpward +OAI.Probability.BenjaminiSchramm.SubdivisionConsequences +OAI.Probability.BenjaminiSchramm.SubdivisionGeometry +OAI.Probability.BenjaminiSchramm.SubdivisionOperator +OAI.Probability.BenjaminiSchramm.SusceptibilityComparison +OAI.Probability.BenjaminiSchramm.SusceptibilityDerivative +OAI.Probability.BenjaminiSchramm.SusceptibilityDerivativeLower +OAI.Probability.BenjaminiSchramm.SusceptibilityLaw +OAI.Probability.BenjaminiSchramm.SusceptibilityUpper +OAI.Probability.BenjaminiSchramm.ThinSphere +OAI.Probability.BenjaminiSchramm.ThinSphereExposure +OAI.Probability.BenjaminiSchramm.ThinSphereProbability +OAI.Probability.BenjaminiSchramm.ThinSphereRecurrence +OAI.Probability.BenjaminiSchramm.ThinSphereStopping +OAI.Probability.BenjaminiSchramm.TiltedGhost +OAI.Probability.BenjaminiSchramm.TiltedGhostSusceptibility +OAI.Probability.BenjaminiSchramm.TiltedHit +OAI.Probability.BenjaminiSchramm.TiltedMagnetization +OAI.Probability.BenjaminiSchramm.TiltedMomentBridge +OAI.Probability.BenjaminiSchramm.TiltedMoments +OAI.Probability.BenjaminiSchramm.TiltedSusceptibility +OAI.Probability.BenjaminiSchramm.TruncatedFractionalSummation +OAI.Probability.BenjaminiSchramm.TruncatedSlabMoment +OAI.Probability.BenjaminiSchramm.TwoGhost +OAI.Probability.BenjaminiSchramm.UnconditionalInputs +OAI.Probability.BenjaminiSchramm.UniformHeightAscent +OAI.Probability.BenjaminiSchramm.UniformHeightDescent +OAI.Probability.BenjaminiSchramm.UpperLayerSecondMoment +OAI.Probability.BenjaminiSchramm.UpperMomentConvolution +OAI.Probability.BenjaminiSchramm.UpwardCeilingProfile +OAI.Probability.BenjaminiSchramm.UpwardFractionalSlabProfile +OAI.Probability.BenjaminiSchramm.UpwardFrontierProbability +OAI.Probability.BenjaminiSchramm.UpwardHalfspaceFromContinuation +OAI.Probability.BenjaminiSchramm.VolumeEntropy +OAI.Probability.BenjaminiSchramm.VolumeLower +OAI.Probability.BenjaminiSchramm.WeightedCostRetention +OAI.Probability.BenjaminiSchramm.WeightedGhostIncidence +OAI.Probability.BenjaminiSchramm.WeightedMomentCauchy +OAI.Probability.BenjaminiSchramm.WeightedPeakSlabComparison +OAI.Probability.CriticalPercolation.Classification.AlgebraicDescent +OAI.Probability.CriticalPercolation.Classification.ClassificationProducerBoundary +OAI.Probability.CriticalPercolation.Classification.CompactQuotientProper +OAI.Probability.CriticalPercolation.Classification.ConcreteStructureAssembly +OAI.Probability.CriticalPercolation.Classification.DiscreteWeakGromovBridge +OAI.Probability.CriticalPercolation.Classification.FaithfulOrbitalModel +OAI.Probability.CriticalPercolation.Classification.FiniteBGTBridge +OAI.Probability.CriticalPercolation.Classification.FiniteClassificationObstruction +OAI.Probability.CriticalPercolation.Classification.GraphCompactNormalClassification +OAI.Probability.CriticalPercolation.Classification.QualitativeClassificationBoundary +OAI.Probability.CriticalPercolation.Classification.RawClassificationBoundary +OAI.Probability.CriticalPercolation.Classification.RelativeClassification +OAI.Probability.CriticalPercolation.Classification.RestrictedQuotient +OAI.Probability.CriticalPercolation.Classification.StructuredCoordinates +OAI.Probability.CriticalPercolation.Classification.WeakGromovMainBoundary +OAI.Probability.CriticalPercolation.Clusters.ClusterCountFlip +OAI.Probability.CriticalPercolation.Clusters.ClusterNumber +OAI.Probability.CriticalPercolation.Clusters.ClusterObject +OAI.Probability.CriticalPercolation.Clusters.ClusterObjectAvoidanceCross +OAI.Probability.CriticalPercolation.Clusters.ClusterTail +OAI.Probability.CriticalPercolation.Clusters.ClusterUpdate +OAI.Probability.CriticalPercolation.Clusters.ComponentSelf +OAI.Probability.CriticalPercolation.Clusters.CriticalClusterMultiplicity +OAI.Probability.CriticalPercolation.Clusters.DeleteBot +OAI.Probability.CriticalPercolation.Clusters.Earlier +OAI.Probability.CriticalPercolation.Clusters.ExpectedCluster +OAI.Probability.CriticalPercolation.Clusters.FiniteClusterCover +OAI.Probability.CriticalPercolation.Clusters.FiniteForcing +OAI.Probability.CriticalPercolation.Clusters.ForcedDisconnectContinuity +OAI.Probability.CriticalPercolation.Clusters.GraphErgodicity +OAI.Probability.CriticalPercolation.Clusters.HitOthers +OAI.Probability.CriticalPercolation.Clusters.HitValue +OAI.Probability.CriticalPercolation.Clusters.InfiniteUniqueness +OAI.Probability.CriticalPercolation.Clusters.InfiniteUniquenessGeometry +OAI.Probability.CriticalPercolation.Clusters.PercolationTail +OAI.Probability.CriticalPercolation.Clusters.ThreeClusterAvoidanceGeneral +OAI.Probability.CriticalPercolation.Clusters.ThreeClusterAvoidanceSecond +OAI.Probability.CriticalPercolation.Criticality.ActualGrowth +OAI.Probability.CriticalPercolation.Criticality.AutDisplacement +OAI.Probability.CriticalPercolation.Criticality.BalancedCycles +OAI.Probability.CriticalPercolation.Criticality.BandScale +OAI.Probability.CriticalPercolation.Criticality.BlockIndependence +OAI.Probability.CriticalPercolation.Criticality.BlockLocalization +OAI.Probability.CriticalPercolation.Criticality.BoundaryCount +OAI.Probability.CriticalPercolation.Criticality.BoundedNormalJoins +OAI.Probability.CriticalPercolation.Criticality.ClassTwoRankOne +OAI.Probability.CriticalPercolation.Criticality.ClosedBoundedCuts +OAI.Probability.CriticalPercolation.Criticality.CompactDiscreteQuotient +OAI.Probability.CriticalPercolation.Criticality.ComponentCritical +OAI.Probability.CriticalPercolation.Criticality.ContractingDomains +OAI.Probability.CriticalPercolation.Criticality.CriticalFragility +OAI.Probability.CriticalPercolation.Criticality.CutInside +OAI.Probability.CriticalPercolation.Criticality.CylinderApproximation +OAI.Probability.CriticalPercolation.Criticality.DeleteImageIso +OAI.Probability.CriticalPercolation.Criticality.DescendingFan +OAI.Probability.CriticalPercolation.Criticality.DescentCritical +OAI.Probability.CriticalPercolation.Criticality.DirectionalTail +OAI.Probability.CriticalPercolation.Criticality.DiskWinding +OAI.Probability.CriticalPercolation.Criticality.DomainPercolation +OAI.Probability.CriticalPercolation.Criticality.DyadicBound +OAI.Probability.CriticalPercolation.Criticality.ExhaustionEvents +OAI.Probability.CriticalPercolation.Criticality.ExpandingCharacterGrowth +OAI.Probability.CriticalPercolation.Criticality.FavoredFinite +OAI.Probability.CriticalPercolation.Criticality.FewOpenBonds +OAI.Probability.CriticalPercolation.Criticality.FiniteEdgeInterpolation +OAI.Probability.CriticalPercolation.Criticality.FiniteEnergy +OAI.Probability.CriticalPercolation.Criticality.FiniteInterpolation +OAI.Probability.CriticalPercolation.Criticality.FiniteInterpolationUniform +OAI.Probability.CriticalPercolation.Criticality.FiniteNearbyPair +OAI.Probability.CriticalPercolation.Criticality.FiniteSeedTree +OAI.Probability.CriticalPercolation.Criticality.FiniteSusceptibility +OAI.Probability.CriticalPercolation.Criticality.FourthMomentFatou +OAI.Probability.CriticalPercolation.Criticality.GeometricFourth +OAI.Probability.CriticalPercolation.Criticality.GrowthAlternatives +OAI.Probability.CriticalPercolation.Criticality.GrowthEstimate +OAI.Probability.CriticalPercolation.Criticality.GrowthProcess +OAI.Probability.CriticalPercolation.Criticality.HeightCuts +OAI.Probability.CriticalPercolation.Criticality.IndicableDegreeStep +OAI.Probability.CriticalPercolation.Criticality.InfiniteEscapeLowerBound +OAI.Probability.CriticalPercolation.Criticality.InfiniteInterpolation +OAI.Probability.CriticalPercolation.Criticality.InfiniteNearbyPair +OAI.Probability.CriticalPercolation.Criticality.IntegerBoxes +OAI.Probability.CriticalPercolation.Criticality.InterpolationUniform +OAI.Probability.CriticalPercolation.Criticality.IntrinsicCriticalFragility +OAI.Probability.CriticalPercolation.Criticality.InvariantFiniteSets +OAI.Probability.CriticalPercolation.Criticality.LayerContradiction +OAI.Probability.CriticalPercolation.Criticality.LayerCounting +OAI.Probability.CriticalPercolation.Criticality.LayerLocality +OAI.Probability.CriticalPercolation.Criticality.Leak +OAI.Probability.CriticalPercolation.Criticality.LocalDescendingBlock +OAI.Probability.CriticalPercolation.Criticality.MainResidualBoundary +OAI.Probability.CriticalPercolation.Criticality.MainSparseBoundary +OAI.Probability.CriticalPercolation.Criticality.MinimalInterpolation +OAI.Probability.CriticalPercolation.Criticality.MinimalPair +OAI.Probability.CriticalPercolation.Criticality.NestedLayerBlock +OAI.Probability.CriticalPercolation.Criticality.NormalClosureGrowth +OAI.Probability.CriticalPercolation.Criticality.OneDimensionalCritical +OAI.Probability.CriticalPercolation.Criticality.OpenRay +OAI.Probability.CriticalPercolation.Criticality.PairedSparseScales +OAI.Probability.CriticalPercolation.Criticality.ParameterLeftBounds +OAI.Probability.CriticalPercolation.Criticality.PositiveCritical +OAI.Probability.CriticalPercolation.Criticality.RestrictedInterpolation +OAI.Probability.CriticalPercolation.Criticality.RestrictedSeed +OAI.Probability.CriticalPercolation.Criticality.ReverseReference +OAI.Probability.CriticalPercolation.Criticality.SharpnessPhi +OAI.Probability.CriticalPercolation.Criticality.SignedCountIdentity +OAI.Probability.CriticalPercolation.Criticality.SparseLinearCritical +OAI.Probability.CriticalPercolation.Criticality.SpecifiedFailures +OAI.Probability.CriticalPercolation.Criticality.SquareBoundary +OAI.Probability.CriticalPercolation.Criticality.SubcriticalLocalRateBound +OAI.Probability.CriticalPercolation.Criticality.SubexponentialVolumes +OAI.Probability.CriticalPercolation.Criticality.SubgroupFiniteIndexExtension +OAI.Probability.CriticalPercolation.Criticality.TwoPoint +OAI.Probability.CriticalPercolation.Criticality.TwoPointSelf +OAI.Probability.CriticalPercolation.Criticality.UniformDescendingFan +OAI.Probability.CriticalPercolation.Criticality.UniformLocalContinuity +OAI.Probability.CriticalPercolation.Criticality.VirtualIndicability +OAI.Probability.CriticalPercolation.Criticality.Weight +OAI.Probability.CriticalPercolation.Criticality.WitnessEvents +OAI.Probability.CriticalPercolation.Entropy.AeEvalNe +OAI.Probability.CriticalPercolation.Entropy.BinaryConfiguration +OAI.Probability.CriticalPercolation.Entropy.BinaryCostBound +OAI.Probability.CriticalPercolation.Entropy.BinaryCosts +OAI.Probability.CriticalPercolation.Entropy.BinaryDescriptor +OAI.Probability.CriticalPercolation.Entropy.BinaryEventBound +OAI.Probability.CriticalPercolation.Entropy.BinaryForest +OAI.Probability.CriticalPercolation.Entropy.BinaryInterpolation +OAI.Probability.CriticalPercolation.Entropy.BinaryInverseCost +OAI.Probability.CriticalPercolation.Entropy.BinaryLaw +OAI.Probability.CriticalPercolation.Entropy.BinaryLikelihood +OAI.Probability.CriticalPercolation.Entropy.BinaryMarks +OAI.Probability.CriticalPercolation.Entropy.BinaryOutput +OAI.Probability.CriticalPercolation.Entropy.BinaryOutputEntropy +OAI.Probability.CriticalPercolation.Entropy.BinaryPairs +OAI.Probability.CriticalPercolation.Entropy.BinaryParents +OAI.Probability.CriticalPercolation.Entropy.BinaryPrefix +OAI.Probability.CriticalPercolation.Entropy.BinaryRaw +OAI.Probability.CriticalPercolation.Entropy.BinaryReferenceLikelihood +OAI.Probability.CriticalPercolation.Entropy.BinaryReverseKernels +OAI.Probability.CriticalPercolation.Entropy.BinaryReversePrices +OAI.Probability.CriticalPercolation.Entropy.BinaryStages +OAI.Probability.CriticalPercolation.Entropy.BinarySupport +OAI.Probability.CriticalPercolation.Entropy.BinarySwitches +OAI.Probability.CriticalPercolation.Entropy.BinaryTranscript +OAI.Probability.CriticalPercolation.Entropy.BinaryWords +OAI.Probability.CriticalPercolation.Entropy.Divergence +OAI.Probability.CriticalPercolation.Entropy.EndpointKernel +OAI.Probability.CriticalPercolation.Entropy.FiberValue +OAI.Probability.CriticalPercolation.Entropy.FiniteEventEntropy +OAI.Probability.CriticalPercolation.Entropy.FreshSet +OAI.Probability.CriticalPercolation.Entropy.MarkedBits +OAI.Probability.CriticalPercolation.Entropy.MarkedEntropy +OAI.Probability.CriticalPercolation.Entropy.MulLogDivScaled +OAI.Probability.CriticalPercolation.Entropy.RecursiveLikelihood +OAI.Probability.CriticalPercolation.Entropy.ReverseGuess +OAI.Probability.CriticalPercolation.Entropy.Uniform01 +OAI.Probability.CriticalPercolation.Exploration.AdaptiveReveal +OAI.Probability.CriticalPercolation.Exploration.AncestryForest +OAI.Probability.CriticalPercolation.Exploration.BallIncidence +OAI.Probability.CriticalPercolation.Exploration.BitWeight +OAI.Probability.CriticalPercolation.Exploration.ClosedFresh +OAI.Probability.CriticalPercolation.Exploration.ClosedPivotWeight +OAI.Probability.CriticalPercolation.Exploration.ClusterUsers +OAI.Probability.CriticalPercolation.Exploration.CompileContactPrefixCongr +OAI.Probability.CriticalPercolation.Exploration.CompileContactScoreErase +OAI.Probability.CriticalPercolation.Exploration.CompileEmptyReads +OAI.Probability.CriticalPercolation.Exploration.CompileStop +OAI.Probability.CriticalPercolation.Exploration.DecisionHistory +OAI.Probability.CriticalPercolation.Exploration.Exhaustive +OAI.Probability.CriticalPercolation.Exploration.FrontierDivergence +OAI.Probability.CriticalPercolation.Exploration.GlobalNode +OAI.Probability.CriticalPercolation.Exploration.GrowthHistoryGeometry +OAI.Probability.CriticalPercolation.Exploration.IncidenceDegree +OAI.Probability.CriticalPercolation.Exploration.IncidenceIdentity +OAI.Probability.CriticalPercolation.Exploration.IncidenceSearch +OAI.Probability.CriticalPercolation.Exploration.Initial +OAI.Probability.CriticalPercolation.Exploration.Initial2 +OAI.Probability.CriticalPercolation.Exploration.LayerExposure +OAI.Probability.CriticalPercolation.Exploration.ListScore +OAI.Probability.CriticalPercolation.Exploration.LocalNode +OAI.Probability.CriticalPercolation.Exploration.Node +OAI.Probability.CriticalPercolation.Exploration.OpenFrontierDivergence +OAI.Probability.CriticalPercolation.Exploration.PhaseFrontier +OAI.Probability.CriticalPercolation.Exploration.PivotalComparison +OAI.Probability.CriticalPercolation.Exploration.PrefixScoreNonneg +OAI.Probability.CriticalPercolation.Exploration.PrefixState +OAI.Probability.CriticalPercolation.Exploration.QueryBand +OAI.Probability.CriticalPercolation.Exploration.QueryDelta +OAI.Probability.CriticalPercolation.Exploration.QueryGeometry +OAI.Probability.CriticalPercolation.Exploration.QueryNormalized +OAI.Probability.CriticalPercolation.Exploration.QueryTree +OAI.Probability.CriticalPercolation.Exploration.ReachableIncidenceImp +OAI.Probability.CriticalPercolation.Exploration.ReachableMemPhaseClosed +OAI.Probability.CriticalPercolation.Exploration.Score +OAI.Probability.CriticalPercolation.Exploration.ScoreCongrSupport +OAI.Probability.CriticalPercolation.Exploration.ScoreMeanStep +OAI.Probability.CriticalPercolation.Exploration.SearchContactMoments +OAI.Probability.CriticalPercolation.Exploration.SearchMarkedContactBound +OAI.Probability.CriticalPercolation.Exploration.SearchTree +OAI.Probability.CriticalPercolation.Exploration.Select +OAI.Probability.CriticalPercolation.Exploration.SequentialExposure +OAI.Probability.CriticalPercolation.Exploration.SliceExploration +OAI.Probability.CriticalPercolation.Exploration.State +OAI.Probability.CriticalPercolation.Exploration.Tagged +OAI.Probability.CriticalPercolation.Exploration.TargetSearch +OAI.Probability.CriticalPercolation.Exploration.TraceTagged +OAI.Probability.CriticalPercolation.Exploration.TranscriptWeight +OAI.Probability.CriticalPercolation.Exploration.Users +OAI.Probability.CriticalPercolation.Exploration.Visits +OAI.Probability.CriticalPercolation.Gluing.ApproximateMoveEndgame +OAI.Probability.CriticalPercolation.Gluing.CollarDistance +OAI.Probability.CriticalPercolation.Gluing.CollarErrorBudget +OAI.Probability.CriticalPercolation.Gluing.ConditionalGluing +OAI.Probability.CriticalPercolation.Gluing.ContactExitPivot +OAI.Probability.CriticalPercolation.Gluing.ContactPivot +OAI.Probability.CriticalPercolation.Gluing.ContactSelection +OAI.Probability.CriticalPercolation.Gluing.ContourSites +OAI.Probability.CriticalPercolation.Gluing.ContourWords +OAI.Probability.CriticalPercolation.Gluing.CoordinateProspective +OAI.Probability.CriticalPercolation.Gluing.CorridorGraph +OAI.Probability.CriticalPercolation.Gluing.CorridorNormalization +OAI.Probability.CriticalPercolation.Gluing.CorridorScaleChoice +OAI.Probability.CriticalPercolation.Gluing.CorridorSeparation +OAI.Probability.CriticalPercolation.Gluing.DistanceCollarTransfer +OAI.Probability.CriticalPercolation.Gluing.DomainFreshExit +OAI.Probability.CriticalPercolation.Gluing.EllipseMoves +OAI.Probability.CriticalPercolation.Gluing.FewContacts +OAI.Probability.CriticalPercolation.Gluing.FiniteJointGluing +OAI.Probability.CriticalPercolation.Gluing.FiniteJointGluingStrict +OAI.Probability.CriticalPercolation.Gluing.FreshCollar +OAI.Probability.CriticalPercolation.Gluing.FreshCollarExact +OAI.Probability.CriticalPercolation.Gluing.FreshContactTransfer +OAI.Probability.CriticalPercolation.Gluing.FreshCorridor +OAI.Probability.CriticalPercolation.Gluing.FreshExitContinuity +OAI.Probability.CriticalPercolation.Gluing.FreshExitWitness +OAI.Probability.CriticalPercolation.Gluing.FreshTrial +OAI.Probability.CriticalPercolation.Gluing.HonestChoice +OAI.Probability.CriticalPercolation.Gluing.InwardTrial +OAI.Probability.CriticalPercolation.Gluing.LevelContactGeometry +OAI.Probability.CriticalPercolation.Gluing.MoveExit +OAI.Probability.CriticalPercolation.Gluing.MoveWitness +OAI.Probability.CriticalPercolation.Gluing.OpenTrialBound +OAI.Probability.CriticalPercolation.Gluing.PinnedTest +OAI.Probability.CriticalPercolation.Gluing.PredictionFailure +OAI.Probability.CriticalPercolation.Gluing.ProspectiveCorridor +OAI.Probability.CriticalPercolation.Gluing.RelayGeometry +OAI.Probability.CriticalPercolation.Gluing.RelayMoves +OAI.Probability.CriticalPercolation.Gluing.RelayScales +OAI.Probability.CriticalPercolation.Gluing.RootCorridor +OAI.Probability.CriticalPercolation.Gluing.SelectedFresh +OAI.Probability.CriticalPercolation.Gluing.SelectedTrials +OAI.Probability.CriticalPercolation.Gluing.SlotContour +OAI.Probability.CriticalPercolation.Gluing.SourceCollarTransfer +OAI.Probability.CriticalPercolation.Gluing.SourceConnectivity +OAI.Probability.CriticalPercolation.Gluing.SourceGraph +OAI.Probability.CriticalPercolation.Gluing.SourceLift +OAI.Probability.CriticalPercolation.Gluing.SourceRelaySeparation +OAI.Probability.CriticalPercolation.Gluing.StoredPrediction +OAI.Probability.CriticalPercolation.Gluing.StripMoves +OAI.Probability.CriticalPercolation.Gluing.TrialSelection +OAI.Probability.CriticalPercolation.Gluing.UniformFreshBoundary +OAI.Probability.CriticalPercolation.GraphGeometry.ActionCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.AdjacentLog +OAI.Probability.CriticalPercolation.GraphGeometry.BallCutGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.Column +OAI.Probability.CriticalPercolation.GraphGeometry.ColumnHitOthersOffdiag +OAI.Probability.CriticalPercolation.GraphGeometry.ComponentAction +OAI.Probability.CriticalPercolation.GraphGeometry.Connects +OAI.Probability.CriticalPercolation.GraphGeometry.CoordinateRotation +OAI.Probability.CriticalPercolation.GraphGeometry.CoordinateScheme +OAI.Probability.CriticalPercolation.GraphGeometry.CriticalCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.CutEdges +OAI.Probability.CriticalPercolation.GraphGeometry.CutEdgesSubsetIncident +OAI.Probability.CriticalPercolation.GraphGeometry.DeletedTailGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseAngles +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseBoundary +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseExit +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseGrid +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseLinear +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseMesh +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseOrigin +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseSeed +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseSeparation +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseUniform +OAI.Probability.CriticalPercolation.GraphGeometry.EncounterGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.EquivariantCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.EraseBond +OAI.Probability.CriticalPercolation.GraphGeometry.EuclideanEllipse +OAI.Probability.CriticalPercolation.GraphGeometry.ExpectedResidualAlt +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteActionAverage +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteAdjacent +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteCoverSums +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteIndexAction +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteInduced +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteKernelDescent +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteKernelOrbits +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteSumConnection +OAI.Probability.CriticalPercolation.GraphGeometry.ForceFalseSubset +OAI.Probability.CriticalPercolation.GraphGeometry.FullOrbitalStructureTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.GraphAction +OAI.Probability.CriticalPercolation.GraphGeometry.GraphActionCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.GraphApproximateNeighborhoods +OAI.Probability.CriticalPercolation.GraphGeometry.GraphBalls +OAI.Probability.CriticalPercolation.GraphGeometry.GraphQuotientPolynomial +OAI.Probability.CriticalPercolation.GraphGeometry.HitEvent +OAI.Probability.CriticalPercolation.GraphGeometry.HitEventUpperSet +OAI.Probability.CriticalPercolation.GraphGeometry.HittingSubAvoidance +OAI.Probability.CriticalPercolation.GraphGeometry.InducedAutomorphism +OAI.Probability.CriticalPercolation.GraphGeometry.InducedCritical +OAI.Probability.CriticalPercolation.GraphGeometry.InfiniteAdjacent +OAI.Probability.CriticalPercolation.GraphGeometry.InfiniteEventSubsetHit +OAI.Probability.CriticalPercolation.GraphGeometry.IntegerKernelGeneration +OAI.Probability.CriticalPercolation.GraphGeometry.IsolateThree +OAI.Probability.CriticalPercolation.GraphGeometry.LastInverseDiagonal +OAI.Probability.CriticalPercolation.GraphGeometry.LatticeGrowth +OAI.Probability.CriticalPercolation.GraphGeometry.Link +OAI.Probability.CriticalPercolation.GraphGeometry.Link2 +OAI.Probability.CriticalPercolation.GraphGeometry.LocallyConnectedActionKernel +OAI.Probability.CriticalPercolation.GraphGeometry.MapVertices +OAI.Probability.CriticalPercolation.GraphGeometry.MarkConnectivity +OAI.Probability.CriticalPercolation.GraphGeometry.MovingStrips +OAI.Probability.CriticalPercolation.GraphGeometry.NestedLayerGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.NormalOrbitAction +OAI.Probability.CriticalPercolation.GraphGeometry.ObjectKernel +OAI.Probability.CriticalPercolation.GraphGeometry.OpenGraphInsert +OAI.Probability.CriticalPercolation.GraphGeometry.OpenGraphIso +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitQuotientTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitRepresentatives +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalAction +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalFiniteGeneration +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalPacking +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalPower +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalScales +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalStructureTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.PhaseStepCharge +OAI.Probability.CriticalPercolation.GraphGeometry.ProbIsolateThree +OAI.Probability.CriticalPercolation.GraphGeometry.ReachableReplaceTail +OAI.Probability.CriticalPercolation.GraphGeometry.ResidualConvertedVariance +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictVertices +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictedAction +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictedOrbitalPacking +OAI.Probability.CriticalPercolation.GraphGeometry.StripCompactness +OAI.Probability.CriticalPercolation.GraphGeometry.StripContinuity +OAI.Probability.CriticalPercolation.GraphGeometry.StripCritical +OAI.Probability.CriticalPercolation.GraphGeometry.StripLinear +OAI.Probability.CriticalPercolation.GraphGeometry.StripOrigin +OAI.Probability.CriticalPercolation.GraphGeometry.StripUniform +OAI.Probability.CriticalPercolation.GraphGeometry.SubgroupOrbitKernel +OAI.Probability.CriticalPercolation.GraphGeometry.UniformGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.UpdateKernel +OAI.Probability.CriticalPercolation.GraphGeometry.VertexBall +OAI.Probability.CriticalPercolation.GraphGeometry.WiredEvent +OAI.Probability.CriticalPercolation.GraphTopology.CommensurableClosure +OAI.Probability.CriticalPercolation.GraphTopology.CompactOrbitKernel +OAI.Probability.CriticalPercolation.GraphTopology.GraphAutomorphismTopology +OAI.Probability.CriticalPercolation.GraphTopology.GraphGeneratingNeighborhood +OAI.Probability.CriticalPercolation.GraphTopology.GraphNeighborhoodCompact +OAI.Probability.CriticalPercolation.GraphTopology.LocalProjectiveTopology +OAI.Probability.CriticalPercolation.GraphTopology.LocallyCompactSubgroup +OAI.Probability.CriticalPercolation.GraphTopology.OpenNormalCore +OAI.Probability.CriticalPercolation.GraphTopology.OrbitalNeighborhoods +OAI.Probability.CriticalPercolation.GraphTopology.TopologicalClassificationBoundary +OAI.Probability.CriticalPercolation.Growth.CosetBallIndex +OAI.Probability.CriticalPercolation.Growth.CosetBounded +OAI.Probability.CriticalPercolation.Growth.CosetFiniteCore +OAI.Probability.CriticalPercolation.Growth.CosetFiniteIndex +OAI.Probability.CriticalPercolation.Growth.CosetGeometry +OAI.Probability.CriticalPercolation.Growth.CosetImageGrowth +OAI.Probability.CriticalPercolation.Growth.CosetIndicability +OAI.Probability.CriticalPercolation.Growth.CosetIntegerKernel +OAI.Probability.CriticalPercolation.Growth.CosetKernelDescent +OAI.Probability.CriticalPercolation.Growth.CosetNormalClosure +OAI.Probability.CriticalPercolation.Growth.CosetNormalPromotion +OAI.Probability.CriticalPercolation.Growth.CosetPresentation +OAI.Probability.CriticalPercolation.Growth.CosetSparseGrowth +OAI.Probability.CriticalPercolation.Growth.CosetSubgroupGenerators +OAI.Probability.CriticalPercolation.Growth.CosetTransfer +OAI.Probability.CriticalPercolation.Growth.GraphQuotientGrowth +OAI.Probability.CriticalPercolation.Growth.GraphRelativeGrowth +OAI.Probability.CriticalPercolation.Growth.HomogeneousAverage +OAI.Probability.CriticalPercolation.Growth.HomogeneousBallPacking +OAI.Probability.CriticalPercolation.Growth.HomogeneousCover +OAI.Probability.CriticalPercolation.Growth.HomogeneousDimension +OAI.Probability.CriticalPercolation.Growth.HomogeneousGeometry +OAI.Probability.CriticalPercolation.Growth.HomogeneousGrowth +OAI.Probability.CriticalPercolation.Growth.HomogeneousPolynomialSpace +OAI.Probability.CriticalPercolation.Growth.HomogeneousTransport +OAI.Probability.CriticalPercolation.Growth.KernelGrowthDescent +OAI.Probability.CriticalPercolation.Growth.PolynomialFolner +OAI.Probability.CriticalPercolation.Growth.PolynomialGrowthDescent +OAI.Probability.CriticalPercolation.Growth.RealSparseDoubling +OAI.Probability.CriticalPercolation.Growth.SparseDoubling +OAI.Probability.CriticalPercolation.Growth.SparseEnergyRatio +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialAlgebra +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialContradiction +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialMain +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialRadius +OAI.Probability.CriticalPercolation.Growth.WordBallPacking +OAI.Probability.CriticalPercolation.Growth.WordLengthGeometry +OAI.Probability.CriticalPercolation.Harmonic.AlmostHarmonicCompactness +OAI.Probability.CriticalPercolation.Harmonic.CayleyCaccioppoli +OAI.Probability.CriticalPercolation.Harmonic.CayleyPoincare +OAI.Probability.CriticalPercolation.Harmonic.CoverPoincare +OAI.Probability.CriticalPercolation.Harmonic.FiniteHilbert +OAI.Probability.CriticalPercolation.Harmonic.FunctionGramMatrix +OAI.Probability.CriticalPercolation.Harmonic.GeneralizedGramSpectrum +OAI.Probability.CriticalPercolation.Harmonic.GramGrowthScales +OAI.Probability.CriticalPercolation.Harmonic.GraphHarmonicCompactness +OAI.Probability.CriticalPercolation.Harmonic.GraphHarmonicLinear +OAI.Probability.CriticalPercolation.Harmonic.GraphProjectedFunctions +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkEnergy +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkOperator +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkProbability +OAI.Probability.CriticalPercolation.Harmonic.HarmonicDimensionBound +OAI.Probability.CriticalPercolation.Harmonic.HarmonicEnergy +OAI.Probability.CriticalPercolation.Harmonic.HarmonicFunctionSpace +OAI.Probability.CriticalPercolation.Harmonic.HarmonicLinearQuotient +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousCaccioppoli +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousGramScales +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousPoincare +OAI.Probability.CriticalPercolation.Harmonic.LazyWalkHilbert +OAI.Probability.CriticalPercolation.Harmonic.LazyWalkProbability +OAI.Probability.CriticalPercolation.Harmonic.PolynomialHarmonicSpace +OAI.Probability.CriticalPercolation.Harmonic.ProjectedWalkFunctions +OAI.Probability.CriticalPercolation.Harmonic.WalkAlmostHarmonic +OAI.Probability.CriticalPercolation.Harmonic.WalkEnergyLower +OAI.Probability.CriticalPercolation.Harmonic.WeakGromovHarmonic +OAI.Probability.CriticalPercolation.LinearGroups.AbsoluteMatrixSpan +OAI.Probability.CriticalPercolation.LinearGroups.AlgebraicVirtualSolvability +OAI.Probability.CriticalPercolation.LinearGroups.AllPlaceKronecker +OAI.Probability.CriticalPercolation.LinearGroups.ArchimedeanDetection +OAI.Probability.CriticalPercolation.LinearGroups.BurnsideDensity +OAI.Probability.CriticalPercolation.LinearGroups.ClusterMatrix +OAI.Probability.CriticalPercolation.LinearGroups.CongruenceTorsion +OAI.Probability.CriticalPercolation.LinearGroups.ConjugationMatrixGrowth +OAI.Probability.CriticalPercolation.LinearGroups.CountableFieldEmbedding +OAI.Probability.CriticalPercolation.LinearGroups.FgMatrixRing +OAI.Probability.CriticalPercolation.LinearGroups.FieldSpanTransfer +OAI.Probability.CriticalPercolation.LinearGroups.FiniteSubspaceOrbit +OAI.Probability.CriticalPercolation.LinearGroups.FullSpanAlternative +OAI.Probability.CriticalPercolation.LinearGroups.GeneralPeriodicCenter +OAI.Probability.CriticalPercolation.LinearGroups.InvariantBlockSolvability +OAI.Probability.CriticalPercolation.LinearGroups.InvariantSubspaceDensity +OAI.Probability.CriticalPercolation.LinearGroups.LocalFurstenbergBound +OAI.Probability.CriticalPercolation.LinearGroups.LocalFurstenbergConcentration +OAI.Probability.CriticalPercolation.LinearGroups.LocalPositiveSubspaceOrbit +OAI.Probability.CriticalPercolation.LinearGroups.LocalProjectiveAction +OAI.Probability.CriticalPercolation.LinearGroups.MatrixLowGrowthSubspace +OAI.Probability.CriticalPercolation.LinearGroups.MatrixPeriodicDirection +OAI.Probability.CriticalPercolation.LinearGroups.PadicDetection +OAI.Probability.CriticalPercolation.LinearGroups.PeriodicSpectrum +OAI.Probability.CriticalPercolation.LinearGroups.PowerBoundedUnipotent +OAI.Probability.CriticalPercolation.LinearGroups.ProjectiveEigenvalues +OAI.Probability.CriticalPercolation.LinearGroups.ProjectivePeriodicity +OAI.Probability.CriticalPercolation.LinearGroups.ProjectivelyPeriodicSchur +OAI.Probability.CriticalPercolation.LinearGroups.ProperPadicModels +OAI.Probability.CriticalPercolation.LinearGroups.RealVirtualSolvability +OAI.Probability.CriticalPercolation.LinearGroups.SelbergCongruence +OAI.Probability.CriticalPercolation.LinearGroups.SelbergSchur +OAI.Probability.CriticalPercolation.LinearGroups.SolvableGrowth +OAI.Probability.CriticalPercolation.LinearGroups.SolvablePeriodicCenter +OAI.Probability.CriticalPercolation.LinearGroups.SolvableSparseClassification +OAI.Probability.CriticalPercolation.LinearGroups.StrongAbstractSpan +OAI.Probability.CriticalPercolation.LinearGroups.StrongDenseEigenvalues +OAI.Probability.CriticalPercolation.LinearGroups.StrongDensePeriodicity +OAI.Probability.CriticalPercolation.Main +OAI.Probability.CriticalPercolation.Model +OAI.Probability.CriticalPercolation.Modular.ActionMassTransport +OAI.Probability.CriticalPercolation.Modular.ActionOrbitTransport +OAI.Probability.CriticalPercolation.Modular.ActionUnimodularRoot +OAI.Probability.CriticalPercolation.Modular.CappedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.ClusterDiscrepancy +OAI.Probability.CriticalPercolation.Modular.ClusterMassEndpoint +OAI.Probability.CriticalPercolation.Modular.ClusterMassEndpointFinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassFinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassInfinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassRestriction +OAI.Probability.CriticalPercolation.Modular.ClusterTransportFinite +OAI.Probability.CriticalPercolation.Modular.ClusterTransportGeometry +OAI.Probability.CriticalPercolation.Modular.ClusterTransportLimit +OAI.Probability.CriticalPercolation.Modular.ClusterTransportSums +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyDrop +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyIdentity +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyNull +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyUniqueness +OAI.Probability.CriticalPercolation.Modular.DensityModular +OAI.Probability.CriticalPercolation.Modular.DiscrepancyTail +OAI.Probability.CriticalPercolation.Modular.ExpectedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.FiniteClusterTransport +OAI.Probability.CriticalPercolation.Modular.GeometricPeakBand +OAI.Probability.CriticalPercolation.Modular.GraphModular +OAI.Probability.CriticalPercolation.Modular.HeavyClusterNumber +OAI.Probability.CriticalPercolation.Modular.HeavyDiscrepancy +OAI.Probability.CriticalPercolation.Modular.HeavyFiniteGeometry +OAI.Probability.CriticalPercolation.Modular.HeavyHarris +OAI.Probability.CriticalPercolation.Modular.HeavyPeaks +OAI.Probability.CriticalPercolation.Modular.HeavyThinning +OAI.Probability.CriticalPercolation.Modular.InputMass +OAI.Probability.CriticalPercolation.Modular.LightCeiling +OAI.Probability.CriticalPercolation.Modular.LightClusterNumber +OAI.Probability.CriticalPercolation.Modular.LightSliceFrontier +OAI.Probability.CriticalPercolation.Modular.LightTwoPointDecay +OAI.Probability.CriticalPercolation.Modular.MainAllLightBoundary +OAI.Probability.CriticalPercolation.Modular.MainInfiniteLightBoundary +OAI.Probability.CriticalPercolation.Modular.MainLightBoundary +OAI.Probability.CriticalPercolation.Modular.MarkedTiltedTransport +OAI.Probability.CriticalPercolation.Modular.Mass +OAI.Probability.CriticalPercolation.Modular.ModularCharacter +OAI.Probability.CriticalPercolation.Modular.ModularClusterCount +OAI.Probability.CriticalPercolation.Modular.ModularClusterMass +OAI.Probability.CriticalPercolation.Modular.ModularGrowth +OAI.Probability.CriticalPercolation.Modular.ModularIncidence +OAI.Probability.CriticalPercolation.Modular.ModularLevelGeometry +OAI.Probability.CriticalPercolation.Modular.ModularSuperlevels +OAI.Probability.CriticalPercolation.Modular.MoveTransport +OAI.Probability.CriticalPercolation.Modular.NormalizedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.NormalizedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.ObjectAvoidMass +OAI.Probability.CriticalPercolation.Modular.OrbitalMassTransport +OAI.Probability.CriticalPercolation.Modular.OrderMass +OAI.Probability.CriticalPercolation.Modular.PeakClusters +OAI.Probability.CriticalPercolation.Modular.PeakRatioTransport +OAI.Probability.CriticalPercolation.Modular.PeakReturn +OAI.Probability.CriticalPercolation.Modular.PeakVolumeBand +OAI.Probability.CriticalPercolation.Modular.PushMass +OAI.Probability.CriticalPercolation.Modular.RandomTiltedTransport +OAI.Probability.CriticalPercolation.Modular.RelativeModular +OAI.Probability.CriticalPercolation.Modular.SignedDiscrepancyContinuity +OAI.Probability.CriticalPercolation.Modular.SignedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.TiltedMassTransport +OAI.Probability.CriticalPercolation.Modular.TiltedTransportENNReal +OAI.Probability.CriticalPercolation.Modular.UnimodularAdjacent +OAI.Probability.CriticalPercolation.Modular.UnimodularAverages +OAI.Probability.CriticalPercolation.Modular.UnimodularGeometric +OAI.Probability.CriticalPercolation.Modular.UnimodularUnique +OAI.Probability.CriticalPercolation.Modular.Unimodularity +OAI.Probability.CriticalPercolation.Modular.WeightedCauchy +OAI.Probability.CriticalPercolation.Modular.WeightedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.WeightedDiscrepancyLimit +OAI.Probability.CriticalPercolation.Modular.WeightedExplorationCost +OAI.Probability.CriticalPercolation.Modular.WeightedIncidenceSearch +OAI.Probability.CriticalPercolation.Modular.WeightedIntegralBand +OAI.Probability.CriticalPercolation.Modular.WeightedPeakBand +OAI.Probability.CriticalPercolation.Modular.WeightedPeakTransport +OAI.Probability.CriticalPercolation.Modular.WeightedQuery +OAI.Probability.CriticalPercolation.Modular.WeightedQueryBand +OAI.Probability.CriticalPercolation.Modular.WeightedQueryLaw +OAI.Probability.CriticalPercolation.Nilpotent.AbelianAlternatives +OAI.Probability.CriticalPercolation.Nilpotent.AbelianConjugationGrowth +OAI.Probability.CriticalPercolation.Nilpotent.AbelianDescent +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorFinite +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorGeneration +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorQuotient +OAI.Probability.CriticalPercolation.Nilpotent.CharacteristicNilpotentCore +OAI.Probability.CriticalPercolation.Nilpotent.CyclicModTorsion +OAI.Probability.CriticalPercolation.Nilpotent.CyclicSubgroupIndex +OAI.Probability.CriticalPercolation.Nilpotent.FGExtensions +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicConstruction +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicExtensionIndex +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicInheritance +OAI.Probability.CriticalPercolation.Nilpotent.FiniteKernelNilpotent +OAI.Probability.CriticalPercolation.Nilpotent.FreeAbelianDescent +OAI.Probability.CriticalPercolation.Nilpotent.GeneralNilpotentCore +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralFG +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralFinite +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralTailFinite +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentAlternatives +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentCyclicConstruction +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentDescent +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentFinite +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentInfiniteCenter +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentRankOne +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentSubgroupFG +OAI.Probability.CriticalPercolation.Nilpotent.SolvableSubgroupFG +OAI.Probability.CriticalPercolation.Nilpotent.StructuredNilpotent +OAI.Probability.CriticalPercolation.Nilpotent.StructuredVirtuallyNilpotent +OAI.Probability.CriticalPercolation.ProductMeasure.Associated +OAI.Probability.CriticalPercolation.ProductMeasure.AvgDiv +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliErgodicity +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliSingleton +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliSingletonIntegration +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliThinning +OAI.Probability.CriticalPercolation.ProductMeasure.BitMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.ClosedCutProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ClosedThin +OAI.Probability.CriticalPercolation.ProductMeasure.CompactInvariantMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.ContinuousExpectWeights +OAI.Probability.CriticalPercolation.ProductMeasure.ContinuousProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ContourProbability +OAI.Probability.CriticalPercolation.ProductMeasure.CoordinateNeDensity +OAI.Probability.CriticalPercolation.ProductMeasure.Delta +OAI.Probability.CriticalPercolation.ProductMeasure.Density +OAI.Probability.CriticalPercolation.ProductMeasure.DensityMulExpect +OAI.Probability.CriticalPercolation.ProductMeasure.Distribution +OAI.Probability.CriticalPercolation.ProductMeasure.EllipseProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ExpectClosedFlip +OAI.Probability.CriticalPercolation.ProductMeasure.ExpectMulReal +OAI.Probability.CriticalPercolation.ProductMeasure.ExposureLaw +OAI.Probability.CriticalPercolation.ProductMeasure.ExposureLawSupport +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteAdjacentMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteInterpolationMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteMarkovAvg +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteOpenWitness +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteProductPin +OAI.Probability.CriticalPercolation.ProductMeasure.ForceClosed +OAI.Probability.CriticalPercolation.ProductMeasure.FreshRegionLaw +OAI.Probability.CriticalPercolation.ProductMeasure.LayerExpectation +OAI.Probability.CriticalPercolation.ProductMeasure.LevelContactMeasurability +OAI.Probability.CriticalPercolation.ProductMeasure.LevelCutProbability +OAI.Probability.CriticalPercolation.ProductMeasure.MeasurableSetRestrict +OAI.Probability.CriticalPercolation.ProductMeasure.MonotoneBernoulli +OAI.Probability.CriticalPercolation.ProductMeasure.MonotoneIndicatorUpper +OAI.Probability.CriticalPercolation.ProductMeasure.Potential +OAI.Probability.CriticalPercolation.ProductMeasure.Prob +OAI.Probability.CriticalPercolation.ProductMeasure.ProbDisjoint +OAI.Probability.CriticalPercolation.ProductMeasure.ProbOr +OAI.Probability.CriticalPercolation.ProductMeasure.ProbRequiresBit +OAI.Probability.CriticalPercolation.ProductMeasure.ProductConditioning +OAI.Probability.CriticalPercolation.ProductMeasure.ProductEmbedding +OAI.Probability.CriticalPercolation.ProductMeasure.QueryMartingale +OAI.Probability.CriticalPercolation.ProductMeasure.RelayProbability +OAI.Probability.CriticalPercolation.ProductMeasure.SourceEventLaw +OAI.Probability.CriticalPercolation.ProductMeasure.SourceMissLaw +OAI.Probability.CriticalPercolation.ProductMeasure.SusceptibilityMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.TailProduct +OAI.Probability.CriticalPercolation.ProductMeasure.TrialProbability +OAI.Probability.CriticalPercolation.ProductMeasure.Variance +OAI.Probability.UnimodularPercolation.Clusters.ExteriorMoments +OAI.Probability.UnimodularPercolation.Clusters.KernelMoments +OAI.Probability.UnimodularPercolation.Clusters.LargeContacts +OAI.Probability.UnimodularPercolation.Clusters.Resampling +OAI.Probability.UnimodularPercolation.Clusters.Uniqueness +OAI.Probability.UnimodularPercolation.Criticality.Finiteness +OAI.Probability.UnimodularPercolation.Criticality.Operator +OAI.Probability.UnimodularPercolation.Criticality.ScaleLimits +OAI.Probability.UnimodularPercolation.Criticality.Sharpness +OAI.Probability.UnimodularPercolation.Criticality.Susceptibility +OAI.Probability.UnimodularPercolation.Deformation.AveragedDecrease +OAI.Probability.UnimodularPercolation.Deformation.Calibration +OAI.Probability.UnimodularPercolation.Deformation.ClusterProducts +OAI.Probability.UnimodularPercolation.Deformation.Corridors +OAI.Probability.UnimodularPercolation.Deformation.Derivatives +OAI.Probability.UnimodularPercolation.Deformation.FiniteScale +OAI.Probability.UnimodularPercolation.Escape.CollisionTails +OAI.Probability.UnimodularPercolation.Escape.Labels +OAI.Probability.UnimodularPercolation.Escape.PathSelection +OAI.Probability.UnimodularPercolation.Escape.PositiveEscapes +OAI.Probability.UnimodularPercolation.Escape.SelectionBounds +OAI.Probability.UnimodularPercolation.Exploration.FractionalMoments +OAI.Probability.UnimodularPercolation.Exploration.Goodness +OAI.Probability.UnimodularPercolation.Exploration.Marked +OAI.Probability.UnimodularPercolation.Exploration.Moments +OAI.Probability.UnimodularPercolation.Exploration.TailBounds +OAI.Probability.UnimodularPercolation.Graph.Automorphisms +OAI.Probability.UnimodularPercolation.Graph.Basic +OAI.Probability.UnimodularPercolation.Graph.Paths +OAI.Probability.UnimodularPercolation.Graph.Topology +OAI.Probability.UnimodularPercolation.Kernel.Amplification +OAI.Probability.UnimodularPercolation.Kernel.Bounds +OAI.Probability.UnimodularPercolation.Kernel.Connections +OAI.Probability.UnimodularPercolation.Kernel.ContactTrace +OAI.Probability.UnimodularPercolation.Kernel.Covariance +OAI.Probability.UnimodularPercolation.Kernel.DistinctMoments +OAI.Probability.UnimodularPercolation.Kernel.RussoRows +OAI.Probability.UnimodularPercolation.Kernel.ScaleBudget +OAI.Probability.UnimodularPercolation.Kernel.Spectral +OAI.Probability.UnimodularPercolation.Kernel.Sprinkling +OAI.Probability.UnimodularPercolation.Kernel.TraceBounds +OAI.Probability.UnimodularPercolation.Main +OAI.Probability.UnimodularPercolation.ProductMeasure.Association +OAI.Probability.UnimodularPercolation.Splicing.EndpointMoments +OAI.Probability.UnimodularPercolation.Splicing.GapCodes +OAI.Probability.UnimodularPercolation.Splicing.Geometry +OAI.Probability.UnimodularPercolation.Splicing.MomentBounds +OAI.Probability.UnimodularPercolation.Splicing.ReferenceLaws +OAI.Probability.UnimodularPercolation.Splicing.Replay +OAI.Probability.UnimodularPercolation.Subdivision.Coupling +OAI.Probability.UnimodularPercolation.Subdivision.Graph +OAI.Probability.UnimodularPercolation.Subdivision.Operator +OAI.Probability.UnimodularPercolation.Transport.EndpointKernels +OAI.Probability.UnimodularPercolation.Transport.Haar +OAI.Probability.UnimodularPercolation.Transport.TrajectoryMass +OAI.Probability.UnimodularPercolation.TwoCluster.Bounds +OAI.Probability.UnimodularPercolation.TwoCluster.Score +OAI.Probability.UnimodularPercolation.TwoCluster.Transport diff --git a/tasks/benjamini-schramm/solution/reference.py b/tasks/benjamini-schramm/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/benjamini-schramm/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/benjamini-schramm/solution/solve.sh b/tasks/benjamini-schramm/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f974c2ef47ad05f7654208eaf53c99024223d8f5 --- /dev/null +++ b/tasks/benjamini-schramm/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BenjaminiSchramm, i.e. module OAI.Probability.BenjaminiSchramm.Main and the +# 970 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.BenjaminiSchramm.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BenjaminiSchramm" diff --git a/tasks/benjamini-schramm/task.toml b/tasks/benjamini-schramm/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..003ad5e26e7a7364b27e127d76b75afad7d49597 --- /dev/null +++ b/tasks/benjamini-schramm/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/benjamini-schramm" +version = "1.0.0" +description = "Prove BenjaminiSchramm (openai/math family 214: The Benjamini–Schramm nonuniqueness conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BenjaminiSchramm.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BenjaminiSchramm" +family = "214" +family_title = "The Benjamini–Schramm nonuniqueness conjecture" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Percolation.BenjaminiSchramm.full_main", "OAI.Percolation.BenjaminiSchramm.cayley_main", "OAI.Percolation.BenjaminiSchramm.critical_laws"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.BenjaminiSchramm.Main" +reference_modules = 970 +reference_lean_bytes = 6834429 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3592 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17850 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/benjamini-schramm/tests/Challenge.lean b/tasks/benjamini-schramm/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d9902dce1400889ebe46ffa3c1f881beab3a9cd8 --- /dev/null +++ b/tasks/benjamini-schramm/tests/Challenge.lean @@ -0,0 +1,240 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory +open scoped ENNReal NNReal + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} + +abbrev BondGraph (V : Type u) (E : Type v) := E → Sym2 V + +def Adj (G : BondGraph V E) (x y : V) : Prop := ∃ e, G e = s(x, y) + +def LocallyFinite (G : BondGraph V E) : Prop := ∀ x, {e | x ∈ G e}.Finite + +def Connected (G : BondGraph V E) : Prop := + ∀ x y, Relation.ReflTransGen (Adj G) x y + +def IsAut (G : BondGraph V E) (a : V ≃ V) (b : E ≃ E) : Prop := + ∀ e, G (b e) = (G e).map a + +def QuasiTransitive (G : BondGraph V E) : Prop := + ∃ representatives : Finset V, ∀ x, ∃ o ∈ representatives, + ∃ a : V ≃ V, ∃ b : E ≃ E, IsAut G a b ∧ a o = x + +def vertexBoundary (G : BondGraph V E) (A : Finset V) : Set V := + {y | y ∉ A ∧ ∃ x ∈ A, Adj G x y} + +noncomputable def hV (G : BondGraph V E) : ℝ := + sInf {r | ∃ A : Finset V, A.Nonempty ∧ + r = (vertexBoundary G A).ncard / (A.card : ℝ)} + +def Conn (G : BondGraph V E) (ω : Set E) (x y : V) : Prop := + Relation.ReflTransGen (fun a b => ∃ e ∈ ω, G e = s(a, b)) x y + +def cluster (G : BondGraph V E) (ω : Set E) (x : V) : Set V := + {y | Conn G ω x y} + +def infiniteClusters (G : BondGraph V E) (ω : Set E) : Set (Set V) := + {C | C.Infinite ∧ ∃ x, C = cluster G ω x} + +noncomputable def law (p : unitInterval) : Measure (Set E) := + setBernoulli Set.univ p + +noncomputable def pc (G : BondGraph V E) : unitInterval := + sInf {p | 0 < law p {ω | (infiniteClusters G ω).Nonempty}} + +noncomputable def pu (G : BondGraph V E) : unitInterval := + sInf {p | law p {ω | ∃! C, C ∈ infiniteClusters G ω} = 1} + +noncomputable def twoPoint (G : BondGraph V E) (p : unitInterval) (x y : V) : ℝ := + (law p {ω | Conn G ω x y}).toReal + +noncomputable abbrev Hilbert (V : Type u) := lp (fun _ : V => ℂ) 2 + +noncomputable def HasKernel [DecidableEq V] + (G : BondGraph V E) (p : unitInterval) + (A : Hilbert V →L[ℂ] Hilbert V) : Prop := + ∀ x y, (A (lp.single 2 y (1 : ℂ))) x = (twoPoint G p x y : ℂ) + +noncomputable def OperatorBounded (G : BondGraph V E) (p : unitInterval) : Prop := by + classical + exact ∃ A : Hilbert V →L[ℂ] Hilbert V, HasKernel G p A + +noncomputable def operatorNorm (G : BondGraph V E) (p : unitInterval) : ℝ≥0∞ := by + classical + exact sInf {r | ∃ A : Hilbert V →L[ℂ] Hilbert V, + HasKernel G p A ∧ r = ENNReal.ofReal ‖A‖} + +noncomputable def ptwo (G : BondGraph V E) : unitInterval := + sSup {p | OperatorBounded G p} + +noncomputable def labelLaw : Measure (E → unitInterval) := + Measure.infinitePi (fun _ => (volume : Measure unitInterval)) + +def openEdges (labels : E → unitInterval) (p : unitInterval) : Set E := + {e | labels e ≤ p} + +def MainConclusion (G : BondGraph V E) : Prop := + (sSup {r | ∃ p : unitInterval, p < pc G ∧ r = operatorNorm G p} = + operatorNorm G (pc G)) ∧ + operatorNorm G (pc G) < ⊤ ∧ + pc G < ptwo G ∧ ptwo G ≤ pu G ∧ + ∃ p₁ p₂ : unitInterval, pc G < p₁ ∧ p₁ < p₂ ∧ p₂ < 1 ∧ + ∀ᵐ labels ∂(labelLaw : Measure (E → unitInterval)), + ∀ p ∈ Set.Icc p₁ p₂, (infiniteClusters G (openEdges labels p)).Infinite + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.propDecidable + +def openSimpleGraph (G : BondGraph V E) (ω : Set E) : SimpleGraph V where + Adj x y := x ≠ y ∧ ∃ e ∈ ω, G e = s(x,y) + symm := ⟨by + rintro x y ⟨hxy, e, he, h⟩ + exact ⟨hxy.symm, e, he, h.trans (Sym2.eq_swap ..)⟩⟩ + loopless := ⟨by simp⟩ + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.propDecidable Classical.decEq + +noncomputable def susceptibility (G : BondGraph V E) (p : unitInterval) (x : V) : ℝ := + ∑' y, twoPoint G p x y + +end Percolation + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u v +variable {V : Type u} {E : Type v} +attribute [local instance] Classical.decEq + +noncomputable def triangleDiagram (G : BondGraph V E) (p : unitInterval) (x : V) : ℝ≥0∞ := + ∑' ab : V × V, ENNReal.ofReal + (twoPoint G p x ab.1 * twoPoint G p ab.1 ab.2 * twoPoint G p ab.2 x) + +noncomputable def graphDistance (G : BondGraph V E) (x y : V) : ℕ := + (openSimpleGraph G Set.univ).dist x y + +def ExponentialDecay (G : BondGraph V E) (p : unitInterval) : Prop := + ∃ A a : ℝ, 0 < A ∧ 0 < a ∧ ∀ x y, + twoPoint G p x y ≤ A * Real.exp (-a * graphDistance G x y) + +noncomputable def pexp (G : BondGraph V E) : unitInterval := + sSup {p | ExponentialDecay G p} + +def PowerTail (f : ℕ → ℝ) (exponent : ℝ) : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∀ n : ℕ, 0 < n → + c * (n : ℝ) ^ (-exponent) ≤ f n ∧ f n ≤ C * (n : ℝ) ^ (-exponent) + +def volumeEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | (n : ℕ∞) ≤ (cluster G ω x).encard} + +def intrinsicRadiusEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | ∃ y ∈ cluster G ω x, n ≤ (openSimpleGraph G ω).dist x y} + +def extrinsicRadiusEvent (G : BondGraph V E) (x : V) (n : ℕ) : Set (Set E) := + {ω | ∃ y ∈ cluster G ω x, n ≤ graphDistance G x y} + +noncomputable def criticalTail (G : BondGraph V E) + (A : V → ℕ → Set (Set E)) (x : V) (n : ℕ) : ℝ := + (law (pc G) (A x n)).toReal + +def CriticalTailLaws (G : BondGraph V E) : Prop := + ∀ x, PowerTail (criticalTail G (volumeEvent G) x) (1 / 2) ∧ + PowerTail (criticalTail G (intrinsicRadiusEvent G) x) 1 ∧ + PowerTail (criticalTail G (extrinsicRadiusEvent G) x) 1 + +def SusceptibilityLaw (G : BondGraph V E) : Prop := + ∀ x, ∃ c C δ : ℝ, 0 < c ∧ 0 < C ∧ 0 < δ ∧ + ∀ p : unitInterval, p < pc G → (pc G : ℝ) - p < δ → + c / ((pc G : ℝ) - p) ≤ susceptibility G p x ∧ + susceptibility G p x ≤ C / ((pc G : ℝ) - p) + +noncomputable def percolationProbability (G : BondGraph V E) (p : unitInterval) + (x : V) : ℝ := (law p {ω | (cluster G ω x).Infinite}).toReal + +def PercolationProbabilityLaw (G : BondGraph V E) : Prop := + ∀ x, ∃ c C δ : ℝ, 0 < c ∧ 0 < C ∧ 0 < δ ∧ + ∀ p : unitInterval, pc G < p → (p : ℝ) - pc G < δ → + c * ((p : ℝ) - pc G) ≤ percolationProbability G p x ∧ + percolationProbability G p x ≤ C * ((p : ℝ) - pc G) + +end Percolation.BenjaminiSchramm + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u v +variable {V : Type u} {E : Type v} + +def CriticalLawsConclusion (G : BondGraph V E) : Prop := + (∀ x, triangleDiagram G (pc G) x ≤ operatorNorm G (pc G) ^ 3 ∧ + triangleDiagram G (pc G) x < ⊤) ∧ + SusceptibilityLaw G ∧ PercolationProbabilityLaw G ∧ CriticalTailLaws G ∧ + (pc G < ptwo G ∧ ptwo G ≤ pexp G) ∧ + ∀ p : unitInterval, p < ptwo G → ExponentialDecay G p + +end Percolation.BenjaminiSchramm + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace Percolation.BenjaminiSchramm +universe u +variable {Λ : Type u} [Group Λ] +attribute [local instance] Classical.decEq + +abbrev CayleyEdge (S : Finset Λ) := (SimpleGraph.mulCayley (S : Set Λ)).edgeSet + +def cayleyBond (S : Finset Λ) : BondGraph Λ (CayleyEdge S) := Subtype.val + +def FolnerAmenable (Λ : Type u) [Group Λ] : Prop := + ∀ K : Finset Λ, ∀ ε : ℝ, 0 < ε → ∃ A : Finset Λ, A.Nonempty ∧ + ∀ k ∈ K, (((A.image (fun x => x * k)) \ A).card : ℝ) < ε * A.card + +end Percolation.BenjaminiSchramm + +namespace Percolation.BenjaminiSchramm + +universe u v + +/-- Critical operator boundedness, the threshold gap, and simultaneous nonuniqueness. -/ +theorem full_main {V : Type u} {E : Type v} [Infinite V] + (G : BondGraph V E) (hc : Connected G) (hl : LocallyFinite G) + (hq : QuasiTransitive G) (hh : 0 < hV G) : MainConclusion G := by + sorry + +/-- Critical mean-field laws and uniform exponential connectivity below the operator threshold. -/ +theorem critical_laws {V : Type u} {E : Type v} [Infinite V] + (G : BondGraph V E) (hc : Connected G) (hl : LocallyFinite G) + (hq : QuasiTransitive G) (hh : 0 < hV G) : CriticalLawsConclusion G := by + sorry + +/-- Nonuniqueness for every prescribed finite symmetric Cayley generating set. -/ +theorem cayley_main {Λ : Type u} [Group Λ] + (S : Finset Λ) (hsym : ∀ s ∈ S, s⁻¹ ∈ S) (_hone : 1 ∉ S) + (hgen : Subgroup.closure (S : Set Λ) = ⊤) (hna : ¬ FolnerAmenable Λ) : + OperatorBounded (cayleyBond S) (pc (cayleyBond S)) ∧ + MainConclusion (cayleyBond S) ∧ + ∀ p : unitInterval, pc (cayleyBond S) < p → p < pu (cayleyBond S) → + ∀ᵐ ω ∂law p, (infiniteClusters (cayleyBond S) ω).Infinite := by + sorry + +end Percolation.BenjaminiSchramm + +end OAI diff --git a/tasks/benjamini-schramm/tests/grade.py b/tasks/benjamini-schramm/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/benjamini-schramm/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/benjamini-schramm/tests/task.json b/tasks/benjamini-schramm/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..08258106d6405e226a94007b5dbd305e37291511 --- /dev/null +++ b/tasks/benjamini-schramm/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "BenjaminiSchramm", + "comparator": { + "theorem_names": [ + "OAI.Percolation.BenjaminiSchramm.full_main", + "OAI.Percolation.BenjaminiSchramm.cayley_main", + "OAI.Percolation.BenjaminiSchramm.critical_laws" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16950 +} \ No newline at end of file diff --git a/tasks/benjamini-schramm/tests/test.sh b/tasks/benjamini-schramm/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/benjamini-schramm/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bernoulli-nonflat-in-seven/environment/Dockerfile b/tasks/bernoulli-nonflat-in-seven/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bernoulli-nonflat-in-seven/environment/fetch_mathlib.sh b/tasks/bernoulli-nonflat-in-seven/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bernoulli-nonflat-in-seven/environment/lake-manifest.json b/tasks/bernoulli-nonflat-in-seven/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bernoulli-nonflat-in-seven/environment/lakefile.lean b/tasks/bernoulli-nonflat-in-seven/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bernoulli-nonflat-in-seven/environment/lean_setup.sh b/tasks/bernoulli-nonflat-in-seven/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bernoulli-nonflat-in-seven/environment/pack_submission.py b/tasks/bernoulli-nonflat-in-seven/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bernoulli-nonflat-in-seven/instruction.md b/tasks/bernoulli-nonflat-in-seven/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4f48156494d61b894b945361b96dcace29d25f93 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/instruction.md @@ -0,0 +1,137 @@ +# openai/math challenge `BernoulliNonflatInSeven` (family 367) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 367 of the release, *The critical dimension for the one-phase Bernoulli problem* +(Partial differential equations). The family as a whole: Establishes seven as the first dimension admitting a nonflat, one-homogeneous global minimizer of the one-phase Bernoulli energy. Consequently, minimizing free boundaries are smooth through dimension six, and their singular sets have dimension at most $n-7$ in higher dimensions. + +The challenge is `BernoulliNonflatInSeven`, also at `/opt/openai-math/challenges/BernoulliNonflatInSeven.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Set Filter +open scoped ENNReal Topology ContDiff + +namespace Bernoulli +open scoped _root_.Bernoulli + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +/-- Compactly supported smooth real tests in the open set. -/ +def Test {d : ℕ} (D : Set (Space d)) (φ : Space d → ℝ) : Prop := + ContDiff ℝ ∞ φ ∧ HasCompactSupport φ ∧ tsupport φ ⊆ D + +/-- Distributional gradient, tested in every constant direction. -/ +def WeakGradient {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + ∀ φ, Test D φ → ∀ h : Space d, + (∫ x in D, u x * (fderiv ℝ φ x) h) = + -(∫ x in D, inner ℝ (G x) h * φ x) + +/-- H¹(D), with its weak gradient. -/ +def H1 {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + MemLp u 2 (volume.restrict D) ∧ + MemLp G 2 (volume.restrict D) ∧ WeakGradient D u G + +/-- H¹₀(D) is H¹-closure of C∞ compactly supported functions. +Both L² errors tend to zero. This does not restrict competitors to smooth ones. -/ +def H10 {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + H1 D u G ∧ ∀ ε : ℝ, 0 < ε → ∃ φ : Space d → ℝ, + Test D φ ∧ + eLpNorm (fun x => u x - φ x) 2 (volume.restrict D) < ENNReal.ofReal ε ∧ + eLpNorm (fun x => G x - gradient φ x) 2 (volume.restrict D) < ENNReal.ofReal ε + +/-- Ballwise H¹_loc, on an open set (balls have compact closure inside D). -/ +def H1Loc {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + ∀ c : Space d, ∀ r : ℝ, 0 < r → Metric.closedBall c r ⊆ D → + H1 (Metric.ball c r) u G + +/-- The exact volume-one Bernoulli energy, not just Dirichlet energy. -/ +def energy {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : ℝ := + ∫ x in D, ‖G x‖ ^ 2 + if 0 < u x then (1 : ℝ) else 0 + +/-- Full ballwise local comparison. Competitor and gradient are arbitrary +Sobolev representatives on the ball, with zero-trace difference. -/ +def LocalMinimizer {d : ℕ} (D : Set (Space d)) (u : Space d → ℝ) : Prop := + IsOpen D ∧ ∃ G : Space d → Space d, + H1Loc D u G ∧ (∀ᵐ x ∂volume.restrict D, 0 ≤ u x) ∧ + ∀ c : Space d, ∀ r : ℝ, 0 < r → Metric.closedBall c r ⊆ D → + ∀ (v : Space d → ℝ) (V : Space d → Space d), + H1 (Metric.ball c r) v V → + (∀ᵐ x ∂volume.restrict (Metric.ball c r), 0 ≤ v x) → + H10 (Metric.ball c r) (fun x => v x - u x) (fun x => V x - G x) → + energy (Metric.ball c r) u G ≤ energy (Metric.ball c r) v V + +/-- Nonnegative global minimizer, with all centers and all positive radii. -/ +def GlobalMinimizer {d : ℕ} (u : Space d → ℝ) : Prop := + LocalMinimizer Set.univ u + +def OneHomogeneous {d : ℕ} (u : Space d → ℝ) : Prop := + ∀ r : ℝ, 0 < r → ∀ᵐ x ∂volume, u (r • x) = r * u x + +def Nonzero {d : ℕ} (u : Space d → ℝ) : Prop := + ¬ (u =ᵐ[volume] fun _ => 0) + +/-- Flatness is a.e. equality of H¹ representatives. -/ +def Flat {d : ℕ} (u : Space d → ℝ) : Prop := + ∃ e : Space d, ‖e‖ = 1 ∧ ∀ᵐ x ∂volume, u x = max (inner ℝ x e) 0 + +theorem nonflat_in_seven : ∃ u : Space 7 → ℝ, + GlobalMinimizer u ∧ Nonzero u ∧ OneHomogeneous u ∧ ¬ Flat u := by + sorry + +end Bernoulli + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BernoulliNonflatInSeven.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Bernoulli.nonflat_in_seven` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bernoulli-nonflat-in-seven/solution/closure.txt b/tasks/bernoulli-nonflat-in-seven/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8d0d11dffb1302ccb329724febfd4ccb3b987147 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/solution/closure.txt @@ -0,0 +1,91 @@ +OAI.Analysis.BernoulliCone.BoundedCalibration +OAI.Analysis.BernoulliCone.CalibrationTraces +OAI.Analysis.BernoulliCone.CapCalculus +OAI.Analysis.BernoulliCone.CapExtension +OAI.Analysis.BernoulliCone.CapFoliation +OAI.Analysis.BernoulliCone.CapGeometry +OAI.Analysis.BernoulliCone.ClampedFoliationGraph +OAI.Analysis.BernoulliCone.ClampedGraphBound +OAI.Analysis.BernoulliCone.ClampedSeam +OAI.Analysis.BernoulliCone.ClosedGermExtension +OAI.Analysis.BernoulliCone.CompactGradient +OAI.Analysis.BernoulliCone.CompactLipschitzDivergence +OAI.Analysis.BernoulliCone.CompactZeroFiber +OAI.Analysis.BernoulliCone.ConePicone +OAI.Analysis.BernoulliCone.CylindricalCalculus +OAI.Analysis.BernoulliCone.DominatedVariation +OAI.Analysis.BernoulliCone.ExteriorCalibration +OAI.Analysis.BernoulliCone.FluxBounds +OAI.Analysis.BernoulliCone.FluxBulk +OAI.Analysis.BernoulliCone.FluxSeam +OAI.Analysis.BernoulliCone.FoliationBulkGerm +OAI.Analysis.BernoulliCone.FoliationDifferential +OAI.Analysis.BernoulliCone.FoliationGraph +OAI.Analysis.BernoulliCone.FoliationSeam +OAI.Analysis.BernoulliCone.GlobalMinimizer +OAI.Analysis.BernoulliCone.GroundState +OAI.Analysis.BernoulliCone.HalfspaceDensity +OAI.Analysis.BernoulliCone.HalfspaceDifferential +OAI.Analysis.BernoulliCone.HalfspaceEnergy +OAI.Analysis.BernoulliCone.HalfspaceGroundstate +OAI.Analysis.BernoulliCone.HalfspacePullback +OAI.Analysis.BernoulliCone.HalfspaceQuotient +OAI.Analysis.BernoulliCone.HalfspaceUnitSlope +OAI.Analysis.BernoulliCone.HarmonicCaccioppoli +OAI.Analysis.BernoulliCone.HarmonicKernel +OAI.Analysis.BernoulliCone.HarmonicRadial +OAI.Analysis.BernoulliCone.HarmonicReplacement +OAI.Analysis.BernoulliCone.HarmonicWeakLaplacian +OAI.Analysis.BernoulliCone.HomogeneousCalculus +OAI.Analysis.BernoulliCone.IntegralUpperLimit +OAI.Analysis.BernoulliCone.IntegratedPrimitive +OAI.Analysis.BernoulliCone.JointIntervalIntegral +OAI.Analysis.BernoulliCone.LaplacianDilation +OAI.Analysis.BernoulliCone.LipschitzProduct +OAI.Analysis.BernoulliCone.LocalFluxExtensions +OAI.Analysis.BernoulliCone.LowerComparison +OAI.Analysis.BernoulliCone.LowerSupport +OAI.Analysis.BernoulliCone.Main +OAI.Analysis.BernoulliCone.MinimizerOuterVariation +OAI.Analysis.BernoulliCone.MinimizerStationarity +OAI.Analysis.BernoulliCone.Model +OAI.Analysis.BernoulliCone.OuterGeometry +OAI.Analysis.BernoulliCone.OuterSlope +OAI.Analysis.BernoulliCone.PiecewiseFoliationGraph +OAI.Analysis.BernoulliCone.PositiveFoliation +OAI.Analysis.BernoulliCone.PositiveQuotient +OAI.Analysis.BernoulliCone.PositiveTrace +OAI.Analysis.BernoulliCone.PrimitiveBound +OAI.Analysis.BernoulliCone.PrimitiveLocal +OAI.Analysis.BernoulliCone.RadialShapeTest +OAI.Analysis.BernoulliCone.RankOneDeterminant +OAI.Analysis.BernoulliCone.RankOnePerturbation +OAI.Analysis.BernoulliCone.ScalarImplicit +OAI.Analysis.BernoulliCone.ScalarLaplacian +OAI.Analysis.BernoulliCone.SeamCalibration +OAI.Analysis.BernoulliCone.SeamHeight +OAI.Analysis.BernoulliCone.ShapeDiffeomorphism +OAI.Analysis.BernoulliCone.SmallPerturbation +OAI.Analysis.BernoulliCone.SmoothIntervalPrimitive +OAI.Analysis.BernoulliCone.SmoothLocalizedExtension +OAI.Analysis.BernoulliCone.SobolevCalculus +OAI.Analysis.BernoulliCone.SobolevIdeals +OAI.Analysis.BernoulliCone.StationarityDensity +OAI.Analysis.BernoulliCone.StationarityEnergy +OAI.Analysis.BernoulliCone.StationarityIntegrability +OAI.Analysis.BernoulliCone.StrictSlope +OAI.Analysis.BernoulliCone.ThresholdRecovery +OAI.Analysis.BernoulliCone.TraceBound +OAI.Analysis.BernoulliCone.UpperCalibration +OAI.Analysis.BernoulliCone.UpperComparison +OAI.Analysis.BernoulliCone.UpperFamily +OAI.Analysis.BernoulliCone.UpperFoliation +OAI.Analysis.BernoulliCone.UpperLeaves +OAI.Analysis.BernoulliCone.UpperLimits +OAI.Analysis.BernoulliCone.UpperLipschitzComparison +OAI.Analysis.BernoulliCone.UpperParameter +OAI.Analysis.BernoulliCone.UpperSeam +OAI.Analysis.BernoulliCone.UpperSmoothLeaves +OAI.Analysis.BernoulliCone.UpperSupport +OAI.Analysis.BernoulliCone.VerticalGraphLocalization +OAI.Analysis.BernoulliCone.ZeroTrace diff --git a/tasks/bernoulli-nonflat-in-seven/solution/reference.py b/tasks/bernoulli-nonflat-in-seven/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bernoulli-nonflat-in-seven/solution/solve.sh b/tasks/bernoulli-nonflat-in-seven/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..09b8b113ea9776d44fe715c7af2266f721c5503b --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BernoulliNonflatInSeven, i.e. module OAI.Analysis.BernoulliCone.Main and the +# 91 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BernoulliCone.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BernoulliNonflatInSeven" diff --git a/tasks/bernoulli-nonflat-in-seven/task.toml b/tasks/bernoulli-nonflat-in-seven/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f9e07cef2a7b54bd713a6fe73e51a13916714cf --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bernoulli-nonflat-in-seven" +version = "1.0.0" +description = "Prove BernoulliNonflatInSeven (openai/math family 367: The critical dimension for the one-phase Bernoulli problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BernoulliNonflatInSeven.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BernoulliNonflatInSeven" +family = "367" +family_title = "The critical dimension for the one-phase Bernoulli problem" +subject = "Partial differential equations" +theorems = ["OAI.Bernoulli.nonflat_in_seven"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BernoulliCone.Main" +reference_modules = 91 +reference_lean_bytes = 640271 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1160 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12276 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bernoulli-nonflat-in-seven/tests/Challenge.lean b/tasks/bernoulli-nonflat-in-seven/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f1783f6743bddb9f2020e7de3c008d353a7d765e --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/tests/Challenge.lean @@ -0,0 +1,86 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Set Filter +open scoped ENNReal Topology ContDiff + +namespace Bernoulli +open scoped _root_.Bernoulli + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +/-- Compactly supported smooth real tests in the open set. -/ +def Test {d : ℕ} (D : Set (Space d)) (φ : Space d → ℝ) : Prop := + ContDiff ℝ ∞ φ ∧ HasCompactSupport φ ∧ tsupport φ ⊆ D + +/-- Distributional gradient, tested in every constant direction. -/ +def WeakGradient {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + ∀ φ, Test D φ → ∀ h : Space d, + (∫ x in D, u x * (fderiv ℝ φ x) h) = + -(∫ x in D, inner ℝ (G x) h * φ x) + +/-- H¹(D), with its weak gradient. -/ +def H1 {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + MemLp u 2 (volume.restrict D) ∧ + MemLp G 2 (volume.restrict D) ∧ WeakGradient D u G + +/-- H¹₀(D) is H¹-closure of C∞ compactly supported functions. +Both L² errors tend to zero. This does not restrict competitors to smooth ones. -/ +def H10 {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + H1 D u G ∧ ∀ ε : ℝ, 0 < ε → ∃ φ : Space d → ℝ, + Test D φ ∧ + eLpNorm (fun x => u x - φ x) 2 (volume.restrict D) < ENNReal.ofReal ε ∧ + eLpNorm (fun x => G x - gradient φ x) 2 (volume.restrict D) < ENNReal.ofReal ε + +/-- Ballwise H¹_loc, on an open set (balls have compact closure inside D). -/ +def H1Loc {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : Prop := + ∀ c : Space d, ∀ r : ℝ, 0 < r → Metric.closedBall c r ⊆ D → + H1 (Metric.ball c r) u G + +/-- The exact volume-one Bernoulli energy, not just Dirichlet energy. -/ +def energy {d : ℕ} (D : Set (Space d)) + (u : Space d → ℝ) (G : Space d → Space d) : ℝ := + ∫ x in D, ‖G x‖ ^ 2 + if 0 < u x then (1 : ℝ) else 0 + +/-- Full ballwise local comparison. Competitor and gradient are arbitrary +Sobolev representatives on the ball, with zero-trace difference. -/ +def LocalMinimizer {d : ℕ} (D : Set (Space d)) (u : Space d → ℝ) : Prop := + IsOpen D ∧ ∃ G : Space d → Space d, + H1Loc D u G ∧ (∀ᵐ x ∂volume.restrict D, 0 ≤ u x) ∧ + ∀ c : Space d, ∀ r : ℝ, 0 < r → Metric.closedBall c r ⊆ D → + ∀ (v : Space d → ℝ) (V : Space d → Space d), + H1 (Metric.ball c r) v V → + (∀ᵐ x ∂volume.restrict (Metric.ball c r), 0 ≤ v x) → + H10 (Metric.ball c r) (fun x => v x - u x) (fun x => V x - G x) → + energy (Metric.ball c r) u G ≤ energy (Metric.ball c r) v V + +/-- Nonnegative global minimizer, with all centers and all positive radii. -/ +def GlobalMinimizer {d : ℕ} (u : Space d → ℝ) : Prop := + LocalMinimizer Set.univ u + +def OneHomogeneous {d : ℕ} (u : Space d → ℝ) : Prop := + ∀ r : ℝ, 0 < r → ∀ᵐ x ∂volume, u (r • x) = r * u x + +def Nonzero {d : ℕ} (u : Space d → ℝ) : Prop := + ¬ (u =ᵐ[volume] fun _ => 0) + +/-- Flatness is a.e. equality of H¹ representatives. -/ +def Flat {d : ℕ} (u : Space d → ℝ) : Prop := + ∃ e : Space d, ‖e‖ = 1 ∧ ∀ᵐ x ∂volume, u x = max (inner ℝ x e) 0 + +theorem nonflat_in_seven : ∃ u : Space 7 → ℝ, + GlobalMinimizer u ∧ Nonzero u ∧ OneHomogeneous u ∧ ¬ Flat u := by + sorry + +end Bernoulli + +end + +end OAI diff --git a/tasks/bernoulli-nonflat-in-seven/tests/grade.py b/tasks/bernoulli-nonflat-in-seven/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bernoulli-nonflat-in-seven/tests/task.json b/tasks/bernoulli-nonflat-in-seven/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b4960127e91b0a748d18a7c3a9cecdacc82594b6 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BernoulliNonflatInSeven", + "comparator": { + "theorem_names": [ + "OAI.Bernoulli.nonflat_in_seven" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11376 +} \ No newline at end of file diff --git a/tasks/bernoulli-nonflat-in-seven/tests/test.sh b/tasks/bernoulli-nonflat-in-seven/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bernoulli-nonflat-in-seven/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/biholder-transport/environment/Dockerfile b/tasks/biholder-transport/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/biholder-transport/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/biholder-transport/environment/fetch_mathlib.sh b/tasks/biholder-transport/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/biholder-transport/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/biholder-transport/environment/lake-manifest.json b/tasks/biholder-transport/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/biholder-transport/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/biholder-transport/environment/lakefile.lean b/tasks/biholder-transport/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/biholder-transport/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/biholder-transport/environment/lean_setup.sh b/tasks/biholder-transport/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/biholder-transport/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/biholder-transport/environment/pack_submission.py b/tasks/biholder-transport/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/biholder-transport/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/biholder-transport/instruction.md b/tasks/biholder-transport/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dfb1d16157919f7b48a76e9961e6cb07640fb94e --- /dev/null +++ b/tasks/biholder-transport/instruction.md @@ -0,0 +1,178 @@ +# openai/math challenge `BiholderTransport` (family 360) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 360 of the release, *Villani’s convexity conjecture and regular optimal transport* +(Differential geometry). The family as a whole: On every closed connected Riemannian manifold of dimension at least two satisfying weak Ma–Trudinger–Wang curvature, all tangent injectivity domains are convex, resolving Villani’s conjecture in this setting. For squared-distance transport between measurable probability densities bounded above and away from zero, the optimal map and its inverse are Holder continuous. + +The challenge is `BiholderTransport`, also at `/opt/openai-math/challenges/BiholderTransport.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory Manifold Bundle +open scoped ContDiff Manifold ENNReal NNReal Topology + +namespace WeakMTWTransport + +abbrev Model (n : ℕ) := EuclideanSpace ℝ (Fin n) + +section MetricDefinitions + +variable {M : Type*} [MetricSpace M] + +/-- Squared-distance cost with factor one half. -/ +def cost (x y : M) : ℝ := dist x y ^ 2 / 2 + +/-- Calibration of Hausdorff measure to Euclidean volume. -/ +def euclideanVolumeFactor (n : ℕ) : ℝ≥0∞ := + volume (Metric.ball (0 : Model n) 1) / + (Measure.hausdorffMeasure (n : ℝ) : Measure (Model n)) + (Metric.ball (0 : Model n) 1) + +variable [MeasurableSpace M] + +/-- Riemannian volume calibrated to Lebesgue measure in Euclidean space. -/ +def metricVolume [BorelSpace M] (n : ℕ) : Measure M := + euclideanVolumeFactor n • Measure.hausdorffMeasure (n : ℝ) + +/-- Almost-everywhere measurable probability densities between fixed bounds. -/ +def AdmissibleDensity (vol : Measure M) (lam cap : ℝ) (rho : M → ℝ) : Prop := + AEMeasurable rho vol ∧ Integrable rho vol ∧ + (∫ x, rho x ∂vol) = 1 ∧ (∀ᵐ x ∂vol, lam ≤ rho x ∧ rho x ≤ cap) + +/-- Multiplication by a density, ignoring exceptional negative values on null sets. -/ +def densityMeasure (vol : Measure M) (rho : M → ℝ) : Measure M := + vol.withDensity (fun x => ENNReal.ofReal (rho x)) + +/-- Optimality for the Monge minimization problem. -/ +def IsOptimalMap (vol : Measure M) (rho0 rho1 : M → ℝ) (T : M → M) : Prop := + Measurable T ∧ Measure.map T (densityMeasure vol rho0) = densityMeasure vol rho1 ∧ + ∀ S : M → M, Measurable S → + Measure.map S (densityMeasure vol rho0) = densityMeasure vol rho1 → + (∫ x, cost x (T x) * rho0 x ∂vol) ≤ + (∫ x, cost x (S x) * rho0 x ∂vol) + +/-- The two global estimates have the very same exponent and constant. -/ +def BiHolderEstimate (alpha C : ℝ) (T : M ≃ₜ M) : Prop := + (∀ x x', dist (T x) (T x') ≤ C * (dist x x') ^ alpha) ∧ + (∀ y y', dist (T.symm y) (T.symm y') ≤ C * (dist y y') ^ alpha) + +end MetricDefinitions + +section RiemannianDefinitions + +variable {n : ℕ} {M : Type*} [MetricSpace M] [ChartedSpace (Model n) M] + [IsManifold 𝓘(ℝ, Model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + +/-- Complete affinely parametrized geodesic with prescribed initial tangent. +Local metric minimization is an intrinsic definition of Riemannian geodesics. -/ +def IsGeodesicWithInitialData (x : M) (v : TangentSpace 𝓘(ℝ, Model n) x) + (gamma : ℝ → M) : Prop := + ContMDiff 𝓘(ℝ, ℝ) 𝓘(ℝ, Model n) ∞ gamma ∧ + (⟨gamma 0, mfderiv 𝓘(ℝ, ℝ) 𝓘(ℝ, Model n) gamma 0 (1 : ℝ)⟩ : + TangentBundle 𝓘(ℝ, Model n) M) = ⟨x, v⟩ ∧ + ∀ t : ℝ, ∃ eps : ℝ, 0 < eps ∧ + ∀ s u : ℝ, |s - t| < eps → |u - t| < eps → + dist (gamma s) (gamma u) = |s - u| * ‖v‖ + +/-- Evaluation at time one of the geodesic determined by initial data. -/ +def riemannianExp (x : M) (v : TangentSpace 𝓘(ℝ, Model n) x) : M := by + classical + exact if h : ∃ gamma, IsGeodesicWithInitialData x v gamma then (Classical.choose h) 1 else x + +/-- The open injectivity domain, defined by extendible minimizing vectors. -/ +def injectivityDomain (x : M) : Set (TangentSpace 𝓘(ℝ, Model n) x) := + {p | ∃ a : ℝ, 1 < a ∧ dist x (riemannianExp x (a • p)) = a * ‖p‖} + +/-- The Ma–Trudinger–Wang fourth derivative with factor -3/2. -/ +def mtw (x : M) (p xi eta : TangentSpace 𝓘(ℝ, Model n) x) : ℝ := + -(3 / 2 : ℝ) * + iteratedDeriv 2 (fun s : ℝ => + iteratedDeriv 2 (fun t : ℝ => + cost (riemannianExp x (t • xi)) (riemannianExp x (p + s • eta))) 0) 0 + +/-- Weak MTW only at interior velocities and only for orthogonal test vectors. -/ +def WeakMTW : Prop := + ∀ (x : M) (p : TangentSpace 𝓘(ℝ, Model n) x), p ∈ injectivityDomain x → + ∀ xi eta : TangentSpace 𝓘(ℝ, Model n) x, + inner ℝ xi eta = 0 → 0 ≤ mtw x p xi eta + +end RiemannianDefinitions + +/-- Uniform bi-Hölder optimal transport for all densities between fixed bounds +on a compact connected smooth Riemannian manifold satisfying weak MTW. -/ +theorem uniform_biHolder_transport + {n : ℕ} (hn : 2 ≤ n) {M : Type*} + [MetricSpace M] [CompactSpace M] [ConnectedSpace M] + [ChartedSpace (Model n) M] [IsManifold 𝓘(ℝ, Model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + [IsContMDiffRiemannianBundle 𝓘(ℝ, Model n) ∞ (Model n) + (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + [IsRiemannianManifold 𝓘(ℝ, Model n) M] + [MeasurableSpace M] [BorelSpace M] + (hmtw : WeakMTW (n := n) (M := M)) + (lam cap : ℝ) (hlam : 0 < lam) (hcap : lam ≤ cap) + (hclass : ∃ rho : M → ℝ, AdmissibleDensity (metricVolume n) lam cap rho) : + ∃ alpha C : ℝ, 0 < alpha ∧ alpha ≤ 1 ∧ 0 ≤ C ∧ + ∀ rho0 rho1 : M → ℝ, + AdmissibleDensity (metricVolume n) lam cap rho0 → + AdmissibleDensity (metricVolume n) lam cap rho1 → + ∃ T : M ≃ₜ M, + IsOptimalMap (metricVolume n) rho0 rho1 T ∧ + (∀ S : M → M, IsOptimalMap (metricVolume n) rho0 rho1 S → + S =ᵐ[densityMeasure (metricVolume n) rho0] T) ∧ + BiHolderEstimate alpha C T := by + sorry + +end WeakMTWTransport + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BiholderTransport.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WeakMTWTransport.uniform_biHolder_transport` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/biholder-transport/solution/closure.txt b/tasks/biholder-transport/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..17b2199f4e783920985eda1fb1291c21bd5d7856 --- /dev/null +++ b/tasks/biholder-transport/solution/closure.txt @@ -0,0 +1,645 @@ +OAI.Analysis.BiholderTransport.Calculus.ActionCalculus +OAI.Analysis.BiholderTransport.Calculus.CompactParameterJets +OAI.Analysis.BiholderTransport.Calculus.CompactSmoothGrowth +OAI.Analysis.BiholderTransport.Calculus.DerivativeNegLowerCrossing +OAI.Analysis.BiholderTransport.Calculus.ExactScalarBounds +OAI.Analysis.BiholderTransport.Calculus.FiberJet +OAI.Analysis.BiholderTransport.Calculus.FiniteSmoothTransverseGrowth +OAI.Analysis.BiholderTransport.Calculus.FiniteTaylor +OAI.Analysis.BiholderTransport.Calculus.FullSet +OAI.Analysis.BiholderTransport.Calculus.Gradient +OAI.Analysis.BiholderTransport.Calculus.HopfGradient +OAI.Analysis.BiholderTransport.Calculus.HopfGradientBound +OAI.Analysis.BiholderTransport.Calculus.ImplicitNeighborhood +OAI.Analysis.BiholderTransport.Calculus.JetPullback +OAI.Analysis.BiholderTransport.Calculus.JetTranslation +OAI.Analysis.BiholderTransport.Calculus.LocalCostGradient +OAI.Analysis.BiholderTransport.Calculus.LocalCostSmooth +OAI.Analysis.BiholderTransport.Calculus.LocalMetricGradient +OAI.Analysis.BiholderTransport.Calculus.LowerTaylorComposition +OAI.Analysis.BiholderTransport.Calculus.MaximumScalarJets +OAI.Analysis.BiholderTransport.Calculus.MixedContinuity +OAI.Analysis.BiholderTransport.Calculus.ModifiedScalarDerivatives +OAI.Analysis.BiholderTransport.Calculus.OuterDerivativeBound +OAI.Analysis.BiholderTransport.Calculus.PartialCalculus +OAI.Analysis.BiholderTransport.Calculus.PartialDerivatives +OAI.Analysis.BiholderTransport.Calculus.PathCalculus +OAI.Analysis.BiholderTransport.Calculus.PhaseGraphDerivative +OAI.Analysis.BiholderTransport.Calculus.PhaseJet +OAI.Analysis.BiholderTransport.Calculus.PoleJetAlgebra +OAI.Analysis.BiholderTransport.Calculus.RiemannianContinuous +OAI.Analysis.BiholderTransport.Calculus.SampleJetData +OAI.Analysis.BiholderTransport.Calculus.SamplePoleDerivative +OAI.Analysis.BiholderTransport.Calculus.ScalarFamily +OAI.Analysis.BiholderTransport.Calculus.ScalarFamilyBounds +OAI.Analysis.BiholderTransport.Calculus.ScalarInverseJet +OAI.Analysis.BiholderTransport.Calculus.ScalarJetFormula +OAI.Analysis.BiholderTransport.Calculus.ScalarJetNeighborhood +OAI.Analysis.BiholderTransport.Calculus.ScalarSecond +OAI.Analysis.BiholderTransport.Calculus.SecondDerivativeLinearSandwich +OAI.Analysis.BiholderTransport.Calculus.SecondDerivativeSlice +OAI.Analysis.BiholderTransport.Calculus.SecondDerivativeTaylor +OAI.Analysis.BiholderTransport.Calculus.SecondFderivScalarComp +OAI.Analysis.BiholderTransport.Calculus.SecondTaylorComposition +OAI.Analysis.BiholderTransport.Calculus.ShortGradientLimit +OAI.Analysis.BiholderTransport.Calculus.ShortPoleIdentities +OAI.Analysis.BiholderTransport.Calculus.ShortSmoothFamily +OAI.Analysis.BiholderTransport.Calculus.SliceDerivatives +OAI.Analysis.BiholderTransport.Calculus.SmoothDistance +OAI.Analysis.BiholderTransport.Calculus.SmoothExtensionNear +OAI.Analysis.BiholderTransport.Calculus.TaylorAlgebra +OAI.Analysis.BiholderTransport.Calculus.TaylorBound +OAI.Analysis.BiholderTransport.Calculus.TaylorPositivity +OAI.Analysis.BiholderTransport.Calculus.TrueCenterGradient +OAI.Analysis.BiholderTransport.Calculus.TrueCenterJet +OAI.Analysis.BiholderTransport.Calculus.TrueCenterJetBuild +OAI.Analysis.BiholderTransport.Calculus.UniformCostTaylor +OAI.Analysis.BiholderTransport.Calculus.WeightedDefect +OAI.Analysis.BiholderTransport.Contact.AEContacts +OAI.Analysis.BiholderTransport.Contact.ActiveContinuationLocal +OAI.Analysis.BiholderTransport.Contact.ActiveLocalGrowth +OAI.Analysis.BiholderTransport.Contact.ActualEnvelopeJets +OAI.Analysis.BiholderTransport.Contact.ActualPoleJet +OAI.Analysis.BiholderTransport.Contact.BranchContact +OAI.Analysis.BiholderTransport.Contact.CenterSupport +OAI.Analysis.BiholderTransport.Contact.CenterSupportFamily +OAI.Analysis.BiholderTransport.Contact.CompactMinty +OAI.Analysis.BiholderTransport.Contact.ContactCharts +OAI.Analysis.BiholderTransport.Contact.ContactCharts2 +OAI.Analysis.BiholderTransport.Contact.ContactDerivative +OAI.Analysis.BiholderTransport.Contact.ContactImage +OAI.Analysis.BiholderTransport.Contact.ContactJetCalculus +OAI.Analysis.BiholderTransport.Contact.ContactPSD +OAI.Analysis.BiholderTransport.Contact.ContactRelationChart +OAI.Analysis.BiholderTransport.Contact.ContactSelection +OAI.Analysis.BiholderTransport.Contact.ContactStationarity +OAI.Analysis.BiholderTransport.Contact.CoordinateScalarSupport +OAI.Analysis.BiholderTransport.Contact.CoordinateSupport +OAI.Analysis.BiholderTransport.Contact.CoordinateSupportGradient +OAI.Analysis.BiholderTransport.Contact.EnvelopePole +OAI.Analysis.BiholderTransport.Contact.GlobalSupport +OAI.Analysis.BiholderTransport.Contact.GraphCompact +OAI.Analysis.BiholderTransport.Contact.GraphProjection +OAI.Analysis.BiholderTransport.Contact.HopfSupports +OAI.Analysis.BiholderTransport.Contact.Inner +OAI.Analysis.BiholderTransport.Contact.IntrinsicCEMS +OAI.Analysis.BiholderTransport.Contact.LocalCEMS +OAI.Analysis.BiholderTransport.Contact.LocalCEMS2 +OAI.Analysis.BiholderTransport.Contact.LocalUniformTestPDE +OAI.Analysis.BiholderTransport.Contact.LowerTestContact +OAI.Analysis.BiholderTransport.Contact.MatchedSupports +OAI.Analysis.BiholderTransport.Contact.MiddleExclusion +OAI.Analysis.BiholderTransport.Contact.ModifiedActiveLowerJet +OAI.Analysis.BiholderTransport.Contact.MovingCostSupport +OAI.Analysis.BiholderTransport.Contact.PhaseContact +OAI.Analysis.BiholderTransport.Contact.ProximalSelectorDerivative +OAI.Analysis.BiholderTransport.Contact.SmoothSupportSemibound +OAI.Analysis.BiholderTransport.Contact.SmoothTestPDE +OAI.Analysis.BiholderTransport.Contact.Subgradient +OAI.Analysis.BiholderTransport.Contact.SubgradientDifferential +OAI.Analysis.BiholderTransport.Contact.SubgradientUpper +OAI.Analysis.BiholderTransport.Contact.TestMountains +OAI.Analysis.BiholderTransport.Contact.UpperContactIteratedDeriv +OAI.Analysis.BiholderTransport.Convexity.ActualCenterSemibound +OAI.Analysis.BiholderTransport.Convexity.AlexandrovDerivative +OAI.Analysis.BiholderTransport.Convexity.BoundedConvexSecant +OAI.Analysis.BiholderTransport.Convexity.ChartJensenFirstLimit +OAI.Analysis.BiholderTransport.Convexity.CompactConvexHullFinite +OAI.Analysis.BiholderTransport.Convexity.ConvexBarycentricSegment +OAI.Analysis.BiholderTransport.Convexity.ConvexNormSq +OAI.Analysis.BiholderTransport.Convexity.CoordinateSemiconvex +OAI.Analysis.BiholderTransport.Convexity.EndpointLowerJet +OAI.Analysis.BiholderTransport.Convexity.EnvelopeData +OAI.Analysis.BiholderTransport.Convexity.FamilyJensen +OAI.Analysis.BiholderTransport.Convexity.FamilySemiconvex +OAI.Analysis.BiholderTransport.Convexity.FamilyShortEnvelope +OAI.Analysis.BiholderTransport.Convexity.Fermat +OAI.Analysis.BiholderTransport.Convexity.FirstCutConvex +OAI.Analysis.BiholderTransport.Convexity.JensenAt +OAI.Analysis.BiholderTransport.Convexity.JensenAtCenter +OAI.Analysis.BiholderTransport.Convexity.JensenAtFirstLimit +OAI.Analysis.BiholderTransport.Convexity.JensenMaximum +OAI.Analysis.BiholderTransport.Convexity.JensenPackage +OAI.Analysis.BiholderTransport.Convexity.JensenPhase +OAI.Analysis.BiholderTransport.Convexity.JensenPhaseGradient +OAI.Analysis.BiholderTransport.Convexity.JensenUndoShort +OAI.Analysis.BiholderTransport.Convexity.MaximumJensen +OAI.Analysis.BiholderTransport.Convexity.MaximumJensenFamily +OAI.Analysis.BiholderTransport.Convexity.ModifiedEnvelopeRegularity +OAI.Analysis.BiholderTransport.Convexity.MovingCenterSemibound +OAI.Analysis.BiholderTransport.Convexity.ParametricSemiconvex +OAI.Analysis.BiholderTransport.Convexity.ParametricShortLowerEnvelope +OAI.Analysis.BiholderTransport.Convexity.ParametricShortLowerJets +OAI.Analysis.BiholderTransport.Convexity.ProximalProducer +OAI.Analysis.BiholderTransport.Convexity.ShortEnvelopeJetTest +OAI.Analysis.BiholderTransport.Convexity.ShortEnvelopeSemibound +OAI.Analysis.BiholderTransport.Convexity.ShortPullbackSemibound +OAI.Analysis.BiholderTransport.Convexity.SimultaneousC11Jensen +OAI.Analysis.BiholderTransport.Convexity.StrongCostConvexity +OAI.Analysis.BiholderTransport.Convexity.StrongEnvelope +OAI.Analysis.BiholderTransport.Convexity.TransformSemiconvex +OAI.Analysis.BiholderTransport.Convexity.TranslatedMinorant +OAI.Analysis.BiholderTransport.Convexity.UniformEnvelope +OAI.Analysis.BiholderTransport.Coordinates.AECertificates +OAI.Analysis.BiholderTransport.Coordinates.ActiveCompact +OAI.Analysis.BiholderTransport.Coordinates.ActiveDifferentiability +OAI.Analysis.BiholderTransport.Coordinates.ActiveHull +OAI.Analysis.BiholderTransport.Coordinates.ActiveHullUniform +OAI.Analysis.BiholderTransport.Coordinates.ActiveUniformGrowth +OAI.Analysis.BiholderTransport.Coordinates.ActualLowerTestBound +OAI.Analysis.BiholderTransport.Coordinates.Add +OAI.Analysis.BiholderTransport.Coordinates.AePullbackLipschitzChart +OAI.Analysis.BiholderTransport.Coordinates.BranchChartBaseline +OAI.Analysis.BiholderTransport.Coordinates.BranchChartJets +OAI.Analysis.BiholderTransport.Coordinates.BranchInverse +OAI.Analysis.BiholderTransport.Coordinates.BranchJets +OAI.Analysis.BiholderTransport.Coordinates.ChartActiveLimit +OAI.Analysis.BiholderTransport.Coordinates.ChartAlexandrov +OAI.Analysis.BiholderTransport.Coordinates.ChartCenterGain +OAI.Analysis.BiholderTransport.Coordinates.ChartCostJets +OAI.Analysis.BiholderTransport.Coordinates.ChartGradientMap +OAI.Analysis.BiholderTransport.Coordinates.ChartHopfLocalization +OAI.Analysis.BiholderTransport.Coordinates.ChartLipschitz +OAI.Analysis.BiholderTransport.Coordinates.ChartParameter +OAI.Analysis.BiholderTransport.Coordinates.ChartTransition +OAI.Analysis.BiholderTransport.Coordinates.ChartTrueCenter +OAI.Analysis.BiholderTransport.Coordinates.Charts +OAI.Analysis.BiholderTransport.Coordinates.CompactConfigurations +OAI.Analysis.BiholderTransport.Coordinates.CompactEventuallyFiberwise +OAI.Analysis.BiholderTransport.Coordinates.CoordinateExpansion +OAI.Analysis.BiholderTransport.Coordinates.CoordinateGradient +OAI.Analysis.BiholderTransport.Coordinates.CoordinateMatrices +OAI.Analysis.BiholderTransport.Coordinates.CoordinateMetricNorm +OAI.Analysis.BiholderTransport.Coordinates.CoordinatePairingDerivative +OAI.Analysis.BiholderTransport.Coordinates.CoordinatePole +OAI.Analysis.BiholderTransport.Coordinates.CoordinateTrueLog +OAI.Analysis.BiholderTransport.Coordinates.CoordinateVariation +OAI.Analysis.BiholderTransport.Coordinates.Coordinates +OAI.Analysis.BiholderTransport.Coordinates.CutCharacterization +OAI.Analysis.BiholderTransport.Coordinates.Endpoint +OAI.Analysis.BiholderTransport.Coordinates.ExpJacContinuity +OAI.Analysis.BiholderTransport.Coordinates.ExpLocalBounds +OAI.Analysis.BiholderTransport.Coordinates.ExpNonconjugacy +OAI.Analysis.BiholderTransport.Coordinates.ExpNonconjugateLimit +OAI.Analysis.BiholderTransport.Coordinates.ExpReciprocity +OAI.Analysis.BiholderTransport.Coordinates.ExpVertical +OAI.Analysis.BiholderTransport.Coordinates.FactorNorm +OAI.Analysis.BiholderTransport.Coordinates.FiberLog +OAI.Analysis.BiholderTransport.Coordinates.FiberNormal +OAI.Analysis.BiholderTransport.Coordinates.FiberwiseHomeomorphism +OAI.Analysis.BiholderTransport.Coordinates.FiniteActiveGrowth +OAI.Analysis.BiholderTransport.Coordinates.FiniteLogScaleAvoidance +OAI.Analysis.BiholderTransport.Coordinates.FixedJoinDifference +OAI.Analysis.BiholderTransport.Coordinates.FixedJoinSmooth +OAI.Analysis.BiholderTransport.Coordinates.GraphCoordinates +OAI.Analysis.BiholderTransport.Coordinates.Inner +OAI.Analysis.BiholderTransport.Coordinates.IntrinsicGradient +OAI.Analysis.BiholderTransport.Coordinates.JetDiffeomorphism +OAI.Analysis.BiholderTransport.Coordinates.JoinCoordinates +OAI.Analysis.BiholderTransport.Coordinates.JoiningCoordinates +OAI.Analysis.BiholderTransport.Coordinates.JointExpInverse +OAI.Analysis.BiholderTransport.Coordinates.JointNormalChart +OAI.Analysis.BiholderTransport.Coordinates.KernelRadial +OAI.Analysis.BiholderTransport.Coordinates.LocalInverseCalculus +OAI.Analysis.BiholderTransport.Coordinates.LocalMetricCharts +OAI.Analysis.BiholderTransport.Coordinates.LocalOuterJetBound +OAI.Analysis.BiholderTransport.Coordinates.LocalOuterLog +OAI.Analysis.BiholderTransport.Coordinates.LogActionMixed +OAI.Analysis.BiholderTransport.Coordinates.ManifoldLipschitz +OAI.Analysis.BiholderTransport.Coordinates.ManifoldMinimum +OAI.Analysis.BiholderTransport.Coordinates.MetricLocalGrowth +OAI.Analysis.BiholderTransport.Coordinates.Midpoint +OAI.Analysis.BiholderTransport.Coordinates.MovingNormalEndpointJoin +OAI.Analysis.BiholderTransport.Coordinates.NormalCoordinates +OAI.Analysis.BiholderTransport.Coordinates.NormalCoordinates2 +OAI.Analysis.BiholderTransport.Coordinates.NormalCoordinates3 +OAI.Analysis.BiholderTransport.Coordinates.NormalEikonal +OAI.Analysis.BiholderTransport.Coordinates.NormalEndpointInverse +OAI.Analysis.BiholderTransport.Coordinates.NormalEndpointJoin +OAI.Analysis.BiholderTransport.Coordinates.NormalFrameTaylor +OAI.Analysis.BiholderTransport.Coordinates.NormalGradient +OAI.Analysis.BiholderTransport.Coordinates.NormalLogMixed +OAI.Analysis.BiholderTransport.Coordinates.NormalLowerTaylorBound +OAI.Analysis.BiholderTransport.Coordinates.NormalPoleTaylor +OAI.Analysis.BiholderTransport.Coordinates.NormalRigidity +OAI.Analysis.BiholderTransport.Coordinates.NormalSubdifferential +OAI.Analysis.BiholderTransport.Coordinates.NormalTestChart +OAI.Analysis.BiholderTransport.Coordinates.OuterCoordinate +OAI.Analysis.BiholderTransport.Coordinates.PoleCoordinates +OAI.Analysis.BiholderTransport.Coordinates.Prefix +OAI.Analysis.BiholderTransport.Coordinates.ProperPieces +OAI.Analysis.BiholderTransport.Coordinates.RadialFactor +OAI.Analysis.BiholderTransport.Coordinates.RadialIdentity +OAI.Analysis.BiholderTransport.Coordinates.RayBenchmark +OAI.Analysis.BiholderTransport.Coordinates.ReverseIsotropicGain +OAI.Analysis.BiholderTransport.Coordinates.ScalarExpansion +OAI.Analysis.BiholderTransport.Coordinates.ShortLocalMinimum +OAI.Analysis.BiholderTransport.Coordinates.SmoothUpperTest +OAI.Analysis.BiholderTransport.Coordinates.SplitAction +OAI.Analysis.BiholderTransport.Coordinates.SplitLogInjective +OAI.Analysis.BiholderTransport.Coordinates.SplitPairing +OAI.Analysis.BiholderTransport.Coordinates.Stationary +OAI.Analysis.BiholderTransport.Coordinates.TangentLift +OAI.Analysis.BiholderTransport.Coordinates.Taylor +OAI.Analysis.BiholderTransport.Coordinates.TotalInjectivity +OAI.Analysis.BiholderTransport.Coordinates.TwoSidedFiberLog +OAI.Analysis.BiholderTransport.Coordinates.UniformLog +OAI.Analysis.BiholderTransport.Coordinates.UniformShort +OAI.Analysis.BiholderTransport.CostGeometry.ActualPole +OAI.Analysis.BiholderTransport.CostGeometry.ActualPoleKernel +OAI.Analysis.BiholderTransport.CostGeometry.BranchActiveGrowth +OAI.Analysis.BiholderTransport.CostGeometry.BranchCost +OAI.Analysis.BiholderTransport.CostGeometry.BranchCost2 +OAI.Analysis.BiholderTransport.CostGeometry.BranchGrowth +OAI.Analysis.BiholderTransport.CostGeometry.BranchJetSecond +OAI.Analysis.BiholderTransport.CostGeometry.CostGradient +OAI.Analysis.BiholderTransport.CostGeometry.CostSmooth +OAI.Analysis.BiholderTransport.CostGeometry.CrossingUniform +OAI.Analysis.BiholderTransport.CostGeometry.CurveAdvance +OAI.Analysis.BiholderTransport.CostGeometry.CurvedQuadratic +OAI.Analysis.BiholderTransport.CostGeometry.DividedAction +OAI.Analysis.BiholderTransport.CostGeometry.DividedPullback +OAI.Analysis.BiholderTransport.CostGeometry.ExactTemplateCurvature +OAI.Analysis.BiholderTransport.CostGeometry.FirstCutLower +OAI.Analysis.BiholderTransport.CostGeometry.FirstCutSegment +OAI.Analysis.BiholderTransport.CostGeometry.GraphOpen +OAI.Analysis.BiholderTransport.CostGeometry.LimitIsolation +OAI.Analysis.BiholderTransport.CostGeometry.LinearRadialDerivative +OAI.Analysis.BiholderTransport.CostGeometry.LocalBranchJetBound +OAI.Analysis.BiholderTransport.CostGeometry.OuterCurvature +OAI.Analysis.BiholderTransport.CostGeometry.OuterNonconjugacy +OAI.Analysis.BiholderTransport.CostGeometry.PoleLipschitz +OAI.Analysis.BiholderTransport.CostGeometry.PrecutExtension +OAI.Analysis.BiholderTransport.CostGeometry.ProjectionContinuation +OAI.Analysis.BiholderTransport.CostGeometry.QuantitativeDividedAction +OAI.Analysis.BiholderTransport.CostGeometry.RadialBounds +OAI.Analysis.BiholderTransport.CostGeometry.RadialSingular +OAI.Analysis.BiholderTransport.CostGeometry.RadialVelocityMetricEqualities +OAI.Analysis.BiholderTransport.CostGeometry.SectionDiameter +OAI.Analysis.BiholderTransport.CostGeometry.Slack +OAI.Analysis.BiholderTransport.CostGeometry.SplitEndpoint +OAI.Analysis.BiholderTransport.CostGeometry.SplitStationary +OAI.Analysis.BiholderTransport.CostGeometry.SplitTrial +OAI.Analysis.BiholderTransport.CostGeometry.StrictDividedAction +OAI.Analysis.BiholderTransport.CostGeometry.UniformFiniteRadialScale +OAI.Analysis.BiholderTransport.CostGeometry.UniformLocalGap +OAI.Analysis.BiholderTransport.CostGeometry.UniformRegularSplit +OAI.Analysis.BiholderTransport.CostGeometry.UniformReverseGain +OAI.Analysis.BiholderTransport.CostGeometry.UpperTest +OAI.Analysis.BiholderTransport.Duality.AEDual +OAI.Analysis.BiholderTransport.Duality.ActualLowerJet +OAI.Analysis.BiholderTransport.Duality.CompactDual +OAI.Analysis.BiholderTransport.Duality.DualCompact +OAI.Analysis.BiholderTransport.Duality.DualFactor +OAI.Analysis.BiholderTransport.Duality.DualVariation +OAI.Analysis.BiholderTransport.Duality.GeometricEnvelope +OAI.Analysis.BiholderTransport.Duality.RiemannianTransport +OAI.Analysis.BiholderTransport.Geodesics.BranchExtension +OAI.Analysis.BiholderTransport.Geodesics.ChartLipschitz +OAI.Analysis.BiholderTransport.Geodesics.CompleteSpray +OAI.Analysis.BiholderTransport.Geodesics.DoubleMountain +OAI.Analysis.BiholderTransport.Geodesics.EndpointIdentity +OAI.Analysis.BiholderTransport.Geodesics.ExpInteriorUnique +OAI.Analysis.BiholderTransport.Geodesics.GaussLemma +OAI.Analysis.BiholderTransport.Geodesics.GeodesicBasics +OAI.Analysis.BiholderTransport.Geodesics.GeodesicExistence +OAI.Analysis.BiholderTransport.Geodesics.GeodesicSpray +OAI.Analysis.BiholderTransport.Geodesics.GlobalGauss +OAI.Analysis.BiholderTransport.Geodesics.GoodContact +OAI.Analysis.BiholderTransport.Geodesics.GraphGlobalMinimal +OAI.Analysis.BiholderTransport.Geodesics.InjectivityOpen +OAI.Analysis.BiholderTransport.Geodesics.IntegratedGauss +OAI.Analysis.BiholderTransport.Geodesics.MetricCurveLocal +OAI.Analysis.BiholderTransport.Geodesics.MetricCurveSpeed +OAI.Analysis.BiholderTransport.Geodesics.MetricGeodesicLift +OAI.Analysis.BiholderTransport.Geodesics.MetricSegments +OAI.Analysis.BiholderTransport.Geodesics.MinimizingChartParameters +OAI.Analysis.BiholderTransport.Geodesics.MinimizingCoordinateLimit +OAI.Analysis.BiholderTransport.Geodesics.MinimizingSubinterval +OAI.Analysis.BiholderTransport.Geodesics.NoCorner +OAI.Analysis.BiholderTransport.Geodesics.NormalEndpointLog +OAI.Analysis.BiholderTransport.Geodesics.OriginalMass +OAI.Analysis.BiholderTransport.Geodesics.RayAdvance +OAI.Analysis.BiholderTransport.Geodesics.ReverseSpectrum +OAI.Analysis.BiholderTransport.Geodesics.ShortGradient +OAI.Analysis.BiholderTransport.Geodesics.SplitMinimizingAction +OAI.Analysis.BiholderTransport.Geodesics.SprayActionMinimum +OAI.Analysis.BiholderTransport.Geodesics.SprayDistanceBound +OAI.Analysis.BiholderTransport.Geodesics.SprayEnergy +OAI.Analysis.BiholderTransport.Geodesics.SprayMinimizerUnique +OAI.Analysis.BiholderTransport.Geodesics.SprayMinimizing +OAI.Analysis.BiholderTransport.Geodesics.SprayNonconjugacy +OAI.Analysis.BiholderTransport.Geodesics.SprayProjection +OAI.Analysis.BiholderTransport.Geodesics.SprayScaling +OAI.Analysis.BiholderTransport.Geodesics.UniformFixedCrossing +OAI.Analysis.BiholderTransport.LinearAlgebra.ActualRadial +OAI.Analysis.BiholderTransport.LinearAlgebra.ActualRelativeHessianBound +OAI.Analysis.BiholderTransport.LinearAlgebra.Aggregate +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearAbsorption +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearClose +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearCompact +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearDet +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearGainLimit +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.BilinearMetricSpeedSquare +OAI.Analysis.BiholderTransport.LinearAlgebra.BranchDividedBaseline +OAI.Analysis.BiholderTransport.LinearAlgebra.BranchHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.C11HessianLimits +OAI.Analysis.BiholderTransport.LinearAlgebra.Calculus +OAI.Analysis.BiholderTransport.LinearAlgebra.ChartFirstMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.ChartOuterMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.ChartTrueMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.CompactConorm +OAI.Analysis.BiholderTransport.LinearAlgebra.CompactCrossing +OAI.Analysis.BiholderTransport.LinearAlgebra.CompactLocalPositiveBounds +OAI.Analysis.BiholderTransport.LinearAlgebra.CompactQuadratic +OAI.Analysis.BiholderTransport.LinearAlgebra.CongruenceSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.ContactDifferential +OAI.Analysis.BiholderTransport.LinearAlgebra.ContactStationarity +OAI.Analysis.BiholderTransport.LinearAlgebra.ConvexSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.CurvedBlowup +OAI.Analysis.BiholderTransport.LinearAlgebra.DeterminantOrder +OAI.Analysis.BiholderTransport.LinearAlgebra.Diagonal +OAI.Analysis.BiholderTransport.LinearAlgebra.DiagonalCostConvexity +OAI.Analysis.BiholderTransport.LinearAlgebra.DividedHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.EigenOrder +OAI.Analysis.BiholderTransport.LinearAlgebra.EndpointSpectrumBound +OAI.Analysis.BiholderTransport.LinearAlgebra.EnvelopeKernelHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.FinitePositiveWeight +OAI.Analysis.BiholderTransport.LinearAlgebra.FirstMatrixLimit +OAI.Analysis.BiholderTransport.LinearAlgebra.FirstRank +OAI.Analysis.BiholderTransport.LinearAlgebra.FixedJoinSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.FrameDeterminantClosure +OAI.Analysis.BiholderTransport.LinearAlgebra.FunctionalCoercive +OAI.Analysis.BiholderTransport.LinearAlgebra.HalfCostUniform +OAI.Analysis.BiholderTransport.LinearAlgebra.Hessian +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianBounds +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianCoordinates +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianMixedOperator +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianSequentialUpper +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianSmooth +OAI.Analysis.BiholderTransport.LinearAlgebra.HessianUpperTransfer +OAI.Analysis.BiholderTransport.LinearAlgebra.InverseProfile +OAI.Analysis.BiholderTransport.LinearAlgebra.JensenHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.JoinCongruence +OAI.Analysis.BiholderTransport.LinearAlgebra.JoinOperator +OAI.Analysis.BiholderTransport.LinearAlgebra.JoinSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.LocalMountains +OAI.Analysis.BiholderTransport.LinearAlgebra.LocalNormalChart +OAI.Analysis.BiholderTransport.LinearAlgebra.LowerTaylor +OAI.Analysis.BiholderTransport.LinearAlgebra.MatrixNormDetFactorial +OAI.Analysis.BiholderTransport.LinearAlgebra.MaximumPolePositive +OAI.Analysis.BiholderTransport.LinearAlgebra.MaximumRank +OAI.Analysis.BiholderTransport.LinearAlgebra.MiddleScaling +OAI.Analysis.BiholderTransport.LinearAlgebra.MixedOperator +OAI.Analysis.BiholderTransport.LinearAlgebra.MixedTrivializationBound +OAI.Analysis.BiholderTransport.LinearAlgebra.MovingFamilyHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.MovingHessianLimit +OAI.Analysis.BiholderTransport.LinearAlgebra.MovingSplit +OAI.Analysis.BiholderTransport.LinearAlgebra.NormDetAdjoint +OAI.Analysis.BiholderTransport.LinearAlgebra.NormDetCoercivity +OAI.Analysis.BiholderTransport.LinearAlgebra.NormalRelativeHessianBound +OAI.Analysis.BiholderTransport.LinearAlgebra.OperatorBounds +OAI.Analysis.BiholderTransport.LinearAlgebra.OuterActiveMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.OuterDisplacementJetBound +OAI.Analysis.BiholderTransport.LinearAlgebra.OuterTrueMatrix +OAI.Analysis.BiholderTransport.LinearAlgebra.Pole +OAI.Analysis.BiholderTransport.LinearAlgebra.PositiveBilinearBound +OAI.Analysis.BiholderTransport.LinearAlgebra.PositiveDetCompact +OAI.Analysis.BiholderTransport.LinearAlgebra.PositiveSingular +OAI.Analysis.BiholderTransport.LinearAlgebra.PrefixActionJets +OAI.Analysis.BiholderTransport.LinearAlgebra.QuadraticTest +OAI.Analysis.BiholderTransport.LinearAlgebra.RadialHessian +OAI.Analysis.BiholderTransport.LinearAlgebra.RankOneCoercive +OAI.Analysis.BiholderTransport.LinearAlgebra.RelativeHessianBound +OAI.Analysis.BiholderTransport.LinearAlgebra.RescaledJoinOperator +OAI.Analysis.BiholderTransport.LinearAlgebra.ScaledQuadraticBoundEigenvalues +OAI.Analysis.BiholderTransport.LinearAlgebra.ScaledSlack +OAI.Analysis.BiholderTransport.LinearAlgebra.ScaledSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.SchurBackground +OAI.Analysis.BiholderTransport.LinearAlgebra.SchurCalculus +OAI.Analysis.BiholderTransport.LinearAlgebra.SchurEnvelope +OAI.Analysis.BiholderTransport.LinearAlgebra.SchurRatioTendstoBot +OAI.Analysis.BiholderTransport.LinearAlgebra.ShearBounds +OAI.Analysis.BiholderTransport.LinearAlgebra.ShearConvexity +OAI.Analysis.BiholderTransport.LinearAlgebra.ShearedOperator +OAI.Analysis.BiholderTransport.LinearAlgebra.ShearedSpectrum +OAI.Analysis.BiholderTransport.LinearAlgebra.SpectralContinuity +OAI.Analysis.BiholderTransport.LinearAlgebra.SplitActionSchur +OAI.Analysis.BiholderTransport.LinearAlgebra.SplitEndpointJets +OAI.Analysis.BiholderTransport.LinearAlgebra.StationarySchur +OAI.Analysis.BiholderTransport.LinearAlgebra.ThreeDeterminantsClose +OAI.Analysis.BiholderTransport.LinearAlgebra.TransverseConcavity +OAI.Analysis.BiholderTransport.LinearAlgebra.TrueCenterMatrix +OAI.Analysis.BiholderTransport.LocalFlow.CompactFlow +OAI.Analysis.BiholderTransport.LocalFlow.CotangentFlow +OAI.Analysis.BiholderTransport.LocalFlow.ForwardChart +OAI.Analysis.BiholderTransport.LocalFlow.ImplicitODE +OAI.Analysis.BiholderTransport.LocalFlow.LocalDomainFlow +OAI.Analysis.BiholderTransport.LocalFlow.LocalMetricNormal +OAI.Analysis.BiholderTransport.LocalFlow.MIntegralCurveUniformInvariant +OAI.Analysis.BiholderTransport.LocalFlow.ModelTangentJet +OAI.Analysis.BiholderTransport.LocalFlow.NormalFlow +OAI.Analysis.BiholderTransport.LocalFlow.SmoothCoordinateFlow +OAI.Analysis.BiholderTransport.LocalFlow.SmoothFlowEndpoint +OAI.Analysis.BiholderTransport.LocalFlow.SmoothIntegralCurve +OAI.Analysis.BiholderTransport.Main +OAI.Analysis.BiholderTransport.MinimizingVectors +OAI.Analysis.BiholderTransport.Model +OAI.Analysis.BiholderTransport.Oscillation.ActualPlateaus +OAI.Analysis.BiholderTransport.Oscillation.ClassPower +OAI.Analysis.BiholderTransport.Oscillation.LowerSwitch +OAI.Analysis.BiholderTransport.Oscillation.NonpowerMaximum +OAI.Analysis.BiholderTransport.Oscillation.ScalarFirstSwitch +OAI.Analysis.BiholderTransport.Oscillation.SectionOscillation +OAI.Analysis.BiholderTransport.Oscillation.SwitchNorms +OAI.Analysis.BiholderTransport.Oscillation.SwitchNumerics +OAI.Analysis.BiholderTransport.Oscillation.SwitchToExcess +OAI.Analysis.BiholderTransport.Regularity.AERademacher +OAI.Analysis.BiholderTransport.Regularity.ActionKernel +OAI.Analysis.BiholderTransport.Regularity.ActionLocalData +OAI.Analysis.BiholderTransport.Regularity.ActiveDifference +OAI.Analysis.BiholderTransport.Regularity.ActiveGraphLimit +OAI.Analysis.BiholderTransport.Regularity.ActiveLimit +OAI.Analysis.BiholderTransport.Regularity.ActiveOuter +OAI.Analysis.BiholderTransport.Regularity.ActualCenterRay +OAI.Analysis.BiholderTransport.Regularity.ActualLevels +OAI.Analysis.BiholderTransport.Regularity.ActualOutward +OAI.Analysis.BiholderTransport.Regularity.ActualParameter +OAI.Analysis.BiholderTransport.Regularity.ActualScaleSmallness +OAI.Analysis.BiholderTransport.Regularity.ActualSmallPlateau +OAI.Analysis.BiholderTransport.Regularity.ActualTransferInequality +OAI.Analysis.BiholderTransport.Regularity.Alignment +OAI.Analysis.BiholderTransport.Regularity.BundleSeparation +OAI.Analysis.BiholderTransport.Regularity.CenterDetCompact +OAI.Analysis.BiholderTransport.Regularity.CenterFullPullback +OAI.Analysis.BiholderTransport.Regularity.CenterPoleLimit +OAI.Analysis.BiholderTransport.Regularity.CenterPoleStationary +OAI.Analysis.BiholderTransport.Regularity.CenterRayLimit +OAI.Analysis.BiholderTransport.Regularity.CenterRegularCompact +OAI.Analysis.BiholderTransport.Regularity.CenterSequenceCompact +OAI.Analysis.BiholderTransport.Regularity.CenterSequenceOriginalLimit +OAI.Analysis.BiholderTransport.Regularity.CenterSequenceRegular +OAI.Analysis.BiholderTransport.Regularity.CenterTrueRayCompact +OAI.Analysis.BiholderTransport.Regularity.CenteredQuadratic +OAI.Analysis.BiholderTransport.Regularity.CompactAE +OAI.Analysis.BiholderTransport.Regularity.CompactDisk +OAI.Analysis.BiholderTransport.Regularity.CompactUniformSecondRemainder +OAI.Analysis.BiholderTransport.Regularity.ConfigurationCompact +OAI.Analysis.BiholderTransport.Regularity.ContDiffParametricQuadratic +OAI.Analysis.BiholderTransport.Regularity.ContDiffParametricSecant +OAI.Analysis.BiholderTransport.Regularity.ContDiffQuadraticUpper +OAI.Analysis.BiholderTransport.Regularity.ContDiffSecondOrder +OAI.Analysis.BiholderTransport.Regularity.ContDiffUncurryIterated +OAI.Analysis.BiholderTransport.Regularity.ContinuousClosedRelationSelector +OAI.Analysis.BiholderTransport.Regularity.CriticalChain +OAI.Analysis.BiholderTransport.Regularity.Diagonal +OAI.Analysis.BiholderTransport.Regularity.EuclideanUpper +OAI.Analysis.BiholderTransport.Regularity.FamilyComparison +OAI.Analysis.BiholderTransport.Regularity.FamilyGlobal +OAI.Analysis.BiholderTransport.Regularity.FiniteIntervalMesh +OAI.Analysis.BiholderTransport.Regularity.FiniteNonnegativeWeight +OAI.Analysis.BiholderTransport.Regularity.FiniteNonnegativeWeightPos +OAI.Analysis.BiholderTransport.Regularity.FiniteSimplexRepresentation +OAI.Analysis.BiholderTransport.Regularity.FirstActiveLimit +OAI.Analysis.BiholderTransport.Regularity.FirstOutward +OAI.Analysis.BiholderTransport.Regularity.FixedJoinMiddle +OAI.Analysis.BiholderTransport.Regularity.FixedJoinUpper +OAI.Analysis.BiholderTransport.Regularity.FrameAbsorption +OAI.Analysis.BiholderTransport.Regularity.FrameDet +OAI.Analysis.BiholderTransport.Regularity.FrameMetric +OAI.Analysis.BiholderTransport.Regularity.FrameOutwardLimit +OAI.Analysis.BiholderTransport.Regularity.FunctionalDet +OAI.Analysis.BiholderTransport.Regularity.GeneratingKernel +OAI.Analysis.BiholderTransport.Regularity.GraphInverse +OAI.Analysis.BiholderTransport.Regularity.HopfApproximation +OAI.Analysis.BiholderTransport.Regularity.InteriorCompactUniqueFiber +OAI.Analysis.BiholderTransport.Regularity.InteriorMaximum +OAI.Analysis.BiholderTransport.Regularity.IntrinsicTestDet +OAI.Analysis.BiholderTransport.Regularity.InverseDifferenceGain +OAI.Analysis.BiholderTransport.Regularity.JointMovingPrefix +OAI.Analysis.BiholderTransport.Regularity.KernelBounds +OAI.Analysis.BiholderTransport.Regularity.LiftedSections +OAI.Analysis.BiholderTransport.Regularity.LimitGeometry +OAI.Analysis.BiholderTransport.Regularity.LipschitzSubAeDeriv +OAI.Analysis.BiholderTransport.Regularity.LocalMinSecondDeriv +OAI.Analysis.BiholderTransport.Regularity.LocalMinStrictGrowth +OAI.Analysis.BiholderTransport.Regularity.MaximumActiveCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumActiveLimits +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterLimit +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterLower +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterRegular +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterSequence +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterSign +OAI.Analysis.BiholderTransport.Regularity.MaximumCenterUpper +OAI.Analysis.BiholderTransport.Regularity.MaximumCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumConfiguration +OAI.Analysis.BiholderTransport.Regularity.MaximumDiagonal +OAI.Analysis.BiholderTransport.Regularity.MaximumEndpoint +OAI.Analysis.BiholderTransport.Regularity.MaximumFamily +OAI.Analysis.BiholderTransport.Regularity.MaximumGoodCenters +OAI.Analysis.BiholderTransport.Regularity.MaximumLowerBound +OAI.Analysis.BiholderTransport.Regularity.MaximumOuterBound +OAI.Analysis.BiholderTransport.Regularity.MaximumOuterSamples +OAI.Analysis.BiholderTransport.Regularity.MaximumOutward +OAI.Analysis.BiholderTransport.Regularity.MaximumOutwardCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumPhaseCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumPoleCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumPoleSymmetric +OAI.Analysis.BiholderTransport.Regularity.MaximumReindex +OAI.Analysis.BiholderTransport.Regularity.MaximumRow +OAI.Analysis.BiholderTransport.Regularity.MaximumSample +OAI.Analysis.BiholderTransport.Regularity.MaximumSelectionCompact +OAI.Analysis.BiholderTransport.Regularity.MaximumSimultaneous +OAI.Analysis.BiholderTransport.Regularity.MaximumTemplateBound +OAI.Analysis.BiholderTransport.Regularity.MaximumTrueCenter +OAI.Analysis.BiholderTransport.Regularity.MaximumTrueOuter +OAI.Analysis.BiholderTransport.Regularity.MetricDefinitions +OAI.Analysis.BiholderTransport.Regularity.MinMax +OAI.Analysis.BiholderTransport.Regularity.MixedDetIntrinsic +OAI.Analysis.BiholderTransport.Regularity.MixedIntrinsic +OAI.Analysis.BiholderTransport.Regularity.ModifiedData +OAI.Analysis.BiholderTransport.Regularity.ModifiedOuterNeighborhood +OAI.Analysis.BiholderTransport.Regularity.ModifiedPhase +OAI.Analysis.BiholderTransport.Regularity.MovingCenterLower +OAI.Analysis.BiholderTransport.Regularity.MovingCenterUpper +OAI.Analysis.BiholderTransport.Regularity.MovingCrossing +OAI.Analysis.BiholderTransport.Regularity.MovingPrefix +OAI.Analysis.BiholderTransport.Regularity.NonnegativeTransfer +OAI.Analysis.BiholderTransport.Regularity.NormLower +OAI.Analysis.BiholderTransport.Regularity.NormMinMax +OAI.Analysis.BiholderTransport.Regularity.OriginalCenterLimit +OAI.Analysis.BiholderTransport.Regularity.OriginalOuterLimit +OAI.Analysis.BiholderTransport.Regularity.OuterBounds +OAI.Analysis.BiholderTransport.Regularity.OuterDetCompact +OAI.Analysis.BiholderTransport.Regularity.OuterIntrinsicDet +OAI.Analysis.BiholderTransport.Regularity.OuterIntrinsicSecond +OAI.Analysis.BiholderTransport.Regularity.OuterSplitLowerTest +OAI.Analysis.BiholderTransport.Regularity.OuterTemplate +OAI.Analysis.BiholderTransport.Regularity.OuterTemplatePrimitive +OAI.Analysis.BiholderTransport.Regularity.OuterVelocityFactorNonneg +OAI.Analysis.BiholderTransport.Regularity.OutwardClosed +OAI.Analysis.BiholderTransport.Regularity.OutwardWeightCap +OAI.Analysis.BiholderTransport.Regularity.ParametricActive +OAI.Analysis.BiholderTransport.Regularity.ParametricLowerSequence +OAI.Analysis.BiholderTransport.Regularity.PosSemidefApplyInner +OAI.Analysis.BiholderTransport.Regularity.PrefixAction +OAI.Analysis.BiholderTransport.Regularity.PullbackDet +OAI.Analysis.BiholderTransport.Regularity.RayAnchor +OAI.Analysis.BiholderTransport.Regularity.ReciprocalInverses +OAI.Analysis.BiholderTransport.Regularity.RestrictedTransform +OAI.Analysis.BiholderTransport.Regularity.Reversal +OAI.Analysis.BiholderTransport.Regularity.ReverseRegular +OAI.Analysis.BiholderTransport.Regularity.RiemannianMetricSegment +OAI.Analysis.BiholderTransport.Regularity.RoughLinear +OAI.Analysis.BiholderTransport.Regularity.SampleCenterFamilies +OAI.Analysis.BiholderTransport.Regularity.SecondFderivAdd +OAI.Analysis.BiholderTransport.Regularity.SecondFderivCompLinear +OAI.Analysis.BiholderTransport.Regularity.SecondScaled +OAI.Analysis.BiholderTransport.Regularity.ShortForward +OAI.Analysis.BiholderTransport.Regularity.ShortSelectorNonsingularity +OAI.Analysis.BiholderTransport.Regularity.SingularValuesBound +OAI.Analysis.BiholderTransport.Regularity.SmallAffineTimeTube +OAI.Analysis.BiholderTransport.Regularity.SmallEpsilon +OAI.Analysis.BiholderTransport.Regularity.SplitEndpointCost +OAI.Analysis.BiholderTransport.Regularity.SplitSelection +OAI.Analysis.BiholderTransport.Regularity.StationaryPullback +OAI.Analysis.BiholderTransport.Regularity.TemplateRightWeight +OAI.Analysis.BiholderTransport.Regularity.TrialBlowup +OAI.Analysis.BiholderTransport.Regularity.TrueCenterGain +OAI.Analysis.BiholderTransport.Regularity.TrueCenterLimit +OAI.Analysis.BiholderTransport.Regularity.UniformFiniteGrowth +OAI.Analysis.BiholderTransport.Regularity.UniformIntervalCrossing +OAI.Analysis.BiholderTransport.Regularity.UniformMiddle +OAI.Analysis.BiholderTransport.Regularity.UniformMixedBound +OAI.Analysis.BiholderTransport.Regularity.UniformShortMinima +OAI.Analysis.BiholderTransport.Regularity.UniformTestDet +OAI.Analysis.BiholderTransport.Regularity.UnitTime +OAI.Analysis.BiholderTransport.Volume.AESelection +OAI.Analysis.BiholderTransport.Volume.AemeasurableAeContinuous +OAI.Analysis.BiholderTransport.Volume.ChartJacobianBounds +OAI.Analysis.BiholderTransport.Volume.ContactJacobianMeasure +OAI.Analysis.BiholderTransport.Volume.DensityBounds +OAI.Analysis.BiholderTransport.Volume.DensityOriginalJets +OAI.Analysis.BiholderTransport.Volume.DiagonalKernel +OAI.Analysis.BiholderTransport.Volume.EuclideanVolumeFactorNe +OAI.Analysis.BiholderTransport.Volume.ExponentialJacobian +OAI.Analysis.BiholderTransport.Volume.IntrinsicJacobian +OAI.Analysis.BiholderTransport.Volume.JensenNullPullback +OAI.Analysis.BiholderTransport.Volume.LocalCharts +OAI.Analysis.BiholderTransport.Volume.LocalJacobianBarrier +OAI.Analysis.BiholderTransport.Volume.Measurable +OAI.Analysis.BiholderTransport.Volume.MeasurableFullSubset +OAI.Analysis.BiholderTransport.Volume.MeasureContacts +OAI.Analysis.BiholderTransport.Volume.OriginalNullSet +OAI.Analysis.BiholderTransport.Volume.OutwardSpectrum +OAI.Analysis.BiholderTransport.Volume.RadialCalibration +OAI.Analysis.BiholderTransport.Volume.RadialNull +OAI.Analysis.BiholderTransport.Volume.ReversedRadial +OAI.Analysis.BiholderTransport.Volume.RiemannianCalibration +OAI.Analysis.BiholderTransport.Volume.SpectralDeterminants +OAI.Analysis.BiholderTransport.Volume.UniformCharts +OAI.Analysis.BiholderTransport.Volume.UniformExpJacobian +OAI.Analysis.BiholderTransport.Volume.UniformJacobian +OAI.Analysis.BiholderTransport.Volume.UpperJacobianBarrier diff --git a/tasks/biholder-transport/solution/reference.py b/tasks/biholder-transport/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/biholder-transport/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/biholder-transport/solution/solve.sh b/tasks/biholder-transport/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e1e739a5669a743b96d304cd57bc366a39de90ce --- /dev/null +++ b/tasks/biholder-transport/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BiholderTransport, i.e. module OAI.Analysis.BiholderTransport.Main and the +# 645 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BiholderTransport.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BiholderTransport" diff --git a/tasks/biholder-transport/task.toml b/tasks/biholder-transport/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..baf1277d06aa5198d0df0041a2b5eacee29e5966 --- /dev/null +++ b/tasks/biholder-transport/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/biholder-transport" +version = "1.0.0" +description = "Prove BiholderTransport (openai/math family 360: Villani’s convexity conjecture and regular optimal transport) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BiholderTransport.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BiholderTransport" +family = "360" +family_title = "Villani’s convexity conjecture and regular optimal transport" +subject = "Differential geometry" +theorems = ["OAI.WeakMTWTransport.uniform_biHolder_transport"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BiholderTransport.Main" +reference_modules = 645 +reference_lean_bytes = 3202559 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3094 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14582 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/biholder-transport/tests/Challenge.lean b/tasks/biholder-transport/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4f16cf778cb4550c5e0eba3d05c425b09248dcfc --- /dev/null +++ b/tasks/biholder-transport/tests/Challenge.lean @@ -0,0 +1,127 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory Manifold Bundle +open scoped ContDiff Manifold ENNReal NNReal Topology + +namespace WeakMTWTransport + +abbrev Model (n : ℕ) := EuclideanSpace ℝ (Fin n) + +section MetricDefinitions + +variable {M : Type*} [MetricSpace M] + +/-- Squared-distance cost with factor one half. -/ +def cost (x y : M) : ℝ := dist x y ^ 2 / 2 + +/-- Calibration of Hausdorff measure to Euclidean volume. -/ +def euclideanVolumeFactor (n : ℕ) : ℝ≥0∞ := + volume (Metric.ball (0 : Model n) 1) / + (Measure.hausdorffMeasure (n : ℝ) : Measure (Model n)) + (Metric.ball (0 : Model n) 1) + +variable [MeasurableSpace M] + +/-- Riemannian volume calibrated to Lebesgue measure in Euclidean space. -/ +def metricVolume [BorelSpace M] (n : ℕ) : Measure M := + euclideanVolumeFactor n • Measure.hausdorffMeasure (n : ℝ) + +/-- Almost-everywhere measurable probability densities between fixed bounds. -/ +def AdmissibleDensity (vol : Measure M) (lam cap : ℝ) (rho : M → ℝ) : Prop := + AEMeasurable rho vol ∧ Integrable rho vol ∧ + (∫ x, rho x ∂vol) = 1 ∧ (∀ᵐ x ∂vol, lam ≤ rho x ∧ rho x ≤ cap) + +/-- Multiplication by a density, ignoring exceptional negative values on null sets. -/ +def densityMeasure (vol : Measure M) (rho : M → ℝ) : Measure M := + vol.withDensity (fun x => ENNReal.ofReal (rho x)) + +/-- Optimality for the Monge minimization problem. -/ +def IsOptimalMap (vol : Measure M) (rho0 rho1 : M → ℝ) (T : M → M) : Prop := + Measurable T ∧ Measure.map T (densityMeasure vol rho0) = densityMeasure vol rho1 ∧ + ∀ S : M → M, Measurable S → + Measure.map S (densityMeasure vol rho0) = densityMeasure vol rho1 → + (∫ x, cost x (T x) * rho0 x ∂vol) ≤ + (∫ x, cost x (S x) * rho0 x ∂vol) + +/-- The two global estimates have the very same exponent and constant. -/ +def BiHolderEstimate (alpha C : ℝ) (T : M ≃ₜ M) : Prop := + (∀ x x', dist (T x) (T x') ≤ C * (dist x x') ^ alpha) ∧ + (∀ y y', dist (T.symm y) (T.symm y') ≤ C * (dist y y') ^ alpha) + +end MetricDefinitions + +section RiemannianDefinitions + +variable {n : ℕ} {M : Type*} [MetricSpace M] [ChartedSpace (Model n) M] + [IsManifold 𝓘(ℝ, Model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + +/-- Complete affinely parametrized geodesic with prescribed initial tangent. +Local metric minimization is an intrinsic definition of Riemannian geodesics. -/ +def IsGeodesicWithInitialData (x : M) (v : TangentSpace 𝓘(ℝ, Model n) x) + (gamma : ℝ → M) : Prop := + ContMDiff 𝓘(ℝ, ℝ) 𝓘(ℝ, Model n) ∞ gamma ∧ + (⟨gamma 0, mfderiv 𝓘(ℝ, ℝ) 𝓘(ℝ, Model n) gamma 0 (1 : ℝ)⟩ : + TangentBundle 𝓘(ℝ, Model n) M) = ⟨x, v⟩ ∧ + ∀ t : ℝ, ∃ eps : ℝ, 0 < eps ∧ + ∀ s u : ℝ, |s - t| < eps → |u - t| < eps → + dist (gamma s) (gamma u) = |s - u| * ‖v‖ + +/-- Evaluation at time one of the geodesic determined by initial data. -/ +def riemannianExp (x : M) (v : TangentSpace 𝓘(ℝ, Model n) x) : M := by + classical + exact if h : ∃ gamma, IsGeodesicWithInitialData x v gamma then (Classical.choose h) 1 else x + +/-- The open injectivity domain, defined by extendible minimizing vectors. -/ +def injectivityDomain (x : M) : Set (TangentSpace 𝓘(ℝ, Model n) x) := + {p | ∃ a : ℝ, 1 < a ∧ dist x (riemannianExp x (a • p)) = a * ‖p‖} + +/-- The Ma–Trudinger–Wang fourth derivative with factor -3/2. -/ +def mtw (x : M) (p xi eta : TangentSpace 𝓘(ℝ, Model n) x) : ℝ := + -(3 / 2 : ℝ) * + iteratedDeriv 2 (fun s : ℝ => + iteratedDeriv 2 (fun t : ℝ => + cost (riemannianExp x (t • xi)) (riemannianExp x (p + s • eta))) 0) 0 + +/-- Weak MTW only at interior velocities and only for orthogonal test vectors. -/ +def WeakMTW : Prop := + ∀ (x : M) (p : TangentSpace 𝓘(ℝ, Model n) x), p ∈ injectivityDomain x → + ∀ xi eta : TangentSpace 𝓘(ℝ, Model n) x, + inner ℝ xi eta = 0 → 0 ≤ mtw x p xi eta + +end RiemannianDefinitions + +/-- Uniform bi-Hölder optimal transport for all densities between fixed bounds +on a compact connected smooth Riemannian manifold satisfying weak MTW. -/ +theorem uniform_biHolder_transport + {n : ℕ} (hn : 2 ≤ n) {M : Type*} + [MetricSpace M] [CompactSpace M] [ConnectedSpace M] + [ChartedSpace (Model n) M] [IsManifold 𝓘(ℝ, Model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + [IsContMDiffRiemannianBundle 𝓘(ℝ, Model n) ∞ (Model n) + (fun x : M => TangentSpace 𝓘(ℝ, Model n) x)] + [IsRiemannianManifold 𝓘(ℝ, Model n) M] + [MeasurableSpace M] [BorelSpace M] + (hmtw : WeakMTW (n := n) (M := M)) + (lam cap : ℝ) (hlam : 0 < lam) (hcap : lam ≤ cap) + (hclass : ∃ rho : M → ℝ, AdmissibleDensity (metricVolume n) lam cap rho) : + ∃ alpha C : ℝ, 0 < alpha ∧ alpha ≤ 1 ∧ 0 ≤ C ∧ + ∀ rho0 rho1 : M → ℝ, + AdmissibleDensity (metricVolume n) lam cap rho0 → + AdmissibleDensity (metricVolume n) lam cap rho1 → + ∃ T : M ≃ₜ M, + IsOptimalMap (metricVolume n) rho0 rho1 T ∧ + (∀ S : M → M, IsOptimalMap (metricVolume n) rho0 rho1 S → + S =ᵐ[densityMeasure (metricVolume n) rho0] T) ∧ + BiHolderEstimate alpha C T := by + sorry + +end WeakMTWTransport + +end + +end OAI diff --git a/tasks/biholder-transport/tests/grade.py b/tasks/biholder-transport/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/biholder-transport/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/biholder-transport/tests/task.json b/tasks/biholder-transport/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..086d5fe529eddb09ff580758c4cdb703f84ebe5d --- /dev/null +++ b/tasks/biholder-transport/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BiholderTransport", + "comparator": { + "theorem_names": [ + "OAI.WeakMTWTransport.uniform_biHolder_transport" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13682 +} \ No newline at end of file diff --git a/tasks/biholder-transport/tests/test.sh b/tasks/biholder-transport/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/biholder-transport/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bin-packing-gap/environment/Dockerfile b/tasks/bin-packing-gap/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bin-packing-gap/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bin-packing-gap/environment/fetch_mathlib.sh b/tasks/bin-packing-gap/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bin-packing-gap/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bin-packing-gap/environment/lake-manifest.json b/tasks/bin-packing-gap/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bin-packing-gap/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bin-packing-gap/environment/lakefile.lean b/tasks/bin-packing-gap/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bin-packing-gap/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bin-packing-gap/environment/lean_setup.sh b/tasks/bin-packing-gap/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bin-packing-gap/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bin-packing-gap/environment/pack_submission.py b/tasks/bin-packing-gap/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bin-packing-gap/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bin-packing-gap/instruction.md b/tasks/bin-packing-gap/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d7412ea8a0d19b64883079723eea610397071b2f --- /dev/null +++ b/tasks/bin-packing-gap/instruction.md @@ -0,0 +1,429 @@ +# openai/math challenge `BinPackingGap` (family 118) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 118 of the release, *Unbounded bin-packing gaps and the modified integer round-up conjecture* +(Theoretical computer science). The family as a whole: Disproves the modified integer round-up conjecture of Scheithauer and Terno: the integral bin-packing optimum can exceed its configuration linear-programming value by an arbitrarily large additive constant. Approximating the optimum within any fixed additive constant is also NP-hard, even when every item exceeds $1/6$ and each bin holds at most five items. + +The challenge is `BinPackingGap`, also at `/opt/openai-math/challenges/BinPackingGap.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace BinPackingGames.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +end BinPackingGames.Foundations.Complexity + +namespace BinPackingGames.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end BinPackingGames.Foundations.Complexity.MachineFiniteAlphabet + +namespace BinPackingGames.Foundations.Complexity.CookLevin + +def pairBits (input : List Bool × List Bool) : List Bool := + encodeWord input.1.length ++ input.1 ++ input.2 + +structure NPVerifier where + witnessBound : Polynomial Nat + verify : (List Bool × List Bool) → Bool + computation : Turing.TM2ComputableInPolyTime pairBits (fun bit => [bit]) verify + finiteAlphabet : (k : computation.tm.K) → Fintype (computation.tm.Γ k) + +def NPVerifier.Accepts (verifier : NPVerifier) (input : List Bool) : Prop := + ∃ witness : List Bool, + witness.length ≤ verifier.witnessBound.eval input.length ∧ + verifier.verify (input, witness) = true + +def InNP (language : List Bool → Prop) : Prop := + ∃ verifier : NPVerifier, ∀ input, language input ↔ verifier.Accepts input + +end BinPackingGames.Foundations.Complexity.CookLevin + +namespace BinPackingCompleteness.BinaryEncoding + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +end BinPackingCompleteness.BinaryEncoding + +namespace BinPackingGap + +open scoped BigOperators + +structure Instance where + n : ℕ + size : Fin n → ℚ + size_pos : ∀ i, 0 < size i + size_le_one : ∀ i, size i ≤ 1 + +namespace Instance + +abbrev Item (I : Instance) := Fin I.n + +end Instance + +structure Packing (I : Instance) (b : ℕ) where + assignment : I.Item → Fin b + capacity : ∀ j, (∑ i, if assignment i = j then I.size i else 0) ≤ 1 + +def HasPacking (I : Instance) (b : ℕ) : Prop := Nonempty (Packing I b) + +def singletonPacking (I : Instance) : Packing I I.n where + assignment i := i + capacity j := by + have hsum : (∑ i, if i = j then I.size i else 0) = I.size j := by + calc + (∑ i, if i = j then I.size i else 0) = + (if j = j then I.size j else 0) := + Finset.sum_eq_single j (fun i _ hij => ite_eq_right hij) + (fun h => False.elim (h (Finset.mem_univ _))) + _ = I.size j := ite_eq_left rfl + rw [hsum] + exact I.size_le_one j + +theorem exists_packing (I : Instance) : ∃ b, HasPacking I b := + ⟨I.n, ⟨singletonPacking I⟩⟩ + +noncomputable def opt (I : Instance) : ℕ := by + classical + exact Nat.find (exists_packing I) + +def IndividualConfiguration (I : Instance) := + {H : Finset I.Item // ∑ i ∈ H, I.size i ≤ 1} + +noncomputable instance (I : Instance) : Fintype (IndividualConfiguration I) := + inferInstanceAs (Fintype {H : Finset I.Item // ∑ i ∈ H, I.size i ≤ 1}) + +def NumericalSize (I : Instance) := ↥(Finset.univ.image I.size) + +instance (I : Instance) : Fintype (NumericalSize I) := + inferInstanceAs (Fintype ↥(Finset.univ.image I.size)) + +namespace NumericalSize + +variable {I : Instance} + +theorem positive (s : NumericalSize I) : 0 < s.val := by + obtain ⟨i, _, hi⟩ := Finset.mem_image.mp s.property + rw [← hi] + exact I.size_pos i + +def multiplicity (s : NumericalSize I) : ℕ := + (Finset.univ.filter fun i : I.Item => I.size i = s.val).card + +def capacityBound (s : NumericalSize I) : ℕ := + Classical.choose (exists_nat_gt (1 / s.val)) + +theorem capacityBound_spec (s : NumericalSize I) : 1 / s.val < (s.capacityBound : ℚ) := + Classical.choose_spec (exists_nat_gt (1 / s.val)) + +end NumericalSize + +def TypeConfiguration (I : Instance) := + {c : NumericalSize I → ℕ // ∑ s, s.val * (c s : ℚ) ≤ 1} + +namespace TypeConfiguration + +variable {I : Instance} + +theorem count_lt_bound (c : TypeConfiguration I) (s : NumericalSize I) : + c.val s < s.capacityBound := by + have hterm : s.val * (c.val s : ℚ) ≤ ∑ t, t.val * (c.val t : ℚ) := by + exact Finset.single_le_sum (fun t _ => mul_nonneg (le_of_lt t.positive) (Nat.cast_nonneg _)) + (Finset.mem_univ s) + have hquot : (c.val s : ℚ) ≤ 1 / s.val := by + apply (le_div_iff₀ s.positive).mpr + simpa [mul_comm] using hterm.trans c.property + have hlt := hquot.trans_lt s.capacityBound_spec + exact_mod_cast hlt + +def boundedCounts (c : TypeConfiguration I) : ∀ s : NumericalSize I, Fin s.capacityBound := + fun s => ⟨c.val s, c.count_lt_bound s⟩ + +theorem boundedCounts_injective : + Function.Injective + (boundedCounts : TypeConfiguration I → ∀ s : NumericalSize I, Fin s.capacityBound) := by + intro c d h + apply Subtype.ext + funext s + exact congrArg Fin.val (congrFun h s) + +instance : Finite (TypeConfiguration I) := by + classical + exact Finite.of_injective boundedCounts boundedCounts_injective + +instance : Fintype (TypeConfiguration I) := Fintype.ofFinite _ + +end TypeConfiguration + +namespace FractionalCover + +open Set +variable {I C : Type*} [Fintype I] [Fintype C] + +def Feasible (a : C → I → ℝ) (d : I → ℝ) (w : C → ℝ) : Prop := + (∀ c, 0 ≤ w c) ∧ ∀ i, d i ≤ ∑ c, a c i * w c + +def objective (w : C → ℝ) : ℝ := ∑ c, w c + +def objectiveSet (a : C → I → ℝ) (d : I → ℝ) : Set ℝ := + {v | ∃ w, Feasible a d w ∧ objective w = v} + +def value (a : C → I → ℝ) (d : I → ℝ) : ℝ := + sInf (objectiveSet a d) + +end FractionalCover + +def individualMatrix (I : Instance) (H : IndividualConfiguration I) (i : I.Item) : ℝ := + if i ∈ H.val then 1 else 0 + +def individualLP (I : Instance) : ℝ := + FractionalCover.value (individualMatrix I) (fun _ => 1) + +def typeMatrix (I : Instance) (c : TypeConfiguration I) (s : NumericalSize I) : ℝ := + c.val s + +def typeLP (I : Instance) : ℝ := + FractionalCover.value (typeMatrix I) (fun s => (s.multiplicity : ℝ)) + +abbrev RawInstance := List (ℕ × ℕ) + +abbrev RawReductionOutput := ℕ × RawInstance + +namespace RawInstance + +def Valid (r : RawInstance) : Prop := + ∀ q ∈ r, 0 < q.1 ∧ q.1 ≤ q.2 + +def ratValue (q : ℕ × ℕ) : ℚ := (q.1 : ℚ) / (q.2 : ℚ) + +theorem den_pos {r : RawInstance} (hr : r.Valid) {q : ℕ × ℕ} (hq : q ∈ r) : + 0 < q.2 := lt_of_lt_of_le (hr q hq).1 (hr q hq).2 + +def toInstance (r : RawInstance) (hr : r.Valid) : Instance where + n := r.length + size i := ratValue (r.get i) + size_pos i := div_pos (Nat.cast_pos.mpr (hr _ (List.get_mem r i)).1) + (Nat.cast_pos.mpr (den_pos hr (List.get_mem r i))) + size_le_one i := (div_le_one₀ (Nat.cast_pos.mpr (den_pos hr (List.get_mem r i)))).mpr + (Nat.cast_le.mpr (hr _ (List.get_mem r i)).2) + +end RawInstance + +structure RawPacking where + bins : ℕ + assignments : List ℕ + +namespace RawPacking + +def load (r : RawInstance) (a : List ℕ) (j : ℕ) : ℚ := + ((r.zip a).map fun qa => + if qa.2 = j then RawInstance.ratValue qa.1 else 0).sum + +def Feasible (r : RawInstance) (p : RawPacking) : Prop := + p.assignments.length = r.length ∧ + (∀ j ∈ p.assignments, j < p.bins) ∧ + ∀ j < p.bins, load r p.assignments j ≤ 1 + +end RawPacking + +namespace BinaryEncoding + +abbrev natBits := BinPackingCompleteness.BinaryEncoding.nameBits + +abbrev parseNat := BinPackingCompleteness.BinaryEncoding.parseName + +def listBits {α : Type} (encode : α → List Bool) : List α → List Bool + | [] => [false] + | a :: rest => true :: (encode a ++ listBits encode rest) + +def pairBits {α β : Type} (ea : α → List Bool) (eb : β → List Bool) + (p : α × β) : List Bool := ea p.1 ++ eb p.2 + +def optionBits {α : Type} (encode : α → List Bool) : Option α → List Bool + | none => [false] + | some a => true :: encode a + +abbrev Parser (α : Type) := List Bool → Option (α × List Bool) + +def parsePair {α β : Type} (pa : Parser α) (pb : Parser β) : Parser (α × β) := + fun input => do + let (a, rest) ← pa input + let (b, suffix) ← pb rest + return ((a, b), suffix) + +def parseListAux {α : Type} (parse : Parser α) : Nat → Parser (List α) + | 0, _ => none + | _ + 1, [] => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: rest => do + let (a, rest) ← parse rest + let (as, suffix) ← parseListAux parse fuel rest + return (a :: as, suffix) + +def parseList {α : Type} (parse : Parser α) : Parser (List α) := + fun input => parseListAux parse input.length input + +def decode {α : Type} (parse : Parser α) (input : List Bool) : Option α := do + let (a, rest) ← parse input + if rest.isEmpty then some a else none + +def rawInstanceBits (r : RawInstance) : List Bool := + listBits (pairBits natBits natBits) r + +def assignmentBits (a : List Nat) : List Bool := listBits natBits a + +def rawPackingBits (p : RawPacking) : List Bool := + natBits p.bins ++ assignmentBits p.assignments + +def packingResultBits (p : Option RawPacking) : List Bool := optionBits rawPackingBits p + +def rawReductionOutputBits (out : RawReductionOutput) : List Bool := + natBits out.1 ++ rawInstanceBits out.2 + +def parseRawInstance : Parser RawInstance := parseList (parsePair parseNat parseNat) + +def decodeRawInstance := decode parseRawInstance + +end BinaryEncoding + +section + +open Turing BinPackingGames.Foundations.Complexity + +abbrev BitLanguage := List Bool → Prop + +def InP (L : BitLanguage) : Prop := + ∃ decider : List Bool → Bool, + ∃ computation : TM2ComputableInPolyTime + (id : List Bool → List Bool) (fun b => [b]) decider, + MachineFiniteAlphabet.FiniteAlphabet computation.tm ∧ + ∀ x, L x ↔ decider x = true + +def ClassP : Set BitLanguage := {L | InP L} + +def ClassNP : Set BitLanguage := {L | CookLevin.InNP L} + +def PEqualsNP : Prop := ClassP = ClassNP + +structure AbsoluteAdditiveAlgorithm (c : Nat) where + run : List Bool → Option RawPacking + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + BinaryEncoding.packingResultBits run + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + guarantee : ∀ (r : RawInstance) (hr : r.Valid), ∃ p : RawPacking, + run (BinaryEncoding.rawInstanceBits r) = some p ∧ + RawPacking.Feasible r p ∧ p.bins ≤ opt (r.toInstance hr) + c + +structure PackingGapReduction (c : Nat) (L : BitLanguage) where + reduce : List Bool → RawReductionOutput + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + BinaryEncoding.rawReductionOutputBits reduce + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + valid : ∀ x, (reduce x).2.Valid + itemCount : ∀ x, (reduce x).2.length = 5 * (reduce x).1 + itemLower : ∀ x i, + (1 / 6 : ℚ) < ((reduce x).2.toInstance (valid x)).size i + completeness : ∀ x, L x → + HasPacking ((reduce x).2.toInstance (valid x)) (reduce x).1 + soundness : ∀ x, ¬L x → + ¬HasPacking ((reduce x).2.toInstance (valid x)) ((reduce x).1 + c) + +def PackingGapNPHard (c : Nat) : Prop := + ∀ L : BitLanguage, CookLevin.InNP L → Nonempty (PackingGapReduction c L) + +end + +theorem main_results : + (∀ c : ℕ, ∃ I : Instance, ∃ B : ℕ, + I.n = 5 * B ∧ + (∀ i, (1 / 6 : ℚ) < I.size i ∧ I.size i < 1) ∧ + B + c < opt I ∧ individualLP I = (B : ℝ) ∧ typeLP I = (B : ℝ)) ∧ + (∀ c : Nat, PackingGapNPHard c) ∧ + ((∃ c : Nat, Nonempty (AbsoluteAdditiveAlgorithm c)) ↔ PEqualsNP) ∧ + (PEqualsNP → ∃ algorithm : AbsoluteAdditiveAlgorithm 0, + (∀ (items : RawInstance) (valid : items.Valid), ∃ packing : RawPacking, + algorithm.run (BinaryEncoding.rawInstanceBits items) = some packing ∧ + packing.Feasible items ∧ packing.bins = opt (items.toInstance valid)) ∧ + algorithm.run (BinaryEncoding.rawInstanceBits []) = some ⟨0, []⟩ ∧ + (∀ input : List Bool, BinaryEncoding.decodeRawInstance input = none → + algorithm.run input = none) ∧ + (∀ items : RawInstance, ¬ items.Valid → + algorithm.run (BinaryEncoding.rawInstanceBits items) = none)) := by + sorry + +end BinPackingGap + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BinPackingGap.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BinPackingGap.main_results` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bin-packing-gap/solution/closure.txt b/tasks/bin-packing-gap/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d3f59c7c9ec635e5e00cb695befff142dcb8ae1b --- /dev/null +++ b/tasks/bin-packing-gap/solution/closure.txt @@ -0,0 +1,284 @@ +OAI.Computability.BinPacking.Arithmetic.BinaryOrderMachine +OAI.Computability.BinPacking.Arithmetic.BinaryPowerMachine +OAI.Computability.BinPacking.Arithmetic.BinaryTallyMachine +OAI.Computability.BinPacking.Arithmetic.BinaryToTallyMachine +OAI.Computability.BinPacking.Arithmetic.GraphPackingRegisters +OAI.Computability.BinPacking.Arithmetic.GraphTallyMachine +OAI.Computability.BinPacking.Arithmetic.NatExpression +OAI.Computability.BinPacking.Arithmetic.NatExpressionBounds +OAI.Computability.BinPacking.Arithmetic.NatExpressionBranch +OAI.Computability.BinPacking.Arithmetic.PackingRegisterFrame +OAI.Computability.BinPacking.Arithmetic.PackingRegisterUpdate +OAI.Computability.BinPacking.Arithmetic.ResetExpressionCompiler +OAI.Computability.BinPacking.Computation.FinalCNFCleanup +OAI.Computability.BinPacking.Computation.FinalCNFRowPlan +OAI.Computability.BinPacking.Computation.FinalCNFRowTrace +OAI.Computability.BinPacking.Computation.GraphCounterStart +OAI.Computability.BinPacking.Computation.GraphIterationBounds +OAI.Computability.BinPacking.Computation.Machine +OAI.Computability.BinPacking.Computation.MachineCanonicalOutput +OAI.Computability.BinPacking.Computation.MachineCeilingPower +OAI.Computability.BinPacking.Computation.MachineCloudPadding +OAI.Computability.BinPacking.Computation.MachineCloudPrefix +OAI.Computability.BinPacking.Computation.MachineCloudRank +OAI.Computability.BinPacking.Computation.MachineCloudSelect +OAI.Computability.BinPacking.Computation.MachineExpanderFamilyAffine +OAI.Computability.BinPacking.Computation.MachineExpanderFamilyBoundary +OAI.Computability.BinPacking.Computation.MachineExpanderRowDivision +OAI.Computability.BinPacking.Computation.MachineExpanderRowEmit +OAI.Computability.BinPacking.Computation.MachineExpanderTable +OAI.Computability.BinPacking.Computation.MachineExpanderTableReverse +OAI.Computability.BinPacking.Computation.MachineFiniteAlphabet +OAI.Computability.BinPacking.Computation.MachineFiniteTable +OAI.Computability.BinPacking.Computation.MachineHorner +OAI.Computability.BinPacking.Computation.MachineInitialHeaders +OAI.Computability.BinPacking.Computation.MachineLazyRows +OAI.Computability.BinPacking.Computation.MachineLazyTableRuntime +OAI.Computability.BinPacking.Computation.MachineOverlayRows +OAI.Computability.BinPacking.Computation.MachineOverlayTable +OAI.Computability.BinPacking.Computation.MachinePaddedExpanderFamily +OAI.Computability.BinPacking.Computation.MachinePaddedOverlayRuntime +OAI.Computability.BinPacking.Computation.MachinePortReindex +OAI.Computability.BinPacking.Computation.MachineRegularDummyRow +OAI.Computability.BinPacking.Computation.MachineRegularExecutionBounds +OAI.Computability.BinPacking.Computation.MachineRegularInternalRow +OAI.Computability.BinPacking.Computation.MachineRegularOwnerBodyBounds +OAI.Computability.BinPacking.Computation.MachineRegularOwnerProgram +OAI.Computability.BinPacking.Computation.MachineRegularTable +OAI.Computability.BinPacking.Computation.MachineRegularTableRuntime +OAI.Computability.BinPacking.Computation.MachineRegularVertexBlock +OAI.Computability.BinPacking.Computation.MachineUnaryEqualityBit +OAI.Computability.BinPacking.Computation.MachineUnaryLessAt +OAI.Computability.BinPacking.Computation.MachineVertexPadding +OAI.Computability.BinPacking.Computation.PoweringGlobalEnumeration +OAI.Computability.BinPacking.Computation.PoweringMachineRow +OAI.Computability.BinPacking.Computation.PoweringMachineRowBody +OAI.Computability.BinPacking.Computation.PoweringMachineRuntime +OAI.Computability.BinPacking.Computation.PoweringMasterState +OAI.Computability.BinPacking.Computation.TableIterationFiniteAlphabet +OAI.Computability.BinPacking.Configurations.ConfigurationLP +OAI.Computability.BinPacking.Configurations.CoverageSoundness +OAI.Computability.BinPacking.Configurations.K4Soundness +OAI.Computability.BinPacking.Configurations.ReductionCompleteness +OAI.Computability.BinPacking.Configurations.ReductionFractional +OAI.Computability.BinPacking.CookLevin.BoundedExecution +OAI.Computability.BinPacking.CookLevin.Bounds +OAI.Computability.BinPacking.CookLevin.CellsTokensAlignment +OAI.Computability.BinPacking.CookLevin.CircuitEncodingBridge +OAI.Computability.BinPacking.CookLevin.CircuitFinish +OAI.Computability.BinPacking.CookLevin.CircuitProducer +OAI.Computability.BinPacking.CookLevin.ClashMachine +OAI.Computability.BinPacking.CookLevin.Completeness +OAI.Computability.BinPacking.CookLevin.ConfigIndex +OAI.Computability.BinPacking.CookLevin.ForestStage +OAI.Computability.BinPacking.CookLevin.InitializationMachine +OAI.Computability.BinPacking.CookLevin.InitializationMachineAt +OAI.Computability.BinPacking.CookLevin.MachineCircuit +OAI.Computability.BinPacking.CookLevin.OutputOrder +OAI.Computability.BinPacking.CookLevin.PaddingCellsMachine +OAI.Computability.BinPacking.CookLevin.PayloadPresenceMachine +OAI.Computability.BinPacking.CookLevin.PolynomialMachine +OAI.Computability.BinPacking.CookLevin.PostfixBounds +OAI.Computability.BinPacking.CookLevin.ProducerFrontStage +OAI.Computability.BinPacking.CookLevin.TermMachine +OAI.Computability.BinPacking.CookLevin.TransitionArena +OAI.Computability.BinPacking.CookLevin.TransitionIteration +OAI.Computability.BinPacking.CookLevin.TransitionIterationTime +OAI.Computability.BinPacking.CookLevin.ValidityComposition +OAI.Computability.BinPacking.CookLevin.ValidityMachine +OAI.Computability.BinPacking.CookLevin.VerifierCircuit +OAI.Computability.BinPacking.CookLevin.VerifierFront +OAI.Computability.BinPacking.Expanders.ExpanderTableEnumeration +OAI.Computability.BinPacking.Expanders.LazySmoothing +OAI.Computability.BinPacking.Expanders.PreprocessingTableSpectral +OAI.Computability.BinPacking.Expanders.SpectralCut +OAI.Computability.BinPacking.Expanders.ZigzagSpectral +OAI.Computability.BinPacking.Games.AlphabetBudget +OAI.Computability.BinPacking.Games.GameConditioning +OAI.Computability.BinPacking.Games.Holenstein +OAI.Computability.BinPacking.Games.LocalSimulation +OAI.Computability.BinPacking.Games.ProfileCorrection +OAI.Computability.BinPacking.Games.QuestionMarginal +OAI.Computability.BinPacking.Games.Reindexing +OAI.Computability.BinPacking.Games.RepetitionUpper +OAI.Computability.BinPacking.Games.SelectedProfiles +OAI.Computability.BinPacking.Hardness.LiteralSlotGraph +OAI.Computability.BinPacking.Hardness.LiteralSlotGraphComputation +OAI.Computability.BinPacking.Hardness.LiteralSlotGraphEnumeration +OAI.Computability.BinPacking.Hardness.PCPPackingGap +OAI.Computability.BinPacking.Information.EmptyContext +OAI.Computability.BinPacking.Information.GameDecoder +OAI.Computability.BinPacking.Information.GamesAdapter +OAI.Computability.BinPacking.Information.SharedProfiles +OAI.Computability.BinPacking.Information.SideInformation +OAI.Computability.BinPacking.Information.SourceFieldArray +OAI.Computability.BinPacking.Information.SourceHonest +OAI.Computability.BinPacking.Information.SourceLoopInit +OAI.Computability.BinPacking.Information.SourceNonempty +OAI.Computability.BinPacking.Information.TraceLaw +OAI.Computability.BinPacking.Inventory.CurrentMatches +OAI.Computability.BinPacking.Inventory.EdgeLongConsumption +OAI.Computability.BinPacking.Inventory.IntegralSpeciesCounts +OAI.Computability.BinPacking.Inventory.InventoryCoverage +OAI.Computability.BinPacking.Inventory.InventoryPrefixConservation +OAI.Computability.BinPacking.Inventory.InventoryScores +OAI.Computability.BinPacking.Inventory.LabelConservation +OAI.Computability.BinPacking.Inventory.LocalCompletionCoverage +OAI.Computability.BinPacking.Inventory.PackingConstantPool +OAI.Computability.BinPacking.Inventory.PackingExclusions +OAI.Computability.BinPacking.Inventory.PackingInventoryDescriptors +OAI.Computability.BinPacking.Inventory.PhysicalPoolLift +OAI.Computability.BinPacking.Inventory.SpeciesAllocation +OAI.Computability.BinPacking.Machines.DropPackingBoundMachine +OAI.Computability.BinPacking.Machines.FrameEmitMachine +OAI.Computability.BinPacking.Machines.GraphPackingBounds +OAI.Computability.BinPacking.Machines.GraphPackingGlobalExecution +OAI.Computability.BinPacking.Machines.GraphPackingJobCleanup +OAI.Computability.BinPacking.Machines.GraphPackingJobEdge +OAI.Computability.BinPacking.Machines.GraphPackingJobList +OAI.Computability.BinPacking.Machines.GraphPackingMachine +OAI.Computability.BinPacking.Machines.GraphPackingOutput +OAI.Computability.BinPacking.Machines.GraphPackingPreparation +OAI.Computability.BinPacking.Machines.GraphPackingPreparationFinish +OAI.Computability.BinPacking.Machines.GraphPackingStockStreams +OAI.Computability.BinPacking.Machines.GraphPackingVerticesBound +OAI.Computability.BinPacking.Machines.IntegerPackingArithmetic +OAI.Computability.BinPacking.Machines.MachineBoundedIteration +OAI.Computability.BinPacking.Machines.MachineControlEmbedding +OAI.Computability.BinPacking.Machines.MachineKeepDecisionTyped +OAI.Computability.BinPacking.Machines.PackingCountMachine +OAI.Computability.BinPacking.Machines.PackingCountedProgram +OAI.Computability.BinPacking.Machines.PackingJobCoverage +OAI.Computability.BinPacking.Machines.PackingJobLoop +OAI.Computability.BinPacking.Machines.PackingPoolMachine +OAI.Computability.BinPacking.Machines.PackingPowerProgram +OAI.Computability.BinPacking.Machines.PackingSetupGraph +OAI.Computability.BinPacking.Machines.PackingVertexUpdate +OAI.Computability.BinPacking.Main +OAI.Computability.BinPacking.Model +OAI.Computability.BinPacking.PCP.AlphabetRetraction +OAI.Computability.BinPacking.PCP.BinaryFormula +OAI.Computability.BinPacking.PCP.BinaryOccurrenceRename +OAI.Computability.BinPacking.PCP.Cleanup +OAI.Computability.BinPacking.PCP.CloudRounding +OAI.Computability.BinPacking.PCP.CompareLoop +OAI.Computability.BinPacking.PCP.Emitter +OAI.Computability.BinPacking.PCP.FinalBooleanVerifier +OAI.Computability.BinPacking.PCP.FinalConstants +OAI.Computability.BinPacking.PCP.FiniteGraph +OAI.Computability.BinPacking.PCP.GraphTransport +OAI.Computability.BinPacking.PCP.Initialization +OAI.Computability.BinPacking.PCP.Lookup +OAI.Computability.BinPacking.PCP.MachineRawInitialTable +OAI.Computability.BinPacking.PCP.NormalizationEmitMachine +OAI.Computability.BinPacking.PCP.NormalizationLoopMachine +OAI.Computability.BinPacking.PCP.NormalizationMachine +OAI.Computability.BinPacking.PCP.NormalizationReadMachine +OAI.Computability.BinPacking.PCP.OccurrenceGame +OAI.Computability.BinPacking.PCP.PCPIteration +OAI.Computability.BinPacking.PCP.PCPSource +OAI.Computability.BinPacking.PCP.PCPSourceHardness +OAI.Computability.BinPacking.PCP.PoweringEnumeration +OAI.Computability.BinPacking.PCP.PoweringFieldPlan +OAI.Computability.BinPacking.PCP.PoweringFinalConstants +OAI.Computability.BinPacking.PCP.PoweringMomentBound +OAI.Computability.BinPacking.PCP.PoweringRowHeaderSemantics +OAI.Computability.BinPacking.PCP.PoweringTableLayout +OAI.Computability.BinPacking.PCP.PoweringTableSemantics +OAI.Computability.BinPacking.PCP.PreprocessingFamilyBridge +OAI.Computability.BinPacking.PCP.PreprocessingGuarantees +OAI.Computability.BinPacking.PCP.PreprocessingLazyWords +OAI.Computability.BinPacking.PCP.PreprocessingMachineBounds +OAI.Computability.BinPacking.PCP.PreprocessingOverlayWords +OAI.Computability.BinPacking.PCP.PreprocessingRegularBounds +OAI.Computability.BinPacking.PCP.PreprocessingRegularSoundness +OAI.Computability.BinPacking.PCP.Queries +OAI.Computability.BinPacking.PCP.RawInitialMachineBody +OAI.Computability.BinPacking.PCP.RawInitialMachineBudget +OAI.Computability.BinPacking.PCP.RawInitialMachineCleanup +OAI.Computability.BinPacking.PCP.RawInitialMachineFinish +OAI.Computability.BinPacking.PCP.RawInitialMachineLoop +OAI.Computability.BinPacking.PCP.RawInitialMachineLoopData +OAI.Computability.BinPacking.PCP.RawInitialMachineReadClause +OAI.Computability.BinPacking.PCP.RawInitialMachineRows +OAI.Computability.BinPacking.PCP.RawInitialPredicate +OAI.Computability.BinPacking.PCP.RoundTableGap +OAI.Computability.BinPacking.PCP.SourceAmplification +OAI.Computability.BinPacking.PCP.SourceEncoding +OAI.Computability.BinPacking.Packing.CapacityScan +OAI.Computability.BinPacking.Packing.ConstructLocalState +OAI.Computability.BinPacking.Packing.CoordinateOrder +OAI.Computability.BinPacking.Packing.ExtractedCover +OAI.Computability.BinPacking.Packing.FiniteHall +OAI.Computability.BinPacking.Packing.FractionWidth +OAI.Computability.BinPacking.Packing.GoodAnchorBound +OAI.Computability.BinPacking.Packing.ItemEnumeration +OAI.Computability.BinPacking.Packing.K4Graph +OAI.Computability.BinPacking.Packing.LiteralSlotGap +OAI.Computability.BinPacking.Packing.LocalJobCounts +OAI.Computability.BinPacking.Packing.LocalTemplateBases +OAI.Computability.BinPacking.Packing.PackingAssignments +OAI.Computability.BinPacking.Packing.PackingCoordinates +OAI.Computability.BinPacking.Packing.PackingFeasibility +OAI.Computability.BinPacking.Packing.PackingGapDefinitions +OAI.Computability.BinPacking.Packing.PackingScalar +OAI.Computability.BinPacking.Packing.PackingScalarExpression +OAI.Computability.BinPacking.Packing.PackingSelections +OAI.Computability.BinPacking.Packing.PackingTokenAffine +OAI.Computability.BinPacking.Packing.PairExpressionCompiler +OAI.Computability.BinPacking.Packing.PhaseIteration +OAI.Computability.BinPacking.Packing.PhysicalRolePacking +OAI.Computability.BinPacking.Packing.PrimaryLoss +OAI.Computability.BinPacking.Reductions.BinaryCoordinates +OAI.Computability.BinPacking.Reductions.BinaryHeaderMachine +OAI.Computability.BinPacking.Reductions.BinaryInputReduction +OAI.Computability.BinPacking.Reductions.BinaryLiteralMachine +OAI.Computability.BinPacking.Reductions.BinaryNameCompare +OAI.Computability.BinPacking.Reductions.BinaryPairMachine +OAI.Computability.BinPacking.Reductions.BinaryRenameLoop +OAI.Computability.BinPacking.Reductions.BinaryRenameWords +OAI.Computability.BinPacking.Reductions.BinaryTokenMachine +OAI.Computability.BinPacking.Reductions.BinaryTotalInputMachine +OAI.Computability.BinPacking.Reductions.BinaryValidatorMachine +OAI.Computability.BinPacking.Reductions.CloneGap +OAI.Computability.BinPacking.Reductions.FiniteNoise +OAI.Computability.BinPacking.Reductions.MachineReverse +OAI.Computability.BinPacking.Reductions.MachineSubstitution +OAI.Computability.BinPacking.Reductions.MachineTransducer +OAI.Computability.BinPacking.Reductions.MachineTransfer +OAI.Computability.BinPacking.Reductions.Target +OAI.Computability.BinPacking.Results.AdditiveHardness +OAI.Computability.BinPacking.Results.Aggregate +OAI.Computability.BinPacking.Results.AlgorithmEquivalence +OAI.Computability.BinPacking.Results.OptimalSearch +OAI.Computability.BinPacking.Results.PackingHardness +OAI.Computability.BinPacking.Results.StructuralGap +OAI.Computability.BinPacking.Search.ApproximationImpliesP +OAI.Computability.BinPacking.Search.ExtensionAgreementMachine +OAI.Computability.BinPacking.Search.ExtensionCapacityBounds +OAI.Computability.BinPacking.Search.ExtensionMachineSpace +OAI.Computability.BinPacking.Search.ExtensionPairMachine +OAI.Computability.BinPacking.Search.ExtensionShapeMachine +OAI.Computability.BinPacking.Search.ExtensionValidationMachine +OAI.Computability.BinPacking.Search.ExtensionVerifier +OAI.Computability.BinPacking.Search.ExtensionVerifierMachine +OAI.Computability.BinPacking.Search.ExtensionVerifierPipeline +OAI.Computability.BinPacking.Search.SearchFinalizeMachine +OAI.Computability.BinPacking.Search.SearchFixedReplaceMachine +OAI.Computability.BinPacking.Search.SearchInitialItemsMachine +OAI.Computability.BinPacking.Search.SearchInitialShapeMachine +OAI.Computability.BinPacking.Search.SearchInitializeEncoding +OAI.Computability.BinPacking.Search.SearchPrepareMachine +OAI.Computability.BinPacking.Search.SearchStageMachines +OAI.Computability.BinPacking.Search.SearchUpdateMachine +OAI.Computability.BinPacking.Trees.CompetingTrees +OAI.Computability.BinPacking.Trees.CompletionGeometry +OAI.Computability.BinPacking.Trees.IntegerTreeGeometry +OAI.Computability.BinPacking.Trees.InventoryFromTrees +OAI.Computability.BinPacking.Trees.InventoryRowGeometry +OAI.Computability.BinPacking.Trees.KeyGeometry +OAI.Computability.BinPacking.Trees.TestGeometry +OAI.Computability.BinPacking.Trees.TreeAttachment +OAI.Computability.BinPacking.Trees.TreeAvoidance +OAI.Computability.BinPacking.Trees.TreeColorCounts +OAI.Computability.BinPacking.Trees.TreePruning diff --git a/tasks/bin-packing-gap/solution/reference.py b/tasks/bin-packing-gap/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bin-packing-gap/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bin-packing-gap/solution/solve.sh b/tasks/bin-packing-gap/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ec63cdb7ccc4f8a819c12502eca00ad7d6ec3ebb --- /dev/null +++ b/tasks/bin-packing-gap/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BinPackingGap, i.e. module OAI.Computability.BinPacking.Main and the +# 284 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.BinPacking.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BinPackingGap" diff --git a/tasks/bin-packing-gap/task.toml b/tasks/bin-packing-gap/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..95c7b72ef1b46a48bb4d1f5205b709e7b558f919 --- /dev/null +++ b/tasks/bin-packing-gap/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bin-packing-gap" +version = "1.0.0" +description = "Prove BinPackingGap (openai/math family 118: Unbounded bin-packing gaps and the modified integer round-up conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BinPackingGap.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BinPackingGap" +family = "118" +family_title = "Unbounded bin-packing gaps and the modified integer round-up conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.BinPackingGap.main_results"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.BinPacking.Main" +reference_modules = 284 +reference_lean_bytes = 7557041 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1412 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 18501 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bin-packing-gap/tests/Challenge.lean b/tasks/bin-packing-gap/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..63e45228b140d55715422f393e48416a234b19c0 --- /dev/null +++ b/tasks/bin-packing-gap/tests/Challenge.lean @@ -0,0 +1,378 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace BinPackingGames.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +end BinPackingGames.Foundations.Complexity + +namespace BinPackingGames.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end BinPackingGames.Foundations.Complexity.MachineFiniteAlphabet + +namespace BinPackingGames.Foundations.Complexity.CookLevin + +def pairBits (input : List Bool × List Bool) : List Bool := + encodeWord input.1.length ++ input.1 ++ input.2 + +structure NPVerifier where + witnessBound : Polynomial Nat + verify : (List Bool × List Bool) → Bool + computation : Turing.TM2ComputableInPolyTime pairBits (fun bit => [bit]) verify + finiteAlphabet : (k : computation.tm.K) → Fintype (computation.tm.Γ k) + +def NPVerifier.Accepts (verifier : NPVerifier) (input : List Bool) : Prop := + ∃ witness : List Bool, + witness.length ≤ verifier.witnessBound.eval input.length ∧ + verifier.verify (input, witness) = true + +def InNP (language : List Bool → Prop) : Prop := + ∃ verifier : NPVerifier, ∀ input, language input ↔ verifier.Accepts input + +end BinPackingGames.Foundations.Complexity.CookLevin + +namespace BinPackingCompleteness.BinaryEncoding + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +end BinPackingCompleteness.BinaryEncoding + +namespace BinPackingGap + +open scoped BigOperators + +structure Instance where + n : ℕ + size : Fin n → ℚ + size_pos : ∀ i, 0 < size i + size_le_one : ∀ i, size i ≤ 1 + +namespace Instance + +abbrev Item (I : Instance) := Fin I.n + +end Instance + +structure Packing (I : Instance) (b : ℕ) where + assignment : I.Item → Fin b + capacity : ∀ j, (∑ i, if assignment i = j then I.size i else 0) ≤ 1 + +def HasPacking (I : Instance) (b : ℕ) : Prop := Nonempty (Packing I b) + +def singletonPacking (I : Instance) : Packing I I.n where + assignment i := i + capacity j := by + have hsum : (∑ i, if i = j then I.size i else 0) = I.size j := by + calc + (∑ i, if i = j then I.size i else 0) = + (if j = j then I.size j else 0) := + Finset.sum_eq_single j (fun i _ hij => ite_eq_right hij) + (fun h => False.elim (h (Finset.mem_univ _))) + _ = I.size j := ite_eq_left rfl + rw [hsum] + exact I.size_le_one j + +theorem exists_packing (I : Instance) : ∃ b, HasPacking I b := + ⟨I.n, ⟨singletonPacking I⟩⟩ + +noncomputable def opt (I : Instance) : ℕ := by + classical + exact Nat.find (exists_packing I) + +def IndividualConfiguration (I : Instance) := + {H : Finset I.Item // ∑ i ∈ H, I.size i ≤ 1} + +noncomputable instance (I : Instance) : Fintype (IndividualConfiguration I) := + inferInstanceAs (Fintype {H : Finset I.Item // ∑ i ∈ H, I.size i ≤ 1}) + +def NumericalSize (I : Instance) := ↥(Finset.univ.image I.size) + +instance (I : Instance) : Fintype (NumericalSize I) := + inferInstanceAs (Fintype ↥(Finset.univ.image I.size)) + +namespace NumericalSize + +variable {I : Instance} + +theorem positive (s : NumericalSize I) : 0 < s.val := by + obtain ⟨i, _, hi⟩ := Finset.mem_image.mp s.property + rw [← hi] + exact I.size_pos i + +def multiplicity (s : NumericalSize I) : ℕ := + (Finset.univ.filter fun i : I.Item => I.size i = s.val).card + +def capacityBound (s : NumericalSize I) : ℕ := + Classical.choose (exists_nat_gt (1 / s.val)) + +theorem capacityBound_spec (s : NumericalSize I) : 1 / s.val < (s.capacityBound : ℚ) := + Classical.choose_spec (exists_nat_gt (1 / s.val)) + +end NumericalSize + +def TypeConfiguration (I : Instance) := + {c : NumericalSize I → ℕ // ∑ s, s.val * (c s : ℚ) ≤ 1} + +namespace TypeConfiguration + +variable {I : Instance} + +theorem count_lt_bound (c : TypeConfiguration I) (s : NumericalSize I) : + c.val s < s.capacityBound := by + have hterm : s.val * (c.val s : ℚ) ≤ ∑ t, t.val * (c.val t : ℚ) := by + exact Finset.single_le_sum (fun t _ => mul_nonneg (le_of_lt t.positive) (Nat.cast_nonneg _)) + (Finset.mem_univ s) + have hquot : (c.val s : ℚ) ≤ 1 / s.val := by + apply (le_div_iff₀ s.positive).mpr + simpa [mul_comm] using hterm.trans c.property + have hlt := hquot.trans_lt s.capacityBound_spec + exact_mod_cast hlt + +def boundedCounts (c : TypeConfiguration I) : ∀ s : NumericalSize I, Fin s.capacityBound := + fun s => ⟨c.val s, c.count_lt_bound s⟩ + +theorem boundedCounts_injective : + Function.Injective + (boundedCounts : TypeConfiguration I → ∀ s : NumericalSize I, Fin s.capacityBound) := by + intro c d h + apply Subtype.ext + funext s + exact congrArg Fin.val (congrFun h s) + +instance : Finite (TypeConfiguration I) := by + classical + exact Finite.of_injective boundedCounts boundedCounts_injective + +instance : Fintype (TypeConfiguration I) := Fintype.ofFinite _ + +end TypeConfiguration + +namespace FractionalCover + +open Set +variable {I C : Type*} [Fintype I] [Fintype C] + +def Feasible (a : C → I → ℝ) (d : I → ℝ) (w : C → ℝ) : Prop := + (∀ c, 0 ≤ w c) ∧ ∀ i, d i ≤ ∑ c, a c i * w c + +def objective (w : C → ℝ) : ℝ := ∑ c, w c + +def objectiveSet (a : C → I → ℝ) (d : I → ℝ) : Set ℝ := + {v | ∃ w, Feasible a d w ∧ objective w = v} + +def value (a : C → I → ℝ) (d : I → ℝ) : ℝ := + sInf (objectiveSet a d) + +end FractionalCover + +def individualMatrix (I : Instance) (H : IndividualConfiguration I) (i : I.Item) : ℝ := + if i ∈ H.val then 1 else 0 + +def individualLP (I : Instance) : ℝ := + FractionalCover.value (individualMatrix I) (fun _ => 1) + +def typeMatrix (I : Instance) (c : TypeConfiguration I) (s : NumericalSize I) : ℝ := + c.val s + +def typeLP (I : Instance) : ℝ := + FractionalCover.value (typeMatrix I) (fun s => (s.multiplicity : ℝ)) + +abbrev RawInstance := List (ℕ × ℕ) + +abbrev RawReductionOutput := ℕ × RawInstance + +namespace RawInstance + +def Valid (r : RawInstance) : Prop := + ∀ q ∈ r, 0 < q.1 ∧ q.1 ≤ q.2 + +def ratValue (q : ℕ × ℕ) : ℚ := (q.1 : ℚ) / (q.2 : ℚ) + +theorem den_pos {r : RawInstance} (hr : r.Valid) {q : ℕ × ℕ} (hq : q ∈ r) : + 0 < q.2 := lt_of_lt_of_le (hr q hq).1 (hr q hq).2 + +def toInstance (r : RawInstance) (hr : r.Valid) : Instance where + n := r.length + size i := ratValue (r.get i) + size_pos i := div_pos (Nat.cast_pos.mpr (hr _ (List.get_mem r i)).1) + (Nat.cast_pos.mpr (den_pos hr (List.get_mem r i))) + size_le_one i := (div_le_one₀ (Nat.cast_pos.mpr (den_pos hr (List.get_mem r i)))).mpr + (Nat.cast_le.mpr (hr _ (List.get_mem r i)).2) + +end RawInstance + +structure RawPacking where + bins : ℕ + assignments : List ℕ + +namespace RawPacking + +def load (r : RawInstance) (a : List ℕ) (j : ℕ) : ℚ := + ((r.zip a).map fun qa => + if qa.2 = j then RawInstance.ratValue qa.1 else 0).sum + +def Feasible (r : RawInstance) (p : RawPacking) : Prop := + p.assignments.length = r.length ∧ + (∀ j ∈ p.assignments, j < p.bins) ∧ + ∀ j < p.bins, load r p.assignments j ≤ 1 + +end RawPacking + +namespace BinaryEncoding + +abbrev natBits := BinPackingCompleteness.BinaryEncoding.nameBits + +abbrev parseNat := BinPackingCompleteness.BinaryEncoding.parseName + +def listBits {α : Type} (encode : α → List Bool) : List α → List Bool + | [] => [false] + | a :: rest => true :: (encode a ++ listBits encode rest) + +def pairBits {α β : Type} (ea : α → List Bool) (eb : β → List Bool) + (p : α × β) : List Bool := ea p.1 ++ eb p.2 + +def optionBits {α : Type} (encode : α → List Bool) : Option α → List Bool + | none => [false] + | some a => true :: encode a + +abbrev Parser (α : Type) := List Bool → Option (α × List Bool) + +def parsePair {α β : Type} (pa : Parser α) (pb : Parser β) : Parser (α × β) := + fun input => do + let (a, rest) ← pa input + let (b, suffix) ← pb rest + return ((a, b), suffix) + +def parseListAux {α : Type} (parse : Parser α) : Nat → Parser (List α) + | 0, _ => none + | _ + 1, [] => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: rest => do + let (a, rest) ← parse rest + let (as, suffix) ← parseListAux parse fuel rest + return (a :: as, suffix) + +def parseList {α : Type} (parse : Parser α) : Parser (List α) := + fun input => parseListAux parse input.length input + +def decode {α : Type} (parse : Parser α) (input : List Bool) : Option α := do + let (a, rest) ← parse input + if rest.isEmpty then some a else none + +def rawInstanceBits (r : RawInstance) : List Bool := + listBits (pairBits natBits natBits) r + +def assignmentBits (a : List Nat) : List Bool := listBits natBits a + +def rawPackingBits (p : RawPacking) : List Bool := + natBits p.bins ++ assignmentBits p.assignments + +def packingResultBits (p : Option RawPacking) : List Bool := optionBits rawPackingBits p + +def rawReductionOutputBits (out : RawReductionOutput) : List Bool := + natBits out.1 ++ rawInstanceBits out.2 + +def parseRawInstance : Parser RawInstance := parseList (parsePair parseNat parseNat) + +def decodeRawInstance := decode parseRawInstance + +end BinaryEncoding + +section + +open Turing BinPackingGames.Foundations.Complexity + +abbrev BitLanguage := List Bool → Prop + +def InP (L : BitLanguage) : Prop := + ∃ decider : List Bool → Bool, + ∃ computation : TM2ComputableInPolyTime + (id : List Bool → List Bool) (fun b => [b]) decider, + MachineFiniteAlphabet.FiniteAlphabet computation.tm ∧ + ∀ x, L x ↔ decider x = true + +def ClassP : Set BitLanguage := {L | InP L} + +def ClassNP : Set BitLanguage := {L | CookLevin.InNP L} + +def PEqualsNP : Prop := ClassP = ClassNP + +structure AbsoluteAdditiveAlgorithm (c : Nat) where + run : List Bool → Option RawPacking + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + BinaryEncoding.packingResultBits run + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + guarantee : ∀ (r : RawInstance) (hr : r.Valid), ∃ p : RawPacking, + run (BinaryEncoding.rawInstanceBits r) = some p ∧ + RawPacking.Feasible r p ∧ p.bins ≤ opt (r.toInstance hr) + c + +structure PackingGapReduction (c : Nat) (L : BitLanguage) where + reduce : List Bool → RawReductionOutput + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + BinaryEncoding.rawReductionOutputBits reduce + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + valid : ∀ x, (reduce x).2.Valid + itemCount : ∀ x, (reduce x).2.length = 5 * (reduce x).1 + itemLower : ∀ x i, + (1 / 6 : ℚ) < ((reduce x).2.toInstance (valid x)).size i + completeness : ∀ x, L x → + HasPacking ((reduce x).2.toInstance (valid x)) (reduce x).1 + soundness : ∀ x, ¬L x → + ¬HasPacking ((reduce x).2.toInstance (valid x)) ((reduce x).1 + c) + +def PackingGapNPHard (c : Nat) : Prop := + ∀ L : BitLanguage, CookLevin.InNP L → Nonempty (PackingGapReduction c L) + +end + +theorem main_results : + (∀ c : ℕ, ∃ I : Instance, ∃ B : ℕ, + I.n = 5 * B ∧ + (∀ i, (1 / 6 : ℚ) < I.size i ∧ I.size i < 1) ∧ + B + c < opt I ∧ individualLP I = (B : ℝ) ∧ typeLP I = (B : ℝ)) ∧ + (∀ c : Nat, PackingGapNPHard c) ∧ + ((∃ c : Nat, Nonempty (AbsoluteAdditiveAlgorithm c)) ↔ PEqualsNP) ∧ + (PEqualsNP → ∃ algorithm : AbsoluteAdditiveAlgorithm 0, + (∀ (items : RawInstance) (valid : items.Valid), ∃ packing : RawPacking, + algorithm.run (BinaryEncoding.rawInstanceBits items) = some packing ∧ + packing.Feasible items ∧ packing.bins = opt (items.toInstance valid)) ∧ + algorithm.run (BinaryEncoding.rawInstanceBits []) = some ⟨0, []⟩ ∧ + (∀ input : List Bool, BinaryEncoding.decodeRawInstance input = none → + algorithm.run input = none) ∧ + (∀ items : RawInstance, ¬ items.Valid → + algorithm.run (BinaryEncoding.rawInstanceBits items) = none)) := by + sorry + +end BinPackingGap + +end + +end OAI diff --git a/tasks/bin-packing-gap/tests/grade.py b/tasks/bin-packing-gap/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bin-packing-gap/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bin-packing-gap/tests/task.json b/tasks/bin-packing-gap/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1dd026c2e2fb282d23cfe9db9bfe54de5273e0f3 --- /dev/null +++ b/tasks/bin-packing-gap/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BinPackingGap", + "comparator": { + "theorem_names": [ + "OAI.BinPackingGap.main_results" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 17601 +} \ No newline at end of file diff --git a/tasks/bin-packing-gap/tests/test.sh b/tasks/bin-packing-gap/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bin-packing-gap/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/binary-edit-lower/environment/Dockerfile b/tasks/binary-edit-lower/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/binary-edit-lower/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/binary-edit-lower/environment/fetch_mathlib.sh b/tasks/binary-edit-lower/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/binary-edit-lower/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/binary-edit-lower/environment/lake-manifest.json b/tasks/binary-edit-lower/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/binary-edit-lower/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/binary-edit-lower/environment/lakefile.lean b/tasks/binary-edit-lower/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/binary-edit-lower/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/binary-edit-lower/environment/lean_setup.sh b/tasks/binary-edit-lower/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/binary-edit-lower/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/binary-edit-lower/environment/pack_submission.py b/tasks/binary-edit-lower/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/binary-edit-lower/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/binary-edit-lower/instruction.md b/tasks/binary-edit-lower/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0cd74fc94a8d8573aeb72ba67011270b028d499e --- /dev/null +++ b/tasks/binary-edit-lower/instruction.md @@ -0,0 +1,111 @@ +# openai/math challenge `BinaryEditLower` (family 099) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 099 of the release, *The sharp distortion of edit distance into $\ell_1$* +(Convex and metric geometry). The family as a whole: Determines the least distortion of embedding edit distance on words of length at most $d$ into real $\ell_1$: it is $\exp(\Theta(\sqrt{\log d\,\log\log d}))$. Insertions, deletions and substitutions have unit cost. The constants are uniform over all finite alphabets with at least two symbols, even when the alphabet grows with $d$; binary words already force the lower bound. + +The challenge is `BinaryEditLower`, also at `/opt/openai-math/challenges/BinaryEditLower.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TreeEdit + +universe u + +/-- A single unit-cost insertion, deletion, or substitution at any position. -/ +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (p q : List α) (a : α) : EditStep (p ++ q) (p ++ a :: q) + | delete (p q : List α) (a : α) : EditStep (p ++ a :: q) (p ++ q) + | substitute (p q : List α) (a b : α) : EditStep (p ++ a :: q) (p ++ b :: q) + +/-- An edit script with no restriction on intermediate word lengths. -/ +inductive EditScript {α : Type u} : List α → List α → ℕ → Prop + | nil (x : List α) : EditScript x x 0 + | cons {x y z : List α} {n : ℕ} : + EditStep x y → EditScript y z n → EditScript x z (n + 1) + +noncomputable def ed {α : Type u} (x y : List α) : ℕ := + sInf {n | EditScript x y n} + +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 +abbrev Word (α : Type u) (n : ℕ) := {x : List α // x.length = n} + +namespace BinaryLower + +/-- The product of the two maximal pairwise distance ratios. -/ +noncomputable def distortion {X : Type u} (ρ : X → X → ℝ) (f : X → RealL1) : ℝ := + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ‖f x - f y‖ / ρ x y} * + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ρ x y / ‖f x - f y‖} + +/-- The infimum over every injective map into the full real sequence space ℓ₁. -/ +noncomputable def c1 (X : Type u) (ρ : X → X → ℝ) : ℝ := + sInf {D : ℝ | ∃ f : X → RealL1, Function.Injective f ∧ D = distortion ρ f} + +noncomputable def binarySetDistortion {n : ℕ} (W : Finset (Word Bool n)) : ℝ := + c1 {x : Word Bool n // x ∈ W} + (fun x y => (ed x.val.val y.val.val : ℝ)) + +noncomputable def growth (c : ℝ) (d : ℕ) : ℝ := + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) + +end BinaryLower + +open BinaryLower + +/-- The binary lower-bound theorem of OpenAI's September 27, 2026 tree-constructions +manuscript: finite equal-length witnesses for every sufficiently large length cap. -/ +theorem binary_lower_bound : + ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∃ n : ℕ, 1 ≤ n ∧ n ≤ d ∧ + ∃ W : Finset (Word Bool n), 2 ≤ W.card ∧ + growth c d ≤ binarySetDistortion W := by + sorry + +end TreeEdit + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BinaryEditLower.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TreeEdit.binary_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/binary-edit-lower/solution/closure.txt b/tasks/binary-edit-lower/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ee41992191af3f402924ffccaa9de73dda466ad --- /dev/null +++ b/tasks/binary-edit-lower/solution/closure.txt @@ -0,0 +1,84 @@ +OAI.Combinatorics.BinaryEdit.BinaryLowerBound +OAI.Combinatorics.BinaryEdit.BlockExtraction +OAI.Combinatorics.BinaryEdit.BlockPairCount +OAI.Combinatorics.BinaryEdit.BlockRestriction +OAI.Combinatorics.BinaryEdit.Branching +OAI.Combinatorics.BinaryEdit.CheapTranslations +OAI.Combinatorics.BinaryEdit.CodeAdditive +OAI.Combinatorics.BinaryEdit.CodeConversion +OAI.Combinatorics.BinaryEdit.CodeEqualMatches +OAI.Combinatorics.BinaryEdit.CodeExistence +OAI.Combinatorics.BinaryEdit.CodeNumerics +OAI.Combinatorics.BinaryEdit.CodeTrimming +OAI.Combinatorics.BinaryEdit.CodeUnionBound +OAI.Combinatorics.BinaryEdit.CutAggregation +OAI.Combinatorics.BinaryEdit.Distortion +OAI.Combinatorics.BinaryEdit.EditDeficit +OAI.Combinatorics.BinaryEdit.EditLCSLower +OAI.Combinatorics.BinaryEdit.EditMetric +OAI.Combinatorics.BinaryEdit.EncodedImage +OAI.Combinatorics.BinaryEdit.EncodedSegmentSeparation +OAI.Combinatorics.BinaryEdit.EncodingIndex +OAI.Combinatorics.BinaryEdit.EncodingUpper +OAI.Combinatorics.BinaryEdit.FiniteActivityBridge +OAI.Combinatorics.BinaryEdit.FiniteAlphabet +OAI.Combinatorics.BinaryEdit.FiniteCapTransfer +OAI.Combinatorics.BinaryEdit.FiniteCoordinates +OAI.Combinatorics.BinaryEdit.FiniteDisplacement +OAI.Combinatorics.BinaryEdit.FiniteFamilyTransfer +OAI.Combinatorics.BinaryEdit.FiniteFourier +OAI.Combinatorics.BinaryEdit.FiniteFourierAssembly +OAI.Combinatorics.BinaryEdit.FiniteL1Tree +OAI.Combinatorics.BinaryEdit.FiniteNumeric +OAI.Combinatorics.BinaryEdit.FiniteParameters +OAI.Combinatorics.BinaryEdit.FinitePeriod +OAI.Combinatorics.BinaryEdit.FiniteSeparation +OAI.Combinatorics.BinaryEdit.FiniteSeparationArithmetic +OAI.Combinatorics.BinaryEdit.FiniteSourceFamily +OAI.Combinatorics.BinaryEdit.FiniteSpectralTree +OAI.Combinatorics.BinaryEdit.FiniteTreeConcreteCosts +OAI.Combinatorics.BinaryEdit.FiniteTreeCostTheorem +OAI.Combinatorics.BinaryEdit.FiniteTreeCosts +OAI.Combinatorics.BinaryEdit.FiniteTreeGeometry +OAI.Combinatorics.BinaryEdit.FiniteTreeInstantiation +OAI.Combinatorics.BinaryEdit.FiniteTreeTags +OAI.Combinatorics.BinaryEdit.FiniteTreeWords +OAI.Combinatorics.BinaryEdit.FiniteVectorDetection +OAI.Combinatorics.BinaryEdit.FiniteVectorRestrictions +OAI.Combinatorics.BinaryEdit.FiniteVectors +OAI.Combinatorics.BinaryEdit.FiniteWordDetection +OAI.Combinatorics.BinaryEdit.FiniteWordL1Mean +OAI.Combinatorics.BinaryEdit.FiniteWordPrimeSeparation +OAI.Combinatorics.BinaryEdit.FixedLengthBinaryConversion +OAI.Combinatorics.BinaryEdit.LCS +OAI.Combinatorics.BinaryEdit.LCSCore +OAI.Combinatorics.BinaryEdit.LCSEditUpper +OAI.Combinatorics.BinaryEdit.MatchingSegments +OAI.Combinatorics.BinaryEdit.MatchingSpanBudget +OAI.Combinatorics.BinaryEdit.MatchingSublist +OAI.Combinatorics.BinaryEdit.Model +OAI.Combinatorics.BinaryEdit.ParameterImage +OAI.Combinatorics.BinaryEdit.PrimeSeparation +OAI.Combinatorics.BinaryEdit.PrimeSupply +OAI.Combinatorics.BinaryEdit.RandomMatching +OAI.Combinatorics.BinaryEdit.ScalarCutsBool +OAI.Combinatorics.BinaryEdit.SegmentCode +OAI.Combinatorics.BinaryEdit.SegmentCodeEstimates +OAI.Combinatorics.BinaryEdit.SegmentCodeLCS +OAI.Combinatorics.BinaryEdit.SegmentMatchingCount +OAI.Combinatorics.BinaryEdit.SparseActivity +OAI.Combinatorics.BinaryEdit.SparseCharacterPeriod +OAI.Combinatorics.BinaryEdit.SubsequenceIntersection +OAI.Combinatorics.BinaryEdit.TaggedAlignment +OAI.Combinatorics.BinaryEdit.TaggedArrayPrerequisites +OAI.Combinatorics.BinaryEdit.TaggedArrays +OAI.Combinatorics.BinaryEdit.TaggedExtraction +OAI.Combinatorics.BinaryEdit.TaggedGaps +OAI.Combinatorics.BinaryEdit.TaggedNonsplit +OAI.Combinatorics.BinaryEdit.TaggedRowLCS +OAI.Combinatorics.BinaryEdit.UnequalCounting +OAI.Combinatorics.BinaryEdit.UnequalSegments +OAI.Combinatorics.BinaryEdit.WordFinite +OAI.Combinatorics.TreeEdit.Alignments +OAI.Combinatorics.TreeEdit.EditMetric +OAI.Combinatorics.TreeEdit.Model diff --git a/tasks/binary-edit-lower/solution/reference.py b/tasks/binary-edit-lower/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/binary-edit-lower/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/binary-edit-lower/solution/solve.sh b/tasks/binary-edit-lower/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c0b3b4a95dcec8f0ea6a975abf15d87f5755ddfa --- /dev/null +++ b/tasks/binary-edit-lower/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BinaryEditLower, i.e. module OAI.Combinatorics.BinaryEdit.BinaryLowerBound and the +# 84 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.BinaryEdit.BinaryLowerBound /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BinaryEditLower" diff --git a/tasks/binary-edit-lower/task.toml b/tasks/binary-edit-lower/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..efb6f878c11442ac09cf09c02465dd4c3d3e005a --- /dev/null +++ b/tasks/binary-edit-lower/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/binary-edit-lower" +version = "1.0.0" +description = "Prove BinaryEditLower (openai/math family 099: The sharp distortion of edit distance into $\\ell_1$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BinaryEditLower.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BinaryEditLower" +family = "099" +family_title = "The sharp distortion of edit distance into $\\ell_1$" +subject = "Convex and metric geometry" +theorems = ["OAI.TreeEdit.binary_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.BinaryEdit.BinaryLowerBound" +reference_modules = 84 +reference_lean_bytes = 464862 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 790 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12118 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/binary-edit-lower/tests/Challenge.lean b/tasks/binary-edit-lower/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9ebbf5f0ddbabc3ad97cabc3e7d69e2ece447a07 --- /dev/null +++ b/tasks/binary-edit-lower/tests/Challenge.lean @@ -0,0 +1,60 @@ +import Mathlib + +namespace OAI + +namespace TreeEdit + +universe u + +/-- A single unit-cost insertion, deletion, or substitution at any position. -/ +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (p q : List α) (a : α) : EditStep (p ++ q) (p ++ a :: q) + | delete (p q : List α) (a : α) : EditStep (p ++ a :: q) (p ++ q) + | substitute (p q : List α) (a b : α) : EditStep (p ++ a :: q) (p ++ b :: q) + +/-- An edit script with no restriction on intermediate word lengths. -/ +inductive EditScript {α : Type u} : List α → List α → ℕ → Prop + | nil (x : List α) : EditScript x x 0 + | cons {x y z : List α} {n : ℕ} : + EditStep x y → EditScript y z n → EditScript x z (n + 1) + +noncomputable def ed {α : Type u} (x y : List α) : ℕ := + sInf {n | EditScript x y n} + +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 +abbrev Word (α : Type u) (n : ℕ) := {x : List α // x.length = n} + +namespace BinaryLower + +/-- The product of the two maximal pairwise distance ratios. -/ +noncomputable def distortion {X : Type u} (ρ : X → X → ℝ) (f : X → RealL1) : ℝ := + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ‖f x - f y‖ / ρ x y} * + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ρ x y / ‖f x - f y‖} + +/-- The infimum over every injective map into the full real sequence space ℓ₁. -/ +noncomputable def c1 (X : Type u) (ρ : X → X → ℝ) : ℝ := + sInf {D : ℝ | ∃ f : X → RealL1, Function.Injective f ∧ D = distortion ρ f} + +noncomputable def binarySetDistortion {n : ℕ} (W : Finset (Word Bool n)) : ℝ := + c1 {x : Word Bool n // x ∈ W} + (fun x y => (ed x.val.val y.val.val : ℝ)) + +noncomputable def growth (c : ℝ) (d : ℕ) : ℝ := + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) + +end BinaryLower + +open BinaryLower + +/-- The binary lower-bound theorem of OpenAI's September 27, 2026 tree-constructions +manuscript: finite equal-length witnesses for every sufficiently large length cap. -/ +theorem binary_lower_bound : + ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∃ n : ℕ, 1 ≤ n ∧ n ≤ d ∧ + ∃ W : Finset (Word Bool n), 2 ≤ W.card ∧ + growth c d ≤ binarySetDistortion W := by + sorry + +end TreeEdit + +end OAI diff --git a/tasks/binary-edit-lower/tests/grade.py b/tasks/binary-edit-lower/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/binary-edit-lower/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/binary-edit-lower/tests/task.json b/tasks/binary-edit-lower/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..30518633cc54bd603bff849f60098f2ae590b4af --- /dev/null +++ b/tasks/binary-edit-lower/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BinaryEditLower", + "comparator": { + "theorem_names": [ + "OAI.TreeEdit.binary_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11218 +} \ No newline at end of file diff --git a/tasks/binary-edit-lower/tests/test.sh b/tasks/binary-edit-lower/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/binary-edit-lower/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/binary-matching/environment/Dockerfile b/tasks/binary-matching/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/binary-matching/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/binary-matching/environment/fetch_mathlib.sh b/tasks/binary-matching/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/binary-matching/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/binary-matching/environment/lake-manifest.json b/tasks/binary-matching/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/binary-matching/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/binary-matching/environment/lakefile.lean b/tasks/binary-matching/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/binary-matching/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/binary-matching/environment/lean_setup.sh b/tasks/binary-matching/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/binary-matching/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/binary-matching/environment/pack_submission.py b/tasks/binary-matching/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/binary-matching/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/binary-matching/instruction.md b/tasks/binary-matching/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69753ec63d861f130e408f839c6d013ecb660e69 --- /dev/null +++ b/tasks/binary-matching/instruction.md @@ -0,0 +1,127 @@ +# openai/math challenge `BinaryMatching` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `BinaryMatching`, also at `/opt/openai-math/challenges/BinaryMatching.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u_1 u_2 + +namespace MatchingEntropy + +structure LooplessGraph (V : Type u_1) (E : Type u_2) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +namespace LooplessGraph + +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e=v ∨ G.right e=v +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e∈M ∧ G.Incident v e +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} +noncomputable instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +end LooplessGraph + +end MatchingEntropy + +namespace BinaryMatching + +abbrev Pair (n : ℕ) := {ij : Fin n × Fin n // ij.1 < ij.2} +def completeGraph (n : ℕ) : MatchingEntropy.LooplessGraph (Fin n) (Pair n) where + left e := e.val.1 + right e := e.val.2 + loopless e := ne_of_lt e.property + +structure Record where + left : ℕ + right : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + n : ℕ + records : List Record + valid : ∀ e∈records, e.left < e.right ∧ e.right < n + unique : (records.map (fun e => (e.left,e.right))).Nodup + +def multiplicity (G : Input) (e : Pair G.n) : ℕ := + match G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => 0 + | some r => r.multiplicity + +noncomputable def count (G : Input) : ℕ := + ∑ M : (completeGraph G.n).Matching, ∏ e∈M.val, multiplicity G e + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length false ++ true :: n.bits + +def encodeRecord (r : Record) : List Bool := + encodeNat r.left ++ encodeNat r.right ++ encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + encodeNat G.n ++ encodeNat G.records.length ++ G.records.flatMap encodeRecord + +theorem deterministic_approximate_counting : + ∃ A : Input → ℕ, + ∃ machine : Turing.TM2ComputableInPolyTime encodeInput Nat.bits A, + (∀ k, Finite (machine.tm.Γ k)) ∧ + (∃ P : Polynomial ℕ, ∀ G,(A G).bits.length≤P.eval (encodeInput G).length) ∧ + ∀ G,A G≤count G ∧ count G≤2^(9*G.n)*A G ∧ (A G=0 ↔ count G=0) := by + sorry + +end BinaryMatching + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BinaryMatching.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BinaryMatching.deterministic_approximate_counting` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/binary-matching/solution/closure.txt b/tasks/binary-matching/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ac10ceabda6f21d292bf54f2492da77e84134bf2 --- /dev/null +++ b/tasks/binary-matching/solution/closure.txt @@ -0,0 +1,112 @@ +OAI.Combinatorics.PerfectMatching.AlgorithmPartition +OAI.Combinatorics.PerfectMatching.Ascent +OAI.Combinatorics.PerfectMatching.Basic +OAI.Combinatorics.PerfectMatching.Calculus +OAI.Combinatorics.PerfectMatching.CompletePairs +OAI.Combinatorics.PerfectMatching.Completion +OAI.Combinatorics.PerfectMatching.Continuity +OAI.Combinatorics.PerfectMatching.Contraction +OAI.Combinatorics.PerfectMatching.CountCorrect +OAI.Combinatorics.PerfectMatching.Coupling +OAI.Combinatorics.PerfectMatching.Covariance +OAI.Combinatorics.PerfectMatching.Duality +OAI.Combinatorics.PerfectMatching.DyadicEntropy +OAI.Combinatorics.PerfectMatching.DyadicEnvelope +OAI.Combinatorics.PerfectMatching.ElementaryCount +OAI.Combinatorics.PerfectMatching.Entropy +OAI.Combinatorics.PerfectMatching.EntropyUpper +OAI.Combinatorics.PerfectMatching.Face +OAI.Combinatorics.PerfectMatching.FeasibilityRepair +OAI.Combinatorics.PerfectMatching.ForcedReduction +OAI.Combinatorics.PerfectMatching.Main +OAI.Combinatorics.PerfectMatching.MatchingCovariance +OAI.Combinatorics.PerfectMatching.Model +OAI.Combinatorics.PerfectMatching.ObjectivePenalty +OAI.Combinatorics.PerfectMatching.OddCuts +OAI.Combinatorics.PerfectMatching.Optimizer +OAI.Combinatorics.PerfectMatching.ParameterBounds +OAI.Combinatorics.PerfectMatching.Partition +OAI.Combinatorics.PerfectMatching.Polyhedron +OAI.Combinatorics.PerfectMatching.Polytope +OAI.Combinatorics.PerfectMatching.SecondVariation +OAI.Combinatorics.PerfectMatching.Separable +OAI.Combinatorics.PerfectMatching.SeparableCovariance +OAI.Combinatorics.PerfectMatching.SeparableLower +OAI.Combinatorics.PerfectMatching.Simplex +OAI.Combinatorics.PerfectMatching.SizeBounds +OAI.Combinatorics.PerfectMatching.Violation +OAI.Combinatorics.PerfectMatching.WeightedSpectrum +OAI.Computability.MatchingCount.ArgRoutine +OAI.Computability.MatchingCount.BinaryAlgorithm +OAI.Computability.MatchingCount.BinaryParser +OAI.Computability.MatchingCount.BinarySolve +OAI.Computability.MatchingCount.CappedPower +OAI.Computability.MatchingCount.CutAlgebra +OAI.Computability.MatchingCount.DenseOracle +OAI.Computability.MatchingCount.DivisionRoutine +OAI.Computability.MatchingCount.FiniteStack +OAI.Computability.MatchingCount.FoldRoutine +OAI.Computability.MatchingCount.GuardRoutine +OAI.Computability.MatchingCount.IntegerRoutine +OAI.Computability.MatchingCount.IterateRoutine +OAI.Computability.MatchingCount.LengthRoutine +OAI.Computability.MatchingCount.ListNumeric +OAI.Computability.MatchingCount.ListRoutine +OAI.Computability.MatchingCount.MapRoutine +OAI.Computability.MatchingCount.OddCutParity +OAI.Computability.MatchingCount.OddCutUncross +OAI.Computability.MatchingCount.OddMincut +OAI.Computability.MatchingCount.OptionCases +OAI.Computability.MatchingCount.OracleBounds +OAI.Computability.MatchingCount.OrbitRoutine +OAI.Computability.MatchingCount.PairRoutine +OAI.Computability.MatchingCount.ParamRoutine +OAI.Computability.MatchingCount.ParserSupport +OAI.Computability.MatchingCount.PolyCoding +OAI.Computability.MatchingCount.ProjectionRoutine +OAI.Computability.MatchingCount.RawBitsBridge +OAI.Computability.MatchingCount.RawContraction +OAI.Computability.MatchingCount.RawContractionCompiler +OAI.Computability.MatchingCount.RawData +OAI.Computability.MatchingCount.RawFlow +OAI.Computability.MatchingCount.RawFlowCompiler +OAI.Computability.MatchingCount.RawFlowSize +OAI.Computability.MatchingCount.RawInput +OAI.Computability.MatchingCount.RawOddBounds +OAI.Computability.MatchingCount.RawOddCompiler +OAI.Computability.MatchingCount.RawOddCut +OAI.Computability.MatchingCount.RawOptimizer +OAI.Computability.MatchingCount.RawOptimizerCompiler +OAI.Computability.MatchingCount.RawOptimizerData +OAI.Computability.MatchingCount.RawOptimizerDataCompiler +OAI.Computability.MatchingCount.RawOptimizerRows +OAI.Computability.MatchingCount.RawOptimizerRowsCompiler +OAI.Computability.MatchingCount.RawPrimitives +OAI.Computability.MatchingCount.RawRoutine +OAI.Computability.MatchingCount.RawSearch +OAI.Computability.MatchingCount.RawSearchCompiler +OAI.Computability.MatchingCount.RawSearchSize +OAI.Computability.MatchingCount.RawSize +OAI.Computability.MatchingCount.RecursiveBounds +OAI.Computability.MatchingCount.RecursiveCoding +OAI.Computability.MatchingCount.RecursiveCompiler +OAI.Computability.MatchingCount.RecursiveEval +OAI.Computability.MatchingCount.ResidualSearch +OAI.Computability.MatchingCount.ScaledAlgorithm +OAI.Computability.MatchingCount.ScaledBounds +OAI.Computability.MatchingCount.ScaledState +OAI.Computability.MatchingCount.SelectRoutine +OAI.Computability.MatchingCount.SequenceRoutine +OAI.Computability.MatchingCount.StackCopy +OAI.Computability.MatchingCount.StackEmbed +OAI.Computability.MatchingCount.StackFrame +OAI.Computability.MatchingCount.StackMacros +OAI.Computability.MatchingCount.StackPair +OAI.Computability.MatchingCount.StackRoutine +OAI.Computability.MatchingCount.SumRoutine +OAI.Computability.MatchingCount.TerminalMincut +OAI.Computability.MatchingCount.UnaryArithmetic +OAI.Computability.MatchingCount.UnaryClog +OAI.Computability.MatchingCount.UnaryDivision +OAI.Computability.MatchingCount.UnitFlow +OAI.Computability.MatchingCount.UnitMincut diff --git a/tasks/binary-matching/solution/reference.py b/tasks/binary-matching/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/binary-matching/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/binary-matching/solution/solve.sh b/tasks/binary-matching/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..339004fc7d5e6f2f821596715dfa92085041b76a --- /dev/null +++ b/tasks/binary-matching/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BinaryMatching, i.e. module OAI.Computability.MatchingCount.BinarySolve and the +# 112 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.MatchingCount.BinarySolve /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BinaryMatching" diff --git a/tasks/binary-matching/task.toml b/tasks/binary-matching/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..304072f07331540c0cf56f0c12444b114100216c --- /dev/null +++ b/tasks/binary-matching/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/binary-matching" +version = "1.0.0" +description = "Prove BinaryMatching (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BinaryMatching.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BinaryMatching" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.BinaryMatching.deterministic_approximate_counting"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.MatchingCount.BinarySolve" +reference_modules = 112 +reference_lean_bytes = 617632 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1132 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12255 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/binary-matching/tests/Challenge.lean b/tasks/binary-matching/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f59d6711d302e26460d0eff1c15c3b9515c87304 --- /dev/null +++ b/tasks/binary-matching/tests/Challenge.lean @@ -0,0 +1,76 @@ +import Mathlib + +namespace OAI + +universe u_1 u_2 + +namespace MatchingEntropy + +structure LooplessGraph (V : Type u_1) (E : Type u_2) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +namespace LooplessGraph + +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e=v ∨ G.right e=v +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e∈M ∧ G.Incident v e +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} +noncomputable instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +end LooplessGraph + +end MatchingEntropy + +namespace BinaryMatching + +abbrev Pair (n : ℕ) := {ij : Fin n × Fin n // ij.1 < ij.2} +def completeGraph (n : ℕ) : MatchingEntropy.LooplessGraph (Fin n) (Pair n) where + left e := e.val.1 + right e := e.val.2 + loopless e := ne_of_lt e.property + +structure Record where + left : ℕ + right : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + n : ℕ + records : List Record + valid : ∀ e∈records, e.left < e.right ∧ e.right < n + unique : (records.map (fun e => (e.left,e.right))).Nodup + +def multiplicity (G : Input) (e : Pair G.n) : ℕ := + match G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => 0 + | some r => r.multiplicity + +noncomputable def count (G : Input) : ℕ := + ∑ M : (completeGraph G.n).Matching, ∏ e∈M.val, multiplicity G e + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length false ++ true :: n.bits + +def encodeRecord (r : Record) : List Bool := + encodeNat r.left ++ encodeNat r.right ++ encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + encodeNat G.n ++ encodeNat G.records.length ++ G.records.flatMap encodeRecord + +theorem deterministic_approximate_counting : + ∃ A : Input → ℕ, + ∃ machine : Turing.TM2ComputableInPolyTime encodeInput Nat.bits A, + (∀ k, Finite (machine.tm.Γ k)) ∧ + (∃ P : Polynomial ℕ, ∀ G,(A G).bits.length≤P.eval (encodeInput G).length) ∧ + ∀ G,A G≤count G ∧ count G≤2^(9*G.n)*A G ∧ (A G=0 ↔ count G=0) := by + sorry + +end BinaryMatching + +end OAI diff --git a/tasks/binary-matching/tests/grade.py b/tasks/binary-matching/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/binary-matching/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/binary-matching/tests/task.json b/tasks/binary-matching/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ea95eb1525ccc43ccb4aa88f09db8c4023aad9d2 --- /dev/null +++ b/tasks/binary-matching/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BinaryMatching", + "comparator": { + "theorem_names": [ + "OAI.BinaryMatching.deterministic_approximate_counting" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11355 +} \ No newline at end of file diff --git a/tasks/binary-matching/tests/test.sh b/tasks/binary-matching/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/binary-matching/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/binary-sweep/environment/Dockerfile b/tasks/binary-sweep/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/binary-sweep/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/binary-sweep/environment/fetch_mathlib.sh b/tasks/binary-sweep/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/binary-sweep/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/binary-sweep/environment/lake-manifest.json b/tasks/binary-sweep/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/binary-sweep/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/binary-sweep/environment/lakefile.lean b/tasks/binary-sweep/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/binary-sweep/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/binary-sweep/environment/lean_setup.sh b/tasks/binary-sweep/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/binary-sweep/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/binary-sweep/environment/pack_submission.py b/tasks/binary-sweep/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/binary-sweep/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/binary-sweep/instruction.md b/tasks/binary-sweep/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8103b6c6c034fadccdc4c0eecd4b933a4cad663 --- /dev/null +++ b/tasks/binary-sweep/instruction.md @@ -0,0 +1,153 @@ +# openai/math challenge `BinarySweep` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `BinarySweep`, also at `/opt/openai-math/challenges/BinarySweep.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace BinaryCoordinateSweeps + +/-- The positions of a binary deck of dimension d. -/ +abbrev Slot (d : ℕ) := Fin d → Bool + +/-- Independent switches on the edges parallel to one coordinate. -/ +def coordinateLayer (d : ℕ) (j : Fin d) + (c : (({i : Fin d // i ≠ j} → Bool)) → Bool) : Equiv.Perm (Slot d) := + let e := Equiv.piSplitAt j (fun _ : Fin d => Bool) + let sw : Equiv.Perm (Bool × ({i : Fin d // i ≠ j} → Bool)) := + { toFun := fun x => (x.1 ^^ c x.2, x.2) + invFun := fun x => (x.1 ^^ c x.2, x.2) + left_inv := fun x => by simp + right_inv := fun x => by simp } + e.trans (sw.trans e.symm) + +abbrev SweepCoins (d : ℕ) := + (j : Fin d) → ({i : Fin d // i ≠ j} → Bool) → Bool + +/-- The coordinate layers are applied in increasing coordinate order. -/ +def binarySweep (d : ℕ) (c : SweepCoins d) : Equiv.Perm (Slot d) := + (List.ofFn (fun j => coordinateLayer d j (c j))).reverse.prod + +def finiteLaw {Ω G : Type*} [Fintype Ω] [Fintype G] (f : Ω → G) (g : G) : ℝ := by + classical + exact ∑ ω, if f ω = g then (Fintype.card Ω : ℝ)⁻¹ else 0 + +/-- Half the unnormalized sum of absolute probability-mass differences. -/ +def totalVariation {G : Type*} [Fintype G] (p q : G → ℝ) : ℝ := + (1 / ((2 : ℕ) : ℝ)) * ∑ g, |p g - q g| + +def uniformLaw (G : Type*) [Fintype G] : G → ℝ := + fun _ => (Fintype.card G : ℝ)⁻¹ + +def binaryLaw (d : ℕ) : Equiv.Perm (Slot d) → ℝ := + finiteLaw (binarySweep d) + +abbrev RepSpace (D : ℕ) := EuclideanSpace ℂ (Fin D) + +def IsUnitaryRep {G : Type*} [Monoid G] + {D : ℕ} (ρ : Representation ℂ G (RepSpace D)) : Prop := + ∀ g x, ‖ρ g x‖ = ‖x‖ + +def averageOperator {G : Type*} [Fintype G] [Monoid G] {D : ℕ} + (p : G → ℝ) (ρ : Representation ℂ G (RepSpace D)) : + RepSpace D →L[ℂ] RepSpace D := + LinearMap.toContinuousLinearMap (∑ g, (p g : ℂ) • ρ g) + +def BinaryContractionTarget : Prop := + ∃ g : ℝ, 0 < g ∧ ∃ d₀ : ℕ, ∀ d ≥ d₀, ∀ D : ℕ, + ∀ ρ : Representation ℂ (Equiv.Perm (Slot d)) (RepSpace D), + ρ.IsIrreducible → IsUnitaryRep ρ → + ‖averageOperator (binaryLaw d) ρ‖ ≤ (D : ℝ) ^ (-g) + +def realSign {α : Type*} [Fintype α] [DecidableEq α] : Equiv.Perm α →* ℝ := + (Int.castRingHom ℝ).toMonoidHom.comp ((Units.coeHom ℤ).comp Equiv.Perm.sign) + +section FiniteLaws +variable {G : Type*} [Fintype G] [Group G] + +def convolution (p q : G → ℝ) (g : G) : ℝ := ∑ x, p x * q (x⁻¹ * g) + +def pointMassOne (g : G) : ℝ := by + classical + exact if g = 1 then 1 else 0 + +/-- The law of independent repetitions, with the empty product at the identity. -/ +def convolutionPower (p : G → ℝ) : ℕ → G → ℝ + | 0 => pointMassOne + | n + 1 => convolution p (convolutionPower p n) + +end FiniteLaws + +def sweepLaw (d t : ℕ) : Equiv.Perm (Slot d) → ℝ := + convolutionPower (binaryLaw d) t + +/-- A single number of sweeps works uniformly over deterministic initial decks. -/ +def UniformSweepMixingTarget : Prop := + ∃ w : ℕ, ∀ ε : ℝ, 0 < ε → ∃ d₀ : ℕ, ∀ d ≥ d₀, + ∀ τ : Equiv.Perm (Slot d), + totalVariation (fun g => sweepLaw d w (g * τ⁻¹)) + (uniformLaw (Equiv.Perm (Slot d))) ≤ ε + +end BinaryCoordinateSweeps +end + +open scoped BigOperators + +theorem binary_sweep_contraction_and_mixing : + BinaryCoordinateSweeps.BinaryContractionTarget ∧ + (∀ d : ℕ, 0 < d → ∑ g : Equiv.Perm (BinaryCoordinateSweeps.Slot d), + BinaryCoordinateSweeps.binaryLaw d g * BinaryCoordinateSweeps.realSign g = 0) ∧ + BinaryCoordinateSweeps.UniformSweepMixingTarget := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BinarySweep.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.binary_sweep_contraction_and_mixing` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/binary-sweep/solution/closure.txt b/tasks/binary-sweep/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3bb5035bc64f28937175f62bd06d6b701f1c138c --- /dev/null +++ b/tasks/binary-sweep/solution/closure.txt @@ -0,0 +1,192 @@ +OAI.Probability.BinarySweep.Analytic.AnalyticTransfer +OAI.Probability.BinarySweep.Analytic.ComplexGrid +OAI.Probability.BinarySweep.Analytic.FiniteAverageGap +OAI.Probability.BinarySweep.Analytic.OneAxis +OAI.Probability.BinarySweep.Analytic.OneAxisBase +OAI.Probability.BinarySweep.Analytic.OneAxisPerturbation +OAI.Probability.BinarySweep.Conditional.AugmentedBlock +OAI.Probability.BinarySweep.Conditional.AugmentedComplement +OAI.Probability.BinarySweep.Conditional.ComplementBlocks +OAI.Probability.BinarySweep.Conditional.ConditionalAverage +OAI.Probability.BinarySweep.Conditional.ConditionalSign +OAI.Probability.BinarySweep.Conditional.ConditionalSpecht +OAI.Probability.BinarySweep.Conditional.CycleAugmentation +OAI.Probability.BinarySweep.Conditional.MainEasyCases +OAI.Probability.BinarySweep.Conditional.MainMomentInterface +OAI.Probability.BinarySweep.Conditional.MomentOperatorBound +OAI.Probability.BinarySweep.Conditional.Placement +OAI.Probability.BinarySweep.Conditional.PlacementAlternation +OAI.Probability.BinarySweep.Conditional.PlacementBlocks +OAI.Probability.BinarySweep.Conditional.PlacementCycleMoment +OAI.Probability.BinarySweep.Conditional.WeightedCycle +OAI.Probability.BinarySweep.FiniteLaws.ActiveTypes +OAI.Probability.BinarySweep.FiniteLaws.AssignmentSign +OAI.Probability.BinarySweep.FiniteLaws.BitBlocks +OAI.Probability.BinarySweep.FiniteLaws.CyclicHolder +OAI.Probability.BinarySweep.FiniteLaws.FiniteLawAverage +OAI.Probability.BinarySweep.FiniteLaws.FiniteProductProbability +OAI.Probability.BinarySweep.FiniteLaws.HilbertMainCases +OAI.Probability.BinarySweep.FiniteLaws.HilbertTranspose +OAI.Probability.BinarySweep.FiniteLaws.IndependentOperator +OAI.Probability.BinarySweep.FiniteLaws.IndependentPush +OAI.Probability.BinarySweep.FiniteLaws.LightLineBound +OAI.Probability.BinarySweep.FiniteLaws.LinearEvenMoment +OAI.Probability.BinarySweep.FiniteLaws.MomentBounds +OAI.Probability.BinarySweep.FiniteLaws.OccurrenceMoment +OAI.Probability.BinarySweep.FiniteLaws.OneCard +OAI.Probability.BinarySweep.FiniteLaws.PiCentrality +OAI.Probability.BinarySweep.FiniteLaws.QuantitativeMoment +OAI.Probability.BinarySweep.FiniteLaws.RemainingSign +OAI.Probability.BinarySweep.FiniteLaws.SampleMoment +OAI.Probability.BinarySweep.FiniteLaws.SoutheastDimension +OAI.Probability.BinarySweep.FiniteLaws.SumDite +OAI.Probability.BinarySweep.FiniteLaws.UniformFiniteProbability +OAI.Probability.BinarySweep.GridBounds.BalancedGrid +OAI.Probability.BinarySweep.GridBounds.BoardLaw +OAI.Probability.BinarySweep.GridBounds.BoardOverlap +OAI.Probability.BinarySweep.GridBounds.BoardProduct +OAI.Probability.BinarySweep.GridBounds.DenseAssembly +OAI.Probability.BinarySweep.GridBounds.DenseClosing +OAI.Probability.BinarySweep.GridBounds.DiagonalDimension +OAI.Probability.BinarySweep.GridBounds.DiagonalRigidity +OAI.Probability.BinarySweep.GridBounds.EmptyGrid +OAI.Probability.BinarySweep.GridBounds.GridBoardAverage +OAI.Probability.BinarySweep.GridBounds.GridChildAverage +OAI.Probability.BinarySweep.GridBounds.GridDenseCost +OAI.Probability.BinarySweep.GridBounds.GridLaw +OAI.Probability.BinarySweep.GridBounds.GridProjectedMoment +OAI.Probability.BinarySweep.GridBounds.GridSplit +OAI.Probability.BinarySweep.GridBounds.GridSplitCost +OAI.Probability.BinarySweep.GridBounds.GridSplitFree +OAI.Probability.BinarySweep.GridBounds.GridSplitSweep +OAI.Probability.BinarySweep.GridBounds.GridSplitWeights +OAI.Probability.BinarySweep.GridBounds.GroupedLogBounds +OAI.Probability.BinarySweep.GridBounds.GroupedMoments +OAI.Probability.BinarySweep.GridBounds.GroupedTypes +OAI.Probability.BinarySweep.GridBounds.GroupingGeometry +OAI.Probability.BinarySweep.GridBounds.ProjectionSplitting +OAI.Probability.BinarySweep.Main +OAI.Probability.BinarySweep.MatrixBounds.BlockTrace +OAI.Probability.BinarySweep.MatrixBounds.CenteredMatrix +OAI.Probability.BinarySweep.MatrixBounds.FourierTrace +OAI.Probability.BinarySweep.MatrixBounds.HilbertBlockTrace +OAI.Probability.BinarySweep.MatrixBounds.MatrixProjection +OAI.Probability.BinarySweep.MatrixBounds.MatrixRegularize +OAI.Probability.BinarySweep.MatrixBounds.MatrixSqrtBlocks +OAI.Probability.BinarySweep.MatrixBounds.PositiveTraceRestriction +OAI.Probability.BinarySweep.MatrixBounds.SchattenBasic +OAI.Probability.BinarySweep.MatrixBounds.SchattenBounds +OAI.Probability.BinarySweep.MatrixBounds.SchattenTriangle +OAI.Probability.BinarySweep.MatrixBounds.SparsePinching +OAI.Probability.BinarySweep.MatrixBounds.SpectralMoment +OAI.Probability.BinarySweep.MatrixBounds.SymmetricDensity +OAI.Probability.BinarySweep.MatrixBounds.TraceConvex +OAI.Probability.BinarySweep.MatrixBounds.TraceDensityComparison +OAI.Probability.BinarySweep.MatrixBounds.TraceHolder +OAI.Probability.BinarySweep.MatrixBounds.TraceInterpolation +OAI.Probability.BinarySweep.MatrixBounds.Whitening +OAI.Probability.BinarySweep.Mixing.BinaryContraction +OAI.Probability.BinarySweep.Mixing.BinaryLineDisk +OAI.Probability.BinarySweep.Mixing.BinaryMixingBounds +OAI.Probability.BinarySweep.Mixing.BinarySplitChoices +OAI.Probability.BinarySweep.Mixing.DimensionSeries +OAI.Probability.BinarySweep.Mixing.LongRowDimension +OAI.Probability.BinarySweep.Mixing.ShapeDimension +OAI.Probability.BinarySweep.Model +OAI.Probability.BinarySweep.Processes.AssignmentWeight +OAI.Probability.BinarySweep.Processes.Basic +OAI.Probability.BinarySweep.Processes.CoordinateLayerEdgeSwap +OAI.Probability.BinarySweep.Processes.GridSweepPath +OAI.Probability.BinarySweep.Processes.IndependentHistory +OAI.Probability.BinarySweep.Processes.LocalPathWeight +OAI.Probability.BinarySweep.Processes.PointMassOne +OAI.Probability.BinarySweep.Processes.SupportTimeBoundBounds +OAI.Probability.BinarySweep.Representations.CharacterComplete +OAI.Probability.BinarySweep.Representations.FiniteUnitaryAverage +OAI.Probability.BinarySweep.Representations.IrrepSupport +OAI.Probability.BinarySweep.Representations.IrrepTransport +OAI.Probability.BinarySweep.Representations.IsotypicCentrality +OAI.Probability.BinarySweep.Representations.IsotypicDensity +OAI.Probability.BinarySweep.Representations.IsotypicMoment +OAI.Probability.BinarySweep.Representations.IsotypicOrthogonal +OAI.Probability.BinarySweep.Representations.IsotypicProjectionMoment +OAI.Probability.BinarySweep.Representations.IsotypicSpectral +OAI.Probability.BinarySweep.Representations.IsotypicTrace +OAI.Probability.BinarySweep.Representations.MatrixIsotypicWhitening +OAI.Probability.BinarySweep.Representations.MultiplicityBound +OAI.Probability.BinarySweep.Representations.UnitaryTransport +OAI.Probability.BinarySweep.SparseBounds.CenteredLineMoment +OAI.Probability.BinarySweep.SparseBounds.CenteredMoment +OAI.Probability.BinarySweep.SparseBounds.CenteredPlacement +OAI.Probability.BinarySweep.SparseBounds.CenteredReindex +OAI.Probability.BinarySweep.SparseBounds.ConditionalCentered +OAI.Probability.BinarySweep.SparseBounds.FewSparse +OAI.Probability.BinarySweep.SparseBounds.FewSparseBases +OAI.Probability.BinarySweep.SparseBounds.FewSparseNumerics +OAI.Probability.BinarySweep.SparseBounds.ManySparse +OAI.Probability.BinarySweep.SparseBounds.SparseAmplitude +OAI.Probability.BinarySweep.SparseBounds.SparseKernel +OAI.Probability.BinarySweep.SparseBounds.SparseNumerics +OAI.Probability.BinarySweep.SparseBounds.SparseReduction +OAI.Probability.BinarySweep.SparseBounds.SparseSignGeometry +OAI.Probability.BinarySweep.TensorBounds.BlockTypes +OAI.Probability.BinarySweep.TensorBounds.EmpiricalTensor +OAI.Probability.BinarySweep.TensorBounds.EvenPostselection +OAI.Probability.BinarySweep.TensorBounds.PiTensorMatrices +OAI.Probability.BinarySweep.TensorBounds.SignedBlock +OAI.Probability.BinarySweep.TensorBounds.SignedBlocks +OAI.Probability.BinarySweep.TensorBounds.SignedCommutant +OAI.Probability.BinarySweep.TensorBounds.SignedConjugation +OAI.Probability.BinarySweep.TensorBounds.SignedPinching +OAI.Probability.BinarySweep.TensorBounds.SignedPlacement +OAI.Probability.BinarySweep.TensorBounds.SignedTypeCentrality +OAI.Probability.BinarySweep.TensorBounds.SignedWhitening +OAI.Probability.BinarySweep.TensorBounds.TensorPhases +OAI.Probability.BinarySweep.TensorBounds.TensorProductMatrices +OAI.Probability.BinarySweep.TensorBounds.TensorReduction +OAI.Probability.BinarySweep.TensorBounds.TypeMass +OAI.Probability.BinarySweep.Trajectories.EndpointEntryBound +OAI.Probability.BinarySweep.Trajectories.EndpointEvents +OAI.Probability.BinarySweep.Trajectories.EndpointFactors +OAI.Probability.BinarySweep.Trajectories.EndpointGood +OAI.Probability.BinarySweep.Trajectories.EndpointOccupancy +OAI.Probability.BinarySweep.Trajectories.EndpointPlacement +OAI.Probability.BinarySweep.Trajectories.EndpointValidity +OAI.Probability.BinarySweep.Trajectories.FallingMoment +OAI.Probability.BinarySweep.Trajectories.IsolatedCancellation +OAI.Probability.BinarySweep.Trajectories.PathExtension +OAI.Probability.BinarySweep.Trajectories.PathMomentMixed +OAI.Probability.BinarySweep.Trajectories.PathSign +OAI.Probability.BinarySweep.Trajectories.PathTelescope +OAI.Probability.BinarySweep.Trajectories.SharingProbability +OAI.Probability.BinarySweep.Trajectories.SharingWitness +OAI.Probability.BinarySweep.Trajectories.SparseOccupancy +OAI.Probability.BinarySweep.Trajectories.Trajectory +OAI.Probability.BinarySweep.Trajectories.TrajectoryComplement +OAI.Probability.BinarySweep.YoungTheory.CoindFibers +OAI.Probability.BinarySweep.YoungTheory.CoinductionTools +OAI.Probability.BinarySweep.YoungTheory.CutBranching +OAI.Probability.BinarySweep.YoungTheory.CutColumns +OAI.Probability.BinarySweep.YoungTheory.CutTensor +OAI.Probability.BinarySweep.YoungTheory.GenericHookAux +OAI.Probability.BinarySweep.YoungTheory.HookCut +OAI.Probability.BinarySweep.YoungTheory.HookHilbertOccurrence +OAI.Probability.BinarySweep.YoungTheory.HookInducedMoment +OAI.Probability.BinarySweep.YoungTheory.HookScalar +OAI.Probability.BinarySweep.YoungTheory.HookWord +OAI.Probability.BinarySweep.YoungTheory.KoszulBlocks +OAI.Probability.BinarySweep.YoungTheory.PhysicalHookInduced +OAI.Probability.BinarySweep.YoungTheory.YoungAnti +OAI.Probability.BinarySweep.YoungTheory.YoungClassification +OAI.Probability.BinarySweep.YoungTheory.YoungDimensionLower +OAI.Probability.BinarySweep.YoungTheory.YoungDominance +OAI.Probability.BinarySweep.YoungTheory.YoungFactor +OAI.Probability.BinarySweep.YoungTheory.YoungFinite +OAI.Probability.BinarySweep.YoungTheory.YoungHilbert +OAI.Probability.BinarySweep.YoungTheory.YoungInducedMap +OAI.Probability.BinarySweep.YoungTheory.YoungPartition +OAI.Probability.BinarySweep.YoungTheory.YoungPlacement +OAI.Probability.BinarySweep.YoungTheory.YoungResolution +OAI.Probability.BinarySweep.YoungTheory.YoungSpecht +OAI.Probability.BinarySweep.YoungTheory.YoungTabloid +OAI.Probability.BinarySweep.YoungTheory.YoungTranspose diff --git a/tasks/binary-sweep/solution/reference.py b/tasks/binary-sweep/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/binary-sweep/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/binary-sweep/solution/solve.sh b/tasks/binary-sweep/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..815f2f0a485f14538a0f8716f38fe05dd3b2c576 --- /dev/null +++ b/tasks/binary-sweep/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BinarySweep, i.e. module OAI.Probability.BinarySweep.Main and the +# 192 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.BinarySweep.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BinarySweep" diff --git a/tasks/binary-sweep/task.toml b/tasks/binary-sweep/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e83e1149213d72ae488efce6ca9692d6198aa999 --- /dev/null +++ b/tasks/binary-sweep/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/binary-sweep" +version = "1.0.0" +description = "Prove BinarySweep (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BinarySweep.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BinarySweep" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.binary_sweep_contraction_and_mixing"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.BinarySweep.Main" +reference_modules = 192 +reference_lean_bytes = 1151658 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1210 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12736 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/binary-sweep/tests/Challenge.lean b/tasks/binary-sweep/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f048a330b5cf939470368bbf59fe133c7ad9f8cc --- /dev/null +++ b/tasks/binary-sweep/tests/Challenge.lean @@ -0,0 +1,102 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators +namespace BinaryCoordinateSweeps + +/-- The positions of a binary deck of dimension d. -/ +abbrev Slot (d : ℕ) := Fin d → Bool + +/-- Independent switches on the edges parallel to one coordinate. -/ +def coordinateLayer (d : ℕ) (j : Fin d) + (c : (({i : Fin d // i ≠ j} → Bool)) → Bool) : Equiv.Perm (Slot d) := + let e := Equiv.piSplitAt j (fun _ : Fin d => Bool) + let sw : Equiv.Perm (Bool × ({i : Fin d // i ≠ j} → Bool)) := + { toFun := fun x => (x.1 ^^ c x.2, x.2) + invFun := fun x => (x.1 ^^ c x.2, x.2) + left_inv := fun x => by simp + right_inv := fun x => by simp } + e.trans (sw.trans e.symm) + +abbrev SweepCoins (d : ℕ) := + (j : Fin d) → ({i : Fin d // i ≠ j} → Bool) → Bool + +/-- The coordinate layers are applied in increasing coordinate order. -/ +def binarySweep (d : ℕ) (c : SweepCoins d) : Equiv.Perm (Slot d) := + (List.ofFn (fun j => coordinateLayer d j (c j))).reverse.prod + +def finiteLaw {Ω G : Type*} [Fintype Ω] [Fintype G] (f : Ω → G) (g : G) : ℝ := by + classical + exact ∑ ω, if f ω = g then (Fintype.card Ω : ℝ)⁻¹ else 0 + +/-- Half the unnormalized sum of absolute probability-mass differences. -/ +def totalVariation {G : Type*} [Fintype G] (p q : G → ℝ) : ℝ := + (1 / ((2 : ℕ) : ℝ)) * ∑ g, |p g - q g| + +def uniformLaw (G : Type*) [Fintype G] : G → ℝ := + fun _ => (Fintype.card G : ℝ)⁻¹ + +def binaryLaw (d : ℕ) : Equiv.Perm (Slot d) → ℝ := + finiteLaw (binarySweep d) + +abbrev RepSpace (D : ℕ) := EuclideanSpace ℂ (Fin D) + +def IsUnitaryRep {G : Type*} [Monoid G] + {D : ℕ} (ρ : Representation ℂ G (RepSpace D)) : Prop := + ∀ g x, ‖ρ g x‖ = ‖x‖ + +def averageOperator {G : Type*} [Fintype G] [Monoid G] {D : ℕ} + (p : G → ℝ) (ρ : Representation ℂ G (RepSpace D)) : + RepSpace D →L[ℂ] RepSpace D := + LinearMap.toContinuousLinearMap (∑ g, (p g : ℂ) • ρ g) + +def BinaryContractionTarget : Prop := + ∃ g : ℝ, 0 < g ∧ ∃ d₀ : ℕ, ∀ d ≥ d₀, ∀ D : ℕ, + ∀ ρ : Representation ℂ (Equiv.Perm (Slot d)) (RepSpace D), + ρ.IsIrreducible → IsUnitaryRep ρ → + ‖averageOperator (binaryLaw d) ρ‖ ≤ (D : ℝ) ^ (-g) + +def realSign {α : Type*} [Fintype α] [DecidableEq α] : Equiv.Perm α →* ℝ := + (Int.castRingHom ℝ).toMonoidHom.comp ((Units.coeHom ℤ).comp Equiv.Perm.sign) + +section FiniteLaws +variable {G : Type*} [Fintype G] [Group G] + +def convolution (p q : G → ℝ) (g : G) : ℝ := ∑ x, p x * q (x⁻¹ * g) + +def pointMassOne (g : G) : ℝ := by + classical + exact if g = 1 then 1 else 0 + +/-- The law of independent repetitions, with the empty product at the identity. -/ +def convolutionPower (p : G → ℝ) : ℕ → G → ℝ + | 0 => pointMassOne + | n + 1 => convolution p (convolutionPower p n) + +end FiniteLaws + +def sweepLaw (d t : ℕ) : Equiv.Perm (Slot d) → ℝ := + convolutionPower (binaryLaw d) t + +/-- A single number of sweeps works uniformly over deterministic initial decks. -/ +def UniformSweepMixingTarget : Prop := + ∃ w : ℕ, ∀ ε : ℝ, 0 < ε → ∃ d₀ : ℕ, ∀ d ≥ d₀, + ∀ τ : Equiv.Perm (Slot d), + totalVariation (fun g => sweepLaw d w (g * τ⁻¹)) + (uniformLaw (Equiv.Perm (Slot d))) ≤ ε + +end BinaryCoordinateSweeps +end + +open scoped BigOperators + +theorem binary_sweep_contraction_and_mixing : + BinaryCoordinateSweeps.BinaryContractionTarget ∧ + (∀ d : ℕ, 0 < d → ∑ g : Equiv.Perm (BinaryCoordinateSweeps.Slot d), + BinaryCoordinateSweeps.binaryLaw d g * BinaryCoordinateSweeps.realSign g = 0) ∧ + BinaryCoordinateSweeps.UniformSweepMixingTarget := by + sorry + +end OAI diff --git a/tasks/binary-sweep/tests/grade.py b/tasks/binary-sweep/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/binary-sweep/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/binary-sweep/tests/task.json b/tasks/binary-sweep/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..638a0af8644f367267502cebf0345165a81ce585 --- /dev/null +++ b/tasks/binary-sweep/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BinarySweep", + "comparator": { + "theorem_names": [ + "OAI.binary_sweep_contraction_and_mixing" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11836 +} \ No newline at end of file diff --git a/tasks/binary-sweep/tests/test.sh b/tasks/binary-sweep/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/binary-sweep/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bipartite-crossing/environment/Dockerfile b/tasks/bipartite-crossing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bipartite-crossing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bipartite-crossing/environment/fetch_mathlib.sh b/tasks/bipartite-crossing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bipartite-crossing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bipartite-crossing/environment/lake-manifest.json b/tasks/bipartite-crossing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bipartite-crossing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bipartite-crossing/environment/lakefile.lean b/tasks/bipartite-crossing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bipartite-crossing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bipartite-crossing/environment/lean_setup.sh b/tasks/bipartite-crossing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bipartite-crossing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bipartite-crossing/environment/pack_submission.py b/tasks/bipartite-crossing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bipartite-crossing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bipartite-crossing/instruction.md b/tasks/bipartite-crossing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f00a0509e14b4cfdb9b36eeb569f72e5313d11f2 --- /dev/null +++ b/tasks/bipartite-crossing/instruction.md @@ -0,0 +1,118 @@ +# openai/math challenge `BipartiteCrossing` (family 165) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 165 of the release, *Exact crossing numbers of complete and complete bipartite graphs* +(Combinatorics). The family as a whole: Resolves the Harary–Hill conjecture and Turan's brickyard problem in the Zarankiewicz formulation, determining the crossing numbers of every complete and complete bipartite graph. The result proves the optimality of the classical drawings among all plane drawings with continuous edge arcs. + +The challenge is `BipartiteCrossing`, also at `/opt/openai-math/challenges/BipartiteCrossing.lean`: + +```lean +import Mathlib.Topology.Path +import Mathlib.Topology.OpenPartialHomeomorph.Defs +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Data.Set.Finite.Basic +import Mathlib.Data.Finset.Attr +import Mathlib.Tactic.Common +import Mathlib.Tactic.Finiteness.Attr +import Mathlib.Tactic.SetLike +import Mathlib.Util.CompileInductive + +namespace OAI + +noncomputable section + +namespace Zarankiewicz + +def axisPairs (r : ℕ) : ℕ := (r/2) * ((r-1)/2) + + +abbrev Plane := ℝ × ℝ +abbrev BipartiteVertex (m n : ℕ) := Fin m ⊕ Fin n +abbrev BipartiteEdge (m n : ℕ) := Fin m × Fin n + +structure ContinuousDrawing (m n : ℕ) where + vertex : BipartiteVertex m n → Plane + vertex_injective : Function.Injective vertex + edge : ∀ e : BipartiteEdge m n, Path (vertex (.inl e.1)) (vertex (.inr e.2)) + edge_injective : ∀ e, Function.Injective (edge e) + interior_avoids_vertices : ∀ e t, t ∈ Set.Ioo (0 : unitInterval) 1 → + ∀ v, edge e t ≠ vertex v + +def edgeInterior {m n : ℕ} (D : ContinuousDrawing m n) (e : BipartiteEdge m n) : Set Plane := + D.edge e '' Set.Ioo (0 : unitInterval) 1 + +def ProperCrossing (A B : Set Plane) (x : Plane) : Prop := + ∃ chart : OpenPartialHomeomorph Plane Plane, + x ∈ chart.source ∧ chart x = (0,0) ∧ + chart '' (chart.source ∩ A) = chart.target ∩ {y | y.2 = 0} ∧ + chart '' (chart.source ∩ B) = chart.target ∩ {y | y.1 = 0} + +def crossingPoints {m n : ℕ} (D : ContinuousDrawing m n) : Set Plane := + {x | ∃ e f : BipartiteEdge m n, e ≠ f ∧ x ∈ edgeInterior D e ∧ x ∈ edgeInterior D f} + +structure AdmissibleDrawing (m n : ℕ) extends ContinuousDrawing m n where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + crossings_proper : ∀ e f, e ≠ f → ∀ x, + x ∈ edgeInterior toContinuousDrawing e → x ∈ edgeInterior toContinuousDrawing f → + ProperCrossing (edgeInterior toContinuousDrawing e) (edgeInterior toContinuousDrawing f) x + no_triples : ∀ e f g, e ≠ f → e ≠ g → f ≠ g → + edgeInterior toContinuousDrawing e ∩ edgeInterior toContinuousDrawing f ∩ + edgeInterior toContinuousDrawing g = ∅ + +def crossingCount {m n : ℕ} (D : AdmissibleDrawing m n) : ℕ := D.crossings_finite.toFinset.card + +def MainTarget : Prop := + ∀ m n : ℕ, 0 < m → 0 < n → + (∃ D : AdmissibleDrawing m n, crossingCount D = axisPairs m * axisPairs n) ∧ + (∀ D : AdmissibleDrawing m n, axisPairs m * axisPairs n ≤ crossingCount D) + +theorem mainTarget_proof : MainTarget := by + sorry + +end Zarankiewicz + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BipartiteCrossing.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Zarankiewicz.mainTarget_proof` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bipartite-crossing/solution/closure.txt b/tasks/bipartite-crossing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c77f33764212b470d2a5dfe11554e965f9cc1ba --- /dev/null +++ b/tasks/bipartite-crossing/solution/closure.txt @@ -0,0 +1,339 @@ +OAI.Combinatorics.Crossing.AdaptedFamily +OAI.Combinatorics.Crossing.AdditiveBlockRelation +OAI.Combinatorics.Crossing.AdjacentSurgeryDrawing +OAI.Combinatorics.Crossing.AdjacentSurgeryPointRemoval +OAI.Combinatorics.Crossing.AdjacentSurgeryRoutes +OAI.Combinatorics.Crossing.AdmissibleAdjacentSurgery +OAI.Combinatorics.Crossing.AffineIntervalRestriction +OAI.Combinatorics.Crossing.AffinePathHalves +OAI.Combinatorics.Crossing.AffineSideEvents +OAI.Combinatorics.Crossing.AffineSubdivisionRefinement +OAI.Combinatorics.Crossing.AlternatingPaths +OAI.Combinatorics.Crossing.ArcRangeMinimality +OAI.Combinatorics.Crossing.AssembledAdmissibleDrawing +OAI.Combinatorics.Crossing.AssembledContinuousDrawing +OAI.Combinatorics.Crossing.AssembledCrossings +OAI.Combinatorics.Crossing.AssembledEdge +OAI.Combinatorics.Crossing.AssembledNoTriples +OAI.Combinatorics.Crossing.AssembledPortIncidence +OAI.Combinatorics.Crossing.AxisAdmissibility +OAI.Combinatorics.Crossing.AxisConcurrency +OAI.Combinatorics.Crossing.AxisContinuousDrawing +OAI.Combinatorics.Crossing.AxisCrossingOrder +OAI.Combinatorics.Crossing.AxisFiniteCrossings +OAI.Combinatorics.Crossing.AxisGenericPositions +OAI.Combinatorics.Crossing.AxisSegments +OAI.Combinatorics.Crossing.BalancedAxisCrossingCount +OAI.Combinatorics.Crossing.BalancedAxisDrawing +OAI.Combinatorics.Crossing.BalancedAxisIntervals +OAI.Combinatorics.Crossing.BalancedRayPairs +OAI.Combinatorics.Crossing.BipartiteDartGeometry +OAI.Combinatorics.Crossing.Bivariate +OAI.Combinatorics.Crossing.BivariateCoefficients +OAI.Combinatorics.Crossing.BoundaryCollar +OAI.Combinatorics.Crossing.ChainPieceInteriors +OAI.Combinatorics.Crossing.ChainTracePieces +OAI.Combinatorics.Crossing.ChordEdgeIntersections +OAI.Combinatorics.Crossing.ChordExteriorSeparation +OAI.Combinatorics.Crossing.ChordOrientations +OAI.Combinatorics.Crossing.ChordPairing +OAI.Combinatorics.Crossing.ChordTransversality +OAI.Combinatorics.Crossing.CircleChords +OAI.Combinatorics.Crossing.CircleConnectors +OAI.Combinatorics.Crossing.CircleDeterminantOrder +OAI.Combinatorics.Crossing.CircleOffset +OAI.Combinatorics.Crossing.CircleOffsetLine +OAI.Combinatorics.Crossing.CircleOffsetParameter +OAI.Combinatorics.Crossing.CircleParameterChart +OAI.Combinatorics.Crossing.ClosedPolygonIntersection +OAI.Combinatorics.Crossing.CollinearSegmentUnion +OAI.Combinatorics.Crossing.CompactCorridors +OAI.Combinatorics.Crossing.ConeIntersection +OAI.Combinatorics.Crossing.ConnectorOtherDisks +OAI.Combinatorics.Crossing.ConnectorSupportingLines +OAI.Combinatorics.Crossing.ConnectorTrackAvoidance +OAI.Combinatorics.Crossing.ConstructAdjacentSurgery +OAI.Combinatorics.Crossing.CrossingCoordinates +OAI.Combinatorics.Crossing.CrossingCutWalks +OAI.Combinatorics.Crossing.CrossingDiskCount +OAI.Combinatorics.Crossing.CrossingDiskIncidence +OAI.Combinatorics.Crossing.CrossingDiskNeighborhood +OAI.Combinatorics.Crossing.CrossingDiskOwners +OAI.Combinatorics.Crossing.CrossingDiskUniqueness +OAI.Combinatorics.Crossing.CrossingIncidence +OAI.Combinatorics.Crossing.CrossingPortClearance +OAI.Combinatorics.Crossing.CrossingReconnection +OAI.Combinatorics.Crossing.CrossingSurgeryGraph +OAI.Combinatorics.Crossing.CurveDiskIsolation +OAI.Combinatorics.Crossing.CutTraceSeparation +OAI.Combinatorics.Crossing.CutVertexAvoidance +OAI.Combinatorics.Crossing.CycleBlockIntersections +OAI.Combinatorics.Crossing.CycleEndpointSum +OAI.Combinatorics.Crossing.CycleMatrixBlocks +OAI.Combinatorics.Crossing.CyclePairing +OAI.Combinatorics.Crossing.CyclicSumArithmetic +OAI.Combinatorics.Crossing.CyclicWalkDarts +OAI.Combinatorics.Crossing.DartCyclePaths +OAI.Combinatorics.Crossing.DartPairIntersections +OAI.Combinatorics.Crossing.DartPathRealizations +OAI.Combinatorics.Crossing.DegreeCounting +OAI.Combinatorics.Crossing.DeletionCount +OAI.Combinatorics.Crossing.DetectorAnnihilation +OAI.Combinatorics.Crossing.DetectorCrossingBound +OAI.Combinatorics.Crossing.DetectorRank +OAI.Combinatorics.Crossing.DetectorRelabeling +OAI.Combinatorics.Crossing.DiskFillingContainment +OAI.Combinatorics.Crossing.DiskPassage +OAI.Combinatorics.Crossing.DiskSegments +OAI.Combinatorics.Crossing.DrawingDefinition +OAI.Combinatorics.Crossing.DrawingDeletion +OAI.Combinatorics.Crossing.DrawingDiskIsolation +OAI.Combinatorics.Crossing.DrawingEdgeWalk +OAI.Combinatorics.Crossing.DrawingEdgeWalkTrace +OAI.Combinatorics.Crossing.DrawingExteriorReplacement +OAI.Combinatorics.Crossing.DrawingMarks +OAI.Combinatorics.Crossing.DrawingPassages +OAI.Combinatorics.Crossing.DrawingPorts +OAI.Combinatorics.Crossing.DrawingRangeCrossings +OAI.Combinatorics.Crossing.DrawingRestriction +OAI.Combinatorics.Crossing.DrawingSegmentIncidence +OAI.Combinatorics.Crossing.DrawingSpokePorts +OAI.Combinatorics.Crossing.DrawingSubdivisionGraph +OAI.Combinatorics.Crossing.DrawingVertexPlacement +OAI.Combinatorics.Crossing.DrawingWalkCutTraces +OAI.Combinatorics.Crossing.DrawnEdgeChains +OAI.Combinatorics.Crossing.EmbeddedGraphPaths +OAI.Combinatorics.Crossing.EndpointFlagPairing +OAI.Combinatorics.Crossing.EndpointVisits +OAI.Combinatorics.Crossing.EvaluationAmbient +OAI.Combinatorics.Crossing.EvenCrossingLowerBound +OAI.Combinatorics.Crossing.ExpectedTrackGeometry +OAI.Combinatorics.Crossing.ExteriorArcReplacement +OAI.Combinatorics.Crossing.ExteriorChordMeeting +OAI.Combinatorics.Crossing.ExteriorCrossingCut +OAI.Combinatorics.Crossing.ExteriorSegmentGraph +OAI.Combinatorics.Crossing.ExteriorSpokeMeeting +OAI.Combinatorics.Crossing.ExtraDrawingSubdivision +OAI.Combinatorics.Crossing.FiniteAffineCover +OAI.Combinatorics.Crossing.FiniteCircleCoordinates +OAI.Combinatorics.Crossing.FiniteConePoint +OAI.Combinatorics.Crossing.FiniteDiskCollar +OAI.Combinatorics.Crossing.FiniteEventualRadius +OAI.Combinatorics.Crossing.FiniteIntersectionDrawing +OAI.Combinatorics.Crossing.FiniteLineAvoidance +OAI.Combinatorics.Crossing.FiniteMovingPoints +OAI.Combinatorics.Crossing.FinitePathChain +OAI.Combinatorics.Crossing.FinitePolygonalComposition +OAI.Combinatorics.Crossing.FiniteScaledRadius +OAI.Combinatorics.Crossing.FiniteSeparation +OAI.Combinatorics.Crossing.FirstLastVisits +OAI.Combinatorics.Crossing.FloorArithmetic +OAI.Combinatorics.Crossing.FourCyclePairing +OAI.Combinatorics.Crossing.FourCycles +OAI.Combinatorics.Crossing.GeneralOrderAveraging +OAI.Combinatorics.Crossing.GeneralSpokeAveraging +OAI.Combinatorics.Crossing.GenericPointExtension +OAI.Combinatorics.Crossing.GenericPointFamily +OAI.Combinatorics.Crossing.GenericPolygonIntersection +OAI.Combinatorics.Crossing.GenericPolynomialBox +OAI.Combinatorics.Crossing.GlobalCycleAveraging +OAI.Combinatorics.Crossing.GlobalCycleIntersection +OAI.Combinatorics.Crossing.GraphSequenceWalk +OAI.Combinatorics.Crossing.GraphWalkRealizationLaws +OAI.Combinatorics.Crossing.GraphWalkTrace +OAI.Combinatorics.Crossing.HalfOrderInvertibility +OAI.Combinatorics.Crossing.HalfOrderReduction +OAI.Combinatorics.Crossing.IncidentSpokePorts +OAI.Combinatorics.Crossing.IndexedMatrixRankSum +OAI.Combinatorics.Crossing.InnerDrawingPassages +OAI.Combinatorics.Crossing.Interpolation +OAI.Combinatorics.Crossing.IntervalSegmentStrict +OAI.Combinatorics.Crossing.IntervalSegments +OAI.Combinatorics.Crossing.LocalLineBends +OAI.Combinatorics.Crossing.LocalSegmentTransversality +OAI.Combinatorics.Crossing.LocallyStraightNormalization +OAI.Combinatorics.Crossing.LocallyTransverseNormalization +OAI.Combinatorics.Crossing.Main +OAI.Combinatorics.Crossing.MarkedCurveDisks +OAI.Combinatorics.Crossing.MatrixGraphs +OAI.Combinatorics.Crossing.MatrixRankBounds +OAI.Combinatorics.Crossing.MatrixRankSum +OAI.Combinatorics.Crossing.MiddleEdgeIncidence +OAI.Combinatorics.Crossing.MiddlePathInjective +OAI.Combinatorics.Crossing.MiddleSpokeMeeting +OAI.Combinatorics.Crossing.MinimumChainGeometry +OAI.Combinatorics.Crossing.MinimumChainVertexPieces +OAI.Combinatorics.Crossing.MovingDiskClearance +OAI.Combinatorics.Crossing.MovingSegmentStability +OAI.Combinatorics.Crossing.NoAdjacentLocalNormalization +OAI.Combinatorics.Crossing.NoAdjacentNormalization +OAI.Combinatorics.Crossing.NodeMoments +OAI.Combinatorics.Crossing.NodeRankLoss +OAI.Combinatorics.Crossing.NormalOffsetExterior +OAI.Combinatorics.Crossing.NormalizedPolygonalDrawing +OAI.Combinatorics.Crossing.OddCrossingLowerBound +OAI.Combinatorics.Crossing.OddNormalizedLowerBound +OAI.Combinatorics.Crossing.OffsetBendSegments +OAI.Combinatorics.Crossing.OffsetSegments +OAI.Combinatorics.Crossing.OffsetTrack +OAI.Combinatorics.Crossing.OffsetVectors +OAI.Combinatorics.Crossing.OpenSegmentEndpoints +OAI.Combinatorics.Crossing.OrderShift +OAI.Combinatorics.Crossing.OrderedAffineSubdivision +OAI.Combinatorics.Crossing.OrderedCrossingPorts +OAI.Combinatorics.Crossing.OrderedExteriorPaths +OAI.Combinatorics.Crossing.OrderedKnotCover +OAI.Combinatorics.Crossing.OrderedNodeIndices +OAI.Combinatorics.Crossing.OrderedPassages +OAI.Combinatorics.Crossing.OrderedPathParts +OAI.Combinatorics.Crossing.OrientedSimilarity +OAI.Combinatorics.Crossing.ParallelDirection +OAI.Combinatorics.Crossing.ParameterNeighborhoods +OAI.Combinatorics.Crossing.PathConcatenationInjective +OAI.Combinatorics.Crossing.PathEndpointNeighborhoods +OAI.Combinatorics.Crossing.PathSubarc +OAI.Combinatorics.Crossing.PeriodicPolygon +OAI.Combinatorics.Crossing.PhysicalCircleAveraging +OAI.Combinatorics.Crossing.PhysicalSpokeAveraging +OAI.Combinatorics.Crossing.PhysicalVertexChords +OAI.Combinatorics.Crossing.PlanarDeterminant +OAI.Combinatorics.Crossing.PlanarSegments +OAI.Combinatorics.Crossing.PolygonComposition +OAI.Combinatorics.Crossing.PolygonStability +OAI.Combinatorics.Crossing.PolygonTransversalityStability +OAI.Combinatorics.Crossing.PolygonalArcInjective +OAI.Combinatorics.Crossing.PolygonalBoundaryReplacement +OAI.Combinatorics.Crossing.PolygonalChainComposition +OAI.Combinatorics.Crossing.PolygonalChainExistence +OAI.Combinatorics.Crossing.PolygonalChainOperations +OAI.Combinatorics.Crossing.PolygonalChainShortcuts +OAI.Combinatorics.Crossing.PolygonalChainTransversality +OAI.Combinatorics.Crossing.PolygonalChains +OAI.Combinatorics.Crossing.PolygonalEndpointCasts +OAI.Combinatorics.Crossing.PolygonalExterior +OAI.Combinatorics.Crossing.PolygonalNormalization +OAI.Combinatorics.Crossing.PolygonalParametrization +OAI.Combinatorics.Crossing.PolygonalParametrizationCover +OAI.Combinatorics.Crossing.PolygonalReach +OAI.Combinatorics.Crossing.PolygonalWalks +OAI.Combinatorics.Crossing.PolynomialCoordinates +OAI.Combinatorics.Crossing.PolynomialFiltration +OAI.Combinatorics.Crossing.PolynomialKernel +OAI.Combinatorics.Crossing.PolynomialLinearMatrix +OAI.Combinatorics.Crossing.PolynomialMinors +OAI.Combinatorics.Crossing.ProperCrossingLocality +OAI.Combinatorics.Crossing.ProperSegmentCrossing +OAI.Combinatorics.Crossing.RadialBoundaryPorts +OAI.Combinatorics.Crossing.RadialExterior +OAI.Combinatorics.Crossing.RankDetector +OAI.Combinatorics.Crossing.RankMultiplicity +OAI.Combinatorics.Crossing.RankSpecialization +OAI.Combinatorics.Crossing.ReconnectedIntersectionCases +OAI.Combinatorics.Crossing.ReconnectedPaths +OAI.Combinatorics.Crossing.ReconnectedPointRemoval +OAI.Combinatorics.Crossing.ReconnectedVertexAvoidance +OAI.Combinatorics.Crossing.ReconnectedWalks +OAI.Combinatorics.Crossing.ReconnectionAvoidance +OAI.Combinatorics.Crossing.ReconnectionChords +OAI.Combinatorics.Crossing.ReconnectionOppositeCuts +OAI.Combinatorics.Crossing.ReconnectionOtherEdges +OAI.Combinatorics.Crossing.ReconnectionVertexAvoidance +OAI.Combinatorics.Crossing.RectangleAlgebra +OAI.Combinatorics.Crossing.ReducedCrossingCorners +OAI.Combinatorics.Crossing.ReducedCrossingTransversality +OAI.Combinatorics.Crossing.ReducedPolygonalPresentation +OAI.Combinatorics.Crossing.ReplaceDrawingEdges +OAI.Combinatorics.Crossing.ReplaceDrawingRangeCases +OAI.Combinatorics.Crossing.RetainedArcDisjointness +OAI.Combinatorics.Crossing.RetainedDrawingArcs +OAI.Combinatorics.Crossing.RoundCircleChords +OAI.Combinatorics.Crossing.RoundDiskChords +OAI.Combinatorics.Crossing.RoundDiskClearance +OAI.Combinatorics.Crossing.RoundDiskVisits +OAI.Combinatorics.Crossing.RowCrossingCount +OAI.Combinatorics.Crossing.SegmentAffineForms +OAI.Combinatorics.Crossing.SegmentAugmentation +OAI.Combinatorics.Crossing.SegmentClosedIncidence +OAI.Combinatorics.Crossing.SegmentContinuity +OAI.Combinatorics.Crossing.SegmentCrossingCoordinates +OAI.Combinatorics.Crossing.SegmentIntersectionUnique +OAI.Combinatorics.Crossing.SegmentParameters +OAI.Combinatorics.Crossing.SegmentSides +OAI.Combinatorics.Crossing.SegmentSymmetries +OAI.Combinatorics.Crossing.SegmentTraversalReversal +OAI.Combinatorics.Crossing.SharedTrackAvoidance +OAI.Combinatorics.Crossing.ShiftedEdgeIntersections +OAI.Combinatorics.Crossing.ShiftedRadialPieces +OAI.Combinatorics.Crossing.ShiftedSegmentStability +OAI.Combinatorics.Crossing.ShiftedTrackDisks +OAI.Combinatorics.Crossing.ShortVertexRadius +OAI.Combinatorics.Crossing.SimilarityCoordinates +OAI.Combinatorics.Crossing.SimultaneousExteriorArcs +OAI.Combinatorics.Crossing.SimultaneousPolygonalReplacement +OAI.Combinatorics.Crossing.SortedMarkedParameters +OAI.Combinatorics.Crossing.SortedSideEvents +OAI.Combinatorics.Crossing.SpokeEndpointSeparation +OAI.Combinatorics.Crossing.SpokePieceIsolation +OAI.Combinatorics.Crossing.SpokeTrackDirections +OAI.Combinatorics.Crossing.StageDegreeBound +OAI.Combinatorics.Crossing.StepEvents +OAI.Combinatorics.Crossing.StraightChainIntersections +OAI.Combinatorics.Crossing.StraightChainTransversality +OAI.Combinatorics.Crossing.SubdivisionPointEndpoints +OAI.Combinatorics.Crossing.SubdivisionSegments +OAI.Combinatorics.Crossing.SublevelExtrema +OAI.Combinatorics.Crossing.SubspaceIntersection +OAI.Combinatorics.Crossing.SubspaceProjection +OAI.Combinatorics.Crossing.SurgeryCrossingContainment +OAI.Combinatorics.Crossing.SurgeryCutWalks +OAI.Combinatorics.Crossing.SurgeryFiniteDrawing +OAI.Combinatorics.Crossing.SurgeryNoTriples +OAI.Combinatorics.Crossing.SurgeryPathWitnesses +OAI.Combinatorics.Crossing.SurgeryRouteIntersections +OAI.Combinatorics.Crossing.SurgeryStrictPointCount +OAI.Combinatorics.Crossing.TangentTrackIdentity +OAI.Combinatorics.Crossing.TrackChordSeparation +OAI.Combinatorics.Crossing.TrackEndpointConnections +OAI.Combinatorics.Crossing.TransversalityStability +OAI.Combinatorics.Crossing.TransversePolygonIntersection +OAI.Combinatorics.Crossing.TriangleEntryExit +OAI.Combinatorics.Crossing.TriangleFactorization +OAI.Combinatorics.Crossing.TriangleOrientations +OAI.Combinatorics.Crossing.TriangleSideEvent +OAI.Combinatorics.Crossing.TriangleTransversality +OAI.Combinatorics.Crossing.TruncatedChainDirections +OAI.Combinatorics.Crossing.TruncatedChainPath +OAI.Combinatorics.Crossing.TruncatedChainVertices +OAI.Combinatorics.Crossing.TruncatedCrossingCorners +OAI.Combinatorics.Crossing.TruncatedCrossingRetention +OAI.Combinatorics.Crossing.TruncatedDrawingDisks +OAI.Combinatorics.Crossing.TruncatedDrawingInteriors +OAI.Combinatorics.Crossing.TruncatedRadialDots +OAI.Combinatorics.Crossing.TruncatedRadialEnds +OAI.Combinatorics.Crossing.TruncatedSegmentTransversality +OAI.Combinatorics.Crossing.TruncatedSignedIntersections +OAI.Combinatorics.Crossing.TruncatedSpokeCoordinates +OAI.Combinatorics.Crossing.TruncatedSpokeDirections +OAI.Combinatorics.Crossing.TruncatedTraceDecomposition +OAI.Combinatorics.Crossing.TruncatedTrackAvoidance +OAI.Combinatorics.Crossing.TruncatedTrackStability +OAI.Combinatorics.Crossing.TwoTriangleBasis +OAI.Combinatorics.Crossing.TwoTriangleIndices +OAI.Combinatorics.Crossing.TwoTriangleUnisolvence +OAI.Combinatorics.Crossing.UniformCrossTypeGeometry +OAI.Combinatorics.Crossing.UniformSpokeRadii +OAI.Combinatorics.Crossing.UniformTrackPerturbation +OAI.Combinatorics.Crossing.UniqueWalkPassage +OAI.Combinatorics.Crossing.VertexChordIntersections +OAI.Combinatorics.Crossing.VertexDiskSpokes +OAI.Combinatorics.Crossing.VertexDisksCrossingFree +OAI.Combinatorics.Crossing.VertexEndpointPorts +OAI.Combinatorics.Crossing.VertexOrderDetector +OAI.Combinatorics.Crossing.VertexPassagePairing +OAI.Combinatorics.Crossing.VertexPieceClearance +OAI.Combinatorics.Crossing.VertexSpokeBounds +OAI.Combinatorics.Crossing.VertexTraceDisks +OAI.Combinatorics.Crossing.VertexTruncation +OAI.Combinatorics.Crossing.VertexTruncationGeometry +OAI.Combinatorics.Crossing.WalkVectorSum +OAI.Combinatorics.Crossing.WeightedGram diff --git a/tasks/bipartite-crossing/solution/reference.py b/tasks/bipartite-crossing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bipartite-crossing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bipartite-crossing/solution/solve.sh b/tasks/bipartite-crossing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0c1b2c4dc40323641ecb43e460d1b209298d1c32 --- /dev/null +++ b/tasks/bipartite-crossing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BipartiteCrossing, i.e. module OAI.Combinatorics.Crossing.Main and the +# 339 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Crossing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BipartiteCrossing" diff --git a/tasks/bipartite-crossing/task.toml b/tasks/bipartite-crossing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..afc2da9aff15c55e9753a648333579dd68d40a18 --- /dev/null +++ b/tasks/bipartite-crossing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bipartite-crossing" +version = "1.0.0" +description = "Prove BipartiteCrossing (openai/math family 165: Exact crossing numbers of complete and complete bipartite graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BipartiteCrossing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BipartiteCrossing" +family = "165" +family_title = "Exact crossing numbers of complete and complete bipartite graphs" +subject = "Combinatorics" +theorems = ["OAI.Zarankiewicz.mainTarget_proof"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Crossing.Main" +reference_modules = 339 +reference_lean_bytes = 893808 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 790 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12504 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bipartite-crossing/tests/Challenge.lean b/tasks/bipartite-crossing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..68c3061f5aa9d7b8d067aa17a007ce67defaae28 --- /dev/null +++ b/tasks/bipartite-crossing/tests/Challenge.lean @@ -0,0 +1,67 @@ +import Mathlib.Topology.Path +import Mathlib.Topology.OpenPartialHomeomorph.Defs +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Data.Set.Finite.Basic +import Mathlib.Data.Finset.Attr +import Mathlib.Tactic.Common +import Mathlib.Tactic.Finiteness.Attr +import Mathlib.Tactic.SetLike +import Mathlib.Util.CompileInductive + +namespace OAI + +noncomputable section + +namespace Zarankiewicz + +def axisPairs (r : ℕ) : ℕ := (r/2) * ((r-1)/2) + + +abbrev Plane := ℝ × ℝ +abbrev BipartiteVertex (m n : ℕ) := Fin m ⊕ Fin n +abbrev BipartiteEdge (m n : ℕ) := Fin m × Fin n + +structure ContinuousDrawing (m n : ℕ) where + vertex : BipartiteVertex m n → Plane + vertex_injective : Function.Injective vertex + edge : ∀ e : BipartiteEdge m n, Path (vertex (.inl e.1)) (vertex (.inr e.2)) + edge_injective : ∀ e, Function.Injective (edge e) + interior_avoids_vertices : ∀ e t, t ∈ Set.Ioo (0 : unitInterval) 1 → + ∀ v, edge e t ≠ vertex v + +def edgeInterior {m n : ℕ} (D : ContinuousDrawing m n) (e : BipartiteEdge m n) : Set Plane := + D.edge e '' Set.Ioo (0 : unitInterval) 1 + +def ProperCrossing (A B : Set Plane) (x : Plane) : Prop := + ∃ chart : OpenPartialHomeomorph Plane Plane, + x ∈ chart.source ∧ chart x = (0,0) ∧ + chart '' (chart.source ∩ A) = chart.target ∩ {y | y.2 = 0} ∧ + chart '' (chart.source ∩ B) = chart.target ∩ {y | y.1 = 0} + +def crossingPoints {m n : ℕ} (D : ContinuousDrawing m n) : Set Plane := + {x | ∃ e f : BipartiteEdge m n, e ≠ f ∧ x ∈ edgeInterior D e ∧ x ∈ edgeInterior D f} + +structure AdmissibleDrawing (m n : ℕ) extends ContinuousDrawing m n where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + crossings_proper : ∀ e f, e ≠ f → ∀ x, + x ∈ edgeInterior toContinuousDrawing e → x ∈ edgeInterior toContinuousDrawing f → + ProperCrossing (edgeInterior toContinuousDrawing e) (edgeInterior toContinuousDrawing f) x + no_triples : ∀ e f g, e ≠ f → e ≠ g → f ≠ g → + edgeInterior toContinuousDrawing e ∩ edgeInterior toContinuousDrawing f ∩ + edgeInterior toContinuousDrawing g = ∅ + +def crossingCount {m n : ℕ} (D : AdmissibleDrawing m n) : ℕ := D.crossings_finite.toFinset.card + +def MainTarget : Prop := + ∀ m n : ℕ, 0 < m → 0 < n → + (∃ D : AdmissibleDrawing m n, crossingCount D = axisPairs m * axisPairs n) ∧ + (∀ D : AdmissibleDrawing m n, axisPairs m * axisPairs n ≤ crossingCount D) + +theorem mainTarget_proof : MainTarget := by + sorry + +end Zarankiewicz + +end + +end OAI diff --git a/tasks/bipartite-crossing/tests/grade.py b/tasks/bipartite-crossing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bipartite-crossing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bipartite-crossing/tests/task.json b/tasks/bipartite-crossing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dfa095f55cb6cb38feb5887fa485156aa503aa42 --- /dev/null +++ b/tasks/bipartite-crossing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BipartiteCrossing", + "comparator": { + "theorem_names": [ + "OAI.Zarankiewicz.mainTarget_proof" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11604 +} \ No newline at end of file diff --git a/tasks/bipartite-crossing/tests/test.sh b/tasks/bipartite-crossing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bipartite-crossing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bogomolov-pop-injectivity/environment/Dockerfile b/tasks/bogomolov-pop-injectivity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bogomolov-pop-injectivity/environment/fetch_mathlib.sh b/tasks/bogomolov-pop-injectivity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bogomolov-pop-injectivity/environment/lake-manifest.json b/tasks/bogomolov-pop-injectivity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bogomolov-pop-injectivity/environment/lakefile.lean b/tasks/bogomolov-pop-injectivity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bogomolov-pop-injectivity/environment/lean_setup.sh b/tasks/bogomolov-pop-injectivity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bogomolov-pop-injectivity/environment/pack_submission.py b/tasks/bogomolov-pop-injectivity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bogomolov-pop-injectivity/instruction.md b/tasks/bogomolov-pop-injectivity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6c244c5f8451549194bdb383ba37fb6d17687a01 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/instruction.md @@ -0,0 +1,182 @@ +# openai/math challenge `BogomolovPopInjectivity` (family 009) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 009 of the release, *Bogomolov–Pop and Milnor $K$-theoretic reconstruction* +(Number theory). The family as a whole: Reconstructs function fields of transcendence degree at least two over algebraically closed constants from $K^{\mathrm M}_1/\ell$, $K^{\mathrm M}_2/\ell$, and their product. These data recover the perfect closure and constants when $\ell$ differs from the characteristic, and the original field and its named base in equal characteristic. Also proves Bogomolov–Pop reconstruction from abelian-by-central pro-$\ell$ Galois data away from the characteristic. + +The challenge is `BogomolovPopInjectivity`, also at `/opt/openai-math/challenges/BogomolovPopInjectivity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace BogomolovPop + +def proEllKernel (ell : ℕ) (G : Type*) [Group G] [TopologicalSpace G] : Subgroup G := + ⨅ (H : OpenNormalSubgroup G) (_ : IsPGroup ell (G ⧸ H.toSubgroup)), H.toSubgroup + +instance proEllKernel_normal (ell : ℕ) (G : Type*) [Group G] [TopologicalSpace G] : + (proEllKernel ell G).Normal := by + unfold proEllKernel + exact Subgroup.normal_iInf_normal fun H => + Subgroup.normal_iInf_normal fun _ => H.isNormal' + +abbrev ProEll (ell : ℕ) (F : Type*) [Field F] := + Field.absoluteGaloisGroup F ⧸ proEllKernel ell (Field.absoluteGaloisGroup F) + +def closedGammaThree (G : Type*) [Group G] [TopologicalSpace G] [IsTopologicalGroup G] : + Subgroup G := + (⁅(commutator G).topologicalClosure, (⊤ : Subgroup G)⁆).topologicalClosure + +instance closedGammaThree_normal (G : Type*) [Group G] [TopologicalSpace G] + [IsTopologicalGroup G] : (closedGammaThree G).Normal := by + unfold closedGammaThree + exact Subgroup.is_normal_topologicalClosure _ + +abbrev PiA (ell : ℕ) (F : Type*) [Field F] := TopologicalAbelianization (ProEll ell F) + +abbrev PiC (ell : ℕ) (F : Type*) [Field F] := ProEll ell F ⧸ closedGammaThree (ProEll ell F) + +theorem closedGammaThree_le (G : Type*) [Group G] [TopologicalSpace G] + [IsTopologicalGroup G] : closedGammaThree G ≤ (commutator G).topologicalClosure := by + exact Subgroup.topologicalClosure_minimal _ (Subgroup.commutator_le_left _ _) + (Subgroup.isClosed_topologicalClosure _) + +def centralProjection (ell : ℕ) (F : Type*) [Field F] : PiC ell F →* PiA ell F := + QuotientGroup.map _ _ (MonoidHom.id _) (closedGammaThree_le _) + +abbrev Delta (ell : ℕ) (F : Type*) [Field F] := (centralProjection ell F).ker + +def sourceCommutator {G : Type*} [Group G] (x y : G) : G := x⁻¹ * y⁻¹ * x * y + +def abelianLift (ell : ℕ) (F : Type*) [Field F] (x : PiA ell F) : ProEll ell F := + Quotient.out x + +theorem abelianLift_spec (ell : ℕ) (F : Type*) [Field F] (x : PiA ell F) : + QuotientGroup.mk' _ (abelianLift ell F x) = x := Quotient.out_eq x + +def bracket (ell : ℕ) (F : Type*) [Field F] (x y : PiA ell F) : Delta ell F := + ⟨QuotientGroup.mk' _ (sourceCommutator (abelianLift ell F x) (abelianLift ell F y)), by + change centralProjection ell F _ = 1 + simp only [centralProjection, sourceCommutator, map_mul, map_inv] + simp [mul_comm]⟩ + +def BracketCompatible {ell : ℕ} {K L : Type*} [Field K] [Field L] + (φ : PiA ell L ≃ₜ* PiA ell K) : Prop := + ∃ ψ : Delta ell L ≃ₜ* Delta ell K, + ∀ σ τ, ψ (bracket ell L σ τ) = bracket ell K (φ σ) (φ τ) + +abbrev PerfectFieldClosure (F : Type*) [Field F] := perfectClosure F (AlgebraicClosure F) + +def PerfectIsom (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] := + { α : PerfectFieldClosure K ≃+* PerfectFieldClosure L // + α '' Set.range (algebraMap k (PerfectFieldClosure K)) = + Set.range (algebraMap l (PerfectFieldClosure L)) } + +def FrobeniusStep {k K l L : Type*} [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] (α β : PerfectIsom k K l L) : Prop := + ∃ p : ℕ, p.Prime ∧ (p : L) = 0 ∧ + ∀ x : PerfectFieldClosure K, β.1 x = (α.1 x) ^ p + +abbrev IsomF (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] := + Quotient (Relation.EqvGen.setoid (FrobeniusStep (k := k) (K := K) (l := l) (L := L))) + +abbrev IsomC (ell : ℕ) (K L : Type*) [Field K] [Field L] := + {φ : PiA ell L ≃ₜ* PiA ell K // BracketCompatible φ} + +def ScalarStep {ell : ℕ} [Fact ell.Prime] {K L : Type*} [Field K] [Field L] + (φ χ : IsomC ell K L) : Prop := + ∃ u : (PadicInt ell)ˣ, ∀ x : PiA ell L, + Filter.Tendsto (fun n : ℕ => (φ.1 x) ^ PadicInt.appr (u : PadicInt ell) n) + Filter.atTop (nhds (χ.1 x)) + +abbrev IsomCUnits (ell : ℕ) [Fact ell.Prime] (K L : Type*) [Field K] [Field L] := + Quotient (Relation.EqvGen.setoid (ScalarStep (ell := ell) (K := K) (L := L))) + +def absoluteToPiA (ell : ℕ) (F : Type*) [Field F] : + Field.absoluteGaloisGroup F →* PiA ell F := + (QuotientGroup.mk' _).comp (QuotientGroup.mk' _) + +def absoluteAction {F : Type*} [Field F] (σ : Field.absoluteGaloisGroup F) + (x : AlgebraicClosure F) : AlgebraicClosure F := by + change AlgebraicClosure F ≃ₐ[F] AlgebraicClosure F at σ + exact σ x + +def PullbackGraph {ell : ℕ} {k K l L : Type*} + [Field k] [Field K] [Field l] [Field L] [Algebra k K] [Algebra l L] + (α : PerfectIsom k K l L) (φ : IsomC ell K L) : Prop := + ∃ β : AlgebraicClosure K ≃+* AlgebraicClosure L, + (∀ x : PerfectFieldClosure K, β x = ((α.1 x : PerfectFieldClosure L) : + AlgebraicClosure L)) ∧ + ∀ σ : Field.absoluteGaloisGroup L, ∃ τ : Field.absoluteGaloisGroup K, + (∀ x : AlgebraicClosure K, + β (absoluteAction τ x) = absoluteAction σ (β x)) ∧ + φ.1 (absoluteToPiA ell L σ) = absoluteToPiA ell K τ + +def PhiGraph {ell : ℕ} [Fact ell.Prime] {k K l L : Type*} + [Field k] [Field K] [Field l] [Field L] [Algebra k K] [Algebra l L] + (a : IsomF k K l L) (b : IsomCUnits ell K L) : Prop := + ∃ α : PerfectIsom k K l L, ∃ φ : IsomC ell K L, + Quotient.mk _ α = a ∧ Quotient.mk _ φ = b ∧ PullbackGraph α φ + +theorem main_graph_injective (ell : ℕ) [Fact ell.Prime] + (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [IsAlgClosed k] [IsAlgClosed l] [Algebra k K] [Algebra l L] + [Algebra.EssFiniteType k K] [Algebra.EssFiniteType l L] + (hk : (ell : k) ≠ 0) (hl : (ell : l) ≠ 0) + (hK : 2 ≤ Algebra.trdeg k K) (hL : 2 ≤ Algebra.trdeg l L) : + ∀ (a a' : IsomF k K l L) (b : IsomCUnits ell K L), + PhiGraph a b → PhiGraph a' b → a = a' := by + sorry + +end BogomolovPop + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BogomolovPopInjectivity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BogomolovPop.main_graph_injective` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bogomolov-pop-injectivity/solution/closure.txt b/tasks/bogomolov-pop-injectivity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c862fc1e7c6ee325940d47380061496f29aba1f1 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/solution/closure.txt @@ -0,0 +1,5 @@ +OAI.Algebra.BogomolovPop.Canonical +OAI.Algebra.BogomolovPop.Foundations +OAI.Algebra.BogomolovPop.Injectivity +OAI.Algebra.BogomolovPop.Kummer +OAI.Algebra.BogomolovPop.PowerCompletion diff --git a/tasks/bogomolov-pop-injectivity/solution/reference.py b/tasks/bogomolov-pop-injectivity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bogomolov-pop-injectivity/solution/solve.sh b/tasks/bogomolov-pop-injectivity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..44b13b09a20454819f8a0ebebe028968d358955b --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BogomolovPopInjectivity, i.e. module OAI.Algebra.BogomolovPop.Injectivity and the +# 5 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.BogomolovPop.Injectivity /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BogomolovPopInjectivity" diff --git a/tasks/bogomolov-pop-injectivity/task.toml b/tasks/bogomolov-pop-injectivity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..88082984db0dc32fdeaaa3d351af91284a851c95 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bogomolov-pop-injectivity" +version = "1.0.0" +description = "Prove BogomolovPopInjectivity (openai/math family 009: Bogomolov–Pop and Milnor $K$-theoretic reconstruction) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BogomolovPopInjectivity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BogomolovPopInjectivity" +family = "009" +family_title = "Bogomolov–Pop and Milnor $K$-theoretic reconstruction" +subject = "Number theory" +theorems = ["OAI.BogomolovPop.main_graph_injective"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.BogomolovPop.Injectivity" +reference_modules = 5 +reference_lean_bytes = 155277 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 445 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11839 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bogomolov-pop-injectivity/tests/Challenge.lean b/tasks/bogomolov-pop-injectivity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0446666dc770587524b19249d3d865a584e655f --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/tests/Challenge.lean @@ -0,0 +1,131 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace BogomolovPop + +def proEllKernel (ell : ℕ) (G : Type*) [Group G] [TopologicalSpace G] : Subgroup G := + ⨅ (H : OpenNormalSubgroup G) (_ : IsPGroup ell (G ⧸ H.toSubgroup)), H.toSubgroup + +instance proEllKernel_normal (ell : ℕ) (G : Type*) [Group G] [TopologicalSpace G] : + (proEllKernel ell G).Normal := by + unfold proEllKernel + exact Subgroup.normal_iInf_normal fun H => + Subgroup.normal_iInf_normal fun _ => H.isNormal' + +abbrev ProEll (ell : ℕ) (F : Type*) [Field F] := + Field.absoluteGaloisGroup F ⧸ proEllKernel ell (Field.absoluteGaloisGroup F) + +def closedGammaThree (G : Type*) [Group G] [TopologicalSpace G] [IsTopologicalGroup G] : + Subgroup G := + (⁅(commutator G).topologicalClosure, (⊤ : Subgroup G)⁆).topologicalClosure + +instance closedGammaThree_normal (G : Type*) [Group G] [TopologicalSpace G] + [IsTopologicalGroup G] : (closedGammaThree G).Normal := by + unfold closedGammaThree + exact Subgroup.is_normal_topologicalClosure _ + +abbrev PiA (ell : ℕ) (F : Type*) [Field F] := TopologicalAbelianization (ProEll ell F) + +abbrev PiC (ell : ℕ) (F : Type*) [Field F] := ProEll ell F ⧸ closedGammaThree (ProEll ell F) + +theorem closedGammaThree_le (G : Type*) [Group G] [TopologicalSpace G] + [IsTopologicalGroup G] : closedGammaThree G ≤ (commutator G).topologicalClosure := by + exact Subgroup.topologicalClosure_minimal _ (Subgroup.commutator_le_left _ _) + (Subgroup.isClosed_topologicalClosure _) + +def centralProjection (ell : ℕ) (F : Type*) [Field F] : PiC ell F →* PiA ell F := + QuotientGroup.map _ _ (MonoidHom.id _) (closedGammaThree_le _) + +abbrev Delta (ell : ℕ) (F : Type*) [Field F] := (centralProjection ell F).ker + +def sourceCommutator {G : Type*} [Group G] (x y : G) : G := x⁻¹ * y⁻¹ * x * y + +def abelianLift (ell : ℕ) (F : Type*) [Field F] (x : PiA ell F) : ProEll ell F := + Quotient.out x + +theorem abelianLift_spec (ell : ℕ) (F : Type*) [Field F] (x : PiA ell F) : + QuotientGroup.mk' _ (abelianLift ell F x) = x := Quotient.out_eq x + +def bracket (ell : ℕ) (F : Type*) [Field F] (x y : PiA ell F) : Delta ell F := + ⟨QuotientGroup.mk' _ (sourceCommutator (abelianLift ell F x) (abelianLift ell F y)), by + change centralProjection ell F _ = 1 + simp only [centralProjection, sourceCommutator, map_mul, map_inv] + simp [mul_comm]⟩ + +def BracketCompatible {ell : ℕ} {K L : Type*} [Field K] [Field L] + (φ : PiA ell L ≃ₜ* PiA ell K) : Prop := + ∃ ψ : Delta ell L ≃ₜ* Delta ell K, + ∀ σ τ, ψ (bracket ell L σ τ) = bracket ell K (φ σ) (φ τ) + +abbrev PerfectFieldClosure (F : Type*) [Field F] := perfectClosure F (AlgebraicClosure F) + +def PerfectIsom (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] := + { α : PerfectFieldClosure K ≃+* PerfectFieldClosure L // + α '' Set.range (algebraMap k (PerfectFieldClosure K)) = + Set.range (algebraMap l (PerfectFieldClosure L)) } + +def FrobeniusStep {k K l L : Type*} [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] (α β : PerfectIsom k K l L) : Prop := + ∃ p : ℕ, p.Prime ∧ (p : L) = 0 ∧ + ∀ x : PerfectFieldClosure K, β.1 x = (α.1 x) ^ p + +abbrev IsomF (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [Algebra k K] [Algebra l L] := + Quotient (Relation.EqvGen.setoid (FrobeniusStep (k := k) (K := K) (l := l) (L := L))) + +abbrev IsomC (ell : ℕ) (K L : Type*) [Field K] [Field L] := + {φ : PiA ell L ≃ₜ* PiA ell K // BracketCompatible φ} + +def ScalarStep {ell : ℕ} [Fact ell.Prime] {K L : Type*} [Field K] [Field L] + (φ χ : IsomC ell K L) : Prop := + ∃ u : (PadicInt ell)ˣ, ∀ x : PiA ell L, + Filter.Tendsto (fun n : ℕ => (φ.1 x) ^ PadicInt.appr (u : PadicInt ell) n) + Filter.atTop (nhds (χ.1 x)) + +abbrev IsomCUnits (ell : ℕ) [Fact ell.Prime] (K L : Type*) [Field K] [Field L] := + Quotient (Relation.EqvGen.setoid (ScalarStep (ell := ell) (K := K) (L := L))) + +def absoluteToPiA (ell : ℕ) (F : Type*) [Field F] : + Field.absoluteGaloisGroup F →* PiA ell F := + (QuotientGroup.mk' _).comp (QuotientGroup.mk' _) + +def absoluteAction {F : Type*} [Field F] (σ : Field.absoluteGaloisGroup F) + (x : AlgebraicClosure F) : AlgebraicClosure F := by + change AlgebraicClosure F ≃ₐ[F] AlgebraicClosure F at σ + exact σ x + +def PullbackGraph {ell : ℕ} {k K l L : Type*} + [Field k] [Field K] [Field l] [Field L] [Algebra k K] [Algebra l L] + (α : PerfectIsom k K l L) (φ : IsomC ell K L) : Prop := + ∃ β : AlgebraicClosure K ≃+* AlgebraicClosure L, + (∀ x : PerfectFieldClosure K, β x = ((α.1 x : PerfectFieldClosure L) : + AlgebraicClosure L)) ∧ + ∀ σ : Field.absoluteGaloisGroup L, ∃ τ : Field.absoluteGaloisGroup K, + (∀ x : AlgebraicClosure K, + β (absoluteAction τ x) = absoluteAction σ (β x)) ∧ + φ.1 (absoluteToPiA ell L σ) = absoluteToPiA ell K τ + +def PhiGraph {ell : ℕ} [Fact ell.Prime] {k K l L : Type*} + [Field k] [Field K] [Field l] [Field L] [Algebra k K] [Algebra l L] + (a : IsomF k K l L) (b : IsomCUnits ell K L) : Prop := + ∃ α : PerfectIsom k K l L, ∃ φ : IsomC ell K L, + Quotient.mk _ α = a ∧ Quotient.mk _ φ = b ∧ PullbackGraph α φ + +theorem main_graph_injective (ell : ℕ) [Fact ell.Prime] + (k K l L : Type*) [Field k] [Field K] [Field l] [Field L] + [IsAlgClosed k] [IsAlgClosed l] [Algebra k K] [Algebra l L] + [Algebra.EssFiniteType k K] [Algebra.EssFiniteType l L] + (hk : (ell : k) ≠ 0) (hl : (ell : l) ≠ 0) + (hK : 2 ≤ Algebra.trdeg k K) (hL : 2 ≤ Algebra.trdeg l L) : + ∀ (a a' : IsomF k K l L) (b : IsomCUnits ell K L), + PhiGraph a b → PhiGraph a' b → a = a' := by + sorry + +end BogomolovPop + +end + +end OAI diff --git a/tasks/bogomolov-pop-injectivity/tests/grade.py b/tasks/bogomolov-pop-injectivity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bogomolov-pop-injectivity/tests/task.json b/tasks/bogomolov-pop-injectivity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4e1e70cef2393db05a020c667597d14178f549ab --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BogomolovPopInjectivity", + "comparator": { + "theorem_names": [ + "OAI.BogomolovPop.main_graph_injective" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10939 +} \ No newline at end of file diff --git a/tasks/bogomolov-pop-injectivity/tests/test.sh b/tasks/bogomolov-pop-injectivity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bogomolov-pop-injectivity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/boltzmann-nonuniqueness/environment/Dockerfile b/tasks/boltzmann-nonuniqueness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/boltzmann-nonuniqueness/environment/fetch_mathlib.sh b/tasks/boltzmann-nonuniqueness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/boltzmann-nonuniqueness/environment/lake-manifest.json b/tasks/boltzmann-nonuniqueness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/boltzmann-nonuniqueness/environment/lakefile.lean b/tasks/boltzmann-nonuniqueness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/boltzmann-nonuniqueness/environment/lean_setup.sh b/tasks/boltzmann-nonuniqueness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/boltzmann-nonuniqueness/environment/pack_submission.py b/tasks/boltzmann-nonuniqueness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/boltzmann-nonuniqueness/instruction.md b/tasks/boltzmann-nonuniqueness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d0c79f2cf4c5a849e4b990c57b7f02daa60f65f0 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/instruction.md @@ -0,0 +1,266 @@ +# openai/math challenge `BoltzmannNonuniqueness` (family 363) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 363 of the release, *Boltzmann nonuniqueness with exact local conservation* +(Partial differential equations). The family as a whole: Constructs two distinct global entropy solutions of the three-dimensional periodic hard-sphere Boltzmann equation from the same nonnegative initial density, with bounded velocity support and finite mass, energy and absolute entropy. Both are strongly continuous in $L^1$ and satisfy exact local conservation of mass, momentum and kinetic energy. + +The challenge is `BoltzmannNonuniqueness`, also at `/opt/openai-math/challenges/BoltzmannNonuniqueness.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Nonuniqueness for the periodic hard-sphere Boltzmann equation + +Theorem 1.1, with the full entropy-class admissibility of Definition 2.1 and +strong initial L¹ continuity with integrable collision gain and loss. +-/ + +noncomputable section + +open MeasureTheory Set Filter +open scoped RealInnerProductSpace ENNReal Topology + +namespace BoltzmannNonuniqueness + +abbrev Velocity := EuclideanSpace ℝ (Fin 3) +abbrev Position := Fin 3 → AddCircle (1 : ℝ) +abbrev Phase := Position × Velocity +abbrev Density := Phase → ℝ +abbrev Sphere := Metric.sphere (0 : Velocity) 1 + +/-- Ordinary surface area, rather than normalized probability on the sphere. -/ +def sphereArea : Measure Sphere := (volume : Measure Velocity).toSphere + +def normalComponent (v w ω : Velocity) : ℝ := inner ℝ (v - w) ω + +def scatterLeft (v w ω : Velocity) : Velocity := v - normalComponent v w ω • ω + +def scatterRight (v w ω : Velocity) : Velocity := w + normalComponent v w ω • ω + +def collisionKernel (v w ω : Velocity) : ℝ := |normalComponent v w ω| + +def gain (f : Density) (x : Position) (v : Velocity) : ℝ := + ∫ p : Velocity × Sphere, + collisionKernel v p.1 p.2 * f (x, scatterLeft v p.1 p.2) * + f (x, scatterRight v p.1 p.2) + ∂((volume : Measure Velocity).prod sphereArea) + +def loss (f : Density) (x : Position) (v : Velocity) : ℝ := + ∫ p : Velocity × Sphere, + collisionKernel v p.1 p.2 * f (x, v) * f (x, p.1) + ∂((volume : Measure Velocity).prod sphereArea) + +def collision (f : Density) (x : Position) (v : Velocity) : ℝ := + gain f x v - loss f x v + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev Evolution := ℝ → Density +abbrev SpaceTimePhase := ℝ × Phase +abbrev LiftedSpaceTimePhase := ℝ × (Velocity × Velocity) + +def torusProjection (x : Velocity) : Position := fun i => (x i : AddCircle (1 : ℝ)) + +/-- A representative in the fundamental half-open unit cube, used only to evaluate periodic +derivatives. Periodicity makes those derivatives independent of this choice. -/ +def torusRepresentative (x : Position) : Velocity := + WithLp.toLp 2 (fun i => ((AddCircle.equivIco (1 : ℝ) 0) (x i) : ℝ)) + +def maxwellian (v : Velocity) : ℝ := + (2 * Real.pi) ^ (-(3 / 2 : ℝ)) * Real.exp (-‖v‖ ^ 2 / 2) + +def entropyMoment (f : Density) (z : Phase) : ℝ := + f z * (1 + ‖z.2‖ ^ 2 + |Real.log (f z)|) + +/-- The convention `0 |log 0| = 0` is automatic in this real-valued moment. -/ +def FiniteEntropyDatum (f : Density) : Prop := + (∀ᵐ z, 0 ≤ f z) ∧ AEStronglyMeasurable f ∧ Integrable (entropyMoment f) + +def BoundedVelocitySupport (f : Density) : Prop := + ∃ R : ℝ, 0 < R ∧ ∀ᵐ z, R < ‖z.2‖ → f z = 0 + +def energy (f : Density) : ℝ := ∫ z, ‖z.2‖ ^ 2 * f z + +def momentum (f : Density) : Velocity := ∫ z, f z • z.2 + +def relativeEntropy (f : Density) : ℝ := + ∫ z, f z * Real.log (f z / maxwellian z.2) - f z + maxwellian z.2 + +/-- Lower semicontinuous extension of `(A-B) log(A/B)` on the nonnegative quadrant. +The off-quadrant value is immaterial for nonnegative densities. -/ +def extendedEntropyProduction (A B : ℝ) : ℝ≥0∞ := + if A = 0 ∧ B = 0 then 0 + else if 0 < A ∧ 0 < B then ENNReal.ofReal ((A - B) * Real.log (A / B)) + else ⊤ + +def entropyDissipation (f : Density) : ℝ≥0∞ := + (4 : ℝ≥0∞)⁻¹ * ∫⁻ p : Position × (Velocity × (Velocity × Sphere)), + ENNReal.ofReal (collisionKernel p.2.1 p.2.2.1 p.2.2.2) * + extendedEntropyProduction + (f (p.1, scatterLeft p.2.1 p.2.2.1 p.2.2.2) * + f (p.1, scatterRight p.2.1 p.2.2.1 p.2.2.2)) + (f (p.1, p.2.1) * f (p.1, p.2.2.1)) + ∂((volume : Measure Position).prod ((volume : Measure Velocity).prod + ((volume : Measure Velocity).prod sphereArea))) + +/-- The renormalizations of Definition 2.1, with the right derivative at zero. -/ +structure Renormalization where + toFun : ℝ → ℝ + regular : ContDiffOn ℝ 1 toFun (Ici 0) + at_zero : toFun 0 = 0 + derivative_bound : ∃ C : ℝ, 0 ≤ C ∧ ∀ z ∈ Ici (0 : ℝ), + |derivWithin toFun (Ici 0) z| ≤ C / (1 + z) + +/-- A smooth test, periodic in the spatial variable and compact in time and velocity. -/ +structure KineticTest where + toFun : ℝ → Position → Velocity → ℝ + regular : ContDiff ℝ (⊤ : ℕ∞) (fun p : LiftedSpaceTimePhase => + toFun p.1 (torusProjection p.2.1) p.2.2) + compact_time_velocity : ∃ R : ℝ, 0 < R ∧ ∀ t x v, + R < |t| ∨ R < ‖v‖ → toFun t x v = 0 + +def KineticTest.transportDerivative (φ : KineticTest) (t : ℝ) (z : Phase) : ℝ := + fderiv ℝ (fun p : LiftedSpaceTimePhase => φ.toFun p.1 (torusProjection p.2.1) p.2.2) + (t, torusRepresentative z.1, z.2) (1, z.2, 0) + +/-- Smooth local mass tests have no velocity cutoff, since their velocity dependence is +introduced only by the transport derivative. -/ +structure MassTest where + toFun : ℝ → Position → ℝ + regular : ContDiff ℝ (⊤ : ℕ∞) (fun p : ℝ × Velocity => toFun p.1 (torusProjection p.2)) + compact_time : ∃ R : ℝ, 0 < R ∧ ∀ t x, R < |t| → toFun t x = 0 + +def MassTest.transportDerivative (φ : MassTest) (t : ℝ) (z : Phase) : ℝ := + fderiv ℝ (fun p : ℝ × Velocity => φ.toFun p.1 (torusProjection p.2)) + (t, torusRepresentative z.1) (1, z.2) + +def relativeDensity (F : Evolution) (t : ℝ) (z : Phase) : ℝ := F t z / maxwellian z.2 + +def renormalizedIntegrand (F : Evolution) (β : Renormalization) (φ : KineticTest) + (p : SpaceTimePhase) : ℝ := + maxwellian p.2.2 * β.toFun (relativeDensity F p.1 p.2) * + φ.transportDerivative p.1 p.2 + + derivWithin β.toFun (Ici 0) (relativeDensity F p.1 p.2) * + collision (F p.1) p.2.1 p.2.2 * φ.toFun p.1 p.2.1 p.2.2 + +def nonnegativeTimes : Set SpaceTimePhase := Ici (0 : ℝ) ×ˢ univ +def boundedTimes (T : ℝ) : Set SpaceTimePhase := Icc 0 T ×ˢ univ + +/-- Full global admissibility, including both separately renormalized collision terms, +local mass, total momentum, and the every-time energy and entropy inequalities. -/ +structure AdmissibleGlobal (f₀ : Density) (F : Evolution) : Prop where + datum : FiniteEntropyDatum f₀ + spacetime_measurable : AEStronglyMeasurable (fun p : SpaceTimePhase => F p.1 p.2) + (volume.restrict nonnegativeTimes) + finite_each_time : ∀ t ∈ Ici (0 : ℝ), FiniteEntropyDatum (F t) + initial : F 0 =ᵐ[volume] f₀ + weak_continuity : ∀ ψ : Phase → ℝ, Measurable ψ → + (∃ C : ℝ, ∀ z, |ψ z| ≤ C) → + ContinuousOn (fun t => ∫ z, F t z * ψ z) (Ici 0) + uniform_moment : ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, ∀ t ∈ Icc 0 T, + (∫ z, entropyMoment (F t) z) ≤ C + -- These finiteness conditions prevent the real Bochner integrals defining `gain` and + -- `loss` from silently taking the value zero at divergent collision fibers. + collision_fibers : ∀ T : ℝ, 0 ≤ T → ∀ᵐ p ∂volume.restrict (boundedTimes T), + Integrable (fun q : Velocity × Sphere => + collisionKernel p.2.2 q.1 q.2 * + F p.1 (p.2.1, scatterLeft p.2.2 q.1 q.2) * + F p.1 (p.2.1, scatterRight p.2.2 q.1 q.2)) + ((volume : Measure Velocity).prod sphereArea) ∧ + Integrable (fun q : Velocity × Sphere => + collisionKernel p.2.2 q.1 q.2 * F p.1 p.2 * F p.1 (p.2.1, q.1)) + ((volume : Measure Velocity).prod sphereArea) + gain_integrable : ∀ T : ℝ, 0 ≤ T → IntegrableOn + (fun p : SpaceTimePhase => gain (F p.1) p.2.1 p.2.2 / + (1 + relativeDensity F p.1 p.2)) (boundedTimes T) + loss_integrable : ∀ T : ℝ, 0 ≤ T → IntegrableOn + (fun p : SpaceTimePhase => loss (F p.1) p.2.1 p.2.2 / + (1 + relativeDensity F p.1 p.2)) (boundedTimes T) + renormalized_integrable : ∀ β φ, IntegrableOn (renormalizedIntegrand F β φ) + nonnegativeTimes + renormalized_equation : ∀ β : Renormalization, ∀ φ : KineticTest, + (∫ p in nonnegativeTimes, renormalizedIntegrand F β φ p) + + (∫ z, maxwellian z.2 * β.toFun (f₀ z / maxwellian z.2) * + φ.toFun 0 z.1 z.2) = 0 + local_mass_integrable : ∀ φ : MassTest, IntegrableOn + (fun p : SpaceTimePhase => F p.1 p.2 * φ.transportDerivative p.1 p.2) + nonnegativeTimes + local_mass : ∀ φ : MassTest, + (∫ p in nonnegativeTimes, F p.1 p.2 * φ.transportDerivative p.1 p.2) + + (∫ z, f₀ z * φ.toFun 0 z.1) = 0 + momentum_conservation : ∀ t ∈ Ici (0 : ℝ), momentum (F t) = momentum f₀ + energy_inequality : ∀ t ∈ Ici (0 : ℝ), energy (F t) ≤ energy f₀ + entropy_inequality : ∀ t ∈ Ici (0 : ℝ), + ENNReal.ofReal (relativeEntropy (F t)) + + (∫⁻ s in Icc (0 : ℝ) t, entropyDissipation (F s)) ≤ + ENNReal.ofReal (relativeEntropy f₀) + +/-- Additional regularity asserted on the common initial interval. The `eLpNorm` statement +is strong `L¹` continuity and cannot be made vacuous by a nonintegrable Bochner integral. -/ +structure StrongEarly (T : ℝ) (F : Evolution) : Prop where + positive_time : 0 < T + strong_continuity : ∀ t ∈ Icc 0 T, + Tendsto (fun s => eLpNorm (fun z => F s z - F t z) 1 volume) + (𝓝[Icc 0 T] t) (𝓝 0) + gain_integrable : IntegrableOn (fun p : SpaceTimePhase => gain (F p.1) p.2.1 p.2.2) + (boundedTimes T) + loss_integrable : IntegrableOn (fun p : SpaceTimePhase => loss (F p.1) p.2.1 p.2.2) + (boundedTimes T) + +theorem nonuniqueness : + ∃ f₀ : Density, BoundedVelocitySupport f₀ ∧ + ∃ (F G : Evolution) (T : ℝ), AdmissibleGlobal f₀ F ∧ AdmissibleGlobal f₀ G ∧ + StrongEarly T F ∧ StrongEarly T G ∧ + ∃ t ∈ Set.Icc 0 T, ¬(F t =ᵐ[MeasureTheory.volume] G t) := + sorry + +end BoltzmannNonuniqueness + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BoltzmannNonuniqueness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoltzmannNonuniqueness.nonuniqueness` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/boltzmann-nonuniqueness/solution/closure.txt b/tasks/boltzmann-nonuniqueness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2ec76afb49ed1d02bb2e9aefad0f6c31d530a480 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/solution/closure.txt @@ -0,0 +1,525 @@ +OAI.MathematicalPhysics.Boltzmann.Admissibility +OAI.MathematicalPhysics.Boltzmann.Approximation.CapActualLossDensity +OAI.MathematicalPhysics.Boltzmann.Approximation.CapAnnularMassGrowth +OAI.MathematicalPhysics.Boltzmann.Approximation.CapCoefficientExtraction +OAI.MathematicalPhysics.Boltzmann.Approximation.CapColdAverages +OAI.MathematicalPhysics.Boltzmann.Approximation.CapColdBounds +OAI.MathematicalPhysics.Boltzmann.Approximation.CapCoveredDamping +OAI.MathematicalPhysics.Boltzmann.Approximation.CapDilationCompactness +OAI.MathematicalPhysics.Boltzmann.Approximation.CapDilationScales +OAI.MathematicalPhysics.Boltzmann.Approximation.CapEntropyMoments +OAI.MathematicalPhysics.Boltzmann.Approximation.CapEscapingSeed +OAI.MathematicalPhysics.Boltzmann.Approximation.CapFiniteBackgroundLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.CapHotSourceIntegrability +OAI.MathematicalPhysics.Boltzmann.Approximation.CapHotTransportBalance +OAI.MathematicalPhysics.Boltzmann.Approximation.CapHotUndamped +OAI.MathematicalPhysics.Boltzmann.Approximation.CapLabelFreeLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.CapLimitTransport +OAI.MathematicalPhysics.Boltzmann.Approximation.CapLocalAdmissibility +OAI.MathematicalPhysics.Boltzmann.Approximation.CapLossScaling +OAI.MathematicalPhysics.Boltzmann.Approximation.CapMildLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.CapMixedCollisionLimits +OAI.MathematicalPhysics.Boltzmann.Approximation.CapMixedPositiveBound +OAI.MathematicalPhysics.Boltzmann.Approximation.CapMomentBound +OAI.MathematicalPhysics.Boltzmann.Approximation.CapNonlinearHotLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.CapPairMoments +OAI.MathematicalPhysics.Boltzmann.Approximation.CapUniformFiniteHorizon +OAI.MathematicalPhysics.Boltzmann.Approximation.CapWeightedNonlinearLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.CappedDensitySequence +OAI.MathematicalPhysics.Boltzmann.Approximation.CappedTightness +OAI.MathematicalPhysics.Boltzmann.Approximation.ColoredDifferenceAlgebra +OAI.MathematicalPhysics.Boltzmann.Approximation.ColoredSourceDifferenceAE +OAI.MathematicalPhysics.Boltzmann.Approximation.CutoffEntropyMeasure +OAI.MathematicalPhysics.Boltzmann.Approximation.CutoffLipschitz +OAI.MathematicalPhysics.Boltzmann.Approximation.CutoffLossFrequency +OAI.MathematicalPhysics.Boltzmann.Approximation.DormantBoxLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.DormantConstruction +OAI.MathematicalPhysics.Boltzmann.Approximation.MassNormalizedCollisionLimits +OAI.MathematicalPhysics.Boltzmann.Approximation.MildCharacteristics +OAI.MathematicalPhysics.Boltzmann.Approximation.MildConservation +OAI.MathematicalPhysics.Boltzmann.Approximation.MildCurveContinuity +OAI.MathematicalPhysics.Boltzmann.Approximation.MildDensityAgreement +OAI.MathematicalPhysics.Boltzmann.Approximation.MildInitialAE +OAI.MathematicalPhysics.Boltzmann.Approximation.MildLocalAdmissibility +OAI.MathematicalPhysics.Boltzmann.Approximation.MildRenormalization +OAI.MathematicalPhysics.Boltzmann.Approximation.MildRenormalizedBalance +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveAccessAngles +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveComparisonBound +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveContributionsIntegrable +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveEndpointHistory +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveIntegralBound +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveIntegralFixedPoint +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveIntegralPasting +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveIntegralTime +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveIntegralWindow +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveMildRepresentative +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveNonlinearLimit +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveRestrictedChain +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveSourceFormula +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveVolterra +OAI.MathematicalPhysics.Boltzmann.Approximation.PositiveVolterraOffAxisAE +OAI.MathematicalPhysics.Boltzmann.Approximation.RegularizedCollisionDifference +OAI.MathematicalPhysics.Boltzmann.Approximation.RegularizedDissipationBound +OAI.MathematicalPhysics.Boltzmann.Approximation.RegularizedEntropyIntegrability +OAI.MathematicalPhysics.Boltzmann.Approximation.RegularizedLogBounds +OAI.MathematicalPhysics.Boltzmann.Approximation.ResolventAverageBound +OAI.MathematicalPhysics.Boltzmann.Approximation.SubcapCapLocalAdmissibility +OAI.MathematicalPhysics.Boltzmann.Approximation.SubcapColdControl +OAI.MathematicalPhysics.Boltzmann.Approximation.SubcapMildLimits +OAI.MathematicalPhysics.Boltzmann.Approximation.SurvivalProfile +OAI.MathematicalPhysics.Boltzmann.Approximation.SurvivalVolterraIntegrable +OAI.MathematicalPhysics.Boltzmann.Branching.AccessAngleStability +OAI.MathematicalPhysics.Boltzmann.Branching.AccessAngularFubini +OAI.MathematicalPhysics.Boltzmann.Branching.AdmissibleDatumCongruence +OAI.MathematicalPhysics.Boltzmann.Branching.AeKernelHistoryOrder +OAI.MathematicalPhysics.Boltzmann.Branching.AeLocalizedHotMassGrowth +OAI.MathematicalPhysics.Boltzmann.Branching.AeWindowPatching +OAI.MathematicalPhysics.Boltzmann.Branching.AffineSlices +OAI.MathematicalPhysics.Boltzmann.Branching.AlmostEverywhereGrowth +OAI.MathematicalPhysics.Boltzmann.Branching.AttenuationGap +OAI.MathematicalPhysics.Boltzmann.Branching.AverageFourierTail +OAI.MathematicalPhysics.Boltzmann.Branching.AverageMajorant +OAI.MathematicalPhysics.Boltzmann.Branching.AveragedPairIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.AveragingTailSources +OAI.MathematicalPhysics.Boltzmann.Branching.AxisInput +OAI.MathematicalPhysics.Boltzmann.Branching.AxisMismatch +OAI.MathematicalPhysics.Boltzmann.Branching.BackgroundBeamCloseness +OAI.MathematicalPhysics.Boltzmann.Branching.BackgroundCappedLoss +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedAverageCompactness +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedAverageProducts +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedCollisionBlocks +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedEntropyProduction +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedEntryPortion +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedGeometricBlock +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedL1Tests +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedMeshStep +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedMildEntropyLimit +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedPairRate +OAI.MathematicalPhysics.Boltzmann.Branching.BoundedVelocityIntegral +OAI.MathematicalPhysics.Boltzmann.Branching.CausalConvolution +OAI.MathematicalPhysics.Boltzmann.Branching.CellLocalizedSource +OAI.MathematicalPhysics.Boltzmann.Branching.CenteredPeriodicBound +OAI.MathematicalPhysics.Boltzmann.Branching.CentralRetainedLimit +OAI.MathematicalPhysics.Boltzmann.Branching.CharacteristicCoordinates +OAI.MathematicalPhysics.Boltzmann.Branching.CharacteristicCutoffGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.CharacteristicPhysicalGain +OAI.MathematicalPhysics.Boltzmann.Branching.CharacteristicProductTest +OAI.MathematicalPhysics.Boltzmann.Branching.ChartPointLift +OAI.MathematicalPhysics.Boltzmann.Branching.ClampedMildAE +OAI.MathematicalPhysics.Boltzmann.Branching.ClippedCharacteristicGain +OAI.MathematicalPhysics.Boltzmann.Branching.ClippedColdFiniteLimit +OAI.MathematicalPhysics.Boltzmann.Branching.ClippedColdShift +OAI.MathematicalPhysics.Boltzmann.Branching.ClippedColdTime +OAI.MathematicalPhysics.Boltzmann.Branching.ClippedProductionLimit +OAI.MathematicalPhysics.Boltzmann.Branching.CommonBoundedAverageCompactness +OAI.MathematicalPhysics.Boltzmann.Branching.CommonHistoryCore +OAI.MathematicalPhysics.Boltzmann.Branching.CommonMomentEnvelope +OAI.MathematicalPhysics.Boltzmann.Branching.CommonStartGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.CompactCapFamily +OAI.MathematicalPhysics.Boltzmann.Branching.CompactParameterConvergence +OAI.MathematicalPhysics.Boltzmann.Branching.ComplexWeakL2Diagonal +OAI.MathematicalPhysics.Boltzmann.Branching.CompressedAxialDecay +OAI.MathematicalPhysics.Boltzmann.Branching.ConditionalMain +OAI.MathematicalPhysics.Boltzmann.Branching.ControlledParameterPath +OAI.MathematicalPhysics.Boltzmann.Branching.CumulativeIntervalBalance +OAI.MathematicalPhysics.Boltzmann.Branching.DampedBoundedEndpointTransport +OAI.MathematicalPhysics.Boltzmann.Branching.DampedBranchingBlocks +OAI.MathematicalPhysics.Boltzmann.Branching.DampedCollisionHistories +OAI.MathematicalPhysics.Boltzmann.Branching.DampedEndpointHistories +OAI.MathematicalPhysics.Boltzmann.Branching.DampedLateBoxPhysicalBlock +OAI.MathematicalPhysics.Boltzmann.Branching.DampedLocalBeamBlock +OAI.MathematicalPhysics.Boltzmann.Branching.DatumBounds +OAI.MathematicalPhysics.Boltzmann.Branching.DensityCompactness +OAI.MathematicalPhysics.Boltzmann.Branching.DiagonalVanishingCap +OAI.MathematicalPhysics.Boltzmann.Branching.DilatedCoreDensity +OAI.MathematicalPhysics.Boltzmann.Branching.DilatedTwoCoreLimit +OAI.MathematicalPhysics.Boltzmann.Branching.DilationBoxOrder +OAI.MathematicalPhysics.Boltzmann.Branching.DissipationMassExhaustion +OAI.MathematicalPhysics.Boltzmann.Branching.DoubleCollisionTests +OAI.MathematicalPhysics.Boltzmann.Branching.EndpointHistoryMass +OAI.MathematicalPhysics.Boltzmann.Branching.EnergyCollisionMarginals +OAI.MathematicalPhysics.Boltzmann.Branching.EnergyTruncation +OAI.MathematicalPhysics.Boltzmann.Branching.EntrySites +OAI.MathematicalPhysics.Boltzmann.Branching.EuclideanBackwardMap +OAI.MathematicalPhysics.Boltzmann.Branching.EuclideanKineticMap +OAI.MathematicalPhysics.Boltzmann.Branching.ExponentialPairIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.ExtendedProductionScale +OAI.MathematicalPhysics.Boltzmann.Branching.FamilyHotBounds +OAI.MathematicalPhysics.Boltzmann.Branching.FanNullSet +OAI.MathematicalPhysics.Boltzmann.Branching.FirstEntryMass +OAI.MathematicalPhysics.Boltzmann.Branching.FiveGainConvergence +OAI.MathematicalPhysics.Boltzmann.Branching.FiveGainPullback +OAI.MathematicalPhysics.Boltzmann.Branching.FiveGainRank +OAI.MathematicalPhysics.Boltzmann.Branching.FlightConeLocalization +OAI.MathematicalPhysics.Boltzmann.Branching.FlightMeasure +OAI.MathematicalPhysics.Boltzmann.Branching.FullDissipationLimit +OAI.MathematicalPhysics.Boltzmann.Branching.GainEntropyTail +OAI.MathematicalPhysics.Boltzmann.Branching.GainMeasureLimit +OAI.MathematicalPhysics.Boltzmann.Branching.GainNonnegative +OAI.MathematicalPhysics.Boltzmann.Branching.GainSmoothingError +OAI.MathematicalPhysics.Boltzmann.Branching.GrowthContradiction +OAI.MathematicalPhysics.Boltzmann.Branching.HalfGaussianMoment +OAI.MathematicalPhysics.Boltzmann.Branching.HotCanonicalFamily +OAI.MathematicalPhysics.Boltzmann.Branching.HotChartHomeomorph +OAI.MathematicalPhysics.Boltzmann.Branching.HotCollisionDecomposition +OAI.MathematicalPhysics.Boltzmann.Branching.HotFullVanishingContradiction +OAI.MathematicalPhysics.Boltzmann.Branching.HotGainReduction +OAI.MathematicalPhysics.Boltzmann.Branching.HotPairWindowGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.HotPhysicalSource +OAI.MathematicalPhysics.Boltzmann.Branching.HotPositiveRegion +OAI.MathematicalPhysics.Boltzmann.Branching.HotQuadraticGain +OAI.MathematicalPhysics.Boltzmann.Branching.HotRatioCollisionTrace +OAI.MathematicalPhysics.Boltzmann.Branching.HotSeedCoreLower +OAI.MathematicalPhysics.Boltzmann.Branching.HotWindowGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.HotWindowInput +OAI.MathematicalPhysics.Boltzmann.Branching.InMeasureDifference +OAI.MathematicalPhysics.Boltzmann.Branching.IncomingLossRate +OAI.MathematicalPhysics.Boltzmann.Branching.InitialLinearComparison +OAI.MathematicalPhysics.Boltzmann.Branching.IntegrablePathTrace +OAI.MathematicalPhysics.Boltzmann.Branching.InteriorCell +OAI.MathematicalPhysics.Boltzmann.Branching.InverseFourierL2 +OAI.MathematicalPhysics.Boltzmann.Branching.L2PairingBound +OAI.MathematicalPhysics.Boltzmann.Branching.LargeOutput +OAI.MathematicalPhysics.Boltzmann.Branching.LateBoxAccessMeasure +OAI.MathematicalPhysics.Boltzmann.Branching.LateBoxCommonDamping +OAI.MathematicalPhysics.Boltzmann.Branching.LimitFullPositiveSurvival +OAI.MathematicalPhysics.Boltzmann.Branching.LinearCharacteristicBalance +OAI.MathematicalPhysics.Boltzmann.Branching.LinearHotLocalization +OAI.MathematicalPhysics.Boltzmann.Branching.LinearSurvivalIdentity +OAI.MathematicalPhysics.Boltzmann.Branching.LogRenormalization +OAI.MathematicalPhysics.Boltzmann.Branching.LogarithmicIteration +OAI.MathematicalPhysics.Boltzmann.Branching.LossIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.LossResidualLimit +OAI.MathematicalPhysics.Boltzmann.Branching.MainCoreScaleWindow +OAI.MathematicalPhysics.Boltzmann.Branching.MainParameters +OAI.MathematicalPhysics.Boltzmann.Branching.MainPositiveRemainderBound +OAI.MathematicalPhysics.Boltzmann.Branching.MarginalUniformIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.MaxwellianFrequency +OAI.MathematicalPhysics.Boltzmann.Branching.MediumEndpointTransport +OAI.MathematicalPhysics.Boltzmann.Branching.MediumStateCollision +OAI.MathematicalPhysics.Boltzmann.Branching.MismatchSlices +OAI.MathematicalPhysics.Boltzmann.Branching.MixedPhysicalMeasures +OAI.MathematicalPhysics.Boltzmann.Branching.MixedRealGain +OAI.MathematicalPhysics.Boltzmann.Branching.MomentAverageBound +OAI.MathematicalPhysics.Boltzmann.Branching.Moments +OAI.MathematicalPhysics.Boltzmann.Branching.MomentumCollisionIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.MovingBoxMass +OAI.MathematicalPhysics.Boltzmann.Branching.MovingCutoffWeakLimit +OAI.MathematicalPhysics.Boltzmann.Branching.NearbyMainCopies +OAI.MathematicalPhysics.Boltzmann.Branching.NonnegativeGainCongruence +OAI.MathematicalPhysics.Boltzmann.Branching.NormalGainMeasureActions +OAI.MathematicalPhysics.Boltzmann.Branching.NormalOutgoingSymmetry +OAI.MathematicalPhysics.Boltzmann.Branching.NormalReflectionGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.OccupationSliceIntegral +OAI.MathematicalPhysics.Boltzmann.Branching.OffAxisBoxExhaustion +OAI.MathematicalPhysics.Boltzmann.Branching.OuterTightness +OAI.MathematicalPhysics.Boltzmann.Branching.OutgoingPairIntegral +OAI.MathematicalPhysics.Boltzmann.Branching.PairwiseSubsequenceCauchy +OAI.MathematicalPhysics.Boltzmann.Branching.PeriodicExistenceReduction +OAI.MathematicalPhysics.Boltzmann.Branching.PerturbedFiniteBlock +OAI.MathematicalPhysics.Boltzmann.Branching.PhaseDecompositionNorm +OAI.MathematicalPhysics.Boltzmann.Branching.PhaseSliceLocalization +OAI.MathematicalPhysics.Boltzmann.Branching.PhaseSourceMeasure +OAI.MathematicalPhysics.Boltzmann.Branching.PlaneChart +OAI.MathematicalPhysics.Boltzmann.Branching.PowerDiskMixture +OAI.MathematicalPhysics.Boltzmann.Branching.ProductKineticCutoff +OAI.MathematicalPhysics.Boltzmann.Branching.ProductionDualLimit +OAI.MathematicalPhysics.Boltzmann.Branching.ProjectedTimeBalance +OAI.MathematicalPhysics.Boltzmann.Branching.PublishedInputs +OAI.MathematicalPhysics.Boltzmann.Branching.PullbackCoordinates +OAI.MathematicalPhysics.Boltzmann.Branching.PullbackRegularLimit +OAI.MathematicalPhysics.Boltzmann.Branching.RadialReflectionChangeVariables +OAI.MathematicalPhysics.Boltzmann.Branching.RateDissipationMonotone +OAI.MathematicalPhysics.Boltzmann.Branching.RationalUniformApproximation +OAI.MathematicalPhysics.Boltzmann.Branching.RawPairCompactness +OAI.MathematicalPhysics.Boltzmann.Branching.RealL1ApproximationLimit +OAI.MathematicalPhysics.Boltzmann.Branching.RebuiltHotCapBound +OAI.MathematicalPhysics.Boltzmann.Branching.RebuiltHotInitial +OAI.MathematicalPhysics.Boltzmann.Branching.RebuiltHotRegularity +OAI.MathematicalPhysics.Boltzmann.Branching.RedundantParameterSupport +OAI.MathematicalPhysics.Boltzmann.Branching.RedundantPlaneIntegral +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceAngularCharts +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceBranchingHistories +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceCollisionGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceFlightLaws +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceGrowthBlocks +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceHistoryMoments +OAI.MathematicalPhysics.Boltzmann.Branching.ReferenceMinorization +OAI.MathematicalPhysics.Boltzmann.Branching.RegularChart +OAI.MathematicalPhysics.Boltzmann.Branching.RelativeCutoffConvergence +OAI.MathematicalPhysics.Boltzmann.Branching.RelativeEntropyMarginal +OAI.MathematicalPhysics.Boltzmann.Branching.RenormalizationBounds +OAI.MathematicalPhysics.Boltzmann.Branching.RescaledBoundedGain +OAI.MathematicalPhysics.Boltzmann.Branching.RescaledColdMajorant +OAI.MathematicalPhysics.Boltzmann.Branching.RescaledParameterSlab +OAI.MathematicalPhysics.Boltzmann.Branching.RestrictedCone +OAI.MathematicalPhysics.Boltzmann.Branching.RetainedAxialDecay +OAI.MathematicalPhysics.Boltzmann.Branching.RetainedWindowDeletion +OAI.MathematicalPhysics.Boltzmann.Branching.RightAverageBound +OAI.MathematicalPhysics.Boltzmann.Branching.ScaledBlockMass +OAI.MathematicalPhysics.Boltzmann.Branching.ScaledBoundedEvent +OAI.MathematicalPhysics.Boltzmann.Branching.ScaledMassAgreement +OAI.MathematicalPhysics.Boltzmann.Branching.SecondCoreOffBands +OAI.MathematicalPhysics.Boltzmann.Branching.SeedEscapeMeasure +OAI.MathematicalPhysics.Boltzmann.Branching.SeparatedMeasureTail +OAI.MathematicalPhysics.Boltzmann.Branching.SeparationBoxContainment +OAI.MathematicalPhysics.Boltzmann.Branching.ShiftedStripe +OAI.MathematicalPhysics.Boltzmann.Branching.SliceUniformLimit +OAI.MathematicalPhysics.Boltzmann.Branching.SlopedChart +OAI.MathematicalPhysics.Boltzmann.Branching.SmallDilationGeometry +OAI.MathematicalPhysics.Boltzmann.Branching.SmallFirstGain +OAI.MathematicalPhysics.Boltzmann.Branching.SmoothTestFamily +OAI.MathematicalPhysics.Boltzmann.Branching.SmoothedPrePostIdentity +OAI.MathematicalPhysics.Boltzmann.Branching.SpaceTimeDilationAE +OAI.MathematicalPhysics.Boltzmann.Branching.SpaceTimeEssSup +OAI.MathematicalPhysics.Boltzmann.Branching.SpacetimeAverageLimit +OAI.MathematicalPhysics.Boltzmann.Branching.SpacetimeFourierCoordinates +OAI.MathematicalPhysics.Boltzmann.Branching.SpacetimeRelativeEntropy +OAI.MathematicalPhysics.Boltzmann.Branching.SquareIntegralToL1 +OAI.MathematicalPhysics.Boltzmann.Branching.StageParameterIntegration +OAI.MathematicalPhysics.Boltzmann.Branching.StripeCells +OAI.MathematicalPhysics.Boltzmann.Branching.SubmersionNullPreimage +OAI.MathematicalPhysics.Boltzmann.Branching.SupportedTensorConvergence +OAI.MathematicalPhysics.Boltzmann.Branching.SupportedTransportTest +OAI.MathematicalPhysics.Boltzmann.Branching.ThreeCollisionTimes +OAI.MathematicalPhysics.Boltzmann.Branching.ThreeSelectedIntegral +OAI.MathematicalPhysics.Boltzmann.Branching.TightApproximation +OAI.MathematicalPhysics.Boltzmann.Branching.TightCapFamily +OAI.MathematicalPhysics.Boltzmann.Branching.TimeSliceIntegration +OAI.MathematicalPhysics.Boltzmann.Branching.TimeSourceCumulative +OAI.MathematicalPhysics.Boltzmann.Branching.TranslatedCoreKernel +OAI.MathematicalPhysics.Boltzmann.Branching.TranslatedTwoCoreLimit +OAI.MathematicalPhysics.Boltzmann.Branching.TransportCutoff +OAI.MathematicalPhysics.Boltzmann.Branching.TransportedKernelRestriction +OAI.MathematicalPhysics.Boltzmann.Branching.TriangularLinearMap +OAI.MathematicalPhysics.Boltzmann.Branching.TruncatedExponential +OAI.MathematicalPhysics.Boltzmann.Branching.TwoCoreLimit +OAI.MathematicalPhysics.Boltzmann.Branching.UnitNormalizedResidual +OAI.MathematicalPhysics.Boltzmann.Branching.UpperTimeDeletion +OAI.MathematicalPhysics.Boltzmann.Branching.VanishingCutoffCollision +OAI.MathematicalPhysics.Boltzmann.Branching.VanishingMajorant +OAI.MathematicalPhysics.Boltzmann.Branching.VariableSurvival +OAI.MathematicalPhysics.Boltzmann.Branching.VaryingBoundedMultiplier +OAI.MathematicalPhysics.Boltzmann.Branching.VelocityAveraging +OAI.MathematicalPhysics.Boltzmann.Branching.VolterraFubini +OAI.MathematicalPhysics.Boltzmann.Branching.WeakCompactness +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedCharacteristic +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedHotGain +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedHotRegularity +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedJetSolutions +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedJetStability +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedMildBalance +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedNetLoss +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedNormalizedGainTranslation +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedPairUniformIntegrability +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedThermalChain +OAI.MathematicalPhysics.Boltzmann.Branching.WeightedTranslationTests +OAI.MathematicalPhysics.Boltzmann.Branching.WidthTails +OAI.MathematicalPhysics.Boltzmann.Branching.WindowCollisionMarginal +OAI.MathematicalPhysics.Boltzmann.Branching.WindowLocalizedSource +OAI.MathematicalPhysics.Boltzmann.Branching.ZeroProfileParameters +OAI.MathematicalPhysics.Boltzmann.Collision.AnalyticRankAlmostEverywhere +OAI.MathematicalPhysics.Boltzmann.Collision.AnalyticTools +OAI.MathematicalPhysics.Boltzmann.Collision.AngularGainTranslationTests +OAI.MathematicalPhysics.Boltzmann.Collision.AngularPairTests +OAI.MathematicalPhysics.Boltzmann.Collision.AxialAtomicSheet +OAI.MathematicalPhysics.Boltzmann.Collision.AxialBandMeasure +OAI.MathematicalPhysics.Boltzmann.Collision.AxialDecayLimit +OAI.MathematicalPhysics.Boltzmann.Collision.AxialFlow +OAI.MathematicalPhysics.Boltzmann.Collision.AxialJointAnalytic +OAI.MathematicalPhysics.Boltzmann.Collision.AxialSecondMismatch +OAI.MathematicalPhysics.Boltzmann.Collision.CarlemanIdentity +OAI.MathematicalPhysics.Boltzmann.Collision.CarlemanNormalCoordinates +OAI.MathematicalPhysics.Boltzmann.Collision.CarlemanOperator +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionComparisonError +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionConservation +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionDissipation +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionMeasure +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionParameterShuffle +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionSources +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionWaitingCone +OAI.MathematicalPhysics.Boltzmann.Collision.CollisionWeakMarginals +OAI.MathematicalPhysics.Boltzmann.Collision.FourierCompactness +OAI.MathematicalPhysics.Boltzmann.Collision.FourierL2Identification +OAI.MathematicalPhysics.Boltzmann.Collision.GaussianColdPhysical +OAI.MathematicalPhysics.Boltzmann.Collision.GaussianEstimates +OAI.MathematicalPhysics.Boltzmann.Collision.GaussianFrequency +OAI.MathematicalPhysics.Boltzmann.Collision.GaussianLocalExistence +OAI.MathematicalPhysics.Boltzmann.Collision.GaussianWeightedConvergence +OAI.MathematicalPhysics.Boltzmann.Collision.KernelConjugacy +OAI.MathematicalPhysics.Boltzmann.Collision.KernelInvariantOrder +OAI.MathematicalPhysics.Boltzmann.Collision.KernelInvariantPowers +OAI.MathematicalPhysics.Boltzmann.Collision.MityaginDischarge +OAI.MathematicalPhysics.Boltzmann.Collision.MityaginPublished +OAI.MathematicalPhysics.Boltzmann.Collision.ScalarEntropyConvex +OAI.MathematicalPhysics.Boltzmann.Collision.ScalarEntropyJointTrace +OAI.MathematicalPhysics.Boltzmann.Collision.SheetGain +OAI.MathematicalPhysics.Boltzmann.Collision.SheetIntervals +OAI.MathematicalPhysics.Boltzmann.Collision.SheetKernelLimits +OAI.MathematicalPhysics.Boltzmann.Collision.SheetMixtures +OAI.MathematicalPhysics.Boltzmann.Collision.SphereAntipodal +OAI.MathematicalPhysics.Boltzmann.Collision.SphereDirectionAbsolute +OAI.MathematicalPhysics.Boltzmann.Collision.SphereIsometryMeasure +OAI.MathematicalPhysics.Boltzmann.Collision.TransverseAverage +OAI.MathematicalPhysics.Boltzmann.Collision.TransverseStripeWeak +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityAverageDifference +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityAverageRepresentatives +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityCutoffEntropyError +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityFourierMultiplier +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityPolynomialBounds +OAI.MathematicalPhysics.Boltzmann.Collision.VelocitySmoothingError +OAI.MathematicalPhysics.Boltzmann.Collision.VelocityWeight +OAI.MathematicalPhysics.Boltzmann.Collision.WeightAlgebra +OAI.MathematicalPhysics.Boltzmann.Collision.WeightLocalL1 +OAI.MathematicalPhysics.Boltzmann.Compactness.ContinuationAdmissibility +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyCollisionIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyDissipationAverage +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyDissipationCoordinates +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyIntegralBalance +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyLocalConstruction +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyRegularizationLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.EntropyUniformIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteDepthKernelOrder +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteEntryPhaseBound +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteGainHistoryComparison +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteHorizonRatio +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteParameterChain +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteRatesWindowUI +OAI.MathematicalPhysics.Boltzmann.Compactness.FiniteThermalLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.KineticDensityMeasurable +OAI.MathematicalPhysics.Boltzmann.Compactness.KineticDilationIntegral +OAI.MathematicalPhysics.Boltzmann.Compactness.KineticEndpointCoordinates +OAI.MathematicalPhysics.Boltzmann.Compactness.KineticEntropyErrorLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.KineticWindowL1 +OAI.MathematicalPhysics.Boltzmann.Compactness.L1CurveEquality +OAI.MathematicalPhysics.Boltzmann.Compactness.L1TruncationCauchy +OAI.MathematicalPhysics.Boltzmann.Compactness.L1VelocityTranslationApproximation +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalAdmissibility +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalBeamBlock +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalL1ApproximationLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalMomentIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalizedBlockComparison +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalizedDampedBalance +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalizedGainCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalizedGainSmoothingAE +OAI.MathematicalPhysics.Boltzmann.Compactness.LocalizedHotMassGrowth +OAI.MathematicalPhysics.Boltzmann.Compactness.MeasurableResolvent +OAI.MathematicalPhysics.Boltzmann.Compactness.NormalizedCollisionRates +OAI.MathematicalPhysics.Boltzmann.Compactness.NormalizedGainCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.NormalizedKernelAction +OAI.MathematicalPhysics.Boltzmann.Compactness.NormalizedPairCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.PairBoundedTruncation +OAI.MathematicalPhysics.Boltzmann.Compactness.PairPatchCover +OAI.MathematicalPhysics.Boltzmann.Compactness.PairPatchIdentity +OAI.MathematicalPhysics.Boltzmann.Compactness.PairRepresentative +OAI.MathematicalPhysics.Boltzmann.Compactness.PairTranslatedProduct +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicCharacteristicGainUnit +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicDensityStrong +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicExistenceDischarge +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicFiniteGainStrong +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicFiniteMild +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicInitialEntropyLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicJointBudgetLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicLinearApproximation +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicMildApproximation +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicMomentEntropy +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicRenormalizedCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicSourceBound +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicStrongAverages +OAI.MathematicalPhysics.Boltzmann.Compactness.PeriodicWeakCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalCharacteristic +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalDissipationBridge +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalEntropyProduction +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalEvolution +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalFrequencyWindow +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalGainStrictTime +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalGainTransport +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalGlobalRenormalized +OAI.MathematicalPhysics.Boltzmann.Compactness.PhysicalLinearContinuous +OAI.MathematicalPhysics.Boltzmann.Compactness.PrefixComparisonConvergence +OAI.MathematicalPhysics.Boltzmann.Compactness.RenormalizedCollisionIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.RenormalizedIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedCoreSelection +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedLargeOutput +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedNonaxialLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedOriginDeletion +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedRemainderMeasure +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedTwoGainLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.SelectedWindowDeletion +OAI.MathematicalPhysics.Boltzmann.Compactness.StrongCompactPairTests +OAI.MathematicalPhysics.Boltzmann.Compactness.StrongMassClip +OAI.MathematicalPhysics.Boltzmann.Compactness.StrongMildRepresentative +OAI.MathematicalPhysics.Boltzmann.Compactness.StrongPairMoment +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformAverageCompactness +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformGain +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformGainTranslation +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformIntegrability +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformIntegrableCoordinates +OAI.MathematicalPhysics.Boltzmann.Compactness.UniformIntegrableGainTail +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakCapOuterBound +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakConservedMarginal +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakDuhamelLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakEntropyMarginal +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakL1Operations +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakL1ToWeakStar +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakLinearMomentLimit +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakTimeBalance +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakTimeLocalization +OAI.MathematicalPhysics.Boltzmann.Compactness.WeakTimeSurvival +OAI.MathematicalPhysics.Boltzmann.Jets.AnnularCharacteristicCutoff +OAI.MathematicalPhysics.Boltzmann.Jets.AnnularCollisionIntegrability +OAI.MathematicalPhysics.Boltzmann.Jets.AnnularEnvelopes +OAI.MathematicalPhysics.Boltzmann.Jets.AnnularTightness +OAI.MathematicalPhysics.Boltzmann.Jets.BeamGainNormalOrder +OAI.MathematicalPhysics.Boltzmann.Jets.BeamNormalCharacteristicIdentity +OAI.MathematicalPhysics.Boltzmann.Jets.BeamNormalOutgoing +OAI.MathematicalPhysics.Boltzmann.Jets.ColdCentralVanishing +OAI.MathematicalPhysics.Boltzmann.Jets.ColdFamilyGlobalStabilityAE +OAI.MathematicalPhysics.Boltzmann.Jets.ColdGaussianFamily +OAI.MathematicalPhysics.Boltzmann.Jets.ColdHotSourceDecomposition +OAI.MathematicalPhysics.Boltzmann.Jets.ColdMildRepresentative +OAI.MathematicalPhysics.Boltzmann.Jets.CoreDensityTranslation +OAI.MathematicalPhysics.Boltzmann.Jets.CoreJointParameterDensity +OAI.MathematicalPhysics.Boltzmann.Jets.CoreParameterStep +OAI.MathematicalPhysics.Boltzmann.Jets.FreeCoreGainKernel +OAI.MathematicalPhysics.Boltzmann.Jets.FreeCoreMismatch +OAI.MathematicalPhysics.Boltzmann.Jets.FreeCoreSharpBound +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricAnnularFrequency +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricColdSource +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricCommonBlock +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricDampedRetention +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricEntry +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricLocalizedEntry +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricMesh +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricPositiveCompact +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricSlice +OAI.MathematicalPhysics.Boltzmann.Jets.GeometricTwoCoreUniform +OAI.MathematicalPhysics.Boltzmann.Jets.JetBarrierKinetic +OAI.MathematicalPhysics.Boltzmann.Jets.JetBarriers +OAI.MathematicalPhysics.Boltzmann.Jets.JetColdLimitComparison +OAI.MathematicalPhysics.Boltzmann.Jets.JetContinuation +OAI.MathematicalPhysics.Boltzmann.Jets.JetCoreConvergence +OAI.MathematicalPhysics.Boltzmann.Jets.JetCoreMomentBound +OAI.MathematicalPhysics.Boltzmann.Jets.JetEnvelopeTimeIntegral +OAI.MathematicalPhysics.Boltzmann.Jets.JetFamilyBounds +OAI.MathematicalPhysics.Boltzmann.Jets.JetFiniteCap +OAI.MathematicalPhysics.Boltzmann.Jets.JetPeriodicDatum +OAI.MathematicalPhysics.Boltzmann.Jets.JetProfiles +OAI.MathematicalPhysics.Boltzmann.Jets.JetSupersolutions +OAI.MathematicalPhysics.Boltzmann.Jets.OriginMeshLimit +OAI.MathematicalPhysics.Boltzmann.Jets.OriginMeshStep +OAI.MathematicalPhysics.Boltzmann.Jets.PeriodicJetFamilies +OAI.MathematicalPhysics.Boltzmann.Jets.SpatialCutoffIntegrability +OAI.MathematicalPhysics.Boltzmann.Jets.SpatialDilationAE +OAI.MathematicalPhysics.Boltzmann.Jets.ThermalParameterChain +OAI.MathematicalPhysics.Boltzmann.Jets.ThermalPointBounds +OAI.MathematicalPhysics.Boltzmann.Jets.ThermalStripeIdentity +OAI.MathematicalPhysics.Boltzmann.Jets.TorusAnnularIntegrability +OAI.MathematicalPhysics.Boltzmann.Jets.TorusCharacteristic +OAI.MathematicalPhysics.Boltzmann.Jets.TorusChart +OAI.MathematicalPhysics.Boltzmann.Jets.TorusTailRegions +OAI.MathematicalPhysics.Boltzmann.Jets.TorusTransport +OAI.MathematicalPhysics.Boltzmann.Jets.TorusVelocityWindowAE +OAI.MathematicalPhysics.Boltzmann.Main +OAI.MathematicalPhysics.Boltzmann.Model +OAI.MathematicalPhysics.Boltzmann.UnconditionalMainProof diff --git a/tasks/boltzmann-nonuniqueness/solution/reference.py b/tasks/boltzmann-nonuniqueness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/boltzmann-nonuniqueness/solution/solve.sh b/tasks/boltzmann-nonuniqueness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ca6e2fd302af552abb4ea34cf313db87ecf2953d --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BoltzmannNonuniqueness, i.e. module OAI.MathematicalPhysics.Boltzmann.Main and the +# 525 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.Boltzmann.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BoltzmannNonuniqueness" diff --git a/tasks/boltzmann-nonuniqueness/task.toml b/tasks/boltzmann-nonuniqueness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2fc553603467eda32e46c5996edb6d4d61bf2a9d --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/boltzmann-nonuniqueness" +version = "1.0.0" +description = "Prove BoltzmannNonuniqueness (openai/math family 363: Boltzmann nonuniqueness with exact local conservation) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BoltzmannNonuniqueness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BoltzmannNonuniqueness" +family = "363" +family_title = "Boltzmann nonuniqueness with exact local conservation" +subject = "Partial differential equations" +theorems = ["OAI.BoltzmannNonuniqueness.nonuniqueness"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.Boltzmann.Main" +reference_modules = 525 +reference_lean_bytes = 7330824 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1584 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 18297 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/boltzmann-nonuniqueness/tests/Challenge.lean b/tasks/boltzmann-nonuniqueness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f09a521ed1a5353020f5391772a63593a2ad59d7 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/tests/Challenge.lean @@ -0,0 +1,215 @@ +import Mathlib + +namespace OAI + +/-! +# Nonuniqueness for the periodic hard-sphere Boltzmann equation + +Theorem 1.1, with the full entropy-class admissibility of Definition 2.1 and +strong initial L¹ continuity with integrable collision gain and loss. +-/ + +noncomputable section + +open MeasureTheory Set Filter +open scoped RealInnerProductSpace ENNReal Topology + +namespace BoltzmannNonuniqueness + +abbrev Velocity := EuclideanSpace ℝ (Fin 3) +abbrev Position := Fin 3 → AddCircle (1 : ℝ) +abbrev Phase := Position × Velocity +abbrev Density := Phase → ℝ +abbrev Sphere := Metric.sphere (0 : Velocity) 1 + +/-- Ordinary surface area, rather than normalized probability on the sphere. -/ +def sphereArea : Measure Sphere := (volume : Measure Velocity).toSphere + +def normalComponent (v w ω : Velocity) : ℝ := inner ℝ (v - w) ω + +def scatterLeft (v w ω : Velocity) : Velocity := v - normalComponent v w ω • ω + +def scatterRight (v w ω : Velocity) : Velocity := w + normalComponent v w ω • ω + +def collisionKernel (v w ω : Velocity) : ℝ := |normalComponent v w ω| + +def gain (f : Density) (x : Position) (v : Velocity) : ℝ := + ∫ p : Velocity × Sphere, + collisionKernel v p.1 p.2 * f (x, scatterLeft v p.1 p.2) * + f (x, scatterRight v p.1 p.2) + ∂((volume : Measure Velocity).prod sphereArea) + +def loss (f : Density) (x : Position) (v : Velocity) : ℝ := + ∫ p : Velocity × Sphere, + collisionKernel v p.1 p.2 * f (x, v) * f (x, p.1) + ∂((volume : Measure Velocity).prod sphereArea) + +def collision (f : Density) (x : Position) (v : Velocity) : ℝ := + gain f x v - loss f x v + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev Evolution := ℝ → Density +abbrev SpaceTimePhase := ℝ × Phase +abbrev LiftedSpaceTimePhase := ℝ × (Velocity × Velocity) + +def torusProjection (x : Velocity) : Position := fun i => (x i : AddCircle (1 : ℝ)) + +/-- A representative in the fundamental half-open unit cube, used only to evaluate periodic +derivatives. Periodicity makes those derivatives independent of this choice. -/ +def torusRepresentative (x : Position) : Velocity := + WithLp.toLp 2 (fun i => ((AddCircle.equivIco (1 : ℝ) 0) (x i) : ℝ)) + +def maxwellian (v : Velocity) : ℝ := + (2 * Real.pi) ^ (-(3 / 2 : ℝ)) * Real.exp (-‖v‖ ^ 2 / 2) + +def entropyMoment (f : Density) (z : Phase) : ℝ := + f z * (1 + ‖z.2‖ ^ 2 + |Real.log (f z)|) + +/-- The convention `0 |log 0| = 0` is automatic in this real-valued moment. -/ +def FiniteEntropyDatum (f : Density) : Prop := + (∀ᵐ z, 0 ≤ f z) ∧ AEStronglyMeasurable f ∧ Integrable (entropyMoment f) + +def BoundedVelocitySupport (f : Density) : Prop := + ∃ R : ℝ, 0 < R ∧ ∀ᵐ z, R < ‖z.2‖ → f z = 0 + +def energy (f : Density) : ℝ := ∫ z, ‖z.2‖ ^ 2 * f z + +def momentum (f : Density) : Velocity := ∫ z, f z • z.2 + +def relativeEntropy (f : Density) : ℝ := + ∫ z, f z * Real.log (f z / maxwellian z.2) - f z + maxwellian z.2 + +/-- Lower semicontinuous extension of `(A-B) log(A/B)` on the nonnegative quadrant. +The off-quadrant value is immaterial for nonnegative densities. -/ +def extendedEntropyProduction (A B : ℝ) : ℝ≥0∞ := + if A = 0 ∧ B = 0 then 0 + else if 0 < A ∧ 0 < B then ENNReal.ofReal ((A - B) * Real.log (A / B)) + else ⊤ + +def entropyDissipation (f : Density) : ℝ≥0∞ := + (4 : ℝ≥0∞)⁻¹ * ∫⁻ p : Position × (Velocity × (Velocity × Sphere)), + ENNReal.ofReal (collisionKernel p.2.1 p.2.2.1 p.2.2.2) * + extendedEntropyProduction + (f (p.1, scatterLeft p.2.1 p.2.2.1 p.2.2.2) * + f (p.1, scatterRight p.2.1 p.2.2.1 p.2.2.2)) + (f (p.1, p.2.1) * f (p.1, p.2.2.1)) + ∂((volume : Measure Position).prod ((volume : Measure Velocity).prod + ((volume : Measure Velocity).prod sphereArea))) + +/-- The renormalizations of Definition 2.1, with the right derivative at zero. -/ +structure Renormalization where + toFun : ℝ → ℝ + regular : ContDiffOn ℝ 1 toFun (Ici 0) + at_zero : toFun 0 = 0 + derivative_bound : ∃ C : ℝ, 0 ≤ C ∧ ∀ z ∈ Ici (0 : ℝ), + |derivWithin toFun (Ici 0) z| ≤ C / (1 + z) + +/-- A smooth test, periodic in the spatial variable and compact in time and velocity. -/ +structure KineticTest where + toFun : ℝ → Position → Velocity → ℝ + regular : ContDiff ℝ (⊤ : ℕ∞) (fun p : LiftedSpaceTimePhase => + toFun p.1 (torusProjection p.2.1) p.2.2) + compact_time_velocity : ∃ R : ℝ, 0 < R ∧ ∀ t x v, + R < |t| ∨ R < ‖v‖ → toFun t x v = 0 + +def KineticTest.transportDerivative (φ : KineticTest) (t : ℝ) (z : Phase) : ℝ := + fderiv ℝ (fun p : LiftedSpaceTimePhase => φ.toFun p.1 (torusProjection p.2.1) p.2.2) + (t, torusRepresentative z.1, z.2) (1, z.2, 0) + +/-- Smooth local mass tests have no velocity cutoff, since their velocity dependence is +introduced only by the transport derivative. -/ +structure MassTest where + toFun : ℝ → Position → ℝ + regular : ContDiff ℝ (⊤ : ℕ∞) (fun p : ℝ × Velocity => toFun p.1 (torusProjection p.2)) + compact_time : ∃ R : ℝ, 0 < R ∧ ∀ t x, R < |t| → toFun t x = 0 + +def MassTest.transportDerivative (φ : MassTest) (t : ℝ) (z : Phase) : ℝ := + fderiv ℝ (fun p : ℝ × Velocity => φ.toFun p.1 (torusProjection p.2)) + (t, torusRepresentative z.1) (1, z.2) + +def relativeDensity (F : Evolution) (t : ℝ) (z : Phase) : ℝ := F t z / maxwellian z.2 + +def renormalizedIntegrand (F : Evolution) (β : Renormalization) (φ : KineticTest) + (p : SpaceTimePhase) : ℝ := + maxwellian p.2.2 * β.toFun (relativeDensity F p.1 p.2) * + φ.transportDerivative p.1 p.2 + + derivWithin β.toFun (Ici 0) (relativeDensity F p.1 p.2) * + collision (F p.1) p.2.1 p.2.2 * φ.toFun p.1 p.2.1 p.2.2 + +def nonnegativeTimes : Set SpaceTimePhase := Ici (0 : ℝ) ×ˢ univ +def boundedTimes (T : ℝ) : Set SpaceTimePhase := Icc 0 T ×ˢ univ + +/-- Full global admissibility, including both separately renormalized collision terms, +local mass, total momentum, and the every-time energy and entropy inequalities. -/ +structure AdmissibleGlobal (f₀ : Density) (F : Evolution) : Prop where + datum : FiniteEntropyDatum f₀ + spacetime_measurable : AEStronglyMeasurable (fun p : SpaceTimePhase => F p.1 p.2) + (volume.restrict nonnegativeTimes) + finite_each_time : ∀ t ∈ Ici (0 : ℝ), FiniteEntropyDatum (F t) + initial : F 0 =ᵐ[volume] f₀ + weak_continuity : ∀ ψ : Phase → ℝ, Measurable ψ → + (∃ C : ℝ, ∀ z, |ψ z| ≤ C) → + ContinuousOn (fun t => ∫ z, F t z * ψ z) (Ici 0) + uniform_moment : ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, ∀ t ∈ Icc 0 T, + (∫ z, entropyMoment (F t) z) ≤ C + -- These finiteness conditions prevent the real Bochner integrals defining `gain` and + -- `loss` from silently taking the value zero at divergent collision fibers. + collision_fibers : ∀ T : ℝ, 0 ≤ T → ∀ᵐ p ∂volume.restrict (boundedTimes T), + Integrable (fun q : Velocity × Sphere => + collisionKernel p.2.2 q.1 q.2 * + F p.1 (p.2.1, scatterLeft p.2.2 q.1 q.2) * + F p.1 (p.2.1, scatterRight p.2.2 q.1 q.2)) + ((volume : Measure Velocity).prod sphereArea) ∧ + Integrable (fun q : Velocity × Sphere => + collisionKernel p.2.2 q.1 q.2 * F p.1 p.2 * F p.1 (p.2.1, q.1)) + ((volume : Measure Velocity).prod sphereArea) + gain_integrable : ∀ T : ℝ, 0 ≤ T → IntegrableOn + (fun p : SpaceTimePhase => gain (F p.1) p.2.1 p.2.2 / + (1 + relativeDensity F p.1 p.2)) (boundedTimes T) + loss_integrable : ∀ T : ℝ, 0 ≤ T → IntegrableOn + (fun p : SpaceTimePhase => loss (F p.1) p.2.1 p.2.2 / + (1 + relativeDensity F p.1 p.2)) (boundedTimes T) + renormalized_integrable : ∀ β φ, IntegrableOn (renormalizedIntegrand F β φ) + nonnegativeTimes + renormalized_equation : ∀ β : Renormalization, ∀ φ : KineticTest, + (∫ p in nonnegativeTimes, renormalizedIntegrand F β φ p) + + (∫ z, maxwellian z.2 * β.toFun (f₀ z / maxwellian z.2) * + φ.toFun 0 z.1 z.2) = 0 + local_mass_integrable : ∀ φ : MassTest, IntegrableOn + (fun p : SpaceTimePhase => F p.1 p.2 * φ.transportDerivative p.1 p.2) + nonnegativeTimes + local_mass : ∀ φ : MassTest, + (∫ p in nonnegativeTimes, F p.1 p.2 * φ.transportDerivative p.1 p.2) + + (∫ z, f₀ z * φ.toFun 0 z.1) = 0 + momentum_conservation : ∀ t ∈ Ici (0 : ℝ), momentum (F t) = momentum f₀ + energy_inequality : ∀ t ∈ Ici (0 : ℝ), energy (F t) ≤ energy f₀ + entropy_inequality : ∀ t ∈ Ici (0 : ℝ), + ENNReal.ofReal (relativeEntropy (F t)) + + (∫⁻ s in Icc (0 : ℝ) t, entropyDissipation (F s)) ≤ + ENNReal.ofReal (relativeEntropy f₀) + +/-- Additional regularity asserted on the common initial interval. The `eLpNorm` statement +is strong `L¹` continuity and cannot be made vacuous by a nonintegrable Bochner integral. -/ +structure StrongEarly (T : ℝ) (F : Evolution) : Prop where + positive_time : 0 < T + strong_continuity : ∀ t ∈ Icc 0 T, + Tendsto (fun s => eLpNorm (fun z => F s z - F t z) 1 volume) + (𝓝[Icc 0 T] t) (𝓝 0) + gain_integrable : IntegrableOn (fun p : SpaceTimePhase => gain (F p.1) p.2.1 p.2.2) + (boundedTimes T) + loss_integrable : IntegrableOn (fun p : SpaceTimePhase => loss (F p.1) p.2.1 p.2.2) + (boundedTimes T) + +theorem nonuniqueness : + ∃ f₀ : Density, BoundedVelocitySupport f₀ ∧ + ∃ (F G : Evolution) (T : ℝ), AdmissibleGlobal f₀ F ∧ AdmissibleGlobal f₀ G ∧ + StrongEarly T F ∧ StrongEarly T G ∧ + ∃ t ∈ Set.Icc 0 T, ¬(F t =ᵐ[MeasureTheory.volume] G t) := + sorry + +end BoltzmannNonuniqueness + +end + +end OAI diff --git a/tasks/boltzmann-nonuniqueness/tests/grade.py b/tasks/boltzmann-nonuniqueness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/boltzmann-nonuniqueness/tests/task.json b/tasks/boltzmann-nonuniqueness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7753624de856ef5a2a7a55768a19e49b349cf480 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BoltzmannNonuniqueness", + "comparator": { + "theorem_names": [ + "OAI.BoltzmannNonuniqueness.nonuniqueness" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 17397 +} \ No newline at end of file diff --git a/tasks/boltzmann-nonuniqueness/tests/test.sh b/tasks/boltzmann-nonuniqueness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/boltzmann-nonuniqueness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/boone-higman/environment/Dockerfile b/tasks/boone-higman/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/boone-higman/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/boone-higman/environment/fetch_mathlib.sh b/tasks/boone-higman/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/boone-higman/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/boone-higman/environment/lake-manifest.json b/tasks/boone-higman/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/boone-higman/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/boone-higman/environment/lakefile.lean b/tasks/boone-higman/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/boone-higman/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/boone-higman/environment/lean_setup.sh b/tasks/boone-higman/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/boone-higman/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/boone-higman/environment/pack_submission.py b/tasks/boone-higman/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/boone-higman/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/boone-higman/instruction.md b/tasks/boone-higman/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b4bf21c5b0bc2962678edd15bd78f9c01326271 --- /dev/null +++ b/tasks/boone-higman/instruction.md @@ -0,0 +1,83 @@ +# openai/math challenge `BooneHigman` (family 250) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 250 of the release, *The Boone–Higman conjecture and higher finiteness* +(Group theory). The family as a whole: A finitely generated group has decidable word problem exactly when it embeds in a finitely presented simple group, proving the Boone–Higman conjecture. The target can have type $F_\infty$: a classifying space with finitely many cells in each dimension. A single group of type $F_\infty$ can also contain every finitely presented group. + +The challenge is `BooneHigman`, also at `/opt/openai-math/challenges/BooneHigman.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace FiniteAlgebraicEnvelopes + +universe u + +abbrev Word (generatorCount : ℕ) := List (Fin generatorCount × Bool) + +def evalWord {GroupType : Type u} [Group GroupType] {generatorCount : ℕ} + (generators : Fin generatorCount → GroupType) (word : Word generatorCount) : GroupType := + (word.map fun letter => + if letter.2 then generators letter.1 else (generators letter.1)⁻¹).prod + +def HasDecidableWordProblem (GroupType : Type u) [Group GroupType] : Prop := + ∃ (generatorCount : ℕ) (generators : Fin generatorCount → GroupType), + Subgroup.closure (Set.range generators) = ⊤ ∧ + ComputablePred (fun word : Word generatorCount => evalWord generators word = 1) + +def EmbedsInFinitelyPresentedSimpleGroup (GroupType : Type u) [Group GroupType] : Prop := + ∃ (TargetGroup : Type u) (_ : Group TargetGroup), + Group.IsFinitelyPresented TargetGroup ∧ IsSimpleGroup TargetGroup ∧ + ∃ embedding : GroupType →* TargetGroup, Function.Injective embedding + +theorem main (GroupType : Type u) [Group GroupType] [Group.FG GroupType] : + HasDecidableWordProblem GroupType ↔ EmbedsInFinitelyPresentedSimpleGroup GroupType := by + sorry + +end FiniteAlgebraicEnvelopes + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BooneHigman.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FiniteAlgebraicEnvelopes.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/boone-higman/solution/closure.txt b/tasks/boone-higman/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8db2774d3e04ab29a632cfa760f64fec30c6ded --- /dev/null +++ b/tasks/boone-higman/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Computability.FiniteCompiler.Control +OAI.Computability.FiniteCompiler.Effectivity +OAI.Computability.FiniteCompiler.Machines +OAI.Computability.FiniteCompiler.Normalization +OAI.Computability.FiniteCompiler.Paths +OAI.Computability.FiniteCompiler.Quotients +OAI.Computability.FiniteCompiler.Rewriting +OAI.Computability.FiniteCompiler.Selectors +OAI.Computability.FiniteCompiler.SelfReference +OAI.Computability.FiniteCompiler.Simulator +OAI.Computability.FiniteCompiler.Surface +OAI.Computability.FiniteCompiler.TapeFolding +OAI.Computability.FiniteCompiler.Transition +OAI.Computability.FiniteCompiler.UniformControl +OAI.Computability.FiniteCompiler.UniformMachines +OAI.Computability.FiniteCompiler.UniformPaths +OAI.Computability.FiniteCompiler.Validator +OAI.GroupTheory.BooneHigman.ActionEnvelope +OAI.GroupTheory.BooneHigman.AdjacentPermutations +OAI.GroupTheory.BooneHigman.Affine +OAI.GroupTheory.BooneHigman.AffineModules +OAI.GroupTheory.BooneHigman.AlgebraPresentations +OAI.GroupTheory.BooneHigman.Basic +OAI.GroupTheory.BooneHigman.BinaryCategory +OAI.GroupTheory.BooneHigman.BinaryCoherence +OAI.GroupTheory.BooneHigman.CantorBricks +OAI.GroupTheory.BooneHigman.Contracted +OAI.GroupTheory.BooneHigman.Corners +OAI.GroupTheory.BooneHigman.DecoratedPresentation +OAI.GroupTheory.BooneHigman.Diagrams +OAI.GroupTheory.BooneHigman.EndpointCoherence +OAI.GroupTheory.BooneHigman.Enveloping +OAI.GroupTheory.BooneHigman.FinitePresentation +OAI.GroupTheory.BooneHigman.Generators +OAI.GroupTheory.BooneHigman.GroupInput +OAI.GroupTheory.BooneHigman.Main +OAI.GroupTheory.BooneHigman.MappingTori +OAI.GroupTheory.BooneHigman.MonoidAlgebras +OAI.GroupTheory.BooneHigman.PartialAffine +OAI.GroupTheory.BooneHigman.Steinberg +OAI.GroupTheory.BooneHigman.SteinbergLimits +OAI.GroupTheory.BooneHigman.SteinbergPresentation +OAI.GroupTheory.BooneHigman.TreeCoherence +OAI.GroupTheory.BooneHigman.TreeRefinement +OAI.GroupTheory.BooneHigman.Trees +OAI.GroupTheory.BooneHigman.TwistedSimplicity +OAI.GroupTheory.BooneHigman.WordProblem diff --git a/tasks/boone-higman/solution/reference.py b/tasks/boone-higman/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/boone-higman/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/boone-higman/solution/solve.sh b/tasks/boone-higman/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5daaba7d31c226c45fb224e8edca5b0b478ecb98 --- /dev/null +++ b/tasks/boone-higman/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BooneHigman, i.e. module OAI.GroupTheory.BooneHigman.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.BooneHigman.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BooneHigman" diff --git a/tasks/boone-higman/task.toml b/tasks/boone-higman/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..683fcefde425b178f52bfdf7b9f71ef7ca8429ca --- /dev/null +++ b/tasks/boone-higman/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/boone-higman" +version = "1.0.0" +description = "Prove BooneHigman (openai/math family 250: The Boone–Higman conjecture and higher finiteness) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BooneHigman.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BooneHigman" +family = "250" +family_title = "The Boone–Higman conjecture and higher finiteness" +subject = "Group theory" +theorems = ["OAI.FiniteAlgebraicEnvelopes.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.BooneHigman.Main" +reference_modules = 47 +reference_lean_bytes = 1687310 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 976 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13218 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/boone-higman/tests/Challenge.lean b/tasks/boone-higman/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a6371d178ba092822c066e530fb14c7ee0a19d39 --- /dev/null +++ b/tasks/boone-higman/tests/Challenge.lean @@ -0,0 +1,32 @@ +import Mathlib + +namespace OAI + +namespace FiniteAlgebraicEnvelopes + +universe u + +abbrev Word (generatorCount : ℕ) := List (Fin generatorCount × Bool) + +def evalWord {GroupType : Type u} [Group GroupType] {generatorCount : ℕ} + (generators : Fin generatorCount → GroupType) (word : Word generatorCount) : GroupType := + (word.map fun letter => + if letter.2 then generators letter.1 else (generators letter.1)⁻¹).prod + +def HasDecidableWordProblem (GroupType : Type u) [Group GroupType] : Prop := + ∃ (generatorCount : ℕ) (generators : Fin generatorCount → GroupType), + Subgroup.closure (Set.range generators) = ⊤ ∧ + ComputablePred (fun word : Word generatorCount => evalWord generators word = 1) + +def EmbedsInFinitelyPresentedSimpleGroup (GroupType : Type u) [Group GroupType] : Prop := + ∃ (TargetGroup : Type u) (_ : Group TargetGroup), + Group.IsFinitelyPresented TargetGroup ∧ IsSimpleGroup TargetGroup ∧ + ∃ embedding : GroupType →* TargetGroup, Function.Injective embedding + +theorem main (GroupType : Type u) [Group GroupType] [Group.FG GroupType] : + HasDecidableWordProblem GroupType ↔ EmbedsInFinitelyPresentedSimpleGroup GroupType := by + sorry + +end FiniteAlgebraicEnvelopes + +end OAI diff --git a/tasks/boone-higman/tests/grade.py b/tasks/boone-higman/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/boone-higman/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/boone-higman/tests/task.json b/tasks/boone-higman/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b5e73f1e3ac26a4222022ada4ca8c30a8c7cfa40 --- /dev/null +++ b/tasks/boone-higman/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BooneHigman", + "comparator": { + "theorem_names": [ + "OAI.FiniteAlgebraicEnvelopes.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12318 +} \ No newline at end of file diff --git a/tasks/boone-higman/tests/test.sh b/tasks/boone-higman/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/boone-higman/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/borsuk-nine/environment/Dockerfile b/tasks/borsuk-nine/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/borsuk-nine/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/borsuk-nine/environment/fetch_mathlib.sh b/tasks/borsuk-nine/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/borsuk-nine/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/borsuk-nine/environment/lake-manifest.json b/tasks/borsuk-nine/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/borsuk-nine/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/borsuk-nine/environment/lakefile.lean b/tasks/borsuk-nine/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/borsuk-nine/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/borsuk-nine/environment/lean_setup.sh b/tasks/borsuk-nine/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/borsuk-nine/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/borsuk-nine/environment/pack_submission.py b/tasks/borsuk-nine/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/borsuk-nine/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/borsuk-nine/instruction.md b/tasks/borsuk-nine/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37415a1983c702e43d98d9618f1c6f54425ccdad --- /dev/null +++ b/tasks/borsuk-nine/instruction.md @@ -0,0 +1,85 @@ +# openai/math challenge `BorsukNine` (family 156) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 156 of the release, *Borsuk's conjecture fails in dimension nine* +(Combinatorics). The family as a whole: Constructs a compact subset of $\mathbb R^9$ that cannot be covered by ten sets of strictly smaller diameter, disproving Borsuk's covering assertion already in dimension nine. The example consists of rank-one orthogonal projectors onto lines in $\mathbb R^4$, with the Frobenius metric. + +The challenge is `BorsukNine`, also at `/opt/openai-math/challenges/BorsukNine.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace BorsukNine + +abbrev Vector4 := EuclideanSpace ℝ (Fin 4) +abbrev Matrix4 := EuclideanSpace ℝ (Fin 4 × Fin 4) + +def projector (u : Vector4) : Matrix4 := + WithLp.toLp 2 (fun ij => u ij.1 * u ij.2) + +def projectorSet : Set Matrix4 := + projector '' {u : Vector4 | ‖u‖ = 1} + +def traceOneSymmetric : Set Matrix4 := + {A | (∀ i j : Fin 4, A (i, j) = A (j, i)) ∧ ∑ i : Fin 4, A (i, i) = 1} + +def HasTenSmallCover : Prop := + ∃ C : Fin 10 → Set Matrix4, + (∀ i, C i ⊆ projectorSet) ∧ + projectorSet ⊆ ⋃ i, C i ∧ + ∀ i, Metric.diam (C i) < Real.sqrt 2 + +theorem main_theorem : + IsCompact projectorSet ∧ + projectorSet ⊆ traceOneSymmetric ∧ + Metric.diam projectorSet = Real.sqrt 2 ∧ + ¬ HasTenSmallCover := by + sorry + +end BorsukNine + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BorsukNine.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BorsukNine.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/borsuk-nine/solution/closure.txt b/tasks/borsuk-nine/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f866e530981d979dff563ef082ea40d0cd6a80c1 --- /dev/null +++ b/tasks/borsuk-nine/solution/closure.txt @@ -0,0 +1,269 @@ +OAI.Geometry.Borsuk.Counterexample +OAI.Geometry.Borsuk.FiniteCases.Cases001 +OAI.Geometry.Borsuk.FiniteCases.Cases002 +OAI.Geometry.Borsuk.FiniteCases.Cases003 +OAI.Geometry.Borsuk.FiniteCases.Cases004 +OAI.Geometry.Borsuk.FiniteCases.Cases005 +OAI.Geometry.Borsuk.FiniteCases.Cases006 +OAI.Geometry.Borsuk.FiniteCases.Cases007 +OAI.Geometry.Borsuk.FiniteCases.Cases008 +OAI.Geometry.Borsuk.FiniteCases.Cases009 +OAI.Geometry.Borsuk.FiniteCases.Cases010 +OAI.Geometry.Borsuk.FiniteCases.Cases011 +OAI.Geometry.Borsuk.FiniteCases.Cases012 +OAI.Geometry.Borsuk.FiniteCases.Cases013 +OAI.Geometry.Borsuk.FiniteCases.Cases014 +OAI.Geometry.Borsuk.FiniteCases.Cases015 +OAI.Geometry.Borsuk.FiniteCases.Cases016 +OAI.Geometry.Borsuk.FiniteCases.Cases017 +OAI.Geometry.Borsuk.FiniteCases.Cases018 +OAI.Geometry.Borsuk.FiniteCases.Cases019 +OAI.Geometry.Borsuk.FiniteCases.Cases020 +OAI.Geometry.Borsuk.FiniteCases.Cases021 +OAI.Geometry.Borsuk.FiniteCases.Cases022 +OAI.Geometry.Borsuk.FiniteCases.Cases023 +OAI.Geometry.Borsuk.FiniteCases.Cases024 +OAI.Geometry.Borsuk.FiniteCases.Cases025 +OAI.Geometry.Borsuk.FiniteCases.Cases026 +OAI.Geometry.Borsuk.FiniteCases.Cases027 +OAI.Geometry.Borsuk.FiniteCases.Cases028 +OAI.Geometry.Borsuk.FiniteCases.Cases029 +OAI.Geometry.Borsuk.FiniteCases.Cases030 +OAI.Geometry.Borsuk.FiniteCases.Cases031 +OAI.Geometry.Borsuk.FiniteCases.Cases032 +OAI.Geometry.Borsuk.FiniteCases.Cases033 +OAI.Geometry.Borsuk.FiniteCases.Cases034 +OAI.Geometry.Borsuk.FiniteCases.Cases035 +OAI.Geometry.Borsuk.FiniteCases.Cases036 +OAI.Geometry.Borsuk.FiniteCases.Cases037 +OAI.Geometry.Borsuk.FiniteCases.Cases038 +OAI.Geometry.Borsuk.FiniteCases.Cases039 +OAI.Geometry.Borsuk.FiniteCases.Cases040 +OAI.Geometry.Borsuk.FiniteCases.Cases041 +OAI.Geometry.Borsuk.FiniteCases.Cases042 +OAI.Geometry.Borsuk.FiniteCases.Cases043 +OAI.Geometry.Borsuk.FiniteCases.Cases044 +OAI.Geometry.Borsuk.FiniteCases.Cases045 +OAI.Geometry.Borsuk.FiniteCases.Cases046 +OAI.Geometry.Borsuk.FiniteCases.Cases047 +OAI.Geometry.Borsuk.FiniteCases.Cases048 +OAI.Geometry.Borsuk.FiniteCases.Cases049 +OAI.Geometry.Borsuk.FiniteCases.Cases050 +OAI.Geometry.Borsuk.FiniteCases.Cases051 +OAI.Geometry.Borsuk.FiniteCases.Cases052 +OAI.Geometry.Borsuk.FiniteCases.Cases053 +OAI.Geometry.Borsuk.FiniteCases.Cases054 +OAI.Geometry.Borsuk.FiniteCases.Cases055 +OAI.Geometry.Borsuk.FiniteCases.Cases056 +OAI.Geometry.Borsuk.FiniteCases.Cases057 +OAI.Geometry.Borsuk.FiniteCases.Cases058 +OAI.Geometry.Borsuk.FiniteCases.Cases059 +OAI.Geometry.Borsuk.FiniteCases.Cases060 +OAI.Geometry.Borsuk.FiniteCases.Cases061 +OAI.Geometry.Borsuk.FiniteCases.Cases062 +OAI.Geometry.Borsuk.FiniteCases.Cases063 +OAI.Geometry.Borsuk.FiniteCases.Cases064 +OAI.Geometry.Borsuk.FiniteCases.Cases065 +OAI.Geometry.Borsuk.FiniteCases.Cases066 +OAI.Geometry.Borsuk.FiniteCases.Cases067 +OAI.Geometry.Borsuk.FiniteCases.Cases068 +OAI.Geometry.Borsuk.FiniteCases.Cases069 +OAI.Geometry.Borsuk.FiniteCases.Cases070 +OAI.Geometry.Borsuk.FiniteCases.Cases071 +OAI.Geometry.Borsuk.FiniteCases.Cases072 +OAI.Geometry.Borsuk.FiniteCases.Cases073 +OAI.Geometry.Borsuk.FiniteCases.Cases074 +OAI.Geometry.Borsuk.FiniteCases.Cases075 +OAI.Geometry.Borsuk.FiniteCases.Cases076 +OAI.Geometry.Borsuk.FiniteCases.Cases077 +OAI.Geometry.Borsuk.FiniteCases.Cases078 +OAI.Geometry.Borsuk.FiniteCases.Cases079 +OAI.Geometry.Borsuk.FiniteCases.Cases080 +OAI.Geometry.Borsuk.FiniteCases.Cases081 +OAI.Geometry.Borsuk.FiniteCases.Cases082 +OAI.Geometry.Borsuk.FiniteCases.Cases083 +OAI.Geometry.Borsuk.FiniteCases.Cases084 +OAI.Geometry.Borsuk.FiniteCases.Cases085 +OAI.Geometry.Borsuk.FiniteCases.Cases086 +OAI.Geometry.Borsuk.FiniteCases.Cases087 +OAI.Geometry.Borsuk.FiniteCases.Cases088 +OAI.Geometry.Borsuk.FiniteCases.Cases089 +OAI.Geometry.Borsuk.FiniteCases.Cases090 +OAI.Geometry.Borsuk.FiniteCases.Cases091 +OAI.Geometry.Borsuk.FiniteCases.Cases092 +OAI.Geometry.Borsuk.FiniteCases.Cases093 +OAI.Geometry.Borsuk.FiniteCases.Cases094 +OAI.Geometry.Borsuk.FiniteCases.Cases095 +OAI.Geometry.Borsuk.FiniteCases.Cases096 +OAI.Geometry.Borsuk.FiniteCases.Cases097 +OAI.Geometry.Borsuk.FiniteCases.Cases098 +OAI.Geometry.Borsuk.FiniteCases.Cases099 +OAI.Geometry.Borsuk.FiniteCases.Cases100 +OAI.Geometry.Borsuk.FiniteCases.Cases101 +OAI.Geometry.Borsuk.FiniteCases.Cases102 +OAI.Geometry.Borsuk.FiniteCases.Cases103 +OAI.Geometry.Borsuk.FiniteCases.Cases104 +OAI.Geometry.Borsuk.FiniteCases.Cases105 +OAI.Geometry.Borsuk.FiniteCases.Cases106 +OAI.Geometry.Borsuk.FiniteCases.Cases107 +OAI.Geometry.Borsuk.FiniteCases.Cases108 +OAI.Geometry.Borsuk.FiniteCases.Cases109 +OAI.Geometry.Borsuk.FiniteCases.Cases110 +OAI.Geometry.Borsuk.FiniteCases.Cases111 +OAI.Geometry.Borsuk.FiniteCases.Cases112 +OAI.Geometry.Borsuk.FiniteCases.Cases113 +OAI.Geometry.Borsuk.FiniteCases.Cases114 +OAI.Geometry.Borsuk.FiniteCases.Cases115 +OAI.Geometry.Borsuk.FiniteCases.Cases116 +OAI.Geometry.Borsuk.FiniteCases.Cases117 +OAI.Geometry.Borsuk.FiniteCases.Cases118 +OAI.Geometry.Borsuk.FiniteCases.Cases119 +OAI.Geometry.Borsuk.FiniteCases.Cases120 +OAI.Geometry.Borsuk.FiniteCases.Cases121 +OAI.Geometry.Borsuk.FiniteCases.Cases122 +OAI.Geometry.Borsuk.FiniteCases.Cases123 +OAI.Geometry.Borsuk.FiniteCases.Cases124 +OAI.Geometry.Borsuk.FiniteCases.Cases125 +OAI.Geometry.Borsuk.FiniteCases.Cases126 +OAI.Geometry.Borsuk.FiniteCases.Cases127 +OAI.Geometry.Borsuk.FiniteCases.Cases128 +OAI.Geometry.Borsuk.FiniteCases.Cases129 +OAI.Geometry.Borsuk.FiniteCases.Cases130 +OAI.Geometry.Borsuk.FiniteCases.Cases131 +OAI.Geometry.Borsuk.FiniteCases.Cases132 +OAI.Geometry.Borsuk.FiniteCases.Cases133 +OAI.Geometry.Borsuk.FiniteCases.Cases134 +OAI.Geometry.Borsuk.FiniteCases.Cases135 +OAI.Geometry.Borsuk.FiniteCases.Cases136 +OAI.Geometry.Borsuk.FiniteCases.Cases137 +OAI.Geometry.Borsuk.FiniteCases.Cases138 +OAI.Geometry.Borsuk.FiniteCases.Cases139 +OAI.Geometry.Borsuk.FiniteCases.Cases140 +OAI.Geometry.Borsuk.FiniteCases.Cases141 +OAI.Geometry.Borsuk.FiniteCases.Cases142 +OAI.Geometry.Borsuk.FiniteCases.Cases143 +OAI.Geometry.Borsuk.FiniteCases.Cases144 +OAI.Geometry.Borsuk.FiniteCases.Cases145 +OAI.Geometry.Borsuk.LocalParity.ChartRegular +OAI.Geometry.Borsuk.LocalParity.LocalModel +OAI.Geometry.Borsuk.LocalParity.LocalRegular +OAI.Geometry.Borsuk.LocalParity.MatrixParity +OAI.Geometry.Borsuk.LocalParity.NoFreeRidge +OAI.Geometry.Borsuk.LocalParity.RegularBase +OAI.Geometry.Borsuk.LocalParity.RegularModel +OAI.Geometry.Borsuk.LocalParity.RegularPatch +OAI.Geometry.Borsuk.LocalParity.Sard +OAI.Geometry.Borsuk.LocalParity.SphereBlock +OAI.Geometry.Borsuk.LocalParity.SphereNullPatch +OAI.Geometry.Borsuk.LocalParity.SphereParity +OAI.Geometry.Borsuk.LocalParity.TraceLocalModels +OAI.Geometry.Borsuk.Main +OAI.Geometry.Borsuk.MatrixGeometry.BlockLine +OAI.Geometry.Borsuk.MatrixGeometry.BlockParts +OAI.Geometry.Borsuk.MatrixGeometry.BlockVector +OAI.Geometry.Borsuk.MatrixGeometry.CenterApproximation +OAI.Geometry.Borsuk.MatrixGeometry.FibreContinuity +OAI.Geometry.Borsuk.MatrixGeometry.FibreHomotopy +OAI.Geometry.Borsuk.MatrixGeometry.FibreTransport +OAI.Geometry.Borsuk.MatrixGeometry.FinitePositiveBound +OAI.Geometry.Borsuk.MatrixGeometry.LineRepresentative +OAI.Geometry.Borsuk.MatrixGeometry.MatrixCompression +OAI.Geometry.Borsuk.MatrixGeometry.MatrixFibre +OAI.Geometry.Borsuk.MatrixGeometry.MatrixKernel +OAI.Geometry.Borsuk.MatrixGeometry.MatrixNorm +OAI.Geometry.Borsuk.MatrixGeometry.MatrixReflection +OAI.Geometry.Borsuk.MatrixGeometry.MatrixTransport +OAI.Geometry.Borsuk.MatrixGeometry.ModelRay +OAI.Geometry.Borsuk.MatrixGeometry.PositiveSlice +OAI.Geometry.Borsuk.MatrixGeometry.Rank +OAI.Geometry.Borsuk.MatrixGeometry.RankPreimage +OAI.Geometry.Borsuk.MatrixGeometry.ReflectionTransport +OAI.Geometry.Borsuk.MatrixGeometry.SignedExtension +OAI.Geometry.Borsuk.MatrixGeometry.SpectralChart +OAI.Geometry.Borsuk.MatrixGeometry.SymmetricCoordinates +OAI.Geometry.Borsuk.MatrixGeometry.SymmetricEntries +OAI.Geometry.Borsuk.MatrixGeometry.TraceHomotopy +OAI.Geometry.Borsuk.MatrixGeometry.TracePatchModels +OAI.Geometry.Borsuk.Model +OAI.Geometry.Borsuk.Projectors.Basic +OAI.Geometry.Borsuk.Projectors.ChartSurgery +OAI.Geometry.Borsuk.Projectors.CompactLocalHomotopy +OAI.Geometry.Borsuk.Projectors.CompactTargetHits +OAI.Geometry.Borsuk.Projectors.CoordinateSum +OAI.Geometry.Borsuk.Projectors.FiniteClosedCutoffs +OAI.Geometry.Borsuk.Projectors.FiniteOpenGlue +OAI.Geometry.Borsuk.Projectors.FinitePatch +OAI.Geometry.Borsuk.Projectors.FiniteSmoothSliceMisses +OAI.Geometry.Borsuk.Projectors.FiniteSmoothSliceMissesBounded +OAI.Geometry.Borsuk.Projectors.NegativeQuadratic +OAI.Geometry.Borsuk.Projectors.NullImage +OAI.Geometry.Borsuk.Projectors.RaySet +OAI.Geometry.Borsuk.Projectors.Restrict +OAI.Geometry.Borsuk.Projectors.SimplexPoint +OAI.Geometry.Borsuk.Projectors.Tangent +OAI.Geometry.Borsuk.Projectors.TenPure +OAI.Geometry.Borsuk.Projectors.Within +OAI.Geometry.Borsuk.Simplicial.Approximation +OAI.Geometry.Borsuk.Simplicial.BarycenterNeg +OAI.Geometry.Borsuk.Simplicial.BoolCubeConstant +OAI.Geometry.Borsuk.Simplicial.CharacteristicDegree +OAI.Geometry.Borsuk.Simplicial.Coefficients +OAI.Geometry.Borsuk.Simplicial.CompactAdditiveLocality +OAI.Geometry.Borsuk.Simplicial.ContigSimplexBoundary +OAI.Geometry.Borsuk.Simplicial.CrossChainDimensionBound +OAI.Geometry.Borsuk.Simplicial.CrossEmbedding +OAI.Geometry.Borsuk.Simplicial.DoubleEraseSumFun +OAI.Geometry.Borsuk.Simplicial.Equivariance +OAI.Geometry.Borsuk.Simplicial.EventuallyFineSphereLabel +OAI.Geometry.Borsuk.Simplicial.F2 +OAI.Geometry.Borsuk.Simplicial.FineCrossMap +OAI.Geometry.Borsuk.Simplicial.FineCrossMapMesh +OAI.Geometry.Borsuk.Simplicial.Flip +OAI.Geometry.Borsuk.Simplicial.GeneralTarget +OAI.Geometry.Borsuk.Simplicial.LabelRegion +OAI.Geometry.Borsuk.Simplicial.LinearMapSupport +OAI.Geometry.Borsuk.Simplicial.MapChainsEquivSimplexAll +OAI.Geometry.Borsuk.Simplicial.Maps +OAI.Geometry.Borsuk.Simplicial.MaxIndex +OAI.Geometry.Borsuk.Simplicial.MemSupportSimplex +OAI.Geometry.Borsuk.Simplicial.NormMap +OAI.Geometry.Borsuk.Simplicial.NullHomotopyLocalModels +OAI.Geometry.Borsuk.Simplicial.OddHomotopySurjective +OAI.Geometry.Borsuk.Simplicial.OddSphereDimensionBoundFintype +OAI.Geometry.Borsuk.Simplicial.Refinement +OAI.Geometry.Borsuk.Simplicial.SignVector +OAI.Geometry.Borsuk.Simplicial.SignedVertex +OAI.Geometry.Borsuk.Simplicial.SimplexMemDegreeAll +OAI.Geometry.Borsuk.Simplicial.SubdivSimplex +OAI.Geometry.Borsuk.Simplicial.Supports +OAI.Geometry.Borsuk.Simplicial.UnitRadial +OAI.Geometry.Borsuk.SmithTheory.CharacteristicCochains +OAI.Geometry.Borsuk.SmithTheory.Involution +OAI.Geometry.Borsuk.SphereGeometry.HemisphereChart +OAI.Geometry.Borsuk.SphereGeometry.HomogeneousLift +OAI.Geometry.Borsuk.SphereGeometry.IntegralLift +OAI.Geometry.Borsuk.SphereGeometry.NormSphere +OAI.Geometry.Borsuk.SphereGeometry.OddSphereMap +OAI.Geometry.Borsuk.SphereGeometry.SphereExtension +OAI.Geometry.Borsuk.SphereGeometry.SphereMeasure +OAI.Geometry.Borsuk.SphereGeometry.SphereMoments +OAI.Geometry.Borsuk.SphereGeometry.TraceSphere +OAI.Geometry.Borsuk.Support.ActiveChambers +OAI.Geometry.Borsuk.Support.AllPairs +OAI.Geometry.Borsuk.Support.BalancedChart +OAI.Geometry.Borsuk.Support.ChamberPath +OAI.Geometry.Borsuk.Support.Chambers +OAI.Geometry.Borsuk.Support.DisjointChambers +OAI.Geometry.Borsuk.Support.FacetTangent +OAI.Geometry.Borsuk.Support.FullSupport +OAI.Geometry.Borsuk.Support.LocalMix +OAI.Geometry.Borsuk.Support.MixedHits +OAI.Geometry.Borsuk.Support.MixedHomotopy +OAI.Geometry.Borsuk.Support.NegativeFibre +OAI.Geometry.Borsuk.Support.Purity +OAI.Geometry.Borsuk.Support.PurityChart +OAI.Geometry.Borsuk.Support.PurityGeometry +OAI.Geometry.Borsuk.Support.SixFaces +OAI.Geometry.Borsuk.Support.SpectralSupport +OAI.Geometry.Borsuk.Support.SupportIncidence +OAI.Geometry.Borsuk.TenLabels.Labels diff --git a/tasks/borsuk-nine/solution/reference.py b/tasks/borsuk-nine/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/borsuk-nine/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/borsuk-nine/solution/solve.sh b/tasks/borsuk-nine/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc421af58dbda05102e9fac09afad47045c74b6a --- /dev/null +++ b/tasks/borsuk-nine/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BorsukNine, i.e. module OAI.Geometry.Borsuk.Main and the +# 269 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.Borsuk.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BorsukNine" diff --git a/tasks/borsuk-nine/task.toml b/tasks/borsuk-nine/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b73771a94ea53ee3f18734db99fbe620d5557219 --- /dev/null +++ b/tasks/borsuk-nine/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/borsuk-nine" +version = "1.0.0" +description = "Prove BorsukNine (openai/math family 156: Borsuk's conjecture fails in dimension nine) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BorsukNine.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BorsukNine" +family = "156" +family_title = "Borsuk's conjecture fails in dimension nine" +subject = "Combinatorics" +theorems = ["OAI.BorsukNine.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.Borsuk.Main" +reference_modules = 269 +reference_lean_bytes = 3525234 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 893 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14872 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/borsuk-nine/tests/Challenge.lean b/tasks/borsuk-nine/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..670e908daaf570021f790cf42bd3169e172158f1 --- /dev/null +++ b/tasks/borsuk-nine/tests/Challenge.lean @@ -0,0 +1,34 @@ +import Mathlib + +namespace OAI + +namespace BorsukNine + +abbrev Vector4 := EuclideanSpace ℝ (Fin 4) +abbrev Matrix4 := EuclideanSpace ℝ (Fin 4 × Fin 4) + +def projector (u : Vector4) : Matrix4 := + WithLp.toLp 2 (fun ij => u ij.1 * u ij.2) + +def projectorSet : Set Matrix4 := + projector '' {u : Vector4 | ‖u‖ = 1} + +def traceOneSymmetric : Set Matrix4 := + {A | (∀ i j : Fin 4, A (i, j) = A (j, i)) ∧ ∑ i : Fin 4, A (i, i) = 1} + +def HasTenSmallCover : Prop := + ∃ C : Fin 10 → Set Matrix4, + (∀ i, C i ⊆ projectorSet) ∧ + projectorSet ⊆ ⋃ i, C i ∧ + ∀ i, Metric.diam (C i) < Real.sqrt 2 + +theorem main_theorem : + IsCompact projectorSet ∧ + projectorSet ⊆ traceOneSymmetric ∧ + Metric.diam projectorSet = Real.sqrt 2 ∧ + ¬ HasTenSmallCover := by + sorry + +end BorsukNine + +end OAI diff --git a/tasks/borsuk-nine/tests/grade.py b/tasks/borsuk-nine/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/borsuk-nine/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/borsuk-nine/tests/task.json b/tasks/borsuk-nine/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3389afe0f8d02621fb796cc90201b4e5af2cfabe --- /dev/null +++ b/tasks/borsuk-nine/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BorsukNine", + "comparator": { + "theorem_names": [ + "OAI.BorsukNine.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13972 +} \ No newline at end of file diff --git a/tasks/borsuk-nine/tests/test.sh b/tasks/borsuk-nine/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/borsuk-nine/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bounded-recovery/environment/Dockerfile b/tasks/bounded-recovery/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bounded-recovery/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bounded-recovery/environment/fetch_mathlib.sh b/tasks/bounded-recovery/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bounded-recovery/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bounded-recovery/environment/lake-manifest.json b/tasks/bounded-recovery/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bounded-recovery/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bounded-recovery/environment/lakefile.lean b/tasks/bounded-recovery/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bounded-recovery/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bounded-recovery/environment/lean_setup.sh b/tasks/bounded-recovery/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bounded-recovery/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bounded-recovery/environment/pack_submission.py b/tasks/bounded-recovery/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bounded-recovery/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bounded-recovery/instruction.md b/tasks/bounded-recovery/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5c9c61dede912c4ee43c2bed71fb494340397e09 --- /dev/null +++ b/tasks/bounded-recovery/instruction.md @@ -0,0 +1,153 @@ +# openai/math challenge `BoundedRecovery` (family 290) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 290 of the release, *Connes' bicentralizer conjecture and relative bicentralizers* +(Operator algebras). The family as a whole: Proves Connes' bicentralizer conjecture for every type $\mathrm{III}_1$ factor with separable predual and every faithful normal state. More generally, for every inclusion $N\subset M$ of von Neumann algebras with separable preduals admitting a faithful normal conditional expectation, constructs an amenable expected subalgebra $P\subset N$ with $P'\cap c(M)=N'\cap c(M)$, resolving the relative bicentralizer conjecture. + +The challenge is `BoundedRecovery`, also at `/opt/openai-math/challenges/BoundedRecovery.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Nondegenerate spectral calculus, the closed Tomita graph, and bounded recovery. -/ + +universe u + +noncomputable section + +open Filter MeasureTheory Set +open scoped Topology ComplexConjugate + +namespace BoundedRecovery + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def spectralCharacter (t : ℝ) : BoundedContinuousFunction ℝ ℂ := + BoundedContinuousFunction.ofNormedAddCommGroup + (fun u : ℝ => Complex.exp (((t * u : ℝ) : ℂ) * Complex.I)) + (by fun_prop) 1 (by intro u; simp [Complex.norm_exp]) + +def halfExponentialCutoff (n : ℕ) : BoundedContinuousFunction ℝ ℂ := + BoundedContinuousFunction.ofNormedAddCommGroup + (fun u : ℝ => (Real.exp (min (n : ℝ) u / 2) : ℂ)) + (by fun_prop) (Real.exp ((n : ℝ) / 2)) (by + intro u + simp only [Complex.norm_real, Real.norm_eq_abs, abs_of_pos (Real.exp_pos _)] + exact Real.exp_le_exp.mpr (div_le_div_of_nonneg_right (min_le_left _ _) (by norm_num))) + +structure RealSpectralCalculus (H : Type u) [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] where + calculus : (BoundedContinuousFunction ℝ ℂ) →⋆ₐ[ℂ] (H →L[ℂ] H) + nondegenerate : Dense {h : H | ∃ f : BoundedContinuousFunction ℝ ℂ, + HasCompactSupport (f : ℝ → ℂ) ∧ ∃ k : H, calculus f k = h} + +namespace RealSpectralCalculus + +def unitary (D : RealSpectralCalculus H) (t : ℝ) : H →L[ℂ] H := + D.calculus (spectralCharacter t) + +def halfGraph (D : RealSpectralCalculus H) : Set (H × H) := + {p | Tendsto (fun n : ℕ => D.calculus (halfExponentialCutoff n) p.1) atTop (𝓝 p.2)} + +def HasSpectralSupport (D : RealSpectralCalculus H) (I : Set ℝ) (h : H) : Prop := + ∀ f : BoundedContinuousFunction ℝ ℂ, (∀ u ∈ I, f u = 0) → D.calculus f h = 0 + +end RealSpectralCalculus + +structure StandardModularData (H : Type u) [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] where + M : VonNeumannAlgebra H + xi : H + norm_xi : ‖xi‖ = 1 + cyclic : Dense {h : H | ∃ a : H →L[ℂ] H, a ∈ M ∧ a xi = h} + separating : ∀ a : H →L[ℂ] H, a ∈ M → a xi = 0 → a = 0 + D : RealSpectralCalculus H + J : H ≃ₗᵢ⋆[ℂ] H + conjugation : Function.Involutive J + tomita_graph : closure {p : H × H | ∃ a : H →L[ℂ] H, + a ∈ M ∧ p = (a xi, (star a) xi)} = + {p | ∃ q : H, (p.1, q) ∈ D.halfGraph ∧ p.2 = J q} + +namespace StandardModularData + +def sigma (S : StandardModularData H) (t : ℝ) (a : H →L[ℂ] H) : H →L[ℂ] H := + S.D.unitary t * a * S.D.unitary (-t) + +def ScalarCentralizer (S : StandardModularData H) : Prop := + ∀ a : H →L[ℂ] H, a ∈ S.M → (∀ t : ℝ, S.sigma t a = a) → + ∃ c : ℂ, a = c • (1 : H →L[ℂ] H) + +end StandardModularData + +def symmetricAverage (f : ℝ → ℝ) (k : ℕ) : ℝ := + (2 * (k : ℝ))⁻¹ * ∫ t in -(k : ℝ)..(k : ℝ), f t + +def fixedMean (omega : Ultrafilter ℕ) (f : ℝ → ℝ) : ℝ := + Filter.limUnder (omega : Filter ℕ) (symmetricAverage f) + +def RecoveryConclusion (S : StandardModularData H) (T : H →L[ℂ] H) + (s : ℝ) (delta : ℕ → ℝ) : Prop := + ∃ (nj : ℕ → ℕ) (_ : StrictMono nj) (v : ℕ → (H →L[ℂ] H)) (C eta : ℝ), + 0 < eta ∧ ∀ j : ℕ, v j ∈ S.M ∧ ‖v j‖ ≤ C ∧ eta ≤ ‖T (v j S.xi)‖ ∧ + S.D.HasSpectralSupport (Icc (s - 4 * delta (nj j)) (s + 4 * delta (nj j))) + (v j S.xi) + +theorem bounded_recovery (S : StandardModularData H) (hscalar : S.ScalarCentralizer) + (omega : Ultrafilter ℕ) (hfree : (omega : Filter ℕ) ≤ Filter.atTop) + (T : H →L[ℂ] H) (s : ℝ) (delta : ℕ → ℝ) (hdelta : ∀ n, 0 < delta n) + (hdelta0 : Tendsto delta atTop (𝓝 0)) (h : ℕ → H) (hunit : ∀ n, ‖h n‖ = 1) + (hband : ∀ n, S.D.HasSpectralSupport (Icc (s - delta n) (s + delta n)) (h n)) + (hpositive : 0 < Filter.limsup + (fun n => fixedMean omega (fun t => ‖T (S.D.unitary t (h n))‖ ^ 2)) atTop) : + RecoveryConclusion S T s delta := by + sorry + +end BoundedRecovery + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BoundedRecovery.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoundedRecovery.bounded_recovery` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bounded-recovery/solution/closure.txt b/tasks/bounded-recovery/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fa0824760797610e1bffe086397c2c7334e4c0b5 --- /dev/null +++ b/tasks/bounded-recovery/solution/closure.txt @@ -0,0 +1,27 @@ +OAI.Analysis.ModularRecovery.CanonicalCalculus +OAI.Analysis.ModularRecovery.CanonicalGraph +OAI.Analysis.ModularRecovery.CanonicalPolar +OAI.Analysis.ModularRecovery.CanonicalTomita +OAI.Analysis.ModularRecovery.Centralizer +OAI.Analysis.ModularRecovery.Commutant +OAI.Analysis.ModularRecovery.ErgodicAverages +OAI.Analysis.ModularRecovery.FiniteMoments +OAI.Analysis.ModularRecovery.FourierKernels +OAI.Analysis.ModularRecovery.FourierLocalization +OAI.Analysis.ModularRecovery.FourierOperators +OAI.Analysis.ModularRecovery.FourthMoments +OAI.Analysis.ModularRecovery.GaussianAverages +OAI.Analysis.ModularRecovery.KernelContinuity +OAI.Analysis.ModularRecovery.Main +OAI.Analysis.ModularRecovery.Mean +OAI.Analysis.ModularRecovery.Model +OAI.Analysis.ModularRecovery.ModularCovariance +OAI.Analysis.ModularRecovery.PolarCutoff +OAI.Analysis.ModularRecovery.PositiveKernels +OAI.Analysis.ModularRecovery.RealGraph +OAI.Analysis.ModularRecovery.Recovery +OAI.Analysis.ModularRecovery.SpectralCalculus +OAI.Analysis.ModularRecovery.StrongIntegrals +OAI.Analysis.ModularRecovery.StrongLimits +OAI.Analysis.ModularRecovery.TomitaFundamental +OAI.Analysis.ModularRecovery.TomitaResolvent diff --git a/tasks/bounded-recovery/solution/reference.py b/tasks/bounded-recovery/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bounded-recovery/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bounded-recovery/solution/solve.sh b/tasks/bounded-recovery/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a624c3c0594fbbd7fdc696541cc87f0c505b30b8 --- /dev/null +++ b/tasks/bounded-recovery/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BoundedRecovery, i.e. module OAI.Analysis.ModularRecovery.Main and the +# 27 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.ModularRecovery.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BoundedRecovery" diff --git a/tasks/bounded-recovery/task.toml b/tasks/bounded-recovery/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d2424ba15751c6d03e022608dc088dfe5f451cf9 --- /dev/null +++ b/tasks/bounded-recovery/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bounded-recovery" +version = "1.0.0" +description = "Prove BoundedRecovery (openai/math family 290: Connes' bicentralizer conjecture and relative bicentralizers) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BoundedRecovery.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BoundedRecovery" +family = "290" +family_title = "Connes' bicentralizer conjecture and relative bicentralizers" +subject = "Operator algebras" +theorems = ["OAI.BoundedRecovery.bounded_recovery"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.ModularRecovery.Main" +reference_modules = 27 +reference_lean_bytes = 368603 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1002 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12031 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bounded-recovery/tests/Challenge.lean b/tasks/bounded-recovery/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..dc79037dec593ee06aba18c07ecc774ef2802422 --- /dev/null +++ b/tasks/bounded-recovery/tests/Challenge.lean @@ -0,0 +1,102 @@ +import Mathlib + +namespace OAI + +/-! Nondegenerate spectral calculus, the closed Tomita graph, and bounded recovery. -/ + +universe u + +noncomputable section + +open Filter MeasureTheory Set +open scoped Topology ComplexConjugate + +namespace BoundedRecovery + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def spectralCharacter (t : ℝ) : BoundedContinuousFunction ℝ ℂ := + BoundedContinuousFunction.ofNormedAddCommGroup + (fun u : ℝ => Complex.exp (((t * u : ℝ) : ℂ) * Complex.I)) + (by fun_prop) 1 (by intro u; simp [Complex.norm_exp]) + +def halfExponentialCutoff (n : ℕ) : BoundedContinuousFunction ℝ ℂ := + BoundedContinuousFunction.ofNormedAddCommGroup + (fun u : ℝ => (Real.exp (min (n : ℝ) u / 2) : ℂ)) + (by fun_prop) (Real.exp ((n : ℝ) / 2)) (by + intro u + simp only [Complex.norm_real, Real.norm_eq_abs, abs_of_pos (Real.exp_pos _)] + exact Real.exp_le_exp.mpr (div_le_div_of_nonneg_right (min_le_left _ _) (by norm_num))) + +structure RealSpectralCalculus (H : Type u) [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] where + calculus : (BoundedContinuousFunction ℝ ℂ) →⋆ₐ[ℂ] (H →L[ℂ] H) + nondegenerate : Dense {h : H | ∃ f : BoundedContinuousFunction ℝ ℂ, + HasCompactSupport (f : ℝ → ℂ) ∧ ∃ k : H, calculus f k = h} + +namespace RealSpectralCalculus + +def unitary (D : RealSpectralCalculus H) (t : ℝ) : H →L[ℂ] H := + D.calculus (spectralCharacter t) + +def halfGraph (D : RealSpectralCalculus H) : Set (H × H) := + {p | Tendsto (fun n : ℕ => D.calculus (halfExponentialCutoff n) p.1) atTop (𝓝 p.2)} + +def HasSpectralSupport (D : RealSpectralCalculus H) (I : Set ℝ) (h : H) : Prop := + ∀ f : BoundedContinuousFunction ℝ ℂ, (∀ u ∈ I, f u = 0) → D.calculus f h = 0 + +end RealSpectralCalculus + +structure StandardModularData (H : Type u) [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] where + M : VonNeumannAlgebra H + xi : H + norm_xi : ‖xi‖ = 1 + cyclic : Dense {h : H | ∃ a : H →L[ℂ] H, a ∈ M ∧ a xi = h} + separating : ∀ a : H →L[ℂ] H, a ∈ M → a xi = 0 → a = 0 + D : RealSpectralCalculus H + J : H ≃ₗᵢ⋆[ℂ] H + conjugation : Function.Involutive J + tomita_graph : closure {p : H × H | ∃ a : H →L[ℂ] H, + a ∈ M ∧ p = (a xi, (star a) xi)} = + {p | ∃ q : H, (p.1, q) ∈ D.halfGraph ∧ p.2 = J q} + +namespace StandardModularData + +def sigma (S : StandardModularData H) (t : ℝ) (a : H →L[ℂ] H) : H →L[ℂ] H := + S.D.unitary t * a * S.D.unitary (-t) + +def ScalarCentralizer (S : StandardModularData H) : Prop := + ∀ a : H →L[ℂ] H, a ∈ S.M → (∀ t : ℝ, S.sigma t a = a) → + ∃ c : ℂ, a = c • (1 : H →L[ℂ] H) + +end StandardModularData + +def symmetricAverage (f : ℝ → ℝ) (k : ℕ) : ℝ := + (2 * (k : ℝ))⁻¹ * ∫ t in -(k : ℝ)..(k : ℝ), f t + +def fixedMean (omega : Ultrafilter ℕ) (f : ℝ → ℝ) : ℝ := + Filter.limUnder (omega : Filter ℕ) (symmetricAverage f) + +def RecoveryConclusion (S : StandardModularData H) (T : H →L[ℂ] H) + (s : ℝ) (delta : ℕ → ℝ) : Prop := + ∃ (nj : ℕ → ℕ) (_ : StrictMono nj) (v : ℕ → (H →L[ℂ] H)) (C eta : ℝ), + 0 < eta ∧ ∀ j : ℕ, v j ∈ S.M ∧ ‖v j‖ ≤ C ∧ eta ≤ ‖T (v j S.xi)‖ ∧ + S.D.HasSpectralSupport (Icc (s - 4 * delta (nj j)) (s + 4 * delta (nj j))) + (v j S.xi) + +theorem bounded_recovery (S : StandardModularData H) (hscalar : S.ScalarCentralizer) + (omega : Ultrafilter ℕ) (hfree : (omega : Filter ℕ) ≤ Filter.atTop) + (T : H →L[ℂ] H) (s : ℝ) (delta : ℕ → ℝ) (hdelta : ∀ n, 0 < delta n) + (hdelta0 : Tendsto delta atTop (𝓝 0)) (h : ℕ → H) (hunit : ∀ n, ‖h n‖ = 1) + (hband : ∀ n, S.D.HasSpectralSupport (Icc (s - delta n) (s + delta n)) (h n)) + (hpositive : 0 < Filter.limsup + (fun n => fixedMean omega (fun t => ‖T (S.D.unitary t (h n))‖ ^ 2)) atTop) : + RecoveryConclusion S T s delta := by + sorry + +end BoundedRecovery + +end + +end OAI diff --git a/tasks/bounded-recovery/tests/grade.py b/tasks/bounded-recovery/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bounded-recovery/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bounded-recovery/tests/task.json b/tasks/bounded-recovery/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..95ba954f7df415caeadb23f5271260ee383d3d12 --- /dev/null +++ b/tasks/bounded-recovery/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BoundedRecovery", + "comparator": { + "theorem_names": [ + "OAI.BoundedRecovery.bounded_recovery" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11131 +} \ No newline at end of file diff --git a/tasks/bounded-recovery/tests/test.sh b/tasks/bounded-recovery/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bounded-recovery/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bounded-tree-potentials/environment/Dockerfile b/tasks/bounded-tree-potentials/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bounded-tree-potentials/environment/fetch_mathlib.sh b/tasks/bounded-tree-potentials/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bounded-tree-potentials/environment/lake-manifest.json b/tasks/bounded-tree-potentials/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bounded-tree-potentials/environment/lakefile.lean b/tasks/bounded-tree-potentials/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bounded-tree-potentials/environment/lean_setup.sh b/tasks/bounded-tree-potentials/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bounded-tree-potentials/environment/pack_submission.py b/tasks/bounded-tree-potentials/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bounded-tree-potentials/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bounded-tree-potentials/instruction.md b/tasks/bounded-tree-potentials/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..af9ee7f3606352da6696e1d34d45d5461a4e9b32 --- /dev/null +++ b/tasks/bounded-tree-potentials/instruction.md @@ -0,0 +1,405 @@ +# openai/math challenge `BoundedTreePotentials` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `BoundedTreePotentials`, also at `/opt/openai-math/challenges/BoundedTreePotentials.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u +open Set +open scoped ENNReal Classical + +namespace BoundedTreePotentials + +section TestNorms + +variable {I : Type*} + +structure TestFamily (I : Type*) where + carrier : Set (I → ℝ) + zero_mem : (0 : I → ℝ) ∈ carrier + neg_mem : ∀ f ∈ carrier, -f ∈ carrier + coeff_bound : ∀ f ∈ carrier, ∀ i, |f i| ≤ 1 + singleton_mem : ∀ i, (fun j => if j = i then (1 : ℝ) else 0) ∈ carrier + +instance : CoeSort (TestFamily I) (Type _) := ⟨fun K => K.carrier⟩ +instance (K : TestFamily I) : Nonempty K.carrier := ⟨⟨0, K.zero_mem⟩⟩ + +def finitePairing (f : I → ℝ) : (I →₀ ℝ) →ₗ[ℝ] ℝ := + Finsupp.linearCombination ℝ f + +def testNorm (K : TestFamily I) (x : I →₀ ℝ) : ℝ := + ⨆ f : K, |finitePairing f.val x| + +def testSeminorm (K : TestFamily I) : Seminorm ℝ (I →₀ ℝ) := by + have finitePairing_apply (f : I → ℝ) (x : I →₀ ℝ) : + finitePairing f x = ∑ i ∈ x.support, x i * f i := rfl + have finitePairing_abs_bound (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ ∑ i ∈ x.support, |x i| := by + rw [finitePairing_apply] + calc + |∑ i ∈ x.support, x i * f.val i| ≤ ∑ i ∈ x.support, |x i * f.val i| := + Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ x.support, |x i| := by + apply Finset.sum_le_sum + intro i hi + rw [abs_mul] + exact mul_le_of_le_one_right (abs_nonneg _) (K.coeff_bound _ f.property i) + have testNorm_bddAbove (K : TestFamily I) (x : I →₀ ℝ) : + BddAbove (range fun f : K => |finitePairing f.val x|) := + ⟨∑ i ∈ x.support, |x i|, by rintro _ ⟨f, rfl⟩; exact finitePairing_abs_bound K f x⟩ + have finitePairing_le_testNorm (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ testNorm K x := le_ciSup (testNorm_bddAbove K x) f + have testNorm_nonneg (K : TestFamily I) (x : I →₀ ℝ) : 0 ≤ testNorm K x := + (abs_nonneg _).trans (finitePairing_le_testNorm K ⟨0, K.zero_mem⟩ x) + have testNorm_le_l1 (K : TestFamily I) (x : I →₀ ℝ) : + testNorm K x ≤ ∑ i ∈ x.support, |x i| := by + apply ciSup_le + exact fun f => finitePairing_abs_bound K f x + have testNorm_zero (K : TestFamily I) : testNorm K 0 = 0 := by + apply le_antisymm + · simpa using testNorm_le_l1 K 0 + · exact testNorm_nonneg K 0 + have testNorm_add_le (K : TestFamily I) (x y : I →₀ ℝ) : + testNorm K (x + y) ≤ testNorm K x + testNorm K y := by + apply ciSup_le + intro f + rw [map_add] + exact (abs_add_le _ _).trans (add_le_add + (finitePairing_le_testNorm K f x) (finitePairing_le_testNorm K f y)) + have testNorm_smul_le (K : TestFamily I) (a : ℝ) (x : I →₀ ℝ) : + testNorm K (a • x) ≤ ‖a‖ * testNorm K x := by + apply ciSup_le + intro f + rw [map_smul, smul_eq_mul, abs_mul, Real.norm_eq_abs] + exact mul_le_mul_of_nonneg_left (finitePairing_le_testNorm K f x) (abs_nonneg a) + exact Seminorm.ofSMulLE (testNorm K) (testNorm_zero K) (testNorm_add_le K) (testNorm_smul_le K) + +def TestVector (_ : TestFamily I) := I →₀ ℝ + +instance (K : TestFamily I) : AddCommGroup (TestVector K) := inferInstanceAs (AddCommGroup (I →₀ ℝ)) +instance (K : TestFamily I) : Module ℝ (TestVector K) := inferInstanceAs (Module ℝ (I →₀ ℝ)) +instance (K : TestFamily I) : Norm (TestVector K) := ⟨testNorm K⟩ + +instance (K : TestFamily I) : NormedAddCommGroup (TestVector K) := by + have finitePairing_apply (f : I → ℝ) (x : I →₀ ℝ) : + finitePairing f x = ∑ i ∈ x.support, x i * f i := rfl + have finitePairing_abs_bound (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ ∑ i ∈ x.support, |x i| := by + rw [finitePairing_apply] + calc + |∑ i ∈ x.support, x i * f.val i| ≤ ∑ i ∈ x.support, |x i * f.val i| := + Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ x.support, |x i| := by + apply Finset.sum_le_sum + intro i hi + rw [abs_mul] + exact mul_le_of_le_one_right (abs_nonneg _) (K.coeff_bound _ f.property i) + have testNorm_bddAbove (K : TestFamily I) (x : I →₀ ℝ) : + BddAbove (range fun f : K => |finitePairing f.val x|) := + ⟨∑ i ∈ x.support, |x i|, by rintro _ ⟨f, rfl⟩; exact finitePairing_abs_bound K f x⟩ + have finitePairing_le_testNorm (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ testNorm K x := le_ciSup (testNorm_bddAbove K x) f + have finitePairing_single_test (x : I →₀ ℝ) (i : I) : + finitePairing (fun j => if j = i then (1 : ℝ) else 0) x = x i := by + classical + rw [finitePairing_apply] + simp only [mul_ite, mul_one, mul_zero] + by_cases hi : i ∈ x.support + · simp [hi] + · simp [hi, Finsupp.notMem_support_iff.mp hi] + have coordinate_le_testNorm (K : TestFamily I) (x : I →₀ ℝ) (i : I) : + |x i| ≤ testNorm K x := by + convert finitePairing_le_testNorm K ⟨_, K.singleton_mem i⟩ x using 1 + rw [finitePairing_single_test] + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg := apply_nonneg (testSeminorm K) + norm_smul := map_smul_eq_mul (testSeminorm K) + norm_triangle := map_add_le_add (testSeminorm K) + norm_eq_zero_iff := fun x => ⟨by + intro h + apply Finsupp.ext + intro i + exact abs_nonpos_iff.mp (h ▸ coordinate_le_testNorm K x i), by + rintro rfl + exact map_zero (testSeminorm K)⟩ } + +instance (K : TestFamily I) : NormedSpace ℝ (TestVector K) where + norm_smul_le a x := le_of_eq (map_smul_eq_mul (testSeminorm K) a x) + +abbrev TestCompletion (K : TestFamily I) := UniformSpace.Completion (TestVector K) + +end TestNorms + +namespace TreeCalculus + +abbrev Node := List ℕ + +def potential (f : Node → ℝ) (s : Node) : ℝ := (s.inits.map f).sum + +inductive QuadraticKind where + | sibling | antichain | global + deriving DecidableEq + +def QuadraticGroup : QuadraticKind → Finset Node → Prop + | .sibling, B => ∃ r, ∀ s ∈ B, ∃ j, s = r ++ [j] + | .antichain, B => (B : Set Node).Pairwise (fun s t => ¬s <+: t ∧ ¬t <+: s) + | .global, _ => True + +def QuadraticBudget (k : QuadraticKind) (f : Node → ℝ) : Prop := + ∀ B : Finset Node, QuadraticGroup k B → ∑ s ∈ B, f s ^ 2 ≤ 1 + +def CoefficientSupport : QuadraticKind → (Node → ℝ) → Prop + | .sibling, _ => True + | .antichain, f => (Function.support f).Finite + | .global, f => Memℓp f 2 + +structure IsTreeTest (includeRoot : Bool) (k : QuadraticKind) (f : Node → ℝ) : Prop where + root_zero : includeRoot = false → f [] = 0 + potential_bound : ∀ s, |potential f s| ≤ 1 + quadratic_budget : QuadraticBudget k f + coefficient_support : CoefficientSupport k f + +abbrev TreeCoordinate (includeRoot : Bool) := {s : Node // includeRoot = true ∨ s ≠ []} + +def liftCoefficients (r : Bool) (f : TreeCoordinate r → ℝ) (s : Node) : ℝ := + if h : r = true ∨ s ≠ [] then f ⟨s, h⟩ else 0 + +def treeTestFamily (r : Bool) (k : QuadraticKind) : TestFamily (TreeCoordinate r) := by + have potential_root (f : Node → ℝ) : potential f [] = f [] := by simp [potential] + have potential_child (f : Node → ℝ) (s : Node) (j : ℕ) : + potential f (s ++ [j]) = potential f s + f (s ++ [j]) := by + simp [potential, List.inits_append] + have potential_smul (a : ℝ) (f : Node → ℝ) (s : Node) : + potential (a • f) s = a * potential f s := by + induction s using List.reverseRecOn with + | nil => simp [potential_root] + | append_singleton s j ih => simp only [potential_child, ih, Pi.smul_apply, smul_eq_mul]; ring + have quadratic_singleton (k : QuadraticKind) {s : Node} (hs : s ≠ []) : + QuadraticGroup k {s} := by + cases k with + | sibling => + cases s using List.reverseRecOn with + | nil => exact (hs rfl).elim + | append_singleton s j => + refine ⟨s, ?_⟩ + intro t ht + have ht' : t = s ++ [j] := by simpa using ht + exact ⟨j, ht'⟩ + | antichain => simp [QuadraticGroup] + | global => trivial + have test_coefficient_bound {r : Bool} {k : QuadraticKind} {f : Node → ℝ} + (hf : IsTreeTest r k f) (s : Node) : |f s| ≤ 1 := by + by_cases hs : s = [] + · subst s; simpa only [potential_root] using hf.potential_bound [] + · have h := hf.quadratic_budget {s} (quadratic_singleton k hs) + rw [Finset.sum_singleton] at h + exact (sq_le_one_iff_abs_le_one (f s)).mp h + have quadraticBudget_dominate {k : QuadraticKind} {f g : Node → ℝ} + (hf : QuadraticBudget k f) (h : ∀ s, |g s| ≤ |f s|) : QuadraticBudget k g := by + intro B hB + apply le_trans _ (hf B hB) + apply Finset.sum_le_sum + intro s hs + exact (sq_le_sq).mpr (h s) + have coefficientSupport_dominate {k : QuadraticKind} {f g : Node → ℝ} + (hf : CoefficientSupport k f) (h : ∀ s, |g s| ≤ |f s|) : CoefficientSupport k g := by + cases k with + | sibling => trivial + | antichain => + apply hf.subset + intro s hs + change g s ≠ 0 at hs + change f s ≠ 0 + intro hzero + have hh := h s + rw [hzero, abs_zero] at hh + exact hs (abs_nonpos_iff.mp hh) + | global => + exact (hf.norm).mono (by intro s; simpa only [Real.norm_eq_abs] using h s) + have zero_isTreeTest (r : Bool) (k : QuadraticKind) : IsTreeTest r k 0 := by + constructor + · simp + · intro s + change |(s.inits.map fun _ => (0 : ℝ)).sum| ≤ 1 + simp + · intro B hB; simp + · cases k with + | sibling => trivial + | antichain => simp [CoefficientSupport] + | global => exact zero_memℓp + have neg_isTreeTest {r : Bool} {k : QuadraticKind} {f : Node → ℝ} + (hf : IsTreeTest r k f) : IsTreeTest r k (-f) := by + constructor + · intro hr; simpa using congrArg Neg.neg (hf.root_zero hr) + · intro s + have he : -f = (-1 : ℝ) • f := by ext s; simp + rw [he, potential_smul, neg_one_mul, abs_neg] + exact hf.potential_bound s + · exact quadraticBudget_dominate hf.quadratic_budget (by intro s; simp) + · exact coefficientSupport_dominate hf.coefficient_support (by intro s; simp) + have inits_nodup (s : Node) : s.inits.Nodup := by + induction s using List.reverseRecOn with + | nil => simp + | append_singleton s j ih => + have he : (s ++ [j]).inits = s.inits ++ [s ++ [j]] := by simp [List.inits_append] + rw [he, List.nodup_append] + refine ⟨ih, by simp, ?_⟩ + intro a ha b hb hab + have hb' : b = s ++ [j] := by simpa using hb + have hp := ((List.mem_inits a s).mp ha).length_le + rw [hab, hb', List.length_append, List.length_singleton] at hp + exact Nat.not_succ_le_self _ hp + have potential_single (i s : Node) : + potential (Pi.single i (1 : ℝ)) s = if i <+: s then 1 else 0 := by + rw [potential, ← List.sum_toFinset _ (inits_nodup s)] + simp only [Pi.single_apply] + by_cases h : i <+: s + · have hm : i ∈ s.inits.toFinset := List.mem_toFinset.mpr ((List.mem_inits i s).mpr h) + simp [hm, h] + · have hm : i ∉ s.inits.toFinset := fun hm => h ((List.mem_inits i s).mp (List.mem_toFinset.mp hm)) + simp [hm, h] + have single_isTreeTest (r : Bool) (k : QuadraticKind) {i : Node} + (hi : r = true ∨ i ≠ []) : IsTreeTest r k (Pi.single i (1 : ℝ)) := by + constructor + · intro hr + have hn : [] ≠ i := by + rcases hi with hi | hi + · simp_all + · exact Ne.symm hi + exact Pi.single_eq_of_ne hn _ + · intro s + rw [potential_single] + split_ifs <;> norm_num + · intro B hB + simp only [Pi.single_apply, ite_pow, one_pow, zero_pow (by decide : (2 : ℕ) ≠ 0)] + by_cases h : i ∈ B <;> simp [h] + · cases k with + | sibling => trivial + | antichain => + change (Function.support (Pi.single i (1 : ℝ))).Finite + exact (Set.finite_singleton i).subset (by intro s hs; simpa [Function.mem_support, Pi.single_apply] using hs) + | global => exact (lp.single (E := fun _ : Node => ℝ) 2 i (1 : ℝ)).property + have liftCoefficients_coord {r : Bool} (f : TreeCoordinate r → ℝ) (s : TreeCoordinate r) : + liftCoefficients r f s.val = f s := by simp [liftCoefficients, s.property] + have liftCoefficients_zero (r : Bool) : liftCoefficients r 0 = 0 := by + ext s; simp [liftCoefficients] + have liftCoefficients_neg (r : Bool) (f : TreeCoordinate r → ℝ) : + liftCoefficients r (-f) = -liftCoefficients r f := by + ext s + by_cases h : r = true ∨ s ≠ [] <;> simp [liftCoefficients, h] + exact { + carrier := {f | IsTreeTest r k (liftCoefficients r f)} + zero_mem := by + change IsTreeTest r k (liftCoefficients r 0) + rw [liftCoefficients_zero] + exact zero_isTreeTest r k + neg_mem := by + intro f hf + change IsTreeTest r k (liftCoefficients r (-f)) + rw [liftCoefficients_neg] + exact neg_isTreeTest hf + coeff_bound := by + intro f hf i + simpa only [liftCoefficients_coord] using test_coefficient_bound hf i.val + singleton_mem := by + rintro ⟨i, hi⟩ + change IsTreeTest r k (liftCoefficients r _) + convert single_isTreeTest r k hi using 1 + ext s + by_cases h : r = true ∨ s ≠ [] + · simp [liftCoefficients, h, Pi.single_apply, Subtype.mk.injEq] + · have hn : s ≠ i := by rintro rfl; exact h hi + simp [liftCoefficients, h, hn] } + +end TreeCalculus + +section AsymptoticModuli + +variable (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] + +structure ClosedFiniteCodim where + space : Submodule ℝ E + closed : IsClosed (space : Set E) + finiteCodim : Module.Finite ℝ (E ⧸ space) + +def averagedModulusReal (t : ℝ) : ℝ := + ⨅ x : {x : E // ‖x‖=1},⨆ F : ClosedFiniteCodim E, + ⨅ y : {y : E // y ∈ F.space ∧ 1≤‖y‖}, + (‖x.val+t • y.val‖+‖x.val-t • y.val‖)/((2 : ℕ) : ℝ)-1 + +def oneSidedModulusReal (t : ℝ) : ℝ := + ⨅ x : {x : E // ‖x‖=1},⨆ F : ClosedFiniteCodim E, + ⨅ y : {y : E // y ∈ F.space ∧ ‖y‖=1},‖x.val+t • y.val‖-1 + +def IsAUCReal : Prop := ∀ t : ℝ, 0 < t → 0 < oneSidedModulusReal E t + +end AsymptoticModuli + +open TreeCalculus in +theorem TreeCalculus.main_counterexample (r : Bool) (k : QuadraticKind) : + (CompleteSpace (TestCompletion (treeTestFamily r k)) ∧ + TopologicalSpace.SeparableSpace (TestCompletion (treeTestFamily r k)) ∧ + ¬Module.Finite ℝ (TestCompletion (treeTestFamily r k))) ∧ + (∀ t : ℝ, 0 < t → t < 1 → + Real.sqrt (1 + t ^ 2 / 4) - 1 ≤ + averagedModulusReal (TestCompletion (treeTestFamily r k)) t) ∧ + (∀ (Y : Type u) [NormedAddCommGroup Y] [NormedSpace ℝ Y], + (TestCompletion (treeTestFamily r k) ≃L[ℝ] Y) → ¬IsAUCReal Y) := by + sorry + +end BoundedTreePotentials + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BoundedTreePotentials.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoundedTreePotentials.TreeCalculus.main_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bounded-tree-potentials/solution/closure.txt b/tasks/bounded-tree-potentials/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b5c9053f3848f2a71f0393a3a104166af81395c9 --- /dev/null +++ b/tasks/bounded-tree-potentials/solution/closure.txt @@ -0,0 +1,46 @@ +OAI.Analysis.TreePotential.Clipping +OAI.Analysis.TreePotential.Completion +OAI.Analysis.TreePotential.Coordinates +OAI.Analysis.TreePotential.CostCompletion +OAI.Analysis.TreePotential.CostGeometry +OAI.Analysis.TreePotential.CostObstruction +OAI.Analysis.TreePotential.DualCoordinates +OAI.Analysis.TreePotential.Dyadic +OAI.Analysis.TreePotential.EndpointTransfer +OAI.Analysis.TreePotential.FiniteHeads +OAI.Analysis.TreePotential.FiniteTree +OAI.Analysis.TreePotential.FreeRoot +OAI.Analysis.TreePotential.HilbertCompletion +OAI.Analysis.TreePotential.HilbertSum +OAI.Analysis.TreePotential.Inward +OAI.Analysis.TreePotential.Leakage +OAI.Analysis.TreePotential.LinearCost +OAI.Analysis.TreePotential.Main +OAI.Analysis.TreePotential.Moduli +OAI.Analysis.TreePotential.NormIdentities +OAI.Analysis.TreePotential.Normalization +OAI.Analysis.TreePotential.QuadraticCost +OAI.Analysis.TreePotential.RealModuli +OAI.Analysis.TreePotential.SegmentBasic +OAI.Analysis.TreePotential.SegmentCancellation +OAI.Analysis.TreePotential.SegmentComponents +OAI.Analysis.TreePotential.SegmentDual +OAI.Analysis.TreePotential.SegmentEndpoints +OAI.Analysis.TreePotential.SegmentHeads +OAI.Analysis.TreePotential.SegmentMidpoint +OAI.Analysis.TreePotential.SegmentMixtures +OAI.Analysis.TreePotential.SegmentPolar +OAI.Analysis.TreePotential.StartComponent +OAI.Analysis.TreePotential.StartEnergy +OAI.Analysis.TreePotential.StartMass +OAI.Analysis.TreePotential.StartModulus +OAI.Analysis.TreePotential.StartPolar +OAI.Analysis.TreePotential.StartQuotient +OAI.Analysis.TreePotential.StartRepresentation +OAI.Analysis.TreePotential.TailEstimates +OAI.Analysis.TreePotential.TestNorm +OAI.Analysis.TreePotential.TreeObstruction +OAI.Analysis.TreePotential.TreeTests +OAI.Analysis.TreePotential.UniformAverages +OAI.Analysis.TreePotential.UniformProtocols +OAI.Analysis.TreePotential.WeakNull diff --git a/tasks/bounded-tree-potentials/solution/reference.py b/tasks/bounded-tree-potentials/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bounded-tree-potentials/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bounded-tree-potentials/solution/solve.sh b/tasks/bounded-tree-potentials/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7a02d117d8c720f53b6ab448da562c3783fc819 --- /dev/null +++ b/tasks/bounded-tree-potentials/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BoundedTreePotentials, i.e. module OAI.Analysis.TreePotential.Main and the +# 46 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.TreePotential.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BoundedTreePotentials" diff --git a/tasks/bounded-tree-potentials/task.toml b/tasks/bounded-tree-potentials/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f56a945d0b1eefc28ca6f09a8c707c4e1c8b3429 --- /dev/null +++ b/tasks/bounded-tree-potentials/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bounded-tree-potentials" +version = "1.0.0" +description = "Prove BoundedTreePotentials (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BoundedTreePotentials.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BoundedTreePotentials" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.BoundedTreePotentials.TreeCalculus.main_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.TreePotential.Main" +reference_modules = 46 +reference_lean_bytes = 595707 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 758 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12236 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bounded-tree-potentials/tests/Challenge.lean b/tasks/bounded-tree-potentials/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ea7e1901e67df6e7e3a17f03a30c10e95897ed5 --- /dev/null +++ b/tasks/bounded-tree-potentials/tests/Challenge.lean @@ -0,0 +1,354 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u +open Set +open scoped ENNReal Classical + +namespace BoundedTreePotentials + +section TestNorms + +variable {I : Type*} + +structure TestFamily (I : Type*) where + carrier : Set (I → ℝ) + zero_mem : (0 : I → ℝ) ∈ carrier + neg_mem : ∀ f ∈ carrier, -f ∈ carrier + coeff_bound : ∀ f ∈ carrier, ∀ i, |f i| ≤ 1 + singleton_mem : ∀ i, (fun j => if j = i then (1 : ℝ) else 0) ∈ carrier + +instance : CoeSort (TestFamily I) (Type _) := ⟨fun K => K.carrier⟩ +instance (K : TestFamily I) : Nonempty K.carrier := ⟨⟨0, K.zero_mem⟩⟩ + +def finitePairing (f : I → ℝ) : (I →₀ ℝ) →ₗ[ℝ] ℝ := + Finsupp.linearCombination ℝ f + +def testNorm (K : TestFamily I) (x : I →₀ ℝ) : ℝ := + ⨆ f : K, |finitePairing f.val x| + +def testSeminorm (K : TestFamily I) : Seminorm ℝ (I →₀ ℝ) := by + have finitePairing_apply (f : I → ℝ) (x : I →₀ ℝ) : + finitePairing f x = ∑ i ∈ x.support, x i * f i := rfl + have finitePairing_abs_bound (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ ∑ i ∈ x.support, |x i| := by + rw [finitePairing_apply] + calc + |∑ i ∈ x.support, x i * f.val i| ≤ ∑ i ∈ x.support, |x i * f.val i| := + Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ x.support, |x i| := by + apply Finset.sum_le_sum + intro i hi + rw [abs_mul] + exact mul_le_of_le_one_right (abs_nonneg _) (K.coeff_bound _ f.property i) + have testNorm_bddAbove (K : TestFamily I) (x : I →₀ ℝ) : + BddAbove (range fun f : K => |finitePairing f.val x|) := + ⟨∑ i ∈ x.support, |x i|, by rintro _ ⟨f, rfl⟩; exact finitePairing_abs_bound K f x⟩ + have finitePairing_le_testNorm (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ testNorm K x := le_ciSup (testNorm_bddAbove K x) f + have testNorm_nonneg (K : TestFamily I) (x : I →₀ ℝ) : 0 ≤ testNorm K x := + (abs_nonneg _).trans (finitePairing_le_testNorm K ⟨0, K.zero_mem⟩ x) + have testNorm_le_l1 (K : TestFamily I) (x : I →₀ ℝ) : + testNorm K x ≤ ∑ i ∈ x.support, |x i| := by + apply ciSup_le + exact fun f => finitePairing_abs_bound K f x + have testNorm_zero (K : TestFamily I) : testNorm K 0 = 0 := by + apply le_antisymm + · simpa using testNorm_le_l1 K 0 + · exact testNorm_nonneg K 0 + have testNorm_add_le (K : TestFamily I) (x y : I →₀ ℝ) : + testNorm K (x + y) ≤ testNorm K x + testNorm K y := by + apply ciSup_le + intro f + rw [map_add] + exact (abs_add_le _ _).trans (add_le_add + (finitePairing_le_testNorm K f x) (finitePairing_le_testNorm K f y)) + have testNorm_smul_le (K : TestFamily I) (a : ℝ) (x : I →₀ ℝ) : + testNorm K (a • x) ≤ ‖a‖ * testNorm K x := by + apply ciSup_le + intro f + rw [map_smul, smul_eq_mul, abs_mul, Real.norm_eq_abs] + exact mul_le_mul_of_nonneg_left (finitePairing_le_testNorm K f x) (abs_nonneg a) + exact Seminorm.ofSMulLE (testNorm K) (testNorm_zero K) (testNorm_add_le K) (testNorm_smul_le K) + +def TestVector (_ : TestFamily I) := I →₀ ℝ + +instance (K : TestFamily I) : AddCommGroup (TestVector K) := inferInstanceAs (AddCommGroup (I →₀ ℝ)) +instance (K : TestFamily I) : Module ℝ (TestVector K) := inferInstanceAs (Module ℝ (I →₀ ℝ)) +instance (K : TestFamily I) : Norm (TestVector K) := ⟨testNorm K⟩ + +instance (K : TestFamily I) : NormedAddCommGroup (TestVector K) := by + have finitePairing_apply (f : I → ℝ) (x : I →₀ ℝ) : + finitePairing f x = ∑ i ∈ x.support, x i * f i := rfl + have finitePairing_abs_bound (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ ∑ i ∈ x.support, |x i| := by + rw [finitePairing_apply] + calc + |∑ i ∈ x.support, x i * f.val i| ≤ ∑ i ∈ x.support, |x i * f.val i| := + Finset.abs_sum_le_sum_abs _ _ + _ ≤ ∑ i ∈ x.support, |x i| := by + apply Finset.sum_le_sum + intro i hi + rw [abs_mul] + exact mul_le_of_le_one_right (abs_nonneg _) (K.coeff_bound _ f.property i) + have testNorm_bddAbove (K : TestFamily I) (x : I →₀ ℝ) : + BddAbove (range fun f : K => |finitePairing f.val x|) := + ⟨∑ i ∈ x.support, |x i|, by rintro _ ⟨f, rfl⟩; exact finitePairing_abs_bound K f x⟩ + have finitePairing_le_testNorm (K : TestFamily I) (f : K) (x : I →₀ ℝ) : + |finitePairing f.val x| ≤ testNorm K x := le_ciSup (testNorm_bddAbove K x) f + have finitePairing_single_test (x : I →₀ ℝ) (i : I) : + finitePairing (fun j => if j = i then (1 : ℝ) else 0) x = x i := by + classical + rw [finitePairing_apply] + simp only [mul_ite, mul_one, mul_zero] + by_cases hi : i ∈ x.support + · simp [hi] + · simp [hi, Finsupp.notMem_support_iff.mp hi] + have coordinate_le_testNorm (K : TestFamily I) (x : I →₀ ℝ) (i : I) : + |x i| ≤ testNorm K x := by + convert finitePairing_le_testNorm K ⟨_, K.singleton_mem i⟩ x using 1 + rw [finitePairing_single_test] + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg := apply_nonneg (testSeminorm K) + norm_smul := map_smul_eq_mul (testSeminorm K) + norm_triangle := map_add_le_add (testSeminorm K) + norm_eq_zero_iff := fun x => ⟨by + intro h + apply Finsupp.ext + intro i + exact abs_nonpos_iff.mp (h ▸ coordinate_le_testNorm K x i), by + rintro rfl + exact map_zero (testSeminorm K)⟩ } + +instance (K : TestFamily I) : NormedSpace ℝ (TestVector K) where + norm_smul_le a x := le_of_eq (map_smul_eq_mul (testSeminorm K) a x) + +abbrev TestCompletion (K : TestFamily I) := UniformSpace.Completion (TestVector K) + +end TestNorms + +namespace TreeCalculus + +abbrev Node := List ℕ + +def potential (f : Node → ℝ) (s : Node) : ℝ := (s.inits.map f).sum + +inductive QuadraticKind where + | sibling | antichain | global + deriving DecidableEq + +def QuadraticGroup : QuadraticKind → Finset Node → Prop + | .sibling, B => ∃ r, ∀ s ∈ B, ∃ j, s = r ++ [j] + | .antichain, B => (B : Set Node).Pairwise (fun s t => ¬s <+: t ∧ ¬t <+: s) + | .global, _ => True + +def QuadraticBudget (k : QuadraticKind) (f : Node → ℝ) : Prop := + ∀ B : Finset Node, QuadraticGroup k B → ∑ s ∈ B, f s ^ 2 ≤ 1 + +def CoefficientSupport : QuadraticKind → (Node → ℝ) → Prop + | .sibling, _ => True + | .antichain, f => (Function.support f).Finite + | .global, f => Memℓp f 2 + +structure IsTreeTest (includeRoot : Bool) (k : QuadraticKind) (f : Node → ℝ) : Prop where + root_zero : includeRoot = false → f [] = 0 + potential_bound : ∀ s, |potential f s| ≤ 1 + quadratic_budget : QuadraticBudget k f + coefficient_support : CoefficientSupport k f + +abbrev TreeCoordinate (includeRoot : Bool) := {s : Node // includeRoot = true ∨ s ≠ []} + +def liftCoefficients (r : Bool) (f : TreeCoordinate r → ℝ) (s : Node) : ℝ := + if h : r = true ∨ s ≠ [] then f ⟨s, h⟩ else 0 + +def treeTestFamily (r : Bool) (k : QuadraticKind) : TestFamily (TreeCoordinate r) := by + have potential_root (f : Node → ℝ) : potential f [] = f [] := by simp [potential] + have potential_child (f : Node → ℝ) (s : Node) (j : ℕ) : + potential f (s ++ [j]) = potential f s + f (s ++ [j]) := by + simp [potential, List.inits_append] + have potential_smul (a : ℝ) (f : Node → ℝ) (s : Node) : + potential (a • f) s = a * potential f s := by + induction s using List.reverseRecOn with + | nil => simp [potential_root] + | append_singleton s j ih => simp only [potential_child, ih, Pi.smul_apply, smul_eq_mul]; ring + have quadratic_singleton (k : QuadraticKind) {s : Node} (hs : s ≠ []) : + QuadraticGroup k {s} := by + cases k with + | sibling => + cases s using List.reverseRecOn with + | nil => exact (hs rfl).elim + | append_singleton s j => + refine ⟨s, ?_⟩ + intro t ht + have ht' : t = s ++ [j] := by simpa using ht + exact ⟨j, ht'⟩ + | antichain => simp [QuadraticGroup] + | global => trivial + have test_coefficient_bound {r : Bool} {k : QuadraticKind} {f : Node → ℝ} + (hf : IsTreeTest r k f) (s : Node) : |f s| ≤ 1 := by + by_cases hs : s = [] + · subst s; simpa only [potential_root] using hf.potential_bound [] + · have h := hf.quadratic_budget {s} (quadratic_singleton k hs) + rw [Finset.sum_singleton] at h + exact (sq_le_one_iff_abs_le_one (f s)).mp h + have quadraticBudget_dominate {k : QuadraticKind} {f g : Node → ℝ} + (hf : QuadraticBudget k f) (h : ∀ s, |g s| ≤ |f s|) : QuadraticBudget k g := by + intro B hB + apply le_trans _ (hf B hB) + apply Finset.sum_le_sum + intro s hs + exact (sq_le_sq).mpr (h s) + have coefficientSupport_dominate {k : QuadraticKind} {f g : Node → ℝ} + (hf : CoefficientSupport k f) (h : ∀ s, |g s| ≤ |f s|) : CoefficientSupport k g := by + cases k with + | sibling => trivial + | antichain => + apply hf.subset + intro s hs + change g s ≠ 0 at hs + change f s ≠ 0 + intro hzero + have hh := h s + rw [hzero, abs_zero] at hh + exact hs (abs_nonpos_iff.mp hh) + | global => + exact (hf.norm).mono (by intro s; simpa only [Real.norm_eq_abs] using h s) + have zero_isTreeTest (r : Bool) (k : QuadraticKind) : IsTreeTest r k 0 := by + constructor + · simp + · intro s + change |(s.inits.map fun _ => (0 : ℝ)).sum| ≤ 1 + simp + · intro B hB; simp + · cases k with + | sibling => trivial + | antichain => simp [CoefficientSupport] + | global => exact zero_memℓp + have neg_isTreeTest {r : Bool} {k : QuadraticKind} {f : Node → ℝ} + (hf : IsTreeTest r k f) : IsTreeTest r k (-f) := by + constructor + · intro hr; simpa using congrArg Neg.neg (hf.root_zero hr) + · intro s + have he : -f = (-1 : ℝ) • f := by ext s; simp + rw [he, potential_smul, neg_one_mul, abs_neg] + exact hf.potential_bound s + · exact quadraticBudget_dominate hf.quadratic_budget (by intro s; simp) + · exact coefficientSupport_dominate hf.coefficient_support (by intro s; simp) + have inits_nodup (s : Node) : s.inits.Nodup := by + induction s using List.reverseRecOn with + | nil => simp + | append_singleton s j ih => + have he : (s ++ [j]).inits = s.inits ++ [s ++ [j]] := by simp [List.inits_append] + rw [he, List.nodup_append] + refine ⟨ih, by simp, ?_⟩ + intro a ha b hb hab + have hb' : b = s ++ [j] := by simpa using hb + have hp := ((List.mem_inits a s).mp ha).length_le + rw [hab, hb', List.length_append, List.length_singleton] at hp + exact Nat.not_succ_le_self _ hp + have potential_single (i s : Node) : + potential (Pi.single i (1 : ℝ)) s = if i <+: s then 1 else 0 := by + rw [potential, ← List.sum_toFinset _ (inits_nodup s)] + simp only [Pi.single_apply] + by_cases h : i <+: s + · have hm : i ∈ s.inits.toFinset := List.mem_toFinset.mpr ((List.mem_inits i s).mpr h) + simp [hm, h] + · have hm : i ∉ s.inits.toFinset := fun hm => h ((List.mem_inits i s).mp (List.mem_toFinset.mp hm)) + simp [hm, h] + have single_isTreeTest (r : Bool) (k : QuadraticKind) {i : Node} + (hi : r = true ∨ i ≠ []) : IsTreeTest r k (Pi.single i (1 : ℝ)) := by + constructor + · intro hr + have hn : [] ≠ i := by + rcases hi with hi | hi + · simp_all + · exact Ne.symm hi + exact Pi.single_eq_of_ne hn _ + · intro s + rw [potential_single] + split_ifs <;> norm_num + · intro B hB + simp only [Pi.single_apply, ite_pow, one_pow, zero_pow (by decide : (2 : ℕ) ≠ 0)] + by_cases h : i ∈ B <;> simp [h] + · cases k with + | sibling => trivial + | antichain => + change (Function.support (Pi.single i (1 : ℝ))).Finite + exact (Set.finite_singleton i).subset (by intro s hs; simpa [Function.mem_support, Pi.single_apply] using hs) + | global => exact (lp.single (E := fun _ : Node => ℝ) 2 i (1 : ℝ)).property + have liftCoefficients_coord {r : Bool} (f : TreeCoordinate r → ℝ) (s : TreeCoordinate r) : + liftCoefficients r f s.val = f s := by simp [liftCoefficients, s.property] + have liftCoefficients_zero (r : Bool) : liftCoefficients r 0 = 0 := by + ext s; simp [liftCoefficients] + have liftCoefficients_neg (r : Bool) (f : TreeCoordinate r → ℝ) : + liftCoefficients r (-f) = -liftCoefficients r f := by + ext s + by_cases h : r = true ∨ s ≠ [] <;> simp [liftCoefficients, h] + exact { + carrier := {f | IsTreeTest r k (liftCoefficients r f)} + zero_mem := by + change IsTreeTest r k (liftCoefficients r 0) + rw [liftCoefficients_zero] + exact zero_isTreeTest r k + neg_mem := by + intro f hf + change IsTreeTest r k (liftCoefficients r (-f)) + rw [liftCoefficients_neg] + exact neg_isTreeTest hf + coeff_bound := by + intro f hf i + simpa only [liftCoefficients_coord] using test_coefficient_bound hf i.val + singleton_mem := by + rintro ⟨i, hi⟩ + change IsTreeTest r k (liftCoefficients r _) + convert single_isTreeTest r k hi using 1 + ext s + by_cases h : r = true ∨ s ≠ [] + · simp [liftCoefficients, h, Pi.single_apply, Subtype.mk.injEq] + · have hn : s ≠ i := by rintro rfl; exact h hi + simp [liftCoefficients, h, hn] } + +end TreeCalculus + +section AsymptoticModuli + +variable (E : Type*) [NormedAddCommGroup E] [NormedSpace ℝ E] + +structure ClosedFiniteCodim where + space : Submodule ℝ E + closed : IsClosed (space : Set E) + finiteCodim : Module.Finite ℝ (E ⧸ space) + +def averagedModulusReal (t : ℝ) : ℝ := + ⨅ x : {x : E // ‖x‖=1},⨆ F : ClosedFiniteCodim E, + ⨅ y : {y : E // y ∈ F.space ∧ 1≤‖y‖}, + (‖x.val+t • y.val‖+‖x.val-t • y.val‖)/((2 : ℕ) : ℝ)-1 + +def oneSidedModulusReal (t : ℝ) : ℝ := + ⨅ x : {x : E // ‖x‖=1},⨆ F : ClosedFiniteCodim E, + ⨅ y : {y : E // y ∈ F.space ∧ ‖y‖=1},‖x.val+t • y.val‖-1 + +def IsAUCReal : Prop := ∀ t : ℝ, 0 < t → 0 < oneSidedModulusReal E t + +end AsymptoticModuli + +open TreeCalculus in +theorem TreeCalculus.main_counterexample (r : Bool) (k : QuadraticKind) : + (CompleteSpace (TestCompletion (treeTestFamily r k)) ∧ + TopologicalSpace.SeparableSpace (TestCompletion (treeTestFamily r k)) ∧ + ¬Module.Finite ℝ (TestCompletion (treeTestFamily r k))) ∧ + (∀ t : ℝ, 0 < t → t < 1 → + Real.sqrt (1 + t ^ 2 / 4) - 1 ≤ + averagedModulusReal (TestCompletion (treeTestFamily r k)) t) ∧ + (∀ (Y : Type u) [NormedAddCommGroup Y] [NormedSpace ℝ Y], + (TestCompletion (treeTestFamily r k) ≃L[ℝ] Y) → ¬IsAUCReal Y) := by + sorry + +end BoundedTreePotentials + +end + +end OAI diff --git a/tasks/bounded-tree-potentials/tests/grade.py b/tasks/bounded-tree-potentials/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bounded-tree-potentials/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bounded-tree-potentials/tests/task.json b/tasks/bounded-tree-potentials/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..77a2552f474e470ec63e03b6c33e75d21e71e7e5 --- /dev/null +++ b/tasks/bounded-tree-potentials/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BoundedTreePotentials", + "comparator": { + "theorem_names": [ + "OAI.BoundedTreePotentials.TreeCalculus.main_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11336 +} \ No newline at end of file diff --git a/tasks/bounded-tree-potentials/tests/test.sh b/tasks/bounded-tree-potentials/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bounded-tree-potentials/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/bounded-treewidth-l1/environment/Dockerfile b/tasks/bounded-treewidth-l1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/bounded-treewidth-l1/environment/fetch_mathlib.sh b/tasks/bounded-treewidth-l1/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/bounded-treewidth-l1/environment/lake-manifest.json b/tasks/bounded-treewidth-l1/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/bounded-treewidth-l1/environment/lakefile.lean b/tasks/bounded-treewidth-l1/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/bounded-treewidth-l1/environment/lean_setup.sh b/tasks/bounded-treewidth-l1/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/bounded-treewidth-l1/environment/pack_submission.py b/tasks/bounded-treewidth-l1/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/bounded-treewidth-l1/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/bounded-treewidth-l1/instruction.md b/tasks/bounded-treewidth-l1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ce0b7517d0937f6e8a0ce636653dc0ec69c8131b --- /dev/null +++ b/tasks/bounded-treewidth-l1/instruction.md @@ -0,0 +1,101 @@ +# openai/math challenge `BoundedTreewidthL1` (family 089) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 089 of the release, *Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs* +(Convex and metric geometry). The family as a whole: Resolves the planar and bounded-treewidth cases of the Gupta–Newman–Rabinovich–Sinclair conjecture. Shortest-path metrics of finite connected graphs with arbitrary positive edge lengths embed into real $L_1$ with universal distortion for planar graphs, and distortion depending only on treewidth for bounded-treewidth graphs. The corresponding multicommodity flow–cut gaps are uniformly bounded. + +The challenge is `BoundedTreewidthL1`, also at `/opt/openai-math/challenges/BoundedTreewidthL1.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace BoundedTreewidthL1 + +universe u_1 + +variable {V : Type u_1} (G : SimpleGraph V) + +/-- Sum of the given positive real edge lengths along a graph walk. -/ +def walkLength (ℓ : G.edgeSet → ℝ) : {u v : V} → G.Walk u v → ℝ + | _, _, .nil => 0 + | u, _, .cons (v := v) h p => ℓ ⟨s(u, v), h⟩ + walkLength ℓ p + +noncomputable def shortestPathDistance (ℓ : G.edgeSet → ℝ) (u v : V) : ℝ := + sInf {r : ℝ | ∃ p : G.Walk u v, p.IsPath ∧ walkLength G ℓ p = r} + +def HasTreeDecomposition [DecidableEq V] (k : ℕ) : Prop := + ∃ n : ℕ, ∃ T : SimpleGraph (Fin n), ∃ bag : Fin n → Finset V, + T.IsTree ∧ + (∀ v : V, ∃ t, v ∈ bag t) ∧ + (∀ u v : V, G.Adj u v → ∃ t, u ∈ bag t ∧ v ∈ bag t) ∧ + (∀ v : V, (T.induce {t | v ∈ bag t}).Connected) ∧ + (∀ t, (bag t).card ≤ k) + +/-- A map to genuine finite-dimensional real ℓ₁, not just a cut pseudometric. -/ +def HasL1Embedding (ℓ : G.edgeSet → ℝ) (C : ℝ) : Prop := + ∃ m : ℕ, ∃ F : V → PiLp (1 : ENNReal) (fun _ : Fin m => ℝ), + ∀ u v : V, + shortestPathDistance G ℓ u v ≤ ‖F u - F v‖ ∧ + ‖F u - F v‖ ≤ C * shortestPathDistance G ℓ u v + +def MainStatement : Prop := + ∀ k : ℕ, 2 ≤ k → ∃ C : ℝ, 1 ≤ C ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] [Nonempty V] + (G : SimpleGraph V), + G.Connected → HasTreeDecomposition G k → + ∀ ℓ : G.edgeSet → ℝ, (∀ e, 0 < ℓ e) → HasL1Embedding G ℓ C + +theorem main_theorem : MainStatement := by + sorry + +end BoundedTreewidthL1 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BoundedTreewidthL1.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoundedTreewidthL1.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/bounded-treewidth-l1/solution/closure.txt b/tasks/bounded-treewidth-l1/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed5502f967504d21b495915c424c1db0086b050e --- /dev/null +++ b/tasks/bounded-treewidth-l1/solution/closure.txt @@ -0,0 +1,33 @@ +OAI.Combinatorics.TreewidthL1.AnchorEmbedding +OAI.Combinatorics.TreewidthL1.AnchorExperiment +OAI.Combinatorics.TreewidthL1.AnchorGeometry +OAI.Combinatorics.TreewidthL1.Anchors +OAI.Combinatorics.TreewidthL1.Annulus +OAI.Combinatorics.TreewidthL1.BagLabels +OAI.Combinatorics.TreewidthL1.CacheControl +OAI.Combinatorics.TreewidthL1.CachedEnsemble +OAI.Combinatorics.TreewidthL1.CobagEmbedding +OAI.Combinatorics.TreewidthL1.CobagNoise +OAI.Combinatorics.TreewidthL1.CobagScales +OAI.Combinatorics.TreewidthL1.Construction +OAI.Combinatorics.TreewidthL1.Cuts +OAI.Combinatorics.TreewidthL1.ExpandedAnchor +OAI.Combinatorics.TreewidthL1.ExpandedParticles +OAI.Combinatorics.TreewidthL1.ExpandedPaths +OAI.Combinatorics.TreewidthL1.ExpandedTree +OAI.Combinatorics.TreewidthL1.LaunchNoise +OAI.Combinatorics.TreewidthL1.Main +OAI.Combinatorics.TreewidthL1.MarkovProduct +OAI.Combinatorics.TreewidthL1.Model +OAI.Combinatorics.TreewidthL1.NoiseCube +OAI.Combinatorics.TreewidthL1.OrderedSweep +OAI.Combinatorics.TreewidthL1.Padding +OAI.Combinatorics.TreewidthL1.ParticleLaws +OAI.Combinatorics.TreewidthL1.Particles +OAI.Combinatorics.TreewidthL1.ReservedCoupling +OAI.Combinatorics.TreewidthL1.ReservedTests +OAI.Combinatorics.TreewidthL1.TreeGeometry +OAI.Combinatorics.TreewidthL1.TreeMarkov +OAI.Combinatorics.TreewidthL1.TreeParticles +OAI.Combinatorics.TreewidthL1.WeightedPaths +OAI.Combinatorics.TreewidthL1.YoungestCrossing diff --git a/tasks/bounded-treewidth-l1/solution/reference.py b/tasks/bounded-treewidth-l1/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/bounded-treewidth-l1/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/bounded-treewidth-l1/solution/solve.sh b/tasks/bounded-treewidth-l1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..eaa0cd73d8363d7c9976d9b2e48a13033f42fa8d --- /dev/null +++ b/tasks/bounded-treewidth-l1/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BoundedTreewidthL1, i.e. module OAI.Combinatorics.TreewidthL1.Main and the +# 33 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TreewidthL1.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BoundedTreewidthL1" diff --git a/tasks/bounded-treewidth-l1/task.toml b/tasks/bounded-treewidth-l1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5d20b7ea4348ad42173bb28afac073547b566870 --- /dev/null +++ b/tasks/bounded-treewidth-l1/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/bounded-treewidth-l1" +version = "1.0.0" +description = "Prove BoundedTreewidthL1 (openai/math family 089: Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BoundedTreewidthL1.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BoundedTreewidthL1" +family = "089" +family_title = "Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs" +subject = "Convex and metric geometry" +theorems = ["OAI.BoundedTreewidthL1.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TreewidthL1.Main" +reference_modules = 33 +reference_lean_bytes = 708126 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 791 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12337 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/bounded-treewidth-l1/tests/Challenge.lean b/tasks/bounded-treewidth-l1/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..67e480b9219a4e49b455b3d34838f82b28296217 --- /dev/null +++ b/tasks/bounded-treewidth-l1/tests/Challenge.lean @@ -0,0 +1,50 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace BoundedTreewidthL1 + +universe u_1 + +variable {V : Type u_1} (G : SimpleGraph V) + +/-- Sum of the given positive real edge lengths along a graph walk. -/ +def walkLength (ℓ : G.edgeSet → ℝ) : {u v : V} → G.Walk u v → ℝ + | _, _, .nil => 0 + | u, _, .cons (v := v) h p => ℓ ⟨s(u, v), h⟩ + walkLength ℓ p + +noncomputable def shortestPathDistance (ℓ : G.edgeSet → ℝ) (u v : V) : ℝ := + sInf {r : ℝ | ∃ p : G.Walk u v, p.IsPath ∧ walkLength G ℓ p = r} + +def HasTreeDecomposition [DecidableEq V] (k : ℕ) : Prop := + ∃ n : ℕ, ∃ T : SimpleGraph (Fin n), ∃ bag : Fin n → Finset V, + T.IsTree ∧ + (∀ v : V, ∃ t, v ∈ bag t) ∧ + (∀ u v : V, G.Adj u v → ∃ t, u ∈ bag t ∧ v ∈ bag t) ∧ + (∀ v : V, (T.induce {t | v ∈ bag t}).Connected) ∧ + (∀ t, (bag t).card ≤ k) + +/-- A map to genuine finite-dimensional real ℓ₁, not just a cut pseudometric. -/ +def HasL1Embedding (ℓ : G.edgeSet → ℝ) (C : ℝ) : Prop := + ∃ m : ℕ, ∃ F : V → PiLp (1 : ENNReal) (fun _ : Fin m => ℝ), + ∀ u v : V, + shortestPathDistance G ℓ u v ≤ ‖F u - F v‖ ∧ + ‖F u - F v‖ ≤ C * shortestPathDistance G ℓ u v + +def MainStatement : Prop := + ∀ k : ℕ, 2 ≤ k → ∃ C : ℝ, 1 ≤ C ∧ + ∀ (V : Type) [Fintype V] [DecidableEq V] [Nonempty V] + (G : SimpleGraph V), + G.Connected → HasTreeDecomposition G k → + ∀ ℓ : G.edgeSet → ℝ, (∀ e, 0 < ℓ e) → HasL1Embedding G ℓ C + +theorem main_theorem : MainStatement := by + sorry + +end BoundedTreewidthL1 + +end + +end OAI diff --git a/tasks/bounded-treewidth-l1/tests/grade.py b/tasks/bounded-treewidth-l1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/bounded-treewidth-l1/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/bounded-treewidth-l1/tests/task.json b/tasks/bounded-treewidth-l1/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9439e7d11234d0747038780a3b34f348ef7a8dc9 --- /dev/null +++ b/tasks/bounded-treewidth-l1/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BoundedTreewidthL1", + "comparator": { + "theorem_names": [ + "OAI.BoundedTreewidthL1.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11437 +} \ No newline at end of file diff --git a/tasks/bounded-treewidth-l1/tests/test.sh b/tasks/bounded-treewidth-l1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/bounded-treewidth-l1/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/brenier/environment/Dockerfile b/tasks/brenier/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/brenier/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/brenier/environment/fetch_mathlib.sh b/tasks/brenier/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/brenier/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/brenier/environment/lake-manifest.json b/tasks/brenier/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/brenier/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/brenier/environment/lakefile.lean b/tasks/brenier/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/brenier/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/brenier/environment/lean_setup.sh b/tasks/brenier/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/brenier/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/brenier/environment/pack_submission.py b/tasks/brenier/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/brenier/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/brenier/instruction.md b/tasks/brenier/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26cda2447ac36ebdf5a7a893b465c398a153cbd3 --- /dev/null +++ b/tasks/brenier/instruction.md @@ -0,0 +1,159 @@ +# openai/math challenge `Brenier` (family 374) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 374 of the release, *Sharp one-third stability of optimal transport maps* +(Partial differential equations). The family as a whole: For uniform source measure $\rho$ on a compact convex body with interior in dimension at least two, quadratic optimal transport maps satisfy $\|T_\mu-T_\nu\|_{L^2(\rho)}\le C W_2(\mu,\nu)^{1/3}$ uniformly over targets in a fixed compact set. The exponent is sharp, even for three-atom targets, disproving Letrouit's conjectured square-root bound. + +The challenge is `Brenier`, also at `/opt/openai-math/challenges/Brenier.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal + +namespace Problem358 + +abbrev E (dimension : ℕ) := EuclideanSpace ℝ (Fin dimension) + +def uniformMeasure {dimension : ℕ} (source : Set (E dimension)) : Measure (E dimension) := + (volume source)⁻¹ • volume.restrict source + +def IsSupported {dimension : ℕ} (measure : Measure (E dimension)) + (container : Set (E dimension)) : Prop := + measure (containerᶜ) = 0 + +def IsCoupling {dimension : ℕ} (source target : Measure (E dimension)) + (plan : Measure (E dimension × E dimension)) : Prop := + IsProbabilityMeasure plan ∧ + Measure.map Prod.fst plan = source ∧ + Measure.map Prod.snd plan = target + +def quadraticPlanCost {dimension : ℕ} (plan : Measure (E dimension × E dimension)) : + ℝ≥0∞ := + ∫⁻ pair, ENNReal.ofReal (‖pair.1 - pair.2‖ ^ 2) ∂plan + +def wasserstein2 {dimension : ℕ} (source target : Measure (E dimension)) : ℝ := + Real.sqrt + (ENNReal.toReal + (sInf {cost : ℝ≥0∞ | + ∃ plan : Measure (E dimension × E dimension), + IsCoupling source target plan ∧ quadraticPlanCost plan = cost})) + +def graphPlan {dimension : ℕ} (source : Measure (E dimension)) + (transport : E dimension → E dimension) : Measure (E dimension × E dimension) := + Measure.map (fun point => (point, transport point)) source + +def IsQuadraticOptimalMap {dimension : ℕ} (source target : Measure (E dimension)) + (transport : E dimension → E dimension) : Prop := + Measurable transport ∧ + Measure.map transport source = target ∧ + ∀ plan : Measure (E dimension × E dimension), + IsCoupling source target plan → + quadraticPlanCost (graphPlan source transport) ≤ quadraticPlanCost plan + +def IsUniqueQuadraticOptimalMap {dimension : ℕ} (source target : Measure (E dimension)) + (transport : E dimension → E dimension) : Prop := + IsQuadraticOptimalMap source target transport ∧ + ∀ plan : Measure (E dimension × E dimension), + IsCoupling source target plan → + quadraticPlanCost plan ≤ quadraticPlanCost (graphPlan source transport) → + plan = graphPlan source transport + +def mapL2Dist {dimension : ℕ} (source : Measure (E dimension)) + (first second : E dimension → E dimension) : ℝ := + Real.sqrt (∫ point, ‖first point - second point‖ ^ 2 ∂source) + +def cube (dimension : ℕ) : Set (E dimension) := + {point | ∀ index, |point index| ≤ 1} + +def HasExactlyThreeAtoms {dimension : ℕ} (measure : Measure (E dimension)) + (container : Set (E dimension)) : Prop := + ∃ atoms : Fin 3 → E dimension, Function.Injective atoms ∧ + (∀ index, atoms index ∈ container) ∧ + ∃ weights : Fin 3 → ℝ≥0∞, (∀ index, 0 < weights index) ∧ + (∑ index, weights index) = 1 ∧ + measure = ∑ index, weights index • Measure.dirac (atoms index) + +theorem one_third_stability : + ∀ (dimension : ℕ) (source container : Set (E dimension)), + 2 ≤ dimension → IsCompact source → Convex ℝ source → (interior source).Nonempty → + IsCompact container → container.Nonempty → + ∃ constant : ℝ, 0 ≤ constant ∧ + ∀ (first second : Measure (E dimension)), + IsProbabilityMeasure first → IsProbabilityMeasure second → + IsSupported first container → IsSupported second container → + ∃ firstMap secondMap : E dimension → E dimension, + IsUniqueQuadraticOptimalMap (uniformMeasure source) first firstMap ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure source) second secondMap ∧ + mapL2Dist (uniformMeasure source) firstMap secondMap ≤ + constant * Real.rpow (wasserstein2 first second) (1 / 3 : ℝ) := by + sorry + +theorem one_third_exponent_is_sharp : + ∀ (dimension : ℕ), 2 ≤ dimension → ∀ exponent : ℝ, (1 / 3 : ℝ) < exponent → + ∀ constant : ℝ, 0 < constant → + ∃ (first second : Measure (E dimension)) (firstMap secondMap : E dimension → E dimension), + IsProbabilityMeasure first ∧ IsProbabilityMeasure second ∧ + IsSupported first (cube dimension) ∧ IsSupported second (cube dimension) ∧ + HasExactlyThreeAtoms first (cube dimension) ∧ + HasExactlyThreeAtoms second (cube dimension) ∧ + first ≠ second ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure (cube dimension)) first firstMap ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure (cube dimension)) second secondMap ∧ + 0 < wasserstein2 first second ∧ + constant * Real.rpow (wasserstein2 first second) exponent < + mapL2Dist (uniformMeasure (cube dimension)) firstMap secondMap := by + sorry + +end Problem358 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Brenier.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Problem358.one_third_stability`, `OAI.Problem358.one_third_exponent_is_sharp` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/brenier/solution/closure.txt b/tasks/brenier/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc125b295c3cbf455c2570cc4ed351bea822ec9d --- /dev/null +++ b/tasks/brenier/solution/closure.txt @@ -0,0 +1,89 @@ +OAI.Analysis.Brenier.AffineCertificate +OAI.Analysis.Brenier.AffineOptimality +OAI.Analysis.Brenier.AffinePaths +OAI.Analysis.Brenier.AffineTies +OAI.Analysis.Brenier.Approximation +OAI.Analysis.Brenier.Argmax +OAI.Analysis.Brenier.Atomic +OAI.Analysis.Brenier.AtomicPaths +OAI.Analysis.Brenier.AtomicTransport +OAI.Analysis.Brenier.Basic +OAI.Analysis.Brenier.BoundaryStrip +OAI.Analysis.Brenier.CanonicalLaplacian +OAI.Analysis.Brenier.CanonicalPaths +OAI.Analysis.Brenier.CellContinuity +OAI.Analysis.Brenier.CellDerivative +OAI.Analysis.Brenier.CellEnergy +OAI.Analysis.Brenier.CellFaces +OAI.Analysis.Brenier.CellGeometry +OAI.Analysis.Brenier.CellMeasure +OAI.Analysis.Brenier.ClosedPaths +OAI.Analysis.Brenier.CompactMeasure +OAI.Analysis.Brenier.CompactTransport +OAI.Analysis.Brenier.Conjugacy +OAI.Analysis.Brenier.ConvexDensity +OAI.Analysis.Brenier.ConvexOptimality +OAI.Analysis.Brenier.ConvexQuantiles +OAI.Analysis.Brenier.Coordinates +OAI.Analysis.Brenier.Coupling +OAI.Analysis.Brenier.Cube +OAI.Analysis.Brenier.CutDerivative +OAI.Analysis.Brenier.CutVariation +OAI.Analysis.Brenier.DensityCDF +OAI.Analysis.Brenier.Difference +OAI.Analysis.Brenier.EndpointEnergy +OAI.Analysis.Brenier.Existence +OAI.Analysis.Brenier.FaceContinuity +OAI.Analysis.Brenier.FacetConnectivity +OAI.Analysis.Brenier.FiniteCoupling +OAI.Analysis.Brenier.FixedMass +OAI.Analysis.Brenier.Flux +OAI.Analysis.Brenier.HalfspaceKernel +OAI.Analysis.Brenier.InterceptContinuity +OAI.Analysis.Brenier.InterceptEnergy +OAI.Analysis.Brenier.Interfaces +OAI.Analysis.Brenier.Laplacian +OAI.Analysis.Brenier.LineDerivative +OAI.Analysis.Brenier.MapDistance +OAI.Analysis.Brenier.MapLimits +OAI.Analysis.Brenier.MapTransport +OAI.Analysis.Brenier.MassDerivative +OAI.Analysis.Brenier.MaxCalculus +OAI.Analysis.Brenier.MaxLimits +OAI.Analysis.Brenier.Midpoint +OAI.Analysis.Brenier.Minimizers +OAI.Analysis.Brenier.MomentAlgebra +OAI.Analysis.Brenier.MovingBoundary +OAI.Analysis.Brenier.MovingTrace +OAI.Analysis.Brenier.NormalizedPaths +OAI.Analysis.Brenier.NormalizedSections +OAI.Analysis.Brenier.Optimality +OAI.Analysis.Brenier.PlaneEnvelopes +OAI.Analysis.Brenier.Potential +OAI.Analysis.Brenier.PotentialLimits +OAI.Analysis.Brenier.PotentialTime +OAI.Analysis.Brenier.PrefixSampling +OAI.Analysis.Brenier.PrefixSections +OAI.Analysis.Brenier.PrescribedCells +OAI.Analysis.Brenier.Quantiles +OAI.Analysis.Brenier.Quantization +OAI.Analysis.Brenier.Sections +OAI.Analysis.Brenier.SharpMaps +OAI.Analysis.Brenier.SharpOptimality +OAI.Analysis.Brenier.SharpRectangle +OAI.Analysis.Brenier.SharpSlices +OAI.Analysis.Brenier.SharpTargets +OAI.Analysis.Brenier.Sharpness +OAI.Analysis.Brenier.SliceInterpolation +OAI.Analysis.Brenier.Stability +OAI.Analysis.Brenier.StationaryMoment +OAI.Analysis.Brenier.SupportingInterpolation +OAI.Analysis.Brenier.SurfaceCoordinates +OAI.Analysis.Brenier.SurfaceMeasure +OAI.Analysis.Brenier.Translation +OAI.Analysis.Brenier.TriangularDomination +OAI.Analysis.Brenier.TriangularRecursion +OAI.Analysis.Brenier.TriangularSampling +OAI.Analysis.Brenier.Uniform +OAI.Analysis.Brenier.UniformInterpolation +OAI.Analysis.Brenier.Wasserstein diff --git a/tasks/brenier/solution/reference.py b/tasks/brenier/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/brenier/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/brenier/solution/solve.sh b/tasks/brenier/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..31f703bf7359af9abab199a231d9350df2bfb3b8 --- /dev/null +++ b/tasks/brenier/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Brenier, i.e. module OAI.Analysis.Brenier.Stability and the +# 89 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Brenier.Stability /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Brenier" diff --git a/tasks/brenier/task.toml b/tasks/brenier/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d25e2621a33867f683bd41ec629efd23a323f837 --- /dev/null +++ b/tasks/brenier/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/brenier" +version = "1.0.0" +description = "Prove Brenier (openai/math family 374: Sharp one-third stability of optimal transport maps) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Brenier.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Brenier" +family = "374" +family_title = "Sharp one-third stability of optimal transport maps" +subject = "Partial differential equations" +theorems = ["OAI.Problem358.one_third_stability", "OAI.Problem358.one_third_exponent_is_sharp"] +definition_holes = [] +fixed_definitions = ["OAI.Problem358.E", "OAI.Problem358.uniformMeasure", "OAI.Problem358.IsSupported", "OAI.Problem358.IsCoupling", "OAI.Problem358.quadraticPlanCost", "OAI.Problem358.wasserstein2", "OAI.Problem358.graphPlan", "OAI.Problem358.IsQuadraticOptimalMap", "OAI.Problem358.IsUniqueQuadraticOptimalMap", "OAI.Problem358.mapL2Dist", "OAI.Problem358.cube", "OAI.Problem358.HasExactlyThreeAtoms"] +reference_module = "OAI.Analysis.Brenier.Stability" +reference_modules = 89 +reference_lean_bytes = 1532625 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2528 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13079 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/brenier/tests/Challenge.lean b/tasks/brenier/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..73aa94c7226db7e0548459fe11eec424c62def7f --- /dev/null +++ b/tasks/brenier/tests/Challenge.lean @@ -0,0 +1,108 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal + +namespace Problem358 + +abbrev E (dimension : ℕ) := EuclideanSpace ℝ (Fin dimension) + +def uniformMeasure {dimension : ℕ} (source : Set (E dimension)) : Measure (E dimension) := + (volume source)⁻¹ • volume.restrict source + +def IsSupported {dimension : ℕ} (measure : Measure (E dimension)) + (container : Set (E dimension)) : Prop := + measure (containerᶜ) = 0 + +def IsCoupling {dimension : ℕ} (source target : Measure (E dimension)) + (plan : Measure (E dimension × E dimension)) : Prop := + IsProbabilityMeasure plan ∧ + Measure.map Prod.fst plan = source ∧ + Measure.map Prod.snd plan = target + +def quadraticPlanCost {dimension : ℕ} (plan : Measure (E dimension × E dimension)) : + ℝ≥0∞ := + ∫⁻ pair, ENNReal.ofReal (‖pair.1 - pair.2‖ ^ 2) ∂plan + +def wasserstein2 {dimension : ℕ} (source target : Measure (E dimension)) : ℝ := + Real.sqrt + (ENNReal.toReal + (sInf {cost : ℝ≥0∞ | + ∃ plan : Measure (E dimension × E dimension), + IsCoupling source target plan ∧ quadraticPlanCost plan = cost})) + +def graphPlan {dimension : ℕ} (source : Measure (E dimension)) + (transport : E dimension → E dimension) : Measure (E dimension × E dimension) := + Measure.map (fun point => (point, transport point)) source + +def IsQuadraticOptimalMap {dimension : ℕ} (source target : Measure (E dimension)) + (transport : E dimension → E dimension) : Prop := + Measurable transport ∧ + Measure.map transport source = target ∧ + ∀ plan : Measure (E dimension × E dimension), + IsCoupling source target plan → + quadraticPlanCost (graphPlan source transport) ≤ quadraticPlanCost plan + +def IsUniqueQuadraticOptimalMap {dimension : ℕ} (source target : Measure (E dimension)) + (transport : E dimension → E dimension) : Prop := + IsQuadraticOptimalMap source target transport ∧ + ∀ plan : Measure (E dimension × E dimension), + IsCoupling source target plan → + quadraticPlanCost plan ≤ quadraticPlanCost (graphPlan source transport) → + plan = graphPlan source transport + +def mapL2Dist {dimension : ℕ} (source : Measure (E dimension)) + (first second : E dimension → E dimension) : ℝ := + Real.sqrt (∫ point, ‖first point - second point‖ ^ 2 ∂source) + +def cube (dimension : ℕ) : Set (E dimension) := + {point | ∀ index, |point index| ≤ 1} + +def HasExactlyThreeAtoms {dimension : ℕ} (measure : Measure (E dimension)) + (container : Set (E dimension)) : Prop := + ∃ atoms : Fin 3 → E dimension, Function.Injective atoms ∧ + (∀ index, atoms index ∈ container) ∧ + ∃ weights : Fin 3 → ℝ≥0∞, (∀ index, 0 < weights index) ∧ + (∑ index, weights index) = 1 ∧ + measure = ∑ index, weights index • Measure.dirac (atoms index) + +theorem one_third_stability : + ∀ (dimension : ℕ) (source container : Set (E dimension)), + 2 ≤ dimension → IsCompact source → Convex ℝ source → (interior source).Nonempty → + IsCompact container → container.Nonempty → + ∃ constant : ℝ, 0 ≤ constant ∧ + ∀ (first second : Measure (E dimension)), + IsProbabilityMeasure first → IsProbabilityMeasure second → + IsSupported first container → IsSupported second container → + ∃ firstMap secondMap : E dimension → E dimension, + IsUniqueQuadraticOptimalMap (uniformMeasure source) first firstMap ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure source) second secondMap ∧ + mapL2Dist (uniformMeasure source) firstMap secondMap ≤ + constant * Real.rpow (wasserstein2 first second) (1 / 3 : ℝ) := by + sorry + +theorem one_third_exponent_is_sharp : + ∀ (dimension : ℕ), 2 ≤ dimension → ∀ exponent : ℝ, (1 / 3 : ℝ) < exponent → + ∀ constant : ℝ, 0 < constant → + ∃ (first second : Measure (E dimension)) (firstMap secondMap : E dimension → E dimension), + IsProbabilityMeasure first ∧ IsProbabilityMeasure second ∧ + IsSupported first (cube dimension) ∧ IsSupported second (cube dimension) ∧ + HasExactlyThreeAtoms first (cube dimension) ∧ + HasExactlyThreeAtoms second (cube dimension) ∧ + first ≠ second ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure (cube dimension)) first firstMap ∧ + IsUniqueQuadraticOptimalMap (uniformMeasure (cube dimension)) second secondMap ∧ + 0 < wasserstein2 first second ∧ + constant * Real.rpow (wasserstein2 first second) exponent < + mapL2Dist (uniformMeasure (cube dimension)) firstMap secondMap := by + sorry + +end Problem358 + +end + +end OAI diff --git a/tasks/brenier/tests/grade.py b/tasks/brenier/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/brenier/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/brenier/tests/task.json b/tasks/brenier/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b350aad23980dd00c3f7b62733f356a22f767e93 --- /dev/null +++ b/tasks/brenier/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "Brenier", + "comparator": { + "theorem_names": [ + "OAI.Problem358.one_third_stability", + "OAI.Problem358.one_third_exponent_is_sharp" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12179 +} \ No newline at end of file diff --git a/tasks/brenier/tests/test.sh b/tasks/brenier/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/brenier/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/brennan-sharp/environment/Dockerfile b/tasks/brennan-sharp/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/brennan-sharp/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/brennan-sharp/environment/fetch_mathlib.sh b/tasks/brennan-sharp/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/brennan-sharp/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/brennan-sharp/environment/lake-manifest.json b/tasks/brennan-sharp/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/brennan-sharp/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/brennan-sharp/environment/lakefile.lean b/tasks/brennan-sharp/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/brennan-sharp/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/brennan-sharp/environment/lean_setup.sh b/tasks/brennan-sharp/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/brennan-sharp/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/brennan-sharp/environment/pack_submission.py b/tasks/brennan-sharp/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/brennan-sharp/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/brennan-sharp/instruction.md b/tasks/brennan-sharp/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fa2edba560773729f0203032d2f9d6d46bf779f4 --- /dev/null +++ b/tasks/brennan-sharp/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `BrennanSharp` (family 072) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 072 of the release, *Brennan's conjecture and a counterexample to Kraetzer's prediction* +(Real and complex analysis). The family as a whole: Proves Brennan's conjecture: for every conformal bijection $\phi$ from a simply connected plane domain onto the disk, $|\phi'|^s$ is area-integrable for $4/3 ‖deriv koebeInverse z‖ ^ (4 : ℝ)) koebeDomain volume ∧ + ¬ IntegrableOn (fun z => ‖deriv koebeInverse z‖ ^ (4 / 3 : ℝ)) koebeDomain volume + +theorem sharp_endpoints : SharpEndpointStatement := by + sorry + +end Sharp +end Brennan + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BrennanSharp.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Brennan.Sharp.sharp_endpoints` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/brennan-sharp/solution/closure.txt b/tasks/brennan-sharp/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..951cf2cce67d9942e370b2f35c7c1f9589bdbf75 --- /dev/null +++ b/tasks/brennan-sharp/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Analysis.IntegralMeans.AffineArea +OAI.Analysis.IntegralMeans.AffineLaw +OAI.Analysis.IntegralMeans.AreaTransport +OAI.Analysis.IntegralMeans.BorelPairing +OAI.Analysis.IntegralMeans.BoundaryEscape +OAI.Analysis.IntegralMeans.BoundaryTail +OAI.Analysis.IntegralMeans.CircleBounds +OAI.Analysis.IntegralMeans.CompactClass +OAI.Analysis.IntegralMeans.CriticalCount +OAI.Analysis.IntegralMeans.CriticalMap +OAI.Analysis.IntegralMeans.CriticalPoint +OAI.Analysis.IntegralMeans.Degree +OAI.Analysis.IntegralMeans.Distortion +OAI.Analysis.IntegralMeans.DomainArea +OAI.Analysis.IntegralMeans.Eigenmeasure +OAI.Analysis.IntegralMeans.ExpectedDensity +OAI.Analysis.IntegralMeans.ExpectedTransport +OAI.Analysis.IntegralMeans.GoodPairs +OAI.Analysis.IntegralMeans.HalfPlane +OAI.Analysis.IntegralMeans.InverseDensity +OAI.Analysis.IntegralMeans.InverseMoment +OAI.Analysis.IntegralMeans.Koebe +OAI.Analysis.IntegralMeans.KoebeCone +OAI.Analysis.IntegralMeans.KoebeDivergence +OAI.Analysis.IntegralMeans.KoebePolar +OAI.Analysis.IntegralMeans.KoebeReduction +OAI.Analysis.IntegralMeans.LevelCurve +OAI.Analysis.IntegralMeans.LevelIndex +OAI.Analysis.IntegralMeans.LogIncrement +OAI.Analysis.IntegralMeans.Main +OAI.Analysis.IntegralMeans.Model +OAI.Analysis.IntegralMeans.Moments +OAI.Analysis.IntegralMeans.NegativeArea +OAI.Analysis.IntegralMeans.PositiveArea +OAI.Analysis.IntegralMeans.RankPairing +OAI.Analysis.IntegralMeans.SectorDivergence +OAI.Analysis.IntegralMeans.SharpEndpoints +OAI.Analysis.IntegralMeans.SharpModel +OAI.Analysis.IntegralMeans.SmoothMeans +OAI.Analysis.IntegralMeans.Spectrum +OAI.Analysis.IntegralMeans.TraceBounds +OAI.Analysis.IntegralMeans.TraceIdentity +OAI.Analysis.IntegralMeans.TransferOperator +OAI.Analysis.IntegralMeans.TransportBoxes +OAI.Analysis.IntegralMeans.Turning +OAI.Analysis.IntegralMeans.UnivalentArea +OAI.Analysis.IntegralMeans.Winding diff --git a/tasks/brennan-sharp/solution/reference.py b/tasks/brennan-sharp/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/brennan-sharp/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/brennan-sharp/solution/solve.sh b/tasks/brennan-sharp/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..80b5659bd3890bcc082d39d22d94598fc0930e0a --- /dev/null +++ b/tasks/brennan-sharp/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BrennanSharp, i.e. module OAI.Analysis.IntegralMeans.SharpEndpoints and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.IntegralMeans.SharpEndpoints /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BrennanSharp" diff --git a/tasks/brennan-sharp/task.toml b/tasks/brennan-sharp/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e697b4437e452845c208dea8ecead463660eb41 --- /dev/null +++ b/tasks/brennan-sharp/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/brennan-sharp" +version = "1.0.0" +description = "Prove BrennanSharp (openai/math family 072: Brennan's conjecture and a counterexample to Kraetzer's prediction) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BrennanSharp.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BrennanSharp" +family = "072" +family_title = "Brennan's conjecture and a counterexample to Kraetzer's prediction" +subject = "Real and complex analysis" +theorems = ["OAI.Brennan.Sharp.sharp_endpoints"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.IntegralMeans.SharpEndpoints" +reference_modules = 47 +reference_lean_bytes = 711263 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 895 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12340 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/brennan-sharp/tests/Challenge.lean b/tasks/brennan-sharp/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ab02a6cd590909d6420393200549efdcd53078f7 --- /dev/null +++ b/tasks/brennan-sharp/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory Filter +open scoped Topology ENNReal +namespace Brennan + +def disk : Set ℂ := Metric.ball 0 1 + +def UnivalentOn (f : ℂ → ℂ) (U : Set ℂ) : Prop := + DifferentiableOn ℂ f U ∧ Set.InjOn f U + +def Schlicht (f : ℂ → ℂ) : Prop := + UnivalentOn f disk ∧ f 0 = 0 ∧ deriv f 0 = 1 + +def koebeMap (z : ℂ) : ℂ := z/(1-z)^2 + +namespace Sharp + +def koebeDomain : Set ℂ := koebeMap '' disk + +def koebeInverse : ℂ → ℂ := Function.invFunOn koebeMap disk + +def areaMoment (f : ℂ → ℂ) (U : Set ℂ) (t : ℝ) : ℝ≥0∞ := + ∫⁻ z in U, ENNReal.ofReal (‖deriv f z‖ ^ t) ∂volume + +def SharpEndpointStatement : Prop := + Schlicht koebeMap ∧ + areaMoment koebeMap disk (-2) = ⊤ ∧ + areaMoment koebeMap disk (2 / 3) = ⊤ ∧ + ¬ IntegrableOn (fun z => ‖deriv koebeInverse z‖ ^ (4 : ℝ)) koebeDomain volume ∧ + ¬ IntegrableOn (fun z => ‖deriv koebeInverse z‖ ^ (4 / 3 : ℝ)) koebeDomain volume + +theorem sharp_endpoints : SharpEndpointStatement := by + sorry + +end Sharp +end Brennan + +end + +end OAI diff --git a/tasks/brennan-sharp/tests/grade.py b/tasks/brennan-sharp/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/brennan-sharp/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/brennan-sharp/tests/task.json b/tasks/brennan-sharp/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e040866ffdee39b5024d8b5ae06516fa5ed86a6f --- /dev/null +++ b/tasks/brennan-sharp/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BrennanSharp", + "comparator": { + "theorem_names": [ + "OAI.Brennan.Sharp.sharp_endpoints" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11440 +} \ No newline at end of file diff --git a/tasks/brennan-sharp/tests/test.sh b/tasks/brennan-sharp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/brennan-sharp/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/brennan/environment/Dockerfile b/tasks/brennan/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/brennan/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/brennan/environment/fetch_mathlib.sh b/tasks/brennan/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/brennan/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/brennan/environment/lake-manifest.json b/tasks/brennan/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/brennan/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/brennan/environment/lakefile.lean b/tasks/brennan/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/brennan/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/brennan/environment/lean_setup.sh b/tasks/brennan/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/brennan/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/brennan/environment/pack_submission.py b/tasks/brennan/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/brennan/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/brennan/instruction.md b/tasks/brennan/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..906c143b9d28df04e0d90a23acd17b04b940a776 --- /dev/null +++ b/tasks/brennan/instruction.md @@ -0,0 +1,104 @@ +# openai/math challenge `Brennan` (family 072) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 072 of the release, *Brennan's conjecture and a counterexample to Kraetzer's prediction* +(Real and complex analysis). The family as a whole: Proves Brennan's conjecture: for every conformal bijection $\phi$ from a simply connected plane domain onto the disk, $|\phi'|^s$ is area-integrable for $4/3 + ((Real.log (integralMean f t r) / Real.log (1 / (1 - r)) : ℝ) : EReal)) + (𝓝[<] (1 : ℝ)) + +def spectrum (t : ℝ) : EReal := + sSup {b | ∃ f : ℂ → ℂ, Schlicht f ∧ beta f t = b} + +def SphericalBoundaryNontrivial (W : Set ℂ) : Prop := + Set.Nontrivial (frontier (((↑) : ℂ → OnePoint ℂ) '' W)) + +def MainStatement : Prop := + (∀ ε : ℝ, 0 < ε → ∃ C : ℝ, ∀ f : ℂ → ℂ, Schlicht f → + ∀ r : ℝ, 1 / 2 ≤ r → r < 1 → + integralMean f (-2) r ≤ C * (1 - r) ^ (-1 - ε)) ∧ + spectrum (-2) = 1 ∧ + (∀ W : Set ℂ, IsOpen W → IsConnected W → SimplyConnectedSpace W → + SphericalBoundaryNontrivial W → ∀ φ : ℂ → ℂ, + DifferentiableOn ℂ φ W → Set.BijOn φ W disk → + ∀ s : ℝ, 4 / 3 < s → s < 4 → + IntegrableOn (fun z => ‖deriv φ z‖ ^ s) W volume) ∧ + (∀ f : ℂ → ℂ, UnivalentOn f disk → ∀ t : ℝ, + -2 < t → t < 2 / 3 → + IntegrableOn (fun z => ‖deriv f z‖ ^ t) disk volume) + +theorem main_theorem : MainStatement := by + sorry + +end Brennan +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Brennan.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Brennan.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/brennan/solution/closure.txt b/tasks/brennan/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..87d01ee8f9e7d21db47266f2e6a0780ec58793fb --- /dev/null +++ b/tasks/brennan/solution/closure.txt @@ -0,0 +1,38 @@ +OAI.Analysis.IntegralMeans.AffineLaw +OAI.Analysis.IntegralMeans.AreaTransport +OAI.Analysis.IntegralMeans.BorelPairing +OAI.Analysis.IntegralMeans.BoundaryEscape +OAI.Analysis.IntegralMeans.BoundaryTail +OAI.Analysis.IntegralMeans.CircleBounds +OAI.Analysis.IntegralMeans.CompactClass +OAI.Analysis.IntegralMeans.CriticalCount +OAI.Analysis.IntegralMeans.CriticalMap +OAI.Analysis.IntegralMeans.CriticalPoint +OAI.Analysis.IntegralMeans.Degree +OAI.Analysis.IntegralMeans.Distortion +OAI.Analysis.IntegralMeans.DomainArea +OAI.Analysis.IntegralMeans.Eigenmeasure +OAI.Analysis.IntegralMeans.ExpectedDensity +OAI.Analysis.IntegralMeans.ExpectedTransport +OAI.Analysis.IntegralMeans.GoodPairs +OAI.Analysis.IntegralMeans.HalfPlane +OAI.Analysis.IntegralMeans.InverseDensity +OAI.Analysis.IntegralMeans.Koebe +OAI.Analysis.IntegralMeans.LevelCurve +OAI.Analysis.IntegralMeans.LevelIndex +OAI.Analysis.IntegralMeans.LogIncrement +OAI.Analysis.IntegralMeans.Main +OAI.Analysis.IntegralMeans.Model +OAI.Analysis.IntegralMeans.Moments +OAI.Analysis.IntegralMeans.NegativeArea +OAI.Analysis.IntegralMeans.PositiveArea +OAI.Analysis.IntegralMeans.RankPairing +OAI.Analysis.IntegralMeans.SmoothMeans +OAI.Analysis.IntegralMeans.Spectrum +OAI.Analysis.IntegralMeans.TraceBounds +OAI.Analysis.IntegralMeans.TraceIdentity +OAI.Analysis.IntegralMeans.TransferOperator +OAI.Analysis.IntegralMeans.TransportBoxes +OAI.Analysis.IntegralMeans.Turning +OAI.Analysis.IntegralMeans.UnivalentArea +OAI.Analysis.IntegralMeans.Winding diff --git a/tasks/brennan/solution/reference.py b/tasks/brennan/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/brennan/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/brennan/solution/solve.sh b/tasks/brennan/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d16fd8757aa281ea27b23800899a8689bd3fa96e --- /dev/null +++ b/tasks/brennan/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Brennan, i.e. module OAI.Analysis.IntegralMeans.Main and the +# 38 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.IntegralMeans.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Brennan" diff --git a/tasks/brennan/task.toml b/tasks/brennan/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..40f38d26efe70b4cdc0efbbf510e0cfa1b4744e8 --- /dev/null +++ b/tasks/brennan/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/brennan" +version = "1.0.0" +description = "Prove Brennan (openai/math family 072: Brennan's conjecture and a counterexample to Kraetzer's prediction) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Brennan.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Brennan" +family = "072" +family_title = "Brennan's conjecture and a counterexample to Kraetzer's prediction" +subject = "Real and complex analysis" +theorems = ["OAI.Brennan.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.IntegralMeans.Main" +reference_modules = 38 +reference_lean_bytes = 692980 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1116 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12323 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/brennan/tests/Challenge.lean b/tasks/brennan/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2b4be0b9d543973151cbae786a53f6c795e37a2c --- /dev/null +++ b/tasks/brennan/tests/Challenge.lean @@ -0,0 +1,53 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory Filter +open scoped Topology +namespace Brennan + +def disk : Set ℂ := Metric.ball 0 1 + +def UnivalentOn (f : ℂ → ℂ) (U : Set ℂ) : Prop := + DifferentiableOn ℂ f U ∧ Set.InjOn f U + +def Schlicht (f : ℂ → ℂ) : Prop := + UnivalentOn f disk ∧ f 0 = 0 ∧ deriv f 0 = 1 + +def integralMean (f : ℂ → ℂ) (t r : ℝ) : ℝ := + (2 * Real.pi)⁻¹ * ∫ θ in -Real.pi..Real.pi, + ‖deriv f ((r : ℂ) * Complex.exp ((θ : ℂ) * Complex.I))‖ ^ t + +def beta (f : ℂ → ℂ) (t : ℝ) : EReal := + Filter.limsup (fun r : ℝ => + ((Real.log (integralMean f t r) / Real.log (1 / (1 - r)) : ℝ) : EReal)) + (𝓝[<] (1 : ℝ)) + +def spectrum (t : ℝ) : EReal := + sSup {b | ∃ f : ℂ → ℂ, Schlicht f ∧ beta f t = b} + +def SphericalBoundaryNontrivial (W : Set ℂ) : Prop := + Set.Nontrivial (frontier (((↑) : ℂ → OnePoint ℂ) '' W)) + +def MainStatement : Prop := + (∀ ε : ℝ, 0 < ε → ∃ C : ℝ, ∀ f : ℂ → ℂ, Schlicht f → + ∀ r : ℝ, 1 / 2 ≤ r → r < 1 → + integralMean f (-2) r ≤ C * (1 - r) ^ (-1 - ε)) ∧ + spectrum (-2) = 1 ∧ + (∀ W : Set ℂ, IsOpen W → IsConnected W → SimplyConnectedSpace W → + SphericalBoundaryNontrivial W → ∀ φ : ℂ → ℂ, + DifferentiableOn ℂ φ W → Set.BijOn φ W disk → + ∀ s : ℝ, 4 / 3 < s → s < 4 → + IntegrableOn (fun z => ‖deriv φ z‖ ^ s) W volume) ∧ + (∀ f : ℂ → ℂ, UnivalentOn f disk → ∀ t : ℝ, + -2 < t → t < 2 / 3 → + IntegrableOn (fun z => ‖deriv f z‖ ^ t) disk volume) + +theorem main_theorem : MainStatement := by + sorry + +end Brennan +end + +end OAI diff --git a/tasks/brennan/tests/grade.py b/tasks/brennan/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/brennan/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/brennan/tests/task.json b/tasks/brennan/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6a3969f5030cf4577ed1b679f9918cd140d33dac --- /dev/null +++ b/tasks/brennan/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Brennan", + "comparator": { + "theorem_names": [ + "OAI.Brennan.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11423 +} \ No newline at end of file diff --git a/tasks/brennan/tests/test.sh b/tasks/brennan/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/brennan/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/buffered-ising/environment/Dockerfile b/tasks/buffered-ising/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/buffered-ising/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/buffered-ising/environment/fetch_mathlib.sh b/tasks/buffered-ising/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/buffered-ising/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/buffered-ising/environment/lake-manifest.json b/tasks/buffered-ising/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/buffered-ising/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/buffered-ising/environment/lakefile.lean b/tasks/buffered-ising/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/buffered-ising/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/buffered-ising/environment/lean_setup.sh b/tasks/buffered-ising/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/buffered-ising/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/buffered-ising/environment/pack_submission.py b/tasks/buffered-ising/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/buffered-ising/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/buffered-ising/instruction.md b/tasks/buffered-ising/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3ea4a51d3e7c32b3214ea4c357d734df43f51785 --- /dev/null +++ b/tasks/buffered-ising/instruction.md @@ -0,0 +1,164 @@ +# openai/math challenge `BufferedIsing` (family 218) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 218 of the release, *Conformal universality for weakly interacting and disordered Ising models* +(Probability and statistical mechanics). The family as a whole: Weak finite-range square-symmetric even multispin perturbations of the square-lattice Ising model preserve critical bulk spin and energy limits; weak square-symmetric contour interactions also yield chordal $\mathrm{SLE}_3$ interface limits. With sufficiently weak iid bond disorder of any fixed bounded nondegenerate mean-zero law, critical spin interfaces converge to the same law in probability over environments. + +The challenge is `BufferedIsing`, also at `/opt/openai-math/challenges/BufferedIsing.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators Classical + +namespace BufferedIsing + +/-- A finite graph given by its edge list. Zero couplings can encode missing edges. +Edges are indexed separately so parallel edges are counted separately. -/ +structure FiniteGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + coupling : Fin m → ℝ + coupling_nonneg : ∀ e, 0 ≤ coupling e + no_loops : ∀ e, left e ≠ right e + +abbrev Spins (n : ℕ) := Fin n → Bool + +def spin (b : Bool) : ℝ := if b then 1 else -1 + +noncomputable def energy {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (σ : Spins n) : ℝ := + (∑ e, G.coupling e * spin (σ (G.left e)) * spin (σ (G.right e))) + + ∑ v, h v * spin (σ v) + +noncomputable def weight {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (σ : Spins n) : ℝ := Real.exp (energy G h σ) + +def AgreesOn {n : ℕ} (S : Finset (Fin n)) (σ τ : Spins n) : Prop := + ∀ v ∈ S, σ v = τ v + +noncomputable def constrainedSum {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (P : Spins n → Prop) : ℝ := by + classical + exact ∑ σ, if P σ then weight G h σ else 0 + +/-- Conditional probability of σ_I=a, with σ_J=b and σ_F=τ prescribed. +All sums are finite and all fields are finite real numbers. -/ +noncomputable def conditionalProb {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) (a b τ : Spins n) : ℝ := + constrainedSum G h (fun σ => AgreesOn I σ a ∧ AgreesOn J σ b ∧ AgreesOn F σ τ) / + constrainedSum G h (fun σ => AgreesOn J σ b ∧ AgreesOn F σ τ) + +/-- Edges remaining after DELETION, not pinning, of F. -/ +def keptEdges {n m : ℕ} (G : FiniteGraph n m) (F : Finset (Fin n)) : Finset (Fin m) := + Finset.univ.filter (fun e => G.left e ∉ F ∧ G.right e ∉ F) + +abbrev KeptVertex {n : ℕ} (F : Finset (Fin n)) := {v : Fin n // v ∉ F} + +/-- Open-edge adjacency together with the two separate terminal identifications. +No virtual identification of common pins is present: those vertices are absent. -/ +def comparisonRel {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) (u v : KeptVertex F) : Prop := + (u.val ∈ I ∧ v.val ∈ I) ∨ (u.val ∈ J ∧ v.val ∈ J) ∨ + ∃ e ∈ ω, (G.left e = u.val ∧ G.right e = v.val) ∨ + (G.left e = v.val ∧ G.right e = u.val) + +/-- The equivalence closure implements components of the contracted open graph. -/ +def comparisonSetoid {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : Setoid (KeptVertex F) := + Relation.EqvGen.setoid (comparisonRel G I J F ω) + +noncomputable def clusterCount {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : ℕ := + Nat.card (Quotient (comparisonSetoid G I J F ω)) + +/-- Zero-field FK weight with q=2 and p_e=1-exp(-2 K_e). +Parallel edges may be retained: the measure after summing them is the measure +for the summed parallel coupling. Loops created by contraction do not change +components and cancel from connection probabilities. -/ +noncomputable def fkWeight {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : ℝ := by + classical + exact (2 : ℝ) ^ clusterCount G I J F ω * + ∏ e ∈ keptEdges G F, + if e ∈ ω then 1 - Real.exp (-2 * G.coupling e) else Real.exp (-2 * G.coupling e) + +/-- Choose any i in I and j in J. The terminal connection is independent of +these choices because I and J are each identified. -/ +noncomputable def qZero {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (i j : KeptVertex F) : ℝ := by + classical + exact (∑ ω ∈ (keptEdges G F).powerset, + if (comparisonSetoid G I J F ω).r i j then fkWeight G I J F ω else 0) / + ∑ ω ∈ (keptEdges G F).powerset, fkWeight G I J F ω + +/-- Any probability mixture of source prescriptions. Full configurations +index the mixture, but only their restrictions to J are used. Thus this is +exactly the class of all mixtures on {-1,+1}^J. -/ +noncomputable def mixtureProb {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) (a τ : Spins n) + (mix : Spins n → ℝ) : ℝ := + ∑ b, mix b * conditionalProb G h I J F a b τ + +/-- Finite-graph comparison for arbitrary probability mixtures on both sides. +Dirac mixtures recover the conditional laws. -/ +theorem finite_graph_comparison {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) + (hIJ : Disjoint I J) (hIF : Disjoint I F) (hJF : Disjoint J F) + (i j : KeptVertex F) (hi : i.val ∈ I) (hj : j.val ∈ J) + (a τ : Spins n) (mix mix' : Spins n → ℝ) + (hmix : ∀ b, 0 ≤ mix b) (hmix' : ∀ b, 0 ≤ mix' b) + (hmixsum : ∑ b, mix b = 1) (hmix'sum : ∑ b, mix' b = 1) : + Real.exp (-4 * Real.artanh (qZero G I J F i j)) ≤ + mixtureProb G h I J F a τ mix / mixtureProb G h I J F a τ mix' ∧ + mixtureProb G h I J F a τ mix / mixtureProb G h I J F a τ mix' ≤ + Real.exp (4 * Real.artanh (qZero G I J F i j)) := by + sorry + +end BufferedIsing + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/BufferedIsing.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BufferedIsing.finite_graph_comparison` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/buffered-ising/solution/closure.txt b/tasks/buffered-ising/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c038cbf3a0c6150d0815dc6943eb13f4b4f2bc75 --- /dev/null +++ b/tasks/buffered-ising/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.Probability.Ising.Basic +OAI.Probability.Ising.Colorings +OAI.Probability.Ising.Contraction +OAI.Probability.Ising.Covariance +OAI.Probability.Ising.EdwardsSokal +OAI.Probability.Ising.FieldUpdate +OAI.Probability.Ising.GibbsMeasure +OAI.Probability.Ising.Influence +OAI.Probability.Ising.Interpolation +OAI.Probability.Ising.Main +OAI.Probability.Ising.Marginals +OAI.Probability.Ising.PinnedMarginal +OAI.Probability.Ising.RandomCluster +OAI.Probability.Ising.SpinCorrelation +OAI.Probability.Ising.TwoSpin diff --git a/tasks/buffered-ising/solution/reference.py b/tasks/buffered-ising/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/buffered-ising/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/buffered-ising/solution/solve.sh b/tasks/buffered-ising/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..064b6106f0c26ce38f9b01e26f1b7bb9ce1333e2 --- /dev/null +++ b/tasks/buffered-ising/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of BufferedIsing, i.e. module OAI.Probability.Ising.Main and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Ising.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of BufferedIsing" diff --git a/tasks/buffered-ising/task.toml b/tasks/buffered-ising/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..31943229fb770b218569592519bdf6907d43de52 --- /dev/null +++ b/tasks/buffered-ising/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/buffered-ising" +version = "1.0.0" +description = "Prove BufferedIsing (openai/math family 218: Conformal universality for weakly interacting and disordered Ising models) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/BufferedIsing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "BufferedIsing" +family = "218" +family_title = "Conformal universality for weakly interacting and disordered Ising models" +subject = "Probability and statistical mechanics" +theorems = ["OAI.BufferedIsing.finite_graph_comparison"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Ising.Main" +reference_modules = 15 +reference_lean_bytes = 136460 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2053 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11822 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/buffered-ising/tests/Challenge.lean b/tasks/buffered-ising/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..62e1e6dfbfc9de2646d4472857e64284a19fab97 --- /dev/null +++ b/tasks/buffered-ising/tests/Challenge.lean @@ -0,0 +1,113 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators Classical + +namespace BufferedIsing + +/-- A finite graph given by its edge list. Zero couplings can encode missing edges. +Edges are indexed separately so parallel edges are counted separately. -/ +structure FiniteGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + coupling : Fin m → ℝ + coupling_nonneg : ∀ e, 0 ≤ coupling e + no_loops : ∀ e, left e ≠ right e + +abbrev Spins (n : ℕ) := Fin n → Bool + +def spin (b : Bool) : ℝ := if b then 1 else -1 + +noncomputable def energy {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (σ : Spins n) : ℝ := + (∑ e, G.coupling e * spin (σ (G.left e)) * spin (σ (G.right e))) + + ∑ v, h v * spin (σ v) + +noncomputable def weight {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (σ : Spins n) : ℝ := Real.exp (energy G h σ) + +def AgreesOn {n : ℕ} (S : Finset (Fin n)) (σ τ : Spins n) : Prop := + ∀ v ∈ S, σ v = τ v + +noncomputable def constrainedSum {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (P : Spins n → Prop) : ℝ := by + classical + exact ∑ σ, if P σ then weight G h σ else 0 + +/-- Conditional probability of σ_I=a, with σ_J=b and σ_F=τ prescribed. +All sums are finite and all fields are finite real numbers. -/ +noncomputable def conditionalProb {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) (a b τ : Spins n) : ℝ := + constrainedSum G h (fun σ => AgreesOn I σ a ∧ AgreesOn J σ b ∧ AgreesOn F σ τ) / + constrainedSum G h (fun σ => AgreesOn J σ b ∧ AgreesOn F σ τ) + +/-- Edges remaining after DELETION, not pinning, of F. -/ +def keptEdges {n m : ℕ} (G : FiniteGraph n m) (F : Finset (Fin n)) : Finset (Fin m) := + Finset.univ.filter (fun e => G.left e ∉ F ∧ G.right e ∉ F) + +abbrev KeptVertex {n : ℕ} (F : Finset (Fin n)) := {v : Fin n // v ∉ F} + +/-- Open-edge adjacency together with the two separate terminal identifications. +No virtual identification of common pins is present: those vertices are absent. -/ +def comparisonRel {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) (u v : KeptVertex F) : Prop := + (u.val ∈ I ∧ v.val ∈ I) ∨ (u.val ∈ J ∧ v.val ∈ J) ∨ + ∃ e ∈ ω, (G.left e = u.val ∧ G.right e = v.val) ∨ + (G.left e = v.val ∧ G.right e = u.val) + +/-- The equivalence closure implements components of the contracted open graph. -/ +def comparisonSetoid {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : Setoid (KeptVertex F) := + Relation.EqvGen.setoid (comparisonRel G I J F ω) + +noncomputable def clusterCount {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : ℕ := + Nat.card (Quotient (comparisonSetoid G I J F ω)) + +/-- Zero-field FK weight with q=2 and p_e=1-exp(-2 K_e). +Parallel edges may be retained: the measure after summing them is the measure +for the summed parallel coupling. Loops created by contraction do not change +components and cancel from connection probabilities. -/ +noncomputable def fkWeight {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (ω : Finset (Fin m)) : ℝ := by + classical + exact (2 : ℝ) ^ clusterCount G I J F ω * + ∏ e ∈ keptEdges G F, + if e ∈ ω then 1 - Real.exp (-2 * G.coupling e) else Real.exp (-2 * G.coupling e) + +/-- Choose any i in I and j in J. The terminal connection is independent of +these choices because I and J are each identified. -/ +noncomputable def qZero {n m : ℕ} (G : FiniteGraph n m) + (I J F : Finset (Fin n)) (i j : KeptVertex F) : ℝ := by + classical + exact (∑ ω ∈ (keptEdges G F).powerset, + if (comparisonSetoid G I J F ω).r i j then fkWeight G I J F ω else 0) / + ∑ ω ∈ (keptEdges G F).powerset, fkWeight G I J F ω + +/-- Any probability mixture of source prescriptions. Full configurations +index the mixture, but only their restrictions to J are used. Thus this is +exactly the class of all mixtures on {-1,+1}^J. -/ +noncomputable def mixtureProb {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) (a τ : Spins n) + (mix : Spins n → ℝ) : ℝ := + ∑ b, mix b * conditionalProb G h I J F a b τ + +/-- Finite-graph comparison for arbitrary probability mixtures on both sides. +Dirac mixtures recover the conditional laws. -/ +theorem finite_graph_comparison {n m : ℕ} (G : FiniteGraph n m) + (h : Fin n → ℝ) (I J F : Finset (Fin n)) + (hIJ : Disjoint I J) (hIF : Disjoint I F) (hJF : Disjoint J F) + (i j : KeptVertex F) (hi : i.val ∈ I) (hj : j.val ∈ J) + (a τ : Spins n) (mix mix' : Spins n → ℝ) + (hmix : ∀ b, 0 ≤ mix b) (hmix' : ∀ b, 0 ≤ mix' b) + (hmixsum : ∑ b, mix b = 1) (hmix'sum : ∑ b, mix' b = 1) : + Real.exp (-4 * Real.artanh (qZero G I J F i j)) ≤ + mixtureProb G h I J F a τ mix / mixtureProb G h I J F a τ mix' ∧ + mixtureProb G h I J F a τ mix / mixtureProb G h I J F a τ mix' ≤ + Real.exp (4 * Real.artanh (qZero G I J F i j)) := by + sorry + +end BufferedIsing + +end OAI diff --git a/tasks/buffered-ising/tests/grade.py b/tasks/buffered-ising/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/buffered-ising/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/buffered-ising/tests/task.json b/tasks/buffered-ising/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e33c7e946f31637e898e50f956518e6d14e7fb32 --- /dev/null +++ b/tasks/buffered-ising/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "BufferedIsing", + "comparator": { + "theorem_names": [ + "OAI.BufferedIsing.finite_graph_comparison" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10922 +} \ No newline at end of file diff --git a/tasks/buffered-ising/tests/test.sh b/tasks/buffered-ising/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/buffered-ising/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/c0-absorption/environment/Dockerfile b/tasks/c0-absorption/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/c0-absorption/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/c0-absorption/environment/fetch_mathlib.sh b/tasks/c0-absorption/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/c0-absorption/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/c0-absorption/environment/lake-manifest.json b/tasks/c0-absorption/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/c0-absorption/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/c0-absorption/environment/lakefile.lean b/tasks/c0-absorption/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/c0-absorption/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/c0-absorption/environment/lean_setup.sh b/tasks/c0-absorption/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/c0-absorption/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/c0-absorption/environment/pack_submission.py b/tasks/c0-absorption/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/c0-absorption/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/c0-absorption/instruction.md b/tasks/c0-absorption/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3d565b6324a858335bf6c47f1b0efab27a5a84ef --- /dev/null +++ b/tasks/c0-absorption/instruction.md @@ -0,0 +1,84 @@ +# openai/math challenge `C0Absorption` (family 324) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 324 of the release, *Lipschitz equivalence without linear isomorphism* +(Functional analysis). The family as a whole: Constructs separable real Banach spaces that are globally bi-Lipschitz equivalent but not linearly isomorphic, resolving the separable Lipschitz-isomorphism problem negatively. Thus even the complete metric structure up to bi-Lipschitz equivalence does not determine a separable Banach space's linear isomorphism class. + +The challenge is `C0Absorption`, also at `/opt/openai-math/challenges/C0Absorption.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace C0Absorption + +open scoped ZeroAtInfty + +abbrev C0 := C₀(ℕ, ℝ) + +def BiLip {X Y : Type*} [MetricSpace X] [MetricSpace Y] (f : X → Y) : Prop := + ∃ c C : ℝ, 0 < c ∧ c ≤ C ∧ + ∀ x y, c * dist x y ≤ dist (f x) (f y) ∧ dist (f x) (f y) ≤ C * dist x y + +def NoLinearC0 (Z : Type*) [NormedAddCommGroup Z] [NormedSpace ℝ Z] : Prop := + ∀ T : C0 →L[ℝ] Z, ¬ ∃ c : ℝ, 0 < c ∧ ∀ x, c * ‖x‖ ≤ ‖T x‖ + +def MetricUniversal (Z : Type*) [MetricSpace Z] : Prop := + ∀ (M : Type) [MetricSpace M] [TopologicalSpace.SeparableSpace M], + ∃ f : M → Z, BiLip f + +def MainConclusion : Prop := + ∃ (Z : Type) (_ : NormedAddCommGroup Z) (_ : NormedSpace ℝ Z), + CompleteSpace Z ∧ TopologicalSpace.SeparableSpace Z ∧ NoLinearC0 Z ∧ + (∃ F : Z × C0 → Z, Function.Surjective F ∧ BiLip F) ∧ + (∃ f : C0 → Z, BiLip f) ∧ MetricUniversal Z ∧ + ¬ Nonempty ((Z × C0) ≃L[ℝ] Z) + +theorem main_result : MainConclusion := by sorry + +end C0Absorption + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/C0Absorption.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.C0Absorption.main_result` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/c0-absorption/solution/closure.txt b/tasks/c0-absorption/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fee387a7dd09c4be2edf8dd3b7df3e64ae241cdc --- /dev/null +++ b/tasks/c0-absorption/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Analysis.C0Absorption.Absorption +OAI.Analysis.C0Absorption.Aharoni +OAI.Analysis.C0Absorption.Angles +OAI.Analysis.C0Absorption.Blocks +OAI.Analysis.C0Absorption.Completion +OAI.Analysis.C0Absorption.Continuity +OAI.Analysis.C0Absorption.Coordinates +OAI.Analysis.C0Absorption.Core +OAI.Analysis.C0Absorption.Correction +OAI.Analysis.C0Absorption.Detection +OAI.Analysis.C0Absorption.Duality +OAI.Analysis.C0Absorption.Finite +OAI.Analysis.C0Absorption.FiniteShift +OAI.Analysis.C0Absorption.Frozen +OAI.Analysis.C0Absorption.Grid +OAI.Analysis.C0Absorption.Lists +OAI.Analysis.C0Absorption.LocalInverse +OAI.Analysis.C0Absorption.Localization +OAI.Analysis.C0Absorption.Main +OAI.Analysis.C0Absorption.Molecules +OAI.Analysis.C0Absorption.Norm +OAI.Analysis.C0Absorption.Onto +OAI.Analysis.C0Absorption.Operations +OAI.Analysis.C0Absorption.Operators +OAI.Analysis.C0Absorption.Pairings +OAI.Analysis.C0Absorption.Selection +OAI.Analysis.C0Absorption.Shift +OAI.Analysis.C0Absorption.Signs +OAI.Analysis.C0Absorption.Space +OAI.Analysis.C0Absorption.Supports +OAI.Analysis.C0Absorption.Tags +OAI.Analysis.C0Absorption.Tests +OAI.Analysis.C0Absorption.Triangular +OAI.Analysis.C0Absorption.Weights diff --git a/tasks/c0-absorption/solution/reference.py b/tasks/c0-absorption/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/c0-absorption/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/c0-absorption/solution/solve.sh b/tasks/c0-absorption/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a8fc755ad71c3d5d8e15d83d0e544ef9ff5495ae --- /dev/null +++ b/tasks/c0-absorption/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of C0Absorption, i.e. module OAI.Analysis.C0Absorption.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.C0Absorption.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of C0Absorption" diff --git a/tasks/c0-absorption/task.toml b/tasks/c0-absorption/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a384077d376aac782dcd87ea084a97263c0c7030 --- /dev/null +++ b/tasks/c0-absorption/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/c0-absorption" +version = "1.0.0" +description = "Prove C0Absorption (openai/math family 324: Lipschitz equivalence without linear isomorphism) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/C0Absorption.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "C0Absorption" +family = "324" +family_title = "Lipschitz equivalence without linear isomorphism" +subject = "Functional analysis" +theorems = ["OAI.C0Absorption.main_result"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.C0Absorption.Main" +reference_modules = 34 +reference_lean_bytes = 366161 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1155 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12029 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/c0-absorption/tests/Challenge.lean b/tasks/c0-absorption/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7b1cb26b3f3debdd0408045cb41076c568f3411a --- /dev/null +++ b/tasks/c0-absorption/tests/Challenge.lean @@ -0,0 +1,33 @@ +import Mathlib + +namespace OAI + +namespace C0Absorption + +open scoped ZeroAtInfty + +abbrev C0 := C₀(ℕ, ℝ) + +def BiLip {X Y : Type*} [MetricSpace X] [MetricSpace Y] (f : X → Y) : Prop := + ∃ c C : ℝ, 0 < c ∧ c ≤ C ∧ + ∀ x y, c * dist x y ≤ dist (f x) (f y) ∧ dist (f x) (f y) ≤ C * dist x y + +def NoLinearC0 (Z : Type*) [NormedAddCommGroup Z] [NormedSpace ℝ Z] : Prop := + ∀ T : C0 →L[ℝ] Z, ¬ ∃ c : ℝ, 0 < c ∧ ∀ x, c * ‖x‖ ≤ ‖T x‖ + +def MetricUniversal (Z : Type*) [MetricSpace Z] : Prop := + ∀ (M : Type) [MetricSpace M] [TopologicalSpace.SeparableSpace M], + ∃ f : M → Z, BiLip f + +def MainConclusion : Prop := + ∃ (Z : Type) (_ : NormedAddCommGroup Z) (_ : NormedSpace ℝ Z), + CompleteSpace Z ∧ TopologicalSpace.SeparableSpace Z ∧ NoLinearC0 Z ∧ + (∃ F : Z × C0 → Z, Function.Surjective F ∧ BiLip F) ∧ + (∃ f : C0 → Z, BiLip f) ∧ MetricUniversal Z ∧ + ¬ Nonempty ((Z × C0) ≃L[ℝ] Z) + +theorem main_result : MainConclusion := by sorry + +end C0Absorption + +end OAI diff --git a/tasks/c0-absorption/tests/grade.py b/tasks/c0-absorption/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/c0-absorption/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/c0-absorption/tests/task.json b/tasks/c0-absorption/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e01f27c77e1b70c74fd6b8ac12bc81e54ce2fb0d --- /dev/null +++ b/tasks/c0-absorption/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "C0Absorption", + "comparator": { + "theorem_names": [ + "OAI.C0Absorption.main_result" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11129 +} \ No newline at end of file diff --git a/tasks/c0-absorption/tests/test.sh b/tasks/c0-absorption/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/c0-absorption/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/c1-entropy-counterexample/environment/Dockerfile b/tasks/c1-entropy-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/c1-entropy-counterexample/environment/fetch_mathlib.sh b/tasks/c1-entropy-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/c1-entropy-counterexample/environment/lake-manifest.json b/tasks/c1-entropy-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/c1-entropy-counterexample/environment/lakefile.lean b/tasks/c1-entropy-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/c1-entropy-counterexample/environment/lean_setup.sh b/tasks/c1-entropy-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/c1-entropy-counterexample/environment/pack_submission.py b/tasks/c1-entropy-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/c1-entropy-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/c1-entropy-counterexample/instruction.md b/tasks/c1-entropy-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71eba9c43687f3f776b9b5cf06495698b7bda2af --- /dev/null +++ b/tasks/c1-entropy-counterexample/instruction.md @@ -0,0 +1,124 @@ +# openai/math challenge `C1EntropyCounterexample` (family 151) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 151 of the release, *A $C^1$ counterexample to Shub’s entropy conjecture* +(Dynamical systems and ergodic theory). The family as a whole: Constructs a noninvertible $C^1$ self-map of a compact smooth manifold with zero topological entropy but eigenvalue $2$ on second homology. This disproves the homological entropy lower bound for general $C^1$ self-maps: homological growth need not force positive orbit complexity. + +The challenge is `C1EntropyCounterexample`, also at `/opt/openai-math/challenges/C1EntropyCounterexample.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open CategoryTheory + +namespace Problem340 + +abbrev ClockAmbient := EuclideanSpace ℝ (Fin 2) + +abbrev SphereAmbient := EuclideanSpace ℝ (Fin 3) + +abbrev StandardClock := Metric.sphere (0 : ClockAmbient) (1 : ℝ) + +abbrev StandardSphere2 := Metric.sphere (0 : SphereAmbient) (1 : ℝ) + +abbrev CounterexampleManifold (q : ℕ) := + StandardClock × (Fin (q + 1) → StandardSphere2) + +abbrev CounterexampleAmbient (q : ℕ) := + ClockAmbient × (Fin (q + 1) → SphereAmbient) + +def standardEmbedding (q : ℕ) : + CounterexampleManifold q → CounterexampleAmbient q := + fun x => (x.1.1, fun i => (x.2 i).1) + +def IsC1SelfMap (q : ℕ) (f : CounterexampleManifold q → CounterexampleManifold q) : Prop := + Continuous f ∧ + ∀ x : CounterexampleManifold q, + ∃ U : Set (CounterexampleAmbient q), + IsOpen U ∧ standardEmbedding q x ∈ U ∧ + ∃ F : CounterexampleAmbient q → CounterexampleAmbient q, + ContDiffOn ℝ 1 F U ∧ + ∀ y : CounterexampleManifold q, + standardEmbedding q y ∈ U → + standardEmbedding q (f y) = F (standardEmbedding q y) + +def continuousMapOf {X Y : Type} [TopologicalSpace X] [TopologicalSpace Y] + (f : X → Y) (hf : Continuous f) : ContinuousMap X Y := + ⟨f, hf⟩ + +abbrev RealSingularHomology (n : ℕ) (X : Type) [TopologicalSpace X] := + (((AlgebraicTopology.singularHomologyFunctor (ModuleCat ℝ) n).obj + (ModuleCat.of ℝ ℝ)).obj (TopCat.of X)) + +def realHomologyMap {X Y : Type} [TopologicalSpace X] [TopologicalSpace Y] + (n : ℕ) (f : X → Y) (hf : Continuous f) : + RealSingularHomology n X →ₗ[ℝ] RealSingularHomology n Y := + (((AlgebraicTopology.singularHomologyFunctor (ModuleCat ℝ) n).obj + (ModuleCat.of ℝ ℝ)).map + (TopCat.ofHom (continuousMapOf f hf))).hom + +def totalRealHomologySpectralRadius {X : Type} [TopologicalSpace X] + (f : X → X) (hf : Continuous f) : ℝ := + sSup {r : ℝ | + ∃ n : ℕ, ∃ a b : ℝ, + ∃ u v : RealSingularHomology n X, + (u ≠ 0 ∨ v ≠ 0) ∧ + realHomologyMap n f hf u = a • u - b • v ∧ + realHomologyMap n f hf v = b • u + a • v ∧ + r = Real.sqrt (a ^ 2 + b ^ 2)} + +theorem exists_C1_entropy_counterexample : + ∃ q : ℕ, 0 < q ∧ ∃ f : CounterexampleManifold q → CounterexampleManifold q, ∃ hf : IsC1SelfMap q f, Dynamics.coverEntropy f (Set.univ : Set (CounterexampleManifold q)) = (0 : EReal) ∧ (∃ v : RealSingularHomology 2 (CounterexampleManifold q), v ≠ 0 ∧ realHomologyMap 2 f hf.1 v = (2 : ℝ) • v) ∧ 0 < Real.log (2 : ℝ) ∧ Real.log (2 : ℝ) ≤ Real.log (totalRealHomologySpectralRadius f hf.1) ∧ ¬ Function.Bijective f ∧ 5 ≤ 2 * q + 3 := by + sorry + +end Problem340 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/C1EntropyCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem340.exists_C1_entropy_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/c1-entropy-counterexample/solution/closure.txt b/tasks/c1-entropy-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e215b272bfcce42fa898b080be5ca22cdfeaf65f --- /dev/null +++ b/tasks/c1-entropy-counterexample/solution/closure.txt @@ -0,0 +1,201 @@ +OAI.Combinatorics.PerfectMatching.Simplex +OAI.Dynamics.EntropyCounterexample.AmbientPrediction +OAI.Dynamics.EntropyCounterexample.AmbientRetraction +OAI.Dynamics.EntropyCounterexample.Assembly +OAI.Dynamics.EntropyCounterexample.C1Conjugacy +OAI.Dynamics.EntropyCounterexample.C1CoordinatePullback +OAI.Dynamics.EntropyCounterexample.C1Coordinates +OAI.Dynamics.EntropyCounterexample.CircleClockDoubling +OAI.Dynamics.EntropyCounterexample.CircleDoublingChains +OAI.Dynamics.EntropyCounterexample.CircleWindingCocycle +OAI.Dynamics.EntropyCounterexample.Clock +OAI.Dynamics.EntropyCounterexample.ClockAtInfinity +OAI.Dynamics.EntropyCounterexample.ClockCharts +OAI.Dynamics.EntropyCounterexample.ClockDynamics +OAI.Dynamics.EntropyCounterexample.ClockLift +OAI.Dynamics.EntropyCounterexample.ClockLiftBridge +OAI.Dynamics.EntropyCounterexample.ClockLocalExtension +OAI.Dynamics.EntropyCounterexample.ClockModel +OAI.Dynamics.EntropyCounterexample.ClockOrbit +OAI.Dynamics.EntropyCounterexample.ClockPassage +OAI.Dynamics.EntropyCounterexample.ClockPeriodization +OAI.Dynamics.EntropyCounterexample.ClockPeriodizationCompatibility +OAI.Dynamics.EntropyCounterexample.ClockPeriodizationLocal +OAI.Dynamics.EntropyCounterexample.ClockPrediction +OAI.Dynamics.EntropyCounterexample.ClockProfiles +OAI.Dynamics.EntropyCounterexample.ClockQuotient +OAI.Dynamics.EntropyCounterexample.ClockQuotientC1 +OAI.Dynamics.EntropyCounterexample.ClockRotation +OAI.Dynamics.EntropyCounterexample.CompactLabels +OAI.Dynamics.EntropyCounterexample.ConcreteContinuity +OAI.Dynamics.EntropyCounterexample.ConcreteErasure +OAI.Dynamics.EntropyCounterexample.ConcreteErasureLimit +OAI.Dynamics.EntropyCounterexample.ConcreteInputRegularity +OAI.Dynamics.EntropyCounterexample.Conjugacy +OAI.Dynamics.EntropyCounterexample.CoordinateGoodCover +OAI.Dynamics.EntropyCounterexample.Counterexample +OAI.Dynamics.EntropyCounterexample.Definitions +OAI.Dynamics.EntropyCounterexample.Embedding +OAI.Dynamics.EntropyCounterexample.EntropyBounds +OAI.Dynamics.EntropyCounterexample.EntropyCoding +OAI.Dynamics.EntropyCounterexample.EntropyLocalization +OAI.Dynamics.EntropyCounterexample.EntropySection +OAI.Dynamics.EntropyCounterexample.EntropySparseCover +OAI.Dynamics.EntropyCounterexample.FiniteSpectrumBound +OAI.Dynamics.EntropyCounterexample.GainCircle +OAI.Dynamics.EntropyCounterexample.GainLocalExtension +OAI.Dynamics.EntropyCounterexample.GainProfile +OAI.Dynamics.EntropyCounterexample.GlobalEscape +OAI.Dynamics.EntropyCounterexample.HomotopySpectrum +OAI.Dynamics.EntropyCounterexample.ImageEntropy +OAI.Dynamics.EntropyCounterexample.InputSeries +OAI.Dynamics.EntropyCounterexample.LocalPredictionInput +OAI.Dynamics.EntropyCounterexample.Map +OAI.Dynamics.EntropyCounterexample.MapBoundedOrbit +OAI.Dynamics.EntropyCounterexample.MapC1 +OAI.Dynamics.EntropyCounterexample.MapC1Complete +OAI.Dynamics.EntropyCounterexample.MapClockComponent +OAI.Dynamics.EntropyCounterexample.MapConcretePassage +OAI.Dynamics.EntropyCounterexample.MapContinuity +OAI.Dynamics.EntropyCounterexample.MapData +OAI.Dynamics.EntropyCounterexample.MapEntropy +OAI.Dynamics.EntropyCounterexample.MapEntropyComplete +OAI.Dynamics.EntropyCounterexample.MapErasure +OAI.Dynamics.EntropyCounterexample.MapFinalReduction +OAI.Dynamics.EntropyCounterexample.MapFiniteOrbit +OAI.Dynamics.EntropyCounterexample.MapGlobalEscape +OAI.Dynamics.EntropyCounterexample.MapInfinity +OAI.Dynamics.EntropyCounterexample.MapInfinityAttraction +OAI.Dynamics.EntropyCounterexample.MapInputRegularity +OAI.Dynamics.EntropyCounterexample.MapLocalEscape +OAI.Dynamics.EntropyCounterexample.MapMainRegularity +OAI.Dynamics.EntropyCounterexample.MapOrbitAlternatives +OAI.Dynamics.EntropyCounterexample.MapOrbitLift +OAI.Dynamics.EntropyCounterexample.MapPassage +OAI.Dynamics.EntropyCounterexample.MapPassagePhase +OAI.Dynamics.EntropyCounterexample.MapPassageSchedule +OAI.Dynamics.EntropyCounterexample.MapPrediction +OAI.Dynamics.EntropyCounterexample.MapPreparationRadius +OAI.Dynamics.EntropyCounterexample.MapPreparationReset +OAI.Dynamics.EntropyCounterexample.MapQuotientContinuity +OAI.Dynamics.EntropyCounterexample.MapReadout +OAI.Dynamics.EntropyCounterexample.MapRecoveredReadout +OAI.Dynamics.EntropyCounterexample.MapRegisterRegularity +OAI.Dynamics.EntropyCounterexample.MapSignal +OAI.Dynamics.EntropyCounterexample.MapSignals +OAI.Dynamics.EntropyCounterexample.MapTerminalEntropy +OAI.Dynamics.EntropyCounterexample.ModelTransport +OAI.Dynamics.EntropyCounterexample.MonotoneItineraries +OAI.Dynamics.EntropyCounterexample.NormalizedPrediction +OAI.Dynamics.EntropyCounterexample.OrderedIntervalLabels +OAI.Dynamics.EntropyCounterexample.PassagePhase +OAI.Dynamics.EntropyCounterexample.PassagePhaseInterval +OAI.Dynamics.EntropyCounterexample.PeriodicEntropy +OAI.Dynamics.EntropyCounterexample.PhaseAlignment +OAI.Dynamics.EntropyCounterexample.PolarLabels +OAI.Dynamics.EntropyCounterexample.PolarProductEntropy +OAI.Dynamics.EntropyCounterexample.PolynomialSpectralBound +OAI.Dynamics.EntropyCounterexample.PredictionDerivative +OAI.Dynamics.EntropyCounterexample.PredictionInput +OAI.Dynamics.EntropyCounterexample.PredictionModelBridge +OAI.Dynamics.EntropyCounterexample.PredictionSeries +OAI.Dynamics.EntropyCounterexample.PredictionSignal +OAI.Dynamics.EntropyCounterexample.RadialRegisterEntropy +OAI.Dynamics.EntropyCounterexample.RawBaseGoodCover +OAI.Dynamics.EntropyCounterexample.RawInvariantInfinity +OAI.Dynamics.EntropyCounterexample.RawInvariantSets +OAI.Dynamics.EntropyCounterexample.RawSpectrumFactor +OAI.Dynamics.EntropyCounterexample.ReadoutCover +OAI.Dynamics.EntropyCounterexample.ReadoutLocalExtension +OAI.Dynamics.EntropyCounterexample.RealizedConstruction +OAI.Dynamics.EntropyCounterexample.RealizedRegisterRegularity +OAI.Dynamics.EntropyCounterexample.RegisterEmbedded +OAI.Dynamics.EntropyCounterexample.RegisterEntropyCoding +OAI.Dynamics.EntropyCounterexample.RegisterErasure +OAI.Dynamics.EntropyCounterexample.RegisterLinearity +OAI.Dynamics.EntropyCounterexample.RegisterReset +OAI.Dynamics.EntropyCounterexample.Saturation +OAI.Dynamics.EntropyCounterexample.SaturationEntropy +OAI.Dynamics.EntropyCounterexample.SkewProduct +OAI.Dynamics.EntropyCounterexample.SmallCoverNaturality +OAI.Dynamics.EntropyCounterexample.SparseVisits +OAI.Dynamics.EntropyCounterexample.SpectralRadius +OAI.Dynamics.EntropyCounterexample.SphereAngularInput +OAI.Dynamics.EntropyCounterexample.SphereChartLimits +OAI.Dynamics.EntropyCounterexample.SphereCharts +OAI.Dynamics.EntropyCounterexample.SphereCompactSupport +OAI.Dynamics.EntropyCounterexample.SphereCoverGeometry +OAI.Dynamics.EntropyCounterexample.SphereCutoffTransport +OAI.Dynamics.EntropyCounterexample.SphereCutoffs +OAI.Dynamics.EntropyCounterexample.SphereCutoffsAffine +OAI.Dynamics.EntropyCounterexample.SphereDoubling +OAI.Dynamics.EntropyCounterexample.SphereDoublingCharts +OAI.Dynamics.EntropyCounterexample.SphereInfinityChart +OAI.Dynamics.EntropyCounterexample.SphereMainUpdate +OAI.Dynamics.EntropyCounterexample.SphereMainUpdateTransport +OAI.Dynamics.EntropyCounterexample.SphereOverlapDoubling +OAI.Dynamics.EntropyCounterexample.SpherePerturbation +OAI.Dynamics.EntropyCounterexample.SphereSquareEquator +OAI.Dynamics.EntropyCounterexample.SphereTranslation +OAI.Dynamics.EntropyCounterexample.StandardRegisterUpdate +OAI.Dynamics.EntropyCounterexample.StandardSaturation +OAI.Dynamics.EntropyCounterexample.TopologicalAttraction +OAI.Geometry.SingularHomology.ActualSingularSubdivision +OAI.Geometry.SingularHomology.ActualSingularSubdivisionMap +OAI.Geometry.SingularHomology.AffineSimplexCone +OAI.Geometry.SingularHomology.AffineSimplexGeometry +OAI.Geometry.SingularHomology.AffineSingularRealization +OAI.Geometry.SingularHomology.BarycentricSubdivision +OAI.Geometry.SingularHomology.CircleHomologySupport +OAI.Geometry.SingularHomology.FiniteCoverHomology +OAI.Geometry.SingularHomology.FiniteCoverHomologyRawBase +OAI.Geometry.SingularHomology.FiniteGoodCoverHomology +OAI.Geometry.SingularHomology.FiniteSimplicialHomology +OAI.Geometry.SingularHomology.HomologyConjugacy +OAI.Geometry.SingularHomology.HomologyConstant +OAI.Geometry.SingularHomology.HomologyCycle +OAI.Geometry.SingularHomology.HomologyEmpty +OAI.Geometry.SingularHomology.HomologyEvaluation +OAI.Geometry.SingularHomology.HomologyHomotopyEquiv +OAI.Geometry.SingularHomology.HomologyNaturality +OAI.Geometry.SingularHomology.HomologySpectrumFactor +OAI.Geometry.SingularHomology.HomologyTransfer +OAI.Geometry.SingularHomology.HomologyZero +OAI.Geometry.SingularHomology.IteratedSubdivision +OAI.Geometry.SingularHomology.IteratedSubdivisionMesh +OAI.Geometry.SingularHomology.MapHomology +OAI.Geometry.SingularHomology.MapRealizedHomology +OAI.Geometry.SingularHomology.RecursiveSubdivisionMesh +OAI.Geometry.SingularHomology.SimplexCoordinates +OAI.Geometry.SingularHomology.SimplexSingularCompatibility +OAI.Geometry.SingularHomology.SimplexSingularRealization +OAI.Geometry.SingularHomology.SimplexSubdivisionMesh +OAI.Geometry.SingularHomology.SimplexSubtypeMesh +OAI.Geometry.SingularHomology.SimplicialMayerVietoris +OAI.Geometry.SingularHomology.SingularAcyclicModels +OAI.Geometry.SingularHomology.SingularChainsFinsupp +OAI.Geometry.SingularHomology.SingularChainsFinsuppBoundary +OAI.Geometry.SingularHomology.SingularCoverChains +OAI.Geometry.SingularHomology.SingularCoverNaturality +OAI.Geometry.SingularHomology.SingularRealizedSmallness +OAI.Geometry.SingularHomology.SingularSimplexCircleLift +OAI.Geometry.SingularHomology.SingularSimplexLebesgue +OAI.Geometry.SingularHomology.SingularSmallChainSupport +OAI.Geometry.SingularHomology.SingularSmallChains +OAI.Geometry.SingularHomology.SingularSmallComparison +OAI.Geometry.SingularHomology.SingularSmallNaturality +OAI.Geometry.SingularHomology.SingularSubdivision +OAI.Geometry.SingularHomology.SingularSubdivisionEventuallySmall +OAI.Geometry.SingularHomology.SingularSubdivisionIterateRealization +OAI.Geometry.SingularHomology.SingularSubdivisionSmallness +OAI.Geometry.SingularHomology.SingularSupportNaturality +OAI.Geometry.SingularHomology.SingularUniversalChainMap +OAI.Geometry.SingularHomology.SingularUniversalFinsupp +OAI.Geometry.SingularHomology.SingularUniversalOperator +OAI.Geometry.SingularHomology.SkewProductHomology +OAI.Geometry.SingularHomology.SmallCoverMayerVietoris +OAI.Geometry.SingularHomology.SphereMayerVietorisEigen +OAI.Geometry.SingularHomology.SphereSquareHomologyTransport +OAI.Geometry.SingularHomology.SubdivisionQuasiIso +OAI.Geometry.SingularHomology.SubdivisionSubtypeMesh +OAI.Geometry.SingularHomology.SubdivisionSupportMesh diff --git a/tasks/c1-entropy-counterexample/solution/reference.py b/tasks/c1-entropy-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/c1-entropy-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/c1-entropy-counterexample/solution/solve.sh b/tasks/c1-entropy-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4fb18c68be46a3d1f828291e88fcde378c1beba --- /dev/null +++ b/tasks/c1-entropy-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of C1EntropyCounterexample, i.e. module OAI.Dynamics.EntropyCounterexample.Counterexample and the +# 201 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.EntropyCounterexample.Counterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of C1EntropyCounterexample" diff --git a/tasks/c1-entropy-counterexample/task.toml b/tasks/c1-entropy-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b50d62a404749df1114a62a0a65a9c2131195743 --- /dev/null +++ b/tasks/c1-entropy-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/c1-entropy-counterexample" +version = "1.0.0" +description = "Prove C1EntropyCounterexample (openai/math family 151: A $C^1$ counterexample to Shub’s entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/C1EntropyCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "C1EntropyCounterexample" +family = "151" +family_title = "A $C^1$ counterexample to Shub’s entropy conjecture" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.Problem340.exists_C1_entropy_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.EntropyCounterexample.Counterexample" +reference_modules = 201 +reference_lean_bytes = 965060 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1331 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12568 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/c1-entropy-counterexample/tests/Challenge.lean b/tasks/c1-entropy-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ae2bdc4655c96b0cf5bee6b9cbe866f27cf75c7 --- /dev/null +++ b/tasks/c1-entropy-counterexample/tests/Challenge.lean @@ -0,0 +1,73 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open CategoryTheory + +namespace Problem340 + +abbrev ClockAmbient := EuclideanSpace ℝ (Fin 2) + +abbrev SphereAmbient := EuclideanSpace ℝ (Fin 3) + +abbrev StandardClock := Metric.sphere (0 : ClockAmbient) (1 : ℝ) + +abbrev StandardSphere2 := Metric.sphere (0 : SphereAmbient) (1 : ℝ) + +abbrev CounterexampleManifold (q : ℕ) := + StandardClock × (Fin (q + 1) → StandardSphere2) + +abbrev CounterexampleAmbient (q : ℕ) := + ClockAmbient × (Fin (q + 1) → SphereAmbient) + +def standardEmbedding (q : ℕ) : + CounterexampleManifold q → CounterexampleAmbient q := + fun x => (x.1.1, fun i => (x.2 i).1) + +def IsC1SelfMap (q : ℕ) (f : CounterexampleManifold q → CounterexampleManifold q) : Prop := + Continuous f ∧ + ∀ x : CounterexampleManifold q, + ∃ U : Set (CounterexampleAmbient q), + IsOpen U ∧ standardEmbedding q x ∈ U ∧ + ∃ F : CounterexampleAmbient q → CounterexampleAmbient q, + ContDiffOn ℝ 1 F U ∧ + ∀ y : CounterexampleManifold q, + standardEmbedding q y ∈ U → + standardEmbedding q (f y) = F (standardEmbedding q y) + +def continuousMapOf {X Y : Type} [TopologicalSpace X] [TopologicalSpace Y] + (f : X → Y) (hf : Continuous f) : ContinuousMap X Y := + ⟨f, hf⟩ + +abbrev RealSingularHomology (n : ℕ) (X : Type) [TopologicalSpace X] := + (((AlgebraicTopology.singularHomologyFunctor (ModuleCat ℝ) n).obj + (ModuleCat.of ℝ ℝ)).obj (TopCat.of X)) + +def realHomologyMap {X Y : Type} [TopologicalSpace X] [TopologicalSpace Y] + (n : ℕ) (f : X → Y) (hf : Continuous f) : + RealSingularHomology n X →ₗ[ℝ] RealSingularHomology n Y := + (((AlgebraicTopology.singularHomologyFunctor (ModuleCat ℝ) n).obj + (ModuleCat.of ℝ ℝ)).map + (TopCat.ofHom (continuousMapOf f hf))).hom + +def totalRealHomologySpectralRadius {X : Type} [TopologicalSpace X] + (f : X → X) (hf : Continuous f) : ℝ := + sSup {r : ℝ | + ∃ n : ℕ, ∃ a b : ℝ, + ∃ u v : RealSingularHomology n X, + (u ≠ 0 ∨ v ≠ 0) ∧ + realHomologyMap n f hf u = a • u - b • v ∧ + realHomologyMap n f hf v = b • u + a • v ∧ + r = Real.sqrt (a ^ 2 + b ^ 2)} + +theorem exists_C1_entropy_counterexample : + ∃ q : ℕ, 0 < q ∧ ∃ f : CounterexampleManifold q → CounterexampleManifold q, ∃ hf : IsC1SelfMap q f, Dynamics.coverEntropy f (Set.univ : Set (CounterexampleManifold q)) = (0 : EReal) ∧ (∃ v : RealSingularHomology 2 (CounterexampleManifold q), v ≠ 0 ∧ realHomologyMap 2 f hf.1 v = (2 : ℝ) • v) ∧ 0 < Real.log (2 : ℝ) ∧ Real.log (2 : ℝ) ≤ Real.log (totalRealHomologySpectralRadius f hf.1) ∧ ¬ Function.Bijective f ∧ 5 ≤ 2 * q + 3 := by + sorry + +end Problem340 + +end + +end OAI diff --git a/tasks/c1-entropy-counterexample/tests/grade.py b/tasks/c1-entropy-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/c1-entropy-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/c1-entropy-counterexample/tests/task.json b/tasks/c1-entropy-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..705d56a745c4d524c7086eae453425e9d545de41 --- /dev/null +++ b/tasks/c1-entropy-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "C1EntropyCounterexample", + "comparator": { + "theorem_names": [ + "OAI.Problem340.exists_C1_entropy_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11668 +} \ No newline at end of file diff --git a/tasks/c1-entropy-counterexample/tests/test.sh b/tasks/c1-entropy-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/c1-entropy-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cannon-geometric-action/environment/Dockerfile b/tasks/cannon-geometric-action/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cannon-geometric-action/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cannon-geometric-action/environment/fetch_mathlib.sh b/tasks/cannon-geometric-action/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cannon-geometric-action/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cannon-geometric-action/environment/lake-manifest.json b/tasks/cannon-geometric-action/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cannon-geometric-action/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cannon-geometric-action/environment/lakefile.lean b/tasks/cannon-geometric-action/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cannon-geometric-action/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cannon-geometric-action/environment/lean_setup.sh b/tasks/cannon-geometric-action/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cannon-geometric-action/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cannon-geometric-action/environment/pack_submission.py b/tasks/cannon-geometric-action/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cannon-geometric-action/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cannon-geometric-action/instruction.md b/tasks/cannon-geometric-action/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee22673870d1279f37f288ce2f89a900720745f0 --- /dev/null +++ b/tasks/cannon-geometric-action/instruction.md @@ -0,0 +1,150 @@ +# openai/math challenge `CannonGeometricAction` (family 246) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 246 of the release, *Cannon's conjecture* +(Group theory). The family as a whole: Every word-hyperbolic group with boundary homeomorphic to $S^2$ admits a proper cocompact isometric action on hyperbolic three-space with finite kernel, proving Cannon's conjecture. Every torsion-free such group is therefore the fundamental group of a closed hyperbolic three-manifold. + +The challenge is `CannonGeometricAction`, also at `/opt/openai-math/challenges/CannonGeometricAction.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace CannonRelease + +universe u + +structure CayleyData (G : Type u) [Group G] where + generators : Finset G + symmetric : ∀ x ∈ generators, x⁻¹ ∈ generators + connected : (SimpleGraph.mulCayley (generators : Set G)).Connected + +def CayleyData.graph {G : Type u} [Group G] (D : CayleyData G) : SimpleGraph G := + SimpleGraph.mulCayley (D.generators : Set G) + +/-- A uniform thinness constant for geodesic triangles in the Cayley graph. -/ +def CayleyData.ThinTriangles {G : Type u} [Group G] (D : CayleyData G) : Prop := + ∃ δ : ℕ, ∀ x y z : G, + ∀ p : D.graph.Walk x y, ∀ q : D.graph.Walk y z, ∀ r : D.graph.Walk z x, + p.length = D.graph.dist x y → q.length = D.graph.dist y z → + r.length = D.graph.dist z x → + ∀ a ∈ p.support, ∃ b ∈ q.support ++ r.support, D.graph.dist a b ≤ δ + +/-- Based geodesic rays, parametrized at integer times. -/ +def BasedRay {G : Type u} [Group G] (D : CayleyData G) := + {r : ℕ → G // r 0 = 1 ∧ ∀ i j, D.graph.dist (r i) (r j) = Nat.dist i j} + +instance {G : Type u} [Group G] [TopologicalSpace G] (D : CayleyData G) : + TopologicalSpace (BasedRay D) := inferInstanceAs (TopologicalSpace {r : ℕ → G // + r 0 = 1 ∧ ∀ i j, D.graph.dist (r i) (r j) = Nat.dist i j}) + +/-- Finite synchronous distance, equivalent to asymptoticity for based rays. -/ +def raySetoid {G : Type u} [Group G] (D : CayleyData G) : Setoid (BasedRay D) where + r r s := ∃ C : ℕ, ∀ n, D.graph.dist (r.val n) (s.val n) ≤ C + iseqv := by + constructor + · intro r + exact ⟨0, fun n => by simp⟩ + · rintro r s ⟨C, hC⟩ + exact ⟨C, fun n => by rw [SimpleGraph.dist_comm]; exact hC n⟩ + · rintro r s t ⟨C, hC⟩ ⟨E, hE⟩ + refine ⟨C + E, fun n => ?_⟩ + exact le_trans ((D.connected (r.val n) (s.val n)).dist_triangle_left (t.val n)) + (Nat.add_le_add (hC n) (hE n)) + +def Boundary {G : Type u} [Group G] (D : CayleyData G) := Quotient (raySetoid D) + +instance {G : Type u} [Group G] [TopologicalSpace G] (D : CayleyData G) : + TopologicalSpace (Boundary D) := + inferInstanceAs (TopologicalSpace (Quotient (raySetoid D))) + +abbrev SphereTwo := {x : EuclideanSpace ℝ (Fin 3) // x ∈ Metric.sphere 0 1} + +/-- The upper-half-space model of hyperbolic three-space. -/ +def HyperbolicThree := {x : Fin 3 → ℝ // 0 < x 2} + +instance : TopologicalSpace HyperbolicThree := + inferInstanceAs (TopologicalSpace {x : Fin 3 → ℝ // 0 < x 2}) + +def hyperbolicDist (x y : HyperbolicThree) : ℝ := + Real.arcosh (1 + (∑ i : Fin 3, (x.val i - y.val i) ^ 2) / (2 * x.val 2 * y.val 2)) + +/-- The full isometry group, including orientation-reversing isometries. -/ +def hyperbolicIsometries : Subgroup (HyperbolicThree ≃ₜ HyperbolicThree) where + carrier := {f | ∀ x y, hyperbolicDist (f x) (f y) = hyperbolicDist x y} + one_mem' := by + change ∀ x y, hyperbolicDist x y = hyperbolicDist x y + intros + rfl + mul_mem' := by + intro f g hf hg x y + exact (hf (g x) (g y)).trans (hg x y) + inv_mem' := by + intro f hf x y + simpa using (hf (f.symm x) (f.symm y)).symm + +abbrev H3Isom := ↥hyperbolicIsometries + +def ProperAction {G : Type u} [Group G] (ρ : G →* H3Isom) : Prop := + ∀ K : Set HyperbolicThree, IsCompact K → + {g : G | ∃ x ∈ K, (ρ g).val x ∈ K}.Finite + +def CocompactAction {G : Type u} [Group G] (ρ : G →* H3Isom) : Prop := + ∃ K : Set HyperbolicThree, IsCompact K ∧ + ∀ x : HyperbolicThree, ∃ g : G, ∃ y ∈ K, (ρ g).val y = x + +theorem cannon (G : Type u) [Group G] [TopologicalSpace G] [DiscreteTopology G] + (D : CayleyData G) (hthin : D.ThinTriangles) + (hsphere : Nonempty (Boundary D ≃ₜ SphereTwo)) : + ∃ ρ : G →* H3Isom, ProperAction ρ ∧ CocompactAction ρ ∧ + (ρ.ker : Set G).Finite := by + sorry + +end CannonRelease +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CannonGeometricAction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CannonRelease.cannon` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cannon-geometric-action/solution/closure.txt b/tasks/cannon-geometric-action/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f4235ac9f5c1f5e9797b8cffb7343d52399ac1e0 --- /dev/null +++ b/tasks/cannon-geometric-action/solution/closure.txt @@ -0,0 +1,299 @@ +OAI.Geometry.Cannon.Actions.BoundaryAction +OAI.Geometry.Cannon.Actions.Height +OAI.Geometry.Cannon.Actions.Proper +OAI.Geometry.Cannon.Actions.Triples +OAI.Geometry.Cannon.Beltrami.Axis +OAI.Geometry.Cannon.Beltrami.Beltrami +OAI.Geometry.Cannon.Beltrami.CauchySymbol +OAI.Geometry.Cannon.Beltrami.ContinuousMemLpRestrict +OAI.Geometry.Cannon.Beltrami.DirichletPullback +OAI.Geometry.Cannon.Beltrami.GlobalMetricWeakMrmt +OAI.Geometry.Cannon.Beltrami.Increment +OAI.Geometry.Cannon.Beltrami.Mollifier +OAI.Geometry.Cannon.Beltrami.MultiplyLp +OAI.Geometry.Cannon.Beltrami.RectCrossing +OAI.Geometry.Cannon.Beltrami.SideOrientation +OAI.Geometry.Cannon.Beltrami.TwoPointNormalize +OAI.Geometry.Cannon.Boundary.BoundaryBasedRay +OAI.Geometry.Cannon.Boundary.BoundaryControlledDiskCover +OAI.Geometry.Cannon.Boundary.BoundaryDist +OAI.Geometry.Cannon.Boundary.BoundaryEventualRelativeShrink +OAI.Geometry.Cannon.Boundary.BoundaryHomeomorph +OAI.Geometry.Cannon.Boundary.BoundaryLocallyConnected +OAI.Geometry.Cannon.Boundary.BoundaryModulusBounded +OAI.Geometry.Cannon.Boundary.BoundaryModulusSubexponential +OAI.Geometry.Cannon.Boundary.BoundaryPackingRelativeTests +OAI.Geometry.Cannon.Boundary.BoundaryPuncturedPathConnected +OAI.Geometry.Cannon.Boundary.BoundaryRecordData +OAI.Geometry.Cannon.Boundary.BoundaryUniformCirclePacking +OAI.Geometry.Cannon.Boundary.BoundaryUniformComplementGraph +OAI.Geometry.Cannon.Boundary.BoundaryUniformConnectedComplement +OAI.Geometry.Cannon.Boundary.BoundaryUniformEmbeddedGraph +OAI.Geometry.Cannon.Boundary.BoundaryUniformRingPacking +OAI.Geometry.Cannon.Boundary.BoundaryUniformTriangularGraphs +OAI.Geometry.Cannon.Boundary.ExpansionGlobalUpper +OAI.Geometry.Cannon.Boundary.GraphPreconnected +OAI.Geometry.Cannon.Boundary.GraphReachableCover +OAI.Geometry.Cannon.Boundary.ImageAwayPuncture +OAI.Geometry.Cannon.Boundary.PolynomialPacking +OAI.Geometry.Cannon.Boundary.Thin +OAI.Geometry.Cannon.Boundary.ThinQuadrilateral +OAI.Geometry.Cannon.Boundary.ThreeMarksTwoMetrics +OAI.Geometry.Cannon.Boundary.UnitCircle +OAI.Geometry.Cannon.Boundary.VisualScale +OAI.Geometry.Cannon.Boundary.VisualSynchronousPrefix +OAI.Geometry.Cannon.Boundary.WordBall +OAI.Geometry.Cannon.CirclePacking.AngleGradient +OAI.Geometry.Cannon.CirclePacking.Cycle +OAI.Geometry.Cannon.CirclePacking.Demand +OAI.Geometry.Cannon.CirclePacking.Det +OAI.Geometry.Cannon.CirclePacking.OpenEuclideanFan +OAI.Geometry.Cannon.CirclePacking.OrientedArea +OAI.Geometry.Cannon.CirclePacking.PetalAngle +OAI.Geometry.Cannon.CirclePacking.Radius +OAI.Geometry.Cannon.CirclePacking.SectorRingData +OAI.Geometry.Cannon.CirclePacking.SplitRadiusRatioTendsto +OAI.Geometry.Cannon.CirclePacking.StrictCutsGiveAngles +OAI.Geometry.Cannon.CirclePacking.TrianglePoint +OAI.Geometry.Cannon.Conformal.AffineRegion +OAI.Geometry.Cannon.Conformal.AnalyticFixInftyAffine +OAI.Geometry.Cannon.Conformal.BoundaryFiniteSphereRealizations +OAI.Geometry.Cannon.Conformal.BoundaryUniformQuasiMobius +OAI.Geometry.Cannon.Conformal.BoundedCrossRatios +OAI.Geometry.Cannon.Conformal.Center +OAI.Geometry.Cannon.Conformal.Chart +OAI.Geometry.Cannon.Conformal.ClosureCoeBall +OAI.Geometry.Cannon.Conformal.CutoffBump +OAI.Geometry.Cannon.Conformal.Distinct +OAI.Geometry.Cannon.Conformal.FiniteB +OAI.Geometry.Cannon.Conformal.FinitePackingVertex +OAI.Geometry.Cannon.Conformal.GeometricConformalAction +OAI.Geometry.Cannon.Conformal.ImageArea +OAI.Geometry.Cannon.Conformal.LinearZ +OAI.Geometry.Cannon.Conformal.MarkedChart +OAI.Geometry.Cannon.Conformal.NormalizePackingCenters +OAI.Geometry.Cannon.Conformal.Normalizer +OAI.Geometry.Cannon.Conformal.OpenMapMaxSphere +OAI.Geometry.Cannon.Conformal.PlaneWeakQSBounded +OAI.Geometry.Cannon.Conformal.PreservesProducts +OAI.Geometry.Cannon.Conformal.QuasiMobius +OAI.Geometry.Cannon.Conformal.RestrictedSphereAction +OAI.Geometry.Cannon.Conformal.Round +OAI.Geometry.Cannon.Conformal.Sphere +OAI.Geometry.Cannon.Conformal.SphereMeasure +OAI.Geometry.Cannon.Conformal.SpherePathConnected +OAI.Geometry.Cannon.Conformal.SpherePuncturedChart +OAI.Geometry.Cannon.Conformal.SphereTile +OAI.Geometry.Cannon.Conformal.SphereTwo +OAI.Geometry.Cannon.Conformal.WeakQSInverseShrink +OAI.Geometry.Cannon.Conformal.WeakQSPartialsLocally +OAI.Geometry.Cannon.Energy.AffineRangeBounded +OAI.Geometry.Cannon.Energy.ApproxSelfSimilar +OAI.Geometry.Cannon.Energy.ChartSquareInterior +OAI.Geometry.Cannon.Energy.ClopenNeighborhoodComponent +OAI.Geometry.Cannon.Energy.DomainImage +OAI.Geometry.Cannon.Energy.Extend +OAI.Geometry.Cannon.Energy.GeometricLimitMeasureHolder +OAI.Geometry.Cannon.Energy.GeometricRecordAnnuli +OAI.Geometry.Cannon.Energy.Interior +OAI.Geometry.Cannon.Energy.LiftPath +OAI.Geometry.Cannon.Energy.MeshEnergy +OAI.Geometry.Cannon.Energy.MeshEnergySumFilter +OAI.Geometry.Cannon.Energy.MeshTransportBound +OAI.Geometry.Cannon.Energy.NormalizedModulus +OAI.Geometry.Cannon.Energy.OpenPreconnectedRemovePoint +OAI.Geometry.Cannon.Energy.PathCosts +OAI.Geometry.Cannon.Energy.Plane +OAI.Geometry.Cannon.Energy.PuncturedBallConnected +OAI.Geometry.Cannon.Energy.RawFunction +OAI.Geometry.Cannon.Energy.RecordData +OAI.Geometry.Cannon.Energy.Square +OAI.Geometry.Cannon.Energy.SquareMap +OAI.Geometry.Cannon.Energy.SquareMapRange +OAI.Geometry.Cannon.Energy.StopInside +OAI.Geometry.Cannon.Energy.StripCrossing +OAI.Geometry.Cannon.Flows.BoundaryRecordFlow +OAI.Geometry.Cannon.Flows.CenterNeighborhood +OAI.Geometry.Cannon.Flows.ContinuousDomain +OAI.Geometry.Cannon.Flows.Domain +OAI.Geometry.Cannon.Flows.DyadicBin +OAI.Geometry.Cannon.Flows.EscapingLevelEnergyObstruction +OAI.Geometry.Cannon.Flows.FarDiam +OAI.Geometry.Cannon.Flows.FlowPaid +OAI.Geometry.Cannon.Flows.FlowPatternSetup +OAI.Geometry.Cannon.Flows.FlowPuncture +OAI.Geometry.Cannon.Flows.FlowSetup +OAI.Geometry.Cannon.Flows.GoodCandidates +OAI.Geometry.Cannon.Flows.IntervalAvoidingShortRange +OAI.Geometry.Cannon.Flows.Lower +OAI.Geometry.Cannon.Flows.NearProbabilityBound +OAI.Geometry.Cannon.Flows.NoVanishingLocalMesh +OAI.Geometry.Cannon.Flows.Node +OAI.Geometry.Cannon.Flows.NormalizedComparison +OAI.Geometry.Cannon.Flows.Oscillation +OAI.Geometry.Cannon.Flows.OscillationMonoRange +OAI.Geometry.Cannon.Flows.State +OAI.Geometry.Cannon.Flows.Subdivision +OAI.Geometry.Cannon.Flows.WeightedOscillation +OAI.Geometry.Cannon.Main +OAI.Geometry.Cannon.Model +OAI.Geometry.Cannon.Modulus.Ambient +OAI.Geometry.Cannon.Modulus.AnnularCutoffEnergy +OAI.Geometry.Cannon.Modulus.AnnularCutoffEnergy2 +OAI.Geometry.Cannon.Modulus.AnnularNet +OAI.Geometry.Cannon.Modulus.AnnularPatternDistance +OAI.Geometry.Cannon.Modulus.BinNearCard +OAI.Geometry.Cannon.Modulus.BoundaryNormalizedAnnularCarriers +OAI.Geometry.Cannon.Modulus.CarrierHomeomorph +OAI.Geometry.Cannon.Modulus.Clip +OAI.Geometry.Cannon.Modulus.ClippedRadialEnergy +OAI.Geometry.Cannon.Modulus.ClosedAnnulus +OAI.Geometry.Cannon.Modulus.ClosedCoverReflTrans +OAI.Geometry.Cannon.Modulus.CompleteSquare +OAI.Geometry.Cannon.Modulus.Cost +OAI.Geometry.Cannon.Modulus.GeometricAnnularCompactTails +OAI.Geometry.Cannon.Modulus.IndicesPreimageImage +OAI.Geometry.Cannon.Modulus.LocalSubdisk +OAI.Geometry.Cannon.Modulus.ModulusEnergy +OAI.Geometry.Cannon.Modulus.ModulusFamilyMono +OAI.Geometry.Cannon.Modulus.ModulusSerialBound +OAI.Geometry.Cannon.Modulus.PathCellIndices +OAI.Geometry.Cannon.Modulus.PositiveCapacityTransitions +OAI.Geometry.Cannon.Modulus.PreimageCarrierPostcompose +OAI.Geometry.Cannon.Modulus.Quad +OAI.Geometry.Cannon.Modulus.RadialCellEnergy +OAI.Geometry.Cannon.Modulus.ScalarAnnularConstant +OAI.Geometry.Cannon.Modulus.SqDiffNormDiff +OAI.Geometry.Cannon.Modulus.TangentDiskMeet +OAI.Geometry.Cannon.Modulus.TracePreconnected +OAI.Geometry.Cannon.Modulus.UniformOriginalChargingCounts +OAI.Geometry.Cannon.Modulus.Weights +OAI.Geometry.Cannon.PlanarGraphs.ChartLabel +OAI.Geometry.Cannon.PlanarGraphs.ClosureRegionInside +OAI.Geometry.Cannon.PlanarGraphs.ComponentRegion +OAI.Geometry.Cannon.PlanarGraphs.ConnectedPlanarBounds +OAI.Geometry.Cannon.PlanarGraphs.CutOrder +OAI.Geometry.Cannon.PlanarGraphs.EdgeGraph +OAI.Geometry.Cannon.PlanarGraphs.EdgesConfinedCore +OAI.Geometry.Cannon.PlanarGraphs.FiniteClosedLocal +OAI.Geometry.Cannon.PlanarGraphs.FlatChartBoundaryPatch +OAI.Geometry.Cannon.PlanarGraphs.GraphShear +OAI.Geometry.Cannon.PlanarGraphs.HomeomorphComponents +OAI.Geometry.Cannon.PlanarGraphs.IncidentSubsetPatch +OAI.Geometry.Cannon.PlanarGraphs.InteriorUnion +OAI.Geometry.Cannon.PlanarGraphs.NetJoined +OAI.Geometry.Cannon.PlanarGraphs.Next +OAI.Geometry.Cannon.PlanarGraphs.PlanarBounds +OAI.Geometry.Cannon.PlanarGraphs.Plane +OAI.Geometry.Cannon.PlanarGraphs.PositiveHalfAxis +OAI.Geometry.Cannon.PlanarGraphs.RadialIncidenceLength +OAI.Geometry.Cannon.PlanarGraphs.Region +OAI.Geometry.Cannon.PlanarGraphs.RegionBoundaryHitsOpen +OAI.Geometry.Cannon.PlanarGraphs.Steps +OAI.Geometry.Cannon.PlanarGraphs.Support +OAI.Geometry.Cannon.PlanarGraphs.TraceCard +OAI.Geometry.Cannon.PlanarGraphs.TriangularCounts +OAI.Geometry.Cannon.PlaneTopology.Arc +OAI.Geometry.Cannon.PlaneTopology.BoundaryBallCover +OAI.Geometry.Cannon.PlaneTopology.BoundaryControlledEmbeddedArcs +OAI.Geometry.Cannon.PlaneTopology.BoundaryRadiusControl +OAI.Geometry.Cannon.PlaneTopology.ChartTameFaceCount +OAI.Geometry.Cannon.PlaneTopology.ClosedInside +OAI.Geometry.Cannon.PlaneTopology.ClosedInsideSegment +OAI.Geometry.Cannon.PlaneTopology.CompactifiedFace +OAI.Geometry.Cannon.PlaneTopology.Consecutive +OAI.Geometry.Cannon.PlaneTopology.ControlledDiskCover +OAI.Geometry.Cannon.PlaneTopology.CrosscutIncidenceLocal +OAI.Geometry.Cannon.PlaneTopology.Crossing +OAI.Geometry.Cannon.PlaneTopology.DevelopedFaces +OAI.Geometry.Cannon.PlaneTopology.DualGraph +OAI.Geometry.Cannon.PlaneTopology.DualGraphGaugeGraph +OAI.Geometry.Cannon.PlaneTopology.FaceClosuresCover +OAI.Geometry.Cannon.PlaneTopology.FaceHull +OAI.Geometry.Cannon.PlaneTopology.FaceHullCompact +OAI.Geometry.Cannon.PlaneTopology.FaceVerticesCard +OAI.Geometry.Cannon.PlaneTopology.FaceVerticesCardThree +OAI.Geometry.Cannon.PlaneTopology.FacewiseCompactSurjectiveRealization +OAI.Geometry.Cannon.PlaneTopology.FacialStar +OAI.Geometry.Cannon.PlaneTopology.FiniteSupport +OAI.Geometry.Cannon.PlaneTopology.FiniteVertexSet +OAI.Geometry.Cannon.PlaneTopology.FreeArcDeleteConnected +OAI.Geometry.Cannon.PlaneTopology.GraphEdgeValueCompatible +OAI.Geometry.Cannon.PlaneTopology.GraphVerticesDenseOriginal +OAI.Geometry.Cannon.PlaneTopology.HalfParam +OAI.Geometry.Cannon.PlaneTopology.Hat +OAI.Geometry.Cannon.PlaneTopology.HomeoPlane +OAI.Geometry.Cannon.PlaneTopology.IncidentEdges +OAI.Geometry.Cannon.PlaneTopology.IncidentFaces +OAI.Geometry.Cannon.PlaneTopology.InnerFlux +OAI.Geometry.Cannon.PlaneTopology.InteriorBallCover +OAI.Geometry.Cannon.PlaneTopology.InteriorRadiusControl +OAI.Geometry.Cannon.PlaneTopology.IntersectionCountEmbedding +OAI.Geometry.Cannon.PlaneTopology.IntrinsicCircleData +OAI.Geometry.Cannon.PlaneTopology.Lift +OAI.Geometry.Cannon.PlaneTopology.MetricStarFlat +OAI.Geometry.Cannon.PlaneTopology.NetArcGraphSet +OAI.Geometry.Cannon.PlaneTopology.NoSingleFaceDiscordance +OAI.Geometry.Cannon.PlaneTopology.NoncutCycleFreeRegion +OAI.Geometry.Cannon.PlaneTopology.NoncutEdgeTwoFaces +OAI.Geometry.Cannon.PlaneTopology.OtherComponentDeleteArc +OAI.Geometry.Cannon.PlaneTopology.PackingNormalizedTileBudget +OAI.Geometry.Cannon.PlaneTopology.PairComponentClosure +OAI.Geometry.Cannon.PlaneTopology.Plane +OAI.Geometry.Cannon.PlaneTopology.Portion +OAI.Geometry.Cannon.PlaneTopology.PullChartUnionCompl +OAI.Geometry.Cannon.PlaneTopology.RadialStable +OAI.Geometry.Cannon.PlaneTopology.RealizationVertex +OAI.Geometry.Cannon.PlaneTopology.RegionEdges +OAI.Geometry.Cannon.PlaneTopology.RetainedFacesSurplus +OAI.Geometry.Cannon.PlaneTopology.Reverse +OAI.Geometry.Cannon.PlaneTopology.SelectedFaceChargingCounts +OAI.Geometry.Cannon.PlaneTopology.SeparatedArcColoring +OAI.Geometry.Cannon.PlaneTopology.Spans +OAI.Geometry.Cannon.PlaneTopology.SquareSide +OAI.Geometry.Cannon.PlaneTopology.Straight +OAI.Geometry.Cannon.PlaneTopology.TameEdgeIncidenceLocal +OAI.Geometry.Cannon.PlaneTopology.TameEdgeIncidenceOpen +OAI.Geometry.Cannon.PlaneTopology.TameGraphFlatChart +OAI.Geometry.Cannon.PlaneTopology.TameInitialInterval +OAI.Geometry.Cannon.PlaneTopology.TamePairJordanRegions +OAI.Geometry.Cannon.PlaneTopology.VertexLines +OAI.Geometry.Cannon.PlaneTopology.VertexLinkOrder +OAI.Geometry.Cannon.PlaneTopology.VertexNearCard +OAI.Geometry.Cannon.ScalarLimits.BoundaryRecordScalarLimit +OAI.Geometry.Cannon.ScalarLimits.CompactVariationRegion +OAI.Geometry.Cannon.ScalarLimits.ConnectedLimit +OAI.Geometry.Cannon.ScalarLimits.Dirac +OAI.Geometry.Cannon.ScalarLimits.EscapingLevelsAlong +OAI.Geometry.Cannon.ScalarLimits.Exhaustion +OAI.Geometry.Cannon.ScalarLimits.InteriorScalar +OAI.Geometry.Cannon.ScalarLimits.IntervalAvoiding +OAI.Geometry.Cannon.ScalarLimits.LaterRecord +OAI.Geometry.Cannon.ScalarLimits.LocalOscillation +OAI.Geometry.Cannon.ScalarLimits.NormalizedLevelsEscape +OAI.Geometry.Cannon.ScalarLimits.OrderedVariationPath +OAI.Geometry.Cannon.ScalarLimits.Osc +OAI.Geometry.Cannon.ScalarLimits.OscillationPairwise +OAI.Geometry.Cannon.ScalarLimits.ReciprocalPowLog +OAI.Geometry.Cannon.ScalarLimits.TransformedScalarEnergyConstant +OAI.Geometry.Cannon.ScalarLimits.UniformlyImage +OAI.Geometry.Cannon.ScalarLimits.Words +OAI.Geometry.Cannon.Topology.CenteredHomeomorph +OAI.Geometry.Cannon.Topology.ComponentRegionConnected +OAI.Geometry.Cannon.Topology.EquicontinuousCompactBound +OAI.Geometry.Cannon.Topology.ExteriorConnected +OAI.Geometry.Cannon.Topology.Glue +OAI.Geometry.Cannon.Topology.LabelsConstant +OAI.Geometry.Cannon.Topology.NoTripleClosedBalls +OAI.Geometry.Cannon.Topology.Plane +OAI.Geometry.Cannon.Topology.PlaneBox +OAI.Geometry.Cannon.Topology.Retraction +OAI.Geometry.Cannon.Topology.ThreeMarksAvoidTwo +OAI.Geometry.Cannon.Topology.ThreeSeparation +OAI.Geometry.Cannon.Uniformization.AnnulusFamily +OAI.Geometry.Cannon.Uniformization.BoundaryUniformizationInputs +OAI.Geometry.Cannon.Uniformization.EventualRelativeShrink +OAI.Geometry.Cannon.Uniformization.LayerFamily +OAI.Geometry.Cannon.Uniformization.LocalCompactSurjection +OAI.Geometry.Cannon.Uniformization.ProductFactorSmall +OAI.Geometry.Cannon.Uniformization.SurjectiveRealizationHomeomorphLimit diff --git a/tasks/cannon-geometric-action/solution/reference.py b/tasks/cannon-geometric-action/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cannon-geometric-action/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cannon-geometric-action/solution/solve.sh b/tasks/cannon-geometric-action/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0e8957e97ed8bb7bac26539e65ff31ea1abff3d1 --- /dev/null +++ b/tasks/cannon-geometric-action/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CannonGeometricAction, i.e. module OAI.Geometry.Cannon.Main and the +# 299 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.Cannon.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CannonGeometricAction" diff --git a/tasks/cannon-geometric-action/task.toml b/tasks/cannon-geometric-action/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..67648708a62c08c8809643fab190c70caf9fe844 --- /dev/null +++ b/tasks/cannon-geometric-action/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cannon-geometric-action" +version = "1.0.0" +description = "Prove CannonGeometricAction (openai/math family 246: Cannon's conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CannonGeometricAction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CannonGeometricAction" +family = "246" +family_title = "Cannon's conjecture" +subject = "Group theory" +theorems = ["OAI.CannonRelease.cannon"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.Cannon.Main" +reference_modules = 299 +reference_lean_bytes = 2904193 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 970 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14313 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cannon-geometric-action/tests/Challenge.lean b/tasks/cannon-geometric-action/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4ede8c0a47dadbee68a946392420d572e4b04a21 --- /dev/null +++ b/tasks/cannon-geometric-action/tests/Challenge.lean @@ -0,0 +1,99 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace CannonRelease + +universe u + +structure CayleyData (G : Type u) [Group G] where + generators : Finset G + symmetric : ∀ x ∈ generators, x⁻¹ ∈ generators + connected : (SimpleGraph.mulCayley (generators : Set G)).Connected + +def CayleyData.graph {G : Type u} [Group G] (D : CayleyData G) : SimpleGraph G := + SimpleGraph.mulCayley (D.generators : Set G) + +/-- A uniform thinness constant for geodesic triangles in the Cayley graph. -/ +def CayleyData.ThinTriangles {G : Type u} [Group G] (D : CayleyData G) : Prop := + ∃ δ : ℕ, ∀ x y z : G, + ∀ p : D.graph.Walk x y, ∀ q : D.graph.Walk y z, ∀ r : D.graph.Walk z x, + p.length = D.graph.dist x y → q.length = D.graph.dist y z → + r.length = D.graph.dist z x → + ∀ a ∈ p.support, ∃ b ∈ q.support ++ r.support, D.graph.dist a b ≤ δ + +/-- Based geodesic rays, parametrized at integer times. -/ +def BasedRay {G : Type u} [Group G] (D : CayleyData G) := + {r : ℕ → G // r 0 = 1 ∧ ∀ i j, D.graph.dist (r i) (r j) = Nat.dist i j} + +instance {G : Type u} [Group G] [TopologicalSpace G] (D : CayleyData G) : + TopologicalSpace (BasedRay D) := inferInstanceAs (TopologicalSpace {r : ℕ → G // + r 0 = 1 ∧ ∀ i j, D.graph.dist (r i) (r j) = Nat.dist i j}) + +/-- Finite synchronous distance, equivalent to asymptoticity for based rays. -/ +def raySetoid {G : Type u} [Group G] (D : CayleyData G) : Setoid (BasedRay D) where + r r s := ∃ C : ℕ, ∀ n, D.graph.dist (r.val n) (s.val n) ≤ C + iseqv := by + constructor + · intro r + exact ⟨0, fun n => by simp⟩ + · rintro r s ⟨C, hC⟩ + exact ⟨C, fun n => by rw [SimpleGraph.dist_comm]; exact hC n⟩ + · rintro r s t ⟨C, hC⟩ ⟨E, hE⟩ + refine ⟨C + E, fun n => ?_⟩ + exact le_trans ((D.connected (r.val n) (s.val n)).dist_triangle_left (t.val n)) + (Nat.add_le_add (hC n) (hE n)) + +def Boundary {G : Type u} [Group G] (D : CayleyData G) := Quotient (raySetoid D) + +instance {G : Type u} [Group G] [TopologicalSpace G] (D : CayleyData G) : + TopologicalSpace (Boundary D) := + inferInstanceAs (TopologicalSpace (Quotient (raySetoid D))) + +abbrev SphereTwo := {x : EuclideanSpace ℝ (Fin 3) // x ∈ Metric.sphere 0 1} + +/-- The upper-half-space model of hyperbolic three-space. -/ +def HyperbolicThree := {x : Fin 3 → ℝ // 0 < x 2} + +instance : TopologicalSpace HyperbolicThree := + inferInstanceAs (TopologicalSpace {x : Fin 3 → ℝ // 0 < x 2}) + +def hyperbolicDist (x y : HyperbolicThree) : ℝ := + Real.arcosh (1 + (∑ i : Fin 3, (x.val i - y.val i) ^ 2) / (2 * x.val 2 * y.val 2)) + +/-- The full isometry group, including orientation-reversing isometries. -/ +def hyperbolicIsometries : Subgroup (HyperbolicThree ≃ₜ HyperbolicThree) where + carrier := {f | ∀ x y, hyperbolicDist (f x) (f y) = hyperbolicDist x y} + one_mem' := by + change ∀ x y, hyperbolicDist x y = hyperbolicDist x y + intros + rfl + mul_mem' := by + intro f g hf hg x y + exact (hf (g x) (g y)).trans (hg x y) + inv_mem' := by + intro f hf x y + simpa using (hf (f.symm x) (f.symm y)).symm + +abbrev H3Isom := ↥hyperbolicIsometries + +def ProperAction {G : Type u} [Group G] (ρ : G →* H3Isom) : Prop := + ∀ K : Set HyperbolicThree, IsCompact K → + {g : G | ∃ x ∈ K, (ρ g).val x ∈ K}.Finite + +def CocompactAction {G : Type u} [Group G] (ρ : G →* H3Isom) : Prop := + ∃ K : Set HyperbolicThree, IsCompact K ∧ + ∀ x : HyperbolicThree, ∃ g : G, ∃ y ∈ K, (ρ g).val y = x + +theorem cannon (G : Type u) [Group G] [TopologicalSpace G] [DiscreteTopology G] + (D : CayleyData G) (hthin : D.ThinTriangles) + (hsphere : Nonempty (Boundary D ≃ₜ SphereTwo)) : + ∃ ρ : G →* H3Isom, ProperAction ρ ∧ CocompactAction ρ ∧ + (ρ.ker : Set G).Finite := by + sorry + +end CannonRelease +end + +end OAI diff --git a/tasks/cannon-geometric-action/tests/grade.py b/tasks/cannon-geometric-action/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cannon-geometric-action/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cannon-geometric-action/tests/task.json b/tasks/cannon-geometric-action/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f21f223cebb4731f5728354ac27b61330f8d9d24 --- /dev/null +++ b/tasks/cannon-geometric-action/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CannonGeometricAction", + "comparator": { + "theorem_names": [ + "OAI.CannonRelease.cannon" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13413 +} \ No newline at end of file diff --git a/tasks/cannon-geometric-action/tests/test.sh b/tasks/cannon-geometric-action/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cannon-geometric-action/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cayley-percolation/environment/Dockerfile b/tasks/cayley-percolation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cayley-percolation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cayley-percolation/environment/fetch_mathlib.sh b/tasks/cayley-percolation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cayley-percolation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cayley-percolation/environment/lake-manifest.json b/tasks/cayley-percolation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cayley-percolation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cayley-percolation/environment/lakefile.lean b/tasks/cayley-percolation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cayley-percolation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cayley-percolation/environment/lean_setup.sh b/tasks/cayley-percolation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cayley-percolation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cayley-percolation/environment/pack_submission.py b/tasks/cayley-percolation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cayley-percolation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cayley-percolation/instruction.md b/tasks/cayley-percolation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09e3a703161051a30717cc1afc09dd741685e2ca --- /dev/null +++ b/tasks/cayley-percolation/instruction.md @@ -0,0 +1,135 @@ +# openai/math challenge `CayleyPercolation` (family 214) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 214 of the release, *The Benjamini–Schramm nonuniqueness conjecture* +(Probability and statistical mechanics). The family as a whole: Proves $p_c ∃ e ∈ ω, G e = s(a, b)) x y + +def cluster (G : BondGraph V E) (ω : Set E) (x : V) : Set V := + {y | Conn G ω x y} + +def infiniteClusters (G : BondGraph V E) (ω : Set E) : Set (Set V) := + {C | C.Infinite ∧ ∃ x, C = cluster G ω x} + +noncomputable def law (p : unitInterval) : Measure (Set E) := + setBernoulli Set.univ p + +noncomputable def pc (G : BondGraph V E) : unitInterval := + sInf {p | 0 < law p {ω | (infiniteClusters G ω).Nonempty}} + +noncomputable def pu (G : BondGraph V E) : unitInterval := + sInf {p | law p {ω | ∃! C, C ∈ infiniteClusters G ω} = 1} + +noncomputable def twoPoint (G : BondGraph V E) (p : unitInterval) (x y : V) : ℝ := + (law p {ω | Conn G ω x y}).toReal + +noncomputable abbrev Hilbert (V : Type u) := lp (fun _ : V => ℂ) 2 + +noncomputable def HasKernel [DecidableEq V] + (G : BondGraph V E) (p : unitInterval) + (A : Hilbert V →L[ℂ] Hilbert V) : Prop := + ∀ x y, (A (lp.single 2 y (1 : ℂ))) x = (twoPoint G p x y : ℂ) + +noncomputable def OperatorBounded (G : BondGraph V E) (p : unitInterval) : Prop := by + classical + exact ∃ A : Hilbert V →L[ℂ] Hilbert V, HasKernel G p A + +noncomputable def ptwo (G : BondGraph V E) : unitInterval := + sSup {p | OperatorBounded G p} + +noncomputable def labelLaw : Measure (E → unitInterval) := + Measure.infinitePi (fun _ => (volume : Measure unitInterval)) + +def openEdges (labels : E → unitInterval) (p : unitInterval) : Set E := + {e | labels e ≤ p} + +noncomputable def AmenableGroup (Λ : Type u) [Group Λ] : Prop := by + classical + exact ∀ K : Finset Λ, ∀ ε : ℝ, 0 < ε → ∃ A : Finset Λ, A.Nonempty ∧ + ∀ g ∈ K, (((A.image (fun x => x * g)) \ A).card : ℝ) < ε * A.card + +def CayleyEdge {Λ : Type u} [Group Λ] (S : Finset Λ) := + {e : Sym2 Λ // ∃ x : Λ, ∃ s ∈ S, e = s(x, x * s)} + +def cayleyGraph {Λ : Type u} [Group Λ] (S : Finset Λ) : + BondGraph Λ (CayleyEdge S) := Subtype.val + +theorem arbitrary_cayley {Λ : Type u} [Group Λ] [Group.FG Λ] + (hna : ¬ AmenableGroup Λ) (S : Finset Λ) + (hsym : ∀ s ∈ S, s⁻¹ ∈ S) (hgen : Subgroup.closure (S : Set Λ) = ⊤) + (h1 : 1 ∉ S) : + OperatorBounded (cayleyGraph S) (pc (cayleyGraph S)) ∧ + pc (cayleyGraph S) < ptwo (cayleyGraph S) ∧ + ptwo (cayleyGraph S) ≤ pu (cayleyGraph S) ∧ + (∃ p₁ p₂ : unitInterval, pc (cayleyGraph S) < p₁ ∧ p₁ < p₂ ∧ p₂ < 1 ∧ + ∀ᵐ labels ∂(labelLaw : Measure (CayleyEdge S → unitInterval)), + ∀ p ∈ Set.Icc p₁ p₂, (infiniteClusters (cayleyGraph S) (openEdges labels p)).Infinite) ∧ + (∀ p : unitInterval, pc (cayleyGraph S) < p → p < pu (cayleyGraph S) → + ∀ᵐ ω ∂law p, (infiniteClusters (cayleyGraph S) ω).Infinite) := by + sorry + +end Percolation + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CayleyPercolation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Percolation.arbitrary_cayley` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cayley-percolation/solution/closure.txt b/tasks/cayley-percolation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..48399a5fefcade3b2fe86e776a6bcd47f7f7ac75 --- /dev/null +++ b/tasks/cayley-percolation/solution/closure.txt @@ -0,0 +1,78 @@ +OAI.Probability.UnimodularPercolation.Cayley.Folner +OAI.Probability.UnimodularPercolation.Cayley.Geometry +OAI.Probability.UnimodularPercolation.Cayley.Nonuniqueness +OAI.Probability.UnimodularPercolation.CayleyMain +OAI.Probability.UnimodularPercolation.Clusters.ExteriorMoments +OAI.Probability.UnimodularPercolation.Clusters.KernelMoments +OAI.Probability.UnimodularPercolation.Clusters.LargeContacts +OAI.Probability.UnimodularPercolation.Clusters.Resampling +OAI.Probability.UnimodularPercolation.Clusters.Uniqueness +OAI.Probability.UnimodularPercolation.Criticality.ClusterCount +OAI.Probability.UnimodularPercolation.Criticality.Connectivity +OAI.Probability.UnimodularPercolation.Criticality.Ergodicity +OAI.Probability.UnimodularPercolation.Criticality.FiniteChanges +OAI.Probability.UnimodularPercolation.Criticality.Finiteness +OAI.Probability.UnimodularPercolation.Criticality.FullFiniteness +OAI.Probability.UnimodularPercolation.Criticality.Operator +OAI.Probability.UnimodularPercolation.Criticality.Phase +OAI.Probability.UnimodularPercolation.Criticality.ScaleLimits +OAI.Probability.UnimodularPercolation.Criticality.Sharpness +OAI.Probability.UnimodularPercolation.Criticality.Susceptibility +OAI.Probability.UnimodularPercolation.Deformation.AveragedDecrease +OAI.Probability.UnimodularPercolation.Deformation.Calibration +OAI.Probability.UnimodularPercolation.Deformation.ClusterProducts +OAI.Probability.UnimodularPercolation.Deformation.Corridors +OAI.Probability.UnimodularPercolation.Deformation.Derivatives +OAI.Probability.UnimodularPercolation.Deformation.FiniteScale +OAI.Probability.UnimodularPercolation.Encounter.Counts +OAI.Probability.UnimodularPercolation.Encounter.Geometry +OAI.Probability.UnimodularPercolation.Encounter.IntrinsicDistance +OAI.Probability.UnimodularPercolation.Encounter.Measurability +OAI.Probability.UnimodularPercolation.Encounter.NearestMass +OAI.Probability.UnimodularPercolation.Encounter.Surgery +OAI.Probability.UnimodularPercolation.Encounter.Transport +OAI.Probability.UnimodularPercolation.Encounter.TreeBranches +OAI.Probability.UnimodularPercolation.Encounter.Vertices +OAI.Probability.UnimodularPercolation.Encounter.ZeroIntensity +OAI.Probability.UnimodularPercolation.Escape.CollisionTails +OAI.Probability.UnimodularPercolation.Escape.Labels +OAI.Probability.UnimodularPercolation.Escape.PathSelection +OAI.Probability.UnimodularPercolation.Escape.PositiveEscapes +OAI.Probability.UnimodularPercolation.Escape.SelectionBounds +OAI.Probability.UnimodularPercolation.Exploration.FractionalMoments +OAI.Probability.UnimodularPercolation.Exploration.Goodness +OAI.Probability.UnimodularPercolation.Exploration.Marked +OAI.Probability.UnimodularPercolation.Exploration.Moments +OAI.Probability.UnimodularPercolation.Exploration.TailBounds +OAI.Probability.UnimodularPercolation.Graph.Automorphisms +OAI.Probability.UnimodularPercolation.Graph.Basic +OAI.Probability.UnimodularPercolation.Graph.Paths +OAI.Probability.UnimodularPercolation.Graph.Topology +OAI.Probability.UnimodularPercolation.Kernel.Amplification +OAI.Probability.UnimodularPercolation.Kernel.Bounds +OAI.Probability.UnimodularPercolation.Kernel.Connections +OAI.Probability.UnimodularPercolation.Kernel.ContactTrace +OAI.Probability.UnimodularPercolation.Kernel.Covariance +OAI.Probability.UnimodularPercolation.Kernel.DistinctMoments +OAI.Probability.UnimodularPercolation.Kernel.RussoRows +OAI.Probability.UnimodularPercolation.Kernel.ScaleBudget +OAI.Probability.UnimodularPercolation.Kernel.Spectral +OAI.Probability.UnimodularPercolation.Kernel.Sprinkling +OAI.Probability.UnimodularPercolation.Kernel.TraceBounds +OAI.Probability.UnimodularPercolation.Main +OAI.Probability.UnimodularPercolation.ProductMeasure.Association +OAI.Probability.UnimodularPercolation.Splicing.EndpointMoments +OAI.Probability.UnimodularPercolation.Splicing.GapCodes +OAI.Probability.UnimodularPercolation.Splicing.Geometry +OAI.Probability.UnimodularPercolation.Splicing.MomentBounds +OAI.Probability.UnimodularPercolation.Splicing.ReferenceLaws +OAI.Probability.UnimodularPercolation.Splicing.Replay +OAI.Probability.UnimodularPercolation.Subdivision.Coupling +OAI.Probability.UnimodularPercolation.Subdivision.Graph +OAI.Probability.UnimodularPercolation.Subdivision.Operator +OAI.Probability.UnimodularPercolation.Transport.EndpointKernels +OAI.Probability.UnimodularPercolation.Transport.Haar +OAI.Probability.UnimodularPercolation.Transport.TrajectoryMass +OAI.Probability.UnimodularPercolation.TwoCluster.Bounds +OAI.Probability.UnimodularPercolation.TwoCluster.Score +OAI.Probability.UnimodularPercolation.TwoCluster.Transport diff --git a/tasks/cayley-percolation/solution/reference.py b/tasks/cayley-percolation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cayley-percolation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cayley-percolation/solution/solve.sh b/tasks/cayley-percolation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..15a7081d04ac31441573910c41997f82376685c3 --- /dev/null +++ b/tasks/cayley-percolation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CayleyPercolation, i.e. module OAI.Probability.UnimodularPercolation.CayleyMain and the +# 78 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.UnimodularPercolation.CayleyMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CayleyPercolation" diff --git a/tasks/cayley-percolation/task.toml b/tasks/cayley-percolation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ffd99a206194c7689316b4b3753aa6eafe4966e --- /dev/null +++ b/tasks/cayley-percolation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cayley-percolation" +version = "1.0.0" +description = "Prove CayleyPercolation (openai/math family 214: The Benjamini–Schramm nonuniqueness conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CayleyPercolation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CayleyPercolation" +family = "214" +family_title = "The Benjamini–Schramm nonuniqueness conjecture" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Percolation.arbitrary_cayley"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.UnimodularPercolation.CayleyMain" +reference_modules = 78 +reference_lean_bytes = 2644104 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1048 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14079 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cayley-percolation/tests/Challenge.lean b/tasks/cayley-percolation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2479acd198ab4564b2ee3f587af93b7a36898b2d --- /dev/null +++ b/tasks/cayley-percolation/tests/Challenge.lean @@ -0,0 +1,84 @@ +import Mathlib + +namespace OAI + +/-! Nonuniqueness of Bernoulli bond percolation on arbitrary Cayley graphs. -/ + +open MeasureTheory ProbabilityTheory +open scoped ENNReal NNReal + +namespace Percolation +universe u v +variable {V : Type u} {E : Type v} + +abbrev BondGraph (V : Type u) (E : Type v) := E → Sym2 V + +def Conn (G : BondGraph V E) (ω : Set E) (x y : V) : Prop := + Relation.ReflTransGen (fun a b => ∃ e ∈ ω, G e = s(a, b)) x y + +def cluster (G : BondGraph V E) (ω : Set E) (x : V) : Set V := + {y | Conn G ω x y} + +def infiniteClusters (G : BondGraph V E) (ω : Set E) : Set (Set V) := + {C | C.Infinite ∧ ∃ x, C = cluster G ω x} + +noncomputable def law (p : unitInterval) : Measure (Set E) := + setBernoulli Set.univ p + +noncomputable def pc (G : BondGraph V E) : unitInterval := + sInf {p | 0 < law p {ω | (infiniteClusters G ω).Nonempty}} + +noncomputable def pu (G : BondGraph V E) : unitInterval := + sInf {p | law p {ω | ∃! C, C ∈ infiniteClusters G ω} = 1} + +noncomputable def twoPoint (G : BondGraph V E) (p : unitInterval) (x y : V) : ℝ := + (law p {ω | Conn G ω x y}).toReal + +noncomputable abbrev Hilbert (V : Type u) := lp (fun _ : V => ℂ) 2 + +noncomputable def HasKernel [DecidableEq V] + (G : BondGraph V E) (p : unitInterval) + (A : Hilbert V →L[ℂ] Hilbert V) : Prop := + ∀ x y, (A (lp.single 2 y (1 : ℂ))) x = (twoPoint G p x y : ℂ) + +noncomputable def OperatorBounded (G : BondGraph V E) (p : unitInterval) : Prop := by + classical + exact ∃ A : Hilbert V →L[ℂ] Hilbert V, HasKernel G p A + +noncomputable def ptwo (G : BondGraph V E) : unitInterval := + sSup {p | OperatorBounded G p} + +noncomputable def labelLaw : Measure (E → unitInterval) := + Measure.infinitePi (fun _ => (volume : Measure unitInterval)) + +def openEdges (labels : E → unitInterval) (p : unitInterval) : Set E := + {e | labels e ≤ p} + +noncomputable def AmenableGroup (Λ : Type u) [Group Λ] : Prop := by + classical + exact ∀ K : Finset Λ, ∀ ε : ℝ, 0 < ε → ∃ A : Finset Λ, A.Nonempty ∧ + ∀ g ∈ K, (((A.image (fun x => x * g)) \ A).card : ℝ) < ε * A.card + +def CayleyEdge {Λ : Type u} [Group Λ] (S : Finset Λ) := + {e : Sym2 Λ // ∃ x : Λ, ∃ s ∈ S, e = s(x, x * s)} + +def cayleyGraph {Λ : Type u} [Group Λ] (S : Finset Λ) : + BondGraph Λ (CayleyEdge S) := Subtype.val + +theorem arbitrary_cayley {Λ : Type u} [Group Λ] [Group.FG Λ] + (hna : ¬ AmenableGroup Λ) (S : Finset Λ) + (hsym : ∀ s ∈ S, s⁻¹ ∈ S) (hgen : Subgroup.closure (S : Set Λ) = ⊤) + (h1 : 1 ∉ S) : + OperatorBounded (cayleyGraph S) (pc (cayleyGraph S)) ∧ + pc (cayleyGraph S) < ptwo (cayleyGraph S) ∧ + ptwo (cayleyGraph S) ≤ pu (cayleyGraph S) ∧ + (∃ p₁ p₂ : unitInterval, pc (cayleyGraph S) < p₁ ∧ p₁ < p₂ ∧ p₂ < 1 ∧ + ∀ᵐ labels ∂(labelLaw : Measure (CayleyEdge S → unitInterval)), + ∀ p ∈ Set.Icc p₁ p₂, (infiniteClusters (cayleyGraph S) (openEdges labels p)).Infinite) ∧ + (∀ p : unitInterval, pc (cayleyGraph S) < p → p < pu (cayleyGraph S) → + ∀ᵐ ω ∂law p, (infiniteClusters (cayleyGraph S) ω).Infinite) := by + sorry + +end Percolation + +end OAI diff --git a/tasks/cayley-percolation/tests/grade.py b/tasks/cayley-percolation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cayley-percolation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cayley-percolation/tests/task.json b/tasks/cayley-percolation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..62ffd80fcad95855e088a4c26c94c87d01d89bbf --- /dev/null +++ b/tasks/cayley-percolation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CayleyPercolation", + "comparator": { + "theorem_names": [ + "OAI.Percolation.arbitrary_cayley" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13179 +} \ No newline at end of file diff --git a/tasks/cayley-percolation/tests/test.sh b/tasks/cayley-percolation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cayley-percolation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ch-obstruction/environment/Dockerfile b/tasks/ch-obstruction/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ch-obstruction/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ch-obstruction/environment/fetch_mathlib.sh b/tasks/ch-obstruction/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ch-obstruction/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ch-obstruction/environment/lake-manifest.json b/tasks/ch-obstruction/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ch-obstruction/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ch-obstruction/environment/lakefile.lean b/tasks/ch-obstruction/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ch-obstruction/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ch-obstruction/environment/lean_setup.sh b/tasks/ch-obstruction/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ch-obstruction/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ch-obstruction/environment/pack_submission.py b/tasks/ch-obstruction/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ch-obstruction/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ch-obstruction/instruction.md b/tasks/ch-obstruction/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc9b61745a4ba7bf836cb54ecc5f46666977b616 --- /dev/null +++ b/tasks/ch-obstruction/instruction.md @@ -0,0 +1,158 @@ +# openai/math challenge `CHObstruction` (family 240) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 240 of the release, *Shelah's eventual categoricity conjecture* +(Mathematical logic). The family as a whole: Proves Shelah's eventual categoricity conjecture in ZFC: for each bound on the Lowenheim–Skolem number, a uniform threshold makes categoricity of an abstract elementary class in one cardinal above that threshold imply categoricity throughout the same tail. Categoricity means uniqueness up to isomorphism at a given cardinality. Under the continuum hypothesis, a proposed specific Hanf threshold need not suffice. + +The challenge is `CHObstruction`, also at `/opt/openai-math/challenges/CHObstruction.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u + +noncomputable section + +namespace CHObstruction + +open Cardinal Ordinal Order + +structure RelModel (L : ℕ → Type) where + carrier : ZFSet.{u} + rel : (n : ℕ) → L n → (Fin n → carrier) → Prop + +namespace RelModel + +variable {L : ℕ → Type} + +structure IsSubstructure (M N : RelModel.{u} L) : Prop where + subset : M.carrier ⊆ N.carrier + restrict : ∀ (n) (r : L n) (a : Fin n → M.carrier), + M.rel n r a ↔ N.rel n r (fun i => ⟨(a i).val, subset (a i).property⟩) + +structure Iso (M N : RelModel.{u} L) where + toEquiv : M.carrier ≃ N.carrier + map_rel : ∀ (n) (r : L n) (a : Fin n → M.carrier), + M.rel n r a ↔ N.rel n r (toEquiv ∘ a) + +def IsUnion {ι : Type u} (F : ι → RelModel.{u} L) (U : RelModel.{u} L) : Prop := + (∀ i, IsSubstructure (F i) U) ∧ + ∀ x : U.carrier, ∃ i, x.val ∈ (F i).carrier + +end RelModel + +structure ClassData (L : ℕ → Type) where + objects : RelModel.{u} L → Prop + strong : RelModel.{u} L → RelModel.{u} L → Prop + +namespace ClassData + +variable {L : ℕ → Type} (K : ClassData.{u} L) + +def LSBound (θ : Cardinal.{u}) : Prop := + ℵ₀ ≤ θ ∧ Cardinal.lift.{u, 0} (# (Σ n, L n)) ≤ θ ∧ + ∀ M, K.objects M → ∀ A : ZFSet.{u}, A ⊆ M.carrier → + ∃ N, K.objects N ∧ K.strong N M ∧ A ⊆ N.carrier ∧ N.carrier.card ≤ A.card + θ + +def HasLSNumber (θ : Cardinal.{u}) : Prop := + K.LSBound θ ∧ ∀ θ', K.LSBound θ' → θ ≤ θ' + +structure IsAEC : Prop where + strong_objects : ∀ {M N}, K.strong M N → K.objects M ∧ K.objects N + refl : ∀ {M}, K.objects M → K.strong M M + antisymm : ∀ {M N}, K.strong M N → K.strong N M → M = N + trans : ∀ {M N P}, K.strong M N → K.strong N P → K.strong M P + substructure : ∀ {M N}, K.strong M N → M.IsSubstructure N + iso_objects : ∀ {M N}, K.objects M → Nonempty (M.Iso N) → K.objects N + iso_strong : ∀ {M N M' N'} (h : K.strong M N) + (e : M.Iso M') (f : N.Iso N'), + (∀ x : M.carrier, + (e.toEquiv x).val = + (f.toEquiv ⟨x.val, (substructure h).subset x.property⟩).val) → + K.strong M' N' + coherence : ∀ {M₀ M₁ M₂}, M₀.IsSubstructure M₁ → + K.strong M₀ M₂ → K.strong M₁ M₂ → K.strong M₀ M₁ + chain_union : ∀ (γ : Ordinal.{u}), γ ≠ 0 → + ∀ (F : γ.ToType → RelModel.{u} L), + (∀ i, K.objects (F i)) → + (∀ i j, i ≤ j → K.strong (F i) (F j)) → + ∃ U, K.objects U ∧ RelModel.IsUnion F U ∧ + (∀ i, K.strong (F i) U) ∧ + (∀ N, K.objects N → (∀ i, K.strong (F i) N) → K.strong U N) + downward : ∃ θ, K.LSBound θ + +def Categorical (μ : Cardinal.{u}) : Prop := + (∃ M, K.objects M ∧ M.carrier.card = μ) ∧ + ∀ M N, K.objects M → K.objects N → + M.carrier.card = μ → N.carrier.card = μ → Nonempty (M.Iso N) + +def TwoModels (μ : Cardinal.{u}) : Prop := + ∃ M N, K.objects M ∧ K.objects N ∧ + M.carrier.card = μ ∧ N.carrier.card = μ ∧ ¬ Nonempty (M.Iso N) + +end ClassData + +def CH : Prop := (2 : Cardinal.{u}) ^ ℵ₀ = ℵ_ 1 + +def hanf (κ : Cardinal.{u}) : Cardinal.{u} := beth (succ ((2 : Cardinal.{u}) ^ κ)).ord + +def endpoint : Cardinal.{u} := beth (ω_ 2) + +def tailThreshold : Cardinal.{u} := beth (succ ((2 : Cardinal.{u}) ^ (ℵ_ 1))).ord + +theorem main (hCH : CH.{u}) : + ∃ (L : ℕ → Type), Countable (Σ n, L n) ∧ + ∃ K : ClassData.{u} L, K.IsAEC ∧ K.HasLSNumber ℵ₀ ∧ + endpoint = hanf (ℵ₀ : Cardinal.{u}) ∧ K.TwoModels endpoint ∧ + ∀ μ, tailThreshold ≤ μ → K.Categorical μ := by + sorry + +end CHObstruction + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CHObstruction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CHObstruction.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ch-obstruction/solution/closure.txt b/tasks/ch-obstruction/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc8843bf868d2728b853b6557c4ffff1999e5405 --- /dev/null +++ b/tasks/ch-obstruction/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.ModelTheory.Categoricity.AEC +OAI.ModelTheory.Categoricity.ArrayEmbeddings +OAI.ModelTheory.Categoricity.ArrayIsomorphisms +OAI.ModelTheory.Categoricity.ArrayMaps +OAI.ModelTheory.Categoricity.Arrays +OAI.ModelTheory.Categoricity.Collapse +OAI.ModelTheory.Categoricity.Colors +OAI.ModelTheory.Categoricity.Diagrams +OAI.ModelTheory.Categoricity.DirectedLimits +OAI.ModelTheory.Categoricity.EndpointDiagrams +OAI.ModelTheory.Categoricity.Main +OAI.ModelTheory.Categoricity.Model +OAI.ModelTheory.Categoricity.Partition +OAI.ModelTheory.Categoricity.Subarrays +OAI.ModelTheory.Categoricity.TailBound diff --git a/tasks/ch-obstruction/solution/reference.py b/tasks/ch-obstruction/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ch-obstruction/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ch-obstruction/solution/solve.sh b/tasks/ch-obstruction/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9a63edbda422a62758a1936c0b3b86c67f0cb9d5 --- /dev/null +++ b/tasks/ch-obstruction/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CHObstruction, i.e. module OAI.ModelTheory.Categoricity.Main and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.ModelTheory.Categoricity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CHObstruction" diff --git a/tasks/ch-obstruction/task.toml b/tasks/ch-obstruction/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e4c385491544fbdcce43b9c8616593f0771ded4e --- /dev/null +++ b/tasks/ch-obstruction/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ch-obstruction" +version = "1.0.0" +description = "Prove CHObstruction (openai/math family 240: Shelah's eventual categoricity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CHObstruction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CHObstruction" +family = "240" +family_title = "Shelah's eventual categoricity conjecture" +subject = "Mathematical logic" +theorems = ["OAI.CHObstruction.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.ModelTheory.Categoricity.Main" +reference_modules = 15 +reference_lean_bytes = 199905 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1476 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11879 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ch-obstruction/tests/Challenge.lean b/tasks/ch-obstruction/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3593ffad8091dbe4356fe01f7c4c7d7dfa8ce6ac --- /dev/null +++ b/tasks/ch-obstruction/tests/Challenge.lean @@ -0,0 +1,107 @@ +import Mathlib + +namespace OAI + +universe u + +noncomputable section + +namespace CHObstruction + +open Cardinal Ordinal Order + +structure RelModel (L : ℕ → Type) where + carrier : ZFSet.{u} + rel : (n : ℕ) → L n → (Fin n → carrier) → Prop + +namespace RelModel + +variable {L : ℕ → Type} + +structure IsSubstructure (M N : RelModel.{u} L) : Prop where + subset : M.carrier ⊆ N.carrier + restrict : ∀ (n) (r : L n) (a : Fin n → M.carrier), + M.rel n r a ↔ N.rel n r (fun i => ⟨(a i).val, subset (a i).property⟩) + +structure Iso (M N : RelModel.{u} L) where + toEquiv : M.carrier ≃ N.carrier + map_rel : ∀ (n) (r : L n) (a : Fin n → M.carrier), + M.rel n r a ↔ N.rel n r (toEquiv ∘ a) + +def IsUnion {ι : Type u} (F : ι → RelModel.{u} L) (U : RelModel.{u} L) : Prop := + (∀ i, IsSubstructure (F i) U) ∧ + ∀ x : U.carrier, ∃ i, x.val ∈ (F i).carrier + +end RelModel + +structure ClassData (L : ℕ → Type) where + objects : RelModel.{u} L → Prop + strong : RelModel.{u} L → RelModel.{u} L → Prop + +namespace ClassData + +variable {L : ℕ → Type} (K : ClassData.{u} L) + +def LSBound (θ : Cardinal.{u}) : Prop := + ℵ₀ ≤ θ ∧ Cardinal.lift.{u, 0} (# (Σ n, L n)) ≤ θ ∧ + ∀ M, K.objects M → ∀ A : ZFSet.{u}, A ⊆ M.carrier → + ∃ N, K.objects N ∧ K.strong N M ∧ A ⊆ N.carrier ∧ N.carrier.card ≤ A.card + θ + +def HasLSNumber (θ : Cardinal.{u}) : Prop := + K.LSBound θ ∧ ∀ θ', K.LSBound θ' → θ ≤ θ' + +structure IsAEC : Prop where + strong_objects : ∀ {M N}, K.strong M N → K.objects M ∧ K.objects N + refl : ∀ {M}, K.objects M → K.strong M M + antisymm : ∀ {M N}, K.strong M N → K.strong N M → M = N + trans : ∀ {M N P}, K.strong M N → K.strong N P → K.strong M P + substructure : ∀ {M N}, K.strong M N → M.IsSubstructure N + iso_objects : ∀ {M N}, K.objects M → Nonempty (M.Iso N) → K.objects N + iso_strong : ∀ {M N M' N'} (h : K.strong M N) + (e : M.Iso M') (f : N.Iso N'), + (∀ x : M.carrier, + (e.toEquiv x).val = + (f.toEquiv ⟨x.val, (substructure h).subset x.property⟩).val) → + K.strong M' N' + coherence : ∀ {M₀ M₁ M₂}, M₀.IsSubstructure M₁ → + K.strong M₀ M₂ → K.strong M₁ M₂ → K.strong M₀ M₁ + chain_union : ∀ (γ : Ordinal.{u}), γ ≠ 0 → + ∀ (F : γ.ToType → RelModel.{u} L), + (∀ i, K.objects (F i)) → + (∀ i j, i ≤ j → K.strong (F i) (F j)) → + ∃ U, K.objects U ∧ RelModel.IsUnion F U ∧ + (∀ i, K.strong (F i) U) ∧ + (∀ N, K.objects N → (∀ i, K.strong (F i) N) → K.strong U N) + downward : ∃ θ, K.LSBound θ + +def Categorical (μ : Cardinal.{u}) : Prop := + (∃ M, K.objects M ∧ M.carrier.card = μ) ∧ + ∀ M N, K.objects M → K.objects N → + M.carrier.card = μ → N.carrier.card = μ → Nonempty (M.Iso N) + +def TwoModels (μ : Cardinal.{u}) : Prop := + ∃ M N, K.objects M ∧ K.objects N ∧ + M.carrier.card = μ ∧ N.carrier.card = μ ∧ ¬ Nonempty (M.Iso N) + +end ClassData + +def CH : Prop := (2 : Cardinal.{u}) ^ ℵ₀ = ℵ_ 1 + +def hanf (κ : Cardinal.{u}) : Cardinal.{u} := beth (succ ((2 : Cardinal.{u}) ^ κ)).ord + +def endpoint : Cardinal.{u} := beth (ω_ 2) + +def tailThreshold : Cardinal.{u} := beth (succ ((2 : Cardinal.{u}) ^ (ℵ_ 1))).ord + +theorem main (hCH : CH.{u}) : + ∃ (L : ℕ → Type), Countable (Σ n, L n) ∧ + ∃ K : ClassData.{u} L, K.IsAEC ∧ K.HasLSNumber ℵ₀ ∧ + endpoint = hanf (ℵ₀ : Cardinal.{u}) ∧ K.TwoModels endpoint ∧ + ∀ μ, tailThreshold ≤ μ → K.Categorical μ := by + sorry + +end CHObstruction + +end + +end OAI diff --git a/tasks/ch-obstruction/tests/grade.py b/tasks/ch-obstruction/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ch-obstruction/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ch-obstruction/tests/task.json b/tasks/ch-obstruction/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2425e25b13790eafa8d14d297654f64826c63925 --- /dev/null +++ b/tasks/ch-obstruction/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CHObstruction", + "comparator": { + "theorem_names": [ + "OAI.CHObstruction.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10979 +} \ No newline at end of file diff --git a/tasks/ch-obstruction/tests/test.sh b/tasks/ch-obstruction/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ch-obstruction/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/character-criterion/environment/Dockerfile b/tasks/character-criterion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/character-criterion/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/character-criterion/environment/fetch_mathlib.sh b/tasks/character-criterion/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/character-criterion/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/character-criterion/environment/lake-manifest.json b/tasks/character-criterion/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/character-criterion/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/character-criterion/environment/lakefile.lean b/tasks/character-criterion/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/character-criterion/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/character-criterion/environment/lean_setup.sh b/tasks/character-criterion/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/character-criterion/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/character-criterion/environment/pack_submission.py b/tasks/character-criterion/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/character-criterion/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/character-criterion/instruction.md b/tasks/character-criterion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d876f4c65d73f879e7d84cf1b851485e2f05325 --- /dev/null +++ b/tasks/character-criterion/instruction.md @@ -0,0 +1,2189 @@ +# openai/math challenge `CharacterCriterion` (family 299) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 299 of the release, *The Kirchberg–R\o rdam character criterion* +(Operator algebras). The family as a whole: A nonzero unital separable complex $C^*$-algebra is Jiang–Su stable exactly when its norm central-sequence algebra has no characters, for every free ultrafilter. This answers the Kirchberg–R\o rdam character question. Also, the infinite minimal tensor power of every such algebra without characters is Jiang–Su stable, answering the Dadarlat–Toms question. + +The challenge is `CharacterCriterion`, also at `/opt/openai-math/challenges/CharacterCriterion.lean`: + +```lean +import Mathlib + +/-! +# Character criterion for Jiang–Su absorption + +The main statement is Theorem 1.1 of the Kirchberg–Rørdam character-criterion paper. +The constructions below specify the norm central-sequence algebra and Jiang–Su absorption. +-/ + +namespace OAI + +noncomputable section + +section + +open scoped TensorProduct InnerProductSpace BigOperators +open Set Module + +universe uQuot +namespace KirchbergRordam.QuotientNormSupport + +@[instance_reducible] +noncomputable def normedRing {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] : NormedRing (R ⧸ I) := by + classical + have h_QuotientNormSupport_distance_eq {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] (x y : R ⧸ I) : + dist x y = ‖-x + y‖ := dist_eq_norm_neg_add x y + have h_QuotientNormSupport_multiplication_bound {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] (x y : R ⧸ I) : + ‖x * y‖ ≤ ‖x‖ * ‖y‖ := le_of_forall_pos_le_add fun ε hε => + let neighborhood : ∃ radii : ℝ × ℝ, (0 < radii.1 ∧ 0 < radii.2) ∧ + ∀ point : ℝ × ℝ, (dist point.1 ‖x‖ < radii.1 ∧ dist point.2 ‖y‖ < radii.2) → + dist (point.1 * point.2) (‖x‖ * ‖y‖) < ε := + ((Metric.nhds_basis_ball.prod_nhds Metric.nhds_basis_ball).tendsto_iff + Metric.nhds_basis_ball).mp (continuous_mul.tendsto (‖x‖, ‖y‖)) ε hε + neighborhood.elim fun radii radii_spec => + (Submodule.Quotient.norm_mk_lt x radii_spec.1.1).elim fun representative_x x_spec => + (Submodule.Quotient.norm_mk_lt y radii_spec.1.2).elim fun representative_y y_spec => + let lower_x : ‖x‖ ≤ ‖representative_x‖ := + Eq.mp (congrArg (fun value : R ⧸ I => ‖value‖ ≤ ‖representative_x‖) x_spec.1) + (Submodule.Quotient.norm_mk_le I representative_x) + let lower_y : ‖y‖ ≤ ‖representative_y‖ := + Eq.mp (congrArg (fun value : R ⧸ I => ‖value‖ ≤ ‖representative_y‖) y_spec.1) + (Submodule.Quotient.norm_mk_le I representative_y) + let distance_x : dist ‖representative_x‖ ‖x‖ < radii.1 := + Eq.mpr (congrArg (fun distance : ℝ => distance < radii.1) + (Real.dist_eq ‖representative_x‖ ‖x‖)) + (abs_sub_lt_iff.mpr ⟨sub_lt_iff_lt_add'.mpr x_spec.2, + (sub_nonpos.mpr lower_x).trans_lt radii_spec.1.1⟩) + let distance_y : dist ‖representative_y‖ ‖y‖ < radii.2 := + Eq.mpr (congrArg (fun distance : ℝ => distance < radii.2) + (Real.dist_eq ‖representative_y‖ ‖y‖)) + (abs_sub_lt_iff.mpr ⟨sub_lt_iff_lt_add'.mpr y_spec.2, + (sub_nonpos.mpr lower_y).trans_lt radii_spec.1.2⟩) + let product_distance := + radii_spec.2 (‖representative_x‖, ‖representative_y‖) ⟨distance_x, distance_y⟩ + let product_bound : ‖x * y‖ ≤ ‖representative_x‖ * ‖representative_y‖ := + Eq.mp (congrArg₂ (fun left right : R ⧸ I => + ‖left * right‖ ≤ ‖representative_x‖ * ‖representative_y‖) x_spec.1 y_spec.1) + ((Submodule.Quotient.norm_mk_le I (representative_x * representative_y)).trans + (norm_mul_le representative_x representative_y)) + product_bound.trans (sub_lt_iff_lt_add'.mp (abs_sub_lt_iff.mp + (Eq.mp (congrArg (fun distance : ℝ => distance < ε) + (Real.dist_eq (‖representative_x‖ * ‖representative_y‖) (‖x‖ * ‖y‖))) + product_distance)).1).le + exact { + toNorm := inferInstance + toRing := inferInstance + toMetricSpace := inferInstance + dist_eq := h_QuotientNormSupport_distance_eq I + norm_mul_le := h_QuotientNormSupport_multiplication_bound I + } + +end KirchbergRordam.QuotientNormSupport + +end + +open scoped TensorProduct CStarAlgebra InnerProductSpace Matrix Kronecker ComplexOrder +open UniformSpace Filter Topology BoundedContinuousFunction + +universe uQuot + +namespace KirchbergRordam.NormUltrapower + +variable {A : Type*} [CStarAlgebra A] + +abbrev BoundedSeq (A : Type*) [CStarAlgebra A] := ℕ →ᵇ A + +def normLimit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : ℝ := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + exact + (h_NormUltrapower_exists_norm_limit ω x).choose + +def nullIdeal (ω : Ultrafilter ℕ) : Ideal (OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_mul_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x * y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x*y)) + ((h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_mul_le (x n) (y n)) + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + have h_NormUltrapower_normLimit_zero (ω : Ultrafilter ℕ) : OAI.KirchbergRordam.NormUltrapower.normLimit ω (0 : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) = 0 := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω 0) + simp + exact { + carrier := {x | OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0} + zero_mem' := h_NormUltrapower_normLimit_zero ω + add_mem' := by + intro x y hx hy + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 at hx + change OAI.KirchbergRordam.NormUltrapower.normLimit ω y = 0 at hy + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x+y)) + simpa only [hx, hy, add_zero] using h_NormUltrapower_normLimit_add_le ω x y + smul_mem' := by + intro x y hy + change OAI.KirchbergRordam.NormUltrapower.normLimit ω y = 0 at hy + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x*y)) + simpa only [hy, mul_zero] using h_NormUltrapower_normLimit_mul_le ω x y + } + +instance nullIdeal_twoSided (ω : Ultrafilter ℕ) : (OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω).IsTwoSided := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_mul_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x * y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x*y)) + ((h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_mul_le (x n) (y n)) + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + exact { + mul_mem_of_left := by + intro x y hx + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (x*y) = 0 + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x*y)) + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 at hx + simpa only [hx, zero_mul] using h_NormUltrapower_normLimit_mul_le ω x y + } + +instance nullIdeal_closed (ω : Ultrafilter ℕ) : IsClosed (OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω : Set (OAI.KirchbergRordam.NormUltrapower.BoundedSeq A)) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_normLimit_le (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖x‖ := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.2 + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_sub_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x - OAI.KirchbergRordam.NormUltrapower.normLimit ω y ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) := by + have h := h_NormUltrapower_normLimit_add_le ω (x-y) y + rw [sub_add_cancel] at h + linarith + have h_NormUltrapower_normLimit_lipschitz (ω : Ultrafilter ℕ) : + LipschitzWith 1 (OAI.KirchbergRordam.NormUltrapower.normLimit ω : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A → ℝ) := by + apply LipschitzWith.of_dist_le_mul + intro x y + rw [NNReal.coe_one, one_mul, Real.dist_eq, abs_le, dist_eq_norm] + constructor + · have h := (h_NormUltrapower_normLimit_sub_le ω y x).trans (h_NormUltrapower_normLimit_le ω (y-x)) + rw [norm_sub_rev] at h + linarith + · exact (h_NormUltrapower_normLimit_sub_le ω x y).trans (h_NormUltrapower_normLimit_le ω (x-y)) + exact + isClosed_eq (h_NormUltrapower_normLimit_lipschitz ω).continuous continuous_const + +abbrev Algebra (A : Type*) [CStarAlgebra A] (ω : Ultrafilter ℕ) := + OAI.KirchbergRordam.NormUltrapower.BoundedSeq A ⧸ OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω + +noncomputable instance quotientNormedRing {R : Type uQuot} [NormedRing R] (I : Ideal R) + [I.IsTwoSided] [IsClosed (I : Set R)] : NormedRing (R ⧸ I) := + KirchbergRordam.QuotientNormSupport.normedRing I + +instance quotientNormedAlgebra (ω : Ultrafilter ℕ) : NormedAlgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + norm_smul_le := norm_smul_le + +instance quotientStar (ω : Ultrafilter ℕ) : Star (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_star (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (star x)) + simp [h_NormUltrapower_tendsto_norm] + exact { + star := Quotient.map' star fun x y h => by + rw [Submodule.quotientRel_def] at h ⊢ + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x - star y) = 0 + rw [← star_sub, h_NormUltrapower_normLimit_star] + exact h + } + +instance quotientStarRing (ω : Ultrafilter ℕ) : StarRing (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + star_involutive := by + rintro ⟨x⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (star x)) = Ideal.Quotient.mk _ x + rw [star_star] + star_mul := by + rintro ⟨x⟩ ⟨y⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (x*y)) = Ideal.Quotient.mk _ (star y * star x) + rw [star_mul] + star_add := by + rintro ⟨x⟩ ⟨y⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (x+y)) = Ideal.Quotient.mk _ (star x + star y) + rw [star_add] + +instance quotientStarModule (ω : Ultrafilter ℕ) : StarModule ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + star_smul := by + intro z + rintro ⟨x⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (z • x)) = Ideal.Quotient.mk _ (star z • star x) + rw [star_smul] + +def cutRepresentative (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) (c : ℝ) (hc : 0 ≤ c) : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A := + ofNormedAddCommGroupDiscrete (fun n => if ‖x n‖ < c then x n else 0) c (by + intro n + split_ifs with h + · exact h.le + · simpa only [norm_zero] using hc) + +instance quotientCStarRing (ω : Ultrafilter ℕ) : CStarRing (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_star_mul (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x * x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (star x * x)) + simpa only [BoundedContinuousFunction.mul_apply, BoundedContinuousFunction.star_apply, + CStarRing.norm_star_mul_self] using (h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω x) + have h_NormUltrapower_normLimit_neg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (-x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (-x)) + simp [h_NormUltrapower_tendsto_norm] + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_sub_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x - OAI.KirchbergRordam.NormUltrapower.normLimit ω y ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) := by + have h := h_NormUltrapower_normLimit_add_le ω (x-y) y + rw [sub_add_cancel] at h + linarith + have h_NormUltrapower_normLimit_eq_of_sub_mem (ω : Ultrafilter ℕ) {x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A} + (h : x-y ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x = OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) = 0 at h + apply le_antisymm + · have h' := h_NormUltrapower_normLimit_sub_le ω x y + linarith + · have h' := h_NormUltrapower_normLimit_sub_le ω y x + rw [← neg_sub x y, h_NormUltrapower_normLimit_neg, h] at h' + linarith + have h_NormUltrapower_normLimit_le (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖x‖ := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.2 + have h_NormUltrapower_normLimit_le_quotient (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ := by + apply QuotientAddGroup.le_norm_iff.mpr + intro y hy + have h : y-x ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω := (Ideal.Quotient.eq).mp hy + rw [← h_NormUltrapower_normLimit_eq_of_sub_mem ω h] + exact h_NormUltrapower_normLimit_le ω y + have h_NormUltrapower_mem_nullIdeal (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + x ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω ↔ Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 0) := by + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 ↔ _ + constructor + · intro h + simpa only [h] using h_NormUltrapower_tendsto_norm ω x + · exact fun h => tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω x) h + have h_NormUltrapower_cutRepresentative_mk_eq (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) + (c : ℝ) (hc : 0 ≤ c) (hlim : OAI.KirchbergRordam.NormUltrapower.normLimit ω x < c) : + Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x = + Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (OAI.KirchbergRordam.NormUltrapower.cutRepresentative x c hc) := by + rw [Ideal.Quotient.eq, h_NormUltrapower_mem_nullIdeal] + have he : ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ < c := + (h_NormUltrapower_tendsto_norm ω x).eventually (eventually_lt_nhds hlim) + have hz : Tendsto (fun _ : ℕ => (0 : ℝ)) (ω : Filter ℕ) (𝓝 0) := tendsto_const_nhds + apply hz.congr' + filter_upwards [he] with n hn + change (0 : ℝ) = ‖x n - (if ‖x n‖ < c then x n else 0)‖ + rw [ite_eq_left hn, sub_self, norm_zero] + have h_NormUltrapower_cutRepresentative_norm_le (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) (c : ℝ) (hc : 0 ≤ c) : + ‖OAI.KirchbergRordam.NormUltrapower.cutRepresentative x c hc‖ ≤ c := by + apply (BoundedContinuousFunction.norm_le hc).mpr + intro n + change ‖if ‖x n‖ < c then x n else 0‖ ≤ c + split_ifs with h + · exact h.le + · simpa only [norm_zero] using hc + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + have h_NormUltrapower_quotient_norm_le_normLimit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply le_of_forall_pos_le_add + intro ε hε + have hpos : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε := add_nonneg (h_NormUltrapower_normLimit_nonneg ω x) hε.le + rw [h_NormUltrapower_cutRepresentative_mk_eq ω x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos (lt_add_of_pos_right _ hε)] + have hb := Submodule.Quotient.norm_mk_le (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) + (OAI.KirchbergRordam.NormUltrapower.cutRepresentative x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos) + exact hb.trans (h_NormUltrapower_cutRepresentative_norm_le x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos) + have h_NormUltrapower_norm_mk_eq (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + le_antisymm (h_NormUltrapower_quotient_norm_le_normLimit ω x) (h_NormUltrapower_normLimit_le_quotient ω x) + exact { + norm_mul_self_le := by + rintro ⟨x⟩ + change ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ * ‖Ideal.Quotient.mk _ x‖ ≤ + ‖Ideal.Quotient.mk _ (star x * x)‖ + rw [h_NormUltrapower_norm_mk_eq, h_NormUltrapower_norm_mk_eq, h_NormUltrapower_normLimit_star_mul] + } + +instance quotientCStarAlgebra (ω : Ultrafilter ℕ) : CStarAlgebra (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + +def quotientMap (ω : Ultrafilter ℕ) : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.Algebra A ω where + __ := Ideal.Quotient.mkₐ ℂ (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) + map_star' _ := rfl + +def constantSeq : A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.BoundedSeq A where + toFun := BoundedContinuousFunction.const ℕ + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def diagonal (ω : Ultrafilter ℕ) : A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.Algebra A ω := + (OAI.KirchbergRordam.NormUltrapower.quotientMap ω).comp OAI.KirchbergRordam.NormUltrapower.constantSeq + +def centralSubalgebra (ω : Ultrafilter ℕ) : StarSubalgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := + StarSubalgebra.centralizer ℂ (Set.range (OAI.KirchbergRordam.NormUltrapower.diagonal (A := A) ω)) + +instance centralSubalgebra_closed (ω : Ultrafilter ℕ) : + IsClosed (OAI.KirchbergRordam.NormUltrapower.centralSubalgebra (A := A) ω : Set (OAI.KirchbergRordam.NormUltrapower.Algebra A ω)) := + Set.isClosed_centralizer _ + +abbrev CentralAlgebra (A : Type*) [CStarAlgebra A] (ω : Ultrafilter ℕ) := + OAI.KirchbergRordam.NormUltrapower.centralSubalgebra (A := A) ω + +instance centralSubringClass (ω : Ultrafilter ℕ) : + SubringClass (StarSubalgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω)) (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := + StarSubalgebra.subringClass (R := ℂ) (A := OAI.KirchbergRordam.NormUltrapower.Algebra A ω) + +instance centralCStarAlgebra (ω : Ultrafilter ℕ) : CStarAlgebra (OAI.KirchbergRordam.NormUltrapower.CentralAlgebra A ω) := + StarSubalgebra.cstarAlgebra _ + +end KirchbergRordam.NormUltrapower + +namespace KirchbergRordam +namespace StarCompletion + +open UniformSpace +variable (R : Type*) [SeminormedRing R] [StarRing R] [NormedStarGroup R] + +instance completionStar : Star (Completion R) := ⟨Completion.map (star : R → R)⟩ + +instance completionContinuousStar : ContinuousStar (Completion R) where + continuous_star := Completion.continuous_map + +instance completionStarRing : StarRing (Completion R) := by + classical + have h_StarCompletion_star_coe (x : R) : star (x : Completion R) = (star x : R) := + Completion.map_coe star_isometry.uniformContinuous x + exact { + star_involutive x := by + induction x using Completion.induction_on with + | hp => exact isClosed_eq (continuous_star.comp continuous_star) continuous_id + | ih x => simp only [h_StarCompletion_star_coe, star_star] + star_mul x y := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simp only [← Completion.coe_mul, h_StarCompletion_star_coe, star_mul] + star_add x y := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simp only [← Completion.coe_add, h_StarCompletion_star_coe, star_add] + } + +variable [NormedAlgebra ℂ R] [StarModule ℂ R] + +instance completionNormedAlgebra : NormedAlgebra ℂ (Completion R) where + norm_smul_le := norm_smul_le + +instance completionStarModule : StarModule ℂ (Completion R) := by + classical + have h_StarCompletion_star_coe (x : R) : star (x : Completion R) = (star x : R) := + Completion.map_coe star_isometry.uniformContinuous x + exact { + star_smul z x := by + induction x using Completion.induction_on with + | hp => + exact isClosed_eq + (continuous_star.comp (continuous_const_smul z)) + ((continuous_const_smul (star z)).comp continuous_star) + | ih x => + rw [← Completion.coe_smul, h_StarCompletion_star_coe, star_smul, Completion.coe_smul, h_StarCompletion_star_coe] + } + +end StarCompletion + +end KirchbergRordam + +namespace KirchbergRordam.CStarInductiveLimit +universe u + +structure System where + obj : ℕ → Type u + [cstar : ∀ n, CStarAlgebra (obj n)] + map : ∀ i j, i ≤ j → obj i →⋆ₐ[ℂ] obj j + map_self : ∀ i x, map i i le_rfl x = x + map_map : ∀ i j k (hij : i ≤ j) (hjk : j ≤ k) x, + map j k hjk (map i j hij x) = map i k (hij.trans hjk) x + norm_map : ∀ i j (h : i ≤ j) x, ‖map i j h x‖ = ‖x‖ + +attribute [instance] System.cstar + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : DirectedSystem S.obj (S.map · · ·) where + map_self := fun {_} x => S.map_self _ x + map_map := fun {_ _ _} hij hjk x => S.map_map _ _ _ hij hjk x + +def Raw (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) := DirectLimit S.obj S.map + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : Ring (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (Ring (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : Algebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (Algebra ℂ (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : StarRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (StarRing (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : StarModule ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (StarModule ℂ (DirectLimit S.obj S.map)) + +def rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) : S.obj n →⋆ₐ[ℂ] OAI.KirchbergRordam.CStarInductiveLimit.Raw S where + __ := DirectLimit.Algebra.of S.obj S.map n + map_star' _ := rfl + +def normLift (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : OAI.KirchbergRordam.CStarInductiveLimit.Raw S → ℝ := + DirectLimit.lift S.map (fun _ x => ‖x‖) (fun i j h x => (S.norm_map i j h x).symm) + +def ringNorm (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : RingNorm (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + exact { + toFun := OAI.KirchbergRordam.CStarInductiveLimit.normLift S + map_zero' := by + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (0 : DirectLimit S.obj S.map) = 0 + rw [DirectLimit.zero_def (f := S.map) 0] + exact norm_zero + add_le' := by + intro x y + refine DirectLimit.induction₂ S.map ?_ x y + intro n x y + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x + OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) ≤ + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) + rw [← map_add, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk] + exact norm_add_le x y + neg' := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (-OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) + rw [← map_neg, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, norm_neg] + mul_le' := by + intro x y + refine DirectLimit.induction₂ S.map ?_ x y + intro n x y + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x * OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) ≤ + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) * OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) + rw [← map_mul, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk] + exact norm_mul_le x y + eq_zero_of_map_eq_zero' := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x hx + change ‖x‖ = 0 at hx + rw [norm_eq_zero] at hx + change OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x = 0 + rw [hx, map_zero] + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := (OAI.KirchbergRordam.CStarInductiveLimit.ringNorm S).toNormedRing + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedAlgebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_smul_le z := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖z • OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ ≤ ‖z‖ * ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_smul, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf] + exact norm_smul_le z x + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedStarGroup (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_star_le := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖star (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x)‖ ≤ ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_star, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf, norm_star] + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_mul_self_le := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ * ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ ≤ ‖star (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) * OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_star, ← map_mul, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf] + exact CStarRing.norm_mul_self_le x + } + +abbrev Algebra (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) := UniformSpace.Completion (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S) := by + classical + have h_StarCompletion_star_coe (x : Raw S) : star (x : Completion (Raw S)) = ((star x : Raw S) : Completion (Raw S)) := Completion.map_coe star_isometry.uniformContinuous x + exact { + norm_mul_self_le x := by + induction x using UniformSpace.Completion.induction_on with + | hp => exact isClosed_le (by fun_prop) (by fun_prop) + | ih x => + rw [(h_StarCompletion_star_coe), ← UniformSpace.Completion.coe_mul] + simpa only [UniformSpace.Completion.norm_coe] using CStarRing.norm_mul_self_le x + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarAlgebra (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S) := + { (inferInstance : NormedRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : NormedAlgebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : CompleteSpace (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : StarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : StarModule ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)) with } + +structure Chain where + obj : ℕ → Type u + [cstar : ∀ n, CStarAlgebra (obj n)] + step : ∀ n, obj n →⋆ₐ[ℂ] obj (n+1) + norm_step : ∀ n x, ‖step n x‖ = ‖x‖ + +attribute [instance] Chain.cstar + +def Chain.map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) : S.obj i →⋆ₐ[ℂ] S.obj j := + Nat.leRecOn (C := fun n => S.obj i →⋆ₐ[ℂ] S.obj n) h + (fun {n} φ => (S.step n).comp φ) (StarAlgHom.id ℂ _) + +def Chain.system (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) : OAI.KirchbergRordam.CStarInductiveLimit.System.{u} := by + classical + have h_CStarInductiveLimit_Chain_map_self (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i : ℕ) : + S.map i i le_rfl = StarAlgHom.id ℂ _ := by simp [Chain.map, Nat.leRecOn_self] + have h_CStarInductiveLimit_Chain_map_succ (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) : + S.map i (j+1) (h.trans (Nat.le_succ j)) = (S.step j).comp (S.map i j h) := by + exact Nat.leRecOn_succ (C := fun n => S.obj i →⋆ₐ[ℂ] S.obj n) + (next := fun {n} φ => (S.step n).comp φ) h (StarAlgHom.id ℂ (S.obj i)) + have h_CStarInductiveLimit_Chain_map_map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j k : ℕ) (hij : i ≤ j) (hjk : j ≤ k) + (x : S.obj i) : S.map j k hjk (S.map i j hij x) = S.map i k (hij.trans hjk) x := by + induction k, hjk using Nat.le_induction with + | base => simp [h_CStarInductiveLimit_Chain_map_self] + | succ k hjk ih => + rw [(h_CStarInductiveLimit_Chain_map_succ S j k hjk), (h_CStarInductiveLimit_Chain_map_succ S i k (LE.le.trans hij hjk))] + exact congrArg (S.step k) ih + have h_CStarInductiveLimit_Chain_norm_map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) (x : S.obj i) : + ‖S.map i j h x‖ = ‖x‖ := by + induction j, h using Nat.le_induction with + | base => simp [h_CStarInductiveLimit_Chain_map_self] + | succ j h ih => + rw [(h_CStarInductiveLimit_Chain_map_succ S i j h)] + exact (S.norm_step j (S.map i j h x)).trans ih + exact { + obj := S.obj + map := S.map + map_self i x := by simp [h_CStarInductiveLimit_Chain_map_self] + map_map := (h_CStarInductiveLimit_Chain_map_map S) + norm_map := (h_CStarInductiveLimit_Chain_norm_map S) + } + +end KirchbergRordam.CStarInductiveLimit + +namespace KirchbergRordam.MaxTensor +variable (A B : Type*) [CStarAlgebra A] [CStarAlgebra B] + +structure CrossSeminorm extends Seminorm ℂ (A ⊗[ℂ] B) where + mul_le : ∀ x y, toSeminorm (x * y) ≤ toSeminorm x * toSeminorm y + star_eq : ∀ x, toSeminorm (star x) = toSeminorm x + cstar_eq : ∀ x, toSeminorm (star x * x) = toSeminorm x * toSeminorm x + tmul_le : ∀ a b, toSeminorm (a ⊗ₜ[ℂ] b) ≤ ‖a‖ * ‖b‖ + +instance : Inhabited (OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B) := ⟨{ + toSeminorm := 0 + mul_le := by simp + star_eq := by simp + cstar_eq := by simp + tmul_le := by intro a b; simp only [zero_apply]; positivity }⟩ + +variable {A B} + +def Raw (A B : Type*) [CStarAlgebra A] [CStarAlgebra B] := A ⊗[ℂ] B + +instance : Ring (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (Ring (A ⊗[ℂ] B)) + +instance : Algebra ℂ (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (Algebra ℂ (A ⊗[ℂ] B)) + +instance : StarRing (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (StarRing (A ⊗[ℂ] B)) + +def rawEquiv : (A ⊗[ℂ] B) ≃⋆ₐ[ℂ] OAI.KirchbergRordam.MaxTensor.Raw A B := + StarAlgEquiv.refl ℂ (A ⊗[ℂ] B) + +variable {C : Type*} [CStarAlgebra C] + +def liftRaw (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) : OAI.KirchbergRordam.MaxTensor.Raw A B →⋆ₐ[ℂ] C where + toAlgHom := _root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h + map_star' x := by + change _root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h (star x) = + star (_root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h x) + induction x using TensorProduct.inductionOn with + | add x y hx hy => simpa only [star_add, map_add] using congrArg₂ (· + ·) hx hy + | tmul a b => + change φ (star a) * ψ (star b) = star (φ a * ψ b) + rw [star_mul, ← map_star, ← map_star] + exact h (star a) (star b) + +def representationSeminorm (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) : OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B := by + classical + have h_MaxTensor_liftRaw_tmul (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) (a : A) (b : B) : + OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (a ⊗ₜ[ℂ] b) = φ a * ψ b := rfl + exact { + toSeminorm := (normSeminorm ℂ C).comp (OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h).toLinearMap + mul_le x y := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x * OAI.KirchbergRordam.MaxTensor.rawEquiv y)‖ ≤ + ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ * ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv y)‖ + rw [map_mul] + exact norm_mul_le _ _ + star_eq x := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (star (OAI.KirchbergRordam.MaxTensor.rawEquiv x))‖ = ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ + rw [map_star, norm_star] + cstar_eq x := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (star (OAI.KirchbergRordam.MaxTensor.rawEquiv x) * OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ = + ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ * ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ + rw [map_mul, map_star, CStarRing.norm_star_mul_self] + tmul_le a b := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (a ⊗ₜ[ℂ] b)‖ ≤ ‖a‖ * ‖b‖ + rw [h_MaxTensor_liftRaw_tmul] + exact (norm_mul_le _ _).trans (mul_le_mul + (NonUnitalStarAlgHom.norm_apply_le φ a) (NonUnitalStarAlgHom.norm_apply_le ψ b) + (norm_nonneg _) (norm_nonneg _)) + } + +end KirchbergRordam.MaxTensor + +namespace KirchbergRordam.Spatial +open Set Module NormedSpace +open scoped TensorProduct InnerProductSpace + +variable {H K : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] + +abbrev Hilbert (H K : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] := Completion (H ⊗[ℂ] K) + +def map (T : H →L[ℂ] H) (S : K →L[ℂ] K) : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K := + (TensorProduct.mapL T S).completion + +variable [CompleteSpace H] [CompleteSpace K] + +def left : (H →L[ℂ] H) →⋆ₐ[ℂ] (OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K) := by + classical + have h_Spatial_ext {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_add_left__simp_1_1 (a b : H ⊗[ℂ] K) : (a : Completion (H ⊗[ℂ] K)) + (b : Completion (H ⊗[ℂ] K)) = ((a + b : H ⊗[ℂ] K) : Completion (H ⊗[ℂ] K)) := (Completion.coe_add a b).symm + have h_Spatial_map_coe (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_add_left (T U : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T + U) S = OAI.KirchbergRordam.Spatial.map T S + OAI.KirchbergRordam.Spatial.map U S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_add_left, (@h_Spatial_map_add_left__simp_1_1)] + have h_Spatial_map_mul (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_map_one : OAI.KirchbergRordam.Spatial.map (1 : H →L[ℂ] H) (1 : K →L[ℂ] K) = 1 := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, show (1 : H →L[ℂ] H) = ContinuousLinearMap.id ℂ H from rfl, + show (1 : K →L[ℂ] K) = ContinuousLinearMap.id ℂ K from rfl] + have h_Spatial_map_smul_left (z : ℂ) (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (z • T) S = z • OAI.KirchbergRordam.Spatial.map T S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_smul_left, ← Completion.coe_smul] + have h_Spatial_map_inner_algebraic (T : H →L[ℂ] H) (S : K →L[ℂ] K) + (x y : H ⊗[ℂ] K) : + ⟪TensorProduct.mapL (star T) (star S) x, y⟫_ℂ = + ⟪x, TensorProduct.mapL T S y⟫_ℂ := by + induction x using TensorProduct.inductionOn with + | add x z hx hz => simp only [map_add, inner_add_left, hx, hz] + | tmul a b => + induction y using TensorProduct.inductionOn with + | add y z hy hz => simp only [map_add, inner_add_right, hy, hz] + | tmul c d => + simp only [TensorProduct.mapL_tmul, TensorProduct.inner_tmul, + ContinuousLinearMap.star_eq_adjoint, ContinuousLinearMap.adjoint_inner_left] + have h_Spatial_map_inner (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x y : OAI.KirchbergRordam.Spatial.Hilbert H K) : + ⟪OAI.KirchbergRordam.Spatial.map (star T) (star S) x, y⟫_ℂ = ⟪x, OAI.KirchbergRordam.Spatial.map T S y⟫_ℂ := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simpa [h_Spatial_map_coe] using h_Spatial_map_inner_algebraic T S x y + have h_Spatial_map_star (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (star T) (star S) = star (OAI.KirchbergRordam.Spatial.map T S) := by + apply ContinuousLinearMap.ext + intro x + apply ext_inner_right ℂ + intro y + rw [h_Spatial_map_inner, ContinuousLinearMap.star_eq_adjoint, + ContinuousLinearMap.adjoint_inner_left] + exact { + toFun T := OAI.KirchbergRordam.Spatial.map T 1 + map_zero' := by apply h_Spatial_ext; intro x; simp [OAI.KirchbergRordam.Spatial.map] + map_one' := h_Spatial_map_one + map_add' T U := h_Spatial_map_add_left T U 1 + map_mul' T U := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_mul T U (1 : K →L[ℂ] K) 1 + commutes' z := by + change OAI.KirchbergRordam.Spatial.map (z • 1) 1 = z • 1 + rw [h_Spatial_map_smul_left, h_Spatial_map_one] + map_star' T := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_star T (1 : K →L[ℂ] K) + } + +def right : (K →L[ℂ] K) →⋆ₐ[ℂ] (OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K) := by + classical + have h_Spatial_ext {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_add_right__simp_1_1 (a b : H ⊗[ℂ] K) : (a : Completion (H ⊗[ℂ] K)) + (b : Completion (H ⊗[ℂ] K)) = ((a + b : H ⊗[ℂ] K) : Completion (H ⊗[ℂ] K)) := (Completion.coe_add a b).symm + have h_Spatial_map_coe (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_add_right (T : H →L[ℂ] H) (S U : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T (S + U) = OAI.KirchbergRordam.Spatial.map T S + OAI.KirchbergRordam.Spatial.map T U := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_add_right, (@h_Spatial_map_add_right__simp_1_1)] + have h_Spatial_map_mul (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_map_one : OAI.KirchbergRordam.Spatial.map (1 : H →L[ℂ] H) (1 : K →L[ℂ] K) = 1 := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, show (1 : H →L[ℂ] H) = ContinuousLinearMap.id ℂ H from rfl, + show (1 : K →L[ℂ] K) = ContinuousLinearMap.id ℂ K from rfl] + have h_Spatial_map_smul_right (z : ℂ) (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T (z • S) = z • OAI.KirchbergRordam.Spatial.map T S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_smul_right, ← Completion.coe_smul] + have h_Spatial_map_inner_algebraic (T : H →L[ℂ] H) (S : K →L[ℂ] K) + (x y : H ⊗[ℂ] K) : + ⟪TensorProduct.mapL (star T) (star S) x, y⟫_ℂ = + ⟪x, TensorProduct.mapL T S y⟫_ℂ := by + induction x using TensorProduct.inductionOn with + | add x z hx hz => simp only [map_add, inner_add_left, hx, hz] + | tmul a b => + induction y using TensorProduct.inductionOn with + | add y z hy hz => simp only [map_add, inner_add_right, hy, hz] + | tmul c d => + simp only [TensorProduct.mapL_tmul, TensorProduct.inner_tmul, + ContinuousLinearMap.star_eq_adjoint, ContinuousLinearMap.adjoint_inner_left] + have h_Spatial_map_inner (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x y : OAI.KirchbergRordam.Spatial.Hilbert H K) : + ⟪OAI.KirchbergRordam.Spatial.map (star T) (star S) x, y⟫_ℂ = ⟪x, OAI.KirchbergRordam.Spatial.map T S y⟫_ℂ := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simpa [h_Spatial_map_coe] using h_Spatial_map_inner_algebraic T S x y + have h_Spatial_map_star (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (star T) (star S) = star (OAI.KirchbergRordam.Spatial.map T S) := by + apply ContinuousLinearMap.ext + intro x + apply ext_inner_right ℂ + intro y + rw [h_Spatial_map_inner, ContinuousLinearMap.star_eq_adjoint, + ContinuousLinearMap.adjoint_inner_left] + exact { + toFun S := OAI.KirchbergRordam.Spatial.map 1 S + map_zero' := by apply h_Spatial_ext; intro x; simp [OAI.KirchbergRordam.Spatial.map] + map_one' := h_Spatial_map_one + map_add' T U := h_Spatial_map_add_right 1 T U + map_mul' T U := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_mul (1 : H →L[ℂ] H) 1 T U + commutes' z := by + change OAI.KirchbergRordam.Spatial.map 1 (z • 1) = z • 1 + rw [h_Spatial_map_smul_right, h_Spatial_map_one] + map_star' S := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_star (1 : H →L[ℂ] H) S + } + +end KirchbergRordam.Spatial + +namespace KirchbergRordam.MinTensor +open scoped TensorProduct +universe u +variable (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] + +structure RepresentationPair where + H : Type u + K : Type u + normH : NormedAddCommGroup H + innerH : InnerProductSpace ℂ H + completeH : CompleteSpace H + normK : NormedAddCommGroup K + innerK : InnerProductSpace ℂ K + completeK : CompleteSpace K + leftRep : A →⋆ₐ[ℂ] (H →L[ℂ] H) + rightRep : B →⋆ₐ[ℂ] (K →L[ℂ] K) + +attribute [instance] RepresentationPair.normH RepresentationPair.innerH + RepresentationPair.completeH RepresentationPair.normK RepresentationPair.innerK + RepresentationPair.completeK +variable {A B} +def RepresentationPair.left (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + A →⋆ₐ[ℂ] (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K) := + Spatial.left.comp ρ.leftRep + +def RepresentationPair.right (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + B →⋆ₐ[ℂ] (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K) := + Spatial.right.comp ρ.rightRep + +def RepresentationPair.crossSeminorm (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + MaxTensor.CrossSeminorm A B := by + classical + have h_Spatial_ext {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_coe {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_mul {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_left_right_commute {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] [inst6 : CompleteSpace H] [inst7 : CompleteSpace K] (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + Commute (OAI.KirchbergRordam.Spatial.left (K := K) T) (OAI.KirchbergRordam.Spatial.right (H := H) S) := by + change OAI.KirchbergRordam.Spatial.map T 1 * OAI.KirchbergRordam.Spatial.map 1 S = OAI.KirchbergRordam.Spatial.map 1 S * OAI.KirchbergRordam.Spatial.map T 1 + rw [← h_Spatial_map_mul, ← h_Spatial_map_mul] + simp + have h_MinTensor_RepresentationPair_commute (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) (a : A) (b : B) : + Commute (ρ.left a) (ρ.right b) := + (@h_Spatial_left_right_commute) _ _ + exact + MaxTensor.representationSeminorm (A := A) (B := B) + (C := (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K)) + ρ.left ρ.right (h_MinTensor_RepresentationPair_commute ρ) + +def spatialIndex : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B) → MaxTensor.CrossSeminorm A B + | none => default + | some ρ => ρ.crossSeminorm + +def seminorm : Seminorm ℂ (A ⊗[ℂ] B) := + ⨆ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm + +end KirchbergRordam.MinTensor +namespace KirchbergRordam.MinTensor +open scoped TensorProduct +open Set Module NormedSpace +universe u +variable {A B : Type u} [CStarAlgebra A] [CStarAlgebra B] +local instance instRingTensorProductComplex_analysis : Ring (A ⊗[ℂ] B) := + _root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B) + +end KirchbergRordam.MinTensor + +namespace KirchbergRordam.MinTensor +universe u +variable (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] + +def Raw : Type u := A ⊗[ℂ] B + +variable {A B} +instance : Ring (OAI.KirchbergRordam.MinTensor.Raw A B) := + _root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B) + +instance : Algebra ℂ (OAI.KirchbergRordam.MinTensor.Raw A B) := _root_.Algebra.TensorProduct.instAlgebra + +instance instStarRingRaw : StarRing (OAI.KirchbergRordam.MinTensor.Raw A B) := + inferInstanceAs (StarRing (MaxTensor.Raw A B)) + +def rawRingSeminorm : RingSeminorm (OAI.KirchbergRordam.MinTensor.Raw A B) := by + classical + have h_MaxTensor_bounded_at {A : Type u} {B : Type u} [inst2 : CStarAlgebra A] [inst3 : CStarAlgebra B] (x : A ⊗[ℂ] B) : + ∃ C : ℝ, ∀ p : OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B, p.toSeminorm x ≤ C := by + induction x using TensorProduct.inductionOn with + | tmul a b => exact ⟨‖a‖ * ‖b‖, fun p => p.tmul_le a b⟩ + | add x y hx hy => + obtain ⟨C, hC⟩ := hx + obtain ⟨D, hD⟩ := hy + exact ⟨C + D, fun p => (map_add_le_add p.toSeminorm x y).trans + (add_le_add (hC p) (hD p))⟩ + have h_MinTensor_bounded : BddAbove (Set.range (fun ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B) => + (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm)) := by + rw [Seminorm.bddAbove_range_iff] + intro x + obtain ⟨C,hC⟩ := (@h_MaxTensor_bounded_at) x + exact ⟨C,by rintro _ ⟨ρ,rfl⟩; exact hC _⟩ + have h_MinTensor_seminorm_apply (x : A ⊗[ℂ] B) : + OAI.KirchbergRordam.MinTensor.seminorm x=⨆ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x := + Seminorm.iSup_apply h_MinTensor_bounded + have h_MinTensor_le_seminorm (ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B)) (x : A ⊗[ℂ] B) : + (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x ≤ OAI.KirchbergRordam.MinTensor.seminorm x := by + rw [h_MinTensor_seminorm_apply] + apply le_ciSup _ ρ + obtain ⟨C,hC⟩ := (@h_MaxTensor_bounded_at) x + exact ⟨C,by rintro _ ⟨ρ,rfl⟩; exact hC _⟩ + have h_MinTensor_seminorm_le {x : A ⊗[ℂ] B} {C : ℝ} + (h : ∀ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x ≤ C) : + OAI.KirchbergRordam.MinTensor.seminorm x ≤ C := by + rw [h_MinTensor_seminorm_apply] + exact ciSup_le h + have h_MinTensor_seminorm_mul_le (x y : A ⊗[ℂ] B) : + @LE.le ℝ Real.instLE + (OAI.KirchbergRordam.MinTensor.seminorm (@Mul.mul (A ⊗[ℂ] B) + (_root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B)).toMul x y)) + (@Mul.mul ℝ Real.instMul (OAI.KirchbergRordam.MinTensor.seminorm x) (OAI.KirchbergRordam.MinTensor.seminorm y)) := by + apply h_MinTensor_seminorm_le + intro ρ + exact ((OAI.KirchbergRordam.MinTensor.spatialIndex ρ).mul_le x y).trans (mul_le_mul (h_MinTensor_le_seminorm ρ x) + (h_MinTensor_le_seminorm ρ y) (apply_nonneg _ _) (apply_nonneg _ _)) + exact { + __ := (OAI.KirchbergRordam.MinTensor.seminorm (A := A) (B := B)).toAddGroupSeminorm + mul_le' := h_MinTensor_seminorm_mul_le + } + +instance : SeminormedRing (OAI.KirchbergRordam.MinTensor.Raw A B) := OAI.KirchbergRordam.MinTensor.rawRingSeminorm.toSeminormedRing + +abbrev Algebra (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] := + UniformSpace.Completion (OAI.KirchbergRordam.MinTensor.Raw A B) + +end KirchbergRordam.MinTensor + +namespace KirchbergRordam.MatrixTensor +open scoped Matrix Kronecker +variable {ι κ : Type*} [Fintype ι] [Fintype κ] [DecidableEq ι] [DecidableEq κ] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def leftMatrixAlgebra : Matrix ι ι ℂ →⋆ₐ[ℂ] + Matrix (ι × κ) (ι × κ) ℂ where + toFun a := a ⊗ₖ (1 : Matrix κ κ ℂ) + map_zero' := Matrix.zero_kronecker _ + map_one' := Matrix.one_kronecker_one + map_add' a b := Matrix.add_kronecker _ _ _ + map_mul' a b := by + simpa only [mul_one] using Matrix.mul_kronecker_mul a b + (1 : Matrix κ κ ℂ) (1 : Matrix κ κ ℂ) + commutes' z := by + simp only [Algebra.algebraMap_eq_smul_one, Matrix.smul_kronecker, + Matrix.one_kronecker_one] + map_star' a := by + change aᴴ ⊗ₖ (1 : Matrix κ κ ℂ) = (a ⊗ₖ 1)ᴴ + rw [Matrix.conjTranspose_kronecker, Matrix.conjTranspose_one] + +def rightMatrixAlgebra : Matrix κ κ ℂ →⋆ₐ[ℂ] + Matrix (ι × κ) (ι × κ) ℂ where + toFun a := (1 : Matrix ι ι ℂ) ⊗ₖ a + map_zero' := Matrix.kronecker_zero _ + map_one' := Matrix.one_kronecker_one + map_add' a b := Matrix.kronecker_add _ _ _ + map_mul' a b := by + simpa only [mul_one] using Matrix.mul_kronecker_mul + (1 : Matrix ι ι ℂ) (1 : Matrix ι ι ℂ) a b + commutes' z := by + simp only [Algebra.algebraMap_eq_smul_one, Matrix.kronecker_smul, + Matrix.one_kronecker_one] + map_star' a := by + change (1 : Matrix ι ι ℂ) ⊗ₖ aᴴ = (1 ⊗ₖ a)ᴴ + rw [Matrix.conjTranspose_kronecker, Matrix.conjTranspose_one] + +def leftMatrix : OAI.KirchbergRordam.MatrixTensor.Mat ι →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixTensor.Mat (ι×κ) := + CStarMatrix.ofMatrixStarAlgEquiv.toStarAlgHom.comp + (OAI.KirchbergRordam.MatrixTensor.leftMatrixAlgebra.comp CStarMatrix.ofMatrixStarAlgEquiv.symm.toStarAlgHom) + +def rightMatrix : OAI.KirchbergRordam.MatrixTensor.Mat κ →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixTensor.Mat (ι×κ) := + CStarMatrix.ofMatrixStarAlgEquiv.toStarAlgHom.comp + (OAI.KirchbergRordam.MatrixTensor.rightMatrixAlgebra.comp CStarMatrix.ofMatrixStarAlgEquiv.symm.toStarAlgHom) + +end KirchbergRordam.MatrixTensor + +namespace KirchbergRordam.PrimeDimensionDrop +open MatrixTensor +open scoped Matrix Kronecker ComplexOrder CStarAlgebra + +abbrev Fiber (p q : ℕ) := OAI.KirchbergRordam.MatrixTensor.Mat (Fin p × Fin q) + +def eval (p q : ℕ) (t : unitInterval) : + C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q where + toFun f := f t + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def subalgebra (p q : ℕ) : StarSubalgebra ℂ C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + (OAI.KirchbergRordam.MatrixTensor.leftMatrix (ι := Fin p) (κ := Fin q)).range.comap (OAI.KirchbergRordam.PrimeDimensionDrop.eval p q 0) ⊓ + (OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι := Fin p) (κ := Fin q)).range.comap (OAI.KirchbergRordam.PrimeDimensionDrop.eval p q 1) + +instance (p q : ℕ) : FiniteDimensional ℂ (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + inferInstanceAs (FiniteDimensional ℂ (Matrix (Fin p × Fin q) (Fin p × Fin q) ℂ)) + +instance (p q : ℕ) : IsClosed (OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q : Set C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) := by + change IsClosed ((fun f : C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) => f 0) ⁻¹' + ((OAI.KirchbergRordam.MatrixTensor.leftMatrix (ι := Fin p) (κ := Fin q)).range : Set (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) ∩ + (fun f : C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) => f 1) ⁻¹' + ((OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι := Fin p) (κ := Fin q)).range : Set (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q))) + exact ((OAI.KirchbergRordam.MatrixTensor.leftMatrix.range.toSubalgebra.toSubmodule.closed_of_finiteDimensional).preimage + (continuous_eval_const (0 : unitInterval))).inter + ((OAI.KirchbergRordam.MatrixTensor.rightMatrix.range.toSubalgebra.toSubmodule.closed_of_finiteDimensional).preimage + (continuous_eval_const (1 : unitInterval))) + +abbrev Algebra (p q : ℕ) := OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q + +instance (p q : ℕ) : SubringClass + (StarSubalgebra ℂ C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + StarSubalgebra.subringClass (R := ℂ) (A := C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) + +instance (p q : ℕ) : CStarAlgebra (OAI.KirchbergRordam.PrimeDimensionDrop.Algebra p q) := StarSubalgebra.cstarAlgebra (OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q) + +end KirchbergRordam.PrimeDimensionDrop + +namespace KirchbergRordam.UnitaryPaths + +variable {A : Type*} [CStarAlgebra A] + +def phase (t : unitInterval) : ℂ := Complex.exp (((t:ℝ) * Real.pi) * Complex.I) + +def involutionValue (U : A) (t : unitInterval) : A := + ((1 + OAI.KirchbergRordam.UnitaryPaths.phase t) / 2) • (1:A) + ((1 - OAI.KirchbergRordam.UnitaryPaths.phase t) / 2) • U + +def involutionPath (U : unitary A) (hs : star (U:A) = U) : Path 1 U := by + classical + have h_UnitaryPaths_phase_continuous : Continuous OAI.KirchbergRordam.UnitaryPaths.phase := by unfold OAI.KirchbergRordam.UnitaryPaths.phase; fun_prop + have h_UnitaryPaths_involutionValue_continuous (U : A) : Continuous (OAI.KirchbergRordam.UnitaryPaths.involutionValue U) := by + unfold OAI.KirchbergRordam.UnitaryPaths.involutionValue + fun_prop + have h_UnitaryPaths_phase_unitary (t : unitInterval) : star (OAI.KirchbergRordam.UnitaryPaths.phase t) * OAI.KirchbergRordam.UnitaryPaths.phase t = 1 := by + have hn : ‖OAI.KirchbergRordam.UnitaryPaths.phase t‖ = 1 := by + simpa [OAI.KirchbergRordam.UnitaryPaths.phase, Complex.ofReal_mul] using Complex.norm_exp_ofReal_mul_I ((t:ℝ) * Real.pi) + rw [Complex.star_def, ← Complex.normSq_eq_conj_mul_self, Complex.normSq_eq_norm_sq, hn] + norm_num + have h_UnitaryPaths_involutionValue_unitary (U : A) (hs : star U = U) (hm : U * U = 1) + (t : unitInterval) : OAI.KirchbergRordam.UnitaryPaths.involutionValue U t ∈ unitary A := by + have hz := h_UnitaryPaths_phase_unitary t + have h1 : (star ((1:ℂ)+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + (star ((1:ℂ)-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)=1 := by + simp only [star_add,star_sub,star_one] + calc + _ = (1+star (OAI.KirchbergRordam.UnitaryPaths.phase t)*OAI.KirchbergRordam.UnitaryPaths.phase t)/2 := by ring + _ = 1 := by rw [hz]; norm_num + have h2 : (star ((1:ℂ)+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + (star ((1:ℂ)-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)=0 := by + simp only [star_add,star_sub,star_one] + calc + _ = (1-star (OAI.KirchbergRordam.UnitaryPaths.phase t)*OAI.KirchbergRordam.UnitaryPaths.phase t)/2 := by ring + _ = 0 := by rw [hz]; norm_num + have h : star (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t) * OAI.KirchbergRordam.UnitaryPaths.involutionValue U t = 1 := by + simp only [OAI.KirchbergRordam.UnitaryPaths.involutionValue, star_add, star_smul, star_one, hs, star_div₀, + star_ofNat, star_sub, smul_add, add_mul, mul_add, smul_mul_assoc, + mul_smul_comm, smul_smul, one_mul, mul_one, hm] + calc + _ = (((1+star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + ((1-star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)) • (1:A) + + (((1+star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + ((1-star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)) • U := by + rw [add_smul, add_smul]; module + _ = 1 := by + simp only [star_add, star_sub, star_one] at h1 h2 + rw [h1, h2, one_smul, zero_smul, add_zero] + refine ⟨h, ?_⟩ + have hc : Commute (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t) (star (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t)) := by + unfold OAI.KirchbergRordam.UnitaryPaths.involutionValue + simp only [star_add, star_smul, star_one, hs] + exact ((Commute.one_left _).smul_left _).add_left + ((((Commute.one_right U).smul_right _).add_right + ((Commute.refl U).smul_right _)).smul_left _) + exact hc.eq.trans h + have h_UnitaryPaths_phase_one : OAI.KirchbergRordam.UnitaryPaths.phase 1 = -1 := by simp [OAI.KirchbergRordam.UnitaryPaths.phase, Complex.exp_pi_mul_I] + have h_UnitaryPaths_phase_zero : OAI.KirchbergRordam.UnitaryPaths.phase 0 = 1 := by simp [OAI.KirchbergRordam.UnitaryPaths.phase] + exact { + toFun t := ⟨OAI.KirchbergRordam.UnitaryPaths.involutionValue (U:A) t, + h_UnitaryPaths_involutionValue_unitary (U:A) hs (by simpa only [hs] using Unitary.coe_star_mul_self U) t⟩ + continuous_toFun := (h_UnitaryPaths_involutionValue_continuous _).subtype_mk _ + source' := by apply Subtype.ext; simp [h_UnitaryPaths_phase_zero, OAI.KirchbergRordam.UnitaryPaths.involutionValue] + target' := by apply Subtype.ext; simp [h_UnitaryPaths_phase_one, OAI.KirchbergRordam.UnitaryPaths.involutionValue] + } + +end KirchbergRordam.UnitaryPaths + +namespace KirchbergRordam.MatrixPermutationPath +open scoped Matrix +variable {ι : Type*} [Fintype ι] [DecidableEq ι] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def perm (σ : Equiv.Perm ι) : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) := + ⟨CStarMatrix.ofMatrix (σ⁻¹.permMatrix ℂ), by + constructor + · change (σ⁻¹.permMatrix ℂ)ᴴ * σ⁻¹.permMatrix ℂ = 1 + rw [Matrix.conjTranspose_permMatrix, ← Matrix.permMatrix_mul] + simp + · change σ⁻¹.permMatrix ℂ * (σ⁻¹.permMatrix ℂ)ᴴ = 1 + rw [Matrix.conjTranspose_permMatrix, ← Matrix.permMatrix_mul] + simp⟩ + +def path (σ τ : Equiv.Perm ι) : Path (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) (OAI.KirchbergRordam.MatrixPermutationPath.perm τ) := by + classical + have h_MatrixPermutationPath_perm_mul (σ τ : Equiv.Perm ι) : OAI.KirchbergRordam.MatrixPermutationPath.perm (σ*τ) = OAI.KirchbergRordam.MatrixPermutationPath.perm σ * OAI.KirchbergRordam.MatrixPermutationPath.perm τ := by + apply Subtype.ext + change ((σ*τ)⁻¹).permMatrix ℂ = σ⁻¹.permMatrix ℂ * τ⁻¹.permMatrix ℂ + simp + have h_MatrixPermutationPath_perm_one : OAI.KirchbergRordam.MatrixPermutationPath.perm (1 : Equiv.Perm ι) = 1 := by + apply Subtype.ext + change (1⁻¹ : Equiv.Perm ι).permMatrix ℂ = 1 + simp + have h_MatrixPermutationPath_perm_swap_selfadjoint (i j : ι) : star (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j) : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) = + (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j) : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) := by + change ((Equiv.swap i j)⁻¹.permMatrix ℂ)ᴴ = (Equiv.swap i j)⁻¹.permMatrix ℂ + simp + have h_MatrixPermutationPath_joined_one_perm (σ : Equiv.Perm ι) : Joined (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) := by + induction σ using Equiv.Perm.swap_induction_on with + | one => simpa [h_MatrixPermutationPath_perm_one] using Joined.refl (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) + | swap_mul σ i j hij ih => + rw [h_MatrixPermutationPath_perm_mul] + have hi : Joined (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j)) := + ⟨UnitaryPaths.involutionPath _ (h_MatrixPermutationPath_perm_swap_selfadjoint i j)⟩ + simpa only [one_mul] using hi.mul ih + exact + ((h_MatrixPermutationPath_joined_one_perm σ).symm.trans (h_MatrixPermutationPath_joined_one_perm τ)).somePath + +end KirchbergRordam.MatrixPermutationPath + +namespace KirchbergRordam.MatrixDiagonalPath +open scoped ComplexOrder CStarAlgebra Matrix +variable {ι κ ν : Type*} [Fintype ι] [DecidableEq ι] + [Fintype κ] [instDecidableEqκ : DecidableEq κ] [Fintype ν] [DecidableEq ν] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def block : (ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι) where + toFun a := CStarMatrix.ofMatrix (Matrix.blockDiagonal a) + map_zero' := Matrix.blockDiagonal_zero + map_one' := Matrix.blockDiagonal_one + map_add' := Matrix.blockDiagonal_add + map_mul' := Matrix.blockDiagonal_mul + commutes' z := by + change Matrix.blockDiagonal (fun _ : ι => (algebraMap ℂ (Matrix κ κ ℂ)) z) = + algebraMap ℂ (Matrix (κ × ι) (κ × ι) ℂ) z + simp only [Algebra.algebraMap_eq_smul_one] + exact (Matrix.blockDiagonal_smul z (1 : ι → Matrix κ κ ℂ)).trans + (congrArg (z • ·) Matrix.blockDiagonal_one) + map_star' a := Matrix.blockDiagonal_conjTranspose a |>.symm + +def evaluationBlock (ξ : ι → C(unitInterval, unitInterval)) (t : unitInterval) : + C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι) where + toFun f := OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => f (ξ i t)) + map_zero' := map_zero OAI.KirchbergRordam.MatrixDiagonalPath.block + map_one' := map_one OAI.KirchbergRordam.MatrixDiagonalPath.block + map_add' first second := map_add OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => first (ξ index t)) (fun index => second (ξ index t)) + map_mul' first second := map_mul OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => first (ξ index t)) (fun index => second (ξ index t)) + commutes' z := OAI.KirchbergRordam.MatrixDiagonalPath.block.commutes z + map_star' path := map_star OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => path (ξ index t)) + +def diagonal (ξ : ι → C(unitInterval, unitInterval)) : + C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι)) := by + classical + have h_MatrixDiagonalPath_evaluationBlock_continuous (ξ : ι → C(unitInterval, unitInterval)) + (f : C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ)) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f) := + (map_continuous OAI.KirchbergRordam.MatrixDiagonalPath.block).comp (continuous_pi (fun i => f.continuous.comp (ξ i).continuous)) + exact { + toFun f := ⟨fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f, h_MatrixDiagonalPath_evaluationBlock_continuous ξ f⟩ + map_zero' := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_zero) _) _ + map_one' := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_one) _) _ + map_add' f g := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_add f g) _) _ + map_mul' f g := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_mul f g) _) _ + commutes' z := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).commutes z) _) _ + map_star' f := by ext t; exact congrFun (congrFun (map_star (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t) f) _) _ + } + +def interpolate (e₀ e₁ : κ ≃ ν) (t : unitInterval) : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ ≃⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν := + (CStarMatrix.reindexₐ ℂ ℂ e₀).trans + (Unitary.conjStarAlgAut ℂ _ + ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t)) + +end KirchbergRordam.MatrixDiagonalPath + +namespace KirchbergRordam.MatrixBlockReindex +open MatrixTensor (leftMatrix rightMatrix) +open MatrixDiagonalPath +open scoped ComplexOrder CStarAlgebra Matrix Kronecker +variable {P Q L R S T : Type*} + [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] + [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] + +def sumBlock : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P × OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P ⊕ Q) where + toFun a := CStarMatrix.ofMatrix (Matrix.fromBlocks a.1 0 0 a.2) + map_zero' := by ext i j; cases i <;> cases j <;> rfl + map_one' := by + change Matrix.fromBlocks (1 : Matrix P P ℂ) 0 0 (1 : Matrix Q Q ℂ) = 1 + exact Matrix.fromBlocks_one + map_add' a b := by ext i j; cases i <;> cases j <;> simp [Matrix.fromBlocks] + map_mul' a b := by + change Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1 * CStarMatrix.ofMatrix.symm b.1) 0 0 + (CStarMatrix.ofMatrix.symm a.2 * CStarMatrix.ofMatrix.symm b.2) = + Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1) 0 0 (CStarMatrix.ofMatrix.symm a.2) * + Matrix.fromBlocks (CStarMatrix.ofMatrix.symm b.1) 0 0 (CStarMatrix.ofMatrix.symm b.2) + simp only [Matrix.fromBlocks_multiply, Matrix.mul_zero, Matrix.zero_mul, add_zero, zero_add] + commutes' z := by + ext i j; cases i <;> cases j <;> + simp [Algebra.algebraMap_eq_smul_one, Matrix.fromBlocks, CStarMatrix.one_apply] + map_star' a := by + change Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1)ᴴ 0 0 + (CStarMatrix.ofMatrix.symm a.2)ᴴ = + (Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1) 0 0 + (CStarMatrix.ofMatrix.symm a.2))ᴴ + simp only [Matrix.fromBlocks_conjTranspose, Matrix.conjTranspose_zero] + +end KirchbergRordam.MatrixBlockReindex + +namespace KirchbergRordam.MatrixBlockReindex +open MatrixDiagonalPath +open MatrixTensor (leftMatrix rightMatrix) +open scoped ComplexOrder CStarAlgebra Matrix +variable {P Q R S : Type*} [Fintype P] [Fintype Q] [Fintype R] [Fintype S] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [DecidableEq R] [DecidableEq S] +end KirchbergRordam.MatrixBlockReindex + +namespace KirchbergRordam.BalancedDropSystem + +def cardEquiv {α β : Type*} [Fintype α] [Fintype β] + (h : Fintype.card α = Fintype.card β) : α ≃ β := + Classical.choice ((Fintype.card_eq.mp h)) + +def half : unitInterval := by + classical + have h_BalancedDropSystem_half_mem : (1 / 2 : ℝ) ∈ Set.Icc (0 : ℝ) 1 := by + constructor <;> norm_num + exact + ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv Real.instOne.one + (Real.instNatCast.natCast 2), h_BalancedDropSystem_half_mem⟩ + +def lowerPath : C(unitInterval, unitInterval) := + ⟨fun point => ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv point.val + (Real.instNatCast.natCast 2), by + change (point : ℝ) / 2 ∈ Set.Icc (0 : ℝ) 1 + constructor <;> linarith [point.property.1, point.property.2]⟩, by + apply Continuous.subtype_mk + change Continuous (fun point : unitInterval => (point : ℝ) / 2) + fun_prop⟩ + +def upperPath : C(unitInterval, unitInterval) := + ⟨fun point => ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv + (@Add.add ℝ Real.instAdd point.val Real.instOne.one) + (Real.instNatCast.natCast 2), by + change ((point : ℝ) + 1) / 2 ∈ Set.Icc (0 : ℝ) 1 + constructor <;> linarith [point.property.1, point.property.2]⟩, by + apply Continuous.subtype_mk + change Continuous (fun point : unitInterval => ((point : ℝ) + 1) / 2) + fun_prop⟩ + +end KirchbergRordam.BalancedDropSystem + +namespace KirchbergRordam.GeneralBlockReindex +open MatrixBlockReindex MatrixDiagonalPath + +open scoped CStarAlgebra Matrix +variable {P Q L R S T U : Type*} + [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] + [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] +def repackLeft (hL : Q × L ≃ U × T) (hR : R ≃ S × T) : + (P × Q) × (L ⊕ R) ≃ ((P × U) ⊕ ((P × Q) × S)) × T where + toFun x := match x.2 with + | .inl l => (.inl (x.1.1,(hL (x.1.2,l)).1),(hL (x.1.2,l)).2) + | .inr r => (.inr (x.1,(hR r).1),(hR r).2) + invFun x := match x.1 with + | .inl y => ((y.1,(hL.symm (y.2,x.2)).1),.inl (hL.symm (y.2,x.2)).2) + | .inr y => (y.1,.inr (hR.symm (y.2,x.2))) + left_inv x := by rcases x with ⟨⟨i,j⟩,l|r⟩ <;> simp + right_inv x := by rcases x with ⟨⟨i,u⟩|⟨ij,s⟩,t⟩ <;> simp + +def repackRight (hL : P × L ≃ T × U) (hR : R ≃ T × S) : + (P × Q) × (L ⊕ R) ≃ T × ((Q × U) ⊕ ((P × Q) × S)) := by + classical + have h_GeneralBlockReindex_left_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inl l) = (.inl (i,(hL (j,l)).1),(hL (j,l)).2) := rfl + have h_GeneralBlockReindex_left_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inr r) = (.inr ((i,j),(hR r).1),(hR r).2) := rfl + exact { + toFun x := match x.2 with + | .inl l => ((hL (x.1.1,l)).1,.inl (x.1.2,(hL (x.1.1,l)).2)) + | .inr r => ((hR r).1,.inr (x.1,(hR r).2)) + invFun x := match x.2 with + | .inl y => (((hL.symm (x.1,y.2)).1,y.1),.inl (hL.symm (x.1,y.2)).2) + | .inr y => (y.1,.inr (hR.symm (x.1,y.2))) + left_inv x := by rcases x with ⟨⟨i,j⟩,l|r⟩ <;> simp + right_inv x := by rcases x with ⟨t,⟨j,u⟩|⟨ij,s⟩⟩ <;> simp + } + +end KirchbergRordam.GeneralBlockReindex + +namespace KirchbergRordam.GeneralDropSystem +open MatrixDiagonalPath MatrixBlockReindex +open BalancedDropSystem (half lowerPath upperPath) +open scoped CStarAlgebra Matrix ComplexOrder + +structure Data (p q P Q : ℕ) where + lower : ℕ + upper : ℕ + middle : ℕ + zeroEnd : ℕ + zeroMid : ℕ + oneEnd : ℕ + oneMid : ℕ + lower_pos : 0 rfl + right_inv x := by rcases x with x|x|x <;> rfl + +def zeroReindex : OAI.KirchbergRordam.GeneralDropSystem.Index d ≃ Fin P × Fin Q := + (GeneralBlockReindex.repackLeft (OAI.KirchbergRordam.GeneralDropSystem.zeroLow d) (OAI.KirchbergRordam.GeneralDropSystem.zeroMid d)).trans + (Equiv.prodCongr (OAI.KirchbergRordam.GeneralDropSystem.zeroOuter d) (Equiv.refl _)) + +def oneReindex : OAI.KirchbergRordam.GeneralDropSystem.Index d ≃ Fin P × Fin Q := + (Equiv.prodCongr (Equiv.refl _) (OAI.KirchbergRordam.GeneralDropSystem.slotSwap d)).trans + ((GeneralBlockReindex.repackRight (OAI.KirchbergRordam.GeneralDropSystem.oneLow d) (OAI.KirchbergRordam.GeneralDropSystem.oneMid d)).trans + (Equiv.prodCongr (Equiv.refl _) (OAI.KirchbergRordam.GeneralDropSystem.oneOuter d))) + +def eigenpath : OAI.KirchbergRordam.GeneralDropSystem.Slot d → C(unitInterval,unitInterval) := + Sum.elim (fun _ => OAI.KirchbergRordam.BalancedDropSystem.lowerPath) (Sum.elim (fun _ => OAI.KirchbergRordam.BalancedDropSystem.upperPath) (fun _ => ContinuousMap.const _ OAI.KirchbergRordam.BalancedDropSystem.half)) + +section + +def interpolatedEvaluation.{sourceLevel, blockLevel, targetLevel} + {SourceIndex : Type sourceLevel} {BlockIndex : Type blockLevel} + {TargetIndex : Type targetLevel} + [sourceFintype : Fintype SourceIndex] [sourceDecidableEq : DecidableEq SourceIndex] + [blockFintype : Fintype BlockIndex] [blockDecidableEq : DecidableEq BlockIndex] + [targetFintype : Fintype TargetIndex] [targetDecidableEq : DecidableEq TargetIndex] + (zeroReindex oneReindex : SourceIndex × BlockIndex ≃ TargetIndex) + (eigenpath : BlockIndex → C(unitInterval, unitInterval)) (point : unitInterval) : + C(unitInterval, MatrixDiagonalPath.Mat SourceIndex) →⋆ₐ[ℂ] + MatrixDiagonalPath.Mat TargetIndex := + (@MatrixDiagonalPath.interpolate (SourceIndex × BlockIndex) TargetIndex + (instFintypeProd SourceIndex BlockIndex) + targetFintype targetDecidableEq zeroReindex oneReindex point).toStarAlgHom.comp + (@MatrixDiagonalPath.evaluationBlock BlockIndex SourceIndex + blockFintype blockDecidableEq sourceFintype sourceDecidableEq eigenpath point) + +end + +def fiberMap (t : unitInterval) : + C(unitInterval,PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] PrimeDimensionDrop.Fiber P Q := + @OAI.KirchbergRordam.GeneralDropSystem.interpolatedEvaluation (Fin p × Fin q) (OAI.KirchbergRordam.GeneralDropSystem.Slot d) (Fin P × Fin Q) + (instFintypeProd (Fin p) (Fin q)) inferInstance + (instFintypeSum (OAI.KirchbergRordam.GeneralDropSystem.Low d) (OAI.KirchbergRordam.GeneralDropSystem.High d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d)) inferInstance + (instFintypeProd (Fin P) (Fin Q)) inferInstance + (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) t + +def continuousFamily {Source Target : Type*} [CStarAlgebra Source] [CStarAlgebra Target] + (family : unitInterval → Source →⋆ₐ[ℂ] Target) + (continuous_family : ∀ value, Continuous (fun point => family point value)) : + Source →⋆ₐ[ℂ] C(unitInterval, Target) where + toFun value := ⟨fun point => family point value, continuous_family value⟩ + map_zero' := ContinuousMap.ext fun point => (family point).map_zero + map_one' := ContinuousMap.ext fun point => (family point).map_one + map_add' first second := ContinuousMap.ext fun point => (family point).map_add first second + map_mul' first second := ContinuousMap.ext fun point => (family point).map_mul first second + commutes' scalar := ContinuousMap.ext fun point => (family point).commutes scalar + map_star' value := ContinuousMap.ext fun point => map_star (family point) value + +def rawStep : + C(unitInterval, PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] + C(unitInterval, PrimeDimensionDrop.Fiber P Q) := by + classical + have h_MatrixDiagonalPath_evaluationBlock_continuous {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (ξ : ι → C(unitInterval, unitInterval)) + (f : C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ)) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f) := + (map_continuous OAI.KirchbergRordam.MatrixDiagonalPath.block).comp (continuous_pi (fun i => f.continuous.comp (ξ i).continuous)) + have h_MatrixDiagonalPath_interpolate_continuous + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (f : unitInterval → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) + (hf : Continuous f) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ t (f t)) := by + change Continuous (fun t => ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν) * + (CStarMatrix.reindexₐ ℂ ℂ e₀) (f t) * + star ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν)) + have hu : Continuous (fun t => ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν)) := + continuous_subtype_val.comp (Path.continuous _) + exact (hu.mul ((map_continuous (CStarMatrix.reindexₐ ℂ ℂ e₀)).comp hf)).mul hu.star + have h_GeneralDropSystem_fiberMap_continuous (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (path : C(unitInterval, PrimeDimensionDrop.Fiber p q)) : + Continuous (fun point => OAI.KirchbergRordam.GeneralDropSystem.fiberMap d point path) := + h_MatrixDiagonalPath_interpolate_continuous (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) + (fun point => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) point path) + (h_MatrixDiagonalPath_evaluationBlock_continuous (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) path) + exact + @OAI.KirchbergRordam.GeneralDropSystem.continuousFamily C(unitInterval, PrimeDimensionDrop.Fiber p q) + (PrimeDimensionDrop.Fiber P Q) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber p q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin p × Fin q) (instFintypeProd (Fin p) (Fin q)) inferInstance)) + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin P × Fin Q) (instFintypeProd (Fin P) (Fin Q)) inferInstance) + (OAI.KirchbergRordam.GeneralDropSystem.fiberMap d) (h_GeneralDropSystem_fiberMap_continuous d) + +def restrictToSubalgebras {Source Target : Type*} [CStarAlgebra Source] [CStarAlgebra Target] + (hom : Source →⋆ₐ[ℂ] Target) (domain : StarSubalgebra ℂ Source) + (codomain : StarSubalgebra ℂ Target) + (map_mem : ∀ value ∈ domain, hom value ∈ codomain) : domain →⋆ₐ[ℂ] codomain := + (hom.comp domain.subtype).codRestrict codomain (fun value => map_mem value value.property) + +def step := by + classical + have h_GeneralBlockReindex_right_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR ((i,j),.inl l) = ((hL (i,l)).1,.inl (j,(hL (i,l)).2)) := rfl + have h_GeneralBlockReindex_right_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR ((i,j),.inr r) = ((hR r).1,.inr ((i,j),(hR r).2)) := rfl + have h_MatrixBlockReindex_sumBlock_ll {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : P) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inl i) (Sum.inl j) = a i j := rfl + have h_MatrixBlockReindex_sumBlock_lr {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i : P) (j : Q) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inl i) (Sum.inr j) = 0 := rfl + have h_MatrixBlockReindex_sumBlock_rl {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i : Q) (j : P) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inr i) (Sum.inl j) = 0 := rfl + have h_MatrixBlockReindex_sumBlock_rr {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : Q) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inr i) (Sum.inr j) = b i j := rfl + have h_MatrixBlockReindex_right_apply {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : P) (k l : Q) : + OAI.KirchbergRordam.MatrixTensor.rightMatrix a (i,k) (j,l) = (if i=j then 1 else 0) * a k l := by + change (Matrix.kronecker (1 : Matrix P P ℂ) (CStarMatrix.ofMatrix.symm a)) (i,k) (j,l)=_ + simp [Matrix.one_apply] + have h_MatrixDiagonalPath_block_apply {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (a : ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) (i j : κ) (k l : ι) : + OAI.KirchbergRordam.MatrixDiagonalPath.block a (i,k) (j,l) = if k=l then a k i j else 0 := rfl + have h_GeneralBlockReindex_right_entry {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) (x y : (P×Q)×(L⊕R)) : + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.rightMatrix (ι:=P) a) (fun _ : R => m)) x y = + MatrixTensor.rightMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) + (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR x) (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR y) := by + rcases x with ⟨⟨i,j⟩,l|r⟩ <;> rcases y with ⟨⟨i',j'⟩,l'|r'⟩ + · by_cases he : (i,l)=(i',l') + · cases he; simp [h_GeneralBlockReindex_right_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · have hh : (hL (i,l)).1≠(hL (i',l')).1 ∨ (hL (i,l)).2≠(hL (i',l')).2 := by + by_contra h; push Not at h; exact he (hL.injective (Prod.ext h.1 h.2)) + have hil : i≠i' ∨ l≠l' := by simpa only [Prod.mk.injEq,not_and_or] using he + rcases hh with h|h <;> rcases hil with hil|hil <;> + simp [h_GeneralBlockReindex_right_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply,h,hil] + · simp [h_GeneralBlockReindex_right_low, h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_lr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · simp [h_GeneralBlockReindex_right_low, h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rl, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · by_cases hr : r=r' + · subst r'; simp [h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · have hrr : (hR r).1≠(hR r').1 ∨ (hR r).2≠(hR r').2 := by + by_contra h; push Not at h; exact hr (hR.injective (Prod.ext h.1 h.2)) + rcases hrr with h|h <;> simp [h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply,hr,h] + have h_GeneralBlockReindex_right_matrix {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) : + CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR) + (OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.rightMatrix (ι:=P) a) (fun _ : R => m))) = + MatrixTensor.rightMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) := by + ext x y + exact h_GeneralBlockReindex_right_entry hL hR a m ((OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR).symm x) + ((OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR).symm y) |>.trans (by simp [h_MatrixBlockReindex_right_apply] ) + have h_BalancedDropSystem_lower_one : OAI.KirchbergRordam.BalancedDropSystem.lowerPath 1 = OAI.KirchbergRordam.BalancedDropSystem.half := by + apply Subtype.ext + change (1 : ℝ) / 2 = (1 : ℝ) / 2 + rfl + have h_BalancedDropSystem_upper_one : OAI.KirchbergRordam.BalancedDropSystem.upperPath 1 = 1 := by + apply Subtype.ext + change ((1 : ℝ) + 1) / 2 = 1 + norm_num + have h_GeneralDropSystem_rawStep_apply (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f) (t : unitInterval) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f t=OAI.KirchbergRordam.MatrixDiagonalPath.interpolate (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) t (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) t f) := rfl + have h_MatrixBlockReindex_reindex_block {P : Type 0} {Q : Type 0} {R : Type 0} [inst3 : Fintype P] [inst4 : Fintype Q] [inst5 : Fintype R] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst8 : DecidableEq R] (e : P ≃ Q) (a : P → OAI.KirchbergRordam.MatrixDiagonalPath.Mat R) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr (Equiv.refl R) e) (OAI.KirchbergRordam.MatrixDiagonalPath.block a) = + OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => a (e.symm i)) := by + ext i j + rcases i with ⟨r,p⟩; rcases j with ⟨s,q⟩ + change (if e.symm p=e.symm q then a (e.symm p) r s else 0) = + (if p=q then a (e.symm p) r s else 0) + simp only [e.symm.injective.eq_iff] + have h_GeneralDropSystem_one_eval (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin q)) (hb : MatrixTensor.rightMatrix b=f 1) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr (Equiv.refl (Fin p × Fin q)) (OAI.KirchbergRordam.GeneralDropSystem.slotSwap d)) + (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) 1 f)= + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : OAI.KirchbergRordam.GeneralDropSystem.High d => MatrixTensor.rightMatrix (ι:=Fin p) b) + (fun _ : OAI.KirchbergRordam.GeneralDropSystem.Low d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d => f OAI.KirchbergRordam.BalancedDropSystem.half)) := by + change CStarMatrix.reindexₐ ℂ ℂ _ (OAI.KirchbergRordam.MatrixDiagonalPath.block _) = _ + rw [h_MatrixBlockReindex_reindex_block] + apply congrArg OAI.KirchbergRordam.MatrixDiagonalPath.block + funext k + rcases k with k|k|k <;> simp [h_BalancedDropSystem_lower_one, h_BalancedDropSystem_upper_one, OAI.KirchbergRordam.GeneralDropSystem.slotSwap,OAI.KirchbergRordam.GeneralDropSystem.eigenpath,hb] + have h_MatrixBlockReindex_reindex_right {P : Type 0} {Q : Type 0} {R : Type 0} {S : Type 0} [inst4 : Fintype P] [inst5 : Fintype Q] [inst6 : Fintype R] [inst7 : Fintype S] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst10 : DecidableEq R] [inst11 : DecidableEq S] (e : P ≃ Q) (f : R ≃ S) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat R) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr e f) (OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι:=P) a) = + OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι:=Q) (CStarMatrix.reindexₐ ℂ ℂ f a) := by + ext i j + rcases i with ⟨p,r⟩; rcases j with ⟨q,s⟩ + change OAI.KirchbergRordam.MatrixTensor.rightMatrix a (e.symm p,f.symm r) (e.symm q,f.symm s) = _ + simp only [h_MatrixBlockReindex_right_apply, e.symm.injective.eq_iff] + rfl + have h_MatrixBlockReindex_reindex_trans + {P : Type 0} + {Q : Type 0} + [Fintype P] + [Fintype Q] + [DecidableEq P] + [DecidableEq Q] + {T : Type 0} [Fintype T] [DecidableEq T] + (e : P ≃ Q) (f : Q ≃ T) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) : + CStarMatrix.reindexₐ ℂ ℂ (e.trans f) a = + CStarMatrix.reindexₐ ℂ ℂ f (CStarMatrix.reindexₐ ℂ ℂ e a) := rfl + have h_MatrixPermutationPath_perm_conjugation {ι : Type 0} [inst1 : Fintype ι] [inst2 : DecidableEq ι] (σ : Equiv.Perm ι) (a : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) : + Unitary.conjStarAlgAut ℂ _ (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) a = CStarMatrix.reindexₐ ℂ ℂ σ a := by + change σ⁻¹.permMatrix ℂ * CStarMatrix.ofMatrix.symm a * (σ⁻¹.permMatrix ℂ)ᴴ = + Matrix.reindex σ σ (CStarMatrix.ofMatrix.symm a) + rw [Matrix.conjTranspose_permMatrix] + change σ.symm.toPEquiv.toMatrix * CStarMatrix.ofMatrix.symm a * σ.toPEquiv.toMatrix = _ + rw [PEquiv.toMatrix_toPEquiv_mul, PEquiv.mul_toMatrix_toPEquiv] + rfl + have h_MatrixDiagonalPath_interpolate_one + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) : + OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ 1 a = CStarMatrix.reindexₐ ℂ ℂ e₁ a := by + simp only [OAI.KirchbergRordam.MatrixDiagonalPath.interpolate, StarAlgEquiv.trans_apply, Path.target, + (@h_MatrixPermutationPath_perm_conjugation)] + ext i j + change a (e₀.symm ((e₀.symm.trans e₁).symm i)) + (e₀.symm ((e₀.symm.trans e₁).symm j)) = a (e₁.symm i) (e₁.symm j) + simp + have h_GeneralDropSystem_rawStep_one (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin q)) (hb : MatrixTensor.rightMatrix b=f 1) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f 1=MatrixTensor.rightMatrix (ι:=Fin P) + (CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralDropSystem.oneOuter d) + (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.oneEnd => b),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.oneMid => f OAI.KirchbergRordam.BalancedDropSystem.half)))) := by + rw [h_GeneralDropSystem_rawStep_apply,h_MatrixDiagonalPath_interpolate_one] + unfold OAI.KirchbergRordam.GeneralDropSystem.oneReindex + rw [h_MatrixBlockReindex_reindex_trans,h_GeneralDropSystem_one_eval d f b hb,h_MatrixBlockReindex_reindex_trans,(@h_GeneralBlockReindex_right_matrix),h_MatrixBlockReindex_reindex_right] + have h_GeneralBlockReindex_left_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inl l) = (.inl (i,(hL (j,l)).1),(hL (j,l)).2) := rfl + have h_GeneralBlockReindex_left_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inr r) = (.inr ((i,j),(hR r).1),(hR r).2) := rfl + have h_MatrixBlockReindex_left_apply {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (i j : P) (k l : Q) : + OAI.KirchbergRordam.MatrixTensor.leftMatrix a (i,k) (j,l) = a i j * if k=l then 1 else 0 := by + change (Matrix.kronecker (CStarMatrix.ofMatrix.symm a) (1 : Matrix Q Q ℂ)) (i,k) (j,l)=_ + simp [Matrix.one_apply] + have h_GeneralBlockReindex_left_entry {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) (x y : (P×Q)×(L⊕R)) : + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.leftMatrix (κ:=Q) a) (fun _ : R => m)) x y = + MatrixTensor.leftMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) + (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR x) (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR y) := by + rcases x with ⟨⟨i,j⟩,l|r⟩ <;> rcases y with ⟨⟨i',j'⟩,l'|r'⟩ + · by_cases he : (j,l)=(j',l') + · cases he; simp [h_GeneralBlockReindex_left_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · have hh : (hL (j,l)).1≠(hL (j',l')).1 ∨ (hL (j,l)).2≠(hL (j',l')).2 := by + by_contra h; push Not at h; exact he (hL.injective (Prod.ext h.1 h.2)) + have hjl : j≠j' ∨ l≠l' := by simpa only [Prod.mk.injEq,not_and_or] using he + rcases hh with h|h <;> rcases hjl with hjl|hjl <;> + simp [h_GeneralBlockReindex_left_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply,h,hjl] + · simp [h_GeneralBlockReindex_left_low, h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_lr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · simp [h_GeneralBlockReindex_left_low, h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rl, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · by_cases hr : r=r' + · subst r'; simp [h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · have hrr : (hR r).1≠(hR r').1 ∨ (hR r).2≠(hR r').2 := by + by_contra h; push Not at h; exact hr (hR.injective (Prod.ext h.1 h.2)) + rcases hrr with h|h <;> simp [h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply,hr,h] + have h_GeneralBlockReindex_left_matrix {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) : + CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR) + (OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.leftMatrix (κ:=Q) a) (fun _ : R => m))) = + MatrixTensor.leftMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) := by + ext x y + exact h_GeneralBlockReindex_left_entry hL hR a m ((OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR).symm x) + ((OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR).symm y) |>.trans (by simp [h_MatrixBlockReindex_left_apply] ) + have h_BalancedDropSystem_lower_zero : OAI.KirchbergRordam.BalancedDropSystem.lowerPath 0 = 0 := by + apply Subtype.ext + change (0 : ℝ) / 2 = 0 + norm_num + have h_BalancedDropSystem_upper_zero : OAI.KirchbergRordam.BalancedDropSystem.upperPath 0 = OAI.KirchbergRordam.BalancedDropSystem.half := by + apply Subtype.ext + change ((0 : ℝ) + 1) / 2 = (1 : ℝ) / 2 + rw [zero_add] + have h_GeneralDropSystem_zero_eval (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin p)) (ha : MatrixTensor.leftMatrix a=f 0) : + OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) 0 f = + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : OAI.KirchbergRordam.GeneralDropSystem.Low d => MatrixTensor.leftMatrix (κ:=Fin q) a) + (fun _ : OAI.KirchbergRordam.GeneralDropSystem.High d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d => f OAI.KirchbergRordam.BalancedDropSystem.half)) := by + apply congrArg OAI.KirchbergRordam.MatrixDiagonalPath.block + funext k + rcases k with k|k|k <;> simp [h_BalancedDropSystem_lower_zero, h_BalancedDropSystem_upper_zero, OAI.KirchbergRordam.GeneralDropSystem.eigenpath,ha] + have h_MatrixBlockReindex_reindex_left {P : Type 0} {Q : Type 0} {R : Type 0} {S : Type 0} [inst4 : Fintype P] [inst5 : Fintype Q] [inst6 : Fintype R] [inst7 : Fintype S] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst10 : DecidableEq R] [inst11 : DecidableEq S] (e : P ≃ Q) (f : R ≃ S) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr e f) (OAI.KirchbergRordam.MatrixTensor.leftMatrix (κ:=R) a) = + OAI.KirchbergRordam.MatrixTensor.leftMatrix (κ:=S) (CStarMatrix.reindexₐ ℂ ℂ e a) := by + ext i j + rcases i with ⟨p,r⟩; rcases j with ⟨q,s⟩ + change OAI.KirchbergRordam.MatrixTensor.leftMatrix a (e.symm p,f.symm r) (e.symm q,f.symm s) = _ + simp only [h_MatrixBlockReindex_left_apply, f.symm.injective.eq_iff] + rfl + have h_MatrixPermutationPath_perm_one {ι : Type 0} [inst1 : Fintype ι] [inst2 : DecidableEq ι] : OAI.KirchbergRordam.MatrixPermutationPath.perm (1 : Equiv.Perm ι) = 1 := by + apply Subtype.ext + change (1⁻¹ : Equiv.Perm ι).permMatrix ℂ = 1 + simp + have h_MatrixDiagonalPath_interpolate_zero + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) : + OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ 0 a = CStarMatrix.reindexₐ ℂ ℂ e₀ a := by + simp only [OAI.KirchbergRordam.MatrixDiagonalPath.interpolate, StarAlgEquiv.trans_apply, Path.source, + (@h_MatrixPermutationPath_perm_one)] + simp + have h_GeneralDropSystem_rawStep_zero (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin p)) (ha : MatrixTensor.leftMatrix a=f 0) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f 0=MatrixTensor.leftMatrix (κ:=Fin Q) + (CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralDropSystem.zeroOuter d) + (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.zeroEnd => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.zeroMid => f OAI.KirchbergRordam.BalancedDropSystem.half)))) := by + rw [h_GeneralDropSystem_rawStep_apply,h_MatrixDiagonalPath_interpolate_zero,h_GeneralDropSystem_zero_eval d f a ha] + unfold OAI.KirchbergRordam.GeneralDropSystem.zeroReindex + rw [h_MatrixBlockReindex_reindex_trans,(@h_GeneralBlockReindex_left_matrix),h_MatrixBlockReindex_reindex_left] + have h_GeneralDropSystem_rawStep_mem (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (path : C(unitInterval, PrimeDimensionDrop.Fiber p q)) + (path_mem : path ∈ PrimeDimensionDrop.subalgebra p q) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d path ∈ PrimeDimensionDrop.subalgebra P Q := by + obtain ⟨⟨leftValue, left_eq⟩, ⟨rightValue, right_eq⟩⟩ := path_mem + exact ⟨⟨_, (h_GeneralDropSystem_rawStep_zero d path leftValue left_eq).symm⟩, + ⟨_, (h_GeneralDropSystem_rawStep_one d path rightValue right_eq).symm⟩⟩ + exact + @OAI.KirchbergRordam.GeneralDropSystem.restrictToSubalgebras C(unitInterval, PrimeDimensionDrop.Fiber p q) + C(unitInterval, PrimeDimensionDrop.Fiber P Q) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber p q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin p × Fin q) (instFintypeProd (Fin p) (Fin q)) inferInstance)) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber P Q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin P × Fin Q) (instFintypeProd (Fin P) (Fin Q)) inferInstance)) + (OAI.KirchbergRordam.GeneralDropSystem.rawStep d) (PrimeDimensionDrop.subalgebra p q) (PrimeDimensionDrop.subalgebra P Q) + (h_GeneralDropSystem_rawStep_mem d) + +end KirchbergRordam.GeneralDropSystem + +namespace KirchbergRordam + +structure PrimeDropPresentation where + size : ℕ → ℕ + exponent : ℕ → ℕ + size_power : ∀ n, size n=2^(exponent n+1) + stepData : ∀ n, GeneralDropSystem.Data (size n) (size n+1) (size (n+1)) (size (n+1)+1) + zero_copies : ∀ n, 2≤(stepData n).zeroEnd+(size n+1)*(stepData n).zeroMid + one_copies : ∀ n, 2≤(stepData n).oneEnd+size n*(stepData n).oneMid + +namespace PrimeDropPresentation +variable (S : PrimeDropPresentation) + +def Stage (n : ℕ) : Type := PrimeDimensionDrop.Algebra (S.size n) (S.size n+1) + +instance (n : ℕ) : CStarAlgebra (S.Stage n) := inferInstanceAs + (CStarAlgebra (PrimeDimensionDrop.Algebra (S.size n) (S.size n+1))) + +def chain (S : OAI.KirchbergRordam.PrimeDropPresentation) : CStarInductiveLimit.Chain.{0} := by + classical + have h_GeneralDropSystem_eigen_cover {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (s : unitInterval) : ∃ i t, OAI.KirchbergRordam.GeneralDropSystem.eigenpath d i t=s := by + by_cases hs : (s:ℝ)≤1/2 + · refine ⟨.inl ⟨0,d.lower_pos⟩,⟨2*s,by constructor <;> linarith [s.property.1]⟩,?_⟩ + apply Subtype.ext + change 2*(s:ℝ)/2=(s:ℝ) + ring + · refine ⟨.inr (.inl ⟨0,d.upper_pos⟩),⟨2*s-1,by constructor <;> linarith [s.property.2]⟩,?_⟩ + apply Subtype.ext + change ((2*(s:ℝ)-1)+1)/2=(s:ℝ) + ring + have h_MatrixDiagonalPath_block_apply {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (a : ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) (i j : κ) (k l : ι) : + OAI.KirchbergRordam.MatrixDiagonalPath.block a (i,k) (j,l) = if k=l then a k i j else 0 := rfl + have h_MatrixDiagonalPath_block_injective {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] : Function.Injective (OAI.KirchbergRordam.MatrixDiagonalPath.block (ι:=ι) (κ:=κ)) := by + intro a b h + funext k + ext i j + have := congrArg (fun m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ×ι) => m (i,k) (j,k)) h + simpa [h_MatrixDiagonalPath_block_apply, h_MatrixDiagonalPath_block_apply] using this + have h_MatrixDiagonalPath_diagonal_injective {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (ξ : ι → C(unitInterval, unitInterval)) + (hcover : ∀ s : unitInterval, ∃ i t, ξ i t = s) : + Function.Injective (OAI.KirchbergRordam.MatrixDiagonalPath.diagonal (κ:=κ) ξ) := by + intro f g h + ext s a b + obtain ⟨i,t,rfl⟩ := hcover s + have ht : OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => f (ξ i t)) = OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => g (ξ i t)) := + DFunLike.congr_fun h t + exact congrFun (congrFun (congrFun (h_MatrixDiagonalPath_block_injective ht) i) a) b + have h_GeneralDropSystem_rawStep_injective {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) : Function.Injective (OAI.KirchbergRordam.GeneralDropSystem.rawStep d) := by + intro f g h + apply h_MatrixDiagonalPath_diagonal_injective (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) (h_GeneralDropSystem_eigen_cover d) + apply ContinuousMap.ext + intro t + exact (OAI.KirchbergRordam.MatrixDiagonalPath.interpolate (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) t).injective (DFunLike.congr_fun h t) + have h_GeneralDropSystem_step_injective {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) : Function.Injective (OAI.KirchbergRordam.GeneralDropSystem.step d) := by + intro f g h + apply Subtype.ext + exact h_GeneralDropSystem_rawStep_injective d (congrArg Subtype.val h) + have h_GeneralDropSystem_step_norm {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : PrimeDimensionDrop.Algebra p q) : ‖OAI.KirchbergRordam.GeneralDropSystem.step d f‖=‖f‖ := + NonUnitalStarAlgHom.norm_map _ (h_GeneralDropSystem_step_injective d) f + have h_PrimeDropPresentation_stage_step_norm (S : OAI.KirchbergRordam.PrimeDropPresentation) : + ∀ stage (element : S.Stage stage), + ‖GeneralDropSystem.step (S.stepData stage) element‖ = ‖element‖ := + fun stage element => (@h_GeneralDropSystem_step_norm) (S.stepData stage) element + exact + @CStarInductiveLimit.Chain.mk.{0} + (@OAI.KirchbergRordam.PrimeDropPresentation.Stage S) + (@OAI.KirchbergRordam.PrimeDropPresentation.instCStarAlgebraStage S) + (fun stage : Nat => @GeneralDropSystem.step + (@PrimeDropPresentation.size S stage) (Nat.succ (@PrimeDropPresentation.size S stage)) + (@PrimeDropPresentation.size S (Nat.succ stage)) + (Nat.succ (@PrimeDropPresentation.size S (Nat.succ stage))) + (@PrimeDropPresentation.stepData S stage)) + (@h_PrimeDropPresentation_stage_step_norm S) + +abbrev system := S.chain.system + +end PrimeDropPresentation +end KirchbergRordam + +namespace KirchbergRordam.StandardPrimeMultiplicity + +def copies (p : ℕ) : ℕ := (p-1)*(p^4+p^2+1) + +def lower (p : ℕ) : ℕ := p*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p+1 + +def upper (p : ℕ) : ℕ := (p+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p+1 + +def middle (p : ℕ) : ℕ := p*(p+1)*(OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p)^2-1 + +def next (p : ℕ) : ℕ := p^7 + +def data (p : ℕ) (hp : 2≤p) : GeneralDropSystem.Data p (p+1) (OAI.KirchbergRordam.StandardPrimeMultiplicity.next p) (OAI.KirchbergRordam.StandardPrimeMultiplicity.next p+1) := by + classical + have h_StandardPrimeMultiplicity_dimension (p : ℕ) (hp : 2≤p) : p+p*(p+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p=OAI.KirchbergRordam.StandardPrimeMultiplicity.next p := by + cases p with + | zero => omega + | succ p => simp only [OAI.KirchbergRordam.StandardPrimeMultiplicity.copies,OAI.KirchbergRordam.StandardPrimeMultiplicity.next,Nat.add_sub_cancel]; ring + have h_StandardPrimeMultiplicity_lower_pos (p : ℕ) : 0 2 + | n+1 => OAI.KirchbergRordam.StandardPrimeMultiplicity.next (size n) + +end KirchbergRordam.StandardPrimeMultiplicity + +namespace KirchbergRordam.StandardPrimeModel +open StandardPrimeMultiplicity +def presentation : OAI.KirchbergRordam.PrimeDropPresentation := by + classical + have h_StandardPrimeMultiplicity_copies_pos (p : ℕ) (hp : 2≤p) : 0 simp [h_StandardPrimeMultiplicity_size_zero] + | succ n ih => rw [h_StandardPrimeMultiplicity_size_succ,OAI.KirchbergRordam.StandardPrimeMultiplicity.next,ih,←pow_mul,pow_succ] + have h_StandardPrimeMultiplicity_next_two (p : ℕ) (hp : 2≤p) : 2≤OAI.KirchbergRordam.StandardPrimeMultiplicity.next p := by + exact hp.trans (Nat.le_self_pow (by decide) p) + have h_StandardPrimeMultiplicity_size_two (n : ℕ) : 2 ≤ OAI.KirchbergRordam.StandardPrimeMultiplicity.size n := by + induction n with + | zero => simp [h_StandardPrimeMultiplicity_size_zero] + | succ n ih => exact h_StandardPrimeMultiplicity_next_two _ ih + exact { + size := OAI.KirchbergRordam.StandardPrimeMultiplicity.size + exponent n := 7^n-1 + size_power n := by + rw [Nat.sub_add_cancel (Nat.one_le_pow n 7 (by decide))] + exact h_StandardPrimeMultiplicity_size_power n + stepData n := OAI.KirchbergRordam.StandardPrimeMultiplicity.data (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + zero_copies n := by + change 2≤1+(OAI.KirchbergRordam.StandardPrimeMultiplicity.size n+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) + have h := h_StandardPrimeMultiplicity_copies_pos (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + nlinarith [h_StandardPrimeMultiplicity_size_two n] + one_copies n := by + change 2≤1+OAI.KirchbergRordam.StandardPrimeMultiplicity.size n*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) + have h := h_StandardPrimeMultiplicity_copies_pos (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + nlinarith [h_StandardPrimeMultiplicity_size_two n] + } + +end KirchbergRordam.StandardPrimeModel + +namespace KirchbergRordam.JiangSu + +def Algebra : Type := CStarInductiveLimit.Algebra StandardPrimeModel.presentation.system + +instance : CStarAlgebra OAI.KirchbergRordam.JiangSu.Algebra := inferInstanceAs + (CStarAlgebra (CStarInductiveLimit.Algebra StandardPrimeModel.presentation.system)) + +end KirchbergRordam.JiangSu + +namespace KirchbergRordam + +def HasNoCharacters (A : Type*) [CStarAlgebra A] : Prop := + ∀ χ : A →⋆ₙₐ[ℂ] ℂ, χ=0 + +theorem character_criterion + (A : Type) [CStarAlgebra A] [Nontrivial A] [TopologicalSpace.SeparableSpace A] + (ω : Ultrafilter ℕ) (hω : (ω : Filter ℕ)≤Filter.cofinite) : + OAI.KirchbergRordam.HasNoCharacters (NormUltrapower.CentralAlgebra A ω) ↔ + Nonempty (A ≃⋆ₐ[ℂ] MinTensor.Algebra A JiangSu.Algebra) := by sorry + +end KirchbergRordam + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CharacterCriterion.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KirchbergRordam.character_criterion` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/character-criterion/solution/closure.txt b/tasks/character-criterion/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..857d5d7cd2d06372700015da2499c4af852cd52c --- /dev/null +++ b/tasks/character-criterion/solution/closure.txt @@ -0,0 +1,62 @@ +OAI.Analysis.CharacterCriterion.Absorption +OAI.Analysis.CharacterCriterion.AmplifiedComparison +OAI.Analysis.CharacterCriterion.BalancedChannels +OAI.Analysis.CharacterCriterion.BalancedLimit +OAI.Analysis.CharacterCriterion.BalancedSystem +OAI.Analysis.CharacterCriterion.CentralSequences +OAI.Analysis.CharacterCriterion.ConeCube +OAI.Analysis.CharacterCriterion.ConeModel +OAI.Analysis.CharacterCriterion.ConePauli +OAI.Analysis.CharacterCriterion.CubeCalculus +OAI.Analysis.CharacterCriterion.CubeField +OAI.Analysis.CharacterCriterion.Definitions +OAI.Analysis.CharacterCriterion.DetectingSpaces +OAI.Analysis.CharacterCriterion.DiagonalIteration +OAI.Analysis.CharacterCriterion.DropSections +OAI.Analysis.CharacterCriterion.EndpointMultiplicity +OAI.Analysis.CharacterCriterion.FactorIndependence +OAI.Analysis.CharacterCriterion.FieldCalculus +OAI.Analysis.CharacterCriterion.FiniteDrop +OAI.Analysis.CharacterCriterion.FlipPath +OAI.Analysis.CharacterCriterion.FourLegSymmetries +OAI.Analysis.CharacterCriterion.FullComparison +OAI.Analysis.CharacterCriterion.Fullness +OAI.Analysis.CharacterCriterion.FunctionalCalculus +OAI.Analysis.CharacterCriterion.GeneralSystem +OAI.Analysis.CharacterCriterion.HereditaryTransport +OAI.Analysis.CharacterCriterion.InductiveLimit +OAI.Analysis.CharacterCriterion.InfiniteTensor +OAI.Analysis.CharacterCriterion.JiangSu +OAI.Analysis.CharacterCriterion.Main +OAI.Analysis.CharacterCriterion.MatrixPaths +OAI.Analysis.CharacterCriterion.MatrixSimplex +OAI.Analysis.CharacterCriterion.MaxTensor +OAI.Analysis.CharacterCriterion.MinTensor +OAI.Analysis.CharacterCriterion.MinimalFunctoriality +OAI.Analysis.CharacterCriterion.MultiplicativeChannels +OAI.Analysis.CharacterCriterion.NoncommutingPair +OAI.Analysis.CharacterCriterion.NormUltrapower +OAI.Analysis.CharacterCriterion.OrderZero +OAI.Analysis.CharacterCriterion.OrderZeroPair +OAI.Analysis.CharacterCriterion.Pauli +OAI.Analysis.CharacterCriterion.PrimeChannels +OAI.Analysis.CharacterCriterion.PrimePresentation +OAI.Analysis.CharacterCriterion.PrimeSpectrum +OAI.Analysis.CharacterCriterion.PrimeSquare +OAI.Analysis.CharacterCriterion.Projectionless +OAI.Analysis.CharacterCriterion.Reindexing +OAI.Analysis.CharacterCriterion.RepresentationTheory +OAI.Analysis.CharacterCriterion.Representations +OAI.Analysis.CharacterCriterion.RepresentedLabels +OAI.Analysis.CharacterCriterion.SeparableReduction +OAI.Analysis.CharacterCriterion.SignObstruction +OAI.Analysis.CharacterCriterion.SpatialTensor +OAI.Analysis.CharacterCriterion.SquareZeroCone +OAI.Analysis.CharacterCriterion.StandardPrime +OAI.Analysis.CharacterCriterion.States +OAI.Analysis.CharacterCriterion.SymmetryFlow +OAI.Analysis.CharacterCriterion.TensorComparison +OAI.Analysis.CharacterCriterion.TensorSections +OAI.Analysis.CharacterCriterion.Traces +OAI.Analysis.CharacterCriterion.UltrapowerSaturation +OAI.Analysis.CharacterCriterion.WeightedUnits diff --git a/tasks/character-criterion/solution/reference.py b/tasks/character-criterion/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/character-criterion/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/character-criterion/solution/solve.sh b/tasks/character-criterion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f2bc2818a399d6f08d142ee8008df5ab5ddc9115 --- /dev/null +++ b/tasks/character-criterion/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CharacterCriterion, i.e. module OAI.Analysis.CharacterCriterion.Main and the +# 62 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.CharacterCriterion.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CharacterCriterion" diff --git a/tasks/character-criterion/task.toml b/tasks/character-criterion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1caf8e4a31da59c43898f16281c02478e5cd51ca --- /dev/null +++ b/tasks/character-criterion/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/character-criterion" +version = "1.0.0" +description = "Prove CharacterCriterion (openai/math family 299: The Kirchberg–R\\o rdam character criterion) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CharacterCriterion.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CharacterCriterion" +family = "299" +family_title = "The Kirchberg–R\\o rdam character criterion" +subject = "Operator algebras" +theorems = ["OAI.KirchbergRordam.character_criterion"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.CharacterCriterion.Main" +reference_modules = 62 +reference_lean_bytes = 1147190 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1889 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12732 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/character-criterion/tests/Challenge.lean b/tasks/character-criterion/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d45ee2022ccf474501e99a042afea7eb6c5494ae --- /dev/null +++ b/tasks/character-criterion/tests/Challenge.lean @@ -0,0 +1,2138 @@ +import Mathlib + +/-! +# Character criterion for Jiang–Su absorption + +The main statement is Theorem 1.1 of the Kirchberg–Rørdam character-criterion paper. +The constructions below specify the norm central-sequence algebra and Jiang–Su absorption. +-/ + +namespace OAI + +noncomputable section + +section + +open scoped TensorProduct InnerProductSpace BigOperators +open Set Module + +universe uQuot +namespace KirchbergRordam.QuotientNormSupport + +@[instance_reducible] +noncomputable def normedRing {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] : NormedRing (R ⧸ I) := by + classical + have h_QuotientNormSupport_distance_eq {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] (x y : R ⧸ I) : + dist x y = ‖-x + y‖ := dist_eq_norm_neg_add x y + have h_QuotientNormSupport_multiplication_bound {R : Type uQuot} [NormedRing R] (I : Ideal R) [I.IsTwoSided] + [IsClosed (I : Set R)] (x y : R ⧸ I) : + ‖x * y‖ ≤ ‖x‖ * ‖y‖ := le_of_forall_pos_le_add fun ε hε => + let neighborhood : ∃ radii : ℝ × ℝ, (0 < radii.1 ∧ 0 < radii.2) ∧ + ∀ point : ℝ × ℝ, (dist point.1 ‖x‖ < radii.1 ∧ dist point.2 ‖y‖ < radii.2) → + dist (point.1 * point.2) (‖x‖ * ‖y‖) < ε := + ((Metric.nhds_basis_ball.prod_nhds Metric.nhds_basis_ball).tendsto_iff + Metric.nhds_basis_ball).mp (continuous_mul.tendsto (‖x‖, ‖y‖)) ε hε + neighborhood.elim fun radii radii_spec => + (Submodule.Quotient.norm_mk_lt x radii_spec.1.1).elim fun representative_x x_spec => + (Submodule.Quotient.norm_mk_lt y radii_spec.1.2).elim fun representative_y y_spec => + let lower_x : ‖x‖ ≤ ‖representative_x‖ := + Eq.mp (congrArg (fun value : R ⧸ I => ‖value‖ ≤ ‖representative_x‖) x_spec.1) + (Submodule.Quotient.norm_mk_le I representative_x) + let lower_y : ‖y‖ ≤ ‖representative_y‖ := + Eq.mp (congrArg (fun value : R ⧸ I => ‖value‖ ≤ ‖representative_y‖) y_spec.1) + (Submodule.Quotient.norm_mk_le I representative_y) + let distance_x : dist ‖representative_x‖ ‖x‖ < radii.1 := + Eq.mpr (congrArg (fun distance : ℝ => distance < radii.1) + (Real.dist_eq ‖representative_x‖ ‖x‖)) + (abs_sub_lt_iff.mpr ⟨sub_lt_iff_lt_add'.mpr x_spec.2, + (sub_nonpos.mpr lower_x).trans_lt radii_spec.1.1⟩) + let distance_y : dist ‖representative_y‖ ‖y‖ < radii.2 := + Eq.mpr (congrArg (fun distance : ℝ => distance < radii.2) + (Real.dist_eq ‖representative_y‖ ‖y‖)) + (abs_sub_lt_iff.mpr ⟨sub_lt_iff_lt_add'.mpr y_spec.2, + (sub_nonpos.mpr lower_y).trans_lt radii_spec.1.2⟩) + let product_distance := + radii_spec.2 (‖representative_x‖, ‖representative_y‖) ⟨distance_x, distance_y⟩ + let product_bound : ‖x * y‖ ≤ ‖representative_x‖ * ‖representative_y‖ := + Eq.mp (congrArg₂ (fun left right : R ⧸ I => + ‖left * right‖ ≤ ‖representative_x‖ * ‖representative_y‖) x_spec.1 y_spec.1) + ((Submodule.Quotient.norm_mk_le I (representative_x * representative_y)).trans + (norm_mul_le representative_x representative_y)) + product_bound.trans (sub_lt_iff_lt_add'.mp (abs_sub_lt_iff.mp + (Eq.mp (congrArg (fun distance : ℝ => distance < ε) + (Real.dist_eq (‖representative_x‖ * ‖representative_y‖) (‖x‖ * ‖y‖))) + product_distance)).1).le + exact { + toNorm := inferInstance + toRing := inferInstance + toMetricSpace := inferInstance + dist_eq := h_QuotientNormSupport_distance_eq I + norm_mul_le := h_QuotientNormSupport_multiplication_bound I + } + +end KirchbergRordam.QuotientNormSupport + +end + +open scoped TensorProduct CStarAlgebra InnerProductSpace Matrix Kronecker ComplexOrder +open UniformSpace Filter Topology BoundedContinuousFunction + +universe uQuot + +namespace KirchbergRordam.NormUltrapower + +variable {A : Type*} [CStarAlgebra A] + +abbrev BoundedSeq (A : Type*) [CStarAlgebra A] := ℕ →ᵇ A + +def normLimit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : ℝ := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + exact + (h_NormUltrapower_exists_norm_limit ω x).choose + +def nullIdeal (ω : Ultrafilter ℕ) : Ideal (OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_mul_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x * y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x*y)) + ((h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_mul_le (x n) (y n)) + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + have h_NormUltrapower_normLimit_zero (ω : Ultrafilter ℕ) : OAI.KirchbergRordam.NormUltrapower.normLimit ω (0 : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) = 0 := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω 0) + simp + exact { + carrier := {x | OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0} + zero_mem' := h_NormUltrapower_normLimit_zero ω + add_mem' := by + intro x y hx hy + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 at hx + change OAI.KirchbergRordam.NormUltrapower.normLimit ω y = 0 at hy + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x+y)) + simpa only [hx, hy, add_zero] using h_NormUltrapower_normLimit_add_le ω x y + smul_mem' := by + intro x y hy + change OAI.KirchbergRordam.NormUltrapower.normLimit ω y = 0 at hy + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x*y)) + simpa only [hy, mul_zero] using h_NormUltrapower_normLimit_mul_le ω x y + } + +instance nullIdeal_twoSided (ω : Ultrafilter ℕ) : (OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω).IsTwoSided := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_mul_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x * y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x*y)) + ((h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_mul_le (x n) (y n)) + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + exact { + mul_mem_of_left := by + intro x y hx + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (x*y) = 0 + apply le_antisymm _ (h_NormUltrapower_normLimit_nonneg ω (x*y)) + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 at hx + simpa only [hx, zero_mul] using h_NormUltrapower_normLimit_mul_le ω x y + } + +instance nullIdeal_closed (ω : Ultrafilter ℕ) : IsClosed (OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω : Set (OAI.KirchbergRordam.NormUltrapower.BoundedSeq A)) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_normLimit_le (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖x‖ := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.2 + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_sub_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x - OAI.KirchbergRordam.NormUltrapower.normLimit ω y ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) := by + have h := h_NormUltrapower_normLimit_add_le ω (x-y) y + rw [sub_add_cancel] at h + linarith + have h_NormUltrapower_normLimit_lipschitz (ω : Ultrafilter ℕ) : + LipschitzWith 1 (OAI.KirchbergRordam.NormUltrapower.normLimit ω : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A → ℝ) := by + apply LipschitzWith.of_dist_le_mul + intro x y + rw [NNReal.coe_one, one_mul, Real.dist_eq, abs_le, dist_eq_norm] + constructor + · have h := (h_NormUltrapower_normLimit_sub_le ω y x).trans (h_NormUltrapower_normLimit_le ω (y-x)) + rw [norm_sub_rev] at h + linarith + · exact (h_NormUltrapower_normLimit_sub_le ω x y).trans (h_NormUltrapower_normLimit_le ω (x-y)) + exact + isClosed_eq (h_NormUltrapower_normLimit_lipschitz ω).continuous continuous_const + +abbrev Algebra (A : Type*) [CStarAlgebra A] (ω : Ultrafilter ℕ) := + OAI.KirchbergRordam.NormUltrapower.BoundedSeq A ⧸ OAI.KirchbergRordam.NormUltrapower.nullIdeal (A := A) ω + +noncomputable instance quotientNormedRing {R : Type uQuot} [NormedRing R] (I : Ideal R) + [I.IsTwoSided] [IsClosed (I : Set R)] : NormedRing (R ⧸ I) := + KirchbergRordam.QuotientNormSupport.normedRing I + +instance quotientNormedAlgebra (ω : Ultrafilter ℕ) : NormedAlgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + norm_smul_le := norm_smul_le + +instance quotientStar (ω : Ultrafilter ℕ) : Star (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_star (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (star x)) + simp [h_NormUltrapower_tendsto_norm] + exact { + star := Quotient.map' star fun x y h => by + rw [Submodule.quotientRel_def] at h ⊢ + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x - star y) = 0 + rw [← star_sub, h_NormUltrapower_normLimit_star] + exact h + } + +instance quotientStarRing (ω : Ultrafilter ℕ) : StarRing (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + star_involutive := by + rintro ⟨x⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (star x)) = Ideal.Quotient.mk _ x + rw [star_star] + star_mul := by + rintro ⟨x⟩ ⟨y⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (x*y)) = Ideal.Quotient.mk _ (star y * star x) + rw [star_mul] + star_add := by + rintro ⟨x⟩ ⟨y⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (x+y)) = Ideal.Quotient.mk _ (star x + star y) + rw [star_add] + +instance quotientStarModule (ω : Ultrafilter ℕ) : StarModule ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + star_smul := by + intro z + rintro ⟨x⟩ + change Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (star (z • x)) = Ideal.Quotient.mk _ (star z • star x) + rw [star_smul] + +def cutRepresentative (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) (c : ℝ) (hc : 0 ≤ c) : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A := + ofNormedAddCommGroupDiscrete (fun n => if ‖x n‖ < c then x n else 0) c (by + intro n + split_ifs with h + · exact h.le + · simpa only [norm_zero] using hc) + +instance quotientCStarRing (ω : Ultrafilter ℕ) : CStarRing (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := by + classical + have h_NormUltrapower_exists_norm_limit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ∃ r ∈ Set.Icc (0 : ℝ) ‖x‖, Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 r) := by + obtain ⟨r, hr, h⟩ := isCompact_Icc.ultrafilter_le_nhds' + (Ultrafilter.map (fun n => ‖x n‖) ω) (by + change ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ ∈ Set.Icc (0 : ℝ) ‖x‖ + exact Eventually.of_forall fun n => ⟨norm_nonneg _, x.norm_coe_le_norm n⟩) + exact ⟨r, hr, h⟩ + have h_NormUltrapower_tendsto_norm (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 (OAI.KirchbergRordam.NormUltrapower.normLimit ω x)) := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.2 + have h_NormUltrapower_normLimit_star_mul (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (star x * x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x * OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (star x * x)) + simpa only [BoundedContinuousFunction.mul_apply, BoundedContinuousFunction.star_apply, + CStarRing.norm_star_mul_self] using (h_NormUltrapower_tendsto_norm ω x).mul (h_NormUltrapower_tendsto_norm ω x) + have h_NormUltrapower_normLimit_neg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (-x) = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω (-x)) + simp [h_NormUltrapower_tendsto_norm] + have h_NormUltrapower_normLimit_add_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω (x + y) ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + exact le_of_tendsto_of_tendsto (h_NormUltrapower_tendsto_norm ω (x+y)) + ((h_NormUltrapower_tendsto_norm ω x).add (h_NormUltrapower_tendsto_norm ω y)) + (Eventually.of_forall fun n => norm_add_le (x n) (y n)) + have h_NormUltrapower_normLimit_sub_le (ω : Ultrafilter ℕ) (x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x - OAI.KirchbergRordam.NormUltrapower.normLimit ω y ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) := by + have h := h_NormUltrapower_normLimit_add_le ω (x-y) y + rw [sub_add_cancel] at h + linarith + have h_NormUltrapower_normLimit_eq_of_sub_mem (ω : Ultrafilter ℕ) {x y : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A} + (h : x-y ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x = OAI.KirchbergRordam.NormUltrapower.normLimit ω y := by + change OAI.KirchbergRordam.NormUltrapower.normLimit ω (x-y) = 0 at h + apply le_antisymm + · have h' := h_NormUltrapower_normLimit_sub_le ω x y + linarith + · have h' := h_NormUltrapower_normLimit_sub_le ω y x + rw [← neg_sub x y, h_NormUltrapower_normLimit_neg, h] at h' + linarith + have h_NormUltrapower_normLimit_le (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖x‖ := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.2 + have h_NormUltrapower_normLimit_le_quotient (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + OAI.KirchbergRordam.NormUltrapower.normLimit ω x ≤ ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ := by + apply QuotientAddGroup.le_norm_iff.mpr + intro y hy + have h : y-x ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω := (Ideal.Quotient.eq).mp hy + rw [← h_NormUltrapower_normLimit_eq_of_sub_mem ω h] + exact h_NormUltrapower_normLimit_le ω y + have h_NormUltrapower_mem_nullIdeal (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + x ∈ OAI.KirchbergRordam.NormUltrapower.nullIdeal ω ↔ Tendsto (fun n => ‖x n‖) (ω : Filter ℕ) (𝓝 0) := by + change OAI.KirchbergRordam.NormUltrapower.normLimit ω x = 0 ↔ _ + constructor + · intro h + simpa only [h] using h_NormUltrapower_tendsto_norm ω x + · exact fun h => tendsto_nhds_unique (h_NormUltrapower_tendsto_norm ω x) h + have h_NormUltrapower_cutRepresentative_mk_eq (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) + (c : ℝ) (hc : 0 ≤ c) (hlim : OAI.KirchbergRordam.NormUltrapower.normLimit ω x < c) : + Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x = + Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) (OAI.KirchbergRordam.NormUltrapower.cutRepresentative x c hc) := by + rw [Ideal.Quotient.eq, h_NormUltrapower_mem_nullIdeal] + have he : ∀ᶠ n in (ω : Filter ℕ), ‖x n‖ < c := + (h_NormUltrapower_tendsto_norm ω x).eventually (eventually_lt_nhds hlim) + have hz : Tendsto (fun _ : ℕ => (0 : ℝ)) (ω : Filter ℕ) (𝓝 0) := tendsto_const_nhds + apply hz.congr' + filter_upwards [he] with n hn + change (0 : ℝ) = ‖x n - (if ‖x n‖ < c then x n else 0)‖ + rw [ite_eq_left hn, sub_self, norm_zero] + have h_NormUltrapower_cutRepresentative_norm_le (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) (c : ℝ) (hc : 0 ≤ c) : + ‖OAI.KirchbergRordam.NormUltrapower.cutRepresentative x c hc‖ ≤ c := by + apply (BoundedContinuousFunction.norm_le hc).mpr + intro n + change ‖if ‖x n‖ < c then x n else 0‖ ≤ c + split_ifs with h + · exact h.le + · simpa only [norm_zero] using hc + have h_NormUltrapower_normLimit_nonneg (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + (h_NormUltrapower_exists_norm_limit ω x).choose_spec.1.1 + have h_NormUltrapower_quotient_norm_le_normLimit (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x := by + apply le_of_forall_pos_le_add + intro ε hε + have hpos : 0 ≤ OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε := add_nonneg (h_NormUltrapower_normLimit_nonneg ω x) hε.le + rw [h_NormUltrapower_cutRepresentative_mk_eq ω x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos (lt_add_of_pos_right _ hε)] + have hb := Submodule.Quotient.norm_mk_le (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) + (OAI.KirchbergRordam.NormUltrapower.cutRepresentative x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos) + exact hb.trans (h_NormUltrapower_cutRepresentative_norm_le x (OAI.KirchbergRordam.NormUltrapower.normLimit ω x + ε) hpos) + have h_NormUltrapower_norm_mk_eq (ω : Ultrafilter ℕ) (x : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A) : + ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ = OAI.KirchbergRordam.NormUltrapower.normLimit ω x := + le_antisymm (h_NormUltrapower_quotient_norm_le_normLimit ω x) (h_NormUltrapower_normLimit_le_quotient ω x) + exact { + norm_mul_self_le := by + rintro ⟨x⟩ + change ‖Ideal.Quotient.mk (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) x‖ * ‖Ideal.Quotient.mk _ x‖ ≤ + ‖Ideal.Quotient.mk _ (star x * x)‖ + rw [h_NormUltrapower_norm_mk_eq, h_NormUltrapower_norm_mk_eq, h_NormUltrapower_normLimit_star_mul] + } + +instance quotientCStarAlgebra (ω : Ultrafilter ℕ) : CStarAlgebra (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) where + +def quotientMap (ω : Ultrafilter ℕ) : OAI.KirchbergRordam.NormUltrapower.BoundedSeq A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.Algebra A ω where + __ := Ideal.Quotient.mkₐ ℂ (OAI.KirchbergRordam.NormUltrapower.nullIdeal ω) + map_star' _ := rfl + +def constantSeq : A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.BoundedSeq A where + toFun := BoundedContinuousFunction.const ℕ + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def diagonal (ω : Ultrafilter ℕ) : A →⋆ₐ[ℂ] OAI.KirchbergRordam.NormUltrapower.Algebra A ω := + (OAI.KirchbergRordam.NormUltrapower.quotientMap ω).comp OAI.KirchbergRordam.NormUltrapower.constantSeq + +def centralSubalgebra (ω : Ultrafilter ℕ) : StarSubalgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := + StarSubalgebra.centralizer ℂ (Set.range (OAI.KirchbergRordam.NormUltrapower.diagonal (A := A) ω)) + +instance centralSubalgebra_closed (ω : Ultrafilter ℕ) : + IsClosed (OAI.KirchbergRordam.NormUltrapower.centralSubalgebra (A := A) ω : Set (OAI.KirchbergRordam.NormUltrapower.Algebra A ω)) := + Set.isClosed_centralizer _ + +abbrev CentralAlgebra (A : Type*) [CStarAlgebra A] (ω : Ultrafilter ℕ) := + OAI.KirchbergRordam.NormUltrapower.centralSubalgebra (A := A) ω + +instance centralSubringClass (ω : Ultrafilter ℕ) : + SubringClass (StarSubalgebra ℂ (OAI.KirchbergRordam.NormUltrapower.Algebra A ω)) (OAI.KirchbergRordam.NormUltrapower.Algebra A ω) := + StarSubalgebra.subringClass (R := ℂ) (A := OAI.KirchbergRordam.NormUltrapower.Algebra A ω) + +instance centralCStarAlgebra (ω : Ultrafilter ℕ) : CStarAlgebra (OAI.KirchbergRordam.NormUltrapower.CentralAlgebra A ω) := + StarSubalgebra.cstarAlgebra _ + +end KirchbergRordam.NormUltrapower + +namespace KirchbergRordam +namespace StarCompletion + +open UniformSpace +variable (R : Type*) [SeminormedRing R] [StarRing R] [NormedStarGroup R] + +instance completionStar : Star (Completion R) := ⟨Completion.map (star : R → R)⟩ + +instance completionContinuousStar : ContinuousStar (Completion R) where + continuous_star := Completion.continuous_map + +instance completionStarRing : StarRing (Completion R) := by + classical + have h_StarCompletion_star_coe (x : R) : star (x : Completion R) = (star x : R) := + Completion.map_coe star_isometry.uniformContinuous x + exact { + star_involutive x := by + induction x using Completion.induction_on with + | hp => exact isClosed_eq (continuous_star.comp continuous_star) continuous_id + | ih x => simp only [h_StarCompletion_star_coe, star_star] + star_mul x y := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simp only [← Completion.coe_mul, h_StarCompletion_star_coe, star_mul] + star_add x y := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simp only [← Completion.coe_add, h_StarCompletion_star_coe, star_add] + } + +variable [NormedAlgebra ℂ R] [StarModule ℂ R] + +instance completionNormedAlgebra : NormedAlgebra ℂ (Completion R) where + norm_smul_le := norm_smul_le + +instance completionStarModule : StarModule ℂ (Completion R) := by + classical + have h_StarCompletion_star_coe (x : R) : star (x : Completion R) = (star x : R) := + Completion.map_coe star_isometry.uniformContinuous x + exact { + star_smul z x := by + induction x using Completion.induction_on with + | hp => + exact isClosed_eq + (continuous_star.comp (continuous_const_smul z)) + ((continuous_const_smul (star z)).comp continuous_star) + | ih x => + rw [← Completion.coe_smul, h_StarCompletion_star_coe, star_smul, Completion.coe_smul, h_StarCompletion_star_coe] + } + +end StarCompletion + +end KirchbergRordam + +namespace KirchbergRordam.CStarInductiveLimit +universe u + +structure System where + obj : ℕ → Type u + [cstar : ∀ n, CStarAlgebra (obj n)] + map : ∀ i j, i ≤ j → obj i →⋆ₐ[ℂ] obj j + map_self : ∀ i x, map i i le_rfl x = x + map_map : ∀ i j k (hij : i ≤ j) (hjk : j ≤ k) x, + map j k hjk (map i j hij x) = map i k (hij.trans hjk) x + norm_map : ∀ i j (h : i ≤ j) x, ‖map i j h x‖ = ‖x‖ + +attribute [instance] System.cstar + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : DirectedSystem S.obj (S.map · · ·) where + map_self := fun {_} x => S.map_self _ x + map_map := fun {_ _ _} hij hjk x => S.map_map _ _ _ hij hjk x + +def Raw (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) := DirectLimit S.obj S.map + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : Ring (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (Ring (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : Algebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (Algebra ℂ (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : StarRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (StarRing (DirectLimit S.obj S.map)) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : StarModule ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := inferInstanceAs (StarModule ℂ (DirectLimit S.obj S.map)) + +def rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) : S.obj n →⋆ₐ[ℂ] OAI.KirchbergRordam.CStarInductiveLimit.Raw S where + __ := DirectLimit.Algebra.of S.obj S.map n + map_star' _ := rfl + +def normLift (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : OAI.KirchbergRordam.CStarInductiveLimit.Raw S → ℝ := + DirectLimit.lift S.map (fun _ x => ‖x‖) (fun i j h x => (S.norm_map i j h x).symm) + +def ringNorm (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : RingNorm (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + exact { + toFun := OAI.KirchbergRordam.CStarInductiveLimit.normLift S + map_zero' := by + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (0 : DirectLimit S.obj S.map) = 0 + rw [DirectLimit.zero_def (f := S.map) 0] + exact norm_zero + add_le' := by + intro x y + refine DirectLimit.induction₂ S.map ?_ x y + intro n x y + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x + OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) ≤ + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) + rw [← map_add, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk] + exact norm_add_le x y + neg' := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (-OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) + rw [← map_neg, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, norm_neg] + mul_le' := by + intro x y + refine DirectLimit.induction₂ S.map ?_ x y + intro n x y + change OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x * OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) ≤ + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) * OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n y) + rw [← map_mul, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk, h_CStarInductiveLimit_normLift_mk] + exact norm_mul_le x y + eq_zero_of_map_eq_zero' := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x hx + change ‖x‖ = 0 at hx + rw [norm_eq_zero] at hx + change OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x = 0 + rw [hx, map_zero] + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := (OAI.KirchbergRordam.CStarInductiveLimit.ringNorm S).toNormedRing + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedAlgebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_smul_le z := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖z • OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ ≤ ‖z‖ * ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_smul, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf] + exact norm_smul_le z x + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : NormedStarGroup (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_star_le := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖star (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x)‖ ≤ ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_star, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf, norm_star] + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) := by + classical + have h_CStarInductiveLimit_normLift_mk (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + OAI.KirchbergRordam.CStarInductiveLimit.normLift S (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) = ‖x‖ := rfl + have h_CStarInductiveLimit_norm_rawOf (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) (n : ℕ) (x : S.obj n) : + ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ = ‖x‖ := rfl + exact { + norm_mul_self_le := by + intro x + refine DirectLimit.induction S.map ?_ x + intro n x + change ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ * ‖OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ ≤ ‖star (OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x) * OAI.KirchbergRordam.CStarInductiveLimit.rawOf S n x‖ + rw [← map_star, ← map_mul, h_CStarInductiveLimit_norm_rawOf, h_CStarInductiveLimit_norm_rawOf] + exact CStarRing.norm_mul_self_le x + } + +abbrev Algebra (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) := UniformSpace.Completion (OAI.KirchbergRordam.CStarInductiveLimit.Raw S) + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S) := by + classical + have h_StarCompletion_star_coe (x : Raw S) : star (x : Completion (Raw S)) = ((star x : Raw S) : Completion (Raw S)) := Completion.map_coe star_isometry.uniformContinuous x + exact { + norm_mul_self_le x := by + induction x using UniformSpace.Completion.induction_on with + | hp => exact isClosed_le (by fun_prop) (by fun_prop) + | ih x => + rw [(h_StarCompletion_star_coe), ← UniformSpace.Completion.coe_mul] + simpa only [UniformSpace.Completion.norm_coe] using CStarRing.norm_mul_self_le x + } + +instance (S : OAI.KirchbergRordam.CStarInductiveLimit.System.{u}) : CStarAlgebra (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S) := + { (inferInstance : NormedRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : NormedAlgebra ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : CompleteSpace (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : StarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : StarModule ℂ (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)), + (inferInstance : CStarRing (OAI.KirchbergRordam.CStarInductiveLimit.Algebra S)) with } + +structure Chain where + obj : ℕ → Type u + [cstar : ∀ n, CStarAlgebra (obj n)] + step : ∀ n, obj n →⋆ₐ[ℂ] obj (n+1) + norm_step : ∀ n x, ‖step n x‖ = ‖x‖ + +attribute [instance] Chain.cstar + +def Chain.map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) : S.obj i →⋆ₐ[ℂ] S.obj j := + Nat.leRecOn (C := fun n => S.obj i →⋆ₐ[ℂ] S.obj n) h + (fun {n} φ => (S.step n).comp φ) (StarAlgHom.id ℂ _) + +def Chain.system (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) : OAI.KirchbergRordam.CStarInductiveLimit.System.{u} := by + classical + have h_CStarInductiveLimit_Chain_map_self (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i : ℕ) : + S.map i i le_rfl = StarAlgHom.id ℂ _ := by simp [Chain.map, Nat.leRecOn_self] + have h_CStarInductiveLimit_Chain_map_succ (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) : + S.map i (j+1) (h.trans (Nat.le_succ j)) = (S.step j).comp (S.map i j h) := by + exact Nat.leRecOn_succ (C := fun n => S.obj i →⋆ₐ[ℂ] S.obj n) + (next := fun {n} φ => (S.step n).comp φ) h (StarAlgHom.id ℂ (S.obj i)) + have h_CStarInductiveLimit_Chain_map_map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j k : ℕ) (hij : i ≤ j) (hjk : j ≤ k) + (x : S.obj i) : S.map j k hjk (S.map i j hij x) = S.map i k (hij.trans hjk) x := by + induction k, hjk using Nat.le_induction with + | base => simp [h_CStarInductiveLimit_Chain_map_self] + | succ k hjk ih => + rw [(h_CStarInductiveLimit_Chain_map_succ S j k hjk), (h_CStarInductiveLimit_Chain_map_succ S i k (LE.le.trans hij hjk))] + exact congrArg (S.step k) ih + have h_CStarInductiveLimit_Chain_norm_map (S : OAI.KirchbergRordam.CStarInductiveLimit.Chain.{u}) (i j : ℕ) (h : i ≤ j) (x : S.obj i) : + ‖S.map i j h x‖ = ‖x‖ := by + induction j, h using Nat.le_induction with + | base => simp [h_CStarInductiveLimit_Chain_map_self] + | succ j h ih => + rw [(h_CStarInductiveLimit_Chain_map_succ S i j h)] + exact (S.norm_step j (S.map i j h x)).trans ih + exact { + obj := S.obj + map := S.map + map_self i x := by simp [h_CStarInductiveLimit_Chain_map_self] + map_map := (h_CStarInductiveLimit_Chain_map_map S) + norm_map := (h_CStarInductiveLimit_Chain_norm_map S) + } + +end KirchbergRordam.CStarInductiveLimit + +namespace KirchbergRordam.MaxTensor +variable (A B : Type*) [CStarAlgebra A] [CStarAlgebra B] + +structure CrossSeminorm extends Seminorm ℂ (A ⊗[ℂ] B) where + mul_le : ∀ x y, toSeminorm (x * y) ≤ toSeminorm x * toSeminorm y + star_eq : ∀ x, toSeminorm (star x) = toSeminorm x + cstar_eq : ∀ x, toSeminorm (star x * x) = toSeminorm x * toSeminorm x + tmul_le : ∀ a b, toSeminorm (a ⊗ₜ[ℂ] b) ≤ ‖a‖ * ‖b‖ + +instance : Inhabited (OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B) := ⟨{ + toSeminorm := 0 + mul_le := by simp + star_eq := by simp + cstar_eq := by simp + tmul_le := by intro a b; simp only [zero_apply]; positivity }⟩ + +variable {A B} + +def Raw (A B : Type*) [CStarAlgebra A] [CStarAlgebra B] := A ⊗[ℂ] B + +instance : Ring (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (Ring (A ⊗[ℂ] B)) + +instance : Algebra ℂ (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (Algebra ℂ (A ⊗[ℂ] B)) + +instance : StarRing (OAI.KirchbergRordam.MaxTensor.Raw A B) := inferInstanceAs (StarRing (A ⊗[ℂ] B)) + +def rawEquiv : (A ⊗[ℂ] B) ≃⋆ₐ[ℂ] OAI.KirchbergRordam.MaxTensor.Raw A B := + StarAlgEquiv.refl ℂ (A ⊗[ℂ] B) + +variable {C : Type*} [CStarAlgebra C] + +def liftRaw (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) : OAI.KirchbergRordam.MaxTensor.Raw A B →⋆ₐ[ℂ] C where + toAlgHom := _root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h + map_star' x := by + change _root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h (star x) = + star (_root_.Algebra.TensorProduct.lift φ.toAlgHom ψ.toAlgHom h x) + induction x using TensorProduct.inductionOn with + | add x y hx hy => simpa only [star_add, map_add] using congrArg₂ (· + ·) hx hy + | tmul a b => + change φ (star a) * ψ (star b) = star (φ a * ψ b) + rw [star_mul, ← map_star, ← map_star] + exact h (star a) (star b) + +def representationSeminorm (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) : OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B := by + classical + have h_MaxTensor_liftRaw_tmul (φ : A →⋆ₐ[ℂ] C) (ψ : B →⋆ₐ[ℂ] C) + (h : ∀ a b, Commute (φ a) (ψ b)) (a : A) (b : B) : + OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (a ⊗ₜ[ℂ] b) = φ a * ψ b := rfl + exact { + toSeminorm := (normSeminorm ℂ C).comp (OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h).toLinearMap + mul_le x y := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x * OAI.KirchbergRordam.MaxTensor.rawEquiv y)‖ ≤ + ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ * ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv y)‖ + rw [map_mul] + exact norm_mul_le _ _ + star_eq x := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (star (OAI.KirchbergRordam.MaxTensor.rawEquiv x))‖ = ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ + rw [map_star, norm_star] + cstar_eq x := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (star (OAI.KirchbergRordam.MaxTensor.rawEquiv x) * OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ = + ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ * ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (OAI.KirchbergRordam.MaxTensor.rawEquiv x)‖ + rw [map_mul, map_star, CStarRing.norm_star_mul_self] + tmul_le a b := by + change ‖OAI.KirchbergRordam.MaxTensor.liftRaw φ ψ h (a ⊗ₜ[ℂ] b)‖ ≤ ‖a‖ * ‖b‖ + rw [h_MaxTensor_liftRaw_tmul] + exact (norm_mul_le _ _).trans (mul_le_mul + (NonUnitalStarAlgHom.norm_apply_le φ a) (NonUnitalStarAlgHom.norm_apply_le ψ b) + (norm_nonneg _) (norm_nonneg _)) + } + +end KirchbergRordam.MaxTensor + +namespace KirchbergRordam.Spatial +open Set Module NormedSpace +open scoped TensorProduct InnerProductSpace + +variable {H K : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] + +abbrev Hilbert (H K : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] := Completion (H ⊗[ℂ] K) + +def map (T : H →L[ℂ] H) (S : K →L[ℂ] K) : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K := + (TensorProduct.mapL T S).completion + +variable [CompleteSpace H] [CompleteSpace K] + +def left : (H →L[ℂ] H) →⋆ₐ[ℂ] (OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K) := by + classical + have h_Spatial_ext {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_add_left__simp_1_1 (a b : H ⊗[ℂ] K) : (a : Completion (H ⊗[ℂ] K)) + (b : Completion (H ⊗[ℂ] K)) = ((a + b : H ⊗[ℂ] K) : Completion (H ⊗[ℂ] K)) := (Completion.coe_add a b).symm + have h_Spatial_map_coe (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_add_left (T U : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T + U) S = OAI.KirchbergRordam.Spatial.map T S + OAI.KirchbergRordam.Spatial.map U S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_add_left, (@h_Spatial_map_add_left__simp_1_1)] + have h_Spatial_map_mul (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_map_one : OAI.KirchbergRordam.Spatial.map (1 : H →L[ℂ] H) (1 : K →L[ℂ] K) = 1 := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, show (1 : H →L[ℂ] H) = ContinuousLinearMap.id ℂ H from rfl, + show (1 : K →L[ℂ] K) = ContinuousLinearMap.id ℂ K from rfl] + have h_Spatial_map_smul_left (z : ℂ) (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (z • T) S = z • OAI.KirchbergRordam.Spatial.map T S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_smul_left, ← Completion.coe_smul] + have h_Spatial_map_inner_algebraic (T : H →L[ℂ] H) (S : K →L[ℂ] K) + (x y : H ⊗[ℂ] K) : + ⟪TensorProduct.mapL (star T) (star S) x, y⟫_ℂ = + ⟪x, TensorProduct.mapL T S y⟫_ℂ := by + induction x using TensorProduct.inductionOn with + | add x z hx hz => simp only [map_add, inner_add_left, hx, hz] + | tmul a b => + induction y using TensorProduct.inductionOn with + | add y z hy hz => simp only [map_add, inner_add_right, hy, hz] + | tmul c d => + simp only [TensorProduct.mapL_tmul, TensorProduct.inner_tmul, + ContinuousLinearMap.star_eq_adjoint, ContinuousLinearMap.adjoint_inner_left] + have h_Spatial_map_inner (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x y : OAI.KirchbergRordam.Spatial.Hilbert H K) : + ⟪OAI.KirchbergRordam.Spatial.map (star T) (star S) x, y⟫_ℂ = ⟪x, OAI.KirchbergRordam.Spatial.map T S y⟫_ℂ := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simpa [h_Spatial_map_coe] using h_Spatial_map_inner_algebraic T S x y + have h_Spatial_map_star (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (star T) (star S) = star (OAI.KirchbergRordam.Spatial.map T S) := by + apply ContinuousLinearMap.ext + intro x + apply ext_inner_right ℂ + intro y + rw [h_Spatial_map_inner, ContinuousLinearMap.star_eq_adjoint, + ContinuousLinearMap.adjoint_inner_left] + exact { + toFun T := OAI.KirchbergRordam.Spatial.map T 1 + map_zero' := by apply h_Spatial_ext; intro x; simp [OAI.KirchbergRordam.Spatial.map] + map_one' := h_Spatial_map_one + map_add' T U := h_Spatial_map_add_left T U 1 + map_mul' T U := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_mul T U (1 : K →L[ℂ] K) 1 + commutes' z := by + change OAI.KirchbergRordam.Spatial.map (z • 1) 1 = z • 1 + rw [h_Spatial_map_smul_left, h_Spatial_map_one] + map_star' T := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_star T (1 : K →L[ℂ] K) + } + +def right : (K →L[ℂ] K) →⋆ₐ[ℂ] (OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K) := by + classical + have h_Spatial_ext {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_add_right__simp_1_1 (a b : H ⊗[ℂ] K) : (a : Completion (H ⊗[ℂ] K)) + (b : Completion (H ⊗[ℂ] K)) = ((a + b : H ⊗[ℂ] K) : Completion (H ⊗[ℂ] K)) := (Completion.coe_add a b).symm + have h_Spatial_map_coe (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_add_right (T : H →L[ℂ] H) (S U : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T (S + U) = OAI.KirchbergRordam.Spatial.map T S + OAI.KirchbergRordam.Spatial.map T U := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_add_right, (@h_Spatial_map_add_right__simp_1_1)] + have h_Spatial_map_mul (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_map_one : OAI.KirchbergRordam.Spatial.map (1 : H →L[ℂ] H) (1 : K →L[ℂ] K) = 1 := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, show (1 : H →L[ℂ] H) = ContinuousLinearMap.id ℂ H from rfl, + show (1 : K →L[ℂ] K) = ContinuousLinearMap.id ℂ K from rfl] + have h_Spatial_map_smul_right (z : ℂ) (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T (z • S) = z • OAI.KirchbergRordam.Spatial.map T S := by + apply h_Spatial_ext + intro x + simp [h_Spatial_map_coe, TensorProduct.mapL_smul_right, ← Completion.coe_smul] + have h_Spatial_map_inner_algebraic (T : H →L[ℂ] H) (S : K →L[ℂ] K) + (x y : H ⊗[ℂ] K) : + ⟪TensorProduct.mapL (star T) (star S) x, y⟫_ℂ = + ⟪x, TensorProduct.mapL T S y⟫_ℂ := by + induction x using TensorProduct.inductionOn with + | add x z hx hz => simp only [map_add, inner_add_left, hx, hz] + | tmul a b => + induction y using TensorProduct.inductionOn with + | add y z hy hz => simp only [map_add, inner_add_right, hy, hz] + | tmul c d => + simp only [TensorProduct.mapL_tmul, TensorProduct.inner_tmul, + ContinuousLinearMap.star_eq_adjoint, ContinuousLinearMap.adjoint_inner_left] + have h_Spatial_map_inner (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x y : OAI.KirchbergRordam.Spatial.Hilbert H K) : + ⟪OAI.KirchbergRordam.Spatial.map (star T) (star S) x, y⟫_ℂ = ⟪x, OAI.KirchbergRordam.Spatial.map T S y⟫_ℂ := by + induction x, y using Completion.induction_on₂ with + | hp => exact isClosed_eq (by fun_prop) (by fun_prop) + | ih x y => simpa [h_Spatial_map_coe] using h_Spatial_map_inner_algebraic T S x y + have h_Spatial_map_star (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (star T) (star S) = star (OAI.KirchbergRordam.Spatial.map T S) := by + apply ContinuousLinearMap.ext + intro x + apply ext_inner_right ℂ + intro y + rw [h_Spatial_map_inner, ContinuousLinearMap.star_eq_adjoint, + ContinuousLinearMap.adjoint_inner_left] + exact { + toFun S := OAI.KirchbergRordam.Spatial.map 1 S + map_zero' := by apply h_Spatial_ext; intro x; simp [OAI.KirchbergRordam.Spatial.map] + map_one' := h_Spatial_map_one + map_add' T U := h_Spatial_map_add_right 1 T U + map_mul' T U := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_mul (1 : H →L[ℂ] H) 1 T U + commutes' z := by + change OAI.KirchbergRordam.Spatial.map 1 (z • 1) = z • 1 + rw [h_Spatial_map_smul_right, h_Spatial_map_one] + map_star' S := by simpa [h_Spatial_map_coe, h_Spatial_map_one] using h_Spatial_map_star (1 : H →L[ℂ] H) S + } + +end KirchbergRordam.Spatial + +namespace KirchbergRordam.MinTensor +open scoped TensorProduct +universe u +variable (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] + +structure RepresentationPair where + H : Type u + K : Type u + normH : NormedAddCommGroup H + innerH : InnerProductSpace ℂ H + completeH : CompleteSpace H + normK : NormedAddCommGroup K + innerK : InnerProductSpace ℂ K + completeK : CompleteSpace K + leftRep : A →⋆ₐ[ℂ] (H →L[ℂ] H) + rightRep : B →⋆ₐ[ℂ] (K →L[ℂ] K) + +attribute [instance] RepresentationPair.normH RepresentationPair.innerH + RepresentationPair.completeH RepresentationPair.normK RepresentationPair.innerK + RepresentationPair.completeK +variable {A B} +def RepresentationPair.left (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + A →⋆ₐ[ℂ] (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K) := + Spatial.left.comp ρ.leftRep + +def RepresentationPair.right (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + B →⋆ₐ[ℂ] (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K) := + Spatial.right.comp ρ.rightRep + +def RepresentationPair.crossSeminorm (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) : + MaxTensor.CrossSeminorm A B := by + classical + have h_Spatial_ext {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] {T S : OAI.KirchbergRordam.Spatial.Hilbert H K →L[ℂ] OAI.KirchbergRordam.Spatial.Hilbert H K} + (h : ∀ x : H ⊗[ℂ] K, T x = S x) : T = S := by + apply ContinuousLinearMap.ext + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_eq T.continuous S.continuous + | ih x => exact h x + have h_Spatial_map_coe {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] (T : H →L[ℂ] H) (S : K →L[ℂ] K) (x : H ⊗[ℂ] K) : + OAI.KirchbergRordam.Spatial.map T S (x : OAI.KirchbergRordam.Spatial.Hilbert H K) = (TensorProduct.mapL T S x : H ⊗[ℂ] K) := by + simp [OAI.KirchbergRordam.Spatial.map] + have h_Spatial_map_mul {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] (T U : H →L[ℂ] H) (S V : K →L[ℂ] K) : + OAI.KirchbergRordam.Spatial.map (T * U) (S * V) = OAI.KirchbergRordam.Spatial.map T S * OAI.KirchbergRordam.Spatial.map U V := by + apply h_Spatial_ext + intro x + simp only [mul_apply_eq_comp, h_Spatial_map_coe, TensorProduct.mapL_mul] + have h_Spatial_left_right_commute {H : Type u} {K : Type u} [inst2 : NormedAddCommGroup H] [inst3 : InnerProductSpace ℂ H] [inst4 : NormedAddCommGroup K] [inst5 : InnerProductSpace ℂ K] [inst6 : CompleteSpace H] [inst7 : CompleteSpace K] (T : H →L[ℂ] H) (S : K →L[ℂ] K) : + Commute (OAI.KirchbergRordam.Spatial.left (K := K) T) (OAI.KirchbergRordam.Spatial.right (H := H) S) := by + change OAI.KirchbergRordam.Spatial.map T 1 * OAI.KirchbergRordam.Spatial.map 1 S = OAI.KirchbergRordam.Spatial.map 1 S * OAI.KirchbergRordam.Spatial.map T 1 + rw [← h_Spatial_map_mul, ← h_Spatial_map_mul] + simp + have h_MinTensor_RepresentationPair_commute (ρ : OAI.KirchbergRordam.MinTensor.RepresentationPair A B) (a : A) (b : B) : + Commute (ρ.left a) (ρ.right b) := + (@h_Spatial_left_right_commute) _ _ + exact + MaxTensor.representationSeminorm (A := A) (B := B) + (C := (Spatial.Hilbert ρ.H ρ.K →L[ℂ] Spatial.Hilbert ρ.H ρ.K)) + ρ.left ρ.right (h_MinTensor_RepresentationPair_commute ρ) + +def spatialIndex : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B) → MaxTensor.CrossSeminorm A B + | none => default + | some ρ => ρ.crossSeminorm + +def seminorm : Seminorm ℂ (A ⊗[ℂ] B) := + ⨆ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm + +end KirchbergRordam.MinTensor +namespace KirchbergRordam.MinTensor +open scoped TensorProduct +open Set Module NormedSpace +universe u +variable {A B : Type u} [CStarAlgebra A] [CStarAlgebra B] +local instance instRingTensorProductComplex_analysis : Ring (A ⊗[ℂ] B) := + _root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B) + +end KirchbergRordam.MinTensor + +namespace KirchbergRordam.MinTensor +universe u +variable (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] + +def Raw : Type u := A ⊗[ℂ] B + +variable {A B} +instance : Ring (OAI.KirchbergRordam.MinTensor.Raw A B) := + _root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B) + +instance : Algebra ℂ (OAI.KirchbergRordam.MinTensor.Raw A B) := _root_.Algebra.TensorProduct.instAlgebra + +instance instStarRingRaw : StarRing (OAI.KirchbergRordam.MinTensor.Raw A B) := + inferInstanceAs (StarRing (MaxTensor.Raw A B)) + +def rawRingSeminorm : RingSeminorm (OAI.KirchbergRordam.MinTensor.Raw A B) := by + classical + have h_MaxTensor_bounded_at {A : Type u} {B : Type u} [inst2 : CStarAlgebra A] [inst3 : CStarAlgebra B] (x : A ⊗[ℂ] B) : + ∃ C : ℝ, ∀ p : OAI.KirchbergRordam.MaxTensor.CrossSeminorm A B, p.toSeminorm x ≤ C := by + induction x using TensorProduct.inductionOn with + | tmul a b => exact ⟨‖a‖ * ‖b‖, fun p => p.tmul_le a b⟩ + | add x y hx hy => + obtain ⟨C, hC⟩ := hx + obtain ⟨D, hD⟩ := hy + exact ⟨C + D, fun p => (map_add_le_add p.toSeminorm x y).trans + (add_le_add (hC p) (hD p))⟩ + have h_MinTensor_bounded : BddAbove (Set.range (fun ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B) => + (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm)) := by + rw [Seminorm.bddAbove_range_iff] + intro x + obtain ⟨C,hC⟩ := (@h_MaxTensor_bounded_at) x + exact ⟨C,by rintro _ ⟨ρ,rfl⟩; exact hC _⟩ + have h_MinTensor_seminorm_apply (x : A ⊗[ℂ] B) : + OAI.KirchbergRordam.MinTensor.seminorm x=⨆ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x := + Seminorm.iSup_apply h_MinTensor_bounded + have h_MinTensor_le_seminorm (ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B)) (x : A ⊗[ℂ] B) : + (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x ≤ OAI.KirchbergRordam.MinTensor.seminorm x := by + rw [h_MinTensor_seminorm_apply] + apply le_ciSup _ ρ + obtain ⟨C,hC⟩ := (@h_MaxTensor_bounded_at) x + exact ⟨C,by rintro _ ⟨ρ,rfl⟩; exact hC _⟩ + have h_MinTensor_seminorm_le {x : A ⊗[ℂ] B} {C : ℝ} + (h : ∀ ρ : Option (OAI.KirchbergRordam.MinTensor.RepresentationPair A B), (OAI.KirchbergRordam.MinTensor.spatialIndex ρ).toSeminorm x ≤ C) : + OAI.KirchbergRordam.MinTensor.seminorm x ≤ C := by + rw [h_MinTensor_seminorm_apply] + exact ciSup_le h + have h_MinTensor_seminorm_mul_le (x y : A ⊗[ℂ] B) : + @LE.le ℝ Real.instLE + (OAI.KirchbergRordam.MinTensor.seminorm (@Mul.mul (A ⊗[ℂ] B) + (_root_.Algebra.TensorProduct.instRing (R := ℂ) (A := A) (B := B)).toMul x y)) + (@Mul.mul ℝ Real.instMul (OAI.KirchbergRordam.MinTensor.seminorm x) (OAI.KirchbergRordam.MinTensor.seminorm y)) := by + apply h_MinTensor_seminorm_le + intro ρ + exact ((OAI.KirchbergRordam.MinTensor.spatialIndex ρ).mul_le x y).trans (mul_le_mul (h_MinTensor_le_seminorm ρ x) + (h_MinTensor_le_seminorm ρ y) (apply_nonneg _ _) (apply_nonneg _ _)) + exact { + __ := (OAI.KirchbergRordam.MinTensor.seminorm (A := A) (B := B)).toAddGroupSeminorm + mul_le' := h_MinTensor_seminorm_mul_le + } + +instance : SeminormedRing (OAI.KirchbergRordam.MinTensor.Raw A B) := OAI.KirchbergRordam.MinTensor.rawRingSeminorm.toSeminormedRing + +abbrev Algebra (A B : Type u) [CStarAlgebra A] [CStarAlgebra B] := + UniformSpace.Completion (OAI.KirchbergRordam.MinTensor.Raw A B) + +end KirchbergRordam.MinTensor + +namespace KirchbergRordam.MatrixTensor +open scoped Matrix Kronecker +variable {ι κ : Type*} [Fintype ι] [Fintype κ] [DecidableEq ι] [DecidableEq κ] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def leftMatrixAlgebra : Matrix ι ι ℂ →⋆ₐ[ℂ] + Matrix (ι × κ) (ι × κ) ℂ where + toFun a := a ⊗ₖ (1 : Matrix κ κ ℂ) + map_zero' := Matrix.zero_kronecker _ + map_one' := Matrix.one_kronecker_one + map_add' a b := Matrix.add_kronecker _ _ _ + map_mul' a b := by + simpa only [mul_one] using Matrix.mul_kronecker_mul a b + (1 : Matrix κ κ ℂ) (1 : Matrix κ κ ℂ) + commutes' z := by + simp only [Algebra.algebraMap_eq_smul_one, Matrix.smul_kronecker, + Matrix.one_kronecker_one] + map_star' a := by + change aᴴ ⊗ₖ (1 : Matrix κ κ ℂ) = (a ⊗ₖ 1)ᴴ + rw [Matrix.conjTranspose_kronecker, Matrix.conjTranspose_one] + +def rightMatrixAlgebra : Matrix κ κ ℂ →⋆ₐ[ℂ] + Matrix (ι × κ) (ι × κ) ℂ where + toFun a := (1 : Matrix ι ι ℂ) ⊗ₖ a + map_zero' := Matrix.kronecker_zero _ + map_one' := Matrix.one_kronecker_one + map_add' a b := Matrix.kronecker_add _ _ _ + map_mul' a b := by + simpa only [mul_one] using Matrix.mul_kronecker_mul + (1 : Matrix ι ι ℂ) (1 : Matrix ι ι ℂ) a b + commutes' z := by + simp only [Algebra.algebraMap_eq_smul_one, Matrix.kronecker_smul, + Matrix.one_kronecker_one] + map_star' a := by + change (1 : Matrix ι ι ℂ) ⊗ₖ aᴴ = (1 ⊗ₖ a)ᴴ + rw [Matrix.conjTranspose_kronecker, Matrix.conjTranspose_one] + +def leftMatrix : OAI.KirchbergRordam.MatrixTensor.Mat ι →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixTensor.Mat (ι×κ) := + CStarMatrix.ofMatrixStarAlgEquiv.toStarAlgHom.comp + (OAI.KirchbergRordam.MatrixTensor.leftMatrixAlgebra.comp CStarMatrix.ofMatrixStarAlgEquiv.symm.toStarAlgHom) + +def rightMatrix : OAI.KirchbergRordam.MatrixTensor.Mat κ →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixTensor.Mat (ι×κ) := + CStarMatrix.ofMatrixStarAlgEquiv.toStarAlgHom.comp + (OAI.KirchbergRordam.MatrixTensor.rightMatrixAlgebra.comp CStarMatrix.ofMatrixStarAlgEquiv.symm.toStarAlgHom) + +end KirchbergRordam.MatrixTensor + +namespace KirchbergRordam.PrimeDimensionDrop +open MatrixTensor +open scoped Matrix Kronecker ComplexOrder CStarAlgebra + +abbrev Fiber (p q : ℕ) := OAI.KirchbergRordam.MatrixTensor.Mat (Fin p × Fin q) + +def eval (p q : ℕ) (t : unitInterval) : + C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q where + toFun f := f t + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def subalgebra (p q : ℕ) : StarSubalgebra ℂ C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + (OAI.KirchbergRordam.MatrixTensor.leftMatrix (ι := Fin p) (κ := Fin q)).range.comap (OAI.KirchbergRordam.PrimeDimensionDrop.eval p q 0) ⊓ + (OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι := Fin p) (κ := Fin q)).range.comap (OAI.KirchbergRordam.PrimeDimensionDrop.eval p q 1) + +instance (p q : ℕ) : FiniteDimensional ℂ (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + inferInstanceAs (FiniteDimensional ℂ (Matrix (Fin p × Fin q) (Fin p × Fin q) ℂ)) + +instance (p q : ℕ) : IsClosed (OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q : Set C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) := by + change IsClosed ((fun f : C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) => f 0) ⁻¹' + ((OAI.KirchbergRordam.MatrixTensor.leftMatrix (ι := Fin p) (κ := Fin q)).range : Set (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) ∩ + (fun f : C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) => f 1) ⁻¹' + ((OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι := Fin p) (κ := Fin q)).range : Set (OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q))) + exact ((OAI.KirchbergRordam.MatrixTensor.leftMatrix.range.toSubalgebra.toSubmodule.closed_of_finiteDimensional).preimage + (continuous_eval_const (0 : unitInterval))).inter + ((OAI.KirchbergRordam.MatrixTensor.rightMatrix.range.toSubalgebra.toSubmodule.closed_of_finiteDimensional).preimage + (continuous_eval_const (1 : unitInterval))) + +abbrev Algebra (p q : ℕ) := OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q + +instance (p q : ℕ) : SubringClass + (StarSubalgebra ℂ C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q) := + StarSubalgebra.subringClass (R := ℂ) (A := C(unitInterval, OAI.KirchbergRordam.PrimeDimensionDrop.Fiber p q)) + +instance (p q : ℕ) : CStarAlgebra (OAI.KirchbergRordam.PrimeDimensionDrop.Algebra p q) := StarSubalgebra.cstarAlgebra (OAI.KirchbergRordam.PrimeDimensionDrop.subalgebra p q) + +end KirchbergRordam.PrimeDimensionDrop + +namespace KirchbergRordam.UnitaryPaths + +variable {A : Type*} [CStarAlgebra A] + +def phase (t : unitInterval) : ℂ := Complex.exp (((t:ℝ) * Real.pi) * Complex.I) + +def involutionValue (U : A) (t : unitInterval) : A := + ((1 + OAI.KirchbergRordam.UnitaryPaths.phase t) / 2) • (1:A) + ((1 - OAI.KirchbergRordam.UnitaryPaths.phase t) / 2) • U + +def involutionPath (U : unitary A) (hs : star (U:A) = U) : Path 1 U := by + classical + have h_UnitaryPaths_phase_continuous : Continuous OAI.KirchbergRordam.UnitaryPaths.phase := by unfold OAI.KirchbergRordam.UnitaryPaths.phase; fun_prop + have h_UnitaryPaths_involutionValue_continuous (U : A) : Continuous (OAI.KirchbergRordam.UnitaryPaths.involutionValue U) := by + unfold OAI.KirchbergRordam.UnitaryPaths.involutionValue + fun_prop + have h_UnitaryPaths_phase_unitary (t : unitInterval) : star (OAI.KirchbergRordam.UnitaryPaths.phase t) * OAI.KirchbergRordam.UnitaryPaths.phase t = 1 := by + have hn : ‖OAI.KirchbergRordam.UnitaryPaths.phase t‖ = 1 := by + simpa [OAI.KirchbergRordam.UnitaryPaths.phase, Complex.ofReal_mul] using Complex.norm_exp_ofReal_mul_I ((t:ℝ) * Real.pi) + rw [Complex.star_def, ← Complex.normSq_eq_conj_mul_self, Complex.normSq_eq_norm_sq, hn] + norm_num + have h_UnitaryPaths_involutionValue_unitary (U : A) (hs : star U = U) (hm : U * U = 1) + (t : unitInterval) : OAI.KirchbergRordam.UnitaryPaths.involutionValue U t ∈ unitary A := by + have hz := h_UnitaryPaths_phase_unitary t + have h1 : (star ((1:ℂ)+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + (star ((1:ℂ)-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)=1 := by + simp only [star_add,star_sub,star_one] + calc + _ = (1+star (OAI.KirchbergRordam.UnitaryPaths.phase t)*OAI.KirchbergRordam.UnitaryPaths.phase t)/2 := by ring + _ = 1 := by rw [hz]; norm_num + have h2 : (star ((1:ℂ)+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + (star ((1:ℂ)-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)=0 := by + simp only [star_add,star_sub,star_one] + calc + _ = (1-star (OAI.KirchbergRordam.UnitaryPaths.phase t)*OAI.KirchbergRordam.UnitaryPaths.phase t)/2 := by ring + _ = 0 := by rw [hz]; norm_num + have h : star (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t) * OAI.KirchbergRordam.UnitaryPaths.involutionValue U t = 1 := by + simp only [OAI.KirchbergRordam.UnitaryPaths.involutionValue, star_add, star_smul, star_one, hs, star_div₀, + star_ofNat, star_sub, smul_add, add_mul, mul_add, smul_mul_assoc, + mul_smul_comm, smul_smul, one_mul, mul_one, hm] + calc + _ = (((1+star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + ((1-star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)) • (1:A) + + (((1+star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1-OAI.KirchbergRordam.UnitaryPaths.phase t)/2)+ + ((1-star (OAI.KirchbergRordam.UnitaryPaths.phase t))/2)*((1+OAI.KirchbergRordam.UnitaryPaths.phase t)/2)) • U := by + rw [add_smul, add_smul]; module + _ = 1 := by + simp only [star_add, star_sub, star_one] at h1 h2 + rw [h1, h2, one_smul, zero_smul, add_zero] + refine ⟨h, ?_⟩ + have hc : Commute (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t) (star (OAI.KirchbergRordam.UnitaryPaths.involutionValue U t)) := by + unfold OAI.KirchbergRordam.UnitaryPaths.involutionValue + simp only [star_add, star_smul, star_one, hs] + exact ((Commute.one_left _).smul_left _).add_left + ((((Commute.one_right U).smul_right _).add_right + ((Commute.refl U).smul_right _)).smul_left _) + exact hc.eq.trans h + have h_UnitaryPaths_phase_one : OAI.KirchbergRordam.UnitaryPaths.phase 1 = -1 := by simp [OAI.KirchbergRordam.UnitaryPaths.phase, Complex.exp_pi_mul_I] + have h_UnitaryPaths_phase_zero : OAI.KirchbergRordam.UnitaryPaths.phase 0 = 1 := by simp [OAI.KirchbergRordam.UnitaryPaths.phase] + exact { + toFun t := ⟨OAI.KirchbergRordam.UnitaryPaths.involutionValue (U:A) t, + h_UnitaryPaths_involutionValue_unitary (U:A) hs (by simpa only [hs] using Unitary.coe_star_mul_self U) t⟩ + continuous_toFun := (h_UnitaryPaths_involutionValue_continuous _).subtype_mk _ + source' := by apply Subtype.ext; simp [h_UnitaryPaths_phase_zero, OAI.KirchbergRordam.UnitaryPaths.involutionValue] + target' := by apply Subtype.ext; simp [h_UnitaryPaths_phase_one, OAI.KirchbergRordam.UnitaryPaths.involutionValue] + } + +end KirchbergRordam.UnitaryPaths + +namespace KirchbergRordam.MatrixPermutationPath +open scoped Matrix +variable {ι : Type*} [Fintype ι] [DecidableEq ι] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def perm (σ : Equiv.Perm ι) : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) := + ⟨CStarMatrix.ofMatrix (σ⁻¹.permMatrix ℂ), by + constructor + · change (σ⁻¹.permMatrix ℂ)ᴴ * σ⁻¹.permMatrix ℂ = 1 + rw [Matrix.conjTranspose_permMatrix, ← Matrix.permMatrix_mul] + simp + · change σ⁻¹.permMatrix ℂ * (σ⁻¹.permMatrix ℂ)ᴴ = 1 + rw [Matrix.conjTranspose_permMatrix, ← Matrix.permMatrix_mul] + simp⟩ + +def path (σ τ : Equiv.Perm ι) : Path (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) (OAI.KirchbergRordam.MatrixPermutationPath.perm τ) := by + classical + have h_MatrixPermutationPath_perm_mul (σ τ : Equiv.Perm ι) : OAI.KirchbergRordam.MatrixPermutationPath.perm (σ*τ) = OAI.KirchbergRordam.MatrixPermutationPath.perm σ * OAI.KirchbergRordam.MatrixPermutationPath.perm τ := by + apply Subtype.ext + change ((σ*τ)⁻¹).permMatrix ℂ = σ⁻¹.permMatrix ℂ * τ⁻¹.permMatrix ℂ + simp + have h_MatrixPermutationPath_perm_one : OAI.KirchbergRordam.MatrixPermutationPath.perm (1 : Equiv.Perm ι) = 1 := by + apply Subtype.ext + change (1⁻¹ : Equiv.Perm ι).permMatrix ℂ = 1 + simp + have h_MatrixPermutationPath_perm_swap_selfadjoint (i j : ι) : star (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j) : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) = + (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j) : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) := by + change ((Equiv.swap i j)⁻¹.permMatrix ℂ)ᴴ = (Equiv.swap i j)⁻¹.permMatrix ℂ + simp + have h_MatrixPermutationPath_joined_one_perm (σ : Equiv.Perm ι) : Joined (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) := by + induction σ using Equiv.Perm.swap_induction_on with + | one => simpa [h_MatrixPermutationPath_perm_one] using Joined.refl (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) + | swap_mul σ i j hij ih => + rw [h_MatrixPermutationPath_perm_mul] + have hi : Joined (1 : unitary (OAI.KirchbergRordam.MatrixPermutationPath.Mat ι)) (OAI.KirchbergRordam.MatrixPermutationPath.perm (Equiv.swap i j)) := + ⟨UnitaryPaths.involutionPath _ (h_MatrixPermutationPath_perm_swap_selfadjoint i j)⟩ + simpa only [one_mul] using hi.mul ih + exact + ((h_MatrixPermutationPath_joined_one_perm σ).symm.trans (h_MatrixPermutationPath_joined_one_perm τ)).somePath + +end KirchbergRordam.MatrixPermutationPath + +namespace KirchbergRordam.MatrixDiagonalPath +open scoped ComplexOrder CStarAlgebra Matrix +variable {ι κ ν : Type*} [Fintype ι] [DecidableEq ι] + [Fintype κ] [instDecidableEqκ : DecidableEq κ] [Fintype ν] [DecidableEq ν] +abbrev Mat (ι : Type*) := CStarMatrix ι ι ℂ + +def block : (ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι) where + toFun a := CStarMatrix.ofMatrix (Matrix.blockDiagonal a) + map_zero' := Matrix.blockDiagonal_zero + map_one' := Matrix.blockDiagonal_one + map_add' := Matrix.blockDiagonal_add + map_mul' := Matrix.blockDiagonal_mul + commutes' z := by + change Matrix.blockDiagonal (fun _ : ι => (algebraMap ℂ (Matrix κ κ ℂ)) z) = + algebraMap ℂ (Matrix (κ × ι) (κ × ι) ℂ) z + simp only [Algebra.algebraMap_eq_smul_one] + exact (Matrix.blockDiagonal_smul z (1 : ι → Matrix κ κ ℂ)).trans + (congrArg (z • ·) Matrix.blockDiagonal_one) + map_star' a := Matrix.blockDiagonal_conjTranspose a |>.symm + +def evaluationBlock (ξ : ι → C(unitInterval, unitInterval)) (t : unitInterval) : + C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι) where + toFun f := OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => f (ξ i t)) + map_zero' := map_zero OAI.KirchbergRordam.MatrixDiagonalPath.block + map_one' := map_one OAI.KirchbergRordam.MatrixDiagonalPath.block + map_add' first second := map_add OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => first (ξ index t)) (fun index => second (ξ index t)) + map_mul' first second := map_mul OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => first (ξ index t)) (fun index => second (ξ index t)) + commutes' z := OAI.KirchbergRordam.MatrixDiagonalPath.block.commutes z + map_star' path := map_star OAI.KirchbergRordam.MatrixDiagonalPath.block (fun index => path (ξ index t)) + +def diagonal (ξ : ι → C(unitInterval, unitInterval)) : + C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) →⋆ₐ[ℂ] C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ × ι)) := by + classical + have h_MatrixDiagonalPath_evaluationBlock_continuous (ξ : ι → C(unitInterval, unitInterval)) + (f : C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ)) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f) := + (map_continuous OAI.KirchbergRordam.MatrixDiagonalPath.block).comp (continuous_pi (fun i => f.continuous.comp (ξ i).continuous)) + exact { + toFun f := ⟨fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f, h_MatrixDiagonalPath_evaluationBlock_continuous ξ f⟩ + map_zero' := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_zero) _) _ + map_one' := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_one) _) _ + map_add' f g := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_add f g) _) _ + map_mul' f g := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).map_mul f g) _) _ + commutes' z := by ext t; exact congrFun (congrFun ((OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t).commutes z) _) _ + map_star' f := by ext t; exact congrFun (congrFun (map_star (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t) f) _) _ + } + +def interpolate (e₀ e₁ : κ ≃ ν) (t : unitInterval) : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ ≃⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν := + (CStarMatrix.reindexₐ ℂ ℂ e₀).trans + (Unitary.conjStarAlgAut ℂ _ + ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t)) + +end KirchbergRordam.MatrixDiagonalPath + +namespace KirchbergRordam.MatrixBlockReindex +open MatrixTensor (leftMatrix rightMatrix) +open MatrixDiagonalPath +open scoped ComplexOrder CStarAlgebra Matrix Kronecker +variable {P Q L R S T : Type*} + [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] + [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] + +def sumBlock : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P × OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q →⋆ₐ[ℂ] OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P ⊕ Q) where + toFun a := CStarMatrix.ofMatrix (Matrix.fromBlocks a.1 0 0 a.2) + map_zero' := by ext i j; cases i <;> cases j <;> rfl + map_one' := by + change Matrix.fromBlocks (1 : Matrix P P ℂ) 0 0 (1 : Matrix Q Q ℂ) = 1 + exact Matrix.fromBlocks_one + map_add' a b := by ext i j; cases i <;> cases j <;> simp [Matrix.fromBlocks] + map_mul' a b := by + change Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1 * CStarMatrix.ofMatrix.symm b.1) 0 0 + (CStarMatrix.ofMatrix.symm a.2 * CStarMatrix.ofMatrix.symm b.2) = + Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1) 0 0 (CStarMatrix.ofMatrix.symm a.2) * + Matrix.fromBlocks (CStarMatrix.ofMatrix.symm b.1) 0 0 (CStarMatrix.ofMatrix.symm b.2) + simp only [Matrix.fromBlocks_multiply, Matrix.mul_zero, Matrix.zero_mul, add_zero, zero_add] + commutes' z := by + ext i j; cases i <;> cases j <;> + simp [Algebra.algebraMap_eq_smul_one, Matrix.fromBlocks, CStarMatrix.one_apply] + map_star' a := by + change Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1)ᴴ 0 0 + (CStarMatrix.ofMatrix.symm a.2)ᴴ = + (Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a.1) 0 0 + (CStarMatrix.ofMatrix.symm a.2))ᴴ + simp only [Matrix.fromBlocks_conjTranspose, Matrix.conjTranspose_zero] + +end KirchbergRordam.MatrixBlockReindex + +namespace KirchbergRordam.MatrixBlockReindex +open MatrixDiagonalPath +open MatrixTensor (leftMatrix rightMatrix) +open scoped ComplexOrder CStarAlgebra Matrix +variable {P Q R S : Type*} [Fintype P] [Fintype Q] [Fintype R] [Fintype S] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [DecidableEq R] [DecidableEq S] +end KirchbergRordam.MatrixBlockReindex + +namespace KirchbergRordam.BalancedDropSystem + +def cardEquiv {α β : Type*} [Fintype α] [Fintype β] + (h : Fintype.card α = Fintype.card β) : α ≃ β := + Classical.choice ((Fintype.card_eq.mp h)) + +def half : unitInterval := by + classical + have h_BalancedDropSystem_half_mem : (1 / 2 : ℝ) ∈ Set.Icc (0 : ℝ) 1 := by + constructor <;> norm_num + exact + ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv Real.instOne.one + (Real.instNatCast.natCast 2), h_BalancedDropSystem_half_mem⟩ + +def lowerPath : C(unitInterval, unitInterval) := + ⟨fun point => ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv point.val + (Real.instNatCast.natCast 2), by + change (point : ℝ) / 2 ∈ Set.Icc (0 : ℝ) 1 + constructor <;> linarith [point.property.1, point.property.2]⟩, by + apply Continuous.subtype_mk + change Continuous (fun point : unitInterval => (point : ℝ) / 2) + fun_prop⟩ + +def upperPath : C(unitInterval, unitInterval) := + ⟨fun point => ⟨@Div.div ℝ Real.instDivInvMonoid.toDiv + (@Add.add ℝ Real.instAdd point.val Real.instOne.one) + (Real.instNatCast.natCast 2), by + change ((point : ℝ) + 1) / 2 ∈ Set.Icc (0 : ℝ) 1 + constructor <;> linarith [point.property.1, point.property.2]⟩, by + apply Continuous.subtype_mk + change Continuous (fun point : unitInterval => ((point : ℝ) + 1) / 2) + fun_prop⟩ + +end KirchbergRordam.BalancedDropSystem + +namespace KirchbergRordam.GeneralBlockReindex +open MatrixBlockReindex MatrixDiagonalPath + +open scoped CStarAlgebra Matrix +variable {P Q L R S T U : Type*} + [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] + [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] + [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] +def repackLeft (hL : Q × L ≃ U × T) (hR : R ≃ S × T) : + (P × Q) × (L ⊕ R) ≃ ((P × U) ⊕ ((P × Q) × S)) × T where + toFun x := match x.2 with + | .inl l => (.inl (x.1.1,(hL (x.1.2,l)).1),(hL (x.1.2,l)).2) + | .inr r => (.inr (x.1,(hR r).1),(hR r).2) + invFun x := match x.1 with + | .inl y => ((y.1,(hL.symm (y.2,x.2)).1),.inl (hL.symm (y.2,x.2)).2) + | .inr y => (y.1,.inr (hR.symm (y.2,x.2))) + left_inv x := by rcases x with ⟨⟨i,j⟩,l|r⟩ <;> simp + right_inv x := by rcases x with ⟨⟨i,u⟩|⟨ij,s⟩,t⟩ <;> simp + +def repackRight (hL : P × L ≃ T × U) (hR : R ≃ T × S) : + (P × Q) × (L ⊕ R) ≃ T × ((Q × U) ⊕ ((P × Q) × S)) := by + classical + have h_GeneralBlockReindex_left_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inl l) = (.inl (i,(hL (j,l)).1),(hL (j,l)).2) := rfl + have h_GeneralBlockReindex_left_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inr r) = (.inr ((i,j),(hR r).1),(hR r).2) := rfl + exact { + toFun x := match x.2 with + | .inl l => ((hL (x.1.1,l)).1,.inl (x.1.2,(hL (x.1.1,l)).2)) + | .inr r => ((hR r).1,.inr (x.1,(hR r).2)) + invFun x := match x.2 with + | .inl y => (((hL.symm (x.1,y.2)).1,y.1),.inl (hL.symm (x.1,y.2)).2) + | .inr y => (y.1,.inr (hR.symm (x.1,y.2))) + left_inv x := by rcases x with ⟨⟨i,j⟩,l|r⟩ <;> simp + right_inv x := by rcases x with ⟨t,⟨j,u⟩|⟨ij,s⟩⟩ <;> simp + } + +end KirchbergRordam.GeneralBlockReindex + +namespace KirchbergRordam.GeneralDropSystem +open MatrixDiagonalPath MatrixBlockReindex +open BalancedDropSystem (half lowerPath upperPath) +open scoped CStarAlgebra Matrix ComplexOrder + +structure Data (p q P Q : ℕ) where + lower : ℕ + upper : ℕ + middle : ℕ + zeroEnd : ℕ + zeroMid : ℕ + oneEnd : ℕ + oneMid : ℕ + lower_pos : 0 rfl + right_inv x := by rcases x with x|x|x <;> rfl + +def zeroReindex : OAI.KirchbergRordam.GeneralDropSystem.Index d ≃ Fin P × Fin Q := + (GeneralBlockReindex.repackLeft (OAI.KirchbergRordam.GeneralDropSystem.zeroLow d) (OAI.KirchbergRordam.GeneralDropSystem.zeroMid d)).trans + (Equiv.prodCongr (OAI.KirchbergRordam.GeneralDropSystem.zeroOuter d) (Equiv.refl _)) + +def oneReindex : OAI.KirchbergRordam.GeneralDropSystem.Index d ≃ Fin P × Fin Q := + (Equiv.prodCongr (Equiv.refl _) (OAI.KirchbergRordam.GeneralDropSystem.slotSwap d)).trans + ((GeneralBlockReindex.repackRight (OAI.KirchbergRordam.GeneralDropSystem.oneLow d) (OAI.KirchbergRordam.GeneralDropSystem.oneMid d)).trans + (Equiv.prodCongr (Equiv.refl _) (OAI.KirchbergRordam.GeneralDropSystem.oneOuter d))) + +def eigenpath : OAI.KirchbergRordam.GeneralDropSystem.Slot d → C(unitInterval,unitInterval) := + Sum.elim (fun _ => OAI.KirchbergRordam.BalancedDropSystem.lowerPath) (Sum.elim (fun _ => OAI.KirchbergRordam.BalancedDropSystem.upperPath) (fun _ => ContinuousMap.const _ OAI.KirchbergRordam.BalancedDropSystem.half)) + +section + +def interpolatedEvaluation.{sourceLevel, blockLevel, targetLevel} + {SourceIndex : Type sourceLevel} {BlockIndex : Type blockLevel} + {TargetIndex : Type targetLevel} + [sourceFintype : Fintype SourceIndex] [sourceDecidableEq : DecidableEq SourceIndex] + [blockFintype : Fintype BlockIndex] [blockDecidableEq : DecidableEq BlockIndex] + [targetFintype : Fintype TargetIndex] [targetDecidableEq : DecidableEq TargetIndex] + (zeroReindex oneReindex : SourceIndex × BlockIndex ≃ TargetIndex) + (eigenpath : BlockIndex → C(unitInterval, unitInterval)) (point : unitInterval) : + C(unitInterval, MatrixDiagonalPath.Mat SourceIndex) →⋆ₐ[ℂ] + MatrixDiagonalPath.Mat TargetIndex := + (@MatrixDiagonalPath.interpolate (SourceIndex × BlockIndex) TargetIndex + (instFintypeProd SourceIndex BlockIndex) + targetFintype targetDecidableEq zeroReindex oneReindex point).toStarAlgHom.comp + (@MatrixDiagonalPath.evaluationBlock BlockIndex SourceIndex + blockFintype blockDecidableEq sourceFintype sourceDecidableEq eigenpath point) + +end + +def fiberMap (t : unitInterval) : + C(unitInterval,PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] PrimeDimensionDrop.Fiber P Q := + @OAI.KirchbergRordam.GeneralDropSystem.interpolatedEvaluation (Fin p × Fin q) (OAI.KirchbergRordam.GeneralDropSystem.Slot d) (Fin P × Fin Q) + (instFintypeProd (Fin p) (Fin q)) inferInstance + (instFintypeSum (OAI.KirchbergRordam.GeneralDropSystem.Low d) (OAI.KirchbergRordam.GeneralDropSystem.High d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d)) inferInstance + (instFintypeProd (Fin P) (Fin Q)) inferInstance + (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) t + +def continuousFamily {Source Target : Type*} [CStarAlgebra Source] [CStarAlgebra Target] + (family : unitInterval → Source →⋆ₐ[ℂ] Target) + (continuous_family : ∀ value, Continuous (fun point => family point value)) : + Source →⋆ₐ[ℂ] C(unitInterval, Target) where + toFun value := ⟨fun point => family point value, continuous_family value⟩ + map_zero' := ContinuousMap.ext fun point => (family point).map_zero + map_one' := ContinuousMap.ext fun point => (family point).map_one + map_add' first second := ContinuousMap.ext fun point => (family point).map_add first second + map_mul' first second := ContinuousMap.ext fun point => (family point).map_mul first second + commutes' scalar := ContinuousMap.ext fun point => (family point).commutes scalar + map_star' value := ContinuousMap.ext fun point => map_star (family point) value + +def rawStep : + C(unitInterval, PrimeDimensionDrop.Fiber p q) →⋆ₐ[ℂ] + C(unitInterval, PrimeDimensionDrop.Fiber P Q) := by + classical + have h_MatrixDiagonalPath_evaluationBlock_continuous {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (ξ : ι → C(unitInterval, unitInterval)) + (f : C(unitInterval, OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ)) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock ξ t f) := + (map_continuous OAI.KirchbergRordam.MatrixDiagonalPath.block).comp (continuous_pi (fun i => f.continuous.comp (ξ i).continuous)) + have h_MatrixDiagonalPath_interpolate_continuous + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (f : unitInterval → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) + (hf : Continuous f) : Continuous (fun t => OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ t (f t)) := by + change Continuous (fun t => ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν) * + (CStarMatrix.reindexₐ ℂ ℂ e₀) (f t) * + star ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν)) + have hu : Continuous (fun t => ((MatrixPermutationPath.path 1 (e₀.symm.trans e₁)) t : OAI.KirchbergRordam.MatrixDiagonalPath.Mat ν)) := + continuous_subtype_val.comp (Path.continuous _) + exact (hu.mul ((map_continuous (CStarMatrix.reindexₐ ℂ ℂ e₀)).comp hf)).mul hu.star + have h_GeneralDropSystem_fiberMap_continuous (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (path : C(unitInterval, PrimeDimensionDrop.Fiber p q)) : + Continuous (fun point => OAI.KirchbergRordam.GeneralDropSystem.fiberMap d point path) := + h_MatrixDiagonalPath_interpolate_continuous (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) + (fun point => OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) point path) + (h_MatrixDiagonalPath_evaluationBlock_continuous (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) path) + exact + @OAI.KirchbergRordam.GeneralDropSystem.continuousFamily C(unitInterval, PrimeDimensionDrop.Fiber p q) + (PrimeDimensionDrop.Fiber P Q) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber p q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin p × Fin q) (instFintypeProd (Fin p) (Fin q)) inferInstance)) + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin P × Fin Q) (instFintypeProd (Fin P) (Fin Q)) inferInstance) + (OAI.KirchbergRordam.GeneralDropSystem.fiberMap d) (h_GeneralDropSystem_fiberMap_continuous d) + +def restrictToSubalgebras {Source Target : Type*} [CStarAlgebra Source] [CStarAlgebra Target] + (hom : Source →⋆ₐ[ℂ] Target) (domain : StarSubalgebra ℂ Source) + (codomain : StarSubalgebra ℂ Target) + (map_mem : ∀ value ∈ domain, hom value ∈ codomain) : domain →⋆ₐ[ℂ] codomain := + (hom.comp domain.subtype).codRestrict codomain (fun value => map_mem value value.property) + +def step := by + classical + have h_GeneralBlockReindex_right_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR ((i,j),.inl l) = ((hL (i,l)).1,.inl (j,(hL (i,l)).2)) := rfl + have h_GeneralBlockReindex_right_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR ((i,j),.inr r) = ((hR r).1,.inr ((i,j),(hR r).2)) := rfl + have h_MatrixBlockReindex_sumBlock_ll {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : P) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inl i) (Sum.inl j) = a i j := rfl + have h_MatrixBlockReindex_sumBlock_lr {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i : P) (j : Q) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inl i) (Sum.inr j) = 0 := rfl + have h_MatrixBlockReindex_sumBlock_rl {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i : Q) (j : P) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inr i) (Sum.inl j) = 0 := rfl + have h_MatrixBlockReindex_sumBlock_rr {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : Q) : + OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (a,b) (Sum.inr i) (Sum.inr j) = b i j := rfl + have h_MatrixBlockReindex_right_apply {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (i j : P) (k l : Q) : + OAI.KirchbergRordam.MatrixTensor.rightMatrix a (i,k) (j,l) = (if i=j then 1 else 0) * a k l := by + change (Matrix.kronecker (1 : Matrix P P ℂ) (CStarMatrix.ofMatrix.symm a)) (i,k) (j,l)=_ + simp [Matrix.one_apply] + have h_MatrixDiagonalPath_block_apply {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (a : ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) (i j : κ) (k l : ι) : + OAI.KirchbergRordam.MatrixDiagonalPath.block a (i,k) (j,l) = if k=l then a k i j else 0 := rfl + have h_GeneralBlockReindex_right_entry {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) (x y : (P×Q)×(L⊕R)) : + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.rightMatrix (ι:=P) a) (fun _ : R => m)) x y = + MatrixTensor.rightMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) + (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR x) (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR y) := by + rcases x with ⟨⟨i,j⟩,l|r⟩ <;> rcases y with ⟨⟨i',j'⟩,l'|r'⟩ + · by_cases he : (i,l)=(i',l') + · cases he; simp [h_GeneralBlockReindex_right_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · have hh : (hL (i,l)).1≠(hL (i',l')).1 ∨ (hL (i,l)).2≠(hL (i',l')).2 := by + by_contra h; push Not at h; exact he (hL.injective (Prod.ext h.1 h.2)) + have hil : i≠i' ∨ l≠l' := by simpa only [Prod.mk.injEq,not_and_or] using he + rcases hh with h|h <;> rcases hil with hil|hil <;> + simp [h_GeneralBlockReindex_right_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply,h,hil] + · simp [h_GeneralBlockReindex_right_low, h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_lr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · simp [h_GeneralBlockReindex_right_low, h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rl, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · by_cases hr : r=r' + · subst r'; simp [h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply] + · have hrr : (hR r).1≠(hR r').1 ∨ (hR r).2≠(hR r').2 := by + by_contra h; push Not at h; exact hr (hR.injective (Prod.ext h.1 h.2)) + rcases hrr with h|h <;> simp [h_GeneralBlockReindex_right_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_right_apply, h_MatrixDiagonalPath_block_apply,hr,h] + have h_GeneralBlockReindex_right_matrix {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : P × L ≃ T × U) (hR : R ≃ T × S) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat Q) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) : + CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR) + (OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.rightMatrix (ι:=P) a) (fun _ : R => m))) = + MatrixTensor.rightMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) := by + ext x y + exact h_GeneralBlockReindex_right_entry hL hR a m ((OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR).symm x) + ((OAI.KirchbergRordam.GeneralBlockReindex.repackRight hL hR).symm y) |>.trans (by simp [h_MatrixBlockReindex_right_apply] ) + have h_BalancedDropSystem_lower_one : OAI.KirchbergRordam.BalancedDropSystem.lowerPath 1 = OAI.KirchbergRordam.BalancedDropSystem.half := by + apply Subtype.ext + change (1 : ℝ) / 2 = (1 : ℝ) / 2 + rfl + have h_BalancedDropSystem_upper_one : OAI.KirchbergRordam.BalancedDropSystem.upperPath 1 = 1 := by + apply Subtype.ext + change ((1 : ℝ) + 1) / 2 = 1 + norm_num + have h_GeneralDropSystem_rawStep_apply (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f) (t : unitInterval) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f t=OAI.KirchbergRordam.MatrixDiagonalPath.interpolate (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) t (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) t f) := rfl + have h_MatrixBlockReindex_reindex_block {P : Type 0} {Q : Type 0} {R : Type 0} [inst3 : Fintype P] [inst4 : Fintype Q] [inst5 : Fintype R] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst8 : DecidableEq R] (e : P ≃ Q) (a : P → OAI.KirchbergRordam.MatrixDiagonalPath.Mat R) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr (Equiv.refl R) e) (OAI.KirchbergRordam.MatrixDiagonalPath.block a) = + OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => a (e.symm i)) := by + ext i j + rcases i with ⟨r,p⟩; rcases j with ⟨s,q⟩ + change (if e.symm p=e.symm q then a (e.symm p) r s else 0) = + (if p=q then a (e.symm p) r s else 0) + simp only [e.symm.injective.eq_iff] + have h_GeneralDropSystem_one_eval (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin q)) (hb : MatrixTensor.rightMatrix b=f 1) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr (Equiv.refl (Fin p × Fin q)) (OAI.KirchbergRordam.GeneralDropSystem.slotSwap d)) + (OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) 1 f)= + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : OAI.KirchbergRordam.GeneralDropSystem.High d => MatrixTensor.rightMatrix (ι:=Fin p) b) + (fun _ : OAI.KirchbergRordam.GeneralDropSystem.Low d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d => f OAI.KirchbergRordam.BalancedDropSystem.half)) := by + change CStarMatrix.reindexₐ ℂ ℂ _ (OAI.KirchbergRordam.MatrixDiagonalPath.block _) = _ + rw [h_MatrixBlockReindex_reindex_block] + apply congrArg OAI.KirchbergRordam.MatrixDiagonalPath.block + funext k + rcases k with k|k|k <;> simp [h_BalancedDropSystem_lower_one, h_BalancedDropSystem_upper_one, OAI.KirchbergRordam.GeneralDropSystem.slotSwap,OAI.KirchbergRordam.GeneralDropSystem.eigenpath,hb] + have h_MatrixBlockReindex_reindex_right {P : Type 0} {Q : Type 0} {R : Type 0} {S : Type 0} [inst4 : Fintype P] [inst5 : Fintype Q] [inst6 : Fintype R] [inst7 : Fintype S] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst10 : DecidableEq R] [inst11 : DecidableEq S] (e : P ≃ Q) (f : R ≃ S) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat R) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr e f) (OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι:=P) a) = + OAI.KirchbergRordam.MatrixTensor.rightMatrix (ι:=Q) (CStarMatrix.reindexₐ ℂ ℂ f a) := by + ext i j + rcases i with ⟨p,r⟩; rcases j with ⟨q,s⟩ + change OAI.KirchbergRordam.MatrixTensor.rightMatrix a (e.symm p,f.symm r) (e.symm q,f.symm s) = _ + simp only [h_MatrixBlockReindex_right_apply, e.symm.injective.eq_iff] + rfl + have h_MatrixBlockReindex_reindex_trans + {P : Type 0} + {Q : Type 0} + [Fintype P] + [Fintype Q] + [DecidableEq P] + [DecidableEq Q] + {T : Type 0} [Fintype T] [DecidableEq T] + (e : P ≃ Q) (f : Q ≃ T) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) : + CStarMatrix.reindexₐ ℂ ℂ (e.trans f) a = + CStarMatrix.reindexₐ ℂ ℂ f (CStarMatrix.reindexₐ ℂ ℂ e a) := rfl + have h_MatrixPermutationPath_perm_conjugation {ι : Type 0} [inst1 : Fintype ι] [inst2 : DecidableEq ι] (σ : Equiv.Perm ι) (a : OAI.KirchbergRordam.MatrixPermutationPath.Mat ι) : + Unitary.conjStarAlgAut ℂ _ (OAI.KirchbergRordam.MatrixPermutationPath.perm σ) a = CStarMatrix.reindexₐ ℂ ℂ σ a := by + change σ⁻¹.permMatrix ℂ * CStarMatrix.ofMatrix.symm a * (σ⁻¹.permMatrix ℂ)ᴴ = + Matrix.reindex σ σ (CStarMatrix.ofMatrix.symm a) + rw [Matrix.conjTranspose_permMatrix] + change σ.symm.toPEquiv.toMatrix * CStarMatrix.ofMatrix.symm a * σ.toPEquiv.toMatrix = _ + rw [PEquiv.toMatrix_toPEquiv_mul, PEquiv.mul_toMatrix_toPEquiv] + rfl + have h_MatrixDiagonalPath_interpolate_one + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) : + OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ 1 a = CStarMatrix.reindexₐ ℂ ℂ e₁ a := by + simp only [OAI.KirchbergRordam.MatrixDiagonalPath.interpolate, StarAlgEquiv.trans_apply, Path.target, + (@h_MatrixPermutationPath_perm_conjugation)] + ext i j + change a (e₀.symm ((e₀.symm.trans e₁).symm i)) + (e₀.symm ((e₀.symm.trans e₁).symm j)) = a (e₁.symm i) (e₁.symm j) + simp + have h_GeneralDropSystem_rawStep_one (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (b : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin q)) (hb : MatrixTensor.rightMatrix b=f 1) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f 1=MatrixTensor.rightMatrix (ι:=Fin P) + (CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralDropSystem.oneOuter d) + (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.oneEnd => b),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.oneMid => f OAI.KirchbergRordam.BalancedDropSystem.half)))) := by + rw [h_GeneralDropSystem_rawStep_apply,h_MatrixDiagonalPath_interpolate_one] + unfold OAI.KirchbergRordam.GeneralDropSystem.oneReindex + rw [h_MatrixBlockReindex_reindex_trans,h_GeneralDropSystem_one_eval d f b hb,h_MatrixBlockReindex_reindex_trans,(@h_GeneralBlockReindex_right_matrix),h_MatrixBlockReindex_reindex_right] + have h_GeneralBlockReindex_left_low + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (l : L) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inl l) = (.inl (i,(hL (j,l)).1),(hL (j,l)).2) := rfl + have h_GeneralBlockReindex_left_full + {P : Type 0} + {Q : Type 0} + {L : Type 0} + {R : Type 0} + {S : Type 0} + {T : Type 0} + {U : Type 0} + [Fintype P] + [Fintype Q] + [Fintype L] + [Fintype R] + [Fintype S] + [Fintype T] + [Fintype U] + [DecidableEq P] + [DecidableEq Q] + [DecidableEq L] + [DecidableEq R] + [DecidableEq S] + [DecidableEq T] + [DecidableEq U] + (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (i : P) (j : Q) (r : R) : + OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR ((i,j),.inr r) = (.inr ((i,j),(hR r).1),(hR r).2) := rfl + have h_MatrixBlockReindex_left_apply {P : Type 0} {Q : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (i j : P) (k l : Q) : + OAI.KirchbergRordam.MatrixTensor.leftMatrix a (i,k) (j,l) = a i j * if k=l then 1 else 0 := by + change (Matrix.kronecker (CStarMatrix.ofMatrix.symm a) (1 : Matrix Q Q ℂ)) (i,k) (j,l)=_ + simp [Matrix.one_apply] + have h_GeneralBlockReindex_left_entry {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) (x y : (P×Q)×(L⊕R)) : + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.leftMatrix (κ:=Q) a) (fun _ : R => m)) x y = + MatrixTensor.leftMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) + (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR x) (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR y) := by + rcases x with ⟨⟨i,j⟩,l|r⟩ <;> rcases y with ⟨⟨i',j'⟩,l'|r'⟩ + · by_cases he : (j,l)=(j',l') + · cases he; simp [h_GeneralBlockReindex_left_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · have hh : (hL (j,l)).1≠(hL (j',l')).1 ∨ (hL (j,l)).2≠(hL (j',l')).2 := by + by_contra h; push Not at h; exact he (hL.injective (Prod.ext h.1 h.2)) + have hjl : j≠j' ∨ l≠l' := by simpa only [Prod.mk.injEq,not_and_or] using he + rcases hh with h|h <;> rcases hjl with hjl|hjl <;> + simp [h_GeneralBlockReindex_left_low, h_MatrixBlockReindex_sumBlock_ll, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply,h,hjl] + · simp [h_GeneralBlockReindex_left_low, h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_lr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · simp [h_GeneralBlockReindex_left_low, h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rl, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · by_cases hr : r=r' + · subst r'; simp [h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply] + · have hrr : (hR r).1≠(hR r').1 ∨ (hR r).2≠(hR r').2 := by + by_contra h; push Not at h; exact hr (hR.injective (Prod.ext h.1 h.2)) + rcases hrr with h|h <;> simp [h_GeneralBlockReindex_left_full, h_MatrixBlockReindex_sumBlock_rr, h_MatrixBlockReindex_left_apply, h_MatrixDiagonalPath_block_apply,hr,h] + have h_GeneralBlockReindex_left_matrix {P : Type 0} {Q : Type 0} {L : Type 0} {R : Type 0} {S : Type 0} {T : Type 0} {U : Type 0} [instFintypeP : Fintype P] [instFintypeQ : Fintype Q] [instFintypeL : Fintype L] [instFintypeR : Fintype R] [instFintypeS : Fintype S] [instFintypeT : Fintype T] [instFintypeU : Fintype U] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [instDecidableEqL : DecidableEq L] [instDecidableEqR : DecidableEq R] [instDecidableEqS : DecidableEq S] [instDecidableEqT : DecidableEq T] [instDecidableEqU : DecidableEq U] (hL : Q × L ≃ U × T) (hR : R ≃ S × T) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) (m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (P×Q)) : + CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR) + (OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : L => MatrixTensor.leftMatrix (κ:=Q) a) (fun _ : R => m))) = + MatrixTensor.leftMatrix (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : U => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : S => m))) := by + ext x y + exact h_GeneralBlockReindex_left_entry hL hR a m ((OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR).symm x) + ((OAI.KirchbergRordam.GeneralBlockReindex.repackLeft hL hR).symm y) |>.trans (by simp [h_MatrixBlockReindex_left_apply] ) + have h_BalancedDropSystem_lower_zero : OAI.KirchbergRordam.BalancedDropSystem.lowerPath 0 = 0 := by + apply Subtype.ext + change (0 : ℝ) / 2 = 0 + norm_num + have h_BalancedDropSystem_upper_zero : OAI.KirchbergRordam.BalancedDropSystem.upperPath 0 = OAI.KirchbergRordam.BalancedDropSystem.half := by + apply Subtype.ext + change ((0 : ℝ) + 1) / 2 = (1 : ℝ) / 2 + rw [zero_add] + have h_GeneralDropSystem_zero_eval (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin p)) (ha : MatrixTensor.leftMatrix a=f 0) : + OAI.KirchbergRordam.MatrixDiagonalPath.evaluationBlock (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) 0 f = + OAI.KirchbergRordam.MatrixDiagonalPath.block (Sum.elim (fun _ : OAI.KirchbergRordam.GeneralDropSystem.Low d => MatrixTensor.leftMatrix (κ:=Fin q) a) + (fun _ : OAI.KirchbergRordam.GeneralDropSystem.High d ⊕ OAI.KirchbergRordam.GeneralDropSystem.Mid d => f OAI.KirchbergRordam.BalancedDropSystem.half)) := by + apply congrArg OAI.KirchbergRordam.MatrixDiagonalPath.block + funext k + rcases k with k|k|k <;> simp [h_BalancedDropSystem_lower_zero, h_BalancedDropSystem_upper_zero, OAI.KirchbergRordam.GeneralDropSystem.eigenpath,ha] + have h_MatrixBlockReindex_reindex_left {P : Type 0} {Q : Type 0} {R : Type 0} {S : Type 0} [inst4 : Fintype P] [inst5 : Fintype Q] [inst6 : Fintype R] [inst7 : Fintype S] [instDecidableEqP : DecidableEq P] [instDecidableEqQ : DecidableEq Q] [inst10 : DecidableEq R] [inst11 : DecidableEq S] (e : P ≃ Q) (f : R ≃ S) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat P) : + CStarMatrix.reindexₐ ℂ ℂ (Equiv.prodCongr e f) (OAI.KirchbergRordam.MatrixTensor.leftMatrix (κ:=R) a) = + OAI.KirchbergRordam.MatrixTensor.leftMatrix (κ:=S) (CStarMatrix.reindexₐ ℂ ℂ e a) := by + ext i j + rcases i with ⟨p,r⟩; rcases j with ⟨q,s⟩ + change OAI.KirchbergRordam.MatrixTensor.leftMatrix a (e.symm p,f.symm r) (e.symm q,f.symm s) = _ + simp only [h_MatrixBlockReindex_left_apply, f.symm.injective.eq_iff] + rfl + have h_MatrixPermutationPath_perm_one {ι : Type 0} [inst1 : Fintype ι] [inst2 : DecidableEq ι] : OAI.KirchbergRordam.MatrixPermutationPath.perm (1 : Equiv.Perm ι) = 1 := by + apply Subtype.ext + change (1⁻¹ : Equiv.Perm ι).permMatrix ℂ = 1 + simp + have h_MatrixDiagonalPath_interpolate_zero + {κ : Type 0} + {ν : Type 0} + [Fintype κ] + [DecidableEq κ] + [Fintype ν] + [DecidableEq ν] + (e₀ e₁ : κ ≃ ν) (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) : + OAI.KirchbergRordam.MatrixDiagonalPath.interpolate e₀ e₁ 0 a = CStarMatrix.reindexₐ ℂ ℂ e₀ a := by + simp only [OAI.KirchbergRordam.MatrixDiagonalPath.interpolate, StarAlgEquiv.trans_apply, Path.source, + (@h_MatrixPermutationPath_perm_one)] + simp + have h_GeneralDropSystem_rawStep_zero (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : C(unitInterval,PrimeDimensionDrop.Fiber p q)) + (a : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (Fin p)) (ha : MatrixTensor.leftMatrix a=f 0) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d f 0=MatrixTensor.leftMatrix (κ:=Fin Q) + (CStarMatrix.reindexₐ ℂ ℂ (OAI.KirchbergRordam.GeneralDropSystem.zeroOuter d) + (OAI.KirchbergRordam.MatrixBlockReindex.sumBlock (OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.zeroEnd => a),OAI.KirchbergRordam.MatrixDiagonalPath.block (fun _ : Fin d.zeroMid => f OAI.KirchbergRordam.BalancedDropSystem.half)))) := by + rw [h_GeneralDropSystem_rawStep_apply,h_MatrixDiagonalPath_interpolate_zero,h_GeneralDropSystem_zero_eval d f a ha] + unfold OAI.KirchbergRordam.GeneralDropSystem.zeroReindex + rw [h_MatrixBlockReindex_reindex_trans,(@h_GeneralBlockReindex_left_matrix),h_MatrixBlockReindex_reindex_left] + have h_GeneralDropSystem_rawStep_mem (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (path : C(unitInterval, PrimeDimensionDrop.Fiber p q)) + (path_mem : path ∈ PrimeDimensionDrop.subalgebra p q) : + OAI.KirchbergRordam.GeneralDropSystem.rawStep d path ∈ PrimeDimensionDrop.subalgebra P Q := by + obtain ⟨⟨leftValue, left_eq⟩, ⟨rightValue, right_eq⟩⟩ := path_mem + exact ⟨⟨_, (h_GeneralDropSystem_rawStep_zero d path leftValue left_eq).symm⟩, + ⟨_, (h_GeneralDropSystem_rawStep_one d path rightValue right_eq).symm⟩⟩ + exact + @OAI.KirchbergRordam.GeneralDropSystem.restrictToSubalgebras C(unitInterval, PrimeDimensionDrop.Fiber p q) + C(unitInterval, PrimeDimensionDrop.Fiber P Q) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber p q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin p × Fin q) (instFintypeProd (Fin p) (Fin q)) inferInstance)) + (@ContinuousMap.instCStarAlgebra unitInterval (PrimeDimensionDrop.Fiber P Q) + inferInstance inferInstance + (@CStarMatrix.instCStarAlgebra ℂ inferInstance Complex.partialOrder inferInstance + (Fin P × Fin Q) (instFintypeProd (Fin P) (Fin Q)) inferInstance)) + (OAI.KirchbergRordam.GeneralDropSystem.rawStep d) (PrimeDimensionDrop.subalgebra p q) (PrimeDimensionDrop.subalgebra P Q) + (h_GeneralDropSystem_rawStep_mem d) + +end KirchbergRordam.GeneralDropSystem + +namespace KirchbergRordam + +structure PrimeDropPresentation where + size : ℕ → ℕ + exponent : ℕ → ℕ + size_power : ∀ n, size n=2^(exponent n+1) + stepData : ∀ n, GeneralDropSystem.Data (size n) (size n+1) (size (n+1)) (size (n+1)+1) + zero_copies : ∀ n, 2≤(stepData n).zeroEnd+(size n+1)*(stepData n).zeroMid + one_copies : ∀ n, 2≤(stepData n).oneEnd+size n*(stepData n).oneMid + +namespace PrimeDropPresentation +variable (S : PrimeDropPresentation) + +def Stage (n : ℕ) : Type := PrimeDimensionDrop.Algebra (S.size n) (S.size n+1) + +instance (n : ℕ) : CStarAlgebra (S.Stage n) := inferInstanceAs + (CStarAlgebra (PrimeDimensionDrop.Algebra (S.size n) (S.size n+1))) + +def chain (S : OAI.KirchbergRordam.PrimeDropPresentation) : CStarInductiveLimit.Chain.{0} := by + classical + have h_GeneralDropSystem_eigen_cover {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (s : unitInterval) : ∃ i t, OAI.KirchbergRordam.GeneralDropSystem.eigenpath d i t=s := by + by_cases hs : (s:ℝ)≤1/2 + · refine ⟨.inl ⟨0,d.lower_pos⟩,⟨2*s,by constructor <;> linarith [s.property.1]⟩,?_⟩ + apply Subtype.ext + change 2*(s:ℝ)/2=(s:ℝ) + ring + · refine ⟨.inr (.inl ⟨0,d.upper_pos⟩),⟨2*s-1,by constructor <;> linarith [s.property.2]⟩,?_⟩ + apply Subtype.ext + change ((2*(s:ℝ)-1)+1)/2=(s:ℝ) + ring + have h_MatrixDiagonalPath_block_apply {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (a : ι → OAI.KirchbergRordam.MatrixDiagonalPath.Mat κ) (i j : κ) (k l : ι) : + OAI.KirchbergRordam.MatrixDiagonalPath.block a (i,k) (j,l) = if k=l then a k i j else 0 := rfl + have h_MatrixDiagonalPath_block_injective {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] : Function.Injective (OAI.KirchbergRordam.MatrixDiagonalPath.block (ι:=ι) (κ:=κ)) := by + intro a b h + funext k + ext i j + have := congrArg (fun m : OAI.KirchbergRordam.MatrixDiagonalPath.Mat (κ×ι) => m (i,k) (j,k)) h + simpa [h_MatrixDiagonalPath_block_apply, h_MatrixDiagonalPath_block_apply] using this + have h_MatrixDiagonalPath_diagonal_injective {ι : Type 0} {κ : Type 0} [inst2 : Fintype ι] [inst3 : DecidableEq ι] [inst4 : Fintype κ] [instDecidableEqκ : DecidableEq κ] (ξ : ι → C(unitInterval, unitInterval)) + (hcover : ∀ s : unitInterval, ∃ i t, ξ i t = s) : + Function.Injective (OAI.KirchbergRordam.MatrixDiagonalPath.diagonal (κ:=κ) ξ) := by + intro f g h + ext s a b + obtain ⟨i,t,rfl⟩ := hcover s + have ht : OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => f (ξ i t)) = OAI.KirchbergRordam.MatrixDiagonalPath.block (fun i => g (ξ i t)) := + DFunLike.congr_fun h t + exact congrFun (congrFun (congrFun (h_MatrixDiagonalPath_block_injective ht) i) a) b + have h_GeneralDropSystem_rawStep_injective {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) : Function.Injective (OAI.KirchbergRordam.GeneralDropSystem.rawStep d) := by + intro f g h + apply h_MatrixDiagonalPath_diagonal_injective (OAI.KirchbergRordam.GeneralDropSystem.eigenpath d) (h_GeneralDropSystem_eigen_cover d) + apply ContinuousMap.ext + intro t + exact (OAI.KirchbergRordam.MatrixDiagonalPath.interpolate (OAI.KirchbergRordam.GeneralDropSystem.zeroReindex d) (OAI.KirchbergRordam.GeneralDropSystem.oneReindex d) t).injective (DFunLike.congr_fun h t) + have h_GeneralDropSystem_step_injective {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) : Function.Injective (OAI.KirchbergRordam.GeneralDropSystem.step d) := by + intro f g h + apply Subtype.ext + exact h_GeneralDropSystem_rawStep_injective d (congrArg Subtype.val h) + have h_GeneralDropSystem_step_norm {p : ℕ} {q : ℕ} {P : ℕ} {Q : ℕ} (d : OAI.KirchbergRordam.GeneralDropSystem.Data p q P Q) (f : PrimeDimensionDrop.Algebra p q) : ‖OAI.KirchbergRordam.GeneralDropSystem.step d f‖=‖f‖ := + NonUnitalStarAlgHom.norm_map _ (h_GeneralDropSystem_step_injective d) f + have h_PrimeDropPresentation_stage_step_norm (S : OAI.KirchbergRordam.PrimeDropPresentation) : + ∀ stage (element : S.Stage stage), + ‖GeneralDropSystem.step (S.stepData stage) element‖ = ‖element‖ := + fun stage element => (@h_GeneralDropSystem_step_norm) (S.stepData stage) element + exact + @CStarInductiveLimit.Chain.mk.{0} + (@OAI.KirchbergRordam.PrimeDropPresentation.Stage S) + (@OAI.KirchbergRordam.PrimeDropPresentation.instCStarAlgebraStage S) + (fun stage : Nat => @GeneralDropSystem.step + (@PrimeDropPresentation.size S stage) (Nat.succ (@PrimeDropPresentation.size S stage)) + (@PrimeDropPresentation.size S (Nat.succ stage)) + (Nat.succ (@PrimeDropPresentation.size S (Nat.succ stage))) + (@PrimeDropPresentation.stepData S stage)) + (@h_PrimeDropPresentation_stage_step_norm S) + +abbrev system := S.chain.system + +end PrimeDropPresentation +end KirchbergRordam + +namespace KirchbergRordam.StandardPrimeMultiplicity + +def copies (p : ℕ) : ℕ := (p-1)*(p^4+p^2+1) + +def lower (p : ℕ) : ℕ := p*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p+1 + +def upper (p : ℕ) : ℕ := (p+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p+1 + +def middle (p : ℕ) : ℕ := p*(p+1)*(OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p)^2-1 + +def next (p : ℕ) : ℕ := p^7 + +def data (p : ℕ) (hp : 2≤p) : GeneralDropSystem.Data p (p+1) (OAI.KirchbergRordam.StandardPrimeMultiplicity.next p) (OAI.KirchbergRordam.StandardPrimeMultiplicity.next p+1) := by + classical + have h_StandardPrimeMultiplicity_dimension (p : ℕ) (hp : 2≤p) : p+p*(p+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies p=OAI.KirchbergRordam.StandardPrimeMultiplicity.next p := by + cases p with + | zero => omega + | succ p => simp only [OAI.KirchbergRordam.StandardPrimeMultiplicity.copies,OAI.KirchbergRordam.StandardPrimeMultiplicity.next,Nat.add_sub_cancel]; ring + have h_StandardPrimeMultiplicity_lower_pos (p : ℕ) : 0 2 + | n+1 => OAI.KirchbergRordam.StandardPrimeMultiplicity.next (size n) + +end KirchbergRordam.StandardPrimeMultiplicity + +namespace KirchbergRordam.StandardPrimeModel +open StandardPrimeMultiplicity +def presentation : OAI.KirchbergRordam.PrimeDropPresentation := by + classical + have h_StandardPrimeMultiplicity_copies_pos (p : ℕ) (hp : 2≤p) : 0 simp [h_StandardPrimeMultiplicity_size_zero] + | succ n ih => rw [h_StandardPrimeMultiplicity_size_succ,OAI.KirchbergRordam.StandardPrimeMultiplicity.next,ih,←pow_mul,pow_succ] + have h_StandardPrimeMultiplicity_next_two (p : ℕ) (hp : 2≤p) : 2≤OAI.KirchbergRordam.StandardPrimeMultiplicity.next p := by + exact hp.trans (Nat.le_self_pow (by decide) p) + have h_StandardPrimeMultiplicity_size_two (n : ℕ) : 2 ≤ OAI.KirchbergRordam.StandardPrimeMultiplicity.size n := by + induction n with + | zero => simp [h_StandardPrimeMultiplicity_size_zero] + | succ n ih => exact h_StandardPrimeMultiplicity_next_two _ ih + exact { + size := OAI.KirchbergRordam.StandardPrimeMultiplicity.size + exponent n := 7^n-1 + size_power n := by + rw [Nat.sub_add_cancel (Nat.one_le_pow n 7 (by decide))] + exact h_StandardPrimeMultiplicity_size_power n + stepData n := OAI.KirchbergRordam.StandardPrimeMultiplicity.data (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + zero_copies n := by + change 2≤1+(OAI.KirchbergRordam.StandardPrimeMultiplicity.size n+1)*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) + have h := h_StandardPrimeMultiplicity_copies_pos (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + nlinarith [h_StandardPrimeMultiplicity_size_two n] + one_copies n := by + change 2≤1+OAI.KirchbergRordam.StandardPrimeMultiplicity.size n*OAI.KirchbergRordam.StandardPrimeMultiplicity.copies (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) + have h := h_StandardPrimeMultiplicity_copies_pos (OAI.KirchbergRordam.StandardPrimeMultiplicity.size n) (h_StandardPrimeMultiplicity_size_two n) + nlinarith [h_StandardPrimeMultiplicity_size_two n] + } + +end KirchbergRordam.StandardPrimeModel + +namespace KirchbergRordam.JiangSu + +def Algebra : Type := CStarInductiveLimit.Algebra StandardPrimeModel.presentation.system + +instance : CStarAlgebra OAI.KirchbergRordam.JiangSu.Algebra := inferInstanceAs + (CStarAlgebra (CStarInductiveLimit.Algebra StandardPrimeModel.presentation.system)) + +end KirchbergRordam.JiangSu + +namespace KirchbergRordam + +def HasNoCharacters (A : Type*) [CStarAlgebra A] : Prop := + ∀ χ : A →⋆ₙₐ[ℂ] ℂ, χ=0 + +theorem character_criterion + (A : Type) [CStarAlgebra A] [Nontrivial A] [TopologicalSpace.SeparableSpace A] + (ω : Ultrafilter ℕ) (hω : (ω : Filter ℕ)≤Filter.cofinite) : + OAI.KirchbergRordam.HasNoCharacters (NormUltrapower.CentralAlgebra A ω) ↔ + Nonempty (A ≃⋆ₐ[ℂ] MinTensor.Algebra A JiangSu.Algebra) := by sorry + +end KirchbergRordam + +end + +end OAI diff --git a/tasks/character-criterion/tests/grade.py b/tasks/character-criterion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/character-criterion/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/character-criterion/tests/task.json b/tasks/character-criterion/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8291f71f63bb1893be8f1dcabec69b7047c9244a --- /dev/null +++ b/tasks/character-criterion/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CharacterCriterion", + "comparator": { + "theorem_names": [ + "OAI.KirchbergRordam.character_criterion" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11832 +} \ No newline at end of file diff --git a/tasks/character-criterion/tests/test.sh b/tasks/character-criterion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/character-criterion/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/choiceless-polynomial-time/environment/Dockerfile b/tasks/choiceless-polynomial-time/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/choiceless-polynomial-time/environment/fetch_mathlib.sh b/tasks/choiceless-polynomial-time/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/choiceless-polynomial-time/environment/lake-manifest.json b/tasks/choiceless-polynomial-time/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/choiceless-polynomial-time/environment/lakefile.lean b/tasks/choiceless-polynomial-time/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/choiceless-polynomial-time/environment/lean_setup.sh b/tasks/choiceless-polynomial-time/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/choiceless-polynomial-time/environment/pack_submission.py b/tasks/choiceless-polynomial-time/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/choiceless-polynomial-time/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/choiceless-polynomial-time/instruction.md b/tasks/choiceless-polynomial-time/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8c56d7c57a954de7ee6b46343ffdd0765a80c555 --- /dev/null +++ b/tasks/choiceless-polynomial-time/instruction.md @@ -0,0 +1,611 @@ +# openai/math challenge `ChoicelessPolynomialTime` (family 243) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 243 of the release, *Choiceless counting does not capture polynomial time* +(Mathematical logic). The family as a whole: Confirms the Blass–Gurevich–Shelah noncapture conjecture: consistency of a linear system over $\mathbb F_3$ defines a polynomial-time query on unordered finite structures that choiceless polynomial time with counting cannot express. A separate result shows that adding witnessed symmetric choice strictly increases expressive power. Both separations hold for the full counting formalism, allowing hereditarily finite sets of arbitrary finite rank. + +The challenge is `ChoicelessPolynomialTime`, also at `/opt/openai-math/challenges/ChoicelessPolynomialTime.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe uA uB uC uF uR + +namespace CPTSeparation + +abbrev Scalar := ZMod 3 + +inductive Symbol + | Ed | Cf | EB | VB | I | Z (δ : Scalar) + deriving DecidableEq, Fintype + +structure Input (A : Type) where + rel : Symbol → A → A → Bool + +namespace Input + +variable {A B : Type} [Fintype A] [Fintype B] + +abbrev Edge (S : Input A) := {y : A // S.rel .Ed y y = true} + +abbrev Config (S : Input A) := {a : A // S.rel .Cf a a = true} + +instance (S : Input A) : Fintype S.Edge := inferInstanceAs (Fintype (Subtype _)) + +instance (S : Input A) : Fintype S.Config := inferInstanceAs (Fintype (Subtype _)) + +def coefficient (S : Input A) (y : S.Edge) (a : S.Config) : Scalar := + ∑ x : S.Edge, if S.rel .I a x then + ∑ δ : Scalar, if S.rel (.Z δ) y x then δ else 0 + else 0 + +def incident (S : Input A) (t : S.Config) (y : S.Edge) : Prop := + ∃ a : S.Config, S.rel .VB t a = true ∧ + ∃ x : S.Edge, S.rel .I a x = true ∧ S.rel .EB y x = true + +def normalized (S : Input A) (lambda : S.Config → Scalar) : Prop := + ∀ t : S.Config, (∑ a : S.Config, if S.rel .VB t a then lambda a else 0) = 1 + +def consistent (S : Input A) (lambda : S.Config → Scalar) (mu : S.Edge → Scalar) : Prop := + ∀ (t : S.Config) (y : S.Edge), S.incident t y → + mu y = ∑ a : S.Config, if S.rel .VB t a then lambda a * S.coefficient y a else 0 + +def query (S : Input A) : Prop := + ∃ (lambda : S.Config → Scalar) (mu : S.Edge → Scalar), S.normalized lambda ∧ S.consistent lambda mu + +structure Iso (S : Input A) (T : Input B) extends A ≃ B where + rel_eq : ∀ r x y, T.rel r (toEquiv x) (toEquiv y) = S.rel r x y + +end Input + +namespace Hereditary + +section + +abbrev HF (A : Type uA) := Quotient (@Lists.instSetoidLists A) + +variable {A : Type uA} {B : Type uB} + +local instance instDecidableEqHF {A : Type uA} : DecidableEq (HF A) := Classical.decEq _ + +def mk (l : Lists A) : HF A := Quotient.mk Lists.instSetoidLists l + +def atom (a : A) : HF A := mk (Lists.atom a) + +def isSet (x : HF A) : Bool := Quotient.liftOn x (fun l => l.1) + (by intro l r h; cases h <;> rfl) + +def rawElements (l : Lists A) : Finset (HF A) := by + classical + exact l.toList.toFinset.image mk + +def elements (x : HF A) : Finset (HF A) := Quotient.liftOn x rawElements (by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have raw_mem_congr_right {l r : Lists A} (h : Lists.Equiv l r) (a : Lists A) : + a ∈ l ↔ a ∈ r := by + cases h with + | refl => rfl + | antisymm hl hr => + exact ⟨Lists'.mem_of_subset hl, Lists'.mem_of_subset hr⟩ + intro l r h + ext z + induction z using Quotient.inductionOn with + | _ a => + change mk a ∈ rawElements l ↔ mk a ∈ rawElements r + rw [mem_rawElements, mem_rawElements] + exact raw_mem_congr_right h a) + +instance : Membership (HF A) (HF A) := ⟨fun y x => x ∈ elements y⟩ + +def ofFinset (s : Finset (HF A)) : HF A := + mk (Lists.ofList (s.toList.map Quotient.out)) + +def rawRank' : {b : Bool} → Lists' A b → ℕ + | _, .atom _ => 0 + | _, .nil => 0 + | _, .cons' a l => max (rawRank' a + 1) (rawRank' l) + +def rawRank (l : Lists A) : ℕ := rawRank' l.2 + +def rank (x : HF A) : ℕ := Quotient.liftOn x rawRank (by + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm hl hr ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r heq hmem hsub iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + exact fun _ _ h => rawRank_congr h) + +end + +open Classical Finset + +variable {A : Type uA} {B : Type uB} + +def double (a b : HF A) : HF A := ofFinset {a,b} + +def ordinal : ℕ → HF A + | 0 => ofFinset ∅ + | i+1 => ofFinset (insert (ordinal i) (elements (ordinal i))) + +end Hereditary + +namespace Operational + +open Classical Hereditary Finset + +variable {A : Type uA} {B : Type uB} {R : Type uR} {F : Type uF} {arity : F → ℕ} + +local instance instDecidableEqHF {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +abbrev empty : HF A := ordinal 0 + +abbrev truth : HF A := ordinal 1 + +def boolean (p : Prop) : HF A := if p then truth else empty + +def inputRelation (rel : R → A → A → Bool) (r : R) (x y : HF A) : Prop := + ∃ a b, x = atom a ∧ y = atom b ∧ rel r a b = true + +def allAtoms [Fintype A] : HF A := ofFinset (univ.image atom) + +def unionHF (x : HF A) : HF A := ofFinset ((elements x).biUnion elements) + +def uniqueHF (x : HF A) : HF A := + if h : ∃ a, elements x = {a} then h.choose else empty + +def cardinalityHF (x : HF A) : HF A := ordinal (elements x).card + +abbrev Location (F : Type uF) (arity : F → ℕ) (A : Type uA) := Σ f : F, Fin (arity f) → HF A + +structure State (F : Type uF) (arity : F → ℕ) (A : Type uA) where + value : Location F arity A → HF A + finite : Set.Finite {l | value l ≠ empty} + +namespace State + +def initial : State F arity A := ⟨fun _ => empty, by simp⟩ + +def support (s : State F arity A) : Finset (Location F arity A) := s.finite.toFinset + +end State + +abbrev Update (F : Type uF) (arity : F → ℕ) (A : Type uA) := Location F arity A × HF A + +def State.Consistent (u : Finset (Update F arity A)) : Prop := + ∀ l x y, (l,x) ∈ u → (l,y) ∈ u → x = y + +def State.updatedValue (s : State F arity A) (u : Finset (Update F arity A)) + (l : Location F arity A) : HF A := + if h : ∃ x, (l,x) ∈ u then h.choose else s.value l + +def State.applyUpdates (s : State F arity A) (u : Finset (Update F arity A)) : State F arity A where + value := s.updatedValue u + finite := by + apply (s.finite.union (u.image Prod.fst).finite_toSet).subset + intro l hl + by_cases h : ∃ x, (l,x) ∈ u + · obtain ⟨x,hx⟩ := h + exact Or.inr (mem_image.mpr ⟨(l,x),hx,rfl⟩) + · exact Or.inl (by simpa only [Set.mem_ofPred_eq,updatedValue,dite_eq_right h] using hl) + +inductive Control | halt | accept deriving DecidableEq + +end Operational + +section + +open Classical Finset + +variable {A : Type uA} {B : Type uB} + +local instance Hereditary.instDecidableEqHF_1 {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +def Hereditary.closure (x : HF A) : Finset (HF A) := + insert x ((elements x).attach.biUnion (fun y => closure y.val)) +termination_by rank x +decreasing_by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _hl _hr ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _heq hmem _hsub iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + have rank_lt_of_mem {x y : HF A} (h : x ∈ y) : rank x < rank y := by + induction y using Quotient.inductionOn with + | _ l => + induction x using Quotient.inductionOn with + | _ a => + have h' := (mem_rawElements a l).mp h + rcases l with ⟨(_ | _), l⟩ + · exact False.elim h' + · obtain ⟨a',ha',heq⟩ := h' + change rawRank a < rawRank' l + rw [rawRank_congr heq] + exact rawRank_lt_of_mem l a' ha' + exact rank_lt_of_mem y.property + +def Hereditary.familyClosure (f : Finset (HF A)) : Finset (HF A) := f.biUnion closure + +end + +section + +open Classical Hereditary Finset + +variable {A : Type uA} {R : Type uR} {F : Type uF} {arity : F → ℕ} + +local instance Operational.instDecidableEqHF_1 {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +def Operational.State.critical (s : State F arity A) : Finset (HF A) := + s.support.biUnion (fun l => insert (s.value l) (univ.image l.2)) + +def Operational.State.active [Fintype A] (s : State F arity A) : Finset (HF A) := + familyClosure (s.critical ∪ {allAtoms,empty,truth} ∪ univ.image atom) + +end + +namespace FullCPT + +section + +open Classical Hereditary Finset + +open Operational (State Control Location Update) + +local instance instDecidableEqHF {C : Type} : DecidableEq (HF C) := Classical.decEq _ + +inductive Term (R F : Type) (arity : F → ℕ) : Type + | var (name : ℕ) + | ordinal (n : ℕ) + | atoms + | app (f : F) (args : Fin (arity f) → Term R F arity) + | pair (a b : Term R F arity) + | union (a : Term R F arity) + | unique (a : Term R F arity) + | card (a : Term R F arity) + | equal (a b : Term R F arity) + | member (a b : Term R F arity) + | isAtom (a : Term R F arity) + | input (r : R) (a b : Term R F arity) + | not (a : Term R F arity) + | and (a b : Term R F arity) + | or (a b : Term R F arity) + | conditional (c a b : Term R F arity) + | comprehend (name : ℕ) (bound guard body : Term R F arity) + +variable {A R F : Type} {arity : F → ℕ} + +namespace Term + +variable [Fintype A] + +def eval (rel : R → A → A → Bool) (s : State F arity A) : + Term R F arity → (ℕ → HF A) → HF A + | .var n, v => v n + | .ordinal n, _ => Hereditary.ordinal n + | .atoms, _ => Operational.allAtoms + | .app f args, v => s.value ⟨f, fun i => eval rel s (args i) v⟩ + | .pair a b, v => double (eval rel s a v) (eval rel s b v) + | .union a, v => Operational.unionHF (eval rel s a v) + | .unique a, v => Operational.uniqueHF (eval rel s a v) + | .card a, v => Operational.cardinalityHF (eval rel s a v) + | .equal a b, v => Operational.boolean (eval rel s a v = eval rel s b v) + | .member a b, v => Operational.boolean (eval rel s a v ∈ eval rel s b v) + | .isAtom a, v => Operational.boolean (isSet (eval rel s a v) = false) + | .input r a b, v => Operational.boolean (Operational.inputRelation rel r (eval rel s a v) (eval rel s b v)) + | .not a, v => Operational.boolean (eval rel s a v ≠ Operational.truth) + | .and a b, v => Operational.boolean (eval rel s a v = Operational.truth ∧ eval rel s b v = Operational.truth) + | .or a b, v => Operational.boolean (eval rel s a v = Operational.truth ∨ eval rel s b v = Operational.truth) + | .conditional c a b, v => if eval rel s c v = Operational.truth then eval rel s a v else eval rel s b v + | .comprehend n bound guard body, v => + ofFinset (((elements (eval rel s bound v)).filter + (fun x => eval rel s guard (Function.update v n x) = Operational.truth)).image + (fun x => eval rel s body (Function.update v n x))) + +end Term + +inductive Rule (R F : Type) (arity : F → ℕ) : Type + | skip + | update (f : F) (args : Fin (arity f) → Term R F arity) (value : Term R F arity) + | parallel (a b : Rule R F arity) + | conditional (condition : Term R F arity) (a b : Rule R F arity) + | forall (name : ℕ) (bound : Term R F arity) (body : Rule R F arity) + | letValue (name : ℕ) (value : Term R F arity) (body : Rule R F arity) + +namespace Rule + +def updates [Fintype A] (rel : R → A → A → Bool) (s : State F arity A) : + Rule R F arity → (ℕ → HF A) → Finset (Update F arity A) + | .skip, _ => ∅ + | .update f args value, v => {(⟨f, fun i => (args i).eval rel s v⟩, value.eval rel s v)} + | .parallel a b, v => updates rel s a v ∪ updates rel s b v + | .conditional c a b, v => if c.eval rel s v = Operational.truth then updates rel s a v else updates rel s b v + | .forall n bound body, v => (elements (bound.eval rel s v)).biUnion + (fun x => updates rel s body (Function.update v n x)) + | .letValue n value body, v => updates rel s body (Function.update v n (value.eval rel s v)) + +end Rule + +structure Program (R : Type) where + Functions : Type + finiteFunctions : Fintype Functions + arity : Functions → ℕ + body : Rule R (Control ⊕ Functions) (Sum.elim (fun _ => 0) arity) + +namespace Program + +variable (P : Program R) [Fintype A] + +abbrev functionArity : Control ⊕ P.Functions → ℕ := Sum.elim (fun _ => 0) P.arity + +abbrev Store := State (Control ⊕ P.Functions) P.functionArity A + +def flag (s : P.Store (A := A)) (c : Control) : Prop := s.value ⟨.inl c, Fin.elim0⟩ = Operational.truth + +def step (rel : R → A → A → Bool) (s : P.Store (A := A)) : Option (P.Store (A := A)) := + if P.flag s .halt then some s else + let u := P.body.updates rel s (fun _ => Operational.empty) + if State.Consistent u then some (s.applyUpdates u) else none + +def run (rel : R → A → A → Bool) : ℕ → Option (P.Store (A := A)) + | 0 => some State.initial + | j+1 => (run rel j).bind (P.step rel) + +def active (rel : R → A → A → Bool) (h : ℕ) : Finset (HF A) := + (Finset.range (h+1)).biUnion (fun j => ((P.run rel j).toFinset).biUnion State.active) + +end Program + +end + +open Classical Hereditary Finset + +open Operational (State Control) + +local instance instDecidableEqHF_1 {C : Type} : DecidableEq (HF C) := Classical.decEq _ + +variable {A R F : Type} {arity : F → ℕ} + +section + +variable [Fintype A] + +def Term.roots (rel : R → A → A → Bool) (s : State F arity A) : + Term R F arity → (ℕ → HF A) → Finset (HF A) + | t@(.var _), v | t@(.ordinal _), v | t@(.atoms), v => {t.eval rel s v} + | t@(.app _ args), v => insert (t.eval rel s v) + ((List.ofFn (fun i => roots rel s (args i) v)).foldr (· ∪ ·) ∅) + | t@(.pair a b), v | t@(.equal a b), v | t@(.member a b), v + | t@(.input _ a b), v | t@(.and a b), v | t@(.or a b), v => + insert (t.eval rel s v) (roots rel s a v ∪ roots rel s b v) + | t@(.union a), v | t@(.unique a), v | t@(.card a), v + | t@(.isAtom a), v | t@(.not a), v => insert (t.eval rel s v) (roots rel s a v) + | .conditional c a b, v => roots rel s c v ∪ + if c.eval rel s v = Operational.truth then roots rel s a v else roots rel s b v + | t@(.comprehend n bound guard body), v => insert (t.eval rel s v) + (roots rel s bound v ∪ (elements (bound.eval rel s v)).biUnion (fun x => + roots rel s guard (Function.update v n x) ∪ + if guard.eval rel s (Function.update v n x) = Operational.truth then + roots rel s body (Function.update v n x) else ∅)) + +def Rule.roots (rel : R → A → A → Bool) (s : State F arity A) : + Rule R F arity → (ℕ → HF A) → Finset (HF A) + | .skip, _ => ∅ + | .update _ args value, v => value.roots rel s v ∪ + (List.ofFn (fun i => (args i).roots rel s v)).foldr (· ∪ ·) ∅ + | .parallel a b, v => roots rel s a v ∪ roots rel s b v + | .conditional c a b, v => c.roots rel s v ∪ + if c.eval rel s v = Operational.truth then roots rel s a v else roots rel s b v + | .forall n bound body, v => bound.roots rel s v ∪ + (elements (bound.eval rel s v)).biUnion (fun x => roots rel s body (Function.update v n x)) + | .letValue n value body, v => value.roots rel s v ∪ + roots rel s body (Function.update v n (value.eval rel s v)) + +end + +section + +variable (P : Program R) [Fintype A] + +def Program.stepRoots (rel : R → A → A → Bool) (s : P.Store (A := A)) : Finset (HF A) := + if P.flag s .halt then ∅ else P.body.roots rel s (fun _ => Operational.empty) + +def Program.occurring (rel : R → A → A → Bool) (h : ℕ) : Finset (HF A) := + P.active rel h ∪ (range h).biUnion (fun j => match P.run rel j with + | none => ∅ + | some s => familyClosure (P.stepRoots rel s)) + +def Program.evaluationAccepts (time space : Polynomial ℕ) (rel : R → A → A → Bool) : Prop := + ∃ h st, h ≤ time.eval (Fintype.card A) ∧ P.run rel h = some st ∧ P.flag st .halt ∧ P.flag st .accept ∧ + (P.occurring rel h).card ≤ space.eval (Fintype.card A) + +end + +def EvaluationDefinable (Q : ∀ {A : Type}, [Fintype A] → Input A → Prop) : Prop := + ∃ P : Program Symbol, ∃ time space : Polynomial ℕ, + ∀ (A : Type) [Fintype A] (I : Input A), P.evaluationAccepts time space I.rel ↔ Q I + +end FullCPT + +namespace OrderedQuery + +section + +open Finset + +variable {N : ℕ} + +abbrev Data (N : ℕ) := Input (Fin N) + +end + +def indexSymbol (i : Fin 8) : Symbol := + if i.val = 0 then .Ed else + if i.val = 1 then .Cf else + if i.val = 2 then .EB else + if i.val = 3 then .VB else + if i.val = 4 then .I else .Z ((i.val-5 : ℕ) : Scalar) + +variable {N : ℕ} + +def cellValue (S : Data N) (k : Fin (8*(N*N))) : Bool := + let ij := finProdFinEquiv.symm k + let ab := finProdFinEquiv.symm ij.2 + S.rel (indexSymbol ij.1) ab.1 ab.2 + +def tableBits (S : Data N) : List Bool := List.ofFn (cellValue S) + +abbrev OrderedInput := Σ N, Data N + +end OrderedQuery + +namespace GaussMachine + +abbrev Letter := Option Scalar + +def boolCode (b : Bool) : List Letter := [some (if b then 1 else 0)] + +end GaussMachine + +namespace CounterLang + +abbrev Letter := Option Scalar + +end CounterLang + +namespace TableMachine + +open CounterLang + +def bitLetter (b : Bool) : Letter := some (if b then 1 else 0) + +def tableInput {N} (S : OrderedQuery.Data N) : List Letter := + (OrderedQuery.tableBits S).map bitLetter + +def code (S : OrderedQuery.OrderedInput) : List Letter := + List.replicate S.1 none ++ some 0 :: tableInput S.2 + +end TableMachine + +def Input.ordered {A : Type} {N : ℕ} (S : Input A) (e : A ≃ Fin N) : OrderedQuery.Data N := + ⟨fun r i j => S.rel r (e.symm i) (e.symm j)⟩ + +def OrdinaryPolynomialTime : Prop := + ∃ answer : OrderedQuery.OrderedInput → Bool, + ∃ machine : Turing.TM2ComputableInPolyTime TableMachine.code GaussMachine.boolCode answer, + (∀ k, Finite (machine.tm.Γ k)) ∧ + ∀ (A : Type) [Fintype A] (N : ℕ) (e : A ≃ Fin N) (S : Input A), + answer ⟨N,S.ordered e⟩ = true ↔ S.query + +theorem main : + (∀ (A B : Type) [Fintype A] [Fintype B] (S : Input A) (T : Input B), + S.Iso T → (S.query ↔ T.query)) ∧ + OrdinaryPolynomialTime ∧ + ¬ FullCPT.EvaluationDefinable (fun {_} [_] I => I.query) := by + sorry + +end CPTSeparation + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ChoicelessPolynomialTime.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CPTSeparation.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/choiceless-polynomial-time/solution/closure.txt b/tasks/choiceless-polynomial-time/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..21fc01cbc5b8d901348b4ef79ca4444c852a68e5 --- /dev/null +++ b/tasks/choiceless-polynomial-time/solution/closure.txt @@ -0,0 +1,26 @@ +OAI.ModelTheory.Choiceless.Bounds +OAI.ModelTheory.Choiceless.Counters +OAI.ModelTheory.Choiceless.Counting +OAI.ModelTheory.Choiceless.Definability +OAI.ModelTheory.Choiceless.Evaluation +OAI.ModelTheory.Choiceless.Flows +OAI.ModelTheory.Choiceless.Forms +OAI.ModelTheory.Choiceless.FullLanguage +OAI.ModelTheory.Choiceless.GaussMachine +OAI.ModelTheory.Choiceless.Gaussian +OAI.ModelTheory.Choiceless.Grid +OAI.ModelTheory.Choiceless.Hereditary +OAI.ModelTheory.Choiceless.Interpretations +OAI.ModelTheory.Choiceless.LowerBound +OAI.ModelTheory.Choiceless.Matrix +OAI.ModelTheory.Choiceless.Model +OAI.ModelTheory.Choiceless.Observers +OAI.ModelTheory.Choiceless.Operational +OAI.ModelTheory.Choiceless.QueryMachine +OAI.ModelTheory.Choiceless.Reachability +OAI.ModelTheory.Choiceless.Separation +OAI.ModelTheory.Choiceless.Simulation +OAI.ModelTheory.Choiceless.Stack +OAI.ModelTheory.Choiceless.Support +OAI.ModelTheory.Choiceless.TableMachine +OAI.ModelTheory.Choiceless.Traces diff --git a/tasks/choiceless-polynomial-time/solution/reference.py b/tasks/choiceless-polynomial-time/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/choiceless-polynomial-time/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/choiceless-polynomial-time/solution/solve.sh b/tasks/choiceless-polynomial-time/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a99653c89e6eea1f6ac6a3b079f6413d41a5497 --- /dev/null +++ b/tasks/choiceless-polynomial-time/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ChoicelessPolynomialTime, i.e. module OAI.ModelTheory.Choiceless.Separation and the +# 26 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.ModelTheory.Choiceless.Separation /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ChoicelessPolynomialTime" diff --git a/tasks/choiceless-polynomial-time/task.toml b/tasks/choiceless-polynomial-time/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..db7152dc74b7c429ed9a10149ed1295311b6fe53 --- /dev/null +++ b/tasks/choiceless-polynomial-time/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/choiceless-polynomial-time" +version = "1.0.0" +description = "Prove ChoicelessPolynomialTime (openai/math family 243: Choiceless counting does not capture polynomial time) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ChoicelessPolynomialTime.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ChoicelessPolynomialTime" +family = "243" +family_title = "Choiceless counting does not capture polynomial time" +subject = "Mathematical logic" +theorems = ["OAI.CPTSeparation.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.ModelTheory.Choiceless.Separation" +reference_modules = 26 +reference_lean_bytes = 803577 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 574 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12423 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/choiceless-polynomial-time/tests/Challenge.lean b/tasks/choiceless-polynomial-time/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bd3c72dce00153c675c2bd897bb1a7ed4cba9c15 --- /dev/null +++ b/tasks/choiceless-polynomial-time/tests/Challenge.lean @@ -0,0 +1,560 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe uA uB uC uF uR + +namespace CPTSeparation + +abbrev Scalar := ZMod 3 + +inductive Symbol + | Ed | Cf | EB | VB | I | Z (δ : Scalar) + deriving DecidableEq, Fintype + +structure Input (A : Type) where + rel : Symbol → A → A → Bool + +namespace Input + +variable {A B : Type} [Fintype A] [Fintype B] + +abbrev Edge (S : Input A) := {y : A // S.rel .Ed y y = true} + +abbrev Config (S : Input A) := {a : A // S.rel .Cf a a = true} + +instance (S : Input A) : Fintype S.Edge := inferInstanceAs (Fintype (Subtype _)) + +instance (S : Input A) : Fintype S.Config := inferInstanceAs (Fintype (Subtype _)) + +def coefficient (S : Input A) (y : S.Edge) (a : S.Config) : Scalar := + ∑ x : S.Edge, if S.rel .I a x then + ∑ δ : Scalar, if S.rel (.Z δ) y x then δ else 0 + else 0 + +def incident (S : Input A) (t : S.Config) (y : S.Edge) : Prop := + ∃ a : S.Config, S.rel .VB t a = true ∧ + ∃ x : S.Edge, S.rel .I a x = true ∧ S.rel .EB y x = true + +def normalized (S : Input A) (lambda : S.Config → Scalar) : Prop := + ∀ t : S.Config, (∑ a : S.Config, if S.rel .VB t a then lambda a else 0) = 1 + +def consistent (S : Input A) (lambda : S.Config → Scalar) (mu : S.Edge → Scalar) : Prop := + ∀ (t : S.Config) (y : S.Edge), S.incident t y → + mu y = ∑ a : S.Config, if S.rel .VB t a then lambda a * S.coefficient y a else 0 + +def query (S : Input A) : Prop := + ∃ (lambda : S.Config → Scalar) (mu : S.Edge → Scalar), S.normalized lambda ∧ S.consistent lambda mu + +structure Iso (S : Input A) (T : Input B) extends A ≃ B where + rel_eq : ∀ r x y, T.rel r (toEquiv x) (toEquiv y) = S.rel r x y + +end Input + +namespace Hereditary + +section + +abbrev HF (A : Type uA) := Quotient (@Lists.instSetoidLists A) + +variable {A : Type uA} {B : Type uB} + +local instance instDecidableEqHF {A : Type uA} : DecidableEq (HF A) := Classical.decEq _ + +def mk (l : Lists A) : HF A := Quotient.mk Lists.instSetoidLists l + +def atom (a : A) : HF A := mk (Lists.atom a) + +def isSet (x : HF A) : Bool := Quotient.liftOn x (fun l => l.1) + (by intro l r h; cases h <;> rfl) + +def rawElements (l : Lists A) : Finset (HF A) := by + classical + exact l.toList.toFinset.image mk + +def elements (x : HF A) : Finset (HF A) := Quotient.liftOn x rawElements (by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have raw_mem_congr_right {l r : Lists A} (h : Lists.Equiv l r) (a : Lists A) : + a ∈ l ↔ a ∈ r := by + cases h with + | refl => rfl + | antisymm hl hr => + exact ⟨Lists'.mem_of_subset hl, Lists'.mem_of_subset hr⟩ + intro l r h + ext z + induction z using Quotient.inductionOn with + | _ a => + change mk a ∈ rawElements l ↔ mk a ∈ rawElements r + rw [mem_rawElements, mem_rawElements] + exact raw_mem_congr_right h a) + +instance : Membership (HF A) (HF A) := ⟨fun y x => x ∈ elements y⟩ + +def ofFinset (s : Finset (HF A)) : HF A := + mk (Lists.ofList (s.toList.map Quotient.out)) + +def rawRank' : {b : Bool} → Lists' A b → ℕ + | _, .atom _ => 0 + | _, .nil => 0 + | _, .cons' a l => max (rawRank' a + 1) (rawRank' l) + +def rawRank (l : Lists A) : ℕ := rawRank' l.2 + +def rank (x : HF A) : ℕ := Quotient.liftOn x rawRank (by + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm hl hr ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r heq hmem hsub iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + exact fun _ _ h => rawRank_congr h) + +end + +open Classical Finset + +variable {A : Type uA} {B : Type uB} + +def double (a b : HF A) : HF A := ofFinset {a,b} + +def ordinal : ℕ → HF A + | 0 => ofFinset ∅ + | i+1 => ofFinset (insert (ordinal i) (elements (ordinal i))) + +end Hereditary + +namespace Operational + +open Classical Hereditary Finset + +variable {A : Type uA} {B : Type uB} {R : Type uR} {F : Type uF} {arity : F → ℕ} + +local instance instDecidableEqHF {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +abbrev empty : HF A := ordinal 0 + +abbrev truth : HF A := ordinal 1 + +def boolean (p : Prop) : HF A := if p then truth else empty + +def inputRelation (rel : R → A → A → Bool) (r : R) (x y : HF A) : Prop := + ∃ a b, x = atom a ∧ y = atom b ∧ rel r a b = true + +def allAtoms [Fintype A] : HF A := ofFinset (univ.image atom) + +def unionHF (x : HF A) : HF A := ofFinset ((elements x).biUnion elements) + +def uniqueHF (x : HF A) : HF A := + if h : ∃ a, elements x = {a} then h.choose else empty + +def cardinalityHF (x : HF A) : HF A := ordinal (elements x).card + +abbrev Location (F : Type uF) (arity : F → ℕ) (A : Type uA) := Σ f : F, Fin (arity f) → HF A + +structure State (F : Type uF) (arity : F → ℕ) (A : Type uA) where + value : Location F arity A → HF A + finite : Set.Finite {l | value l ≠ empty} + +namespace State + +def initial : State F arity A := ⟨fun _ => empty, by simp⟩ + +def support (s : State F arity A) : Finset (Location F arity A) := s.finite.toFinset + +end State + +abbrev Update (F : Type uF) (arity : F → ℕ) (A : Type uA) := Location F arity A × HF A + +def State.Consistent (u : Finset (Update F arity A)) : Prop := + ∀ l x y, (l,x) ∈ u → (l,y) ∈ u → x = y + +def State.updatedValue (s : State F arity A) (u : Finset (Update F arity A)) + (l : Location F arity A) : HF A := + if h : ∃ x, (l,x) ∈ u then h.choose else s.value l + +def State.applyUpdates (s : State F arity A) (u : Finset (Update F arity A)) : State F arity A where + value := s.updatedValue u + finite := by + apply (s.finite.union (u.image Prod.fst).finite_toSet).subset + intro l hl + by_cases h : ∃ x, (l,x) ∈ u + · obtain ⟨x,hx⟩ := h + exact Or.inr (mem_image.mpr ⟨(l,x),hx,rfl⟩) + · exact Or.inl (by simpa only [Set.mem_ofPred_eq,updatedValue,dite_eq_right h] using hl) + +inductive Control | halt | accept deriving DecidableEq + +end Operational + +section + +open Classical Finset + +variable {A : Type uA} {B : Type uB} + +local instance Hereditary.instDecidableEqHF_1 {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +def Hereditary.closure (x : HF A) : Finset (HF A) := + insert x ((elements x).attach.biUnion (fun y => closure y.val)) +termination_by rank x +decreasing_by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _hl _hr ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _heq hmem _hsub iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + have rank_lt_of_mem {x y : HF A} (h : x ∈ y) : rank x < rank y := by + induction y using Quotient.inductionOn with + | _ l => + induction x using Quotient.inductionOn with + | _ a => + have h' := (mem_rawElements a l).mp h + rcases l with ⟨(_ | _), l⟩ + · exact False.elim h' + · obtain ⟨a',ha',heq⟩ := h' + change rawRank a < rawRank' l + rw [rawRank_congr heq] + exact rawRank_lt_of_mem l a' ha' + exact rank_lt_of_mem y.property + +def Hereditary.familyClosure (f : Finset (HF A)) : Finset (HF A) := f.biUnion closure + +end + +section + +open Classical Hereditary Finset + +variable {A : Type uA} {R : Type uR} {F : Type uF} {arity : F → ℕ} + +local instance Operational.instDecidableEqHF_1 {C : Type uC} : DecidableEq (HF C) := Classical.decEq _ + +def Operational.State.critical (s : State F arity A) : Finset (HF A) := + s.support.biUnion (fun l => insert (s.value l) (univ.image l.2)) + +def Operational.State.active [Fintype A] (s : State F arity A) : Finset (HF A) := + familyClosure (s.critical ∪ {allAtoms,empty,truth} ∪ univ.image atom) + +end + +namespace FullCPT + +section + +open Classical Hereditary Finset + +open Operational (State Control Location Update) + +local instance instDecidableEqHF {C : Type} : DecidableEq (HF C) := Classical.decEq _ + +inductive Term (R F : Type) (arity : F → ℕ) : Type + | var (name : ℕ) + | ordinal (n : ℕ) + | atoms + | app (f : F) (args : Fin (arity f) → Term R F arity) + | pair (a b : Term R F arity) + | union (a : Term R F arity) + | unique (a : Term R F arity) + | card (a : Term R F arity) + | equal (a b : Term R F arity) + | member (a b : Term R F arity) + | isAtom (a : Term R F arity) + | input (r : R) (a b : Term R F arity) + | not (a : Term R F arity) + | and (a b : Term R F arity) + | or (a b : Term R F arity) + | conditional (c a b : Term R F arity) + | comprehend (name : ℕ) (bound guard body : Term R F arity) + +variable {A R F : Type} {arity : F → ℕ} + +namespace Term + +variable [Fintype A] + +def eval (rel : R → A → A → Bool) (s : State F arity A) : + Term R F arity → (ℕ → HF A) → HF A + | .var n, v => v n + | .ordinal n, _ => Hereditary.ordinal n + | .atoms, _ => Operational.allAtoms + | .app f args, v => s.value ⟨f, fun i => eval rel s (args i) v⟩ + | .pair a b, v => double (eval rel s a v) (eval rel s b v) + | .union a, v => Operational.unionHF (eval rel s a v) + | .unique a, v => Operational.uniqueHF (eval rel s a v) + | .card a, v => Operational.cardinalityHF (eval rel s a v) + | .equal a b, v => Operational.boolean (eval rel s a v = eval rel s b v) + | .member a b, v => Operational.boolean (eval rel s a v ∈ eval rel s b v) + | .isAtom a, v => Operational.boolean (isSet (eval rel s a v) = false) + | .input r a b, v => Operational.boolean (Operational.inputRelation rel r (eval rel s a v) (eval rel s b v)) + | .not a, v => Operational.boolean (eval rel s a v ≠ Operational.truth) + | .and a b, v => Operational.boolean (eval rel s a v = Operational.truth ∧ eval rel s b v = Operational.truth) + | .or a b, v => Operational.boolean (eval rel s a v = Operational.truth ∨ eval rel s b v = Operational.truth) + | .conditional c a b, v => if eval rel s c v = Operational.truth then eval rel s a v else eval rel s b v + | .comprehend n bound guard body, v => + ofFinset (((elements (eval rel s bound v)).filter + (fun x => eval rel s guard (Function.update v n x) = Operational.truth)).image + (fun x => eval rel s body (Function.update v n x))) + +end Term + +inductive Rule (R F : Type) (arity : F → ℕ) : Type + | skip + | update (f : F) (args : Fin (arity f) → Term R F arity) (value : Term R F arity) + | parallel (a b : Rule R F arity) + | conditional (condition : Term R F arity) (a b : Rule R F arity) + | forall (name : ℕ) (bound : Term R F arity) (body : Rule R F arity) + | letValue (name : ℕ) (value : Term R F arity) (body : Rule R F arity) + +namespace Rule + +def updates [Fintype A] (rel : R → A → A → Bool) (s : State F arity A) : + Rule R F arity → (ℕ → HF A) → Finset (Update F arity A) + | .skip, _ => ∅ + | .update f args value, v => {(⟨f, fun i => (args i).eval rel s v⟩, value.eval rel s v)} + | .parallel a b, v => updates rel s a v ∪ updates rel s b v + | .conditional c a b, v => if c.eval rel s v = Operational.truth then updates rel s a v else updates rel s b v + | .forall n bound body, v => (elements (bound.eval rel s v)).biUnion + (fun x => updates rel s body (Function.update v n x)) + | .letValue n value body, v => updates rel s body (Function.update v n (value.eval rel s v)) + +end Rule + +structure Program (R : Type) where + Functions : Type + finiteFunctions : Fintype Functions + arity : Functions → ℕ + body : Rule R (Control ⊕ Functions) (Sum.elim (fun _ => 0) arity) + +namespace Program + +variable (P : Program R) [Fintype A] + +abbrev functionArity : Control ⊕ P.Functions → ℕ := Sum.elim (fun _ => 0) P.arity + +abbrev Store := State (Control ⊕ P.Functions) P.functionArity A + +def flag (s : P.Store (A := A)) (c : Control) : Prop := s.value ⟨.inl c, Fin.elim0⟩ = Operational.truth + +def step (rel : R → A → A → Bool) (s : P.Store (A := A)) : Option (P.Store (A := A)) := + if P.flag s .halt then some s else + let u := P.body.updates rel s (fun _ => Operational.empty) + if State.Consistent u then some (s.applyUpdates u) else none + +def run (rel : R → A → A → Bool) : ℕ → Option (P.Store (A := A)) + | 0 => some State.initial + | j+1 => (run rel j).bind (P.step rel) + +def active (rel : R → A → A → Bool) (h : ℕ) : Finset (HF A) := + (Finset.range (h+1)).biUnion (fun j => ((P.run rel j).toFinset).biUnion State.active) + +end Program + +end + +open Classical Hereditary Finset + +open Operational (State Control) + +local instance instDecidableEqHF_1 {C : Type} : DecidableEq (HF C) := Classical.decEq _ + +variable {A R F : Type} {arity : F → ℕ} + +section + +variable [Fintype A] + +def Term.roots (rel : R → A → A → Bool) (s : State F arity A) : + Term R F arity → (ℕ → HF A) → Finset (HF A) + | t@(.var _), v | t@(.ordinal _), v | t@(.atoms), v => {t.eval rel s v} + | t@(.app _ args), v => insert (t.eval rel s v) + ((List.ofFn (fun i => roots rel s (args i) v)).foldr (· ∪ ·) ∅) + | t@(.pair a b), v | t@(.equal a b), v | t@(.member a b), v + | t@(.input _ a b), v | t@(.and a b), v | t@(.or a b), v => + insert (t.eval rel s v) (roots rel s a v ∪ roots rel s b v) + | t@(.union a), v | t@(.unique a), v | t@(.card a), v + | t@(.isAtom a), v | t@(.not a), v => insert (t.eval rel s v) (roots rel s a v) + | .conditional c a b, v => roots rel s c v ∪ + if c.eval rel s v = Operational.truth then roots rel s a v else roots rel s b v + | t@(.comprehend n bound guard body), v => insert (t.eval rel s v) + (roots rel s bound v ∪ (elements (bound.eval rel s v)).biUnion (fun x => + roots rel s guard (Function.update v n x) ∪ + if guard.eval rel s (Function.update v n x) = Operational.truth then + roots rel s body (Function.update v n x) else ∅)) + +def Rule.roots (rel : R → A → A → Bool) (s : State F arity A) : + Rule R F arity → (ℕ → HF A) → Finset (HF A) + | .skip, _ => ∅ + | .update _ args value, v => value.roots rel s v ∪ + (List.ofFn (fun i => (args i).roots rel s v)).foldr (· ∪ ·) ∅ + | .parallel a b, v => roots rel s a v ∪ roots rel s b v + | .conditional c a b, v => c.roots rel s v ∪ + if c.eval rel s v = Operational.truth then roots rel s a v else roots rel s b v + | .forall n bound body, v => bound.roots rel s v ∪ + (elements (bound.eval rel s v)).biUnion (fun x => roots rel s body (Function.update v n x)) + | .letValue n value body, v => value.roots rel s v ∪ + roots rel s body (Function.update v n (value.eval rel s v)) + +end + +section + +variable (P : Program R) [Fintype A] + +def Program.stepRoots (rel : R → A → A → Bool) (s : P.Store (A := A)) : Finset (HF A) := + if P.flag s .halt then ∅ else P.body.roots rel s (fun _ => Operational.empty) + +def Program.occurring (rel : R → A → A → Bool) (h : ℕ) : Finset (HF A) := + P.active rel h ∪ (range h).biUnion (fun j => match P.run rel j with + | none => ∅ + | some s => familyClosure (P.stepRoots rel s)) + +def Program.evaluationAccepts (time space : Polynomial ℕ) (rel : R → A → A → Bool) : Prop := + ∃ h st, h ≤ time.eval (Fintype.card A) ∧ P.run rel h = some st ∧ P.flag st .halt ∧ P.flag st .accept ∧ + (P.occurring rel h).card ≤ space.eval (Fintype.card A) + +end + +def EvaluationDefinable (Q : ∀ {A : Type}, [Fintype A] → Input A → Prop) : Prop := + ∃ P : Program Symbol, ∃ time space : Polynomial ℕ, + ∀ (A : Type) [Fintype A] (I : Input A), P.evaluationAccepts time space I.rel ↔ Q I + +end FullCPT + +namespace OrderedQuery + +section + +open Finset + +variable {N : ℕ} + +abbrev Data (N : ℕ) := Input (Fin N) + +end + +def indexSymbol (i : Fin 8) : Symbol := + if i.val = 0 then .Ed else + if i.val = 1 then .Cf else + if i.val = 2 then .EB else + if i.val = 3 then .VB else + if i.val = 4 then .I else .Z ((i.val-5 : ℕ) : Scalar) + +variable {N : ℕ} + +def cellValue (S : Data N) (k : Fin (8*(N*N))) : Bool := + let ij := finProdFinEquiv.symm k + let ab := finProdFinEquiv.symm ij.2 + S.rel (indexSymbol ij.1) ab.1 ab.2 + +def tableBits (S : Data N) : List Bool := List.ofFn (cellValue S) + +abbrev OrderedInput := Σ N, Data N + +end OrderedQuery + +namespace GaussMachine + +abbrev Letter := Option Scalar + +def boolCode (b : Bool) : List Letter := [some (if b then 1 else 0)] + +end GaussMachine + +namespace CounterLang + +abbrev Letter := Option Scalar + +end CounterLang + +namespace TableMachine + +open CounterLang + +def bitLetter (b : Bool) : Letter := some (if b then 1 else 0) + +def tableInput {N} (S : OrderedQuery.Data N) : List Letter := + (OrderedQuery.tableBits S).map bitLetter + +def code (S : OrderedQuery.OrderedInput) : List Letter := + List.replicate S.1 none ++ some 0 :: tableInput S.2 + +end TableMachine + +def Input.ordered {A : Type} {N : ℕ} (S : Input A) (e : A ≃ Fin N) : OrderedQuery.Data N := + ⟨fun r i j => S.rel r (e.symm i) (e.symm j)⟩ + +def OrdinaryPolynomialTime : Prop := + ∃ answer : OrderedQuery.OrderedInput → Bool, + ∃ machine : Turing.TM2ComputableInPolyTime TableMachine.code GaussMachine.boolCode answer, + (∀ k, Finite (machine.tm.Γ k)) ∧ + ∀ (A : Type) [Fintype A] (N : ℕ) (e : A ≃ Fin N) (S : Input A), + answer ⟨N,S.ordered e⟩ = true ↔ S.query + +theorem main : + (∀ (A B : Type) [Fintype A] [Fintype B] (S : Input A) (T : Input B), + S.Iso T → (S.query ↔ T.query)) ∧ + OrdinaryPolynomialTime ∧ + ¬ FullCPT.EvaluationDefinable (fun {_} [_] I => I.query) := by + sorry + +end CPTSeparation + +end + +end OAI diff --git a/tasks/choiceless-polynomial-time/tests/grade.py b/tasks/choiceless-polynomial-time/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/choiceless-polynomial-time/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/choiceless-polynomial-time/tests/task.json b/tasks/choiceless-polynomial-time/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ea1ec366a6c20d4db8f529ce0377eb36c49e4576 --- /dev/null +++ b/tasks/choiceless-polynomial-time/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ChoicelessPolynomialTime", + "comparator": { + "theorem_names": [ + "OAI.CPTSeparation.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11523 +} \ No newline at end of file diff --git a/tasks/choiceless-polynomial-time/tests/test.sh b/tasks/choiceless-polynomial-time/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/choiceless-polynomial-time/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/circulant-hadamard/environment/Dockerfile b/tasks/circulant-hadamard/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/circulant-hadamard/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/circulant-hadamard/environment/fetch_mathlib.sh b/tasks/circulant-hadamard/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/circulant-hadamard/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/circulant-hadamard/environment/lake-manifest.json b/tasks/circulant-hadamard/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/circulant-hadamard/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/circulant-hadamard/environment/lakefile.lean b/tasks/circulant-hadamard/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/circulant-hadamard/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/circulant-hadamard/environment/lean_setup.sh b/tasks/circulant-hadamard/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/circulant-hadamard/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/circulant-hadamard/environment/pack_submission.py b/tasks/circulant-hadamard/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/circulant-hadamard/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/circulant-hadamard/instruction.md b/tasks/circulant-hadamard/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..74f8a523048515ee6d322ade997cfcbcfbc37275 --- /dev/null +++ b/tasks/circulant-hadamard/instruction.md @@ -0,0 +1,81 @@ +# openai/math challenge `CirculantHadamard` (family 179) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 179 of the release, *The circulant Hadamard conjecture* +(Combinatorics). The family as a whole: Proves that real circulant Hadamard matrices exist exactly in orders $1$ and $4$, resolving the circulant Hadamard conjecture. Together with classical Barker-sequence results, this shows that binary sequences whose nontrivial aperiodic autocorrelations have magnitude at most $1$ exist at lengths $n>1$ exactly when $n\in\{2,3,4,5,7,11,13\}$. + +The challenge is `CirculantHadamard`, also at `/opt/openai-math/challenges/CirculantHadamard.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CirculantHadamard + +universe u + +def IsSign {R : Type u} [One R] [Neg R] (x : R) : Prop := + x = 1 ∨ x = -1 + +abbrev RealMatrix (n : ℕ) := Matrix (Fin n) (Fin n) ℝ + +def IsCirculant {n : ℕ} (H : RealMatrix n) : Prop := + ∃ h : Fin n → ℝ, ∀ i j, H i j = h (j - i) + +def IsSignHadamard {n : ℕ} (H : RealMatrix n) : Prop := + (∀ i j, IsSign (H i j)) ∧ + H * H.transpose = (n : ℝ) • (1 : RealMatrix n) + +def ExistsRealCirculantHadamard (n : ℕ) : Prop := + ∃ H : RealMatrix n, IsCirculant H ∧ IsSignHadamard H + +theorem exists_iff_order_one_or_four (n : ℕ) (hn : 0 < n) : + ExistsRealCirculantHadamard n ↔ n = 1 ∨ n = 4 := by + sorry + +end CirculantHadamard + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CirculantHadamard.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CirculantHadamard.exists_iff_order_one_or_four` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/circulant-hadamard/solution/closure.txt b/tasks/circulant-hadamard/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1a2632cc39e424000571e823cb218e2ae365f79f --- /dev/null +++ b/tasks/circulant-hadamard/solution/closure.txt @@ -0,0 +1,68 @@ +OAI.LinearAlgebra.CirculantHadamard.AlternatingField +OAI.LinearAlgebra.CirculantHadamard.AlternatingLocalization +OAI.LinearAlgebra.CirculantHadamard.AlternatingNorm +OAI.LinearAlgebra.CirculantHadamard.AlternatingProducts +OAI.LinearAlgebra.CirculantHadamard.AlternatingTorsion +OAI.LinearAlgebra.CirculantHadamard.Basic +OAI.LinearAlgebra.CirculantHadamard.BinaryBlocks +OAI.LinearAlgebra.CirculantHadamard.BinaryCharacterSum +OAI.LinearAlgebra.CirculantHadamard.BinaryCoefficients +OAI.LinearAlgebra.CirculantHadamard.BinaryContradiction +OAI.LinearAlgebra.CirculantHadamard.BinaryEvaluation +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalFamily +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalRing +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalization +OAI.LinearAlgebra.CirculantHadamard.BinaryNorms +OAI.LinearAlgebra.CirculantHadamard.BinaryProductTransport +OAI.LinearAlgebra.CirculantHadamard.BinaryResidue +OAI.LinearAlgebra.CirculantHadamard.CoefficientEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluationAt +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluationProjection +OAI.LinearAlgebra.CirculantHadamard.CyclicNorm +OAI.LinearAlgebra.CirculantHadamard.CyclicPolynomial +OAI.LinearAlgebra.CirculantHadamard.CyclicProjection +OAI.LinearAlgebra.CirculantHadamard.CyclicProjectionPolynomial +OAI.LinearAlgebra.CirculantHadamard.CyclicRing +OAI.LinearAlgebra.CirculantHadamard.CyclicScalarDivision +OAI.LinearAlgebra.CirculantHadamard.CyclotomicAdjoin +OAI.LinearAlgebra.CirculantHadamard.CyclotomicAwayLocal +OAI.LinearAlgebra.CirculantHadamard.CyclotomicFactorDivision +OAI.LinearAlgebra.CirculantHadamard.CyclotomicIntegerEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclotomicLocalBase +OAI.LinearAlgebra.CirculantHadamard.CyclotomicProjection +OAI.LinearAlgebra.CirculantHadamard.CyclotomicRemainder +OAI.LinearAlgebra.CirculantHadamard.CyclotomicRings +OAI.LinearAlgebra.CirculantHadamard.CyclotomicTorsion +OAI.LinearAlgebra.CirculantHadamard.DyadicRemainder +OAI.LinearAlgebra.CirculantHadamard.FirstOrderResidue +OAI.LinearAlgebra.CirculantHadamard.IntegerLocalDivisibility +OAI.LinearAlgebra.CirculantHadamard.IntegerTwoLocal +OAI.LinearAlgebra.CirculantHadamard.Kronecker +OAI.LinearAlgebra.CirculantHadamard.LocalComparison +OAI.LinearAlgebra.CirculantHadamard.LocalComparisonInduction +OAI.LinearAlgebra.CirculantHadamard.LocalDVR +OAI.LinearAlgebra.CirculantHadamard.LocalizationIntersection +OAI.LinearAlgebra.CirculantHadamard.LocalizationMaps +OAI.LinearAlgebra.CirculantHadamard.Main +OAI.LinearAlgebra.CirculantHadamard.MatrixBridge +OAI.LinearAlgebra.CirculantHadamard.ModEight +OAI.LinearAlgebra.CirculantHadamard.Model +OAI.LinearAlgebra.CirculantHadamard.OrderCyclotomicDivisibility +OAI.LinearAlgebra.CirculantHadamard.OrderDescent +OAI.LinearAlgebra.CirculantHadamard.OrderHalving +OAI.LinearAlgebra.CirculantHadamard.OrderProjection +OAI.LinearAlgebra.CirculantHadamard.OrderReduction +OAI.LinearAlgebra.CirculantHadamard.OrderSquareEven +OAI.LinearAlgebra.CirculantHadamard.PrimeCharacterEvaluations +OAI.LinearAlgebra.CirculantHadamard.PrimeComponents +OAI.LinearAlgebra.CirculantHadamard.ProjectionCoefficients +OAI.LinearAlgebra.CirculantHadamard.ProjectionPairFiber +OAI.LinearAlgebra.CirculantHadamard.RamifiedConjugation +OAI.LinearAlgebra.CirculantHadamard.RamifiedEisenstein +OAI.LinearAlgebra.CirculantHadamard.RamifiedLocal +OAI.LinearAlgebra.CirculantHadamard.RamifiedUnit +OAI.LinearAlgebra.CirculantHadamard.ResidueOneAssociation +OAI.LinearAlgebra.CirculantHadamard.ResidueTorsion +OAI.LinearAlgebra.CirculantHadamard.TwoAdicDecomposition +OAI.LinearAlgebra.CirculantHadamard.Witnesses diff --git a/tasks/circulant-hadamard/solution/reference.py b/tasks/circulant-hadamard/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/circulant-hadamard/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/circulant-hadamard/solution/solve.sh b/tasks/circulant-hadamard/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ce8883dce54b46fed0f5add9c98995559f1a6c6 --- /dev/null +++ b/tasks/circulant-hadamard/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CirculantHadamard, i.e. module OAI.LinearAlgebra.CirculantHadamard.Main and the +# 68 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.LinearAlgebra.CirculantHadamard.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CirculantHadamard" diff --git a/tasks/circulant-hadamard/task.toml b/tasks/circulant-hadamard/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3958808113e6ddd1aefd90739423b373d4653422 --- /dev/null +++ b/tasks/circulant-hadamard/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/circulant-hadamard" +version = "1.0.0" +description = "Prove CirculantHadamard (openai/math family 179: The circulant Hadamard conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CirculantHadamard.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CirculantHadamard" +family = "179" +family_title = "The circulant Hadamard conjecture" +subject = "Combinatorics" +theorems = ["OAI.CirculantHadamard.exists_iff_order_one_or_four"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.LinearAlgebra.CirculantHadamard.Main" +reference_modules = 68 +reference_lean_bytes = 400871 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1652 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12060 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/circulant-hadamard/tests/Challenge.lean b/tasks/circulant-hadamard/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5a1a9aca17a7ad9e667be88bd60008f05a6a192 --- /dev/null +++ b/tasks/circulant-hadamard/tests/Challenge.lean @@ -0,0 +1,30 @@ +import Mathlib + +namespace OAI + +namespace CirculantHadamard + +universe u + +def IsSign {R : Type u} [One R] [Neg R] (x : R) : Prop := + x = 1 ∨ x = -1 + +abbrev RealMatrix (n : ℕ) := Matrix (Fin n) (Fin n) ℝ + +def IsCirculant {n : ℕ} (H : RealMatrix n) : Prop := + ∃ h : Fin n → ℝ, ∀ i j, H i j = h (j - i) + +def IsSignHadamard {n : ℕ} (H : RealMatrix n) : Prop := + (∀ i j, IsSign (H i j)) ∧ + H * H.transpose = (n : ℝ) • (1 : RealMatrix n) + +def ExistsRealCirculantHadamard (n : ℕ) : Prop := + ∃ H : RealMatrix n, IsCirculant H ∧ IsSignHadamard H + +theorem exists_iff_order_one_or_four (n : ℕ) (hn : 0 < n) : + ExistsRealCirculantHadamard n ↔ n = 1 ∨ n = 4 := by + sorry + +end CirculantHadamard + +end OAI diff --git a/tasks/circulant-hadamard/tests/grade.py b/tasks/circulant-hadamard/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/circulant-hadamard/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/circulant-hadamard/tests/task.json b/tasks/circulant-hadamard/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..290dc18d31243d5f4bdd6e8999a62be354c0c189 --- /dev/null +++ b/tasks/circulant-hadamard/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CirculantHadamard", + "comparator": { + "theorem_names": [ + "OAI.CirculantHadamard.exists_iff_order_one_or_four" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11160 +} \ No newline at end of file diff --git a/tasks/circulant-hadamard/tests/test.sh b/tasks/circulant-hadamard/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/circulant-hadamard/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cks-bondi-penrose/environment/Dockerfile b/tasks/cks-bondi-penrose/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cks-bondi-penrose/environment/fetch_mathlib.sh b/tasks/cks-bondi-penrose/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cks-bondi-penrose/environment/lake-manifest.json b/tasks/cks-bondi-penrose/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cks-bondi-penrose/environment/lakefile.lean b/tasks/cks-bondi-penrose/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cks-bondi-penrose/environment/lean_setup.sh b/tasks/cks-bondi-penrose/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cks-bondi-penrose/environment/pack_submission.py b/tasks/cks-bondi-penrose/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cks-bondi-penrose/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cks-bondi-penrose/instruction.md b/tasks/cks-bondi-penrose/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49c4ecb32124c827ef145651660a696242e14126 --- /dev/null +++ b/tasks/cks-bondi-penrose/instruction.md @@ -0,0 +1,3647 @@ +# openai/math challenge `CKSBondiPenrose` (family 260) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 260 of the release, *Spacetime Penrose inequalities and rigidity* +(Mathematical physics). The family as a whole: Proves the sharp enclosing-area spacetime Penrose inequality for smooth one-ended asymptotically flat initial data in every spatial dimension $n\ge3$, under dominant energy, weak future trapping, positive enclosing area, and the stated decay assumptions. It bounds invariant ADM mass below using minimum enclosing area, with equality rigidity under additional horizon hypotheses. Charged upper-area bounds treat dyonic three-dimensional data; the higher-dimensional purely electric extension uses the matched neutral theorem. + +The challenge is `CKSBondiPenrose`, also at `/opt/openai-math/challenges/CKSBondiPenrose.lean`: + +```lean +import Mathlib + +/-! Area-controlled end replacement and Schwarzschild equality examples. -/ + +namespace OAI.CKSADM +end OAI.CKSADM +namespace OAI.CKSAngularGeometry +end OAI.CKSAngularGeometry +namespace OAI.CKSAngularSlice +end OAI.CKSAngularSlice +namespace OAI.CKSBoundarySurface +end OAI.CKSBoundarySurface +namespace OAI.CKSCalculus +end OAI.CKSCalculus +namespace OAI.CKSCartesianOuter +end OAI.CKSCartesianOuter +namespace OAI.CKSEmbeddingDerivative +end OAI.CKSEmbeddingDerivative +namespace OAI.CKSFullCutArea +end OAI.CKSFullCutArea +namespace OAI.CKSGeometricCuts +end OAI.CKSGeometricCuts +namespace OAI.CKSInducedArea +end OAI.CKSInducedArea +namespace OAI.CKSInducedSphere +end OAI.CKSInducedSphere +namespace OAI.CKSIntrinsicConstraints +end OAI.CKSIntrinsicConstraints +namespace OAI.CKSIntrinsicGeometry +end OAI.CKSIntrinsicGeometry +namespace OAI.CKSIntrinsicVolume +end OAI.CKSIntrinsicVolume +namespace OAI.CKSLocalBending +end OAI.CKSLocalBending +namespace OAI.CKSLorentz +end OAI.CKSLorentz +namespace OAI.CKSLorentz.SmoothAngularPatch +end OAI.CKSLorentz.SmoothAngularPatch +namespace OAI.CKSMain +end OAI.CKSMain +namespace OAI.CKSMain.InteriorSurface +end OAI.CKSMain.InteriorSurface +namespace OAI.CKSMetricGluing +end OAI.CKSMetricGluing +namespace OAI.CKSMixedGeometry +end OAI.CKSMixedGeometry +namespace OAI.CKSMixedGeometry.FiniteLogDecay +end OAI.CKSMixedGeometry.FiniteLogDecay +namespace OAI.CKSRealizedRound +end OAI.CKSRealizedRound +namespace OAI.CKSReplacementCompleteness +end OAI.CKSReplacementCompleteness +namespace OAI.CKSRound +end OAI.CKSRound +namespace OAI.CKSRound.MetricJet +end OAI.CKSRound.MetricJet +namespace OAI.CKSSchwarzschild +end OAI.CKSSchwarzschild +namespace OAI.CKSSourceExterior +end OAI.CKSSourceExterior +namespace OAI.CKSSpatialManifold +end OAI.CKSSpatialManifold +namespace OAI.CKSSphericalHarmonics +end OAI.CKSSphericalHarmonics +namespace OAI.CKSSurfaceVolume +end OAI.CKSSurfaceVolume +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold + + +local instance real_id_isometric : RingHomIsometric (RingHom.id ℝ) := inferInstance + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMetricGluing +open Bundle Manifold Set Bornology +open scoped Bundle Manifold ContDiff +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSMetricGluing +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMetricGluing +open Bundle Manifold Set Bornology +open scoped Bundle Manifold ContDiff +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_2} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_3} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_continuousAdd + + +abbrev InnerField := + letI := OAI.CKSMetricGluing.real_smulCommClass + letI := OAI.CKSMetricGluing.real_continuousConstSMul + ∀ x : M, TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ + +abbrev SmoothMetric := ContMDiffRiemannianMetric I ∞ E (fun x : M => TangentSpace I x) + +def innerSection (q : OAI.CKSMetricGluing.InnerField I (M := M)) : + M → TotalSpace (E →L[ℝ] E →L[ℝ] ℝ) + (fun x : M => TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) := + fun x => ⟨x,q x⟩ + +end OAI.CKSMetricGluing +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev I := Fin 2 + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSCalculus +open Filter Set +open scoped Topology ContDiff +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + +def D (e : E) (f : E → ℝ) (x : E) : ℝ := fderiv ℝ f x e + +end OAI.CKSCalculus +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound + + +abbrev Idx := Fin 3 + +abbrev Mat := Matrix OAI.CKSRound.Idx OAI.CKSRound.Idx ℝ + +structure MetricJet where + inv : OAI.CKSRound.Mat + d : OAI.CKSRound.Idx → OAI.CKSRound.Mat + dd : OAI.CKSRound.Idx → OAI.CKSRound.Idx → OAI.CKSRound.Mat + +end OAI.CKSRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound.MetricJet + + +def gamma (j : OAI.CKSRound.MetricJet) (a i k : OAI.CKSRound.Idx) : ℝ := + (∑ l, j.inv a l * (j.d i k l + j.d k i l - j.d l i k)) / 2 + +def dInv (j : OAI.CKSRound.MetricJet) (s a b : OAI.CKSRound.Idx) : ℝ := + - ∑ i, ∑ k, j.inv a i * j.d s i k * j.inv k b + +def dGamma (j : OAI.CKSRound.MetricJet) (s a i k : OAI.CKSRound.Idx) : ℝ := + (∑ l, (j.dInv s a l * (j.d i k l + j.d k i l - j.d l i k) + + j.inv a l * (j.dd s i k l + j.dd s k i l - j.dd s l i k))) / 2 + +def ricci (j : OAI.CKSRound.MetricJet) (i k : OAI.CKSRound.Idx) : ℝ := + (∑ a, (j.dGamma a a i k - j.dGamma k a i a)) + + ∑ a, ∑ b, (j.gamma a a b * j.gamma b i k - j.gamma a k b * j.gamma b i a) + +def scalar (j : OAI.CKSRound.MetricJet) : ℝ := ∑ i, ∑ k, j.inv i k * j.ricci i k + +end OAI.CKSRound.MetricJet +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound + + +structure TensorJet where + val : OAI.CKSRound.Mat + d : OAI.CKSRound.Idx → OAI.CKSRound.Mat + +end OAI.CKSRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound.MetricJet + + +def trace (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ a, ∑ b, g.inv a b * k.val a b + +def normSq (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ a, ∑ b, ∑ c, ∑ d, g.inv a c * g.inv b d * k.val a b * k.val c d + +def dTrace (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + ∑ a, ∑ b, (g.dInv i a b * k.val a b + g.inv a b * k.d i a b) + +def tensorDivergence (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + ∑ a, ∑ b, g.inv a b * (k.d a b i - + (∑ c, g.gamma c a b * k.val c i) - (∑ c, g.gamma c a i * k.val b c)) + +def energy (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + (g.scalar + g.trace k ^ 2 - g.normSq k) / 2 + +def momentum (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + g.tensorDivergence k i - g.dTrace k i + +end OAI.CKSRound.MetricJet +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRealizedRound +open CKSCalculus CKSRound +open scoped Topology ContDiff + +abbrev Point := Fin 3 → ℝ + +def basis (a : OAI.CKSRound.Idx) : OAI.CKSRealizedRound.Point := Pi.single a 1 + +end OAI.CKSRealizedRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLocalBending +open CKSRound + +def momentumSq (j : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ i, ∑ l, j.inv i l * j.momentum k i * j.momentum k l + +def DEC (j : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : Prop := + Real.sqrt (OAI.CKSLocalBending.momentumSq j k) ≤ j.energy k + +end OAI.CKSLocalBending +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev Point := OAI.CKSAngularGeometry.I → ℝ + +def basis (a : OAI.CKSAngularGeometry.I) : OAI.CKSAngularGeometry.Point := Pi.single a 1 + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open CKSCalculus Set Filter Matrix +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev AmbientMat := Matrix (Fin 3) (Fin 3) ℝ + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Matrix CKSCalculus +open scoped BigOperators + +abbrev PhysicalPoint := Fin 3 → ℝ + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev I := Fin 3 + +abbrev A := Fin 2 + +abbrev Point := OAI.CKSMixedGeometry.I → ℝ + +def basis (a : OAI.CKSMixedGeometry.I) : OAI.CKSMixedGeometry.Point := Pi.single a 1 + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal + +local instance pointDimension_neZero : NeZero (3 : ℕ) := inferInstance + +def radialFactor (a : OAI.CKSMixedGeometry.I) (y : OAI.CKSMixedGeometry.Point) : ℝ := + letI := OAI.CKSMixedGeometry.pointDimension_neZero + if a = 0 then y 0 else 1 + +def scaledD (a : OAI.CKSMixedGeometry.I) (f : OAI.CKSMixedGeometry.Point → ℝ) : OAI.CKSMixedGeometry.Point → ℝ := + fun y => OAI.CKSMixedGeometry.radialFactor a y * OAI.CKSCalculus.D (OAI.CKSMixedGeometry.basis a) f y + +def scaledIter : List OAI.CKSMixedGeometry.I → (OAI.CKSMixedGeometry.Point → ℝ) → OAI.CKSMixedGeometry.Point → ℝ + | [], f => f + | a::l,f => OAI.CKSMixedGeometry.scaledD a (scaledIter l f) + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev Angle := OAI.CKSMixedGeometry.A → ℝ + +def angularProjection : OAI.CKSMixedGeometry.Point →L[ℝ] OAI.CKSMixedGeometry.Angle := + ContinuousLinearMap.pi (fun a => ContinuousLinearMap.proj a.succ) + +def ScaledComponentBound (f : OAI.CKSMixedGeometry.Point → ℝ) (j q : ℕ) (B : ℝ) (y : OAI.CKSMixedGeometry.Point) : Prop := + letI := OAI.CKSMixedGeometry.pointDimension_neZero + ∀ l : List OAI.CKSMixedGeometry.I, l.length ≤ j → |scaledIter l f y| ≤ B/(y 0)^q + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Finset + +abbrev Ix := Fin 3 + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial + +abbrev Ambient := EuclideanSpace ℝ (Fin 3) + +abbrev Sphere := ↥(Metric.sphere (0 : OAI.CKSSphericalHarmonics.Ambient) 1) + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial +open MeasureTheory + +abbrev surfaceMeasure : Measure OAI.CKSSphericalHarmonics.Sphere := (volume : Measure OAI.CKSSphericalHarmonics.Ambient).toSphere + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial +open MeasureTheory +open scoped Pointwise +open scoped Manifold ContDiff Topology +open Set + +def SmoothSphere (f : OAI.CKSSphericalHarmonics.Sphere → ℝ) : Prop := ContMDiff (𝓡 2) 𝓘(ℝ, ℝ) ∞ f + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz + + +local instance two_atLeastTwo : Nat.AtLeastTwo 2 := inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Set Filter Finset +open scoped Topology ContDiff + +abbrev E := EuclideanSpace ℝ OAI.CKSInducedSphere.Ix + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Set Filter Finset +open scoped Topology ContDiff +attribute [local instance] CKSLorentz.two_atLeastTwo + + +def e (i : OAI.CKSInducedSphere.Ix) : OAI.CKSInducedSphere.E := WithLp.toLp 2 (Pi.single i 1) + +def pd (i : OAI.CKSInducedSphere.Ix) (F : OAI.CKSInducedSphere.E → ℝ) (x : OAI.CKSInducedSphere.E) : ℝ := fderiv ℝ F x (OAI.CKSInducedSphere.e i) + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped InnerProductSpace RealInnerProductSpace ContDiff Manifold Topology +open Set + +abbrev E := EuclideanSpace ℝ (Fin 3) + +abbrev V := ℝ × OAI.CKSLorentz.E + +abbrev Sphere := ↥(Metric.sphere (0 : OAI.CKSLorentz.E) 1) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +local instance pointDimension_neZero : NeZero (3 : ℕ) := inferInstance + +def ordinaryLeadingComponent (q : ℕ) (M : OAI.CKSMixedGeometry.Angle → ℝ) (y : OAI.CKSMixedGeometry.Point) : ℝ := + letI := OAI.CKSLorentz.pointDimension_neZero + 1/(y 0)^q * M (OAI.CKSMixedGeometry.angularProjection y) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open Set +open scoped ContDiff + +structure SourceRemainderOn (j q : ℕ) (V : Set OAI.CKSMixedGeometry.Point) (f : OAI.CKSMixedGeometry.Point → ℝ) : Prop where + regular : ∀ y ∈ V, ContDiffAt ℝ j f y + bound : ∃ B : ℝ, 0 ≤ B ∧ ∀ y ∈ V, OAI.CKSMixedGeometry.ScaledComponentBound f j q B y + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure SourceCKSComponents (j qrad : ℕ) (V : Set OAI.CKSMixedGeometry.Point) + (A : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ) (mr : OAI.CKSMixedGeometry.Angle → ℝ) (mg : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ) : Prop where + radial : OAI.CKSMixedGeometry.SourceRemainderOn j qrad V (fun y => A 0 0 y-OAI.CKSLorentz.ordinaryLeadingComponent 5 mr y) + mixed : ∀ i k, (i=0 ∧ k≠0) ∨ (i≠0 ∧ k=0) → OAI.CKSMixedGeometry.SourceRemainderOn j 3 V (A i k) + angular : ∀ i k, i≠0 → k≠0 → OAI.CKSMixedGeometry.SourceRemainderOn j 2 V + (fun y => A i k y-OAI.CKSLorentz.ordinaryLeadingComponent 1 (mg i k) y) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set + +def angularRadialTail (R : ℝ) (W : Set OAI.CKSMixedGeometry.Angle) : Set OAI.CKSMixedGeometry.Point := + letI := OAI.CKSLorentz.pointDimension_neZero + {y | R < y 0 ∧ OAI.CKSMixedGeometry.angularProjection y ∈ W} + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure SmoothAngularPatch where + chart : OpenPartialHomeomorph OAI.CKSLorentz.Sphere OAI.CKSMixedGeometry.Angle + param_smooth : ContDiffOn ℝ ∞ (fun θ => (chart.symm θ : OAI.CKSLorentz.E)) chart.target + extension : OAI.CKSLorentz.E → OAI.CKSMixedGeometry.Angle + domain : Set OAI.CKSLorentz.E + isOpen_domain : IsOpen domain + extension_smooth : ContDiffOn ℝ ∞ extension domain + source_domain : ∀ n ∈ chart.source, (n:OAI.CKSLorentz.E) ∈ domain + extension_eq : ∀ n ∈ chart.source, extension n = chart n + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz.SmoothAngularPatch +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +def param (P : OAI.CKSLorentz.SmoothAngularPatch) (θ : OAI.CKSMixedGeometry.Angle) : OAI.CKSLorentz.E := P.chart.symm θ + +def sphereRegion (P : OAI.CKSLorentz.SmoothAngularPatch) (W : Set OAI.CKSMixedGeometry.Angle) : Set OAI.CKSLorentz.Sphere := + P.chart.source ∩ P.chart ⁻¹' W + +end OAI.CKSLorentz.SmoothAngularPatch +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure CKSTensorPatch where + patch : OAI.CKSLorentz.SmoothAngularPatch + region : Set OAI.CKSMixedGeometry.Angle + open_region : IsOpen region + region_target : region ⊆ patch.chart.target + radius : ℝ + metric : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ + second : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ + mr : OAI.CKSMixedGeometry.Angle → ℝ + mg : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ + mK : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ + mr_smooth : ContDiffOn ℝ ∞ mr region + mg_smooth : ∀ i k, i≠0 → k≠0 → ContDiffOn ℝ ∞ (mg i k) region + mK_smooth : ∀ i k, i≠0 → k≠0 → ContDiffOn ℝ ∞ (mK i k) region + metric_CKS : OAI.CKSLorentz.SourceCKSComponents 3 6 (OAI.CKSLorentz.angularRadialTail radius region) metric mr mg + second_CKS : OAI.CKSLorentz.SourceCKSComponents 2 5 (OAI.CKSLorentz.angularRadialTail radius region) second (fun _ => 0) mK + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice +attribute [local instance] real_continuousAdd + + +abbrev SpatialBilinear := + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_continuousConstSMul + OAI.CKSLorentz.E →L[ℝ] OAI.CKSLorentz.E →L[ℝ] ℝ + +abbrev SpatialTensor := OAI.CKSLorentz.E → OAI.CKSLorentz.SpatialBilinear + +local instance three_neZero : NeZero 3 := inferInstance + +def polarParam (P : OAI.CKSLorentz.SmoothAngularPatch) (y : OAI.CKSMixedGeometry.Point) : OAI.CKSLorentz.E := + letI := OAI.CKSLorentz.three_neZero + y 0 • P.param (OAI.CKSMixedGeometry.angularProjection y) + +def polarTensorComponents (P : OAI.CKSLorentz.SmoothAngularPatch) (A : OAI.CKSLorentz.SpatialTensor) + (i k : OAI.CKSMixedGeometry.I) (y : OAI.CKSMixedGeometry.Point) : ℝ := + A (OAI.CKSLorentz.polarParam P y) (fderiv ℝ (OAI.CKSLorentz.polarParam P) y (OAI.CKSMixedGeometry.basis i)) + (fderiv ℝ (OAI.CKSLorentz.polarParam P) y (OAI.CKSMixedGeometry.basis k)) + +def CKSTensorPatch.Realizes (Q : OAI.CKSLorentz.CKSTensorPatch) (A B : OAI.CKSLorentz.SpatialTensor) : Prop := + ∀ y ∈ OAI.CKSLorentz.angularRadialTail Q.radius Q.region, ∀ i k, + Q.metric i k y = OAI.CKSLorentz.polarTensorComponents Q.patch A i k y ∧ + Q.second i k y = OAI.CKSLorentz.polarTensorComponents Q.patch B i k y + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice CKSCalculus + +abbrev AngularMatrix := Matrix (Fin 2) (Fin 2) ℝ + +def angularMetricTrace (σ A : OAI.CKSLorentz.AngularMatrix) : ℝ := (σ⁻¹ * A).trace + +def angularRoundMetric (φ : OAI.CKSMixedGeometry.Angle → OAI.CKSLorentz.E) (θ : OAI.CKSMixedGeometry.Angle) : OAI.CKSLorentz.AngularMatrix := + letI := OAI.CKSLorentz.two_atLeastTwo + letI : Inner ℝ OAI.CKSLorentz.E := + @InnerProductSpace.toInner ℝ OAI.CKSLorentz.E _ + (PiLp.seminormedAddCommGroup 2 (fun _ : Fin 3 => ℝ)) + (PiLp.innerProductSpace (fun _ : Fin 3 => ℝ)) + fun a b => inner ℝ (fderiv ℝ φ θ (OAI.CKSAngularGeometry.basis a)) + (fderiv ℝ φ θ (OAI.CKSAngularGeometry.basis b)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped RealInnerProductSpace ContDiff Manifold Topology +open MeasureTheory +open CKSSphericalHarmonics (SmoothSphere surfaceMeasure) + +def nullDirection (n : OAI.CKSLorentz.Sphere) : OAI.CKSLorentz.V := (1,(n:OAI.CKSLorentz.E)) + +def rawCharge (M : OAI.CKSLorentz.Sphere → ℝ) : OAI.CKSLorentz.V := ∫ n : OAI.CKSLorentz.Sphere, M n • OAI.CKSLorentz.nullDirection n ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +def bondiCharge (M : OAI.CKSLorentz.Sphere → ℝ) : OAI.CKSLorentz.V := (16*Real.pi)⁻¹ • OAI.CKSLorentz.rawCharge M + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry + +local instance real_isTopologicalAddGroup : IsTopologicalAddGroup ℝ := inferInstance + +local instance spatialDual_isTopologicalAddGroup : IsTopologicalAddGroup (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_smulCommClass : + letI := OAI.CKSLorentz.real_smulCommClass + SMulCommClass ℝ ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_continuousConstSMul : ContinuousConstSMul ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_isScalarTower : IsScalarTower ℝ ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := inferInstance + +local instance spatialDual_continuousSMul : ContinuousSMul ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := inferInstance + +def hyperbolicField (x : OAI.CKSLorentz.E) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSLorentz.spatialDual_isTopologicalAddGroup + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + letI := OAI.CKSLorentz.spatialDual_isScalarTower + letI := OAI.CKSLorentz.spatialDual_continuousSMul + let f : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + f - (1/(1+‖x‖^2)) • (f x).smulRight (f x) + +def sourceSpatial (A : OAI.CKSLorentz.SpatialTensor) : OAI.CKSLorentz.SpatialTensor := fun x => OAI.CKSLorentz.hyperbolicField x + A x + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped ContDiff +attribute [local instance] CKSSpatialManifold.real_id_isometric real_smulCommClass spatialDual_smulCommClass + + +local instance hsgNorm : NormedAddCommGroup OAI.CKSLorentz.SpatialBilinear := + let dualSpace : NormedSpace ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E ℝ _ _ _ _ _ _ (RingHom.id ℝ) + OAI.CKSSpatialManifold.real_id_isometric ℝ _ _ OAI.CKSLorentz.real_smulCommClass + @ContinuousLinearMap.toNormedAddCommGroup ℝ ℝ OAI.CKSLorentz.E (OAI.CKSLorentz.E →L[ℝ] ℝ) + _ _ _ _ _ dualSpace (RingHom.id ℝ) OAI.CKSSpatialManifold.real_id_isometric + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped ContDiff +attribute [local instance] CKSSpatialManifold.real_id_isometric real_smulCommClass spatialDual_smulCommClass +attribute [local instance] OAI.CKSLorentz.hsgNorm + + +local instance hsgSpace : NormedSpace ℝ OAI.CKSLorentz.SpatialBilinear := + let dualSpace : NormedSpace ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E ℝ _ _ _ _ _ _ (RingHom.id ℝ) + OAI.CKSSpatialManifold.real_id_isometric ℝ _ _ OAI.CKSLorentz.real_smulCommClass + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E (OAI.CKSLorentz.E →L[ℝ] ℝ) + _ _ _ _ _ dualSpace (RingHom.id ℝ) OAI.CKSSpatialManifold.real_id_isometric + ℝ _ dualSpace OAI.CKSLorentz.spatialDual_smulCommClass + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSADM +open Finset CKSInducedSphere +open scoped RealInnerProductSpace ContDiff + +def normal (x : OAI.CKSInducedSphere.E) (i : OAI.CKSInducedSphere.Ix) : ℝ := x i / ‖x‖ + +end OAI.CKSADM +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSADM +open Set Filter Finset CKSSphericalHarmonics CKSInducedSphere +open scoped Topology ContDiff + +def spatialInfinity : Filter OAI.CKSInducedSphere.E := Filter.comap (fun x : OAI.CKSInducedSphere.E => ‖x‖) atTop + +def TailRegular (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + ∀ᶠ x in OAI.CKSADM.spatialInfinity, ContDiffAt ℝ ∞ F x + +def Decay (d : ℝ) (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ᶠ x in OAI.CKSADM.spatialInfinity, |F x| ≤ C*‖x‖^(-d) + +def SymbolN : ℕ → ℝ → (OAI.CKSInducedSphere.E → ℝ) → Prop + | 0, d, F => OAI.CKSADM.Decay d F + | n+1, d, F => OAI.CKSADM.Decay d F ∧ ∀ j : OAI.CKSInducedSphere.Ix, SymbolN n (d+1) (OAI.CKSInducedSphere.pd j F) + +def Symbol (d : ℝ) (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + OAI.CKSADM.TailRegular F ∧ ∀ n : ℕ, OAI.CKSADM.SymbolN n d F + +end OAI.CKSADM +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Matrix CKSCalculus Filter +open scoped BigOperators Topology ContDiff Matrix.Norms.Elementwise + +def physicalMetricJet (G : OAI.CKSAngularGeometry.PhysicalPoint → OAI.CKSAngularGeometry.AmbientMat) (x : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSRound.MetricJet where + inv := (G x)⁻¹ + d := fun a i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (fun y => G y i j) x + dd := fun a b i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis b) (fun y => G y i j)) x + +def physicalTensorJet (K : OAI.CKSAngularGeometry.PhysicalPoint → OAI.CKSAngularGeometry.AmbientMat) (x : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSRound.TensorJet where + val := K x + d := fun a i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (fun y => K y i j) x + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSCartesianOuter +open Set Filter Matrix CKSADM CKSInducedSphere CKSSphericalHarmonics +open CKSAngularGeometry (PhysicalPoint) +open scoped Topology ContDiff Matrix.Norms.Elementwise + +abbrev toPoint : OAI.CKSInducedSphere.E ≃L[ℝ] OAI.CKSAngularGeometry.PhysicalPoint := EuclideanSpace.equiv (Fin 3) ℝ + +end OAI.CKSCartesianOuter +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice CKSCalculus + +def cksChartMassAspect (φ : OAI.CKSMixedGeometry.Angle → OAI.CKSLorentz.E) (mr : OAI.CKSMixedGeometry.Angle → ℝ) + (mg mK : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ) (θ : OAI.CKSMixedGeometry.Angle) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + OAI.CKSLorentz.angularMetricTrace (OAI.CKSLorentz.angularRoundMetric φ θ) + (fun a b => mg a.succ b.succ θ + 2*mK a.succ b.succ θ) + 2*mr θ + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry + +def spatialCoefficients (A : OAI.CKSLorentz.SpatialTensor) (y : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSAngularGeometry.AmbientMat := + fun i j => A (OAI.CKSCartesianOuter.toPoint.symm y) + (OAI.CKSCartesianOuter.toPoint.symm (OAI.CKSMixedGeometry.basis i)) + (OAI.CKSCartesianOuter.toPoint.symm (OAI.CKSMixedGeometry.basis j)) + +def spatialDEC (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : Prop := + OAI.CKSLocalBending.DEC (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)) + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set + +def CKSTensorPatch.RepresentsMassAspect (Q : OAI.CKSLorentz.CKSTensorPatch) (M : OAI.CKSLorentz.Sphere → ℝ) : Prop := + ∀ n ∈ Q.patch.sphereRegion Q.region, + OAI.CKSLorentz.cksChartMassAspect Q.patch.param Q.mr Q.mg Q.mK (Q.patch.chart n) = M n + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry CKSInducedSphere CKSSphericalHarmonics MeasureTheory + +def spatialCartesian (A : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : OAI.CKSAngularGeometry.AmbientMat := + OAI.CKSLorentz.spatialCoefficients A (OAI.CKSCartesianOuter.toPoint x) + +local instance sixteen_atLeastTwo : Nat.AtLeastTwo 16 := inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry CKSInducedSphere CKSSphericalHarmonics MeasureTheory +attribute [local instance] sixteen_atLeastTwo + + +def spatialADMEnergy (A : OAI.CKSLorentz.SpatialTensor) (r : ℝ) : ℝ := + r^2/(16*Real.pi) * ∫ n : OAI.CKSLorentz.Sphere, + ∑ i : Fin 3, (∑ j : Fin 3, + (OAI.CKSInducedSphere.pd j (fun y => OAI.CKSLorentz.spatialCartesian A y i j) (r • (n:OAI.CKSLorentz.E)) - + OAI.CKSInducedSphere.pd i (fun y => OAI.CKSLorentz.spatialCartesian A y j j) (r • (n:OAI.CKSLorentz.E)))) * + OAI.CKSADM.normal (r • (n:OAI.CKSLorentz.E)) i ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +def spatialADMMomentum (A B : OAI.CKSLorentz.SpatialTensor) (r : ℝ) : Fin 3 → ℝ := fun i => + r^2/(8*Real.pi) * ∫ n : OAI.CKSLorentz.Sphere, + ∑ j : Fin 3, (OAI.CKSLorentz.spatialCartesian B (r • (n:OAI.CKSLorentz.E)) i j - + (∑ a : Fin 3, ∑ b : Fin 3, + (OAI.CKSLorentz.spatialCartesian A (r • (n:OAI.CKSLorentz.E)))⁻¹ a b * OAI.CKSLorentz.spatialCartesian B (r • (n:OAI.CKSLorentz.E)) a b) * + OAI.CKSLorentz.spatialCartesian A (r • (n:OAI.CKSLorentz.E)) i j) * OAI.CKSADM.normal (r • (n:OAI.CKSLorentz.E)) j ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry MeasureTheory + +def spatialEnergy (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : ℝ := + (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)).energy + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSReplacementCompleteness +open Bundle Manifold +open scoped Bundle Manifold ENNReal +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_2} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_3} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric E (fun x : M => TangentSpace I x) + +local instance metric_isContinuousRiemannianBundle (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : + letI : RiemannianBundle (fun x : M => TangentSpace I x) := ⟨g.toRiemannianMetric⟩ + IsContinuousRiemannianBundle E (fun x : M => TangentSpace I x) := inferInstance + +@[instance_reducible] def metricSpace [T3Space M] (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : EMetricSpace M := + letI : RiemannianBundle (fun x : M => TangentSpace I x) := ⟨g.toRiemannianMetric⟩ + letI := OAI.CKSReplacementCompleteness.metric_isContinuousRiemannianBundle I g + EMetricSpace.ofRiemannianMetric I M + +def IsComplete [T3Space M] (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : Prop := + @CompleteSpace M (OAI.CKSReplacementCompleteness.metricSpace I g).toUniformSpace + +end OAI.CKSReplacementCompleteness +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSGeometricCuts +open Set Manifold MeasureTheory Bundle CKSReplacementCompleteness +open scoped ENNReal Manifold Bundle ContDiff + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero + +end OAI.CKSGeometricCuts +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSGeometricCuts +open Set Manifold MeasureTheory Bundle CKSReplacementCompleteness +open scoped ENNReal Manifold Bundle ContDiff +variable (M : Type u) [TopologicalSpace M] [ChartedSpace H3 M] [IsManifold I3 1 M] + +structure OuterDomain where + Carrier : Type u + topology : TopologicalSpace Carrier + charts : @ChartedSpace OAI.CKSGeometricCuts.H3 _ Carrier topology + smooth : @IsManifold ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 (∞ : ℕ∞ω) Carrier topology charts + inclusion : Carrier → M + embedding : @IsSmoothEmbedding ℝ _ OAI.CKSGeometricCuts.E3 OAI.CKSGeometricCuts.E3 _ _ _ _ OAI.CKSGeometricCuts.H3 OAI.CKSGeometricCuts.H3 _ _ OAI.CKSGeometricCuts.I3 OAI.CKSGeometricCuts.I3 + Carrier M topology charts _ _ ∞ inclusion + closed : IsClosed (range inclusion) + connected : IsConnected (range inclusion) + contains_distant_end : ∃ K : Set M, IsCompact K ∧ Kᶜ ⊆ range inclusion + interior_into : inclusion '' (@ModelWithCorners.interior ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 + Carrier topology charts) ⊆ OAI.CKSGeometricCuts.I3.interior M + compact_boundary : IsCompact (inclusion '' (@ModelWithCorners.boundary ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 + Carrier topology charts)) + +end OAI.CKSGeometricCuts +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Bornology Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_id_isometric CKSMetricGluing.real_continuousAdd CKSMetricGluing.real_continuousConstSMul CKSMetricGluing.real_smulCommClass + + +local instance real_id_compTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Bornology Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type u_1} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_2} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_id_isometric CKSMetricGluing.real_continuousAdd CKSMetricGluing.real_continuousConstSMul CKSMetricGluing.real_smulCommClass + + +def endInner (f : M → OAI.CKSLorentz.E) (A : OAI.CKSLorentz.SpatialTensor) : OAI.CKSMetricGluing.InnerField I (M := M) := fun x => by + letI := OAI.CKSSpatialManifold.real_id_isometric + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI : NormedAddCommGroup (TangentSpace I x) := by unfold TangentSpace; infer_instance + letI : NormedSpace ℝ (TangentSpace I x) := by unfold TangentSpace; infer_instance + let df : TangentSpace I x →L[ℝ] OAI.CKSLorentz.E := + (NormedSpace.fromTangentSpace (f x)).toContinuousLinearMap.comp (mfderiv I 𝓘(ℝ,OAI.CKSLorentz.E) f x) + exact (A (f x)).bilinearComp df df + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type u_1} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_2} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] CKSLorentz.hsgNorm CKSLorentz.hsgSpace + + +def PhysicalDECAt (g : OAI.CKSMetricGluing.InnerField I (M := M)) (K : OAI.CKSMetricGluing.InnerField I (M := M)) (x : M) : Prop := + ∃ (V : Set M) (f : M → OAI.CKSLorentz.E) (A B : OAI.CKSLorentz.SpatialTensor), + IsOpen V ∧ x ∈ V ∧ ContMDiffOn I 𝓘(ℝ,OAI.CKSLorentz.E) ∞ f V ∧ + (∀ y ∈ V, Function.Bijective (mfderiv I 𝓘(ℝ,OAI.CKSLorentz.E) f y)) ∧ + (∀ y ∈ V, ContDiffAt ℝ ∞ A (f y) ∧ ContDiffAt ℝ ∞ B (f y)) ∧ + (∀ y ∈ V, (∀ v w, A (f y) v w = A (f y) w v) ∧ + (∀ v : OAI.CKSLorentz.E, v ≠ 0 → 0 < A (f y) v v) ∧ + (∀ v w, B (f y) v w = B (f y) w v)) ∧ + (∀ y ∈ V, g y = OAI.CKSSpatialManifold.endInner I f A y ∧ K y = OAI.CKSSpatialManifold.endInner I f B y) ∧ + OAI.CKSLorentz.spatialDEC A B (f x) + +def PhysicalDEC (g : OAI.CKSMetricGluing.InnerField I (M := M)) (K : OAI.CKSMetricGluing.InnerField I (M := M)) : Prop := + ∀ x : M, OAI.CKSSpatialManifold.PhysicalDECAt I g K x + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicGeometry +open Bundle Bornology Set MeasureTheory Manifold Filter Metric +open scoped ENNReal ContDiff Topology NNReal + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSIntrinsicGeometry.halfSpaceDimension_neZero + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicGeometry.halfSpaceDimension_neZero + +end OAI.CKSIntrinsicGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology + +abbrev E2 := EuclideanSpace ℝ (Fin 2) + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero + +abbrev I2 := 𝓘(ℝ,OAI.CKSBoundarySurface.E2) + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero + +local instance two_atLeastTwo : Nat.AtLeastTwo 2 := inferInstance + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] two_atLeastTwo + + +def insertNormalZero (point : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.E3 := WithLp.toLp 2 (Fin.cons 0 point) + +def liftPlane : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3 := + have proof_insertNormalZero_add_0 (first second : OAI.CKSBoundarySurface.E2) : + OAI.CKSBoundarySurface.insertNormalZero (first + second) = OAI.CKSBoundarySurface.insertNormalZero first + OAI.CKSBoundarySurface.insertNormalZero second := by + ext index + cases index using Fin.cases <;> simp [OAI.CKSBoundarySurface.insertNormalZero] + have proof_insertNormalZero_smul_1 (scalar : ℝ) (point : OAI.CKSBoundarySurface.E2) : + OAI.CKSBoundarySurface.insertNormalZero (scalar • point) = scalar • OAI.CKSBoundarySurface.insertNormalZero point := by + ext index + cases index using Fin.cases <;> simp [OAI.CKSBoundarySurface.insertNormalZero] + have proof_insertNormalZero_continuous_2 : Continuous OAI.CKSBoundarySurface.insertNormalZero := by + apply (PiLp.continuous_toLp 2 (fun _ : Fin 3 => ℝ)).comp + apply continuous_pi + intro index + cases index using Fin.cases with + | zero => exact continuous_const + | succ index => exact PiLp.continuous_apply 2 (fun _ : Fin 2 => ℝ) index + { + toFun := OAI.CKSBoundarySurface.insertNormalZero + map_add' := proof_insertNormalZero_add_0 + map_smul' := proof_insertNormalZero_smul_1 + cont := proof_insertNormalZero_continuous_2 + } + +def tangentialCoordinates (point : OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := WithLp.toLp 2 (fun index => point index.succ) + +def dropPlane : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E2 := + have proof_tangentialCoordinates_add_3 (first second : OAI.CKSBoundarySurface.E3) : + OAI.CKSBoundarySurface.tangentialCoordinates (first + second) = + OAI.CKSBoundarySurface.tangentialCoordinates first + OAI.CKSBoundarySurface.tangentialCoordinates second := by + ext index + simp [OAI.CKSBoundarySurface.tangentialCoordinates] + have proof_tangentialCoordinates_smul_4 (scalar : ℝ) (point : OAI.CKSBoundarySurface.E3) : + OAI.CKSBoundarySurface.tangentialCoordinates (scalar • point) = scalar • OAI.CKSBoundarySurface.tangentialCoordinates point := by + ext index + simp [OAI.CKSBoundarySurface.tangentialCoordinates] + have proof_tangentialCoordinates_continuous_5 : Continuous OAI.CKSBoundarySurface.tangentialCoordinates := by + apply (PiLp.continuous_toLp 2 (fun _ : Fin 2 => ℝ)).comp + exact continuous_pi fun index => PiLp.continuous_apply 2 (fun _ : Fin 3 => ℝ) index.succ + { + toFun := OAI.CKSBoundarySurface.tangentialCoordinates + map_add' := proof_tangentialCoordinates_add_3 + map_smul' := proof_tangentialCoordinates_smul_4 + cont := proof_tangentialCoordinates_continuous_5 + } + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology + +def liftHalf (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.H3 := + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + ⟨OAI.CKSBoundarySurface.liftPlane z, by simp [*]⟩ + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface + +abbrev Radial := {t : ℝ // 0 ≤ t} + +abbrev Sphere := Metric.sphere (0 : OAI.CKSBoundarySurface.E3) 1 + +abbrev Exterior := OAI.CKSSchwarzschild.Radial × OAI.CKSSchwarzschild.Sphere + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface +attribute [local instance] Classical.propDecidable + + +local instance real_id_invPair : RingHomInvPair (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +def join : (ℝ × OAI.CKSBoundarySurface.E2) →L[ℝ] OAI.CKSBoundarySurface.E3 := + letI := OAI.CKSSchwarzschild.real_id_invPair + letI := OAI.CKSBoundarySurface.two_atLeastTwo + let continuousLinearMap : ((ℝ × OAI.CKSBoundarySurface.E2) →ₗ[ℝ] OAI.CKSBoundarySurface.E3) ≃ₗ[ℝ] ((ℝ × OAI.CKSBoundarySurface.E2) →L[ℝ] OAI.CKSBoundarySurface.E3) := + LinearMap.toContinuousLinearMap + continuousLinearMap { + toFun := fun z => WithLp.toLp 2 (Fin.cons z.1 z.2) + map_add' := by intro a b; ext i; cases i using Fin.cases <;> simp + map_smul' := by intro a b; ext i; cases i using Fin.cases <;> simp } + +def halfProduct : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2 ≃ₜ OAI.CKSBoundarySurface.H3 := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_join_drop_8 (z : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.join (z 0,OAI.CKSBoundarySurface.dropPlane z) = z := by + ext i; cases i using Fin.cases <;> rfl + have proof_drop_join_11 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSSchwarzschild.join z) = z.2 := by ext i; rfl + letI := OAI.CKSBoundarySurface.halfSpaceDimension_neZero + { toFun z := ⟨OAI.CKSSchwarzschild.join (z.1.val,z.2),z.1.property⟩ + invFun z := (⟨z.val 0,z.property⟩,OAI.CKSBoundarySurface.dropPlane z.val) + left_inv z := by cases z; simp [*] + right_inv z := by apply Subtype.ext; exact proof_join_drop_8 _ + continuous_toFun := (OAI.CKSSchwarzschild.join.continuous.comp + ((continuous_subtype_val.comp continuous_fst).prodMk continuous_snd)).subtype_mk _ + continuous_invFun := ((by fun_prop : Continuous (fun z : H3 => z.val 0)).subtype_mk _).prodMk + (OAI.CKSBoundarySurface.dropPlane.continuous.comp continuous_subtype_val) } + +def productChart (s : OAI.CKSSchwarzschild.Sphere) : OpenPartialHomeomorph OAI.CKSSchwarzschild.Exterior OAI.CKSBoundarySurface.H3 := + ((OpenPartialHomeomorph.refl OAI.CKSSchwarzschild.Radial).prod (chartAt OAI.CKSBoundarySurface.E2 s)).trans OAI.CKSSchwarzschild.halfProduct.toOpenPartialHomeomorph + +instance exteriorChartedSpace : ChartedSpace OAI.CKSBoundarySurface.H3 OAI.CKSSchwarzschild.Exterior := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_halfProduct_val_12 (z : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2) : (OAI.CKSSchwarzschild.halfProduct z).val = OAI.CKSSchwarzschild.join (z.1.val,z.2) := rfl + have proof_halfProduct_symm_fst_13 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).1.val = z.val 0 := rfl + have proof_halfProduct_symm_snd_14 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).2 = OAI.CKSBoundarySurface.dropPlane z.val := rfl + { + atlas := range OAI.CKSSchwarzschild.productChart + chartAt p := OAI.CKSSchwarzschild.productChart p.2 + mem_chart_source p := by simp [*, OAI.CKSSchwarzschild.productChart,mem_chart_source OAI.CKSBoundarySurface.E2 p.2] + chart_mem_atlas p := mem_range_self _ + } + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface +attribute [local instance] halfSpaceDimension_neZero + + +instance exteriorIsManifold : IsManifold OAI.CKSBoundarySurface.I3 ∞ OAI.CKSSchwarzschild.Exterior := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_halfProduct_val_12 (z : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2) : (OAI.CKSSchwarzschild.halfProduct z).val = OAI.CKSSchwarzschild.join (z.1.val,z.2) := rfl + have proof_halfProduct_symm_fst_13 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).1.val = z.val 0 := rfl + have proof_halfProduct_symm_snd_14 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).2 = OAI.CKSBoundarySurface.dropPlane z.val := rfl + have proof_productChart_target_17 (s : OAI.CKSSchwarzschild.Sphere) : + (OAI.CKSSchwarzschild.productChart s).target = (fun z : OAI.CKSBoundarySurface.H3 => OAI.CKSBoundarySurface.dropPlane z.val) ⁻¹' (chartAt OAI.CKSBoundarySurface.E2 s).target := by + ext p; simp [*, OAI.CKSSchwarzschild.productChart] + have proof_productChart_source_18 (s : OAI.CKSSchwarzschild.Sphere) : + (OAI.CKSSchwarzschild.productChart s).source = Prod.snd ⁻¹' (chartAt OAI.CKSBoundarySurface.E2 s).source := by + ext p; simp [*, OAI.CKSSchwarzschild.productChart] + have proof_productChart_symm_19 (s : OAI.CKSSchwarzschild.Sphere) (z : OAI.CKSBoundarySurface.H3) : + (OAI.CKSSchwarzschild.productChart s).symm z = (⟨z.val 0,z.property⟩,(chartAt OAI.CKSBoundarySurface.E2 s).symm (OAI.CKSBoundarySurface.dropPlane z.val)) := rfl + have proof_transition_source_20 (a b : OAI.CKSSchwarzschild.Sphere) : + ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source = + (fun z : OAI.CKSBoundarySurface.H3 => OAI.CKSBoundarySurface.dropPlane z.val) ⁻¹' ((chartAt OAI.CKSBoundarySurface.E2 a).symm ≫ₕ chartAt OAI.CKSBoundarySurface.E2 b).source := by + ext z + simp only [OpenPartialHomeomorph.trans_source,OpenPartialHomeomorph.symm_source, + mem_inter_iff,mem_preimage,proof_productChart_target_17,proof_productChart_source_18,proof_productChart_symm_19] + have proof_transition_maps_15 (a b : OAI.CKSSchwarzschild.Sphere) : + MapsTo OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm ⁻¹' ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source ∩ range OAI.CKSBoundarySurface.I3) + ((extChartAt OAI.CKSBoundarySurface.I2 a).symm ≫ extChartAt OAI.CKSBoundarySurface.I2 b).source := by + intro z hz + have he : (OAI.CKSBoundarySurface.I3.symm z).val = z := OAI.CKSBoundarySurface.I3.right_inv hz.2 + have h := hz.1 + rw [proof_transition_source_20] at h + change OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm z).val ∈ ((chartAt OAI.CKSBoundarySurface.E2 a).symm ≫ₕ chartAt OAI.CKSBoundarySurface.E2 b).source at h + rw [he] at h + simpa only [OAI.CKSBoundarySurface.I2,extChartAt_model_space_eq_id,mfld_simps] using h + have proof_transition_formula_16 (a b : OAI.CKSSchwarzschild.Sphere) {z : OAI.CKSBoundarySurface.E3} (hz : z ∈ range OAI.CKSBoundarySurface.I3) : + OAI.CKSBoundarySurface.I3 (((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b) (OAI.CKSBoundarySurface.I3.symm z)) = + OAI.CKSSchwarzschild.join (z 0,((extChartAt OAI.CKSBoundarySurface.I2 a).symm ≫ extChartAt OAI.CKSBoundarySurface.I2 b) (OAI.CKSBoundarySurface.dropPlane z)) := by + have he : (OAI.CKSBoundarySurface.I3.symm z).val = z := OAI.CKSBoundarySurface.I3.right_inv hz + change OAI.CKSSchwarzschild.join ((OAI.CKSBoundarySurface.I3.symm z).val 0, + chartAt OAI.CKSBoundarySurface.E2 b ((chartAt OAI.CKSBoundarySurface.E2 a).symm (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm z).val))) = _ + rw [he] + rfl + by + apply isManifold_of_contDiffOn + rintro e e' ⟨a,rfl⟩ ⟨b,rfl⟩ + change ContDiffOn ℝ ∞ + (fun z => OAI.CKSBoundarySurface.I3 (((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b) (OAI.CKSBoundarySurface.I3.symm z))) + (OAI.CKSBoundarySurface.I3.symm ⁻¹' ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source ∩ range OAI.CKSBoundarySurface.I3) + have hs := (contDiffOn_ext_coord_change (I := OAI.CKSBoundarySurface.I2) (n := ∞) b a).comp + OAI.CKSBoundarySurface.dropPlane.contDiff.contDiffOn (proof_transition_maps_15 a b) + have h0 : ContDiff ℝ ∞ (fun z : OAI.CKSBoundarySurface.E3 => z 0) := by fun_prop + apply (OAI.CKSSchwarzschild.join.contDiff.comp_contDiffOn (h0.contDiffOn.prodMk hs)).congr + intro z hz + exact proof_transition_formula_16 a b hz.2 + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology +open CKSBoundarySurface + +def height (p : OAI.CKSSchwarzschild.Exterior) : ℝ := p.1.val + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle Function +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + + +def radius (m : ℝ) (p : OAI.CKSSchwarzschild.Exterior) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 2*m+OAI.CKSSchwarzschild.height p + +def directionAmbient (p : OAI.CKSSchwarzschild.Exterior) : OAI.CKSBoundarySurface.E3 := p.2.val + +def position (m : ℝ) (p : OAI.CKSSchwarzschild.Exterior) : OAI.CKSBoundarySurface.E3 := OAI.CKSSchwarzschild.radius m p • OAI.CKSSchwarzschild.directionAmbient p + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter +open scoped ContDiff Topology + +def velocity (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo; + -1 + (r+1)*Real.smoothTransition (r-2*m-1) + +def lapseSquared (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 1-2*m/r+(OAI.CKSSchwarzschild.velocity m r)^2 + +def lapse (m r : ℝ) : ℝ := Real.sqrt (OAI.CKSSchwarzschild.lapseSquared m r) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Manifold Bundle Set Filter CKSLorentz CKSMetricGluing CKSSpatialManifold +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +def euclideanForm : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + +def radialUnit (x : OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E3 := ‖x‖⁻¹ • x + +local instance real_isScalarTower : IsScalarTower ℝ ℝ ℝ := inferInstance + +def radialForm (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI := OAI.CKSSpatialManifold.real_id_isometric + letI := OAI.CKSSchwarzschild.real_isScalarTower + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + let innerForm : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + (ContinuousLinearMap.mul ℝ ℝ).bilinearComp + (innerForm (OAI.CKSSchwarzschild.radialUnit x)) (innerForm (OAI.CKSSchwarzschild.radialUnit x)) + +local instance spatialDual_continuousAdd : ContinuousAdd (OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) := inferInstance + +def cartMetric (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSSchwarzschild.spatialDual_continuousAdd + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + OAI.CKSSchwarzschild.euclideanForm + ((OAI.CKSSchwarzschild.lapseSquared m ‖x‖)⁻¹-1) • OAI.CKSSchwarzschild.radialForm x + +def cartTensor (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSSchwarzschild.spatialDual_continuousAdd + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + (OAI.CKSSchwarzschild.velocity m ‖x‖ / ‖x‖) • OAI.CKSSchwarzschild.euclideanForm + + (deriv (OAI.CKSSchwarzschild.velocity m) ‖x‖ / OAI.CKSSchwarzschild.lapseSquared m ‖x‖ - OAI.CKSSchwarzschild.velocity m ‖x‖ / ‖x‖) • OAI.CKSSchwarzschild.radialForm x + +def metricInner (m : ℝ) : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior) := OAI.CKSSpatialManifold.endInner OAI.CKSBoundarySurface.I3 (OAI.CKSSchwarzschild.position m) (OAI.CKSSchwarzschild.cartMetric m) + +def tensorInner (m : ℝ) : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior) := OAI.CKSSpatialManifold.endInner OAI.CKSBoundarySurface.I3 (OAI.CKSSchwarzschild.position m) (OAI.CKSSchwarzschild.cartTensor m) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology + +abbrev E := OAI.CKSLorentz.E + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology +attribute [local instance] halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +def coordinateMomentumNorm (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSIntrinsicConstraints.E) : ℝ := + Real.sqrt (OAI.CKSLocalBending.momentumSq + (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)) + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x))) + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology +attribute [local instance] halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +structure ConstraintChart (g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)) (x : M) where + domain : Set M + coordinate : M → OAI.CKSIntrinsicConstraints.E + metric : OAI.CKSLorentz.SpatialTensor + tensor : OAI.CKSLorentz.SpatialTensor + isOpen : IsOpen domain + mem : x ∈ domain + smooth : ContMDiffOn OAI.CKSIntrinsicConstraints.I 𝓘(ℝ,OAI.CKSIntrinsicConstraints.E) ∞ coordinate domain + fullRank : ∀ y ∈ domain, Function.Bijective (mfderiv OAI.CKSIntrinsicConstraints.I 𝓘(ℝ,OAI.CKSIntrinsicConstraints.E) coordinate y) + coefficientSmooth : + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.spatialDual_smulCommClass + ∀ y ∈ domain, + ContDiffAt ℝ ∞ metric (coordinate y) ∧ ContDiffAt ℝ ∞ tensor (coordinate y) + positiveSymmetric : ∀ y ∈ domain, + (∀ v w, metric (coordinate y) v w = metric (coordinate y) w v) ∧ + (∀ v : OAI.CKSIntrinsicConstraints.E, v ≠ 0 → 0 < metric (coordinate y) v v) ∧ + (∀ v w, tensor (coordinate y) v w = tensor (coordinate y) w v) + represents : ∀ y ∈ domain, + g y = OAI.CKSSpatialManifold.endInner OAI.CKSIntrinsicConstraints.I coordinate metric y ∧ + K y = OAI.CKSSpatialManifold.endInner OAI.CKSIntrinsicConstraints.I coordinate tensor y + +def ConstraintChart.energy {g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)} {x : M} + (c : OAI.CKSIntrinsicConstraints.ConstraintChart g K x) : ℝ := OAI.CKSLorentz.spatialEnergy c.metric c.tensor (c.coordinate x) + +def ConstraintChart.momentumNorm {g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)} {x : M} + (c : OAI.CKSIntrinsicConstraints.ConstraintChart g K x) : ℝ := OAI.CKSIntrinsicConstraints.coordinateMomentumNorm c.metric c.tensor (c.coordinate x) + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero + + +abbrev E := EuclideanSpace ℝ (Fin 3) + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev basis (i : Fin 3) : OAI.CKSIntrinsicVolume.E := EuclideanSpace.single i 1 + +local instance model_finiteDimensional : FiniteDimensional ℝ OAI.CKSIntrinsicVolume.E := inferInstance + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +attribute [local instance] model_finiteDimensional + + +local instance model_borelSpace : BorelSpace OAI.CKSIntrinsicVolume.E := inferInstance + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric OAI.CKSIntrinsicVolume.E (fun x : M => TangentSpace OAI.CKSIntrinsicVolume.I x) + +def chartFrame (x : M) (y : OAI.CKSIntrinsicVolume.E) : OAI.CKSIntrinsicVolume.E →L[ℝ] TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) := + mfderivWithin 𝓘(ℝ,OAI.CKSIntrinsicVolume.E) OAI.CKSIntrinsicVolume.I (extChartAt OAI.CKSIntrinsicVolume.I x).symm (range OAI.CKSIntrinsicVolume.I) y + +def chartMatrix (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) (y : OAI.CKSIntrinsicVolume.E) : Matrix (Fin 3) (Fin 3) ℝ := + letI := OAI.CKSMetricGluing.real_continuousAdd + letI := OAI.CKSMetricGluing.real_continuousConstSMul + letI := OAI.CKSMetricGluing.real_smulCommClass + let form : TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) →L[ℝ] + TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) →L[ℝ] ℝ := + g.inner ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) + fun first second => form (OAI.CKSIntrinsicVolume.chartFrame x y (OAI.CKSIntrinsicVolume.basis first)) (OAI.CKSIntrinsicVolume.chartFrame x y (OAI.CKSIntrinsicVolume.basis second)) + +def chartDensity (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) (y : OAI.CKSIntrinsicVolume.E) : ℝ := + Real.sqrt (OAI.CKSIntrinsicVolume.chartMatrix g x y).det + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] +attribute [local instance] model_finiteDimensional model_borelSpace +variable [MeasurableSpace M] [BorelSpace M] + +def localVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) : Measure M := + Measure.map (extChartAt OAI.CKSIntrinsicVolume.I x).symm + ((volume.restrict (extChartAt OAI.CKSIntrinsicVolume.I x).target).withDensity + (fun y => ENNReal.ofReal (OAI.CKSIntrinsicVolume.chartDensity g x y))) + +def IsVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (ν : Measure M) : Prop := + ∀ x : M, ν.restrict (extChartAt OAI.CKSIntrinsicVolume.I x).source = OAI.CKSIntrinsicVolume.localVolume g x + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] +variable [IsManifold I 1 M] + +def riemannianVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) : Measure M := Classical.epsilon (fun ν => OAI.CKSIntrinsicVolume.IsVolume g ν) + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] Classical.propDecidable +variable {M : Type u_2} [TopologicalSpace M] [ChartedSpace H3 M] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 halfSpaceDimension_neZero) I3 ∞ M _ _] + +abbrev Boundary (M : Type u_2) [TopologicalSpace M] [ChartedSpace OAI.CKSBoundarySurface.H3 M] := + @ModelWithCorners.boundary ℝ _ OAI.CKSBoundarySurface.E3 _ _ OAI.CKSBoundarySurface.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero) OAI.CKSBoundarySurface.I3 M _ _ + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] Classical.propDecidable +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H3 M] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 halfSpaceDimension_neZero) I3 ∞ M _ _] + +def boundaryInverse (x : OAI.CKSBoundarySurface.Boundary M) (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.Boundary M := + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + if hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target then + ⟨(chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z),proof_boundaryInverse_mem_21 x hz⟩ else x + +def boundaryChart (x : OAI.CKSBoundarySurface.Boundary M) : OpenPartialHomeomorph (OAI.CKSBoundarySurface.Boundary M) OAI.CKSBoundarySurface.E2 := + have proof_lift_drop_30 {z : OAI.CKSBoundarySurface.E3} (hz : z 0 = 0) : OAI.CKSBoundarySurface.liftPlane (OAI.CKSBoundarySurface.dropPlane z) = z := by + ext i + cases i using Fin.cases with + | zero => exact hz.symm + | succ i => rfl + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_liftHalf_drop_chart_26 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) (y : OAI.CKSBoundarySurface.Boundary M) (hy : y.val ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + OAI.CKSBoundarySurface.liftHalf (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y.val))) = chartAt OAI.CKSBoundarySurface.H3 x y.val := by + apply Subtype.ext + exact proof_lift_drop_30 ((proof_boundary_iff_zero_24 x y.val hy).mp y.property) + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + have proof_boundaryInverse_val_27 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_dropPlane_apply_31 (z : OAI.CKSBoundarySurface.E3) (i : Fin 2) : OAI.CKSBoundarySurface.dropPlane z i = z i.succ := rfl + have proof_drop_lift_28 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane z) = z := by ext i; rfl + have proof_liftHalf_continuous_29 : Continuous OAI.CKSBoundarySurface.liftHalf := + OAI.CKSBoundarySurface.liftPlane.continuous.subtype_mk (fun _ => by simp [*]) + { + toFun y := OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val y.val)) + invFun := OAI.CKSBoundarySurface.boundaryInverse x + source := Subtype.val ⁻¹' (chartAt OAI.CKSBoundarySurface.H3 x.val).source + target := OAI.CKSBoundarySurface.liftHalf ⁻¹' (chartAt OAI.CKSBoundarySurface.H3 x.val).target + map_source' := by + intro y hy + change OAI.CKSBoundarySurface.liftHalf (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val y.val))) ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target + rw [proof_liftHalf_drop_chart_26 x.val y hy] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_source hy + map_target' := by + intro z hz + change (OAI.CKSBoundarySurface.boundaryInverse x z).val ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).source + rw [proof_boundaryInverse_val_27 x hz] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_target hz + left_inv' := by + intro y hy + have h := proof_liftHalf_drop_chart_26 x.val y hy + apply Subtype.ext + rw [proof_boundaryInverse_val_27 x (by rw [h]; exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_source hy),h] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).left_inv hy + right_inv' := by + intro z hz + rw [proof_boundaryInverse_val_27 x hz,(chartAt OAI.CKSBoundarySurface.H3 x.val).right_inv hz,proof_I3_liftHalf_23,proof_drop_lift_28] + open_source := (chartAt OAI.CKSBoundarySurface.H3 x.val).open_source.preimage continuous_subtype_val + open_target := (chartAt OAI.CKSBoundarySurface.H3 x.val).open_target.preimage proof_liftHalf_continuous_29 + continuousOn_toFun := OAI.CKSBoundarySurface.dropPlane.continuous.comp_continuousOn + (OAI.CKSBoundarySurface.I3.continuous.comp_continuousOn ((chartAt OAI.CKSBoundarySurface.H3 x.val).continuousOn.comp + continuous_subtype_val.continuousOn (fun _ h => h))) + continuousOn_invFun := by + apply Topology.IsInducing.subtypeVal.continuousOn_iff.mpr + apply ((chartAt OAI.CKSBoundarySurface.H3 x.val).continuousOn_symm.comp + proof_liftHalf_continuous_29.continuousOn (fun _ h => h)).congr + intro z hz + exact proof_boundaryInverse_val_27 x hz + } + +instance boundaryChartedSpace : ChartedSpace OAI.CKSBoundarySurface.E2 (OAI.CKSBoundarySurface.Boundary M) where + atlas := range OAI.CKSBoundarySurface.boundaryChart + chartAt := OAI.CKSBoundarySurface.boundaryChart + mem_chart_source x := mem_chart_source OAI.CKSBoundarySurface.H3 x.val + chart_mem_atlas x := mem_range_self x + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter Function +open scoped ContDiff Topology +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H3 M] [IsManifold I3 ∞ M] + +instance boundaryIsManifold : IsManifold OAI.CKSBoundarySurface.I2 ∞ (OAI.CKSBoundarySurface.Boundary M) := + have proof_lift_mem_ext_target_34 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] [IsManifold OAI.CKSBoundarySurface.I3 ∞ M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + OAI.CKSBoundarySurface.liftPlane z ∈ (extChartAt OAI.CKSBoundarySurface.I3 x).target := by + change OAI.CKSBoundarySurface.liftPlane z ∈ ((chartAt OAI.CKSBoundarySurface.H3 x).extend OAI.CKSBoundarySurface.I3).target + rw [OpenPartialHomeomorph.extend_target'] + exact ⟨OAI.CKSBoundarySurface.liftHalf z,hz,rfl⟩ + have proof_ext_symm_lift_35 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] [IsManifold OAI.CKSBoundarySurface.I3 ∞ M] (x : M) (z : OAI.CKSBoundarySurface.E2) : + (extChartAt OAI.CKSBoundarySurface.I3 x).symm (OAI.CKSBoundarySurface.liftPlane z) = (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) := by + change (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.I3.symm (OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z))) = _ + rw [OAI.CKSBoundarySurface.I3.left_inv] + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + have proof_boundaryInverse_val_27 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_boundaryChart_symm_val_36 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := + proof_boundaryInverse_val_27 x hz + have proof_transition_lift_maps_32 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : OAI.CKSBoundarySurface.Boundary M) : + MapsTo OAI.CKSBoundarySurface.liftPlane ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source + ((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm ≫ extChartAt OAI.CKSBoundarySurface.I3 y.val).source := by + intro z hz + change z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target ∧ (OAI.CKSBoundarySurface.boundaryChart x).symm z ∈ (OAI.CKSBoundarySurface.boundaryChart y).source at hz + refine ⟨proof_lift_mem_ext_target_34 x.val hz.1, ?_⟩ + change (extChartAt OAI.CKSBoundarySurface.I3 x.val).symm (OAI.CKSBoundarySurface.liftPlane z) ∈ (extChartAt OAI.CKSBoundarySurface.I3 y.val).source + rw [proof_ext_symm_lift_35] + have h := hz.2 + change ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val ∈ (chartAt OAI.CKSBoundarySurface.H3 y.val).source at h + rw [proof_boundaryChart_symm_val_36 x hz.1] at h + simpa only [extChartAt_source] using h + have proof_transition_formula_33 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : z ∈ ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y) z = + OAI.CKSBoundarySurface.dropPlane (((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm ≫ extChartAt OAI.CKSBoundarySurface.I3 y.val) (OAI.CKSBoundarySurface.liftPlane z)) := by + change OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 y.val ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val)) = _ + rw [proof_boundaryChart_symm_val_36 x hz.1] + change _ = OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 y.val ((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm (OAI.CKSBoundarySurface.liftPlane z)))) + rw [proof_ext_symm_lift_35] + by + apply isManifold_of_contDiffOn + rintro e e' ⟨x,rfl⟩ ⟨y,rfl⟩ + change ContDiffOn ℝ ∞ (fun z => ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y) z) + (id ⁻¹' ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source ∩ range id) + rw [preimage_id,range_id,inter_univ] + apply (OAI.CKSBoundarySurface.dropPlane.contDiff.comp_contDiffOn ((contDiffOn_ext_coord_change (I := OAI.CKSBoundarySurface.I3) y.val x.val).comp + OAI.CKSBoundarySurface.liftPlane.contDiff.contDiffOn (proof_transition_lift_maps_32 x y))).congr + intro z hz + exact proof_transition_formula_33 x y hz + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal + +abbrev E := EuclideanSpace ℝ (Fin 2) + +abbrev H := OAI.CKSSurfaceVolume.E + +abbrev I := 𝓘(ℝ,OAI.CKSSurfaceVolume.E) + +abbrev basis (i : Fin 2) : OAI.CKSSurfaceVolume.E := EuclideanSpace.single i 1 + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric OAI.CKSSurfaceVolume.E (fun x : M => TangentSpace OAI.CKSSurfaceVolume.I x) + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +def chartFrame (x : M) (y : OAI.CKSSurfaceVolume.E) : OAI.CKSSurfaceVolume.E →L[ℝ] TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) := + mfderivWithin 𝓘(ℝ,OAI.CKSSurfaceVolume.E) OAI.CKSSurfaceVolume.I (extChartAt OAI.CKSSurfaceVolume.I x).symm (range OAI.CKSSurfaceVolume.I) y + +def chartMatrix (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) (y : OAI.CKSSurfaceVolume.E) : Matrix (Fin 2) (Fin 2) ℝ := + letI := OAI.CKSSurfaceVolume.real_continuousAdd + letI := OAI.CKSSurfaceVolume.real_continuousConstSMul + letI := OAI.CKSSurfaceVolume.real_smulCommClass + let inner : TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) →L[ℝ] + TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) →L[ℝ] ℝ := + g.inner ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) + fun i j => inner (OAI.CKSSurfaceVolume.chartFrame x y (OAI.CKSSurfaceVolume.basis i)) + (OAI.CKSSurfaceVolume.chartFrame x y (OAI.CKSSurfaceVolume.basis j)) + +def chartDensity (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) (y : OAI.CKSSurfaceVolume.E) : ℝ := + Real.sqrt (OAI.CKSSurfaceVolume.chartMatrix g x y).det + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] +variable [MeasurableSpace M] [BorelSpace M] + +def localVolume (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) : Measure M := + Measure.map (extChartAt OAI.CKSSurfaceVolume.I x).symm + ((volume.restrict (extChartAt OAI.CKSSurfaceVolume.I x).target).withDensity + (fun y => ENNReal.ofReal (OAI.CKSSurfaceVolume.chartDensity g x y))) + +def IsVolume (g : OAI.CKSSurfaceVolume.Metric (M := M)) (ν : Measure M) : Prop := + ∀ x : M, ν.restrict (extChartAt OAI.CKSSurfaceVolume.I x).source = OAI.CKSSurfaceVolume.localVolume g x + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal + +def riemannianVolume {M : Type u_1} [TopologicalSpace M] [ChartedSpace OAI.CKSSurfaceVolume.H M] + [IsManifold OAI.CKSSurfaceVolume.I 1 M] [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] + (g : OAI.CKSSurfaceVolume.Metric (M := M)) : Measure M := + Classical.epsilon (fun ν => OAI.CKSSurfaceVolume.IsVolume g ν) + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology + +abbrev E2 := EuclideanSpace ℝ (Fin 2) + +abbrev I2 := 𝓘(ℝ,OAI.CKSInducedArea.E2) + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_id_isometric : RingHomIsometric (RingHom.id ℝ) := inferInstance + +local instance real_id_compTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Inner2 := + letI := OAI.CKSInducedArea.real_smulCommClass + ∀ x : S, TangentSpace OAI.CKSInducedArea.I2 x →L[ℝ] TangentSpace OAI.CKSInducedArea.I2 x →L[ℝ] ℝ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Smooth3 := ContMDiffRiemannianMetric I3 ∞ OAI.CKSInducedArea.E3 (fun x : N => TangentSpace I3 x) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ + +abbrev Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +def inducedInner (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (φ : S → N) : OAI.CKSInducedArea.Inner2 (S := S) := + letI := OAI.CKSInducedArea.real_id_isometric + letI := OAI.CKSInducedArea.real_id_compTriple + fun x => by + let : NormedAddCommGroup (TangentSpace OAI.CKSInducedArea.I2 x) := by unfold TangentSpace; infer_instance + let : NormedSpace ℝ (TangentSpace OAI.CKSInducedArea.I2 x) := by unfold TangentSpace; infer_instance + let : NormedAddCommGroup (TangentSpace I3 (φ x)) := by unfold TangentSpace; infer_instance + let : NormedSpace ℝ (TangentSpace I3 (φ x)) := by unfold TangentSpace; infer_instance + exact (g.inner (φ x)).bilinearComp (mfderiv OAI.CKSInducedArea.I2 I3 φ x) (mfderiv OAI.CKSInducedArea.I2 I3 φ x) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +local instance tangent_manifold_one : IsManifold I 1 M := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one + + +local instance tangent_vectorBundle : VectorBundle ℝ E (fun x : M => TangentSpace I x) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle + + +local instance scalar_smulCommClass : SMulCommClass ℝ ℝ ℝ := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass + + +local instance scalar_vectorBundle : VectorBundle ℝ ℝ (Bundle.Trivial M ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle + + +local instance scalar_continuousSMul : ContinuousSMul ℝ ℝ := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul + + +local instance covector_vectorBundle : + VectorBundle ℝ (E →L[ℝ] ℝ) (fun x : M => TangentSpace I x →L[ℝ] ℝ) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle + + +local instance covector_topologicalAddGroup (x : M) : + IsTopologicalAddGroup (TangentSpace I x →L[ℝ] ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup + + +local instance covector_continuousSMul (x : M) : + ContinuousSMul ℝ (TangentSpace I x →L[ℝ] ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul + + +local instance scalarAtlas : MemTrivializationAtlas (Bundle.Trivial.trivialization M ℝ) := ⟨rfl⟩ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul +attribute [local instance] OAI.CKSInducedArea.scalarAtlas + + +local instance covector_atlas (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : + MemTrivializationAtlas + (e.continuousLinearMap (RingHom.id ℝ) (Bundle.Trivial.trivialization M ℝ)) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul +attribute [local instance] OAI.CKSInducedArea.scalarAtlas +attribute [local instance] covector_atlas + + +def bilinearTriv (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : + Trivialization (E →L[ℝ] E →L[ℝ] ℝ) (π (E →L[ℝ] E →L[ℝ] ℝ) (fun x : M => + TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ)) := + letI := OAI.CKSInducedArea.real_smulCommClass + e.continuousLinearMap (RingHom.id ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Bundle.Trivial.trivialization M ℝ)) + +instance bilinearTriv_atlas (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : MemTrivializationAtlas (OAI.CKSInducedArea.bilinearTriv I e) := by + unfold OAI.CKSInducedArea.bilinearTriv + infer_instance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +local instance covector_smulCommClass {Space : Type u_4} [NormedAddCommGroup Space] + [NormedSpace ℝ Space] : + letI := OAI.CKSInducedArea.real_smulCommClass + SMulCommClass ℝ ℝ (Space →L[ℝ] ℝ) := by + infer_instance + +local instance bilNorm2 : NormedAddCommGroup OAI.CKSInducedArea.Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E2) (F := OAI.CKSInducedArea.E2 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 + + +local instance bilSpace2 : NormedSpace ℝ OAI.CKSInducedArea.Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E2) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 + + +local instance bilNorm3 : NormedAddCommGroup OAI.CKSInducedArea.Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E3) (F := OAI.CKSInducedArea.E3 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 + + +local instance bilSpace3 : NormedSpace ℝ OAI.CKSInducedArea.Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E3) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 + + +local instance mixNorm23 : NormedAddCommGroup (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E2) (F := OAI.CKSInducedArea.E3 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 + + +local instance mixSpace23 : NormedSpace ℝ (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E3) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 + + +local instance mixNorm32 : NormedAddCommGroup (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E3) (F := OAI.CKSInducedArea.E2 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 +attribute [local instance] OAI.CKSInducedArea.mixNorm32 + + +local instance mixSpace32 : NormedSpace ℝ (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E2) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 +attribute [local instance] OAI.CKSInducedArea.mixNorm32 +attribute [local instance] OAI.CKSInducedArea.mixSpace32 + + +def inducedMetric (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (φ : S → N) + (hφ : ContMDiff OAI.CKSInducedArea.I2 I3 ∞ φ) + (hinj : ∀ x, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 φ x)) : + ContMDiffRiemannianMetric OAI.CKSInducedArea.I2 ∞ OAI.CKSInducedArea.E2 (fun x : S => TangentSpace OAI.CKSInducedArea.I2 x) := + have proof_inducedInner_symm_37 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (point : S) (left right : TangentSpace OAI.CKSInducedArea.I2 point) : + OAI.CKSInducedArea.inducedInner metric immersion point left right = OAI.CKSInducedArea.inducedInner metric immersion point right left := + metric.symm (immersion point) _ _ + have proof_inducedInner_pos_38 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (injective : ∀ point, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 immersion point)) + (point : S) (vector : TangentSpace OAI.CKSInducedArea.I2 point) (nonzero : vector ≠ 0) : + 0 < OAI.CKSInducedArea.inducedInner metric immersion point vector vector := + metric.pos (immersion point) _ + (fun zero => nonzero (injective point (zero.trans (map_zero _).symm))) + have proof_positive_bilinear_bounded_41 (B : OAI.CKSInducedArea.Bil2) (hB : ∀ v : OAI.CKSInducedArea.E2, v ≠ 0 → 0 < B v v) : + IsVonNBounded ℝ {v : OAI.CKSInducedArea.E2 | B v v < 1} := by + have hc : Continuous (fun v : OAI.CKSInducedArea.E2 => B v v) := B.continuous.clm_apply continuous_id + obtain ⟨a,ha,hm⟩ := (isCompact_sphere (0 : OAI.CKSInducedArea.E2) 1).exists_isMinOn + (NormedSpace.sphere_nonempty.mpr (by norm_num : (0 : ℝ) ≤ 1)) hc.continuousOn + have haNorm : ‖a‖ = 1 := by simpa [Metric.mem_sphere] using ha + have ha0 : a ≠ 0 := by intro h; simp [h] at haNorm + have hp : 0 < B a a := hB a ha0 + have hlow : ∀ v : OAI.CKSInducedArea.E2, B a a * ‖v‖ ^ 2 ≤ B v v := by + intro v + by_cases hv : v = 0 + · simp [hv] + have hn : 0 < ‖v‖ := norm_pos_iff.mpr hv + have hy : ‖(‖v‖⁻¹ : ℝ) • v‖ = 1 := by + rw [norm_smul, Real.norm_eq_abs, abs_of_pos (inv_pos.mpr hn), inv_mul_cancel₀ hn.ne'] + have h := hm (show (‖v‖⁻¹ : ℝ) • v ∈ Metric.sphere (0 : OAI.CKSInducedArea.E2) 1 by + simpa [Metric.mem_sphere] using hy) + have he : B ((‖v‖⁻¹ : ℝ) • v) ((‖v‖⁻¹ : ℝ) • v) = B v v / ‖v‖^2 := by + simp only [map_smul, smul_apply, smul_eq_mul] + field_simp + change B a a ≤ B ((‖v‖⁻¹ : ℝ) • v) ((‖v‖⁻¹ : ℝ) • v) at h + rw [he] at h + exact (le_div_iff₀ (sq_pos_of_pos hn)).mp h + apply (NormedSpace.isVonNBounded_iff ℝ).mpr + apply (Metric.isBounded_iff_subset_ball (0 : OAI.CKSInducedArea.E2)).mpr + refine ⟨1 + (B a a)⁻¹, ?_⟩ + intro v hv + change dist v 0 < 1 + (B a a)⁻¹ + rw [dist_zero_right] + have hbv : B v v < 1 := hv + have hl := hlow v + have hinv : 0 < (B a a)⁻¹ := inv_pos.mpr hp + have he : B a a * (B a a)⁻¹ = 1 := mul_inv_cancel₀ hp.ne' + by_contra hh + have hn : 1 + (B a a)⁻¹ ≤ ‖v‖ := le_of_not_gt hh + have hn1 : 1 ≤ ‖v‖ := by linarith + have hn2 : ‖v‖ ≤ ‖v‖^2 := by nlinarith + have hmul := mul_le_mul_of_nonneg_left hn hp.le + have hmul2 := mul_le_mul_of_nonneg_left hn2 hp.le + nlinarith + have proof_inducedInner_bounded_39 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (injective : ∀ point, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 immersion point)) (point : S) : + IsVonNBounded ℝ {vector : TangentSpace OAI.CKSInducedArea.I2 point | + inducedInner metric immersion point vector vector < 1} := + proof_positive_bilinear_bounded_41 (OAI.CKSInducedArea.inducedInner metric immersion point) + (proof_inducedInner_pos_38 metric immersion injective point) + have proof_bilinearComp_smoothAt_42 {S : Type u_3} [instLocal1 : TopologicalSpace.{u_3} S] [instLocal2 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] [instLocal3 : IsManifold.{0, 0, 0, u_3} OAI.CKSInducedArea.I2 (∞ : ℕ∞ω) S] [IsManifold OAI.CKSInducedArea.I2 ∞ S] + {B : S → OAI.CKSInducedArea.Bil3} {A : S → OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3} {x : S} + (hB : ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil3) ∞ B x) + (hA : ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3) ∞ A x) : + ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil2) ∞ (fun y => (B y).bilinearComp (A y) (A y)) x := by + have flip1 : ContDiff ℝ ∞ (fun B : OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ => B.flip) := + by + let L : (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) →L[ℝ] (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + (ContinuousLinearMap.flipₗᵢ ℝ OAI.CKSInducedArea.E2 OAI.CKSInducedArea.E3 ℝ).toContinuousLinearEquiv.toContinuousLinearMap + exact L.contDiff + have flip2 : ContDiff ℝ ∞ (fun B : OAI.CKSInducedArea.Bil2 => B.flip) := + by + let L : OAI.CKSInducedArea.Bil2 →L[ℝ] OAI.CKSInducedArea.Bil2 := + (ContinuousLinearMap.flipₗᵢ ℝ OAI.CKSInducedArea.E2 OAI.CKSInducedArea.E2 ℝ).toContinuousLinearEquiv.toContinuousLinearMap + exact L.contDiff + exact flip2.comp_contMDiffAt ((flip1.comp_contMDiffAt (hB.clm_comp hA)).clm_comp hA) + have proof_bilinearTriv_pair_43 {E : Type 0} [instLocal1 : NormedAddCommGroup.{0} E] [instLocal2 : NormedSpace.{0, 0} ℝ E] {H : Type 0} [instLocal4 : TopologicalSpace.{0} H] (I : ModelWithCorners.{0, 0, 0} ℝ E H) {M : Type u_3} [instLocal7 : TopologicalSpace.{u_3} M] [instLocal8 : ChartedSpace.{0, u_3} H M] [instLocal9 : IsManifold.{0, 0, 0, u_3} I (∞ : ℕ∞ω) M] (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] {x : M} (hx : x ∈ e.baseSet) + (B : TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) (v w : E) : + ((OAI.CKSInducedArea.bilinearTriv I e) ⟨x,B⟩).2 v w = B (e.symmL ℝ x v) (e.symmL ℝ x w) := by + let := OAI.CKSInducedArea.scalarAtlas (M := M) + unfold OAI.CKSInducedArea.bilinearTriv + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)) + (show x ∈ (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)).baseSet by simpa using hx)] + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (Trivial.trivialization M ℝ) (show x ∈ (Trivial.trivialization M ℝ).baseSet from mem_univ x)] + rfl + have proof_bilinearTriv_pair_44 {E : Type 0} [instLocal1 : NormedAddCommGroup.{0} E] [instLocal2 : NormedSpace.{0, 0} ℝ E] {H : Type u_1} [instLocal4 : TopologicalSpace.{u_1} H] (I : ModelWithCorners.{0, 0, u_1} ℝ E H) {M : Type u_2} [instLocal7 : TopologicalSpace.{u_2} M] [instLocal8 : ChartedSpace.{u_1, u_2} H M] [instLocal9 : IsManifold.{0, 0, u_1, u_2} I (∞ : ℕ∞ω) M] (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] {x : M} (hx : x ∈ e.baseSet) + (B : TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) (v w : E) : + ((OAI.CKSInducedArea.bilinearTriv I e) ⟨x,B⟩).2 v w = B (e.symmL ℝ x v) (e.symmL ℝ x w) := by + let := OAI.CKSInducedArea.scalarAtlas (M := M) + unfold OAI.CKSInducedArea.bilinearTriv + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)) + (show x ∈ (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)).baseSet by simpa using hx)] + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (Trivial.trivialization M ℝ) (show x ∈ (Trivial.trivialization M ℝ).baseSet from mem_univ x)] + rfl + have proof_inducedInner_smooth_40 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] [instLocal10 : IsManifold.{0, 0, 0, u_3} OAI.CKSInducedArea.I2 (∞ : ℕ∞ω) S] (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) {φ : S → N} + (hφ : ContMDiff OAI.CKSInducedArea.I2 I3 ∞ φ) : + ContMDiff OAI.CKSInducedArea.I2 (OAI.CKSInducedArea.I2.prod 𝓘(ℝ,OAI.CKSInducedArea.Bil2)) ∞ + (fun x => TotalSpace.mk' OAI.CKSInducedArea.Bil2 x (OAI.CKSInducedArea.inducedInner g φ x)) := by + let := OAI.CKSInducedArea.real_id_isometric + let := OAI.CKSInducedArea.real_smulCommClass + intro x + let e := trivializationAt OAI.CKSInducedArea.E2 (TangentSpace OAI.CKSInducedArea.I2) x + let e' := trivializationAt OAI.CKSInducedArea.E3 (TangentSpace I3) (φ x) + have hx : x ∈ e.baseSet := mem_baseSet_trivializationAt OAI.CKSInducedArea.E2 (TangentSpace OAI.CKSInducedArea.I2) x + have hx' : φ x ∈ e'.baseSet := mem_baseSet_trivializationAt OAI.CKSInducedArea.E3 (TangentSpace I3) (φ x) + apply (contMDiffAt_section (𝕜 := ℝ) (B := S) + (E := fun z : S => TangentSpace OAI.CKSInducedArea.I2 z →L[ℝ] TangentSpace OAI.CKSInducedArea.I2 z →L[ℝ] ℝ) + (IB := OAI.CKSInducedArea.I2) (n := ∞) (F := OAI.CKSInducedArea.Bil2) + (s := OAI.CKSInducedArea.inducedInner g φ) x).mpr + change ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil2) ∞ + (fun y : S => ((OAI.CKSInducedArea.bilinearTriv OAI.CKSInducedArea.I2 e) + ⟨y, OAI.CKSInducedArea.inducedInner g φ y⟩).2) x + have hB := (contMDiffAt_section (𝕜 := ℝ) (B := N) + (E := fun z : N => TangentSpace I3 z →L[ℝ] TangentSpace I3 z →L[ℝ] ℝ) + (IB := I3) (n := ∞) (F := OAI.CKSInducedArea.Bil3) (s := g.inner) (φ x)).mp (g.contMDiff (φ x)) + change ContMDiffAt I3 𝓘(ℝ,OAI.CKSInducedArea.Bil3) ∞ + (fun y : N => ((OAI.CKSInducedArea.bilinearTriv I3 e') ⟨y, g.inner y⟩).2) (φ x) at hB + have hD := (hφ x).mfderiv_const (show (∞ : ℕ∞ω) + 1 ≤ ∞ by simp [*]) + apply (proof_bilinearComp_smoothAt_42 (hB.comp x (hφ x)) hD).congr_of_eventuallyEq + filter_upwards [e.open_baseSet.mem_nhds hx, + hφ.continuous.continuousAt.preimage_mem_nhds (e'.open_baseSet.mem_nhds hx')] with y hy hy' + ext v w + rw [proof_bilinearTriv_pair_43 OAI.CKSInducedArea.I2 e hy] + rw [ContinuousLinearMap.bilinearComp_apply] + dsimp only [Function.comp_apply] + rw [proof_bilinearTriv_pair_44 I3 e' hy'] + dsimp [OAI.CKSInducedArea.inducedInner,inTangentCoordinates,ContinuousLinearMap.inCoordinates] + rw [e'.symmL_continuousLinearMapAt hy', e'.symmL_continuousLinearMapAt hy'] + rfl + { + inner := OAI.CKSInducedArea.inducedInner g φ + symm := proof_inducedInner_symm_37 g φ + pos := proof_inducedInner_pos_38 g φ hinj + isVonNBounded := proof_inducedInner_bounded_39 g φ hinj + contMDiff := proof_inducedInner_smooth_40 g hφ + } + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSEmbeddingDerivative +open Set Manifold Bundle Filter Function +open scoped ContDiff Topology + +abbrev E := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSEmbeddingDerivative.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSEmbeddingDerivative.halfSpaceDimension_neZero + +end OAI.CKSEmbeddingDerivative +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle Function +open scoped ContDiff Topology +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] + +instance domainTopology (D : OAI.CKSGeometricCuts.OuterDomain N) : TopologicalSpace D.Carrier := D.topology + +instance domainCharts (D : OAI.CKSGeometricCuts.OuterDomain N) : ChartedSpace OAI.CKSBoundarySurface.H3 D.Carrier := D.charts + +instance domainSmooth (D : OAI.CKSGeometricCuts.OuterDomain N) : IsManifold OAI.CKSBoundarySurface.I3 ∞ D.Carrier := D.smooth + +abbrev Surface (D : OAI.CKSGeometricCuts.OuterDomain N) := OAI.CKSBoundarySurface.Boundary D.Carrier + +def cutInclusion (D : OAI.CKSGeometricCuts.OuterDomain N) : OAI.CKSFullCutArea.Surface D → N := D.inclusion ∘ Subtype.val + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle Function +open scoped ContDiff Topology +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] +variable [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSBoundarySurface.halfSpaceDimension_neZero) I3 ∞ N _ _] + +instance domainSecondCountable [SecondCountableTopology N] (D : OAI.CKSGeometricCuts.OuterDomain N) : + SecondCountableTopology D.Carrier := D.embedding.isEmbedding.secondCountableTopology + +abbrev SmoothMetric := + letI := OAI.CKSBoundarySurface.halfSpaceDimension_neZero + letI := OAI.CKSInducedArea.tangent_vectorBundle OAI.CKSBoundarySurface.I3 (M := N) + ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I3 ∞ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) + +def cutMetric (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) (D : OAI.CKSGeometricCuts.OuterDomain N) : + ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I2 ∞ OAI.CKSBoundarySurface.E2 (fun x : OAI.CKSFullCutArea.Surface D => TangentSpace OAI.CKSBoundarySurface.I2 x) := + have proof_boundary_chart_zero_49 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_50 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_49 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_51 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_50 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_52 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_51 x.val hz + have proof_boundaryInverse_val_53 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_boundaryChart_symm_val_54 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := + proof_boundaryInverse_val_53 x hz + have proof_inclusion_chart_formula_55 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + writtenInExtChartAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 x (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) z = OAI.CKSBoundarySurface.liftPlane z := by + change OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val (((OAI.CKSBoundarySurface.boundaryChart x).symm z).val)) = _ + rw [proof_boundaryChart_symm_val_54 x hz, (chartAt OAI.CKSBoundarySurface.H3 x.val).right_inv hz] + rfl + have proof_inclusion_chart_eventually_56 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + writtenInExtChartAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 x (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) =ᶠ[𝓝 (extChartAt OAI.CKSBoundarySurface.I2 x x)] OAI.CKSBoundarySurface.liftPlane := by + have ht : (OAI.CKSBoundarySurface.boundaryChart x).target ∈ 𝓝 (extChartAt OAI.CKSBoundarySurface.I2 x x) := + (OAI.CKSBoundarySurface.boundaryChart x).open_target.mem_nhds ((OAI.CKSBoundarySurface.boundaryChart x).map_source (mem_chart_source OAI.CKSBoundarySurface.E2 x)) + filter_upwards [ht] with z hz + exact proof_inclusion_chart_formula_55 x hz + have proof_inclusion_smooth_57 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] : ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) := by + intro x + apply contMDiffAt_iff.mpr + refine ⟨continuous_subtype_val.continuousAt, ?_⟩ + exact ((OAI.CKSBoundarySurface.liftPlane.contDiff.contDiffAt).congr_of_eventuallyEq (proof_inclusion_chart_eventually_56 x)).contDiffWithinAt + have proof_cutInclusion_smooth_47 {N : Type u} [instLocal1 : TopologicalSpace.{u} N] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 N] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) N] [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (D : OAI.CKSGeometricCuts.OuterDomain N) : + ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ (OAI.CKSFullCutArea.cutInclusion D) := + D.embedding.isImmersion.contMDiff.comp proof_inclusion_smooth_57 + have proof_extended_chart_derivative_injective_58 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [IsManifold OAI.CKSEmbeddingDerivative.I ∞ M] (e : OpenPartialHomeomorph M OAI.CKSEmbeddingDerivative.H) + (he : e ∈ IsManifold.maximalAtlas OAI.CKSEmbeddingDerivative.I ∞ M) {x : M} (hx : x ∈ e.source) : + Injective (mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x) := by + have hed : e.MDifferentiable OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I := ⟨ + (contMDiffOn_of_mem_maximalAtlas he).mdifferentiableOn (by simp), + (contMDiffOn_symm_of_mem_maximalAtlas he).mdifferentiableOn (by simp)⟩ + have hcomp := mfderiv_comp x OAI.CKSEmbeddingDerivative.I.mdifferentiableAt ((hed.1 x hx).mdifferentiableAt (e.open_source.mem_nhds hx)) + change mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x = _ at hcomp + rw [OAI.CKSEmbeddingDerivative.I.hasMFDerivAt.mfderiv] at hcomp + change mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x = mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I e x at hcomp + rw [hcomp] + exact hed.mfderiv_injective hx + have proof_immersion_derivative_injective_59 {M : Type u} {N : Type u} [instLocal2 : TopologicalSpace.{u} M] [instLocal3 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal4 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [instLocal5 : TopologicalSpace.{u} N] [instLocal6 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H N] [instLocal7 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) N] [IsManifold OAI.CKSEmbeddingDerivative.I ∞ N] {f : M → N} {x : M} + (h : IsImmersionAt OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I ∞ f x) : Injective (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x) := by + let A : OAI.CKSEmbeddingDerivative.E →L[ℝ] OAI.CKSEmbeddingDerivative.E := (ContinuousLinearMap.fst ℝ OAI.CKSEmbeddingDerivative.E h.complement).comp + h.equiv.symm.toContinuousLinearMap + let L : N → OAI.CKSEmbeddingDerivative.E := A ∘ (h.codChart.extend OAI.CKSEmbeddingDerivative.I) + have hL : ContMDiffAt OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) ∞ L (f x) := + A.contMDiff.contMDiffAt.comp _ + (h.codChart.contMDiffAt_extend h.codChart_mem_maximalAtlas h.mem_codChart_source) + have heq : (L ∘ f) =ᶠ[𝓝 x] h.domChart.extend OAI.CKSEmbeddingDerivative.I := by + filter_upwards [h.domChart.open_source.mem_nhds h.mem_domChart_source] with y hy + have hy' : y ∈ (h.domChart.extend OAI.CKSEmbeddingDerivative.I).source := by simpa only [OpenPartialHomeomorph.extend_source] using hy + have hw := h.writtenInCharts ((h.domChart.extend OAI.CKSEmbeddingDerivative.I).map_source hy') + dsimp only [Function.comp_apply] at hw + rw [(h.domChart.extend OAI.CKSEmbeddingDerivative.I).left_inv hy'] at hw + change A ((h.codChart.extend OAI.CKSEmbeddingDerivative.I) (f y)) = _ + rw [hw] + simp only [A,ContinuousLinearMap.comp_apply,ContinuousLinearEquiv.coe_coe, + ContinuousLinearEquiv.symm_apply_apply ] + rfl + have hdL := hL.mdifferentiableAt (by simp) + have hdf := h.contMDiffAt.mdifferentiableAt (by simp) + have hder := heq.mfderiv_eq (I := OAI.CKSEmbeddingDerivative.I) (I' := 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E)) + rw [mfderiv_comp x hdL hdf] at hder + change _ = mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (h.domChart.extend OAI.CKSEmbeddingDerivative.I) x at hder + have hinj := proof_extended_chart_derivative_injective_58 h.domChart h.domChart_mem_maximalAtlas + h.mem_domChart_source + rw [← hder] at hinj + have hi' : Injective ((mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) L (f x)) ∘ (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x)) := hinj + exact hi'.of_comp + have proof_smooth_embedding_derivative_injective_60 {M : Type u} {N : Type u} [instLocal2 : TopologicalSpace.{u} M] [instLocal3 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal4 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [instLocal5 : TopologicalSpace.{u} N] [instLocal6 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H N] [instLocal7 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) N] {f : M → N} (h : IsSmoothEmbedding OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I ∞ f) : + ∀ x, Injective (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x) := fun x => + proof_immersion_derivative_injective_59 (h.isImmersion.isImmersionAt x) + have proof_inclusion_hasMFDeriv_61 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + HasMFDerivAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) x OAI.CKSBoundarySurface.liftPlane := by + refine ⟨continuous_subtype_val.continuousAt, ?_⟩ + exact (OAI.CKSBoundarySurface.liftPlane.hasFDerivAt.congr_of_eventuallyEq (proof_inclusion_chart_eventually_56 x)).hasFDerivWithinAt + have proof_dropPlane_apply_31 (z : OAI.CKSBoundarySurface.E3) (i : Fin 2) : OAI.CKSBoundarySurface.dropPlane z i = z i.succ := rfl + have proof_drop_lift_28 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane z) = z := by ext i; rfl + have proof_inclusion_mfderiv_injective_62 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) x) := by + rw [(proof_inclusion_hasMFDeriv_61 x).mfderiv] + intro a b h + change OAI.CKSBoundarySurface.liftPlane a = OAI.CKSBoundarySurface.liftPlane b at h + have hh : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane a) = OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane b) := congrArg OAI.CKSBoundarySurface.dropPlane h + change (a : OAI.CKSBoundarySurface.E2) = (b : OAI.CKSBoundarySurface.E2) + exact (proof_drop_lift_28 a).symm.trans (hh.trans (proof_drop_lift_28 b)) + have proof_cutInclusion_derivative_injective_48 {N : Type u} [instLocal1 : TopologicalSpace.{u} N] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 N] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) N] [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (D : OAI.CKSGeometricCuts.OuterDomain N) (x : OAI.CKSFullCutArea.Surface D) : + Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (OAI.CKSFullCutArea.cutInclusion D) x) := by + unfold OAI.CKSFullCutArea.cutInclusion + rw [mfderiv_comp x ((D.embedding.isImmersion.contMDiff x.val).mdifferentiableAt (by simp [*])) + ((proof_inclusion_smooth_57 x).mdifferentiableAt (by simp [*]))] + · change Injective ((mfderiv OAI.CKSBoundarySurface.I3 OAI.CKSBoundarySurface.I3 D.inclusion x.val) ∘ + (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSFullCutArea.Surface D → D.Carrier) x)) + exact (proof_smooth_embedding_derivative_injective_60 D.embedding x.val).comp + (proof_inclusion_mfderiv_injective_62 x) + @OAI.CKSInducedArea.inducedMetric OAI.CKSBoundarySurface.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero) + OAI.CKSBoundarySurface.I3 N _ _ _ (OAI.CKSFullCutArea.Surface D) _ _ _ g (OAI.CKSFullCutArea.cutInclusion D) (proof_cutInclusion_smooth_47 D) + (proof_cutInclusion_derivative_injective_48 D) + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle MeasureTheory +open scoped ContDiff Topology ENNReal +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSBoundarySurface.halfSpaceDimension_neZero) I3 ∞ N _ _] + [SecondCountableTopology N] + +def area (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) (D : OAI.CKSGeometricCuts.OuterDomain N) : ℝ≥0∞ := + letI : MeasurableSpace (OAI.CKSFullCutArea.Surface D) := borel (OAI.CKSFullCutArea.Surface D) + letI : BorelSpace (OAI.CKSFullCutArea.Surface D) := ⟨rfl⟩ + OAI.CKSSurfaceVolume.riemannianVolume (OAI.CKSFullCutArea.cutMetric g D).toContinuousRiemannianMetric univ + +def minEnclosingArea (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) : ℝ≥0∞ := + ⨅ D : OAI.CKSGeometricCuts.OuterDomain N, OAI.CKSFullCutArea.area g D + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Set Manifold Bundle MeasureTheory CKSLorentz CKSMetricGluing +open scoped ContDiff Topology ENNReal +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] + +local instance eight_atLeastTwo : Nat.AtLeastTwo 8 := inferInstance + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Set Manifold Bundle MeasureTheory CKSLorentz CKSMetricGluing +open scoped ContDiff Topology ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] +attribute [local instance] eight_atLeastTwo + + +def IntegrableConstraints (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSIntrinsicConstraints.I (M := M)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)) : Prop := + ∃ μ j : M → ℝ, Continuous μ ∧ Continuous j ∧ + Integrable μ (OAI.CKSIntrinsicVolume.riemannianVolume g.toContinuousRiemannianMetric) ∧ + Integrable j (OAI.CKSIntrinsicVolume.riemannianVolume g.toContinuousRiemannianMetric) ∧ + (∀ x, 0 ≤ j x ∧ j x ≤ μ x) ∧ + ∀ x (c : OAI.CKSIntrinsicConstraints.ConstraintChart g.inner K x), + 8 * Real.pi * μ x = c.energy ∧ 8 * Real.pi * j x = c.momentumNorm + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +local instance id_invPair (Scalar : Type u_1) [Semiring Scalar] : + RingHomInvPair (RingHom.id Scalar) (RingHom.id Scalar) := inferInstance + +local instance source_manifold_one : IsManifold OAI.CKSGeometricCuts.I3 1 N := inferInstance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] CKSGeometricCuts.halfSpaceDimension_neZero id_invPair source_manifold_one + + +local instance source_trivialization_isLinear (point : N) : + (trivializationAt OAI.CKSLorentz.E (TangentSpace OAI.CKSGeometricCuts.I3) point).IsLinear ℝ := inferInstance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] CKSGeometricCuts.halfSpaceDimension_neZero id_invPair source_manifold_one +attribute [local instance] source_trivialization_isLinear + + +def Orientable : Prop := + ∃ o : ∀ x : N, Orientation ℝ (TangentSpace OAI.CKSGeometricCuts.I3 x) (Fin 3), ∀ x : N, + let e := trivializationAt OAI.CKSLorentz.E (TangentSpace OAI.CKSGeometricCuts.I3) x + ∃ V : Set N, IsOpen V ∧ ∃ hx : x ∈ V, ∃ hV : V ⊆ e.baseSet, + ∀ y (hy : y ∈ V), + let atPoint : TangentSpace OAI.CKSGeometricCuts.I3 y ≃L[ℝ] OAI.CKSLorentz.E := e.continuousLinearEquivAt ℝ y (hV hy) + let atBase : TangentSpace OAI.CKSGeometricCuts.I3 x ≃L[ℝ] OAI.CKSLorentz.E := e.continuousLinearEquivAt ℝ x (hV hx) + Orientation.map (Fin 3) atPoint.toLinearEquiv (o y) = + Orientation.map (Fin 3) atBase.toLinearEquiv (o x) + +structure CoordinateEnd where + radius : ℝ + radius_pos : 0 < radius + domain : Set N + isOpen : IsOpen domain + coordinate : N → OAI.CKSLorentz.E + inverse : OAI.CKSLorentz.E → N + smooth : ContMDiffOn OAI.CKSGeometricCuts.I3 𝓘(ℝ,OAI.CKSLorentz.E) ∞ coordinate domain + inverse_smooth : ContMDiffOn 𝓘(ℝ,OAI.CKSLorentz.E) OAI.CKSGeometricCuts.I3 ∞ inverse {y | radius < ‖y‖} + mapsTo : ∀ x ∈ domain, radius < ‖coordinate x‖ + left_inverse : ∀ x ∈ domain, inverse (coordinate x) = x + right_inverse : ∀ y, radius < ‖y‖ → inverse y ∈ domain ∧ coordinate (inverse y) = y + closed_far_side : ∀ r, radius < r → IsClosed {x : N | x ∈ domain ∧ r ≤ ‖coordinate x‖} + compact_inner_side : ∀ r, radius < r → IsCompact {x : N | x ∉ domain ∨ ‖coordinate x‖ ≤ r} + +structure CKSData (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) where + chart : OAI.CKSSourceExterior.CoordinateEnd (N := N) + metricPerturbation : OAI.CKSLorentz.SpatialTensor + tensorPerturbation : OAI.CKSLorentz.SpatialTensor + metric_smooth : ∀ y, chart.radius < ‖y‖ → ContDiffAt ℝ ∞ metricPerturbation y + tensor_smooth : ∀ y, chart.radius < ‖y‖ → ContDiffAt ℝ ∞ tensorPerturbation y + represents : ∀ x ∈ chart.domain, + g.inner x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 chart.coordinate (OAI.CKSLorentz.sourceSpatial metricPerturbation) x ∧ + K x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 chart.coordinate (OAI.CKSLorentz.sourceSpatial tensorPerturbation) x + massAspect : OAI.CKSLorentz.Sphere → ℝ + aspect_smooth : OAI.CKSSphericalHarmonics.SmoothSphere massAspect + patches : OAI.CKSLorentz.Sphere → OAI.CKSLorentz.CKSTensorPatch + covers : ∀ n, n ∈ (patches n).patch.sphereRegion (patches n).region + realizes : ∀ n, (patches n).Realizes metricPerturbation tensorPerturbation + aspect_eq : ∀ n, (patches n).RepresentsMassAspect massAspect + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle MeasureTheory +open scoped ContDiff Topology InnerProductSpace ENNReal +open CKSBoundarySurface CKSFullCutArea CKSSurfaceVolume + +instance exteriorConnected : ConnectedSpace OAI.CKSSchwarzschild.Exterior := by + have : ConnectedSpace OAI.CKSSchwarzschild.Radial := isConnected_iff_connectedSpace.mp isConnected_Ici + have : ConnectedSpace OAI.CKSSchwarzschild.Sphere := isConnected_iff_connectedSpace.mp + (isConnected_sphere (by rw [← Module.finrank_eq_rank]; norm_num : 1 < Module.rank ℝ E3) (0 : OAI.CKSBoundarySurface.E3) (by norm_num : (0 : ℝ) ≤ 1)) + infer_instance + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle MeasureTheory CKSGeometricCuts CKSMetricGluing +open scoped ContDiff +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSGeometricCuts.halfSpaceDimension_neZero) I3 ∞ N _ _] + [SecondCountableTopology N] + +def cutArea (g : @OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero) + OAI.CKSGeometricCuts.I3 N _ _ _) (D : OAI.CKSGeometricCuts.OuterDomain N) : ℝ := + (OAI.CKSFullCutArea.area g D).toReal + +def minimumEnclosingArea (g : @OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero) + OAI.CKSGeometricCuts.I3 N _ _ _) : ℝ := + ⨅ D : OAI.CKSGeometricCuts.OuterDomain N, OAI.CKSSourceExterior.cutArea g D + +def constraintsIntegrable (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) : Prop := + letI : MeasurableSpace N := borel N + letI : BorelSpace N := ⟨rfl⟩ + OAI.CKSIntrinsicConstraints.IntegrableConstraints g K + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Manifold Bundle Set Filter +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +variable {V : Type u_1} [NormedAddCommGroup V] [NormedSpace ℝ V] + +def covariantPair (g : + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + V → V →L[ℝ] V →L[ℝ] ℝ) (N : V → V) + (x a b : V) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + g x (fderiv ℝ N x a) b + 1/2 * + (fderiv ℝ (fun y => g y (N x) b) x a + + fderiv ℝ (fun y => g y a b) x (N x) - + fderiv ℝ (fun y => g y a (N x)) x b) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +abbrev Spacetime := ℝ × OAI.CKSBoundarySurface.E3 + +abbrev SpacetimeBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_continuousConstSMul + OAI.CKSSchwarzschild.Spacetime →L[ℝ] OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ + +def timeForm : OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ := ContinuousLinearMap.fst ℝ ℝ OAI.CKSBoundarySurface.E3 + +def spacePart : OAI.CKSSchwarzschild.Spacetime →L[ℝ] OAI.CKSBoundarySurface.E3 := ContinuousLinearMap.snd ℝ ℝ OAI.CKSBoundarySurface.E3 + +def radiusForm (x : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ := (OAI.CKSSchwarzschild.euclideanForm (OAI.CKSSchwarzschild.radialUnit x)).comp OAI.CKSSchwarzschild.spacePart + +def schwarzschildH (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 1-2*m/r + +local instance spacetimeDual_continuousAdd : ContinuousAdd (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_isTopologicalAddGroup : IsTopologicalAddGroup (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := + inferInstance + +local instance spacetimeDual_smulCommClass : SMulCommClass ℝ ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_continuousConstSMul : ContinuousConstSMul ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := + inferInstance + +local instance spacetimeDual_isScalarTower : IsScalarTower ℝ ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_continuousSMul : ContinuousSMul ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +def advancedMetric (m : ℝ) (z : OAI.CKSSchwarzschild.Spacetime) : OAI.CKSSchwarzschild.SpacetimeBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousAdd + letI := OAI.CKSSchwarzschild.spacetimeDual_isTopologicalAddGroup + letI := OAI.CKSSchwarzschild.spacetimeDual_smulCommClass + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousConstSMul + letI := OAI.CKSSchwarzschild.spacetimeDual_isScalarTower + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousSMul + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI := OAI.CKSSpatialManifold.real_id_isometric + let spatialMetric : OAI.CKSSchwarzschild.SpacetimeBilinear := OAI.CKSSchwarzschild.euclideanForm.bilinearComp OAI.CKSSchwarzschild.spacePart OAI.CKSSchwarzschild.spacePart + (-OAI.CKSSchwarzschild.schwarzschildH m ‖z.2‖) • OAI.CKSSchwarzschild.timeForm.smulRight OAI.CKSSchwarzschild.timeForm + + OAI.CKSSchwarzschild.timeForm.smulRight (OAI.CKSSchwarzschild.radiusForm z.2) + (OAI.CKSSchwarzschild.radiusForm z.2).smulRight OAI.CKSSchwarzschild.timeForm + + spatialMetric - + (OAI.CKSSchwarzschild.radiusForm z.2).smulRight (OAI.CKSSchwarzschild.radiusForm z.2) + +def advancedSlope (m r : ℝ) : ℝ := (OAI.CKSSchwarzschild.lapse m r*(OAI.CKSSchwarzschild.lapse m r-OAI.CKSSchwarzschild.velocity m r))⁻¹ + +def advancedTime (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + ∫ s in (2*m)..r, OAI.CKSSchwarzschild.advancedSlope m s + +def advancedGraph (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime := (OAI.CKSSchwarzschild.advancedTime m ‖x‖,x) + +def futureNormal (m : ℝ) (z : OAI.CKSSchwarzschild.Spacetime) : OAI.CKSSchwarzschild.Spacetime := + ((OAI.CKSSchwarzschild.lapse m ‖z.2‖-OAI.CKSSchwarzschild.velocity m ‖z.2‖)⁻¹,OAI.CKSSchwarzschild.velocity m ‖z.2‖ • OAI.CKSSchwarzschild.radialUnit z.2) + +def graphTangent (m : ℝ) (x a : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime := + letI := OAI.CKSLorentz.two_atLeastTwo + letI : Inner ℝ OAI.CKSBoundarySurface.E3 := + @InnerProductSpace.toInner ℝ OAI.CKSBoundarySurface.E3 _ + (PiLp.seminormedAddCommGroup 2 (fun _ : Fin 3 => ℝ)) + (PiLp.innerProductSpace (fun _ : Fin 3 => ℝ)) + (OAI.CKSSchwarzschild.advancedSlope m ‖x‖ * ⟪OAI.CKSSchwarzschild.radialUnit x,a⟫_ℝ,a) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle CKSSpatialManifold CKSMetricGluing CKSLorentz +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +structure HorizonRegularGraph (m : ℝ) : Prop where + ambient_smooth : ∀ z : OAI.CKSSchwarzschild.Spacetime, z.2 ≠ 0 → ContDiffAt ℝ ∞ (OAI.CKSSchwarzschild.advancedMetric m) z + ambient_symmetric : ∀ z a b, OAI.CKSSchwarzschild.advancedMetric m z a b = OAI.CKSSchwarzschild.advancedMetric m z b a + ambient_nondegenerate : ∀ z : OAI.CKSSchwarzschild.Spacetime, z.2 ≠ 0 → ∀ a : OAI.CKSSchwarzschild.Spacetime, + (∀ b, OAI.CKSSchwarzschild.advancedMetric m z a b = 0) → a = 0 + graph_smooth_across : ∀ x : OAI.CKSBoundarySurface.E3, m < ‖x‖ → ContDiffAt ℝ ∞ (OAI.CKSSchwarzschild.advancedGraph m) x + graph_injective : Function.Injective (OAI.CKSSchwarzschild.advancedGraph m) + graph_derivative : ∀ x : OAI.CKSBoundarySurface.E3, m < ‖x‖ → ∀ a, + fderiv ℝ (OAI.CKSSchwarzschild.advancedGraph m) x a = OAI.CKSSchwarzschild.graphTangent m x a + horizon_time : OAI.CKSSchwarzschild.advancedTime m (2*m) = 0 + horizon_slope : OAI.CKSSchwarzschild.advancedSlope m (2*m) = 1/2 + induced_metric : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a b, + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.graphTangent m x a) (OAI.CKSSchwarzschild.graphTangent m x b) = OAI.CKSSchwarzschild.cartMetric m x a b + normal_unit : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) + (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) = -1 + normal_orthogonal : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a, + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) (OAI.CKSSchwarzschild.graphTangent m x a) = 0 + future_facing : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → 0 < (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)).1 + induced_second_form : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a b, + OAI.CKSSchwarzschild.covariantPair (OAI.CKSSchwarzschild.advancedMetric m) (OAI.CKSSchwarzschild.futureNormal m) (OAI.CKSSchwarzschild.advancedGraph m x) + (OAI.CKSSchwarzschild.graphTangent m x a) (OAI.CKSSchwarzschild.graphTangent m x b) = OAI.CKSSchwarzschild.cartTensor m x a b + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +attribute [local instance] CKSInducedArea.real_continuousAdd CKSInducedArea.real_smulCommClass CKSInducedArea.real_continuousConstSMul CKSBoundarySurface.two_atLeastTwo + + +local instance frameCovectorModule : Module ℝ (OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) := + @ContinuousLinearMap.module ℝ ℝ ℝ _ _ _ OAI.CKSBoundarySurface.E3 _ _ _ ℝ _ _ _ _ + OAI.CKSInducedArea.real_smulCommClass OAI.CKSInducedArea.real_continuousConstSMul + (RingHom.id ℝ) OAI.CKSInducedArea.real_continuousAdd + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +attribute [local instance] CKSInducedArea.real_continuousAdd CKSInducedArea.real_smulCommClass CKSInducedArea.real_continuousConstSMul CKSBoundarySurface.two_atLeastTwo +attribute [local instance] OAI.CKSSchwarzschild.frameCovectorModule + + +def christoffelPair (g : OAI.CKSBoundarySurface.E3 → OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (x a b c : OAI.CKSBoundarySurface.E3) : ℝ := + 1/2 * (fderiv ℝ (fun z => g z b c) x a + + fderiv ℝ (fun z => g z a c) x b - fderiv ℝ (fun z => g z a b) x c) + +def firstFrame (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + (Real.sqrt (g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 0 1))))⁻¹ • + EuclideanSpace.single 0 1 + +def secondResidual (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + EuclideanSpace.single 1 1 - + (g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 1 1)) / + g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 0 1))) • EuclideanSpace.single 0 1 + +def secondFrame (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + (Real.sqrt (g (T (OAI.CKSSchwarzschild.secondResidual g T)) (T (OAI.CKSSchwarzschild.secondResidual g T))))⁻¹ • OAI.CKSSchwarzschild.secondResidual g T + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Manifold CKSGeometricCuts +open scoped ContDiff +variable {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] + +local instance halfSpace_locallyCompact : LocallyCompactSpace OAI.CKSGeometricCuts.H3 := by + change LocallyCompactSpace {x : EuclideanSpace ℝ (Fin 3) // 0 ≤ x 0} + have hc : IsClosed {x : EuclideanSpace ℝ (Fin 3) | 0 ≤ x 0} := + isClosed_le continuous_const (by fun_prop) + exact hc.locallyCompactSpace + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Manifold CKSGeometricCuts +open scoped ContDiff +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] + +local instance manifold_regular [IsManifold OAI.CKSGeometricCuts.I3 ∞ N] [T2Space N] : T3Space N := by + let := OAI.CKSSourceExterior.halfSpace_locallyCompact + let : LocallyCompactSpace N := ChartedSpace.locallyCompactSpace OAI.CKSGeometricCuts.H3 N + infer_instance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle Filter CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts +open CKSADM (Symbol) +open scoped ContDiff Topology +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + [T2Space N] [SecondCountableTopology N] [ConnectedSpace N] +attribute [local instance] manifold_regular + + +theorem area_controlled_end_replacement + (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) + (hK : ContMDiff OAI.CKSGeometricCuts.I3 (OAI.CKSGeometricCuts.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSGeometricCuts.I3 K)) + (hKsym : ∀ x v w, K x v w = K x w v) + (hOrient : OAI.CKSSourceExterior.Orientable (N := N)) + (hScompact : IsCompact (OAI.CKSGeometricCuts.I3.boundary N)) (hSnonempty : (OAI.CKSGeometricCuts.I3.boundary N).Nonempty) + (hcomplete : OAI.CKSReplacementCompleteness.IsComplete OAI.CKSGeometricCuts.I3 g.toContinuousRiemannianMetric) + (hDEC : OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSGeometricCuts.I3 g.inner K) + (d : OAI.CKSSourceExterior.CKSData g K) + (ht : ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖ < (OAI.CKSLorentz.bondiCharge d.massAspect).1) : + ∃ (d' : OAI.CKSSourceExterior.CKSData g K) (R₀ : ℝ) (ε : ℝ → ℝ), + OAI.CKSLorentz.bondiCharge d'.massAspect = + (Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2),0) ∧ + d'.chart.radius < R₀ ∧ 12 ≤ R₀ ∧ Tendsto ε atTop (𝓝 0) ∧ + OAI.CKSFullCutArea.minEnclosingArea g < ⊤ ∧ + ∀ R ≥ R₀, (0 ≤ ε R ∧ ε R < 1) ∧ + ∃ (gR : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (kR : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) + (G k : OAI.CKSLorentz.SpatialTensor) (η : ℝ), + ContMDiff OAI.CKSGeometricCuts.I3 (OAI.CKSGeometricCuts.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSGeometricCuts.I3 kR) ∧ + (∀ x v w, kR x v w = kR x w v) ∧ + (∀ x, x ∉ d'.chart.domain ∨ ‖d'.chart.coordinate x‖ ≤ R → + gR.inner x = g.inner x ∧ kR x = K x) ∧ + OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSGeometricCuts.I3 gR.inner kR ∧ + (∀ x v, (1-ε R) * g.inner x v v ≤ gR.inner x v v) ∧ + OAI.CKSReplacementCompleteness.IsComplete OAI.CKSGeometricCuts.I3 gR.toContinuousRiemannianMetric ∧ + OAI.CKSSourceExterior.constraintsIntegrable gR kR ∧ + (∀ x ∈ d'.chart.domain, + gR.inner x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 d'.chart.coordinate G x ∧ + kR x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 d'.chart.coordinate k x) ∧ + (∀ i j : Fin 3, OAI.CKSADM.Symbol 1 + (fun x => OAI.CKSLorentz.spatialCartesian G x i j - (if i=j then 1 else 0))) ∧ + (∀ x : OAI.CKSLorentz.E, 2*R^2 < ‖x‖ → k x = 0) ∧ + Tendsto (OAI.CKSLorentz.spatialADMEnergy G) atTop + (𝓝 (Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2) + η)) ∧ + Tendsto (OAI.CKSLorentz.spatialADMMomentum G k) atTop (𝓝 0) ∧ + 0 ≤ η ∧ η ≤ 2 * R ^ (-(1/2 : ℝ)) ∧ + OAI.CKSFullCutArea.minEnclosingArea gR < ⊤ ∧ + (1-ε R) * OAI.CKSSourceExterior.minimumEnclosingArea g ≤ OAI.CKSSourceExterior.minimumEnclosingArea gR ∧ + ∀ D : OAI.CKSGeometricCuts.OuterDomain N, + OAI.CKSFullCutArea.area g D < ⊤ ∧ OAI.CKSFullCutArea.area gR D < ⊤ ∧ + (1-ε R) * OAI.CKSSourceExterior.cutArea g D ≤ OAI.CKSSourceExterior.cutArea gR D := by + sorry + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular + + +def secondForm (q : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) (ν : OAI.CKSBoundarySurface.E3) + (a b : OAI.CKSBoundarySurface.E2) : ℝ := + -(q (f y) ν (fderiv ℝ (fun z => fderiv ℝ f z b) y a) + + OAI.CKSSchwarzschild.christoffelPair q (f y) (fderiv ℝ f y a) (fderiv ℝ f y b) ν) + +def meanCurvature (q : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) (ν : OAI.CKSBoundarySurface.E3) : ℝ := + let a := OAI.CKSSchwarzschild.firstFrame (q (f y)) (fderiv ℝ f y) + let b := OAI.CKSSchwarzschild.secondFrame (q (f y)) (fderiv ℝ f y) + OAI.CKSMain.secondForm q f y ν a a + OAI.CKSMain.secondForm q f y ν b b + +def tangentialTrace (q k : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) : ℝ := + let a := fderiv ℝ f y (OAI.CKSSchwarzschild.firstFrame (q (f y)) (fderiv ℝ f y)) + let b := fderiv ℝ f y (OAI.CKSSchwarzschild.secondFrame (q (f y)) (fderiv ℝ f y)) + k (f y) a a + k (f y) b b + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +structure BoundaryGeometry (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) where + normal : ∀ p : OAI.CKSBoundarySurface.Boundary N, TangentSpace OAI.CKSBoundarySurface.I3 p.val + unit : ∀ p, q.inner p.val (normal p) (normal p) = 1 + orthogonal : ∀ p a, q.inner p.val (normal p) + (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary N → N) p a) = 0 + inward : ∀ p, 0 < (show OAI.CKSBoundarySurface.E3 from normal p) 0 + chart : ∀ p : OAI.CKSBoundarySurface.Boundary N, OAI.CKSIntrinsicConstraints.ConstraintChart q.inner k p.val + normal_smooth : ∀ p, ContMDiffAt OAI.CKSBoundarySurface.I2 𝓘(ℝ,OAI.CKSBoundarySurface.E3) ∞ + (fun z : OAI.CKSBoundarySurface.Boundary N => mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) (chart p).coordinate z.val (normal z)) p + +def BoundaryGeometry.parameter {q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (B : OAI.CKSMain.BoundaryGeometry q k) (p : OAI.CKSBoundarySurface.Boundary N) : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3 := + (B.chart p).coordinate ∘ (Subtype.val : OAI.CKSBoundarySurface.Boundary N → N) ∘ (extChartAt OAI.CKSBoundarySurface.I2 p).symm + +def BoundaryGeometry.thetaPlus {q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (B : OAI.CKSMain.BoundaryGeometry q k) (p : OAI.CKSBoundarySurface.Boundary N) : ℝ := + let c := B.chart p + let f := B.parameter p + let y := (extChartAt OAI.CKSBoundarySurface.I2 p) p + let ν := mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) c.coordinate p.val (B.normal p) + OAI.CKSMain.meanCurvature c.metric f y ν + OAI.CKSMain.tangentialTrace c.metric c.tensor f y + +def MarginalBoundary (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) : Prop := + ∃ B : OAI.CKSMain.BoundaryGeometry q k, ∀ p, B.thetaPlus p = 0 + +def bondiMass {g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {K : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (d : OAI.CKSSourceExterior.CKSData g K) : ℝ := + Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2) + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology InnerProductSpace +open CKSSchwarzschild +attribute [local instance] manifold_regular +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass + + +local instance atlas_manifold_one {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] : IsManifold OAI.CKSBoundarySurface.I3 1 N := inferInstance + +local instance atlas_tangent_vectorBundle {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] : + letI := OAI.CKSMain.atlas_manifold_one (N := N) + VectorBundle ℝ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) := by + infer_instance + +abbrev CoefficientAtlas {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) := + letI := OAI.CKSMain.atlas_manifold_one (N := N) + letI := OAI.CKSMain.atlas_tangent_vectorBundle (N := N) + let metric : ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I3 ∞ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) := q + ∀ x : N, OAI.CKSIntrinsicConstraints.ConstraintChart metric.inner k x + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +structure InteriorSurface (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (A : OAI.CKSMain.CoefficientAtlas q k) (T : Type v) [TopologicalSpace T] [ChartedSpace OAI.CKSBoundarySurface.E2 T] + [IsManifold OAI.CKSBoundarySurface.I2 ∞ T] where + map : T → N + smooth : ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ map + embedding : Topology.IsEmbedding map + immersion : ∀ p, Function.Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 map p) + interior : ∀ p, map p ∈ OAI.CKSBoundarySurface.I3.interior N + normal : ∀ p, TangentSpace OAI.CKSBoundarySurface.I3 (map p) + normal_unit : ∀ p, q.inner (map p) (normal p) (normal p) = 1 + normal_orthogonal : ∀ p a, q.inner (map p) (normal p) (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 map p a) = 0 + normal_smooth : ∀ p, ContMDiffAt OAI.CKSBoundarySurface.I2 𝓘(ℝ,OAI.CKSBoundarySurface.E3) ∞ + (fun t => mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) (A (map p)).coordinate (map t) (normal t)) p + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain.InteriorSurface +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +variable {q : SmoothMetric I3 (M := N)} {k : InnerField I3 (M := N)} + {A : CoefficientAtlas q k} {T : Type v} [TopologicalSpace T] [ChartedSpace E2 T] + [IsManifold I2 ∞ T] (D : InteriorSurface q k A T) + +def parameter (p : T) : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3 := + (A (D.map p)).coordinate ∘ D.map ∘ (extChartAt OAI.CKSBoundarySurface.I2 p).symm + +def mean (p : T) : ℝ := + let c := A (D.map p) + OAI.CKSMain.meanCurvature c.metric (D.parameter p) ((extChartAt OAI.CKSBoundarySurface.I2 p) p) + (mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) c.coordinate (D.map p) (D.normal p)) + +def trace (p : T) : ℝ := + let c := A (D.map p) + OAI.CKSMain.tangentialTrace c.metric c.tensor (D.parameter p) ((extChartAt OAI.CKSBoundarySurface.I2 p) p) + +def thetaPlus (p : T) : ℝ := D.mean p + D.trace p + +def thetaMinus (p : T) : ℝ := D.mean p - D.trace p + +def SeparatesAway (c : OAI.CKSSourceExterior.CoordinateEnd (N := N)) : Prop := + ∃ B : Set N, B = closure (_root_.interior B) ∧ (_root_.interior B).Nonempty ∧ + frontier B = range D.map ∧ + ∃ r : ℝ, c.radius < r ∧ B ⊆ {x | x ∉ c.domain ∨ ‖c.coordinate x‖ ≤ r} + +def ComponentwiseApparent : Prop := + ∀ p : T, (∀ z ∈ connectedComponent p, D.thetaPlus z = 0) ∨ + (∀ z ∈ connectedComponent p, D.thetaMinus z = 0) + +end OAI.CKSMain.InteriorSurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +def NoAdditionalHorizons (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (c : OAI.CKSSourceExterior.CoordinateEnd (N := N)) (A : OAI.CKSMain.CoefficientAtlas q k) : Prop := + ∀ (T : Type v) [TopologicalSpace T] [ChartedSpace OAI.CKSBoundarySurface.E2 T] [IsManifold OAI.CKSBoundarySurface.I2 ∞ T] + [T2Space T] [SecondCountableTopology T] [CompactSpace T] [Nonempty T] + (D : OAI.CKSMain.InteriorSurface q k A T), D.SeparatesAway c → ¬ D.ComponentwiseApparent + +structure MainHypotheses [T2Space N] [SecondCountableTopology N] [ConnectedSpace N] + (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (d : OAI.CKSSourceExterior.CKSData g K) (A : OAI.CKSMain.CoefficientAtlas g K) : Prop where + smooth_tensor : ContMDiff OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSBoundarySurface.I3 K) + symmetric_tensor : ∀ x v w, K x v w = K x w v + orientable : OAI.CKSSourceExterior.Orientable (N := N) + boundary_compact : IsCompact (OAI.CKSBoundarySurface.I3.boundary N) + boundary_nonempty : (OAI.CKSBoundarySurface.I3.boundary N).Nonempty + complete : OAI.CKSReplacementCompleteness.IsComplete OAI.CKSBoundarySurface.I3 g.toContinuousRiemannianMetric + dec : OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSBoundarySurface.I3 g.inner K + timelike : ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖ < (OAI.CKSLorentz.bondiCharge d.massAspect).1 + boundary_connected : ConnectedSpace (OAI.CKSBoundarySurface.Boundary N) + boundary_marginal : OAI.CKSMain.MarginalBoundary g K + positive_area : 0 < OAI.CKSSourceExterior.minimumEnclosingArea g + no_horizons : OAI.CKSMain.NoAdditionalHorizons.{u,v} g K d.chart A + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] sixteen_atLeastTwo + + +def SchwarzschildExample (m : ℝ) (_hm : 0 < m) : Prop := + ∃ (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior)) + (d : OAI.CKSSourceExterior.CKSData g (OAI.CKSSchwarzschild.tensorInner m)) + (A : OAI.CKSMain.CoefficientAtlas g (OAI.CKSSchwarzschild.tensorInner m)), + (∀ p, g.inner p = OAI.CKSSchwarzschild.metricInner m p) ∧ + OAI.CKSMain.MainHypotheses.{0,v} g (OAI.CKSSchwarzschild.tensorInner m) d A ∧ + OAI.CKSSchwarzschild.HorizonRegularGraph m ∧ + OAI.CKSMain.bondiMass d = m ∧ + OAI.CKSSourceExterior.minimumEnclosingArea g = 16*Real.pi*m^2 ∧ + OAI.CKSMain.bondiMass d = Real.sqrt (OAI.CKSSourceExterior.minimumEnclosingArea g / (16*Real.pi)) + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +open CKSSchwarzschild + +theorem schwarzschild_equality_examples (m : ℝ) (hm : 0 < m) : + SchwarzschildExample.{v} m hm := by + sorry + +end OAI.CKSMain +end +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CKSBondiPenrose.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.CKSSourceExterior.area_controlled_end_replacement`, `OAI.CKSMain.schwarzschild_equality_examples` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cks-bondi-penrose/solution/closure.txt b/tasks/cks-bondi-penrose/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c8103368710052455568344bf3ef1e037a7ca0cf --- /dev/null +++ b/tasks/cks-bondi-penrose/solution/closure.txt @@ -0,0 +1,336 @@ +OAI.Geometry.Relativity.CKS.ADMAverage +OAI.Geometry.Relativity.CKS.ADMFlux +OAI.Geometry.Relativity.CKS.ADMTail +OAI.Geometry.Relativity.CKS.AdaptedKoszul +OAI.Geometry.Relativity.CKS.AngularCoefficientBounds +OAI.Geometry.Relativity.CKS.AngularCurvature +OAI.Geometry.Relativity.CKS.AngularDifferentiation +OAI.Geometry.Relativity.CKS.AngularFreeze +OAI.Geometry.Relativity.CKS.AngularGeometry +OAI.Geometry.Relativity.CKS.AngularSlice +OAI.Geometry.Relativity.CKS.AngularSymbols +OAI.Geometry.Relativity.CKS.AngularWeighted +OAI.Geometry.Relativity.CKS.AreaCuts +OAI.Geometry.Relativity.CKS.AreaGram +OAI.Geometry.Relativity.CKS.BendingDerivative +OAI.Geometry.Relativity.CKS.BendingFirstJet +OAI.Geometry.Relativity.CKS.BendingProfiles +OAI.Geometry.Relativity.CKS.BondiBalance +OAI.Geometry.Relativity.CKS.BondiCharge +OAI.Geometry.Relativity.CKS.BoostDivergence +OAI.Geometry.Relativity.CKS.BoostFlow +OAI.Geometry.Relativity.CKS.BoostIntegral +OAI.Geometry.Relativity.CKS.BoostSubstitution +OAI.Geometry.Relativity.CKS.BoostTransport +OAI.Geometry.Relativity.CKS.BoundaryBridge +OAI.Geometry.Relativity.CKS.BoundaryCharts +OAI.Geometry.Relativity.CKS.BoundaryFinite +OAI.Geometry.Relativity.CKS.BoundaryPartial +OAI.Geometry.Relativity.CKS.BoundaryPlane +OAI.Geometry.Relativity.CKS.BoundarySmooth +OAI.Geometry.Relativity.CKS.CKSCoefficientRealization +OAI.Geometry.Relativity.CKS.CKSCollarConcrete +OAI.Geometry.Relativity.CKS.CKSCollarCoordinates +OAI.Geometry.Relativity.CKS.CKSCollarExpansion +OAI.Geometry.Relativity.CKS.CKSCollarSourceData +OAI.Geometry.Relativity.CKS.CKSFoliationAsymptotics +OAI.Geometry.Relativity.CKS.CKSFoliationFields +OAI.Geometry.Relativity.CKS.CKSFoliationJet +OAI.Geometry.Relativity.CKS.CKSFoliationLeading +OAI.Geometry.Relativity.CKS.CKSFoliationLeadingFields +OAI.Geometry.Relativity.CKS.CKSFoliationMixed +OAI.Geometry.Relativity.CKS.CKSLeadingBound +OAI.Geometry.Relativity.CKS.CKSLogData +OAI.Geometry.Relativity.CKS.CKSMassCoefficient +OAI.Geometry.Relativity.CKS.CKSMassFields +OAI.Geometry.Relativity.CKS.CKSMassInputBounds +OAI.Geometry.Relativity.CKS.CKSMassMixed +OAI.Geometry.Relativity.CKS.CKSMetricInput +OAI.Geometry.Relativity.CKS.CKSMetricPositivity +OAI.Geometry.Relativity.CKS.CKSPhysicalCoefficients +OAI.Geometry.Relativity.CKS.CKSPhysicalMass +OAI.Geometry.Relativity.CKS.CKSPhysicalRegular +OAI.Geometry.Relativity.CKS.CKSPhysicalSmooth +OAI.Geometry.Relativity.CKS.CKSScaledBounds +OAI.Geometry.Relativity.CKS.CKSSourceFoliationAsymptotics +OAI.Geometry.Relativity.CKS.CKSSourceMass +OAI.Geometry.Relativity.CKS.CKSTensorCompact +OAI.Geometry.Relativity.CKS.CKSTensorFields +OAI.Geometry.Relativity.CKS.CKSTensorJet +OAI.Geometry.Relativity.CKS.CKSTensorMixed +OAI.Geometry.Relativity.CKS.CKSTensorRealization +OAI.Geometry.Relativity.CKS.ChartDistance +OAI.Geometry.Relativity.CKS.CollarAngularMetric +OAI.Geometry.Relativity.CKS.CollarAngularNorm +OAI.Geometry.Relativity.CKS.CollarAngularWeighted +OAI.Geometry.Relativity.CKS.CollarConeErrors +OAI.Geometry.Relativity.CKS.CollarConstraintBounded +OAI.Geometry.Relativity.CKS.CollarCutoffs +OAI.Geometry.Relativity.CKS.CollarExpansionGeometry +OAI.Geometry.Relativity.CKS.CollarExpansionInputNorm +OAI.Geometry.Relativity.CKS.CollarExpansionJet +OAI.Geometry.Relativity.CKS.CollarExpansionRealization +OAI.Geometry.Relativity.CKS.CollarExpansionWeighted +OAI.Geometry.Relativity.CKS.CollarFieldBounded +OAI.Geometry.Relativity.CKS.CollarFieldConstraint +OAI.Geometry.Relativity.CKS.CollarFieldExpansion +OAI.Geometry.Relativity.CKS.CollarFieldJets +OAI.Geometry.Relativity.CKS.CollarFieldLapse +OAI.Geometry.Relativity.CKS.CollarFieldRegion +OAI.Geometry.Relativity.CKS.CollarFieldTensor +OAI.Geometry.Relativity.CKS.CollarLapseCoefficient +OAI.Geometry.Relativity.CKS.CollarLapseJet +OAI.Geometry.Relativity.CKS.CollarLapseRealization +OAI.Geometry.Relativity.CKS.CollarLogRegular +OAI.Geometry.Relativity.CKS.CollarLogSlices +OAI.Geometry.Relativity.CKS.CollarMetricCoefficient +OAI.Geometry.Relativity.CKS.CollarMetricComparison +OAI.Geometry.Relativity.CKS.CollarMetricRealization +OAI.Geometry.Relativity.CKS.CollarMomentumBounded +OAI.Geometry.Relativity.CKS.CollarMomentumNormalization +OAI.Geometry.Relativity.CKS.CollarMomentumWeighted +OAI.Geometry.Relativity.CKS.CollarNullErrors +OAI.Geometry.Relativity.CKS.CollarNullMap +OAI.Geometry.Relativity.CKS.CollarNullNormalization +OAI.Geometry.Relativity.CKS.CollarNullRatio +OAI.Geometry.Relativity.CKS.CollarOrientation +OAI.Geometry.Relativity.CKS.CollarRadialFields +OAI.Geometry.Relativity.CKS.CollarRatioBounded +OAI.Geometry.Relativity.CKS.CollarRawCompact +OAI.Geometry.Relativity.CKS.CollarRawCurvature +OAI.Geometry.Relativity.CKS.CollarRawDEC +OAI.Geometry.Relativity.CKS.CollarRawFamily +OAI.Geometry.Relativity.CKS.CollarRawMomentum +OAI.Geometry.Relativity.CKS.CollarRawNull +OAI.Geometry.Relativity.CKS.CollarRawRatio +OAI.Geometry.Relativity.CKS.CollarRawSmallNull +OAI.Geometry.Relativity.CKS.CollarRawWeighted +OAI.Geometry.Relativity.CKS.CollarRoundReferences +OAI.Geometry.Relativity.CKS.CollarShiftJet +OAI.Geometry.Relativity.CKS.CollarSmallNullBounded +OAI.Geometry.Relativity.CKS.CollarSourceParams +OAI.Geometry.Relativity.CKS.CollarThinConstraint +OAI.Geometry.Relativity.CKS.CollarThinInputs +OAI.Geometry.Relativity.CKS.CollarThinInvariance +OAI.Geometry.Relativity.CKS.CollarThinPrimitives +OAI.Geometry.Relativity.CKS.CompactMetricCoercivity +OAI.Geometry.Relativity.CKS.ComparatorDefinitions +OAI.Geometry.Relativity.CKS.ComparatorMain +OAI.Geometry.Relativity.CKS.ConeSupport +OAI.Geometry.Relativity.CKS.ConstraintCanonical +OAI.Geometry.Relativity.CKS.ConstraintCompareInterior +OAI.Geometry.Relativity.CKS.ConstraintCoordinateCovariance +OAI.Geometry.Relativity.CKS.ConstraintDensityDefinitions +OAI.Geometry.Relativity.CKS.ConstraintGlobalIntegral +OAI.Geometry.Relativity.CKS.ConstraintInterior +OAI.Geometry.Relativity.CKS.ConstraintLocalInverse +OAI.Geometry.Relativity.CKS.ConstraintPhysicalNormalization +OAI.Geometry.Relativity.CKS.ConstraintVolumeCoordinate +OAI.Geometry.Relativity.CKS.ConstructedOuterMetric +OAI.Geometry.Relativity.CKS.CoordinateLeviCivita +OAI.Geometry.Relativity.CKS.CovariantHeat +OAI.Geometry.Relativity.CKS.CutArea +OAI.Geometry.Relativity.CKS.CutAreaDefinitions +OAI.Geometry.Relativity.CKS.CutSurface +OAI.Geometry.Relativity.CKS.DenseInterior +OAI.Geometry.Relativity.CKS.EmbeddingDerivative +OAI.Geometry.Relativity.CKS.EmbeddingOpenInterior +OAI.Geometry.Relativity.CKS.FoliationCurvatureOperator +OAI.Geometry.Relativity.CKS.FoliationFirstJet +OAI.Geometry.Relativity.CKS.FoliationFrameRegularity +OAI.Geometry.Relativity.CKS.FoliationKoszul +OAI.Geometry.Relativity.CKS.FoliationOrthonormalFrame +OAI.Geometry.Relativity.CKS.FoliationPhysicalLeaf +OAI.Geometry.Relativity.CKS.FoliationReconstruction +OAI.Geometry.Relativity.CKS.FullSphereHeat +OAI.Geometry.Relativity.CKS.HeatBase +OAI.Geometry.Relativity.CKS.HeatChart +OAI.Geometry.Relativity.CKS.HeatChartTensor +OAI.Geometry.Relativity.CKS.HeatEquation +OAI.Geometry.Relativity.CKS.HeatGenerated +OAI.Geometry.Relativity.CKS.HeatPotential +OAI.Geometry.Relativity.CKS.HeatRadial +OAI.Geometry.Relativity.CKS.HeatRegularity +OAI.Geometry.Relativity.CKS.HeatSymbols +OAI.Geometry.Relativity.CKS.HeatTensor +OAI.Geometry.Relativity.CKS.HeatUniform +OAI.Geometry.Relativity.CKS.InducedMetric +OAI.Geometry.Relativity.CKS.InducedSphereAlgebra +OAI.Geometry.Relativity.CKS.InducedSphereCalculus +OAI.Geometry.Relativity.CKS.IntrinsicEndChart +OAI.Geometry.Relativity.CKS.IntrinsicReplacementDefinitions +OAI.Geometry.Relativity.CKS.IntrinsicReplacementPackage +OAI.Geometry.Relativity.CKS.IntrinsicReplacementWithChart +OAI.Geometry.Relativity.CKS.JetBounds +OAI.Geometry.Relativity.CKS.JetPolynomial +OAI.Geometry.Relativity.CKS.JointJets +OAI.Geometry.Relativity.CKS.LocalConstraints +OAI.Geometry.Relativity.CKS.LocalMaximumHessian +OAI.Geometry.Relativity.CKS.LogPhysicalCoefficients +OAI.Geometry.Relativity.CKS.LogPhysicalFoliation +OAI.Geometry.Relativity.CKS.LogPhysicalMass +OAI.Geometry.Relativity.CKS.LogPhysicalMassJet +OAI.Geometry.Relativity.CKS.LogPhysicalTensor +OAI.Geometry.Relativity.CKS.LogRadialIdentity +OAI.Geometry.Relativity.CKS.LogRadiusJets +OAI.Geometry.Relativity.CKS.Main +OAI.Geometry.Relativity.CKS.MainDefinitions +OAI.Geometry.Relativity.CKS.MainProof +OAI.Geometry.Relativity.CKS.MassJetRealization +OAI.Geometry.Relativity.CKS.MatrixScalarJets +OAI.Geometry.Relativity.CKS.MatrixThreeJets +OAI.Geometry.Relativity.CKS.MeasureGlue +OAI.Geometry.Relativity.CKS.MetricComparisonAssembly +OAI.Geometry.Relativity.CKS.MetricPairDerivative +OAI.Geometry.Relativity.CKS.MetricSymbols +OAI.Geometry.Relativity.CKS.MixedCoefficientRealization +OAI.Geometry.Relativity.CKS.MixedFieldJets +OAI.Geometry.Relativity.CKS.MixedInputBounds +OAI.Geometry.Relativity.CKS.MixedJetCalculus +OAI.Geometry.Relativity.CKS.MixedJetPolynomial +OAI.Geometry.Relativity.CKS.MixedMassCoefficient +OAI.Geometry.Relativity.CKS.MixedMassCompact +OAI.Geometry.Relativity.CKS.MixedMassFields +OAI.Geometry.Relativity.CKS.MixedMassRealization +OAI.Geometry.Relativity.CKS.MixedMassUniform +OAI.Geometry.Relativity.CKS.MixedMatrixJets +OAI.Geometry.Relativity.CKS.MixedSqrtJet +OAI.Geometry.Relativity.CKS.MixedThreeJets +OAI.Geometry.Relativity.CKS.NonroundConstraints +OAI.Geometry.Relativity.CKS.NonroundFrame +OAI.Geometry.Relativity.CKS.NonroundMass +OAI.Geometry.Relativity.CKS.OriginalMetricEstimate +OAI.Geometry.Relativity.CKS.OuterBounds +OAI.Geometry.Relativity.CKS.OuterMetricComparison +OAI.Geometry.Relativity.CKS.OuterRealization +OAI.Geometry.Relativity.CKS.PhysicalAccelerationNorm +OAI.Geometry.Relativity.CKS.PhysicalConnectionRegularity +OAI.Geometry.Relativity.CKS.PhysicalCovariantTensor +OAI.Geometry.Relativity.CKS.PhysicalCurvatureOperator +OAI.Geometry.Relativity.CKS.PhysicalFoliationConstraints +OAI.Geometry.Relativity.CKS.PhysicalFrameBasis +OAI.Geometry.Relativity.CKS.PhysicalFrameCalculus +OAI.Geometry.Relativity.CKS.PhysicalFrameConnection +OAI.Geometry.Relativity.CKS.PhysicalFrameContractions +OAI.Geometry.Relativity.CKS.PhysicalFrameCurvature +OAI.Geometry.Relativity.CKS.PhysicalFrameTensor +OAI.Geometry.Relativity.CKS.PhysicalLeafConnection +OAI.Geometry.Relativity.CKS.PhysicalLeafTrace +OAI.Geometry.Relativity.CKS.PhysicalMomentumCoordinate +OAI.Geometry.Relativity.CKS.PhysicalMomentumCovector +OAI.Geometry.Relativity.CKS.PhysicalMomentumNorm +OAI.Geometry.Relativity.CKS.PhysicalNormalFrame +OAI.Geometry.Relativity.CKS.RadialPrimitive +OAI.Geometry.Relativity.CKS.RadialProfiles +OAI.Geometry.Relativity.CKS.RadialTail +OAI.Geometry.Relativity.CKS.RiemannianContraction +OAI.Geometry.Relativity.CKS.RoundCasimir +OAI.Geometry.Relativity.CKS.RoundReferenceJets +OAI.Geometry.Relativity.CKS.ScalarJetCalculus +OAI.Geometry.Relativity.CKS.ScalarThreeJets +OAI.Geometry.Relativity.CKS.ScaledJetOutput +OAI.Geometry.Relativity.CKS.ScaledPullback +OAI.Geometry.Relativity.CKS.ScaledThreeJetOutput +OAI.Geometry.Relativity.CKS.SchwarzschildAdvancedTime +OAI.Geometry.Relativity.CKS.SchwarzschildArea +OAI.Geometry.Relativity.CKS.SchwarzschildAreaDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildBoundary +OAI.Geometry.Relativity.CKS.SchwarzschildCKS +OAI.Geometry.Relativity.CKS.SchwarzschildCKSAlgebra +OAI.Geometry.Relativity.CKS.SchwarzschildCKSDecay +OAI.Geometry.Relativity.CKS.SchwarzschildCartesianDerivatives +OAI.Geometry.Relativity.CKS.SchwarzschildCharges +OAI.Geometry.Relativity.CKS.SchwarzschildCharts +OAI.Geometry.Relativity.CKS.SchwarzschildCompleteness +OAI.Geometry.Relativity.CKS.SchwarzschildConnection +OAI.Geometry.Relativity.CKS.SchwarzschildConnectionDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildCoordinates +OAI.Geometry.Relativity.CKS.SchwarzschildEnd +OAI.Geometry.Relativity.CKS.SchwarzschildEquality +OAI.Geometry.Relativity.CKS.SchwarzschildEqualityDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildGraphSecondForm +OAI.Geometry.Relativity.CKS.SchwarzschildHorizon +OAI.Geometry.Relativity.CKS.SchwarzschildHorizonExclusion +OAI.Geometry.Relativity.CKS.SchwarzschildHorizonExclusionDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildIntrinsicEquality +OAI.Geometry.Relativity.CKS.SchwarzschildIntrinsicHorizonDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildMetric +OAI.Geometry.Relativity.CKS.SchwarzschildMetricDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildModel +OAI.Geometry.Relativity.CKS.SchwarzschildNormalDerivative +OAI.Geometry.Relativity.CKS.SchwarzschildOrientability +OAI.Geometry.Relativity.CKS.SchwarzschildPosition +OAI.Geometry.Relativity.CKS.SchwarzschildProfile +OAI.Geometry.Relativity.CKS.SchwarzschildProjection +OAI.Geometry.Relativity.CKS.SchwarzschildRadialDecay +OAI.Geometry.Relativity.CKS.SchwarzschildRoundMetric +OAI.Geometry.Relativity.CKS.SchwarzschildSpacetimeAlgebra +OAI.Geometry.Relativity.CKS.SchwarzschildSpacetimeDefinitions +OAI.Geometry.Relativity.CKS.SchwarzschildSpacetimeDerivatives +OAI.Geometry.Relativity.CKS.SchwarzschildSpacetimeRegular +OAI.Geometry.Relativity.CKS.SchwarzschildSpherical +OAI.Geometry.Relativity.CKS.SchwarzschildStrongEquality +OAI.Geometry.Relativity.CKS.SchwarzschildVacuum +OAI.Geometry.Relativity.CKS.SchwarzschildVacuumRound +OAI.Geometry.Relativity.CKS.SchwarzschildVacuumSpherical +OAI.Geometry.Relativity.CKS.SmoothOuterDEC +OAI.Geometry.Relativity.CKS.SourceBalancedChart +OAI.Geometry.Relativity.CKS.SourceBalancedPatches +OAI.Geometry.Relativity.CKS.SourceCollarBound +OAI.Geometry.Relativity.CKS.SourceCollarMetric +OAI.Geometry.Relativity.CKS.SourceExteriorDefinitions +OAI.Geometry.Relativity.CKS.SourceFoliationLeading +OAI.Geometry.Relativity.CKS.SourceGeometry +OAI.Geometry.Relativity.CKS.SourceMassRegularity +OAI.Geometry.Relativity.CKS.SourcePhysicalFoliation +OAI.Geometry.Relativity.CKS.SourcePhysicalMass +OAI.Geometry.Relativity.CKS.SourcePhysicalTensor +OAI.Geometry.Relativity.CKS.SourceReconstruction +OAI.Geometry.Relativity.CKS.SourceReplacement +OAI.Geometry.Relativity.CKS.SourceReplacementDefinitions +OAI.Geometry.Relativity.CKS.SourceTopology +OAI.Geometry.Relativity.CKS.SphereConeAlgebra +OAI.Geometry.Relativity.CKS.SphereConeChart +OAI.Geometry.Relativity.CKS.SphereConeMeasure +OAI.Geometry.Relativity.CKS.SphereHeat +OAI.Geometry.Relativity.CKS.SphereVolume +OAI.Geometry.Relativity.CKS.SphericalCharts +OAI.Geometry.Relativity.CKS.SphericalDivergence +OAI.Geometry.Relativity.CKS.SphericalFrame +OAI.Geometry.Relativity.CKS.SphericalLaplacian +OAI.Geometry.Relativity.CKS.SphericalTensor +OAI.Geometry.Relativity.CKS.SphericalTensorChart +OAI.Geometry.Relativity.CKS.SphericalTensorIdentity +OAI.Geometry.Relativity.CKS.SurfaceBarrier +OAI.Geometry.Relativity.CKS.SurfaceChristoffel +OAI.Geometry.Relativity.CKS.SurfaceDeterminant +OAI.Geometry.Relativity.CKS.SurfaceDivergence +OAI.Geometry.Relativity.CKS.SurfaceFrames +OAI.Geometry.Relativity.CKS.SurfaceImage +OAI.Geometry.Relativity.CKS.SurfaceImageMeasure +OAI.Geometry.Relativity.CKS.SurfaceLocalImage +OAI.Geometry.Relativity.CKS.SurfaceMapDerivative +OAI.Geometry.Relativity.CKS.SurfaceNormal +OAI.Geometry.Relativity.CKS.SurfaceNormalization +OAI.Geometry.Relativity.CKS.SurfaceParameter +OAI.Geometry.Relativity.CKS.SurfaceScaling +OAI.Geometry.Relativity.CKS.SurfaceVolume +OAI.Geometry.Relativity.CKS.SurfaceVolumeGlobalLower +OAI.Geometry.Relativity.CKS.SurfaceVolumeLower +OAI.Geometry.Relativity.CKS.TailConstraints +OAI.Geometry.Relativity.CKS.TailDifferentiation +OAI.Geometry.Relativity.CKS.TailEnergy +OAI.Geometry.Relativity.CKS.TailSymbols +OAI.Geometry.Relativity.CKS.TailTensor +OAI.Geometry.Relativity.CKS.Transfer +OAI.Geometry.Relativity.CKS.TransferDefinitions +OAI.Geometry.Relativity.CKS.VolumeAlgebra +OAI.Geometry.Relativity.CKS.VolumeCompatibility +OAI.Geometry.Relativity.CKS.VolumeCoordinate +OAI.Geometry.Relativity.CKS.VolumeDefinitions +OAI.Geometry.Relativity.CKS.VolumeExistence +OAI.Geometry.Relativity.CKS.VolumeMeasurable +OAI.Geometry.Relativity.CKS.VolumeRegularity +OAI.Geometry.Relativity.CKS.VolumeTransition +OAI.Geometry.Relativity.CKS.VolumeUnique +OAI.Geometry.Relativity.CKS.WeightedArea diff --git a/tasks/cks-bondi-penrose/solution/reference.py b/tasks/cks-bondi-penrose/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cks-bondi-penrose/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cks-bondi-penrose/solution/solve.sh b/tasks/cks-bondi-penrose/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ccc8fb691ffc7fa48b8cec911753ebd4fda899b6 --- /dev/null +++ b/tasks/cks-bondi-penrose/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CKSBondiPenrose, i.e. module OAI.Geometry.Relativity.CKS.ComparatorMain and the +# 336 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.Relativity.CKS.ComparatorMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CKSBondiPenrose" diff --git a/tasks/cks-bondi-penrose/task.toml b/tasks/cks-bondi-penrose/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ea11c52f21e2796b205d5b9a9ca0d54baddad517 --- /dev/null +++ b/tasks/cks-bondi-penrose/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cks-bondi-penrose" +version = "1.0.0" +description = "Prove CKSBondiPenrose (openai/math family 260: Spacetime Penrose inequalities and rigidity) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CKSBondiPenrose.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CKSBondiPenrose" +family = "260" +family_title = "Spacetime Penrose inequalities and rigidity" +subject = "Mathematical physics" +theorems = ["OAI.CKSSourceExterior.area_controlled_end_replacement", "OAI.CKSMain.schwarzschild_equality_examples"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.Relativity.CKS.ComparatorMain" +reference_modules = 336 +reference_lean_bytes = 2829003 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1456 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14246 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cks-bondi-penrose/tests/Challenge.lean b/tasks/cks-bondi-penrose/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6d896eef2d884e4da89b68a37afe7d67cb011b3 --- /dev/null +++ b/tasks/cks-bondi-penrose/tests/Challenge.lean @@ -0,0 +1,3596 @@ +import Mathlib + +/-! Area-controlled end replacement and Schwarzschild equality examples. -/ + +namespace OAI.CKSADM +end OAI.CKSADM +namespace OAI.CKSAngularGeometry +end OAI.CKSAngularGeometry +namespace OAI.CKSAngularSlice +end OAI.CKSAngularSlice +namespace OAI.CKSBoundarySurface +end OAI.CKSBoundarySurface +namespace OAI.CKSCalculus +end OAI.CKSCalculus +namespace OAI.CKSCartesianOuter +end OAI.CKSCartesianOuter +namespace OAI.CKSEmbeddingDerivative +end OAI.CKSEmbeddingDerivative +namespace OAI.CKSFullCutArea +end OAI.CKSFullCutArea +namespace OAI.CKSGeometricCuts +end OAI.CKSGeometricCuts +namespace OAI.CKSInducedArea +end OAI.CKSInducedArea +namespace OAI.CKSInducedSphere +end OAI.CKSInducedSphere +namespace OAI.CKSIntrinsicConstraints +end OAI.CKSIntrinsicConstraints +namespace OAI.CKSIntrinsicGeometry +end OAI.CKSIntrinsicGeometry +namespace OAI.CKSIntrinsicVolume +end OAI.CKSIntrinsicVolume +namespace OAI.CKSLocalBending +end OAI.CKSLocalBending +namespace OAI.CKSLorentz +end OAI.CKSLorentz +namespace OAI.CKSLorentz.SmoothAngularPatch +end OAI.CKSLorentz.SmoothAngularPatch +namespace OAI.CKSMain +end OAI.CKSMain +namespace OAI.CKSMain.InteriorSurface +end OAI.CKSMain.InteriorSurface +namespace OAI.CKSMetricGluing +end OAI.CKSMetricGluing +namespace OAI.CKSMixedGeometry +end OAI.CKSMixedGeometry +namespace OAI.CKSMixedGeometry.FiniteLogDecay +end OAI.CKSMixedGeometry.FiniteLogDecay +namespace OAI.CKSRealizedRound +end OAI.CKSRealizedRound +namespace OAI.CKSReplacementCompleteness +end OAI.CKSReplacementCompleteness +namespace OAI.CKSRound +end OAI.CKSRound +namespace OAI.CKSRound.MetricJet +end OAI.CKSRound.MetricJet +namespace OAI.CKSSchwarzschild +end OAI.CKSSchwarzschild +namespace OAI.CKSSourceExterior +end OAI.CKSSourceExterior +namespace OAI.CKSSpatialManifold +end OAI.CKSSpatialManifold +namespace OAI.CKSSphericalHarmonics +end OAI.CKSSphericalHarmonics +namespace OAI.CKSSurfaceVolume +end OAI.CKSSurfaceVolume +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold + + +local instance real_id_isometric : RingHomIsometric (RingHom.id ℝ) := inferInstance + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMetricGluing +open Bundle Manifold Set Bornology +open scoped Bundle Manifold ContDiff +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSMetricGluing +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMetricGluing +open Bundle Manifold Set Bornology +open scoped Bundle Manifold ContDiff +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_2} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_3} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_continuousAdd + + +abbrev InnerField := + letI := OAI.CKSMetricGluing.real_smulCommClass + letI := OAI.CKSMetricGluing.real_continuousConstSMul + ∀ x : M, TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ + +abbrev SmoothMetric := ContMDiffRiemannianMetric I ∞ E (fun x : M => TangentSpace I x) + +def innerSection (q : OAI.CKSMetricGluing.InnerField I (M := M)) : + M → TotalSpace (E →L[ℝ] E →L[ℝ] ℝ) + (fun x : M => TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) := + fun x => ⟨x,q x⟩ + +end OAI.CKSMetricGluing +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev I := Fin 2 + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSCalculus +open Filter Set +open scoped Topology ContDiff +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + +def D (e : E) (f : E → ℝ) (x : E) : ℝ := fderiv ℝ f x e + +end OAI.CKSCalculus +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound + + +abbrev Idx := Fin 3 + +abbrev Mat := Matrix OAI.CKSRound.Idx OAI.CKSRound.Idx ℝ + +structure MetricJet where + inv : OAI.CKSRound.Mat + d : OAI.CKSRound.Idx → OAI.CKSRound.Mat + dd : OAI.CKSRound.Idx → OAI.CKSRound.Idx → OAI.CKSRound.Mat + +end OAI.CKSRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound.MetricJet + + +def gamma (j : OAI.CKSRound.MetricJet) (a i k : OAI.CKSRound.Idx) : ℝ := + (∑ l, j.inv a l * (j.d i k l + j.d k i l - j.d l i k)) / 2 + +def dInv (j : OAI.CKSRound.MetricJet) (s a b : OAI.CKSRound.Idx) : ℝ := + - ∑ i, ∑ k, j.inv a i * j.d s i k * j.inv k b + +def dGamma (j : OAI.CKSRound.MetricJet) (s a i k : OAI.CKSRound.Idx) : ℝ := + (∑ l, (j.dInv s a l * (j.d i k l + j.d k i l - j.d l i k) + + j.inv a l * (j.dd s i k l + j.dd s k i l - j.dd s l i k))) / 2 + +def ricci (j : OAI.CKSRound.MetricJet) (i k : OAI.CKSRound.Idx) : ℝ := + (∑ a, (j.dGamma a a i k - j.dGamma k a i a)) + + ∑ a, ∑ b, (j.gamma a a b * j.gamma b i k - j.gamma a k b * j.gamma b i a) + +def scalar (j : OAI.CKSRound.MetricJet) : ℝ := ∑ i, ∑ k, j.inv i k * j.ricci i k + +end OAI.CKSRound.MetricJet +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound + + +structure TensorJet where + val : OAI.CKSRound.Mat + d : OAI.CKSRound.Idx → OAI.CKSRound.Mat + +end OAI.CKSRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRound.MetricJet + + +def trace (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ a, ∑ b, g.inv a b * k.val a b + +def normSq (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ a, ∑ b, ∑ c, ∑ d, g.inv a c * g.inv b d * k.val a b * k.val c d + +def dTrace (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + ∑ a, ∑ b, (g.dInv i a b * k.val a b + g.inv a b * k.d i a b) + +def tensorDivergence (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + ∑ a, ∑ b, g.inv a b * (k.d a b i - + (∑ c, g.gamma c a b * k.val c i) - (∑ c, g.gamma c a i * k.val b c)) + +def energy (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + (g.scalar + g.trace k ^ 2 - g.normSq k) / 2 + +def momentum (g : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) (i : OAI.CKSRound.Idx) : ℝ := + g.tensorDivergence k i - g.dTrace k i + +end OAI.CKSRound.MetricJet +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSRealizedRound +open CKSCalculus CKSRound +open scoped Topology ContDiff + +abbrev Point := Fin 3 → ℝ + +def basis (a : OAI.CKSRound.Idx) : OAI.CKSRealizedRound.Point := Pi.single a 1 + +end OAI.CKSRealizedRound +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLocalBending +open CKSRound + +def momentumSq (j : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : ℝ := + ∑ i, ∑ l, j.inv i l * j.momentum k i * j.momentum k l + +def DEC (j : OAI.CKSRound.MetricJet) (k : OAI.CKSRound.TensorJet) : Prop := + Real.sqrt (OAI.CKSLocalBending.momentumSq j k) ≤ j.energy k + +end OAI.CKSLocalBending +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev Point := OAI.CKSAngularGeometry.I → ℝ + +def basis (a : OAI.CKSAngularGeometry.I) : OAI.CKSAngularGeometry.Point := Pi.single a 1 + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open CKSCalculus Set Filter Matrix +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev AmbientMat := Matrix (Fin 3) (Fin 3) ℝ + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Matrix CKSCalculus +open scoped BigOperators + +abbrev PhysicalPoint := Fin 3 → ℝ + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev I := Fin 3 + +abbrev A := Fin 2 + +abbrev Point := OAI.CKSMixedGeometry.I → ℝ + +def basis (a : OAI.CKSMixedGeometry.I) : OAI.CKSMixedGeometry.Point := Pi.single a 1 + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal + +local instance pointDimension_neZero : NeZero (3 : ℕ) := inferInstance + +def radialFactor (a : OAI.CKSMixedGeometry.I) (y : OAI.CKSMixedGeometry.Point) : ℝ := + letI := OAI.CKSMixedGeometry.pointDimension_neZero + if a = 0 then y 0 else 1 + +def scaledD (a : OAI.CKSMixedGeometry.I) (f : OAI.CKSMixedGeometry.Point → ℝ) : OAI.CKSMixedGeometry.Point → ℝ := + fun y => OAI.CKSMixedGeometry.radialFactor a y * OAI.CKSCalculus.D (OAI.CKSMixedGeometry.basis a) f y + +def scaledIter : List OAI.CKSMixedGeometry.I → (OAI.CKSMixedGeometry.Point → ℝ) → OAI.CKSMixedGeometry.Point → ℝ + | [], f => f + | a::l,f => OAI.CKSMixedGeometry.scaledD a (scaledIter l f) + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open CKSCalculus Set Filter +open scoped Topology ContDiff NNReal Matrix.Norms.Elementwise + +abbrev Angle := OAI.CKSMixedGeometry.A → ℝ + +def angularProjection : OAI.CKSMixedGeometry.Point →L[ℝ] OAI.CKSMixedGeometry.Angle := + ContinuousLinearMap.pi (fun a => ContinuousLinearMap.proj a.succ) + +def ScaledComponentBound (f : OAI.CKSMixedGeometry.Point → ℝ) (j q : ℕ) (B : ℝ) (y : OAI.CKSMixedGeometry.Point) : Prop := + letI := OAI.CKSMixedGeometry.pointDimension_neZero + ∀ l : List OAI.CKSMixedGeometry.I, l.length ≤ j → |scaledIter l f y| ≤ B/(y 0)^q + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Finset + +abbrev Ix := Fin 3 + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial + +abbrev Ambient := EuclideanSpace ℝ (Fin 3) + +abbrev Sphere := ↥(Metric.sphere (0 : OAI.CKSSphericalHarmonics.Ambient) 1) + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial +open MeasureTheory + +abbrev surfaceMeasure : Measure OAI.CKSSphericalHarmonics.Sphere := (volume : Measure OAI.CKSSphericalHarmonics.Ambient).toSphere + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSphericalHarmonics +open MvPolynomial +open MeasureTheory +open scoped Pointwise +open scoped Manifold ContDiff Topology +open Set + +def SmoothSphere (f : OAI.CKSSphericalHarmonics.Sphere → ℝ) : Prop := ContMDiff (𝓡 2) 𝓘(ℝ, ℝ) ∞ f + +end OAI.CKSSphericalHarmonics +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz + + +local instance two_atLeastTwo : Nat.AtLeastTwo 2 := inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Set Filter Finset +open scoped Topology ContDiff + +abbrev E := EuclideanSpace ℝ OAI.CKSInducedSphere.Ix + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedSphere +open Set Filter Finset +open scoped Topology ContDiff +attribute [local instance] CKSLorentz.two_atLeastTwo + + +def e (i : OAI.CKSInducedSphere.Ix) : OAI.CKSInducedSphere.E := WithLp.toLp 2 (Pi.single i 1) + +def pd (i : OAI.CKSInducedSphere.Ix) (F : OAI.CKSInducedSphere.E → ℝ) (x : OAI.CKSInducedSphere.E) : ℝ := fderiv ℝ F x (OAI.CKSInducedSphere.e i) + +end OAI.CKSInducedSphere +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped InnerProductSpace RealInnerProductSpace ContDiff Manifold Topology +open Set + +abbrev E := EuclideanSpace ℝ (Fin 3) + +abbrev V := ℝ × OAI.CKSLorentz.E + +abbrev Sphere := ↥(Metric.sphere (0 : OAI.CKSLorentz.E) 1) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +local instance pointDimension_neZero : NeZero (3 : ℕ) := inferInstance + +def ordinaryLeadingComponent (q : ℕ) (M : OAI.CKSMixedGeometry.Angle → ℝ) (y : OAI.CKSMixedGeometry.Point) : ℝ := + letI := OAI.CKSLorentz.pointDimension_neZero + 1/(y 0)^q * M (OAI.CKSMixedGeometry.angularProjection y) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMixedGeometry +open Set +open scoped ContDiff + +structure SourceRemainderOn (j q : ℕ) (V : Set OAI.CKSMixedGeometry.Point) (f : OAI.CKSMixedGeometry.Point → ℝ) : Prop where + regular : ∀ y ∈ V, ContDiffAt ℝ j f y + bound : ∃ B : ℝ, 0 ≤ B ∧ ∀ y ∈ V, OAI.CKSMixedGeometry.ScaledComponentBound f j q B y + +end OAI.CKSMixedGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure SourceCKSComponents (j qrad : ℕ) (V : Set OAI.CKSMixedGeometry.Point) + (A : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ) (mr : OAI.CKSMixedGeometry.Angle → ℝ) (mg : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ) : Prop where + radial : OAI.CKSMixedGeometry.SourceRemainderOn j qrad V (fun y => A 0 0 y-OAI.CKSLorentz.ordinaryLeadingComponent 5 mr y) + mixed : ∀ i k, (i=0 ∧ k≠0) ∨ (i≠0 ∧ k=0) → OAI.CKSMixedGeometry.SourceRemainderOn j 3 V (A i k) + angular : ∀ i k, i≠0 → k≠0 → OAI.CKSMixedGeometry.SourceRemainderOn j 2 V + (fun y => A i k y-OAI.CKSLorentz.ordinaryLeadingComponent 1 (mg i k) y) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set + +def angularRadialTail (R : ℝ) (W : Set OAI.CKSMixedGeometry.Angle) : Set OAI.CKSMixedGeometry.Point := + letI := OAI.CKSLorentz.pointDimension_neZero + {y | R < y 0 ∧ OAI.CKSMixedGeometry.angularProjection y ∈ W} + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure SmoothAngularPatch where + chart : OpenPartialHomeomorph OAI.CKSLorentz.Sphere OAI.CKSMixedGeometry.Angle + param_smooth : ContDiffOn ℝ ∞ (fun θ => (chart.symm θ : OAI.CKSLorentz.E)) chart.target + extension : OAI.CKSLorentz.E → OAI.CKSMixedGeometry.Angle + domain : Set OAI.CKSLorentz.E + isOpen_domain : IsOpen domain + extension_smooth : ContDiffOn ℝ ∞ extension domain + source_domain : ∀ n ∈ chart.source, (n:OAI.CKSLorentz.E) ∈ domain + extension_eq : ∀ n ∈ chart.source, extension n = chart n + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz.SmoothAngularPatch +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +def param (P : OAI.CKSLorentz.SmoothAngularPatch) (θ : OAI.CKSMixedGeometry.Angle) : OAI.CKSLorentz.E := P.chart.symm θ + +def sphereRegion (P : OAI.CKSLorentz.SmoothAngularPatch) (W : Set OAI.CKSMixedGeometry.Angle) : Set OAI.CKSLorentz.Sphere := + P.chart.source ∩ P.chart ⁻¹' W + +end OAI.CKSLorentz.SmoothAngularPatch +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set +open scoped ContDiff Topology + +structure CKSTensorPatch where + patch : OAI.CKSLorentz.SmoothAngularPatch + region : Set OAI.CKSMixedGeometry.Angle + open_region : IsOpen region + region_target : region ⊆ patch.chart.target + radius : ℝ + metric : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ + second : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Point → ℝ + mr : OAI.CKSMixedGeometry.Angle → ℝ + mg : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ + mK : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ + mr_smooth : ContDiffOn ℝ ∞ mr region + mg_smooth : ∀ i k, i≠0 → k≠0 → ContDiffOn ℝ ∞ (mg i k) region + mK_smooth : ∀ i k, i≠0 → k≠0 → ContDiffOn ℝ ∞ (mK i k) region + metric_CKS : OAI.CKSLorentz.SourceCKSComponents 3 6 (OAI.CKSLorentz.angularRadialTail radius region) metric mr mg + second_CKS : OAI.CKSLorentz.SourceCKSComponents 2 5 (OAI.CKSLorentz.angularRadialTail radius region) second (fun _ => 0) mK + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice +attribute [local instance] real_continuousAdd + + +abbrev SpatialBilinear := + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_continuousConstSMul + OAI.CKSLorentz.E →L[ℝ] OAI.CKSLorentz.E →L[ℝ] ℝ + +abbrev SpatialTensor := OAI.CKSLorentz.E → OAI.CKSLorentz.SpatialBilinear + +local instance three_neZero : NeZero 3 := inferInstance + +def polarParam (P : OAI.CKSLorentz.SmoothAngularPatch) (y : OAI.CKSMixedGeometry.Point) : OAI.CKSLorentz.E := + letI := OAI.CKSLorentz.three_neZero + y 0 • P.param (OAI.CKSMixedGeometry.angularProjection y) + +def polarTensorComponents (P : OAI.CKSLorentz.SmoothAngularPatch) (A : OAI.CKSLorentz.SpatialTensor) + (i k : OAI.CKSMixedGeometry.I) (y : OAI.CKSMixedGeometry.Point) : ℝ := + A (OAI.CKSLorentz.polarParam P y) (fderiv ℝ (OAI.CKSLorentz.polarParam P) y (OAI.CKSMixedGeometry.basis i)) + (fderiv ℝ (OAI.CKSLorentz.polarParam P) y (OAI.CKSMixedGeometry.basis k)) + +def CKSTensorPatch.Realizes (Q : OAI.CKSLorentz.CKSTensorPatch) (A B : OAI.CKSLorentz.SpatialTensor) : Prop := + ∀ y ∈ OAI.CKSLorentz.angularRadialTail Q.radius Q.region, ∀ i k, + Q.metric i k y = OAI.CKSLorentz.polarTensorComponents Q.patch A i k y ∧ + Q.second i k y = OAI.CKSLorentz.polarTensorComponents Q.patch B i k y + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice CKSCalculus + +abbrev AngularMatrix := Matrix (Fin 2) (Fin 2) ℝ + +def angularMetricTrace (σ A : OAI.CKSLorentz.AngularMatrix) : ℝ := (σ⁻¹ * A).trace + +def angularRoundMetric (φ : OAI.CKSMixedGeometry.Angle → OAI.CKSLorentz.E) (θ : OAI.CKSMixedGeometry.Angle) : OAI.CKSLorentz.AngularMatrix := + letI := OAI.CKSLorentz.two_atLeastTwo + letI : Inner ℝ OAI.CKSLorentz.E := + @InnerProductSpace.toInner ℝ OAI.CKSLorentz.E _ + (PiLp.seminormedAddCommGroup 2 (fun _ : Fin 3 => ℝ)) + (PiLp.innerProductSpace (fun _ : Fin 3 => ℝ)) + fun a b => inner ℝ (fderiv ℝ φ θ (OAI.CKSAngularGeometry.basis a)) + (fderiv ℝ φ θ (OAI.CKSAngularGeometry.basis b)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped RealInnerProductSpace ContDiff Manifold Topology +open MeasureTheory +open CKSSphericalHarmonics (SmoothSphere surfaceMeasure) + +def nullDirection (n : OAI.CKSLorentz.Sphere) : OAI.CKSLorentz.V := (1,(n:OAI.CKSLorentz.E)) + +def rawCharge (M : OAI.CKSLorentz.Sphere → ℝ) : OAI.CKSLorentz.V := ∫ n : OAI.CKSLorentz.Sphere, M n • OAI.CKSLorentz.nullDirection n ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +def bondiCharge (M : OAI.CKSLorentz.Sphere → ℝ) : OAI.CKSLorentz.V := (16*Real.pi)⁻¹ • OAI.CKSLorentz.rawCharge M + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry + +local instance real_isTopologicalAddGroup : IsTopologicalAddGroup ℝ := inferInstance + +local instance spatialDual_isTopologicalAddGroup : IsTopologicalAddGroup (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_smulCommClass : + letI := OAI.CKSLorentz.real_smulCommClass + SMulCommClass ℝ ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_continuousConstSMul : ContinuousConstSMul ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + inferInstance + +local instance spatialDual_isScalarTower : IsScalarTower ℝ ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := inferInstance + +local instance spatialDual_continuousSMul : ContinuousSMul ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := inferInstance + +def hyperbolicField (x : OAI.CKSLorentz.E) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSLorentz.spatialDual_isTopologicalAddGroup + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + letI := OAI.CKSLorentz.spatialDual_isScalarTower + letI := OAI.CKSLorentz.spatialDual_continuousSMul + let f : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + f - (1/(1+‖x‖^2)) • (f x).smulRight (f x) + +def sourceSpatial (A : OAI.CKSLorentz.SpatialTensor) : OAI.CKSLorentz.SpatialTensor := fun x => OAI.CKSLorentz.hyperbolicField x + A x + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped ContDiff +attribute [local instance] CKSSpatialManifold.real_id_isometric real_smulCommClass spatialDual_smulCommClass + + +local instance hsgNorm : NormedAddCommGroup OAI.CKSLorentz.SpatialBilinear := + let dualSpace : NormedSpace ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E ℝ _ _ _ _ _ _ (RingHom.id ℝ) + OAI.CKSSpatialManifold.real_id_isometric ℝ _ _ OAI.CKSLorentz.real_smulCommClass + @ContinuousLinearMap.toNormedAddCommGroup ℝ ℝ OAI.CKSLorentz.E (OAI.CKSLorentz.E →L[ℝ] ℝ) + _ _ _ _ _ dualSpace (RingHom.id ℝ) OAI.CKSSpatialManifold.real_id_isometric + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open scoped ContDiff +attribute [local instance] CKSSpatialManifold.real_id_isometric real_smulCommClass spatialDual_smulCommClass +attribute [local instance] OAI.CKSLorentz.hsgNorm + + +local instance hsgSpace : NormedSpace ℝ OAI.CKSLorentz.SpatialBilinear := + let dualSpace : NormedSpace ℝ (OAI.CKSLorentz.E →L[ℝ] ℝ) := + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E ℝ _ _ _ _ _ _ (RingHom.id ℝ) + OAI.CKSSpatialManifold.real_id_isometric ℝ _ _ OAI.CKSLorentz.real_smulCommClass + @ContinuousLinearMap.toNormedSpace ℝ ℝ OAI.CKSLorentz.E (OAI.CKSLorentz.E →L[ℝ] ℝ) + _ _ _ _ _ dualSpace (RingHom.id ℝ) OAI.CKSSpatialManifold.real_id_isometric + ℝ _ dualSpace OAI.CKSLorentz.spatialDual_smulCommClass + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSADM +open Finset CKSInducedSphere +open scoped RealInnerProductSpace ContDiff + +def normal (x : OAI.CKSInducedSphere.E) (i : OAI.CKSInducedSphere.Ix) : ℝ := x i / ‖x‖ + +end OAI.CKSADM +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSADM +open Set Filter Finset CKSSphericalHarmonics CKSInducedSphere +open scoped Topology ContDiff + +def spatialInfinity : Filter OAI.CKSInducedSphere.E := Filter.comap (fun x : OAI.CKSInducedSphere.E => ‖x‖) atTop + +def TailRegular (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + ∀ᶠ x in OAI.CKSADM.spatialInfinity, ContDiffAt ℝ ∞ F x + +def Decay (d : ℝ) (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ᶠ x in OAI.CKSADM.spatialInfinity, |F x| ≤ C*‖x‖^(-d) + +def SymbolN : ℕ → ℝ → (OAI.CKSInducedSphere.E → ℝ) → Prop + | 0, d, F => OAI.CKSADM.Decay d F + | n+1, d, F => OAI.CKSADM.Decay d F ∧ ∀ j : OAI.CKSInducedSphere.Ix, SymbolN n (d+1) (OAI.CKSInducedSphere.pd j F) + +def Symbol (d : ℝ) (F : OAI.CKSInducedSphere.E → ℝ) : Prop := + OAI.CKSADM.TailRegular F ∧ ∀ n : ℕ, OAI.CKSADM.SymbolN n d F + +end OAI.CKSADM +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSAngularGeometry +open Matrix CKSCalculus Filter +open scoped BigOperators Topology ContDiff Matrix.Norms.Elementwise + +def physicalMetricJet (G : OAI.CKSAngularGeometry.PhysicalPoint → OAI.CKSAngularGeometry.AmbientMat) (x : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSRound.MetricJet where + inv := (G x)⁻¹ + d := fun a i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (fun y => G y i j) x + dd := fun a b i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis b) (fun y => G y i j)) x + +def physicalTensorJet (K : OAI.CKSAngularGeometry.PhysicalPoint → OAI.CKSAngularGeometry.AmbientMat) (x : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSRound.TensorJet where + val := K x + d := fun a i j => OAI.CKSCalculus.D (OAI.CKSRealizedRound.basis a) (fun y => K y i j) x + +end OAI.CKSAngularGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSCartesianOuter +open Set Filter Matrix CKSADM CKSInducedSphere CKSSphericalHarmonics +open CKSAngularGeometry (PhysicalPoint) +open scoped Topology ContDiff Matrix.Norms.Elementwise + +abbrev toPoint : OAI.CKSInducedSphere.E ≃L[ℝ] OAI.CKSAngularGeometry.PhysicalPoint := EuclideanSpace.equiv (Fin 3) ℝ + +end OAI.CKSCartesianOuter +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice CKSCalculus + +def cksChartMassAspect (φ : OAI.CKSMixedGeometry.Angle → OAI.CKSLorentz.E) (mr : OAI.CKSMixedGeometry.Angle → ℝ) + (mg mK : OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.I → OAI.CKSMixedGeometry.Angle → ℝ) (θ : OAI.CKSMixedGeometry.Angle) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + OAI.CKSLorentz.angularMetricTrace (OAI.CKSLorentz.angularRoundMetric φ θ) + (fun a b => mg a.succ b.succ θ + 2*mK a.succ b.succ θ) + 2*mr θ + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry + +def spatialCoefficients (A : OAI.CKSLorentz.SpatialTensor) (y : OAI.CKSAngularGeometry.PhysicalPoint) : OAI.CKSAngularGeometry.AmbientMat := + fun i j => A (OAI.CKSCartesianOuter.toPoint.symm y) + (OAI.CKSCartesianOuter.toPoint.symm (OAI.CKSMixedGeometry.basis i)) + (OAI.CKSCartesianOuter.toPoint.symm (OAI.CKSMixedGeometry.basis j)) + +def spatialDEC (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : Prop := + OAI.CKSLocalBending.DEC (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)) + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularSlice Set + +def CKSTensorPatch.RepresentsMassAspect (Q : OAI.CKSLorentz.CKSTensorPatch) (M : OAI.CKSLorentz.Sphere → ℝ) : Prop := + ∀ n ∈ Q.patch.sphereRegion Q.region, + OAI.CKSLorentz.cksChartMassAspect Q.patch.param Q.mr Q.mg Q.mK (Q.patch.chart n) = M n + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry CKSInducedSphere CKSSphericalHarmonics MeasureTheory + +def spatialCartesian (A : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : OAI.CKSAngularGeometry.AmbientMat := + OAI.CKSLorentz.spatialCoefficients A (OAI.CKSCartesianOuter.toPoint x) + +local instance sixteen_atLeastTwo : Nat.AtLeastTwo 16 := inferInstance + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry CKSInducedSphere CKSSphericalHarmonics MeasureTheory +attribute [local instance] sixteen_atLeastTwo + + +def spatialADMEnergy (A : OAI.CKSLorentz.SpatialTensor) (r : ℝ) : ℝ := + r^2/(16*Real.pi) * ∫ n : OAI.CKSLorentz.Sphere, + ∑ i : Fin 3, (∑ j : Fin 3, + (OAI.CKSInducedSphere.pd j (fun y => OAI.CKSLorentz.spatialCartesian A y i j) (r • (n:OAI.CKSLorentz.E)) - + OAI.CKSInducedSphere.pd i (fun y => OAI.CKSLorentz.spatialCartesian A y j j) (r • (n:OAI.CKSLorentz.E)))) * + OAI.CKSADM.normal (r • (n:OAI.CKSLorentz.E)) i ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +def spatialADMMomentum (A B : OAI.CKSLorentz.SpatialTensor) (r : ℝ) : Fin 3 → ℝ := fun i => + r^2/(8*Real.pi) * ∫ n : OAI.CKSLorentz.Sphere, + ∑ j : Fin 3, (OAI.CKSLorentz.spatialCartesian B (r • (n:OAI.CKSLorentz.E)) i j - + (∑ a : Fin 3, ∑ b : Fin 3, + (OAI.CKSLorentz.spatialCartesian A (r • (n:OAI.CKSLorentz.E)))⁻¹ a b * OAI.CKSLorentz.spatialCartesian B (r • (n:OAI.CKSLorentz.E)) a b) * + OAI.CKSLorentz.spatialCartesian A (r • (n:OAI.CKSLorentz.E)) i j) * OAI.CKSADM.normal (r • (n:OAI.CKSLorentz.E)) j ∂OAI.CKSSphericalHarmonics.surfaceMeasure + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSLorentz +open CKSMixedGeometry CKSAngularGeometry MeasureTheory + +def spatialEnergy (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSLorentz.E) : ℝ := + (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)).energy + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x)) + +end OAI.CKSLorentz +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSReplacementCompleteness +open Bundle Manifold +open scoped Bundle Manifold ENNReal +variable {E : Type u_1} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_2} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_3} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric E (fun x : M => TangentSpace I x) + +local instance metric_isContinuousRiemannianBundle (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : + letI : RiemannianBundle (fun x : M => TangentSpace I x) := ⟨g.toRiemannianMetric⟩ + IsContinuousRiemannianBundle E (fun x : M => TangentSpace I x) := inferInstance + +@[instance_reducible] def metricSpace [T3Space M] (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : EMetricSpace M := + letI : RiemannianBundle (fun x : M => TangentSpace I x) := ⟨g.toRiemannianMetric⟩ + letI := OAI.CKSReplacementCompleteness.metric_isContinuousRiemannianBundle I g + EMetricSpace.ofRiemannianMetric I M + +def IsComplete [T3Space M] (g : OAI.CKSReplacementCompleteness.Metric I (M := M)) : Prop := + @CompleteSpace M (OAI.CKSReplacementCompleteness.metricSpace I g).toUniformSpace + +end OAI.CKSReplacementCompleteness +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSGeometricCuts +open Set Manifold MeasureTheory Bundle CKSReplacementCompleteness +open scoped ENNReal Manifold Bundle ContDiff + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero + +end OAI.CKSGeometricCuts +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSGeometricCuts +open Set Manifold MeasureTheory Bundle CKSReplacementCompleteness +open scoped ENNReal Manifold Bundle ContDiff +variable (M : Type u) [TopologicalSpace M] [ChartedSpace H3 M] [IsManifold I3 1 M] + +structure OuterDomain where + Carrier : Type u + topology : TopologicalSpace Carrier + charts : @ChartedSpace OAI.CKSGeometricCuts.H3 _ Carrier topology + smooth : @IsManifold ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 (∞ : ℕ∞ω) Carrier topology charts + inclusion : Carrier → M + embedding : @IsSmoothEmbedding ℝ _ OAI.CKSGeometricCuts.E3 OAI.CKSGeometricCuts.E3 _ _ _ _ OAI.CKSGeometricCuts.H3 OAI.CKSGeometricCuts.H3 _ _ OAI.CKSGeometricCuts.I3 OAI.CKSGeometricCuts.I3 + Carrier M topology charts _ _ ∞ inclusion + closed : IsClosed (range inclusion) + connected : IsConnected (range inclusion) + contains_distant_end : ∃ K : Set M, IsCompact K ∧ Kᶜ ⊆ range inclusion + interior_into : inclusion '' (@ModelWithCorners.interior ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 + Carrier topology charts) ⊆ OAI.CKSGeometricCuts.I3.interior M + compact_boundary : IsCompact (inclusion '' (@ModelWithCorners.boundary ℝ _ OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 _ OAI.CKSGeometricCuts.I3 + Carrier topology charts)) + +end OAI.CKSGeometricCuts +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Bornology Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_id_isometric CKSMetricGluing.real_continuousAdd CKSMetricGluing.real_continuousConstSMul CKSMetricGluing.real_smulCommClass + + +local instance real_id_compTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Bornology Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type u_1} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_2} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] real_id_isometric CKSMetricGluing.real_continuousAdd CKSMetricGluing.real_continuousConstSMul CKSMetricGluing.real_smulCommClass + + +def endInner (f : M → OAI.CKSLorentz.E) (A : OAI.CKSLorentz.SpatialTensor) : OAI.CKSMetricGluing.InnerField I (M := M) := fun x => by + letI := OAI.CKSSpatialManifold.real_id_isometric + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI : NormedAddCommGroup (TangentSpace I x) := by unfold TangentSpace; infer_instance + letI : NormedSpace ℝ (TangentSpace I x) := by unfold TangentSpace; infer_instance + let df : TangentSpace I x →L[ℝ] OAI.CKSLorentz.E := + (NormedSpace.fromTangentSpace (f x)).toContinuousLinearMap.comp (mfderiv I 𝓘(ℝ,OAI.CKSLorentz.E) f x) + exact (A (f x)).bilinearComp df df + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSpatialManifold +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped Bundle Manifold ContDiff Topology +variable {H : Type u_1} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_2} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] CKSLorentz.hsgNorm CKSLorentz.hsgSpace + + +def PhysicalDECAt (g : OAI.CKSMetricGluing.InnerField I (M := M)) (K : OAI.CKSMetricGluing.InnerField I (M := M)) (x : M) : Prop := + ∃ (V : Set M) (f : M → OAI.CKSLorentz.E) (A B : OAI.CKSLorentz.SpatialTensor), + IsOpen V ∧ x ∈ V ∧ ContMDiffOn I 𝓘(ℝ,OAI.CKSLorentz.E) ∞ f V ∧ + (∀ y ∈ V, Function.Bijective (mfderiv I 𝓘(ℝ,OAI.CKSLorentz.E) f y)) ∧ + (∀ y ∈ V, ContDiffAt ℝ ∞ A (f y) ∧ ContDiffAt ℝ ∞ B (f y)) ∧ + (∀ y ∈ V, (∀ v w, A (f y) v w = A (f y) w v) ∧ + (∀ v : OAI.CKSLorentz.E, v ≠ 0 → 0 < A (f y) v v) ∧ + (∀ v w, B (f y) v w = B (f y) w v)) ∧ + (∀ y ∈ V, g y = OAI.CKSSpatialManifold.endInner I f A y ∧ K y = OAI.CKSSpatialManifold.endInner I f B y) ∧ + OAI.CKSLorentz.spatialDEC A B (f x) + +def PhysicalDEC (g : OAI.CKSMetricGluing.InnerField I (M := M)) (K : OAI.CKSMetricGluing.InnerField I (M := M)) : Prop := + ∀ x : M, OAI.CKSSpatialManifold.PhysicalDECAt I g K x + +end OAI.CKSSpatialManifold +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicGeometry +open Bundle Bornology Set MeasureTheory Manifold Filter Metric +open scoped ENNReal ContDiff Topology NNReal + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSIntrinsicGeometry.halfSpaceDimension_neZero + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicGeometry.halfSpaceDimension_neZero + +end OAI.CKSIntrinsicGeometry +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology + +abbrev E2 := EuclideanSpace ℝ (Fin 2) + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H3 := @EuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero + +abbrev I2 := 𝓘(ℝ,OAI.CKSBoundarySurface.E2) + +abbrev I3 := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero + +local instance two_atLeastTwo : Nat.AtLeastTwo 2 := inferInstance + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] two_atLeastTwo + + +def insertNormalZero (point : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.E3 := WithLp.toLp 2 (Fin.cons 0 point) + +def liftPlane : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3 := + have proof_insertNormalZero_add_0 (first second : OAI.CKSBoundarySurface.E2) : + OAI.CKSBoundarySurface.insertNormalZero (first + second) = OAI.CKSBoundarySurface.insertNormalZero first + OAI.CKSBoundarySurface.insertNormalZero second := by + ext index + cases index using Fin.cases <;> simp [OAI.CKSBoundarySurface.insertNormalZero] + have proof_insertNormalZero_smul_1 (scalar : ℝ) (point : OAI.CKSBoundarySurface.E2) : + OAI.CKSBoundarySurface.insertNormalZero (scalar • point) = scalar • OAI.CKSBoundarySurface.insertNormalZero point := by + ext index + cases index using Fin.cases <;> simp [OAI.CKSBoundarySurface.insertNormalZero] + have proof_insertNormalZero_continuous_2 : Continuous OAI.CKSBoundarySurface.insertNormalZero := by + apply (PiLp.continuous_toLp 2 (fun _ : Fin 3 => ℝ)).comp + apply continuous_pi + intro index + cases index using Fin.cases with + | zero => exact continuous_const + | succ index => exact PiLp.continuous_apply 2 (fun _ : Fin 2 => ℝ) index + { + toFun := OAI.CKSBoundarySurface.insertNormalZero + map_add' := proof_insertNormalZero_add_0 + map_smul' := proof_insertNormalZero_smul_1 + cont := proof_insertNormalZero_continuous_2 + } + +def tangentialCoordinates (point : OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := WithLp.toLp 2 (fun index => point index.succ) + +def dropPlane : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E2 := + have proof_tangentialCoordinates_add_3 (first second : OAI.CKSBoundarySurface.E3) : + OAI.CKSBoundarySurface.tangentialCoordinates (first + second) = + OAI.CKSBoundarySurface.tangentialCoordinates first + OAI.CKSBoundarySurface.tangentialCoordinates second := by + ext index + simp [OAI.CKSBoundarySurface.tangentialCoordinates] + have proof_tangentialCoordinates_smul_4 (scalar : ℝ) (point : OAI.CKSBoundarySurface.E3) : + OAI.CKSBoundarySurface.tangentialCoordinates (scalar • point) = scalar • OAI.CKSBoundarySurface.tangentialCoordinates point := by + ext index + simp [OAI.CKSBoundarySurface.tangentialCoordinates] + have proof_tangentialCoordinates_continuous_5 : Continuous OAI.CKSBoundarySurface.tangentialCoordinates := by + apply (PiLp.continuous_toLp 2 (fun _ : Fin 2 => ℝ)).comp + exact continuous_pi fun index => PiLp.continuous_apply 2 (fun _ : Fin 3 => ℝ) index.succ + { + toFun := OAI.CKSBoundarySurface.tangentialCoordinates + map_add' := proof_tangentialCoordinates_add_3 + map_smul' := proof_tangentialCoordinates_smul_4 + cont := proof_tangentialCoordinates_continuous_5 + } + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology + +def liftHalf (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.H3 := + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + ⟨OAI.CKSBoundarySurface.liftPlane z, by simp [*]⟩ + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface + +abbrev Radial := {t : ℝ // 0 ≤ t} + +abbrev Sphere := Metric.sphere (0 : OAI.CKSBoundarySurface.E3) 1 + +abbrev Exterior := OAI.CKSSchwarzschild.Radial × OAI.CKSSchwarzschild.Sphere + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface +attribute [local instance] Classical.propDecidable + + +local instance real_id_invPair : RingHomInvPair (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +def join : (ℝ × OAI.CKSBoundarySurface.E2) →L[ℝ] OAI.CKSBoundarySurface.E3 := + letI := OAI.CKSSchwarzschild.real_id_invPair + letI := OAI.CKSBoundarySurface.two_atLeastTwo + let continuousLinearMap : ((ℝ × OAI.CKSBoundarySurface.E2) →ₗ[ℝ] OAI.CKSBoundarySurface.E3) ≃ₗ[ℝ] ((ℝ × OAI.CKSBoundarySurface.E2) →L[ℝ] OAI.CKSBoundarySurface.E3) := + LinearMap.toContinuousLinearMap + continuousLinearMap { + toFun := fun z => WithLp.toLp 2 (Fin.cons z.1 z.2) + map_add' := by intro a b; ext i; cases i using Fin.cases <;> simp + map_smul' := by intro a b; ext i; cases i using Fin.cases <;> simp } + +def halfProduct : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2 ≃ₜ OAI.CKSBoundarySurface.H3 := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_join_drop_8 (z : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.join (z 0,OAI.CKSBoundarySurface.dropPlane z) = z := by + ext i; cases i using Fin.cases <;> rfl + have proof_drop_join_11 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSSchwarzschild.join z) = z.2 := by ext i; rfl + letI := OAI.CKSBoundarySurface.halfSpaceDimension_neZero + { toFun z := ⟨OAI.CKSSchwarzschild.join (z.1.val,z.2),z.1.property⟩ + invFun z := (⟨z.val 0,z.property⟩,OAI.CKSBoundarySurface.dropPlane z.val) + left_inv z := by cases z; simp [*] + right_inv z := by apply Subtype.ext; exact proof_join_drop_8 _ + continuous_toFun := (OAI.CKSSchwarzschild.join.continuous.comp + ((continuous_subtype_val.comp continuous_fst).prodMk continuous_snd)).subtype_mk _ + continuous_invFun := ((by fun_prop : Continuous (fun z : H3 => z.val 0)).subtype_mk _).prodMk + (OAI.CKSBoundarySurface.dropPlane.continuous.comp continuous_subtype_val) } + +def productChart (s : OAI.CKSSchwarzschild.Sphere) : OpenPartialHomeomorph OAI.CKSSchwarzschild.Exterior OAI.CKSBoundarySurface.H3 := + ((OpenPartialHomeomorph.refl OAI.CKSSchwarzschild.Radial).prod (chartAt OAI.CKSBoundarySurface.E2 s)).trans OAI.CKSSchwarzschild.halfProduct.toOpenPartialHomeomorph + +instance exteriorChartedSpace : ChartedSpace OAI.CKSBoundarySurface.H3 OAI.CKSSchwarzschild.Exterior := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_halfProduct_val_12 (z : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2) : (OAI.CKSSchwarzschild.halfProduct z).val = OAI.CKSSchwarzschild.join (z.1.val,z.2) := rfl + have proof_halfProduct_symm_fst_13 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).1.val = z.val 0 := rfl + have proof_halfProduct_symm_snd_14 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).2 = OAI.CKSBoundarySurface.dropPlane z.val := rfl + { + atlas := range OAI.CKSSchwarzschild.productChart + chartAt p := OAI.CKSSchwarzschild.productChart p.2 + mem_chart_source p := by simp [*, OAI.CKSSchwarzschild.productChart,mem_chart_source OAI.CKSBoundarySurface.E2 p.2] + chart_mem_atlas p := mem_range_self _ + } + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Manifold Bundle Filter +open scoped ContDiff Topology +open CKSBoundarySurface +attribute [local instance] halfSpaceDimension_neZero + + +instance exteriorIsManifold : IsManifold OAI.CKSBoundarySurface.I3 ∞ OAI.CKSSchwarzschild.Exterior := + have proof_join_zero_9 (z : ℝ × OAI.CKSBoundarySurface.E2) : OAI.CKSSchwarzschild.join z 0 = z.1 := rfl + have proof_join_succ_10 (z : ℝ × OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSSchwarzschild.join z i.succ = z.2 i := rfl + have proof_halfProduct_val_12 (z : OAI.CKSSchwarzschild.Radial × OAI.CKSBoundarySurface.E2) : (OAI.CKSSchwarzschild.halfProduct z).val = OAI.CKSSchwarzschild.join (z.1.val,z.2) := rfl + have proof_halfProduct_symm_fst_13 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).1.val = z.val 0 := rfl + have proof_halfProduct_symm_snd_14 (z : OAI.CKSBoundarySurface.H3) : (OAI.CKSSchwarzschild.halfProduct.symm z).2 = OAI.CKSBoundarySurface.dropPlane z.val := rfl + have proof_productChart_target_17 (s : OAI.CKSSchwarzschild.Sphere) : + (OAI.CKSSchwarzschild.productChart s).target = (fun z : OAI.CKSBoundarySurface.H3 => OAI.CKSBoundarySurface.dropPlane z.val) ⁻¹' (chartAt OAI.CKSBoundarySurface.E2 s).target := by + ext p; simp [*, OAI.CKSSchwarzschild.productChart] + have proof_productChart_source_18 (s : OAI.CKSSchwarzschild.Sphere) : + (OAI.CKSSchwarzschild.productChart s).source = Prod.snd ⁻¹' (chartAt OAI.CKSBoundarySurface.E2 s).source := by + ext p; simp [*, OAI.CKSSchwarzschild.productChart] + have proof_productChart_symm_19 (s : OAI.CKSSchwarzschild.Sphere) (z : OAI.CKSBoundarySurface.H3) : + (OAI.CKSSchwarzschild.productChart s).symm z = (⟨z.val 0,z.property⟩,(chartAt OAI.CKSBoundarySurface.E2 s).symm (OAI.CKSBoundarySurface.dropPlane z.val)) := rfl + have proof_transition_source_20 (a b : OAI.CKSSchwarzschild.Sphere) : + ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source = + (fun z : OAI.CKSBoundarySurface.H3 => OAI.CKSBoundarySurface.dropPlane z.val) ⁻¹' ((chartAt OAI.CKSBoundarySurface.E2 a).symm ≫ₕ chartAt OAI.CKSBoundarySurface.E2 b).source := by + ext z + simp only [OpenPartialHomeomorph.trans_source,OpenPartialHomeomorph.symm_source, + mem_inter_iff,mem_preimage,proof_productChart_target_17,proof_productChart_source_18,proof_productChart_symm_19] + have proof_transition_maps_15 (a b : OAI.CKSSchwarzschild.Sphere) : + MapsTo OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm ⁻¹' ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source ∩ range OAI.CKSBoundarySurface.I3) + ((extChartAt OAI.CKSBoundarySurface.I2 a).symm ≫ extChartAt OAI.CKSBoundarySurface.I2 b).source := by + intro z hz + have he : (OAI.CKSBoundarySurface.I3.symm z).val = z := OAI.CKSBoundarySurface.I3.right_inv hz.2 + have h := hz.1 + rw [proof_transition_source_20] at h + change OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm z).val ∈ ((chartAt OAI.CKSBoundarySurface.E2 a).symm ≫ₕ chartAt OAI.CKSBoundarySurface.E2 b).source at h + rw [he] at h + simpa only [OAI.CKSBoundarySurface.I2,extChartAt_model_space_eq_id,mfld_simps] using h + have proof_transition_formula_16 (a b : OAI.CKSSchwarzschild.Sphere) {z : OAI.CKSBoundarySurface.E3} (hz : z ∈ range OAI.CKSBoundarySurface.I3) : + OAI.CKSBoundarySurface.I3 (((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b) (OAI.CKSBoundarySurface.I3.symm z)) = + OAI.CKSSchwarzschild.join (z 0,((extChartAt OAI.CKSBoundarySurface.I2 a).symm ≫ extChartAt OAI.CKSBoundarySurface.I2 b) (OAI.CKSBoundarySurface.dropPlane z)) := by + have he : (OAI.CKSBoundarySurface.I3.symm z).val = z := OAI.CKSBoundarySurface.I3.right_inv hz + change OAI.CKSSchwarzschild.join ((OAI.CKSBoundarySurface.I3.symm z).val 0, + chartAt OAI.CKSBoundarySurface.E2 b ((chartAt OAI.CKSBoundarySurface.E2 a).symm (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3.symm z).val))) = _ + rw [he] + rfl + by + apply isManifold_of_contDiffOn + rintro e e' ⟨a,rfl⟩ ⟨b,rfl⟩ + change ContDiffOn ℝ ∞ + (fun z => OAI.CKSBoundarySurface.I3 (((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b) (OAI.CKSBoundarySurface.I3.symm z))) + (OAI.CKSBoundarySurface.I3.symm ⁻¹' ((OAI.CKSSchwarzschild.productChart a).symm ≫ₕ OAI.CKSSchwarzschild.productChart b).source ∩ range OAI.CKSBoundarySurface.I3) + have hs := (contDiffOn_ext_coord_change (I := OAI.CKSBoundarySurface.I2) (n := ∞) b a).comp + OAI.CKSBoundarySurface.dropPlane.contDiff.contDiffOn (proof_transition_maps_15 a b) + have h0 : ContDiff ℝ ∞ (fun z : OAI.CKSBoundarySurface.E3 => z 0) := by fun_prop + apply (OAI.CKSSchwarzschild.join.contDiff.comp_contDiffOn (h0.contDiffOn.prodMk hs)).congr + intro z hz + exact proof_transition_formula_16 a b hz.2 + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology +open CKSBoundarySurface + +def height (p : OAI.CKSSchwarzschild.Exterior) : ℝ := p.1.val + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle Function +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + + +def radius (m : ℝ) (p : OAI.CKSSchwarzschild.Exterior) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 2*m+OAI.CKSSchwarzschild.height p + +def directionAmbient (p : OAI.CKSSchwarzschild.Exterior) : OAI.CKSBoundarySurface.E3 := p.2.val + +def position (m : ℝ) (p : OAI.CKSSchwarzschild.Exterior) : OAI.CKSBoundarySurface.E3 := OAI.CKSSchwarzschild.radius m p • OAI.CKSSchwarzschild.directionAmbient p + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter +open scoped ContDiff Topology + +def velocity (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo; + -1 + (r+1)*Real.smoothTransition (r-2*m-1) + +def lapseSquared (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 1-2*m/r+(OAI.CKSSchwarzschild.velocity m r)^2 + +def lapse (m r : ℝ) : ℝ := Real.sqrt (OAI.CKSSchwarzschild.lapseSquared m r) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Manifold Bundle Set Filter CKSLorentz CKSMetricGluing CKSSpatialManifold +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +def euclideanForm : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + +def radialUnit (x : OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E3 := ‖x‖⁻¹ • x + +local instance real_isScalarTower : IsScalarTower ℝ ℝ ℝ := inferInstance + +def radialForm (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI := OAI.CKSSpatialManifold.real_id_isometric + letI := OAI.CKSSchwarzschild.real_isScalarTower + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + let innerForm : OAI.CKSLorentz.SpatialBilinear := innerSL ℝ + (ContinuousLinearMap.mul ℝ ℝ).bilinearComp + (innerForm (OAI.CKSSchwarzschild.radialUnit x)) (innerForm (OAI.CKSSchwarzschild.radialUnit x)) + +local instance spatialDual_continuousAdd : ContinuousAdd (OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) := inferInstance + +def cartMetric (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSSchwarzschild.spatialDual_continuousAdd + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + OAI.CKSSchwarzschild.euclideanForm + ((OAI.CKSSchwarzschild.lapseSquared m ‖x‖)⁻¹-1) • OAI.CKSSchwarzschild.radialForm x + +def cartTensor (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSLorentz.SpatialBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSSchwarzschild.spatialDual_continuousAdd + letI := OAI.CKSLorentz.spatialDual_smulCommClass + letI := OAI.CKSLorentz.spatialDual_continuousConstSMul + (OAI.CKSSchwarzschild.velocity m ‖x‖ / ‖x‖) • OAI.CKSSchwarzschild.euclideanForm + + (deriv (OAI.CKSSchwarzschild.velocity m) ‖x‖ / OAI.CKSSchwarzschild.lapseSquared m ‖x‖ - OAI.CKSSchwarzschild.velocity m ‖x‖ / ‖x‖) • OAI.CKSSchwarzschild.radialForm x + +def metricInner (m : ℝ) : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior) := OAI.CKSSpatialManifold.endInner OAI.CKSBoundarySurface.I3 (OAI.CKSSchwarzschild.position m) (OAI.CKSSchwarzschild.cartMetric m) + +def tensorInner (m : ℝ) : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior) := OAI.CKSSpatialManifold.endInner OAI.CKSBoundarySurface.I3 (OAI.CKSSchwarzschild.position m) (OAI.CKSSchwarzschild.cartTensor m) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology + +abbrev E := OAI.CKSLorentz.E + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology +attribute [local instance] halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +def coordinateMomentumNorm (A B : OAI.CKSLorentz.SpatialTensor) (x : OAI.CKSIntrinsicConstraints.E) : ℝ := + Real.sqrt (OAI.CKSLocalBending.momentumSq + (OAI.CKSAngularGeometry.physicalMetricJet (OAI.CKSLorentz.spatialCoefficients A) (OAI.CKSCartesianOuter.toPoint x)) + (OAI.CKSAngularGeometry.physicalTensorJet (OAI.CKSLorentz.spatialCoefficients B) (OAI.CKSCartesianOuter.toPoint x))) + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Bundle Manifold Set Filter CKSLorentz CKSMetricGluing +open scoped ContDiff Topology +attribute [local instance] halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +structure ConstraintChart (g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)) (x : M) where + domain : Set M + coordinate : M → OAI.CKSIntrinsicConstraints.E + metric : OAI.CKSLorentz.SpatialTensor + tensor : OAI.CKSLorentz.SpatialTensor + isOpen : IsOpen domain + mem : x ∈ domain + smooth : ContMDiffOn OAI.CKSIntrinsicConstraints.I 𝓘(ℝ,OAI.CKSIntrinsicConstraints.E) ∞ coordinate domain + fullRank : ∀ y ∈ domain, Function.Bijective (mfderiv OAI.CKSIntrinsicConstraints.I 𝓘(ℝ,OAI.CKSIntrinsicConstraints.E) coordinate y) + coefficientSmooth : + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.spatialDual_smulCommClass + ∀ y ∈ domain, + ContDiffAt ℝ ∞ metric (coordinate y) ∧ ContDiffAt ℝ ∞ tensor (coordinate y) + positiveSymmetric : ∀ y ∈ domain, + (∀ v w, metric (coordinate y) v w = metric (coordinate y) w v) ∧ + (∀ v : OAI.CKSIntrinsicConstraints.E, v ≠ 0 → 0 < metric (coordinate y) v v) ∧ + (∀ v w, tensor (coordinate y) v w = tensor (coordinate y) w v) + represents : ∀ y ∈ domain, + g y = OAI.CKSSpatialManifold.endInner OAI.CKSIntrinsicConstraints.I coordinate metric y ∧ + K y = OAI.CKSSpatialManifold.endInner OAI.CKSIntrinsicConstraints.I coordinate tensor y + +def ConstraintChart.energy {g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)} {x : M} + (c : OAI.CKSIntrinsicConstraints.ConstraintChart g K x) : ℝ := OAI.CKSLorentz.spatialEnergy c.metric c.tensor (c.coordinate x) + +def ConstraintChart.momentumNorm {g K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)} {x : M} + (c : OAI.CKSIntrinsicConstraints.ConstraintChart g K x) : ℝ := OAI.CKSIntrinsicConstraints.coordinateMomentumNorm c.metric c.tensor (c.coordinate x) + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero + + +abbrev E := EuclideanSpace ℝ (Fin 3) + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSIntrinsicConstraints.halfSpaceDimension_neZero + +abbrev basis (i : Fin 3) : OAI.CKSIntrinsicVolume.E := EuclideanSpace.single i 1 + +local instance model_finiteDimensional : FiniteDimensional ℝ OAI.CKSIntrinsicVolume.E := inferInstance + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +attribute [local instance] model_finiteDimensional + + +local instance model_borelSpace : BorelSpace OAI.CKSIntrinsicVolume.E := inferInstance + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric OAI.CKSIntrinsicVolume.E (fun x : M => TangentSpace OAI.CKSIntrinsicVolume.I x) + +def chartFrame (x : M) (y : OAI.CKSIntrinsicVolume.E) : OAI.CKSIntrinsicVolume.E →L[ℝ] TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) := + mfderivWithin 𝓘(ℝ,OAI.CKSIntrinsicVolume.E) OAI.CKSIntrinsicVolume.I (extChartAt OAI.CKSIntrinsicVolume.I x).symm (range OAI.CKSIntrinsicVolume.I) y + +def chartMatrix (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) (y : OAI.CKSIntrinsicVolume.E) : Matrix (Fin 3) (Fin 3) ℝ := + letI := OAI.CKSMetricGluing.real_continuousAdd + letI := OAI.CKSMetricGluing.real_continuousConstSMul + letI := OAI.CKSMetricGluing.real_smulCommClass + let form : TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) →L[ℝ] + TangentSpace OAI.CKSIntrinsicVolume.I ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) →L[ℝ] ℝ := + g.inner ((extChartAt OAI.CKSIntrinsicVolume.I x).symm y) + fun first second => form (OAI.CKSIntrinsicVolume.chartFrame x y (OAI.CKSIntrinsicVolume.basis first)) (OAI.CKSIntrinsicVolume.chartFrame x y (OAI.CKSIntrinsicVolume.basis second)) + +def chartDensity (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) (y : OAI.CKSIntrinsicVolume.E) : ℝ := + Real.sqrt (OAI.CKSIntrinsicVolume.chartMatrix g x y).det + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] +attribute [local instance] model_finiteDimensional model_borelSpace +variable [MeasurableSpace M] [BorelSpace M] + +def localVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (x : M) : Measure M := + Measure.map (extChartAt OAI.CKSIntrinsicVolume.I x).symm + ((volume.restrict (extChartAt OAI.CKSIntrinsicVolume.I x).target).withDensity + (fun y => ENNReal.ofReal (OAI.CKSIntrinsicVolume.chartDensity g x y))) + +def IsVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) (ν : Measure M) : Prop := + ∀ x : M, ν.restrict (extChartAt OAI.CKSIntrinsicVolume.I x).source = OAI.CKSIntrinsicVolume.localVolume g x + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] +variable [IsManifold I 1 M] + +def riemannianVolume (g : OAI.CKSIntrinsicVolume.Metric (M := M)) : Measure M := Classical.epsilon (fun ν => OAI.CKSIntrinsicVolume.IsVolume g ν) + +end OAI.CKSIntrinsicVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] Classical.propDecidable +variable {M : Type u_2} [TopologicalSpace M] [ChartedSpace H3 M] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 halfSpaceDimension_neZero) I3 ∞ M _ _] + +abbrev Boundary (M : Type u_2) [TopologicalSpace M] [ChartedSpace OAI.CKSBoundarySurface.H3 M] := + @ModelWithCorners.boundary ℝ _ OAI.CKSBoundarySurface.E3 _ _ OAI.CKSBoundarySurface.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero) OAI.CKSBoundarySurface.I3 M _ _ + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter +open scoped ContDiff Topology +attribute [local instance] Classical.propDecidable +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H3 M] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 halfSpaceDimension_neZero) I3 ∞ M _ _] + +def boundaryInverse (x : OAI.CKSBoundarySurface.Boundary M) (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.Boundary M := + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + if hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target then + ⟨(chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z),proof_boundaryInverse_mem_21 x hz⟩ else x + +def boundaryChart (x : OAI.CKSBoundarySurface.Boundary M) : OpenPartialHomeomorph (OAI.CKSBoundarySurface.Boundary M) OAI.CKSBoundarySurface.E2 := + have proof_lift_drop_30 {z : OAI.CKSBoundarySurface.E3} (hz : z 0 = 0) : OAI.CKSBoundarySurface.liftPlane (OAI.CKSBoundarySurface.dropPlane z) = z := by + ext i + cases i using Fin.cases with + | zero => exact hz.symm + | succ i => rfl + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_liftHalf_drop_chart_26 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) (y : OAI.CKSBoundarySurface.Boundary M) (hy : y.val ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + OAI.CKSBoundarySurface.liftHalf (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y.val))) = chartAt OAI.CKSBoundarySurface.H3 x y.val := by + apply Subtype.ext + exact proof_lift_drop_30 ((proof_boundary_iff_zero_24 x y.val hy).mp y.property) + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + have proof_boundaryInverse_val_27 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_dropPlane_apply_31 (z : OAI.CKSBoundarySurface.E3) (i : Fin 2) : OAI.CKSBoundarySurface.dropPlane z i = z i.succ := rfl + have proof_drop_lift_28 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane z) = z := by ext i; rfl + have proof_liftHalf_continuous_29 : Continuous OAI.CKSBoundarySurface.liftHalf := + OAI.CKSBoundarySurface.liftPlane.continuous.subtype_mk (fun _ => by simp [*]) + { + toFun y := OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val y.val)) + invFun := OAI.CKSBoundarySurface.boundaryInverse x + source := Subtype.val ⁻¹' (chartAt OAI.CKSBoundarySurface.H3 x.val).source + target := OAI.CKSBoundarySurface.liftHalf ⁻¹' (chartAt OAI.CKSBoundarySurface.H3 x.val).target + map_source' := by + intro y hy + change OAI.CKSBoundarySurface.liftHalf (OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val y.val))) ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target + rw [proof_liftHalf_drop_chart_26 x.val y hy] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_source hy + map_target' := by + intro z hz + change (OAI.CKSBoundarySurface.boundaryInverse x z).val ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).source + rw [proof_boundaryInverse_val_27 x hz] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_target hz + left_inv' := by + intro y hy + have h := proof_liftHalf_drop_chart_26 x.val y hy + apply Subtype.ext + rw [proof_boundaryInverse_val_27 x (by rw [h]; exact (chartAt OAI.CKSBoundarySurface.H3 x.val).map_source hy),h] + exact (chartAt OAI.CKSBoundarySurface.H3 x.val).left_inv hy + right_inv' := by + intro z hz + rw [proof_boundaryInverse_val_27 x hz,(chartAt OAI.CKSBoundarySurface.H3 x.val).right_inv hz,proof_I3_liftHalf_23,proof_drop_lift_28] + open_source := (chartAt OAI.CKSBoundarySurface.H3 x.val).open_source.preimage continuous_subtype_val + open_target := (chartAt OAI.CKSBoundarySurface.H3 x.val).open_target.preimage proof_liftHalf_continuous_29 + continuousOn_toFun := OAI.CKSBoundarySurface.dropPlane.continuous.comp_continuousOn + (OAI.CKSBoundarySurface.I3.continuous.comp_continuousOn ((chartAt OAI.CKSBoundarySurface.H3 x.val).continuousOn.comp + continuous_subtype_val.continuousOn (fun _ h => h))) + continuousOn_invFun := by + apply Topology.IsInducing.subtypeVal.continuousOn_iff.mpr + apply ((chartAt OAI.CKSBoundarySurface.H3 x.val).continuousOn_symm.comp + proof_liftHalf_continuous_29.continuousOn (fun _ h => h)).congr + intro z hz + exact proof_boundaryInverse_val_27 x hz + } + +instance boundaryChartedSpace : ChartedSpace OAI.CKSBoundarySurface.E2 (OAI.CKSBoundarySurface.Boundary M) where + atlas := range OAI.CKSBoundarySurface.boundaryChart + chartAt := OAI.CKSBoundarySurface.boundaryChart + mem_chart_source x := mem_chart_source OAI.CKSBoundarySurface.H3 x.val + chart_mem_atlas x := mem_range_self x + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSBoundarySurface +open Set Manifold Bundle Filter Function +open scoped ContDiff Topology +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H3 M] [IsManifold I3 ∞ M] + +instance boundaryIsManifold : IsManifold OAI.CKSBoundarySurface.I2 ∞ (OAI.CKSBoundarySurface.Boundary M) := + have proof_lift_mem_ext_target_34 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] [IsManifold OAI.CKSBoundarySurface.I3 ∞ M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + OAI.CKSBoundarySurface.liftPlane z ∈ (extChartAt OAI.CKSBoundarySurface.I3 x).target := by + change OAI.CKSBoundarySurface.liftPlane z ∈ ((chartAt OAI.CKSBoundarySurface.H3 x).extend OAI.CKSBoundarySurface.I3).target + rw [OpenPartialHomeomorph.extend_target'] + exact ⟨OAI.CKSBoundarySurface.liftHalf z,hz,rfl⟩ + have proof_ext_symm_lift_35 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] [IsManifold OAI.CKSBoundarySurface.I3 ∞ M] (x : M) (z : OAI.CKSBoundarySurface.E2) : + (extChartAt OAI.CKSBoundarySurface.I3 x).symm (OAI.CKSBoundarySurface.liftPlane z) = (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) := by + change (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.I3.symm (OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z))) = _ + rw [OAI.CKSBoundarySurface.I3.left_inv] + have proof_boundary_chart_zero_22 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_24 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_22 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_25 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_24 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_21 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_25 x.val hz + have proof_boundaryInverse_val_27 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_boundaryChart_symm_val_36 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := + proof_boundaryInverse_val_27 x hz + have proof_transition_lift_maps_32 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : OAI.CKSBoundarySurface.Boundary M) : + MapsTo OAI.CKSBoundarySurface.liftPlane ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source + ((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm ≫ extChartAt OAI.CKSBoundarySurface.I3 y.val).source := by + intro z hz + change z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target ∧ (OAI.CKSBoundarySurface.boundaryChart x).symm z ∈ (OAI.CKSBoundarySurface.boundaryChart y).source at hz + refine ⟨proof_lift_mem_ext_target_34 x.val hz.1, ?_⟩ + change (extChartAt OAI.CKSBoundarySurface.I3 x.val).symm (OAI.CKSBoundarySurface.liftPlane z) ∈ (extChartAt OAI.CKSBoundarySurface.I3 y.val).source + rw [proof_ext_symm_lift_35] + have h := hz.2 + change ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val ∈ (chartAt OAI.CKSBoundarySurface.H3 y.val).source at h + rw [proof_boundaryChart_symm_val_36 x hz.1] at h + simpa only [extChartAt_source] using h + have proof_transition_formula_33 {M : Type u_1} [instLocal1 : TopologicalSpace.{u_1} M] [instLocal2 : ChartedSpace.{0, u_1} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u_1} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : z ∈ ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y) z = + OAI.CKSBoundarySurface.dropPlane (((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm ≫ extChartAt OAI.CKSBoundarySurface.I3 y.val) (OAI.CKSBoundarySurface.liftPlane z)) := by + change OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 y.val ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val)) = _ + rw [proof_boundaryChart_symm_val_36 x hz.1] + change _ = OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 y.val ((extChartAt OAI.CKSBoundarySurface.I3 x.val).symm (OAI.CKSBoundarySurface.liftPlane z)))) + rw [proof_ext_symm_lift_35] + by + apply isManifold_of_contDiffOn + rintro e e' ⟨x,rfl⟩ ⟨y,rfl⟩ + change ContDiffOn ℝ ∞ (fun z => ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y) z) + (id ⁻¹' ((OAI.CKSBoundarySurface.boundaryChart x).symm ≫ₕ OAI.CKSBoundarySurface.boundaryChart y).source ∩ range id) + rw [preimage_id,range_id,inter_univ] + apply (OAI.CKSBoundarySurface.dropPlane.contDiff.comp_contDiffOn ((contDiffOn_ext_coord_change (I := OAI.CKSBoundarySurface.I3) y.val x.val).comp + OAI.CKSBoundarySurface.liftPlane.contDiff.contDiffOn (proof_transition_lift_maps_32 x y))).congr + intro z hz + exact proof_transition_formula_33 x y hz + +end OAI.CKSBoundarySurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal + +abbrev E := EuclideanSpace ℝ (Fin 2) + +abbrev H := OAI.CKSSurfaceVolume.E + +abbrev I := 𝓘(ℝ,OAI.CKSSurfaceVolume.E) + +abbrev basis (i : Fin 2) : OAI.CKSSurfaceVolume.E := EuclideanSpace.single i 1 + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +abbrev Metric := ContinuousRiemannianMetric OAI.CKSSurfaceVolume.E (fun x : M => TangentSpace OAI.CKSSurfaceVolume.I x) + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] + +def chartFrame (x : M) (y : OAI.CKSSurfaceVolume.E) : OAI.CKSSurfaceVolume.E →L[ℝ] TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) := + mfderivWithin 𝓘(ℝ,OAI.CKSSurfaceVolume.E) OAI.CKSSurfaceVolume.I (extChartAt OAI.CKSSurfaceVolume.I x).symm (range OAI.CKSSurfaceVolume.I) y + +def chartMatrix (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) (y : OAI.CKSSurfaceVolume.E) : Matrix (Fin 2) (Fin 2) ℝ := + letI := OAI.CKSSurfaceVolume.real_continuousAdd + letI := OAI.CKSSurfaceVolume.real_continuousConstSMul + letI := OAI.CKSSurfaceVolume.real_smulCommClass + let inner : TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) →L[ℝ] + TangentSpace OAI.CKSSurfaceVolume.I ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) →L[ℝ] ℝ := + g.inner ((extChartAt OAI.CKSSurfaceVolume.I x).symm y) + fun i j => inner (OAI.CKSSurfaceVolume.chartFrame x y (OAI.CKSSurfaceVolume.basis i)) + (OAI.CKSSurfaceVolume.chartFrame x y (OAI.CKSSurfaceVolume.basis j)) + +def chartDensity (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) (y : OAI.CKSSurfaceVolume.E) : ℝ := + Real.sqrt (OAI.CKSSurfaceVolume.chartMatrix g x y).det + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I 1 M] +variable [MeasurableSpace M] [BorelSpace M] + +def localVolume (g : OAI.CKSSurfaceVolume.Metric (M := M)) (x : M) : Measure M := + Measure.map (extChartAt OAI.CKSSurfaceVolume.I x).symm + ((volume.restrict (extChartAt OAI.CKSSurfaceVolume.I x).target).withDensity + (fun y => ENNReal.ofReal (OAI.CKSSurfaceVolume.chartDensity g x y))) + +def IsVolume (g : OAI.CKSSurfaceVolume.Metric (M := M)) (ν : Measure M) : Prop := + ∀ x : M, ν.restrict (extChartAt OAI.CKSSurfaceVolume.I x).source = OAI.CKSSurfaceVolume.localVolume g x + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSurfaceVolume +open Bundle Manifold Set MeasureTheory +open scoped ContDiff ENNReal + +def riemannianVolume {M : Type u_1} [TopologicalSpace M] [ChartedSpace OAI.CKSSurfaceVolume.H M] + [IsManifold OAI.CKSSurfaceVolume.I 1 M] [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] + (g : OAI.CKSSurfaceVolume.Metric (M := M)) : Measure M := + Classical.epsilon (fun ν => OAI.CKSSurfaceVolume.IsVolume g ν) + +end OAI.CKSSurfaceVolume +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology + +abbrev E2 := EuclideanSpace ℝ (Fin 2) + +abbrev I2 := 𝓘(ℝ,OAI.CKSInducedArea.E2) + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] + +local instance real_continuousAdd : ContinuousAdd ℝ := inferInstance + +local instance real_continuousConstSMul : ContinuousConstSMul ℝ ℝ := inferInstance + +local instance real_id_isometric : RingHomIsometric (RingHom.id ℝ) := inferInstance + +local instance real_id_compTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +local instance real_smulCommClass : + @SMulCommClass ℝ ℝ ℝ Algebra.toSMul + (@instSMulOfMul ℝ (@Distrib.toMul ℝ + (@instDistribOfSemiring ℝ (@CommSemiring.toSemiring ℝ Real.instCommSemiring)))) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Inner2 := + letI := OAI.CKSInducedArea.real_smulCommClass + ∀ x : S, TangentSpace OAI.CKSInducedArea.I2 x →L[ℝ] TangentSpace OAI.CKSInducedArea.I2 x →L[ℝ] ℝ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Smooth3 := ContMDiffRiemannianMetric I3 ∞ OAI.CKSInducedArea.E3 (fun x : N => TangentSpace I3 x) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +abbrev Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ + +abbrev Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +def inducedInner (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (φ : S → N) : OAI.CKSInducedArea.Inner2 (S := S) := + letI := OAI.CKSInducedArea.real_id_isometric + letI := OAI.CKSInducedArea.real_id_compTriple + fun x => by + let : NormedAddCommGroup (TangentSpace OAI.CKSInducedArea.I2 x) := by unfold TangentSpace; infer_instance + let : NormedSpace ℝ (TangentSpace OAI.CKSInducedArea.I2 x) := by unfold TangentSpace; infer_instance + let : NormedAddCommGroup (TangentSpace I3 (φ x)) := by unfold TangentSpace; infer_instance + let : NormedSpace ℝ (TangentSpace I3 (φ x)) := by unfold TangentSpace; infer_instance + exact (g.inner (φ x)).bilinearComp (mfderiv OAI.CKSInducedArea.I2 I3 φ x) (mfderiv OAI.CKSInducedArea.I2 I3 φ x) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + +local instance tangent_manifold_one : IsManifold I 1 M := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one + + +local instance tangent_vectorBundle : VectorBundle ℝ E (fun x : M => TangentSpace I x) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle + + +local instance scalar_smulCommClass : SMulCommClass ℝ ℝ ℝ := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass + + +local instance scalar_vectorBundle : VectorBundle ℝ ℝ (Bundle.Trivial M ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle + + +local instance scalar_continuousSMul : ContinuousSMul ℝ ℝ := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul + + +local instance covector_vectorBundle : + VectorBundle ℝ (E →L[ℝ] ℝ) (fun x : M => TangentSpace I x →L[ℝ] ℝ) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle + + +local instance covector_topologicalAddGroup (x : M) : + IsTopologicalAddGroup (TangentSpace I x →L[ℝ] ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup + + +local instance covector_continuousSMul (x : M) : + ContinuousSMul ℝ (TangentSpace I x →L[ℝ] ℝ) := inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type*} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul + + +local instance scalarAtlas : MemTrivializationAtlas (Bundle.Trivial.trivialization M ℝ) := ⟨rfl⟩ + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul +attribute [local instance] OAI.CKSInducedArea.scalarAtlas + + +local instance covector_atlas (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : + MemTrivializationAtlas + (e.continuousLinearMap (RingHom.id ℝ) (Bundle.Trivial.trivialization M ℝ)) := + inferInstance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +variable {E : Type u_4} [NormedAddCommGroup E] [NormedSpace ℝ E] + {H : Type u_5} [TopologicalSpace H] (I : ModelWithCorners ℝ E H) + {M : Type u_6} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] +attribute [local instance] tangent_manifold_one +attribute [local instance] tangent_vectorBundle +attribute [local instance] scalar_smulCommClass +attribute [local instance] scalar_vectorBundle +attribute [local instance] scalar_continuousSMul +attribute [local instance] covector_vectorBundle +attribute [local instance] covector_topologicalAddGroup +attribute [local instance] covector_continuousSMul +attribute [local instance] OAI.CKSInducedArea.scalarAtlas +attribute [local instance] covector_atlas + + +def bilinearTriv (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : + Trivialization (E →L[ℝ] E →L[ℝ] ℝ) (π (E →L[ℝ] E →L[ℝ] ℝ) (fun x : M => + TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ)) := + letI := OAI.CKSInducedArea.real_smulCommClass + e.continuousLinearMap (RingHom.id ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Bundle.Trivial.trivialization M ℝ)) + +instance bilinearTriv_atlas (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] : MemTrivializationAtlas (OAI.CKSInducedArea.bilinearTriv I e) := by + unfold OAI.CKSInducedArea.bilinearTriv + infer_instance + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric + + +local instance covector_smulCommClass {Space : Type u_4} [NormedAddCommGroup Space] + [NormedSpace ℝ Space] : + letI := OAI.CKSInducedArea.real_smulCommClass + SMulCommClass ℝ ℝ (Space →L[ℝ] ℝ) := by + infer_instance + +local instance bilNorm2 : NormedAddCommGroup OAI.CKSInducedArea.Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E2) (F := OAI.CKSInducedArea.E2 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 + + +local instance bilSpace2 : NormedSpace ℝ OAI.CKSInducedArea.Bil2 := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E2) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 + + +local instance bilNorm3 : NormedAddCommGroup OAI.CKSInducedArea.Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E3) (F := OAI.CKSInducedArea.E3 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 + + +local instance bilSpace3 : NormedSpace ℝ OAI.CKSInducedArea.Bil3 := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E3) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 + + +local instance mixNorm23 : NormedAddCommGroup (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E2) (F := OAI.CKSInducedArea.E3 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 + + +local instance mixSpace23 : NormedSpace ℝ (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E3) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 + + +local instance mixNorm32 : NormedAddCommGroup (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + ContinuousLinearMap.toNormedAddCommGroup (E := OAI.CKSInducedArea.E3) (F := OAI.CKSInducedArea.E2 →L[ℝ] ℝ) (σ₁₂ := RingHom.id ℝ) + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type*} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type*} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 +attribute [local instance] OAI.CKSInducedArea.mixNorm32 + + +local instance mixSpace32 : NormedSpace ℝ (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + letI := OAI.CKSInducedArea.real_smulCommClass + letI := OAI.CKSInducedArea.covector_smulCommClass (Space := OAI.CKSInducedArea.E2) + ContinuousLinearMap.toNormedSpace + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSInducedArea +open Bundle Manifold Set Bornology Filter +open scoped Bundle Manifold ContDiff Topology +variable {H3 : Type u_1} [TopologicalSpace H3] {I3 : ModelWithCorners ℝ E3 H3} + {N : Type u_2} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + {S : Type u_3} [TopologicalSpace S] [ChartedSpace E2 S] [IsManifold I2 ∞ S] +attribute [local instance] real_continuousAdd real_continuousConstSMul real_smulCommClass real_id_isometric +attribute [local instance] OAI.CKSInducedArea.bilNorm2 +attribute [local instance] OAI.CKSInducedArea.bilSpace2 +attribute [local instance] OAI.CKSInducedArea.bilNorm3 +attribute [local instance] OAI.CKSInducedArea.bilSpace3 +attribute [local instance] OAI.CKSInducedArea.mixNorm23 +attribute [local instance] OAI.CKSInducedArea.mixSpace23 +attribute [local instance] OAI.CKSInducedArea.mixNorm32 +attribute [local instance] OAI.CKSInducedArea.mixSpace32 + + +def inducedMetric (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (φ : S → N) + (hφ : ContMDiff OAI.CKSInducedArea.I2 I3 ∞ φ) + (hinj : ∀ x, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 φ x)) : + ContMDiffRiemannianMetric OAI.CKSInducedArea.I2 ∞ OAI.CKSInducedArea.E2 (fun x : S => TangentSpace OAI.CKSInducedArea.I2 x) := + have proof_inducedInner_symm_37 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (point : S) (left right : TangentSpace OAI.CKSInducedArea.I2 point) : + OAI.CKSInducedArea.inducedInner metric immersion point left right = OAI.CKSInducedArea.inducedInner metric immersion point right left := + metric.symm (immersion point) _ _ + have proof_inducedInner_pos_38 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (injective : ∀ point, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 immersion point)) + (point : S) (vector : TangentSpace OAI.CKSInducedArea.I2 point) (nonzero : vector ≠ 0) : + 0 < OAI.CKSInducedArea.inducedInner metric immersion point vector vector := + metric.pos (immersion point) _ + (fun zero => nonzero (injective point (zero.trans (map_zero _).symm))) + have proof_positive_bilinear_bounded_41 (B : OAI.CKSInducedArea.Bil2) (hB : ∀ v : OAI.CKSInducedArea.E2, v ≠ 0 → 0 < B v v) : + IsVonNBounded ℝ {v : OAI.CKSInducedArea.E2 | B v v < 1} := by + have hc : Continuous (fun v : OAI.CKSInducedArea.E2 => B v v) := B.continuous.clm_apply continuous_id + obtain ⟨a,ha,hm⟩ := (isCompact_sphere (0 : OAI.CKSInducedArea.E2) 1).exists_isMinOn + (NormedSpace.sphere_nonempty.mpr (by norm_num : (0 : ℝ) ≤ 1)) hc.continuousOn + have haNorm : ‖a‖ = 1 := by simpa [Metric.mem_sphere] using ha + have ha0 : a ≠ 0 := by intro h; simp [h] at haNorm + have hp : 0 < B a a := hB a ha0 + have hlow : ∀ v : OAI.CKSInducedArea.E2, B a a * ‖v‖ ^ 2 ≤ B v v := by + intro v + by_cases hv : v = 0 + · simp [hv] + have hn : 0 < ‖v‖ := norm_pos_iff.mpr hv + have hy : ‖(‖v‖⁻¹ : ℝ) • v‖ = 1 := by + rw [norm_smul, Real.norm_eq_abs, abs_of_pos (inv_pos.mpr hn), inv_mul_cancel₀ hn.ne'] + have h := hm (show (‖v‖⁻¹ : ℝ) • v ∈ Metric.sphere (0 : OAI.CKSInducedArea.E2) 1 by + simpa [Metric.mem_sphere] using hy) + have he : B ((‖v‖⁻¹ : ℝ) • v) ((‖v‖⁻¹ : ℝ) • v) = B v v / ‖v‖^2 := by + simp only [map_smul, smul_apply, smul_eq_mul] + field_simp + change B a a ≤ B ((‖v‖⁻¹ : ℝ) • v) ((‖v‖⁻¹ : ℝ) • v) at h + rw [he] at h + exact (le_div_iff₀ (sq_pos_of_pos hn)).mp h + apply (NormedSpace.isVonNBounded_iff ℝ).mpr + apply (Metric.isBounded_iff_subset_ball (0 : OAI.CKSInducedArea.E2)).mpr + refine ⟨1 + (B a a)⁻¹, ?_⟩ + intro v hv + change dist v 0 < 1 + (B a a)⁻¹ + rw [dist_zero_right] + have hbv : B v v < 1 := hv + have hl := hlow v + have hinv : 0 < (B a a)⁻¹ := inv_pos.mpr hp + have he : B a a * (B a a)⁻¹ = 1 := mul_inv_cancel₀ hp.ne' + by_contra hh + have hn : 1 + (B a a)⁻¹ ≤ ‖v‖ := le_of_not_gt hh + have hn1 : 1 ≤ ‖v‖ := by linarith + have hn2 : ‖v‖ ≤ ‖v‖^2 := by nlinarith + have hmul := mul_le_mul_of_nonneg_left hn hp.le + have hmul2 := mul_le_mul_of_nonneg_left hn2 hp.le + nlinarith + have proof_inducedInner_bounded_39 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] (metric : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) (immersion : S → N) + (injective : ∀ point, Function.Injective (mfderiv OAI.CKSInducedArea.I2 I3 immersion point)) (point : S) : + IsVonNBounded ℝ {vector : TangentSpace OAI.CKSInducedArea.I2 point | + inducedInner metric immersion point vector vector < 1} := + proof_positive_bilinear_bounded_41 (OAI.CKSInducedArea.inducedInner metric immersion point) + (proof_inducedInner_pos_38 metric immersion injective point) + have proof_bilinearComp_smoothAt_42 {S : Type u_3} [instLocal1 : TopologicalSpace.{u_3} S] [instLocal2 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] [instLocal3 : IsManifold.{0, 0, 0, u_3} OAI.CKSInducedArea.I2 (∞ : ℕ∞ω) S] [IsManifold OAI.CKSInducedArea.I2 ∞ S] + {B : S → OAI.CKSInducedArea.Bil3} {A : S → OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3} {x : S} + (hB : ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil3) ∞ B x) + (hA : ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3) ∞ A x) : + ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil2) ∞ (fun y => (B y).bilinearComp (A y) (A y)) x := by + have flip1 : ContDiff ℝ ∞ (fun B : OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ => B.flip) := + by + let L : (OAI.CKSInducedArea.E2 →L[ℝ] OAI.CKSInducedArea.E3 →L[ℝ] ℝ) →L[ℝ] (OAI.CKSInducedArea.E3 →L[ℝ] OAI.CKSInducedArea.E2 →L[ℝ] ℝ) := + (ContinuousLinearMap.flipₗᵢ ℝ OAI.CKSInducedArea.E2 OAI.CKSInducedArea.E3 ℝ).toContinuousLinearEquiv.toContinuousLinearMap + exact L.contDiff + have flip2 : ContDiff ℝ ∞ (fun B : OAI.CKSInducedArea.Bil2 => B.flip) := + by + let L : OAI.CKSInducedArea.Bil2 →L[ℝ] OAI.CKSInducedArea.Bil2 := + (ContinuousLinearMap.flipₗᵢ ℝ OAI.CKSInducedArea.E2 OAI.CKSInducedArea.E2 ℝ).toContinuousLinearEquiv.toContinuousLinearMap + exact L.contDiff + exact flip2.comp_contMDiffAt ((flip1.comp_contMDiffAt (hB.clm_comp hA)).clm_comp hA) + have proof_bilinearTriv_pair_43 {E : Type 0} [instLocal1 : NormedAddCommGroup.{0} E] [instLocal2 : NormedSpace.{0, 0} ℝ E] {H : Type 0} [instLocal4 : TopologicalSpace.{0} H] (I : ModelWithCorners.{0, 0, 0} ℝ E H) {M : Type u_3} [instLocal7 : TopologicalSpace.{u_3} M] [instLocal8 : ChartedSpace.{0, u_3} H M] [instLocal9 : IsManifold.{0, 0, 0, u_3} I (∞ : ℕ∞ω) M] (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] {x : M} (hx : x ∈ e.baseSet) + (B : TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) (v w : E) : + ((OAI.CKSInducedArea.bilinearTriv I e) ⟨x,B⟩).2 v w = B (e.symmL ℝ x v) (e.symmL ℝ x w) := by + let := OAI.CKSInducedArea.scalarAtlas (M := M) + unfold OAI.CKSInducedArea.bilinearTriv + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)) + (show x ∈ (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)).baseSet by simpa using hx)] + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (Trivial.trivialization M ℝ) (show x ∈ (Trivial.trivialization M ℝ).baseSet from mem_univ x)] + rfl + have proof_bilinearTriv_pair_44 {E : Type 0} [instLocal1 : NormedAddCommGroup.{0} E] [instLocal2 : NormedSpace.{0, 0} ℝ E] {H : Type u_1} [instLocal4 : TopologicalSpace.{u_1} H] (I : ModelWithCorners.{0, 0, u_1} ℝ E H) {M : Type u_2} [instLocal7 : TopologicalSpace.{u_2} M] [instLocal8 : ChartedSpace.{u_1, u_2} H M] [instLocal9 : IsManifold.{0, 0, u_1, u_2} I (∞ : ℕ∞ω) M] (e : Trivialization E (π E (fun x : M => TangentSpace I x))) + [MemTrivializationAtlas e] {x : M} (hx : x ∈ e.baseSet) + (B : TangentSpace I x →L[ℝ] TangentSpace I x →L[ℝ] ℝ) (v w : E) : + ((OAI.CKSInducedArea.bilinearTriv I e) ⟨x,B⟩).2 v w = B (e.symmL ℝ x v) (e.symmL ℝ x w) := by + let := OAI.CKSInducedArea.scalarAtlas (M := M) + unfold OAI.CKSInducedArea.bilinearTriv + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)) + (show x ∈ (e.continuousLinearMap (RingHom.id ℝ) (Trivial.trivialization M ℝ)).baseSet by simpa using hx)] + rw [Trivialization.continuousLinearMap_apply] + dsimp only [ContinuousLinearMap.comp_apply] + rw [Trivialization.continuousLinearMapAt_apply_of_mem (R := ℝ) + (Trivial.trivialization M ℝ) (show x ∈ (Trivial.trivialization M ℝ).baseSet from mem_univ x)] + rfl + have proof_inducedInner_smooth_40 {H3 : Type u_1} [instLocal1 : TopologicalSpace.{u_1} H3] {I3 : ModelWithCorners.{0, 0, u_1} ℝ OAI.CKSInducedArea.E3 H3} {N : Type u_2} [instLocal4 : TopologicalSpace.{u_2} N] [instLocal5 : ChartedSpace.{u_1, u_2} H3 N] [instLocal6 : IsManifold.{0, 0, u_1, u_2} I3 (∞ : ℕ∞ω) N] {S : Type u_3} [instLocal8 : TopologicalSpace.{u_3} S] [instLocal9 : ChartedSpace.{0, u_3} OAI.CKSInducedArea.E2 S] [instLocal10 : IsManifold.{0, 0, 0, u_3} OAI.CKSInducedArea.I2 (∞ : ℕ∞ω) S] (g : OAI.CKSInducedArea.Smooth3 (I3 := I3) (N := N)) {φ : S → N} + (hφ : ContMDiff OAI.CKSInducedArea.I2 I3 ∞ φ) : + ContMDiff OAI.CKSInducedArea.I2 (OAI.CKSInducedArea.I2.prod 𝓘(ℝ,OAI.CKSInducedArea.Bil2)) ∞ + (fun x => TotalSpace.mk' OAI.CKSInducedArea.Bil2 x (OAI.CKSInducedArea.inducedInner g φ x)) := by + let := OAI.CKSInducedArea.real_id_isometric + let := OAI.CKSInducedArea.real_smulCommClass + intro x + let e := trivializationAt OAI.CKSInducedArea.E2 (TangentSpace OAI.CKSInducedArea.I2) x + let e' := trivializationAt OAI.CKSInducedArea.E3 (TangentSpace I3) (φ x) + have hx : x ∈ e.baseSet := mem_baseSet_trivializationAt OAI.CKSInducedArea.E2 (TangentSpace OAI.CKSInducedArea.I2) x + have hx' : φ x ∈ e'.baseSet := mem_baseSet_trivializationAt OAI.CKSInducedArea.E3 (TangentSpace I3) (φ x) + apply (contMDiffAt_section (𝕜 := ℝ) (B := S) + (E := fun z : S => TangentSpace OAI.CKSInducedArea.I2 z →L[ℝ] TangentSpace OAI.CKSInducedArea.I2 z →L[ℝ] ℝ) + (IB := OAI.CKSInducedArea.I2) (n := ∞) (F := OAI.CKSInducedArea.Bil2) + (s := OAI.CKSInducedArea.inducedInner g φ) x).mpr + change ContMDiffAt OAI.CKSInducedArea.I2 𝓘(ℝ,OAI.CKSInducedArea.Bil2) ∞ + (fun y : S => ((OAI.CKSInducedArea.bilinearTriv OAI.CKSInducedArea.I2 e) + ⟨y, OAI.CKSInducedArea.inducedInner g φ y⟩).2) x + have hB := (contMDiffAt_section (𝕜 := ℝ) (B := N) + (E := fun z : N => TangentSpace I3 z →L[ℝ] TangentSpace I3 z →L[ℝ] ℝ) + (IB := I3) (n := ∞) (F := OAI.CKSInducedArea.Bil3) (s := g.inner) (φ x)).mp (g.contMDiff (φ x)) + change ContMDiffAt I3 𝓘(ℝ,OAI.CKSInducedArea.Bil3) ∞ + (fun y : N => ((OAI.CKSInducedArea.bilinearTriv I3 e') ⟨y, g.inner y⟩).2) (φ x) at hB + have hD := (hφ x).mfderiv_const (show (∞ : ℕ∞ω) + 1 ≤ ∞ by simp [*]) + apply (proof_bilinearComp_smoothAt_42 (hB.comp x (hφ x)) hD).congr_of_eventuallyEq + filter_upwards [e.open_baseSet.mem_nhds hx, + hφ.continuous.continuousAt.preimage_mem_nhds (e'.open_baseSet.mem_nhds hx')] with y hy hy' + ext v w + rw [proof_bilinearTriv_pair_43 OAI.CKSInducedArea.I2 e hy] + rw [ContinuousLinearMap.bilinearComp_apply] + dsimp only [Function.comp_apply] + rw [proof_bilinearTriv_pair_44 I3 e' hy'] + dsimp [OAI.CKSInducedArea.inducedInner,inTangentCoordinates,ContinuousLinearMap.inCoordinates] + rw [e'.symmL_continuousLinearMapAt hy', e'.symmL_continuousLinearMapAt hy'] + rfl + { + inner := OAI.CKSInducedArea.inducedInner g φ + symm := proof_inducedInner_symm_37 g φ + pos := proof_inducedInner_pos_38 g φ hinj + isVonNBounded := proof_inducedInner_bounded_39 g φ hinj + contMDiff := proof_inducedInner_smooth_40 g hφ + } + +end OAI.CKSInducedArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSEmbeddingDerivative +open Set Manifold Bundle Filter Function +open scoped ContDiff Topology + +abbrev E := EuclideanSpace ℝ (Fin 3) + +local instance halfSpaceDimension_neZero : NeZero (3 : ℕ) := inferInstance + +abbrev H := @EuclideanHalfSpace 3 OAI.CKSEmbeddingDerivative.halfSpaceDimension_neZero + +abbrev I := @modelWithCornersEuclideanHalfSpace 3 OAI.CKSEmbeddingDerivative.halfSpaceDimension_neZero + +end OAI.CKSEmbeddingDerivative +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle Function +open scoped ContDiff Topology +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] + +instance domainTopology (D : OAI.CKSGeometricCuts.OuterDomain N) : TopologicalSpace D.Carrier := D.topology + +instance domainCharts (D : OAI.CKSGeometricCuts.OuterDomain N) : ChartedSpace OAI.CKSBoundarySurface.H3 D.Carrier := D.charts + +instance domainSmooth (D : OAI.CKSGeometricCuts.OuterDomain N) : IsManifold OAI.CKSBoundarySurface.I3 ∞ D.Carrier := D.smooth + +abbrev Surface (D : OAI.CKSGeometricCuts.OuterDomain N) := OAI.CKSBoundarySurface.Boundary D.Carrier + +def cutInclusion (D : OAI.CKSGeometricCuts.OuterDomain N) : OAI.CKSFullCutArea.Surface D → N := D.inclusion ∘ Subtype.val + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle Function +open scoped ContDiff Topology +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] +variable [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSBoundarySurface.halfSpaceDimension_neZero) I3 ∞ N _ _] + +instance domainSecondCountable [SecondCountableTopology N] (D : OAI.CKSGeometricCuts.OuterDomain N) : + SecondCountableTopology D.Carrier := D.embedding.isEmbedding.secondCountableTopology + +abbrev SmoothMetric := + letI := OAI.CKSBoundarySurface.halfSpaceDimension_neZero + letI := OAI.CKSInducedArea.tangent_vectorBundle OAI.CKSBoundarySurface.I3 (M := N) + ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I3 ∞ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) + +def cutMetric (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) (D : OAI.CKSGeometricCuts.OuterDomain N) : + ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I2 ∞ OAI.CKSBoundarySurface.E2 (fun x : OAI.CKSFullCutArea.Surface D => TangentSpace OAI.CKSBoundarySurface.I2 x) := + have proof_boundary_chart_zero_49 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSIntrinsicGeometry.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSIntrinsicGeometry.I3 1 M] (x y : M) (hy : y ∈ (extChartAt OAI.CKSIntrinsicGeometry.I3 x).source) + (hS : y ∈ OAI.CKSIntrinsicGeometry.I3.boundary M) : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 = 0 := by + have hychart : y ∈ (chartAt OAI.CKSIntrinsicGeometry.H3 x).source := by simpa using hy + have hyrange : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ range OAI.CKSIntrinsicGeometry.I3 := + (extChartAt_target_subset_range x) ((extChartAt OAI.CKSIntrinsicGeometry.I3 x).map_source hy) + have hnonneg : 0 ≤ (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := by + simpa only [OAI.CKSIntrinsicGeometry.I3, range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hyrange + have hnot : ¬OAI.CKSIntrinsicGeometry.I3.IsInteriorPoint y := + (OAI.CKSIntrinsicGeometry.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mp hS + have hle : (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 ≤ 0 := by + by_contra h + have hpos : 0 < (extChartAt OAI.CKSIntrinsicGeometry.I3 x y) 0 := lt_of_not_ge h + have hint : extChartAt OAI.CKSIntrinsicGeometry.I3 x y ∈ interior (range OAI.CKSIntrinsicGeometry.I3) := by + simpa only [OAI.CKSIntrinsicGeometry.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq] using hpos + apply hnot + apply (OAI.CKSIntrinsicGeometry.I3.isInteriorPoint_iff_of_mem_atlas one_ne_zero (chart_mem_atlas OAI.CKSIntrinsicGeometry.H3 x) hychart).mpr + exact (chartAt OAI.CKSIntrinsicGeometry.H3 x).mem_interior_extend_target ((chartAt OAI.CKSIntrinsicGeometry.H3 x).map_source hychart) hint + exact le_antisymm hle hnonneg + have proof_liftPlane_zero_6 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.liftPlane z 0 = 0 := rfl + have proof_liftPlane_succ_7 (z : OAI.CKSBoundarySurface.E2) (i : Fin 2) : OAI.CKSBoundarySurface.liftPlane z i.succ = z i := rfl + have proof_I3_liftHalf_23 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.liftHalf z) = OAI.CKSBoundarySurface.liftPlane z := rfl + have proof_boundary_iff_zero_50 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x y : M) (hy : y ∈ (chartAt OAI.CKSBoundarySurface.H3 x).source) : + y ∈ OAI.CKSBoundarySurface.I3.boundary M ↔ (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 = 0 := by + constructor + · exact proof_boundary_chart_zero_49 x y (by simp [*]) + · intro hz + apply (OAI.CKSBoundarySurface.I3.isBoundaryPoint_iff_not_isInteriorPoint y).mpr + intro hi + have hin := (OAI.CKSBoundarySurface.I3.isInteriorPoint_iff_of_mem_atlas + (by simp [*] : (∞ : ℕ∞ω) ≠ 0) (chart_mem_atlas OAI.CKSBoundarySurface.H3 x) hy).mp hi + have hr := (chartAt OAI.CKSBoundarySurface.H3 x).interior_extend_target_subset_interior_range hin + have hp : 0 < (OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x y)) 0 := by + simpa only [OAI.CKSBoundarySurface.I3, interior_range_modelWithCornersEuclideanHalfSpace, mem_ofPred_eq, + OpenPartialHomeomorph.extend_coe, Function.comp_apply] using hr + rw [hz] at hp + exact (lt_irrefl 0) hp + have proof_chart_inverse_boundary_51 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x).target) : + (chartAt OAI.CKSBoundarySurface.H3 x).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.I3.boundary M := by + apply (proof_boundary_iff_zero_50 x _ ((chartAt OAI.CKSBoundarySurface.H3 x).map_target hz)).mpr + rw [(chartAt OAI.CKSBoundarySurface.H3 x).right_inv hz] + rfl + have proof_boundaryInverse_mem_52 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) ∈ OAI.CKSBoundarySurface.Boundary M := + proof_chart_inverse_boundary_51 x.val hz + have proof_boundaryInverse_val_53 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : OAI.CKSBoundarySurface.liftHalf z ∈ (chartAt OAI.CKSBoundarySurface.H3 x.val).target) : + (OAI.CKSBoundarySurface.boundaryInverse x z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := by + simp only [OAI.CKSBoundarySurface.boundaryInverse,dite_eq_left hz] + have proof_boundaryChart_symm_val_54 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + ((OAI.CKSBoundarySurface.boundaryChart x).symm z).val = (chartAt OAI.CKSBoundarySurface.H3 x.val).symm (OAI.CKSBoundarySurface.liftHalf z) := + proof_boundaryInverse_val_53 x hz + have proof_inclusion_chart_formula_55 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) {z : OAI.CKSBoundarySurface.E2} + (hz : z ∈ (OAI.CKSBoundarySurface.boundaryChart x).target) : + writtenInExtChartAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 x (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) z = OAI.CKSBoundarySurface.liftPlane z := by + change OAI.CKSBoundarySurface.I3 (chartAt OAI.CKSBoundarySurface.H3 x.val (((OAI.CKSBoundarySurface.boundaryChart x).symm z).val)) = _ + rw [proof_boundaryChart_symm_val_54 x hz, (chartAt OAI.CKSBoundarySurface.H3 x.val).right_inv hz] + rfl + have proof_inclusion_chart_eventually_56 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + writtenInExtChartAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 x (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) =ᶠ[𝓝 (extChartAt OAI.CKSBoundarySurface.I2 x x)] OAI.CKSBoundarySurface.liftPlane := by + have ht : (OAI.CKSBoundarySurface.boundaryChart x).target ∈ 𝓝 (extChartAt OAI.CKSBoundarySurface.I2 x x) := + (OAI.CKSBoundarySurface.boundaryChart x).open_target.mem_nhds ((OAI.CKSBoundarySurface.boundaryChart x).map_source (mem_chart_source OAI.CKSBoundarySurface.E2 x)) + filter_upwards [ht] with z hz + exact proof_inclusion_chart_formula_55 x hz + have proof_inclusion_smooth_57 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] : ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) := by + intro x + apply contMDiffAt_iff.mpr + refine ⟨continuous_subtype_val.continuousAt, ?_⟩ + exact ((OAI.CKSBoundarySurface.liftPlane.contDiff.contDiffAt).congr_of_eventuallyEq (proof_inclusion_chart_eventually_56 x)).contDiffWithinAt + have proof_cutInclusion_smooth_47 {N : Type u} [instLocal1 : TopologicalSpace.{u} N] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 N] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) N] [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (D : OAI.CKSGeometricCuts.OuterDomain N) : + ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ (OAI.CKSFullCutArea.cutInclusion D) := + D.embedding.isImmersion.contMDiff.comp proof_inclusion_smooth_57 + have proof_extended_chart_derivative_injective_58 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [IsManifold OAI.CKSEmbeddingDerivative.I ∞ M] (e : OpenPartialHomeomorph M OAI.CKSEmbeddingDerivative.H) + (he : e ∈ IsManifold.maximalAtlas OAI.CKSEmbeddingDerivative.I ∞ M) {x : M} (hx : x ∈ e.source) : + Injective (mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x) := by + have hed : e.MDifferentiable OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I := ⟨ + (contMDiffOn_of_mem_maximalAtlas he).mdifferentiableOn (by simp), + (contMDiffOn_symm_of_mem_maximalAtlas he).mdifferentiableOn (by simp)⟩ + have hcomp := mfderiv_comp x OAI.CKSEmbeddingDerivative.I.mdifferentiableAt ((hed.1 x hx).mdifferentiableAt (e.open_source.mem_nhds hx)) + change mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x = _ at hcomp + rw [OAI.CKSEmbeddingDerivative.I.hasMFDerivAt.mfderiv] at hcomp + change mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (e.extend OAI.CKSEmbeddingDerivative.I) x = mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I e x at hcomp + rw [hcomp] + exact hed.mfderiv_injective hx + have proof_immersion_derivative_injective_59 {M : Type u} {N : Type u} [instLocal2 : TopologicalSpace.{u} M] [instLocal3 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal4 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [instLocal5 : TopologicalSpace.{u} N] [instLocal6 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H N] [instLocal7 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) N] [IsManifold OAI.CKSEmbeddingDerivative.I ∞ N] {f : M → N} {x : M} + (h : IsImmersionAt OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I ∞ f x) : Injective (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x) := by + let A : OAI.CKSEmbeddingDerivative.E →L[ℝ] OAI.CKSEmbeddingDerivative.E := (ContinuousLinearMap.fst ℝ OAI.CKSEmbeddingDerivative.E h.complement).comp + h.equiv.symm.toContinuousLinearMap + let L : N → OAI.CKSEmbeddingDerivative.E := A ∘ (h.codChart.extend OAI.CKSEmbeddingDerivative.I) + have hL : ContMDiffAt OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) ∞ L (f x) := + A.contMDiff.contMDiffAt.comp _ + (h.codChart.contMDiffAt_extend h.codChart_mem_maximalAtlas h.mem_codChart_source) + have heq : (L ∘ f) =ᶠ[𝓝 x] h.domChart.extend OAI.CKSEmbeddingDerivative.I := by + filter_upwards [h.domChart.open_source.mem_nhds h.mem_domChart_source] with y hy + have hy' : y ∈ (h.domChart.extend OAI.CKSEmbeddingDerivative.I).source := by simpa only [OpenPartialHomeomorph.extend_source] using hy + have hw := h.writtenInCharts ((h.domChart.extend OAI.CKSEmbeddingDerivative.I).map_source hy') + dsimp only [Function.comp_apply] at hw + rw [(h.domChart.extend OAI.CKSEmbeddingDerivative.I).left_inv hy'] at hw + change A ((h.codChart.extend OAI.CKSEmbeddingDerivative.I) (f y)) = _ + rw [hw] + simp only [A,ContinuousLinearMap.comp_apply,ContinuousLinearEquiv.coe_coe, + ContinuousLinearEquiv.symm_apply_apply ] + rfl + have hdL := hL.mdifferentiableAt (by simp) + have hdf := h.contMDiffAt.mdifferentiableAt (by simp) + have hder := heq.mfderiv_eq (I := OAI.CKSEmbeddingDerivative.I) (I' := 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E)) + rw [mfderiv_comp x hdL hdf] at hder + change _ = mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) (h.domChart.extend OAI.CKSEmbeddingDerivative.I) x at hder + have hinj := proof_extended_chart_derivative_injective_58 h.domChart h.domChart_mem_maximalAtlas + h.mem_domChart_source + rw [← hder] at hinj + have hi' : Injective ((mfderiv OAI.CKSEmbeddingDerivative.I 𝓘(ℝ,OAI.CKSEmbeddingDerivative.E) L (f x)) ∘ (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x)) := hinj + exact hi'.of_comp + have proof_smooth_embedding_derivative_injective_60 {M : Type u} {N : Type u} [instLocal2 : TopologicalSpace.{u} M] [instLocal3 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H M] [instLocal4 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) M] [instLocal5 : TopologicalSpace.{u} N] [instLocal6 : ChartedSpace.{0, u} OAI.CKSEmbeddingDerivative.H N] [instLocal7 : IsManifold.{0, 0, 0, u} OAI.CKSEmbeddingDerivative.I (∞ : ℕ∞ω) N] {f : M → N} (h : IsSmoothEmbedding OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I ∞ f) : + ∀ x, Injective (mfderiv OAI.CKSEmbeddingDerivative.I OAI.CKSEmbeddingDerivative.I f x) := fun x => + proof_immersion_derivative_injective_59 (h.isImmersion.isImmersionAt x) + have proof_inclusion_hasMFDeriv_61 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + HasMFDerivAt OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) x OAI.CKSBoundarySurface.liftPlane := by + refine ⟨continuous_subtype_val.continuousAt, ?_⟩ + exact (OAI.CKSBoundarySurface.liftPlane.hasFDerivAt.congr_of_eventuallyEq (proof_inclusion_chart_eventually_56 x)).hasFDerivWithinAt + have proof_dropPlane_apply_31 (z : OAI.CKSBoundarySurface.E3) (i : Fin 2) : OAI.CKSBoundarySurface.dropPlane z i = z i.succ := rfl + have proof_drop_lift_28 (z : OAI.CKSBoundarySurface.E2) : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane z) = z := by ext i; rfl + have proof_inclusion_mfderiv_injective_62 {M : Type u} [instLocal1 : TopologicalSpace.{u} M] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 M] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) M] (x : OAI.CKSBoundarySurface.Boundary M) : + Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary M → M) x) := by + rw [(proof_inclusion_hasMFDeriv_61 x).mfderiv] + intro a b h + change OAI.CKSBoundarySurface.liftPlane a = OAI.CKSBoundarySurface.liftPlane b at h + have hh : OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane a) = OAI.CKSBoundarySurface.dropPlane (OAI.CKSBoundarySurface.liftPlane b) := congrArg OAI.CKSBoundarySurface.dropPlane h + change (a : OAI.CKSBoundarySurface.E2) = (b : OAI.CKSBoundarySurface.E2) + exact (proof_drop_lift_28 a).symm.trans (hh.trans (proof_drop_lift_28 b)) + have proof_cutInclusion_derivative_injective_48 {N : Type u} [instLocal1 : TopologicalSpace.{u} N] [instLocal2 : ChartedSpace.{0, u} OAI.CKSBoundarySurface.H3 N] [instLocal3 : IsManifold.{0, 0, 0, u} OAI.CKSBoundarySurface.I3 (∞ : ℕ∞ω) N] [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (D : OAI.CKSGeometricCuts.OuterDomain N) (x : OAI.CKSFullCutArea.Surface D) : + Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (OAI.CKSFullCutArea.cutInclusion D) x) := by + unfold OAI.CKSFullCutArea.cutInclusion + rw [mfderiv_comp x ((D.embedding.isImmersion.contMDiff x.val).mdifferentiableAt (by simp [*])) + ((proof_inclusion_smooth_57 x).mdifferentiableAt (by simp [*]))] + · change Injective ((mfderiv OAI.CKSBoundarySurface.I3 OAI.CKSBoundarySurface.I3 D.inclusion x.val) ∘ + (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSFullCutArea.Surface D → D.Carrier) x)) + exact (proof_smooth_embedding_derivative_injective_60 D.embedding x.val).comp + (proof_inclusion_mfderiv_injective_62 x) + @OAI.CKSInducedArea.inducedMetric OAI.CKSBoundarySurface.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSBoundarySurface.halfSpaceDimension_neZero) + OAI.CKSBoundarySurface.I3 N _ _ _ (OAI.CKSFullCutArea.Surface D) _ _ _ g (OAI.CKSFullCutArea.cutInclusion D) (proof_cutInclusion_smooth_47 D) + (proof_cutInclusion_derivative_injective_48 D) + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSFullCutArea +open Set Manifold Bundle MeasureTheory +open scoped ContDiff Topology ENNReal +open CKSGeometricCuts (OuterDomain) +open CKSBoundarySurface +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSBoundarySurface.halfSpaceDimension_neZero) I3 ∞ N _ _] + [SecondCountableTopology N] + +def area (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) (D : OAI.CKSGeometricCuts.OuterDomain N) : ℝ≥0∞ := + letI : MeasurableSpace (OAI.CKSFullCutArea.Surface D) := borel (OAI.CKSFullCutArea.Surface D) + letI : BorelSpace (OAI.CKSFullCutArea.Surface D) := ⟨rfl⟩ + OAI.CKSSurfaceVolume.riemannianVolume (OAI.CKSFullCutArea.cutMetric g D).toContinuousRiemannianMetric univ + +def minEnclosingArea (g : OAI.CKSFullCutArea.SmoothMetric (N := N)) : ℝ≥0∞ := + ⨅ D : OAI.CKSGeometricCuts.OuterDomain N, OAI.CKSFullCutArea.area g D + +end OAI.CKSFullCutArea +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Set Manifold Bundle MeasureTheory CKSLorentz CKSMetricGluing +open scoped ContDiff Topology ENNReal +variable {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] + +local instance eight_atLeastTwo : Nat.AtLeastTwo 8 := inferInstance + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSIntrinsicConstraints +open Set Manifold Bundle MeasureTheory CKSLorentz CKSMetricGluing +open scoped ContDiff Topology ENNReal +variable {M : Type u_1} [TopologicalSpace M] [ChartedSpace H M] [IsManifold I ∞ M] + [MeasurableSpace M] [BorelSpace M] [SecondCountableTopology M] +attribute [local instance] eight_atLeastTwo + + +def IntegrableConstraints (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSIntrinsicConstraints.I (M := M)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSIntrinsicConstraints.I (M := M)) : Prop := + ∃ μ j : M → ℝ, Continuous μ ∧ Continuous j ∧ + Integrable μ (OAI.CKSIntrinsicVolume.riemannianVolume g.toContinuousRiemannianMetric) ∧ + Integrable j (OAI.CKSIntrinsicVolume.riemannianVolume g.toContinuousRiemannianMetric) ∧ + (∀ x, 0 ≤ j x ∧ j x ≤ μ x) ∧ + ∀ x (c : OAI.CKSIntrinsicConstraints.ConstraintChart g.inner K x), + 8 * Real.pi * μ x = c.energy ∧ 8 * Real.pi * j x = c.momentumNorm + +end OAI.CKSIntrinsicConstraints +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +local instance id_invPair (Scalar : Type u_1) [Semiring Scalar] : + RingHomInvPair (RingHom.id Scalar) (RingHom.id Scalar) := inferInstance + +local instance source_manifold_one : IsManifold OAI.CKSGeometricCuts.I3 1 N := inferInstance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] CKSGeometricCuts.halfSpaceDimension_neZero id_invPair source_manifold_one + + +local instance source_trivialization_isLinear (point : N) : + (trivializationAt OAI.CKSLorentz.E (TangentSpace OAI.CKSGeometricCuts.I3) point).IsLinear ℝ := inferInstance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts CKSSphericalHarmonics +open scoped ContDiff Topology +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] CKSGeometricCuts.halfSpaceDimension_neZero id_invPair source_manifold_one +attribute [local instance] source_trivialization_isLinear + + +def Orientable : Prop := + ∃ o : ∀ x : N, Orientation ℝ (TangentSpace OAI.CKSGeometricCuts.I3 x) (Fin 3), ∀ x : N, + let e := trivializationAt OAI.CKSLorentz.E (TangentSpace OAI.CKSGeometricCuts.I3) x + ∃ V : Set N, IsOpen V ∧ ∃ hx : x ∈ V, ∃ hV : V ⊆ e.baseSet, + ∀ y (hy : y ∈ V), + let atPoint : TangentSpace OAI.CKSGeometricCuts.I3 y ≃L[ℝ] OAI.CKSLorentz.E := e.continuousLinearEquivAt ℝ y (hV hy) + let atBase : TangentSpace OAI.CKSGeometricCuts.I3 x ≃L[ℝ] OAI.CKSLorentz.E := e.continuousLinearEquivAt ℝ x (hV hx) + Orientation.map (Fin 3) atPoint.toLinearEquiv (o y) = + Orientation.map (Fin 3) atBase.toLinearEquiv (o x) + +structure CoordinateEnd where + radius : ℝ + radius_pos : 0 < radius + domain : Set N + isOpen : IsOpen domain + coordinate : N → OAI.CKSLorentz.E + inverse : OAI.CKSLorentz.E → N + smooth : ContMDiffOn OAI.CKSGeometricCuts.I3 𝓘(ℝ,OAI.CKSLorentz.E) ∞ coordinate domain + inverse_smooth : ContMDiffOn 𝓘(ℝ,OAI.CKSLorentz.E) OAI.CKSGeometricCuts.I3 ∞ inverse {y | radius < ‖y‖} + mapsTo : ∀ x ∈ domain, radius < ‖coordinate x‖ + left_inverse : ∀ x ∈ domain, inverse (coordinate x) = x + right_inverse : ∀ y, radius < ‖y‖ → inverse y ∈ domain ∧ coordinate (inverse y) = y + closed_far_side : ∀ r, radius < r → IsClosed {x : N | x ∈ domain ∧ r ≤ ‖coordinate x‖} + compact_inner_side : ∀ r, radius < r → IsCompact {x : N | x ∉ domain ∨ ‖coordinate x‖ ≤ r} + +structure CKSData (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) where + chart : OAI.CKSSourceExterior.CoordinateEnd (N := N) + metricPerturbation : OAI.CKSLorentz.SpatialTensor + tensorPerturbation : OAI.CKSLorentz.SpatialTensor + metric_smooth : ∀ y, chart.radius < ‖y‖ → ContDiffAt ℝ ∞ metricPerturbation y + tensor_smooth : ∀ y, chart.radius < ‖y‖ → ContDiffAt ℝ ∞ tensorPerturbation y + represents : ∀ x ∈ chart.domain, + g.inner x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 chart.coordinate (OAI.CKSLorentz.sourceSpatial metricPerturbation) x ∧ + K x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 chart.coordinate (OAI.CKSLorentz.sourceSpatial tensorPerturbation) x + massAspect : OAI.CKSLorentz.Sphere → ℝ + aspect_smooth : OAI.CKSSphericalHarmonics.SmoothSphere massAspect + patches : OAI.CKSLorentz.Sphere → OAI.CKSLorentz.CKSTensorPatch + covers : ∀ n, n ∈ (patches n).patch.sphereRegion (patches n).region + realizes : ∀ n, (patches n).Realizes metricPerturbation tensorPerturbation + aspect_eq : ∀ n, (patches n).RepresentsMassAspect massAspect + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle MeasureTheory +open scoped ContDiff Topology InnerProductSpace ENNReal +open CKSBoundarySurface CKSFullCutArea CKSSurfaceVolume + +instance exteriorConnected : ConnectedSpace OAI.CKSSchwarzschild.Exterior := by + have : ConnectedSpace OAI.CKSSchwarzschild.Radial := isConnected_iff_connectedSpace.mp isConnected_Ici + have : ConnectedSpace OAI.CKSSchwarzschild.Sphere := isConnected_iff_connectedSpace.mp + (isConnected_sphere (by rw [← Module.finrank_eq_rank]; norm_num : 1 < Module.rank ℝ E3) (0 : OAI.CKSBoundarySurface.E3) (by norm_num : (0 : ℝ) ≤ 1)) + infer_instance + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle MeasureTheory CKSGeometricCuts CKSMetricGluing +open scoped ContDiff +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] + [@IsManifold ℝ _ E3 _ _ H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 CKSGeometricCuts.halfSpaceDimension_neZero) I3 ∞ N _ _] + [SecondCountableTopology N] + +def cutArea (g : @OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero) + OAI.CKSGeometricCuts.I3 N _ _ _) (D : OAI.CKSGeometricCuts.OuterDomain N) : ℝ := + (OAI.CKSFullCutArea.area g D).toReal + +def minimumEnclosingArea (g : @OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.E3 _ _ OAI.CKSGeometricCuts.H3 + (@instTopologicalSpaceEuclideanHalfSpace 3 OAI.CKSGeometricCuts.halfSpaceDimension_neZero) + OAI.CKSGeometricCuts.I3 N _ _ _) : ℝ := + ⨅ D : OAI.CKSGeometricCuts.OuterDomain N, OAI.CKSSourceExterior.cutArea g D + +def constraintsIntegrable (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) : Prop := + letI : MeasurableSpace N := borel N + letI : BorelSpace N := ⟨rfl⟩ + OAI.CKSIntrinsicConstraints.IntegrableConstraints g K + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Manifold Bundle Set Filter +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +variable {V : Type u_1} [NormedAddCommGroup V] [NormedSpace ℝ V] + +def covariantPair (g : + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + V → V →L[ℝ] V →L[ℝ] ℝ) (N : V → V) + (x a b : V) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + g x (fderiv ℝ N x a) b + 1/2 * + (fderiv ℝ (fun y => g y (N x) b) x a + + fderiv ℝ (fun y => g y a b) x (N x) - + fderiv ℝ (fun y => g y a (N x)) x b) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +abbrev Spacetime := ℝ × OAI.CKSBoundarySurface.E3 + +abbrev SpacetimeBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_continuousConstSMul + OAI.CKSSchwarzschild.Spacetime →L[ℝ] OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ + +def timeForm : OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ := ContinuousLinearMap.fst ℝ ℝ OAI.CKSBoundarySurface.E3 + +def spacePart : OAI.CKSSchwarzschild.Spacetime →L[ℝ] OAI.CKSBoundarySurface.E3 := ContinuousLinearMap.snd ℝ ℝ OAI.CKSBoundarySurface.E3 + +def radiusForm (x : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ := (OAI.CKSSchwarzschild.euclideanForm (OAI.CKSSchwarzschild.radialUnit x)).comp OAI.CKSSchwarzschild.spacePart + +def schwarzschildH (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + 1-2*m/r + +local instance spacetimeDual_continuousAdd : ContinuousAdd (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_isTopologicalAddGroup : IsTopologicalAddGroup (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := + inferInstance + +local instance spacetimeDual_smulCommClass : SMulCommClass ℝ ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_continuousConstSMul : ContinuousConstSMul ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := + inferInstance + +local instance spacetimeDual_isScalarTower : IsScalarTower ℝ ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +local instance spacetimeDual_continuousSMul : ContinuousSMul ℝ (OAI.CKSSchwarzschild.Spacetime →L[ℝ] ℝ) := inferInstance + +def advancedMetric (m : ℝ) (z : OAI.CKSSchwarzschild.Spacetime) : OAI.CKSSchwarzschild.SpacetimeBilinear := + letI := OAI.CKSLorentz.real_continuousAdd + letI := OAI.CKSLorentz.real_continuousConstSMul + letI := OAI.CKSLorentz.real_smulCommClass + letI := OAI.CKSLorentz.real_isTopologicalAddGroup + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousAdd + letI := OAI.CKSSchwarzschild.spacetimeDual_isTopologicalAddGroup + letI := OAI.CKSSchwarzschild.spacetimeDual_smulCommClass + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousConstSMul + letI := OAI.CKSSchwarzschild.spacetimeDual_isScalarTower + letI := OAI.CKSSchwarzschild.spacetimeDual_continuousSMul + letI := OAI.CKSSpatialManifold.real_id_compTriple + letI := OAI.CKSSpatialManifold.real_id_isometric + let spatialMetric : OAI.CKSSchwarzschild.SpacetimeBilinear := OAI.CKSSchwarzschild.euclideanForm.bilinearComp OAI.CKSSchwarzschild.spacePart OAI.CKSSchwarzschild.spacePart + (-OAI.CKSSchwarzschild.schwarzschildH m ‖z.2‖) • OAI.CKSSchwarzschild.timeForm.smulRight OAI.CKSSchwarzschild.timeForm + + OAI.CKSSchwarzschild.timeForm.smulRight (OAI.CKSSchwarzschild.radiusForm z.2) + (OAI.CKSSchwarzschild.radiusForm z.2).smulRight OAI.CKSSchwarzschild.timeForm + + spatialMetric - + (OAI.CKSSchwarzschild.radiusForm z.2).smulRight (OAI.CKSSchwarzschild.radiusForm z.2) + +def advancedSlope (m r : ℝ) : ℝ := (OAI.CKSSchwarzschild.lapse m r*(OAI.CKSSchwarzschild.lapse m r-OAI.CKSSchwarzschild.velocity m r))⁻¹ + +def advancedTime (m r : ℝ) : ℝ := + letI := OAI.CKSLorentz.two_atLeastTwo + ∫ s in (2*m)..r, OAI.CKSSchwarzschild.advancedSlope m s + +def advancedGraph (m : ℝ) (x : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime := (OAI.CKSSchwarzschild.advancedTime m ‖x‖,x) + +def futureNormal (m : ℝ) (z : OAI.CKSSchwarzschild.Spacetime) : OAI.CKSSchwarzschild.Spacetime := + ((OAI.CKSSchwarzschild.lapse m ‖z.2‖-OAI.CKSSchwarzschild.velocity m ‖z.2‖)⁻¹,OAI.CKSSchwarzschild.velocity m ‖z.2‖ • OAI.CKSSchwarzschild.radialUnit z.2) + +def graphTangent (m : ℝ) (x a : OAI.CKSBoundarySurface.E3) : OAI.CKSSchwarzschild.Spacetime := + letI := OAI.CKSLorentz.two_atLeastTwo + letI : Inner ℝ OAI.CKSBoundarySurface.E3 := + @InnerProductSpace.toInner ℝ OAI.CKSBoundarySurface.E3 _ + (PiLp.seminormedAddCommGroup 2 (fun _ : Fin 3 => ℝ)) + (PiLp.innerProductSpace (fun _ : Fin 3 => ℝ)) + (OAI.CKSSchwarzschild.advancedSlope m ‖x‖ * ⟪OAI.CKSSchwarzschild.radialUnit x,a⟫_ℝ,a) + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle CKSSpatialManifold CKSMetricGluing CKSLorentz +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface + +structure HorizonRegularGraph (m : ℝ) : Prop where + ambient_smooth : ∀ z : OAI.CKSSchwarzschild.Spacetime, z.2 ≠ 0 → ContDiffAt ℝ ∞ (OAI.CKSSchwarzschild.advancedMetric m) z + ambient_symmetric : ∀ z a b, OAI.CKSSchwarzschild.advancedMetric m z a b = OAI.CKSSchwarzschild.advancedMetric m z b a + ambient_nondegenerate : ∀ z : OAI.CKSSchwarzschild.Spacetime, z.2 ≠ 0 → ∀ a : OAI.CKSSchwarzschild.Spacetime, + (∀ b, OAI.CKSSchwarzschild.advancedMetric m z a b = 0) → a = 0 + graph_smooth_across : ∀ x : OAI.CKSBoundarySurface.E3, m < ‖x‖ → ContDiffAt ℝ ∞ (OAI.CKSSchwarzschild.advancedGraph m) x + graph_injective : Function.Injective (OAI.CKSSchwarzschild.advancedGraph m) + graph_derivative : ∀ x : OAI.CKSBoundarySurface.E3, m < ‖x‖ → ∀ a, + fderiv ℝ (OAI.CKSSchwarzschild.advancedGraph m) x a = OAI.CKSSchwarzschild.graphTangent m x a + horizon_time : OAI.CKSSchwarzschild.advancedTime m (2*m) = 0 + horizon_slope : OAI.CKSSchwarzschild.advancedSlope m (2*m) = 1/2 + induced_metric : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a b, + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.graphTangent m x a) (OAI.CKSSchwarzschild.graphTangent m x b) = OAI.CKSSchwarzschild.cartMetric m x a b + normal_unit : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) + (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) = -1 + normal_orthogonal : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a, + OAI.CKSSchwarzschild.advancedMetric m (OAI.CKSSchwarzschild.advancedGraph m x) (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)) (OAI.CKSSchwarzschild.graphTangent m x a) = 0 + future_facing : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → 0 < (OAI.CKSSchwarzschild.futureNormal m (OAI.CKSSchwarzschild.advancedGraph m x)).1 + induced_second_form : ∀ x : OAI.CKSBoundarySurface.E3, 2*m ≤ ‖x‖ → ∀ a b, + OAI.CKSSchwarzschild.covariantPair (OAI.CKSSchwarzschild.advancedMetric m) (OAI.CKSSchwarzschild.futureNormal m) (OAI.CKSSchwarzschild.advancedGraph m x) + (OAI.CKSSchwarzschild.graphTangent m x a) (OAI.CKSSchwarzschild.graphTangent m x b) = OAI.CKSSchwarzschild.cartTensor m x a b + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +attribute [local instance] CKSInducedArea.real_continuousAdd CKSInducedArea.real_smulCommClass CKSInducedArea.real_continuousConstSMul CKSBoundarySurface.two_atLeastTwo + + +local instance frameCovectorModule : Module ℝ (OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) := + @ContinuousLinearMap.module ℝ ℝ ℝ _ _ _ OAI.CKSBoundarySurface.E3 _ _ _ ℝ _ _ _ _ + OAI.CKSInducedArea.real_smulCommClass OAI.CKSInducedArea.real_continuousConstSMul + (RingHom.id ℝ) OAI.CKSInducedArea.real_continuousAdd + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSchwarzschild +open Set Filter Manifold Bundle +open scoped ContDiff Topology InnerProductSpace +open CKSBoundarySurface +attribute [local instance] CKSInducedArea.real_continuousAdd CKSInducedArea.real_smulCommClass CKSInducedArea.real_continuousConstSMul CKSBoundarySurface.two_atLeastTwo +attribute [local instance] OAI.CKSSchwarzschild.frameCovectorModule + + +def christoffelPair (g : OAI.CKSBoundarySurface.E3 → OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (x a b c : OAI.CKSBoundarySurface.E3) : ℝ := + 1/2 * (fderiv ℝ (fun z => g z b c) x a + + fderiv ℝ (fun z => g z a c) x b - fderiv ℝ (fun z => g z a b) x c) + +def firstFrame (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + (Real.sqrt (g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 0 1))))⁻¹ • + EuclideanSpace.single 0 1 + +def secondResidual (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + EuclideanSpace.single 1 1 - + (g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 1 1)) / + g (T (EuclideanSpace.single 0 1)) (T (EuclideanSpace.single 0 1))) • EuclideanSpace.single 0 1 + +def secondFrame (g : OAI.CKSBoundarySurface.E3 →L[ℝ] OAI.CKSBoundarySurface.E3 →L[ℝ] ℝ) (T : OAI.CKSBoundarySurface.E2 →L[ℝ] OAI.CKSBoundarySurface.E3) : OAI.CKSBoundarySurface.E2 := + (Real.sqrt (g (T (OAI.CKSSchwarzschild.secondResidual g T)) (T (OAI.CKSSchwarzschild.secondResidual g T))))⁻¹ • OAI.CKSSchwarzschild.secondResidual g T + +end OAI.CKSSchwarzschild +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Manifold CKSGeometricCuts +open scoped ContDiff +variable {N : Type*} [TopologicalSpace N] [ChartedSpace H3 N] + +local instance halfSpace_locallyCompact : LocallyCompactSpace OAI.CKSGeometricCuts.H3 := by + change LocallyCompactSpace {x : EuclideanSpace ℝ (Fin 3) // 0 ≤ x 0} + have hc : IsClosed {x : EuclideanSpace ℝ (Fin 3) | 0 ≤ x 0} := + isClosed_le continuous_const (by fun_prop) + exact hc.locallyCompactSpace + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Manifold CKSGeometricCuts +open scoped ContDiff +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] + +local instance manifold_regular [IsManifold OAI.CKSGeometricCuts.I3 ∞ N] [T2Space N] : T3Space N := by + let := OAI.CKSSourceExterior.halfSpace_locallyCompact + let : LocallyCompactSpace N := ChartedSpace.locallyCompactSpace OAI.CKSGeometricCuts.H3 N + infer_instance + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSSourceExterior +open Set Manifold Bundle Filter CKSLorentz CKSMetricGluing CKSSpatialManifold CKSGeometricCuts +open CKSADM (Symbol) +open scoped ContDiff Topology +variable {N : Type u_1} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + [T2Space N] [SecondCountableTopology N] [ConnectedSpace N] +attribute [local instance] manifold_regular + + +theorem area_controlled_end_replacement + (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) + (hK : ContMDiff OAI.CKSGeometricCuts.I3 (OAI.CKSGeometricCuts.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSGeometricCuts.I3 K)) + (hKsym : ∀ x v w, K x v w = K x w v) + (hOrient : OAI.CKSSourceExterior.Orientable (N := N)) + (hScompact : IsCompact (OAI.CKSGeometricCuts.I3.boundary N)) (hSnonempty : (OAI.CKSGeometricCuts.I3.boundary N).Nonempty) + (hcomplete : OAI.CKSReplacementCompleteness.IsComplete OAI.CKSGeometricCuts.I3 g.toContinuousRiemannianMetric) + (hDEC : OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSGeometricCuts.I3 g.inner K) + (d : OAI.CKSSourceExterior.CKSData g K) + (ht : ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖ < (OAI.CKSLorentz.bondiCharge d.massAspect).1) : + ∃ (d' : OAI.CKSSourceExterior.CKSData g K) (R₀ : ℝ) (ε : ℝ → ℝ), + OAI.CKSLorentz.bondiCharge d'.massAspect = + (Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2),0) ∧ + d'.chart.radius < R₀ ∧ 12 ≤ R₀ ∧ Tendsto ε atTop (𝓝 0) ∧ + OAI.CKSFullCutArea.minEnclosingArea g < ⊤ ∧ + ∀ R ≥ R₀, (0 ≤ ε R ∧ ε R < 1) ∧ + ∃ (gR : OAI.CKSMetricGluing.SmoothMetric OAI.CKSGeometricCuts.I3 (M := N)) (kR : OAI.CKSMetricGluing.InnerField OAI.CKSGeometricCuts.I3 (M := N)) + (G k : OAI.CKSLorentz.SpatialTensor) (η : ℝ), + ContMDiff OAI.CKSGeometricCuts.I3 (OAI.CKSGeometricCuts.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSGeometricCuts.I3 kR) ∧ + (∀ x v w, kR x v w = kR x w v) ∧ + (∀ x, x ∉ d'.chart.domain ∨ ‖d'.chart.coordinate x‖ ≤ R → + gR.inner x = g.inner x ∧ kR x = K x) ∧ + OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSGeometricCuts.I3 gR.inner kR ∧ + (∀ x v, (1-ε R) * g.inner x v v ≤ gR.inner x v v) ∧ + OAI.CKSReplacementCompleteness.IsComplete OAI.CKSGeometricCuts.I3 gR.toContinuousRiemannianMetric ∧ + OAI.CKSSourceExterior.constraintsIntegrable gR kR ∧ + (∀ x ∈ d'.chart.domain, + gR.inner x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 d'.chart.coordinate G x ∧ + kR x = OAI.CKSSpatialManifold.endInner OAI.CKSGeometricCuts.I3 d'.chart.coordinate k x) ∧ + (∀ i j : Fin 3, OAI.CKSADM.Symbol 1 + (fun x => OAI.CKSLorentz.spatialCartesian G x i j - (if i=j then 1 else 0))) ∧ + (∀ x : OAI.CKSLorentz.E, 2*R^2 < ‖x‖ → k x = 0) ∧ + Tendsto (OAI.CKSLorentz.spatialADMEnergy G) atTop + (𝓝 (Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2) + η)) ∧ + Tendsto (OAI.CKSLorentz.spatialADMMomentum G k) atTop (𝓝 0) ∧ + 0 ≤ η ∧ η ≤ 2 * R ^ (-(1/2 : ℝ)) ∧ + OAI.CKSFullCutArea.minEnclosingArea gR < ⊤ ∧ + (1-ε R) * OAI.CKSSourceExterior.minimumEnclosingArea g ≤ OAI.CKSSourceExterior.minimumEnclosingArea gR ∧ + ∀ D : OAI.CKSGeometricCuts.OuterDomain N, + OAI.CKSFullCutArea.area g D < ⊤ ∧ OAI.CKSFullCutArea.area gR D < ⊤ ∧ + (1-ε R) * OAI.CKSSourceExterior.cutArea g D ≤ OAI.CKSSourceExterior.cutArea gR D := by + sorry + +end OAI.CKSSourceExterior +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular + + +def secondForm (q : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) (ν : OAI.CKSBoundarySurface.E3) + (a b : OAI.CKSBoundarySurface.E2) : ℝ := + -(q (f y) ν (fderiv ℝ (fun z => fderiv ℝ f z b) y a) + + OAI.CKSSchwarzschild.christoffelPair q (f y) (fderiv ℝ f y a) (fderiv ℝ f y b) ν) + +def meanCurvature (q : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) (ν : OAI.CKSBoundarySurface.E3) : ℝ := + let a := OAI.CKSSchwarzschild.firstFrame (q (f y)) (fderiv ℝ f y) + let b := OAI.CKSSchwarzschild.secondFrame (q (f y)) (fderiv ℝ f y) + OAI.CKSMain.secondForm q f y ν a a + OAI.CKSMain.secondForm q f y ν b b + +def tangentialTrace (q k : OAI.CKSLorentz.SpatialTensor) (f : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3) (y : OAI.CKSBoundarySurface.E2) : ℝ := + let a := fderiv ℝ f y (OAI.CKSSchwarzschild.firstFrame (q (f y)) (fderiv ℝ f y)) + let b := fderiv ℝ f y (OAI.CKSSchwarzschild.secondFrame (q (f y)) (fderiv ℝ f y)) + k (f y) a a + k (f y) b b + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +structure BoundaryGeometry (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) where + normal : ∀ p : OAI.CKSBoundarySurface.Boundary N, TangentSpace OAI.CKSBoundarySurface.I3 p.val + unit : ∀ p, q.inner p.val (normal p) (normal p) = 1 + orthogonal : ∀ p a, q.inner p.val (normal p) + (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 (Subtype.val : OAI.CKSBoundarySurface.Boundary N → N) p a) = 0 + inward : ∀ p, 0 < (show OAI.CKSBoundarySurface.E3 from normal p) 0 + chart : ∀ p : OAI.CKSBoundarySurface.Boundary N, OAI.CKSIntrinsicConstraints.ConstraintChart q.inner k p.val + normal_smooth : ∀ p, ContMDiffAt OAI.CKSBoundarySurface.I2 𝓘(ℝ,OAI.CKSBoundarySurface.E3) ∞ + (fun z : OAI.CKSBoundarySurface.Boundary N => mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) (chart p).coordinate z.val (normal z)) p + +def BoundaryGeometry.parameter {q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (B : OAI.CKSMain.BoundaryGeometry q k) (p : OAI.CKSBoundarySurface.Boundary N) : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3 := + (B.chart p).coordinate ∘ (Subtype.val : OAI.CKSBoundarySurface.Boundary N → N) ∘ (extChartAt OAI.CKSBoundarySurface.I2 p).symm + +def BoundaryGeometry.thetaPlus {q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (B : OAI.CKSMain.BoundaryGeometry q k) (p : OAI.CKSBoundarySurface.Boundary N) : ℝ := + let c := B.chart p + let f := B.parameter p + let y := (extChartAt OAI.CKSBoundarySurface.I2 p) p + let ν := mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) c.coordinate p.val (B.normal p) + OAI.CKSMain.meanCurvature c.metric f y ν + OAI.CKSMain.tangentialTrace c.metric c.tensor f y + +def MarginalBoundary (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) : Prop := + ∃ B : OAI.CKSMain.BoundaryGeometry q k, ∀ p, B.thetaPlus p = 0 + +def bondiMass {g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)} {K : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)} + (d : OAI.CKSSourceExterior.CKSData g K) : ℝ := + Real.sqrt ((OAI.CKSLorentz.bondiCharge d.massAspect).1^2 - ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖^2) + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology InnerProductSpace +open CKSSchwarzschild +attribute [local instance] manifold_regular +attribute [local instance] CKSIntrinsicConstraints.halfSpaceDimension_neZero +attribute [local instance] CKSSpatialManifold.real_id_isometric CKSLorentz.real_smulCommClass CKSLorentz.spatialDual_smulCommClass + + +local instance atlas_manifold_one {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] : IsManifold OAI.CKSBoundarySurface.I3 1 N := inferInstance + +local instance atlas_tangent_vectorBundle {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] : + letI := OAI.CKSMain.atlas_manifold_one (N := N) + VectorBundle ℝ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) := by + infer_instance + +abbrev CoefficientAtlas {N : Type u_1} [TopologicalSpace N] [ChartedSpace OAI.CKSBoundarySurface.H3 N] + [IsManifold OAI.CKSBoundarySurface.I3 ∞ N] (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) := + letI := OAI.CKSMain.atlas_manifold_one (N := N) + letI := OAI.CKSMain.atlas_tangent_vectorBundle (N := N) + let metric : ContMDiffRiemannianMetric OAI.CKSBoundarySurface.I3 ∞ OAI.CKSBoundarySurface.E3 (fun x : N => TangentSpace OAI.CKSBoundarySurface.I3 x) := q + ∀ x : N, OAI.CKSIntrinsicConstraints.ConstraintChart metric.inner k x + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +structure InteriorSurface (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (A : OAI.CKSMain.CoefficientAtlas q k) (T : Type v) [TopologicalSpace T] [ChartedSpace OAI.CKSBoundarySurface.E2 T] + [IsManifold OAI.CKSBoundarySurface.I2 ∞ T] where + map : T → N + smooth : ContMDiff OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 ∞ map + embedding : Topology.IsEmbedding map + immersion : ∀ p, Function.Injective (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 map p) + interior : ∀ p, map p ∈ OAI.CKSBoundarySurface.I3.interior N + normal : ∀ p, TangentSpace OAI.CKSBoundarySurface.I3 (map p) + normal_unit : ∀ p, q.inner (map p) (normal p) (normal p) = 1 + normal_orthogonal : ∀ p a, q.inner (map p) (normal p) (mfderiv OAI.CKSBoundarySurface.I2 OAI.CKSBoundarySurface.I3 map p a) = 0 + normal_smooth : ∀ p, ContMDiffAt OAI.CKSBoundarySurface.I2 𝓘(ℝ,OAI.CKSBoundarySurface.E3) ∞ + (fun t => mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) (A (map p)).coordinate (map t) (normal t)) p + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain.InteriorSurface +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +variable {q : SmoothMetric I3 (M := N)} {k : InnerField I3 (M := N)} + {A : CoefficientAtlas q k} {T : Type v} [TopologicalSpace T] [ChartedSpace E2 T] + [IsManifold I2 ∞ T] (D : InteriorSurface q k A T) + +def parameter (p : T) : OAI.CKSBoundarySurface.E2 → OAI.CKSBoundarySurface.E3 := + (A (D.map p)).coordinate ∘ D.map ∘ (extChartAt OAI.CKSBoundarySurface.I2 p).symm + +def mean (p : T) : ℝ := + let c := A (D.map p) + OAI.CKSMain.meanCurvature c.metric (D.parameter p) ((extChartAt OAI.CKSBoundarySurface.I2 p) p) + (mfderiv OAI.CKSBoundarySurface.I3 𝓘(ℝ,OAI.CKSBoundarySurface.E3) c.coordinate (D.map p) (D.normal p)) + +def trace (p : T) : ℝ := + let c := A (D.map p) + OAI.CKSMain.tangentialTrace c.metric c.tensor (D.parameter p) ((extChartAt OAI.CKSBoundarySurface.I2 p) p) + +def thetaPlus (p : T) : ℝ := D.mean p + D.trace p + +def thetaMinus (p : T) : ℝ := D.mean p - D.trace p + +def SeparatesAway (c : OAI.CKSSourceExterior.CoordinateEnd (N := N)) : Prop := + ∃ B : Set N, B = closure (_root_.interior B) ∧ (_root_.interior B).Nonempty ∧ + frontier B = range D.map ∧ + ∃ r : ℝ, c.radius < r ∧ B ⊆ {x | x ∉ c.domain ∨ ‖c.coordinate x‖ ≤ r} + +def ComponentwiseApparent : Prop := + ∀ p : T, (∀ z ∈ connectedComponent p, D.thetaPlus z = 0) ∨ + (∀ z ∈ connectedComponent p, D.thetaMinus z = 0) + +end OAI.CKSMain.InteriorSurface +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] + +def NoAdditionalHorizons (q : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (k : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (c : OAI.CKSSourceExterior.CoordinateEnd (N := N)) (A : OAI.CKSMain.CoefficientAtlas q k) : Prop := + ∀ (T : Type v) [TopologicalSpace T] [ChartedSpace OAI.CKSBoundarySurface.E2 T] [IsManifold OAI.CKSBoundarySurface.I2 ∞ T] + [T2Space T] [SecondCountableTopology T] [CompactSpace T] [Nonempty T] + (D : OAI.CKSMain.InteriorSurface q k A T), D.SeparatesAway c → ¬ D.ComponentwiseApparent + +structure MainHypotheses [T2Space N] [SecondCountableTopology N] [ConnectedSpace N] + (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := N)) (K : OAI.CKSMetricGluing.InnerField OAI.CKSBoundarySurface.I3 (M := N)) + (d : OAI.CKSSourceExterior.CKSData g K) (A : OAI.CKSMain.CoefficientAtlas g K) : Prop where + smooth_tensor : ContMDiff OAI.CKSBoundarySurface.I3 (OAI.CKSBoundarySurface.I3.prod 𝓘(ℝ,OAI.CKSLorentz.SpatialBilinear)) ∞ (OAI.CKSMetricGluing.innerSection OAI.CKSBoundarySurface.I3 K) + symmetric_tensor : ∀ x v w, K x v w = K x w v + orientable : OAI.CKSSourceExterior.Orientable (N := N) + boundary_compact : IsCompact (OAI.CKSBoundarySurface.I3.boundary N) + boundary_nonempty : (OAI.CKSBoundarySurface.I3.boundary N).Nonempty + complete : OAI.CKSReplacementCompleteness.IsComplete OAI.CKSBoundarySurface.I3 g.toContinuousRiemannianMetric + dec : OAI.CKSSpatialManifold.PhysicalDEC OAI.CKSBoundarySurface.I3 g.inner K + timelike : ‖(OAI.CKSLorentz.bondiCharge d.massAspect).2‖ < (OAI.CKSLorentz.bondiCharge d.massAspect).1 + boundary_connected : ConnectedSpace (OAI.CKSBoundarySurface.Boundary N) + boundary_marginal : OAI.CKSMain.MarginalBoundary g K + positive_area : 0 < OAI.CKSSourceExterior.minimumEnclosingArea g + no_horizons : OAI.CKSMain.NoAdditionalHorizons.{u,v} g K d.chart A + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +variable {N : Type u} [TopologicalSpace N] [ChartedSpace H3 N] [IsManifold I3 ∞ N] +attribute [local instance] sixteen_atLeastTwo + + +def SchwarzschildExample (m : ℝ) (_hm : 0 < m) : Prop := + ∃ (g : OAI.CKSMetricGluing.SmoothMetric OAI.CKSBoundarySurface.I3 (M := OAI.CKSSchwarzschild.Exterior)) + (d : OAI.CKSSourceExterior.CKSData g (OAI.CKSSchwarzschild.tensorInner m)) + (A : OAI.CKSMain.CoefficientAtlas g (OAI.CKSSchwarzschild.tensorInner m)), + (∀ p, g.inner p = OAI.CKSSchwarzschild.metricInner m p) ∧ + OAI.CKSMain.MainHypotheses.{0,v} g (OAI.CKSSchwarzschild.tensorInner m) d A ∧ + OAI.CKSSchwarzschild.HorizonRegularGraph m ∧ + OAI.CKSMain.bondiMass d = m ∧ + OAI.CKSSourceExterior.minimumEnclosingArea g = 16*Real.pi*m^2 ∧ + OAI.CKSMain.bondiMass d = Real.sqrt (OAI.CKSSourceExterior.minimumEnclosingArea g / (16*Real.pi)) + +end OAI.CKSMain +end + +noncomputable section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 +namespace OAI.CKSMain +open Set Filter Manifold Bundle CKSLorentz CKSMetricGluing CKSSpatialManifold +open CKSBoundarySurface CKSIntrinsicConstraints CKSSourceExterior +open scoped ContDiff Topology +attribute [local instance] manifold_regular +open CKSSchwarzschild + +theorem schwarzschild_equality_examples (m : ℝ) (hm : 0 < m) : + SchwarzschildExample.{v} m hm := by + sorry + +end OAI.CKSMain +end diff --git a/tasks/cks-bondi-penrose/tests/grade.py b/tasks/cks-bondi-penrose/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cks-bondi-penrose/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cks-bondi-penrose/tests/task.json b/tasks/cks-bondi-penrose/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f0fb48c60a3540bc473e4386140d09a1df488c5c --- /dev/null +++ b/tasks/cks-bondi-penrose/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "CKSBondiPenrose", + "comparator": { + "theorem_names": [ + "OAI.CKSSourceExterior.area_controlled_end_replacement", + "OAI.CKSMain.schwarzschild_equality_examples" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13346 +} \ No newline at end of file diff --git a/tasks/cks-bondi-penrose/tests/test.sh b/tasks/cks-bondi-penrose/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cks-bondi-penrose/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/classical-on/environment/Dockerfile b/tasks/classical-on/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/classical-on/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/classical-on/environment/fetch_mathlib.sh b/tasks/classical-on/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/classical-on/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/classical-on/environment/lake-manifest.json b/tasks/classical-on/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/classical-on/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/classical-on/environment/lakefile.lean b/tasks/classical-on/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/classical-on/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/classical-on/environment/lean_setup.sh b/tasks/classical-on/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/classical-on/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/classical-on/environment/pack_submission.py b/tasks/classical-on/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/classical-on/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/classical-on/instruction.md b/tasks/classical-on/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9a4ae6d7e4fb37eb18d1cf7c2393daa9160309b --- /dev/null +++ b/tasks/classical-on/instruction.md @@ -0,0 +1,111 @@ +# openai/math challenge `ClassicalON` (family 215) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 215 of the release, *Massive continuum limits and exact mass asymptotics for planar $O(n)$ models* +(Probability and statistical mechanics). The family as a whole: Constructs the canonical continuum limit of the two-dimensional nearest-neighbor $O(3)$ model: a non-Gaussian local relativistic theory with a unique vacuum and a positive mass gap. For the square-lattice $O(4)$ model, determines the exact leading asymptotic of the full transfer gap, $m_{\mathrm{lat}}(\beta)\sim32e^{\pi/4-1/2}\sqrt\beta\,e^{-\pi\beta}$. The family also proves exponential spin-correlation decay for two-dimensional nearest-neighbor $O(n)$ models with $n\ge3$ at every positive temperature. + +The challenge is `ClassicalON`, also at `/opt/openai-math/challenges/ClassicalON.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped BigOperators InnerProductSpace + +namespace ClassicalON + +abbrev Site := ℤ × ℤ + +def PositiveNeighbor (x y : Site) : Prop := + (y.1 = x.1 + 1 ∧ y.2 = x.2) ∨ (y.1 = x.1 ∧ y.2 = x.2 + 1) + +structure LatticeGraph where + vertices : Finset Site + edges : Finset (vertices × vertices) + nearest : ∀ e ∈ edges, PositiveNeighbor e.1.val e.2.val + +abbrev Spin (n : ℕ) := ↥(Metric.sphere (0 : EuclideanSpace ℝ (Fin n)) 1) +abbrev Configuration (n : ℕ) (G : LatticeGraph) := G.vertices → Spin n + +def sphereProbability (n : ℕ) : Measure (Spin n) := + let surface := (volume : Measure (EuclideanSpace ℝ (Fin n))).toSphere + (surface Set.univ)⁻¹ • surface + +def referenceLaw (n : ℕ) (G : LatticeGraph) : Measure (Configuration n G) := + Measure.pi (fun _ => sphereProbability n) + +def interaction (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) + (σ : Configuration n G) : ℝ := + ∑ e : G.edges, b e * ⟪(σ e.val.1).val, (σ e.val.2).val⟫_ℝ + +def partition (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) : ℝ := + ∫ σ, Real.exp (interaction n G b σ) ∂referenceLaw n G + +def correlation (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) + (x y : G.vertices) : ℝ := + (∫ σ, ⟪(σ x).val, (σ y).val⟫_ℝ * Real.exp (interaction n G b σ) + ∂referenceLaw n G) / partition n G b + +def siteDistance (x y : Site) : ℝ := + Real.sqrt (((x.1 : ℝ) - (y.1 : ℝ)) ^ 2 + ((x.2 : ℝ) - (y.2 : ℝ)) ^ 2) + +def ExponentialDecay : Prop := + ∀ (n : ℕ), 3 ≤ n → ∀ (β : ℝ), 0 < β → + ∃ A m : ℝ, 0 < m ∧ ∀ (G : LatticeGraph) (b : G.edges → ℝ), + (∀ e, 0 ≤ b e ∧ b e ≤ β) → ∀ x y : G.vertices, + 0 ≤ correlation n G b x y ∧ + correlation n G b x y ≤ A * Real.exp (-m * siteDistance x.val y.val) + +theorem main : ExponentialDecay := by + sorry + +end ClassicalON + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ClassicalON.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ClassicalON.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/classical-on/solution/closure.txt b/tasks/classical-on/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..caf1d861fd04203240e6d42a20abc476507dbe18 --- /dev/null +++ b/tasks/classical-on/solution/closure.txt @@ -0,0 +1,117 @@ +OAI.Probability.ClassicalON.AmplitudeLaw +OAI.Probability.ClassicalON.AmplitudeModular +OAI.Probability.ClassicalON.AmplitudePartition +OAI.Probability.ClassicalON.AmplitudeSplit +OAI.Probability.ClassicalON.AnnulusBlocks +OAI.Probability.ClassicalON.AnnulusCrossing +OAI.Probability.ClassicalON.AnnulusCut +OAI.Probability.ClassicalON.AnnulusLabels +OAI.Probability.ClassicalON.AnnulusPartition +OAI.Probability.ClassicalON.AnnulusResponse +OAI.Probability.ClassicalON.AnnulusSmall +OAI.Probability.ClassicalON.AssociationCore +OAI.Probability.ClassicalON.AxisRotation +OAI.Probability.ClassicalON.BlockGeometry +OAI.Probability.ClassicalON.BlockKernel +OAI.Probability.ClassicalON.BlockLocal +OAI.Probability.ClassicalON.BlockOrbit +OAI.Probability.ClassicalON.BlockReduction +OAI.Probability.ClassicalON.BondAssociation +OAI.Probability.ClassicalON.BondConnectivity +OAI.Probability.ClassicalON.BondExpansion +OAI.Probability.ClassicalON.BondLaw +OAI.Probability.ClassicalON.BondMeanOrder +OAI.Probability.ClassicalON.BondMoments +OAI.Probability.ClassicalON.BondPin +OAI.Probability.ClassicalON.BondSigns +OAI.Probability.ClassicalON.BondSubspace +OAI.Probability.ClassicalON.CenteredAnnulus +OAI.Probability.ClassicalON.CoarseCodes +OAI.Probability.ClassicalON.CoarseExponential +OAI.Probability.ClassicalON.CoarseGeometry +OAI.Probability.ClassicalON.CoarsePaths +OAI.Probability.ClassicalON.CoarseTail +OAI.Probability.ClassicalON.ComplexWard +OAI.Probability.ClassicalON.CylindricalConfiguration +OAI.Probability.ClassicalON.CylindricalFiber +OAI.Probability.ClassicalON.CylindricalGeometry +OAI.Probability.ClassicalON.CylindricalLaw +OAI.Probability.ClassicalON.DiscreteReference +OAI.Probability.ClassicalON.DyadicFourier +OAI.Probability.ClassicalON.DyadicModes +OAI.Probability.ClassicalON.DyadicSine +OAI.Probability.ClassicalON.DyadicSums +OAI.Probability.ClassicalON.EdgeOperators +OAI.Probability.ClassicalON.ExpMoments +OAI.Probability.ClassicalON.FamilyAlgebra +OAI.Probability.ClassicalON.FamilyBound +OAI.Probability.ClassicalON.FamilyEstimate +OAI.Probability.ClassicalON.FamilyKernel +OAI.Probability.ClassicalON.FamilyLower +OAI.Probability.ClassicalON.FerromagneticMean +OAI.Probability.ClassicalON.FinFKG +OAI.Probability.ClassicalON.FiniteVolume +OAI.Probability.ClassicalON.FourierOperator +OAI.Probability.ClassicalON.GibbsCovariance +OAI.Probability.ClassicalON.GibbsDerivative +OAI.Probability.ClassicalON.GradientComplex +OAI.Probability.ClassicalON.IsingGinibre +OAI.Probability.ClassicalON.IsingPositive +OAI.Probability.ClassicalON.IsingReference +OAI.Probability.ClassicalON.JointBond +OAI.Probability.ClassicalON.LatticeGeometry +OAI.Probability.ClassicalON.LatticeModes +OAI.Probability.ClassicalON.LatticeRadius +OAI.Probability.ClassicalON.LatticeRestriction +OAI.Probability.ClassicalON.Main +OAI.Probability.ClassicalON.MatrixSquare +OAI.Probability.ClassicalON.MixedWard +OAI.Probability.ClassicalON.ModeBounds +OAI.Probability.ClassicalON.ModeCommutator +OAI.Probability.ClassicalON.ModeCosts +OAI.Probability.ClassicalON.Model +OAI.Probability.ClassicalON.MomentCone +OAI.Probability.ClassicalON.ObservableBounds +OAI.Probability.ClassicalON.OrthogonalAverage +OAI.Probability.ClassicalON.PeriodicODE +OAI.Probability.ClassicalON.PeriodicPartition +OAI.Probability.ClassicalON.PinComparison +OAI.Probability.ClassicalON.PinnedBlocks +OAI.Probability.ClassicalON.PinnedBonds +OAI.Probability.ClassicalON.PinnedCylinder +OAI.Probability.ClassicalON.PinnedReference +OAI.Probability.ClassicalON.PinnedSigns +OAI.Probability.ClassicalON.PlanarAlgebra +OAI.Probability.ClassicalON.PlanarGinibre +OAI.Probability.ClassicalON.PlanarPositive +OAI.Probability.ClassicalON.PoleCrossing +OAI.Probability.ClassicalON.PositiveKernel +OAI.Probability.ClassicalON.PotentialRotation +OAI.Probability.ClassicalON.ProductFKG +OAI.Probability.ClassicalON.ProductGrouping +OAI.Probability.ClassicalON.ProductMoments +OAI.Probability.ClassicalON.ProfileEstimates +OAI.Probability.ClassicalON.RawBond +OAI.Probability.ClassicalON.ReindexIntegral +OAI.Probability.ClassicalON.ResponseTransfer +OAI.Probability.ClassicalON.RotationInequality +OAI.Probability.ClassicalON.RotationWork +OAI.Probability.ClassicalON.SecondBound +OAI.Probability.ClassicalON.SecondGauge +OAI.Probability.ClassicalON.SeparatedAnnuli +OAI.Probability.ClassicalON.SignedSigns +OAI.Probability.ClassicalON.SmoothBounds +OAI.Probability.ClassicalON.SmoothProfiles +OAI.Probability.ClassicalON.SpinBondKernel +OAI.Probability.ClassicalON.SpinBonds +OAI.Probability.ClassicalON.SpinCorrelation +OAI.Probability.ClassicalON.SpinIsotropy +OAI.Probability.ClassicalON.SpinReindex +OAI.Probability.ClassicalON.SquareEstimates +OAI.Probability.ClassicalON.ThetaEstimates +OAI.Probability.ClassicalON.TorusDouble +OAI.Probability.ClassicalON.TorusFourier +OAI.Probability.ClassicalON.UpperEndpoint +OAI.Probability.ClassicalON.WeightedLinear +OAI.Probability.ClassicalON.WeightedProduct +OAI.Probability.ClassicalON.WeightedTilt diff --git a/tasks/classical-on/solution/reference.py b/tasks/classical-on/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/classical-on/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/classical-on/solution/solve.sh b/tasks/classical-on/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0bdc9f4e5eaac2c401e0969671b786739ac09c6c --- /dev/null +++ b/tasks/classical-on/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ClassicalON, i.e. module OAI.Probability.ClassicalON.Main and the +# 117 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ClassicalON.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ClassicalON" diff --git a/tasks/classical-on/task.toml b/tasks/classical-on/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..638fe5886c906d6cc35c8890e03453bec9f3819d --- /dev/null +++ b/tasks/classical-on/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/classical-on" +version = "1.0.0" +description = "Prove ClassicalON (openai/math family 215: Massive continuum limits and exact mass asymptotics for planar $O(n)$ models) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ClassicalON.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ClassicalON" +family = "215" +family_title = "Massive continuum limits and exact mass asymptotics for planar $O(n)$ models" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ClassicalON.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ClassicalON.Main" +reference_modules = 117 +reference_lean_bytes = 582811 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1392 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12224 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/classical-on/tests/Challenge.lean b/tasks/classical-on/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c217967fbf85e6066bf39aebfdf4f5656a46d612 --- /dev/null +++ b/tasks/classical-on/tests/Challenge.lean @@ -0,0 +1,60 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped BigOperators InnerProductSpace + +namespace ClassicalON + +abbrev Site := ℤ × ℤ + +def PositiveNeighbor (x y : Site) : Prop := + (y.1 = x.1 + 1 ∧ y.2 = x.2) ∨ (y.1 = x.1 ∧ y.2 = x.2 + 1) + +structure LatticeGraph where + vertices : Finset Site + edges : Finset (vertices × vertices) + nearest : ∀ e ∈ edges, PositiveNeighbor e.1.val e.2.val + +abbrev Spin (n : ℕ) := ↥(Metric.sphere (0 : EuclideanSpace ℝ (Fin n)) 1) +abbrev Configuration (n : ℕ) (G : LatticeGraph) := G.vertices → Spin n + +def sphereProbability (n : ℕ) : Measure (Spin n) := + let surface := (volume : Measure (EuclideanSpace ℝ (Fin n))).toSphere + (surface Set.univ)⁻¹ • surface + +def referenceLaw (n : ℕ) (G : LatticeGraph) : Measure (Configuration n G) := + Measure.pi (fun _ => sphereProbability n) + +def interaction (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) + (σ : Configuration n G) : ℝ := + ∑ e : G.edges, b e * ⟪(σ e.val.1).val, (σ e.val.2).val⟫_ℝ + +def partition (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) : ℝ := + ∫ σ, Real.exp (interaction n G b σ) ∂referenceLaw n G + +def correlation (n : ℕ) (G : LatticeGraph) (b : G.edges → ℝ) + (x y : G.vertices) : ℝ := + (∫ σ, ⟪(σ x).val, (σ y).val⟫_ℝ * Real.exp (interaction n G b σ) + ∂referenceLaw n G) / partition n G b + +def siteDistance (x y : Site) : ℝ := + Real.sqrt (((x.1 : ℝ) - (y.1 : ℝ)) ^ 2 + ((x.2 : ℝ) - (y.2 : ℝ)) ^ 2) + +def ExponentialDecay : Prop := + ∀ (n : ℕ), 3 ≤ n → ∀ (β : ℝ), 0 < β → + ∃ A m : ℝ, 0 < m ∧ ∀ (G : LatticeGraph) (b : G.edges → ℝ), + (∀ e, 0 ≤ b e ∧ b e ≤ β) → ∀ x y : G.vertices, + 0 ≤ correlation n G b x y ∧ + correlation n G b x y ≤ A * Real.exp (-m * siteDistance x.val y.val) + +theorem main : ExponentialDecay := by + sorry + +end ClassicalON + +end + +end OAI diff --git a/tasks/classical-on/tests/grade.py b/tasks/classical-on/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/classical-on/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/classical-on/tests/task.json b/tasks/classical-on/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4c4a1be2413948ebe2d4cce40930a3c2bfce3e87 --- /dev/null +++ b/tasks/classical-on/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ClassicalON", + "comparator": { + "theorem_names": [ + "OAI.ClassicalON.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11324 +} \ No newline at end of file diff --git a/tasks/classical-on/tests/test.sh b/tasks/classical-on/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/classical-on/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/clique-free-log/environment/Dockerfile b/tasks/clique-free-log/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/clique-free-log/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/clique-free-log/environment/fetch_mathlib.sh b/tasks/clique-free-log/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/clique-free-log/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/clique-free-log/environment/lake-manifest.json b/tasks/clique-free-log/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/clique-free-log/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/clique-free-log/environment/lakefile.lean b/tasks/clique-free-log/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/clique-free-log/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/clique-free-log/environment/lean_setup.sh b/tasks/clique-free-log/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/clique-free-log/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/clique-free-log/environment/pack_submission.py b/tasks/clique-free-log/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/clique-free-log/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/clique-free-log/instruction.md b/tasks/clique-free-log/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e1f08f5f3b324795a3d9ce49c4846590d6fa2d97 --- /dev/null +++ b/tasks/clique-free-log/instruction.md @@ -0,0 +1,72 @@ +# openai/math challenge `CliqueFreeLog` (family 184) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 184 of the release, *Coloring and independence in graphs with forbidden subgraphs* +(Combinatorics). The family as a whole: Proves the Alon–Krivelevich–Sudakov coloring conjecture in correspondence-coloring form: graphs avoiding any fixed subgraph $F$ need $O_F(\Delta/\log\Delta)$ colors when their maximum degree $\Delta$ is sufficiently large. Also proves the Ajtai–Erd\H{o}s–Komlos–Szemeredi independence conjecture: for fixed $r\ge4$, every $n$-vertex $K_r$-free graph of average degree $d\ge2$ has an independent set of size $\Omega_r(n\log d/d)$. + +The challenge is `CliqueFreeLog`, also at `/opt/openai-math/challenges/CliqueFreeLog.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CliqueFreeLog + +noncomputable def averageDegree {V : Type*} [Fintype V] (G : SimpleGraph V) : ℝ := by + classical + exact 2 * (G.edgeFinset.card : ℝ) / (Fintype.card V : ℝ) + +theorem logarithmic_independence_bound (r : ℕ) (hr : 4 ≤ r) : + ∃ c : ℝ, 0 < c ∧ + ∀ {V : Type} [Fintype V] (G : SimpleGraph V), + G.CliqueFree r → 2 ≤ averageDegree G → + c * (Fintype.card V : ℝ) * Real.log (averageDegree G) / averageDegree G ≤ + (G.indepNum : ℝ) := by + sorry + +end CliqueFreeLog + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CliqueFreeLog.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CliqueFreeLog.logarithmic_independence_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/clique-free-log/solution/closure.txt b/tasks/clique-free-log/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0563683cceff121ab1aa351a50dc2fbd9825ddb3 --- /dev/null +++ b/tasks/clique-free-log/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Combinatorics.CliqueFree.CrossBound +OAI.Combinatorics.CliqueFree.Deletion +OAI.Combinatorics.CliqueFree.DisjointCross +OAI.Combinatorics.CliqueFree.EdgeState +OAI.Combinatorics.CliqueFree.FiniteCoupling +OAI.Combinatorics.CliqueFree.FiniteEntropy +OAI.Combinatorics.CliqueFree.FiniteKernel +OAI.Combinatorics.CliqueFree.IndependentSet +OAI.Combinatorics.CliqueFree.LocalWalk +OAI.Combinatorics.CliqueFree.Lottery +OAI.Combinatorics.CliqueFree.Main +OAI.Combinatorics.CliqueFree.MaxDegree +OAI.Combinatorics.CliqueFree.Model +OAI.Combinatorics.CliqueFree.MultiplierLaw +OAI.Combinatorics.CliqueFree.Numerical +OAI.Combinatorics.CliqueFree.Optimizer +OAI.Combinatorics.CliqueFree.OptimizerBounds +OAI.Combinatorics.CliqueFree.Packing +OAI.Combinatorics.CliqueFree.Peeling +OAI.Combinatorics.CliqueFree.Projection +OAI.Combinatorics.CliqueFree.Reach +OAI.Combinatorics.CliqueFree.SparseMultipliers +OAI.Combinatorics.CliqueFree.Splitting +OAI.Combinatorics.CliqueFree.SplittingLoss +OAI.Combinatorics.CliqueFree.TriangleBound +OAI.Combinatorics.CliqueFree.TriangleState +OAI.Combinatorics.CliqueFree.VariationalCross +OAI.Combinatorics.CliqueFree.VertexSplitting +OAI.Combinatorics.CliqueFree.WalkCoupling +OAI.Combinatorics.CliqueFree.WalkEntropy +OAI.Combinatorics.CliqueFree.WeightedGraph diff --git a/tasks/clique-free-log/solution/reference.py b/tasks/clique-free-log/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/clique-free-log/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/clique-free-log/solution/solve.sh b/tasks/clique-free-log/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea6dfa4707b76427e0a75aad07cb152f63cfb1c3 --- /dev/null +++ b/tasks/clique-free-log/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CliqueFreeLog, i.e. module OAI.Combinatorics.CliqueFree.Main and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.CliqueFree.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CliqueFreeLog" diff --git a/tasks/clique-free-log/task.toml b/tasks/clique-free-log/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..91786fb3a48a3a5445bb8ea59b17e9cfc2cef0e3 --- /dev/null +++ b/tasks/clique-free-log/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/clique-free-log" +version = "1.0.0" +description = "Prove CliqueFreeLog (openai/math family 184: Coloring and independence in graphs with forbidden subgraphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CliqueFreeLog.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CliqueFreeLog" +family = "184" +family_title = "Coloring and independence in graphs with forbidden subgraphs" +subject = "Combinatorics" +theorems = ["OAI.CliqueFreeLog.logarithmic_independence_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.CliqueFree.Main" +reference_modules = 31 +reference_lean_bytes = 229474 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 794 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11906 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/clique-free-log/tests/Challenge.lean b/tasks/clique-free-log/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8dce79875ebcb7a95bf84282a9ad26a0f7fa957e --- /dev/null +++ b/tasks/clique-free-log/tests/Challenge.lean @@ -0,0 +1,21 @@ +import Mathlib + +namespace OAI + +namespace CliqueFreeLog + +noncomputable def averageDegree {V : Type*} [Fintype V] (G : SimpleGraph V) : ℝ := by + classical + exact 2 * (G.edgeFinset.card : ℝ) / (Fintype.card V : ℝ) + +theorem logarithmic_independence_bound (r : ℕ) (hr : 4 ≤ r) : + ∃ c : ℝ, 0 < c ∧ + ∀ {V : Type} [Fintype V] (G : SimpleGraph V), + G.CliqueFree r → 2 ≤ averageDegree G → + c * (Fintype.card V : ℝ) * Real.log (averageDegree G) / averageDegree G ≤ + (G.indepNum : ℝ) := by + sorry + +end CliqueFreeLog + +end OAI diff --git a/tasks/clique-free-log/tests/grade.py b/tasks/clique-free-log/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/clique-free-log/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/clique-free-log/tests/task.json b/tasks/clique-free-log/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0d14428bf87d5b361e9618729859b8d00329a2e5 --- /dev/null +++ b/tasks/clique-free-log/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CliqueFreeLog", + "comparator": { + "theorem_names": [ + "OAI.CliqueFreeLog.logarithmic_independence_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11006 +} \ No newline at end of file diff --git a/tasks/clique-free-log/tests/test.sh b/tasks/clique-free-log/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/clique-free-log/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coboundary-expanders/environment/Dockerfile b/tasks/coboundary-expanders/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coboundary-expanders/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coboundary-expanders/environment/fetch_mathlib.sh b/tasks/coboundary-expanders/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coboundary-expanders/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coboundary-expanders/environment/lake-manifest.json b/tasks/coboundary-expanders/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coboundary-expanders/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coboundary-expanders/environment/lakefile.lean b/tasks/coboundary-expanders/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coboundary-expanders/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coboundary-expanders/environment/lean_setup.sh b/tasks/coboundary-expanders/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coboundary-expanders/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coboundary-expanders/environment/pack_submission.py b/tasks/coboundary-expanders/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coboundary-expanders/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coboundary-expanders/instruction.md b/tasks/coboundary-expanders/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..556e15a21b46c2df8f6b63ff6a324679e147a627 --- /dev/null +++ b/tasks/coboundary-expanders/instruction.md @@ -0,0 +1,149 @@ +# openai/math challenge `CoboundaryExpanders` (family 177) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 177 of the release, *Bounded-degree coboundary expanders in every dimension* +(Combinatorics). The family as a whole: Constructs arbitrarily large finite $d$-dimensional simplicial complexes, for every $d\ge3$, with uniformly bounded vertex degrees and uniform $\mathbb F_2$ coboundary expansion in every degree below $d$. Together with the known graph and two-dimensional cases, this establishes the existence of such expanders in every positive dimension. + +The challenge is `CoboundaryExpanders`, also at `/opt/openai-math/challenges/CoboundaryExpanders.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Bounded-degree coboundary expanders in every dimension + +Finite connected pure complexes with uniformly bounded top-face incidence and +uniform weighted coboundary expansion over F₂ in all degrees below the dimension. +-/ + +noncomputable section +open scoped BigOperators +open Filter + +namespace CoboundaryExpanders + +/-- A finite abstract simplicial complex with every labelled vertex present. -/ +structure Complex where + vertexCount : ℕ + faces : Finset (Finset (Fin vertexCount)) + empty_mem : ∅ ∈ faces + downward : ∀ {σ τ}, σ ∈ faces → τ ⊆ σ → τ ∈ faces + vertex_mem : ∀ v, {v} ∈ faces + +namespace Complex + +/-- Faces of dimension `i` have exactly `i + 1` vertices. -/ +def facesOf (X : Complex) (i : ℕ) : Finset (Finset (Fin X.vertexCount)) := + X.faces.filter (fun σ => σ.card = i + 1) + +def Face (X : Complex) (i : ℕ) := {σ // σ ∈ X.facesOf i} + +instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := Subtype.fintype _ +instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := Classical.decEq _ + +/-- Exact purity: top faces exist and every face lies in a top face. -/ +def Pure (X : Complex) (s : ℕ) : Prop := + (X.facesOf s).Nonempty ∧ + ∀ σ ∈ X.faces, ∃ τ ∈ X.facesOf s, σ ⊆ τ + +/-- Connectedness of the nonempty one-skeleton. -/ +def Connected (X : Complex) : Prop := + Nonempty (Fin X.vertexCount) ∧ + ∀ v w : Fin X.vertexCount, + Relation.ReflTransGen (fun a b => a ≠ b ∧ {a, b} ∈ X.faces) v w + +abbrev Cochain (X : Complex) (i : ℕ) := X.Face i → ZMod 2 + +/-- Weights are normalized counts of incident top-dimensional faces. -/ +def weight (X : Complex) (s i : ℕ) (σ : X.Face i) : ℝ := + (((X.facesOf s).filter (fun τ => σ.val ⊆ τ)).card : ℝ) / + ((Nat.choose (s + 1) (i + 1) : ℝ) * (X.facesOf s).card) + +/-- Weighted support norm. -/ +def norm (X : Complex) (s i : ℕ) (f : X.Cochain i) : ℝ := + ∑ σ : X.Face i, if f σ ≠ 0 then X.weight s i σ else 0 + +/-- Simplicial coboundary over F₂. -/ +def coboundary (X : Complex) (i : ℕ) (f : X.Cochain i) : X.Cochain (i + 1) := + fun τ => ∑ σ : X.Face i, if σ.val ⊆ τ.val then f σ else 0 + +/-- Actual coboundaries, with constant cochains in degree zero. -/ +def coboundaries (X : Complex) : (i : ℕ) → Set (X.Cochain i) + | 0 => {f | ∃ c : ZMod 2, f = fun _ => c} + | i + 1 => Set.range (X.coboundary i) + +/-- Distance in the weighted support norm; on a nonempty finite set it is a minimum. -/ +def distance (X : Complex) (s i : ℕ) (f : X.Cochain i) + (A : Set (X.Cochain i)) : ℝ := + sInf ((fun a => X.norm s i (f - a)) '' A) + +/-- Number of top-dimensional faces incident to a vertex. -/ +def topDegree (X : Complex) (s : ℕ) (v : Fin X.vertexCount) : ℕ := + ((X.facesOf s).filter (fun τ => v ∈ τ)).card + +end Complex + +/-- Both constants are uniform over the sequence, all degrees below `d`, and all cochains. -/ +def MainStatement : Prop := + ∀ d : ℕ, 3 ≤ d → + ∃ (D : ℕ) (ε : ℝ), 0 < ε ∧ + ∃ X : ℕ → Complex, + (∀ m, (X m).Pure d ∧ (X m).Connected) ∧ + Tendsto (fun m => ((X m).facesOf 0).card) atTop atTop ∧ + (∀ m (v : Fin (X m).vertexCount), (X m).topDegree d v ≤ D) ∧ + ∀ m i, i < d → ∀ f : (X m).Cochain i, + ε * (X m).distance d i f ((X m).coboundaries i) ≤ + (X m).norm d (i + 1) ((X m).coboundary i f) + +theorem main : MainStatement := by + sorry + +end CoboundaryExpanders + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoboundaryExpanders.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CoboundaryExpanders.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coboundary-expanders/solution/closure.txt b/tasks/coboundary-expanders/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6f49dff4c2643ebb9fe3126ea15b34c503c547a6 --- /dev/null +++ b/tasks/coboundary-expanders/solution/closure.txt @@ -0,0 +1,36 @@ +OAI.Combinatorics.Coboundary.Averaging +OAI.Combinatorics.Coboundary.Chains +OAI.Combinatorics.Coboundary.Complex +OAI.Combinatorics.Coboundary.Cones +OAI.Combinatorics.Coboundary.Cosets +OAI.Combinatorics.Coboundary.Expansion +OAI.Combinatorics.Coboundary.FatLadders +OAI.Combinatorics.Coboundary.Joins +OAI.Combinatorics.Coboundary.LinkSpectrum +OAI.Combinatorics.Coboundary.Links +OAI.Combinatorics.Coboundary.Main +OAI.Combinatorics.Coboundary.Mixing +OAI.Combinatorics.Coboundary.Realization +OAI.Combinatorics.Coboundary.Skeleton +OAI.Combinatorics.Coboundary.Spectral +OAI.Geometry.Coboundary.ChamberCones +OAI.Geometry.Coboundary.Chambers +OAI.Geometry.Coboundary.Flags +OAI.Geometry.Coboundary.Frames +OAI.Geometry.Coboundary.LatticeCones +OAI.Geometry.Coboundary.Lattices +OAI.Geometry.Coboundary.Polynomial +OAI.Geometry.Coboundary.Windows +OAI.GroupTheory.Congruence.Basic +OAI.GroupTheory.Congruence.Coinvariants +OAI.GroupTheory.Congruence.CongruenceFrames +OAI.GroupTheory.Congruence.Elementary +OAI.GroupTheory.Congruence.FrameHomology +OAI.GroupTheory.Congruence.HomologyEdge +OAI.GroupTheory.Congruence.OddHomology +OAI.GroupTheory.Congruence.Parabolic +OAI.GroupTheory.Congruence.Patterns +OAI.GroupTheory.Congruence.ProStability +OAI.GroupTheory.Congruence.Resolution +OAI.GroupTheory.Congruence.Stabilization +OAI.GroupTheory.Congruence.Transfer diff --git a/tasks/coboundary-expanders/solution/reference.py b/tasks/coboundary-expanders/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coboundary-expanders/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coboundary-expanders/solution/solve.sh b/tasks/coboundary-expanders/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..877b654cbf23decfd8531515deecd0d97d1a6ae1 --- /dev/null +++ b/tasks/coboundary-expanders/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoboundaryExpanders, i.e. module OAI.Combinatorics.Coboundary.Main and the +# 36 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Coboundary.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoboundaryExpanders" diff --git a/tasks/coboundary-expanders/task.toml b/tasks/coboundary-expanders/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a41a2f3dde20775681b72b47637ba21947f6346f --- /dev/null +++ b/tasks/coboundary-expanders/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coboundary-expanders" +version = "1.0.0" +description = "Prove CoboundaryExpanders (openai/math family 177: Bounded-degree coboundary expanders in every dimension) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoboundaryExpanders.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoboundaryExpanders" +family = "177" +family_title = "Bounded-degree coboundary expanders in every dimension" +subject = "Combinatorics" +theorems = ["OAI.CoboundaryExpanders.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Coboundary.Main" +reference_modules = 36 +reference_lean_bytes = 1459141 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1082 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13013 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coboundary-expanders/tests/Challenge.lean b/tasks/coboundary-expanders/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..404476ff72b0e8c39e85bc3eebd1ea4f3e7a7995 --- /dev/null +++ b/tasks/coboundary-expanders/tests/Challenge.lean @@ -0,0 +1,98 @@ +import Mathlib + +namespace OAI + +/-! +# Bounded-degree coboundary expanders in every dimension + +Finite connected pure complexes with uniformly bounded top-face incidence and +uniform weighted coboundary expansion over F₂ in all degrees below the dimension. +-/ + +noncomputable section +open scoped BigOperators +open Filter + +namespace CoboundaryExpanders + +/-- A finite abstract simplicial complex with every labelled vertex present. -/ +structure Complex where + vertexCount : ℕ + faces : Finset (Finset (Fin vertexCount)) + empty_mem : ∅ ∈ faces + downward : ∀ {σ τ}, σ ∈ faces → τ ⊆ σ → τ ∈ faces + vertex_mem : ∀ v, {v} ∈ faces + +namespace Complex + +/-- Faces of dimension `i` have exactly `i + 1` vertices. -/ +def facesOf (X : Complex) (i : ℕ) : Finset (Finset (Fin X.vertexCount)) := + X.faces.filter (fun σ => σ.card = i + 1) + +def Face (X : Complex) (i : ℕ) := {σ // σ ∈ X.facesOf i} + +instance (X : Complex) (i : ℕ) : Fintype (X.Face i) := Subtype.fintype _ +instance (X : Complex) (i : ℕ) : DecidableEq (X.Face i) := Classical.decEq _ + +/-- Exact purity: top faces exist and every face lies in a top face. -/ +def Pure (X : Complex) (s : ℕ) : Prop := + (X.facesOf s).Nonempty ∧ + ∀ σ ∈ X.faces, ∃ τ ∈ X.facesOf s, σ ⊆ τ + +/-- Connectedness of the nonempty one-skeleton. -/ +def Connected (X : Complex) : Prop := + Nonempty (Fin X.vertexCount) ∧ + ∀ v w : Fin X.vertexCount, + Relation.ReflTransGen (fun a b => a ≠ b ∧ {a, b} ∈ X.faces) v w + +abbrev Cochain (X : Complex) (i : ℕ) := X.Face i → ZMod 2 + +/-- Weights are normalized counts of incident top-dimensional faces. -/ +def weight (X : Complex) (s i : ℕ) (σ : X.Face i) : ℝ := + (((X.facesOf s).filter (fun τ => σ.val ⊆ τ)).card : ℝ) / + ((Nat.choose (s + 1) (i + 1) : ℝ) * (X.facesOf s).card) + +/-- Weighted support norm. -/ +def norm (X : Complex) (s i : ℕ) (f : X.Cochain i) : ℝ := + ∑ σ : X.Face i, if f σ ≠ 0 then X.weight s i σ else 0 + +/-- Simplicial coboundary over F₂. -/ +def coboundary (X : Complex) (i : ℕ) (f : X.Cochain i) : X.Cochain (i + 1) := + fun τ => ∑ σ : X.Face i, if σ.val ⊆ τ.val then f σ else 0 + +/-- Actual coboundaries, with constant cochains in degree zero. -/ +def coboundaries (X : Complex) : (i : ℕ) → Set (X.Cochain i) + | 0 => {f | ∃ c : ZMod 2, f = fun _ => c} + | i + 1 => Set.range (X.coboundary i) + +/-- Distance in the weighted support norm; on a nonempty finite set it is a minimum. -/ +def distance (X : Complex) (s i : ℕ) (f : X.Cochain i) + (A : Set (X.Cochain i)) : ℝ := + sInf ((fun a => X.norm s i (f - a)) '' A) + +/-- Number of top-dimensional faces incident to a vertex. -/ +def topDegree (X : Complex) (s : ℕ) (v : Fin X.vertexCount) : ℕ := + ((X.facesOf s).filter (fun τ => v ∈ τ)).card + +end Complex + +/-- Both constants are uniform over the sequence, all degrees below `d`, and all cochains. -/ +def MainStatement : Prop := + ∀ d : ℕ, 3 ≤ d → + ∃ (D : ℕ) (ε : ℝ), 0 < ε ∧ + ∃ X : ℕ → Complex, + (∀ m, (X m).Pure d ∧ (X m).Connected) ∧ + Tendsto (fun m => ((X m).facesOf 0).card) atTop atTop ∧ + (∀ m (v : Fin (X m).vertexCount), (X m).topDegree d v ≤ D) ∧ + ∀ m i, i < d → ∀ f : (X m).Cochain i, + ε * (X m).distance d i f ((X m).coboundaries i) ≤ + (X m).norm d (i + 1) ((X m).coboundary i f) + +theorem main : MainStatement := by + sorry + +end CoboundaryExpanders + +end + +end OAI diff --git a/tasks/coboundary-expanders/tests/grade.py b/tasks/coboundary-expanders/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coboundary-expanders/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coboundary-expanders/tests/task.json b/tasks/coboundary-expanders/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0fe6234abd22707f66554e09d0c7477f0b257155 --- /dev/null +++ b/tasks/coboundary-expanders/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoboundaryExpanders", + "comparator": { + "theorem_names": [ + "OAI.CoboundaryExpanders.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12113 +} \ No newline at end of file diff --git a/tasks/coboundary-expanders/tests/test.sh b/tasks/coboundary-expanders/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coboundary-expanders/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/common-bases-fpras/environment/Dockerfile b/tasks/common-bases-fpras/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/common-bases-fpras/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/common-bases-fpras/environment/fetch_mathlib.sh b/tasks/common-bases-fpras/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/common-bases-fpras/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/common-bases-fpras/environment/lake-manifest.json b/tasks/common-bases-fpras/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/common-bases-fpras/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/common-bases-fpras/environment/lakefile.lean b/tasks/common-bases-fpras/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/common-bases-fpras/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/common-bases-fpras/environment/lean_setup.sh b/tasks/common-bases-fpras/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/common-bases-fpras/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/common-bases-fpras/environment/pack_submission.py b/tasks/common-bases-fpras/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/common-bases-fpras/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/common-bases-fpras/instruction.md b/tasks/common-bases-fpras/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3f8e0e02acf0ea53b076bd239ace8ba00f701452 --- /dev/null +++ b/tasks/common-bases-fpras/instruction.md @@ -0,0 +1,182 @@ +# openai/math challenge `CommonBasesFPRAS` (family 114) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 114 of the release, *Approximate counting of common integer polymatroid bases* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting common integer bases of two integral polymatroids of equal total rank, supplied by exact rank-value oracles. Capacities are binary-encoded, each integer vector counts once, and oracle calls and bit operations outside the oracles are polynomial on every execution. For matroids presented by independence oracles, the results also cover common independent sets of prescribed, unrestricted, or maximum cardinality, even when the ranks differ. + +The challenge is `CommonBasesFPRAS`, also at `/opt/openai-math/challenges/CommonBasesFPRAS.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CommonBasesFPRAS + +abbrev IndependenceOracle (n : ℕ) := Bool → (Fin n → Bool) → Bool + +def ExactOracles {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) : Prop := + ∀ (which : Bool) (A : Fin n → Bool), + O which A = true ↔ (if which then M₂ else M₁).Indep {i | A i = true} + +noncomputable def commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : ℕ := + Nat.card {A : Finset (Fin n) // M₁.IsBase (A : Set (Fin n)) ∧ + M₂.IsBase (A : Set (Fin n))} + +inductive Instruction (k s : ℕ) where + | push (register : Fin (k + 8)) (bit : Bool) (next : Fin (s + 1)) + | pop (register : Fin (k + 8)) (empty zero one : Fin (s + 1)) + | coin (zero one : Fin (s + 1)) + | query (which : Bool) (register : Fin (k + 8)) (no yes : Fin (s + 1)) + | halt + +def Program (k s : ℕ) := Fin (s + 1) → Instruction k s + +def binaryValue : List Bool → ℕ + | [] => 0 + | b :: l => (if b then 1 else 0) + 2 * binaryValue l + +structure MachineConfig (k s : ℕ) where + registers : Fin (k + 8) → List Bool + control : Fin (s + 1) + output : Option ℚ := none + oracleCalls : ℕ := 0 + bitOperations : ℕ := 0 + +def inputLength (n r : ℕ) (ε δ : ℚ) : ℕ := + 6 + n.bits.length + r.bits.length + ε.num.natAbs.bits.length + ε.den.bits.length + + δ.num.natAbs.bits.length + δ.den.bits.length + +def initialConfig (k s n r : ℕ) (ε δ : ℚ) : MachineConfig k s where + registers := fun i => match i.val with + | 0 => n.bits + | 1 => r.bits + | 2 => ε.num.natAbs.bits + | 3 => ε.den.bits + | 4 => δ.num.natAbs.bits + | 5 => δ.den.bits + | _ => [] + control := 0 + +def machineStep {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (randomBit : Bool) (c : MachineConfig k s) : MachineConfig k s := + if c.output.isSome then c else + match P c.control with + | .push i b next => + { c with + registers := Function.update c.registers i (b :: c.registers i) + control := next + bitOperations := c.bitOperations + 1 } + | .pop i empty zero one => + match c.registers i with + | [] => { c with + control := empty + bitOperations := c.bitOperations + 1 } + | b :: l => + { c with + registers := Function.update c.registers i l + control := if b then one else zero + bitOperations := c.bitOperations + 1 } + | .coin zero one => + { c with + control := if randomBit then one else zero + bitOperations := c.bitOperations + 1 } + | .query which i no yes => + if (c.registers i).length = n then + { c with + control := if O which (fun j => (c.registers i)[j.val]?.getD false) + then yes else no + oracleCalls := c.oracleCalls + 1 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + else + { c with + output := some 0 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + | .halt => + { c with + output := some ((binaryValue (c.registers ⟨6, by omega⟩) : ℚ) / + (binaryValue (c.registers ⟨7, by omega⟩) : ℚ)) + bitOperations := c.bitOperations + (c.registers ⟨6, by omega⟩).length + + (c.registers ⟨7, by omega⟩).length + 1 } + +def execution {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) : ℕ → MachineConfig k s + | 0 => c + | t + 1 => machineStep P O (bits t) (execution P O c bits t) + +def finiteBits {B : ℕ} (bits : Fin B → Bool) (t : ℕ) : Bool := + if h : t < B then bits ⟨t, h⟩ else false + +def relativeAccuracy (ε : ℚ) (Z : ℕ) (z : ℚ) : Prop := + (1-ε)*(Z:ℚ)≤z ∧ z≤(1+ε)*(Z:ℚ) + +def resourceBound (C d n r : ℕ) (ε δ : ℚ) : ℕ := + C * (1 + n + inputLength n r ε δ + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊) ^ d + +def MainTheorem : Prop := + ∃ (k s : ℕ) (P : Program k s) (C d : ℕ), 0 < C ∧ + ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (ε δ : ℚ), + M₁.E = Set.univ → M₂.E = Set.univ → + M₁.eRank = (r : ℕ∞) → M₂.eRank = (r : ℕ∞) → + ExactOracles M₁ M₂ O → 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let B := resourceBound C d n r ε δ + let Z := commonBaseCount M₁ M₂ + (∀ bits : ℕ → Bool, + let out := execution P O (initialConfig k s n r ε δ) bits B + out.output.isSome ∧ out.oracleCalls ≤ B ∧ out.bitOperations ≤ B ∧ + ∀ z, out.output = some z → 0 ≤ z ∧ (Z = 0 → z = 0)) ∧ + (1 - δ) * (2 : ℚ) ^ B ≤ + (Nat.card {bits : Fin B → Bool // + ∃ z, (execution P O (initialConfig k s n r ε δ) (finiteBits bits) B).output + = some z ∧ relativeAccuracy ε Z z} : ℚ) + +end CommonBasesFPRAS + +theorem common_bases_fpras : CommonBasesFPRAS.MainTheorem := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CommonBasesFPRAS.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.common_bases_fpras` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/common-bases-fpras/solution/closure.txt b/tasks/common-bases-fpras/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9af53d70efd6fd4054d933f54ceb650d8f68ab7c --- /dev/null +++ b/tasks/common-bases-fpras/solution/closure.txt @@ -0,0 +1 @@ +OAI.Combinatorics.MatroidCounting.CommonBases diff --git a/tasks/common-bases-fpras/solution/reference.py b/tasks/common-bases-fpras/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/common-bases-fpras/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/common-bases-fpras/solution/solve.sh b/tasks/common-bases-fpras/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..74513594409d6e4907bbf426a41c9fb4a98c5822 --- /dev/null +++ b/tasks/common-bases-fpras/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CommonBasesFPRAS, i.e. module OAI.Combinatorics.MatroidCounting.CommonBases and the +# 1 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatroidCounting.CommonBases /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CommonBasesFPRAS" diff --git a/tasks/common-bases-fpras/task.toml b/tasks/common-bases-fpras/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2a096aa6fe0f3b8ab97c2bcdba5f68af1072a580 --- /dev/null +++ b/tasks/common-bases-fpras/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/common-bases-fpras" +version = "1.0.0" +description = "Prove CommonBasesFPRAS (openai/math family 114: Approximate counting of common integer polymatroid bases) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CommonBasesFPRAS.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CommonBasesFPRAS" +family = "114" +family_title = "Approximate counting of common integer polymatroid bases" +subject = "Theoretical computer science" +theorems = ["OAI.common_bases_fpras"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatroidCounting.CommonBases" +reference_modules = 1 +reference_lean_bytes = 1336009 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 950 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12902 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/common-bases-fpras/tests/Challenge.lean b/tasks/common-bases-fpras/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b03428bbdc26dbe79be12218920c3313a5df5695 --- /dev/null +++ b/tasks/common-bases-fpras/tests/Challenge.lean @@ -0,0 +1,131 @@ +import Mathlib + +namespace OAI + +namespace CommonBasesFPRAS + +abbrev IndependenceOracle (n : ℕ) := Bool → (Fin n → Bool) → Bool + +def ExactOracles {n : ℕ} (M₁ M₂ : Matroid (Fin n)) + (O : IndependenceOracle n) : Prop := + ∀ (which : Bool) (A : Fin n → Bool), + O which A = true ↔ (if which then M₂ else M₁).Indep {i | A i = true} + +noncomputable def commonBaseCount {n : ℕ} (M₁ M₂ : Matroid (Fin n)) : ℕ := + Nat.card {A : Finset (Fin n) // M₁.IsBase (A : Set (Fin n)) ∧ + M₂.IsBase (A : Set (Fin n))} + +inductive Instruction (k s : ℕ) where + | push (register : Fin (k + 8)) (bit : Bool) (next : Fin (s + 1)) + | pop (register : Fin (k + 8)) (empty zero one : Fin (s + 1)) + | coin (zero one : Fin (s + 1)) + | query (which : Bool) (register : Fin (k + 8)) (no yes : Fin (s + 1)) + | halt + +def Program (k s : ℕ) := Fin (s + 1) → Instruction k s + +def binaryValue : List Bool → ℕ + | [] => 0 + | b :: l => (if b then 1 else 0) + 2 * binaryValue l + +structure MachineConfig (k s : ℕ) where + registers : Fin (k + 8) → List Bool + control : Fin (s + 1) + output : Option ℚ := none + oracleCalls : ℕ := 0 + bitOperations : ℕ := 0 + +def inputLength (n r : ℕ) (ε δ : ℚ) : ℕ := + 6 + n.bits.length + r.bits.length + ε.num.natAbs.bits.length + ε.den.bits.length + + δ.num.natAbs.bits.length + δ.den.bits.length + +def initialConfig (k s n r : ℕ) (ε δ : ℚ) : MachineConfig k s where + registers := fun i => match i.val with + | 0 => n.bits + | 1 => r.bits + | 2 => ε.num.natAbs.bits + | 3 => ε.den.bits + | 4 => δ.num.natAbs.bits + | 5 => δ.den.bits + | _ => [] + control := 0 + +def machineStep {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (randomBit : Bool) (c : MachineConfig k s) : MachineConfig k s := + if c.output.isSome then c else + match P c.control with + | .push i b next => + { c with + registers := Function.update c.registers i (b :: c.registers i) + control := next + bitOperations := c.bitOperations + 1 } + | .pop i empty zero one => + match c.registers i with + | [] => { c with + control := empty + bitOperations := c.bitOperations + 1 } + | b :: l => + { c with + registers := Function.update c.registers i l + control := if b then one else zero + bitOperations := c.bitOperations + 1 } + | .coin zero one => + { c with + control := if randomBit then one else zero + bitOperations := c.bitOperations + 1 } + | .query which i no yes => + if (c.registers i).length = n then + { c with + control := if O which (fun j => (c.registers i)[j.val]?.getD false) + then yes else no + oracleCalls := c.oracleCalls + 1 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + else + { c with + output := some 0 + bitOperations := c.bitOperations + (c.registers i).length + n + 1 } + | .halt => + { c with + output := some ((binaryValue (c.registers ⟨6, by omega⟩) : ℚ) / + (binaryValue (c.registers ⟨7, by omega⟩) : ℚ)) + bitOperations := c.bitOperations + (c.registers ⟨6, by omega⟩).length + + (c.registers ⟨7, by omega⟩).length + 1 } + +def execution {k s n : ℕ} (P : Program k s) (O : IndependenceOracle n) + (c : MachineConfig k s) (bits : ℕ → Bool) : ℕ → MachineConfig k s + | 0 => c + | t + 1 => machineStep P O (bits t) (execution P O c bits t) + +def finiteBits {B : ℕ} (bits : Fin B → Bool) (t : ℕ) : Bool := + if h : t < B then bits ⟨t, h⟩ else false + +def relativeAccuracy (ε : ℚ) (Z : ℕ) (z : ℚ) : Prop := + (1-ε)*(Z:ℚ)≤z ∧ z≤(1+ε)*(Z:ℚ) + +def resourceBound (C d n r : ℕ) (ε δ : ℚ) : ℕ := + C * (1 + n + inputLength n r ε δ + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊) ^ d + +def MainTheorem : Prop := + ∃ (k s : ℕ) (P : Program k s) (C d : ℕ), 0 < C ∧ + ∀ (n r : ℕ) (M₁ M₂ : Matroid (Fin n)) (O : IndependenceOracle n) + (ε δ : ℚ), + M₁.E = Set.univ → M₂.E = Set.univ → + M₁.eRank = (r : ℕ∞) → M₂.eRank = (r : ℕ∞) → + ExactOracles M₁ M₂ O → 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let B := resourceBound C d n r ε δ + let Z := commonBaseCount M₁ M₂ + (∀ bits : ℕ → Bool, + let out := execution P O (initialConfig k s n r ε δ) bits B + out.output.isSome ∧ out.oracleCalls ≤ B ∧ out.bitOperations ≤ B ∧ + ∀ z, out.output = some z → 0 ≤ z ∧ (Z = 0 → z = 0)) ∧ + (1 - δ) * (2 : ℚ) ^ B ≤ + (Nat.card {bits : Fin B → Bool // + ∃ z, (execution P O (initialConfig k s n r ε δ) (finiteBits bits) B).output + = some z ∧ relativeAccuracy ε Z z} : ℚ) + +end CommonBasesFPRAS + +theorem common_bases_fpras : CommonBasesFPRAS.MainTheorem := by + sorry + +end OAI diff --git a/tasks/common-bases-fpras/tests/grade.py b/tasks/common-bases-fpras/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/common-bases-fpras/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/common-bases-fpras/tests/task.json b/tasks/common-bases-fpras/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d1788222f2775cbcf5de0277f0d5db015b10e078 --- /dev/null +++ b/tasks/common-bases-fpras/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CommonBasesFPRAS", + "comparator": { + "theorem_names": [ + "OAI.common_bases_fpras" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12002 +} \ No newline at end of file diff --git a/tasks/common-bases-fpras/tests/test.sh b/tasks/common-bases-fpras/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/common-bases-fpras/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/commuting-derivations/environment/Dockerfile b/tasks/commuting-derivations/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/commuting-derivations/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/commuting-derivations/environment/fetch_mathlib.sh b/tasks/commuting-derivations/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/commuting-derivations/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/commuting-derivations/environment/lake-manifest.json b/tasks/commuting-derivations/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/commuting-derivations/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/commuting-derivations/environment/lakefile.lean b/tasks/commuting-derivations/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/commuting-derivations/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/commuting-derivations/environment/lean_setup.sh b/tasks/commuting-derivations/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/commuting-derivations/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/commuting-derivations/environment/pack_submission.py b/tasks/commuting-derivations/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/commuting-derivations/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/commuting-derivations/instruction.md b/tasks/commuting-derivations/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93e449d652a6a1071adc3c256961f8c172d6277b --- /dev/null +++ b/tasks/commuting-derivations/instruction.md @@ -0,0 +1,126 @@ +# openai/math challenge `CommutingDerivations` (family 049) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 049 of the release, *A stable-coordinate counterexample in four variables* +(Algebraic and complex geometry). The family as a whole: Constructs a polynomial in four complex variables that is not a coordinate but becomes one after adjoining a single variable, disproving the Stable Coordinate conjecture in four variables. Every fiber is affine three-space, yet none of its embeddings is rectifiable, also disproving the Abhyankar–Sathaye conjecture even when all fibers are affine spaces. + +The challenge is `CommutingDerivations`, also at `/opt/openai-math/challenges/CommutingDerivations.lean`: + +```lean +import Mathlib.Algebra.MvPolynomial.PDeriv +import Mathlib.Basic.Complex.Basic +import Mathlib.LinearAlgebra.LinearIndependent.Defs +import Mathlib.Logic.Equiv.Fin.Basic +import Mathlib.Logic.Function.Iterate +import Mathlib.RingTheory.Adjoin.Basic + +namespace OAI + +noncomputable section + +namespace AbhyankarSathaye + +def S {B : Type*} [CommRing B] (h u v w : B) : B := + 2*u^3*v + 3*u^4*w + h*(v^2 - 3*u^2*w^2) + h^2*w^3 + +def P {B : Type*} [CommRing B] (x y s : B) : B := + -2*s^2*x + 3*s*y^2 - 3*s^3*y + +abbrev R := MvPolynomial (Fin 4) ℂ + +def h : R := MvPolynomial.X 0 +def u : R := MvPolynomial.X 1 +def v : R := MvPolynomial.X 2 +def w : R := MvPolynomial.X 3 +def x : R := u^3 + h*v +def y : R := -u^2 + h*w +def s : R := S h u v w +def p : R := P x y s +def F : R := h - p - 1 + +def fourInclusion {n : ℕ} (hn : 4 ≤ n) (i : Fin 4) : Fin n := + ⟨i.val, lt_of_lt_of_le i.isLt hn⟩ + +def extendedF {n : ℕ} (hn : 4 ≤ n) : MvPolynomial (Fin n) ℂ := + MvPolynomial.rename (fourInclusion hn) F + +def blocksToAmbient {n : ℕ} (hn : 4 ≤ n) : Fin (n-4) ⊕ Fin 4 ≃ Fin n := + (Equiv.sumComm _ _).trans (finSumFinEquiv.trans (finCongr (by omega))) + +def blocksToOutput {n : ℕ} (hn : 4 ≤ n) : Fin (n-4) ⊕ Fin 3 ≃ Fin (n-1) := + (Equiv.sumComm _ _).trans (finSumFinEquiv.trans (finCongr (by omega))) + +namespace CommutingDerivations + +variable {K A B : Type*} [CommRing K] [CommRing A] [CommRing B] + [Algebra K A] [Algebra K B] + +def LocallyNilpotent (D : Derivation K A A) : Prop := + ∀ a : A, ∃ n : ℕ, (D : A → A)^[n] a = 0 + +open MvPolynomial + +theorem commuting_derivations_with_ordinary_extras (n : ℕ) (hn : 4 ≤ n) : + ∃ d : Fin (n-1) → Derivation ℂ (MvPolynomial (Fin n) ℂ) (MvPolynomial (Fin n) ℂ), + (∀ i, d i (extendedF hn + 1) = 0) ∧ + (∀ i j p, d i (d j p) = d j (d i p)) ∧ + (∀ i, LocallyNilpotent (d i)) ∧ + LinearIndependent (MvPolynomial (Fin n) ℂ) d ∧ + (∀ p, (∀ i, d i p = 0) ↔ + p ∈ Algebra.adjoin ℂ ({extendedF hn} : Set (MvPolynomial (Fin n) ℂ))) ∧ + (∀ g, (∀ i, d i g = 0) → + ¬ ∃ (e : MvPolynomial (Fin n) ℂ ≃ₐ[ℂ] MvPolynomial (Fin n) ℂ) (j : Fin n), + e (X j) = g) ∧ + (∀ i : Fin (n-4), d (blocksToOutput hn (Sum.inl i)) = + pderiv (blocksToAmbient hn (Sum.inl i))) := by + sorry + +end CommutingDerivations + +end AbhyankarSathaye + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CommutingDerivations.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AbhyankarSathaye.CommutingDerivations.commuting_derivations_with_ordinary_extras` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/commuting-derivations/solution/closure.txt b/tasks/commuting-derivations/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5db452e3476d3ef2939ef5a32f56c964b5f9ce4a --- /dev/null +++ b/tasks/commuting-derivations/solution/closure.txt @@ -0,0 +1,32 @@ +OAI.AlgebraicGeometry.AbhyankarSathaye.CriticalPoint +OAI.AlgebraicGeometry.AbhyankarSathaye.Fiber +OAI.AlgebraicGeometry.AbhyankarSathaye.Identities +OAI.AlgebraicGeometry.AbhyankarSathaye.Lifting +OAI.AlgebraicGeometry.AbhyankarSathaye.LiftingIdentities +OAI.AlgebraicGeometry.AbhyankarSathaye.NonCoordinate +OAI.AlgebraicGeometry.AbhyankarSathaye.Plane +OAI.AlgebraicGeometry.AbhyankarSathaye.Presentation +OAI.AlgebraicGeometry.AbhyankarSathaye.Quotient +OAI.AlgebraicGeometry.AbhyankarSathaye.Reconstruction +OAI.AlgebraicGeometry.AbhyankarSathaye.Stabilization +OAI.AlgebraicGeometry.CommutingDerivations.CoefficientInstances +OAI.AlgebraicGeometry.CommutingDerivations.ConcreteKernelIntersection +OAI.AlgebraicGeometry.CommutingDerivations.CoordinatePartials +OAI.AlgebraicGeometry.CommutingDerivations.DenominatorDescent +OAI.AlgebraicGeometry.CommutingDerivations.DerivationOperations +OAI.AlgebraicGeometry.CommutingDerivations.DescentFamily +OAI.AlgebraicGeometry.CommutingDerivations.ExtendedExtraPartials +OAI.AlgebraicGeometry.CommutingDerivations.ExtendedKernelIntersection +OAI.AlgebraicGeometry.CommutingDerivations.ExtendedLocalization +OAI.AlgebraicGeometry.CommutingDerivations.ExtendedParameterRetraction +OAI.AlgebraicGeometry.CommutingDerivations.FamilyFromLocalization +OAI.AlgebraicGeometry.CommutingDerivations.KernelObstruction +OAI.AlgebraicGeometry.CommutingDerivations.LocalizationEquivalence +OAI.AlgebraicGeometry.CommutingDerivations.LocalizationSetup +OAI.AlgebraicGeometry.CommutingDerivations.LocalizedPartials +OAI.AlgebraicGeometry.CommutingDerivations.Main +OAI.AlgebraicGeometry.CommutingDerivations.MixedDescentFamily +OAI.AlgebraicGeometry.CommutingDerivations.OrdinaryExtraMain +OAI.AlgebraicGeometry.CommutingDerivations.ParameterBezout +OAI.AlgebraicGeometry.CommutingDerivations.ParameterBridge +OAI.AlgebraicGeometry.CommutingDerivations.ParameterRetraction diff --git a/tasks/commuting-derivations/solution/reference.py b/tasks/commuting-derivations/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/commuting-derivations/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/commuting-derivations/solution/solve.sh b/tasks/commuting-derivations/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e75a32029a375d021031267310e129d64018282d --- /dev/null +++ b/tasks/commuting-derivations/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CommutingDerivations, i.e. module OAI.AlgebraicGeometry.CommutingDerivations.OrdinaryExtraMain and the +# 32 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.AlgebraicGeometry.CommutingDerivations.OrdinaryExtraMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CommutingDerivations" diff --git a/tasks/commuting-derivations/task.toml b/tasks/commuting-derivations/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e683c376e86cc78f9dd919f6ebfbc65c1485d1a9 --- /dev/null +++ b/tasks/commuting-derivations/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/commuting-derivations" +version = "1.0.0" +description = "Prove CommutingDerivations (openai/math family 049: A stable-coordinate counterexample in four variables) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CommutingDerivations.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CommutingDerivations" +family = "049" +family_title = "A stable-coordinate counterexample in four variables" +subject = "Algebraic and complex geometry" +theorems = ["OAI.AbhyankarSathaye.CommutingDerivations.commuting_derivations_with_ordinary_extras"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.AlgebraicGeometry.CommutingDerivations.OrdinaryExtraMain" +reference_modules = 32 +reference_lean_bytes = 135211 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 426 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11821 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/commuting-derivations/tests/Challenge.lean b/tasks/commuting-derivations/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b5d5e957bf83ac776ebcce472efc4991e3b37f98 --- /dev/null +++ b/tasks/commuting-derivations/tests/Challenge.lean @@ -0,0 +1,75 @@ +import Mathlib.Algebra.MvPolynomial.PDeriv +import Mathlib.Basic.Complex.Basic +import Mathlib.LinearAlgebra.LinearIndependent.Defs +import Mathlib.Logic.Equiv.Fin.Basic +import Mathlib.Logic.Function.Iterate +import Mathlib.RingTheory.Adjoin.Basic + +namespace OAI + +noncomputable section + +namespace AbhyankarSathaye + +def S {B : Type*} [CommRing B] (h u v w : B) : B := + 2*u^3*v + 3*u^4*w + h*(v^2 - 3*u^2*w^2) + h^2*w^3 + +def P {B : Type*} [CommRing B] (x y s : B) : B := + -2*s^2*x + 3*s*y^2 - 3*s^3*y + +abbrev R := MvPolynomial (Fin 4) ℂ + +def h : R := MvPolynomial.X 0 +def u : R := MvPolynomial.X 1 +def v : R := MvPolynomial.X 2 +def w : R := MvPolynomial.X 3 +def x : R := u^3 + h*v +def y : R := -u^2 + h*w +def s : R := S h u v w +def p : R := P x y s +def F : R := h - p - 1 + +def fourInclusion {n : ℕ} (hn : 4 ≤ n) (i : Fin 4) : Fin n := + ⟨i.val, lt_of_lt_of_le i.isLt hn⟩ + +def extendedF {n : ℕ} (hn : 4 ≤ n) : MvPolynomial (Fin n) ℂ := + MvPolynomial.rename (fourInclusion hn) F + +def blocksToAmbient {n : ℕ} (hn : 4 ≤ n) : Fin (n-4) ⊕ Fin 4 ≃ Fin n := + (Equiv.sumComm _ _).trans (finSumFinEquiv.trans (finCongr (by omega))) + +def blocksToOutput {n : ℕ} (hn : 4 ≤ n) : Fin (n-4) ⊕ Fin 3 ≃ Fin (n-1) := + (Equiv.sumComm _ _).trans (finSumFinEquiv.trans (finCongr (by omega))) + +namespace CommutingDerivations + +variable {K A B : Type*} [CommRing K] [CommRing A] [CommRing B] + [Algebra K A] [Algebra K B] + +def LocallyNilpotent (D : Derivation K A A) : Prop := + ∀ a : A, ∃ n : ℕ, (D : A → A)^[n] a = 0 + +open MvPolynomial + +theorem commuting_derivations_with_ordinary_extras (n : ℕ) (hn : 4 ≤ n) : + ∃ d : Fin (n-1) → Derivation ℂ (MvPolynomial (Fin n) ℂ) (MvPolynomial (Fin n) ℂ), + (∀ i, d i (extendedF hn + 1) = 0) ∧ + (∀ i j p, d i (d j p) = d j (d i p)) ∧ + (∀ i, LocallyNilpotent (d i)) ∧ + LinearIndependent (MvPolynomial (Fin n) ℂ) d ∧ + (∀ p, (∀ i, d i p = 0) ↔ + p ∈ Algebra.adjoin ℂ ({extendedF hn} : Set (MvPolynomial (Fin n) ℂ))) ∧ + (∀ g, (∀ i, d i g = 0) → + ¬ ∃ (e : MvPolynomial (Fin n) ℂ ≃ₐ[ℂ] MvPolynomial (Fin n) ℂ) (j : Fin n), + e (X j) = g) ∧ + (∀ i : Fin (n-4), d (blocksToOutput hn (Sum.inl i)) = + pderiv (blocksToAmbient hn (Sum.inl i))) := by + sorry + +end CommutingDerivations + +end AbhyankarSathaye + +end + +end OAI diff --git a/tasks/commuting-derivations/tests/grade.py b/tasks/commuting-derivations/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/commuting-derivations/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/commuting-derivations/tests/task.json b/tasks/commuting-derivations/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4141b36f13ed61f4ea811ec1214f1962233337ee --- /dev/null +++ b/tasks/commuting-derivations/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CommutingDerivations", + "comparator": { + "theorem_names": [ + "OAI.AbhyankarSathaye.CommutingDerivations.commuting_derivations_with_ordinary_extras" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10921 +} \ No newline at end of file diff --git a/tasks/commuting-derivations/tests/test.sh b/tasks/commuting-derivations/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/commuting-derivations/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/compact-banach/environment/Dockerfile b/tasks/compact-banach/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/compact-banach/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/compact-banach/environment/fetch_mathlib.sh b/tasks/compact-banach/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/compact-banach/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/compact-banach/environment/lake-manifest.json b/tasks/compact-banach/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/compact-banach/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/compact-banach/environment/lakefile.lean b/tasks/compact-banach/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/compact-banach/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/compact-banach/environment/lean_setup.sh b/tasks/compact-banach/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/compact-banach/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/compact-banach/environment/pack_submission.py b/tasks/compact-banach/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/compact-banach/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/compact-banach/instruction.md b/tasks/compact-banach/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..662a5cfff4cc182a433a840e237667d136753a11 --- /dev/null +++ b/tasks/compact-banach/instruction.md @@ -0,0 +1,85 @@ +# openai/math challenge `CompactBanach` (family 098) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 098 of the release, *A negative answer to the Lang–Plaut problem* +(Convex and metric geometry). The family as a whole: Every infinite-dimensional real Banach space contains a compact doubling set that admits no bi-Lipschitz embedding into any finite-dimensional normed space. The doubling constant is universal. This answers the Lang–Plaut problem negatively, even for compact subsets of Hilbert space. + +The challenge is `CompactBanach`, also at `/opt/openai-math/challenges/CompactBanach.lean`: + +```lean +import Mathlib + +namespace OAI + + + + + + +universe u v +namespace CompactBanach + +def DoublingAtMost {B : Type*} [MetricSpace B] (K : Set B) (bound : ℕ) : Prop := + ∀ x : K, ∀ r : ℝ, 0 < r → + ∃ centers : Finset K, centers.card ≤ bound ∧ + ∀ y : K, dist y x < r → ∃ c ∈ centers, dist y c < r / ((2 : ℕ) : ℝ) + +def AdmitsBiLipschitzEmbedding {B : Type*} [MetricSpace B] (K : Set B) + (E : Type*) [MetricSpace E] : Prop := + ∃ f : K → E, ∃ a : ℝ, 0 < a ∧ ∃ D : ℝ, 1 ≤ D ∧ + ∀ x y : K, a * dist x y ≤ dist (f x) (f y) ∧ + dist (f x) (f y) ≤ D * a * dist x y + + +theorem main : ∃ Λ : ℕ, ∀ (B : Type u) [NormedAddCommGroup B] [NormedSpace ℝ B] + [CompleteSpace B], ¬ FiniteDimensional ℝ B → + ∃ K : Set B, IsCompact K ∧ DoublingAtMost K Λ ∧ + ∀ (E : Type v) [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E], ¬ AdmitsBiLipschitzEmbedding K E := by + sorry + +end CompactBanach + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CompactBanach.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CompactBanach.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/compact-banach/solution/closure.txt b/tasks/compact-banach/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..01dd3987797b59ffe80f86cd32974ec2a8a1f16d --- /dev/null +++ b/tasks/compact-banach/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.Geometry.DoublingHilbert.Auerbach +OAI.Geometry.DoublingHilbert.ClusterCover +OAI.Geometry.DoublingHilbert.ClusterPlacement +OAI.Geometry.DoublingHilbert.ClusterScales +OAI.Geometry.DoublingHilbert.CompactBanach +OAI.Geometry.DoublingHilbert.CompactModel +OAI.Geometry.DoublingHilbert.CompactUnion +OAI.Geometry.DoublingHilbert.Construction +OAI.Geometry.DoublingHilbert.CoordinateMap +OAI.Geometry.DoublingHilbert.CoordinateSupport +OAI.Geometry.DoublingHilbert.CoverTransfer +OAI.Geometry.DoublingHilbert.Crossings +OAI.Geometry.DoublingHilbert.Derivatives +OAI.Geometry.DoublingHilbert.Doubling +OAI.Geometry.DoublingHilbert.Energy +OAI.Geometry.DoublingHilbert.Extremal +OAI.Geometry.DoublingHilbert.FiniteCompactness +OAI.Geometry.DoublingHilbert.FinitePlacement +OAI.Geometry.DoublingHilbert.FiniteTargets +OAI.Geometry.DoublingHilbert.FiniteWitness +OAI.Geometry.DoublingHilbert.Grids +OAI.Geometry.DoublingHilbert.Integration +OAI.Geometry.DoublingHilbert.IntrinsicCovers +OAI.Geometry.DoublingHilbert.Main +OAI.Geometry.DoublingHilbert.Model +OAI.Geometry.DoublingHilbert.Rectangles +OAI.Geometry.DoublingHilbert.SelectedSheets +OAI.Geometry.DoublingHilbert.SparseCoordinates diff --git a/tasks/compact-banach/solution/reference.py b/tasks/compact-banach/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/compact-banach/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/compact-banach/solution/solve.sh b/tasks/compact-banach/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..77ceb72e2a2ed57bdff872075fcc45f492d3b238 --- /dev/null +++ b/tasks/compact-banach/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CompactBanach, i.e. module OAI.Geometry.DoublingHilbert.CompactBanach and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.DoublingHilbert.CompactBanach /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CompactBanach" diff --git a/tasks/compact-banach/task.toml b/tasks/compact-banach/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fbe539546cc70e1c33def98d94c7287ae0a0d53d --- /dev/null +++ b/tasks/compact-banach/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/compact-banach" +version = "1.0.0" +description = "Prove CompactBanach (openai/math family 098: A negative answer to the Lang–Plaut problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CompactBanach.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CompactBanach" +family = "098" +family_title = "A negative answer to the Lang–Plaut problem" +subject = "Convex and metric geometry" +theorems = ["OAI.CompactBanach.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.DoublingHilbert.CompactBanach" +reference_modules = 28 +reference_lean_bytes = 207061 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1439 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11886 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/compact-banach/tests/Challenge.lean b/tasks/compact-banach/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e97151f96fd0db36523025143ce7ae4f54b9908d --- /dev/null +++ b/tasks/compact-banach/tests/Challenge.lean @@ -0,0 +1,34 @@ +import Mathlib + +namespace OAI + + + + + + +universe u v +namespace CompactBanach + +def DoublingAtMost {B : Type*} [MetricSpace B] (K : Set B) (bound : ℕ) : Prop := + ∀ x : K, ∀ r : ℝ, 0 < r → + ∃ centers : Finset K, centers.card ≤ bound ∧ + ∀ y : K, dist y x < r → ∃ c ∈ centers, dist y c < r / ((2 : ℕ) : ℝ) + +def AdmitsBiLipschitzEmbedding {B : Type*} [MetricSpace B] (K : Set B) + (E : Type*) [MetricSpace E] : Prop := + ∃ f : K → E, ∃ a : ℝ, 0 < a ∧ ∃ D : ℝ, 1 ≤ D ∧ + ∀ x y : K, a * dist x y ≤ dist (f x) (f y) ∧ + dist (f x) (f y) ≤ D * a * dist x y + + +theorem main : ∃ Λ : ℕ, ∀ (B : Type u) [NormedAddCommGroup B] [NormedSpace ℝ B] + [CompleteSpace B], ¬ FiniteDimensional ℝ B → + ∃ K : Set B, IsCompact K ∧ DoublingAtMost K Λ ∧ + ∀ (E : Type v) [NormedAddCommGroup E] [NormedSpace ℝ E] + [FiniteDimensional ℝ E], ¬ AdmitsBiLipschitzEmbedding K E := by + sorry + +end CompactBanach + +end OAI diff --git a/tasks/compact-banach/tests/grade.py b/tasks/compact-banach/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/compact-banach/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/compact-banach/tests/task.json b/tasks/compact-banach/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5d7f8fb0129b48aa8feb5941a15338f009e4bde6 --- /dev/null +++ b/tasks/compact-banach/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CompactBanach", + "comparator": { + "theorem_names": [ + "OAI.CompactBanach.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 10986 +} \ No newline at end of file diff --git a/tasks/compact-banach/tests/test.sh b/tasks/compact-banach/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/compact-banach/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/complete-crossing/environment/Dockerfile b/tasks/complete-crossing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/complete-crossing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/complete-crossing/environment/fetch_mathlib.sh b/tasks/complete-crossing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/complete-crossing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/complete-crossing/environment/lake-manifest.json b/tasks/complete-crossing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/complete-crossing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/complete-crossing/environment/lakefile.lean b/tasks/complete-crossing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/complete-crossing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/complete-crossing/environment/lean_setup.sh b/tasks/complete-crossing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/complete-crossing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/complete-crossing/environment/pack_submission.py b/tasks/complete-crossing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/complete-crossing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/complete-crossing/instruction.md b/tasks/complete-crossing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a9455e8a8053b7cfcc7e89801834d832d30b529d --- /dev/null +++ b/tasks/complete-crossing/instruction.md @@ -0,0 +1,140 @@ +# openai/math challenge `CompleteCrossing` (family 165) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 165 of the release, *Exact crossing numbers of complete and complete bipartite graphs* +(Combinatorics). The family as a whole: Resolves the Harary–Hill conjecture and Turan's brickyard problem in the Zarankiewicz formulation, determining the crossing numbers of every complete and complete bipartite graph. The result proves the optimality of the classical drawings among all plane drawings with continuous edge arcs. + +The challenge is `CompleteCrossing`, also at `/opt/openai-math/challenges/CompleteCrossing.lean`: + +```lean +import Mathlib.Data.Set.Card +import Mathlib.Order.Lattice.Nat +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Topology.OpenPartialHomeomorph.Defs +import Mathlib.Topology.Path + +namespace OAI + +noncomputable section + +namespace Paper170 + +abbrev Plane := ℝ × ℝ + +structure Graph (Vertex Edge : Type) where + src : Edge → Vertex + dst : Edge → Vertex + loopless : ∀ edge, src edge ≠ dst edge + simple : ∀ edge other, ((src edge = src other ∧ dst edge = dst other) ∨ + (src edge = dst other ∧ dst edge = src other)) → edge = other + +abbrev CompleteEdge (order : ℕ) := {pair : Fin order × Fin order // pair.1 < pair.2} + +def completeGraph (order : ℕ) : Graph (Fin order) (CompleteEdge order) where + src edge := edge.val.1 + dst edge := edge.val.2 + loopless edge := ne_of_lt edge.property + simple edge other same := by + rcases same with same | reversed + · exact Subtype.ext (Prod.ext same.1 same.2) + · have increasing := edge.property + have other_increasing := other.property + rw [reversed.1, reversed.2] at increasing + exact (lt_asymm increasing other_increasing).elim + +variable {Vertex Edge : Type} + +structure ContinuousDrawing (graph : Graph Vertex Edge) where + vertex : Vertex → Plane + vertex_injective : Function.Injective vertex + edge : ∀ edge : Edge, Path (vertex (graph.src edge)) (vertex (graph.dst edge)) + edge_injective : ∀ selected, Function.Injective (edge selected) + interior_avoids_vertices : ∀ selected time, time ∈ Set.Ioo (0 : unitInterval) 1 → + ∀ other, edge selected time ≠ vertex other + +variable {graph : Graph Vertex Edge} + +def edgeInterior (drawing : ContinuousDrawing graph) (edge : Edge) : Set Plane := + drawing.edge edge '' Set.Ioo (0 : unitInterval) 1 + +structure ProperCrossing (first second : Set Plane) (point : Plane) : Prop where + chart_exists : ∃ chart : OpenPartialHomeomorph Plane Plane, + point ∈ chart.source ∧ chart point = (0, 0) ∧ + chart '' (chart.source ∩ first) = chart.target ∩ {image | image.2 = 0} ∧ + chart '' (chart.source ∩ second) = chart.target ∩ {image | image.1 = 0} + +def crossingPoints (drawing : ContinuousDrawing graph) : Set Plane := + {point | ∃ edge other : Edge, edge ≠ other ∧ + point ∈ edgeInterior drawing edge ∧ point ∈ edgeInterior drawing other} + +structure AdmissibleDrawing (graph : Graph Vertex Edge) extends ContinuousDrawing graph where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + crossings_proper : ∀ edge other, edge ≠ other → ∀ point, + point ∈ edgeInterior toContinuousDrawing edge → + point ∈ edgeInterior toContinuousDrawing other → + ProperCrossing (edgeInterior toContinuousDrawing edge) + (edgeInterior toContinuousDrawing other) point + no_triples : ∀ first second third, first ≠ second → first ≠ third → second ≠ third → + edgeInterior toContinuousDrawing first ∩ edgeInterior toContinuousDrawing second ∩ + edgeInterior toContinuousDrawing third = ∅ + +def crossingCount (drawing : AdmissibleDrawing graph) : ℕ := + drawing.crossings_finite.toFinset.card + +def ordinaryCrossingNumber (graph : Graph Vertex Edge) : ℕ := + sInf (Set.range (@crossingCount Vertex Edge graph)) + +def hill (order : ℕ) : ℕ := + (order / 2 * ((order - 1) / 2) * ((order - 2) / 2) * ((order - 3) / 2)) / 4 + +theorem complete_graph_crossing_number (order : ℕ) (at_least_three : 3 ≤ order) : + ordinaryCrossingNumber (completeGraph order) = hill order := by + sorry + +end Paper170 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CompleteCrossing.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Paper170.complete_graph_crossing_number` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/complete-crossing/solution/closure.txt b/tasks/complete-crossing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..54833bf75e8ff7a8d9b1d79063720140f92ea76e --- /dev/null +++ b/tasks/complete-crossing/solution/closure.txt @@ -0,0 +1,300 @@ +OAI.Combinatorics.CompleteCrossing.AdjacentSurgery +OAI.Combinatorics.CompleteCrossing.AlgebraDefs +OAI.Combinatorics.CompleteCrossing.Angles +OAI.Combinatorics.CompleteCrossing.Assembly +OAI.Combinatorics.CompleteCrossing.CircleArcs +OAI.Combinatorics.CompleteCrossing.CirclePlacement +OAI.Combinatorics.CompleteCrossing.Counting +OAI.Combinatorics.CompleteCrossing.CrossingCuts +OAI.Combinatorics.CompleteCrossing.CycleIdentity +OAI.Combinatorics.CompleteCrossing.CycleIntersections +OAI.Combinatorics.CompleteCrossing.CycleSpace +OAI.Combinatorics.CompleteCrossing.DartPaths +OAI.Combinatorics.CompleteCrossing.Deletion +OAI.Combinatorics.CompleteCrossing.DiskChords +OAI.Combinatorics.CompleteCrossing.DiskFilling +OAI.Combinatorics.CompleteCrossing.Drawing +OAI.Combinatorics.CompleteCrossing.DrawingMarks +OAI.Combinatorics.CompleteCrossing.Hill +OAI.Combinatorics.CompleteCrossing.Interpolation +OAI.Combinatorics.CompleteCrossing.Isotropy +OAI.Combinatorics.CompleteCrossing.LocalGeometry +OAI.Combinatorics.CompleteCrossing.LowerBound +OAI.Combinatorics.CompleteCrossing.Main +OAI.Combinatorics.CompleteCrossing.Normalization +OAI.Combinatorics.CompleteCrossing.OrderPairing +OAI.Combinatorics.CompleteCrossing.PairSums +OAI.Combinatorics.CompleteCrossing.Plane +OAI.Combinatorics.CompleteCrossing.Polygonalization +OAI.Combinatorics.CompleteCrossing.Polynomials +OAI.Combinatorics.CompleteCrossing.Ports +OAI.Combinatorics.CompleteCrossing.RadialTracks +OAI.Combinatorics.CompleteCrossing.Reconnection +OAI.Combinatorics.CompleteCrossing.Refinement +OAI.Combinatorics.CompleteCrossing.Residues +OAI.Combinatorics.CompleteCrossing.SpokePorts +OAI.Combinatorics.CompleteCrossing.Subdivision +OAI.Combinatorics.CompleteCrossing.Support +OAI.Combinatorics.CompleteCrossing.SurgeryIntersections +OAI.Combinatorics.CompleteCrossing.Tensor +OAI.Combinatorics.CompleteCrossing.Tracks +OAI.Combinatorics.CompleteCrossing.Triangle +OAI.Combinatorics.CompleteCrossing.TriangleFactors +OAI.Combinatorics.CompleteCrossing.Truncation +OAI.Combinatorics.CompleteCrossing.TwoPage +OAI.Combinatorics.CompleteCrossing.VertexChords +OAI.Combinatorics.CompleteCrossing.VertexEvaluation +OAI.Combinatorics.Crossing.AdjacentSurgeryDrawing +OAI.Combinatorics.Crossing.AdjacentSurgeryPointRemoval +OAI.Combinatorics.Crossing.AdjacentSurgeryRoutes +OAI.Combinatorics.Crossing.AdmissibleAdjacentSurgery +OAI.Combinatorics.Crossing.AffineIntervalRestriction +OAI.Combinatorics.Crossing.AffinePathHalves +OAI.Combinatorics.Crossing.AffineSideEvents +OAI.Combinatorics.Crossing.AffineSubdivisionRefinement +OAI.Combinatorics.Crossing.AlternatingPaths +OAI.Combinatorics.Crossing.ArcRangeMinimality +OAI.Combinatorics.Crossing.AssembledAdmissibleDrawing +OAI.Combinatorics.Crossing.AssembledContinuousDrawing +OAI.Combinatorics.Crossing.AssembledCrossings +OAI.Combinatorics.Crossing.AssembledEdge +OAI.Combinatorics.Crossing.AssembledNoTriples +OAI.Combinatorics.Crossing.AssembledPortIncidence +OAI.Combinatorics.Crossing.Bivariate +OAI.Combinatorics.Crossing.BoundaryCollar +OAI.Combinatorics.Crossing.ChainPieceInteriors +OAI.Combinatorics.Crossing.ChainTracePieces +OAI.Combinatorics.Crossing.ChordOrientations +OAI.Combinatorics.Crossing.ChordPairing +OAI.Combinatorics.Crossing.ChordTransversality +OAI.Combinatorics.Crossing.CircleChords +OAI.Combinatorics.Crossing.CircleConnectors +OAI.Combinatorics.Crossing.CircleDeterminantOrder +OAI.Combinatorics.Crossing.CircleOffset +OAI.Combinatorics.Crossing.CircleOffsetLine +OAI.Combinatorics.Crossing.CircleOffsetParameter +OAI.Combinatorics.Crossing.CircleParameterChart +OAI.Combinatorics.Crossing.ClosedPolygonIntersection +OAI.Combinatorics.Crossing.CollinearSegmentUnion +OAI.Combinatorics.Crossing.CompactCorridors +OAI.Combinatorics.Crossing.ConeIntersection +OAI.Combinatorics.Crossing.ConstructAdjacentSurgery +OAI.Combinatorics.Crossing.CrossingCoordinates +OAI.Combinatorics.Crossing.CrossingCutWalks +OAI.Combinatorics.Crossing.CrossingDiskCount +OAI.Combinatorics.Crossing.CrossingDiskIncidence +OAI.Combinatorics.Crossing.CrossingDiskNeighborhood +OAI.Combinatorics.Crossing.CrossingDiskOwners +OAI.Combinatorics.Crossing.CrossingDiskUniqueness +OAI.Combinatorics.Crossing.CrossingIncidence +OAI.Combinatorics.Crossing.CrossingPortClearance +OAI.Combinatorics.Crossing.CrossingReconnection +OAI.Combinatorics.Crossing.CrossingSurgeryGraph +OAI.Combinatorics.Crossing.CurveDiskIsolation +OAI.Combinatorics.Crossing.CutTraceSeparation +OAI.Combinatorics.Crossing.CutVertexAvoidance +OAI.Combinatorics.Crossing.CyclicSumArithmetic +OAI.Combinatorics.Crossing.DiskFillingContainment +OAI.Combinatorics.Crossing.DiskPassage +OAI.Combinatorics.Crossing.DiskSegments +OAI.Combinatorics.Crossing.DrawingDefinition +OAI.Combinatorics.Crossing.DrawingDiskIsolation +OAI.Combinatorics.Crossing.DrawingEdgeWalk +OAI.Combinatorics.Crossing.DrawingEdgeWalkTrace +OAI.Combinatorics.Crossing.DrawingExteriorReplacement +OAI.Combinatorics.Crossing.DrawingMarks +OAI.Combinatorics.Crossing.DrawingPassages +OAI.Combinatorics.Crossing.DrawingPorts +OAI.Combinatorics.Crossing.DrawingRangeCrossings +OAI.Combinatorics.Crossing.DrawingSegmentIncidence +OAI.Combinatorics.Crossing.DrawingSpokePorts +OAI.Combinatorics.Crossing.DrawingSubdivisionGraph +OAI.Combinatorics.Crossing.DrawingVertexPlacement +OAI.Combinatorics.Crossing.DrawingWalkCutTraces +OAI.Combinatorics.Crossing.DrawnEdgeChains +OAI.Combinatorics.Crossing.EmbeddedGraphPaths +OAI.Combinatorics.Crossing.EndpointVisits +OAI.Combinatorics.Crossing.ExteriorArcReplacement +OAI.Combinatorics.Crossing.ExteriorChordMeeting +OAI.Combinatorics.Crossing.ExteriorCrossingCut +OAI.Combinatorics.Crossing.ExteriorSegmentGraph +OAI.Combinatorics.Crossing.ExteriorSpokeMeeting +OAI.Combinatorics.Crossing.ExtraDrawingSubdivision +OAI.Combinatorics.Crossing.FiniteAffineCover +OAI.Combinatorics.Crossing.FiniteCircleCoordinates +OAI.Combinatorics.Crossing.FiniteConePoint +OAI.Combinatorics.Crossing.FiniteDiskCollar +OAI.Combinatorics.Crossing.FiniteEventualRadius +OAI.Combinatorics.Crossing.FiniteIntersectionDrawing +OAI.Combinatorics.Crossing.FiniteLineAvoidance +OAI.Combinatorics.Crossing.FiniteMovingPoints +OAI.Combinatorics.Crossing.FinitePathChain +OAI.Combinatorics.Crossing.FinitePolygonalComposition +OAI.Combinatorics.Crossing.FiniteScaledRadius +OAI.Combinatorics.Crossing.FiniteSeparation +OAI.Combinatorics.Crossing.FirstLastVisits +OAI.Combinatorics.Crossing.FloorArithmetic +OAI.Combinatorics.Crossing.FourCycles +OAI.Combinatorics.Crossing.GeneralOrderAveraging +OAI.Combinatorics.Crossing.GeneralSpokeAveraging +OAI.Combinatorics.Crossing.GenericPointExtension +OAI.Combinatorics.Crossing.GenericPointFamily +OAI.Combinatorics.Crossing.GenericPolygonIntersection +OAI.Combinatorics.Crossing.GenericPolynomialBox +OAI.Combinatorics.Crossing.GraphSequenceWalk +OAI.Combinatorics.Crossing.GraphWalkRealizationLaws +OAI.Combinatorics.Crossing.GraphWalkTrace +OAI.Combinatorics.Crossing.IncidentSpokePorts +OAI.Combinatorics.Crossing.InnerDrawingPassages +OAI.Combinatorics.Crossing.Interpolation +OAI.Combinatorics.Crossing.IntervalSegmentStrict +OAI.Combinatorics.Crossing.IntervalSegments +OAI.Combinatorics.Crossing.LocalLineBends +OAI.Combinatorics.Crossing.LocalSegmentTransversality +OAI.Combinatorics.Crossing.LocallyStraightNormalization +OAI.Combinatorics.Crossing.LocallyTransverseNormalization +OAI.Combinatorics.Crossing.MarkedCurveDisks +OAI.Combinatorics.Crossing.MiddleEdgeIncidence +OAI.Combinatorics.Crossing.MiddlePathInjective +OAI.Combinatorics.Crossing.MiddleSpokeMeeting +OAI.Combinatorics.Crossing.MinimumChainGeometry +OAI.Combinatorics.Crossing.MinimumChainVertexPieces +OAI.Combinatorics.Crossing.MovingDiskClearance +OAI.Combinatorics.Crossing.MovingSegmentStability +OAI.Combinatorics.Crossing.NoAdjacentLocalNormalization +OAI.Combinatorics.Crossing.NoAdjacentNormalization +OAI.Combinatorics.Crossing.NodeMoments +OAI.Combinatorics.Crossing.NormalOffsetExterior +OAI.Combinatorics.Crossing.NormalizedPolygonalDrawing +OAI.Combinatorics.Crossing.OffsetBendSegments +OAI.Combinatorics.Crossing.OffsetSegments +OAI.Combinatorics.Crossing.OffsetTrack +OAI.Combinatorics.Crossing.OffsetVectors +OAI.Combinatorics.Crossing.OpenSegmentEndpoints +OAI.Combinatorics.Crossing.OrderShift +OAI.Combinatorics.Crossing.OrderedAffineSubdivision +OAI.Combinatorics.Crossing.OrderedCrossingPorts +OAI.Combinatorics.Crossing.OrderedExteriorPaths +OAI.Combinatorics.Crossing.OrderedKnotCover +OAI.Combinatorics.Crossing.OrderedPassages +OAI.Combinatorics.Crossing.OrderedPathParts +OAI.Combinatorics.Crossing.OrientedSimilarity +OAI.Combinatorics.Crossing.ParallelDirection +OAI.Combinatorics.Crossing.ParameterNeighborhoods +OAI.Combinatorics.Crossing.PathConcatenationInjective +OAI.Combinatorics.Crossing.PathEndpointNeighborhoods +OAI.Combinatorics.Crossing.PathSubarc +OAI.Combinatorics.Crossing.PeriodicPolygon +OAI.Combinatorics.Crossing.PhysicalCircleAveraging +OAI.Combinatorics.Crossing.PhysicalSpokeAveraging +OAI.Combinatorics.Crossing.PlanarDeterminant +OAI.Combinatorics.Crossing.PlanarSegments +OAI.Combinatorics.Crossing.PolygonComposition +OAI.Combinatorics.Crossing.PolygonStability +OAI.Combinatorics.Crossing.PolygonTransversalityStability +OAI.Combinatorics.Crossing.PolygonalArcInjective +OAI.Combinatorics.Crossing.PolygonalBoundaryReplacement +OAI.Combinatorics.Crossing.PolygonalChainComposition +OAI.Combinatorics.Crossing.PolygonalChainExistence +OAI.Combinatorics.Crossing.PolygonalChainOperations +OAI.Combinatorics.Crossing.PolygonalChainShortcuts +OAI.Combinatorics.Crossing.PolygonalChainTransversality +OAI.Combinatorics.Crossing.PolygonalChains +OAI.Combinatorics.Crossing.PolygonalEndpointCasts +OAI.Combinatorics.Crossing.PolygonalExterior +OAI.Combinatorics.Crossing.PolygonalNormalization +OAI.Combinatorics.Crossing.PolygonalParametrization +OAI.Combinatorics.Crossing.PolygonalParametrizationCover +OAI.Combinatorics.Crossing.PolygonalReach +OAI.Combinatorics.Crossing.PolygonalWalks +OAI.Combinatorics.Crossing.PolynomialKernel +OAI.Combinatorics.Crossing.ProperCrossingLocality +OAI.Combinatorics.Crossing.ProperSegmentCrossing +OAI.Combinatorics.Crossing.RadialBoundaryPorts +OAI.Combinatorics.Crossing.RadialExterior +OAI.Combinatorics.Crossing.ReconnectedIntersectionCases +OAI.Combinatorics.Crossing.ReconnectedPaths +OAI.Combinatorics.Crossing.ReconnectedPointRemoval +OAI.Combinatorics.Crossing.ReconnectedVertexAvoidance +OAI.Combinatorics.Crossing.ReconnectedWalks +OAI.Combinatorics.Crossing.ReconnectionAvoidance +OAI.Combinatorics.Crossing.ReconnectionChords +OAI.Combinatorics.Crossing.ReconnectionOppositeCuts +OAI.Combinatorics.Crossing.ReconnectionOtherEdges +OAI.Combinatorics.Crossing.ReconnectionVertexAvoidance +OAI.Combinatorics.Crossing.ReducedCrossingCorners +OAI.Combinatorics.Crossing.ReducedCrossingTransversality +OAI.Combinatorics.Crossing.ReducedPolygonalPresentation +OAI.Combinatorics.Crossing.ReplaceDrawingEdges +OAI.Combinatorics.Crossing.ReplaceDrawingRangeCases +OAI.Combinatorics.Crossing.RetainedArcDisjointness +OAI.Combinatorics.Crossing.RetainedDrawingArcs +OAI.Combinatorics.Crossing.RoundCircleChords +OAI.Combinatorics.Crossing.RoundDiskChords +OAI.Combinatorics.Crossing.RoundDiskClearance +OAI.Combinatorics.Crossing.RoundDiskVisits +OAI.Combinatorics.Crossing.RowCrossingCount +OAI.Combinatorics.Crossing.SegmentAffineForms +OAI.Combinatorics.Crossing.SegmentAugmentation +OAI.Combinatorics.Crossing.SegmentClosedIncidence +OAI.Combinatorics.Crossing.SegmentContinuity +OAI.Combinatorics.Crossing.SegmentCrossingCoordinates +OAI.Combinatorics.Crossing.SegmentIntersectionUnique +OAI.Combinatorics.Crossing.SegmentParameters +OAI.Combinatorics.Crossing.SegmentSides +OAI.Combinatorics.Crossing.SegmentSymmetries +OAI.Combinatorics.Crossing.SegmentTraversalReversal +OAI.Combinatorics.Crossing.SharedTrackAvoidance +OAI.Combinatorics.Crossing.ShiftedSegmentStability +OAI.Combinatorics.Crossing.ShortVertexRadius +OAI.Combinatorics.Crossing.SimilarityCoordinates +OAI.Combinatorics.Crossing.SimultaneousExteriorArcs +OAI.Combinatorics.Crossing.SimultaneousPolygonalReplacement +OAI.Combinatorics.Crossing.SortedMarkedParameters +OAI.Combinatorics.Crossing.SortedSideEvents +OAI.Combinatorics.Crossing.SpokeTrackDirections +OAI.Combinatorics.Crossing.StepEvents +OAI.Combinatorics.Crossing.StraightChainIntersections +OAI.Combinatorics.Crossing.StraightChainTransversality +OAI.Combinatorics.Crossing.SubdivisionPointEndpoints +OAI.Combinatorics.Crossing.SubdivisionSegments +OAI.Combinatorics.Crossing.SublevelExtrema +OAI.Combinatorics.Crossing.SurgeryCrossingContainment +OAI.Combinatorics.Crossing.SurgeryCutWalks +OAI.Combinatorics.Crossing.SurgeryFiniteDrawing +OAI.Combinatorics.Crossing.SurgeryNoTriples +OAI.Combinatorics.Crossing.SurgeryPathWitnesses +OAI.Combinatorics.Crossing.SurgeryRouteIntersections +OAI.Combinatorics.Crossing.SurgeryStrictPointCount +OAI.Combinatorics.Crossing.TangentTrackIdentity +OAI.Combinatorics.Crossing.TrackEndpointConnections +OAI.Combinatorics.Crossing.TransversalityStability +OAI.Combinatorics.Crossing.TransversePolygonIntersection +OAI.Combinatorics.Crossing.TriangleEntryExit +OAI.Combinatorics.Crossing.TriangleOrientations +OAI.Combinatorics.Crossing.TriangleSideEvent +OAI.Combinatorics.Crossing.TriangleTransversality +OAI.Combinatorics.Crossing.TruncatedChainDirections +OAI.Combinatorics.Crossing.TruncatedChainPath +OAI.Combinatorics.Crossing.TruncatedChainVertices +OAI.Combinatorics.Crossing.TruncatedCrossingCorners +OAI.Combinatorics.Crossing.TruncatedCrossingRetention +OAI.Combinatorics.Crossing.TruncatedDrawingDisks +OAI.Combinatorics.Crossing.TruncatedDrawingInteriors +OAI.Combinatorics.Crossing.TruncatedRadialEnds +OAI.Combinatorics.Crossing.TruncatedSegmentTransversality +OAI.Combinatorics.Crossing.TruncatedSpokeCoordinates +OAI.Combinatorics.Crossing.TruncatedSpokeDirections +OAI.Combinatorics.Crossing.TruncatedTraceDecomposition +OAI.Combinatorics.Crossing.TruncatedTrackAvoidance +OAI.Combinatorics.Crossing.TwoTriangleIndices +OAI.Combinatorics.Crossing.TwoTriangleUnisolvence +OAI.Combinatorics.Crossing.UniqueWalkPassage +OAI.Combinatorics.Crossing.VertexDiskSpokes +OAI.Combinatorics.Crossing.VertexDisksCrossingFree +OAI.Combinatorics.Crossing.VertexEndpointPorts +OAI.Combinatorics.Crossing.VertexPieceClearance +OAI.Combinatorics.Crossing.VertexSpokeBounds +OAI.Combinatorics.Crossing.VertexTraceDisks +OAI.Combinatorics.Crossing.VertexTruncation +OAI.Combinatorics.Crossing.VertexTruncationGeometry diff --git a/tasks/complete-crossing/solution/reference.py b/tasks/complete-crossing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/complete-crossing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/complete-crossing/solution/solve.sh b/tasks/complete-crossing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e40c9adde66d3b2105b2f4bf9afb4b6be69d5efc --- /dev/null +++ b/tasks/complete-crossing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CompleteCrossing, i.e. module OAI.Combinatorics.CompleteCrossing.Main and the +# 300 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.CompleteCrossing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CompleteCrossing" diff --git a/tasks/complete-crossing/task.toml b/tasks/complete-crossing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fcad59baa109684a472bf6b6153605c6fff5ff5 --- /dev/null +++ b/tasks/complete-crossing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/complete-crossing" +version = "1.0.0" +description = "Prove CompleteCrossing (openai/math family 165: Exact crossing numbers of complete and complete bipartite graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CompleteCrossing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CompleteCrossing" +family = "165" +family_title = "Exact crossing numbers of complete and complete bipartite graphs" +subject = "Combinatorics" +theorems = ["OAI.Paper170.complete_graph_crossing_number"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.CompleteCrossing.Main" +reference_modules = 300 +reference_lean_bytes = 1464297 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 800 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13017 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/complete-crossing/tests/Challenge.lean b/tasks/complete-crossing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..71d55871fcf64b6b7b64c0de5f799e5af5f8f96e --- /dev/null +++ b/tasks/complete-crossing/tests/Challenge.lean @@ -0,0 +1,89 @@ +import Mathlib.Data.Set.Card +import Mathlib.Order.Lattice.Nat +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Topology.OpenPartialHomeomorph.Defs +import Mathlib.Topology.Path + +namespace OAI + +noncomputable section + +namespace Paper170 + +abbrev Plane := ℝ × ℝ + +structure Graph (Vertex Edge : Type) where + src : Edge → Vertex + dst : Edge → Vertex + loopless : ∀ edge, src edge ≠ dst edge + simple : ∀ edge other, ((src edge = src other ∧ dst edge = dst other) ∨ + (src edge = dst other ∧ dst edge = src other)) → edge = other + +abbrev CompleteEdge (order : ℕ) := {pair : Fin order × Fin order // pair.1 < pair.2} + +def completeGraph (order : ℕ) : Graph (Fin order) (CompleteEdge order) where + src edge := edge.val.1 + dst edge := edge.val.2 + loopless edge := ne_of_lt edge.property + simple edge other same := by + rcases same with same | reversed + · exact Subtype.ext (Prod.ext same.1 same.2) + · have increasing := edge.property + have other_increasing := other.property + rw [reversed.1, reversed.2] at increasing + exact (lt_asymm increasing other_increasing).elim + +variable {Vertex Edge : Type} + +structure ContinuousDrawing (graph : Graph Vertex Edge) where + vertex : Vertex → Plane + vertex_injective : Function.Injective vertex + edge : ∀ edge : Edge, Path (vertex (graph.src edge)) (vertex (graph.dst edge)) + edge_injective : ∀ selected, Function.Injective (edge selected) + interior_avoids_vertices : ∀ selected time, time ∈ Set.Ioo (0 : unitInterval) 1 → + ∀ other, edge selected time ≠ vertex other + +variable {graph : Graph Vertex Edge} + +def edgeInterior (drawing : ContinuousDrawing graph) (edge : Edge) : Set Plane := + drawing.edge edge '' Set.Ioo (0 : unitInterval) 1 + +structure ProperCrossing (first second : Set Plane) (point : Plane) : Prop where + chart_exists : ∃ chart : OpenPartialHomeomorph Plane Plane, + point ∈ chart.source ∧ chart point = (0, 0) ∧ + chart '' (chart.source ∩ first) = chart.target ∩ {image | image.2 = 0} ∧ + chart '' (chart.source ∩ second) = chart.target ∩ {image | image.1 = 0} + +def crossingPoints (drawing : ContinuousDrawing graph) : Set Plane := + {point | ∃ edge other : Edge, edge ≠ other ∧ + point ∈ edgeInterior drawing edge ∧ point ∈ edgeInterior drawing other} + +structure AdmissibleDrawing (graph : Graph Vertex Edge) extends ContinuousDrawing graph where + crossings_finite : (crossingPoints toContinuousDrawing).Finite + crossings_proper : ∀ edge other, edge ≠ other → ∀ point, + point ∈ edgeInterior toContinuousDrawing edge → + point ∈ edgeInterior toContinuousDrawing other → + ProperCrossing (edgeInterior toContinuousDrawing edge) + (edgeInterior toContinuousDrawing other) point + no_triples : ∀ first second third, first ≠ second → first ≠ third → second ≠ third → + edgeInterior toContinuousDrawing first ∩ edgeInterior toContinuousDrawing second ∩ + edgeInterior toContinuousDrawing third = ∅ + +def crossingCount (drawing : AdmissibleDrawing graph) : ℕ := + drawing.crossings_finite.toFinset.card + +def ordinaryCrossingNumber (graph : Graph Vertex Edge) : ℕ := + sInf (Set.range (@crossingCount Vertex Edge graph)) + +def hill (order : ℕ) : ℕ := + (order / 2 * ((order - 1) / 2) * ((order - 2) / 2) * ((order - 3) / 2)) / 4 + +theorem complete_graph_crossing_number (order : ℕ) (at_least_three : 3 ≤ order) : + ordinaryCrossingNumber (completeGraph order) = hill order := by + sorry + +end Paper170 + +end + +end OAI diff --git a/tasks/complete-crossing/tests/grade.py b/tasks/complete-crossing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/complete-crossing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/complete-crossing/tests/task.json b/tasks/complete-crossing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2308151cf379e1d0900a81bdf379f34ff09229ae --- /dev/null +++ b/tasks/complete-crossing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CompleteCrossing", + "comparator": { + "theorem_names": [ + "OAI.Paper170.complete_graph_crossing_number" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12117 +} \ No newline at end of file diff --git a/tasks/complete-crossing/tests/test.sh b/tasks/complete-crossing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/complete-crossing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/complete-crouzeix/environment/Dockerfile b/tasks/complete-crouzeix/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/complete-crouzeix/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/complete-crouzeix/environment/fetch_mathlib.sh b/tasks/complete-crouzeix/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/complete-crouzeix/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/complete-crouzeix/environment/lake-manifest.json b/tasks/complete-crouzeix/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/complete-crouzeix/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/complete-crouzeix/environment/lakefile.lean b/tasks/complete-crouzeix/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/complete-crouzeix/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/complete-crouzeix/environment/lean_setup.sh b/tasks/complete-crouzeix/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/complete-crouzeix/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/complete-crouzeix/environment/pack_submission.py b/tasks/complete-crouzeix/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/complete-crouzeix/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/complete-crouzeix/instruction.md b/tasks/complete-crouzeix/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..152742bb6c713f4e24a08cdf746783414de6d92a --- /dev/null +++ b/tasks/complete-crouzeix/instruction.md @@ -0,0 +1,90 @@ +# openai/math challenge `CompleteCrouzeix` (family 325) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 325 of the release, *The complete Crouzeix conjecture* +(Functional analysis). The family as a whole: Resolves the complete Crouzeix conjecture: for every bounded operator $A$ on a complex Hilbert space and every finite matrix-valued polynomial $P$, one has $\lVert P[A]\rVert\le2\sup_{z\in W(A)}\lVert P(z)\rVert$, where $W(A)$ is the numerical range. The constant $2$ is sharp, independent of the matrix size, and valid in infinite dimensions. + +The challenge is `CompleteCrouzeix`, also at `/opt/openai-math/challenges/CompleteCrouzeix.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder + +namespace CompleteCrouzeix + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ x : EuclideanSpace ℂ (Fin n), ‖x‖ = 1 ∧ + inner ℂ x (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A x) = z} + +def polynomialValue {m d : ℕ} (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) + (z : ℂ) : Matrix (Fin m) (Fin m) ℂ := + ∑ k : Fin (d + 1), (z ^ (k : ℕ)) • B k + +def polynomialAt {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : + Matrix (Fin n × Fin m) (Fin n × Fin m) ℂ := + ∑ k : Fin (d + 1), Matrix.kronecker (A ^ (k : ℕ)) (B k) + +def rangeMaximum {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖polynomialValue B z‖) '' numericalRange A) + +def UniversalBound (C : ℝ) : Prop := + ∀ (n m d : ℕ), 0 < n → 0 < m → + ∀ (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ), + ‖polynomialAt A B‖ ≤ C * rangeMaximum A B + +theorem main : UniversalBound 2 ∧ ∀ C : ℝ, UniversalBound C → 2 ≤ C := by + sorry + +end CompleteCrouzeix +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CompleteCrouzeix.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CompleteCrouzeix.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/complete-crouzeix/solution/closure.txt b/tasks/complete-crouzeix/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c17233ee2304b190401ceff620ff51ba67a829eb --- /dev/null +++ b/tasks/complete-crouzeix/solution/closure.txt @@ -0,0 +1,48 @@ +OAI.Analysis.NumericalRange.AnalyticCharts +OAI.Analysis.NumericalRange.BoundaryCalculus +OAI.Analysis.NumericalRange.BoundaryNormals +OAI.Analysis.NumericalRange.BoundaryRepresentation +OAI.Analysis.NumericalRange.CauchyEvaluation +OAI.Analysis.NumericalRange.CauchyProjection +OAI.Analysis.NumericalRange.CircleIntegrals +OAI.Analysis.NumericalRange.CompleteResolvent +OAI.Analysis.NumericalRange.ConformalGluing +OAI.Analysis.NumericalRange.ConformalJacobian +OAI.Analysis.NumericalRange.ConformalWinding +OAI.Analysis.NumericalRange.ConvexBarrier +OAI.Analysis.NumericalRange.ConvexExterior +OAI.Analysis.NumericalRange.Convexity +OAI.Analysis.NumericalRange.DensityAdjoints +OAI.Analysis.NumericalRange.DensityComparison +OAI.Analysis.NumericalRange.DensityIdentification +OAI.Analysis.NumericalRange.DensityTransport +OAI.Analysis.NumericalRange.DilationDensity +OAI.Analysis.NumericalRange.DiskCalculus +OAI.Analysis.NumericalRange.DiskMapping +OAI.Analysis.NumericalRange.DomainBound +OAI.Analysis.NumericalRange.DomainCalculus +OAI.Analysis.NumericalRange.DualSeparation +OAI.Analysis.NumericalRange.ExteriorKernel +OAI.Analysis.NumericalRange.ExteriorProjection +OAI.Analysis.NumericalRange.FourierExtension +OAI.Analysis.NumericalRange.FourierResolution +OAI.Analysis.NumericalRange.HerglotzReflection +OAI.Analysis.NumericalRange.HilbertSchmidt +OAI.Analysis.NumericalRange.HolomorphicEvaluation +OAI.Analysis.NumericalRange.Main +OAI.Analysis.NumericalRange.MarkovOperator +OAI.Analysis.NumericalRange.MetricFeasibility +OAI.Analysis.NumericalRange.MetricNorm +OAI.Analysis.NumericalRange.Model +OAI.Analysis.NumericalRange.OptimalExtremal +OAI.Analysis.NumericalRange.OrderedDensities +OAI.Analysis.NumericalRange.OrderedMultiplication +OAI.Analysis.NumericalRange.OuterNeighborhood +OAI.Analysis.NumericalRange.PoissonBoundary +OAI.Analysis.NumericalRange.PolynomialCalculus +OAI.Analysis.NumericalRange.PositiveDensity +OAI.Analysis.NumericalRange.PulledDensity +OAI.Analysis.NumericalRange.ResolventPositivity +OAI.Analysis.NumericalRange.Sharpness +OAI.Analysis.NumericalRange.TestingAlgebra +OAI.Analysis.NumericalRange.UnitaryRealization diff --git a/tasks/complete-crouzeix/solution/reference.py b/tasks/complete-crouzeix/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/complete-crouzeix/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/complete-crouzeix/solution/solve.sh b/tasks/complete-crouzeix/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..548aa8fa27d33fd1899cda8260bc22cd3307c9e0 --- /dev/null +++ b/tasks/complete-crouzeix/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CompleteCrouzeix, i.e. module OAI.Analysis.NumericalRange.Main and the +# 48 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.NumericalRange.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CompleteCrouzeix" diff --git a/tasks/complete-crouzeix/task.toml b/tasks/complete-crouzeix/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..76eedf1fd570a812943b2b2b327afde9164d4379 --- /dev/null +++ b/tasks/complete-crouzeix/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/complete-crouzeix" +version = "1.0.0" +description = "Prove CompleteCrouzeix (openai/math family 325: The complete Crouzeix conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CompleteCrouzeix.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CompleteCrouzeix" +family = "325" +family_title = "The complete Crouzeix conjecture" +subject = "Functional analysis" +theorems = ["OAI.CompleteCrouzeix.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.NumericalRange.Main" +reference_modules = 48 +reference_lean_bytes = 652138 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1153 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12286 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/complete-crouzeix/tests/Challenge.lean b/tasks/complete-crouzeix/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..36d438f5bd42fd295ec0f01069440406582e29dc --- /dev/null +++ b/tasks/complete-crouzeix/tests/Challenge.lean @@ -0,0 +1,39 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder + +namespace CompleteCrouzeix + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ x : EuclideanSpace ℂ (Fin n), ‖x‖ = 1 ∧ + inner ℂ x (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A x) = z} + +def polynomialValue {m d : ℕ} (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) + (z : ℂ) : Matrix (Fin m) (Fin m) ℂ := + ∑ k : Fin (d + 1), (z ^ (k : ℕ)) • B k + +def polynomialAt {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : + Matrix (Fin n × Fin m) (Fin n × Fin m) ℂ := + ∑ k : Fin (d + 1), Matrix.kronecker (A ^ (k : ℕ)) (B k) + +def rangeMaximum {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖polynomialValue B z‖) '' numericalRange A) + +def UniversalBound (C : ℝ) : Prop := + ∀ (n m d : ℕ), 0 < n → 0 < m → + ∀ (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ), + ‖polynomialAt A B‖ ≤ C * rangeMaximum A B + +theorem main : UniversalBound 2 ∧ ∀ C : ℝ, UniversalBound C → 2 ≤ C := by + sorry + +end CompleteCrouzeix +end + +end OAI diff --git a/tasks/complete-crouzeix/tests/grade.py b/tasks/complete-crouzeix/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/complete-crouzeix/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/complete-crouzeix/tests/task.json b/tasks/complete-crouzeix/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c810f6a31a46ef0deab86c14fa67bbe7d18568da --- /dev/null +++ b/tasks/complete-crouzeix/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CompleteCrouzeix", + "comparator": { + "theorem_names": [ + "OAI.CompleteCrouzeix.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11386 +} \ No newline at end of file diff --git a/tasks/complete-crouzeix/tests/test.sh b/tasks/complete-crouzeix/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/complete-crouzeix/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/complex-cancellation/environment/Dockerfile b/tasks/complex-cancellation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/complex-cancellation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/complex-cancellation/environment/fetch_mathlib.sh b/tasks/complex-cancellation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/complex-cancellation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/complex-cancellation/environment/lake-manifest.json b/tasks/complex-cancellation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/complex-cancellation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/complex-cancellation/environment/lakefile.lean b/tasks/complex-cancellation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/complex-cancellation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/complex-cancellation/environment/lean_setup.sh b/tasks/complex-cancellation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/complex-cancellation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/complex-cancellation/environment/pack_submission.py b/tasks/complex-cancellation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/complex-cancellation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/complex-cancellation/instruction.md b/tasks/complex-cancellation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b244037e82f43358f49a2829589d8a9c746d3f08 --- /dev/null +++ b/tasks/complex-cancellation/instruction.md @@ -0,0 +1,83 @@ +# openai/math challenge `ComplexCancellation` (family 047) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 047 of the release, *Complex counterexamples to cancellation and affine fibrations* +(Algebraic and complex geometry). The family as a whole: Constructs an integral complex affine fourfold $X\not\cong\mathbb A^4$ with $X\times\mathbb A^1\cong\mathbb A^5$, disproving affine-space cancellation over $\mathbb C$ in dimension four. It also disproves the Dolgachev–Weisfeiler affine-fibration conjecture: smooth surjections $X\to\mathbb A^1$ and $\mathbb A^5\to\mathbb A^2$ have every residue-field fiber isomorphic to affine three-space but are not Zariski-locally trivial. + +The challenge is `ComplexCancellation`, also at `/opt/openai-math/challenges/ComplexCancellation.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace ComplexCancellation + +abbrev P := MvPolynomial (Fin 5) ℂ + +def p : P := MvPolynomial.X 0 +def s : P := MvPolynomial.X 1 +def u : P := MvPolynomial.X 2 +def F : P := MvPolynomial.X 3 +def J : P := MvPolynomial.X 4 +def x : P := s ^ 2 + u ^ 3 + p ^ 2 * F +def H : P := x ^ 2 * F - (1 + 2 * s * x) * J - p ^ 2 * J ^ 2 - p * u +abbrev A := P ⧸ Ideal.span {H} + +def MainStatement : Prop := + Algebra.FiniteType ℂ A ∧ IsDomain A ∧ ringKrullDim A = 4 ∧ + Nonempty (Polynomial A ≃ₐ[ℂ] MvPolynomial (Fin 5) ℂ) ∧ + ¬ Nonempty (A ≃ₐ[ℂ] MvPolynomial (Fin 4) ℂ) + +theorem main : MainStatement := by + sorry + +end ComplexCancellation + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ComplexCancellation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ComplexCancellation.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/complex-cancellation/solution/closure.txt b/tasks/complex-cancellation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3eddaf948a7d9df25421ae5ae20cc04cb0f41dfa --- /dev/null +++ b/tasks/complex-cancellation/solution/closure.txt @@ -0,0 +1,55 @@ +OAI.Algebra.AffineCancellation.BezoutFrame +OAI.Algebra.AffineCancellation.Bundle +OAI.Algebra.AffineCancellation.BundleGrading +OAI.Algebra.AffineCancellation.Clearing +OAI.Algebra.AffineCancellation.Cylinder +OAI.Algebra.AffineCancellation.CylinderMaps +OAI.Algebra.AffineCancellation.CylinderShift +OAI.Algebra.AffineCancellation.Degeneration +OAI.Algebra.AffineCancellation.DegenerationGrading +OAI.Algebra.AffineCancellation.Determinant +OAI.Algebra.AffineCancellation.DeterminantRigidity +OAI.Algebra.AffineCancellation.DifferentialSlice +OAI.Algebra.AffineCancellation.Dimension +OAI.Algebra.AffineCancellation.EquivariantLift +OAI.Algebra.AffineCancellation.Extraction +OAI.Algebra.AffineCancellation.FactorDerivation +OAI.Algebra.AffineCancellation.FractionDerivation +OAI.Algebra.AffineCancellation.GradedCommutation +OAI.Algebra.AffineCancellation.GradedLND +OAI.Algebra.AffineCancellation.GradedMap +OAI.Algebra.AffineCancellation.HighestWeight +OAI.Algebra.AffineCancellation.HomogeneousExtraction +OAI.Algebra.AffineCancellation.Intertwining +OAI.Algebra.AffineCancellation.InvariantRestriction +OAI.Algebra.AffineCancellation.Kernel +OAI.Algebra.AffineCancellation.LaurentDerivation +OAI.Algebra.AffineCancellation.LaurentEuler +OAI.Algebra.AffineCancellation.Main +OAI.Algebra.AffineCancellation.Model +OAI.Algebra.AffineCancellation.Modification +OAI.Algebra.AffineCancellation.ModificationGrading +OAI.Algebra.AffineCancellation.Orbit +OAI.Algebra.AffineCancellation.OrbitRigidity +OAI.Algebra.AffineCancellation.Order +OAI.Algebra.AffineCancellation.PolynomialDerivation +OAI.Algebra.AffineCancellation.PolynomialSlice +OAI.Algebra.AffineCancellation.PositiveInvariant +OAI.Algebra.AffineCancellation.PositiveObstruction +OAI.Algebra.AffineCancellation.Primitive +OAI.Algebra.AffineCancellation.Quadric +OAI.Algebra.AffineCancellation.QuotientDerivation +OAI.Algebra.AffineCancellation.QuotientGrading +OAI.Algebra.AffineCancellation.RationalSlice +OAI.Algebra.AffineCancellation.Rees +OAI.Algebra.AffineCancellation.ReesClearing +OAI.Algebra.AffineCancellation.ReesDerivation +OAI.Algebra.AffineCancellation.ReesGrading +OAI.Algebra.AffineCancellation.ReesReduction +OAI.Algebra.AffineCancellation.RelativeClearing +OAI.Algebra.AffineCancellation.ReplicaLift +OAI.Algebra.AffineCancellation.Rigidity +OAI.Algebra.AffineCancellation.TorsorClearing +OAI.Algebra.AffineCancellation.TorsorEuler +OAI.Algebra.AffineCancellation.TorsorFrame +OAI.Algebra.AffineCancellation.TorsorInverse diff --git a/tasks/complex-cancellation/solution/reference.py b/tasks/complex-cancellation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/complex-cancellation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/complex-cancellation/solution/solve.sh b/tasks/complex-cancellation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6311ecd95f4ba910e001562c5c71e072c55e5ed3 --- /dev/null +++ b/tasks/complex-cancellation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ComplexCancellation, i.e. module OAI.Algebra.AffineCancellation.Main and the +# 55 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.AffineCancellation.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ComplexCancellation" diff --git a/tasks/complex-cancellation/task.toml b/tasks/complex-cancellation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..19839976c6efb573208abe3b5140be940324fab8 --- /dev/null +++ b/tasks/complex-cancellation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/complex-cancellation" +version = "1.0.0" +description = "Prove ComplexCancellation (openai/math family 047: Complex counterexamples to cancellation and affine fibrations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ComplexCancellation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ComplexCancellation" +family = "047" +family_title = "Complex counterexamples to cancellation and affine fibrations" +subject = "Algebraic and complex geometry" +theorems = ["OAI.ComplexCancellation.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.AffineCancellation.Main" +reference_modules = 55 +reference_lean_bytes = 242585 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 971 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11918 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/complex-cancellation/tests/Challenge.lean b/tasks/complex-cancellation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4066ae67e0506a60911ca9763bb2cc4e56eeb1da --- /dev/null +++ b/tasks/complex-cancellation/tests/Challenge.lean @@ -0,0 +1,32 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace ComplexCancellation + +abbrev P := MvPolynomial (Fin 5) ℂ + +def p : P := MvPolynomial.X 0 +def s : P := MvPolynomial.X 1 +def u : P := MvPolynomial.X 2 +def F : P := MvPolynomial.X 3 +def J : P := MvPolynomial.X 4 +def x : P := s ^ 2 + u ^ 3 + p ^ 2 * F +def H : P := x ^ 2 * F - (1 + 2 * s * x) * J - p ^ 2 * J ^ 2 - p * u +abbrev A := P ⧸ Ideal.span {H} + +def MainStatement : Prop := + Algebra.FiniteType ℂ A ∧ IsDomain A ∧ ringKrullDim A = 4 ∧ + Nonempty (Polynomial A ≃ₐ[ℂ] MvPolynomial (Fin 5) ℂ) ∧ + ¬ Nonempty (A ≃ₐ[ℂ] MvPolynomial (Fin 4) ℂ) + +theorem main : MainStatement := by + sorry + +end ComplexCancellation + +end + +end OAI diff --git a/tasks/complex-cancellation/tests/grade.py b/tasks/complex-cancellation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/complex-cancellation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/complex-cancellation/tests/task.json b/tasks/complex-cancellation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..10ac7f18e39cb0649aa4409fc961629fef56e985 --- /dev/null +++ b/tasks/complex-cancellation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ComplexCancellation", + "comparator": { + "theorem_names": [ + "OAI.ComplexCancellation.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11018 +} \ No newline at end of file diff --git a/tasks/complex-cancellation/tests/test.sh b/tasks/complex-cancellation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/complex-cancellation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/conductivity/environment/Dockerfile b/tasks/conductivity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/conductivity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/conductivity/environment/fetch_mathlib.sh b/tasks/conductivity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/conductivity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/conductivity/environment/lake-manifest.json b/tasks/conductivity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/conductivity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/conductivity/environment/lakefile.lean b/tasks/conductivity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/conductivity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/conductivity/environment/lean_setup.sh b/tasks/conductivity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/conductivity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/conductivity/environment/pack_submission.py b/tasks/conductivity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/conductivity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/conductivity/instruction.md b/tasks/conductivity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9659f768b693e7b660819026a6a224519398b554 --- /dev/null +++ b/tasks/conductivity/instruction.md @@ -0,0 +1,134 @@ +# openai/math challenge `Conductivity` (family 365) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 365 of the release, *Joint metric and connection recovery from one boundary patch* +(Partial differential equations). The family as a whole: Zero-frequency measurements on any nonempty open boundary patch determine a smooth metric and smooth unitary connection on a trivial Hermitian rank-two bundle over a compact connected manifold of dimension at least three, up to diffeomorphism and gauge fixed on that patch. Inputs and observations use the same patch. In contrast, distinct uniformly positive bounded measurable scalar conductivities on a three-dimensional ball can have identical full-boundary data. + +The challenge is `Conductivity`, also at `/opt/openai-math/challenges/Conductivity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace ScalarConductivity + +abbrev R3 := EuclideanSpace ℝ (Fin 3) +abbrev JetFiber := EuclideanSpace ℝ (Fin 4) +def ball : Set R3 := Metric.ball 0 3 +def ballMeasure : Measure R3 := volume.restrict ball +abbrev JetSpace := Lp JetFiber 2 ballMeasure + +def smoothJet (f : R3 → ℝ) (x : R3) : JetFiber := + WithLp.toLp 2 (Fin.cases (f x) (fun i => gradient f x i)) + +def smoothJets : Set JetSpace := + { z | ∃ (f : R3 → ℝ) (_ : ContDiff ℝ (↑(⊤ : ℕ∞)) f) + (hf : MemLp (smoothJet f) 2 ballMeasure), z = hf.toLp (smoothJet f) } + +def compactSmoothJets : Set JetSpace := + { z | ∃ (f : R3 → ℝ) (_ : ContDiff ℝ (↑(⊤ : ℕ∞)) f) + (_ : HasCompactSupport f) (_ : tsupport f ⊆ ball) + (hf : MemLp (smoothJet f) 2 ballMeasure), z = hf.toLp (smoothJet f) } + +def H1Space : Submodule ℝ JetSpace := + (Submodule.span ℝ smoothJets).topologicalClosure +abbrev H1 := H1Space + +def zeroTraceAmbient : Submodule ℝ JetSpace := + (Submodule.span ℝ compactSmoothJets).topologicalClosure + +def H10 : Submodule ℝ H1 := zeroTraceAmbient.comap H1Space.subtype + +instance H10_isClosed : IsClosed (H10 : Set H1) := by + exact (Submodule.isClosed_topologicalClosure + (Submodule.span ℝ compactSmoothJets)).preimage continuous_subtype_val + +abbrev TraceSpace := H1 ⧸ H10 +abbrev TraceDual := TraceSpace →L[ℝ] ℝ +abbrev DNOperator := TraceSpace →L[ℝ] TraceDual + +def trace (u : H1) : TraceSpace := H10.mkQ u + +def weakGradient (u : H1) (x : R3) : R3 := + WithLp.toLp 2 (fun i => (u.val x) i.succ) + +def energy (γ : R3 → ℝ) (u v : H1) : ℝ := + ∫ x, γ x * inner ℝ (weakGradient u x) (weakGradient v x) ∂ballMeasure + +def Harmonic (γ : R3 → ℝ) (u : H1) : Prop := + ∀ h : H1, h ∈ H10 → energy γ u h = 0 + +def IsDirichletToNeumann (γ : R3 → ℝ) (Λ : DNOperator) : Prop := + ∀ f : TraceSpace, ∃ u : H1, + trace u = f ∧ Harmonic γ u ∧ + (∀ u' : H1, trace u' = f → Harmonic γ u' → u' = u) ∧ + ∀ v : H1, Λ f (trace v) = energy γ u v + +def EqualOneNearBoundary (γ : R3 → ℝ) : Prop := + ∃ r : ℝ, 0 < r ∧ r < 3 ∧ ∀ᵐ x ∂ballMeasure, r < ‖x‖ → γ x = 1 + +def MainStatement : Prop := + ∃ (γ₀ γ₁ : R3 → ℝ) (c C : ℝ) (Λ : DNOperator), + 0 < c ∧ c < C ∧ + Measurable γ₀ ∧ Measurable γ₁ ∧ + MemLp γ₀ ∞ ballMeasure ∧ MemLp γ₁ ∞ ballMeasure ∧ + (∀ᵐ x ∂ballMeasure, c ≤ γ₀ x ∧ γ₀ x ≤ C) ∧ + (∀ᵐ x ∂ballMeasure, c ≤ γ₁ x ∧ γ₁ x ≤ C) ∧ + EqualOneNearBoundary γ₀ ∧ EqualOneNearBoundary γ₁ ∧ + 0 < ballMeasure {x | γ₀ x ≠ γ₁ x} ∧ + IsDirichletToNeumann γ₀ Λ ∧ IsDirichletToNeumann γ₁ Λ + +theorem main_nonuniqueness : MainStatement := by + sorry + +end ScalarConductivity +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Conductivity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ScalarConductivity.main_nonuniqueness` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/conductivity/solution/closure.txt b/tasks/conductivity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb57ae4ab955e39c33a8faf6d5dd37e4baf51ff5 --- /dev/null +++ b/tasks/conductivity/solution/closure.txt @@ -0,0 +1,595 @@ +OAI.Analysis.Conductivity.Branching.AlignedEndingData +OAI.Analysis.Conductivity.Branching.AlignedEndingRegularity +OAI.Analysis.Conductivity.Branching.AttachedCutLayer +OAI.Analysis.Conductivity.Branching.AttachedEndGradientL2 +OAI.Analysis.Conductivity.Branching.AttachedEndL2 +OAI.Analysis.Conductivity.Branching.AttachedEndLayer +OAI.Analysis.Conductivity.Branching.AttachedEndLinear +OAI.Analysis.Conductivity.Branching.AttachedFlatTransport +OAI.Analysis.Conductivity.Branching.BranchFiniteEnding +OAI.Analysis.Conductivity.Branching.BranchOutputNormalization +OAI.Analysis.Conductivity.Branching.CascadeCoefficient +OAI.Analysis.Conductivity.Branching.CascadeGeometry +OAI.Analysis.Conductivity.Branching.CascadeLocality +OAI.Analysis.Conductivity.Branching.CascadeProfile +OAI.Analysis.Conductivity.Branching.CascadeProfileDeriv +OAI.Analysis.Conductivity.Branching.CascadeRankPieces +OAI.Analysis.Conductivity.Branching.CascadeStreams +OAI.Analysis.Conductivity.Branching.CascadeWeakEnd +OAI.Analysis.Conductivity.Branching.CentralChildCollar +OAI.Analysis.Conductivity.Branching.CentralJoinCover +OAI.Analysis.Conductivity.Branching.ChildCentralL2 +OAI.Analysis.Conductivity.Branching.ChildComplementPartition +OAI.Analysis.Conductivity.Branching.ChildCoordinateAnalysis +OAI.Analysis.Conductivity.Branching.ChildEndPartition +OAI.Analysis.Conductivity.Branching.ChildFullEndEnergy +OAI.Analysis.Conductivity.Branching.ChildInverse +OAI.Analysis.Conductivity.Branching.ChildJetScaling +OAI.Analysis.Conductivity.Branching.ChildLocalizedJet +OAI.Analysis.Conductivity.Branching.ChildTransportFormula +OAI.Analysis.Conductivity.Branching.CollarMeasureTransport +OAI.Analysis.Conductivity.Branching.CrossingBlock +OAI.Analysis.Conductivity.Branching.DelayedEndingRegularity +OAI.Analysis.Conductivity.Branching.Ending +OAI.Analysis.Conductivity.Branching.EndingCoordinateTransport +OAI.Analysis.Conductivity.Branching.EndingJoinElliptic +OAI.Analysis.Conductivity.Branching.EndingJoinOverlap +OAI.Analysis.Conductivity.Branching.FiniteEndingRegularity +OAI.Analysis.Conductivity.Branching.FlatEndingSplice +OAI.Analysis.Conductivity.Branching.JoinHull +OAI.Analysis.Conductivity.Branching.JoinedPhysicalEnds +OAI.Analysis.Conductivity.Branching.LinearFiniteEndTransport +OAI.Analysis.Conductivity.Branching.MatchedEndingRegularity +OAI.Analysis.Conductivity.Branching.MatchedEndingWeak +OAI.Analysis.Conductivity.Branching.MeasurableDisjointGluing +OAI.Analysis.Conductivity.Branching.MeasurableDisjointGluingMeasurable +OAI.Analysis.Conductivity.Branching.OpenDisjointify +OAI.Analysis.Conductivity.Branching.ParametricCorrectionTransport +OAI.Analysis.Conductivity.Branching.ParentCentralL2 +OAI.Analysis.Conductivity.Branching.ParentComplementPartition +OAI.Analysis.Conductivity.Branching.ParentCompletedEndJet +OAI.Analysis.Conductivity.Branching.ParentEndPartition +OAI.Analysis.Conductivity.Branching.ParentFullEndEnergy +OAI.Analysis.Conductivity.Branching.ParentLocalizedJet +OAI.Analysis.Conductivity.Branching.PhysicalAttachedAssembly +OAI.Analysis.Conductivity.Branching.PhysicalAttachedWeakPDE +OAI.Analysis.Conductivity.Branching.PhysicalBlockEnergy +OAI.Analysis.Conductivity.Branching.PhysicalBlockEnergySum +OAI.Analysis.Conductivity.Branching.PhysicalBlockRepresentative +OAI.Analysis.Conductivity.Branching.PhysicalChildAttachedCorrection +OAI.Analysis.Conductivity.Branching.PhysicalChildIntegral +OAI.Analysis.Conductivity.Branching.PhysicalFiniteEndingData +OAI.Analysis.Conductivity.Branching.PhysicalFlatTransport +OAI.Analysis.Conductivity.Branching.PhysicalJoin +OAI.Analysis.Conductivity.Branching.PhysicalNullTransport +OAI.Analysis.Conductivity.Branching.PhysicalOpenBlock +OAI.Analysis.Conductivity.Branching.PhysicalRankTransport +OAI.Analysis.Conductivity.Branching.PhysicalTraceTransport +OAI.Analysis.Conductivity.Branching.QuantitativeRegularTransport +OAI.Analysis.Conductivity.Branching.RecoverJoinChild +OAI.Analysis.Conductivity.Branching.RegularMomentTransport +OAI.Analysis.Conductivity.Branching.SmoothFamilyCorrectionTransport +OAI.Analysis.Conductivity.Branching.TorusEndingCorrection +OAI.Analysis.Conductivity.Branching.VariableBlockEnergy +OAI.Analysis.Conductivity.Flux.AEFluxWeak +OAI.Analysis.Conductivity.Flux.AntisymmetricFlux +OAI.Analysis.Conductivity.Flux.AssembleCompatibleTensors +OAI.Analysis.Conductivity.Flux.AttachedEndDifferential +OAI.Analysis.Conductivity.Flux.AttachedFlatTensor +OAI.Analysis.Conductivity.Flux.AttachedPhysicalSmoothGreen +OAI.Analysis.Conductivity.Flux.AttachedSplicedGreen +OAI.Analysis.Conductivity.Flux.AxialFluxBlend +OAI.Analysis.Conductivity.Flux.BranchTerminalFluxIntegral +OAI.Analysis.Conductivity.Flux.C1WeakDivergence +OAI.Analysis.Conductivity.Flux.CascadeFluxLocal +OAI.Analysis.Conductivity.Flux.CascadeStageCurl +OAI.Analysis.Conductivity.Flux.CascadeTensorBounds +OAI.Analysis.Conductivity.Flux.CascadeTensorLocality +OAI.Analysis.Conductivity.Flux.CentralCylinderGreen +OAI.Analysis.Conductivity.Flux.CentralDistribution +OAI.Analysis.Conductivity.Flux.CentralDistributionLaplacian +OAI.Analysis.Conductivity.Flux.ChartTwoFluxLocalized +OAI.Analysis.Conductivity.Flux.CollarCartesianDifferential +OAI.Analysis.Conductivity.Flux.CompactBoxDivergence +OAI.Analysis.Conductivity.Flux.CompactBoxDivergenceC1 +OAI.Analysis.Conductivity.Flux.CompactFluxDivergence +OAI.Analysis.Conductivity.Flux.CompactInteriorDivergence +OAI.Analysis.Conductivity.Flux.CubeWeakDivergence +OAI.Analysis.Conductivity.Flux.CylinderCompletedGreen +OAI.Analysis.Conductivity.Flux.CylinderGreen +OAI.Analysis.Conductivity.Flux.CylinderSeriesGreen +OAI.Analysis.Conductivity.Flux.CylinderSlopeGreen +OAI.Analysis.Conductivity.Flux.DelayedPairFlux +OAI.Analysis.Conductivity.Flux.FiberDivergenceBounds +OAI.Analysis.Conductivity.Flux.FiberDivergenceC1 +OAI.Analysis.Conductivity.Flux.FiniteEndPhysicalSmoothTensor +OAI.Analysis.Conductivity.Flux.FiniteEndPhysicalTensor +OAI.Analysis.Conductivity.Flux.FlatBackgroundTensor +OAI.Analysis.Conductivity.Flux.FluxPotentialSymbol +OAI.Analysis.Conductivity.Flux.LinearFluxWeakTransport +OAI.Analysis.Conductivity.Flux.LinearTensorEllipticity +OAI.Analysis.Conductivity.Flux.LocalTensorBounds +OAI.Analysis.Conductivity.Flux.LocalizedTwoFlux +OAI.Analysis.Conductivity.Flux.OpenRegularTensorTarget +OAI.Analysis.Conductivity.Flux.PhysicalAttachedGreen +OAI.Analysis.Conductivity.Flux.PhysicalBlockTensor +OAI.Analysis.Conductivity.Flux.PhysicalChildTensor +OAI.Analysis.Conductivity.Flux.PhysicalEndDifferential +OAI.Analysis.Conductivity.Flux.PhysicalEndSmoothGreen +OAI.Analysis.Conductivity.Flux.PhysicalSplicedGreen +OAI.Analysis.Conductivity.Flux.PhysicalTensorBound +OAI.Analysis.Conductivity.Flux.PhysicalTensorPatch +OAI.Analysis.Conductivity.Flux.PhysicalVoltageFlux +OAI.Analysis.Conductivity.Flux.PiolaFluxAdd +OAI.Analysis.Conductivity.Flux.PiolaFluxContDiff +OAI.Analysis.Conductivity.Flux.PotentialCurl +OAI.Analysis.Conductivity.Flux.SmoothFluxIntegrable +OAI.Analysis.Conductivity.Flux.TorusBoxFlux +OAI.Analysis.Conductivity.Flux.TorusCrossFluxDecay +OAI.Analysis.Conductivity.Flux.TorusCylinderGreenComplex +OAI.Analysis.Conductivity.Flux.TorusCylinderGreenReal +OAI.Analysis.Conductivity.Flux.TorusFluxDecay +OAI.Analysis.Conductivity.Flux.TwoFluxColumns +OAI.Analysis.Conductivity.Flux.TwoFluxDivergence +OAI.Analysis.Conductivity.Flux.VariableBlockTensor +OAI.Analysis.Conductivity.Flux.VariableCollarTensor +OAI.Analysis.Conductivity.Flux.VoltageFluxConstraints +OAI.Analysis.Conductivity.Flux.WeakFluxClassicalC1 +OAI.Analysis.Conductivity.Fourier.AffineFourierField +OAI.Analysis.Conductivity.Fourier.AnalyticDerivativeBounds +OAI.Analysis.Conductivity.Fourier.AnalyticNull +OAI.Analysis.Conductivity.Fourier.AnalyticNullEuclidean +OAI.Analysis.Conductivity.Fourier.AngularFourierConjugacy +OAI.Analysis.Conductivity.Fourier.AngularIntegratedTrace +OAI.Analysis.Conductivity.Fourier.AngularIntegration +OAI.Analysis.Conductivity.Fourier.AngularInverseTensor +OAI.Analysis.Conductivity.Fourier.AngularLocalizedMoments +OAI.Analysis.Conductivity.Fourier.AngularMeasureExact +OAI.Analysis.Conductivity.Fourier.AngularNormalTrace +OAI.Analysis.Conductivity.Fourier.AngularPeriodization +OAI.Analysis.Conductivity.Fourier.AngularPhaseTranslation +OAI.Analysis.Conductivity.Fourier.AngularSignedTrace +OAI.Analysis.Conductivity.Fourier.AttachedEndPoisson +OAI.Analysis.Conductivity.Fourier.AttachedPeriodicDerivative +OAI.Analysis.Conductivity.Fourier.AttachedPeriodicFlux +OAI.Analysis.Conductivity.Fourier.AttachedPeriodicGreen +OAI.Analysis.Conductivity.Fourier.CascadePeriodicity +OAI.Analysis.Conductivity.Fourier.CollarAngularInverse +OAI.Analysis.Conductivity.Fourier.CompactifiedFourierTail +OAI.Analysis.Conductivity.Fourier.CylinderFourier +OAI.Analysis.Conductivity.Fourier.CylinderFourierComplete +OAI.Analysis.Conductivity.Fourier.CylinderFourierGraph +OAI.Analysis.Conductivity.Fourier.CylinderModeGreen +OAI.Analysis.Conductivity.Fourier.CylinderPoissonTrace +OAI.Analysis.Conductivity.Fourier.EndPoissonDifferential +OAI.Analysis.Conductivity.Fourier.EndPoissonJets +OAI.Analysis.Conductivity.Fourier.EndPoissonRepresentative +OAI.Analysis.Conductivity.Fourier.EndingJoinMiddleModel +OAI.Analysis.Conductivity.Fourier.EndingJoinPeriodicity +OAI.Analysis.Conductivity.Fourier.FlatFourierFlux +OAI.Analysis.Conductivity.Fourier.FourierEndConcomitant +OAI.Analysis.Conductivity.Fourier.FourierEndFlux +OAI.Analysis.Conductivity.Fourier.FourierFiniteEnding +OAI.Analysis.Conductivity.Fourier.FourierFiniteEndingNormal +OAI.Analysis.Conductivity.Fourier.FourierMatchingElliptic +OAI.Analysis.Conductivity.Fourier.FourierMatchingFamilyCorrection +OAI.Analysis.Conductivity.Fourier.FourierMatchingInterpolation +OAI.Analysis.Conductivity.Fourier.FourierMatchingLocalData +OAI.Analysis.Conductivity.Fourier.FourierPairFlux +OAI.Analysis.Conductivity.Fourier.GeneralModeFiniteEndNormal +OAI.Analysis.Conductivity.Fourier.GeneralModeRecombinedEnding +OAI.Analysis.Conductivity.Fourier.LeadingFrequencyAlignment +OAI.Analysis.Conductivity.Fourier.LinearPhaseDerivativeIntegralBound +OAI.Analysis.Conductivity.Fourier.ModeConnector +OAI.Analysis.Conductivity.Fourier.PeriodicAveragingSmooth +OAI.Analysis.Conductivity.Fourier.PeriodicBandCompactness +OAI.Analysis.Conductivity.Fourier.PeriodicFamilyCorrection +OAI.Analysis.Conductivity.Fourier.PoissonGreen +OAI.Analysis.Conductivity.Fourier.PoissonTraceRate +OAI.Analysis.Conductivity.Fourier.PureMode +OAI.Analysis.Conductivity.Fourier.PureModeFamilyLocalCorrection +OAI.Analysis.Conductivity.Fourier.PureModeWall +OAI.Analysis.Conductivity.Fourier.PureModeWallRegion +OAI.Analysis.Conductivity.Fourier.RectangularRayTrace +OAI.Analysis.Conductivity.Fourier.RectangularTorusAtlas +OAI.Analysis.Conductivity.Fourier.RectangularTorusInverse +OAI.Analysis.Conductivity.Fourier.SmoothAngularCutoff +OAI.Analysis.Conductivity.Fourier.SmoothHarmonicAnalytic +OAI.Analysis.Conductivity.Fourier.SmoothPhase +OAI.Analysis.Conductivity.Fourier.SpectralAffineCovector +OAI.Analysis.Conductivity.Fourier.SpectralExtensionMono +OAI.Analysis.Conductivity.Fourier.SpectralExtensionNonemptyNonempty +OAI.Analysis.Conductivity.Fourier.SpectralTerminalIntegral +OAI.Analysis.Conductivity.Fourier.SpectralTerminalL2 +OAI.Analysis.Conductivity.Fourier.SpectralTrace +OAI.Analysis.Conductivity.Fourier.TorusDirectionalFourier +OAI.Analysis.Conductivity.Fourier.TorusFlatMode +OAI.Analysis.Conductivity.Fourier.TorusFourierAnalytic +OAI.Analysis.Conductivity.Fourier.TorusFourierSmooth +OAI.Analysis.Conductivity.Fourier.TorusFourierTranslation +OAI.Analysis.Conductivity.Fourier.TorusLeadingRealMode +OAI.Analysis.Conductivity.Fourier.TorusNonresonance +OAI.Analysis.Conductivity.Fourier.TorusPeriodicDescent +OAI.Analysis.Conductivity.Fourier.TorusPoissonContinuous +OAI.Analysis.Conductivity.Fourier.TorusPoissonFlow +OAI.Analysis.Conductivity.Fourier.TorusSmoothModeJet +OAI.Analysis.Conductivity.Fourier.TorusSpectralContinuation +OAI.Analysis.Conductivity.Fourier.UndoAngularProperties +OAI.Analysis.Conductivity.Fourier.UndoAngularWeakPair +OAI.Analysis.Conductivity.Geometry.AffineBoxPoincare +OAI.Analysis.Conductivity.Geometry.AffineCylinder +OAI.Analysis.Conductivity.Geometry.AffineCylinderIntegral +OAI.Analysis.Conductivity.Geometry.BoxCoordinateBridge +OAI.Analysis.Conductivity.Geometry.BoxEnergyPoincare +OAI.Analysis.Conductivity.Geometry.BoxIteration +OAI.Analysis.Conductivity.Geometry.BoxMomentRightInverse +OAI.Analysis.Conductivity.Geometry.CentralSlopeJet +OAI.Analysis.Conductivity.Geometry.CollarAE +OAI.Analysis.Conductivity.Geometry.CollarInteriorFacts +OAI.Analysis.Conductivity.Geometry.CollarLip +OAI.Analysis.Conductivity.Geometry.CollarLocalInverse +OAI.Analysis.Conductivity.Geometry.CollarReverseBound +OAI.Analysis.Conductivity.Geometry.CollarVolumeBound +OAI.Analysis.Conductivity.Geometry.CompactRegularBoxCorrection +OAI.Analysis.Conductivity.Geometry.CompactSplitSubpatch +OAI.Analysis.Conductivity.Geometry.ControlledCorrectionBoxes +OAI.Analysis.Conductivity.Geometry.CoordinateCorrectionC0 +OAI.Analysis.Conductivity.Geometry.CoordinateWeakCorrection +OAI.Analysis.Conductivity.Geometry.CutSlopeGradient +OAI.Analysis.Conductivity.Geometry.CylinderJetOrthogonal +OAI.Analysis.Conductivity.Geometry.CylinderPhysicalEquiv +OAI.Analysis.Conductivity.Geometry.CylinderPointEnergy +OAI.Analysis.Conductivity.Geometry.CylinderPolynomial +OAI.Analysis.Conductivity.Geometry.ExtendedCollar +OAI.Analysis.Conductivity.Geometry.FlatTorusPDE +OAI.Analysis.Conductivity.Geometry.InverseChartPiolaOperator +OAI.Analysis.Conductivity.Geometry.LocalFamilyRegionCoordinates +OAI.Analysis.Conductivity.Geometry.LocalSplitSubpatchRetained +OAI.Analysis.Conductivity.Geometry.MatrixPerturbInverse +OAI.Analysis.Conductivity.Geometry.ParametricCorrectionRegionPiola +OAI.Analysis.Conductivity.Geometry.ParametricPotentialCoordinates +OAI.Analysis.Conductivity.Geometry.PhysicalBoxCorrection +OAI.Analysis.Conductivity.Geometry.PhysicalCollarBand +OAI.Analysis.Conductivity.Geometry.PhysicalCollarRegularity +OAI.Analysis.Conductivity.Geometry.PhysicalCollarTrace +OAI.Analysis.Conductivity.Geometry.PhysicalEndRegions +OAI.Analysis.Conductivity.Geometry.PhysicalRegionGluing +OAI.Analysis.Conductivity.Geometry.RectanglePoincare +OAI.Analysis.Conductivity.Geometry.RegularPatch +OAI.Analysis.Conductivity.Geometry.RegularPatchCoordinates +OAI.Analysis.Conductivity.Geometry.RegularPatchLinear +OAI.Analysis.Conductivity.Geometry.RegularPatchTranslation +OAI.Analysis.Conductivity.Geometry.RegularPotentialCoordinates +OAI.Analysis.Conductivity.Geometry.RegularRegionCongrSubset +OAI.Analysis.Conductivity.Geometry.RegularRegionFiniteGluing +OAI.Analysis.Conductivity.Geometry.SmoothCollarRate +OAI.Analysis.Conductivity.Geometry.SmoothCollarTrace +OAI.Analysis.Conductivity.Geometry.SplitJacobian +OAI.Analysis.Conductivity.Geometry.TorusAffineField +OAI.Analysis.Conductivity.Geometry.TorusDirectionalDerivative +OAI.Analysis.Conductivity.Geometry.TorusExponential +OAI.Analysis.Conductivity.Geometry.TorusFaceIntegration +OAI.Analysis.Conductivity.Geometry.TorusIntegralAlgebra +OAI.Analysis.Conductivity.Geometry.TorusLeadingDecay +OAI.Analysis.Conductivity.Geometry.TorusLeadingDecomposition +OAI.Analysis.Conductivity.Geometry.TorusLipschitzTrace +OAI.Analysis.Conductivity.Geometry.TorusLocalizedMoments +OAI.Analysis.Conductivity.Geometry.TorusTraceFiniteEnd +OAI.Analysis.Conductivity.Geometry.UniformPhysicalBoxCorrection +OAI.Analysis.Conductivity.Geometry.UnitBoxAverage +OAI.Analysis.Conductivity.Main +OAI.Analysis.Conductivity.Model +OAI.Analysis.Conductivity.Scalarization.ApproxScalar +OAI.Analysis.Conductivity.Scalarization.AttachedSplicedConstitution +OAI.Analysis.Conductivity.Scalarization.CascadeConnectorConstitution +OAI.Analysis.Conductivity.Scalarization.CascadeConstitution +OAI.Analysis.Conductivity.Scalarization.ConcreteFluxH1Scalarization +OAI.Analysis.Conductivity.Scalarization.ConcreteFluxScalarization +OAI.Analysis.Conductivity.Scalarization.DefectMeasure +OAI.Analysis.Conductivity.Scalarization.DenseClosureApprox +OAI.Analysis.Conductivity.Scalarization.EndingJoinConstitution +OAI.Analysis.Conductivity.Scalarization.FineScalarSequence +OAI.Analysis.Conductivity.Scalarization.GeneralModeEndingScalarization +OAI.Analysis.Conductivity.Scalarization.LocalConstitution +OAI.Analysis.Conductivity.Scalarization.OriginalScalarizationCauchy +OAI.Analysis.Conductivity.Scalarization.PhysicalScalarization +OAI.Analysis.Conductivity.Scalarization.ScalarRelationLpStrongClosed +OAI.Analysis.Conductivity.Scalarization.ScalarRelationStrongClosed +OAI.Analysis.Conductivity.Scalarization.ScalarizationAffineLimit +OAI.Analysis.Conductivity.Scalarization.SmoothScalarAlgebra +OAI.Analysis.Conductivity.Scalarization.UniformMatrixScalarization +OAI.Analysis.Conductivity.Scalarization.UpdateFieldPair +OAI.Analysis.Conductivity.Scalarization.WeakCellFast +OAI.Analysis.Conductivity.Scalarization.WeakDensityLp +OAI.Analysis.Conductivity.Sobolev.AttachedEndMatchedH1 +OAI.Analysis.Conductivity.Sobolev.AxialExtension +OAI.Analysis.Conductivity.Sobolev.AxialPairRank +OAI.Analysis.Conductivity.Sobolev.BoundedMultiplier +OAI.Analysis.Conductivity.Sobolev.CentralNeighborhoodCompletion +OAI.Analysis.Conductivity.Sobolev.CentralPairRegularity +OAI.Analysis.Conductivity.Sobolev.CentralPhysicalEnergy +OAI.Analysis.Conductivity.Sobolev.CentralPhysicalRegion +OAI.Analysis.Conductivity.Sobolev.CentralPhysicalTrace +OAI.Analysis.Conductivity.Sobolev.CentralPhysicalVariational +OAI.Analysis.Conductivity.Sobolev.CentralPieceRegular +OAI.Analysis.Conductivity.Sobolev.CentralPoincare +OAI.Analysis.Conductivity.Sobolev.ChildCompletionJoin +OAI.Analysis.Conductivity.Sobolev.ChildFullEndH1 +OAI.Analysis.Conductivity.Sobolev.ChildH10Transport +OAI.Analysis.Conductivity.Sobolev.ChildH1Pullback +OAI.Analysis.Conductivity.Sobolev.CollarLpPullback +OAI.Analysis.Conductivity.Sobolev.CompactLipschitzH1 +OAI.Analysis.Conductivity.Sobolev.CompactUpdateLp +OAI.Analysis.Conductivity.Sobolev.CriticalWallParticularC0 +OAI.Analysis.Conductivity.Sobolev.CutAttachedEndH1 +OAI.Analysis.Conductivity.Sobolev.CutSlopeH1 +OAI.Analysis.Conductivity.Sobolev.CylinderPoissonH1 +OAI.Analysis.Conductivity.Sobolev.CylinderSobolevGraph +OAI.Analysis.Conductivity.Sobolev.FiniteEndPhysicalH1 +OAI.Analysis.Conductivity.Sobolev.IntervalTraceEnergy +OAI.Analysis.Conductivity.Sobolev.KernelParamDerivative +OAI.Analysis.Conductivity.Sobolev.L2SpectralMultiplier +OAI.Analysis.Conductivity.Sobolev.LocalJoinedH1 +OAI.Analysis.Conductivity.Sobolev.LocalPhysicalCorrectionBound +OAI.Analysis.Conductivity.Sobolev.LocalPiolaFlux +OAI.Analysis.Conductivity.Sobolev.LocalPiolaFluxPotentialPairing +OAI.Analysis.Conductivity.Sobolev.LocalPiolaFluxSub +OAI.Analysis.Conductivity.Sobolev.LocalPullback +OAI.Analysis.Conductivity.Sobolev.LocalPullbackTsupportInside +OAI.Analysis.Conductivity.Sobolev.LpEllipticBounds +OAI.Analysis.Conductivity.Sobolev.LpExtension +OAI.Analysis.Conductivity.Sobolev.LpFourJet +OAI.Analysis.Conductivity.Sobolev.MatchedSeamH1 +OAI.Analysis.Conductivity.Sobolev.NonlinearLp +OAI.Analysis.Conductivity.Sobolev.OriginalH1VoltageRestriction +OAI.Analysis.Conductivity.Sobolev.OriginalMultiplierOperator +OAI.Analysis.Conductivity.Sobolev.OriginalPairVoltage +OAI.Analysis.Conductivity.Sobolev.OriginalSmoothMultiplier +OAI.Analysis.Conductivity.Sobolev.ParentCompletionJoin +OAI.Analysis.Conductivity.Sobolev.ParentFullEndH1 +OAI.Analysis.Conductivity.Sobolev.PhysicalProductJet +OAI.Analysis.Conductivity.Sobolev.SobolevChain +OAI.Analysis.Conductivity.Sobolev.SobolevDistribution +OAI.Analysis.Conductivity.Sobolev.SobolevGaugeTransform +OAI.Analysis.Conductivity.Sobolev.SobolevMaximum +OAI.Analysis.Conductivity.Sobolev.SobolevOuterTests +OAI.Analysis.Conductivity.Sobolev.SobolevSmoothOperations +OAI.Analysis.Conductivity.Sobolev.SobolevSmoothTests +OAI.Analysis.Conductivity.Sobolev.SobolevTraceChain +OAI.Analysis.Conductivity.Sobolev.UniformLocalPhysicalCorrection +OAI.Analysis.Conductivity.Sobolev.VoltageH1Completion +OAI.Analysis.Conductivity.Sobolev.VoltageJetCompletion +OAI.Analysis.Conductivity.Sobolev.VoltageOriginalH10 +OAI.Analysis.Conductivity.Sobolev.WallParticular +OAI.Analysis.Conductivity.Sobolev.WallParticularBounds +OAI.Analysis.Conductivity.Sobolev.WallParticularFamily +OAI.Analysis.Conductivity.Sobolev.WallParticularFinish +OAI.Analysis.Conductivity.Sobolev.WallPrimitive +OAI.Analysis.Conductivity.Sobolev.WeakCompactHilbert +OAI.Analysis.Conductivity.Sobolev.WeylPairGluing +OAI.Analysis.Conductivity.Sources.AngularCoefficient +OAI.Analysis.Conductivity.Sources.AngularGraph +OAI.Analysis.Conductivity.Sources.AngularJet +OAI.Analysis.Conductivity.Sources.AngularLocalizedSources +OAI.Analysis.Conductivity.Sources.AngularPhysicalTest +OAI.Analysis.Conductivity.Sources.AngularTrace +OAI.Analysis.Conductivity.Sources.BranchCombine +OAI.Analysis.Conductivity.Sources.CentralWeightedVariational +OAI.Analysis.Conductivity.Sources.CopiedEnergyAlgebra +OAI.Analysis.Conductivity.Sources.CopiedScalarCoefficient +OAI.Analysis.Conductivity.Sources.CriticalWallGap +OAI.Analysis.Conductivity.Sources.EndPointEnergy +OAI.Analysis.Conductivity.Sources.FaceIntegral +OAI.Analysis.Conductivity.Sources.FaceMeasure +OAI.Analysis.Conductivity.Sources.FacePasting +OAI.Analysis.Conductivity.Sources.FluxCylinder +OAI.Analysis.Conductivity.Sources.IteratedAverages +OAI.Analysis.Conductivity.Sources.LocalPhysicalCorrection +OAI.Analysis.Conductivity.Sources.LocalPiola +OAI.Analysis.Conductivity.Sources.LocalRegular +OAI.Analysis.Conductivity.Sources.NestedGeometry +OAI.Analysis.Conductivity.Sources.NestedLimits +OAI.Analysis.Conductivity.Sources.NestedWeightedLimit +OAI.Analysis.Conductivity.Sources.NonzeroJacobianAE +OAI.Analysis.Conductivity.Sources.ParametricPullback +OAI.Analysis.Conductivity.Sources.ParametricSymmetricSources +OAI.Analysis.Conductivity.Sources.PhysicalBlockDomain +OAI.Analysis.Conductivity.Sources.PhysicalC1Pullback +OAI.Analysis.Conductivity.Sources.PhysicalGradient +OAI.Analysis.Conductivity.Sources.PhysicalMaximum +OAI.Analysis.Conductivity.Sources.PhysicalPatching +OAI.Analysis.Conductivity.Sources.PhysicalRoot +OAI.Analysis.Conductivity.Sources.PhysicalTrace +OAI.Analysis.Conductivity.Sources.SymmetricCutoffSources +OAI.Analysis.Conductivity.Sources.TorusMoments +OAI.Analysis.Conductivity.Sources.WeightedGaugeDN +OAI.Analysis.Conductivity.Sources.WeightedSpectralSpace +OAI.Analysis.Conductivity.Sources.WordGeometry +OAI.Analysis.Conductivity.Sources.WordTrace +OAI.Analysis.Conductivity.Variational.AdaptedSpatialBasis +OAI.Analysis.Conductivity.Variational.AffineLayer +OAI.Analysis.Conductivity.Variational.AffineWeakConstraints +OAI.Analysis.Conductivity.Variational.AirySymbol +OAI.Analysis.Conductivity.Variational.AxialDecayL2 +OAI.Analysis.Conductivity.Variational.AxialLocalRegularity +OAI.Analysis.Conductivity.Variational.BoundedPiolaCorrection +OAI.Analysis.Conductivity.Variational.C1VoltageApproximation +OAI.Analysis.Conductivity.Variational.CentralAnchor +OAI.Analysis.Conductivity.Variational.CentralCoercivitySmooth +OAI.Analysis.Conductivity.Variational.CentralCorrectedRepresentative +OAI.Analysis.Conductivity.Variational.CentralEnergySpace +OAI.Analysis.Conductivity.Variational.CentralEuclideanBridge +OAI.Analysis.Conductivity.Variational.CentralEuclideanJets +OAI.Analysis.Conductivity.Variational.CentralHarmonicOpen +OAI.Analysis.Conductivity.Variational.CentralJetIdentity +OAI.Analysis.Conductivity.Variational.CentralLocalAgreement +OAI.Analysis.Conductivity.Variational.CentralSmoothTrace +OAI.Analysis.Conductivity.Variational.CentralUnnormalizedVariational +OAI.Analysis.Conductivity.Variational.CentralVariational +OAI.Analysis.Conductivity.Variational.ChangeOld +OAI.Analysis.Conductivity.Variational.CompactBridge +OAI.Analysis.Conductivity.Variational.CompactCompatibleReplacement +OAI.Analysis.Conductivity.Variational.CompactDepthReductionRegular +OAI.Analysis.Conductivity.Variational.CompactDepthReductionTwo +OAI.Analysis.Conductivity.Variational.CompactFiberDecomposition +OAI.Analysis.Conductivity.Variational.CompactFiberPrimitive +OAI.Analysis.Conductivity.Variational.CompactGlobalUpdate +OAI.Analysis.Conductivity.Variational.CompactMomentPerturbation +OAI.Analysis.Conductivity.Variational.CompactParametricBounds +OAI.Analysis.Conductivity.Variational.CompactParametricIntegral +OAI.Analysis.Conductivity.Variational.CompactPhysicalCorrections +OAI.Analysis.Conductivity.Variational.CompactRegularC0 +OAI.Analysis.Conductivity.Variational.CompactRegularCorrection +OAI.Analysis.Conductivity.Variational.CompactSelectedReplacement +OAI.Analysis.Conductivity.Variational.CompactSymmetricMoments +OAI.Analysis.Conductivity.Variational.CompletePhysicalAttachment +OAI.Analysis.Conductivity.Variational.CompletedPotential +OAI.Analysis.Conductivity.Variational.ConjugateDiagonal +OAI.Analysis.Conductivity.Variational.ContDiffClmDet +OAI.Analysis.Conductivity.Variational.CrossingEllipticity +OAI.Analysis.Conductivity.Variational.CrossingEstimates +OAI.Analysis.Conductivity.Variational.CrossingGradient +OAI.Analysis.Conductivity.Variational.CrossingHxx +OAI.Analysis.Conductivity.Variational.CrossingProfiles +OAI.Analysis.Conductivity.Variational.DenseWeakStrongContinuityPoints +OAI.Analysis.Conductivity.Variational.DerivativeEquiv +OAI.Analysis.Conductivity.Variational.DetIdAddRank +OAI.Analysis.Conductivity.Variational.DirectionCalculus +OAI.Analysis.Conductivity.Variational.DivSymbolTwo +OAI.Analysis.Conductivity.Variational.EndPartitionJet +OAI.Analysis.Conductivity.Variational.FiberTangentialDerivative +OAI.Analysis.Conductivity.Variational.FieldMean +OAI.Analysis.Conductivity.Variational.FieldVector +OAI.Analysis.Conductivity.Variational.FieldVectorCLM +OAI.Analysis.Conductivity.Variational.FiniteEndPhysicalDescent +OAI.Analysis.Conductivity.Variational.FiniteEndPhysicalRegularity +OAI.Analysis.Conductivity.Variational.FiniteMomentTransfer +OAI.Analysis.Conductivity.Variational.FlatSpliceRegularity +OAI.Analysis.Conductivity.Variational.FullEndClosedEnergy +OAI.Analysis.Conductivity.Variational.FullWeakEndEnergy +OAI.Analysis.Conductivity.Variational.GlobalRegularCorrection +OAI.Analysis.Conductivity.Variational.GradientColumns +OAI.Analysis.Conductivity.Variational.GramRankDetNe +OAI.Analysis.Conductivity.Variational.HarmonicRankAffine +OAI.Analysis.Conductivity.Variational.IntervalMeanPoincare +OAI.Analysis.Conductivity.Variational.L2TranslationAverage +OAI.Analysis.Conductivity.Variational.LocalBoundedPiolaCorrection +OAI.Analysis.Conductivity.Variational.LocalSmoothSeries +OAI.Analysis.Conductivity.Variational.LocalSmoothWeakDerivative +OAI.Analysis.Conductivity.Variational.LocalSymmetricPiola +OAI.Analysis.Conductivity.Variational.LocalizedFirstPotential +OAI.Analysis.Conductivity.Variational.MatrixCompact +OAI.Analysis.Conductivity.Variational.MatrixFiniteLaminate +OAI.Analysis.Conductivity.Variational.MatrixOperator +OAI.Analysis.Conductivity.Variational.MetricControlledPiola +OAI.Analysis.Conductivity.Variational.NormalStretch +OAI.Analysis.Conductivity.Variational.OriginalGradientLocality +OAI.Analysis.Conductivity.Variational.OriginalVoltageRestriction +OAI.Analysis.Conductivity.Variational.OverlapPoincare +OAI.Analysis.Conductivity.Variational.PairedPotential +OAI.Analysis.Conductivity.Variational.ParametricAxialNormalization +OAI.Analysis.Conductivity.Variational.ParametricDiffeomorph +OAI.Analysis.Conductivity.Variational.ParametricGlobalCorrection +OAI.Analysis.Conductivity.Variational.ParametricLocalRegularCorrection +OAI.Analysis.Conductivity.Variational.ParametricMomentSmall +OAI.Analysis.Conductivity.Variational.ParametricSpatialDerivative +OAI.Analysis.Conductivity.Variational.PhysicalCentralRegularPair +OAI.Analysis.Conductivity.Variational.PhysicalCorrectionC0 +OAI.Analysis.Conductivity.Variational.PhysicalEndLocalLipschitz +OAI.Analysis.Conductivity.Variational.PhysicalEndOpen +OAI.Analysis.Conductivity.Variational.PhysicalEndSmoothEnergy +OAI.Analysis.Conductivity.Variational.PhysicalEnergyContinuous +OAI.Analysis.Conductivity.Variational.PhysicalFaceSum +OAI.Analysis.Conductivity.Variational.PhysicalFaceUniqueness +OAI.Analysis.Conductivity.Variational.PhysicalFlatEllipticity +OAI.Analysis.Conductivity.Variational.PhysicalOpenVoltage +OAI.Analysis.Conductivity.Variational.PhysicalOuterTrace +OAI.Analysis.Conductivity.Variational.PhysicalOverlapMoments +OAI.Analysis.Conductivity.Variational.PhysicalRealTrace +OAI.Analysis.Conductivity.Variational.PhysicalRepresentativeGluing +OAI.Analysis.Conductivity.Variational.PhysicalSmoothTest +OAI.Analysis.Conductivity.Variational.PhysicalStripIntegral +OAI.Analysis.Conductivity.Variational.PhysicalTerminalBands +OAI.Analysis.Conductivity.Variational.PhysicalTestEnergy +OAI.Analysis.Conductivity.Variational.PhysicalTraceBounds +OAI.Analysis.Conductivity.Variational.PhysicalTraceMean +OAI.Analysis.Conductivity.Variational.PreliminaryQ +OAI.Analysis.Conductivity.Variational.ProductFactorSpec +OAI.Analysis.Conductivity.Variational.QuantitativeGlobalCorrection +OAI.Analysis.Conductivity.Variational.QuantitativeLocalTwoFieldSplit +OAI.Analysis.Conductivity.Variational.QuantitativePhysicalMoments +OAI.Analysis.Conductivity.Variational.RadialLaplacian +OAI.Analysis.Conductivity.Variational.RadialWeylScale +OAI.Analysis.Conductivity.Variational.RankProjectionFirst +OAI.Analysis.Conductivity.Variational.Refl +OAI.Analysis.Conductivity.Variational.RegularVanishingFamily +OAI.Analysis.Conductivity.Variational.RepairPushedGraphStability +OAI.Analysis.Conductivity.Variational.ScaledSmoothSeries +OAI.Analysis.Conductivity.Variational.SimpleLevelNull +OAI.Analysis.Conductivity.Variational.SmoothCompactExtension +OAI.Analysis.Conductivity.Variational.SmoothCompactParameter +OAI.Analysis.Conductivity.Variational.SmoothCompose +OAI.Analysis.Conductivity.Variational.SmoothDirectionIntegral +OAI.Analysis.Conductivity.Variational.SmoothFamilyGlobalCorrection +OAI.Analysis.Conductivity.Variational.SmoothNormalizedEndFamily +OAI.Analysis.Conductivity.Variational.SmoothPhysicalMomentFamily +OAI.Analysis.Conductivity.Variational.SmoothPrimitive +OAI.Analysis.Conductivity.Variational.SmoothRankRegularity +OAI.Analysis.Conductivity.Variational.SmoothRepresentativeGluing +OAI.Analysis.Conductivity.Variational.SmoothSupportedAdd +OAI.Analysis.Conductivity.Variational.SymmetricCorrection +OAI.Analysis.Conductivity.Variational.SymmetricQuadraticBound +OAI.Analysis.Conductivity.Variational.Symmetrize +OAI.Analysis.Conductivity.Variational.SynchronizedChartWaves +OAI.Analysis.Conductivity.Variational.TransitionMajorant +OAI.Analysis.Conductivity.Variational.TsupportFiniteSumSubset +OAI.Analysis.Conductivity.Variational.Unchanged +OAI.Analysis.Conductivity.Variational.UniformC1Bounds +OAI.Analysis.Conductivity.Variational.UniformNormBound +OAI.Analysis.Conductivity.Variational.UnitSquarePoincare +OAI.Analysis.Conductivity.Variational.VanishingMomentChoice +OAI.Analysis.Conductivity.Variational.VariationalDN +OAI.Analysis.Conductivity.Variational.VoltageBoundaryTrace +OAI.Analysis.Conductivity.Variational.VoltagePoincare +OAI.Analysis.Conductivity.Variational.VoltageRecombination +OAI.Analysis.Conductivity.Variational.WeakHarmonicClassical +OAI.Analysis.Conductivity.Variational.WeakHarmonicMean +OAI.Analysis.Conductivity.Variational.WeakPairOverlap +OAI.Analysis.Conductivity.Variational.WeakWeyl +OAI.Analysis.Conductivity.Variational.WholeBallJet +OAI.Analysis.Conductivity.Variational.WholeBallJetFormula +OAI.Analysis.Conductivity.Variational.WholeWeakClosure +OAI.Analysis.Conductivity.Walls.CentralSeamCutoff +OAI.Analysis.Conductivity.Walls.ChildSeamCutoff +OAI.Analysis.Conductivity.Walls.CriticalWall +OAI.Analysis.Conductivity.Walls.CriticalWallBounds +OAI.Analysis.Conductivity.Walls.CriticalWallFamilyCorrection +OAI.Analysis.Conductivity.Walls.CriticalWallHomogeneous +OAI.Analysis.Conductivity.Walls.CriticalWallRegion +OAI.Analysis.Conductivity.Walls.CriticalWallResidual +OAI.Analysis.Conductivity.Walls.CriticalWallTensor +OAI.Analysis.Conductivity.Walls.EndingJoinCutoff +OAI.Analysis.Conductivity.Walls.FlattenedWall +OAI.Analysis.Conductivity.Walls.HadamardWall +OAI.Analysis.Conductivity.Walls.LocalizedMatchedSeam +OAI.Analysis.Conductivity.Walls.ParametricWallAmplitude +OAI.Analysis.Conductivity.Walls.ParametricWallOperators +OAI.Analysis.Conductivity.Walls.ParametricWallTensors +OAI.Analysis.Conductivity.Walls.PhysicalCollarCutoff +OAI.Analysis.Conductivity.Walls.PhysicalTerminalCutoff +OAI.Analysis.Conductivity.Walls.RecenteredWallField +OAI.Analysis.Conductivity.Walls.SeamCubicRate +OAI.Analysis.Conductivity.Walls.SeamCutoff +OAI.Analysis.Conductivity.Walls.SeamL2 +OAI.Analysis.Conductivity.Walls.SimpleCriticalWallCoordinates +OAI.Analysis.Conductivity.Walls.SimpleCriticalWallRegion +OAI.Analysis.Conductivity.Walls.SimpleWallGraph +OAI.Analysis.Conductivity.Walls.SmoothCutoffSmallMargin +OAI.Analysis.Conductivity.Walls.WallHalfspaceIntegral +OAI.Analysis.Conductivity.Walls.WallHomogeneous +OAI.Analysis.Conductivity.Walls.WallMomentAmplitudeBounds +OAI.Analysis.Conductivity.Walls.WallMomentIndependence +OAI.Analysis.Conductivity.Walls.WallSideMoments +OAI.Analysis.Conductivity.Walls.WallSurfaceMomentInverse +OAI.Analysis.Conductivity.Walls.WallTransferParametric +OAI.Analysis.Conductivity.Walls.WallVanishingMomentCoefficients diff --git a/tasks/conductivity/solution/reference.py b/tasks/conductivity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/conductivity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/conductivity/solution/solve.sh b/tasks/conductivity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e24adcbe0651b9a440a0823a1c7aaf2df398b7f --- /dev/null +++ b/tasks/conductivity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Conductivity, i.e. module OAI.Analysis.Conductivity.Main and the +# 595 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Conductivity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Conductivity" diff --git a/tasks/conductivity/task.toml b/tasks/conductivity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0d64b55e9f6738e58eaea5a376151ac9396b30ca --- /dev/null +++ b/tasks/conductivity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/conductivity" +version = "1.0.0" +description = "Prove Conductivity (openai/math family 365: Joint metric and connection recovery from one boundary patch) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Conductivity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Conductivity" +family = "365" +family_title = "Joint metric and connection recovery from one boundary patch" +subject = "Partial differential equations" +theorems = ["OAI.ScalarConductivity.main_nonuniqueness"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Conductivity.Main" +reference_modules = 595 +reference_lean_bytes = 3618863 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1871 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14956 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/conductivity/tests/Challenge.lean b/tasks/conductivity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9ec5e895aa395a437c9386a9e790315dba193f4 --- /dev/null +++ b/tasks/conductivity/tests/Challenge.lean @@ -0,0 +1,83 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace ScalarConductivity + +abbrev R3 := EuclideanSpace ℝ (Fin 3) +abbrev JetFiber := EuclideanSpace ℝ (Fin 4) +def ball : Set R3 := Metric.ball 0 3 +def ballMeasure : Measure R3 := volume.restrict ball +abbrev JetSpace := Lp JetFiber 2 ballMeasure + +def smoothJet (f : R3 → ℝ) (x : R3) : JetFiber := + WithLp.toLp 2 (Fin.cases (f x) (fun i => gradient f x i)) + +def smoothJets : Set JetSpace := + { z | ∃ (f : R3 → ℝ) (_ : ContDiff ℝ (↑(⊤ : ℕ∞)) f) + (hf : MemLp (smoothJet f) 2 ballMeasure), z = hf.toLp (smoothJet f) } + +def compactSmoothJets : Set JetSpace := + { z | ∃ (f : R3 → ℝ) (_ : ContDiff ℝ (↑(⊤ : ℕ∞)) f) + (_ : HasCompactSupport f) (_ : tsupport f ⊆ ball) + (hf : MemLp (smoothJet f) 2 ballMeasure), z = hf.toLp (smoothJet f) } + +def H1Space : Submodule ℝ JetSpace := + (Submodule.span ℝ smoothJets).topologicalClosure +abbrev H1 := H1Space + +def zeroTraceAmbient : Submodule ℝ JetSpace := + (Submodule.span ℝ compactSmoothJets).topologicalClosure + +def H10 : Submodule ℝ H1 := zeroTraceAmbient.comap H1Space.subtype + +instance H10_isClosed : IsClosed (H10 : Set H1) := by + exact (Submodule.isClosed_topologicalClosure + (Submodule.span ℝ compactSmoothJets)).preimage continuous_subtype_val + +abbrev TraceSpace := H1 ⧸ H10 +abbrev TraceDual := TraceSpace →L[ℝ] ℝ +abbrev DNOperator := TraceSpace →L[ℝ] TraceDual + +def trace (u : H1) : TraceSpace := H10.mkQ u + +def weakGradient (u : H1) (x : R3) : R3 := + WithLp.toLp 2 (fun i => (u.val x) i.succ) + +def energy (γ : R3 → ℝ) (u v : H1) : ℝ := + ∫ x, γ x * inner ℝ (weakGradient u x) (weakGradient v x) ∂ballMeasure + +def Harmonic (γ : R3 → ℝ) (u : H1) : Prop := + ∀ h : H1, h ∈ H10 → energy γ u h = 0 + +def IsDirichletToNeumann (γ : R3 → ℝ) (Λ : DNOperator) : Prop := + ∀ f : TraceSpace, ∃ u : H1, + trace u = f ∧ Harmonic γ u ∧ + (∀ u' : H1, trace u' = f → Harmonic γ u' → u' = u) ∧ + ∀ v : H1, Λ f (trace v) = energy γ u v + +def EqualOneNearBoundary (γ : R3 → ℝ) : Prop := + ∃ r : ℝ, 0 < r ∧ r < 3 ∧ ∀ᵐ x ∂ballMeasure, r < ‖x‖ → γ x = 1 + +def MainStatement : Prop := + ∃ (γ₀ γ₁ : R3 → ℝ) (c C : ℝ) (Λ : DNOperator), + 0 < c ∧ c < C ∧ + Measurable γ₀ ∧ Measurable γ₁ ∧ + MemLp γ₀ ∞ ballMeasure ∧ MemLp γ₁ ∞ ballMeasure ∧ + (∀ᵐ x ∂ballMeasure, c ≤ γ₀ x ∧ γ₀ x ≤ C) ∧ + (∀ᵐ x ∂ballMeasure, c ≤ γ₁ x ∧ γ₁ x ≤ C) ∧ + EqualOneNearBoundary γ₀ ∧ EqualOneNearBoundary γ₁ ∧ + 0 < ballMeasure {x | γ₀ x ≠ γ₁ x} ∧ + IsDirichletToNeumann γ₀ Λ ∧ IsDirichletToNeumann γ₁ Λ + +theorem main_nonuniqueness : MainStatement := by + sorry + +end ScalarConductivity +end + +end OAI diff --git a/tasks/conductivity/tests/grade.py b/tasks/conductivity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/conductivity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/conductivity/tests/task.json b/tasks/conductivity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3f47da01079dd001330801e7732c425c4308117b --- /dev/null +++ b/tasks/conductivity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Conductivity", + "comparator": { + "theorem_names": [ + "OAI.ScalarConductivity.main_nonuniqueness" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14056 +} \ No newline at end of file diff --git a/tasks/conductivity/tests/test.sh b/tasks/conductivity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/conductivity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/conjugate-points/environment/Dockerfile b/tasks/conjugate-points/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/conjugate-points/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/conjugate-points/environment/fetch_mathlib.sh b/tasks/conjugate-points/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/conjugate-points/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/conjugate-points/environment/lake-manifest.json b/tasks/conjugate-points/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/conjugate-points/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/conjugate-points/environment/lakefile.lean b/tasks/conjugate-points/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/conjugate-points/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/conjugate-points/environment/lean_setup.sh b/tasks/conjugate-points/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/conjugate-points/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/conjugate-points/environment/pack_submission.py b/tasks/conjugate-points/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/conjugate-points/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/conjugate-points/instruction.md b/tasks/conjugate-points/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0894f9cd617209e99a7554a40ffd9d715a734b5f --- /dev/null +++ b/tasks/conjugate-points/instruction.md @@ -0,0 +1,167 @@ +# openai/math challenge `ConjugatePoints` (family 358) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 358 of the release, *A three-manifold with no conjugate points and no nonpositively curved metric* +(Differential geometry). The family as a whole: Constructs a closed connected orientable smooth three-manifold that admits a metric without conjugate points but no metric of nonpositive sectional curvature. This answers negatively, already in dimension three, whether the first metric-existence property implies the second. + +The challenge is `ConjugatePoints`, also at `/opt/openai-math/challenges/ConjugatePoints.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Set Manifold Bundle +open scoped ContDiff + +namespace ThreeManifold + +abbrev E3 := Fin 3 → ℝ +abbrev I3 := 𝓘(ℝ, E3) + +variable {M : Type} [TopologicalSpace M] [ChartedSpace E3 M] + +def OrientedAtlas : Prop := + ∀ (c d : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → d ∈ atlas E3 M → + ∀ x ∈ c.target, c.symm x ∈ d.source → + 0 < LinearMap.det (fderiv ℝ (d ∘ c.symm) x).toLinearMap + +variable [IsManifold I3 ∞ M] + +abbrev SmoothMetric (M : Type) [TopologicalSpace M] [ChartedSpace E3 M] + [IsManifold I3 ∞ M] := + ContMDiffRiemannianMetric I3 ∞ E3 (fun x : M => TangentSpace I3 x) + +def basisVector (i : Fin 3) : E3 := Pi.single i 1 + +def metricMatrix (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) (x : E3) : + Matrix (Fin 3) (Fin 3) ℝ := + fun i j => g.inner (c.symm x) + (mfderiv I3 I3 c.symm x (basisVector i)) + (mfderiv I3 I3 c.symm x (basisVector j)) + +def coordPartial (f : E3 → ℝ) (x : E3) (i : Fin 3) : ℝ := + fderiv ℝ f x (basisVector i) + +def christoffel (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x : E3) (i j k : Fin 3) : ℝ := + (1 / 2 : ℝ) * ∑ l : Fin 3, (metricMatrix g c x)⁻¹ i l * + (coordPartial (fun y => metricMatrix g c y l k) x j + + coordPartial (fun y => metricMatrix g c y l j) x k - + coordPartial (fun y => metricMatrix g c y j k) x l) + +def connectionTerm (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x u v : E3) : E3 := + fun i => ∑ j : Fin 3, ∑ k : Fin 3, christoffel g c x i j k * u j * v k + +def curvatureCoefficient (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x : E3) (l k i j : Fin 3) : ℝ := + coordPartial (fun y => christoffel g c y l j k) x i - + coordPartial (fun y => christoffel g c y l i k) x j + + ∑ a : Fin 3, (christoffel g c x l i a * christoffel g c x a j k - + christoffel g c x l j a * christoffel g c x a i k) + +def curvatureTerm (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x u v w : E3) : E3 := + fun l => ∑ k : Fin 3, ∑ i : Fin 3, ∑ j : Fin 3, + curvatureCoefficient g c x l k i j * w k * u i * v j + +def NonpositiveSectionalCurvature (g : SmoothMetric M) : Prop := + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ∀ x ∈ c.target, ∀ u v : E3, + (∑ i : Fin 3, ∑ j : Fin 3, + metricMatrix g c x i j * curvatureTerm g c x u v v i * u j) ≤ 0 + +def alongDerivative (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x w : ℝ → E3) (s : ℝ) : E3 := + deriv w s + connectionTerm g c (x s) (deriv x s) (w s) + +def IsGeodesicOn (g : SmoothMetric M) (γ : ℝ → M) (U : Set ℝ) : Prop := + ContMDiffOn 𝓘(ℝ, ℝ) I3 ∞ γ U ∧ + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ∀ s ∈ U, γ s ∈ c.source → + alongDerivative g c (c ∘ γ) (deriv (c ∘ γ)) s = 0 + +def fieldCoordinates (γ : ℝ → M) (J : ∀ s, TangentSpace I3 (γ s)) + (c : OpenPartialHomeomorph M E3) (s : ℝ) : E3 := + mfderiv I3 I3 c (γ s) (J s) + +def IsJacobiFieldOn (g : SmoothMetric M) (γ : ℝ → M) + (J : ∀ s, TangentSpace I3 (γ s)) (U : Set ℝ) : Prop := + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ContDiffOn ℝ ∞ (fieldCoordinates γ J c) (U ∩ γ ⁻¹' c.source) ∧ + ∀ s ∈ U, γ s ∈ c.source → + alongDerivative g c (c ∘ γ) + (alongDerivative g c (c ∘ γ) (fieldCoordinates γ J c)) s + + curvatureTerm g c (c (γ s)) (fieldCoordinates γ J c s) + (deriv (c ∘ γ) s) (deriv (c ∘ γ) s) = 0 + +def NoConjugatePoints (g : SmoothMetric M) : Prop := + ∀ (U : Set ℝ), IsOpen U → OrdConnected U → + ∀ (γ : ℝ → M), IsGeodesicOn g γ U → + ∀ (J : ∀ s, TangentSpace I3 (γ s)), IsJacobiFieldOn g γ J U → + ∀ a ∈ U, ∀ b ∈ U, a ≠ b → J a = 0 → J b = 0 → ∀ s ∈ U, J s = 0 + +def MainStatement : Prop := + ∃ (M : Type) (top : TopologicalSpace M), + letI := top + ∃ (_ : T2Space M) (_ : SecondCountableTopology M) (_ : CompactSpace M) + (_ : ConnectedSpace M) (charts : ChartedSpace E3 M), + letI := charts + ∃ (smooth : IsManifold I3 ∞ M), + letI := smooth + OrientedAtlas (M := M) ∧ + (∃ g : SmoothMetric M, NoConjugatePoints g) ∧ + ¬ ∃ g : SmoothMetric M, NonpositiveSectionalCurvature g + +theorem main_theorem : MainStatement := by + sorry + +end ThreeManifold + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ConjugatePoints.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThreeManifold.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/conjugate-points/solution/closure.txt b/tasks/conjugate-points/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c4e9582f8e9a477b81441f104a8935bed84b8b4 --- /dev/null +++ b/tasks/conjugate-points/solution/closure.txt @@ -0,0 +1,19 @@ +OAI.Geometry.ConjugatePoints.Basic +OAI.Geometry.ConjugatePoints.Cometric +OAI.Geometry.ConjugatePoints.CompactMetric +OAI.Geometry.ConjugatePoints.Continuation +OAI.Geometry.ConjugatePoints.Convexity +OAI.Geometry.ConjugatePoints.Coordinates +OAI.Geometry.ConjugatePoints.Curvature +OAI.Geometry.ConjugatePoints.Distance +OAI.Geometry.ConjugatePoints.FundamentalGroup +OAI.Geometry.ConjugatePoints.Geodesics +OAI.Geometry.ConjugatePoints.Gluing +OAI.Geometry.ConjugatePoints.Index +OAI.Geometry.ConjugatePoints.Metric +OAI.Geometry.ConjugatePoints.Neck +OAI.Geometry.ConjugatePoints.NoConjugatePoints +OAI.Geometry.ConjugatePoints.Passages +OAI.Geometry.ConjugatePoints.Quotient +OAI.Geometry.ConjugatePoints.Returning +OAI.Geometry.ConjugatePoints.ThreeManifold diff --git a/tasks/conjugate-points/solution/reference.py b/tasks/conjugate-points/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/conjugate-points/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/conjugate-points/solution/solve.sh b/tasks/conjugate-points/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..20d1abe85305d02ad462ed26470b30d2772968ef --- /dev/null +++ b/tasks/conjugate-points/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ConjugatePoints, i.e. module OAI.Geometry.ConjugatePoints.ThreeManifold and the +# 19 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.ConjugatePoints.ThreeManifold /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ConjugatePoints" diff --git a/tasks/conjugate-points/task.toml b/tasks/conjugate-points/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f983f3c41f46d8642c17b48b2f875e98cf4a410f --- /dev/null +++ b/tasks/conjugate-points/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/conjugate-points" +version = "1.0.0" +description = "Prove ConjugatePoints (openai/math family 358: A three-manifold with no conjugate points and no nonpositively curved metric) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ConjugatePoints.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ConjugatePoints" +family = "358" +family_title = "A three-manifold with no conjugate points and no nonpositively curved metric" +subject = "Differential geometry" +theorems = ["OAI.ThreeManifold.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.ConjugatePoints.ThreeManifold" +reference_modules = 19 +reference_lean_bytes = 1279256 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1609 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12851 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/conjugate-points/tests/Challenge.lean b/tasks/conjugate-points/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..dee85f3d2724ab03a9b8f382f17feb3547b3661b --- /dev/null +++ b/tasks/conjugate-points/tests/Challenge.lean @@ -0,0 +1,116 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set Manifold Bundle +open scoped ContDiff + +namespace ThreeManifold + +abbrev E3 := Fin 3 → ℝ +abbrev I3 := 𝓘(ℝ, E3) + +variable {M : Type} [TopologicalSpace M] [ChartedSpace E3 M] + +def OrientedAtlas : Prop := + ∀ (c d : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → d ∈ atlas E3 M → + ∀ x ∈ c.target, c.symm x ∈ d.source → + 0 < LinearMap.det (fderiv ℝ (d ∘ c.symm) x).toLinearMap + +variable [IsManifold I3 ∞ M] + +abbrev SmoothMetric (M : Type) [TopologicalSpace M] [ChartedSpace E3 M] + [IsManifold I3 ∞ M] := + ContMDiffRiemannianMetric I3 ∞ E3 (fun x : M => TangentSpace I3 x) + +def basisVector (i : Fin 3) : E3 := Pi.single i 1 + +def metricMatrix (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) (x : E3) : + Matrix (Fin 3) (Fin 3) ℝ := + fun i j => g.inner (c.symm x) + (mfderiv I3 I3 c.symm x (basisVector i)) + (mfderiv I3 I3 c.symm x (basisVector j)) + +def coordPartial (f : E3 → ℝ) (x : E3) (i : Fin 3) : ℝ := + fderiv ℝ f x (basisVector i) + +def christoffel (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x : E3) (i j k : Fin 3) : ℝ := + (1 / 2 : ℝ) * ∑ l : Fin 3, (metricMatrix g c x)⁻¹ i l * + (coordPartial (fun y => metricMatrix g c y l k) x j + + coordPartial (fun y => metricMatrix g c y l j) x k - + coordPartial (fun y => metricMatrix g c y j k) x l) + +def connectionTerm (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x u v : E3) : E3 := + fun i => ∑ j : Fin 3, ∑ k : Fin 3, christoffel g c x i j k * u j * v k + +def curvatureCoefficient (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x : E3) (l k i j : Fin 3) : ℝ := + coordPartial (fun y => christoffel g c y l j k) x i - + coordPartial (fun y => christoffel g c y l i k) x j + + ∑ a : Fin 3, (christoffel g c x l i a * christoffel g c x a j k - + christoffel g c x l j a * christoffel g c x a i k) + +def curvatureTerm (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x u v w : E3) : E3 := + fun l => ∑ k : Fin 3, ∑ i : Fin 3, ∑ j : Fin 3, + curvatureCoefficient g c x l k i j * w k * u i * v j + +def NonpositiveSectionalCurvature (g : SmoothMetric M) : Prop := + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ∀ x ∈ c.target, ∀ u v : E3, + (∑ i : Fin 3, ∑ j : Fin 3, + metricMatrix g c x i j * curvatureTerm g c x u v v i * u j) ≤ 0 + +def alongDerivative (g : SmoothMetric M) (c : OpenPartialHomeomorph M E3) + (x w : ℝ → E3) (s : ℝ) : E3 := + deriv w s + connectionTerm g c (x s) (deriv x s) (w s) + +def IsGeodesicOn (g : SmoothMetric M) (γ : ℝ → M) (U : Set ℝ) : Prop := + ContMDiffOn 𝓘(ℝ, ℝ) I3 ∞ γ U ∧ + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ∀ s ∈ U, γ s ∈ c.source → + alongDerivative g c (c ∘ γ) (deriv (c ∘ γ)) s = 0 + +def fieldCoordinates (γ : ℝ → M) (J : ∀ s, TangentSpace I3 (γ s)) + (c : OpenPartialHomeomorph M E3) (s : ℝ) : E3 := + mfderiv I3 I3 c (γ s) (J s) + +def IsJacobiFieldOn (g : SmoothMetric M) (γ : ℝ → M) + (J : ∀ s, TangentSpace I3 (γ s)) (U : Set ℝ) : Prop := + ∀ (c : OpenPartialHomeomorph M E3), c ∈ atlas E3 M → + ContDiffOn ℝ ∞ (fieldCoordinates γ J c) (U ∩ γ ⁻¹' c.source) ∧ + ∀ s ∈ U, γ s ∈ c.source → + alongDerivative g c (c ∘ γ) + (alongDerivative g c (c ∘ γ) (fieldCoordinates γ J c)) s + + curvatureTerm g c (c (γ s)) (fieldCoordinates γ J c s) + (deriv (c ∘ γ) s) (deriv (c ∘ γ) s) = 0 + +def NoConjugatePoints (g : SmoothMetric M) : Prop := + ∀ (U : Set ℝ), IsOpen U → OrdConnected U → + ∀ (γ : ℝ → M), IsGeodesicOn g γ U → + ∀ (J : ∀ s, TangentSpace I3 (γ s)), IsJacobiFieldOn g γ J U → + ∀ a ∈ U, ∀ b ∈ U, a ≠ b → J a = 0 → J b = 0 → ∀ s ∈ U, J s = 0 + +def MainStatement : Prop := + ∃ (M : Type) (top : TopologicalSpace M), + letI := top + ∃ (_ : T2Space M) (_ : SecondCountableTopology M) (_ : CompactSpace M) + (_ : ConnectedSpace M) (charts : ChartedSpace E3 M), + letI := charts + ∃ (smooth : IsManifold I3 ∞ M), + letI := smooth + OrientedAtlas (M := M) ∧ + (∃ g : SmoothMetric M, NoConjugatePoints g) ∧ + ¬ ∃ g : SmoothMetric M, NonpositiveSectionalCurvature g + +theorem main_theorem : MainStatement := by + sorry + +end ThreeManifold + +end + +end OAI diff --git a/tasks/conjugate-points/tests/grade.py b/tasks/conjugate-points/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/conjugate-points/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/conjugate-points/tests/task.json b/tasks/conjugate-points/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3a0e2ab1f84eec79fe294b821b3396ff250a2a56 --- /dev/null +++ b/tasks/conjugate-points/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ConjugatePoints", + "comparator": { + "theorem_names": [ + "OAI.ThreeManifold.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11951 +} \ No newline at end of file diff --git a/tasks/conjugate-points/tests/test.sh b/tasks/conjugate-points/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/conjugate-points/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/contingency-tables/environment/Dockerfile b/tasks/contingency-tables/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/contingency-tables/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/contingency-tables/environment/fetch_mathlib.sh b/tasks/contingency-tables/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/contingency-tables/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/contingency-tables/environment/lake-manifest.json b/tasks/contingency-tables/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/contingency-tables/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/contingency-tables/environment/lakefile.lean b/tasks/contingency-tables/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/contingency-tables/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/contingency-tables/environment/lean_setup.sh b/tasks/contingency-tables/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/contingency-tables/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/contingency-tables/environment/pack_submission.py b/tasks/contingency-tables/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/contingency-tables/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/contingency-tables/instruction.md b/tasks/contingency-tables/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3c9c3edffbd837b5912b9ab56f34e3a9aea9ad37 --- /dev/null +++ b/tasks/contingency-tables/instruction.md @@ -0,0 +1,272 @@ +# openai/math challenge `ContingencyTables` (family 115) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 115 of the release, *Sampling and counting contingency tables with arbitrary margins* +(Theoretical computer science). The family as a whole: For nonnegative integer matrices with prescribed row and column sums, gives exact uniform sampling in expected polynomial bit time and almost-uniform sampling in worst-case polynomial bit time. The dimensions and binary-encoded margins are unrestricted. Also gives a fully polynomial randomized approximation scheme for counting such tables with arbitrary individual cell bounds, including structural zeros, with polynomial cost on every execution. + +The challenge is `ContingencyTables`, also at `/opt/openai-math/challenges/ContingencyTables.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MatchingFPRAS + +abbrev Symbol := Fin 8 + +/-- Binary numeral followed by a delimiter. Tape blank is 0; bits use 1 and 2. -/ +def encodeNat (n : ℕ) : List Symbol := + (Nat.bits n).map (fun b => if b then 2 else 1) ++ [3] + +def encodeInt (z : ℤ) : List Symbol := + (if z < 0 then [5] else [4]) ++ encodeNat z.natAbs + +/-- A rational encoded by its reduced numerator and positive denominator. -/ +def encodeRat (q : ℚ) : List Symbol := encodeInt q.num ++ encodeNat q.den + +/-- A uniform randomized Post-Turing machine: a single finite transition table. -/ +structure RandomMachine where + states : ℕ + transition : Fin (states + 1) → Symbol → Bool → + Option (Fin (states + 1) × Turing.TM0.Stmt Symbol) + +structure Configuration (A : RandomMachine) where + state : Option (Fin (A.states + 1)) + tape : Turing.Tape Symbol + +/-- A halted configuration is absorbing. Each nonhalting tick is exactly one +write or one move, or the detection of halt. -/ +def tick (A : RandomMachine) (c : Configuration A) (bit : Bool) : Configuration A := + match c.state with + | none => c + | some s => match A.transition s c.tape.head bit with + | none => ⟨none, c.tape⟩ + | some (s', action) => + ⟨some s', match action with + | .move d => c.tape.move d + | .write a => c.tape.write a⟩ + +def initial (A : RandomMachine) (input : List Symbol) : Configuration A := + ⟨some 0, Turing.Tape.mk₁ input⟩ + +/-- Bounded execution on a finite prefix of the random tape. -/ +def run (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) : Configuration A := + (List.ofFn bits).foldl (tick A) (initial A input) + +def Outputs (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) (q : ℚ) : Prop := + (run A input bits).state = none ∧ + (run A input bits).tape.right₀ = Turing.ListBlank.mk (encodeRat q) + +end MatchingFPRAS + +namespace ContingencyTables + +open Finset +variable {I J : Type*} [Fintype I] [Fintype J] + +def HasMargins (X : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) : Prop := + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) + +def Table (r : I → ℕ) (c : J → ℕ) := {X : I → J → ℕ // HasMargins X r c} + +def BoundedTable (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) := + {X : Table r c // ∀ i j, X.val i j ≤ b i j} + +theorem entry_le_row {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ r i := by + rw [← h.1 i] + exact single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ j) + +theorem entry_le_total {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ ∑ i, r i := + (entry_le_row h i j).trans (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)) + +instance table_finite (r : I → ℕ) (c : J → ℕ) : Finite (Table r c) := by + let encode : Table r c → I → J → Fin ((∑ i, r i) + 1) := + fun X i j => ⟨X.val i j, Nat.lt_succ_of_le (entry_le_total X.property i j)⟩ + apply Finite.of_injective encode + intro X Y h + apply Subtype.ext + funext i j + exact congrArg Fin.val (congrFun (congrFun h i) j) + +noncomputable instance table_fintype (r : I → ℕ) (c : J → ℕ) : Fintype (Table r c) := + Fintype.ofFinite _ + +noncomputable instance boundedTable_fintype (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) : + Fintype (BoundedTable r c b) := by + classical + unfold BoundedTable + infer_instance + +end ContingencyTables + +namespace ContingencyTables.Algorithms + +open scoped BigOperators +open Filter + +abbrev Machine := MatchingFPRAS.RandomMachine +abbrev Symbol := MatchingFPRAS.Symbol + +def encodeMatrix {m n : ℕ} (X : Fin m → Fin n → ℕ) : List Symbol := + ((List.ofFn fun i => (List.ofFn fun j => MatchingFPRAS.encodeNat (X i j)).flatten)).flatten + +def encodeMargins {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : List Symbol := + MatchingFPRAS.encodeNat m ++ MatchingFPRAS.encodeNat n ++ + (List.ofFn fun i => MatchingFPRAS.encodeNat (r i)).flatten ++ + (List.ofFn fun j => MatchingFPRAS.encodeNat (c j)).flatten + +def encodeSamplingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : List Symbol := + encodeMargins r c ++ MatchingFPRAS.encodeNat k + +def encodeCountingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : List Symbol := + encodeMargins r c ++ encodeMatrix b ++ MatchingFPRAS.encodeRat ε ++ MatchingFPRAS.encodeRat δ + +/-- The tape alphabet has positive cardinality. -/ +theorem alphabetSize_neZero : NeZero (8 : ℕ) := inferInstance + +/-- A halted tape contains the row-major binary matrix encoding. -/ +def OutputsTable (A : Machine) (input : List Symbol) {t m n : ℕ} + (bits : Fin t → Bool) (X : Fin m → Fin n → ℕ) : Prop := + (MatchingFPRAS.run A input bits).state = none ∧ + @Turing.Tape.right₀ MatchingFPRAS.Symbol (@Fin.instInhabited 8 alphabetSize_neZero) + (MatchingFPRAS.run A input bits).tape = + @Turing.ListBlank.mk Symbol (@Fin.instInhabited 8 alphabetSize_neZero) (encodeMatrix X) + +noncomputable def tableMass (A : Machine) (input : List Symbol) (t : ℕ) + {m n : ℕ} (X : Fin m → Fin n → ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => OutputsTable A input bits X).card : ℝ) / + (2 : ℝ) ^ t + +noncomputable def haltMass (A : Machine) (input : List Symbol) (t : ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => + (MatchingFPRAS.run A input bits).state = none).card : ℝ) / (2 : ℝ) ^ t + +def samplingSize (n : ℕ) {m : ℕ} (r : Fin m → ℕ) (k : ℕ) : ℕ := + m + n + Nat.clog 2 ((∑ i, r i) + 1) + k + 1 + +/-- Paper 200-01, Theorem main(i): bounded runtime on every random tape +and total variation at most `2⁻ᵏ`, with freely varying dimensions. -/ +def BoundedSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → ∀ k : ℕ, 1 ≤ k → + let input := encodeSamplingInput r c k + let t := C * (samplingSize n r k) ^ d + (∀ bits : Fin t → Bool, ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∑ X : Table r c, + |tableMass A input t X.val - (Fintype.card (Table r c) : ℝ)⁻¹|) / 2 ≤ + ((2 : ℝ) ^ k)⁻¹ + +/-- Paper 200-01, Theorem main(ii): every halted output is feasible, each +table has limiting mass `1/|Ω|`, termination has probability one, and the +expected number of bit operations is bounded by a uniform polynomial. -/ +def ExactSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + let input := encodeMargins r c + let tail : ℕ → ℝ := fun t => 1 - haltMass A input t + (∀ t (bits : Fin t → Bool), (MatchingFPRAS.run A input bits).state = none → + ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∀ X : Table r c, Tendsto (fun t => tableMass A input t X.val) atTop + (nhds ((Fintype.card (Table r c) : ℝ)⁻¹))) ∧ + Tendsto (haltMass A input) atTop (nhds 1) ∧ + Summable tail ∧ + tsum tail ≤ C * (samplingSize n r 0) ^ d + +noncomputable def count {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) : ℕ := Fintype.card (BoundedTable r c b) + +def countingTime (C d : ℕ) {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : ℕ := + C * ((encodeCountingInput r c b ε δ).length + ⌈ε⁻¹⌉₊ + + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodCountingTapes (A : Machine) {m n : ℕ} + (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (ε δ : ℚ) (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + MatchingFPRAS.Outputs A (encodeCountingInput r c b ε δ) bits q ∧ + (1 - ε) * count r c b ≤ q ∧ q ≤ (1 + ε) * count r c b + +/-- Paper 200-02, Theorem main. The input length includes the rational +accuracy parameters, and infeasible inputs always produce exactly zero. -/ +def CountingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ), 0 < m → 0 < n → + ∀ (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + ∀ ε δ : ℚ, 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let input := encodeCountingInput r c b ε δ + let t := countingTime C d r c b ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ MatchingFPRAS.Outputs A input bits q) ∧ + (count r c b = 0 → ∀ bits : Fin t → Bool, MatchingFPRAS.Outputs A input bits 0) ∧ + ((goodCountingTapes A r c b ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + +end ContingencyTables.Algorithms + +namespace ContingencyTables + +/-- An almost-uniform sampler with polynomial cost on every execution. -/ +theorem boundedSampling : Algorithms.BoundedSamplingStatement := by sorry + +/-- Exact uniform sampling in polynomial expected bit time. -/ +theorem exactSampling : Algorithms.ExactSamplingStatement := by sorry + +/-- A cell-bounded FPRAS, with zero output on every infeasible execution. -/ +theorem counting : Algorithms.CountingStatement := by sorry + +end ContingencyTables + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ContingencyTables.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.ContingencyTables.boundedSampling`, `OAI.ContingencyTables.exactSampling`, `OAI.ContingencyTables.counting` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/contingency-tables/solution/closure.txt b/tasks/contingency-tables/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..13e806c2b7e115b6d715924f56fd6b93bfb9c9a3 --- /dev/null +++ b/tasks/contingency-tables/solution/closure.txt @@ -0,0 +1,1297 @@ +OAI.Analysis.KLS.Convexity.PrekopaLeindler +OAI.Combinatorics.ContingencyTables.AlgorithmStatements +OAI.Combinatorics.ContingencyTables.Counting.AnnealingMultipliers +OAI.Combinatorics.ContingencyTables.Counting.CompanionAnnealing +OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticProposal +OAI.Combinatorics.ContingencyTables.Counting.CompanionArithmeticStep +OAI.Combinatorics.ContingencyTables.Counting.CompanionBinIntervals +OAI.Combinatorics.ContingencyTables.Counting.CompanionBinPopulation +OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanKernel +OAI.Combinatorics.ContingencyTables.Counting.CompanionBooleanPhase +OAI.Combinatorics.ContingencyTables.Counting.CompanionBoundedWalkProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionBoundedWalkSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalEncoding +OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalHistory +OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalHistoryLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalPhaseLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionCanonicalPhaseSupport +OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturn +OAI.Combinatorics.ContingencyTables.Counting.CompanionCappedReturnProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionCellCatalogProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionChainValidator +OAI.Combinatorics.ContingencyTables.Counting.CompanionCodeBounds +OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedInitial +OAI.Combinatorics.ContingencyTables.Counting.CompanionComputedProposal +OAI.Combinatorics.ContingencyTables.Counting.CompanionConcentration +OAI.Combinatorics.ContingencyTables.Counting.CompanionCorrectionArithmetic +OAI.Combinatorics.ContingencyTables.Counting.CompanionCorrectionSamples +OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorAmplification +OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorConfidence +OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorRange +OAI.Combinatorics.ContingencyTables.Counting.CompanionEstimatorWords +OAI.Combinatorics.ContingencyTables.Counting.CompanionEvaluatedWeightLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionEvaluatedWeightProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionFactorialApplication +OAI.Combinatorics.ContingencyTables.Counting.CompanionFarMass +OAI.Combinatorics.ContingencyTables.Counting.CompanionFlatReturnProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionFractionSize +OAI.Combinatorics.ContingencyTables.Counting.CompanionHistoryReadback +OAI.Combinatorics.ContingencyTables.Counting.CompanionHistorySize +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialDraw +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialMatrixProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialStoredProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitialization +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartJoint +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionInitializedRestartSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionLabelMetadataProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionMetropolisWordSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionMinMass +OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierAgreement +OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierMatrixProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionMultiplierUpdate +OAI.Combinatorics.ContingencyTables.Counting.CompanionNearMass +OAI.Combinatorics.ContingencyTables.Counting.CompanionNeighborProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservableApplication +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationPadding +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationQueriesLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservationQueriesProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservedUpdateLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionObservedUpdateProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleAcceptance +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleBudget +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleChain +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleCorrection +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleCut +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDensity +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleDraw +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleEstimator +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFibres +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleFiniteStep +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleJointLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleKernel +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleMixing +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleRational +OAI.Combinatorics.ContingencyTables.Counting.CompanionOracleSchedule +OAI.Combinatorics.ContingencyTables.Counting.CompanionOrderedProposal +OAI.Combinatorics.ContingencyTables.Counting.CompanionOrderedReturn +OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterHistoryProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterPhaseSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionOuterWidths +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseComposition +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseContextProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseContinuation +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseCounts +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseFinishSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseOracleError +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseSize +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrajectory +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrialLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseTrialProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhaseWords +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalNormalizer +OAI.Combinatorics.ContingencyTables.Counting.CompanionPhysicalTables +OAI.Combinatorics.ContingencyTables.Counting.CompanionProjectedHistory +OAI.Combinatorics.ContingencyTables.Counting.CompanionRatioSamples +OAI.Combinatorics.ContingencyTables.Counting.CompanionRationalUpdates +OAI.Combinatorics.ContingencyTables.Counting.CompanionReferenceAccuracy +OAI.Combinatorics.ContingencyTables.Counting.CompanionRepeatedReturnLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionRepeatedReturnProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartContinuation +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartDataLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartInitializer +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartNativeLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartPadding +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSchedule +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartScheduleSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSemantics +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartStageLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartStageProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionRestartSupport +OAI.Combinatorics.ContingencyTables.Counting.CompanionReturnIteration +OAI.Combinatorics.ContingencyTables.Counting.CompanionReturnWords +OAI.Combinatorics.ContingencyTables.Counting.CompanionScaleSizes +OAI.Combinatorics.ContingencyTables.Counting.CompanionStateMultiplierProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredRepresentation +OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredShape +OAI.Combinatorics.ContingencyTables.Counting.CompanionStoredSize +OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetMixing +OAI.Combinatorics.ContingencyTables.Counting.CompanionTargetTrace +OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalApplication +OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalMass +OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalParameters +OAI.Combinatorics.ContingencyTables.Counting.CompanionTerminalRegions +OAI.Combinatorics.ContingencyTables.Counting.CompanionTrace +OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionTraceWords +OAI.Combinatorics.ContingencyTables.Counting.CompanionTrajectoryLaw +OAI.Combinatorics.ContingencyTables.Counting.CompanionTrajectoryProgram +OAI.Combinatorics.ContingencyTables.Counting.CompanionTransitionWidth +OAI.Combinatorics.ContingencyTables.Counting.CompanionTrialPadding +OAI.Combinatorics.ContingencyTables.Counting.CompanionUniformPhaseBounds +OAI.Combinatorics.ContingencyTables.Counting.CompanionUniformPhaseWidth +OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmReturn +OAI.Combinatorics.ContingencyTables.Counting.CompanionWarmStart +OAI.Combinatorics.ContingencyTables.Counting.CompanionWeightOracle +OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingParameters +OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingWords +OAI.Combinatorics.ContingencyTables.Counting.ComputedCountingZero +OAI.Combinatorics.ContingencyTables.Counting.CountingActualInitialization +OAI.Combinatorics.ContingencyTables.Counting.CountingActualPhase +OAI.Combinatorics.ContingencyTables.Counting.CountingActualSettings +OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveInputSemantics +OAI.Combinatorics.ContingencyTables.Counting.CountingAdaptiveReserve +OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedLaw +OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingAmplifiedSourceLaw +OAI.Combinatorics.ContingencyTables.Counting.CountingBaseProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingBranchBudgetBound +OAI.Combinatorics.ContingencyTables.Counting.CountingBranchMachine +OAI.Combinatorics.ContingencyTables.Counting.CountingBranchProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSemantics +OAI.Combinatorics.ContingencyTables.Counting.CountingBranchSuccess +OAI.Combinatorics.ContingencyTables.Counting.CountingCoefficientBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingCoefficientProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingComputedSettings +OAI.Combinatorics.ContingencyTables.Counting.CountingConditionalAssembly +OAI.Combinatorics.ContingencyTables.Counting.CountingControlBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectBudgetBound +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectLaw +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSemantics +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectSuccess +OAI.Combinatorics.ContingencyTables.Counting.CountingDirectWordBound +OAI.Combinatorics.ContingencyTables.Counting.CountingExecutedMachine +OAI.Combinatorics.ContingencyTables.Counting.CountingHistoryApplication +OAI.Combinatorics.ContingencyTables.Counting.CountingInputParser +OAI.Combinatorics.ContingencyTables.Counting.CountingInputSymbols +OAI.Combinatorics.ContingencyTables.Counting.CountingLabelCountProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingMachineEvents +OAI.Combinatorics.ContingencyTables.Counting.CountingMachineMainEvent +OAI.Combinatorics.ContingencyTables.Counting.CountingMachineTime +OAI.Combinatorics.ContingencyTables.Counting.CountingMainMachine +OAI.Combinatorics.ContingencyTables.Counting.CountingMarkerBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingOracleScheduleProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingOracleWordBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseParametersProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseScalarProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingPhaseSchedule +OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveSemantics +OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveWordBound +OAI.Combinatorics.ContingencyTables.Counting.CountingPositiveWordLaw +OAI.Combinatorics.ContingencyTables.Counting.CountingPreparedState +OAI.Combinatorics.ContingencyTables.Counting.CountingPublicAccuracy +OAI.Combinatorics.ContingencyTables.Counting.CountingPublicControls +OAI.Combinatorics.ContingencyTables.Counting.CountingPublicInputBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingPublicTerminalBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingPublicWordBound +OAI.Combinatorics.ContingencyTables.Counting.CountingScheduleSizes +OAI.Combinatorics.ContingencyTables.Counting.CountingSettingsCorrect +OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalBounds +OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalProgram +OAI.Combinatorics.ContingencyTables.Counting.CountingTerminalSchedule +OAI.Combinatorics.ContingencyTables.Counting.CountingWordsBound +OAI.Combinatorics.ContingencyTables.Counting.EstimatorWordBanks +OAI.Combinatorics.ContingencyTables.Counting.InitialMultiplierValues +OAI.Combinatorics.ContingencyTables.Counting.InitializationBrackets +OAI.Combinatorics.ContingencyTables.Dense.AffineRegion +OAI.Combinatorics.ContingencyTables.Dense.AffineRegionVolume +OAI.Combinatorics.ContingencyTables.Dense.CheegerCoarea +OAI.Combinatorics.ContingencyTables.Dense.CheegerMedian +OAI.Combinatorics.ContingencyTables.Dense.CheegerPositive +OAI.Combinatorics.ContingencyTables.Dense.DenseAcceptance +OAI.Combinatorics.ContingencyTables.Dense.DenseAffine +OAI.Combinatorics.ContingencyTables.Dense.DenseAxisBits +OAI.Combinatorics.ContingencyTables.Dense.DenseAxisProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseAxisProposal +OAI.Combinatorics.ContingencyTables.Dense.DenseAxisSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseAxisWordProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseBitBudget +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanDraw +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanOffsets +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanStep +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanTrial +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalk +OAI.Combinatorics.ContingencyTables.Dense.DenseBooleanWalkProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseBoundedRejection +OAI.Combinatorics.ContingencyTables.Dense.DenseBoundedTrial +OAI.Combinatorics.ContingencyTables.Dense.DenseCandidateCounts +OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseCanonicalSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseChain +OAI.Combinatorics.ContingencyTables.Dense.DenseCoefficients +OAI.Combinatorics.ContingencyTables.Dense.DenseCompletedMatrixProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseCompletionProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseCompletionTest +OAI.Combinatorics.ContingencyTables.Dense.DenseCountProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseCutParameters +OAI.Combinatorics.ContingencyTables.Dense.DenseDrawProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseDrawSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseDrawTabulation +OAI.Combinatorics.ContingencyTables.Dense.DenseEnumeratedMatrix +OAI.Combinatorics.ContingencyTables.Dense.DenseErrorArithmetic +OAI.Combinatorics.ContingencyTables.Dense.DenseExponentArithmetic +OAI.Combinatorics.ContingencyTables.Dense.DenseExponentBound +OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseExponentListSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseExponentProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseFiniteTransition +OAI.Combinatorics.ContingencyTables.Dense.DenseFiniteWalk +OAI.Combinatorics.ContingencyTables.Dense.DenseFlatExponentProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseGeometry +OAI.Combinatorics.ContingencyTables.Dense.DenseGoodBins +OAI.Combinatorics.ContingencyTables.Dense.DenseGrid +OAI.Combinatorics.ContingencyTables.Dense.DenseGridExponentProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseIdealRejection +OAI.Combinatorics.ContingencyTables.Dense.DenseIndexedCounts +OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerLaw +OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseIntegerTable +OAI.Combinatorics.ContingencyTables.Dense.DenseInteriorVolume +OAI.Combinatorics.ContingencyTables.Dense.DenseLayerArithmetic +OAI.Combinatorics.ContingencyTables.Dense.DenseLocalGeometry +OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixLayoutProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixTable +OAI.Combinatorics.ContingencyTables.Dense.DenseMatrixWalk +OAI.Combinatorics.ContingencyTables.Dense.DenseMaximalReindex +OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseMetropolisSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseMixing +OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizeProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizeSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseNormalizer +OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetTrial +OAI.Combinatorics.ContingencyTables.Dense.DenseOffsetWidths +OAI.Combinatorics.ContingencyTables.Dense.DenseOffsets +OAI.Combinatorics.ContingencyTables.Dense.DenseRational +OAI.Combinatorics.ContingencyTables.Dense.DenseRationalKernel +OAI.Combinatorics.ContingencyTables.Dense.DenseRationalTrial +OAI.Combinatorics.ContingencyTables.Dense.DenseRegionVolume +OAI.Combinatorics.ContingencyTables.Dense.DenseRegularity +OAI.Combinatorics.ContingencyTables.Dense.DenseReindexedVolume +OAI.Combinatorics.ContingencyTables.Dense.DenseReservedWord +OAI.Combinatorics.ContingencyTables.Dense.DenseScaleCellProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseScaleMatrixProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseScales +OAI.Combinatorics.ContingencyTables.Dense.DenseStepGrowth +OAI.Combinatorics.ContingencyTables.Dense.DenseSuccessCounts +OAI.Combinatorics.ContingencyTables.Dense.DenseSuppliedFallback +OAI.Combinatorics.ContingencyTables.Dense.DenseSwapProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseTableCoordinates +OAI.Combinatorics.ContingencyTables.Dense.DenseTabulationScalarBounds +OAI.Combinatorics.ContingencyTables.Dense.DenseTransitionCounts +OAI.Combinatorics.ContingencyTables.Dense.DenseTrial +OAI.Combinatorics.ContingencyTables.Dense.DenseTrialAcceptance +OAI.Combinatorics.ContingencyTables.Dense.DenseTrialCountProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseTrialProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseTrialSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseTrialWeights +OAI.Combinatorics.ContingencyTables.Dense.DenseWalkProgram +OAI.Combinatorics.ContingencyTables.Dense.DenseWalkSemantics +OAI.Combinatorics.ContingencyTables.Dense.DenseWalkTabulation +OAI.Combinatorics.ContingencyTables.Dense.DenseWeights +OAI.Combinatorics.ContingencyTables.Dense.DenseWordProgram +OAI.Combinatorics.ContingencyTables.Dense.DensityLayers +OAI.Combinatorics.ContingencyTables.Dense.FiniteBoxPrekopa +OAI.Combinatorics.ContingencyTables.Dense.FiniteCheegerProof +OAI.Combinatorics.ContingencyTables.Dense.GridAdjacency +OAI.Combinatorics.ContingencyTables.Dense.GridBoundary +OAI.Combinatorics.ContingencyTables.Dense.GridConductance +OAI.Combinatorics.ContingencyTables.Dense.GridCover +OAI.Combinatorics.ContingencyTables.Dense.GridCutFlow +OAI.Combinatorics.ContingencyTables.Dense.GridIndexProgram +OAI.Combinatorics.ContingencyTables.Dense.GridMass +OAI.Combinatorics.ContingencyTables.Dense.GridMeasure +OAI.Combinatorics.ContingencyTables.Dense.GridMetropolis +OAI.Combinatorics.ContingencyTables.Dense.GridMinCut +OAI.Combinatorics.ContingencyTables.Dense.GridPartition +OAI.Combinatorics.ContingencyTables.Dense.PublishedCheeger +OAI.Combinatorics.ContingencyTables.Machines.BinIntervalProgram +OAI.Combinatorics.ContingencyTables.Machines.BinPopulationProgram +OAI.Combinatorics.ContingencyTables.Machines.BinVectorProgram +OAI.Combinatorics.ContingencyTables.Machines.BinaryContraction +OAI.Combinatorics.ContingencyTables.Machines.BinaryExchangeProgram +OAI.Combinatorics.ContingencyTables.Machines.BinaryPowerProgram +OAI.Combinatorics.ContingencyTables.Machines.BinarySearchProgram +OAI.Combinatorics.ContingencyTables.Machines.BooleanChunkProgram +OAI.Combinatorics.ContingencyTables.Machines.BoundedBinarySearch +OAI.Combinatorics.ContingencyTables.Machines.BoundedComplementProgram +OAI.Combinatorics.ContingencyTables.Machines.BoundedPowerProgram +OAI.Combinatorics.ContingencyTables.Machines.CachedCompletionWeights +OAI.Combinatorics.ContingencyTables.Machines.CachedDecisionSemantics +OAI.Combinatorics.ContingencyTables.Machines.CachedProfileDecision +OAI.Combinatorics.ContingencyTables.Machines.CachedStepCount +OAI.Combinatorics.ContingencyTables.Machines.CachedTerminalCount +OAI.Combinatorics.ContingencyTables.Machines.CachedTerminalSemantics +OAI.Combinatorics.ContingencyTables.Machines.CanonicalInitialEncoding +OAI.Combinatorics.ContingencyTables.Machines.CellLowerTestProgram +OAI.Combinatorics.ContingencyTables.Machines.CellMaximumProgram +OAI.Combinatorics.ContingencyTables.Machines.CellMinimumProgram +OAI.Combinatorics.ContingencyTables.Machines.CompletionEnumerationProgram +OAI.Combinatorics.ContingencyTables.Machines.CorrectionValueProgram +OAI.Combinatorics.ContingencyTables.Machines.DependentWordProgram +OAI.Combinatorics.ContingencyTables.Machines.DirectedBFSProgram +OAI.Combinatorics.ContingencyTables.Machines.DirectedBFSRuntime +OAI.Combinatorics.ContingencyTables.Machines.DyadicRootProgram +OAI.Combinatorics.ContingencyTables.Machines.DyadicWordProgram +OAI.Combinatorics.ContingencyTables.Machines.EndpointMatrixProgram +OAI.Combinatorics.ContingencyTables.Machines.EnumerationPointBounds +OAI.Combinatorics.ContingencyTables.Machines.FairBits +OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedBind +OAI.Combinatorics.ContingencyTables.Machines.FiniteEncodedHistory +OAI.Combinatorics.ContingencyTables.Machines.FiniteFairBits +OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphCutProgram +OAI.Combinatorics.ContingencyTables.Machines.FiniteGraphRootProgram +OAI.Combinatorics.ContingencyTables.Machines.FinitePlainLift +OAI.Combinatorics.ContingencyTables.Machines.FiniteTraceSlowdown +OAI.Combinatorics.ContingencyTables.Machines.FiniteVaryingObservable +OAI.Combinatorics.ContingencyTables.Machines.FiniteVaryingWordWalk +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordDependent +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordExecution +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordJointPadding +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordMachine +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordOutput +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordPadding +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordRationalLaw +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordRejection +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordSlices +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordTableLaw +OAI.Combinatorics.ContingencyTables.Machines.FiniteWordWalk +OAI.Combinatorics.ContingencyTables.Machines.FirstSuccessProgram +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityBits +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityFlat +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityFold +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityLaw +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityMixture +OAI.Combinatorics.ContingencyTables.Machines.FixedCardinalityProgram +OAI.Combinatorics.ContingencyTables.Machines.FlowEntryProgram +OAI.Combinatorics.ContingencyTables.Machines.FlowLoopProgram +OAI.Combinatorics.ContingencyTables.Machines.FlowMatrixProgram +OAI.Combinatorics.ContingencyTables.Machines.FlowPathProgram +OAI.Combinatorics.ContingencyTables.Machines.FractionAcceptanceProgram +OAI.Combinatorics.ContingencyTables.Machines.FractionAggregateProgram +OAI.Combinatorics.ContingencyTables.Machines.FractionMetropolisProgram +OAI.Combinatorics.ContingencyTables.Machines.FractionOutputProgram +OAI.Combinatorics.ContingencyTables.Machines.FractionRepetitionProgram +OAI.Combinatorics.ContingencyTables.Machines.GeometricRuntime +OAI.Combinatorics.ContingencyTables.Machines.InitialChoiceProgram +OAI.Combinatorics.ContingencyTables.Machines.InitialDrawReindex +OAI.Combinatorics.ContingencyTables.Machines.InitialFactorialBits +OAI.Combinatorics.ContingencyTables.Machines.InitialLocalChoices +OAI.Combinatorics.ContingencyTables.Machines.IntegerMatrixProgram +OAI.Combinatorics.ContingencyTables.Machines.ListSubtractProgram +OAI.Combinatorics.ContingencyTables.Machines.ListWordProgram +OAI.Combinatorics.ContingencyTables.Machines.LiteralProgram +OAI.Combinatorics.ContingencyTables.Machines.LowerCapacityProgram +OAI.Combinatorics.ContingencyTables.Machines.MatrixCodeEquality +OAI.Combinatorics.ContingencyTables.Machines.MatrixEncoding +OAI.Combinatorics.ContingencyTables.Machines.MatrixSubtractProgram +OAI.Combinatorics.ContingencyTables.Machines.MaximalListProgram +OAI.Combinatorics.ContingencyTables.Machines.MedianFractionProgram +OAI.Combinatorics.ContingencyTables.Machines.NatListEquality +OAI.Combinatorics.ContingencyTables.Machines.NaturalBlockProgram +OAI.Combinatorics.ContingencyTables.Machines.NetworkCapacityProgram +OAI.Combinatorics.ContingencyTables.Machines.NetworkFeasibilityProgram +OAI.Combinatorics.ContingencyTables.Machines.NetworkTableProgram +OAI.Combinatorics.ContingencyTables.Machines.OffsetCountProgram +OAI.Combinatorics.ContingencyTables.Machines.OnlineIntegerRetry +OAI.Combinatorics.ContingencyTables.Machines.OnlinePartialCall +OAI.Combinatorics.ContingencyTables.Machines.OnlineRetryPrefix +OAI.Combinatorics.ContingencyTables.Machines.OnlineRetryRuntime +OAI.Combinatorics.ContingencyTables.Machines.PackedMatrixInjective +OAI.Combinatorics.ContingencyTables.Machines.PairedCatalogProgram +OAI.Combinatorics.ContingencyTables.Machines.PairedDemandProgram +OAI.Combinatorics.ContingencyTables.Machines.PairedFactorialProgram +OAI.Combinatorics.ContingencyTables.Machines.PairedProfileProgram +OAI.Combinatorics.ContingencyTables.Machines.PowerApproximationProgram +OAI.Combinatorics.ContingencyTables.Machines.PreparedDenseCount +OAI.Combinatorics.ContingencyTables.Machines.PreparedOffsetCount +OAI.Combinatorics.ContingencyTables.Machines.PreparedTransitionCache +OAI.Combinatorics.ContingencyTables.Machines.PublicInputLength +OAI.Combinatorics.ContingencyTables.Machines.QuadraticPrefixRuntime +OAI.Combinatorics.ContingencyTables.Machines.RationalIntervalProgram +OAI.Combinatorics.ContingencyTables.Machines.RepeatedFractionProgram +OAI.Combinatorics.ContingencyTables.Machines.ResidualDenseProgram +OAI.Combinatorics.ContingencyTables.Machines.ResidualGraphProgram +OAI.Combinatorics.ContingencyTables.Machines.ResidualWeightProgram +OAI.Combinatorics.ContingencyTables.Machines.RetryNumeratorProgram +OAI.Combinatorics.ContingencyTables.Machines.RoundedPowerProgram +OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleBounds +OAI.Combinatorics.ContingencyTables.Machines.ScalarScheduleProgram +OAI.Combinatorics.ContingencyTables.Machines.ScaledWordProgram +OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountInput +OAI.Combinatorics.ContingencyTables.Machines.ScheduledCountSemantics +OAI.Combinatorics.ContingencyTables.Machines.ScheduledResidualLaw +OAI.Combinatorics.ContingencyTables.Machines.ScheduledResidualProgram +OAI.Combinatorics.ContingencyTables.Machines.ScheduledScalarBounds +OAI.Combinatorics.ContingencyTables.Machines.SignedFloorProgram +OAI.Combinatorics.ContingencyTables.Machines.SignedPairProgram +OAI.Combinatorics.ContingencyTables.Machines.SparseViewMatrixProgram +OAI.Combinatorics.ContingencyTables.Machines.TableIndexProgram +OAI.Combinatorics.ContingencyTables.Machines.TightenedInputProgram +OAI.Combinatorics.ContingencyTables.Machines.TransitionCacheRuntime +OAI.Combinatorics.ContingencyTables.Machines.TranslationDecisionProgram +OAI.Combinatorics.ContingencyTables.Machines.VectorRetryProgram +OAI.Combinatorics.ContingencyTables.Machines.WeightedArgmaxProgram +OAI.Combinatorics.ContingencyTables.Model +OAI.Combinatorics.ContingencyTables.Parameters +OAI.Combinatorics.ContingencyTables.PublishedInputs +OAI.Combinatorics.ContingencyTables.Rooted.ComputedForestCode +OAI.Combinatorics.ContingencyTables.Rooted.ComputedLargeForest +OAI.Combinatorics.ContingencyTables.Rooted.ComputedRootedInput +OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineCoefficients +OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineCompletion +OAI.Combinatorics.ContingencyTables.Rooted.ForestAffineProgram +OAI.Combinatorics.ContingencyTables.Rooted.ForestAssignmentSplit +OAI.Combinatorics.ContingencyTables.Rooted.ForestBoxCardinality +OAI.Combinatorics.ContingencyTables.Rooted.ForestCapacity +OAI.Combinatorics.ContingencyTables.Rooted.ForestCountIdentification +OAI.Combinatorics.ContingencyTables.Rooted.ForestCut +OAI.Combinatorics.ContingencyTables.Rooted.ForestEdgeChoiceProgram +OAI.Combinatorics.ContingencyTables.Rooted.ForestGreedyProgram +OAI.Combinatorics.ContingencyTables.Rooted.ForestGreedySemantics +OAI.Combinatorics.ContingencyTables.Rooted.ForestIntegerEvaluation +OAI.Combinatorics.ContingencyTables.Rooted.ForestJoinProgram +OAI.Combinatorics.ContingencyTables.Rooted.ForestLargeMarginal +OAI.Combinatorics.ContingencyTables.Rooted.ForestLiteralCount +OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyApplication +OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyBound +OAI.Combinatorics.ContingencyTables.Rooted.ForestPenaltyProgram +OAI.Combinatorics.ContingencyTables.Rooted.ForestPhysicalCompletion +OAI.Combinatorics.ContingencyTables.Rooted.ForestRootPenalty +OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledBounds +OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledIdentification +OAI.Combinatorics.ContingencyTables.Rooted.ForestScaledPenalty +OAI.Combinatorics.ContingencyTables.Rooted.LargeEdgeCatalogProgram +OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginProgram +OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginReference +OAI.Combinatorics.ContingencyTables.Rooted.LargeMarginSemantics +OAI.Combinatorics.ContingencyTables.Rooted.LargePairEnumeration +OAI.Combinatorics.ContingencyTables.Rooted.MaximumForest +OAI.Combinatorics.ContingencyTables.Rooted.MaximumForestExchange +OAI.Combinatorics.ContingencyTables.Rooted.RootedAffine +OAI.Combinatorics.ContingencyTables.Rooted.RootedAnnealing +OAI.Combinatorics.ContingencyTables.Rooted.RootedArithmeticStep +OAI.Combinatorics.ContingencyTables.Rooted.RootedBinDrawLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedBinFramesProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedBooleanKernel +OAI.Combinatorics.ContingencyTables.Rooted.RootedBooleanPhase +OAI.Combinatorics.ContingencyTables.Rooted.RootedCappedReturn +OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogGrid +OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogStep +OAI.Combinatorics.ContingencyTables.Rooted.RootedCatalogWalk +OAI.Combinatorics.ContingencyTables.Rooted.RootedCellDataProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedCoefficientProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedCompletion +OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentCode +OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedComponentSemantics +OAI.Combinatorics.ContingencyTables.Rooted.RootedComputedEstimator +OAI.Combinatorics.ContingencyTables.Rooted.RootedConcentration +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionArithmetic +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSampleLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSampleProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSamples +OAI.Combinatorics.ContingencyTables.Rooted.RootedCorrectionSemantics +OAI.Combinatorics.ContingencyTables.Rooted.RootedCountIdentification +OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingAmplification +OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingSchedule +OAI.Combinatorics.ContingencyTables.Rooted.RootedCountingWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedCut +OAI.Combinatorics.ContingencyTables.Rooted.RootedCutReindex +OAI.Combinatorics.ContingencyTables.Rooted.RootedDemandProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorAmplification +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorBlockProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorConfidence +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorExecution +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorLayoutProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorMedianLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorMedianProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorRange +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWordSemantics +OAI.Combinatorics.ContingencyTables.Rooted.RootedEstimatorWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedFactorialApplication +OAI.Combinatorics.ContingencyTables.Rooted.RootedFarMass +OAI.Combinatorics.ContingencyTables.Rooted.RootedForestCatalog +OAI.Combinatorics.ContingencyTables.Rooted.RootedForestDataProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedForestPrepareProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedHistoryConfidence +OAI.Combinatorics.ContingencyTables.Rooted.RootedHistoryStep +OAI.Combinatorics.ContingencyTables.Rooted.RootedIntegerEvaluation +OAI.Combinatorics.ContingencyTables.Rooted.RootedIntervals +OAI.Combinatorics.ContingencyTables.Rooted.RootedLabelWeightProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedLargeMarginal +OAI.Combinatorics.ContingencyTables.Rooted.RootedLiteralCount +OAI.Combinatorics.ContingencyTables.Rooted.RootedMultiplierUpdate +OAI.Combinatorics.ContingencyTables.Rooted.RootedNearMass +OAI.Combinatorics.ContingencyTables.Rooted.RootedObservableApplication +OAI.Combinatorics.ContingencyTables.Rooted.RootedObservationStart +OAI.Combinatorics.ContingencyTables.Rooted.RootedOffsetProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleAcceptance +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleChain +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleConfigSemantics +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleCorrection +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleCut +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleDensity +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleDraw +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleEstimator +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFiniteStep +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleFlatProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleKernel +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleMixing +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleRational +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleSchedule +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleStepProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWalkProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedOracleWordProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedPenalty +OAI.Combinatorics.ContingencyTables.Rooted.RootedPenaltyEvaluateProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedPenaltyProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseAccuracy +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseComposition +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseExperiment +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseHistory +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseOracleError +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrajectory +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseTrial +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhaseWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalCompletion +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalNormalizer +OAI.Combinatorics.ContingencyTables.Rooted.RootedPhysicalTables +OAI.Combinatorics.ContingencyTables.Rooted.RootedPlainTrial +OAI.Combinatorics.ContingencyTables.Rooted.RootedPointPenaltyProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSampleLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSampleProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedRatioSamples +OAI.Combinatorics.ContingencyTables.Rooted.RootedReferenceAccuracy +OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartAgreement +OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartPrefix +OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartStages +OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartTrial +OAI.Combinatorics.ContingencyTables.Rooted.RootedRestartWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnHistoryLaw +OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnIteration +OAI.Combinatorics.ContingencyTables.Rooted.RootedReturnWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedRootPenalty +OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledBounds +OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledIdentification +OAI.Combinatorics.ContingencyTables.Rooted.RootedScaledPenalty +OAI.Combinatorics.ContingencyTables.Rooted.RootedSlowConcentration +OAI.Combinatorics.ContingencyTables.Rooted.RootedStoredEstimate +OAI.Combinatorics.ContingencyTables.Rooted.RootedStoredHistory +OAI.Combinatorics.ContingencyTables.Rooted.RootedTargetMixing +OAI.Combinatorics.ContingencyTables.Rooted.RootedTargetTrace +OAI.Combinatorics.ContingencyTables.Rooted.RootedTerminalApplication +OAI.Combinatorics.ContingencyTables.Rooted.RootedTerminalMass +OAI.Combinatorics.ContingencyTables.Rooted.RootedTerminalRegions +OAI.Combinatorics.ContingencyTables.Rooted.RootedTrace +OAI.Combinatorics.ContingencyTables.Rooted.RootedTraceWords +OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeBounds +OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeExteriorMass +OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeFeasibleMass +OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeInputProgram +OAI.Combinatorics.ContingencyTables.Rooted.RootedTreeMarginal +OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmReturn +OAI.Combinatorics.ContingencyTables.Rooted.RootedWarmStart +OAI.Combinatorics.ContingencyTables.Rooted.RootedWeightOracle +OAI.Combinatorics.ContingencyTables.Rooted.RootedZeroLabels +OAI.Combinatorics.ContingencyTables.Rooted.TreeExteriorMass +OAI.Combinatorics.ContingencyTables.Rooted.TreeExteriorPositions +OAI.Combinatorics.ContingencyTables.Rooted.TreeFeasibleMass +OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalBounds +OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalEnumeration +OAI.Combinatorics.ContingencyTables.Rooted.TreeMarginalSignature +OAI.Combinatorics.ContingencyTables.Sampling.AllBalancedWidths +OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingAccuracy +OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingMachine +OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingProgram +OAI.Combinatorics.ContingencyTables.Sampling.AllSamplingSemantics +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallBoolean +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallChain +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallFibres +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallInitialization +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallOuter +OAI.Combinatorics.ContingencyTables.Sampling.AllSmallRational +OAI.Combinatorics.ContingencyTables.Sampling.CompiledResidualCorrection +OAI.Combinatorics.ContingencyTables.Sampling.ExactBoxBounds +OAI.Combinatorics.ContingencyTables.Sampling.ExactBranchChoice +OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactCoreProgram +OAI.Combinatorics.ContingencyTables.Sampling.ExactCorrectionPrefix +OAI.Combinatorics.ContingencyTables.Sampling.ExactEntryBoxBound +OAI.Combinatorics.ContingencyTables.Sampling.ExactExpectedTime +OAI.Combinatorics.ContingencyTables.Sampling.ExactGateCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePhysical +OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePolynomial +OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePrefix +OAI.Combinatorics.ContingencyTables.Sampling.ExactGatePublic +OAI.Combinatorics.ContingencyTables.Sampling.ExactGateTyped +OAI.Combinatorics.ContingencyTables.Sampling.ExactInputBounds +OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerChoice +OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerOnline +OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerPhysical +OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerProgram +OAI.Combinatorics.ContingencyTables.Sampling.ExactIntegerRetry +OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixLimits +OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixLookup +OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixTableLaw +OAI.Combinatorics.ContingencyTables.Sampling.ExactMatrixTrial +OAI.Combinatorics.ContingencyTables.Sampling.ExactOrdinaryProgram +OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactPhysicalProgram +OAI.Combinatorics.ContingencyTables.Sampling.ExactPrefixFeasibility +OAI.Combinatorics.ContingencyTables.Sampling.ExactPrefixLaw +OAI.Combinatorics.ContingencyTables.Sampling.ExactPrintCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicLaw +OAI.Combinatorics.ContingencyTables.Sampling.ExactPublicPrefix +OAI.Combinatorics.ContingencyTables.Sampling.ExactRareCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactRareMeasureBound +OAI.Combinatorics.ContingencyTables.Sampling.ExactRarePublicBound +OAI.Combinatorics.ContingencyTables.Sampling.ExactResidualInput +OAI.Combinatorics.ContingencyTables.Sampling.ExactSamplingMachine +OAI.Combinatorics.ContingencyTables.Sampling.ExactSamplingParameters +OAI.Combinatorics.ContingencyTables.Sampling.ExactTablePrefix +OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedCost +OAI.Combinatorics.ContingencyTables.Sampling.ExactTypedProgram +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBinaryParameters +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanDraw +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanProposal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBooleanStep +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperBoundedLaw +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperChildMass +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCodeNeighbors +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCodeProposal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCompletionComparison +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCompletionLaws +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperComputedCatalog +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextBox +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextChildren +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperContextTransport +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperCorrectionBudget +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperExposureVariance +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFeasibility +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFiniteSampler +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperFullVariance +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealKernel +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperIdealRejection +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperImplementedLaw +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInitialization +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperInputWordBudget +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperJointLaw +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperLocalNeighbors +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperLocalProposal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperOuterBudget +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalMarginal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPhysicalVariance +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperPreparedProposal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProfiles +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperProposal +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperRationalMixing +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallChain +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallKernel +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSmallMixing +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperStationaryMass +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessEvent +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperSuccessRatio +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperTransversalVariance +OAI.Combinatorics.ContingencyTables.Sampling.FirstPaperWordBudget +OAI.Combinatorics.ContingencyTables.Sampling.GreedyCellMachine +OAI.Combinatorics.ContingencyTables.Sampling.GreedyFeasibleTable +OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicMachine +OAI.Combinatorics.ContingencyTables.Sampling.GreedyPublicProgram +OAI.Combinatorics.ContingencyTables.Sampling.GreedyRowComplexity +OAI.Combinatorics.ContingencyTables.Sampling.GreedyRowMachine +OAI.Combinatorics.ContingencyTables.Sampling.GreedyTableComplexity +OAI.Combinatorics.ContingencyTables.Sampling.GreedyTableMachine +OAI.Combinatorics.ContingencyTables.Sampling.InverseSmallRepair +OAI.Combinatorics.ContingencyTables.Sampling.OriginalBalancedJoint +OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxLaw +OAI.Combinatorics.ContingencyTables.Sampling.OriginalBoxPush +OAI.Combinatorics.ContingencyTables.Sampling.OriginalOuterVector +OAI.Combinatorics.ContingencyTables.Sampling.OriginalPointBounds +OAI.Combinatorics.ContingencyTables.Sampling.OriginalProfileEntries +OAI.Combinatorics.ContingencyTables.Sampling.OriginalProfileProgram +OAI.Combinatorics.ContingencyTables.Sampling.OriginalResidualVector +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableBox +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableCardinality +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableCheck +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableEnumeration +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTableIndex +OAI.Combinatorics.ContingencyTables.Sampling.OriginalTrialVector +OAI.Combinatorics.ContingencyTables.Sampling.OuterMatrixSemantics +OAI.Combinatorics.ContingencyTables.Sampling.OuterTableProgram +OAI.Combinatorics.ContingencyTables.Sampling.OuterTrialProgram +OAI.Combinatorics.ContingencyTables.Sampling.PaddedCompletions +OAI.Combinatorics.ContingencyTables.Sampling.PaddedEnumerationBounds +OAI.Combinatorics.ContingencyTables.Sampling.PaddedResidualProgram +OAI.Combinatorics.ContingencyTables.Sampling.PaddedResidualSemantics +OAI.Combinatorics.ContingencyTables.Sampling.Padding +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalCompletionFibres +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalContextVariance +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalCostPolynomial +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalEdgeMargins +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalEventBounds +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalExchangeMargins +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphDegree +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalGraphVertices +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalLargeProfiles +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalMassBound +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalOriginalResiduals +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPaperCapacity +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPartialSequence +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPrefixEnergies +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPrefixTail +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalPublicLaw +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairGraph +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairMargins +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRepairMass +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalResidualMargins +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRetryIteration +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalRetryTail +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalSmallEnergy +OAI.Combinatorics.ContingencyTables.Sampling.PhysicalSmallGraph +OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxEnumeration +OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxIndex +OAI.Combinatorics.ContingencyTables.Sampling.ProfileBoxLaw +OAI.Combinatorics.ContingencyTables.Sampling.ProfileCodeEquality +OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeCandidates +OAI.Combinatorics.ContingencyTables.Sampling.ProfileExchangeProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileInverseRepairProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntry +OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixEntryRuntime +OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixLaw +OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileMatrixSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicMachine +OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfilePublicSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileRepairProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileRetryProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileRetrySemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileRuntimeBound +OAI.Combinatorics.ContingencyTables.Sampling.ProfileSamplingProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileScheduleProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileScheduleSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTerminalSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCount +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionCountSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTransitionSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialCountProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialProgram +OAI.Combinatorics.ContingencyTables.Sampling.ProfileTrialSemantics +OAI.Combinatorics.ContingencyTables.Sampling.ProfileVectorMeasureBounds +OAI.Combinatorics.ContingencyTables.Sampling.ProfileWordProgram +OAI.Combinatorics.ContingencyTables.Sampling.RareBranchRuntime +OAI.Combinatorics.ContingencyTables.Sampling.Repair +OAI.Combinatorics.ContingencyTables.Sampling.RepairFibres +OAI.Combinatorics.ContingencyTables.Sampling.RepairLargeMass +OAI.Combinatorics.ContingencyTables.Sampling.RepairPrefixes +OAI.Combinatorics.ContingencyTables.Sampling.RepairResiduals +OAI.Combinatorics.ContingencyTables.Sampling.RepairSmallMargins +OAI.Combinatorics.ContingencyTables.Sampling.ResidualMixture +OAI.Combinatorics.ContingencyTables.Sampling.SmallBalancedEncoding +OAI.Combinatorics.ContingencyTables.Sampling.SmallBalancedMarginal +OAI.Combinatorics.ContingencyTables.Sampling.SmallBoundsProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallCellCatalogProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallCellIndexProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallChainBudget +OAI.Combinatorics.ContingencyTables.Sampling.SmallComplementProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallCompletionAcceptance +OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCoordinates +OAI.Combinatorics.ContingencyTables.Sampling.SmallContextCount +OAI.Combinatorics.ContingencyTables.Sampling.SmallContextEnumeration +OAI.Combinatorics.ContingencyTables.Sampling.SmallContextFibres +OAI.Combinatorics.ContingencyTables.Sampling.SmallCoordinateSums +OAI.Combinatorics.ContingencyTables.Sampling.SmallDefectCodeTest +OAI.Combinatorics.ContingencyTables.Sampling.SmallDefectLabels +OAI.Combinatorics.ContingencyTables.Sampling.SmallEntries +OAI.Combinatorics.ContingencyTables.Sampling.SmallExchangeListProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallGraphProfiles +OAI.Combinatorics.ContingencyTables.Sampling.SmallInverseRepairList +OAI.Combinatorics.ContingencyTables.Sampling.SmallLineSumProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallMarginSemantics +OAI.Combinatorics.ContingencyTables.Sampling.SmallMarginTestProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternArithmetic +OAI.Combinatorics.ContingencyTables.Sampling.SmallPatternProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileCode +OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileEncoding +OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileFlatCode +OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileRepair +OAI.Combinatorics.ContingencyTables.Sampling.SmallProfileValidator +OAI.Combinatorics.ContingencyTables.Sampling.SmallProposal +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCandidates +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCapacity +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairCodeProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairGeometryProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairListProgram +OAI.Combinatorics.ContingencyTables.Sampling.SmallRepairWords +OAI.Combinatorics.ContingencyTables.Sampling.SmallResidualTotals +OAI.Combinatorics.ContingencyTables.Sampling.SmallViewLookupProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitBoxLaw +OAI.Combinatorics.ContingencyTables.Sampling.UnitFiniteLaw +OAI.Combinatorics.ContingencyTables.Sampling.UnitGraphEnergy +OAI.Combinatorics.ContingencyTables.Sampling.UnitIntegerLaw +OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixEntry +OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixLaw +OAI.Combinatorics.ContingencyTables.Sampling.UnitMatrixProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitOriginalVector +OAI.Combinatorics.ContingencyTables.Sampling.UnitOuterVector +OAI.Combinatorics.ContingencyTables.Sampling.UnitOutputSemantics +OAI.Combinatorics.ContingencyTables.Sampling.UnitProfileProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitProfileSemantics +OAI.Combinatorics.ContingencyTables.Sampling.UnitTerminalProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitTerminalSemantics +OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialCountProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialProgram +OAI.Combinatorics.ContingencyTables.Sampling.UnitTrialSemantics +OAI.Combinatorics.ContingencyTables.Transport.AffinePenalty +OAI.Combinatorics.ContingencyTables.Transport.AuxiliaryRepairMass +OAI.Combinatorics.ContingencyTables.Transport.AxisProposalTest +OAI.Combinatorics.ContingencyTables.Transport.BalancedBox +OAI.Combinatorics.ContingencyTables.Transport.BalancedCellFibres +OAI.Combinatorics.ContingencyTables.Transport.BalancedCompletionMass +OAI.Combinatorics.ContingencyTables.Transport.BalancedEnumeration +OAI.Combinatorics.ContingencyTables.Transport.BalancedFamily +OAI.Combinatorics.ContingencyTables.Transport.BalancedJointConstruction +OAI.Combinatorics.ContingencyTables.Transport.BalancedPhysicalPartition +OAI.Combinatorics.ContingencyTables.Transport.BalancedSummation +OAI.Combinatorics.ContingencyTables.Transport.BooleanCountTransport +OAI.Combinatorics.ContingencyTables.Transport.BooleanEnumeration +OAI.Combinatorics.ContingencyTables.Transport.BooleanIntegerLaw +OAI.Combinatorics.ContingencyTables.Transport.BoundedCellShift +OAI.Combinatorics.ContingencyTables.Transport.BoundedOffsetLaw +OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileSemantics +OAI.Combinatorics.ContingencyTables.Transport.BoundedProfileWalk +OAI.Combinatorics.ContingencyTables.Transport.BoundedTableComplement +OAI.Combinatorics.ContingencyTables.Transport.BoundedTableFeasibility +OAI.Combinatorics.ContingencyTables.Transport.BoxCompletion +OAI.Combinatorics.ContingencyTables.Transport.BoxGeometry +OAI.Combinatorics.ContingencyTables.Transport.CacheBoxBounds +OAI.Combinatorics.ContingencyTables.Transport.CanonicalDrawTabulation +OAI.Combinatorics.ContingencyTables.Transport.CanonicalIntegerLaw +OAI.Combinatorics.ContingencyTables.Transport.ChoiceContextEnumeration +OAI.Combinatorics.ContingencyTables.Transport.ComplementChain +OAI.Combinatorics.ContingencyTables.Transport.CompletionChainFlow +OAI.Combinatorics.ContingencyTables.Transport.CompletionCounts +OAI.Combinatorics.ContingencyTables.Transport.CompletionDecisionReindex +OAI.Combinatorics.ContingencyTables.Transport.CompletionEnergyComparison +OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreEquiv +OAI.Combinatorics.ContingencyTables.Transport.CompletionFibreTransport +OAI.Combinatorics.ContingencyTables.Transport.CompletionKernelIdentification +OAI.Combinatorics.ContingencyTables.Transport.CompletionProposalLaw +OAI.Combinatorics.ContingencyTables.Transport.CompletionStepApproximation +OAI.Combinatorics.ContingencyTables.Transport.ComputedCompanionInstance +OAI.Combinatorics.ContingencyTables.Transport.ComputedTableTightening +OAI.Combinatorics.ContingencyTables.Transport.ContextAdjacentTransport +OAI.Combinatorics.ContingencyTables.Transport.ContextChildVariance +OAI.Combinatorics.ContingencyTables.Transport.ContextGraphEnergy +OAI.Combinatorics.ContingencyTables.Transport.ContextGraphMembership +OAI.Combinatorics.ContingencyTables.Transport.ContextWeightedEnumeration +OAI.Combinatorics.ContingencyTables.Transport.DegreeCompletion +OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSBounds +OAI.Combinatorics.ContingencyTables.Transport.DirectedBFSCode +OAI.Combinatorics.ContingencyTables.Transport.DyadicAcceptance +OAI.Combinatorics.ContingencyTables.Transport.DyadicRootBisection +OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpAlgorithm +OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpAugmentation +OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpBound +OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpDistance +OAI.Combinatorics.ContingencyTables.Transport.EdmondsKarpTrace +OAI.Combinatorics.ContingencyTables.Transport.EqualityReindex +OAI.Combinatorics.ContingencyTables.Transport.EqualitySoftening +OAI.Combinatorics.ContingencyTables.Transport.ExcessContextDefects +OAI.Combinatorics.ContingencyTables.Transport.ExcessContextProfiles +OAI.Combinatorics.ContingencyTables.Transport.ExcessPairCoordinates +OAI.Combinatorics.ContingencyTables.Transport.FactorialSignatures +OAI.Combinatorics.ContingencyTables.Transport.FiniteAcceptCounts +OAI.Combinatorics.ContingencyTables.Transport.FiniteAdaptiveObservable +OAI.Combinatorics.ContingencyTables.Transport.FiniteBiasedAverages +OAI.Combinatorics.ContingencyTables.Transport.FiniteBoundedProjectedHistory +OAI.Combinatorics.ContingencyTables.Transport.FiniteChainGraphComparison +OAI.Combinatorics.ContingencyTables.Transport.FiniteChainSlowdown +OAI.Combinatorics.ContingencyTables.Transport.FiniteChainWeightVariance +OAI.Combinatorics.ContingencyTables.Transport.FiniteChoiceFibres +OAI.Combinatorics.ContingencyTables.Transport.FiniteCorrectionLaw +OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentApproximation +OAI.Combinatorics.ContingencyTables.Transport.FiniteDependentLaw +OAI.Combinatorics.ContingencyTables.Transport.FiniteDeterministicJoint +OAI.Combinatorics.ContingencyTables.Transport.FiniteDirectedBFS +OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeDegree +OAI.Combinatorics.ContingencyTables.Transport.FiniteExchangeObservables +OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureBudget +OAI.Combinatorics.ContingencyTables.Transport.FiniteExposureVariance +OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphCutSemantics +OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphPoincareBudget +OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRootSemantics +OAI.Combinatorics.ContingencyTables.Transport.FiniteGraphRoots +OAI.Combinatorics.ContingencyTables.Transport.FiniteGridWords +OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentAverages +OAI.Combinatorics.ContingencyTables.Transport.FiniteIndependentFailures +OAI.Combinatorics.ContingencyTables.Transport.FiniteLawDecidableEq +OAI.Combinatorics.ContingencyTables.Transport.FiniteLawMoments +OAI.Combinatorics.ContingencyTables.Transport.FiniteLawRelativeError +OAI.Combinatorics.ContingencyTables.Transport.FiniteMedianConfidence +OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolis +OAI.Combinatorics.ContingencyTables.Transport.FiniteMetropolisTransport +OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableReindex +OAI.Combinatorics.ContingencyTables.Transport.FiniteObservableTransport +OAI.Combinatorics.ContingencyTables.Transport.FinitePaddedAverage +OAI.Combinatorics.ContingencyTables.Transport.FinitePartialDraw +OAI.Combinatorics.ContingencyTables.Transport.FinitePartitionVariance +OAI.Combinatorics.ContingencyTables.Transport.FinitePrefixVariance +OAI.Combinatorics.ContingencyTables.Transport.FiniteProductAccuracy +OAI.Combinatorics.ContingencyTables.Transport.FiniteProjectedHistory +OAI.Combinatorics.ContingencyTables.Transport.FiniteProposalStay +OAI.Combinatorics.ContingencyTables.Transport.FiniteRationalThreshold +OAI.Combinatorics.ContingencyTables.Transport.FiniteRecordedHistory +OAI.Combinatorics.ContingencyTables.Transport.FiniteRepairDegree +OAI.Combinatorics.ContingencyTables.Transport.FiniteRepairVariance +OAI.Combinatorics.ContingencyTables.Transport.FiniteSameLawSupport +OAI.Combinatorics.ContingencyTables.Transport.FiniteScaledDraw +OAI.Combinatorics.ContingencyTables.Transport.FiniteSupportEnergy +OAI.Combinatorics.ContingencyTables.Transport.FiniteSupportVariance +OAI.Combinatorics.ContingencyTables.Transport.FiniteSymmetricEnergy +OAI.Combinatorics.ContingencyTables.Transport.FiniteUniformHistory +OAI.Combinatorics.ContingencyTables.Transport.FirstSuccess +OAI.Combinatorics.ContingencyTables.Transport.FlowClamp +OAI.Combinatorics.ContingencyTables.Transport.FlowMatrixBounds +OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionCounts +OAI.Combinatorics.ContingencyTables.Transport.GraphCompletionUnique +OAI.Combinatorics.ContingencyTables.Transport.GraphIntegralCompletion +OAI.Combinatorics.ContingencyTables.Transport.HardZeroTransport +OAI.Combinatorics.ContingencyTables.Transport.IndexedTableLaw +OAI.Combinatorics.ContingencyTables.Transport.InitialDefectChoices +OAI.Combinatorics.ContingencyTables.Transport.InitialFactorialLaw +OAI.Combinatorics.ContingencyTables.Transport.InitialTransversals +OAI.Combinatorics.ContingencyTables.Transport.IntegerAuxiliaryEnumeration +OAI.Combinatorics.ContingencyTables.Transport.IntegerBoxTruncation +OAI.Combinatorics.ContingencyTables.Transport.IntegerChildLogConcavity +OAI.Combinatorics.ContingencyTables.Transport.IntegerChildVariance +OAI.Combinatorics.ContingencyTables.Transport.IntegerContextSlices +OAI.Combinatorics.ContingencyTables.Transport.IntegerCorrectionKernel +OAI.Combinatorics.ContingencyTables.Transport.IntegerEquivLaw +OAI.Combinatorics.ContingencyTables.Transport.IntegerExchangeArithmetic +OAI.Combinatorics.ContingencyTables.Transport.IntegerExposure +OAI.Combinatorics.ContingencyTables.Transport.IntegerFutureKernel +OAI.Combinatorics.ContingencyTables.Transport.IntegerFutureSquare +OAI.Combinatorics.ContingencyTables.Transport.IntegerGraphTruncation +OAI.Combinatorics.ContingencyTables.Transport.IntegerLaw +OAI.Combinatorics.ContingencyTables.Transport.IntegerLawEmbedding +OAI.Combinatorics.ContingencyTables.Transport.IntegerLeafEnergy +OAI.Combinatorics.ContingencyTables.Transport.IntegerLeafTransport +OAI.Combinatorics.ContingencyTables.Transport.IntegerMarginal +OAI.Combinatorics.ContingencyTables.Transport.IntegerMatrixPoint +OAI.Combinatorics.ContingencyTables.Transport.IntegerPairRecursion +OAI.Combinatorics.ContingencyTables.Transport.IntegerPropagation +OAI.Combinatorics.ContingencyTables.Transport.IntegerPushTransport +OAI.Combinatorics.ContingencyTables.Transport.IntegerRecursiveFlow +OAI.Combinatorics.ContingencyTables.Transport.IntegerRecursivePotential +OAI.Combinatorics.ContingencyTables.Transport.IntegerReflection +OAI.Combinatorics.ContingencyTables.Transport.IntegerResidualCorrection +OAI.Combinatorics.ContingencyTables.Transport.IntegerRootEstimate +OAI.Combinatorics.ContingencyTables.Transport.IntegerRootTransport +OAI.Combinatorics.ContingencyTables.Transport.IntegerSliceReindex +OAI.Combinatorics.ContingencyTables.Transport.IntegerSliceRestriction +OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportCoefficient +OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportLevels +OAI.Combinatorics.ContingencyTables.Transport.IntegerTransportLimit +OAI.Combinatorics.ContingencyTables.Transport.IntegerTruncatedTransport +OAI.Combinatorics.ContingencyTables.Transport.IntegerWeightedTransport +OAI.Combinatorics.ContingencyTables.Transport.LabelledFactorial +OAI.Combinatorics.ContingencyTables.Transport.LaminarSignature +OAI.Combinatorics.ContingencyTables.Transport.LayeredTableNetwork +OAI.Combinatorics.ContingencyTables.Transport.LineUnarySignature +OAI.Combinatorics.ContingencyTables.Transport.ListBitProposal +OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanDraw +OAI.Combinatorics.ContingencyTables.Transport.ListedBooleanStep +OAI.Combinatorics.ContingencyTables.Transport.ListedCompletion +OAI.Combinatorics.ContingencyTables.Transport.ListedDenseDraw +OAI.Combinatorics.ContingencyTables.Transport.ListedDenseProgramSemantics +OAI.Combinatorics.ContingencyTables.Transport.ListedIntegerLaw +OAI.Combinatorics.ContingencyTables.Transport.ListedKernelAccuracy +OAI.Combinatorics.ContingencyTables.Transport.ListedOutputSemantics +OAI.Combinatorics.ContingencyTables.Transport.ListedReferenceDecision +OAI.Combinatorics.ContingencyTables.Transport.ListedReservedDraw +OAI.Combinatorics.ContingencyTables.Transport.ListedScheduledSampler +OAI.Combinatorics.ContingencyTables.Transport.MeasuredFold +OAI.Combinatorics.ContingencyTables.Transport.MeasuredMap +OAI.Combinatorics.ContingencyTables.Transport.MetropolisChain +OAI.Combinatorics.ContingencyTables.Transport.NestedPenaltyApplication +OAI.Combinatorics.ContingencyTables.Transport.NestedProductSignature +OAI.Combinatorics.ContingencyTables.Transport.NestedReindex +OAI.Combinatorics.ContingencyTables.Transport.NetworkVertexCode +OAI.Combinatorics.ContingencyTables.Transport.ObservableBounds +OAI.Combinatorics.ContingencyTables.Transport.ObservableTrajectory +OAI.Combinatorics.ContingencyTables.Transport.ObservableVariance +OAI.Combinatorics.ContingencyTables.Transport.PairedComplement +OAI.Combinatorics.ContingencyTables.Transport.PairedLabels +OAI.Combinatorics.ContingencyTables.Transport.PairedProfileSemantics +OAI.Combinatorics.ContingencyTables.Transport.PathAugmentation +OAI.Combinatorics.ContingencyTables.Transport.PositiveSequenceInterpolation +OAI.Combinatorics.ContingencyTables.Transport.PositiveSequenceMinimum +OAI.Combinatorics.ContingencyTables.Transport.PowerOfTwoApproximation +OAI.Combinatorics.ContingencyTables.Transport.ProductIntegerSignature +OAI.Combinatorics.ContingencyTables.Transport.PublishedEdmondsKarp +OAI.Combinatorics.ContingencyTables.Transport.QuadraticTransport +OAI.Combinatorics.ContingencyTables.Transport.RationalChainCast +OAI.Combinatorics.ContingencyTables.Transport.RationalChainMixing +OAI.Combinatorics.ContingencyTables.Transport.RationalMapProducts +OAI.Combinatorics.ContingencyTables.Transport.RationalProducts +OAI.Combinatorics.ContingencyTables.Transport.RationalReindex +OAI.Combinatorics.ContingencyTables.Transport.RationalRootBisection +OAI.Combinatorics.ContingencyTables.Transport.RationalWalkApproximation +OAI.Combinatorics.ContingencyTables.Transport.RationalWalks +OAI.Combinatorics.ContingencyTables.Transport.RawSmallChoiceProperties +OAI.Combinatorics.ContingencyTables.Transport.RealCompletion +OAI.Combinatorics.ContingencyTables.Transport.RealKernelApproximation +OAI.Combinatorics.ContingencyTables.Transport.RealPathApproximation +OAI.Combinatorics.ContingencyTables.Transport.RectangleCompletions +OAI.Combinatorics.ContingencyTables.Transport.RecursiveSignedTransport +OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBlock +OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionBounds +OAI.Combinatorics.ContingencyTables.Transport.ReferenceCompletionEntries +OAI.Combinatorics.ContingencyTables.Transport.ReferenceDrawBounds +OAI.Combinatorics.ContingencyTables.Transport.ReferenceEdgeAcceptance +OAI.Combinatorics.ContingencyTables.Transport.ReferenceFiniteDraw +OAI.Combinatorics.ContingencyTables.Transport.ReflectedNested +OAI.Combinatorics.ContingencyTables.Transport.ReflectedSlices +OAI.Combinatorics.ContingencyTables.Transport.RejectionLaw +OAI.Combinatorics.ContingencyTables.Transport.ResidualAugmentation +OAI.Combinatorics.ContingencyTables.Transport.ResidualBoxScale +OAI.Combinatorics.ContingencyTables.Transport.ResidualEnumerationBounds +OAI.Combinatorics.ContingencyTables.Transport.ResidualSearch +OAI.Combinatorics.ContingencyTables.Transport.RowColumnPenalties +OAI.Combinatorics.ContingencyTables.Transport.RowMajorEnumeration +OAI.Combinatorics.ContingencyTables.Transport.RowMajorPrefixFibres +OAI.Combinatorics.ContingencyTables.Transport.ScalarPenalty +OAI.Combinatorics.ContingencyTables.Transport.SignedMarginTranslation +OAI.Combinatorics.ContingencyTables.Transport.SignedTransport +OAI.Combinatorics.ContingencyTables.Transport.SliceFactorial +OAI.Combinatorics.ContingencyTables.Transport.SoftWeightUpper +OAI.Combinatorics.ContingencyTables.Transport.StarReindex +OAI.Combinatorics.ContingencyTables.Transport.StateSuccessEntries +OAI.Combinatorics.ContingencyTables.Transport.SuccessfulJointBijection +OAI.Combinatorics.ContingencyTables.Transport.TableMarginTransport +OAI.Combinatorics.ContingencyTables.Transport.TableReindex +OAI.Combinatorics.ContingencyTables.Transport.TableTightening +OAI.Combinatorics.ContingencyTables.Transport.TabulationMeasureBounds +OAI.Combinatorics.ContingencyTables.Transport.TabulationPreparationBounds +OAI.Combinatorics.ContingencyTables.Transport.TerminalMassCover +OAI.Combinatorics.ContingencyTables.Transport.TraceBounds +OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionAcceptance +OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionChain +OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletionCounts +OAI.Combinatorics.ContingencyTables.Transport.TranslatedCompletions +OAI.Combinatorics.ContingencyTables.Transport.TranslationDecisionSemantics +OAI.Combinatorics.ContingencyTables.Transport.TransversalCount +OAI.Combinatorics.ContingencyTables.Transport.TwoLiftStates +OAI.Combinatorics.ContingencyTables.Transport.UnaryMarkers +OAI.Combinatorics.ContingencyTables.Transport.UniformPartialRejection +OAI.Combinatorics.ContingencyTables.Transport.WarmKernelIteration +OAI.Combinatorics.ContingencyTables.Transport.WeightedCellFibres +OAI.Combinatorics.ContingencyTables.Transport.WordCompletionStep +OAI.Combinatorics.ContingencyTables.Transport.WordContextVariance +OAI.Combinatorics.ContingencyTables.UnconditionalMain +OAI.Combinatorics.MatchingCount.Algorithm.AffineWeights +OAI.Combinatorics.MatchingCount.Algorithm.OnlineScheduleNat +OAI.Combinatorics.MatchingCount.Arithmetic.ArithmeticSize +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryAddition +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryCompare +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryNormalize +OAI.Combinatorics.MatchingCount.Arithmetic.BinarySubtract +OAI.Combinatorics.MatchingCount.Arithmetic.PostAddition +OAI.Combinatorics.MatchingCount.Arithmetic.PostComparison +OAI.Combinatorics.MatchingCount.Arithmetic.SubtractProc +OAI.Combinatorics.MatchingCount.Arithmetic.TreeCompare +OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction +OAI.Combinatorics.MatchingCount.Arithmetic.TreeGCD +OAI.Combinatorics.MatchingCount.Arithmetic.TreeNatDivision +OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps +OAI.Combinatorics.MatchingCount.Arithmetic.TreeSubtract +OAI.Combinatorics.MatchingCount.Complexity.AlphabetCompilerCost +OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase +OAI.Combinatorics.MatchingCount.Complexity.OnlineCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineFoldCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineFrameCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineWordCost +OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost +OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure +OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic +OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts +OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts +OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomial +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialArithmetic +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialCollections +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialDivision +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGCD +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLists +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLoop +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums +OAI.Combinatorics.MatchingCount.Graphs.AdaptiveStream +OAI.Combinatorics.MatchingCount.Graphs.Admissible +OAI.Combinatorics.MatchingCount.Graphs.ArcData +OAI.Combinatorics.MatchingCount.Graphs.ColoredEdge +OAI.Combinatorics.MatchingCount.Graphs.Cumulative +OAI.Combinatorics.MatchingCount.Graphs.Cycle +OAI.Combinatorics.MatchingCount.Graphs.Density +OAI.Combinatorics.MatchingCount.Graphs.Edge +OAI.Combinatorics.MatchingCount.Graphs.Edge2 +OAI.Combinatorics.MatchingCount.Graphs.EdgeLow +OAI.Combinatorics.MatchingCount.Graphs.EnlargementRun +OAI.Combinatorics.MatchingCount.Graphs.Evolve +OAI.Combinatorics.MatchingCount.Graphs.ExperimentSupport +OAI.Combinatorics.MatchingCount.Graphs.FillHoles +OAI.Combinatorics.MatchingCount.Graphs.FirstHoleSortedCons +OAI.Combinatorics.MatchingCount.Graphs.Height +OAI.Combinatorics.MatchingCount.Graphs.HoleBlocks +OAI.Combinatorics.MatchingCount.Graphs.HoleStrength +OAI.Combinatorics.MatchingCount.Graphs.Incident +OAI.Combinatorics.MatchingCount.Graphs.IndexedCycle +OAI.Combinatorics.MatchingCount.Graphs.LabelCycle +OAI.Combinatorics.MatchingCount.Graphs.Marked +OAI.Combinatorics.MatchingCount.Graphs.MatchingMap +OAI.Combinatorics.MatchingCount.Graphs.Mate +OAI.Combinatorics.MatchingCount.Graphs.PM +OAI.Combinatorics.MatchingCount.Graphs.PathActivity +OAI.Combinatorics.MatchingCount.Graphs.PathStrength +OAI.Combinatorics.MatchingCount.Graphs.Profile +OAI.Combinatorics.MatchingCount.Graphs.PushedFlow +OAI.Combinatorics.MatchingCount.Graphs.Related +OAI.Combinatorics.MatchingCount.Graphs.RemainingBags +OAI.Combinatorics.MatchingCount.Graphs.SafeSwitch +OAI.Combinatorics.MatchingCount.Graphs.SafeTrace +OAI.Combinatorics.MatchingCount.Graphs.Sets +OAI.Combinatorics.MatchingCount.Graphs.SumLiftMate +OAI.Combinatorics.MatchingCount.Graphs.ThresholdGraph +OAI.Combinatorics.MatchingCount.Graphs.Vertex +OAI.Combinatorics.MatchingCount.Machines.BoolPostCompiler +OAI.Combinatorics.MatchingCount.Machines.CoinTM1 +OAI.Combinatorics.MatchingCount.Machines.CoinTM1Finite +OAI.Combinatorics.MatchingCount.Machines.FiniteStore +OAI.Combinatorics.MatchingCount.Machines.OnlineControl +OAI.Combinatorics.MatchingCount.Machines.OnlineFold +OAI.Combinatorics.MatchingCount.Machines.OnlineFrame +OAI.Combinatorics.MatchingCount.Machines.OnlinePhysicalProgram +OAI.Combinatorics.MatchingCount.Machines.OnlineTree +OAI.Combinatorics.MatchingCount.Machines.PhysicalPost +OAI.Combinatorics.MatchingCount.Machines.PhysicalProcess +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramMap +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramSeal +OAI.Combinatorics.MatchingCount.Machines.PhysicalRestriction +OAI.Combinatorics.MatchingCount.Machines.PhysicalSequential +OAI.Combinatorics.MatchingCount.Machines.RegisterControl +OAI.Combinatorics.MatchingCount.Machines.RegisterProc +OAI.Combinatorics.MatchingCount.Machines.RegisterStructured +OAI.Combinatorics.MatchingCount.Machines.RegisterTree +OAI.Combinatorics.MatchingCount.Machines.SupportedCompiler +OAI.Combinatorics.MatchingCount.Machines.TableLookup +OAI.Combinatorics.MatchingCount.Machines.TreeCanonical +OAI.Combinatorics.MatchingCount.Machines.TreeChoice +OAI.Combinatorics.MatchingCount.Machines.TreeColex +OAI.Combinatorics.MatchingCount.Machines.TreeCompiler +OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +OAI.Combinatorics.MatchingCount.Machines.TreeFinite +OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections +OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps +OAI.Combinatorics.MatchingCount.Machines.TreeFold +OAI.Combinatorics.MatchingCount.Machines.TreeFrame +OAI.Combinatorics.MatchingCount.Machines.TreeFunction +OAI.Combinatorics.MatchingCount.Machines.TreeIndex +OAI.Combinatorics.MatchingCount.Machines.TreeList +OAI.Combinatorics.MatchingCount.Machines.TreeListMore +OAI.Combinatorics.MatchingCount.Machines.TreeListOps +OAI.Combinatorics.MatchingCount.Machines.TreeLookup +OAI.Combinatorics.MatchingCount.Machines.TreeMachine +OAI.Combinatorics.MatchingCount.Machines.TreeNaturalComb +OAI.Combinatorics.MatchingCount.Machines.TreePairProposal +OAI.Combinatorics.MatchingCount.Machines.TreePartialChoice +OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +OAI.Combinatorics.MatchingCount.Machines.TreePredicate +OAI.Combinatorics.MatchingCount.Machines.TreeProgramUnique +OAI.Combinatorics.MatchingCount.Machines.TreeRepeat +OAI.Combinatorics.MatchingCount.Machines.TreeSum +OAI.Combinatorics.MatchingCount.Machines.TreeTransfer +OAI.Combinatorics.MatchingCount.Machines.TreeTyped +OAI.Combinatorics.MatchingCount.Model +OAI.Combinatorics.MatchingCount.Probability.LocalVariance +OAI.Combinatorics.MatchingCount.Probability.Mean +OAI.Combinatorics.MatchingCount.Probability.Tv +OAI.Combinatorics.MatchingCount.Probability.Variance +OAI.Combinatorics.MatchingCount.Sampling.AssignmentEquiv +OAI.Combinatorics.MatchingCount.Sampling.Certify +OAI.Combinatorics.MatchingCount.Sampling.ChosenChord +OAI.Combinatorics.MatchingCount.Sampling.Component +OAI.Combinatorics.MatchingCount.Sampling.ComponentOrder +OAI.Combinatorics.MatchingCount.Sampling.Components +OAI.Combinatorics.MatchingCount.Sampling.Corner +OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps +OAI.Combinatorics.MatchingCount.Sampling.EndpointPair +OAI.Combinatorics.MatchingCount.Sampling.IntervalPattern +OAI.Combinatorics.MatchingCount.Sampling.LadderL +OAI.Combinatorics.MatchingCount.Sampling.MetropolisChoice +OAI.Combinatorics.MatchingCount.Sampling.PM +OAI.Combinatorics.MatchingCount.Sampling.PairStep +OAI.Combinatorics.MatchingCount.Sampling.Plan +OAI.Combinatorics.MatchingCount.Sampling.RankOrder +OAI.Combinatorics.MatchingCount.Sampling.RelationDestinations +OAI.Combinatorics.MatchingCount.Sampling.Sewn +OAI.Combinatorics.MatchingCount.Sampling.Span +OAI.Combinatorics.MatchingCount.Sampling.Sym2Order +OAI.Combinatorics.MatchingCount.Sampling.Through +OAI.Combinatorics.MatchingCount.Sampling.TierClamp +OAI.Combinatorics.MatchingCount.Sampling.TreeCategorical +OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts +OAI.Combinatorics.MatchingCount.Sampling.TreeDPEntry +OAI.Combinatorics.MatchingCount.Sampling.Underlying +OAI.Combinatorics.MatchingCount.Tapes.BlockMap +OAI.Combinatorics.MatchingCount.Tapes.Codec +OAI.Combinatorics.MatchingCount.Tapes.CoinAlphabet +OAI.Combinatorics.MatchingCount.Tapes.CoinStack +OAI.Combinatorics.MatchingCount.Tapes.CoinSupport +OAI.Combinatorics.MatchingCount.Tapes.FixedAlphabetCompiler +OAI.Combinatorics.MatchingCount.Tapes.FixedEncoding +OAI.Combinatorics.MatchingCount.Tapes.Online +OAI.Combinatorics.MatchingCount.Tapes.OnlineComposition +OAI.Combinatorics.MatchingCount.Tapes.OnlineStackCompiler +OAI.Combinatorics.MatchingCount.Tapes.OnlineWord +OAI.Combinatorics.MatchingCount.Tapes.Packed +OAI.Combinatorics.MatchingCount.Tapes.PackedExecution +OAI.Combinatorics.MatchingCount.Tapes.PackedInverse +OAI.Combinatorics.MatchingCount.Tapes.Parse +OAI.Combinatorics.MatchingCount.Tapes.Physical +OAI.Combinatorics.MatchingCount.Tapes.PhysicalAlphabet +OAI.Combinatorics.MatchingCount.Tapes.RunBits +OAI.Combinatorics.MatchingCount.Tapes.StackEmbedding +OAI.Combinatorics.MatchingCount.Tapes.StackLens +OAI.Combinatorics.MatchingCount.Tapes.StackWords +OAI.Combinatorics.MatchingCount.Tapes.TapeTools +OAI.Combinatorics.MatchingCount.Tapes.TreeBits +OAI.Combinatorics.MatchingCount.Tapes.TreeEncodingInjective +OAI.Combinatorics.MatchingCount.Tapes.WordOps +OAI.Combinatorics.MatroidCounting.CommonBases diff --git a/tasks/contingency-tables/solution/reference.py b/tasks/contingency-tables/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/contingency-tables/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/contingency-tables/solution/solve.sh b/tasks/contingency-tables/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee6aa13905736b07b2270edcdeb5ada874533db3 --- /dev/null +++ b/tasks/contingency-tables/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ContingencyTables, i.e. module OAI.Combinatorics.ContingencyTables.UnconditionalMain and the +# 1297 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ContingencyTables.UnconditionalMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ContingencyTables" diff --git a/tasks/contingency-tables/task.toml b/tasks/contingency-tables/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4afa92e659a6919c5417c28be97693fabe16c5ea --- /dev/null +++ b/tasks/contingency-tables/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/contingency-tables" +version = "1.0.0" +description = "Prove ContingencyTables (openai/math family 115: Sampling and counting contingency tables with arbitrary margins) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ContingencyTables.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ContingencyTables" +family = "115" +family_title = "Sampling and counting contingency tables with arbitrary margins" +subject = "Theoretical computer science" +theorems = ["OAI.ContingencyTables.boundedSampling", "OAI.ContingencyTables.exactSampling", "OAI.ContingencyTables.counting"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ContingencyTables.UnconditionalMain" +reference_modules = 1297 +reference_lean_bytes = 9098638 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3243 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19888 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/contingency-tables/tests/Challenge.lean b/tasks/contingency-tables/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..898c717347f72973521c92597d7aee9818eb13b4 --- /dev/null +++ b/tasks/contingency-tables/tests/Challenge.lean @@ -0,0 +1,221 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS + +abbrev Symbol := Fin 8 + +/-- Binary numeral followed by a delimiter. Tape blank is 0; bits use 1 and 2. -/ +def encodeNat (n : ℕ) : List Symbol := + (Nat.bits n).map (fun b => if b then 2 else 1) ++ [3] + +def encodeInt (z : ℤ) : List Symbol := + (if z < 0 then [5] else [4]) ++ encodeNat z.natAbs + +/-- A rational encoded by its reduced numerator and positive denominator. -/ +def encodeRat (q : ℚ) : List Symbol := encodeInt q.num ++ encodeNat q.den + +/-- A uniform randomized Post-Turing machine: a single finite transition table. -/ +structure RandomMachine where + states : ℕ + transition : Fin (states + 1) → Symbol → Bool → + Option (Fin (states + 1) × Turing.TM0.Stmt Symbol) + +structure Configuration (A : RandomMachine) where + state : Option (Fin (A.states + 1)) + tape : Turing.Tape Symbol + +/-- A halted configuration is absorbing. Each nonhalting tick is exactly one +write or one move, or the detection of halt. -/ +def tick (A : RandomMachine) (c : Configuration A) (bit : Bool) : Configuration A := + match c.state with + | none => c + | some s => match A.transition s c.tape.head bit with + | none => ⟨none, c.tape⟩ + | some (s', action) => + ⟨some s', match action with + | .move d => c.tape.move d + | .write a => c.tape.write a⟩ + +def initial (A : RandomMachine) (input : List Symbol) : Configuration A := + ⟨some 0, Turing.Tape.mk₁ input⟩ + +/-- Bounded execution on a finite prefix of the random tape. -/ +def run (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) : Configuration A := + (List.ofFn bits).foldl (tick A) (initial A input) + +def Outputs (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) (q : ℚ) : Prop := + (run A input bits).state = none ∧ + (run A input bits).tape.right₀ = Turing.ListBlank.mk (encodeRat q) + +end MatchingFPRAS + +namespace ContingencyTables + +open Finset +variable {I J : Type*} [Fintype I] [Fintype J] + +def HasMargins (X : I → J → ℕ) (r : I → ℕ) (c : J → ℕ) : Prop := + (∀ i, ∑ j, X i j = r i) ∧ (∀ j, ∑ i, X i j = c j) + +def Table (r : I → ℕ) (c : J → ℕ) := {X : I → J → ℕ // HasMargins X r c} + +def BoundedTable (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) := + {X : Table r c // ∀ i j, X.val i j ≤ b i j} + +theorem entry_le_row {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ r i := by + rw [← h.1 i] + exact single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ j) + +theorem entry_le_total {X : I → J → ℕ} {r : I → ℕ} {c : J → ℕ} + (h : HasMargins X r c) (i : I) (j : J) : X i j ≤ ∑ i, r i := + (entry_le_row h i j).trans (single_le_sum (fun _ _ => Nat.zero_le _) (mem_univ i)) + +instance table_finite (r : I → ℕ) (c : J → ℕ) : Finite (Table r c) := by + let encode : Table r c → I → J → Fin ((∑ i, r i) + 1) := + fun X i j => ⟨X.val i j, Nat.lt_succ_of_le (entry_le_total X.property i j)⟩ + apply Finite.of_injective encode + intro X Y h + apply Subtype.ext + funext i j + exact congrArg Fin.val (congrFun (congrFun h i) j) + +noncomputable instance table_fintype (r : I → ℕ) (c : J → ℕ) : Fintype (Table r c) := + Fintype.ofFinite _ + +noncomputable instance boundedTable_fintype (r : I → ℕ) (c : J → ℕ) (b : I → J → ℕ) : + Fintype (BoundedTable r c b) := by + classical + unfold BoundedTable + infer_instance + +end ContingencyTables + +namespace ContingencyTables.Algorithms + +open scoped BigOperators +open Filter + +abbrev Machine := MatchingFPRAS.RandomMachine +abbrev Symbol := MatchingFPRAS.Symbol + +def encodeMatrix {m n : ℕ} (X : Fin m → Fin n → ℕ) : List Symbol := + ((List.ofFn fun i => (List.ofFn fun j => MatchingFPRAS.encodeNat (X i j)).flatten)).flatten + +def encodeMargins {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) : List Symbol := + MatchingFPRAS.encodeNat m ++ MatchingFPRAS.encodeNat n ++ + (List.ofFn fun i => MatchingFPRAS.encodeNat (r i)).flatten ++ + (List.ofFn fun j => MatchingFPRAS.encodeNat (c j)).flatten + +def encodeSamplingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) (k : ℕ) : List Symbol := + encodeMargins r c ++ MatchingFPRAS.encodeNat k + +def encodeCountingInput {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : List Symbol := + encodeMargins r c ++ encodeMatrix b ++ MatchingFPRAS.encodeRat ε ++ MatchingFPRAS.encodeRat δ + +/-- The tape alphabet has positive cardinality. -/ +theorem alphabetSize_neZero : NeZero (8 : ℕ) := inferInstance + +/-- A halted tape contains the row-major binary matrix encoding. -/ +def OutputsTable (A : Machine) (input : List Symbol) {t m n : ℕ} + (bits : Fin t → Bool) (X : Fin m → Fin n → ℕ) : Prop := + (MatchingFPRAS.run A input bits).state = none ∧ + @Turing.Tape.right₀ MatchingFPRAS.Symbol (@Fin.instInhabited 8 alphabetSize_neZero) + (MatchingFPRAS.run A input bits).tape = + @Turing.ListBlank.mk Symbol (@Fin.instInhabited 8 alphabetSize_neZero) (encodeMatrix X) + +noncomputable def tableMass (A : Machine) (input : List Symbol) (t : ℕ) + {m n : ℕ} (X : Fin m → Fin n → ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => OutputsTable A input bits X).card : ℝ) / + (2 : ℝ) ^ t + +noncomputable def haltMass (A : Machine) (input : List Symbol) (t : ℕ) : ℝ := by + classical + exact ((Finset.univ.filter fun bits : Fin t → Bool => + (MatchingFPRAS.run A input bits).state = none).card : ℝ) / (2 : ℝ) ^ t + +def samplingSize (n : ℕ) {m : ℕ} (r : Fin m → ℕ) (k : ℕ) : ℕ := + m + n + Nat.clog 2 ((∑ i, r i) + 1) + k + 1 + +/-- Paper 200-01, Theorem main(i): bounded runtime on every random tape +and total variation at most `2⁻ᵏ`, with freely varying dimensions. -/ +def BoundedSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → ∀ k : ℕ, 1 ≤ k → + let input := encodeSamplingInput r c k + let t := C * (samplingSize n r k) ^ d + (∀ bits : Fin t → Bool, ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∑ X : Table r c, + |tableMass A input t X.val - (Fintype.card (Table r c) : ℝ)⁻¹|) / 2 ≤ + ((2 : ℝ) ^ k)⁻¹ + +/-- Paper 200-01, Theorem main(ii): every halted output is feasible, each +table has limiting mass `1/|Ω|`, termination has probability one, and the +expected number of bit operations is bounded by a uniform polynomial. -/ +def ExactSamplingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ) (r : Fin m → ℕ) (c : Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + let input := encodeMargins r c + let tail : ℕ → ℝ := fun t => 1 - haltMass A input t + (∀ t (bits : Fin t → Bool), (MatchingFPRAS.run A input bits).state = none → + ∃ X : Table r c, OutputsTable A input bits X.val) ∧ + (∀ X : Table r c, Tendsto (fun t => tableMass A input t X.val) atTop + (nhds ((Fintype.card (Table r c) : ℝ)⁻¹))) ∧ + Tendsto (haltMass A input) atTop (nhds 1) ∧ + Summable tail ∧ + tsum tail ≤ C * (samplingSize n r 0) ^ d + +noncomputable def count {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) : ℕ := Fintype.card (BoundedTable r c b) + +def countingTime (C d : ℕ) {m n : ℕ} (r : Fin m → ℕ) (c : Fin n → ℕ) + (b : Fin m → Fin n → ℕ) (ε δ : ℚ) : ℕ := + C * ((encodeCountingInput r c b ε δ).length + ⌈ε⁻¹⌉₊ + + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodCountingTapes (A : Machine) {m n : ℕ} + (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ) + (ε δ : ℚ) (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + MatchingFPRAS.Outputs A (encodeCountingInput r c b ε δ) bits q ∧ + (1 - ε) * count r c b ≤ q ∧ q ≤ (1 + ε) * count r c b + +/-- Paper 200-02, Theorem main. The input length includes the rational +accuracy parameters, and infeasible inputs always produce exactly zero. -/ +def CountingStatement : Prop := + ∃ (A : Machine) (C d : ℕ), 0 < C ∧ + ∀ (m n : ℕ), 0 < m → 0 < n → + ∀ (r : Fin m → ℕ) (c : Fin n → ℕ) (b : Fin m → Fin n → ℕ), + (∑ i, r i) = ∑ j, c j → + ∀ ε δ : ℚ, 0 < ε → ε < 1 → 0 < δ → δ < 1 → + let input := encodeCountingInput r c b ε δ + let t := countingTime C d r c b ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ MatchingFPRAS.Outputs A input bits q) ∧ + (count r c b = 0 → ∀ bits : Fin t → Bool, MatchingFPRAS.Outputs A input bits 0) ∧ + ((goodCountingTapes A r c b ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + +end ContingencyTables.Algorithms + +namespace ContingencyTables + +/-- An almost-uniform sampler with polynomial cost on every execution. -/ +theorem boundedSampling : Algorithms.BoundedSamplingStatement := by sorry + +/-- Exact uniform sampling in polynomial expected bit time. -/ +theorem exactSampling : Algorithms.ExactSamplingStatement := by sorry + +/-- A cell-bounded FPRAS, with zero output on every infeasible execution. -/ +theorem counting : Algorithms.CountingStatement := by sorry + +end ContingencyTables + +end OAI diff --git a/tasks/contingency-tables/tests/grade.py b/tasks/contingency-tables/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/contingency-tables/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/contingency-tables/tests/task.json b/tasks/contingency-tables/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3e2df3d30a42dfdcf33401154f3c450a74814315 --- /dev/null +++ b/tasks/contingency-tables/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "ContingencyTables", + "comparator": { + "theorem_names": [ + "OAI.ContingencyTables.boundedSampling", + "OAI.ContingencyTables.exactSampling", + "OAI.ContingencyTables.counting" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18988 +} \ No newline at end of file diff --git a/tasks/contingency-tables/tests/test.sh b/tasks/contingency-tables/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/contingency-tables/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/continuous-circle-weight/environment/Dockerfile b/tasks/continuous-circle-weight/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/continuous-circle-weight/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/continuous-circle-weight/environment/fetch_mathlib.sh b/tasks/continuous-circle-weight/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/continuous-circle-weight/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/continuous-circle-weight/environment/lake-manifest.json b/tasks/continuous-circle-weight/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/continuous-circle-weight/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/continuous-circle-weight/environment/lakefile.lean b/tasks/continuous-circle-weight/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/continuous-circle-weight/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/continuous-circle-weight/environment/lean_setup.sh b/tasks/continuous-circle-weight/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/continuous-circle-weight/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/continuous-circle-weight/environment/pack_submission.py b/tasks/continuous-circle-weight/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/continuous-circle-weight/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/continuous-circle-weight/instruction.md b/tasks/continuous-circle-weight/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..66344f004b7d182564959c36a0f3e6aabf8f3c91 --- /dev/null +++ b/tasks/continuous-circle-weight/instruction.md @@ -0,0 +1,107 @@ +# openai/math challenge `ContinuousCircleWeight` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `ContinuousCircleWeight`, also at `/opt/openai-math/challenges/ContinuousCircleWeight.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal ComplexInnerProductSpace +namespace ContinuousCircleWeight + +abbrev CircleX := AddCircle (1:ℝ) + +abbrev TracialHilbert := lp (fun _ : ℤ × ℤ => ℂ) 2 +abbrev Operator := TracialHilbert →L[ℂ] TracialHilbert + +def circleIdentification : CircleX ≃ₜ Circle := + AddCircle.homeomorphCircle (by norm_num) +def circleFunction (f : C(CircleX, ℝ)) (z : ℂ) : ℂ := + if hz : ‖z‖ = 1 then f (circleIdentification.symm ⟨z, mem_sphere_zero_iff_norm.mpr hz⟩) else 0 + +def negativeLog (t : ℝ) : ℝ≥0∞ := + if t = 0 then ∞ else ENNReal.ofReal (-Real.log t) + +structure IsTracialRotation (θ : ℝ) (U V : unitary Operator) + (e : TracialHilbert) : Prop where + relation : (V : Operator) * (U : Operator) = + Complex.exp (2 * Real.pi * θ * Complex.I) • ((U : Operator) * (V : Operator)) + moments : ∀ m n : ℤ, + inner ℂ e (((U ^ m * V ^ n : unitary Operator) : Operator) e) = + if m = 0 ∧ n = 0 then 1 else 0 + cyclic : (Submodule.span ℂ + (Set.range (fun mn : ℤ × ℤ => + ((U ^ mn.1 * V ^ mn.2 : unitary Operator) : Operator) e))).topologicalClosure = ⊤ + +def rotationAlgebra (U V : unitary Operator) : Set Operator := + Set.centralizer (Set.centralizer ({(U : Operator), (V : Operator)} : Set Operator)) + +def weightedRotation (U V : unitary Operator) (f : C(CircleX, ℝ)) : Operator := + (U : Operator) * cfc (circleFunction f) (V : Operator) + +def MainStatement : Prop := + ∃ (θ : ℝ) (f : C(CircleX, ℝ)) (U V : unitary Operator) (e : TracialHilbert), + 0 < θ ∧ θ < 1 ∧ Irrational θ ∧ + IsTracialRotation θ U V e ∧ + (∀ x, 0 ≤ f x ∧ f x ≤ 1) ∧ + (∃ z : CircleX, ∀ x, f x = 0 ↔ x = z) ∧ + (∫⁻ x, negativeLog (f x) ∂(volume : Measure CircleX)) = ∞ ∧ + ∀ p : Operator, p ∈ rotationAlgebra U V → IsStarProjection p → + (1 - p) * weightedRotation U V f * p = 0 → p = 0 ∨ p = 1 + +theorem main_theorem : MainStatement := by + sorry + +end ContinuousCircleWeight +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ContinuousCircleWeight.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ContinuousCircleWeight.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/continuous-circle-weight/solution/closure.txt b/tasks/continuous-circle-weight/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b3101460862e6481226d305fad119c6e0b02c8c --- /dev/null +++ b/tasks/continuous-circle-weight/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Analysis.RotationWeights.ActualDigits +OAI.Analysis.RotationWeights.BorelTransport +OAI.Analysis.RotationWeights.BorelWeights +OAI.Analysis.RotationWeights.Concentration +OAI.Analysis.RotationWeights.ConditionalBounds +OAI.Analysis.RotationWeights.ContinuousWeight +OAI.Analysis.RotationWeights.Convolution +OAI.Analysis.RotationWeights.CoordinateLaws +OAI.Analysis.RotationWeights.CouplingMoments +OAI.Analysis.RotationWeights.Covariance +OAI.Analysis.RotationWeights.CrossingEstimates +OAI.Analysis.RotationWeights.Decomposable +OAI.Analysis.RotationWeights.DigitCouplings +OAI.Analysis.RotationWeights.Discrepancy +OAI.Analysis.RotationWeights.EndpointMoments +OAI.Analysis.RotationWeights.FiberActions +OAI.Analysis.RotationWeights.Fibers +OAI.Analysis.RotationWeights.FieldExtraction +OAI.Analysis.RotationWeights.FiniteSampling +OAI.Analysis.RotationWeights.FourierSampling +OAI.Analysis.RotationWeights.FunctionalCalculus +OAI.Analysis.RotationWeights.GraphTransfer +OAI.Analysis.RotationWeights.LaurentCoefficients +OAI.Analysis.RotationWeights.LogarithmicDrops +OAI.Analysis.RotationWeights.Main +OAI.Analysis.RotationWeights.MaskedEstimates +OAI.Analysis.RotationWeights.MeasurableWeight +OAI.Analysis.RotationWeights.Model +OAI.Analysis.RotationWeights.NestedAngles +OAI.Analysis.RotationWeights.OrbitBounds +OAI.Analysis.RotationWeights.Parameters +OAI.Analysis.RotationWeights.PhaseWeights +OAI.Analysis.RotationWeights.Polar +OAI.Analysis.RotationWeights.ProductSampling +OAI.Analysis.RotationWeights.ProjectionFields +OAI.Analysis.RotationWeights.ProjectionIdentity +OAI.Analysis.RotationWeights.RadixDigits +OAI.Analysis.RotationWeights.RationalGraphs +OAI.Analysis.RotationWeights.Regular +OAI.Analysis.RotationWeights.ReturnSamples +OAI.Analysis.RotationWeights.Rounding +OAI.Analysis.RotationWeights.SamplingBounds +OAI.Analysis.RotationWeights.SamplingStage +OAI.Analysis.RotationWeights.TaggedEvents +OAI.Analysis.RotationWeights.TailBounds +OAI.Analysis.RotationWeights.TensorBasis +OAI.Analysis.RotationWeights.Thresholds +OAI.Analysis.RotationWeights.TracialAction +OAI.Analysis.RotationWeights.Transport +OAI.Analysis.RotationWeights.TrialBounds +OAI.Analysis.RotationWeights.WeakSampling diff --git a/tasks/continuous-circle-weight/solution/reference.py b/tasks/continuous-circle-weight/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/continuous-circle-weight/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/continuous-circle-weight/solution/solve.sh b/tasks/continuous-circle-weight/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1dc6d0c45289ad862eb6a5aa770ca2f866ae24eb --- /dev/null +++ b/tasks/continuous-circle-weight/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ContinuousCircleWeight, i.e. module OAI.Analysis.RotationWeights.Main and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.RotationWeights.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ContinuousCircleWeight" diff --git a/tasks/continuous-circle-weight/task.toml b/tasks/continuous-circle-weight/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5270a0cd487bbb27c0520812d3f7b2690dad3d0b --- /dev/null +++ b/tasks/continuous-circle-weight/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/continuous-circle-weight" +version = "1.0.0" +description = "Prove ContinuousCircleWeight (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ContinuousCircleWeight.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ContinuousCircleWeight" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.ContinuousCircleWeight.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.RotationWeights.Main" +reference_modules = 51 +reference_lean_bytes = 908147 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1217 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12517 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/continuous-circle-weight/tests/Challenge.lean b/tasks/continuous-circle-weight/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b9750f68cb459a42c4860a83295e09da1b2b208 --- /dev/null +++ b/tasks/continuous-circle-weight/tests/Challenge.lean @@ -0,0 +1,56 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal ComplexInnerProductSpace +namespace ContinuousCircleWeight + +abbrev CircleX := AddCircle (1:ℝ) + +abbrev TracialHilbert := lp (fun _ : ℤ × ℤ => ℂ) 2 +abbrev Operator := TracialHilbert →L[ℂ] TracialHilbert + +def circleIdentification : CircleX ≃ₜ Circle := + AddCircle.homeomorphCircle (by norm_num) +def circleFunction (f : C(CircleX, ℝ)) (z : ℂ) : ℂ := + if hz : ‖z‖ = 1 then f (circleIdentification.symm ⟨z, mem_sphere_zero_iff_norm.mpr hz⟩) else 0 + +def negativeLog (t : ℝ) : ℝ≥0∞ := + if t = 0 then ∞ else ENNReal.ofReal (-Real.log t) + +structure IsTracialRotation (θ : ℝ) (U V : unitary Operator) + (e : TracialHilbert) : Prop where + relation : (V : Operator) * (U : Operator) = + Complex.exp (2 * Real.pi * θ * Complex.I) • ((U : Operator) * (V : Operator)) + moments : ∀ m n : ℤ, + inner ℂ e (((U ^ m * V ^ n : unitary Operator) : Operator) e) = + if m = 0 ∧ n = 0 then 1 else 0 + cyclic : (Submodule.span ℂ + (Set.range (fun mn : ℤ × ℤ => + ((U ^ mn.1 * V ^ mn.2 : unitary Operator) : Operator) e))).topologicalClosure = ⊤ + +def rotationAlgebra (U V : unitary Operator) : Set Operator := + Set.centralizer (Set.centralizer ({(U : Operator), (V : Operator)} : Set Operator)) + +def weightedRotation (U V : unitary Operator) (f : C(CircleX, ℝ)) : Operator := + (U : Operator) * cfc (circleFunction f) (V : Operator) + +def MainStatement : Prop := + ∃ (θ : ℝ) (f : C(CircleX, ℝ)) (U V : unitary Operator) (e : TracialHilbert), + 0 < θ ∧ θ < 1 ∧ Irrational θ ∧ + IsTracialRotation θ U V e ∧ + (∀ x, 0 ≤ f x ∧ f x ≤ 1) ∧ + (∃ z : CircleX, ∀ x, f x = 0 ↔ x = z) ∧ + (∫⁻ x, negativeLog (f x) ∂(volume : Measure CircleX)) = ∞ ∧ + ∀ p : Operator, p ∈ rotationAlgebra U V → IsStarProjection p → + (1 - p) * weightedRotation U V f * p = 0 → p = 0 ∨ p = 1 + +theorem main_theorem : MainStatement := by + sorry + +end ContinuousCircleWeight +end + +end OAI diff --git a/tasks/continuous-circle-weight/tests/grade.py b/tasks/continuous-circle-weight/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/continuous-circle-weight/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/continuous-circle-weight/tests/task.json b/tasks/continuous-circle-weight/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..81ba34bdbcf7c6bebed8ff5f4af3b66c69ce661c --- /dev/null +++ b/tasks/continuous-circle-weight/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ContinuousCircleWeight", + "comparator": { + "theorem_names": [ + "OAI.ContinuousCircleWeight.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11617 +} \ No newline at end of file diff --git a/tasks/continuous-circle-weight/tests/test.sh b/tasks/continuous-circle-weight/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/continuous-circle-weight/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/continuum-transition/environment/Dockerfile b/tasks/continuum-transition/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/continuum-transition/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/continuum-transition/environment/fetch_mathlib.sh b/tasks/continuum-transition/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/continuum-transition/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/continuum-transition/environment/lake-manifest.json b/tasks/continuum-transition/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/continuum-transition/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/continuum-transition/environment/lakefile.lean b/tasks/continuum-transition/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/continuum-transition/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/continuum-transition/environment/lean_setup.sh b/tasks/continuum-transition/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/continuum-transition/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/continuum-transition/environment/pack_submission.py b/tasks/continuum-transition/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/continuum-transition/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/continuum-transition/instruction.md b/tasks/continuum-transition/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..305dff55bd8339c45d5755b0715d998e5c29319f --- /dev/null +++ b/tasks/continuum-transition/instruction.md @@ -0,0 +1,115 @@ +# openai/math challenge `ContinuumTransition` (family 228) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 228 of the release, *Continuum phase transitions for radial pair potentials* +(Probability and statistical mechanics). The family as a whole: Constructs stable distance-dependent pair interactions for three-dimensional classical particles with a first-order phase transition: the canonical free energy has a derivative jump at one inverse temperature throughout an open density interval. One potential has a divergent repulsive core; another is bounded and continuous with an integrable power-law tail, realizing the type of transition sought in Simon's continuum problem. + +The challenge is `ContinuumTransition`, also at `/opt/openai-math/challenges/ContinuumTransition.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped Topology BigOperators ENNReal +open Filter MeasureTheory Set + +namespace ContinuumTemperature + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +noncomputable def radialPotential (φ : ℝ → ℝ) (x : Space) : EReal := + if x = 0 then ⊤ else (φ ‖x‖ : EReal) + +noncomputable def energy (φ : ℝ → ℝ) {N : ℕ} (x : Fin N → Space) : EReal := + ∑ i : Fin N, ∑ j ∈ Finset.univ.filter (fun j : Fin N => i < j), + radialPotential φ (x i - x j) + +def Admissible (φ : ℝ → ℝ) : Prop := + Measurable (radialPotential φ) ∧ + (∀ a b : ℝ, 0 < a → a ≤ b → + BddAbove (φ '' Icc a b) ∧ BddBelow (φ '' Icc a b)) ∧ + Tendsto φ (𝓝[>] (0 : ℝ)) atTop ∧ + (∃ r₁ r₂ a : ℝ, 0 < r₁ ∧ r₁ < r₂ ∧ 0 < a ∧ + ∀ r ∈ Icc r₁ r₂, φ r ≤ -a) ∧ + (∃ R : ℝ, 0 < R ∧ IntegrableOn (fun r : ℝ => r ^ 2 * |φ r|) (Ioi R)) ∧ + (∃ B : ℝ, ∀ (N : ℕ) (x : Fin N → Space), + ((-B * (N : ℝ) : ℝ) : EReal) ≤ energy φ x) + +def cube (L : ℝ) : Set Space := + {x | ∀ i, x i ∈ Icc (-L / 2) (L / 2)} + +noncomputable def boltzmann (φ : ℝ → ℝ) (β : ℝ) {N : ℕ} + (x : Fin N → Space) : ℝ := + if energy φ x = ⊤ then 0 else Real.exp (-β * (energy φ x).toReal) + +noncomputable def partition (φ : ℝ → ℝ) (β L : ℝ) (N : ℕ) : ℝ := + if N = 0 then 1 else + (1 / (N.factorial : ℝ)) * + ∫ x in {x : Fin N → Space | ∀ i, x i ∈ cube L}, boltzmann φ β x + +def HasCanonicalFreeEnergy (φ : ℝ → ℝ) (f : ℝ → ℝ → ℝ) : Prop := + ∀ β ρ : ℝ, 0 < β → 0 < ρ → + Tendsto (fun L : ℝ => L⁻¹ ^ 3 * Real.log (partition φ β L ⌊ρ * L ^ 3⌋₊)) + atTop (𝓝 (-β * f β ρ)) + +def MainStatement : Prop := + ∃ (φ : ℝ → ℝ) (f : ℝ → ℝ → ℝ) (I : Set ℝ) (βc : ℝ), + Admissible φ ∧ + Asymptotics.IsLittleO atTop φ (fun r : ℝ => r ^ (-3 : ℤ)) ∧ + HasCanonicalFreeEnergy φ f ∧ + IsOpen I ∧ OrdConnected I ∧ I.Nonempty ∧ I ⊆ Ioi 0 ∧ + βc ∈ Ioo (1 / 2 : ℝ) (3 / 2 : ℝ) ∧ + ∀ ρ ∈ I, ∃ dminus dplus : ℝ, + HasDerivWithinAt (fun β => f β ρ) dminus (Iic βc) βc ∧ + HasDerivWithinAt (fun β => f β ρ) dplus (Ici βc) βc ∧ + dplus < dminus + +theorem main_theorem : MainStatement := by + sorry + +end ContinuumTemperature + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ContinuumTransition.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ContinuumTemperature.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/continuum-transition/solution/closure.txt b/tasks/continuum-transition/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ab408f18418e8c045bc02fee476910122bda1d6 --- /dev/null +++ b/tasks/continuum-transition/solution/closure.txt @@ -0,0 +1,161 @@ +OAI.Probability.ContinuumTransition.ActiveLimits +OAI.Probability.ContinuumTransition.ActiveSupports +OAI.Probability.ContinuumTransition.ActiveUniform +OAI.Probability.ContinuumTransition.AppendAttraction +OAI.Probability.ContinuumTransition.ApproximateSupports +OAI.Probability.ContinuumTransition.Assignments +OAI.Probability.ContinuumTransition.BadEndpoints +OAI.Probability.ContinuumTransition.BlockEnergy +OAI.Probability.ContinuumTransition.BlockPartition +OAI.Probability.ContinuumTransition.BoundarySum +OAI.Probability.ContinuumTransition.BoxTiling +OAI.Probability.ContinuumTransition.CanonicalIntegral +OAI.Probability.ContinuumTransition.CanonicalLimit +OAI.Probability.ContinuumTransition.CellEnergy +OAI.Probability.ContinuumTransition.CoerciveCanonical +OAI.Probability.ContinuumTransition.CompactHulls +OAI.Probability.ContinuumTransition.CompactSequences +OAI.Probability.ContinuumTransition.ConstructionBounds +OAI.Probability.ContinuumTransition.ConstructionCap +OAI.Probability.ContinuumTransition.ConstructionLimit +OAI.Probability.ContinuumTransition.ConstructionLocation +OAI.Probability.ContinuumTransition.ConstructionMasses +OAI.Probability.ContinuumTransition.ConstructionSequence +OAI.Probability.ContinuumTransition.ConstructionStage +OAI.Probability.ContinuumTransition.ConstructionStep +OAI.Probability.ContinuumTransition.ConvexSupport +OAI.Probability.ContinuumTransition.ConvexUniform +OAI.Probability.ContinuumTransition.ConvolutionLimit +OAI.Probability.ContinuumTransition.CubeBoundary +OAI.Probability.ContinuumTransition.CubeCoercivity +OAI.Probability.ContinuumTransition.DensityBounds +OAI.Probability.ContinuumTransition.DensityLimit +OAI.Probability.ContinuumTransition.DensityUniform +OAI.Probability.ContinuumTransition.ExactAssignments +OAI.Probability.ContinuumTransition.FiniteBlocks +OAI.Probability.ContinuumTransition.FiniteBounds +OAI.Probability.ContinuumTransition.FiniteProduct +OAI.Probability.ContinuumTransition.FixedOccupation +OAI.Probability.ContinuumTransition.FreeFamily +OAI.Probability.ContinuumTransition.FreeGeometry +OAI.Probability.ContinuumTransition.FreeGrand +OAI.Probability.ContinuumTransition.FreeIdeal +OAI.Probability.ContinuumTransition.FreeLimit +OAI.Probability.ContinuumTransition.FreeRoots +OAI.Probability.ContinuumTransition.FreeUpper +OAI.Probability.ContinuumTransition.GeneralGrand +OAI.Probability.ContinuumTransition.GeneralLabels +OAI.Probability.ContinuumTransition.GenericGibbs +OAI.Probability.ContinuumTransition.GibbsBridge +OAI.Probability.ContinuumTransition.GibbsIntegrability +OAI.Probability.ContinuumTransition.GibbsMonotonicity +OAI.Probability.ContinuumTransition.GibbsQuadratic +OAI.Probability.ContinuumTransition.GrandBlocks +OAI.Probability.ContinuumTransition.GrandDomination +OAI.Probability.ContinuumTransition.GrandFinite +OAI.Probability.ContinuumTransition.GrandInteraction +OAI.Probability.ContinuumTransition.GrandLinearity +OAI.Probability.ContinuumTransition.GrandOn +OAI.Probability.ContinuumTransition.GrandPartition +OAI.Probability.ContinuumTransition.GrandPerturbation +OAI.Probability.ContinuumTransition.GrandProduct +OAI.Probability.ContinuumTransition.GridBoundary +OAI.Probability.ContinuumTransition.GridCover +OAI.Probability.ContinuumTransition.GridVolume +OAI.Probability.ContinuumTransition.IdealSlopes +OAI.Probability.ContinuumTransition.InitialTriple +OAI.Probability.ContinuumTransition.InitialUniform +OAI.Probability.ContinuumTransition.InnerGrand +OAI.Probability.ContinuumTransition.InnerGrid +OAI.Probability.ContinuumTransition.KacBlocks +OAI.Probability.ContinuumTransition.KacBounds +OAI.Probability.ContinuumTransition.KacEnergy +OAI.Probability.ContinuumTransition.KacGrid +OAI.Probability.ContinuumTransition.KacKernel +OAI.Probability.ContinuumTransition.KacLimit +OAI.Probability.ContinuumTransition.KacRows +OAI.Probability.ContinuumTransition.KacUniform +OAI.Probability.ContinuumTransition.LabelConvolution +OAI.Probability.ContinuumTransition.LaplaceBounds +OAI.Probability.ContinuumTransition.LaplaceEventual +OAI.Probability.ContinuumTransition.LaplacePrinciple +OAI.Probability.ContinuumTransition.LatticeBounds +OAI.Probability.ContinuumTransition.LocalSupports +OAI.Probability.ContinuumTransition.LowerBounds +OAI.Probability.ContinuumTransition.LowerComparison +OAI.Probability.ContinuumTransition.LowerEnergy +OAI.Probability.ContinuumTransition.LowerGibbs +OAI.Probability.ContinuumTransition.LowerKac +OAI.Probability.ContinuumTransition.LowerLimit +OAI.Probability.ContinuumTransition.LowerPressure +OAI.Probability.ContinuumTransition.LowerRows +OAI.Probability.ContinuumTransition.Main +OAI.Probability.ContinuumTransition.MaskedComparison +OAI.Probability.ContinuumTransition.MaskedReference +OAI.Probability.ContinuumTransition.MeanFieldAttainment +OAI.Probability.ContinuumTransition.Model +OAI.Probability.ContinuumTransition.ModifiedComparison +OAI.Probability.ContinuumTransition.ModifiedEnergy +OAI.Probability.ContinuumTransition.ModifiedFinite +OAI.Probability.ContinuumTransition.ModifiedInsertion +OAI.Probability.ContinuumTransition.ModifiedMoments +OAI.Probability.ContinuumTransition.MomentBootstrap +OAI.Probability.ContinuumTransition.MomentBounds +OAI.Probability.ContinuumTransition.MomentEnergy +OAI.Probability.ContinuumTransition.MomentExpectations +OAI.Probability.ContinuumTransition.NearbySupport +OAI.Probability.ContinuumTransition.OccupationEnergy +OAI.Probability.ContinuumTransition.OccupationProducts +OAI.Probability.ContinuumTransition.PackingBalls +OAI.Probability.ContinuumTransition.PackingGeometry +OAI.Probability.ContinuumTransition.PackingLimit +OAI.Probability.ContinuumTransition.PackingLower +OAI.Probability.ContinuumTransition.PackingPressure +OAI.Probability.ContinuumTransition.PackingUpper +OAI.Probability.ContinuumTransition.PairEnergy +OAI.Probability.ContinuumTransition.PairMoments +OAI.Probability.ContinuumTransition.Persistence +OAI.Probability.ContinuumTransition.PhysicalInsertion +OAI.Probability.ContinuumTransition.PhysicalMeanField +OAI.Probability.ContinuumTransition.PhysicalMoments +OAI.Probability.ContinuumTransition.PhysicalPerturbation +OAI.Probability.ContinuumTransition.PhysicalPressure +OAI.Probability.ContinuumTransition.PhysicalUniform +OAI.Probability.ContinuumTransition.PressureDuality +OAI.Probability.ContinuumTransition.PressureGeometry +OAI.Probability.ContinuumTransition.PressureRegularity +OAI.Probability.ContinuumTransition.ProductEquality +OAI.Probability.ContinuumTransition.ProfileBounds +OAI.Probability.ContinuumTransition.ProfileTail +OAI.Probability.ContinuumTransition.QuadraticBlocks +OAI.Probability.ContinuumTransition.QuadraticGrand +OAI.Probability.ContinuumTransition.QuadraticLaplace +OAI.Probability.ContinuumTransition.QuadraticTransform +OAI.Probability.ContinuumTransition.RadialKernel +OAI.Probability.ContinuumTransition.Regroup +OAI.Probability.ContinuumTransition.RootVolume +OAI.Probability.ContinuumTransition.ScaledActive +OAI.Probability.ContinuumTransition.ScaledBounded +OAI.Probability.ContinuumTransition.ScaledLocalization +OAI.Probability.ContinuumTransition.ShellGeometry +OAI.Probability.ContinuumTransition.SpatialProducts +OAI.Probability.ContinuumTransition.Stability +OAI.Probability.ContinuumTransition.SubgradientBounds +OAI.Probability.ContinuumTransition.SupportGenerators +OAI.Probability.ContinuumTransition.TailBounds +OAI.Probability.ContinuumTransition.TailComparison +OAI.Probability.ContinuumTransition.TailPressure +OAI.Probability.ContinuumTransition.TetraVolume +OAI.Probability.ContinuumTransition.Tetrahedron +OAI.Probability.ContinuumTransition.ThermodynamicExtension +OAI.Probability.ContinuumTransition.TransformAttainment +OAI.Probability.ContinuumTransition.TransformBounds +OAI.Probability.ContinuumTransition.TrialConfigurations +OAI.Probability.ContinuumTransition.TriangleGeometry +OAI.Probability.ContinuumTransition.TriangleSeparation +OAI.Probability.ContinuumTransition.TripleState +OAI.Probability.ContinuumTransition.UniformMin +OAI.Probability.ContinuumTransition.UpperComparison +OAI.Probability.ContinuumTransition.UpperKac +OAI.Probability.ContinuumTransition.UpperLimit +OAI.Probability.ContinuumTransition.UpperPressure diff --git a/tasks/continuum-transition/solution/reference.py b/tasks/continuum-transition/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/continuum-transition/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/continuum-transition/solution/solve.sh b/tasks/continuum-transition/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..545ff56d5442ce8e54d9727fe84008a244992180 --- /dev/null +++ b/tasks/continuum-transition/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ContinuumTransition, i.e. module OAI.Probability.ContinuumTransition.Main and the +# 161 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ContinuumTransition.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ContinuumTransition" diff --git a/tasks/continuum-transition/task.toml b/tasks/continuum-transition/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47661ac99db673a8cc199f4ea3f474c326bc2831 --- /dev/null +++ b/tasks/continuum-transition/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/continuum-transition" +version = "1.0.0" +description = "Prove ContinuumTransition (openai/math family 228: Continuum phase transitions for radial pair potentials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ContinuumTransition.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ContinuumTransition" +family = "228" +family_title = "Continuum phase transitions for radial pair potentials" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ContinuumTemperature.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ContinuumTransition.Main" +reference_modules = 161 +reference_lean_bytes = 697604 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1607 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12327 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/continuum-transition/tests/Challenge.lean b/tasks/continuum-transition/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b0ec4defad39d4aadcb9c07cd64478e568a0316 --- /dev/null +++ b/tasks/continuum-transition/tests/Challenge.lean @@ -0,0 +1,64 @@ +import Mathlib + +namespace OAI + +open scoped Topology BigOperators ENNReal +open Filter MeasureTheory Set + +namespace ContinuumTemperature + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +noncomputable def radialPotential (φ : ℝ → ℝ) (x : Space) : EReal := + if x = 0 then ⊤ else (φ ‖x‖ : EReal) + +noncomputable def energy (φ : ℝ → ℝ) {N : ℕ} (x : Fin N → Space) : EReal := + ∑ i : Fin N, ∑ j ∈ Finset.univ.filter (fun j : Fin N => i < j), + radialPotential φ (x i - x j) + +def Admissible (φ : ℝ → ℝ) : Prop := + Measurable (radialPotential φ) ∧ + (∀ a b : ℝ, 0 < a → a ≤ b → + BddAbove (φ '' Icc a b) ∧ BddBelow (φ '' Icc a b)) ∧ + Tendsto φ (𝓝[>] (0 : ℝ)) atTop ∧ + (∃ r₁ r₂ a : ℝ, 0 < r₁ ∧ r₁ < r₂ ∧ 0 < a ∧ + ∀ r ∈ Icc r₁ r₂, φ r ≤ -a) ∧ + (∃ R : ℝ, 0 < R ∧ IntegrableOn (fun r : ℝ => r ^ 2 * |φ r|) (Ioi R)) ∧ + (∃ B : ℝ, ∀ (N : ℕ) (x : Fin N → Space), + ((-B * (N : ℝ) : ℝ) : EReal) ≤ energy φ x) + +def cube (L : ℝ) : Set Space := + {x | ∀ i, x i ∈ Icc (-L / 2) (L / 2)} + +noncomputable def boltzmann (φ : ℝ → ℝ) (β : ℝ) {N : ℕ} + (x : Fin N → Space) : ℝ := + if energy φ x = ⊤ then 0 else Real.exp (-β * (energy φ x).toReal) + +noncomputable def partition (φ : ℝ → ℝ) (β L : ℝ) (N : ℕ) : ℝ := + if N = 0 then 1 else + (1 / (N.factorial : ℝ)) * + ∫ x in {x : Fin N → Space | ∀ i, x i ∈ cube L}, boltzmann φ β x + +def HasCanonicalFreeEnergy (φ : ℝ → ℝ) (f : ℝ → ℝ → ℝ) : Prop := + ∀ β ρ : ℝ, 0 < β → 0 < ρ → + Tendsto (fun L : ℝ => L⁻¹ ^ 3 * Real.log (partition φ β L ⌊ρ * L ^ 3⌋₊)) + atTop (𝓝 (-β * f β ρ)) + +def MainStatement : Prop := + ∃ (φ : ℝ → ℝ) (f : ℝ → ℝ → ℝ) (I : Set ℝ) (βc : ℝ), + Admissible φ ∧ + Asymptotics.IsLittleO atTop φ (fun r : ℝ => r ^ (-3 : ℤ)) ∧ + HasCanonicalFreeEnergy φ f ∧ + IsOpen I ∧ OrdConnected I ∧ I.Nonempty ∧ I ⊆ Ioi 0 ∧ + βc ∈ Ioo (1 / 2 : ℝ) (3 / 2 : ℝ) ∧ + ∀ ρ ∈ I, ∃ dminus dplus : ℝ, + HasDerivWithinAt (fun β => f β ρ) dminus (Iic βc) βc ∧ + HasDerivWithinAt (fun β => f β ρ) dplus (Ici βc) βc ∧ + dplus < dminus + +theorem main_theorem : MainStatement := by + sorry + +end ContinuumTemperature + +end OAI diff --git a/tasks/continuum-transition/tests/grade.py b/tasks/continuum-transition/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/continuum-transition/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/continuum-transition/tests/task.json b/tasks/continuum-transition/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..08d7923c110bebde67141a568a84990ab5a1f713 --- /dev/null +++ b/tasks/continuum-transition/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ContinuumTransition", + "comparator": { + "theorem_names": [ + "OAI.ContinuumTemperature.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11427 +} \ No newline at end of file diff --git a/tasks/continuum-transition/tests/test.sh b/tasks/continuum-transition/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/continuum-transition/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coordinate-sweeps/environment/Dockerfile b/tasks/coordinate-sweeps/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coordinate-sweeps/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coordinate-sweeps/environment/fetch_mathlib.sh b/tasks/coordinate-sweeps/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coordinate-sweeps/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coordinate-sweeps/environment/lake-manifest.json b/tasks/coordinate-sweeps/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coordinate-sweeps/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coordinate-sweeps/environment/lakefile.lean b/tasks/coordinate-sweeps/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coordinate-sweeps/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coordinate-sweeps/environment/lean_setup.sh b/tasks/coordinate-sweeps/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coordinate-sweeps/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coordinate-sweeps/environment/pack_submission.py b/tasks/coordinate-sweeps/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coordinate-sweeps/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coordinate-sweeps/instruction.md b/tasks/coordinate-sweeps/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a709796108eae70b0721fd4b7a2bc86b0856b88e --- /dev/null +++ b/tasks/coordinate-sweeps/instruction.md @@ -0,0 +1,365 @@ +# openai/math challenge `CoordinateSweeps` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `CoordinateSweeps`, also at `/opt/openai-math/challenges/CoordinateSweeps.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Conditional moments for one ordered coordinate sweep on power-of-two rectangular +grids. The line law mixes uniform permutations with a binary coordinate sweep. +The trace is unnormalized, and the trajectory cost uses falling factorials. +-/ + +noncomputable section + +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder ComplexConjugate MatrixOrder ENNReal +open MeasureTheory +attribute [local instance] Classical.propDecidable + +namespace CoordinateSweeps + +structure FiniteLaw (Ω : Type*) where + mass : Ω → ℝ + nonneg : ∀ x, 0 ≤ mass x + total : ∑ᶠ x, mass x = 1 + +namespace FiniteLaw + +variable {Ω X Y : Type*} + +instance : CoeFun (FiniteLaw Ω) (fun _ => Ω → ℝ) := ⟨FiniteLaw.mass⟩ + +@[ext] theorem ext {μ ν : FiniteLaw Ω} (h : ∀ x, μ x = ν x) : μ = ν := by + cases μ + cases ν + congr + exact funext h + +variable [Fintype Ω] [Fintype X] [Fintype Y] + +@[simp] theorem sum_mass (μ : FiniteLaw Ω) : ∑ x, μ x = 1 := by + simpa only [finsum_eq_sum_of_fintype] using μ.total + +def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FiniteLaw Ω where + mass _ := (Fintype.card Ω : ℝ)⁻¹ + nonneg _ := inv_nonneg.mpr (Nat.cast_nonneg _) + total := by + rw [finsum_eq_sum_of_fintype] + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + exact mul_inv_cancel₀ (by exact_mod_cast Fintype.card_ne_zero) + +def map (μ : FiniteLaw Ω) (f : Ω → X) : FiniteLaw X where + mass y := ∑ x, if f x = y then μ x else 0 + nonneg y := Finset.sum_nonneg (fun x _ => by split_ifs; exact μ.nonneg x; exact le_rfl) + total := by + rw [finsum_eq_sum_of_fintype] + classical + rw [Finset.sum_comm] + simp [μ.sum_mass] + +end FiniteLaw + +abbrev Cube (d : ℕ) := Fin d → Bool + +def pairSwitch {L : Type*} (bits : L → Bool) : Equiv.Perm (Bool × L) where + toFun x := (Bool.xor x.1 (bits x.2), x.2) + invFun x := (Bool.xor x.1 (bits x.2), x.2) + left_inv point := by + rcases point with ⟨bit, label⟩ + change ((bit ^^ bits label) ^^ bits label, label) = (bit, label) + cases bit <;> cases bits label <;> simp + right_inv point := by + rcases point with ⟨bit, label⟩ + change ((bit ^^ bits label) ^^ bits label, label) = (bit, label) + cases bit <;> cases bits label <;> simp + +def binaryLayer {d : ℕ} (j : Fin d) (bits : ({k : Fin d // k ≠ j} → Bool) → Bool) : + Equiv.Perm (Cube d) := + (Equiv.funSplitAt j Bool).trans ((pairSwitch bits).trans (Equiv.funSplitAt j Bool).symm) + +/-- Coordinate zero acts first. -/ +def orderedProduct {G : Type*} [Monoid G] {d : ℕ} (g : Fin d → G) : G := + (List.ofFn g).reverse.prod + +abbrev BinaryChoices (d : ℕ) := ∀ j : Fin d, ({k : Fin d // k ≠ j} → Bool) → Bool + +instance (d : ℕ) : Nonempty (BinaryChoices d) := ⟨fun _ _ => false⟩ + +def binarySweep (d : ℕ) (bits : BinaryChoices d) : Equiv.Perm (Cube d) := + orderedProduct (fun j => binaryLayer j (bits j)) + +def binaryLaw (d : ℕ) : FiniteLaw (Equiv.Perm (Cube d)) := + (FiniteLaw.uniform (BinaryChoices d)).map (binarySweep d) + +structure Grid where + b : ℕ + positive : 0 < b + bits : Fin b → ℕ + +namespace Grid + +def size (G : Grid) : ℕ := ∏ j, 2 ^ G.bits j + +abbrev Slot (G : Grid) := ∀ j, Cube (G.bits j) + +abbrev Line (G : Grid) (j : Fin G.b) := ∀ k : {k : Fin G.b // k ≠ j}, Cube (G.bits k) + +abbrev Choices (G : Grid) := ∀ j, G.Line j → Equiv.Perm (Cube (G.bits j)) + +def fiberPerm {A B : Type*} (p : B → Equiv.Perm A) : Equiv.Perm (A × B) where + toFun x := (p x.2 x.1, x.2) + invFun x := ((p x.2).symm x.1, x.2) + left_inv x := by simp + right_inv x := by simp + +def stage (G : Grid) (ω : G.Choices) (j : Fin G.b) : Equiv.Perm G.Slot := + (Equiv.piSplitAt j (fun k => Cube (G.bits k))).trans + ((fiberPerm (ω j)).trans (Equiv.piSplitAt j (fun k => Cube (G.bits k))).symm) + +def boundary (G : Grid) (ω : G.Choices) (t : ℕ) : Equiv.Perm G.Slot := + ((List.ofFn (G.stage ω)).take t).reverse.prod + +def sweep (G : Grid) (ω : G.Choices) : Equiv.Perm G.Slot := G.boundary ω G.b + +/-- The side lengths are in `[R, R²]`, where the single global scale is `R = 2^r`. -/ +def Allowed (G : Grid) (r : ℕ) : Prop := ∀ j, r ≤ G.bits j ∧ G.bits j ≤ 2 * r + +/-- Full disjoint paths, including every boundary of the ordered sweep. -/ +structure Holes (G : Grid) (h : ℕ) where + path : Fin h → Fin (G.b + 1) → G.Slot + disjoint : ∀ t, Function.Injective (fun i => path i t) + coordinate_step : ∀ i (j : Fin G.b) (k : Fin G.b), k ≠ j → + path i j.succ k = path i j.castSucc k + +namespace Holes + +variable {G : Grid} {h : ℕ} + +def Compatible (H : G.Holes h) (ω : G.Choices) : Prop := + ∀ i (t : Fin (G.b + 1)), G.boundary ω t (H.path i 0) = H.path i t + +def Feasible (H : G.Holes h) : Prop := ∃ ω, H.Compatible ω + +def lineCount (H : G.Holes h) (j : Fin G.b) (L : G.Line j) : ℕ := + (Finset.univ.filter (fun i : Fin h => + (fun k : {k : Fin G.b // k ≠ j} => H.path i j.castSucc k) = L)).card + +def cost (H : G.Holes h) : ℝ := + ∑ j, ∑ L : G.Line j, + Real.log (((2 ^ G.bits j : ℕ) : ℝ) ^ H.lineCount j L / + ((2 ^ G.bits j).descFactorial (H.lineCount j L) : ℝ)) + +/-- The symmetric group on the unmarked input sites. -/ +def stabilizer (H : G.Holes h) : Subgroup (Equiv.Perm G.Slot) where + carrier g := ∀ i, g (H.path i 0) = H.path i 0 + one_mem' _ := rfl + mul_mem' := by + intro g g' hg hg' i + change g (g' (H.path i 0)) = H.path i 0 + rw [hg' i, hg i] + inv_mem' hg i := (Equiv.symm_apply_eq _).mpr (hg i).symm + +def reference (H : G.Holes h) (hf : H.Feasible) : G.Choices := hf.choose + +theorem reference_compatible (H : G.Holes h) (hf : H.Feasible) : + H.Compatible (H.reference hf) := hf.choose_spec + +/-- A reference completion identifies the free input and output sites. -/ +def residual (H : G.Holes h) (hf : H.Feasible) (ω : {ω : G.Choices // H.Compatible ω}) : + H.stabilizer := + ⟨(G.sweep (H.reference hf))⁻¹ * G.sweep ω.val, by + intro i + change (G.sweep (H.reference hf)).symm (G.sweep ω.val (H.path i 0)) = H.path i 0 + apply (Equiv.symm_apply_eq _).mpr + exact (ω.property i (Fin.last _)).trans ((H.reference_compatible hf i (Fin.last _)).symm)⟩ + +end Holes + +/-- Independent line permutations with law `(1-z) U + z B`. -/ +def choiceWeight (G : Grid) (z : ℝ) (ω : G.Choices) : ℝ := + ∏ j, ∏ L : G.Line j, + ((1-z) * (Fintype.card (Equiv.Perm (Cube (G.bits j))) : ℝ)⁻¹ + + z * binaryLaw (G.bits j) (ω j L)) + +namespace Holes + +variable {G : Grid} {h : ℕ} + +def probability (H : G.Holes h) (z : ℝ) : ℝ := + ∑ ω : {ω : G.Choices // H.Compatible ω}, G.choiceWeight z ω.val + +end Holes + +def eventDistance (G : Grid) (E : Finset G.Choices) (z : ℝ) : ℝ := + ∑ ω ∈ E, |G.choiceWeight z ω/(∑ v ∈ E, G.choiceWeight z v)- + G.choiceWeight 0 ω/(∑ v ∈ E, G.choiceWeight 0 v)| + +end Grid + +structure UnitaryIrrep (Γ : Type*) [Group Γ] where + dimension : ℕ + positive : 0 < dimension + matrix : Γ →* Matrix (Fin dimension) (Fin dimension) ℂ + unitary : ∀ g, (matrix g).conjTranspose * matrix g = 1 + irreducible : ∀ S : Submodule ℂ (Fin dimension → ℂ), + (∀ g v, v ∈ S → (matrix g).mulVec v ∈ S) → S = ⊥ ∨ S = ⊤ + +/-- Unnormalized Schatten `2q` moment, without division by the dimension. -/ +def schattenMoment {D : ℕ} (q : ℕ) (K : Matrix (Fin D) (Fin D) ℂ) : ℝ := + (Matrix.trace ((K.conjTranspose * K) ^ q)).re + +namespace Grid.Holes + +variable {G : Grid} {h : ℕ} + +def conditionalAverage (H : G.Holes h) (hf : H.Feasible) (z : ℝ) + (ρ : UnitaryIrrep H.stabilizer) : Matrix (Fin ρ.dimension) (Fin ρ.dimension) ℂ := + (H.probability z : ℂ)⁻¹ • + ∑ ω : {ω : G.Choices // H.Compatible ω}, + (G.choiceWeight z ω.val : ℂ) • ρ.matrix (H.residual hf ω) + +end Grid.Holes + +def a : ℝ := 1 / 100 +def c0 : ℝ := a / 100 +def e0 : ℝ := a / 100 +def c (s : ℕ) : ℝ := c0 + 1 / Real.sqrt (Real.log s) +def e (s : ℕ) : ℝ := e0 - 1 / Real.sqrt (Real.log s) + +/-- The logarithm of a zero moment is minus infinity. -/ +def logMoment (t : ℝ) : EReal := if t = 0 then ⊥ else (Real.log t : EReal) + +def ConditionalMain : Prop := + ∃ (r q : ℕ) (zStar : ℝ), 1 ≤ r ∧ 1 ≤ q ∧ 0 < zStar ∧ zStar ≤ 1 / ((2 : ℕ) : ℝ) ∧ + ∀ (G : Grid), G.Allowed r → ∀ (h : ℕ) (H : G.Holes h) (hf : H.Feasible), + ∀ z ∈ Set.Icc 0 zStar, ∀ ρ : UnitaryIrrep H.stabilizer, + logMoment (schattenMoment q (H.conditionalAverage hf z ρ)) ≤ + ((-c G.size * Real.log ρ.dimension + e G.size * h * Real.log G.size - H.cost : ℝ) : EReal) + +def MomentBound (G : Grid) (q : ℕ) (z : ℝ) : Prop := + ∀ (h : ℕ) (H : G.Holes h) (hf : H.Feasible) (σ : UnitaryIrrep H.stabilizer), + schattenMoment q (H.conditionalAverage hf z σ) ≤ + Real.exp (-c G.size*Real.log σ.dimension+e G.size*h*Real.log G.size-H.cost) + +def ScaleLarge (r : ℕ) : Prop := + 1 ≤ r ∧ (2/e0)^2 ≤ (r : ℝ)*Real.log 2 ∧ 4/e0 ≤ (r : ℝ)*Real.log 2 + +def baseWidth (r : ℕ) : ℝ := ((2^(2*r)).factorial : ℕ) +def baseZeta (r : ℕ) : ℝ := 1/(4*(baseWidth r)^2) + +namespace ScalarInduction + +structure MainSizeReady (q : ℕ) (s : ℝ) : Prop where + one : 1 ≤ Real.log s + sparse : (100004:ℝ)*s^(1-a/4) ≤ s^(1-(1:ℝ)/1600) + hook : (((2*q+1:ℕ):ℝ)*4+82*c0)*2*s^((4:ℝ)/5+2*a)*Real.log (s+1) ≤ s^((9:ℝ)/10) + removed : s^((9:ℝ)/10)+s^(1-a/2)*Real.log s ≤ s^(1-a/4)/(20*Real.sqrt (Real.log s)) + +end ScalarInduction + +namespace SparseScalar + +def theta : ℝ := 1/1600 +def K0 : ℝ := 100000 +def B0 : ℕ := 12800 +def xi : ℝ := 1/2048000000 +def rho : ℝ := 1/32768000000 +def q : ℕ := 65536000000 + +def uniformRate : ℝ := Real.log ((2 : ℕ) : ℝ) + (B0 : ℝ) * + (K0 + 1 + Real.log ((4 : ℕ) : ℝ) + + Real.log (((16 : ℕ) : ℝ) * Real.exp ((2 : ℕ) : ℝ)) + + Real.log (1 + ((16 : ℕ) : ℝ) * Real.exp ((2 : ℕ) : ℝ))) + +structure SizeReady (s : ℝ) : Prop where + two : 2 ≤ s + logpow : Real.log s ≤ s^(theta/4) + powtwo : 2 ≤ s^(theta/4) + powB : (B0+1:ℝ) ≤ s^(theta/2) + count : 4/s^(1/(4*(B0:ℝ))) ≤ theta/(64*B0) + absorb : Real.log (1+2*(B0:ℝ))+Real.log 2 ≤ xi*Real.log s + eta : s^(-xi) ≤ 1/8 + prefactor : uniformRate ≤ xi*Real.log s/16 + logtwo : Real.log 2 ≤ xi*Real.log s/8 + +structure ScaleReady (r : ℕ) : Prop where + two : 2 ≤ r + logone : 1 ≤ (r:ℝ)*Real.log 2 + absorb : 3*Real.log 2+2*(K0+1+Real.log 4) ≤ theta*((r:ℝ)*Real.log 2)/8 + size : ∀ s : ℝ, (2:ℝ)^r ≤ s → SizeReady s + +def slack (s : ℝ) : ℝ := + if 1 < s then s ^ (-((2 : ℕ) : ℝ) * rho * s) * (s ^ rho - 1) else 1 + +end SparseScalar + +def SparsePerturb (r : ℕ) (zStar : ℝ) : Prop := + 0 < zStar ∧ zStar ≤ baseZeta r ∧ ∀ G : Grid, G.b ≤ SparseScalar.B0 → G.Allowed r → + ∀ z ∈ Set.Icc 0 zStar, ∀ E : Finset G.Choices, E.Nonempty → + G.eventDistance E z < SparseScalar.slack G.size + +/-- The quantitative all-grid estimate under the explicit scale and perturbation bounds. -/ +theorem all_grid_moment {r : ℕ} (hr : ScaleLarge r) (hrS : SparseScalar.ScaleReady r) + (hS : ∀ G : Grid, G.Allowed r → ScalarInduction.MainSizeReady SparseScalar.q G.size) + {zStar : ℝ} (hζ : SparsePerturb r zStar) {z : ℝ} (hz : z∈Set.Icc 0 zStar) : + ∀ G : Grid, G.Allowed r → MomentBound G SparseScalar.q z := by + sorry + +/-- One global choice of scale, moment order, and positive perturbation interval. -/ +theorem conditional_main : ConditionalMain := by + sorry + +end CoordinateSweeps + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoordinateSweeps.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.CoordinateSweeps.conditional_main`, `OAI.CoordinateSweeps.all_grid_moment` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coordinate-sweeps/solution/closure.txt b/tasks/coordinate-sweeps/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..daabf7f67dfa3e2c7ccdef119e0d5b06cc1ec428 --- /dev/null +++ b/tasks/coordinate-sweeps/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Analysis.Matrix.BlockCycles +OAI.Analysis.Matrix.Holder +OAI.Analysis.Matrix.TensorMoment +OAI.Combinatorics.Graphs.Coverage +OAI.Probability.CoordinateSweeps.Attachment +OAI.Probability.CoordinateSweeps.BaseCase +OAI.Probability.CoordinateSweeps.Conditioning +OAI.Probability.CoordinateSweeps.Decomposition +OAI.Probability.CoordinateSweeps.Grid +OAI.Probability.CoordinateSweeps.Induction +OAI.Probability.CoordinateSweeps.Kernel +OAI.Probability.CoordinateSweeps.Main +OAI.Probability.CoordinateSweeps.Perturbation +OAI.Probability.CoordinateSweeps.PlacementMoment +OAI.Probability.CoordinateSweeps.Scales +OAI.Probability.CoordinateSweeps.SparseBound +OAI.Probability.CoordinateSweeps.SparseDimension +OAI.Probability.CoordinateSweeps.SparseMoment +OAI.Probability.CoordinateSweeps.TrajectoryMoment +OAI.Probability.CoordinateSweeps.Transition +OAI.Probability.Moments.LineExpansion +OAI.RepresentationTheory.Placement.Chart +OAI.RepresentationTheory.Placement.Occurrence +OAI.RepresentationTheory.SignedTensor.Basic +OAI.RepresentationTheory.SignedTensor.Blocks +OAI.RepresentationTheory.SignedTensor.Domination +OAI.RepresentationTheory.SignedTensor.Overlap +OAI.RepresentationTheory.SignedTensor.Resolution +OAI.RepresentationTheory.Tensor.Postselection +OAI.RepresentationTheory.Unitary.Basic +OAI.RepresentationTheory.Unitary.Spectral +OAI.RepresentationTheory.Young.Classification +OAI.RepresentationTheory.Young.Entropy +OAI.RepresentationTheory.Young.Restriction diff --git a/tasks/coordinate-sweeps/solution/reference.py b/tasks/coordinate-sweeps/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coordinate-sweeps/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coordinate-sweeps/solution/solve.sh b/tasks/coordinate-sweeps/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..02ab62a13a13a7210c1601f3dc466c45efaddaf1 --- /dev/null +++ b/tasks/coordinate-sweeps/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoordinateSweeps, i.e. module OAI.Probability.CoordinateSweeps.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.CoordinateSweeps.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoordinateSweeps" diff --git a/tasks/coordinate-sweeps/task.toml b/tasks/coordinate-sweeps/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85722a7a8b9e63702bc73c1496071ef7fd42059a --- /dev/null +++ b/tasks/coordinate-sweeps/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coordinate-sweeps" +version = "1.0.0" +description = "Prove CoordinateSweeps (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoordinateSweeps.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoordinateSweeps" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CoordinateSweeps.conditional_main", "OAI.CoordinateSweeps.all_grid_moment"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.CoordinateSweeps.Main" +reference_modules = 34 +reference_lean_bytes = 1085561 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1051 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12677 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coordinate-sweeps/tests/Challenge.lean b/tasks/coordinate-sweeps/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b6ed4a34e44ddeb739a70704ff4484d49782618 --- /dev/null +++ b/tasks/coordinate-sweeps/tests/Challenge.lean @@ -0,0 +1,314 @@ +import Mathlib + +namespace OAI + +/-! +Conditional moments for one ordered coordinate sweep on power-of-two rectangular +grids. The line law mixes uniform permutations with a binary coordinate sweep. +The trace is unnormalized, and the trajectory cost uses falling factorials. +-/ + +noncomputable section + +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder ComplexConjugate MatrixOrder ENNReal +open MeasureTheory +attribute [local instance] Classical.propDecidable + +namespace CoordinateSweeps + +structure FiniteLaw (Ω : Type*) where + mass : Ω → ℝ + nonneg : ∀ x, 0 ≤ mass x + total : ∑ᶠ x, mass x = 1 + +namespace FiniteLaw + +variable {Ω X Y : Type*} + +instance : CoeFun (FiniteLaw Ω) (fun _ => Ω → ℝ) := ⟨FiniteLaw.mass⟩ + +@[ext] theorem ext {μ ν : FiniteLaw Ω} (h : ∀ x, μ x = ν x) : μ = ν := by + cases μ + cases ν + congr + exact funext h + +variable [Fintype Ω] [Fintype X] [Fintype Y] + +@[simp] theorem sum_mass (μ : FiniteLaw Ω) : ∑ x, μ x = 1 := by + simpa only [finsum_eq_sum_of_fintype] using μ.total + +def uniform (Ω : Type*) [Fintype Ω] [Nonempty Ω] : FiniteLaw Ω where + mass _ := (Fintype.card Ω : ℝ)⁻¹ + nonneg _ := inv_nonneg.mpr (Nat.cast_nonneg _) + total := by + rw [finsum_eq_sum_of_fintype] + simp only [Finset.sum_const, Finset.card_univ, nsmul_eq_mul] + exact mul_inv_cancel₀ (by exact_mod_cast Fintype.card_ne_zero) + +def map (μ : FiniteLaw Ω) (f : Ω → X) : FiniteLaw X where + mass y := ∑ x, if f x = y then μ x else 0 + nonneg y := Finset.sum_nonneg (fun x _ => by split_ifs; exact μ.nonneg x; exact le_rfl) + total := by + rw [finsum_eq_sum_of_fintype] + classical + rw [Finset.sum_comm] + simp [μ.sum_mass] + +end FiniteLaw + +abbrev Cube (d : ℕ) := Fin d → Bool + +def pairSwitch {L : Type*} (bits : L → Bool) : Equiv.Perm (Bool × L) where + toFun x := (Bool.xor x.1 (bits x.2), x.2) + invFun x := (Bool.xor x.1 (bits x.2), x.2) + left_inv point := by + rcases point with ⟨bit, label⟩ + change ((bit ^^ bits label) ^^ bits label, label) = (bit, label) + cases bit <;> cases bits label <;> simp + right_inv point := by + rcases point with ⟨bit, label⟩ + change ((bit ^^ bits label) ^^ bits label, label) = (bit, label) + cases bit <;> cases bits label <;> simp + +def binaryLayer {d : ℕ} (j : Fin d) (bits : ({k : Fin d // k ≠ j} → Bool) → Bool) : + Equiv.Perm (Cube d) := + (Equiv.funSplitAt j Bool).trans ((pairSwitch bits).trans (Equiv.funSplitAt j Bool).symm) + +/-- Coordinate zero acts first. -/ +def orderedProduct {G : Type*} [Monoid G] {d : ℕ} (g : Fin d → G) : G := + (List.ofFn g).reverse.prod + +abbrev BinaryChoices (d : ℕ) := ∀ j : Fin d, ({k : Fin d // k ≠ j} → Bool) → Bool + +instance (d : ℕ) : Nonempty (BinaryChoices d) := ⟨fun _ _ => false⟩ + +def binarySweep (d : ℕ) (bits : BinaryChoices d) : Equiv.Perm (Cube d) := + orderedProduct (fun j => binaryLayer j (bits j)) + +def binaryLaw (d : ℕ) : FiniteLaw (Equiv.Perm (Cube d)) := + (FiniteLaw.uniform (BinaryChoices d)).map (binarySweep d) + +structure Grid where + b : ℕ + positive : 0 < b + bits : Fin b → ℕ + +namespace Grid + +def size (G : Grid) : ℕ := ∏ j, 2 ^ G.bits j + +abbrev Slot (G : Grid) := ∀ j, Cube (G.bits j) + +abbrev Line (G : Grid) (j : Fin G.b) := ∀ k : {k : Fin G.b // k ≠ j}, Cube (G.bits k) + +abbrev Choices (G : Grid) := ∀ j, G.Line j → Equiv.Perm (Cube (G.bits j)) + +def fiberPerm {A B : Type*} (p : B → Equiv.Perm A) : Equiv.Perm (A × B) where + toFun x := (p x.2 x.1, x.2) + invFun x := ((p x.2).symm x.1, x.2) + left_inv x := by simp + right_inv x := by simp + +def stage (G : Grid) (ω : G.Choices) (j : Fin G.b) : Equiv.Perm G.Slot := + (Equiv.piSplitAt j (fun k => Cube (G.bits k))).trans + ((fiberPerm (ω j)).trans (Equiv.piSplitAt j (fun k => Cube (G.bits k))).symm) + +def boundary (G : Grid) (ω : G.Choices) (t : ℕ) : Equiv.Perm G.Slot := + ((List.ofFn (G.stage ω)).take t).reverse.prod + +def sweep (G : Grid) (ω : G.Choices) : Equiv.Perm G.Slot := G.boundary ω G.b + +/-- The side lengths are in `[R, R²]`, where the single global scale is `R = 2^r`. -/ +def Allowed (G : Grid) (r : ℕ) : Prop := ∀ j, r ≤ G.bits j ∧ G.bits j ≤ 2 * r + +/-- Full disjoint paths, including every boundary of the ordered sweep. -/ +structure Holes (G : Grid) (h : ℕ) where + path : Fin h → Fin (G.b + 1) → G.Slot + disjoint : ∀ t, Function.Injective (fun i => path i t) + coordinate_step : ∀ i (j : Fin G.b) (k : Fin G.b), k ≠ j → + path i j.succ k = path i j.castSucc k + +namespace Holes + +variable {G : Grid} {h : ℕ} + +def Compatible (H : G.Holes h) (ω : G.Choices) : Prop := + ∀ i (t : Fin (G.b + 1)), G.boundary ω t (H.path i 0) = H.path i t + +def Feasible (H : G.Holes h) : Prop := ∃ ω, H.Compatible ω + +def lineCount (H : G.Holes h) (j : Fin G.b) (L : G.Line j) : ℕ := + (Finset.univ.filter (fun i : Fin h => + (fun k : {k : Fin G.b // k ≠ j} => H.path i j.castSucc k) = L)).card + +def cost (H : G.Holes h) : ℝ := + ∑ j, ∑ L : G.Line j, + Real.log (((2 ^ G.bits j : ℕ) : ℝ) ^ H.lineCount j L / + ((2 ^ G.bits j).descFactorial (H.lineCount j L) : ℝ)) + +/-- The symmetric group on the unmarked input sites. -/ +def stabilizer (H : G.Holes h) : Subgroup (Equiv.Perm G.Slot) where + carrier g := ∀ i, g (H.path i 0) = H.path i 0 + one_mem' _ := rfl + mul_mem' := by + intro g g' hg hg' i + change g (g' (H.path i 0)) = H.path i 0 + rw [hg' i, hg i] + inv_mem' hg i := (Equiv.symm_apply_eq _).mpr (hg i).symm + +def reference (H : G.Holes h) (hf : H.Feasible) : G.Choices := hf.choose + +theorem reference_compatible (H : G.Holes h) (hf : H.Feasible) : + H.Compatible (H.reference hf) := hf.choose_spec + +/-- A reference completion identifies the free input and output sites. -/ +def residual (H : G.Holes h) (hf : H.Feasible) (ω : {ω : G.Choices // H.Compatible ω}) : + H.stabilizer := + ⟨(G.sweep (H.reference hf))⁻¹ * G.sweep ω.val, by + intro i + change (G.sweep (H.reference hf)).symm (G.sweep ω.val (H.path i 0)) = H.path i 0 + apply (Equiv.symm_apply_eq _).mpr + exact (ω.property i (Fin.last _)).trans ((H.reference_compatible hf i (Fin.last _)).symm)⟩ + +end Holes + +/-- Independent line permutations with law `(1-z) U + z B`. -/ +def choiceWeight (G : Grid) (z : ℝ) (ω : G.Choices) : ℝ := + ∏ j, ∏ L : G.Line j, + ((1-z) * (Fintype.card (Equiv.Perm (Cube (G.bits j))) : ℝ)⁻¹ + + z * binaryLaw (G.bits j) (ω j L)) + +namespace Holes + +variable {G : Grid} {h : ℕ} + +def probability (H : G.Holes h) (z : ℝ) : ℝ := + ∑ ω : {ω : G.Choices // H.Compatible ω}, G.choiceWeight z ω.val + +end Holes + +def eventDistance (G : Grid) (E : Finset G.Choices) (z : ℝ) : ℝ := + ∑ ω ∈ E, |G.choiceWeight z ω/(∑ v ∈ E, G.choiceWeight z v)- + G.choiceWeight 0 ω/(∑ v ∈ E, G.choiceWeight 0 v)| + +end Grid + +structure UnitaryIrrep (Γ : Type*) [Group Γ] where + dimension : ℕ + positive : 0 < dimension + matrix : Γ →* Matrix (Fin dimension) (Fin dimension) ℂ + unitary : ∀ g, (matrix g).conjTranspose * matrix g = 1 + irreducible : ∀ S : Submodule ℂ (Fin dimension → ℂ), + (∀ g v, v ∈ S → (matrix g).mulVec v ∈ S) → S = ⊥ ∨ S = ⊤ + +/-- Unnormalized Schatten `2q` moment, without division by the dimension. -/ +def schattenMoment {D : ℕ} (q : ℕ) (K : Matrix (Fin D) (Fin D) ℂ) : ℝ := + (Matrix.trace ((K.conjTranspose * K) ^ q)).re + +namespace Grid.Holes + +variable {G : Grid} {h : ℕ} + +def conditionalAverage (H : G.Holes h) (hf : H.Feasible) (z : ℝ) + (ρ : UnitaryIrrep H.stabilizer) : Matrix (Fin ρ.dimension) (Fin ρ.dimension) ℂ := + (H.probability z : ℂ)⁻¹ • + ∑ ω : {ω : G.Choices // H.Compatible ω}, + (G.choiceWeight z ω.val : ℂ) • ρ.matrix (H.residual hf ω) + +end Grid.Holes + +def a : ℝ := 1 / 100 +def c0 : ℝ := a / 100 +def e0 : ℝ := a / 100 +def c (s : ℕ) : ℝ := c0 + 1 / Real.sqrt (Real.log s) +def e (s : ℕ) : ℝ := e0 - 1 / Real.sqrt (Real.log s) + +/-- The logarithm of a zero moment is minus infinity. -/ +def logMoment (t : ℝ) : EReal := if t = 0 then ⊥ else (Real.log t : EReal) + +def ConditionalMain : Prop := + ∃ (r q : ℕ) (zStar : ℝ), 1 ≤ r ∧ 1 ≤ q ∧ 0 < zStar ∧ zStar ≤ 1 / ((2 : ℕ) : ℝ) ∧ + ∀ (G : Grid), G.Allowed r → ∀ (h : ℕ) (H : G.Holes h) (hf : H.Feasible), + ∀ z ∈ Set.Icc 0 zStar, ∀ ρ : UnitaryIrrep H.stabilizer, + logMoment (schattenMoment q (H.conditionalAverage hf z ρ)) ≤ + ((-c G.size * Real.log ρ.dimension + e G.size * h * Real.log G.size - H.cost : ℝ) : EReal) + +def MomentBound (G : Grid) (q : ℕ) (z : ℝ) : Prop := + ∀ (h : ℕ) (H : G.Holes h) (hf : H.Feasible) (σ : UnitaryIrrep H.stabilizer), + schattenMoment q (H.conditionalAverage hf z σ) ≤ + Real.exp (-c G.size*Real.log σ.dimension+e G.size*h*Real.log G.size-H.cost) + +def ScaleLarge (r : ℕ) : Prop := + 1 ≤ r ∧ (2/e0)^2 ≤ (r : ℝ)*Real.log 2 ∧ 4/e0 ≤ (r : ℝ)*Real.log 2 + +def baseWidth (r : ℕ) : ℝ := ((2^(2*r)).factorial : ℕ) +def baseZeta (r : ℕ) : ℝ := 1/(4*(baseWidth r)^2) + +namespace ScalarInduction + +structure MainSizeReady (q : ℕ) (s : ℝ) : Prop where + one : 1 ≤ Real.log s + sparse : (100004:ℝ)*s^(1-a/4) ≤ s^(1-(1:ℝ)/1600) + hook : (((2*q+1:ℕ):ℝ)*4+82*c0)*2*s^((4:ℝ)/5+2*a)*Real.log (s+1) ≤ s^((9:ℝ)/10) + removed : s^((9:ℝ)/10)+s^(1-a/2)*Real.log s ≤ s^(1-a/4)/(20*Real.sqrt (Real.log s)) + +end ScalarInduction + +namespace SparseScalar + +def theta : ℝ := 1/1600 +def K0 : ℝ := 100000 +def B0 : ℕ := 12800 +def xi : ℝ := 1/2048000000 +def rho : ℝ := 1/32768000000 +def q : ℕ := 65536000000 + +def uniformRate : ℝ := Real.log ((2 : ℕ) : ℝ) + (B0 : ℝ) * + (K0 + 1 + Real.log ((4 : ℕ) : ℝ) + + Real.log (((16 : ℕ) : ℝ) * Real.exp ((2 : ℕ) : ℝ)) + + Real.log (1 + ((16 : ℕ) : ℝ) * Real.exp ((2 : ℕ) : ℝ))) + +structure SizeReady (s : ℝ) : Prop where + two : 2 ≤ s + logpow : Real.log s ≤ s^(theta/4) + powtwo : 2 ≤ s^(theta/4) + powB : (B0+1:ℝ) ≤ s^(theta/2) + count : 4/s^(1/(4*(B0:ℝ))) ≤ theta/(64*B0) + absorb : Real.log (1+2*(B0:ℝ))+Real.log 2 ≤ xi*Real.log s + eta : s^(-xi) ≤ 1/8 + prefactor : uniformRate ≤ xi*Real.log s/16 + logtwo : Real.log 2 ≤ xi*Real.log s/8 + +structure ScaleReady (r : ℕ) : Prop where + two : 2 ≤ r + logone : 1 ≤ (r:ℝ)*Real.log 2 + absorb : 3*Real.log 2+2*(K0+1+Real.log 4) ≤ theta*((r:ℝ)*Real.log 2)/8 + size : ∀ s : ℝ, (2:ℝ)^r ≤ s → SizeReady s + +def slack (s : ℝ) : ℝ := + if 1 < s then s ^ (-((2 : ℕ) : ℝ) * rho * s) * (s ^ rho - 1) else 1 + +end SparseScalar + +def SparsePerturb (r : ℕ) (zStar : ℝ) : Prop := + 0 < zStar ∧ zStar ≤ baseZeta r ∧ ∀ G : Grid, G.b ≤ SparseScalar.B0 → G.Allowed r → + ∀ z ∈ Set.Icc 0 zStar, ∀ E : Finset G.Choices, E.Nonempty → + G.eventDistance E z < SparseScalar.slack G.size + +/-- The quantitative all-grid estimate under the explicit scale and perturbation bounds. -/ +theorem all_grid_moment {r : ℕ} (hr : ScaleLarge r) (hrS : SparseScalar.ScaleReady r) + (hS : ∀ G : Grid, G.Allowed r → ScalarInduction.MainSizeReady SparseScalar.q G.size) + {zStar : ℝ} (hζ : SparsePerturb r zStar) {z : ℝ} (hz : z∈Set.Icc 0 zStar) : + ∀ G : Grid, G.Allowed r → MomentBound G SparseScalar.q z := by + sorry + +/-- One global choice of scale, moment order, and positive perturbation interval. -/ +theorem conditional_main : ConditionalMain := by + sorry + +end CoordinateSweeps + +end + +end OAI diff --git a/tasks/coordinate-sweeps/tests/grade.py b/tasks/coordinate-sweeps/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coordinate-sweeps/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coordinate-sweeps/tests/task.json b/tasks/coordinate-sweeps/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..edbc2620a1407c84dd569a2740fcaccafc8e6c3e --- /dev/null +++ b/tasks/coordinate-sweeps/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "CoordinateSweeps", + "comparator": { + "theorem_names": [ + "OAI.CoordinateSweeps.conditional_main", + "OAI.CoordinateSweeps.all_grid_moment" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11777 +} \ No newline at end of file diff --git a/tasks/coordinate-sweeps/tests/test.sh b/tasks/coordinate-sweeps/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coordinate-sweeps/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coordinate-trace/environment/Dockerfile b/tasks/coordinate-trace/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coordinate-trace/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coordinate-trace/environment/fetch_mathlib.sh b/tasks/coordinate-trace/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coordinate-trace/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coordinate-trace/environment/lake-manifest.json b/tasks/coordinate-trace/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coordinate-trace/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coordinate-trace/environment/lakefile.lean b/tasks/coordinate-trace/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coordinate-trace/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coordinate-trace/environment/lean_setup.sh b/tasks/coordinate-trace/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coordinate-trace/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coordinate-trace/environment/pack_submission.py b/tasks/coordinate-trace/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coordinate-trace/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coordinate-trace/instruction.md b/tasks/coordinate-trace/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71d88f171733d757d52d54496ebac681501319dd --- /dev/null +++ b/tasks/coordinate-trace/instruction.md @@ -0,0 +1,424 @@ +# openai/math challenge `CoordinateTrace` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `CoordinateTrace`, also at `/opt/openai-math/challenges/CoordinateTrace.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end Thorp.UnitaryFinite + +namespace Thorp.UnitaryFinite +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical + +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +noncomputable def cellRowsEquiv (μ : YoungDiagram) : + Cell μ ≃ (i : Fin (μ.colLen 0)) × Fin (μ.rowLen i) where + toFun x := ⟨rowIndex x,⟨col x,YoungDiagram.mem_iff_lt_rowLen.mp x.2⟩⟩ + invFun p := ⟨(p.1,p.2),YoungDiagram.mem_iff_lt_rowLen.mpr p.2.2⟩ + left_inv x := by apply Subtype.ext; rfl + right_inv p := by rcases p with ⟨⟨i,hi⟩,⟨j,hj⟩⟩; rfl + +lemma card_eq_sum_rowLen (μ : YoungDiagram) : μ.card = ∑ i : Fin (μ.colLen 0), μ.rowLen i := by + rw [←card_cell,Fintype.card_congr (cellRowsEquiv μ),Fintype.card_sigma] + simp only [Fintype.card_fin] + +lemma sum_rowLens (μ : YoungDiagram) : μ.rowLens.sum = μ.card := by + rw [card_eq_sum_rowLen,YoungDiagram.rowLens] + rw [Fin.sum_univ_eq_sum_range] + have hh (n : ℕ) : (List.map μ.rowLen (List.range n)).sum = ∑ i ∈ Finset.range n, μ.rowLen i := by + induction n with + | zero => simp + | succ n ih => simp [List.range_succ,List.map_append,Finset.sum_range_succ,ih] + exact hh _ + +noncomputable def diagramPartition (μ : YoungDiagram) : Nat.Partition μ.card where + parts := μ.rowLens + parts_pos := fun {i} hi => μ.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simp + +noncomputable def partitionDiagram {N : ℕ} (p : Nat.Partition N) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +lemma partitionDiagram_rowLens {N : ℕ} (p : Nat.Partition N) : + (partitionDiagram p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + +lemma partitionDiagram_card {N : ℕ} (p : Nat.Partition N) : (partitionDiagram p).card = N := by + rw [←sum_rowLens,partitionDiagram_rowLens] + change (↑(p.parts.sort (· ≥ ·)) : Multiset ℕ).sum = N + rw [Multiset.sort_eq,p.parts_sum] + +lemma partitionDiagram_diagramPartition (μ : YoungDiagram) : + partitionDiagram (diagramPartition μ) = μ := by + apply YoungDiagram.equivListRowLens.injective + apply Subtype.ext + change (partitionDiagram (diagramPartition μ)).rowLens = μ.rowLens + rw [partitionDiagram_rowLens] + change (↑μ.rowLens : Multiset ℕ).sort (· ≥ ·) = μ.rowLens + rw [Multiset.coe_sort,List.mergeSort_eq_self _ μ.rowLens_sorted.pairwise] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def shapePartitionEquiv (N : ℕ) : Shapes N ≃ Nat.Partition N where + toFun μ := { parts := μ.1.rowLens + parts_pos := fun {i} hi => μ.1.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simpa using (sum_rowLens μ.1).trans μ.2 } + invFun p := ⟨partitionDiagram p,partitionDiagram_card p⟩ + left_inv μ := by + apply Subtype.ext + obtain ⟨μ,rfl⟩ := μ + exact partitionDiagram_diagramPartition μ + right_inv p := by + apply Nat.Partition.ext + change ((partitionDiagram p).rowLens : Multiset ℕ) = p.parts + rw [partitionDiagram_rowLens,Multiset.sort_eq] + +noncomputable instance (N : ℕ) : Fintype (Shapes N) := Fintype.ofEquiv _ (shapePartitionEquiv N).symm + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end Thorp.Specht + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace Thorp.LowPlanes +open scoped BigOperators Classical +open Specht UnitaryFinite + +noncomputable local instance hsNorm (μ : YoungDiagram) : NormedAddCommGroup (hilbertSpace μ) := inferInstance +noncomputable local instance hsInner (μ : YoungDiagram) : InnerProductSpace ℂ (hilbertSpace μ) := inferInstance +noncomputable local instance hsFinite (μ : YoungDiagram) : FiniteDimensional ℂ (hilbertSpace μ) := inferInstance + +noncomputable def Q (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) + +noncomputable def absoluteTrace {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + (A : V →L[ℂ] V) (P : ℝ) : ℝ := + (LinearMap.trace ℂ V (CFC.rpow (CFC.sqrt (star A * A)) P).toLinearMap).re + +noncomputable def regularTrace (d : ℕ) (P : ℝ) : ℝ := + ∑ μ : Shapes (2^d), (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + absoluteTrace (V := hilbertSpace μ.1) (Q d μ) P + +noncomputable def sweepDistance (d v : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d (v*d) (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +def MainStatement : Prop := + ∃ P : ℝ, 2 ≤ P ∧ ∀ d : ℕ, 1 ≤ d → + regularTrace d P ≤ 1 + ((2 : ℝ)^d) ^ (-10 : ℤ) ∧ + ∀ v : ℤ, P ≤ 2 * (v : ℝ) → ∀ σ : Equiv.Perm (Card d), + sweepDistance d v.toNat σ ≤ (1/2 : ℝ) * ((2 : ℝ)^d) ^ (-5 : ℤ) + +theorem regular_trace_smoothing : MainStatement := by + sorry + +end Thorp.LowPlanes + +end ThorpNine.Harmonic + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoordinateTrace.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThorpNine.Harmonic.Thorp.LowPlanes.regular_trace_smoothing` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coordinate-trace/solution/closure.txt b/tasks/coordinate-trace/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a719bd08ff7201407ba78003e43f54845fd78b5 --- /dev/null +++ b/tasks/coordinate-trace/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.Probability.ThorpRouting.Harmonic.AlternatingPerm +OAI.Probability.ThorpRouting.Harmonic.AssignmentSlots +OAI.Probability.ThorpRouting.Harmonic.AverageMap +OAI.Probability.ThorpRouting.Harmonic.BlockProduct +OAI.Probability.ThorpRouting.Harmonic.Coins +OAI.Probability.ThorpRouting.Harmonic.CutoffMass +OAI.Probability.ThorpRouting.Harmonic.ExposedCoins +OAI.Probability.ThorpRouting.Harmonic.InputTree +OAI.Probability.ThorpRouting.Harmonic.InsertionPerm +OAI.Probability.ThorpRouting.Harmonic.Main +OAI.Probability.ThorpRouting.Harmonic.Model +OAI.Probability.ThorpRouting.Harmonic.ModifiedReverseCoins +OAI.Probability.ThorpRouting.Harmonic.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Harmonic.PairAssembleEquiv +OAI.Probability.ThorpRouting.Harmonic.PalindromeFamilyCost +OAI.Probability.ThorpRouting.Harmonic.ParallelFollow +OAI.Probability.ThorpRouting.Harmonic.PriorPaths +OAI.Probability.ThorpRouting.Harmonic.RotationMeeting +OAI.Probability.ThorpRouting.Harmonic.SandwichShuffle +OAI.Probability.ThorpRouting.Harmonic.Shapes +OAI.Probability.ThorpRouting.Harmonic.Site +OAI.Probability.ThorpRouting.Harmonic.TailShapes +OAI.Probability.ThorpRouting.Harmonic.TypedSet +OAI.Probability.ThorpRouting.Harmonic.ZeroExtend +OAI.Probability.ThorpRouting.RegularTrace +OAI.Probability.ThorpRouting.TraceBound +OAI.Probability.ThorpRouting.TraceDecay +OAI.Probability.ThorpRouting.TraceModel diff --git a/tasks/coordinate-trace/solution/reference.py b/tasks/coordinate-trace/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coordinate-trace/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coordinate-trace/solution/solve.sh b/tasks/coordinate-trace/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..68c8df52334f8b116fd49e909a144a4a8af4878a --- /dev/null +++ b/tasks/coordinate-trace/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoordinateTrace, i.e. module OAI.Probability.ThorpRouting.RegularTrace and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThorpRouting.RegularTrace /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoordinateTrace" diff --git a/tasks/coordinate-trace/task.toml b/tasks/coordinate-trace/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bb5efa751cb153b51cca83d3793294573779ef56 --- /dev/null +++ b/tasks/coordinate-trace/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coordinate-trace" +version = "1.0.0" +description = "Prove CoordinateTrace (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoordinateTrace.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoordinateTrace" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThorpNine.Harmonic.Thorp.LowPlanes.regular_trace_smoothing"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThorpRouting.RegularTrace" +reference_modules = 28 +reference_lean_bytes = 974102 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1254 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12576 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coordinate-trace/tests/Challenge.lean b/tasks/coordinate-trace/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..01bca12a699b3a52e0558ffad13ccdc35c904c53 --- /dev/null +++ b/tasks/coordinate-trace/tests/Challenge.lean @@ -0,0 +1,373 @@ +import Mathlib + +namespace OAI + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end Thorp.UnitaryFinite + +namespace Thorp.UnitaryFinite +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical + +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +noncomputable def cellRowsEquiv (μ : YoungDiagram) : + Cell μ ≃ (i : Fin (μ.colLen 0)) × Fin (μ.rowLen i) where + toFun x := ⟨rowIndex x,⟨col x,YoungDiagram.mem_iff_lt_rowLen.mp x.2⟩⟩ + invFun p := ⟨(p.1,p.2),YoungDiagram.mem_iff_lt_rowLen.mpr p.2.2⟩ + left_inv x := by apply Subtype.ext; rfl + right_inv p := by rcases p with ⟨⟨i,hi⟩,⟨j,hj⟩⟩; rfl + +lemma card_eq_sum_rowLen (μ : YoungDiagram) : μ.card = ∑ i : Fin (μ.colLen 0), μ.rowLen i := by + rw [←card_cell,Fintype.card_congr (cellRowsEquiv μ),Fintype.card_sigma] + simp only [Fintype.card_fin] + +lemma sum_rowLens (μ : YoungDiagram) : μ.rowLens.sum = μ.card := by + rw [card_eq_sum_rowLen,YoungDiagram.rowLens] + rw [Fin.sum_univ_eq_sum_range] + have hh (n : ℕ) : (List.map μ.rowLen (List.range n)).sum = ∑ i ∈ Finset.range n, μ.rowLen i := by + induction n with + | zero => simp + | succ n ih => simp [List.range_succ,List.map_append,Finset.sum_range_succ,ih] + exact hh _ + +noncomputable def diagramPartition (μ : YoungDiagram) : Nat.Partition μ.card where + parts := μ.rowLens + parts_pos := fun {i} hi => μ.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simp + +noncomputable def partitionDiagram {N : ℕ} (p : Nat.Partition N) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +lemma partitionDiagram_rowLens {N : ℕ} (p : Nat.Partition N) : + (partitionDiagram p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + +lemma partitionDiagram_card {N : ℕ} (p : Nat.Partition N) : (partitionDiagram p).card = N := by + rw [←sum_rowLens,partitionDiagram_rowLens] + change (↑(p.parts.sort (· ≥ ·)) : Multiset ℕ).sum = N + rw [Multiset.sort_eq,p.parts_sum] + +lemma partitionDiagram_diagramPartition (μ : YoungDiagram) : + partitionDiagram (diagramPartition μ) = μ := by + apply YoungDiagram.equivListRowLens.injective + apply Subtype.ext + change (partitionDiagram (diagramPartition μ)).rowLens = μ.rowLens + rw [partitionDiagram_rowLens] + change (↑μ.rowLens : Multiset ℕ).sort (· ≥ ·) = μ.rowLens + rw [Multiset.coe_sort,List.mergeSort_eq_self _ μ.rowLens_sorted.pairwise] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def shapePartitionEquiv (N : ℕ) : Shapes N ≃ Nat.Partition N where + toFun μ := { parts := μ.1.rowLens + parts_pos := fun {i} hi => μ.1.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simpa using (sum_rowLens μ.1).trans μ.2 } + invFun p := ⟨partitionDiagram p,partitionDiagram_card p⟩ + left_inv μ := by + apply Subtype.ext + obtain ⟨μ,rfl⟩ := μ + exact partitionDiagram_diagramPartition μ + right_inv p := by + apply Nat.Partition.ext + change ((partitionDiagram p).rowLens : Multiset ℕ) = p.parts + rw [partitionDiagram_rowLens,Multiset.sort_eq] + +noncomputable instance (N : ℕ) : Fintype (Shapes N) := Fintype.ofEquiv _ (shapePartitionEquiv N).symm + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end Thorp.Specht + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace Thorp.LowPlanes +open scoped BigOperators Classical +open Specht UnitaryFinite + +noncomputable local instance hsNorm (μ : YoungDiagram) : NormedAddCommGroup (hilbertSpace μ) := inferInstance +noncomputable local instance hsInner (μ : YoungDiagram) : InnerProductSpace ℂ (hilbertSpace μ) := inferInstance +noncomputable local instance hsFinite (μ : YoungDiagram) : FiniteDimensional ℂ (hilbertSpace μ) := inferInstance + +noncomputable def Q (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) + +noncomputable def absoluteTrace {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + (A : V →L[ℂ] V) (P : ℝ) : ℝ := + (LinearMap.trace ℂ V (CFC.rpow (CFC.sqrt (star A * A)) P).toLinearMap).re + +noncomputable def regularTrace (d : ℕ) (P : ℝ) : ℝ := + ∑ μ : Shapes (2^d), (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + absoluteTrace (V := hilbertSpace μ.1) (Q d μ) P + +noncomputable def sweepDistance (d v : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d (v*d) (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +def MainStatement : Prop := + ∃ P : ℝ, 2 ≤ P ∧ ∀ d : ℕ, 1 ≤ d → + regularTrace d P ≤ 1 + ((2 : ℝ)^d) ^ (-10 : ℤ) ∧ + ∀ v : ℤ, P ≤ 2 * (v : ℝ) → ∀ σ : Equiv.Perm (Card d), + sweepDistance d v.toNat σ ≤ (1/2 : ℝ) * ((2 : ℝ)^d) ^ (-5 : ℤ) + +theorem regular_trace_smoothing : MainStatement := by + sorry + +end Thorp.LowPlanes + +end ThorpNine.Harmonic + +end OAI diff --git a/tasks/coordinate-trace/tests/grade.py b/tasks/coordinate-trace/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coordinate-trace/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coordinate-trace/tests/task.json b/tasks/coordinate-trace/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8d2e660c137c612cd90412ace7a9e06d2d7ebf04 --- /dev/null +++ b/tasks/coordinate-trace/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoordinateTrace", + "comparator": { + "theorem_names": [ + "OAI.ThorpNine.Harmonic.Thorp.LowPlanes.regular_trace_smoothing" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11676 +} \ No newline at end of file diff --git a/tasks/coordinate-trace/tests/test.sh b/tasks/coordinate-trace/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coordinate-trace/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cotype/environment/Dockerfile b/tasks/cotype/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cotype/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cotype/environment/fetch_mathlib.sh b/tasks/cotype/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cotype/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cotype/environment/lake-manifest.json b/tasks/cotype/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cotype/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cotype/environment/lakefile.lean b/tasks/cotype/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cotype/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cotype/environment/lean_setup.sh b/tasks/cotype/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cotype/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cotype/environment/pack_submission.py b/tasks/cotype/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cotype/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cotype/instruction.md b/tasks/cotype/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6a96f6929deb29be559f6fc1a9314ea2d7257064 --- /dev/null +++ b/tasks/cotype/instruction.md @@ -0,0 +1,111 @@ +# openai/math challenge `Cotype` (family 326) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 326 of the release, *The cotype–cotype conjecture under the approximation property* +(Functional analysis). The family as a whole: Resolves the cotype–cotype conjecture for real Banach spaces with the approximation property. Such a nonzero space is $K$-convex if and only if both it and its dual have finite Rademacher cotype, with possibly different exponents. Equivalently, these cotype assumptions force nontrivial Rademacher type. + +The challenge is `Cotype`, also at `/opt/openai-math/challenges/Cotype.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u v + +namespace Cotype + +abbrev Cube (n : ℕ) := Fin n → Bool + +def sign (b : Bool) : ℝ := if b then -1 else 1 + +def average {ι : Type u} [Fintype ι] {E : Type v} [AddCommMonoid E] [Module ℝ E] + (f : ι → E) : E := (Fintype.card ι : ℝ)⁻¹ • ∑ i, f i + +variable (E : Type u) [NormedAddCommGroup E] [NormedSpace ℝ E] + +def cubeL2 {n : ℕ} (f : Cube n → E) : ℝ := + Real.sqrt (average (fun ε => ‖f ε‖ ^ 2)) + +def rademacherSum {n : ℕ} (x : Fin n → E) (ε : Cube n) : E := + ∑ i, sign (ε i) • x i + +def moment {n : ℕ} (f : Cube n → E) (i : Fin n) : E := + average (fun ε => sign (ε i) • f ε) + +def radProjection {n : ℕ} (f : Cube n → E) : Cube n → E := + rademacherSum E (moment E f) + +def KConvex : Prop := ∃ K : ℝ, 0 ≤ K ∧ ∀ (n : ℕ) (f : Cube n → E), + cubeL2 E (radProjection E f) ≤ K * cubeL2 E f + +def HasCotype (q : ℝ) : Prop := 2 ≤ q ∧ ∃ C : ℝ, 0 ≤ C ∧ + ∀ (n : ℕ) (x : Fin n → E), + (∑ i, ‖x i‖ ^ q) ^ (1 / q) ≤ C * cubeL2 E (rademacherSum E x) + +def FiniteCotype : Prop := ∃ q : ℝ, HasCotype E q + +def ApproximationProperty : Prop := ∀ (M : Set E), IsCompact M → + ∀ δ : ℝ, 0 < δ → ∃ S : E →L[ℝ] E, + FiniteDimensional ℝ (LinearMap.range S.toLinearMap) ∧ + ∀ x ∈ M, ‖S x - x‖ < δ + +def MainTarget [CompleteSpace E] [Nontrivial E] : Prop := + ApproximationProperty E → + (KConvex E ↔ FiniteCotype E ∧ FiniteCotype (E →L[ℝ] ℝ)) + +variable {X : Type u} [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + +theorem mainTarget_proved [Nontrivial X] : MainTarget X := by + sorry + +end Cotype + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Cotype.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Cotype.mainTarget_proved` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cotype/solution/closure.txt b/tasks/cotype/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b48dc6444ac41bfbc97fb3b91572ac5f4dce462e --- /dev/null +++ b/tasks/cotype/solution/closure.txt @@ -0,0 +1,125 @@ +OAI.Analysis.Cotype.APNontrivialType +OAI.Analysis.Cotype.Approximation +OAI.Analysis.Cotype.BConvexBlocking +OAI.Analysis.Cotype.BConvexQuantitative +OAI.Analysis.Cotype.BConvexity +OAI.Analysis.Cotype.BiasedFourier +OAI.Analysis.Cotype.BinaryCoordinates +OAI.Analysis.Cotype.BinaryRank +OAI.Analysis.Cotype.BivariateSplit +OAI.Analysis.Cotype.ChebyshevBounds +OAI.Analysis.Cotype.ChebyshevTruncation +OAI.Analysis.Cotype.CoefficientArithmetic +OAI.Analysis.Cotype.CoefficientBounds +OAI.Analysis.Cotype.CoefficientCompactness +OAI.Analysis.Cotype.CoefficientPowerGap +OAI.Analysis.Cotype.CoefficientTarget +OAI.Analysis.Cotype.CompactDomain +OAI.Analysis.Cotype.CompactDomainSource +OAI.Analysis.Cotype.CompactMomentAssembly +OAI.Analysis.Cotype.CompactQuotient +OAI.Analysis.Cotype.ComplexDualLift +OAI.Analysis.Cotype.ComplexPowerGapInverse +OAI.Analysis.Cotype.ComplexProjectionPolynomial +OAI.Analysis.Cotype.ComplexProjectionSpectrum +OAI.Analysis.Cotype.CotypeAmplification +OAI.Analysis.Cotype.Cube +OAI.Analysis.Cotype.CubeCoordinateProjections +OAI.Analysis.Cotype.CubeFirstChaos +OAI.Analysis.Cotype.CubeNoise +OAI.Analysis.Cotype.DampedPolynomial +OAI.Analysis.Cotype.Damping +OAI.Analysis.Cotype.DeletedTail +OAI.Analysis.Cotype.DualAction +OAI.Analysis.Cotype.DualCotypeFromLifts +OAI.Analysis.Cotype.DualMomentLifts +OAI.Analysis.Cotype.EquivariantLifts +OAI.Analysis.Cotype.EquivariantPairing +OAI.Analysis.Cotype.ExponentialIntegral +OAI.Analysis.Cotype.FiniteContour +OAI.Analysis.Cotype.FiniteCotypeBounds +OAI.Analysis.Cotype.FiniteL2Dual +OAI.Analysis.Cotype.FiniteL2DualNorm +OAI.Analysis.Cotype.FiniteLevelLift +OAI.Analysis.Cotype.FiniteLevelTower +OAI.Analysis.Cotype.FiniteRankWalsh +OAI.Analysis.Cotype.FiniteSupDual +OAI.Analysis.Cotype.FixedTypeImprovement +OAI.Analysis.Cotype.Fourier +OAI.Analysis.Cotype.FrameFeasibility +OAI.Analysis.Cotype.FrameLifts +OAI.Analysis.Cotype.FrameOrbit +OAI.Analysis.Cotype.GeometricTypeLevels +OAI.Analysis.Cotype.GroupedPolynomial +OAI.Analysis.Cotype.GrowthCoefficient +OAI.Analysis.Cotype.GrowthScalarData +OAI.Analysis.Cotype.GrowthTheorem +OAI.Analysis.Cotype.GrowthTuplePairing +OAI.Analysis.Cotype.IdentityWalshDecay +OAI.Analysis.Cotype.IndependentSigns +OAI.Analysis.Cotype.KConvexCoordinateCriterion +OAI.Analysis.Cotype.KConvexDuality +OAI.Analysis.Cotype.KConvexUniformL1 +OAI.Analysis.Cotype.L2MomentLifts +OAI.Analysis.Cotype.L2Sequence +OAI.Analysis.Cotype.Main +OAI.Analysis.Cotype.MainConstruction +OAI.Analysis.Cotype.MixedDerivative +OAI.Analysis.Cotype.Model +OAI.Analysis.Cotype.Moments +OAI.Analysis.Cotype.NoiseHypercontractivity +OAI.Analysis.Cotype.OddPatternBounds +OAI.Analysis.Cotype.PairedExtension +OAI.Analysis.Cotype.ParameterChoice +OAI.Analysis.Cotype.PatternNormalization +OAI.Analysis.Cotype.PatternPairing +OAI.Analysis.Cotype.PatternProjections +OAI.Analysis.Cotype.PowerGapInverse +OAI.Analysis.Cotype.PowerGapScaling +OAI.Analysis.Cotype.PrimalMomentLifts +OAI.Analysis.Cotype.ProjectionAverages +OAI.Analysis.Cotype.ProjectionCoefficientDerivative +OAI.Analysis.Cotype.ProjectionCoefficients +OAI.Analysis.Cotype.ProjectionDeficit +OAI.Analysis.Cotype.ProjectionDerivatives +OAI.Analysis.Cotype.ProjectionEigenvectors +OAI.Analysis.Cotype.ProjectionGenerator +OAI.Analysis.Cotype.ProjectionL2Gap +OAI.Analysis.Cotype.ProjectionProducts +OAI.Analysis.Cotype.ProjectionResolvent +OAI.Analysis.Cotype.ProjectionSemigroup +OAI.Analysis.Cotype.ProjectionSemigroupBasics +OAI.Analysis.Cotype.ProjectionSpectrum +OAI.Analysis.Cotype.QuadraticTypeTensor +OAI.Analysis.Cotype.QuotientLifts +OAI.Analysis.Cotype.RademacherComparison +OAI.Analysis.Cotype.RankFactors +OAI.Analysis.Cotype.RankWalsh +OAI.Analysis.Cotype.Rectangles +OAI.Analysis.Cotype.ScalarWalsh +OAI.Analysis.Cotype.SectorResolvent +OAI.Analysis.Cotype.SlowDrop +OAI.Analysis.Cotype.TaggedCoefficient +OAI.Analysis.Cotype.TaggedFrames +OAI.Analysis.Cotype.Target +OAI.Analysis.Cotype.TimedShiftScalars +OAI.Analysis.Cotype.TypeCotypeDuality +OAI.Analysis.Cotype.TypeExtrapolation +OAI.Analysis.Cotype.TypeExtrapolationParameters +OAI.Analysis.Cotype.TypeL2Amplification +OAI.Analysis.Cotype.TypeUniformL1 +OAI.Analysis.Cotype.UniformDecay +OAI.Analysis.Cotype.UniformL1 +OAI.Analysis.Cotype.VectorWalsh +OAI.Analysis.Cotype.VerticalTimeCoefficient +OAI.Analysis.Cotype.WalshAmplification +OAI.Analysis.Cotype.WalshCoordinates +OAI.Analysis.Cotype.WalshDuality +OAI.Analysis.Cotype.WalshExactPairing +OAI.Analysis.Cotype.WalshFrameOrbit +OAI.Analysis.Cotype.WalshLower +OAI.Analysis.Cotype.WalshMainEstimates +OAI.Analysis.Cotype.WalshMonotonicity +OAI.Analysis.Cotype.WalshNorm +OAI.Analysis.Cotype.WalshSymmetry +OAI.Analysis.Cotype.WeightedCompact diff --git a/tasks/cotype/solution/reference.py b/tasks/cotype/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cotype/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cotype/solution/solve.sh b/tasks/cotype/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e827c1c880a5605cdc7301d38a1d0262f581c1e3 --- /dev/null +++ b/tasks/cotype/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Cotype, i.e. module OAI.Analysis.Cotype.Main and the +# 125 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Cotype.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Cotype" diff --git a/tasks/cotype/task.toml b/tasks/cotype/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d11f3436f60179e6569fbd9efc2c663d7a5028c1 --- /dev/null +++ b/tasks/cotype/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cotype" +version = "1.0.0" +description = "Prove Cotype (openai/math family 326: The cotype–cotype conjecture under the approximation property) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Cotype.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Cotype" +family = "326" +family_title = "The cotype–cotype conjecture under the approximation property" +subject = "Functional analysis" +theorems = ["OAI.Cotype.mainTarget_proved"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Cotype.Main" +reference_modules = 125 +reference_lean_bytes = 503929 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1088 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12153 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cotype/tests/Challenge.lean b/tasks/cotype/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5b54fc098ee4b43218690dc256cdd5795ac4a671 --- /dev/null +++ b/tasks/cotype/tests/Challenge.lean @@ -0,0 +1,60 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u v + +namespace Cotype + +abbrev Cube (n : ℕ) := Fin n → Bool + +def sign (b : Bool) : ℝ := if b then -1 else 1 + +def average {ι : Type u} [Fintype ι] {E : Type v} [AddCommMonoid E] [Module ℝ E] + (f : ι → E) : E := (Fintype.card ι : ℝ)⁻¹ • ∑ i, f i + +variable (E : Type u) [NormedAddCommGroup E] [NormedSpace ℝ E] + +def cubeL2 {n : ℕ} (f : Cube n → E) : ℝ := + Real.sqrt (average (fun ε => ‖f ε‖ ^ 2)) + +def rademacherSum {n : ℕ} (x : Fin n → E) (ε : Cube n) : E := + ∑ i, sign (ε i) • x i + +def moment {n : ℕ} (f : Cube n → E) (i : Fin n) : E := + average (fun ε => sign (ε i) • f ε) + +def radProjection {n : ℕ} (f : Cube n → E) : Cube n → E := + rademacherSum E (moment E f) + +def KConvex : Prop := ∃ K : ℝ, 0 ≤ K ∧ ∀ (n : ℕ) (f : Cube n → E), + cubeL2 E (radProjection E f) ≤ K * cubeL2 E f + +def HasCotype (q : ℝ) : Prop := 2 ≤ q ∧ ∃ C : ℝ, 0 ≤ C ∧ + ∀ (n : ℕ) (x : Fin n → E), + (∑ i, ‖x i‖ ^ q) ^ (1 / q) ≤ C * cubeL2 E (rademacherSum E x) + +def FiniteCotype : Prop := ∃ q : ℝ, HasCotype E q + +def ApproximationProperty : Prop := ∀ (M : Set E), IsCompact M → + ∀ δ : ℝ, 0 < δ → ∃ S : E →L[ℝ] E, + FiniteDimensional ℝ (LinearMap.range S.toLinearMap) ∧ + ∀ x ∈ M, ‖S x - x‖ < δ + +def MainTarget [CompleteSpace E] [Nontrivial E] : Prop := + ApproximationProperty E → + (KConvex E ↔ FiniteCotype E ∧ FiniteCotype (E →L[ℝ] ℝ)) + +variable {X : Type u} [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + +theorem mainTarget_proved [Nontrivial X] : MainTarget X := by + sorry + +end Cotype + +end + +end OAI diff --git a/tasks/cotype/tests/grade.py b/tasks/cotype/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cotype/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cotype/tests/task.json b/tasks/cotype/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..05e6ff5f0f33caec17239b95f8ec8a605880252d --- /dev/null +++ b/tasks/cotype/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Cotype", + "comparator": { + "theorem_names": [ + "OAI.Cotype.mainTarget_proved" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11253 +} \ No newline at end of file diff --git a/tasks/cotype/tests/test.sh b/tasks/cotype/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cotype/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coulomb-counterexample/environment/Dockerfile b/tasks/coulomb-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coulomb-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coulomb-counterexample/environment/fetch_mathlib.sh b/tasks/coulomb-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coulomb-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coulomb-counterexample/environment/lake-manifest.json b/tasks/coulomb-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coulomb-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coulomb-counterexample/environment/lakefile.lean b/tasks/coulomb-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coulomb-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coulomb-counterexample/environment/lean_setup.sh b/tasks/coulomb-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coulomb-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coulomb-counterexample/environment/pack_submission.py b/tasks/coulomb-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coulomb-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coulomb-counterexample/instruction.md b/tasks/coulomb-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0f6e7e424f7343416b0ba97d1529fb1be2b0317b --- /dev/null +++ b/tasks/coulomb-counterexample/instruction.md @@ -0,0 +1,153 @@ +# openai/math challenge `CoulombCounterexample` (family 373) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 373 of the release, *Nonattainment in three-marginal Coulomb transport* +(Partial differential equations). The family as a whole: An optimal three-particle Coulomb configuration need not be a deterministic function of the first particle, even for smooth identical spatial densities. The Monge and Kantorovich infima agree, but the Monge infimum is not attained. The same phenomenon occurs for every inverse-power Riesz exponent in each dimension at least two, with a suitable density in each case. + +The challenge is `CoulombCounterexample`, also at `/opt/openai-math/challenges/CoulombCounterexample.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +namespace Problem356 + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +abbrev Triple := E3 × (E3 × E3) + +def tripleFst (t : Triple) : E3 := t.1 + +def tripleSnd (t : Triple) : E3 := t.2.1 + +def tripleThd (t : Triple) : E3 := t.2.2 + +def invDistance (x y : E3) : ℝ≥0∞ := + (ENNReal.ofReal ‖x - y‖)⁻¹ + +def coulombCost (t : Triple) : ℝ≥0∞ := + invDistance (tripleFst t) (tripleSnd t) + + invDistance (tripleFst t) (tripleThd t) + + invDistance (tripleSnd t) (tripleThd t) + +def IsThreeCoupling (mu : Measure E3) (pi : Measure Triple) : Prop := + IsProbabilityMeasure pi ∧ + Measure.map tripleFst pi = mu ∧ + Measure.map tripleSnd pi = mu ∧ + Measure.map tripleThd pi = mu + +def densityMeasure (rho : E3 → ℝ) : Measure E3 := + Measure.withDensity (volume : Measure E3) (fun x => ENNReal.ofReal (rho x)) + +def Preserves (mu : Measure E3) (T : E3 → E3) : Prop := + Measurable T ∧ Measure.map T mu = mu + +def graphCost (mu : Measure E3) (T2 T3 : E3 → E3) : ℝ≥0∞ := + ∫⁻ x, coulombCost (x, (T2 x, T3 x)) ∂mu + +def kantorovichValue (mu : Measure E3) : ℝ≥0∞ := + ⨅ (pi : Measure Triple), ⨅ (_h : IsThreeCoupling mu pi), + ∫⁻ t, coulombCost t ∂pi + +def mongeValue (mu : Measure E3) : ℝ≥0∞ := + ⨅ (T2 : E3 → E3), ⨅ (T3 : E3 → E3), + ⨅ (_h2 : Preserves mu T2), ⨅ (_h3 : Preserves mu T3), + graphCost mu T2 T3 + +def IsSmoothCompactProbabilityDensity (rho : E3 → ℝ) : Prop := + (∀ x, 0 ≤ rho x) ∧ + ContDiff ℝ (↑(⊤ : ENat) : WithTop ENat) rho ∧ + HasCompactSupport rho ∧ + ContDiff ℝ (↑(⊤ : ENat) : WithTop ENat) (fun x : E3 => Real.sqrt (rho x)) ∧ + HasCompactSupport (fun x : E3 => Real.sqrt (rho x)) ∧ + (∫ x : E3, rho x ∂(volume : Measure E3)) = 1 + +def KantorovichAttained (mu : Measure E3) : Prop := + ∃ pi : Measure Triple, + IsThreeCoupling mu pi ∧ + (∫⁻ t, coulombCost t ∂pi) = kantorovichValue mu + +def NoMongeOptimizer (mu : Measure E3) : Prop := + ∀ T2 T3 : E3 → E3, + Preserves mu T2 → Preserves mu T3 → + kantorovichValue mu < graphCost mu T2 T3 + +def FiniteMongeApproximation (mu : Measure E3) : Prop := + ∀ epsilon : ℝ, 0 < epsilon → + ∃ T2 T3 : E3 → E3, + Preserves mu T2 ∧ + Preserves mu T3 ∧ + graphCost mu T2 T3 < ⊤ ∧ + graphCost mu T2 T3 ≤ + kantorovichValue mu + ENNReal.ofReal epsilon + +def HasCoulombCounterexample (rho : E3 → ℝ) : Prop := + IsSmoothCompactProbabilityDensity rho ∧ + IsProbabilityMeasure (densityMeasure rho) ∧ + kantorovichValue (densityMeasure rho) < ⊤ ∧ + KantorovichAttained (densityMeasure rho) ∧ + NoMongeOptimizer (densityMeasure rho) + +def HasFullCoulombConclusion (rho : E3 → ℝ) : Prop := + HasCoulombCounterexample rho ∧ + mongeValue (densityMeasure rho) = + kantorovichValue (densityMeasure rho) ∧ + FiniteMongeApproximation (densityMeasure rho) + +theorem coulomb_counterexample_and_equal_infima : + ∃ rho : E3 → ℝ, HasFullCoulombConclusion rho := by + sorry + +end Problem356 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoulombCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem356.coulomb_counterexample_and_equal_infima` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coulomb-counterexample/solution/closure.txt b/tasks/coulomb-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6135ba5e1c0083736ce55eaba893c8b8c9e3b177 --- /dev/null +++ b/tasks/coulomb-counterexample/solution/closure.txt @@ -0,0 +1,97 @@ +OAI.Analysis.CoulombTransport.ActualGeometryConclusion +OAI.Analysis.CoulombTransport.All +OAI.Analysis.CoulombTransport.AnalyticCoulomb +OAI.Analysis.CoulombTransport.AtomlessMap +OAI.Analysis.CoulombTransport.AtomlessTransport +OAI.Analysis.CoulombTransport.AxisHessian +OAI.Analysis.CoulombTransport.BorelTransport +OAI.Analysis.CoulombTransport.BranchCoupling +OAI.Analysis.CoulombTransport.BranchDensity +OAI.Analysis.CoulombTransport.BranchInterfaces +OAI.Analysis.CoulombTransport.BranchOptimizer +OAI.Analysis.CoulombTransport.BranchSeparation +OAI.Analysis.CoulombTransport.Calibration +OAI.Analysis.CoulombTransport.CellOscillation +OAI.Analysis.CoulombTransport.CellTable +OAI.Analysis.CoulombTransport.CellwiseLift +OAI.Analysis.CoulombTransport.CenterAxis +OAI.Analysis.CoulombTransport.CenterCertificate +OAI.Analysis.CoulombTransport.CertificateAttainment +OAI.Analysis.CoulombTransport.CertificateDuality +OAI.Analysis.CoulombTransport.CertificateNeighborhoods +OAI.Analysis.CoulombTransport.CommonBranches +OAI.Analysis.CoulombTransport.CompactLiftApproximation +OAI.Analysis.CoulombTransport.CompactPartition +OAI.Analysis.CoulombTransport.CompactSeparation +OAI.Analysis.CoulombTransport.ComponentCertificate +OAI.Analysis.CoulombTransport.ComponentPotential +OAI.Analysis.CoulombTransport.ComponentRegions +OAI.Analysis.CoulombTransport.Conclusion +OAI.Analysis.CoulombTransport.ContactCommonBranches +OAI.Analysis.CoulombTransport.ContactObstruction +OAI.Analysis.CoulombTransport.ContactSelection +OAI.Analysis.CoulombTransport.ContactSelectionAE +OAI.Analysis.CoulombTransport.ContinuousCDF +OAI.Analysis.CoulombTransport.CostTopology +OAI.Analysis.CoulombTransport.CoulombBranches +OAI.Analysis.CoulombTransport.CoulombCalculus +OAI.Analysis.CoulombTransport.CoulombCharts +OAI.Analysis.CoulombTransport.CoulombCoercivity +OAI.Analysis.CoulombTransport.CoulombEstimates +OAI.Analysis.CoulombTransport.CoulombLocalCertificate +OAI.Analysis.CoulombTransport.CoulombSupportExistence +OAI.Analysis.CoulombTransport.CoulombSupportSeparated +OAI.Analysis.CoulombTransport.CounterexampleAssembly +OAI.Analysis.CoulombTransport.CouplingSupport +OAI.Analysis.CoulombTransport.Density +OAI.Analysis.CoulombTransport.DensityMeasure +OAI.Analysis.CoulombTransport.DensityMixture +OAI.Analysis.CoulombTransport.DisjointSquares +OAI.Analysis.CoulombTransport.DualCertificate +OAI.Analysis.CoulombTransport.Endgame +OAI.Analysis.CoulombTransport.EqualInfima +OAI.Analysis.CoulombTransport.ExistenceFromLocalGeometry +OAI.Analysis.CoulombTransport.ExtendedPushforward +OAI.Analysis.CoulombTransport.FiniteMassSplit +OAI.Analysis.CoulombTransport.FirstCoordinateLift +OAI.Analysis.CoulombTransport.FiveComponentCanonical +OAI.Analysis.CoulombTransport.FiveComponentGeometry +OAI.Analysis.CoulombTransport.FiveComponentGlobal +OAI.Analysis.CoulombTransport.FiveComponentSelection +OAI.Analysis.CoulombTransport.GeometryJets +OAI.Analysis.CoulombTransport.GluedCertificate +OAI.Analysis.CoulombTransport.GluedCertificateForward +OAI.Analysis.CoulombTransport.GoodTypePermutation +OAI.Analysis.CoulombTransport.GraphBridge +OAI.Analysis.CoulombTransport.HessianCLM +OAI.Analysis.CoulombTransport.HessianCoercivity +OAI.Analysis.CoulombTransport.HessianMatrix +OAI.Analysis.CoulombTransport.IsometryTransport +OAI.Analysis.CoulombTransport.JacobianSquareRoot +OAI.Analysis.CoulombTransport.LocalBranchMeasure +OAI.Analysis.CoulombTransport.LocalCertificate +OAI.Analysis.CoulombTransport.LocalImplicit +OAI.Analysis.CoulombTransport.LocalPotentialBounds +OAI.Analysis.CoulombTransport.LocalSplitting +OAI.Analysis.CoulombTransport.Main +OAI.Analysis.CoulombTransport.Model +OAI.Analysis.CoulombTransport.NeighborhoodCertificate +OAI.Analysis.CoulombTransport.OptimalLocalization +OAI.Analysis.CoulombTransport.PairEnergyFinite +OAI.Analysis.CoulombTransport.PartitionLabel +OAI.Analysis.CoulombTransport.PartitionTransport +OAI.Analysis.CoulombTransport.ProductPlan +OAI.Analysis.CoulombTransport.RealCounterexampleAssembly +OAI.Analysis.CoulombTransport.SeparatedLiftApproximation +OAI.Analysis.CoulombTransport.SmoothBranchMarginal +OAI.Analysis.CoulombTransport.SmoothPushforward +OAI.Analysis.CoulombTransport.SplitMeasure +OAI.Analysis.CoulombTransport.Splitting +OAI.Analysis.CoulombTransport.SplittingConstruction +OAI.Analysis.CoulombTransport.StateDual +OAI.Analysis.CoulombTransport.StationaryConvexity +OAI.Analysis.CoulombTransport.StationaryEquation +OAI.Analysis.CoulombTransport.StationaryMap +OAI.Analysis.CoulombTransport.StrictMinimum +OAI.Analysis.CoulombTransport.Symmetrization +OAI.Analysis.CoulombTransport.TriplePermutation diff --git a/tasks/coulomb-counterexample/solution/reference.py b/tasks/coulomb-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coulomb-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coulomb-counterexample/solution/solve.sh b/tasks/coulomb-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e75294b37168df0d46c23598d0142f59c1948c00 --- /dev/null +++ b/tasks/coulomb-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoulombCounterexample, i.e. module OAI.Analysis.CoulombTransport.Main and the +# 97 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.CoulombTransport.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoulombCounterexample" diff --git a/tasks/coulomb-counterexample/task.toml b/tasks/coulomb-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8aa8ddce8eb1730fa2e48e81b06976bb2c5c352d --- /dev/null +++ b/tasks/coulomb-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coulomb-counterexample" +version = "1.0.0" +description = "Prove CoulombCounterexample (openai/math family 373: Nonattainment in three-marginal Coulomb transport) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoulombCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoulombCounterexample" +family = "373" +family_title = "Nonattainment in three-marginal Coulomb transport" +subject = "Partial differential equations" +theorems = ["OAI.Problem356.coulomb_counterexample_and_equal_infima"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.CoulombTransport.Main" +reference_modules = 97 +reference_lean_bytes = 467629 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 891 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12120 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coulomb-counterexample/tests/Challenge.lean b/tasks/coulomb-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b3184926ff734f2db7a5201fc01bcc8a7062a457 --- /dev/null +++ b/tasks/coulomb-counterexample/tests/Challenge.lean @@ -0,0 +1,102 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +namespace Problem356 + +abbrev E3 := EuclideanSpace ℝ (Fin 3) + +abbrev Triple := E3 × (E3 × E3) + +def tripleFst (t : Triple) : E3 := t.1 + +def tripleSnd (t : Triple) : E3 := t.2.1 + +def tripleThd (t : Triple) : E3 := t.2.2 + +def invDistance (x y : E3) : ℝ≥0∞ := + (ENNReal.ofReal ‖x - y‖)⁻¹ + +def coulombCost (t : Triple) : ℝ≥0∞ := + invDistance (tripleFst t) (tripleSnd t) + + invDistance (tripleFst t) (tripleThd t) + + invDistance (tripleSnd t) (tripleThd t) + +def IsThreeCoupling (mu : Measure E3) (pi : Measure Triple) : Prop := + IsProbabilityMeasure pi ∧ + Measure.map tripleFst pi = mu ∧ + Measure.map tripleSnd pi = mu ∧ + Measure.map tripleThd pi = mu + +def densityMeasure (rho : E3 → ℝ) : Measure E3 := + Measure.withDensity (volume : Measure E3) (fun x => ENNReal.ofReal (rho x)) + +def Preserves (mu : Measure E3) (T : E3 → E3) : Prop := + Measurable T ∧ Measure.map T mu = mu + +def graphCost (mu : Measure E3) (T2 T3 : E3 → E3) : ℝ≥0∞ := + ∫⁻ x, coulombCost (x, (T2 x, T3 x)) ∂mu + +def kantorovichValue (mu : Measure E3) : ℝ≥0∞ := + ⨅ (pi : Measure Triple), ⨅ (_h : IsThreeCoupling mu pi), + ∫⁻ t, coulombCost t ∂pi + +def mongeValue (mu : Measure E3) : ℝ≥0∞ := + ⨅ (T2 : E3 → E3), ⨅ (T3 : E3 → E3), + ⨅ (_h2 : Preserves mu T2), ⨅ (_h3 : Preserves mu T3), + graphCost mu T2 T3 + +def IsSmoothCompactProbabilityDensity (rho : E3 → ℝ) : Prop := + (∀ x, 0 ≤ rho x) ∧ + ContDiff ℝ (↑(⊤ : ENat) : WithTop ENat) rho ∧ + HasCompactSupport rho ∧ + ContDiff ℝ (↑(⊤ : ENat) : WithTop ENat) (fun x : E3 => Real.sqrt (rho x)) ∧ + HasCompactSupport (fun x : E3 => Real.sqrt (rho x)) ∧ + (∫ x : E3, rho x ∂(volume : Measure E3)) = 1 + +def KantorovichAttained (mu : Measure E3) : Prop := + ∃ pi : Measure Triple, + IsThreeCoupling mu pi ∧ + (∫⁻ t, coulombCost t ∂pi) = kantorovichValue mu + +def NoMongeOptimizer (mu : Measure E3) : Prop := + ∀ T2 T3 : E3 → E3, + Preserves mu T2 → Preserves mu T3 → + kantorovichValue mu < graphCost mu T2 T3 + +def FiniteMongeApproximation (mu : Measure E3) : Prop := + ∀ epsilon : ℝ, 0 < epsilon → + ∃ T2 T3 : E3 → E3, + Preserves mu T2 ∧ + Preserves mu T3 ∧ + graphCost mu T2 T3 < ⊤ ∧ + graphCost mu T2 T3 ≤ + kantorovichValue mu + ENNReal.ofReal epsilon + +def HasCoulombCounterexample (rho : E3 → ℝ) : Prop := + IsSmoothCompactProbabilityDensity rho ∧ + IsProbabilityMeasure (densityMeasure rho) ∧ + kantorovichValue (densityMeasure rho) < ⊤ ∧ + KantorovichAttained (densityMeasure rho) ∧ + NoMongeOptimizer (densityMeasure rho) + +def HasFullCoulombConclusion (rho : E3 → ℝ) : Prop := + HasCoulombCounterexample rho ∧ + mongeValue (densityMeasure rho) = + kantorovichValue (densityMeasure rho) ∧ + FiniteMongeApproximation (densityMeasure rho) + +theorem coulomb_counterexample_and_equal_infima : + ∃ rho : E3 → ℝ, HasFullCoulombConclusion rho := by + sorry + +end Problem356 + +end + +end OAI diff --git a/tasks/coulomb-counterexample/tests/grade.py b/tasks/coulomb-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coulomb-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coulomb-counterexample/tests/task.json b/tasks/coulomb-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..deb02203e3bed8a95348d071b23628297db5bb20 --- /dev/null +++ b/tasks/coulomb-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoulombCounterexample", + "comparator": { + "theorem_names": [ + "OAI.Problem356.coulomb_counterexample_and_equal_infima" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11220 +} \ No newline at end of file diff --git a/tasks/coulomb-counterexample/tests/test.sh b/tasks/coulomb-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coulomb-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coulomb-ionization/environment/Dockerfile b/tasks/coulomb-ionization/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coulomb-ionization/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coulomb-ionization/environment/fetch_mathlib.sh b/tasks/coulomb-ionization/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coulomb-ionization/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coulomb-ionization/environment/lake-manifest.json b/tasks/coulomb-ionization/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coulomb-ionization/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coulomb-ionization/environment/lakefile.lean b/tasks/coulomb-ionization/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coulomb-ionization/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coulomb-ionization/environment/lean_setup.sh b/tasks/coulomb-ionization/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coulomb-ionization/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coulomb-ionization/environment/pack_submission.py b/tasks/coulomb-ionization/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coulomb-ionization/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coulomb-ionization/instruction.md b/tasks/coulomb-ionization/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4314d5ea3bd87aeca5fd46c56b8d7e064866a83 --- /dev/null +++ b/tasks/coulomb-ionization/instruction.md @@ -0,0 +1,150 @@ +# openai/math challenge `CoulombIonization` (family 263) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 263 of the release, *The ionization and generalized ionization conjectures* +(Mathematical physics). The family as a whole: For the full nonrelativistic Coulomb model with two electron spin states, proves that a molecule with $M$ fixed nuclei of charges at least one and total charge $Z$ strictly binds at most $Z+CM$ electrons. Neutral-atom first ionization energies and radii containing all but an expected half-electron have universal positive upper and lower bounds. The energy cost of removing $m$ electrons has Thomas–Fermi asymptotics as $m\to\infty$ and $Z/m\to\infty$; neutral-atom outer radii have the corresponding iterated-limit asymptotics, taking $Z\to\infty$ first. + +The challenge is `CoulombIonization`, also at `/opt/openai-math/challenges/CoulombIonization.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory Filter +open scoped Topology BigOperators ContDiff + +noncomputable section +namespace CoulombAtom + +abbrev Space := EuclideanSpace ℝ (Fin 3) +abbrev Configuration (N : ℕ) := Fin N → Space +abbrev Spins (N : ℕ) := Fin N → Fin 2 + +structure FormVector (N : ℕ) where + value : Spins N → Configuration N → ℂ + gradient : Spins N → Fin N → Fin 3 → Configuration N → ℂ + +def direction {N : ℕ} (i : Fin N) (a : Fin 3) : Configuration N := + Pi.single i (EuclideanSpace.single a 1) + +def FormAdmissible {N : ℕ} (ψ : FormVector N) : Prop := + (∀ s, MemLp (ψ.value s) 2) ∧ + (∀ s i a, MemLp (ψ.gradient s i a) 2) ∧ + (∀ s i a (φ : Configuration N → ℝ), + ContDiff ℝ ∞ φ → HasCompactSupport φ → + (∫ x, ψ.value s x * Complex.ofReal (lineDeriv ℝ φ x (direction i a))) = + -(∫ x, ψ.gradient s i a x * (φ x : ℂ))) ∧ + (∀ (π : Equiv.Perm (Fin N)) s, ∀ᵐ x, + ψ.value (s ∘ π) (x ∘ π) = + (((Equiv.Perm.sign π : ℤ) : ℂ) * ψ.value s x)) ∧ + (∑ s : Spins N, ∫ x, ‖ψ.value s x‖ ^ 2) = 1 ∧ + (∀ s i, Integrable (fun x => ‖ψ.value s x‖ ^ 2 / ‖x i‖)) ∧ + (∀ s i j, i ≠ j → + Integrable (fun x => ‖ψ.value s x‖ ^ 2 / ‖x i - x j‖)) + +def formEnergy {N : ℕ} (Z : ℝ) (ψ : FormVector N) : ℝ := + (1 / 2 : ℝ) * + (∑ s : Spins N, ∑ i : Fin N, ∑ a : Fin 3, + (∫ x, ‖ψ.gradient s i a x‖ ^ 2)) - + Z * (∑ s : Spins N, ∑ i : Fin N, + (∫ x, ‖ψ.value s x‖ ^ 2 / ‖x i‖)) + + (∑ s : Spins N, ∑ i : Fin N, ∑ j : Fin N, + if i < j then (∫ x, ‖ψ.value s x‖ ^ 2 / ‖x i - x j‖) else 0) + +def energy (Z : ℝ) (N : ℕ) : ℝ := + if N = 0 then 0 else sInf {e | ∃ ψ : FormVector N, + FormAdmissible ψ ∧ formEnergy Z ψ = e} + +def ionization (m Z : ℕ) : ℝ := + energy Z (Z - m) - energy Z Z + +def tfKinetic : ℝ := (3 / 10 : ℝ) * (3 * Real.pi ^ 2) ^ (2 / 3 : ℝ) + +def directIntegrand (ρ : Space → ℝ) (p : Space × Space) : ℝ := + ρ p.1 * ρ p.2 / ‖p.1 - p.2‖ + +def TFAdmissible (M : ℝ) (ρ : Space → ℝ) : Prop := + (∀ᵐ x, 0 ≤ ρ x) ∧ Integrable ρ ∧ (∫ x, ρ x) = M ∧ + Integrable (fun x => ρ x ^ (5 / 3 : ℝ)) ∧ + Integrable (fun x => ρ x / ‖x‖) ∧ Integrable (directIntegrand ρ) + +def tfFunctional (Z : ℝ) (ρ : Space → ℝ) : ℝ := + tfKinetic * (∫ x, ρ x ^ (5 / 3 : ℝ)) - Z * (∫ x, ρ x / ‖x‖) + + (1 / 2 : ℝ) * ∫ p, directIntegrand ρ p + +def tfEnergy (Z M : ℝ) : ℝ := + sInf {e | ∃ ρ : Space → ℝ, TFAdmissible M ρ ∧ tfFunctional Z ρ = e} + +def tfIonization (m Z : ℝ) : ℝ := tfEnergy Z (Z - m) - tfEnergy Z Z + +def TFCharacterization (a : ℝ) : Prop := + ∀ m : ℝ, 0 < m → + Tendsto (tfIonization m) atTop (𝓝 (a * m ^ (7 / 3 : ℝ))) + +def JointLimit (a : ℝ) : Prop := + ∀ m Z : ℕ → ℕ, (∀ j, 1 ≤ m j ∧ m j < Z j) → + Tendsto m atTop atTop → + Tendsto (fun j => (Z j : ℝ) / (m j : ℝ)) atTop atTop → + Tendsto (fun j => ionization (m j) (Z j) / (m j : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) + +def IteratedLimits (a : ℝ) : Prop := + Tendsto (fun m : ℕ => (limsup (ionization m) atTop) / (m : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) ∧ + Tendsto (fun m : ℕ => (liminf (ionization m) atTop) / (m : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) + +def MainStatement : Prop := + ∃ a : ℝ, 0 < a ∧ TFCharacterization a ∧ JointLimit a ∧ IteratedLimits a + +theorem generalized_ionization : MainStatement := by + sorry + +end CoulombAtom + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoulombIonization.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CoulombAtom.generalized_ionization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coulomb-ionization/solution/closure.txt b/tasks/coulomb-ionization/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0a02e81f760d1260f55e5316a45fb8a73e0359a --- /dev/null +++ b/tasks/coulomb-ionization/solution/closure.txt @@ -0,0 +1,607 @@ +OAI.Analysis.CoulombIonization.Fermionic.ApproximateEventTilt +OAI.Analysis.CoulombIonization.Fermionic.Basis +OAI.Analysis.CoulombIonization.Fermionic.CorePotentialTower +OAI.Analysis.CoulombIonization.Fermionic.CountableTests +OAI.Analysis.CoulombIonization.Fermionic.CutCountDomination +OAI.Analysis.CoulombIonization.Fermionic.Density +OAI.Analysis.CoulombIonization.Fermionic.DyadicPowerSq +OAI.Analysis.CoulombIonization.Fermionic.FreqCut +OAI.Analysis.CoulombIonization.Fermionic.GlobalDensityConstant +OAI.Analysis.CoulombIonization.Fermionic.HalfScaleNormSq +OAI.Analysis.CoulombIonization.Fermionic.InfiniteDensity +OAI.Analysis.CoulombIonization.Fermionic.InsertTest +OAI.Analysis.CoulombIonization.Fermionic.ManyTest +OAI.Analysis.CoulombIonization.Fermionic.Multiplier +OAI.Analysis.CoulombIonization.Fermionic.Multiplier2 +OAI.Analysis.CoulombIonization.Fermionic.MultiplierError +OAI.Analysis.CoulombIonization.Fermionic.OccupationPairDensity +OAI.Analysis.CoulombIonization.Fermionic.ParticleDensity +OAI.Analysis.CoulombIonization.Fermionic.Pauli +OAI.Analysis.CoulombIonization.Fermionic.Pull +OAI.Analysis.CoulombIonization.Fermionic.QuantumEventMultiplier +OAI.Analysis.CoulombIonization.Fermionic.QuantumEventTilt +OAI.Analysis.CoulombIonization.Fermionic.Slater +OAI.Analysis.CoulombIonization.Fermionic.SlaterBody +OAI.Analysis.CoulombIonization.Fermionic.SlaterMeasure +OAI.Analysis.CoulombIonization.Fermionic.SlaterOccupation +OAI.Analysis.CoulombIonization.Fermionic.SlaterPairAlgebra +OAI.Analysis.CoulombIonization.Fermionic.SlaterPairTrace +OAI.Analysis.CoulombIonization.Fermionic.SlaterPole +OAI.Analysis.CoulombIonization.Fermionic.SlaterRepulsion +OAI.Analysis.CoulombIonization.Fermionic.SlaterSymmetry +OAI.Analysis.CoulombIonization.Fermionic.SlaterTwoBody +OAI.Analysis.CoulombIonization.Fermionic.Spin +OAI.Analysis.CoulombIonization.Fermionic.Sum +OAI.Analysis.CoulombIonization.Fermionic.WeightedCoreStatistics +OAI.Analysis.CoulombIonization.Fermionic.WeightedPairDensity +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierInitialPoissonBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierNonlinearBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierNuclearBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierObservationTowerBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierTransferPoissonBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BarrierWeakMaxBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.BoundedL1PoissonBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.CapProbabilityWeightBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.CellFieldNormalizationBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.Conditional +OAI.Analysis.CoulombIonization.FieldAnalysis.Conditional2 +OAI.Analysis.CoulombIonization.FieldAnalysis.Conditional3 +OAI.Analysis.CoulombIonization.FieldAnalysis.ConditionalFieldIdentity +OAI.Analysis.CoulombIonization.FieldAnalysis.ConditionalObservables +OAI.Analysis.CoulombIonization.FieldAnalysis.ConditionalShellField +OAI.Analysis.CoulombIonization.FieldAnalysis.CoreFieldPairing +OAI.Analysis.CoulombIonization.FieldAnalysis.CoreFieldRegularity +OAI.Analysis.CoulombIonization.FieldAnalysis.CoreHistoryFieldBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.CoreSubmeanSquareBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.CorrectedFieldCharge +OAI.Analysis.CoulombIonization.FieldAnalysis.CubeDensity +OAI.Analysis.CoulombIonization.FieldAnalysis.CubeRotations +OAI.Analysis.CoulombIonization.FieldAnalysis.CubeTiling +OAI.Analysis.CoulombIonization.FieldAnalysis.CubeTranslationAverage +OAI.Analysis.CoulombIonization.FieldAnalysis.DeletedFieldBudget +OAI.Analysis.CoulombIonization.FieldAnalysis.ExpandedAnnulusSmallEventIntegral +OAI.Analysis.CoulombIonization.FieldAnalysis.ExpectedPatchCenter +OAI.Analysis.CoulombIonization.FieldAnalysis.FineLocalPotential +OAI.Analysis.CoulombIonization.FieldAnalysis.FineSmearingPotential +OAI.Analysis.CoulombIonization.FieldAnalysis.FiniteMean +OAI.Analysis.CoulombIonization.FieldAnalysis.FiniteProfile +OAI.Analysis.CoulombIonization.FieldAnalysis.FreshFieldTower +OAI.Analysis.CoulombIonization.FieldAnalysis.FreshKineticBudgetBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.HardyField +OAI.Analysis.CoulombIonization.FieldAnalysis.InnerCapStatistic +OAI.Analysis.CoulombIonization.FieldAnalysis.InnerExterior +OAI.Analysis.CoulombIonization.FieldAnalysis.InnerFieldCap +OAI.Analysis.CoulombIonization.FieldAnalysis.LaplacianCompDilation +OAI.Analysis.CoulombIonization.FieldAnalysis.LinearCoulomb +OAI.Analysis.CoulombIonization.FieldAnalysis.LocalFieldBootstrapBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.LocalFieldEnvelopeBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.LocalFieldScalarBoundBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.LocalGreen +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannCounts +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannCube +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannFermions +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannGradient +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannPhysical +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannReindex +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannSine +OAI.Analysis.CoulombIonization.FieldAnalysis.NeumannWeak +OAI.Analysis.CoulombIonization.FieldAnalysis.Nonneg +OAI.Analysis.CoulombIonization.FieldAnalysis.ObservedFieldScale +OAI.Analysis.CoulombIonization.FieldAnalysis.OriginalFieldOscillationBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.OutMaximumSubmeanBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.OuterFieldMaximum +OAI.Analysis.CoulombIonization.FieldAnalysis.OwnProbabilityFieldCapBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.PatchMassSubmeanBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.PatchWeakPoisson +OAI.Analysis.CoulombIonization.FieldAnalysis.PauliMomentum +OAI.Analysis.CoulombIonization.FieldAnalysis.PhysicalGridMeasurable +OAI.Analysis.CoulombIonization.FieldAnalysis.PressureWeak +OAI.Analysis.CoulombIonization.FieldAnalysis.PuncturedGreenBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.QuantumFieldExcessBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.RadialPower +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedFieldIdentity +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedInnerMassBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedKineticLower +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedMeasurable +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedPatchDensity +OAI.Analysis.CoulombIonization.FieldAnalysis.RetainedSmear +OAI.Analysis.CoulombIonization.FieldAnalysis.RotationTrace +OAI.Analysis.CoulombIonization.FieldAnalysis.ScaledSmearPressure +OAI.Analysis.CoulombIonization.FieldAnalysis.SelectedBarrierTransferBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.ShellBiasField +OAI.Analysis.CoulombIonization.FieldAnalysis.ShellMeanStatistic +OAI.Analysis.CoulombIonization.FieldAnalysis.SmearTestRecovery +OAI.Analysis.CoulombIonization.FieldAnalysis.SphericalMeanFieldBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.ThinFieldConstantsBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.ThinFieldFeedbackBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.UnshiftedField +OAI.Analysis.CoulombIonization.FieldAnalysis.Vartheta +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakExteriorDecayBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakFieldLimitBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakHarmonicL1Barrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakHarmonicMean +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakHarmonicOscillation +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakHarmonicRegularityBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakPoissonOscillationBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeakPositiveComparisonBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.WeightedAverage +OAI.Analysis.CoulombIonization.FieldAnalysis.WeightedCapLimitBarrier +OAI.Analysis.CoulombIonization.FieldAnalysis.dShellInnerField +OAI.Analysis.CoulombIonization.FormDomain.ActualMasterCenterComparison +OAI.Analysis.CoulombIonization.FormDomain.ApproximateLipschitz +OAI.Analysis.CoulombIonization.FormDomain.BindingSums +OAI.Analysis.CoulombIonization.FormDomain.BlockEnergetics +OAI.Analysis.CoulombIonization.FormDomain.BlockWedge +OAI.Analysis.CoulombIonization.FormDomain.CoerciveOperator +OAI.Analysis.CoulombIonization.FormDomain.CoherentHilbert +OAI.Analysis.CoulombIonization.FormDomain.CoherentLimitInsertion +OAI.Analysis.CoulombIonization.FormDomain.CoherentSchwartz +OAI.Analysis.CoulombIonization.FormDomain.CompCL +OAI.Analysis.CoulombIonization.FormDomain.CompactEigenbasis +OAI.Analysis.CoulombIonization.FormDomain.CoreKinetic +OAI.Analysis.CoulombIonization.FormDomain.CoreSliceMassIntegrable +OAI.Analysis.CoulombIonization.FormDomain.CosetWedge +OAI.Analysis.CoulombIonization.FormDomain.CoulombCoercivity +OAI.Analysis.CoulombIonization.FormDomain.FermionDensityMass +OAI.Analysis.CoulombIonization.FormDomain.FermionicDensity +OAI.Analysis.CoulombIonization.FormDomain.FiniteFermionEnsemble +OAI.Analysis.CoulombIonization.FormDomain.Form +OAI.Analysis.CoulombIonization.FormDomain.FormBody +OAI.Analysis.CoulombIonization.FormDomain.FormBottom +OAI.Analysis.CoulombIonization.FormDomain.FormRawPotential +OAI.Analysis.CoulombIonization.FormDomain.Forms +OAI.Analysis.CoulombIonization.FormDomain.FourierMomentGradient +OAI.Analysis.CoulombIonization.FormDomain.FullSpectral +OAI.Analysis.CoulombIonization.FormDomain.GradientVector +OAI.Analysis.CoulombIonization.FormDomain.GraphWeightIntegral +OAI.Analysis.CoulombIonization.FormDomain.InnerLinearCap +OAI.Analysis.CoulombIonization.FormDomain.L2 +OAI.Analysis.CoulombIonization.FormDomain.LipschitzResidualBase +OAI.Analysis.CoulombIonization.FormDomain.LipschitzWeak +OAI.Analysis.CoulombIonization.FormDomain.PhysicalGrid +OAI.Analysis.CoulombIonization.FormDomain.Restriction +OAI.Analysis.CoulombIonization.FormDomain.ShiftedCoulombIntegrable +OAI.Analysis.CoulombIonization.FormDomain.ShiftedFormBottom +OAI.Analysis.CoulombIonization.FormDomain.Slater +OAI.Analysis.CoulombIonization.FormDomain.SobolevVector +OAI.Analysis.CoulombIonization.FormDomain.SumForm +OAI.Analysis.CoulombIonization.FormDomain.TrialSmoothTest +OAI.Analysis.CoulombIonization.FormDomain.UnboundedSpectrum +OAI.Analysis.CoulombIonization.FormDomain.UniformFormResidual +OAI.Analysis.CoulombIonization.FormDomain.WeakChangeVariables +OAI.Analysis.CoulombIonization.FormDomain.WeakComparison +OAI.Analysis.CoulombIonization.FormDomain.WeakDerivative +OAI.Analysis.CoulombIonization.FormDomain.WeakDerivativeSmulL2 +OAI.Analysis.CoulombIonization.FormDomain.WeakDirectionalDerivative +OAI.Analysis.CoulombIonization.FormDomain.WeakL2PartialDerivative +OAI.Analysis.CoulombIonization.FormDomain.WeakMaximum +OAI.Analysis.CoulombIonization.FormDomain.WeakProduct +OAI.Analysis.CoulombIonization.Ionization.ActualPricedParticleBound +OAI.Analysis.CoulombIonization.Ionization.ActualTFCoefficient +OAI.Analysis.CoulombIonization.Ionization.ActualUnshiftedBudget +OAI.Analysis.CoulombIonization.Ionization.ActualUpperDeficitBarrier +OAI.Analysis.CoulombIonization.Ionization.BarrierActualMeanFieldBarrier +OAI.Analysis.CoulombIonization.Ionization.BarrierInitialDeterministicBarrier +OAI.Analysis.CoulombIonization.Ionization.BarrierInitialEventBarrier +OAI.Analysis.CoulombIonization.Ionization.CoherentDerivatives +OAI.Analysis.CoulombIonization.Ionization.ConditionalPatchMinimizer +OAI.Analysis.CoulombIonization.Ionization.ConditionalPricedUpper +OAI.Analysis.CoulombIonization.Ionization.CoreHistoryFieldFubiniBarrier +OAI.Analysis.CoulombIonization.Ionization.InsertionTermsDisjointSet +OAI.Analysis.CoulombIonization.Ionization.IntegratedStability +OAI.Analysis.CoulombIonization.Ionization.IteratedReduction +OAI.Analysis.CoulombIonization.Ionization.MasterJointPosterior +OAI.Analysis.CoulombIonization.Ionization.MasterPosteriorPotential +OAI.Analysis.CoulombIonization.Ionization.MasterPotentialEvent +OAI.Analysis.CoulombIonization.Ionization.OriginalTFScale +OAI.Analysis.CoulombIonization.Ionization.PricedAnnularCountBarrier +OAI.Analysis.CoulombIonization.Ionization.PricedCoulombTail +OAI.Analysis.CoulombIonization.Ionization.PricedSelectedMaster +OAI.Analysis.CoulombIonization.Ionization.PricedSubsequence +OAI.Analysis.CoulombIonization.Ionization.PricedUpperComparison +OAI.Analysis.CoulombIonization.Ionization.PullAdjoint +OAI.Analysis.CoulombIonization.Ionization.SelectedProfileSubsequence +OAI.Analysis.CoulombIonization.Ionization.SharpEventLawJointComparisonCell +OAI.Analysis.CoulombIonization.Ionization.SharpJointComparisonBarrier +OAI.Analysis.CoulombIonization.Ionization.SpatialCapActualBarrier +OAI.Analysis.CoulombIonization.Ionization.TFPriceData +OAI.Analysis.CoulombIonization.Localization.ActualPointInverseBarrier +OAI.Analysis.CoulombIonization.Localization.ActualPosteriorCapBarrier +OAI.Analysis.CoulombIonization.Localization.ActualTailStateCapBarrier +OAI.Analysis.CoulombIonization.Localization.ArraySymmetry +OAI.Analysis.CoulombIonization.Localization.BarrierConditionalBarrier +OAI.Analysis.CoulombIonization.Localization.BarrierEventSymmetryBarrier +OAI.Analysis.CoulombIonization.Localization.BarrierOrdinaryGlobalBarrier +OAI.Analysis.CoulombIonization.Localization.CanonicalRealPacketBarrier +OAI.Analysis.CoulombIonization.Localization.CoherentKinetic +OAI.Analysis.CoulombIonization.Localization.CoherentPackets +OAI.Analysis.CoulombIonization.Localization.CoherentRealKinetic +OAI.Analysis.CoulombIonization.Localization.ConditionalRetainedGap +OAI.Analysis.CoulombIonization.Localization.ConditionalSandwich +OAI.Analysis.CoulombIonization.Localization.CoreHistoryAverageBarrier +OAI.Analysis.CoulombIonization.Localization.CoreHistoryCoordinatesBarrier +OAI.Analysis.CoulombIonization.Localization.CoreHistoryMassBarrier +OAI.Analysis.CoulombIonization.Localization.CoreHistoryOutMaximumBarrier +OAI.Analysis.CoulombIonization.Localization.CoreObservationEnsembleBarrier +OAI.Analysis.CoulombIonization.Localization.Cut +OAI.Analysis.CoulombIonization.Localization.CutOuterLaw +OAI.Analysis.CoulombIonization.Localization.DyadicObservation +OAI.Analysis.CoulombIonization.Localization.EventLawSelectedMaster +OAI.Analysis.CoulombIonization.Localization.FermiDensity +OAI.Analysis.CoulombIonization.Localization.FermionGradient +OAI.Analysis.CoulombIonization.Localization.FermionL2 +OAI.Analysis.CoulombIonization.Localization.FiniteCellObservation +OAI.Analysis.CoulombIonization.Localization.FormRawLaw +OAI.Analysis.CoulombIonization.Localization.FreshObservedSandwichBarrier +OAI.Analysis.CoulombIonization.Localization.FreshPosteriorSandwich +OAI.Analysis.CoulombIonization.Localization.GridPacketRadius +OAI.Analysis.CoulombIonization.Localization.InverseNetEventsBarrier +OAI.Analysis.CoulombIonization.Localization.InverseObservationScaleBarrier +OAI.Analysis.CoulombIonization.Localization.LipschitzMollifier +OAI.Analysis.CoulombIonization.Localization.MasterExpandedAnnularQuery +OAI.Analysis.CoulombIonization.Localization.MasterPotential +OAI.Analysis.CoulombIonization.Localization.Observation +OAI.Analysis.CoulombIonization.Localization.ObservationIntegral +OAI.Analysis.CoulombIonization.Localization.ObservationLikelihood +OAI.Analysis.CoulombIonization.Localization.ObservationScoreMoments +OAI.Analysis.CoulombIonization.Localization.ObservationSmooth +OAI.Analysis.CoulombIonization.Localization.ObservedAnnularCountBarrier +OAI.Analysis.CoulombIonization.Localization.ObservedExpandedAnnular +OAI.Analysis.CoulombIonization.Localization.ObservedInnerCap +OAI.Analysis.CoulombIonization.Localization.ObservedPosteriorDensityBarrier +OAI.Analysis.CoulombIonization.Localization.OrdinaryDensity +OAI.Analysis.CoulombIonization.Localization.OriginalPosteriorKernel +OAI.Analysis.CoulombIonization.Localization.OriginalPosteriorMomentBarrier +OAI.Analysis.CoulombIonization.Localization.PacketCloud +OAI.Analysis.CoulombIonization.Localization.PacketComparison +OAI.Analysis.CoulombIonization.Localization.PacketDensity +OAI.Analysis.CoulombIonization.Localization.PacketDensityRadius +OAI.Analysis.CoulombIonization.Localization.PacketFourier +OAI.Analysis.CoulombIonization.Localization.PacketInsert +OAI.Analysis.CoulombIonization.Localization.PacketScale +OAI.Analysis.CoulombIonization.Localization.PacketScaleControl +OAI.Analysis.CoulombIonization.Localization.PatchCenterObservable +OAI.Analysis.CoulombIonization.Localization.PatchLocalObservable +OAI.Analysis.CoulombIonization.Localization.PosteriorAnnularQueryBarrier +OAI.Analysis.CoulombIonization.Localization.PosteriorFreshTestBarrier +OAI.Analysis.CoulombIonization.Localization.PosteriorSubmeanBarrier +OAI.Analysis.CoulombIonization.Localization.QuantumMultiplierLaw +OAI.Analysis.CoulombIonization.Localization.QuantumRawLaw +OAI.Analysis.CoulombIonization.Localization.RadialPacket +OAI.Analysis.CoulombIonization.Localization.RadialPacketBase +OAI.Analysis.CoulombIonization.Localization.ScoreDirectional +OAI.Analysis.CoulombIonization.Localization.SpinCorrelated +OAI.Analysis.CoulombIonization.Localization.SpinPartialOccupationKineticLintegral +OAI.Analysis.CoulombIonization.Localization.SqrtMultiplier +OAI.Analysis.CoulombIonization.Localization.SubGaussianMoments +OAI.Analysis.CoulombIonization.Localization.TailObservationEventBarrier +OAI.Analysis.CoulombIonization.Localization.TensorRightSpinVectorAe +OAI.Analysis.CoulombIonization.Localization.Trace +OAI.Analysis.CoulombIonization.Localization.UniformApproximateEvent +OAI.Analysis.CoulombIonization.Localization.UniformDyadicEvent +OAI.Analysis.CoulombIonization.Localization.UniformEventGraph +OAI.Analysis.CoulombIonization.Localization.UniformObservationNoiseBarrier +OAI.Analysis.CoulombIonization.Localization.UnorderedObservations +OAI.Analysis.CoulombIonization.Localization.UnshiftedEnsemble +OAI.Analysis.CoulombIonization.Localization.WeightedMoments +OAI.Analysis.CoulombIonization.Main +OAI.Analysis.CoulombIonization.Model +OAI.Analysis.CoulombIonization.RadialBounds.ActualBandInverseBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ActualLowInverseBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ActualSimultaneousCapBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ActualTailTiltBarrier +OAI.Analysis.CoulombIonization.RadialBounds.AnnularCellGeometryBarrier +OAI.Analysis.CoulombIonization.RadialBounds.AnnularCutExcess +OAI.Analysis.CoulombIonization.RadialBounds.AnnularEventNumericsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.AnnularFirst +OAI.Analysis.CoulombIonization.RadialBounds.ArbitraryCutExcess +OAI.Analysis.CoulombIonization.RadialBounds.Average +OAI.Analysis.CoulombIonization.RadialBounds.BallAverageKernelBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BandInverseNumericsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierActualInitializationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierChargeBound +OAI.Analysis.CoulombIonization.RadialBounds.BarrierDataSelectionBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierDilationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierForgettingBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierForgottenInvariantBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierInitialBoundsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierInitialCapsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierInitialInvariantBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierInitialLipschitzBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierInitializationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierLimitPositiveBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierMasterRegularityBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierNuclearScaleBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierOriginalForgettingBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierOuterWeakBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierQuantitativeStepBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierRetainedComparisonBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierRetainedFiniteBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierSmoothMaxBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierSpatialBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierSpatialNetBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierStepBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierStepGeometryBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierStepWeakBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierTowerBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierTransferBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierTransferGlobal +OAI.Analysis.CoulombIonization.RadialBounds.BarrierTruncationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BarrierWeakMaxGeneralBarrier +OAI.Analysis.CoulombIonization.RadialBounds.BindingBounds +OAI.Analysis.CoulombIonization.RadialBounds.BoundedL1PotentialBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CapBudgetHomogeneityBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CapInformationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CellBudgetNormalizationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CellCountAbsorptionBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CellCountSupremumBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CellScaleBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CoreHistoryCountsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CoreHistoryFermionBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CoreMultiplierLiftBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CoreSubmeanBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CorrectionPotentialSmallBarrier +OAI.Analysis.CoulombIonization.RadialBounds.CoulombBallIntegral +OAI.Analysis.CoulombIonization.RadialBounds.CoulombSelfBound +OAI.Analysis.CoulombIonization.RadialBounds.CoulombTailNumerics +OAI.Analysis.CoulombIonization.RadialBounds.CoulombTailStatistic +OAI.Analysis.CoulombIonization.RadialBounds.CoupledCoreExcessBarrier +OAI.Analysis.CoulombIonization.RadialBounds.Cut +OAI.Analysis.CoulombIonization.RadialBounds.Error +OAI.Analysis.CoulombIonization.RadialBounds.ExpandedAnnulusCapExcess +OAI.Analysis.CoulombIonization.RadialBounds.ExpandedAnnulusCapNumerics +OAI.Analysis.CoulombIonization.RadialBounds.ExpandedAnnulusGeometry +OAI.Analysis.CoulombIonization.RadialBounds.ExpandedAnnulusInverse +OAI.Analysis.CoulombIonization.RadialBounds.ExpectedRadialCapBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ExteriorScreenNumerics +OAI.Analysis.CoulombIonization.RadialBounds.FermiMeasure +OAI.Analysis.CoulombIonization.RadialBounds.FiniteBarrier +OAI.Analysis.CoulombIonization.RadialBounds.FockKineticReindexBarrier +OAI.Analysis.CoulombIonization.RadialBounds.FreshCutBarrier +OAI.Analysis.CoulombIonization.RadialBounds.FreshInnerCountsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.FreshRetainedMassBarrier +OAI.Analysis.CoulombIonization.RadialBounds.FullAnnulusBandCover +OAI.Analysis.CoulombIonization.RadialBounds.FullAnnulusGeometry +OAI.Analysis.CoulombIonization.RadialBounds.FullAnnulusGoodEvent +OAI.Analysis.CoulombIonization.RadialBounds.FullAnnulusWidthNumerics +OAI.Analysis.CoulombIonization.RadialBounds.Geometry +OAI.Analysis.CoulombIonization.RadialBounds.GlobalDensityBarrier +OAI.Analysis.CoulombIonization.RadialBounds.InverseBudgetScaleBarrier +OAI.Analysis.CoulombIonization.RadialBounds.InverseKernelMassBarrier +OAI.Analysis.CoulombIonization.RadialBounds.InverseNumericalStatementsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.InverseThresholdMarginsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalArzelaAscoliBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalBallTraceBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalCountGapBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalDensityTraceBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalFermionDensityBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalHistoryWeightsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.LocalOrdinaryBarrier +OAI.Analysis.CoulombIonization.RadialBounds.MasterExteriorStatistic +OAI.Analysis.CoulombIonization.RadialBounds.MomentumBall +OAI.Analysis.CoulombIonization.RadialBounds.NonlinearLocalLimitBarrier +OAI.Analysis.CoulombIonization.RadialBounds.NormalizedMasterEvent +OAI.Analysis.CoulombIonization.RadialBounds.OriginalAnnularOscillationBarrier +OAI.Analysis.CoulombIonization.RadialBounds.OutwardBarrier +OAI.Analysis.CoulombIonization.RadialBounds.OwnProbabilityBudgetScaleBarrier +OAI.Analysis.CoulombIonization.RadialBounds.OwnProbabilityRareCapBarrier +OAI.Analysis.CoulombIonization.RadialBounds.OwnProbabilityTailTiltBarrier +OAI.Analysis.CoulombIonization.RadialBounds.PatchAverageSubmeanBarrier +OAI.Analysis.CoulombIonization.RadialBounds.PatchFailureMass +OAI.Analysis.CoulombIonization.RadialBounds.PatchMass +OAI.Analysis.CoulombIonization.RadialBounds.PointInverseEventsCell +OAI.Analysis.CoulombIonization.RadialBounds.PolynomialProbabilityBudgetBarrier +OAI.Analysis.CoulombIonization.RadialBounds.Radial +OAI.Analysis.CoulombIonization.RadialBounds.RadialAxis +OAI.Analysis.CoulombIonization.RadialBounds.RadialCenterRawComparison +OAI.Analysis.CoulombIonization.RadialBounds.RadialCountSelection +OAI.Analysis.CoulombIonization.RadialBounds.RadialInside +OAI.Analysis.CoulombIonization.RadialBounds.RadialMeanCenterBarrier +OAI.Analysis.CoulombIonization.RadialBounds.RadialPatchGeometry +OAI.Analysis.CoulombIonization.RadialBounds.RadialPotentialSqrtDeriv +OAI.Analysis.CoulombIonization.RadialBounds.RadialSelectedCounts +OAI.Analysis.CoulombIonization.RadialBounds.RetainedNeighborhoodBarrier +OAI.Analysis.CoulombIonization.RadialBounds.RootMomentCauchyBarrier +OAI.Analysis.CoulombIonization.RadialBounds.RotationIntegralBarrier +OAI.Analysis.CoulombIonization.RadialBounds.RotationShellBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ScreenedLimitDynamicsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SelectedBarrierLimitBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SelectedData +OAI.Analysis.CoulombIonization.RadialBounds.SelectionBudget +OAI.Analysis.CoulombIonization.RadialBounds.SelectionDiagonal +OAI.Analysis.CoulombIonization.RadialBounds.SelectionNumerics +OAI.Analysis.CoulombIonization.RadialBounds.SharpBudgetMonotoneBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SharpErrorLimitBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SharpFreshPatchBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SharpLocalPotentialBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SharpMasterPotentialBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SharpOrdinaryCapBarrier +OAI.Analysis.CoulombIonization.RadialBounds.ShellAbsorptionNumerics +OAI.Analysis.CoulombIonization.RadialBounds.ShellBias +OAI.Analysis.CoulombIonization.RadialBounds.ShellBiasEnergy +OAI.Analysis.CoulombIonization.RadialBounds.ShellCoulombDuality +OAI.Analysis.CoulombIonization.RadialBounds.ShellCutoffBounds +OAI.Analysis.CoulombIonization.RadialBounds.ShellResidualControl +OAI.Analysis.CoulombIonization.RadialBounds.ShellTelescoping +OAI.Analysis.CoulombIonization.RadialBounds.SpatialCapSubmeanBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SphericalMeanLimitBarrier +OAI.Analysis.CoulombIonization.RadialBounds.SquareCompletion +OAI.Analysis.CoulombIonization.RadialBounds.StripAveraging +OAI.Analysis.CoulombIonization.RadialBounds.TailInitialEventuallyBarrier +OAI.Analysis.CoulombIonization.RadialBounds.TailInitialPointwiseBarrier +OAI.Analysis.CoulombIonization.RadialBounds.TailParticleCount +OAI.Analysis.CoulombIonization.RadialBounds.TinyProbabilityFloorBarrier +OAI.Analysis.CoulombIonization.RadialBounds.TranslatedShortRange +OAI.Analysis.CoulombIonization.RadialBounds.TruncationRadius +OAI.Analysis.CoulombIonization.RadialBounds.UniformNetErrorsBarrier +OAI.Analysis.CoulombIonization.RadialBounds.UnshiftedCellCountBarrier +OAI.Analysis.CoulombIonization.RadialBounds.WeakPuncturedMaximumBarrier +OAI.Analysis.CoulombIonization.RadialBounds.WeakSemilinearComparison +OAI.Analysis.CoulombIonization.RadialBounds.WeakSingularProfileBarrier +OAI.Analysis.CoulombIonization.RadialBounds.WeakWindowMoment +OAI.Analysis.CoulombIonization.RadialBounds.dShellForm +OAI.Analysis.CoulombIonization.ThomasFermi.ActualMeanComparison +OAI.Analysis.CoulombIonization.ThomasFermi.ActualPatchCap +OAI.Analysis.CoulombIonization.ThomasFermi.AnnularApproximationLimitBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.AnnularTFAndCap +OAI.Analysis.CoulombIonization.ThomasFermi.CellCountFeedbackBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.CellDensityBoundBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.CoherentFiniteInsertion +OAI.Analysis.CoulombIonization.ThomasFermi.CoherentPhaseBasis +OAI.Analysis.CoulombIonization.ThomasFermi.CompactDirichletBound +OAI.Analysis.CoulombIonization.ThomasFermi.ConditionalPatchPDE +OAI.Analysis.CoulombIonization.ThomasFermi.ContractFunction +OAI.Analysis.CoulombIonization.ThomasFermi.CoulombLipschitzDuality +OAI.Analysis.CoulombIonization.ThomasFermi.CutMomentBounds +OAI.Analysis.CoulombIonization.ThomasFermi.FlatFermionAverage +OAI.Analysis.CoulombIonization.ThomasFermi.FlatFermionGradient +OAI.Analysis.CoulombIonization.ThomasFermi.FlatFermionMollify +OAI.Analysis.CoulombIonization.ThomasFermi.FullAnnulusNormalization +OAI.Analysis.CoulombIonization.ThomasFermi.InverseNetPropagationBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.InverseThresholdLimitBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.Lp +OAI.Analysis.CoulombIonization.ThomasFermi.NearTFReaction +OAI.Analysis.CoulombIonization.ThomasFermi.NetFieldVariationBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.NuclearDilationBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.OutCutAntisymmetry +OAI.Analysis.CoulombIonization.ThomasFermi.PacketFieldConstant +OAI.Analysis.CoulombIonization.ThomasFermi.Pairing +OAI.Analysis.CoulombIonization.ThomasFermi.PatchCoulombControl +OAI.Analysis.CoulombIonization.ThomasFermi.PatchEuler +OAI.Analysis.CoulombIonization.ThomasFermi.PatchFullPotential +OAI.Analysis.CoulombIonization.ThomasFermi.PatchGap +OAI.Analysis.CoulombIonization.ThomasFermi.PatchGapMeasurable +OAI.Analysis.CoulombIonization.ThomasFermi.PatchRandomVariables +OAI.Analysis.CoulombIonization.ThomasFermi.PatchTF +OAI.Analysis.CoulombIonization.ThomasFermi.PatchTruncationLoss +OAI.Analysis.CoulombIonization.ThomasFermi.QuantumSectorNearMinimizer +OAI.Analysis.CoulombIonization.ThomasFermi.RadialPatchCap +OAI.Analysis.CoulombIonization.ThomasFermi.RadialShellPotential +OAI.Analysis.CoulombIonization.ThomasFermi.ScaledBarrierCorrectionBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.SelectedScreenedProfileBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.SmallEventFieldIntegralBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.SommerfeldCoefficient +OAI.Analysis.CoulombIonization.ThomasFermi.TFMeanComparison +OAI.Analysis.CoulombIonization.ThomasFermi.TFNonradialBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.TFNonradialCap +OAI.Analysis.CoulombIonization.ThomasFermi.TFNonradialOscillation +OAI.Analysis.CoulombIonization.ThomasFermi.Tensor +OAI.Analysis.CoulombIonization.ThomasFermi.TfBallFunctionalConvex +OAI.Analysis.CoulombIonization.ThomasFermi.TfCenteredPrice +OAI.Analysis.CoulombIonization.ThomasFermi.TfDilation +OAI.Analysis.CoulombIonization.ThomasFermi.TfEulerDensity +OAI.Analysis.CoulombIonization.ThomasFermi.TfIncreasingData +OAI.Analysis.CoulombIonization.ThomasFermi.TfInfiniteField +OAI.Analysis.CoulombIonization.ThomasFermi.TfInfiniteFieldDominatesDilation +OAI.Analysis.CoulombIonization.ThomasFermi.TfPotential +OAI.Analysis.CoulombIonization.ThomasFermi.TfPowerIntegralDeriv +OAI.Analysis.CoulombIonization.ThomasFermi.TfReactionCoefficient +OAI.Analysis.CoulombIonization.ThomasFermi.TfRotate +OAI.Analysis.CoulombIonization.ThomasFermi.TfWeight +OAI.Analysis.CoulombIonization.ThomasFermi.UniformFamilyEventBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.UniformPhysicalEvent +OAI.Analysis.CoulombIonization.ThomasFermi.UniformVariableTailEventBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.WeakSommerfeldAsymptoticBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.WeakSommerfeldBoundsBarrier +OAI.Analysis.CoulombIonization.ThomasFermi.dInverseLocalTF +OAI.Analysis.CoulombIonization.Variational.ActualSectorPlateau +OAI.Analysis.CoulombIonization.Variational.AllSectorEnergy +OAI.Analysis.CoulombIonization.Variational.BindingBase +OAI.Analysis.CoulombIonization.Variational.BindingNuclearSum +OAI.Analysis.CoulombIonization.Variational.BindingPairApproxIntegral +OAI.Analysis.CoulombIonization.Variational.BindingResidual +OAI.Analysis.CoulombIonization.Variational.BindingWeightContinuous +OAI.Analysis.CoulombIonization.Variational.BlockEnergy +OAI.Analysis.CoulombIonization.Variational.BlockPermutations +OAI.Analysis.CoulombIonization.Variational.BlockSwap +OAI.Analysis.CoulombIonization.Variational.BoundedDensityPotential +OAI.Analysis.CoulombIonization.Variational.ClosedInnerStatistic +OAI.Analysis.CoulombIonization.Variational.CoherentBessel +OAI.Analysis.CoulombIonization.Variational.CoherentDensity +OAI.Analysis.CoulombIonization.Variational.CoherentDensityTrace +OAI.Analysis.CoulombIonization.Variational.CoherentOrbitals +OAI.Analysis.CoulombIonization.Variational.CoherentResolution +OAI.Analysis.CoulombIonization.Variational.CompactPotential +OAI.Analysis.CoulombIonization.Variational.ComplexOccupation +OAI.Analysis.CoulombIonization.Variational.ComplexRealWeightPairing +OAI.Analysis.CoulombIonization.Variational.ConfigurationCoordinates +OAI.Analysis.CoulombIonization.Variational.ContinuousUniversalEvent +OAI.Analysis.CoulombIonization.Variational.CorePriceExcess +OAI.Analysis.CoulombIonization.Variational.CorrelatedFiniteInsertion +OAI.Analysis.CoulombIonization.Variational.CoulombNear +OAI.Analysis.CoulombIonization.Variational.CoulombTestCharge +OAI.Analysis.CoulombIonization.Variational.CutCoreExcess +OAI.Analysis.CoulombIonization.Variational.CutCoreNumber +OAI.Analysis.CoulombIonization.Variational.CutExpectedOut +OAI.Analysis.CoulombIonization.Variational.DeletedPotential +OAI.Analysis.CoulombIonization.Variational.DiffuseSeed +OAI.Analysis.CoulombIonization.Variational.Electrostatic +OAI.Analysis.CoulombIonization.Variational.ExpectedFullPotential +OAI.Analysis.CoulombIonization.Variational.ExpectedTruncatedControl +OAI.Analysis.CoulombIonization.Variational.FatouIntegrable +OAI.Analysis.CoulombIonization.Variational.FinitePotentialDecay +OAI.Analysis.CoulombIonization.Variational.FreshPatchBudget +OAI.Analysis.CoulombIonization.Variational.FullCoulomb +OAI.Analysis.CoulombIonization.Variational.FullPotentialComparison +OAI.Analysis.CoulombIonization.Variational.FullSliceStatistics +OAI.Analysis.CoulombIonization.Variational.GridIncrementError +OAI.Analysis.CoulombIonization.Variational.HardySquare +OAI.Analysis.CoulombIonization.Variational.Inner +OAI.Analysis.CoulombIonization.Variational.InnerPotential +OAI.Analysis.CoulombIonization.Variational.InsertionSwap +OAI.Analysis.CoulombIonization.Variational.IntegrableCutTower +OAI.Analysis.CoulombIonization.Variational.IntegralFourierInvMul +OAI.Analysis.CoulombIonization.Variational.IntegratedLipschitzControl +OAI.Analysis.CoulombIonization.Variational.IntegratedTruncatedControl +OAI.Analysis.CoulombIonization.Variational.L2 +OAI.Analysis.CoulombIonization.Variational.LocalWidthKernel +OAI.Analysis.CoulombIonization.Variational.MasterKernelFubini +OAI.Analysis.CoulombIonization.Variational.MasterRecovery +OAI.Analysis.CoulombIonization.Variational.MasterWidth +OAI.Analysis.CoulombIonization.Variational.NegativePatchControl +OAI.Analysis.CoulombIonization.Variational.NewtonComparisonTest +OAI.Analysis.CoulombIonization.Variational.OccupationTraces +OAI.Analysis.CoulombIonization.Variational.OrbitalPole +OAI.Analysis.CoulombIonization.Variational.OriginalKernelEvent +OAI.Analysis.CoulombIonization.Variational.OutRetainedLower +OAI.Analysis.CoulombIonization.Variational.OwnStateResidual +OAI.Analysis.CoulombIonization.Variational.PatchBounded +OAI.Analysis.CoulombIonization.Variational.PatchCenterIntegrable +OAI.Analysis.CoulombIonization.Variational.PatchContinuity +OAI.Analysis.CoulombIonization.Variational.PatchMeasurable +OAI.Analysis.CoulombIonization.Variational.PatchTranslatedDensity +OAI.Analysis.CoulombIonization.Variational.PhaseBathtub +OAI.Analysis.CoulombIonization.Variational.Pointwise +OAI.Analysis.CoulombIonization.Variational.PotentialRecovery +OAI.Analysis.CoulombIonization.Variational.RetainedRepulsion +OAI.Analysis.CoulombIonization.Variational.RootCoulomb +OAI.Analysis.CoulombIonization.Variational.RotationCoreKernelIntegrable +OAI.Analysis.CoulombIonization.Variational.ScaledOriginalCap +OAI.Analysis.CoulombIonization.Variational.ScaledSpatialInverse +OAI.Analysis.CoulombIonization.Variational.SelectedMasterComparison +OAI.Analysis.CoulombIonization.Variational.SelectedPatchBudget +OAI.Analysis.CoulombIonization.Variational.ShortRangePotential +OAI.Analysis.CoulombIonization.Variational.SliceLp +OAI.Analysis.CoulombIonization.Variational.Slices +OAI.Analysis.CoulombIonization.Variational.SmearRepulsion +OAI.Analysis.CoulombIonization.Variational.SmearingPotential +OAI.Analysis.CoulombIonization.Variational.SmoothCompactIntegral +OAI.Analysis.CoulombIonization.Variational.SmoothNewton +OAI.Analysis.CoulombIonization.Variational.SmoothTransitionBound +OAI.Analysis.CoulombIonization.Variational.Space +OAI.Analysis.CoulombIonization.Variational.Spatial +OAI.Analysis.CoulombIonization.Variational.SpatialErrorWeight +OAI.Analysis.CoulombIonization.Variational.SpatialProductFactor +OAI.Analysis.CoulombIonization.Variational.SpatialRotation +OAI.Analysis.CoulombIonization.Variational.SpinEnergy +OAI.Analysis.CoulombIonization.Variational.SpinFinite +OAI.Analysis.CoulombIonization.Variational.SpinJoinEquiv +OAI.Analysis.CoulombIonization.Variational.SpinSpaceIntegrable +OAI.Analysis.CoulombIonization.Variational.SumPairsHalf +OAI.Analysis.CoulombIonization.Variational.TensorLp +OAI.Analysis.CoulombIonization.Variational.TruncatedCoulomb +OAI.Analysis.CoulombIonization.Variational.Weighted +OAI.Analysis.CoulombIonization.Variational.WeightedCauchy +OAI.Analysis.CoulombIonization.Variational.WeightedMass +OAI.Analysis.CoulombIonization.Variational.WeightedVariance +OAI.Analysis.CoulombIonization.Variational.WidthKernelAmplitude diff --git a/tasks/coulomb-ionization/solution/reference.py b/tasks/coulomb-ionization/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coulomb-ionization/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coulomb-ionization/solution/solve.sh b/tasks/coulomb-ionization/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b59beb248243395d98ab5f0f0c13aa6eb70cbe68 --- /dev/null +++ b/tasks/coulomb-ionization/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoulombIonization, i.e. module OAI.Analysis.CoulombIonization.Main and the +# 607 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.CoulombIonization.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoulombIonization" diff --git a/tasks/coulomb-ionization/task.toml b/tasks/coulomb-ionization/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c18fe65d1955f1a6b55e20d5ce42dec225d3dcc --- /dev/null +++ b/tasks/coulomb-ionization/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coulomb-ionization" +version = "1.0.0" +description = "Prove CoulombIonization (openai/math family 263: The ionization and generalized ionization conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoulombIonization.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoulombIonization" +family = "263" +family_title = "The ionization and generalized ionization conjectures" +subject = "Mathematical physics" +theorems = ["OAI.CoulombAtom.generalized_ionization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.CoulombIonization.Main" +reference_modules = 607 +reference_lean_bytes = 4613552 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2115 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15852 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coulomb-ionization/tests/Challenge.lean b/tasks/coulomb-ionization/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..972806e6009c1a1dc1bc123502a01af078227ac4 --- /dev/null +++ b/tasks/coulomb-ionization/tests/Challenge.lean @@ -0,0 +1,99 @@ +import Mathlib + +namespace OAI + +open MeasureTheory Filter +open scoped Topology BigOperators ContDiff + +noncomputable section +namespace CoulombAtom + +abbrev Space := EuclideanSpace ℝ (Fin 3) +abbrev Configuration (N : ℕ) := Fin N → Space +abbrev Spins (N : ℕ) := Fin N → Fin 2 + +structure FormVector (N : ℕ) where + value : Spins N → Configuration N → ℂ + gradient : Spins N → Fin N → Fin 3 → Configuration N → ℂ + +def direction {N : ℕ} (i : Fin N) (a : Fin 3) : Configuration N := + Pi.single i (EuclideanSpace.single a 1) + +def FormAdmissible {N : ℕ} (ψ : FormVector N) : Prop := + (∀ s, MemLp (ψ.value s) 2) ∧ + (∀ s i a, MemLp (ψ.gradient s i a) 2) ∧ + (∀ s i a (φ : Configuration N → ℝ), + ContDiff ℝ ∞ φ → HasCompactSupport φ → + (∫ x, ψ.value s x * Complex.ofReal (lineDeriv ℝ φ x (direction i a))) = + -(∫ x, ψ.gradient s i a x * (φ x : ℂ))) ∧ + (∀ (π : Equiv.Perm (Fin N)) s, ∀ᵐ x, + ψ.value (s ∘ π) (x ∘ π) = + (((Equiv.Perm.sign π : ℤ) : ℂ) * ψ.value s x)) ∧ + (∑ s : Spins N, ∫ x, ‖ψ.value s x‖ ^ 2) = 1 ∧ + (∀ s i, Integrable (fun x => ‖ψ.value s x‖ ^ 2 / ‖x i‖)) ∧ + (∀ s i j, i ≠ j → + Integrable (fun x => ‖ψ.value s x‖ ^ 2 / ‖x i - x j‖)) + +def formEnergy {N : ℕ} (Z : ℝ) (ψ : FormVector N) : ℝ := + (1 / 2 : ℝ) * + (∑ s : Spins N, ∑ i : Fin N, ∑ a : Fin 3, + (∫ x, ‖ψ.gradient s i a x‖ ^ 2)) - + Z * (∑ s : Spins N, ∑ i : Fin N, + (∫ x, ‖ψ.value s x‖ ^ 2 / ‖x i‖)) + + (∑ s : Spins N, ∑ i : Fin N, ∑ j : Fin N, + if i < j then (∫ x, ‖ψ.value s x‖ ^ 2 / ‖x i - x j‖) else 0) + +def energy (Z : ℝ) (N : ℕ) : ℝ := + if N = 0 then 0 else sInf {e | ∃ ψ : FormVector N, + FormAdmissible ψ ∧ formEnergy Z ψ = e} + +def ionization (m Z : ℕ) : ℝ := + energy Z (Z - m) - energy Z Z + +def tfKinetic : ℝ := (3 / 10 : ℝ) * (3 * Real.pi ^ 2) ^ (2 / 3 : ℝ) + +def directIntegrand (ρ : Space → ℝ) (p : Space × Space) : ℝ := + ρ p.1 * ρ p.2 / ‖p.1 - p.2‖ + +def TFAdmissible (M : ℝ) (ρ : Space → ℝ) : Prop := + (∀ᵐ x, 0 ≤ ρ x) ∧ Integrable ρ ∧ (∫ x, ρ x) = M ∧ + Integrable (fun x => ρ x ^ (5 / 3 : ℝ)) ∧ + Integrable (fun x => ρ x / ‖x‖) ∧ Integrable (directIntegrand ρ) + +def tfFunctional (Z : ℝ) (ρ : Space → ℝ) : ℝ := + tfKinetic * (∫ x, ρ x ^ (5 / 3 : ℝ)) - Z * (∫ x, ρ x / ‖x‖) + + (1 / 2 : ℝ) * ∫ p, directIntegrand ρ p + +def tfEnergy (Z M : ℝ) : ℝ := + sInf {e | ∃ ρ : Space → ℝ, TFAdmissible M ρ ∧ tfFunctional Z ρ = e} + +def tfIonization (m Z : ℝ) : ℝ := tfEnergy Z (Z - m) - tfEnergy Z Z + +def TFCharacterization (a : ℝ) : Prop := + ∀ m : ℝ, 0 < m → + Tendsto (tfIonization m) atTop (𝓝 (a * m ^ (7 / 3 : ℝ))) + +def JointLimit (a : ℝ) : Prop := + ∀ m Z : ℕ → ℕ, (∀ j, 1 ≤ m j ∧ m j < Z j) → + Tendsto m atTop atTop → + Tendsto (fun j => (Z j : ℝ) / (m j : ℝ)) atTop atTop → + Tendsto (fun j => ionization (m j) (Z j) / (m j : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) + +def IteratedLimits (a : ℝ) : Prop := + Tendsto (fun m : ℕ => (limsup (ionization m) atTop) / (m : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) ∧ + Tendsto (fun m : ℕ => (liminf (ionization m) atTop) / (m : ℝ) ^ (7 / 3 : ℝ)) + atTop (𝓝 a) + +def MainStatement : Prop := + ∃ a : ℝ, 0 < a ∧ TFCharacterization a ∧ JointLimit a ∧ IteratedLimits a + +theorem generalized_ionization : MainStatement := by + sorry + +end CoulombAtom + +end + +end OAI diff --git a/tasks/coulomb-ionization/tests/grade.py b/tasks/coulomb-ionization/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coulomb-ionization/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coulomb-ionization/tests/task.json b/tasks/coulomb-ionization/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6da47ece1691ef441f9448940a8226483e1b0e96 --- /dev/null +++ b/tasks/coulomb-ionization/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoulombIonization", + "comparator": { + "theorem_names": [ + "OAI.CoulombAtom.generalized_ionization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14952 +} \ No newline at end of file diff --git a/tasks/coulomb-ionization/tests/test.sh b/tasks/coulomb-ionization/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coulomb-ionization/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/coulomb-radii/environment/Dockerfile b/tasks/coulomb-radii/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/coulomb-radii/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/coulomb-radii/environment/fetch_mathlib.sh b/tasks/coulomb-radii/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/coulomb-radii/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/coulomb-radii/environment/lake-manifest.json b/tasks/coulomb-radii/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/coulomb-radii/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/coulomb-radii/environment/lakefile.lean b/tasks/coulomb-radii/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/coulomb-radii/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/coulomb-radii/environment/lean_setup.sh b/tasks/coulomb-radii/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/coulomb-radii/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/coulomb-radii/environment/pack_submission.py b/tasks/coulomb-radii/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/coulomb-radii/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/coulomb-radii/instruction.md b/tasks/coulomb-radii/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76b20d0653ad86910e6e415d21e7f2077a8ec903 --- /dev/null +++ b/tasks/coulomb-radii/instruction.md @@ -0,0 +1,140 @@ +# openai/math challenge `CoulombRadii` (family 263) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 263 of the release, *The ionization and generalized ionization conjectures* +(Mathematical physics). The family as a whole: For the full nonrelativistic Coulomb model with two electron spin states, proves that a molecule with $M$ fixed nuclei of charges at least one and total charge $Z$ strictly binds at most $Z+CM$ electrons. Neutral-atom first ionization energies and radii containing all but an expected half-electron have universal positive upper and lower bounds. The energy cost of removing $m$ electrons has Thomas–Fermi asymptotics as $m\to\infty$ and $Z/m\to\infty$; neutral-atom outer radii have the corresponding iterated-limit asymptotics, taking $Z\to\infty$ first. + +The challenge is `CoulombRadii`, also at `/opt/openai-math/challenges/CoulombRadii.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter +open scoped BigOperators Topology ContDiff + +namespace NeutralAtom + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Configuration (n : ℕ) := Fin n → Position +abbrev Spins (n : ℕ) := Fin n → Fin 2 +abbrev Wavefunction (n : ℕ) := Spins n → Configuration n → ℂ +abbrev Gradient (n : ℕ) := Spins n → Fin n → Fin 3 → Configuration n → ℂ + +def coordinateDirection {n : ℕ} (i : Fin n) (a : Fin 3) : Configuration n := + Pi.single i (EuclideanSpace.single a 1) + +def HasWeakGradient {n : ℕ} (ψ : Wavefunction n) (g : Gradient n) : Prop := + ∀ σ i a (φ : Configuration n → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + (∫ x, (fderiv ℝ φ x (coordinateDirection i a) : ℂ) * ψ σ x) = + -(∫ x, (φ x : ℂ) * g σ i a x) + +def IsAntisymmetric {n : ℕ} (ψ : Wavefunction n) : Prop := + ∀ (p : Equiv.Perm (Fin n)) (σ : Spins n), + (fun x : Configuration n => ψ (σ ∘ p) (x ∘ p)) =ᵐ[volume] + (fun x => (((Equiv.Perm.sign p : ℤ) : ℂ)) * ψ σ x) + +def FormDomain {n : ℕ} (ψ : Wavefunction n) (g : Gradient n) : Prop := + IsAntisymmetric ψ ∧ HasWeakGradient ψ g ∧ + (∀ σ, MemLp (ψ σ) 2 volume) ∧ + (∀ σ i a, MemLp (g σ i a) 2 volume) ∧ + (∀ σ i, Integrable (fun x : Configuration n => ‖x i‖⁻¹ * ‖ψ σ x‖ ^ 2)) ∧ + (∀ σ i j, i < j → + Integrable (fun x : Configuration n => ‖x i - x j‖⁻¹ * ‖ψ σ x‖ ^ 2)) + +def normSquared {n : ℕ} (ψ : Wavefunction n) : ℝ := + ∑ σ : Spins n, ∫ x : Configuration n, ‖ψ σ x‖ ^ 2 + +def coulombPotential {n : ℕ} (Z : ℕ) (x : Configuration n) : ℝ := + -(Z : ℝ) * (∑ i : Fin n, ‖x i‖⁻¹) + + ∑ i : Fin n, ∑ j ∈ Finset.univ.filter (fun j : Fin n => i < j), ‖x i - x j‖⁻¹ + +def energy {n : ℕ} (Z : ℕ) (ψ : Wavefunction n) (g : Gradient n) : ℝ := + (1 / 2 : ℝ) * (∑ σ : Spins n, ∑ i : Fin n, ∑ a : Fin 3, + ∫ x : Configuration n, ‖g σ i a x‖ ^ 2) + + ∑ σ : Spins n, ∫ x : Configuration n, coulombPotential Z x * ‖ψ σ x‖ ^ 2 + +def IsNormalizedGroundState (Z : ℕ) (ψ : Wavefunction Z) : Prop := + ∃ g : Gradient Z, FormDomain ψ g ∧ normSquared ψ = 1 ∧ + ∀ (χ : Wavefunction Z) (h : Gradient Z), + FormDomain χ h → normSquared χ = 1 → energy Z ψ g ≤ energy Z χ h + +def density {N : ℕ} (ψ : Wavefunction (N + 1)) (x : Position) : ℝ := + (N + 1 : ℝ) * ∑ σ : Spins (N + 1), + ∫ y : Configuration N, ‖ψ σ (Fin.cons x y)‖ ^ 2 + +def exteriorMass {N : ℕ} (ψ : Wavefunction (N + 1)) (r : ℝ) : ℝ := + ∫ x in {x : Position | r < ‖x‖}, density ψ x + +def radius {N : ℕ} (ψ : Wavefunction (N + 1)) (m : ℕ) : ℝ := + sInf {r : ℝ | 0 ≤ r ∧ exteriorMass ψ r ≤ (m : ℝ)} + +def bTF : ℝ := (81 * Real.pi ^ 2 / 2) ^ (1 / 3 : ℝ) + +def largeCharge (m : ℕ) : Filter ℕ := + atTop ⊓ Filter.principal {N : ℕ | m < N + 1} + +def upperRadius (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) (m : ℕ) : EReal := + Filter.limsup (fun N : ℕ => (radius (Ψ N) m : EReal)) (largeCharge m) + +def lowerRadius (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) (m : ℕ) : EReal := + Filter.liminf (fun N : ℕ => (radius (Ψ N) m : EReal)) (largeCharge m) + +theorem generalized_outer_radii + (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) + (hΨ : ∀ N : ℕ, IsNormalizedGroundState (N + 1) (Ψ N)) : + Tendsto (fun m : ℕ => (((m : ℝ) ^ (1 / 3 : ℝ) : ℝ) : EReal) * upperRadius Ψ m) + atTop (𝓝 (bTF : EReal)) ∧ + Tendsto (fun m : ℕ => (((m : ℝ) ^ (1 / 3 : ℝ) : ℝ) : EReal) * lowerRadius Ψ m) + atTop (𝓝 (bTF : EReal)) := by + sorry + +end NeutralAtom +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoulombRadii.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.NeutralAtom.generalized_outer_radii` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/coulomb-radii/solution/closure.txt b/tasks/coulomb-radii/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e7b1174355cdcdb7a6609e5c7cd79a3a8365901 --- /dev/null +++ b/tasks/coulomb-radii/solution/closure.txt @@ -0,0 +1,428 @@ +OAI.Analysis.CoulombRadii.FieldAnalysis.AmplitudeOscillation +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicGapScale +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicGlobalScale +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicNear +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicStability +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicWeightGeometry +OAI.Analysis.CoulombRadii.FieldAnalysis.AtomicWeighted +OAI.Analysis.CoulombRadii.FieldAnalysis.BallCloudDuality +OAI.Analysis.CoulombRadii.FieldAnalysis.BinaryOrder +OAI.Analysis.CoulombRadii.FieldAnalysis.BlockIndex +OAI.Analysis.CoulombRadii.FieldAnalysis.BodyCoefficient +OAI.Analysis.CoulombRadii.FieldAnalysis.ColoredObservable +OAI.Analysis.CoulombRadii.FieldAnalysis.CommonIsometryApply +OAI.Analysis.CoulombRadii.FieldAnalysis.ComplexMollify +OAI.Analysis.CoulombRadii.FieldAnalysis.ConfigurationMeasurableEquiv +OAI.Analysis.CoulombRadii.FieldAnalysis.CoreCoulombPotential +OAI.Analysis.CoulombRadii.FieldAnalysis.CorePerm +OAI.Analysis.CoulombRadii.FieldAnalysis.CorePointMeasurable +OAI.Analysis.CoulombRadii.FieldAnalysis.CoreReindex +OAI.Analysis.CoulombRadii.FieldAnalysis.CosineWeight +OAI.Analysis.CoulombRadii.FieldAnalysis.CoulombBilinear +OAI.Analysis.CoulombRadii.FieldAnalysis.CoulombTest +OAI.Analysis.CoulombRadii.FieldAnalysis.CoulombTransfer +OAI.Analysis.CoulombRadii.FieldAnalysis.CubeLabelEquiv +OAI.Analysis.CoulombRadii.FieldAnalysis.CubeMassMass +OAI.Analysis.CoulombRadii.FieldAnalysis.CubeMeasure +OAI.Analysis.CoulombRadii.FieldAnalysis.DeterminantBodyReal +OAI.Analysis.CoulombRadii.FieldAnalysis.DeterminantWave +OAI.Analysis.CoulombRadii.FieldAnalysis.DyadicInnerRMS +OAI.Analysis.CoulombRadii.FieldAnalysis.FarSubmean +OAI.Analysis.CoulombRadii.FieldAnalysis.FermionicCoefficients +OAI.Analysis.CoulombRadii.FieldAnalysis.FermionicNear +OAI.Analysis.CoulombRadii.FieldAnalysis.Field +OAI.Analysis.CoulombRadii.FieldAnalysis.FieldSubmean +OAI.Analysis.CoulombRadii.FieldAnalysis.FiniteProdSum +OAI.Analysis.CoulombRadii.FieldAnalysis.FiniteSubsequence +OAI.Analysis.CoulombRadii.FieldAnalysis.FirstParticleDensityNonneg +OAI.Analysis.CoulombRadii.FieldAnalysis.FlatBodyDensity +OAI.Analysis.CoulombRadii.FieldAnalysis.FlatDensityPower +OAI.Analysis.CoulombRadii.FieldAnalysis.FrameDensity +OAI.Analysis.CoulombRadii.FieldAnalysis.FrameImageDensity +OAI.Analysis.CoulombRadii.FieldAnalysis.FrameOperator +OAI.Analysis.CoulombRadii.FieldAnalysis.FreshFieldTransfer +OAI.Analysis.CoulombRadii.FieldAnalysis.FreshMeanBounds +OAI.Analysis.CoulombRadii.FieldAnalysis.FreshPotentialTower +OAI.Analysis.CoulombRadii.FieldAnalysis.FreshTransferScale +OAI.Analysis.CoulombRadii.FieldAnalysis.Gaussian +OAI.Analysis.CoulombRadii.FieldAnalysis.GeometricRecursion +OAI.Analysis.CoulombRadii.FieldAnalysis.GridIndex +OAI.Analysis.CoulombRadii.FieldAnalysis.GroupFermionicCoefficients +OAI.Analysis.CoulombRadii.FieldAnalysis.HighProjection +OAI.Analysis.CoulombRadii.FieldAnalysis.IntegrableIntegralAeTendsto +OAI.Analysis.CoulombRadii.FieldAnalysis.IntegrableTsumSummableNormIntegral +OAI.Analysis.CoulombRadii.FieldAnalysis.JoinSpins +OAI.Analysis.CoulombRadii.FieldAnalysis.LeftPotential +OAI.Analysis.CoulombRadii.FieldAnalysis.LipschitzTestEnergy +OAI.Analysis.CoulombRadii.FieldAnalysis.LowProjection +OAI.Analysis.CoulombRadii.FieldAnalysis.MeridianMap +OAI.Analysis.CoulombRadii.FieldAnalysis.MinimizerMidpointControl +OAI.Analysis.CoulombRadii.FieldAnalysis.ModulatedRealDerivativeNorm +OAI.Analysis.CoulombRadii.FieldAnalysis.NearCoulombFiveHalves +OAI.Analysis.CoulombRadii.FieldAnalysis.NewtonInterior +OAI.Analysis.CoulombRadii.FieldAnalysis.NewtonSubmean +OAI.Analysis.CoulombRadii.FieldAnalysis.NormSqSumCosets +OAI.Analysis.CoulombRadii.FieldAnalysis.Occupancy +OAI.Analysis.CoulombRadii.FieldAnalysis.OuterJoinConfiguration +OAI.Analysis.CoulombRadii.FieldAnalysis.PairRegroup +OAI.Analysis.CoulombRadii.FieldAnalysis.PatchNegativeMean +OAI.Analysis.CoulombRadii.FieldAnalysis.PatchRawTransfer +OAI.Analysis.CoulombRadii.FieldAnalysis.PermOrCompSwapOffTwo +OAI.Analysis.CoulombRadii.FieldAnalysis.PermuteJoinBlock +OAI.Analysis.CoulombRadii.FieldAnalysis.PhaseRegion +OAI.Analysis.CoulombRadii.FieldAnalysis.PhysicalPoisson +OAI.Analysis.CoulombRadii.FieldAnalysis.PoissonInterior +OAI.Analysis.CoulombRadii.FieldAnalysis.PositiveField +OAI.Analysis.CoulombRadii.FieldAnalysis.PotentialAddRsmul +OAI.Analysis.CoulombRadii.FieldAnalysis.RawObservable +OAI.Analysis.CoulombRadii.FieldAnalysis.RawRMS +OAI.Analysis.CoulombRadii.FieldAnalysis.RawThomasFermiEnergy +OAI.Analysis.CoulombRadii.FieldAnalysis.RestrictedField +OAI.Analysis.CoulombRadii.FieldAnalysis.RetainedFineDensity +OAI.Analysis.CoulombRadii.FieldAnalysis.RetainedFineDensityConfigurationMeasurable +OAI.Analysis.CoulombRadii.FieldAnalysis.RetainedFinePower +OAI.Analysis.CoulombRadii.FieldAnalysis.RotatedDensityPower +OAI.Analysis.CoulombRadii.FieldAnalysis.Rotation +OAI.Analysis.CoulombRadii.FieldAnalysis.ScaledOscillation +OAI.Analysis.CoulombRadii.FieldAnalysis.SliceExpectation +OAI.Analysis.CoulombRadii.FieldAnalysis.SlotTensor +OAI.Analysis.CoulombRadii.FieldAnalysis.SortedObservable +OAI.Analysis.CoulombRadii.FieldAnalysis.Space +OAI.Analysis.CoulombRadii.FieldAnalysis.SpinConfigurationIntegral +OAI.Analysis.CoulombRadii.FieldAnalysis.SpinCubeEquiv +OAI.Analysis.CoulombRadii.FieldAnalysis.SpinMode +OAI.Analysis.CoulombRadii.FieldAnalysis.SumSpinDuplicate +OAI.Analysis.CoulombRadii.FieldAnalysis.SumSwapNonnegative +OAI.Analysis.CoulombRadii.FieldAnalysis.TailClosure +OAI.Analysis.CoulombRadii.FieldAnalysis.TsumFixed +OAI.Analysis.CoulombRadii.FieldAnalysis.TwoBodyTensorIntegrable +OAI.Analysis.CoulombRadii.FieldAnalysis.UniformBall +OAI.Analysis.CoulombRadii.FieldAnalysis.UnitNucleus +OAI.Analysis.CoulombRadii.FieldAnalysis.WeakDirectionalUnique +OAI.Analysis.CoulombRadii.FieldAnalysis.WedgeMultiplicity +OAI.Analysis.CoulombRadii.FieldAnalysis.Weighted +OAI.Analysis.CoulombRadii.FieldAnalysis.WeightedExchangeAlgebra +OAI.Analysis.CoulombRadii.FieldAnalysis.WeightedExterior +OAI.Analysis.CoulombRadii.FieldAnalysis.WeightedInner +OAI.Analysis.CoulombRadii.FormDomain.Add +OAI.Analysis.CoulombRadii.FormDomain.AppendJensen +OAI.Analysis.CoulombRadii.FormDomain.AtomicPhysicalKinetic +OAI.Analysis.CoulombRadii.FormDomain.BallTrial +OAI.Analysis.CoulombRadii.FormDomain.CoreKinetic +OAI.Analysis.CoulombRadii.FormDomain.CoreSliceRegular +OAI.Analysis.CoulombRadii.FormDomain.CubeGradient +OAI.Analysis.CoulombRadii.FormDomain.ExplicitMultiplyGradient +OAI.Analysis.CoulombRadii.FormDomain.FieldOptimization +OAI.Analysis.CoulombRadii.FormDomain.H1EnergyLimit +OAI.Analysis.CoulombRadii.FormDomain.H1Pairing +OAI.Analysis.CoulombRadii.FormDomain.H1VectorL2 +OAI.Analysis.CoulombRadii.FormDomain.HardyMollifier +OAI.Analysis.CoulombRadii.FormDomain.HilbertBasisContaining +OAI.Analysis.CoulombRadii.FormDomain.HilbertBasisSumSqInner +OAI.Analysis.CoulombRadii.FormDomain.L1L2Fourier +OAI.Analysis.CoulombRadii.FormDomain.L2KernelIntegral +OAI.Analysis.CoulombRadii.FormDomain.L2MeasureInclusion +OAI.Analysis.CoulombRadii.FormDomain.L2MultiplierContinuity +OAI.Analysis.CoulombRadii.FormDomain.L2MultiplierDistribution +OAI.Analysis.CoulombRadii.FormDomain.L2TightCompact +OAI.Analysis.CoulombRadii.FormDomain.L2WeightedDensitySetIntegral +OAI.Analysis.CoulombRadii.FormDomain.ObservationAtomic +OAI.Analysis.CoulombRadii.FormDomain.OrbitalHilbertBasis +OAI.Analysis.CoulombRadii.FormDomain.PacketStateL2Norm +OAI.Analysis.CoulombRadii.FormDomain.ParticleGradientNorm +OAI.Analysis.CoulombRadii.FormDomain.PatchErrors +OAI.Analysis.CoulombRadii.FormDomain.PhysicalEnsemble +OAI.Analysis.CoulombRadii.FormDomain.Pullback +OAI.Analysis.CoulombRadii.FormDomain.RawAnnularMoment +OAI.Analysis.CoulombRadii.FormDomain.RecordReindex +OAI.Analysis.CoulombRadii.FormDomain.RegularizedHardyField +OAI.Analysis.CoulombRadii.FormDomain.RegularizedKinetic +OAI.Analysis.CoulombRadii.FormDomain.RetainedPotentialMean +OAI.Analysis.CoulombRadii.FormDomain.SchwartzFourierDerivativeNorm +OAI.Analysis.CoulombRadii.FormDomain.SchwartzSquareIntegrable +OAI.Analysis.CoulombRadii.FormDomain.SmoothCompact +OAI.Analysis.CoulombRadii.FormDomain.SortedCut +OAI.Analysis.CoulombRadii.FormDomain.SpaceFourierL2 +OAI.Analysis.CoulombRadii.FormDomain.TfGradientField +OAI.Analysis.CoulombRadii.FormDomain.ThomasFermiKineticConstant +OAI.Analysis.CoulombRadii.FormDomain.Translate +OAI.Analysis.CoulombRadii.FormDomain.WeakFourierDerivative +OAI.Analysis.CoulombRadii.FormDomain.WeakHilbertCompact +OAI.Analysis.CoulombRadii.FormDomain.WeakSchwartzDerivative +OAI.Analysis.CoulombRadii.FormDomain.WindowSquare +OAI.Analysis.CoulombRadii.LimitTheory.AdmissibleStage +OAI.Analysis.CoulombRadii.LimitTheory.AtomicOutKinetic +OAI.Analysis.CoulombRadii.LimitTheory.NeutralBaseline +OAI.Analysis.CoulombRadii.LimitTheory.NeutralCountControl +OAI.Analysis.CoulombRadii.LimitTheory.TailFinish +OAI.Analysis.CoulombRadii.LimitTheory.UniformGroundStateCountControl +OAI.Analysis.CoulombRadii.Localization.AnnularCut +OAI.Analysis.CoulombRadii.Localization.AnnularHistory +OAI.Analysis.CoulombRadii.Localization.AtomicHistory +OAI.Analysis.CoulombRadii.Localization.AtomicRetainedGap +OAI.Analysis.CoulombRadii.Localization.ConfigSupported +OAI.Analysis.CoulombRadii.Localization.CutCombinatorics +OAI.Analysis.CoulombRadii.Localization.CutCore +OAI.Analysis.CoulombRadii.Localization.CutRefinement +OAI.Analysis.CoulombRadii.Localization.DeletedLabels +OAI.Analysis.CoulombRadii.Localization.DeletionEnvelope +OAI.Analysis.CoulombRadii.Localization.DensityCut +OAI.Analysis.CoulombRadii.Localization.DyadicTailPartial +OAI.Analysis.CoulombRadii.Localization.ExteriorCut +OAI.Analysis.CoulombRadii.Localization.HarmonicInterior +OAI.Analysis.CoulombRadii.Localization.HarmonicScale +OAI.Analysis.CoulombRadii.Localization.Partial +OAI.Analysis.CoulombRadii.Localization.RadialAppend +OAI.Analysis.CoulombRadii.Localization.RadialCut +OAI.Analysis.CoulombRadii.Localization.RegularizedBounds +OAI.Analysis.CoulombRadii.Localization.ShellChoice +OAI.Analysis.CoulombRadii.Localization.ShellIMS +OAI.Analysis.CoulombRadii.Localization.SmoothMultiplier +OAI.Analysis.CoulombRadii.Localization.ThinCut +OAI.Analysis.CoulombRadii.Localization.ThinIMS +OAI.Analysis.CoulombRadii.Localization.TotalDeletion +OAI.Analysis.CoulombRadii.Localization.TruncatedCoulomb +OAI.Analysis.CoulombRadii.Main +OAI.Analysis.CoulombRadii.Model +OAI.Analysis.CoulombRadii.Packets.AnnularAddback +OAI.Analysis.CoulombRadii.Packets.AnnularIMS +OAI.Analysis.CoulombRadii.Packets.AtomicMesh +OAI.Analysis.CoulombRadii.Packets.AtomicSmallPatch +OAI.Analysis.CoulombRadii.Packets.BandOscillation +OAI.Analysis.CoulombRadii.Packets.ComplexWindow +OAI.Analysis.CoulombRadii.Packets.CoreScreenedFieldPacketIntegral +OAI.Analysis.CoulombRadii.Packets.CoulombKernel +OAI.Analysis.CoulombRadii.Packets.CoulombKernelFiveHalvesIntegrable +OAI.Analysis.CoulombRadii.Packets.FineKernelShiftCoulombIntegrable +OAI.Analysis.CoulombRadii.Packets.FineNear +OAI.Analysis.CoulombRadii.Packets.InnerMeshCap +OAI.Analysis.CoulombRadii.Packets.InverseErrorScale +OAI.Analysis.CoulombRadii.Packets.InverseGeometry +OAI.Analysis.CoulombRadii.Packets.KernelCenterMass +OAI.Analysis.CoulombRadii.Packets.KernelScale +OAI.Analysis.CoulombRadii.Packets.LipschitzMollifier +OAI.Analysis.CoulombRadii.Packets.MasterKernel +OAI.Analysis.CoulombRadii.Packets.MasterKernelDuality +OAI.Analysis.CoulombRadii.Packets.MasterNewton +OAI.Analysis.CoulombRadii.Packets.MasterTruncatedCap +OAI.Analysis.CoulombRadii.Packets.MeshInverseDeterministic +OAI.Analysis.CoulombRadii.Packets.NearLpCoulomb +OAI.Analysis.CoulombRadii.Packets.NormalizedBandModulus +OAI.Analysis.CoulombRadii.Packets.NormalizedInversePoint +OAI.Analysis.CoulombRadii.Packets.OrbitalKernel +OAI.Analysis.CoulombRadii.Packets.OriginalPotentialTower +OAI.Analysis.CoulombRadii.Packets.PacketBandGeometry +OAI.Analysis.CoulombRadii.Packets.PacketBridge +OAI.Analysis.CoulombRadii.Packets.PacketDensity +OAI.Analysis.CoulombRadii.Packets.PacketDensityReal +OAI.Analysis.CoulombRadii.Packets.PacketIndex +OAI.Analysis.CoulombRadii.Packets.PacketStateJointSquareIntegrable +OAI.Analysis.CoulombRadii.Packets.PacketSynthesis +OAI.Analysis.CoulombRadii.Packets.PacketSynthesisIndicator +OAI.Analysis.CoulombRadii.Packets.PacketWidthScalar +OAI.Analysis.CoulombRadii.Packets.PacketWindowed +OAI.Analysis.CoulombRadii.Packets.PatchKernelDuality +OAI.Analysis.CoulombRadii.Packets.PatchPacketResponse +OAI.Analysis.CoulombRadii.Packets.PhysicalInteriorTransfer +OAI.Analysis.CoulombRadii.Packets.PhysicalInverseCap +OAI.Analysis.CoulombRadii.Packets.PhysicalRetainedDatum +OAI.Analysis.CoulombRadii.Packets.PhysicalRetainedMean +OAI.Analysis.CoulombRadii.Packets.PhysicalSimultaneousInverse +OAI.Analysis.CoulombRadii.Packets.RadialRMS +OAI.Analysis.CoulombRadii.Packets.RawMasterNewton +OAI.Analysis.CoulombRadii.Packets.RetainedInverseOffset +OAI.Analysis.CoulombRadii.Packets.ScaledWindow +OAI.Analysis.CoulombRadii.Packets.ScreenBox +OAI.Analysis.CoulombRadii.Packets.SimultaneousInverseScale +OAI.Analysis.CoulombRadii.Packets.TailMoment +OAI.Analysis.CoulombRadii.Packets.WindowCoulomb +OAI.Analysis.CoulombRadii.Propagation.EnsembleMoments +OAI.Analysis.CoulombRadii.Propagation.InitialDatum +OAI.Analysis.CoulombRadii.Propagation.InitialInvariant +OAI.Analysis.CoulombRadii.Propagation.InitialMesh +OAI.Analysis.CoulombRadii.Propagation.InitializationBranch +OAI.Analysis.CoulombRadii.Propagation.MaximumMollifier +OAI.Analysis.CoulombRadii.Propagation.NearActiveMaximum +OAI.Analysis.CoulombRadii.Propagation.NuclearPotential +OAI.Analysis.CoulombRadii.Propagation.NuclearPotentialSplitJoin +OAI.Analysis.CoulombRadii.Propagation.ObservationGoodGap +OAI.Analysis.CoulombRadii.Propagation.PhysicalFinitePropagation +OAI.Analysis.CoulombRadii.Propagation.PhysicalInitialPoint +OAI.Analysis.CoulombRadii.Propagation.PosteriorPropagationData +OAI.Analysis.CoulombRadii.Propagation.PropagationAverage +OAI.Analysis.CoulombRadii.Propagation.PropagationAverageAE +OAI.Analysis.CoulombRadii.Propagation.PropagationBarrierBounds +OAI.Analysis.CoulombRadii.Propagation.PropagationBarrierOffset +OAI.Analysis.CoulombRadii.Propagation.PropagationConstants +OAI.Analysis.CoulombRadii.Propagation.PropagationDatumRegularity +OAI.Analysis.CoulombRadii.Propagation.PropagationExpectedDeficit +OAI.Analysis.CoulombRadii.Propagation.PropagationMassTest +OAI.Analysis.CoulombRadii.Propagation.PropagationMaximum +OAI.Analysis.CoulombRadii.Propagation.PropagationPosteriorMass +OAI.Analysis.CoulombRadii.Propagation.PropagationPosteriorStep +OAI.Analysis.CoulombRadii.Propagation.PropagationRegularity +OAI.Analysis.CoulombRadii.Propagation.PropagationStepWeak +OAI.Analysis.CoulombRadii.Propagation.RadialMaxSplice +OAI.Analysis.CoulombRadii.Propagation.RetainedGoodEvent +OAI.Analysis.CoulombRadii.Propagation.SmoothMaximum +OAI.Analysis.CoulombRadii.Propagation.TfReaction +OAI.Analysis.CoulombRadii.Propagation.UniformScreening +OAI.Analysis.CoulombRadii.Propagation.WeakLocality +OAI.Analysis.CoulombRadii.Propagation.WeakReactionMax +OAI.Analysis.CoulombRadii.RadialBounds.AtomicMasterError +OAI.Analysis.CoulombRadii.RadialBounds.InteriorBarrier +OAI.Analysis.CoulombRadii.RadialBounds.NearActive +OAI.Analysis.CoulombRadii.RadialBounds.PhysicalBarrierData +OAI.Analysis.CoulombRadii.RadialBounds.PhysicalShellError +OAI.Analysis.CoulombRadii.RadialBounds.Radial +OAI.Analysis.CoulombRadii.RadialBounds.SpatialAnnulus +OAI.Analysis.CoulombRadii.RandomFields.AtomicThinScreening +OAI.Analysis.CoulombRadii.RandomFields.BinaryDeletion +OAI.Analysis.CoulombRadii.RandomFields.CompactRandomField +OAI.Analysis.CoulombRadii.RandomFields.ConditionalDensity +OAI.Analysis.CoulombRadii.RandomFields.ConditionalEnergy +OAI.Analysis.CoulombRadii.RandomFields.ConditionalMatching +OAI.Analysis.CoulombRadii.RandomFields.ConditionalPositiveField +OAI.Analysis.CoulombRadii.RandomFields.ConditionalRMS +OAI.Analysis.CoulombRadii.RandomFields.CoreBudget +OAI.Analysis.CoulombRadii.RandomFields.CoreGap +OAI.Analysis.CoulombRadii.RandomFields.CutJensen +OAI.Analysis.CoulombRadii.RandomFields.EnsembleCauchy +OAI.Analysis.CoulombRadii.RandomFields.EnsembleCoveredCost +OAI.Analysis.CoulombRadii.RandomFields.EnsembleTransfer +OAI.Analysis.CoulombRadii.RandomFields.EventTiltWavefunction +OAI.Analysis.CoulombRadii.RandomFields.ExactRecordedCount +OAI.Analysis.CoulombRadii.RandomFields.ExteriorIMS +OAI.Analysis.CoulombRadii.RandomFields.FiniteInverseEvent +OAI.Analysis.CoulombRadii.RandomFields.InnerFieldRMS +OAI.Analysis.CoulombRadii.RandomFields.InverseEventContradiction +OAI.Analysis.CoulombRadii.RandomFields.JointSlice +OAI.Analysis.CoulombRadii.RandomFields.LocalizedEnsemble +OAI.Analysis.CoulombRadii.RandomFields.ObservationAnnulusTail +OAI.Analysis.CoulombRadii.RandomFields.ObservationDyadicWidth +OAI.Analysis.CoulombRadii.RandomFields.ObservationFieldTransfer +OAI.Analysis.CoulombRadii.RandomFields.ObservationHigh +OAI.Analysis.CoulombRadii.RandomFields.ObservationMatching +OAI.Analysis.CoulombRadii.RandomFields.ObservationMeanBounds +OAI.Analysis.CoulombRadii.RandomFields.ObservationNegativeMean +OAI.Analysis.CoulombRadii.RandomFields.ObservationPatchScale +OAI.Analysis.CoulombRadii.RandomFields.ObservationProductDensity +OAI.Analysis.CoulombRadii.RandomFields.ObservationSmallScale +OAI.Analysis.CoulombRadii.RandomFields.ObservationWidthSquareSum +OAI.Analysis.CoulombRadii.RandomFields.ObservedUnordered +OAI.Analysis.CoulombRadii.RandomFields.PhysicalBandEvent +OAI.Analysis.CoulombRadii.RandomFields.PhysicalBandRegularity +OAI.Analysis.CoulombRadii.RandomFields.PhysicalDeficitMoment +OAI.Analysis.CoulombRadii.RandomFields.PhysicalDeficitTail +OAI.Analysis.CoulombRadii.RandomFields.PhysicalEnsembleGap +OAI.Analysis.CoulombRadii.RandomFields.PhysicalLikelihoodBridge +OAI.Analysis.CoulombRadii.RandomFields.PhysicalPosteriorInverse +OAI.Analysis.CoulombRadii.RandomFields.PhysicalRetainedLikelihood +OAI.Analysis.CoulombRadii.RandomFields.PosteriorBandOscillation +OAI.Analysis.CoulombRadii.RandomFields.PosteriorCount +OAI.Analysis.CoulombRadii.RandomFields.PosteriorDataMeasurable +OAI.Analysis.CoulombRadii.RandomFields.PosteriorDensityContinuity +OAI.Analysis.CoulombRadii.RandomFields.PosteriorFieldPDE +OAI.Analysis.CoulombRadii.RandomFields.PosteriorRegularBounds +OAI.Analysis.CoulombRadii.RandomFields.PosteriorShellError +OAI.Analysis.CoulombRadii.RandomFields.PosteriorSpatialCap +OAI.Analysis.CoulombRadii.RandomFields.QuantumRetainedFamily +OAI.Analysis.CoulombRadii.RandomFields.RawCap +OAI.Analysis.CoulombRadii.RandomFields.RecordJensen +OAI.Analysis.CoulombRadii.RandomFields.RecordedCount +OAI.Analysis.CoulombRadii.RandomFields.RecordedEnsemble +OAI.Analysis.CoulombRadii.RandomFields.RecordedStatistic +OAI.Analysis.CoulombRadii.RandomFields.ThinEnsemble +OAI.Analysis.CoulombRadii.RandomFields.WeightedDeletion +OAI.Analysis.CoulombRadii.Screening.AnnularSubmeanCap +OAI.Analysis.CoulombRadii.Screening.AtomicBudgetHistory +OAI.Analysis.CoulombRadii.Screening.AtomicBudgetScreening +OAI.Analysis.CoulombRadii.Screening.AtomicCapRaw +OAI.Analysis.CoulombRadii.Screening.AtomicMasterFresh +OAI.Analysis.CoulombRadii.Screening.AtomicMasterRelative +OAI.Analysis.CoulombRadii.Screening.AtomicNumber +OAI.Analysis.CoulombRadii.Screening.AtomicPatchCap +OAI.Analysis.CoulombRadii.Screening.CoreCount +OAI.Analysis.CoulombRadii.Screening.CoreMoment +OAI.Analysis.CoulombRadii.Screening.CoreScreenedField +OAI.Analysis.CoulombRadii.Screening.CountMoments +OAI.Analysis.CoulombRadii.Screening.CountScalar +OAI.Analysis.CoulombRadii.Screening.CountUnits +OAI.Analysis.CoulombRadii.Screening.CoveredOutCost +OAI.Analysis.CoulombRadii.Screening.DeficitMoment +OAI.Analysis.CoulombRadii.Screening.FineCountTest +OAI.Analysis.CoulombRadii.Screening.InnerCap +OAI.Analysis.CoulombRadii.Screening.LogTailMoment +OAI.Analysis.CoulombRadii.Screening.NegativeCost +OAI.Analysis.CoulombRadii.Screening.OutCap +OAI.Analysis.CoulombRadii.Screening.PatchComparison +OAI.Analysis.CoulombRadii.Screening.PhysicalCapMoment +OAI.Analysis.CoulombRadii.Screening.PhysicalLTBridge +OAI.Analysis.CoulombRadii.Screening.PhysicalSpatialCap +OAI.Analysis.CoulombRadii.Screening.ScaledFieldCap +OAI.Analysis.CoulombRadii.Screening.ScaledTest +OAI.Analysis.CoulombRadii.Screening.ScreenNumeric +OAI.Analysis.CoulombRadii.Screening.ScreenRecurrence +OAI.Analysis.CoulombRadii.Screening.ScreenUnits +OAI.Analysis.CoulombRadii.Screening.ScreeningNormalization +OAI.Analysis.CoulombRadii.Screening.SharpThinScreening +OAI.Analysis.CoulombRadii.Screening.ShellSummable +OAI.Analysis.CoulombRadii.Screening.UniformCountConsequences +OAI.Analysis.CoulombRadii.Screening.UpperDeficit +OAI.Analysis.CoulombRadii.SpectralTheory.AmbientEigen +OAI.Analysis.CoulombRadii.SpectralTheory.BindingBump +OAI.Analysis.CoulombRadii.SpectralTheory.BindingCut +OAI.Analysis.CoulombRadii.SpectralTheory.CorePredecessor +OAI.Analysis.CoulombRadii.SpectralTheory.EigenspaceBasisSet +OAI.Analysis.CoulombRadii.SpectralTheory.FermiPacketSpectralTrace +OAI.Analysis.CoulombRadii.SpectralTheory.GlobalSectorMinimum +OAI.Analysis.CoulombRadii.SpectralTheory.SectorBottomBridge +OAI.Analysis.CoulombRadii.SpectralTheory.SectorFormBottom +OAI.Analysis.CoulombRadii.SpectralTheory.StrictBinding +OAI.Analysis.CoulombRadii.ThomasFermi.AtomicRefinedGap +OAI.Analysis.CoulombRadii.ThomasFermi.AtomicThinCounts +OAI.Analysis.CoulombRadii.ThomasFermi.BinaryEnsemble +OAI.Analysis.CoulombRadii.ThomasFermi.CountTestFlux +OAI.Analysis.CoulombRadii.ThomasFermi.FirstFiber +OAI.Analysis.CoulombRadii.ThomasFermi.InverseDensityError +OAI.Analysis.CoulombRadii.ThomasFermi.LpParameter +OAI.Analysis.CoulombRadii.ThomasFermi.PacketFrame +OAI.Analysis.CoulombRadii.ThomasFermi.PatchFieldMeans +OAI.Analysis.CoulombRadii.ThomasFermi.PatchGeometry +OAI.Analysis.CoulombRadii.ThomasFermi.PatchNegativeCost +OAI.Analysis.CoulombRadii.ThomasFermi.PatchResponse +OAI.Analysis.CoulombRadii.ThomasFermi.PhysicalCount +OAI.Analysis.CoulombRadii.ThomasFermi.QuantumProfileDatum +OAI.Analysis.CoulombRadii.ThomasFermi.Rescaling +OAI.Analysis.CoulombRadii.ThomasFermi.ScaledProfile +OAI.Analysis.CoulombRadii.ThomasFermi.TFCountTest +OAI.Analysis.CoulombRadii.ThomasFermi.TFExponent +OAI.Analysis.CoulombRadii.ThomasFermi.TFInterior +OAI.Analysis.CoulombRadii.ThomasFermi.TFNegativeGap +OAI.Analysis.CoulombRadii.ThomasFermi.TFNonneg +OAI.Analysis.CoulombRadii.ThomasFermi.TFOscillation +OAI.Analysis.CoulombRadii.ThomasFermi.TFPotentialParameter +OAI.Analysis.CoulombRadii.ThomasFermi.TFResponseMargins +OAI.Analysis.CoulombRadii.ThomasFermi.TfExtendNonneg +OAI.Analysis.CoulombRadii.ThomasFermi.TfFunctional +OAI.Analysis.CoulombRadii.ThomasFermi.TfFunctionalGapControl +OAI.Analysis.CoulombRadii.ThomasFermi.TfFunctionalUniformBound +OAI.Analysis.CoulombRadii.ThomasFermi.TfPotential +OAI.Analysis.CoulombRadii.ThomasFermi.TfRawVariation +OAI.Analysis.CoulombRadii.Variational.AtomicMasterUniform +OAI.Analysis.CoulombRadii.Variational.Axis +OAI.Analysis.CoulombRadii.Variational.ConfigurationDensity +OAI.Analysis.CoulombRadii.Variational.ConfigurationSplit +OAI.Analysis.CoulombRadii.Variational.CorrectionDensity +OAI.Analysis.CoulombRadii.Variational.PhysicalBridge +OAI.Analysis.CoulombRadii.Variational.PhysicalCoreMean +OAI.Analysis.CoulombRadii.Variational.PhysicalDensityWeighted +OAI.Analysis.CoulombRadii.Variational.PhysicalOffsetMean +OAI.Analysis.CoulombRadii.Variational.PuncturedPosition +OAI.Analysis.CoulombRadii.Variational.RetainedAnalyticSequence +OAI.Analysis.CoulombRadii.Variational.RetainedMasterTransfer +OAI.Analysis.CoulombRadii.Variational.SignAverage +OAI.Analysis.CoulombRadii.Variational.WeakAdd +OAI.Analysis.CoulombRadii.Variational.WeakLaplacian +OAI.Analysis.CoulombRadii.Variational.WedgeInsert +OAI.Analysis.CoulombRadii.Variational.WeightedNegative diff --git a/tasks/coulomb-radii/solution/reference.py b/tasks/coulomb-radii/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/coulomb-radii/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/coulomb-radii/solution/solve.sh b/tasks/coulomb-radii/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..70ca682f9f3e8e5513af6aa58c44a2595e09ec64 --- /dev/null +++ b/tasks/coulomb-radii/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoulombRadii, i.e. module OAI.Analysis.CoulombRadii.Main and the +# 428 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.CoulombRadii.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoulombRadii" diff --git a/tasks/coulomb-radii/task.toml b/tasks/coulomb-radii/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f9c3730ee0c88d5225cd0688a07bb680235e0c8 --- /dev/null +++ b/tasks/coulomb-radii/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/coulomb-radii" +version = "1.0.0" +description = "Prove CoulombRadii (openai/math family 263: The ionization and generalized ionization conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoulombRadii.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoulombRadii" +family = "263" +family_title = "The ionization and generalized ionization conjectures" +subject = "Mathematical physics" +theorems = ["OAI.NeutralAtom.generalized_outer_radii"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.CoulombRadii.Main" +reference_modules = 428 +reference_lean_bytes = 3858816 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2054 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15172 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/coulomb-radii/tests/Challenge.lean b/tasks/coulomb-radii/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1b02bc0cef6c54a74c1dfb5d3eca36292586e8d7 --- /dev/null +++ b/tasks/coulomb-radii/tests/Challenge.lean @@ -0,0 +1,89 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter +open scoped BigOperators Topology ContDiff + +namespace NeutralAtom + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Configuration (n : ℕ) := Fin n → Position +abbrev Spins (n : ℕ) := Fin n → Fin 2 +abbrev Wavefunction (n : ℕ) := Spins n → Configuration n → ℂ +abbrev Gradient (n : ℕ) := Spins n → Fin n → Fin 3 → Configuration n → ℂ + +def coordinateDirection {n : ℕ} (i : Fin n) (a : Fin 3) : Configuration n := + Pi.single i (EuclideanSpace.single a 1) + +def HasWeakGradient {n : ℕ} (ψ : Wavefunction n) (g : Gradient n) : Prop := + ∀ σ i a (φ : Configuration n → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + (∫ x, (fderiv ℝ φ x (coordinateDirection i a) : ℂ) * ψ σ x) = + -(∫ x, (φ x : ℂ) * g σ i a x) + +def IsAntisymmetric {n : ℕ} (ψ : Wavefunction n) : Prop := + ∀ (p : Equiv.Perm (Fin n)) (σ : Spins n), + (fun x : Configuration n => ψ (σ ∘ p) (x ∘ p)) =ᵐ[volume] + (fun x => (((Equiv.Perm.sign p : ℤ) : ℂ)) * ψ σ x) + +def FormDomain {n : ℕ} (ψ : Wavefunction n) (g : Gradient n) : Prop := + IsAntisymmetric ψ ∧ HasWeakGradient ψ g ∧ + (∀ σ, MemLp (ψ σ) 2 volume) ∧ + (∀ σ i a, MemLp (g σ i a) 2 volume) ∧ + (∀ σ i, Integrable (fun x : Configuration n => ‖x i‖⁻¹ * ‖ψ σ x‖ ^ 2)) ∧ + (∀ σ i j, i < j → + Integrable (fun x : Configuration n => ‖x i - x j‖⁻¹ * ‖ψ σ x‖ ^ 2)) + +def normSquared {n : ℕ} (ψ : Wavefunction n) : ℝ := + ∑ σ : Spins n, ∫ x : Configuration n, ‖ψ σ x‖ ^ 2 + +def coulombPotential {n : ℕ} (Z : ℕ) (x : Configuration n) : ℝ := + -(Z : ℝ) * (∑ i : Fin n, ‖x i‖⁻¹) + + ∑ i : Fin n, ∑ j ∈ Finset.univ.filter (fun j : Fin n => i < j), ‖x i - x j‖⁻¹ + +def energy {n : ℕ} (Z : ℕ) (ψ : Wavefunction n) (g : Gradient n) : ℝ := + (1 / 2 : ℝ) * (∑ σ : Spins n, ∑ i : Fin n, ∑ a : Fin 3, + ∫ x : Configuration n, ‖g σ i a x‖ ^ 2) + + ∑ σ : Spins n, ∫ x : Configuration n, coulombPotential Z x * ‖ψ σ x‖ ^ 2 + +def IsNormalizedGroundState (Z : ℕ) (ψ : Wavefunction Z) : Prop := + ∃ g : Gradient Z, FormDomain ψ g ∧ normSquared ψ = 1 ∧ + ∀ (χ : Wavefunction Z) (h : Gradient Z), + FormDomain χ h → normSquared χ = 1 → energy Z ψ g ≤ energy Z χ h + +def density {N : ℕ} (ψ : Wavefunction (N + 1)) (x : Position) : ℝ := + (N + 1 : ℝ) * ∑ σ : Spins (N + 1), + ∫ y : Configuration N, ‖ψ σ (Fin.cons x y)‖ ^ 2 + +def exteriorMass {N : ℕ} (ψ : Wavefunction (N + 1)) (r : ℝ) : ℝ := + ∫ x in {x : Position | r < ‖x‖}, density ψ x + +def radius {N : ℕ} (ψ : Wavefunction (N + 1)) (m : ℕ) : ℝ := + sInf {r : ℝ | 0 ≤ r ∧ exteriorMass ψ r ≤ (m : ℝ)} + +def bTF : ℝ := (81 * Real.pi ^ 2 / 2) ^ (1 / 3 : ℝ) + +def largeCharge (m : ℕ) : Filter ℕ := + atTop ⊓ Filter.principal {N : ℕ | m < N + 1} + +def upperRadius (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) (m : ℕ) : EReal := + Filter.limsup (fun N : ℕ => (radius (Ψ N) m : EReal)) (largeCharge m) + +def lowerRadius (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) (m : ℕ) : EReal := + Filter.liminf (fun N : ℕ => (radius (Ψ N) m : EReal)) (largeCharge m) + +theorem generalized_outer_radii + (Ψ : ∀ N : ℕ, Wavefunction (N + 1)) + (hΨ : ∀ N : ℕ, IsNormalizedGroundState (N + 1) (Ψ N)) : + Tendsto (fun m : ℕ => (((m : ℝ) ^ (1 / 3 : ℝ) : ℝ) : EReal) * upperRadius Ψ m) + atTop (𝓝 (bTF : EReal)) ∧ + Tendsto (fun m : ℕ => (((m : ℝ) ^ (1 / 3 : ℝ) : ℝ) : EReal) * lowerRadius Ψ m) + atTop (𝓝 (bTF : EReal)) := by + sorry + +end NeutralAtom +end + +end OAI diff --git a/tasks/coulomb-radii/tests/grade.py b/tasks/coulomb-radii/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/coulomb-radii/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/coulomb-radii/tests/task.json b/tasks/coulomb-radii/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6bc32617d7e27f56a2cc632e1ebf9b3b234bae4c --- /dev/null +++ b/tasks/coulomb-radii/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoulombRadii", + "comparator": { + "theorem_names": [ + "OAI.NeutralAtom.generalized_outer_radii" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14272 +} \ No newline at end of file diff --git a/tasks/coulomb-radii/tests/test.sh b/tasks/coulomb-radii/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/coulomb-radii/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/courtade-kumar/environment/Dockerfile b/tasks/courtade-kumar/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/courtade-kumar/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/courtade-kumar/environment/fetch_mathlib.sh b/tasks/courtade-kumar/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/courtade-kumar/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/courtade-kumar/environment/lake-manifest.json b/tasks/courtade-kumar/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/courtade-kumar/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/courtade-kumar/environment/lakefile.lean b/tasks/courtade-kumar/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/courtade-kumar/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/courtade-kumar/environment/lean_setup.sh b/tasks/courtade-kumar/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/courtade-kumar/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/courtade-kumar/environment/pack_submission.py b/tasks/courtade-kumar/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/courtade-kumar/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/courtade-kumar/instruction.md b/tasks/courtade-kumar/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..847d4e44b58e86ec36f4ecb906a9063c5a32e2ec --- /dev/null +++ b/tasks/courtade-kumar/instruction.md @@ -0,0 +1,127 @@ +# openai/math challenge `CourtadeKumar` (family 119) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 119 of the release, *The Courtade–Kumar and Hellinger conjectures* +(Theoretical computer science). The family as a whole: Proves the Courtade–Kumar conjecture: among Boolean functions of independent uniform bits, a single coordinate retains the most mutual information after independent bit-flip noise. A stronger theorem treats randomized binary summaries at fixed initial information. The Hellinger conjecture is also proved for every Boolean output bias and noise correlation. + +The challenge is `CourtadeKumar`, also at `/opt/openai-math/challenges/CourtadeKumar.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators + +namespace LeanBlast.GotsmanLinial + +abbrev Cube (n : ℕ) := Fin n → Bool + +end LeanBlast.GotsmanLinial + +noncomputable section + +open scoped BigOperators + +namespace LeanBlast.CourtadeKumar + +abbrev Cube (n : ℕ) := LeanBlast.GotsmanLinial.Cube n + +def cubeAverage {n : ℕ} (g : Cube n → ℝ) : ℝ := + (∑ x, g x) / (2 : ℝ) ^ n + +def ell : ℝ := Real.log 2 + +def bitFlipKernel {n : ℕ} (ε : ℝ) (x y : Cube n) : ℝ := + ∏ i, if x i = y i then 1 - ε else ε + +def jointProbability {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (b : Bool) (y : Cube n) : ℝ := + cubeAverage (fun x => if f x = b then bitFlipKernel ε x y else 0) + +def functionMarginal {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (b : Bool) : ℝ := + ∑ y, jointProbability ε f b y + +def observationMarginal {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (y : Cube n) : ℝ := + ∑ b : Bool, jointProbability ε f b y + +def xlogx (t : ℝ) : ℝ := t * Real.log t + +def binaryEntropy (ε : ℝ) : ℝ := + -(xlogx ε + xlogx (1 - ε)) / ell + +def mutualInformation {n : ℕ} (ε : ℝ) (f : Cube n → Bool) : ℝ := + (∑ b : Bool, ∑ y : Cube n, + if 0 < jointProbability ε f b y then + jointProbability ε f b y * + Real.log (jointProbability ε f b y / + (functionMarginal ε f b * observationMarginal ε f y)) + else 0) / ell + +def dictator {n : ℕ} (i : Fin n) (x : Cube n) : Bool := x i + +def complementDictator {n : ℕ} (i : Fin n) (x : Cube n) : Bool := !(x i) + +def CourtadeKumarStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → + ∀ ε : ℝ, 0 ≤ ε → ε ≤ (1 : ℝ) / 2 → + ∀ f : Cube n → Bool, mutualInformation ε f ≤ 1 - binaryEntropy ε + +def DictatorAttainmentStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → + ∀ ε : ℝ, 0 ≤ ε → ε ≤ (1 : ℝ) / 2 → + ∀ i : Fin n, + mutualInformation ε (dictator i) = 1 - binaryEntropy ε ∧ + mutualInformation ε (complementDictator i) = 1 - binaryEntropy ε + +def FullStatement : Prop := CourtadeKumarStatement ∧ DictatorAttainmentStatement + +theorem courtadeKumarAndAttainment : FullStatement := by + sorry + +end LeanBlast.CourtadeKumar + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CourtadeKumar.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LeanBlast.CourtadeKumar.courtadeKumarAndAttainment` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/courtade-kumar/solution/closure.txt b/tasks/courtade-kumar/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ec7a30d3c84c7196e5224f1367e02b01e2971990 --- /dev/null +++ b/tasks/courtade-kumar/solution/closure.txt @@ -0,0 +1,43 @@ +OAI.Combinatorics.GotsmanLinial.Model +OAI.Combinatorics.GotsmanLinial.Statement +OAI.InformationTheory.BooleanNoise.ArtanhBounds +OAI.InformationTheory.BooleanNoise.Attainment +OAI.InformationTheory.BooleanNoise.Basic +OAI.InformationTheory.BooleanNoise.Comparison +OAI.InformationTheory.BooleanNoise.ComparisonEstimates +OAI.InformationTheory.BooleanNoise.ConcavityAcrossJoin +OAI.InformationTheory.BooleanNoise.CubeSplits +OAI.InformationTheory.BooleanNoise.CubeVariance +OAI.InformationTheory.BooleanNoise.CurvatureBounds +OAI.InformationTheory.BooleanNoise.CurvatureCertificates +OAI.InformationTheory.BooleanNoise.EndpointLimits +OAI.InformationTheory.BooleanNoise.EntropyBounds +OAI.InformationTheory.BooleanNoise.EntropyScalars +OAI.InformationTheory.BooleanNoise.EntropySeries +OAI.InformationTheory.BooleanNoise.FiniteDistribution +OAI.InformationTheory.BooleanNoise.FiniteInformation +OAI.InformationTheory.BooleanNoise.FiniteNoise +OAI.InformationTheory.BooleanNoise.GeneralDissipation +OAI.InformationTheory.BooleanNoise.InformationIdentity +OAI.InformationTheory.BooleanNoise.InverseRegularity +OAI.InformationTheory.BooleanNoise.InverseScalars +OAI.InformationTheory.BooleanNoise.JensenGaps +OAI.InformationTheory.BooleanNoise.KRegularity +OAI.InformationTheory.BooleanNoise.LRegularity +OAI.InformationTheory.BooleanNoise.LShape +OAI.InformationTheory.BooleanNoise.LambdaScalars +OAI.InformationTheory.BooleanNoise.LargeCurvature +OAI.InformationTheory.BooleanNoise.Main +OAI.InformationTheory.BooleanNoise.MediumCurvature +OAI.InformationTheory.BooleanNoise.Model +OAI.InformationTheory.BooleanNoise.MonotoneDissipation +OAI.InformationTheory.BooleanNoise.NormalizedPair +OAI.InformationTheory.BooleanNoise.PairEntropy +OAI.InformationTheory.BooleanNoise.PerspectiveCalculus +OAI.InformationTheory.BooleanNoise.PerspectiveInequality +OAI.InformationTheory.BooleanNoise.PerspectiveJensen +OAI.InformationTheory.BooleanNoise.PerspectiveLogTrapezoid +OAI.InformationTheory.BooleanNoise.Rearrangement +OAI.InformationTheory.BooleanNoise.SemigroupFlow +OAI.InformationTheory.BooleanNoise.SmallCurvatureAux +OAI.InformationTheory.BooleanNoise.Statement diff --git a/tasks/courtade-kumar/solution/reference.py b/tasks/courtade-kumar/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/courtade-kumar/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/courtade-kumar/solution/solve.sh b/tasks/courtade-kumar/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..afaf63f2d4dc5f3c1ac080553faa36f1346bf5dd --- /dev/null +++ b/tasks/courtade-kumar/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CourtadeKumar, i.e. module OAI.InformationTheory.BooleanNoise.Main and the +# 43 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.BooleanNoise.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CourtadeKumar" diff --git a/tasks/courtade-kumar/task.toml b/tasks/courtade-kumar/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f22aba3dad4556442c3c3a7714a24f1565d2b38 --- /dev/null +++ b/tasks/courtade-kumar/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/courtade-kumar" +version = "1.0.0" +description = "Prove CourtadeKumar (openai/math family 119: The Courtade–Kumar and Hellinger conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CourtadeKumar.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CourtadeKumar" +family = "119" +family_title = "The Courtade–Kumar and Hellinger conjectures" +subject = "Theoretical computer science" +theorems = ["OAI.LeanBlast.CourtadeKumar.courtadeKumarAndAttainment"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.BooleanNoise.Main" +reference_modules = 43 +reference_lean_bytes = 327942 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 468 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11995 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/courtade-kumar/tests/Challenge.lean b/tasks/courtade-kumar/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..587eb586d60c195a56fe10973ef2fcf9cf737591 --- /dev/null +++ b/tasks/courtade-kumar/tests/Challenge.lean @@ -0,0 +1,76 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators + +namespace LeanBlast.GotsmanLinial + +abbrev Cube (n : ℕ) := Fin n → Bool + +end LeanBlast.GotsmanLinial + +noncomputable section + +open scoped BigOperators + +namespace LeanBlast.CourtadeKumar + +abbrev Cube (n : ℕ) := LeanBlast.GotsmanLinial.Cube n + +def cubeAverage {n : ℕ} (g : Cube n → ℝ) : ℝ := + (∑ x, g x) / (2 : ℝ) ^ n + +def ell : ℝ := Real.log 2 + +def bitFlipKernel {n : ℕ} (ε : ℝ) (x y : Cube n) : ℝ := + ∏ i, if x i = y i then 1 - ε else ε + +def jointProbability {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (b : Bool) (y : Cube n) : ℝ := + cubeAverage (fun x => if f x = b then bitFlipKernel ε x y else 0) + +def functionMarginal {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (b : Bool) : ℝ := + ∑ y, jointProbability ε f b y + +def observationMarginal {n : ℕ} (ε : ℝ) (f : Cube n → Bool) (y : Cube n) : ℝ := + ∑ b : Bool, jointProbability ε f b y + +def xlogx (t : ℝ) : ℝ := t * Real.log t + +def binaryEntropy (ε : ℝ) : ℝ := + -(xlogx ε + xlogx (1 - ε)) / ell + +def mutualInformation {n : ℕ} (ε : ℝ) (f : Cube n → Bool) : ℝ := + (∑ b : Bool, ∑ y : Cube n, + if 0 < jointProbability ε f b y then + jointProbability ε f b y * + Real.log (jointProbability ε f b y / + (functionMarginal ε f b * observationMarginal ε f y)) + else 0) / ell + +def dictator {n : ℕ} (i : Fin n) (x : Cube n) : Bool := x i + +def complementDictator {n : ℕ} (i : Fin n) (x : Cube n) : Bool := !(x i) + +def CourtadeKumarStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → + ∀ ε : ℝ, 0 ≤ ε → ε ≤ (1 : ℝ) / 2 → + ∀ f : Cube n → Bool, mutualInformation ε f ≤ 1 - binaryEntropy ε + +def DictatorAttainmentStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → + ∀ ε : ℝ, 0 ≤ ε → ε ≤ (1 : ℝ) / 2 → + ∀ i : Fin n, + mutualInformation ε (dictator i) = 1 - binaryEntropy ε ∧ + mutualInformation ε (complementDictator i) = 1 - binaryEntropy ε + +def FullStatement : Prop := CourtadeKumarStatement ∧ DictatorAttainmentStatement + +theorem courtadeKumarAndAttainment : FullStatement := by + sorry + +end LeanBlast.CourtadeKumar + +end + +end OAI diff --git a/tasks/courtade-kumar/tests/grade.py b/tasks/courtade-kumar/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/courtade-kumar/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/courtade-kumar/tests/task.json b/tasks/courtade-kumar/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..91b03d1680f1cb73624e8ab9953b00003e6c31ac --- /dev/null +++ b/tasks/courtade-kumar/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CourtadeKumar", + "comparator": { + "theorem_names": [ + "OAI.LeanBlast.CourtadeKumar.courtadeKumarAndAttainment" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11095 +} \ No newline at end of file diff --git a/tasks/courtade-kumar/tests/test.sh b/tasks/courtade-kumar/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/courtade-kumar/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/covering-density/environment/Dockerfile b/tasks/covering-density/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/covering-density/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/covering-density/environment/fetch_mathlib.sh b/tasks/covering-density/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/covering-density/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/covering-density/environment/lake-manifest.json b/tasks/covering-density/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/covering-density/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/covering-density/environment/lakefile.lean b/tasks/covering-density/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/covering-density/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/covering-density/environment/lean_setup.sh b/tasks/covering-density/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/covering-density/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/covering-density/environment/pack_submission.py b/tasks/covering-density/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/covering-density/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/covering-density/instruction.md b/tasks/covering-density/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7e185d047614fc37ea07f985753a7c67ca235527 --- /dev/null +++ b/tasks/covering-density/instruction.md @@ -0,0 +1,167 @@ +# openai/math challenge `CoveringDensity` (family 092) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 092 of the release, *The optimal order of convex-body covering density* +(Convex and metric geometry). The family as a whole: Determines the optimal worst-case covering density as $\Theta(n\log n)$, for both lattice and unrestricted translative coverings. Every convex body in $\mathbb R^n$, $n\ge2$, admits a lattice covering of density at most $Cn\log n$; centrally symmetric examples in every sufficiently large dimension require at least $cn\log n$ even without the lattice restriction, for absolute $c,C>0$. + +The challenge is `CoveringDensity`, also at `/opt/openai-math/challenges/CoveringDensity.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CoveringOrder +open Set MeasureTheory +open scoped ENNReal + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +/-- Actual discrete full-rank lattice coverings; no assumed density theorem. -/ +structure LatticeCover {n : ℕ} (K : Set (Space n)) where + lattice : Submodule ℤ (Space n) + discrete : DiscreteTopology lattice + fullrank : IsZLattice ℝ lattice + covers : ∀ y, ∃ l : lattice, y - l.val ∈ K + +noncomputable def euclideanVolume (n : ℕ) : + @Measure (EuclideanSpace ℝ (Fin n)) + (@WithLp.measurableSpace 2 (Fin n → ℝ) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace))) := + @Measure.map (Fin n → ℝ) (EuclideanSpace ℝ (Fin n)) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace)) + (@WithLp.measurableSpace 2 (Fin n → ℝ) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace))) + (@WithLp.toLp 2 (Fin n → ℝ)) + (Measure.pi (fun _ : Fin n => @volume ℝ Real.measureSpace)) + +noncomputable def euclideanCovolume {n : ℕ} + (lattice : Submodule ℤ (EuclideanSpace ℝ (Fin n))) : ℝ≥0∞ := + addCovolume lattice (EuclideanSpace ℝ (Fin n)) (euclideanVolume n) + +noncomputable def latticeDensity {n : ℕ} {K : Set (Space n)} + (cover : LatticeCover K) : ℝ≥0∞ := + euclideanVolume n K / euclideanCovolume cover.lattice + +noncomputable def thetaL {n : ℕ} (K : Set (EuclideanSpace ℝ (Fin n))) : ℝ≥0∞ := + ⨅ cover : LatticeCover K, latticeDensity cover + +end CoveringOrder + +namespace TranslativeCovering + +open Set Filter MeasureTheory +open scoped ENNReal + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def cube (n : ℕ) (R : ℝ) : Set (Space n) := + {x | ∀ i, -R ≤ x i ∧ x i ≤ R} + +def LocallyFiniteCenters {n : ℕ} (X : Set (Space n)) : Prop := + ∀ B : Set (Space n), Bornology.IsBounded B → (X ∩ B).Finite + +def Covers {n : ℕ} (K X : Set (Space n)) : Prop := + ∀ y, ∃ x ∈ X, y - x ∈ K + +def ConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def CentrallySymmetric {n : ℕ} (K : Set (Space n)) : Prop := + ∃ z, ∀ x, x ∈ K ↔ (2 : ℝ) • z - x ∈ K + +noncomputable def upperCenterIntensity {n : ℕ} (X : Set (Space n)) : ℝ≥0∞ := + Filter.limsup (fun R : ℝ => + (↑(X ∩ cube n R).ncard : ℝ≥0∞) / ENNReal.ofReal ((2 * R) ^ n)) atTop + +noncomputable def thetaT {n : ℕ} (K : Set (Space n)) : ℝ≥0∞ := + ⨅ X : {X : Set (Space n) // LocallyFiniteCenters X ∧ Covers K X}, + volume K * upperCenterIntensity X.val + +end TranslativeCovering + +namespace CoveringOrder +open Set MeasureTheory +open scoped ENNReal + +abbrev Body (n : ℕ) := {K : Set (Space n) // TranslativeCovering.ConvexBody K} +abbrev SymmetricBody (n : ℕ) := + {K : Body n // TranslativeCovering.CentrallySymmetric K.val} + +noncomputable def translativeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : Body n, TranslativeCovering.thetaT K.val + +noncomputable def symmetricTranslativeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : SymmetricBody n, TranslativeCovering.thetaT K.val.val + +noncomputable def latticeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : Body n, thetaL K.val + +noncomputable def symmetricLatticeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : SymmetricBody n, thetaL K.val.val + +/-- The finite real comparison scale, viewed in extended nonnegative reals. -/ +def orderBounds (c C : ℝ) (n : ℕ) (a : ℝ≥0∞) : Prop := + ENNReal.ofReal (c * (n : ℝ) * Real.log (n : ℝ)) ≤ a ∧ + a ≤ ENNReal.ofReal (C * (n : ℝ) * Real.log (n : ℝ)) + +/-- All four extremal quantities have common +absolute positive comparison constants. ENNReal bounds imply finiteness rather +than mapping a potentially infinite density to zero through `toReal`. -/ +def OptimalOrder : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → + orderBounds c C n (translativeSup n) ∧ + orderBounds c C n (symmetricTranslativeSup n) ∧ + orderBounds c C n (latticeSup n) ∧ + orderBounds c C n (symmetricLatticeSup n) + +end CoveringOrder + +/-- Translative and lattice covering densities over all convex bodies and over +centrally symmetric convex bodies have the same asymptotic order. -/ +theorem CoveringOrder.optimal_order : CoveringOrder.OptimalOrder := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CoveringDensity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CoveringOrder.optimal_order` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/covering-density/solution/closure.txt b/tasks/covering-density/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3c381856ea1f5f8eeb47b0d2c7c243d0bcb05046 --- /dev/null +++ b/tasks/covering-density/solution/closure.txt @@ -0,0 +1,143 @@ +OAI.Geometry.CoveringDensity.EuclideanTransport +OAI.Geometry.CoveringDensity.Main +OAI.Geometry.CoveringDensity.Model +OAI.Geometry.LatticeCovering.Assembly +OAI.Geometry.LatticeCovering.Bits +OAI.Geometry.LatticeCovering.BrokenCircuits +OAI.Geometry.LatticeCovering.Chains +OAI.Geometry.LatticeCovering.CircuitErrors +OAI.Geometry.LatticeCovering.CircuitLattices +OAI.Geometry.LatticeCovering.CircuitSums +OAI.Geometry.LatticeCovering.CircuitVolumes +OAI.Geometry.LatticeCovering.Completion +OAI.Geometry.LatticeCovering.Concentration +OAI.Geometry.LatticeCovering.Covering +OAI.Geometry.LatticeCovering.Desmoothing +OAI.Geometry.LatticeCovering.Folded +OAI.Geometry.LatticeCovering.GaussianMoments +OAI.Geometry.LatticeCovering.GaussianPositions +OAI.Geometry.LatticeCovering.GaussianRates +OAI.Geometry.LatticeCovering.GaussianSections +OAI.Geometry.LatticeCovering.GaussianSmoothing +OAI.Geometry.LatticeCovering.GridCounts +OAI.Geometry.LatticeCovering.Horizontal +OAI.Geometry.LatticeCovering.Isotropy +OAI.Geometry.LatticeCovering.Lines +OAI.Geometry.LatticeCovering.LogConcavity +OAI.Geometry.LatticeCovering.Main +OAI.Geometry.LatticeCovering.Marginals +OAI.Geometry.LatticeCovering.MeanHoles +OAI.Geometry.LatticeCovering.Model +OAI.Geometry.LatticeCovering.Patterns +OAI.Geometry.LatticeCovering.PrimeGrids +OAI.Geometry.LatticeCovering.PrimeKernels +OAI.Geometry.LatticeCovering.Products +OAI.Geometry.LatticeCovering.ProjectionBounds +OAI.Geometry.LatticeCovering.RadialBounds +OAI.Geometry.LatticeCovering.Rates +OAI.Geometry.LatticeCovering.Residuals +OAI.Geometry.LatticeCovering.Rounding +OAI.Geometry.LatticeCovering.Sampling +OAI.Geometry.LatticeCovering.SamplingBounds +OAI.Geometry.LatticeCovering.Sections +OAI.Geometry.LatticeCovering.Shears +OAI.Geometry.LatticeCovering.Transport +OAI.Geometry.TranslativeCovering.ActivityBins +OAI.Geometry.TranslativeCovering.AllLatticeExclusion +OAI.Geometry.TranslativeCovering.BinSelection +OAI.Geometry.TranslativeCovering.BinnedTail +OAI.Geometry.TranslativeCovering.BlockCount +OAI.Geometry.TranslativeCovering.BlockDimension +OAI.Geometry.TranslativeCovering.BlockGeometry +OAI.Geometry.TranslativeCovering.BlockRow +OAI.Geometry.TranslativeCovering.BlockSets +OAI.Geometry.TranslativeCovering.BlockTerminal +OAI.Geometry.TranslativeCovering.BlockWeightMeasure +OAI.Geometry.TranslativeCovering.BlockWeights +OAI.Geometry.TranslativeCovering.Blocks +OAI.Geometry.TranslativeCovering.BodySelection +OAI.Geometry.TranslativeCovering.BodyVolume +OAI.Geometry.TranslativeCovering.CapAffinity +OAI.Geometry.TranslativeCovering.CapCost +OAI.Geometry.TranslativeCovering.CapDisjoint +OAI.Geometry.TranslativeCovering.CapGeometry +OAI.Geometry.TranslativeCovering.CapLens +OAI.Geometry.TranslativeCovering.CapOverlap +OAI.Geometry.TranslativeCovering.CellCounts +OAI.Geometry.TranslativeCovering.CellMatching +OAI.Geometry.TranslativeCovering.ConeStretch +OAI.Geometry.TranslativeCovering.CoveringAsymptotics +OAI.Geometry.TranslativeCovering.CoveringGrowth +OAI.Geometry.TranslativeCovering.CrossDeployment +OAI.Geometry.TranslativeCovering.CrossDiagram +OAI.Geometry.TranslativeCovering.CrossSlots +OAI.Geometry.TranslativeCovering.CubicLattice +OAI.Geometry.TranslativeCovering.CylinderAngle +OAI.Geometry.TranslativeCovering.CylinderProbability +OAI.Geometry.TranslativeCovering.CylinderVolume +OAI.Geometry.TranslativeCovering.DecayNormalization +OAI.Geometry.TranslativeCovering.DiagramActivity +OAI.Geometry.TranslativeCovering.DiagramCrossBounds +OAI.Geometry.TranslativeCovering.DiagramSelfBounds +OAI.Geometry.TranslativeCovering.DistinctCosets +OAI.Geometry.TranslativeCovering.EntropyRates +OAI.Geometry.TranslativeCovering.FiniteJanson +OAI.Geometry.TranslativeCovering.GeometryDimension +OAI.Geometry.TranslativeCovering.JansonSampling +OAI.Geometry.TranslativeCovering.LatticeAveraging +OAI.Geometry.TranslativeCovering.LensDeployment +OAI.Geometry.TranslativeCovering.LensQuantitative +OAI.Geometry.TranslativeCovering.LocalizationComplete +OAI.Geometry.TranslativeCovering.LocalizationGood +OAI.Geometry.TranslativeCovering.LocalizationMeans +OAI.Geometry.TranslativeCovering.LocalizationRates +OAI.Geometry.TranslativeCovering.LocalizationRounding +OAI.Geometry.TranslativeCovering.LocalizationWindow +OAI.Geometry.TranslativeCovering.Main +OAI.Geometry.TranslativeCovering.MatchingAlgebra +OAI.Geometry.TranslativeCovering.MatchingBounds +OAI.Geometry.TranslativeCovering.MatchingSelf +OAI.Geometry.TranslativeCovering.MeasureCut +OAI.Geometry.TranslativeCovering.NormalizedCaps +OAI.Geometry.TranslativeCovering.NumericTail +OAI.Geometry.TranslativeCovering.PatternCross +OAI.Geometry.TranslativeCovering.PatternEnumeration +OAI.Geometry.TranslativeCovering.PatternGeometry +OAI.Geometry.TranslativeCovering.PatternRounding +OAI.Geometry.TranslativeCovering.PatternTail +OAI.Geometry.TranslativeCovering.PatternWitness +OAI.Geometry.TranslativeCovering.PeriodicDensity +OAI.Geometry.TranslativeCovering.PeriodicEquality +OAI.Geometry.TranslativeCovering.Periodization +OAI.Geometry.TranslativeCovering.PoissonActualBound +OAI.Geometry.TranslativeCovering.PoissonBinned +OAI.Geometry.TranslativeCovering.PoissonCells +OAI.Geometry.TranslativeCovering.PoissonConfig +OAI.Geometry.TranslativeCovering.PoissonDiagrams +OAI.Geometry.TranslativeCovering.PoissonFinite +OAI.Geometry.TranslativeCovering.PoissonLimit +OAI.Geometry.TranslativeCovering.PoissonMeasureCells +OAI.Geometry.TranslativeCovering.PoissonRealization +OAI.Geometry.TranslativeCovering.PoissonSample +OAI.Geometry.TranslativeCovering.ProjectiveCaps +OAI.Geometry.TranslativeCovering.RadialCost +OAI.Geometry.TranslativeCovering.RadialIntegral +OAI.Geometry.TranslativeCovering.RadialShell +OAI.Geometry.TranslativeCovering.RadiusLens +OAI.Geometry.TranslativeCovering.RandomBody +OAI.Geometry.TranslativeCovering.ResidualCaps +OAI.Geometry.TranslativeCovering.RowGrouping +OAI.Geometry.TranslativeCovering.ShellCaps +OAI.Geometry.TranslativeCovering.SlotGeometry +OAI.Geometry.TranslativeCovering.SourceLocalization +OAI.Geometry.TranslativeCovering.SourceParameters +OAI.Geometry.TranslativeCovering.SourcePatternTail +OAI.Geometry.TranslativeCovering.SourceScale +OAI.Geometry.TranslativeCovering.SphericalBlocks +OAI.Geometry.TranslativeCovering.SphericalLaw +OAI.Geometry.TranslativeCovering.TailComparison +OAI.Geometry.TranslativeCovering.TargetGeometry +OAI.Geometry.TranslativeCovering.TargetSampling +OAI.Geometry.TranslativeCovering.WeightedVolume +OAI.Geometry.TranslativeCovering.WitnessBlocks +OAI.Geometry.TranslativeCovering.WitnessConstruction diff --git a/tasks/covering-density/solution/reference.py b/tasks/covering-density/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/covering-density/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/covering-density/solution/solve.sh b/tasks/covering-density/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..99e9288d07beea99141ae578a837558c5ed38fc3 --- /dev/null +++ b/tasks/covering-density/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CoveringDensity, i.e. module OAI.Geometry.CoveringDensity.Main and the +# 143 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.CoveringDensity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CoveringDensity" diff --git a/tasks/covering-density/task.toml b/tasks/covering-density/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..03293f4c5c41c2f3f6c9a70ba4c01e20bf027278 --- /dev/null +++ b/tasks/covering-density/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/covering-density" +version = "1.0.0" +description = "Prove CoveringDensity (openai/math family 092: The optimal order of convex-body covering density) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CoveringDensity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CoveringDensity" +family = "092" +family_title = "The optimal order of convex-body covering density" +subject = "Convex and metric geometry" +theorems = ["OAI.CoveringOrder.optimal_order"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.CoveringDensity.Main" +reference_modules = 143 +reference_lean_bytes = 1760761 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1458 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13284 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/covering-density/tests/Challenge.lean b/tasks/covering-density/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..470f7f583332d9ae68bcc33f4b381bbb95201ff0 --- /dev/null +++ b/tasks/covering-density/tests/Challenge.lean @@ -0,0 +1,116 @@ +import Mathlib + +namespace OAI + +namespace CoveringOrder +open Set MeasureTheory +open scoped ENNReal + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +/-- Actual discrete full-rank lattice coverings; no assumed density theorem. -/ +structure LatticeCover {n : ℕ} (K : Set (Space n)) where + lattice : Submodule ℤ (Space n) + discrete : DiscreteTopology lattice + fullrank : IsZLattice ℝ lattice + covers : ∀ y, ∃ l : lattice, y - l.val ∈ K + +noncomputable def euclideanVolume (n : ℕ) : + @Measure (EuclideanSpace ℝ (Fin n)) + (@WithLp.measurableSpace 2 (Fin n → ℝ) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace))) := + @Measure.map (Fin n → ℝ) (EuclideanSpace ℝ (Fin n)) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace)) + (@WithLp.measurableSpace 2 (Fin n → ℝ) + (@MeasurableSpace.pi (Fin n) (fun _ => ℝ) (fun _ => Real.measurableSpace))) + (@WithLp.toLp 2 (Fin n → ℝ)) + (Measure.pi (fun _ : Fin n => @volume ℝ Real.measureSpace)) + +noncomputable def euclideanCovolume {n : ℕ} + (lattice : Submodule ℤ (EuclideanSpace ℝ (Fin n))) : ℝ≥0∞ := + addCovolume lattice (EuclideanSpace ℝ (Fin n)) (euclideanVolume n) + +noncomputable def latticeDensity {n : ℕ} {K : Set (Space n)} + (cover : LatticeCover K) : ℝ≥0∞ := + euclideanVolume n K / euclideanCovolume cover.lattice + +noncomputable def thetaL {n : ℕ} (K : Set (EuclideanSpace ℝ (Fin n))) : ℝ≥0∞ := + ⨅ cover : LatticeCover K, latticeDensity cover + +end CoveringOrder + +namespace TranslativeCovering + +open Set Filter MeasureTheory +open scoped ENNReal + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def cube (n : ℕ) (R : ℝ) : Set (Space n) := + {x | ∀ i, -R ≤ x i ∧ x i ≤ R} + +def LocallyFiniteCenters {n : ℕ} (X : Set (Space n)) : Prop := + ∀ B : Set (Space n), Bornology.IsBounded B → (X ∩ B).Finite + +def Covers {n : ℕ} (K X : Set (Space n)) : Prop := + ∀ y, ∃ x ∈ X, y - x ∈ K + +def ConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def CentrallySymmetric {n : ℕ} (K : Set (Space n)) : Prop := + ∃ z, ∀ x, x ∈ K ↔ (2 : ℝ) • z - x ∈ K + +noncomputable def upperCenterIntensity {n : ℕ} (X : Set (Space n)) : ℝ≥0∞ := + Filter.limsup (fun R : ℝ => + (↑(X ∩ cube n R).ncard : ℝ≥0∞) / ENNReal.ofReal ((2 * R) ^ n)) atTop + +noncomputable def thetaT {n : ℕ} (K : Set (Space n)) : ℝ≥0∞ := + ⨅ X : {X : Set (Space n) // LocallyFiniteCenters X ∧ Covers K X}, + volume K * upperCenterIntensity X.val + +end TranslativeCovering + +namespace CoveringOrder +open Set MeasureTheory +open scoped ENNReal + +abbrev Body (n : ℕ) := {K : Set (Space n) // TranslativeCovering.ConvexBody K} +abbrev SymmetricBody (n : ℕ) := + {K : Body n // TranslativeCovering.CentrallySymmetric K.val} + +noncomputable def translativeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : Body n, TranslativeCovering.thetaT K.val + +noncomputable def symmetricTranslativeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : SymmetricBody n, TranslativeCovering.thetaT K.val.val + +noncomputable def latticeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : Body n, thetaL K.val + +noncomputable def symmetricLatticeSup (n : ℕ) : ℝ≥0∞ := + ⨆ K : SymmetricBody n, thetaL K.val.val + +/-- The finite real comparison scale, viewed in extended nonnegative reals. -/ +def orderBounds (c C : ℝ) (n : ℕ) (a : ℝ≥0∞) : Prop := + ENNReal.ofReal (c * (n : ℝ) * Real.log (n : ℝ)) ≤ a ∧ + a ≤ ENNReal.ofReal (C * (n : ℝ) * Real.log (n : ℝ)) + +/-- All four extremal quantities have common +absolute positive comparison constants. ENNReal bounds imply finiteness rather +than mapping a potentially infinite density to zero through `toReal`. -/ +def OptimalOrder : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → + orderBounds c C n (translativeSup n) ∧ + orderBounds c C n (symmetricTranslativeSup n) ∧ + orderBounds c C n (latticeSup n) ∧ + orderBounds c C n (symmetricLatticeSup n) + +end CoveringOrder + +/-- Translative and lattice covering densities over all convex bodies and over +centrally symmetric convex bodies have the same asymptotic order. -/ +theorem CoveringOrder.optimal_order : CoveringOrder.OptimalOrder := by + sorry + +end OAI diff --git a/tasks/covering-density/tests/grade.py b/tasks/covering-density/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/covering-density/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/covering-density/tests/task.json b/tasks/covering-density/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fa9aba5e90ab522bc34e3291a4ec21993042ada8 --- /dev/null +++ b/tasks/covering-density/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CoveringDensity", + "comparator": { + "theorem_names": [ + "OAI.CoveringOrder.optimal_order" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12384 +} \ No newline at end of file diff --git a/tasks/covering-density/tests/test.sh b/tasks/covering-density/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/covering-density/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/critical-percolation/environment/Dockerfile b/tasks/critical-percolation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/critical-percolation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/critical-percolation/environment/fetch_mathlib.sh b/tasks/critical-percolation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/critical-percolation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/critical-percolation/environment/lake-manifest.json b/tasks/critical-percolation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/critical-percolation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/critical-percolation/environment/lakefile.lean b/tasks/critical-percolation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/critical-percolation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/critical-percolation/environment/lean_setup.sh b/tasks/critical-percolation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/critical-percolation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/critical-percolation/environment/pack_submission.py b/tasks/critical-percolation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/critical-percolation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/critical-percolation/instruction.md b/tasks/critical-percolation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c1f8e701ea4205ca801cca45fa5fb9816a4610ef --- /dev/null +++ b/tasks/critical-percolation/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `CriticalPercolation` (family 213) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 213 of the release, *No infinite critical clusters on quasi-transitive graphs* +(Probability and statistical mechanics). The family as a whole: Resolves the Benjamini–Schramm criticality conjecture for bond percolation on every infinite connected locally finite quasi-transitive graph with $p_c<1$: at the critical probability, there is almost surely no infinite cluster. The family also establishes this conclusion for both nearest-neighbor bond and site percolation on $\mathbb Z^3$. + +The challenge is `CriticalPercolation`, also at `/opt/openai-math/challenges/CriticalPercolation.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set MeasureTheory ProbabilityTheory + +namespace CriticalPercolation + +/-- An undirected graph with labelled bonds, including loops and parallel bonds. -/ +structure BondGraph (V E : Type*) where + ends : E → Sym2 V + +namespace BondGraph +variable {V E : Type*} (G : BondGraph V E) + +/-- The graph of retained bonds. `fromEdgeSet` discards loops. -/ +def openGraph (ω : Set E) : SimpleGraph V := + SimpleGraph.fromEdgeSet (G.ends '' ω) + +/-- The underlying connectivity graph with every bond retained. -/ +def fullGraph : SimpleGraph V := G.openGraph Set.univ + +/-- Local finiteness counts bonds, not just distinct neighbors. -/ +def LocallyFinite : Prop := ∀ v : V, {e : E | v ∈ G.ends e}.Finite + +/-- Automorphisms preserve the vertex and bond structure, including multiplicities. -/ +structure Aut where + vertex : V ≃ V + edge : E ≃ E + preserves : ∀ e, G.ends (edge e) = Sym2.map vertex (G.ends e) + +/-- Finitely many vertex orbits under the full automorphism group. -/ +def QuasiTransitive : Prop := + ∃ S : Set V, S.Finite ∧ ∀ v : V, ∃ s ∈ S, ∃ φ : G.Aut, φ.vertex s = v + +/-- Finite open paths, including the path of length zero, define the open cluster. -/ +def cluster (ω : Set E) (v : V) : Set V := {w | (G.openGraph ω).Reachable v w} + +/-- The event that at least one open cluster is infinite. -/ +def percolates : Set (Set E) := {ω | ∃ v : V, (G.cluster ω v).Infinite} + +/-- Independent retention with parameter `p ∈ [0,1]` of each labelled bond. -/ +noncomputable def law (_G : BondGraph V E) (p : unitInterval) : Measure (Set E) := + ProbabilityTheory.setBernoulli Set.univ p + +/-- The infimum of parameters with positive probability of an infinite cluster. -/ +noncomputable def criticalProbability : unitInterval := + sInf {p : unitInterval | 0 < G.law p G.percolates} + +/-- Critical Bernoulli bond percolation has no infinite cluster when the critical +probability is below one. -/ +theorem no_percolation_at_criticality [Infinite V] + (hconnected : G.fullGraph.Connected) + (hlocal : G.LocallyFinite) + (hquasi : G.QuasiTransitive) + (hpc : G.criticalProbability < 1) : + G.law G.criticalProbability G.percolates = 0 := by + sorry + +end BondGraph +end CriticalPercolation + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CriticalPercolation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CriticalPercolation.BondGraph.no_percolation_at_criticality` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/critical-percolation/solution/closure.txt b/tasks/critical-percolation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bec9199c6f90c88df9b0cecb60e35b4cf5953376 --- /dev/null +++ b/tasks/critical-percolation/solution/closure.txt @@ -0,0 +1,627 @@ +OAI.Probability.CriticalPercolation.Classification.AlgebraicDescent +OAI.Probability.CriticalPercolation.Classification.ClassificationProducerBoundary +OAI.Probability.CriticalPercolation.Classification.CompactQuotientProper +OAI.Probability.CriticalPercolation.Classification.ConcreteStructureAssembly +OAI.Probability.CriticalPercolation.Classification.DiscreteWeakGromovBridge +OAI.Probability.CriticalPercolation.Classification.FaithfulOrbitalModel +OAI.Probability.CriticalPercolation.Classification.FiniteBGTBridge +OAI.Probability.CriticalPercolation.Classification.FiniteClassificationObstruction +OAI.Probability.CriticalPercolation.Classification.GraphCompactNormalClassification +OAI.Probability.CriticalPercolation.Classification.QualitativeClassificationBoundary +OAI.Probability.CriticalPercolation.Classification.RawClassificationBoundary +OAI.Probability.CriticalPercolation.Classification.RelativeClassification +OAI.Probability.CriticalPercolation.Classification.RestrictedQuotient +OAI.Probability.CriticalPercolation.Classification.StructuredCoordinates +OAI.Probability.CriticalPercolation.Classification.WeakGromovMainBoundary +OAI.Probability.CriticalPercolation.Clusters.ClusterCountFlip +OAI.Probability.CriticalPercolation.Clusters.ClusterNumber +OAI.Probability.CriticalPercolation.Clusters.ClusterObject +OAI.Probability.CriticalPercolation.Clusters.ClusterObjectAvoidanceCross +OAI.Probability.CriticalPercolation.Clusters.ClusterTail +OAI.Probability.CriticalPercolation.Clusters.ClusterUpdate +OAI.Probability.CriticalPercolation.Clusters.ComponentSelf +OAI.Probability.CriticalPercolation.Clusters.CriticalClusterMultiplicity +OAI.Probability.CriticalPercolation.Clusters.DeleteBot +OAI.Probability.CriticalPercolation.Clusters.Earlier +OAI.Probability.CriticalPercolation.Clusters.ExpectedCluster +OAI.Probability.CriticalPercolation.Clusters.FiniteClusterCover +OAI.Probability.CriticalPercolation.Clusters.FiniteForcing +OAI.Probability.CriticalPercolation.Clusters.ForcedDisconnectContinuity +OAI.Probability.CriticalPercolation.Clusters.GraphErgodicity +OAI.Probability.CriticalPercolation.Clusters.HitOthers +OAI.Probability.CriticalPercolation.Clusters.HitValue +OAI.Probability.CriticalPercolation.Clusters.InfiniteUniqueness +OAI.Probability.CriticalPercolation.Clusters.InfiniteUniquenessGeometry +OAI.Probability.CriticalPercolation.Clusters.PercolationTail +OAI.Probability.CriticalPercolation.Clusters.ThreeClusterAvoidanceGeneral +OAI.Probability.CriticalPercolation.Clusters.ThreeClusterAvoidanceSecond +OAI.Probability.CriticalPercolation.Criticality.ActualGrowth +OAI.Probability.CriticalPercolation.Criticality.AutDisplacement +OAI.Probability.CriticalPercolation.Criticality.BalancedCycles +OAI.Probability.CriticalPercolation.Criticality.BandScale +OAI.Probability.CriticalPercolation.Criticality.BlockIndependence +OAI.Probability.CriticalPercolation.Criticality.BlockLocalization +OAI.Probability.CriticalPercolation.Criticality.BoundaryCount +OAI.Probability.CriticalPercolation.Criticality.BoundedNormalJoins +OAI.Probability.CriticalPercolation.Criticality.ClassTwoRankOne +OAI.Probability.CriticalPercolation.Criticality.ClosedBoundedCuts +OAI.Probability.CriticalPercolation.Criticality.CompactDiscreteQuotient +OAI.Probability.CriticalPercolation.Criticality.ComponentCritical +OAI.Probability.CriticalPercolation.Criticality.ContractingDomains +OAI.Probability.CriticalPercolation.Criticality.CriticalFragility +OAI.Probability.CriticalPercolation.Criticality.CutInside +OAI.Probability.CriticalPercolation.Criticality.CylinderApproximation +OAI.Probability.CriticalPercolation.Criticality.DeleteImageIso +OAI.Probability.CriticalPercolation.Criticality.DescendingFan +OAI.Probability.CriticalPercolation.Criticality.DescentCritical +OAI.Probability.CriticalPercolation.Criticality.DirectionalTail +OAI.Probability.CriticalPercolation.Criticality.DiskWinding +OAI.Probability.CriticalPercolation.Criticality.DomainPercolation +OAI.Probability.CriticalPercolation.Criticality.DyadicBound +OAI.Probability.CriticalPercolation.Criticality.ExhaustionEvents +OAI.Probability.CriticalPercolation.Criticality.ExpandingCharacterGrowth +OAI.Probability.CriticalPercolation.Criticality.FavoredFinite +OAI.Probability.CriticalPercolation.Criticality.FewOpenBonds +OAI.Probability.CriticalPercolation.Criticality.FiniteEdgeInterpolation +OAI.Probability.CriticalPercolation.Criticality.FiniteEnergy +OAI.Probability.CriticalPercolation.Criticality.FiniteInterpolation +OAI.Probability.CriticalPercolation.Criticality.FiniteInterpolationUniform +OAI.Probability.CriticalPercolation.Criticality.FiniteNearbyPair +OAI.Probability.CriticalPercolation.Criticality.FiniteSeedTree +OAI.Probability.CriticalPercolation.Criticality.FiniteSusceptibility +OAI.Probability.CriticalPercolation.Criticality.FourthMomentFatou +OAI.Probability.CriticalPercolation.Criticality.GeometricFourth +OAI.Probability.CriticalPercolation.Criticality.GrowthAlternatives +OAI.Probability.CriticalPercolation.Criticality.GrowthEstimate +OAI.Probability.CriticalPercolation.Criticality.GrowthProcess +OAI.Probability.CriticalPercolation.Criticality.HeightCuts +OAI.Probability.CriticalPercolation.Criticality.IndicableDegreeStep +OAI.Probability.CriticalPercolation.Criticality.InfiniteEscapeLowerBound +OAI.Probability.CriticalPercolation.Criticality.InfiniteInterpolation +OAI.Probability.CriticalPercolation.Criticality.InfiniteNearbyPair +OAI.Probability.CriticalPercolation.Criticality.IntegerBoxes +OAI.Probability.CriticalPercolation.Criticality.InterpolationUniform +OAI.Probability.CriticalPercolation.Criticality.IntrinsicCriticalFragility +OAI.Probability.CriticalPercolation.Criticality.InvariantFiniteSets +OAI.Probability.CriticalPercolation.Criticality.LayerContradiction +OAI.Probability.CriticalPercolation.Criticality.LayerCounting +OAI.Probability.CriticalPercolation.Criticality.LayerLocality +OAI.Probability.CriticalPercolation.Criticality.Leak +OAI.Probability.CriticalPercolation.Criticality.LocalDescendingBlock +OAI.Probability.CriticalPercolation.Criticality.MainResidualBoundary +OAI.Probability.CriticalPercolation.Criticality.MainSparseBoundary +OAI.Probability.CriticalPercolation.Criticality.MinimalInterpolation +OAI.Probability.CriticalPercolation.Criticality.MinimalPair +OAI.Probability.CriticalPercolation.Criticality.NestedLayerBlock +OAI.Probability.CriticalPercolation.Criticality.NormalClosureGrowth +OAI.Probability.CriticalPercolation.Criticality.OneDimensionalCritical +OAI.Probability.CriticalPercolation.Criticality.OpenRay +OAI.Probability.CriticalPercolation.Criticality.PairedSparseScales +OAI.Probability.CriticalPercolation.Criticality.ParameterLeftBounds +OAI.Probability.CriticalPercolation.Criticality.PositiveCritical +OAI.Probability.CriticalPercolation.Criticality.RestrictedInterpolation +OAI.Probability.CriticalPercolation.Criticality.RestrictedSeed +OAI.Probability.CriticalPercolation.Criticality.ReverseReference +OAI.Probability.CriticalPercolation.Criticality.SharpnessPhi +OAI.Probability.CriticalPercolation.Criticality.SignedCountIdentity +OAI.Probability.CriticalPercolation.Criticality.SparseLinearCritical +OAI.Probability.CriticalPercolation.Criticality.SpecifiedFailures +OAI.Probability.CriticalPercolation.Criticality.SquareBoundary +OAI.Probability.CriticalPercolation.Criticality.SubcriticalLocalRateBound +OAI.Probability.CriticalPercolation.Criticality.SubexponentialVolumes +OAI.Probability.CriticalPercolation.Criticality.SubgroupFiniteIndexExtension +OAI.Probability.CriticalPercolation.Criticality.TwoPoint +OAI.Probability.CriticalPercolation.Criticality.TwoPointSelf +OAI.Probability.CriticalPercolation.Criticality.UniformDescendingFan +OAI.Probability.CriticalPercolation.Criticality.UniformLocalContinuity +OAI.Probability.CriticalPercolation.Criticality.VirtualIndicability +OAI.Probability.CriticalPercolation.Criticality.Weight +OAI.Probability.CriticalPercolation.Criticality.WitnessEvents +OAI.Probability.CriticalPercolation.Entropy.AeEvalNe +OAI.Probability.CriticalPercolation.Entropy.BinaryConfiguration +OAI.Probability.CriticalPercolation.Entropy.BinaryCostBound +OAI.Probability.CriticalPercolation.Entropy.BinaryCosts +OAI.Probability.CriticalPercolation.Entropy.BinaryDescriptor +OAI.Probability.CriticalPercolation.Entropy.BinaryEventBound +OAI.Probability.CriticalPercolation.Entropy.BinaryForest +OAI.Probability.CriticalPercolation.Entropy.BinaryInterpolation +OAI.Probability.CriticalPercolation.Entropy.BinaryInverseCost +OAI.Probability.CriticalPercolation.Entropy.BinaryLaw +OAI.Probability.CriticalPercolation.Entropy.BinaryLikelihood +OAI.Probability.CriticalPercolation.Entropy.BinaryMarks +OAI.Probability.CriticalPercolation.Entropy.BinaryOutput +OAI.Probability.CriticalPercolation.Entropy.BinaryOutputEntropy +OAI.Probability.CriticalPercolation.Entropy.BinaryPairs +OAI.Probability.CriticalPercolation.Entropy.BinaryParents +OAI.Probability.CriticalPercolation.Entropy.BinaryPrefix +OAI.Probability.CriticalPercolation.Entropy.BinaryRaw +OAI.Probability.CriticalPercolation.Entropy.BinaryReferenceLikelihood +OAI.Probability.CriticalPercolation.Entropy.BinaryReverseKernels +OAI.Probability.CriticalPercolation.Entropy.BinaryReversePrices +OAI.Probability.CriticalPercolation.Entropy.BinaryStages +OAI.Probability.CriticalPercolation.Entropy.BinarySupport +OAI.Probability.CriticalPercolation.Entropy.BinarySwitches +OAI.Probability.CriticalPercolation.Entropy.BinaryTranscript +OAI.Probability.CriticalPercolation.Entropy.BinaryWords +OAI.Probability.CriticalPercolation.Entropy.Divergence +OAI.Probability.CriticalPercolation.Entropy.EndpointKernel +OAI.Probability.CriticalPercolation.Entropy.FiberValue +OAI.Probability.CriticalPercolation.Entropy.FiniteEventEntropy +OAI.Probability.CriticalPercolation.Entropy.FreshSet +OAI.Probability.CriticalPercolation.Entropy.MarkedBits +OAI.Probability.CriticalPercolation.Entropy.MarkedEntropy +OAI.Probability.CriticalPercolation.Entropy.MulLogDivScaled +OAI.Probability.CriticalPercolation.Entropy.RecursiveLikelihood +OAI.Probability.CriticalPercolation.Entropy.ReverseGuess +OAI.Probability.CriticalPercolation.Entropy.Uniform01 +OAI.Probability.CriticalPercolation.Exploration.AdaptiveReveal +OAI.Probability.CriticalPercolation.Exploration.AncestryForest +OAI.Probability.CriticalPercolation.Exploration.BallIncidence +OAI.Probability.CriticalPercolation.Exploration.BitWeight +OAI.Probability.CriticalPercolation.Exploration.ClosedFresh +OAI.Probability.CriticalPercolation.Exploration.ClosedPivotWeight +OAI.Probability.CriticalPercolation.Exploration.ClusterUsers +OAI.Probability.CriticalPercolation.Exploration.CompileContactPrefixCongr +OAI.Probability.CriticalPercolation.Exploration.CompileContactScoreErase +OAI.Probability.CriticalPercolation.Exploration.CompileEmptyReads +OAI.Probability.CriticalPercolation.Exploration.CompileStop +OAI.Probability.CriticalPercolation.Exploration.DecisionHistory +OAI.Probability.CriticalPercolation.Exploration.Exhaustive +OAI.Probability.CriticalPercolation.Exploration.FrontierDivergence +OAI.Probability.CriticalPercolation.Exploration.GlobalNode +OAI.Probability.CriticalPercolation.Exploration.GrowthHistoryGeometry +OAI.Probability.CriticalPercolation.Exploration.IncidenceDegree +OAI.Probability.CriticalPercolation.Exploration.IncidenceIdentity +OAI.Probability.CriticalPercolation.Exploration.IncidenceSearch +OAI.Probability.CriticalPercolation.Exploration.Initial +OAI.Probability.CriticalPercolation.Exploration.Initial2 +OAI.Probability.CriticalPercolation.Exploration.LayerExposure +OAI.Probability.CriticalPercolation.Exploration.ListScore +OAI.Probability.CriticalPercolation.Exploration.LocalNode +OAI.Probability.CriticalPercolation.Exploration.Node +OAI.Probability.CriticalPercolation.Exploration.OpenFrontierDivergence +OAI.Probability.CriticalPercolation.Exploration.PhaseFrontier +OAI.Probability.CriticalPercolation.Exploration.PivotalComparison +OAI.Probability.CriticalPercolation.Exploration.PrefixScoreNonneg +OAI.Probability.CriticalPercolation.Exploration.PrefixState +OAI.Probability.CriticalPercolation.Exploration.QueryBand +OAI.Probability.CriticalPercolation.Exploration.QueryDelta +OAI.Probability.CriticalPercolation.Exploration.QueryGeometry +OAI.Probability.CriticalPercolation.Exploration.QueryNormalized +OAI.Probability.CriticalPercolation.Exploration.QueryTree +OAI.Probability.CriticalPercolation.Exploration.ReachableIncidenceImp +OAI.Probability.CriticalPercolation.Exploration.ReachableMemPhaseClosed +OAI.Probability.CriticalPercolation.Exploration.Score +OAI.Probability.CriticalPercolation.Exploration.ScoreCongrSupport +OAI.Probability.CriticalPercolation.Exploration.ScoreMeanStep +OAI.Probability.CriticalPercolation.Exploration.SearchContactMoments +OAI.Probability.CriticalPercolation.Exploration.SearchMarkedContactBound +OAI.Probability.CriticalPercolation.Exploration.SearchTree +OAI.Probability.CriticalPercolation.Exploration.Select +OAI.Probability.CriticalPercolation.Exploration.SequentialExposure +OAI.Probability.CriticalPercolation.Exploration.SliceExploration +OAI.Probability.CriticalPercolation.Exploration.State +OAI.Probability.CriticalPercolation.Exploration.Tagged +OAI.Probability.CriticalPercolation.Exploration.TargetSearch +OAI.Probability.CriticalPercolation.Exploration.TraceTagged +OAI.Probability.CriticalPercolation.Exploration.TranscriptWeight +OAI.Probability.CriticalPercolation.Exploration.Users +OAI.Probability.CriticalPercolation.Exploration.Visits +OAI.Probability.CriticalPercolation.Gluing.ApproximateMoveEndgame +OAI.Probability.CriticalPercolation.Gluing.CollarDistance +OAI.Probability.CriticalPercolation.Gluing.CollarErrorBudget +OAI.Probability.CriticalPercolation.Gluing.ConditionalGluing +OAI.Probability.CriticalPercolation.Gluing.ContactExitPivot +OAI.Probability.CriticalPercolation.Gluing.ContactPivot +OAI.Probability.CriticalPercolation.Gluing.ContactSelection +OAI.Probability.CriticalPercolation.Gluing.ContourSites +OAI.Probability.CriticalPercolation.Gluing.ContourWords +OAI.Probability.CriticalPercolation.Gluing.CoordinateProspective +OAI.Probability.CriticalPercolation.Gluing.CorridorGraph +OAI.Probability.CriticalPercolation.Gluing.CorridorNormalization +OAI.Probability.CriticalPercolation.Gluing.CorridorScaleChoice +OAI.Probability.CriticalPercolation.Gluing.CorridorSeparation +OAI.Probability.CriticalPercolation.Gluing.DistanceCollarTransfer +OAI.Probability.CriticalPercolation.Gluing.DomainFreshExit +OAI.Probability.CriticalPercolation.Gluing.EllipseMoves +OAI.Probability.CriticalPercolation.Gluing.FewContacts +OAI.Probability.CriticalPercolation.Gluing.FiniteJointGluing +OAI.Probability.CriticalPercolation.Gluing.FiniteJointGluingStrict +OAI.Probability.CriticalPercolation.Gluing.FreshCollar +OAI.Probability.CriticalPercolation.Gluing.FreshCollarExact +OAI.Probability.CriticalPercolation.Gluing.FreshContactTransfer +OAI.Probability.CriticalPercolation.Gluing.FreshCorridor +OAI.Probability.CriticalPercolation.Gluing.FreshExitContinuity +OAI.Probability.CriticalPercolation.Gluing.FreshExitWitness +OAI.Probability.CriticalPercolation.Gluing.FreshTrial +OAI.Probability.CriticalPercolation.Gluing.HonestChoice +OAI.Probability.CriticalPercolation.Gluing.InwardTrial +OAI.Probability.CriticalPercolation.Gluing.LevelContactGeometry +OAI.Probability.CriticalPercolation.Gluing.MoveExit +OAI.Probability.CriticalPercolation.Gluing.MoveWitness +OAI.Probability.CriticalPercolation.Gluing.OpenTrialBound +OAI.Probability.CriticalPercolation.Gluing.PinnedTest +OAI.Probability.CriticalPercolation.Gluing.PredictionFailure +OAI.Probability.CriticalPercolation.Gluing.ProspectiveCorridor +OAI.Probability.CriticalPercolation.Gluing.RelayGeometry +OAI.Probability.CriticalPercolation.Gluing.RelayMoves +OAI.Probability.CriticalPercolation.Gluing.RelayScales +OAI.Probability.CriticalPercolation.Gluing.RootCorridor +OAI.Probability.CriticalPercolation.Gluing.SelectedFresh +OAI.Probability.CriticalPercolation.Gluing.SelectedTrials +OAI.Probability.CriticalPercolation.Gluing.SlotContour +OAI.Probability.CriticalPercolation.Gluing.SourceCollarTransfer +OAI.Probability.CriticalPercolation.Gluing.SourceConnectivity +OAI.Probability.CriticalPercolation.Gluing.SourceGraph +OAI.Probability.CriticalPercolation.Gluing.SourceLift +OAI.Probability.CriticalPercolation.Gluing.SourceRelaySeparation +OAI.Probability.CriticalPercolation.Gluing.StoredPrediction +OAI.Probability.CriticalPercolation.Gluing.StripMoves +OAI.Probability.CriticalPercolation.Gluing.TrialSelection +OAI.Probability.CriticalPercolation.Gluing.UniformFreshBoundary +OAI.Probability.CriticalPercolation.GraphGeometry.ActionCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.AdjacentLog +OAI.Probability.CriticalPercolation.GraphGeometry.BallCutGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.Column +OAI.Probability.CriticalPercolation.GraphGeometry.ColumnHitOthersOffdiag +OAI.Probability.CriticalPercolation.GraphGeometry.ComponentAction +OAI.Probability.CriticalPercolation.GraphGeometry.Connects +OAI.Probability.CriticalPercolation.GraphGeometry.CoordinateRotation +OAI.Probability.CriticalPercolation.GraphGeometry.CoordinateScheme +OAI.Probability.CriticalPercolation.GraphGeometry.CriticalCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.CutEdges +OAI.Probability.CriticalPercolation.GraphGeometry.CutEdgesSubsetIncident +OAI.Probability.CriticalPercolation.GraphGeometry.DeletedTailGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseAngles +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseBoundary +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseExit +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseGrid +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseLinear +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseMesh +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseOrigin +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseSeed +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseSeparation +OAI.Probability.CriticalPercolation.GraphGeometry.EllipseUniform +OAI.Probability.CriticalPercolation.GraphGeometry.EncounterGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.EquivariantCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.EraseBond +OAI.Probability.CriticalPercolation.GraphGeometry.EuclideanEllipse +OAI.Probability.CriticalPercolation.GraphGeometry.ExpectedResidualAlt +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteActionAverage +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteAdjacent +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteCoverSums +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteIndexAction +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteInduced +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteKernelDescent +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteKernelOrbits +OAI.Probability.CriticalPercolation.GraphGeometry.FiniteSumConnection +OAI.Probability.CriticalPercolation.GraphGeometry.ForceFalseSubset +OAI.Probability.CriticalPercolation.GraphGeometry.FullOrbitalStructureTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.GraphAction +OAI.Probability.CriticalPercolation.GraphGeometry.GraphActionCoordinates +OAI.Probability.CriticalPercolation.GraphGeometry.GraphApproximateNeighborhoods +OAI.Probability.CriticalPercolation.GraphGeometry.GraphBalls +OAI.Probability.CriticalPercolation.GraphGeometry.GraphQuotientPolynomial +OAI.Probability.CriticalPercolation.GraphGeometry.HitEvent +OAI.Probability.CriticalPercolation.GraphGeometry.HitEventUpperSet +OAI.Probability.CriticalPercolation.GraphGeometry.HittingSubAvoidance +OAI.Probability.CriticalPercolation.GraphGeometry.InducedAutomorphism +OAI.Probability.CriticalPercolation.GraphGeometry.InducedCritical +OAI.Probability.CriticalPercolation.GraphGeometry.InfiniteAdjacent +OAI.Probability.CriticalPercolation.GraphGeometry.InfiniteEventSubsetHit +OAI.Probability.CriticalPercolation.GraphGeometry.IntegerKernelGeneration +OAI.Probability.CriticalPercolation.GraphGeometry.IsolateThree +OAI.Probability.CriticalPercolation.GraphGeometry.LastInverseDiagonal +OAI.Probability.CriticalPercolation.GraphGeometry.LatticeGrowth +OAI.Probability.CriticalPercolation.GraphGeometry.Link +OAI.Probability.CriticalPercolation.GraphGeometry.Link2 +OAI.Probability.CriticalPercolation.GraphGeometry.LocallyConnectedActionKernel +OAI.Probability.CriticalPercolation.GraphGeometry.MapVertices +OAI.Probability.CriticalPercolation.GraphGeometry.MarkConnectivity +OAI.Probability.CriticalPercolation.GraphGeometry.MovingStrips +OAI.Probability.CriticalPercolation.GraphGeometry.NestedLayerGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.NormalOrbitAction +OAI.Probability.CriticalPercolation.GraphGeometry.ObjectKernel +OAI.Probability.CriticalPercolation.GraphGeometry.OpenGraphInsert +OAI.Probability.CriticalPercolation.GraphGeometry.OpenGraphIso +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitQuotientTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitRepresentatives +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalAction +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalFiniteGeneration +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalPacking +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalPower +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalScales +OAI.Probability.CriticalPercolation.GraphGeometry.OrbitalStructureTransfer +OAI.Probability.CriticalPercolation.GraphGeometry.PhaseStepCharge +OAI.Probability.CriticalPercolation.GraphGeometry.ProbIsolateThree +OAI.Probability.CriticalPercolation.GraphGeometry.ReachableReplaceTail +OAI.Probability.CriticalPercolation.GraphGeometry.ResidualConvertedVariance +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictVertices +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictedAction +OAI.Probability.CriticalPercolation.GraphGeometry.RestrictedOrbitalPacking +OAI.Probability.CriticalPercolation.GraphGeometry.StripCompactness +OAI.Probability.CriticalPercolation.GraphGeometry.StripContinuity +OAI.Probability.CriticalPercolation.GraphGeometry.StripCritical +OAI.Probability.CriticalPercolation.GraphGeometry.StripLinear +OAI.Probability.CriticalPercolation.GraphGeometry.StripOrigin +OAI.Probability.CriticalPercolation.GraphGeometry.StripUniform +OAI.Probability.CriticalPercolation.GraphGeometry.SubgroupOrbitKernel +OAI.Probability.CriticalPercolation.GraphGeometry.UniformGeometry +OAI.Probability.CriticalPercolation.GraphGeometry.UpdateKernel +OAI.Probability.CriticalPercolation.GraphGeometry.VertexBall +OAI.Probability.CriticalPercolation.GraphGeometry.WiredEvent +OAI.Probability.CriticalPercolation.GraphTopology.CommensurableClosure +OAI.Probability.CriticalPercolation.GraphTopology.CompactOrbitKernel +OAI.Probability.CriticalPercolation.GraphTopology.GraphAutomorphismTopology +OAI.Probability.CriticalPercolation.GraphTopology.GraphGeneratingNeighborhood +OAI.Probability.CriticalPercolation.GraphTopology.GraphNeighborhoodCompact +OAI.Probability.CriticalPercolation.GraphTopology.LocalProjectiveTopology +OAI.Probability.CriticalPercolation.GraphTopology.LocallyCompactSubgroup +OAI.Probability.CriticalPercolation.GraphTopology.OpenNormalCore +OAI.Probability.CriticalPercolation.GraphTopology.OrbitalNeighborhoods +OAI.Probability.CriticalPercolation.GraphTopology.TopologicalClassificationBoundary +OAI.Probability.CriticalPercolation.Growth.CosetBallIndex +OAI.Probability.CriticalPercolation.Growth.CosetBounded +OAI.Probability.CriticalPercolation.Growth.CosetFiniteCore +OAI.Probability.CriticalPercolation.Growth.CosetFiniteIndex +OAI.Probability.CriticalPercolation.Growth.CosetGeometry +OAI.Probability.CriticalPercolation.Growth.CosetImageGrowth +OAI.Probability.CriticalPercolation.Growth.CosetIndicability +OAI.Probability.CriticalPercolation.Growth.CosetIntegerKernel +OAI.Probability.CriticalPercolation.Growth.CosetKernelDescent +OAI.Probability.CriticalPercolation.Growth.CosetNormalClosure +OAI.Probability.CriticalPercolation.Growth.CosetNormalPromotion +OAI.Probability.CriticalPercolation.Growth.CosetPresentation +OAI.Probability.CriticalPercolation.Growth.CosetSparseGrowth +OAI.Probability.CriticalPercolation.Growth.CosetSubgroupGenerators +OAI.Probability.CriticalPercolation.Growth.CosetTransfer +OAI.Probability.CriticalPercolation.Growth.GraphQuotientGrowth +OAI.Probability.CriticalPercolation.Growth.GraphRelativeGrowth +OAI.Probability.CriticalPercolation.Growth.HomogeneousAverage +OAI.Probability.CriticalPercolation.Growth.HomogeneousBallPacking +OAI.Probability.CriticalPercolation.Growth.HomogeneousCover +OAI.Probability.CriticalPercolation.Growth.HomogeneousDimension +OAI.Probability.CriticalPercolation.Growth.HomogeneousGeometry +OAI.Probability.CriticalPercolation.Growth.HomogeneousGrowth +OAI.Probability.CriticalPercolation.Growth.HomogeneousPolynomialSpace +OAI.Probability.CriticalPercolation.Growth.HomogeneousTransport +OAI.Probability.CriticalPercolation.Growth.KernelGrowthDescent +OAI.Probability.CriticalPercolation.Growth.PolynomialFolner +OAI.Probability.CriticalPercolation.Growth.PolynomialGrowthDescent +OAI.Probability.CriticalPercolation.Growth.RealSparseDoubling +OAI.Probability.CriticalPercolation.Growth.SparseDoubling +OAI.Probability.CriticalPercolation.Growth.SparseEnergyRatio +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialAlgebra +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialContradiction +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialMain +OAI.Probability.CriticalPercolation.Growth.SuperpolynomialRadius +OAI.Probability.CriticalPercolation.Growth.WordBallPacking +OAI.Probability.CriticalPercolation.Growth.WordLengthGeometry +OAI.Probability.CriticalPercolation.Harmonic.AlmostHarmonicCompactness +OAI.Probability.CriticalPercolation.Harmonic.CayleyCaccioppoli +OAI.Probability.CriticalPercolation.Harmonic.CayleyPoincare +OAI.Probability.CriticalPercolation.Harmonic.CoverPoincare +OAI.Probability.CriticalPercolation.Harmonic.FiniteHilbert +OAI.Probability.CriticalPercolation.Harmonic.FunctionGramMatrix +OAI.Probability.CriticalPercolation.Harmonic.GeneralizedGramSpectrum +OAI.Probability.CriticalPercolation.Harmonic.GramGrowthScales +OAI.Probability.CriticalPercolation.Harmonic.GraphHarmonicCompactness +OAI.Probability.CriticalPercolation.Harmonic.GraphHarmonicLinear +OAI.Probability.CriticalPercolation.Harmonic.GraphProjectedFunctions +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkEnergy +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkOperator +OAI.Probability.CriticalPercolation.Harmonic.GraphWalkProbability +OAI.Probability.CriticalPercolation.Harmonic.HarmonicDimensionBound +OAI.Probability.CriticalPercolation.Harmonic.HarmonicEnergy +OAI.Probability.CriticalPercolation.Harmonic.HarmonicFunctionSpace +OAI.Probability.CriticalPercolation.Harmonic.HarmonicLinearQuotient +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousCaccioppoli +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousGramScales +OAI.Probability.CriticalPercolation.Harmonic.HomogeneousPoincare +OAI.Probability.CriticalPercolation.Harmonic.LazyWalkHilbert +OAI.Probability.CriticalPercolation.Harmonic.LazyWalkProbability +OAI.Probability.CriticalPercolation.Harmonic.PolynomialHarmonicSpace +OAI.Probability.CriticalPercolation.Harmonic.ProjectedWalkFunctions +OAI.Probability.CriticalPercolation.Harmonic.WalkAlmostHarmonic +OAI.Probability.CriticalPercolation.Harmonic.WalkEnergyLower +OAI.Probability.CriticalPercolation.Harmonic.WeakGromovHarmonic +OAI.Probability.CriticalPercolation.LinearGroups.AbsoluteMatrixSpan +OAI.Probability.CriticalPercolation.LinearGroups.AlgebraicVirtualSolvability +OAI.Probability.CriticalPercolation.LinearGroups.AllPlaceKronecker +OAI.Probability.CriticalPercolation.LinearGroups.ArchimedeanDetection +OAI.Probability.CriticalPercolation.LinearGroups.BurnsideDensity +OAI.Probability.CriticalPercolation.LinearGroups.ClusterMatrix +OAI.Probability.CriticalPercolation.LinearGroups.CongruenceTorsion +OAI.Probability.CriticalPercolation.LinearGroups.ConjugationMatrixGrowth +OAI.Probability.CriticalPercolation.LinearGroups.CountableFieldEmbedding +OAI.Probability.CriticalPercolation.LinearGroups.FgMatrixRing +OAI.Probability.CriticalPercolation.LinearGroups.FieldSpanTransfer +OAI.Probability.CriticalPercolation.LinearGroups.FiniteSubspaceOrbit +OAI.Probability.CriticalPercolation.LinearGroups.FullSpanAlternative +OAI.Probability.CriticalPercolation.LinearGroups.GeneralPeriodicCenter +OAI.Probability.CriticalPercolation.LinearGroups.InvariantBlockSolvability +OAI.Probability.CriticalPercolation.LinearGroups.InvariantSubspaceDensity +OAI.Probability.CriticalPercolation.LinearGroups.LocalFurstenbergBound +OAI.Probability.CriticalPercolation.LinearGroups.LocalFurstenbergConcentration +OAI.Probability.CriticalPercolation.LinearGroups.LocalPositiveSubspaceOrbit +OAI.Probability.CriticalPercolation.LinearGroups.LocalProjectiveAction +OAI.Probability.CriticalPercolation.LinearGroups.MatrixLowGrowthSubspace +OAI.Probability.CriticalPercolation.LinearGroups.MatrixPeriodicDirection +OAI.Probability.CriticalPercolation.LinearGroups.PadicDetection +OAI.Probability.CriticalPercolation.LinearGroups.PeriodicSpectrum +OAI.Probability.CriticalPercolation.LinearGroups.PowerBoundedUnipotent +OAI.Probability.CriticalPercolation.LinearGroups.ProjectiveEigenvalues +OAI.Probability.CriticalPercolation.LinearGroups.ProjectivePeriodicity +OAI.Probability.CriticalPercolation.LinearGroups.ProjectivelyPeriodicSchur +OAI.Probability.CriticalPercolation.LinearGroups.ProperPadicModels +OAI.Probability.CriticalPercolation.LinearGroups.RealVirtualSolvability +OAI.Probability.CriticalPercolation.LinearGroups.SelbergCongruence +OAI.Probability.CriticalPercolation.LinearGroups.SelbergSchur +OAI.Probability.CriticalPercolation.LinearGroups.SolvableGrowth +OAI.Probability.CriticalPercolation.LinearGroups.SolvablePeriodicCenter +OAI.Probability.CriticalPercolation.LinearGroups.SolvableSparseClassification +OAI.Probability.CriticalPercolation.LinearGroups.StrongAbstractSpan +OAI.Probability.CriticalPercolation.LinearGroups.StrongDenseEigenvalues +OAI.Probability.CriticalPercolation.LinearGroups.StrongDensePeriodicity +OAI.Probability.CriticalPercolation.Main +OAI.Probability.CriticalPercolation.Model +OAI.Probability.CriticalPercolation.Modular.ActionMassTransport +OAI.Probability.CriticalPercolation.Modular.ActionOrbitTransport +OAI.Probability.CriticalPercolation.Modular.ActionUnimodularRoot +OAI.Probability.CriticalPercolation.Modular.CappedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.ClusterDiscrepancy +OAI.Probability.CriticalPercolation.Modular.ClusterMassEndpoint +OAI.Probability.CriticalPercolation.Modular.ClusterMassEndpointFinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassFinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassInfinite +OAI.Probability.CriticalPercolation.Modular.ClusterMassRestriction +OAI.Probability.CriticalPercolation.Modular.ClusterTransportFinite +OAI.Probability.CriticalPercolation.Modular.ClusterTransportGeometry +OAI.Probability.CriticalPercolation.Modular.ClusterTransportLimit +OAI.Probability.CriticalPercolation.Modular.ClusterTransportSums +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyDrop +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyIdentity +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyNull +OAI.Probability.CriticalPercolation.Modular.CriticalHeavyUniqueness +OAI.Probability.CriticalPercolation.Modular.DensityModular +OAI.Probability.CriticalPercolation.Modular.DiscrepancyTail +OAI.Probability.CriticalPercolation.Modular.ExpectedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.FiniteClusterTransport +OAI.Probability.CriticalPercolation.Modular.GeometricPeakBand +OAI.Probability.CriticalPercolation.Modular.GraphModular +OAI.Probability.CriticalPercolation.Modular.HeavyClusterNumber +OAI.Probability.CriticalPercolation.Modular.HeavyDiscrepancy +OAI.Probability.CriticalPercolation.Modular.HeavyFiniteGeometry +OAI.Probability.CriticalPercolation.Modular.HeavyHarris +OAI.Probability.CriticalPercolation.Modular.HeavyPeaks +OAI.Probability.CriticalPercolation.Modular.HeavyThinning +OAI.Probability.CriticalPercolation.Modular.InputMass +OAI.Probability.CriticalPercolation.Modular.LightCeiling +OAI.Probability.CriticalPercolation.Modular.LightClusterNumber +OAI.Probability.CriticalPercolation.Modular.LightSliceFrontier +OAI.Probability.CriticalPercolation.Modular.LightTwoPointDecay +OAI.Probability.CriticalPercolation.Modular.MainAllLightBoundary +OAI.Probability.CriticalPercolation.Modular.MainInfiniteLightBoundary +OAI.Probability.CriticalPercolation.Modular.MainLightBoundary +OAI.Probability.CriticalPercolation.Modular.MarkedTiltedTransport +OAI.Probability.CriticalPercolation.Modular.Mass +OAI.Probability.CriticalPercolation.Modular.ModularCharacter +OAI.Probability.CriticalPercolation.Modular.ModularClusterCount +OAI.Probability.CriticalPercolation.Modular.ModularClusterMass +OAI.Probability.CriticalPercolation.Modular.ModularGrowth +OAI.Probability.CriticalPercolation.Modular.ModularIncidence +OAI.Probability.CriticalPercolation.Modular.ModularLevelGeometry +OAI.Probability.CriticalPercolation.Modular.ModularSuperlevels +OAI.Probability.CriticalPercolation.Modular.MoveTransport +OAI.Probability.CriticalPercolation.Modular.NormalizedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.NormalizedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.ObjectAvoidMass +OAI.Probability.CriticalPercolation.Modular.OrbitalMassTransport +OAI.Probability.CriticalPercolation.Modular.OrderMass +OAI.Probability.CriticalPercolation.Modular.PeakClusters +OAI.Probability.CriticalPercolation.Modular.PeakRatioTransport +OAI.Probability.CriticalPercolation.Modular.PeakReturn +OAI.Probability.CriticalPercolation.Modular.PeakVolumeBand +OAI.Probability.CriticalPercolation.Modular.PushMass +OAI.Probability.CriticalPercolation.Modular.RandomTiltedTransport +OAI.Probability.CriticalPercolation.Modular.RelativeModular +OAI.Probability.CriticalPercolation.Modular.SignedDiscrepancyContinuity +OAI.Probability.CriticalPercolation.Modular.SignedIncidenceTransport +OAI.Probability.CriticalPercolation.Modular.TiltedMassTransport +OAI.Probability.CriticalPercolation.Modular.TiltedTransportENNReal +OAI.Probability.CriticalPercolation.Modular.UnimodularAdjacent +OAI.Probability.CriticalPercolation.Modular.UnimodularAverages +OAI.Probability.CriticalPercolation.Modular.UnimodularGeometric +OAI.Probability.CriticalPercolation.Modular.UnimodularUnique +OAI.Probability.CriticalPercolation.Modular.Unimodularity +OAI.Probability.CriticalPercolation.Modular.WeightedCauchy +OAI.Probability.CriticalPercolation.Modular.WeightedDiscrepancy +OAI.Probability.CriticalPercolation.Modular.WeightedDiscrepancyLimit +OAI.Probability.CriticalPercolation.Modular.WeightedExplorationCost +OAI.Probability.CriticalPercolation.Modular.WeightedIncidenceSearch +OAI.Probability.CriticalPercolation.Modular.WeightedIntegralBand +OAI.Probability.CriticalPercolation.Modular.WeightedPeakBand +OAI.Probability.CriticalPercolation.Modular.WeightedPeakTransport +OAI.Probability.CriticalPercolation.Modular.WeightedQuery +OAI.Probability.CriticalPercolation.Modular.WeightedQueryBand +OAI.Probability.CriticalPercolation.Modular.WeightedQueryLaw +OAI.Probability.CriticalPercolation.Nilpotent.AbelianAlternatives +OAI.Probability.CriticalPercolation.Nilpotent.AbelianConjugationGrowth +OAI.Probability.CriticalPercolation.Nilpotent.AbelianDescent +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorFinite +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorGeneration +OAI.Probability.CriticalPercolation.Nilpotent.CentralCommutatorQuotient +OAI.Probability.CriticalPercolation.Nilpotent.CharacteristicNilpotentCore +OAI.Probability.CriticalPercolation.Nilpotent.CyclicModTorsion +OAI.Probability.CriticalPercolation.Nilpotent.CyclicSubgroupIndex +OAI.Probability.CriticalPercolation.Nilpotent.FGExtensions +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicConstruction +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicExtensionIndex +OAI.Probability.CriticalPercolation.Nilpotent.FiniteCyclicInheritance +OAI.Probability.CriticalPercolation.Nilpotent.FiniteKernelNilpotent +OAI.Probability.CriticalPercolation.Nilpotent.FreeAbelianDescent +OAI.Probability.CriticalPercolation.Nilpotent.GeneralNilpotentCore +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralFG +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralFinite +OAI.Probability.CriticalPercolation.Nilpotent.LowerCentralTailFinite +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentAlternatives +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentCyclicConstruction +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentDescent +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentFinite +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentInfiniteCenter +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentRankOne +OAI.Probability.CriticalPercolation.Nilpotent.NilpotentSubgroupFG +OAI.Probability.CriticalPercolation.Nilpotent.SolvableSubgroupFG +OAI.Probability.CriticalPercolation.Nilpotent.StructuredNilpotent +OAI.Probability.CriticalPercolation.Nilpotent.StructuredVirtuallyNilpotent +OAI.Probability.CriticalPercolation.ProductMeasure.Associated +OAI.Probability.CriticalPercolation.ProductMeasure.AvgDiv +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliErgodicity +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliSingleton +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliSingletonIntegration +OAI.Probability.CriticalPercolation.ProductMeasure.BernoulliThinning +OAI.Probability.CriticalPercolation.ProductMeasure.BitMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.ClosedCutProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ClosedThin +OAI.Probability.CriticalPercolation.ProductMeasure.CompactInvariantMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.ContinuousExpectWeights +OAI.Probability.CriticalPercolation.ProductMeasure.ContinuousProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ContourProbability +OAI.Probability.CriticalPercolation.ProductMeasure.CoordinateNeDensity +OAI.Probability.CriticalPercolation.ProductMeasure.Delta +OAI.Probability.CriticalPercolation.ProductMeasure.Density +OAI.Probability.CriticalPercolation.ProductMeasure.DensityMulExpect +OAI.Probability.CriticalPercolation.ProductMeasure.Distribution +OAI.Probability.CriticalPercolation.ProductMeasure.EllipseProbability +OAI.Probability.CriticalPercolation.ProductMeasure.ExpectClosedFlip +OAI.Probability.CriticalPercolation.ProductMeasure.ExpectMulReal +OAI.Probability.CriticalPercolation.ProductMeasure.ExposureLaw +OAI.Probability.CriticalPercolation.ProductMeasure.ExposureLawSupport +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteAdjacentMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteInterpolationMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteMarkovAvg +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteOpenWitness +OAI.Probability.CriticalPercolation.ProductMeasure.FiniteProductPin +OAI.Probability.CriticalPercolation.ProductMeasure.ForceClosed +OAI.Probability.CriticalPercolation.ProductMeasure.FreshRegionLaw +OAI.Probability.CriticalPercolation.ProductMeasure.LayerExpectation +OAI.Probability.CriticalPercolation.ProductMeasure.LevelContactMeasurability +OAI.Probability.CriticalPercolation.ProductMeasure.LevelCutProbability +OAI.Probability.CriticalPercolation.ProductMeasure.MeasurableSetRestrict +OAI.Probability.CriticalPercolation.ProductMeasure.MonotoneBernoulli +OAI.Probability.CriticalPercolation.ProductMeasure.MonotoneIndicatorUpper +OAI.Probability.CriticalPercolation.ProductMeasure.Potential +OAI.Probability.CriticalPercolation.ProductMeasure.Prob +OAI.Probability.CriticalPercolation.ProductMeasure.ProbDisjoint +OAI.Probability.CriticalPercolation.ProductMeasure.ProbOr +OAI.Probability.CriticalPercolation.ProductMeasure.ProbRequiresBit +OAI.Probability.CriticalPercolation.ProductMeasure.ProductConditioning +OAI.Probability.CriticalPercolation.ProductMeasure.ProductEmbedding +OAI.Probability.CriticalPercolation.ProductMeasure.QueryMartingale +OAI.Probability.CriticalPercolation.ProductMeasure.RelayProbability +OAI.Probability.CriticalPercolation.ProductMeasure.SourceEventLaw +OAI.Probability.CriticalPercolation.ProductMeasure.SourceMissLaw +OAI.Probability.CriticalPercolation.ProductMeasure.SusceptibilityMeasure +OAI.Probability.CriticalPercolation.ProductMeasure.TailProduct +OAI.Probability.CriticalPercolation.ProductMeasure.TrialProbability +OAI.Probability.CriticalPercolation.ProductMeasure.Variance diff --git a/tasks/critical-percolation/solution/reference.py b/tasks/critical-percolation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/critical-percolation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/critical-percolation/solution/solve.sh b/tasks/critical-percolation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f38791605f01ec4ec93af24e52b9b8a9a6522bc3 --- /dev/null +++ b/tasks/critical-percolation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CriticalPercolation, i.e. module OAI.Probability.CriticalPercolation.Main and the +# 627 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.CriticalPercolation.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CriticalPercolation" diff --git a/tasks/critical-percolation/task.toml b/tasks/critical-percolation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3b9c814ac22631cdf28940126f35f41e7fd692f4 --- /dev/null +++ b/tasks/critical-percolation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/critical-percolation" +version = "1.0.0" +description = "Prove CriticalPercolation (openai/math family 213: No infinite critical clusters on quasi-transitive graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CriticalPercolation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CriticalPercolation" +family = "213" +family_title = "No infinite critical clusters on quasi-transitive graphs" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CriticalPercolation.BondGraph.no_percolation_at_criticality"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.CriticalPercolation.Main" +reference_modules = 627 +reference_lean_bytes = 2911033 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2360 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14319 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/critical-percolation/tests/Challenge.lean b/tasks/critical-percolation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c169f9f897c35165672a2070cdf4a3cec85e5d3 --- /dev/null +++ b/tasks/critical-percolation/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib + +namespace OAI + +open Set MeasureTheory ProbabilityTheory + +namespace CriticalPercolation + +/-- An undirected graph with labelled bonds, including loops and parallel bonds. -/ +structure BondGraph (V E : Type*) where + ends : E → Sym2 V + +namespace BondGraph +variable {V E : Type*} (G : BondGraph V E) + +/-- The graph of retained bonds. `fromEdgeSet` discards loops. -/ +def openGraph (ω : Set E) : SimpleGraph V := + SimpleGraph.fromEdgeSet (G.ends '' ω) + +/-- The underlying connectivity graph with every bond retained. -/ +def fullGraph : SimpleGraph V := G.openGraph Set.univ + +/-- Local finiteness counts bonds, not just distinct neighbors. -/ +def LocallyFinite : Prop := ∀ v : V, {e : E | v ∈ G.ends e}.Finite + +/-- Automorphisms preserve the vertex and bond structure, including multiplicities. -/ +structure Aut where + vertex : V ≃ V + edge : E ≃ E + preserves : ∀ e, G.ends (edge e) = Sym2.map vertex (G.ends e) + +/-- Finitely many vertex orbits under the full automorphism group. -/ +def QuasiTransitive : Prop := + ∃ S : Set V, S.Finite ∧ ∀ v : V, ∃ s ∈ S, ∃ φ : G.Aut, φ.vertex s = v + +/-- Finite open paths, including the path of length zero, define the open cluster. -/ +def cluster (ω : Set E) (v : V) : Set V := {w | (G.openGraph ω).Reachable v w} + +/-- The event that at least one open cluster is infinite. -/ +def percolates : Set (Set E) := {ω | ∃ v : V, (G.cluster ω v).Infinite} + +/-- Independent retention with parameter `p ∈ [0,1]` of each labelled bond. -/ +noncomputable def law (_G : BondGraph V E) (p : unitInterval) : Measure (Set E) := + ProbabilityTheory.setBernoulli Set.univ p + +/-- The infimum of parameters with positive probability of an infinite cluster. -/ +noncomputable def criticalProbability : unitInterval := + sInf {p : unitInterval | 0 < G.law p G.percolates} + +/-- Critical Bernoulli bond percolation has no infinite cluster when the critical +probability is below one. -/ +theorem no_percolation_at_criticality [Infinite V] + (hconnected : G.fullGraph.Connected) + (hlocal : G.LocallyFinite) + (hquasi : G.QuasiTransitive) + (hpc : G.criticalProbability < 1) : + G.law G.criticalProbability G.percolates = 0 := by + sorry + +end BondGraph +end CriticalPercolation + +end OAI diff --git a/tasks/critical-percolation/tests/grade.py b/tasks/critical-percolation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/critical-percolation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/critical-percolation/tests/task.json b/tasks/critical-percolation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..03b7d3277bc7526063f738623cdc3597c22f10e1 --- /dev/null +++ b/tasks/critical-percolation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CriticalPercolation", + "comparator": { + "theorem_names": [ + "OAI.CriticalPercolation.BondGraph.no_percolation_at_criticality" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13419 +} \ No newline at end of file diff --git a/tasks/critical-percolation/tests/test.sh b/tasks/critical-percolation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/critical-percolation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/critical-sk-mixing/environment/Dockerfile b/tasks/critical-sk-mixing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/critical-sk-mixing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/critical-sk-mixing/environment/fetch_mathlib.sh b/tasks/critical-sk-mixing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/critical-sk-mixing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/critical-sk-mixing/environment/lake-manifest.json b/tasks/critical-sk-mixing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/critical-sk-mixing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/critical-sk-mixing/environment/lakefile.lean b/tasks/critical-sk-mixing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/critical-sk-mixing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/critical-sk-mixing/environment/lean_setup.sh b/tasks/critical-sk-mixing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/critical-sk-mixing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/critical-sk-mixing/environment/pack_submission.py b/tasks/critical-sk-mixing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/critical-sk-mixing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/critical-sk-mixing/instruction.md b/tasks/critical-sk-mixing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..775e7b07f41743a3a00c1ee6f955f1fab864f825 --- /dev/null +++ b/tasks/critical-sk-mixing/instruction.md @@ -0,0 +1,130 @@ +# openai/math challenge `CriticalSKMixing` (family 227) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 227 of the release, *The dynamical phase transition in the Sherrington–Kirkpatrick model* +(Probability and statistical mechanics). The family as a whole: For zero-field Gaussian SK heat-bath dynamics with rate-one updates per spin, proves worst-start cutoff on the $\log n$ scale for fixed $0\le\beta<1$, mixing time $n^{2/3+o(1)}$ at $\beta=1$, and stretched-exponential mixing from a Gibbs-sampled fixed starting configuration for $\beta>1$, in probability over disorder. At criticality, rescaled stationary and quench autocorrelation processes have universal random limits for Gaussian and Rademacher disorder; the quench limit relaxes to the stationary limit. + +The challenge is `CriticalSKMixing`, also at `/opt/openai-math/challenges/CriticalSKMixing.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators Topology NNReal ENNReal +open MeasureTheory ProbabilityTheory Filter + +noncomputable section +namespace CriticalSK + +abbrev Spin (n : ℕ) := Fin n → Bool + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +abbrev Disorder (n : ℕ) := Edge n → ℝ + +def spinValue (b : Bool) : ℝ := if b then 1 else -1 + +def hamiltonian {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + ∑ e : Edge n, W e * spinValue (x e.val.1) * spinValue (x e.val.2) + +def partition {n : ℕ} (W : Disorder n) : ℝ := + ∑ x : Spin n, Real.exp (hamiltonian W x) + +def gibbs {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + Real.exp (hamiltonian W x) / partition W + +def disorderLaw (n : ℕ) : Measure (Disorder n) := + Measure.pi fun _ : Edge n => gaussianReal 0 (n : ℝ≥0)⁻¹ + +def sameExcept {n : ℕ} (i : Fin n) (x y : Spin n) : Prop := + ∀ j, j ≠ i → y j = x j + +instance {n : ℕ} (i : Fin n) (x y : Spin n) : Decidable (sameExcept i x y) := + Classical.propDecidable _ + +def siteKernel {n : ℕ} (W : Disorder n) (i : Fin n) : Matrix (Spin n) (Spin n) ℝ := + fun x y => if sameExcept i x y then + gibbs W y / (∑ z : Spin n, if sameExcept i x z then gibbs W z else 0) + else 0 + +def discreteKernel {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + (n : ℝ)⁻¹ • ∑ i : Fin n, siteKernel W i + +def generator {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + ∑ i : Fin n, (siteKernel W i - 1) + +def continuousKernel {n : ℕ} (W : Disorder n) (t : ℝ) : + Matrix (Spin n) (Spin n) ℝ := + NormedSpace.exp (t • generator W) + +def totalVariation {n : ℕ} (W : Disorder n) (p : Spin n → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ y : Spin n, |p y - gibbs W y| + +def continuousDistance {n : ℕ} (W : Disorder n) (t : ℝ) (x : Spin n) : ℝ := + totalVariation W (continuousKernel W t x) + +def discreteDistance {n : ℕ} (W : Disorder n) (k : ℕ) (x : Spin n) : ℝ := + totalVariation W ((discreteKernel W ^ k) x) + +def continuousMixingTime {n : ℕ} (W : Disorder n) : ℝ := + sInf {t : ℝ | 0 ≤ t ∧ ∀ x, continuousDistance W t x ≤ 1 / 4} + +def discreteMixingTime {n : ℕ} (W : Disorder n) : ℕ := + sInf {k : ℕ | ∀ x, discreteDistance W k x ≤ 1 / 4} + +theorem critical_mixing_bounds (ε : ℝ) (hε : 0 < ε) : + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((2 : ℝ) / 3 - ε) ≤ continuousMixingTime W ∧ + continuousMixingTime W ≤ Real.exp (ε * n)}).toReal) atTop (𝓝 1) ∧ + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((5 : ℝ) / 3 - ε) ≤ (discreteMixingTime W : ℝ) ∧ + (discreteMixingTime W : ℝ) ≤ Real.exp (ε * n)}).toReal) atTop (𝓝 1) := by + sorry + +end CriticalSK +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CriticalSKMixing.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CriticalSK.critical_mixing_bounds` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/critical-sk-mixing/solution/closure.txt b/tasks/critical-sk-mixing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4a7003e31c94a50a19cfd521d1de4b78ef548a62 --- /dev/null +++ b/tasks/critical-sk-mixing/solution/closure.txt @@ -0,0 +1,593 @@ +OAI.MathematicalPhysics.CriticalMixing.Comparison +OAI.MathematicalPhysics.CriticalMixing.Main +OAI.MathematicalPhysics.CriticalSK.BlockEnergy +OAI.MathematicalPhysics.CriticalSK.Cavity +OAI.MathematicalPhysics.CriticalSK.Covariance +OAI.MathematicalPhysics.CriticalSK.CubeOverlap +OAI.MathematicalPhysics.CriticalSK.CubeRestriction +OAI.MathematicalPhysics.CriticalSK.DisorderTransfer +OAI.MathematicalPhysics.CriticalSK.EdgeAsymptotics +OAI.MathematicalPhysics.CriticalSK.Equilibrium +OAI.MathematicalPhysics.CriticalSK.GOESpectrum +OAI.MathematicalPhysics.CriticalSK.GapMixing +OAI.MathematicalPhysics.CriticalSK.GaussianConcentration +OAI.MathematicalPhysics.CriticalSK.GaussianMatrices +OAI.MathematicalPhysics.CriticalSK.GaussianMoments +OAI.MathematicalPhysics.CriticalSK.Gibbs +OAI.MathematicalPhysics.CriticalSK.HeatBath +OAI.MathematicalPhysics.CriticalSK.HighTemperature +OAI.MathematicalPhysics.CriticalSK.Main +OAI.MathematicalPhysics.CriticalSK.MinMax +OAI.MathematicalPhysics.CriticalSK.Mixing +OAI.MathematicalPhysics.CriticalSK.OrientationBounds +OAI.MathematicalPhysics.CriticalSK.OrientationLimits +OAI.MathematicalPhysics.CriticalSK.OverlapMoments +OAI.MathematicalPhysics.CriticalSK.PartitionBounds +OAI.MathematicalPhysics.CriticalSK.PathEnergy +OAI.MathematicalPhysics.CriticalSK.PathSpectra +OAI.MathematicalPhysics.CriticalSK.Powers +OAI.MathematicalPhysics.CriticalSK.Rayleigh +OAI.MathematicalPhysics.CriticalSK.Resolvent +OAI.MathematicalPhysics.CriticalSK.Saddle +OAI.MathematicalPhysics.CriticalSK.SaddleLimit +OAI.MathematicalPhysics.CriticalSK.SmallBall +OAI.MathematicalPhysics.CriticalSK.SphereGeometry +OAI.MathematicalPhysics.CriticalSK.SphereSaddle +OAI.MathematicalPhysics.CriticalSK.SpinModel +OAI.MathematicalPhysics.CriticalSK.TriNoise +OAI.Probability.SKGap.Brownian.BrownianCoordinateTail +OAI.Probability.SKGap.Brownian.BrownianMesh +OAI.Probability.SKGap.Brownian.BrownianPathFernique +OAI.Probability.SKGap.Brownian.ContinuousEnergy +OAI.Probability.SKGap.Brownian.ContinuousKernel +OAI.Probability.SKGap.Brownian.ContinuousPosteriorMass +OAI.Probability.SKGap.Brownian.DiscreteUpperContinuous +OAI.Probability.SKGap.Brownian.GibbsContinuity +OAI.Probability.SKGap.Brownian.GramPathRobust +OAI.Probability.SKGap.Brownian.IndependentPathTail +OAI.Probability.SKGap.Brownian.IntervalMesh +OAI.Probability.SKGap.Brownian.LogDetMesh +OAI.Probability.SKGap.Brownian.LogDetPath +OAI.Probability.SKGap.Brownian.MatrixMeanContinuous +OAI.Probability.SKGap.Brownian.ObservationPathEstimate +OAI.Probability.SKGap.Brownian.PathAgreement +OAI.Probability.SKGap.Brownian.PathBias +OAI.Probability.SKGap.Brownian.PathBiasBase +OAI.Probability.SKGap.Brownian.PathBiasCutoff +OAI.Probability.SKGap.Brownian.PathCutoff +OAI.Probability.SKGap.Brownian.PathDiagonal +OAI.Probability.SKGap.Brownian.PathEquivalents +OAI.Probability.SKGap.Brownian.PathExpectation +OAI.Probability.SKGap.Brownian.PathParameter +OAI.Probability.SKGap.Brownian.PathResolvent +OAI.Probability.SKGap.Brownian.WorstContinuousFieldMgf +OAI.Probability.SKGap.Brownian.WorstContinuousPolynomialUpper +OAI.Probability.SKGap.Entropy.AdaptiveTrueAffineQuery +OAI.Probability.SKGap.Entropy.BadIntegralEndpoints +OAI.Probability.SKGap.Entropy.BoundGood +OAI.Probability.SKGap.Entropy.ConditionalBadSet +OAI.Probability.SKGap.Entropy.DisorderWeightedMean +OAI.Probability.SKGap.Entropy.EntropyBound +OAI.Probability.SKGap.Entropy.EntropyEll +OAI.Probability.SKGap.Entropy.EntropyTestBoundQPos +OAI.Probability.SKGap.Entropy.EntropyTransport +OAI.Probability.SKGap.Entropy.ExponentialEmpiricalConcentration +OAI.Probability.SKGap.Entropy.ExponentiallyRare +OAI.Probability.SKGap.Entropy.GaussianExponentialLinear +OAI.Probability.SKGap.Entropy.NormalizedWeightedMean +OAI.Probability.SKGap.Entropy.OrthogonalCoefficients +OAI.Probability.SKGap.Entropy.ParameterMapWeight +OAI.Probability.SKGap.Entropy.ProdFst +OAI.Probability.SKGap.Entropy.QuenchedFieldAverageExponential +OAI.Probability.SKGap.Entropy.QuenchedWeightedMean +OAI.Probability.SKGap.Entropy.RegeneratedNormalizedQuery +OAI.Probability.SKGap.Entropy.RootBadMeasurable +OAI.Probability.SKGap.Entropy.ScalarEntropyTarget +OAI.Probability.SKGap.Entropy.SparseSubsetEntropy +OAI.Probability.SKGap.Entropy.SparseWeightedForm +OAI.Probability.SKGap.Entropy.UpperRare +OAI.Probability.SKGap.Entropy.WeightedMean +OAI.Probability.SKGap.Entropy.WeightedMomentComparison +OAI.Probability.SKGap.Entropy.WeightedRateAssembly +OAI.Probability.SKGap.Entropy.WeightedScalarMoments +OAI.Probability.SKGap.Entropy.WordUniformCost +OAI.Probability.SKGap.Gaussian.AdaptiveInnovationSquareTails +OAI.Probability.SKGap.Gaussian.ConditionalGramTail +OAI.Probability.SKGap.Gaussian.ConditionalUniformTail +OAI.Probability.SKGap.Gaussian.DiagonalNormTail +OAI.Probability.SKGap.Gaussian.FourierMoment +OAI.Probability.SKGap.Gaussian.GOEGaussian +OAI.Probability.SKGap.Gaussian.GOERowTail +OAI.Probability.SKGap.Gaussian.GOEScalarTail +OAI.Probability.SKGap.Gaussian.GaussMoment +OAI.Probability.SKGap.Gaussian.GaussianCompactTailRate +OAI.Probability.SKGap.Gaussian.GaussianCoordinateMemLp +OAI.Probability.SKGap.Gaussian.GaussianCoordinates +OAI.Probability.SKGap.Gaussian.GaussianDisintegration +OAI.Probability.SKGap.Gaussian.GaussianFiniteIBPError +OAI.Probability.SKGap.Gaussian.GaussianGramMomentsJoined +OAI.Probability.SKGap.Gaussian.GaussianLinearDensity +OAI.Probability.SKGap.Gaussian.GaussianMarginal +OAI.Probability.SKGap.Gaussian.GaussianMatrixChaining +OAI.Probability.SKGap.Gaussian.GaussianPDFMoment +OAI.Probability.SKGap.Gaussian.GaussianPartition +OAI.Probability.SKGap.Gaussian.GaussianProductIntegral +OAI.Probability.SKGap.Gaussian.GaussianProductPower +OAI.Probability.SKGap.Gaussian.GaussianProductUpperTailLipschitz +OAI.Probability.SKGap.Gaussian.GaussianQuadratic +OAI.Probability.SKGap.Gaussian.GaussianQuadraticSupComparison +OAI.Probability.SKGap.Gaussian.GaussianRankCorrection +OAI.Probability.SKGap.Gaussian.GaussianRecipeEvent +OAI.Probability.SKGap.Gaussian.GaussianReductionPointwise +OAI.Probability.SKGap.Gaussian.GaussianRegression +OAI.Probability.SKGap.Gaussian.GaussianSign +OAI.Probability.SKGap.Gaussian.GaussianSquareTail +OAI.Probability.SKGap.Gaussian.GaussianTailScale +OAI.Probability.SKGap.Gaussian.GaussianTiltIdentity +OAI.Probability.SKGap.Gaussian.GaussianTiltMass +OAI.Probability.SKGap.Gaussian.GaussianVectorMoments +OAI.Probability.SKGap.Gaussian.IndependentBoundedAverageTailLaw +OAI.Probability.SKGap.Gaussian.LiteralWeakTail +OAI.Probability.SKGap.Gaussian.LocalGaussianMoments +OAI.Probability.SKGap.Gaussian.MatrixNormTail +OAI.Probability.SKGap.Gaussian.MatrixWordMoments +OAI.Probability.SKGap.Gaussian.PartitionSecondMoment +OAI.Probability.SKGap.Gaussian.PhiMoments +OAI.Probability.SKGap.Gaussian.PhiStein +OAI.Probability.SKGap.Gaussian.ProductGaussianDensity +OAI.Probability.SKGap.Gaussian.RegressionMoments +OAI.Probability.SKGap.Gaussian.ReplicaTailWeight +OAI.Probability.SKGap.Gaussian.SampledInnerTailScaled +OAI.Probability.SKGap.Gaussian.ScalarGaussianReductionAlgebra +OAI.Probability.SKGap.Gaussian.ScalarMomentGram +OAI.Probability.SKGap.Gaussian.SquareTail +OAI.Probability.SKGap.Gaussian.SquareTail2 +OAI.Probability.SKGap.Gaussian.SquaredGaussianFourth +OAI.Probability.SKGap.Gaussian.StandardGaussianProduct +OAI.Probability.SKGap.Gaussian.StdGaussianMgfLipschitz +OAI.Probability.SKGap.Gaussian.SteinRecipeRegularity +OAI.Probability.SKGap.Gaussian.SubgaussianAbsTail +OAI.Probability.SKGap.Localization.AffineBilinear +OAI.Probability.SKGap.Localization.AffineUpper +OAI.Probability.SKGap.Localization.Append +OAI.Probability.SKGap.Localization.AttractionBasinIUnion +OAI.Probability.SKGap.Localization.Bilinear +OAI.Probability.SKGap.Localization.Bilinear2 +OAI.Probability.SKGap.Localization.BilinearCoefficient +OAI.Probability.SKGap.Localization.BilinearUnion +OAI.Probability.SKGap.Localization.BlockDegree +OAI.Probability.SKGap.Localization.BoundedIntervalFubini +OAI.Probability.SKGap.Localization.BoxChaining +OAI.Probability.SKGap.Localization.BufferedComparisonBound +OAI.Probability.SKGap.Localization.BufferedFlip +OAI.Probability.SKGap.Localization.BufferedSelectionDiagnostics +OAI.Probability.SKGap.Localization.Centered +OAI.Probability.SKGap.Localization.ChainingCore +OAI.Probability.SKGap.Localization.Character +OAI.Probability.SKGap.Localization.ClosedMarked +OAI.Probability.SKGap.Localization.ClosedMarkedControl +OAI.Probability.SKGap.Localization.ClosedPrediction +OAI.Probability.SKGap.Localization.CoefficientFlip +OAI.Probability.SKGap.Localization.CoefficientInputBridge +OAI.Probability.SKGap.Localization.CoefficientRow +OAI.Probability.SKGap.Localization.CompactTube +OAI.Probability.SKGap.Localization.ComponentRefresh +OAI.Probability.SKGap.Localization.CondSubConst +OAI.Probability.SKGap.Localization.ConditionalEmpiricalLaw +OAI.Probability.SKGap.Localization.ConditionalHessianLaw +OAI.Probability.SKGap.Localization.ConditionalIntegralRate +OAI.Probability.SKGap.Localization.ConditionalMiddleSize +OAI.Probability.SKGap.Localization.ConditionalModelAlgebra +OAI.Probability.SKGap.Localization.ConditionalRankAlgebra +OAI.Probability.SKGap.Localization.ConditionalTolerance +OAI.Probability.SKGap.Localization.ConditionalWeight +OAI.Probability.SKGap.Localization.ConditionalWellDefined +OAI.Probability.SKGap.Localization.Conjugation +OAI.Probability.SKGap.Localization.ConstantRecipe +OAI.Probability.SKGap.Localization.CoordinateDeriv +OAI.Probability.SKGap.Localization.CoordinateLipschitz +OAI.Probability.SKGap.Localization.CubeApprox +OAI.Probability.SKGap.Localization.CubeWeight +OAI.Probability.SKGap.Localization.CurieWeiss +OAI.Probability.SKGap.Localization.CyclicPrediction +OAI.Probability.SKGap.Localization.DerivNonnegRightMin +OAI.Probability.SKGap.Localization.DiagonalHessianJoined +OAI.Probability.SKGap.Localization.DiagonalSqrt +OAI.Probability.SKGap.Localization.DiagonalSum +OAI.Probability.SKGap.Localization.DiagonalTMemLp +OAI.Probability.SKGap.Localization.DimensionDecay +OAI.Probability.SKGap.Localization.DimensionDecayPos +OAI.Probability.SKGap.Localization.DisorderRecipeEvent +OAI.Probability.SKGap.Localization.DivergenceIntegrand +OAI.Probability.SKGap.Localization.DoublePlantedLawTransfer +OAI.Probability.SKGap.Localization.DriftSquare +OAI.Probability.SKGap.Localization.EmpiricalConditionalData +OAI.Probability.SKGap.Localization.EmpiricalGramBound +OAI.Probability.SKGap.Localization.EmpiricalLaw +OAI.Probability.SKGap.Localization.EntryLM +OAI.Probability.SKGap.Localization.Envelope +OAI.Probability.SKGap.Localization.EqualityCurve +OAI.Probability.SKGap.Localization.Error +OAI.Probability.SKGap.Localization.ExpAbsSum +OAI.Probability.SKGap.Localization.ExpDrift +OAI.Probability.SKGap.Localization.ExpDuhamel +OAI.Probability.SKGap.Localization.ExpSum +OAI.Probability.SKGap.Localization.ExpectedCutoff +OAI.Probability.SKGap.Localization.FiniteMax +OAI.Probability.SKGap.Localization.FiniteRankPositive +OAI.Probability.SKGap.Localization.FiniteRecipeControl +OAI.Probability.SKGap.Localization.FiniteStartedControlGeneral +OAI.Probability.SKGap.Localization.FixedTimeQuenched +OAI.Probability.SKGap.Localization.FockSeries +OAI.Probability.SKGap.Localization.FrobeniusSq +OAI.Probability.SKGap.Localization.GeneralTemplateRegularity +OAI.Probability.SKGap.Localization.GeneratorNonposMax +OAI.Probability.SKGap.Localization.GramColumnBounds +OAI.Probability.SKGap.Localization.GramRobust +OAI.Probability.SKGap.Localization.GramUniformRobust +OAI.Probability.SKGap.Localization.GraphPrediction +OAI.Probability.SKGap.Localization.GridSteps +OAI.Probability.SKGap.Localization.IntegrableLinearCombinationSq +OAI.Probability.SKGap.Localization.IntegrableMulBounded +OAI.Probability.SKGap.Localization.IntegrableResidualRecipeSq +OAI.Probability.SKGap.Localization.IntegralAbsSet +OAI.Probability.SKGap.Localization.IntegralProductDeviation +OAI.Probability.SKGap.Localization.Invert +OAI.Probability.SKGap.Localization.JumpBilinear +OAI.Probability.SKGap.Localization.JumpEnergy +OAI.Probability.SKGap.Localization.JumpWeight +OAI.Probability.SKGap.Localization.KernelDensity +OAI.Probability.SKGap.Localization.Letter +OAI.Probability.SKGap.Localization.LinSub +OAI.Probability.SKGap.Localization.LinearObservable +OAI.Probability.SKGap.Localization.LiteralConstruction +OAI.Probability.SKGap.Localization.LiteralInitialRecipe +OAI.Probability.SKGap.Localization.LiteralInitialSystem +OAI.Probability.SKGap.Localization.LiteralLocalInput +OAI.Probability.SKGap.Localization.LiteralLocalWeak +OAI.Probability.SKGap.Localization.LiteralMargin +OAI.Probability.SKGap.Localization.LiteralPartial +OAI.Probability.SKGap.Localization.LiteralRegularity +OAI.Probability.SKGap.Localization.LiteralSeriesLiftAppend +OAI.Probability.SKGap.Localization.LiteralSystemBridge +OAI.Probability.SKGap.Localization.LiteralValues +OAI.Probability.SKGap.Localization.LiteralWeak +OAI.Probability.SKGap.Localization.LocalCoefficient +OAI.Probability.SKGap.Localization.LocalExtraction +OAI.Probability.SKGap.Localization.LocalFixedRecipe +OAI.Probability.SKGap.Localization.LocalRecipeClass +OAI.Probability.SKGap.Localization.LocalResidualInduction +OAI.Probability.SKGap.Localization.LocalStartedDiagonal +OAI.Probability.SKGap.Localization.LocalUniformWeak +OAI.Probability.SKGap.Localization.LocalVolumeChange +OAI.Probability.SKGap.Localization.LocalVolumeEnergy +OAI.Probability.SKGap.Localization.LocalVolumeFull +OAI.Probability.SKGap.Localization.LocalWeakBase +OAI.Probability.SKGap.Localization.LocalWhitening +OAI.Probability.SKGap.Localization.LogPartitionDeviationProbability +OAI.Probability.SKGap.Localization.LogQuadratic +OAI.Probability.SKGap.Localization.Magnetization +OAI.Probability.SKGap.Localization.Map +OAI.Probability.SKGap.Localization.MarkedDiagnostic +OAI.Probability.SKGap.Localization.MarkedErrorRate +OAI.Probability.SKGap.Localization.MarkedProductIBP +OAI.Probability.SKGap.Localization.ModelLocalization +OAI.Probability.SKGap.Localization.NoiseSplit +OAI.Probability.SKGap.Localization.Operation +OAI.Probability.SKGap.Localization.OperatorQuenched +OAI.Probability.SKGap.Localization.OriginalEventRegeneration +OAI.Probability.SKGap.Localization.PartitionChangeMeasure +OAI.Probability.SKGap.Localization.PartitionLogLipschitz +OAI.Probability.SKGap.Localization.PhiAlgebra +OAI.Probability.SKGap.Localization.PhiBounds +OAI.Probability.SKGap.Localization.PhiCoefficient +OAI.Probability.SKGap.Localization.PhiFrechet +OAI.Probability.SKGap.Localization.PhiHessianBridge +OAI.Probability.SKGap.Localization.PhiRatio +OAI.Probability.SKGap.Localization.PhiRegularity +OAI.Probability.SKGap.Localization.PhiResponse +OAI.Probability.SKGap.Localization.PlantedFixedTime +OAI.Probability.SKGap.Localization.PlantedMarginalLaw +OAI.Probability.SKGap.Localization.PlantedTilt +OAI.Probability.SKGap.Localization.PoissonBinomial +OAI.Probability.SKGap.Localization.PoissonBinomialProbability +OAI.Probability.SKGap.Localization.PoissonWeight +OAI.Probability.SKGap.Localization.PositiveRamp +OAI.Probability.SKGap.Localization.Prediction +OAI.Probability.SKGap.Localization.PreparationGrowth +OAI.Probability.SKGap.Localization.PrimaryDifferentiation +OAI.Probability.SKGap.Localization.PrimaryFiniteControl +OAI.Probability.SKGap.Localization.PrimaryLocalInput +OAI.Probability.SKGap.Localization.PrimaryPrediction +OAI.Probability.SKGap.Localization.PrimaryQuenched +OAI.Probability.SKGap.Localization.ProdEventSectionLaw +OAI.Probability.SKGap.Localization.ProjectedMarkedIBP +OAI.Probability.SKGap.Localization.ProjectedReal +OAI.Probability.SKGap.Localization.Quadratic +OAI.Probability.SKGap.Localization.QuadraticCoeff +OAI.Probability.SKGap.Localization.QuenchedHelpers +OAI.Probability.SKGap.Localization.QueryColumn +OAI.Probability.SKGap.Localization.QueryResidual +OAI.Probability.SKGap.Localization.RankCovariance +OAI.Probability.SKGap.Localization.RareCoordinate +OAI.Probability.SKGap.Localization.RealParameterIncrement +OAI.Probability.SKGap.Localization.RealPart +OAI.Probability.SKGap.Localization.RealQuadratic +OAI.Probability.SKGap.Localization.RecipeArgumentPullback +OAI.Probability.SKGap.Localization.RecipeBound +OAI.Probability.SKGap.Localization.RecipeCoefficientClosure +OAI.Probability.SKGap.Localization.RecipeError +OAI.Probability.SKGap.Localization.RecipeGraph +OAI.Probability.SKGap.Localization.RecipeIncrement +OAI.Probability.SKGap.Localization.RecipeMarked +OAI.Probability.SKGap.Localization.RecipePrimaryMass +OAI.Probability.SKGap.Localization.Reference +OAI.Probability.SKGap.Localization.RefreshGenerator +OAI.Probability.SKGap.Localization.RegeneratedAnswer +OAI.Probability.SKGap.Localization.ResidualAdmissibility +OAI.Probability.SKGap.Localization.ResidualInduction +OAI.Probability.SKGap.Localization.ResidualMultiplier +OAI.Probability.SKGap.Localization.ResidualRecipe +OAI.Probability.SKGap.Localization.ResidualRecipe2 +OAI.Probability.SKGap.Localization.ResidualSelection +OAI.Probability.SKGap.Localization.SampledFlatCLM +OAI.Probability.SKGap.Localization.SandShift +OAI.Probability.SKGap.Localization.SandShiftSpecial +OAI.Probability.SKGap.Localization.ScalarClosedIsolation +OAI.Probability.SKGap.Localization.ScalarConsistency +OAI.Probability.SKGap.Localization.ScalarEigenfunction +OAI.Probability.SKGap.Localization.ScalarEmpirical +OAI.Probability.SKGap.Localization.ScalarFixedPointJoined +OAI.Probability.SKGap.Localization.ScalarParametersJoined +OAI.Probability.SKGap.Localization.ScalarRelativeIsolation +OAI.Probability.SKGap.Localization.ScalarSlowConeStep +OAI.Probability.SKGap.Localization.ScalarSmallNoiseTests +OAI.Probability.SKGap.Localization.ScalarVariance +OAI.Probability.SKGap.Localization.SelectionDeficit +OAI.Probability.SKGap.Localization.SelectionPartition +OAI.Probability.SKGap.Localization.SemicircleDensity +OAI.Probability.SKGap.Localization.SemigroupAbs +OAI.Probability.SKGap.Localization.SeparateCut +OAI.Probability.SKGap.Localization.SeparatedCard +OAI.Probability.SKGap.Localization.SmallOverlap +OAI.Probability.SKGap.Localization.SmoothSelection +OAI.Probability.SKGap.Localization.SparseCubeNet +OAI.Probability.SKGap.Localization.SparseQuadratic +OAI.Probability.SKGap.Localization.SparseShrink +OAI.Probability.SKGap.Localization.StandardArrayLaw +OAI.Probability.SKGap.Localization.StartedFixed +OAI.Probability.SKGap.Localization.StartedGraph +OAI.Probability.SKGap.Localization.StartedMarked +OAI.Probability.SKGap.Localization.StartedPrefix +OAI.Probability.SKGap.Localization.StartedPrimary +OAI.Probability.SKGap.Localization.StartedRecipe +OAI.Probability.SKGap.Localization.StartedResidualStep +OAI.Probability.SKGap.Localization.StartedSmall +OAI.Probability.SKGap.Localization.StationaryInner +OAI.Probability.SKGap.Localization.StepMass +OAI.Probability.SKGap.Localization.SumPoissonMass +OAI.Probability.SKGap.Localization.SusceptibilityMiddle +OAI.Probability.SKGap.Localization.SusceptibilityTest +OAI.Probability.SKGap.Localization.SymmetricElementaryComm +OAI.Probability.SKGap.Localization.TAPGauge +OAI.Probability.SKGap.Localization.TAPScalarTaylor +OAI.Probability.SKGap.Localization.TAPVectorTaylor +OAI.Probability.SKGap.Localization.TanhContDiff +OAI.Probability.SKGap.Localization.TanhCubic +OAI.Probability.SKGap.Localization.TapPotential +OAI.Probability.SKGap.Localization.TargetAttempt +OAI.Probability.SKGap.Localization.Taylor +OAI.Probability.SKGap.Localization.TemplateChaining +OAI.Probability.SKGap.Localization.TemplatePatterns +OAI.Probability.SKGap.Localization.ThresholdChoice +OAI.Probability.SKGap.Localization.TruncationGoodSet +OAI.Probability.SKGap.Localization.UniformRecipeClass +OAI.Probability.SKGap.Localization.UniformResidual +OAI.Probability.SKGap.Localization.UniformSquareInduction +OAI.Probability.SKGap.Localization.UniformStarted +OAI.Probability.SKGap.Localization.UnitBall +OAI.Probability.SKGap.Localization.UpperClockTendstoTop +OAI.Probability.SKGap.Localization.UpperCoefficient +OAI.Probability.SKGap.Localization.Vectorize +OAI.Probability.SKGap.Localization.WeakResidual +OAI.Probability.SKGap.Main +OAI.Probability.SKGap.Matrix.BufferedClosedWord +OAI.Probability.SKGap.Matrix.ClosedErrorTrace +OAI.Probability.SKGap.Matrix.ClosedMatrix +OAI.Probability.SKGap.Matrix.ClosedTrace +OAI.Probability.SKGap.Matrix.ClosedTreeMatrix +OAI.Probability.SKGap.Matrix.CompletedMatrix +OAI.Probability.SKGap.Matrix.ConditionalEmpiricalNorm +OAI.Probability.SKGap.Matrix.ConditionalMiddleNorm +OAI.Probability.SKGap.Matrix.CorrectionTrace +OAI.Probability.SKGap.Matrix.DiscreteMatrixCalculus +OAI.Probability.SKGap.Matrix.DoublePlantLogNorm +OAI.Probability.SKGap.Matrix.DoublePlantedGOEArray +OAI.Probability.SKGap.Matrix.FixedNormRecipeEvent +OAI.Probability.SKGap.Matrix.FockTensor +OAI.Probability.SKGap.Matrix.GOEBilinearCov +OAI.Probability.SKGap.Matrix.GOEBlockExpansion +OAI.Probability.SKGap.Matrix.GOEDiagonalSquare +OAI.Probability.SKGap.Matrix.GOEGlobalEvents +OAI.Probability.SKGap.Matrix.GOERegression +OAI.Probability.SKGap.Matrix.GOEResidualCov +OAI.Probability.SKGap.Matrix.GOERowLaw +OAI.Probability.SKGap.Matrix.GOESparse +OAI.Probability.SKGap.Matrix.GOESubmatrix +OAI.Probability.SKGap.Matrix.GapHalfSmallOpNorm +OAI.Probability.SKGap.Matrix.GlobalWordIncrement +OAI.Probability.SKGap.Matrix.GoeInverseLoopCentered +OAI.Probability.SKGap.Matrix.InverseDiagram +OAI.Probability.SKGap.Matrix.InverseSeries +OAI.Probability.SKGap.Matrix.InverseSubSquareMul +OAI.Probability.SKGap.Matrix.LiftMatrix +OAI.Probability.SKGap.Matrix.LipschitzNormedConvolution +OAI.Probability.SKGap.Matrix.LiteralTrace +OAI.Probability.SKGap.Matrix.LogDetConcentration +OAI.Probability.SKGap.Matrix.LogDetExpected +OAI.Probability.SKGap.Matrix.LogDetIntegral +OAI.Probability.SKGap.Matrix.LogDetUniform +OAI.Probability.SKGap.Matrix.LoopPrediction +OAI.Probability.SKGap.Matrix.MarkedWordIBP +OAI.Probability.SKGap.Matrix.MatrixCoordinates +OAI.Probability.SKGap.Matrix.MatrixEntryCLM +OAI.Probability.SKGap.Matrix.MatrixLogDet +OAI.Probability.SKGap.Matrix.MatrixQuad +OAI.Probability.SKGap.Matrix.MatrixSeminorm +OAI.Probability.SKGap.Matrix.MatrixWhitening +OAI.Probability.SKGap.Matrix.MatrixWordIncrement +OAI.Probability.SKGap.Matrix.MatrixWordRegularity +OAI.Probability.SKGap.Matrix.MeasurableCompletedMatrix +OAI.Probability.SKGap.Matrix.NormalLogConst +OAI.Probability.SKGap.Matrix.NormalLogDensityCentered +OAI.Probability.SKGap.Matrix.NormalizedInfluence +OAI.Probability.SKGap.Matrix.NormalizedPrimaryRecipe +OAI.Probability.SKGap.Matrix.NormalizedRecipeLaw +OAI.Probability.SKGap.Matrix.OpNorm +OAI.Probability.SKGap.Matrix.OpNormDiagonal +OAI.Probability.SKGap.Matrix.OpNormKernelMatrixSub +OAI.Probability.SKGap.Matrix.PolynomialCoeListSum +OAI.Probability.SKGap.Matrix.PrimaryMatrix +OAI.Probability.SKGap.Matrix.PrimaryWordControl +OAI.Probability.SKGap.Matrix.PrimaryWordEventBinding +OAI.Probability.SKGap.Matrix.PrimitiveTrace +OAI.Probability.SKGap.Matrix.RankNorm +OAI.Probability.SKGap.Matrix.RealSymmetricResolventUnit +OAI.Probability.SKGap.Matrix.RecipeNodeTrace +OAI.Probability.SKGap.Matrix.RecipeTraceBudget +OAI.Probability.SKGap.Matrix.RecipeWordEvent +OAI.Probability.SKGap.Matrix.RegularizedLogDet +OAI.Probability.SKGap.Matrix.StartedMatrixEvent +OAI.Probability.SKGap.Matrix.StartedNodeTrace +OAI.Probability.SKGap.Matrix.StartedTraceBudget +OAI.Probability.SKGap.Matrix.StartedWordClosure +OAI.Probability.SKGap.Matrix.StaticCovarianceMatrix +OAI.Probability.SKGap.Matrix.TanhMatrixBounds +OAI.Probability.SKGap.Matrix.Trace +OAI.Probability.SKGap.Matrix.Word +OAI.Probability.SKGap.Matrix.WordBaseBias +OAI.Probability.SKGap.Matrix.WordBiasCutoff +OAI.Probability.SKGap.Matrix.WordBiasInduction +OAI.Probability.SKGap.Matrix.WordDerivative +OAI.Probability.SKGap.Matrix.WordDiag +OAI.Probability.SKGap.Matrix.WordDiagUniform +OAI.Probability.SKGap.Matrix.WordExpectedRecursion +OAI.Probability.SKGap.Matrix.WordFockSeries +OAI.Probability.SKGap.Matrix.WordIncrement +OAI.Probability.SKGap.Matrix.WordLeading +OAI.Probability.SKGap.Matrix.WordLoop +OAI.Probability.SKGap.Matrix.WordLoopLeading +OAI.Probability.SKGap.Matrix.WordPartnerContraction +OAI.Probability.SKGap.Matrix.WordSimultaneousPrediction +OAI.Probability.SKGap.Matrix.WordTemplateSurjective +OAI.Probability.SKGap.Model +OAI.Probability.SKGap.Posterior.BufferedPosteriorCovariance +OAI.Probability.SKGap.Posterior.BufferedPosteriorDirection +OAI.Probability.SKGap.Posterior.ChannelTranslation +OAI.Probability.SKGap.Posterior.ConditionalObservationData +OAI.Probability.SKGap.Posterior.GOEObservation +OAI.Probability.SKGap.Posterior.GOEPointwisePosterior +OAI.Probability.SKGap.Posterior.GaussianChannel +OAI.Probability.SKGap.Posterior.History +OAI.Probability.SKGap.Posterior.QuenchedPosterior +OAI.Probability.SKGap.Posterior.StaticExperimentBridge +OAI.Probability.SKGap.Stability.ClosedOrdinaryBridge +OAI.Probability.SKGap.Stability.ConditionalMean +OAI.Probability.SKGap.Stability.ConditionalMeanScalar +OAI.Probability.SKGap.Stability.ConditionalStability +OAI.Probability.SKGap.Stability.DiagonalStability +OAI.Probability.SKGap.Stability.FieldIntegralMeasure +OAI.Probability.SKGap.Stability.FieldIntegralReduction +OAI.Probability.SKGap.Stability.FieldLogDet +OAI.Probability.SKGap.Stability.FieldSquareSum +OAI.Probability.SKGap.Stability.FieldTonelli +OAI.Probability.SKGap.Stability.FixedTimeAnnealed +OAI.Probability.SKGap.Stability.GaugeStabilityLaw +OAI.Probability.SKGap.Stability.GaugedField +OAI.Probability.SKGap.Stability.HalfDiffField +OAI.Probability.SKGap.Stability.ImplicitCoefficient +OAI.Probability.SKGap.Stability.ImplicitComparison +OAI.Probability.SKGap.Stability.ImplicitFlip +OAI.Probability.SKGap.Stability.ImplicitFrobenius +OAI.Probability.SKGap.Stability.ImplicitLinear +OAI.Probability.SKGap.Stability.ImplicitNode +OAI.Probability.SKGap.Stability.ImplicitPerturb +OAI.Probability.SKGap.Stability.ImplicitTraceControl +OAI.Probability.SKGap.Stability.ImplicitUniform +OAI.Probability.SKGap.Stability.ImplicitUniformControl +OAI.Probability.SKGap.Stability.LawMean +OAI.Probability.SKGap.Stability.LiteralStableControl +OAI.Probability.SKGap.Stability.LiteralStableEvent +OAI.Probability.SKGap.Stability.LocalImplicitNode +OAI.Probability.SKGap.Stability.LocalStartedImplicit +OAI.Probability.SKGap.Stability.LogDetMean +OAI.Probability.SKGap.Stability.LogDetUniformMean +OAI.Probability.SKGap.Stability.Ordinary +OAI.Probability.SKGap.Stability.OrdinaryClosure +OAI.Probability.SKGap.Stability.OrdinaryCutLeft +OAI.Probability.SKGap.Stability.OrdinaryGraph +OAI.Probability.SKGap.Stability.OrdinaryRecipe +OAI.Probability.SKGap.Stability.OrdinaryWordEvent +OAI.Probability.SKGap.Stability.PlantedFieldArray +OAI.Probability.SKGap.Stability.PlantedFieldCenter +OAI.Probability.SKGap.Stability.PositiveRootStability +OAI.Probability.SKGap.Stability.QuenchedStableFields +OAI.Probability.SKGap.Stability.ResidualRoot +OAI.Probability.SKGap.Stability.RootDiagonalTransfer +OAI.Probability.SKGap.Stability.RootFieldTransfer +OAI.Probability.SKGap.Stability.RootGrid +OAI.Probability.SKGap.Stability.SmallRootStability +OAI.Probability.SKGap.Stability.StabilityMatrix +OAI.Probability.SKGap.Stability.StableFields +OAI.Probability.SKGap.Stability.StableLiteralComparison +OAI.Probability.SKGap.Stability.StableLiteralWeak +OAI.Probability.SKGap.Stability.StableRootInverse +OAI.Probability.SKGap.Stability.TapFieldE +OAI.Probability.SKGap.Stability.UniformOrdinary +OAI.Probability.SKGap.Stability.WordDiagStable +OAI.Probability.SKGap.Stability.WordMeanSeminorm +OAI.Probability.SKGap.Stability.WordOrdinaryAgreement +OAI.Probability.SKGap.Stability.WordPredictionStability +OAI.Probability.SKGap.Stability.WordStableAgreement +OAI.Probability.SKGap.Stability.WordStablePrediction +OAI.Probability.SKGap.Terminal.ConsDiag +OAI.Probability.SKGap.Terminal.FieldGibbs +OAI.Probability.SKGap.Terminal.FinitePairTail +OAI.Probability.SKGap.Terminal.FiniteSpinCalculus +OAI.Probability.SKGap.Terminal.GibbsEventProbability +OAI.Probability.SKGap.Terminal.GibbsEventProbabilityReal +OAI.Probability.SKGap.Terminal.GibbsExpectation +OAI.Probability.SKGap.Terminal.GibbsExpectationMono +OAI.Probability.SKGap.Terminal.GibbsLExpectation +OAI.Probability.SKGap.Terminal.Map +OAI.Probability.SKGap.Terminal.PairBoltzmann +OAI.Probability.SKGap.Terminal.PairConditioning +OAI.Probability.SKGap.Terminal.PairCrossIdentity +OAI.Probability.SKGap.Terminal.PairCrossLower +OAI.Probability.SKGap.Terminal.PairGibbsBound +OAI.Probability.SKGap.Terminal.PairInteraction +OAI.Probability.SKGap.Terminal.PairRationalBounds +OAI.Probability.SKGap.Terminal.PairSpinFrequency +OAI.Probability.SKGap.Terminal.PairingPairingAddError +OAI.Probability.SKGap.Terminal.PowExponentialPair +OAI.Probability.SKGap.Terminal.ResidualPairMoments +OAI.Probability.SKGap.Terminal.SingleSpinPlantedLaw +OAI.Probability.SKGap.Terminal.SmallFieldCount +OAI.Probability.SKGap.Terminal.Spin +OAI.Probability.SKGap.Terminal.SpinChebyshev +OAI.Probability.SKGap.Terminal.SpinCovarianceMeasure +OAI.Probability.SKGap.Terminal.SpinDifferenceEnergy +OAI.Probability.SKGap.Terminal.SpinDifferenceEnergyReplace +OAI.Probability.SKGap.Terminal.SpinEnergy +OAI.Probability.SKGap.Terminal.SpinGaussianBound +OAI.Probability.SKGap.Terminal.SpinLocalField +OAI.Probability.SKGap.Terminal.SpinSpectralMassBelow +OAI.Probability.SKGap.Terminal.StableLiteralTerminal +OAI.Probability.SKGap.Terminal.TerminalChannel +OAI.Probability.SKGap.Terminal.TerminalDeterministic +OAI.Probability.SKGap.Terminal.TerminalHighProbability +OAI.Probability.SKGap.Terminal.TerminalIdentity +OAI.Probability.SKGap.Terminal.TerminalMatrixMeasurable +OAI.Probability.SKGap.Terminal.TerminalMatrixTransfer +OAI.Probability.SKGap.Terminal.TerminalProbability +OAI.Probability.SKGap.Terminal.TerminalRates diff --git a/tasks/critical-sk-mixing/solution/reference.py b/tasks/critical-sk-mixing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/critical-sk-mixing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/critical-sk-mixing/solution/solve.sh b/tasks/critical-sk-mixing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0dbe9f72fb53dcf422c25f65a80ce0d33feacea --- /dev/null +++ b/tasks/critical-sk-mixing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CriticalSKMixing, i.e. module OAI.MathematicalPhysics.CriticalMixing.Main and the +# 593 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.CriticalMixing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CriticalSKMixing" diff --git a/tasks/critical-sk-mixing/task.toml b/tasks/critical-sk-mixing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d44553a80e65861e91226759cc532cdf5cc8b426 --- /dev/null +++ b/tasks/critical-sk-mixing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/critical-sk-mixing" +version = "1.0.0" +description = "Prove CriticalSKMixing (openai/math family 227: The dynamical phase transition in the Sherrington–Kirkpatrick model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CriticalSKMixing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CriticalSKMixing" +family = "227" +family_title = "The dynamical phase transition in the Sherrington–Kirkpatrick model" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CriticalSK.critical_mixing_bounds"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.CriticalMixing.Main" +reference_modules = 593 +reference_lean_bytes = 5600145 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2139 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 16740 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/critical-sk-mixing/tests/Challenge.lean b/tasks/critical-sk-mixing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..990194ad19caefcfa7a5c4ecd104051a91b6f3ba --- /dev/null +++ b/tasks/critical-sk-mixing/tests/Challenge.lean @@ -0,0 +1,79 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators Topology NNReal ENNReal +open MeasureTheory ProbabilityTheory Filter + +noncomputable section +namespace CriticalSK + +abbrev Spin (n : ℕ) := Fin n → Bool + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +abbrev Disorder (n : ℕ) := Edge n → ℝ + +def spinValue (b : Bool) : ℝ := if b then 1 else -1 + +def hamiltonian {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + ∑ e : Edge n, W e * spinValue (x e.val.1) * spinValue (x e.val.2) + +def partition {n : ℕ} (W : Disorder n) : ℝ := + ∑ x : Spin n, Real.exp (hamiltonian W x) + +def gibbs {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + Real.exp (hamiltonian W x) / partition W + +def disorderLaw (n : ℕ) : Measure (Disorder n) := + Measure.pi fun _ : Edge n => gaussianReal 0 (n : ℝ≥0)⁻¹ + +def sameExcept {n : ℕ} (i : Fin n) (x y : Spin n) : Prop := + ∀ j, j ≠ i → y j = x j + +instance {n : ℕ} (i : Fin n) (x y : Spin n) : Decidable (sameExcept i x y) := + Classical.propDecidable _ + +def siteKernel {n : ℕ} (W : Disorder n) (i : Fin n) : Matrix (Spin n) (Spin n) ℝ := + fun x y => if sameExcept i x y then + gibbs W y / (∑ z : Spin n, if sameExcept i x z then gibbs W z else 0) + else 0 + +def discreteKernel {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + (n : ℝ)⁻¹ • ∑ i : Fin n, siteKernel W i + +def generator {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + ∑ i : Fin n, (siteKernel W i - 1) + +def continuousKernel {n : ℕ} (W : Disorder n) (t : ℝ) : + Matrix (Spin n) (Spin n) ℝ := + NormedSpace.exp (t • generator W) + +def totalVariation {n : ℕ} (W : Disorder n) (p : Spin n → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ y : Spin n, |p y - gibbs W y| + +def continuousDistance {n : ℕ} (W : Disorder n) (t : ℝ) (x : Spin n) : ℝ := + totalVariation W (continuousKernel W t x) + +def discreteDistance {n : ℕ} (W : Disorder n) (k : ℕ) (x : Spin n) : ℝ := + totalVariation W ((discreteKernel W ^ k) x) + +def continuousMixingTime {n : ℕ} (W : Disorder n) : ℝ := + sInf {t : ℝ | 0 ≤ t ∧ ∀ x, continuousDistance W t x ≤ 1 / 4} + +def discreteMixingTime {n : ℕ} (W : Disorder n) : ℕ := + sInf {k : ℕ | ∀ x, discreteDistance W k x ≤ 1 / 4} + +theorem critical_mixing_bounds (ε : ℝ) (hε : 0 < ε) : + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((2 : ℝ) / 3 - ε) ≤ continuousMixingTime W ∧ + continuousMixingTime W ≤ Real.exp (ε * n)}).toReal) atTop (𝓝 1) ∧ + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((5 : ℝ) / 3 - ε) ≤ (discreteMixingTime W : ℝ) ∧ + (discreteMixingTime W : ℝ) ≤ Real.exp (ε * n)}).toReal) atTop (𝓝 1) := by + sorry + +end CriticalSK +end + +end OAI diff --git a/tasks/critical-sk-mixing/tests/grade.py b/tasks/critical-sk-mixing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/critical-sk-mixing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/critical-sk-mixing/tests/task.json b/tasks/critical-sk-mixing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7486c15d35c034184b788f04a72ea3fded1e16d7 --- /dev/null +++ b/tasks/critical-sk-mixing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CriticalSKMixing", + "comparator": { + "theorem_names": [ + "OAI.CriticalSK.critical_mixing_bounds" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 15840 +} \ No newline at end of file diff --git a/tasks/critical-sk-mixing/tests/test.sh b/tasks/critical-sk-mixing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/critical-sk-mixing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/critical-sk/environment/Dockerfile b/tasks/critical-sk/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/critical-sk/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/critical-sk/environment/fetch_mathlib.sh b/tasks/critical-sk/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/critical-sk/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/critical-sk/environment/lake-manifest.json b/tasks/critical-sk/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/critical-sk/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/critical-sk/environment/lakefile.lean b/tasks/critical-sk/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/critical-sk/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/critical-sk/environment/lean_setup.sh b/tasks/critical-sk/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/critical-sk/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/critical-sk/environment/pack_submission.py b/tasks/critical-sk/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/critical-sk/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/critical-sk/instruction.md b/tasks/critical-sk/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..301bbb5c1cb54871eaf744a20f937e1e8571be1b --- /dev/null +++ b/tasks/critical-sk/instruction.md @@ -0,0 +1,200 @@ +# openai/math challenge `CriticalSK` (family 227) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 227 of the release, *The dynamical phase transition in the Sherrington–Kirkpatrick model* +(Probability and statistical mechanics). The family as a whole: For zero-field Gaussian SK heat-bath dynamics with rate-one updates per spin, proves worst-start cutoff on the $\log n$ scale for fixed $0\le\beta<1$, mixing time $n^{2/3+o(1)}$ at $\beta=1$, and stretched-exponential mixing from a Gibbs-sampled fixed starting configuration for $\beta>1$, in probability over disorder. At criticality, rescaled stationary and quench autocorrelation processes have universal random limits for Gaussian and Rademacher disorder; the quench limit relaxes to the stationary limit. + +The challenge is `CriticalSK`, also at `/opt/openai-math/challenges/CriticalSK.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Critical SK equilibrium starts, covariance, and mixing lower bounds + +The zero-field model has independent Gaussian edge couplings of variance `1 / n`. +Continuous heat bath updates each site at rate one; a discrete attempt chooses a +site uniformly. Distances and mixing times use total variation threshold `1 / 4`. +-/ + +noncomputable section + +open scoped BigOperators Topology NNReal ENNReal +open MeasureTheory ProbabilityTheory Filter + +namespace CriticalSK + +abbrev Spin (n : ℕ) := Fin n → Bool + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +abbrev Disorder (n : ℕ) := Edge n → ℝ + +def spinValue (b : Bool) : ℝ := if b then 1 else -1 + +def hamiltonian {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + ∑ e : Edge n, W e * spinValue (x e.val.1) * spinValue (x e.val.2) + +def partition {n : ℕ} (W : Disorder n) : ℝ := + ∑ x : Spin n, Real.exp (hamiltonian W x) + +def gibbs {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + Real.exp (hamiltonian W x) / partition W + +def disorderLaw (n : ℕ) : Measure (Disorder n) := + Measure.pi fun _ : Edge n => gaussianReal 0 (n : ℝ≥0)⁻¹ + +def sameExcept {n : ℕ} (i : Fin n) (x y : Spin n) : Prop := + ∀ j, j ≠ i → y j = x j + +instance {n : ℕ} (i : Fin n) (x y : Spin n) : Decidable (sameExcept i x y) := + Classical.propDecidable _ + +def siteKernel {n : ℕ} (W : Disorder n) (i : Fin n) : Matrix (Spin n) (Spin n) ℝ := + fun x y => if sameExcept i x y then + gibbs W y / (∑ z : Spin n, if sameExcept i x z then gibbs W z else 0) + else 0 + +def discreteKernel {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + (n : ℝ)⁻¹ • ∑ i : Fin n, siteKernel W i + +def generator {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + ∑ i : Fin n, (siteKernel W i - 1) + +def continuousKernel {n : ℕ} (W : Disorder n) (t : ℝ) : + Matrix (Spin n) (Spin n) ℝ := + NormedSpace.exp (t • generator W) + +def totalVariation {n : ℕ} (W : Disorder n) (p : Spin n → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ y : Spin n, |p y - gibbs W y| + +def continuousDistance {n : ℕ} (W : Disorder n) (t : ℝ) (x : Spin n) : ℝ := + totalVariation W (continuousKernel W t x) + +def discreteDistance {n : ℕ} (W : Disorder n) (k : ℕ) (x : Spin n) : ℝ := + totalVariation W ((discreteKernel W ^ k) x) + +def continuousMixingTime {n : ℕ} (W : Disorder n) : ℝ := + sInf {t : ℝ | 0 ≤ t ∧ ∀ x, continuousDistance W t x ≤ 1 / 4} + +def discreteMixingTime {n : ℕ} (W : Disorder n) : ℕ := + sInf {k : ℕ | ∀ x, discreteDistance W k x ≤ 1 / 4} + +def mean {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + ∑ x : Spin n, gibbs W x * f x + +def variance {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + mean W (fun x => (f x - mean W f) ^ 2) + +def dirichlet {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + ∑ i : Fin n, mean W (fun x => (f x - ∑ y : Spin n, siteKernel W i x y * f y) ^ 2) + +def linearObservable {n : ℕ} (a : Fin n → ℝ) (x : Spin n) : ℝ := + ∑ i : Fin n, a i * spinValue (x i) + +def covariance {n : ℕ} (W : Disorder n) : Matrix (Fin n) (Fin n) ℝ := + fun i j => mean W (fun x => + (spinValue (x i) - mean W (fun y => spinValue (y i))) * + (spinValue (x j) - mean W (fun y => spinValue (y j)))) + +def covarianceNorm {n : ℕ} (W : Disorder n) : ℝ := + ‖(covariance W).toEuclideanLin.toContinuousLinearMap‖ + +/-- The supremum of variance divided by the rate-one Dirichlet form over nonzero +linear spin observables. -/ +def linearRayleigh {n : ℕ} (W : Disorder n) : ℝ := + sSup {r : ℝ | ∃ a : Fin n → ℝ, a ≠ 0 ∧ + r = variance W (linearObservable a) / dirichlet W (linearObservable a)} + +/-- Gibbs mass of realized initial states still farther than `1 / 4` from equilibrium. -/ +def continuousGoodMass {n : ℕ} (W : Disorder n) (t : ℝ) : ℝ := + ∑ x : Spin n, if 1 / 4 < continuousDistance W t x then gibbs W x else 0 + +/-- Gibbs mass of realized initial states still farther than `1 / 4` after `k` attempts. -/ +def discreteGoodMass {n : ℕ} (W : Disorder n) (k : ℕ) : ℝ := + ∑ x : Spin n, if 1 / 4 < discreteDistance W k x then gibbs W x else 0 + +/-- For deterministic nonnegative times `o(n^(2/3))` and attempt counts `o(n^(5/3))`, +the Gibbs mass of obstructed initial states tends to one in disorder probability. -/ +theorem realized_equilibrium_initial_states : + (∀ t : ℕ → ℝ, (∀ n, 0 ≤ t n) → + Tendsto (fun n => t n / (n : ℝ) ^ ((2 : ℝ) / 3)) atTop (𝓝 0) → + ∀ δ : ℝ, 0 < δ → + Tendsto (fun n => (disorderLaw n {W | + δ ≤ |continuousGoodMass W (t n) - 1|}).toReal) atTop (𝓝 0)) ∧ + (∀ k : ℕ → ℕ, + Tendsto (fun n => (k n : ℝ) / (n : ℝ) ^ ((5 : ℝ) / 3)) atTop (𝓝 0) → + ∀ δ : ℝ, 0 < δ → + Tendsto (fun n => (disorderLaw n {W | + δ ≤ |discreteGoodMass W (k n) - 1|}).toReal) atTop (𝓝 0)) := by + sorry + +/-- Both the covariance operator norm and the linear inverse-Rayleigh supremum lie +between `n^(2/3) / M n` and `M n * n^(2/3)` with probability tending to one. -/ +theorem covariance_and_linear_tests (M : ℕ → ℝ) + (hMpos : ∀ n, 0 < M n) (hM : Tendsto M atTop atTop) : + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((2 : ℝ) / 3) / M n ≤ covarianceNorm W ∧ + covarianceNorm W ≤ M n * (n : ℝ) ^ ((2 : ℝ) / 3) ∧ + (n : ℝ) ^ ((2 : ℝ) / 3) / M n ≤ linearRayleigh W ∧ + linearRayleigh W ≤ M n * (n : ℝ) ^ ((2 : ℝ) / 3)}).toReal) atTop (𝓝 1) := by + sorry + +/-- Worst-start mixing takes at least `n^(2/3-ε)` continuous time and +`n^(5/3-ε)` discrete attempts with probability tending to one. -/ +theorem critical_mixing_lower_bounds (ε : ℝ) (hε : 0 < ε) : + Tendsto (fun n => (disorderLaw n).real {W | + (n : ℝ) ^ (2 / 3 - ε) ≤ continuousMixingTime W}) atTop (𝓝 1) ∧ + Tendsto (fun n => (disorderLaw n).real {W | + (n : ℝ) ^ (5 / 3 - ε) ≤ (discreteMixingTime W : ℝ)}) atTop (𝓝 1) := by + sorry + +end CriticalSK + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CriticalSK.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.CriticalSK.realized_equilibrium_initial_states`, `OAI.CriticalSK.covariance_and_linear_tests`, `OAI.CriticalSK.critical_mixing_lower_bounds` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/critical-sk/solution/closure.txt b/tasks/critical-sk/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ec1a4a6f7e17302fc5496a3e573c604192bea85 --- /dev/null +++ b/tasks/critical-sk/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.MathematicalPhysics.CriticalSK.BlockEnergy +OAI.MathematicalPhysics.CriticalSK.Cavity +OAI.MathematicalPhysics.CriticalSK.Covariance +OAI.MathematicalPhysics.CriticalSK.CubeOverlap +OAI.MathematicalPhysics.CriticalSK.CubeRestriction +OAI.MathematicalPhysics.CriticalSK.DisorderTransfer +OAI.MathematicalPhysics.CriticalSK.EdgeAsymptotics +OAI.MathematicalPhysics.CriticalSK.Equilibrium +OAI.MathematicalPhysics.CriticalSK.GOESpectrum +OAI.MathematicalPhysics.CriticalSK.GapMixing +OAI.MathematicalPhysics.CriticalSK.GaussianConcentration +OAI.MathematicalPhysics.CriticalSK.GaussianMatrices +OAI.MathematicalPhysics.CriticalSK.GaussianMoments +OAI.MathematicalPhysics.CriticalSK.Gibbs +OAI.MathematicalPhysics.CriticalSK.HeatBath +OAI.MathematicalPhysics.CriticalSK.HighTemperature +OAI.MathematicalPhysics.CriticalSK.Main +OAI.MathematicalPhysics.CriticalSK.MinMax +OAI.MathematicalPhysics.CriticalSK.Mixing +OAI.MathematicalPhysics.CriticalSK.OrientationBounds +OAI.MathematicalPhysics.CriticalSK.OrientationLimits +OAI.MathematicalPhysics.CriticalSK.OverlapMoments +OAI.MathematicalPhysics.CriticalSK.PartitionBounds +OAI.MathematicalPhysics.CriticalSK.PathEnergy +OAI.MathematicalPhysics.CriticalSK.PathSpectra +OAI.MathematicalPhysics.CriticalSK.Powers +OAI.MathematicalPhysics.CriticalSK.Rayleigh +OAI.MathematicalPhysics.CriticalSK.Resolvent +OAI.MathematicalPhysics.CriticalSK.Saddle +OAI.MathematicalPhysics.CriticalSK.SaddleLimit +OAI.MathematicalPhysics.CriticalSK.SmallBall +OAI.MathematicalPhysics.CriticalSK.SphereGeometry +OAI.MathematicalPhysics.CriticalSK.SphereSaddle +OAI.MathematicalPhysics.CriticalSK.SpinModel +OAI.MathematicalPhysics.CriticalSK.TriNoise diff --git a/tasks/critical-sk/solution/reference.py b/tasks/critical-sk/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/critical-sk/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/critical-sk/solution/solve.sh b/tasks/critical-sk/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..257b65ffc74e67e04fbe2230a5daca45c26ebfd6 --- /dev/null +++ b/tasks/critical-sk/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CriticalSK, i.e. module OAI.MathematicalPhysics.CriticalSK.Main and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.CriticalSK.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CriticalSK" diff --git a/tasks/critical-sk/task.toml b/tasks/critical-sk/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2f4dce2546294a1748040330c336195679d4b7bb --- /dev/null +++ b/tasks/critical-sk/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/critical-sk" +version = "1.0.0" +description = "Prove CriticalSK (openai/math family 227: The dynamical phase transition in the Sherrington–Kirkpatrick model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CriticalSK.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CriticalSK" +family = "227" +family_title = "The dynamical phase transition in the Sherrington–Kirkpatrick model" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CriticalSK.realized_equilibrium_initial_states", "OAI.CriticalSK.covariance_and_linear_tests", "OAI.CriticalSK.critical_mixing_lower_bounds"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.CriticalSK.Main" +reference_modules = 35 +reference_lean_bytes = 890802 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 892 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12501 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/critical-sk/tests/Challenge.lean b/tasks/critical-sk/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..aa91eb181022691cd57798d89d23c42b7d67dded --- /dev/null +++ b/tasks/critical-sk/tests/Challenge.lean @@ -0,0 +1,149 @@ +import Mathlib + +namespace OAI + +/-! +# Critical SK equilibrium starts, covariance, and mixing lower bounds + +The zero-field model has independent Gaussian edge couplings of variance `1 / n`. +Continuous heat bath updates each site at rate one; a discrete attempt chooses a +site uniformly. Distances and mixing times use total variation threshold `1 / 4`. +-/ + +noncomputable section + +open scoped BigOperators Topology NNReal ENNReal +open MeasureTheory ProbabilityTheory Filter + +namespace CriticalSK + +abbrev Spin (n : ℕ) := Fin n → Bool + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +abbrev Disorder (n : ℕ) := Edge n → ℝ + +def spinValue (b : Bool) : ℝ := if b then 1 else -1 + +def hamiltonian {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + ∑ e : Edge n, W e * spinValue (x e.val.1) * spinValue (x e.val.2) + +def partition {n : ℕ} (W : Disorder n) : ℝ := + ∑ x : Spin n, Real.exp (hamiltonian W x) + +def gibbs {n : ℕ} (W : Disorder n) (x : Spin n) : ℝ := + Real.exp (hamiltonian W x) / partition W + +def disorderLaw (n : ℕ) : Measure (Disorder n) := + Measure.pi fun _ : Edge n => gaussianReal 0 (n : ℝ≥0)⁻¹ + +def sameExcept {n : ℕ} (i : Fin n) (x y : Spin n) : Prop := + ∀ j, j ≠ i → y j = x j + +instance {n : ℕ} (i : Fin n) (x y : Spin n) : Decidable (sameExcept i x y) := + Classical.propDecidable _ + +def siteKernel {n : ℕ} (W : Disorder n) (i : Fin n) : Matrix (Spin n) (Spin n) ℝ := + fun x y => if sameExcept i x y then + gibbs W y / (∑ z : Spin n, if sameExcept i x z then gibbs W z else 0) + else 0 + +def discreteKernel {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + (n : ℝ)⁻¹ • ∑ i : Fin n, siteKernel W i + +def generator {n : ℕ} (W : Disorder n) : Matrix (Spin n) (Spin n) ℝ := + ∑ i : Fin n, (siteKernel W i - 1) + +def continuousKernel {n : ℕ} (W : Disorder n) (t : ℝ) : + Matrix (Spin n) (Spin n) ℝ := + NormedSpace.exp (t • generator W) + +def totalVariation {n : ℕ} (W : Disorder n) (p : Spin n → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ y : Spin n, |p y - gibbs W y| + +def continuousDistance {n : ℕ} (W : Disorder n) (t : ℝ) (x : Spin n) : ℝ := + totalVariation W (continuousKernel W t x) + +def discreteDistance {n : ℕ} (W : Disorder n) (k : ℕ) (x : Spin n) : ℝ := + totalVariation W ((discreteKernel W ^ k) x) + +def continuousMixingTime {n : ℕ} (W : Disorder n) : ℝ := + sInf {t : ℝ | 0 ≤ t ∧ ∀ x, continuousDistance W t x ≤ 1 / 4} + +def discreteMixingTime {n : ℕ} (W : Disorder n) : ℕ := + sInf {k : ℕ | ∀ x, discreteDistance W k x ≤ 1 / 4} + +def mean {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + ∑ x : Spin n, gibbs W x * f x + +def variance {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + mean W (fun x => (f x - mean W f) ^ 2) + +def dirichlet {n : ℕ} (W : Disorder n) (f : Spin n → ℝ) : ℝ := + ∑ i : Fin n, mean W (fun x => (f x - ∑ y : Spin n, siteKernel W i x y * f y) ^ 2) + +def linearObservable {n : ℕ} (a : Fin n → ℝ) (x : Spin n) : ℝ := + ∑ i : Fin n, a i * spinValue (x i) + +def covariance {n : ℕ} (W : Disorder n) : Matrix (Fin n) (Fin n) ℝ := + fun i j => mean W (fun x => + (spinValue (x i) - mean W (fun y => spinValue (y i))) * + (spinValue (x j) - mean W (fun y => spinValue (y j)))) + +def covarianceNorm {n : ℕ} (W : Disorder n) : ℝ := + ‖(covariance W).toEuclideanLin.toContinuousLinearMap‖ + +/-- The supremum of variance divided by the rate-one Dirichlet form over nonzero +linear spin observables. -/ +def linearRayleigh {n : ℕ} (W : Disorder n) : ℝ := + sSup {r : ℝ | ∃ a : Fin n → ℝ, a ≠ 0 ∧ + r = variance W (linearObservable a) / dirichlet W (linearObservable a)} + +/-- Gibbs mass of realized initial states still farther than `1 / 4` from equilibrium. -/ +def continuousGoodMass {n : ℕ} (W : Disorder n) (t : ℝ) : ℝ := + ∑ x : Spin n, if 1 / 4 < continuousDistance W t x then gibbs W x else 0 + +/-- Gibbs mass of realized initial states still farther than `1 / 4` after `k` attempts. -/ +def discreteGoodMass {n : ℕ} (W : Disorder n) (k : ℕ) : ℝ := + ∑ x : Spin n, if 1 / 4 < discreteDistance W k x then gibbs W x else 0 + +/-- For deterministic nonnegative times `o(n^(2/3))` and attempt counts `o(n^(5/3))`, +the Gibbs mass of obstructed initial states tends to one in disorder probability. -/ +theorem realized_equilibrium_initial_states : + (∀ t : ℕ → ℝ, (∀ n, 0 ≤ t n) → + Tendsto (fun n => t n / (n : ℝ) ^ ((2 : ℝ) / 3)) atTop (𝓝 0) → + ∀ δ : ℝ, 0 < δ → + Tendsto (fun n => (disorderLaw n {W | + δ ≤ |continuousGoodMass W (t n) - 1|}).toReal) atTop (𝓝 0)) ∧ + (∀ k : ℕ → ℕ, + Tendsto (fun n => (k n : ℝ) / (n : ℝ) ^ ((5 : ℝ) / 3)) atTop (𝓝 0) → + ∀ δ : ℝ, 0 < δ → + Tendsto (fun n => (disorderLaw n {W | + δ ≤ |discreteGoodMass W (k n) - 1|}).toReal) atTop (𝓝 0)) := by + sorry + +/-- Both the covariance operator norm and the linear inverse-Rayleigh supremum lie +between `n^(2/3) / M n` and `M n * n^(2/3)` with probability tending to one. -/ +theorem covariance_and_linear_tests (M : ℕ → ℝ) + (hMpos : ∀ n, 0 < M n) (hM : Tendsto M atTop atTop) : + Tendsto (fun n : ℕ => (disorderLaw n {W | + (n : ℝ) ^ ((2 : ℝ) / 3) / M n ≤ covarianceNorm W ∧ + covarianceNorm W ≤ M n * (n : ℝ) ^ ((2 : ℝ) / 3) ∧ + (n : ℝ) ^ ((2 : ℝ) / 3) / M n ≤ linearRayleigh W ∧ + linearRayleigh W ≤ M n * (n : ℝ) ^ ((2 : ℝ) / 3)}).toReal) atTop (𝓝 1) := by + sorry + +/-- Worst-start mixing takes at least `n^(2/3-ε)` continuous time and +`n^(5/3-ε)` discrete attempts with probability tending to one. -/ +theorem critical_mixing_lower_bounds (ε : ℝ) (hε : 0 < ε) : + Tendsto (fun n => (disorderLaw n).real {W | + (n : ℝ) ^ (2 / 3 - ε) ≤ continuousMixingTime W}) atTop (𝓝 1) ∧ + Tendsto (fun n => (disorderLaw n).real {W | + (n : ℝ) ^ (5 / 3 - ε) ≤ (discreteMixingTime W : ℝ)}) atTop (𝓝 1) := by + sorry + +end CriticalSK + +end + +end OAI diff --git a/tasks/critical-sk/tests/grade.py b/tasks/critical-sk/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/critical-sk/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/critical-sk/tests/task.json b/tasks/critical-sk/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1ee559d33385459b65b9fafeae872336baff8bd9 --- /dev/null +++ b/tasks/critical-sk/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "CriticalSK", + "comparator": { + "theorem_names": [ + "OAI.CriticalSK.realized_equilibrium_initial_states", + "OAI.CriticalSK.covariance_and_linear_tests", + "OAI.CriticalSK.critical_mixing_lower_bounds" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11601 +} \ No newline at end of file diff --git a/tasks/critical-sk/tests/test.sh b/tasks/critical-sk/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/critical-sk/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/critical-strip-mass/environment/Dockerfile b/tasks/critical-strip-mass/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/critical-strip-mass/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/critical-strip-mass/environment/fetch_mathlib.sh b/tasks/critical-strip-mass/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/critical-strip-mass/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/critical-strip-mass/environment/lake-manifest.json b/tasks/critical-strip-mass/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/critical-strip-mass/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/critical-strip-mass/environment/lakefile.lean b/tasks/critical-strip-mass/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/critical-strip-mass/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/critical-strip-mass/environment/lean_setup.sh b/tasks/critical-strip-mass/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/critical-strip-mass/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/critical-strip-mass/environment/pack_submission.py b/tasks/critical-strip-mass/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/critical-strip-mass/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/critical-strip-mass/instruction.md b/tasks/critical-strip-mass/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb8c02d6bbe5e3f21b4a2d76ce532274ac180d98 --- /dev/null +++ b/tasks/critical-strip-mass/instruction.md @@ -0,0 +1,133 @@ +# openai/math challenge `CriticalStripMass` (family 237) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 237 of the release, *The three-quarter diameter exponent for honeycomb walks* +(Probability and statistical mechanics). The family as a whole: Proves the diameter form of Nienhuis's predicted three-quarter exponent: a uniformly chosen $n$-step self-avoiding walk on the honeycomb lattice has diameter $n^{3/4+o(1)}$. Its local mass and covering numbers have exponent $4/3$. These estimates hold at every sufficiently large fixed length, simultaneously across scales, with arbitrarily high polynomial probability. + +The challenge is `CriticalStripMass`, also at `/opt/openai-math/challenges/CriticalStripMass.lean`: + +```lean +import Mathlib + +namespace OAI + + + +namespace CriticalStrip + +noncomputable section +open scoped BigOperators +open Set MeasureTheory + +def rho : ℝ := 1 / Real.sqrt (2 + Real.sqrt 2) +def c : ℝ := Real.cos (3 * Real.pi / 8) +def lambda : ℝ := Real.pi / 8 +def d : ℝ := Real.cos (2 * lambda) +def C : ℝ := Real.cos lambda +def eta : ℝ := 2 * d - 1 + +abbrev Triangle := ℤ × ℕ × Bool + +def up (i : ℤ) (j : ℕ) : Triangle := (i, j, true) +def down (i : ℤ) (j : ℕ) : Triangle := (i, j, false) + +def upDownAdjacent (v w : Triangle) : Prop := + v.2.2 = true ∧ w.2.2 = false ∧ + ((v.2.1 = w.2.1 ∧ (w.1 = v.1 ∨ w.1 + 1 = v.1)) ∨ + (v.2.1 = w.2.1 + 1 ∧ v.1 = w.1)) + +def adjacent (v w : Triangle) : Prop := upDownAdjacent v w ∨ upDownAdjacent w v + + +def IsPath (N : ℕ) (finish : Triangle) (p : List Triangle) : Prop := + p.head? = some (up 0 0) ∧ p.getLast? = some finish ∧ p.Nodup ∧ + p.IsChain adjacent ∧ ∀ v ∈ p, v.2.1 < N + + +def archWeight (N : ℕ) (k : ℤ) (p : List Triangle) : ℝ := by + classical + exact if k ≠ 0 ∧ IsPath N (up k 0) p then rho ^ p.length else 0 + + +def bridgeWeight (N : ℕ) (k : ℤ) (p : List Triangle) : ℝ := by + classical + exact if 0 < N ∧ IsPath N (down k (N - 1)) p then rho ^ p.length else 0 + +def K (N : ℕ) (k : ℤ) : ℝ := ∑' p, archWeight N k p +def bridgeKernel (N : ℕ) (k : ℤ) : ℝ := ∑' p, bridgeWeight N k p +def archMass (N : ℕ) : ℝ := ∑' k : ℤ, K N k +def bridgeMass (N : ℕ) : ℝ := ∑' k : ℤ, bridgeKernel N k +def moment (N : ℕ) : ℝ := ∑' k : ℕ, (k + 1 : ℝ) * K N (k + 1) + + +def StripSumsFinite (N : ℕ) : Prop := + (∀ k : ℤ, Summable (archWeight N k)) ∧ + (∀ k : ℤ, Summable (bridgeWeight N k)) ∧ + Summable (K N) ∧ Summable (bridgeKernel N) ∧ + Summable (fun k : ℕ => (k + 1 : ℝ) * K N (k + 1)) + + +def Comparable (f g : ℕ → ℝ) : Prop := + ∃ lo hi : ℝ, 0 < lo ∧ 0 < hi ∧ + ∀ N : ℕ, 1 ≤ N → lo * g N ≤ f N ∧ f N ≤ hi * g N + + +def CriticalStripMass : Prop := + (∀ N : ℕ, 1 ≤ N → StripSumsFinite N) ∧ + (∀ N : ℕ, 1 ≤ N → c * archMass N + bridgeMass N = 1) ∧ + Comparable (fun N => moment (N + 1) - moment N) bridgeMass ∧ + Comparable moment (fun N => (N : ℝ) ^ (3 / 4 : ℝ)) ∧ + Comparable bridgeMass (fun N => (N : ℝ) ^ (-(1 / 4) : ℝ)) ∧ + (∀ N : ℕ, 1 ≤ N → bridgeMass (N + 1) ≤ bridgeMass N) + + + +theorem critical_strip_mass : CriticalStripMass := by + sorry + +end +end CriticalStrip + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CriticalStripMass.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CriticalStrip.critical_strip_mass` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/critical-strip-mass/solution/closure.txt b/tasks/critical-strip-mass/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc824ca96fa6b6079f7f3aa849a93078a0ffa60f --- /dev/null +++ b/tasks/critical-strip-mass/solution/closure.txt @@ -0,0 +1,130 @@ +OAI.Combinatorics.StripMass.ArchIntegrals +OAI.Combinatorics.StripMass.ArchRoots +OAI.Combinatorics.StripMass.ArchTrig +OAI.Combinatorics.StripMass.AugmentedColumn +OAI.Combinatorics.StripMass.AugmentedTail +OAI.Combinatorics.StripMass.Basic +OAI.Combinatorics.StripMass.BlockPfaffian +OAI.Combinatorics.StripMass.BottomGauge +OAI.Combinatorics.StripMass.BottomPadding +OAI.Combinatorics.StripMass.BoundaryTree +OAI.Combinatorics.StripMass.BridgeUnfold +OAI.Combinatorics.StripMass.CauchyMatrices +OAI.Combinatorics.StripMass.CollisionLeaf +OAI.Combinatorics.StripMass.CollisionSubstitutions +OAI.Combinatorics.StripMass.ColumnGeometry +OAI.Combinatorics.StripMass.ColumnSew +OAI.Combinatorics.StripMass.ColumnSweep +OAI.Combinatorics.StripMass.CoordinateBoxes +OAI.Combinatorics.StripMass.CramerBounds +OAI.Combinatorics.StripMass.CutPatch +OAI.Combinatorics.StripMass.CutStateSound +OAI.Combinatorics.StripMass.DeficitBounds +OAI.Combinatorics.StripMass.DeformationWeights +OAI.Combinatorics.StripMass.DensityExhaustion +OAI.Combinatorics.StripMass.DiagonalFactors +OAI.Combinatorics.StripMass.FiniteEnds +OAI.Combinatorics.StripMass.FirstFlatSpecialization +OAI.Combinatorics.StripMass.FirstThree +OAI.Combinatorics.StripMass.FluxWindow +OAI.Combinatorics.StripMass.FreshGate +OAI.Combinatorics.StripMass.GraphPath +OAI.Combinatorics.StripMass.HalfTurn +OAI.Combinatorics.StripMass.HeightOne +OAI.Combinatorics.StripMass.HoneycombClip +OAI.Combinatorics.StripMass.HoneycombDictionary +OAI.Combinatorics.StripMass.HoneycombTiles +OAI.Combinatorics.StripMass.InterpolantCovariance +OAI.Combinatorics.StripMass.InverseIntegrability +OAI.Combinatorics.StripMass.InverseMoments +OAI.Combinatorics.StripMass.LaguerreNormalization +OAI.Combinatorics.StripMass.LaguerreScaling +OAI.Combinatorics.StripMass.LaguerreTails +OAI.Combinatorics.StripMass.LastRow +OAI.Combinatorics.StripMass.LaurentBox +OAI.Combinatorics.StripMass.LaurentNumerator +OAI.Combinatorics.StripMass.LocalPadding +OAI.Combinatorics.StripMass.Main +OAI.Combinatorics.StripMass.MergePairCandidate +OAI.Combinatorics.StripMass.MirrorExterior +OAI.Combinatorics.StripMass.MomentGrowth +OAI.Combinatorics.StripMass.MonicPositive +OAI.Combinatorics.StripMass.NodalEmpty +OAI.Combinatorics.StripMass.NodalExchange +OAI.Combinatorics.StripMass.NodalNodes +OAI.Combinatorics.StripMass.NodalRegularity +OAI.Combinatorics.StripMass.NodalScalarDeletion +OAI.Combinatorics.StripMass.NodalTorusValue +OAI.Combinatorics.StripMass.NorthBijection +OAI.Combinatorics.StripMass.NorthGluing +OAI.Combinatorics.StripMass.NorthMass +OAI.Combinatorics.StripMass.NorthMerging +OAI.Combinatorics.StripMass.PairCoordinates +OAI.Combinatorics.StripMass.PairSelfNode +OAI.Combinatorics.StripMass.PairingDiagrams +OAI.Combinatorics.StripMass.PairingSurgery +OAI.Combinatorics.StripMass.PatchReplacement +OAI.Combinatorics.StripMass.PfaffianConfluentLimit +OAI.Combinatorics.StripMass.PfaffianEvaluation +OAI.Combinatorics.StripMass.PfaffianIntegration +OAI.Combinatorics.StripMass.PfaffianMatrices +OAI.Combinatorics.StripMass.PfaffianRecursion +OAI.Combinatorics.StripMass.PfaffianSupport +OAI.Combinatorics.StripMass.PhaseAlgebra +OAI.Combinatorics.StripMass.PhysicalPorts +OAI.Combinatorics.StripMass.PhysicalStationarity +OAI.Combinatorics.StripMass.PolynomialDegrees +OAI.Combinatorics.StripMass.PositiveAssociation +OAI.Combinatorics.StripMass.ProjectionInjection +OAI.Combinatorics.StripMass.QuarterMoments +OAI.Combinatorics.StripMass.QuarticIntegrals +OAI.Combinatorics.StripMass.RealEvaluation +OAI.Combinatorics.StripMass.ReflectionFractions +OAI.Combinatorics.StripMass.ReflectionIntegrals +OAI.Combinatorics.StripMass.ResidualEvaluation +OAI.Combinatorics.StripMass.ResidualParityCoefficients +OAI.Combinatorics.StripMass.RestrictedDiagrams +OAI.Combinatorics.StripMass.ReversedConvergence +OAI.Combinatorics.StripMass.RibbonGlobal +OAI.Combinatorics.StripMass.RibbonLocal +OAI.Combinatorics.StripMass.RibbonWalk +OAI.Combinatorics.StripMass.RightStieltjes +OAI.Combinatorics.StripMass.RootOfUnityPowers +OAI.Combinatorics.StripMass.ScalarBridge +OAI.Combinatorics.StripMass.ScalarDegree +OAI.Combinatorics.StripMass.ScalarDeleteContinuation +OAI.Combinatorics.StripMass.ScalarFlat +OAI.Combinatorics.StripMass.ScalarMergeTrig +OAI.Combinatorics.StripMass.SchurIdentity +OAI.Combinatorics.StripMass.SewnAssignment +OAI.Combinatorics.StripMass.SidePaths +OAI.Combinatorics.StripMass.Specialization +OAI.Combinatorics.StripMass.SpecializationPolynomial +OAI.Combinatorics.StripMass.SpectralComponents +OAI.Combinatorics.StripMass.SplitGluing +OAI.Combinatorics.StripMass.SplitProjection +OAI.Combinatorics.StripMass.StepComplete +OAI.Combinatorics.StripMass.StepToCut +OAI.Combinatorics.StripMass.StieltjesLimits +OAI.Combinatorics.StripMass.SwapVacancy +OAI.Combinatorics.StripMass.TailIntegrals +OAI.Combinatorics.StripMass.ThreeBoxBraidPolynomial +OAI.Combinatorics.StripMass.ThreeBoxCertificates +OAI.Combinatorics.StripMass.ThreeBoxProfiles +OAI.Combinatorics.StripMass.ThreeBoxSplitPolynomial +OAI.Combinatorics.StripMass.ThreeBoxWeights +OAI.Combinatorics.StripMass.TopPadding +OAI.Combinatorics.StripMass.Trigonometry +OAI.Combinatorics.StripMass.TripleCircuit +OAI.Combinatorics.StripMass.TriplePatch +OAI.Combinatorics.StripMass.TurnDisk +OAI.Combinatorics.StripMass.TurnEvolution +OAI.Combinatorics.StripMass.TurnGate +OAI.Combinatorics.StripMass.TurnRectangleMatching +OAI.Combinatorics.StripMass.TurnRhombus +OAI.Combinatorics.StripMass.TurnShelling +OAI.Combinatorics.StripMass.TurnWideGate +OAI.Combinatorics.StripMass.VacuumClosure +OAI.Combinatorics.StripMass.VacuumDegree +OAI.Combinatorics.StripMass.WeightComparison +OAI.Combinatorics.StripMass.WireContraction diff --git a/tasks/critical-strip-mass/solution/reference.py b/tasks/critical-strip-mass/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/critical-strip-mass/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/critical-strip-mass/solution/solve.sh b/tasks/critical-strip-mass/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..947a658895a4cbc4d4369d06c9bfc70671096749 --- /dev/null +++ b/tasks/critical-strip-mass/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CriticalStripMass, i.e. module OAI.Combinatorics.StripMass.Main and the +# 130 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.StripMass.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CriticalStripMass" diff --git a/tasks/critical-strip-mass/task.toml b/tasks/critical-strip-mass/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5c64e824b6a7d1cd166f2e41360c34b9df25e35 --- /dev/null +++ b/tasks/critical-strip-mass/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/critical-strip-mass" +version = "1.0.0" +description = "Prove CriticalStripMass (openai/math family 237: The three-quarter diameter exponent for honeycomb walks) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CriticalStripMass.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CriticalStripMass" +family = "237" +family_title = "The three-quarter diameter exponent for honeycomb walks" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CriticalStrip.critical_strip_mass"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.StripMass.Main" +reference_modules = 130 +reference_lean_bytes = 2796916 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1959 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14217 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/critical-strip-mass/tests/Challenge.lean b/tasks/critical-strip-mass/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..635595fc4054a796ccfd1977fb0b060ec42917ed --- /dev/null +++ b/tasks/critical-strip-mass/tests/Challenge.lean @@ -0,0 +1,82 @@ +import Mathlib + +namespace OAI + + + +namespace CriticalStrip + +noncomputable section +open scoped BigOperators +open Set MeasureTheory + +def rho : ℝ := 1 / Real.sqrt (2 + Real.sqrt 2) +def c : ℝ := Real.cos (3 * Real.pi / 8) +def lambda : ℝ := Real.pi / 8 +def d : ℝ := Real.cos (2 * lambda) +def C : ℝ := Real.cos lambda +def eta : ℝ := 2 * d - 1 + +abbrev Triangle := ℤ × ℕ × Bool + +def up (i : ℤ) (j : ℕ) : Triangle := (i, j, true) +def down (i : ℤ) (j : ℕ) : Triangle := (i, j, false) + +def upDownAdjacent (v w : Triangle) : Prop := + v.2.2 = true ∧ w.2.2 = false ∧ + ((v.2.1 = w.2.1 ∧ (w.1 = v.1 ∨ w.1 + 1 = v.1)) ∨ + (v.2.1 = w.2.1 + 1 ∧ v.1 = w.1)) + +def adjacent (v w : Triangle) : Prop := upDownAdjacent v w ∨ upDownAdjacent w v + + +def IsPath (N : ℕ) (finish : Triangle) (p : List Triangle) : Prop := + p.head? = some (up 0 0) ∧ p.getLast? = some finish ∧ p.Nodup ∧ + p.IsChain adjacent ∧ ∀ v ∈ p, v.2.1 < N + + +def archWeight (N : ℕ) (k : ℤ) (p : List Triangle) : ℝ := by + classical + exact if k ≠ 0 ∧ IsPath N (up k 0) p then rho ^ p.length else 0 + + +def bridgeWeight (N : ℕ) (k : ℤ) (p : List Triangle) : ℝ := by + classical + exact if 0 < N ∧ IsPath N (down k (N - 1)) p then rho ^ p.length else 0 + +def K (N : ℕ) (k : ℤ) : ℝ := ∑' p, archWeight N k p +def bridgeKernel (N : ℕ) (k : ℤ) : ℝ := ∑' p, bridgeWeight N k p +def archMass (N : ℕ) : ℝ := ∑' k : ℤ, K N k +def bridgeMass (N : ℕ) : ℝ := ∑' k : ℤ, bridgeKernel N k +def moment (N : ℕ) : ℝ := ∑' k : ℕ, (k + 1 : ℝ) * K N (k + 1) + + +def StripSumsFinite (N : ℕ) : Prop := + (∀ k : ℤ, Summable (archWeight N k)) ∧ + (∀ k : ℤ, Summable (bridgeWeight N k)) ∧ + Summable (K N) ∧ Summable (bridgeKernel N) ∧ + Summable (fun k : ℕ => (k + 1 : ℝ) * K N (k + 1)) + + +def Comparable (f g : ℕ → ℝ) : Prop := + ∃ lo hi : ℝ, 0 < lo ∧ 0 < hi ∧ + ∀ N : ℕ, 1 ≤ N → lo * g N ≤ f N ∧ f N ≤ hi * g N + + +def CriticalStripMass : Prop := + (∀ N : ℕ, 1 ≤ N → StripSumsFinite N) ∧ + (∀ N : ℕ, 1 ≤ N → c * archMass N + bridgeMass N = 1) ∧ + Comparable (fun N => moment (N + 1) - moment N) bridgeMass ∧ + Comparable moment (fun N => (N : ℝ) ^ (3 / 4 : ℝ)) ∧ + Comparable bridgeMass (fun N => (N : ℝ) ^ (-(1 / 4) : ℝ)) ∧ + (∀ N : ℕ, 1 ≤ N → bridgeMass (N + 1) ≤ bridgeMass N) + + + +theorem critical_strip_mass : CriticalStripMass := by + sorry + +end +end CriticalStrip + +end OAI diff --git a/tasks/critical-strip-mass/tests/grade.py b/tasks/critical-strip-mass/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/critical-strip-mass/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/critical-strip-mass/tests/task.json b/tasks/critical-strip-mass/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..777b6c23a5b4960490a528d40222c1541fa92f04 --- /dev/null +++ b/tasks/critical-strip-mass/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CriticalStripMass", + "comparator": { + "theorem_names": [ + "OAI.CriticalStrip.critical_strip_mass" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13317 +} \ No newline at end of file diff --git a/tasks/critical-strip-mass/tests/test.sh b/tasks/critical-strip-mass/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/critical-strip-mass/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/critical-z3/environment/Dockerfile b/tasks/critical-z3/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/critical-z3/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/critical-z3/environment/fetch_mathlib.sh b/tasks/critical-z3/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/critical-z3/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/critical-z3/environment/lake-manifest.json b/tasks/critical-z3/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/critical-z3/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/critical-z3/environment/lakefile.lean b/tasks/critical-z3/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/critical-z3/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/critical-z3/environment/lean_setup.sh b/tasks/critical-z3/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/critical-z3/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/critical-z3/environment/pack_submission.py b/tasks/critical-z3/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/critical-z3/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/critical-z3/instruction.md b/tasks/critical-z3/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a39ffdc8918fcdb4291bef97284aa0c0aecd321f --- /dev/null +++ b/tasks/critical-z3/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `CriticalZ3` (family 213) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 213 of the release, *No infinite critical clusters on quasi-transitive graphs* +(Probability and statistical mechanics). The family as a whole: Resolves the Benjamini–Schramm criticality conjecture for bond percolation on every infinite connected locally finite quasi-transitive graph with $p_c<1$: at the critical probability, there is almost surely no infinite cluster. The family also establishes this conclusion for both nearest-neighbor bond and site percolation on $\mathbb Z^3$. + +The challenge is `CriticalZ3`, also at `/opt/openai-math/challenges/CriticalZ3.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory + +namespace CriticalZ3 + +abbrev Vertex := Fin 3 → ℤ +abbrev Bond := Vertex × Fin 3 +abbrev BondConfig := Bond → Bool +abbrev SiteConfig := Vertex → Bool + +def step (x : Vertex) (i : Fin 3) : Vertex := fun j => x j + if i = j then 1 else 0 + +def NearestNeighbor (x y : Vertex) : Prop := + ∃ i : Fin 3, y = step x i ∨ x = step y i + +def BondOpen (ω : BondConfig) (x y : Vertex) : Prop := + (∃ i : Fin 3, y = step x i ∧ ω (x, i) = true) ∨ + (∃ i : Fin 3, x = step y i ∧ ω (y, i) = true) + +def SiteOpen (ω : SiteConfig) (x y : Vertex) : Prop := + NearestNeighbor x y ∧ ω x = true ∧ ω y = true + +def BondConnected (ω : BondConfig) (x y : Vertex) : Prop := + Relation.ReflTransGen (BondOpen ω) x y + +def SiteConnected (ω : SiteConfig) (x y : Vertex) : Prop := + ω x = true ∧ Relation.ReflTransGen (SiteOpen ω) x y + +def bondCluster (ω : BondConfig) (x : Vertex) : Set Vertex := + {y | BondConnected ω x y} + +def siteCluster (ω : SiteConfig) (x : Vertex) : Set Vertex := + {y | SiteConnected ω x y} + +def bondInfiniteAt (x : Vertex) : Set BondConfig := {ω | (bondCluster ω x).Infinite} +def siteInfiniteAt (x : Vertex) : Set SiteConfig := {ω | (siteCluster ω x).Infinite} + +noncomputable def parameter (p : ℝ) : Set.Icc (0 : ℝ) 1 := + ⟨max 0 (min 1 p), le_max_left _ _, max_le (by norm_num) (min_le_left _ _)⟩ + +noncomputable def bondLaw (p : ℝ) : Measure BondConfig := + Measure.infinitePi (fun _ : Bond => bernoulliMeasure true false (parameter p)) + +noncomputable def siteLaw (p : ℝ) : Measure SiteConfig := + Measure.infinitePi (fun _ : Vertex => bernoulliMeasure true false (parameter p)) + +noncomputable def bondCritical : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ 0 < bondLaw p (bondInfiniteAt 0)} + +noncomputable def siteCritical : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ 0 < siteLaw p (siteInfiniteAt 0)} + +theorem critical_no_infinite : + (∀ᵐ ω ∂bondLaw bondCritical, ∀ x : Vertex, (bondCluster ω x).Finite) ∧ + (∀ᵐ ω ∂siteLaw siteCritical, ∀ x : Vertex, (siteCluster ω x).Finite) := by + sorry + +end CriticalZ3 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CriticalZ3.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CriticalZ3.critical_no_infinite` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/critical-z3/solution/closure.txt b/tasks/critical-z3/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9d51318c1a8984f623fd6fd74bdd657b48c91ce8 --- /dev/null +++ b/tasks/critical-z3/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Probability.CriticalZ3.AdaptiveReveals +OAI.Probability.CriticalZ3.Basic +OAI.Probability.CriticalZ3.BoxGeometry +OAI.Probability.CriticalZ3.Coarse +OAI.Probability.CriticalZ3.ConditionalQuality +OAI.Probability.CriticalZ3.Conditioning +OAI.Probability.CriticalZ3.EntryLayers +OAI.Probability.CriticalZ3.Exploration +OAI.Probability.CriticalZ3.ExplorationConnectivity +OAI.Probability.CriticalZ3.ExplorationInvariant +OAI.Probability.CriticalZ3.ExplorationProbability +OAI.Probability.CriticalZ3.ExplorationSurvival +OAI.Probability.CriticalZ3.Extension +OAI.Probability.CriticalZ3.FiniteTrails +OAI.Probability.CriticalZ3.HyperedgeComparison +OAI.Probability.CriticalZ3.LatticeGraph +OAI.Probability.CriticalZ3.LatticePaths +OAI.Probability.CriticalZ3.Main +OAI.Probability.CriticalZ3.Matching +OAI.Probability.CriticalZ3.Model +OAI.Probability.CriticalZ3.Peierls +OAI.Probability.CriticalZ3.PlanarBoundary +OAI.Probability.CriticalZ3.ProductCylinder +OAI.Probability.CriticalZ3.QuarterFaces +OAI.Probability.CriticalZ3.Relay +OAI.Probability.CriticalZ3.RelayProbability +OAI.Probability.CriticalZ3.Resampling +OAI.Probability.CriticalZ3.Scales +OAI.Probability.CriticalZ3.SeedQuality +OAI.Probability.CriticalZ3.SeedTrials +OAI.Probability.CriticalZ3.ShellProbability +OAI.Probability.CriticalZ3.Subunit +OAI.Probability.CriticalZ3.Symmetry +OAI.Probability.CriticalZ3.TrialCounts diff --git a/tasks/critical-z3/solution/reference.py b/tasks/critical-z3/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/critical-z3/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/critical-z3/solution/solve.sh b/tasks/critical-z3/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c9b8d331944cc3b6d94a95a68004ffefdd17858 --- /dev/null +++ b/tasks/critical-z3/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CriticalZ3, i.e. module OAI.Probability.CriticalZ3.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.CriticalZ3.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CriticalZ3" diff --git a/tasks/critical-z3/task.toml b/tasks/critical-z3/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..218c15bda28e4246eb7638f51a6858a68bda6cd0 --- /dev/null +++ b/tasks/critical-z3/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/critical-z3" +version = "1.0.0" +description = "Prove CriticalZ3 (openai/math family 213: No infinite critical clusters on quasi-transitive graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CriticalZ3.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CriticalZ3" +family = "213" +family_title = "No infinite critical clusters on quasi-transitive graphs" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CriticalZ3.critical_no_infinite"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.CriticalZ3.Main" +reference_modules = 34 +reference_lean_bytes = 461840 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 859 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12115 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/critical-z3/tests/Challenge.lean b/tasks/critical-z3/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..56e93b89a55e098ad924270cd85ec9f5754fd57f --- /dev/null +++ b/tasks/critical-z3/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory + +namespace CriticalZ3 + +abbrev Vertex := Fin 3 → ℤ +abbrev Bond := Vertex × Fin 3 +abbrev BondConfig := Bond → Bool +abbrev SiteConfig := Vertex → Bool + +def step (x : Vertex) (i : Fin 3) : Vertex := fun j => x j + if i = j then 1 else 0 + +def NearestNeighbor (x y : Vertex) : Prop := + ∃ i : Fin 3, y = step x i ∨ x = step y i + +def BondOpen (ω : BondConfig) (x y : Vertex) : Prop := + (∃ i : Fin 3, y = step x i ∧ ω (x, i) = true) ∨ + (∃ i : Fin 3, x = step y i ∧ ω (y, i) = true) + +def SiteOpen (ω : SiteConfig) (x y : Vertex) : Prop := + NearestNeighbor x y ∧ ω x = true ∧ ω y = true + +def BondConnected (ω : BondConfig) (x y : Vertex) : Prop := + Relation.ReflTransGen (BondOpen ω) x y + +def SiteConnected (ω : SiteConfig) (x y : Vertex) : Prop := + ω x = true ∧ Relation.ReflTransGen (SiteOpen ω) x y + +def bondCluster (ω : BondConfig) (x : Vertex) : Set Vertex := + {y | BondConnected ω x y} + +def siteCluster (ω : SiteConfig) (x : Vertex) : Set Vertex := + {y | SiteConnected ω x y} + +def bondInfiniteAt (x : Vertex) : Set BondConfig := {ω | (bondCluster ω x).Infinite} +def siteInfiniteAt (x : Vertex) : Set SiteConfig := {ω | (siteCluster ω x).Infinite} + +noncomputable def parameter (p : ℝ) : Set.Icc (0 : ℝ) 1 := + ⟨max 0 (min 1 p), le_max_left _ _, max_le (by norm_num) (min_le_left _ _)⟩ + +noncomputable def bondLaw (p : ℝ) : Measure BondConfig := + Measure.infinitePi (fun _ : Bond => bernoulliMeasure true false (parameter p)) + +noncomputable def siteLaw (p : ℝ) : Measure SiteConfig := + Measure.infinitePi (fun _ : Vertex => bernoulliMeasure true false (parameter p)) + +noncomputable def bondCritical : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ 0 < bondLaw p (bondInfiniteAt 0)} + +noncomputable def siteCritical : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ 0 < siteLaw p (siteInfiniteAt 0)} + +theorem critical_no_infinite : + (∀ᵐ ω ∂bondLaw bondCritical, ∀ x : Vertex, (bondCluster ω x).Finite) ∧ + (∀ᵐ ω ∂siteLaw siteCritical, ∀ x : Vertex, (siteCluster ω x).Finite) := by + sorry + +end CriticalZ3 + +end OAI diff --git a/tasks/critical-z3/tests/grade.py b/tasks/critical-z3/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/critical-z3/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/critical-z3/tests/task.json b/tasks/critical-z3/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..51cd9a4d0067461b50ba86946118903b2c0debaf --- /dev/null +++ b/tasks/critical-z3/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CriticalZ3", + "comparator": { + "theorem_names": [ + "OAI.CriticalZ3.critical_no_infinite" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11215 +} \ No newline at end of file diff --git a/tasks/critical-z3/tests/test.sh b/tasks/critical-z3/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/critical-z3/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/crouzeix-hilbert/environment/Dockerfile b/tasks/crouzeix-hilbert/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/crouzeix-hilbert/environment/fetch_mathlib.sh b/tasks/crouzeix-hilbert/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/crouzeix-hilbert/environment/lake-manifest.json b/tasks/crouzeix-hilbert/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/crouzeix-hilbert/environment/lakefile.lean b/tasks/crouzeix-hilbert/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/crouzeix-hilbert/environment/lean_setup.sh b/tasks/crouzeix-hilbert/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/crouzeix-hilbert/environment/pack_submission.py b/tasks/crouzeix-hilbert/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/crouzeix-hilbert/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/crouzeix-hilbert/instruction.md b/tasks/crouzeix-hilbert/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea0a63e2fe63513c3900b089bb82e3b02a141e82 --- /dev/null +++ b/tasks/crouzeix-hilbert/instruction.md @@ -0,0 +1,209 @@ +# openai/math challenge `CrouzeixHilbert` (family 325) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 325 of the release, *The complete Crouzeix conjecture* +(Functional analysis). The family as a whole: Resolves the complete Crouzeix conjecture: for every bounded operator $A$ on a complex Hilbert space and every finite matrix-valued polynomial $P$, one has $\lVert P[A]\rVert\le2\sup_{z\in W(A)}\lVert P(z)\rVert$, where $W(A)$ is the numerical range. The constant $2$ is sharp, independent of the matrix size, and valid in infinite dimensions. + +The challenge is `CrouzeixHilbert`, also at `/opt/openai-math/challenges/CrouzeixHilbert.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! The sharp complete inequality for bounded operators on complex Hilbert spaces. -/ + +noncomputable section + +open scoped TensorProduct Matrix.Norms.L2Operator InnerProductSpace +open Set + +namespace CrouzeixHilbert + +universe u + +abbrev Operator (H : Type u) [NormedAddCommGroup H] [NormedSpace ℂ H] := H →L[ℂ] H +abbrev Coeff (m : ℕ) := Matrix (Fin m) (Fin m) ℂ + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +def numericalRange (A : Operator H) : Set ℂ := + {z | ∃ x : H, ‖x‖ = 1 ∧ ⟪x, A x⟫_ℂ = z} + +def numericalClosure (A : Operator H) : Set ℂ := closure (numericalRange A) + +def supNorm {E : Type*} [NormedAddCommGroup E] (S : Set ℂ) (F : ℂ → E) : ℝ := + sSup (insert 0 ((fun z => ‖F z‖) '' S)) + +abbrev Amplification (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (m : ℕ) := UniformSpace.Completion (H ⊗[ℂ] EuclideanSpace ℂ (Fin m)) + +def tensorOperator (A : Operator H) {m : ℕ} (B : Coeff m) : + Operator (Amplification H m) := + (TensorProduct.mapL A (Matrix.toEuclideanCLM (𝕜 := ℂ) (n := Fin m) B)).completion + +def matrixPolynomial {m d : ℕ} (B : Fin (d + 1) → Coeff m) (z : ℂ) : Coeff m := + ∑ k : Fin (d + 1), z ^ (k : ℕ) • B k + +def polynomialEval (A : Operator H) {m d : ℕ} (B : Fin (d + 1) → Coeff m) : + Operator (Amplification H m) := + ∑ k : Fin (d + 1), tensorOperator (A ^ (k : ℕ)) (B k) + +structure SmoothContour where + path : ℝ → ℂ + smooth : ContDiff ℝ 1 path + closed : path 0 = path 1 + +def SmoothContour.index (Γ : SmoothContour) (z : ℂ) : ℂ := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ * + ∫ t in (0 : ℝ)..1, deriv Γ.path t / (Γ.path t - z) + +structure CalculusContour (K U : Set ℂ) extends SmoothContour where + avoids : ∀ t ∈ Icc (0 : ℝ) 1, path t ∈ U \ K + index_inside : ∀ z ∈ K, toSmoothContour.index z = 1 + index_outside : ∀ z ∉ U, toSmoothContour.index z = 0 + +def contourEval (A : Operator H) (Γ : SmoothContour) (f : ℂ → ℂ) : Operator H := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ • + ∫ t in (0 : ℝ)..1, (deriv Γ.path t * f (Γ.path t)) • + Ring.inverse (algebraMap ℂ (Operator H) (Γ.path t) - A) + +def holomorphicEval (A : Operator H) (U : Set ℂ) (f : ℂ → ℂ) : Operator H := by + classical + exact if h : Nonempty (CalculusContour (numericalClosure A) U) then + contourEval A (Classical.choice h).toSmoothContour f + else 0 + +def matrixHolomorphicEval (A : Operator H) {m : ℕ} (U : Set ℂ) + (F : ℂ → Coeff m) : Operator (Amplification H m) := + ∑ i, ∑ j, tensorOperator (holomorphicEval A U (fun z => F z i j)) + (Matrix.single i j 1) + +def EntrywiseHolomorphic {m : ℕ} (U : Set ℂ) (F : ℂ → Coeff m) : Prop := + ∀ i j, DifferentiableOn ℂ (fun z => F z i j) U + +abbrev RationalMatrix (m : ℕ) := Matrix (Fin m) (Fin m) (RatFunc ℂ) + +def PolesOutside {m : ℕ} (K : Set ℂ) (R : RationalMatrix m) : Prop := + ∀ i j z, z ∈ K → (R i j).denom.eval z ≠ 0 + +def matrixRationalFunction {m : ℕ} (R : RationalMatrix m) (z : ℂ) : Coeff m := + fun i j => RatFunc.eval (RingHom.id ℂ) z (R i j) + +def rationalEval (A : Operator H) (r : RatFunc ℂ) : Operator H := + (Polynomial.aeval A r.num) * Ring.inverse (Polynomial.aeval A r.denom) + +def matrixRationalEval (A : Operator H) {m : ℕ} (R : RationalMatrix m) : + Operator (Amplification H m) := + ∑ i, ∑ j, tensorOperator (rationalEval A (R i j)) (Matrix.single i j 1) + +def NonzeroConclusion (A : Operator H) : Prop := + IsCompact (numericalClosure A) ∧ + Convex ℝ (numericalClosure A) ∧ + spectrum ℂ A ⊆ numericalClosure A ∧ + (∀ (m : ℕ), 0 < m → ∀ (d : ℕ) (B : Fin (d + 1) → Coeff m), + ‖polynomialEval A B‖ ≤ 2 * supNorm (numericalRange A) (matrixPolynomial B) ∧ + supNorm (numericalRange A) (matrixPolynomial B) = + supNorm (numericalClosure A) (matrixPolynomial B) ∧ + ∃ z ∈ numericalClosure A, + supNorm (numericalClosure A) (matrixPolynomial B) = ‖matrixPolynomial B z‖) ∧ + (∀ (m : ℕ), 0 < m → ∀ (U : Set ℂ) (F : ℂ → Coeff m), + IsOpen U → numericalClosure A ⊆ U → EntrywiseHolomorphic U F → + Nonempty (CalculusContour (numericalClosure A) U) ∧ + (∀ Γ : CalculusContour (numericalClosure A) U, ∀ i j, + holomorphicEval A U (fun z => F z i j) = + contourEval A Γ.toSmoothContour (fun z => F z i j)) ∧ + ‖matrixHolomorphicEval A U F‖ ≤ 2 * supNorm (numericalClosure A) F ∧ + ∃ z ∈ numericalClosure A, supNorm (numericalClosure A) F = ‖F z‖) ∧ + (∀ (m : ℕ), 0 < m → ∀ (R : RationalMatrix m), + PolesOutside (numericalClosure A) R → + (∀ i j, IsUnit (Polynomial.aeval A (R i j).denom)) ∧ + ‖matrixRationalEval A R‖ ≤ + 2 * supNorm (numericalClosure A) (matrixRationalFunction R) ∧ + (∃ z ∈ numericalClosure A, + supNorm (numericalClosure A) (matrixRationalFunction R) = + ‖matrixRationalFunction R z‖) ∧ + ∃ U : Set ℂ, IsOpen U ∧ numericalClosure A ⊆ U ∧ + EntrywiseHolomorphic U (matrixRationalFunction R) ∧ + matrixRationalEval A R = matrixHolomorphicEval A U (matrixRationalFunction R)) + +def ZeroConclusion (A : Operator H) : Prop := + numericalRange A = ∅ ∧ + (∀ (m d : ℕ) (B : Fin (d + 1) → Coeff m), + polynomialEval A B = 0 ∧ + supNorm (numericalRange A) (matrixPolynomial B) = 0 ∧ + ‖polynomialEval A B‖ ≤ 2 * supNorm (numericalRange A) (matrixPolynomial B)) ∧ + (∀ (m : ℕ) (U : Set ℂ) (F : ℂ → Coeff m), + matrixHolomorphicEval A U F = 0 ∧ + supNorm (numericalRange A) F = 0 ∧ + ‖matrixHolomorphicEval A U F‖ ≤ 2 * supNorm (numericalRange A) F) ∧ + (∀ (m : ℕ) (R : RationalMatrix m), + matrixRationalEval A R = 0 ∧ + supNorm (numericalRange A) (matrixRationalFunction R) = 0 ∧ + ‖matrixRationalEval A R‖ ≤ + 2 * supNorm (numericalRange A) (matrixRationalFunction R)) + +def SharpConstant : Prop := + ∃ (A : Operator (EuclideanSpace ℂ (Fin 2))) (B : Fin 2 → Coeff 1), + supNorm (numericalRange A) (matrixPolynomial (d := 1) B) = 1 ∧ + ‖polynomialEval A (d := 1) B‖ = 2 + +end CrouzeixHilbert + +namespace CrouzeixHilbert + +universe u + +theorem hilbert (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (A : Operator H) : + (Nontrivial H → NonzeroConclusion A) ∧ + (Subsingleton H → ZeroConclusion A) ∧ SharpConstant := by + sorry + +end CrouzeixHilbert + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CrouzeixHilbert.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CrouzeixHilbert.hilbert` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/crouzeix-hilbert/solution/closure.txt b/tasks/crouzeix-hilbert/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..71dfe50c4f88740a04d4bfefaf1cadd1d1404c0f --- /dev/null +++ b/tasks/crouzeix-hilbert/solution/closure.txt @@ -0,0 +1,90 @@ +OAI.Analysis.Crouzeix.Amplification +OAI.Analysis.Crouzeix.AngularMeasure +OAI.Analysis.Crouzeix.AngularMoments +OAI.Analysis.Crouzeix.AngularRadius +OAI.Analysis.Crouzeix.AngularTransport +OAI.Analysis.Crouzeix.BlockPolynomial +OAI.Analysis.Crouzeix.BoundaryChart +OAI.Analysis.Crouzeix.BoundaryFibers +OAI.Analysis.Crouzeix.BoundaryForms +OAI.Analysis.Crouzeix.BoundaryKernel +OAI.Analysis.Crouzeix.BoundaryModulus +OAI.Analysis.Crouzeix.BoundaryMoments +OAI.Analysis.Crouzeix.BoundaryOperators +OAI.Analysis.Crouzeix.BoundaryPatching +OAI.Analysis.Crouzeix.CauchyProjection +OAI.Analysis.Crouzeix.CircleAnalytic +OAI.Analysis.Crouzeix.CircleCoordinate +OAI.Analysis.Crouzeix.CollarUnivalence +OAI.Analysis.Crouzeix.CompleteFinite +OAI.Analysis.Crouzeix.Compression +OAI.Analysis.Crouzeix.ConformalCollar +OAI.Analysis.Crouzeix.ContourExistence +OAI.Analysis.Crouzeix.ContourHomotopy +OAI.Analysis.Crouzeix.ContourPolynomials +OAI.Analysis.Crouzeix.ConvexApproximation +OAI.Analysis.Crouzeix.ConvexCoordinates +OAI.Analysis.Crouzeix.ConvexNeighborhood +OAI.Analysis.Crouzeix.Convexity +OAI.Analysis.Crouzeix.Definitions +OAI.Analysis.Crouzeix.Density +OAI.Analysis.Crouzeix.DensityCompatibility +OAI.Analysis.Crouzeix.DiskAutomorphism +OAI.Analysis.Crouzeix.DiskBoundaryChart +OAI.Analysis.Crouzeix.DiskCalculus +OAI.Analysis.Crouzeix.DiskEndpoint +OAI.Analysis.Crouzeix.DiskHolomorphic +OAI.Analysis.Crouzeix.Endpoint +OAI.Analysis.Crouzeix.EndpointInterpolation +OAI.Analysis.Crouzeix.ExteriorBoundaryChart +OAI.Analysis.Crouzeix.ExteriorCollar +OAI.Analysis.Crouzeix.ExteriorContour +OAI.Analysis.Crouzeix.ExteriorKernel +OAI.Analysis.Crouzeix.ExteriorNormal +OAI.Analysis.Crouzeix.ExteriorRiemann +OAI.Analysis.Crouzeix.Faber +OAI.Analysis.Crouzeix.FiniteCompression +OAI.Analysis.Crouzeix.Fourier +OAI.Analysis.Crouzeix.FunctionalComposition +OAI.Analysis.Crouzeix.HarmonicMaximum +OAI.Analysis.Crouzeix.HarmonicReflection +OAI.Analysis.Crouzeix.HilbertExtension +OAI.Analysis.Crouzeix.HilbertInequality +OAI.Analysis.Crouzeix.HolomorphicAlgebra +OAI.Analysis.Crouzeix.HolomorphicReflection +OAI.Analysis.Crouzeix.HolomorphicSpectrum +OAI.Analysis.Crouzeix.HomologicalCauchy +OAI.Analysis.Crouzeix.Hurwitz +OAI.Analysis.Crouzeix.InteriorCollar +OAI.Analysis.Crouzeix.Iteration +OAI.Analysis.Crouzeix.LaurentSplit +OAI.Analysis.Crouzeix.Main +OAI.Analysis.Crouzeix.MatrixContours +OAI.Analysis.Crouzeix.MatrixEndpoint +OAI.Analysis.Crouzeix.MetricBoundary +OAI.Analysis.Crouzeix.Montel +OAI.Analysis.Crouzeix.NumericalRange +OAI.Analysis.Crouzeix.PhysicalCalculus +OAI.Analysis.Crouzeix.PhysicalComparison +OAI.Analysis.Crouzeix.PhysicalDensity +OAI.Analysis.Crouzeix.PhysicalFourier +OAI.Analysis.Crouzeix.PhysicalModule +OAI.Analysis.Crouzeix.PhysicalProjection +OAI.Analysis.Crouzeix.PoissonExtension +OAI.Analysis.Crouzeix.PolynomialApproximation +OAI.Analysis.Crouzeix.RationalContours +OAI.Analysis.Crouzeix.RationalEvaluation +OAI.Analysis.Crouzeix.RationalTransfer +OAI.Analysis.Crouzeix.Realization +OAI.Analysis.Crouzeix.ReflectionDerivative +OAI.Analysis.Crouzeix.Resolvent +OAI.Analysis.Crouzeix.ResolventBounds +OAI.Analysis.Crouzeix.ResolventMoments +OAI.Analysis.Crouzeix.Riemann +OAI.Analysis.Crouzeix.SeparateHolomorphic +OAI.Analysis.Crouzeix.Sharpness +OAI.Analysis.Crouzeix.SimilarityRepresentation +OAI.Analysis.Crouzeix.SteinMetric +OAI.Analysis.Crouzeix.TensorDensity +OAI.Analysis.Crouzeix.Univalent +OAI.Analysis.Crouzeix.Vectorization diff --git a/tasks/crouzeix-hilbert/solution/reference.py b/tasks/crouzeix-hilbert/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/crouzeix-hilbert/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/crouzeix-hilbert/solution/solve.sh b/tasks/crouzeix-hilbert/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b7cf302b4d0707585c44a8ad3ff1ad9933586e1f --- /dev/null +++ b/tasks/crouzeix-hilbert/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CrouzeixHilbert, i.e. module OAI.Analysis.Crouzeix.Main and the +# 90 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Crouzeix.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CrouzeixHilbert" diff --git a/tasks/crouzeix-hilbert/task.toml b/tasks/crouzeix-hilbert/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49bbdc0bad4a55de59699357dbc101e5b444aff6 --- /dev/null +++ b/tasks/crouzeix-hilbert/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/crouzeix-hilbert" +version = "1.0.0" +description = "Prove CrouzeixHilbert (openai/math family 325: The complete Crouzeix conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CrouzeixHilbert.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CrouzeixHilbert" +family = "325" +family_title = "The complete Crouzeix conjecture" +subject = "Functional analysis" +theorems = ["OAI.CrouzeixHilbert.hilbert"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Crouzeix.Main" +reference_modules = 90 +reference_lean_bytes = 723645 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1215 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12351 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/crouzeix-hilbert/tests/Challenge.lean b/tasks/crouzeix-hilbert/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e0286b989fc1b0699fa9cfdf60fb667605cd9cb --- /dev/null +++ b/tasks/crouzeix-hilbert/tests/Challenge.lean @@ -0,0 +1,158 @@ +import Mathlib + +namespace OAI + +/-! The sharp complete inequality for bounded operators on complex Hilbert spaces. -/ + +noncomputable section + +open scoped TensorProduct Matrix.Norms.L2Operator InnerProductSpace +open Set + +namespace CrouzeixHilbert + +universe u + +abbrev Operator (H : Type u) [NormedAddCommGroup H] [NormedSpace ℂ H] := H →L[ℂ] H +abbrev Coeff (m : ℕ) := Matrix (Fin m) (Fin m) ℂ + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +def numericalRange (A : Operator H) : Set ℂ := + {z | ∃ x : H, ‖x‖ = 1 ∧ ⟪x, A x⟫_ℂ = z} + +def numericalClosure (A : Operator H) : Set ℂ := closure (numericalRange A) + +def supNorm {E : Type*} [NormedAddCommGroup E] (S : Set ℂ) (F : ℂ → E) : ℝ := + sSup (insert 0 ((fun z => ‖F z‖) '' S)) + +abbrev Amplification (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (m : ℕ) := UniformSpace.Completion (H ⊗[ℂ] EuclideanSpace ℂ (Fin m)) + +def tensorOperator (A : Operator H) {m : ℕ} (B : Coeff m) : + Operator (Amplification H m) := + (TensorProduct.mapL A (Matrix.toEuclideanCLM (𝕜 := ℂ) (n := Fin m) B)).completion + +def matrixPolynomial {m d : ℕ} (B : Fin (d + 1) → Coeff m) (z : ℂ) : Coeff m := + ∑ k : Fin (d + 1), z ^ (k : ℕ) • B k + +def polynomialEval (A : Operator H) {m d : ℕ} (B : Fin (d + 1) → Coeff m) : + Operator (Amplification H m) := + ∑ k : Fin (d + 1), tensorOperator (A ^ (k : ℕ)) (B k) + +structure SmoothContour where + path : ℝ → ℂ + smooth : ContDiff ℝ 1 path + closed : path 0 = path 1 + +def SmoothContour.index (Γ : SmoothContour) (z : ℂ) : ℂ := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ * + ∫ t in (0 : ℝ)..1, deriv Γ.path t / (Γ.path t - z) + +structure CalculusContour (K U : Set ℂ) extends SmoothContour where + avoids : ∀ t ∈ Icc (0 : ℝ) 1, path t ∈ U \ K + index_inside : ∀ z ∈ K, toSmoothContour.index z = 1 + index_outside : ∀ z ∉ U, toSmoothContour.index z = 0 + +def contourEval (A : Operator H) (Γ : SmoothContour) (f : ℂ → ℂ) : Operator H := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ • + ∫ t in (0 : ℝ)..1, (deriv Γ.path t * f (Γ.path t)) • + Ring.inverse (algebraMap ℂ (Operator H) (Γ.path t) - A) + +def holomorphicEval (A : Operator H) (U : Set ℂ) (f : ℂ → ℂ) : Operator H := by + classical + exact if h : Nonempty (CalculusContour (numericalClosure A) U) then + contourEval A (Classical.choice h).toSmoothContour f + else 0 + +def matrixHolomorphicEval (A : Operator H) {m : ℕ} (U : Set ℂ) + (F : ℂ → Coeff m) : Operator (Amplification H m) := + ∑ i, ∑ j, tensorOperator (holomorphicEval A U (fun z => F z i j)) + (Matrix.single i j 1) + +def EntrywiseHolomorphic {m : ℕ} (U : Set ℂ) (F : ℂ → Coeff m) : Prop := + ∀ i j, DifferentiableOn ℂ (fun z => F z i j) U + +abbrev RationalMatrix (m : ℕ) := Matrix (Fin m) (Fin m) (RatFunc ℂ) + +def PolesOutside {m : ℕ} (K : Set ℂ) (R : RationalMatrix m) : Prop := + ∀ i j z, z ∈ K → (R i j).denom.eval z ≠ 0 + +def matrixRationalFunction {m : ℕ} (R : RationalMatrix m) (z : ℂ) : Coeff m := + fun i j => RatFunc.eval (RingHom.id ℂ) z (R i j) + +def rationalEval (A : Operator H) (r : RatFunc ℂ) : Operator H := + (Polynomial.aeval A r.num) * Ring.inverse (Polynomial.aeval A r.denom) + +def matrixRationalEval (A : Operator H) {m : ℕ} (R : RationalMatrix m) : + Operator (Amplification H m) := + ∑ i, ∑ j, tensorOperator (rationalEval A (R i j)) (Matrix.single i j 1) + +def NonzeroConclusion (A : Operator H) : Prop := + IsCompact (numericalClosure A) ∧ + Convex ℝ (numericalClosure A) ∧ + spectrum ℂ A ⊆ numericalClosure A ∧ + (∀ (m : ℕ), 0 < m → ∀ (d : ℕ) (B : Fin (d + 1) → Coeff m), + ‖polynomialEval A B‖ ≤ 2 * supNorm (numericalRange A) (matrixPolynomial B) ∧ + supNorm (numericalRange A) (matrixPolynomial B) = + supNorm (numericalClosure A) (matrixPolynomial B) ∧ + ∃ z ∈ numericalClosure A, + supNorm (numericalClosure A) (matrixPolynomial B) = ‖matrixPolynomial B z‖) ∧ + (∀ (m : ℕ), 0 < m → ∀ (U : Set ℂ) (F : ℂ → Coeff m), + IsOpen U → numericalClosure A ⊆ U → EntrywiseHolomorphic U F → + Nonempty (CalculusContour (numericalClosure A) U) ∧ + (∀ Γ : CalculusContour (numericalClosure A) U, ∀ i j, + holomorphicEval A U (fun z => F z i j) = + contourEval A Γ.toSmoothContour (fun z => F z i j)) ∧ + ‖matrixHolomorphicEval A U F‖ ≤ 2 * supNorm (numericalClosure A) F ∧ + ∃ z ∈ numericalClosure A, supNorm (numericalClosure A) F = ‖F z‖) ∧ + (∀ (m : ℕ), 0 < m → ∀ (R : RationalMatrix m), + PolesOutside (numericalClosure A) R → + (∀ i j, IsUnit (Polynomial.aeval A (R i j).denom)) ∧ + ‖matrixRationalEval A R‖ ≤ + 2 * supNorm (numericalClosure A) (matrixRationalFunction R) ∧ + (∃ z ∈ numericalClosure A, + supNorm (numericalClosure A) (matrixRationalFunction R) = + ‖matrixRationalFunction R z‖) ∧ + ∃ U : Set ℂ, IsOpen U ∧ numericalClosure A ⊆ U ∧ + EntrywiseHolomorphic U (matrixRationalFunction R) ∧ + matrixRationalEval A R = matrixHolomorphicEval A U (matrixRationalFunction R)) + +def ZeroConclusion (A : Operator H) : Prop := + numericalRange A = ∅ ∧ + (∀ (m d : ℕ) (B : Fin (d + 1) → Coeff m), + polynomialEval A B = 0 ∧ + supNorm (numericalRange A) (matrixPolynomial B) = 0 ∧ + ‖polynomialEval A B‖ ≤ 2 * supNorm (numericalRange A) (matrixPolynomial B)) ∧ + (∀ (m : ℕ) (U : Set ℂ) (F : ℂ → Coeff m), + matrixHolomorphicEval A U F = 0 ∧ + supNorm (numericalRange A) F = 0 ∧ + ‖matrixHolomorphicEval A U F‖ ≤ 2 * supNorm (numericalRange A) F) ∧ + (∀ (m : ℕ) (R : RationalMatrix m), + matrixRationalEval A R = 0 ∧ + supNorm (numericalRange A) (matrixRationalFunction R) = 0 ∧ + ‖matrixRationalEval A R‖ ≤ + 2 * supNorm (numericalRange A) (matrixRationalFunction R)) + +def SharpConstant : Prop := + ∃ (A : Operator (EuclideanSpace ℂ (Fin 2))) (B : Fin 2 → Coeff 1), + supNorm (numericalRange A) (matrixPolynomial (d := 1) B) = 1 ∧ + ‖polynomialEval A (d := 1) B‖ = 2 + +end CrouzeixHilbert + +namespace CrouzeixHilbert + +universe u + +theorem hilbert (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (A : Operator H) : + (Nontrivial H → NonzeroConclusion A) ∧ + (Subsingleton H → ZeroConclusion A) ∧ SharpConstant := by + sorry + +end CrouzeixHilbert + +end + +end OAI diff --git a/tasks/crouzeix-hilbert/tests/grade.py b/tasks/crouzeix-hilbert/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/crouzeix-hilbert/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/crouzeix-hilbert/tests/task.json b/tasks/crouzeix-hilbert/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6034e4a3c435aeaacf7c6282588d6f95d755c5f3 --- /dev/null +++ b/tasks/crouzeix-hilbert/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CrouzeixHilbert", + "comparator": { + "theorem_names": [ + "OAI.CrouzeixHilbert.hilbert" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11451 +} \ No newline at end of file diff --git a/tasks/crouzeix-hilbert/tests/test.sh b/tasks/crouzeix-hilbert/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/crouzeix-hilbert/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cubic-torus/environment/Dockerfile b/tasks/cubic-torus/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cubic-torus/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cubic-torus/environment/fetch_mathlib.sh b/tasks/cubic-torus/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cubic-torus/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cubic-torus/environment/lake-manifest.json b/tasks/cubic-torus/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cubic-torus/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cubic-torus/environment/lakefile.lean b/tasks/cubic-torus/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cubic-torus/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cubic-torus/environment/lean_setup.sh b/tasks/cubic-torus/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cubic-torus/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cubic-torus/environment/pack_submission.py b/tasks/cubic-torus/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cubic-torus/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cubic-torus/instruction.md b/tasks/cubic-torus/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b68830d89a983bbf30fe10368b40d199ea8b41f --- /dev/null +++ b/tasks/cubic-torus/instruction.md @@ -0,0 +1,149 @@ +# openai/math challenge `CubicTorus` (family 354) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 354 of the release, *Isoperimetric regions in the cubic three-torus* +(Differential geometry). The family as a whole: Determines the isoperimetric profile of the unit cubic flat three-torus and classifies every finite-perimeter minimizer: balls, circular tubes around shortest closed geodesics, coordinate slabs, and their complements. The transition volumes are $4\pi/81$ and $1/\pi$, with exactly the adjacent two types minimizing at each transition. + +The challenge is `CubicTorus`, also at `/opt/openai-math/challenges/CubicTorus.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Set +open scoped ENNReal + +namespace CubicTorus + +abbrev Cover := EuclideanSpace ℝ (Fin 3) +abbrev Torus := PiLp 2 (fun _ : Fin 3 => AddCircle (1 : ℝ)) + +/-- The quotient R³ → R³/Z³ in orthonormal coordinates. -/ +def quotientMap (x : Cover) : Torus := + WithLp.toLp 2 (fun i => (x i : AddCircle (1 : ℝ))) + +/-- One unit-volume fundamental domain; its boundary is immaterial to integration. -/ +def fundamentalCube : Set Cover := {x | ∀ i, 0 ≤ x i ∧ x i < 1} + +/-- The Riemannian volume measure of the unit flat torus. -/ +def torusVolume : Measure Torus := + Measure.map quotientMap (volume.restrict fundamentalCube) + +/-- An integer lattice vector in the Euclidean cover. -/ +def latticeVector (n : Fin 3 → ℤ) : Cover := WithLp.toLp 2 (fun i => (n i : ℝ)) + +/-- The smooth vector fields on the flat torus with pointwise length at most one, +expressed as Z³-periodic fields on its Euclidean cover. The explicit ℕ∞ index +is C^∞; top of WithTop ℕ∞ would instead mean analytic in this Mathlib. -/ +def AdmissibleField (F : Cover → Cover) : Prop := + ContDiff ℝ (⊤ : ℕ∞) F ∧ + (∀ (n : Fin 3 → ℤ) (x : Cover), F (x + latticeVector n) = F x) ∧ + ∀ x, ‖F x‖ ≤ 1 + +/-- Euclidean divergence in the orthonormal coordinate frame. -/ +def divergence (F : Cover → Cover) (x : Cover) : ℝ := + ∑ i : Fin 3, (fderiv ℝ F x (EuclideanSpace.single i 1)) i + +/-- De Giorgi perimeter, allowed to be infinite; no regularity of E is imposed. -/ +def perimeter (E : Set Torus) : ℝ≥0∞ := + ⨆ (F : Cover → Cover) (_ : AdmissibleField F), + ENNReal.ofReal (∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x) + +/-- Finite-perimeter measurable regions, including all null-set modifications. -/ +def FinitePerimeter (E : Set Torus) : Prop := + NullMeasurableSet E torusVolume ∧ perimeter E < ⊤ + +/-- A global perimeter minimizer under the prescribed volume constraint. -/ +def IsMinimizerAt (V : ℝ) (E : Set Torus) : Prop := + FinitePerimeter E ∧ torusVolume E = ENNReal.ofReal V ∧ + ∀ F : Set Torus, FinitePerimeter F → torusVolume F = ENNReal.ofReal V → + perimeter E ≤ perimeter F + +/-- The candidate unit-torus isoperimetric profile. -/ +def candidateProfile (V : ℝ) : ℝ := + let v := min V (1 - V) + min ((36 * Real.pi) ^ (1 / 3 : ℝ) * v ^ (2 / 3 : ℝ)) + (min (2 * Real.sqrt (Real.pi * v)) 2) + +/-- Canonical centered ball. Its radius on the listed branch is below 1/2. -/ +def canonicalBall (V : ℝ) : Set Torus := + Metric.ball 0 ((3 * V / (4 * Real.pi)) ^ (1 / 3 : ℝ)) + +/-- Canonical tube around the shortest closed geodesic in coordinate direction 0. -/ +def canonicalTube (V : ℝ) : Set Torus := + {x | ‖x 1‖ ^ 2 + ‖x 2‖ ^ 2 < (Real.sqrt (V / Real.pi)) ^ 2} + +/-- Canonical slab of width V between two parallel coordinate tori. -/ +def canonicalSlab (V : ℝ) : Set Torus := {x | ‖x 0‖ < V / 2} + +/-- Equality of regions up to ambient flat isometry and a null set. -/ +def CongruentAE (E F : Set Torus) : Prop := + ∃ φ : Torus ≃ᵢ Torus, E =ᵐ[torusVolume] (φ '' F) + +/-- Exactly the closed phase ranges, so adjacent types are BOTH included at ties. -/ +def SmallStandardRegion (V : ℝ) (E : Set Torus) : Prop := + (V ≤ 4 * Real.pi / 81 ∧ CongruentAE E (canonicalBall V)) ∨ + (4 * Real.pi / 81 ≤ V ∧ V ≤ 1 / Real.pi ∧ CongruentAE E (canonicalTube V)) ∨ + (1 / Real.pi ≤ V ∧ CongruentAE E (canonicalSlab V)) + +/-- The equality class at every interior volume, including complementation. -/ +def StandardRegionAt (V : ℝ) (E : Set Torus) : Prop := + if V ≤ 1 / 2 then SmallStandardRegion V E + else SmallStandardRegion (1 - V) Eᶜ + +/-- Attainment, the sharp profile, and all equality cases at interior volumes. -/ +theorem unit_cubic_isoperimetric (V : ℝ) (hV : V ∈ Ioo 0 1) : + (∃ E : Set Torus, IsMinimizerAt V E) ∧ + (∀ E : Set Torus, IsMinimizerAt V E → + perimeter E = ENNReal.ofReal (candidateProfile V)) ∧ + (∀ E : Set Torus, IsMinimizerAt V E ↔ StandardRegionAt V E) := by + sorry + +end CubicTorus +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CubicTorus.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CubicTorus.unit_cubic_isoperimetric` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cubic-torus/solution/closure.txt b/tasks/cubic-torus/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ba47f1415f1a257ea8a3a12ba9896e5d430f8fc7 --- /dev/null +++ b/tasks/cubic-torus/solution/closure.txt @@ -0,0 +1,162 @@ +OAI.Geometry.CubicTorus.Compactness.BVLocalTranslation +OAI.Geometry.CubicTorus.Compactness.BVWeyl +OAI.Geometry.CubicTorus.Compactness.GraphMollifier +OAI.Geometry.CubicTorus.Curvature.CMCFrameOperator +OAI.Geometry.CubicTorus.Curvature.CmcStretch +OAI.Geometry.CubicTorus.Curvature.LinearCMCEquation +OAI.Geometry.CubicTorus.Curvature.LinearCMCEquationNear +OAI.Geometry.CubicTorus.Curvature.MinimizerJacobiEquation +OAI.Geometry.CubicTorus.Curvature.NormalCurvatureScalar +OAI.Geometry.CubicTorus.Curvature.SurfaceJacobiLocalization +OAI.Geometry.CubicTorus.Curvature.TorusC2CMCAt +OAI.Geometry.CubicTorus.Estimates.BVAnnulusSelection +OAI.Geometry.CubicTorus.Estimates.BVBallCalibration +OAI.Geometry.CubicTorus.Estimates.BVBallProbability +OAI.Geometry.CubicTorus.Estimates.BVGraphEnergy +OAI.Geometry.CubicTorus.Estimates.BVGraphRescaling +OAI.Geometry.CubicTorus.Estimates.BVInteriorMultiplier +OAI.Geometry.CubicTorus.Estimates.BVLocalScaling +OAI.Geometry.CubicTorus.Estimates.BVMovingTrappedDecay +OAI.Geometry.CubicTorus.Estimates.BVOneDimensionalHat +OAI.Geometry.CubicTorus.Estimates.BVPlanarLocalModels +OAI.Geometry.CubicTorus.Estimates.BVRadial +OAI.Geometry.CubicTorus.Estimates.BVSecondaryPlanarData +OAI.Geometry.CubicTorus.Estimates.BVSharpUpperBound +OAI.Geometry.CubicTorus.Estimates.BVTriangleRegion +OAI.Geometry.CubicTorus.Estimates.ChainAcceleration +OAI.Geometry.CubicTorus.Estimates.ChainMass +OAI.Geometry.CubicTorus.Estimates.CirclePeriodize +OAI.Geometry.CubicTorus.Estimates.ConeSlopeReciprocalArea +OAI.Geometry.CubicTorus.Estimates.CoordinatePlaneRays +OAI.Geometry.CubicTorus.Estimates.CorrectedChain +OAI.Geometry.CubicTorus.Estimates.DifferenceStep +OAI.Geometry.CubicTorus.Estimates.GraphInverseMetric +OAI.Geometry.CubicTorus.Estimates.HolderNear +OAI.Geometry.CubicTorus.Estimates.InteriorBallSubset +OAI.Geometry.CubicTorus.Estimates.L2ReplacementBallBound +OAI.Geometry.CubicTorus.Estimates.LatticeHeightHom +OAI.Geometry.CubicTorus.Estimates.MinimizerLevelSliceIsoperimetric +OAI.Geometry.CubicTorus.Estimates.NodalBalanceValue +OAI.Geometry.CubicTorus.Estimates.PlanarRadialArea +OAI.Geometry.CubicTorus.Estimates.PlaneQuadraticWeight +OAI.Geometry.CubicTorus.Estimates.PlaneScaleEquiv +OAI.Geometry.CubicTorus.Estimates.PlaneWeakGradient +OAI.Geometry.CubicTorus.Estimates.RadialSectionArea +OAI.Geometry.CubicTorus.Estimates.SliceJensenWeight +OAI.Geometry.CubicTorus.Estimates.SmoothScalarSeparatedTrunc +OAI.Geometry.CubicTorus.Estimates.SurfaceJet +OAI.Geometry.CubicTorus.Estimates.TorusCoordinatePermute +OAI.Geometry.CubicTorus.Estimates.TubeCalibration +OAI.Geometry.CubicTorus.Estimates.UnitAngle +OAI.Geometry.CubicTorus.Main +OAI.Geometry.CubicTorus.Model +OAI.Geometry.CubicTorus.Profiles.AtanPoly +OAI.Geometry.CubicTorus.Profiles.AxisCircleLebesgue +OAI.Geometry.CubicTorus.Profiles.CMCSecantSymbol +OAI.Geometry.CubicTorus.Profiles.CenteredJacobiChart +OAI.Geometry.CubicTorus.Profiles.CornerGrid155 +OAI.Geometry.CubicTorus.Profiles.CornerGrid269 +OAI.Geometry.CubicTorus.Profiles.CornerGrid381 +OAI.Geometry.CubicTorus.Profiles.CornerGrid42 +OAI.Geometry.CubicTorus.Profiles.Endpoint +OAI.Geometry.CubicTorus.Profiles.FirstAxisShift +OAI.Geometry.CubicTorus.Profiles.FirstSeamFunction +OAI.Geometry.CubicTorus.Profiles.FlatTranslation +OAI.Geometry.CubicTorus.Profiles.FourStarScalarGrid +OAI.Geometry.CubicTorus.Profiles.GainBounds +OAI.Geometry.CubicTorus.Profiles.GainEnclosure150 +OAI.Geometry.CubicTorus.Profiles.MinimizerFirstTransitionTube +OAI.Geometry.CubicTorus.Profiles.NestingBaseline +OAI.Geometry.CubicTorus.Profiles.NestingEndpointBound +OAI.Geometry.CubicTorus.Profiles.NodalTorusScalar +OAI.Geometry.CubicTorus.Profiles.NormalMap +OAI.Geometry.CubicTorus.Profiles.NormalTransverseLength +OAI.Geometry.CubicTorus.Profiles.NormalizedCMCCharts +OAI.Geometry.CubicTorus.Profiles.OctantVertex +OAI.Geometry.CubicTorus.Profiles.PlanarProfile +OAI.Geometry.CubicTorus.Profiles.PlanarRadialDownset +OAI.Geometry.CubicTorus.Profiles.PlanarWeakGradient +OAI.Geometry.CubicTorus.Profiles.ProfileBounds +OAI.Geometry.CubicTorus.Profiles.SectionExtentBounds +OAI.Geometry.CubicTorus.Profiles.SharpSectionWeight +OAI.Geometry.CubicTorus.Profiles.SiblingCmcSecant +OAI.Geometry.CubicTorus.Profiles.SiblingPlaneCarlemanS +OAI.Geometry.CubicTorus.Profiles.SmoothSeamProbability +OAI.Geometry.CubicTorus.Profiles.TransverseTorus +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures1165To1383 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures1384To1602 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures1603To1821 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures1822To2041 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures2042To2262 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures2263To2479 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures2480To2700 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures2701To2920 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures289To507 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures2921To3142 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures3143To3335 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures508To725 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures726To944 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures72To288 +OAI.Geometry.CubicTorus.Profiles.ValueEnclosures945To1164 +OAI.Geometry.CubicTorus.Reflection.ActualAxialFlux +OAI.Geometry.CubicTorus.Reflection.AxialAreaDensity +OAI.Geometry.CubicTorus.Reflection.AxialAreaMarginal +OAI.Geometry.CubicTorus.Reflection.AxialFluxDensity +OAI.Geometry.CubicTorus.Reflection.AxialNormalCalibration +OAI.Geometry.CubicTorus.Reflection.AxialSectionCoordinates +OAI.Geometry.CubicTorus.Reflection.AxialSectionCorner +OAI.Geometry.CubicTorus.Reflection.AxialWeightedHeight +OAI.Geometry.CubicTorus.Reflection.BVConeSecondaryFlux +OAI.Geometry.CubicTorus.Reflection.BVScaledFlux +OAI.Geometry.CubicTorus.Reflection.BVTorusGraphFlux +OAI.Geometry.CubicTorus.Reflection.ChamberGlobalFold +OAI.Geometry.CubicTorus.Reflection.ChamberPositionProducer +OAI.Geometry.CubicTorus.Reflection.CoordinateChamber +OAI.Geometry.CubicTorus.Reflection.CoordinateReflection +OAI.Geometry.CubicTorus.Reflection.CoordinateReflection2 +OAI.Geometry.CubicTorus.Reflection.DelaunayPeriodicMoments +OAI.Geometry.CubicTorus.Reflection.MinimizerAxialCenter +OAI.Geometry.CubicTorus.Reflection.NormalMeasureCoordinateReflection +OAI.Geometry.CubicTorus.Reflection.RevolutionTangents +OAI.Geometry.CubicTorus.Reflection.SiblingAxialProjection +OAI.Geometry.CubicTorus.Reflection.SiblingReflectNormal +OAI.Geometry.CubicTorus.Reflection.TorusCylinders +OAI.Geometry.CubicTorus.Regularity.BVBlowupComplement +OAI.Geometry.CubicTorus.Regularity.BVBlowupNormalMeasure +OAI.Geometry.CubicTorus.Regularity.BVBlowupRigidCovariance +OAI.Geometry.CubicTorus.Regularity.BVC1Patch +OAI.Geometry.CubicTorus.Regularity.BVColumnHeight +OAI.Geometry.CubicTorus.Regularity.BVFlatBlowupRegular +OAI.Geometry.CubicTorus.Regularity.BVGraphNormalization +OAI.Geometry.CubicTorus.Regularity.BVLipschitzGraph +OAI.Geometry.CubicTorus.Regularity.BVMovingOrientedReplacement +OAI.Geometry.CubicTorus.Regularity.BVNormalTiltMeasure +OAI.Geometry.CubicTorus.Regularity.BVOrientedGraphCost +OAI.Geometry.CubicTorus.Regularity.BVPlanarAngularChart +OAI.Geometry.CubicTorus.Regularity.BVPlanarEssentialBoundary +OAI.Geometry.CubicTorus.Regularity.BVPlaneAreaCoordinates +OAI.Geometry.CubicTorus.Regularity.BVRadialVariation +OAI.Geometry.CubicTorus.Regularity.BVRegularity +OAI.Geometry.CubicTorus.Regularity.BVStationaryDensity +OAI.Geometry.CubicTorus.Regularity.BVTangentialBlowup +OAI.Geometry.CubicTorus.Regularity.CoverEssentialBoundary +OAI.Geometry.CubicTorus.Regularity.FiberPoint +OAI.Geometry.CubicTorus.Regularity.GradientCalibration +OAI.Geometry.CubicTorus.Regularity.GraphNormalExtensionDivergence +OAI.Geometry.CubicTorus.Regularity.MinimalGraphDensity +OAI.Geometry.CubicTorus.Regularity.NormalCoverMap +OAI.Geometry.CubicTorus.Regularity.NormalFirstVariation +OAI.Geometry.CubicTorus.Regularity.NormalMeasureCoordinatePermutation +OAI.Geometry.CubicTorus.Regularity.NormalRotationWeak +OAI.Geometry.CubicTorus.Regularity.SmoothApproxLip +OAI.Geometry.CubicTorus.Regularity.SurfaceGraphBundleMeasure +OAI.Geometry.CubicTorus.Regularity.SurfaceH1Tangency +OAI.Geometry.CubicTorus.Regularity.SurfaceH1Translation +OAI.Geometry.CubicTorus.Regularity.SurfaceNormalReverse +OAI.Geometry.CubicTorus.Regularity.TorusC1Boundary +OAI.Geometry.CubicTorus.Regularity.TranslateNormal +OAI.Geometry.CubicTorus.Regularity.WeightedPerimeter +OAI.Geometry.CubicTorus.Rigidity.LocalGraphSphere +OAI.Geometry.CubicTorus.Rigidity.TwoVolumeNodal +OAI.Geometry.CubicTorus.Variation.BVColumnMismatchMeasure +OAI.Geometry.CubicTorus.Variation.ComponentDivergence diff --git a/tasks/cubic-torus/solution/reference.py b/tasks/cubic-torus/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cubic-torus/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cubic-torus/solution/solve.sh b/tasks/cubic-torus/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..508ba44fb85671aabd0f0d06335ef47e292fc2f6 --- /dev/null +++ b/tasks/cubic-torus/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CubicTorus, i.e. module OAI.Geometry.CubicTorus.Main and the +# 162 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.CubicTorus.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CubicTorus" diff --git a/tasks/cubic-torus/task.toml b/tasks/cubic-torus/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01f662bbf8d3abdb0ac2edbe5455b66e181a2b19 --- /dev/null +++ b/tasks/cubic-torus/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cubic-torus" +version = "1.0.0" +description = "Prove CubicTorus (openai/math family 354: Isoperimetric regions in the cubic three-torus) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CubicTorus.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CubicTorus" +family = "354" +family_title = "Isoperimetric regions in the cubic three-torus" +subject = "Differential geometry" +theorems = ["OAI.CubicTorus.unit_cubic_isoperimetric"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.CubicTorus.Main" +reference_modules = 162 +reference_lean_bytes = 6992456 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2541 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17993 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cubic-torus/tests/Challenge.lean b/tasks/cubic-torus/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..29ee08365530ee2899a0038137bd0a0eeac0cb84 --- /dev/null +++ b/tasks/cubic-torus/tests/Challenge.lean @@ -0,0 +1,98 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Set +open scoped ENNReal + +namespace CubicTorus + +abbrev Cover := EuclideanSpace ℝ (Fin 3) +abbrev Torus := PiLp 2 (fun _ : Fin 3 => AddCircle (1 : ℝ)) + +/-- The quotient R³ → R³/Z³ in orthonormal coordinates. -/ +def quotientMap (x : Cover) : Torus := + WithLp.toLp 2 (fun i => (x i : AddCircle (1 : ℝ))) + +/-- One unit-volume fundamental domain; its boundary is immaterial to integration. -/ +def fundamentalCube : Set Cover := {x | ∀ i, 0 ≤ x i ∧ x i < 1} + +/-- The Riemannian volume measure of the unit flat torus. -/ +def torusVolume : Measure Torus := + Measure.map quotientMap (volume.restrict fundamentalCube) + +/-- An integer lattice vector in the Euclidean cover. -/ +def latticeVector (n : Fin 3 → ℤ) : Cover := WithLp.toLp 2 (fun i => (n i : ℝ)) + +/-- The smooth vector fields on the flat torus with pointwise length at most one, +expressed as Z³-periodic fields on its Euclidean cover. The explicit ℕ∞ index +is C^∞; top of WithTop ℕ∞ would instead mean analytic in this Mathlib. -/ +def AdmissibleField (F : Cover → Cover) : Prop := + ContDiff ℝ (⊤ : ℕ∞) F ∧ + (∀ (n : Fin 3 → ℤ) (x : Cover), F (x + latticeVector n) = F x) ∧ + ∀ x, ‖F x‖ ≤ 1 + +/-- Euclidean divergence in the orthonormal coordinate frame. -/ +def divergence (F : Cover → Cover) (x : Cover) : ℝ := + ∑ i : Fin 3, (fderiv ℝ F x (EuclideanSpace.single i 1)) i + +/-- De Giorgi perimeter, allowed to be infinite; no regularity of E is imposed. -/ +def perimeter (E : Set Torus) : ℝ≥0∞ := + ⨆ (F : Cover → Cover) (_ : AdmissibleField F), + ENNReal.ofReal (∫ x in fundamentalCube ∩ quotientMap ⁻¹' E, divergence F x) + +/-- Finite-perimeter measurable regions, including all null-set modifications. -/ +def FinitePerimeter (E : Set Torus) : Prop := + NullMeasurableSet E torusVolume ∧ perimeter E < ⊤ + +/-- A global perimeter minimizer under the prescribed volume constraint. -/ +def IsMinimizerAt (V : ℝ) (E : Set Torus) : Prop := + FinitePerimeter E ∧ torusVolume E = ENNReal.ofReal V ∧ + ∀ F : Set Torus, FinitePerimeter F → torusVolume F = ENNReal.ofReal V → + perimeter E ≤ perimeter F + +/-- The candidate unit-torus isoperimetric profile. -/ +def candidateProfile (V : ℝ) : ℝ := + let v := min V (1 - V) + min ((36 * Real.pi) ^ (1 / 3 : ℝ) * v ^ (2 / 3 : ℝ)) + (min (2 * Real.sqrt (Real.pi * v)) 2) + +/-- Canonical centered ball. Its radius on the listed branch is below 1/2. -/ +def canonicalBall (V : ℝ) : Set Torus := + Metric.ball 0 ((3 * V / (4 * Real.pi)) ^ (1 / 3 : ℝ)) + +/-- Canonical tube around the shortest closed geodesic in coordinate direction 0. -/ +def canonicalTube (V : ℝ) : Set Torus := + {x | ‖x 1‖ ^ 2 + ‖x 2‖ ^ 2 < (Real.sqrt (V / Real.pi)) ^ 2} + +/-- Canonical slab of width V between two parallel coordinate tori. -/ +def canonicalSlab (V : ℝ) : Set Torus := {x | ‖x 0‖ < V / 2} + +/-- Equality of regions up to ambient flat isometry and a null set. -/ +def CongruentAE (E F : Set Torus) : Prop := + ∃ φ : Torus ≃ᵢ Torus, E =ᵐ[torusVolume] (φ '' F) + +/-- Exactly the closed phase ranges, so adjacent types are BOTH included at ties. -/ +def SmallStandardRegion (V : ℝ) (E : Set Torus) : Prop := + (V ≤ 4 * Real.pi / 81 ∧ CongruentAE E (canonicalBall V)) ∨ + (4 * Real.pi / 81 ≤ V ∧ V ≤ 1 / Real.pi ∧ CongruentAE E (canonicalTube V)) ∨ + (1 / Real.pi ≤ V ∧ CongruentAE E (canonicalSlab V)) + +/-- The equality class at every interior volume, including complementation. -/ +def StandardRegionAt (V : ℝ) (E : Set Torus) : Prop := + if V ≤ 1 / 2 then SmallStandardRegion V E + else SmallStandardRegion (1 - V) Eᶜ + +/-- Attainment, the sharp profile, and all equality cases at interior volumes. -/ +theorem unit_cubic_isoperimetric (V : ℝ) (hV : V ∈ Ioo 0 1) : + (∃ E : Set Torus, IsMinimizerAt V E) ∧ + (∀ E : Set Torus, IsMinimizerAt V E → + perimeter E = ENNReal.ofReal (candidateProfile V)) ∧ + (∀ E : Set Torus, IsMinimizerAt V E ↔ StandardRegionAt V E) := by + sorry + +end CubicTorus +end + +end OAI diff --git a/tasks/cubic-torus/tests/grade.py b/tasks/cubic-torus/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cubic-torus/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cubic-torus/tests/task.json b/tasks/cubic-torus/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4fe560b5c7e45c2fd29059bf6aaab07168c2a35a --- /dev/null +++ b/tasks/cubic-torus/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CubicTorus", + "comparator": { + "theorem_names": [ + "OAI.CubicTorus.unit_cubic_isoperimetric" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 17093 +} \ No newline at end of file diff --git a/tasks/cubic-torus/tests/test.sh b/tasks/cubic-torus/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cubic-torus/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cycle-decomposition/environment/Dockerfile b/tasks/cycle-decomposition/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cycle-decomposition/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cycle-decomposition/environment/fetch_mathlib.sh b/tasks/cycle-decomposition/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cycle-decomposition/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cycle-decomposition/environment/lake-manifest.json b/tasks/cycle-decomposition/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cycle-decomposition/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cycle-decomposition/environment/lakefile.lean b/tasks/cycle-decomposition/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cycle-decomposition/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cycle-decomposition/environment/lean_setup.sh b/tasks/cycle-decomposition/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cycle-decomposition/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cycle-decomposition/environment/pack_submission.py b/tasks/cycle-decomposition/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cycle-decomposition/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cycle-decomposition/instruction.md b/tasks/cycle-decomposition/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..44cd3fd706ef5a856f739d12807852d6ab5ac836 --- /dev/null +++ b/tasks/cycle-decomposition/instruction.md @@ -0,0 +1,89 @@ +# openai/math challenge `CycleDecomposition` (family 181) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 181 of the release, *The Erd\H{o}s–Gallai cycle-decomposition conjecture* +(Combinatorics). The family as a whole: Proves that the edges of every finite simple undirected graph on $n$ vertices can be partitioned into at most $Cn$ simple cycles and single edges, for an absolute constant $C$. This resolves the Erd\H{o}s–Gallai cycle-decomposition conjecture, bounding the number of pieces linearly even for dense graphs. + +The challenge is `CycleDecomposition`, also at `/opt/openai-math/challenges/CycleDecomposition.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + + +open Filter Asymptotics Real +open scoped Topology + +open MeasureTheory ProbabilityTheory Finset + +namespace ErdosGallai + +def CycleOrSingleEdge {V : Type} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ s = p.edgeSet) ∨ + ∃ e ∈ G.edgeSet, s = {e} + +def EdgeDecomposition {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∃ parts : Fin k → Set (Sym2 V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet + + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ) (G : SimpleGraph (Fin n)), + ∃ k : ℕ, EdgeDecomposition G k ∧ (k : ℝ) ≤ C * n + +theorem erdos_gallai : MainStatement := by + sorry + +end ErdosGallai + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CycleDecomposition.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ErdosGallai.erdos_gallai` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cycle-decomposition/solution/closure.txt b/tasks/cycle-decomposition/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5d0879e816ac1139af60dd42e77ec433949344cf --- /dev/null +++ b/tasks/cycle-decomposition/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Combinatorics.CycleDecomposition.BatchEndpoints +OAI.Combinatorics.CycleDecomposition.BatchIndexing +OAI.Combinatorics.CycleDecomposition.BatchLovasz +OAI.Combinatorics.CycleDecomposition.BatchPathDeletion +OAI.Combinatorics.CycleDecomposition.BatchPreparation +OAI.Combinatorics.CycleDecomposition.BatchResolution +OAI.Combinatorics.CycleDecomposition.BatchRouting +OAI.Combinatorics.CycleDecomposition.CollisionEstimates +OAI.Combinatorics.CycleDecomposition.CostRegrouping +OAI.Combinatorics.CycleDecomposition.CoupledResolution +OAI.Combinatorics.CycleDecomposition.CycleLifting +OAI.Combinatorics.CycleDecomposition.Decomposition +OAI.Combinatorics.CycleDecomposition.DepthFirstSearch +OAI.Combinatorics.CycleDecomposition.EdgeSplitting +OAI.Combinatorics.CycleDecomposition.EndpointPartition +OAI.Combinatorics.CycleDecomposition.ExpansionBoxes +OAI.Combinatorics.CycleDecomposition.LayerCosts +OAI.Combinatorics.CycleDecomposition.Lovasz +OAI.Combinatorics.CycleDecomposition.Main +OAI.Combinatorics.CycleDecomposition.Pairing +OAI.Combinatorics.CycleDecomposition.PathDeletion +OAI.Combinatorics.CycleDecomposition.PrefixSelection +OAI.Combinatorics.CycleDecomposition.Representatives +OAI.Combinatorics.CycleDecomposition.ReservoirCycles +OAI.Combinatorics.CycleDecomposition.ReservoirRemainder +OAI.Combinatorics.CycleDecomposition.ReservoirSampling +OAI.Combinatorics.CycleDecomposition.Routing +OAI.Combinatorics.CycleDecomposition.Sampling +OAI.Combinatorics.CycleDecomposition.SamplingCuts +OAI.Combinatorics.CycleDecomposition.ScaleDecomposition +OAI.Combinatorics.CycleDecomposition.ScaleExtraction +OAI.Combinatorics.CycleDecomposition.ScaleHierarchy +OAI.Combinatorics.CycleDecomposition.Templates +OAI.Combinatorics.CycleDecomposition.UniformLayers diff --git a/tasks/cycle-decomposition/solution/reference.py b/tasks/cycle-decomposition/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cycle-decomposition/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cycle-decomposition/solution/solve.sh b/tasks/cycle-decomposition/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c56eeb81e8e7cdad33abe574201501e69d96d7eb --- /dev/null +++ b/tasks/cycle-decomposition/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CycleDecomposition, i.e. module OAI.Combinatorics.CycleDecomposition.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.CycleDecomposition.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CycleDecomposition" diff --git a/tasks/cycle-decomposition/task.toml b/tasks/cycle-decomposition/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4a8734ad3fea2416b07a68a32c906cc4149881bf --- /dev/null +++ b/tasks/cycle-decomposition/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cycle-decomposition" +version = "1.0.0" +description = "Prove CycleDecomposition (openai/math family 181: The Erd\\H{o}s–Gallai cycle-decomposition conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CycleDecomposition.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CycleDecomposition" +family = "181" +family_title = "The Erd\\H{o}s–Gallai cycle-decomposition conjecture" +subject = "Combinatorics" +theorems = ["OAI.ErdosGallai.erdos_gallai"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.CycleDecomposition.Main" +reference_modules = 34 +reference_lean_bytes = 998368 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 827 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12598 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cycle-decomposition/tests/Challenge.lean b/tasks/cycle-decomposition/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..aebc8e97f968a482cb56312201bf05a0e4b1e67f --- /dev/null +++ b/tasks/cycle-decomposition/tests/Challenge.lean @@ -0,0 +1,38 @@ +import Mathlib + +namespace OAI + +noncomputable section + + +open Filter Asymptotics Real +open scoped Topology + +open MeasureTheory ProbabilityTheory Finset + +namespace ErdosGallai + +def CycleOrSingleEdge {V : Type} (G : SimpleGraph V) + (s : Set (Sym2 V)) : Prop := + (∃ (v : V) (p : G.Walk v v), p.IsCycle ∧ s = p.edgeSet) ∨ + ∃ e ∈ G.edgeSet, s = {e} + +def EdgeDecomposition {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∃ parts : Fin k → Set (Sym2 V), + (∀ i, CycleOrSingleEdge G (parts i)) ∧ + Pairwise (fun i j => Disjoint (parts i) (parts j)) ∧ + (⋃ i, parts i) = G.edgeSet + + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ) (G : SimpleGraph (Fin n)), + ∃ k : ℕ, EdgeDecomposition G k ∧ (k : ℝ) ≤ C * n + +theorem erdos_gallai : MainStatement := by + sorry + +end ErdosGallai + +end + +end OAI diff --git a/tasks/cycle-decomposition/tests/grade.py b/tasks/cycle-decomposition/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cycle-decomposition/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cycle-decomposition/tests/task.json b/tasks/cycle-decomposition/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d0721837371dedd753d635626f257aac7a45fe1a --- /dev/null +++ b/tasks/cycle-decomposition/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CycleDecomposition", + "comparator": { + "theorem_names": [ + "OAI.ErdosGallai.erdos_gallai" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11698 +} \ No newline at end of file diff --git a/tasks/cycle-decomposition/tests/test.sh b/tasks/cycle-decomposition/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cycle-decomposition/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/cylinder-covering/environment/Dockerfile b/tasks/cylinder-covering/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/cylinder-covering/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/cylinder-covering/environment/fetch_mathlib.sh b/tasks/cylinder-covering/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/cylinder-covering/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/cylinder-covering/environment/lake-manifest.json b/tasks/cylinder-covering/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/cylinder-covering/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/cylinder-covering/environment/lakefile.lean b/tasks/cylinder-covering/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/cylinder-covering/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/cylinder-covering/environment/lean_setup.sh b/tasks/cylinder-covering/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/cylinder-covering/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/cylinder-covering/environment/pack_submission.py b/tasks/cylinder-covering/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/cylinder-covering/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/cylinder-covering/instruction.md b/tasks/cylinder-covering/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9a726c1b7874e618a54068b95633b64836d0fae5 --- /dev/null +++ b/tasks/cylinder-covering/instruction.md @@ -0,0 +1,624 @@ +# openai/math challenge `CylinderCovering` (family 100) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 100 of the release, *A counterexample to Bang's cylinder-covering bound* +(Convex and metric geometry). The family as a whole: Covers the entire closed regular tetrahedron by finitely many cylinders with compact triangular perpendicular bases whose total area is less than half its smallest orthogonal projection area. This disproves Bang's half-area cylinder-covering bound and the stronger directionwise normalized conjecture in dimension three. + +The challenge is `CylinderCovering`, also at `/opt/openai-math/challenges/CylinderCovering.lean`: + +```lean +import Mathlib + +namespace OAI + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def H : ℝ := Real.sqrt 2 + +def point (x y t : ℝ) : Space := !₂[x, y, H * t] + +def K : Set Space := + {z | ∃ x y t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |x| ≤ 1 - t ∧ |y| ≤ t ∧ z = point x y t} + +def projection (u z : Space) : Space := z - (inner ℝ u z) • u + +def area (B : Set Space) : ℝ := (Measure.euclideanHausdorffMeasure 2 B).toReal + +def shadowArea (u : Space) : ℝ := area (projection u '' K) + +def A_min : ℝ := sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea u} + +structure TriCylinder where + axis : Space + base : Set Space + unit_axis : ‖axis‖ = 1 + perpendicular : ∀ z ∈ base, inner ℝ axis z = 0 + triangular : ∃ v : Fin 3 → Space, AffineIndependent ℝ v ∧ + base = convexHull ℝ (Set.range v) + compact : IsCompact base + convex : Convex ℝ base + measurable : MeasurableSet base + finite_area : Measure.euclideanHausdorffMeasure 2 base ≠ ⊤ + +def TriCylinder.carrier (c : TriCylinder) : Set Space := + {z | ∃ b ∈ c.base, ∃ r : ℝ, z = b + r • c.axis} + +def Covers {m : ℕ} (c : Fin m → TriCylinder) : Prop := + ∀ z ∈ K, ∃ i : Fin m, z ∈ (c i).carrier + +def totalArea {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base + +def relativeCost {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base / shadowArea (c i).axis + +def n (ε : ℝ) : ℕ := ⌈2 / ε ^ 2⌉₊ +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def η : ℝ := 1 / 1000 + +def alpha (a b : ℝ) : ℝ := (1 + a * b) / 4 + +def beta (a b : ℝ) : ℝ := (a + b) / 4 + +def d (q : ℝ) : ℝ := q ^ 2 * (1 + q ^ 2) / 16 + +def cutoffCoeff (a b : ℝ) : ℝ := η + max (d a) (d b) + +def step (N : ℕ) : ℝ := 2 / N + +def mesh (N i : ℕ) : ℝ := -1 + i * step N + +def cutoff (ε a b : ℝ) : ℝ := 1 / 2 + ε ^ 2 * cutoffCoeff a b + +def speedSq (a b : ℝ) : ℝ := (alpha a b)^2 + 2*(beta a b)^2 + +def normalizedTerm (ε a b : ℝ) : ℝ := + (b-a) * (cutoff ε a b)^2 / Real.sqrt (1+ε^2*speedSq a b) + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def unit (v : Space) : Space := ‖v‖⁻¹ • v + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def tiltV (ε A B : ℝ) : Space := !₂[1, ε*A, H*ε*B] + +def tiltW (ε A B : ℝ) : Space := !₂[-ε*A, 1, H*ε*B] + +def lowerVertices (a b T : ℝ) : Fin 3 → Space := + ![point 0 0 0, point 0 (a*T) T, point 0 (b*T) T] + +def upperVertices (a b T : ℝ) : Fin 3 → Space := + ![point 0 0 1, point (a*T) 0 (1-T), point (b*T) 0 (1-T)] + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering.Planar + +abbrev Coord := Fin 2 → ℝ + +def standard : Set Coord := {x | 0 ≤ x 0 ∧ 0 ≤ x 1 ∧ x 0 + x 1 ≤ 1} + +def vertices : Fin 3 → Coord := ![0, ![1, 0], ![0, 1] ] + +end TriangularCovering.Planar + +namespace TriangularCovering + +section Triangles +variable {E F : Type*} [AddCommGroup E] [Module ℝ E] [AddCommGroup F] [Module ℝ F] + +def triangle (a b c : E) : Set E := convexHull ℝ (range (![a, b, c] : Fin 3 → E)) + +end Triangles +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace + +noncomputable section +namespace TriangularCovering + +def lowerAngularIndex {N : ℕ} (j : Fin N) : Fin (2*N) := + Fin.cast (two_mul N).symm (Fin.castAdd N j) + +def upperAngularIndex {N : ℕ} (j : Fin N) : Fin (2*N) := + Fin.cast (two_mul N).symm (Fin.natAdd N j) + +def lowerAngularAxis (ε : ℝ) (j : ℕ) : Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + unit (tiltV ε (alpha a b) (beta a b)) + +def upperAngularAxis (ε : ℝ) (j : ℕ) : Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + unit (tiltW ε (alpha a b) (beta a b)) + +def lowerAngularBase (ε : ℝ) (j : ℕ) : Set Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + let v := lowerVertices a b (cutoff ε a b) + projection (lowerAngularAxis ε j) '' triangle (v 0) (v 1) (v 2) + +def upperAngularBase (ε : ℝ) (j : ℕ) : Set Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + let v := upperVertices a b (cutoff ε a b) + projection (upperAngularAxis ε j) '' triangle (v 0) (v 1) (v 2) + +def ExplicitAngularFamily (ε : ℝ) (c : Fin (2*n ε) → TriCylinder) : Prop := + ∀ j : Fin (n ε), + (c (lowerAngularIndex j)).axis = lowerAngularAxis ε j ∧ + (c (lowerAngularIndex j)).base = lowerAngularBase ε j ∧ + (c (upperAngularIndex j)).axis = upperAngularAxis ε j ∧ + (c (upperAngularIndex j)).base = upperAngularBase ε j + +def AngularAreaStatement : Prop := + ∀ ε : ℝ, 0 < ε → ε ≤ 1 → + ∃ c : Fin (2*n ε) → TriCylinder, + ExplicitAngularFamily ε c ∧ + totalArea c/H = ∑ j : Fin (n ε), + normalizedTerm ε (mesh (n ε) j) (mesh (n ε) (j+1)) ∧ + |totalArea c/H - (1/2-(13/6000:ℝ)*ε^2)| ≤ 2*ε^4 + +def ExplicitAngularStatement : Prop := + A_min = H ∧ + ∀ ε : ℝ, 0 < ε → ε ≤ 1/2000 → + ∃ c : Fin (2*n ε) → TriCylinder, + ExplicitAngularFamily ε c ∧ Covers c ∧ + |totalArea c/H - (1/2-(13/6000:ℝ)*ε^2)| ≤ 2*ε^4 ∧ + totalArea c < A_min/2 ∧ relativeCost c < 1/2 + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory Filter Metric +open scoped Topology ContDiff Pointwise +namespace RuledApproximation + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev Space := EuclideanSpace ℝ (Fin 3) +def vec2 (x y : ℝ) : Plane := WithLp.toLp 2 ![x, y] +def vec3 (x y z : ℝ) : Space := WithLp.toLp 2 ![x, y, z] +def axial (s : ℝ) (p : Plane) : Space := vec3 s (p 0) (p 1) + +def IsParallelogram {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s ∈ Icc (0 : ℝ) 1, ∃ t ∈ Icc (0 : ℝ) 1, + x = c + s • u + t • v} +structure Cylinder where + axis : Space + unit_axis : ‖axis‖ = 1 + base : Set ((Submodule.span ℝ ({axis} : Set Space))ᗮ) + +namespace Cylinder + +def carrier (C : Cylinder) : Set Space := + {x | ∃ b ∈ C.base, ∃ t : ℝ, x = (b : Space) + t • C.axis} + +def area (C : Cylinder) : ℝ := volume.real C.base + +def parallelogram (C : Cylinder) : Prop := IsParallelogram C.base + +def openBounded (C : Cylinder) : Prop := + IsOpen C.base ∧ Bornology.IsBounded C.base ∧ MeasurableSet C.base +end Cylinder + +def familySet {n : ℕ} (C : Fin n → Cylinder) : Set Space := ⋃ i, (C i).carrier +def familyArea {n : ℕ} (C : Fin n → Cylinder) : ℝ := ∑ i, (C i).area + +def HasFiniteCover (shape : Cylinder → Prop) (S : Set Space) (A : ℝ) : Prop := + ∃ n : ℕ, ∃ C : Fin n → Cylinder, + (∀ i, shape (C i)) ∧ S ⊆ familySet C ∧ familyArea C ≤ A + +def SmoothNear (n : WithTop ℕ∞) (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ D ⊆ U ∧ ContDiffOn ℝ n v U + +def HyperbolicAt (L : ℝ) (v : Plane → Plane) (p : Plane) : Prop := + ∃ lam : ℝ, 0 < L * lam ∧ L * lam < 1 ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap lam ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap (-lam) + +def weight (v : Plane) : ℝ := 1 / Real.sqrt (1 + ‖v‖ ^ 2) +def physicalWeight (h : ℝ) (w : Plane) : ℝ := + 1 / Real.sqrt (1 + w 0 ^ 2 + h ^ 2 * w 1 ^ 2) + +def ruled (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ r : ℝ, |r| ≤ L ∧ + z = vec3 (p 0 + r * v p 0) (p 1 + r * v p 1) r} + +def physicalRuled (h : ℝ) (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ s : ℝ, |s| ≤ L ∧ + z = vec3 s (p 0 + s * v p 0) (h * (p 1 + s * v p 1))} + +def HyperbolicStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (L : ℝ), + IsCompact D → SmoothNear 1 D v → 0 < L → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram (ruled D v L) + ((∫ p in D, weight (v p)) + e) + +def unitSquare : Set Plane := {x | ∀ i, |x i| ≤ (1 : ℝ) / 2} + +def IsSquareTile (T : Set Plane) : Prop := + ∃ c : Plane, ∃ R : Plane ≃ₗᵢ[ℝ] Plane, ∃ a : ℝ, 0 < a ∧ + T = (fun x => c + a • R x) '' unitSquare + +def auxiliaryCylinder (T : Set Plane) (g : Plane) : Set Space := + {z | ∃ s : ℝ, ∃ b ∈ T, z = axial s (b + s • g)} + +def firstPhysicalMap (h : ℝ) (z : Space) : Space := vec3 (z 0) (z 1) (h * z 2) +def secondPhysicalMap (h a : ℝ) (z : Space) : Space := + vec3 (z 1) (z 0) (h * (a - z 2)) +end RuledApproximation +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory +open scoped InnerProductSpace + +namespace CylinderCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def IsRegularTetrahedron (K : Set Space) : Prop := + ∃ v : Fin 4 → Space, AffineIndependent ℝ v ∧ + ∃ edge : ℝ, 0 < edge ∧ + (∀ i j : Fin 4, i ≠ j → dist (v i) (v j) = edge) ∧ + K = convexHull ℝ (range v) + +def shadowArea (K : Set Space) (u : Space) : ℝ := + TriangularCovering.area (TriangularCovering.projection u '' K) + +def minimumShadowArea (K : Set Space) : ℝ := + sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea K u} + +def triangularCovers {n : ℕ} (K : Set Space) + (C : Fin n → TriangularCovering.TriCylinder) : Prop := + ∀ x ∈ K, ∃ i : Fin n, x ∈ (C i).carrier + +def triangularRelativeCost {n : ℕ} (K : Set Space) + (C : Fin n → TriangularCovering.TriCylinder) : ℝ := + ∑ i, TriangularCovering.area (C i).base / shadowArea K (C i).axis + +def relativeCost {n : ℕ} (K : Set Space) + (C : Fin n → RuledApproximation.Cylinder) : ℝ := + ∑ i, (C i).area / shadowArea K (C i).axis + +def AngularExplicitStatement : Prop := + TriangularCovering.AngularAreaStatement ∧ TriangularCovering.ExplicitAngularStatement + +def RegularTriangularCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → TriangularCovering.TriCylinder, + triangularCovers K C ∧ + TriangularCovering.totalArea C < minimumShadowArea K / 2 ∧ + triangularRelativeCost K C < 1 / 2 + +def RegularParallelogramCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → RuledApproximation.Cylinder, + (∀ i, (C i).parallelogram) ∧ + K ⊆ RuledApproximation.familySet C ∧ + RuledApproximation.familyArea C < minimumShadowArea K / 2 ∧ + relativeCost K C < 1 / 2 + +def RegularOpenCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → RuledApproximation.Cylinder, + (∀ i, (C i).openBounded) ∧ + K ⊆ RuledApproximation.familySet C ∧ + RuledApproximation.familyArea C < minimumShadowArea K / 2 ∧ + relativeCost K C < 1 / 2 + +end CylinderCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory Filter +open scoped Topology ContDiff +namespace RuledApproximation + +def NilpotentC1Statement : Prop := + ∀ (D : Set Plane) (G : Plane → Plane), IsCompact D → SmoothNear 1 D G → + (∀ b ∈ D, (fderiv ℝ G b).comp (fderiv ℝ G b) = 0) → + ∀ h eps : ℝ, 0 < h → 0 < eps → + ∃ n : ℕ, ∃ T : Fin n → Set Plane, ∃ g : Fin n → Plane, + (∀ i, IsSquareTile (T i)) ∧ + physicalRuled 1 D G 1 ⊆ ⋃ i, auxiliaryCylinder (T i) (g i) ∧ + (∑ i, volume.real (T i) * physicalWeight h (g i)) ≤ + (∫ b in D, physicalWeight h (G b)) + eps ∧ + ∀ a : ℝ, ∃ C₁ C₂ : Fin n → Cylinder, + (∀ i, (C₁ i).parallelogram ∧ (C₂ i).parallelogram ∧ + (C₁ i).carrier = firstPhysicalMap h '' auxiliaryCylinder (T i) (g i) ∧ + (C₂ i).carrier = secondPhysicalMap h a '' auxiliaryCylinder (T i) (g i) ∧ + (C₁ i).area = h * volume.real (T i) * physicalWeight h (g i) ∧ + (C₂ i).area = h * volume.real (T i) * physicalWeight h (g i)) + +end RuledApproximation +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +namespace CylinderCovering.RadialRiemann +open Set + +def step (a b : ℝ) (N : ℕ) : ℝ := (b - a) / N + +def point (a b : ℝ) (N i : ℕ) : ℝ := a + i * step a b N + +def cell (a b : ℝ) (N : ℕ) (i : Fin N) : Set ℝ := + Icc (point a b N i) (point a b N (i + 1)) + +def IsTagged (a b : ℝ) (N : ℕ) (tag : Fin N → ℝ) : Prop := + ∀ i, tag i ∈ cell a b N i + +def capMax (R : ℝ → ℝ) (a b : ℝ) (N : ℕ) (i : Fin N) : ℝ := + sSup (R '' cell a b N i) +end CylinderCovering.RadialRiemann +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory Filter +open scoped InnerProductSpace Topology + +noncomputable section + +namespace CylinderCovering.RadialSweep + +abbrev Space := TriangularCovering.Space + +structure Data where + e : Space + a : Space + b : Space + p₀ : Space + α : ℝ + β : ℝ + L : ℝ + R : ℝ → ℝ + lam : ℝ → ℝ + w : ℝ → Space + interval_nonempty : α < β + length_pos : 0 < L + normal_unit : ‖e‖ = 1 + a_perp : inner ℝ e a = 0 + b_perp : inner ℝ e b = 0 + origin_perp : inner ℝ e p₀ = 0 + independent : LinearIndependent ℝ ![a, b] + cap_continuous : ContinuousOn R (Icc α β) + cap_nonneg : ∀ t ∈ Icc α β, 0 ≤ R t + scalar_continuous : ContinuousOn lam (Icc α β) + velocity_continuous : ContinuousOn w (Icc α β) + velocity_perp : ∀ t ∈ Icc α β, inner ℝ e (w t) = 0 + aligned : ∀ t ∈ Icc α β, + HasDerivWithinAt w (lam t • (a + t • b)) (Icc α β) t + +def sweep (D : Data) : Set Space := + {z | ∃ t ∈ Icc D.α D.β, ∃ ρ ∈ Icc (0 : ℝ) (D.R t), + ∃ s : ℝ, |s| ≤ D.L ∧ + z = D.p₀ + ρ • (D.a + t • D.b) + s • (D.e + D.w t)} + +def kappa (D : Data) : ℝ := + Real.sqrt (inner ℝ D.a D.a * inner ℝ D.b D.b - (inner ℝ D.a D.b) ^ 2) + +def direction (D : Data) (t : ℝ) : Space := + ‖D.e + D.w t‖⁻¹ • (D.e + D.w t) + +def weightedArea (D : Data) : ℝ := + kappa D * ∫ t in D.α..D.β, + D.R t ^ 2 / (2 * Real.sqrt (1 + ‖D.w t‖ ^ 2)) + +def scalarBound (D : Data) : ℝ := sSup ((fun t => |D.lam t|) '' Icc D.α D.β) + +def radialError (D : Data) : ℝ := D.L * scalarBound D + +def collar (D : Data) : ℝ := 3 * radialError D + 1 + +def midpoint (D : Data) (N : ℕ) (i : Fin N) : ℝ := + (RadialRiemann.point D.α D.β N i + RadialRiemann.point D.α D.β N (i + 1)) / 2 + +def leftTip (D : Data) (N : ℕ) : ℝ := -collar D * RadialRiemann.step D.α D.β N + +def rightEdge (D : Data) (N : ℕ) (i : Fin N) : ℝ := + RadialRiemann.capMax D.R D.α D.β N i + radialError D * RadialRiemann.step D.α D.β N + +def coordinateMap (D : Data) (p : ℝ × ℝ) : Space := D.p₀ + p.1 • D.a + p.2 • D.b + +def frozenVertices (D : Data) (N : ℕ) (i : Fin N) : Fin 3 → Space := + let l := leftTip D N + let r := rightEdge D N i + let m := midpoint D N i + let d := RadialRiemann.step D.α D.β N + ![coordinateMap D (l, m * l), + coordinateMap D (r, m * r - d / 2 * (r - l)), + coordinateMap D (r, m * r + d / 2 * (r - l))] + +def frozenTriangle (D : Data) (N : ℕ) (i : Fin N) : Set Space := + convexHull ℝ (Set.range (frozenVertices D N i)) + +def frozenBase (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : Set Space := + TriangularCovering.projection (direction D (tag i)) '' frozenTriangle D N i + +def frozenArea (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : ℝ := + kappa D * RadialRiemann.step D.α D.β N * + (RadialRiemann.capMax D.R D.α D.β N i + + (radialError D + collar D) * RadialRiemann.step D.α D.β N) ^ 2 / + (2 * Real.sqrt (1 + ‖D.w (tag i)‖ ^ 2)) + +def localSweep (D : Data) (N : ℕ) (i : Fin N) : Set Space := + {z | ∃ t ∈ RadialRiemann.cell D.α D.β N i, + ∃ ρ ∈ Icc (0 : ℝ) (D.R t), ∃ s : ℝ, |s| ≤ D.L ∧ + z = D.p₀ + ρ • (D.a + t • D.b) + s • (D.e + D.w t)} + +def actualBase (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : Set Space := + TriangularCovering.projection (direction D (tag i)) '' localSweep D N i + +def cylinder (u : Space) (B : Set Space) : Set Space := + {z | ∃ b ∈ B, ∃ s : ℝ, z = b + s • u} + +def actualCost (D : Data) (N : ℕ) (tag : Fin N → ℝ) : ℝ := + ∑ i : Fin N, TriangularCovering.area (actualBase D N tag i) + +def AlignedStatement : Prop := + ∀ D : Data, ∀ tag : (N : ℕ) → Fin N → ℝ, + (∀ N, RadialRiemann.IsTagged D.α D.β N (tag N)) → + ∃ C : (N : ℕ) → Fin N → TriangularCovering.TriCylinder, + (∀ N, 0 < N → + (∀ i, (C N i).axis = direction D (tag N i) ∧ + (C N i).base = frozenBase D N (tag N) i ∧ + TriangularCovering.area (C N i).base = frozenArea D N (tag N) i) ∧ + (∀ z ∈ sweep D, ∃ i : Fin N, z ∈ (C N i).carrier)) ∧ + Tendsto (fun N => TriangularCovering.totalArea (C N)) atTop (𝓝 (weightedArea D)) + +def ActualSweepStatement : Prop := + ∀ D : Data, ∀ tag : (N : ℕ) → Fin N → ℝ, + (∀ N, RadialRiemann.IsTagged D.α D.β N (tag N)) → + (∀ N, 0 < N → + (∀ i : Fin N, ‖direction D (tag N i)‖ = 1 ∧ + IsCompact (actualBase D N (tag N) i) ∧ + MeasurableSet (actualBase D N (tag N) i) ∧ + Measure.euclideanHausdorffMeasure 2 (actualBase D N (tag N) i) ≠ ⊤ ∧ + (∀ z ∈ actualBase D N (tag N) i, inner ℝ (direction D (tag N i)) z = 0) ∧ + actualBase D N (tag N) i ⊆ frozenBase D N (tag N) i) ∧ + (∀ z ∈ sweep D, ∃ i : Fin N, + z ∈ cylinder (direction D (tag N i)) (actualBase D N (tag N) i))) ∧ + (∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, actualCost D N (tag N) ≤ weightedArea D + ε) ∧ + Filter.limsup (fun N => actualCost D N (tag N)) atTop ≤ weightedArea D + +end CylinderCovering.RadialSweep +end +end + +namespace CylinderCovering + +theorem fourPaperMain : + AngularExplicitStatement ∧ + RuledApproximation.HyperbolicStatement ∧ + RuledApproximation.NilpotentC1Statement ∧ + RegularParallelogramCounterexampleStatement ∧ + RegularOpenCounterexampleStatement ∧ + RadialSweep.AlignedStatement ∧ + RadialSweep.ActualSweepStatement := by + sorry + +end CylinderCovering + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/CylinderCovering.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CylinderCovering.fourPaperMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/cylinder-covering/solution/closure.txt b/tasks/cylinder-covering/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9504d0389897f37cc1af3788dc9cd70db5e6308b --- /dev/null +++ b/tasks/cylinder-covering/solution/closure.txt @@ -0,0 +1,641 @@ +OAI.Geometry.CylinderCovering.Angular.Admissibility +OAI.Geometry.CylinderCovering.Angular.Aperture +OAI.Geometry.CylinderCovering.Angular.ApertureDefinitions +OAI.Geometry.CylinderCovering.Angular.AreaRefinement +OAI.Geometry.CylinderCovering.Angular.Caps +OAI.Geometry.CylinderCovering.Angular.CapsDefinitions +OAI.Geometry.CylinderCovering.Angular.CartesianDirect +OAI.Geometry.CylinderCovering.Angular.CartesianFailure +OAI.Geometry.CylinderCovering.Angular.CartesianObstruction +OAI.Geometry.CylinderCovering.Angular.CartesianRemainder +OAI.Geometry.CylinderCovering.Angular.CartesianSelectedCover +OAI.Geometry.CylinderCovering.Angular.CartesianSelectedPair +OAI.Geometry.CylinderCovering.Angular.CartesianTaylor +OAI.Geometry.CylinderCovering.Angular.Construction +OAI.Geometry.CylinderCovering.Angular.ConstructionDefinitions +OAI.Geometry.CylinderCovering.Angular.Cubic +OAI.Geometry.CylinderCovering.Angular.CubicArea +OAI.Geometry.CylinderCovering.Angular.CubicAreaDefinitions +OAI.Geometry.CylinderCovering.Angular.CubicCost +OAI.Geometry.CylinderCovering.Angular.CubicCoverDefinitions +OAI.Geometry.CylinderCovering.Angular.CubicEstimates +OAI.Geometry.CylinderCovering.Angular.CubicFamily +OAI.Geometry.CylinderCovering.Angular.CubicMain +OAI.Geometry.CylinderCovering.Angular.CubicRescaled +OAI.Geometry.CylinderCovering.Angular.CubicRescaledDefinitions +OAI.Geometry.CylinderCovering.Angular.CubicScaledFamily +OAI.Geometry.CylinderCovering.Angular.CubicTheorem +OAI.Geometry.CylinderCovering.Angular.CubicTheoremDefinitions +OAI.Geometry.CylinderCovering.Angular.DirectBounds +OAI.Geometry.CylinderCovering.Angular.Endpoint +OAI.Geometry.CylinderCovering.Angular.EndpointCover +OAI.Geometry.CylinderCovering.Angular.EndpointCoverDefinitions +OAI.Geometry.CylinderCovering.Angular.EndpointDefinitions +OAI.Geometry.CylinderCovering.Angular.EndpointScaled +OAI.Geometry.CylinderCovering.Angular.EndpointScaledDefinitions +OAI.Geometry.CylinderCovering.Angular.EqualPartition +OAI.Geometry.CylinderCovering.Angular.Estimates +OAI.Geometry.CylinderCovering.Angular.Extensions +OAI.Geometry.CylinderCovering.Angular.ExtensionsCore +OAI.Geometry.CylinderCovering.Angular.ExtensionsDefinitions +OAI.Geometry.CylinderCovering.Angular.Family +OAI.Geometry.CylinderCovering.Angular.FamilyDefinitions +OAI.Geometry.CylinderCovering.Angular.GeneralArea +OAI.Geometry.CylinderCovering.Angular.GeneralAssembly +OAI.Geometry.CylinderCovering.Angular.GeneralCap +OAI.Geometry.CylinderCovering.Angular.GeneralCost +OAI.Geometry.CylinderCovering.Angular.GeneralCoverage +OAI.Geometry.CylinderCovering.Angular.GeneralDefinitions +OAI.Geometry.CylinderCovering.Angular.GeneralFamilyCosts +OAI.Geometry.CylinderCovering.Angular.GeneralGeometry +OAI.Geometry.CylinderCovering.Angular.GeneralGeometryDefinitions +OAI.Geometry.CylinderCovering.Angular.GeneralTheorem +OAI.Geometry.CylinderCovering.Angular.GeneralTriangles +OAI.Geometry.CylinderCovering.Angular.GeneralVolume +OAI.Geometry.CylinderCovering.Angular.Geometry +OAI.Geometry.CylinderCovering.Angular.GeometryDefinitions +OAI.Geometry.CylinderCovering.Angular.InterceptDefinitions +OAI.Geometry.CylinderCovering.Angular.Margins +OAI.Geometry.CylinderCovering.Angular.MarginsDefinitions +OAI.Geometry.CylinderCovering.Angular.OrdinaryCaps +OAI.Geometry.CylinderCovering.Angular.OrdinaryCapsDefinitions +OAI.Geometry.CylinderCovering.Angular.OrdinaryCover +OAI.Geometry.CylinderCovering.Angular.Partition +OAI.Geometry.CylinderCovering.Angular.PartitionIdentities +OAI.Geometry.CylinderCovering.Angular.SampledCover +OAI.Geometry.CylinderCovering.Angular.Sampling +OAI.Geometry.CylinderCovering.Angular.SamplingArea +OAI.Geometry.CylinderCovering.Angular.SharpArea +OAI.Geometry.CylinderCovering.Angular.SquaredDirect +OAI.Geometry.CylinderCovering.Angular.SquaredDirectDefinitions +OAI.Geometry.CylinderCovering.Angular.Table +OAI.Geometry.CylinderCovering.Angular.TableConsequences +OAI.Geometry.CylinderCovering.Angular.TableCover +OAI.Geometry.CylinderCovering.Angular.TableCoverDefinitions +OAI.Geometry.CylinderCovering.Angular.TableDefinitions +OAI.Geometry.CylinderCovering.Angular.TableFamilyCosts +OAI.Geometry.CylinderCovering.Angular.TableGeometry +OAI.Geometry.CylinderCovering.Angular.TableGeometryDefinitions +OAI.Geometry.CylinderCovering.Angular.Taylor +OAI.Geometry.CylinderCovering.Angular.ZeroTilt +OAI.Geometry.CylinderCovering.Barycentric.CanonicalEnclosure +OAI.Geometry.CylinderCovering.Barycentric.CanonicalMapDefinitions +OAI.Geometry.CylinderCovering.Barycentric.Closure +OAI.Geometry.CylinderCovering.Barycentric.Core +OAI.Geometry.CylinderCovering.Barycentric.CoreDefinitions +OAI.Geometry.CylinderCovering.Barycentric.Correspondence +OAI.Geometry.CylinderCovering.Barycentric.Cost +OAI.Geometry.CylinderCovering.Barycentric.Coverage +OAI.Geometry.CylinderCovering.Barycentric.EmbeddingArea +OAI.Geometry.CylinderCovering.Barycentric.Enclosure +OAI.Geometry.CylinderCovering.Barycentric.EnclosureDefinitions +OAI.Geometry.CylinderCovering.Barycentric.Finite +OAI.Geometry.CylinderCovering.Barycentric.FiniteDefinitions +OAI.Geometry.CylinderCovering.Barycentric.LocalDictionary +OAI.Geometry.CylinderCovering.Barycentric.Metric +OAI.Geometry.CylinderCovering.Barycentric.MetricDefinitions +OAI.Geometry.CylinderCovering.Barycentric.ProjectionFactor +OAI.Geometry.CylinderCovering.Barycentric.Radial +OAI.Geometry.CylinderCovering.Barycentric.Sector +OAI.Geometry.CylinderCovering.Barycentric.SectorDefinitions +OAI.Geometry.CylinderCovering.Barycentric.SectorFinite +OAI.Geometry.CylinderCovering.Barycentric.SectorNeighborhood +OAI.Geometry.CylinderCovering.Barycentric.SectorNeighborhoodDefinitions +OAI.Geometry.CylinderCovering.Barycentric.SweepCompact +OAI.Geometry.CylinderCovering.Barycentric.SweepsDefinitions +OAI.Geometry.CylinderCovering.Beams.Algebra +OAI.Geometry.CylinderCovering.Beams.BeamStrip +OAI.Geometry.CylinderCovering.Beams.Core +OAI.Geometry.CylinderCovering.Beams.Cost +OAI.Geometry.CylinderCovering.Beams.CostDefinitions +OAI.Geometry.CylinderCovering.Beams.Coverage +OAI.Geometry.CylinderCovering.Beams.ExplicitTriangles +OAI.Geometry.CylinderCovering.Beams.Finite +OAI.Geometry.CylinderCovering.Beams.Full +OAI.Geometry.CylinderCovering.Beams.FullDefinitions +OAI.Geometry.CylinderCovering.Beams.FullStatement +OAI.Geometry.CylinderCovering.Beams.Geometry +OAI.Geometry.CylinderCovering.Beams.Main +OAI.Geometry.CylinderCovering.Beams.MainDefinitions +OAI.Geometry.CylinderCovering.Beams.Midsection +OAI.Geometry.CylinderCovering.Beams.Neighborhood +OAI.Geometry.CylinderCovering.Beams.NeighborhoodArea +OAI.Geometry.CylinderCovering.Beams.NeighborhoodCovers +OAI.Geometry.CylinderCovering.Beams.NeighborhoodCoversDefinitions +OAI.Geometry.CylinderCovering.Beams.NeighborhoodDefinitions +OAI.Geometry.CylinderCovering.Beams.NeighborhoodEnclosure +OAI.Geometry.CylinderCovering.Beams.NeighborhoodFinite +OAI.Geometry.CylinderCovering.Beams.NeighborhoodIntrinsic +OAI.Geometry.CylinderCovering.Beams.NeighborhoodRealizationDefinitions +OAI.Geometry.CylinderCovering.Beams.NeighborhoodRiemann +OAI.Geometry.CylinderCovering.Beams.NeighborhoodSimilarity +OAI.Geometry.CylinderCovering.Beams.NeighborhoodSimilarityDefinitions +OAI.Geometry.CylinderCovering.Beams.PositivePart +OAI.Geometry.CylinderCovering.Beams.ProjectionFactor +OAI.Geometry.CylinderCovering.Beams.ProjectionFactorDefinitions +OAI.Geometry.CylinderCovering.Beams.Radial +OAI.Geometry.CylinderCovering.Beams.Rectangle +OAI.Geometry.CylinderCovering.Beams.RectangleCylinder +OAI.Geometry.CylinderCovering.Beams.RectangleSimilarity +OAI.Geometry.CylinderCovering.Beams.SectorGeometry +OAI.Geometry.CylinderCovering.Beams.ShapeCompact +OAI.Geometry.CylinderCovering.Beams.ShapeEquivalence +OAI.Geometry.CylinderCovering.Beams.ShortenedBeamStrip +OAI.Geometry.CylinderCovering.Beams.StatementsDefinitions +OAI.Geometry.CylinderCovering.Beams.StripDefinitions +OAI.Geometry.CylinderCovering.Beams.StripFinite +OAI.Geometry.CylinderCovering.Beams.sDefinitions +OAI.Geometry.CylinderCovering.Caps.CapRegularity +OAI.Geometry.CylinderCovering.Caps.Caps +OAI.Geometry.CylinderCovering.Caps.CapsDefinitions +OAI.Geometry.CylinderCovering.Caps.Certificates +OAI.Geometry.CylinderCovering.Caps.CertificatesDefinitions +OAI.Geometry.CylinderCovering.Caps.CompensationEstimates +OAI.Geometry.CylinderCovering.Caps.CoverageBounds +OAI.Geometry.CylinderCovering.Caps.FiniteArea +OAI.Geometry.CylinderCovering.Caps.FiniteAsymptotics +OAI.Geometry.CylinderCovering.Caps.FiniteCylinders +OAI.Geometry.CylinderCovering.Caps.FiniteDefinitions +OAI.Geometry.CylinderCovering.Caps.FiniteGeometry +OAI.Geometry.CylinderCovering.Caps.FiniteLimit +OAI.Geometry.CylinderCovering.Caps.FiniteProperties +OAI.Geometry.CylinderCovering.Caps.FiniteShape +OAI.Geometry.CylinderCovering.Caps.FiniteShapes +OAI.Geometry.CylinderCovering.Caps.FiniteTheorem +OAI.Geometry.CylinderCovering.Caps.FractionalDefinitions +OAI.Geometry.CylinderCovering.Caps.FractionalEstimates +OAI.Geometry.CylinderCovering.Caps.Geometry +OAI.Geometry.CylinderCovering.Caps.Symmetry +OAI.Geometry.CylinderCovering.Caps.TrapezoidGeometry +OAI.Geometry.CylinderCovering.Caps.TrapezoidGeometryDefinitions +OAI.Geometry.CylinderCovering.Caps.TrapezoidShapes +OAI.Geometry.CylinderCovering.Cartesian.Caps +OAI.Geometry.CylinderCovering.Cartesian.CapsDefinitions +OAI.Geometry.CylinderCovering.Cartesian.Cover +OAI.Geometry.CylinderCovering.Cartesian.CoverDefinitions +OAI.Geometry.CylinderCovering.Cartesian.CoverEligibility +OAI.Geometry.CylinderCovering.Cartesian.Domain +OAI.Geometry.CylinderCovering.Cartesian.DomainDefinitions +OAI.Geometry.CylinderCovering.Cartesian.Full +OAI.Geometry.CylinderCovering.Cartesian.FullDefinitions +OAI.Geometry.CylinderCovering.Cartesian.General +OAI.Geometry.CylinderCovering.Cartesian.GeneralDefinitions +OAI.Geometry.CylinderCovering.Cartesian.Statement +OAI.Geometry.CylinderCovering.Cartesian.StatementDefinitions +OAI.Geometry.CylinderCovering.Convexity.AffineSimplexChord +OAI.Geometry.CylinderCovering.Convexity.AmbientCylinderBridge +OAI.Geometry.CylinderCovering.Convexity.AmbientCylinderDefinitions +OAI.Geometry.CylinderCovering.Convexity.CanonicalRegularSimilarity +OAI.Geometry.CylinderCovering.Convexity.CompactC1Remainder +OAI.Geometry.CylinderCovering.Convexity.CompactEigenframes +OAI.Geometry.CylinderCovering.Convexity.CompactOuterConvergence +OAI.Geometry.CylinderCovering.Convexity.CompactParallelogramApproximation +OAI.Geometry.CylinderCovering.Convexity.CompactParallelogramCover +OAI.Geometry.CylinderCovering.Convexity.CompactProductEigenframes +OAI.Geometry.CylinderCovering.Convexity.CompactSpectralBounds +OAI.Geometry.CylinderCovering.Convexity.ConvexBodyShadowBounds +OAI.Geometry.CylinderCovering.Convexity.ConvexOpenEnlargement +OAI.Geometry.CylinderCovering.Convexity.ConvexPerturbationInverse +OAI.Geometry.CylinderCovering.Convexity.CylinderBridge +OAI.Geometry.CylinderCovering.Convexity.CylinderBridgeDefinitions +OAI.Geometry.CylinderCovering.Convexity.CylinderSimilarity +OAI.Geometry.CylinderCovering.Convexity.EigenframeBounds +OAI.Geometry.CylinderCovering.Convexity.FiniteCauchyVariation +OAI.Geometry.CylinderCovering.Convexity.FiniteLatticeNeighborhood +OAI.Geometry.CylinderCovering.Convexity.FinitePlaneHausdorff +OAI.Geometry.CylinderCovering.Convexity.FinitePlaneMeasure +OAI.Geometry.CylinderCovering.Convexity.GeneralCapArea +OAI.Geometry.CylinderCovering.Convexity.GeneralCapAreaDefinitions +OAI.Geometry.CylinderCovering.Convexity.GeneralCapCoverage +OAI.Geometry.CylinderCovering.Convexity.GeneralCapFamily +OAI.Geometry.CylinderCovering.Convexity.GeneralCapScalarHelpers +OAI.Geometry.CylinderCovering.Convexity.GlobalDefinitions +OAI.Geometry.CylinderCovering.Convexity.InverseSqrtBounds +OAI.Geometry.CylinderCovering.Convexity.IsometricCylinderEmbedding +OAI.Geometry.CylinderCovering.Convexity.IsometricCylinderEmbeddingDefinitions +OAI.Geometry.CylinderCovering.Convexity.LevelCrossing +OAI.Geometry.CylinderCovering.Convexity.NormalFrame +OAI.Geometry.CylinderCovering.Convexity.NormalFrameDefinitions +OAI.Geometry.CylinderCovering.Convexity.NormalFrameProjection +OAI.Geometry.CylinderCovering.Convexity.OpenBaseApproximation +OAI.Geometry.CylinderCovering.Convexity.OpenBaseApproximationDefinitions +OAI.Geometry.CylinderCovering.Convexity.OpenBaseComparison +OAI.Geometry.CylinderCovering.Convexity.OpenBaseThickening +OAI.Geometry.CylinderCovering.Convexity.OpenParallelogram +OAI.Geometry.CylinderCovering.Convexity.OpenParallelogramComparison +OAI.Geometry.CylinderCovering.Convexity.OpenParallelogramDefinitions +OAI.Geometry.CylinderCovering.Convexity.OpenThickening +OAI.Geometry.CylinderCovering.Convexity.OrthonormalHeightComparison +OAI.Geometry.CylinderCovering.Convexity.OrthonormalHeightComparisonDefinitions +OAI.Geometry.CylinderCovering.Convexity.PairedFamilyDefinitions +OAI.Geometry.CylinderCovering.Convexity.ParallelogramGeometry +OAI.Geometry.CylinderCovering.Convexity.ProjectionShapeSupport +OAI.Geometry.CylinderCovering.Convexity.QuadraticTaylorBound +OAI.Geometry.CylinderCovering.Convexity.RegularAngularDefinitions +OAI.Geometry.CylinderCovering.Convexity.RegularBaseVariants +OAI.Geometry.CylinderCovering.Convexity.RegularCounterexamples +OAI.Geometry.CylinderCovering.Convexity.RegularOpenParallelogram +OAI.Geometry.CylinderCovering.Convexity.RegularSimilarityBasis +OAI.Geometry.CylinderCovering.Convexity.RegularSimplexSimilarity +OAI.Geometry.CylinderCovering.Convexity.RelativeCostComparison +OAI.Geometry.CylinderCovering.Convexity.RelaxedInversion +OAI.Geometry.CylinderCovering.Convexity.ResidualDisk +OAI.Geometry.CylinderCovering.Convexity.SimilarityDefinitions +OAI.Geometry.CylinderCovering.Convexity.SlidingRowCertificates +OAI.Geometry.CylinderCovering.Convexity.SpectralNormComparison +OAI.Geometry.CylinderCovering.Convexity.SpectralNormComparisonDefinitions +OAI.Geometry.CylinderCovering.Convexity.SquaredCapCover +OAI.Geometry.CylinderCovering.Convexity.SquaredCapCoverDefinitions +OAI.Geometry.CylinderCovering.Convexity.SquaredCapData +OAI.Geometry.CylinderCovering.Convexity.SquaredCapDataDefinitions +OAI.Geometry.CylinderCovering.Convexity.TetrahedronIdentification +OAI.Geometry.CylinderCovering.Convexity.ThresholdInverse +OAI.Geometry.CylinderCovering.Convexity.ThresholdInversion +OAI.Geometry.CylinderCovering.Convexity.ThresholdRemainder +OAI.Geometry.CylinderCovering.Convexity.TriangularSimilarity +OAI.Geometry.CylinderCovering.Convexity.UniformTaylor +OAI.Geometry.CylinderCovering.Cubic.Contraction +OAI.Geometry.CylinderCovering.Cubic.LowerGeometry +OAI.Geometry.CylinderCovering.Cubic.Profile +OAI.Geometry.CylinderCovering.Cubic.Rescaling +OAI.Geometry.CylinderCovering.Cubic.RescalingDefinitions +OAI.Geometry.CylinderCovering.Cubic.ScalarEstimates +OAI.Geometry.CylinderCovering.Cubic.ScaledLaws +OAI.Geometry.CylinderCovering.Cubic.Similarity +OAI.Geometry.CylinderCovering.Footprints.Area +OAI.Geometry.CylinderCovering.Footprints.Bridge +OAI.Geometry.CylinderCovering.Footprints.Certificates +OAI.Geometry.CylinderCovering.Footprints.CertificatesDefinitions +OAI.Geometry.CylinderCovering.Footprints.Containment +OAI.Geometry.CylinderCovering.Footprints.Convergence +OAI.Geometry.CylinderCovering.Footprints.ConvergenceDefinitions +OAI.Geometry.CylinderCovering.Footprints.Finite +OAI.Geometry.CylinderCovering.Footprints.FiniteDefinitions +OAI.Geometry.CylinderCovering.Footprints.Footprints +OAI.Geometry.CylinderCovering.Footprints.FootprintsDefinitions +OAI.Geometry.CylinderCovering.Footprints.Limits +OAI.Geometry.CylinderCovering.Footprints.PhysicalConvergence +OAI.Geometry.CylinderCovering.Footprints.PhysicalConvergenceDefinitions +OAI.Geometry.CylinderCovering.Footprints.Polygon +OAI.Geometry.CylinderCovering.Footprints.PolygonDefinitions +OAI.Geometry.CylinderCovering.Footprints.Projection +OAI.Geometry.CylinderCovering.Footprints.ProjectionDefinitions +OAI.Geometry.CylinderCovering.Footprints.QuadraticFootprintsDefinitions +OAI.Geometry.CylinderCovering.Footprints.QuadraticPhysicalFootprints +OAI.Geometry.CylinderCovering.Footprints.QuadraticPhysicalFootprintsDefinitions +OAI.Geometry.CylinderCovering.Footprints.Shapes +OAI.Geometry.CylinderCovering.Footprints.ShapesDefinitions +OAI.Geometry.CylinderCovering.Main +OAI.Geometry.CylinderCovering.Nilpotent.ApexBridge +OAI.Geometry.CylinderCovering.Nilpotent.ApexIdentities +OAI.Geometry.CylinderCovering.Nilpotent.ApexNet +OAI.Geometry.CylinderCovering.Nilpotent.ApexNetDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.ApexPhysical +OAI.Geometry.CylinderCovering.Nilpotent.ApexPhysicalDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.BasicDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Bounds +OAI.Geometry.CylinderCovering.Nilpotent.C1 +OAI.Geometry.CylinderCovering.Nilpotent.Construction +OAI.Geometry.CylinderCovering.Nilpotent.ConstructionDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Corollaries +OAI.Geometry.CylinderCovering.Nilpotent.Cost +OAI.Geometry.CylinderCovering.Nilpotent.CostDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Counterexample +OAI.Geometry.CylinderCovering.Nilpotent.DomainExample +OAI.Geometry.CylinderCovering.Nilpotent.DomainExampleDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.ExceptionalSupport +OAI.Geometry.CylinderCovering.Nilpotent.ExplicitCorollaries +OAI.Geometry.CylinderCovering.Nilpotent.Field +OAI.Geometry.CylinderCovering.Nilpotent.FieldDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Finite +OAI.Geometry.CylinderCovering.Nilpotent.FiniteDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Grid +OAI.Geometry.CylinderCovering.Nilpotent.GridBridge +OAI.Geometry.CylinderCovering.Nilpotent.GridConvergence +OAI.Geometry.CylinderCovering.Nilpotent.GridDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.GridMeasure +OAI.Geometry.CylinderCovering.Nilpotent.IntegralSpecialization +OAI.Geometry.CylinderCovering.Nilpotent.Profile +OAI.Geometry.CylinderCovering.Nilpotent.ProfileDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.RadialIntegral +OAI.Geometry.CylinderCovering.Nilpotent.RateAssembly +OAI.Geometry.CylinderCovering.Nilpotent.RateCertificates +OAI.Geometry.CylinderCovering.Nilpotent.RateCertificatesDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.RateCost +OAI.Geometry.CylinderCovering.Nilpotent.RatePhysical +OAI.Geometry.CylinderCovering.Nilpotent.RateUniform +OAI.Geometry.CylinderCovering.Nilpotent.RetainedArea +OAI.Geometry.CylinderCovering.Nilpotent.Rows +OAI.Geometry.CylinderCovering.Nilpotent.ShadowConsequences +OAI.Geometry.CylinderCovering.Nilpotent.ShadowMeasure +OAI.Geometry.CylinderCovering.Nilpotent.ShadowSimilarity +OAI.Geometry.CylinderCovering.Nilpotent.ShadowSimilarityDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.ShearC1 +OAI.Geometry.CylinderCovering.Nilpotent.ShearDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.Similarity +OAI.Geometry.CylinderCovering.Nilpotent.SimilarityDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.SmoothProducer +OAI.Geometry.CylinderCovering.Nilpotent.SmoothRate +OAI.Geometry.CylinderCovering.Nilpotent.SmoothRateDefinitions +OAI.Geometry.CylinderCovering.Nilpotent.SmoothRateTheorem +OAI.Geometry.CylinderCovering.Nilpotent.Theorem +OAI.Geometry.CylinderCovering.Nilpotent.Volume +OAI.Geometry.CylinderCovering.Nilpotent.ZeroProfile +OAI.Geometry.CylinderCovering.Physical.CapFinite +OAI.Geometry.CylinderCovering.Physical.CapFiniteDefinitions +OAI.Geometry.CylinderCovering.Physical.CapMarginThreshold +OAI.Geometry.CylinderCovering.Physical.CapNormalized +OAI.Geometry.CylinderCovering.Physical.CapNormalizedDefinitions +OAI.Geometry.CylinderCovering.Physical.CoordinateStatementDefinitions +OAI.Geometry.CylinderCovering.Physical.Coordinates +OAI.Geometry.CylinderCovering.Physical.CoordinatesDefinitions +OAI.Geometry.CylinderCovering.Physical.Cost +OAI.Geometry.CylinderCovering.Physical.CostDefinitions +OAI.Geometry.CylinderCovering.Physical.CostVariants +OAI.Geometry.CylinderCovering.Physical.CostVariantsDefinitions +OAI.Geometry.CylinderCovering.Physical.Coverage +OAI.Geometry.CylinderCovering.Physical.Finite +OAI.Geometry.CylinderCovering.Physical.FiniteDefinitions +OAI.Geometry.CylinderCovering.Physical.FiniteLimits +OAI.Geometry.CylinderCovering.Physical.FootprintRate +OAI.Geometry.CylinderCovering.Physical.HalfTilt +OAI.Geometry.CylinderCovering.Physical.LocalDictionary +OAI.Geometry.CylinderCovering.Physical.Minimum +OAI.Geometry.CylinderCovering.Physical.MinimumDefinitions +OAI.Geometry.CylinderCovering.Physical.MinimumExamples +OAI.Geometry.CylinderCovering.Physical.PaddedCosts +OAI.Geometry.CylinderCovering.Physical.PaddedFinite +OAI.Geometry.CylinderCovering.Physical.PaddedFiniteDefinitions +OAI.Geometry.CylinderCovering.Physical.Paired +OAI.Geometry.CylinderCovering.Physical.PairedDefinitions +OAI.Geometry.CylinderCovering.Physical.PhysicalFootprints +OAI.Geometry.CylinderCovering.Physical.PhysicalFootprintsDefinitions +OAI.Geometry.CylinderCovering.Physical.ProjectionDictionary +OAI.Geometry.CylinderCovering.Physical.Support +OAI.Geometry.CylinderCovering.Physical.SweepTransport +OAI.Geometry.CylinderCovering.Physical.TetrahedronMinimum +OAI.Geometry.CylinderCovering.Physical.Triangles +OAI.Geometry.CylinderCovering.Physical.TrianglesDefinitions +OAI.Geometry.CylinderCovering.Physical.UnitEdgeFootprints +OAI.Geometry.CylinderCovering.Physical.UnitEdgeFootprintsDefinitions +OAI.Geometry.CylinderCovering.Physical.WeightLipschitz +OAI.Geometry.CylinderCovering.Radial.ActualEndpoint +OAI.Geometry.CylinderCovering.Radial.ActualSweep +OAI.Geometry.CylinderCovering.Radial.Alignment +OAI.Geometry.CylinderCovering.Radial.AreaConvergence +OAI.Geometry.CylinderCovering.Radial.Assembly +OAI.Geometry.CylinderCovering.Radial.CapCosts +OAI.Geometry.CylinderCovering.Radial.CapCoverage +OAI.Geometry.CylinderCovering.Radial.CapVariants +OAI.Geometry.CylinderCovering.Radial.CapVariantsDefinitions +OAI.Geometry.CylinderCovering.Radial.CapsDefinitions +OAI.Geometry.CylinderCovering.Radial.CollarRate +OAI.Geometry.CylinderCovering.Radial.Coordinates +OAI.Geometry.CylinderCovering.Radial.CoordinatesDefinitions +OAI.Geometry.CylinderCovering.Radial.EqualityCover +OAI.Geometry.CylinderCovering.Radial.EqualityCoverDefinitions +OAI.Geometry.CylinderCovering.Radial.FinitePair +OAI.Geometry.CylinderCovering.Radial.FinitePairDefinitions +OAI.Geometry.CylinderCovering.Radial.Freezing +OAI.Geometry.CylinderCovering.Radial.InducedField +OAI.Geometry.CylinderCovering.Radial.InducedFieldDefinitions +OAI.Geometry.CylinderCovering.Radial.Integral +OAI.Geometry.CylinderCovering.Radial.Intercept +OAI.Geometry.CylinderCovering.Radial.JointFailure +OAI.Geometry.CylinderCovering.Radial.Nilpotent +OAI.Geometry.CylinderCovering.Radial.Overlap +OAI.Geometry.CylinderCovering.Radial.OverlapBounds +OAI.Geometry.CylinderCovering.Radial.OverlapDefinitions +OAI.Geometry.CylinderCovering.Radial.OverlapQuantitative +OAI.Geometry.CylinderCovering.Radial.OverlapQuantitativeDefinitions +OAI.Geometry.CylinderCovering.Radial.PairedActual +OAI.Geometry.CylinderCovering.Radial.PairedActualDefinitions +OAI.Geometry.CylinderCovering.Radial.PairedSweep +OAI.Geometry.CylinderCovering.Radial.PairedSweepDefinitions +OAI.Geometry.CylinderCovering.Radial.PartitionAffine +OAI.Geometry.CylinderCovering.Radial.PartitionCover +OAI.Geometry.CylinderCovering.Radial.PolygonProjection +OAI.Geometry.CylinderCovering.Radial.Projection +OAI.Geometry.CylinderCovering.Radial.ProjectionShapes +OAI.Geometry.CylinderCovering.Radial.Regularity +OAI.Geometry.CylinderCovering.Radial.Riemann +OAI.Geometry.CylinderCovering.Radial.RiemannDefinitions +OAI.Geometry.CylinderCovering.Radial.SectorArea +OAI.Geometry.CylinderCovering.Radial.SectorEuclidean +OAI.Geometry.CylinderCovering.Radial.SectorWeighted +OAI.Geometry.CylinderCovering.Radial.SetProjection +OAI.Geometry.CylinderCovering.Radial.SqrtActual +OAI.Geometry.CylinderCovering.Radial.SqrtActualDefinitions +OAI.Geometry.CylinderCovering.Radial.SqrtCap +OAI.Geometry.CylinderCovering.Radial.SqrtCapDefinitions +OAI.Geometry.CylinderCovering.Radial.SqrtRealization +OAI.Geometry.CylinderCovering.Radial.SqrtRealizationDefinitions +OAI.Geometry.CylinderCovering.Radial.SweepDefinitions +OAI.Geometry.CylinderCovering.Radial.TetraGeometry +OAI.Geometry.CylinderCovering.Radial.TetraGeometryDefinitions +OAI.Geometry.CylinderCovering.Radial.Triangle +OAI.Geometry.CylinderCovering.Radial.TriangleDefinitions +OAI.Geometry.CylinderCovering.Radial.UniformApproximation +OAI.Geometry.CylinderCovering.Radial.UniformApproximationDefinitions +OAI.Geometry.CylinderCovering.Radial.UniformTags +OAI.Geometry.CylinderCovering.Radial.Variants +OAI.Geometry.CylinderCovering.Radial.VariantsCore +OAI.Geometry.CylinderCovering.Radial.VariantsCoreDefinitions +OAI.Geometry.CylinderCovering.Radial.VariantsDefinitions +OAI.Geometry.CylinderCovering.Radial.ZeroCapDefinitions +OAI.Geometry.CylinderCovering.Radial.ZeroCapSeparation +OAI.Geometry.CylinderCovering.Rational.Asymptotic +OAI.Geometry.CylinderCovering.Rational.Bundle +OAI.Geometry.CylinderCovering.Rational.CeilingIntegral +OAI.Geometry.CylinderCovering.Rational.CeilingIntegralDefinitions +OAI.Geometry.CylinderCovering.Rational.Coefficients +OAI.Geometry.CylinderCovering.Rational.CoefficientsDefinitions +OAI.Geometry.CylinderCovering.Rational.Construction +OAI.Geometry.CylinderCovering.Rational.ConstructionDefinitions +OAI.Geometry.CylinderCovering.Rational.CoordinateDictionary +OAI.Geometry.CylinderCovering.Rational.CostActual +OAI.Geometry.CylinderCovering.Rational.CostDictionary +OAI.Geometry.CylinderCovering.Rational.CostExpansion +OAI.Geometry.CylinderCovering.Rational.Coverage +OAI.Geometry.CylinderCovering.Rational.DictionaryBridge +OAI.Geometry.CylinderCovering.Rational.DictionaryCoefficients +OAI.Geometry.CylinderCovering.Rational.DictionaryCoefficientsDefinitions +OAI.Geometry.CylinderCovering.Rational.DictionaryCost +OAI.Geometry.CylinderCovering.Rational.DictionaryCostDefinitions +OAI.Geometry.CylinderCovering.Rational.DictionaryDefinitions +OAI.Geometry.CylinderCovering.Rational.DictionaryExpansion +OAI.Geometry.CylinderCovering.Rational.DictionaryExpansionDefinitions +OAI.Geometry.CylinderCovering.Rational.DictionaryFull +OAI.Geometry.CylinderCovering.Rational.DictionaryFullDefinitions +OAI.Geometry.CylinderCovering.Rational.DictionaryStatementDefinitions +OAI.Geometry.CylinderCovering.Rational.Domain +OAI.Geometry.CylinderCovering.Rational.DomainArea +OAI.Geometry.CylinderCovering.Rational.DomainIntegrals +OAI.Geometry.CylinderCovering.Rational.Eligibility +OAI.Geometry.CylinderCovering.Rational.EnergyBounds +OAI.Geometry.CylinderCovering.Rational.EnergyIntegral +OAI.Geometry.CylinderCovering.Rational.EnergyIntegralDefinitions +OAI.Geometry.CylinderCovering.Rational.Equality +OAI.Geometry.CylinderCovering.Rational.EqualityCover +OAI.Geometry.CylinderCovering.Rational.EqualityCoverDefinitions +OAI.Geometry.CylinderCovering.Rational.EqualityDefinitions +OAI.Geometry.CylinderCovering.Rational.Field +OAI.Geometry.CylinderCovering.Rational.FieldDefinitions +OAI.Geometry.CylinderCovering.Rational.Gap +OAI.Geometry.CylinderCovering.Rational.GlobalDifferential +OAI.Geometry.CylinderCovering.Rational.GlobalInversion +OAI.Geometry.CylinderCovering.Rational.GlobalInversionDefinitions +OAI.Geometry.CylinderCovering.Rational.GlobalQuantitative +OAI.Geometry.CylinderCovering.Rational.GlobalTopology +OAI.Geometry.CylinderCovering.Rational.Integrals +OAI.Geometry.CylinderCovering.Rational.InverseSum +OAI.Geometry.CylinderCovering.Rational.Inversion +OAI.Geometry.CylinderCovering.Rational.InversionDefinitions +OAI.Geometry.CylinderCovering.Rational.Lipschitz +OAI.Geometry.CylinderCovering.Rational.LogarithmicPair +OAI.Geometry.CylinderCovering.Rational.LogarithmicStatementDefinitions +OAI.Geometry.CylinderCovering.Rational.Normalization +OAI.Geometry.CylinderCovering.Rational.NormalizedCost +OAI.Geometry.CylinderCovering.Rational.OpenSchedules +OAI.Geometry.CylinderCovering.Rational.OpenSchedulesDefinitions +OAI.Geometry.CylinderCovering.Rational.Padding +OAI.Geometry.CylinderCovering.Rational.Potential +OAI.Geometry.CylinderCovering.Rational.PotentialExamples +OAI.Geometry.CylinderCovering.Rational.Product +OAI.Geometry.CylinderCovering.Rational.ProductDefinitions +OAI.Geometry.CylinderCovering.Rational.RationalThreshold +OAI.Geometry.CylinderCovering.Rational.RationalThresholdSource +OAI.Geometry.CylinderCovering.Rational.Realization +OAI.Geometry.CylinderCovering.Rational.RealizationDefinitions +OAI.Geometry.CylinderCovering.Rational.ScheduleExpansions +OAI.Geometry.CylinderCovering.Rational.Schedules +OAI.Geometry.CylinderCovering.Rational.Similarity +OAI.Geometry.CylinderCovering.Rational.SimilarityDefinitions +OAI.Geometry.CylinderCovering.Rational.StrictInverse +OAI.Geometry.CylinderCovering.Rational.TetrahedronDiameter +OAI.Geometry.CylinderCovering.Rational.TetrahedronGeometry +OAI.Geometry.CylinderCovering.Rational.TetrahedronGeometryDefinitions +OAI.Geometry.CylinderCovering.Rational.TetrahedronVolume +OAI.Geometry.CylinderCovering.Rational.ThresholdBounds +OAI.Geometry.CylinderCovering.Rational.ThresholdDefinitions +OAI.Geometry.CylinderCovering.Rational.ThresholdExpansion +OAI.Geometry.CylinderCovering.Rational.UncenteredCoefficients +OAI.Geometry.CylinderCovering.Rational.UncenteredCoefficientsDefinitions +OAI.Geometry.CylinderCovering.Rational.UncenteredField +OAI.Geometry.CylinderCovering.Rational.UncenteredLogarithmic +OAI.Geometry.CylinderCovering.Rational.UncenteredPotential +OAI.Geometry.CylinderCovering.Rational.UncenteredPotentialDefinitions +OAI.Geometry.CylinderCovering.Rational.UncenteredThreshold +OAI.Geometry.CylinderCovering.Rational.UncenteredThresholdDefinitions +OAI.Geometry.CylinderCovering.Rational.Wedge +OAI.Geometry.CylinderCovering.Results +OAI.Geometry.CylinderCovering.Ruled.BoundaryCertificates +OAI.Geometry.CylinderCovering.Ruled.C1Definitions +OAI.Geometry.CylinderCovering.Ruled.CellArea +OAI.Geometry.CylinderCovering.Ruled.CellCoordinates +OAI.Geometry.CylinderCovering.Ruled.CellCost +OAI.Geometry.CylinderCovering.Ruled.CellGeometry +OAI.Geometry.CylinderCovering.Ruled.CellsDefinitions +OAI.Geometry.CylinderCovering.Ruled.Comparison +OAI.Geometry.CylinderCovering.Ruled.ComparisonDefinitions +OAI.Geometry.CylinderCovering.Ruled.EigenframeGeometry +OAI.Geometry.CylinderCovering.Ruled.Fubini +OAI.Geometry.CylinderCovering.Ruled.Jacobian +OAI.Geometry.CylinderCovering.Ruled.Local +OAI.Geometry.CylinderCovering.Ruled.LocalCylinder +OAI.Geometry.CylinderCovering.Ruled.LocalDefinitions +OAI.Geometry.CylinderCovering.Ruled.LocalEndpoint +OAI.Geometry.CylinderCovering.Ruled.LocalGeometry +OAI.Geometry.CylinderCovering.Ruled.LogarithmicLocalDefinitions +OAI.Geometry.CylinderCovering.Ruled.MotionJacobian +OAI.Geometry.CylinderCovering.Ruled.NullDomain +OAI.Geometry.CylinderCovering.Ruled.Patch +OAI.Geometry.CylinderCovering.Ruled.Projection +OAI.Geometry.CylinderCovering.Ruled.ProjectionDefinitions +OAI.Geometry.CylinderCovering.Ruled.Remainder +OAI.Geometry.CylinderCovering.Ruled.Retention +OAI.Geometry.CylinderCovering.Ruled.RetentionArea +OAI.Geometry.CylinderCovering.Ruled.Similarity +OAI.Geometry.CylinderCovering.Ruled.SquareArea +OAI.Geometry.CylinderCovering.Ruled.WeightedCost +OAI.Geometry.CylinderCovering.Ruled.ZeroDiagonal +OAI.Geometry.CylinderCovering.Ruled.ZeroDiagonalDefinitions +OAI.Geometry.CylinderCovering.Simplex.Chord +OAI.Geometry.CylinderCovering.Simplex.Diameter +OAI.Geometry.CylinderCovering.Simplex.DiameterBridge +OAI.Geometry.CylinderCovering.Simplex.DiameterDefinitions +OAI.Geometry.CylinderCovering.Simplex.LayerCake +OAI.Geometry.CylinderCovering.Simplex.MetricNormalizationDefinitions +OAI.Geometry.CylinderCovering.Simplex.OverlapVolume +OAI.Geometry.CylinderCovering.Simplex.Projection +OAI.Geometry.CylinderCovering.Simplex.ProjectionDefinitions +OAI.Geometry.CylinderCovering.Simplex.ProjectionIdentity +OAI.Geometry.CylinderCovering.Simplex.ZeroShift +OAI.Geometry.CylinderCovering.Singular.Basic +OAI.Geometry.CylinderCovering.Singular.BasicDefinitions +OAI.Geometry.CylinderCovering.Singular.Cost +OAI.Geometry.CylinderCovering.Singular.Cutoff +OAI.Geometry.CylinderCovering.Singular.CutoffDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOne +OAI.Geometry.CylinderCovering.Singular.EdgeOneCost +OAI.Geometry.CylinderCovering.Singular.EdgeOneCover +OAI.Geometry.CylinderCovering.Singular.EdgeOneCoverDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOneDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOneDifferential +OAI.Geometry.CylinderCovering.Singular.EdgeOneDifferentialDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOneGeometry +OAI.Geometry.CylinderCovering.Singular.EdgeOneGeometryDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOneNormalization +OAI.Geometry.CylinderCovering.Singular.EdgeOneNormalizationDefinitions +OAI.Geometry.CylinderCovering.Singular.EdgeOneResults +OAI.Geometry.CylinderCovering.Singular.EdgeOneResultsDefinitions +OAI.Geometry.CylinderCovering.Singular.Endpoint +OAI.Geometry.CylinderCovering.Singular.Extensions +OAI.Geometry.CylinderCovering.Singular.ExtensionsDefinitions +OAI.Geometry.CylinderCovering.Singular.Hessian +OAI.Geometry.CylinderCovering.Singular.HessianDefinitions +OAI.Geometry.CylinderCovering.Singular.Orthogonal +OAI.Geometry.CylinderCovering.Singular.OverlapRemainder +OAI.Geometry.CylinderCovering.Singular.ParameterRange +OAI.Geometry.CylinderCovering.Singular.ParameterRangeDefinitions +OAI.Geometry.CylinderCovering.Singular.Stream +OAI.Geometry.CylinderCovering.Singular.StreamDefinitions +OAI.Geometry.RuledCovering.CapAsymptotics +OAI.Geometry.RuledCovering.ConeVolume +OAI.Geometry.RuledCovering.ConvexBases +OAI.Geometry.RuledCovering.EnergyIntegral +OAI.Geometry.RuledCovering.Frames +OAI.Geometry.RuledCovering.Hyperbolic +OAI.Geometry.RuledCovering.HyperbolicCover +OAI.Geometry.RuledCovering.HyperbolicLattice +OAI.Geometry.RuledCovering.Isometries +OAI.Geometry.RuledCovering.Lattice +OAI.Geometry.RuledCovering.LocalApproximation +OAI.Geometry.RuledCovering.LocalCover +OAI.Geometry.RuledCovering.Main +OAI.Geometry.RuledCovering.Model +OAI.Geometry.RuledCovering.Nilpotent +OAI.Geometry.RuledCovering.NilpotentLattice +OAI.Geometry.RuledCovering.OuterApproximation +OAI.Geometry.RuledCovering.PlanarIntegration +OAI.Geometry.RuledCovering.Projection +OAI.Geometry.RuledCovering.Singular +OAI.Geometry.RuledCovering.SingularAsymptotics +OAI.Geometry.RuledCovering.SingularBounds +OAI.Geometry.RuledCovering.SingularEnergy +OAI.Geometry.RuledCovering.SingularField +OAI.Geometry.RuledCovering.SingularGeometry +OAI.Geometry.RuledCovering.SingularInverse +OAI.Geometry.RuledCovering.SingularOverlap +OAI.Geometry.RuledCovering.SpecializedCover +OAI.Geometry.RuledCovering.SquareCover +OAI.Geometry.RuledCovering.TipCylinders +OAI.Geometry.TriangularCovering.Asymptotics +OAI.Geometry.TriangularCovering.Basic +OAI.Geometry.TriangularCovering.CoordinateCover +OAI.Geometry.TriangularCovering.CylinderFamily +OAI.Geometry.TriangularCovering.Main +OAI.Geometry.TriangularCovering.Projection +OAI.Geometry.TriangularCovering.Shadows +OAI.Geometry.TriangularCovering.Tetrahedron +OAI.Geometry.TriangularCovering.TriangleArea diff --git a/tasks/cylinder-covering/solution/reference.py b/tasks/cylinder-covering/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/cylinder-covering/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/cylinder-covering/solution/solve.sh b/tasks/cylinder-covering/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..29d0cf0d0d8ee6e3334e463a83031ef77e069a33 --- /dev/null +++ b/tasks/cylinder-covering/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of CylinderCovering, i.e. module OAI.Geometry.CylinderCovering.Main and the +# 641 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.CylinderCovering.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of CylinderCovering" diff --git a/tasks/cylinder-covering/task.toml b/tasks/cylinder-covering/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..89584dcdb042610b4a8ffac0bee9e300066b7e4a --- /dev/null +++ b/tasks/cylinder-covering/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/cylinder-covering" +version = "1.0.0" +description = "Prove CylinderCovering (openai/math family 100: A counterexample to Bang's cylinder-covering bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/CylinderCovering.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "CylinderCovering" +family = "100" +family_title = "A counterexample to Bang's cylinder-covering bound" +subject = "Convex and metric geometry" +theorems = ["OAI.CylinderCovering.fourPaperMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.CylinderCovering.Main" +reference_modules = 641 +reference_lean_bytes = 3013309 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2016 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14411 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/cylinder-covering/tests/Challenge.lean b/tasks/cylinder-covering/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..21967ad0942869aef0115df93dc31793025e3692 --- /dev/null +++ b/tasks/cylinder-covering/tests/Challenge.lean @@ -0,0 +1,573 @@ +import Mathlib + +namespace OAI + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def H : ℝ := Real.sqrt 2 + +def point (x y t : ℝ) : Space := !₂[x, y, H * t] + +def K : Set Space := + {z | ∃ x y t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |x| ≤ 1 - t ∧ |y| ≤ t ∧ z = point x y t} + +def projection (u z : Space) : Space := z - (inner ℝ u z) • u + +def area (B : Set Space) : ℝ := (Measure.euclideanHausdorffMeasure 2 B).toReal + +def shadowArea (u : Space) : ℝ := area (projection u '' K) + +def A_min : ℝ := sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea u} + +structure TriCylinder where + axis : Space + base : Set Space + unit_axis : ‖axis‖ = 1 + perpendicular : ∀ z ∈ base, inner ℝ axis z = 0 + triangular : ∃ v : Fin 3 → Space, AffineIndependent ℝ v ∧ + base = convexHull ℝ (Set.range v) + compact : IsCompact base + convex : Convex ℝ base + measurable : MeasurableSet base + finite_area : Measure.euclideanHausdorffMeasure 2 base ≠ ⊤ + +def TriCylinder.carrier (c : TriCylinder) : Set Space := + {z | ∃ b ∈ c.base, ∃ r : ℝ, z = b + r • c.axis} + +def Covers {m : ℕ} (c : Fin m → TriCylinder) : Prop := + ∀ z ∈ K, ∃ i : Fin m, z ∈ (c i).carrier + +def totalArea {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base + +def relativeCost {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base / shadowArea (c i).axis + +def n (ε : ℝ) : ℕ := ⌈2 / ε ^ 2⌉₊ +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def η : ℝ := 1 / 1000 + +def alpha (a b : ℝ) : ℝ := (1 + a * b) / 4 + +def beta (a b : ℝ) : ℝ := (a + b) / 4 + +def d (q : ℝ) : ℝ := q ^ 2 * (1 + q ^ 2) / 16 + +def cutoffCoeff (a b : ℝ) : ℝ := η + max (d a) (d b) + +def step (N : ℕ) : ℝ := 2 / N + +def mesh (N i : ℕ) : ℝ := -1 + i * step N + +def cutoff (ε a b : ℝ) : ℝ := 1 / 2 + ε ^ 2 * cutoffCoeff a b + +def speedSq (a b : ℝ) : ℝ := (alpha a b)^2 + 2*(beta a b)^2 + +def normalizedTerm (ε a b : ℝ) : ℝ := + (b-a) * (cutoff ε a b)^2 / Real.sqrt (1+ε^2*speedSq a b) + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def unit (v : Space) : Space := ‖v‖⁻¹ • v + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +def tiltV (ε A B : ℝ) : Space := !₂[1, ε*A, H*ε*B] + +def tiltW (ε A B : ℝ) : Space := !₂[-ε*A, 1, H*ε*B] + +def lowerVertices (a b T : ℝ) : Fin 3 → Space := + ![point 0 0 0, point 0 (a*T) T, point 0 (b*T) T] + +def upperVertices (a b T : ℝ) : Fin 3 → Space := + ![point 0 0 1, point (a*T) 0 (1-T), point (b*T) 0 (1-T)] + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering.Planar + +abbrev Coord := Fin 2 → ℝ + +def standard : Set Coord := {x | 0 ≤ x 0 ∧ 0 ≤ x 1 ∧ x 0 + x 1 ≤ 1} + +def vertices : Fin 3 → Coord := ![0, ![1, 0], ![0, 1] ] + +end TriangularCovering.Planar + +namespace TriangularCovering + +section Triangles +variable {E F : Type*} [AddCommGroup E] [Module ℝ E] [AddCommGroup F] [Module ℝ F] + +def triangle (a b c : E) : Set E := convexHull ℝ (range (![a, b, c] : Fin 3 → E)) + +end Triangles +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory +open scoped InnerProductSpace + +noncomputable section +namespace TriangularCovering + +def lowerAngularIndex {N : ℕ} (j : Fin N) : Fin (2*N) := + Fin.cast (two_mul N).symm (Fin.castAdd N j) + +def upperAngularIndex {N : ℕ} (j : Fin N) : Fin (2*N) := + Fin.cast (two_mul N).symm (Fin.natAdd N j) + +def lowerAngularAxis (ε : ℝ) (j : ℕ) : Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + unit (tiltV ε (alpha a b) (beta a b)) + +def upperAngularAxis (ε : ℝ) (j : ℕ) : Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + unit (tiltW ε (alpha a b) (beta a b)) + +def lowerAngularBase (ε : ℝ) (j : ℕ) : Set Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + let v := lowerVertices a b (cutoff ε a b) + projection (lowerAngularAxis ε j) '' triangle (v 0) (v 1) (v 2) + +def upperAngularBase (ε : ℝ) (j : ℕ) : Set Space := + let a := mesh (n ε) j + let b := mesh (n ε) (j+1) + let v := upperVertices a b (cutoff ε a b) + projection (upperAngularAxis ε j) '' triangle (v 0) (v 1) (v 2) + +def ExplicitAngularFamily (ε : ℝ) (c : Fin (2*n ε) → TriCylinder) : Prop := + ∀ j : Fin (n ε), + (c (lowerAngularIndex j)).axis = lowerAngularAxis ε j ∧ + (c (lowerAngularIndex j)).base = lowerAngularBase ε j ∧ + (c (upperAngularIndex j)).axis = upperAngularAxis ε j ∧ + (c (upperAngularIndex j)).base = upperAngularBase ε j + +def AngularAreaStatement : Prop := + ∀ ε : ℝ, 0 < ε → ε ≤ 1 → + ∃ c : Fin (2*n ε) → TriCylinder, + ExplicitAngularFamily ε c ∧ + totalArea c/H = ∑ j : Fin (n ε), + normalizedTerm ε (mesh (n ε) j) (mesh (n ε) (j+1)) ∧ + |totalArea c/H - (1/2-(13/6000:ℝ)*ε^2)| ≤ 2*ε^4 + +def ExplicitAngularStatement : Prop := + A_min = H ∧ + ∀ ε : ℝ, 0 < ε → ε ≤ 1/2000 → + ∃ c : Fin (2*n ε) → TriCylinder, + ExplicitAngularFamily ε c ∧ Covers c ∧ + |totalArea c/H - (1/2-(13/6000:ℝ)*ε^2)| ≤ 2*ε^4 ∧ + totalArea c < A_min/2 ∧ relativeCost c < 1/2 + +end TriangularCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory Filter Metric +open scoped Topology ContDiff Pointwise +namespace RuledApproximation + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev Space := EuclideanSpace ℝ (Fin 3) +def vec2 (x y : ℝ) : Plane := WithLp.toLp 2 ![x, y] +def vec3 (x y z : ℝ) : Space := WithLp.toLp 2 ![x, y, z] +def axial (s : ℝ) (p : Plane) : Space := vec3 s (p 0) (p 1) + +def IsParallelogram {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s ∈ Icc (0 : ℝ) 1, ∃ t ∈ Icc (0 : ℝ) 1, + x = c + s • u + t • v} +structure Cylinder where + axis : Space + unit_axis : ‖axis‖ = 1 + base : Set ((Submodule.span ℝ ({axis} : Set Space))ᗮ) + +namespace Cylinder + +def carrier (C : Cylinder) : Set Space := + {x | ∃ b ∈ C.base, ∃ t : ℝ, x = (b : Space) + t • C.axis} + +def area (C : Cylinder) : ℝ := volume.real C.base + +def parallelogram (C : Cylinder) : Prop := IsParallelogram C.base + +def openBounded (C : Cylinder) : Prop := + IsOpen C.base ∧ Bornology.IsBounded C.base ∧ MeasurableSet C.base +end Cylinder + +def familySet {n : ℕ} (C : Fin n → Cylinder) : Set Space := ⋃ i, (C i).carrier +def familyArea {n : ℕ} (C : Fin n → Cylinder) : ℝ := ∑ i, (C i).area + +def HasFiniteCover (shape : Cylinder → Prop) (S : Set Space) (A : ℝ) : Prop := + ∃ n : ℕ, ∃ C : Fin n → Cylinder, + (∀ i, shape (C i)) ∧ S ⊆ familySet C ∧ familyArea C ≤ A + +def SmoothNear (n : WithTop ℕ∞) (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ D ⊆ U ∧ ContDiffOn ℝ n v U + +def HyperbolicAt (L : ℝ) (v : Plane → Plane) (p : Plane) : Prop := + ∃ lam : ℝ, 0 < L * lam ∧ L * lam < 1 ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap lam ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap (-lam) + +def weight (v : Plane) : ℝ := 1 / Real.sqrt (1 + ‖v‖ ^ 2) +def physicalWeight (h : ℝ) (w : Plane) : ℝ := + 1 / Real.sqrt (1 + w 0 ^ 2 + h ^ 2 * w 1 ^ 2) + +def ruled (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ r : ℝ, |r| ≤ L ∧ + z = vec3 (p 0 + r * v p 0) (p 1 + r * v p 1) r} + +def physicalRuled (h : ℝ) (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ s : ℝ, |s| ≤ L ∧ + z = vec3 s (p 0 + s * v p 0) (h * (p 1 + s * v p 1))} + +def HyperbolicStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (L : ℝ), + IsCompact D → SmoothNear 1 D v → 0 < L → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram (ruled D v L) + ((∫ p in D, weight (v p)) + e) + +def unitSquare : Set Plane := {x | ∀ i, |x i| ≤ (1 : ℝ) / 2} + +def IsSquareTile (T : Set Plane) : Prop := + ∃ c : Plane, ∃ R : Plane ≃ₗᵢ[ℝ] Plane, ∃ a : ℝ, 0 < a ∧ + T = (fun x => c + a • R x) '' unitSquare + +def auxiliaryCylinder (T : Set Plane) (g : Plane) : Set Space := + {z | ∃ s : ℝ, ∃ b ∈ T, z = axial s (b + s • g)} + +def firstPhysicalMap (h : ℝ) (z : Space) : Space := vec3 (z 0) (z 1) (h * z 2) +def secondPhysicalMap (h a : ℝ) (z : Space) : Space := + vec3 (z 1) (z 0) (h * (a - z 2)) +end RuledApproximation +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory +open scoped InnerProductSpace + +namespace CylinderCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def IsRegularTetrahedron (K : Set Space) : Prop := + ∃ v : Fin 4 → Space, AffineIndependent ℝ v ∧ + ∃ edge : ℝ, 0 < edge ∧ + (∀ i j : Fin 4, i ≠ j → dist (v i) (v j) = edge) ∧ + K = convexHull ℝ (range v) + +def shadowArea (K : Set Space) (u : Space) : ℝ := + TriangularCovering.area (TriangularCovering.projection u '' K) + +def minimumShadowArea (K : Set Space) : ℝ := + sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea K u} + +def triangularCovers {n : ℕ} (K : Set Space) + (C : Fin n → TriangularCovering.TriCylinder) : Prop := + ∀ x ∈ K, ∃ i : Fin n, x ∈ (C i).carrier + +def triangularRelativeCost {n : ℕ} (K : Set Space) + (C : Fin n → TriangularCovering.TriCylinder) : ℝ := + ∑ i, TriangularCovering.area (C i).base / shadowArea K (C i).axis + +def relativeCost {n : ℕ} (K : Set Space) + (C : Fin n → RuledApproximation.Cylinder) : ℝ := + ∑ i, (C i).area / shadowArea K (C i).axis + +def AngularExplicitStatement : Prop := + TriangularCovering.AngularAreaStatement ∧ TriangularCovering.ExplicitAngularStatement + +def RegularTriangularCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → TriangularCovering.TriCylinder, + triangularCovers K C ∧ + TriangularCovering.totalArea C < minimumShadowArea K / 2 ∧ + triangularRelativeCost K C < 1 / 2 + +def RegularParallelogramCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → RuledApproximation.Cylinder, + (∀ i, (C i).parallelogram) ∧ + K ⊆ RuledApproximation.familySet C ∧ + RuledApproximation.familyArea C < minimumShadowArea K / 2 ∧ + relativeCost K C < 1 / 2 + +def RegularOpenCounterexampleStatement : Prop := + ∀ K : Set Space, IsRegularTetrahedron K → + ∃ n : ℕ, ∃ C : Fin n → RuledApproximation.Cylinder, + (∀ i, (C i).openBounded) ∧ + K ⊆ RuledApproximation.familySet C ∧ + RuledApproximation.familyArea C < minimumShadowArea K / 2 ∧ + relativeCost K C < 1 / 2 + +end CylinderCovering +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +open Set MeasureTheory Filter +open scoped Topology ContDiff +namespace RuledApproximation + +def NilpotentC1Statement : Prop := + ∀ (D : Set Plane) (G : Plane → Plane), IsCompact D → SmoothNear 1 D G → + (∀ b ∈ D, (fderiv ℝ G b).comp (fderiv ℝ G b) = 0) → + ∀ h eps : ℝ, 0 < h → 0 < eps → + ∃ n : ℕ, ∃ T : Fin n → Set Plane, ∃ g : Fin n → Plane, + (∀ i, IsSquareTile (T i)) ∧ + physicalRuled 1 D G 1 ⊆ ⋃ i, auxiliaryCylinder (T i) (g i) ∧ + (∑ i, volume.real (T i) * physicalWeight h (g i)) ≤ + (∫ b in D, physicalWeight h (G b)) + eps ∧ + ∀ a : ℝ, ∃ C₁ C₂ : Fin n → Cylinder, + (∀ i, (C₁ i).parallelogram ∧ (C₂ i).parallelogram ∧ + (C₁ i).carrier = firstPhysicalMap h '' auxiliaryCylinder (T i) (g i) ∧ + (C₂ i).carrier = secondPhysicalMap h a '' auxiliaryCylinder (T i) (g i) ∧ + (C₁ i).area = h * volume.real (T i) * physicalWeight h (g i) ∧ + (C₂ i).area = h * volume.real (T i) * physicalWeight h (g i)) + +end RuledApproximation +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +noncomputable section +namespace CylinderCovering.RadialRiemann +open Set + +def step (a b : ℝ) (N : ℕ) : ℝ := (b - a) / N + +def point (a b : ℝ) (N i : ℕ) : ℝ := a + i * step a b N + +def cell (a b : ℝ) (N : ℕ) (i : Fin N) : Set ℝ := + Icc (point a b N i) (point a b N (i + 1)) + +def IsTagged (a b : ℝ) (N : ℕ) (tag : Fin N → ℝ) : Prop := + ∀ i, tag i ∈ cell a b N i + +def capMax (R : ℝ → ℝ) (a b : ℝ) (N : ℕ) (i : Fin N) : ℝ := + sSup (R '' cell a b N i) +end CylinderCovering.RadialRiemann +end +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +section +open Set MeasureTheory Filter +open scoped InnerProductSpace Topology + +noncomputable section + +namespace CylinderCovering.RadialSweep + +abbrev Space := TriangularCovering.Space + +structure Data where + e : Space + a : Space + b : Space + p₀ : Space + α : ℝ + β : ℝ + L : ℝ + R : ℝ → ℝ + lam : ℝ → ℝ + w : ℝ → Space + interval_nonempty : α < β + length_pos : 0 < L + normal_unit : ‖e‖ = 1 + a_perp : inner ℝ e a = 0 + b_perp : inner ℝ e b = 0 + origin_perp : inner ℝ e p₀ = 0 + independent : LinearIndependent ℝ ![a, b] + cap_continuous : ContinuousOn R (Icc α β) + cap_nonneg : ∀ t ∈ Icc α β, 0 ≤ R t + scalar_continuous : ContinuousOn lam (Icc α β) + velocity_continuous : ContinuousOn w (Icc α β) + velocity_perp : ∀ t ∈ Icc α β, inner ℝ e (w t) = 0 + aligned : ∀ t ∈ Icc α β, + HasDerivWithinAt w (lam t • (a + t • b)) (Icc α β) t + +def sweep (D : Data) : Set Space := + {z | ∃ t ∈ Icc D.α D.β, ∃ ρ ∈ Icc (0 : ℝ) (D.R t), + ∃ s : ℝ, |s| ≤ D.L ∧ + z = D.p₀ + ρ • (D.a + t • D.b) + s • (D.e + D.w t)} + +def kappa (D : Data) : ℝ := + Real.sqrt (inner ℝ D.a D.a * inner ℝ D.b D.b - (inner ℝ D.a D.b) ^ 2) + +def direction (D : Data) (t : ℝ) : Space := + ‖D.e + D.w t‖⁻¹ • (D.e + D.w t) + +def weightedArea (D : Data) : ℝ := + kappa D * ∫ t in D.α..D.β, + D.R t ^ 2 / (2 * Real.sqrt (1 + ‖D.w t‖ ^ 2)) + +def scalarBound (D : Data) : ℝ := sSup ((fun t => |D.lam t|) '' Icc D.α D.β) + +def radialError (D : Data) : ℝ := D.L * scalarBound D + +def collar (D : Data) : ℝ := 3 * radialError D + 1 + +def midpoint (D : Data) (N : ℕ) (i : Fin N) : ℝ := + (RadialRiemann.point D.α D.β N i + RadialRiemann.point D.α D.β N (i + 1)) / 2 + +def leftTip (D : Data) (N : ℕ) : ℝ := -collar D * RadialRiemann.step D.α D.β N + +def rightEdge (D : Data) (N : ℕ) (i : Fin N) : ℝ := + RadialRiemann.capMax D.R D.α D.β N i + radialError D * RadialRiemann.step D.α D.β N + +def coordinateMap (D : Data) (p : ℝ × ℝ) : Space := D.p₀ + p.1 • D.a + p.2 • D.b + +def frozenVertices (D : Data) (N : ℕ) (i : Fin N) : Fin 3 → Space := + let l := leftTip D N + let r := rightEdge D N i + let m := midpoint D N i + let d := RadialRiemann.step D.α D.β N + ![coordinateMap D (l, m * l), + coordinateMap D (r, m * r - d / 2 * (r - l)), + coordinateMap D (r, m * r + d / 2 * (r - l))] + +def frozenTriangle (D : Data) (N : ℕ) (i : Fin N) : Set Space := + convexHull ℝ (Set.range (frozenVertices D N i)) + +def frozenBase (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : Set Space := + TriangularCovering.projection (direction D (tag i)) '' frozenTriangle D N i + +def frozenArea (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : ℝ := + kappa D * RadialRiemann.step D.α D.β N * + (RadialRiemann.capMax D.R D.α D.β N i + + (radialError D + collar D) * RadialRiemann.step D.α D.β N) ^ 2 / + (2 * Real.sqrt (1 + ‖D.w (tag i)‖ ^ 2)) + +def localSweep (D : Data) (N : ℕ) (i : Fin N) : Set Space := + {z | ∃ t ∈ RadialRiemann.cell D.α D.β N i, + ∃ ρ ∈ Icc (0 : ℝ) (D.R t), ∃ s : ℝ, |s| ≤ D.L ∧ + z = D.p₀ + ρ • (D.a + t • D.b) + s • (D.e + D.w t)} + +def actualBase (D : Data) (N : ℕ) (tag : Fin N → ℝ) (i : Fin N) : Set Space := + TriangularCovering.projection (direction D (tag i)) '' localSweep D N i + +def cylinder (u : Space) (B : Set Space) : Set Space := + {z | ∃ b ∈ B, ∃ s : ℝ, z = b + s • u} + +def actualCost (D : Data) (N : ℕ) (tag : Fin N → ℝ) : ℝ := + ∑ i : Fin N, TriangularCovering.area (actualBase D N tag i) + +def AlignedStatement : Prop := + ∀ D : Data, ∀ tag : (N : ℕ) → Fin N → ℝ, + (∀ N, RadialRiemann.IsTagged D.α D.β N (tag N)) → + ∃ C : (N : ℕ) → Fin N → TriangularCovering.TriCylinder, + (∀ N, 0 < N → + (∀ i, (C N i).axis = direction D (tag N i) ∧ + (C N i).base = frozenBase D N (tag N) i ∧ + TriangularCovering.area (C N i).base = frozenArea D N (tag N) i) ∧ + (∀ z ∈ sweep D, ∃ i : Fin N, z ∈ (C N i).carrier)) ∧ + Tendsto (fun N => TriangularCovering.totalArea (C N)) atTop (𝓝 (weightedArea D)) + +def ActualSweepStatement : Prop := + ∀ D : Data, ∀ tag : (N : ℕ) → Fin N → ℝ, + (∀ N, RadialRiemann.IsTagged D.α D.β N (tag N)) → + (∀ N, 0 < N → + (∀ i : Fin N, ‖direction D (tag N i)‖ = 1 ∧ + IsCompact (actualBase D N (tag N) i) ∧ + MeasurableSet (actualBase D N (tag N) i) ∧ + Measure.euclideanHausdorffMeasure 2 (actualBase D N (tag N) i) ≠ ⊤ ∧ + (∀ z ∈ actualBase D N (tag N) i, inner ℝ (direction D (tag N i)) z = 0) ∧ + actualBase D N (tag N) i ⊆ frozenBase D N (tag N) i) ∧ + (∀ z ∈ sweep D, ∃ i : Fin N, + z ∈ cylinder (direction D (tag N i)) (actualBase D N (tag N) i))) ∧ + (∀ ε : ℝ, 0 < ε → ∀ᶠ N in atTop, actualCost D N (tag N) ≤ weightedArea D + ε) ∧ + Filter.limsup (fun N => actualCost D N (tag N)) atTop ≤ weightedArea D + +end CylinderCovering.RadialSweep +end +end + +namespace CylinderCovering + +theorem fourPaperMain : + AngularExplicitStatement ∧ + RuledApproximation.HyperbolicStatement ∧ + RuledApproximation.NilpotentC1Statement ∧ + RegularParallelogramCounterexampleStatement ∧ + RegularOpenCounterexampleStatement ∧ + RadialSweep.AlignedStatement ∧ + RadialSweep.ActualSweepStatement := by + sorry + +end CylinderCovering + +end OAI diff --git a/tasks/cylinder-covering/tests/grade.py b/tasks/cylinder-covering/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/cylinder-covering/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/cylinder-covering/tests/task.json b/tasks/cylinder-covering/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b0be62d8ca5d5e9c6fc5381a4b8d6e4e3530d20f --- /dev/null +++ b/tasks/cylinder-covering/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "CylinderCovering", + "comparator": { + "theorem_names": [ + "OAI.CylinderCovering.fourPaperMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13511 +} \ No newline at end of file diff --git a/tasks/cylinder-covering/tests/test.sh b/tasks/cylinder-covering/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/cylinder-covering/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/daugavet-moduli/environment/Dockerfile b/tasks/daugavet-moduli/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/daugavet-moduli/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/daugavet-moduli/environment/fetch_mathlib.sh b/tasks/daugavet-moduli/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/daugavet-moduli/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/daugavet-moduli/environment/lake-manifest.json b/tasks/daugavet-moduli/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/daugavet-moduli/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/daugavet-moduli/environment/lakefile.lean b/tasks/daugavet-moduli/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/daugavet-moduli/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/daugavet-moduli/environment/lean_setup.sh b/tasks/daugavet-moduli/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/daugavet-moduli/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/daugavet-moduli/environment/pack_submission.py b/tasks/daugavet-moduli/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/daugavet-moduli/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/daugavet-moduli/instruction.md b/tasks/daugavet-moduli/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e977c5e00ca3f02af7fa117d2035f1e173409f8f --- /dev/null +++ b/tasks/daugavet-moduli/instruction.md @@ -0,0 +1,159 @@ +# openai/math challenge `DaugavetModuli` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `DaugavetModuli`, also at `/opt/openai-math/challenges/DaugavetModuli.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter Set +open scoped ENNReal NNReal Topology + +universe uX u_1 + +namespace ExactModuli + +variable {X : Type uX} [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Closed linear subspaces of finite codimension. -/ +def Cofinite (F : Submodule ℝ X) : Prop := + IsClosed (F : Set X) ∧ FiniteDimensional ℝ (X ⧸ F) + +/-- Averaged increment for directions of norm at least one. -/ +def averagedIncrement (N : Seminorm ℝ X) (x : X) (t : ℝ) (y : X) : ℝ := + (N (x + t • y) + N (x - t • y)) / 2 - 1 + +def H (N : Seminorm ℝ X) (x : X) (t : ℝ) : ℝ := + sSup {r | ∃ F : Submodule ℝ X, Cofinite F ∧ + r = sInf {a | ∃ y ∈ F, 1 ≤ N y ∧ a = averagedIncrement N x t y}} + +def D (N : Seminorm ℝ X) (x : X) (t : ℝ) : ℝ := + sSup {r | ∃ F : Submodule ℝ X, Cofinite F ∧ + r = sInf {a | ∃ y ∈ F, N y = 1 ∧ a = N (x + t • y) - 1}} + +def averagedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x, N x = 1 ∧ r = H N x t} + +def oneSidedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x, N x = 1 ∧ r = D N x t} + +/-- Two-sided comparison makes this seminorm a genuine norm equivalent to the original. -/ +def EquivalentNorm (N : Seminorm ℝ X) : Prop := + ∃ a b : ℝ, 0 < a ∧ 0 < b ∧ ∀ x, a * ‖x‖ ≤ N x ∧ N x ≤ b * ‖x‖ + +def AUC (N : Seminorm ℝ X) : Prop := + ∀ t : ℝ, 0 < t → 0 < oneSidedModulus N t + +/-- Every rank-one operator has the form `ell.smulRight v`. -/ +def Daugavet (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ (ell : X →L[ℝ] ℝ) (v : X), + ‖ContinuousLinearMap.id ℝ X + ell.smulRight v‖ = 1 + ‖ell.smulRight v‖ + +variable {Ω : Type u_1} [MeasurableSpace Ω] (μ : Measure Ω) + +/-- Convergence-in-measure distance on L1 equivalence classes. -/ +def measureDistance (f g : Lp ℝ 1 μ) : ℝ := + sInf {a : ℝ | 0 < a ∧ μ.real {ω | a < |f ω - g ω|} < a} + +/-- Finite covers of the entire unit ball in convergence-in-measure distance. -/ +def MeasurePrecompactBall (E : Submodule ℝ (Lp ℝ 1 μ)) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ s : Finset (Lp ℝ 1 μ), + ∀ y : E, ‖y‖ ≤ 1 → ∃ b ∈ s, measureDistance μ (y : Lp ℝ 1 μ) b < ε + +/-- Every nonempty unit-ball slice contains an almost antipodal unit vector. -/ +def UnitSliceProperty (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ (w : X), ‖w‖ = 1 → ∀ (ell : X →L[ℝ] ℝ) (α : ℝ), + (∃ u : X, ‖u‖ ≤ 1 ∧ α < ell u) → + ∀ ρ : ℝ, 0 < ρ → ∃ y : X, ‖y‖ = 1 ∧ α < ell y ∧ 2 - ρ ≤ ‖w + y‖ + +/-- The countable product of unit intervals. -/ +abbrev KWOmega := ℕ → unitInterval + +def kwMeasure : Measure KWOmega := Measure.infinitePi (fun _ : ℕ => (volume : Measure unitInterval)) + +theorem exact_main {Ω : Type u_1} [MeasurableSpace Ω] (μ : Measure Ω) + [IsProbabilityMeasure μ] (E : Submodule ℝ (Lp ℝ 1 μ)) + (_hclosed : IsClosed (E : Set (Lp ℝ 1 μ))) (hdim : ¬ FiniteDimensional ℝ E) + (hprecompact : MeasurePrecompactBall μ E) (hdaugavet : Daugavet E) : + (∀ (x : E), ‖x‖ = 1 → ∀ t : ℝ, 0 < t → + H (normSeminorm ℝ E) x t = max (t / 2) (t - 1) ∧ + D (normSeminorm ℝ E) x t = max 0 (t - 2)) ∧ + (∀ t : ℝ, 0 < t → + averagedModulus (normSeminorm ℝ E) t = max (t / 2) (t - 1) ∧ + oneSidedModulus (normSeminorm ℝ E) t = max 0 (t - 2)) ∧ + (∀ N : Seminorm ℝ E, EquivalentNorm N → ¬ AUC N) := by + sorry + +theorem kadets_werner_existence : + ∃ E : Submodule ℝ (Lp ℝ 1 kwMeasure), + IsClosed (E : Set (Lp ℝ 1 kwMeasure)) ∧ (¬ FiniteDimensional ℝ E) ∧ + MeasurePrecompactBall kwMeasure E ∧ UnitSliceProperty E ∧ Daugavet E := by + sorry + +theorem exact_example : + ∃ E : Submodule ℝ (Lp ℝ 1 kwMeasure), + IsClosed (E : Set (Lp ℝ 1 kwMeasure)) ∧ (¬ FiniteDimensional ℝ E) ∧ + MeasurePrecompactBall kwMeasure E ∧ UnitSliceProperty E ∧ Daugavet E ∧ + (∀ (x : E), ‖x‖ = 1 → ∀ t : ℝ, 0 < t → + H (normSeminorm ℝ E) x t = max (t / 2) (t - 1) ∧ + D (normSeminorm ℝ E) x t = max 0 (t - 2)) ∧ + (∀ t : ℝ, 0 < t → + averagedModulus (normSeminorm ℝ E) t = max (t / 2) (t - 1) ∧ + oneSidedModulus (normSeminorm ℝ E) t = max 0 (t - 2)) ∧ + (∀ N : Seminorm ℝ E, EquivalentNorm N → ¬ AUC N) := by + sorry + +end ExactModuli + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DaugavetModuli.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.ExactModuli.exact_main`, `OAI.ExactModuli.kadets_werner_existence`, `OAI.ExactModuli.exact_example` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/daugavet-moduli/solution/closure.txt b/tasks/daugavet-moduli/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f1cf2d3b5dc07889b54ff0ea70a1959bf071f193 --- /dev/null +++ b/tasks/daugavet-moduli/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.Analysis.Daugavet.Clipping +OAI.Analysis.Daugavet.ClosedUnion +OAI.Analysis.Daugavet.Diameter +OAI.Analysis.Daugavet.Enlargement +OAI.Analysis.Daugavet.EquivalentNorm +OAI.Analysis.Daugavet.ExactModuli +OAI.Analysis.Daugavet.FiniteCoordinates +OAI.Analysis.Daugavet.HeavyTails +OAI.Analysis.Daugavet.Joining +OAI.Analysis.Daugavet.LimitingSlices +OAI.Analysis.Daugavet.LowerBounds +OAI.Analysis.Daugavet.Main +OAI.Analysis.Daugavet.MeasureDistance +OAI.Analysis.Daugavet.Model +OAI.Analysis.Daugavet.Multipliers +OAI.Analysis.Daugavet.ProductApproximation +OAI.Analysis.Daugavet.ProductModels +OAI.Analysis.Daugavet.ProductOperators +OAI.Analysis.Daugavet.ProductSeparation +OAI.Analysis.Daugavet.Recovery +OAI.Analysis.Daugavet.SignAverages +OAI.Analysis.Daugavet.SliceCharacterization +OAI.Analysis.Daugavet.Slices +OAI.Analysis.Daugavet.Stages +OAI.Analysis.Daugavet.TailEstimates +OAI.Analysis.Daugavet.UpperBounds +OAI.Analysis.Daugavet.WholeBallCoefficients +OAI.Analysis.Daugavet.WholeBallConcentration diff --git a/tasks/daugavet-moduli/solution/reference.py b/tasks/daugavet-moduli/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/daugavet-moduli/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/daugavet-moduli/solution/solve.sh b/tasks/daugavet-moduli/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..97ece8adccb23b1b73997b4bac638ee12bd39f9c --- /dev/null +++ b/tasks/daugavet-moduli/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DaugavetModuli, i.e. module OAI.Analysis.Daugavet.Main and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Daugavet.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DaugavetModuli" diff --git a/tasks/daugavet-moduli/task.toml b/tasks/daugavet-moduli/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1b076538350d03470f4a72537ca84ed434494433 --- /dev/null +++ b/tasks/daugavet-moduli/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/daugavet-moduli" +version = "1.0.0" +description = "Prove DaugavetModuli (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DaugavetModuli.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DaugavetModuli" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.ExactModuli.exact_main", "OAI.ExactModuli.kadets_werner_existence", "OAI.ExactModuli.exact_example"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Daugavet.Main" +reference_modules = 28 +reference_lean_bytes = 201678 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 462 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11881 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/daugavet-moduli/tests/Challenge.lean b/tasks/daugavet-moduli/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9147ec931cd9b8c18b2f5a094a5bb28b92614498 --- /dev/null +++ b/tasks/daugavet-moduli/tests/Challenge.lean @@ -0,0 +1,108 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter Set +open scoped ENNReal NNReal Topology + +universe uX u_1 + +namespace ExactModuli + +variable {X : Type uX} [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Closed linear subspaces of finite codimension. -/ +def Cofinite (F : Submodule ℝ X) : Prop := + IsClosed (F : Set X) ∧ FiniteDimensional ℝ (X ⧸ F) + +/-- Averaged increment for directions of norm at least one. -/ +def averagedIncrement (N : Seminorm ℝ X) (x : X) (t : ℝ) (y : X) : ℝ := + (N (x + t • y) + N (x - t • y)) / 2 - 1 + +def H (N : Seminorm ℝ X) (x : X) (t : ℝ) : ℝ := + sSup {r | ∃ F : Submodule ℝ X, Cofinite F ∧ + r = sInf {a | ∃ y ∈ F, 1 ≤ N y ∧ a = averagedIncrement N x t y}} + +def D (N : Seminorm ℝ X) (x : X) (t : ℝ) : ℝ := + sSup {r | ∃ F : Submodule ℝ X, Cofinite F ∧ + r = sInf {a | ∃ y ∈ F, N y = 1 ∧ a = N (x + t • y) - 1}} + +def averagedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x, N x = 1 ∧ r = H N x t} + +def oneSidedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x, N x = 1 ∧ r = D N x t} + +/-- Two-sided comparison makes this seminorm a genuine norm equivalent to the original. -/ +def EquivalentNorm (N : Seminorm ℝ X) : Prop := + ∃ a b : ℝ, 0 < a ∧ 0 < b ∧ ∀ x, a * ‖x‖ ≤ N x ∧ N x ≤ b * ‖x‖ + +def AUC (N : Seminorm ℝ X) : Prop := + ∀ t : ℝ, 0 < t → 0 < oneSidedModulus N t + +/-- Every rank-one operator has the form `ell.smulRight v`. -/ +def Daugavet (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ (ell : X →L[ℝ] ℝ) (v : X), + ‖ContinuousLinearMap.id ℝ X + ell.smulRight v‖ = 1 + ‖ell.smulRight v‖ + +variable {Ω : Type u_1} [MeasurableSpace Ω] (μ : Measure Ω) + +/-- Convergence-in-measure distance on L1 equivalence classes. -/ +def measureDistance (f g : Lp ℝ 1 μ) : ℝ := + sInf {a : ℝ | 0 < a ∧ μ.real {ω | a < |f ω - g ω|} < a} + +/-- Finite covers of the entire unit ball in convergence-in-measure distance. -/ +def MeasurePrecompactBall (E : Submodule ℝ (Lp ℝ 1 μ)) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ s : Finset (Lp ℝ 1 μ), + ∀ y : E, ‖y‖ ≤ 1 → ∃ b ∈ s, measureDistance μ (y : Lp ℝ 1 μ) b < ε + +/-- Every nonempty unit-ball slice contains an almost antipodal unit vector. -/ +def UnitSliceProperty (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ (w : X), ‖w‖ = 1 → ∀ (ell : X →L[ℝ] ℝ) (α : ℝ), + (∃ u : X, ‖u‖ ≤ 1 ∧ α < ell u) → + ∀ ρ : ℝ, 0 < ρ → ∃ y : X, ‖y‖ = 1 ∧ α < ell y ∧ 2 - ρ ≤ ‖w + y‖ + +/-- The countable product of unit intervals. -/ +abbrev KWOmega := ℕ → unitInterval + +def kwMeasure : Measure KWOmega := Measure.infinitePi (fun _ : ℕ => (volume : Measure unitInterval)) + +theorem exact_main {Ω : Type u_1} [MeasurableSpace Ω] (μ : Measure Ω) + [IsProbabilityMeasure μ] (E : Submodule ℝ (Lp ℝ 1 μ)) + (_hclosed : IsClosed (E : Set (Lp ℝ 1 μ))) (hdim : ¬ FiniteDimensional ℝ E) + (hprecompact : MeasurePrecompactBall μ E) (hdaugavet : Daugavet E) : + (∀ (x : E), ‖x‖ = 1 → ∀ t : ℝ, 0 < t → + H (normSeminorm ℝ E) x t = max (t / 2) (t - 1) ∧ + D (normSeminorm ℝ E) x t = max 0 (t - 2)) ∧ + (∀ t : ℝ, 0 < t → + averagedModulus (normSeminorm ℝ E) t = max (t / 2) (t - 1) ∧ + oneSidedModulus (normSeminorm ℝ E) t = max 0 (t - 2)) ∧ + (∀ N : Seminorm ℝ E, EquivalentNorm N → ¬ AUC N) := by + sorry + +theorem kadets_werner_existence : + ∃ E : Submodule ℝ (Lp ℝ 1 kwMeasure), + IsClosed (E : Set (Lp ℝ 1 kwMeasure)) ∧ (¬ FiniteDimensional ℝ E) ∧ + MeasurePrecompactBall kwMeasure E ∧ UnitSliceProperty E ∧ Daugavet E := by + sorry + +theorem exact_example : + ∃ E : Submodule ℝ (Lp ℝ 1 kwMeasure), + IsClosed (E : Set (Lp ℝ 1 kwMeasure)) ∧ (¬ FiniteDimensional ℝ E) ∧ + MeasurePrecompactBall kwMeasure E ∧ UnitSliceProperty E ∧ Daugavet E ∧ + (∀ (x : E), ‖x‖ = 1 → ∀ t : ℝ, 0 < t → + H (normSeminorm ℝ E) x t = max (t / 2) (t - 1) ∧ + D (normSeminorm ℝ E) x t = max 0 (t - 2)) ∧ + (∀ t : ℝ, 0 < t → + averagedModulus (normSeminorm ℝ E) t = max (t / 2) (t - 1) ∧ + oneSidedModulus (normSeminorm ℝ E) t = max 0 (t - 2)) ∧ + (∀ N : Seminorm ℝ E, EquivalentNorm N → ¬ AUC N) := by + sorry + +end ExactModuli + +end + +end OAI diff --git a/tasks/daugavet-moduli/tests/grade.py b/tasks/daugavet-moduli/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/daugavet-moduli/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/daugavet-moduli/tests/task.json b/tasks/daugavet-moduli/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..66fb88a2b29a191b4aa0cb120b90d8ab1b18540b --- /dev/null +++ b/tasks/daugavet-moduli/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "DaugavetModuli", + "comparator": { + "theorem_names": [ + "OAI.ExactModuli.exact_main", + "OAI.ExactModuli.kadets_werner_existence", + "OAI.ExactModuli.exact_example" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10981 +} \ No newline at end of file diff --git a/tasks/daugavet-moduli/tests/test.sh b/tasks/daugavet-moduli/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/daugavet-moduli/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/degree-rigidity/environment/Dockerfile b/tasks/degree-rigidity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/degree-rigidity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/degree-rigidity/environment/fetch_mathlib.sh b/tasks/degree-rigidity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/degree-rigidity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/degree-rigidity/environment/lake-manifest.json b/tasks/degree-rigidity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/degree-rigidity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/degree-rigidity/environment/lakefile.lean b/tasks/degree-rigidity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/degree-rigidity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/degree-rigidity/environment/lean_setup.sh b/tasks/degree-rigidity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/degree-rigidity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/degree-rigidity/environment/pack_submission.py b/tasks/degree-rigidity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/degree-rigidity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/degree-rigidity/instruction.md b/tasks/degree-rigidity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..24e9894029a14b2ffcaaa080304b095edc3a479d --- /dev/null +++ b/tasks/degree-rigidity/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `DegreeRigidity` (family 241) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 241 of the release, *Rigidity of the Turing degrees* +(Mathematical logic). The family as a whole: Every order automorphism of the Turing degrees is the identity, resolving their rigidity problem. Thus no nontrivial relabeling of degrees preserves the ordering by relative computability. + +The challenge is `DegreeRigidity`, also at `/opt/openai-math/challenges/DegreeRigidity.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TuringRigidity + +abbrev Oracle := ℕ → Bool + +def oracleFunction (A : Oracle) : ℕ →. ℕ := fun n => Part.some (if A n then 1 else 0) + +def Reduces (A B : Oracle) : Prop := TuringReducible (oracleFunction A) (oracleFunction B) + +instance : IsPreorder Oracle Reduces where + refl A := TuringReducible.refl (oracleFunction A) + trans _ _ _ h k := TuringReducible.trans h k + +def Degree := Antisymmetrization Oracle Reduces + +instance : PartialOrder Degree := + @instPartialOrderAntisymmetrization Oracle + { le := Reduces + lt A B := Reduces A B ∧ ¬ Reduces B A + lt_iff_le_not_ge _ _ := Iff.rfl + le_refl A := TuringReducible.refl (oracleFunction A) + le_trans _ _ _ h k := TuringReducible.trans h k } + +private instance oraclePreorder : Preorder Oracle where + le := Reduces + lt A B := Reduces A B ∧ ¬ Reduces B A + lt_iff_le_not_ge _ _ := Iff.rfl + le_refl A := TuringReducible.refl (oracleFunction A) + le_trans _ _ _ h k := TuringReducible.trans h k + +def MainTheorem : Prop := ∀ π : Degree ≃o Degree, ∀ a : Degree, π a = a + +namespace ManuscriptMain + +theorem rigidity : MainTheorem := by + sorry + +end ManuscriptMain +end TuringRigidity + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DegreeRigidity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TuringRigidity.ManuscriptMain.rigidity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/degree-rigidity/solution/closure.txt b/tasks/degree-rigidity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ef7e37eb078e09304b37c9153de65599f5798aeb --- /dev/null +++ b/tasks/degree-rigidity/solution/closure.txt @@ -0,0 +1,974 @@ +OAI.Computability.DegreeRigidity.CohenForcing.AtomicForcing +OAI.Computability.DegreeRigidity.CohenForcing.BoundedForcing +OAI.Computability.DegreeRigidity.CohenForcing.BoundedForcingCode +OAI.Computability.DegreeRigidity.CohenForcing.CheckedForcingRelation +OAI.Computability.DegreeRigidity.CohenForcing.CohenAbsorptionGeneric +OAI.Computability.DegreeRigidity.CohenForcing.CohenAbsorptionTree +OAI.Computability.DegreeRigidity.CohenForcing.CohenAntichainFamilySupport +OAI.Computability.DegreeRigidity.CohenForcing.CohenAntichainSelector +OAI.Computability.DegreeRigidity.CohenForcing.CohenAntichainSequence +OAI.Computability.DegreeRigidity.CohenForcing.CohenAntichainStages +OAI.Computability.DegreeRigidity.CohenForcing.CohenBorelForcing +OAI.Computability.DegreeRigidity.CohenForcing.CohenChainCondition +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumnAbsorption +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumnPrefixCone +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumnPrefixGeneric +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumnRealName +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumnRealValue +OAI.Computability.DegreeRigidity.CohenForcing.CohenColumns +OAI.Computability.DegreeRigidity.CohenForcing.CohenCompleteness +OAI.Computability.DegreeRigidity.CohenForcing.CohenConditionCode +OAI.Computability.DegreeRigidity.CohenForcing.CohenConservative +OAI.Computability.DegreeRigidity.CohenForcing.CohenCoordinates +OAI.Computability.DegreeRigidity.CohenForcing.CohenCountedAntichain +OAI.Computability.DegreeRigidity.CohenForcing.CohenDisjointPrefixPair +OAI.Computability.DegreeRigidity.CohenForcing.CohenEffectiveGeneric +OAI.Computability.DegreeRigidity.CohenForcing.CohenFactorIteration +OAI.Computability.DegreeRigidity.CohenForcing.CohenFactorReconstruction +OAI.Computability.DegreeRigidity.CohenForcing.CohenFactorRequirement +OAI.Computability.DegreeRigidity.CohenForcing.CohenFilterReal +OAI.Computability.DegreeRigidity.CohenForcing.CohenFiniteAntichains +OAI.Computability.DegreeRigidity.CohenForcing.CohenFiniteFlip +OAI.Computability.DegreeRigidity.CohenForcing.CohenFreshColumn +OAI.Computability.DegreeRigidity.CohenForcing.CohenGenericUnion +OAI.Computability.DegreeRigidity.CohenForcing.CohenGroundGeneric +OAI.Computability.DegreeRigidity.CohenForcing.CohenGroundJump +OAI.Computability.DegreeRigidity.CohenForcing.CohenGroundPoset +OAI.Computability.DegreeRigidity.CohenForcing.CohenGroundProgram +OAI.Computability.DegreeRigidity.CohenForcing.CohenHalting +OAI.Computability.DegreeRigidity.CohenForcing.CohenInternalAntichain +OAI.Computability.DegreeRigidity.CohenForcing.CohenInternalDecision +OAI.Computability.DegreeRigidity.CohenForcing.CohenInternalSupport +OAI.Computability.DegreeRigidity.CohenForcing.CohenIteratedAbsorption +OAI.Computability.DegreeRigidity.CohenForcing.CohenLiteralAbsorption +OAI.Computability.DegreeRigidity.CohenForcing.CohenLowness +OAI.Computability.DegreeRigidity.CohenForcing.CohenManyAbsorption +OAI.Computability.DegreeRigidity.CohenForcing.CohenNiceNameConstruction +OAI.Computability.DegreeRigidity.CohenForcing.CohenNiceNames +OAI.Computability.DegreeRigidity.CohenForcing.CohenPartitionBridge +OAI.Computability.DegreeRigidity.CohenForcing.CohenPartitionJoint +OAI.Computability.DegreeRigidity.CohenForcing.CohenPartitionRealization +OAI.Computability.DegreeRigidity.CohenForcing.CohenPrefixDensity +OAI.Computability.DegreeRigidity.CohenForcing.CohenPrefixHull +OAI.Computability.DegreeRigidity.CohenForcing.CohenPrefixOverwrite +OAI.Computability.DegreeRigidity.CohenForcing.CohenPrefixReconstruction +OAI.Computability.DegreeRigidity.CohenForcing.CohenProductFilters +OAI.Computability.DegreeRigidity.CohenForcing.CohenProductSplitting +OAI.Computability.DegreeRigidity.CohenForcing.CohenProgramTotality +OAI.Computability.DegreeRigidity.CohenForcing.CohenProjectedNameLift +OAI.Computability.DegreeRigidity.CohenForcing.CohenRecursiveName +OAI.Computability.DegreeRigidity.CohenForcing.CohenRemainderTransport +OAI.Computability.DegreeRigidity.CohenForcing.CohenRun +OAI.Computability.DegreeRigidity.CohenForcing.CohenSizeLevels +OAI.Computability.DegreeRigidity.CohenForcing.CohenSymmetry +OAI.Computability.DegreeRigidity.CohenForcing.CohenUntouchedGeneric +OAI.Computability.DegreeRigidity.CohenForcing.CohenUnusedTransport +OAI.Computability.DegreeRigidity.CohenForcing.CohenWordCodeGraph +OAI.Computability.DegreeRigidity.CohenForcing.CountableForcing +OAI.Computability.DegreeRigidity.CohenForcing.CountedCohenConditions +OAI.Computability.DegreeRigidity.CohenForcing.EffectiveForcing +OAI.Computability.DegreeRigidity.CohenForcing.EncodedForcing +OAI.Computability.DegreeRigidity.CohenForcing.ForcingProjection +OAI.Computability.DegreeRigidity.CohenForcing.ForcingRequirements +OAI.Computability.DegreeRigidity.CohenForcing.ForcingSymmetry +OAI.Computability.DegreeRigidity.CohenForcing.ForcingWitnessCollection +OAI.Computability.DegreeRigidity.CohenForcing.FullSetForcing +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenBitFlip +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenBooleanReading +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenColumnReading +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenConditions +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenFactor +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenFilters +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenHomogeneity +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenName +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenOddHits +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenPartition +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenProjectedGeneric +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenProjectionSymmetry +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenReindex +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenRequirements +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenRestriction +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenSupportedValue +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenTailHomogeneity +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenTailTruth +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenUnusedColumns +OAI.Computability.DegreeRigidity.CohenForcing.InternalCohenValue +OAI.Computability.DegreeRigidity.CohenForcing.QuotientDense +OAI.Computability.DegreeRigidity.CohenForcing.QuotientNames +OAI.Computability.DegreeRigidity.CohenForcing.RestrictedForcingFilter +OAI.Computability.DegreeRigidity.CohenForcing.SigmaForcing +OAI.Computability.DegreeRigidity.CohenForcing.SparseCohenFilter +OAI.Computability.DegreeRigidity.CohenForcing.SparseCohenPrefixGeneric +OAI.Computability.DegreeRigidity.CohenForcing.SparseCohenRealName +OAI.Computability.DegreeRigidity.CohenForcing.SparseCohenRealValue +OAI.Computability.DegreeRigidity.CohenForcing.TaggedProductConditions +OAI.Computability.DegreeRigidity.CohenForcing.TaggedProductExtension +OAI.Computability.DegreeRigidity.CohenForcing.TaggedProductGeneric +OAI.Computability.DegreeRigidity.CohenForcing.TaggedProductRecovery +OAI.Computability.DegreeRigidity.CohenForcing.WeakForcingCode +OAI.Computability.DegreeRigidity.Computability.ArithmeticActions +OAI.Computability.DegreeRigidity.Computability.ArithmeticAtoms +OAI.Computability.DegreeRigidity.Computability.ArithmeticBounded +OAI.Computability.DegreeRigidity.Computability.ArithmeticCoanalytic +OAI.Computability.DegreeRigidity.Computability.ArithmeticCommonRequirement +OAI.Computability.DegreeRigidity.Computability.ArithmeticCommonRun +OAI.Computability.DegreeRigidity.Computability.ArithmeticFinite +OAI.Computability.DegreeRigidity.Computability.ArithmeticFiniteTest +OAI.Computability.DegreeRigidity.Computability.ArithmeticFiniteTruthTransfer +OAI.Computability.DegreeRigidity.Computability.ArithmeticFreeConstruction +OAI.Computability.DegreeRigidity.Computability.ArithmeticGenericDensity +OAI.Computability.DegreeRigidity.Computability.ArithmeticGenericTruth +OAI.Computability.DegreeRigidity.Computability.ArithmeticHierarchy +OAI.Computability.DegreeRigidity.Computability.ArithmeticIdeals +OAI.Computability.DegreeRigidity.Computability.ArithmeticIteratedJoin +OAI.Computability.DegreeRigidity.Computability.ArithmeticJoinSections +OAI.Computability.DegreeRigidity.Computability.ArithmeticJumpBound +OAI.Computability.DegreeRigidity.Computability.ArithmeticModelDecoding +OAI.Computability.DegreeRigidity.Computability.ArithmeticOracles +OAI.Computability.DegreeRigidity.Computability.ArithmeticOutputSyntax +OAI.Computability.DegreeRigidity.Computability.ArithmeticParameterFormula +OAI.Computability.DegreeRigidity.Computability.ArithmeticPersistence +OAI.Computability.DegreeRigidity.Computability.ArithmeticPersistenceDegreeModel +OAI.Computability.DegreeRigidity.Computability.ArithmeticPrefixFamilies +OAI.Computability.DegreeRigidity.Computability.ArithmeticPrefixForcing +OAI.Computability.DegreeRigidity.Computability.ArithmeticPresentation +OAI.Computability.DegreeRigidity.Computability.ArithmeticPresentationProperty +OAI.Computability.DegreeRigidity.Computability.ArithmeticPrincipalIntersection +OAI.Computability.DegreeRigidity.Computability.ArithmeticProgramGraph +OAI.Computability.DegreeRigidity.Computability.ArithmeticRelations +OAI.Computability.DegreeRigidity.Computability.ArithmeticSetSyntax +OAI.Computability.DegreeRigidity.Computability.ArithmeticShuffleCertificate +OAI.Computability.DegreeRigidity.Computability.ArithmeticShuffleGraph +OAI.Computability.DegreeRigidity.Computability.ArithmeticSkolem +OAI.Computability.DegreeRigidity.Computability.ArithmeticSourceEquation +OAI.Computability.DegreeRigidity.Computability.ArithmeticSourceTruth +OAI.Computability.DegreeRigidity.Computability.ArithmeticTables +OAI.Computability.DegreeRigidity.Computability.ArithmeticTestApproximation +OAI.Computability.DegreeRigidity.Computability.ArithmeticTreeDefinability +OAI.Computability.DegreeRigidity.Computability.ArithmeticTreeDescent +OAI.Computability.DegreeRigidity.Computability.ArithmeticTreeSequence +OAI.Computability.DegreeRigidity.Computability.ArithmeticTruthRequirements +OAI.Computability.DegreeRigidity.Computability.ArithmeticWitnessTree +OAI.Computability.DegreeRigidity.Computability.BinaryCut +OAI.Computability.DegreeRigidity.Computability.BinaryMachine +OAI.Computability.DegreeRigidity.Computability.BinaryRecovery +OAI.Computability.DegreeRigidity.Computability.BinarySeries +OAI.Computability.DegreeRigidity.Computability.BranchFrequency +OAI.Computability.DegreeRigidity.Computability.BranchMachine +OAI.Computability.DegreeRigidity.Computability.BranchRecovery +OAI.Computability.DegreeRigidity.Computability.CutAddition +OAI.Computability.DegreeRigidity.Computability.CutArithmetic +OAI.Computability.DegreeRigidity.Computability.CutTranscript +OAI.Computability.DegreeRigidity.Computability.Cuts +OAI.Computability.DegreeRigidity.Computability.DegreeCoverage +OAI.Computability.DegreeRigidity.Computability.EffectiveRecovery +OAI.Computability.DegreeRigidity.Computability.Introreducible +OAI.Computability.DegreeRigidity.Computability.Joins +OAI.Computability.DegreeRigidity.Computability.JumpIdeal +OAI.Computability.DegreeRigidity.Computability.JumpIdealPresentation +OAI.Computability.DegreeRigidity.Computability.JumpIterationFormula +OAI.Computability.DegreeRigidity.Computability.JumpProperties +OAI.Computability.DegreeRigidity.Computability.JumpSetFormula +OAI.Computability.DegreeRigidity.Computability.NormalizedRecovery +OAI.Computability.DegreeRigidity.Computability.OracleCode +OAI.Computability.DegreeRigidity.Computability.OracleEnumeration +OAI.Computability.DegreeRigidity.Computability.OracleJump +OAI.Computability.DegreeRigidity.Computability.RationalCoding +OAI.Computability.DegreeRigidity.Computability.RationalCut +OAI.Computability.DegreeRigidity.Computability.RealProjectionSyntax +OAI.Computability.DegreeRigidity.Computability.RecoverySetup +OAI.Computability.DegreeRigidity.Computability.ScalarCoding +OAI.Computability.DegreeRigidity.Computability.UniformArithmetic +OAI.Computability.DegreeRigidity.Constructibility.CollectionHierarchyInternal +OAI.Computability.DegreeRigidity.Constructibility.CollectionHierarchyRecursion +OAI.Computability.DegreeRigidity.Constructibility.CollectionHierarchySyntax +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleBase +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleClosure +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleGroundReals +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleSatisfaction +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleSeparation +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleStages +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleSuccessorCode +OAI.Computability.DegreeRigidity.Constructibility.ConstructibleTupleSpace +OAI.Computability.DegreeRigidity.Constructibility.ConstructionDefinition +OAI.Computability.DegreeRigidity.Constructibility.ConstructionHeightDomains +OAI.Computability.DegreeRigidity.Constructibility.ConstructionInlining +OAI.Computability.DegreeRigidity.Constructibility.ConstructionInputData +OAI.Computability.DegreeRigidity.Constructibility.ConstructionStageBound +OAI.Computability.DegreeRigidity.Constructibility.ContextDefinablePower +OAI.Computability.DegreeRigidity.Constructibility.ContextHierarchyGraph +OAI.Computability.DegreeRigidity.Constructibility.DecodedConstructionSyntax +OAI.Computability.DegreeRigidity.Constructibility.DefSystemCertificate +OAI.Computability.DegreeRigidity.Constructibility.DomainParameterizedSyntax +OAI.Computability.DegreeRigidity.Constructibility.DomainSyntaxClosure +OAI.Computability.DegreeRigidity.Constructibility.FiniteDefinitionTransfer +OAI.Computability.DegreeRigidity.Constructibility.FiniteStageDefinition +OAI.Computability.DegreeRigidity.Constructibility.FiniteStageSetBounds +OAI.Computability.DegreeRigidity.Constructibility.FixedRelativeGround +OAI.Computability.DegreeRigidity.Constructibility.HierarchyCertificatePower +OAI.Computability.DegreeRigidity.Constructibility.HierarchyGraph +OAI.Computability.DegreeRigidity.Constructibility.HierarchySyntax +OAI.Computability.DegreeRigidity.Constructibility.HierarchyWitnessCollection +OAI.Computability.DegreeRigidity.Constructibility.InternalConstructibleHierarchy +OAI.Computability.DegreeRigidity.Constructibility.InternalHeightDomains +OAI.Computability.DegreeRigidity.Constructibility.InternalHierarchyRecursion +OAI.Computability.DegreeRigidity.Constructibility.InternalOmegaFixedPoint +OAI.Computability.DegreeRigidity.Constructibility.InternalOmegaPower +OAI.Computability.DegreeRigidity.Constructibility.InternalRankRecursion +OAI.Computability.DegreeRigidity.Constructibility.OneRealConstructionDefinition +OAI.Computability.DegreeRigidity.Constructibility.OneRealDefinitionSentence +OAI.Computability.DegreeRigidity.Constructibility.ParameterFreeOrdinalStage +OAI.Computability.DegreeRigidity.Constructibility.ParameterPersistentCollapse +OAI.Computability.DegreeRigidity.Constructibility.PersistenceCriterion +OAI.Computability.DegreeRigidity.Constructibility.PersistenceExtensionAbsoluteness +OAI.Computability.DegreeRigidity.Constructibility.PersistenceRealClosure +OAI.Computability.DegreeRigidity.Constructibility.PersistenceWitnessTree +OAI.Computability.DegreeRigidity.Constructibility.PersistentConstruction +OAI.Computability.DegreeRigidity.Constructibility.PersistentCountability +OAI.Computability.DegreeRigidity.Constructibility.PersistentExtension +OAI.Computability.DegreeRigidity.Constructibility.PersistentExtensionName +OAI.Computability.DegreeRigidity.Constructibility.PersistentLocality +OAI.Computability.DegreeRigidity.Constructibility.PersistentNonidentity +OAI.Computability.DegreeRigidity.Constructibility.PersistentOneRealDefinition +OAI.Computability.DegreeRigidity.Constructibility.PersistentPresentation +OAI.Computability.DegreeRigidity.Constructibility.PersistentRestrictionCode +OAI.Computability.DegreeRigidity.Constructibility.PersistentRestrictions +OAI.Computability.DegreeRigidity.Constructibility.RelativeCohenJump +OAI.Computability.DegreeRigidity.Constructibility.RelativeConstruction +OAI.Computability.DegreeRigidity.Constructibility.RelativeDefCertificates +OAI.Computability.DegreeRigidity.Constructibility.RelativeDegreeIdeal +OAI.Computability.DegreeRigidity.Constructibility.RelativeHierarchyInternal +OAI.Computability.DegreeRigidity.Constructibility.RelativeLevySchemas +OAI.Computability.DegreeRigidity.Constructibility.RelativeModel +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelBounds +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelClosure +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelComparison +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelOrdinals +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelPower +OAI.Computability.DegreeRigidity.Constructibility.RelativeModelSyntax +OAI.Computability.DegreeRigidity.Constructibility.RelativeOmegaCertificates +OAI.Computability.DegreeRigidity.Constructibility.RelativeOmegaLevels +OAI.Computability.DegreeRigidity.Constructibility.RelativePersistentDescent +OAI.Computability.DegreeRigidity.Constructibility.RelativePersistentExtension +OAI.Computability.DegreeRigidity.Constructibility.RelativeSigmaReflection +OAI.Computability.DegreeRigidity.Constructibility.RelativeSigmaSchemas +OAI.Computability.DegreeRigidity.Constructibility.RelativeSigmaWitness +OAI.Computability.DegreeRigidity.Constructibility.SeedBoundStageSyntax +OAI.Computability.DegreeRigidity.Constructibility.SingleRealConstruction +OAI.Computability.DegreeRigidity.Constructibility.UniformDefSuccessor +OAI.Computability.DegreeRigidity.Constructibility.UniformDefinedSubsetName +OAI.Computability.DegreeRigidity.Constructibility.UniformDefinitionSymmetry +OAI.Computability.DegreeRigidity.Constructibility.UniformExtensionWitnessCover +OAI.Computability.DegreeRigidity.Constructibility.UniformFragmentHull +OAI.Computability.DegreeRigidity.Constructibility.UniformHeightDomains +OAI.Computability.DegreeRigidity.Constructibility.UniformHierarchyStage +OAI.Computability.DegreeRigidity.Constructibility.UniformInternalSatisfaction +OAI.Computability.DegreeRigidity.Constructibility.UniformNameDescent +OAI.Computability.DegreeRigidity.Constructibility.UniformNameValueCover +OAI.Computability.DegreeRigidity.Constructibility.UniformOmegaLevels +OAI.Computability.DegreeRigidity.Constructibility.UniformOrdinalDefinitionName +OAI.Computability.DegreeRigidity.Constructibility.UniformOrdinalStageName +OAI.Computability.DegreeRigidity.Constructibility.UniformOwnRealsName +OAI.Computability.DegreeRigidity.Constructibility.UniformPowerName +OAI.Computability.DegreeRigidity.Constructibility.UniformProductName +OAI.Computability.DegreeRigidity.Constructibility.UniformSentenceSupport +OAI.Computability.DegreeRigidity.Constructibility.UniformSeparationName +OAI.Computability.DegreeRigidity.Constructibility.UniformSigmaDefinability +OAI.Computability.DegreeRigidity.Constructibility.UniformSigmaHierarchy +OAI.Computability.DegreeRigidity.Constructibility.UniformSigmaHull +OAI.Computability.DegreeRigidity.Constructibility.UniformSigmaSeparationName +OAI.Computability.DegreeRigidity.Constructibility.UniformSigmaUniqueName +OAI.Computability.DegreeRigidity.Constructibility.UniformTruthRecursion +OAI.Computability.DegreeRigidity.Constructibility.UniformTruthStep +OAI.Computability.DegreeRigidity.Effective.AntichainCoding +OAI.Computability.DegreeRigidity.Effective.AntichainDecoding +OAI.Computability.DegreeRigidity.Effective.AntichainParameters +OAI.Computability.DegreeRigidity.Effective.CodingAgreement +OAI.Computability.DegreeRigidity.Effective.CodingBounds +OAI.Computability.DegreeRigidity.Effective.CodingColumns +OAI.Computability.DegreeRigidity.Effective.CodingDiagonal +OAI.Computability.DegreeRigidity.Effective.CodingExtraction +OAI.Computability.DegreeRigidity.Effective.CodingForcing +OAI.Computability.DegreeRigidity.Effective.CodingGeneric +OAI.Computability.DegreeRigidity.Effective.CodingLocations +OAI.Computability.DegreeRigidity.Effective.CodingOnePoint +OAI.Computability.DegreeRigidity.Effective.CodingRequirements +OAI.Computability.DegreeRigidity.Effective.CodingSplitSearch +OAI.Computability.DegreeRigidity.Effective.CodingSplitting +OAI.Computability.DegreeRigidity.Effective.EffectiveCohen +OAI.Computability.DegreeRigidity.Effective.EffectiveFamilies +OAI.Computability.DegreeRigidity.Effective.EffectivePresentation +OAI.Computability.DegreeRigidity.Effective.EffectiveRelations +OAI.Computability.DegreeRigidity.Effective.EffectiveSplit +OAI.Computability.DegreeRigidity.Effective.EffectiveSplitConditions +OAI.Computability.DegreeRigidity.Effective.EffectiveWitness +OAI.Computability.DegreeRigidity.Effective.FiniteApproximation +OAI.Computability.DegreeRigidity.Effective.FiniteBlockProducts +OAI.Computability.DegreeRigidity.Effective.FiniteCodeBound +OAI.Computability.DegreeRigidity.Effective.FiniteExtensionCode +OAI.Computability.DegreeRigidity.Effective.FiniteInjury +OAI.Computability.DegreeRigidity.Effective.FiniteInjuryLimits +OAI.Computability.DegreeRigidity.Effective.FiniteInjurySchedule +OAI.Computability.DegreeRigidity.Effective.FiniteJoinSections +OAI.Computability.DegreeRigidity.Effective.FiniteNaturalGraph +OAI.Computability.DegreeRigidity.Effective.FiniteOverwrite +OAI.Computability.DegreeRigidity.Effective.FiniteOverwriteHull +OAI.Computability.DegreeRigidity.Effective.FiniteRealPacking +OAI.Computability.DegreeRigidity.Effective.FiniteShuffle +OAI.Computability.DegreeRigidity.Effective.FiniteShuffleCertificate +OAI.Computability.DegreeRigidity.Effective.FiniteShuffleComputation +OAI.Computability.DegreeRigidity.Effective.FiniteSumDomains +OAI.Computability.DegreeRigidity.Effective.FiniteSumGraph +OAI.Computability.DegreeRigidity.Effective.FiniteSumPowerBound +OAI.Computability.DegreeRigidity.Effective.FiniteSumStep +OAI.Computability.DegreeRigidity.Effective.FiniteTranscript +OAI.Computability.DegreeRigidity.Effective.FiniteTuple +OAI.Computability.DegreeRigidity.Effective.GuardedCoding +OAI.Computability.DegreeRigidity.Effective.GuardedComputability +OAI.Computability.DegreeRigidity.Effective.GuardedExtraction +OAI.Computability.DegreeRigidity.Effective.GuardedLimits +OAI.Computability.DegreeRigidity.Effective.GuardedOutcomes +OAI.Computability.DegreeRigidity.Effective.GuardedPair +OAI.Computability.DegreeRigidity.Effective.GuardedScan +OAI.Computability.DegreeRigidity.Effective.GuardedStage +OAI.Computability.DegreeRigidity.Effective.IndependentFamily +OAI.Computability.DegreeRigidity.Effective.LocalAgreement +OAI.Computability.DegreeRigidity.Effective.LocalCoding +OAI.Computability.DegreeRigidity.Effective.LocalColumnCertificates +OAI.Computability.DegreeRigidity.Effective.LocalColumnIndices +OAI.Computability.DegreeRigidity.Effective.LocalComputability +OAI.Computability.DegreeRigidity.Effective.LocalDecisive +OAI.Computability.DegreeRigidity.Effective.LocalExtraction +OAI.Computability.DegreeRigidity.Effective.LocalInputs +OAI.Computability.DegreeRigidity.Effective.LocalLimits +OAI.Computability.DegreeRigidity.Effective.LocalOpen +OAI.Computability.DegreeRigidity.Effective.LocalOutcomes +OAI.Computability.DegreeRigidity.Effective.LocalPair +OAI.Computability.DegreeRigidity.Effective.LocalPrograms +OAI.Computability.DegreeRigidity.Effective.LocalScan +OAI.Computability.DegreeRigidity.Effective.LocalSourceEquation +OAI.Computability.DegreeRigidity.Effective.LocalStage +OAI.Computability.DegreeRigidity.Effective.LocalUnary +OAI.Computability.DegreeRigidity.Effective.OrderMatrixRecursive +OAI.Computability.DegreeRigidity.Effective.OrderNormalForm +OAI.Computability.DegreeRigidity.Effective.PartialComputability +OAI.Computability.DegreeRigidity.Effective.PrefixComputability +OAI.Computability.DegreeRigidity.Effective.PrefixSingletonRealization +OAI.Computability.DegreeRigidity.Effective.PriorityStage +OAI.Computability.DegreeRigidity.Effective.ProgramContinuity +OAI.Computability.DegreeRigidity.Effective.ProgramSelection +OAI.Computability.DegreeRigidity.Effective.ProgramTopology +OAI.Computability.DegreeRigidity.Effective.RecursiveInfiniteSubset +OAI.Computability.DegreeRigidity.Effective.SetCoding +OAI.Computability.DegreeRigidity.Effective.StablePair +OAI.Computability.DegreeRigidity.Effective.StageComputability +OAI.Computability.DegreeRigidity.Effective.StageLimits +OAI.Computability.DegreeRigidity.Effective.StageNormalization +OAI.Computability.DegreeRigidity.Effective.StageRecords +OAI.Computability.DegreeRigidity.Effective.StageScan +OAI.Computability.DegreeRigidity.Effective.TableIndices +OAI.Computability.DegreeRigidity.Effective.TriplePrefix +OAI.Computability.DegreeRigidity.Effective.TupleFormula +OAI.Computability.DegreeRigidity.Effective.TupleLookupAdequacy +OAI.Computability.DegreeRigidity.Effective.TuplePrefixSyntax +OAI.Computability.DegreeRigidity.Effective.TupleRelation +OAI.Computability.DegreeRigidity.Effective.TupleSystemCertificate +OAI.Computability.DegreeRigidity.Effective.UniformAgreement +OAI.Computability.DegreeRigidity.Effective.UniformCohenDefinitionExtension +OAI.Computability.DegreeRigidity.Effective.UniformCohenDefinitionSymmetry +OAI.Computability.DegreeRigidity.Effective.UniformCohenIteration +OAI.Computability.DegreeRigidity.Effective.UniformCohenJump +OAI.Computability.DegreeRigidity.Effective.UniformCohenPrefix +OAI.Computability.DegreeRigidity.Effective.UniformDegreeOrderName +OAI.Computability.DegreeRigidity.Effective.UniformDegreeUniverseName +OAI.Computability.DegreeRigidity.Effective.UniformJumpSimulation +OAI.Computability.DegreeRigidity.Effective.UniformOracle +OAI.Computability.DegreeRigidity.Effective.UniformOracleSimulation +OAI.Computability.DegreeRigidity.Effective.UniformPair +OAI.Computability.DegreeRigidity.Effective.UniformPartialGraph +OAI.Computability.DegreeRigidity.Effective.UniformProgram +OAI.Computability.DegreeRigidity.Effective.UniformPrograms +OAI.Computability.DegreeRigidity.Effective.UniformRun +OAI.Computability.DegreeRigidity.Effective.UniformSplit +OAI.Computability.DegreeRigidity.Effective.UniformTableSimulation +OAI.Computability.DegreeRigidity.Main +OAI.Computability.DegreeRigidity.Model +OAI.Computability.DegreeRigidity.OrdinalCodes.CanonicalAdditionSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.CanonicalOmegaSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.CanonicalRealsSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.CodeBranchCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.CodeBranchLevels +OAI.Computability.DegreeRigidity.OrdinalCodes.CodeOperationCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.IndexJoin +OAI.Computability.DegreeRigidity.OrdinalCodes.IndexMatrix +OAI.Computability.DegreeRigidity.OrdinalCodes.IndexPresentation +OAI.Computability.DegreeRigidity.OrdinalCodes.IndexTuples +OAI.Computability.DegreeRigidity.OrdinalCodes.IndexedOrder +OAI.Computability.DegreeRigidity.OrdinalCodes.LargestOrdinalSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.LevelInlinedDefinition +OAI.Computability.DegreeRigidity.OrdinalCodes.LevelOrdinalHeight +OAI.Computability.DegreeRigidity.OrdinalCodes.LevelSubsetDefinition +OAI.Computability.DegreeRigidity.OrdinalCodes.LimitOmegaCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.LimitOmegaGraphSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalAdditionTrace +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalDefinitions +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalIterationFormula +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalIterationTrace +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalMultiplicationFormula +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalPairingFormula +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalPrimitiveRecursion +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalProjectionFormula +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalRealRelation +OAI.Computability.DegreeRigidity.OrdinalCodes.NaturalTermFormula +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericBinding +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericDefSystem +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericDomain +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericFamilySupport +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericHierarchy +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericParameters +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericStage +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericTruth +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericalAutomorphism +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericalCohenProductSets +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericalCohenSets +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericalExtension +OAI.Computability.DegreeRigidity.OrdinalCodes.NumericalIdeal +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaCertificateCollection +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaGraphRestriction +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaGraphSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelArithmetic +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelAxiomTransport +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelCollapse +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelCore +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelCoreClosure +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaModelSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaPowerCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaPowerDefinability +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaPowerGraph +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaPowerStage +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaPowerSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaRecursionSchemas +OAI.Computability.DegreeRigidity.OrdinalCodes.OmegaStageSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalCodeBranch +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalCodeDomains +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalCodeOperations +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalConstruction +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalCut +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalDecoderDomains +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalEntryBinding +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalEntryDecoder +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalInputSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalOrderPresentation +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalOrderType +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalOrderTypeLevels +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalOrderTypeSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalPaddingSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalPairCode +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalPairSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalProductClosure +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalProductPresentation +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalProductReplacement +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalProductSets +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalProductSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalSumClosure +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalSumLevels +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalSumPresentation +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalSumSets +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalSumSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalVectorRecovery +OAI.Computability.DegreeRigidity.OrdinalCodes.OrdinalVectorSyntax +OAI.Computability.DegreeRigidity.OrdinalCodes.PaddedOmegaBoundary +OAI.Computability.DegreeRigidity.OrdinalCodes.ProductCertificateCollection +OAI.Computability.DegreeRigidity.OrdinalCodes.RankDefinability +OAI.Computability.DegreeRigidity.OrdinalCodes.RankGraphConstruction +OAI.Computability.DegreeRigidity.OrdinalCodes.RankOrdinal +OAI.Computability.DegreeRigidity.OrdinalCodes.RankRecursion +OAI.Computability.DegreeRigidity.OrdinalCodes.Recurrence +OAI.Computability.DegreeRigidity.OrdinalCodes.SelectorOrdinalEnumeration +OAI.Computability.DegreeRigidity.OrdinalCodes.SuccessorOmegaCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.SumCertificateLevels +OAI.Computability.DegreeRigidity.OrdinalCodes.SumCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.SumComparison +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedBoundaryCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedOrderDomains +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedPaddedSum +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedPresentation +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedProductGraph +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedSumDomains +OAI.Computability.DegreeRigidity.OrdinalCodes.TrimmedSumGraph +OAI.Computability.DegreeRigidity.OrdinalCodes.VectorCodeCertificates +OAI.Computability.DegreeRigidity.OrdinalCodes.VectorCodeLevels +OAI.Computability.DegreeRigidity.Representation.AmbientDegreeActual +OAI.Computability.DegreeRigidity.Representation.AmbientDegreeBinding +OAI.Computability.DegreeRigidity.Representation.AmbientDegreeSyntax +OAI.Computability.DegreeRigidity.Representation.AmbientExtensionBody +OAI.Computability.DegreeRigidity.Representation.Assembly +OAI.Computability.DegreeRigidity.Representation.AutomorphismName +OAI.Computability.DegreeRigidity.Representation.AutomorphismOutputSentence +OAI.Computability.DegreeRigidity.Representation.AutomorphismUnion +OAI.Computability.DegreeRigidity.Representation.BorelGeneric +OAI.Computability.DegreeRigidity.Representation.Category +OAI.Computability.DegreeRigidity.Representation.CategoryAvoidance +OAI.Computability.DegreeRigidity.Representation.CategoryMachine +OAI.Computability.DegreeRigidity.Representation.CategoryMain +OAI.Computability.DegreeRigidity.Representation.CategoryReduction +OAI.Computability.DegreeRigidity.Representation.CommonExtensionProgram +OAI.Computability.DegreeRigidity.Representation.CommonGenericModels +OAI.Computability.DegreeRigidity.Representation.CommonIdeal +OAI.Computability.DegreeRigidity.Representation.CommonIdealBorel +OAI.Computability.DegreeRigidity.Representation.CommonIdealSearch +OAI.Computability.DegreeRigidity.Representation.CommonIdealSelection +OAI.Computability.DegreeRigidity.Representation.CountableGroundGeneric +OAI.Computability.DegreeRigidity.Representation.CoverageMain +OAI.Computability.DegreeRigidity.Representation.Endpoints +OAI.Computability.DegreeRigidity.Representation.FullNativePersistence +OAI.Computability.DegreeRigidity.Representation.GenericAssembly +OAI.Computability.DegreeRigidity.Representation.GenericCoding +OAI.Computability.DegreeRigidity.Representation.GenericCodingBorel +OAI.Computability.DegreeRigidity.Representation.GenericDescentDefinition +OAI.Computability.DegreeRigidity.Representation.GenericFactor +OAI.Computability.DegreeRigidity.Representation.GenericFiberIdeal +OAI.Computability.DegreeRigidity.Representation.GenericFilterName +OAI.Computability.DegreeRigidity.Representation.GenericIdentity +OAI.Computability.DegreeRigidity.Representation.GenericOneRealNames +OAI.Computability.DegreeRigidity.Representation.GenericPersistenceDescent +OAI.Computability.DegreeRigidity.Representation.GenericRealColumnRealization +OAI.Computability.DegreeRigidity.Representation.GenericRepresentation +OAI.Computability.DegreeRigidity.Representation.GenericSourceTransfer +OAI.Computability.DegreeRigidity.Representation.GenericTopology +OAI.Computability.DegreeRigidity.Representation.GenericTotality +OAI.Computability.DegreeRigidity.Representation.GenericTruth +OAI.Computability.DegreeRigidity.Representation.GlobalArithmeticGenericProgram +OAI.Computability.DegreeRigidity.Representation.GlobalJumpRestriction +OAI.Computability.DegreeRigidity.Representation.GlobalLocality +OAI.Computability.DegreeRigidity.Representation.GroundArithmeticGeneric +OAI.Computability.DegreeRigidity.Representation.GroundDegreeCollapse +OAI.Computability.DegreeRigidity.Representation.GroundDegreePresentation +OAI.Computability.DegreeRigidity.Representation.GroundGenericRequirements +OAI.Computability.DegreeRigidity.Representation.GroundInclusion +OAI.Computability.DegreeRigidity.Representation.GroundIteratedTriple +OAI.Computability.DegreeRigidity.Representation.GroundPrefixOverwrite +OAI.Computability.DegreeRigidity.Representation.GroundSeedOrdinalHeight +OAI.Computability.DegreeRigidity.Representation.HomogeneousDegreeExtension +OAI.Computability.DegreeRigidity.Representation.IteratedGenericCommonIdeal +OAI.Computability.DegreeRigidity.Representation.NativeGenericWitness +OAI.Computability.DegreeRigidity.Representation.NativeModelCompatibility +OAI.Computability.DegreeRigidity.Representation.NativePersistenceSyntax +OAI.Computability.DegreeRigidity.Representation.OriginalRealCohenFactorization +OAI.Computability.DegreeRigidity.Representation.OriginalRealDefinitionTransport +OAI.Computability.DegreeRigidity.Representation.OriginalRealFullIteration +OAI.Computability.DegreeRigidity.Representation.OriginalRealGeneratedModel +OAI.Computability.DegreeRigidity.Representation.OriginalRealQuotientModel +OAI.Computability.DegreeRigidity.Representation.OriginalRealUniformDefinition +OAI.Computability.DegreeRigidity.Representation.OriginalRealUniformExtension +OAI.Computability.DegreeRigidity.Representation.OwnDegreeExtensionMeaning +OAI.Computability.DegreeRigidity.Representation.OwnProgramValue +OAI.Computability.DegreeRigidity.Representation.OwnRealsConstruction +OAI.Computability.DegreeRigidity.Representation.OwnRealsLevelDefinition +OAI.Computability.DegreeRigidity.Representation.OwnSourceEquation +OAI.Computability.DegreeRigidity.Representation.OwnStageSourceTheory +OAI.Computability.DegreeRigidity.Representation.PairGenericSelection +OAI.Computability.DegreeRigidity.Representation.ParameterCoveringModels +OAI.Computability.DegreeRigidity.Representation.PrescribedArithmeticGenericProgram +OAI.Computability.DegreeRigidity.Representation.PrescribedColumnPrefixProgram +OAI.Computability.DegreeRigidity.Representation.PrescribedCoveringModel +OAI.Computability.DegreeRigidity.Representation.PrescribedFirstUncountable +OAI.Computability.DegreeRigidity.Representation.PrescribedGenericRestriction +OAI.Computability.DegreeRigidity.Representation.PrescribedGroundOracleProgram +OAI.Computability.DegreeRigidity.Representation.PrescribedModelRestriction +OAI.Computability.DegreeRigidity.Representation.PrescribedOneRealNames +OAI.Computability.DegreeRigidity.Representation.PrescribedOracleValue +OAI.Computability.DegreeRigidity.Representation.PrescribedRealHullExtension +OAI.Computability.DegreeRigidity.Representation.PrescribedUnrestrictedGroundProgram +OAI.Computability.DegreeRigidity.Representation.RealCollapseReconstruction +OAI.Computability.DegreeRigidity.Representation.RealGeneratedModel +OAI.Computability.DegreeRigidity.Representation.RealGeneratedPart +OAI.Computability.DegreeRigidity.Representation.RealHullColumnRealization +OAI.Computability.DegreeRigidity.Representation.RealHullGenericTriple +OAI.Computability.DegreeRigidity.Representation.RealHullIteration +OAI.Computability.DegreeRigidity.Representation.RealHullPrescribedTruth +OAI.Computability.DegreeRigidity.Representation.RealHullQuotient +OAI.Computability.DegreeRigidity.Representation.Reduction +OAI.Computability.DegreeRigidity.Representation.RepresentationEndgame +OAI.Computability.DegreeRigidity.Representation.SameExtensionCommonIdeal +OAI.Computability.DegreeRigidity.Representation.SameExtensionGenericTriple +OAI.Computability.DegreeRigidity.Representation.SameExtensionIteration +OAI.Computability.DegreeRigidity.Representation.SameRealBooleanFilter +OAI.Computability.DegreeRigidity.Representation.SetAutomorphismReconstruction +OAI.Computability.DegreeRigidity.Representation.SourceEquationTail +OAI.Computability.DegreeRigidity.Representation.SourceIdentity +OAI.Computability.DegreeRigidity.Representation.SourceTAbsolutenessEndpoint +OAI.Computability.DegreeRigidity.Representation.SourceTArithmeticAbsoluteness +OAI.Computability.DegreeRigidity.Representation.SourceTCountability +OAI.Computability.DegreeRigidity.Representation.SourceTDependentChoice +OAI.Computability.DegreeRigidity.Representation.SourceTGenericExistence +OAI.Computability.DegreeRigidity.Representation.SourceTGenericPersistence +OAI.Computability.DegreeRigidity.Representation.SourceTGenericPresentation +OAI.Computability.DegreeRigidity.Representation.SourceTModelBridge +OAI.Computability.DegreeRigidity.Representation.SourceTNativeAbsoluteness +OAI.Computability.DegreeRigidity.Representation.SourceTNativeComparison +OAI.Computability.DegreeRigidity.Representation.SourceTPersistentDecoding +OAI.Computability.DegreeRigidity.Representation.SourceTPresentationComparison +OAI.Computability.DegreeRigidity.Representation.SourceTTreeAbsoluteness +OAI.Computability.DegreeRigidity.Representation.SourceTWellFounded +OAI.Computability.DegreeRigidity.Representation.SourceTheory +OAI.Computability.DegreeRigidity.SetModels.BindCanonicalArithmetic +OAI.Computability.DegreeRigidity.SetModels.ChoiceFromOrdinalCover +OAI.Computability.DegreeRigidity.SetModels.ChoiceTrace +OAI.Computability.DegreeRigidity.SetModels.ChoiceTraceExtension +OAI.Computability.DegreeRigidity.SetModels.ChoiceTraceFormula +OAI.Computability.DegreeRigidity.SetModels.ClosedPaddingCertificates +OAI.Computability.DegreeRigidity.SetModels.CofinalPaddedDecoder +OAI.Computability.DegreeRigidity.SetModels.CollapseCertificate +OAI.Computability.DegreeRigidity.SetModels.CollapseCoding +OAI.Computability.DegreeRigidity.SetModels.CollapseCollection +OAI.Computability.DegreeRigidity.SetModels.CollapseCountWithoutChoice +OAI.Computability.DegreeRigidity.SetModels.CollapseDenseWithoutChoice +OAI.Computability.DegreeRigidity.SetModels.CollapseInternalCountingWithoutChoice +OAI.Computability.DegreeRigidity.SetModels.CollapsePrefixAbsolute +OAI.Computability.DegreeRigidity.SetModels.CollapseWithoutChoice +OAI.Computability.DegreeRigidity.SetModels.ColumnSetFormula +OAI.Computability.DegreeRigidity.SetModels.ConservativeExtension +OAI.Computability.DegreeRigidity.SetModels.ContinuousCode +OAI.Computability.DegreeRigidity.SetModels.CountableBound +OAI.Computability.DegreeRigidity.SetModels.CountableElementaryHull +OAI.Computability.DegreeRigidity.SetModels.CountableNameAvoidance +OAI.Computability.DegreeRigidity.SetModels.CountableSetReal +OAI.Computability.DegreeRigidity.SetModels.CountedOriginalRealQuotient +OAI.Computability.DegreeRigidity.SetModels.CountedRealsPresentation +OAI.Computability.DegreeRigidity.SetModels.CountedRegularBasis +OAI.Computability.DegreeRigidity.SetModels.DecodingTheorem +OAI.Computability.DegreeRigidity.SetModels.DegreeSetFormula +OAI.Computability.DegreeRigidity.SetModels.DegreeUniverseWithoutChoice +OAI.Computability.DegreeRigidity.SetModels.Degrees +OAI.Computability.DegreeRigidity.SetModels.DenseInclusionExtension +OAI.Computability.DegreeRigidity.SetModels.ElementaryAxioms +OAI.Computability.DegreeRigidity.SetModels.ElementaryCheckedCode +OAI.Computability.DegreeRigidity.SetModels.ElementaryCollapse +OAI.Computability.DegreeRigidity.SetModels.ElementaryCollapsePoset +OAI.Computability.DegreeRigidity.SetModels.ElementaryDefinableSets +OAI.Computability.DegreeRigidity.SetModels.ElementaryDegreeHull +OAI.Computability.DegreeRigidity.SetModels.ElementaryLanguage +OAI.Computability.DegreeRigidity.SetModels.ElementaryModelIdeal +OAI.Computability.DegreeRigidity.SetModels.ElementaryRealModel +OAI.Computability.DegreeRigidity.SetModels.ElementarySatisfaction +OAI.Computability.DegreeRigidity.SetModels.ElementarySchemas +OAI.Computability.DegreeRigidity.SetModels.EnumerationConstruction +OAI.Computability.DegreeRigidity.SetModels.EnumerationDecoding +OAI.Computability.DegreeRigidity.SetModels.EnumerationTransport +OAI.Computability.DegreeRigidity.SetModels.EvaluationNameCode +OAI.Computability.DegreeRigidity.SetModels.ExactOmegaGraph +OAI.Computability.DegreeRigidity.SetModels.ExtensionArithmeticRepresentative +OAI.Computability.DegreeRigidity.SetModels.ExtensionBasicAxioms +OAI.Computability.DegreeRigidity.SetModels.ExtensionChoice +OAI.Computability.DegreeRigidity.SetModels.ExtensionPowerSet +OAI.Computability.DegreeRigidity.SetModels.ExtensionSeparation +OAI.Computability.DegreeRigidity.SetModels.ExtensionSigmaReplacement +OAI.Computability.DegreeRigidity.SetModels.ExtensionSigmaSeparation +OAI.Computability.DegreeRigidity.SetModels.ExtensionWitnessCover +OAI.Computability.DegreeRigidity.SetModels.FiniteClosure +OAI.Computability.DegreeRigidity.SetModels.FiniteOrdinalCode +OAI.Computability.DegreeRigidity.SetModels.FinitePresentation +OAI.Computability.DegreeRigidity.SetModels.FiniteSkolem +OAI.Computability.DegreeRigidity.SetModels.FiniteSupport +OAI.Computability.DegreeRigidity.SetModels.FixedArithmetic +OAI.Computability.DegreeRigidity.SetModels.FixedArithmeticTailCone +OAI.Computability.DegreeRigidity.SetModels.FragmentHull +OAI.Computability.DegreeRigidity.SetModels.FullSetTruth +OAI.Computability.DegreeRigidity.SetModels.GeneratedBooleanPart +OAI.Computability.DegreeRigidity.SetModels.GeneratedHull +OAI.Computability.DegreeRigidity.SetModels.IdealCopy +OAI.Computability.DegreeRigidity.SetModels.IdealEnumeration +OAI.Computability.DegreeRigidity.SetModels.IdealInterpretation +OAI.Computability.DegreeRigidity.SetModels.IdealLift +OAI.Computability.DegreeRigidity.SetModels.IdealLocality +OAI.Computability.DegreeRigidity.SetModels.IdealPresentation +OAI.Computability.DegreeRigidity.SetModels.IdealSelection +OAI.Computability.DegreeRigidity.SetModels.InternalAtomicTruth +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanBits +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanDense +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanExtension +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanGeneric +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanGraph +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanIntermediate +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanName +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanProjection +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanSyntax +OAI.Computability.DegreeRigidity.SetModels.InternalBooleanTop +OAI.Computability.DegreeRigidity.SetModels.InternalBoundedTruth +OAI.Computability.DegreeRigidity.SetModels.InternalCheckRecursion +OAI.Computability.DegreeRigidity.SetModels.InternalCheckedValue +OAI.Computability.DegreeRigidity.SetModels.InternalChoice +OAI.Computability.DegreeRigidity.SetModels.InternalCollapseConditions +OAI.Computability.DegreeRigidity.SetModels.InternalCollapseCounting +OAI.Computability.DegreeRigidity.SetModels.InternalCollapseDense +OAI.Computability.DegreeRigidity.SetModels.InternalCollapseExistence +OAI.Computability.DegreeRigidity.SetModels.InternalColumnExtension +OAI.Computability.DegreeRigidity.SetModels.InternalColumnProjection +OAI.Computability.DegreeRigidity.SetModels.InternalCommonRequirements +OAI.Computability.DegreeRigidity.SetModels.InternalContainer +OAI.Computability.DegreeRigidity.SetModels.InternalCountableClosure +OAI.Computability.DegreeRigidity.SetModels.InternalCountableEnumeration +OAI.Computability.DegreeRigidity.SetModels.InternalCountableFamily +OAI.Computability.DegreeRigidity.SetModels.InternalCountableFiniteUnion +OAI.Computability.DegreeRigidity.SetModels.InternalCountableMap +OAI.Computability.DegreeRigidity.SetModels.InternalCountableOrdinals +OAI.Computability.DegreeRigidity.SetModels.InternalCountableProduct +OAI.Computability.DegreeRigidity.SetModels.InternalCountableUnion +OAI.Computability.DegreeRigidity.SetModels.InternalCoverInjection +OAI.Computability.DegreeRigidity.SetModels.InternalDefinablePower +OAI.Computability.DegreeRigidity.SetModels.InternalDenseFamily +OAI.Computability.DegreeRigidity.SetModels.InternalDenseInclusion +OAI.Computability.DegreeRigidity.SetModels.InternalFiniteEnumeration +OAI.Computability.DegreeRigidity.SetModels.InternalFiniteExhaustion +OAI.Computability.DegreeRigidity.SetModels.InternalFiniteSubsets +OAI.Computability.DegreeRigidity.SetModels.InternalFixedPoint +OAI.Computability.DegreeRigidity.SetModels.InternalFunctionOrbit +OAI.Computability.DegreeRigidity.SetModels.InternalGeneratedAlgebra +OAI.Computability.DegreeRigidity.SetModels.InternalGenericFilter +OAI.Computability.DegreeRigidity.SetModels.InternalGenericSequence +OAI.Computability.DegreeRigidity.SetModels.InternalGraphEquiv +OAI.Computability.DegreeRigidity.SetModels.InternalHartogs +OAI.Computability.DegreeRigidity.SetModels.InternalHomogeneousTruth +OAI.Computability.DegreeRigidity.SetModels.InternalHull +OAI.Computability.DegreeRigidity.SetModels.InternalInfinity +OAI.Computability.DegreeRigidity.SetModels.InternalInverseGraph +OAI.Computability.DegreeRigidity.SetModels.InternalInverseIso +OAI.Computability.DegreeRigidity.SetModels.InternalMinimalSelector +OAI.Computability.DegreeRigidity.SetModels.InternalNameEvaluation +OAI.Computability.DegreeRigidity.SetModels.InternalNameValidity +OAI.Computability.DegreeRigidity.SetModels.InternalNaturalCheckSequence +OAI.Computability.DegreeRigidity.SetModels.InternalNaturalRelationReal +OAI.Computability.DegreeRigidity.SetModels.InternalNiceName +OAI.Computability.DegreeRigidity.SetModels.InternalOrderIsoTransport +OAI.Computability.DegreeRigidity.SetModels.InternalOrdinalCodes +OAI.Computability.DegreeRigidity.SetModels.InternalOrdinalEnumeration +OAI.Computability.DegreeRigidity.SetModels.InternalOrdinalSubset +OAI.Computability.DegreeRigidity.SetModels.InternalPositiveNameFamily +OAI.Computability.DegreeRigidity.SetModels.InternalPresentationEnumeration +OAI.Computability.DegreeRigidity.SetModels.InternalPrimitiveGraph +OAI.Computability.DegreeRigidity.SetModels.InternalProductBijection +OAI.Computability.DegreeRigidity.SetModels.InternalProjectedGeneric +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientConditions +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientCountability +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientExtension +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientGeneric +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientLifting +OAI.Computability.DegreeRigidity.SetModels.InternalQuotientRequirement +OAI.Computability.DegreeRigidity.SetModels.InternalRealQuotient +OAI.Computability.DegreeRigidity.SetModels.InternalRegularAlgebra +OAI.Computability.DegreeRigidity.SetModels.InternalRegularOperations +OAI.Computability.DegreeRigidity.SetModels.InternalRegularOrder +OAI.Computability.DegreeRigidity.SetModels.InternalRegularSplitter +OAI.Computability.DegreeRigidity.SetModels.InternalRegularTree +OAI.Computability.DegreeRigidity.SetModels.InternalRelationCollapse +OAI.Computability.DegreeRigidity.SetModels.InternalRelationSelection +OAI.Computability.DegreeRigidity.SetModels.InternalSameNameGeneric +OAI.Computability.DegreeRigidity.SetModels.InternalSatisfactionSlice +OAI.Computability.DegreeRigidity.SetModels.InternalSequenceRange +OAI.Computability.DegreeRigidity.SetModels.InternalSerialSelection +OAI.Computability.DegreeRigidity.SetModels.InternalShuffleGeneric +OAI.Computability.DegreeRigidity.SetModels.InternalShuffleSets +OAI.Computability.DegreeRigidity.SetModels.InternalSigmaSequence +OAI.Computability.DegreeRigidity.SetModels.InternalSingletonColumn +OAI.Computability.DegreeRigidity.SetModels.InternalStructureCollapse +OAI.Computability.DegreeRigidity.SetModels.InternalSubsetSequence +OAI.Computability.DegreeRigidity.SetModels.InternalUncountableComplement +OAI.Computability.DegreeRigidity.SetModels.InternalUncountableSentence +OAI.Computability.DegreeRigidity.SetModels.InternalUniformization +OAI.Computability.DegreeRigidity.SetModels.IntersectionName +OAI.Computability.DegreeRigidity.SetModels.ModelArithmeticComprehension +OAI.Computability.DegreeRigidity.SetModels.ModelArithmeticTreeDescent +OAI.Computability.DegreeRigidity.SetModels.ModelAutomorphismInterpretation +OAI.Computability.DegreeRigidity.SetModels.ModelDegreeCodes +OAI.Computability.DegreeRigidity.SetModels.ModelDegreeOrder +OAI.Computability.DegreeRigidity.SetModels.ModelDegreeUniverse +OAI.Computability.DegreeRigidity.SetModels.ModelIdealInterpretation +OAI.Computability.DegreeRigidity.SetModels.ModelIterationFormula +OAI.Computability.DegreeRigidity.SetModels.ModelIterationTrace +OAI.Computability.DegreeRigidity.SetModels.ModelNaturalNumbers +OAI.Computability.DegreeRigidity.SetModels.ModelOmegaJump +OAI.Computability.DegreeRigidity.SetModels.ModelOrderSatisfaction +OAI.Computability.DegreeRigidity.SetModels.ModelPersistenceReals +OAI.Computability.DegreeRigidity.SetModels.ModelPersistenceSatisfaction +OAI.Computability.DegreeRigidity.SetModels.ModelPersistentGraph +OAI.Computability.DegreeRigidity.SetModels.ModelPresentationSets +OAI.Computability.DegreeRigidity.SetModels.ModelProducts +OAI.Computability.DegreeRigidity.SetModels.ModelRealOperations +OAI.Computability.DegreeRigidity.SetModels.ModelReals +OAI.Computability.DegreeRigidity.SetModels.MostowskiCollapse +OAI.Computability.DegreeRigidity.SetModels.NameDifferenceDense +OAI.Computability.DegreeRigidity.SetModels.NameEncoding +OAI.Computability.DegreeRigidity.SetModels.NameEvaluationGraph +OAI.Computability.DegreeRigidity.SetModels.NameExtension +OAI.Computability.DegreeRigidity.SetModels.NameSupport +OAI.Computability.DegreeRigidity.SetModels.NameUnionCode +OAI.Computability.DegreeRigidity.SetModels.NameValidity +OAI.Computability.DegreeRigidity.SetModels.NameValueCover +OAI.Computability.DegreeRigidity.SetModels.NoNewOrdinals +OAI.Computability.DegreeRigidity.SetModels.OrderedNameCode +OAI.Computability.DegreeRigidity.SetModels.ParametricEval +OAI.Computability.DegreeRigidity.SetModels.PresentationEnumeration +OAI.Computability.DegreeRigidity.SetModels.PresentationGraphSet +OAI.Computability.DegreeRigidity.SetModels.PresentedDegreeEmbedding +OAI.Computability.DegreeRigidity.SetModels.ProjectedArithmeticOutputCone +OAI.Computability.DegreeRigidity.SetModels.ProjectedArithmeticOutputName +OAI.Computability.DegreeRigidity.SetModels.RecursiveNameSymmetry +OAI.Computability.DegreeRigidity.SetModels.RecursiveNames +OAI.Computability.DegreeRigidity.SetModels.RecursiveOmegaBound +OAI.Computability.DegreeRigidity.SetModels.RecursiveSumBound +OAI.Computability.DegreeRigidity.SetModels.RegularBinaryTree +OAI.Computability.DegreeRigidity.SetModels.RegularCodeSplitting +OAI.Computability.DegreeRigidity.SetModels.RegularCompletion +OAI.Computability.DegreeRigidity.SetModels.RegularDecisionPartition +OAI.Computability.DegreeRigidity.SetModels.RegularProjection +OAI.Computability.DegreeRigidity.SetModels.RegularTreeCofinality +OAI.Computability.DegreeRigidity.SetModels.RegularTreeCompatibility +OAI.Computability.DegreeRigidity.SetModels.RegularTreeExtension +OAI.Computability.DegreeRigidity.SetModels.RegularTreeFilter +OAI.Computability.DegreeRigidity.SetModels.RegularTreeRecovery +OAI.Computability.DegreeRigidity.SetModels.RegularTreeRun +OAI.Computability.DegreeRigidity.SetModels.RelationCoding +OAI.Computability.DegreeRigidity.SetModels.RelationCollapse +OAI.Computability.DegreeRigidity.SetModels.RelationHull +OAI.Computability.DegreeRigidity.SetModels.RelationPresentation +OAI.Computability.DegreeRigidity.SetModels.RestrictedName +OAI.Computability.DegreeRigidity.SetModels.RestrictedOmegaRecursion +OAI.Computability.DegreeRigidity.SetModels.SelectedColumnArithmeticCone +OAI.Computability.DegreeRigidity.SetModels.SelectedColumnPrefixProgram +OAI.Computability.DegreeRigidity.SetModels.SetDegreeDecoding +OAI.Computability.DegreeRigidity.SetModels.SetModelActionDecoding +OAI.Computability.DegreeRigidity.SetModels.SetModelActionSatisfaction +OAI.Computability.DegreeRigidity.SetModels.SetModelAddition +OAI.Computability.DegreeRigidity.SetModels.SetModelArithmeticClosure +OAI.Computability.DegreeRigidity.SetModels.SetModelArithmeticDischarge +OAI.Computability.DegreeRigidity.SetModels.SetModelArithmeticInterface +OAI.Computability.DegreeRigidity.SetModels.SetModelArithmeticSyntax +OAI.Computability.DegreeRigidity.SetModels.SetModelArithmeticTree +OAI.Computability.DegreeRigidity.SetModels.SetModelColumns +OAI.Computability.DegreeRigidity.SetModels.SetModelCountability +OAI.Computability.DegreeRigidity.SetModels.SetModelCountableExtensions +OAI.Computability.DegreeRigidity.SetModels.SetModelCountablePresentation +OAI.Computability.DegreeRigidity.SetModels.SetModelDegreeUniverse +OAI.Computability.DegreeRigidity.SetModels.SetModelFunctionGraphs +OAI.Computability.DegreeRigidity.SetModels.SetModelFunctionIteration +OAI.Computability.DegreeRigidity.SetModels.SetModelFunctionPairing +OAI.Computability.DegreeRigidity.SetModels.SetModelGraphImage +OAI.Computability.DegreeRigidity.SetModels.SetModelGraphPresentation +OAI.Computability.DegreeRigidity.SetModels.SetModelIdealDecoding +OAI.Computability.DegreeRigidity.SetModels.SetModelIdealSatisfaction +OAI.Computability.DegreeRigidity.SetModels.SetModelInternalRelations +OAI.Computability.DegreeRigidity.SetModels.SetModelIteration +OAI.Computability.DegreeRigidity.SetModels.SetModelJoin +OAI.Computability.DegreeRigidity.SetModels.SetModelMultiplication +OAI.Computability.DegreeRigidity.SetModels.SetModelMultiplicationStep +OAI.Computability.DegreeRigidity.SetModels.SetModelOmegaJump +OAI.Computability.DegreeRigidity.SetModels.SetModelPairing +OAI.Computability.DegreeRigidity.SetModels.SetModelPersistence +OAI.Computability.DegreeRigidity.SetModels.SetModelPersistenceDecoding +OAI.Computability.DegreeRigidity.SetModels.SetModelPersistentSatisfaction +OAI.Computability.DegreeRigidity.SetModels.SetModelPresentedCountability +OAI.Computability.DegreeRigidity.SetModels.SetModelPrimrec +OAI.Computability.DegreeRigidity.SetModels.SetModelReals +OAI.Computability.DegreeRigidity.SetModels.SetModelRecursion +OAI.Computability.DegreeRigidity.SetModels.SetModelSequences +OAI.Computability.DegreeRigidity.SetModels.SetModelTreeRelations +OAI.Computability.DegreeRigidity.SetModels.SetPresentationDecoding +OAI.Computability.DegreeRigidity.SetModels.ShuffleRequirements +OAI.Computability.DegreeRigidity.SetModels.SkolemHull +OAI.Computability.DegreeRigidity.SetModels.SkolemOperations +OAI.Computability.DegreeRigidity.SetModels.SmallWitnessBound +OAI.Computability.DegreeRigidity.SetModels.TransitiveNameModel +OAI.Computability.DegreeRigidity.SetModels.TwoRealHull +OAI.Computability.DegreeRigidity.SetModels.UnionIteration +OAI.Computability.DegreeRigidity.SetModels.ValidFirstUncountable +OAI.Computability.DegreeRigidity.SetModels.WeakNameAvoidance +OAI.Computability.DegreeRigidity.SetModels.WeakNameDifference +OAI.Computability.DegreeRigidity.SetModels.WeakRealDescent +OAI.Computability.DegreeRigidity.Syntax.AtomicCertificate +OAI.Computability.DegreeRigidity.Syntax.AtomicDecisionFormula +OAI.Computability.DegreeRigidity.Syntax.AtomicDefinability +OAI.Computability.DegreeRigidity.Syntax.AtomicEncoding +OAI.Computability.DegreeRigidity.Syntax.AtomicFormula +OAI.Computability.DegreeRigidity.Syntax.AtomicGraph +OAI.Computability.DegreeRigidity.Syntax.AtomicGraphCorrect +OAI.Computability.DegreeRigidity.Syntax.AtomicRequirements +OAI.Computability.DegreeRigidity.Syntax.AtomicTruth +OAI.Computability.DegreeRigidity.Syntax.BooleanEvaluationWitness +OAI.Computability.DegreeRigidity.Syntax.BooleanExpressionAssembly +OAI.Computability.DegreeRigidity.Syntax.BooleanExpressionCertificate +OAI.Computability.DegreeRigidity.Syntax.BooleanExpressionCoverage +OAI.Computability.DegreeRigidity.Syntax.BooleanExpressionSyntax +OAI.Computability.DegreeRigidity.Syntax.BooleanExpressionTruth +OAI.Computability.DegreeRigidity.Syntax.BooleanFilterReconstruction +OAI.Computability.DegreeRigidity.Syntax.BooleanProjection +OAI.Computability.DegreeRigidity.Syntax.BooleanTruthReading +OAI.Computability.DegreeRigidity.Syntax.BoundedAutomorphismOutput +OAI.Computability.DegreeRigidity.Syntax.BoundedCertificate +OAI.Computability.DegreeRigidity.Syntax.BoundedDecoding +OAI.Computability.DegreeRigidity.Syntax.BoundedDefinability +OAI.Computability.DegreeRigidity.Syntax.BoundedFormulaRename +OAI.Computability.DegreeRigidity.Syntax.BoundedHierarchyCertificates +OAI.Computability.DegreeRigidity.Syntax.BoundedOmegaGraph +OAI.Computability.DegreeRigidity.Syntax.BoundedRecursive +OAI.Computability.DegreeRigidity.Syntax.BoundedRelations +OAI.Computability.DegreeRigidity.Syntax.BoundedSeparationName +OAI.Computability.DegreeRigidity.Syntax.BoundedSetTheory +OAI.Computability.DegreeRigidity.Syntax.BoundedSupport +OAI.Computability.DegreeRigidity.Syntax.BoundedTruthRecursion +OAI.Computability.DegreeRigidity.Syntax.CertificateMatrix +OAI.Computability.DegreeRigidity.Syntax.CheckGraphConstruction +OAI.Computability.DegreeRigidity.Syntax.CheckedCode +OAI.Computability.DegreeRigidity.Syntax.CheckedDefSuccessor +OAI.Computability.DegreeRigidity.Syntax.CheckedHierarchySyntax +OAI.Computability.DegreeRigidity.Syntax.CheckedMembershipSeparation +OAI.Computability.DegreeRigidity.Syntax.DefinablePower +OAI.Computability.DegreeRigidity.Syntax.DefinableSubsetCertificates +OAI.Computability.DegreeRigidity.Syntax.DefinedOutputTailCone +OAI.Computability.DegreeRigidity.Syntax.DefinedPrefixRemoval +OAI.Computability.DegreeRigidity.Syntax.FiniteFragment +OAI.Computability.DegreeRigidity.Syntax.FiniteGraphSatisfaction +OAI.Computability.DegreeRigidity.Syntax.FiniteModelGraph +OAI.Computability.DegreeRigidity.Syntax.FiniteSatisfactionCertificate +OAI.Computability.DegreeRigidity.Syntax.FiniteTerm +OAI.Computability.DegreeRigidity.Syntax.FormulaIsomorphism +OAI.Computability.DegreeRigidity.Syntax.LevySigmaNormalization +OAI.Computability.DegreeRigidity.Syntax.LevySigmaSchemas +OAI.Computability.DegreeRigidity.Syntax.MembershipInterpretation +OAI.Computability.DegreeRigidity.Syntax.PiOneOneSatisfaction +OAI.Computability.DegreeRigidity.Syntax.PrimitivePredicateFormula +OAI.Computability.DegreeRigidity.Syntax.SatisfactionCertificateBound +OAI.Computability.DegreeRigidity.Syntax.SatisfactionRecursion +OAI.Computability.DegreeRigidity.Syntax.SatisfactionSystemCertificate +OAI.Computability.DegreeRigidity.Syntax.SentenceCode +OAI.Computability.DegreeRigidity.Syntax.SentenceCodeDefinability +OAI.Computability.DegreeRigidity.Syntax.SentenceCodeFamily +OAI.Computability.DegreeRigidity.Syntax.SentenceFamilyFormula +OAI.Computability.DegreeRigidity.Syntax.SentenceInlining +OAI.Computability.DegreeRigidity.Syntax.SentenceSupportCertificate +OAI.Computability.DegreeRigidity.Syntax.SentenceSupportFormula +OAI.Computability.DegreeRigidity.Syntax.SetRankCertificate +OAI.Computability.DegreeRigidity.Syntax.SetSatisfactionBounded +OAI.Computability.DegreeRigidity.Syntax.SigmaBoundedUniversal +OAI.Computability.DegreeRigidity.Syntax.SigmaCollection +OAI.Computability.DegreeRigidity.Syntax.SigmaCollectionClosure +OAI.Computability.DegreeRigidity.Syntax.SigmaDefinability +OAI.Computability.DegreeRigidity.Syntax.SigmaDisjunction +OAI.Computability.DegreeRigidity.Syntax.SigmaDomainCollection +OAI.Computability.DegreeRigidity.Syntax.SigmaHull +OAI.Computability.DegreeRigidity.Syntax.SigmaInterpretation +OAI.Computability.DegreeRigidity.Syntax.SigmaParameterized +OAI.Computability.DegreeRigidity.Syntax.SigmaParameterizedClosure +OAI.Computability.DegreeRigidity.Syntax.SigmaSeparationName +OAI.Computability.DegreeRigidity.Syntax.SigmaSequenceTrace +OAI.Computability.DegreeRigidity.Syntax.SigmaSyntax +OAI.Computability.DegreeRigidity.Syntax.SigmaTransitiveWitness +OAI.Computability.DegreeRigidity.Syntax.TermCertificate +OAI.Computability.DegreeRigidity.Syntax.TermEvaluationGraph +OAI.Computability.DegreeRigidity.Syntax.TermFormula +OAI.Computability.DegreeRigidity.Syntax.TermFunctionality +OAI.Computability.DegreeRigidity.Syntax.VariableCertificateBounds +OAI.Computability.DegreeRigidity.Syntax.VariableTruthSyntax +OAI.Computability.DegreeRigidity.Syntax.WeakCheckedMembership +OAI.Computability.DegreeRigidity.Syntax.WeakCheckedValue +OAI.Computability.DegreeRigidity.Syntax.WeakExtensionContext diff --git a/tasks/degree-rigidity/solution/reference.py b/tasks/degree-rigidity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/degree-rigidity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/degree-rigidity/solution/solve.sh b/tasks/degree-rigidity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..eb7c1c333b007845ddb7e52d6d0ff45206caa5cf --- /dev/null +++ b/tasks/degree-rigidity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DegreeRigidity, i.e. module OAI.Computability.DegreeRigidity.Main and the +# 974 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.DegreeRigidity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DegreeRigidity" diff --git a/tasks/degree-rigidity/task.toml b/tasks/degree-rigidity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8977a889e7947c3a655695931e3c85d0f5f63f63 --- /dev/null +++ b/tasks/degree-rigidity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/degree-rigidity" +version = "1.0.0" +description = "Prove DegreeRigidity (openai/math family 241: Rigidity of the Turing degrees) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DegreeRigidity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DegreeRigidity" +family = "241" +family_title = "Rigidity of the Turing degrees" +subject = "Mathematical logic" +theorems = ["OAI.TuringRigidity.ManuscriptMain.rigidity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.DegreeRigidity.Main" +reference_modules = 974 +reference_lean_bytes = 3922761 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1821 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15230 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/degree-rigidity/tests/Challenge.lean b/tasks/degree-rigidity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a90bf57d0240e799a371c917cb2aee14a354d03 --- /dev/null +++ b/tasks/degree-rigidity/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +namespace TuringRigidity + +abbrev Oracle := ℕ → Bool + +def oracleFunction (A : Oracle) : ℕ →. ℕ := fun n => Part.some (if A n then 1 else 0) + +def Reduces (A B : Oracle) : Prop := TuringReducible (oracleFunction A) (oracleFunction B) + +instance : IsPreorder Oracle Reduces where + refl A := TuringReducible.refl (oracleFunction A) + trans _ _ _ h k := TuringReducible.trans h k + +def Degree := Antisymmetrization Oracle Reduces + +instance : PartialOrder Degree := + @instPartialOrderAntisymmetrization Oracle + { le := Reduces + lt A B := Reduces A B ∧ ¬ Reduces B A + lt_iff_le_not_ge _ _ := Iff.rfl + le_refl A := TuringReducible.refl (oracleFunction A) + le_trans _ _ _ h k := TuringReducible.trans h k } + +private instance oraclePreorder : Preorder Oracle where + le := Reduces + lt A B := Reduces A B ∧ ¬ Reduces B A + lt_iff_le_not_ge _ _ := Iff.rfl + le_refl A := TuringReducible.refl (oracleFunction A) + le_trans _ _ _ h k := TuringReducible.trans h k + +def MainTheorem : Prop := ∀ π : Degree ≃o Degree, ∀ a : Degree, π a = a + +namespace ManuscriptMain + +theorem rigidity : MainTheorem := by + sorry + +end ManuscriptMain +end TuringRigidity + +end OAI diff --git a/tasks/degree-rigidity/tests/grade.py b/tasks/degree-rigidity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/degree-rigidity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/degree-rigidity/tests/task.json b/tasks/degree-rigidity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..21c5c3f28be02a5ede849139a5fc4f5317a2f141 --- /dev/null +++ b/tasks/degree-rigidity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DegreeRigidity", + "comparator": { + "theorem_names": [ + "OAI.TuringRigidity.ManuscriptMain.rigidity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14330 +} \ No newline at end of file diff --git a/tasks/degree-rigidity/tests/test.sh b/tasks/degree-rigidity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/degree-rigidity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/deligne-drinfeld/environment/Dockerfile b/tasks/deligne-drinfeld/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/deligne-drinfeld/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/deligne-drinfeld/environment/fetch_mathlib.sh b/tasks/deligne-drinfeld/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/deligne-drinfeld/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/deligne-drinfeld/environment/lake-manifest.json b/tasks/deligne-drinfeld/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/deligne-drinfeld/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/deligne-drinfeld/environment/lakefile.lean b/tasks/deligne-drinfeld/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/deligne-drinfeld/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/deligne-drinfeld/environment/lean_setup.sh b/tasks/deligne-drinfeld/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/deligne-drinfeld/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/deligne-drinfeld/environment/pack_submission.py b/tasks/deligne-drinfeld/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/deligne-drinfeld/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/deligne-drinfeld/instruction.md b/tasks/deligne-drinfeld/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..37f3425b7158a67481c206b84942dc6439dc16ec --- /dev/null +++ b/tasks/deligne-drinfeld/instruction.md @@ -0,0 +1,246 @@ +# openai/math challenge `DeligneDrinfeld` (family 008) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 008 of the release, *The Deligne–Drinfeld conjecture* +(Number theory). The family as a whole: Proves that the rational Grothendieck–Teichmuller Lie algebra, with the Ihara bracket, is freely generated by one element in each odd weight $3,5,7,\ldots$, resolving the Deligne–Drinfeld conjecture. + +The challenge is `DeligneDrinfeld`, also at `/opt/openai-math/challenges/DeligneDrinfeld.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace DeligneDrinfeld + +abbrev L := FreeLieAlgebra ℚ Bool +def x : L := FreeLieAlgebra.of ℚ false +def y : L := FreeLieAlgebra.of ℚ true + +def eval {M : Type*} [LieRing M] [LieAlgebra ℚ M] (a b : M) : L →ₗ⁅ℚ⁆ M := + FreeLieAlgebra.lift ℚ (fun i => if i then b else a) + +abbrev Edge := {p : Fin 4 × Fin 4 // p.1 < p.2} +abbrev BraidFree := FreeLieAlgebra ℚ Edge + +def chord (i j : Fin 4) : BraidFree := + if h : i < j then FreeLieAlgebra.of ℚ ⟨(i, j), h⟩ + else if h : j < i then FreeLieAlgebra.of ℚ ⟨(j, i), h⟩ else 0 + +def braidRelations : Set BraidFree := + {z | (∃ i j k l : Fin 4, + i ≠ j ∧ i ≠ k ∧ i ≠ l ∧ j ≠ k ∧ j ≠ l ∧ k ≠ l ∧ + z = ⁅chord i j, chord k l⁆) ∨ + (∃ i j k : Fin 4, i ≠ j ∧ i ≠ k ∧ j ≠ k ∧ + z = ⁅chord i j, chord i k + chord j k⁆)} + +def braidIdeal : LieIdeal ℚ BraidFree := + LieSubmodule.lieSpan ℚ BraidFree braidRelations + +abbrev T4 := BraidFree ⧸ braidIdeal +def t (i j : Fin 4) : T4 := LieSubmodule.Quotient.mk (chord i j) + +def IsSolution (p : L) : Prop := + p + eval y x p = 0 ∧ + p + eval y (-x-y) p + eval (-x-y) x p = 0 ∧ + eval (t 0 1) (t 1 2 + t 1 3) p + eval (t 0 2 + t 1 2) (t 2 3) p = + eval (t 1 2) (t 2 3) p + eval (t 0 1 + t 0 2) (t 1 3 + t 2 3) p + + eval (t 0 1) (t 1 2) p + +def W : Submodule ℚ L where + carrier := {p | IsSolution p} + zero_mem' := by simp [IsSolution] + add_mem' := by + intro p q hp hq + rcases hp with ⟨hp1, hp2, hp3⟩ + rcases hq with ⟨hq1, hq2, hq3⟩ + refine ⟨?_, ?_, ?_⟩ + · simp only [map_add] + calc + _ = (p + eval y x p) + (q + eval y x q) := by abel + _ = 0 := by rw [hp1, hq1, add_zero] + · simp only [map_add] + calc + _ = (p + eval y (-x-y) p + eval (-x-y) x p) + + (q + eval y (-x-y) q + eval (-x-y) x q) := by abel + _ = 0 := by rw [hp2, hq2, add_zero] + · simp only [map_add] + calc + _ = (eval (t 0 1) (t 1 2 + t 1 3) p + eval (t 0 2 + t 1 2) (t 2 3) p) + + (eval (t 0 1) (t 1 2 + t 1 3) q + eval (t 0 2 + t 1 2) (t 2 3) q) := by abel + _ = _ := by rw [hp3, hq3]; abel + smul_mem' := by + intro a p hp + rcases hp with ⟨hp1, hp2, hp3⟩ + change IsSolution (a • p) + simp only [IsSolution, map_smul] + constructor + · simpa only [smul_add, smul_zero] using congrArg (a • ·) hp1 + constructor + · simpa only [smul_add, smul_zero] using congrArg (a • ·) hp2 + · simpa only [smul_add] using congrArg (a • ·) hp3 + +structure Tangent where + base : L + velocity : L + +def Tangent.equiv : Tangent ≃ L × L where + toFun z := (z.base, z.velocity) + invFun z := ⟨z.1, z.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +instance : AddCommGroup Tangent := Tangent.equiv.addCommGroup +instance : Module ℚ Tangent := Tangent.equiv.addEquiv.module ℚ +instance : Bracket Tangent Tangent := + ⟨fun a b => ⟨⁅a.base, b.base⁆, + ⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆⟩⟩ + +instance : LieRing Tangent where + add_lie a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact add_lie a.base b.base c.base + · change ⁅a.velocity + b.velocity, c.base⁆ + ⁅a.base + b.base, c.velocity⁆ = + (⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆) + + (⁅b.velocity, c.base⁆ + ⁅b.base, c.velocity⁆) + simp only [add_lie] + abel + lie_add a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_add a.base b.base c.base + · change ⁅a.velocity, b.base + c.base⁆ + ⁅a.base, b.velocity + c.velocity⁆ = + (⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆) + + (⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆) + simp only [lie_add] + abel + lie_self a := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_self a.base + · change ⁅a.velocity, a.base⁆ + ⁅a.base, a.velocity⁆ = 0 + rw [← lie_skew a.velocity a.base] + exact neg_add_cancel _ + leibniz_lie a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact leibniz_lie a.base b.base c.base + · change ⁅a.velocity, ⁅b.base, c.base⁆⁆ + + ⁅a.base, ⁅b.velocity, c.base⁆ + ⁅b.base, c.velocity⁆⁆ = + (⁅⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆, c.base⁆ + + ⁅⁅a.base, b.base⁆, c.velocity⁆) + + (⁅b.velocity, ⁅a.base, c.base⁆⁆ + + ⁅b.base, ⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆⁆) + simp only [lie_add, add_lie, lie_lie] + abel + +instance : LieAlgebra ℚ Tangent where + lie_smul scalar left right := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_smul scalar left.base right.base + · change ⁅left.velocity, scalar • right.base⁆ + ⁅left.base, scalar • right.velocity⁆ = + scalar • (⁅left.velocity, right.base⁆ + ⁅left.base, right.velocity⁆) + simp only [lie_smul, smul_add] + +def tangentLift (p : L) : L →ₗ⁅ℚ⁆ Tangent := + FreeLieAlgebra.lift ℚ (fun i => if i then ⟨y, ⁅y,p⁆⟩ else ⟨x, 0⟩) + +def D (p q : L) : L := (tangentLift p q).velocity + +def ihara (p q : L) : L := D p q - D q p + ⁅p,q⁆ + +inductive WeightedWord {α : Type*} (wt : α → ℕ) : ℕ → FreeLieAlgebra ℚ α → Prop + | generator (a : α) : WeightedWord wt (wt a) (FreeLieAlgebra.of ℚ a) + | bracket {n m a b} : WeightedWord wt n a → WeightedWord wt m b → + WeightedWord wt (n+m) ⁅a,b⁆ + +def weightPiece {α : Type*} (wt : α → ℕ) (n : ℕ) : Submodule ℚ (FreeLieAlgebra ℚ α) := + Submodule.span ℚ {p | WeightedWord wt n p} + +abbrev OddFree := FreeLieAlgebra ℚ ℕ +def oddWeight (k : ℕ) : ℕ := 2*k+3 +abbrev Fn (n : ℕ) := weightPiece oddWeight n +abbrev Ln (n : ℕ) := weightPiece (fun _ : Bool => 1) n +abbrev Wn (n : ℕ) : Submodule ℚ L := W ⊓ Ln n + +def Graded (e : OddFree ≃ₗ[ℚ] W) : Prop := + ∀ n a, (e a : L) ∈ Ln n ↔ a ∈ Fn n + +abbrev OddCompletion := (n : ℕ) → Fn n +abbrev WCompletion := (n : ℕ) → Wn n + +instance : TopologicalSpace L := ⊥ +instance : TopologicalSpace OddFree := ⊥ + +def completed (e : OddFree ≃ₗ[ℚ] W) (h : Graded e) : OddCompletion → WCompletion := + fun a n => ⟨e (a n), (e (a n)).property, (h n (a n)).2 (a n).property⟩ + +def completedInv (e : OddFree ≃ₗ[ℚ] W) (h : Graded e) : WCompletion → OddCompletion := + fun a n => ⟨e.symm ⟨a n, (a n).property.1⟩, + (h n (e.symm ⟨a n, (a n).property.1⟩)).1 (by + rw [LinearEquiv.apply_symm_apply] + exact (a n).property.2)⟩ + +def MainStatement : Prop := + ∃ (e : OddFree ≃ₗ[ℚ] W) (h : Graded e), + (∀ a b, (e ⁅a,b⁆ : L) = ihara (e a) (e b)) ∧ + Function.LeftInverse (completedInv e h) (completed e h) ∧ + Function.RightInverse (completedInv e h) (completed e h) ∧ + Continuous (completed e h) ∧ Continuous (completedInv e h) ∧ + (∀ (a b : OddCompletion) n, + (e (∑ i ∈ Finset.range (n+1), ⁅(a i : OddFree), (b (n-i) : OddFree)⁆) : L) = + ∑ i ∈ Finset.range (n+1), + ihara (completed e h a i) (completed e h b (n-i))) + +theorem main : MainStatement := by + sorry + +end DeligneDrinfeld +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DeligneDrinfeld.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DeligneDrinfeld.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/deligne-drinfeld/solution/closure.txt b/tasks/deligne-drinfeld/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..97982a08414a411f0235051d27d5a2c9b0fa64da --- /dev/null +++ b/tasks/deligne-drinfeld/solution/closure.txt @@ -0,0 +1,21 @@ +OAI.Algebra.Drinfeld.Boundary +OAI.Algebra.Drinfeld.BraidExp +OAI.Algebra.Drinfeld.Categories +OAI.Algebra.Drinfeld.Coefficients +OAI.Algebra.Drinfeld.Completion +OAI.Algebra.Drinfeld.Descent +OAI.Algebra.Drinfeld.Flatness +OAI.Algebra.Drinfeld.Foundations +OAI.Algebra.Drinfeld.Grading +OAI.Algebra.Drinfeld.Hexagon +OAI.Algebra.Drinfeld.Holonomy +OAI.Algebra.Drinfeld.Ihara +OAI.Algebra.Drinfeld.KZTransport +OAI.Algebra.Drinfeld.Lattice +OAI.Algebra.Drinfeld.Logarithm +OAI.Algebra.Drinfeld.Ordering +OAI.Algebra.Drinfeld.Pentagon +OAI.Algebra.Drinfeld.RealBraid +OAI.Algebra.Drinfeld.RealLie +OAI.Algebra.Drinfeld.Reduction +OAI.Algebra.Drinfeld.Transport diff --git a/tasks/deligne-drinfeld/solution/reference.py b/tasks/deligne-drinfeld/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/deligne-drinfeld/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/deligne-drinfeld/solution/solve.sh b/tasks/deligne-drinfeld/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d6be0036b6d415728cedb43e2642f1071fa08ead --- /dev/null +++ b/tasks/deligne-drinfeld/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DeligneDrinfeld, i.e. module OAI.Algebra.Drinfeld.Completion and the +# 21 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.Drinfeld.Completion /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DeligneDrinfeld" diff --git a/tasks/deligne-drinfeld/task.toml b/tasks/deligne-drinfeld/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1b2730fd1307bdc84403b8310097c13dc3cf7b8d --- /dev/null +++ b/tasks/deligne-drinfeld/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/deligne-drinfeld" +version = "1.0.0" +description = "Prove DeligneDrinfeld (openai/math family 008: The Deligne–Drinfeld conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DeligneDrinfeld.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DeligneDrinfeld" +family = "008" +family_title = "The Deligne–Drinfeld conjecture" +subject = "Number theory" +theorems = ["OAI.DeligneDrinfeld.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.Drinfeld.Completion" +reference_modules = 21 +reference_lean_bytes = 1357966 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 921 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12922 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/deligne-drinfeld/tests/Challenge.lean b/tasks/deligne-drinfeld/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..35b7ac31d724c1b5383d30513443ecabda05e53c --- /dev/null +++ b/tasks/deligne-drinfeld/tests/Challenge.lean @@ -0,0 +1,195 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace DeligneDrinfeld + +abbrev L := FreeLieAlgebra ℚ Bool +def x : L := FreeLieAlgebra.of ℚ false +def y : L := FreeLieAlgebra.of ℚ true + +def eval {M : Type*} [LieRing M] [LieAlgebra ℚ M] (a b : M) : L →ₗ⁅ℚ⁆ M := + FreeLieAlgebra.lift ℚ (fun i => if i then b else a) + +abbrev Edge := {p : Fin 4 × Fin 4 // p.1 < p.2} +abbrev BraidFree := FreeLieAlgebra ℚ Edge + +def chord (i j : Fin 4) : BraidFree := + if h : i < j then FreeLieAlgebra.of ℚ ⟨(i, j), h⟩ + else if h : j < i then FreeLieAlgebra.of ℚ ⟨(j, i), h⟩ else 0 + +def braidRelations : Set BraidFree := + {z | (∃ i j k l : Fin 4, + i ≠ j ∧ i ≠ k ∧ i ≠ l ∧ j ≠ k ∧ j ≠ l ∧ k ≠ l ∧ + z = ⁅chord i j, chord k l⁆) ∨ + (∃ i j k : Fin 4, i ≠ j ∧ i ≠ k ∧ j ≠ k ∧ + z = ⁅chord i j, chord i k + chord j k⁆)} + +def braidIdeal : LieIdeal ℚ BraidFree := + LieSubmodule.lieSpan ℚ BraidFree braidRelations + +abbrev T4 := BraidFree ⧸ braidIdeal +def t (i j : Fin 4) : T4 := LieSubmodule.Quotient.mk (chord i j) + +def IsSolution (p : L) : Prop := + p + eval y x p = 0 ∧ + p + eval y (-x-y) p + eval (-x-y) x p = 0 ∧ + eval (t 0 1) (t 1 2 + t 1 3) p + eval (t 0 2 + t 1 2) (t 2 3) p = + eval (t 1 2) (t 2 3) p + eval (t 0 1 + t 0 2) (t 1 3 + t 2 3) p + + eval (t 0 1) (t 1 2) p + +def W : Submodule ℚ L where + carrier := {p | IsSolution p} + zero_mem' := by simp [IsSolution] + add_mem' := by + intro p q hp hq + rcases hp with ⟨hp1, hp2, hp3⟩ + rcases hq with ⟨hq1, hq2, hq3⟩ + refine ⟨?_, ?_, ?_⟩ + · simp only [map_add] + calc + _ = (p + eval y x p) + (q + eval y x q) := by abel + _ = 0 := by rw [hp1, hq1, add_zero] + · simp only [map_add] + calc + _ = (p + eval y (-x-y) p + eval (-x-y) x p) + + (q + eval y (-x-y) q + eval (-x-y) x q) := by abel + _ = 0 := by rw [hp2, hq2, add_zero] + · simp only [map_add] + calc + _ = (eval (t 0 1) (t 1 2 + t 1 3) p + eval (t 0 2 + t 1 2) (t 2 3) p) + + (eval (t 0 1) (t 1 2 + t 1 3) q + eval (t 0 2 + t 1 2) (t 2 3) q) := by abel + _ = _ := by rw [hp3, hq3]; abel + smul_mem' := by + intro a p hp + rcases hp with ⟨hp1, hp2, hp3⟩ + change IsSolution (a • p) + simp only [IsSolution, map_smul] + constructor + · simpa only [smul_add, smul_zero] using congrArg (a • ·) hp1 + constructor + · simpa only [smul_add, smul_zero] using congrArg (a • ·) hp2 + · simpa only [smul_add] using congrArg (a • ·) hp3 + +structure Tangent where + base : L + velocity : L + +def Tangent.equiv : Tangent ≃ L × L where + toFun z := (z.base, z.velocity) + invFun z := ⟨z.1, z.2⟩ + left_inv _ := rfl + right_inv _ := rfl + +instance : AddCommGroup Tangent := Tangent.equiv.addCommGroup +instance : Module ℚ Tangent := Tangent.equiv.addEquiv.module ℚ +instance : Bracket Tangent Tangent := + ⟨fun a b => ⟨⁅a.base, b.base⁆, + ⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆⟩⟩ + +instance : LieRing Tangent where + add_lie a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact add_lie a.base b.base c.base + · change ⁅a.velocity + b.velocity, c.base⁆ + ⁅a.base + b.base, c.velocity⁆ = + (⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆) + + (⁅b.velocity, c.base⁆ + ⁅b.base, c.velocity⁆) + simp only [add_lie] + abel + lie_add a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_add a.base b.base c.base + · change ⁅a.velocity, b.base + c.base⁆ + ⁅a.base, b.velocity + c.velocity⁆ = + (⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆) + + (⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆) + simp only [lie_add] + abel + lie_self a := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_self a.base + · change ⁅a.velocity, a.base⁆ + ⁅a.base, a.velocity⁆ = 0 + rw [← lie_skew a.velocity a.base] + exact neg_add_cancel _ + leibniz_lie a b c := by + apply Tangent.equiv.injective + apply Prod.ext + · exact leibniz_lie a.base b.base c.base + · change ⁅a.velocity, ⁅b.base, c.base⁆⁆ + + ⁅a.base, ⁅b.velocity, c.base⁆ + ⁅b.base, c.velocity⁆⁆ = + (⁅⁅a.velocity, b.base⁆ + ⁅a.base, b.velocity⁆, c.base⁆ + + ⁅⁅a.base, b.base⁆, c.velocity⁆) + + (⁅b.velocity, ⁅a.base, c.base⁆⁆ + + ⁅b.base, ⁅a.velocity, c.base⁆ + ⁅a.base, c.velocity⁆⁆) + simp only [lie_add, add_lie, lie_lie] + abel + +instance : LieAlgebra ℚ Tangent where + lie_smul scalar left right := by + apply Tangent.equiv.injective + apply Prod.ext + · exact lie_smul scalar left.base right.base + · change ⁅left.velocity, scalar • right.base⁆ + ⁅left.base, scalar • right.velocity⁆ = + scalar • (⁅left.velocity, right.base⁆ + ⁅left.base, right.velocity⁆) + simp only [lie_smul, smul_add] + +def tangentLift (p : L) : L →ₗ⁅ℚ⁆ Tangent := + FreeLieAlgebra.lift ℚ (fun i => if i then ⟨y, ⁅y,p⁆⟩ else ⟨x, 0⟩) + +def D (p q : L) : L := (tangentLift p q).velocity + +def ihara (p q : L) : L := D p q - D q p + ⁅p,q⁆ + +inductive WeightedWord {α : Type*} (wt : α → ℕ) : ℕ → FreeLieAlgebra ℚ α → Prop + | generator (a : α) : WeightedWord wt (wt a) (FreeLieAlgebra.of ℚ a) + | bracket {n m a b} : WeightedWord wt n a → WeightedWord wt m b → + WeightedWord wt (n+m) ⁅a,b⁆ + +def weightPiece {α : Type*} (wt : α → ℕ) (n : ℕ) : Submodule ℚ (FreeLieAlgebra ℚ α) := + Submodule.span ℚ {p | WeightedWord wt n p} + +abbrev OddFree := FreeLieAlgebra ℚ ℕ +def oddWeight (k : ℕ) : ℕ := 2*k+3 +abbrev Fn (n : ℕ) := weightPiece oddWeight n +abbrev Ln (n : ℕ) := weightPiece (fun _ : Bool => 1) n +abbrev Wn (n : ℕ) : Submodule ℚ L := W ⊓ Ln n + +def Graded (e : OddFree ≃ₗ[ℚ] W) : Prop := + ∀ n a, (e a : L) ∈ Ln n ↔ a ∈ Fn n + +abbrev OddCompletion := (n : ℕ) → Fn n +abbrev WCompletion := (n : ℕ) → Wn n + +instance : TopologicalSpace L := ⊥ +instance : TopologicalSpace OddFree := ⊥ + +def completed (e : OddFree ≃ₗ[ℚ] W) (h : Graded e) : OddCompletion → WCompletion := + fun a n => ⟨e (a n), (e (a n)).property, (h n (a n)).2 (a n).property⟩ + +def completedInv (e : OddFree ≃ₗ[ℚ] W) (h : Graded e) : WCompletion → OddCompletion := + fun a n => ⟨e.symm ⟨a n, (a n).property.1⟩, + (h n (e.symm ⟨a n, (a n).property.1⟩)).1 (by + rw [LinearEquiv.apply_symm_apply] + exact (a n).property.2)⟩ + +def MainStatement : Prop := + ∃ (e : OddFree ≃ₗ[ℚ] W) (h : Graded e), + (∀ a b, (e ⁅a,b⁆ : L) = ihara (e a) (e b)) ∧ + Function.LeftInverse (completedInv e h) (completed e h) ∧ + Function.RightInverse (completedInv e h) (completed e h) ∧ + Continuous (completed e h) ∧ Continuous (completedInv e h) ∧ + (∀ (a b : OddCompletion) n, + (e (∑ i ∈ Finset.range (n+1), ⁅(a i : OddFree), (b (n-i) : OddFree)⁆) : L) = + ∑ i ∈ Finset.range (n+1), + ihara (completed e h a i) (completed e h b (n-i))) + +theorem main : MainStatement := by + sorry + +end DeligneDrinfeld +end + +end OAI diff --git a/tasks/deligne-drinfeld/tests/grade.py b/tasks/deligne-drinfeld/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/deligne-drinfeld/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/deligne-drinfeld/tests/task.json b/tasks/deligne-drinfeld/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9d78b5537a482d7974cc459566df13e5ade66497 --- /dev/null +++ b/tasks/deligne-drinfeld/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DeligneDrinfeld", + "comparator": { + "theorem_names": [ + "OAI.DeligneDrinfeld.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12022 +} \ No newline at end of file diff --git a/tasks/deligne-drinfeld/tests/test.sh b/tasks/deligne-drinfeld/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/deligne-drinfeld/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/depth-five/environment/Dockerfile b/tasks/depth-five/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/depth-five/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/depth-five/environment/fetch_mathlib.sh b/tasks/depth-five/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/depth-five/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/depth-five/environment/lake-manifest.json b/tasks/depth-five/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/depth-five/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/depth-five/environment/lakefile.lean b/tasks/depth-five/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/depth-five/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/depth-five/environment/lean_setup.sh b/tasks/depth-five/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/depth-five/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/depth-five/environment/pack_submission.py b/tasks/depth-five/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/depth-five/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/depth-five/instruction.md b/tasks/depth-five/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..789d9bda3d72a5ecd13fa97865c3cf2d5ed4cc08 --- /dev/null +++ b/tasks/depth-five/instruction.md @@ -0,0 +1,187 @@ +# openai/math challenge `DepthFive` (family 135) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 135 of the release, *Sharp homogeneous depth-five complexity of matrix products* +(Theoretical computer science). The family as a whole: Over every characteristic-zero field, the $(1,1)$ entry of a product of $n$ independent $n\times n$ variable matrices requires $n^{\Theta(\sqrt n)}$ gates in homogeneous depth-five sum–product circuits. This sharp bound allows shared gates and bottom linear forms involving all variables. + +The challenge is `DepthFive`, also at `/opt/openai-math/challenges/DepthFive.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u + +namespace Problem335 + +inductive D5Leaf (K : Type u) (n : ℕ) where + | scalar : K → D5Leaf K n + | variable : (Fin n × Fin n × Fin n) → D5Leaf K n + +def d5LeafDegree {K : Type u} {n : ℕ} : D5Leaf K n → ℕ + | D5Leaf.scalar _ => 0 + | D5Leaf.variable _ => 1 + +structure Depth5Circuit (K : Type u) [CommSemiring K] (n : ℕ) where + leafCount : ℕ + leaves : Fin leafCount → D5Leaf K n + bottomCount : ℕ + bottomInputs : Fin bottomCount → List (K × Fin leafCount) + bottomDegree : Fin bottomCount → ℕ + bottomHomogeneous : + ∀ i entry, entry ∈ bottomInputs i → d5LeafDegree (leaves entry.2) = bottomDegree i + bottomEmpty : + ∀ i, bottomInputs i = [] → bottomDegree i = 0 + lowerCount : ℕ + lowerInputs : Fin lowerCount → List (Fin bottomCount) + middleCount : ℕ + middleInputs : Fin middleCount → List (K × Fin lowerCount) + middleDegree : Fin middleCount → ℕ + middleHomogeneous : + ∀ i entry, entry ∈ middleInputs i → + ((lowerInputs entry.2).map bottomDegree).sum = middleDegree i + middleEmpty : + ∀ i, middleInputs i = [] → middleDegree i = 0 + upperCount : ℕ + upperInputs : Fin upperCount → List (Fin middleCount) + outputInputs : List (K × Fin upperCount) + outputDegree : ℕ + outputHomogeneous : + ∀ entry, entry ∈ outputInputs → + ((upperInputs entry.2).map middleDegree).sum = outputDegree + outputEmpty : + outputInputs = [] → outputDegree = 0 + +def d5LeafValue {K : Type u} [CommSemiring K] {n : ℕ} + (x : D5Leaf K n) : MvPolynomial (Fin n × Fin n × Fin n) K := + match x with + | D5Leaf.scalar a => MvPolynomial.C a + | D5Leaf.variable i => MvPolynomial.X i + +def bottomValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.bottomCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.bottomInputs i).map (fun entry => + MvPolynomial.C entry.1 * d5LeafValue (c.leaves entry.2))).sum + +def lowerValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.lowerCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.lowerInputs i).map (fun j => bottomValue c j)).prod + +def middleValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.middleCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.middleInputs i).map (fun entry => + MvPolynomial.C entry.1 * lowerValue c entry.2)).sum + +def upperValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.upperCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.upperInputs i).map (fun j => middleValue c j)).prod + +def circuitValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) : MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact (c.outputInputs.map (fun entry => + MvPolynomial.C entry.1 * upperValue c entry.2)).sum + +def circuitSize {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) : ℕ := + c.leafCount + c.bottomCount + c.lowerCount + c.middleCount + c.upperCount + 1 + +def immLayer (K : Type u) [CommSemiring K] (n : ℕ) (t : Fin n) : + Matrix (Fin n) (Fin n) (MvPolynomial (Fin n × Fin n × Fin n) K) := + fun i j => MvPolynomial.X (t, i, j) + +def imm (K : Type u) [CommSemiring K] (n : ℕ) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + by_cases h : 0 < n + · let matrices : + List (Matrix (Fin n) (Fin n) + (MvPolynomial (Fin n × Fin n × Fin n) K)) := + List.ofFn (fun t : Fin n => immLayer K n t) + exact matrices.prod ⟨0, h⟩ ⟨0, h⟩ + · exact 0 + +def ceilSqrt (n : ℕ) : ℕ := + Nat.sqrt n + if (Nat.sqrt n) ^ 2 = n then 0 else 1 + +def ceilDiv (n t : ℕ) : ℕ := + (n + t - 1) / t + +def upperGateBound (n : ℕ) : ℕ := + let t := ceilSqrt n + let r := ceilDiv n t + 2 * n ^ 3 + r * n ^ 2 + r * n ^ (t + 1) + n ^ (r - 1) + 1 + +theorem main : + (∃ threshold : ℕ, ∀ size : ℕ, threshold ≤ size → + ∀ circuit : Depth5Circuit ℂ size, circuitValue circuit = imm ℂ size → + (size : ℝ) ^ (Real.sqrt (size : ℝ) / 400) ≤ (circuitSize circuit : ℝ)) ∧ + (∃ threshold : ℕ, ∀ (FieldType : Type u) [Field FieldType] [CharZero FieldType], + ∀ size : ℕ, threshold ≤ size → ∀ circuit : Depth5Circuit FieldType size, + circuitValue circuit = imm FieldType size → + (size : ℝ) ^ (Real.sqrt (size : ℝ) / 400) ≤ (circuitSize circuit : ℝ)) ∧ + (∀ (FieldType : Type u) [Field FieldType] (size : ℕ), 2 ≤ size → + ∃ circuit : Depth5Circuit FieldType size, circuitValue circuit = imm FieldType size ∧ + circuitSize circuit ≤ upperGateBound size ∧ + (upperGateBound size : ℝ) ≤ (size : ℝ) ^ (Real.sqrt (size : ℝ) + 4)) := by + sorry + +end Problem335 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DepthFive.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem335.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/depth-five/solution/closure.txt b/tasks/depth-five/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..69b2b76779134770c645b3f154b53929d8b3c62d --- /dev/null +++ b/tasks/depth-five/solution/closure.txt @@ -0,0 +1,164 @@ +OAI.Algebra.DepthFive.ActualBalancedWordSum +OAI.Algebra.DepthFive.ActualCircuitRank +OAI.Algebra.DepthFive.ActualImmRank +OAI.Algebra.DepthFive.ActualProductRank +OAI.Algebra.DepthFive.ActualRelaxedWeightBound +OAI.Algebra.DepthFive.ActualSecondMomentParameters +OAI.Algebra.DepthFive.ActualWeightParameters +OAI.Algebra.DepthFive.AlphaParameters +OAI.Algebra.DepthFive.AnalyticParameters +OAI.Algebra.DepthFive.BalancedSchedule +OAI.Algebra.DepthFive.BalancedWordSum +OAI.Algebra.DepthFive.Basic +OAI.Algebra.DepthFive.BetaRefinements +OAI.Algebra.DepthFive.Bidegree +OAI.Algebra.DepthFive.BidegreeAverages +OAI.Algebra.DepthFive.BidegreeBasis +OAI.Algebra.DepthFive.BidegreeBridge +OAI.Algebra.DepthFive.BidegreeCompositionReindex +OAI.Algebra.DepthFive.BidegreeDimension +OAI.Algebra.DepthFive.BidegreeLocalProductAverage +OAI.Algebra.DepthFive.BinomialRatios +OAI.Algebra.DepthFive.BlockCircuit +OAI.Algebra.DepthFive.BlockCircuitValue +OAI.Algebra.DepthFive.BlockMiddleSemantics +OAI.Algebra.DepthFive.BlockPartition +OAI.Algebra.DepthFive.Bounds +OAI.Algebra.DepthFive.CeilArithmetic +OAI.Algebra.DepthFive.CharacteristicZeroTransfer +OAI.Algebra.DepthFive.CircuitDegreeBounds +OAI.Algebra.DepthFive.CircuitFactorForms +OAI.Algebra.DepthFive.CircuitOutputDegree +OAI.Algebra.DepthFive.CircuitProductBound +OAI.Algebra.DepthFive.CircuitRankAssembly +OAI.Algebra.DepthFive.CircuitStructure +OAI.Algebra.DepthFive.CircuitWeightBound +OAI.Algebra.DepthFive.CoefficientDescent +OAI.Algebra.DepthFive.CoefficientMap +OAI.Algebra.DepthFive.CoefficientSupport +OAI.Algebra.DepthFive.ComplexEmbedding +OAI.Algebra.DepthFive.CompositionAntidiag +OAI.Algebra.DepthFive.ConfiguredImmSecondMoment +OAI.Algebra.DepthFive.ConfiguredRankData +OAI.Algebra.DepthFive.DegreeDiscrepancy +OAI.Algebra.DepthFive.DegreeDistances +OAI.Algebra.DepthFive.DegreeProductBounds +OAI.Algebra.DepthFive.DegreeWeight +OAI.Algebra.DepthFive.DimensionCorrection +OAI.Algebra.DepthFive.ExponentCardinality +OAI.Algebra.DepthFive.FactorialGeometricValue +OAI.Algebra.DepthFive.FactorialPositive +OAI.Algebra.DepthFive.FiniteOperator +OAI.Algebra.DepthFive.FirstOccupationMoment +OAI.Algebra.DepthFive.FirstTraceNonnegative +OAI.Algebra.DepthFive.FockBidegreeBasis +OAI.Algebra.DepthFive.FockLayerProfile +OAI.Algebra.DepthFive.FockMonomials +OAI.Algebra.DepthFive.FockPaths +OAI.Algebra.DepthFive.FourPathLocal +OAI.Algebra.DepthFive.FourPathTrace +OAI.Algebra.DepthFive.FractionRounding +OAI.Algebra.DepthFive.GateSums +OAI.Algebra.DepthFive.HighDegreeWeights +OAI.Algebra.DepthFive.Homogeneity +OAI.Algebra.DepthFive.HomogeneousSpaceDimension +OAI.Algebra.DepthFive.ImmBidegree +OAI.Algebra.DepthFive.ImmBlocks +OAI.Algebra.DepthFive.ImmCompatibleTrace +OAI.Algebra.DepthFive.ImmDegree +OAI.Algebra.DepthFive.ImmFiniteMatrix +OAI.Algebra.DepthFive.ImmFirstMomentParameters +OAI.Algebra.DepthFive.ImmFirstTrace +OAI.Algebra.DepthFive.ImmFockMatrix +OAI.Algebra.DepthFive.ImmMap +OAI.Algebra.DepthFive.ImmOperatorPaths +OAI.Algebra.DepthFive.ImmPairingCompatibility +OAI.Algebra.DepthFive.ImmPairingReindex +OAI.Algebra.DepthFive.ImmPathCompatibility +OAI.Algebra.DepthFive.ImmPathShifts +OAI.Algebra.DepthFive.ImmProfileCompatibility +OAI.Algebra.DepthFive.ImmSecondLocalBound +OAI.Algebra.DepthFive.ImmSecondMomentParameters +OAI.Algebra.DepthFive.ImmSecondTrace +OAI.Algebra.DepthFive.IndependentCoordinates +OAI.Algebra.DepthFive.IndexedCircuit +OAI.Algebra.DepthFive.IndexedCircuitValue +OAI.Algebra.DepthFive.IntermediateDimension +OAI.Algebra.DepthFive.IntermediateFactorization +OAI.Algebra.DepthFive.IsolatedFlip +OAI.Algebra.DepthFive.IsolatedWeight +OAI.Algebra.DepthFive.LayeredFourPath +OAI.Algebra.DepthFive.LocalFactorialExpansion +OAI.Algebra.DepthFive.LocalMomentPairing +OAI.Algebra.DepthFive.LocalMomentPolynomials +OAI.Algebra.DepthFive.LocalMomentWeights +OAI.Algebra.DepthFive.LocalOccupationAverage +OAI.Algebra.DepthFive.LocalProductAverage +OAI.Algebra.DepthFive.LowDegreeWeights +OAI.Algebra.DepthFive.LowerAsymptotics +OAI.Algebra.DepthFive.LowerBoundAssembly +OAI.Algebra.DepthFive.LowerParameters +OAI.Algebra.DepthFive.LowerSchedule +OAI.Algebra.DepthFive.MatrixNormalization +OAI.Algebra.DepthFive.MatrixPathPairings +OAI.Algebra.DepthFive.MatrixPathSemantics +OAI.Algebra.DepthFive.MatrixPathVertices +OAI.Algebra.DepthFive.MatrixPaths +OAI.Algebra.DepthFive.MixedOperator +OAI.Algebra.DepthFive.MixedOperatorBidegree +OAI.Algebra.DepthFive.MomentLossParameters +OAI.Algebra.DepthFive.OccupationComparison +OAI.Algebra.DepthFive.OccupationExpansion +OAI.Algebra.DepthFive.OccupationParameterBounds +OAI.Algebra.DepthFive.OccupationRatio +OAI.Algebra.DepthFive.OccupationRatioAlgebra +OAI.Algebra.DepthFive.OccupationSum +OAI.Algebra.DepthFive.OddDegreeThreshold +OAI.Algebra.DepthFive.OperatorHomogeneity +OAI.Algebra.DepthFive.OperatorRank +OAI.Algebra.DepthFive.OperatorRankBridge +OAI.Algebra.DepthFive.PairingAverageCardinality +OAI.Algebra.DepthFive.PairingNeighborCount +OAI.Algebra.DepthFive.PairingOccupationAverage +OAI.Algebra.DepthFive.PairingPartition +OAI.Algebra.DepthFive.PairingWeights +OAI.Algebra.DepthFive.Pairings +OAI.Algebra.DepthFive.ParameterBounds +OAI.Algebra.DepthFive.PathInjectivity +OAI.Algebra.DepthFive.PathMassLowerBound +OAI.Algebra.DepthFive.PathMassParameters +OAI.Algebra.DepthFive.PathOccupationGroups +OAI.Algebra.DepthFive.PathShifts +OAI.Algebra.DepthFive.PowerPerturbation +OAI.Algebra.DepthFive.ProductCost +OAI.Algebra.DepthFive.ProductNormalization +OAI.Algebra.DepthFive.ProductRank +OAI.Algebra.DepthFive.ProductRankAssembly +OAI.Algebra.DepthFive.ProductRankCanonical +OAI.Algebra.DepthFive.RankMeasure +OAI.Algebra.DepthFive.RelaxedPaths +OAI.Algebra.DepthFive.RelaxedWeightBound +OAI.Algebra.DepthFive.RelaxedWordBridge +OAI.Algebra.DepthFive.RunBlocks +OAI.Algebra.DepthFive.RunLayerWeights +OAI.Algebra.DepthFive.RunSum +OAI.Algebra.DepthFive.RunWeights +OAI.Algebra.DepthFive.ScheduleEnds +OAI.Algebra.DepthFive.ScheduleInterior +OAI.Algebra.DepthFive.ScheduleIntervals +OAI.Algebra.DepthFive.ScheduleWeightBridge +OAI.Algebra.DepthFive.SecondMomentNormalization +OAI.Algebra.DepthFive.SecondMomentPairing +OAI.Algebra.DepthFive.SmallDegreeCorrections +OAI.Algebra.DepthFive.SwitchRestoration +OAI.Algebra.DepthFive.TraceComplexification +OAI.Algebra.DepthFive.TraceExpansion +OAI.Algebra.DepthFive.TraceRank +OAI.Algebra.DepthFive.UpperBlockData +OAI.Algebra.DepthFive.UpperBoundArithmetic +OAI.Algebra.DepthFive.UpperConstruction +OAI.Algebra.DepthFive.UpperGateCounting +OAI.Algebra.DepthFive.WordRuns +OAI.Algebra.DepthFive.WordSum +OAI.Algebra.DepthFive.WordSwitches +OAI.Algebra.DepthFive.WordWeightParameters diff --git a/tasks/depth-five/solution/reference.py b/tasks/depth-five/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/depth-five/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/depth-five/solution/solve.sh b/tasks/depth-five/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d35b95a186bad0f52c7637d26a720c4a5f87605e --- /dev/null +++ b/tasks/depth-five/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DepthFive, i.e. module OAI.Algebra.DepthFive.Bounds and the +# 164 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.DepthFive.Bounds /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DepthFive" diff --git a/tasks/depth-five/task.toml b/tasks/depth-five/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4791b7e241da65cd198d1e1e533bb77779273c2a --- /dev/null +++ b/tasks/depth-five/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/depth-five" +version = "1.0.0" +description = "Prove DepthFive (openai/math family 135: Sharp homogeneous depth-five complexity of matrix products) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DepthFive.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DepthFive" +family = "135" +family_title = "Sharp homogeneous depth-five complexity of matrix products" +subject = "Theoretical computer science" +theorems = ["OAI.Problem335.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.DepthFive.Bounds" +reference_modules = 164 +reference_lean_bytes = 880264 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1051 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12492 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/depth-five/tests/Challenge.lean b/tasks/depth-five/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a286b6a56142c44c901dd3eb46e105697e7e2bdb --- /dev/null +++ b/tasks/depth-five/tests/Challenge.lean @@ -0,0 +1,136 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u + +namespace Problem335 + +inductive D5Leaf (K : Type u) (n : ℕ) where + | scalar : K → D5Leaf K n + | variable : (Fin n × Fin n × Fin n) → D5Leaf K n + +def d5LeafDegree {K : Type u} {n : ℕ} : D5Leaf K n → ℕ + | D5Leaf.scalar _ => 0 + | D5Leaf.variable _ => 1 + +structure Depth5Circuit (K : Type u) [CommSemiring K] (n : ℕ) where + leafCount : ℕ + leaves : Fin leafCount → D5Leaf K n + bottomCount : ℕ + bottomInputs : Fin bottomCount → List (K × Fin leafCount) + bottomDegree : Fin bottomCount → ℕ + bottomHomogeneous : + ∀ i entry, entry ∈ bottomInputs i → d5LeafDegree (leaves entry.2) = bottomDegree i + bottomEmpty : + ∀ i, bottomInputs i = [] → bottomDegree i = 0 + lowerCount : ℕ + lowerInputs : Fin lowerCount → List (Fin bottomCount) + middleCount : ℕ + middleInputs : Fin middleCount → List (K × Fin lowerCount) + middleDegree : Fin middleCount → ℕ + middleHomogeneous : + ∀ i entry, entry ∈ middleInputs i → + ((lowerInputs entry.2).map bottomDegree).sum = middleDegree i + middleEmpty : + ∀ i, middleInputs i = [] → middleDegree i = 0 + upperCount : ℕ + upperInputs : Fin upperCount → List (Fin middleCount) + outputInputs : List (K × Fin upperCount) + outputDegree : ℕ + outputHomogeneous : + ∀ entry, entry ∈ outputInputs → + ((upperInputs entry.2).map middleDegree).sum = outputDegree + outputEmpty : + outputInputs = [] → outputDegree = 0 + +def d5LeafValue {K : Type u} [CommSemiring K] {n : ℕ} + (x : D5Leaf K n) : MvPolynomial (Fin n × Fin n × Fin n) K := + match x with + | D5Leaf.scalar a => MvPolynomial.C a + | D5Leaf.variable i => MvPolynomial.X i + +def bottomValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.bottomCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.bottomInputs i).map (fun entry => + MvPolynomial.C entry.1 * d5LeafValue (c.leaves entry.2))).sum + +def lowerValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.lowerCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.lowerInputs i).map (fun j => bottomValue c j)).prod + +def middleValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.middleCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.middleInputs i).map (fun entry => + MvPolynomial.C entry.1 * lowerValue c entry.2)).sum + +def upperValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) (i : Fin c.upperCount) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact ((c.upperInputs i).map (fun j => middleValue c j)).prod + +def circuitValue {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) : MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + exact (c.outputInputs.map (fun entry => + MvPolynomial.C entry.1 * upperValue c entry.2)).sum + +def circuitSize {K : Type u} [CommSemiring K] {n : ℕ} + (c : Depth5Circuit K n) : ℕ := + c.leafCount + c.bottomCount + c.lowerCount + c.middleCount + c.upperCount + 1 + +def immLayer (K : Type u) [CommSemiring K] (n : ℕ) (t : Fin n) : + Matrix (Fin n) (Fin n) (MvPolynomial (Fin n × Fin n × Fin n) K) := + fun i j => MvPolynomial.X (t, i, j) + +def imm (K : Type u) [CommSemiring K] (n : ℕ) : + MvPolynomial (Fin n × Fin n × Fin n) K := by + classical + by_cases h : 0 < n + · let matrices : + List (Matrix (Fin n) (Fin n) + (MvPolynomial (Fin n × Fin n × Fin n) K)) := + List.ofFn (fun t : Fin n => immLayer K n t) + exact matrices.prod ⟨0, h⟩ ⟨0, h⟩ + · exact 0 + +def ceilSqrt (n : ℕ) : ℕ := + Nat.sqrt n + if (Nat.sqrt n) ^ 2 = n then 0 else 1 + +def ceilDiv (n t : ℕ) : ℕ := + (n + t - 1) / t + +def upperGateBound (n : ℕ) : ℕ := + let t := ceilSqrt n + let r := ceilDiv n t + 2 * n ^ 3 + r * n ^ 2 + r * n ^ (t + 1) + n ^ (r - 1) + 1 + +theorem main : + (∃ threshold : ℕ, ∀ size : ℕ, threshold ≤ size → + ∀ circuit : Depth5Circuit ℂ size, circuitValue circuit = imm ℂ size → + (size : ℝ) ^ (Real.sqrt (size : ℝ) / 400) ≤ (circuitSize circuit : ℝ)) ∧ + (∃ threshold : ℕ, ∀ (FieldType : Type u) [Field FieldType] [CharZero FieldType], + ∀ size : ℕ, threshold ≤ size → ∀ circuit : Depth5Circuit FieldType size, + circuitValue circuit = imm FieldType size → + (size : ℝ) ^ (Real.sqrt (size : ℝ) / 400) ≤ (circuitSize circuit : ℝ)) ∧ + (∀ (FieldType : Type u) [Field FieldType] (size : ℕ), 2 ≤ size → + ∃ circuit : Depth5Circuit FieldType size, circuitValue circuit = imm FieldType size ∧ + circuitSize circuit ≤ upperGateBound size ∧ + (upperGateBound size : ℝ) ≤ (size : ℝ) ^ (Real.sqrt (size : ℝ) + 4)) := by + sorry + +end Problem335 + +end + +end OAI diff --git a/tasks/depth-five/tests/grade.py b/tasks/depth-five/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/depth-five/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/depth-five/tests/task.json b/tasks/depth-five/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2a1f372660e1a7e36e3dd6b3fc9ffed76147caed --- /dev/null +++ b/tasks/depth-five/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DepthFive", + "comparator": { + "theorem_names": [ + "OAI.Problem335.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11592 +} \ No newline at end of file diff --git a/tasks/depth-five/tests/test.sh b/tasks/depth-five/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/depth-five/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/depth-three/environment/Dockerfile b/tasks/depth-three/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/depth-three/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/depth-three/environment/fetch_mathlib.sh b/tasks/depth-three/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/depth-three/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/depth-three/environment/lake-manifest.json b/tasks/depth-three/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/depth-three/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/depth-three/environment/lakefile.lean b/tasks/depth-three/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/depth-three/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/depth-three/environment/lean_setup.sh b/tasks/depth-three/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/depth-three/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/depth-three/environment/pack_submission.py b/tasks/depth-three/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/depth-three/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/depth-three/instruction.md b/tasks/depth-three/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..987350bb9566bee4a9579803e86eec92e11857f4 --- /dev/null +++ b/tasks/depth-three/instruction.md @@ -0,0 +1,195 @@ +# openai/math challenge `DepthThree` (family 112) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 112 of the release, *Beyond the square-root exponent for depth-three circuits* +(Theoretical computer science). The family as a whole: Constructs a single language in deterministic polynomial time whose $n$-bit membership function requires $2^{\omega(\sqrt n)}$ total gates in unbounded-fan-in OR–AND–OR circuits, at every sufficiently large input length. This crosses the square-root-exponent threshold for explicit depth-three Boolean circuit lower bounds. + +The challenge is `DepthThree`, also at `/opt/openai-math/challenges/DepthThree.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace DepthThreeLowerBound + +universe uV uS uK uGamma uQ + +abbrev Cube (V : Type uV) := V → Bool +abbrev Literal (V : Type uV) := V × Bool + +variable {V : Type uV} + +namespace Literal + +def eval (l : Literal V) (x : Cube V) : Bool := decide (x l.1 = l.2) + +end Literal + +abbrev GateInput (V : Type uV) := Sum (Literal V) Bool +abbrev RawClause (V : Type uV) := List (GateInput V) + +namespace GateInput + +def eval : GateInput V → Cube V → Bool + | .inl l, x => l.eval x + | .inr b, _ => b + +end GateInput + +namespace RawClause + +noncomputable def eval (C : RawClause V) (x : Cube V) : Bool := by + classical + exact decide (∃ l ∈ C, l.eval x = true) + +end RawClause + +structure Circuit3 (V : Type uV) where + bottomCount : ℕ + middleCount : ℕ + bottom : Fin bottomCount → RawClause V + middle : Fin middleCount → Finset (Fin bottomCount) + top : Finset (Fin middleCount) + +namespace Circuit3 + +def gateCount (C : Circuit3 V) : ℕ := C.bottomCount + C.middleCount + 1 + +noncomputable def middleEval (C : Circuit3 V) (j : Fin C.middleCount) + (x : Cube V) : Bool := by + classical + exact decide (∀ i ∈ C.middle j, (C.bottom i).eval x = true) + +noncomputable def eval (C : Circuit3 V) (x : Cube V) : Bool := by + classical + exact decide (∃ j ∈ C.top, C.middleEval j x = true) + +def Computes (C : Circuit3 V) (f : Cube V → Bool) : Prop := ∀ x, C.eval x = f x + +end Circuit3 + +def runSteps {S : Type uS} (step : S → Option S) (n : ℕ) (c : Option S) : Option S := + (fun oc => oc.bind step)^[n] c + +inductive HeadMove + | left + | stay + | right + +def HeadMove.apply {Γ : Type uGamma} [Inhabited Γ] : HeadMove → Turing.Tape Γ → Turing.Tape Γ + | .left, t => t.move Turing.Dir.left + | .stay, t => t + | .right, t => t.move Turing.Dir.right + +structure MultiTapeCfg (K : Type uK) (Γ : Type uGamma) (Q : Type uQ) [Inhabited Γ] where + q : Q + tapes : K → Turing.Tape Γ + +abbrev MultiTapeCode (K : Type uK) (Γ : Type uGamma) (Q : Type uQ) := + Q → (K → Γ) → Option (Q × (K → Γ) × (K → HeadMove)) + +def multiTapeUpdate {K : Type uK} {Γ : Type uGamma} {Q : Type uQ} [Inhabited Γ] (c : MultiTapeCfg K Γ Q) + (q : Q) (writes : K → Γ) (moves : K → HeadMove) : MultiTapeCfg K Γ Q := + ⟨q, fun k => (moves k).apply ((c.tapes k).write (writes k))⟩ + +def multiTapeStep {K : Type uK} {Γ : Type uGamma} {Q : Type uQ} [Inhabited Γ] (code : MultiTapeCode K Γ Q) + (c : MultiTapeCfg K Γ Q) : Option (MultiTapeCfg K Γ Q) := + (code c.q (fun k => (c.tapes k).head)).map fun out => + multiTapeUpdate c out.1 out.2.1 out.2.2 + +structure FiniteMultiTapeMachine where + K : Type + [tapeFinite : Fintype K] + [tapeDecidableEq : DecidableEq K] + inputTape : K + Γ : Type + [alphabetInhabited : Inhabited Γ] + [alphabetFinite : Fintype Γ] + Q : Type + [stateFinite : Fintype Q] + initialState : Q + inputSymbol : Bool → Γ + input_injective : Function.Injective inputSymbol + input_ne_blank : ∀ b, inputSymbol b ≠ default + code : MultiTapeCode K Γ Q + accept : Q → Bool + +attribute [instance] FiniteMultiTapeMachine.tapeFinite + FiniteMultiTapeMachine.tapeDecidableEq FiniteMultiTapeMachine.alphabetInhabited + FiniteMultiTapeMachine.alphabetFinite FiniteMultiTapeMachine.stateFinite + +namespace FiniteMultiTapeMachine + +abbrev Cfg (M : FiniteMultiTapeMachine) := MultiTapeCfg M.K M.Γ M.Q + +abbrev step (M : FiniteMultiTapeMachine) : M.Cfg → Option M.Cfg := + multiTapeStep M.code + +def init (M : FiniteMultiTapeMachine) (input : List Bool) : M.Cfg := + ⟨M.initialState, fun k => + if k = M.inputTape then Turing.Tape.mk₁ (input.map M.inputSymbol) + else Turing.Tape.mk₁ []⟩ + +end FiniteMultiTapeMachine + +def MultiTapeHaltsIn (M : FiniteMultiTapeMachine) (input : List Bool) + (output : Bool) (time : ℕ) : Prop := + ∃ k ≤ time, ∃ c : M.Cfg, + runSteps M.step k (some (M.init input)) = some c ∧ + M.step c = none ∧ M.accept c.q = output + +theorem exists_polynomial_time_language_depth_three_lower_bound : + ∃ (L : List Bool → Bool) (M : FiniteMultiTapeMachine) (C a : ℕ), + 0 < C ∧ 0 < a ∧ + (∀ w : List Bool, MultiTapeHaltsIn M w (L w) (C * (w.length + 1) ^ a)) ∧ + ∀ A : ℝ, 0 < A → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → + ∀ D : Circuit3 (Fin n), D.Computes (fun x => L (List.ofFn x)) → + (2 : ℝ) ^ (A * Real.sqrt (n : ℝ)) < (D.gateCount : ℝ) := by + sorry + +end DepthThreeLowerBound + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DepthThree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DepthThreeLowerBound.exists_polynomial_time_language_depth_three_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/depth-three/solution/closure.txt b/tasks/depth-three/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4633e2e6861f03cc3e6da9636f24190d3c02b5ab --- /dev/null +++ b/tasks/depth-three/solution/closure.txt @@ -0,0 +1,175 @@ +OAI.Computability.DepthThree.AlgebraBits +OAI.Computability.DepthThree.AlgebraFiniteFibers +OAI.Computability.DepthThree.AlgebraLanguage +OAI.Computability.DepthThree.AlgebraPolynomial +OAI.Computability.DepthThree.AlgebraQuotient +OAI.Computability.DepthThree.AsymptoticBounds +OAI.Computability.DepthThree.Circuit +OAI.Computability.DepthThree.CircuitDeletion +OAI.Computability.DepthThree.CircuitDensity +OAI.Computability.DepthThree.CircuitLowerBound +OAI.Computability.DepthThree.CircuitNormalization +OAI.Computability.DepthThree.CircuitQuantitative +OAI.Computability.DepthThree.Core +OAI.Computability.DepthThree.CorrelationTransfer +OAI.Computability.DepthThree.CylinderProbability +OAI.Computability.DepthThree.Entropy +OAI.Computability.DepthThree.EntropyBits +OAI.Computability.DepthThree.EntropyThreshold +OAI.Computability.DepthThree.FinalParameterBounds +OAI.Computability.DepthThree.FiniteProbability +OAI.Computability.DepthThree.FiniteProbabilityBounds +OAI.Computability.DepthThree.HardSlice +OAI.Computability.DepthThree.HardSliceEventual +OAI.Computability.DepthThree.HardSliceExistence +OAI.Computability.DepthThree.HardSliceMoment +OAI.Computability.DepthThree.HardSliceParameters +OAI.Computability.DepthThree.HardSliceProbability +OAI.Computability.DepthThree.HardSliceSelection +OAI.Computability.DepthThree.Hash +OAI.Computability.DepthThree.HashAffine +OAI.Computability.DepthThree.HashBool +OAI.Computability.DepthThree.HashFibers +OAI.Computability.DepthThree.HashProbability +OAI.Computability.DepthThree.HashTriangular +OAI.Computability.DepthThree.InterpolationEvaluation +OAI.Computability.DepthThree.InterpolationQuotient +OAI.Computability.DepthThree.InterpolationSigns +OAI.Computability.DepthThree.IrreducibleEncoding +OAI.Computability.DepthThree.IrreduciblePolynomial +OAI.Computability.DepthThree.Language +OAI.Computability.DepthThree.LanguageBitArithmetic +OAI.Computability.DepthThree.LanguageBitConvolution +OAI.Computability.DepthThree.LanguageBitConvolutionUpdates +OAI.Computability.DepthThree.LanguageBitEvaluator +OAI.Computability.DepthThree.LanguageBitHashUpdates +OAI.Computability.DepthThree.LanguageBitHornerLoop +OAI.Computability.DepthThree.LanguageBitLoopInvariants +OAI.Computability.DepthThree.LanguageBitReductionLoop +OAI.Computability.DepthThree.LanguageBitWord +OAI.Computability.DepthThree.LanguageInputBlockLists +OAI.Computability.DepthThree.LanguageInputBlockWords +OAI.Computability.DepthThree.LanguageLowerBound +OAI.Computability.DepthThree.LanguageParameterBounds +OAI.Computability.DepthThree.LanguageParameters +OAI.Computability.DepthThree.LanguageParser +OAI.Computability.DepthThree.LanguageSearchTests +OAI.Computability.DepthThree.LanguageSlice +OAI.Computability.DepthThree.MachineBasic +OAI.Computability.DepthThree.MachineLanguage +OAI.Computability.DepthThree.Main +OAI.Computability.DepthThree.MarkerMixture +OAI.Computability.DepthThree.MarkerPermutation +OAI.Computability.DepthThree.Model +OAI.Computability.DepthThree.MomentBounds +OAI.Computability.DepthThree.MultiTapeMachine +OAI.Computability.DepthThree.Restriction +OAI.Computability.DepthThree.RestrictionClause +OAI.Computability.DepthThree.RestrictionCorrelation +OAI.Computability.DepthThree.RestrictionCostCorrelation +OAI.Computability.DepthThree.RestrictionCountSplit +OAI.Computability.DepthThree.RestrictionCylinders +OAI.Computability.DepthThree.RestrictionEasyBase +OAI.Computability.DepthThree.RestrictionExpansion +OAI.Computability.DepthThree.RestrictionExpectedCost +OAI.Computability.DepthThree.RestrictionKeepClause +OAI.Computability.DepthThree.RestrictionMarkerCNF +OAI.Computability.DepthThree.RestrictionNormalization +OAI.Computability.DepthThree.RestrictionPathData +OAI.Computability.DepthThree.RestrictionPathMixture +OAI.Computability.DepthThree.RestrictionPathProducts +OAI.Computability.DepthThree.RestrictionPaths +OAI.Computability.DepthThree.RestrictionProbability +OAI.Computability.DepthThree.RestrictionTails +OAI.Computability.DepthThree.ReversePathEncoding +OAI.Computability.DepthThree.ReversePathRecurrence +OAI.Computability.DepthThree.ReversePathWeights +OAI.Computability.DepthThree.SparseBranch +OAI.Computability.DepthThree.SparseCorrelation +OAI.Computability.DepthThree.SparseCounting +OAI.Computability.DepthThree.SparseFiniteFamily +OAI.Computability.DepthThree.SparseLeafCNF +OAI.Computability.DepthThree.SparseLeafCount +OAI.Computability.DepthThree.SparseNormalize +OAI.Computability.DepthThree.SparsePartition +OAI.Computability.DepthThree.SparsePrefix +OAI.Computability.DepthThree.SparseStreams +OAI.Computability.DepthThree.SparseTailBounds +OAI.Computability.DepthThree.SparseTestCodes +OAI.Computability.DepthThree.SparseThresholds +OAI.Computability.DepthThree.SparseTree +OAI.Computability.DepthThree.Sunflower +OAI.Computability.DepthThree.TapeArithmetic +OAI.Computability.DepthThree.TapeArray +OAI.Computability.DepthThree.TapeBranch +OAI.Computability.DepthThree.TapeCancel +OAI.Computability.DepthThree.TapeCancelRow +OAI.Computability.DepthThree.TapeCancelStep +OAI.Computability.DepthThree.TapeConvolutionPrepare +OAI.Computability.DepthThree.TapeConvolutionRow +OAI.Computability.DepthThree.TapeConvolutionRows +OAI.Computability.DepthThree.TapeConvolutionStep +OAI.Computability.DepthThree.TapeConvolve +OAI.Computability.DepthThree.TapeCopy +OAI.Computability.DepthThree.TapeCopyAdd +OAI.Computability.DepthThree.TapeDecodeBlock +OAI.Computability.DepthThree.TapeDecodeBlocks +OAI.Computability.DepthThree.TapeDecodeParsed +OAI.Computability.DepthThree.TapeDivideFive +OAI.Computability.DepthThree.TapeEncoding +OAI.Computability.DepthThree.TapeErase +OAI.Computability.DepthThree.TapeEvaluation +OAI.Computability.DepthThree.TapeFill +OAI.Computability.DepthThree.TapeForLoop +OAI.Computability.DepthThree.TapeHash +OAI.Computability.DepthThree.TapeHashClean +OAI.Computability.DepthThree.TapeHashInitialize +OAI.Computability.DepthThree.TapeHashInner +OAI.Computability.DepthThree.TapeHashOuter +OAI.Computability.DepthThree.TapeHashRow +OAI.Computability.DepthThree.TapeHashStep +OAI.Computability.DepthThree.TapeHorner +OAI.Computability.DepthThree.TapeHornerBody +OAI.Computability.DepthThree.TapeHornerExtract +OAI.Computability.DepthThree.TapeHornerLoop +OAI.Computability.DepthThree.TapeHornerMultiply +OAI.Computability.DepthThree.TapeHornerPrepare +OAI.Computability.DepthThree.TapeHornerTake +OAI.Computability.DepthThree.TapeInitialization +OAI.Computability.DepthThree.TapeInputBlockLoop +OAI.Computability.DepthThree.TapeInputBlocks +OAI.Computability.DepthThree.TapeInputGuard +OAI.Computability.DepthThree.TapeInputGuardLength +OAI.Computability.DepthThree.TapeInputPrepare +OAI.Computability.DepthThree.TapeMultiProgram +OAI.Computability.DepthThree.TapeMultiRoutines +OAI.Computability.DepthThree.TapeMultiply +OAI.Computability.DepthThree.TapeNaturalAccess +OAI.Computability.DepthThree.TapeOutput +OAI.Computability.DepthThree.TapeParameterCost +OAI.Computability.DepthThree.TapeParameterSearch +OAI.Computability.DepthThree.TapeParameters +OAI.Computability.DepthThree.TapeParametersBound +OAI.Computability.DepthThree.TapeParse +OAI.Computability.DepthThree.TapePower +OAI.Computability.DepthThree.TapePowerCompare +OAI.Computability.DepthThree.TapePowerSearch +OAI.Computability.DepthThree.TapeProductLength +OAI.Computability.DepthThree.TapeProductTerm +OAI.Computability.DepthThree.TapeReadPush +OAI.Computability.DepthThree.TapeRemainder +OAI.Computability.DepthThree.TapeRemainderOuter +OAI.Computability.DepthThree.TapeRemainderSetup +OAI.Computability.DepthThree.TapeRewind +OAI.Computability.DepthThree.TapeRouting +OAI.Computability.DepthThree.TapeSearchBody +OAI.Computability.DepthThree.TapeStoreRepresentation +OAI.Computability.DepthThree.TapeUnary +OAI.Computability.DepthThree.TapeUnaryCompare +OAI.Computability.DepthThree.TapeUnaryCompareScan +OAI.Computability.DepthThree.TapeWord +OAI.Computability.DepthThree.TapeWordRewind +OAI.Computability.DepthThree.TapeXor +OAI.Computability.DepthThree.TupleCounting +OAI.Computability.DepthThree.UniformSparseBounds +OAI.Computability.DepthThree.WideCorrelation diff --git a/tasks/depth-three/solution/reference.py b/tasks/depth-three/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/depth-three/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/depth-three/solution/solve.sh b/tasks/depth-three/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b203b070bf5e306c30e7ecb7a7d974dcf7489225 --- /dev/null +++ b/tasks/depth-three/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DepthThree, i.e. module OAI.Computability.DepthThree.Main and the +# 175 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.DepthThree.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DepthThree" diff --git a/tasks/depth-three/task.toml b/tasks/depth-three/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..547cb324983c213c02f34ced16797b466e782a1d --- /dev/null +++ b/tasks/depth-three/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/depth-three" +version = "1.0.0" +description = "Prove DepthThree (openai/math family 112: Beyond the square-root exponent for depth-three circuits) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DepthThree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DepthThree" +family = "112" +family_title = "Beyond the square-root exponent for depth-three circuits" +subject = "Theoretical computer science" +theorems = ["OAI.DepthThreeLowerBound.exists_polynomial_time_language_depth_three_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.DepthThree.Main" +reference_modules = 175 +reference_lean_bytes = 1026594 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 776 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12623 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/depth-three/tests/Challenge.lean b/tasks/depth-three/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..64c86b980b111624f1a56e4bc8d61dfc8f02c621 --- /dev/null +++ b/tasks/depth-three/tests/Challenge.lean @@ -0,0 +1,144 @@ +import Mathlib + +namespace OAI + +namespace DepthThreeLowerBound + +universe uV uS uK uGamma uQ + +abbrev Cube (V : Type uV) := V → Bool +abbrev Literal (V : Type uV) := V × Bool + +variable {V : Type uV} + +namespace Literal + +def eval (l : Literal V) (x : Cube V) : Bool := decide (x l.1 = l.2) + +end Literal + +abbrev GateInput (V : Type uV) := Sum (Literal V) Bool +abbrev RawClause (V : Type uV) := List (GateInput V) + +namespace GateInput + +def eval : GateInput V → Cube V → Bool + | .inl l, x => l.eval x + | .inr b, _ => b + +end GateInput + +namespace RawClause + +noncomputable def eval (C : RawClause V) (x : Cube V) : Bool := by + classical + exact decide (∃ l ∈ C, l.eval x = true) + +end RawClause + +structure Circuit3 (V : Type uV) where + bottomCount : ℕ + middleCount : ℕ + bottom : Fin bottomCount → RawClause V + middle : Fin middleCount → Finset (Fin bottomCount) + top : Finset (Fin middleCount) + +namespace Circuit3 + +def gateCount (C : Circuit3 V) : ℕ := C.bottomCount + C.middleCount + 1 + +noncomputable def middleEval (C : Circuit3 V) (j : Fin C.middleCount) + (x : Cube V) : Bool := by + classical + exact decide (∀ i ∈ C.middle j, (C.bottom i).eval x = true) + +noncomputable def eval (C : Circuit3 V) (x : Cube V) : Bool := by + classical + exact decide (∃ j ∈ C.top, C.middleEval j x = true) + +def Computes (C : Circuit3 V) (f : Cube V → Bool) : Prop := ∀ x, C.eval x = f x + +end Circuit3 + +def runSteps {S : Type uS} (step : S → Option S) (n : ℕ) (c : Option S) : Option S := + (fun oc => oc.bind step)^[n] c + +inductive HeadMove + | left + | stay + | right + +def HeadMove.apply {Γ : Type uGamma} [Inhabited Γ] : HeadMove → Turing.Tape Γ → Turing.Tape Γ + | .left, t => t.move Turing.Dir.left + | .stay, t => t + | .right, t => t.move Turing.Dir.right + +structure MultiTapeCfg (K : Type uK) (Γ : Type uGamma) (Q : Type uQ) [Inhabited Γ] where + q : Q + tapes : K → Turing.Tape Γ + +abbrev MultiTapeCode (K : Type uK) (Γ : Type uGamma) (Q : Type uQ) := + Q → (K → Γ) → Option (Q × (K → Γ) × (K → HeadMove)) + +def multiTapeUpdate {K : Type uK} {Γ : Type uGamma} {Q : Type uQ} [Inhabited Γ] (c : MultiTapeCfg K Γ Q) + (q : Q) (writes : K → Γ) (moves : K → HeadMove) : MultiTapeCfg K Γ Q := + ⟨q, fun k => (moves k).apply ((c.tapes k).write (writes k))⟩ + +def multiTapeStep {K : Type uK} {Γ : Type uGamma} {Q : Type uQ} [Inhabited Γ] (code : MultiTapeCode K Γ Q) + (c : MultiTapeCfg K Γ Q) : Option (MultiTapeCfg K Γ Q) := + (code c.q (fun k => (c.tapes k).head)).map fun out => + multiTapeUpdate c out.1 out.2.1 out.2.2 + +structure FiniteMultiTapeMachine where + K : Type + [tapeFinite : Fintype K] + [tapeDecidableEq : DecidableEq K] + inputTape : K + Γ : Type + [alphabetInhabited : Inhabited Γ] + [alphabetFinite : Fintype Γ] + Q : Type + [stateFinite : Fintype Q] + initialState : Q + inputSymbol : Bool → Γ + input_injective : Function.Injective inputSymbol + input_ne_blank : ∀ b, inputSymbol b ≠ default + code : MultiTapeCode K Γ Q + accept : Q → Bool + +attribute [instance] FiniteMultiTapeMachine.tapeFinite + FiniteMultiTapeMachine.tapeDecidableEq FiniteMultiTapeMachine.alphabetInhabited + FiniteMultiTapeMachine.alphabetFinite FiniteMultiTapeMachine.stateFinite + +namespace FiniteMultiTapeMachine + +abbrev Cfg (M : FiniteMultiTapeMachine) := MultiTapeCfg M.K M.Γ M.Q + +abbrev step (M : FiniteMultiTapeMachine) : M.Cfg → Option M.Cfg := + multiTapeStep M.code + +def init (M : FiniteMultiTapeMachine) (input : List Bool) : M.Cfg := + ⟨M.initialState, fun k => + if k = M.inputTape then Turing.Tape.mk₁ (input.map M.inputSymbol) + else Turing.Tape.mk₁ []⟩ + +end FiniteMultiTapeMachine + +def MultiTapeHaltsIn (M : FiniteMultiTapeMachine) (input : List Bool) + (output : Bool) (time : ℕ) : Prop := + ∃ k ≤ time, ∃ c : M.Cfg, + runSteps M.step k (some (M.init input)) = some c ∧ + M.step c = none ∧ M.accept c.q = output + +theorem exists_polynomial_time_language_depth_three_lower_bound : + ∃ (L : List Bool → Bool) (M : FiniteMultiTapeMachine) (C a : ℕ), + 0 < C ∧ 0 < a ∧ + (∀ w : List Bool, MultiTapeHaltsIn M w (L w) (C * (w.length + 1) ^ a)) ∧ + ∀ A : ℝ, 0 < A → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → + ∀ D : Circuit3 (Fin n), D.Computes (fun x => L (List.ofFn x)) → + (2 : ℝ) ^ (A * Real.sqrt (n : ℝ)) < (D.gateCount : ℝ) := by + sorry + +end DepthThreeLowerBound + +end OAI diff --git a/tasks/depth-three/tests/grade.py b/tasks/depth-three/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/depth-three/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/depth-three/tests/task.json b/tasks/depth-three/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e8bb2a8e2fbda64f758df290ce7f5a033c258f87 --- /dev/null +++ b/tasks/depth-three/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DepthThree", + "comparator": { + "theorem_names": [ + "OAI.DepthThreeLowerBound.exists_polynomial_time_language_depth_three_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11723 +} \ No newline at end of file diff --git a/tasks/depth-three/tests/test.sh b/tasks/depth-three/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/depth-three/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/diamond-distortion/environment/Dockerfile b/tasks/diamond-distortion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/diamond-distortion/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/diamond-distortion/environment/fetch_mathlib.sh b/tasks/diamond-distortion/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/diamond-distortion/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/diamond-distortion/environment/lake-manifest.json b/tasks/diamond-distortion/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/diamond-distortion/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/diamond-distortion/environment/lakefile.lean b/tasks/diamond-distortion/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/diamond-distortion/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/diamond-distortion/environment/lean_setup.sh b/tasks/diamond-distortion/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/diamond-distortion/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/diamond-distortion/environment/pack_submission.py b/tasks/diamond-distortion/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/diamond-distortion/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/diamond-distortion/instruction.md b/tasks/diamond-distortion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..57fabb49b7a613fb08e86946c942b1fe2652e577 --- /dev/null +++ b/tasks/diamond-distortion/instruction.md @@ -0,0 +1,367 @@ +# openai/math challenge `DiamondDistortion` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `DiamondDistortion`, also at `/opt/openai-math/challenges/DiamondDistortion.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u v + + +open scoped BigOperators Classical Topology +open Set + +namespace DiamondDistortion + +structure SegmentSystem (ι : Type*) where + IsSegment : Finset ι → Prop + singleton : ∀ v, IsSegment {v} + +namespace SegmentSystem + +variable {ι : Type*} (T : SegmentSystem ι) + +/-- The represented disjoint families in the definition of the primal segment norm. -/ +structure Family where + n : ℕ + seg : Fin n → Finset ι + allowed : ∀ i, T.IsSegment (seg i) + disjoint : Pairwise (fun i j => Disjoint (seg i) (seg j)) + +instance : Nonempty T.Family := ⟨{ + n := 0 + seg := Fin.elim0 + allowed := fun i => Fin.elim0 i + disjoint := fun {i} => Fin.elim0 i }⟩ + +variable {T} + +/-- Segment testing as a Euclidean-valued linear map. -/ +def Family.test (F : T.Family) : (ι →₀ ℝ) →ₗ[ℝ] EuclideanSpace ℝ (Fin F.n) where + toFun u := WithLp.toLp 2 (fun i => ∑ v ∈ F.seg i, u v) + map_add' u v := by + ext i + simp [Finset.sum_add_distrib] + map_smul' c u := by + ext i + simp [Finset.mul_sum] + +def Family.seminorm (F : T.Family) : Seminorm ℝ (ι →₀ ℝ) := + (normSeminorm ℝ (EuclideanSpace ℝ (Fin F.n))).comp F.test + +variable (T) + +def primalSeminorm : Seminorm ℝ (ι →₀ ℝ) := ⨆ F : T.Family, F.seminorm + +/-- Singleton families ensure that the segment seminorm separates points. -/ +def singletonFamily (v : ι) : T.Family where + n := 1 + seg _ := {v} + allowed _ := T.singleton v + disjoint := by intro i j h; exact False.elim (h (Subsingleton.elim _ _)) + +def Primal (_T : SegmentSystem ι) := ι →₀ ℝ + +instance : AddCommGroup T.Primal := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) +instance : Module ℝ T.Primal := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : NormedAddCommGroup T.Primal := by + have Family.test_apply (F : T.Family) (u : ι →₀ ℝ) (i : Fin F.n) : + F.test u i = ∑ v ∈ F.seg i, u v := rfl + have Family.seminorm_apply (F : T.Family) (u : ι →₀ ℝ) : + F.seminorm u = ‖F.test u‖ := rfl + have Family.test_single_le (F : T.Family) (v : ι) (r : ℝ) : + ‖F.test (Finsupp.single v r)‖ ≤ |r| := by + classical + rw [EuclideanSpace.norm_eq] + apply (Real.sqrt_le_left (abs_nonneg r)).2 + by_cases h : ∃ i, v ∈ F.seg i + · obtain ⟨i, hi⟩ := h + have hne : ∀ j, j ≠ i → v ∉ F.seg j := by + intro j hji hj + exact Finset.disjoint_left.mp (F.disjoint hji) hj hi + rw [Finset.sum_eq_single i] + · simp [Family.test, Finsupp.single_apply, hi] + · intro j _ hji + simp [Family.test, Finsupp.single_apply, hne j hji] + · simp + · have hn : ∀ i, v ∉ F.seg i := by simpa using h + simp [Family.test, Finsupp.single_apply, hn, sq_nonneg] + have Family.test_le_l1 (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ u.sum (fun _ r => |r|) := by + classical + calc + ‖F.test u‖ = ‖∑ v ∈ u.support, F.test (Finsupp.single v (u v))‖ := by + rw [← map_sum] + congr 2 + exact (Finsupp.sum_single u).symm + _ ≤ ∑ v ∈ u.support, ‖F.test (Finsupp.single v (u v))‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := Finset.sum_le_sum fun v _ => Family.test_single_le F v (u v) + _ = u.sum (fun _ r => |r|) := rfl + have families_bddAbove : BddAbove (Set.range (Family.seminorm (T := T))) := by + rw [Seminorm.bddAbove_range_iff] + intro u + exact ⟨u.sum (fun _ r => |r|), by rintro _ ⟨F, rfl⟩; exact Family.test_le_l1 F u⟩ + have test_le_primal (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ T.primalSeminorm u := by + rw [primalSeminorm, Seminorm.iSup_apply families_bddAbove] + exact le_ciSup (⟨u.sum (fun _ r => |r|), by + rintro _ ⟨G, rfl⟩; exact Family.test_le_l1 G u⟩ : + BddAbove (Set.range (fun G : T.Family => G.seminorm u))) F + have coordinate_le_primal (u : ι →₀ ℝ) (v : ι) : |u v| ≤ T.primalSeminorm u := by + have h := test_le_primal (T.singletonFamily v) u + rw [EuclideanSpace.norm_eq] at h + change Real.sqrt (∑ _ : Fin 1, ‖∑ w ∈ ({v} : Finset ι), u w‖ ^ 2) ≤ _ at h + simpa [Real.sqrt_sq_eq_abs] using h + have primal_eq_zero_iff (u : ι →₀ ℝ) : T.primalSeminorm u = 0 ↔ u = 0 := by + constructor + · intro h + ext v + have := coordinate_le_primal u v + simpa [h] using this + · rintro rfl + exact map_zero _ + exact AddGroupNorm.toNormedAddCommGroup + { T.primalSeminorm.toAddGroupSeminorm with + eq_zero_of_map_eq_zero' := fun u h => (primal_eq_zero_iff u).mp h } + +instance : NormedSpace ℝ T.Primal where + norm_smul_le c u := le_of_eq (T.primalSeminorm.smul' c u) + +abbrev JamesSpace := UniformSpace.Completion T.Primal + +/-- Its full real continuous dual. -/ +abbrev Dual := StrongDual ℝ T.JamesSpace + +/-- Coordinate evaluation on finite arrays, bounded by the singleton test. -/ +def coordinateFinite (v : ι) : T.Primal →L[ℝ] ℝ := by + have Family.test_apply (F : T.Family) (u : ι →₀ ℝ) (i : Fin F.n) : + F.test u i = ∑ v ∈ F.seg i, u v := rfl + have Family.seminorm_apply (F : T.Family) (u : ι →₀ ℝ) : + F.seminorm u = ‖F.test u‖ := rfl + have Family.test_single_le (F : T.Family) (v : ι) (r : ℝ) : + ‖F.test (Finsupp.single v r)‖ ≤ |r| := by + classical + rw [EuclideanSpace.norm_eq] + apply (Real.sqrt_le_left (abs_nonneg r)).2 + by_cases h : ∃ i, v ∈ F.seg i + · obtain ⟨i, hi⟩ := h + have hne : ∀ j, j ≠ i → v ∉ F.seg j := by + intro j hji hj + exact Finset.disjoint_left.mp (F.disjoint hji) hj hi + rw [Finset.sum_eq_single i] + · simp [Family.test, Finsupp.single_apply, hi] + · intro j _ hji + simp [Family.test, Finsupp.single_apply, hne j hji] + · simp + · have hn : ∀ i, v ∉ F.seg i := by simpa using h + simp [Family.test, Finsupp.single_apply, hn, sq_nonneg] + have Family.test_le_l1 (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ u.sum (fun _ r => |r|) := by + classical + calc + ‖F.test u‖ = ‖∑ v ∈ u.support, F.test (Finsupp.single v (u v))‖ := by + rw [← map_sum] + congr 2 + exact (Finsupp.sum_single u).symm + _ ≤ ∑ v ∈ u.support, ‖F.test (Finsupp.single v (u v))‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := Finset.sum_le_sum fun v _ => Family.test_single_le F v (u v) + _ = u.sum (fun _ r => |r|) := rfl + have families_bddAbove : BddAbove (Set.range (Family.seminorm (T := T))) := by + rw [Seminorm.bddAbove_range_iff] + intro u + exact ⟨u.sum (fun _ r => |r|), by rintro _ ⟨F, rfl⟩; exact Family.test_le_l1 F u⟩ + have test_le_primal (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ T.primalSeminorm u := by + rw [primalSeminorm, Seminorm.iSup_apply families_bddAbove] + exact le_ciSup (⟨u.sum (fun _ r => |r|), by + rintro _ ⟨G, rfl⟩; exact Family.test_le_l1 G u⟩ : + BddAbove (Set.range (fun G : T.Family => G.seminorm u))) F + have coordinate_le_primal (u : ι →₀ ℝ) (v : ι) : |u v| ≤ T.primalSeminorm u := by + have h := test_le_primal (T.singletonFamily v) u + rw [EuclideanSpace.norm_eq] at h + change Real.sqrt (∑ _ : Fin 1, ‖∑ w ∈ ({v} : Finset ι), u w‖ ^ 2) ≤ _ at h + simpa [Real.sqrt_sq_eq_abs] using h + exact (show T.Primal →ₗ[ℝ] ℝ from Finsupp.lapply v).mkContinuous 1 (by + intro u + change ‖(show ι →₀ ℝ from u) v‖ ≤ 1 * T.primalSeminorm u + simpa only [one_mul, Real.norm_eq_abs] using coordinate_le_primal u v) + +def coordinate (v : ι) : T.Dual := + (T.coordinateFinite v).extend UniformSpace.Completion.toComplL + +/-- Primal unit coordinate and its canonical image in the completion. -/ +def unitFinite (v : ι) : T.Primal := Finsupp.single v 1 + +def unitVector (v : ι) : T.JamesSpace := (T.unitFinite v : T.JamesSpace) + +def headDual (H : Finset ι) : T.Dual →L[ℝ] T.Dual := + ∑ v ∈ H, (ContinuousLinearMap.apply ℝ ℝ (T.unitVector v)).smulRight (T.coordinate v) + +/-- The norm-closed coordinate span, not the full infinite-tree dual. -/ +def CoordinatePredual : Submodule ℝ T.Dual := + (Submodule.span ℝ (Set.range T.coordinate)).topologicalClosure + +end SegmentSystem + +/-- A finite interval in an ancestral order. This keeps the root in every tree. -/ +def intervalSystem {ι : Type*} (r : ι → ι → Prop) + (hrefl : ∀ a, r a a) (hanti : ∀ a b, r a b → r b a → a = b) : SegmentSystem ι where + IsSegment s := ∃ a b, r a b ∧ ∀ v, v ∈ s ↔ r a v ∧ r v b + singleton v := by + refine ⟨v, v, hrefl v, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl + exact ⟨hrefl _, hrefl _⟩ + · intro h + exact hanti w v h.2 h.1 + +/-- An ancestral partial order: the predecessors of any vertex form a chain. -/ +class Ancestry (ι : Type*) extends PartialOrder ι where + predecessors_total : ∀ {a b c : ι}, le a c → le b c → le a b ∨ le b a + +namespace Ancestry + +open scoped Classical +variable {ι : Type*} [A : Ancestry ι] +local instance : PartialOrder ι := A.toPartialOrder + +/-- Nonempty finite intervals for an ancestral order. -/ +def segments : SegmentSystem ι := + intervalSystem (· ≤ ·) (fun _ => le_rfl) (fun _ _ => le_antisymm) + +end Ancestry + +def ForestNode := {hw : ℕ × List ℕ // 1 ≤ hw.1 ∧ hw.2.length ≤ hw.1} + +def ForestAncestor (a b : ForestNode) : Prop := + a.val.1 = b.val.1 ∧ a.val.2.IsPrefix b.val.2 + +@[instance_reducible] def forestAncestry : Ancestry ForestNode where + le := ForestAncestor + lt a b := ForestAncestor a b ∧ ¬ ForestAncestor b a + le_refl a := ⟨rfl, List.prefix_refl _⟩ + le_trans _ _ _ hab hbc := ⟨hab.1.trans hbc.1, hab.2.trans hbc.2⟩ + le_antisymm a b hab hba := by + apply Subtype.ext + exact Prod.ext hab.1 (hab.2.sublist.antisymm hba.2.sublist) + predecessors_total hab hac := by + rcases List.prefix_or_prefix_of_prefix hab.2 hac.2 with h | h + · exact Or.inl ⟨hab.1.trans hac.1.symm, h⟩ + · exact Or.inr ⟨hac.1.trans hab.1.symm, h⟩ + +def forestSegments : SegmentSystem ForestNode := + Ancestry.segments (A := forestAncestry) + +/-- Prefix order on all finite words, explicitly distinct from their lexicographic order. -/ +@[instance_reducible] def infiniteAncestry : Ancestry (List ℕ) where + le := List.IsPrefix + lt a b := a.IsPrefix b ∧ ¬ b.IsPrefix a + le_refl := List.prefix_refl + le_trans _ _ _ := List.IsPrefix.trans + le_antisymm _ _ hab hba := hab.sublist.antisymm hba.sublist + predecessors_total := List.prefix_or_prefix_of_prefix + +/-- The infinite-height tree of all finite words; this includes the empty root. -/ +def infiniteSegments : SegmentSystem (List ℕ) := + Ancestry.segments (A := infiniteAncestry) + +abbrev ForestDual := forestSegments.Dual +abbrev InfinitePredual := infiniteSegments.CoordinatePredual + +namespace Diamond + +/-- Stage edges, retaining their parent, child number, and side. -/ +@[reducible] def Edge : ℕ → Type + | 0 => Unit + | n + 1 => Edge n × ℕ × Bool + +/-- At every replacement every parent edge receives countably many distinct new vertices. -/ +@[reducible] def Vertex : ℕ → Type + | 0 => Bool + | n + 1 => Vertex n ⊕ (Edge n × ℕ) + +def endpoint : (n : ℕ) → Edge n → Bool → Vertex n + | 0, _, b => b + | n + 1, (e, _, false), false => Sum.inl (endpoint n e false) + | _ + 1, (e, i, false), true => Sum.inr (e, i) + | _ + 1, (e, i, true), false => Sum.inr (e, i) + | n + 1, (e, _, true), true => Sum.inl (endpoint n e true) + +/-- The undirected replacement graph. -/ +def graph (n : ℕ) : SimpleGraph (Vertex n) := + SimpleGraph.fromRel (fun u v => ∃ e : Edge n, u = endpoint n e false ∧ v = endpoint n e true) + +/-- Final edges have length 2⁻ᵏ: this is the shortest-path metric of the normalized graph. -/ +def distance (k : ℕ) (u v : Vertex k) : ℝ := + ((graph k).dist u v : ℝ) / (Nat.cast 2 : ℝ) ^ k + +end Diamond + +theorem headline_all_pairs : + (∀ (k : ℕ) (f : Diamond.Vertex k → ForestDual) (D s : ℝ), + 0 < s → (∀ u v,s*Diamond.distance k u v ≤ ‖f u-f v‖ ∧ + ‖f u-f v‖ ≤ D*s*Diamond.distance k u v) → 1+(k:ℝ)/4 ≤ D^2) ∧ + (∀ (k : ℕ) (f : Diamond.Vertex k → InfinitePredual) (D s : ℝ), + 0 < s → (∀ u v,s*Diamond.distance k u v ≤ ‖f u-f v‖ ∧ + ‖f u-f v‖ ≤ D*s*Diamond.distance k u v) → 1+(k:ℝ)/4 ≤ D^2) := by + + sorry + +end DiamondDistortion + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DiamondDistortion.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DiamondDistortion.headline_all_pairs` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/diamond-distortion/solution/closure.txt b/tasks/diamond-distortion/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9789fc9e8dd198805d26ec44d9c35448f4ee07e --- /dev/null +++ b/tasks/diamond-distortion/solution/closure.txt @@ -0,0 +1,32 @@ +OAI.Analysis.DiamondDistortion.AMUC +OAI.Analysis.DiamondDistortion.Ancestry +OAI.Analysis.DiamondDistortion.Backward +OAI.Analysis.DiamondDistortion.CoordinateDual +OAI.Analysis.DiamondDistortion.CoordinateSpace +OAI.Analysis.DiamondDistortion.Descent +OAI.Analysis.DiamondDistortion.DiamondGraph +OAI.Analysis.DiamondDistortion.DirectEnergy +OAI.Analysis.DiamondDistortion.EquivalentNorm +OAI.Analysis.DiamondDistortion.FiniteAverage +OAI.Analysis.DiamondDistortion.ForestModels +OAI.Analysis.DiamondDistortion.HeadProjections +OAI.Analysis.DiamondDistortion.Incomparable +OAI.Analysis.DiamondDistortion.InfimalCost +OAI.Analysis.DiamondDistortion.MidpointHeads +OAI.Analysis.DiamondDistortion.ModelMaps +OAI.Analysis.DiamondDistortion.Orthogonality +OAI.Analysis.DiamondDistortion.PathBounds +OAI.Analysis.DiamondDistortion.PathLenses +OAI.Analysis.DiamondDistortion.PathModels +OAI.Analysis.DiamondDistortion.RecursiveBounds +OAI.Analysis.DiamondDistortion.RecursiveLenses +OAI.Analysis.DiamondDistortion.RecursiveModels +OAI.Analysis.DiamondDistortion.Relations +OAI.Analysis.DiamondDistortion.SegmentNorm +OAI.Analysis.DiamondDistortion.SignCube +OAI.Analysis.DiamondDistortion.StartModels +OAI.Analysis.DiamondDistortion.Stretch +OAI.Analysis.DiamondDistortion.Transfers +OAI.Analysis.DiamondDistortion.UpperFunction +OAI.Analysis.DiamondDistortion.Vanishing +OAI.Analysis.DiamondDistortion.WeakLenses diff --git a/tasks/diamond-distortion/solution/reference.py b/tasks/diamond-distortion/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/diamond-distortion/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/diamond-distortion/solution/solve.sh b/tasks/diamond-distortion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d14ca2b02131c3561e6192b0a016dcaf6e4236bc --- /dev/null +++ b/tasks/diamond-distortion/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DiamondDistortion, i.e. module OAI.Analysis.DiamondDistortion.Descent and the +# 32 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.DiamondDistortion.Descent /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DiamondDistortion" diff --git a/tasks/diamond-distortion/task.toml b/tasks/diamond-distortion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32e077ea3b3399abe5f2d9398de9a95aadb56150 --- /dev/null +++ b/tasks/diamond-distortion/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/diamond-distortion" +version = "1.0.0" +description = "Prove DiamondDistortion (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DiamondDistortion.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DiamondDistortion" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.DiamondDistortion.headline_all_pairs"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.DiamondDistortion.Descent" +reference_modules = 32 +reference_lean_bytes = 472861 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 771 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12125 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/diamond-distortion/tests/Challenge.lean b/tasks/diamond-distortion/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ba0bf57772dcb942df9bd044dee794f465657bc1 --- /dev/null +++ b/tasks/diamond-distortion/tests/Challenge.lean @@ -0,0 +1,316 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u v + + +open scoped BigOperators Classical Topology +open Set + +namespace DiamondDistortion + +structure SegmentSystem (ι : Type*) where + IsSegment : Finset ι → Prop + singleton : ∀ v, IsSegment {v} + +namespace SegmentSystem + +variable {ι : Type*} (T : SegmentSystem ι) + +/-- The represented disjoint families in the definition of the primal segment norm. -/ +structure Family where + n : ℕ + seg : Fin n → Finset ι + allowed : ∀ i, T.IsSegment (seg i) + disjoint : Pairwise (fun i j => Disjoint (seg i) (seg j)) + +instance : Nonempty T.Family := ⟨{ + n := 0 + seg := Fin.elim0 + allowed := fun i => Fin.elim0 i + disjoint := fun {i} => Fin.elim0 i }⟩ + +variable {T} + +/-- Segment testing as a Euclidean-valued linear map. -/ +def Family.test (F : T.Family) : (ι →₀ ℝ) →ₗ[ℝ] EuclideanSpace ℝ (Fin F.n) where + toFun u := WithLp.toLp 2 (fun i => ∑ v ∈ F.seg i, u v) + map_add' u v := by + ext i + simp [Finset.sum_add_distrib] + map_smul' c u := by + ext i + simp [Finset.mul_sum] + +def Family.seminorm (F : T.Family) : Seminorm ℝ (ι →₀ ℝ) := + (normSeminorm ℝ (EuclideanSpace ℝ (Fin F.n))).comp F.test + +variable (T) + +def primalSeminorm : Seminorm ℝ (ι →₀ ℝ) := ⨆ F : T.Family, F.seminorm + +/-- Singleton families ensure that the segment seminorm separates points. -/ +def singletonFamily (v : ι) : T.Family where + n := 1 + seg _ := {v} + allowed _ := T.singleton v + disjoint := by intro i j h; exact False.elim (h (Subsingleton.elim _ _)) + +def Primal (_T : SegmentSystem ι) := ι →₀ ℝ + +instance : AddCommGroup T.Primal := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) +instance : Module ℝ T.Primal := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : NormedAddCommGroup T.Primal := by + have Family.test_apply (F : T.Family) (u : ι →₀ ℝ) (i : Fin F.n) : + F.test u i = ∑ v ∈ F.seg i, u v := rfl + have Family.seminorm_apply (F : T.Family) (u : ι →₀ ℝ) : + F.seminorm u = ‖F.test u‖ := rfl + have Family.test_single_le (F : T.Family) (v : ι) (r : ℝ) : + ‖F.test (Finsupp.single v r)‖ ≤ |r| := by + classical + rw [EuclideanSpace.norm_eq] + apply (Real.sqrt_le_left (abs_nonneg r)).2 + by_cases h : ∃ i, v ∈ F.seg i + · obtain ⟨i, hi⟩ := h + have hne : ∀ j, j ≠ i → v ∉ F.seg j := by + intro j hji hj + exact Finset.disjoint_left.mp (F.disjoint hji) hj hi + rw [Finset.sum_eq_single i] + · simp [Family.test, Finsupp.single_apply, hi] + · intro j _ hji + simp [Family.test, Finsupp.single_apply, hne j hji] + · simp + · have hn : ∀ i, v ∉ F.seg i := by simpa using h + simp [Family.test, Finsupp.single_apply, hn, sq_nonneg] + have Family.test_le_l1 (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ u.sum (fun _ r => |r|) := by + classical + calc + ‖F.test u‖ = ‖∑ v ∈ u.support, F.test (Finsupp.single v (u v))‖ := by + rw [← map_sum] + congr 2 + exact (Finsupp.sum_single u).symm + _ ≤ ∑ v ∈ u.support, ‖F.test (Finsupp.single v (u v))‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := Finset.sum_le_sum fun v _ => Family.test_single_le F v (u v) + _ = u.sum (fun _ r => |r|) := rfl + have families_bddAbove : BddAbove (Set.range (Family.seminorm (T := T))) := by + rw [Seminorm.bddAbove_range_iff] + intro u + exact ⟨u.sum (fun _ r => |r|), by rintro _ ⟨F, rfl⟩; exact Family.test_le_l1 F u⟩ + have test_le_primal (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ T.primalSeminorm u := by + rw [primalSeminorm, Seminorm.iSup_apply families_bddAbove] + exact le_ciSup (⟨u.sum (fun _ r => |r|), by + rintro _ ⟨G, rfl⟩; exact Family.test_le_l1 G u⟩ : + BddAbove (Set.range (fun G : T.Family => G.seminorm u))) F + have coordinate_le_primal (u : ι →₀ ℝ) (v : ι) : |u v| ≤ T.primalSeminorm u := by + have h := test_le_primal (T.singletonFamily v) u + rw [EuclideanSpace.norm_eq] at h + change Real.sqrt (∑ _ : Fin 1, ‖∑ w ∈ ({v} : Finset ι), u w‖ ^ 2) ≤ _ at h + simpa [Real.sqrt_sq_eq_abs] using h + have primal_eq_zero_iff (u : ι →₀ ℝ) : T.primalSeminorm u = 0 ↔ u = 0 := by + constructor + · intro h + ext v + have := coordinate_le_primal u v + simpa [h] using this + · rintro rfl + exact map_zero _ + exact AddGroupNorm.toNormedAddCommGroup + { T.primalSeminorm.toAddGroupSeminorm with + eq_zero_of_map_eq_zero' := fun u h => (primal_eq_zero_iff u).mp h } + +instance : NormedSpace ℝ T.Primal where + norm_smul_le c u := le_of_eq (T.primalSeminorm.smul' c u) + +abbrev JamesSpace := UniformSpace.Completion T.Primal + +/-- Its full real continuous dual. -/ +abbrev Dual := StrongDual ℝ T.JamesSpace + +/-- Coordinate evaluation on finite arrays, bounded by the singleton test. -/ +def coordinateFinite (v : ι) : T.Primal →L[ℝ] ℝ := by + have Family.test_apply (F : T.Family) (u : ι →₀ ℝ) (i : Fin F.n) : + F.test u i = ∑ v ∈ F.seg i, u v := rfl + have Family.seminorm_apply (F : T.Family) (u : ι →₀ ℝ) : + F.seminorm u = ‖F.test u‖ := rfl + have Family.test_single_le (F : T.Family) (v : ι) (r : ℝ) : + ‖F.test (Finsupp.single v r)‖ ≤ |r| := by + classical + rw [EuclideanSpace.norm_eq] + apply (Real.sqrt_le_left (abs_nonneg r)).2 + by_cases h : ∃ i, v ∈ F.seg i + · obtain ⟨i, hi⟩ := h + have hne : ∀ j, j ≠ i → v ∉ F.seg j := by + intro j hji hj + exact Finset.disjoint_left.mp (F.disjoint hji) hj hi + rw [Finset.sum_eq_single i] + · simp [Family.test, Finsupp.single_apply, hi] + · intro j _ hji + simp [Family.test, Finsupp.single_apply, hne j hji] + · simp + · have hn : ∀ i, v ∉ F.seg i := by simpa using h + simp [Family.test, Finsupp.single_apply, hn, sq_nonneg] + have Family.test_le_l1 (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ u.sum (fun _ r => |r|) := by + classical + calc + ‖F.test u‖ = ‖∑ v ∈ u.support, F.test (Finsupp.single v (u v))‖ := by + rw [← map_sum] + congr 2 + exact (Finsupp.sum_single u).symm + _ ≤ ∑ v ∈ u.support, ‖F.test (Finsupp.single v (u v))‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := Finset.sum_le_sum fun v _ => Family.test_single_le F v (u v) + _ = u.sum (fun _ r => |r|) := rfl + have families_bddAbove : BddAbove (Set.range (Family.seminorm (T := T))) := by + rw [Seminorm.bddAbove_range_iff] + intro u + exact ⟨u.sum (fun _ r => |r|), by rintro _ ⟨F, rfl⟩; exact Family.test_le_l1 F u⟩ + have test_le_primal (F : T.Family) (u : ι →₀ ℝ) : + ‖F.test u‖ ≤ T.primalSeminorm u := by + rw [primalSeminorm, Seminorm.iSup_apply families_bddAbove] + exact le_ciSup (⟨u.sum (fun _ r => |r|), by + rintro _ ⟨G, rfl⟩; exact Family.test_le_l1 G u⟩ : + BddAbove (Set.range (fun G : T.Family => G.seminorm u))) F + have coordinate_le_primal (u : ι →₀ ℝ) (v : ι) : |u v| ≤ T.primalSeminorm u := by + have h := test_le_primal (T.singletonFamily v) u + rw [EuclideanSpace.norm_eq] at h + change Real.sqrt (∑ _ : Fin 1, ‖∑ w ∈ ({v} : Finset ι), u w‖ ^ 2) ≤ _ at h + simpa [Real.sqrt_sq_eq_abs] using h + exact (show T.Primal →ₗ[ℝ] ℝ from Finsupp.lapply v).mkContinuous 1 (by + intro u + change ‖(show ι →₀ ℝ from u) v‖ ≤ 1 * T.primalSeminorm u + simpa only [one_mul, Real.norm_eq_abs] using coordinate_le_primal u v) + +def coordinate (v : ι) : T.Dual := + (T.coordinateFinite v).extend UniformSpace.Completion.toComplL + +/-- Primal unit coordinate and its canonical image in the completion. -/ +def unitFinite (v : ι) : T.Primal := Finsupp.single v 1 + +def unitVector (v : ι) : T.JamesSpace := (T.unitFinite v : T.JamesSpace) + +def headDual (H : Finset ι) : T.Dual →L[ℝ] T.Dual := + ∑ v ∈ H, (ContinuousLinearMap.apply ℝ ℝ (T.unitVector v)).smulRight (T.coordinate v) + +/-- The norm-closed coordinate span, not the full infinite-tree dual. -/ +def CoordinatePredual : Submodule ℝ T.Dual := + (Submodule.span ℝ (Set.range T.coordinate)).topologicalClosure + +end SegmentSystem + +/-- A finite interval in an ancestral order. This keeps the root in every tree. -/ +def intervalSystem {ι : Type*} (r : ι → ι → Prop) + (hrefl : ∀ a, r a a) (hanti : ∀ a b, r a b → r b a → a = b) : SegmentSystem ι where + IsSegment s := ∃ a b, r a b ∧ ∀ v, v ∈ s ↔ r a v ∧ r v b + singleton v := by + refine ⟨v, v, hrefl v, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl + exact ⟨hrefl _, hrefl _⟩ + · intro h + exact hanti w v h.2 h.1 + +/-- An ancestral partial order: the predecessors of any vertex form a chain. -/ +class Ancestry (ι : Type*) extends PartialOrder ι where + predecessors_total : ∀ {a b c : ι}, le a c → le b c → le a b ∨ le b a + +namespace Ancestry + +open scoped Classical +variable {ι : Type*} [A : Ancestry ι] +local instance : PartialOrder ι := A.toPartialOrder + +/-- Nonempty finite intervals for an ancestral order. -/ +def segments : SegmentSystem ι := + intervalSystem (· ≤ ·) (fun _ => le_rfl) (fun _ _ => le_antisymm) + +end Ancestry + +def ForestNode := {hw : ℕ × List ℕ // 1 ≤ hw.1 ∧ hw.2.length ≤ hw.1} + +def ForestAncestor (a b : ForestNode) : Prop := + a.val.1 = b.val.1 ∧ a.val.2.IsPrefix b.val.2 + +@[instance_reducible] def forestAncestry : Ancestry ForestNode where + le := ForestAncestor + lt a b := ForestAncestor a b ∧ ¬ ForestAncestor b a + le_refl a := ⟨rfl, List.prefix_refl _⟩ + le_trans _ _ _ hab hbc := ⟨hab.1.trans hbc.1, hab.2.trans hbc.2⟩ + le_antisymm a b hab hba := by + apply Subtype.ext + exact Prod.ext hab.1 (hab.2.sublist.antisymm hba.2.sublist) + predecessors_total hab hac := by + rcases List.prefix_or_prefix_of_prefix hab.2 hac.2 with h | h + · exact Or.inl ⟨hab.1.trans hac.1.symm, h⟩ + · exact Or.inr ⟨hac.1.trans hab.1.symm, h⟩ + +def forestSegments : SegmentSystem ForestNode := + Ancestry.segments (A := forestAncestry) + +/-- Prefix order on all finite words, explicitly distinct from their lexicographic order. -/ +@[instance_reducible] def infiniteAncestry : Ancestry (List ℕ) where + le := List.IsPrefix + lt a b := a.IsPrefix b ∧ ¬ b.IsPrefix a + le_refl := List.prefix_refl + le_trans _ _ _ := List.IsPrefix.trans + le_antisymm _ _ hab hba := hab.sublist.antisymm hba.sublist + predecessors_total := List.prefix_or_prefix_of_prefix + +/-- The infinite-height tree of all finite words; this includes the empty root. -/ +def infiniteSegments : SegmentSystem (List ℕ) := + Ancestry.segments (A := infiniteAncestry) + +abbrev ForestDual := forestSegments.Dual +abbrev InfinitePredual := infiniteSegments.CoordinatePredual + +namespace Diamond + +/-- Stage edges, retaining their parent, child number, and side. -/ +@[reducible] def Edge : ℕ → Type + | 0 => Unit + | n + 1 => Edge n × ℕ × Bool + +/-- At every replacement every parent edge receives countably many distinct new vertices. -/ +@[reducible] def Vertex : ℕ → Type + | 0 => Bool + | n + 1 => Vertex n ⊕ (Edge n × ℕ) + +def endpoint : (n : ℕ) → Edge n → Bool → Vertex n + | 0, _, b => b + | n + 1, (e, _, false), false => Sum.inl (endpoint n e false) + | _ + 1, (e, i, false), true => Sum.inr (e, i) + | _ + 1, (e, i, true), false => Sum.inr (e, i) + | n + 1, (e, _, true), true => Sum.inl (endpoint n e true) + +/-- The undirected replacement graph. -/ +def graph (n : ℕ) : SimpleGraph (Vertex n) := + SimpleGraph.fromRel (fun u v => ∃ e : Edge n, u = endpoint n e false ∧ v = endpoint n e true) + +/-- Final edges have length 2⁻ᵏ: this is the shortest-path metric of the normalized graph. -/ +def distance (k : ℕ) (u v : Vertex k) : ℝ := + ((graph k).dist u v : ℝ) / (Nat.cast 2 : ℝ) ^ k + +end Diamond + +theorem headline_all_pairs : + (∀ (k : ℕ) (f : Diamond.Vertex k → ForestDual) (D s : ℝ), + 0 < s → (∀ u v,s*Diamond.distance k u v ≤ ‖f u-f v‖ ∧ + ‖f u-f v‖ ≤ D*s*Diamond.distance k u v) → 1+(k:ℝ)/4 ≤ D^2) ∧ + (∀ (k : ℕ) (f : Diamond.Vertex k → InfinitePredual) (D s : ℝ), + 0 < s → (∀ u v,s*Diamond.distance k u v ≤ ‖f u-f v‖ ∧ + ‖f u-f v‖ ≤ D*s*Diamond.distance k u v) → 1+(k:ℝ)/4 ≤ D^2) := by + + sorry + +end DiamondDistortion + +end + +end OAI diff --git a/tasks/diamond-distortion/tests/grade.py b/tasks/diamond-distortion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/diamond-distortion/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/diamond-distortion/tests/task.json b/tasks/diamond-distortion/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8ca4d85063f37f6a7a93a2a4b59c119d81e55133 --- /dev/null +++ b/tasks/diamond-distortion/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DiamondDistortion", + "comparator": { + "theorem_names": [ + "OAI.DiamondDistortion.headline_all_pairs" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11225 +} \ No newline at end of file diff --git a/tasks/diamond-distortion/tests/test.sh b/tasks/diamond-distortion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/diamond-distortion/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/diluted-spin/environment/Dockerfile b/tasks/diluted-spin/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/diluted-spin/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/diluted-spin/environment/fetch_mathlib.sh b/tasks/diluted-spin/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/diluted-spin/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/diluted-spin/environment/lake-manifest.json b/tasks/diluted-spin/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/diluted-spin/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/diluted-spin/environment/lakefile.lean b/tasks/diluted-spin/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/diluted-spin/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/diluted-spin/environment/lean_setup.sh b/tasks/diluted-spin/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/diluted-spin/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/diluted-spin/environment/pack_submission.py b/tasks/diluted-spin/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/diluted-spin/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/diluted-spin/instruction.md b/tasks/diluted-spin/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c47d4fa44d2a3c578eebed44acc2603fe422bd31 --- /dev/null +++ b/tasks/diluted-spin/instruction.md @@ -0,0 +1,205 @@ +# openai/math challenge `DilutedSpin` (family 221) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 221 of the release, *The Mezard–Parisi formula for diluted spin glasses* +(Probability and statistical mechanics). The family as a whole: Proves the Mezard–Parisi hierarchical cavity formula for Poisson-diluted even-arity Ising models satisfying the Panchenko–Talagrand factorization and positivity assumptions, with only first-moment integrability. The limiting free energy equals the infimum over finite-depth hierarchical trial laws. This includes the Viana–Bray model, symmetric diluted even-spin models, and weighted soft even-$K$ satisfiability. + +The challenge is `DilutedSpin`, also at `/opt/openai-math/challenges/DilutedSpin.lean`: + +```lean +import Mathlib + +namespace OAI + + + +open MeasureTheory ProbabilityTheory Filter +open scoped BigOperators ENNReal NNReal Topology + +namespace DilutedSpinGlass + +abbrev Spin := Bool + +def spin (s : Spin) : ℝ := if s then 1 else -1 + +abbrev Interaction (p : ℕ) := (Fin p → Spin) → ℝ + +/-- One interaction together with its factorization witness: theta,a,b,f. -/ +abbrev InteractionSample (p : ℕ) := + Interaction p × ℝ × ℝ × (Fin p → Spin → ℝ) + +structure Model (p : ℕ) where + alpha : ℝ≥0 + disorder : ProbabilityMeasure (InteractionSample p) + field : ProbabilityMeasure ℝ + +/-- Exactly the standing hypotheses (model:integrability through positivity). +`norm` on the finite function space is max_s |theta(s)|. -/ +structure Admissible {p : ℕ} (M : Model p) : Prop where + arity : 2 ≤ p + even : Even p + density : 0 < M.alpha + interaction_integrable : Integrable (fun z : InteractionSample p => ‖z.1‖) + M.disorder.toMeasure + field_integrable : Integrable (fun h : ℝ => |h|) M.field.toMeasure + factorization : ∀ᵐ z ∂M.disorder.toMeasure, + 0 < z.2.1 ∧ ∀ s : Fin p → Spin, + Real.exp (z.1 s) = z.2.1 * (1 + z.2.2.1 * ∏ l, z.2.2.2 l (s l)) ∧ + |z.2.2.1 * ∏ l, z.2.2.2 l (s l)| < 1 + independent_f : iIndepFun (fun l (z : InteractionSample p) => z.2.2.2 l) + M.disorder.toMeasure + identically_distributed_f : ∀ l j : Fin p, + IdentDistrib (fun z : InteractionSample p => z.2.2.2 l) + (fun z : InteractionSample p => z.2.2.2 j) + M.disorder.toMeasure M.disorder.toMeasure + independent_b : IndepFun (fun z : InteractionSample p => z.2.2.1) + (fun z : InteractionSample p => z.2.2.2) M.disorder.toMeasure + finite_b_moments : ∀ n : ℕ, 1 ≤ n → + Integrable (fun z : InteractionSample p => (-z.2.2.1) ^ n) M.disorder.toMeasure + positivity : ∀ n : ℕ, 1 ≤ n → + 0 ≤ ∫ z : InteractionSample p, (-z.2.2.1) ^ n ∂M.disorder.toMeasure + +/-- Minus the Hamiltonian, with all index choices including repetitions. -/ +noncomputable def logWeight {p N k : ℕ} (theta : Fin k → InteractionSample p) + (h : Fin N → ℝ) (indices : Fin k → Fin p → Fin N) (σ : Fin N → Spin) : ℝ := + (∑ j, (theta j).1 (fun l => σ (indices j l))) + ∑ i, h i * spin (σ i) + +noncomputable def logPartition {p N k : ℕ} (theta : Fin k → InteractionSample p) + (h : Fin N → ℝ) (indices : Fin k → Fin p → Fin N) : ℝ := + Real.log (∑ σ : Fin N → Spin, Real.exp (logWeight theta h indices σ)) + +/-- F_N, using an explicit uniform average over the independent index labels. +The value at N=0 is irrelevant to the limit; valid system sizes are N>=1. -/ +noncomputable def pressure {p : ℕ} (M : Model p) (N : ℕ) : ℝ := + (∫ k : ℕ, + ∫ theta : Fin k → InteractionSample p, + ∫ h : Fin N → ℝ, + ((∑ indices : Fin k → Fin p → Fin N, logPartition theta h indices) / + (Fintype.card (Fin k → Fin p → Fin N) : ℝ)) + ∂Measure.pi (fun _ : Fin N => M.field.toMeasure) + ∂Measure.pi (fun _ : Fin k => M.disorder.toMeasure) + ∂poissonMeasure (M.alpha * N)) / N + +noncomputable def q (x : ℝ) (s : Spin) : ℝ := + Real.exp (x * spin s) / (2 * Real.cosh x) + +noncomputable def edge {p : ℕ} (theta : Interaction p) (x : Fin p → ℝ) : ℝ := + ∑ s : Fin p → Spin, Real.exp (theta s) * ∏ l, q (x l) (s l) + +/-- Append the distinguished cavity spin in the last position. -/ +def appendSpin {p : ℕ} (s : Fin (p - 1) → Spin) (ε : Spin) (l : Fin p) : Spin := + if h : l.val < p - 1 then s ⟨l.val, h⟩ else ε + +noncomputable def message {p : ℕ} (theta : Interaction p) + (x : Fin (p - 1) → ℝ) (ε : Spin) : ℝ := + Real.log (∑ s : Fin (p - 1) → Spin, + Real.exp (theta (appendSpin s ε)) * ∏ l, q (x l) (s l)) + +noncomputable def siteLog {p k : ℕ} (theta : Fin k → InteractionSample p) + (h : ℝ) (x : (Fin k × Fin (p - 1)) → ℝ) : ℝ := + Real.log ((∑ ε : Spin, Real.exp + (h * spin ε + ∑ j, message (theta j).1 (fun l => x (j, l)) ε)) / 2) + +/-- Use literally the Borel sigma-field of the weak topology at each level, +as stipulated in model.tex. -/ +local instance instMeasurableSpaceCarrier_challenge (X : TopCat) : MeasurableSpace X := borel X +local instance instBorelSpaceCarrier_challenge (X : TopCat) : BorelSpace X := ⟨rfl⟩ + +/-- Nested probability laws: H_0=R and H_{j+1}=P(H_j), with weak topologies. -/ +noncomputable def Hierarchy : ℕ → TopCat + | 0 => TopCat.of ℝ + | r + 1 => TopCat.of (ProbabilityMeasure (Hierarchy r)) + +/-- Logarithmic form of the conditional power means T_0 using independent +message labels. The current eta's are held fixed; only their descendants +are integrated. Physical disorder is a fixed argument of g throughout. -/ +noncomputable def logMean {ι : Type} [Fintype ι] : + (r : ℕ) → ((ι → ℝ) → ℝ) → (Fin r → ℝ) → (ι → Hierarchy r) → ℝ + | 0, g, _, x => g x + | r + 1, g, m, eta => + Real.log (∫ x : ι → Hierarchy r, + Real.exp (m 0 * logMean r g (fun i => m i.succ) x) + ∂Measure.pi (fun i => (eta i).toMeasure)) / m 0 + +/-- Expectation over the root laws eta_0 of each independent message label. +This also gives the r=0 convention (iid real messages, no power means). -/ +noncomputable def trialLog {ι : Type} [Fintype ι] (r : ℕ) + (ζ : Hierarchy (r + 1)) (m : Fin r → ℝ) (g : (ι → ℝ) → ℝ) : ℝ := + ∫ eta : ι → Hierarchy r, logMean r g m eta + ∂Measure.pi (fun _ : ι => ζ.toMeasure) + +/-- Admissible exponents 0 M.disorder.toMeasure) + ∂poissonMeasure (M.alpha * p)) - + (M.alpha : ℝ) * (p - 1 : ℕ) * + (∫ theta : InteractionSample p, + trialLog r ζ m (fun x => Real.log (edge theta.1 x)) ∂M.disorder.toMeasure) + +noncomputable def phi {p : ℕ} (M : Model p) (r : ℕ) : ℝ := + sInf {v : ℝ | ∃ (ζ : Hierarchy (r + 1)) (m : Fin r → ℝ), + Exponents m ∧ v = functional M r ζ m} + +noncomputable def variationalValue {p : ℕ} (M : Model p) : ℝ := + ⨅ r : ℕ, phi M r + +/-- main:theorem. No boundedness of interactions, fields, or messages is added. +Existence of the thermodynamic limit is part of this convergence assertion. -/ +theorem mezard_parisi {p : ℕ} (M : Model p) (hM : Admissible M) : + Tendsto (pressure M) atTop (𝓝 (variationalValue M)) := by + sorry + +end DilutedSpinGlass + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DilutedSpin.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DilutedSpinGlass.mezard_parisi` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/diluted-spin/solution/closure.txt b/tasks/diluted-spin/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..16ca19d86802fd48b63574d24a4368031ed239f4 --- /dev/null +++ b/tasks/diluted-spin/solution/closure.txt @@ -0,0 +1,405 @@ +OAI.Probability.DilutedSpin.ActualCharging +OAI.Probability.DilutedSpin.ActualLowIncrement +OAI.Probability.DilutedSpin.ActualNegligible +OAI.Probability.DilutedSpin.ActualPrefix +OAI.Probability.DilutedSpin.ActualRootVariance +OAI.Probability.DilutedSpin.ActualTreeSelector +OAI.Probability.DilutedSpin.AdmissibleInterval +OAI.Probability.DilutedSpin.AnchorExtension +OAI.Probability.DilutedSpin.AveragedEnergyRoot +OAI.Probability.DilutedSpin.AveragedMatrixSelection +OAI.Probability.DilutedSpin.AveragedRootBounds +OAI.Probability.DilutedSpin.BoundedCavityLower +OAI.Probability.DilutedSpin.BranchingEvaluation +OAI.Probability.DilutedSpin.CanonicalRegularMultileaf +OAI.Probability.DilutedSpin.CavityAllocatedMean +OAI.Probability.DilutedSpin.CavityAllocation +OAI.Probability.DilutedSpin.CavityBounds +OAI.Probability.DilutedSpin.CavityDatumProjection +OAI.Probability.DilutedSpin.CavityEndpointCount +OAI.Probability.DilutedSpin.CavityErrorLimit +OAI.Probability.DilutedSpin.CavityGapFubini +OAI.Probability.DilutedSpin.CavityIndex +OAI.Probability.DilutedSpin.CavityInsertionAlgebra +OAI.Probability.DilutedSpin.CavityInsertionFunctional +OAI.Probability.DilutedSpin.CavityMaskEnergy +OAI.Probability.DilutedSpin.CavityOldNewMean +OAI.Probability.DilutedSpin.CavityPack +OAI.Probability.DilutedSpin.CavityPoissonEndpoint +OAI.Probability.DilutedSpin.CavityProxy +OAI.Probability.DilutedSpin.CavityRateLimits +OAI.Probability.DilutedSpin.CavitySeparable +OAI.Probability.DilutedSpin.CavitySiteMean +OAI.Probability.DilutedSpin.CavitySplit +OAI.Probability.DilutedSpin.CavityTrialIdentity +OAI.Probability.DilutedSpin.CenteredPressure +OAI.Probability.DilutedSpin.CenteredTrialLocal +OAI.Probability.DilutedSpin.ClippedCavityProxy +OAI.Probability.DilutedSpin.ClippedModelFacts +OAI.Probability.DilutedSpin.ClippedProxyRate +OAI.Probability.DilutedSpin.ColorIterate +OAI.Probability.DilutedSpin.ColorPolarization +OAI.Probability.DilutedSpin.ColorSymmetry +OAI.Probability.DilutedSpin.ColoredAnchor +OAI.Probability.DilutedSpin.CommonFresh +OAI.Probability.DilutedSpin.CommonTreeSample +OAI.Probability.DilutedSpin.CompleteShapeSelection +OAI.Probability.DilutedSpin.CompoundCoupling +OAI.Probability.DilutedSpin.CompoundMoment +OAI.Probability.DilutedSpin.CompoundPhysicalMean +OAI.Probability.DilutedSpin.CompoundPoisson +OAI.Probability.DilutedSpin.CompoundRate +OAI.Probability.DilutedSpin.CompoundRateAverage +OAI.Probability.DilutedSpin.CompoundSample +OAI.Probability.DilutedSpin.CompoundSuperposition +OAI.Probability.DilutedSpin.ConcentrationRate +OAI.Probability.DilutedSpin.ConcreteAnalyticSelection +OAI.Probability.DilutedSpin.ConcreteHistory +OAI.Probability.DilutedSpin.ConcreteReservoir +OAI.Probability.DilutedSpin.ConcreteSelection +OAI.Probability.DilutedSpin.ConditionalScheduledMean +OAI.Probability.DilutedSpin.ConditionalSpatialContinuity +OAI.Probability.DilutedSpin.ConvexBounds +OAI.Probability.DilutedSpin.CoordinateFiber +OAI.Probability.DilutedSpin.Core +OAI.Probability.DilutedSpin.CountArrayBridge +OAI.Probability.DilutedSpin.CountBridgeTools +OAI.Probability.DilutedSpin.CountableFullSupport +OAI.Probability.DilutedSpin.CountableReservoir +OAI.Probability.DilutedSpin.CountableTagSelection +OAI.Probability.DilutedSpin.CountedSizeCoupling +OAI.Probability.DilutedSpin.CountedSpinMean +OAI.Probability.DilutedSpin.CountedSteps +OAI.Probability.DilutedSpin.DenseUpper +OAI.Probability.DilutedSpin.DepthChildMoment +OAI.Probability.DilutedSpin.DeviationLimitTools +OAI.Probability.DilutedSpin.DictionaryAnalytic +OAI.Probability.DilutedSpin.DictionaryExtraction +OAI.Probability.DilutedSpin.DictionaryPalm +OAI.Probability.DilutedSpin.DoubledStemProjection +OAI.Probability.DilutedSpin.EarliestChildDepth +OAI.Probability.DilutedSpin.EnergyInsertionMean +OAI.Probability.DilutedSpin.ExactVariationalLower +OAI.Probability.DilutedSpin.ExtendedExponents +OAI.Probability.DilutedSpin.ExternalAverageTaylor +OAI.Probability.DilutedSpin.ExternalCoefficientLaw +OAI.Probability.DilutedSpin.ExternalCovariance +OAI.Probability.DilutedSpin.ExternalFreshLaw +OAI.Probability.DilutedSpin.ExternalRoot +OAI.Probability.DilutedSpin.ExternalTaylor +OAI.Probability.DilutedSpin.FiniteAnalytic +OAI.Probability.DilutedSpin.FiniteEncoding +OAI.Probability.DilutedSpin.FiniteHierarchyDense +OAI.Probability.DilutedSpin.FiniteLaw +OAI.Probability.DilutedSpin.FiniteLogExpansion +OAI.Probability.DilutedSpin.FinitePiInjective +OAI.Probability.DilutedSpin.FinitePoissonSplit +OAI.Probability.DilutedSpin.FiniteProducts +OAI.Probability.DilutedSpin.FiniteProjection +OAI.Probability.DilutedSpin.FiniteTowerPi +OAI.Probability.DilutedSpin.FirstMomentConditional +OAI.Probability.DilutedSpin.FirstMomentCount +OAI.Probability.DilutedSpin.FirstMomentFresh +OAI.Probability.DilutedSpin.FirstMomentUpper +OAI.Probability.DilutedSpin.FirstSplitSchedule +OAI.Probability.DilutedSpin.ForkTree +OAI.Probability.DilutedSpin.FullCountCorrection +OAI.Probability.DilutedSpin.FullCubeConditionalContinuity +OAI.Probability.DilutedSpin.FullPalm +OAI.Probability.DilutedSpin.FullRegularSelection +OAI.Probability.DilutedSpin.FullRootCounts +OAI.Probability.DilutedSpin.FullRootIncrement +OAI.Probability.DilutedSpin.FullRootPalm +OAI.Probability.DilutedSpin.FullSelectedConcentration +OAI.Probability.DilutedSpin.FullSelectedError +OAI.Probability.DilutedSpin.FullSelectedRawConcentration +OAI.Probability.DilutedSpin.FullSelectedRegularity +OAI.Probability.DilutedSpin.FullSelectedThermal +OAI.Probability.DilutedSpin.FullThermalAverage +OAI.Probability.DilutedSpin.FullTreeScore +OAI.Probability.DilutedSpin.FunctionalContinuity +OAI.Probability.DilutedSpin.FunctionalStability +OAI.Probability.DilutedSpin.GeneralPairSquare +OAI.Probability.DilutedSpin.GeneralRootArrayLaw +OAI.Probability.DilutedSpin.GlobalSelectedAverage +OAI.Probability.DilutedSpin.GlobalSelectedConcentration +OAI.Probability.DilutedSpin.GlobalSelectedError +OAI.Probability.DilutedSpin.GridIncrementSupport +OAI.Probability.DilutedSpin.HeightTransport +OAI.Probability.DilutedSpin.HeterogeneousFullVariance +OAI.Probability.DilutedSpin.HeterogeneousMarks +OAI.Probability.DilutedSpin.HeterogeneousProjection +OAI.Probability.DilutedSpin.HeterogeneousTwoPoisson +OAI.Probability.DilutedSpin.HeterogeneousVariance +OAI.Probability.DilutedSpin.HierarchyBasic +OAI.Probability.DilutedSpin.HistoryDistinct +OAI.Probability.DilutedSpin.HistoryGeometry +OAI.Probability.DilutedSpin.HistoryRetained +OAI.Probability.DilutedSpin.HistorySelector +OAI.Probability.DilutedSpin.IncrementCavityProxy +OAI.Probability.DilutedSpin.IncrementErrorLimit +OAI.Probability.DilutedSpin.InsertionCoefficient +OAI.Probability.DilutedSpin.InsertionPoint +OAI.Probability.DilutedSpin.InsertionPoissonAlgebra +OAI.Probability.DilutedSpin.InsertionStability +OAI.Probability.DilutedSpin.IntegralError +OAI.Probability.DilutedSpin.IntegratedFiniteUpper +OAI.Probability.DilutedSpin.JointGridSelection +OAI.Probability.DilutedSpin.JointPhysicalSelection +OAI.Probability.DilutedSpin.JointRootLaw +OAI.Probability.DilutedSpin.JointRootParam +OAI.Probability.DilutedSpin.KernelTower +OAI.Probability.DilutedSpin.LabeledColorHistory +OAI.Probability.DilutedSpin.Main +OAI.Probability.DilutedSpin.MarkInsertion +OAI.Probability.DilutedSpin.MarkMeanProjection +OAI.Probability.DilutedSpin.MarkSiteCoupling +OAI.Probability.DilutedSpin.MarkedPoisson +OAI.Probability.DilutedSpin.MarkerConcrete +OAI.Probability.DilutedSpin.MarkerGeometry +OAI.Probability.DilutedSpin.MarkerHistory +OAI.Probability.DilutedSpin.MarkerHistoryTransport +OAI.Probability.DilutedSpin.MarkerJointHistory +OAI.Probability.DilutedSpin.MarkerNormalization +OAI.Probability.DilutedSpin.MarkerPhysicalBridge +OAI.Probability.DilutedSpin.MarkerRootIdentity +OAI.Probability.DilutedSpin.MarkerScheduledIdentity +OAI.Probability.DilutedSpin.MarkerVariance +OAI.Probability.DilutedSpin.MatrixConstant +OAI.Probability.DilutedSpin.MatrixEnergy +OAI.Probability.DilutedSpin.MatrixHistory +OAI.Probability.DilutedSpin.MatrixLeafProjection +OAI.Probability.DilutedSpin.MatrixNormalization +OAI.Probability.DilutedSpin.MatrixPair +OAI.Probability.DilutedSpin.MatrixPhysical +OAI.Probability.DilutedSpin.MatrixRoot +OAI.Probability.DilutedSpin.MatrixTriple +OAI.Probability.DilutedSpin.MeasurableEncoding +OAI.Probability.DilutedSpin.MeasurableEnergy +OAI.Probability.DilutedSpin.MeasurableProjectionError +OAI.Probability.DilutedSpin.MeasurableProjector +OAI.Probability.DilutedSpin.MeasurableShapeEnergy +OAI.Probability.DilutedSpin.MeasureHierarchy +OAI.Probability.DilutedSpin.MixedDeviation +OAI.Probability.DilutedSpin.MixedEnergy +OAI.Probability.DilutedSpin.MixedPatterns +OAI.Probability.DilutedSpin.MixtureMeasures +OAI.Probability.DilutedSpin.Model +OAI.Probability.DilutedSpin.MultileafMatrixPointwise +OAI.Probability.DilutedSpin.NormalizationSymmetry +OAI.Probability.DilutedSpin.NormalizedCutoff +OAI.Probability.DilutedSpin.NormalizedInsertion +OAI.Probability.DilutedSpin.NormalizedPalm +OAI.Probability.DilutedSpin.OldEnergyEmbedding +OAI.Probability.DilutedSpin.OneNewLaw +OAI.Probability.DilutedSpin.OverlapDepthAverage +OAI.Probability.DilutedSpin.PairSquare +OAI.Probability.DilutedSpin.PalmError +OAI.Probability.DilutedSpin.ParameterConcentration +OAI.Probability.DilutedSpin.ParameterPalm +OAI.Probability.DilutedSpin.ParameterProduct +OAI.Probability.DilutedSpin.ParameterRate +OAI.Probability.DilutedSpin.ParameterScoreMeasurable +OAI.Probability.DilutedSpin.PatternComparison +OAI.Probability.DilutedSpin.Perturbations +OAI.Probability.DilutedSpin.PerturbedEnergyMean +OAI.Probability.DilutedSpin.PerturbedSizeCoupling +OAI.Probability.DilutedSpin.PhysicalAverages +OAI.Probability.DilutedSpin.PhysicalCavityPoisson +OAI.Probability.DilutedSpin.PhysicalCavityRate +OAI.Probability.DilutedSpin.PhysicalCavitySplit +OAI.Probability.DilutedSpin.PhysicalCountLaw +OAI.Probability.DilutedSpin.PhysicalEncodingInterior +OAI.Probability.DilutedSpin.PhysicalFieldOrder +OAI.Probability.DilutedSpin.PhysicalGridMultileaf +OAI.Probability.DilutedSpin.PhysicalIndex +OAI.Probability.DilutedSpin.PhysicalInsertionComparison +OAI.Probability.DilutedSpin.PhysicalInsertionEnergy +OAI.Probability.DilutedSpin.PhysicalInsertionIdentity +OAI.Probability.DilutedSpin.PhysicalInsertionLimit +OAI.Probability.DilutedSpin.PhysicalMarkerControl +OAI.Probability.DilutedSpin.PhysicalMultileafMoments +OAI.Probability.DilutedSpin.PhysicalNewSpin +OAI.Probability.DilutedSpin.PhysicalOverlapAverage +OAI.Probability.DilutedSpin.PhysicalOverlapConcentration +OAI.Probability.DilutedSpin.PhysicalOverlapLimit +OAI.Probability.DilutedSpin.PhysicalPairConnection +OAI.Probability.DilutedSpin.PhysicalPairEnergy +OAI.Probability.DilutedSpin.PhysicalReservoirIncrement +OAI.Probability.DilutedSpin.PhysicalScheduledMultileaf +OAI.Probability.DilutedSpin.PhysicalScheduledStep +OAI.Probability.DilutedSpin.PhysicalScoreRate +OAI.Probability.DilutedSpin.PhysicalSelectedConcentration +OAI.Probability.DilutedSpin.PhysicalShapeError +OAI.Probability.DilutedSpin.PhysicalSingleton +OAI.Probability.DilutedSpin.PhysicalSubtreeConcentration +OAI.Probability.DilutedSpin.PhysicalTreeMatrix +OAI.Probability.DilutedSpin.PoissonCountThinning +OAI.Probability.DilutedSpin.PoissonInsertionLimit +OAI.Probability.DilutedSpin.PoissonMoments +OAI.Probability.DilutedSpin.PoissonRateCoupling +OAI.Probability.DilutedSpin.PoissonReplacement +OAI.Probability.DilutedSpin.PoissonRootSelection +OAI.Probability.DilutedSpin.PoissonSiteThinning +OAI.Probability.DilutedSpin.PoissonSmoothing +OAI.Probability.DilutedSpin.PoissonVariance +OAI.Probability.DilutedSpin.Polarization +OAI.Probability.DilutedSpin.PrefixProjection +OAI.Probability.DilutedSpin.PressureLiminf +OAI.Probability.DilutedSpin.ProductComparison +OAI.Probability.DilutedSpin.ProductEvaluationContinuity +OAI.Probability.DilutedSpin.ProductPatterns +OAI.Probability.DilutedSpin.ProductTower +OAI.Probability.DilutedSpin.ProductTowers +OAI.Probability.DilutedSpin.ProfileHistory +OAI.Probability.DilutedSpin.ProjectionShiftError +OAI.Probability.DilutedSpin.ProperChildScheduleContinuity +OAI.Probability.DilutedSpin.ProxyRateIncrement +OAI.Probability.DilutedSpin.QIntegration +OAI.Probability.DilutedSpin.QSubsetDeviation +OAI.Probability.DilutedSpin.QSubtreePotential +OAI.Probability.DilutedSpin.QTopologyBound +OAI.Probability.DilutedSpin.QTreeLaw +OAI.Probability.DilutedSpin.RandomInsertion +OAI.Probability.DilutedSpin.RawPatternIdentity +OAI.Probability.DilutedSpin.RealEncoding +OAI.Probability.DilutedSpin.RegularBadMass +OAI.Probability.DilutedSpin.RegularCovarianceConvergence +OAI.Probability.DilutedSpin.RegularCovarianceLimit +OAI.Probability.DilutedSpin.RegularDepth +OAI.Probability.DilutedSpin.RegularFrameExtraction +OAI.Probability.DilutedSpin.RegularNodeAverage +OAI.Probability.DilutedSpin.RegularNodeEstimates +OAI.Probability.DilutedSpin.RegularNodeGeometry +OAI.Probability.DilutedSpin.RegularNodeProducer +OAI.Probability.DilutedSpin.RegularOverlapGeometry +OAI.Probability.DilutedSpin.RegularPhysicalShift +OAI.Probability.DilutedSpin.RegularScheduleShift +OAI.Probability.DilutedSpin.RegularizedNormalization +OAI.Probability.DilutedSpin.ReservoirBondEnergy +OAI.Probability.DilutedSpin.ReservoirEnergyBounds +OAI.Probability.DilutedSpin.ReservoirInsertionEnergy +OAI.Probability.DilutedSpin.ReservoirInsertionOnEnergy +OAI.Probability.DilutedSpin.ReservoirRate +OAI.Probability.DilutedSpin.ReservoirShapeLimit +OAI.Probability.DilutedSpin.ReservoirSitePoisson +OAI.Probability.DilutedSpin.ReservoirSiteTransport +OAI.Probability.DilutedSpin.ReservoirTrees +OAI.Probability.DilutedSpin.ReservoirVariance +OAI.Probability.DilutedSpin.RetainedHistory +OAI.Probability.DilutedSpin.RootAE +OAI.Probability.DilutedSpin.RootChildMoment +OAI.Probability.DilutedSpin.RootChildSumIntegrability +OAI.Probability.DilutedSpin.RootCoefficients +OAI.Probability.DilutedSpin.RootDeviationDistance +OAI.Probability.DilutedSpin.RootEncoding +OAI.Probability.DilutedSpin.RootIntegralOrder +OAI.Probability.DilutedSpin.RootLogComparison +OAI.Probability.DilutedSpin.RootMapLaw +OAI.Probability.DilutedSpin.RootMarkerEstimate +OAI.Probability.DilutedSpin.RootMatrixTriple +OAI.Probability.DilutedSpin.RootMultileafMatrix +OAI.Probability.DilutedSpin.RootOverlapBounds +OAI.Probability.DilutedSpin.RootOverlapDeviation +OAI.Probability.DilutedSpin.RootOverlapVariance +OAI.Probability.DilutedSpin.RootPatternComparison +OAI.Probability.DilutedSpin.RootPatternProduct +OAI.Probability.DilutedSpin.RootProductLaw +OAI.Probability.DilutedSpin.RootProjectionIntegrability +OAI.Probability.DilutedSpin.RootProjectionShiftError +OAI.Probability.DilutedSpin.RootShapeEnergy +OAI.Probability.DilutedSpin.RootShiftIntegrability +OAI.Probability.DilutedSpin.RootSplit +OAI.Probability.DilutedSpin.SameInsertionAverage +OAI.Probability.DilutedSpin.ScheduledContinuity +OAI.Probability.DilutedSpin.ScheduledCovariance +OAI.Probability.DilutedSpin.ScheduledEnergyBound +OAI.Probability.DilutedSpin.ScheduledEvaluationContinuity +OAI.Probability.DilutedSpin.ScheduledFrameError +OAI.Probability.DilutedSpin.ScheduledFrameGeometry +OAI.Probability.DilutedSpin.ScheduledGeometry +OAI.Probability.DilutedSpin.ScheduledMarkerEstimate +OAI.Probability.DilutedSpin.ScheduledMultileafMatrix +OAI.Probability.DilutedSpin.ScheduledProtectedLabels +OAI.Probability.DilutedSpin.ScheduledRegularFrame +OAI.Probability.DilutedSpin.ScheduledRelativeCharge +OAI.Probability.DilutedSpin.ScheduledRootMultileaf +OAI.Probability.DilutedSpin.ScheduledSelection +OAI.Probability.DilutedSpin.ScheduledSingleton +OAI.Probability.DilutedSpin.ScheduledTopology +OAI.Probability.DilutedSpin.ScoreIncrement +OAI.Probability.DilutedSpin.SelectedPalm +OAI.Probability.DilutedSpin.SelectedRegularity +OAI.Probability.DilutedSpin.SelectedTree +OAI.Probability.DilutedSpin.SelectorPolarization +OAI.Probability.DilutedSpin.ShapeCharging +OAI.Probability.DilutedSpin.ShapeEmbedding +OAI.Probability.DilutedSpin.ShapeMarginal +OAI.Probability.DilutedSpin.ShapeMatrix +OAI.Probability.DilutedSpin.ShapeMatrixPhysical +OAI.Probability.DilutedSpin.ShapeMean +OAI.Probability.DilutedSpin.ShapeProjectionEnergy +OAI.Probability.DilutedSpin.ShapeRoot +OAI.Probability.DilutedSpin.ShiftedFrameGeometry +OAI.Probability.DilutedSpin.ShiftedTree +OAI.Probability.DilutedSpin.SimultaneousShift +OAI.Probability.DilutedSpin.SingletonAverage +OAI.Probability.DilutedSpin.SingletonRoot +OAI.Probability.DilutedSpin.SingletonSelection +OAI.Probability.DilutedSpin.SizeSpinRoot +OAI.Probability.DilutedSpin.SpatialScheduledContinuity +OAI.Probability.DilutedSpin.SpinBaseComparison +OAI.Probability.DilutedSpin.SpinLogContinuous +OAI.Probability.DilutedSpin.SpinMarginal +OAI.Probability.DilutedSpin.SpinRootData +OAI.Probability.DilutedSpin.SplitDepthContinuity +OAI.Probability.DilutedSpin.StemCoupling +OAI.Probability.DilutedSpin.StemCovarianceTransfer +OAI.Probability.DilutedSpin.StemTwoSideProjection +OAI.Probability.DilutedSpin.SubsetTree +OAI.Probability.DilutedSpin.SymmetricTrialLower +OAI.Probability.DilutedSpin.TargetEvaluationContinuity +OAI.Probability.DilutedSpin.TargetScheduleContinuity +OAI.Probability.DilutedSpin.TerminalInterior +OAI.Probability.DilutedSpin.TerminalMarginal +OAI.Probability.DilutedSpin.TerminalMeanCavity +OAI.Probability.DilutedSpin.TerminalMeanField +OAI.Probability.DilutedSpin.TerminalPiRoot +OAI.Probability.DilutedSpin.TopologyChargeBound +OAI.Probability.DilutedSpin.TopologyDecay +OAI.Probability.DilutedSpin.TowerArraySplit +OAI.Probability.DilutedSpin.TowerPadding +OAI.Probability.DilutedSpin.TowerSum +OAI.Probability.DilutedSpin.TowerTerminalPad +OAI.Probability.DilutedSpin.TreeAnchor +OAI.Probability.DilutedSpin.TreeDerivatives +OAI.Probability.DilutedSpin.TreeMarkLaw +OAI.Probability.DilutedSpin.TreeMeasurable +OAI.Probability.DilutedSpin.TreeSampleProjection +OAI.Probability.DilutedSpin.TreeSampling +OAI.Probability.DilutedSpin.TrialPhysical +OAI.Probability.DilutedSpin.TripleMarginal +OAI.Probability.DilutedSpin.TwoPointLabeling +OAI.Probability.DilutedSpin.TwoSideProjection +OAI.Probability.DilutedSpin.UniformIndexCoupling +OAI.Probability.DilutedSpin.UniformRootDecorrelation +OAI.Probability.DilutedSpin.UniversalDictionary +OAI.Probability.DilutedSpin.UpperCommonCoefficient +OAI.Probability.DilutedSpin.UpperConditional +OAI.Probability.DilutedSpin.UpperCountLocal +OAI.Probability.DilutedSpin.UpperCountMean +OAI.Probability.DilutedSpin.UpperCountState +OAI.Probability.DilutedSpin.UpperDatum +OAI.Probability.DilutedSpin.UpperDatumIntegral +OAI.Probability.DilutedSpin.UpperFreshLocal +OAI.Probability.DilutedSpin.UpperInsertion +OAI.Probability.DilutedSpin.UpperMoments +OAI.Probability.DilutedSpin.UpperPoissonBound +OAI.Probability.DilutedSpin.UpperRealEndpoint +OAI.Probability.DilutedSpin.UpperRegularized +OAI.Probability.DilutedSpin.UpperReplicaPatterns +OAI.Probability.DilutedSpin.UpperRootInsertion +OAI.Probability.DilutedSpin.UpperTrial +OAI.Probability.DilutedSpin.VariationalUpper +OAI.Probability.DilutedSpin.VertexContinuity +OAI.Probability.DilutedSpin.ZeroShape diff --git a/tasks/diluted-spin/solution/reference.py b/tasks/diluted-spin/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/diluted-spin/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/diluted-spin/solution/solve.sh b/tasks/diluted-spin/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee037c78ff82ad08dbe1a6b6ba0a80f054512d5f --- /dev/null +++ b/tasks/diluted-spin/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DilutedSpin, i.e. module OAI.Probability.DilutedSpin.Main and the +# 405 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.DilutedSpin.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DilutedSpin" diff --git a/tasks/diluted-spin/task.toml b/tasks/diluted-spin/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7078f433cd6b731038d1638c9113fbf231acebdb --- /dev/null +++ b/tasks/diluted-spin/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/diluted-spin" +version = "1.0.0" +description = "Prove DilutedSpin (openai/math family 221: The Mezard–Parisi formula for diluted spin glasses) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DilutedSpin.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DilutedSpin" +family = "221" +family_title = "The Mezard–Parisi formula for diluted spin glasses" +subject = "Probability and statistical mechanics" +theorems = ["OAI.DilutedSpinGlass.mezard_parisi"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.DilutedSpin.Main" +reference_modules = 405 +reference_lean_bytes = 2760702 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1537 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14184 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/diluted-spin/tests/Challenge.lean b/tasks/diluted-spin/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d6df4eb9c837e9083c15159cd0a74947f47f759e --- /dev/null +++ b/tasks/diluted-spin/tests/Challenge.lean @@ -0,0 +1,154 @@ +import Mathlib + +namespace OAI + + + +open MeasureTheory ProbabilityTheory Filter +open scoped BigOperators ENNReal NNReal Topology + +namespace DilutedSpinGlass + +abbrev Spin := Bool + +def spin (s : Spin) : ℝ := if s then 1 else -1 + +abbrev Interaction (p : ℕ) := (Fin p → Spin) → ℝ + +/-- One interaction together with its factorization witness: theta,a,b,f. -/ +abbrev InteractionSample (p : ℕ) := + Interaction p × ℝ × ℝ × (Fin p → Spin → ℝ) + +structure Model (p : ℕ) where + alpha : ℝ≥0 + disorder : ProbabilityMeasure (InteractionSample p) + field : ProbabilityMeasure ℝ + +/-- Exactly the standing hypotheses (model:integrability through positivity). +`norm` on the finite function space is max_s |theta(s)|. -/ +structure Admissible {p : ℕ} (M : Model p) : Prop where + arity : 2 ≤ p + even : Even p + density : 0 < M.alpha + interaction_integrable : Integrable (fun z : InteractionSample p => ‖z.1‖) + M.disorder.toMeasure + field_integrable : Integrable (fun h : ℝ => |h|) M.field.toMeasure + factorization : ∀ᵐ z ∂M.disorder.toMeasure, + 0 < z.2.1 ∧ ∀ s : Fin p → Spin, + Real.exp (z.1 s) = z.2.1 * (1 + z.2.2.1 * ∏ l, z.2.2.2 l (s l)) ∧ + |z.2.2.1 * ∏ l, z.2.2.2 l (s l)| < 1 + independent_f : iIndepFun (fun l (z : InteractionSample p) => z.2.2.2 l) + M.disorder.toMeasure + identically_distributed_f : ∀ l j : Fin p, + IdentDistrib (fun z : InteractionSample p => z.2.2.2 l) + (fun z : InteractionSample p => z.2.2.2 j) + M.disorder.toMeasure M.disorder.toMeasure + independent_b : IndepFun (fun z : InteractionSample p => z.2.2.1) + (fun z : InteractionSample p => z.2.2.2) M.disorder.toMeasure + finite_b_moments : ∀ n : ℕ, 1 ≤ n → + Integrable (fun z : InteractionSample p => (-z.2.2.1) ^ n) M.disorder.toMeasure + positivity : ∀ n : ℕ, 1 ≤ n → + 0 ≤ ∫ z : InteractionSample p, (-z.2.2.1) ^ n ∂M.disorder.toMeasure + +/-- Minus the Hamiltonian, with all index choices including repetitions. -/ +noncomputable def logWeight {p N k : ℕ} (theta : Fin k → InteractionSample p) + (h : Fin N → ℝ) (indices : Fin k → Fin p → Fin N) (σ : Fin N → Spin) : ℝ := + (∑ j, (theta j).1 (fun l => σ (indices j l))) + ∑ i, h i * spin (σ i) + +noncomputable def logPartition {p N k : ℕ} (theta : Fin k → InteractionSample p) + (h : Fin N → ℝ) (indices : Fin k → Fin p → Fin N) : ℝ := + Real.log (∑ σ : Fin N → Spin, Real.exp (logWeight theta h indices σ)) + +/-- F_N, using an explicit uniform average over the independent index labels. +The value at N=0 is irrelevant to the limit; valid system sizes are N>=1. -/ +noncomputable def pressure {p : ℕ} (M : Model p) (N : ℕ) : ℝ := + (∫ k : ℕ, + ∫ theta : Fin k → InteractionSample p, + ∫ h : Fin N → ℝ, + ((∑ indices : Fin k → Fin p → Fin N, logPartition theta h indices) / + (Fintype.card (Fin k → Fin p → Fin N) : ℝ)) + ∂Measure.pi (fun _ : Fin N => M.field.toMeasure) + ∂Measure.pi (fun _ : Fin k => M.disorder.toMeasure) + ∂poissonMeasure (M.alpha * N)) / N + +noncomputable def q (x : ℝ) (s : Spin) : ℝ := + Real.exp (x * spin s) / (2 * Real.cosh x) + +noncomputable def edge {p : ℕ} (theta : Interaction p) (x : Fin p → ℝ) : ℝ := + ∑ s : Fin p → Spin, Real.exp (theta s) * ∏ l, q (x l) (s l) + +/-- Append the distinguished cavity spin in the last position. -/ +def appendSpin {p : ℕ} (s : Fin (p - 1) → Spin) (ε : Spin) (l : Fin p) : Spin := + if h : l.val < p - 1 then s ⟨l.val, h⟩ else ε + +noncomputable def message {p : ℕ} (theta : Interaction p) + (x : Fin (p - 1) → ℝ) (ε : Spin) : ℝ := + Real.log (∑ s : Fin (p - 1) → Spin, + Real.exp (theta (appendSpin s ε)) * ∏ l, q (x l) (s l)) + +noncomputable def siteLog {p k : ℕ} (theta : Fin k → InteractionSample p) + (h : ℝ) (x : (Fin k × Fin (p - 1)) → ℝ) : ℝ := + Real.log ((∑ ε : Spin, Real.exp + (h * spin ε + ∑ j, message (theta j).1 (fun l => x (j, l)) ε)) / 2) + +/-- Use literally the Borel sigma-field of the weak topology at each level, +as stipulated in model.tex. -/ +local instance instMeasurableSpaceCarrier_challenge (X : TopCat) : MeasurableSpace X := borel X +local instance instBorelSpaceCarrier_challenge (X : TopCat) : BorelSpace X := ⟨rfl⟩ + +/-- Nested probability laws: H_0=R and H_{j+1}=P(H_j), with weak topologies. -/ +noncomputable def Hierarchy : ℕ → TopCat + | 0 => TopCat.of ℝ + | r + 1 => TopCat.of (ProbabilityMeasure (Hierarchy r)) + +/-- Logarithmic form of the conditional power means T_0 using independent +message labels. The current eta's are held fixed; only their descendants +are integrated. Physical disorder is a fixed argument of g throughout. -/ +noncomputable def logMean {ι : Type} [Fintype ι] : + (r : ℕ) → ((ι → ℝ) → ℝ) → (Fin r → ℝ) → (ι → Hierarchy r) → ℝ + | 0, g, _, x => g x + | r + 1, g, m, eta => + Real.log (∫ x : ι → Hierarchy r, + Real.exp (m 0 * logMean r g (fun i => m i.succ) x) + ∂Measure.pi (fun i => (eta i).toMeasure)) / m 0 + +/-- Expectation over the root laws eta_0 of each independent message label. +This also gives the r=0 convention (iid real messages, no power means). -/ +noncomputable def trialLog {ι : Type} [Fintype ι] (r : ℕ) + (ζ : Hierarchy (r + 1)) (m : Fin r → ℝ) (g : (ι → ℝ) → ℝ) : ℝ := + ∫ eta : ι → Hierarchy r, logMean r g m eta + ∂Measure.pi (fun _ : ι => ζ.toMeasure) + +/-- Admissible exponents 0 M.disorder.toMeasure) + ∂poissonMeasure (M.alpha * p)) - + (M.alpha : ℝ) * (p - 1 : ℕ) * + (∫ theta : InteractionSample p, + trialLog r ζ m (fun x => Real.log (edge theta.1 x)) ∂M.disorder.toMeasure) + +noncomputable def phi {p : ℕ} (M : Model p) (r : ℕ) : ℝ := + sInf {v : ℝ | ∃ (ζ : Hierarchy (r + 1)) (m : Fin r → ℝ), + Exponents m ∧ v = functional M r ζ m} + +noncomputable def variationalValue {p : ℕ} (M : Model p) : ℝ := + ⨅ r : ℕ, phi M r + +/-- main:theorem. No boundedness of interactions, fields, or messages is added. +Existence of the thermodynamic limit is part of this convergence assertion. -/ +theorem mezard_parisi {p : ℕ} (M : Model p) (hM : Admissible M) : + Tendsto (pressure M) atTop (𝓝 (variationalValue M)) := by + sorry + +end DilutedSpinGlass + +end OAI diff --git a/tasks/diluted-spin/tests/grade.py b/tasks/diluted-spin/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/diluted-spin/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/diluted-spin/tests/task.json b/tasks/diluted-spin/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..478437cd14d2faeff8d42f10484106b3ee5a2d46 --- /dev/null +++ b/tasks/diluted-spin/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DilutedSpin", + "comparator": { + "theorem_names": [ + "OAI.DilutedSpinGlass.mezard_parisi" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13284 +} \ No newline at end of file diff --git a/tasks/diluted-spin/tests/test.sh b/tasks/diluted-spin/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/diluted-spin/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dimension-ten-channel/environment/Dockerfile b/tasks/dimension-ten-channel/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dimension-ten-channel/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dimension-ten-channel/environment/fetch_mathlib.sh b/tasks/dimension-ten-channel/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dimension-ten-channel/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dimension-ten-channel/environment/lake-manifest.json b/tasks/dimension-ten-channel/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dimension-ten-channel/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dimension-ten-channel/environment/lakefile.lean b/tasks/dimension-ten-channel/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dimension-ten-channel/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dimension-ten-channel/environment/lean_setup.sh b/tasks/dimension-ten-channel/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dimension-ten-channel/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dimension-ten-channel/environment/pack_submission.py b/tasks/dimension-ten-channel/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dimension-ten-channel/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dimension-ten-channel/instruction.md b/tasks/dimension-ten-channel/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3e7dc8aad092e7fa6ffcf6980175065334d0dd1a --- /dev/null +++ b/tasks/dimension-ten-channel/instruction.md @@ -0,0 +1,106 @@ +# openai/math challenge `DimensionTenChannel` (family 272) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 272 of the release, *Entanglement without secret key and the PPT-square conjecture* +(Mathematical physics). The family as a whole: Constructs an entangled state on $\mathbb C^{10}\otimes\mathbb C^{10}$ with zero distillable secret key for the specified local-instrument protocols that complete almost surely. These allow joint local processing and authenticated two-way public communication, with no other shared private resource and an eavesdropper holding the input purification and public record. A trace-preserving PPT channel on $M_{21}(\mathbb C)$ whose square is not entanglement breaking disproves Christandl\textquotesingle s PPT-square conjecture. + +The challenge is `DimensionTenChannel`, also at `/opt/openai-math/challenges/DimensionTenChannel.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ComplexOrder Kronecker MatrixOrder +open Matrix + +namespace ChannelCompletion + +abbrev Mat (n : Type) := Matrix n n ℂ +abbrev Map (n m : Type) := Mat n →ₗ[ℂ] Mat m + +variable {n m p : Type} [Fintype n] [Fintype m] [Fintype p] + +def amplify (F : Map n m) {k : Type} (X : Mat (k × n)) : Mat (k × m) := + fun a b => F (fun i j => X (a.1, i) (b.1, j)) a.2 b.2 + +def CP (F : Map n m) : Prop := + ∀ (k : Type) [Fintype k] (X : Mat (k × n)), X.PosSemidef → (amplify F X).PosSemidef + +def transposeMap : Map n n where + toFun := Matrix.transpose + map_add' _ _ := rfl + map_smul' _ _ := rfl + +def PPT (F : Map n m) : Prop := CP F ∧ CP (transposeMap.comp F) + +def TracePreserving (F : Map n m) : Prop := ∀ X, Matrix.trace (F X) = Matrix.trace X + +def Separable (Z : Mat (n × m)) : Prop := + ∃ (r : ℕ) (A : Fin r → Mat n) (B : Fin r → Mat m), + (∀ i, (A i).PosSemidef) ∧ (∀ i, (B i).PosSemidef) ∧ + Z = ∑ i, A i ⊗ₖ B i + +def EntanglementBreaking (F : Map n m) : Prop := + CP F ∧ ∀ (k : Type) [Fintype k] (X : Mat (k × n)), + X.PosSemidef → Separable (amplify F X) + +end ChannelCompletion + +namespace DimensionTen + +/-- A trace-preserving PPT channel on twenty-one dimensions with a non-entanglement-breaking square. -/ +theorem exists_channel_fin21 : + ∃ Θ : ChannelCompletion.Map (Fin 21) (Fin 21), + ChannelCompletion.PPT Θ ∧ ChannelCompletion.TracePreserving Θ ∧ + ¬ ChannelCompletion.EntanglementBreaking (Θ.comp Θ) := by + sorry + +end DimensionTen + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DimensionTenChannel.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DimensionTen.exists_channel_fin21` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dimension-ten-channel/solution/closure.txt b/tasks/dimension-ten-channel/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..127e277d1dc1f85b2a5e44f9615bcd4a044b34ed --- /dev/null +++ b/tasks/dimension-ten-channel/solution/closure.txt @@ -0,0 +1,148 @@ +OAI.Analysis.Quantum.DimensionTen.AlphaMinors +OAI.Analysis.Quantum.DimensionTen.Annihilator +OAI.Analysis.Quantum.DimensionTen.BorderData +OAI.Analysis.Quantum.DimensionTen.BorderField +OAI.Analysis.Quantum.DimensionTen.BorderRelations +OAI.Analysis.Quantum.DimensionTen.Channel +OAI.Analysis.Quantum.DimensionTen.ChoiPairing +OAI.Analysis.Quantum.DimensionTen.Cofactors +OAI.Analysis.Quantum.DimensionTen.CompoundTrace +OAI.Analysis.Quantum.DimensionTen.EigenAdjoin +OAI.Analysis.Quantum.DimensionTen.EigenData +OAI.Analysis.Quantum.DimensionTen.EvaluationMinors +OAI.Analysis.Quantum.DimensionTen.ExteriorEvaluation +OAI.Analysis.Quantum.DimensionTen.ExteriorMaps +OAI.Analysis.Quantum.DimensionTen.FamilyGeometry +OAI.Analysis.Quantum.DimensionTen.FieldRepresentation +OAI.Analysis.Quantum.DimensionTen.FrobeniusRoots +OAI.Analysis.Quantum.DimensionTen.GaloisCertificate +OAI.Analysis.Quantum.DimensionTen.GaloisField +OAI.Analysis.Quantum.DimensionTen.IndependentMinor +OAI.Analysis.Quantum.DimensionTen.IntegerPolynomials +OAI.Analysis.Quantum.DimensionTen.Kraus +OAI.Analysis.Quantum.DimensionTen.LowBasis +OAI.Analysis.Quantum.DimensionTen.Main +OAI.Analysis.Quantum.DimensionTen.MinorData +OAI.Analysis.Quantum.DimensionTen.MinorRelations +OAI.Analysis.Quantum.DimensionTen.Mod131Model +OAI.Analysis.Quantum.DimensionTen.Mod131Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod131Result +OAI.Analysis.Quantum.DimensionTen.Mod139Model +OAI.Analysis.Quantum.DimensionTen.Mod139Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers10 +OAI.Analysis.Quantum.DimensionTen.Mod139Result +OAI.Analysis.Quantum.DimensionTen.Mod41Model +OAI.Analysis.Quantum.DimensionTen.Mod41Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers10 +OAI.Analysis.Quantum.DimensionTen.Mod41Result +OAI.Analysis.Quantum.DimensionTen.ModularPermutations +OAI.Analysis.Quantum.DimensionTen.NormalizedMatrices +OAI.Analysis.Quantum.DimensionTen.PencilKraus +OAI.Analysis.Quantum.DimensionTen.PencilModel +OAI.Analysis.Quantum.DimensionTen.PencilPoints +OAI.Analysis.Quantum.DimensionTen.PolynomialData +OAI.Analysis.Quantum.DimensionTen.PureMatrices +OAI.Analysis.Quantum.DimensionTen.QuadraticBounds +OAI.Analysis.Quantum.DimensionTen.RootPermutation +OAI.Analysis.Quantum.DimensionTen.RootReduction +OAI.Analysis.Quantum.DimensionTen.TensorKraus +OAI.Analysis.Quantum.DimensionTen.TensorSymmetry +OAI.Analysis.Quantum.DimensionTen.TwentyDirections +OAI.Analysis.Quantum.DimensionTen.Veronese +OAI.Analysis.Quantum.PPTSquare.AffineMinors +OAI.Analysis.Quantum.PPTSquare.AlgebraData +OAI.Analysis.Quantum.PPTSquare.ChannelCompletion +OAI.Analysis.Quantum.PPTSquare.ChannelModel +OAI.Analysis.Quantum.PPTSquare.Commutators +OAI.Analysis.Quantum.PPTSquare.Compression +OAI.Analysis.Quantum.PPTSquare.Directions +OAI.Analysis.Quantum.PPTSquare.EigenGalois +OAI.Analysis.Quantum.PPTSquare.EigenRows +OAI.Analysis.Quantum.PPTSquare.Evaluation +OAI.Analysis.Quantum.PPTSquare.ExplicitMaps +OAI.Analysis.Quantum.PPTSquare.FieldExtension +OAI.Analysis.Quantum.PPTSquare.GaloisAction +OAI.Analysis.Quantum.PPTSquare.InfinityMinors +OAI.Analysis.Quantum.PPTSquare.MatrixInverse +OAI.Analysis.Quantum.PPTSquare.MatrixSelection +OAI.Analysis.Quantum.PPTSquare.Mod131Data +OAI.Analysis.Quantum.PPTSquare.Mod131Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod131Products +OAI.Analysis.Quantum.PPTSquare.Mod131Reduction +OAI.Analysis.Quantum.PPTSquare.Mod131Result +OAI.Analysis.Quantum.PPTSquare.Mod139Data +OAI.Analysis.Quantum.PPTSquare.Mod139Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers05 +OAI.Analysis.Quantum.PPTSquare.Mod139Products +OAI.Analysis.Quantum.PPTSquare.Mod139Reduction +OAI.Analysis.Quantum.PPTSquare.Mod139Result +OAI.Analysis.Quantum.PPTSquare.Mod41Data +OAI.Analysis.Quantum.PPTSquare.Mod41Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers05 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers06 +OAI.Analysis.Quantum.PPTSquare.Mod41Products +OAI.Analysis.Quantum.PPTSquare.Mod41Reduction +OAI.Analysis.Quantum.PPTSquare.Mod41Result +OAI.Analysis.Quantum.PPTSquare.Modular +OAI.Analysis.Quantum.PPTSquare.ModularSupport +OAI.Analysis.Quantum.PPTSquare.Multiplication +OAI.Analysis.Quantum.PPTSquare.OrderedChannel +OAI.Analysis.Quantum.PPTSquare.PairResult +OAI.Analysis.Quantum.PPTSquare.PencilData +OAI.Analysis.Quantum.PPTSquare.PencilGeometry +OAI.Analysis.Quantum.PPTSquare.PencilPoints +OAI.Analysis.Quantum.PPTSquare.QuadraticBasis +OAI.Analysis.Quantum.PPTSquare.QuadraticCriterion +OAI.Analysis.Quantum.PPTSquare.QuadraticEvaluation +OAI.Analysis.Quantum.PPTSquare.Recurrence +OAI.Analysis.Quantum.PPTSquare.SplittingField +OAI.Analysis.Quantum.PPTSquare.SplittingSetup +OAI.Analysis.Quantum.PPTSquare.SymmetricVectors +OAI.Analysis.Quantum.PPTSquare.TensorModel +OAI.Analysis.Quantum.PPTSquare.TensorPositivity +OAI.Analysis.Quantum.PPTSquare.TraceCompletion +OAI.InformationTheory.DimensionTen.ChoiTransfer +OAI.InformationTheory.SecretKey.Construction +OAI.InformationTheory.SecretKey.Discussion +OAI.InformationTheory.SecretKey.Extensions +OAI.InformationTheory.SecretKey.Gap +OAI.InformationTheory.SecretKey.KeyRate +OAI.InformationTheory.SecretKey.Main +OAI.InformationTheory.SecretKey.MatrixBasics +OAI.InformationTheory.SecretKey.MatrixMeasure +OAI.InformationTheory.SecretKey.Model +OAI.InformationTheory.SecretKey.Purification +OAI.InformationTheory.SecretKey.Sampling diff --git a/tasks/dimension-ten-channel/solution/reference.py b/tasks/dimension-ten-channel/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dimension-ten-channel/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dimension-ten-channel/solution/solve.sh b/tasks/dimension-ten-channel/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd7eba1f0763ef39f41cb58dcf0e6cfee0611818 --- /dev/null +++ b/tasks/dimension-ten-channel/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DimensionTenChannel, i.e. module OAI.Analysis.Quantum.DimensionTen.Channel and the +# 148 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Quantum.DimensionTen.Channel /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DimensionTenChannel" diff --git a/tasks/dimension-ten-channel/task.toml b/tasks/dimension-ten-channel/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90f23bebbd4ad87c2e4c5cd3c5963ef5e06b68c1 --- /dev/null +++ b/tasks/dimension-ten-channel/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dimension-ten-channel" +version = "1.0.0" +description = "Prove DimensionTenChannel (openai/math family 272: Entanglement without secret key and the PPT-square conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DimensionTenChannel.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DimensionTenChannel" +family = "272" +family_title = "Entanglement without secret key and the PPT-square conjecture" +subject = "Mathematical physics" +theorems = ["OAI.DimensionTen.exists_channel_fin21"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Quantum.DimensionTen.Channel" +reference_modules = 148 +reference_lean_bytes = 3075057 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2360 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14467 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dimension-ten-channel/tests/Challenge.lean b/tasks/dimension-ten-channel/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..229466188e477a520b3a2250fc5981da4d447d67 --- /dev/null +++ b/tasks/dimension-ten-channel/tests/Challenge.lean @@ -0,0 +1,55 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ComplexOrder Kronecker MatrixOrder +open Matrix + +namespace ChannelCompletion + +abbrev Mat (n : Type) := Matrix n n ℂ +abbrev Map (n m : Type) := Mat n →ₗ[ℂ] Mat m + +variable {n m p : Type} [Fintype n] [Fintype m] [Fintype p] + +def amplify (F : Map n m) {k : Type} (X : Mat (k × n)) : Mat (k × m) := + fun a b => F (fun i j => X (a.1, i) (b.1, j)) a.2 b.2 + +def CP (F : Map n m) : Prop := + ∀ (k : Type) [Fintype k] (X : Mat (k × n)), X.PosSemidef → (amplify F X).PosSemidef + +def transposeMap : Map n n where + toFun := Matrix.transpose + map_add' _ _ := rfl + map_smul' _ _ := rfl + +def PPT (F : Map n m) : Prop := CP F ∧ CP (transposeMap.comp F) + +def TracePreserving (F : Map n m) : Prop := ∀ X, Matrix.trace (F X) = Matrix.trace X + +def Separable (Z : Mat (n × m)) : Prop := + ∃ (r : ℕ) (A : Fin r → Mat n) (B : Fin r → Mat m), + (∀ i, (A i).PosSemidef) ∧ (∀ i, (B i).PosSemidef) ∧ + Z = ∑ i, A i ⊗ₖ B i + +def EntanglementBreaking (F : Map n m) : Prop := + CP F ∧ ∀ (k : Type) [Fintype k] (X : Mat (k × n)), + X.PosSemidef → Separable (amplify F X) + +end ChannelCompletion + +namespace DimensionTen + +/-- A trace-preserving PPT channel on twenty-one dimensions with a non-entanglement-breaking square. -/ +theorem exists_channel_fin21 : + ∃ Θ : ChannelCompletion.Map (Fin 21) (Fin 21), + ChannelCompletion.PPT Θ ∧ ChannelCompletion.TracePreserving Θ ∧ + ¬ ChannelCompletion.EntanglementBreaking (Θ.comp Θ) := by + sorry + +end DimensionTen + +end + +end OAI diff --git a/tasks/dimension-ten-channel/tests/grade.py b/tasks/dimension-ten-channel/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dimension-ten-channel/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dimension-ten-channel/tests/task.json b/tasks/dimension-ten-channel/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..04308f639e0028e4443e416f690831bf5123262a --- /dev/null +++ b/tasks/dimension-ten-channel/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DimensionTenChannel", + "comparator": { + "theorem_names": [ + "OAI.DimensionTen.exists_channel_fin21" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13567 +} \ No newline at end of file diff --git a/tasks/dimension-ten-channel/tests/test.sh b/tasks/dimension-ten-channel/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dimension-ten-channel/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dimension-ten-pair/environment/Dockerfile b/tasks/dimension-ten-pair/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dimension-ten-pair/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dimension-ten-pair/environment/fetch_mathlib.sh b/tasks/dimension-ten-pair/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dimension-ten-pair/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dimension-ten-pair/environment/lake-manifest.json b/tasks/dimension-ten-pair/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dimension-ten-pair/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dimension-ten-pair/environment/lakefile.lean b/tasks/dimension-ten-pair/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dimension-ten-pair/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dimension-ten-pair/environment/lean_setup.sh b/tasks/dimension-ten-pair/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dimension-ten-pair/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dimension-ten-pair/environment/pack_submission.py b/tasks/dimension-ten-pair/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dimension-ten-pair/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dimension-ten-pair/instruction.md b/tasks/dimension-ten-pair/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d421082bd174d45f7547335c92c5890b61af418a --- /dev/null +++ b/tasks/dimension-ten-pair/instruction.md @@ -0,0 +1,176 @@ +# openai/math challenge `DimensionTenPair` (family 272) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 272 of the release, *Entanglement without secret key and the PPT-square conjecture* +(Mathematical physics). The family as a whole: Constructs an entangled state on $\mathbb C^{10}\otimes\mathbb C^{10}$ with zero distillable secret key for the specified local-instrument protocols that complete almost surely. These allow joint local processing and authenticated two-way public communication, with no other shared private resource and an eavesdropper holding the input purification and public record. A trace-preserving PPT channel on $M_{21}(\mathbb C)$ whose square is not entanglement breaking disproves Christandl\textquotesingle s PPT-square conjecture. + +The challenge is `DimensionTenPair`, also at `/opt/openai-math/challenges/DimensionTenPair.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped Matrix ComplexOrder +open Matrix Complex +namespace DimensionTen + +def blocksZ : Fin 4 → Matrix (Fin 6) (Fin 4) ℤ := + ![ ![ ![6,0,0,0], ![0,6,0,0], ![0,0,6,0], ![0,0,0,6], ![0,0,0,0], ![0,0,0,0] ], + ![ ![-12,0,0,0], ![0,-6,0,0], ![0,0,6,0], ![0,0,0,12], ![-6,0,6,6], ![-6,-6,6,0] ], + ![ ![0,6,-2,0], ![6,6,0,2], ![-2,0,10,0], ![0,2,0,24], ![0,0,0,6], ![0,-6,6,-6] ], + ![ ![0,0,-4,-3], ![0,-2,-3,-4], ![-4,-3,11,6], ![-3,-4,6,25], ![6,6,0,0], ![0,-6,6,6] ] ] + +def blocks (i : Fin 4) : Matrix (Fin 6) (Fin 4) ℂ := + (blocksZ i).map (Int.castRingHom ℂ) + +def pencilMap (A : Matrix (Fin 4) (Fin 4) ℂ) : Matrix (Fin 4) (Fin 4) ℂ := + ∑ i : Fin 4, ∑ j : Fin 4, A i j • ((blocks i)ᵀ * blocks j) + +abbrev Mat (n : ℕ) := Matrix (Fin n) (Fin n) ℂ + +def IsComplexLinear {a b : ℕ} (F : Mat a → Mat b) : Prop := + (∀ A B, F (A + B) = F A + F B) ∧ + (∀ (c : ℂ) A, F (c • A) = c • F A) + +def amplify {a b : ℕ} (F : Mat a → Mat b) (k : ℕ) + (X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ) : + Matrix (Fin k × Fin b) (Fin k × Fin b) ℂ := + fun u v => F (fun i j => X (u.1, i) (v.1, j)) u.2 v.2 + +def CompletelyPositive {a b : ℕ} (F : Mat a → Mat b) : Prop := + ∀ k : ℕ, 0 < k → ∀ X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ, + X.PosSemidef → (amplify F k X).PosSemidef + +def PPT {a b : ℕ} (F : Mat a → Mat b) : Prop := + IsComplexLinear F ∧ CompletelyPositive F ∧ + CompletelyPositive (fun X => (F X)ᵀ) + +def separable {a b : ℕ} (X : Matrix (Fin a × Fin b) (Fin a × Fin b) ℂ) : Prop := + ∃ r : ℕ, ∃ A : Fin r → Mat a, ∃ B : Fin r → Mat b, + (∀ i, (A i).PosSemidef ∧ (B i).PosSemidef) ∧ + X = ∑ i, Matrix.kronecker (A i) (B i) + +def EntanglementBreaking {a b : ℕ} (F : Mat a → Mat b) : Prop := + CompletelyPositive F ∧ + ∀ k : ℕ, 0 < k → ∀ X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ, + X.PosSemidef → separable (amplify F k X) + +def choi {a b : ℕ} (F : Mat a → Mat b) : + Matrix (Fin a × Fin b) (Fin a × Fin b) ℂ := + fun u v => F (Matrix.single u.1 v.1 1) u.2 v.2 + +def tensorMap {a b c d : ℕ} (F : Mat a → Mat b) (G : Mat c → Mat d) + (X : Matrix (Fin a × Fin c) (Fin a × Fin c) ℂ) : + Matrix (Fin b × Fin d) (Fin b × Fin d) ℂ := + ∑ i : Fin c, ∑ j : Fin c, + Matrix.kronecker (F (fun a b => X (a, i) (b, j))) (G (Matrix.single i j 1)) + +def hsAdjoint {a b : ℕ} (F : Mat a → Mat b) (Y : Mat b) : Mat a := + fun i j => ∑ u : Fin b, ∑ v : Fin b, star (F (Matrix.single i j 1) u v) * Y u v + +def symmetricPairs : Fin 10 → Fin 4 × Fin 4 := + ![(0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)] + +def exteriorPairs : Fin 6 → Fin 4 × Fin 4 := + ![(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)] + +def symmetricIsometry : Matrix (Fin 4 × Fin 4) (Fin 10) ℂ := + fun ij a => + let p := (symmetricPairs a).1 + let q := (symmetricPairs a).2 + if p = q then (if ij = (p,p) then 1 else 0) + else ((if ij = (p,q) then 1 else 0) + (if ij = (q,p) then 1 else 0)) / + (Real.sqrt 2 : ℂ) + +def exteriorIsometry : Matrix (Fin 4 × Fin 4) (Fin 6) ℂ := + fun ij a => + let p := (exteriorPairs a).1 + let q := (exteriorPairs a).2 + ((if ij = (p,q) then 1 else 0) - (if ij = (q,p) then 1 else 0)) / + (Real.sqrt 2 : ℂ) + +def hodgeComplement : Mat 6 := + ![ ![0,0,0,0,0,1], ![0,0,0,0,-1,0], ![0,0,0,1,0,0], + ![0,0,1,0,0,0], ![0,-1,0,0,0,0], ![1,0,0,0,0,0] ] + +def firstSix : Matrix (Fin 10) (Fin 6) ℂ := + fun i j => if i.val = j.val then 1 else 0 + +def exteriorMap (A : Mat 10) : Mat 6 := + exteriorIsometryᴴ * + tensorMap pencilMap pencilMap (symmetricIsometry * A * symmetricIsometryᴴ) * + exteriorIsometry + +def complementaryMap (A : Mat 10) : Mat 6 := + hodgeComplement * (exteriorMap A)ᵀ * hodgeComplementᴴ + +def phiOne (A : Mat 10) : Mat 10 := + firstSix * exteriorMap Aᵀ * firstSixᴴ + +def phiTwo (B : Mat 10) : Mat 10 := + hsAdjoint complementaryMap (firstSixᴴ * B * firstSix) + +def compositeChoi : Matrix (Fin 10 × Fin 10) (Fin 10 × Fin 10) ℂ := + choi (phiTwo ∘ phiOne) + +def productVector {a b : ℕ} (u : Fin a → ℂ) (v : Fin b → ℂ) : Fin a × Fin b → ℂ := + fun ij => u ij.1 * v ij.2 + +theorem main_pair : + ∃ Φ₁ Φ₂ : Mat 10 → Mat 10, + Φ₁ = phiOne ∧ Φ₂ = phiTwo ∧ PPT Φ₁ ∧ PPT Φ₂ ∧ + (let Z := choi (Φ₂ ∘ Φ₁) + Z ≠ 0 ∧ + (∀ u v : Fin 10 → ℂ, ∀ w : Fin 10 × Fin 10 → ℂ, + Z *ᵥ w = productVector u v → u = 0 ∨ v = 0) ∧ + ¬ EntanglementBreaking (Φ₂ ∘ Φ₁)) := by + sorry + +end DimensionTen +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DimensionTenPair.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DimensionTen.main_pair` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dimension-ten-pair/solution/closure.txt b/tasks/dimension-ten-pair/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e38a795be4bbcc345e20421e67d5db8e709d0354 --- /dev/null +++ b/tasks/dimension-ten-pair/solution/closure.txt @@ -0,0 +1,129 @@ +OAI.Analysis.Quantum.DimensionTen.AlphaMinors +OAI.Analysis.Quantum.DimensionTen.Annihilator +OAI.Analysis.Quantum.DimensionTen.BorderData +OAI.Analysis.Quantum.DimensionTen.BorderField +OAI.Analysis.Quantum.DimensionTen.BorderRelations +OAI.Analysis.Quantum.DimensionTen.ChoiPairing +OAI.Analysis.Quantum.DimensionTen.Cofactors +OAI.Analysis.Quantum.DimensionTen.CompoundTrace +OAI.Analysis.Quantum.DimensionTen.EigenAdjoin +OAI.Analysis.Quantum.DimensionTen.EigenData +OAI.Analysis.Quantum.DimensionTen.EvaluationMinors +OAI.Analysis.Quantum.DimensionTen.ExteriorEvaluation +OAI.Analysis.Quantum.DimensionTen.ExteriorMaps +OAI.Analysis.Quantum.DimensionTen.FamilyGeometry +OAI.Analysis.Quantum.DimensionTen.FieldRepresentation +OAI.Analysis.Quantum.DimensionTen.FrobeniusRoots +OAI.Analysis.Quantum.DimensionTen.GaloisCertificate +OAI.Analysis.Quantum.DimensionTen.GaloisField +OAI.Analysis.Quantum.DimensionTen.IndependentMinor +OAI.Analysis.Quantum.DimensionTen.IntegerPolynomials +OAI.Analysis.Quantum.DimensionTen.Kraus +OAI.Analysis.Quantum.DimensionTen.LowBasis +OAI.Analysis.Quantum.DimensionTen.Main +OAI.Analysis.Quantum.DimensionTen.MinorData +OAI.Analysis.Quantum.DimensionTen.MinorRelations +OAI.Analysis.Quantum.DimensionTen.Mod131Model +OAI.Analysis.Quantum.DimensionTen.Mod131Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod131Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod131Result +OAI.Analysis.Quantum.DimensionTen.Mod139Model +OAI.Analysis.Quantum.DimensionTen.Mod139Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod139Powers10 +OAI.Analysis.Quantum.DimensionTen.Mod139Result +OAI.Analysis.Quantum.DimensionTen.Mod41Model +OAI.Analysis.Quantum.DimensionTen.Mod41Powers01 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers02 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers03 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers04 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers05 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers06 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers07 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers08 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers09 +OAI.Analysis.Quantum.DimensionTen.Mod41Powers10 +OAI.Analysis.Quantum.DimensionTen.Mod41Result +OAI.Analysis.Quantum.DimensionTen.ModularPermutations +OAI.Analysis.Quantum.DimensionTen.NormalizedMatrices +OAI.Analysis.Quantum.DimensionTen.PencilKraus +OAI.Analysis.Quantum.DimensionTen.PencilModel +OAI.Analysis.Quantum.DimensionTen.PencilPoints +OAI.Analysis.Quantum.DimensionTen.PolynomialData +OAI.Analysis.Quantum.DimensionTen.PureMatrices +OAI.Analysis.Quantum.DimensionTen.QuadraticBounds +OAI.Analysis.Quantum.DimensionTen.RootPermutation +OAI.Analysis.Quantum.DimensionTen.RootReduction +OAI.Analysis.Quantum.DimensionTen.TensorKraus +OAI.Analysis.Quantum.DimensionTen.TensorSymmetry +OAI.Analysis.Quantum.DimensionTen.TwentyDirections +OAI.Analysis.Quantum.DimensionTen.Veronese +OAI.Analysis.Quantum.PPTSquare.AffineMinors +OAI.Analysis.Quantum.PPTSquare.AlgebraData +OAI.Analysis.Quantum.PPTSquare.ChannelCompletion +OAI.Analysis.Quantum.PPTSquare.ChannelModel +OAI.Analysis.Quantum.PPTSquare.Commutators +OAI.Analysis.Quantum.PPTSquare.Compression +OAI.Analysis.Quantum.PPTSquare.Directions +OAI.Analysis.Quantum.PPTSquare.EigenGalois +OAI.Analysis.Quantum.PPTSquare.EigenRows +OAI.Analysis.Quantum.PPTSquare.Evaluation +OAI.Analysis.Quantum.PPTSquare.FieldExtension +OAI.Analysis.Quantum.PPTSquare.GaloisAction +OAI.Analysis.Quantum.PPTSquare.InfinityMinors +OAI.Analysis.Quantum.PPTSquare.MatrixInverse +OAI.Analysis.Quantum.PPTSquare.MatrixSelection +OAI.Analysis.Quantum.PPTSquare.Mod131Data +OAI.Analysis.Quantum.PPTSquare.Mod131Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod131Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod131Products +OAI.Analysis.Quantum.PPTSquare.Mod131Reduction +OAI.Analysis.Quantum.PPTSquare.Mod131Result +OAI.Analysis.Quantum.PPTSquare.Mod139Data +OAI.Analysis.Quantum.PPTSquare.Mod139Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod139Powers05 +OAI.Analysis.Quantum.PPTSquare.Mod139Products +OAI.Analysis.Quantum.PPTSquare.Mod139Reduction +OAI.Analysis.Quantum.PPTSquare.Mod139Result +OAI.Analysis.Quantum.PPTSquare.Mod41Data +OAI.Analysis.Quantum.PPTSquare.Mod41Powers01 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers02 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers03 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers04 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers05 +OAI.Analysis.Quantum.PPTSquare.Mod41Powers06 +OAI.Analysis.Quantum.PPTSquare.Mod41Products +OAI.Analysis.Quantum.PPTSquare.Mod41Reduction +OAI.Analysis.Quantum.PPTSquare.Mod41Result +OAI.Analysis.Quantum.PPTSquare.Modular +OAI.Analysis.Quantum.PPTSquare.ModularSupport +OAI.Analysis.Quantum.PPTSquare.Multiplication +OAI.Analysis.Quantum.PPTSquare.PencilData +OAI.Analysis.Quantum.PPTSquare.PencilGeometry +OAI.Analysis.Quantum.PPTSquare.PencilPoints +OAI.Analysis.Quantum.PPTSquare.QuadraticBasis +OAI.Analysis.Quantum.PPTSquare.QuadraticEvaluation +OAI.Analysis.Quantum.PPTSquare.Recurrence +OAI.Analysis.Quantum.PPTSquare.SplittingField +OAI.Analysis.Quantum.PPTSquare.SplittingSetup +OAI.Analysis.Quantum.PPTSquare.TensorModel +OAI.Analysis.Quantum.PPTSquare.TraceCompletion diff --git a/tasks/dimension-ten-pair/solution/reference.py b/tasks/dimension-ten-pair/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dimension-ten-pair/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dimension-ten-pair/solution/solve.sh b/tasks/dimension-ten-pair/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bd1398773bf21c0ede3cd5aa94e830d3a0748306 --- /dev/null +++ b/tasks/dimension-ten-pair/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DimensionTenPair, i.e. module OAI.Analysis.Quantum.DimensionTen.Main and the +# 129 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Quantum.DimensionTen.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DimensionTenPair" diff --git a/tasks/dimension-ten-pair/task.toml b/tasks/dimension-ten-pair/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..01c77e01b062d46415c90505a35ae63b8a765def --- /dev/null +++ b/tasks/dimension-ten-pair/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dimension-ten-pair" +version = "1.0.0" +description = "Prove DimensionTenPair (openai/math family 272: Entanglement without secret key and the PPT-square conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DimensionTenPair.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DimensionTenPair" +family = "272" +family_title = "Entanglement without secret key and the PPT-square conjecture" +subject = "Mathematical physics" +theorems = ["OAI.DimensionTen.main_pair"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Quantum.DimensionTen.Main" +reference_modules = 129 +reference_lean_bytes = 2413995 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1766 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13872 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dimension-ten-pair/tests/Challenge.lean b/tasks/dimension-ten-pair/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b64053b2a7231c5b0152449bb7ccd60cde6cdd8 --- /dev/null +++ b/tasks/dimension-ten-pair/tests/Challenge.lean @@ -0,0 +1,125 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped Matrix ComplexOrder +open Matrix Complex +namespace DimensionTen + +def blocksZ : Fin 4 → Matrix (Fin 6) (Fin 4) ℤ := + ![ ![ ![6,0,0,0], ![0,6,0,0], ![0,0,6,0], ![0,0,0,6], ![0,0,0,0], ![0,0,0,0] ], + ![ ![-12,0,0,0], ![0,-6,0,0], ![0,0,6,0], ![0,0,0,12], ![-6,0,6,6], ![-6,-6,6,0] ], + ![ ![0,6,-2,0], ![6,6,0,2], ![-2,0,10,0], ![0,2,0,24], ![0,0,0,6], ![0,-6,6,-6] ], + ![ ![0,0,-4,-3], ![0,-2,-3,-4], ![-4,-3,11,6], ![-3,-4,6,25], ![6,6,0,0], ![0,-6,6,6] ] ] + +def blocks (i : Fin 4) : Matrix (Fin 6) (Fin 4) ℂ := + (blocksZ i).map (Int.castRingHom ℂ) + +def pencilMap (A : Matrix (Fin 4) (Fin 4) ℂ) : Matrix (Fin 4) (Fin 4) ℂ := + ∑ i : Fin 4, ∑ j : Fin 4, A i j • ((blocks i)ᵀ * blocks j) + +abbrev Mat (n : ℕ) := Matrix (Fin n) (Fin n) ℂ + +def IsComplexLinear {a b : ℕ} (F : Mat a → Mat b) : Prop := + (∀ A B, F (A + B) = F A + F B) ∧ + (∀ (c : ℂ) A, F (c • A) = c • F A) + +def amplify {a b : ℕ} (F : Mat a → Mat b) (k : ℕ) + (X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ) : + Matrix (Fin k × Fin b) (Fin k × Fin b) ℂ := + fun u v => F (fun i j => X (u.1, i) (v.1, j)) u.2 v.2 + +def CompletelyPositive {a b : ℕ} (F : Mat a → Mat b) : Prop := + ∀ k : ℕ, 0 < k → ∀ X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ, + X.PosSemidef → (amplify F k X).PosSemidef + +def PPT {a b : ℕ} (F : Mat a → Mat b) : Prop := + IsComplexLinear F ∧ CompletelyPositive F ∧ + CompletelyPositive (fun X => (F X)ᵀ) + +def separable {a b : ℕ} (X : Matrix (Fin a × Fin b) (Fin a × Fin b) ℂ) : Prop := + ∃ r : ℕ, ∃ A : Fin r → Mat a, ∃ B : Fin r → Mat b, + (∀ i, (A i).PosSemidef ∧ (B i).PosSemidef) ∧ + X = ∑ i, Matrix.kronecker (A i) (B i) + +def EntanglementBreaking {a b : ℕ} (F : Mat a → Mat b) : Prop := + CompletelyPositive F ∧ + ∀ k : ℕ, 0 < k → ∀ X : Matrix (Fin k × Fin a) (Fin k × Fin a) ℂ, + X.PosSemidef → separable (amplify F k X) + +def choi {a b : ℕ} (F : Mat a → Mat b) : + Matrix (Fin a × Fin b) (Fin a × Fin b) ℂ := + fun u v => F (Matrix.single u.1 v.1 1) u.2 v.2 + +def tensorMap {a b c d : ℕ} (F : Mat a → Mat b) (G : Mat c → Mat d) + (X : Matrix (Fin a × Fin c) (Fin a × Fin c) ℂ) : + Matrix (Fin b × Fin d) (Fin b × Fin d) ℂ := + ∑ i : Fin c, ∑ j : Fin c, + Matrix.kronecker (F (fun a b => X (a, i) (b, j))) (G (Matrix.single i j 1)) + +def hsAdjoint {a b : ℕ} (F : Mat a → Mat b) (Y : Mat b) : Mat a := + fun i j => ∑ u : Fin b, ∑ v : Fin b, star (F (Matrix.single i j 1) u v) * Y u v + +def symmetricPairs : Fin 10 → Fin 4 × Fin 4 := + ![(0,0), (0,1), (0,2), (0,3), (1,1), (1,2), (1,3), (2,2), (2,3), (3,3)] + +def exteriorPairs : Fin 6 → Fin 4 × Fin 4 := + ![(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)] + +def symmetricIsometry : Matrix (Fin 4 × Fin 4) (Fin 10) ℂ := + fun ij a => + let p := (symmetricPairs a).1 + let q := (symmetricPairs a).2 + if p = q then (if ij = (p,p) then 1 else 0) + else ((if ij = (p,q) then 1 else 0) + (if ij = (q,p) then 1 else 0)) / + (Real.sqrt 2 : ℂ) + +def exteriorIsometry : Matrix (Fin 4 × Fin 4) (Fin 6) ℂ := + fun ij a => + let p := (exteriorPairs a).1 + let q := (exteriorPairs a).2 + ((if ij = (p,q) then 1 else 0) - (if ij = (q,p) then 1 else 0)) / + (Real.sqrt 2 : ℂ) + +def hodgeComplement : Mat 6 := + ![ ![0,0,0,0,0,1], ![0,0,0,0,-1,0], ![0,0,0,1,0,0], + ![0,0,1,0,0,0], ![0,-1,0,0,0,0], ![1,0,0,0,0,0] ] + +def firstSix : Matrix (Fin 10) (Fin 6) ℂ := + fun i j => if i.val = j.val then 1 else 0 + +def exteriorMap (A : Mat 10) : Mat 6 := + exteriorIsometryᴴ * + tensorMap pencilMap pencilMap (symmetricIsometry * A * symmetricIsometryᴴ) * + exteriorIsometry + +def complementaryMap (A : Mat 10) : Mat 6 := + hodgeComplement * (exteriorMap A)ᵀ * hodgeComplementᴴ + +def phiOne (A : Mat 10) : Mat 10 := + firstSix * exteriorMap Aᵀ * firstSixᴴ + +def phiTwo (B : Mat 10) : Mat 10 := + hsAdjoint complementaryMap (firstSixᴴ * B * firstSix) + +def compositeChoi : Matrix (Fin 10 × Fin 10) (Fin 10 × Fin 10) ℂ := + choi (phiTwo ∘ phiOne) + +def productVector {a b : ℕ} (u : Fin a → ℂ) (v : Fin b → ℂ) : Fin a × Fin b → ℂ := + fun ij => u ij.1 * v ij.2 + +theorem main_pair : + ∃ Φ₁ Φ₂ : Mat 10 → Mat 10, + Φ₁ = phiOne ∧ Φ₂ = phiTwo ∧ PPT Φ₁ ∧ PPT Φ₂ ∧ + (let Z := choi (Φ₂ ∘ Φ₁) + Z ≠ 0 ∧ + (∀ u v : Fin 10 → ℂ, ∀ w : Fin 10 × Fin 10 → ℂ, + Z *ᵥ w = productVector u v → u = 0 ∨ v = 0) ∧ + ¬ EntanglementBreaking (Φ₂ ∘ Φ₁)) := by + sorry + +end DimensionTen +end + +end OAI diff --git a/tasks/dimension-ten-pair/tests/grade.py b/tasks/dimension-ten-pair/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dimension-ten-pair/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dimension-ten-pair/tests/task.json b/tasks/dimension-ten-pair/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4a5527b65721bcdae65501f4adcb733949b2c6be --- /dev/null +++ b/tasks/dimension-ten-pair/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DimensionTenPair", + "comparator": { + "theorem_names": [ + "OAI.DimensionTen.main_pair" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12972 +} \ No newline at end of file diff --git a/tasks/dimension-ten-pair/tests/test.sh b/tasks/dimension-ten-pair/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dimension-ten-pair/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/direct-crouzeix/environment/Dockerfile b/tasks/direct-crouzeix/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/direct-crouzeix/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/direct-crouzeix/environment/fetch_mathlib.sh b/tasks/direct-crouzeix/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/direct-crouzeix/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/direct-crouzeix/environment/lake-manifest.json b/tasks/direct-crouzeix/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/direct-crouzeix/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/direct-crouzeix/environment/lakefile.lean b/tasks/direct-crouzeix/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/direct-crouzeix/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/direct-crouzeix/environment/lean_setup.sh b/tasks/direct-crouzeix/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/direct-crouzeix/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/direct-crouzeix/environment/pack_submission.py b/tasks/direct-crouzeix/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/direct-crouzeix/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/direct-crouzeix/instruction.md b/tasks/direct-crouzeix/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70ccaccaa4c68abcce3cd4c9583b9bfbb408bc8d --- /dev/null +++ b/tasks/direct-crouzeix/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `DirectCrouzeix` (family 325) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 325 of the release, *The complete Crouzeix conjecture* +(Functional analysis). The family as a whole: Resolves the complete Crouzeix conjecture: for every bounded operator $A$ on a complex Hilbert space and every finite matrix-valued polynomial $P$, one has $\lVert P[A]\rVert\le2\sup_{z\in W(A)}\lVert P(z)\rVert$, where $W(A)$ is the numerical range. The constant $2$ is sharp, independent of the matrix size, and valid in infinite dimensions. + +The challenge is `DirectCrouzeix`, also at `/opt/openai-math/challenges/DirectCrouzeix.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Matrix Matrix.Norms.L2Operator Kronecker + +namespace DirectCrouzeix + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ u : EuclideanSpace ℂ (Fin n), ‖u‖ = 1 ∧ + inner ℂ u (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A u) = z} + +def polynomialValue {m d : ℕ} (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) + (z : ℂ) : Matrix (Fin m) (Fin m) ℂ := + ∑ k : Fin (d + 1), z ^ (k : ℕ) • B k + +def tensorEvaluation {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : + Matrix (Fin n × Fin m) (Fin n × Fin m) ℂ := + ∑ k : Fin (d + 1), (A ^ (k : ℕ)) ⊗ₖ (B k) + +def rangeMaximum {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖polynomialValue B z‖) '' numericalRange A) + +def UniversalBound (c : ℝ) : Prop := + ∀ (n m d : ℕ), 0 < n → 0 < m → + ∀ (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ), + ‖tensorEvaluation A B‖ ≤ c * rangeMaximum A B + +theorem complete_crouzeix : UniversalBound 2 := by + sorry + +theorem uniform_sharpness (c : ℝ) (hc : UniversalBound c) : 2 ≤ c := by + sorry + +end DirectCrouzeix + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DirectCrouzeix.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.DirectCrouzeix.complete_crouzeix`, `OAI.DirectCrouzeix.uniform_sharpness` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/direct-crouzeix/solution/closure.txt b/tasks/direct-crouzeix/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8eb68055b2c67c690af8105c3b883271fdbe4703 --- /dev/null +++ b/tasks/direct-crouzeix/solution/closure.txt @@ -0,0 +1,42 @@ +OAI.Analysis.DirectCrouzeix.AnalyticCharts +OAI.Analysis.DirectCrouzeix.BoundaryEnergy +OAI.Analysis.DirectCrouzeix.BoundaryKernel +OAI.Analysis.DirectCrouzeix.BoundaryParametrization +OAI.Analysis.DirectCrouzeix.CircleFourier +OAI.Analysis.DirectCrouzeix.CompactIntegrals +OAI.Analysis.DirectCrouzeix.CompleteBound +OAI.Analysis.DirectCrouzeix.ConformalCollar +OAI.Analysis.DirectCrouzeix.Continuation +OAI.Analysis.DirectCrouzeix.Convexity +OAI.Analysis.DirectCrouzeix.DiskMapping +OAI.Analysis.DirectCrouzeix.DividedDifferences +OAI.Analysis.DirectCrouzeix.DomainBound +OAI.Analysis.DirectCrouzeix.DomainCore +OAI.Analysis.DirectCrouzeix.Duality +OAI.Analysis.DirectCrouzeix.ExponentialLevels +OAI.Analysis.DirectCrouzeix.ExponentialSupport +OAI.Analysis.DirectCrouzeix.ExteriorCollar +OAI.Analysis.DirectCrouzeix.ExteriorMapping +OAI.Analysis.DirectCrouzeix.ExtremalEmbedding +OAI.Analysis.DirectCrouzeix.FaberCalculus +OAI.Analysis.DirectCrouzeix.FaberEnergy +OAI.Analysis.DirectCrouzeix.FaberPolynomials +OAI.Analysis.DirectCrouzeix.HarmonicReflection +OAI.Analysis.DirectCrouzeix.HilbertSchmidt +OAI.Analysis.DirectCrouzeix.HolomorphicReflection +OAI.Analysis.DirectCrouzeix.InverseExterior +OAI.Analysis.DirectCrouzeix.KernelContraction +OAI.Analysis.DirectCrouzeix.Main +OAI.Analysis.DirectCrouzeix.Model +OAI.Analysis.DirectCrouzeix.NormalFamilies +OAI.Analysis.DirectCrouzeix.NumericalRange +OAI.Analysis.DirectCrouzeix.OuterApproximation +OAI.Analysis.DirectCrouzeix.PoissonBoundary +OAI.Analysis.DirectCrouzeix.PolynomialCalculus +OAI.Analysis.DirectCrouzeix.PolynomialEnergy +OAI.Analysis.DirectCrouzeix.PositiveBlocks +OAI.Analysis.DirectCrouzeix.Resolvent +OAI.Analysis.DirectCrouzeix.Sharpness +OAI.Analysis.DirectCrouzeix.SingularPairs +OAI.Analysis.DirectCrouzeix.SupportNets +OAI.Analysis.DirectCrouzeix.TaylorFourier diff --git a/tasks/direct-crouzeix/solution/reference.py b/tasks/direct-crouzeix/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/direct-crouzeix/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/direct-crouzeix/solution/solve.sh b/tasks/direct-crouzeix/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fcdc32e4664bc7b90ab22f0d89ce1c0021e271f9 --- /dev/null +++ b/tasks/direct-crouzeix/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DirectCrouzeix, i.e. module OAI.Analysis.DirectCrouzeix.Main and the +# 42 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.DirectCrouzeix.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DirectCrouzeix" diff --git a/tasks/direct-crouzeix/task.toml b/tasks/direct-crouzeix/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..908319f7577698b916df425db8f0d23d5c02ba78 --- /dev/null +++ b/tasks/direct-crouzeix/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/direct-crouzeix" +version = "1.0.0" +description = "Prove DirectCrouzeix (openai/math family 325: The complete Crouzeix conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DirectCrouzeix.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DirectCrouzeix" +family = "325" +family_title = "The complete Crouzeix conjecture" +subject = "Functional analysis" +theorems = ["OAI.DirectCrouzeix.complete_crouzeix", "OAI.DirectCrouzeix.uniform_sharpness"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.DirectCrouzeix.Main" +reference_modules = 42 +reference_lean_bytes = 314025 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1202 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11982 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/direct-crouzeix/tests/Challenge.lean b/tasks/direct-crouzeix/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff445cf2d835a67739ddbfa113a50c3f4e876ceb --- /dev/null +++ b/tasks/direct-crouzeix/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Matrix Matrix.Norms.L2Operator Kronecker + +namespace DirectCrouzeix + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ u : EuclideanSpace ℂ (Fin n), ‖u‖ = 1 ∧ + inner ℂ u (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A u) = z} + +def polynomialValue {m d : ℕ} (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) + (z : ℂ) : Matrix (Fin m) (Fin m) ℂ := + ∑ k : Fin (d + 1), z ^ (k : ℕ) • B k + +def tensorEvaluation {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : + Matrix (Fin n × Fin m) (Fin n × Fin m) ℂ := + ∑ k : Fin (d + 1), (A ^ (k : ℕ)) ⊗ₖ (B k) + +def rangeMaximum {n m d : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖polynomialValue B z‖) '' numericalRange A) + +def UniversalBound (c : ℝ) : Prop := + ∀ (n m d : ℕ), 0 < n → 0 < m → + ∀ (A : Matrix (Fin n) (Fin n) ℂ) + (B : Fin (d + 1) → Matrix (Fin m) (Fin m) ℂ), + ‖tensorEvaluation A B‖ ≤ c * rangeMaximum A B + +theorem complete_crouzeix : UniversalBound 2 := by + sorry + +theorem uniform_sharpness (c : ℝ) (hc : UniversalBound c) : 2 ≤ c := by + sorry + +end DirectCrouzeix + +end + +end OAI diff --git a/tasks/direct-crouzeix/tests/grade.py b/tasks/direct-crouzeix/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/direct-crouzeix/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/direct-crouzeix/tests/task.json b/tasks/direct-crouzeix/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..52b8b19d4ef87cf2125e8e03dae1eb34b89c7ff0 --- /dev/null +++ b/tasks/direct-crouzeix/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "DirectCrouzeix", + "comparator": { + "theorem_names": [ + "OAI.DirectCrouzeix.complete_crouzeix", + "OAI.DirectCrouzeix.uniform_sharpness" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11082 +} \ No newline at end of file diff --git a/tasks/direct-crouzeix/tests/test.sh b/tasks/direct-crouzeix/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/direct-crouzeix/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/directed-feedback/environment/Dockerfile b/tasks/directed-feedback/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/directed-feedback/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/directed-feedback/environment/fetch_mathlib.sh b/tasks/directed-feedback/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/directed-feedback/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/directed-feedback/environment/lake-manifest.json b/tasks/directed-feedback/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/directed-feedback/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/directed-feedback/environment/lakefile.lean b/tasks/directed-feedback/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/directed-feedback/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/directed-feedback/environment/lean_setup.sh b/tasks/directed-feedback/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/directed-feedback/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/directed-feedback/environment/pack_submission.py b/tasks/directed-feedback/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/directed-feedback/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/directed-feedback/instruction.md b/tasks/directed-feedback/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1fe4268c7b07b3480663f3879628bd57cb1d7dcd --- /dev/null +++ b/tasks/directed-feedback/instruction.md @@ -0,0 +1,152 @@ +# openai/math challenge `DirectedFeedback` (family 102) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 102 of the release, *The Unique Games Conjecture and optimal approximation thresholds* +(Theoretical computer science). The family as a whole: Proves Khot's Unique Games Conjecture. Independent direct reductions also establish NP-hardness, on unweighted graphs, of approximation beyond the Goemans–Williamson ratio for Max-Cut, below factor two for Vertex Cover, and within any fixed constant factor for Min-UnCut and directed feedback vertex set. These direct proofs use established PCP and Label Cover hardness results. + +The challenge is `DirectedFeedback`, also at `/opt/openai-math/challenges/DirectedFeedback.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace DirectedFeedback + +/-- Unary self-delimiting natural numbers. Outputs are explicit, not succinct. -/ +def natBits (n : ℕ) : List Bool := List.replicate n true ++ [false] + +/-- The explicit framing used for an input and its NP certificate. -/ +def pairBits (p : List Bool × List Bool) : List Bool := + natBits p.1.length ++ p.1 ++ p.2 + +/-- Finitely many stacks and control states are already part of `FinTM2`. +This additionally excludes infinite stack alphabets. -/ +def FiniteAlphabet (M : Turing.FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +/-- Polynomially bounded certificates checked by an actual deterministic +finite-alphabet machine, on the explicitly encoded input/certificate pair. -/ +structure NPVerifier where + witnessBound : Polynomial ℕ + verify : (List Bool × List Bool) → Bool + computation : Turing.TM2ComputableInPolyTime pairBits (fun b : Bool => [b]) verify + finiteAlphabet : FiniteAlphabet computation.tm + +def NPVerifier.Accepts (V : NPVerifier) (input : List Bool) : Prop := + ∃ witness : List Bool, witness.length ≤ V.witnessBound.eval input.length ∧ + V.verify (input, witness) = true + +/-- NP is defined independently of SAT or any hardness assertion. -/ +def InNP (language : List Bool → Prop) : Prop := + ∃ V : NPVerifier, ∀ input, language input ↔ V.Accepts input + +/-- Finite loopless digraph. Opposite arcs are permitted. Every arc is listed +explicitly. No symmetric closure or undirected-cycle convention is used. -/ +structure Digraph where + n : ℕ + arcs : List (Fin n × Fin n) + loopless : ∀ e ∈ arcs, e.1 ≠ e.2 + nodup : arcs.Nodup + +namespace Digraph + +/-- An actual simple directed cycle of positive length. A cyclic enumeration +of `r + 1` distinct vertices supplies every successive arc, including the +closing arc. A 2-cycle is allowed; looplessness rules out length 1. -/ +def IsCycle (G : Digraph) {r : ℕ} (c : Fin (r + 1) → Fin G.n) : Prop := + Function.Injective c ∧ ∀ i, (c i, c (i + 1)) ∈ G.arcs + +/-- A feedback set intersects EVERY actual directed cycle. -/ +def Feedback (G : Digraph) (F : Finset (Fin G.n)) : Prop := + ∀ (r : ℕ) (c : Fin (r + 1) → Fin G.n), G.IsCycle c → ∃ i, c i ∈ F + +/-- Minimum number of vertices of a feedback set. No weights or auxiliary +cost oracle appear in this definition. -/ +noncomputable def dfvs (G : Digraph) : ℕ := by + classical + exact Nat.find (show ∃ k : ℕ, ∃ F : Finset (Fin G.n), G.Feedback F ∧ F.card = k from + ⟨G.n, Finset.univ, by + intro r c _ + exact ⟨0, Finset.mem_univ _⟩, by simp⟩) + +/-- Full explicit vertex and arc serialization, including isolated vertices. -/ +def bits (G : Digraph) : List Bool := + ([G.n] ++ List.range G.n ++ [G.arcs.length] ++ + G.arcs.flatMap (fun e => [e.1.val, e.2.val])).flatMap natBits + +end Digraph + +/-- Output includes a strictly positive integer threshold. -/ +structure GapInstance where + graph : Digraph + k : ℕ + k_pos : 0 < k + +def GapInstance.bits (I : GapInstance) : List Bool := + natBits I.k ++ I.graph.bits + +/-- A strict YES/NO gap reduction implemented by a finite-alphabet machine +with polynomial runtime in the raw input bit length. -/ +structure GapReduction (A : ℝ) (language : List Bool → Prop) where + construct : List Bool → GapInstance + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + GapInstance.bits construct + finiteAlphabet : FiniteAlphabet computation.tm + completeness : ∀ input, language input → + (construct input).graph.dfvs ≤ (construct input).k + soundness : ∀ input, ¬ language input → + A * ((construct input).k : ℝ) < ((construct input).graph.dfvs : ℝ) + +/-- Constant-factor directed feedback vertex set hardness for all NP languages. -/ +def MainStatement : Prop := + ∀ A : ℝ, 1 ≤ A → ∀ language : List Bool → Prop, + InNP language → Nonempty (GapReduction A language) + +end DirectedFeedback + +theorem DirectedFeedback.main : DirectedFeedback.MainStatement := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DirectedFeedback.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DirectedFeedback.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/directed-feedback/solution/closure.txt b/tasks/directed-feedback/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..62807119e0fafb6cffdf949bdf5952d1a7dac6e7 --- /dev/null +++ b/tasks/directed-feedback/solution/closure.txt @@ -0,0 +1,224 @@ +OAI.Computability.DirectedFeedback.Analysis.Deletion +OAI.Computability.DirectedFeedback.Analysis.KMSMomentScalar +OAI.Computability.DirectedFeedback.Analysis.MatrixCharacters +OAI.Computability.DirectedFeedback.Analysis.MatrixEnergy +OAI.Computability.DirectedFeedback.Analysis.MatrixNoise +OAI.Computability.DirectedFeedback.Analysis.NoiseEnumeration +OAI.Computability.DirectedFeedback.Analysis.PrivateFourier +OAI.Computability.DirectedFeedback.CookLevin.NPTableau +OAI.Computability.DirectedFeedback.CookLevin.PolynomialMachine +OAI.Computability.DirectedFeedback.Encoding.ActualGoodRows +OAI.Computability.DirectedFeedback.Encoding.Body +OAI.Computability.DirectedFeedback.Encoding.Bounds +OAI.Computability.DirectedFeedback.Encoding.CanonicalWordTemplate +OAI.Computability.DirectedFeedback.Encoding.CompareLoop +OAI.Computability.DirectedFeedback.Encoding.EmitRows +OAI.Computability.DirectedFeedback.Encoding.ExpanderTableWords +OAI.Computability.DirectedFeedback.Encoding.FinalCNFPattern +OAI.Computability.DirectedFeedback.Encoding.Finite +OAI.Computability.DirectedFeedback.Encoding.FormulaEncoding +OAI.Computability.DirectedFeedback.Encoding.InstanceEquivalences +OAI.Computability.DirectedFeedback.Encoding.Lookup +OAI.Computability.DirectedFeedback.Encoding.NameCompaction +OAI.Computability.DirectedFeedback.Encoding.Occurrences +OAI.Computability.DirectedFeedback.Encoding.PortTables +OAI.Computability.DirectedFeedback.Encoding.PoweringAddresses +OAI.Computability.DirectedFeedback.Encoding.PoweringTables +OAI.Computability.DirectedFeedback.Encoding.PreprocessingOverlayTables +OAI.Computability.DirectedFeedback.Encoding.PreprocessingRegularTables +OAI.Computability.DirectedFeedback.Encoding.PreprocessingRegularWords +OAI.Computability.DirectedFeedback.Encoding.PreprocessingStageMaps +OAI.Computability.DirectedFeedback.Encoding.ProductTarget +OAI.Computability.DirectedFeedback.Encoding.Queries +OAI.Computability.DirectedFeedback.Encoding.RawPrivateTable +OAI.Computability.DirectedFeedback.Encoding.SelectedPolicies +OAI.Computability.DirectedFeedback.Encoding.Setup +OAI.Computability.DirectedFeedback.Encoding.TableIteration +OAI.Computability.DirectedFeedback.Encoding.VerifierCNF +OAI.Computability.DirectedFeedback.Games.A4IndexCount +OAI.Computability.DirectedFeedback.Games.A5ForwardIndex +OAI.Computability.DirectedFeedback.Games.A5Scalar +OAI.Computability.DirectedFeedback.Games.ActualAdviceSampling +OAI.Computability.DirectedFeedback.Games.ActualAdviceStochasticBridge +OAI.Computability.DirectedFeedback.Games.ActualAdviceUpper +OAI.Computability.DirectedFeedback.Games.ActualCanonical +OAI.Computability.DirectedFeedback.Games.AddressTupleBody +OAI.Computability.DirectedFeedback.Games.AddressTupleLoaded +OAI.Computability.DirectedFeedback.Games.AdviceLaw +OAI.Computability.DirectedFeedback.Games.AffineWitnessNormalization +OAI.Computability.DirectedFeedback.Games.AlphabetReduction +OAI.Computability.DirectedFeedback.Games.BlockOrientations +OAI.Computability.DirectedFeedback.Games.CanonicalAddress +OAI.Computability.DirectedFeedback.Games.CayleySampling +OAI.Computability.DirectedFeedback.Games.CayleySpectral +OAI.Computability.DirectedFeedback.Games.ChainRule +OAI.Computability.DirectedFeedback.Games.ChildLifts +OAI.Computability.DirectedFeedback.Games.Collision +OAI.Computability.DirectedFeedback.Games.CompletedSampling +OAI.Computability.DirectedFeedback.Games.ConditionalIncidences +OAI.Computability.DirectedFeedback.Games.CoordinateTransport +OAI.Computability.DirectedFeedback.Games.Decoder +OAI.Computability.DirectedFeedback.Games.DegreeCover +OAI.Computability.DirectedFeedback.Games.Derivatives +OAI.Computability.DirectedFeedback.Games.EqualityFiber +OAI.Computability.DirectedFeedback.Games.ExpanderFamily +OAI.Computability.DirectedFeedback.Games.Explicit +OAI.Computability.DirectedFeedback.Games.FieldArray +OAI.Computability.DirectedFeedback.Games.FinalParameters +OAI.Computability.DirectedFeedback.Games.FinishReduction +OAI.Computability.DirectedFeedback.Games.Game +OAI.Computability.DirectedFeedback.Games.Generator +OAI.Computability.DirectedFeedback.Games.GeneratorModel +OAI.Computability.DirectedFeedback.Games.GenericPolynomial +OAI.Computability.DirectedFeedback.Games.Genericity +OAI.Computability.DirectedFeedback.Games.Harmonic +OAI.Computability.DirectedFeedback.Games.InitialGraph +OAI.Computability.DirectedFeedback.Games.KMSAnalyticCodomainTransport +OAI.Computability.DirectedFeedback.Games.KMSAnalyticHybridEnergyFiber +OAI.Computability.DirectedFeedback.Games.KMSAnalyticHybridEnergyImageSplit +OAI.Computability.DirectedFeedback.Games.KMSAnalyticHybridEnergyMixed +OAI.Computability.DirectedFeedback.Games.KMSAnalyticHyperplaneExtensions +OAI.Computability.DirectedFeedback.Games.KMSAnalyticSmallTransport +OAI.Computability.DirectedFeedback.Games.KMSBasisComparisonFibers +OAI.Computability.DirectedFeedback.Games.KMSBasisComparisonPseudorandom +OAI.Computability.DirectedFeedback.Games.KMSBasisComparisonRetention +OAI.Computability.DirectedFeedback.Games.KMSKernelFiberDefs +OAI.Computability.DirectedFeedback.Games.KernelCardinality +OAI.Computability.DirectedFeedback.Games.LocalEquation +OAI.Computability.DirectedFeedback.Games.MatrixChartDegreeNeighbors +OAI.Computability.DirectedFeedback.Games.NaturalTransport +OAI.Computability.DirectedFeedback.Games.NonlinearRecurrence +OAI.Computability.DirectedFeedback.Games.Overlay +OAI.Computability.DirectedFeedback.Games.Parameters +OAI.Computability.DirectedFeedback.Games.PartnerFullSampling +OAI.Computability.DirectedFeedback.Games.PositiveMultiplier +OAI.Computability.DirectedFeedback.Games.PoweringFinalConstants +OAI.Computability.DirectedFeedback.Games.PoweringReach +OAI.Computability.DirectedFeedback.Games.Preprocessing +OAI.Computability.DirectedFeedback.Games.Product +OAI.Computability.DirectedFeedback.Games.ProductLaw +OAI.Computability.DirectedFeedback.Games.ProfileCorrection +OAI.Computability.DirectedFeedback.Games.QuestionMarginal +OAI.Computability.DirectedFeedback.Games.RowErasureSliceQuotient +OAI.Computability.DirectedFeedback.Games.RowErasureSliceUniform +OAI.Computability.DirectedFeedback.Games.RowErasureSlices +OAI.Computability.DirectedFeedback.Games.SelectedInformation +OAI.Computability.DirectedFeedback.Games.SelectedLikelihood +OAI.Computability.DirectedFeedback.Games.SharedSampling +OAI.Computability.DirectedFeedback.Games.SignaturePrepare +OAI.Computability.DirectedFeedback.Games.StageData +OAI.Computability.DirectedFeedback.Games.SubmoduleInterval +OAI.Computability.DirectedFeedback.Games.Target +OAI.Computability.DirectedFeedback.Games.TensorDomination +OAI.Computability.DirectedFeedback.Games.TestEmit +OAI.Computability.DirectedFeedback.Games.TupleBody +OAI.Computability.DirectedFeedback.Games.UniformReduction +OAI.Computability.DirectedFeedback.Games.UpperMobius +OAI.Computability.DirectedFeedback.Games.VisibleTransfer +OAI.Computability.DirectedFeedback.Machines.AddressMachineInitial +OAI.Computability.DirectedFeedback.Machines.ContextClear +OAI.Computability.DirectedFeedback.Machines.ContextLoad +OAI.Computability.DirectedFeedback.Machines.DummySelectSteps +OAI.Computability.DirectedFeedback.Machines.FinalCNFHeader +OAI.Computability.DirectedFeedback.Machines.FinalCNFStream +OAI.Computability.DirectedFeedback.Machines.FinalCNFTime +OAI.Computability.DirectedFeedback.Machines.GraphCounterFinish +OAI.Computability.DirectedFeedback.Machines.Label +OAI.Computability.DirectedFeedback.Machines.LoopInit +OAI.Computability.DirectedFeedback.Machines.MachineAddressHeaders +OAI.Computability.DirectedFeedback.Machines.MachineAffineLookup +OAI.Computability.DirectedFeedback.Machines.MachineBinaryLiteralMachine +OAI.Computability.DirectedFeedback.Machines.MachineBinaryNameMachine +OAI.Computability.DirectedFeedback.Machines.MachineBinaryRenameMachine +OAI.Computability.DirectedFeedback.Machines.MachineBinaryTokenMachine +OAI.Computability.DirectedFeedback.Machines.MachineBinaryTotalInputMachine +OAI.Computability.DirectedFeedback.Machines.MachineCloudCount +OAI.Computability.DirectedFeedback.Machines.MachineCloudPadding +OAI.Computability.DirectedFeedback.Machines.MachineCloudSelect +OAI.Computability.DirectedFeedback.Machines.MachineDummyRows +OAI.Computability.DirectedFeedback.Machines.MachineEmbedding +OAI.Computability.DirectedFeedback.Machines.MachineExpanderFamilyLoop +OAI.Computability.DirectedFeedback.Machines.MachineExpanderFamilyTapes +OAI.Computability.DirectedFeedback.Machines.MachineExpanderRow +OAI.Computability.DirectedFeedback.Machines.MachineExpanderRowDivision +OAI.Computability.DirectedFeedback.Machines.MachineExpanderRowLookup +OAI.Computability.DirectedFeedback.Machines.MachineExpanderTableLoop +OAI.Computability.DirectedFeedback.Machines.MachineLazyTable +OAI.Computability.DirectedFeedback.Machines.MachineLazyTableRuntime +OAI.Computability.DirectedFeedback.Machines.MachineLookupSpec +OAI.Computability.DirectedFeedback.Machines.MachineOutcomeRows +OAI.Computability.DirectedFeedback.Machines.MachineOverlayTable +OAI.Computability.DirectedFeedback.Machines.MachinePaddedExpanderFamily +OAI.Computability.DirectedFeedback.Machines.MachinePaddedOverlay +OAI.Computability.DirectedFeedback.Machines.MachinePortReindex +OAI.Computability.DirectedFeedback.Machines.MachinePreservingLookupClean +OAI.Computability.DirectedFeedback.Machines.MachineProductField +OAI.Computability.DirectedFeedback.Machines.MachineProductFinish +OAI.Computability.DirectedFeedback.Machines.MachineProductPower +OAI.Computability.DirectedFeedback.Machines.MachineProductProgram +OAI.Computability.DirectedFeedback.Machines.MachineRegularExecutionBounds +OAI.Computability.DirectedFeedback.Machines.MachineRegularInternalRow +OAI.Computability.DirectedFeedback.Machines.MachineRegularMetadata +OAI.Computability.DirectedFeedback.Machines.MachineRegularOriginalBody +OAI.Computability.DirectedFeedback.Machines.MachineRegularOwnerBody +OAI.Computability.DirectedFeedback.Machines.MachineRegularTable +OAI.Computability.DirectedFeedback.Machines.MachineSingleOrbitBridge +OAI.Computability.DirectedFeedback.Machines.MachineSingleOrbitCodec +OAI.Computability.DirectedFeedback.Machines.MachineStateEquiv +OAI.Computability.DirectedFeedback.Machines.MachineSubdivisionInit +OAI.Computability.DirectedFeedback.Machines.MachineSubdivisionLoop +OAI.Computability.DirectedFeedback.Machines.MachineSubdivisionRows +OAI.Computability.DirectedFeedback.Machines.MachineSubstitution +OAI.Computability.DirectedFeedback.Machines.MachineTableRows +OAI.Computability.DirectedFeedback.Machines.MachineTemplateAddress +OAI.Computability.DirectedFeedback.Machines.MachineTransducer +OAI.Computability.DirectedFeedback.Machines.MachineTuple +OAI.Computability.DirectedFeedback.Machines.MachineUnaryAdd +OAI.Computability.DirectedFeedback.Machines.OutputSize +OAI.Computability.DirectedFeedback.Machines.PoweringMachineLoop +OAI.Computability.DirectedFeedback.Machines.PoweringMachineOuterLoop +OAI.Computability.DirectedFeedback.Machines.PoweringMachineRelationField +OAI.Computability.DirectedFeedback.Machines.PoweringMachineRowBody +OAI.Computability.DirectedFeedback.Machines.PoweringMachineWord +OAI.Computability.DirectedFeedback.Machines.PoweringRuntimeBudget +OAI.Computability.DirectedFeedback.Machines.RawInitialMachineFinish +OAI.Computability.DirectedFeedback.Machines.RawInitialMachineStart +OAI.Computability.DirectedFeedback.Machines.RuntimeFinish +OAI.Computability.DirectedFeedback.Machines.RuntimeSpace +OAI.Computability.DirectedFeedback.Machines.Tape +OAI.Computability.DirectedFeedback.Machines.TupleOrder +OAI.Computability.DirectedFeedback.Machines.VertexLabel +OAI.Computability.DirectedFeedback.Main +OAI.Computability.DirectedFeedback.Model +OAI.Computability.DirectedFeedback.Probability.A13Reduction +OAI.Computability.DirectedFeedback.Probability.Basic +OAI.Computability.DirectedFeedback.Probability.DescentProbability +OAI.Computability.DirectedFeedback.Probability.Enlargement +OAI.Computability.DirectedFeedback.Probability.KMSFourthMomentMixedRestriction +OAI.Computability.DirectedFeedback.Probability.KMSFourthMomentZoomTransport +OAI.Computability.DirectedFeedback.Probability.KMSMomentConstants +OAI.Computability.DirectedFeedback.Probability.Mixture +OAI.Computability.DirectedFeedback.Probability.PolynomialProbability +OAI.Computability.DirectedFeedback.Probability.PoweringFieldPlan +OAI.Computability.DirectedFeedback.Probability.RepeatedGameBounds +OAI.Computability.DirectedFeedback.Probability.TraceLaw +OAI.Computability.DirectedFeedback.RankGraph.AllGraph +OAI.Computability.DirectedFeedback.RankGraph.Bias +OAI.Computability.DirectedFeedback.RankGraph.CellCount +OAI.Computability.DirectedFeedback.RankGraph.Clone100Counting +OAI.Computability.DirectedFeedback.RankGraph.CloneGap +OAI.Computability.DirectedFeedback.RankGraph.ExprLayout +OAI.Computability.DirectedFeedback.RankGraph.FailureEvent +OAI.Computability.DirectedFeedback.RankGraph.LastBias +OAI.Computability.DirectedFeedback.RankGraph.MachineClone100Cleanup +OAI.Computability.DirectedFeedback.RankGraph.MachineClone100Finish +OAI.Computability.DirectedFeedback.RankGraph.OutputDef +OAI.Computability.DirectedFeedback.RankGraph.PacketLocality +OAI.Computability.DirectedFeedback.RankGraph.Point +OAI.Computability.DirectedFeedback.RankGraph.PrefixBit +OAI.Computability.DirectedFeedback.RankGraph.Rational +OAI.Computability.DirectedFeedback.RankGraph.RoundBoolean +OAI.Computability.DirectedFeedback.RankGraph.StackFinite +OAI.Computability.DirectedFeedback.RankGraph.Store +OAI.Computability.DirectedFeedback.RankGraph.SumBox +OAI.Computability.DirectedFeedback.RankGraph.UnweightedIntegrated diff --git a/tasks/directed-feedback/solution/reference.py b/tasks/directed-feedback/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/directed-feedback/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/directed-feedback/solution/solve.sh b/tasks/directed-feedback/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ce5f948837a66675f5733ef42472d5d5fd39a0b --- /dev/null +++ b/tasks/directed-feedback/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DirectedFeedback, i.e. module OAI.Computability.DirectedFeedback.Main and the +# 224 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.DirectedFeedback.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DirectedFeedback" diff --git a/tasks/directed-feedback/task.toml b/tasks/directed-feedback/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..253edbf8550bdc318fa6e527d3d973c57119be32 --- /dev/null +++ b/tasks/directed-feedback/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/directed-feedback" +version = "1.0.0" +description = "Prove DirectedFeedback (openai/math family 102: The Unique Games Conjecture and optimal approximation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DirectedFeedback.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DirectedFeedback" +family = "102" +family_title = "The Unique Games Conjecture and optimal approximation thresholds" +subject = "Theoretical computer science" +theorems = ["OAI.DirectedFeedback.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.DirectedFeedback.Main" +reference_modules = 224 +reference_lean_bytes = 8506385 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1662 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19355 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/directed-feedback/tests/Challenge.lean b/tasks/directed-feedback/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e06dfe4c76191215806a7e504f75089868898110 --- /dev/null +++ b/tasks/directed-feedback/tests/Challenge.lean @@ -0,0 +1,101 @@ +import Mathlib + +namespace OAI + +namespace DirectedFeedback + +/-- Unary self-delimiting natural numbers. Outputs are explicit, not succinct. -/ +def natBits (n : ℕ) : List Bool := List.replicate n true ++ [false] + +/-- The explicit framing used for an input and its NP certificate. -/ +def pairBits (p : List Bool × List Bool) : List Bool := + natBits p.1.length ++ p.1 ++ p.2 + +/-- Finitely many stacks and control states are already part of `FinTM2`. +This additionally excludes infinite stack alphabets. -/ +def FiniteAlphabet (M : Turing.FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +/-- Polynomially bounded certificates checked by an actual deterministic +finite-alphabet machine, on the explicitly encoded input/certificate pair. -/ +structure NPVerifier where + witnessBound : Polynomial ℕ + verify : (List Bool × List Bool) → Bool + computation : Turing.TM2ComputableInPolyTime pairBits (fun b : Bool => [b]) verify + finiteAlphabet : FiniteAlphabet computation.tm + +def NPVerifier.Accepts (V : NPVerifier) (input : List Bool) : Prop := + ∃ witness : List Bool, witness.length ≤ V.witnessBound.eval input.length ∧ + V.verify (input, witness) = true + +/-- NP is defined independently of SAT or any hardness assertion. -/ +def InNP (language : List Bool → Prop) : Prop := + ∃ V : NPVerifier, ∀ input, language input ↔ V.Accepts input + +/-- Finite loopless digraph. Opposite arcs are permitted. Every arc is listed +explicitly. No symmetric closure or undirected-cycle convention is used. -/ +structure Digraph where + n : ℕ + arcs : List (Fin n × Fin n) + loopless : ∀ e ∈ arcs, e.1 ≠ e.2 + nodup : arcs.Nodup + +namespace Digraph + +/-- An actual simple directed cycle of positive length. A cyclic enumeration +of `r + 1` distinct vertices supplies every successive arc, including the +closing arc. A 2-cycle is allowed; looplessness rules out length 1. -/ +def IsCycle (G : Digraph) {r : ℕ} (c : Fin (r + 1) → Fin G.n) : Prop := + Function.Injective c ∧ ∀ i, (c i, c (i + 1)) ∈ G.arcs + +/-- A feedback set intersects EVERY actual directed cycle. -/ +def Feedback (G : Digraph) (F : Finset (Fin G.n)) : Prop := + ∀ (r : ℕ) (c : Fin (r + 1) → Fin G.n), G.IsCycle c → ∃ i, c i ∈ F + +/-- Minimum number of vertices of a feedback set. No weights or auxiliary +cost oracle appear in this definition. -/ +noncomputable def dfvs (G : Digraph) : ℕ := by + classical + exact Nat.find (show ∃ k : ℕ, ∃ F : Finset (Fin G.n), G.Feedback F ∧ F.card = k from + ⟨G.n, Finset.univ, by + intro r c _ + exact ⟨0, Finset.mem_univ _⟩, by simp⟩) + +/-- Full explicit vertex and arc serialization, including isolated vertices. -/ +def bits (G : Digraph) : List Bool := + ([G.n] ++ List.range G.n ++ [G.arcs.length] ++ + G.arcs.flatMap (fun e => [e.1.val, e.2.val])).flatMap natBits + +end Digraph + +/-- Output includes a strictly positive integer threshold. -/ +structure GapInstance where + graph : Digraph + k : ℕ + k_pos : 0 < k + +def GapInstance.bits (I : GapInstance) : List Bool := + natBits I.k ++ I.graph.bits + +/-- A strict YES/NO gap reduction implemented by a finite-alphabet machine +with polynomial runtime in the raw input bit length. -/ +structure GapReduction (A : ℝ) (language : List Bool → Prop) where + construct : List Bool → GapInstance + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + GapInstance.bits construct + finiteAlphabet : FiniteAlphabet computation.tm + completeness : ∀ input, language input → + (construct input).graph.dfvs ≤ (construct input).k + soundness : ∀ input, ¬ language input → + A * ((construct input).k : ℝ) < ((construct input).graph.dfvs : ℝ) + +/-- Constant-factor directed feedback vertex set hardness for all NP languages. -/ +def MainStatement : Prop := + ∀ A : ℝ, 1 ≤ A → ∀ language : List Bool → Prop, + InNP language → Nonempty (GapReduction A language) + +end DirectedFeedback + +theorem DirectedFeedback.main : DirectedFeedback.MainStatement := by + sorry + +end OAI diff --git a/tasks/directed-feedback/tests/grade.py b/tasks/directed-feedback/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/directed-feedback/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/directed-feedback/tests/task.json b/tasks/directed-feedback/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..28ba4a0c15dfd0ba0963053f94f3e5f4948a81d0 --- /dev/null +++ b/tasks/directed-feedback/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DirectedFeedback", + "comparator": { + "theorem_names": [ + "OAI.DirectedFeedback.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18455 +} \ No newline at end of file diff --git a/tasks/directed-feedback/tests/test.sh b/tasks/directed-feedback/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/directed-feedback/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/directional-ballisticity/environment/Dockerfile b/tasks/directional-ballisticity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/directional-ballisticity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/directional-ballisticity/environment/fetch_mathlib.sh b/tasks/directional-ballisticity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/directional-ballisticity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/directional-ballisticity/environment/lake-manifest.json b/tasks/directional-ballisticity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/directional-ballisticity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/directional-ballisticity/environment/lakefile.lean b/tasks/directional-ballisticity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/directional-ballisticity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/directional-ballisticity/environment/lean_setup.sh b/tasks/directional-ballisticity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/directional-ballisticity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/directional-ballisticity/environment/pack_submission.py b/tasks/directional-ballisticity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/directional-ballisticity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/directional-ballisticity/instruction.md b/tasks/directional-ballisticity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f6e3bbef1466bdbc7c03d5cae3dc7680e4edfd0 --- /dev/null +++ b/tasks/directional-ballisticity/instruction.md @@ -0,0 +1,151 @@ +# openai/math challenge `DirectionalBallisticity` (family 220) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 220 of the release, *Directional zero–one laws and ballisticity in random environments* +(Probability and statistical mechanics). The family as a whole: On $\mathbb Z^d$, $d\ge3$, directional escape has probability zero or one for iid strictly elliptic nearest-neighbor environments, and for stationary ergodic finite-range-dependent environments under uniform ellipticity. In iid uniformly elliptic environments with $d\ge2$, almost-sure directional transience implies a deterministic limiting velocity with positive projection in that direction, resolving the ballisticity conjecture. + +The challenge is `DirectionalBallisticity`, also at `/opt/openai-math/challenges/DirectionalBallisticity.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped ENNReal NNReal BigOperators Topology + +namespace DirectionalTransience + +abbrev Lattice (d : ℕ) := Fin d → ℤ +abbrev Direction (d : ℕ) := Fin d × Bool +abbrev Vector (d : ℕ) := Fin d → ℝ +abbrev Row (d : ℕ) := {p : Direction d → ℝ≥0 // ∑ e, p e = 1} +abbrev Environment (d : ℕ) := Lattice d → Row d +abbrev State (d : ℕ) := Environment d × Lattice d +abbrev Path (d : ℕ) := ℕ → Lattice d + +def step {d : ℕ} (e : Direction d) : Lattice d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +noncomputable def environmentLaw {d : ℕ} (ν : Measure (Row d)) : + Measure (Environment d) := Measure.infinitePi (fun _ => ν) + +def UniformElliptic {d : ℕ} (ν : Measure (Row d)) : Prop := + ∃ κ : ℝ≥0, 0 < κ ∧ ∀ᵐ p ∂ν, ∀ e, κ ≤ p.1 e + +lemma measurable_current_row {d : ℕ} : + Measurable (fun z : State d => z.1 z.2) := by + apply measurable_from_prod_countable_left + intro x + exact measurable_pi_apply x + +noncomputable def transition {d : ℕ} : Kernel (State d) (State d) where + toFun z := ∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e) + measurable' := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.finsetSum_apply, Measure.smul_apply, smul_eq_mul] + apply Finset.measurable_fun_sum + intro e _ + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp measurable_current_row)).coe_nnreal_ennreal + · exact (Measure.measurable_coe hs).comp + (Measure.measurable_dirac.comp (measurable_fst.prodMk + (measurable_snd.add_const (step e)))) + +instance transition_markov {d : ℕ} : IsMarkovKernel (transition (d := d)) where + isProbabilityMeasure z := by + constructor + change (∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, Measure.dirac_apply_of_mem + (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofNNReal_finsetSum, (z.1 z.2).2] + rfl + +noncomputable def historyTransition {d : ℕ} (n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) where + toFun z := transition (z ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + measurable' := transition.measurable.comp (measurable_pi_apply _) + +instance historyTransition_markov {d : ℕ} (n : ℕ) : + IsMarkovKernel (historyTransition (d := d) n) where + isProbabilityMeasure _ := transition_markov.isProbabilityMeasure _ + +noncomputable def initialLaw {d : ℕ} (ν : Measure (Row d)) : Measure (State d) := + (environmentLaw ν).map (fun ω => (ω, (0 : Lattice d))) + +noncomputable def annealedLaw {d : ℕ} (ν : Measure (Row d)) : Measure (Path d) := + (@Kernel.trajMeasure (fun _ => State d) _ (initialLaw ν) (historyTransition (d := d)) _).map + (fun z n => (z n).2) + +def dot {d : ℕ} (v ℓ : Vector d) : ℝ := ∑ i, v i * ℓ i + +def realPosition {d : ℕ} (x : Lattice d) : Vector d := fun i => (x i : ℝ) + +def DirectionallyTransient {d : ℕ} (ν : Measure (Row d)) (ℓ : Vector d) : Prop := + ∀ᵐ X ∂annealedLaw ν, + Tendsto (fun n => dot (realPosition (X n)) ℓ) atTop atTop + +def HasVelocity {d : ℕ} (ν : Measure (Row d)) (v : Vector d) : Prop := + ∀ᵐ X ∂annealedLaw ν, + Tendsto (fun n : ℕ => (fun i => (X n i : ℝ) / (n : ℝ))) atTop (𝓝 v) + +open scoped ENNReal NNReal Classical Topology BigOperators + +def MainStatement : Prop := + ∀ (d : ℕ), 2 ≤ d → ∀ (ν : Measure (Row d)), IsProbabilityMeasure ν → + UniformElliptic ν → ∀ (ℓ : Vector d), dot ℓ ℓ = 1 → + DirectionallyTransient ν ℓ → + ∃ v : Vector d, 0 < dot v ℓ ∧ HasVelocity ν v + +theorem directional_transience_implies_ballisticity : MainStatement := by + sorry + +end DirectionalTransience + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DirectionalBallisticity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DirectionalTransience.directional_transience_implies_ballisticity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/directional-ballisticity/solution/closure.txt b/tasks/directional-ballisticity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ce65674d42aea96e1082fac7845c8ef1e51c687 --- /dev/null +++ b/tasks/directional-ballisticity/solution/closure.txt @@ -0,0 +1,513 @@ +OAI.Probability.Ballisticity.Coupling.CellSeedParameters +OAI.Probability.Ballisticity.Coupling.CountableFreshBuffer +OAI.Probability.Ballisticity.Coupling.FreshBudgetEvent +OAI.Probability.Ballisticity.Coupling.FreshBuffer +OAI.Probability.Ballisticity.Coupling.FreshBufferAE +OAI.Probability.Ballisticity.Coupling.FreshClipping +OAI.Probability.Ballisticity.Coupling.FreshCrossing +OAI.Probability.Ballisticity.Coupling.FreshMoment +OAI.Probability.Ballisticity.Coupling.FreshPolicyIndependence +OAI.Probability.Ballisticity.Coupling.FreshStages +OAI.Probability.Ballisticity.Coupling.FreshThreat +OAI.Probability.Ballisticity.Coupling.FreshWeightedTest +OAI.Probability.Ballisticity.Coupling.GaussianQuenchedMass +OAI.Probability.Ballisticity.Coupling.GaussianQuenchedTube +OAI.Probability.Ballisticity.Coupling.QuenchedConcentration +OAI.Probability.Ballisticity.Coupling.QuenchedConditionalProbability +OAI.Probability.Ballisticity.Coupling.QuenchedConditionedTubeTransfer +OAI.Probability.Ballisticity.Coupling.QuenchedGaussian +OAI.Probability.Ballisticity.Coupling.QuenchedMoments +OAI.Probability.Ballisticity.Coupling.QuenchedPrefixDeterminedFuture +OAI.Probability.Ballisticity.Coupling.QuenchedSuccessComparison +OAI.Probability.Ballisticity.Coupling.SeedIteration +OAI.Probability.Ballisticity.Coupling.SeedMedian +OAI.Probability.Ballisticity.Coupling.SeedOptions +OAI.Probability.Ballisticity.Coupling.SeedOrder +OAI.Probability.Ballisticity.Coupling.SeedProfile +OAI.Probability.Ballisticity.Coupling.SeedRadius +OAI.Probability.Ballisticity.Coupling.SeedStateOrder +OAI.Probability.Ballisticity.Coupling.SeedUniform +OAI.Probability.Ballisticity.Coupling.StageSeedProfile +OAI.Probability.Ballisticity.Coupling.StoppedFreshField +OAI.Probability.Ballisticity.Coupling.WeakLimitBoundedFreshMap +OAI.Probability.Ballisticity.Coupling.WeightedAnnealed +OAI.Probability.Ballisticity.Crossings.BadCrossingLaw +OAI.Probability.Ballisticity.Crossings.BoundaryCrossBound +OAI.Probability.Ballisticity.Crossings.BoundaryFirstHits +OAI.Probability.Ballisticity.Crossings.CanonicalHeightCutoff +OAI.Probability.Ballisticity.Crossings.CommonCutCounting +OAI.Probability.Ballisticity.Crossings.CommonCutObserver +OAI.Probability.Ballisticity.Crossings.ContinuousCrossPast +OAI.Probability.Ballisticity.Crossings.CoordinateHitExact +OAI.Probability.Ballisticity.Crossings.CrossTranslation +OAI.Probability.Ballisticity.Crossings.CrossingEstimate +OAI.Probability.Ballisticity.Crossings.CrossingGap +OAI.Probability.Ballisticity.Crossings.CrossingGapDecay +OAI.Probability.Ballisticity.Crossings.CrossingSurplus +OAI.Probability.Ballisticity.Crossings.CutoffTimeAverages +OAI.Probability.Ballisticity.Crossings.DeterministicCrossBound +OAI.Probability.Ballisticity.Crossings.FiniteBoxExit +OAI.Probability.Ballisticity.Crossings.FiniteHitOscillation +OAI.Probability.Ballisticity.Crossings.FinitePastCrossBound +OAI.Probability.Ballisticity.Crossings.FirstHitPairGap +OAI.Probability.Ballisticity.Crossings.FirstHitUpward +OAI.Probability.Ballisticity.Crossings.FirstLayerHitConcat +OAI.Probability.Ballisticity.Crossings.FirstLayerHitRecordIndexTime +OAI.Probability.Ballisticity.Crossings.FirstLayerHitRecordPrefix +OAI.Probability.Ballisticity.Crossings.FixedLowerCutoffEscape +OAI.Probability.Ballisticity.Crossings.GaussianBadCutoff +OAI.Probability.Ballisticity.Crossings.Hit +OAI.Probability.Ballisticity.Crossings.HitWord +OAI.Probability.Ballisticity.Crossings.HittingIteration +OAI.Probability.Ballisticity.Crossings.LowerObservedCut +OAI.Probability.Ballisticity.Crossings.NearCrossEstimates +OAI.Probability.Ballisticity.Crossings.OccupationCutoffs +OAI.Probability.Ballisticity.Crossings.OffDiagonalCenteredCross +OAI.Probability.Ballisticity.Crossings.PastCutoffs +OAI.Probability.Ballisticity.Crossings.PhysicalExit +OAI.Probability.Ballisticity.Crossings.PhysicalFirstHitGapHitWords +OAI.Probability.Ballisticity.Crossings.SharedInteriorCross +OAI.Probability.Ballisticity.Crossings.StripExitBound +OAI.Probability.Ballisticity.Crossings.TailCuts +OAI.Probability.Ballisticity.Crossings.UniformLowerCutoff +OAI.Probability.Ballisticity.Entropy.AnchorEntropy +OAI.Probability.Ballisticity.Entropy.BadWindowEntropy +OAI.Probability.Ballisticity.Entropy.BufferCostBounds +OAI.Probability.Ballisticity.Entropy.CanonicalLogExcess +OAI.Probability.Ballisticity.Entropy.DominatedEntropy +OAI.Probability.Ballisticity.Entropy.EntropyContinuousTests +OAI.Probability.Ballisticity.Entropy.EntropyDecorrelation +OAI.Probability.Ballisticity.Entropy.EntropyDensity +OAI.Probability.Ballisticity.Entropy.EntropyEvent +OAI.Probability.Ballisticity.Entropy.EntropyPlus +OAI.Probability.Ballisticity.Entropy.EntropyVariational +OAI.Probability.Ballisticity.Entropy.FiniteLogStability +OAI.Probability.Ballisticity.Entropy.OccupationEntropy +OAI.Probability.Ballisticity.Entropy.OccupationEntropy2 +OAI.Probability.Ballisticity.Entropy.OutwardOrder +OAI.Probability.Ballisticity.Entropy.StoppedEntropySum +OAI.Probability.Ballisticity.Entropy.StoppedWindowEntropy +OAI.Probability.Ballisticity.Entropy.WindowEntropy +OAI.Probability.Ballisticity.Entropy.WindowProjectionEntropy +OAI.Probability.Ballisticity.Estimates.AdaptiveFailureWeights +OAI.Probability.Ballisticity.Estimates.AeMaximalSquare +OAI.Probability.Ballisticity.Estimates.AlignedRecordPrefix +OAI.Probability.Ballisticity.Estimates.AllIndexMarks +OAI.Probability.Ballisticity.Estimates.AllLayerOccupation +OAI.Probability.Ballisticity.Estimates.AllOffsetConsistency +OAI.Probability.Ballisticity.Estimates.AnchorFrameReference +OAI.Probability.Ballisticity.Estimates.AnchorMoments +OAI.Probability.Ballisticity.Estimates.BadDropMoment +OAI.Probability.Ballisticity.Estimates.BadOccupationLimit +OAI.Probability.Ballisticity.Estimates.BadStageMoment +OAI.Probability.Ballisticity.Estimates.BindIntegral +OAI.Probability.Ballisticity.Estimates.BoundaryDecorrelation +OAI.Probability.Ballisticity.Estimates.BoundaryGapReplacement +OAI.Probability.Ballisticity.Estimates.BoundarySuffixIdentity +OAI.Probability.Ballisticity.Estimates.BoundedAnchorAverage +OAI.Probability.Ballisticity.Estimates.BudgetAdapted +OAI.Probability.Ballisticity.Estimates.BudgetAlgebra +OAI.Probability.Ballisticity.Estimates.BudgetClipping +OAI.Probability.Ballisticity.Estimates.BudgetEndpoint +OAI.Probability.Ballisticity.Estimates.BudgetLoss +OAI.Probability.Ballisticity.Estimates.BudgetMeasurable +OAI.Probability.Ballisticity.Estimates.BudgetNormalize +OAI.Probability.Ballisticity.Estimates.BudgetThreat +OAI.Probability.Ballisticity.Estimates.Buffer +OAI.Probability.Ballisticity.Estimates.BufferChanceData +OAI.Probability.Ballisticity.Estimates.BufferChildNode +OAI.Probability.Ballisticity.Estimates.BufferExcess +OAI.Probability.Ballisticity.Estimates.BufferFirstFailure +OAI.Probability.Ballisticity.Estimates.BufferRestorationScript +OAI.Probability.Ballisticity.Estimates.BufferRootRetention +OAI.Probability.Ballisticity.Estimates.BufferStageCount +OAI.Probability.Ballisticity.Estimates.BufferStagePacket +OAI.Probability.Ballisticity.Estimates.BufferStageSuccess +OAI.Probability.Ballisticity.Estimates.BufferTree +OAI.Probability.Ballisticity.Estimates.CappedExp +OAI.Probability.Ballisticity.Estimates.CappedLoss +OAI.Probability.Ballisticity.Estimates.CappedMomentTransfer +OAI.Probability.Ballisticity.Estimates.Cell +OAI.Probability.Ballisticity.Estimates.CellAttempt +OAI.Probability.Ballisticity.Estimates.CellBadEvent +OAI.Probability.Ballisticity.Estimates.CellCertificates +OAI.Probability.Ballisticity.Estimates.CellExhaustion +OAI.Probability.Ballisticity.Estimates.CellFailure +OAI.Probability.Ballisticity.Estimates.CellRadiusComparison +OAI.Probability.Ballisticity.Estimates.CellSchedule +OAI.Probability.Ballisticity.Estimates.CharacteristicProductLaw +OAI.Probability.Ballisticity.Estimates.CharacteristicTaylor +OAI.Probability.Ballisticity.Estimates.ClassFinset +OAI.Probability.Ballisticity.Estimates.ClassMoment +OAI.Probability.Ballisticity.Estimates.ClassSelection +OAI.Probability.Ballisticity.Estimates.ClippedAbsThreeHalves +OAI.Probability.Ballisticity.Estimates.ClippedInverse +OAI.Probability.Ballisticity.Estimates.ClippedThreeHalves +OAI.Probability.Ballisticity.Estimates.ClippingTime +OAI.Probability.Ballisticity.Estimates.ClosedEmbeddingWeak +OAI.Probability.Ballisticity.Estimates.CommonBoundaryRestart +OAI.Probability.Ballisticity.Estimates.CommonLayer +OAI.Probability.Ballisticity.Estimates.CommonOccupationBound +OAI.Probability.Ballisticity.Estimates.CommonOffset +OAI.Probability.Ballisticity.Estimates.CommonTrueRecord +OAI.Probability.Ballisticity.Estimates.CommonWidthProcess +OAI.Probability.Ballisticity.Estimates.CommonWordIncrement +OAI.Probability.Ballisticity.Estimates.CommonWordWidth +OAI.Probability.Ballisticity.Estimates.ConditionalLawTests +OAI.Probability.Ballisticity.Estimates.ConfinementTemplates +OAI.Probability.Ballisticity.Estimates.ConvolutionCentersClose +OAI.Probability.Ballisticity.Estimates.CountableProdBind +OAI.Probability.Ballisticity.Estimates.CurveCenter +OAI.Probability.Ballisticity.Estimates.CurveEndpointLaw +OAI.Probability.Ballisticity.Estimates.CurvePolicy +OAI.Probability.Ballisticity.Estimates.CurvePolicyAlignment +OAI.Probability.Ballisticity.Estimates.CurvePolicyAverageMoment +OAI.Probability.Ballisticity.Estimates.CurvePolicyLateral +OAI.Probability.Ballisticity.Estimates.CurvePolicyMaximal +OAI.Probability.Ballisticity.Estimates.CurvePolicyPMF +OAI.Probability.Ballisticity.Estimates.CurvePrefix +OAI.Probability.Ballisticity.Estimates.CurveShortBlock +OAI.Probability.Ballisticity.Estimates.CurveWordDisjoint +OAI.Probability.Ballisticity.Estimates.DensityTransfer +OAI.Probability.Ballisticity.Estimates.DescendingTrials +OAI.Probability.Ballisticity.Estimates.DifferentiableExp +OAI.Probability.Ballisticity.Estimates.DirectBridge +OAI.Probability.Ballisticity.Estimates.DominatedTranslationBounded +OAI.Probability.Ballisticity.Estimates.Dust +OAI.Probability.Ballisticity.Estimates.EndpointPrefix +OAI.Probability.Ballisticity.Estimates.EndpointPrefixConditionedReal +OAI.Probability.Ballisticity.Estimates.EventRate +OAI.Probability.Ballisticity.Estimates.FavorablePairFraction +OAI.Probability.Ballisticity.Estimates.FiniteClasses +OAI.Probability.Ballisticity.Estimates.FinitePastDecorrelation +OAI.Probability.Ballisticity.Estimates.FinitePolicyFailure +OAI.Probability.Ballisticity.Estimates.FinitePolicyPMF +OAI.Probability.Ballisticity.Estimates.FiniteStage +OAI.Probability.Ballisticity.Estimates.FirstBelow +OAI.Probability.Ballisticity.Estimates.FirstHighRecord +OAI.Probability.Ballisticity.Estimates.FirstWordEvent +OAI.Probability.Ballisticity.Estimates.FixedPairSuffix +OAI.Probability.Ballisticity.Estimates.FluctuationScaleUpperMultiple +OAI.Probability.Ballisticity.Estimates.FullCapTransfer +OAI.Probability.Ballisticity.Estimates.GaussianAbsTail +OAI.Probability.Ballisticity.Estimates.GaussianPiReal +OAI.Probability.Ballisticity.Estimates.GlobalContinuation +OAI.Probability.Ballisticity.Estimates.GlobalProfile +OAI.Probability.Ballisticity.Estimates.GlobalTuple +OAI.Probability.Ballisticity.Estimates.GridLinear +OAI.Probability.Ballisticity.Estimates.GridOccupation +OAI.Probability.Ballisticity.Estimates.GridOscillation +OAI.Probability.Ballisticity.Estimates.GridTrials +OAI.Probability.Ballisticity.Estimates.HighRecordCount +OAI.Probability.Ballisticity.Estimates.IidDifferenceCenteredHalf +OAI.Probability.Ballisticity.Estimates.IidListProcess +OAI.Probability.Ballisticity.Estimates.IndependentDyadic +OAI.Probability.Ballisticity.Estimates.IndependentPairLaw +OAI.Probability.Ballisticity.Estimates.IndependentRandomTestBound +OAI.Probability.Ballisticity.Estimates.IndependentRecenterMap +OAI.Probability.Ballisticity.Estimates.InputMarginal +OAI.Probability.Ballisticity.Estimates.IntegerMedian +OAI.Probability.Ballisticity.Estimates.InteriorPairMeasureExt +OAI.Probability.Ballisticity.Estimates.JointMeshPhase +OAI.Probability.Ballisticity.Estimates.JointPastMoments +OAI.Probability.Ballisticity.Estimates.JointPastRestart +OAI.Probability.Ballisticity.Estimates.LateMoment +OAI.Probability.Ballisticity.Estimates.LayerPairTruthEventMono +OAI.Probability.Ballisticity.Estimates.ListPrefixSum +OAI.Probability.Ballisticity.Estimates.LocalRadiusOrder +OAI.Probability.Ballisticity.Estimates.LocalStoppedSplice +OAI.Probability.Ballisticity.Estimates.LowerClip +OAI.Probability.Ballisticity.Estimates.MarkedObservables +OAI.Probability.Ballisticity.Estimates.MartingaleExponentialSubmartingale +OAI.Probability.Ballisticity.Estimates.MaxTailDecomposition +OAI.Probability.Ballisticity.Estimates.MeasurableCountableSample +OAI.Probability.Ballisticity.Estimates.MeasureAdd +OAI.Probability.Ballisticity.Estimates.MedianAeConst +OAI.Probability.Ballisticity.Estimates.MixtureSmallMassProbability +OAI.Probability.Ballisticity.Estimates.MomentRescaling +OAI.Probability.Ballisticity.Estimates.NaturalTailIntegrable +OAI.Probability.Ballisticity.Estimates.NoDropApproxError +OAI.Probability.Ballisticity.Estimates.NonCollapsedSums +OAI.Probability.Ballisticity.Estimates.NormalLinearPast +OAI.Probability.Ballisticity.Estimates.NormalizedRestrictionContact +OAI.Probability.Ballisticity.Estimates.NormalizedSharedRestrict +OAI.Probability.Ballisticity.Estimates.ObservedBudget +OAI.Probability.Ballisticity.Estimates.ObservedCharges +OAI.Probability.Ballisticity.Estimates.ObservedDrift +OAI.Probability.Ballisticity.Estimates.ObservedPotential +OAI.Probability.Ballisticity.Estimates.ObserverAlmostSure +OAI.Probability.Ballisticity.Estimates.OccupationAlgebra +OAI.Probability.Ballisticity.Estimates.OccupationLimit +OAI.Probability.Ballisticity.Estimates.OccupationParameters +OAI.Probability.Ballisticity.Estimates.OccupationSampling +OAI.Probability.Ballisticity.Estimates.OperationalLengthMarks +OAI.Probability.Ballisticity.Estimates.OperationalMarkBounds +OAI.Probability.Ballisticity.Estimates.OrderedTimes +OAI.Probability.Ballisticity.Estimates.OutwardCanonical +OAI.Probability.Ballisticity.Estimates.OutwardCapL1 +OAI.Probability.Ballisticity.Estimates.OutwardCapLocality +OAI.Probability.Ballisticity.Estimates.OwnMarginalOccupation +OAI.Probability.Ballisticity.Estimates.PairPrefix +OAI.Probability.Ballisticity.Estimates.PairUpwardRetention +OAI.Probability.Ballisticity.Estimates.PairWeakUniqueness +OAI.Probability.Ballisticity.Estimates.PastPhaseExtension +OAI.Probability.Ballisticity.Estimates.PolicyGoodMass +OAI.Probability.Ballisticity.Estimates.PrefixVariation +OAI.Probability.Ballisticity.Estimates.PrefixVariationNonneg +OAI.Probability.Ballisticity.Estimates.ProbabilityLowerTransfer +OAI.Probability.Ballisticity.Estimates.ProductNormalJointPast +OAI.Probability.Ballisticity.Estimates.ProductTruncationError +OAI.Probability.Ballisticity.Estimates.ProfileMeasureUpdate +OAI.Probability.Ballisticity.Estimates.ProperProfile +OAI.Probability.Ballisticity.Estimates.ProtectionFirstFailure +OAI.Probability.Ballisticity.Estimates.ProtectionLoss +OAI.Probability.Ballisticity.Estimates.RadixBudget +OAI.Probability.Ballisticity.Estimates.RapidDecay +OAI.Probability.Ballisticity.Estimates.RapidDecaySubsequence +OAI.Probability.Ballisticity.Estimates.RapidDecayTail +OAI.Probability.Ballisticity.Estimates.RawConditionedWeight +OAI.Probability.Ballisticity.Estimates.RawDropBounds +OAI.Probability.Ballisticity.Estimates.RawPair +OAI.Probability.Ballisticity.Estimates.RawPairEndpoint +OAI.Probability.Ballisticity.Estimates.RawPairLocality +OAI.Probability.Ballisticity.Estimates.RawPairMassComposition +OAI.Probability.Ballisticity.Estimates.RawPairRetention +OAI.Probability.Ballisticity.Estimates.RealJointPastRestart +OAI.Probability.Ballisticity.Estimates.RecordIndexTime +OAI.Probability.Ballisticity.Estimates.RecordMedianSlope +OAI.Probability.Ballisticity.Estimates.RecordOrPrefixAdd +OAI.Probability.Ballisticity.Estimates.RecordPairFuture +OAI.Probability.Ballisticity.Estimates.RecordPrefixControl +OAI.Probability.Ballisticity.Estimates.ReferenceContinuity +OAI.Probability.Ballisticity.Estimates.ReferenceFeller +OAI.Probability.Ballisticity.Estimates.RelativeBudget +OAI.Probability.Ballisticity.Estimates.RestartLyapunov +OAI.Probability.Ballisticity.Estimates.RestartSupportedBound +OAI.Probability.Ballisticity.Estimates.RetainedComposition +OAI.Probability.Ballisticity.Estimates.Sampling +OAI.Probability.Ballisticity.Estimates.SamplingLaw +OAI.Probability.Ballisticity.Estimates.SamplingLimit +OAI.Probability.Ballisticity.Estimates.SamplingRearrangement +OAI.Probability.Ballisticity.Estimates.ScaledMaxMoment +OAI.Probability.Ballisticity.Estimates.ScaledMaxTail +OAI.Probability.Ballisticity.Estimates.ScheduledCellSuccess +OAI.Probability.Ballisticity.Estimates.SecondMomentConcentration +OAI.Probability.Ballisticity.Estimates.SelectedBoundaryRestart +OAI.Probability.Ballisticity.Estimates.SelectedEndpointMoment +OAI.Probability.Ballisticity.Estimates.SharedConditionedContactBound +OAI.Probability.Ballisticity.Estimates.SharedConditionedPairLawFst +OAI.Probability.Ballisticity.Estimates.SharedEndpointOverlapRight +OAI.Probability.Ballisticity.Estimates.SharedEndpointTests +OAI.Probability.Ballisticity.Estimates.SharedLimitNormalPast +OAI.Probability.Ballisticity.Estimates.SharedLimitOccupation +OAI.Probability.Ballisticity.Estimates.SharedLimitPastIdentity +OAI.Probability.Ballisticity.Estimates.SharedShrinking +OAI.Probability.Ballisticity.Estimates.SharedWordCylinderLower +OAI.Probability.Ballisticity.Estimates.ShiftedCurveConcatenation +OAI.Probability.Ballisticity.Estimates.SignedPrefixComparison +OAI.Probability.Ballisticity.Estimates.SingleAdjacentRadiusBound +OAI.Probability.Ballisticity.Estimates.SingleCoverWord +OAI.Probability.Ballisticity.Estimates.SingleThreat +OAI.Probability.Ballisticity.Estimates.SmallScaleGaussianMass +OAI.Probability.Ballisticity.Estimates.SmallScaleTailMoment +OAI.Probability.Ballisticity.Estimates.SmallTimeExponentialError +OAI.Probability.Ballisticity.Estimates.StageClassification +OAI.Probability.Ballisticity.Estimates.StageExponentialScales +OAI.Probability.Ballisticity.Estimates.StageInjection +OAI.Probability.Ballisticity.Estimates.StageParameters +OAI.Probability.Ballisticity.Estimates.StageRetention +OAI.Probability.Ballisticity.Estimates.StageStopping +OAI.Probability.Ballisticity.Estimates.StayUntil +OAI.Probability.Ballisticity.Estimates.StoppedSplice +OAI.Probability.Ballisticity.Estimates.StrictRecord +OAI.Probability.Ballisticity.Estimates.SuccessfulAverage +OAI.Probability.Ballisticity.Estimates.SuccessfulAverageBind +OAI.Probability.Ballisticity.Estimates.SuccessfulScaledTail +OAI.Probability.Ballisticity.Estimates.SuccessfulWords +OAI.Probability.Ballisticity.Estimates.SurvivalConditional +OAI.Probability.Ballisticity.Estimates.SurvivalLimit +OAI.Probability.Ballisticity.Estimates.SurvivingLane +OAI.Probability.Ballisticity.Estimates.SymmetricPrefixTail +OAI.Probability.Ballisticity.Estimates.SymmetricTruncate +OAI.Probability.Ballisticity.Estimates.SymmetrizedMgf +OAI.Probability.Ballisticity.Estimates.TailProfile +OAI.Probability.Ballisticity.Estimates.TailSampling +OAI.Probability.Ballisticity.Estimates.TightIidDifferenceTranslations +OAI.Probability.Ballisticity.Estimates.TripleTestPerturbation +OAI.Probability.Ballisticity.Estimates.TruncatedVarianceDouble +OAI.Probability.Ballisticity.Estimates.TupleClipping +OAI.Probability.Ballisticity.Estimates.TupleEndpoint +OAI.Probability.Ballisticity.Estimates.TwoStopSplice +OAI.Probability.Ballisticity.Estimates.UniformLowerMass +OAI.Probability.Ballisticity.Estimates.UniformRiemannMesh +OAI.Probability.Ballisticity.Estimates.UniformSpreadSequences +OAI.Probability.Ballisticity.Estimates.UpperPairPatch +OAI.Probability.Ballisticity.Estimates.VarianceTailDifference +OAI.Probability.Ballisticity.Estimates.VisibleFailure +OAI.Probability.Ballisticity.Estimates.VisitTrials +OAI.Probability.Ballisticity.Estimates.WeakAddTendsto +OAI.Probability.Ballisticity.Estimates.WeakTailTransfer +OAI.Probability.Ballisticity.Estimates.WeakVaryingParameter +OAI.Probability.Ballisticity.Estimates.WeightedConditioned +OAI.Probability.Ballisticity.Estimates.WeightedTestPerturbation +OAI.Probability.Ballisticity.Estimates.WidthGridTail +OAI.Probability.Ballisticity.Estimates.WordConcatenation +OAI.Probability.Ballisticity.Estimates.WordDepartures +OAI.Probability.Ballisticity.Estimates.WordPrefixes +OAI.Probability.Ballisticity.Estimates.WordTemplate +OAI.Probability.Ballisticity.Geometry.AlignedSlabs +OAI.Probability.Ballisticity.Geometry.BufferAllHeightRetention +OAI.Probability.Ballisticity.Geometry.BufferElapsedHeight +OAI.Probability.Ballisticity.Geometry.BufferStructuralHeight +OAI.Probability.Ballisticity.Geometry.CenteredHeightAdditiveUniform +OAI.Probability.Ballisticity.Geometry.CoordinateLanesDisjoint +OAI.Probability.Ballisticity.Geometry.CoordinateStrip +OAI.Probability.Ballisticity.Geometry.CurvePolicyTubeMass +OAI.Probability.Ballisticity.Geometry.CurveWordTube +OAI.Probability.Ballisticity.Geometry.FiniteConditionalDensityTubeTransfer +OAI.Probability.Ballisticity.Geometry.FiniteCoordinateApproximation +OAI.Probability.Ballisticity.Geometry.FinitePastCoordinates +OAI.Probability.Ballisticity.Geometry.FiniteWordGeometry +OAI.Probability.Ballisticity.Geometry.HeightIncrement +OAI.Probability.Ballisticity.Geometry.HeightPolygon +OAI.Probability.Ballisticity.Geometry.HeightPolygonRandomShiftSmall +OAI.Probability.Ballisticity.Geometry.HeightPolygonTranslateApply +OAI.Probability.Ballisticity.Geometry.HeightSlab +OAI.Probability.Ballisticity.Geometry.HeightTubeWindow +OAI.Probability.Ballisticity.Geometry.JointTubeSuccess +OAI.Probability.Ballisticity.Geometry.LatticeVector +OAI.Probability.Ballisticity.Geometry.MedianTubeFailure +OAI.Probability.Ballisticity.Geometry.NormHeightPolygon +OAI.Probability.Ballisticity.Geometry.OccupationWindow +OAI.Probability.Ballisticity.Geometry.PairHeight +OAI.Probability.Ballisticity.Geometry.RawMedianTubeSingleSite +OAI.Probability.Ballisticity.Geometry.RawWindow +OAI.Probability.Ballisticity.Geometry.RecordIndexPrefixHeight +OAI.Probability.Ballisticity.Geometry.RestrictedWindow +OAI.Probability.Ballisticity.Geometry.SignedCoordinate +OAI.Probability.Ballisticity.Geometry.SignedHeight +OAI.Probability.Ballisticity.Geometry.SignedHeightSub +OAI.Probability.Ballisticity.Geometry.SignedStripTruncation +OAI.Probability.Ballisticity.Geometry.SpatialConfinement +OAI.Probability.Ballisticity.Geometry.StoppedTubeEndpoint +OAI.Probability.Ballisticity.Geometry.StripTimeTail +OAI.Probability.Ballisticity.Geometry.SuccessfulAverageTubeTransfer +OAI.Probability.Ballisticity.Geometry.SumWindowDifference +OAI.Probability.Ballisticity.Geometry.TubeEndpoint +OAI.Probability.Ballisticity.Geometry.TubeHeightMono +OAI.Probability.Ballisticity.Geometry.TubePrefix +OAI.Probability.Ballisticity.Geometry.TubePrefixMass +OAI.Probability.Ballisticity.Geometry.TubePrefixMonoRadius +OAI.Probability.Ballisticity.Geometry.WeightedConditionedTubeTransfer +OAI.Probability.Ballisticity.Geometry.WindowProjection +OAI.Probability.Ballisticity.Geometry.WindowWeak +OAI.Probability.Ballisticity.Geometry.WordCoordinate +OAI.Probability.Ballisticity.Geometry.WordHeightGain +OAI.Probability.Ballisticity.Main +OAI.Probability.Ballisticity.Model +OAI.Probability.Ballisticity.Renewal.ClippingPositiveNumbers +OAI.Probability.Ballisticity.Renewal.CurvePositiveScale +OAI.Probability.Ballisticity.Renewal.DurationMoment +OAI.Probability.Ballisticity.Renewal.DurationTail +OAI.Probability.Ballisticity.Renewal.PositiveLengthMark +OAI.Probability.Ballisticity.Renewal.PositiveOpenTest +OAI.Probability.Ballisticity.Renewal.PositiveQuenchedEvent +OAI.Probability.Ballisticity.Renewal.Regeneration +OAI.Probability.Ballisticity.Renewal.RegenerationWords +OAI.Probability.Ballisticity.Renewal.RenewalCountBounds +OAI.Probability.Ballisticity.Renewal.VelocityWords +OAI.Probability.Ballisticity.Stationary.Array +OAI.Probability.Ballisticity.Stationary.ArrayClassProbability +OAI.Probability.Ballisticity.Stationary.ArrayClosed +OAI.Probability.Ballisticity.Stationary.ArrayDust +OAI.Probability.Ballisticity.Stationary.ArrayFiniteClasses +OAI.Probability.Ballisticity.Stationary.ArrayFull +OAI.Probability.Ballisticity.Stationary.ArrayMap +OAI.Probability.Ballisticity.Stationary.ArrayMarkTests +OAI.Probability.Ballisticity.Stationary.ArrayMarkedEntropy +OAI.Probability.Ballisticity.Stationary.ArrayMarkedIterate +OAI.Probability.Ballisticity.Stationary.ArrayMassSurvival +OAI.Probability.Ballisticity.Stationary.ArrayPermutation +OAI.Probability.Ballisticity.Stationary.ArrayProfileConsistency +OAI.Probability.Ballisticity.Stationary.ArraySurvival +OAI.Probability.Ballisticity.Stationary.ArrayTopology +OAI.Probability.Ballisticity.Stationary.ArrayWindowMarks +OAI.Probability.Ballisticity.Stationary.BadArrayElliptic +OAI.Probability.Ballisticity.Stationary.BadArraySampling +OAI.Probability.Ballisticity.Stationary.BadCrossingEpisodes +OAI.Probability.Ballisticity.Stationary.BadFiniteArray +OAI.Probability.Ballisticity.Stationary.CompactCapTransfer +OAI.Probability.Ballisticity.Stationary.EpisodeAdapted +OAI.Probability.Ballisticity.Stationary.EpisodeCharts +OAI.Probability.Ballisticity.Stationary.EpisodeCountLedger +OAI.Probability.Ballisticity.Stationary.EpisodeCounterChain +OAI.Probability.Ballisticity.Stationary.EpisodeDropLedger +OAI.Probability.Ballisticity.Stationary.EpisodeEntropyTelescoping +OAI.Probability.Ballisticity.Stationary.EpisodeExponential +OAI.Probability.Ballisticity.Stationary.EpisodeFresh +OAI.Probability.Ballisticity.Stationary.EpisodeGlobalRetention +OAI.Probability.Ballisticity.Stationary.EpisodeInjection +OAI.Probability.Ballisticity.Stationary.EpisodeLength +OAI.Probability.Ballisticity.Stationary.EpisodeLogLength +OAI.Probability.Ballisticity.Stationary.EpisodeMeanDrop +OAI.Probability.Ballisticity.Stationary.EpisodeNumber +OAI.Probability.Ballisticity.Stationary.EpisodePotentialIteration +OAI.Probability.Ballisticity.Stationary.EpisodeRandomStart +OAI.Probability.Ballisticity.Stationary.EpisodeRecordedAtlas +OAI.Probability.Ballisticity.Stationary.EpisodeRetention +OAI.Probability.Ballisticity.Stationary.LocalEpisodeLog +OAI.Probability.Ballisticity.Stationary.OperationalEpisode +OAI.Probability.Ballisticity.Stationary.StationaryArrayLaw +OAI.Probability.Ballisticity.Stationary.StationaryCompact +OAI.Probability.Ballisticity.Stationary.StationaryMarking +OAI.Probability.Ballisticity.Stationary.StationaryMonotone +OAI.Probability.Ballisticity.Stationary.StationaryProfile +OAI.Probability.Ballisticity.Stationary.StationaryProfile2 +OAI.Probability.Ballisticity.Stationary.StationaryWindowEntropy +OAI.Probability.Ballisticity.Walk.ArrayCostGrowth +OAI.Probability.Ballisticity.Walk.ArrayGrowthEvent +OAI.Probability.Ballisticity.Walk.BoundaryPathCoordinates +OAI.Probability.Ballisticity.Walk.BufferGrowthArithmetic +OAI.Probability.Ballisticity.Walk.BufferHistoryBracket +OAI.Probability.Ballisticity.Walk.BufferNormalizedRows +OAI.Probability.Ballisticity.Walk.ClippedPairGrowth +OAI.Probability.Ballisticity.Walk.CompactPathModulus +OAI.Probability.Ballisticity.Walk.CoordinateKernelComp +OAI.Probability.Ballisticity.Walk.CurvePolicyKernel +OAI.Probability.Ballisticity.Walk.FiniteOutwardRowApproximation +OAI.Probability.Ballisticity.Walk.FixedQuenchedKernel +OAI.Probability.Ballisticity.Walk.FreshRowWeights +OAI.Probability.Ballisticity.Walk.GaussianPathFiniteLawSingleton +OAI.Probability.Ballisticity.Walk.GaussianPathFiniteLawSmul +OAI.Probability.Ballisticity.Walk.JointPathIndependence +OAI.Probability.Ballisticity.Walk.Kernel +OAI.Probability.Ballisticity.Walk.KernelBoundedExpectation +OAI.Probability.Ballisticity.Walk.KernelSections +OAI.Probability.Ballisticity.Walk.KernelTranslation +OAI.Probability.Ballisticity.Walk.OutwardCanonicalRows +OAI.Probability.Ballisticity.Walk.OutwardKernelElementary +OAI.Probability.Ballisticity.Walk.PathCompact +OAI.Probability.Ballisticity.Walk.PathPointMean +OAI.Probability.Ballisticity.Walk.PathWindowTest +OAI.Probability.Ballisticity.Walk.PreBrownianGridMartingale +OAI.Probability.Ballisticity.Walk.ProfileGrowth +OAI.Probability.Ballisticity.Walk.ProfileGrowth2 +OAI.Probability.Ballisticity.Walk.QuenchedRegularPathAe +OAI.Probability.Ballisticity.Walk.RawPairKernel +OAI.Probability.Ballisticity.Walk.RecordLinearPath +OAI.Probability.Ballisticity.Walk.RegularPath +OAI.Probability.Ballisticity.Walk.RetentionRowsAllHeights +OAI.Probability.Ballisticity.Walk.RowProductIntegral +OAI.Probability.Ballisticity.Walk.Rows +OAI.Probability.Ballisticity.Walk.SelectedFiniteKernel +OAI.Probability.Ballisticity.Walk.SelectedKernelMap +OAI.Probability.Ballisticity.Walk.SharedPairPathLimit +OAI.Probability.Ballisticity.Walk.StateTrajectory +OAI.Probability.Ballisticity.Walk.StationaryGrowth +OAI.Probability.Ballisticity.Walk.TailGrowth +OAI.Probability.Ballisticity.Walk.TransverseFirstHitSinglePathLimit +OAI.Probability.Ballisticity.Walk.UniformFinsetKernel +OAI.Probability.Ballisticity.Walk.UpperKernel +OAI.Probability.Ballisticity.Walk.VaryingHeightPathGaussianEval +OAI.Probability.Ballisticity.Walk.WeakPathEvalTendsto +OAI.Probability.Ballisticity.Walk.WienerPathMaximal diff --git a/tasks/directional-ballisticity/solution/reference.py b/tasks/directional-ballisticity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/directional-ballisticity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/directional-ballisticity/solution/solve.sh b/tasks/directional-ballisticity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bbe931d39348a24d5f692003ff70409491244f53 --- /dev/null +++ b/tasks/directional-ballisticity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DirectionalBallisticity, i.e. module OAI.Probability.Ballisticity.Main and the +# 513 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Ballisticity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DirectionalBallisticity" diff --git a/tasks/directional-ballisticity/task.toml b/tasks/directional-ballisticity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca7adde4d0fb2a258308652c45d89720fc2288d8 --- /dev/null +++ b/tasks/directional-ballisticity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/directional-ballisticity" +version = "1.0.0" +description = "Prove DirectionalBallisticity (openai/math family 220: Directional zero–one laws and ballisticity in random environments) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DirectionalBallisticity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DirectionalBallisticity" +family = "220" +family_title = "Directional zero–one laws and ballisticity in random environments" +subject = "Probability and statistical mechanics" +theorems = ["OAI.DirectionalTransience.directional_transience_implies_ballisticity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Ballisticity.Main" +reference_modules = 513 +reference_lean_bytes = 5012403 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1730 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 16211 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/directional-ballisticity/tests/Challenge.lean b/tasks/directional-ballisticity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a52ef70a36e506bedc50c4759bc442e005b22eef --- /dev/null +++ b/tasks/directional-ballisticity/tests/Challenge.lean @@ -0,0 +1,100 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped ENNReal NNReal BigOperators Topology + +namespace DirectionalTransience + +abbrev Lattice (d : ℕ) := Fin d → ℤ +abbrev Direction (d : ℕ) := Fin d × Bool +abbrev Vector (d : ℕ) := Fin d → ℝ +abbrev Row (d : ℕ) := {p : Direction d → ℝ≥0 // ∑ e, p e = 1} +abbrev Environment (d : ℕ) := Lattice d → Row d +abbrev State (d : ℕ) := Environment d × Lattice d +abbrev Path (d : ℕ) := ℕ → Lattice d + +def step {d : ℕ} (e : Direction d) : Lattice d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +noncomputable def environmentLaw {d : ℕ} (ν : Measure (Row d)) : + Measure (Environment d) := Measure.infinitePi (fun _ => ν) + +def UniformElliptic {d : ℕ} (ν : Measure (Row d)) : Prop := + ∃ κ : ℝ≥0, 0 < κ ∧ ∀ᵐ p ∂ν, ∀ e, κ ≤ p.1 e + +lemma measurable_current_row {d : ℕ} : + Measurable (fun z : State d => z.1 z.2) := by + apply measurable_from_prod_countable_left + intro x + exact measurable_pi_apply x + +noncomputable def transition {d : ℕ} : Kernel (State d) (State d) where + toFun z := ∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e) + measurable' := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.finsetSum_apply, Measure.smul_apply, smul_eq_mul] + apply Finset.measurable_fun_sum + intro e _ + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp measurable_current_row)).coe_nnreal_ennreal + · exact (Measure.measurable_coe hs).comp + (Measure.measurable_dirac.comp (measurable_fst.prodMk + (measurable_snd.add_const (step e)))) + +instance transition_markov {d : ℕ} : IsMarkovKernel (transition (d := d)) where + isProbabilityMeasure z := by + constructor + change (∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, Measure.dirac_apply_of_mem + (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofNNReal_finsetSum, (z.1 z.2).2] + rfl + +noncomputable def historyTransition {d : ℕ} (n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) where + toFun z := transition (z ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + measurable' := transition.measurable.comp (measurable_pi_apply _) + +instance historyTransition_markov {d : ℕ} (n : ℕ) : + IsMarkovKernel (historyTransition (d := d) n) where + isProbabilityMeasure _ := transition_markov.isProbabilityMeasure _ + +noncomputable def initialLaw {d : ℕ} (ν : Measure (Row d)) : Measure (State d) := + (environmentLaw ν).map (fun ω => (ω, (0 : Lattice d))) + +noncomputable def annealedLaw {d : ℕ} (ν : Measure (Row d)) : Measure (Path d) := + (@Kernel.trajMeasure (fun _ => State d) _ (initialLaw ν) (historyTransition (d := d)) _).map + (fun z n => (z n).2) + +def dot {d : ℕ} (v ℓ : Vector d) : ℝ := ∑ i, v i * ℓ i + +def realPosition {d : ℕ} (x : Lattice d) : Vector d := fun i => (x i : ℝ) + +def DirectionallyTransient {d : ℕ} (ν : Measure (Row d)) (ℓ : Vector d) : Prop := + ∀ᵐ X ∂annealedLaw ν, + Tendsto (fun n => dot (realPosition (X n)) ℓ) atTop atTop + +def HasVelocity {d : ℕ} (ν : Measure (Row d)) (v : Vector d) : Prop := + ∀ᵐ X ∂annealedLaw ν, + Tendsto (fun n : ℕ => (fun i => (X n i : ℝ) / (n : ℝ))) atTop (𝓝 v) + +open scoped ENNReal NNReal Classical Topology BigOperators + +def MainStatement : Prop := + ∀ (d : ℕ), 2 ≤ d → ∀ (ν : Measure (Row d)), IsProbabilityMeasure ν → + UniformElliptic ν → ∀ (ℓ : Vector d), dot ℓ ℓ = 1 → + DirectionallyTransient ν ℓ → + ∃ v : Vector d, 0 < dot v ℓ ∧ HasVelocity ν v + +theorem directional_transience_implies_ballisticity : MainStatement := by + sorry + +end DirectionalTransience + +end OAI diff --git a/tasks/directional-ballisticity/tests/grade.py b/tasks/directional-ballisticity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/directional-ballisticity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/directional-ballisticity/tests/task.json b/tasks/directional-ballisticity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..653f645c6926d29b49a5b469596809c8a896f422 --- /dev/null +++ b/tasks/directional-ballisticity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DirectionalBallisticity", + "comparator": { + "theorem_names": [ + "OAI.DirectionalTransience.directional_transience_implies_ballisticity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 15311 +} \ No newline at end of file diff --git a/tasks/directional-ballisticity/tests/test.sh b/tasks/directional-ballisticity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/directional-ballisticity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/directional-walk/environment/Dockerfile b/tasks/directional-walk/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/directional-walk/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/directional-walk/environment/fetch_mathlib.sh b/tasks/directional-walk/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/directional-walk/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/directional-walk/environment/lake-manifest.json b/tasks/directional-walk/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/directional-walk/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/directional-walk/environment/lakefile.lean b/tasks/directional-walk/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/directional-walk/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/directional-walk/environment/lean_setup.sh b/tasks/directional-walk/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/directional-walk/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/directional-walk/environment/pack_submission.py b/tasks/directional-walk/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/directional-walk/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/directional-walk/instruction.md b/tasks/directional-walk/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..121c4842ed78fec88765c072fe0ea6af12343be9 --- /dev/null +++ b/tasks/directional-walk/instruction.md @@ -0,0 +1,143 @@ +# openai/math challenge `DirectionalWalk` (family 220) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 220 of the release, *Directional zero–one laws and ballisticity in random environments* +(Probability and statistical mechanics). The family as a whole: On $\mathbb Z^d$, $d\ge3$, directional escape has probability zero or one for iid strictly elliptic nearest-neighbor environments, and for stationary ergodic finite-range-dependent environments under uniform ellipticity. In iid uniformly elliptic environments with $d\ge2$, almost-sure directional transience implies a deterministic limiting velocity with positive projection in that direction, resolving the ballisticity conjecture. + +The challenge is `DirectionalWalk`, also at `/opt/openai-math/challenges/DirectionalWalk.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter Preorder +open scoped ENNReal BigOperators Topology + +namespace DirectionalZeroOne + +abbrev Site (d : ℕ) := Fin d → ℤ +abbrev Step (d : ℕ) := Fin d × Bool + +def stepVector {d : ℕ} (e : Step d) : Site d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +def Row (d : ℕ) := + {p : Step d → ℝ // (∀ e, p e ∈ Set.Icc (0 : ℝ) 1) ∧ ∑ e, p e = 1} + +instance (d : ℕ) : MeasurableSpace (Row d) := inferInstanceAs + (MeasurableSpace {p : Step d → ℝ // + (∀ e, p e ∈ Set.Icc (0 : ℝ) 1) ∧ ∑ e, p e = 1}) + +abbrev Environment (d : ℕ) := Site d → Row d +abbrev Path (d : ℕ) := ℕ → Site d +abbrev State (d : ℕ) := Environment d × Site d + +def StrictEllipticity {d : ℕ} (μ : Measure (Row d)) : Prop := + ∀ᵐ p ∂μ, ∀ e, 0 < p.val e + +noncomputable def environmentLaw {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] : Measure (Environment d) := + Measure.infinitePi (fun _ => μ) + +noncomputable def transition (d : ℕ) : Kernel (State d) (State d) where + toFun s := ∑ e : Step d, + ENNReal.ofReal ((s.1 s.2).val e) • Measure.dirac (s.1, s.2 + stepVector e) + measurable' := by + apply measurable_from_prod_countable_left + intro x + apply Finset.measurable_sum + intro e he + apply Measure.measurable_of_measurable_coe + intro t ht + simp only [Measure.smul_apply, smul_eq_mul] + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp (measurable_pi_apply x))).ennreal_ofReal + · exact (Measure.measurable_coe ht).comp + (Measure.measurable_dirac.comp (measurable_id.prodMk measurable_const)) + +instance (d : ℕ) : IsMarkovKernel (transition d) where + isProbabilityMeasure s := by + constructor + change (∑ e : Step d, + ENNReal.ofReal ((s.1 s.2).val e) • + Measure.dirac (s.1, s.2 + stepVector e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, + Measure.dirac_apply_of_mem (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofReal_sum_of_nonneg] + · rw [(s.1 s.2).property.2, ENNReal.ofReal_one] + · intro e he + exact ((s.1 s.2).property.1 e).1 + +noncomputable def historyKernel (d n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) := + (transition d).comap (fun h => h ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + (measurable_pi_apply _) + +instance (d n : ℕ) : IsMarkovKernel (historyKernel d n) := by + unfold historyKernel + infer_instance + +noncomputable def initialLaw {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] (x : Site d) : Measure (State d) := + (environmentLaw μ).map (fun ω => (ω, x)) + +noncomputable def annealed {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] (x : Site d) : Measure (Path d) := + (Kernel.trajMeasure (X := fun _ => State d) (initialLaw μ x) (historyKernel d)).map + (fun z n => (z n).2) + +def escape {d : ℕ} (ℓ : Fin d → ℝ) : Set (Path d) := + {X | Tendsto (fun n => ∑ i, (X n i : ℝ) * ℓ i) atTop atTop} + +theorem directional_zero_one (d : ℕ) (hd : 3 ≤ d) + (μ : Measure (Row d)) [IsProbabilityMeasure μ] + (hell : StrictEllipticity μ) (ℓ : Fin d → ℝ) (hℓ : ℓ ≠ 0) : + annealed μ 0 (escape ℓ) = 0 ∨ annealed μ 0 (escape ℓ) = 1 := by sorry + +end DirectionalZeroOne + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DirectionalWalk.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DirectionalZeroOne.directional_zero_one` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/directional-walk/solution/closure.txt b/tasks/directional-walk/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fb0a520900f7aa9c0182e9a20f392d195e4a799 --- /dev/null +++ b/tasks/directional-walk/solution/closure.txt @@ -0,0 +1,69 @@ +OAI.Probability.DirectionalWalk.ActualComparison +OAI.Probability.DirectionalWalk.Avoidance +OAI.Probability.DirectionalWalk.Axis +OAI.Probability.DirectionalWalk.AxisBridges +OAI.Probability.DirectionalWalk.AxisCubes +OAI.Probability.DirectionalWalk.BandContacts +OAI.Probability.DirectionalWalk.BridgeKernels +OAI.Probability.DirectionalWalk.BridgeWords +OAI.Probability.DirectionalWalk.BufferEntropy +OAI.Probability.DirectionalWalk.BufferedComparison +OAI.Probability.DirectionalWalk.Columns +OAI.Probability.DirectionalWalk.CommonBands +OAI.Probability.DirectionalWalk.CommonBlocks +OAI.Probability.DirectionalWalk.ContactBins +OAI.Probability.DirectionalWalk.ContactEvents +OAI.Probability.DirectionalWalk.ContactGeometry +OAI.Probability.DirectionalWalk.ContactJoins +OAI.Probability.DirectionalWalk.CountWindows +OAI.Probability.DirectionalWalk.CylinderLaw +OAI.Probability.DirectionalWalk.DirectionalReduction +OAI.Probability.DirectionalWalk.DyadicBounds +OAI.Probability.DirectionalWalk.DyadicCover +OAI.Probability.DirectionalWalk.Entropy +OAI.Probability.DirectionalWalk.EntropyBounds +OAI.Probability.DirectionalWalk.EntropyLaws +OAI.Probability.DirectionalWalk.EntropyTransforms +OAI.Probability.DirectionalWalk.EntropyUpperBound +OAI.Probability.DirectionalWalk.Escape +OAI.Probability.DirectionalWalk.ExperimentContact +OAI.Probability.DirectionalWalk.FiniteContacts +OAI.Probability.DirectionalWalk.FreshContacts +OAI.Probability.DirectionalWalk.FreshPaths +OAI.Probability.DirectionalWalk.HittingWords +OAI.Probability.DirectionalWalk.Information +OAI.Probability.DirectionalWalk.JoinedBridges +OAI.Probability.DirectionalWalk.LateContacts +OAI.Probability.DirectionalWalk.LateEndpoints +OAI.Probability.DirectionalWalk.LatePrefixes +OAI.Probability.DirectionalWalk.Main +OAI.Probability.DirectionalWalk.MarkedSums +OAI.Probability.DirectionalWalk.MixedTapes +OAI.Probability.DirectionalWalk.Model +OAI.Probability.DirectionalWalk.PosteriorMax +OAI.Probability.DirectionalWalk.PosteriorTails +OAI.Probability.DirectionalWalk.Radii +OAI.Probability.DirectionalWalk.RadiusLaunch +OAI.Probability.DirectionalWalk.RadiusMoment +OAI.Probability.DirectionalWalk.RadiusTails +OAI.Probability.DirectionalWalk.Records +OAI.Probability.DirectionalWalk.Regeneration +OAI.Probability.DirectionalWalk.RegenerativeTapes +OAI.Probability.DirectionalWalk.RelativeContinuation +OAI.Probability.DirectionalWalk.RelativeEntropy +OAI.Probability.DirectionalWalk.Renewal +OAI.Probability.DirectionalWalk.RenewalFactorization +OAI.Probability.DirectionalWalk.RenewalMass +OAI.Probability.DirectionalWalk.ReversedContacts +OAI.Probability.DirectionalWalk.ShiftedBlocks +OAI.Probability.DirectionalWalk.Shifts +OAI.Probability.DirectionalWalk.SignedInformation +OAI.Probability.DirectionalWalk.Slabs +OAI.Probability.DirectionalWalk.SumLaws +OAI.Probability.DirectionalWalk.ThreeChunks +OAI.Probability.DirectionalWalk.ThreeLists +OAI.Probability.DirectionalWalk.TotalEntropy +OAI.Probability.DirectionalWalk.TwoTapes +OAI.Probability.DirectionalWalk.Widths +OAI.Probability.DirectionalWalk.WordPosterior +OAI.Probability.DirectionalWalk.Words diff --git a/tasks/directional-walk/solution/reference.py b/tasks/directional-walk/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/directional-walk/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/directional-walk/solution/solve.sh b/tasks/directional-walk/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..acf43bb2de2fe0652b2a7d2c6173ae27be38ba95 --- /dev/null +++ b/tasks/directional-walk/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DirectionalWalk, i.e. module OAI.Probability.DirectionalWalk.Main and the +# 69 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.DirectionalWalk.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DirectionalWalk" diff --git a/tasks/directional-walk/task.toml b/tasks/directional-walk/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7915cb4abdddeffb75cd520dbeb88c37f9893086 --- /dev/null +++ b/tasks/directional-walk/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/directional-walk" +version = "1.0.0" +description = "Prove DirectionalWalk (openai/math family 220: Directional zero–one laws and ballisticity in random environments) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DirectionalWalk.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DirectionalWalk" +family = "220" +family_title = "Directional zero–one laws and ballisticity in random environments" +subject = "Probability and statistical mechanics" +theorems = ["OAI.DirectionalZeroOne.directional_zero_one"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.DirectionalWalk.Main" +reference_modules = 69 +reference_lean_bytes = 951618 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 968 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12556 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/directional-walk/tests/Challenge.lean b/tasks/directional-walk/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9d324a1a922d9bfc497417d985ca7b33138e17ef --- /dev/null +++ b/tasks/directional-walk/tests/Challenge.lean @@ -0,0 +1,92 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter Preorder +open scoped ENNReal BigOperators Topology + +namespace DirectionalZeroOne + +abbrev Site (d : ℕ) := Fin d → ℤ +abbrev Step (d : ℕ) := Fin d × Bool + +def stepVector {d : ℕ} (e : Step d) : Site d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +def Row (d : ℕ) := + {p : Step d → ℝ // (∀ e, p e ∈ Set.Icc (0 : ℝ) 1) ∧ ∑ e, p e = 1} + +instance (d : ℕ) : MeasurableSpace (Row d) := inferInstanceAs + (MeasurableSpace {p : Step d → ℝ // + (∀ e, p e ∈ Set.Icc (0 : ℝ) 1) ∧ ∑ e, p e = 1}) + +abbrev Environment (d : ℕ) := Site d → Row d +abbrev Path (d : ℕ) := ℕ → Site d +abbrev State (d : ℕ) := Environment d × Site d + +def StrictEllipticity {d : ℕ} (μ : Measure (Row d)) : Prop := + ∀ᵐ p ∂μ, ∀ e, 0 < p.val e + +noncomputable def environmentLaw {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] : Measure (Environment d) := + Measure.infinitePi (fun _ => μ) + +noncomputable def transition (d : ℕ) : Kernel (State d) (State d) where + toFun s := ∑ e : Step d, + ENNReal.ofReal ((s.1 s.2).val e) • Measure.dirac (s.1, s.2 + stepVector e) + measurable' := by + apply measurable_from_prod_countable_left + intro x + apply Finset.measurable_sum + intro e he + apply Measure.measurable_of_measurable_coe + intro t ht + simp only [Measure.smul_apply, smul_eq_mul] + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp (measurable_pi_apply x))).ennreal_ofReal + · exact (Measure.measurable_coe ht).comp + (Measure.measurable_dirac.comp (measurable_id.prodMk measurable_const)) + +instance (d : ℕ) : IsMarkovKernel (transition d) where + isProbabilityMeasure s := by + constructor + change (∑ e : Step d, + ENNReal.ofReal ((s.1 s.2).val e) • + Measure.dirac (s.1, s.2 + stepVector e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, + Measure.dirac_apply_of_mem (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofReal_sum_of_nonneg] + · rw [(s.1 s.2).property.2, ENNReal.ofReal_one] + · intro e he + exact ((s.1 s.2).property.1 e).1 + +noncomputable def historyKernel (d n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) := + (transition d).comap (fun h => h ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + (measurable_pi_apply _) + +instance (d n : ℕ) : IsMarkovKernel (historyKernel d n) := by + unfold historyKernel + infer_instance + +noncomputable def initialLaw {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] (x : Site d) : Measure (State d) := + (environmentLaw μ).map (fun ω => (ω, x)) + +noncomputable def annealed {d : ℕ} (μ : Measure (Row d)) + [IsProbabilityMeasure μ] (x : Site d) : Measure (Path d) := + (Kernel.trajMeasure (X := fun _ => State d) (initialLaw μ x) (historyKernel d)).map + (fun z n => (z n).2) + +def escape {d : ℕ} (ℓ : Fin d → ℝ) : Set (Path d) := + {X | Tendsto (fun n => ∑ i, (X n i : ℝ) * ℓ i) atTop atTop} + +theorem directional_zero_one (d : ℕ) (hd : 3 ≤ d) + (μ : Measure (Row d)) [IsProbabilityMeasure μ] + (hell : StrictEllipticity μ) (ℓ : Fin d → ℝ) (hℓ : ℓ ≠ 0) : + annealed μ 0 (escape ℓ) = 0 ∨ annealed μ 0 (escape ℓ) = 1 := by sorry + +end DirectionalZeroOne + +end OAI diff --git a/tasks/directional-walk/tests/grade.py b/tasks/directional-walk/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/directional-walk/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/directional-walk/tests/task.json b/tasks/directional-walk/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7321d67491d47d496734cd0a86f70cf8835f6a36 --- /dev/null +++ b/tasks/directional-walk/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DirectionalWalk", + "comparator": { + "theorem_names": [ + "OAI.DirectionalZeroOne.directional_zero_one" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11656 +} \ No newline at end of file diff --git a/tasks/directional-walk/tests/test.sh b/tasks/directional-walk/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/directional-walk/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/discrete-lipschitz-free/environment/Dockerfile b/tasks/discrete-lipschitz-free/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/discrete-lipschitz-free/environment/fetch_mathlib.sh b/tasks/discrete-lipschitz-free/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/discrete-lipschitz-free/environment/lake-manifest.json b/tasks/discrete-lipschitz-free/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/discrete-lipschitz-free/environment/lakefile.lean b/tasks/discrete-lipschitz-free/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/discrete-lipschitz-free/environment/lean_setup.sh b/tasks/discrete-lipschitz-free/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/discrete-lipschitz-free/environment/pack_submission.py b/tasks/discrete-lipschitz-free/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/discrete-lipschitz-free/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/discrete-lipschitz-free/instruction.md b/tasks/discrete-lipschitz-free/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..69430ae214c603ce734fe9f3e05a26312d4b3d87 --- /dev/null +++ b/tasks/discrete-lipschitz-free/instruction.md @@ -0,0 +1,214 @@ +# openai/math challenge `DiscreteLipschitzFree` (family 330) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 330 of the release, *A negative answer to Kalton's Lipschitz-free approximation question* +(Functional analysis). The family as a whole: Constructs a countable uniformly discrete metric space whose real Lipschitz-free Banach space has the approximation property but not the bounded approximation property, answering Kalton's question negatively. Finite-rank operators approximate the identity on every compact set, but their norms cannot share a finite bound. + +The challenge is `DiscreteLipschitzFree`, also at `/opt/openai-math/challenges/DiscreteLipschitzFree.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Real Lipschitz-free spaces and approximation properties +-/ + +noncomputable section +open scoped BigOperators ENNReal + +namespace DiscreteFree + +variable {M : Type*} [MetricSpace M] + +def lipSubmodule (o : M) : Submodule ℝ (M → ℝ) where + carrier := {f | f o = 0 ∧ ∃ C : ℝ, 0 ≤ C ∧ + ∀ x y, |f x - f y| ≤ C * dist x y} + zero_mem' := by + refine ⟨rfl, 0, le_rfl, ?_⟩ + intro x y + simp + add_mem' := by + rintro f g ⟨hfo, C, hC, hf⟩ ⟨hgo, D, hD, hg⟩ + refine ⟨by simpa using congrArg₂ (· + ·) hfo hgo, + C + D, add_nonneg hC hD, ?_⟩ + intro x y + change |f x + g x - (f y + g y)| ≤ (C + D) * dist x y + calc + _ = |(f x - f y) + (g x - g y)| := by ring_nf + _ ≤ |f x - f y| + |g x - g y| := abs_add_le _ _ + _ ≤ C * dist x y + D * dist x y := add_le_add (hf x y) (hg x y) + _ = _ := by ring + smul_mem' := by + rintro c f ⟨hfo, C, hC, hf⟩ + refine ⟨by simp [hfo], |c| * C, mul_nonneg (abs_nonneg c) hC, ?_⟩ + intro x y + change |c * f x - c * f y| ≤ (|c| * C) * dist x y + calc + _ = |c| * |f x - f y| := by rw [← mul_sub, abs_mul] + _ ≤ |c| * (C * dist x y) := mul_le_mul_of_nonneg_left (hf x y) (abs_nonneg c) + _ = _ := by ring + +def Lip0 (o : M) := ↥(lipSubmodule o) + +namespace Lip0 + +variable {o : M} + +instance : AddCommGroup (Lip0 o) := inferInstanceAs (AddCommGroup ↥(lipSubmodule o)) +instance : Module ℝ (Lip0 o) := inferInstanceAs (Module ℝ ↥(lipSubmodule o)) + +instance : CoeFun (Lip0 o) (fun _ => M → ℝ) := ⟨fun f => f.val⟩ + +def slope (o : M) : Lip0 o →ₗ[ℝ] lp (fun _ : M × M => ℝ) ∞ where + toFun f := ⟨fun z : M × M => (f z.1 - f z.2) / dist z.1 z.2, by + obtain ⟨C, hC, hf⟩ := f.property.2 + apply memℓp_infty + refine ⟨C, ?_⟩ + rintro r ⟨⟨x, y⟩, rfl⟩ + change ‖(f x - f y) / dist x y‖ ≤ C + rw [Real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg] + by_cases hxy : x = y + · simp [hxy, hC] + · exact (div_le_iff₀ (dist_pos.mpr hxy)).2 (hf x y)⟩ + map_add' f g := by + apply lp.ext + funext z + change ((f z.1 + g z.1) - (f z.2 + g z.2)) / dist z.1 z.2 = + (f z.1 - f z.2) / dist z.1 z.2 + (g z.1 - g z.2) / dist z.1 z.2 + ring + map_smul' c f := by + apply lp.ext + funext z + change (c * f z.1 - c * f z.2) / dist z.1 z.2 = + c * ((f z.1 - f z.2) / dist z.1 z.2) + ring + +instance (o : M) : NormedAddCommGroup (Lip0 o) := + NormedAddCommGroup.induced _ _ (slope o).toAddMonoidHom (by + intro f g h + apply Subtype.ext + funext x + have hx := congrArg (fun q : lp (fun _ : M × M => ℝ) ∞ => q (x, o)) h + change (f x - f o) / dist x o = (g x - g o) / dist x o at hx + rw [f.property.1, g.property.1, sub_zero, sub_zero] at hx + by_cases hxo : x = o + · rw [hxo, f.property.1, g.property.1] + · exact (div_left_inj' (ne_of_gt (dist_pos.mpr hxo))).mp hx) + +instance (o : M) : NormedSpace ℝ (Lip0 o) := + NormedSpace.induced ℝ _ _ (slope o) + +end Lip0 + +def evaluation (o x : M) : (Lip0 o →L[ℝ] ℝ) := + LinearMap.mkContinuous + ({ toFun := fun f : Lip0 o => f x + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } : Lip0 o →ₗ[ℝ] ℝ) + (dist x o) (fun f => by + change ‖f x‖ ≤ dist x o * ‖f‖ + rw [mul_comm] + have hx := lp.norm_apply_le_norm (by simp : (∞ : ℝ≥0∞) ≠ 0) + (Lip0.slope o f) (x, o) + change ‖(f x - f o) / dist x o‖ ≤ ‖f‖ at hx + rw [f.property.1, sub_zero, norm_div, Real.norm_of_nonneg dist_nonneg] at hx + by_cases hxo : x = o + · rw [hxo, f.property.1, norm_zero, dist_self, mul_zero] + · exact (div_le_iff₀ (dist_pos.mpr hxo)).mp hx) + +def freeSubmodule (o : M) : Submodule ℝ ((Lip0 o →L[ℝ] ℝ)) := + (Submodule.span ℝ (Set.range (evaluation o))).topologicalClosure + +def FreeSpace (o : M) := ↥(freeSubmodule o) + +instance (o : M) : NormedAddCommGroup (FreeSpace o) := + inferInstanceAs (NormedAddCommGroup ↥(freeSubmodule o)) + +instance (o : M) : NormedSpace ℝ (FreeSpace o) := + inferInstanceAs (NormedSpace ℝ ↥(freeSubmodule o)) + +def delta (o x : M) : FreeSpace o := + ⟨evaluation o x, Submodule.le_topologicalClosure _ + (Submodule.subset_span ⟨x, rfl⟩)⟩ + +def HasAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def HasBAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] (Λ : ℝ) : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ‖T‖ ≤ Λ ∧ ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def blockBound (p : ℕ) : ℝ := 300 * (p : ℝ)^2 + 150 * (p : ℝ) + 5 + +def BlockStatement : Prop := + ∀ p : ℕ, 1 ≤ p → ∃ (M : Type) (d : MetricSpace M) (o : M), + letI := d + Countable M ∧ (∀ x y : M, x ≠ y → 1 ≤ dist x y) ∧ + (∀ x y : M, dist x y ≤ blockBound p) ∧ + ∃ A : Finset M, o ∈ A ∧ ∀ T : FreeSpace o →L[ℝ] FreeSpace o, + Module.Finite ℝ (LinearMap.range T.toLinearMap) → ‖T‖ ≤ (p : ℝ) → + ∃ a ∈ A, (1 / 2 : ℝ) ≤ ‖T (delta o a) - delta o a‖ + +def MainStatement : Prop := + ∃ (M : Type) (d : MetricSpace M) (o : M), + letI := d + Countable M ∧ (∀ x y : M, x ≠ y → 1 ≤ dist x y) ∧ + (¬ Bornology.IsBounded (Set.univ : Set M)) ∧ + (¬ ProperSpace M) ∧ HasAP (FreeSpace o) ∧ + ∀ Λ : ℝ, 1 ≤ Λ → ¬ HasBAP (FreeSpace o) Λ + +theorem source_endpoints : BlockStatement ∧ MainStatement := by + sorry + +end DiscreteFree + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DiscreteLipschitzFree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DiscreteFree.source_endpoints` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/discrete-lipschitz-free/solution/closure.txt b/tasks/discrete-lipschitz-free/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..22310b84abcc7457bbd1f8b20f913d74985f3598 --- /dev/null +++ b/tasks/discrete-lipschitz-free/solution/closure.txt @@ -0,0 +1,32 @@ +OAI.Analysis.LipschitzFree.AffineWeights +OAI.Analysis.LipschitzFree.Attachment +OAI.Analysis.LipschitzFree.BlockBAP +OAI.Analysis.LipschitzFree.BlockObstruction +OAI.Analysis.LipschitzFree.BlockPaths +OAI.Analysis.LipschitzFree.BoxLabels +OAI.Analysis.LipschitzFree.ColorCounting +OAI.Analysis.LipschitzFree.CompactApproximation +OAI.Analysis.LipschitzFree.Coordinates +OAI.Analysis.LipschitzFree.Evaluation +OAI.Analysis.LipschitzFree.FiniteQuotients +OAI.Analysis.LipschitzFree.Functor +OAI.Analysis.LipschitzFree.GraphColoring +OAI.Analysis.LipschitzFree.GraphGirth +OAI.Analysis.LipschitzFree.GraphSequence +OAI.Analysis.LipschitzFree.GraphWalks +OAI.Analysis.LipschitzFree.LabelBumps +OAI.Analysis.LipschitzFree.Main +OAI.Analysis.LipschitzFree.MetricBlock +OAI.Analysis.LipschitzFree.MetricClosure +OAI.Analysis.LipschitzFree.Model +OAI.Analysis.LipschitzFree.Parameters +OAI.Analysis.LipschitzFree.PortGraphs +OAI.Analysis.LipschitzFree.RenormingModel +OAI.Analysis.LipschitzFree.RetainedWedge +OAI.Analysis.LipschitzFree.ScalarTests +OAI.Analysis.LipschitzFree.SignedTests +OAI.Analysis.LipschitzFree.StatePaths +OAI.Analysis.LipschitzFree.SupportReduction +OAI.Analysis.LipschitzFree.Wedge +OAI.Analysis.LipschitzFree.WedgeApproximation +OAI.Analysis.LipschitzFree.Words diff --git a/tasks/discrete-lipschitz-free/solution/reference.py b/tasks/discrete-lipschitz-free/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/discrete-lipschitz-free/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/discrete-lipschitz-free/solution/solve.sh b/tasks/discrete-lipschitz-free/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b06a8982a4fa1ce098ea2ca8db64065dada44fed --- /dev/null +++ b/tasks/discrete-lipschitz-free/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DiscreteLipschitzFree, i.e. module OAI.Analysis.LipschitzFree.Main and the +# 32 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LipschitzFree.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DiscreteLipschitzFree" diff --git a/tasks/discrete-lipschitz-free/task.toml b/tasks/discrete-lipschitz-free/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23796c72aafadf0734b4cc26e6aec9fa3e14c5f7 --- /dev/null +++ b/tasks/discrete-lipschitz-free/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/discrete-lipschitz-free" +version = "1.0.0" +description = "Prove DiscreteLipschitzFree (openai/math family 330: A negative answer to Kalton's Lipschitz-free approximation question) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DiscreteLipschitzFree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DiscreteLipschitzFree" +family = "330" +family_title = "A negative answer to Kalton's Lipschitz-free approximation question" +subject = "Functional analysis" +theorems = ["OAI.DiscreteFree.source_endpoints"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LipschitzFree.Main" +reference_modules = 32 +reference_lean_bytes = 173635 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 662 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11856 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/discrete-lipschitz-free/tests/Challenge.lean b/tasks/discrete-lipschitz-free/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..72b4780a68158715ffeb4118d2dc132451cf9bc9 --- /dev/null +++ b/tasks/discrete-lipschitz-free/tests/Challenge.lean @@ -0,0 +1,163 @@ +import Mathlib + +namespace OAI + +/-! +# Real Lipschitz-free spaces and approximation properties +-/ + +noncomputable section +open scoped BigOperators ENNReal + +namespace DiscreteFree + +variable {M : Type*} [MetricSpace M] + +def lipSubmodule (o : M) : Submodule ℝ (M → ℝ) where + carrier := {f | f o = 0 ∧ ∃ C : ℝ, 0 ≤ C ∧ + ∀ x y, |f x - f y| ≤ C * dist x y} + zero_mem' := by + refine ⟨rfl, 0, le_rfl, ?_⟩ + intro x y + simp + add_mem' := by + rintro f g ⟨hfo, C, hC, hf⟩ ⟨hgo, D, hD, hg⟩ + refine ⟨by simpa using congrArg₂ (· + ·) hfo hgo, + C + D, add_nonneg hC hD, ?_⟩ + intro x y + change |f x + g x - (f y + g y)| ≤ (C + D) * dist x y + calc + _ = |(f x - f y) + (g x - g y)| := by ring_nf + _ ≤ |f x - f y| + |g x - g y| := abs_add_le _ _ + _ ≤ C * dist x y + D * dist x y := add_le_add (hf x y) (hg x y) + _ = _ := by ring + smul_mem' := by + rintro c f ⟨hfo, C, hC, hf⟩ + refine ⟨by simp [hfo], |c| * C, mul_nonneg (abs_nonneg c) hC, ?_⟩ + intro x y + change |c * f x - c * f y| ≤ (|c| * C) * dist x y + calc + _ = |c| * |f x - f y| := by rw [← mul_sub, abs_mul] + _ ≤ |c| * (C * dist x y) := mul_le_mul_of_nonneg_left (hf x y) (abs_nonneg c) + _ = _ := by ring + +def Lip0 (o : M) := ↥(lipSubmodule o) + +namespace Lip0 + +variable {o : M} + +instance : AddCommGroup (Lip0 o) := inferInstanceAs (AddCommGroup ↥(lipSubmodule o)) +instance : Module ℝ (Lip0 o) := inferInstanceAs (Module ℝ ↥(lipSubmodule o)) + +instance : CoeFun (Lip0 o) (fun _ => M → ℝ) := ⟨fun f => f.val⟩ + +def slope (o : M) : Lip0 o →ₗ[ℝ] lp (fun _ : M × M => ℝ) ∞ where + toFun f := ⟨fun z : M × M => (f z.1 - f z.2) / dist z.1 z.2, by + obtain ⟨C, hC, hf⟩ := f.property.2 + apply memℓp_infty + refine ⟨C, ?_⟩ + rintro r ⟨⟨x, y⟩, rfl⟩ + change ‖(f x - f y) / dist x y‖ ≤ C + rw [Real.norm_eq_abs, abs_div, abs_of_nonneg dist_nonneg] + by_cases hxy : x = y + · simp [hxy, hC] + · exact (div_le_iff₀ (dist_pos.mpr hxy)).2 (hf x y)⟩ + map_add' f g := by + apply lp.ext + funext z + change ((f z.1 + g z.1) - (f z.2 + g z.2)) / dist z.1 z.2 = + (f z.1 - f z.2) / dist z.1 z.2 + (g z.1 - g z.2) / dist z.1 z.2 + ring + map_smul' c f := by + apply lp.ext + funext z + change (c * f z.1 - c * f z.2) / dist z.1 z.2 = + c * ((f z.1 - f z.2) / dist z.1 z.2) + ring + +instance (o : M) : NormedAddCommGroup (Lip0 o) := + NormedAddCommGroup.induced _ _ (slope o).toAddMonoidHom (by + intro f g h + apply Subtype.ext + funext x + have hx := congrArg (fun q : lp (fun _ : M × M => ℝ) ∞ => q (x, o)) h + change (f x - f o) / dist x o = (g x - g o) / dist x o at hx + rw [f.property.1, g.property.1, sub_zero, sub_zero] at hx + by_cases hxo : x = o + · rw [hxo, f.property.1, g.property.1] + · exact (div_left_inj' (ne_of_gt (dist_pos.mpr hxo))).mp hx) + +instance (o : M) : NormedSpace ℝ (Lip0 o) := + NormedSpace.induced ℝ _ _ (slope o) + +end Lip0 + +def evaluation (o x : M) : (Lip0 o →L[ℝ] ℝ) := + LinearMap.mkContinuous + ({ toFun := fun f : Lip0 o => f x + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } : Lip0 o →ₗ[ℝ] ℝ) + (dist x o) (fun f => by + change ‖f x‖ ≤ dist x o * ‖f‖ + rw [mul_comm] + have hx := lp.norm_apply_le_norm (by simp : (∞ : ℝ≥0∞) ≠ 0) + (Lip0.slope o f) (x, o) + change ‖(f x - f o) / dist x o‖ ≤ ‖f‖ at hx + rw [f.property.1, sub_zero, norm_div, Real.norm_of_nonneg dist_nonneg] at hx + by_cases hxo : x = o + · rw [hxo, f.property.1, norm_zero, dist_self, mul_zero] + · exact (div_le_iff₀ (dist_pos.mpr hxo)).mp hx) + +def freeSubmodule (o : M) : Submodule ℝ ((Lip0 o →L[ℝ] ℝ)) := + (Submodule.span ℝ (Set.range (evaluation o))).topologicalClosure + +def FreeSpace (o : M) := ↥(freeSubmodule o) + +instance (o : M) : NormedAddCommGroup (FreeSpace o) := + inferInstanceAs (NormedAddCommGroup ↥(freeSubmodule o)) + +instance (o : M) : NormedSpace ℝ (FreeSpace o) := + inferInstanceAs (NormedSpace ℝ ↥(freeSubmodule o)) + +def delta (o x : M) : FreeSpace o := + ⟨evaluation o x, Submodule.le_topologicalClosure _ + (Submodule.subset_span ⟨x, rfl⟩)⟩ + +def HasAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def HasBAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] (Λ : ℝ) : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ‖T‖ ≤ Λ ∧ ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def blockBound (p : ℕ) : ℝ := 300 * (p : ℝ)^2 + 150 * (p : ℝ) + 5 + +def BlockStatement : Prop := + ∀ p : ℕ, 1 ≤ p → ∃ (M : Type) (d : MetricSpace M) (o : M), + letI := d + Countable M ∧ (∀ x y : M, x ≠ y → 1 ≤ dist x y) ∧ + (∀ x y : M, dist x y ≤ blockBound p) ∧ + ∃ A : Finset M, o ∈ A ∧ ∀ T : FreeSpace o →L[ℝ] FreeSpace o, + Module.Finite ℝ (LinearMap.range T.toLinearMap) → ‖T‖ ≤ (p : ℝ) → + ∃ a ∈ A, (1 / 2 : ℝ) ≤ ‖T (delta o a) - delta o a‖ + +def MainStatement : Prop := + ∃ (M : Type) (d : MetricSpace M) (o : M), + letI := d + Countable M ∧ (∀ x y : M, x ≠ y → 1 ≤ dist x y) ∧ + (¬ Bornology.IsBounded (Set.univ : Set M)) ∧ + (¬ ProperSpace M) ∧ HasAP (FreeSpace o) ∧ + ∀ Λ : ℝ, 1 ≤ Λ → ¬ HasBAP (FreeSpace o) Λ + +theorem source_endpoints : BlockStatement ∧ MainStatement := by + sorry + +end DiscreteFree + +end + +end OAI diff --git a/tasks/discrete-lipschitz-free/tests/grade.py b/tasks/discrete-lipschitz-free/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/discrete-lipschitz-free/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/discrete-lipschitz-free/tests/task.json b/tasks/discrete-lipschitz-free/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0ae59690f73c047cc6564f1e671ea96089719613 --- /dev/null +++ b/tasks/discrete-lipschitz-free/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DiscreteLipschitzFree", + "comparator": { + "theorem_names": [ + "OAI.DiscreteFree.source_endpoints" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10956 +} \ No newline at end of file diff --git a/tasks/discrete-lipschitz-free/tests/test.sh b/tasks/discrete-lipschitz-free/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/discrete-lipschitz-free/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/disk-maximal/environment/Dockerfile b/tasks/disk-maximal/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/disk-maximal/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/disk-maximal/environment/fetch_mathlib.sh b/tasks/disk-maximal/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/disk-maximal/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/disk-maximal/environment/lake-manifest.json b/tasks/disk-maximal/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/disk-maximal/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/disk-maximal/environment/lakefile.lean b/tasks/disk-maximal/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/disk-maximal/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/disk-maximal/environment/lean_setup.sh b/tasks/disk-maximal/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/disk-maximal/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/disk-maximal/environment/pack_submission.py b/tasks/disk-maximal/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/disk-maximal/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/disk-maximal/instruction.md b/tasks/disk-maximal/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43f55e920e3ef658b1b2ff87901e098ce8e05786 --- /dev/null +++ b/tasks/disk-maximal/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `DiskMaximal` (family 085) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 085 of the release, *Endpoint regularity of the planar centered maximal function* +(Real and complex analysis). The family as a whole: Resolves the planar centered-disk case of the Haj{\l}asz–Onninen maximal-function regularity problem. For every real $f\in W^{1,1}(\mathbb R^2)$, the centered disk maximal function satisfies $\|\nabla Mf\|_1\le C\|\nabla f\|_1$ with an absolute constant. It belongs locally to $W^{1,1}$ and has a globally integrable weak gradient. + +The challenge is `DiskMaximal`, also at `/opt/openai-math/challenges/DiskMaximal.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory Set +open scoped ENNReal NNReal Topology ContDiff + +noncomputable section +namespace CenteredDiskEndpoint + +/-- The Euclidean plane, not the product space with its max norm. -/ +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +/-- Absolute disk average, retaining possible infinite values. -/ +def absoluteDiskAverage (f : Plane → ℝ) (x : Plane) (r : ℝ) : ℝ≥0∞ := + (∫⁻ y in Metric.ball x r, ENNReal.ofReal |f y|) / + ENNReal.ofReal (Real.pi * r ^ 2) + +/-- The actual centered disk maximal function, over every positive real radius. -/ +def maximal (f : Plane → ℝ) (x : Plane) : ℝ≥0∞ := + ⨆ (r : ℝ) (_ : 0 < r), absoluteDiskAverage f x r + +/-- Real representative; the endpoint also asserts that `maximal f` is finite a.e. -/ +def maximalReal (f : Plane → ℝ) (x : Plane) : ℝ := (maximal f x).toReal + +/-- The i-th coordinate derivative of a smooth test function. -/ +def testPartial (φ : Plane → ℝ) (i : Fin 2) (x : Plane) : ℝ := + fderiv ℝ φ x (EuclideanSpace.single i 1) + +/-- Distributional first derivatives represented by a vector-valued function. -/ +def HasWeakGradient (f : Plane → ℝ) (g : Plane → Plane) : Prop := + ∀ (φ : Plane → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + ∀ i : Fin 2, (∫ x, f x * testPartial φ i x) = -∫ x, g x i * φ x + +/-- Local W^(1,1), expressed using the same distributional gradient convention. -/ +def InW11Loc (f : Plane → ℝ) : Prop := + LocallyIntegrable f ∧ + ∃ g : Plane → Plane, LocallyIntegrable g ∧ HasWeakGradient f g + +/-- The gradient L1 norm in Euclidean norm. -/ +def gradientNorm (g : Plane → Plane) : ℝ := ∫ x, ‖g x‖ + +/-- Exact endpoint, including finiteness before passing to the real representative. +Quantifying the input gradient makes the norm bound independent of a choice of +representative of its weak derivatives. -/ +def EndpointStatement : Prop := + ∃ C : ℝ, 0 ≤ C ∧ + ∀ (f : Plane → ℝ) (g : Plane → Plane), + Integrable f → Integrable g → HasWeakGradient f g → + (∀ᵐ x, maximal f x ≠ ⊤) ∧ + LocallyIntegrable (maximalReal f) ∧ + InW11Loc (maximalReal f) ∧ + ∃ G : Plane → Plane, Integrable G ∧ + HasWeakGradient (maximalReal f) G ∧ gradientNorm G ≤ C * gradientNorm g + +theorem main_endpoint : EndpointStatement := by + sorry + +end CenteredDiskEndpoint + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DiskMaximal.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CenteredDiskEndpoint.main_endpoint` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/disk-maximal/solution/closure.txt b/tasks/disk-maximal/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..10ce183b9329658027f04cc7611774dc7b2ba336 --- /dev/null +++ b/tasks/disk-maximal/solution/closure.txt @@ -0,0 +1,30 @@ +OAI.Analysis.DiskMaximal.AbsoluteContinuity +OAI.Analysis.DiskMaximal.Approximation +OAI.Analysis.DiskMaximal.BandBounds +OAI.Analysis.DiskMaximal.Basic +OAI.Analysis.DiskMaximal.Cancellation +OAI.Analysis.DiskMaximal.DirectionEstimates +OAI.Analysis.DiskMaximal.DirectionLaws +OAI.Analysis.DiskMaximal.Envelopes +OAI.Analysis.DiskMaximal.Geometry +OAI.Analysis.DiskMaximal.GreenBounds +OAI.Analysis.DiskMaximal.Kernels +OAI.Analysis.DiskMaximal.LocalPrices +OAI.Analysis.DiskMaximal.Localization +OAI.Analysis.DiskMaximal.Main +OAI.Analysis.DiskMaximal.Marks +OAI.Analysis.DiskMaximal.MaximalEstimates +OAI.Analysis.DiskMaximal.Model +OAI.Analysis.DiskMaximal.Moments +OAI.Analysis.DiskMaximal.Packing +OAI.Analysis.DiskMaximal.Potentials +OAI.Analysis.DiskMaximal.Prices +OAI.Analysis.DiskMaximal.Refinement +OAI.Analysis.DiskMaximal.RunCancellation +OAI.Analysis.DiskMaximal.Runs +OAI.Analysis.DiskMaximal.ScalarTrees +OAI.Analysis.DiskMaximal.Scales +OAI.Analysis.DiskMaximal.SpatialBudgets +OAI.Analysis.DiskMaximal.SpatialLaws +OAI.Analysis.DiskMaximal.Telescoping +OAI.Analysis.DiskMaximal.WeakLimits diff --git a/tasks/disk-maximal/solution/reference.py b/tasks/disk-maximal/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/disk-maximal/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/disk-maximal/solution/solve.sh b/tasks/disk-maximal/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..49d25e601c5c96a37a51ae65e740d80523127fc4 --- /dev/null +++ b/tasks/disk-maximal/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DiskMaximal, i.e. module OAI.Analysis.DiskMaximal.Main and the +# 30 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.DiskMaximal.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DiskMaximal" diff --git a/tasks/disk-maximal/task.toml b/tasks/disk-maximal/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..969d49ad33d34e02423a0b6aed2f3f76f744c1bc --- /dev/null +++ b/tasks/disk-maximal/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/disk-maximal" +version = "1.0.0" +description = "Prove DiskMaximal (openai/math family 085: Endpoint regularity of the planar centered maximal function) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DiskMaximal.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DiskMaximal" +family = "085" +family_title = "Endpoint regularity of the planar centered maximal function" +subject = "Real and complex analysis" +theorems = ["OAI.CenteredDiskEndpoint.main_endpoint"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.DiskMaximal.Main" +reference_modules = 30 +reference_lean_bytes = 970308 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 756 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12573 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/disk-maximal/tests/Challenge.lean b/tasks/disk-maximal/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6892648a438d58462010bce38713a04d0705a49 --- /dev/null +++ b/tasks/disk-maximal/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib + +namespace OAI + +open MeasureTheory Set +open scoped ENNReal NNReal Topology ContDiff + +noncomputable section +namespace CenteredDiskEndpoint + +/-- The Euclidean plane, not the product space with its max norm. -/ +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +/-- Absolute disk average, retaining possible infinite values. -/ +def absoluteDiskAverage (f : Plane → ℝ) (x : Plane) (r : ℝ) : ℝ≥0∞ := + (∫⁻ y in Metric.ball x r, ENNReal.ofReal |f y|) / + ENNReal.ofReal (Real.pi * r ^ 2) + +/-- The actual centered disk maximal function, over every positive real radius. -/ +def maximal (f : Plane → ℝ) (x : Plane) : ℝ≥0∞ := + ⨆ (r : ℝ) (_ : 0 < r), absoluteDiskAverage f x r + +/-- Real representative; the endpoint also asserts that `maximal f` is finite a.e. -/ +def maximalReal (f : Plane → ℝ) (x : Plane) : ℝ := (maximal f x).toReal + +/-- The i-th coordinate derivative of a smooth test function. -/ +def testPartial (φ : Plane → ℝ) (i : Fin 2) (x : Plane) : ℝ := + fderiv ℝ φ x (EuclideanSpace.single i 1) + +/-- Distributional first derivatives represented by a vector-valued function. -/ +def HasWeakGradient (f : Plane → ℝ) (g : Plane → Plane) : Prop := + ∀ (φ : Plane → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + ∀ i : Fin 2, (∫ x, f x * testPartial φ i x) = -∫ x, g x i * φ x + +/-- Local W^(1,1), expressed using the same distributional gradient convention. -/ +def InW11Loc (f : Plane → ℝ) : Prop := + LocallyIntegrable f ∧ + ∃ g : Plane → Plane, LocallyIntegrable g ∧ HasWeakGradient f g + +/-- The gradient L1 norm in Euclidean norm. -/ +def gradientNorm (g : Plane → Plane) : ℝ := ∫ x, ‖g x‖ + +/-- Exact endpoint, including finiteness before passing to the real representative. +Quantifying the input gradient makes the norm bound independent of a choice of +representative of its weak derivatives. -/ +def EndpointStatement : Prop := + ∃ C : ℝ, 0 ≤ C ∧ + ∀ (f : Plane → ℝ) (g : Plane → Plane), + Integrable f → Integrable g → HasWeakGradient f g → + (∀ᵐ x, maximal f x ≠ ⊤) ∧ + LocallyIntegrable (maximalReal f) ∧ + InW11Loc (maximalReal f) ∧ + ∃ G : Plane → Plane, Integrable G ∧ + HasWeakGradient (maximalReal f) G ∧ gradientNorm G ≤ C * gradientNorm g + +theorem main_endpoint : EndpointStatement := by + sorry + +end CenteredDiskEndpoint + +end + +end OAI diff --git a/tasks/disk-maximal/tests/grade.py b/tasks/disk-maximal/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/disk-maximal/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/disk-maximal/tests/task.json b/tasks/disk-maximal/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e64ceac7afae4a09710dd60b067bf230c29bcef7 --- /dev/null +++ b/tasks/disk-maximal/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DiskMaximal", + "comparator": { + "theorem_names": [ + "OAI.CenteredDiskEndpoint.main_endpoint" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11673 +} \ No newline at end of file diff --git a/tasks/disk-maximal/tests/test.sh b/tasks/disk-maximal/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/disk-maximal/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dixmier-all-discrete/environment/Dockerfile b/tasks/dixmier-all-discrete/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dixmier-all-discrete/environment/fetch_mathlib.sh b/tasks/dixmier-all-discrete/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dixmier-all-discrete/environment/lake-manifest.json b/tasks/dixmier-all-discrete/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dixmier-all-discrete/environment/lakefile.lean b/tasks/dixmier-all-discrete/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dixmier-all-discrete/environment/lean_setup.sh b/tasks/dixmier-all-discrete/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dixmier-all-discrete/environment/pack_submission.py b/tasks/dixmier-all-discrete/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dixmier-all-discrete/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dixmier-all-discrete/instruction.md b/tasks/dixmier-all-discrete/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c09b6b6b10ac5b868e92216e8d44db92eb277928 --- /dev/null +++ b/tasks/dixmier-all-discrete/instruction.md @@ -0,0 +1,100 @@ +# openai/math challenge `DixmierAllDiscrete` (family 251) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 251 of the release, *Amenability, unitarizability, and Ulam stability* +(Group theory). The family as a whole: Resolves Dixmier's problem for all discrete groups: amenability is equivalent to every uniformly bounded Hilbert-space representation being similar to a unitary representation. For countable discrete groups, amenability is also equivalent to strong Ulam stability: sufficiently accurate unitary approximate representations are uniformly close in operator norm to genuine representations on the same, possibly infinite-dimensional, Hilbert space. + +The challenge is `DixmierAllDiscrete`, also at `/opt/openai-math/challenges/DixmierAllDiscrete.lean`: + +```lean +import Mathlib.Analysis.InnerProductSpace.LinearMap +import Mathlib.Topology.ContinuousMap.Bounded.Normed +import Mathlib.Topology.Instances.Discrete + +namespace OAI + +noncomputable section +universe u v +namespace Dixmier +open scoped BoundedContinuousFunction + +def leftTranslate {G : Type u} [Group G] [TopologicalSpace G] + [DiscreteTopology G] (g : G) (f : G →ᵇ ℂ) : G →ᵇ ℂ := + f.compContinuous ⟨fun x => g⁻¹ * x, continuous_of_discreteTopology⟩ + +def Amenable (G : Type u) [Group G] [TopologicalSpace G] + [DiscreteTopology G] : Prop := + ∃ m : (G →ᵇ ℂ) →ₗ[ℂ] ℂ, + m (BoundedContinuousFunction.const G 1) = 1 ∧ + (∀ f : G →ᵇ ℂ, (∀ x, 0 ≤ (f x).re ∧ (f x).im = 0) → + 0 ≤ (m f).re ∧ (m f).im = 0) ∧ + ∀ (g : G) (f : G →ᵇ ℂ), m (leftTranslate g f) = m f + +def SimilarToUnitary {G : Type u} [Group G] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (π : G →* (H →L[ℂ] H)) : Prop := + ∃ S : H ≃L[ℂ] H, ∀ (g : G) (x : H), ‖S (π g (S.symm x))‖ = ‖x‖ + +def Unitarizable (G : Type u) [Group G] : Prop := + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (π : G →* (H →L[ℂ] H)), + (∃ C : ℝ, ∀ g, ‖π g‖ ≤ C) → SimilarToUnitary π + +def CurrentMainTheorem : Prop := + ∀ (G : Type u) [Group G] [TopologicalSpace G] [DiscreteTopology G], + (Amenable G ↔ Unitarizable.{u, max u v} G) ∧ + ∀ (ε : ℝ), 0 < ε → ¬ Amenable G → + ∃ (H : Type (max u v)) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (π : G →* (H →L[ℂ] H)), + (Countable G → TopologicalSpace.SeparableSpace H) ∧ + (∀ g, ‖π g‖ ≤ 1 + ε) ∧ ¬ SimilarToUnitary π + +theorem current_main_theorem : CurrentMainTheorem.{u,v} := by + sorry + +end Dixmier +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DixmierAllDiscrete.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Dixmier.current_main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dixmier-all-discrete/solution/closure.txt b/tasks/dixmier-all-discrete/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..246dc2f484bf651e2b49807e7346ca13cde2ad6e --- /dev/null +++ b/tasks/dixmier-all-discrete/solution/closure.txt @@ -0,0 +1,39 @@ +OAI.Analysis.Unitarizability.AllDiscrete +OAI.Analysis.Unitarizability.Amenable +OAI.Analysis.Unitarizability.Average +OAI.Analysis.Unitarizability.AveragedForm +OAI.Analysis.Unitarizability.Cocycle +OAI.Analysis.Unitarizability.CompactMean +OAI.Analysis.Unitarizability.ComplexFrames +OAI.Analysis.Unitarizability.Contracting +OAI.Analysis.Unitarizability.DiscreteModel +OAI.Analysis.Unitarizability.EndpointAssignment +OAI.Analysis.Unitarizability.FiniteSigns +OAI.Analysis.Unitarizability.FiniteSynthesis +OAI.Analysis.Unitarizability.FrameParameters +OAI.Analysis.Unitarizability.FrameSelection +OAI.Analysis.Unitarizability.Frames +OAI.Analysis.Unitarizability.HilbertSum +OAI.Analysis.Unitarizability.InvariantProjection +OAI.Analysis.Unitarizability.KernelEnergy +OAI.Analysis.Unitarizability.KernelObstruction +OAI.Analysis.Unitarizability.LocalBounds +OAI.Analysis.Unitarizability.Main +OAI.Analysis.Unitarizability.MaskAlgebra +OAI.Analysis.Unitarizability.Masked +OAI.Analysis.Unitarizability.MeanBounds +OAI.Analysis.Unitarizability.Model +OAI.Analysis.Unitarizability.NearOne +OAI.Analysis.Unitarizability.NetOperator +OAI.Analysis.Unitarizability.Parameters +OAI.Analysis.Unitarizability.Regular +OAI.Analysis.Unitarizability.ScaledObstruction +OAI.Analysis.Unitarizability.SignMatrix +OAI.Analysis.Unitarizability.SparseMask +OAI.Analysis.Unitarizability.SparseSplitting +OAI.Analysis.Unitarizability.SphereNet +OAI.Analysis.Unitarizability.SumObstruction +OAI.Analysis.Unitarizability.Triangular +OAI.Analysis.Unitarizability.Unitarizer +OAI.Analysis.Unitarizability.UniverseTransport +OAI.Analysis.Unitarizability.VectorMean diff --git a/tasks/dixmier-all-discrete/solution/reference.py b/tasks/dixmier-all-discrete/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dixmier-all-discrete/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dixmier-all-discrete/solution/solve.sh b/tasks/dixmier-all-discrete/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e86837b049736e7f15e5b5de45339cf05a4a6cef --- /dev/null +++ b/tasks/dixmier-all-discrete/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DixmierAllDiscrete, i.e. module OAI.Analysis.Unitarizability.AllDiscrete and the +# 39 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Unitarizability.AllDiscrete /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DixmierAllDiscrete" diff --git a/tasks/dixmier-all-discrete/task.toml b/tasks/dixmier-all-discrete/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7f1af0984c5ec19e0f6ec8deca50e413bc86d574 --- /dev/null +++ b/tasks/dixmier-all-discrete/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dixmier-all-discrete" +version = "1.0.0" +description = "Prove DixmierAllDiscrete (openai/math family 251: Amenability, unitarizability, and Ulam stability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DixmierAllDiscrete.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DixmierAllDiscrete" +family = "251" +family_title = "Amenability, unitarizability, and Ulam stability" +subject = "Group theory" +theorems = ["OAI.Dixmier.current_main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Unitarizability.AllDiscrete" +reference_modules = 39 +reference_lean_bytes = 181502 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 471 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11863 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dixmier-all-discrete/tests/Challenge.lean b/tasks/dixmier-all-discrete/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b507e5de028de94d25d1315bf0bb9bee413dcebd --- /dev/null +++ b/tasks/dixmier-all-discrete/tests/Challenge.lean @@ -0,0 +1,49 @@ +import Mathlib.Analysis.InnerProductSpace.LinearMap +import Mathlib.Topology.ContinuousMap.Bounded.Normed +import Mathlib.Topology.Instances.Discrete + +namespace OAI + +noncomputable section +universe u v +namespace Dixmier +open scoped BoundedContinuousFunction + +def leftTranslate {G : Type u} [Group G] [TopologicalSpace G] + [DiscreteTopology G] (g : G) (f : G →ᵇ ℂ) : G →ᵇ ℂ := + f.compContinuous ⟨fun x => g⁻¹ * x, continuous_of_discreteTopology⟩ + +def Amenable (G : Type u) [Group G] [TopologicalSpace G] + [DiscreteTopology G] : Prop := + ∃ m : (G →ᵇ ℂ) →ₗ[ℂ] ℂ, + m (BoundedContinuousFunction.const G 1) = 1 ∧ + (∀ f : G →ᵇ ℂ, (∀ x, 0 ≤ (f x).re ∧ (f x).im = 0) → + 0 ≤ (m f).re ∧ (m f).im = 0) ∧ + ∀ (g : G) (f : G →ᵇ ℂ), m (leftTranslate g f) = m f + +def SimilarToUnitary {G : Type u} [Group G] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (π : G →* (H →L[ℂ] H)) : Prop := + ∃ S : H ≃L[ℂ] H, ∀ (g : G) (x : H), ‖S (π g (S.symm x))‖ = ‖x‖ + +def Unitarizable (G : Type u) [Group G] : Prop := + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (π : G →* (H →L[ℂ] H)), + (∃ C : ℝ, ∀ g, ‖π g‖ ≤ C) → SimilarToUnitary π + +def CurrentMainTheorem : Prop := + ∀ (G : Type u) [Group G] [TopologicalSpace G] [DiscreteTopology G], + (Amenable G ↔ Unitarizable.{u, max u v} G) ∧ + ∀ (ε : ℝ), 0 < ε → ¬ Amenable G → + ∃ (H : Type (max u v)) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (π : G →* (H →L[ℂ] H)), + (Countable G → TopologicalSpace.SeparableSpace H) ∧ + (∀ g, ‖π g‖ ≤ 1 + ε) ∧ ¬ SimilarToUnitary π + +theorem current_main_theorem : CurrentMainTheorem.{u,v} := by + sorry + +end Dixmier +end + +end OAI diff --git a/tasks/dixmier-all-discrete/tests/grade.py b/tasks/dixmier-all-discrete/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dixmier-all-discrete/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dixmier-all-discrete/tests/task.json b/tasks/dixmier-all-discrete/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1b3560d5d77064407ef9084c077bea65644eb2eb --- /dev/null +++ b/tasks/dixmier-all-discrete/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DixmierAllDiscrete", + "comparator": { + "theorem_names": [ + "OAI.Dixmier.current_main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 10963 +} \ No newline at end of file diff --git a/tasks/dixmier-all-discrete/tests/test.sh b/tasks/dixmier-all-discrete/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dixmier-all-discrete/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dixmier/environment/Dockerfile b/tasks/dixmier/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dixmier/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dixmier/environment/fetch_mathlib.sh b/tasks/dixmier/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dixmier/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dixmier/environment/lake-manifest.json b/tasks/dixmier/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dixmier/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dixmier/environment/lakefile.lean b/tasks/dixmier/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dixmier/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dixmier/environment/lean_setup.sh b/tasks/dixmier/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dixmier/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dixmier/environment/pack_submission.py b/tasks/dixmier/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dixmier/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dixmier/instruction.md b/tasks/dixmier/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bb95ea46e5856ca749122944a86326e7c399dc5d --- /dev/null +++ b/tasks/dixmier/instruction.md @@ -0,0 +1,102 @@ +# openai/math challenge `Dixmier` (family 251) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 251 of the release, *Amenability, unitarizability, and Ulam stability* +(Group theory). The family as a whole: Resolves Dixmier's problem for all discrete groups: amenability is equivalent to every uniformly bounded Hilbert-space representation being similar to a unitary representation. For countable discrete groups, amenability is also equivalent to strong Ulam stability: sufficiently accurate unitary approximate representations are uniformly close in operator norm to genuine representations on the same, possibly infinite-dimensional, Hilbert space. + +The challenge is `Dixmier`, also at `/opt/openai-math/challenges/Dixmier.lean`: + +```lean +import Mathlib.Analysis.InnerProductSpace.LinearMap +import Mathlib.Topology.ContinuousMap.Bounded.Normed +import Mathlib.Topology.Instances.Discrete + +namespace OAI + +noncomputable section +universe u v +namespace Dixmier +open scoped BoundedContinuousFunction + +def leftTranslate {G : Type u} [Group G] [TopologicalSpace G] + [DiscreteTopology G] (g : G) (f : G →ᵇ ℂ) : G →ᵇ ℂ := + f.compContinuous ⟨fun x => g⁻¹ * x, continuous_of_discreteTopology⟩ + +/-- A positive normalized left-invariant complex mean. -/ +def Amenable (G : Type u) [Group G] [TopologicalSpace G] + [DiscreteTopology G] : Prop := + ∃ m : (G →ᵇ ℂ) →ₗ[ℂ] ℂ, + m (BoundedContinuousFunction.const G 1) = 1 ∧ + (∀ f : G →ᵇ ℂ, (∀ x, 0 ≤ (f x).re ∧ (f x).im = 0) → + 0 ≤ (m f).re ∧ (m f).im = 0) ∧ + ∀ (g : G) (f : G →ᵇ ℂ), m (leftTranslate g f) = m f + +def SimilarToUnitary {G : Type u} [Group G] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (π : G →* (H →L[ℂ] H)) : Prop := + ∃ S : H ≃L[ℂ] H, ∀ (g : G) (x : H), ‖S (π g (S.symm x))‖ = ‖x‖ + +/-- A uniformly 101-bounded nonunitarizable representation on a separable +complete complex Hilbert space, with its universe explicit. -/ +def NonamenableWitness (G : Type u) [Group G] : Prop := + ∃ (H : Type v) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (_ : TopologicalSpace.SeparableSpace H) + (π : G →* (H →L[ℂ] H)), + (∀ g : G, ‖π g‖ ≤ 101) ∧ ¬ SimilarToUnitary π + +/-- Every countable discrete nonamenable group has a bounded nonunitarizable witness. -/ +def MainTheorem : Prop := + ∀ (G : Type u) [Group G] [Countable G] [TopologicalSpace G] + [DiscreteTopology G], ¬ Amenable G → NonamenableWitness.{u, v} G + +/-- The main theorem with independent group and Hilbert-space universes. -/ +theorem main_theorem_all_universes : MainTheorem.{u,v} := by + sorry + +end Dixmier + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Dixmier.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Dixmier.main_theorem_all_universes` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dixmier/solution/closure.txt b/tasks/dixmier/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..eecf7275e56566e9ccc8aed3fe460c419ffedc8c --- /dev/null +++ b/tasks/dixmier/solution/closure.txt @@ -0,0 +1,32 @@ +OAI.Analysis.Unitarizability.Average +OAI.Analysis.Unitarizability.Cocycle +OAI.Analysis.Unitarizability.CompactMean +OAI.Analysis.Unitarizability.ComplexFrames +OAI.Analysis.Unitarizability.Contracting +OAI.Analysis.Unitarizability.EndpointAssignment +OAI.Analysis.Unitarizability.FiniteSigns +OAI.Analysis.Unitarizability.FiniteSynthesis +OAI.Analysis.Unitarizability.FrameParameters +OAI.Analysis.Unitarizability.FrameSelection +OAI.Analysis.Unitarizability.Frames +OAI.Analysis.Unitarizability.HilbertSum +OAI.Analysis.Unitarizability.InvariantProjection +OAI.Analysis.Unitarizability.KernelEnergy +OAI.Analysis.Unitarizability.KernelObstruction +OAI.Analysis.Unitarizability.LocalBounds +OAI.Analysis.Unitarizability.Main +OAI.Analysis.Unitarizability.MaskAlgebra +OAI.Analysis.Unitarizability.Masked +OAI.Analysis.Unitarizability.Model +OAI.Analysis.Unitarizability.NetOperator +OAI.Analysis.Unitarizability.Parameters +OAI.Analysis.Unitarizability.Regular +OAI.Analysis.Unitarizability.SignMatrix +OAI.Analysis.Unitarizability.SparseMask +OAI.Analysis.Unitarizability.SparseSplitting +OAI.Analysis.Unitarizability.SphereNet +OAI.Analysis.Unitarizability.SumObstruction +OAI.Analysis.Unitarizability.Triangular +OAI.Analysis.Unitarizability.Unitarizer +OAI.Analysis.Unitarizability.UniverseTransport +OAI.Analysis.Unitarizability.VectorMean diff --git a/tasks/dixmier/solution/reference.py b/tasks/dixmier/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dixmier/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dixmier/solution/solve.sh b/tasks/dixmier/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d8001fe31e67f75b555da3d62453eed0c3f575be --- /dev/null +++ b/tasks/dixmier/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Dixmier, i.e. module OAI.Analysis.Unitarizability.UniverseTransport and the +# 32 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Unitarizability.UniverseTransport /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Dixmier" diff --git a/tasks/dixmier/task.toml b/tasks/dixmier/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4bed1182d57ea721e9f8d45b25fa85ee10fb7f7d --- /dev/null +++ b/tasks/dixmier/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dixmier" +version = "1.0.0" +description = "Prove Dixmier (openai/math family 251: Amenability, unitarizability, and Ulam stability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Dixmier.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Dixmier" +family = "251" +family_title = "Amenability, unitarizability, and Ulam stability" +subject = "Group theory" +theorems = ["OAI.Dixmier.main_theorem_all_universes"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Unitarizability.UniverseTransport" +reference_modules = 32 +reference_lean_bytes = 158919 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 332 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11843 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dixmier/tests/Challenge.lean b/tasks/dixmier/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b79e07c2b0e0a4e693d9c8e090887be106a220d7 --- /dev/null +++ b/tasks/dixmier/tests/Challenge.lean @@ -0,0 +1,51 @@ +import Mathlib.Analysis.InnerProductSpace.LinearMap +import Mathlib.Topology.ContinuousMap.Bounded.Normed +import Mathlib.Topology.Instances.Discrete + +namespace OAI + +noncomputable section +universe u v +namespace Dixmier +open scoped BoundedContinuousFunction + +def leftTranslate {G : Type u} [Group G] [TopologicalSpace G] + [DiscreteTopology G] (g : G) (f : G →ᵇ ℂ) : G →ᵇ ℂ := + f.compContinuous ⟨fun x => g⁻¹ * x, continuous_of_discreteTopology⟩ + +/-- A positive normalized left-invariant complex mean. -/ +def Amenable (G : Type u) [Group G] [TopologicalSpace G] + [DiscreteTopology G] : Prop := + ∃ m : (G →ᵇ ℂ) →ₗ[ℂ] ℂ, + m (BoundedContinuousFunction.const G 1) = 1 ∧ + (∀ f : G →ᵇ ℂ, (∀ x, 0 ≤ (f x).re ∧ (f x).im = 0) → + 0 ≤ (m f).re ∧ (m f).im = 0) ∧ + ∀ (g : G) (f : G →ᵇ ℂ), m (leftTranslate g f) = m f + +def SimilarToUnitary {G : Type u} [Group G] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (π : G →* (H →L[ℂ] H)) : Prop := + ∃ S : H ≃L[ℂ] H, ∀ (g : G) (x : H), ‖S (π g (S.symm x))‖ = ‖x‖ + +/-- A uniformly 101-bounded nonunitarizable representation on a separable +complete complex Hilbert space, with its universe explicit. -/ +def NonamenableWitness (G : Type u) [Group G] : Prop := + ∃ (H : Type v) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (_ : TopologicalSpace.SeparableSpace H) + (π : G →* (H →L[ℂ] H)), + (∀ g : G, ‖π g‖ ≤ 101) ∧ ¬ SimilarToUnitary π + +/-- Every countable discrete nonamenable group has a bounded nonunitarizable witness. -/ +def MainTheorem : Prop := + ∀ (G : Type u) [Group G] [Countable G] [TopologicalSpace G] + [DiscreteTopology G], ¬ Amenable G → NonamenableWitness.{u, v} G + +/-- The main theorem with independent group and Hilbert-space universes. -/ +theorem main_theorem_all_universes : MainTheorem.{u,v} := by + sorry + +end Dixmier + +end + +end OAI diff --git a/tasks/dixmier/tests/grade.py b/tasks/dixmier/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dixmier/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dixmier/tests/task.json b/tasks/dixmier/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4154e841c3dc09c98517a749d214f90a71da3c3e --- /dev/null +++ b/tasks/dixmier/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Dixmier", + "comparator": { + "theorem_names": [ + "OAI.Dixmier.main_theorem_all_universes" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10943 +} \ No newline at end of file diff --git a/tasks/dixmier/tests/test.sh b/tasks/dixmier/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dixmier/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/doubling-hilbert/environment/Dockerfile b/tasks/doubling-hilbert/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/doubling-hilbert/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/doubling-hilbert/environment/fetch_mathlib.sh b/tasks/doubling-hilbert/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/doubling-hilbert/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/doubling-hilbert/environment/lake-manifest.json b/tasks/doubling-hilbert/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/doubling-hilbert/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/doubling-hilbert/environment/lakefile.lean b/tasks/doubling-hilbert/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/doubling-hilbert/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/doubling-hilbert/environment/lean_setup.sh b/tasks/doubling-hilbert/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/doubling-hilbert/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/doubling-hilbert/environment/pack_submission.py b/tasks/doubling-hilbert/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/doubling-hilbert/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/doubling-hilbert/instruction.md b/tasks/doubling-hilbert/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6168b7bce6c320c22be5b2c4e78c26178721b0a --- /dev/null +++ b/tasks/doubling-hilbert/instruction.md @@ -0,0 +1,81 @@ +# openai/math challenge `DoublingHilbert` (family 098) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 098 of the release, *A negative answer to the Lang–Plaut problem* +(Convex and metric geometry). The family as a whole: Every infinite-dimensional real Banach space contains a compact doubling set that admits no bi-Lipschitz embedding into any finite-dimensional normed space. The doubling constant is universal. This answers the Lang–Plaut problem negatively, even for compact subsets of Hilbert space. + +The challenge is `DoublingHilbert`, also at `/opt/openai-math/challenges/DoublingHilbert.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace DoublingHilbert + +abbrev RealL2 := lp (fun _ : ℕ => ℝ) 2 + +/-- Intrinsic open-ball doubling with a specified integer bound and centers in the subset. -/ +def DoublingAtMost (S : Set RealL2) (bound : ℕ) : Prop := + ∀ x : S, ∀ r : ℝ, 0 < r → + ∃ centers : Finset S, centers.card ≤ bound ∧ + ∀ y : S, dist y x < r → ∃ c ∈ centers, dist y c < r / 2 + +/-- Finite distortion includes an arbitrary positive change of scale. -/ +def AdmitsBiLipschitzEmbedding (S : Set RealL2) (k : ℕ) : Prop := + ∃ f : S → EuclideanSpace ℝ (Fin k), + ∃ a : ℝ, 0 < a ∧ ∃ D : ℝ, 1 ≤ D ∧ + ∀ x y : S, a * dist x y ≤ dist (f x) (f y) ∧ + dist (f x) (f y) ≤ D * a * dist x y + +/-- A single fixed subset, independent of dimension and distortion. -/ +theorem main : ∃ S : Set RealL2, + DoublingAtMost S 76800 ∧ + ∀ k : ℕ, 0 < k → ¬ AdmitsBiLipschitzEmbedding S k := by + sorry + +end DoublingHilbert + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DoublingHilbert.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DoublingHilbert.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/doubling-hilbert/solution/closure.txt b/tasks/doubling-hilbert/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a134a36e4463c2514f6cfc5614eea1e0fb3b8998 --- /dev/null +++ b/tasks/doubling-hilbert/solution/closure.txt @@ -0,0 +1,12 @@ +OAI.Geometry.DoublingHilbert.Construction +OAI.Geometry.DoublingHilbert.Crossings +OAI.Geometry.DoublingHilbert.Derivatives +OAI.Geometry.DoublingHilbert.Doubling +OAI.Geometry.DoublingHilbert.Energy +OAI.Geometry.DoublingHilbert.Extremal +OAI.Geometry.DoublingHilbert.Grids +OAI.Geometry.DoublingHilbert.Integration +OAI.Geometry.DoublingHilbert.Main +OAI.Geometry.DoublingHilbert.Model +OAI.Geometry.DoublingHilbert.Rectangles +OAI.Geometry.DoublingHilbert.SelectedSheets diff --git a/tasks/doubling-hilbert/solution/reference.py b/tasks/doubling-hilbert/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/doubling-hilbert/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/doubling-hilbert/solution/solve.sh b/tasks/doubling-hilbert/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..80aae662b29df168f9d4f97df160a17892ef8763 --- /dev/null +++ b/tasks/doubling-hilbert/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DoublingHilbert, i.e. module OAI.Geometry.DoublingHilbert.Main and the +# 12 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.DoublingHilbert.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DoublingHilbert" diff --git a/tasks/doubling-hilbert/task.toml b/tasks/doubling-hilbert/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ddf5c925a2bebfcd5162e8db3481205b23fd5681 --- /dev/null +++ b/tasks/doubling-hilbert/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/doubling-hilbert" +version = "1.0.0" +description = "Prove DoublingHilbert (openai/math family 098: A negative answer to the Lang–Plaut problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DoublingHilbert.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DoublingHilbert" +family = "098" +family_title = "A negative answer to the Lang–Plaut problem" +subject = "Convex and metric geometry" +theorems = ["OAI.DoublingHilbert.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.DoublingHilbert.Main" +reference_modules = 12 +reference_lean_bytes = 157722 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 454 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11841 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/doubling-hilbert/tests/Challenge.lean b/tasks/doubling-hilbert/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a581b828ee7894328c069e907b24fe8547e264d7 --- /dev/null +++ b/tasks/doubling-hilbert/tests/Challenge.lean @@ -0,0 +1,30 @@ +import Mathlib + +namespace OAI + +namespace DoublingHilbert + +abbrev RealL2 := lp (fun _ : ℕ => ℝ) 2 + +/-- Intrinsic open-ball doubling with a specified integer bound and centers in the subset. -/ +def DoublingAtMost (S : Set RealL2) (bound : ℕ) : Prop := + ∀ x : S, ∀ r : ℝ, 0 < r → + ∃ centers : Finset S, centers.card ≤ bound ∧ + ∀ y : S, dist y x < r → ∃ c ∈ centers, dist y c < r / 2 + +/-- Finite distortion includes an arbitrary positive change of scale. -/ +def AdmitsBiLipschitzEmbedding (S : Set RealL2) (k : ℕ) : Prop := + ∃ f : S → EuclideanSpace ℝ (Fin k), + ∃ a : ℝ, 0 < a ∧ ∃ D : ℝ, 1 ≤ D ∧ + ∀ x y : S, a * dist x y ≤ dist (f x) (f y) ∧ + dist (f x) (f y) ≤ D * a * dist x y + +/-- A single fixed subset, independent of dimension and distortion. -/ +theorem main : ∃ S : Set RealL2, + DoublingAtMost S 76800 ∧ + ∀ k : ℕ, 0 < k → ¬ AdmitsBiLipschitzEmbedding S k := by + sorry + +end DoublingHilbert + +end OAI diff --git a/tasks/doubling-hilbert/tests/grade.py b/tasks/doubling-hilbert/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/doubling-hilbert/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/doubling-hilbert/tests/task.json b/tasks/doubling-hilbert/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8484b9eb48e8b7f88a675703b26472f8f174e5d0 --- /dev/null +++ b/tasks/doubling-hilbert/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DoublingHilbert", + "comparator": { + "theorem_names": [ + "OAI.DoublingHilbert.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10941 +} \ No newline at end of file diff --git a/tasks/doubling-hilbert/tests/test.sh b/tasks/doubling-hilbert/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/doubling-hilbert/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dutta-domain/environment/Dockerfile b/tasks/dutta-domain/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dutta-domain/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dutta-domain/environment/fetch_mathlib.sh b/tasks/dutta-domain/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dutta-domain/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dutta-domain/environment/lake-manifest.json b/tasks/dutta-domain/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dutta-domain/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dutta-domain/environment/lakefile.lean b/tasks/dutta-domain/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dutta-domain/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dutta-domain/environment/lean_setup.sh b/tasks/dutta-domain/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dutta-domain/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dutta-domain/environment/pack_submission.py b/tasks/dutta-domain/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dutta-domain/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dutta-domain/instruction.md b/tasks/dutta-domain/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..005d4a0964ee3bb04d52045ea66785e7489eed54 --- /dev/null +++ b/tasks/dutta-domain/instruction.md @@ -0,0 +1,132 @@ +# openai/math challenge `DuttaDomain` (family 194) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 194 of the release, *Lech's multiplicity conjecture* +(Algebra). The family as a whole: Proves $e(R)\le e(S)$ for every flat local homomorphism of nonzero Noetherian local rings, where $e$ is Hilbert–Samuel multiplicity. This resolves Lech's conjecture in every dimension and characteristic. + +The challenge is `DuttaDomain`, also at `/opt/openai-math/challenges/DuttaDomain.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace Lech +noncomputable def dimension (A : Type*) [CommRing A] : ℕ := + (WithBot.unbotD 0 (ringKrullDim A)).toNat + +noncomputable def colength (A : Type*) [CommRing A] [IsLocalRing A] + (N : ℕ) : ℕ := + (Module.length A (A ⧸ (IsLocalRing.maximalIdeal A) ^ N)).toNat + +noncomputable def normalizedColength (A : Type*) [CommRing A] [IsLocalRing A] + (N : ℕ) : ℝ := + (Nat.factorial (dimension A) : ℝ) * (colength A N : ℝ) / + (N : ℝ) ^ dimension A + +noncomputable def multiplicity (A : Type*) [CommRing A] [IsLocalRing A] : ℝ := + Filter.limUnder Filter.atTop (normalizedColength A) +end Lech + + + + +noncomputable section +namespace Lech +open CategoryTheory CategoryTheory.Limits HomologicalComplex Filter +open scoped Topology +universe u +variable (R : Type u) [CommRing R] [IsNoetherianRing R] [IsLocalRing R] + + +structure IsShortComplex (F : CochainComplex (ModuleCat.{u} R) ℤ) : Prop where + term_free : ∀ i, Module.Free R (F.X i) + term_finite : ∀ i, Module.Finite R (F.X i) + bounded : ∀ i, i < -(dimension R : ℤ) ∨ 0 < i → IsZero (F.X i) + homology_finite_length : ∀ i, IsFiniteLength R (F.homology i) + homology_zero_nonzero : ¬ IsZero (F.homology 0) + + + +def frobeniusComplex (p : ℕ) [Fact p.Prime] [CharP R p] (n : ℕ) + (F : CochainComplex (ModuleCat.{u} R) ℤ) : CochainComplex (ModuleCat.{u} R) ℤ := + ((ModuleCat.extendScalars (iterateFrobenius R p n)).mapHomologicalComplex (.up ℤ)).obj F + + +def shortEuler (F : CochainComplex (ModuleCat.{u} R) ℤ) : ℝ := + ∑ i∈Finset.range (dimension R+1),(-1:ℝ)^i* + ((Module.length R (F.homology (-(i:ℤ)))).toNat : ℝ) + +def duttaSequence (p : ℕ) [Fact p.Prime] [CharP R p] + (F : CochainComplex (ModuleCat.{u} R) ℤ) (n : ℕ) : ℝ := + (p:ℝ)^(-(n*dimension R : ℤ)) * shortEuler R (frobeniusComplex R p n F) + +def duttaMultiplicity (p : ℕ) [Fact p.Prime] [CharP R p] + (F : CochainComplex (ModuleCat.{u} R) ℤ) : ℝ := + limUnder atTop (duttaSequence R p F) + + + +def DuttaDomainClaim : Prop := + ∀ (D : Type u) [CommRing D] [IsNoetherianRing D] [IsLocalRing D] [IsDomain D] + [IsAdicComplete (IsLocalRing.maximalIdeal D) D] + (p : ℕ) [Fact p.Prime] [CharP D p] + (F : CochainComplex (ModuleCat.{u} D) ℤ), IsShortComplex D F → + (∀ n i,IsFiniteLength D ((frobeniusComplex D p n F).homology i)) ∧ + Tendsto (duttaSequence D p F) atTop (𝓝 (duttaMultiplicity D p F)) ∧ + multiplicity D ≤ duttaMultiplicity D p F +end Lech + +namespace Lech +universe u +theorem dutta_domain : DuttaDomainClaim.{u} := by + sorry +end Lech + +end +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DuttaDomain.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Lech.dutta_domain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dutta-domain/solution/closure.txt b/tasks/dutta-domain/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..18360db736c5933a35d38f102aa2adcc66b7f255 --- /dev/null +++ b/tasks/dutta-domain/solution/closure.txt @@ -0,0 +1,278 @@ +OAI.RingTheory.Multiplicity.ActualCechTranspose +OAI.RingTheory.Multiplicity.AdditiveLength +OAI.RingTheory.Multiplicity.AdicDense +OAI.RingTheory.Multiplicity.AdicFlatCriterion +OAI.RingTheory.Multiplicity.AlgebraicResidueTensor +OAI.RingTheory.Multiplicity.AlternatingCechAlt +OAI.RingTheory.Multiplicity.AlternatingCechPost +OAI.RingTheory.Multiplicity.AlternatingCechPrismPrimitive +OAI.RingTheory.Multiplicity.AlternatingCechUnaugmentedComplex +OAI.RingTheory.Multiplicity.ArbitraryCoefficientField +OAI.RingTheory.Multiplicity.ArtinianSupport +OAI.RingTheory.Multiplicity.AssociatedGradedReduction +OAI.RingTheory.Multiplicity.BicomplexEuler +OAI.RingTheory.Multiplicity.BicomplexImageLift +OAI.RingTheory.Multiplicity.CarrierOperators +OAI.RingTheory.Multiplicity.CartierQuotientDevissage +OAI.RingTheory.Multiplicity.CartierTowerDevissage +OAI.RingTheory.Multiplicity.CechCarrierOperators +OAI.RingTheory.Multiplicity.CechCartierRange +OAI.RingTheory.Multiplicity.CechCartierZRange +OAI.RingTheory.Multiplicity.CechCopies +OAI.RingTheory.Multiplicity.CechExact +OAI.RingTheory.Multiplicity.CechIndexing +OAI.RingTheory.Multiplicity.CechNormalization +OAI.RingTheory.Multiplicity.CechNormalizationRows +OAI.RingTheory.Multiplicity.CechProducts +OAI.RingTheory.Multiplicity.CechReduction +OAI.RingTheory.Multiplicity.CharPModuleLength +OAI.RingTheory.Multiplicity.CoefficientFieldLocalSection +OAI.RingTheory.Multiplicity.CompleteNoetherian +OAI.RingTheory.Multiplicity.CompleteQuotient +OAI.RingTheory.Multiplicity.CompleteResidueExtension +OAI.RingTheory.Multiplicity.ComplexConductor +OAI.RingTheory.Multiplicity.ComplexEstimate +OAI.RingTheory.Multiplicity.ComplexEstimateAllModule +OAI.RingTheory.Multiplicity.ComplexReduction +OAI.RingTheory.Multiplicity.ComplexTensorComparison +OAI.RingTheory.Multiplicity.ComplexTheorem +OAI.RingTheory.Multiplicity.ContractibleRetract +OAI.RingTheory.Multiplicity.CyclicDutta +OAI.RingTheory.Multiplicity.DuttaAlgClosed +OAI.RingTheory.Multiplicity.DuttaBaseChange +OAI.RingTheory.Multiplicity.DuttaData +OAI.RingTheory.Multiplicity.DuttaDimensionZero +OAI.RingTheory.Multiplicity.DuttaDomain +OAI.RingTheory.Multiplicity.DuttaEstimateLimit +OAI.RingTheory.Multiplicity.DuttaEulerLimit +OAI.RingTheory.Multiplicity.DuttaFrobeniusShift +OAI.RingTheory.Multiplicity.DuttaInfinitePerfect +OAI.RingTheory.Multiplicity.DuttaMinimalEstimate +OAI.RingTheory.Multiplicity.DuttaPerfectResidue +OAI.RingTheory.Multiplicity.DuttaPerfectionValue +OAI.RingTheory.Multiplicity.ElementaryContractibleProjector +OAI.RingTheory.Multiplicity.ExactSequenceTransport +OAI.RingTheory.Multiplicity.ExceptionalCoefficientSquare +OAI.RingTheory.Multiplicity.ExceptionalFibre +OAI.RingTheory.Multiplicity.ExceptionalFibreRestriction +OAI.RingTheory.Multiplicity.ExceptionalRootCohomology +OAI.RingTheory.Multiplicity.ExceptionalRootEulerZ +OAI.RingTheory.Multiplicity.FibreSquare +OAI.RingTheory.Multiplicity.FieldNilpotentLift +OAI.RingTheory.Multiplicity.FilteredCechAugmentationRing +OAI.RingTheory.Multiplicity.FilteredCechAugmented +OAI.RingTheory.Multiplicity.FilteredFractionReesDenominator +OAI.RingTheory.Multiplicity.FilteredFractionReesDenominatorTheory +OAI.RingTheory.Multiplicity.FiniteComplexTopInclusion +OAI.RingTheory.Multiplicity.FiniteFreeRetract +OAI.RingTheory.Multiplicity.FiniteFreeTensorCohomology +OAI.RingTheory.Multiplicity.FiniteGradedQuotient +OAI.RingTheory.Multiplicity.FiniteLengthPrimary +OAI.RingTheory.Multiplicity.FiniteModuleCech +OAI.RingTheory.Multiplicity.FiniteModuleTensor +OAI.RingTheory.Multiplicity.FiniteTensorBound +OAI.RingTheory.Multiplicity.FlatLocalSupport +OAI.RingTheory.Multiplicity.FrobeniusComplexStage +OAI.RingTheory.Multiplicity.FrobeniusFiniteLength +OAI.RingTheory.Multiplicity.FrobeniusHomologyFinite +OAI.RingTheory.Multiplicity.FrobeniusHomologyGrowth +OAI.RingTheory.Multiplicity.FrobeniusHomologySmall +OAI.RingTheory.Multiplicity.FrobeniusIntermediatePowerMap +OAI.RingTheory.Multiplicity.FrobeniusModule +OAI.RingTheory.Multiplicity.FrobeniusOrderTransfer +OAI.RingTheory.Multiplicity.FrobeniusScalarError +OAI.RingTheory.Multiplicity.FrobeniusTensorStage +OAI.RingTheory.Multiplicity.FrobeniusTensorTransfer +OAI.RingTheory.Multiplicity.GradedChartCochains +OAI.RingTheory.Multiplicity.GradedLineBasisHasBasis +OAI.RingTheory.Multiplicity.GradedLinearNormalization +OAI.RingTheory.Multiplicity.HomogeneousEval +OAI.RingTheory.Multiplicity.HomogeneousFunctor +OAI.RingTheory.Multiplicity.HomogeneousRegradeIdentity +OAI.RingTheory.Multiplicity.HomogeneousZeroPiece +OAI.RingTheory.Multiplicity.HomologyLengthDevissage +OAI.RingTheory.Multiplicity.IdealFilteredComplex +OAI.RingTheory.Multiplicity.IdealFilteredHomotopy +OAI.RingTheory.Multiplicity.IdealFilteredLayers +OAI.RingTheory.Multiplicity.IdealFilteredQuotient +OAI.RingTheory.Multiplicity.IdealFilteredRows +OAI.RingTheory.Multiplicity.IdealGradedLengthPiece +OAI.RingTheory.Multiplicity.IdealGradedRing +OAI.RingTheory.Multiplicity.IdealQuotientFunctor +OAI.RingTheory.Multiplicity.IntermediateTensorLength +OAI.RingTheory.Multiplicity.KoszulConeFunctor +OAI.RingTheory.Multiplicity.KoszulFiniteComplexBound +OAI.RingTheory.Multiplicity.KoszulHomologyMap +OAI.RingTheory.Multiplicity.KoszulPowerGrowth +OAI.RingTheory.Multiplicity.KoszulQuotientFinite +OAI.RingTheory.Multiplicity.KoszulSwap +OAI.RingTheory.Multiplicity.KoszulTensorSingle +OAI.RingTheory.Multiplicity.LechBoundedEquiv +OAI.RingTheory.Multiplicity.LechCokernelComp +OAI.RingTheory.Multiplicity.LechConnectingIso +OAI.RingTheory.Multiplicity.LechFactorizationMap +OAI.RingTheory.Multiplicity.LechFiniteFree +OAI.RingTheory.Multiplicity.LechHilbertSerre +OAI.RingTheory.Multiplicity.LechHomogeneousEval +OAI.RingTheory.Multiplicity.LechHomologyProp +OAI.RingTheory.Multiplicity.LechLengthLe +OAI.RingTheory.Multiplicity.LechLevel +OAI.RingTheory.Multiplicity.LechMapCochain +OAI.RingTheory.Multiplicity.LechNatTrans +OAI.RingTheory.Multiplicity.LechPiIso +OAI.RingTheory.Multiplicity.LechQuotientScalar +OAI.RingTheory.Multiplicity.LechSignedUnit +OAI.RingTheory.Multiplicity.LechTorsionOf +OAI.RingTheory.Multiplicity.LinearNormalization +OAI.RingTheory.Multiplicity.LinearNormalizationDimension +OAI.RingTheory.Multiplicity.LocalContractibility +OAI.RingTheory.Multiplicity.Main +OAI.RingTheory.Multiplicity.MinimalComplex +OAI.RingTheory.Multiplicity.MinimalComplexReduction +OAI.RingTheory.Multiplicity.MinimalReduction +OAI.RingTheory.Multiplicity.ModuleComplexQuotient +OAI.RingTheory.Multiplicity.NativeDescentCanonicalAlg +OAI.RingTheory.Multiplicity.NonminimalPivot +OAI.RingTheory.Multiplicity.NormalizationModuleLimit +OAI.RingTheory.Multiplicity.NormalizedLengthTrivialRelation +OAI.RingTheory.Multiplicity.NumericalSupport +OAI.RingTheory.Multiplicity.OrderedRootBasis +OAI.RingTheory.Multiplicity.PartialLaurentTotalDegree +OAI.RingTheory.Multiplicity.PerfectDomainStagesTensorTo +OAI.RingTheory.Multiplicity.PerfectTensorLimit +OAI.RingTheory.Multiplicity.PerfectionAcyclicity +OAI.RingTheory.Multiplicity.PerfectionModuleLengthFinite +OAI.RingTheory.Multiplicity.PowerSeriesFinDimension +OAI.RingTheory.Multiplicity.PowerSeriesFlatVariables +OAI.RingTheory.Multiplicity.PrimeFiltrationEuler +OAI.RingTheory.Multiplicity.PrimeFiltrationMultiplicity +OAI.RingTheory.Multiplicity.PrimeFiltrationSupport +OAI.RingTheory.Multiplicity.PrimeQuotientParameters +OAI.RingTheory.Multiplicity.PrimitiveChartFaithfullyFlat +OAI.RingTheory.Multiplicity.PrincipalCoverRegularRegularMap +OAI.RingTheory.Multiplicity.ProductSourceCoverAllowedEmpty +OAI.RingTheory.Multiplicity.ProductSourceCoverCechNat +OAI.RingTheory.Multiplicity.ProductSourceCoverFaceSlice +OAI.RingTheory.Multiplicity.ProductSourceCoverHighThreshold +OAI.RingTheory.Multiplicity.ProductSourceCoverOrdinaryPositive +OAI.RingTheory.Multiplicity.ProductSourceCoverRootSigned +OAI.RingTheory.Multiplicity.ProjectiveGhost +OAI.RingTheory.Multiplicity.ProjectiveReduction +OAI.RingTheory.Multiplicity.PureProjective +OAI.RingTheory.Multiplicity.QuotientExtension +OAI.RingTheory.Multiplicity.QuotientParameters +OAI.RingTheory.Multiplicity.QuotientShort +OAI.RingTheory.Multiplicity.ReducedRootCohomology +OAI.RingTheory.Multiplicity.ReductionMultiplicity +OAI.RingTheory.Multiplicity.ReesCoordinate +OAI.RingTheory.Multiplicity.ReesExceptionalRing +OAI.RingTheory.Multiplicity.ReesExceptionalSquare +OAI.RingTheory.Multiplicity.ReesRegular +OAI.RingTheory.Multiplicity.ReesRootBundle +OAI.RingTheory.Multiplicity.ReesRootCech +OAI.RingTheory.Multiplicity.ReesRootCechEuler +OAI.RingTheory.Multiplicity.ReesRootEuler +OAI.RingTheory.Multiplicity.ReesRootEulerConstant +OAI.RingTheory.Multiplicity.ReesRootEulerFunction +OAI.RingTheory.Multiplicity.ReesRootEulerPositivity +OAI.RingTheory.Multiplicity.ReesRootEulerRank +OAI.RingTheory.Multiplicity.ReesRootG +OAI.RingTheory.Multiplicity.ReesRootGLayer +OAI.RingTheory.Multiplicity.ReesRootGLayerCohomology +OAI.RingTheory.Multiplicity.ReesRootInclusion +OAI.RingTheory.Multiplicity.ReesRootIteration +OAI.RingTheory.Multiplicity.ReesRootLayerCech +OAI.RingTheory.Multiplicity.ReesRootLayerTotal +OAI.RingTheory.Multiplicity.ReesRootLayers +OAI.RingTheory.Multiplicity.ReesRootMap +OAI.RingTheory.Multiplicity.ReesRootNilpotence +OAI.RingTheory.Multiplicity.ReesRootPermutation +OAI.RingTheory.Multiplicity.ReesRootPositivity +OAI.RingTheory.Multiplicity.ReesRootPowerPath +OAI.RingTheory.Multiplicity.ReesRootQuotient +OAI.RingTheory.Multiplicity.ReesRootQuotientEuler +OAI.RingTheory.Multiplicity.ReesRootRows +OAI.RingTheory.Multiplicity.ReesRootThickeningEuler +OAI.RingTheory.Multiplicity.ReesRootUnfiltered +OAI.RingTheory.Multiplicity.ReesUlrichCech +OAI.RingTheory.Multiplicity.ResidueExtension +OAI.RingTheory.Multiplicity.RestrictedPolynomialImageCechComparisonHomology +OAI.RingTheory.Multiplicity.RobertsNormalization +OAI.RingTheory.Multiplicity.RobertsOrderTransfer +OAI.RingTheory.Multiplicity.RobertsPerfectResidue +OAI.RingTheory.Multiplicity.RobertsSeparable +OAI.RingTheory.Multiplicity.RootBaseProjective +OAI.RingTheory.Multiplicity.RootBundleChartsDenominator +OAI.RingTheory.Multiplicity.RootCechCoefficients +OAI.RingTheory.Multiplicity.RootCechProjective +OAI.RingTheory.Multiplicity.RootChartAtlasGlobalCoefficient +OAI.RingTheory.Multiplicity.RootChartUlrich +OAI.RingTheory.Multiplicity.RootCoactionT +OAI.RingTheory.Multiplicity.RootCoefficientEuler +OAI.RingTheory.Multiplicity.RootCoordinateMultiplication +OAI.RingTheory.Multiplicity.RootFibreCech +OAI.RingTheory.Multiplicity.RootHomogeneousCoordinates +OAI.RingTheory.Multiplicity.RootInvariantsWeightZero +OAI.RingTheory.Multiplicity.RootLineEuler +OAI.RingTheory.Multiplicity.RootOverlap +OAI.RingTheory.Multiplicity.RootPermutation +OAI.RingTheory.Multiplicity.RootProjectiveEuler +OAI.RingTheory.Multiplicity.RootRestriction +OAI.RingTheory.Multiplicity.RootSectionBase +OAI.RingTheory.Multiplicity.RootSectionDiagram +OAI.RingTheory.Multiplicity.RootStageQuotient +OAI.RingTheory.Multiplicity.RootStripComplement +OAI.RingTheory.Multiplicity.RootTowerLengthEq +OAI.RingTheory.Multiplicity.RootTowerNormalizedLength +OAI.RingTheory.Multiplicity.RootTowerRemainderExponent +OAI.RingTheory.Multiplicity.RootTowerRootWeight +OAI.RingTheory.Multiplicity.RootTwist +OAI.RingTheory.Multiplicity.RootUlrichModule +OAI.RingTheory.Multiplicity.RootUlrichNaturality +OAI.RingTheory.Multiplicity.RootUlrichSpan +OAI.RingTheory.Multiplicity.ScalarCartierLift +OAI.RingTheory.Multiplicity.ScalarCechComparison +OAI.RingTheory.Multiplicity.ScalarCechEuler +OAI.RingTheory.Multiplicity.ScalarCechShift +OAI.RingTheory.Multiplicity.ScalarChartComparison +OAI.RingTheory.Multiplicity.ScalarExtensionComplexCompare +OAI.RingTheory.Multiplicity.ScalarExtensionDepth +OAI.RingTheory.Multiplicity.ScalarExtensionFiniteHomology +OAI.RingTheory.Multiplicity.ScalarExtensionHomotopy +OAI.RingTheory.Multiplicity.ScalarHomologyError +OAI.RingTheory.Multiplicity.ScalarQuotientTransport +OAI.RingTheory.Multiplicity.SeparableOrderNormalizedLength +OAI.RingTheory.Multiplicity.ShortRankEuler +OAI.RingTheory.Multiplicity.SignedCechBicRow +OAI.RingTheory.Multiplicity.SourceGradedCechHomology +OAI.RingTheory.Multiplicity.SourceGradedThickeningNat +OAI.RingTheory.Multiplicity.StandardFactorChartsL +OAI.RingTheory.Multiplicity.SubalgebraStageFromBase +OAI.RingTheory.Multiplicity.SumEstimate +OAI.RingTheory.Multiplicity.SymmetricAffine +OAI.RingTheory.Multiplicity.TensorCechEuler +OAI.RingTheory.Multiplicity.TensorCechHomotopy +OAI.RingTheory.Multiplicity.TensorCechRankEuler +OAI.RingTheory.Multiplicity.TensorCoefficientFibre +OAI.RingTheory.Multiplicity.TensorConductor +OAI.RingTheory.Multiplicity.TensorEuler +OAI.RingTheory.Multiplicity.TensorGeneratorBound +OAI.RingTheory.Multiplicity.TensorIdealRange +OAI.RingTheory.Multiplicity.TensorPushout +OAI.RingTheory.Multiplicity.TensorQuotientCommutation +OAI.RingTheory.Multiplicity.TensorReduction +OAI.RingTheory.Multiplicity.TensorRingTwist +OAI.RingTheory.Multiplicity.TensorTotalHomologyProperty +OAI.RingTheory.Multiplicity.TorsionAcyclicity +OAI.RingTheory.Multiplicity.TorsionChartKernel +OAI.RingTheory.Multiplicity.TorsionScalarComparison +OAI.RingTheory.Multiplicity.TorsionTensorLeft +OAI.RingTheory.Multiplicity.TorsionThickening +OAI.RingTheory.Multiplicity.TorsionZeroStability +OAI.RingTheory.Multiplicity.TotalExact +OAI.RingTheory.Multiplicity.TotalGhostRowHom +OAI.RingTheory.Multiplicity.TowerRestrictedLength +OAI.RingTheory.Multiplicity.TraceConductorPerfectOrder +OAI.RingTheory.Multiplicity.TwistedLocalizationPieceMap +OAI.RingTheory.Multiplicity.UniversalFactorMapMapChart +OAI.RingTheory.Multiplicity.ZeroHomologyScalarExtension diff --git a/tasks/dutta-domain/solution/reference.py b/tasks/dutta-domain/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dutta-domain/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dutta-domain/solution/solve.sh b/tasks/dutta-domain/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..495b3d37c4a275d534c6ccba64dc68006ce29986 --- /dev/null +++ b/tasks/dutta-domain/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DuttaDomain, i.e. module OAI.RingTheory.Multiplicity.Main and the +# 278 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.Multiplicity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DuttaDomain" diff --git a/tasks/dutta-domain/task.toml b/tasks/dutta-domain/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..09817ebd729968f009cefcae11cc463c2bde1654 --- /dev/null +++ b/tasks/dutta-domain/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dutta-domain" +version = "1.0.0" +description = "Prove DuttaDomain (openai/math family 194: Lech's multiplicity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DuttaDomain.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DuttaDomain" +family = "194" +family_title = "Lech's multiplicity conjecture" +subject = "Algebra" +theorems = ["OAI.Lech.dutta_domain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.Multiplicity.Main" +reference_modules = 278 +reference_lean_bytes = 2409516 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1913 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13868 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dutta-domain/tests/Challenge.lean b/tasks/dutta-domain/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c8782275912b6b8be30b58b40bedefc5bc603b05 --- /dev/null +++ b/tasks/dutta-domain/tests/Challenge.lean @@ -0,0 +1,81 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace Lech +noncomputable def dimension (A : Type*) [CommRing A] : ℕ := + (WithBot.unbotD 0 (ringKrullDim A)).toNat + +noncomputable def colength (A : Type*) [CommRing A] [IsLocalRing A] + (N : ℕ) : ℕ := + (Module.length A (A ⧸ (IsLocalRing.maximalIdeal A) ^ N)).toNat + +noncomputable def normalizedColength (A : Type*) [CommRing A] [IsLocalRing A] + (N : ℕ) : ℝ := + (Nat.factorial (dimension A) : ℝ) * (colength A N : ℝ) / + (N : ℝ) ^ dimension A + +noncomputable def multiplicity (A : Type*) [CommRing A] [IsLocalRing A] : ℝ := + Filter.limUnder Filter.atTop (normalizedColength A) +end Lech + + + + +noncomputable section +namespace Lech +open CategoryTheory CategoryTheory.Limits HomologicalComplex Filter +open scoped Topology +universe u +variable (R : Type u) [CommRing R] [IsNoetherianRing R] [IsLocalRing R] + + +structure IsShortComplex (F : CochainComplex (ModuleCat.{u} R) ℤ) : Prop where + term_free : ∀ i, Module.Free R (F.X i) + term_finite : ∀ i, Module.Finite R (F.X i) + bounded : ∀ i, i < -(dimension R : ℤ) ∨ 0 < i → IsZero (F.X i) + homology_finite_length : ∀ i, IsFiniteLength R (F.homology i) + homology_zero_nonzero : ¬ IsZero (F.homology 0) + + + +def frobeniusComplex (p : ℕ) [Fact p.Prime] [CharP R p] (n : ℕ) + (F : CochainComplex (ModuleCat.{u} R) ℤ) : CochainComplex (ModuleCat.{u} R) ℤ := + ((ModuleCat.extendScalars (iterateFrobenius R p n)).mapHomologicalComplex (.up ℤ)).obj F + + +def shortEuler (F : CochainComplex (ModuleCat.{u} R) ℤ) : ℝ := + ∑ i∈Finset.range (dimension R+1),(-1:ℝ)^i* + ((Module.length R (F.homology (-(i:ℤ)))).toNat : ℝ) + +def duttaSequence (p : ℕ) [Fact p.Prime] [CharP R p] + (F : CochainComplex (ModuleCat.{u} R) ℤ) (n : ℕ) : ℝ := + (p:ℝ)^(-(n*dimension R : ℤ)) * shortEuler R (frobeniusComplex R p n F) + +def duttaMultiplicity (p : ℕ) [Fact p.Prime] [CharP R p] + (F : CochainComplex (ModuleCat.{u} R) ℤ) : ℝ := + limUnder atTop (duttaSequence R p F) + + + +def DuttaDomainClaim : Prop := + ∀ (D : Type u) [CommRing D] [IsNoetherianRing D] [IsLocalRing D] [IsDomain D] + [IsAdicComplete (IsLocalRing.maximalIdeal D) D] + (p : ℕ) [Fact p.Prime] [CharP D p] + (F : CochainComplex (ModuleCat.{u} D) ℤ), IsShortComplex D F → + (∀ n i,IsFiniteLength D ((frobeniusComplex D p n F).homology i)) ∧ + Tendsto (duttaSequence D p F) atTop (𝓝 (duttaMultiplicity D p F)) ∧ + multiplicity D ≤ duttaMultiplicity D p F +end Lech + +namespace Lech +universe u +theorem dutta_domain : DuttaDomainClaim.{u} := by + sorry +end Lech + +end +end + +end OAI diff --git a/tasks/dutta-domain/tests/grade.py b/tasks/dutta-domain/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dutta-domain/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dutta-domain/tests/task.json b/tasks/dutta-domain/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f1626a4791ccae381426b7bb46ce780d403d6d98 --- /dev/null +++ b/tasks/dutta-domain/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DuttaDomain", + "comparator": { + "theorem_names": [ + "OAI.Lech.dutta_domain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12968 +} \ No newline at end of file diff --git a/tasks/dutta-domain/tests/test.sh b/tasks/dutta-domain/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dutta-domain/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/dyadic-avoidance/environment/Dockerfile b/tasks/dyadic-avoidance/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/dyadic-avoidance/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/dyadic-avoidance/environment/fetch_mathlib.sh b/tasks/dyadic-avoidance/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/dyadic-avoidance/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/dyadic-avoidance/environment/lake-manifest.json b/tasks/dyadic-avoidance/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/dyadic-avoidance/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/dyadic-avoidance/environment/lakefile.lean b/tasks/dyadic-avoidance/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/dyadic-avoidance/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/dyadic-avoidance/environment/lean_setup.sh b/tasks/dyadic-avoidance/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/dyadic-avoidance/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/dyadic-avoidance/environment/pack_submission.py b/tasks/dyadic-avoidance/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/dyadic-avoidance/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/dyadic-avoidance/instruction.md b/tasks/dyadic-avoidance/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2195a52cbeead3725929376c7eecc1b01318a120 --- /dev/null +++ b/tasks/dyadic-avoidance/instruction.md @@ -0,0 +1,75 @@ +# openai/math challenge `DyadicAvoidance` (family 084) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 084 of the release, *The geometric case of the Erd\H{o}s similarity conjecture* +(Real and complex analysis). The family as a whole: For every fixed $q\in(0,1)$, constructs compact subsets of $[0,1]$ with measure arbitrarily close to one containing no translated and nontrivially dilated copy of $\{q^n:n\ge1\}$, with dilations of either sign. This resolves the geometric-progression case of the Erd\H{o}s similarity conjecture for every ratio. + +The challenge is `DyadicAvoidance`, also at `/opt/openai-math/challenges/DyadicAvoidance.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem310 + +def dyadicPoint (n : ℕ) : ℝ := + (2 : ℝ)⁻¹ ^ n + +theorem dyadic_affine_avoidance : + ∀ η : ℝ, 0 < η → η < 1 → ∃ E : Set ℝ, + E ⊆ Set.Icc (0 : ℝ) 1 ∧ IsCompact E ∧ + MeasureTheory.volume E > ENNReal.ofReal (1 - η) ∧ + ∀ x s : ℝ, s ≠ 0 → ∃ n : ℕ, 1 ≤ n ∧ + x + s * dyadicPoint n ∉ E := by + sorry + +end Problem310 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/DyadicAvoidance.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem310.dyadic_affine_avoidance` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/dyadic-avoidance/solution/closure.txt b/tasks/dyadic-avoidance/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4c592af09496558b1dd5fe5bcd6679a74a4ed58b --- /dev/null +++ b/tasks/dyadic-avoidance/solution/closure.txt @@ -0,0 +1,75 @@ +OAI.MeasureTheory.DyadicAvoidance.AdaptiveLabels +OAI.MeasureTheory.DyadicAvoidance.AddressInjectivity +OAI.MeasureTheory.DyadicAvoidance.CenterExposure +OAI.MeasureTheory.DyadicAvoidance.CenterFailureBound +OAI.MeasureTheory.DyadicAvoidance.CenterFirstDefault +OAI.MeasureTheory.DyadicAvoidance.CenterNoDefaultMass +OAI.MeasureTheory.DyadicAvoidance.CenterRouteExposure +OAI.MeasureTheory.DyadicAvoidance.ChildDistribution +OAI.MeasureTheory.DyadicAvoidance.ConcreteLabelMeasures +OAI.MeasureTheory.DyadicAvoidance.ConcreteWindowAtom +OAI.MeasureTheory.DyadicAvoidance.Construction +OAI.MeasureTheory.DyadicAvoidance.DyadicRoutedAddresses +OAI.MeasureTheory.DyadicAvoidance.ExceptionalCenters +OAI.MeasureTheory.DyadicAvoidance.ExceptionalExpectation +OAI.MeasureTheory.DyadicAvoidance.ExpectedRepair +OAI.MeasureTheory.DyadicAvoidance.ExposureMoments +OAI.MeasureTheory.DyadicAvoidance.ExposureUnionBound +OAI.MeasureTheory.DyadicAvoidance.FiniteLocalHit +OAI.MeasureTheory.DyadicAvoidance.FiniteLocalPredicate +OAI.MeasureTheory.DyadicAvoidance.FiniteTableFirstDefault +OAI.MeasureTheory.DyadicAvoidance.FiniteTableModel +OAI.MeasureTheory.DyadicAvoidance.FirstDefault +OAI.MeasureTheory.DyadicAvoidance.FirstDefaultSelection +OAI.MeasureTheory.DyadicAvoidance.FixedScaleProbability +OAI.MeasureTheory.DyadicAvoidance.GlobalFromPeriodic +OAI.MeasureTheory.DyadicAvoidance.GridGeometry +OAI.MeasureTheory.DyadicAvoidance.GridMeasure +OAI.MeasureTheory.DyadicAvoidance.GridModelStability +OAI.MeasureTheory.DyadicAvoidance.GridSeparation +OAI.MeasureTheory.DyadicAvoidance.GridStability +OAI.MeasureTheory.DyadicAvoidance.GridStabilityFin +OAI.MeasureTheory.DyadicAvoidance.GridWindowStability +OAI.MeasureTheory.DyadicAvoidance.LocalPredicateFactor +OAI.MeasureTheory.DyadicAvoidance.Main +OAI.MeasureTheory.DyadicAvoidance.Model +OAI.MeasureTheory.DyadicAvoidance.MonotoneRepresentatives +OAI.MeasureTheory.DyadicAvoidance.OrderedRoutePreservation +OAI.MeasureTheory.DyadicAvoidance.OrderedRouting +OAI.MeasureTheory.DyadicAvoidance.PackedWindowSpan +OAI.MeasureTheory.DyadicAvoidance.PeriodicBasic +OAI.MeasureTheory.DyadicAvoidance.PeriodicEnlargement +OAI.MeasureTheory.DyadicAvoidance.PeriodicEnvelope +OAI.MeasureTheory.DyadicAvoidance.PeriodicMeasure +OAI.MeasureTheory.DyadicAvoidance.PreorderIndex +OAI.MeasureTheory.DyadicAvoidance.RandomSetDensity +OAI.MeasureTheory.DyadicAvoidance.RawRepair +OAI.MeasureTheory.DyadicAvoidance.RepresentativeFailure +OAI.MeasureTheory.DyadicAvoidance.RoutedAddressInjectivity +OAI.MeasureTheory.DyadicAvoidance.RoutedExposure +OAI.MeasureTheory.DyadicAvoidance.RoutedFirstDefault +OAI.MeasureTheory.DyadicAvoidance.RoutedSetDensity +OAI.MeasureTheory.DyadicAvoidance.RoutingBudget +OAI.MeasureTheory.DyadicAvoidance.RoutingPath +OAI.MeasureTheory.DyadicAvoidance.SelectedCoordinateLaw +OAI.MeasureTheory.DyadicAvoidance.SelectorMoment +OAI.MeasureTheory.DyadicAvoidance.StableKeyRouting +OAI.MeasureTheory.DyadicAvoidance.StableRoutingBridge +OAI.MeasureTheory.DyadicAvoidance.TreePreorder +OAI.MeasureTheory.DyadicAvoidance.TreePreorderRank +OAI.MeasureTheory.DyadicAvoidance.TreeSpanBridge +OAI.MeasureTheory.DyadicAvoidance.TrialAddresses +OAI.MeasureTheory.DyadicAvoidance.WindowBudgets +OAI.MeasureTheory.DyadicAvoidance.WindowData +OAI.MeasureTheory.DyadicAvoidance.WindowDataExistence +OAI.MeasureTheory.DyadicAvoidance.WindowDataStability +OAI.MeasureTheory.DyadicAvoidance.WindowExceptionalTransfer +OAI.MeasureTheory.DyadicAvoidance.WindowFixedScale +OAI.MeasureTheory.DyadicAvoidance.WindowLocalFactor +OAI.MeasureTheory.DyadicAvoidance.WindowLocalHit +OAI.MeasureTheory.DyadicAvoidance.WindowMetadata +OAI.MeasureTheory.DyadicAvoidance.WindowPlacement +OAI.MeasureTheory.DyadicAvoidance.WindowRecursion +OAI.MeasureTheory.DyadicAvoidance.WindowSpanSum +OAI.MeasureTheory.DyadicAvoidance.WindowTableModel +OAI.MeasureTheory.DyadicAvoidance.WindowTrialAddresses diff --git a/tasks/dyadic-avoidance/solution/reference.py b/tasks/dyadic-avoidance/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/dyadic-avoidance/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/dyadic-avoidance/solution/solve.sh b/tasks/dyadic-avoidance/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..13527d941efbbbd7356cc6704cc3b159d2895f7d --- /dev/null +++ b/tasks/dyadic-avoidance/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of DyadicAvoidance, i.e. module OAI.MeasureTheory.DyadicAvoidance.Main and the +# 75 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MeasureTheory.DyadicAvoidance.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of DyadicAvoidance" diff --git a/tasks/dyadic-avoidance/task.toml b/tasks/dyadic-avoidance/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..142ee2a2caa5245569a18ecdec00b80753b53322 --- /dev/null +++ b/tasks/dyadic-avoidance/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/dyadic-avoidance" +version = "1.0.0" +description = "Prove DyadicAvoidance (openai/math family 084: The geometric case of the Erd\\H{o}s similarity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/DyadicAvoidance.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "DyadicAvoidance" +family = "084" +family_title = "The geometric case of the Erd\\H{o}s similarity conjecture" +subject = "Real and complex analysis" +theorems = ["OAI.Problem310.dyadic_affine_avoidance"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MeasureTheory.DyadicAvoidance.Main" +reference_modules = 75 +reference_lean_bytes = 369234 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 796 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12032 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/dyadic-avoidance/tests/Challenge.lean b/tasks/dyadic-avoidance/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d1abcefea41491bd5bbe0a3f22fe42e61a2d98d7 --- /dev/null +++ b/tasks/dyadic-avoidance/tests/Challenge.lean @@ -0,0 +1,24 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem310 + +def dyadicPoint (n : ℕ) : ℝ := + (2 : ℝ)⁻¹ ^ n + +theorem dyadic_affine_avoidance : + ∀ η : ℝ, 0 < η → η < 1 → ∃ E : Set ℝ, + E ⊆ Set.Icc (0 : ℝ) 1 ∧ IsCompact E ∧ + MeasureTheory.volume E > ENNReal.ofReal (1 - η) ∧ + ∀ x s : ℝ, s ≠ 0 → ∃ n : ℕ, 1 ≤ n ∧ + x + s * dyadicPoint n ∉ E := by + sorry + +end Problem310 + +end + +end OAI diff --git a/tasks/dyadic-avoidance/tests/grade.py b/tasks/dyadic-avoidance/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/dyadic-avoidance/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/dyadic-avoidance/tests/task.json b/tasks/dyadic-avoidance/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a0cdcd9b741b7dd4966d645a05168e365d5448c5 --- /dev/null +++ b/tasks/dyadic-avoidance/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "DyadicAvoidance", + "comparator": { + "theorem_names": [ + "OAI.Problem310.dyadic_affine_avoidance" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11132 +} \ No newline at end of file diff --git a/tasks/dyadic-avoidance/tests/test.sh b/tasks/dyadic-avoidance/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/dyadic-avoidance/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/edit-approximation/environment/Dockerfile b/tasks/edit-approximation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/edit-approximation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/edit-approximation/environment/fetch_mathlib.sh b/tasks/edit-approximation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/edit-approximation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/edit-approximation/environment/lake-manifest.json b/tasks/edit-approximation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/edit-approximation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/edit-approximation/environment/lakefile.lean b/tasks/edit-approximation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/edit-approximation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/edit-approximation/environment/lean_setup.sh b/tasks/edit-approximation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/edit-approximation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/edit-approximation/environment/pack_submission.py b/tasks/edit-approximation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/edit-approximation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/edit-approximation/instruction.md b/tasks/edit-approximation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29a050391dda274273e22729df46788791df2e73 --- /dev/null +++ b/tasks/edit-approximation/instruction.md @@ -0,0 +1,19220 @@ +# openai/math challenge `EditApproximation` (family 121) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 121 of the release, *Almost-linear expected-time approximation of edit distance* +(Theoretical computer science). The family as a whole: For every fixed rational $\varepsilon\in(0,1)$, gives a randomized $(1+\varepsilon)$ approximation to unit-cost edit distance in worst-case expected time $N^{1+o(1)}$, with success probability at least $2/3$. The strings have total length $N$ and polynomially bounded integer symbols. This is an asymptotic guarantee at fixed accuracy. + +The challenge is `EditApproximation`, also at `/opt/openai-math/challenges/EditApproximation.lean`: + +```lean +import Mathlib + +namespace OAI.EditDistortion +end OAI.EditDistortion + +/-! A uniform almost-linear approximation scheme for edit distance. +The statement retains the concrete binary algorithm and its exact resource accounting. -/ + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bitWordValue : List Bool → ℕ + | [] => 0 + | bit :: bits => bit.toNat + 2 * bitWordValue bits + +def bitSum (a b carry : Bool) : Bool := xor (xor a b) carry + +def bitCarry (a b carry : Bool) : Bool := (a && b) || (a && carry) || (b && carry) + +structure UnreducedRational where + num : ℤ + den : ℕ + den_pos : 0 < den + +def orderingMatches (o : Ordering) (a b : ℕ) : Prop := + (o = .lt ∧ a < b) ∨ (o = .eq ∧ a = b) ∨ (o = .gt ∧ b < a) + +def bitOrdering (high : Ordering) (a b : Bool) : Ordering := + match high with + | .lt => .lt + | .gt => .gt + | .eq => if a = b then .eq else if a then .gt else .lt + +def bitDifference (a b borrow : Bool) : Bool := xor (xor a b) borrow + +def bitBorrow (a b borrow : Bool) : Bool := ((!a) && (b || borrow)) || (b && borrow) + +structure SignedBinary where + negative : Bool + bits : List Bool + +def signedMagnitude (negative : Bool) (magnitude : ℕ) : ℤ := + if negative then -(magnitude : ℤ) else magnitude + +def trimBitWordWithWork : List Bool → List Bool × ℕ + | [] => ([], 1) + | bit :: bits => + let tail := trimBitWordWithWork bits + (if tail.1 = [] ∧ bit = false then [] else bit :: tail.1, tail.2 + 3) + +def balancedCut (lo width M i : ℕ) : ℕ := lo + i * width / M + +def gridRound (spacing position : ℕ) : ℕ := spacing * (position / spacing) + +def rationalMinimum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => min value (rationalMinimum fallback rest) + +structure RationalBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : ℚ + childState : Fin M → Child + +def rationalRefinementUpdate (δ cone : ℚ) : Option ℚ → ℚ + | none => cone + | some online => min cone (max (cone / (1 + δ)) online) + +def heightExponent (N : ℕ) : ℕ := Nat.clog 2 (Nat.clog 2 (N + 2)) + +def coarseExponent (ell : ℕ) : ℕ := Nat.sqrt (Nat.sqrt (Nat.log 2 ell)) + +structure IntegerParameters where + H : ℕ + ell : ℕ + p : ℕ + B : ℕ + initialFactor : ℕ + M : ℕ + P : ℕ + T : ℕ + S : ℕ + +structure RationalParameters where + F : ℚ + initialSlope : ℚ + coneSlope : ℚ + delta : ℚ + kappa : ℚ + tau : ℚ + theta : ℚ + gamma : ℚ + eta : ℚ + +def gridPointsBetween (g lo hi : ℕ) : List ℕ := + (List.range' (lo ⌈/⌉ g) ((hi / g + 1) - lo ⌈/⌉ g)).map fun i => g * i + +def scaledSeedValue (U : ℕ) (a gap : ℚ) : ℚ := + max (⌈(U : ℚ) / a⌉₊ : ℚ) |gap| + +def dyadicScales (N : ℕ) : List ℕ := + (List.range (Nat.log 2 N + 1)).map fun k => 2 ^ k + +def seedGridSpacing (b P : ℕ) : ℕ := max 1 (b / P) + +def finiteAssignments {α : Type u_1} : (M : ℕ) → (Fin M → List α) → List (Fin M → α) + | 0, _ => [Fin.elim0] + | M + 1, choices => + (choices 0).flatMap fun head => + (finiteAssignments M (fun i => choices i.succ)).map fun tail => Fin.cons head tail + +def powerTwoWord (n : ℕ) : List Bool := List.replicate n false ++ [true] + +def filterWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 0) + | a :: rest => + let current := test a + let tail := filterWithWork test rest + (if current.1 then a :: tail.1 else tail.1, current.2 + tail.2 + 3) + +def allWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → Bool × ℕ + | [] => (true, 0) + | a :: rest => + let current := test a + let tail := allWithWork test rest + (current.1 && tail.1, current.2 + tail.2 + 3) + +def arithmeticMapWithWork {α : Type u_1} {β : Type u_2} (f : α → β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticMapWithWork f rest + (current.1 :: tail.1, current.2 + tail.2 + 3) + +def arithmeticFlatMapWithWork {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticFlatMapWithWork f rest + (current.1 ++ tail.1, current.2 + tail.2 + current.1.length + 3) + +def upperMedian (values : List ℕ) : ℕ := + (values.mergeSort (· ≤ ·)).getD (values.length / 2) 0 + +def filterMapWithWork {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let first := f a + let tail := filterMapWithWork f rest + (match first.1 with | none => tail.1 | some b => b :: tail.1, first.2 + tail.2 + 3) + +def cellGridPoints (side : ℚ) (g cell : ℕ) : List ℕ := + (List.range' ⌈(cell : ℚ) * side / g⌉₊ + (⌈((cell : ℚ) + 1) * side / g⌉₊ - ⌈(cell : ℚ) * side / g⌉₊)).map fun i => g * i + +def groupRoundSpacing (exponent : ℕ) (h : ℚ) : ℕ := + ⌈max 1 ((2 : ℚ) ^ (-(exponent : ℤ)) * h)⌉₊ + +def refinementFactor (A : ℚ) (F : ℕ) : ℚ := max 1 (A / F) + +def localCellCoordinates (side : ℚ) (p radius : ℕ) : List ℕ := + let first := ⌊((p - radius : ℕ) : ℚ) / side⌋₊ + let last := ⌊((p + radius : ℕ) : ℚ) / side⌋₊ + List.range' first (last + 1 - first) + +def dyadicSeedPassCount (f initial : ℕ) : ℕ := (initial - f) ⌈/⌉ (f - 2) + +def dyadicSeedExponent (f initial pass : ℕ) : ℕ := initial - pass * (f - 2) + +def memberByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := equal a b + let tail := memberByWithWork equal a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +inductive BinaryMemo (α : Type u_1) where + | empty + | node (value : Option α) (left right : BinaryMemo α) + +def binaryMemoKey : ℕ → ℕ → List Bool + | 0, _ => [] + | d + 1, n => decide (n % 2 = 1) :: binaryMemoKey d (n / 2) + +inductive FiniteQuery (ι : Type u_1) where + | done (value : ℚ) + | read (key : ι) (next : ℚ → FiniteQuery ι) + +def finiteAnswerTable {κ : Type u_1} [DecidableEq κ] : List κ → List ℚ → κ → ℚ + | key :: keys, value :: values, query => + if query = key then value else finiteAnswerTable keys values query + | _, _, _ => 0 + +def queryFinRange (n m : ℕ) (h : n = m) : List (Fin m) := + (List.finRange n).map fun i => ⟨i.val, by simpa only [← h] using i.isLt⟩ + +def queryInsertWithWork {α : Type u_1} (le : α → α → Bool × ℕ) (a : α) : List α → List α × ℕ + | [] => ([a], 1) + | b :: rest => + let test := le a b + if test.1 then (a :: b :: rest, test.2 + 2) + else + let tail := queryInsertWithWork le a rest + (b :: tail.1, test.2 + tail.2 + 2) + +def integerSymbolCode : ℤ → ℕ + | .ofNat n => 2 * n + | .negSucc n => 2 * n + 1 + +inductive PositionCounts where + | empty + | node (count : ℕ) (left right : PositionCounts) + +def integerMagnitude : List ℤ → ℕ + | [] => 0 + | z :: zs => max z.natAbs (integerMagnitude zs) + +def integerInputPositionBits (target : List ℤ) : ℕ := Nat.size target.length + +def dpLength {α : Type u_1} : List α → ℕ × ℕ + | [] => (0, 1) + | _ :: rest => let result := dpLength rest; (result.1 + 1, result.2 + 1) + +def dpDrop {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, word => (word, 1) + | _ + 1, [] => ([], 1) + | n + 1, _ :: rest => let result := dpDrop n rest; (result.1, result.2 + 1) + +def dpTake {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, _ => ([], 1) + | _ + 1, [] => ([], 1) + | n + 1, first :: rest => let result := dpTake n rest; (first :: result.1, result.2 + 1) + +def dpGetD : List ℕ → ℕ → ℕ × ℕ + | [], _ => (0, 1) + | first :: _, 0 => (first, 1) + | _ :: rest, n + 1 => let result := dpGetD rest n; (result.1, result.2 + 1) + +def dpMember {α : Type u_1} [DecidableEq α] (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | first :: rest => if a = first then (true, 1) else + let result := dpMember a rest; (result.1, result.2 + 1) + +def dpMinimum (fallback : ℕ) : List ℕ → ℕ × ℕ + | [] => (fallback, 1) + | first :: rest => let result := dpMinimum fallback rest; (min first result.1, result.2 + 1) + +def integerMagnitudeWithWork : List ℤ → ℕ × ℕ + | [] => (0, 0) + | z :: rest => + let tail := integerMagnitudeWithWork rest + (max z.natAbs tail.1, tail.2 + 2) + +def inputBitLengthWithWork (n : ℕ) : ℕ × ℕ := + if h : n = 0 then (0, 1) else + let tail := inputBitLengthWithWork (n / 2) + (tail.1 + 1, tail.2 + 2) +termination_by n +decreasing_by exact Nat.div_lt_self (by omega) (by decide) + +def naturalPairWithWork (a b : ℕ) : ℕ × ℕ := + if a < b then (b * b + a, 4) else (a * a + a + b, 5) + +def inspectBitPrefix : ℕ → List Bool → Bool × ℕ + | 0, [] => (true, 1) + | 0, _ :: _ => (false, 1) + | _ + 1, [] => (true, 1) + | n + 1, _ :: rest => + let result := inspectBitPrefix n rest + (result.1, result.2 + 1) + +def memoRequestCells (bits addressCells : ℕ) : ℕ := addressCells + 8 * (bits + 1) + 64 + +def arithmeticMapAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => allocation a + arithmeticMapAllocation allocation rest + 1 + +def arithmeticFlatMapAllocation {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + arithmeticFlatMapAllocation f allocation xs + (f x).1.length + +def filterAllocation {α : Type u_1} (test : α → Bool × ℕ) (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterAllocation test allocation xs + if (test x).1 then 1 else 0 + +def filterMapAllocation {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterMapAllocation f allocation xs + if (f x).1.isSome then 1 else 0 + +def naturalEqualAllocation (a b : ℕ) : ℕ := a.bits.length + b.bits.length + 1 + +def memberByAllocation {α : Type u_1} (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 0 + | b :: rest => allocation a b + memberByAllocation allocation a rest + 1 + +def naturalWordLEAllocation (a b : List Bool) : ℕ := a.length + b.length + 1 + +def vectorMapAllocation (d : ℕ) (allocation : Fin d → ℕ) : ℕ := + (∑ i, allocation i) + 3 * d + +def allAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + allAllocation allocation xs + 1 + +def queryInsertAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 1 + | b :: rest => allocation a b + if (le a b).1 then 2 else queryInsertAllocation le allocation a rest + 1 + +def wordLEAllocation (_a _b : List Bool) : ℕ := 0 + +def indexedLeafAllocation (symbolBits positionBits : ℕ) (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + match symbol with + | none => 1 + | some _ => if lo = hi then 1 else symbolBits + 2 * positionBits + 4 + +def storedNaturalBits (values : List ℕ) : ℕ := + 1 + (values.map fun a => Nat.size a + 1).sum + +def coarseHistoryKeyCost {α : Type u_1} {β : Type u_2} {ι : Type u_3} (cost : ι → ℕ) : Sum α (Sum ι β) → ℕ + | .inr (.inl entry) => cost entry + | _ => 0 + +def bitAddNilLeftWithWork (right : List Bool) (carry : Bool) : List Bool × ℕ := + match right with + | [] => (if carry then [true] else [], 1) + | b :: bs => + let rest := bitAddNilLeftWithWork bs (OAI.EditApproximation.bitCarry false b carry) + (OAI.EditApproximation.bitSum false b carry :: rest.1, rest.2 + 9) +termination_by structural right + +def bitCompareNilLeftWithWork (right : List Bool) : Ordering × ℕ := + match right with + | [] => (.eq, 1) + | b :: bs => + let high := bitCompareNilLeftWithWork bs + (OAI.EditApproximation.bitOrdering high.1 false b, high.2 + 4) +termination_by structural right + +def bitSubtractNilLeftWithWork (right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match right with + | [] => ([], borrow, 1) + | b :: bs => + let rest := bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow) + (OAI.EditApproximation.bitDifference false b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural right + +structure BinaryFraction where + numerator : OAI.EditApproximation.SignedBinary + denominator : List Bool + denominator_pos : 0 < OAI.EditApproximation.bitWordValue denominator + +def rationalActionValue {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) (child : Child → ℚ) + (query : Parent) (action : OAI.EditApproximation.RationalBellmanAction Parent Child M) : ℚ := + L * distance query action.center + action.connection + ∑ i, child (action.childState i) + +def inputHeight (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.heightExponent N + +def smallLogExponent (N : ℕ) : ℕ := Nat.clog 2 (max 1 (OAI.EditApproximation.heightExponent N)) + +def rationalParameters (ell : ℕ) : OAI.EditApproximation.RationalParameters := + { F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (ell : ℚ) ^ 10, kappa := 1 / (ell : ℚ) ^ 4, + tau := 1 / (ell : ℚ) ^ 4, theta := 1 / (ell : ℚ) ^ 40, + gamma := 1 / (ell : ℚ) ^ 20, eta := (ell : ℚ) ^ 5 } + +def materializedAssignmentsWithWork {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → List (Vector α M) × ℕ + | 0, _ => ([Vector.ofFn Fin.elim0], 1) + | M + 1, choices => + let previous := materializedAssignmentsWithWork M (fun i => choices i.succ) + let expanded := OAI.EditApproximation.arithmeticFlatMapWithWork (fun head => + OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1) (choices 0) + (expanded.1, previous.2 + expanded.2 + 1) + +def dyadicScalesWithWork (N : ℕ) : List ℕ × ℕ := + let count := max 1 N.bits.length + let values := OAI.EditApproximation.arithmeticMapWithWork (fun e => + let word := OAI.EditApproximation.powerTwoWord e + (OAI.EditApproximation.bitWordValue word, e + 3)) (List.range count) + (values.1, values.2 + N.bits.length + count + 2) + +def dedupByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := dedupByWithWork equal rest + let member := OAI.EditApproximation.memberByWithWork equal a rest + (if member.1 then tail.1 else a :: tail.1, tail.2 + member.2 + 2) + +def queryEraseLoopWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : + List α → List α → List α × ℕ + | [], seen => (seen.reverse, seen.length + 1) + | a :: rest, seen => + let test := OAI.EditApproximation.memberByWithWork equal a seen + let tail := queryEraseLoopWithWork equal rest (if test.1 then seen else a :: seen) + (tail.1, test.2 + tail.2 + 2) + +structure RecursiveMemoResult (κ : Type u_1) where + value : ℚ + memory : OAI.EditApproximation.BinaryMemo ℚ + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + +def querySortWithWork {α : Type u_1} (le : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := querySortWithWork le rest + let inserted := OAI.EditApproximation.queryInsertWithWork le a tail.1 + (inserted.1, tail.2 + inserted.2 + 1) + +def encodeIntegerSymbolsWithWork : List ℤ → List ℕ × ℕ + | [] => ([], 0) + | z :: zs => + let rest := encodeIntegerSymbolsWithWork zs + (OAI.EditApproximation.integerSymbolCode z :: rest.1, rest.2 + 3) + +def integerInputSymbolBits (source target : List ℤ) : ℕ := + Nat.size (2 * OAI.EditApproximation.integerMagnitude (source ++ target)) + +def dpSingleton {α : Type u_1} [DecidableEq α] (a : α) (word : List α) : ℕ × ℕ := + if word = [] then (1, 1) else + let count := OAI.EditApproximation.dpLength word + let found := OAI.EditApproximation.dpMember a word + (count.1 - if found.1 then 1 else 0, count.2 + found.2 + 2) + +def dpCandidateAllocation {α : Type u_1} (target : List α) (j k : ℕ) : ℕ := + (OAI.EditApproximation.dpTake k (OAI.EditApproximation.dpDrop j target).1).1.length + +def integerInputInspectionWithWork (source target : List ℤ) : (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.integerMagnitudeWithWork source + let right := OAI.EditApproximation.integerMagnitudeWithWork target + let lengths := (OAI.EditApproximation.dpLength source, OAI.EditApproximation.dpLength target) + let symbols := OAI.EditApproximation.inputBitLengthWithWork (2 * max left.1 right.1) + let positions := OAI.EditApproximation.inputBitLengthWithWork lengths.2.1 + ((symbols.1, positions.1), + left.2 + right.2 + lengths.1.2 + lengths.2.2 + symbols.2 + positions.2 + 4) + +def bitAddNilLeftAllocation (right : List Bool) (carry : Bool) : ℕ := + match right with + | [] => if carry then 1 else 0 + | b :: bs => bitAddNilLeftAllocation bs (OAI.EditApproximation.bitCarry false b carry) + 1 +termination_by structural right + +def bitSubtractNilLeftAllocation (right : List Bool) (borrow : Bool) : ℕ := + match right with + | [] => 0 + | b :: bs => bitSubtractNilLeftAllocation bs (OAI.EditApproximation.bitBorrow false b borrow) + 1 +termination_by structural right + +def trimBitWordAllocation : List Bool → ℕ + | [] => 0 + | bit :: bits => trimBitWordAllocation bits + + if (OAI.EditApproximation.trimBitWordWithWork bits).1 = [] ∧ bit = false then 0 else 1 + +def dedupByAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => dedupByAllocation equal allocation rest + OAI.EditApproximation.memberByAllocation allocation a rest + + if (OAI.EditApproximation.memberByWithWork equal a rest).1 then 0 else 1 + +def dyadicScalesAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (List.range (max 1 N.bits.length)) + N.bits.length + max 1 N.bits.length + +def queryRangeValidAllocation (B range : ℕ) : ℕ := + (0 : ℕ).bits.length + range.bits.length + OAI.EditApproximation.naturalWordLEAllocation range.bits B.bits + +def queryEraseLoopAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → List α → ℕ + | [], seen => seen.length + | a :: rest, seen => + OAI.EditApproximation.memberByAllocation allocation a seen + + queryEraseLoopAllocation equal allocation rest (if (OAI.EditApproximation.memberByWithWork equal a seen).1 then seen else a :: seen) + + if (OAI.EditApproximation.memberByWithWork equal a seen).1 then 0 else 1 + +def queryEncodedLEAllocation {α : Type u_1} (code : α → ℕ × ℕ) (allocation : α → ℕ) (a b : α) : ℕ := + allocation a + allocation b + OAI.EditApproximation.naturalWordLEAllocation (code a).1.bits (code b).1.bits + + Nat.size (code a).1 + Nat.size (code b).1 + +def bitAddWithWork (left right : List Bool) (carry : Bool) : List Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftWithWork right carry + | a :: as => + match right with + | [] => + let rest := bitAddWithWork as [] (OAI.EditApproximation.bitCarry a false carry) + (OAI.EditApproximation.bitSum a false carry :: rest.1, rest.2 + 9) + | b :: bs => + let rest := bitAddWithWork as bs (OAI.EditApproximation.bitCarry a b carry) + (OAI.EditApproximation.bitSum a b carry :: rest.1, rest.2 + 9) +termination_by structural left + +def bitCompareWithWork (left right : List Bool) : Ordering × ℕ := + match left with + | [] => OAI.EditApproximation.bitCompareNilLeftWithWork right + | a :: as => + match right with + | [] => + let high := bitCompareWithWork as [] + (OAI.EditApproximation.bitOrdering high.1 a false, high.2 + 4) + | b :: bs => + let high := bitCompareWithWork as bs + (OAI.EditApproximation.bitOrdering high.1 a b, high.2 + 4) +termination_by structural left + +def bitSubtractWithWork (left right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftWithWork right borrow + | a :: as => + match right with + | [] => + let rest := bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow) + (OAI.EditApproximation.bitDifference a false borrow :: rest.1, rest.2.1, rest.2.2 + 9) + | b :: bs => + let rest := bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow) + (OAI.EditApproximation.bitDifference a b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural left + +def rationalBellman {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) (child : Child → ℚ) (query : Parent) : ℚ := + OAI.EditApproximation.rationalMinimum (fallback query) (actions.map (OAI.EditApproximation.rationalActionValue distance L child query)) + +def inputSmallLog (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.smallLogExponent N + +structure BinaryBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : OAI.EditApproximation.BinaryFraction + childState : Fin M → Child + +def queryEraseWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (xs : List α) : + List α × ℕ := OAI.EditApproximation.queryEraseLoopWithWork equal xs [] + +inductive BitQuery (ι : Type u_1) (β : Type u_2) where + | done (value : β) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → BitQuery ι β) + | charge (work : ℕ) (next : BitQuery ι β) + +def dpCandidate {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j k : ℕ) : ℕ × ℕ := + let suffix := OAI.EditApproximation.dpDrop j target + let piece := OAI.EditApproximation.dpTake k suffix.1 + let one := OAI.EditApproximation.dpSingleton a piece.1 + let old := OAI.EditApproximation.dpGetD previous (j + k) + (one.1 + old.1, suffix.2 + piece.2 + one.2 + old.2 + 3) + +def dpCellAllocation {α : Type u_1} (target : List α) (j : ℕ) : ℕ := + OAI.EditApproximation.dpCandidateAllocation target j 0 + + ((List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidateAllocation target j)).sum + + 4 * (target.length - j + 1) + +def initialThresholdQ (N : ℕ) : ℚ := (OAI.EditApproximation.inputHeight N : ℚ) ^ 4 + +def initialLambda (N : ℕ) : ℚ := 1 / (64 * OAI.EditApproximation.inputHeight N) + +structure BitRecursiveMemoResult (κ : Type u_1) where + value : OAI.EditApproximation.BinaryFraction + memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + localWork : ℕ + +structure RefinementParameterWords where + tau : OAI.EditApproximation.BinaryFraction + factor : OAI.EditApproximation.BinaryFraction + eta : OAI.EditApproximation.BinaryFraction + kappa : OAI.EditApproximation.BinaryFraction + delta : OAI.EditApproximation.BinaryFraction + +def inspectAccuracyWithWork (budget : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.inspectBitPrefix budget epsilon.numerator.bits + let denominator := OAI.EditApproximation.inspectBitPrefix budget epsilon.denominator + (if numerator.1 && denominator.1 then some epsilon else none, + numerator.2 + denominator.2 + 2) + +local instance queryRoundsNeZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (Nat.ne_of_gt (Nat.two_pow_pos _))⟩ + +def bitAddAllocation (left right : List Bool) (carry : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftAllocation right carry + | a :: as => + match right with + | [] => bitAddAllocation as [] (OAI.EditApproximation.bitCarry a false carry) + 1 + | b :: bs => bitAddAllocation as bs (OAI.EditApproximation.bitCarry a b carry) + 1 +termination_by structural left + +def bitSubtractAllocation (left right : List Bool) (borrow : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftAllocation right borrow + | a :: as => + match right with + | [] => bitSubtractAllocation as [] (OAI.EditApproximation.bitBorrow a false borrow) + 1 + | b :: bs => bitSubtractAllocation as bs (OAI.EditApproximation.bitBorrow a b borrow) + 1 +termination_by structural left + +def materializedAssignmentsAllocation {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → ℕ + | 0, _ => 1 + | M + 1, choices => + let previous := (OAI.EditApproximation.materializedAssignmentsWithWork M (fun i => choices i.succ)).1 + let build := fun head => OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous + materializedAssignmentsAllocation M (fun i => choices i.succ) + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Vector α M => M + 1) previous) (choices 0) + +def queryEraseAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs : List α) : ℕ := OAI.EditApproximation.queryEraseLoopAllocation equal allocation xs [] + +def querySortAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => querySortAllocation le allocation rest + + OAI.EditApproximation.queryInsertAllocation le allocation a (OAI.EditApproximation.querySortWithWork le rest).1 + +def binaryNaturalAddWithWork (a b : ℕ) : List Bool × ℕ := + OAI.EditApproximation.bitAddWithWork a.bits b.bits false + +def bitMulWithWork : List Bool → List Bool → List Bool × ℕ + | [], _ => ([], 1) + | bit :: bits, right => + let rest := bitMulWithWork bits right + if bit then + let total := OAI.EditApproximation.bitAddWithWork (false :: rest.1) right false + (total.1, rest.2 + total.2 + 2) + else (false :: rest.1, rest.2 + 2) + +def binaryNaturalCompareWithWork (a b : ℕ) : Ordering × ℕ := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + +def binaryNaturalSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let result := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (result.1, result.2.2) + +def integerParameters (N : ℕ) : OAI.EditApproximation.IntegerParameters := + let H := OAI.EditApproximation.inputHeight N + let ell := OAI.EditApproximation.inputSmallLog N + let p := OAI.EditApproximation.coarseExponent ell + { H, ell, p, B := H ^ p, initialFactor := H ^ (p + 4), + M := 2 ^ (OAI.EditApproximation.heightExponent N / 20), P := H ^ (p + 20), + T := 2 ^ ((3 * OAI.EditApproximation.heightExponent N + 3) / 4), S := H / ell ^ 2 } + +def bitDivModWithWork (divisor : List Bool) : List Bool → List Bool × List Bool × ℕ + | [] => ([], [], 1) + | bit :: bits => + let previous := bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + let comparison := OAI.EditApproximation.bitCompareWithWork candidate divisor + if comparison.1 = .lt then + (false :: previous.1, candidate, previous.2.2 + comparison.2 + 4) + else + let reduced := OAI.EditApproximation.bitSubtractWithWork candidate divisor false + (true :: previous.1, reduced.1, previous.2.2 + comparison.2 + reduced.2.2 + 5) + +def wordLEWithWork (a b : List Bool) : Bool × ℕ := + let compared := OAI.EditApproximation.bitCompareWithWork b a + (!(decide (compared.1 = .lt)), compared.2 + 1) + +def computedSeedInitialExponent (N : ℕ) : ℕ := + (OAI.EditApproximation.coarseExponent (OAI.EditApproximation.inputSmallLog N) + 4) * OAI.EditApproximation.heightExponent N + +def queryOrderedInputsWithWork {α : Type u_1} (equal le : α → α → Bool × ℕ) + (xs : List α) : List α × ℕ := + let unique := OAI.EditApproximation.queryEraseWithWork equal xs + let sorted := OAI.EditApproximation.querySortWithWork le unique.1 + (sorted.1, unique.2 + sorted.2 + 1) + +def queryActionInputsWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : List Child × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) actions + (inputs.1, inputs.2 + M + 1) + +def largeAccuracyInput (N : ℕ) (epsilon : ℚ) : Prop := + 2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon + +def dpCell {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j : ℕ) : ℕ × ℕ := + let fallback := OAI.EditApproximation.dpCandidate a target previous j 0 + let candidates := (List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidate a target previous j) + let minimum := OAI.EditApproximation.dpMinimum fallback.1 (candidates.map Prod.fst) + (minimum.1, fallback.2 + (candidates.map Prod.snd).sum + minimum.2 + + (OAI.EditApproximation.dpLength target).2 + 3 * candidates.length + 4) + +def suffixDPAllocation {α : Type u_1} : List α → List α → ℕ + | [], target => target.length + 1 + | _ :: rest, target => suffixDPAllocation rest target + + (List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCellAllocation target j.val).sum + + 3 * (target.length + 1) + +def binaryNaturalAddAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitAddAllocation a.bits b.bits false + +def queryOrderedInputsAllocation {α : Type u_1} (equal le : α → α → Bool × ℕ) + (equalAllocation leAllocation : α → α → ℕ) (xs : List α) : ℕ := + OAI.EditApproximation.queryEraseAllocation equal equalAllocation xs + + OAI.EditApproximation.querySortAllocation le leAllocation (OAI.EditApproximation.queryEraseWithWork equal xs).1 + +def queryActionInputsAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) actions + +def binaryNaturalMulWithWork (a b : ℕ) : List Bool × ℕ := OAI.EditApproximation.bitMulWithWork a.bits b.bits + +def binaryNaturalDivModWithWork (n d : ℕ) : List Bool × List Bool × ℕ := + OAI.EditApproximation.bitDivModWithWork d.bits n.bits + +def bitCeilDivWithWork (divisor bits : List Bool) : List Bool × ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + let zeroCheck := OAI.EditApproximation.bitCompareWithWork divided.2.1 [] + if zeroCheck.1 = .eq then (divided.1, divided.2.2 + zeroCheck.2 + 3) + else + let rounded := OAI.EditApproximation.bitAddWithWork divided.1 [true] false + (rounded.1, divided.2.2 + zeroCheck.2 + rounded.2 + 3) + +def wordMinWithWork (a b : List Bool) : List Bool × ℕ := + let compared := OAI.EditApproximation.wordLEWithWork a b + (if compared.1 then a else b, compared.2 + 1) + +def wordInsertWithWork (a : List Bool) : List (List Bool) → List (List Bool) × ℕ + | [] => ([a], 1) + | b :: rest => + let compared := OAI.EditApproximation.wordLEWithWork a b + if compared.1 then (a :: b :: rest, compared.2 + 2) else + let tail := wordInsertWithWork a rest + (b :: tail.1, compared.2 + tail.2 + 2) + +def saturatingSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then ([], test.2 + 1) else + let result := OAI.EditApproximation.binaryNaturalSubtractWithWork a b + (result.1, test.2 + result.2 + 2) + +def computedSeedPassCount (N : ℕ) : ℕ := + OAI.EditApproximation.dyadicSeedPassCount (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) + +def bitPowerWithWork (base : List Bool) : ℕ → List Bool × ℕ + | 0 => ([true], 1) + | n + 1 => + let previous := bitPowerWithWork base n + let product := OAI.EditApproximation.bitMulWithWork previous.1 base + let answer := OAI.EditApproximation.trimBitWordWithWork product.1 + (answer.1, previous.2 + product.2 + answer.2 + 2) + +def queryEncodedLEWithWork {α : Type u_1} (code : α → ℕ × ℕ) (a b : α) : Bool × ℕ := + let left := code a + let right := code b + let comparison := OAI.EditApproximation.wordLEWithWork left.1.bits right.1.bits + (comparison.1, left.2 + right.2 + comparison.2 + Nat.size left.1 + Nat.size right.1 + 3) + +instance largeAccuracyInput_decidable (N : ℕ) (epsilon : ℚ) : Decidable (OAI.EditApproximation.largeAccuracyInput N epsilon) := + inferInstanceAs (Decidable (2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon)) + +def chargedSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ × ℕ + | [], target => + (List.ofFn (fun j : Fin (target.length + 1) => target.length - j.val), + 4 * (target.length + 1)) + | a :: rest, target => + let previous := chargedSuffixDP rest target + let cells := List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCell a target previous.1 j.val + (cells.map Prod.fst, previous.2 + (cells.map Prod.snd).sum + + 2 * (OAI.EditApproximation.dpLength target).2 + 2 * cells.length + 3) + +def computedCoarseDepth (N n : ℕ) : ℕ := Nat.clog (OAI.EditApproximation.integerParameters N).B (max 1 n) + +def queryRangeValidWithWork (B range : ℕ) : Bool × ℕ := + let positive := OAI.EditApproximation.binaryNaturalCompareWithWork 0 range + let bounded := OAI.EditApproximation.wordLEWithWork range.bits B.bits + (decide (positive.1 = .lt) && bounded.1, positive.2 + bounded.2 + 2) + +def coarsePaddedReadWithWork {α : Type u_1} (n : ℕ) (source : List α) (offset : ℕ) : + Option (Option α) × ℕ := + let inside := OAI.EditApproximation.binaryNaturalCompareWithWork offset n + (if inside.1 = .lt then some source[offset]? else none, + inside.2 + Nat.size n + Nat.size offset + 2) + +def coarseRangeCopyWithWork (read : ℕ → ℕ) : ℕ → ℕ → List ℕ × ℕ + | _, 0 => ([], 1) + | start, length + 1 => + let next := OAI.EditApproximation.binaryNaturalAddWithWork start 1 + let tail := coarseRangeCopyWithWork read (OAI.EditApproximation.bitWordValue next.1) length + (read start :: tail.1, tail.2 + next.2 + Nat.size start + Nat.size (read start) + 3) + +def bitMulAllocation : List Bool → List Bool → ℕ + | [], _ => 0 + | bit :: bits, right => + bitMulAllocation bits right + 1 + + if bit then OAI.EditApproximation.bitAddAllocation (false :: (OAI.EditApproximation.bitMulWithWork bits right).1) right false else 0 + +def bitDivModAllocation (divisor : List Bool) : List Bool → ℕ + | [] => 0 + | bit :: bits => + let candidate := bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + bitDivModAllocation divisor bits + 2 + + if (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt then 0 + else OAI.EditApproximation.bitSubtractAllocation candidate divisor false + +def saturatingSubtractAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then 0 else OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def makeStateAllocation (n lo hi : ℕ) : ℕ := + OAI.EditApproximation.naturalWordLEAllocation lo.bits hi.bits + OAI.EditApproximation.naturalWordLEAllocation hi.bits n.bits + + if ((OAI.EditApproximation.wordLEWithWork lo.bits hi.bits).1 && (OAI.EditApproximation.wordLEWithWork hi.bits n.bits).1) = true then 2 else 0 + +def translatedEndpointAllocation (reference root endpoint : ℕ) : ℕ := + OAI.EditApproximation.bitSubtractAllocation endpoint.bits root.bits false + + OAI.EditApproximation.binaryNaturalAddAllocation reference (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root).1) + +def wordInsertAllocation (a : List Bool) : List (List Bool) → ℕ + | [] => 1 + | b :: rest => OAI.EditApproximation.wordLEAllocation a b + + if (OAI.EditApproximation.wordLEWithWork a b).1 then 2 else wordInsertAllocation a rest + 1 + +def wordSortWithWork : List (List Bool) → List (List Bool) × ℕ + | [] => ([], 1) + | a :: rest => + let tail := wordSortWithWork rest + let inserted := OAI.EditApproximation.wordInsertWithWork a tail.1 + (inserted.1, tail.2 + inserted.2 + 2) + +def binaryGridRoundWithWork (spacing position : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork position spacing + let rounded := OAI.EditApproximation.bitMulWithWork spacing.bits quotient.1 + (rounded.1, quotient.2.2 + rounded.2 + 2) + +def gridPointsWithWork (g lo hi : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits + let upper := OAI.EditApproximation.binaryNaturalDivModWithWork hi g + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue lower.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, lower.2 + upper.2.2 + stop.2 + count.2 + points.2 + + Nat.size g + Nat.size lo + Nat.size hi + 5) + +def seedGridSpacingWithWork (b P : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork b P + let test := OAI.EditApproximation.wordLEWithWork quotient.1 [true] + (if test.1 then [true] else quotient.1, quotient.2.2 + test.2 + 2) + +def balancedCutWithWork (lo width M i : ℕ) : List Bool × ℕ := + let product := OAI.EditApproximation.binaryNaturalMulWithWork i width + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) M + let result := OAI.EditApproximation.binaryNaturalAddWithWork lo (OAI.EditApproximation.bitWordValue quotient.1) + (result.1, product.2 + quotient.2.2 + result.2 + 2) + +def triangularMassWithWork (K : ℕ) : List Bool × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork K 1 + let product := OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next.1) + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) 2 + (quotient.1, next.2 + product.2 + quotient.2.2 + 3) + +def refinementBaseWithWork (ell : List Bool) : List Bool × ℕ := + let power := OAI.EditApproximation.bitPowerWithWork ell 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + let result := OAI.EditApproximation.trimBitWordWithWork increment.1 + (result.1, power.2 + increment.2 + result.2 + 2) + +def queryPairWithWork (a b : ℕ) : ℕ × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then + let square := OAI.EditApproximation.binaryNaturalMulWithWork b b + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + result.2 + 3) + else + let square := OAI.EditApproximation.binaryNaturalMulWithWork a a + let linear := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue linear.1) b + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + linear.2 + result.2 + 4) + +def queryCellValidWithWork (n exponent : ℕ) (cell : ℕ × ℕ) : Bool × ℕ := + let cap := OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + let left := OAI.EditApproximation.wordLEWithWork cell.1.bits cap.1 + let right := OAI.EditApproximation.wordLEWithWork cell.2.bits cap.1 + (left.1 && right.1, cap.2 + left.2 + right.2 + exponent + 4) + +def queryFinOfNatWithWork (bound value : ℕ) (hb : 0 < bound) : Fin bound × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let result := OAI.EditApproximation.binaryNaturalDivModWithWork value bound + (⟨OAI.EditApproximation.bitWordValue result.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 value bound hb).2] + exact Nat.mod_lt value hb⟩, result.2.2 + 1) + +def coarseDenominatorWithWork (allowanceDen q L branching : List Bool) (D : ℕ) : + List Bool × ℕ := + let first := OAI.EditApproximation.bitMulWithWork L branching + let base := OAI.EditApproximation.bitMulWithWork first.1 q + let trimmedBase := OAI.EditApproximation.trimBitWordWithWork base.1 + let power := OAI.EditApproximation.bitPowerWithWork trimmedBase.1 D + let initial := OAI.EditApproximation.bitMulWithWork allowanceDen q + let product := OAI.EditApproximation.bitMulWithWork initial.1 power.1 + let result := OAI.EditApproximation.trimBitWordWithWork product.1 + (result.1, first.2 + base.2 + trimmedBase.2 + power.2 + initial.2 + product.2 + result.2 + 7) + +def coarseFramedReadWithWork {α : Type u_1} (k n : ℕ) (word : List α) (i : ℕ) : + Option (Option α) × ℕ := + let lower := OAI.EditApproximation.binaryNaturalCompareWithWork i k + if lower.1 = .lt then (none, lower.2 + Nat.size k + Nat.size n + Nat.size i + 2) else + let finish := OAI.EditApproximation.binaryNaturalAddWithWork k n + let upper := OAI.EditApproximation.binaryNaturalCompareWithWork i (OAI.EditApproximation.bitWordValue finish.1) + if upper.1 = .lt then + let offset := OAI.EditApproximation.saturatingSubtractWithWork i k + (some word[OAI.EditApproximation.bitWordValue offset.1]?, lower.2 + finish.2 + upper.2 + offset.2 + + Nat.size k + Nat.size n + Nat.size i + 4) + else (none, lower.2 + finish.2 + upper.2 + Nat.size k + Nat.size n + Nat.size i + 3) + +def coarseDescriptorWithWork (B d n start : ℕ) : List Bool × ℕ := + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let remaining := OAI.EditApproximation.saturatingSubtractWithWork n start + let clipped := OAI.EditApproximation.wordMinWithWork capacity.1 remaining.1 + (clipped.1, capacity.2 + remaining.2 + clipped.2 + + Nat.size B + Nat.size d + Nat.size n + Nat.size start + 4) + +def coarseChildOffsetWithWork (offset capacity index : ℕ) : List Bool × ℕ := + let displacement := OAI.EditApproximation.binaryNaturalMulWithWork index capacity + let result := OAI.EditApproximation.binaryNaturalAddWithWork offset (OAI.EditApproximation.bitWordValue displacement.1) + (result.1, displacement.2 + result.2 + Nat.size index + Nat.size capacity + Nat.size offset + 3) + +def coarseInputGuardWithWork (sourceLo sourceHi targetLo targetHi : ℕ) : Bool × ℕ := + let sourceWidth := OAI.EditApproximation.saturatingSubtractWithWork sourceHi sourceLo + let targetWidth := OAI.EditApproximation.saturatingSubtractWithWork targetHi targetLo + let twice := OAI.EditApproximation.binaryNaturalMulWithWork 2 (OAI.EditApproximation.bitWordValue sourceWidth.1) + let compared := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.bitWordValue twice.1) (OAI.EditApproximation.bitWordValue targetWidth.1) + (decide (compared.1 = .lt), sourceWidth.2 + targetWidth.2 + twice.2 + compared.2 + 6) + +def bitPowerAllocation (base : List Bool) : ℕ → ℕ + | 0 => 1 + | n + 1 => + let previous := (OAI.EditApproximation.bitPowerWithWork base n).1 + bitPowerAllocation base n + OAI.EditApproximation.bitMulAllocation previous base + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.bitMulWithWork previous base).1 + +def bitCeilDivAllocation (divisor bits : List Bool) : ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + OAI.EditApproximation.bitDivModAllocation divisor bits + + if (OAI.EditApproximation.bitCompareWithWork divided.2.1 []).1 = .eq then 0 + else 1 + OAI.EditApproximation.bitAddAllocation divided.1 [true] false + +def binaryNaturalMulAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def binaryNaturalDivAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitDivModAllocation b.bits a.bits + +def triangularMassAllocation (K : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork K 1).1 + let product := (OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next)).1 + OAI.EditApproximation.bitAddAllocation K.bits (1 : ℕ).bits false + + OAI.EditApproximation.bitMulAllocation K.bits (OAI.EditApproximation.bitWordValue next).bits + + OAI.EditApproximation.bitDivModAllocation (2 : ℕ).bits (OAI.EditApproximation.bitWordValue product).bits + +def binaryIntervalRoundWithWork (spacing lo hi : ℕ) : (List Bool × List Bool) × ℕ := + let left := OAI.EditApproximation.binaryGridRoundWithWork spacing lo + let right := OAI.EditApproximation.binaryGridRoundWithWork spacing hi + ((left.1, right.1), left.2 + right.2 + 1) + +def computedQueryBase (N : ℕ) : List Bool := + (OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits).1 + +def coarsePreparedSlicesWithWork (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : Option (List ℕ × List ℕ) × ℕ := + let guard := OAI.EditApproximation.coarseInputGuardWithWork sourceLo sourceHi targetLo targetHi + if guard.1 then (none, guard.2) else + let copiedSource := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => source[i]?.getD 0) sourceLo (sourceHi - sourceLo) + let copiedTarget := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => target[i]?.getD 0) targetLo (targetHi - targetLo) + (some (copiedSource.1, copiedTarget.1), guard.2 + copiedSource.2 + copiedTarget.2) + +def gridPointsAllocation (g lo hi : ℕ) : ℕ := + let lower := (OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits).1 + let upper := (OAI.EditApproximation.binaryNaturalDivModWithWork hi g).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.bitCeilDivAllocation g.bits lo.bits + OAI.EditApproximation.binaryNaturalDivAllocation hi g + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue upper) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower) + + indices.length + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i) indices + +def balancedCutAllocation (lo width M i : ℕ) : ℕ := + let product := (OAI.EditApproximation.binaryNaturalMulWithWork i width).1 + let quotient := (OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product) M).1 + OAI.EditApproximation.binaryNaturalMulAllocation i width + OAI.EditApproximation.binaryNaturalDivAllocation (OAI.EditApproximation.bitWordValue product) M + + OAI.EditApproximation.binaryNaturalAddAllocation lo (OAI.EditApproximation.bitWordValue quotient) + +def seedGridSpacingAllocation (b P : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation b P + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 [true] + 1 + +def queryCellValidAllocation (n exponent : ℕ) (cell : ℕ × ℕ) : ℕ := + let cap := (OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent))).1 + OAI.EditApproximation.binaryNaturalMulAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + + OAI.EditApproximation.naturalWordLEAllocation cell.1.bits cap + OAI.EditApproximation.naturalWordLEAllocation cell.2.bits cap + exponent + 1 + +def queryPairAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then + OAI.EditApproximation.binaryNaturalMulAllocation b b + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork b b).1) a + else + OAI.EditApproximation.binaryNaturalMulAllocation a a + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a + + OAI.EditApproximation.binaryNaturalAddAllocation + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a).1) b + +def binaryGridRoundAllocation (spacing position : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation position spacing + + OAI.EditApproximation.bitMulAllocation spacing.bits (OAI.EditApproximation.binaryNaturalDivModWithWork position spacing).1 + +def wordSortAllocation : List (List Bool) → ℕ + | [] => 0 + | a :: rest => wordSortAllocation rest + + OAI.EditApproximation.wordInsertAllocation a (OAI.EditApproximation.wordSortWithWork rest).1 + 0 + +def reduceOnlineIntegerAllocation (K integer : ℕ) : ℕ := + OAI.EditApproximation.triangularMassAllocation K + + OAI.EditApproximation.bitDivModAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1).bits integer.bits + Nat.size integer + +def coarsePreparedInputStorage (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : ℕ := + match (OAI.EditApproximation.coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).1 with + | none => 1 + | some (x, y) => 1 + OAI.EditApproximation.storedNaturalBits x + OAI.EditApproximation.storedNaturalBits y + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def optimizerTriangularMass (K : ℕ) : ℕ := ∑ j ∈ range K, (j + 1) + +def rationalLogApproximation (r : ℚ) (K : ℕ) : ℚ := + 2 * ∑ k ∈ range K, (((r - 1) / (r + 1)) ^ (2 * k + 1) / (2 * k + 1)) + +def rationalLinearizationMaximizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (gradient : ι → ℚ) : ι → ℚ := + (vertices.argmax fun p => ∑ i ∈ coordinates, gradient i * p i).getD (fun _ => 0) + +def bandCoordinates {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) : Finset (β × σ) := + band.biUnion fun action => univ.image fun child => (child, action child) + +def actionVector {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq σ] + (mass : β → ℚ) (action : β → σ) (coordinate : β × σ) : ℚ := + if coordinate.2 = action coordinate.1 then mass coordinate.1 / (∑ child, mass child) else 0 + +def rationalOptimisticHistory {ι : Type u_1} (κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + ∑ j ∈ range t, (gain j i + (1 - 2 * κ) * decrement j i) + +def rejectionBitCount (N : ℕ) : ℕ := Nat.clog 2 N + +def vectorMapWithWork {α : Type u_1} (d : ℕ) (f : Fin d → α × ℕ) : Vector α d × ℕ := + let cells := Vector.ofFn f + (cells.map Prod.fst, (cells.map Prod.snd).toList.sum + 6 * d) + +def TreeLayer (M : ℕ) : ℕ → Type + | 0 => PUnit + | d + 1 => TreeLayer M d × Fin M + +def intervalTreeDepth (M nx : ℕ) : ℕ := Nat.clog M (max 1 nx) + +def rationalMaximum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => max value (rationalMaximum fallback rest) + +def rationalDyadicCeiling (value : ℚ) : ℚ := (2 : ℚ) ^ Int.clog 2 value + +def listedBandCoordinates {M : ℕ} {σ : Type u_1} [DecidableEq σ] + (band : List (Fin M → σ)) : List (Fin M × σ) := + (band.flatMap fun action => List.ofFn fun child => (child, action child)).dedup + +def childGain {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := -table t i / mass i.1 + +def childDecrement {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := (table t i - table (t + 1) i) / mass i.1 + +def naturalEqualWithWork (a b : ℕ) : Bool × ℕ := + let result := OAI.EditApproximation.binaryNaturalCompareWithWork a b + (decide (result.1 = .eq), result.2 + 1) + +def translatedEndpointWithWork (reference root endpoint : ℕ) : ℕ × ℕ := + let difference := OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root + let result := OAI.EditApproximation.binaryNaturalAddWithWork reference (OAI.EditApproximation.bitWordValue difference.1) + (OAI.EditApproximation.bitWordValue result.1, difference.2 + result.2 + 2) + +def rationalOnlineMinimum : List ℚ → Option ℚ + | [] => none + | first :: rest => some (OAI.EditApproximation.rationalMinimum first rest) + +def dyadicQueryWindow (N : ℕ) (w a F : ℚ) : List ℕ := + (OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide (w / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * w) + +def actionCurrentInputCover {Parent : Type u_1} {Child : Type u_2} [DecidableEq Child] {M : ℕ} + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) : Finset Child := + (List.finRange actions.length).toFinset.biUnion fun index => + Finset.univ.image (actions.get index).childState + +def boundedOnlineInteger (n : ℕ) (hn : 0 < n) (integer : ℕ) : Fin n := + ⟨integer % n, Nat.mod_lt _ hn⟩ + +def orderedInputs {ι : Type u_1} [DecidableEq ι] (encode : ι → ℕ) + (hinjective : Function.Injective encode) (inputs : Finset ι) : List ι := + let _ : LinearOrder ι := LinearOrder.lift' encode hinjective + inputs.sort (· ≤ ·) + +def CoarseThresholdDraws (B : ℕ) : ℕ → Type + | 0 => PUnit + | D + 1 => (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D) + +def coarseThresholdContribution (threshold scale value : ℚ) : ℚ := + if threshold ≤ value then max value scale else 0 + +def coarseChildThreshold (B : ℕ) (Q allowance : ℚ) (draw : Fin B) : ℚ := + allowance * (draw.val + 1 : ℕ) / ((B : ℚ) * Q) + +def coarseCommonDenominator (allowanceDen q L B D : ℕ) : ℕ := + allowanceDen * q * (L * B * q) ^ D + +def rationalSmoothedGradient {ι : Type u_1} (G : ℕ) (linear p : ι → ℚ) (i : ι) : ℚ := + -OAI.EditApproximation.rationalLogApproximation (p i + 1 / (G : ℚ) ^ 50) (G ^ 60) - 1 + linear i + +def rationalOnlineLinear {ι : Type u_1} (η κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + η * (OAI.EditApproximation.rationalOptimisticHistory κ gain decrement t i + gain t i) + +def triangularChoice : (K : ℕ) → Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K + | 0, integer => Fin.elim0 integer + | K + 1, integer => + if h : integer.val < OAI.EditApproximation.optimizerTriangularMass K then + (triangularChoice K ⟨integer.val, h⟩).castSucc + else ⟨K, by omega⟩ + +instance treeLayerFintype (M : ℕ) : (d : ℕ) → Fintype (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (Fintype PUnit) + | d + 1 => + letI := treeLayerFintype M d + inferInstanceAs (Fintype (OAI.EditApproximation.TreeLayer M d × Fin M)) + +abbrev PhysicalNode (M J : ℕ) := Σ d : Fin (J + 1), OAI.EditApproximation.TreeLayer M d.val + +def finiteRationalOptimizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G : ℕ) : ℕ → ι → ℚ + | 0 => vertices.headD (fun _ => 0) + | j + 1 => + let p := finiteRationalOptimizer coordinates vertices linear G j + let selected := OAI.EditApproximation.rationalLinearizationMaximizer coordinates vertices + (OAI.EditApproximation.rationalSmoothedGradient G linear p) + fun i => (1 - 2 / ((j : ℚ) + 2)) * p i + (2 / ((j : ℚ) + 2)) * selected i + +instance physicalNodeFintype (M J : ℕ) : Fintype (OAI.EditApproximation.PhysicalNode M J) := inferInstance + +abbrev PhysicalInternalNode (M J : ℕ) := {node : OAI.EditApproximation.PhysicalNode M J // node.1.val < J} + +def finiteOptimizerAction {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G j : ℕ) : β → σ := + let coordinates := OAI.EditApproximation.bandCoordinates band.toFinset + let vertices := band.map (OAI.EditApproximation.actionVector mass) + let gradient := OAI.EditApproximation.rationalSmoothedGradient G linear (OAI.EditApproximation.finiteRationalOptimizer coordinates vertices linear G j) + (band.argmax fun action => ∑ coordinate ∈ coordinates, + gradient coordinate * OAI.EditApproximation.actionVector mass action coordinate).getD (band.head hband) + +def finiteOptimizerActionDraw {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G K : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : β → σ := + OAI.EditApproximation.finiteOptimizerAction band hband mass linear G (OAI.EditApproximation.triangularChoice K integer).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def width (a : OAI.EditApproximation.BinaryFraction) : ℕ := max a.numerator.bits.length a.denominator.length + +def denominatorInteger (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.SignedBinary := ⟨false, a.denominator⟩ + +def zero : OAI.EditApproximation.BinaryFraction := ⟨⟨false, []⟩, [true], by decide⟩ + +def canonicalizeWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + exact + let numerator := OAI.EditApproximation.trimBitWordWithWork a.numerator.bits + let denominator := OAI.EditApproximation.trimBitWordWithWork a.denominator + (⟨⟨a.numerator.negative, numerator.1⟩, denominator.1, by + rw [proof_trimBitWordWithWork_value_6] + exact a.denominator_pos⟩, numerator.2 + denominator.2 + 2) + +def inversePowerTwo (n : ℕ) : OAI.EditApproximation.BinaryFraction := by + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + exact + ⟨⟨false, [true]⟩, OAI.EditApproximation.powerTwoWord n, by rw [proof_powerTwoWord_value_13]; positivity⟩ + +def doubleFraction (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨a.numerator.negative, false :: a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def absolute (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def naturalCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) + else + let result := OAI.EditApproximation.bitCeilDivWithWork a.denominator a.numerator.bits + (result.1, result.2 + 1) + +def ofNaturalWord (bits : List Bool) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, bits⟩, [true], by decide⟩ + +def naturalFloorWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) else + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator a.numerator.bits + (quotient.1, quotient.2.2 + 1) + +def queryDataReadBudget (M n : ℕ) {κ : Type u_1} (keys : List κ) : ℕ := + 1 + keys.length * (24 * max (Nat.size M) (Nat.size n) + 9) + +def onlineParametersWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : + (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.BinaryFraction) × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let etaPower := OAI.EditApproximation.bitPowerWithWork ell 5 + let kappaPower := OAI.EditApproximation.bitPowerWithWork ell 4 + let eta : OAI.EditApproximation.BinaryFraction := ⟨⟨false, etaPower.1⟩, [true], by decide⟩ + let kappa : OAI.EditApproximation.BinaryFraction := ⟨⟨false, [true]⟩, kappaPower.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩ + ((eta, kappa), etaPower.2 + kappaPower.2 + 2) + +def refinementDecrementWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork ell 10 + (⟨⟨false, [true]⟩, denominator.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩, denominator.2 + 1) + +abbrev CoarseBinaryArray := Option (List OAI.EditApproximation.BinaryFraction) + +def coarseRootDenominator (B q L d : ℕ) : List Bool × ℕ := + OAI.EditApproximation.coarseDenominatorWithWork (1 : ℕ).bits q.bits L.bits B.bits d + +def naturalListEqualWithWork : List ℕ → List ℕ → Bool × ℕ + | [], [] => (true, 1) + | a :: left, b :: right => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then + let tail := naturalListEqualWithWork left right + (tail.1, test.2 + tail.2 + 2) + else (false, test.2 + 2) + | _, _ => (false, 1) + +def canonicalizeAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.trimBitWordAllocation a.numerator.bits + OAI.EditApproximation.trimBitWordAllocation a.denominator + +def invAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if (OAI.EditApproximation.bitCompareWithWork a.numerator.bits []).1 = .eq then 1 else 0 + +def naturalCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitCeilDivAllocation a.denominator a.numerator.bits + +def gatheredLookupAllocation {κ : Type u_1} (equal : κ → κ → Bool × ℕ) + (allocation : κ → κ → ℕ) : List κ → List OAI.EditApproximation.BinaryFraction → κ → ℕ + | key :: keys, _value :: values, query => + allocation query key + if (equal query key).1 then 0 + else gatheredLookupAllocation equal allocation keys values query + | _, _, _ => 0 + +def naturalFloorAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitDivModAllocation a.denominator a.numerator.bits + +def signedPowerTwoAllocation (e : ℤ) : ℕ := + if 0 ≤ e then e.toNat + 2 else (-e).toNat + 2 + +def invWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + exact + let comparison := OAI.EditApproximation.bitCompareWithWork a.numerator.bits [] + if h : comparison.1 = .eq then (OAI.EditApproximation.BinaryFraction.zero, comparison.2 + 2) else + (⟨⟨a.numerator.negative, a.denominator⟩, a.numerator.bits, by + have hnonzero : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hzero + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 hzero) + omega⟩, comparison.2 + 2) + +def signedPowerTwoWithWork (e : ℤ) : OAI.EditApproximation.BinaryFraction × ℕ := + if 0 ≤ e then + (⟨⟨false, OAI.EditApproximation.powerTwoWord e.toNat⟩, [true], by decide⟩, e.toNat + 3) + else (OAI.EditApproximation.BinaryFraction.inversePowerTwo (-e).toNat, (-e).toNat + 3) + +def fixedDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + quotient.2.2 + answer.2 + 4) + +def finalAnswerWithWork (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a + let clamped := OAI.EditApproximation.wordMinWithWork N.bits floor.1 + (clamped.1, floor.2 + clamped.2 + Nat.size N + 2) + +def coarseGridNatWithWork (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork n.bits denominator + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨false, product.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + answer.2 + 3) + +def coarseBinaryMapWithWork (f : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ) : + OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.arithmeticMapWithWork f values + (some result.1, result.2) + +def fixedDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + OAI.EditApproximation.bitMulAllocation a.numerator.bits denominator + OAI.EditApproximation.bitDivModAllocation a.denominator product.1 + + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation raw + +def finalAnswerAllocation (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation a + OAI.EditApproximation.naturalWordLEAllocation N.bits (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a).1 + Nat.size N + 1 + +def powerDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork base n + let answer := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork a denominator.1 (by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hbase) + (answer.1, denominator.2 + answer.2 + 1) + +def powerDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + OAI.EditApproximation.bitPowerAllocation base n + OAI.EditApproximation.BinaryFraction.fixedDenominatorAllocation a (OAI.EditApproximation.bitPowerWithWork base n).1 + (by rw [proof_bitPowerWithWork_value_76]; exact Nat.pow_pos hbase) + +def finishCachedWithWork (raw : OAI.EditApproximation.BinaryFraction × ℕ) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.powerDenominatorWithWork raw.1 base hbase remaining + (result.1, raw.2 + result.2 + 1) + +def finishCachedAllocation (raw : OAI.EditApproximation.BinaryFraction × ℕ) (allocation : ℕ) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : ℕ := + allocation + OAI.EditApproximation.BinaryFraction.powerDenominatorAllocation raw.1 base hbase remaining + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalChild {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) + (i : Fin M) : OAI.EditApproximation.PhysicalNode M J := + ⟨⟨node.1.val + 1, by omega⟩, (node.2, i)⟩ + +instance treeLayerDecidableEq (M : ℕ) : (d : ℕ) → DecidableEq (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (DecidableEq PUnit) + | d + 1 => + letI := treeLayerDecidableEq M d + inferInstanceAs (DecidableEq (OAI.EditApproximation.TreeLayer M d × Fin M)) + +def treeLayerCode (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ + | 0, _ => 0 + | d + 1, path => path.2.val + M * treeLayerCode M d path.1 + +def localOnlineMassBound (M P H : ℕ) : ℕ := + OAI.EditApproximation.optimizerTriangularMass ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) + +def treeLayerCodeWithWork (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ × ℕ + | 0, _ => (0, 1) + | d + 1, path => let previous := treeLayerCodeWithWork M d path.1 + (path.2.val + M * previous.1, previous.2 + 3) + +def queryNaturalIndexWithWork (a : ℕ) : List ℕ → ℕ × ℕ + | [] => (0, 1) + | b :: rest => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then (0, test.2 + 1) + else + let tail := queryNaturalIndexWithWork a rest + (tail.1 + 1, test.2 + tail.2 + 2) + +def scheduledSeedWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + +def coarseLetterMatchWithWork : Option (Option ℕ) → Option ℕ → Bool × ℕ + | none, _ => (false, 1) + | some none, none => (true, 1) + | some (some a), some b => OAI.EditApproximation.naturalEqualWithWork a b + | _, _ => (false, 1) + +def queryNaturalIndexAllocation (a : ℕ) : List ℕ → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.naturalEqualAllocation a b + + if (OAI.EditApproximation.naturalEqualWithWork a b).1 then 1 else queryNaturalIndexAllocation a rest + 1 + +def physicalNodeCode {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ := + OAI.EditApproximation.treeLayerCode M node.1.val node.2 + M ^ J * node.1.val + +def queryScaleDispatchWithWork (N b : ℕ) : ℕ × ℕ := + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let index := OAI.EditApproximation.queryNaturalIndexWithWork b scales.1 + (index.1, scales.2 + index.2 + scales.1.length + 2) + +def queryScaleDispatchAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.dyadicScalesAllocation N + OAI.EditApproximation.queryNaturalIndexAllocation b (OAI.EditApproximation.dyadicScalesWithWork N).1 + + (OAI.EditApproximation.dyadicScalesWithWork N).1.length + +def queryScalePresentWithWork (N b : ℕ) : Bool × ℕ := + let found := OAI.EditApproximation.queryScaleDispatchWithWork N b + let test := OAI.EditApproximation.binaryNaturalCompareWithWork found.1 (max 1 N.bits.length) + (decide (test.1 = .lt), found.2 + test.2 + 2) + +def queryScalePresentAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.queryScaleDispatchAllocation N b + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1.bits.length + (max 1 N.bits.length).bits.length + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +def physicalScaleIndex (N b : ℕ) (hb : b ∈ OAI.EditApproximation.dyadicScales N) : + Fin (OAI.EditApproximation.dyadicScales N).length := + ⟨(OAI.EditApproximation.dyadicScales N).idxOf b, List.idxOf_lt_length_of_mem hb⟩ + +abbrev PositiveDrawRange (B : ℕ) := {n : Fin (B + 1) // 0 < n.val} + +abbrev PhysicalLocalGroupKey (M J N n exponent : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × + Fin (n * 2 ^ exponent + 1) × Fin (n * 2 ^ exponent + 1) + +noncomputable def rejectionSuccessParameter (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : unitInterval := + ⟨(N : ℝ) / R, div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _), + (div_le_one₀ (by exact_mod_cast hN.trans_le hNR : (0 : ℝ) < R)).mpr (by exact_mod_cast hNR)⟩ + +def scheduledSeedFactor (N pass : ℕ) : ℚ := + (2 : ℚ) ^ OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass + +def scheduledSeedMultiplier (N pass : ℕ) : ℕ := + 2 ^ (OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N) + +instance computedBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0)⟩ + +instance computedCoarseBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).B := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +instance computedSourceTime_neZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +abbrev CommonRangeKey (ι : Type u_1) (B : ℕ) := ι × OAI.EditApproximation.PositiveDrawRange B + +def positiveDrawRangeOfLE (B n : ℕ) (hn : 0 < n) (hB : n ≤ B) : OAI.EditApproximation.PositiveDrawRange B := + ⟨⟨n, Nat.lt_succ_of_le hB⟩, hn⟩ + +instance positiveDrawRange_nezero {B : ℕ} (n : OAI.EditApproximation.PositiveDrawRange B) : NeZero n.val.val := + ⟨Nat.ne_of_gt n.property⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SignedBinary + + +def value (a : OAI.EditApproximation.SignedBinary) : ℤ := OAI.EditApproximation.signedMagnitude a.negative (OAI.EditApproximation.bitWordValue a.bits) + +def ofInt (a : ℤ) : OAI.EditApproximation.SignedBinary := ⟨decide (a < 0), a.natAbs.bits⟩ + +def neg (a : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary := ⟨!a.negative, a.bits⟩ + +def addWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + if a.negative = b.negative then + let total := OAI.EditApproximation.bitAddWithWork a.bits b.bits false + (⟨a.negative, total.1⟩, total.2 + 4) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + match comparison.1 with + | .eq => (⟨false, []⟩, comparison.2 + 4) + | .lt => + let difference := OAI.EditApproximation.bitSubtractWithWork b.bits a.bits false + (⟨b.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + | .gt => + let difference := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (⟨a.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + +def mulWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.bits b.bits + (⟨xor a.negative b.negative, product.1⟩, product.2 + 4) + +def nonzeroWithWork (bits : List Bool) : Bool × ℕ := + let comparison := OAI.EditApproximation.bitCompareWithWork bits [] + (if comparison.1 = .eq then false else true, comparison.2 + 1) + +def addAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := + if a.negative = b.negative then OAI.EditApproximation.bitAddAllocation a.bits b.bits false + else match (OAI.EditApproximation.bitCompareWithWork a.bits b.bits).1 with + | .eq => 0 + | .lt => OAI.EditApproximation.bitSubtractAllocation b.bits a.bits false + | .gt => OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def mulAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def ltWithWork (a b : OAI.EditApproximation.SignedBinary) : Bool × ℕ := + if a.negative then + if b.negative then + let comparison := OAI.EditApproximation.bitCompareWithWork b.bits a.bits + (comparison.1 == .lt, comparison.2 + 2) + else + let left := OAI.EditApproximation.SignedBinary.nonzeroWithWork a.bits + let right := OAI.EditApproximation.SignedBinary.nonzeroWithWork b.bits + (left.1 || right.1, left.2 + right.2 + 4) + else + if b.negative then (false, 2) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + (comparison.1 == .lt, comparison.2 + 2) + + +end OAI.EditApproximation.SignedBinary +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def value (a : OAI.EditApproximation.BinaryFraction) : ℚ := (a.numerator.value : ℚ) / OAI.EditApproximation.bitWordValue a.denominator + +def representation (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.UnreducedRational := + ⟨a.numerator.value, OAI.EditApproximation.bitWordValue a.denominator, a.denominator_pos⟩ + +def addWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let first := a.numerator.mulWithWork b.denominatorInteger + let second := b.numerator.mulWithWork a.denominatorInteger + let numerator := first.1.addWithWork second.1 + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + first.2 + second.2 + numerator.2 + denominator.2 + 8) + +def mulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let numerator := a.numerator.mulWithWork b.numerator + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + numerator.2 + denominator.2 + 4) + +def neg (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨a.numerator.neg, a.denominator, a.denominator_pos⟩ + +def ltWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.numerator.mulWithWork b.denominatorInteger + let right := b.numerator.mulWithWork a.denominatorInteger + let compared := left.1.ltWithWork right.1 + (compared.1, left.2 + right.2 + compared.2 + 4) + +def nat (n : ℕ) : OAI.EditApproximation.BinaryFraction := + ⟨OAI.EditApproximation.SignedBinary.ofInt n, [true], by decide⟩ + +def coarseGridAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := a.numerator.addWithWork b.numerator + let raw : OAI.EditApproximation.BinaryFraction := ⟨total.1, a.denominator, a.denominator_pos⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, total.2 + answer.2 + 3) + +def coarseReadShiftWithWork (k n : ℕ) (target : List ℕ) (letter : Option (Option ℕ)) + (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ × ℕ := + match letter with + | none => (0, 1) + | some letter => + let position := OAI.EditApproximation.binaryNaturalAddWithWork start shift.val + let actual := OAI.EditApproximation.coarseFramedReadWithWork k n target (OAI.EditApproximation.bitWordValue position.1) + let matched := OAI.EditApproximation.coarseLetterMatchWithWork actual.1 letter + (if matched.1 then 0 else 1, position.2 + actual.2 + matched.2 + 3) + +def addAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + + ((a.numerator.mulWithWork b.denominatorInteger).1.addAllocation + (b.numerator.mulWithWork a.denominatorInteger).1) + + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def mulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.numerator + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def ltAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + +def canonicalAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.addWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def canonicalMulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.mulWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def one : OAI.EditApproximation.BinaryFraction := OAI.EditApproximation.BinaryFraction.nat 1 + +def dyadicScanWithWork (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (candidate, 1) + | n + 1 => + let comparison := candidate.ltWithWork a + if comparison.1 then + let next := dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + (next.1, comparison.2 + next.2 + 2) + else (candidate, comparison.2 + 1) + +def maxWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then b else a, comparison.2 + 1) + +def leWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let result := b.ltWithWork a + (!result.1, result.2 + 1) + +def minWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then a else b, comparison.2 + 1) + +def queryScaleAt (words : List OAI.EditApproximation.BinaryFraction) (scales : List ℚ) + (h : words.map OAI.EditApproximation.BinaryFraction.value = scales) (i : Fin scales.length) : OAI.EditApproximation.BinaryFraction := + words[i.val]'(by have hl := congrArg List.length h; simp only [List.length_map] at hl; omega) + +def gatheredWordLookupWithWork {κ : Type u_1} (equal : κ → κ → Bool × ℕ) : + List κ → List OAI.EditApproximation.BinaryFraction → κ → OAI.EditApproximation.BinaryFraction × ℕ + | key :: keys, value :: values, query => + let test := equal query key + if test.1 then (value, test.2 + 1) + else + let rest := gatheredWordLookupWithWork equal keys values query + (rest.1, test.2 + rest.2 + 1) + | _, _, _ => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + +def coarseGridZipAddWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork a b + let tail := coarseGridZipAddWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryRead (array : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray) (i : ℕ) : OAI.EditApproximation.BinaryFraction := + match array with + | none => OAI.EditApproximation.BinaryFraction.nat 0 + | some cells => cells[i]?.getD (OAI.EditApproximation.BinaryFraction.nat 0) + +def canonicalAddAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.addAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.addWithWork b).1 + +def canonicalMulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.mulAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.mulWithWork b).1 + +def minAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def maxAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def leAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation b a + +def dyadicScanAllocation (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + OAI.EditApproximation.BinaryFraction.ltAllocation candidate a + if (candidate.ltWithWork a).1 then + dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + 1 else 0 + +def equalAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.ltAllocation b a + OAI.EditApproximation.BinaryFraction.ltAllocation a b + 0 + +def subWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork a b.neg + (result.1, result.2 + 1) + +def divWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let inverse := b.invWithWork + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a inverse.1 + (result.1, inverse.2 + result.2 + 1) + +def powWithWork (a : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.one, 1) + | k + 1 => + let previous := powWithWork a k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork previous.1 a + (result.1, previous.2 + result.2 + 1) + +def dotListWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.zero, 1) + | i :: rest => + let tail := dotListWithWork left right rest + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork product.1 tail.1 + (result.1, tail.2 + product.2 + result.2 + 5) + +def dyadicCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + (result.1, result.2 + 3 * a.width + 5) + +def maximumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := maximumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.maxWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def minimumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := minimumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.minWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def scaledCeilingWithWork (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork product.1 + (result.1, product.2 + result.2 + Nat.size multiplier + 3) + +def coarseContributionWithWork (threshold scale a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.BinaryFraction.leWithWork threshold a + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.maxWithWork a scale + (result.1, test.2 + result.2 + 2) + else + let result := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork a.denominator a.denominator_pos 0 + (result.1, test.2 + result.2 + 2) + +def coarseGridScanWithWork (two previous : OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([previous], 0) + | head :: rest => + let added := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork previous two + let next := OAI.EditApproximation.BinaryFraction.minWithWork head added.1 + let tail := coarseGridScanWithWork two next.1 rest + (previous :: tail.1, added.2 + next.2 + tail.2 + 3) + +def coarseGridZipMinimumWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.minWithWork a b + let tail := coarseGridZipMinimumWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryAddWithWork : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none, right => (right, 0) + | left, none => (left, 0) + | some left, some right => + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipAddWithWork left right + (some result.1, result.2) + +def divAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.invAllocation b + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation a b.invWithWork.1 + +def subAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.canonicalAddAllocation a b.neg + +def optimizerUpdateCellAllocation {d : ℕ} (step complement : OAI.EditApproximation.BinaryFraction) + (previous selected : Vector OAI.EditApproximation.BinaryFraction d) (i : Fin d) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation complement (previous.get i) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation step (selected.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement (previous.get i)).1 + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step (selected.get i)).1 + +def dyadicCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + a.width + 2 + +def roundedSpacingAllocation (theta envelope : OAI.EditApproximation.BinaryFraction) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta envelope + OAI.EditApproximation.BinaryFraction.maxAllocation OAI.EditApproximation.BinaryFraction.one product + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product).1 + +def scaledCeilingAllocation (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat multiplier) a + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a).1 + Nat.size multiplier + 1 + +def groupTermsAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.BinaryFraction.equalAllocation (envelope.get i) h + 2) indices + +def logarithmPartialWithWork (b : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.zero, 1) + | k + 1 => + let previous := logarithmPartialWithWork b k + let power := OAI.EditApproximation.BinaryFraction.powWithWork b (2 * k + 1) + let term := OAI.EditApproximation.BinaryFraction.divWithWork power.1 (OAI.EditApproximation.BinaryFraction.nat (2 * k + 1)) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork previous.1 term.1 + (result.1, previous.2 + power.2 + term.2 + result.2 + Nat.size (2 * k + 1) + 5) + +def dotWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotListWithWork left right (List.finRange d) + +def distanceWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let difference := a.subWithWork b + (difference.1.absolute, difference.2 + 1) + +def affineErrorWithWork (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : + Bool × ℕ := + let displacement := position.subWithWork offset + let product := velocity.canonicalMulWithWork prediction + let error := displacement.1.subWithWork product.1 + let comparison := error.1.absolute.leWithWork tolerance + (comparison.1, displacement.2 + product.2 + error.2 + comparison.2 + 4) + +def bandToleranceWithWork (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta + let scale := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat b) + let result := OAI.EditApproximation.BinaryFraction.divWithWork scale.1 (OAI.EditApproximation.BinaryFraction.nat M) + (result.1, product.2 + scale.2 + result.2 + Nat.size b + Nat.size M + 3) + +def medianSeedWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let rounded := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values + let sorted := OAI.EditApproximation.wordSortWithWork rounded.1 + let middle := sorted.1.getD (values.length / 2) [] + let clamped := OAI.EditApproximation.wordMinWithWork N.bits middle + (clamped.1, rounded.2 + sorted.2 + values.length + clamped.2 + Nat.size N + 3) + +def groupSampleCountWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let qm := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm.1 h + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 (OAI.EditApproximation.BinaryFraction.nat b) + let ceiling := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.wordMinWithWork M.bits ceiling.1 + (result.1, qm.2 + numerator.2 + ratio.2 + ceiling.2 + result.2 + + Nat.size M + Nat.size Q + Nat.size b + 5) + +def gainReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let word := read s i + let result := OAI.EditApproximation.BinaryFraction.divWithWork word.1.neg (mass i.1) + (result.1, word.2 + result.2 + 1) + +def decrementReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let first := read s i + let second := read (s + 1) i + let difference := OAI.EditApproximation.BinaryFraction.subWithWork first.1 second.1 + let result := OAI.EditApproximation.BinaryFraction.divWithWork difference.1 (mass i.1) + (result.1, first.2 + second.2 + difference.2 + result.2 + 1) + +def scaledSeedWithWork (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.BinaryFraction.maxWithWork (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded.1) gap.absolute + (result.1, ratio.2 + rounded.2 + result.2 + Nat.size U + 3) + +def initialScaleGuardWithWork (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let square := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square.1 + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat U) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, square.2 + denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size U + Nat.size b + 7) + +def initialCenterGuardWithWork (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat U) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat U) upper.1 + (low.1 && high.1, lower.2 + factor.2 + upper.2 + low.2 + high.2 + Nat.size b + Nat.size U + 5) + +def cellCoordinatesWithWork (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.saturatingSubtractWithWork p radius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork p radius + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower.1)) side + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper.1)) side + let first := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ.1 + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue first.1) + let values := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + (values, lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + stop.2 + count.2 + + values.length + Nat.size p + Nat.size radius + 9) + +def cellGridPointsWithWork (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : List ℕ × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork cell 1 + let lower := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next.1)) side + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat g) + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork upper.1 (OAI.EditApproximation.BinaryFraction.nat g) + let first := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ.1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last.1) (OAI.EditApproximation.bitWordValue first.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, next.2 + lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + count.2 + + points.2 + indices.length + Nat.size cell + Nat.size g + 10) + +def centerEligibilityWithWork (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 initial + let high := OAI.EditApproximation.BinaryFraction.leWithWork initial upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def refinementScaleGuardWithWork (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + let lower := OAI.EditApproximation.BinaryFraction.divWithWork w denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 w + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def coarseDivideWithWork (a divisor : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let quotient := OAI.EditApproximation.BinaryFraction.divWithWork a divisor + let result := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork quotient.1 a.denominator a.denominator_pos + (result.1, quotient.2 + result.2 + 2) + +def coarseGridLeftWithWork (two : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([], 0) + | head :: rest => OAI.EditApproximation.BinaryFraction.coarseGridScanWithWork two head rest + +def coarseMinimumWithWork : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + | a :: rest => OAI.EditApproximation.BinaryFraction.minimumWithWork a rest + +def powAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => powAllocation a n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.powWithWork a n).1 a + +def dotListAllocation {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → ℕ + | [] => 0 + | i :: rest => dotListAllocation left right rest + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (left.get i) (right.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i)).1 (OAI.EditApproximation.BinaryFraction.dotListWithWork left right rest).1 + +def minimumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => minimumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.minAllocation head (OAI.EditApproximation.BinaryFraction.minimumWithWork fallback rest).1 + +def maximumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => maximumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.maxAllocation head (OAI.EditApproximation.BinaryFraction.maximumWithWork fallback rest).1 + +def distanceAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.subAllocation a b + 0 + +def optimizerUpdateAllocation {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + let step := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2))).1 + let complement := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one step + + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.optimizerUpdateCellAllocation step complement previous selected) + + Nat.size (j + 2) + 1 + +def affineErrorAllocation (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : ℕ := + let displacement := (OAI.EditApproximation.BinaryFraction.subWithWork position offset).1 + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork velocity prediction).1 + OAI.EditApproximation.BinaryFraction.subAllocation position offset + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation velocity prediction + + OAI.EditApproximation.BinaryFraction.subAllocation displacement product + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.subWithWork displacement product).1.absolute tolerance + +def bandToleranceAllocation (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta).1 + let scale := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation tau theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation product (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.divAllocation scale (OAI.EditApproximation.BinaryFraction.nat M) + Nat.size b + Nat.size M + +def initialScaleGuardAllocation (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let square := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat U)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation A A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) square + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) denominator + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat U) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) upper + Nat.size U + Nat.size b + +def initialCenterGuardAllocation (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2)).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat U) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat U) upper + Nat.size b + Nat.size U + +def scaledSeedAllocation (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : ℕ := + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a).1 + let rounded := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) a + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.BinaryFraction.maxAllocation (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded) gap.absolute + Nat.size U + 2 + +def centerEligibilityAllocation (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) a + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1).1 initial + + OAI.EditApproximation.BinaryFraction.leAllocation initial (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b)).1 + Nat.size b + Nat.size F + +def refinementScaleGuardAllocation (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.divAllocation w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) a + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w).1 + Nat.size b + Nat.size F + +def cellCoordinatesAllocation (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : ℕ := + let lower := (OAI.EditApproximation.saturatingSubtractWithWork p radius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork p radius).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first)).1 + OAI.EditApproximation.saturatingSubtractAllocation p radius + OAI.EditApproximation.binaryNaturalAddAllocation p radius + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation lastQ + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue last) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first) + OAI.EditApproximation.bitWordValue count + + Nat.size p + Nat.size radius + +def cellGridPointsAllocation (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork cell 1).1 + let lower := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork lower (OAI.EditApproximation.BinaryFraction.nat g)).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork upper (OAI.EditApproximation.BinaryFraction.nat g)).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue first) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.binaryNaturalAddAllocation cell 1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell) side + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side + OAI.EditApproximation.BinaryFraction.divAllocation lower (OAI.EditApproximation.BinaryFraction.nat g) + OAI.EditApproximation.BinaryFraction.divAllocation upper (OAI.EditApproximation.BinaryFraction.nat g) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation lastQ + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first) + + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i + Nat.size i) indices + + indices.length + Nat.size cell + Nat.size g + +def medianSeedAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + let rounded := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values).1 + let sorted := (OAI.EditApproximation.wordSortWithWork rounded).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.scaledCeilingAllocation multiplier) values + OAI.EditApproximation.wordSortAllocation rounded + + OAI.EditApproximation.wordLEAllocation N.bits (sorted.getD (values.length / 2) []) + + Nat.size N + +def groupSampleCountAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let qm := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let numerator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm h).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation qm h + + OAI.EditApproximation.BinaryFraction.divAllocation numerator (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.wordLEAllocation M.bits (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + + Nat.size M + Nat.size Q + Nat.size b + +def refinementUpdateAllocation (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → ℕ + | none => 0 + | some online => + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork cone denominator).1 + let clipped := (OAI.EditApproximation.BinaryFraction.maxWithWork lower online).1 + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation OAI.EditApproximation.BinaryFraction.one delta + OAI.EditApproximation.BinaryFraction.divAllocation cone denominator + + OAI.EditApproximation.BinaryFraction.maxAllocation lower online + OAI.EditApproximation.BinaryFraction.minAllocation cone clipped + +def coefficientAllocation (kappa : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) kappa + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa).1 + 0 + +def gainReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + OAI.EditApproximation.BinaryFraction.divAllocation (read s i).1.neg (mass i.1) + 0 + +def decrementReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + footprint (s + 1) i + OAI.EditApproximation.BinaryFraction.subAllocation (read s i).1 (read (s + 1) i).1 + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + 0 + +def logarithmWithWork (r : OAI.EditApproximation.BinaryFraction) (k : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 denominator.1 + let subtotal := OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio.1 k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) subtotal.1 + (result.1, numerator.2 + denominator.2 + ratio.2 + subtotal.2 + result.2 + 5) + +def optimisticTermReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (coefficient : OAI.EditApproximation.BinaryFraction) + (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let gain := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i + let decrement := OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement.1 + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork gain.1 scaled.1 + (total.1, gain.2 + decrement.2 + scaled.2 + total.2 + 2) + +def queryExponentsWithWork (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let count := max 1 N.bits.length + let selected := OAI.EditApproximation.filterWithWork (fun e => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w + (guard.1, guard.2 + e + 2)) (List.range count) + (selected.1, selected.2 + count + N.bits.length + 2) + +def seedMedianWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let median := OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values + let trimmed := OAI.EditApproximation.trimBitWordWithWork median.1 + (trimmed.1, median.2 + trimmed.2 + 1) + +def coarseGridPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) (source : List OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source + let right := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source.reverse + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipMinimumWithWork left.1 right.1.reverse + (result.1, left.2 + right.2 + result.2 + 3 * source.length) + +def coarseChildThresholdWithWork (B q : ℕ) (allowance : OAI.EditApproximation.BinaryFraction) (draw : Fin B) : + OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork allowance (OAI.EditApproximation.BinaryFraction.nat (draw.val + 1)) + let divisor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat B) (OAI.EditApproximation.BinaryFraction.nat q) + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork numerator.1 divisor.1 + (result.1, numerator.2 + divisor.2 + result.2 + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 4) + +def coarseChildAllowanceWithWork (L : ℕ) (threshold : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork threshold (OAI.EditApproximation.BinaryFraction.nat L) + (result.1, result.2 + Nat.size L + 1) + +def logarithmPartialAllocation (b : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork b n).1 + let power := (OAI.EditApproximation.BinaryFraction.powWithWork b (2 * n + 1)).1 + let term := (OAI.EditApproximation.BinaryFraction.divWithWork power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1))).1 + logarithmPartialAllocation b n + OAI.EditApproximation.BinaryFraction.powAllocation b (2 * n + 1) + + OAI.EditApproximation.BinaryFraction.divAllocation power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1)) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation previous term + Nat.size (2 * n + 1) + 1 + +def bandMassAllocation {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) (List.finRange M) + 2 * M + +def sumListAllocation (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation (Vector.ofFn values.get) (Vector.replicate values.length OAI.EditApproximation.BinaryFraction.one) + (List.finRange values.length) + 3 * values.length + +def naturalDistanceLeAllocation (a b radius : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b)).1 (OAI.EditApproximation.BinaryFraction.nat radius) + + Nat.size a + Nat.size b + Nat.size radius + +def queryExponentsAllocation (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + let count := max 1 N.bits.length + OAI.EditApproximation.filterAllocation (fun e => ((OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).1, + (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2)) + (fun e => OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ e) a w + e + 1) (List.range count) + + count + N.bits.length + +def seedMedianAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.medianSeedAllocation N multiplier values + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values).1 + 0 + +def onlineMinimumAllocation : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | first :: rest => OAI.EditApproximation.BinaryFraction.minimumAllocation first rest + +def optimisticTermReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : OAI.EditApproximation.BinaryFraction) (s : ℕ) (i : β × σ) : ℕ := + let gain := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i).1 + let decrement := (OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i).1 + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint s i + OAI.EditApproximation.BinaryFraction.decrementReadAllocation mass read footprint s i + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient decrement + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation gain (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement).1 + 0 + +def gradientCellWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : OAI.EditApproximation.BinaryFraction × ℕ := + let smoothing := OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50 + let inverse := smoothing.1.invWithWork + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse.1 + let logarithm := OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted.1 (G ^ 60) + let deficit := OAI.EditApproximation.BinaryFraction.subWithWork logarithm.1.neg OAI.EditApproximation.BinaryFraction.one + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork deficit.1 (linear.get i) + (result.1, smoothing.2 + inverse.2 + shifted.2 + logarithm.2 + deficit.2 + result.2 + + Nat.size G + 70) + +def queryScalesWithWork (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let exponents := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let scales := OAI.EditApproximation.arithmeticMapWithWork (fun e => (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e), e + 3)) exponents.1 + (scales.1, exponents.2 + scales.2 + 1) + +def querySeedMedianWithWork (N multiplier : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.seedMedianWithWork N multiplier words + (OAI.EditApproximation.BinaryFraction.ofNaturalWord result.1, result.2 + result.1.length + 1) + +def coarseBinaryPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.BinaryFraction.coarseGridPenaltyWithWork two values + (some result.1, result.2) + +def logarithmAllocation (r : OAI.EditApproximation.BinaryFraction) (n : ℕ) : ℕ := + let numerator := (OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator denominator).1 + OAI.EditApproximation.BinaryFraction.subAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.divAllocation numerator denominator + + OAI.EditApproximation.BinaryFraction.logarithmPartialAllocation ratio n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio n).1 + +def queryScalesAllocation (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def coarseIndexChildren {B : ℕ} (k q L : ℕ) (two : OAI.EditApproximation.BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (allowance : OAI.EditApproximation.BinaryFraction) : + List (Fin B) → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | [], _ => (none, 0) + | i :: rest, start => + let threshold := OAI.EditApproximation.BinaryFraction.coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := OAI.EditApproximation.BinaryFraction.coarseBinaryPenaltyWithWork two evaluated.1 + let scale := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork q allowance + let contribution := OAI.EditApproximation.BinaryFraction.coarseBinaryMapWithWork (OAI.EditApproximation.BinaryFraction.coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren k q L two width evaluate draw allowance rest (start + width i) + let total := OAI.EditApproximation.BinaryFraction.coarseBinaryAddWithWork contribution.1 remainder.1 + (total.1, threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + total.2 + Nat.size start + Nat.size (width i) + 9) + +def gradientCellAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : ℕ := + let smoothing := (OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50).1 + let inverse := smoothing.invWithWork.1 + let shifted := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse).1 + let logarithm := (OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted (G ^ 60)).1 + let deficit := (OAI.EditApproximation.BinaryFraction.subWithWork logarithm.neg OAI.EditApproximation.BinaryFraction.one).1 + OAI.EditApproximation.BinaryFraction.powAllocation (OAI.EditApproximation.BinaryFraction.nat G) 50 + OAI.EditApproximation.BinaryFraction.invAllocation smoothing + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (point.get i) inverse + OAI.EditApproximation.BinaryFraction.logarithmAllocation shifted (G ^ 60) + + OAI.EditApproximation.BinaryFraction.subAllocation logarithm.neg OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation deficit (linear.get i) + Nat.size G + 1 + +def coarseIndexedWithWork {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : OAI.EditApproximation.BinaryFraction) : (d offset : ℕ) → OAI.EditApproximation.CoarseThresholdDraws B d → + OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | 0, offset, _, allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B 0 n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let letter := OAI.EditApproximation.coarsePaddedReadWithWork n source offset + let cells := OAI.EditApproximation.arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + let mismatch := OAI.EditApproximation.BinaryFraction.coarseReadShiftWithWork k n target letter.1 start shift + let value := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork allowance.denominator allowance.denominator_pos mismatch.1 + (value.1, value.2 + mismatch.2)) (List.finRange (2 * k + 1)) + (some cells.1, descriptor.2 + letter.2 + prune.2 + cells.2 + + Nat.size size + 3 * (2 * k + 1) + 1) + | d + 1, offset, (draws, below), allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B (d + 1) n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => + OAI.EditApproximation.coarseChildOffsetWithWork offset (OAI.EditApproximation.bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => + OAI.EditApproximation.coarseDescriptorWithWork B d n (OAI.EditApproximation.bitWordValue (childOffset i).1) + let result := OAI.EditApproximation.BinaryFraction.coarseIndexChildren k q L two + (fun i => OAI.EditApproximation.bitWordValue (childSize i).1) + (fun i a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (OAI.EditApproximation.bitWordValue (childOffset i).1) (below i) a s + let next := OAI.EditApproximation.binaryNaturalAddWithWork s (OAI.EditApproximation.bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3))) + draws allowance (List.finRange B) start + (result.1, descriptor.2 + capacity.2 + result.2 + prune.2 + Nat.size size + B + 1) + +def gradientAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.gradientCellAllocation G linear point) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def gradientWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + OAI.EditApproximation.vectorMapWithWork d (OAI.EditApproximation.BinaryFraction.gradientCellWithWork G linear point) + +def scoredArgmaxWithWork {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) : + List α → Option (α × OAI.EditApproximation.BinaryFraction) × ℕ + | [] => (none, 0) + | a :: rest => + let tail := scoredArgmaxWithWork score rest + let current := score a + match tail.1 with + | none => (some (a, current.1), tail.2 + current.2 + 1) + | some best => + let comparison := current.1.ltWithWork best.2 + (if comparison.1 then some best else some (a, current.1), + tail.2 + current.2 + comparison.2 + 2) + +def optimizerUpdateWithWork {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let step := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + let complement := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step.1 + let result := OAI.EditApproximation.vectorMapWithWork d fun i => + let first := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement.1 (previous.get i) + let second := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step.1 (selected.get i) + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4) + (result.1, step.2 + complement.2 + result.2 + Nat.size (j + 2) + 4) + +def bandMassTotalWithWork {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotWithWork mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) + +def coefficientWithWork (kappa : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa + let difference := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one scaled.1 + (difference.1, scaled.2 + difference.2 + 1) + +def naturalDistanceLeWithWork (a b radius : ℕ) : Bool × ℕ := + let distance := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + let result := distance.1.leWithWork (OAI.EditApproximation.BinaryFraction.nat radius) + (result.1, distance.2 + result.2 + Nat.size a + Nat.size b + Nat.size radius + 3) + +def onlineMinimumWithWork : List OAI.EditApproximation.BinaryFraction → Option OAI.EditApproximation.BinaryFraction × ℕ + | [] => (none, 1) + | first :: rest => + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork first rest + (some result.1, result.2 + 1) + +def refinementUpdateWithWork (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | none => (cone, 1) + | some online => + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta + let lower := OAI.EditApproximation.BinaryFraction.divWithWork cone denominator.1 + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork lower.1 online + let result := OAI.EditApproximation.BinaryFraction.minWithWork cone clipped.1 + (result.1, denominator.2 + lower.2 + clipped.2 + result.2 + 2) + +def equalWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.leWithWork b + let right := b.leWithWork a + (left.1 && right.1, left.2 + right.2 + 1) + +def roundedSpacingWithWork (theta envelope : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork clipped.1 + (rounded.1, product.2 + clipped.2 + rounded.2 + 2) + +def maximizerWithWork {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) vertices + ((selected.1.map Prod.fst).getD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), selected.2 + d + 1) + +def groupTermsWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : List OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.arithmeticMapWithWork (fun i => + let test := OAI.EditApproximation.BinaryFraction.equalWithWork (envelope.get i) h + (if test.1 then values.get i else OAI.EditApproximation.BinaryFraction.zero, test.2 + 2)) indices + +def selectGroupWithWork {ι : Type u_1} (members : List ι) (hne : members ≠ []) + (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) : ι × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun member => + let result := estimate member + (result.1.neg, result.2 + 1)) members + ((selected.1.map Prod.fst).getD (members.head hne), selected.2 + 1) + +def finiteOptimizerWithWork {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → Vector OAI.EditApproximation.BinaryFraction d × ℕ + | 0 => (vertices.headD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), d + 1) + | j + 1 => + let previous := finiteOptimizerWithWork vertices linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous.1 + let selected := OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient.1 vertices + let updated := OAI.EditApproximation.BinaryFraction.optimizerUpdateWithWork j previous.1 selected.1 + (updated.1, previous.2 + gradient.2 + selected.2 + updated.2 + 3) + +def selectionWithWork {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : + Option α × ℕ := + let iterate := OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate.1 + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient.1 vertex.2) vertices + (selected.1.map fun chosen => chosen.1.1, iterate.2 + gradient.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery + + +def value {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BitQuery ι β → β + | .done result => result + | .read key next => value oracle (next (oracle key)) + | .charge _ next => value oracle next + +def work {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) (readWork : ι → ℕ) : OAI.EditApproximation.BitQuery ι β → ℕ + | .done _ => 0 + | .read key next => readWork key + work oracle readWork (next (oracle key)) + | .charge steps next => steps + work oracle readWork next + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} : OAI.EditApproximation.BitQuery ι α → (α → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | .done result, next => next result + | .read key continuation, next => .read key (fun word => bind (continuation word) next) + | .charge steps continuation, next => .charge steps (bind continuation next) + +def compute {ι : Type u_1} {α : Type u_2} (execution : α × ℕ) : OAI.EditApproximation.BitQuery ι α := + .charge execution.2 (.done execution.1) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) : OAI.EditApproximation.BitQuery ι β → OAI.EditApproximation.BitQuery κ β + | .done result => .done result + | .read key next => .charge (f key).2 + (.read (f key).1 (fun word => mapKeysWithWork f (next word))) + | .charge steps next => .charge steps (mapKeysWithWork f next) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery {key // P key} OAI.EditApproximation.BinaryFraction + | .done result => .done result + | .charge steps next => .charge steps (restrictWithWork P test htest next) + | .read key next => .charge (test key).2 + (if h : (test key).1 = true then + .read ⟨key, (htest key).mp h⟩ (fun word => restrictWithWork P test htest (next word)) + else restrictWithWork P test htest (next (OAI.EditApproximation.BinaryFraction.nat 0))) + +def runMemo {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := runMemo ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests, + first.localWork + rest.localWork⟩ + | .charge steps next, memory => + let rest := runMemo ask next memory + {rest with localWork := steps + rest.localWork} + +inductive Footprint {ι : Type u_1} {β : Type u_2} : OAI.EditApproximation.BitQuery ι β → Type _ where + | done (value : β) : Footprint (.done value) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (continuation : ∀ word, Footprint (next word)) : Footprint (.read key next) + | charge {steps : ℕ} {next : OAI.EditApproximation.BitQuery ι β} (cells : ℕ) + (continuation : Footprint next) : Footprint (.charge steps next) + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + List κ → (List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | [], next => next [] + | key :: rest, next => (reader key).bind (fun word => + .charge 3 (collect reader rest (fun words => next (word :: words)))) + +def normalize {ι : Type u_1} (program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + program.bind fun word => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + + +end OAI.EditApproximation.BitQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion + +def substring {α : Type u} (word : List α) (lo hi : ℕ) : List α := + (word.take hi).drop lo + +structure TargetInterval (length : ℕ) where + lo : ℕ + hi : ℕ + ordered : lo ≤ hi + valid : hi ≤ length + +def occurrenceDeficit {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + word.length - if a ∈ word then 1 else 0 + +def natListMinimum (fallback : ℕ) : List ℕ → ℕ + | [] => fallback + | first :: rest => min first (natListMinimum fallback rest) + +def coarsePadTo {α : Type u} (n : ℕ) (word : List α) : List (Option α) := + word.map some ++ List.replicate (n - word.length) none + +def connectionBudget {n : ℕ} (start : ℕ) (states : List (OAI.EditApproximation.TargetInterval n)) + (finish : ℕ) : ℕ := + match states with + | [] => Nat.dist start finish + | state :: rest => Nat.dist start state.lo + connectionBudget state.hi rest finish + +def singletonCost {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + if word = [] then 1 else OAI.EditApproximation.occurrenceDeficit a word + +def makeTargetState (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) := + if h : lo ≤ hi ∧ hi ≤ n then some ⟨lo, hi, h.1, h.2⟩ else none + +def targetEndpointDistance {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.dist q.lo r.lo + Nat.dist q.hi r.hi + +def targetStates (n : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (List.range (n + 1)).flatMap fun lo => + (List.range (n + 1)).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def shortSourceCost {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + match source with + | [] => target.length + | a :: _ => OAI.EditApproximation.singletonCost a target + +def exactSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ + | [], target => List.ofFn fun j : Fin (target.length + 1) => target.length - j.val + | a :: rest, target => + let previous := exactSuffixDP rest target + List.ofFn fun j : Fin (target.length + 1) => + OAI.EditApproximation.natListMinimum (OAI.EditApproximation.singletonCost a [] + previous.getD j.val 0) + ((List.range (target.length - j.val + 1)).map fun k => + OAI.EditApproximation.singletonCost a ((target.drop j.val).take k) + previous.getD (j.val + k) 0) + +def exactSuffixAnswer {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + (OAI.EditApproximation.exactSuffixDP source target).getD 0 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def sourceChild {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (child : Fin M) : OAI.EditApproximation.TargetInterval n := by + have proof_balancedCut_monotone_7 (lo : ℕ) (width : ℕ) (M : ℕ) : Monotone (OAI.EditApproximation.balancedCut lo width M) := by + intro i j hij + exact Nat.add_le_add_left (Nat.div_le_div_right (Nat.mul_le_mul_right width hij)) lo + have proof_balancedCut_last_9 (lo : ℕ) (width : ℕ) (M : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.balancedCut lo width M M = lo + width := by + simp only [OAI.EditApproximation.balancedCut, Nat.mul_div_cancel_left _ hM] + have proof_balancedCut_bounds_8 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) (hi : LE.le.{0} i M) : + lo ≤ OAI.EditApproximation.balancedCut lo width M i ∧ OAI.EditApproximation.balancedCut lo width M i ≤ lo + width := by + constructor + · exact Nat.le_add_right _ _ + · rw [← proof_balancedCut_last_9 lo width M hM] + exact proof_balancedCut_monotone_7 lo width M hi + exact + { lo := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M child.val + hi := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M (child.val + 1) + ordered := proof_balancedCut_monotone_7 _ _ _ (Nat.le_succ _) + valid := by + have hM : 0 < M := Nat.zero_lt_of_lt child.isLt + have hbound := (proof_balancedCut_bounds_8 parent.lo (parent.hi - parent.lo) M (child.val + 1) + hM (by omega)).2 + rw [Nat.add_sub_of_le parent.ordered] at hbound + exact hbound.trans parent.valid } + +def roundInterval {n : ℕ} (spacing : ℕ) (state : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n := by + have proof_gridRound_mono_10 (spacing : ℕ) : Monotone (OAI.EditApproximation.gridRound spacing) := by + intro p q hpq + exact Nat.mul_le_mul_left spacing (Nat.div_le_div_right hpq) + have proof_gridRound_le_11 (spacing : ℕ) (position : ℕ) : OAI.EditApproximation.gridRound spacing position ≤ position := + Nat.mul_div_le _ _ + exact { + lo := OAI.EditApproximation.gridRound spacing state.lo + hi := OAI.EditApproximation.gridRound spacing state.hi + ordered := proof_gridRound_mono_10 spacing state.ordered + valid := (proof_gridRound_le_11 spacing state.hi).trans state.valid + } + +def localTargetStates (n g radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (q.lo - radius) (q.lo + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (q.hi - radius) (q.hi + radius)).filterMap fun hi => + OAI.EditApproximation.makeTargetState n lo hi + +def rationalStateGap {α : Type u_1} (source target : List α) (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + (q.hi : ℚ) - q.lo - source.length + +def gridStateBox (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (lo - radius) (lo + radius)).flatMap fun s => + (OAI.EditApproximation.gridPointsBetween g (hi - radius) (hi + radius)).filterMap fun t => + OAI.EditApproximation.makeTargetState n s t + +abbrev PhysicalEntry (M J ny : ℕ) := OAI.EditApproximation.PhysicalNode M J × OAI.EditApproximation.TargetInterval ny + +def makeStateWithWork (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let first := OAI.EditApproximation.wordLEWithWork lo.bits hi.bits + let second := OAI.EditApproximation.wordLEWithWork hi.bits n.bits + if h : (first.1 && second.1) = true then + (some ⟨lo, hi, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [first, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.1, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [second, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.2⟩, + first.2 + second.2 + 4) + else (none, first.2 + second.2 + 2) + +def cellTargetStates (n g : ℕ) (side : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellGridPoints side g cell.1).flatMap fun lo => + (OAI.EditApproximation.cellGridPoints side g cell.2).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def gridGapStates (n g anchor radius sourceLength gapRadius : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (anchor - radius) (anchor + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (lo + sourceLength - gapRadius) (lo + sourceLength + gapRadius)).filterMap + fun hi => OAI.EditApproximation.makeTargetState n lo hi + +abbrev PhysicalChildTables (M ny : ℕ) := Fin M → ℕ → OAI.EditApproximation.TargetInterval ny → ℚ + +abbrev PhysicalRationalAction (M ny : ℕ) := + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M + +def localTargetCells {n : ℕ} (side : ℚ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) := + (OAI.EditApproximation.localCellCoordinates side q.lo radius).flatMap fun lo => + (OAI.EditApproximation.localCellCoordinates side q.hi radius).map fun hi => (lo, hi) + +def coordinateEqualWithWork {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.naturalEqualWithWork a.1.val b.1.val + let lo := OAI.EditApproximation.naturalEqualWithWork a.2.lo b.2.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.2.hi b.2.hi + (child.1 && lo.1 && hi.1, child.2 + lo.2 + hi.2 + 2) + +def queryIntervalEqualWithWork {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let lo := OAI.EditApproximation.naturalEqualWithWork a.lo b.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.hi b.hi + (lo.1 && hi.1, lo.2 + hi.2 + 1) + +def childInputCode {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + input.1.val + M * (input.2.lo + (n + 1) * input.2.hi) + +def queryChildCodeWithWork {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let width := OAI.EditApproximation.binaryNaturalAddWithWork n 1 + let high := OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width.1) input.2.hi + let coordinate := OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high.1) + let scaled := OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate.1) + let result := OAI.EditApproximation.binaryNaturalAddWithWork input.1.val (OAI.EditApproximation.bitWordValue scaled.1) + (OAI.EditApproximation.bitWordValue result.1, width.2 + high.2 + coordinate.2 + scaled.2 + result.2 + 5) + +def querySliceHeadWithWork {α : Type u_1} (source : List α) + (interval : OAI.EditApproximation.TargetInterval source.length) : Option α × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork interval.lo interval.hi + (if test.1 = .lt then source[interval.lo]? else none, + test.2 + Nat.size interval.lo + Nat.size interval.hi + 3) + +def rankedBitProgramValue {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : OAI.EditApproximation.BinaryFraction := + (program key).value (fun child => rankedBitProgramValue rank program child.val) +termination_by rank key +decreasing_by exact child.property + +def scheduledRefinementWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + let e := OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - + OAI.EditApproximation.smallLogExponent N + let value := OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork (e : ℤ) + (value.1, value.2 + 5) + else (OAI.EditApproximation.BinaryFraction.nat 1, 3) + +def coordinateEqualAllocation {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.val b.1.val + OAI.EditApproximation.naturalEqualAllocation a.2.lo b.2.lo + + OAI.EditApproximation.naturalEqualAllocation a.2.hi b.2.hi + 2 + +def queryIntervalEqualAllocation {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.lo b.lo + OAI.EditApproximation.naturalEqualAllocation a.hi b.hi + 1 + +def sourceChildAllocation {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let next := (OAI.EditApproximation.binaryNaturalAddWithWork i.val 1).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + OAI.EditApproximation.binaryNaturalAddAllocation i.val 1 + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M i.val + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M (OAI.EditApproximation.bitWordValue next) + 2 + +def zeroConnectionAllocation {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → ℕ + | [], finish => OAI.EditApproximation.naturalEqualAllocation start finish + | state :: rest, finish => OAI.EditApproximation.naturalEqualAllocation start state.lo + + zeroConnectionAllocation state.hi rest finish + 1 + +def queryChildCodeAllocation {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + let width := (OAI.EditApproximation.binaryNaturalAddWithWork n 1).1 + let high := (OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width) input.2.hi).1 + let coordinate := (OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high)).1 + let scaled := (OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate)).1 + OAI.EditApproximation.binaryNaturalAddAllocation n 1 + OAI.EditApproximation.binaryNaturalMulAllocation (OAI.EditApproximation.bitWordValue width) input.2.hi + + OAI.EditApproximation.binaryNaturalAddAllocation input.2.lo (OAI.EditApproximation.bitWordValue high) + + OAI.EditApproximation.binaryNaturalMulAllocation M (OAI.EditApproximation.bitWordValue coordinate) + + OAI.EditApproximation.binaryNaturalAddAllocation input.1.val (OAI.EditApproximation.bitWordValue scaled) + +def roundStateAllocation {n : ℕ} (spacing : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.binaryGridRoundAllocation spacing q.lo + OAI.EditApproximation.binaryGridRoundAllocation spacing q.hi + 2 + +def actionEqualAllocation {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.allAllocation (fun i => OAI.EditApproximation.naturalEqualAllocation (a i).lo (b i).lo + + OAI.EditApproximation.naturalEqualAllocation (a i).hi (b i).hi) (List.finRange M) + +structure RawUnskippedBand (M ny : ℕ) where + center : OAI.EditApproximation.TargetInterval ny + actions : List (Fin M → OAI.EditApproximation.TargetInterval ny) + nonempty : actions ≠ [] + +def sourceIntervalAt (M n : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → OAI.EditApproximation.TargetInterval n + | 0, _ => ⟨0, n, Nat.zero_le _, le_rfl⟩ + | d + 1, node => OAI.EditApproximation.sourceChild (sourceIntervalAt M n d node.1) node.2 + +def initialConeValue {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (a L0 : ℚ) + (query center : OAI.EditApproximation.TargetInterval target.length) : ℚ := + OAI.EditApproximation.scaledSeedValue (U center) a (OAI.EditApproximation.rationalStateGap source target center) + + L0 * OAI.EditApproximation.targetEndpointDistance query center + +def wideChildStateList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.gridStateBox ny (OAI.EditApproximation.seedGridSpacing b P) (10 * b) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) + +def bandCutShift {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (j : Fin M) : ℚ := + (states j).lo - ((OAI.EditApproximation.sourceChild parent j).lo : ℚ) + +def localInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) + (U : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter (fun (b : ℕ) => decide + ((U q : ℚ) / (16 * A ^ 2) ≤ (b : ℚ) ∧ (b : ℚ) ≤ 4 * A * U q))).flatMap fun b => + (OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (U q) q).filter fun r => + decide ((b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b) + +def gridStateBoxWithWork (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let leftLow := OAI.EditApproximation.saturatingSubtractWithWork lo radius + let leftHigh := OAI.EditApproximation.binaryNaturalAddWithWork lo radius + let rightLow := OAI.EditApproximation.saturatingSubtractWithWork hi radius + let rightHigh := OAI.EditApproximation.binaryNaturalAddWithWork hi radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow.1) (OAI.EditApproximation.bitWordValue leftHigh.1) + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow.1) (OAI.EditApproximation.bitWordValue rightHigh.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right.1) left.1 + (states.1, leftLow.2 + leftHigh.2 + rightLow.2 + rightHigh.2 + left.2 + right.2 + states.2 + 6) + +def sourceChildWithWork {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_binaryNaturalSubtractWithWork_value_54 (a : ℕ) (b : ℕ) (h : LE.le.{0} b a) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork a b).1 = a - b := by + simpa only [OAI.EditApproximation.binaryNaturalSubtractWithWork, proof_bitWordValue_bits_15] using + proof_bitSubtractWithWork_sub_22 a.bits b.bits (by simpa only [proof_bitWordValue_bits_15] using h) + have proof_saturatingSubtractWithWork_value_50 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.saturatingSubtractWithWork a b).1 = a - b := by + unfold OAI.EditApproximation.saturatingSubtractWithWork + dsimp only + split_ifs with h + · have hlt := (proof_binaryNaturalCompareWithWork_lt_53 a b).mp h + simp only [OAI.EditApproximation.bitWordValue, Nat.sub_eq_zero_of_le hlt.le] + · exact proof_binaryNaturalSubtractWithWork_value_54 a b (le_of_not_gt (fun hab => + h ((proof_binaryNaturalCompareWithWork_lt_53 a b).mpr hab))) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_balancedCutWithWork_value_51 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.balancedCutWithWork lo width M i).1 = OAI.EditApproximation.balancedCut lo width M i := by + simp only [OAI.EditApproximation.balancedCutWithWork, proof_binaryNaturalAddWithWork_value_52, + (proof_binaryNaturalDivModWithWork_spec_24 _ M hM).1, proof_binaryNaturalMulWithWork_value_55, OAI.EditApproximation.balancedCut] + exact + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let next := OAI.EditApproximation.binaryNaturalAddWithWork i.val 1 + let left := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M i.val + let right := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M (OAI.EditApproximation.bitWordValue next.1) + let heql : OAI.EditApproximation.bitWordValue left.1 = (OAI.EditApproximation.sourceChild parent i).lo := by + simp only [left, width, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, OAI.EditApproximation.sourceChild] + let heqh : OAI.EditApproximation.bitWordValue right.1 = (OAI.EditApproximation.sourceChild parent i).hi := by + simp only [right, width, next, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.sourceChild] + (⟨OAI.EditApproximation.bitWordValue left.1, OAI.EditApproximation.bitWordValue right.1, + by rw [heql, heqh]; exact (OAI.EditApproximation.sourceChild parent i).ordered, + by rw [heqh]; exact (OAI.EditApproximation.sourceChild parent i).valid⟩, + width.2 + next.2 + left.2 + right.2 + 4) + +def cellRepresentativeStates (n P F b : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval n → ℚ) + (theta : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (theta * b) cell).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b) + +def groupRoundedStateList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent : ℕ) (cell : ℕ × ℕ) + (i : Fin M) (h : ℚ) : List (OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.gridGapStates target.length (OAI.EditApproximation.groupRoundSpacing exponent h) + (⌊(cell.1 : ℚ) * ((2 : ℚ) ^ (-(exponent : ℤ)) * b)⌋₊ + + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (12 * b) + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi).length ⌈2 * h⌉₊ + +def rawInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) (value : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + ((value : ℚ) / (16 * A ^ 2) ≤ b ∧ (b : ℚ) ≤ 4 * A * value)).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) value q + +def historyInputCode {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.pair input.2.1 (OAI.EditApproximation.childInputCode (input.1, input.2.2)) + +def localOnlineSourceKeys {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def queryHistoryCodeWithWork {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let child := OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2) + let pair := OAI.EditApproximation.queryPairWithWork input.2.1 child.1 + (pair.1, child.2 + pair.2 + 1) + +def queryOrderedChildInputsWithWork {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.coordinateEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) inputs + +def queryHistoryEqualWithWork {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.coordinateEqualWithWork (a.1, a.2.2) (b.1, b.2.2) + let time := OAI.EditApproximation.naturalEqualWithWork a.2.1 b.2.1 + (child.1 && time.1, child.2 + time.2 + 1) + +def queryGapStatesWithWork (n g anchor radius sourceLength gapRadius : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let lo := OAI.EditApproximation.saturatingSubtractWithWork anchor radius + let hi := OAI.EditApproximation.binaryNaturalAddWithWork anchor radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo.1) (OAI.EditApproximation.bitWordValue hi.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4)) left.1 + (states.1, lo.2 + hi.2 + left.2 + states.2 + 3) + +def queryOnlineKeyEqualWithWork {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1 b.1 + let state := OAI.EditApproximation.queryIntervalEqualWithWork a.2 b.2 + (scale.1 && state.1, scale.2 + state.2 + 1) + +def physicalEntryCode {M J n : ℕ} (state : OAI.EditApproximation.PhysicalEntry M J n) : ℕ := + OAI.EditApproximation.childInputCode ((0 : Fin 1), state.2) + (n + 1) ^ 2 * OAI.EditApproximation.physicalNodeCode state.1 + +def rankedBitLocalWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : ℕ := + (program key).work (fun child => OAI.EditApproximation.rankedBitProgramValue rank program child.val) (fun _ => 0) + +def refinementParameterWordsWithWork (N pass : ℕ) (word : List Bool) + (hpositive : 0 < OAI.EditApproximation.bitWordValue word) : OAI.EditApproximation.RefinementParameterWords × ℕ := + let online := OAI.EditApproximation.BinaryFraction.onlineParametersWithWork word hpositive + let factor := OAI.EditApproximation.scheduledRefinementWordWithWork N pass + let decrement := OAI.EditApproximation.BinaryFraction.refinementDecrementWithWork word hpositive + (⟨online.1.2, factor.1, online.1.1, online.1.2, decrement.1⟩, + online.2 + factor.2 + decrement.2 + 5) + +def queryHistoryEqualAllocation {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation (a.1, a.2.2) (b.1, b.2.2) + OAI.EditApproximation.naturalEqualAllocation a.2.1 b.2.1 + 1 + +def queryOnlineKeyEqualAllocation {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1 b.1 + OAI.EditApproximation.queryIntervalEqualAllocation a.2 b.2 + 1 + +def gridStateBoxAllocation (n g radius lo hi : ℕ) : ℕ := + let leftLow := (OAI.EditApproximation.saturatingSubtractWithWork lo radius).1 + let leftHigh := (OAI.EditApproximation.binaryNaturalAddWithWork lo radius).1 + let rightLow := (OAI.EditApproximation.saturatingSubtractWithWork hi radius).1 + let rightHigh := (OAI.EditApproximation.binaryNaturalAddWithWork hi radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh)).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh)).1 + OAI.EditApproximation.saturatingSubtractAllocation lo radius + OAI.EditApproximation.binaryNaturalAddAllocation lo radius + + OAI.EditApproximation.saturatingSubtractAllocation hi radius + OAI.EditApproximation.binaryNaturalAddAllocation hi radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh) + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh) + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right) + (fun s => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n s) (OAI.EditApproximation.makeStateAllocation n s) right) left + +def queryHistoryCodeAllocation {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryChildCodeAllocation (input.1, input.2.2) + + OAI.EditApproximation.queryPairAllocation input.2.1 (OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2)).1 + +def queryOrderedChildInputsAllocation {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.coordinateEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) + OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryChildCodeWithWork OAI.EditApproximation.queryChildCodeAllocation) inputs + +def actionMemberAllocation {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : List (Fin M → OAI.EditApproximation.TargetInterval n) → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.actionEqualAllocation a b + actionMemberAllocation a rest + +def queryGapStatesAllocation (n g anchor radius sourceLength gapRadius : ℕ) : ℕ := + let lo := (OAI.EditApproximation.saturatingSubtractWithWork anchor radius).1 + let hi := (OAI.EditApproximation.binaryNaturalAddWithWork anchor radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi)).1 + let build := fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4) + let allocation := fun first => + let center := (OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength).1 + let lower := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper)).1 + OAI.EditApproximation.binaryNaturalAddAllocation first sourceLength + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper) + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n first) (OAI.EditApproximation.makeStateAllocation n first) right + OAI.EditApproximation.saturatingSubtractAllocation anchor radius + OAI.EditApproximation.binaryNaturalAddAllocation anchor radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi) + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation left + +def wideActionList {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.finiteAssignments M (OAI.EditApproximation.wideChildStateList parent r b P) + +def physicalSourceInterval {M J : ℕ} (nx : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) : OAI.EditApproximation.TargetInterval nx := + OAI.EditApproximation.sourceIntervalAt M nx node.1.val node.2 + +def localInitialConeTable {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + if U q = 0 then 0 else + OAI.EditApproximation.rationalMinimum ((32 * F + 1) * N) + ((OAI.EditApproximation.localInitialConeCenters N P A U q).map + (OAI.EditApproximation.initialConeValue source target U a (32 * F) q)) + +def wideChildGridWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let child := OAI.EditApproximation.sourceChildWithWork parent i + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 10 b + let leftOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let rightOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi parent.lo + let left := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset.1) + let right := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset.1) + let grid := OAI.EditApproximation.gridStateBoxWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) + (OAI.EditApproximation.bitWordValue left.1) (OAI.EditApproximation.bitWordValue right.1) + (grid.1, child.2 + spacing.2 + radius.2 + leftOffset.2 + rightOffset.2 + left.2 + right.2 + grid.2 + 8) + +def queryOrderedHistoryInputsWithWork {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.queryHistoryEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) inputs + +def queryNeededInputsWithWork {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let first := OAI.EditApproximation.queryActionInputsWithWork selected + let second := OAI.EditApproximation.queryActionInputsWithWork online + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork (first.1 ++ second.1) + (sorted.1, first.2 + second.2 + first.1.length + sorted.2 + 2) + +def computedQueryParameters (N pass : ℕ) : OAI.EditApproximation.RefinementParameterWords := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computed_small_word_pos_125 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.inputSmallLog N).bits := by + rw [proof_bitWordValue_bits_15] + exact Nat.two_pow_pos _ + exact + (OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits (proof_computed_small_word_pos_125 N)).1 + +def wideChildGridAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : ℕ := + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 10 b).1 + let leftOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let rightOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.hi parent.lo).1 + let left := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset)).1 + let right := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset)).1 + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.binaryNaturalMulAllocation 10 b + + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + OAI.EditApproximation.saturatingSubtractAllocation child.hi parent.lo + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue leftOffset) + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue rightOffset) + + OAI.EditApproximation.gridStateBoxAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) + +def queryOrderedHistoryInputsAllocation {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.queryHistoryEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) + OAI.EditApproximation.queryHistoryEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryHistoryCodeWithWork OAI.EditApproximation.queryHistoryCodeAllocation) inputs + +def queryNeededInputsAllocation {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : ℕ := + let first := (OAI.EditApproximation.queryActionInputsWithWork selected).1 + let second := (OAI.EditApproximation.queryActionInputsWithWork online).1 + OAI.EditApproximation.queryActionInputsAllocation selected + OAI.EditApproximation.queryActionInputsAllocation online + first.length + + OAI.EditApproximation.queryOrderedChildInputsAllocation (first ++ second) + +def physicalSource {α : Type u_1} {M J : ℕ} (source : List α) (node : OAI.EditApproximation.PhysicalNode M J) : List α := + OAI.EditApproximation.substring source (OAI.EditApproximation.physicalSourceInterval source.length node).lo (OAI.EditApproximation.physicalSourceInterval source.length node).hi + +def wideActionGridWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Vector (OAI.EditApproximation.TargetInterval ny) M) × ℕ := + let choices := OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P) + let product := OAI.EditApproximation.materializedAssignmentsWithWork M choices.1.get + (product.1, choices.2 + product.2 + 1) + +def physicalCoarsePreparationCost {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + (OAI.EditApproximation.coarsePreparedSlicesWithWork source target interval.lo interval.hi entry.2.lo entry.2.hi).2 + +def wideActionGridAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : ℕ := + let choices := (OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P)).1 + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.wideChildGridAllocation parent r b P) + OAI.EditApproximation.materializedAssignmentsAllocation M choices.get + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def sumListWithWork (values : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork (Vector.ofFn values.get) + (result.1, result.2 + 6 * values.length) + +def connectionTermsWithWork {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [], finish => + let result := OAI.EditApproximation.BinaryFraction.distanceWithWork start finish + ([result.1], result.2 + 2) + | state :: rest, finish => + let current := OAI.EditApproximation.BinaryFraction.distanceWithWork start (OAI.EditApproximation.BinaryFraction.nat state.lo) + let tail := connectionTermsWithWork (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + (current.1 :: tail.1, + current.2 + tail.2 + Nat.size state.lo + Nat.size state.hi + 6) + +def bandEnvelopeReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (i : Fin M) : OAI.EditApproximation.BinaryFraction × ℕ := + let values := OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band + let floor := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + let maximum := OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values.1 + let input := OAI.EditApproximation.BinaryFraction.maxWithWork floor.1 maximum.1 + let result := OAI.EditApproximation.BinaryFraction.dyadicCeilingWithWork input.1 + (result.1, values.2 + floor.2 + maximum.2 + input.2 + result.2 + band.length + 4) + +def onlineLinearReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (eta kappa : OAI.EditApproximation.BinaryFraction) + (t : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let coefficient := OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa + let terms := OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient.1 s.val i + let history := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms.1 + let current := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history.1 current.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork eta total.1 + (result.1, coefficient.2 + terms.2 + history.2 + current.2 + total.2 + result.2 + 3) + +def targetCellsWithWork {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius + let right := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1 + (cells.1, left.2 + right.2 + cells.2 + 2) + +def cellStatesWithWork (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1 + let right := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2 + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right.1) left.1 + (states.1, left.2 + right.2 + states.2 + 2) + +def bandCoordinatesWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M)) band + let unique := OAI.EditApproximation.dedupByWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + 1) + +def countedBandCoordinateWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) + (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1) + let result := if test.1 then OAI.EditApproximation.BinaryFraction.divWithWork (mass.get coordinate.1) total else (OAI.EditApproximation.BinaryFraction.zero, 1) + (result.1, test.2 + result.2 + 1) + +def representativeScaleReadWithWork {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (radius : List Bool) + (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (guard.1, guard.2 + word.2)) points.1 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5) + +def queryRawCentersWithWork {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) scales.1 + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.queryIntervalEqualWithWork centers.1 + (unique.1, scales.2 + radius.2 + centers.2 + unique.2 + 3) + +def queryWideInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M)) representatives + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + M + 2) + +def queryRawHistoryInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2)) (List.finRange M)) representatives + (inputs.1, inputs.2 + M + 1) + +def queryGroupRoundedStatesWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h + let child := OAI.EditApproximation.sourceChildWithWork parent i + let offset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let base := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + let position := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base.1 (OAI.EditApproximation.BinaryFraction.nat b) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position.1 + let anchor := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor.1) (OAI.EditApproximation.bitWordValue offset.1) + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 12 b + let length := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi child.1.lo + let twice := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h + let gap := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice.1 + let states := OAI.EditApproximation.queryGapStatesWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue anchor.1) + (OAI.EditApproximation.bitWordValue radius.1) (OAI.EditApproximation.bitWordValue length.1) (OAI.EditApproximation.bitWordValue gap.1) + (states.1, spacing.2 + child.2 + offset.2 + base.2 + position.2 + floor.2 + anchor.2 + + radius.2 + length.2 + twice.2 + gap.2 + states.2 + exponent + 12) + +def queryOnlineIntegerReadWithWork {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + (OAI.EditApproximation.bitWordValue floor.1, word.2 + floor.2 + 1) + +def queryChildReadWithWork {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.coordinateEqualWithWork keys values (i, q) + +def queryHistoryReadWithWork {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryHistoryEqualWithWork keys values (input.1, s, input.2) + +def queryParentReadWithWork {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryIntervalEqualWithWork keys words r + +def initialGridReadWithWork {n : ℕ} (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) radius q.lo q.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue word.1) A + (guard.1, guard.2 + word.2)) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2) + +def queryInitialConeCentersWithWork {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius.1) b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) active.1 + (centers.1, radius.2 + scales.2 + active.2 + centers.2 + 2) + +def connectionTermsAllocation {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → ℕ + | [], finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start finish + 1 + | state :: rest, finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start (OAI.EditApproximation.BinaryFraction.nat state.lo) + + connectionTermsAllocation (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + Nat.size state.lo + Nat.size state.hi + 3 + +def endpointDistanceAllocation {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 + (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi)).1 + Nat.size q.lo + Nat.size q.hi + Nat.size r.lo + Nat.size r.hi + +def stateGapAllocation {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + +def queryChildReadAllocation {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation keys values (i, q) + +def queryHistoryReadAllocation {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryHistoryEqualWithWork OAI.EditApproximation.queryHistoryEqualAllocation keys values (input.1, s, input.2) + +def queryOnlineIntegerReadAllocation {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q)).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryOnlineKeyEqualWithWork OAI.EditApproximation.queryOnlineKeyEqualAllocation keys values (b, q) + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + +def bandCoordinatesAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let build := fun action : Fin M → OAI.EditApproximation.TargetInterval n => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M) + let raw := (OAI.EditApproximation.arithmeticFlatMapWithWork build band).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) band + + OAI.EditApproximation.dedupByAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation raw + +def scoredArgmaxAllocation {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => + scoredArgmaxAllocation score allocation rest + allocation a + + match (OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork score rest).1 with + | none => 1 + | some best => OAI.EditApproximation.BinaryFraction.ltAllocation (score a).1 best.2 + 1 + +def anchorGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) (i : Fin M) : ℕ := + let left := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo).1 + let right := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi).1 + let radius := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork 6 b).1 + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + OAI.EditApproximation.binaryNaturalMulAllocation 6 b + + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation left (states i).lo radius + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation right (states i).hi radius + +def bandEnvelopeReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (i : Fin M) : ℕ := + let values := (OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band).1 + let floor := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let maximum := (OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values).1 + OAI.EditApproximation.arithmeticMapAllocation (fun action => footprint i (action i)) band + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.maximumAllocation OAI.EditApproximation.BinaryFraction.zero values + OAI.EditApproximation.BinaryFraction.maxAllocation floor maximum + + OAI.EditApproximation.BinaryFraction.dyadicCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork floor maximum).1 + 0 + +def targetCellsAllocation {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius).1 + let right := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius).1 + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.lo radius + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.hi radius + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) right) left + +def cellStatesAllocation (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1).1 + let right := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2).1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.2 + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right) + (fun lo => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n lo) (OAI.EditApproximation.makeStateAllocation n lo) right) left + +def queryRawCentersAllocation {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let build := fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1) + let allocation := fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + let centers := (OAI.EditApproximation.arithmeticFlatMapWithWork build (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1).1 + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation centers + +def queryOnlineKeysAllocation {n : ℕ} (N P F : ℕ) (_hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.arithmeticMapAllocation (fun b => + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) q + 1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + +def representativeScaleReadAllocation {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (radius : List Bool) (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : ℕ := + let b := 2 ^ e + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).1, + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).2 + (read r).2) + let selected := (OAI.EditApproximation.filterWithWork test points).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + + OAI.EditApproximation.filterAllocation test (fun r => OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (read r).1 + allocation r) points + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) selected + e + 1 + +def queryWideInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let build := fun br : ℕ × OAI.EditApproximation.TargetInterval ny => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (one br) (List.finRange M)) representatives + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.arithmeticFlatMapWithWork build representatives).1 + M + +def queryRawHistoryInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let child := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + history + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun t => OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) + (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (List.range history) + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => OAI.EditApproximation.arithmeticFlatMapWithWork (child br) (List.finRange M)) + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (child br) (one br) (List.finRange M)) representatives + M + +def queryGroupRoundedStatesAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h).1 + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let offset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let base := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta).1 + let position := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base (OAI.EditApproximation.BinaryFraction.nat b)).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position).1 + let anchor := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset)).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 12 b).1 + let length := (OAI.EditApproximation.saturatingSubtractWithWork child.hi child.lo).1 + let twice := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h).1 + let gap := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice).1 + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation theta h + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation base (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation position + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset) + OAI.EditApproximation.binaryNaturalMulAllocation 12 b + + OAI.EditApproximation.saturatingSubtractAllocation child.hi child.lo + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) h + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation twice + + OAI.EditApproximation.queryGapStatesAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue anchor) (OAI.EditApproximation.bitWordValue radius) + (OAI.EditApproximation.bitWordValue length) (OAI.EditApproximation.bitWordValue gap) + exponent + 2 + +def groupIndexAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.BinaryFraction.groupTermsAllocation h envelope indices + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices).1 + 0 + +def queryParentReadAllocation {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation keys words r + +def onlineLinearReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (t : ℕ) (i : β × σ) : ℕ := + let coefficient := (OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa).1 + let terms := (OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient s.val i).1 + let history := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms).1 + let current := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i).1 + OAI.EditApproximation.BinaryFraction.coefficientAllocation kappa + + OAI.EditApproximation.vectorMapAllocation t (fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadAllocation mass read footprint coefficient s.val i) + + OAI.EditApproximation.BinaryFraction.bandMassAllocation terms + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint t i + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation history current + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation eta (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history current).1 + 0 + +def countedBandCoordinateAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation coordinate (coordinate.1, action coordinate.1) + + if (OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1)).1 then + OAI.EditApproximation.BinaryFraction.divAllocation (mass.get coordinate.1) total else 0 + +def queryInitialConeCentersAllocation {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1).1 + let build := fun b => + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi + (states.1, (OAI.EditApproximation.seedGridSpacingWithWork b P).2 + states.2 + 1) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) + (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi) active + +def connectionWithWork {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish + let result := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (result.1, terms.2 + result.2 + 1) + +def envelopeVectorReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector OAI.EditApproximation.BinaryFraction M × ℕ := + OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read) + +def bellmanActionReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M) + let dist := distance query action.center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist.1 + let connection := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial.1 action.connection + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + dist.2 + spatial.2 + connection.2 + children.2 + result.2 + 3) + +def cellCentersReadWithWork {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 cell + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := initial r + let tested := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (tested.1, word.2 + tested.2)) states.1 + (selected.1, spacing.2 + side.2 + states.2 + selected.2 + 3) + +def countedBandVerticesWithWork {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List ((Fin M → OAI.EditApproximation.TargetInterval n) × Vector OAI.EditApproximation.BinaryFraction d) × ℕ := + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass + let vertices := band.map fun action => + let vertex := OAI.EditApproximation.vectorMapWithWork d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateWithWork mass total.1 action (coordinates.get i) + ((action, vertex.1), vertex.2) + (vertices.map Prod.fst, total.2 + (vertices.map Prod.snd).sum + 8 * band.length) + +def onlineIndexSetupWithWork {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + ℕ × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + let sum := OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.1.length + let offset := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum.1) 2 + let power := OAI.EditApproximation.bitPowerWithWork offset.1 80 + (OAI.EditApproximation.bitWordValue offset.1, coordinates.2 + sum.2 + offset.2 + power.2 + 3) + +def localRepresentativeReadWithWork {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a queryWord.1 + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork queryWord.1 + let result := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read radius.1 query) scales.1 + (result.1, queryWord.2 + scales.2 + radius.2 + result.2 + 3) + +def queryGroupKeysWithWork {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + exponent + 4) + +def queryMeanWithWork (count : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words + let result := OAI.EditApproximation.BinaryFraction.divWithWork total.1 (OAI.EditApproximation.BinaryFraction.nat count) + (result.1, total.2 + result.2 + Nat.size count + 2) + +def initialCentersReadWithWork {n : ℕ} (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read q + let Uq := OAI.EditApproximation.bitWordValue queryWord.1 + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) active.1 + (centers.1, queryWord.2 + scales.2 + active.2 + centers.2 + 3) + +def queryInitialSeedReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : List Bool × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + (result.1, test.2 + result.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork found.1 + (result.1, test.2 + found.2 + result.2 + 1) + +def queryOverrideParentReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then (value, test.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + (found.1, test.2 + found.2 + 1) + +def connectionAllocation {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionTermsAllocation start states finish + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish).1 + 0 + +def coordinateVectorAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1.length + +def maximizerAllocation {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) + (fun v => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient v (List.finRange d)) vertices + d + +def onlineIndexSetupAllocation {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 + let sum := (OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.length).1 + let offset := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum) 2).1 + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + OAI.EditApproximation.binaryNaturalAddAllocation H coordinates.length + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue sum) 2 + OAI.EditApproximation.bitPowerAllocation offset 80 + +def envelopeVectorReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read footprint) + +def roundedBandReadAllocation {n M : ℕ} (exponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M fun i => + let envelope := (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i).1 + let spacing := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope).1 + OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read allocation i + + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope + + OAI.EditApproximation.roundStateAllocation spacing (band.head hne i) + exponent + 2 + +def queryGroupKeysAllocation {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2) + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun b => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + exponent + 2 + +def initialCellAllocation (n P exponent : ℕ) (key : ℕ × ℕ × ℕ) : ℕ := + OAI.EditApproximation.seedGridSpacingAllocation key.1 P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork key.1 P).1) + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1)).1 key.2 + exponent + 2 + +def localRepresentativeReadAllocation {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (query : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (read query).1 + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (read query).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.representativeScaleReadAllocation P F a read allocation (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (read query).1).1 + +def cellCentersReadAllocation {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (cell : ℕ × ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b)).1 + let states := (OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing) side cell).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).1, + (initial r).2 + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).2) + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue spacing) side cell + + OAI.EditApproximation.filterAllocation test (fun r => allocation r + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (initial r).1) states + +def selectGroupAllocation {ι : Type u_1} (members : List ι) (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : ι → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun member => ((estimate member).1.neg, (estimate member).2 + 1)) allocation members + +def bellmanActionReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M)).1 + let dist := (distance query action.center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist).1 + let connection := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial action.connection).1 + let children := (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint (action.childState i)) (List.finRange M) + + distanceAllocation query action.center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L dist + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation spatial action.connection + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection children + +def countedBandVerticesAllocation {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandMassAllocation mass + + (band.map fun action => OAI.EditApproximation.vectorMapAllocation d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateAllocation mass (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass).1 action (coordinates.get i)).sum + + 4 * band.length + +def queryInitialSeedReadAllocation {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r).1 + +def queryOverrideParentReadAllocation {n : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then 0 else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + +def prefixReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M) + let finish := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + let connection := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish.1 ((List.ofFn states).take j) + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 total.1 + (result.1, words.2 + finish.2 + connection.2 + total.2 + result.2 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 6 * M + 5) + +def bellmanReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L fallback : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback scores.1 + (result.1, scores.2 + result.2 + 1) + +def queryWarmupInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def endpointConnectionAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + Nat.size r.lo + Nat.size r.hi + M + +def prefixReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M)).1 + let finish := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i : Fin M => if i.val < j then allocation i (states i) else 0) + (List.finRange M) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j) + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j)).1 + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 2 * M + +def optimizerAllocation {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → ℕ + | 0 => d + | j + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork vertices linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous).1 + let selected := (OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient vertices).1 + optimizerAllocation vertices linear G j + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear previous + + OAI.EditApproximation.BinaryFraction.maximizerAllocation gradient vertices + OAI.EditApproximation.BinaryFraction.optimizerUpdateAllocation j previous selected + +def queryEarlierRepresentativesAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a (initial q).1 q).1 + let build := fun key : ℕ × ℕ × ℕ => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1) + allocation q + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a (initial q).1 q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun key => + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial allocation key.2 + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) + (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2).1) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q + + 2 * (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1.length + + (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1.length + +def queryWarmupInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1 + +def bellmanReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L fallback : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L read footprint query) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def prefixMinimumReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p + let scores := OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 1) + +def localContinuationReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let warm := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide + let cone := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm.1 current query groups + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online + let onlineMin := OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores.1 + let result := OAI.EditApproximation.BinaryFraction.refinementUpdateWithWork delta cone.1 onlineMin.1 + (result.1, warm.2 + cone.2 + scores.2 + onlineMin.2 + result.2 + 3) + +def prefixMinimumReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions).1 + OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r (actions.head hne) read allocation j p + + OAI.EditApproximation.arithmeticMapAllocation (fun action => OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r action read allocation j p) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def localContinuationReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L delta fallback : OAI.EditApproximation.BinaryFraction) (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Child → ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let warm := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide).1 + let cone := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm current query groups).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online).1 + let onlineMin := (OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores).1 + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L fallback old oldAllocation query wide + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L warm current currentAllocation query groups + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L current currentAllocation query) online + + OAI.EditApproximation.BinaryFraction.onlineMinimumAllocation scores + OAI.EditApproximation.BinaryFraction.refinementUpdateAllocation delta cone onlineMin + +def endpointActionAllocation {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation center states + M + 1 + +def selectionAllocation {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : ℕ := + let iterate := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate).1 + vertices.length + OAI.EditApproximation.BinaryFraction.optimizerAllocation (vertices.map Prod.snd) linear G j + + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear iterate + + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient vertex.2) + (fun vertex => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient vertex.2 (List.finRange d)) vertices + +def cutGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : Bool × ℕ := + if j.val = 0 then (true, 1) else + let shift := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + let offset := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + let prediction := OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift.1 + let result := OAI.EditApproximation.BinaryFraction.affineErrorWithWork shift.1 offset.1 velocity prediction.1 tolerance + (result.1, shift.2 + offset.2 + prediction.2 + result.2 + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + 5) + +def cutGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : ℕ := + if j.val = 0 then 0 else + let shift := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo)).1 + let offset := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo)).1 + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + + OAI.EditApproximation.BinaryFraction.prefixMinimumReadAllocation parent r actions hne read allocation j.val shift + + OAI.EditApproximation.BinaryFraction.affineErrorAllocation shift offset velocity + (OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift).1 tolerance + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + +def bandPredicateReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.zeroConnectionAllocation r.lo (List.ofFn states) r.hi + M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.anchorGuardAllocation parent r b states) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.bandToleranceAllocation tau theta b M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.cutGuardReadAllocation parent r actions hne read allocation states velocity + (OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M).1) (List.finRange M) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalConnectionBudget {n : ℕ} (start : ℚ) : List (OAI.EditApproximation.TargetInterval n) → ℚ → ℚ + | [], finish => |start - finish| + | state :: rest, finish => |start - state.lo| + rationalConnectionBudget state.hi rest finish + +def bandChildEnvelope {ny M : ℕ} (b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℚ := + OAI.EditApproximation.rationalDyadicCeiling (max ((b : ℚ) / M) + (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +def bandEnvelopeExponent {ny M : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℤ := + Int.clog 2 (max ((b : ℚ) / M) (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +deriving instance DecidableEq for OAI.EditApproximation.TargetInterval + +def zeroConnectionWithWork {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → Bool × ℕ + | [], finish => OAI.EditApproximation.naturalEqualWithWork start finish + | state :: rest, finish => + let current := OAI.EditApproximation.naturalEqualWithWork start state.lo + let tail := zeroConnectionWithWork state.hi rest finish + (current.1 && tail.1, current.2 + tail.2 + 1) + +def roundStateWithWork {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryGridRoundWithWork_value_25 (spacing : ℕ) (position : ℕ) (hspacing : LT.lt.{0} 0 spacing) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryGridRoundWithWork spacing position).1 = OAI.EditApproximation.gridRound spacing position := by + simp only [OAI.EditApproximation.binaryGridRoundWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15, + (proof_binaryNaturalDivModWithWork_spec_24 position spacing hspacing).1, OAI.EditApproximation.gridRound] + have proof_binaryIntervalRoundWithWork_value_14 {n : ℕ} (spacing : ℕ) (hspacing : LT.lt.{0} 0 spacing) (q : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.1, + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.2) = + ((OAI.EditApproximation.roundInterval spacing q).lo, (OAI.EditApproximation.roundInterval spacing q).hi) := by + simp only [OAI.EditApproximation.binaryIntervalRoundWithWork, proof_binaryGridRoundWithWork_value_25 _ _ hspacing, + OAI.EditApproximation.roundInterval] + exact + let output := OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi + let heq := proof_binaryIntervalRoundWithWork_value_14 spacing hspacing q + (⟨OAI.EditApproximation.bitWordValue output.1.1, OAI.EditApproximation.bitWordValue output.1.2, + by exact (congrArg Prod.fst heq).le.trans ((OAI.EditApproximation.roundInterval spacing q).ordered.trans + (congrArg Prod.snd heq).symm.le), + by exact (congrArg Prod.snd heq).le.trans (OAI.EditApproximation.roundInterval spacing q).valid⟩, output.2 + 1) + +def actionEqualWithWork {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + OAI.EditApproximation.allWithWork (fun i => + let left := OAI.EditApproximation.naturalEqualWithWork (a i).lo (b i).lo + let right := OAI.EditApproximation.naturalEqualWithWork (a i).hi (b i).hi + (left.1 && right.1, left.2 + right.2 + 1)) (List.finRange M) + +def localRefinementRepresentatives {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (initial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * initial q)).flatMap fun b => + ((OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈initial q⌉₊ q).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b)).map fun r => (b, r) + +def sharedBandRationalAction {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalRationalAction M ny := + ⟨center, 0, fun i => (i, states i)⟩ + +def localGroupQueryKeys {n : ℕ} (N F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells ((2 : ℚ) ^ (-(exponent : ℤ)) * b) ⌈initial q⌉₊ q).map fun cell => (b, cell) + +def rationalWidePrefixCost {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalConnectionBudget r.lo ((List.ofFn states).take j) + ((OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j : ℚ) + p) + + ∑ i, if i.val < j then child i (states i) else 0 + +def bandRoundSpacing {ny M : ℕ} (thetaExponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℕ := + 2 ^ (OAI.EditApproximation.bandEnvelopeExponent b band initial i - thetaExponent).toNat + +def actionMemberWithWork {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : + List (Fin M → OAI.EditApproximation.TargetInterval n) → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := OAI.EditApproximation.actionEqualWithWork a b + let tail := actionMemberWithWork a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +def wideEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + representatives.toFinset.biUnion fun br => + Finset.univ.biUnion fun i : Fin M => + (Finset.range history).biUnion fun t => + ((OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r) + +def queryEarlierRepresentatives {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + OAI.EditApproximation.localRefinementRepresentatives N P F a initial q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).flatMap (fun key => + (OAI.EditApproximation.cellRepresentativeStates n P F key.1 a initial ((2 : ℚ) ^ (-(exponent : ℤ))) key.2).map + fun r => (key.1, r)) ++ + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map + fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def rationalWidePrefixMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalWidePrefixCost parent r (actions.head hnonempty) child j p) + (actions.map fun action => OAI.EditApproximation.rationalWidePrefixCost parent r action child j p) + +def roundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (action : Fin M → OAI.EditApproximation.TargetInterval ny) : + Fin M → OAI.EditApproximation.TargetInterval ny := + fun i => OAI.EditApproximation.roundInterval (OAI.EditApproximation.bandRoundSpacing thetaExponent b band initial i) (action i) + +def queryEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideEarlierInputCover parent P history (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def canonicalRoundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : band ≠ []) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : Fin M → OAI.EditApproximation.TargetInterval ny := + OAI.EditApproximation.roundedBandAction thetaExponent b band initial (band.head hnonempty) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def parameterClogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork (n - 1) + (result.1, result.2 + 2) + +def parameterLogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork n + (result.1 - 1, result.2 + 1) + +def parameterRootSearch (n : ℕ) : ℕ → ℕ × ℕ + | 0 => (0, 1) + | k + 1 => if (k + 1) * (k + 1) ≤ n then (k + 1, 3) else + let result := parameterRootSearch n k + (result.1, result.2 + 3) + +def parameterPowerWithWork (a : ℕ) : ℕ → ℕ × ℕ + | 0 => (1, 1) + | k + 1 => let result := parameterPowerWithWork a k + (result.1 * a, result.2 + 2) + +def physicalCoarseInputStorage {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + OAI.EditApproximation.coarsePreparedInputStorage source target interval.lo interval.hi entry.2.lo entry.2.hi + +def computedQueryPassWithWork (N pass : ℕ) : (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.RefinementParameterWords) × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let seed := OAI.EditApproximation.scheduledSeedWordWithWork N pass + let parameters := OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits + (by rw [proof_bitWordValue_bits_15]; exact Nat.two_pow_pos _) + ((seed.1, parameters.1), seed.2 + parameters.2 + 2) + +def storedIntegerBits (values : List ℤ) : ℕ := + 1 + (values.map fun z => Nat.size z.natAbs + 2).sum + +def parameterSqrtWithWork (n : ℕ) : ℕ × ℕ := OAI.EditApproximation.parameterRootSearch n n + +def computedQuerySetupWithWork (N : ℕ) := + let parameters := OAI.EditApproximation.vectorMapWithWork (OAI.EditApproximation.computedSeedPassCount N + 1) + (fun i => OAI.EditApproximation.computedQueryPassWithWork N i.val) + let base := OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits + ((parameters.1, base.1), parameters.2 + base.2 + 5) + +def integerParametersWithWork (N : ℕ) : OAI.EditApproximation.IntegerParameters × ℕ := + let first := OAI.EditApproximation.parameterClogWithWork (N + 2) + let heightExponent := OAI.EditApproximation.parameterClogWithWork first.1 + let height := OAI.EditApproximation.parameterPowerWithWork 2 heightExponent.1 + let smallExponent := OAI.EditApproximation.parameterClogWithWork (max 1 heightExponent.1) + let small := OAI.EditApproximation.parameterPowerWithWork 2 smallExponent.1 + let logarithm := OAI.EditApproximation.parameterLogWithWork small.1 + let firstRoot := OAI.EditApproximation.parameterSqrtWithWork logarithm.1 + let secondRoot := OAI.EditApproximation.parameterSqrtWithWork firstRoot.1 + let branching := OAI.EditApproximation.parameterPowerWithWork 2 (heightExponent.1 / 20) + let coarseBranching := OAI.EditApproximation.parameterPowerWithWork height.1 secondRoot.1 + let factor := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 4) + let grid := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 20) + let rounds := OAI.EditApproximation.parameterPowerWithWork 2 ((3 * heightExponent.1 + 3) / 4) + let spacingDenominator := OAI.EditApproximation.parameterPowerWithWork small.1 2 + ({ H := height.1, ell := small.1, p := secondRoot.1, B := coarseBranching.1, + initialFactor := factor.1, M := branching.1, P := grid.1, + T := rounds.1, S := height.1 / spacingDenominator.1 }, + first.2 + heightExponent.2 + height.2 + smallExponent.2 + small.2 + logarithm.2 + + firstRoot.2 + secondRoot.2 + branching.2 + coarseBranching.2 + factor.2 + grid.2 + + rounds.2 + spacingDenominator.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +structure PhysicalTableRequest (M J ny : ℕ) where + pass : ℕ + copy : ℕ + node : OAI.EditApproximation.PhysicalNode M J + index : ℕ + state : OAI.EditApproximation.TargetInterval ny + +deriving DecidableEq + +def rawRefinementCenters {n : ℕ} (N P F : ℕ) (a value : ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicQueryWindow N value a F).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈value⌉₊ q).eraseDups + +def wideWarmupInputs {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) := + (representatives.flatMap fun br => (List.finRange M).flatMap fun i => + (OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).map fun r => (i, r)).eraseDups + +def queryMeanRead {ι : Type u_1} (count : ℕ) (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + .charge (count + 1) (OAI.EditApproximation.BitQuery.collect reader (List.ofFn fun i : Fin count => i) + (fun words => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words))) + +def physicalNodeCodeWithWork {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ × ℕ := + let path := OAI.EditApproximation.treeLayerCodeWithWork M node.1.val node.2 + let power := OAI.EditApproximation.parameterPowerWithWork M J + (path.1 + power.1 * node.1.val, path.2 + power.2 + 3) + +def rationalParametersWithWork (ell : ℕ) : OAI.EditApproximation.RationalParameters × ℕ := + let fourth := OAI.EditApproximation.parameterPowerWithWork ell 4 + let fifth := OAI.EditApproximation.parameterPowerWithWork ell 5 + let tenth := OAI.EditApproximation.parameterPowerWithWork ell 10 + let twentieth := OAI.EditApproximation.parameterPowerWithWork ell 20 + let fortieth := OAI.EditApproximation.parameterPowerWithWork ell 40 + ({ F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (tenth.1 : ℚ), kappa := 1 / (fourth.1 : ℚ), tau := 1 / (fourth.1 : ℚ), + theta := 1 / (fortieth.1 : ℚ), gamma := 1 / (twentieth.1 : ℚ), eta := fifth.1 }, + fourth.2 + fifth.2 + tenth.2 + twentieth.2 + fortieth.2 + 20) + +def onlineMassWithWork (M P H : ℕ) : ℕ × ℕ := + let width := 40 * P + 2 + let square := OAI.EditApproximation.parameterPowerWithWork width 2 + let dimension := H + M * square.1 + 2 + let rounds := OAI.EditApproximation.parameterPowerWithWork dimension 80 + (rounds.1 * (rounds.1 + 1) / 2, square.2 + rounds.2 + 9) + +def refinementInitialSupport {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + q :: (OAI.EditApproximation.rawRefinementCenters N P F a value q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a (fun _ => value) q).flatMap (fun key => + OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing key.1 P) + ((2 : ℚ) ^ (-(exponent : ℤ)) * key.1) key.2) ++ + (OAI.EditApproximation.dyadicQueryWindow N value a F).map (fun b => OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q)) + +def refinementBandInputList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideWarmupInputs parent P (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def previousPassRequest {M J ny : ℕ} (T S copy : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (state : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨parent.pass - 1, copy, parent.node, T + S, state⟩ + +def physicalEntryCodeWithWork {M J n : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J n) : ℕ × ℕ := + let node := OAI.EditApproximation.physicalNodeCodeWithWork entry.1 + let width := n + 1 + (entry.2.lo + width * entry.2.hi + width * width * node.1, node.2 + 8) + +def queryPhysicalBoundedWithWork {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : Bool × ℕ := + let pass := OAI.EditApproximation.binaryNaturalCompareWithWork request.pass passes + let copy := OAI.EditApproximation.binaryNaturalCompareWithWork request.copy copies + let cap := OAI.EditApproximation.binaryNaturalAddWithWork T S + let index := OAI.EditApproximation.wordLEWithWork request.index.bits cap.1 + (decide (pass.1 = .lt) && decide (copy.1 = .lt) && index.1, + pass.2 + copy.2 + cap.2 + index.2 + 4) + +def globalParameterWork (N : ℕ) : ℕ := + (OAI.EditApproximation.integerParametersWithWork N).2 + (OAI.EditApproximation.rationalParametersWithWork (OAI.EditApproximation.inputSmallLog N)).2 + + (OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)).2 + +def physicalLargeInputWithWork (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let inspected := OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon + if inspected.1.isSome = true then + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.inputSmallLog N)) epsilon + let accuracy := OAI.EditApproximation.BinaryFraction.ltWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat 10) + let threshold := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputSmallLog N) (2 ^ 1000) + let mass := OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + let width := OAI.EditApproximation.inputBitLengthWithWork mass.1 + let capacity := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputHeight N) width.1 + (decide (threshold.1 ≠ .lt ∧ accuracy.1 ≠ true ∧ capacity.1 ≠ .lt), + inspected.2 + product.2 + accuracy.2 + threshold.2 + mass.2 + width.2 + capacity.2 + 10) + else (false, inspected.2 + 1) + +def physicalTableCodeAllocation {M J n : ℕ} (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + 2 * request.node.1.val + 2 * J + 20 + +def queryPhysicalBoundedAllocation {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.pass.bits.length + passes.bits.length + request.copy.bits.length + copies.bits.length + + OAI.EditApproximation.binaryNaturalAddAllocation T S + OAI.EditApproximation.naturalWordLEAllocation request.index.bits (OAI.EditApproximation.binaryNaturalAddWithWork T S).1 + +def physicalTableCodeWithWork {M J n : ℕ} (copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ × ℕ := + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (request.node, request.state) + let power := OAI.EditApproximation.parameterPowerWithWork M J + let capacity := (n + 1) * (n + 1) * (power.1 * (J + 1)) + (request.index + (T + S + 1) * (request.copy + copies * (entry.1 + capacity * request.pass)), + entry.2 + power.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest +variable {M J ny : ℕ} + +def remainingDepth (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + J - request.node.1.val + +def rank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.pass * (T + S + 1) + request.index + +def Bounded (passes copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : Prop := + request.pass < passes ∧ request.copy < copies ∧ request.index ≤ T + S + +def warmup (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (j : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, j, state⟩ + +def refinement (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (T t : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, T + t, state⟩ + +def sameIndexChild (request : OAI.EditApproximation.PhysicalTableRequest M J ny) + (hbelow : request.node.1.val < J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + { request with node := OAI.EditApproximation.physicalChild request.node hbelow i, state := state } + +def combinedRank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.remainingDepth + request.rank T S + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalWarmupChildQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node (t + 1) q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) t input.2, + by simpa only [Nat.add_sub_cancel] using + proof_combinedRank_warmup_child_79 pass copy T S (t + 1) + node hbelow input.1 q input.2 (Nat.zero_lt_succ t)⟩ .done + +def physicalRefinementCurrentQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ .done + +def physicalRefinementEarlierQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + exact + if hs : input.2.1 < t then + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).2⟩)⟩ .done + else .done 0 + +def physicalRefinementWarmupRead {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval ny) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ .done + +def previousPassRead {M J ny : ℕ} (T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) + (state : OAI.EditApproximation.TargetInterval ny) (copy : ℕ) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨OAI.EditApproximation.previousPassRequest T S copy parent state, + proof_combinedRank_lt_of_progress_80 T S parent _ (Or.inr + ⟨(proof_previousPassRequest_progress_97 T S copy parent hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy parent hpass state).2⟩)⟩ .done + +abbrev ChargedPhysicalRequest (M J ny passes copies T S : ℕ) := + Sum (OAI.EditApproximation.PhysicalEntry M J ny) + {request : OAI.EditApproximation.PhysicalTableRequest M J ny // request.Bounded passes copies T S} + +def chargedPreviousPass {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S} := + ⟨OAI.EditApproximation.previousPassRequest T S copy.val parent.val state, + Nat.lt_of_le_of_lt (Nat.sub_le _ _) parent.property.1, copy.isLt, le_rfl⟩ + +def queryPhysicalTableRead {M J n : ℕ} (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) : + OAI.EditApproximation.BitQuery {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S} + OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalTableCodeWithWork copies T S child.val).2 + 1) (.read child .done) + +abbrev ComputedFamilyTableKey (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ChargedPhysicalRequest (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length + (OAI.EditApproximation.computedSeedPassCount N + 1) (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + +def chargedPhysicalCodeWithWork {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ × ℕ + | .inl entry => let result := OAI.EditApproximation.physicalEntryCodeWithWork entry + (2 * result.1, result.2 + 2) + | .inr request => let result := OAI.EditApproximation.physicalTableCodeWithWork copies T S request.val + (2 * result.1 + 1, result.2 + 3) + +def queryPhysicalWarmupRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval n) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ + +def queryPhysicalCurrentRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ + +def queryPhysicalEarlierRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).2 + 1) + (if hs : (OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).1 = .lt then + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).2⟩)⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + +def chargedPhysicalRemaining {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.remainingDepth + +def chargedPhysicalCodeAllocation {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl entry => 2 * entry.1.1.val + J + 12 + | .inr request => OAI.EditApproximation.physicalTableCodeAllocation request.val + 2 + +def queryPhysicalMassRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryMeanRead T (fun j => OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val j.isLt.le input.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def integerClosedRange (lo hi : ℤ) : List ℤ := + (List.range (hi - lo + 1).toNat).map fun i : ℕ => lo + (i : ℤ) + +def groupSampleCount (M Q b : ℕ) (h : ℚ) : ℕ := min M ⌈(Q : ℚ) * M * h / b⌉₊ + +def groupScaleTrueCost {M : ℕ} (h : ℚ) (envelope value : Fin M → ℚ) : ℚ := + ∑ i, if envelope i = h then value i else 0 + +def selectGroupMember {ι : Type u_1} (members : List ι) (hnonempty : members ≠ []) + (estimate : ι → ℚ) : ι := + (members.argmax fun member => -estimate member).getD (members.head hnonempty) + +instance coarseDrawsMeasurableSpace (B D : ℕ) [MeasurableSpace (Fin B)] : + MeasurableSpace (OAI.EditApproximation.CoarseThresholdDraws B D) := by + induction D with + | zero => exact inferInstanceAs (MeasurableSpace PUnit) + | succ D ih => + letI := ih + exact inferInstanceAs + (MeasurableSpace ((Fin B → Fin B) × (Fin B → OAI.EditApproximation.CoarseThresholdDraws B D))) + +def groupDyadicScales (M b : ℕ) (F : ℚ) : List ℚ := + (OAI.EditApproximation.integerClosedRange (Int.clog 2 ((b : ℚ) / M)) (Int.log 2 (64 * F * b))).map + fun exponent => (2 : ℚ) ^ exponent + +def groupScaleEstimate {M : ℕ} (k : ℕ) (h : ℚ) (envelope value : Fin M → ℚ) + (draw : Fin k → Fin M) : ℚ := + if k = M then OAI.EditApproximation.groupScaleTrueCost h envelope value + else (M : ℚ) / k * ∑ j, if envelope (draw j) = h then value (draw j) else 0 + +noncomputable def coarseDrawMeasure (B : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + (D : ℕ) → Measure (OAI.EditApproximation.CoarseThresholdDraws B D) + | 0 => Measure.dirac PUnit.unit + | D + 1 => + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).prod + (Measure.pi fun _ : Fin B => coarseDrawMeasure B D) + +def groupMemberEstimate {M T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (connection : ℚ) (envelope value : Fin M → ℚ) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + connection + ∑ scale, OAI.EditApproximation.groupScaleEstimate (count scale) (scales scale) envelope value (draw scale) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScalesWithWork (eM eb eF : ℕ) : List OAI.EditApproximation.BinaryFraction × ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + let values := OAI.EditApproximation.arithmeticMapWithWork OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork exponents + (values.1, values.2 + exponents.length + Nat.size eM + Nat.size eb + Nat.size eF + 8) + +def bandPredicateReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Bool × ℕ := + let connection := OAI.EditApproximation.zeroConnectionWithWork r.lo (List.ofFn states) r.hi + let anchors := OAI.EditApproximation.allWithWork (fun i : Fin M => + let leftAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + let rightAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 6 b + let left := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork leftAnchor.1 (states i).lo (OAI.EditApproximation.bitWordValue radius.1) + let right := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork rightAnchor.1 (states i).hi (OAI.EditApproximation.bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)) (List.finRange M) + let tolerance := OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M + let cuts := OAI.EditApproximation.allWithWork (OAI.EditApproximation.BinaryFraction.cutGuardReadWithWork parent r actions hne read states velocity tolerance.1) + (List.finRange M) + (connection.1 && anchors.1 && cuts.1, connection.2 + anchors.2 + tolerance.2 + cuts.2 + 4) + +def indexedGroupScales (raw : List OAI.EditApproximation.BinaryFraction) (M b : ℕ) (F : ℚ) + (h : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) : + Fin (OAI.EditApproximation.groupDyadicScales M b F).length → OAI.EditApproximation.BinaryFraction := + fun i => raw.get ⟨i.val, by + have hlen := congrArg List.length h + simp only [List.length_map] at hlen + omega⟩ + +def queryOnlineKeysWithWork {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let keys := OAI.EditApproximation.arithmeticMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) q + ((b, center.1), spacing.2 + center.2 + 2)) scales.1 + (keys.1, scales.2 + keys.2 + 1) + +def groupScalesAllocation (eM eb eF : ℕ) : ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + OAI.EditApproximation.arithmeticMapAllocation OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation exponents + exponents.length + + Nat.size eM + Nat.size eb + Nat.size eF + +def bandFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : + List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let margin := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau + let guard := OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin.1 + if guard.1 then + let filtered := OAI.EditApproximation.filterWithWork + (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) actions + (filtered.1, margin.2 + guard.2 + filtered.2 + 2) + else ([], margin.2 + guard.2 + 1) + +def queryInitialSupportWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q + let onlineStates := OAI.EditApproximation.arithmeticMapWithWork (fun key => (key.2, 1)) online.1 + (q :: (raw.1 ++ cells.1 ++ onlineStates.1), + raw.2 + groups.2 + cells.2 + online.2 + onlineStates.2 + 2 * raw.1.length + cells.1.length + 5) + +def queryEarlierRepresentativesWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let query := initial q + let reps := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a query.1 q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q + (reps.1 ++ cells.1 ++ online.1, + query.2 + reps.2 + groups.2 + cells.2 + online.2 + 2 * reps.1.length + cells.1.length + 4) + +def bandFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : ℕ := + let margin := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau).1 + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one tau + OAI.EditApproximation.BinaryFraction.leAllocation velocity.absolute margin + + if (OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin).1 then + OAI.EditApproximation.filterAllocation (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (OAI.EditApproximation.BinaryFraction.bandPredicateReadAllocation parent r b tau theta velocity actions hne read allocation) actions + else 0 + +def queryInitialSupportAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let raw := (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q).1 + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q).1 + let build := fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3) + let cells := (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1 + let online := (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q).1 + OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a value q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (OAI.EditApproximation.BinaryFraction.initialCellAllocation n P exponent) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a value q + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) online + + 2 * raw.length + cells.length + 1 + +def queryBandInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def queryEarlierInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let raw := OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history representatives.1 + let ordered := OAI.EditApproximation.queryOrderedHistoryInputsWithWork raw.1 + (ordered.1, representatives.2 + raw.2 + ordered.2 + 2) + +def queryEarlierInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + let reps := (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsAllocation M parent P history reps + + OAI.EditApproximation.queryOrderedHistoryInputsAllocation (OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history reps).1 + +def queryBandInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.FiniteQuery + + +def run {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) : + OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := run ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests⟩ + +def bind {ι : Type u_1} : OAI.EditApproximation.FiniteQuery ι → (ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | .done result, next => next result + | .read key continuation, next => .read key (fun result => bind (continuation result) next) + +def mapKeys {ι : Type u_1} {κ : Type u_2} (f : ι → κ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery κ + | .done result => .done result + | .read key next => .read (f key) (fun answer => mapKeys f (next answer)) + +def restrict {ι : Type u_1} (P : ι → Prop) [DecidablePred P] : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery {key // P key} + | .done result => .done result + | .read key next => if h : P key then + .read ⟨key, h⟩ (fun answer => restrict P (next answer)) + else restrict P (next 0) + +def requestWork {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) + (cost : ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ + | .done _, _ => 0 + | .read key next, memory => + let first := ask key memory + cost key memory + requestWork ask cost (next first.value) first.memory + +def collect {ι : Type u_1} {κ : Type u_2} (reader : κ → OAI.EditApproximation.FiniteQuery ι) : + List κ → (List ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | [], next => next [] + | key :: keys, next => OAI.EditApproximation.FiniteQuery.bind (reader key) fun result => + collect reader keys (fun results => next (result :: results)) + + +end OAI.EditApproximation.FiniteQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalInitialQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (state : OAI.EditApproximation.PhysicalEntry M J target.length) : OAI.EditApproximation.FiniteQuery ι := + let piece := OAI.EditApproximation.physicalSource source state.1 + if piece.length ≤ 1 then .done (OAI.EditApproximation.shortSourceCost piece (OAI.EditApproximation.substring target state.2.lo state.2.hi)) + else OAI.EditApproximation.FiniteQuery.bind (seedRead state) fun answer => + let value := ⌈answer⌉₊ + let keys := OAI.EditApproximation.rawInitialConeCenters N P A value state.2 + OAI.EditApproximation.FiniteQuery.collect (fun q => seedRead (state.1, q)) keys fun answers => + let localTable := fun q => if q = state.2 then value + else ⌈OAI.EditApproximation.finiteAnswerTable keys answers q⌉₊ + .done (OAI.EditApproximation.localInitialConeTable piece target localTable N P F A (OAI.EditApproximation.refinementFactor A F) state.2) + +def queryInitialGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.TargetInterval n) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys) + +def queryBandGather {ι : Type u_1} {β : Type u_2} {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : (Fin M × OAI.EditApproximation.TargetInterval ny) → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → + OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect massReader keys fun mass => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass) + +def physicalRefinementMassQuery {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun j : Fin T => OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val (Nat.le_of_lt j.isLt) input.2) (List.ofFn fun j : Fin T => j) + (fun values => .done (values.sum / T)) + +def physicalMedianSeedQuery {M J ny : ℕ} (N T S copies multiplier : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun copy : Fin copies => OAI.EditApproximation.previousPassRead T S parent hpass state copy.val) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => ⌈(multiplier : ℚ) * value⌉₊)) : ℕ) + +def globalSeedRead {M J ny : ℕ} (N T S copies : ℕ) (multiplier : ℕ → ℕ) + (initial : OAI.EditApproximation.PhysicalEntry M J ny → ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + if state.1 = parent.node then + if hp : parent.pass = 0 then .done (initial state : ℚ) + else OAI.EditApproximation.physicalMedianSeedQuery N T S copies (multiplier (parent.pass - 1)) parent + (Nat.pos_of_ne_zero hp) state.2 + else .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational + + +def value (a : OAI.EditApproximation.UnreducedRational) : ℚ := (a.num : ℚ) / a.den + +def zero : OAI.EditApproximation.UnreducedRational := ⟨0, 1, by decide⟩ + +def mul (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + ⟨a.num * b.num, a.den * b.den, Nat.mul_pos a.den_pos b.den_pos⟩ + +def lt (a b : OAI.EditApproximation.UnreducedRational) : Bool := decide (a.num * b.den < b.num * a.den) + +def inv (a : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + if h : a.num = 0 then OAI.EditApproximation.UnreducedRational.zero else + ⟨a.num.sign * a.den, a.num.natAbs, Int.natAbs_pos.mpr h⟩ + +def div (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := a.mul b.inv + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +inductive CoarseSourceTree (B : ℕ) (α : Type u) : ℕ → Type u + | leaf (letter : Option α) : CoarseSourceTree B α 0 + | branch {D : ℕ} (children : Fin B → CoarseSourceTree B α D) : CoarseSourceTree B α (D + 1) + +def coarseTargetFrame {α : Type u} (k : ℕ) (target : List α) : List (Option α) := + (List.replicate k none ++ target.map some) ++ List.replicate k none + +def coarseRootShift (k : ℕ) : Fin (2 * k + 1) := ⟨k, by omega⟩ + +def endpointActionConnection {n M : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.connectionBudget q.lo (List.ofFn states) q.hi + +def coarseSourceTreeOfList (B : ℕ) {α : Type u} : + (D : ℕ) → List α → OAI.EditApproximation.CoarseSourceTree B α D + | 0, source => .leaf source.head? + | D + 1, source => .branch (fun i => + coarseSourceTreeOfList B D ((source.drop (i.val * B ^ D)).take (B ^ D))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def groupIndexWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (total.1, terms.2 + total.2 + 1) + +def endpointDistanceWithWork {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let right := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork left.1 right.1 + (result.1, left.2 + right.2 + result.2 + Nat.size q.lo + Nat.size q.hi + + Nat.size r.lo + Nat.size r.hi + 3) + +def endpointConnectionWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + (result.1, result.2 + Nat.size r.lo + Nat.size r.hi + M + 2) + +def stateGapWithWork {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let targetLength := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let result := OAI.EditApproximation.BinaryFraction.subWithWork targetLength.1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + (result.1, targetLength.2 + result.2 + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScaleSourceWithWork {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let subtotal := OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1 + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 subtotal.1 + (result.1, indices.2 + subtotal.2 + factor.2 + result.2 + Nat.size M + Nat.size k + 3) + +def endpointScoreReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + connection.2 + children.2 + result.2 + 2) + +def initialConeWithWork {n : ℕ} (sourceLength : ℕ) (U : OAI.EditApproximation.TargetInterval n → ℕ) + (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center + let seed := OAI.EditApproximation.BinaryFraction.scaledSeedWithWork (U center) a gap.1 + let distance := OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork seed.1 spatial.1 + (result.1, gap.2 + seed.2 + distance.2 + spatial.2 + result.2 + 4) + +def endpointActionWithWork {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork center states + (⟨center, connection.1, fun i => (i, states i)⟩, connection.2 + M + 1) + +def endpointScoreReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint i (states i)) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation r states + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states).1 (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + 0 + +def initialConeAllocation {n : ℕ} (sourceLength U : ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center).1 + let seed := (OAI.EditApproximation.BinaryFraction.scaledSeedWithWork U a gap).1 + let distance := (OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance).1 + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength center + OAI.EditApproximation.BinaryFraction.scaledSeedAllocation U a gap + + OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation query center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L distance + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation seed spatial + +def groupScaleSourceAllocation {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) + (allocation : Fin k → ℕ) : ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + (if k = M then 0 else OAI.EditApproximation.arithmeticMapAllocation allocation (List.finRange k)) + + OAI.EditApproximation.BinaryFraction.groupIndexAllocation h envelope values indices.1 + + (if k = M then 0 else OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k)) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor.1 (OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1).1 + + Nat.size M + Nat.size k + +def gapGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (envelope : Vector OAI.EditApproximation.BinaryFraction M) (rounded : Vector (OAI.EditApproximation.TargetInterval ny) M) (i : Fin M) : ℕ := + let sourceLength := (OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo).1 + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i)).1 + let bound := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i)).1 + OAI.EditApproximation.bitSubtractAllocation (OAI.EditApproximation.sourceChild parent i).hi.bits (OAI.EditApproximation.sourceChild parent i).lo.bits false + + OAI.EditApproximation.BinaryFraction.stateGapAllocation (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i) + OAI.EditApproximation.BinaryFraction.leAllocation gap.absolute bound + +def wideMinimumReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 2) + +def groupMemberSourceWithWork {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) + let subtotal := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection subtotal.1 + (result.1, terms.2 + subtotal.2 + result.2 + 1) + +def wideActionsFromRepresentativesWithWork {nx ny : ℕ} (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) × ℕ := + OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) representatives + +def initialConeReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let seed := read center + let result := OAI.EditApproximation.BinaryFraction.initialConeWithWork sourceLength (fun _ => OAI.EditApproximation.bitWordValue seed.1) a L query center + (result.1, seed.2 + result.2) + +def wideMinimumReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions).1 + OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint (actions.head hne) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + 0 + +def groupMemberSourceAllocation {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) + (allocation : ∀ s : Fin T, Fin (count s) → ℕ) : ℕ := + let terms := (OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceAllocation (count s) (scales s) envelope values (draw s) (allocation s)) (List.finRange T) + + OAI.EditApproximation.BinaryFraction.sumListAllocation terms + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection (OAI.EditApproximation.BinaryFraction.sumListWithWork terms).1 + +def wideActionsFromRepresentativesAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) + (fun br => OAI.EditApproximation.wideActionGridAllocation M parent br.2 br.1 P + + OAI.EditApproximation.arithmeticMapAllocation (fun states => OAI.EditApproximation.BinaryFraction.endpointActionAllocation br.2 states.get) + (OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P).1) representatives + +def representativeFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + if hne : actions = [] then ([], 1) else + let Z := OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne + let positive := OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z.1 + if positive.1 then + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r + let velocity := OAI.EditApproximation.BinaryFraction.divWithWork gap.1 Z.1 + let result := OAI.EditApproximation.BinaryFraction.bandFromActionsReadWithWork parent r b tau theta velocity.1 read actions hne + (result.1, Z.2 + positive.2 + gap.2 + velocity.2 + result.2 + 3) + else ([], Z.2 + positive.2 + 2) + +def physicalContinuationReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) + (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.BinaryFraction × ℕ := + let wide := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.localContinuationReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 delta fallback + old current query wide.1 groups online + (result.1, wide.2 + L.2 + result.2 + 1) + +def initialMinimumReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let queryWord := read query + let zeroTest := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue queryWord.1) 0 + if zeroTest.1 then (OAI.EditApproximation.BinaryFraction.zero, queryWord.2 + zeroTest.2 + 1) else + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + let coefficient := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L.1 OAI.EditApproximation.BinaryFraction.one + let fallback := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient.1 (OAI.EditApproximation.BinaryFraction.nat N) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L.1 query) centers + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, queryWord.2 + zeroTest.2 + L.2 + coefficient.2 + fallback.2 + scores.2 + result.2 + + Nat.size F + Nat.size N + 6) + +def localWarmupReadKernelWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let actions := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives.1 P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 fallback.1 child query actions.1 + (result.1, fallback.2 + representatives.2 + actions.2 + L.2 + result.2 + 3) + +def representativeFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : ℕ := + if hne : actions = [] then 0 else + let Z := (OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne).1 + OAI.EditApproximation.BinaryFraction.wideMinimumReadAllocation r read allocation actions hne + OAI.EditApproximation.BinaryFraction.ltAllocation OAI.EditApproximation.BinaryFraction.zero Z + + if (OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z).1 then + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength r + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z + + OAI.EditApproximation.BinaryFraction.bandFromActionsReadAllocation parent r b tau theta + (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z).1 read allocation actions hne + else 0 + +def physicalContinuationReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.localContinuationReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 delta fallback old current oldAllocation currentAllocation query + (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online + +def localWarmupReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + let representatives := (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 + let actions := (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 (initial query).1 child childAllocation query actions + +def preparedRepresentativeReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let result := OAI.EditApproximation.BinaryFraction.representativeFromActionsReadWithWork parent center sourceLength b tau theta read + (wide.1.map Vector.get) + (result.1, wide.2 + result.2 + wide.1.length + 1) + +def initialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let centers := OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query + let result := OAI.EditApproximation.BinaryFraction.initialMinimumReadWithWork sourceLength read N F a query centers.1 + (result.1, centers.2 + result.2 + 1) + +def preparedRepresentativeReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.representativeFromActionsReadAllocation parent center sourceLength b tau theta read allocation (wide.map Vector.get) + +def queryRefinementFinishAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (N P F : ℕ) + (a delta : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (t : ℕ) + (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny)) (earlierWords : List OAI.EditApproximation.BinaryFraction) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) (currentWords : List OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.physicalContinuationReadAllocation parent (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 P F delta (initial query).1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadAllocation currentKeys currentWords input.1 input.2) groups online query + +def queryOnlineRangeWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ × ℕ := + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width.1) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let power := OAI.EditApproximation.bitPowerWithWork setup.1.bits 80 + let mass := OAI.EditApproximation.triangularMassWithWork (OAI.EditApproximation.bitWordValue power.1) + (OAI.EditApproximation.bitWordValue mass.1, width.2 + band.2 + setup.2 + power.2 + mass.2 + 4) + +def cachedInitialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedWithWork (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + [true] (by decide) 0 + +def queryOnlineRangeAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let setup := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let power := (OAI.EditApproximation.bitPowerWithWork setup.bits 80).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child allocation + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + + OAI.EditApproximation.bitPowerAllocation setup.bits 80 + OAI.EditApproximation.triangularMassAllocation (OAI.EditApproximation.bitWordValue power) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PositionCounts + + +def count : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n _ _ => n + +def left : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ _ r => r + +def storageBits : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n l r => Nat.size n + 3 + l.storageBits + r.storageBits + +def add (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts + | 0, _ => .node (tree.count + 1) tree.left tree.right + | d + 1, i => + if i < 2 ^ d then + .node (tree.count + 1) (tree.left.add d i) tree.right + else .node (tree.count + 1) tree.left (tree.right.add d (i - 2 ^ d)) + +def addWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts × ℕ + | 0, _ => (.node (tree.count + 1) tree.left tree.right, 1) + | d + 1, i => + if i < 2 ^ d then + let result := tree.left.addWithWork d i + (.node (tree.count + 1) result.1 tree.right, result.2 + 2) + else + let result := tree.right.addWithWork d (i - 2 ^ d) + (.node (tree.count + 1) tree.left result.1, result.2 + 2) + +def prefixWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → ℕ × ℕ + | 0, t => (if t = 0 then 0 else tree.count, 1) + | d + 1, t => + if t ≤ 2 ^ d then + let result := tree.left.prefixWithWork d t + (result.1, result.2 + 2) + else + let result := tree.right.prefixWithWork d (t - 2 ^ d) + (tree.left.count + result.1, result.2 + 2) + + +end OAI.EditApproximation.PositionCounts +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} {program : OAI.EditApproximation.BitQuery ι α} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (next : α → OAI.EditApproximation.BitQuery ι β) (allocation : ∀ value, OAI.EditApproximation.BitQuery.Footprint (next value)) : + OAI.EditApproximation.BitQuery.Footprint (program.bind next) := + match heap with + | .done result => allocation result + | .read key continuation stored => .read key _ (fun word => (stored word).bind next allocation) + | .charge localCells tail => .charge localCells (tail.bind next allocation) + +def compute {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + .charge allocation (.done execution.1) + +def chargeOf {ι : Type u_1} {β : Type u_2} {steps : ℕ} {program : OAI.EditApproximation.BitQuery ι β} (allocation : ℕ) + (tail : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (.charge steps program) := + .charge allocation tail + +def runCells {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) + (childCells : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} : OAI.EditApproximation.BitQuery.Footprint program → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .done _, _ => 0 + | .read key _ continuation, memory => + let first := ask key memory + 3 + childCells key memory + (continuation first.value).runCells ask childCells first.memory + | .charge cells next, memory => cells + next.runCells ask childCells memory + +def computeOf {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + OAI.EditApproximation.BitQuery.Footprint.compute execution allocation + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (allocation : ∀ key, OAI.EditApproximation.BitQuery.Footprint (reader key)) : + (inputs : List κ) → (next : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → + (∀ words, OAI.EditApproximation.BitQuery.Footprint (next words)) → OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.collect reader inputs next) + | [], _, continuation => continuation [] + | key :: rest, next, continuation => + (allocation key).bind _ fun word => .charge 1 + (collect reader allocation rest (fun words => next (word :: words)) + (fun words => continuation (word :: words))) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι β} (heap : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (program.mapKeysWithWork f) := + match heap with + | .done result => .done result + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (.read (f key).1 _ (fun word => (continuation word).mapKeysWithWork f allocation)) + | .charge localCells next => .charge localCells (next.mapKeysWithWork f allocation) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) + (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) : + OAI.EditApproximation.BitQuery.Footprint (program.restrictWithWork P test htest) := + match heap with + | .done result => .done result + | .charge localCells next => .charge localCells (next.restrictWithWork P test htest allocation) + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (by + split + · exact .read _ _ (fun word => (continuation word).restrictWithWork P test htest allocation) + · exact (continuation (OAI.EditApproximation.BinaryFraction.nat 0)).restrictWithWork P test htest allocation) + +def normalize {ι : Type u_1} {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (program.normalize base hbase remaining) := + heap.bind _ fun word => OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + (OAI.EditApproximation.BinaryFraction.finishCachedAllocation (word, 0) 0 base hbase remaining) + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bandActionPredicate {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : Prop := + OAI.EditApproximation.endpointActionConnection r states = 0 ∧ + (∀ i, Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b) ∧ + ∀ j : Fin M, 0 < j.val → + |bandCutShift parent states j - ((r.lo : ℚ) - parent.lo) - velocity * + OAI.EditApproximation.rationalWidePrefixMinimum parent r actions hnonempty child j.val (OAI.EditApproximation.bandCutShift parent states j)| ≤ + tau * theta * b / M + +def queryOnlineSourceGather {ι : Type u_1} {β : Type u_2} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) (hP : 0 < P) (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (reader : (ℕ × OAI.EditApproximation.TargetInterval ny) → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect (fun key => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) keys (next keys)) + +def coarseLabelChildren {B d : ℕ} {α : Type u_1} (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α d × Fin B × OAI.EditApproximation.CoarseThresholdDraws B d) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseLabelChildren Q lam allowance work rest + +instance bandActionPredicateDecidable {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Decidable (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions hnonempty child states) := by + unfold OAI.EditApproximation.bandActionPredicate + infer_instance + +def computedBandActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + let actions := OAI.EditApproximation.wideActionList M parent r b P + if h : actions = [] then [] else + if |velocity| ≤ 1 - tau then + actions.filter (fun states => decide (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions h child states)) + else [] + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalEndpointActionValue {ny M : ℕ} (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.endpointActionConnection r states + ∑ i, child i (states i) + +def rationalActualWideActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) := + representatives.flatMap fun br => (OAI.EditApproximation.wideActionList M parent br.2 br.1 P).map fun states => + ⟨br.2, OAI.EditApproximation.endpointActionConnection br.2 states, fun i => (i, states i)⟩ + +def groupQueriedChildLabels (M Q b : ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M) := + if OAI.EditApproximation.groupSampleCount M Q b h = M then univ else univ.image draw + +def rationalWideActionMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (hnonempty : OAI.EditApproximation.wideActionList M parent r b P ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalEndpointActionValue r ((OAI.EditApproximation.wideActionList M parent r b P).head hnonempty) child) + ((OAI.EditApproximation.wideActionList M parent r b P).map fun states => OAI.EditApproximation.rationalEndpointActionValue r states child) + +def groupCurrentInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.groupQueriedChildLabels M Q b h draw).biUnion fun i => + (OAI.EditApproximation.groupRoundedStateList source target parent b exponent cell i h).toFinset.image fun r => (i, r) + +def representativeBandActions {α : Type u_1} (source target : List α) + {M : ℕ} (parent : OAI.EditApproximation.TargetInterval source.length) (r : OAI.EditApproximation.TargetInterval target.length) + (b P : ℕ) (tau theta : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) : + List (Fin M → OAI.EditApproximation.TargetInterval target.length) := + if h : OAI.EditApproximation.wideActionList M parent r b P = [] then [] else + let Z := OAI.EditApproximation.rationalWideActionMinimum parent r b P h child + if 0 < Z then + OAI.EditApproximation.computedBandActions parent r b P tau theta + (OAI.EditApproximation.rationalStateGap (OAI.EditApproximation.substring source parent.lo parent.hi) target r / Z) child + else [] + +structure UnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) where + center : OAI.EditApproximation.TargetInterval target.length + nonempty : OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child ≠ [] + sum_guard : (∑ i, OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i) ≤ 64 * F * b + wide_guard : OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial ∈ OAI.EditApproximation.wideActionList M parent center b P + imbalance_guard : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target + (OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i + +def keyedOnlineBandG {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H b : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (r : OAI.EditApproximation.TargetInterval target.length) : ℕ := + H + (OAI.EditApproximation.bandCoordinates (OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child).toFinset).card + 2 + +def testUnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (center : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + let band := OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + if hband : band = [] then none else + if hsum : (∑ i, OAI.EditApproximation.bandChildEnvelope b band initial i) ≤ 64 * F * b then + let rounded := OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b band hband initial + if hwide : rounded ∈ OAI.EditApproximation.wideActionList M parent center b P then + if hgap : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target (rounded i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b band initial i then + some ⟨center, hband, hsum, hwide, hgap⟩ + else none + else none + else none + +def unskippedBandList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (centers : List (OAI.EditApproximation.TargetInterval target.length)) : + List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + centers.filterMap (OAI.EditApproximation.testUnskippedBand source target parent b P thetaExponent tau F child initial) + +def keyedOnlineCandidate {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (r : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.PhysicalRationalAction M target.length) := by + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + have proof_keyedOnlineBandG_positive_78 {α : Type u_1} (source : List.{u_1} α) (target : List.{u_1} α) {M : ℕ} (parent : OAI.EditApproximation.TargetInterval (List.length.{u_1} source)) (P : ℕ) (exponent : ℕ) (H : ℕ) (b : ℕ) (tau : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval (List.length.{u_1} target) → ℚ) (r : OAI.EditApproximation.TargetInterval (List.length.{u_1} target)) : + 0 < OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r := by + unfold OAI.EditApproximation.keyedOnlineBandG + omega + exact + let band := OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child + let envelope := OAI.EditApproximation.bandChildEnvelope b band initial + let G := OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r + let K := G ^ 80 + let accepted := OAI.EditApproximation.boundedOnlineInteger (OAI.EditApproximation.optimizerTriangularMass K) + (proof_optimizerTriangularMass_positive_77 _ + (pow_pos (proof_keyedOnlineBandG_positive_78 source target parent P exponent H b tau child r) 80)) integer + if hband : band = [] then none else + match OAI.EditApproximation.testUnskippedBand source target parent b P exponent tau F child initial r with + | none => none + | some _ => some (OAI.EditApproximation.sharedBandRationalAction r + (OAI.EditApproximation.finiteOptimizerActionDraw band hband envelope + (OAI.EditApproximation.rationalOnlineLinear eta kappa + (OAI.EditApproximation.childGain envelope (fun s coordinate => children coordinate.1 s coordinate.2)) + (OAI.EditApproximation.childDecrement envelope (fun s coordinate => children coordinate.1 s coordinate.2)) t) + G K accepted)) + +def cellUnskippedBands {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) := + OAI.EditApproximation.unskippedBandList source target parent b P thetaExponent tau F child initial + (OAI.EditApproximation.cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) cell) + +def localOnlineCandidates {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N P F exponent H : ℕ) (tau a eta kappa : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + (OAI.EditApproximation.dyadicQueryWindow N (parentInitial q) a F).filterMap fun b => + let r := OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q + if (b : ℚ) / (4 * a) ≤ parentInitial r ∧ parentInitial r ≤ 8 * F * b then + OAI.EditApproximation.keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child initial children t r (integer b r) + else none + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo +variable {α : Type u_1} + +def value : OAI.EditApproximation.BinaryMemo α → Option α + | .empty => none + | .node v _ _ => v + +def left : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ _ r => r + +def lookup (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α + | [] => tree.value + | false :: rest => tree.left.lookup rest + | true :: rest => tree.right.lookup rest + +def insert (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α + | [], a => .node (some a) tree.left tree.right + | false :: rest, a => .node tree.value (tree.left.insert rest a) tree.right + | true :: rest, a => .node tree.value tree.left (tree.right.insert rest a) + +def lookupCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α × ℕ + | [] => (tree.value, 1) + | false :: rest => + let result := tree.left.lookupCosted rest + (result.1, result.2 + 1) + | true :: rest => + let result := tree.right.lookupCosted rest + (result.1, result.2 + 1) + +def insertCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α × ℕ + | [], a => (.node (some a) tree.left tree.right, 1) + | false :: rest, a => + let result := tree.left.insertCosted rest a + (.node tree.value result.1 tree.right, result.2 + 1) + | true :: rest, a => + let result := tree.right.insertCosted rest a + (.node tree.value tree.left result.1, result.2 + 1) + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def rankedMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : OAI.EditApproximation.RecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1⟩ + | none => + let result := OAI.EditApproximation.FiniteQuery.run (fun child previous => + rankedMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1⟩ +termination_by rank key +decreasing_by exact child.property + +def localWarmupStepQuery {ι : Type u_1} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : ℚ) (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) (q : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (initialRead q) fun value => + let centers := OAI.EditApproximation.rawRefinementCenters N P F a value q + OAI.EditApproximation.FiniteQuery.collect initialRead centers fun answers => + let initial := fun r => if r = q then value else OAI.EditApproximation.finiteAnswerTable centers answers r + let representatives := OAI.EditApproximation.localRefinementRepresentatives N P F a initial q + let inputs := OAI.EditApproximation.wideWarmupInputs (M := M) parent P representatives + OAI.EditApproximation.FiniteQuery.collect childRead inputs fun values => + .done (OAI.EditApproximation.rationalBellman initial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent representatives P) (OAI.EditApproximation.finiteAnswerTable inputs values) q) + +def keyedOnlineSourceRange {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (key : ℕ × OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.optimizerTriangularMass (OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H key.1 tau child key.2 ^ 80) + +def occurrenceBuild (symbolBits positionBits : ℕ) : List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts + | [] => .empty + | e :: es => + let table := occurrenceBuild symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let old := (table.lookup key).getD .empty + table.insert key (old.add positionBits e.2) + +def occurrenceBuildWithWork (symbolBits positionBits : ℕ) : + List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ + | [] => (.empty, 0) + | e :: es => + let previous := occurrenceBuildWithWork symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let found := previous.1.lookupCosted key + let inserted := (found.1.getD .empty).addWithWork positionBits e.2 + let updated := previous.1.insertCosted key inserted.1 + (updated.1, previous.2 + symbolBits + found.2 + inserted.2 + updated.2 + 2) + +def occurrenceQueryWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : Bool × ℕ := + let key := OAI.EditApproximation.binaryMemoKey symbolBits a + let found := table.lookupCosted key + let tree := found.1.getD .empty + let first := tree.prefixWithWork positionBits lo + let last := tree.prefixWithWork positionBits hi + (decide (first.1 < last.1), symbolBits + found.2 + first.2 + last.2 + 2) + +def rankedBitMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitRecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1, 0⟩ + | none => + let result := OAI.EditApproximation.BitQuery.runMemo (fun child previous => + rankedBitMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1, result.localWork⟩ +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupStepQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.FiniteQuery ι) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.localWarmupStepQuery (OAI.EditApproximation.physicalSourceInterval source.length node) N P F (OAI.EditApproximation.refinementFactor A F) + (fun r => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, r)) childRead q + +def indexedSingletonCostWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : ℕ × ℕ := + if lo = hi then (1, 1) else + let query := OAI.EditApproximation.occurrenceQueryWithWork table symbolBits positionBits a lo hi + (hi - lo - if query.1 = true then 1 else 0, query.2 + 4) + +def integerOccurrenceIndex (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts := + OAI.EditApproximation.occurrenceBuild (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def integerOccurrenceBuildWithWork (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ := + OAI.EditApproximation.occurrenceBuildWithWork (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def rankedMemoAddressWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => cost key + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoAddressWork rank program bits encode cost child.val previous) + (program key) memory + cost key +termination_by rank key +decreasing_by exact child.property + +def rankedMemoKernelWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => 0 + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoKernelWork rank program bits encode cost child.val previous) + (program key) memory +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupRequestQuery {α : Type u_1} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (pass copy T S j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S} := + match j with + | 0 => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + | t + 1 => + if hbelow : node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F A seedRead + (OAI.EditApproximation.physicalWarmupChildQuery pass copy T S t node hbelow q) node q + else OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalLocalOnlineKey (M J N n : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × OAI.EditApproximation.TargetInterval n + +abbrev ClampedPhysicalSeed (M J ny N : ℕ) := OAI.EditApproximation.PhysicalEntry M J ny → Fin (N + 1) + +def finalTargetState (n : ℕ) : OAI.EditApproximation.TargetInterval n := ⟨0, n, Nat.zero_le _, le_rfl⟩ + +abbrev PhysicalCommonKey (M J N n exponent B : ℕ) := + Sum (OAI.EditApproximation.CommonRangeKey (OAI.EditApproximation.PhysicalLocalOnlineKey M J N n) B) + (OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) + +def clampedSeedNat {M J ny N : ℕ} (seed : OAI.EditApproximation.ClampedPhysicalSeed M J ny N) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : ℕ := (seed state).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open Finset + +def triangularChoiceWithWork (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K × ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, by omega⟩, threshold.2 + test.2 + 1) + +def triangularChoiceAllocation (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + let localCells := OAI.EditApproximation.triangularMassAllocation K + integer.val.bits.length + + (OAI.EditApproximation.bitWordValue threshold.1).bits.length + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + localCells + triangularChoiceAllocation K ⟨integer.val, hsmall⟩ + else localCells + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def coordinateVectorWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + Vector (Fin M × OAI.EditApproximation.TargetInterval n) (OAI.EditApproximation.listedBandCoordinates band).length × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + exact + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + (Vector.ofFn (fun i => coordinates.1.get ⟨i.val, by + rw [proof_bandCoordinatesWithWork_value_68] + exact i.isLt⟩), coordinates.2 + coordinates.1.length + 1) + +def reduceOnlineIntegerWithWork (K : ℕ) (hK : 0 < K) (integer : ℕ) : + Fin (OAI.EditApproximation.optimizerTriangularMass K) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + exact + let mass := OAI.EditApproximation.triangularMassWithWork K + let divided := OAI.EditApproximation.binaryNaturalDivModWithWork integer (OAI.EditApproximation.bitWordValue mass.1) + (⟨OAI.EditApproximation.bitWordValue divided.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 integer (OAI.EditApproximation.bitWordValue mass.1) + (by rw [proof_triangularMassWithWork_value_65]; exact proof_optimizerTriangularMass_positive_77 K hK)).2] + rw [proof_triangularMassWithWork_value_65] + exact Nat.mod_lt _ (proof_optimizerTriangularMass_positive_77 K hK)⟩, + mass.2 + divided.2.2 + Nat.size integer + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def countedPreparedActionReadWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band + let vertices := OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates.1 mass band + let linear := OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.1.get i) + let selected := OAI.EditApproximation.BinaryFraction.selectionWithWork vertices.1 linear.1 G j + (selected.1, coordinates.2 + vertices.2 + linear.2 + selected.2 + 3) + +def countedPreparedActionKernelAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band).1 + let vertices := (OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates mass band).1 + let linear := (OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.get i)).1 + OAI.EditApproximation.BinaryFraction.countedBandVerticesAllocation coordinates mass band + + OAI.EditApproximation.vectorMapAllocation _ (fun i => OAI.EditApproximation.BinaryFraction.onlineLinearReadAllocation (fun child => mass.get child) + read footprint eta kappa t (coordinates.get i)) + OAI.EditApproximation.BinaryFraction.selectionAllocation vertices linear G j + +def countedBandActionReadWithWork {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial + let selected := OAI.EditApproximation.BinaryFraction.countedPreparedActionReadWithWork mass.1 read eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +def countedPreparedActionAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.coordinateVectorAllocation band + OAI.EditApproximation.BinaryFraction.countedPreparedActionKernelAllocation mass read footprint eta kappa band G j t + +def countedSampledOnlineReadWithWork {n M : ℕ} (center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M × ℕ := + let chosen := OAI.EditApproximation.triangularChoiceWithWork K integer + let selected := OAI.EditApproximation.BinaryFraction.countedBandActionReadWithWork b initial read eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, OAI.EditApproximation.BinaryFraction.zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +def countedBandActionAllocation {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band initial initialAllocation + + OAI.EditApproximation.BinaryFraction.countedPreparedActionAllocation (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial).1 + read footprint eta kappa band G j t + +def countedSampledOnlineAllocation {n M : ℕ} (_center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (_hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : ℕ := + let chosen := (OAI.EditApproximation.triangularChoiceWithWork K integer).1 + OAI.EditApproximation.triangularChoiceAllocation K integer + + OAI.EditApproximation.BinaryFraction.countedBandActionAllocation b initial initialAllocation read readAllocation eta kappa band G chosen.val t + M + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} + +def rank (tableRank : κ → ℕ) : Sum σ κ → ℕ + | .inl _ => 0 + | .inr key => tableRank key + 1 + +def keyCode (sourceCode : σ → ℕ) (tableCode : κ → ℕ) : Sum σ κ → ℕ + | .inl source => 2 * sourceCode source + | .inr table => 2 * tableCode table + 1 + +def child (tableRank : κ → ℕ) (parent : κ) : + Sum σ {key : κ // tableRank key < tableRank parent} → + {key : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank key < OAI.EditApproximation.SourceRanked.rank (σ := σ) tableRank (.inr parent)} + | .inl source => ⟨.inl source, Nat.zero_lt_succ _⟩ + | .inr table => ⟨.inr table.val, Nat.add_lt_add_right table.property 1⟩ + +def body (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (key : Sum σ κ) : + OAI.EditApproximation.FiniteQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} := + match key with + | .inl source => .done (sourceValue source) + | .inr table => OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.child tableRank table) (tableBody table) + +def bitBody (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.BitQuery (Sum σ {key : κ // tableRank key < tableRank parent}) OAI.EditApproximation.BinaryFraction) + (sourceValue : σ → OAI.EditApproximation.BinaryFraction × ℕ) (key : Sum σ κ) : + OAI.EditApproximation.BitQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} OAI.EditApproximation.BinaryFraction := + match key with + | .inl source => OAI.EditApproximation.BitQuery.compute (sourceValue source) + | .inr table => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (OAI.EditApproximation.SourceRanked.child tableRank table key, 1)) (tableBody table) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def depth {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => J - entry.1.1.val + | .inr request => request.val.remainingDepth + +def index {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.rank T S + 1 + +def rank {M J ny passes copies T S : ℕ} + (request : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) : ℕ := + request.depth + request.index + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def chargedPreviousRead {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hpass : 0 < parent.val.pass) (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨Sum.inr (OAI.EditApproximation.chargedPreviousPass parent state copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).2⟩⟩ .done + +def chargedWarmupChild {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨Sum.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ .done + +def chargedSeedQuery {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + exact + if hn : state.1 = parent.val.node then + if hp : parent.val.pass = 0 then + .read ⟨Sum.inl state, proof_coarse_rank_lt_100 state parent hn⟩ .done + else OAI.EditApproximation.FiniteQuery.collect (OAI.EditApproximation.chargedPreviousRead parent (Nat.pos_of_ne_zero hp) state.2) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => + ⌈(multiplier (parent.val.pass - 1) : ℚ) * value⌉₊)) : ℕ) + else .done 0 + +def chargedWarmupQuery {α : Type u_1} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := + if hz : parent.val.index = 0 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else if hbelow : parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) + (OAI.EditApproximation.chargedWarmupChild parent hbelow (Nat.pos_of_ne_zero hz)) parent.val.node parent.val.state + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +abbrev coarseEntryWidth {α : Type u} (x y : List α) : ℕ := max x.length y.length + +abbrev CoarseGuessIndex (n : ℕ) := Fin (Nat.clog 2 n + 1) + +def coarseGuess (n : ℕ) (i : OAI.EditApproximation.CoarseGuessIndex n) : ℕ := 2 ^ i.val + +def coarseEntryTree (B D : ℕ) {α : Type u} (x y : List α) : OAI.EditApproximation.CoarseSourceTree B (Option α) D := + OAI.EditApproximation.coarseSourceTreeOfList B D (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) x) + +noncomputable def coarseInitialMeasure (B D n : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseGuessIndex n → OAI.EditApproximation.CoarseThresholdDraws B D) := + Measure.pi fun _ => OAI.EditApproximation.coarseDrawMeasure B D + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveChildrenWork {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseActiveChildrenWork Q lam allowance work rest + +abbrev CoarseFullSeedDraws (B : ℕ) {I : Type u_1} {α : Type u_2} (depth : I → ℕ) (x y : I → List α) := + ∀ i, OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) → OAI.EditApproximation.CoarseThresholdDraws B (depth i) + +noncomputable def coarseFullSeedMeasure (B : ℕ) [NeZero B] + {I : Type u_1} {α : Type u_2} [Fintype I] (depth : I → ℕ) (x y : I → List α) + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseFullSeedDraws B depth x y) := + Measure.pi fun i => OAI.EditApproximation.coarseInitialMeasure B (depth i) (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionAcceptedLaw : Measure (∀ i, Fin (range i)) := + Measure.pi fun i => (PMF.uniformOfFintype (Fin (range i))).toMeasure + +abbrev RejectionRuntimeArray := (ι → ℕ) × (∀ i, Fin (range i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo + + +def fractionStorage : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .empty => 0 + | .node value left right => + 3 + (value.map fun word => word.numerator.bits.length + word.denominator.length + 1).getD 0 + + left.fractionStorage + right.fractionStorage + +def valueStorage {α : Type u_1} (bits : α → ℕ) : OAI.EditApproximation.BinaryMemo α → ℕ + | .empty => 0 + | .node value l r => 3 + (value.map bits).getD 0 + valueStorage bits l + valueStorage bits r + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def indexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ × ℕ := + match symbol with + | none => (hi - lo, 2) + | some a => OAI.EditApproximation.indexedSingletonCostWithWork table symbolBits positionBits a lo hi + +def integerOccurrenceStorage (source target : List ℤ) : ℕ := + OAI.EditApproximation.BinaryMemo.valueStorage OAI.EditApproximation.PositionCounts.storageBits (OAI.EditApproximation.integerOccurrenceIndex source target) + +def integerStoredDataSpace (source target : List ℤ) : ℕ := + OAI.EditApproximation.storedIntegerBits source + OAI.EditApproximation.storedIntegerBits target + + OAI.EditApproximation.storedNaturalBits (source.map OAI.EditApproximation.integerSymbolCode) + OAI.EditApproximation.storedNaturalBits (target.map OAI.EditApproximation.integerSymbolCode) + + OAI.EditApproximation.integerOccurrenceStorage source target + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def binaryIndexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi + (OAI.EditApproximation.BinaryFraction.nat result.1, result.2 + Nat.size result.1 + 2) + +def binaryIndexedLeafAllocation (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + OAI.EditApproximation.indexedLeafAllocation symbolBits positionBits symbol lo hi + + Nat.size (OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi).1 + 2 + +def queryIndexedSliceWithWork (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let symbol := OAI.EditApproximation.querySliceHeadWithWork source interval + let result := OAI.EditApproximation.binaryIndexedLeafWithWork occurrence symbolBits positionBits symbol.1 q.lo q.hi + (result.1, symbol.2 + result.2 + 1) + +def queryIndexedSliceAllocation (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : ℕ := + interval.lo.bits.length + interval.hi.bits.length + 1 + + OAI.EditApproximation.binaryIndexedLeafAllocation occurrence symbolBits positionBits (OAI.EditApproximation.querySliceHeadWithWork source interval).1 q.lo q.hi + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {n : ℕ} (read : TargetInterval n → List Bool × ℕ) (allocation : TargetInterval n → ℕ) + +def initialGridReadAllocation (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi + + OAI.EditApproximation.filterAllocation (fun r => ((OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).1, + (OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).2 + (read r).2)) + (fun r => OAI.EditApproximation.BinaryFraction.initialCenterGuardAllocation b (OAI.EditApproximation.bitWordValue (read r).1) A + allocation r) points + +def initialConeReadAllocation (sourceLength : ℕ) (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation center + OAI.EditApproximation.BinaryFraction.initialConeAllocation sourceLength (OAI.EditApproximation.bitWordValue (read center).1) a L query center + +def initialCentersReadAllocation (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read q).1 + let scales := (OAI.EditApproximation.dyadicScalesWithWork N).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales).1 + allocation q + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation Uq b A) scales + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) + (OAI.EditApproximation.BinaryFraction.initialGridReadAllocation read allocation P A Uq q) active + +def initialMinimumReadAllocation (sourceLength N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read query).1 + allocation query + OAI.EditApproximation.naturalEqualAllocation Uq 0 + + if (OAI.EditApproximation.naturalEqualWithWork Uq 0).1 then 0 else + let L := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F)).1 + let coefficient := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L OAI.EditApproximation.BinaryFraction.one).1 + let fallback := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient (OAI.EditApproximation.BinaryFraction.nat N)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L query) centers).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation L OAI.EditApproximation.BinaryFraction.one + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient (OAI.EditApproximation.BinaryFraction.nat N) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.initialConeReadAllocation read allocation sourceLength a L query) centers + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + Nat.size F + Nat.size N + +def initialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.initialCentersReadAllocation read allocation N P A query + OAI.EditApproximation.BinaryFraction.initialMinimumReadAllocation read allocation sourceLength N F a + query (OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query).1 + +def cachedInitialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedAllocation (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + (OAI.EditApproximation.BinaryFraction.initialProgramReadAllocation read allocation sourceLength N P F A a query) [true] (by decide) 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open BinaryFraction + +def onlineParametersAllocation (word : List Bool) : ℕ := + OAI.EditApproximation.bitPowerAllocation word 5 + OAI.EditApproximation.bitPowerAllocation word 4 + 2 + +def refinementDecrementAllocation (word : List Bool) : ℕ := OAI.EditApproximation.bitPowerAllocation word 10 + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BinaryFraction + +def scheduledRefinementAllocation (N pass : ℕ) : ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N : ℕ) : ℤ) + 2 + else 2 + +def refinementBaseAllocation (word : List Bool) : ℕ := + let power := OAI.EditApproximation.bitPowerWithWork word 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + OAI.EditApproximation.bitPowerAllocation word 10 + OAI.EditApproximation.bitAddAllocation power.1 [true] false + + OAI.EditApproximation.trimBitWordAllocation increment.1 + 2 + +def refinementParameterAllocation (N pass : ℕ) (word : List Bool) : ℕ := + OAI.EditApproximation.BinaryFraction.onlineParametersAllocation word + OAI.EditApproximation.scheduledRefinementAllocation N pass + + OAI.EditApproximation.BinaryFraction.refinementDecrementAllocation word + 5 + +def computedQueryPassAllocation (N pass : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + + OAI.EditApproximation.refinementParameterAllocation N pass (OAI.EditApproximation.inputSmallLog N).bits + 2 + +def computedQuerySetupAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation (OAI.EditApproximation.computedSeedPassCount N + 1) (fun i => OAI.EditApproximation.computedQueryPassAllocation N i.val) + + OAI.EditApproximation.refinementBaseAllocation (OAI.EditApproximation.inputSmallLog N).bits + 5 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational +open Finset + +def nat (n : ℕ) : OAI.EditApproximation.UnreducedRational := ⟨n, 1, by decide⟩ + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def countedGroupMemberSourceWithWork {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + let result := OAI.EditApproximation.BinaryFraction.groupMemberSourceWithWork scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) + (result.1, counts.2 + result.2 + 1) + +def roundedBandReadWithWork {n M : ℕ} (exponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector (OAI.EditApproximation.TargetInterval n) M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_lt_eq_true_57 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : a.lt b = true ↔ a.value < b.value := by + simp only [OAI.EditApproximation.UnreducedRational.lt, decide_eq_true_eq, OAI.EditApproximation.UnreducedRational.value] + rw [div_lt_div_iff₀ (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den) + (by exact_mod_cast b.den_pos : (0 : ℚ) < b.den)] + exact_mod_cast (Iff.rfl : a.num * (b.den : ℤ) < b.num * (a.den : ℤ) ↔ _) + have proof_nonzeroWithWork_value_58 (bits : List.{0} Bool) : + (OAI.EditApproximation.SignedBinary.nonzeroWithWork bits).1 = true ↔ OAI.EditApproximation.bitWordValue bits ≠ 0 := by + (simp [OAI.EditApproximation.SignedBinary.nonzeroWithWork, proof_bitCompareWithWork_eq_3, OAI.EditApproximation.bitWordValue]) + have proof_ltWithWork_value_59 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + cases ha : a.negative <;> cases hb : b.negative + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + · (simp only [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, ↓reduceIte, Bool.false_eq_true, + Bool.or_eq_true, proof_nonzeroWithWork_value_58, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + omega + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_denominatorInteger_value_60 (a : OAI.EditApproximation.BinaryFraction) : + a.denominatorInteger.value = (OAI.EditApproximation.bitWordValue a.denominator : ℤ) := rfl + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_ltWithWork_representation_61 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = a.representation.lt b.representation := by + apply Bool.eq_iff_iff.mpr + rw [proof_lt_eq_true_57] + simp only [OAI.EditApproximation.BinaryFraction.ltWithWork, proof_ltWithWork_value_59, proof_mulWithWork_value_35, + proof_denominatorInteger_value_60, proof_representation_value_32] + unfold OAI.EditApproximation.BinaryFraction.value + rw [div_lt_div_iff₀ (by exact_mod_cast a.denominator_pos : (0 : ℚ) < bitWordValue a.denominator) + (by exact_mod_cast b.denominator_pos : (0 : ℚ) < bitWordValue b.denominator)] + exact_mod_cast (Iff.rfl : + a.numerator.value * (OAI.EditApproximation.bitWordValue b.denominator : ℤ) < + b.numerator.value * (OAI.EditApproximation.bitWordValue a.denominator : ℤ) ↔ _) + have proof_ltWithWork_value_62 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + rw [proof_ltWithWork_representation_61, proof_lt_eq_true_57] + rfl + have proof_maxWithWork_value_63 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.maxWithWork a b).1.value = max a.value b.value := by + by_cases h : a.value < b.value + · simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, (proof_ltWithWork_value_62 a b).mpr h, ↓reduceIte, max_eq_right h.le] + · have hb : (a.ltWithWork b).1 = false := Bool.eq_false_iff.mpr (fun hh => h ((proof_ltWithWork_value_62 a b).mp hh)) + simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, hb, Bool.false_eq_true, ↓reduceIte, max_eq_left (le_of_not_gt h)] + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_roundedSpacingWithWork_value_64 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 = ⌈max 1 (theta.value * envelope.value)⌉₊ := by + simp only [OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork, proof_naturalCeilingWithWork_value_31, proof_maxWithWork_value_63, + proof_canonicalMulWithWork_value_45, OAI.EditApproximation.BinaryFraction.one, proof_nat_value_49, Nat.cast_one] + have proof_roundedSpacingWithWork_pos_56 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 := by + rw [proof_roundedSpacingWithWork_value_64, Nat.ceil_pos] + exact lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) (le_max_left _ _) + exact + OAI.EditApproximation.vectorMapWithWork M fun i => + let envelope := OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope.1 + let rounded := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) + (proof_roundedSpacingWithWork_pos_56 _ _) (band.head hne i) + (rounded.1, envelope.2 + spacing.2 + rounded.2 + exponent + 3) + +def queryGroupLabelsWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : List (Fin M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h + let test := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count.1) M + if test.1 then (List.finRange M, count.2 + test.2 + M + 2) + else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + let labels := OAI.EditApproximation.arithmeticMapWithWork draw indices + (labels.1, count.2 + test.2 + labels.2 + indices.length + 2) + +def queryGroupLabelsAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (_draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 + let test := (OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count) M).1 + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b h + OAI.EditApproximation.naturalEqualAllocation (OAI.EditApproximation.bitWordValue count) M + + if test then M else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + OAI.EditApproximation.arithmeticMapAllocation allocation indices + 2 * indices.length + +def countedGroupMemberSourceAllocation {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (allocation : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → ℕ) : ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + OAI.EditApproximation.vectorMapAllocation T (fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b (scales t)) + + OAI.EditApproximation.BinaryFraction.groupMemberSourceAllocation scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + (fun t j => allocation t (Fin.cast (heq t) j)) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def unskippedGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (_center : OAI.EditApproximation.TargetInterval ny) + (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : Bool × ℕ := + let envelope := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope.1 + let fb := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b) + let limit := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb.1 + let sumGuard := OAI.EditApproximation.BinaryFraction.leWithWork total.1 limit.1 + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read + let wideGuard := OAI.EditApproximation.actionMemberWithWork rounded.1.get wide + let gapGuard := OAI.EditApproximation.allWithWork (fun i => + let sourceLength := OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength.1) (rounded.1.get i) + let bound := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.1.get i) + let test := OAI.EditApproximation.BinaryFraction.leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) (List.finRange M) + (sumGuard.1 && wideGuard.1 && gapGuard.1, + envelope.2 + total.2 + fb.2 + limit.2 + sumGuard.2 + rounded.2 + wideGuard.2 + gapGuard.2 + 5) + +def queryGroupInputsWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let labels := OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun i => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1)) labels.1 + (inputs.1, labels.2 + inputs.2 + 1) + +def coarseIndexedRootWithWork {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_coarseDenominatorWithWork_value_127 (allowanceDen : List.{0} Bool) (q : List.{0} Bool) (L : List.{0} Bool) (branching : List.{0} Bool) (D : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.coarseDenominatorWithWork allowanceDen q L branching D).1 = + OAI.EditApproximation.coarseCommonDenominator (OAI.EditApproximation.bitWordValue allowanceDen) (OAI.EditApproximation.bitWordValue q) + (OAI.EditApproximation.bitWordValue L) (OAI.EditApproximation.bitWordValue branching) D := by + simp only [OAI.EditApproximation.coarseDenominatorWithWork, proof_trimBitWordWithWork_value_6, + proof_bitMulWithWork_value_0, proof_bitPowerWithWork_value_76, OAI.EditApproximation.coarseCommonDenominator] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_coarseRootDenominator_value_128 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 = OAI.EditApproximation.coarseCommonDenominator 1 q L B d := by + simp only [OAI.EditApproximation.BinaryFraction.coarseRootDenominator, proof_coarseDenominatorWithWork_value_127, proof_bitWordValue_bits_15] + have proof_coarseRootDenominator_pos_126 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) (hB : LT.lt.{0} 0 B) (hq : LT.lt.{0} 0 q) (hL : LT.lt.{0} 0 L) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 := by + rw [proof_coarseRootDenominator_value_128] + unfold OAI.EditApproximation.coarseCommonDenominator + positivity + exact + let den := OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d + let denPos := proof_coarseRootDenominator_pos_126 B q L d hB hq hL + let two := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos 2 + let allowance := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos k + let evaluated := OAI.EditApproximation.BinaryFraction.coarseIndexedWithWork k q L (OAI.EditApproximation.coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + (OAI.EditApproximation.BinaryFraction.coarseBinaryRead evaluated.1 (OAI.EditApproximation.coarseRootShift k).val, + den.2 + two.2 + allowance.2 + evaluated.2 + 1) + +def queryGroupInputsAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := + let build := fun i : Fin M => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1) + OAI.EditApproximation.BinaryFraction.queryGroupLabelsAllocation M Q b h draw allocation + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun i => OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesAllocation (ny := ny) parent b exponent cell i h + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1) + (OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw).1 + +def unskippedGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (_center : OAI.EditApproximation.TargetInterval ny) (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) + (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let envelope := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read).1 + let total := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope).1 + let fb := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b)).1 + let limit := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band read allocation + OAI.EditApproximation.BinaryFraction.bandMassAllocation envelope + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation F (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 64) fb + OAI.EditApproximation.BinaryFraction.leAllocation total limit + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b band hne read allocation + OAI.EditApproximation.actionMemberAllocation rounded.get wide + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.gapGuardAllocation parent envelope rounded) (List.finRange M) + +def queryGroupInputsTransportWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsWithWork parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def coarseIndexedCandidateWithWork {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : + OAI.EditApproximation.BinaryFraction × ℕ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + let root := OAI.EditApproximation.BinaryFraction.coarseIndexedRootWithWork k q L hB hq hL x y draws + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork root.1 (OAI.EditApproximation.BinaryFraction.nat k) + let doubled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) shifted.1 + (doubled.1, root.2 + shifted.2 + doubled.2 + Nat.size k + 3) + +def preparedUnskippedReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read readAllocation + + if hband : band = [] then 0 else + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.unskippedGuardReadAllocation parent center b exponent F band (wide.map Vector.get) hband initial initialAllocation + + if (OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band (wide.map Vector.get) hband initial).1 then 3 else 0 + +def queryGroupInputsTransportAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsAllocation (ny := ny) parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + (fun sample => allocation (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def preparedUnskippedReadWithWorkRaw {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (center : OAI.EditApproximation.TargetInterval ny) : Option (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let guard := OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band.1 + (wide.1.map Vector.get) hband initial + if guard.1 = true then + (some ⟨center, band.1, hband⟩, band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +def coarseIndexedInitialWithWork {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ × ℕ := + let long := OAI.EditApproximation.binaryNaturalCompareWithWork (2 * x.length) y.length + if long.1 = .lt then (min N y.length, long.2 + Nat.size N + Nat.size y.length + 4) else + let equal := OAI.EditApproximation.BinaryFraction.naturalListEqualWithWork x y + if equal.1 then (0, long.2 + equal.2 + 3) else + let roots := OAI.EditApproximation.arithmeticMapWithWork (fun i => OAI.EditApproximation.BinaryFraction.coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) + (List.finRange (Nat.clog 2 (OAI.EditApproximation.coarseEntryWidth x y) + 1)) + let smallest := OAI.EditApproximation.BinaryFraction.coarseMinimumWithWork roots.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork smallest.1 + let result := OAI.EditApproximation.wordMinWithWork N.bits rounded.1 + (OAI.EditApproximation.bitWordValue result.1, long.2 + equal.2 + roots.2 + smallest.2 + rounded.2 + result.2 + Nat.size N + 6) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {ny M T : ℕ} (b exponent Q : ℕ) + (initial current : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (initialAllocation currentAllocation : Fin M → TargetInterval ny → ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (drawSource : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (drawAllocation : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → ℕ) + +def unskippedEstimateSourceWithWorkRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : OAI.EditApproximation.BinaryFraction × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial + let values := OAI.EditApproximation.vectorMapWithWork M fun i => current i (rounded.1.get i) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.1.get + let result := OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceWithWork Q b scales connection.1 mass.1 values.1 drawSource + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +def unskippedEstimateSourceAllocationRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + let mass := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial).1 + let values := (OAI.EditApproximation.vectorMapWithWork M (fun i => current i (rounded.get i))).1 + let connection := (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.get).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b member.actions initial initialAllocation + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b member.actions member.nonempty initial initialAllocation + + OAI.EditApproximation.vectorMapAllocation M (fun i => currentAllocation i (rounded.get i)) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation member.center rounded.get + OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceAllocation Q b scales connection mass values drawSource drawAllocation + +def chooseUnskippedSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupWithWork members hne + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + +def chooseUnskippedSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupAllocation members + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation) + +def sampledGroupActionSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current scales drawSource members hne + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := OAI.EditApproximation.BinaryFraction.endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +def sampledGroupActionSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : ℕ := + let selected := (OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current + scales drawSource members hne).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.actions selected.nonempty initial).1 + OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation members + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b selected.actions selected.nonempty initial initialAllocation + + OAI.EditApproximation.BinaryFraction.endpointActionAllocation selected.center rounded.get + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def preparedOnlineReadWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [proof_onlineIndexSetupWithWork_value_129] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center + if guard.1.isSome then + let sampled := OAI.EditApproximation.BinaryFraction.countedSampledOnlineReadWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +def preparedOnlineReadAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (tableAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → ℕ) + + + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let G := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let accepted := (OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G]; rw [proof_onlineIndexSetupWithWork_value_129]; positivity) integer).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child childAllocation + + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + OAI.EditApproximation.reduceOnlineIntegerAllocation (G ^ 80) integer + + if hband : band = [] then 0 else + OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation + + if (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center).1.isSome then + OAI.EditApproximation.BinaryFraction.countedSampledOnlineAllocation center b initial initialAllocation table tableAllocation eta kappa + band hband G (G ^ 80) t accepted + 1 + else 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion + + +inductive Step (substitutions : Bool) {Alpha : Type u} : List Alpha → List Alpha → Prop + | insert (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ q) (p ++ a :: q) + | delete (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ a :: q) (p ++ q) + | substitute (h : substitutions = true) (p q : List Alpha) (a b : Alpha) : + Step substitutions (p ++ a :: q) (p ++ b :: q) + +inductive Script (substitutions : Bool) {Alpha : Type u} : ℕ → List Alpha → List Alpha → Prop + | nil (x : List Alpha) : Script substitutions 0 x x + | cons {n : ℕ} {x y z : List Alpha} (first : OAI.EditDistortion.Step substitutions x y) + (rest : Script substitutions n y z) : Script substitutions (n + 1) x z + +noncomputable def edit {Alpha : Type u} (x y : List Alpha) : ℕ := + sInf {n | Script true n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion +variable {Alpha : Type u} {s : Bool} + +noncomputable def cost (s : Bool) (x y : List Alpha) : ℕ := sInf {n | Script s n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.CoarseSourceTree +open Finset EditDistortion + +def word {B : ℕ} {α : Type u} : {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → List α + | _, .leaf letter => letter.toList + | _, .branch children => (List.ofFn fun i => word (children i)).flatten + + +end OAI.EditApproximation.CoarseSourceTree +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def coarseLabelCount {B : ℕ} {α : Type u_1} (Q lam : ℚ) : + {d : ℕ} → OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => 0 + | .branch children, (draws, below) => B + + OAI.EditApproximation.coarseLabelChildren Q lam allowance (fun child => coarseLabelCount Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseIndexedEntryBinaryCost (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + (OAI.EditApproximation.BinaryFraction.coarseIndexedInitialWithWork (OAI.EditApproximation.inputHeight N ^ 4) (64 * OAI.EditApproximation.inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) x y draws).2 + +def coarseInitialLabelCount {α : Type u_1} [DecidableEq α] + (B d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseLabelCount Q lam (OAI.EditApproximation.coarseEntryTree B d x y) (draws i) + (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +def coarseChildrenCost {B D : ℕ} {α : Type u} (k : ℕ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D) → ℕ → Fin (2 * k + 1) → ℕ + | [], _, _ => 0 + | child :: rest, start, shift => + univ.inf' univ_nonempty (fun next => value child start next + 2 * Nat.dist shift.val next.val) + + coarseChildrenCost k value rest (start + child.word.length) shift + +def coarseShiftCost {B : ℕ} {α : Type u} [DecidableEq α] (k : ℕ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ + | _, .leaf none, _, _ => 0 + | _, .leaf (some letter), start, shift => + if (frame[start + shift.val]?.getD none) = some letter then 0 else 1 + | _, .branch children, start, shift => + OAI.EditApproximation.coarseChildrenCost k (fun child => coarseShiftCost k frame child) + (List.ofFn children) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset +open EditDistortion + +instance targetIntervalFintype (n : ℕ) : Fintype (OAI.EditApproximation.TargetInterval n) := by + have proof_targetStates_complete_12 (n : ℕ) (q : OAI.EditApproximation.TargetInterval n) : q ∈ OAI.EditApproximation.targetStates n := by + apply List.mem_flatMap.mpr + refine ⟨q.lo, List.mem_range.mpr (Nat.lt_succ_of_le (q.ordered.trans q.valid)), ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨q.hi, List.mem_range.mpr (Nat.lt_succ_of_le q.valid), ?_⟩ + rw [OAI.EditApproximation.makeTargetState, dite_eq_left (show q.lo ≤ q.hi ∧ q.hi ≤ n from ⟨q.ordered, q.valid⟩)] + exact + Fintype.ofList (OAI.EditApproximation.targetStates n) (proof_targetStates_complete_12 n) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnskippedBand +open Finset + +def actions {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + OAI.EditApproximation.representativeBandActions source target parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + +def envelope {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) (i : Fin M) : ℚ := + OAI.EditApproximation.bandChildEnvelope b member.actions initial i + +def rounded {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + Fin M → OAI.EditApproximation.TargetInterval target.length := + OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b member.actions member.nonempty initial + +def rationalAction {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M := + ⟨member.center, OAI.EditApproximation.endpointActionConnection member.center member.rounded, fun i => (i, member.rounded i)⟩ + + +end OAI.EditApproximation.UnskippedBand +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def unskippedGroupEstimate {T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + OAI.EditApproximation.groupMemberEstimate scales count (OAI.EditApproximation.endpointActionConnection member.center member.rounded) + member.envelope (fun i => value i (member.rounded i)) draw + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def groupDyadicScaleAt (M b : ℕ) (F : ℚ) (i : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℚ := + (OAI.EditApproximation.groupDyadicScales M b F).get i + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev CellGroupDraws (M F Q : ℕ) := ∀ b : ℕ, (ℕ × ℕ) → + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M + +abbrev cellScaleReadDraw (M b Q : ℕ) (F : ℚ) := + ∀ (t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length), + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → Fin M × ℕ + +abbrev GroupScalarKey (M F Q : ℕ) := + Σ key : ℕ × (ℕ × ℕ), Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale)) + +abbrev CountedCellGroupDraws (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M × ℕ + +abbrev CellGroupSourceAllocations (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → ℕ + +abbrev CountedCellGroupAllocations (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → ℕ + +abbrev CellGroupReadDraws (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + OAI.EditApproximation.cellScaleReadDraw M b Q F + +def groupScalarKeys (M F Q : ℕ) (groups : List (ℕ × (ℕ × ℕ))) : List (OAI.EditApproximation.GroupScalarKey M F Q) := + groups.flatMap fun (key : ℕ × (ℕ × ℕ)) => + (List.finRange (OAI.EditApproximation.groupDyadicScales M key.1 F).length).flatMap + fun (scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length) => + (List.finRange (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale))).map + fun sample => Sigma.mk key (Sigma.mk scale sample) + +noncomputable def groupDrawFromValues {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List ℚ) : OAI.EditApproximation.CellGroupDraws M F Q := by + classical + exact fun b cell scale sample => Fin.ofNat M ⌊OAI.EditApproximation.finiteAnswerTable keys values ⟨(b, cell), scale, sample⟩⌋₊ + +def queryGroupKeyEqualWithWork {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1.1 b.1.1 + let lo := OAI.EditApproximation.naturalEqualWithWork a.1.2.1 b.1.2.1 + let hi := OAI.EditApproximation.naturalEqualWithWork a.1.2.2 b.1.2.2 + let label := OAI.EditApproximation.naturalEqualWithWork a.2.1.val b.2.1.val + let sample := OAI.EditApproximation.naturalEqualWithWork a.2.2.val b.2.2.val + (scale.1 && lo.1 && hi.1 && label.1 && sample.1, + scale.2 + lo.2 + hi.2 + label.2 + sample.2 + 4) + +def queryGroupKeyEqualAllocation {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.1 b.1.1 + OAI.EditApproximation.naturalEqualAllocation a.1.2.1 b.1.2.1 + + OAI.EditApproximation.naturalEqualAllocation a.1.2.2 b.1.2.2 + OAI.EditApproximation.naturalEqualAllocation a.2.1.val b.2.1.val + + OAI.EditApproximation.naturalEqualAllocation a.2.2.val b.2.2.val + 4 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def queryGroupKeySamplesWithWork (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let samples := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, scales.1.length + count.2 + labeled.2 + coordinates.length + 3)) indices + (samples.1, scales.2 + 4 * scales.1.length + samples.2 + eb + 4) + +def querySharedCellInputsWithWork {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1)) indices + (inputs.1, scales.2 + 4 * scales.1.length + inputs.2 + eb + 4) + +def groupKeySampleBlock {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, raw.length + count.2 + labeled.2 + coordinates.length + 3) + +def groupKeySampleBlockAllocation {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (_cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b word + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 2) coordinates + + 2 * coordinates.length + +def querySharedCellInputsAllocation {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) + (allocation : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let build := fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1) + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportAllocation (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) (allocation scale)) indices + +def queryGroupKeySamplesAllocation (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (OAI.EditApproximation.BinaryFraction.groupKeySampleBlockAllocation (Q := Q) b scales.1 hs cell) indices + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def querySharedInputsWithWork {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4)) scales.1 + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork inputs.1 + (sorted.1, scales.2 + radius.2 + inputs.2 + sorted.2 + 3) + +def queryGroupDrawReadWithWork {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : Fin M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values ⟨(b, cell), scale, sample⟩ + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + let reduced := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue floor.1) M + (⟨OAI.EditApproximation.bitWordValue reduced.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 _ M (NeZero.pos M)).2] + exact Nat.mod_lt _ (NeZero.pos M)⟩, + word.2 + floor.2 + reduced.2.2 + 3) + +def queryGroupSourceKeysWithWork {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + 2) + +def queryGroupDrawReadAllocation {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : ℕ := + let key : OAI.EditApproximation.GroupScalarKey M F Q := ⟨(b, cell), scale, sample⟩ + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values key).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryGroupKeyEqualWithWork OAI.EditApproximation.queryGroupKeyEqualAllocation keys values key + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + OAI.EditApproximation.bitDivModAllocation M.bits (OAI.EditApproximation.bitWordValue floor).bits + +def queryGroupSourceKeysAllocation {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4) + let allocation := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesAllocation M F Q eM eb eF hM hF) cells + eb + exponent + 2 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def querySharedInputsAllocation {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (allocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) : ℕ := + let scales := (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4) + let alloc := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell)) cells + eb + exponent + 2 + let inputs := (OAI.EditApproximation.arithmeticFlatMapWithWork build scales).1 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build alloc scales + OAI.EditApproximation.queryOrderedChildInputsAllocation inputs + +def preparedCellGroupSourceAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation currentAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + + + (cell : ℕ × ℕ) : ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell).1 + let members := (OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers).1 + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial parentAllocation cell + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) + (fun center => OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation) centers + + if hempty : members = [] then 0 else + OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceAllocationRaw b exponent Q initial current initialAllocation currentAllocation + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) + (fun t j => drawAllocation t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members hempty + 1 + +def preparedCellGroupSourceWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell + let members := OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceWithWorkRaw b exponent Q initial current (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def querySharedInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N F exponent Q : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval target.length → ℚ) (q : OAI.EditApproximation.TargetInterval target.length) + (draw : OAI.EditApproximation.CellGroupDraws M F Q) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).toFinset.biUnion fun key => + Finset.univ.biUnion fun scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length => + OAI.EditApproximation.groupCurrentInputCover source target parent key.1 exponent Q key.2 + (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale) + +def coarseThresholdChildrenCost {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (allowance : ℚ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ → Fin (2 * k + 1) → ℚ + | [], _, _ => 0 + | (child, draw, below) :: rest, start, shift => + let threshold := OAI.EditApproximation.coarseChildThreshold B Q allowance draw + let childMinimum := univ.inf' univ_nonempty (fun next => + value child below (lam * threshold) start next + (2 * Nat.dist shift.val next.val : ℕ)) + OAI.EditApproximation.coarseThresholdContribution threshold (allowance / Q) childMinimum + + coarseThresholdChildrenCost k Q lam value allowance rest (start + child.word.length) shift + +def coarseThresholdEstimate {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ + | _, tree, draws, allowance, start, shift => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf letter, _ => (OAI.EditApproximation.coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℚ) + | .branch children, (draws, below) => + OAI.EditApproximation.coarseThresholdChildrenCost k Q lam + (fun child => coarseThresholdEstimate k Q lam frame child) allowance + (List.ofFn fun i => (children i, draws i, below i)) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalScalarIndex (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : Type := + match key with + | .inl _ => Fin R + | .inr group => Σ _time : Fin R, + Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q ((OAI.EditApproximation.dyadicScales N).get group.2.1) + (OAI.EditApproximation.groupDyadicScaleAt M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F scale)) + +def computedPhysicalCoarseDepth (source target : List ℕ) (N : ℕ) + (entry : OAI.EditApproximation.PhysicalEntry (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length) : ℕ := + OAI.EditApproximation.computedCoarseDepth N (OAI.EditApproximation.coarseEntryWidth (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi)) + +abbrev PhysicalScalarKey (M J N n exponent F Q R B : ℕ) := + Σ key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B, OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key + +instance physicalScalarIndexFintype (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : + Fintype (OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key) := by + cases key <;> dsimp only [OAI.EditApproximation.PhysicalScalarIndex] <;> infer_instance + +def physicalScalarRange (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key.1 with + | .inl online => online.2.val.val + | .inr _ => M + +instance physicalScalarRangeNeZero (M J N n exponent F Q R B : ℕ) [NeZero M] + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + NeZero (OAI.EditApproximation.physicalScalarRange M J N n exponent F Q R B key) := by + rcases key with ⟨key, index⟩ + cases key <;> dsimp only [OAI.EditApproximation.physicalScalarRange] <;> infer_instance + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def queryGroupSourceGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + +def physicalScalarCodeWithWork {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ × ℕ := + match key with + | ⟨.inl online, time⟩ => + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (online.1.1.val, online.1.2.2) + let first := OAI.EditApproximation.naturalPairWithWork online.2.val.val time.val + let second := OAI.EditApproximation.naturalPairWithWork online.1.2.1.val first.1 + let last := OAI.EditApproximation.naturalPairWithWork entry.1 second.1 + (2 * last.1, entry.2 + first.2 + second.2 + last.2 + 2) + | ⟨.inr group, index⟩ => + let node := OAI.EditApproximation.physicalNodeCodeWithWork group.1.val + let a := OAI.EditApproximation.naturalPairWithWork index.2.1.val index.2.2.val + let b := OAI.EditApproximation.naturalPairWithWork index.1.val a.1 + let c := OAI.EditApproximation.naturalPairWithWork group.2.2.2.val b.1 + let d := OAI.EditApproximation.naturalPairWithWork group.2.2.1.val c.1 + let e := OAI.EditApproximation.naturalPairWithWork group.2.1.val d.1 + let f := OAI.EditApproximation.naturalPairWithWork node.1 e.1 + (2 * f.1 + 1, node.2 + a.2 + b.2 + c.2 + d.2 + e.2 + f.2 + 3) + +def physicalScalarCodeAllocation {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, _⟩ => 2 * online.1.1.val.1.val + J + 20 + | ⟨.inr group, _⟩ => 2 * group.1.val.1.val + J + 25 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +abbrev PhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) + +def physicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + if hb : key.1 ∈ OAI.EditApproximation.dyadicScales N then + if hr : 0 < range ∧ range ≤ B then + .read ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 hb, key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range hr.1 hr.2), time⟩ .done + else .done 0 + else .done 0 + +def physicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => .read ⟨.inr key, ⟨time, scale, sample⟩⟩ .done + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +abbrev BitPhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction + +def queryPhysicalScalarRead (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalScalarCodeWithWork key).2 + 1) (.read key .done) + +def queryPhysicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inr key, ⟨time, scale, sample⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def dyadicUnskippedGroupEstimate (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : ℚ := + OAI.EditApproximation.unskippedGroupEstimate (OAI.EditApproximation.groupDyadicScaleAt M b F) + (fun scale => OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) value member draw + +def chooseUnskippedGroup (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (members : List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hnonempty : members ≠ []) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial := + OAI.EditApproximation.selectGroupMember members hnonempty (fun member => OAI.EditApproximation.dyadicUnskippedGroupEstimate Q value member draw) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def chooseCellGroupAction {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent Q : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + Option (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) := + let members := OAI.EditApproximation.cellUnskippedBands source target parent b P F thetaExponent tau a parentInitial child initial cell + if h : members = [] then none else some (OAI.EditApproximation.chooseUnskippedGroup Q value members h draw).rationalAction + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M : ℕ} (source target : List α) (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) (parentInitial : TargetInterval target.length → ℚ) (child initial current : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalGroupCones_8) "theta" => (2 : ℚ) ^ (-(exponent : ℤ)) + +def localCellGroupActions (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (parentInitial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * parentInitial q)).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells (theta * b) ⌈parentInitial q⌉₊ q).filterMap fun cell => + OAI.EditApproximation.chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell (draw b cell) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localRefinementStepQuery : OAI.EditApproximation.FiniteQuery ι := by + have proof_mixedRadix_injective_84 {radix : ℕ} {lo : ℕ} {lo' : ℕ} {hi : ℕ} {hi' : ℕ} (hlo : LT.lt.{0} lo radix) (hlo' : LT.lt.{0} lo' radix) (heq : Eq.{1} (HAdd.hAdd.{0, 0, 0} lo (HMul.hMul.{0, 0, 0} radix hi)) (HAdd.hAdd.{0, 0, 0} lo' (HMul.hMul.{0, 0, 0} radix hi'))) : lo = lo' ∧ hi = hi' := by + have hmod := congrArg (fun n => n % radix) heq + simp only [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlo, Nat.mod_eq_of_lt hlo'] at hmod + refine ⟨hmod, ?_⟩ + apply Nat.mul_left_cancel (by omega : 0 < radix) + omega + have proof_childInputCode_injective_83 (M : ℕ) (n : ℕ) : + Function.Injective (@OAI.EditApproximation.childInputCode M n) := by + rintro ⟨i, q⟩ ⟨i', q'⟩ heq + obtain ⟨hi, hq⟩ := proof_mixedRadix_injective_84 i.isLt i'.isLt heq + have hqlo : q.lo < n + 1 := by have := q.ordered.trans q.valid; omega + have hqlo' : q'.lo < n + 1 := by have := q'.ordered.trans q'.valid; omega + obtain ⟨hlo, hhi⟩ := proof_mixedRadix_injective_84 hqlo hqlo' hq + have hqeq : q = q' := by cases q; cases q'; cases hlo; cases hhi; rfl + exact Prod.ext (Fin.ext hi) hqeq + have proof_historyInputCode_injective_82 (M : ℕ) (n : ℕ) : + Function.Injective (OAI.EditApproximation.historyInputCode (M := M) (n := n)) := by + rintro ⟨i, s, q⟩ ⟨i', s', q'⟩ heq + have h := Nat.pair_eq_pair.mp heq + have hc := proof_childInputCode_injective_83 M n h.2 + cases hc + cases h.1 + rfl + exact + let earlierKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.historyInputCode (proof_historyInputCode_injective_82 M target.length) + (OAI.EditApproximation.queryEarlierInputCover parent N P F exponent t a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readEarlier earlierKeys fun earlierAnswers => + let earlier := fun i s r => OAI.EditApproximation.finiteAnswerTable earlierKeys earlierAnswers (i, s, r) + let online := OAI.EditApproximation.localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q + let sharedKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) + (OAI.EditApproximation.querySharedInputCover source target parent N F exponent Q a parentInitial q draw) + OAI.EditApproximation.FiniteQuery.collect readCurrent sharedKeys fun sharedAnswers => + let current := fun i r => OAI.EditApproximation.finiteAnswerTable sharedKeys sharedAnswers (i, r) + let selected := OAI.EditApproximation.localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q + let needed := OAI.EditApproximation.actionCurrentInputCover selected ∪ OAI.EditApproximation.actionCurrentInputCover online + let currentKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) needed + OAI.EditApproximation.FiniteQuery.collect readCurrent currentKeys fun currentAnswers => + let value := OAI.EditApproximation.rationalActionValue (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.finiteAnswerTable currentKeys currentAnswers) q + let fallback := OAI.EditApproximation.rationalBellman parentInitial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent (OAI.EditApproximation.localRefinementRepresentatives N P F a parentInitial q) P) + (fun input => earlier input.1 (t - 1) input.2) q + .done (OAI.EditApproximation.rationalRefinementUpdate delta (OAI.EditApproximation.rationalMinimum fallback (selected.map value)) + (OAI.EditApproximation.rationalOnlineMinimum (online.map value))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localOnlineSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.localOnlineSourceKeys N P F a parentInitial q + OAI.EditApproximation.FiniteQuery.collect + (fun key => readInteger key (OAI.EditApproximation.keyedOnlineSourceRange source target parent P exponent H tau child key)) + keys fun values => + OAI.EditApproximation.localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw (fun b r => ⌊OAI.EditApproximation.finiteAnswerTable keys values (b, r)⌋₊) q + readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {β : Type u_2} {α : Type u_3} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : BinaryFraction) (t : ℕ) (initial : TargetInterval target.length → BinaryFraction × ℕ) (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + +def queryRefinementGather : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q)).bind + fun earlierKeys => OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys fun earlierWords => + (OAI.EditApproximation.BitQuery.compute (online earlierKeys earlierWords)).bind fun onlineActions => + let word := initial q + .charge word.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent + eM eF hM hF parent a word.1 q draw)).bind fun sharedKeys => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys fun sharedWords => + (OAI.EditApproximation.BitQuery.compute (selected sharedKeys sharedWords)).bind fun selectedActions => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun currentKeys => OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + (next earlierKeys earlierWords selectedActions onlineActions currentKeys)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a delta : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) (t : ℕ) (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) (query : TargetInterval ny) + +def queryRefinementFinishWithWork : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let result := OAI.EditApproximation.BinaryFraction.physicalContinuationReadWithWork parent representatives.1 P F delta fallback.1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + groups online query + (result.1, fallback.2 + representatives.2 + result.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.groupScalarKeys M F Q (OAI.EditApproximation.localGroupQueryKeys N F exponent a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readGroup keys fun values => + OAI.EditApproximation.localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial (OAI.EditApproximation.groupDrawFromValues keys values) q readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomBandDataQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.refinementBandInputList (M := M) parent N P F exponent a parentInitial q + OAI.EditApproximation.FiniteQuery.collect readMass keys fun massValues => + OAI.EditApproximation.FiniteQuery.collect readInitial keys fun initialValues => + OAI.EditApproximation.localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial (fun i r => OAI.EditApproximation.finiteAnswerTable keys massValues (i, r)) + (fun i r => OAI.EditApproximation.finiteAnswerTable keys initialValues (i, r)) q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (readParentInitial : TargetInterval target.length → FiniteQuery ι) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomDataQuery : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (readParentInitial q) fun value => + let keys := OAI.EditApproximation.refinementInitialSupport N P F exponent a value q + OAI.EditApproximation.FiniteQuery.collect readParentInitial keys fun initialValues => + OAI.EditApproximation.localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + (OAI.EditApproximation.finiteAnswerTable keys initialValues) readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J N n exponent F Q R B : ℕ} + +def physicalScalarCode (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, time⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalEntryCode (online.1.1.val, online.1.2.2)) + (Nat.pair online.1.2.1.val (Nat.pair online.2.val.val time.val)) + | ⟨.inr group, index⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalNodeCode group.1.val) + (Nat.pair group.2.1.val (Nat.pair group.2.2.1.val (Nat.pair group.2.2.2.val + (Nat.pair index.1.val (Nat.pair index.2.1.val index.2.2.val))))) + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] +open MeasureTheory ProbabilityTheory + +def physicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : b ∈ OAI.EditApproximation.dyadicScales N then + if hc : cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b hb, + ⟨cell.1, Nat.lt_succ_of_le hc.1⟩, ⟨cell.2, Nat.lt_succ_of_le hc.2⟩) + Eq.mp (congrArg (OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b hb)) (OAI.EditApproximation.physicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done 0 + else fun _ _ => .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +def physicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + OAI.EditApproximation.physicalScalarGroupQueries M J N n exponent F Q R B node time key.1.1 key.1.2 key.2.1 key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → FiniteQuery σ) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (q : TargetInterval target.length) + +noncomputable def physicalRandomDataRequestQuery : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) := + OAI.EditApproximation.localRandomDataQuery source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q tau a eta kappa delta t + (fun r => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementMassQuery pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readGroup key)) + (fun key range => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readInteger key range)) q + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementEarlierQuery pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementCurrentQuery pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type*} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +def physicalInactiveGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S} := + if request.index ≤ T then + OAI.EditApproximation.physicalWarmupRequestQuery source target N P F (factor request.pass) + request.pass request.copy T S request.index request.node request.state + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor request.pass) + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) (request.node, request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) := by + by_cases hactive : T < request.index ∧ request.node.1.val < J ∧ + ¬ (OAI.EditApproximation.physicalSourceInterval source.length request.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length request.node).lo ≤ 1 + · have ht : 0 < request.index - T := Nat.sub_pos_of_lt hactive.1 + have hrequest : OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node + T (request.index - T) request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + let node : OAI.EditApproximation.PhysicalInternalNode M J := ⟨request.node, hactive.2.1⟩ + let time : Fin R := Fin.ofNat R (request.index - T - 1) + exact OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => ⟨child.val, by simpa only [hrequest] using child.property⟩)) + (OAI.EditApproximation.physicalRandomDataRequestQuery source target N P F exponent H Q tau + (OAI.EditApproximation.refinementFactor (factor request.pass) F) eta kappa delta request.pass request.copy T S + (request.index - T) ht request.node hactive.2.1 + (readGroup request.pass request.copy node time) + (readInteger request.pass request.copy node time) request.state) + · exact OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInactiveGlobalQuery source target N P F T S copies factor multiplier initial request) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest + + +def entryCapacity (M J n : ℕ) : ℕ := (n + 1) ^ 2 * (M ^ J * (J + 1)) + +def code {M J n : ℕ} (copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.index + (T + S + 1) * (request.copy + copies * + (OAI.EditApproximation.physicalEntryCode (request.node, request.state) + OAI.EditApproximation.PhysicalTableRequest.entryCapacity M J n * request.pass)) + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} (tableRank : κ → ℕ) (supported : κ → Prop) + +def supportedChild (parent : κ) : Sum σ {key : κ // tableRank key < tableRank parent} → Prop + | .inl _ => True + | .inr table => supported table.val + +def supportedChildMap (parent : {key : κ // supported key}) : + {key : Sum σ {key : κ // tableRank key < tableRank parent.val} // + OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val key} → + Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val} + | ⟨.inl source, _⟩ => .inl source + | ⟨.inr table, hs⟩ => .inr ⟨⟨table.val, hs⟩, table.property⟩ + +noncomputable def restrictBody + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (parent : {key : κ // supported key}) : + OAI.EditApproximation.FiniteQuery (Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val}) := by + classical + exact OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.supportedChildMap tableRank supported parent) + (OAI.EditApproximation.FiniteQuery.restrict (OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val) (tableBody parent.val)) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomBoundedQuery + (request : {request : OAI.EditApproximation.PhysicalTableRequest M J target.length // request.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.Bounded passes copies T S} // child.val.combinedRank T S < request.val.combinedRank T S}) := + OAI.EditApproximation.SourceRanked.restrictBody (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) + (OAI.EditApproximation.physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger initial) request + +noncomputable def chargedRandomGlobalQuery + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank}) := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + exact + match request with + | .inl entry => .done (initial entry) + | .inr parent => + if parent.val.index ≤ T then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr (OAI.EditApproximation.chargedWarmupQuery source target N P F factor multiplier parent) + else if parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + else OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩)) + (OAI.EditApproximation.physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial parent) + else OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + +abbrev PhysicalFamilyScalarKey := Fin (passes + 1) × Fin (copies + 1) × + OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + +abbrev PhysicalFamilyScalarDraw := ∀ key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies, + Fin (OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) +variable (draw : PhysicalFamilyScalarDraw + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + +def physicalFamilyAnswer (key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) : ℚ := + (draw key).val + +def physicalFamilyGroupRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + +def physicalFamilyOnlineRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +abbrev QueryFamilyMemoKey := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) + +def queryFamilySourceWordWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : OAI.EditApproximation.BinaryFraction × ℕ := + (OAI.EditApproximation.BinaryFraction.nat (draw key).val, Nat.size (draw key).val + 3) + +def queryFamilyMemoRemaining : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q → ℕ + | .inl _ => 0 + | .inr request => OAI.EditApproximation.chargedPhysicalRemaining request + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +abbrev ComputedFamilySeed (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ClampedPhysicalSeed (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length N + +abbrev ComputedFamilyDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +abbrev ComputedFamilyInput (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedFamilySeed source target N × OAI.EditApproximation.ComputedFamilyDraw source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyEncoding_3) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies + +def physicalFamilyCode (key : Key) : ℕ := + Nat.pair key.1.val (Nat.pair key.2.1.val (OAI.EditApproximation.physicalScalarCode key.2.2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def code {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => 2 * OAI.EditApproximation.physicalEntryCode entry + | .inr request => 2 * OAI.EditApproximation.PhysicalTableRequest.code copies T S request.val + 1 + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev ComputedFamilyScalarKey (source target : List ℕ) (N R : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarKey (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := R) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +def computedFamilyMemoCode (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ := + OAI.EditApproximation.SourceRanked.keyCode + (OAI.EditApproximation.physicalFamilyCode target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + OAI.EditApproximation.ChargedPhysicalRequest.code + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +def coarseInitialCandidate {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + 2 * (OAI.EditApproximation.coarseThresholdEstimate k Q lam + (OAI.EditApproximation.coarseTargetFrame k (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) y)) + (OAI.EditApproximation.coarseEntryTree B D x y) draws k 0 (OAI.EditApproximation.coarseRootShift k) + k) + +def coarseInitialMinimum {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + univ.inf' univ_nonempty (fun i => OAI.EditApproximation.coarseInitialCandidate B D Q lam x y i (draws i)) + +def coarseInitialValue {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then min N y.length + else if x = y then 0 + else min N ⌈OAI.EditApproximation.coarseInitialMinimum B D Q lam x y draws⌉₊ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveArrayWork {B : ℕ} {α : Type u} (k : ℕ) (Q lam : ℚ) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => B * (2 * k + 1) + | .branch children, (draws, below) => + B * (2 * k + 1) + + OAI.EditApproximation.coarseActiveChildrenWork Q lam allowance (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseFullSeedTable (N B : ℕ) {I : Type u_1} {α : Type u_2} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) + (draws : OAI.EditApproximation.CoarseFullSeedDraws B depth x y) : I → ℕ := + fun i => OAI.EditApproximation.coarseInitialValue B (depth i) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) N (x i) (y i) (draws i) + +def coarseInitialArrayWork {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseActiveArrayWork (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) Q lam + (OAI.EditApproximation.coarseEntryTree B D x y) (draws i) (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter +open scoped Topology + +def integerEqualWithWork : List ℤ → List ℤ → Bool × ℕ + | [], [] => (true, 1) + | [], _ :: _ => (false, 1) + | _ :: _, [] => (false, 1) + | x :: xs, y :: ys => + if x = y then + let tail := integerEqualWithWork xs ys + (tail.1, tail.2 + 1) + else (false, 1) + +def integerPreprocessingWork (source target : List ℤ) : ℕ := + (OAI.EditApproximation.integerInputInspectionWithWork source target).2 + + (OAI.EditApproximation.encodeIntegerSymbolsWithWork source).2 + (OAI.EditApproximation.encodeIntegerSymbolsWithWork target).2 + + (OAI.EditApproximation.integerOccurrenceBuildWithWork source target).2 + (OAI.EditApproximation.integerEqualWithWork source target).2 + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +abbrev ComputedFamilyMemoKey (source target : List ℕ) (N : ℕ) := + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.ComputedFamilyTableKey source target N) + +def integerPreevaluationWork (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.integerPreprocessingWork source target + OAI.EditApproximation.globalParameterWork N + + (OAI.EditApproximation.physicalLargeInputWithWork N epsilon).2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) + +def physicalFamilyCodeWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ × ℕ := + let scalar := OAI.EditApproximation.physicalScalarCodeWithWork key.2.2 + let copy := OAI.EditApproximation.naturalPairWithWork key.2.1.val scalar.1 + let pass := OAI.EditApproximation.naturalPairWithWork key.1.val copy.1 + (pass.1, scalar.2 + copy.2 + pass.2 + 2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedFamilyMemoCodeWithWork (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ × ℕ + | .inl key => + let result := OAI.EditApproximation.physicalFamilyCodeWithWork target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) key + (2 * result.1, result.2 + 2) + | .inr key => let result := OAI.EditApproximation.chargedPhysicalCodeWithWork key + (2 * result.1 + 1, result.2 + 3) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true then + if hc : (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb), + ⟨cell.1, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).1⟩, + ⟨cell.2, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).2⟩) + Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb))) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +def queryPhysicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1.1).2 + + (OAI.EditApproximation.queryCellValidWithWork n exponent key.1.2).2 + 2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time + key.1.1 key.1.2 key.2.1 key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset + +def queryPhysicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + exact + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1).2 + (OAI.EditApproximation.queryRangeValidWithWork B range).2 + 2) + (if hb : (OAI.EditApproximation.queryScalePresentWithWork N key.1).1 = true then + if hr : (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true then + OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 ((proof_queryScalePresentWithWork_value_101 N key.1).mp hb), key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range ((proof_queryRangeValidWithWork_value_107 B range).mp hr).1 + ((proof_queryRangeValidWithWork_value_107 B range).mp hr).2), time⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0) + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagWithWork + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : + OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies × ℕ := + let p := OAI.EditApproximation.queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _) + let c := OAI.EditApproximation.queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _) + let key := (p.1, c.1, scalar) + (key, p.2 + c.2 + (OAI.EditApproximation.physicalFamilyCodeWithWork target N P F exponent H Q passes copies key).2 + 1) + +def queryFamilyGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key) + +def queryFamilyOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +abbrev QueryPhysicalChild := Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J n // + child.combinedRank T S < parent.val.combinedRank T S} + +def querySupportedChildWithWork (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : Bool × ℕ := + match key with + | .inl _ => (true, 1) + | .inr child => OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S child.val + +def queryRestrictPhysicalBody (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery (Sum σ {child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (OAI.EditApproximation.SourceRanked.supportedChildMap (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent key, 1)) + (OAI.EditApproximation.BitQuery.restrictWithWork + (OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val) + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent) + (proof_querySupportedChildWithWork_value_108 passes copies T S parent) program) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type*} (source target : List α) (N P F : ℕ) (A a : BinaryFraction) (reader : TargetInterval target.length → BitQuery ι BinaryFraction) (q : TargetInterval target.length) + +def queryInitialConeProgramAt {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind fun keys => + OAI.EditApproximation.BitQuery.collect reader keys fun words => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (OAI.EditApproximation.BinaryFraction.queryInitialSeedReadWithWork value q keys words) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +def queryChargedRead + (key : {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)}) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.chargedPhysicalCodeWithWork key.val).2 + 1) (.read key .done) + +def queryChargedPreviousRead (hp : 0 < parent.val.pass) (q : OAI.EditApproximation.TargetInterval n) (copy : Fin copies) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr (OAI.EditApproximation.chargedPreviousPass parent q copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).2⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) +open Finset + +def queryChargedSeedAt (N : ℕ) (multiplier : ℕ → ℕ) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).2 + 1) + (if hp : (OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).1 = true then + OAI.EditApproximation.queryChargedRead parent ⟨.inl (parent.val.node, q), proof_coarse_rank_lt_100 _ parent rfl⟩ + else .charge (copies + 1) + (OAI.EditApproximation.BitQuery.collect (OAI.EditApproximation.queryChargedPreviousRead parent + (Nat.pos_of_ne_zero (fun h => hp ((proof_naturalEqualWithWork_value_74 _ _).mpr h))) q) + (List.finRange copies) fun words => OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N (multiplier (parent.val.pass - 1)) words))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (q : TargetInterval target.length) + +def queryPhysicalInitial : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 2) + (if test.1 then + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryIndexedSliceWithWork source interval target.length q + occurrence symbolBits positionBits) + else OAI.EditApproximation.queryInitialConeProgramAt (OAI.EditApproximation.bitWordValue length.1) N P F A a + (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a : BinaryFraction) (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) (q : TargetInterval ny) + +def queryWarmupProgram : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (initialRead q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind fun centers => + OAI.EditApproximation.BitQuery.collect initialRead centers fun words => + let initial := OAI.EditApproximation.BinaryFraction.queryOverrideParentReadWithWork value q centers words + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun inputs => OAI.EditApproximation.BitQuery.collect childRead inputs fun childWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J ny passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) (input : Fin M × TargetInterval ny) + +def queryChargedWarmupChild : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) +open Finset + +def queryChargedWarmup : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).2 + 1) + (if hz : (OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).1 = true then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state + else .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1) + (if hb : (OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 1) + (if test.1 then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits + positionBits parent.val.state + else OAI.EditApproximation.queryWarmupProgram interval N P F a + (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits) + (OAI.EditApproximation.queryChargedWarmupChild parent ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb) + (Nat.pos_of_ne_zero (fun h => hz ((proof_naturalEqualWithWork_value_74 _ _).mpr h)))) + parent.val.state) + else OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +abbrev ChargedFamilyQueryKey (parent : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S // child.rank < parent.rank} + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {κ : Type u_1} (rank : κ → ℕ) (raw : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : κ → ℕ) + +def rankedNormalizeBody (key : κ) : + OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction := + (raw key).normalize base hbase (remaining key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) (sourceAnswer : σ → ℚ) + +noncomputable def chargedRandomMemoEvaluate (bits : ℕ) + (encode : Sum σ (OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) := + OAI.EditApproximation.rankedMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer) + bits encode (.inr request) .empty + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalFamilyProgram := + OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S (passes + 1) copies + factor multiplier tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.physicalFamilyOnlineRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + initial + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseDraw := OAI.EditApproximation.CoarseFullSeedDraws B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) +open EditDistortion Finset MeasureTheory ProbabilityTheory +open Finset MeasureTheory ProbabilityTheory + +noncomputable def physicalCoarseSeedTable (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : + OAI.EditApproximation.ClampedPhysicalSeed M J target.length N := by + have proof_coarseInitialValue_le_length_111 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) : + OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws ≤ N := by + unfold OAI.EditApproximation.coarseInitialValue + split_ifs + · exact min_le_left _ _ + · exact Nat.zero_le _ + · exact min_le_left _ _ + have proof_trans_112 {Alpha : Type u_1} {s : Bool} {m : ℕ} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} {z : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s m x y) (k : OAI.EditDistortion.Script.{u_1} s n y z) : OAI.EditDistortion.Script s (m + n) x z := by + induction h with + | nil => simpa using k + | @cons l x w y e h ih => + simpa only [Nat.add_right_comm] using OAI.EditDistortion.Script.cons e (ih k) + have proof_to_nil_113 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.Script s x.length x [] := by + induction x with + | nil => exact .nil [] + | cons a x ih => exact .cons (.delete [] x a) ih + have proof_single_114 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Script s 1 x y := + .cons h (.nil y) + have proof_symm_115 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Step s y x := by + cases h with + | insert p q a => exact .delete p q a + | delete p q a => exact .insert p q a + | substitute hs p q a b => exact .substitute hs p q b a + have proof_symm_116 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.Script s n y x := by + induction h with + | nil x => exact .nil x + | cons e h ih => exact (proof_trans_112 ih (proof_single_114 (proof_symm_115 e))) + have proof_exists_script_117 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : ∃ n, OAI.EditDistortion.Script s n x y := + ⟨x.length + y.length, (proof_trans_112 (proof_to_nil_113 x) + (proof_symm_116 (proof_to_nil_113 y)))⟩ + have proof_cost_spec_118 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : OAI.EditDistortion.Script s (OAI.EditDistortion.cost s x y) x y := + Nat.sInf_mem (proof_exists_script_117 x y) + have proof_eq_of_zero_119 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s 0 x y) : x = y := by + cases h + rfl + have proof_cost_le_120 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.cost s x y ≤ n := + Nat.sInf_le h + have proof_cost_refl_121 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.cost s x x = 0 := + Nat.eq_zero_of_le_zero (proof_cost_le_120 (.nil x)) + have proof_cost_eq_zero_iff_122 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} : OAI.EditDistortion.cost s x y = 0 ↔ x = y := by + constructor + · intro h + have hc := proof_cost_spec_118 (s := s) x y + rw [h] at hc + exact (proof_eq_of_zero_119 hc) + · rintro rfl + exact proof_cost_refl_121 _ + have proof_coarseInitialValue_zero_123 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) (hzero : Eq.{1} (OAI.EditDistortion.edit.{u_1} x y) 0) : OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws = 0 := by + have hxy : x = y := (proof_cost_eq_zero_iff_122 (s := true)).mp hzero + subst y + simp only [OAI.EditApproximation.coarseInitialValue, ite_eq_right (by omega : ¬ 2 * x.length < x.length), ite_true] + have proof_computed_fullSeedTable_range_zero_110 (N : ℕ) (B : ℕ) {I : Type 0} {α : Type u_1} [instLocal4 : DecidableEq.{u_1 + 1} α] (depth : I → ℕ) (x : I → List.{u_1} α) (y : I → List.{u_1} α) (draws : OAI.EditApproximation.CoarseFullSeedDraws.{0, u_1} B depth x y) : + ∀ i, OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i ≤ N ∧ + (OAI.EditDistortion.edit (x i) (y i) = 0 → OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i = 0) := by + intro i + exact ⟨proof_coarseInitialValue_le_length_111 _ _ _ _ _ _ _ _, + proof_coarseInitialValue_zero_123 _ _ _ _ _ _ _ _⟩ + exact + fun state => + ⟨OAI.EditApproximation.coarseFullSeedTable N B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) draw state, + Nat.lt_succ_of_le ((proof_computed_fullSeedTable_range_zero_110 N B depth _ _ draw state).1)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalTraceMemoOutput_5) "passes" => computedSeedPassCount N + +def localFinalRootRequest (hH : 0 < H) (rootQ : OAI.EditApproximation.TargetInterval target.length) : + OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S := + .inr ⟨OAI.EditApproximation.PhysicalTableRequest.refinement passes 0 + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit) T S rootQ, + ⟨Nat.lt_succ_self _, pow_pos hH 2, le_rfl⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +noncomputable def computedFamilyKernelWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (cost : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) : ℕ := + OAI.EditApproximation.rankedMemoKernelWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) cost + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyAddressWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.rankedMemoAddressWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyCoarseCopyStorage (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost + (OAI.EditApproximation.physicalCoarseInputStorage (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target)) + +noncomputable def computedFamilyCoarseArrayCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 37)) + +noncomputable def computedFamilyCoarseScratchCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 181)) + +noncomputable def computedFamilyCoarseControlCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 182)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_4) "Seed" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_8) "tau" => RationalParameters.tau (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_9) "eta" => RationalParameters.eta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_10) "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_11) "delta" => RationalParameters.delta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_12) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_13) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_14) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S + +noncomputable def physicalFamilyMemoResult (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (input : Seed × Family) := + OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) T S (passes + 1) (H ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.physicalFamilyOnlineRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.clampedSeedNat input.1) + (OAI.EditApproximation.physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes (H ^ 2) input.2) + bits encode (OAI.EditApproximation.localFinalRootRequest target N T S H hH rootQ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Finset +attribute [local instance] Classical.propDecidable + +noncomputable def selectionIndicator (p : Prop) : ℝ := if p then 1 else 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +noncomputable def coarseIndexedEntryCostSum {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) + (selected : OAI.EditApproximation.PhysicalEntry M J target.length → Prop) : ℝ := by + classical + exact ∑ entry : OAI.EditApproximation.PhysicalEntry M J target.length, OAI.EditApproximation.selectionIndicator (selected entry) * + (OAI.EditApproximation.coarseIndexedEntryBinaryCost N B (depth entry) (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + +def querySupportedChildAllocation {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : ℕ := + match key with + | .inl _ => 0 + | .inr child => OAI.EditApproximation.queryPhysicalBoundedAllocation passes copies T S child.val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] +open Finset + +noncomputable def rejectionFailureLaw (i : ι) : Measure ℕ := by + have proof_rejectionWord_range_124 (N : ℕ) (hN : LT.lt.{0} 0 N) : + N ≤ 2 ^ OAI.EditApproximation.rejectionBitCount N ∧ 2 ^ OAI.EditApproximation.rejectionBitCount N < 2 * N := by + constructor + · exact Nat.le_pow_clog (by norm_num) N + · by_cases hNone : N = 1 + · subst N + norm_num [OAI.EditApproximation.rejectionBitCount] + · have hN1 : 1 < N := by omega + have hpred := Nat.pow_pred_clog_lt_self (by norm_num : 1 < 2) hN1 + have hB := Nat.clog_pos (by norm_num : 1 < 2) hN1 + have hpow : 2 ^ OAI.EditApproximation.rejectionBitCount N = 2 ^ (Nat.clog 2 N).pred * 2 := by + rw [OAI.EditApproximation.rejectionBitCount, ← pow_succ] + congr 1 + exact (Nat.succ_pred_eq_of_pos hB).symm + rw [hpow] + omega + exact + geometricMeasure (OAI.EditApproximation.rejectionSuccessParameter (range i) (2 ^ OAI.EditApproximation.rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (proof_rejectionWord_range_124 (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionRuntimeArrayLaw : Measure (OAI.EditApproximation.RejectionRuntimeArray range) := + (Measure.pi (OAI.EditApproximation.rejectionFailureLaw range)).prod (OAI.EditApproximation.rejectionAcceptedLaw range) + +noncomputable def rejectionSelectedBits + (selected : ι → (∀ i, Fin (range i)) → Prop) (execution : OAI.EditApproximation.RejectionRuntimeArray range) : ℝ := + ∑ i, (((execution.1 i : ℝ) + 1) * OAI.EditApproximation.rejectionBitCount (range i)) * + OAI.EditApproximation.selectionIndicator (selected i execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} {M J R : ℕ} [NeZero M] (target : List α) (N P F exponent H Q passes copies : ℕ) + +abbrev physicalFamilyRange (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ := + OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + +instance physicalFamilyRange_neZero (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : + NeZero (OAI.EditApproximation.physicalFamilyRange target N P F exponent H Q passes copies key) := by + exact OAI.EditApproximation.physicalScalarRangeNeZero M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +abbrev ComputedPhysicalCoarseDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalCoarseDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +abbrev ComputedRejectionRuntime (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + +noncomputable def computedPhysicalCoarseLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N) := + OAI.EditApproximation.coarseFullSeedMeasure (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (fun entry => OAI.EditApproximation.physicalSource source entry.1) + (fun entry => OAI.EditApproximation.substring target entry.2.lo entry.2.hi) + +abbrev ComputedExecutionOutcome (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N × OAI.EditApproximation.ComputedRejectionRuntime source target N + +noncomputable def computedExecutionLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedExecutionOutcome source target N) := + (OAI.EditApproximation.computedPhysicalCoarseLaw source target N).prod + (OAI.EditApproximation.rejectionRuntimeArrayLaw (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2))) + +abbrev ComputedFullOutcome (source target : List ℕ) (N : ℕ) := + Unit ⊕ OAI.EditApproximation.ComputedExecutionOutcome source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_8) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_9) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +abbrev PhysicalFamilyRuntimeOutcome := SeedState × OAI.EditApproximation.RejectionRuntimeArray FamilyRange + +def physicalFamilyRuntimeAccepted + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H) : SeedState × Family := + (execution.1, execution.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Filter + +def physicalLargeInput (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Prop := + (OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon).1.isSome = true ∧ + OAI.EditApproximation.largeAccuracyInput N epsilon.value ∧ + Nat.size (OAI.EditApproximation.localOnlineMassBound (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N)) ≤ OAI.EditApproximation.inputHeight N + +instance physicalLargeInput_decidable (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Decidable (OAI.EditApproximation.physicalLargeInput N epsilon) := inferInstanceAs (Decidable (_ ∧ _ ∧ _)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_8) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_9) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_10) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +noncomputable def physicalFamilyMemoBits (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (seed : SeedState) + (execution : OAI.EditApproximation.RejectionRuntimeArray FamilyRange) : ℝ := + OAI.EditApproximation.rejectionSelectedBits FamilyRange (fun key accepted => Sum.inl key ∈ + (OAI.EditApproximation.physicalFamilyMemoResult source target N P T S H hH bits encode rootQ (seed, accepted)).freshKeys) + execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyResult (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.physicalFamilyMemoResult source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.finalTargetState target.length) input + +noncomputable def computedFamilyRejectionWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)) : ℝ := + OAI.EditApproximation.physicalFamilyMemoBits source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) (OAI.EditApproximation.finalTargetState target.length) + execution.1 execution.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (B : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyMemoCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.coarseInitialArrayWork B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseExecution := OAI.EditApproximation.PhysicalCoarseDraw source target B depth × + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := M) (J := J) (R := R) + target N P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) H + (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (H ^ 2)) + +noncomputable def physicalCoarseExecutionProjection + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N P H B depth) : + OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H := + (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth execution.1, execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def computedExecutionProjection (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.physicalCoarseExecutionProjection (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).B + (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +noncomputable def computedFullLaw (source target : List ℕ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Measure (OAI.EditApproximation.ComputedFullOutcome source target N) := + if OAI.EditApproximation.physicalLargeInput N epsilon then (OAI.EditApproximation.computedExecutionLaw source target N).map Sum.inr + else Measure.dirac (Sum.inl ()) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionAccepted (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : OAI.EditApproximation.ComputedFamilyInput source target N := + OAI.EditApproximation.physicalFamilyRuntimeAccepted target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.computedExecutionProjection source target N execution) + +noncomputable def computedExecutionRejectionWork (source target : List ℕ) (N : ℕ) : + OAI.EditApproximation.ComputedExecutionOutcome source target N → ℝ := + OAI.EditApproximation.computedFamilyRejectionWork source target N ∘ OAI.EditApproximation.computedExecutionProjection source target N + +def computedFinalRoot (source target : List ℕ) (N : ℕ) : OAI.EditApproximation.ComputedFamilyTableKey source target N := + OAI.EditApproximation.localFinalRootRequest (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target N + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (OAI.EditApproximation.finalTargetState target.length) + +noncomputable def computedExecutionKernelWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + let input := OAI.EditApproximation.computedExecutionAccepted source target N execution + OAI.EditApproximation.computedFamilyKernelWork source target N input (cost input) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionDictionaryWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + (OAI.EditApproximation.computedFamilyResult source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution)).dictionaryVisits + +noncomputable def computedExecutionAddressWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyAddressWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedCoarseWork := + fun draw => OAI.EditApproximation.physicalFamilyMemoCoarseWork source target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + draw B depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) + +noncomputable def symbolicComputedExecutionCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.symbolicComputedCoarseWork source target N depth encode execution.2.2 execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionNonlocalWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionRejectionWork source target N execution + + OAI.EditApproximation.computedExecutionDictionaryWork source target N execution + + OAI.EditApproximation.computedExecutionAddressWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyIndexedCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + OAI.EditApproximation.coarseIndexedEntryCostSum source target N depth coarse + (fun entry => Sum.inr (Sum.inl entry) ∈ result.freshKeys) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionIndexedCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyIndexedCoarseWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionIndexedCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionIndexedCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarseSamplingWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + ((Nat.size B * OAI.EditApproximation.coarseInitialLabelCount B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℕ) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionCoarseSamplingWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyCoarseSamplingWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseSamplingWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseSamplingWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarsePreparationWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) : ℝ := + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.physicalCoarsePreparationCost source target entry : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℝ := + OAI.EditApproximation.physicalFamilyCoarsePreparationWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1) input.2 (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.computedFinalRoot source target N) + +noncomputable def computedExecutionCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyCoarsePreparationWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + +noncomputable def computedExecutionReadChargedWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionIndexedCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionCoarseSamplingWork source target N execution + + OAI.EditApproximation.computedExecutionNonlocalWork source target N execution + + OAI.EditApproximation.computedExecutionCoarsePreparationWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionTotalWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionReadChargedWork source target N execution + + OAI.EditApproximation.computedExecutionKernelWork source target N cost execution + +noncomputable def computedFullOutputWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (setup : ℝ) (shared : ℕ) (output : OAI.EditApproximation.ComputedFamilyInput source target N → ℕ) + (fallbackOutput : ℕ) : OAI.EditApproximation.ComputedFullOutcome source target N → ℝ + | .inl _ => setup + (OAI.EditApproximation.chargedSuffixDP source target).2 + fallbackOutput + | .inr execution => setup + shared + OAI.EditApproximation.computedExecutionTotalWork source target N cost execution + + output (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagAllocation + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation pass (passes + 1) + OAI.EditApproximation.binaryNaturalDivAllocation copy (copies + 1) + + OAI.EditApproximation.physicalScalarCodeAllocation scalar + 9 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def rankedBitMemoCells {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (heap : ∀ key, OAI.EditApproximation.BitQuery.Footprint (program key)) + (bits : ℕ) (encode addressCells : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : ℕ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some _ => OAI.EditApproximation.memoRequestCells bits (addressCells key) + | none => OAI.EditApproximation.memoRequestCells bits (addressCells key) + (heap key).runCells + (fun child previous => OAI.EditApproximation.rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedBitMemoCells rank program heap bits encode addressCells child.val previous) + memory +termination_by rank key +decreasing_by exact child.property + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery + +local instance queryArityNeZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨by change 2 ^ (OAI.EditApproximation.heightExponent N / 20) ≠ 0; exact Nat.ne_of_gt (Nat.two_pow_pos _)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryInitialGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.TargetInterval n) → (reader key).Footprint) + (next : List (OAI.EditApproximation.TargetInterval n) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.TargetInterval n)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryInitialGather N P F exponent hP a q reader next).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q) + (OAI.EditApproximation.BinaryFraction.queryInitialSupportAllocation N P F exponent hP a value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys) + +def queryBandGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny : ℕ} + (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (massReader key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (initialReader key).Footprint) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) → + (mass words : List OAI.EditApproximation.BinaryFraction) → (next keys mass words).Footprint) : (OAI.EditApproximation.queryBandGather M parent N P F exponent hP a initial q massReader initialReader next).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q) + (OAI.EditApproximation.BinaryFraction.queryBandInputsAllocation M parent N P F exponent hP a initial allocation + q)).bind + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect massReader keys fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect massReader hm keys + (fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.collect initialReader hi keys (next keys mass) (hn keys mass) + +def queryGroupSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (reader key).Footprint) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 + q) + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysAllocation M N F Q exponent eM eF hM hF a + (initial q).1 q)).bind + (fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys)) + +def queryOnlineSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) + (hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (reader : ℕ × OAI.EditApproximation.TargetInterval ny → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : ℕ × OAI.EditApproximation.TargetInterval ny) → (range : ℕ) → (reader key range).Footprint) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (initialAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a (initial q).1 q) + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q)).bind + (fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + keys (next keys)) + fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key) + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeAllocation parent P exponent H tau child + childAllocation key)).bind + (reader key) (hr key)) + keys (next keys) (hn keys)) + +def queryPhysicalTableReadFootprint + {M J n : ℕ} + (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S r < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent }) : (OAI.EditApproximation.queryPhysicalTableRead copies T S parent child).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalTableCodeAllocation (M := M) (J := J) (n := n) child.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read child OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryMeanReadFootprint + {ι : Type u_1} + (count : ℕ) + (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (i : Fin count) → (reader i).Footprint) : (OAI.EditApproximation.queryMeanRead count reader).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf count + (OAI.EditApproximation.BitQuery.Footprint.collect reader hr (List.ofFn fun (i : Fin count) => i) + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words) + (OAI.EditApproximation.BinaryFraction.sumListAllocation words + + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1.divAllocation + (OAI.EditApproximation.BinaryFraction.nat count) + + count.size)) + +def queryPhysicalScalarReadFootprint + (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : (OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalScalarCodeAllocation key + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryRestrictPhysicalBodyFootprint + {σ : Type u_1} + {M J n : ℕ} + (passes copies T S : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) + OAI.EditApproximation.BinaryFraction) + (heap : program.Footprint) : (OAI.EditApproximation.queryRestrictPhysicalBody passes copies T S parent program).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + (heap.restrictWithWork _ _ (proof_querySupportedChildWithWork_value_108 passes copies T S parent) + (OAI.EditApproximation.querySupportedChildAllocation passes copies T S parent) + ).mapKeysWithWork _ (fun _ => 1) + +def queryInitialConeProgramAtFootprint + {ι : Type u_1} + {n : ℕ} + (sourceLength N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (hr : (r : OAI.EditApproximation.TargetInterval n) → (reader r).Footprint) : (OAI.EditApproximation.queryInitialConeProgramAt sourceLength N P F A a reader q).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q) + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersAllocation N P A value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q) + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadAllocation + (value.queryInitialSeedReadWithWork q keys words) (value.queryInitialSeedReadAllocation q keys words) + sourceLength N P F A a q) + +def queryChargedReadFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (key : { child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) }) : (OAI.EditApproximation.queryChargedRead parent key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.chargedPhysicalCodeAllocation (M := M) (J := J) (n := n) (passes := passes) (copies := copies) (T := T) (S := S) key.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryWarmupProgramFootprint + {ι : Type u_1} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) + (a : OAI.EditApproximation.BinaryFraction) + (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval ny) + (hi : (r : OAI.EditApproximation.TargetInterval ny) → (initialRead r).Footprint) + (hc : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (childRead key).Footprint) : (OAI.EditApproximation.queryWarmupProgram parent N P F a initialRead childRead q).Footprint := +(hi q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q) + (OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q)).bind + (fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect initialRead hi centers + (fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + let initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + let allocation : OAI.EditApproximation.TargetInterval ny → ℕ := + OAI.EditApproximation.BinaryFraction.queryOverrideParentReadAllocation q centers words; + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q) + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsAllocation M parent N P F a initial allocation + q)).bind + (fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect childRead hc inputs + (fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q) + (OAI.EditApproximation.BinaryFraction.localWarmupReadAllocation parent N P F a initial allocation + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadAllocation inputs childWords input.1 input.2) + q) + +def queryPhysicalEarlierReadFootprint + {M J n : ℕ} + (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (input.2.1.bits.length + t.bits.length) ?_ + split + · exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryPhysicalScalarOnlineReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) + (range : ℕ) : (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range).Footprint := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.1 + OAI.EditApproximation.queryRangeValidAllocation B range) ?_ + split + · split + · exact OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _ + · exact .done _ + · exact .done _ + +def queryChargedSeedAtFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (N : ℕ) + (multiplier : ℕ → ℕ) + (q : OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryChargedSeedAt parent N multiplier q).Footprint := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.pass 0) ?_ + split + · exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf copies ?_ + refine OAI.EditApproximation.BitQuery.Footprint.collect _ (fun _ => OAI.EditApproximation.queryChargedReadFootprint parent _) _ _ fun words => ?_ + let factor := multiplier (parent.val.pass - 1) + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N factor words) + (OAI.EditApproximation.BinaryFraction.seedMedianAllocation N factor words + + (OAI.EditApproximation.BinaryFraction.seedMedianWithWork N factor words).1.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryFamilyOnlineReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) + (range : ℕ) : (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key + range).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + +def queryPhysicalInitialFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + q).Footprint := by + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact OAI.EditApproximation.BitQuery.Footprint.computeOf _ + (OAI.EditApproximation.queryIndexedSliceAllocation source interval target.length q occurrence symbolBits positionBits) + · exact OAI.EditApproximation.queryInitialConeProgramAtFootprint _ N P F A a (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q + (OAI.EditApproximation.queryChargedSeedAtFootprint parent N multiplier) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueriesFootprint (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) (b : ℕ) (cell : ℕ × ℕ) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time b cell s j) := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + have groupTransport (b c : ℕ) (h : b = c) + (actual : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b) + (heap : ∀ s j, OAI.EditApproximation.BitQuery.Footprint (actual s j)) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + ((Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) s j) := by + cases h + exact heap + intro s j + unfold OAI.EditApproximation.queryPhysicalScalarGroupQueries + split + · rename_i hb + split + · exact groupTransport _ _ + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb)) _ + (fun _ _ => OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _) s j + · exact .done _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryPhysicalScalarGroupReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.fst.1 + + OAI.EditApproximation.queryCellValidAllocation n exponent key.fst.2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesFootprint M J N n exponent F Q R B node time key.fst.1 key.fst.2 + key.snd.fst key.snd.snd) + +def queryFamilyGroupReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryChargedWarmupFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) : (OAI.EditApproximation.queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits + positionBits).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F A a multiplier parent occurrence + symbolBits positionBits + unfold OAI.EditApproximation.queryChargedWarmup + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.index 0) ?_ + split + · exact hinit _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit _ + · apply OAI.EditApproximation.queryWarmupProgramFootprint + · exact hinit + · intro input + exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · exact hinit _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) +open Finset + +def preparedComputedCellSourceWithWorkRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let result := OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceWithWorkRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi scales.1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +def preparedLocalGroupScaleSourceWithWorkRawBand (eb : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let word := parentInitial query + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork word.1 + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let selected := OAI.EditApproximation.filterMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) cells.1 + (selected.1, word.2 + side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +def preparedLocalCellGroupsSourceWithWorkRawBand (N : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let word := parentInitial query + let groups := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a word.1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, word.2 + groups.2 + count + N.bits.length + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + +def preparedLocalOnlineScaleSourceWithWorkRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) query + let word := parentInitial center.1 + let eligible := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + if eligible.1 then + let sample := integer b center.1 + let selected := OAI.EditApproximation.BinaryFraction.preparedOnlineReadWithWorkRaw source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table R hc hi t center.1 sample.1 + (selected.1, spacing.2 + center.2 + word.2 + eligible.2 + selected.2 + sample.2 + e + 5) + else (none, spacing.2 + center.2 + word.2 + eligible.2 + e + 3) + +def preparedLocalOnlineActionsSourceWithWorkRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let word := parentInitial query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a word.1 + let selected := OAI.EditApproximation.filterMapWithWork + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) scales.1 + (selected.1, word.2 + scales.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + +def queryOnlineSelectWithWorkRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer N q + +def queryGroupSelectWithWorkRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi N draw q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (draw : CountedCellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRefinementRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF a t parentInitial draw q + readEarlier readCurrent + (fun keys words => OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer keys words q) + (fun keys words => OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw keys words q) + (fun earlierKeys earlierWords groups online currentKeys currentWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta parentInitial + t earlierKeys earlierWords groups online currentKeys currentWords q)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRandomSourcesRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a parentInitial q readGroup + fun groupKeys groupWords => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun onlineKeys onlineWords => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) + q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) +open Finset + +def queryLocalBandRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGather M parent N P F exponent hP a parentInitial q readMass readInitial + fun keys massWords initialWords => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) + (proof_queryChildReadWithWork_budget_131 keys massWords) + (proof_queryChildReadWithWork_budget_131 keys initialWords) + q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalProgramRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryInitialGather N P F exponent hP a q readParent fun keys words => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_4} {α : Type u_5} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) (q : TargetInterval target.length) + +def queryPhysicalRandomDataRequestRawBand : + OAI.EditApproximation.BitQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) + OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryLocalProgramRawBand source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (fun r => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalMassRead copies pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readGroup key)) + (fun key range => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readInteger key range)) q + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalCurrentRead copies pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} {M J R : ℕ} [NeZero M] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) (q : TargetInterval target.length) + +def queryFamilyRefinementRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (request : PhysicalTableRequest M J target.length) (hindex : T < request.index) (hbelow : request.node.1.val < J) + +def queryFamilyActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_active_request_eq_139 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + have proof_active_request_eqRawBand_138 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => ⟨child.val, by + simpa only [proof_active_request_eqRawBand_138 (target := target) (T := T) (request := request) (hindex := hindex)] using child.property⟩) key, 1)) + (OAI.EditApproximation.queryFamilyRefinementRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + +def queryFamilyBoundedActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRestrictPhysicalBody (passes + 1) copies T S parent + (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies parent.val hindex hbelow) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +def queryChargedFamilyTableRawBand + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent)) OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + let index := OAI.EditApproximation.wordLEWithWork parent.val.index.bits T.bits + .charge (index.2 + 1) + (if hi : index.1 = true then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryChargedWarmup source target N P F (A parent.val.pass) (a parent.val.pass) multiplier + parent occurrence symbolBits positionBits) + else let depth := OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J + .charge (depth.2 + 1) + (if hb : depth.1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let short := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + short.2 + 1) + (if short.1 then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state) + else OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩) + key, 1)) + (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent + (Nat.lt_of_not_ge (fun h => hi ((proof_queryNaturalLEWithWork_value_140 parent.val.index T).mpr h))) + ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb))) + else OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state))) + +def queryChargedFamilyGlobalRawBand + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q request) OAI.EditApproximation.BinaryFraction := + match request with + | .inl entry => OAI.EditApproximation.BitQuery.compute (coarse entry) + | .inr parent => OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +def queryFamilyMemoRawRawBand (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) := + OAI.EditApproximation.SourceRanked.bitBody OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse) + (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw) key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedQueryMemoNormalizedRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) → OAI.EditApproximation.BitQuery + {child : OAI.EditApproximation.ComputedFamilyMemoKey source target N // + OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank child < OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank key} + OAI.EditApproximation.BinaryFraction := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + OAI.EditApproximation.rankedNormalizeBody (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +attribute [local instance] queryRoundsNeZero + +def computedQueryMemoResultRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.rankedBitMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +def computedQueryLocalWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ := + OAI.EditApproximation.rankedBitLocalWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + +def computedQueryAnswerWithWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : List Bool × ℕ := + if source = target then ([], source.length + target.length + 1) + else let result := OAI.EditApproximation.computedQueryMemoResultRawBand source target N occurrence symbolBits positionBits input + let answer := OAI.EditApproximation.BinaryFraction.finalAnswerWithWork N result.value + (answer.1, answer.2 + source.length + target.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +def integerQueryLocalWorkRawBand (source target : List ℤ) (N : ℕ) := + OAI.EditApproximation.computedQueryLocalWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def integerBinaryOutputRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) := + OAI.EditApproximation.computedQueryAnswerWithWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def integerBinaryAnswerRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + | .inr execution => OAI.EditApproximation.bitWordValue (OAI.EditApproximation.integerBinaryOutputRawBand source target N + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).1 + else OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +open Finset + +def preparedComputedCellSourceAllocationRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : OAI.EditApproximation.cellScaleReadDraw M b Q (OAI.EditApproximation.BinaryFraction.nat F).value) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + + OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceAllocationRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) + draw parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type*} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def castGroupSourceAllocationRawBand (b : ℕ) (cell : ℕ × ℕ) : + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + Eq.mpr (congrArg (fun f => ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b f).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b f t)) → ℕ) (proof_nat_value_49 F)) (drawAllocation b cell) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def preparedLocalGroupScaleSourceAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (parentInitial query).1).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + parentAllocation query + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (parentInitial query).1 + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.filterMapAllocation (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) + (fun cell => OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) + (OAI.EditApproximation.BinaryFraction.castGroupSourceAllocationRawBand F Q drawAllocation b cell) cell) cells + eb + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) + +def localGroupSourceScaleBlockRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + +def localGroupSourceScaleBlockAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ eb) a (parentInitial query).1 + eb + + if (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).1 then + OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query + else 0 + +def preparedLocalCellGroupsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + let count := max 1 N.bits.length + parentAllocation query + count + N.bits.length + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query) (List.range count) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) (tableAllocation : ℕ → Fin M × TargetInterval target.length → ℕ) (integerAllocation : ℕ → TargetInterval target.length → ℕ) + +def preparedLocalOnlineScaleSourceAllocationRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let center := (OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (proof_seedGridSpacingWithWork_pos_85 b P hP) query).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) query + + parentAllocation center + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (parentInitial center).1 + e + + if (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (parentInitial center).1).1 then + integerAllocation b center + OAI.EditApproximation.BinaryFraction.preparedOnlineReadAllocationRaw source target parent P F exponent H b + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi + childAllocation initialAllocation tableAllocation t center (integer b center).1 + else 0 + +def preparedLocalOnlineActionsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + parentAllocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (parentInitial query).1 + + OAI.EditApproximation.filterMapAllocation + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (parentInitial query).1).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + +def queryOnlineSelectAllocationRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation keys words) + integerAllocation N q + +def queryGroupSelectAllocationRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (drawAllocation : OAI.EditApproximation.CellGroupSourceAllocations M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys words) + draw drawAllocation N q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def integerBinaryWorkRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) := + OAI.EditApproximation.computedFullOutputWork (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerQueryLocalWorkRawBand source target N) (OAI.EditApproximation.integerPreevaluationWork source target N epsilon) + (OAI.EditApproximation.computedQuerySetupWithWork N).2 (fun input => (OAI.EditApproximation.integerBinaryOutputRawBand source target N input).2) + (N + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def integerFinalAllocationRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if source.map OAI.EditApproximation.integerSymbolCode = target.map OAI.EditApproximation.integerSymbolCode then 0 else + OAI.EditApproximation.BinaryFraction.finalAnswerAllocation N + (OAI.EditApproximation.computedQueryMemoResultRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) + (OAI.EditApproximation.integerInputPositionBits target) input).value + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalRefinementFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + t parentInitial child initial R hc hi draw integer q readEarlier readCurrent).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q) + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsAllocation M parent N P F exponent t hP a parentInitial + parentAllocation q)).bind + (fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readEarlier he earlierKeys + (fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau a + eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q) + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectAllocationRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation t integer + integerAllocation earlierKeys earlierWords q)).bind + (fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun + (online : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (parentAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw) + (OAI.EditApproximation.BinaryFraction.querySharedInputsAllocation M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw drawAllocation)).bind + (fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr sharedKeys + (fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q) + (OAI.EditApproximation.BinaryFraction.queryGroupSelectAllocationRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi parentAllocation childAllocation + initialAllocation draw drawAllocation sharedKeys sharedWords q)).bind + (fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun + (groups : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.queryNeededInputsWithWork groups online) + (OAI.EditApproximation.queryNeededInputsAllocation groups online)).bind + (fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr currentKeys + (fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q) + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishAllocation parent N P F a delta + parentInitial parentAllocation t earlierKeys earlierWords groups online currentKeys currentWords + q)) + +def queryLocalRandomSourcesFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi q readGroup readInteger readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryGroupSourceGatherFootprint M N F Q exponent eM eF hM hF a parentInitial parentAllocation q + readGroup hg + (fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGatherFootprint parent N P F exponent H hP tau a parentInitial parentAllocation + child childAllocation q readInteger hz + (fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) parentAllocation + childAllocation initialAllocation + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadAllocation groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadAllocation onlineKeys onlineWords) q readEarlier + readCurrent he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryLocalBandFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGatherFootprint M parent N P F exponent hP a parentInitial parentAllocation q readMass + readInitial hm hi + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) q readGroup + readInteger readEarlier readCurrent) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a + eta kappa delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) + parentAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys initialWords) q readGroup readInteger + readEarlier readCurrent hg hz he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalProgramFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (readParent : OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hp : (key : OAI.EditApproximation.TargetInterval target.length) → (readParent key).Footprint) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalProgramRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryInitialGatherFootprint N P F exponent hP a q readParent hp + (fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent) + fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + (OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent hm hi hg hz he hr + +def queryPhysicalRandomDataRequestFootprintRawBand + {σ : Type u_1} + {α : Type u_2} + (source target : List α) + {M J : ℕ} + [NeZero M] + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) : (OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta copies pass copy T S t ht node hbelow readGroup readInteger q).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + unfold OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand + apply OAI.EditApproximation.queryLocalProgramFootprintRawBand + · intro r + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro input + apply OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork _ (fun _ => 1) + apply OAI.EditApproximation.queryMeanReadFootprint + intro j + exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro key + exact (hg key).mapKeysWithWork _ (fun _ => 1) + · intro key range + exact (hz key range).mapKeysWithWork _ (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalEarlierReadFootprint copies pass copy T S t node hbelow q input).mapKeysWithWork _ + (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyRefinementFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (passes copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (time : Fin R) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryFamilyRefinementRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q).Footprint := +OAI.EditApproximation.queryPhysicalRandomDataRequestFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + (OAI.EditApproximation.queryFamilyGroupReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + (OAI.EditApproximation.queryFamilyOnlineReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + +def queryFamilyActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) + (hindex : T < request.index) + (hbelow : ↑request.node.fst < J) : (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T S + passes copies request hindex hbelow).Footprint := by + have proof_active_request_eq_145 {α : Type u_1} {M : ℕ} {J : ℕ} (target : List.{u_1} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_1} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + (OAI.EditApproximation.queryFamilyRefinementFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyBoundedActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) + (hindex : T < parent.val.index) + (hbelow : ↑parent.val.node.fst < J) : (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T + S passes copies parent hindex hbelow).Footprint := + OAI.EditApproximation.queryRestrictPhysicalBodyFootprint (passes + 1) copies T S parent _ + (OAI.EditApproximation.queryFamilyActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow) + +def queryChargedFamilyTableFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) : (OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits parent).Footprint := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state + unfold OAI.EditApproximation.queryChargedFamilyTableRawBand + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalWordLEAllocation parent.val.index.bits T.bits) ?_ + split + · exact (OAI.EditApproximation.queryChargedWarmupFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits).mapKeysWithWork _ (fun _ => 1) + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit.mapKeysWithWork _ (fun _ => 1) + · exact (OAI.EditApproximation.queryFamilyBoundedActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent _ _).mapKeysWithWork _ + (fun _ => 1) + · exact hinit.mapKeysWithWork _ (fun _ => 1) + +def queryChargedFamilyGlobalFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse request).Footprint := by + cases request with + | inl entry => exact OAI.EditApproximation.BitQuery.Footprint.compute (coarse entry) (allocation entry) + | inr parent => + exact OAI.EditApproximation.queryChargedFamilyTableFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + +def queryFamilyMemoRawFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : (OAI.EditApproximation.queryFamilyMemoRawRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse draw key).Footprint := by + cases key with + | inl scalar => + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw scalar) + (Nat.size (draw scalar).val + 2) + | inr request => + exact (OAI.EditApproximation.queryChargedFamilyGlobalFootprintRawBand source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse allocation request).mapKeysWithWork + _ (fun _ => 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input key).Footprint := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawFootprintRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) + (fun _ => 0) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def computedQueryMemoFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input + key).Footprint := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + (OAI.EditApproximation.computedQueryMemoRawFootprintRawBand source target N occurrence symbolBits positionBits input + key).normalize + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +attribute [local instance] queryRoundsNeZero + +def computedQueryTemporaryCellsFootprintRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.BitQuery.Footprint.rankedBitMemoCells (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryMemoFootprintRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def integerAcceptedSpaceTermsFootprintRawBand (source target : List ℤ) (N : ℕ) + (epsilon : OAI.EditApproximation.BinaryFraction) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : List ℕ := + let x := source.map OAI.EditApproximation.integerSymbolCode + let y := target.map OAI.EditApproximation.integerSymbolCode + [8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon, + 2 * OAI.EditApproximation.integerStoredDataSpace source target, + OAI.EditApproximation.computedQuerySetupAllocation N, + (OAI.EditApproximation.computedQueryMemoResultRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input).memory.fractionStorage, + OAI.EditApproximation.computedQueryTemporaryCellsFootprintRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input, + OAI.EditApproximation.computedFamilyCoarseCopyStorage x y N input, + OAI.EditApproximation.computedFamilyCoarseArrayCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseScratchCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseControlCapacity x y N input, + 4 * (OAI.EditApproximation.inputHeight N + (OAI.EditApproximation.integerParameters N).B + 4), + OAI.EditApproximation.integerFinalAllocationRawBand source target N input, + 8 * (N + 1)] + +noncomputable def integerBinarySpaceFootprintRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + | .inr execution => (OAI.EditApproximation.integerAcceptedSpaceTermsFootprintRawBand source target N epsilon + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).sum + else 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + +theorem almostLinearEditDistanceRawBand (epsilon : OAI.EditApproximation.BinaryFraction) + (hepsilon : 0 < epsilon.value) (_hepsilonOne : epsilon.value < 1) + : + (∀ (source target : List ℤ) (N : ℕ), source.length + target.length ≤ N → + (2 / 3 : ℝ) ≤ (OAI.EditApproximation.computedFullLaw (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N epsilon).real + {outcome | EditDistortion.edit source target ≤ OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome ∧ + (OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * OAI.EditDistortion.edit source target}) ∧ + (∀ (source target : List ℤ) (N : ℕ), source = target → ∀ outcome, + OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome = 0) ∧ + (∀ (C : ℕ) (eta : ℝ), 0 < eta → ∀ᶠ N : ℕ in atTop, + ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, OAI.EditApproximation.integerBinaryWorkRawBand source target N epsilon outcome + ∂OAI.EditApproximation.computedFullLaw (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + eta)) ∧ + (∀ C : ℕ, ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ outcome, OAI.EditApproximation.integerBinarySpaceFootprintRawBand source target N epsilon outcome ≤ (N + 2) ^ (C + 65564)) := by + sorry + +end OAI.EditApproximation +end +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EditApproximation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EditApproximation.almostLinearEditDistanceRawBand` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/edit-approximation/solution/closure.txt b/tasks/edit-approximation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..403809a3cce1172243d38e7f68d10ed592041570 --- /dev/null +++ b/tasks/edit-approximation/solution/closure.txt @@ -0,0 +1,1024 @@ +OAI.Combinatorics.EditApproximation.AlmostLinear +OAI.Combinatorics.EditApproximation.AlmostLinearConditional +OAI.Combinatorics.EditApproximation.Binary.BinaryActionSelection +OAI.Combinatorics.EditApproximation.Binary.BinaryActualBandOptimizer +OAI.Combinatorics.EditApproximation.Binary.BinaryAffineGuard +OAI.Combinatorics.EditApproximation.Binary.BinaryArithmeticWork +OAI.Combinatorics.EditApproximation.Binary.BinaryBandAction +OAI.Combinatorics.EditApproximation.Binary.BinaryBandActionReads +OAI.Combinatorics.EditApproximation.Binary.BinaryBandCoordinates +OAI.Combinatorics.EditApproximation.Binary.BinaryBandEnvelope +OAI.Combinatorics.EditApproximation.Binary.BinaryBandGuardWork +OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputWork +OAI.Combinatorics.EditApproximation.Binary.BinaryBandInputs +OAI.Combinatorics.EditApproximation.Binary.BinaryBandReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryBandReads +OAI.Combinatorics.EditApproximation.Binary.BinaryBandSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryBandStorage +OAI.Combinatorics.EditApproximation.Binary.BinaryBandTailWork +OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanReads +OAI.Combinatorics.EditApproximation.Binary.BinaryBellmanSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryBufferInputBounds +OAI.Combinatorics.EditApproximation.Binary.BinaryBufferSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryCachedContinuation +OAI.Combinatorics.EditApproximation.Binary.BinaryCachedShellWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCanonicalWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCeilingWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCellCenters +OAI.Combinatorics.EditApproximation.Binary.BinaryCellCentersWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCellGrid +OAI.Combinatorics.EditApproximation.Binary.BinaryCellGridWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCellGroupKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryCellReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryCellReads +OAI.Combinatorics.EditApproximation.Binary.BinaryCellSourcePort +OAI.Combinatorics.EditApproximation.Binary.BinaryCellSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryCellSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryComputedCellGroup +OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationReads +OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryContinuationWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateAction +OAI.Combinatorics.EditApproximation.Binary.BinaryCoordinateActionWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCountedActionSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroup +OAI.Combinatorics.EditApproximation.Binary.BinaryCountedGroupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryCountedOptimizerSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryCutReads +OAI.Combinatorics.EditApproximation.Binary.BinaryDistanceWork +OAI.Combinatorics.EditApproximation.Binary.BinaryDivisionWork +OAI.Combinatorics.EditApproximation.Binary.BinaryDyadicCeiling +OAI.Combinatorics.EditApproximation.Binary.BinaryDyadicSampledGroups +OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeReads +OAI.Combinatorics.EditApproximation.Binary.BinaryEnvelopeSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryFinalAnswer +OAI.Combinatorics.EditApproximation.Binary.BinaryFinalSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryFiniteLoops +OAI.Combinatorics.EditApproximation.Binary.BinaryFixedDenominator +OAI.Combinatorics.EditApproximation.Binary.BinaryFractionWork +OAI.Combinatorics.EditApproximation.Binary.BinaryGatheredValues +OAI.Combinatorics.EditApproximation.Binary.BinaryGeometrySpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGradientWork +OAI.Combinatorics.EditApproximation.Binary.BinaryGridSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGridWork +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupActionReads +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupActionSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupMemberSource +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReads +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupReductionSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetup +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSetupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSourcePort +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGroupSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryGuardSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryIndexedLeaf +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGridWork +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialGuardWork +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialMinimumWork +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReadSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialReads +OAI.Combinatorics.EditApproximation.Binary.BinaryInitialWork +OAI.Combinatorics.EditApproximation.Binary.BinaryKeyedOnline +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGrid +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGridWork +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupActions +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupReads +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupSource +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGroupSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalGuardWork +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineReads +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineSource +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalOnlineSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalReadValues +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalRepresentativeWork +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalSourceKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalSourceValues +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryLocalWarmupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryLogWork +OAI.Combinatorics.EditApproximation.Binary.BinaryLoopSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryMaximizerWork +OAI.Combinatorics.EditApproximation.Binary.BinaryMedianKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryMedianSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryMemo +OAI.Combinatorics.EditApproximation.Binary.BinaryMemoSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryNormalizationSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryNumericSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineInputWork +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineInputs +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineParameters +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineReads +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSetupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSourceSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryOnlineSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryOptimizerWork +OAI.Combinatorics.EditApproximation.Binary.BinaryOrderWork +OAI.Combinatorics.EditApproximation.Binary.BinaryOuterReadCosts +OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuation +OAI.Combinatorics.EditApproximation.Binary.BinaryPhysicalContinuationWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPowerStorage +OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixReads +OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryPrefixWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedActionStorage +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroup +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedCellGroupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedComputedCell +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedComputedCellWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelReads +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedKernelWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedListBounds +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroupWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalGroups +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnline +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedLocalOnlineWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnline +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineReads +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOnlineWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedOptimizer +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentative +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedRepresentativeWork +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskipped +OAI.Combinatorics.EditApproximation.Binary.BinaryPreparedUnskippedWork +OAI.Combinatorics.EditApproximation.Binary.BinaryRawCost +OAI.Combinatorics.EditApproximation.Binary.BinaryRawNumerics +OAI.Combinatorics.EditApproximation.Binary.BinaryRawOptimizer +OAI.Combinatorics.EditApproximation.Binary.BinaryRawStorage +OAI.Combinatorics.EditApproximation.Binary.BinaryReadComposition +OAI.Combinatorics.EditApproximation.Binary.BinaryReadCostBounds +OAI.Combinatorics.EditApproximation.Binary.BinaryReductionSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementLists +OAI.Combinatorics.EditApproximation.Binary.BinaryRefinementParameters +OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeReads +OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryRepresentativeWork +OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedReads +OAI.Combinatorics.EditApproximation.Binary.BinaryRoundedWork +OAI.Combinatorics.EditApproximation.Binary.BinaryRoundingSpace +OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroupPolynomial +OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroupWork +OAI.Combinatorics.EditApproximation.Binary.BinarySampledGroups +OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnline +OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlinePolynomial +OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlineSpace +OAI.Combinatorics.EditApproximation.Binary.BinarySampledOnlineWork +OAI.Combinatorics.EditApproximation.Binary.BinarySampledSourcePort +OAI.Combinatorics.EditApproximation.Binary.BinaryScaleGrid +OAI.Combinatorics.EditApproximation.Binary.BinaryScoreReads +OAI.Combinatorics.EditApproximation.Binary.BinarySeedMedianWork +OAI.Combinatorics.EditApproximation.Binary.BinarySelectedGroupWork +OAI.Combinatorics.EditApproximation.Binary.BinarySelectionSpace +OAI.Combinatorics.EditApproximation.Binary.BinarySourceSelectorBounds +OAI.Combinatorics.EditApproximation.Binary.BinarySubtractWork +OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularChoice +OAI.Combinatorics.EditApproximation.Binary.BinaryTriangularSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedGuardWork +OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedKernel +OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedReads +OAI.Combinatorics.EditApproximation.Binary.BinaryUnskippedSpace +OAI.Combinatorics.EditApproximation.Binary.BinaryUpdateWork +OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupAverage +OAI.Combinatorics.EditApproximation.Binary.BinaryWarmupReads +OAI.Combinatorics.EditApproximation.Binary.BinaryWideActionsWork +OAI.Combinatorics.EditApproximation.Binary.BinaryWideChildWork +OAI.Combinatorics.EditApproximation.Binary.BinaryWideGrid +OAI.Combinatorics.EditApproximation.Binary.BinaryWideGridWork +OAI.Combinatorics.EditApproximation.Binary.BinaryWideSpace +OAI.Combinatorics.EditApproximation.Binary.BitAllocation +OAI.Combinatorics.EditApproximation.Binary.BitControlSpace +OAI.Combinatorics.EditApproximation.Binary.BitMemoHeap +OAI.Combinatorics.EditApproximation.Binary.BitMemoMap +OAI.Combinatorics.EditApproximation.Binary.BitMemoOn +OAI.Combinatorics.EditApproximation.Binary.BitMemoRun +OAI.Combinatorics.EditApproximation.Binary.BitMemoSound +OAI.Combinatorics.EditApproximation.Binary.BitMemoStorage +OAI.Combinatorics.EditApproximation.Binary.BitMemoWork +OAI.Combinatorics.EditApproximation.Binary.BitMemoWorkOn +OAI.Combinatorics.EditApproximation.Binary.BitMemoWorkTransfer +OAI.Combinatorics.EditApproximation.Binary.BitQuery +OAI.Combinatorics.EditApproximation.Binary.BitQueryKeys +OAI.Combinatorics.EditApproximation.Binary.BitQueryKeysSpace +OAI.Combinatorics.EditApproximation.Binary.BitQueryNormalizationCost +OAI.Combinatorics.EditApproximation.Binary.BitQueryNormalize +OAI.Combinatorics.EditApproximation.Binary.BitQueryOn +OAI.Combinatorics.EditApproximation.Binary.BitQuerySpace +OAI.Combinatorics.EditApproximation.Binary.BitRankedMemo +OAI.Combinatorics.EditApproximation.Binary.BitRankedMemoOn +OAI.Combinatorics.EditApproximation.Binary.BitRankedNormalize +OAI.Combinatorics.EditApproximation.Binary.BitSourceRanked +OAI.Combinatorics.EditApproximation.Binary.FractionAllocation +OAI.Combinatorics.EditApproximation.Binary.FractionControlSpace +OAI.Combinatorics.EditApproximation.Binary.IntegerAlgorithm +OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryAccuracy +OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryOutput +OAI.Combinatorics.EditApproximation.Binary.IntegerBinarySpace +OAI.Combinatorics.EditApproximation.Binary.IntegerBinaryWork +OAI.Combinatorics.EditApproximation.Binary.IntegerCoarseSymbolBits +OAI.Combinatorics.EditApproximation.Binary.IntegerInputInspection +OAI.Combinatorics.EditApproximation.Binary.IntegerInputStorage +OAI.Combinatorics.EditApproximation.Binary.IntegerKernelWork +OAI.Combinatorics.EditApproximation.Binary.IntegerOccurrenceIndex +OAI.Combinatorics.EditApproximation.Binary.IntegerOccurrenceStorage +OAI.Combinatorics.EditApproximation.Binary.IntegerPreprocessing +OAI.Combinatorics.EditApproximation.Binary.IntegerQueryWork +OAI.Combinatorics.EditApproximation.Binary.IntegerReadChargedWork +OAI.Combinatorics.EditApproximation.Binary.IntegerStoredDataSpace +OAI.Combinatorics.EditApproximation.Binary.IntegerSymbols +OAI.Combinatorics.EditApproximation.Binary.SignedBinaryOrderWork +OAI.Combinatorics.EditApproximation.Binary.SignedBinaryWork +OAI.Combinatorics.EditApproximation.Binary.UnreducedNumerics +OAI.Combinatorics.EditApproximation.Binary.UnreducedOptimizer +OAI.Combinatorics.EditApproximation.Binary.UnreducedRational +OAI.Combinatorics.EditApproximation.Binary.UnreducedStorage +OAI.Combinatorics.EditApproximation.Coarse.CoarseAccessAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseAccessControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseAccuracy +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayArithmetic +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayEval +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayHistory +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayRepresentation +OAI.Combinatorics.EditApproximation.Coarse.CoarseArraySimulation +OAI.Combinatorics.EditApproximation.Coarse.CoarseArrayStorage +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryBitWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryBox +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryCorrectness +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryEvaluation +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryGrid +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryRead +OAI.Combinatorics.EditApproximation.Coarse.CoarseBinaryWeight +OAI.Combinatorics.EditApproximation.Coarse.CoarseBitParameters +OAI.Combinatorics.EditApproximation.Coarse.CoarseCellBounds +OAI.Combinatorics.EditApproximation.Coarse.CoarseChildAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseChildControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseChildrenBitWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseChildrenSimulation +OAI.Combinatorics.EditApproximation.Coarse.CoarseCompactCells +OAI.Combinatorics.EditApproximation.Coarse.CoarseCompleteArrayWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseCompletePolynomial +OAI.Combinatorics.EditApproximation.Coarse.CoarseCompleteWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseDenominatorArithmetic +OAI.Combinatorics.EditApproximation.Coarse.CoarseDescriptorWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseEntryCostSum +OAI.Combinatorics.EditApproximation.Coarse.CoarseEstimator +OAI.Combinatorics.EditApproximation.Coarse.CoarseFirstRequestCost +OAI.Combinatorics.EditApproximation.Coarse.CoarseGlobalSeed +OAI.Combinatorics.EditApproximation.Coarse.CoarseGridArithmetic +OAI.Combinatorics.EditApproximation.Coarse.CoarseGridInvariant +OAI.Combinatorics.EditApproximation.Coarse.CoarseGridTransfers +OAI.Combinatorics.EditApproximation.Coarse.CoarseHistoryBound +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexBudget +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedArrayHistory +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedChildren +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedCompare +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedCostComparison +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedEntryCost +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExecution +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedExtra +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedFrameWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedHistory +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitial +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedInitialCost +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedOverhead +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRead +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRootBound +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedRootCost +OAI.Combinatorics.EditApproximation.Coarse.CoarseIndexedValue +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitial +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialBinary +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialCost +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialExecution +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialLabels +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialScalar +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialStorage +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseInitialWorkBounds +OAI.Combinatorics.EditApproximation.Coarse.CoarseInputGuard +OAI.Combinatorics.EditApproximation.Coarse.CoarseInputPreparation +OAI.Combinatorics.EditApproximation.Coarse.CoarseInputStorage +OAI.Combinatorics.EditApproximation.Coarse.CoarseLabelWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseLevelMagnitude +OAI.Combinatorics.EditApproximation.Coarse.CoarseNumericalUnit +OAI.Combinatorics.EditApproximation.Coarse.CoarsePadding +OAI.Combinatorics.EditApproximation.Coarse.CoarseParameters +OAI.Combinatorics.EditApproximation.Coarse.CoarsePenaltyArithmetic +OAI.Combinatorics.EditApproximation.Coarse.CoarsePrecision +OAI.Combinatorics.EditApproximation.Coarse.CoarseProbability +OAI.Combinatorics.EditApproximation.Coarse.CoarseRangeCopy +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadAccess +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadBudget +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadCore +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadEvaluation +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadLeafWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadNumericalBounds +OAI.Combinatorics.EditApproximation.Coarse.CoarseReadTree +OAI.Combinatorics.EditApproximation.Coarse.CoarseRootBounds +OAI.Combinatorics.EditApproximation.Coarse.CoarseRootExecution +OAI.Combinatorics.EditApproximation.Coarse.CoarseRootHistory +OAI.Combinatorics.EditApproximation.Coarse.CoarseRootWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseSampling +OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarAllocation +OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarBounds +OAI.Combinatorics.EditApproximation.Coarse.CoarseScalarControlSpace +OAI.Combinatorics.EditApproximation.Coarse.CoarseSeed +OAI.Combinatorics.EditApproximation.Coarse.CoarseSliceCopy +OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdArithmetic +OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStep +OAI.Combinatorics.EditApproximation.Coarse.CoarseThresholdStepWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseTransforms +OAI.Combinatorics.EditApproximation.Coarse.CoarseWeightSimulation +OAI.Combinatorics.EditApproximation.Coarse.CoarseWidthWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseWork +OAI.Combinatorics.EditApproximation.Coarse.CoarseWorkAsymptotics +OAI.Combinatorics.EditApproximation.Coarse.CoarseWorkEnvelope +OAI.Combinatorics.EditApproximation.Definitions +OAI.Combinatorics.EditApproximation.Geometry.Accuracy +OAI.Combinatorics.EditApproximation.Geometry.AccuracyCutoff +OAI.Combinatorics.EditApproximation.Geometry.AccuracyPrefixInspection +OAI.Combinatorics.EditApproximation.Geometry.ActionLower +OAI.Combinatorics.EditApproximation.Geometry.ActionVectors +OAI.Combinatorics.EditApproximation.Geometry.ActualActionValues +OAI.Combinatorics.EditApproximation.Geometry.ActualBandBitEnvelope +OAI.Combinatorics.EditApproximation.Geometry.ActualRepresentatives +OAI.Combinatorics.EditApproximation.Geometry.ActualRoundedGroupInputs +OAI.Combinatorics.EditApproximation.Geometry.AlignedStates +OAI.Combinatorics.EditApproximation.Geometry.AlignmentSplitting +OAI.Combinatorics.EditApproximation.Geometry.BalancedIntervals +OAI.Combinatorics.EditApproximation.Geometry.BalancedWidths +OAI.Combinatorics.EditApproximation.Geometry.BandActionGuards +OAI.Combinatorics.EditApproximation.Geometry.BandActionPolynomial +OAI.Combinatorics.EditApproximation.Geometry.BandDimension +OAI.Combinatorics.EditApproximation.Geometry.BandEarlierDependence +OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopeBits +OAI.Combinatorics.EditApproximation.Geometry.BandEnvelopes +OAI.Combinatorics.EditApproximation.Geometry.BandGroupSampling +OAI.Combinatorics.EditApproximation.Geometry.BandGuards +OAI.Combinatorics.EditApproximation.Geometry.BandNumericalBits +OAI.Combinatorics.EditApproximation.Geometry.BandOptimizerWork +OAI.Combinatorics.EditApproximation.Geometry.BandParameters +OAI.Combinatorics.EditApproximation.Geometry.BandRegret +OAI.Combinatorics.EditApproximation.Geometry.BandRounding +OAI.Combinatorics.EditApproximation.Geometry.Bands +OAI.Combinatorics.EditApproximation.Geometry.Bellman +OAI.Combinatorics.EditApproximation.Geometry.CanonicalFractionWork +OAI.Combinatorics.EditApproximation.Geometry.CellGroupSelection +OAI.Combinatorics.EditApproximation.Geometry.ChargedCoarseOracle +OAI.Combinatorics.EditApproximation.Geometry.ChargedDependencyExpansion +OAI.Combinatorics.EditApproximation.Geometry.ChargedGlobalQuery +OAI.Combinatorics.EditApproximation.Geometry.ChargedIndexCost +OAI.Combinatorics.EditApproximation.Geometry.ChargedPhysicalRequest +OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryAsymptotics +OAI.Combinatorics.EditApproximation.Geometry.ChargedQueryProgress +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCoarseKeys +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCoarseOracle +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCoarseWork +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomCost +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomExpansion +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomGlobalQuery +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomIndexCost +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomMemo +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomMemoWork +OAI.Combinatorics.EditApproximation.Geometry.ChargedRandomProgress +OAI.Combinatorics.EditApproximation.Geometry.ChargedRequestSpace +OAI.Combinatorics.EditApproximation.Geometry.ChargedSeedQuery +OAI.Combinatorics.EditApproximation.Geometry.ChargedTerminalCost +OAI.Combinatorics.EditApproximation.Geometry.ChildIncrements +OAI.Combinatorics.EditApproximation.Geometry.CommonArrayFinal +OAI.Combinatorics.EditApproximation.Geometry.CommonArrayTrace +OAI.Combinatorics.EditApproximation.Geometry.CommonRangeSource +OAI.Combinatorics.EditApproximation.Geometry.CommonSeedTrace +OAI.Combinatorics.EditApproximation.Geometry.ComparisonAccounting +OAI.Combinatorics.EditApproximation.Geometry.ComparisonBandCoverage +OAI.Combinatorics.EditApproximation.Geometry.ComparisonBounds +OAI.Combinatorics.EditApproximation.Geometry.ComparisonLift +OAI.Combinatorics.EditApproximation.Geometry.ComparisonLiftBounds +OAI.Combinatorics.EditApproximation.Geometry.ComparisonLiftStep +OAI.Combinatorics.EditApproximation.Geometry.ComparisonPhysical +OAI.Combinatorics.EditApproximation.Geometry.ComparisonTree +OAI.Combinatorics.EditApproximation.Geometry.ConeLocality +OAI.Combinatorics.EditApproximation.Geometry.Cones +OAI.Combinatorics.EditApproximation.Geometry.Connections +OAI.Combinatorics.EditApproximation.Geometry.CurrentQueryInputs +OAI.Combinatorics.EditApproximation.Geometry.Curvature +OAI.Combinatorics.EditApproximation.Geometry.DependencyExpansion +OAI.Combinatorics.EditApproximation.Geometry.DependencyPathEnvelope +OAI.Combinatorics.EditApproximation.Geometry.DependencyWeightedWork +OAI.Combinatorics.EditApproximation.Geometry.DomainCounts +OAI.Combinatorics.EditApproximation.Geometry.DomainExponential +OAI.Combinatorics.EditApproximation.Geometry.DyadicQueryWindow +OAI.Combinatorics.EditApproximation.Geometry.EarlierInputBudget +OAI.Combinatorics.EditApproximation.Geometry.EarlierValueDependence +OAI.Combinatorics.EditApproximation.Geometry.FirstCrossing +OAI.Combinatorics.EditApproximation.Geometry.GatheredInputs +OAI.Combinatorics.EditApproximation.Geometry.GatheredLocalStep +OAI.Combinatorics.EditApproximation.Geometry.Geometry +OAI.Combinatorics.EditApproximation.Geometry.GlobalQueryCost +OAI.Combinatorics.EditApproximation.Geometry.GlobalQueryProgress +OAI.Combinatorics.EditApproximation.Geometry.Grid +OAI.Combinatorics.EditApproximation.Geometry.GroupCells +OAI.Combinatorics.EditApproximation.Geometry.GroupInputDependence +OAI.Combinatorics.EditApproximation.Geometry.GroupNumerical +OAI.Combinatorics.EditApproximation.Geometry.GroupSampling +OAI.Combinatorics.EditApproximation.Geometry.GroupSamplingWork +OAI.Combinatorics.EditApproximation.Geometry.GroupSmallConstants +OAI.Combinatorics.EditApproximation.Geometry.HeightPowerWork +OAI.Combinatorics.EditApproximation.Geometry.IndexedTerminalWork +OAI.Combinatorics.EditApproximation.Geometry.InitialConeGrid +OAI.Combinatorics.EditApproximation.Geometry.InitialConeTable +OAI.Combinatorics.EditApproximation.Geometry.InitialCones +OAI.Combinatorics.EditApproximation.Geometry.InitialInputBudget +OAI.Combinatorics.EditApproximation.Geometry.InputViews +OAI.Combinatorics.EditApproximation.Geometry.Leaves +OAI.Combinatorics.EditApproximation.Geometry.ListBandRegret +OAI.Combinatorics.EditApproximation.Geometry.LocalArithmeticAsymptotics +OAI.Combinatorics.EditApproximation.Geometry.LocalArithmeticBudget +OAI.Combinatorics.EditApproximation.Geometry.LocalCells +OAI.Combinatorics.EditApproximation.Geometry.LocalCommonOutput +OAI.Combinatorics.EditApproximation.Geometry.LocalCommonSeed +OAI.Combinatorics.EditApproximation.Geometry.LocalCommonTrace +OAI.Combinatorics.EditApproximation.Geometry.LocalFinalAccuracy +OAI.Combinatorics.EditApproximation.Geometry.LocalGrid +OAI.Combinatorics.EditApproximation.Geometry.LocalGroupBudget +OAI.Combinatorics.EditApproximation.Geometry.LocalGroupCones +OAI.Combinatorics.EditApproximation.Geometry.LocalGroupSourceQuery +OAI.Combinatorics.EditApproximation.Geometry.LocalInitialCones +OAI.Combinatorics.EditApproximation.Geometry.LocalMedianDrawLaw +OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineMassBound +OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineProgram +OAI.Combinatorics.EditApproximation.Geometry.LocalOnlineSourceQuery +OAI.Combinatorics.EditApproximation.Geometry.LocalRandomDataQuery +OAI.Combinatorics.EditApproximation.Geometry.LocalRandomQueryKeys +OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceCost +OAI.Combinatorics.EditApproximation.Geometry.LocalRandomSourceQuery +OAI.Combinatorics.EditApproximation.Geometry.LocalRandomTableCost +OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementCones +OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQuery +OAI.Combinatorics.EditApproximation.Geometry.LocalRefinementQueryWork +OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSchedule +OAI.Combinatorics.EditApproximation.Geometry.LocalSeedSequence +OAI.Combinatorics.EditApproximation.Geometry.LocalSourceReadCost +OAI.Combinatorics.EditApproximation.Geometry.LocalTraceMemoOutput +OAI.Combinatorics.EditApproximation.Geometry.LocalTraceProgram +OAI.Combinatorics.EditApproximation.Geometry.LocalWideStep +OAI.Combinatorics.EditApproximation.Geometry.LocalWorkEnvelope +OAI.Combinatorics.EditApproximation.Geometry.MemoCodeWork +OAI.Combinatorics.EditApproximation.Geometry.MemoizedOracle +OAI.Combinatorics.EditApproximation.Geometry.NodeRegret +OAI.Combinatorics.EditApproximation.Geometry.OccurrenceIndex +OAI.Combinatorics.EditApproximation.Geometry.OccurrenceLeaf +OAI.Combinatorics.EditApproximation.Geometry.OccurrencePrefix +OAI.Combinatorics.EditApproximation.Geometry.OccurrenceStorage +OAI.Combinatorics.EditApproximation.Geometry.OnlineActionDraw +OAI.Combinatorics.EditApproximation.Geometry.OnlineEarlierDependence +OAI.Combinatorics.EditApproximation.Geometry.OnlineLinearBits +OAI.Combinatorics.EditApproximation.Geometry.ParameterAsymptotics +OAI.Combinatorics.EditApproximation.Geometry.ParameterConstruction +OAI.Combinatorics.EditApproximation.Geometry.ParameterDependencyAsymptotics +OAI.Combinatorics.EditApproximation.Geometry.ParameterLocalAsymptotics +OAI.Combinatorics.EditApproximation.Geometry.ParameterNumericalConstruction +OAI.Combinatorics.EditApproximation.Geometry.ParameterSlack +OAI.Combinatorics.EditApproximation.Geometry.Parameters +OAI.Combinatorics.EditApproximation.Geometry.PartitionIntervals +OAI.Combinatorics.EditApproximation.Geometry.PrefixBitEnvelope +OAI.Combinatorics.EditApproximation.Geometry.PrefixComparison +OAI.Combinatorics.EditApproximation.Geometry.PrefixCosts +OAI.Combinatorics.EditApproximation.Geometry.PreparedBandPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedCachedKernelWork +OAI.Combinatorics.EditApproximation.Geometry.PreparedGroupPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedInitialPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedKernelPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedLocalGroupPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedShellPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PreparedWarmupPolynomial +OAI.Combinatorics.EditApproximation.Geometry.PublishedInputs +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoAddressWork +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelFresh +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKernelWork +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoKeys +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoProgram +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoSimulation +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoStorage +OAI.Combinatorics.EditApproximation.Geometry.RankedMemoWork +OAI.Combinatorics.EditApproximation.Geometry.RankedProgramRestriction +OAI.Combinatorics.EditApproximation.Geometry.RefinementBandSupport +OAI.Combinatorics.EditApproximation.Geometry.RefinementBufferRanges +OAI.Combinatorics.EditApproximation.Geometry.RefinementConeLocality +OAI.Combinatorics.EditApproximation.Geometry.RefinementDataQuery +OAI.Combinatorics.EditApproximation.Geometry.RefinementDataQueryWork +OAI.Combinatorics.EditApproximation.Geometry.RefinementErrorTerms +OAI.Combinatorics.EditApproximation.Geometry.RefinementInitialSupport +OAI.Combinatorics.EditApproximation.Geometry.RefinementRankCost +OAI.Combinatorics.EditApproximation.Geometry.RefinementSupportBudget +OAI.Combinatorics.EditApproximation.Geometry.Regret +OAI.Combinatorics.EditApproximation.Geometry.RepresentativeBands +OAI.Combinatorics.EditApproximation.Geometry.RoundedComparison +OAI.Combinatorics.EditApproximation.Geometry.RoundedGroupStates +OAI.Combinatorics.EditApproximation.Geometry.Seed +OAI.Combinatorics.EditApproximation.Geometry.SeedFactorSchedule +OAI.Combinatorics.EditApproximation.Geometry.SeedPassNumerics +OAI.Combinatorics.EditApproximation.Geometry.SharedActions +OAI.Combinatorics.EditApproximation.Geometry.SharedGroupInputBudget +OAI.Combinatorics.EditApproximation.Geometry.SourceErasure +OAI.Combinatorics.EditApproximation.Geometry.SourcePrefixes +OAI.Combinatorics.EditApproximation.Geometry.SourceRankedEncoding +OAI.Combinatorics.EditApproximation.Geometry.SourceRankedKeys +OAI.Combinatorics.EditApproximation.Geometry.SourceRankedProgram +OAI.Combinatorics.EditApproximation.Geometry.SourceRankedRestriction +OAI.Combinatorics.EditApproximation.Geometry.SourceRankedWork +OAI.Combinatorics.EditApproximation.Geometry.StateDomain +OAI.Combinatorics.EditApproximation.Geometry.StateGeometry +OAI.Combinatorics.EditApproximation.Geometry.SubexponentialTransfer +OAI.Combinatorics.EditApproximation.Geometry.TreeAccounting +OAI.Combinatorics.EditApproximation.Geometry.TreeParameters +OAI.Combinatorics.EditApproximation.Geometry.UnifiedPhysicalTable +OAI.Combinatorics.EditApproximation.Geometry.UnskippedBands +OAI.Combinatorics.EditApproximation.Geometry.UnskippedRegretBudget +OAI.Combinatorics.EditApproximation.Geometry.WarmupQueryKeys +OAI.Combinatorics.EditApproximation.Geometry.WarmupReadWork +OAI.Combinatorics.EditApproximation.Geometry.WeightedTreeWork +OAI.Combinatorics.EditApproximation.Geometry.WideActions +OAI.Combinatorics.EditApproximation.Geometry.WideBellman +OAI.Combinatorics.EditApproximation.Geometry.WideEarlierInputs +OAI.Combinatorics.EditApproximation.Geometry.Work +OAI.Combinatorics.EditApproximation.Numerics.GradientStorageBits +OAI.Combinatorics.EditApproximation.Numerics.NumericalWork +OAI.Combinatorics.EditApproximation.Numerics.Numerics +OAI.Combinatorics.EditApproximation.Numerics.OptimizerBitEnvelope +OAI.Combinatorics.EditApproximation.Numerics.OptimizerBits +OAI.Combinatorics.EditApproximation.Numerics.OptimizerWorkspace +OAI.Combinatorics.EditApproximation.Numerics.RationalIntermediateBits +OAI.Combinatorics.EditApproximation.Numerics.RationalPrefix +OAI.Combinatorics.EditApproximation.Numerics.RationalPruning +OAI.Combinatorics.EditApproximation.Numerics.RationalRefinement +OAI.Combinatorics.EditApproximation.Numerics.RationalWideSpatial +OAI.Combinatorics.EditApproximation.Numerics.RationalWideStep +OAI.Combinatorics.EditApproximation.Numerics.ScalarAllocation +OAI.Combinatorics.EditApproximation.Numerics.ScalarControlSpace +OAI.Combinatorics.EditApproximation.Numerics.VectorOptimizerWork +OAI.Combinatorics.EditApproximation.Probability.AdaptiveMarginalLaw +OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedLaw +OAI.Combinatorics.EditApproximation.Probability.AdaptiveSeedTrace +OAI.Combinatorics.EditApproximation.Probability.Amplification +OAI.Combinatorics.EditApproximation.Probability.BernsteinEnvelope +OAI.Combinatorics.EditApproximation.Probability.BernsteinFinite +OAI.Combinatorics.EditApproximation.Probability.BernsteinMGF +OAI.Combinatorics.EditApproximation.Probability.Concentration +OAI.Combinatorics.EditApproximation.Probability.Exact +OAI.Combinatorics.EditApproximation.Probability.ExactSampling +OAI.Combinatorics.EditApproximation.Probability.ExactSuffixDP +OAI.Combinatorics.EditApproximation.Probability.ExactSuffixDPWork +OAI.Combinatorics.EditApproximation.Probability.ExpectedRegret +OAI.Combinatorics.EditApproximation.Probability.FiniteArrayMarginal +OAI.Combinatorics.EditApproximation.Probability.FiniteAssignments +OAI.Combinatorics.EditApproximation.Probability.FiniteBitPolynomial +OAI.Combinatorics.EditApproximation.Probability.FiniteBufferRanges +OAI.Combinatorics.EditApproximation.Probability.FiniteEnumerationWork +OAI.Combinatorics.EditApproximation.Probability.FiniteKeyRestriction +OAI.Combinatorics.EditApproximation.Probability.FiniteProductWork +OAI.Combinatorics.EditApproximation.Probability.FiniteQueryCostOrder +OAI.Combinatorics.EditApproximation.Probability.FiniteQueryRestriction +OAI.Combinatorics.EditApproximation.Probability.FiniteQueryWork +OAI.Combinatorics.EditApproximation.Probability.FiniteResampling +OAI.Combinatorics.EditApproximation.Probability.FiniteSampling +OAI.Combinatorics.EditApproximation.Probability.FiniteSeedFinal +OAI.Combinatorics.EditApproximation.Probability.FreshCoordinateCost +OAI.Combinatorics.EditApproximation.Probability.Median +OAI.Combinatorics.EditApproximation.Probability.RejectionArrayLaw +OAI.Combinatorics.EditApproximation.Probability.RejectionMemoCost +OAI.Combinatorics.EditApproximation.Probability.RejectionRuntimeLaw +OAI.Combinatorics.EditApproximation.Probability.RejectionSelectedCost +OAI.Combinatorics.EditApproximation.Probability.RejectionSelectedLaw +OAI.Combinatorics.EditApproximation.Probability.RejectionSpace +OAI.Combinatorics.EditApproximation.Probability.SampledRegret +OAI.Combinatorics.EditApproximation.Probability.ThresholdMoments +OAI.Combinatorics.EditApproximation.Queries.QueryActionInputCost +OAI.Combinatorics.EditApproximation.Queries.QueryActionInputs +OAI.Combinatorics.EditApproximation.Queries.QueryActiveCost +OAI.Combinatorics.EditApproximation.Queries.QueryBandGather +OAI.Combinatorics.EditApproximation.Queries.QueryBandInputCost +OAI.Combinatorics.EditApproximation.Queries.QueryBoundedActiveCost +OAI.Combinatorics.EditApproximation.Queries.QueryBoundedBody +OAI.Combinatorics.EditApproximation.Queries.QueryBoundedSemanticCost +OAI.Combinatorics.EditApproximation.Queries.QueryBoundedWork +OAI.Combinatorics.EditApproximation.Queries.QueryBufferSpace +OAI.Combinatorics.EditApproximation.Queries.QueryBufferedInputBounds +OAI.Combinatorics.EditApproximation.Queries.QueryBufferedSharedCost +OAI.Combinatorics.EditApproximation.Queries.QueryBufferedSourceBounds +OAI.Combinatorics.EditApproximation.Queries.QueryCallbackPolynomial +OAI.Combinatorics.EditApproximation.Queries.QueryCellCost +OAI.Combinatorics.EditApproximation.Queries.QueryCellStateCost +OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamily +OAI.Combinatorics.EditApproximation.Queries.QueryChargedFamilySpace +OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeed +OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeedCost +OAI.Combinatorics.EditApproximation.Queries.QueryChargedSeedSpace +OAI.Combinatorics.EditApproximation.Queries.QueryChargedTableCost +OAI.Combinatorics.EditApproximation.Queries.QueryChargedTableWidth +OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmup +OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupCost +OAI.Combinatorics.EditApproximation.Queries.QueryChargedWarmupSpace +OAI.Combinatorics.EditApproximation.Queries.QueryCodeBounds +OAI.Combinatorics.EditApproximation.Queries.QueryContinuationSpace +OAI.Combinatorics.EditApproximation.Queries.QueryCoordinateSpace +OAI.Combinatorics.EditApproximation.Queries.QueryDataBuffers +OAI.Combinatorics.EditApproximation.Queries.QueryDependencyCosts +OAI.Combinatorics.EditApproximation.Queries.QueryDependencyExpansion +OAI.Combinatorics.EditApproximation.Queries.QueryEarlierInputs +OAI.Combinatorics.EditApproximation.Queries.QueryEligibilitySpace +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyActive +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyMemo +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyMemoSpace +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyNormalize +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyReaderBounds +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinement +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyRefinementCost +OAI.Combinatorics.EditApproximation.Queries.QueryFamilyScalarReads +OAI.Combinatorics.EditApproximation.Queries.QueryFamilySourceCosts +OAI.Combinatorics.EditApproximation.Queries.QueryFamilySpace +OAI.Combinatorics.EditApproximation.Queries.QueryFinishCost +OAI.Combinatorics.EditApproximation.Queries.QueryGapStateCost +OAI.Combinatorics.EditApproximation.Queries.QueryGatherPolynomial +OAI.Combinatorics.EditApproximation.Queries.QueryGatherSpace +OAI.Combinatorics.EditApproximation.Queries.QueryGridCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupInputs +OAI.Combinatorics.EditApproximation.Queries.QueryGroupKeyCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupLabelCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSampleCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSamples +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSetupSpace +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceCost +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSourceSpace +OAI.Combinatorics.EditApproximation.Queries.QueryGroupSources +OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBounds +OAI.Combinatorics.EditApproximation.Queries.QueryHistoryBufferCost +OAI.Combinatorics.EditApproximation.Queries.QueryHistoryCodeBounds +OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputCost +OAI.Combinatorics.EditApproximation.Queries.QueryHistoryInputs +OAI.Combinatorics.EditApproximation.Queries.QueryHistorySemantic +OAI.Combinatorics.EditApproximation.Queries.QueryHistorySpace +OAI.Combinatorics.EditApproximation.Queries.QueryIndexedSlice +OAI.Combinatorics.EditApproximation.Queries.QueryIndexedSpace +OAI.Combinatorics.EditApproximation.Queries.QueryInitialCenterCost +OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeCenters +OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeProgram +OAI.Combinatorics.EditApproximation.Queries.QueryInitialConeSpace +OAI.Combinatorics.EditApproximation.Queries.QueryInitialGather +OAI.Combinatorics.EditApproximation.Queries.QueryInitialProgramCost +OAI.Combinatorics.EditApproximation.Queries.QueryInitialSpace +OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupport +OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupportCost +OAI.Combinatorics.EditApproximation.Queries.QueryInitialSupportSpace +OAI.Combinatorics.EditApproximation.Queries.QueryInitialWarmupPolynomial +OAI.Combinatorics.EditApproximation.Queries.QueryInputCodes +OAI.Combinatorics.EditApproximation.Queries.QueryInputSpace +OAI.Combinatorics.EditApproximation.Queries.QueryListWork +OAI.Combinatorics.EditApproximation.Queries.QueryLocalBand +OAI.Combinatorics.EditApproximation.Queries.QueryLocalBandCost +OAI.Combinatorics.EditApproximation.Queries.QueryLocalBuffers +OAI.Combinatorics.EditApproximation.Queries.QueryLocalFinishCost +OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgram +OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgramCost +OAI.Combinatorics.EditApproximation.Queries.QueryLocalProgramSpace +OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinement +OAI.Combinatorics.EditApproximation.Queries.QueryLocalRefinementCost +OAI.Combinatorics.EditApproximation.Queries.QueryLocalRepresentativeSpace +OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectorSpace +OAI.Combinatorics.EditApproximation.Queries.QueryLocalSelectors +OAI.Combinatorics.EditApproximation.Queries.QueryLocalSources +OAI.Combinatorics.EditApproximation.Queries.QueryLocalSourcesCost +OAI.Combinatorics.EditApproximation.Queries.QueryMeanRead +OAI.Combinatorics.EditApproximation.Queries.QueryNumericInteger +OAI.Combinatorics.EditApproximation.Queries.QueryOnlineKeyCost +OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeCost +OAI.Combinatorics.EditApproximation.Queries.QueryOnlineRangeSpace +OAI.Combinatorics.EditApproximation.Queries.QueryOnlineSources +OAI.Combinatorics.EditApproximation.Queries.QueryOrderBounds +OAI.Combinatorics.EditApproximation.Queries.QueryOrderedInputs +OAI.Combinatorics.EditApproximation.Queries.QueryOrderedSpace +OAI.Combinatorics.EditApproximation.Queries.QueryOuterGatherCost +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalInitial +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalInitialCost +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgram +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgramCost +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalProgramWidth +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaderBounds +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaderSpace +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalReaders +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarCosts +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarGuards +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalScalarReads +OAI.Combinatorics.EditApproximation.Queries.QueryPhysicalSourceCosts +OAI.Combinatorics.EditApproximation.Queries.QueryProgramPolynomial +OAI.Combinatorics.EditApproximation.Queries.QueryProgramWidth +OAI.Combinatorics.EditApproximation.Queries.QueryRawCenterCost +OAI.Combinatorics.EditApproximation.Queries.QueryRawWidthPolynomial +OAI.Combinatorics.EditApproximation.Queries.QueryReadBoundIrrelevance +OAI.Combinatorics.EditApproximation.Queries.QueryRefinementFinish +OAI.Combinatorics.EditApproximation.Queries.QueryRefinementGather +OAI.Combinatorics.EditApproximation.Queries.QueryRefinementSpace +OAI.Combinatorics.EditApproximation.Queries.QueryRefinementWorkBound +OAI.Combinatorics.EditApproximation.Queries.QueryRepresentativeCost +OAI.Combinatorics.EditApproximation.Queries.QueryRepresentativeScales +OAI.Combinatorics.EditApproximation.Queries.QueryRepresentatives +OAI.Combinatorics.EditApproximation.Queries.QueryRestrictionCost +OAI.Combinatorics.EditApproximation.Queries.QueryRestrictionSpace +OAI.Combinatorics.EditApproximation.Queries.QueryRoundedCounts +OAI.Combinatorics.EditApproximation.Queries.QueryRoundedStateCost +OAI.Combinatorics.EditApproximation.Queries.QueryScalarDispatch +OAI.Combinatorics.EditApproximation.Queries.QueryScalarGuardSpace +OAI.Combinatorics.EditApproximation.Queries.QueryScalarReadSpace +OAI.Combinatorics.EditApproximation.Queries.QueryScopedOrder +OAI.Combinatorics.EditApproximation.Queries.QueryScopedSourceCost +OAI.Combinatorics.EditApproximation.Queries.QuerySelectorCost +OAI.Combinatorics.EditApproximation.Queries.QuerySelectorGeometry +OAI.Combinatorics.EditApproximation.Queries.QuerySemanticRestriction +OAI.Combinatorics.EditApproximation.Queries.QuerySharedCellCost +OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometry +OAI.Combinatorics.EditApproximation.Queries.QuerySharedGeometrySpace +OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputCost +OAI.Combinatorics.EditApproximation.Queries.QuerySharedInputs +OAI.Combinatorics.EditApproximation.Queries.QuerySharedSpace +OAI.Combinatorics.EditApproximation.Queries.QuerySourceBufferBounds +OAI.Combinatorics.EditApproximation.Queries.QuerySourceBuffers +OAI.Combinatorics.EditApproximation.Queries.QuerySourceGatherCost +OAI.Combinatorics.EditApproximation.Queries.QuerySourceKeyWidths +OAI.Combinatorics.EditApproximation.Queries.QuerySourceWidths +OAI.Combinatorics.EditApproximation.Queries.QuerySourceWork +OAI.Combinatorics.EditApproximation.Queries.QueryTableSemanticCost +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupBuffers +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgram +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupProgramCost +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupSpace +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupUniformCost +OAI.Combinatorics.EditApproximation.Queries.QueryWarmupWidth +OAI.Combinatorics.EditApproximation.Queries.QueryWeightedWork +OAI.Combinatorics.EditApproximation.Queries.QueryWideBounds +OAI.Combinatorics.EditApproximation.Refinement.ComputedActualBandWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedAddressWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedBandSpacing +OAI.Combinatorics.EditApproximation.Refinement.ComputedBands +OAI.Combinatorics.EditApproximation.Refinement.ComputedBaseStorage +OAI.Combinatorics.EditApproximation.Refinement.ComputedBinaryOnlineParameters +OAI.Combinatorics.EditApproximation.Refinement.ComputedCacheWords +OAI.Combinatorics.EditApproximation.Refinement.ComputedChargedQueryBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedChargedRandomBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedChargedRandomSourceCost +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseArrayStorage +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitParameters +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBitWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBits +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseCandidateWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseControlSpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseCopySpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseExecution +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistory +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseHistorySpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseIndexedWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInitialWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseInputWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePolynomial +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarsePreparation +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseReadBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseSamplingWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseScratchSpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedCoarseWidthCost +OAI.Combinatorics.EditApproximation.Refinement.ComputedComparisonBand +OAI.Combinatorics.EditApproximation.Refinement.ComputedCurrentQueryBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierHistory +OAI.Combinatorics.EditApproximation.Refinement.ComputedEarlierInputBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionCosts +OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionKernelWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionLaw +OAI.Combinatorics.EditApproximation.Refinement.ComputedExecutionWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyEncoding +OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilyMemoCode +OAI.Combinatorics.EditApproximation.Refinement.ComputedFamilySampling +OAI.Combinatorics.EditApproximation.Refinement.ComputedFreshWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedGlobalSourceCost +OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupAccuracy +OAI.Combinatorics.EditApproximation.Refinement.ComputedGroupNumerical +OAI.Combinatorics.EditApproximation.Refinement.ComputedIndexedCoarseWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedJointCoarseWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedKernelWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedLocalKernelWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedNumericalParameters +OAI.Combinatorics.EditApproximation.Refinement.ComputedOptimizerBitWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedOutputWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedParameterRegisters +OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalCoarseWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalUniform +OAI.Combinatorics.EditApproximation.Refinement.ComputedPhysicalWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedPreevaluation +OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedInputBounds +OAI.Combinatorics.EditApproximation.Refinement.ComputedPreparedWords +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryAnswer +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryBudgetAlgebra +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryConstants +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryCorrect +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryExecution +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryHeap +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryMemo +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryNormalizationBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryNumericZero +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryOutput +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryProgramWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryRawWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryReadBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryRegisters +OAI.Combinatorics.EditApproximation.Refinement.ComputedQuerySetup +OAI.Combinatorics.EditApproximation.Refinement.ComputedQuerySetupSpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryStorage +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTableBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTableWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryTemporarySpace +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWarmupBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWidth +OAI.Combinatorics.EditApproximation.Refinement.ComputedQueryWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedRandomPhysicalCost +OAI.Combinatorics.EditApproximation.Refinement.ComputedRandomTableCost +OAI.Combinatorics.EditApproximation.Refinement.ComputedReadChargedWork +OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementReadBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedRefinementWords +OAI.Combinatorics.EditApproximation.Refinement.ComputedRetainedValues +OAI.Combinatorics.EditApproximation.Refinement.ComputedScalarCodeBits +OAI.Combinatorics.EditApproximation.Refinement.ComputedSeed +OAI.Combinatorics.EditApproximation.Refinement.ComputedSeedWords +OAI.Combinatorics.EditApproximation.Refinement.ComputedSourceAddressBits +OAI.Combinatorics.EditApproximation.Refinement.ComputedSourceReadBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedStageParameters +OAI.Combinatorics.EditApproximation.Refinement.ComputedStageTime +OAI.Combinatorics.EditApproximation.Refinement.ComputedWarmupReadBudget +OAI.Combinatorics.EditApproximation.Refinement.ComputedWidthEnvelope +OAI.Combinatorics.EditApproximation.Refinement.PhysicalBinaryMass +OAI.Combinatorics.EditApproximation.Refinement.PhysicalBinaryStep +OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundedQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalBoundsAllSeeds +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCachedWords +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseBitWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseExecution +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseInputWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarsePreparation +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSamplingWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCoarseSeedLaw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalCommonSource +OAI.Combinatorics.EditApproximation.Refinement.PhysicalComparisonBand +OAI.Combinatorics.EditApproximation.Refinement.PhysicalConditionalAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalConditionalNode +OAI.Combinatorics.EditApproximation.Refinement.PhysicalDenominator +OAI.Combinatorics.EditApproximation.Refinement.PhysicalDependencyRank +OAI.Combinatorics.EditApproximation.Refinement.PhysicalExpectedRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyCoarseWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyEncoding +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyMemo +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyMemoCoarse +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyOutput +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyRejectionWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyRuntime +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilySampling +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilySeedTrace +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyTrace +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFamilyWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalFinalAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalGenericRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalGlobalQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalGlobalValue +OAI.Combinatorics.EditApproximation.Refinement.PhysicalGroupAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalIndexedCoarseWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalInitial +OAI.Combinatorics.EditApproximation.Refinement.PhysicalInputEncoding +OAI.Combinatorics.EditApproximation.Refinement.PhysicalInputGuard +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLeaves +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalDenominator +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalGroupKeys +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalGroupProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalJointProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalOnlineEquality +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalOnlineKeys +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalProgramEquality +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalProgramLaw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinement +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalRefinementEquality +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalValueBits +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalValueLaw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalLocalWarmup +OAI.Combinatorics.EditApproximation.Refinement.PhysicalMedianQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalNodeEncoding +OAI.Combinatorics.EditApproximation.Refinement.PhysicalNodeRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineBand +OAI.Combinatorics.EditApproximation.Refinement.PhysicalOnlineLocality +OAI.Combinatorics.EditApproximation.Refinement.PhysicalParentDraw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalPreparedInputBounds +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramComparisonRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramLaw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramNodeRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramRefreshWiring +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramStateAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalProgramSubtreeRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryBudget +OAI.Combinatorics.EditApproximation.Refinement.PhysicalQueryProgress +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedCost +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomBoundedQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomDataRequest +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomGlobalProgress +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomGlobalQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomPassCopy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomRankCost +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomRequestBounds +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomRequestProgress +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomSourceCost +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRandomValue +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRationalWarmup +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRawGroupProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRawOnlineProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinement +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementDataRequest +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementInvariants +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementLocality +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementReadWork +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementRequest +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRefinementSpatial +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestBits +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestEncoding +OAI.Combinatorics.EditApproximation.Refinement.PhysicalRequestGrid +OAI.Combinatorics.EditApproximation.Refinement.PhysicalResampledRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarCodeBits +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarEncoding +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarFamily +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarFamilyLaw +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarReadCost +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarReads +OAI.Combinatorics.EditApproximation.Refinement.PhysicalScalarSource +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedMedian +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedPass +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedSchedule +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSeedTables +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSelectionProgram +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSelectionResampling +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSpatial +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtree +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeBad +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeBudget +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeCharges +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeExpectation +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeGeneric +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeMass +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeNear +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreePrediction +OAI.Combinatorics.EditApproximation.Refinement.PhysicalSubtreeRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeBudget +OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeExpectation +OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeGeneric +OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeNear +OAI.Combinatorics.EditApproximation.Refinement.PhysicalTreeRegret +OAI.Combinatorics.EditApproximation.Refinement.PhysicalUniformAccuracy +OAI.Combinatorics.EditApproximation.Refinement.PhysicalUnskippedComparison +OAI.Combinatorics.EditApproximation.Refinement.PhysicalValueBits +OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmup +OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupQuery +OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupSlack +OAI.Combinatorics.EditApproximation.Refinement.PhysicalWarmupStepQuery +OAI.Combinatorics.EditApproximation.Refinement.StageComparison +OAI.Combinatorics.EditApproximation.Refinement.StageComparisonBad +OAI.Combinatorics.EditApproximation.Refinement.StageComparisonCharges +OAI.Combinatorics.EditApproximation.Refinement.StageComparisonEnergy +OAI.Combinatorics.EditApproximation.Refinement.StageComparisonPrediction +OAI.Combinatorics.EditApproximation.Refinement.StageParameterBounds +OAI.Combinatorics.EditApproximation.Refinement.StageTerminal +OAI.Combinatorics.EditApproximation.Refinement.StageWarmup +OAI.Combinatorics.EditApproximation.Specification.ConcreteFootprintBridges +OAI.Combinatorics.EditApproximation.Specification.ConcreteFootprints +OAI.Combinatorics.EditApproximation.Specification.Footprint +OAI.Combinatorics.EditApproximation.Specification.FootprintMain +OAI.Combinatorics.EditApproximation.Specification.RawBand +OAI.Combinatorics.EditApproximation.Specification.RawBandBridges +OAI.Combinatorics.EditApproximation.Specification.RawBandConsumers +OAI.Combinatorics.EditApproximation.Specification.RawBandMain +OAI.Combinatorics.EditApproximation.Specification.RawBandOuter +OAI.Combinatorics.EditApproximation.Specification.RawBandOuterBridges +OAI.Combinatorics.EditApproximation.Specification.RawBandPipeline +OAI.Combinatorics.EditApproximation.Specification.RawBandPipelineBridges +OAI.Combinatorics.EditApproximation.Specification.RawBandPipelineFootprintBridges +OAI.Combinatorics.EditDistance.Metric +OAI.Combinatorics.EditDistance.Model diff --git a/tasks/edit-approximation/solution/reference.py b/tasks/edit-approximation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/edit-approximation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/edit-approximation/solution/solve.sh b/tasks/edit-approximation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3d3d663190dd97ac60372ed1e062ce9d5caf115 --- /dev/null +++ b/tasks/edit-approximation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EditApproximation, i.e. module OAI.Combinatorics.EditApproximation.Specification.RawBandMain and the +# 1024 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EditApproximation.Specification.RawBandMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EditApproximation" diff --git a/tasks/edit-approximation/task.toml b/tasks/edit-approximation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a489b7e0d6d5825c62b712a74c849032ee21275a --- /dev/null +++ b/tasks/edit-approximation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/edit-approximation" +version = "1.0.0" +description = "Prove EditApproximation (openai/math family 121: Almost-linear expected-time approximation of edit distance) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EditApproximation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EditApproximation" +family = "121" +family_title = "Almost-linear expected-time approximation of edit distance" +subject = "Theoretical computer science" +theorems = ["OAI.EditApproximation.almostLinearEditDistanceRawBand"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EditApproximation.Specification.RawBandMain" +reference_modules = 1024 +reference_lean_bytes = 7591774 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3183 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 18532 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/edit-approximation/tests/Challenge.lean b/tasks/edit-approximation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..31c0e5b3484e9a91d5f1eeea7bb2d69a1dcb8105 --- /dev/null +++ b/tasks/edit-approximation/tests/Challenge.lean @@ -0,0 +1,19169 @@ +import Mathlib + +namespace OAI.EditDistortion +end OAI.EditDistortion + +/-! A uniform almost-linear approximation scheme for edit distance. +The statement retains the concrete binary algorithm and its exact resource accounting. -/ + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bitWordValue : List Bool → ℕ + | [] => 0 + | bit :: bits => bit.toNat + 2 * bitWordValue bits + +def bitSum (a b carry : Bool) : Bool := xor (xor a b) carry + +def bitCarry (a b carry : Bool) : Bool := (a && b) || (a && carry) || (b && carry) + +structure UnreducedRational where + num : ℤ + den : ℕ + den_pos : 0 < den + +def orderingMatches (o : Ordering) (a b : ℕ) : Prop := + (o = .lt ∧ a < b) ∨ (o = .eq ∧ a = b) ∨ (o = .gt ∧ b < a) + +def bitOrdering (high : Ordering) (a b : Bool) : Ordering := + match high with + | .lt => .lt + | .gt => .gt + | .eq => if a = b then .eq else if a then .gt else .lt + +def bitDifference (a b borrow : Bool) : Bool := xor (xor a b) borrow + +def bitBorrow (a b borrow : Bool) : Bool := ((!a) && (b || borrow)) || (b && borrow) + +structure SignedBinary where + negative : Bool + bits : List Bool + +def signedMagnitude (negative : Bool) (magnitude : ℕ) : ℤ := + if negative then -(magnitude : ℤ) else magnitude + +def trimBitWordWithWork : List Bool → List Bool × ℕ + | [] => ([], 1) + | bit :: bits => + let tail := trimBitWordWithWork bits + (if tail.1 = [] ∧ bit = false then [] else bit :: tail.1, tail.2 + 3) + +def balancedCut (lo width M i : ℕ) : ℕ := lo + i * width / M + +def gridRound (spacing position : ℕ) : ℕ := spacing * (position / spacing) + +def rationalMinimum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => min value (rationalMinimum fallback rest) + +structure RationalBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : ℚ + childState : Fin M → Child + +def rationalRefinementUpdate (δ cone : ℚ) : Option ℚ → ℚ + | none => cone + | some online => min cone (max (cone / (1 + δ)) online) + +def heightExponent (N : ℕ) : ℕ := Nat.clog 2 (Nat.clog 2 (N + 2)) + +def coarseExponent (ell : ℕ) : ℕ := Nat.sqrt (Nat.sqrt (Nat.log 2 ell)) + +structure IntegerParameters where + H : ℕ + ell : ℕ + p : ℕ + B : ℕ + initialFactor : ℕ + M : ℕ + P : ℕ + T : ℕ + S : ℕ + +structure RationalParameters where + F : ℚ + initialSlope : ℚ + coneSlope : ℚ + delta : ℚ + kappa : ℚ + tau : ℚ + theta : ℚ + gamma : ℚ + eta : ℚ + +def gridPointsBetween (g lo hi : ℕ) : List ℕ := + (List.range' (lo ⌈/⌉ g) ((hi / g + 1) - lo ⌈/⌉ g)).map fun i => g * i + +def scaledSeedValue (U : ℕ) (a gap : ℚ) : ℚ := + max (⌈(U : ℚ) / a⌉₊ : ℚ) |gap| + +def dyadicScales (N : ℕ) : List ℕ := + (List.range (Nat.log 2 N + 1)).map fun k => 2 ^ k + +def seedGridSpacing (b P : ℕ) : ℕ := max 1 (b / P) + +def finiteAssignments {α : Type u_1} : (M : ℕ) → (Fin M → List α) → List (Fin M → α) + | 0, _ => [Fin.elim0] + | M + 1, choices => + (choices 0).flatMap fun head => + (finiteAssignments M (fun i => choices i.succ)).map fun tail => Fin.cons head tail + +def powerTwoWord (n : ℕ) : List Bool := List.replicate n false ++ [true] + +def filterWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 0) + | a :: rest => + let current := test a + let tail := filterWithWork test rest + (if current.1 then a :: tail.1 else tail.1, current.2 + tail.2 + 3) + +def allWithWork {α : Type u_1} (test : α → Bool × ℕ) : List α → Bool × ℕ + | [] => (true, 0) + | a :: rest => + let current := test a + let tail := allWithWork test rest + (current.1 && tail.1, current.2 + tail.2 + 3) + +def arithmeticMapWithWork {α : Type u_1} {β : Type u_2} (f : α → β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticMapWithWork f rest + (current.1 :: tail.1, current.2 + tail.2 + 3) + +def arithmeticFlatMapWithWork {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let current := f a + let tail := arithmeticFlatMapWithWork f rest + (current.1 ++ tail.1, current.2 + tail.2 + current.1.length + 3) + +def upperMedian (values : List ℕ) : ℕ := + (values.mergeSort (· ≤ ·)).getD (values.length / 2) 0 + +def filterMapWithWork {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) : List α → List β × ℕ + | [] => ([], 0) + | a :: rest => + let first := f a + let tail := filterMapWithWork f rest + (match first.1 with | none => tail.1 | some b => b :: tail.1, first.2 + tail.2 + 3) + +def cellGridPoints (side : ℚ) (g cell : ℕ) : List ℕ := + (List.range' ⌈(cell : ℚ) * side / g⌉₊ + (⌈((cell : ℚ) + 1) * side / g⌉₊ - ⌈(cell : ℚ) * side / g⌉₊)).map fun i => g * i + +def groupRoundSpacing (exponent : ℕ) (h : ℚ) : ℕ := + ⌈max 1 ((2 : ℚ) ^ (-(exponent : ℤ)) * h)⌉₊ + +def refinementFactor (A : ℚ) (F : ℕ) : ℚ := max 1 (A / F) + +def localCellCoordinates (side : ℚ) (p radius : ℕ) : List ℕ := + let first := ⌊((p - radius : ℕ) : ℚ) / side⌋₊ + let last := ⌊((p + radius : ℕ) : ℚ) / side⌋₊ + List.range' first (last + 1 - first) + +def dyadicSeedPassCount (f initial : ℕ) : ℕ := (initial - f) ⌈/⌉ (f - 2) + +def dyadicSeedExponent (f initial pass : ℕ) : ℕ := initial - pass * (f - 2) + +def memberByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := equal a b + let tail := memberByWithWork equal a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +inductive BinaryMemo (α : Type u_1) where + | empty + | node (value : Option α) (left right : BinaryMemo α) + +def binaryMemoKey : ℕ → ℕ → List Bool + | 0, _ => [] + | d + 1, n => decide (n % 2 = 1) :: binaryMemoKey d (n / 2) + +inductive FiniteQuery (ι : Type u_1) where + | done (value : ℚ) + | read (key : ι) (next : ℚ → FiniteQuery ι) + +def finiteAnswerTable {κ : Type u_1} [DecidableEq κ] : List κ → List ℚ → κ → ℚ + | key :: keys, value :: values, query => + if query = key then value else finiteAnswerTable keys values query + | _, _, _ => 0 + +def queryFinRange (n m : ℕ) (h : n = m) : List (Fin m) := + (List.finRange n).map fun i => ⟨i.val, by simpa only [← h] using i.isLt⟩ + +def queryInsertWithWork {α : Type u_1} (le : α → α → Bool × ℕ) (a : α) : List α → List α × ℕ + | [] => ([a], 1) + | b :: rest => + let test := le a b + if test.1 then (a :: b :: rest, test.2 + 2) + else + let tail := queryInsertWithWork le a rest + (b :: tail.1, test.2 + tail.2 + 2) + +def integerSymbolCode : ℤ → ℕ + | .ofNat n => 2 * n + | .negSucc n => 2 * n + 1 + +inductive PositionCounts where + | empty + | node (count : ℕ) (left right : PositionCounts) + +def integerMagnitude : List ℤ → ℕ + | [] => 0 + | z :: zs => max z.natAbs (integerMagnitude zs) + +def integerInputPositionBits (target : List ℤ) : ℕ := Nat.size target.length + +def dpLength {α : Type u_1} : List α → ℕ × ℕ + | [] => (0, 1) + | _ :: rest => let result := dpLength rest; (result.1 + 1, result.2 + 1) + +def dpDrop {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, word => (word, 1) + | _ + 1, [] => ([], 1) + | n + 1, _ :: rest => let result := dpDrop n rest; (result.1, result.2 + 1) + +def dpTake {α : Type u_1} : ℕ → List α → List α × ℕ + | 0, _ => ([], 1) + | _ + 1, [] => ([], 1) + | n + 1, first :: rest => let result := dpTake n rest; (first :: result.1, result.2 + 1) + +def dpGetD : List ℕ → ℕ → ℕ × ℕ + | [], _ => (0, 1) + | first :: _, 0 => (first, 1) + | _ :: rest, n + 1 => let result := dpGetD rest n; (result.1, result.2 + 1) + +def dpMember {α : Type u_1} [DecidableEq α] (a : α) : List α → Bool × ℕ + | [] => (false, 1) + | first :: rest => if a = first then (true, 1) else + let result := dpMember a rest; (result.1, result.2 + 1) + +def dpMinimum (fallback : ℕ) : List ℕ → ℕ × ℕ + | [] => (fallback, 1) + | first :: rest => let result := dpMinimum fallback rest; (min first result.1, result.2 + 1) + +def integerMagnitudeWithWork : List ℤ → ℕ × ℕ + | [] => (0, 0) + | z :: rest => + let tail := integerMagnitudeWithWork rest + (max z.natAbs tail.1, tail.2 + 2) + +def inputBitLengthWithWork (n : ℕ) : ℕ × ℕ := + if h : n = 0 then (0, 1) else + let tail := inputBitLengthWithWork (n / 2) + (tail.1 + 1, tail.2 + 2) +termination_by n +decreasing_by exact Nat.div_lt_self (by omega) (by decide) + +def naturalPairWithWork (a b : ℕ) : ℕ × ℕ := + if a < b then (b * b + a, 4) else (a * a + a + b, 5) + +def inspectBitPrefix : ℕ → List Bool → Bool × ℕ + | 0, [] => (true, 1) + | 0, _ :: _ => (false, 1) + | _ + 1, [] => (true, 1) + | n + 1, _ :: rest => + let result := inspectBitPrefix n rest + (result.1, result.2 + 1) + +def memoRequestCells (bits addressCells : ℕ) : ℕ := addressCells + 8 * (bits + 1) + 64 + +def arithmeticMapAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => allocation a + arithmeticMapAllocation allocation rest + 1 + +def arithmeticFlatMapAllocation {α : Type u_1} {β : Type u_2} (f : α → List β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + arithmeticFlatMapAllocation f allocation xs + (f x).1.length + +def filterAllocation {α : Type u_1} (test : α → Bool × ℕ) (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterAllocation test allocation xs + if (test x).1 then 1 else 0 + +def filterMapAllocation {α : Type u_1} {β : Type u_2} (f : α → Option β × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + filterMapAllocation f allocation xs + if (f x).1.isSome then 1 else 0 + +def naturalEqualAllocation (a b : ℕ) : ℕ := a.bits.length + b.bits.length + 1 + +def memberByAllocation {α : Type u_1} (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 0 + | b :: rest => allocation a b + memberByAllocation allocation a rest + 1 + +def naturalWordLEAllocation (a b : List Bool) : ℕ := a.length + b.length + 1 + +def vectorMapAllocation (d : ℕ) (allocation : Fin d → ℕ) : ℕ := + (∑ i, allocation i) + 3 * d + +def allAllocation {α : Type u_1} (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | x :: xs => allocation x + allAllocation allocation xs + 1 + +def queryInsertAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (a : α) : List α → ℕ + | [] => 1 + | b :: rest => allocation a b + if (le a b).1 then 2 else queryInsertAllocation le allocation a rest + 1 + +def wordLEAllocation (_a _b : List Bool) : ℕ := 0 + +def indexedLeafAllocation (symbolBits positionBits : ℕ) (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + match symbol with + | none => 1 + | some _ => if lo = hi then 1 else symbolBits + 2 * positionBits + 4 + +def storedNaturalBits (values : List ℕ) : ℕ := + 1 + (values.map fun a => Nat.size a + 1).sum + +def coarseHistoryKeyCost {α : Type u_1} {β : Type u_2} {ι : Type u_3} (cost : ι → ℕ) : Sum α (Sum ι β) → ℕ + | .inr (.inl entry) => cost entry + | _ => 0 + +def bitAddNilLeftWithWork (right : List Bool) (carry : Bool) : List Bool × ℕ := + match right with + | [] => (if carry then [true] else [], 1) + | b :: bs => + let rest := bitAddNilLeftWithWork bs (OAI.EditApproximation.bitCarry false b carry) + (OAI.EditApproximation.bitSum false b carry :: rest.1, rest.2 + 9) +termination_by structural right + +def bitCompareNilLeftWithWork (right : List Bool) : Ordering × ℕ := + match right with + | [] => (.eq, 1) + | b :: bs => + let high := bitCompareNilLeftWithWork bs + (OAI.EditApproximation.bitOrdering high.1 false b, high.2 + 4) +termination_by structural right + +def bitSubtractNilLeftWithWork (right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match right with + | [] => ([], borrow, 1) + | b :: bs => + let rest := bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow) + (OAI.EditApproximation.bitDifference false b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural right + +structure BinaryFraction where + numerator : OAI.EditApproximation.SignedBinary + denominator : List Bool + denominator_pos : 0 < OAI.EditApproximation.bitWordValue denominator + +def rationalActionValue {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → ℚ) (L : ℚ) (child : Child → ℚ) + (query : Parent) (action : OAI.EditApproximation.RationalBellmanAction Parent Child M) : ℚ := + L * distance query action.center + action.connection + ∑ i, child (action.childState i) + +def inputHeight (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.heightExponent N + +def smallLogExponent (N : ℕ) : ℕ := Nat.clog 2 (max 1 (OAI.EditApproximation.heightExponent N)) + +def rationalParameters (ell : ℕ) : OAI.EditApproximation.RationalParameters := + { F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (ell : ℚ) ^ 10, kappa := 1 / (ell : ℚ) ^ 4, + tau := 1 / (ell : ℚ) ^ 4, theta := 1 / (ell : ℚ) ^ 40, + gamma := 1 / (ell : ℚ) ^ 20, eta := (ell : ℚ) ^ 5 } + +def materializedAssignmentsWithWork {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → List (Vector α M) × ℕ + | 0, _ => ([Vector.ofFn Fin.elim0], 1) + | M + 1, choices => + let previous := materializedAssignmentsWithWork M (fun i => choices i.succ) + let expanded := OAI.EditApproximation.arithmeticFlatMapWithWork (fun head => + OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous.1) (choices 0) + (expanded.1, previous.2 + expanded.2 + 1) + +def dyadicScalesWithWork (N : ℕ) : List ℕ × ℕ := + let count := max 1 N.bits.length + let values := OAI.EditApproximation.arithmeticMapWithWork (fun e => + let word := OAI.EditApproximation.powerTwoWord e + (OAI.EditApproximation.bitWordValue word, e + 3)) (List.range count) + (values.1, values.2 + N.bits.length + count + 2) + +def dedupByWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := dedupByWithWork equal rest + let member := OAI.EditApproximation.memberByWithWork equal a rest + (if member.1 then tail.1 else a :: tail.1, tail.2 + member.2 + 2) + +def queryEraseLoopWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) : + List α → List α → List α × ℕ + | [], seen => (seen.reverse, seen.length + 1) + | a :: rest, seen => + let test := OAI.EditApproximation.memberByWithWork equal a seen + let tail := queryEraseLoopWithWork equal rest (if test.1 then seen else a :: seen) + (tail.1, test.2 + tail.2 + 2) + +structure RecursiveMemoResult (κ : Type u_1) where + value : ℚ + memory : OAI.EditApproximation.BinaryMemo ℚ + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + +def querySortWithWork {α : Type u_1} (le : α → α → Bool × ℕ) : List α → List α × ℕ + | [] => ([], 1) + | a :: rest => + let tail := querySortWithWork le rest + let inserted := OAI.EditApproximation.queryInsertWithWork le a tail.1 + (inserted.1, tail.2 + inserted.2 + 1) + +def encodeIntegerSymbolsWithWork : List ℤ → List ℕ × ℕ + | [] => ([], 0) + | z :: zs => + let rest := encodeIntegerSymbolsWithWork zs + (OAI.EditApproximation.integerSymbolCode z :: rest.1, rest.2 + 3) + +def integerInputSymbolBits (source target : List ℤ) : ℕ := + Nat.size (2 * OAI.EditApproximation.integerMagnitude (source ++ target)) + +def dpSingleton {α : Type u_1} [DecidableEq α] (a : α) (word : List α) : ℕ × ℕ := + if word = [] then (1, 1) else + let count := OAI.EditApproximation.dpLength word + let found := OAI.EditApproximation.dpMember a word + (count.1 - if found.1 then 1 else 0, count.2 + found.2 + 2) + +def dpCandidateAllocation {α : Type u_1} (target : List α) (j k : ℕ) : ℕ := + (OAI.EditApproximation.dpTake k (OAI.EditApproximation.dpDrop j target).1).1.length + +def integerInputInspectionWithWork (source target : List ℤ) : (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.integerMagnitudeWithWork source + let right := OAI.EditApproximation.integerMagnitudeWithWork target + let lengths := (OAI.EditApproximation.dpLength source, OAI.EditApproximation.dpLength target) + let symbols := OAI.EditApproximation.inputBitLengthWithWork (2 * max left.1 right.1) + let positions := OAI.EditApproximation.inputBitLengthWithWork lengths.2.1 + ((symbols.1, positions.1), + left.2 + right.2 + lengths.1.2 + lengths.2.2 + symbols.2 + positions.2 + 4) + +def bitAddNilLeftAllocation (right : List Bool) (carry : Bool) : ℕ := + match right with + | [] => if carry then 1 else 0 + | b :: bs => bitAddNilLeftAllocation bs (OAI.EditApproximation.bitCarry false b carry) + 1 +termination_by structural right + +def bitSubtractNilLeftAllocation (right : List Bool) (borrow : Bool) : ℕ := + match right with + | [] => 0 + | b :: bs => bitSubtractNilLeftAllocation bs (OAI.EditApproximation.bitBorrow false b borrow) + 1 +termination_by structural right + +def trimBitWordAllocation : List Bool → ℕ + | [] => 0 + | bit :: bits => trimBitWordAllocation bits + + if (OAI.EditApproximation.trimBitWordWithWork bits).1 = [] ∧ bit = false then 0 else 1 + +def dedupByAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => dedupByAllocation equal allocation rest + OAI.EditApproximation.memberByAllocation allocation a rest + + if (OAI.EditApproximation.memberByWithWork equal a rest).1 then 0 else 1 + +def dyadicScalesAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (List.range (max 1 N.bits.length)) + N.bits.length + max 1 N.bits.length + +def queryRangeValidAllocation (B range : ℕ) : ℕ := + (0 : ℕ).bits.length + range.bits.length + OAI.EditApproximation.naturalWordLEAllocation range.bits B.bits + +def queryEraseLoopAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → List α → ℕ + | [], seen => seen.length + | a :: rest, seen => + OAI.EditApproximation.memberByAllocation allocation a seen + + queryEraseLoopAllocation equal allocation rest (if (OAI.EditApproximation.memberByWithWork equal a seen).1 then seen else a :: seen) + + if (OAI.EditApproximation.memberByWithWork equal a seen).1 then 0 else 1 + +def queryEncodedLEAllocation {α : Type u_1} (code : α → ℕ × ℕ) (allocation : α → ℕ) (a b : α) : ℕ := + allocation a + allocation b + OAI.EditApproximation.naturalWordLEAllocation (code a).1.bits (code b).1.bits + + Nat.size (code a).1 + Nat.size (code b).1 + +def bitAddWithWork (left right : List Bool) (carry : Bool) : List Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftWithWork right carry + | a :: as => + match right with + | [] => + let rest := bitAddWithWork as [] (OAI.EditApproximation.bitCarry a false carry) + (OAI.EditApproximation.bitSum a false carry :: rest.1, rest.2 + 9) + | b :: bs => + let rest := bitAddWithWork as bs (OAI.EditApproximation.bitCarry a b carry) + (OAI.EditApproximation.bitSum a b carry :: rest.1, rest.2 + 9) +termination_by structural left + +def bitCompareWithWork (left right : List Bool) : Ordering × ℕ := + match left with + | [] => OAI.EditApproximation.bitCompareNilLeftWithWork right + | a :: as => + match right with + | [] => + let high := bitCompareWithWork as [] + (OAI.EditApproximation.bitOrdering high.1 a false, high.2 + 4) + | b :: bs => + let high := bitCompareWithWork as bs + (OAI.EditApproximation.bitOrdering high.1 a b, high.2 + 4) +termination_by structural left + +def bitSubtractWithWork (left right : List Bool) (borrow : Bool) : List Bool × Bool × ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftWithWork right borrow + | a :: as => + match right with + | [] => + let rest := bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow) + (OAI.EditApproximation.bitDifference a false borrow :: rest.1, rest.2.1, rest.2.2 + 9) + | b :: bs => + let rest := bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow) + (OAI.EditApproximation.bitDifference a b borrow :: rest.1, rest.2.1, rest.2.2 + 9) +termination_by structural left + +def rationalBellman {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (fallback : Parent → ℚ) (distance : Parent → Parent → ℚ) (L : ℚ) + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) (child : Child → ℚ) (query : Parent) : ℚ := + OAI.EditApproximation.rationalMinimum (fallback query) (actions.map (OAI.EditApproximation.rationalActionValue distance L child query)) + +def inputSmallLog (N : ℕ) : ℕ := 2 ^ OAI.EditApproximation.smallLogExponent N + +structure BinaryBellmanAction (Parent : Type u_1) (Child : Type u_2) (M : ℕ) where + center : Parent + connection : OAI.EditApproximation.BinaryFraction + childState : Fin M → Child + +def queryEraseWithWork {α : Type u_1} (equal : α → α → Bool × ℕ) (xs : List α) : + List α × ℕ := OAI.EditApproximation.queryEraseLoopWithWork equal xs [] + +inductive BitQuery (ι : Type u_1) (β : Type u_2) where + | done (value : β) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → BitQuery ι β) + | charge (work : ℕ) (next : BitQuery ι β) + +def dpCandidate {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j k : ℕ) : ℕ × ℕ := + let suffix := OAI.EditApproximation.dpDrop j target + let piece := OAI.EditApproximation.dpTake k suffix.1 + let one := OAI.EditApproximation.dpSingleton a piece.1 + let old := OAI.EditApproximation.dpGetD previous (j + k) + (one.1 + old.1, suffix.2 + piece.2 + one.2 + old.2 + 3) + +def dpCellAllocation {α : Type u_1} (target : List α) (j : ℕ) : ℕ := + OAI.EditApproximation.dpCandidateAllocation target j 0 + + ((List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidateAllocation target j)).sum + + 4 * (target.length - j + 1) + +def initialThresholdQ (N : ℕ) : ℚ := (OAI.EditApproximation.inputHeight N : ℚ) ^ 4 + +def initialLambda (N : ℕ) : ℚ := 1 / (64 * OAI.EditApproximation.inputHeight N) + +structure BitRecursiveMemoResult (κ : Type u_1) where + value : OAI.EditApproximation.BinaryFraction + memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction + freshKeys : List κ + dictionaryVisits : ℕ + requests : ℕ + localWork : ℕ + +structure RefinementParameterWords where + tau : OAI.EditApproximation.BinaryFraction + factor : OAI.EditApproximation.BinaryFraction + eta : OAI.EditApproximation.BinaryFraction + kappa : OAI.EditApproximation.BinaryFraction + delta : OAI.EditApproximation.BinaryFraction + +def inspectAccuracyWithWork (budget : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.inspectBitPrefix budget epsilon.numerator.bits + let denominator := OAI.EditApproximation.inspectBitPrefix budget epsilon.denominator + (if numerator.1 && denominator.1 then some epsilon else none, + numerator.2 + denominator.2 + 2) + +local instance queryRoundsNeZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (Nat.ne_of_gt (Nat.two_pow_pos _))⟩ + +def bitAddAllocation (left right : List Bool) (carry : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitAddNilLeftAllocation right carry + | a :: as => + match right with + | [] => bitAddAllocation as [] (OAI.EditApproximation.bitCarry a false carry) + 1 + | b :: bs => bitAddAllocation as bs (OAI.EditApproximation.bitCarry a b carry) + 1 +termination_by structural left + +def bitSubtractAllocation (left right : List Bool) (borrow : Bool) : ℕ := + match left with + | [] => OAI.EditApproximation.bitSubtractNilLeftAllocation right borrow + | a :: as => + match right with + | [] => bitSubtractAllocation as [] (OAI.EditApproximation.bitBorrow a false borrow) + 1 + | b :: bs => bitSubtractAllocation as bs (OAI.EditApproximation.bitBorrow a b borrow) + 1 +termination_by structural left + +def materializedAssignmentsAllocation {α : Type u_1} : + (M : ℕ) → (Fin M → List α) → ℕ + | 0, _ => 1 + | M + 1, choices => + let previous := (OAI.EditApproximation.materializedAssignmentsWithWork M (fun i => choices i.succ)).1 + let build := fun head => OAI.EditApproximation.arithmeticMapWithWork (fun tail : Vector α M => + (Vector.ofFn (Fin.cons head tail.get), 3 * (M + 1))) previous + materializedAssignmentsAllocation M (fun i => choices i.succ) + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Vector α M => M + 1) previous) (choices 0) + +def queryEraseAllocation {α : Type u_1} (equal : α → α → Bool × ℕ) + (allocation : α → α → ℕ) (xs : List α) : ℕ := OAI.EditApproximation.queryEraseLoopAllocation equal allocation xs [] + +def querySortAllocation {α : Type u_1} (le : α → α → Bool × ℕ) + (allocation : α → α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => querySortAllocation le allocation rest + + OAI.EditApproximation.queryInsertAllocation le allocation a (OAI.EditApproximation.querySortWithWork le rest).1 + +def binaryNaturalAddWithWork (a b : ℕ) : List Bool × ℕ := + OAI.EditApproximation.bitAddWithWork a.bits b.bits false + +def bitMulWithWork : List Bool → List Bool → List Bool × ℕ + | [], _ => ([], 1) + | bit :: bits, right => + let rest := bitMulWithWork bits right + if bit then + let total := OAI.EditApproximation.bitAddWithWork (false :: rest.1) right false + (total.1, rest.2 + total.2 + 2) + else (false :: rest.1, rest.2 + 2) + +def binaryNaturalCompareWithWork (a b : ℕ) : Ordering × ℕ := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + +def binaryNaturalSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let result := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (result.1, result.2.2) + +def integerParameters (N : ℕ) : OAI.EditApproximation.IntegerParameters := + let H := OAI.EditApproximation.inputHeight N + let ell := OAI.EditApproximation.inputSmallLog N + let p := OAI.EditApproximation.coarseExponent ell + { H, ell, p, B := H ^ p, initialFactor := H ^ (p + 4), + M := 2 ^ (OAI.EditApproximation.heightExponent N / 20), P := H ^ (p + 20), + T := 2 ^ ((3 * OAI.EditApproximation.heightExponent N + 3) / 4), S := H / ell ^ 2 } + +def bitDivModWithWork (divisor : List Bool) : List Bool → List Bool × List Bool × ℕ + | [] => ([], [], 1) + | bit :: bits => + let previous := bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + let comparison := OAI.EditApproximation.bitCompareWithWork candidate divisor + if comparison.1 = .lt then + (false :: previous.1, candidate, previous.2.2 + comparison.2 + 4) + else + let reduced := OAI.EditApproximation.bitSubtractWithWork candidate divisor false + (true :: previous.1, reduced.1, previous.2.2 + comparison.2 + reduced.2.2 + 5) + +def wordLEWithWork (a b : List Bool) : Bool × ℕ := + let compared := OAI.EditApproximation.bitCompareWithWork b a + (!(decide (compared.1 = .lt)), compared.2 + 1) + +def computedSeedInitialExponent (N : ℕ) : ℕ := + (OAI.EditApproximation.coarseExponent (OAI.EditApproximation.inputSmallLog N) + 4) * OAI.EditApproximation.heightExponent N + +def queryOrderedInputsWithWork {α : Type u_1} (equal le : α → α → Bool × ℕ) + (xs : List α) : List α × ℕ := + let unique := OAI.EditApproximation.queryEraseWithWork equal xs + let sorted := OAI.EditApproximation.querySortWithWork le unique.1 + (sorted.1, unique.2 + sorted.2 + 1) + +def queryActionInputsWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : List Child × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) actions + (inputs.1, inputs.2 + M + 1) + +def largeAccuracyInput (N : ℕ) (epsilon : ℚ) : Prop := + 2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon + +def dpCell {α : Type u_1} [DecidableEq α] (a : α) (target : List α) + (previous : List ℕ) (j : ℕ) : ℕ × ℕ := + let fallback := OAI.EditApproximation.dpCandidate a target previous j 0 + let candidates := (List.range (target.length - j + 1)).map (OAI.EditApproximation.dpCandidate a target previous j) + let minimum := OAI.EditApproximation.dpMinimum fallback.1 (candidates.map Prod.fst) + (minimum.1, fallback.2 + (candidates.map Prod.snd).sum + minimum.2 + + (OAI.EditApproximation.dpLength target).2 + 3 * candidates.length + 4) + +def suffixDPAllocation {α : Type u_1} : List α → List α → ℕ + | [], target => target.length + 1 + | _ :: rest, target => suffixDPAllocation rest target + + (List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCellAllocation target j.val).sum + + 3 * (target.length + 1) + +def binaryNaturalAddAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitAddAllocation a.bits b.bits false + +def queryOrderedInputsAllocation {α : Type u_1} (equal le : α → α → Bool × ℕ) + (equalAllocation leAllocation : α → α → ℕ) (xs : List α) : ℕ := + OAI.EditApproximation.queryEraseAllocation equal equalAllocation xs + + OAI.EditApproximation.querySortAllocation le leAllocation (OAI.EditApproximation.queryEraseWithWork equal xs).1 + +def queryActionInputsAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => (action.childState i, 1)) (List.finRange M)) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) actions + +def binaryNaturalMulWithWork (a b : ℕ) : List Bool × ℕ := OAI.EditApproximation.bitMulWithWork a.bits b.bits + +def binaryNaturalDivModWithWork (n d : ℕ) : List Bool × List Bool × ℕ := + OAI.EditApproximation.bitDivModWithWork d.bits n.bits + +def bitCeilDivWithWork (divisor bits : List Bool) : List Bool × ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + let zeroCheck := OAI.EditApproximation.bitCompareWithWork divided.2.1 [] + if zeroCheck.1 = .eq then (divided.1, divided.2.2 + zeroCheck.2 + 3) + else + let rounded := OAI.EditApproximation.bitAddWithWork divided.1 [true] false + (rounded.1, divided.2.2 + zeroCheck.2 + rounded.2 + 3) + +def wordMinWithWork (a b : List Bool) : List Bool × ℕ := + let compared := OAI.EditApproximation.wordLEWithWork a b + (if compared.1 then a else b, compared.2 + 1) + +def wordInsertWithWork (a : List Bool) : List (List Bool) → List (List Bool) × ℕ + | [] => ([a], 1) + | b :: rest => + let compared := OAI.EditApproximation.wordLEWithWork a b + if compared.1 then (a :: b :: rest, compared.2 + 2) else + let tail := wordInsertWithWork a rest + (b :: tail.1, compared.2 + tail.2 + 2) + +def saturatingSubtractWithWork (a b : ℕ) : List Bool × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then ([], test.2 + 1) else + let result := OAI.EditApproximation.binaryNaturalSubtractWithWork a b + (result.1, test.2 + result.2 + 2) + +def computedSeedPassCount (N : ℕ) : ℕ := + OAI.EditApproximation.dyadicSeedPassCount (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) + +def bitPowerWithWork (base : List Bool) : ℕ → List Bool × ℕ + | 0 => ([true], 1) + | n + 1 => + let previous := bitPowerWithWork base n + let product := OAI.EditApproximation.bitMulWithWork previous.1 base + let answer := OAI.EditApproximation.trimBitWordWithWork product.1 + (answer.1, previous.2 + product.2 + answer.2 + 2) + +def queryEncodedLEWithWork {α : Type u_1} (code : α → ℕ × ℕ) (a b : α) : Bool × ℕ := + let left := code a + let right := code b + let comparison := OAI.EditApproximation.wordLEWithWork left.1.bits right.1.bits + (comparison.1, left.2 + right.2 + comparison.2 + Nat.size left.1 + Nat.size right.1 + 3) + +instance largeAccuracyInput_decidable (N : ℕ) (epsilon : ℚ) : Decidable (OAI.EditApproximation.largeAccuracyInput N epsilon) := + inferInstanceAs (Decidable (2 ^ 1000 ≤ OAI.EditApproximation.inputSmallLog N ∧ 10 ≤ (OAI.EditApproximation.inputSmallLog N : ℚ) * epsilon)) + +def chargedSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ × ℕ + | [], target => + (List.ofFn (fun j : Fin (target.length + 1) => target.length - j.val), + 4 * (target.length + 1)) + | a :: rest, target => + let previous := chargedSuffixDP rest target + let cells := List.ofFn fun j : Fin (target.length + 1) => OAI.EditApproximation.dpCell a target previous.1 j.val + (cells.map Prod.fst, previous.2 + (cells.map Prod.snd).sum + + 2 * (OAI.EditApproximation.dpLength target).2 + 2 * cells.length + 3) + +def computedCoarseDepth (N n : ℕ) : ℕ := Nat.clog (OAI.EditApproximation.integerParameters N).B (max 1 n) + +def queryRangeValidWithWork (B range : ℕ) : Bool × ℕ := + let positive := OAI.EditApproximation.binaryNaturalCompareWithWork 0 range + let bounded := OAI.EditApproximation.wordLEWithWork range.bits B.bits + (decide (positive.1 = .lt) && bounded.1, positive.2 + bounded.2 + 2) + +def coarsePaddedReadWithWork {α : Type u_1} (n : ℕ) (source : List α) (offset : ℕ) : + Option (Option α) × ℕ := + let inside := OAI.EditApproximation.binaryNaturalCompareWithWork offset n + (if inside.1 = .lt then some source[offset]? else none, + inside.2 + Nat.size n + Nat.size offset + 2) + +def coarseRangeCopyWithWork (read : ℕ → ℕ) : ℕ → ℕ → List ℕ × ℕ + | _, 0 => ([], 1) + | start, length + 1 => + let next := OAI.EditApproximation.binaryNaturalAddWithWork start 1 + let tail := coarseRangeCopyWithWork read (OAI.EditApproximation.bitWordValue next.1) length + (read start :: tail.1, tail.2 + next.2 + Nat.size start + Nat.size (read start) + 3) + +def bitMulAllocation : List Bool → List Bool → ℕ + | [], _ => 0 + | bit :: bits, right => + bitMulAllocation bits right + 1 + + if bit then OAI.EditApproximation.bitAddAllocation (false :: (OAI.EditApproximation.bitMulWithWork bits right).1) right false else 0 + +def bitDivModAllocation (divisor : List Bool) : List Bool → ℕ + | [] => 0 + | bit :: bits => + let candidate := bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + bitDivModAllocation divisor bits + 2 + + if (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt then 0 + else OAI.EditApproximation.bitSubtractAllocation candidate divisor false + +def saturatingSubtractAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then 0 else OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def makeStateAllocation (n lo hi : ℕ) : ℕ := + OAI.EditApproximation.naturalWordLEAllocation lo.bits hi.bits + OAI.EditApproximation.naturalWordLEAllocation hi.bits n.bits + + if ((OAI.EditApproximation.wordLEWithWork lo.bits hi.bits).1 && (OAI.EditApproximation.wordLEWithWork hi.bits n.bits).1) = true then 2 else 0 + +def translatedEndpointAllocation (reference root endpoint : ℕ) : ℕ := + OAI.EditApproximation.bitSubtractAllocation endpoint.bits root.bits false + + OAI.EditApproximation.binaryNaturalAddAllocation reference (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root).1) + +def wordInsertAllocation (a : List Bool) : List (List Bool) → ℕ + | [] => 1 + | b :: rest => OAI.EditApproximation.wordLEAllocation a b + + if (OAI.EditApproximation.wordLEWithWork a b).1 then 2 else wordInsertAllocation a rest + 1 + +def wordSortWithWork : List (List Bool) → List (List Bool) × ℕ + | [] => ([], 1) + | a :: rest => + let tail := wordSortWithWork rest + let inserted := OAI.EditApproximation.wordInsertWithWork a tail.1 + (inserted.1, tail.2 + inserted.2 + 2) + +def binaryGridRoundWithWork (spacing position : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork position spacing + let rounded := OAI.EditApproximation.bitMulWithWork spacing.bits quotient.1 + (rounded.1, quotient.2.2 + rounded.2 + 2) + +def gridPointsWithWork (g lo hi : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits + let upper := OAI.EditApproximation.binaryNaturalDivModWithWork hi g + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue lower.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, lower.2 + upper.2.2 + stop.2 + count.2 + points.2 + + Nat.size g + Nat.size lo + Nat.size hi + 5) + +def seedGridSpacingWithWork (b P : ℕ) : List Bool × ℕ := + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork b P + let test := OAI.EditApproximation.wordLEWithWork quotient.1 [true] + (if test.1 then [true] else quotient.1, quotient.2.2 + test.2 + 2) + +def balancedCutWithWork (lo width M i : ℕ) : List Bool × ℕ := + let product := OAI.EditApproximation.binaryNaturalMulWithWork i width + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) M + let result := OAI.EditApproximation.binaryNaturalAddWithWork lo (OAI.EditApproximation.bitWordValue quotient.1) + (result.1, product.2 + quotient.2.2 + result.2 + 2) + +def triangularMassWithWork (K : ℕ) : List Bool × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork K 1 + let product := OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next.1) + let quotient := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product.1) 2 + (quotient.1, next.2 + product.2 + quotient.2.2 + 3) + +def refinementBaseWithWork (ell : List Bool) : List Bool × ℕ := + let power := OAI.EditApproximation.bitPowerWithWork ell 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + let result := OAI.EditApproximation.trimBitWordWithWork increment.1 + (result.1, power.2 + increment.2 + result.2 + 2) + +def queryPairWithWork (a b : ℕ) : ℕ × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork a b + if test.1 = .lt then + let square := OAI.EditApproximation.binaryNaturalMulWithWork b b + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + result.2 + 3) + else + let square := OAI.EditApproximation.binaryNaturalMulWithWork a a + let linear := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue square.1) a + let result := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue linear.1) b + (OAI.EditApproximation.bitWordValue result.1, test.2 + square.2 + linear.2 + result.2 + 4) + +def queryCellValidWithWork (n exponent : ℕ) (cell : ℕ × ℕ) : Bool × ℕ := + let cap := OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + let left := OAI.EditApproximation.wordLEWithWork cell.1.bits cap.1 + let right := OAI.EditApproximation.wordLEWithWork cell.2.bits cap.1 + (left.1 && right.1, cap.2 + left.2 + right.2 + exponent + 4) + +def queryFinOfNatWithWork (bound value : ℕ) (hb : 0 < bound) : Fin bound × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let result := OAI.EditApproximation.binaryNaturalDivModWithWork value bound + (⟨OAI.EditApproximation.bitWordValue result.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 value bound hb).2] + exact Nat.mod_lt value hb⟩, result.2.2 + 1) + +def coarseDenominatorWithWork (allowanceDen q L branching : List Bool) (D : ℕ) : + List Bool × ℕ := + let first := OAI.EditApproximation.bitMulWithWork L branching + let base := OAI.EditApproximation.bitMulWithWork first.1 q + let trimmedBase := OAI.EditApproximation.trimBitWordWithWork base.1 + let power := OAI.EditApproximation.bitPowerWithWork trimmedBase.1 D + let initial := OAI.EditApproximation.bitMulWithWork allowanceDen q + let product := OAI.EditApproximation.bitMulWithWork initial.1 power.1 + let result := OAI.EditApproximation.trimBitWordWithWork product.1 + (result.1, first.2 + base.2 + trimmedBase.2 + power.2 + initial.2 + product.2 + result.2 + 7) + +def coarseFramedReadWithWork {α : Type u_1} (k n : ℕ) (word : List α) (i : ℕ) : + Option (Option α) × ℕ := + let lower := OAI.EditApproximation.binaryNaturalCompareWithWork i k + if lower.1 = .lt then (none, lower.2 + Nat.size k + Nat.size n + Nat.size i + 2) else + let finish := OAI.EditApproximation.binaryNaturalAddWithWork k n + let upper := OAI.EditApproximation.binaryNaturalCompareWithWork i (OAI.EditApproximation.bitWordValue finish.1) + if upper.1 = .lt then + let offset := OAI.EditApproximation.saturatingSubtractWithWork i k + (some word[OAI.EditApproximation.bitWordValue offset.1]?, lower.2 + finish.2 + upper.2 + offset.2 + + Nat.size k + Nat.size n + Nat.size i + 4) + else (none, lower.2 + finish.2 + upper.2 + Nat.size k + Nat.size n + Nat.size i + 3) + +def coarseDescriptorWithWork (B d n start : ℕ) : List Bool × ℕ := + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let remaining := OAI.EditApproximation.saturatingSubtractWithWork n start + let clipped := OAI.EditApproximation.wordMinWithWork capacity.1 remaining.1 + (clipped.1, capacity.2 + remaining.2 + clipped.2 + + Nat.size B + Nat.size d + Nat.size n + Nat.size start + 4) + +def coarseChildOffsetWithWork (offset capacity index : ℕ) : List Bool × ℕ := + let displacement := OAI.EditApproximation.binaryNaturalMulWithWork index capacity + let result := OAI.EditApproximation.binaryNaturalAddWithWork offset (OAI.EditApproximation.bitWordValue displacement.1) + (result.1, displacement.2 + result.2 + Nat.size index + Nat.size capacity + Nat.size offset + 3) + +def coarseInputGuardWithWork (sourceLo sourceHi targetLo targetHi : ℕ) : Bool × ℕ := + let sourceWidth := OAI.EditApproximation.saturatingSubtractWithWork sourceHi sourceLo + let targetWidth := OAI.EditApproximation.saturatingSubtractWithWork targetHi targetLo + let twice := OAI.EditApproximation.binaryNaturalMulWithWork 2 (OAI.EditApproximation.bitWordValue sourceWidth.1) + let compared := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.bitWordValue twice.1) (OAI.EditApproximation.bitWordValue targetWidth.1) + (decide (compared.1 = .lt), sourceWidth.2 + targetWidth.2 + twice.2 + compared.2 + 6) + +def bitPowerAllocation (base : List Bool) : ℕ → ℕ + | 0 => 1 + | n + 1 => + let previous := (OAI.EditApproximation.bitPowerWithWork base n).1 + bitPowerAllocation base n + OAI.EditApproximation.bitMulAllocation previous base + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.bitMulWithWork previous base).1 + +def bitCeilDivAllocation (divisor bits : List Bool) : ℕ := + let divided := OAI.EditApproximation.bitDivModWithWork divisor bits + OAI.EditApproximation.bitDivModAllocation divisor bits + + if (OAI.EditApproximation.bitCompareWithWork divided.2.1 []).1 = .eq then 0 + else 1 + OAI.EditApproximation.bitAddAllocation divided.1 [true] false + +def binaryNaturalMulAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def binaryNaturalDivAllocation (a b : ℕ) : ℕ := OAI.EditApproximation.bitDivModAllocation b.bits a.bits + +def triangularMassAllocation (K : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork K 1).1 + let product := (OAI.EditApproximation.binaryNaturalMulWithWork K (OAI.EditApproximation.bitWordValue next)).1 + OAI.EditApproximation.bitAddAllocation K.bits (1 : ℕ).bits false + + OAI.EditApproximation.bitMulAllocation K.bits (OAI.EditApproximation.bitWordValue next).bits + + OAI.EditApproximation.bitDivModAllocation (2 : ℕ).bits (OAI.EditApproximation.bitWordValue product).bits + +def binaryIntervalRoundWithWork (spacing lo hi : ℕ) : (List Bool × List Bool) × ℕ := + let left := OAI.EditApproximation.binaryGridRoundWithWork spacing lo + let right := OAI.EditApproximation.binaryGridRoundWithWork spacing hi + ((left.1, right.1), left.2 + right.2 + 1) + +def computedQueryBase (N : ℕ) : List Bool := + (OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits).1 + +def coarsePreparedSlicesWithWork (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : Option (List ℕ × List ℕ) × ℕ := + let guard := OAI.EditApproximation.coarseInputGuardWithWork sourceLo sourceHi targetLo targetHi + if guard.1 then (none, guard.2) else + let copiedSource := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => source[i]?.getD 0) sourceLo (sourceHi - sourceLo) + let copiedTarget := OAI.EditApproximation.coarseRangeCopyWithWork (fun i => target[i]?.getD 0) targetLo (targetHi - targetLo) + (some (copiedSource.1, copiedTarget.1), guard.2 + copiedSource.2 + copiedTarget.2) + +def gridPointsAllocation (g lo hi : ℕ) : ℕ := + let lower := (OAI.EditApproximation.bitCeilDivWithWork g.bits lo.bits).1 + let upper := (OAI.EditApproximation.binaryNaturalDivModWithWork hi g).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue upper) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.bitCeilDivAllocation g.bits lo.bits + OAI.EditApproximation.binaryNaturalDivAllocation hi g + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue upper) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue lower) + + indices.length + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i) indices + +def balancedCutAllocation (lo width M i : ℕ) : ℕ := + let product := (OAI.EditApproximation.binaryNaturalMulWithWork i width).1 + let quotient := (OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue product) M).1 + OAI.EditApproximation.binaryNaturalMulAllocation i width + OAI.EditApproximation.binaryNaturalDivAllocation (OAI.EditApproximation.bitWordValue product) M + + OAI.EditApproximation.binaryNaturalAddAllocation lo (OAI.EditApproximation.bitWordValue quotient) + +def seedGridSpacingAllocation (b P : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation b P + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 [true] + 1 + +def queryCellValidAllocation (n exponent : ℕ) (cell : ℕ × ℕ) : ℕ := + let cap := (OAI.EditApproximation.binaryNaturalMulWithWork n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent))).1 + OAI.EditApproximation.binaryNaturalMulAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord exponent)) + + OAI.EditApproximation.naturalWordLEAllocation cell.1.bits cap + OAI.EditApproximation.naturalWordLEAllocation cell.2.bits cap + exponent + 1 + +def queryPairAllocation (a b : ℕ) : ℕ := + a.bits.length + b.bits.length + + if (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt then + OAI.EditApproximation.binaryNaturalMulAllocation b b + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork b b).1) a + else + OAI.EditApproximation.binaryNaturalMulAllocation a a + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a + + OAI.EditApproximation.binaryNaturalAddAllocation + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a a).1) a).1) b + +def binaryGridRoundAllocation (spacing position : ℕ) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation position spacing + + OAI.EditApproximation.bitMulAllocation spacing.bits (OAI.EditApproximation.binaryNaturalDivModWithWork position spacing).1 + +def wordSortAllocation : List (List Bool) → ℕ + | [] => 0 + | a :: rest => wordSortAllocation rest + + OAI.EditApproximation.wordInsertAllocation a (OAI.EditApproximation.wordSortWithWork rest).1 + 0 + +def reduceOnlineIntegerAllocation (K integer : ℕ) : ℕ := + OAI.EditApproximation.triangularMassAllocation K + + OAI.EditApproximation.bitDivModAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1).bits integer.bits + Nat.size integer + +def coarsePreparedInputStorage (source target : List ℕ) + (sourceLo sourceHi targetLo targetHi : ℕ) : ℕ := + match (OAI.EditApproximation.coarsePreparedSlicesWithWork source target sourceLo sourceHi targetLo targetHi).1 with + | none => 1 + | some (x, y) => 1 + OAI.EditApproximation.storedNaturalBits x + OAI.EditApproximation.storedNaturalBits y + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def optimizerTriangularMass (K : ℕ) : ℕ := ∑ j ∈ range K, (j + 1) + +def rationalLogApproximation (r : ℚ) (K : ℕ) : ℚ := + 2 * ∑ k ∈ range K, (((r - 1) / (r + 1)) ^ (2 * k + 1) / (2 * k + 1)) + +def rationalLinearizationMaximizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (gradient : ι → ℚ) : ι → ℚ := + (vertices.argmax fun p => ∑ i ∈ coordinates, gradient i * p i).getD (fun _ => 0) + +def bandCoordinates {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : Finset (β → σ)) : Finset (β × σ) := + band.biUnion fun action => univ.image fun child => (child, action child) + +def actionVector {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq σ] + (mass : β → ℚ) (action : β → σ) (coordinate : β × σ) : ℚ := + if coordinate.2 = action coordinate.1 then mass coordinate.1 / (∑ child, mass child) else 0 + +def rationalOptimisticHistory {ι : Type u_1} (κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + ∑ j ∈ range t, (gain j i + (1 - 2 * κ) * decrement j i) + +def rejectionBitCount (N : ℕ) : ℕ := Nat.clog 2 N + +def vectorMapWithWork {α : Type u_1} (d : ℕ) (f : Fin d → α × ℕ) : Vector α d × ℕ := + let cells := Vector.ofFn f + (cells.map Prod.fst, (cells.map Prod.snd).toList.sum + 6 * d) + +def TreeLayer (M : ℕ) : ℕ → Type + | 0 => PUnit + | d + 1 => TreeLayer M d × Fin M + +def intervalTreeDepth (M nx : ℕ) : ℕ := Nat.clog M (max 1 nx) + +def rationalMaximum (fallback : ℚ) : List ℚ → ℚ + | [] => fallback + | value :: rest => max value (rationalMaximum fallback rest) + +def rationalDyadicCeiling (value : ℚ) : ℚ := (2 : ℚ) ^ Int.clog 2 value + +def listedBandCoordinates {M : ℕ} {σ : Type u_1} [DecidableEq σ] + (band : List (Fin M → σ)) : List (Fin M × σ) := + (band.flatMap fun action => List.ofFn fun child => (child, action child)).dedup + +def childGain {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := -table t i / mass i.1 + +def childDecrement {β : Type u_1} {σ : Type u_2} (mass : β → ℚ) (table : ℕ → β × σ → ℚ) + (t : ℕ) (i : β × σ) : ℚ := (table t i - table (t + 1) i) / mass i.1 + +def naturalEqualWithWork (a b : ℕ) : Bool × ℕ := + let result := OAI.EditApproximation.binaryNaturalCompareWithWork a b + (decide (result.1 = .eq), result.2 + 1) + +def translatedEndpointWithWork (reference root endpoint : ℕ) : ℕ × ℕ := + let difference := OAI.EditApproximation.binaryNaturalSubtractWithWork endpoint root + let result := OAI.EditApproximation.binaryNaturalAddWithWork reference (OAI.EditApproximation.bitWordValue difference.1) + (OAI.EditApproximation.bitWordValue result.1, difference.2 + result.2 + 2) + +def rationalOnlineMinimum : List ℚ → Option ℚ + | [] => none + | first :: rest => some (OAI.EditApproximation.rationalMinimum first rest) + +def dyadicQueryWindow (N : ℕ) (w a F : ℚ) : List ℕ := + (OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide (w / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * w) + +def actionCurrentInputCover {Parent : Type u_1} {Child : Type u_2} [DecidableEq Child] {M : ℕ} + (actions : List (OAI.EditApproximation.RationalBellmanAction Parent Child M)) : Finset Child := + (List.finRange actions.length).toFinset.biUnion fun index => + Finset.univ.image (actions.get index).childState + +def boundedOnlineInteger (n : ℕ) (hn : 0 < n) (integer : ℕ) : Fin n := + ⟨integer % n, Nat.mod_lt _ hn⟩ + +def orderedInputs {ι : Type u_1} [DecidableEq ι] (encode : ι → ℕ) + (hinjective : Function.Injective encode) (inputs : Finset ι) : List ι := + let _ : LinearOrder ι := LinearOrder.lift' encode hinjective + inputs.sort (· ≤ ·) + +def CoarseThresholdDraws (B : ℕ) : ℕ → Type + | 0 => PUnit + | D + 1 => (Fin B → Fin B) × (Fin B → CoarseThresholdDraws B D) + +def coarseThresholdContribution (threshold scale value : ℚ) : ℚ := + if threshold ≤ value then max value scale else 0 + +def coarseChildThreshold (B : ℕ) (Q allowance : ℚ) (draw : Fin B) : ℚ := + allowance * (draw.val + 1 : ℕ) / ((B : ℚ) * Q) + +def coarseCommonDenominator (allowanceDen q L B D : ℕ) : ℕ := + allowanceDen * q * (L * B * q) ^ D + +def rationalSmoothedGradient {ι : Type u_1} (G : ℕ) (linear p : ι → ℚ) (i : ι) : ℚ := + -OAI.EditApproximation.rationalLogApproximation (p i + 1 / (G : ℚ) ^ 50) (G ^ 60) - 1 + linear i + +def rationalOnlineLinear {ι : Type u_1} (η κ : ℚ) + (gain decrement : ℕ → ι → ℚ) (t : ℕ) (i : ι) : ℚ := + η * (OAI.EditApproximation.rationalOptimisticHistory κ gain decrement t i + gain t i) + +def triangularChoice : (K : ℕ) → Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K + | 0, integer => Fin.elim0 integer + | K + 1, integer => + if h : integer.val < OAI.EditApproximation.optimizerTriangularMass K then + (triangularChoice K ⟨integer.val, h⟩).castSucc + else ⟨K, by omega⟩ + +instance treeLayerFintype (M : ℕ) : (d : ℕ) → Fintype (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (Fintype PUnit) + | d + 1 => + letI := treeLayerFintype M d + inferInstanceAs (Fintype (OAI.EditApproximation.TreeLayer M d × Fin M)) + +abbrev PhysicalNode (M J : ℕ) := Σ d : Fin (J + 1), OAI.EditApproximation.TreeLayer M d.val + +def finiteRationalOptimizer {ι : Type u_1} (coordinates : Finset ι) + (vertices : List (ι → ℚ)) (linear : ι → ℚ) (G : ℕ) : ℕ → ι → ℚ + | 0 => vertices.headD (fun _ => 0) + | j + 1 => + let p := finiteRationalOptimizer coordinates vertices linear G j + let selected := OAI.EditApproximation.rationalLinearizationMaximizer coordinates vertices + (OAI.EditApproximation.rationalSmoothedGradient G linear p) + fun i => (1 - 2 / ((j : ℚ) + 2)) * p i + (2 / ((j : ℚ) + 2)) * selected i + +instance physicalNodeFintype (M J : ℕ) : Fintype (OAI.EditApproximation.PhysicalNode M J) := inferInstance + +abbrev PhysicalInternalNode (M J : ℕ) := {node : OAI.EditApproximation.PhysicalNode M J // node.1.val < J} + +def finiteOptimizerAction {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G j : ℕ) : β → σ := + let coordinates := OAI.EditApproximation.bandCoordinates band.toFinset + let vertices := band.map (OAI.EditApproximation.actionVector mass) + let gradient := OAI.EditApproximation.rationalSmoothedGradient G linear (OAI.EditApproximation.finiteRationalOptimizer coordinates vertices linear G j) + (band.argmax fun action => ∑ coordinate ∈ coordinates, + gradient coordinate * OAI.EditApproximation.actionVector mass action coordinate).getD (band.head hband) + +def finiteOptimizerActionDraw {β : Type u_1} {σ : Type u_2} [Fintype β] [DecidableEq β] [DecidableEq σ] + (band : List (β → σ)) (hband : band ≠ []) (mass : β → ℚ) + (linear : β × σ → ℚ) (G K : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : β → σ := + OAI.EditApproximation.finiteOptimizerAction band hband mass linear G (OAI.EditApproximation.triangularChoice K integer).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def width (a : OAI.EditApproximation.BinaryFraction) : ℕ := max a.numerator.bits.length a.denominator.length + +def denominatorInteger (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.SignedBinary := ⟨false, a.denominator⟩ + +def zero : OAI.EditApproximation.BinaryFraction := ⟨⟨false, []⟩, [true], by decide⟩ + +def canonicalizeWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + exact + let numerator := OAI.EditApproximation.trimBitWordWithWork a.numerator.bits + let denominator := OAI.EditApproximation.trimBitWordWithWork a.denominator + (⟨⟨a.numerator.negative, numerator.1⟩, denominator.1, by + rw [proof_trimBitWordWithWork_value_6] + exact a.denominator_pos⟩, numerator.2 + denominator.2 + 2) + +def inversePowerTwo (n : ℕ) : OAI.EditApproximation.BinaryFraction := by + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + exact + ⟨⟨false, [true]⟩, OAI.EditApproximation.powerTwoWord n, by rw [proof_powerTwoWord_value_13]; positivity⟩ + +def doubleFraction (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨a.numerator.negative, false :: a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def absolute (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, a.numerator.bits⟩, a.denominator, a.denominator_pos⟩ + +def naturalCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) + else + let result := OAI.EditApproximation.bitCeilDivWithWork a.denominator a.numerator.bits + (result.1, result.2 + 1) + +def ofNaturalWord (bits : List Bool) : OAI.EditApproximation.BinaryFraction := + ⟨⟨false, bits⟩, [true], by decide⟩ + +def naturalFloorWithWork (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + if a.numerator.negative then ([], 1) else + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator a.numerator.bits + (quotient.1, quotient.2.2 + 1) + +def queryDataReadBudget (M n : ℕ) {κ : Type u_1} (keys : List κ) : ℕ := + 1 + keys.length * (24 * max (Nat.size M) (Nat.size n) + 9) + +def onlineParametersWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : + (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.BinaryFraction) × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let etaPower := OAI.EditApproximation.bitPowerWithWork ell 5 + let kappaPower := OAI.EditApproximation.bitPowerWithWork ell 4 + let eta : OAI.EditApproximation.BinaryFraction := ⟨⟨false, etaPower.1⟩, [true], by decide⟩ + let kappa : OAI.EditApproximation.BinaryFraction := ⟨⟨false, [true]⟩, kappaPower.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩ + ((eta, kappa), etaPower.2 + kappaPower.2 + 2) + +def refinementDecrementWithWork (ell : List Bool) (hell : 0 < OAI.EditApproximation.bitWordValue ell) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork ell 10 + (⟨⟨false, [true]⟩, denominator.1, by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hell⟩, denominator.2 + 1) + +abbrev CoarseBinaryArray := Option (List OAI.EditApproximation.BinaryFraction) + +def coarseRootDenominator (B q L d : ℕ) : List Bool × ℕ := + OAI.EditApproximation.coarseDenominatorWithWork (1 : ℕ).bits q.bits L.bits B.bits d + +def naturalListEqualWithWork : List ℕ → List ℕ → Bool × ℕ + | [], [] => (true, 1) + | a :: left, b :: right => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then + let tail := naturalListEqualWithWork left right + (tail.1, test.2 + tail.2 + 2) + else (false, test.2 + 2) + | _, _ => (false, 1) + +def canonicalizeAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.trimBitWordAllocation a.numerator.bits + OAI.EditApproximation.trimBitWordAllocation a.denominator + +def invAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if (OAI.EditApproximation.bitCompareWithWork a.numerator.bits []).1 = .eq then 1 else 0 + +def naturalCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitCeilDivAllocation a.denominator a.numerator.bits + +def gatheredLookupAllocation {κ : Type u_1} (equal : κ → κ → Bool × ℕ) + (allocation : κ → κ → ℕ) : List κ → List OAI.EditApproximation.BinaryFraction → κ → ℕ + | key :: keys, _value :: values, query => + allocation query key + if (equal query key).1 then 0 + else gatheredLookupAllocation equal allocation keys values query + | _, _, _ => 0 + +def naturalFloorAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + if a.numerator.negative then 0 else OAI.EditApproximation.bitDivModAllocation a.denominator a.numerator.bits + +def signedPowerTwoAllocation (e : ℤ) : ℕ := + if 0 ≤ e then e.toNat + 2 else (-e).toNat + 2 + +def invWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + exact + let comparison := OAI.EditApproximation.bitCompareWithWork a.numerator.bits [] + if h : comparison.1 = .eq then (OAI.EditApproximation.BinaryFraction.zero, comparison.2 + 2) else + (⟨⟨a.numerator.negative, a.denominator⟩, a.numerator.bits, by + have hnonzero : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hzero + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 hzero) + omega⟩, comparison.2 + 2) + +def signedPowerTwoWithWork (e : ℤ) : OAI.EditApproximation.BinaryFraction × ℕ := + if 0 ≤ e then + (⟨⟨false, OAI.EditApproximation.powerTwoWord e.toNat⟩, [true], by decide⟩, e.toNat + 3) + else (OAI.EditApproximation.BinaryFraction.inversePowerTwo (-e).toNat, (-e).toNat + 3) + +def fixedDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + quotient.2.2 + answer.2 + 4) + +def finalAnswerWithWork (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a + let clamped := OAI.EditApproximation.wordMinWithWork N.bits floor.1 + (clamped.1, floor.2 + clamped.2 + Nat.size N + 2) + +def coarseGridNatWithWork (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.bitMulWithWork n.bits denominator + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨false, product.1⟩, denominator, hden⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, product.2 + answer.2 + 3) + +def coarseBinaryMapWithWork (f : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ) : + OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.arithmeticMapWithWork f values + (some result.1, result.2) + +def fixedDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (denominator : List Bool) + (hden : 0 < OAI.EditApproximation.bitWordValue denominator) : ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.numerator.bits denominator + let quotient := OAI.EditApproximation.bitDivModWithWork a.denominator product.1 + let raw : OAI.EditApproximation.BinaryFraction := ⟨⟨a.numerator.negative, quotient.1⟩, denominator, hden⟩ + OAI.EditApproximation.bitMulAllocation a.numerator.bits denominator + OAI.EditApproximation.bitDivModAllocation a.denominator product.1 + + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation raw + +def finalAnswerAllocation (N : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation a + OAI.EditApproximation.naturalWordLEAllocation N.bits (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork a).1 + Nat.size N + 1 + +def powerDenominatorWithWork (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + let denominator := OAI.EditApproximation.bitPowerWithWork base n + let answer := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork a denominator.1 (by + rw [proof_bitPowerWithWork_value_76] + exact Nat.pow_pos hbase) + (answer.1, denominator.2 + answer.2 + 1) + +def powerDenominatorAllocation (a : OAI.EditApproximation.BinaryFraction) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (n : ℕ) : ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + exact + OAI.EditApproximation.bitPowerAllocation base n + OAI.EditApproximation.BinaryFraction.fixedDenominatorAllocation a (OAI.EditApproximation.bitPowerWithWork base n).1 + (by rw [proof_bitPowerWithWork_value_76]; exact Nat.pow_pos hbase) + +def finishCachedWithWork (raw : OAI.EditApproximation.BinaryFraction × ℕ) (base : List Bool) + (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.powerDenominatorWithWork raw.1 base hbase remaining + (result.1, raw.2 + result.2 + 1) + +def finishCachedAllocation (raw : OAI.EditApproximation.BinaryFraction × ℕ) (allocation : ℕ) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : ℕ := + allocation + OAI.EditApproximation.BinaryFraction.powerDenominatorAllocation raw.1 base hbase remaining + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalChild {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) + (i : Fin M) : OAI.EditApproximation.PhysicalNode M J := + ⟨⟨node.1.val + 1, by omega⟩, (node.2, i)⟩ + +instance treeLayerDecidableEq (M : ℕ) : (d : ℕ) → DecidableEq (OAI.EditApproximation.TreeLayer M d) + | 0 => inferInstanceAs (DecidableEq PUnit) + | d + 1 => + letI := treeLayerDecidableEq M d + inferInstanceAs (DecidableEq (OAI.EditApproximation.TreeLayer M d × Fin M)) + +def treeLayerCode (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ + | 0, _ => 0 + | d + 1, path => path.2.val + M * treeLayerCode M d path.1 + +def localOnlineMassBound (M P H : ℕ) : ℕ := + OAI.EditApproximation.optimizerTriangularMass ((H + M * (40 * P + 2) ^ 2 + 2) ^ 80) + +def treeLayerCodeWithWork (M : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → ℕ × ℕ + | 0, _ => (0, 1) + | d + 1, path => let previous := treeLayerCodeWithWork M d path.1 + (path.2.val + M * previous.1, previous.2 + 3) + +def queryNaturalIndexWithWork (a : ℕ) : List ℕ → ℕ × ℕ + | [] => (0, 1) + | b :: rest => + let test := OAI.EditApproximation.naturalEqualWithWork a b + if test.1 then (0, test.2 + 1) + else + let tail := queryNaturalIndexWithWork a rest + (tail.1 + 1, test.2 + tail.2 + 2) + +def scheduledSeedWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + +def coarseLetterMatchWithWork : Option (Option ℕ) → Option ℕ → Bool × ℕ + | none, _ => (false, 1) + | some none, none => (true, 1) + | some (some a), some b => OAI.EditApproximation.naturalEqualWithWork a b + | _, _ => (false, 1) + +def queryNaturalIndexAllocation (a : ℕ) : List ℕ → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.naturalEqualAllocation a b + + if (OAI.EditApproximation.naturalEqualWithWork a b).1 then 1 else queryNaturalIndexAllocation a rest + 1 + +def physicalNodeCode {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ := + OAI.EditApproximation.treeLayerCode M node.1.val node.2 + M ^ J * node.1.val + +def queryScaleDispatchWithWork (N b : ℕ) : ℕ × ℕ := + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let index := OAI.EditApproximation.queryNaturalIndexWithWork b scales.1 + (index.1, scales.2 + index.2 + scales.1.length + 2) + +def queryScaleDispatchAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.dyadicScalesAllocation N + OAI.EditApproximation.queryNaturalIndexAllocation b (OAI.EditApproximation.dyadicScalesWithWork N).1 + + (OAI.EditApproximation.dyadicScalesWithWork N).1.length + +def queryScalePresentWithWork (N b : ℕ) : Bool × ℕ := + let found := OAI.EditApproximation.queryScaleDispatchWithWork N b + let test := OAI.EditApproximation.binaryNaturalCompareWithWork found.1 (max 1 N.bits.length) + (decide (test.1 = .lt), found.2 + test.2 + 2) + +def queryScalePresentAllocation (N b : ℕ) : ℕ := + OAI.EditApproximation.queryScaleDispatchAllocation N b + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1.bits.length + (max 1 N.bits.length).bits.length + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +def physicalScaleIndex (N b : ℕ) (hb : b ∈ OAI.EditApproximation.dyadicScales N) : + Fin (OAI.EditApproximation.dyadicScales N).length := + ⟨(OAI.EditApproximation.dyadicScales N).idxOf b, List.idxOf_lt_length_of_mem hb⟩ + +abbrev PositiveDrawRange (B : ℕ) := {n : Fin (B + 1) // 0 < n.val} + +abbrev PhysicalLocalGroupKey (M J N n exponent : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × + Fin (n * 2 ^ exponent + 1) × Fin (n * 2 ^ exponent + 1) + +noncomputable def rejectionSuccessParameter (N R : ℕ) (hN : 0 < N) (hNR : N ≤ R) : unitInterval := + ⟨(N : ℝ) / R, div_nonneg (Nat.cast_nonneg _) (Nat.cast_nonneg _), + (div_le_one₀ (by exact_mod_cast hN.trans_le hNR : (0 : ℝ) < R)).mpr (by exact_mod_cast hNR)⟩ + +def scheduledSeedFactor (N pass : ℕ) : ℚ := + (2 : ℚ) ^ OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass + +def scheduledSeedMultiplier (N pass : ℕ) : ℕ := + 2 ^ (OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N) + +instance computedBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0)⟩ + +instance computedCoarseBranching_neZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).B := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +instance computedSourceTime_neZero (N : ℕ) : NeZero (OAI.EditApproximation.inputHeight N ^ 2) := + ⟨pow_ne_zero _ (pow_ne_zero _ (by decide : (2 : ℕ) ≠ 0))⟩ + +abbrev CommonRangeKey (ι : Type u_1) (B : ℕ) := ι × OAI.EditApproximation.PositiveDrawRange B + +def positiveDrawRangeOfLE (B n : ℕ) (hn : 0 < n) (hB : n ≤ B) : OAI.EditApproximation.PositiveDrawRange B := + ⟨⟨n, Nat.lt_succ_of_le hB⟩, hn⟩ + +instance positiveDrawRange_nezero {B : ℕ} (n : OAI.EditApproximation.PositiveDrawRange B) : NeZero n.val.val := + ⟨Nat.ne_of_gt n.property⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SignedBinary + + +def value (a : OAI.EditApproximation.SignedBinary) : ℤ := OAI.EditApproximation.signedMagnitude a.negative (OAI.EditApproximation.bitWordValue a.bits) + +def ofInt (a : ℤ) : OAI.EditApproximation.SignedBinary := ⟨decide (a < 0), a.natAbs.bits⟩ + +def neg (a : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary := ⟨!a.negative, a.bits⟩ + +def addWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + if a.negative = b.negative then + let total := OAI.EditApproximation.bitAddWithWork a.bits b.bits false + (⟨a.negative, total.1⟩, total.2 + 4) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + match comparison.1 with + | .eq => (⟨false, []⟩, comparison.2 + 4) + | .lt => + let difference := OAI.EditApproximation.bitSubtractWithWork b.bits a.bits false + (⟨b.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + | .gt => + let difference := OAI.EditApproximation.bitSubtractWithWork a.bits b.bits false + (⟨a.negative, difference.1⟩, comparison.2 + difference.2.2 + 4) + +def mulWithWork (a b : OAI.EditApproximation.SignedBinary) : OAI.EditApproximation.SignedBinary × ℕ := + let product := OAI.EditApproximation.bitMulWithWork a.bits b.bits + (⟨xor a.negative b.negative, product.1⟩, product.2 + 4) + +def nonzeroWithWork (bits : List Bool) : Bool × ℕ := + let comparison := OAI.EditApproximation.bitCompareWithWork bits [] + (if comparison.1 = .eq then false else true, comparison.2 + 1) + +def addAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := + if a.negative = b.negative then OAI.EditApproximation.bitAddAllocation a.bits b.bits false + else match (OAI.EditApproximation.bitCompareWithWork a.bits b.bits).1 with + | .eq => 0 + | .lt => OAI.EditApproximation.bitSubtractAllocation b.bits a.bits false + | .gt => OAI.EditApproximation.bitSubtractAllocation a.bits b.bits false + +def mulAllocation (a b : OAI.EditApproximation.SignedBinary) : ℕ := OAI.EditApproximation.bitMulAllocation a.bits b.bits + +def ltWithWork (a b : OAI.EditApproximation.SignedBinary) : Bool × ℕ := + if a.negative then + if b.negative then + let comparison := OAI.EditApproximation.bitCompareWithWork b.bits a.bits + (comparison.1 == .lt, comparison.2 + 2) + else + let left := OAI.EditApproximation.SignedBinary.nonzeroWithWork a.bits + let right := OAI.EditApproximation.SignedBinary.nonzeroWithWork b.bits + (left.1 || right.1, left.2 + right.2 + 4) + else + if b.negative then (false, 2) + else + let comparison := OAI.EditApproximation.bitCompareWithWork a.bits b.bits + (comparison.1 == .lt, comparison.2 + 2) + + +end OAI.EditApproximation.SignedBinary +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def value (a : OAI.EditApproximation.BinaryFraction) : ℚ := (a.numerator.value : ℚ) / OAI.EditApproximation.bitWordValue a.denominator + +def representation (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.UnreducedRational := + ⟨a.numerator.value, OAI.EditApproximation.bitWordValue a.denominator, a.denominator_pos⟩ + +def addWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let first := a.numerator.mulWithWork b.denominatorInteger + let second := b.numerator.mulWithWork a.denominatorInteger + let numerator := first.1.addWithWork second.1 + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + first.2 + second.2 + numerator.2 + denominator.2 + 8) + +def mulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + exact + let numerator := a.numerator.mulWithWork b.numerator + let denominator := OAI.EditApproximation.bitMulWithWork a.denominator b.denominator + (⟨numerator.1, denominator.1, by + change 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork a.denominator b.denominator).1 + rw [proof_bitMulWithWork_value_0] + exact Nat.mul_pos a.denominator_pos b.denominator_pos⟩, + numerator.2 + denominator.2 + 4) + +def neg (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction := + ⟨a.numerator.neg, a.denominator, a.denominator_pos⟩ + +def ltWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.numerator.mulWithWork b.denominatorInteger + let right := b.numerator.mulWithWork a.denominatorInteger + let compared := left.1.ltWithWork right.1 + (compared.1, left.2 + right.2 + compared.2 + 4) + +def nat (n : ℕ) : OAI.EditApproximation.BinaryFraction := + ⟨OAI.EditApproximation.SignedBinary.ofInt n, [true], by decide⟩ + +def coarseGridAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := a.numerator.addWithWork b.numerator + let raw : OAI.EditApproximation.BinaryFraction := ⟨total.1, a.denominator, a.denominator_pos⟩ + let answer := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw + (answer.1, total.2 + answer.2 + 3) + +def coarseReadShiftWithWork (k n : ℕ) (target : List ℕ) (letter : Option (Option ℕ)) + (start : ℕ) (shift : Fin (2 * k + 1)) : ℕ × ℕ := + match letter with + | none => (0, 1) + | some letter => + let position := OAI.EditApproximation.binaryNaturalAddWithWork start shift.val + let actual := OAI.EditApproximation.coarseFramedReadWithWork k n target (OAI.EditApproximation.bitWordValue position.1) + let matched := OAI.EditApproximation.coarseLetterMatchWithWork actual.1 letter + (if matched.1 then 0 else 1, position.2 + actual.2 + matched.2 + 3) + +def addAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + + ((a.numerator.mulWithWork b.denominatorInteger).1.addAllocation + (b.numerator.mulWithWork a.denominatorInteger).1) + + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def mulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.numerator + OAI.EditApproximation.bitMulAllocation a.denominator b.denominator + +def ltAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.numerator.mulAllocation b.denominatorInteger + + b.numerator.mulAllocation a.denominatorInteger + +def canonicalAddWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.addWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def canonicalMulWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let raw := a.mulWithWork b + let result := OAI.EditApproximation.BinaryFraction.canonicalizeWithWork raw.1 + (result.1, raw.2 + result.2) + +def one : OAI.EditApproximation.BinaryFraction := OAI.EditApproximation.BinaryFraction.nat 1 + +def dyadicScanWithWork (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (candidate, 1) + | n + 1 => + let comparison := candidate.ltWithWork a + if comparison.1 then + let next := dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + (next.1, comparison.2 + next.2 + 2) + else (candidate, comparison.2 + 1) + +def maxWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then b else a, comparison.2 + 1) + +def leWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let result := b.ltWithWork a + (!result.1, result.2 + 1) + +def minWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let comparison := a.ltWithWork b + (if comparison.1 then a else b, comparison.2 + 1) + +def queryScaleAt (words : List OAI.EditApproximation.BinaryFraction) (scales : List ℚ) + (h : words.map OAI.EditApproximation.BinaryFraction.value = scales) (i : Fin scales.length) : OAI.EditApproximation.BinaryFraction := + words[i.val]'(by have hl := congrArg List.length h; simp only [List.length_map] at hl; omega) + +def gatheredWordLookupWithWork {κ : Type u_1} (equal : κ → κ → Bool × ℕ) : + List κ → List OAI.EditApproximation.BinaryFraction → κ → OAI.EditApproximation.BinaryFraction × ℕ + | key :: keys, value :: values, query => + let test := equal query key + if test.1 then (value, test.2 + 1) + else + let rest := gatheredWordLookupWithWork equal keys values query + (rest.1, test.2 + rest.2 + 1) + | _, _, _ => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + +def coarseGridZipAddWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork a b + let tail := coarseGridZipAddWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryRead (array : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray) (i : ℕ) : OAI.EditApproximation.BinaryFraction := + match array with + | none => OAI.EditApproximation.BinaryFraction.nat 0 + | some cells => cells[i]?.getD (OAI.EditApproximation.BinaryFraction.nat 0) + +def canonicalAddAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.addAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.addWithWork b).1 + +def canonicalMulAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + a.mulAllocation b + OAI.EditApproximation.BinaryFraction.canonicalizeAllocation (a.mulWithWork b).1 + +def minAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def maxAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation a b + +def leAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.ltAllocation b a + +def dyadicScanAllocation (a candidate : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + OAI.EditApproximation.BinaryFraction.ltAllocation candidate a + if (candidate.ltWithWork a).1 then + dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.doubleFraction candidate) n + 1 else 0 + +def equalAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.ltAllocation b a + OAI.EditApproximation.BinaryFraction.ltAllocation a b + 0 + +def subWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork a b.neg + (result.1, result.2 + 1) + +def divWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let inverse := b.invWithWork + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a inverse.1 + (result.1, inverse.2 + result.2 + 1) + +def powWithWork (a : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.one, 1) + | k + 1 => + let previous := powWithWork a k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork previous.1 a + (result.1, previous.2 + result.2 + 1) + +def dotListWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.zero, 1) + | i :: rest => + let tail := dotListWithWork left right rest + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork product.1 tail.1 + (result.1, tail.2 + product.2 + result.2 + 5) + +def dyadicCeilingWithWork (a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.dyadicScanWithWork a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + (result.1, result.2 + 3 * a.width + 5) + +def maximumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := maximumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.maxWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def minimumWithWork (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (fallback, 1) + | head :: rest => + let tail := minimumWithWork fallback rest + let result := OAI.EditApproximation.BinaryFraction.minWithWork head tail.1 + (result.1, tail.2 + result.2 + 1) + +def scaledCeilingWithWork (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork product.1 + (result.1, product.2 + result.2 + Nat.size multiplier + 3) + +def coarseContributionWithWork (threshold scale a : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.BinaryFraction.leWithWork threshold a + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.maxWithWork a scale + (result.1, test.2 + result.2 + 2) + else + let result := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork a.denominator a.denominator_pos 0 + (result.1, test.2 + result.2 + 2) + +def coarseGridScanWithWork (two previous : OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([previous], 0) + | head :: rest => + let added := OAI.EditApproximation.BinaryFraction.coarseGridAddWithWork previous two + let next := OAI.EditApproximation.BinaryFraction.minWithWork head added.1 + let tail := coarseGridScanWithWork two next.1 rest + (previous :: tail.1, added.2 + next.2 + tail.2 + 3) + +def coarseGridZipMinimumWithWork : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | a :: left, b :: right => + let here := OAI.EditApproximation.BinaryFraction.minWithWork a b + let tail := coarseGridZipMinimumWithWork left right + (here.1 :: tail.1, here.2 + tail.2 + 3) + | _, _ => ([], 0) + +def coarseBinaryAddWithWork : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none, right => (right, 0) + | left, none => (left, 0) + | some left, some right => + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipAddWithWork left right + (some result.1, result.2) + +def divAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.invAllocation b + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation a b.invWithWork.1 + +def subAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.canonicalAddAllocation a b.neg + +def optimizerUpdateCellAllocation {d : ℕ} (step complement : OAI.EditApproximation.BinaryFraction) + (previous selected : Vector OAI.EditApproximation.BinaryFraction d) (i : Fin d) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation complement (previous.get i) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation step (selected.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement (previous.get i)).1 + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step (selected.get i)).1 + +def dyadicCeilingAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dyadicScanAllocation a (OAI.EditApproximation.BinaryFraction.inversePowerTwo a.width) (2 * a.width) + a.width + 2 + +def roundedSpacingAllocation (theta envelope : OAI.EditApproximation.BinaryFraction) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta envelope + OAI.EditApproximation.BinaryFraction.maxAllocation OAI.EditApproximation.BinaryFraction.one product + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product).1 + +def scaledCeilingAllocation (multiplier : ℕ) (a : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat multiplier) a + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat multiplier) a).1 + Nat.size multiplier + 1 + +def groupTermsAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.BinaryFraction.equalAllocation (envelope.get i) h + 2) indices + +def logarithmPartialWithWork (b : OAI.EditApproximation.BinaryFraction) : ℕ → OAI.EditApproximation.BinaryFraction × ℕ + | 0 => (OAI.EditApproximation.BinaryFraction.zero, 1) + | k + 1 => + let previous := logarithmPartialWithWork b k + let power := OAI.EditApproximation.BinaryFraction.powWithWork b (2 * k + 1) + let term := OAI.EditApproximation.BinaryFraction.divWithWork power.1 (OAI.EditApproximation.BinaryFraction.nat (2 * k + 1)) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork previous.1 term.1 + (result.1, previous.2 + power.2 + term.2 + result.2 + Nat.size (2 * k + 1) + 5) + +def dotWithWork {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotListWithWork left right (List.finRange d) + +def distanceWithWork (a b : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let difference := a.subWithWork b + (difference.1.absolute, difference.2 + 1) + +def affineErrorWithWork (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : + Bool × ℕ := + let displacement := position.subWithWork offset + let product := velocity.canonicalMulWithWork prediction + let error := displacement.1.subWithWork product.1 + let comparison := error.1.absolute.leWithWork tolerance + (comparison.1, displacement.2 + product.2 + error.2 + comparison.2 + 4) + +def bandToleranceWithWork (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta + let scale := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat b) + let result := OAI.EditApproximation.BinaryFraction.divWithWork scale.1 (OAI.EditApproximation.BinaryFraction.nat M) + (result.1, product.2 + scale.2 + result.2 + Nat.size b + Nat.size M + 3) + +def medianSeedWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let rounded := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values + let sorted := OAI.EditApproximation.wordSortWithWork rounded.1 + let middle := sorted.1.getD (values.length / 2) [] + let clamped := OAI.EditApproximation.wordMinWithWork N.bits middle + (clamped.1, rounded.2 + sorted.2 + values.length + clamped.2 + Nat.size N + 3) + +def groupSampleCountWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let qm := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm.1 h + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 (OAI.EditApproximation.BinaryFraction.nat b) + let ceiling := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.wordMinWithWork M.bits ceiling.1 + (result.1, qm.2 + numerator.2 + ratio.2 + ceiling.2 + result.2 + + Nat.size M + Nat.size Q + Nat.size b + 5) + +def gainReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let word := read s i + let result := OAI.EditApproximation.BinaryFraction.divWithWork word.1.neg (mass i.1) + (result.1, word.2 + result.2 + 1) + +def decrementReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let first := read s i + let second := read (s + 1) i + let difference := OAI.EditApproximation.BinaryFraction.subWithWork first.1 second.1 + let result := OAI.EditApproximation.BinaryFraction.divWithWork difference.1 (mass i.1) + (result.1, first.2 + second.2 + difference.2 + result.2 + 1) + +def scaledSeedWithWork (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio.1 + let result := OAI.EditApproximation.BinaryFraction.maxWithWork (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded.1) gap.absolute + (result.1, ratio.2 + rounded.2 + result.2 + Nat.size U + 3) + +def initialScaleGuardWithWork (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let square := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square.1 + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat U) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, square.2 + denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size U + Nat.size b + 7) + +def initialCenterGuardWithWork (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat U) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat U) upper.1 + (low.1 && high.1, lower.2 + factor.2 + upper.2 + low.2 + high.2 + Nat.size b + Nat.size U + 5) + +def cellCoordinatesWithWork (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : List ℕ × ℕ := + let lower := OAI.EditApproximation.saturatingSubtractWithWork p radius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork p radius + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower.1)) side + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper.1)) side + let first := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ.1 + let stop := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last.1) 1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop.1) (OAI.EditApproximation.bitWordValue first.1) + let values := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + (values, lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + stop.2 + count.2 + + values.length + Nat.size p + Nat.size radius + 9) + +def cellGridPointsWithWork (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : List ℕ × ℕ := + let next := OAI.EditApproximation.binaryNaturalAddWithWork cell 1 + let lower := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next.1)) side + let firstQ := OAI.EditApproximation.BinaryFraction.divWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat g) + let lastQ := OAI.EditApproximation.BinaryFraction.divWithWork upper.1 (OAI.EditApproximation.BinaryFraction.nat g) + let first := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ.1 + let last := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ.1 + let count := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last.1) (OAI.EditApproximation.bitWordValue first.1) + let indices := List.range' (OAI.EditApproximation.bitWordValue first.1) (OAI.EditApproximation.bitWordValue count.1) + let points := OAI.EditApproximation.arithmeticMapWithWork (fun i => + let product := OAI.EditApproximation.binaryNaturalMulWithWork g i + (OAI.EditApproximation.bitWordValue product.1, product.2 + Nat.size i + 2)) indices + (points.1, next.2 + lower.2 + upper.2 + firstQ.2 + lastQ.2 + first.2 + last.2 + count.2 + + points.2 + indices.length + Nat.size cell + Nat.size g + 10) + +def centerEligibilityWithWork (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a + let lower := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 (OAI.EditApproximation.BinaryFraction.nat b) + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 initial + let high := OAI.EditApproximation.BinaryFraction.leWithWork initial upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def refinementScaleGuardWithWork (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let denominator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + let lower := OAI.EditApproximation.BinaryFraction.divWithWork w denominator.1 + let factor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a + let upper := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 w + let low := OAI.EditApproximation.BinaryFraction.leWithWork lower.1 (OAI.EditApproximation.BinaryFraction.nat b) + let high := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat b) upper.1 + (low.1 && high.1, denominator.2 + lower.2 + factor.2 + upper.2 + low.2 + high.2 + + Nat.size b + Nat.size F + 8) + +def coarseDivideWithWork (a divisor : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let quotient := OAI.EditApproximation.BinaryFraction.divWithWork a divisor + let result := OAI.EditApproximation.BinaryFraction.fixedDenominatorWithWork quotient.1 a.denominator a.denominator_pos + (result.1, quotient.2 + result.2 + 2) + +def coarseGridLeftWithWork (two : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [] => ([], 0) + | head :: rest => OAI.EditApproximation.BinaryFraction.coarseGridScanWithWork two head rest + +def coarseMinimumWithWork : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | [] => (OAI.EditApproximation.BinaryFraction.nat 0, 1) + | a :: rest => OAI.EditApproximation.BinaryFraction.minimumWithWork a rest + +def powAllocation (a : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => powAllocation a n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.powWithWork a n).1 a + +def dotListAllocation {d : ℕ} (left right : Vector OAI.EditApproximation.BinaryFraction d) : List (Fin d) → ℕ + | [] => 0 + | i :: rest => dotListAllocation left right rest + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (left.get i) (right.get i) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (left.get i) (right.get i)).1 (OAI.EditApproximation.BinaryFraction.dotListWithWork left right rest).1 + +def minimumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => minimumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.minAllocation head (OAI.EditApproximation.BinaryFraction.minimumWithWork fallback rest).1 + +def maximumAllocation (fallback : OAI.EditApproximation.BinaryFraction) : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | head :: rest => maximumAllocation fallback rest + + OAI.EditApproximation.BinaryFraction.maxAllocation head (OAI.EditApproximation.BinaryFraction.maximumWithWork fallback rest).1 + +def distanceAllocation (a b : OAI.EditApproximation.BinaryFraction) : ℕ := OAI.EditApproximation.BinaryFraction.subAllocation a b + 0 + +def optimizerUpdateAllocation {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + let step := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2))).1 + let complement := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one step + + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.optimizerUpdateCellAllocation step complement previous selected) + + Nat.size (j + 2) + 1 + +def affineErrorAllocation (position offset velocity prediction tolerance : OAI.EditApproximation.BinaryFraction) : ℕ := + let displacement := (OAI.EditApproximation.BinaryFraction.subWithWork position offset).1 + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork velocity prediction).1 + OAI.EditApproximation.BinaryFraction.subAllocation position offset + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation velocity prediction + + OAI.EditApproximation.BinaryFraction.subAllocation displacement product + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.subWithWork displacement product).1.absolute tolerance + +def bandToleranceAllocation (tau theta : OAI.EditApproximation.BinaryFraction) (b M : ℕ) : ℕ := + let product := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork tau theta).1 + let scale := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork product (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation tau theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation product (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.divAllocation scale (OAI.EditApproximation.BinaryFraction.nat M) + Nat.size b + Nat.size M + +def initialScaleGuardAllocation (U b : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let square := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork A A).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) square).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) denominator).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat U)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation A A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) square + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) denominator + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat U) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) upper + Nat.size U + Nat.size b + +def initialCenterGuardAllocation (b U : ℕ) (A : OAI.EditApproximation.BinaryFraction) : ℕ := + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2)).1 + let factor := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) A).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat 2) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) A + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation lower (OAI.EditApproximation.BinaryFraction.nat U) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat U) upper + Nat.size b + Nat.size U + +def scaledSeedAllocation (U : ℕ) (a gap : OAI.EditApproximation.BinaryFraction) : ℕ := + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat U) a).1 + let rounded := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat U) a + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.BinaryFraction.maxAllocation (OAI.EditApproximation.BinaryFraction.ofNaturalWord rounded) gap.absolute + Nat.size U + 2 + +def centerEligibilityAllocation (b F : ℕ) (a initial : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 4) a + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 4) a).1).1 initial + + OAI.EditApproximation.BinaryFraction.leAllocation initial (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) (OAI.EditApproximation.BinaryFraction.nat F)).1 (OAI.EditApproximation.BinaryFraction.nat b)).1 + Nat.size b + Nat.size F + +def refinementScaleGuardAllocation (F b : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.divAllocation w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1 + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 8) a + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.divWithWork w (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 16) (OAI.EditApproximation.BinaryFraction.nat F)).1).1 (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 8) a).1 w).1 + Nat.size b + Nat.size F + +def cellCoordinatesAllocation (side : OAI.EditApproximation.BinaryFraction) (p radius : ℕ) : ℕ := + let lower := (OAI.EditApproximation.saturatingSubtractWithWork p radius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork p radius).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork lastQ).1 + let stop := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue last) 1).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first)).1 + OAI.EditApproximation.saturatingSubtractAllocation p radius + OAI.EditApproximation.binaryNaturalAddAllocation p radius + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue lower)) side + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue upper)) side + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation lastQ + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue last) 1 + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue stop) (OAI.EditApproximation.bitWordValue first) + OAI.EditApproximation.bitWordValue count + + Nat.size p + Nat.size radius + +def cellGridPointsAllocation (side : OAI.EditApproximation.BinaryFraction) (g cell : ℕ) : ℕ := + let next := (OAI.EditApproximation.binaryNaturalAddWithWork cell 1).1 + let lower := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell) side).1 + let upper := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side).1 + let firstQ := (OAI.EditApproximation.BinaryFraction.divWithWork lower (OAI.EditApproximation.BinaryFraction.nat g)).1 + let lastQ := (OAI.EditApproximation.BinaryFraction.divWithWork upper (OAI.EditApproximation.BinaryFraction.nat g)).1 + let first := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork firstQ).1 + let last := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork lastQ).1 + let count := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first)).1 + let indices := List.range' (OAI.EditApproximation.bitWordValue first) (OAI.EditApproximation.bitWordValue count) + OAI.EditApproximation.binaryNaturalAddAllocation cell 1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell) side + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.bitWordValue next)) side + OAI.EditApproximation.BinaryFraction.divAllocation lower (OAI.EditApproximation.BinaryFraction.nat g) + OAI.EditApproximation.BinaryFraction.divAllocation upper (OAI.EditApproximation.BinaryFraction.nat g) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation firstQ + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation lastQ + + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue last) (OAI.EditApproximation.bitWordValue first) + + OAI.EditApproximation.arithmeticMapAllocation (fun i => OAI.EditApproximation.binaryNaturalMulAllocation g i + Nat.size i) indices + + indices.length + Nat.size cell + Nat.size g + +def medianSeedAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + let rounded := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.scaledCeilingWithWork multiplier) values).1 + let sorted := (OAI.EditApproximation.wordSortWithWork rounded).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.scaledCeilingAllocation multiplier) values + OAI.EditApproximation.wordSortAllocation rounded + + OAI.EditApproximation.wordLEAllocation N.bits (sorted.getD (values.length / 2) []) + + Nat.size N + +def groupSampleCountAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let qm := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let numerator := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork qm h).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat Q) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation qm h + + OAI.EditApproximation.BinaryFraction.divAllocation numerator (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation ratio + + OAI.EditApproximation.wordLEAllocation M.bits (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork ratio).1 + + Nat.size M + Nat.size Q + Nat.size b + +def refinementUpdateAllocation (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → ℕ + | none => 0 + | some online => + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta).1 + let lower := (OAI.EditApproximation.BinaryFraction.divWithWork cone denominator).1 + let clipped := (OAI.EditApproximation.BinaryFraction.maxWithWork lower online).1 + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation OAI.EditApproximation.BinaryFraction.one delta + OAI.EditApproximation.BinaryFraction.divAllocation cone denominator + + OAI.EditApproximation.BinaryFraction.maxAllocation lower online + OAI.EditApproximation.BinaryFraction.minAllocation cone clipped + +def coefficientAllocation (kappa : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) kappa + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa).1 + 0 + +def gainReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + OAI.EditApproximation.BinaryFraction.divAllocation (read s i).1.neg (mass i.1) + 0 + +def decrementReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (s : ℕ) (i : β × σ) : ℕ := + footprint s i + footprint (s + 1) i + OAI.EditApproximation.BinaryFraction.subAllocation (read s i).1 (read (s + 1) i).1 + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (read s i).1 (read (s + 1) i).1).1 (mass i.1) + 0 + +def logarithmWithWork (r : OAI.EditApproximation.BinaryFraction) (k : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one + let ratio := OAI.EditApproximation.BinaryFraction.divWithWork numerator.1 denominator.1 + let subtotal := OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio.1 k + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) subtotal.1 + (result.1, numerator.2 + denominator.2 + ratio.2 + subtotal.2 + result.2 + 5) + +def optimisticTermReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (coefficient : OAI.EditApproximation.BinaryFraction) + (s : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let gain := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i + let decrement := OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement.1 + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork gain.1 scaled.1 + (total.1, gain.2 + decrement.2 + scaled.2 + total.2 + 2) + +def queryExponentsWithWork (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let count := max 1 N.bits.length + let selected := OAI.EditApproximation.filterWithWork (fun e => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w + (guard.1, guard.2 + e + 2)) (List.range count) + (selected.1, selected.2 + count + N.bits.length + 2) + +def seedMedianWithWork (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let median := OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values + let trimmed := OAI.EditApproximation.trimBitWordWithWork median.1 + (trimmed.1, median.2 + trimmed.2 + 1) + +def coarseGridPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) (source : List OAI.EditApproximation.BinaryFraction) : + List OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source + let right := OAI.EditApproximation.BinaryFraction.coarseGridLeftWithWork two source.reverse + let result := OAI.EditApproximation.BinaryFraction.coarseGridZipMinimumWithWork left.1 right.1.reverse + (result.1, left.2 + right.2 + result.2 + 3 * source.length) + +def coarseChildThresholdWithWork (B q : ℕ) (allowance : OAI.EditApproximation.BinaryFraction) (draw : Fin B) : + OAI.EditApproximation.BinaryFraction × ℕ := + let numerator := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork allowance (OAI.EditApproximation.BinaryFraction.nat (draw.val + 1)) + let divisor := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat B) (OAI.EditApproximation.BinaryFraction.nat q) + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork numerator.1 divisor.1 + (result.1, numerator.2 + divisor.2 + result.2 + Nat.size (draw.val + 1) + Nat.size B + Nat.size q + 4) + +def coarseChildAllowanceWithWork (L : ℕ) (threshold : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.coarseDivideWithWork threshold (OAI.EditApproximation.BinaryFraction.nat L) + (result.1, result.2 + Nat.size L + 1) + +def logarithmPartialAllocation (b : OAI.EditApproximation.BinaryFraction) : ℕ → ℕ + | 0 => 0 + | n + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork b n).1 + let power := (OAI.EditApproximation.BinaryFraction.powWithWork b (2 * n + 1)).1 + let term := (OAI.EditApproximation.BinaryFraction.divWithWork power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1))).1 + logarithmPartialAllocation b n + OAI.EditApproximation.BinaryFraction.powAllocation b (2 * n + 1) + + OAI.EditApproximation.BinaryFraction.divAllocation power (OAI.EditApproximation.BinaryFraction.nat (2 * n + 1)) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation previous term + Nat.size (2 * n + 1) + 1 + +def bandMassAllocation {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) (List.finRange M) + 2 * M + +def sumListAllocation (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.dotListAllocation (Vector.ofFn values.get) (Vector.replicate values.length OAI.EditApproximation.BinaryFraction.one) + (List.finRange values.length) + 3 * values.length + +def naturalDistanceLeAllocation (a b radius : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.leAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b)).1 (OAI.EditApproximation.BinaryFraction.nat radius) + + Nat.size a + Nat.size b + Nat.size radius + +def queryExponentsAllocation (N F : ℕ) (a w : OAI.EditApproximation.BinaryFraction) : ℕ := + let count := max 1 N.bits.length + OAI.EditApproximation.filterAllocation (fun e => ((OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).1, + (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ e) a w).2 + e + 2)) + (fun e => OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ e) a w + e + 1) (List.range count) + + count + N.bits.length + +def seedMedianAllocation (N multiplier : ℕ) (values : List OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.medianSeedAllocation N multiplier values + + OAI.EditApproximation.trimBitWordAllocation (OAI.EditApproximation.BinaryFraction.medianSeedWithWork N multiplier values).1 + 0 + +def onlineMinimumAllocation : List OAI.EditApproximation.BinaryFraction → ℕ + | [] => 0 + | first :: rest => OAI.EditApproximation.BinaryFraction.minimumAllocation first rest + +def optimisticTermReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (coefficient : OAI.EditApproximation.BinaryFraction) (s : ℕ) (i : β × σ) : ℕ := + let gain := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read s i).1 + let decrement := (OAI.EditApproximation.BinaryFraction.decrementReadWithWork mass read s i).1 + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint s i + OAI.EditApproximation.BinaryFraction.decrementReadAllocation mass read footprint s i + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient decrement + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation gain (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient decrement).1 + 0 + +def gradientCellWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : OAI.EditApproximation.BinaryFraction × ℕ := + let smoothing := OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50 + let inverse := smoothing.1.invWithWork + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse.1 + let logarithm := OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted.1 (G ^ 60) + let deficit := OAI.EditApproximation.BinaryFraction.subWithWork logarithm.1.neg OAI.EditApproximation.BinaryFraction.one + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork deficit.1 (linear.get i) + (result.1, smoothing.2 + inverse.2 + shifted.2 + logarithm.2 + deficit.2 + result.2 + + Nat.size G + 70) + +def queryScalesWithWork (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : List ℕ × ℕ := + let exponents := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let scales := OAI.EditApproximation.arithmeticMapWithWork (fun e => (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e), e + 3)) exponents.1 + (scales.1, exponents.2 + scales.2 + 1) + +def querySeedMedianWithWork (N multiplier : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.seedMedianWithWork N multiplier words + (OAI.EditApproximation.BinaryFraction.ofNaturalWord result.1, result.2 + result.1.length + 1) + +def coarseBinaryPenaltyWithWork (two : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction.CoarseBinaryArray → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | none => (none, 0) + | some values => + let result := OAI.EditApproximation.BinaryFraction.coarseGridPenaltyWithWork two values + (some result.1, result.2) + +def logarithmAllocation (r : OAI.EditApproximation.BinaryFraction) (n : ℕ) : ℕ := + let numerator := (OAI.EditApproximation.BinaryFraction.subWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let denominator := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork r OAI.EditApproximation.BinaryFraction.one).1 + let ratio := (OAI.EditApproximation.BinaryFraction.divWithWork numerator denominator).1 + OAI.EditApproximation.BinaryFraction.subAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation r OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.divAllocation numerator denominator + + OAI.EditApproximation.BinaryFraction.logarithmPartialAllocation ratio n + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.logarithmPartialWithWork ratio n).1 + +def queryScalesAllocation (N F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + + OAI.EditApproximation.arithmeticMapAllocation (fun e => e + 1) (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def coarseIndexChildren {B : ℕ} (k q L : ℕ) (two : OAI.EditApproximation.BinaryFraction) + (width : Fin B → ℕ) + (evaluate : Fin B → OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ) + (draw : Fin B → Fin B) (allowance : OAI.EditApproximation.BinaryFraction) : + List (Fin B) → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | [], _ => (none, 0) + | i :: rest, start => + let threshold := OAI.EditApproximation.BinaryFraction.coarseChildThresholdWithWork B q allowance (draw i) + let childAllowance := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork L threshold.1 + let evaluated := evaluate i childAllowance.1 start + let penalty := OAI.EditApproximation.BinaryFraction.coarseBinaryPenaltyWithWork two evaluated.1 + let scale := OAI.EditApproximation.BinaryFraction.coarseChildAllowanceWithWork q allowance + let contribution := OAI.EditApproximation.BinaryFraction.coarseBinaryMapWithWork (OAI.EditApproximation.BinaryFraction.coarseContributionWithWork threshold.1 scale.1) penalty.1 + let remainder := coarseIndexChildren k q L two width evaluate draw allowance rest (start + width i) + let total := OAI.EditApproximation.BinaryFraction.coarseBinaryAddWithWork contribution.1 remainder.1 + (total.1, threshold.2 + childAllowance.2 + evaluated.2 + penalty.2 + scale.2 + contribution.2 + + remainder.2 + total.2 + Nat.size start + Nat.size (width i) + 9) + +def gradientCellAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) + (i : Fin d) : ℕ := + let smoothing := (OAI.EditApproximation.BinaryFraction.powWithWork (OAI.EditApproximation.BinaryFraction.nat G) 50).1 + let inverse := smoothing.invWithWork.1 + let shifted := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (point.get i) inverse).1 + let logarithm := (OAI.EditApproximation.BinaryFraction.logarithmWithWork shifted (G ^ 60)).1 + let deficit := (OAI.EditApproximation.BinaryFraction.subWithWork logarithm.neg OAI.EditApproximation.BinaryFraction.one).1 + OAI.EditApproximation.BinaryFraction.powAllocation (OAI.EditApproximation.BinaryFraction.nat G) 50 + OAI.EditApproximation.BinaryFraction.invAllocation smoothing + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (point.get i) inverse + OAI.EditApproximation.BinaryFraction.logarithmAllocation shifted (G ^ 60) + + OAI.EditApproximation.BinaryFraction.subAllocation logarithm.neg OAI.EditApproximation.BinaryFraction.one + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation deficit (linear.get i) + Nat.size G + 1 + +def coarseIndexedWithWork {B : ℕ} (k q L n : ℕ) (source target : List ℕ) + (two : OAI.EditApproximation.BinaryFraction) : (d offset : ℕ) → OAI.EditApproximation.CoarseThresholdDraws B d → + OAI.EditApproximation.BinaryFraction → ℕ → OAI.EditApproximation.BinaryFraction.CoarseBinaryArray × ℕ + | 0, offset, _, allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B 0 n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let letter := OAI.EditApproximation.coarsePaddedReadWithWork n source offset + let cells := OAI.EditApproximation.arithmeticMapWithWork (fun shift : Fin (2 * k + 1) => + let mismatch := OAI.EditApproximation.BinaryFraction.coarseReadShiftWithWork k n target letter.1 start shift + let value := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork allowance.denominator allowance.denominator_pos mismatch.1 + (value.1, value.2 + mismatch.2)) (List.finRange (2 * k + 1)) + (some cells.1, descriptor.2 + letter.2 + prune.2 + cells.2 + + Nat.size size + 3 * (2 * k + 1) + 1) + | d + 1, offset, (draws, below), allowance, start => + let descriptor := OAI.EditApproximation.coarseDescriptorWithWork B (d + 1) n offset + let size := OAI.EditApproximation.bitWordValue descriptor.1 + let prune := OAI.EditApproximation.BinaryFraction.leWithWork (OAI.EditApproximation.BinaryFraction.nat size) allowance + if prune.1 then (none, descriptor.2 + prune.2 + Nat.size size + 1) else + let capacity := OAI.EditApproximation.bitPowerWithWork B.bits d + let childOffset := fun i : Fin B => + OAI.EditApproximation.coarseChildOffsetWithWork offset (OAI.EditApproximation.bitWordValue capacity.1) i.val + let childSize := fun i : Fin B => + OAI.EditApproximation.coarseDescriptorWithWork B d n (OAI.EditApproximation.bitWordValue (childOffset i).1) + let result := OAI.EditApproximation.BinaryFraction.coarseIndexChildren k q L two + (fun i => OAI.EditApproximation.bitWordValue (childSize i).1) + (fun i a s => + let evaluated := coarseIndexedWithWork k q L n source target two d + (OAI.EditApproximation.bitWordValue (childOffset i).1) (below i) a s + let next := OAI.EditApproximation.binaryNaturalAddWithWork s (OAI.EditApproximation.bitWordValue (childSize i).1) + (evaluated.1, evaluated.2 + 3 * ((childOffset i).2 + (childSize i).2 + next.2 + 3))) + draws allowance (List.finRange B) start + (result.1, descriptor.2 + capacity.2 + result.2 + prune.2 + Nat.size size + B + 1) + +def gradientAllocation {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : ℕ := + OAI.EditApproximation.vectorMapAllocation d (OAI.EditApproximation.BinaryFraction.gradientCellAllocation G linear point) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def gradientWithWork {d : ℕ} (G : ℕ) (linear point : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + OAI.EditApproximation.vectorMapWithWork d (OAI.EditApproximation.BinaryFraction.gradientCellWithWork G linear point) + +def scoredArgmaxWithWork {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) : + List α → Option (α × OAI.EditApproximation.BinaryFraction) × ℕ + | [] => (none, 0) + | a :: rest => + let tail := scoredArgmaxWithWork score rest + let current := score a + match tail.1 with + | none => (some (a, current.1), tail.2 + current.2 + 1) + | some best => + let comparison := current.1.ltWithWork best.2 + (if comparison.1 then some best else some (a, current.1), + tail.2 + current.2 + comparison.2 + 2) + +def optimizerUpdateWithWork {d : ℕ} (j : ℕ) (previous selected : Vector OAI.EditApproximation.BinaryFraction d) : + Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let step := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (OAI.EditApproximation.BinaryFraction.nat (j + 2)) + let complement := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one step.1 + let result := OAI.EditApproximation.vectorMapWithWork d fun i => + let first := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork complement.1 (previous.get i) + let second := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork step.1 (selected.get i) + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork first.1 second.1 + (total.1, first.2 + second.2 + total.2 + 4) + (result.1, step.2 + complement.2 + result.2 + Nat.size (j + 2) + 4) + +def bandMassTotalWithWork {M : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.dotWithWork mass (Vector.replicate M OAI.EditApproximation.BinaryFraction.one) + +def coefficientWithWork (kappa : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let scaled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) kappa + let difference := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one scaled.1 + (difference.1, scaled.2 + difference.2 + 1) + +def naturalDistanceLeWithWork (a b radius : ℕ) : Bool × ℕ := + let distance := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat a) (OAI.EditApproximation.BinaryFraction.nat b) + let result := distance.1.leWithWork (OAI.EditApproximation.BinaryFraction.nat radius) + (result.1, distance.2 + result.2 + Nat.size a + Nat.size b + Nat.size radius + 3) + +def onlineMinimumWithWork : List OAI.EditApproximation.BinaryFraction → Option OAI.EditApproximation.BinaryFraction × ℕ + | [] => (none, 1) + | first :: rest => + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork first rest + (some result.1, result.2 + 1) + +def refinementUpdateWithWork (delta cone : OAI.EditApproximation.BinaryFraction) : Option OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryFraction × ℕ + | none => (cone, 1) + | some online => + let denominator := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork OAI.EditApproximation.BinaryFraction.one delta + let lower := OAI.EditApproximation.BinaryFraction.divWithWork cone denominator.1 + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork lower.1 online + let result := OAI.EditApproximation.BinaryFraction.minWithWork cone clipped.1 + (result.1, denominator.2 + lower.2 + clipped.2 + result.2 + 2) + +def equalWithWork (a b : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let left := a.leWithWork b + let right := b.leWithWork a + (left.1 && right.1, left.2 + right.2 + 1) + +def roundedSpacingWithWork (theta envelope : OAI.EditApproximation.BinaryFraction) : List Bool × ℕ := + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta envelope + let clipped := OAI.EditApproximation.BinaryFraction.maxWithWork OAI.EditApproximation.BinaryFraction.one product.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork clipped.1 + (rounded.1, product.2 + clipped.2 + rounded.2 + 2) + +def maximizerWithWork {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : Vector OAI.EditApproximation.BinaryFraction d × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) vertices + ((selected.1.map Prod.fst).getD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), selected.2 + d + 1) + +def groupTermsWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : List OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.arithmeticMapWithWork (fun i => + let test := OAI.EditApproximation.BinaryFraction.equalWithWork (envelope.get i) h + (if test.1 then values.get i else OAI.EditApproximation.BinaryFraction.zero, test.2 + 2)) indices + +def selectGroupWithWork {ι : Type u_1} (members : List ι) (hne : members ≠ []) + (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) : ι × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun member => + let result := estimate member + (result.1.neg, result.2 + 1)) members + ((selected.1.map Prod.fst).getD (members.head hne), selected.2 + 1) + +def finiteOptimizerWithWork {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → Vector OAI.EditApproximation.BinaryFraction d × ℕ + | 0 => (vertices.headD (Vector.replicate d OAI.EditApproximation.BinaryFraction.zero), d + 1) + | j + 1 => + let previous := finiteOptimizerWithWork vertices linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous.1 + let selected := OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient.1 vertices + let updated := OAI.EditApproximation.BinaryFraction.optimizerUpdateWithWork j previous.1 selected.1 + (updated.1, previous.2 + gradient.2 + selected.2 + updated.2 + 3) + +def selectionWithWork {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : + Option α × ℕ := + let iterate := OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j + let gradient := OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate.1 + let selected := OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient.1 vertex.2) vertices + (selected.1.map fun chosen => chosen.1.1, iterate.2 + gradient.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery + + +def value {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BitQuery ι β → β + | .done result => result + | .read key next => value oracle (next (oracle key)) + | .charge _ next => value oracle next + +def work {ι : Type u_1} {β : Type u_2} (oracle : ι → OAI.EditApproximation.BinaryFraction) (readWork : ι → ℕ) : OAI.EditApproximation.BitQuery ι β → ℕ + | .done _ => 0 + | .read key next => readWork key + work oracle readWork (next (oracle key)) + | .charge steps next => steps + work oracle readWork next + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} : OAI.EditApproximation.BitQuery ι α → (α → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | .done result, next => next result + | .read key continuation, next => .read key (fun word => bind (continuation word) next) + | .charge steps continuation, next => .charge steps (bind continuation next) + +def compute {ι : Type u_1} {α : Type u_2} (execution : α × ℕ) : OAI.EditApproximation.BitQuery ι α := + .charge execution.2 (.done execution.1) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) : OAI.EditApproximation.BitQuery ι β → OAI.EditApproximation.BitQuery κ β + | .done result => .done result + | .read key next => .charge (f key).2 + (.read (f key).1 (fun word => mapKeysWithWork f (next word))) + | .charge steps next => .charge steps (mapKeysWithWork f next) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery {key // P key} OAI.EditApproximation.BinaryFraction + | .done result => .done result + | .charge steps next => .charge steps (restrictWithWork P test htest next) + | .read key next => .charge (test key).2 + (if h : (test key).1 = true then + .read ⟨key, (htest key).mp h⟩ (fun word => restrictWithWork P test htest (next word)) + else restrictWithWork P test htest (next (OAI.EditApproximation.BinaryFraction.nat 0))) + +def runMemo {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := runMemo ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests, + first.localWork + rest.localWork⟩ + | .charge steps next, memory => + let rest := runMemo ask next memory + {rest with localWork := steps + rest.localWork} + +inductive Footprint {ι : Type u_1} {β : Type u_2} : OAI.EditApproximation.BitQuery ι β → Type _ where + | done (value : β) : Footprint (.done value) + | read (key : ι) (next : OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (continuation : ∀ word, Footprint (next word)) : Footprint (.read key next) + | charge {steps : ℕ} {next : OAI.EditApproximation.BitQuery ι β} (cells : ℕ) + (continuation : Footprint next) : Footprint (.charge steps next) + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + List κ → (List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → OAI.EditApproximation.BitQuery ι β + | [], next => next [] + | key :: rest, next => (reader key).bind (fun word => + .charge 3 (collect reader rest (fun words => next (word :: words)))) + +def normalize {ι : Type u_1} (program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + program.bind fun word => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + + +end OAI.EditApproximation.BitQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion + +def substring {α : Type u} (word : List α) (lo hi : ℕ) : List α := + (word.take hi).drop lo + +structure TargetInterval (length : ℕ) where + lo : ℕ + hi : ℕ + ordered : lo ≤ hi + valid : hi ≤ length + +def occurrenceDeficit {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + word.length - if a ∈ word then 1 else 0 + +def natListMinimum (fallback : ℕ) : List ℕ → ℕ + | [] => fallback + | first :: rest => min first (natListMinimum fallback rest) + +def coarsePadTo {α : Type u} (n : ℕ) (word : List α) : List (Option α) := + word.map some ++ List.replicate (n - word.length) none + +def connectionBudget {n : ℕ} (start : ℕ) (states : List (OAI.EditApproximation.TargetInterval n)) + (finish : ℕ) : ℕ := + match states with + | [] => Nat.dist start finish + | state :: rest => Nat.dist start state.lo + connectionBudget state.hi rest finish + +def singletonCost {α : Type u} [DecidableEq α] (a : α) (word : List α) : ℕ := + if word = [] then 1 else OAI.EditApproximation.occurrenceDeficit a word + +def makeTargetState (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) := + if h : lo ≤ hi ∧ hi ≤ n then some ⟨lo, hi, h.1, h.2⟩ else none + +def targetEndpointDistance {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.dist q.lo r.lo + Nat.dist q.hi r.hi + +def targetStates (n : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (List.range (n + 1)).flatMap fun lo => + (List.range (n + 1)).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def shortSourceCost {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + match source with + | [] => target.length + | a :: _ => OAI.EditApproximation.singletonCost a target + +def exactSuffixDP {α : Type u_1} [DecidableEq α] : List α → List α → List ℕ + | [], target => List.ofFn fun j : Fin (target.length + 1) => target.length - j.val + | a :: rest, target => + let previous := exactSuffixDP rest target + List.ofFn fun j : Fin (target.length + 1) => + OAI.EditApproximation.natListMinimum (OAI.EditApproximation.singletonCost a [] + previous.getD j.val 0) + ((List.range (target.length - j.val + 1)).map fun k => + OAI.EditApproximation.singletonCost a ((target.drop j.val).take k) + previous.getD (j.val + k) 0) + +def exactSuffixAnswer {α : Type u_1} [DecidableEq α] (source target : List α) : ℕ := + (OAI.EditApproximation.exactSuffixDP source target).getD 0 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def sourceChild {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (child : Fin M) : OAI.EditApproximation.TargetInterval n := by + have proof_balancedCut_monotone_7 (lo : ℕ) (width : ℕ) (M : ℕ) : Monotone (OAI.EditApproximation.balancedCut lo width M) := by + intro i j hij + exact Nat.add_le_add_left (Nat.div_le_div_right (Nat.mul_le_mul_right width hij)) lo + have proof_balancedCut_last_9 (lo : ℕ) (width : ℕ) (M : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.balancedCut lo width M M = lo + width := by + simp only [OAI.EditApproximation.balancedCut, Nat.mul_div_cancel_left _ hM] + have proof_balancedCut_bounds_8 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) (hi : LE.le.{0} i M) : + lo ≤ OAI.EditApproximation.balancedCut lo width M i ∧ OAI.EditApproximation.balancedCut lo width M i ≤ lo + width := by + constructor + · exact Nat.le_add_right _ _ + · rw [← proof_balancedCut_last_9 lo width M hM] + exact proof_balancedCut_monotone_7 lo width M hi + exact + { lo := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M child.val + hi := OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M (child.val + 1) + ordered := proof_balancedCut_monotone_7 _ _ _ (Nat.le_succ _) + valid := by + have hM : 0 < M := Nat.zero_lt_of_lt child.isLt + have hbound := (proof_balancedCut_bounds_8 parent.lo (parent.hi - parent.lo) M (child.val + 1) + hM (by omega)).2 + rw [Nat.add_sub_of_le parent.ordered] at hbound + exact hbound.trans parent.valid } + +def roundInterval {n : ℕ} (spacing : ℕ) (state : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n := by + have proof_gridRound_mono_10 (spacing : ℕ) : Monotone (OAI.EditApproximation.gridRound spacing) := by + intro p q hpq + exact Nat.mul_le_mul_left spacing (Nat.div_le_div_right hpq) + have proof_gridRound_le_11 (spacing : ℕ) (position : ℕ) : OAI.EditApproximation.gridRound spacing position ≤ position := + Nat.mul_div_le _ _ + exact { + lo := OAI.EditApproximation.gridRound spacing state.lo + hi := OAI.EditApproximation.gridRound spacing state.hi + ordered := proof_gridRound_mono_10 spacing state.ordered + valid := (proof_gridRound_le_11 spacing state.hi).trans state.valid + } + +def localTargetStates (n g radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (q.lo - radius) (q.lo + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (q.hi - radius) (q.hi + radius)).filterMap fun hi => + OAI.EditApproximation.makeTargetState n lo hi + +def rationalStateGap {α : Type u_1} (source target : List α) (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + (q.hi : ℚ) - q.lo - source.length + +def gridStateBox (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (lo - radius) (lo + radius)).flatMap fun s => + (OAI.EditApproximation.gridPointsBetween g (hi - radius) (hi + radius)).filterMap fun t => + OAI.EditApproximation.makeTargetState n s t + +abbrev PhysicalEntry (M J ny : ℕ) := OAI.EditApproximation.PhysicalNode M J × OAI.EditApproximation.TargetInterval ny + +def makeStateWithWork (n lo hi : ℕ) : Option (OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let first := OAI.EditApproximation.wordLEWithWork lo.bits hi.bits + let second := OAI.EditApproximation.wordLEWithWork hi.bits n.bits + if h : (first.1 && second.1) = true then + (some ⟨lo, hi, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [first, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.1, + by have hp : first.1 = true ∧ second.1 = true := by simpa only [Bool.and_eq_true] using h + simpa only [second, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] using hp.2⟩, + first.2 + second.2 + 4) + else (none, first.2 + second.2 + 2) + +def cellTargetStates (n g : ℕ) (side : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellGridPoints side g cell.1).flatMap fun lo => + (OAI.EditApproximation.cellGridPoints side g cell.2).filterMap fun hi => OAI.EditApproximation.makeTargetState n lo hi + +def gridGapStates (n g anchor radius sourceLength gapRadius : ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.gridPointsBetween g (anchor - radius) (anchor + radius)).flatMap fun lo => + (OAI.EditApproximation.gridPointsBetween g (lo + sourceLength - gapRadius) (lo + sourceLength + gapRadius)).filterMap + fun hi => OAI.EditApproximation.makeTargetState n lo hi + +abbrev PhysicalChildTables (M ny : ℕ) := Fin M → ℕ → OAI.EditApproximation.TargetInterval ny → ℚ + +abbrev PhysicalRationalAction (M ny : ℕ) := + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M + +def localTargetCells {n : ℕ} (side : ℚ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) := + (OAI.EditApproximation.localCellCoordinates side q.lo radius).flatMap fun lo => + (OAI.EditApproximation.localCellCoordinates side q.hi radius).map fun hi => (lo, hi) + +def coordinateEqualWithWork {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.naturalEqualWithWork a.1.val b.1.val + let lo := OAI.EditApproximation.naturalEqualWithWork a.2.lo b.2.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.2.hi b.2.hi + (child.1 && lo.1 && hi.1, child.2 + lo.2 + hi.2 + 2) + +def queryIntervalEqualWithWork {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let lo := OAI.EditApproximation.naturalEqualWithWork a.lo b.lo + let hi := OAI.EditApproximation.naturalEqualWithWork a.hi b.hi + (lo.1 && hi.1, lo.2 + hi.2 + 1) + +def childInputCode {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + input.1.val + M * (input.2.lo + (n + 1) * input.2.hi) + +def queryChildCodeWithWork {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let width := OAI.EditApproximation.binaryNaturalAddWithWork n 1 + let high := OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width.1) input.2.hi + let coordinate := OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high.1) + let scaled := OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate.1) + let result := OAI.EditApproximation.binaryNaturalAddWithWork input.1.val (OAI.EditApproximation.bitWordValue scaled.1) + (OAI.EditApproximation.bitWordValue result.1, width.2 + high.2 + coordinate.2 + scaled.2 + result.2 + 5) + +def querySliceHeadWithWork {α : Type u_1} (source : List α) + (interval : OAI.EditApproximation.TargetInterval source.length) : Option α × ℕ := + let test := OAI.EditApproximation.binaryNaturalCompareWithWork interval.lo interval.hi + (if test.1 = .lt then source[interval.lo]? else none, + test.2 + Nat.size interval.lo + Nat.size interval.hi + 3) + +def rankedBitProgramValue {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : OAI.EditApproximation.BinaryFraction := + (program key).value (fun child => rankedBitProgramValue rank program child.val) +termination_by rank key +decreasing_by exact child.property + +def scheduledRefinementWordWithWork (N pass : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + let e := OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass - + OAI.EditApproximation.smallLogExponent N + let value := OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork (e : ℤ) + (value.1, value.2 + 5) + else (OAI.EditApproximation.BinaryFraction.nat 1, 3) + +def coordinateEqualAllocation {M n : ℕ} (a b : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.val b.1.val + OAI.EditApproximation.naturalEqualAllocation a.2.lo b.2.lo + + OAI.EditApproximation.naturalEqualAllocation a.2.hi b.2.hi + 2 + +def queryIntervalEqualAllocation {n : ℕ} (a b : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.lo b.lo + OAI.EditApproximation.naturalEqualAllocation a.hi b.hi + 1 + +def sourceChildAllocation {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let next := (OAI.EditApproximation.binaryNaturalAddWithWork i.val 1).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + OAI.EditApproximation.binaryNaturalAddAllocation i.val 1 + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M i.val + + OAI.EditApproximation.balancedCutAllocation parent.lo (OAI.EditApproximation.bitWordValue width) M (OAI.EditApproximation.bitWordValue next) + 2 + +def zeroConnectionAllocation {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → ℕ + | [], finish => OAI.EditApproximation.naturalEqualAllocation start finish + | state :: rest, finish => OAI.EditApproximation.naturalEqualAllocation start state.lo + + zeroConnectionAllocation state.hi rest finish + 1 + +def queryChildCodeAllocation {M n : ℕ} (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + let width := (OAI.EditApproximation.binaryNaturalAddWithWork n 1).1 + let high := (OAI.EditApproximation.binaryNaturalMulWithWork (OAI.EditApproximation.bitWordValue width) input.2.hi).1 + let coordinate := (OAI.EditApproximation.binaryNaturalAddWithWork input.2.lo (OAI.EditApproximation.bitWordValue high)).1 + let scaled := (OAI.EditApproximation.binaryNaturalMulWithWork M (OAI.EditApproximation.bitWordValue coordinate)).1 + OAI.EditApproximation.binaryNaturalAddAllocation n 1 + OAI.EditApproximation.binaryNaturalMulAllocation (OAI.EditApproximation.bitWordValue width) input.2.hi + + OAI.EditApproximation.binaryNaturalAddAllocation input.2.lo (OAI.EditApproximation.bitWordValue high) + + OAI.EditApproximation.binaryNaturalMulAllocation M (OAI.EditApproximation.bitWordValue coordinate) + + OAI.EditApproximation.binaryNaturalAddAllocation input.1.val (OAI.EditApproximation.bitWordValue scaled) + +def roundStateAllocation {n : ℕ} (spacing : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.binaryGridRoundAllocation spacing q.lo + OAI.EditApproximation.binaryGridRoundAllocation spacing q.hi + 2 + +def actionEqualAllocation {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.allAllocation (fun i => OAI.EditApproximation.naturalEqualAllocation (a i).lo (b i).lo + + OAI.EditApproximation.naturalEqualAllocation (a i).hi (b i).hi) (List.finRange M) + +structure RawUnskippedBand (M ny : ℕ) where + center : OAI.EditApproximation.TargetInterval ny + actions : List (Fin M → OAI.EditApproximation.TargetInterval ny) + nonempty : actions ≠ [] + +def sourceIntervalAt (M n : ℕ) : (d : ℕ) → OAI.EditApproximation.TreeLayer M d → OAI.EditApproximation.TargetInterval n + | 0, _ => ⟨0, n, Nat.zero_le _, le_rfl⟩ + | d + 1, node => OAI.EditApproximation.sourceChild (sourceIntervalAt M n d node.1) node.2 + +def initialConeValue {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (a L0 : ℚ) + (query center : OAI.EditApproximation.TargetInterval target.length) : ℚ := + OAI.EditApproximation.scaledSeedValue (U center) a (OAI.EditApproximation.rationalStateGap source target center) + + L0 * OAI.EditApproximation.targetEndpointDistance query center + +def wideChildStateList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.gridStateBox ny (OAI.EditApproximation.seedGridSpacing b P) (10 * b) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) + (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) + +def bandCutShift {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (j : Fin M) : ℚ := + (states j).lo - ((OAI.EditApproximation.sourceChild parent j).lo : ℚ) + +def localInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) + (U : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter (fun (b : ℕ) => decide + ((U q : ℚ) / (16 * A ^ 2) ≤ (b : ℚ) ∧ (b : ℚ) ≤ 4 * A * U q))).flatMap fun b => + (OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (U q) q).filter fun r => + decide ((b : ℚ) / 2 ≤ U r ∧ (U r : ℚ) ≤ 4 * A * b) + +def gridStateBoxWithWork (n g radius lo hi : ℕ) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let leftLow := OAI.EditApproximation.saturatingSubtractWithWork lo radius + let leftHigh := OAI.EditApproximation.binaryNaturalAddWithWork lo radius + let rightLow := OAI.EditApproximation.saturatingSubtractWithWork hi radius + let rightHigh := OAI.EditApproximation.binaryNaturalAddWithWork hi radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow.1) (OAI.EditApproximation.bitWordValue leftHigh.1) + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow.1) (OAI.EditApproximation.bitWordValue rightHigh.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right.1) left.1 + (states.1, leftLow.2 + leftHigh.2 + rightLow.2 + rightHigh.2 + left.2 + right.2 + states.2 + 6) + +def sourceChildWithWork {n M : ℕ} (parent : OAI.EditApproximation.TargetInterval n) (i : Fin M) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_binaryNaturalSubtractWithWork_value_54 (a : ℕ) (b : ℕ) (h : LE.le.{0} b a) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalSubtractWithWork a b).1 = a - b := by + simpa only [OAI.EditApproximation.binaryNaturalSubtractWithWork, proof_bitWordValue_bits_15] using + proof_bitSubtractWithWork_sub_22 a.bits b.bits (by simpa only [proof_bitWordValue_bits_15] using h) + have proof_saturatingSubtractWithWork_value_50 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.saturatingSubtractWithWork a b).1 = a - b := by + unfold OAI.EditApproximation.saturatingSubtractWithWork + dsimp only + split_ifs with h + · have hlt := (proof_binaryNaturalCompareWithWork_lt_53 a b).mp h + simp only [OAI.EditApproximation.bitWordValue, Nat.sub_eq_zero_of_le hlt.le] + · exact proof_binaryNaturalSubtractWithWork_value_54 a b (le_of_not_gt (fun hab => + h ((proof_binaryNaturalCompareWithWork_lt_53 a b).mpr hab))) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_balancedCutWithWork_value_51 (lo : ℕ) (width : ℕ) (M : ℕ) (i : ℕ) (hM : LT.lt.{0} 0 M) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.balancedCutWithWork lo width M i).1 = OAI.EditApproximation.balancedCut lo width M i := by + simp only [OAI.EditApproximation.balancedCutWithWork, proof_binaryNaturalAddWithWork_value_52, + (proof_binaryNaturalDivModWithWork_spec_24 _ M hM).1, proof_binaryNaturalMulWithWork_value_55, OAI.EditApproximation.balancedCut] + exact + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let next := OAI.EditApproximation.binaryNaturalAddWithWork i.val 1 + let left := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M i.val + let right := OAI.EditApproximation.balancedCutWithWork parent.lo (OAI.EditApproximation.bitWordValue width.1) M (OAI.EditApproximation.bitWordValue next.1) + let heql : OAI.EditApproximation.bitWordValue left.1 = (OAI.EditApproximation.sourceChild parent i).lo := by + simp only [left, width, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, OAI.EditApproximation.sourceChild] + let heqh : OAI.EditApproximation.bitWordValue right.1 = (OAI.EditApproximation.sourceChild parent i).hi := by + simp only [right, width, next, proof_balancedCutWithWork_value_51 _ _ _ _ (Nat.zero_lt_of_lt i.isLt), + proof_saturatingSubtractWithWork_value_50, proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.sourceChild] + (⟨OAI.EditApproximation.bitWordValue left.1, OAI.EditApproximation.bitWordValue right.1, + by rw [heql, heqh]; exact (OAI.EditApproximation.sourceChild parent i).ordered, + by rw [heqh]; exact (OAI.EditApproximation.sourceChild parent i).valid⟩, + width.2 + next.2 + left.2 + right.2 + 4) + +def cellRepresentativeStates (n P F b : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval n → ℚ) + (theta : ℚ) (cell : ℕ × ℕ) : List (OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing b P) (theta * b) cell).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b) + +def groupRoundedStateList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent : ℕ) (cell : ℕ × ℕ) + (i : Fin M) (h : ℚ) : List (OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.gridGapStates target.length (OAI.EditApproximation.groupRoundSpacing exponent h) + (⌊(cell.1 : ℚ) * ((2 : ℚ) ^ (-(exponent : ℤ)) * b)⌋₊ + + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (12 * b) + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi).length ⌈2 * h⌉₊ + +def rawInitialConeCenters {n : ℕ} (N P : ℕ) (A : ℚ) (value : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + ((value : ℚ) / (16 * A ^ 2) ≤ b ∧ (b : ℚ) ≤ 4 * A * value)).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) value q + +def historyInputCode {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + Nat.pair input.2.1 (OAI.EditApproximation.childInputCode (input.1, input.2.2)) + +def localOnlineSourceKeys {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def queryHistoryCodeWithWork {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let child := OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2) + let pair := OAI.EditApproximation.queryPairWithWork input.2.1 child.1 + (pair.1, child.2 + pair.2 + 1) + +def queryOrderedChildInputsWithWork {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.coordinateEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) inputs + +def queryHistoryEqualWithWork {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let child := OAI.EditApproximation.coordinateEqualWithWork (a.1, a.2.2) (b.1, b.2.2) + let time := OAI.EditApproximation.naturalEqualWithWork a.2.1 b.2.1 + (child.1 && time.1, child.2 + time.2 + 1) + +def queryGapStatesWithWork (n g anchor radius sourceLength gapRadius : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let lo := OAI.EditApproximation.saturatingSubtractWithWork anchor radius + let hi := OAI.EditApproximation.binaryNaturalAddWithWork anchor radius + let left := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo.1) (OAI.EditApproximation.bitWordValue hi.1) + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4)) left.1 + (states.1, lo.2 + hi.2 + left.2 + states.2 + 3) + +def queryOnlineKeyEqualWithWork {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1 b.1 + let state := OAI.EditApproximation.queryIntervalEqualWithWork a.2 b.2 + (scale.1 && state.1, scale.2 + state.2 + 1) + +def physicalEntryCode {M J n : ℕ} (state : OAI.EditApproximation.PhysicalEntry M J n) : ℕ := + OAI.EditApproximation.childInputCode ((0 : Fin 1), state.2) + (n + 1) ^ 2 * OAI.EditApproximation.physicalNodeCode state.1 + +def rankedBitLocalWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (key : κ) : ℕ := + (program key).work (fun child => OAI.EditApproximation.rankedBitProgramValue rank program child.val) (fun _ => 0) + +def refinementParameterWordsWithWork (N pass : ℕ) (word : List Bool) + (hpositive : 0 < OAI.EditApproximation.bitWordValue word) : OAI.EditApproximation.RefinementParameterWords × ℕ := + let online := OAI.EditApproximation.BinaryFraction.onlineParametersWithWork word hpositive + let factor := OAI.EditApproximation.scheduledRefinementWordWithWork N pass + let decrement := OAI.EditApproximation.BinaryFraction.refinementDecrementWithWork word hpositive + (⟨online.1.2, factor.1, online.1.1, online.1.2, decrement.1⟩, + online.2 + factor.2 + decrement.2 + 5) + +def queryHistoryEqualAllocation {M n : ℕ} (a b : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation (a.1, a.2.2) (b.1, b.2.2) + OAI.EditApproximation.naturalEqualAllocation a.2.1 b.2.1 + 1 + +def queryOnlineKeyEqualAllocation {n : ℕ} (a b : ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1 b.1 + OAI.EditApproximation.queryIntervalEqualAllocation a.2 b.2 + 1 + +def gridStateBoxAllocation (n g radius lo hi : ℕ) : ℕ := + let leftLow := (OAI.EditApproximation.saturatingSubtractWithWork lo radius).1 + let leftHigh := (OAI.EditApproximation.binaryNaturalAddWithWork lo radius).1 + let rightLow := (OAI.EditApproximation.saturatingSubtractWithWork hi radius).1 + let rightHigh := (OAI.EditApproximation.binaryNaturalAddWithWork hi radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh)).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh)).1 + OAI.EditApproximation.saturatingSubtractAllocation lo radius + OAI.EditApproximation.binaryNaturalAddAllocation lo radius + + OAI.EditApproximation.saturatingSubtractAllocation hi radius + OAI.EditApproximation.binaryNaturalAddAllocation hi radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue leftLow) (OAI.EditApproximation.bitWordValue leftHigh) + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue rightLow) (OAI.EditApproximation.bitWordValue rightHigh) + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun s => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n s) right) + (fun s => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n s) (OAI.EditApproximation.makeStateAllocation n s) right) left + +def queryHistoryCodeAllocation {M n : ℕ} (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryChildCodeAllocation (input.1, input.2.2) + + OAI.EditApproximation.queryPairAllocation input.2.1 (OAI.EditApproximation.queryChildCodeWithWork (input.1, input.2.2)).1 + +def queryOrderedChildInputsAllocation {M n : ℕ} (inputs : List (Fin M × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.coordinateEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryChildCodeWithWork) + OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryChildCodeWithWork OAI.EditApproximation.queryChildCodeAllocation) inputs + +def actionMemberAllocation {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : List (Fin M → OAI.EditApproximation.TargetInterval n) → ℕ + | [] => 0 + | b :: rest => OAI.EditApproximation.actionEqualAllocation a b + actionMemberAllocation a rest + +def queryGapStatesAllocation (n g anchor radius sourceLength gapRadius : ℕ) : ℕ := + let lo := (OAI.EditApproximation.saturatingSubtractWithWork anchor radius).1 + let hi := (OAI.EditApproximation.binaryNaturalAddWithWork anchor radius).1 + let left := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi)).1 + let build := fun first => + let center := OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength + let lower := OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let upper := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center.1) gapRadius + let right := OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower.1) (OAI.EditApproximation.bitWordValue upper.1) + let valid := OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n first) right.1 + (valid.1, center.2 + lower.2 + upper.2 + right.2 + valid.2 + 4) + let allocation := fun first => + let center := (OAI.EditApproximation.binaryNaturalAddWithWork first sourceLength).1 + let lower := (OAI.EditApproximation.saturatingSubtractWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let upper := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue center) gapRadius).1 + let right := (OAI.EditApproximation.gridPointsWithWork g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper)).1 + OAI.EditApproximation.binaryNaturalAddAllocation first sourceLength + OAI.EditApproximation.saturatingSubtractAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue center) gapRadius + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lower) (OAI.EditApproximation.bitWordValue upper) + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n first) (OAI.EditApproximation.makeStateAllocation n first) right + OAI.EditApproximation.saturatingSubtractAllocation anchor radius + OAI.EditApproximation.binaryNaturalAddAllocation anchor radius + + OAI.EditApproximation.gridPointsAllocation g (OAI.EditApproximation.bitWordValue lo) (OAI.EditApproximation.bitWordValue hi) + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation left + +def wideActionList {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.finiteAssignments M (OAI.EditApproximation.wideChildStateList parent r b P) + +def physicalSourceInterval {M J : ℕ} (nx : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) : OAI.EditApproximation.TargetInterval nx := + OAI.EditApproximation.sourceIntervalAt M nx node.1.val node.2 + +def localInitialConeTable {α : Type u_1} (source target : List α) + (U : OAI.EditApproximation.TargetInterval target.length → ℕ) (N P F : ℕ) (A a : ℚ) + (q : OAI.EditApproximation.TargetInterval target.length) : ℚ := + if U q = 0 then 0 else + OAI.EditApproximation.rationalMinimum ((32 * F + 1) * N) + ((OAI.EditApproximation.localInitialConeCenters N P A U q).map + (OAI.EditApproximation.initialConeValue source target U a (32 * F) q)) + +def wideChildGridWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let child := OAI.EditApproximation.sourceChildWithWork parent i + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 10 b + let leftOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let rightOffset := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi parent.lo + let left := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset.1) + let right := OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset.1) + let grid := OAI.EditApproximation.gridStateBoxWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) + (OAI.EditApproximation.bitWordValue left.1) (OAI.EditApproximation.bitWordValue right.1) + (grid.1, child.2 + spacing.2 + radius.2 + leftOffset.2 + rightOffset.2 + left.2 + right.2 + grid.2 + 8) + +def queryOrderedHistoryInputsWithWork {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + OAI.EditApproximation.queryOrderedInputsWithWork OAI.EditApproximation.queryHistoryEqualWithWork + (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) inputs + +def queryNeededInputsWithWork {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let first := OAI.EditApproximation.queryActionInputsWithWork selected + let second := OAI.EditApproximation.queryActionInputsWithWork online + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork (first.1 ++ second.1) + (sorted.1, first.2 + second.2 + first.1.length + sorted.2 + 2) + +def computedQueryParameters (N pass : ℕ) : OAI.EditApproximation.RefinementParameterWords := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computed_small_word_pos_125 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.inputSmallLog N).bits := by + rw [proof_bitWordValue_bits_15] + exact Nat.two_pow_pos _ + exact + (OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits (proof_computed_small_word_pos_125 N)).1 + +def wideChildGridAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (i : Fin M) : ℕ := + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 10 b).1 + let leftOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let rightOffset := (OAI.EditApproximation.saturatingSubtractWithWork child.hi parent.lo).1 + let left := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue leftOffset)).1 + let right := (OAI.EditApproximation.binaryNaturalAddWithWork r.lo (OAI.EditApproximation.bitWordValue rightOffset)).1 + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.binaryNaturalMulAllocation 10 b + + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + OAI.EditApproximation.saturatingSubtractAllocation child.hi parent.lo + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue leftOffset) + + OAI.EditApproximation.binaryNaturalAddAllocation r.lo (OAI.EditApproximation.bitWordValue rightOffset) + + OAI.EditApproximation.gridStateBoxAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) + +def queryOrderedHistoryInputsAllocation {M n : ℕ} (inputs : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.queryOrderedInputsAllocation OAI.EditApproximation.queryHistoryEqualWithWork (OAI.EditApproximation.queryEncodedLEWithWork OAI.EditApproximation.queryHistoryCodeWithWork) + OAI.EditApproximation.queryHistoryEqualAllocation (OAI.EditApproximation.queryEncodedLEAllocation OAI.EditApproximation.queryHistoryCodeWithWork OAI.EditApproximation.queryHistoryCodeAllocation) inputs + +def queryNeededInputsAllocation {n M : ℕ} + (selected online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M)) : ℕ := + let first := (OAI.EditApproximation.queryActionInputsWithWork selected).1 + let second := (OAI.EditApproximation.queryActionInputsWithWork online).1 + OAI.EditApproximation.queryActionInputsAllocation selected + OAI.EditApproximation.queryActionInputsAllocation online + first.length + + OAI.EditApproximation.queryOrderedChildInputsAllocation (first ++ second) + +def physicalSource {α : Type u_1} {M J : ℕ} (source : List α) (node : OAI.EditApproximation.PhysicalNode M J) : List α := + OAI.EditApproximation.substring source (OAI.EditApproximation.physicalSourceInterval source.length node).lo (OAI.EditApproximation.physicalSourceInterval source.length node).hi + +def wideActionGridWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : List (Vector (OAI.EditApproximation.TargetInterval ny) M) × ℕ := + let choices := OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P) + let product := OAI.EditApproximation.materializedAssignmentsWithWork M choices.1.get + (product.1, choices.2 + product.2 + 1) + +def physicalCoarsePreparationCost {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + (OAI.EditApproximation.coarsePreparedSlicesWithWork source target interval.lo interval.hi entry.2.lo entry.2.hi).2 + +def wideActionGridAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) : ℕ := + let choices := (OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.wideChildGridWithWork parent r b P)).1 + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.wideChildGridAllocation parent r b P) + OAI.EditApproximation.materializedAssignmentsAllocation M choices.get + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def sumListWithWork (values : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork (Vector.ofFn values.get) + (result.1, result.2 + 6 * values.length) + +def connectionTermsWithWork {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction × ℕ + | [], finish => + let result := OAI.EditApproximation.BinaryFraction.distanceWithWork start finish + ([result.1], result.2 + 2) + | state :: rest, finish => + let current := OAI.EditApproximation.BinaryFraction.distanceWithWork start (OAI.EditApproximation.BinaryFraction.nat state.lo) + let tail := connectionTermsWithWork (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + (current.1 :: tail.1, + current.2 + tail.2 + Nat.size state.lo + Nat.size state.hi + 6) + +def bandEnvelopeReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (i : Fin M) : OAI.EditApproximation.BinaryFraction × ℕ := + let values := OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band + let floor := OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + let maximum := OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values.1 + let input := OAI.EditApproximation.BinaryFraction.maxWithWork floor.1 maximum.1 + let result := OAI.EditApproximation.BinaryFraction.dyadicCeilingWithWork input.1 + (result.1, values.2 + floor.2 + maximum.2 + input.2 + result.2 + band.length + 4) + +def onlineLinearReadWithWork {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (eta kappa : OAI.EditApproximation.BinaryFraction) + (t : ℕ) (i : β × σ) : OAI.EditApproximation.BinaryFraction × ℕ := + let coefficient := OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa + let terms := OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient.1 s.val i + let history := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms.1 + let current := OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i + let total := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history.1 current.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork eta total.1 + (result.1, coefficient.2 + terms.2 + history.2 + current.2 + total.2 + result.2 + 3) + +def targetCellsWithWork {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × ℕ) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius + let right := OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right.1) left.1 + (cells.1, left.2 + right.2 + cells.2 + 2) + +def cellStatesWithWork (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let left := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1 + let right := OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2 + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun lo => + OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right.1) left.1 + (states.1, left.2 + right.2 + states.2 + 2) + +def bandCoordinatesWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List (Fin M × OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun action => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M)) band + let unique := OAI.EditApproximation.dedupByWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + 1) + +def countedBandCoordinateWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) + (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1) + let result := if test.1 then OAI.EditApproximation.BinaryFraction.divWithWork (mass.get coordinate.1) total else (OAI.EditApproximation.BinaryFraction.zero, 1) + (result.1, test.2 + result.2 + 1) + +def representativeScaleReadWithWork {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (radius : List Bool) + (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (guard.1, guard.2 + word.2)) points.1 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((b, r), 1)) selected.1 + (labeled.1, spacing.2 + points.2 + selected.2 + labeled.2 + e + 5) + +def queryRawCentersWithWork {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) scales.1 + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.queryIntervalEqualWithWork centers.1 + (unique.1, scales.2 + radius.2 + centers.2 + unique.2 + 3) + +def queryWideInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let raw := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M)) representatives + let unique := OAI.EditApproximation.queryEraseWithWork OAI.EditApproximation.coordinateEqualWithWork raw.1 + (unique.1, raw.2 + unique.2 + M + 2) + +def queryRawHistoryInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2)) (List.finRange M)) representatives + (inputs.1, inputs.2 + M + 1) + +def queryGroupRoundedStatesWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval ny) × ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h + let child := OAI.EditApproximation.sourceChildWithWork parent i + let offset := OAI.EditApproximation.saturatingSubtractWithWork child.1.lo parent.lo + let base := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + let position := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base.1 (OAI.EditApproximation.BinaryFraction.nat b) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position.1 + let anchor := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor.1) (OAI.EditApproximation.bitWordValue offset.1) + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 12 b + let length := OAI.EditApproximation.saturatingSubtractWithWork child.1.hi child.1.lo + let twice := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h + let gap := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice.1 + let states := OAI.EditApproximation.queryGapStatesWithWork ny (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue anchor.1) + (OAI.EditApproximation.bitWordValue radius.1) (OAI.EditApproximation.bitWordValue length.1) (OAI.EditApproximation.bitWordValue gap.1) + (states.1, spacing.2 + child.2 + offset.2 + base.2 + position.2 + floor.2 + anchor.2 + + radius.2 + length.2 + twice.2 + gap.2 + states.2 + exponent + 12) + +def queryOnlineIntegerReadWithWork {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ × ℕ := + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q) + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + (OAI.EditApproximation.bitWordValue floor.1, word.2 + floor.2 + 1) + +def queryChildReadWithWork {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.coordinateEqualWithWork keys values (i, q) + +def queryHistoryReadWithWork {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryHistoryEqualWithWork keys values (input.1, s, input.2) + +def queryParentReadWithWork {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryIntervalEqualWithWork keys words r + +def initialGridReadWithWork {n : ℕ} (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let points := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) radius q.lo q.hi + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := read r + let guard := OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue word.1) A + (guard.1, guard.2 + word.2)) points.1 + (selected.1, spacing.2 + points.2 + selected.2 + 2) + +def queryInitialConeCentersWithWork {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius.1) b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue radius.1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1)) active.1 + (centers.1, radius.2 + scales.2 + active.2 + centers.2 + 2) + +def connectionTermsAllocation {n : ℕ} (start : OAI.EditApproximation.BinaryFraction) : + List (OAI.EditApproximation.TargetInterval n) → OAI.EditApproximation.BinaryFraction → ℕ + | [], finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start finish + 1 + | state :: rest, finish => OAI.EditApproximation.BinaryFraction.distanceAllocation start (OAI.EditApproximation.BinaryFraction.nat state.lo) + + connectionTermsAllocation (OAI.EditApproximation.BinaryFraction.nat state.hi) rest finish + Nat.size state.lo + Nat.size state.hi + 3 + +def endpointDistanceAllocation {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + OAI.EditApproximation.BinaryFraction.distanceAllocation (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 + (OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi)).1 + Nat.size q.lo + Nat.size q.hi + Nat.size r.lo + Nat.size r.hi + +def stateGapAllocation {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo)).1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + +def queryChildReadAllocation {M n : ℕ} (keys : List (Fin M × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation keys values (i, q) + +def queryHistoryReadAllocation {M n : ℕ} (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (s : ℕ) (input : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryHistoryEqualWithWork OAI.EditApproximation.queryHistoryEqualAllocation keys values (input.1, s, input.2) + +def queryOnlineIntegerReadAllocation {n : ℕ} (keys : List (ℕ × OAI.EditApproximation.TargetInterval n)) + (values : List OAI.EditApproximation.BinaryFraction) (b : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryOnlineKeyEqualWithWork keys values (b, q)).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryOnlineKeyEqualWithWork OAI.EditApproximation.queryOnlineKeyEqualAllocation keys values (b, q) + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + +def bandCoordinatesAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let build := fun action : Fin M → OAI.EditApproximation.TargetInterval n => + OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => ((i, action i), 1)) (List.finRange M) + let raw := (OAI.EditApproximation.arithmeticFlatMapWithWork build band).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ : Fin M => 1) (List.finRange M) + M) band + + OAI.EditApproximation.dedupByAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation raw + +def scoredArgmaxAllocation {α : Type u_1} (score : α → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : α → ℕ) : List α → ℕ + | [] => 0 + | a :: rest => + scoredArgmaxAllocation score allocation rest + allocation a + + match (OAI.EditApproximation.BinaryFraction.scoredArgmaxWithWork score rest).1 with + | none => 1 + | some best => OAI.EditApproximation.BinaryFraction.ltAllocation (score a).1 best.2 + 1 + +def anchorGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) (i : Fin M) : ℕ := + let left := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo).1 + let right := (OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi).1 + let radius := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork 6 b).1 + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + + OAI.EditApproximation.translatedEndpointAllocation r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + OAI.EditApproximation.binaryNaturalMulAllocation 6 b + + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation left (states i).lo radius + OAI.EditApproximation.BinaryFraction.naturalDistanceLeAllocation right (states i).hi radius + +def bandEnvelopeReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (i : Fin M) : ℕ := + let values := (OAI.EditApproximation.arithmeticMapWithWork (fun action => read i (action i)) band).1 + let floor := (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M)).1 + let maximum := (OAI.EditApproximation.BinaryFraction.maximumWithWork OAI.EditApproximation.BinaryFraction.zero values).1 + OAI.EditApproximation.arithmeticMapAllocation (fun action => footprint i (action i)) band + + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat b) (OAI.EditApproximation.BinaryFraction.nat M) + OAI.EditApproximation.BinaryFraction.maximumAllocation OAI.EditApproximation.BinaryFraction.zero values + OAI.EditApproximation.BinaryFraction.maxAllocation floor maximum + + OAI.EditApproximation.BinaryFraction.dyadicCeilingAllocation (OAI.EditApproximation.BinaryFraction.maxWithWork floor maximum).1 + 0 + +def targetCellsAllocation {n : ℕ} (side : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.lo radius).1 + let right := (OAI.EditApproximation.BinaryFraction.cellCoordinatesWithWork side q.hi radius).1 + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.lo radius + OAI.EditApproximation.BinaryFraction.cellCoordinatesAllocation side q.hi radius + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.arithmeticMapWithWork (fun hi => ((lo, hi), 1)) right) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) right) left + +def cellStatesAllocation (n g : ℕ) (side : OAI.EditApproximation.BinaryFraction) (cell : ℕ × ℕ) : ℕ := + let left := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.1).1 + let right := (OAI.EditApproximation.BinaryFraction.cellGridPointsWithWork side g cell.2).1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.1 + OAI.EditApproximation.BinaryFraction.cellGridPointsAllocation side g cell.2 + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun lo => OAI.EditApproximation.filterMapWithWork (OAI.EditApproximation.makeStateWithWork n lo) right) + (fun lo => OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.makeStateWithWork n lo) (OAI.EditApproximation.makeStateAllocation n lo) right) left + +def queryRawCentersAllocation {n : ℕ} (N P F : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let build := fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing.1) (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + (states.1, spacing.2 + states.2 + 1) + let allocation := fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1) q.lo q.hi + let centers := (OAI.EditApproximation.arithmeticFlatMapWithWork build (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1).1 + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation centers + +def queryOnlineKeysAllocation {n : ℕ} (N P F : ℕ) (_hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.arithmeticMapAllocation (fun b => + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) q + 1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + +def representativeScaleReadAllocation {n : ℕ} (P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (radius : List Bool) (query : OAI.EditApproximation.TargetInterval n) (e : ℕ) : ℕ := + let b := 2 ^ e + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).1, + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (read r).1).2 + (read r).2) + let selected := (OAI.EditApproximation.filterWithWork test points).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) query.lo query.hi + + OAI.EditApproximation.filterAllocation test (fun r => OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (read r).1 + allocation r) points + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) selected + e + 1 + +def queryWideInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let build := fun br : ℕ × OAI.EditApproximation.TargetInterval ny => + OAI.EditApproximation.arithmeticFlatMapWithWork (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (List.finRange M) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1 + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (fun i : Fin M => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (labeled.1, states.2 + labeled.2 + 1)) (one br) (List.finRange M)) representatives + + OAI.EditApproximation.queryEraseAllocation OAI.EditApproximation.coordinateEqualWithWork OAI.EditApproximation.coordinateEqualAllocation (OAI.EditApproximation.arithmeticFlatMapWithWork build representatives).1 + M + +def queryRawHistoryInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (P history : ℕ) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : ℕ := + let child := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + let states := OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i + let times := OAI.EditApproximation.arithmeticFlatMapWithWork (fun t => + OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) states.1) (List.range history) + (times.1, states.2 + times.2 + history + 2) + let one := fun (br : ℕ × OAI.EditApproximation.TargetInterval ny) (i : Fin M) => + OAI.EditApproximation.wideChildGridAllocation parent br.2 br.1 P i + history + + OAI.EditApproximation.arithmeticFlatMapAllocation (fun t => OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, t, r), 1)) + (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (fun _ => OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.wideChildGridWithWork parent br.2 br.1 P i).1) + (List.range history) + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => OAI.EditApproximation.arithmeticFlatMapWithWork (child br) (List.finRange M)) + (fun br => OAI.EditApproximation.arithmeticFlatMapAllocation (child br) (one br) (List.finRange M)) representatives + M + +def queryGroupRoundedStatesAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent : ℕ) (cell : ℕ × ℕ) (i : Fin M) (h : OAI.EditApproximation.BinaryFraction) : ℕ := + let theta := OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent + let spacing := (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta h).1 + let child := (OAI.EditApproximation.sourceChildWithWork parent i).1 + let offset := (OAI.EditApproximation.saturatingSubtractWithWork child.lo parent.lo).1 + let base := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat cell.1) theta).1 + let position := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork base (OAI.EditApproximation.BinaryFraction.nat b)).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork position).1 + let anchor := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset)).1 + let radius := (OAI.EditApproximation.binaryNaturalMulWithWork 12 b).1 + let length := (OAI.EditApproximation.saturatingSubtractWithWork child.hi child.lo).1 + let twice := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) h).1 + let gap := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork twice).1 + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation theta h + OAI.EditApproximation.sourceChildAllocation parent i + OAI.EditApproximation.saturatingSubtractAllocation child.lo parent.lo + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat cell.1) theta + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation base (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation position + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue floor) (OAI.EditApproximation.bitWordValue offset) + OAI.EditApproximation.binaryNaturalMulAllocation 12 b + + OAI.EditApproximation.saturatingSubtractAllocation child.hi child.lo + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) h + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation twice + + OAI.EditApproximation.queryGapStatesAllocation ny (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue anchor) (OAI.EditApproximation.bitWordValue radius) + (OAI.EditApproximation.bitWordValue length) (OAI.EditApproximation.bitWordValue gap) + exponent + 2 + +def groupIndexAllocation {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : ℕ := + OAI.EditApproximation.BinaryFraction.groupTermsAllocation h envelope indices + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices).1 + 0 + +def queryParentReadAllocation {n : ℕ} (keys : List (OAI.EditApproximation.TargetInterval n)) + (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryIntervalEqualWithWork OAI.EditApproximation.queryIntervalEqualAllocation keys words r + +def onlineLinearReadAllocation {β : Type u_1} {σ : Type u_2} (mass : β → OAI.EditApproximation.BinaryFraction) + (read : ℕ → β × σ → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : ℕ → β × σ → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (t : ℕ) (i : β × σ) : ℕ := + let coefficient := (OAI.EditApproximation.BinaryFraction.coefficientWithWork kappa).1 + let terms := (OAI.EditApproximation.vectorMapWithWork t fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadWithWork mass read coefficient s.val i).1 + let history := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork terms).1 + let current := (OAI.EditApproximation.BinaryFraction.gainReadWithWork mass read t i).1 + OAI.EditApproximation.BinaryFraction.coefficientAllocation kappa + + OAI.EditApproximation.vectorMapAllocation t (fun s => OAI.EditApproximation.BinaryFraction.optimisticTermReadAllocation mass read footprint coefficient s.val i) + + OAI.EditApproximation.BinaryFraction.bandMassAllocation terms + OAI.EditApproximation.BinaryFraction.gainReadAllocation mass read footprint t i + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation history current + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation eta (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork history current).1 + 0 + +def countedBandCoordinateAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (total : OAI.EditApproximation.BinaryFraction) (action : Fin M → OAI.EditApproximation.TargetInterval n) (coordinate : Fin M × OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.coordinateEqualAllocation coordinate (coordinate.1, action coordinate.1) + + if (OAI.EditApproximation.coordinateEqualWithWork coordinate (coordinate.1, action coordinate.1)).1 then + OAI.EditApproximation.BinaryFraction.divAllocation (mass.get coordinate.1) total else 0 + +def queryInitialConeCentersAllocation {n : ℕ} (N P : ℕ) (A value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1).1 + let build := fun b => + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let states := OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi + (states.1, (OAI.EditApproximation.seedGridSpacingWithWork b P).2 + states.2 + 1) + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork (OAI.EditApproximation.bitWordValue radius) b A) + (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation (OAI.EditApproximation.bitWordValue radius) b A) (OAI.EditApproximation.dyadicScalesWithWork N).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun b => OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) (OAI.EditApproximation.bitWordValue radius) q.lo q.hi) active + +def connectionWithWork {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish + let result := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (result.1, terms.2 + result.2 + 1) + +def envelopeVectorReadWithWork {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector OAI.EditApproximation.BinaryFraction M × ℕ := + OAI.EditApproximation.vectorMapWithWork M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read) + +def bellmanActionReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M) + let dist := distance query action.center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist.1 + let connection := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial.1 action.connection + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + dist.2 + spatial.2 + connection.2 + children.2 + result.2 + 3) + +def cellCentersReadWithWork {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 cell + let selected := OAI.EditApproximation.filterWithWork (fun r => + let word := initial r + let tested := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + (tested.1, word.2 + tested.2)) states.1 + (selected.1, spacing.2 + side.2 + states.2 + selected.2 + 3) + +def countedBandVerticesWithWork {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + List ((Fin M → OAI.EditApproximation.TargetInterval n) × Vector OAI.EditApproximation.BinaryFraction d) × ℕ := + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass + let vertices := band.map fun action => + let vertex := OAI.EditApproximation.vectorMapWithWork d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateWithWork mass total.1 action (coordinates.get i) + ((action, vertex.1), vertex.2) + (vertices.map Prod.fst, total.2 + (vertices.map Prod.snd).sum + 8 * band.length) + +def onlineIndexSetupWithWork {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + ℕ × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + let sum := OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.1.length + let offset := OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum.1) 2 + let power := OAI.EditApproximation.bitPowerWithWork offset.1 80 + (OAI.EditApproximation.bitWordValue offset.1, coordinates.2 + sum.2 + offset.2 + power.2 + 3) + +def localRepresentativeReadWithWork {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval n) : + List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a queryWord.1 + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork queryWord.1 + let result := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read radius.1 query) scales.1 + (result.1, queryWord.2 + scales.2 + radius.2 + result.2 + 3) + +def queryGroupKeysWithWork {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + exponent + 4) + +def queryMeanWithWork (count : ℕ) (words : List OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words + let result := OAI.EditApproximation.BinaryFraction.divWithWork total.1 (OAI.EditApproximation.BinaryFraction.nat count) + (result.1, total.2 + result.2 + Nat.size count + 2) + +def initialCentersReadWithWork {n : ℕ} (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) × ℕ := + let queryWord := read q + let Uq := OAI.EditApproximation.bitWordValue queryWord.1 + let scales := OAI.EditApproximation.dyadicScalesWithWork N + let active := OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales.1 + let centers := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) active.1 + (centers.1, queryWord.2 + scales.2 + active.2 + centers.2 + 3) + +def queryInitialSeedReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : List Bool × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + (result.1, test.2 + result.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + let result := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork found.1 + (result.1, test.2 + found.2 + result.2 + 1) + +def queryOverrideParentReadWithWork {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let test := OAI.EditApproximation.queryIntervalEqualWithWork r q + if test.1 then (value, test.2 + 1) + else + let found := OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r + (found.1, test.2 + found.2 + 1) + +def connectionAllocation {n : ℕ} (start finish : OAI.EditApproximation.BinaryFraction) + (states : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionTermsAllocation start states finish + + OAI.EditApproximation.BinaryFraction.sumListAllocation (OAI.EditApproximation.BinaryFraction.connectionTermsWithWork start states finish).1 + 0 + +def coordinateVectorAllocation {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1.length + +def maximizerAllocation {d : ℕ} (gradient : Vector OAI.EditApproximation.BinaryFraction d) + (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (OAI.EditApproximation.BinaryFraction.dotWithWork gradient) + (fun v => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient v (List.finRange d)) vertices + d + +def onlineIndexSetupAllocation {M n : ℕ} (H : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 + let sum := (OAI.EditApproximation.binaryNaturalAddWithWork H coordinates.length).1 + let offset := (OAI.EditApproximation.binaryNaturalAddWithWork (OAI.EditApproximation.bitWordValue sum) 2).1 + OAI.EditApproximation.BinaryFraction.bandCoordinatesAllocation band + OAI.EditApproximation.binaryNaturalAddAllocation H coordinates.length + + OAI.EditApproximation.binaryNaturalAddAllocation (OAI.EditApproximation.bitWordValue sum) 2 + OAI.EditApproximation.bitPowerAllocation offset 80 + +def envelopeVectorReadAllocation {M n : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read footprint) + +def roundedBandReadAllocation {n M : ℕ} (exponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation M fun i => + let envelope := (OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i).1 + let spacing := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope).1 + OAI.EditApproximation.BinaryFraction.bandEnvelopeReadAllocation b band read allocation i + + OAI.EditApproximation.BinaryFraction.roundedSpacingAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope + + OAI.EditApproximation.roundStateAllocation spacing (band.head hne i) + exponent + 2 + +def queryGroupKeysAllocation {n : ℕ} (N F exponent : ℕ) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun b => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun cell => ((b, cell), 1)) cells.1 + (labeled.1, side.2 + cells.2 + labeled.2 + 2) + OAI.EditApproximation.BinaryFraction.queryScalesAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun b => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1) + (OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value).1 + exponent + 2 + +def initialCellAllocation (n P exponent : ℕ) (key : ℕ × ℕ × ℕ) : ℕ := + OAI.EditApproximation.seedGridSpacingAllocation key.1 P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork key.1 P).1) + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1)).1 key.2 + exponent + 2 + +def localRepresentativeReadAllocation {n : ℕ} (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (query : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (read query).1 + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (read query).1 + + OAI.EditApproximation.arithmeticFlatMapAllocation + (OAI.EditApproximation.BinaryFraction.representativeScaleReadWithWork P F a read (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.representativeScaleReadAllocation P F a read allocation (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (read query).1).1 query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (read query).1).1 + +def cellCentersReadAllocation {n : ℕ} (P F b : ℕ) (a theta : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (cell : ℕ × ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork theta (OAI.EditApproximation.BinaryFraction.nat b)).1 + let states := (OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing) side cell).1 + let test := fun r => ((OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).1, + (initial r).2 + (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (initial r).1).2) + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation theta (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.cellStatesAllocation n (OAI.EditApproximation.bitWordValue spacing) side cell + + OAI.EditApproximation.filterAllocation test (fun r => allocation r + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (initial r).1) states + +def selectGroupAllocation {ι : Type u_1} (members : List ι) (estimate : ι → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : ι → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun member => ((estimate member).1.neg, (estimate member).2 + 1)) allocation members + +def bellmanActionReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (action : OAI.EditApproximation.BinaryBellmanAction Parent Child M) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read (action.childState i)) (List.finRange M)).1 + let dist := (distance query action.center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L dist).1 + let connection := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork spatial action.connection).1 + let children := (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint (action.childState i)) (List.finRange M) + + distanceAllocation query action.center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L dist + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation spatial action.connection + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection children + +def countedBandVerticesAllocation {M n d : ℕ} (coordinates : Vector (Fin M × OAI.EditApproximation.TargetInterval n) d) + (mass : Vector OAI.EditApproximation.BinaryFraction M) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : ℕ := + OAI.EditApproximation.BinaryFraction.bandMassAllocation mass + + (band.map fun action => OAI.EditApproximation.vectorMapAllocation d fun i => + OAI.EditApproximation.BinaryFraction.countedBandCoordinateAllocation mass (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork mass).1 action (coordinates.get i)).sum + + 4 * band.length + +def queryInitialSeedReadAllocation {n : ℕ} (value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words r).1 + +def queryOverrideParentReadAllocation {n : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (keys : List (OAI.EditApproximation.TargetInterval n)) (words : List OAI.EditApproximation.BinaryFraction) (r : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.queryIntervalEqualAllocation r q + + if (OAI.EditApproximation.queryIntervalEqualWithWork r q).1 then 0 else OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words r + +def prefixReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M) + let finish := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + let connection := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish.1 ((List.ofFn states).take j) + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 total.1 + (result.1, words.2 + finish.2 + connection.2 + total.2 + result.2 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 6 * M + 5) + +def bellmanReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L fallback : OAI.EditApproximation.BinaryFraction) + (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback scores.1 + (result.1, scores.2 + result.2 + 1) + +def queryWarmupInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def endpointConnectionAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + Nat.size r.lo + Nat.size r.hi + M + +def prefixReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i : Fin M => + if i.val < j then read i (states i) else (OAI.EditApproximation.BinaryFraction.zero, 1)) (List.finRange M)).1 + let finish := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i : Fin M => if i.val < j then allocation i (states i) else 0) + (List.finRange M) + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j)) p + + OAI.EditApproximation.BinaryFraction.connectionAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j) + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) finish ((List.ofFn states).take j)).1 + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + + Nat.size (OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j) + Nat.size r.lo + 2 * M + +def optimizerAllocation {d : ℕ} (vertices : List (Vector OAI.EditApproximation.BinaryFraction d)) + (linear : Vector OAI.EditApproximation.BinaryFraction d) (G : ℕ) : ℕ → ℕ + | 0 => d + | j + 1 => + let previous := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork vertices linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear previous).1 + let selected := (OAI.EditApproximation.BinaryFraction.maximizerWithWork gradient vertices).1 + optimizerAllocation vertices linear G j + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear previous + + OAI.EditApproximation.BinaryFraction.maximizerAllocation gradient vertices + OAI.EditApproximation.BinaryFraction.optimizerUpdateAllocation j previous selected + +def queryEarlierRepresentativesAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a (initial q).1 q).1 + let build := fun key : ℕ × ℕ × ℕ => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1) + allocation q + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a (initial q).1 q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun key => + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial allocation key.2 + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) + (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2).1) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q + + 2 * (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1.length + + (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1.length + +def queryWarmupInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q).1 + +def bellmanReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L fallback : OAI.EditApproximation.BinaryFraction) (read : Child → OAI.EditApproximation.BinaryFraction × ℕ) (footprint : Child → ℕ) + (query : Parent) (actions : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L read query) actions).1 + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L read footprint query) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def prefixMinimumReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p + let scores := OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 1) + +def localContinuationReadWithWork {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (L delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let warm := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide + let cone := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm.1 current query groups + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online + let onlineMin := OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores.1 + let result := OAI.EditApproximation.BinaryFraction.refinementUpdateWithWork delta cone.1 onlineMin.1 + (result.1, warm.2 + cone.2 + scores.2 + onlineMin.2 + result.2 + 3) + +def prefixMinimumReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (j : ℕ) (p : OAI.EditApproximation.BinaryFraction) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r (actions.head hne) read j p).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (fun action => OAI.EditApproximation.BinaryFraction.prefixReadWithWork parent r action read j p) actions).1 + OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r (actions.head hne) read allocation j p + + OAI.EditApproximation.arithmeticMapAllocation (fun action => OAI.EditApproximation.BinaryFraction.prefixReadAllocation parent r action read allocation j p) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + +def localContinuationReadAllocation {Parent : Type u_1} {Child : Type u_2} {M : ℕ} + (distance : Parent → Parent → OAI.EditApproximation.BinaryFraction × ℕ) (distanceAllocation : Parent → Parent → ℕ) + (L delta fallback : OAI.EditApproximation.BinaryFraction) (old current : Child → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Child → ℕ) (query : Parent) + (wide groups online : List (OAI.EditApproximation.BinaryBellmanAction Parent Child M)) : ℕ := + let warm := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L fallback old query wide).1 + let cone := (OAI.EditApproximation.BinaryFraction.bellmanReadWithWork distance L warm current query groups).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.bellmanActionReadWithWork distance L current query) online).1 + let onlineMin := (OAI.EditApproximation.BinaryFraction.onlineMinimumWithWork scores).1 + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L fallback old oldAllocation query wide + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation distance distanceAllocation L warm current currentAllocation query groups + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.bellmanActionReadAllocation distance distanceAllocation L current currentAllocation query) online + + OAI.EditApproximation.BinaryFraction.onlineMinimumAllocation scores + OAI.EditApproximation.BinaryFraction.refinementUpdateAllocation delta cone onlineMin + +def endpointActionAllocation {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation center states + M + 1 + +def selectionAllocation {α : Type u_1} {d : ℕ} + (vertices : List (α × Vector OAI.EditApproximation.BinaryFraction d)) (linear : Vector OAI.EditApproximation.BinaryFraction d) (G j : ℕ) : ℕ := + let iterate := (OAI.EditApproximation.BinaryFraction.finiteOptimizerWithWork (vertices.map Prod.snd) linear G j).1 + let gradient := (OAI.EditApproximation.BinaryFraction.gradientWithWork G linear iterate).1 + vertices.length + OAI.EditApproximation.BinaryFraction.optimizerAllocation (vertices.map Prod.snd) linear G j + + OAI.EditApproximation.BinaryFraction.gradientAllocation G linear iterate + + OAI.EditApproximation.BinaryFraction.scoredArgmaxAllocation (fun vertex => OAI.EditApproximation.BinaryFraction.dotWithWork gradient vertex.2) + (fun vertex => OAI.EditApproximation.BinaryFraction.dotListAllocation gradient vertex.2 (List.finRange d)) vertices + +def cutGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : Bool × ℕ := + if j.val = 0 then (true, 1) else + let shift := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + let offset := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + let prediction := OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift.1 + let result := OAI.EditApproximation.BinaryFraction.affineErrorWithWork shift.1 offset.1 velocity prediction.1 tolerance + (result.1, shift.2 + offset.2 + prediction.2 + result.2 + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + 5) + +def cutGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (velocity tolerance : OAI.EditApproximation.BinaryFraction) (j : Fin M) : ℕ := + if j.val = 0 then 0 else + let shift := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo)).1 + let offset := (OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo)).1 + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat (states j).lo) (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.sourceChild parent j).lo) + + OAI.EditApproximation.BinaryFraction.subAllocation (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat parent.lo) + + OAI.EditApproximation.BinaryFraction.prefixMinimumReadAllocation parent r actions hne read allocation j.val shift + + OAI.EditApproximation.BinaryFraction.affineErrorAllocation shift offset velocity + (OAI.EditApproximation.BinaryFraction.prefixMinimumReadWithWork parent r actions hne read j.val shift).1 tolerance + + Nat.size (states j).lo + Nat.size (OAI.EditApproximation.sourceChild parent j).lo + Nat.size r.lo + Nat.size parent.lo + +def bandPredicateReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.zeroConnectionAllocation r.lo (List.ofFn states) r.hi + M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.anchorGuardAllocation parent r b states) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.bandToleranceAllocation tau theta b M + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.cutGuardReadAllocation parent r actions hne read allocation states velocity + (OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M).1) (List.finRange M) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalConnectionBudget {n : ℕ} (start : ℚ) : List (OAI.EditApproximation.TargetInterval n) → ℚ → ℚ + | [], finish => |start - finish| + | state :: rest, finish => |start - state.lo| + rationalConnectionBudget state.hi rest finish + +def bandChildEnvelope {ny M : ℕ} (b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℚ := + OAI.EditApproximation.rationalDyadicCeiling (max ((b : ℚ) / M) + (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +def bandEnvelopeExponent {ny M : ℕ} (b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℤ := + Int.clog 2 (max ((b : ℚ) / M) (OAI.EditApproximation.rationalMaximum 0 (band.map fun action => initial i (action i)))) + +deriving instance DecidableEq for OAI.EditApproximation.TargetInterval + +def zeroConnectionWithWork {n : ℕ} (start : ℕ) : List (OAI.EditApproximation.TargetInterval n) → ℕ → Bool × ℕ + | [], finish => OAI.EditApproximation.naturalEqualWithWork start finish + | state :: rest, finish => + let current := OAI.EditApproximation.naturalEqualWithWork start state.lo + let tail := zeroConnectionWithWork state.hi rest finish + (current.1 && tail.1, current.2 + tail.2 + 1) + +def roundStateWithWork {n : ℕ} (spacing : ℕ) (hspacing : 0 < spacing) + (q : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.TargetInterval n × ℕ := by + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_binaryGridRoundWithWork_value_25 (spacing : ℕ) (position : ℕ) (hspacing : LT.lt.{0} 0 spacing) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryGridRoundWithWork spacing position).1 = OAI.EditApproximation.gridRound spacing position := by + simp only [OAI.EditApproximation.binaryGridRoundWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15, + (proof_binaryNaturalDivModWithWork_spec_24 position spacing hspacing).1, OAI.EditApproximation.gridRound] + have proof_binaryIntervalRoundWithWork_value_14 {n : ℕ} (spacing : ℕ) (hspacing : LT.lt.{0} 0 spacing) (q : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.1, + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi).1.2) = + ((OAI.EditApproximation.roundInterval spacing q).lo, (OAI.EditApproximation.roundInterval spacing q).hi) := by + simp only [OAI.EditApproximation.binaryIntervalRoundWithWork, proof_binaryGridRoundWithWork_value_25 _ _ hspacing, + OAI.EditApproximation.roundInterval] + exact + let output := OAI.EditApproximation.binaryIntervalRoundWithWork spacing q.lo q.hi + let heq := proof_binaryIntervalRoundWithWork_value_14 spacing hspacing q + (⟨OAI.EditApproximation.bitWordValue output.1.1, OAI.EditApproximation.bitWordValue output.1.2, + by exact (congrArg Prod.fst heq).le.trans ((OAI.EditApproximation.roundInterval spacing q).ordered.trans + (congrArg Prod.snd heq).symm.le), + by exact (congrArg Prod.snd heq).le.trans (OAI.EditApproximation.roundInterval spacing q).valid⟩, output.2 + 1) + +def actionEqualWithWork {n M : ℕ} (a b : Fin M → OAI.EditApproximation.TargetInterval n) : Bool × ℕ := + OAI.EditApproximation.allWithWork (fun i => + let left := OAI.EditApproximation.naturalEqualWithWork (a i).lo (b i).lo + let right := OAI.EditApproximation.naturalEqualWithWork (a i).hi (b i).hi + (left.1 && right.1, left.2 + right.2 + 1)) (List.finRange M) + +def localRefinementRepresentatives {n : ℕ} (N P F : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (initial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * initial q)).flatMap fun b => + ((OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈initial q⌉₊ q).filter fun r => decide + ((b : ℚ) / (4 * a) ≤ initial r ∧ initial r ≤ 8 * F * b)).map fun r => (b, r) + +def sharedBandRationalAction {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalRationalAction M ny := + ⟨center, 0, fun i => (i, states i)⟩ + +def localGroupQueryKeys {n : ℕ} (N F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × (ℕ × ℕ)) := + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells ((2 : ℚ) ^ (-(exponent : ℤ)) * b) ⌈initial q⌉₊ q).map fun cell => (b, cell) + +def rationalWidePrefixCost {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (states : Fin M → OAI.EditApproximation.TargetInterval ny) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalConnectionBudget r.lo ((List.ofFn states).take j) + ((OAI.EditApproximation.balancedCut parent.lo (parent.hi - parent.lo) M j : ℚ) + p) + + ∑ i, if i.val < j then child i (states i) else 0 + +def bandRoundSpacing {ny M : ℕ} (thetaExponent b : ℕ) (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (i : Fin M) : ℕ := + 2 ^ (OAI.EditApproximation.bandEnvelopeExponent b band initial i - thetaExponent).toNat + +def actionMemberWithWork {n M : ℕ} (a : Fin M → OAI.EditApproximation.TargetInterval n) : + List (Fin M → OAI.EditApproximation.TargetInterval n) → Bool × ℕ + | [] => (false, 1) + | b :: rest => + let test := OAI.EditApproximation.actionEqualWithWork a b + let tail := actionMemberWithWork a rest + (test.1 || tail.1, test.2 + tail.2 + 1) + +def wideEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P history : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + representatives.toFinset.biUnion fun br => + Finset.univ.biUnion fun i : Fin M => + (Finset.range history).biUnion fun t => + ((OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).toFinset).image fun r => (i, t, r) + +def queryEarlierRepresentatives {n : ℕ} (N P F exponent : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval n → ℚ) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) := + OAI.EditApproximation.localRefinementRepresentatives N P F a initial q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).flatMap (fun key => + (OAI.EditApproximation.cellRepresentativeStates n P F key.1 a initial ((2 : ℚ) ^ (-(exponent : ℤ))) key.2).map + fun r => (key.1, r)) ++ + (OAI.EditApproximation.dyadicQueryWindow N (initial q) a F).map + fun b => (b, OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q) + +def rationalWidePrefixMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (j : ℕ) (p : ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalWidePrefixCost parent r (actions.head hnonempty) child j p) + (actions.map fun action => OAI.EditApproximation.rationalWidePrefixCost parent r action child j p) + +def roundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (action : Fin M → OAI.EditApproximation.TargetInterval ny) : + Fin M → OAI.EditApproximation.TargetInterval ny := + fun i => OAI.EditApproximation.roundInterval (OAI.EditApproximation.bandRoundSpacing thetaExponent b band initial i) (action i) + +def queryEarlierInputCover {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + Finset (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideEarlierInputCover parent P history (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def canonicalRoundedBandAction {ny M : ℕ} (thetaExponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : band ≠ []) + (initial : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : Fin M → OAI.EditApproximation.TargetInterval ny := + OAI.EditApproximation.roundedBandAction thetaExponent b band initial (band.head hnonempty) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def parameterClogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork (n - 1) + (result.1, result.2 + 2) + +def parameterLogWithWork (n : ℕ) : ℕ × ℕ := + let result := OAI.EditApproximation.inputBitLengthWithWork n + (result.1 - 1, result.2 + 1) + +def parameterRootSearch (n : ℕ) : ℕ → ℕ × ℕ + | 0 => (0, 1) + | k + 1 => if (k + 1) * (k + 1) ≤ n then (k + 1, 3) else + let result := parameterRootSearch n k + (result.1, result.2 + 3) + +def parameterPowerWithWork (a : ℕ) : ℕ → ℕ × ℕ + | 0 => (1, 1) + | k + 1 => let result := parameterPowerWithWork a k + (result.1 * a, result.2 + 2) + +def physicalCoarseInputStorage {M J : ℕ} (source target : List ℕ) + (entry : OAI.EditApproximation.PhysicalEntry M J target.length) : ℕ := + let interval := OAI.EditApproximation.physicalSourceInterval source.length entry.1 + OAI.EditApproximation.coarsePreparedInputStorage source target interval.lo interval.hi entry.2.lo entry.2.hi + +def computedQueryPassWithWork (N pass : ℕ) : (OAI.EditApproximation.BinaryFraction × OAI.EditApproximation.RefinementParameterWords) × ℕ := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + exact + let seed := OAI.EditApproximation.scheduledSeedWordWithWork N pass + let parameters := OAI.EditApproximation.refinementParameterWordsWithWork N pass (OAI.EditApproximation.inputSmallLog N).bits + (by rw [proof_bitWordValue_bits_15]; exact Nat.two_pow_pos _) + ((seed.1, parameters.1), seed.2 + parameters.2 + 2) + +def storedIntegerBits (values : List ℤ) : ℕ := + 1 + (values.map fun z => Nat.size z.natAbs + 2).sum + +def parameterSqrtWithWork (n : ℕ) : ℕ × ℕ := OAI.EditApproximation.parameterRootSearch n n + +def computedQuerySetupWithWork (N : ℕ) := + let parameters := OAI.EditApproximation.vectorMapWithWork (OAI.EditApproximation.computedSeedPassCount N + 1) + (fun i => OAI.EditApproximation.computedQueryPassWithWork N i.val) + let base := OAI.EditApproximation.refinementBaseWithWork (OAI.EditApproximation.inputSmallLog N).bits + ((parameters.1, base.1), parameters.2 + base.2 + 5) + +def integerParametersWithWork (N : ℕ) : OAI.EditApproximation.IntegerParameters × ℕ := + let first := OAI.EditApproximation.parameterClogWithWork (N + 2) + let heightExponent := OAI.EditApproximation.parameterClogWithWork first.1 + let height := OAI.EditApproximation.parameterPowerWithWork 2 heightExponent.1 + let smallExponent := OAI.EditApproximation.parameterClogWithWork (max 1 heightExponent.1) + let small := OAI.EditApproximation.parameterPowerWithWork 2 smallExponent.1 + let logarithm := OAI.EditApproximation.parameterLogWithWork small.1 + let firstRoot := OAI.EditApproximation.parameterSqrtWithWork logarithm.1 + let secondRoot := OAI.EditApproximation.parameterSqrtWithWork firstRoot.1 + let branching := OAI.EditApproximation.parameterPowerWithWork 2 (heightExponent.1 / 20) + let coarseBranching := OAI.EditApproximation.parameterPowerWithWork height.1 secondRoot.1 + let factor := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 4) + let grid := OAI.EditApproximation.parameterPowerWithWork height.1 (secondRoot.1 + 20) + let rounds := OAI.EditApproximation.parameterPowerWithWork 2 ((3 * heightExponent.1 + 3) / 4) + let spacingDenominator := OAI.EditApproximation.parameterPowerWithWork small.1 2 + ({ H := height.1, ell := small.1, p := secondRoot.1, B := coarseBranching.1, + initialFactor := factor.1, M := branching.1, P := grid.1, + T := rounds.1, S := height.1 / spacingDenominator.1 }, + first.2 + heightExponent.2 + height.2 + smallExponent.2 + small.2 + logarithm.2 + + firstRoot.2 + secondRoot.2 + branching.2 + coarseBranching.2 + factor.2 + grid.2 + + rounds.2 + spacingDenominator.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +structure PhysicalTableRequest (M J ny : ℕ) where + pass : ℕ + copy : ℕ + node : OAI.EditApproximation.PhysicalNode M J + index : ℕ + state : OAI.EditApproximation.TargetInterval ny + +deriving DecidableEq + +def rawRefinementCenters {n : ℕ} (N P F : ℕ) (a value : ℚ) (q : OAI.EditApproximation.TargetInterval n) : + List (OAI.EditApproximation.TargetInterval n) := + ((OAI.EditApproximation.dyadicQueryWindow N value a F).flatMap fun b => + OAI.EditApproximation.localTargetStates n (OAI.EditApproximation.seedGridSpacing b P) ⌈value⌉₊ q).eraseDups + +def wideWarmupInputs {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (P : ℕ) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) : List (Fin M × OAI.EditApproximation.TargetInterval ny) := + (representatives.flatMap fun br => (List.finRange M).flatMap fun i => + (OAI.EditApproximation.wideChildStateList parent br.2 br.1 P i).map fun r => (i, r)).eraseDups + +def queryMeanRead {ι : Type u_1} (count : ℕ) (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + .charge (count + 1) (OAI.EditApproximation.BitQuery.collect reader (List.ofFn fun i : Fin count => i) + (fun words => OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words))) + +def physicalNodeCodeWithWork {M J : ℕ} (node : OAI.EditApproximation.PhysicalNode M J) : ℕ × ℕ := + let path := OAI.EditApproximation.treeLayerCodeWithWork M node.1.val node.2 + let power := OAI.EditApproximation.parameterPowerWithWork M J + (path.1 + power.1 * node.1.val, path.2 + power.2 + 3) + +def rationalParametersWithWork (ell : ℕ) : OAI.EditApproximation.RationalParameters × ℕ := + let fourth := OAI.EditApproximation.parameterPowerWithWork ell 4 + let fifth := OAI.EditApproximation.parameterPowerWithWork ell 5 + let tenth := OAI.EditApproximation.parameterPowerWithWork ell 10 + let twentieth := OAI.EditApproximation.parameterPowerWithWork ell 20 + let fortieth := OAI.EditApproximation.parameterPowerWithWork ell 40 + ({ F := ell, initialSlope := 32 * ell, coneSlope := 128 * ell, + delta := 1 / (tenth.1 : ℚ), kappa := 1 / (fourth.1 : ℚ), tau := 1 / (fourth.1 : ℚ), + theta := 1 / (fortieth.1 : ℚ), gamma := 1 / (twentieth.1 : ℚ), eta := fifth.1 }, + fourth.2 + fifth.2 + tenth.2 + twentieth.2 + fortieth.2 + 20) + +def onlineMassWithWork (M P H : ℕ) : ℕ × ℕ := + let width := 40 * P + 2 + let square := OAI.EditApproximation.parameterPowerWithWork width 2 + let dimension := H + M * square.1 + 2 + let rounds := OAI.EditApproximation.parameterPowerWithWork dimension 80 + (rounds.1 * (rounds.1 + 1) / 2, square.2 + rounds.2 + 9) + +def refinementInitialSupport {n : ℕ} (N P F exponent : ℕ) (a value : ℚ) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) := + q :: (OAI.EditApproximation.rawRefinementCenters N P F a value q ++ + (OAI.EditApproximation.localGroupQueryKeys N F exponent a (fun _ => value) q).flatMap (fun key => + OAI.EditApproximation.cellTargetStates n (OAI.EditApproximation.seedGridSpacing key.1 P) + ((2 : ℚ) ^ (-(exponent : ℤ)) * key.1) key.2) ++ + (OAI.EditApproximation.dyadicQueryWindow N value a F).map (fun b => OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q)) + +def refinementBandInputList {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (a : ℚ) (initial : OAI.EditApproximation.TargetInterval ny → ℚ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) := + OAI.EditApproximation.wideWarmupInputs parent P (OAI.EditApproximation.queryEarlierRepresentatives N P F exponent a initial q) + +def previousPassRequest {M J ny : ℕ} (T S copy : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (state : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨parent.pass - 1, copy, parent.node, T + S, state⟩ + +def physicalEntryCodeWithWork {M J n : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J n) : ℕ × ℕ := + let node := OAI.EditApproximation.physicalNodeCodeWithWork entry.1 + let width := n + 1 + (entry.2.lo + width * entry.2.hi + width * width * node.1, node.2 + 8) + +def queryPhysicalBoundedWithWork {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : Bool × ℕ := + let pass := OAI.EditApproximation.binaryNaturalCompareWithWork request.pass passes + let copy := OAI.EditApproximation.binaryNaturalCompareWithWork request.copy copies + let cap := OAI.EditApproximation.binaryNaturalAddWithWork T S + let index := OAI.EditApproximation.wordLEWithWork request.index.bits cap.1 + (decide (pass.1 = .lt) && decide (copy.1 = .lt) && index.1, + pass.2 + copy.2 + cap.2 + index.2 + 4) + +def globalParameterWork (N : ℕ) : ℕ := + (OAI.EditApproximation.integerParametersWithWork N).2 + (OAI.EditApproximation.rationalParametersWithWork (OAI.EditApproximation.inputSmallLog N)).2 + + (OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)).2 + +def physicalLargeInputWithWork (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Bool × ℕ := + let inspected := OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon + if inspected.1.isSome = true then + let product := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.inputSmallLog N)) epsilon + let accuracy := OAI.EditApproximation.BinaryFraction.ltWithWork product.1 (OAI.EditApproximation.BinaryFraction.nat 10) + let threshold := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputSmallLog N) (2 ^ 1000) + let mass := OAI.EditApproximation.onlineMassWithWork (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + let width := OAI.EditApproximation.inputBitLengthWithWork mass.1 + let capacity := OAI.EditApproximation.binaryNaturalCompareWithWork (OAI.EditApproximation.inputHeight N) width.1 + (decide (threshold.1 ≠ .lt ∧ accuracy.1 ≠ true ∧ capacity.1 ≠ .lt), + inspected.2 + product.2 + accuracy.2 + threshold.2 + mass.2 + width.2 + capacity.2 + 10) + else (false, inspected.2 + 1) + +def physicalTableCodeAllocation {M J n : ℕ} (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + 2 * request.node.1.val + 2 * J + 20 + +def queryPhysicalBoundedAllocation {M J n : ℕ} (passes copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.pass.bits.length + passes.bits.length + request.copy.bits.length + copies.bits.length + + OAI.EditApproximation.binaryNaturalAddAllocation T S + OAI.EditApproximation.naturalWordLEAllocation request.index.bits (OAI.EditApproximation.binaryNaturalAddWithWork T S).1 + +def physicalTableCodeWithWork {M J n : ℕ} (copies T S : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ × ℕ := + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (request.node, request.state) + let power := OAI.EditApproximation.parameterPowerWithWork M J + let capacity := (n + 1) * (n + 1) * (power.1 * (J + 1)) + (request.index + (T + S + 1) * (request.copy + copies * (entry.1 + capacity * request.pass)), + entry.2 + power.2 + 15) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest +variable {M J ny : ℕ} + +def remainingDepth (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + J - request.node.1.val + +def rank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.pass * (T + S + 1) + request.index + +def Bounded (passes copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : Prop := + request.pass < passes ∧ request.copy < copies ∧ request.index ≤ T + S + +def warmup (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (j : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, j, state⟩ + +def refinement (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (T t : ℕ) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + ⟨pass, copy, node, T + t, state⟩ + +def sameIndexChild (request : OAI.EditApproximation.PhysicalTableRequest M J ny) + (hbelow : request.node.1.val < J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest M J ny := + { request with node := OAI.EditApproximation.physicalChild request.node hbelow i, state := state } + +def combinedRank (T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) : ℕ := + request.remainingDepth + request.rank T S + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalWarmupChildQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node (t + 1) q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) t input.2, + by simpa only [Nat.add_sub_cancel] using + proof_combinedRank_warmup_child_79 pass copy T S (t + 1) + node hbelow input.1 q input.2 (Nat.zero_lt_succ t)⟩ .done + +def physicalRefinementCurrentQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ .done + +def physicalRefinementEarlierQuery {M J ny : ℕ} (pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + exact + if hs : input.2.1 < t then + .read ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 hs).2⟩)⟩ .done + else .done 0 + +def physicalRefinementWarmupRead {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval ny) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + .read ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ .done + +def previousPassRead {M J ny : ℕ} (T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) + (state : OAI.EditApproximation.TargetInterval ny) (copy : ℕ) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨OAI.EditApproximation.previousPassRequest T S copy parent state, + proof_combinedRank_lt_of_progress_80 T S parent _ (Or.inr + ⟨(proof_previousPassRequest_progress_97 T S copy parent hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy parent hpass state).2⟩)⟩ .done + +abbrev ChargedPhysicalRequest (M J ny passes copies T S : ℕ) := + Sum (OAI.EditApproximation.PhysicalEntry M J ny) + {request : OAI.EditApproximation.PhysicalTableRequest M J ny // request.Bounded passes copies T S} + +def chargedPreviousPass {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S} := + ⟨OAI.EditApproximation.previousPassRequest T S copy.val parent.val state, + Nat.lt_of_le_of_lt (Nat.sub_le _ _) parent.property.1, copy.isLt, le_rfl⟩ + +def queryPhysicalTableRead {M J n : ℕ} (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S}) : + OAI.EditApproximation.BitQuery {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.combinedRank T S < parent.combinedRank T S} + OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalTableCodeWithWork copies T S child.val).2 + 1) (.read child .done) + +abbrev ComputedFamilyTableKey (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ChargedPhysicalRequest (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length + (OAI.EditApproximation.computedSeedPassCount N + 1) (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + +def chargedPhysicalCodeWithWork {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ × ℕ + | .inl entry => let result := OAI.EditApproximation.physicalEntryCodeWithWork entry + (2 * result.1, result.2 + 2) + | .inr request => let result := OAI.EditApproximation.physicalTableCodeWithWork copies T S request.val + (2 * result.1 + 1, result.2 + 3) + +def queryPhysicalWarmupRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval n) + (otherNode : OAI.EditApproximation.PhysicalNode M J) (hnode : node.1.val ≤ otherNode.1.val) + (j : ℕ) (hj : j ≤ T) (r : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.warmup pass copy otherNode j r, by + apply proof_combinedRank_lt_of_progress_80 T S _ _ + apply Or.inr + constructor + · exact Nat.sub_le_sub_left hnode J + · change pass * (T + S + 1) + j < pass * (T + S + 1) + (T + t) + omega⟩ + +def queryPhysicalCurrentRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + exact + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T t input.2, + proof_combinedRank_sameIndexChild_94 T S + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) hbelow input.1 input.2⟩ + +def queryPhysicalEarlierRead {M J n : ℕ} (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).2 + 1) + (if hs : (OAI.EditApproximation.binaryNaturalCompareWithWork input.2.1 t).1 = .lt then + OAI.EditApproximation.queryPhysicalTableRead copies T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q) + ⟨OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow input.1) T input.2.1 input.2.2, + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).1.le, + (proof_refinement_history_child_progress_96 pass copy T S t input.2.1 + node hbelow input.1 q input.2.2 ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hs)).2⟩)⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + +def chargedPhysicalRemaining {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.remainingDepth + +def chargedPhysicalCodeAllocation {M J n passes copies T S : ℕ} : + OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S → ℕ + | .inl entry => 2 * entry.1.1.val + J + 12 + | .inr request => OAI.EditApproximation.physicalTableCodeAllocation request.val + 2 + +def queryPhysicalMassRead {M J n : ℕ} (copies pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.PhysicalTableRequest M J n // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryMeanRead T (fun j => OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val j.isLt.le input.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def integerClosedRange (lo hi : ℤ) : List ℤ := + (List.range (hi - lo + 1).toNat).map fun i : ℕ => lo + (i : ℤ) + +def groupSampleCount (M Q b : ℕ) (h : ℚ) : ℕ := min M ⌈(Q : ℚ) * M * h / b⌉₊ + +def groupScaleTrueCost {M : ℕ} (h : ℚ) (envelope value : Fin M → ℚ) : ℚ := + ∑ i, if envelope i = h then value i else 0 + +def selectGroupMember {ι : Type u_1} (members : List ι) (hnonempty : members ≠ []) + (estimate : ι → ℚ) : ι := + (members.argmax fun member => -estimate member).getD (members.head hnonempty) + +instance coarseDrawsMeasurableSpace (B D : ℕ) [MeasurableSpace (Fin B)] : + MeasurableSpace (OAI.EditApproximation.CoarseThresholdDraws B D) := by + induction D with + | zero => exact inferInstanceAs (MeasurableSpace PUnit) + | succ D ih => + letI := ih + exact inferInstanceAs + (MeasurableSpace ((Fin B → Fin B) × (Fin B → OAI.EditApproximation.CoarseThresholdDraws B D))) + +def groupDyadicScales (M b : ℕ) (F : ℚ) : List ℚ := + (OAI.EditApproximation.integerClosedRange (Int.clog 2 ((b : ℚ) / M)) (Int.log 2 (64 * F * b))).map + fun exponent => (2 : ℚ) ^ exponent + +def groupScaleEstimate {M : ℕ} (k : ℕ) (h : ℚ) (envelope value : Fin M → ℚ) + (draw : Fin k → Fin M) : ℚ := + if k = M then OAI.EditApproximation.groupScaleTrueCost h envelope value + else (M : ℚ) / k * ∑ j, if envelope (draw j) = h then value (draw j) else 0 + +noncomputable def coarseDrawMeasure (B : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + (D : ℕ) → Measure (OAI.EditApproximation.CoarseThresholdDraws B D) + | 0 => Measure.dirac PUnit.unit + | D + 1 => + (Measure.pi fun _ : Fin B => (PMF.uniformOfFintype (Fin B)).toMeasure).prod + (Measure.pi fun _ : Fin B => coarseDrawMeasure B D) + +def groupMemberEstimate {M T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (connection : ℚ) (envelope value : Fin M → ℚ) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + connection + ∑ scale, OAI.EditApproximation.groupScaleEstimate (count scale) (scales scale) envelope value (draw scale) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScalesWithWork (eM eb eF : ℕ) : List OAI.EditApproximation.BinaryFraction × ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + let values := OAI.EditApproximation.arithmeticMapWithWork OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork exponents + (values.1, values.2 + exponents.length + Nat.size eM + Nat.size eb + Nat.size eF + 8) + +def bandPredicateReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (r : OAI.EditApproximation.TargetInterval ny) + (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Bool × ℕ := + let connection := OAI.EditApproximation.zeroConnectionWithWork r.lo (List.ofFn states) r.hi + let anchors := OAI.EditApproximation.allWithWork (fun i : Fin M => + let leftAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).lo + let rightAnchor := OAI.EditApproximation.translatedEndpointWithWork r.lo parent.lo (OAI.EditApproximation.sourceChild parent i).hi + let radius := OAI.EditApproximation.binaryNaturalMulWithWork 6 b + let left := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork leftAnchor.1 (states i).lo (OAI.EditApproximation.bitWordValue radius.1) + let right := OAI.EditApproximation.BinaryFraction.naturalDistanceLeWithWork rightAnchor.1 (states i).hi (OAI.EditApproximation.bitWordValue radius.1) + (left.1 && right.1, leftAnchor.2 + rightAnchor.2 + radius.2 + left.2 + right.2 + 3)) (List.finRange M) + let tolerance := OAI.EditApproximation.BinaryFraction.bandToleranceWithWork tau theta b M + let cuts := OAI.EditApproximation.allWithWork (OAI.EditApproximation.BinaryFraction.cutGuardReadWithWork parent r actions hne read states velocity tolerance.1) + (List.finRange M) + (connection.1 && anchors.1 && cuts.1, connection.2 + anchors.2 + tolerance.2 + cuts.2 + 4) + +def indexedGroupScales (raw : List OAI.EditApproximation.BinaryFraction) (M b : ℕ) (F : ℚ) + (h : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) : + Fin (OAI.EditApproximation.groupDyadicScales M b F).length → OAI.EditApproximation.BinaryFraction := + fun i => raw.get ⟨i.val, by + have hlen := congrArg List.length h + simp only [List.length_map] at hlen + omega⟩ + +def queryOnlineKeysWithWork {n : ℕ} (N P F : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let scales := OAI.EditApproximation.BinaryFraction.queryScalesWithWork N F a value + let keys := OAI.EditApproximation.arithmeticMapWithWork (fun b => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) q + ((b, center.1), spacing.2 + center.2 + 2)) scales.1 + (keys.1, scales.2 + keys.2 + 1) + +def groupScalesAllocation (eM eb eF : ℕ) : ℕ := + let exponents := OAI.EditApproximation.integerClosedRange ((eb : ℤ) - eM) ((6 + eF + eb : ℕ) : ℤ) + OAI.EditApproximation.arithmeticMapAllocation OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation exponents + exponents.length + + Nat.size eM + Nat.size eb + Nat.size eF + +def bandFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : + List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let margin := OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau + let guard := OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin.1 + if guard.1 then + let filtered := OAI.EditApproximation.filterWithWork + (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) actions + (filtered.1, margin.2 + guard.2 + filtered.2 + 2) + else ([], margin.2 + guard.2 + 1) + +def queryInitialSupportWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.TargetInterval n) × ℕ := + let raw := OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q + let onlineStates := OAI.EditApproximation.arithmeticMapWithWork (fun key => (key.2, 1)) online.1 + (q :: (raw.1 ++ cells.1 ++ onlineStates.1), + raw.2 + groups.2 + cells.2 + online.2 + onlineStates.2 + 2 * raw.1.length + cells.1.length + 5) + +def queryEarlierRepresentativesWithWork {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (q : OAI.EditApproximation.TargetInterval n) : List (ℕ × OAI.EditApproximation.TargetInterval n) × ℕ := + let query := initial q + let reps := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial q + let groups := OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a query.1 q + let cells := OAI.EditApproximation.arithmeticFlatMapWithWork (fun key => + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F key.1 a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) initial key.2 + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((key.1, r), 1)) centers.1 + (labeled.1, centers.2 + labeled.2 + 1)) groups.1 + let online := OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q + (reps.1 ++ cells.1 ++ online.1, + query.2 + reps.2 + groups.2 + cells.2 + online.2 + 2 * reps.1.length + cells.1.length + 4) + +def bandFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : actions ≠ []) : ℕ := + let margin := (OAI.EditApproximation.BinaryFraction.subWithWork OAI.EditApproximation.BinaryFraction.one tau).1 + OAI.EditApproximation.BinaryFraction.subAllocation OAI.EditApproximation.BinaryFraction.one tau + OAI.EditApproximation.BinaryFraction.leAllocation velocity.absolute margin + + if (OAI.EditApproximation.BinaryFraction.leWithWork velocity.absolute margin).1 then + OAI.EditApproximation.filterAllocation (OAI.EditApproximation.BinaryFraction.bandPredicateReadWithWork parent r b tau theta velocity actions hne read) + (OAI.EditApproximation.BinaryFraction.bandPredicateReadAllocation parent r b tau theta velocity actions hne read allocation) actions + else 0 + +def queryInitialSupportAllocation {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let raw := (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q).1 + let groups := (OAI.EditApproximation.BinaryFraction.queryGroupKeysWithWork N F exponent a value q).1 + let build := fun key => + let spacing := OAI.EditApproximation.seedGridSpacingWithWork key.1 P + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat key.1) + let states := OAI.EditApproximation.BinaryFraction.cellStatesWithWork n (OAI.EditApproximation.bitWordValue spacing.1) side.1 key.2 + (states.1, spacing.2 + side.2 + states.2 + exponent + 3) + let cells := (OAI.EditApproximation.arithmeticFlatMapWithWork build groups).1 + let online := (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a value q).1 + OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q + OAI.EditApproximation.BinaryFraction.queryGroupKeysAllocation N F exponent a value q + + OAI.EditApproximation.arithmeticFlatMapAllocation build (OAI.EditApproximation.BinaryFraction.initialCellAllocation n P exponent) groups + + OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a value q + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) online + + 2 * raw.length + cells.length + 1 + +def queryBandInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let inputs := OAI.EditApproximation.BinaryFraction.queryWideInputsWithWork M parent P representatives.1 + (inputs.1, representatives.2 + inputs.2 + 1) + +def queryEarlierInputsWithWork {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) : + List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny) × ℕ := + let representatives := OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q + let raw := OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history representatives.1 + let ordered := OAI.EditApproximation.queryOrderedHistoryInputsWithWork raw.1 + (ordered.1, representatives.2 + raw.2 + ordered.2 + 2) + +def queryEarlierInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent history : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + let reps := (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsAllocation M parent P history reps + + OAI.EditApproximation.queryOrderedHistoryInputsAllocation (OAI.EditApproximation.BinaryFraction.queryRawHistoryInputsWithWork M parent P history reps).1 + +def queryBandInputsAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesAllocation N P F exponent hP a initial allocation q + + OAI.EditApproximation.BinaryFraction.queryWideInputsAllocation M parent P (OAI.EditApproximation.BinaryFraction.queryEarlierRepresentativesWithWork N P F exponent hP a initial q).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.FiniteQuery + + +def run {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) : + OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ + | .done result, memory => ⟨result, memory, [], 0, 0⟩ + | .read key next, memory => + let first := ask key memory + let rest := run ask (next first.value) first.memory + ⟨rest.value, rest.memory, first.freshKeys ++ rest.freshKeys, + first.dictionaryVisits + rest.dictionaryVisits, first.requests + rest.requests⟩ + +def bind {ι : Type u_1} : OAI.EditApproximation.FiniteQuery ι → (ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | .done result, next => next result + | .read key continuation, next => .read key (fun result => bind (continuation result) next) + +def mapKeys {ι : Type u_1} {κ : Type u_2} (f : ι → κ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery κ + | .done result => .done result + | .read key next => .read (f key) (fun answer => mapKeys f (next answer)) + +def restrict {ι : Type u_1} (P : ι → Prop) [DecidablePred P] : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.FiniteQuery {key // P key} + | .done result => .done result + | .read key next => if h : P key then + .read ⟨key, h⟩ (fun answer => restrict P (next answer)) + else restrict P (next 0) + +def requestWork {ι : Type u_1} {κ : Type u_2} (ask : ι → OAI.EditApproximation.BinaryMemo ℚ → OAI.EditApproximation.RecursiveMemoResult κ) + (cost : ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ) : OAI.EditApproximation.FiniteQuery ι → OAI.EditApproximation.BinaryMemo ℚ → ℕ + | .done _, _ => 0 + | .read key next, memory => + let first := ask key memory + cost key memory + requestWork ask cost (next first.value) first.memory + +def collect {ι : Type u_1} {κ : Type u_2} (reader : κ → OAI.EditApproximation.FiniteQuery ι) : + List κ → (List ℚ → OAI.EditApproximation.FiniteQuery ι) → OAI.EditApproximation.FiniteQuery ι + | [], next => next [] + | key :: keys, next => OAI.EditApproximation.FiniteQuery.bind (reader key) fun result => + collect reader keys (fun results => next (result :: results)) + + +end OAI.EditApproximation.FiniteQuery +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def physicalInitialQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (state : OAI.EditApproximation.PhysicalEntry M J target.length) : OAI.EditApproximation.FiniteQuery ι := + let piece := OAI.EditApproximation.physicalSource source state.1 + if piece.length ≤ 1 then .done (OAI.EditApproximation.shortSourceCost piece (OAI.EditApproximation.substring target state.2.lo state.2.hi)) + else OAI.EditApproximation.FiniteQuery.bind (seedRead state) fun answer => + let value := ⌈answer⌉₊ + let keys := OAI.EditApproximation.rawInitialConeCenters N P A value state.2 + OAI.EditApproximation.FiniteQuery.collect (fun q => seedRead (state.1, q)) keys fun answers => + let localTable := fun q => if q = state.2 then value + else ⌈OAI.EditApproximation.finiteAnswerTable keys answers q⌉₊ + .done (OAI.EditApproximation.localInitialConeTable piece target localTable N P F A (OAI.EditApproximation.refinementFactor A F) state.2) + +def queryInitialGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (N P F exponent : ℕ) (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.TargetInterval n) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys) + +def queryBandGather {ι : Type u_1} {β : Type u_2} {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) (hP : 0 < P) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : (Fin M × OAI.EditApproximation.TargetInterval ny) → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → List OAI.EditApproximation.BinaryFraction → + OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect massReader keys fun mass => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass) + +def physicalRefinementMassQuery {M J ny : ℕ} (pass copy T S t : ℕ) (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : node.1.val < J) (q : OAI.EditApproximation.TargetInterval ny) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun j : Fin T => OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + j.val (Nat.le_of_lt j.isLt) input.2) (List.ofFn fun j : Fin T => j) + (fun values => .done (values.sum / T)) + +def physicalMedianSeedQuery {M J ny : ℕ} (N T S copies multiplier : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : 0 < parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + OAI.EditApproximation.FiniteQuery.collect (fun copy : Fin copies => OAI.EditApproximation.previousPassRead T S parent hpass state copy.val) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => ⌈(multiplier : ℚ) * value⌉₊)) : ℕ) + +def globalSeedRead {M J ny : ℕ} (N T S copies : ℕ) (multiplier : ℕ → ℕ) + (initial : OAI.EditApproximation.PhysicalEntry M J ny → ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J ny // + child.combinedRank T S < parent.combinedRank T S} := + if state.1 = parent.node then + if hp : parent.pass = 0 then .done (initial state : ℚ) + else OAI.EditApproximation.physicalMedianSeedQuery N T S copies (multiplier (parent.pass - 1)) parent + (Nat.pos_of_ne_zero hp) state.2 + else .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational + + +def value (a : OAI.EditApproximation.UnreducedRational) : ℚ := (a.num : ℚ) / a.den + +def zero : OAI.EditApproximation.UnreducedRational := ⟨0, 1, by decide⟩ + +def mul (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + ⟨a.num * b.num, a.den * b.den, Nat.mul_pos a.den_pos b.den_pos⟩ + +def lt (a b : OAI.EditApproximation.UnreducedRational) : Bool := decide (a.num * b.den < b.num * a.den) + +def inv (a : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := + if h : a.num = 0 then OAI.EditApproximation.UnreducedRational.zero else + ⟨a.num.sign * a.den, a.num.natAbs, Int.natAbs_pos.mpr h⟩ + +def div (a b : OAI.EditApproximation.UnreducedRational) : OAI.EditApproximation.UnreducedRational := a.mul b.inv + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +inductive CoarseSourceTree (B : ℕ) (α : Type u) : ℕ → Type u + | leaf (letter : Option α) : CoarseSourceTree B α 0 + | branch {D : ℕ} (children : Fin B → CoarseSourceTree B α D) : CoarseSourceTree B α (D + 1) + +def coarseTargetFrame {α : Type u} (k : ℕ) (target : List α) : List (Option α) := + (List.replicate k none ++ target.map some) ++ List.replicate k none + +def coarseRootShift (k : ℕ) : Fin (2 * k + 1) := ⟨k, by omega⟩ + +def endpointActionConnection {n M : ℕ} (q : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.connectionBudget q.lo (List.ofFn states) q.hi + +def coarseSourceTreeOfList (B : ℕ) {α : Type u} : + (D : ℕ) → List α → OAI.EditApproximation.CoarseSourceTree B α D + | 0, source => .leaf source.head? + | D + 1, source => .branch (fun i => + coarseSourceTreeOfList B D ((source.drop (i.val * B ^ D)).take (B ^ D))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open Finset + +def groupIndexWithWork {M : ℕ} (h : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (indices : List (Fin M)) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.BinaryFraction.groupTermsWithWork h envelope values indices + let total := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + (total.1, terms.2 + total.2 + 1) + +def endpointDistanceWithWork {n : ℕ} (q r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let left := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.lo) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let right := OAI.EditApproximation.BinaryFraction.distanceWithWork (OAI.EditApproximation.BinaryFraction.nat q.hi) (OAI.EditApproximation.BinaryFraction.nat r.hi) + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork left.1 right.1 + (result.1, left.2 + right.2 + result.2 + Nat.size q.lo + Nat.size q.hi + + Nat.size r.lo + Nat.size r.hi + 3) + +def endpointConnectionWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (states : Fin M → OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.BinaryFraction.connectionWithWork (OAI.EditApproximation.BinaryFraction.nat r.lo) (OAI.EditApproximation.BinaryFraction.nat r.hi) (List.ofFn states) + (result.1, result.2 + Nat.size r.lo + Nat.size r.hi + M + 2) + +def stateGapWithWork {n : ℕ} (sourceLength : ℕ) (r : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let targetLength := OAI.EditApproximation.BinaryFraction.subWithWork (OAI.EditApproximation.BinaryFraction.nat r.hi) (OAI.EditApproximation.BinaryFraction.nat r.lo) + let result := OAI.EditApproximation.BinaryFraction.subWithWork targetLength.1 (OAI.EditApproximation.BinaryFraction.nat sourceLength) + (result.1, targetLength.2 + result.2 + Nat.size r.hi + Nat.size r.lo + Nat.size sourceLength + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def groupScaleSourceWithWork {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let subtotal := OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1 + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + let result := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork factor.1 subtotal.1 + (result.1, indices.2 + subtotal.2 + factor.2 + result.2 + Nat.size M + Nat.size k + 3) + +def endpointScoreReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BinaryFraction × ℕ := + let words := OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states + let children := OAI.EditApproximation.BinaryFraction.sumListWithWork words.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection.1 children.1 + (result.1, words.2 + connection.2 + children.2 + result.2 + 2) + +def initialConeWithWork {n : ℕ} (sourceLength : ℕ) (U : OAI.EditApproximation.TargetInterval n → ℕ) + (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center + let seed := OAI.EditApproximation.BinaryFraction.scaledSeedWithWork (U center) a gap.1 + let distance := OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center + let spatial := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork seed.1 spatial.1 + (result.1, gap.2 + seed.2 + distance.2 + spatial.2 + result.2 + 4) + +def endpointActionWithWork {ny M : ℕ} (center : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork center states + (⟨center, connection.1, fun i => (i, states i)⟩, connection.2 + M + 1) + +def endpointScoreReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) (states : Fin M → OAI.EditApproximation.TargetInterval n) : ℕ := + let words := (OAI.EditApproximation.arithmeticMapWithWork (fun i => read i (states i)) (List.finRange M)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun i => footprint i (states i)) (List.finRange M) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation r states + OAI.EditApproximation.BinaryFraction.sumListAllocation words + + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork r states).1 (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1 + 0 + +def initialConeAllocation {n : ℕ} (sourceLength U : ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength center).1 + let seed := (OAI.EditApproximation.BinaryFraction.scaledSeedWithWork U a gap).1 + let distance := (OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork query center).1 + let spatial := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork L distance).1 + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength center + OAI.EditApproximation.BinaryFraction.scaledSeedAllocation U a gap + + OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation query center + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation L distance + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation seed spatial + +def groupScaleSourceAllocation {M : ℕ} (k : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (envelope values : Vector OAI.EditApproximation.BinaryFraction M) (draw : Fin k → Fin M × ℕ) + (allocation : Fin k → ℕ) : ℕ := + let indices := if k = M then (List.finRange M, 0) else OAI.EditApproximation.arithmeticMapWithWork draw (List.finRange k) + let factor := if k = M then (OAI.EditApproximation.BinaryFraction.one, 1) else OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k) + (if k = M then 0 else OAI.EditApproximation.arithmeticMapAllocation allocation (List.finRange k)) + + OAI.EditApproximation.BinaryFraction.groupIndexAllocation h envelope values indices.1 + + (if k = M then 0 else OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.nat M) (OAI.EditApproximation.BinaryFraction.nat k)) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation factor.1 (OAI.EditApproximation.BinaryFraction.groupIndexWithWork h envelope values indices.1).1 + + Nat.size M + Nat.size k + +def gapGuardAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (envelope : Vector OAI.EditApproximation.BinaryFraction M) (rounded : Vector (OAI.EditApproximation.TargetInterval ny) M) (i : Fin M) : ℕ := + let sourceLength := (OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo).1 + let gap := (OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i)).1 + let bound := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i)).1 + OAI.EditApproximation.bitSubtractAllocation (OAI.EditApproximation.sourceChild parent i).hi.bits (OAI.EditApproximation.sourceChild parent i).lo.bits false + + OAI.EditApproximation.BinaryFraction.stateGapAllocation (OAI.EditApproximation.bitWordValue sourceLength) (rounded.get i) + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.get i) + OAI.EditApproximation.BinaryFraction.leAllocation gap.absolute bound + +def wideMinimumReadWithWork {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, fallback.2 + scores.2 + result.2 + 2) + +def groupMemberSourceWithWork {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let terms := OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T) + let subtotal := OAI.EditApproximation.BinaryFraction.sumListWithWork terms.1 + let result := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork connection subtotal.1 + (result.1, terms.2 + subtotal.2 + result.2 + 1) + +def wideActionsFromRepresentativesWithWork {nx ny : ℕ} (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) × ℕ := + OAI.EditApproximation.arithmeticFlatMapWithWork (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) representatives + +def initialConeReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (a L : OAI.EditApproximation.BinaryFraction) + (query center : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let seed := read center + let result := OAI.EditApproximation.BinaryFraction.initialConeWithWork sourceLength (fun _ => OAI.EditApproximation.bitWordValue seed.1) a L query center + (result.1, seed.2 + result.2) + +def wideMinimumReadAllocation {n M : ℕ} (r : OAI.EditApproximation.TargetInterval n) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : actions ≠ []) : ℕ := + let fallback := (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read (actions.head hne)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.endpointScoreReadWithWork r read) actions).1 + OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint (actions.head hne) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.endpointScoreReadAllocation r read footprint) actions + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + 0 + +def groupMemberSourceAllocation {M T : ℕ} (scales : Fin T → OAI.EditApproximation.BinaryFraction) (count : Fin T → ℕ) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ s : Fin T, Fin (count s) → Fin M × ℕ) + (allocation : ∀ s : Fin T, Fin (count s) → ℕ) : ℕ := + let terms := (OAI.EditApproximation.arithmeticMapWithWork (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceWithWork (count s) (scales s) + envelope values (draw s)) (List.finRange T)).1 + OAI.EditApproximation.arithmeticMapAllocation (fun s => OAI.EditApproximation.BinaryFraction.groupScaleSourceAllocation (count s) (scales s) envelope values (draw s) (allocation s)) (List.finRange T) + + OAI.EditApproximation.BinaryFraction.sumListAllocation terms + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation connection (OAI.EditApproximation.BinaryFraction.sumListWithWork terms).1 + +def wideActionsFromRepresentativesAllocation {nx ny : ℕ} (M : ℕ) (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : ℕ := + OAI.EditApproximation.arithmeticFlatMapAllocation (fun br => + let grids := OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P + let actions := OAI.EditApproximation.arithmeticMapWithWork (fun states => OAI.EditApproximation.BinaryFraction.endpointActionWithWork br.2 states.get) grids.1 + (actions.1, grids.2 + actions.2 + 1)) + (fun br => OAI.EditApproximation.wideActionGridAllocation M parent br.2 br.1 P + + OAI.EditApproximation.arithmeticMapAllocation (fun states => OAI.EditApproximation.BinaryFraction.endpointActionAllocation br.2 states.get) + (OAI.EditApproximation.wideActionGridWithWork M parent br.2 br.1 P).1) representatives + +def representativeFromActionsReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + if hne : actions = [] then ([], 1) else + let Z := OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne + let positive := OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z.1 + if positive.1 then + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r + let velocity := OAI.EditApproximation.BinaryFraction.divWithWork gap.1 Z.1 + let result := OAI.EditApproximation.BinaryFraction.bandFromActionsReadWithWork parent r b tau theta velocity.1 read actions hne + (result.1, Z.2 + positive.2 + gap.2 + velocity.2 + result.2 + 3) + else ([], Z.2 + positive.2 + 2) + +def physicalContinuationReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) + (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : OAI.EditApproximation.BinaryFraction × ℕ := + let wide := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.localContinuationReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 delta fallback + old current query wide.1 groups online + (result.1, wide.2 + L.2 + result.2 + 1) + +def initialMinimumReadWithWork {n : ℕ} (sourceLength : ℕ) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : OAI.EditApproximation.BinaryFraction × ℕ := + let queryWord := read query + let zeroTest := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue queryWord.1) 0 + if zeroTest.1 then (OAI.EditApproximation.BinaryFraction.zero, queryWord.2 + zeroTest.2 + 1) else + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + let coefficient := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L.1 OAI.EditApproximation.BinaryFraction.one + let fallback := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient.1 (OAI.EditApproximation.BinaryFraction.nat N) + let scores := OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L.1 query) centers + let result := OAI.EditApproximation.BinaryFraction.minimumWithWork fallback.1 scores.1 + (result.1, queryWord.2 + zeroTest.2 + L.2 + coefficient.2 + fallback.2 + scores.2 + result.2 + + Nat.size F + Nat.size N + 6) + +def localWarmupReadKernelWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (query : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let actions := OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives.1 P + let L := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + let result := OAI.EditApproximation.BinaryFraction.bellmanReadWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork L.1 fallback.1 child query actions.1 + (result.1, fallback.2 + representatives.2 + actions.2 + L.2 + result.2 + 3) + +def representativeFromActionsReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (sourceLength b : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) : ℕ := + if hne : actions = [] then 0 else + let Z := (OAI.EditApproximation.BinaryFraction.wideMinimumReadWithWork r read actions hne).1 + OAI.EditApproximation.BinaryFraction.wideMinimumReadAllocation r read allocation actions hne + OAI.EditApproximation.BinaryFraction.ltAllocation OAI.EditApproximation.BinaryFraction.zero Z + + if (OAI.EditApproximation.BinaryFraction.ltWithWork OAI.EditApproximation.BinaryFraction.zero Z).1 then + OAI.EditApproximation.BinaryFraction.stateGapAllocation sourceLength r + OAI.EditApproximation.BinaryFraction.divAllocation (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z + + OAI.EditApproximation.BinaryFraction.bandFromActionsReadAllocation parent r b tau theta + (OAI.EditApproximation.BinaryFraction.divWithWork (OAI.EditApproximation.BinaryFraction.stateGapWithWork sourceLength r).1 Z).1 read allocation actions hne + else 0 + +def physicalContinuationReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P F : ℕ) (delta fallback : OAI.EditApproximation.BinaryFraction) + (old current : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (oldAllocation currentAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.localContinuationReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 delta fallback old current oldAllocation currentAllocation query + (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 groups online + +def localWarmupReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (child : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M × OAI.EditApproximation.TargetInterval ny → ℕ) (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + let representatives := (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 + let actions := (OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesWithWork M parent representatives P).1 + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.wideActionsFromRepresentativesAllocation M parent representatives P + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F) + + OAI.EditApproximation.BinaryFraction.bellmanReadAllocation OAI.EditApproximation.BinaryFraction.endpointDistanceWithWork OAI.EditApproximation.BinaryFraction.endpointDistanceAllocation + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 128) (OAI.EditApproximation.BinaryFraction.nat F)).1 (initial query).1 child childAllocation query actions + +def preparedRepresentativeReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) × ℕ := + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let result := OAI.EditApproximation.BinaryFraction.representativeFromActionsReadWithWork parent center sourceLength b tau theta read + (wide.1.map Vector.get) + (result.1, wide.2 + result.2 + wide.1.length + 1) + +def initialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + let centers := OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query + let result := OAI.EditApproximation.BinaryFraction.initialMinimumReadWithWork sourceLength read N F a query centers.1 + (result.1, centers.2 + result.2 + 1) + +def preparedRepresentativeReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (sourceLength b P : ℕ) (tau theta : OAI.EditApproximation.BinaryFraction) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.representativeFromActionsReadAllocation parent center sourceLength b tau theta read allocation (wide.map Vector.get) + +def queryRefinementFinishAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (N P F : ℕ) + (a delta : OAI.EditApproximation.BinaryFraction) (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) (t : ℕ) + (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval ny)) (earlierWords : List OAI.EditApproximation.BinaryFraction) + (groups online : List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M)) + (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) (currentWords : List OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval ny) : ℕ := + initialAllocation query + OAI.EditApproximation.BinaryFraction.localRepresentativeReadAllocation N P F a initial initialAllocation query + + OAI.EditApproximation.BinaryFraction.physicalContinuationReadAllocation parent (OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query).1 P F delta (initial query).1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadAllocation currentKeys currentWords input.1 input.2) groups online query + +def queryOnlineRangeWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ × ℕ := + let width := OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width.1) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let power := OAI.EditApproximation.bitPowerWithWork setup.1.bits 80 + let mass := OAI.EditApproximation.triangularMassWithWork (OAI.EditApproximation.bitWordValue power.1) + (OAI.EditApproximation.bitWordValue mass.1, width.2 + band.2 + setup.2 + power.2 + mass.2 + 4) + +def cachedInitialProgramReadWithWork {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (read : OAI.EditApproximation.TargetInterval n → List Bool × ℕ) (query : OAI.EditApproximation.TargetInterval n) : OAI.EditApproximation.BinaryFraction × ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedWithWork (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + [true] (by decide) 0 + +def queryOnlineRangeAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (P exponent H : ℕ) (tau : OAI.EditApproximation.BinaryFraction) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) (key : ℕ × OAI.EditApproximation.TargetInterval ny) : ℕ := + let width := (OAI.EditApproximation.saturatingSubtractWithWork parent.hi parent.lo).1 + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let setup := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let power := (OAI.EditApproximation.bitPowerWithWork setup.bits 80).1 + OAI.EditApproximation.saturatingSubtractAllocation parent.hi parent.lo + + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent key.2 (OAI.EditApproximation.bitWordValue width) key.1 P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child allocation + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + + OAI.EditApproximation.bitPowerAllocation setup.bits 80 + OAI.EditApproximation.triangularMassAllocation (OAI.EditApproximation.bitWordValue power) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PositionCounts + + +def count : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n _ _ => n + +def left : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.PositionCounts → OAI.EditApproximation.PositionCounts + | .empty => .empty + | .node _ _ r => r + +def storageBits : OAI.EditApproximation.PositionCounts → ℕ + | .empty => 0 + | .node n l r => Nat.size n + 3 + l.storageBits + r.storageBits + +def add (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts + | 0, _ => .node (tree.count + 1) tree.left tree.right + | d + 1, i => + if i < 2 ^ d then + .node (tree.count + 1) (tree.left.add d i) tree.right + else .node (tree.count + 1) tree.left (tree.right.add d (i - 2 ^ d)) + +def addWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → OAI.EditApproximation.PositionCounts × ℕ + | 0, _ => (.node (tree.count + 1) tree.left tree.right, 1) + | d + 1, i => + if i < 2 ^ d then + let result := tree.left.addWithWork d i + (.node (tree.count + 1) result.1 tree.right, result.2 + 2) + else + let result := tree.right.addWithWork d (i - 2 ^ d) + (.node (tree.count + 1) tree.left result.1, result.2 + 2) + +def prefixWithWork (tree : OAI.EditApproximation.PositionCounts) : ℕ → ℕ → ℕ × ℕ + | 0, t => (if t = 0 then 0 else tree.count, 1) + | d + 1, t => + if t ≤ 2 ^ d then + let result := tree.left.prefixWithWork d t + (result.1, result.2 + 2) + else + let result := tree.right.prefixWithWork d (t - 2 ^ d) + (tree.left.count + result.1, result.2 + 2) + + +end OAI.EditApproximation.PositionCounts +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def bind {ι : Type u_1} {α : Type u_2} {β : Type u_3} {program : OAI.EditApproximation.BitQuery ι α} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (next : α → OAI.EditApproximation.BitQuery ι β) (allocation : ∀ value, OAI.EditApproximation.BitQuery.Footprint (next value)) : + OAI.EditApproximation.BitQuery.Footprint (program.bind next) := + match heap with + | .done result => allocation result + | .read key continuation stored => .read key _ (fun word => (stored word).bind next allocation) + | .charge localCells tail => .charge localCells (tail.bind next allocation) + +def compute {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + .charge allocation (.done execution.1) + +def chargeOf {ι : Type u_1} {β : Type u_2} {steps : ℕ} {program : OAI.EditApproximation.BitQuery ι β} (allocation : ℕ) + (tail : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (.charge steps program) := + .charge allocation tail + +def runCells {ι : Type u_1} {κ : Type u_2} + (ask : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitRecursiveMemoResult κ) + (childCells : ι → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} : OAI.EditApproximation.BitQuery.Footprint program → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .done _, _ => 0 + | .read key _ continuation, memory => + let first := ask key memory + 3 + childCells key memory + (continuation first.value).runCells ask childCells first.memory + | .charge cells next, memory => cells + next.runCells ask childCells memory + +def computeOf {ι : Type u_1} {β : Type u_2} (execution : β × ℕ) (allocation : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.compute (ι := ι) execution) := + OAI.EditApproximation.BitQuery.Footprint.compute execution allocation + +def collect {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (reader : κ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (allocation : ∀ key, OAI.EditApproximation.BitQuery.Footprint (reader key)) : + (inputs : List κ) → (next : List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) → + (∀ words, OAI.EditApproximation.BitQuery.Footprint (next words)) → OAI.EditApproximation.BitQuery.Footprint (OAI.EditApproximation.BitQuery.collect reader inputs next) + | [], _, continuation => continuation [] + | key :: rest, next, continuation => + (allocation key).bind _ fun word => .charge 1 + (collect reader allocation rest (fun words => next (word :: words)) + (fun words => continuation (word :: words))) + +def mapKeysWithWork {ι : Type u_1} {κ : Type u_2} {β : Type u_3} (f : ι → κ × ℕ) (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι β} (heap : OAI.EditApproximation.BitQuery.Footprint program) : OAI.EditApproximation.BitQuery.Footprint (program.mapKeysWithWork f) := + match heap with + | .done result => .done result + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (.read (f key).1 _ (fun word => (continuation word).mapKeysWithWork f allocation)) + | .charge localCells next => .charge localCells (next.mapKeysWithWork f allocation) + +def restrictWithWork {ι : Type u_1} (P : ι → Prop) + (test : ι → Bool × ℕ) (htest : ∀ key, (test key).1 = true ↔ P key) + (allocation : ι → ℕ) + {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) : + OAI.EditApproximation.BitQuery.Footprint (program.restrictWithWork P test htest) := + match heap with + | .done result => .done result + | .charge localCells next => .charge localCells (next.restrictWithWork P test htest allocation) + | .read key next continuation => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation key) + (by + split + · exact .read _ _ (fun word => (continuation word).restrictWithWork P test htest allocation) + · exact (continuation (OAI.EditApproximation.BinaryFraction.nat 0)).restrictWithWork P test htest allocation) + +def normalize {ι : Type u_1} {program : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction} (heap : OAI.EditApproximation.BitQuery.Footprint program) + (base : List Bool) (hbase : 0 < OAI.EditApproximation.bitWordValue base) (remaining : ℕ) : + OAI.EditApproximation.BitQuery.Footprint (program.normalize base hbase remaining) := + heap.bind _ fun word => OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.finishCachedWithWork (word, 0) base hbase remaining) + (OAI.EditApproximation.BinaryFraction.finishCachedAllocation (word, 0) 0 base hbase remaining) + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def bandActionPredicate {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : Prop := + OAI.EditApproximation.endpointActionConnection r states = 0 ∧ + (∀ i, Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).lo - parent.lo)) (states i).lo ≤ 6 * b ∧ + Nat.dist (r.lo + ((OAI.EditApproximation.sourceChild parent i).hi - parent.lo)) (states i).hi ≤ 6 * b) ∧ + ∀ j : Fin M, 0 < j.val → + |bandCutShift parent states j - ((r.lo : ℚ) - parent.lo) - velocity * + OAI.EditApproximation.rationalWidePrefixMinimum parent r actions hnonempty child j.val (OAI.EditApproximation.bandCutShift parent states j)| ≤ + tau * theta * b / M + +def queryOnlineSourceGather {ι : Type u_1} {β : Type u_2} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) (hP : 0 < P) (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval ny) + (reader : (ℕ × OAI.EditApproximation.TargetInterval ny) → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect (fun key => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) keys (next keys)) + +def coarseLabelChildren {B d : ℕ} {α : Type u_1} (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α d × Fin B × OAI.EditApproximation.CoarseThresholdDraws B d) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseLabelChildren Q lam allowance work rest + +instance bandActionPredicateDecidable {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b : ℕ) (tau theta velocity : ℚ) + (actions : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hnonempty : actions ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) (states : Fin M → OAI.EditApproximation.TargetInterval ny) : + Decidable (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions hnonempty child states) := by + unfold OAI.EditApproximation.bandActionPredicate + infer_instance + +def computedBandActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (tau theta velocity : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : List (Fin M → OAI.EditApproximation.TargetInterval ny) := + let actions := OAI.EditApproximation.wideActionList M parent r b P + if h : actions = [] then [] else + if |velocity| ≤ 1 - tau then + actions.filter (fun states => decide (OAI.EditApproximation.bandActionPredicate parent r b tau theta velocity actions h child states)) + else [] + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def rationalEndpointActionValue {ny M : ℕ} (r : OAI.EditApproximation.TargetInterval ny) + (states : Fin M → OAI.EditApproximation.TargetInterval ny) (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.endpointActionConnection r states + ∑ i, child i (states i) + +def rationalActualWideActions {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (representatives : List (ℕ × OAI.EditApproximation.TargetInterval ny)) (P : ℕ) : + List (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M) := + representatives.flatMap fun br => (OAI.EditApproximation.wideActionList M parent br.2 br.1 P).map fun states => + ⟨br.2, OAI.EditApproximation.endpointActionConnection br.2 states, fun i => (i, states i)⟩ + +def groupQueriedChildLabels (M Q b : ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M) := + if OAI.EditApproximation.groupSampleCount M Q b h = M then univ else univ.image draw + +def rationalWideActionMinimum {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (r : OAI.EditApproximation.TargetInterval ny) (b P : ℕ) (hnonempty : OAI.EditApproximation.wideActionList M parent r b P ≠ []) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → ℚ) : ℚ := + OAI.EditApproximation.rationalMinimum (OAI.EditApproximation.rationalEndpointActionValue r ((OAI.EditApproximation.wideActionList M parent r b P).head hnonempty) child) + ((OAI.EditApproximation.wideActionList M parent r b P).map fun states => OAI.EditApproximation.rationalEndpointActionValue r states child) + +def groupCurrentInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : ℚ) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h) → Fin M) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.groupQueriedChildLabels M Q b h draw).biUnion fun i => + (OAI.EditApproximation.groupRoundedStateList source target parent b exponent cell i h).toFinset.image fun r => (i, r) + +def representativeBandActions {α : Type u_1} (source target : List α) + {M : ℕ} (parent : OAI.EditApproximation.TargetInterval source.length) (r : OAI.EditApproximation.TargetInterval target.length) + (b P : ℕ) (tau theta : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) : + List (Fin M → OAI.EditApproximation.TargetInterval target.length) := + if h : OAI.EditApproximation.wideActionList M parent r b P = [] then [] else + let Z := OAI.EditApproximation.rationalWideActionMinimum parent r b P h child + if 0 < Z then + OAI.EditApproximation.computedBandActions parent r b P tau theta + (OAI.EditApproximation.rationalStateGap (OAI.EditApproximation.substring source parent.lo parent.hi) target r / Z) child + else [] + +structure UnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) where + center : OAI.EditApproximation.TargetInterval target.length + nonempty : OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child ≠ [] + sum_guard : (∑ i, OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i) ≤ 64 * F * b + wide_guard : OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial ∈ OAI.EditApproximation.wideActionList M parent center b P + imbalance_guard : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target + (OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b + (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) nonempty initial i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b (OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child) initial i + +def keyedOnlineBandG {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H b : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (r : OAI.EditApproximation.TargetInterval target.length) : ℕ := + H + (OAI.EditApproximation.bandCoordinates (OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child).toFinset).card + 2 + +def testUnskippedBand {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (center : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + let band := OAI.EditApproximation.representativeBandActions source target parent center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + if hband : band = [] then none else + if hsum : (∑ i, OAI.EditApproximation.bandChildEnvelope b band initial i) ≤ 64 * F * b then + let rounded := OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b band hband initial + if hwide : rounded ∈ OAI.EditApproximation.wideActionList M parent center b P then + if hgap : ∀ i, |rationalStateGap + (OAI.EditApproximation.substring source (OAI.EditApproximation.sourceChild parent i).lo (OAI.EditApproximation.sourceChild parent i).hi) target (rounded i)| ≤ + 2 * OAI.EditApproximation.bandChildEnvelope b band initial i then + some ⟨center, hband, hsum, hwide, hgap⟩ + else none + else none + else none + +def unskippedBandList {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P thetaExponent : ℕ) + (tau F : ℚ) (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (centers : List (OAI.EditApproximation.TargetInterval target.length)) : + List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + centers.filterMap (OAI.EditApproximation.testUnskippedBand source target parent b P thetaExponent tau F child initial) + +def keyedOnlineCandidate {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (tau eta kappa : ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (r : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.PhysicalRationalAction M target.length) := by + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + have proof_keyedOnlineBandG_positive_78 {α : Type u_1} (source : List.{u_1} α) (target : List.{u_1} α) {M : ℕ} (parent : OAI.EditApproximation.TargetInterval (List.length.{u_1} source)) (P : ℕ) (exponent : ℕ) (H : ℕ) (b : ℕ) (tau : ℚ) (child : Fin M → OAI.EditApproximation.TargetInterval (List.length.{u_1} target) → ℚ) (r : OAI.EditApproximation.TargetInterval (List.length.{u_1} target)) : + 0 < OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r := by + unfold OAI.EditApproximation.keyedOnlineBandG + omega + exact + let band := OAI.EditApproximation.representativeBandActions source target parent r b P tau + ((2 : ℚ) ^ (-(exponent : ℤ))) child + let envelope := OAI.EditApproximation.bandChildEnvelope b band initial + let G := OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H b tau child r + let K := G ^ 80 + let accepted := OAI.EditApproximation.boundedOnlineInteger (OAI.EditApproximation.optimizerTriangularMass K) + (proof_optimizerTriangularMass_positive_77 _ + (pow_pos (proof_keyedOnlineBandG_positive_78 source target parent P exponent H b tau child r) 80)) integer + if hband : band = [] then none else + match OAI.EditApproximation.testUnskippedBand source target parent b P exponent tau F child initial r with + | none => none + | some _ => some (OAI.EditApproximation.sharedBandRationalAction r + (OAI.EditApproximation.finiteOptimizerActionDraw band hband envelope + (OAI.EditApproximation.rationalOnlineLinear eta kappa + (OAI.EditApproximation.childGain envelope (fun s coordinate => children coordinate.1 s coordinate.2)) + (OAI.EditApproximation.childDecrement envelope (fun s coordinate => children coordinate.1 s coordinate.2)) t) + G K accepted)) + +def cellUnskippedBands {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) := + OAI.EditApproximation.unskippedBandList source target parent b P thetaExponent tau F child initial + (OAI.EditApproximation.cellRepresentativeStates target.length P F b a parentInitial + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) cell) + +def localOnlineCandidates {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N P F exponent H : ℕ) (tau a eta kappa : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (children : OAI.EditApproximation.PhysicalChildTables M target.length) (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + (OAI.EditApproximation.dyadicQueryWindow N (parentInitial q) a F).filterMap fun b => + let r := OAI.EditApproximation.roundInterval (OAI.EditApproximation.seedGridSpacing b P) q + if (b : ℚ) / (4 * a) ≤ parentInitial r ∧ parentInitial r ≤ 8 * F * b then + OAI.EditApproximation.keyedOnlineCandidate source target parent P F exponent H b tau eta kappa + child initial children t r (integer b r) + else none + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo +variable {α : Type u_1} + +def value : OAI.EditApproximation.BinaryMemo α → Option α + | .empty => none + | .node v _ _ => v + +def left : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ l _ => l + +def right : OAI.EditApproximation.BinaryMemo α → OAI.EditApproximation.BinaryMemo α + | .empty => .empty + | .node _ _ r => r + +def lookup (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α + | [] => tree.value + | false :: rest => tree.left.lookup rest + | true :: rest => tree.right.lookup rest + +def insert (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α + | [], a => .node (some a) tree.left tree.right + | false :: rest, a => .node tree.value (tree.left.insert rest a) tree.right + | true :: rest, a => .node tree.value tree.left (tree.right.insert rest a) + +def lookupCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → Option α × ℕ + | [] => (tree.value, 1) + | false :: rest => + let result := tree.left.lookupCosted rest + (result.1, result.2 + 1) + | true :: rest => + let result := tree.right.lookupCosted rest + (result.1, result.2 + 1) + +def insertCosted (tree : OAI.EditApproximation.BinaryMemo α) : List Bool → α → OAI.EditApproximation.BinaryMemo α × ℕ + | [], a => (.node (some a) tree.left tree.right, 1) + | false :: rest, a => + let result := tree.left.insertCosted rest a + (.node tree.value result.1 tree.right, result.2 + 1) + | true :: rest, a => + let result := tree.right.insertCosted rest a + (.node tree.value tree.left result.1, result.2 + 1) + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def rankedMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : OAI.EditApproximation.RecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1⟩ + | none => + let result := OAI.EditApproximation.FiniteQuery.run (fun child previous => + rankedMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1⟩ +termination_by rank key +decreasing_by exact child.property + +def localWarmupStepQuery {ι : Type u_1} {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) (a : ℚ) (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.FiniteQuery ι) (q : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (initialRead q) fun value => + let centers := OAI.EditApproximation.rawRefinementCenters N P F a value q + OAI.EditApproximation.FiniteQuery.collect initialRead centers fun answers => + let initial := fun r => if r = q then value else OAI.EditApproximation.finiteAnswerTable centers answers r + let representatives := OAI.EditApproximation.localRefinementRepresentatives N P F a initial q + let inputs := OAI.EditApproximation.wideWarmupInputs (M := M) parent P representatives + OAI.EditApproximation.FiniteQuery.collect childRead inputs fun values => + .done (OAI.EditApproximation.rationalBellman initial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent representatives P) (OAI.EditApproximation.finiteAnswerTable inputs values) q) + +def keyedOnlineSourceRange {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P exponent H : ℕ) (tau : ℚ) + (child : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (key : ℕ × OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.optimizerTriangularMass (OAI.EditApproximation.keyedOnlineBandG source target parent P exponent H key.1 tau child key.2 ^ 80) + +def occurrenceBuild (symbolBits positionBits : ℕ) : List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts + | [] => .empty + | e :: es => + let table := occurrenceBuild symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let old := (table.lookup key).getD .empty + table.insert key (old.add positionBits e.2) + +def occurrenceBuildWithWork (symbolBits positionBits : ℕ) : + List (ℕ × ℕ) → OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ + | [] => (.empty, 0) + | e :: es => + let previous := occurrenceBuildWithWork symbolBits positionBits es + let key := OAI.EditApproximation.binaryMemoKey symbolBits e.1 + let found := previous.1.lookupCosted key + let inserted := (found.1.getD .empty).addWithWork positionBits e.2 + let updated := previous.1.insertCosted key inserted.1 + (updated.1, previous.2 + symbolBits + found.2 + inserted.2 + updated.2 + 2) + +def occurrenceQueryWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : Bool × ℕ := + let key := OAI.EditApproximation.binaryMemoKey symbolBits a + let found := table.lookupCosted key + let tree := found.1.getD .empty + let first := tree.prefixWithWork positionBits lo + let last := tree.prefixWithWork positionBits hi + (decide (first.1 < last.1), symbolBits + found.2 + first.2 + last.2 + 2) + +def rankedBitMemoEvaluate {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (bits : ℕ) (encode : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitRecursiveMemoResult κ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some result => ⟨result, memory, [], found.2, 1, 0⟩ + | none => + let result := OAI.EditApproximation.BitQuery.runMemo (fun child previous => + rankedBitMemoEvaluate rank program bits encode child.val previous) (program key) memory + let stored := result.memory.insertCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) result.value + ⟨result.value, stored.1, key :: result.freshKeys, + found.2 + result.dictionaryVisits + stored.2, result.requests + 1, result.localWork⟩ +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupStepQuery {ι : Type u_1} {α : Type u_2} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.FiniteQuery ι) + (childRead : Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.FiniteQuery ι) + (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.localWarmupStepQuery (OAI.EditApproximation.physicalSourceInterval source.length node) N P F (OAI.EditApproximation.refinementFactor A F) + (fun r => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, r)) childRead q + +def indexedSingletonCostWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits a lo hi : ℕ) : ℕ × ℕ := + if lo = hi then (1, 1) else + let query := OAI.EditApproximation.occurrenceQueryWithWork table symbolBits positionBits a lo hi + (hi - lo - if query.1 = true then 1 else 0, query.2 + 4) + +def integerOccurrenceIndex (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts := + OAI.EditApproximation.occurrenceBuild (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def integerOccurrenceBuildWithWork (source target : List ℤ) : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts × ℕ := + OAI.EditApproximation.occurrenceBuildWithWork (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + (target.map OAI.EditApproximation.integerSymbolCode).zipIdx + +def rankedMemoAddressWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => cost key + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoAddressWork rank program bits encode cost child.val previous) + (program key) memory + cost key +termination_by rank key +decreasing_by exact child.property + +def rankedMemoKernelWork {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.FiniteQuery {child : κ // rank child < rank key}) + (bits : ℕ) (encode cost : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo ℚ) : ℕ := + match (memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key))).1 with + | some _ => 0 + | none => cost key + OAI.EditApproximation.FiniteQuery.requestWork + (fun child previous => OAI.EditApproximation.rankedMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedMemoKernelWork rank program bits encode cost child.val previous) + (program key) memory +termination_by rank key +decreasing_by exact child.property + +def physicalWarmupRequestQuery {α : Type u_1} [DecidableEq α] {M J : ℕ} + (source target : List α) (N P F : ℕ) (A : ℚ) + (pass copy T S j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (q : OAI.EditApproximation.TargetInterval target.length) + (seedRead : OAI.EditApproximation.PhysicalEntry M J target.length → + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j q).combinedRank T S} := + match j with + | 0 => OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + | t + 1 => + if hbelow : node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F A seedRead + (OAI.EditApproximation.physicalWarmupChildQuery pass copy T S t node hbelow q) node q + else OAI.EditApproximation.physicalInitialQuery source target N P F A seedRead (node, q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalLocalOnlineKey (M J N n : ℕ) := + OAI.EditApproximation.PhysicalInternalNode M J × Fin (OAI.EditApproximation.dyadicScales N).length × OAI.EditApproximation.TargetInterval n + +abbrev ClampedPhysicalSeed (M J ny N : ℕ) := OAI.EditApproximation.PhysicalEntry M J ny → Fin (N + 1) + +def finalTargetState (n : ℕ) : OAI.EditApproximation.TargetInterval n := ⟨0, n, Nat.zero_le _, le_rfl⟩ + +abbrev PhysicalCommonKey (M J N n exponent B : ℕ) := + Sum (OAI.EditApproximation.CommonRangeKey (OAI.EditApproximation.PhysicalLocalOnlineKey M J N n) B) + (OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) + +def clampedSeedNat {M J ny N : ℕ} (seed : OAI.EditApproximation.ClampedPhysicalSeed M J ny N) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : ℕ := (seed state).val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open Finset + +def triangularChoiceWithWork (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → Fin K × ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + let chosen := triangularChoiceWithWork K ⟨integer.val, hsmall⟩ + (chosen.1.castSucc, threshold.2 + test.2 + chosen.2 + 2) + else (⟨K, by omega⟩, threshold.2 + test.2 + 1) + +def triangularChoiceAllocation (K : ℕ) : Fin (OAI.EditApproximation.optimizerTriangularMass K) → ℕ:= by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + exact fun integer => match K, integer with + | 0, integer => Fin.elim0 integer + | K + 1, integer => + let threshold := OAI.EditApproximation.triangularMassWithWork K + let test := OAI.EditApproximation.binaryNaturalCompareWithWork integer.val (OAI.EditApproximation.bitWordValue threshold.1) + let localCells := OAI.EditApproximation.triangularMassAllocation K + integer.val.bits.length + + (OAI.EditApproximation.bitWordValue threshold.1).bits.length + if h : test.1 = .lt then + let hsmall : integer.val < OAI.EditApproximation.optimizerTriangularMass K := by + have ht := (proof_binaryNaturalCompareWithWork_lt_53 _ _).mp h + simpa only [threshold, proof_triangularMassWithWork_value_65] using ht + localCells + triangularChoiceAllocation K ⟨integer.val, hsmall⟩ + else localCells + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def coordinateVectorWithWork {M n : ℕ} (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) : + Vector (Fin M × OAI.EditApproximation.TargetInterval n) (OAI.EditApproximation.listedBandCoordinates band).length × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + exact + let coordinates := OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band + (Vector.ofFn (fun i => coordinates.1.get ⟨i.val, by + rw [proof_bandCoordinatesWithWork_value_68] + exact i.isLt⟩), coordinates.2 + coordinates.1.length + 1) + +def reduceOnlineIntegerWithWork (K : ℕ) (hK : 0 < K) (integer : ℕ) : + Fin (OAI.EditApproximation.optimizerTriangularMass K) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_optimizerTriangularMass_succ_66 (K : ℕ) : + OAI.EditApproximation.optimizerTriangularMass (K + 1) = OAI.EditApproximation.optimizerTriangularMass K + (K + 1) := by + unfold OAI.EditApproximation.optimizerTriangularMass + rw [sum_range_succ] + have proof_optimizerTriangularMass_twice_67 (K : ℕ) : + 2 * OAI.EditApproximation.optimizerTriangularMass K = K * (K + 1) := by + induction K with + | zero => simp [OAI.EditApproximation.optimizerTriangularMass] + | succ K ih => + rw [proof_optimizerTriangularMass_succ_66] + nlinarith + have proof_triangularMassWithWork_value_65 (K : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.triangularMassWithWork K).1 = OAI.EditApproximation.optimizerTriangularMass K := by + simp only [OAI.EditApproximation.triangularMassWithWork, proof_binaryNaturalAddWithWork_value_52, proof_binaryNaturalMulWithWork_value_55, + (proof_binaryNaturalDivModWithWork_spec_24 _ 2 (by decide)).1] + rw [← proof_optimizerTriangularMass_twice_67 K, Nat.mul_div_cancel_left _ (by decide : 0 < 2)] + have proof_optimizerTriangularMass_positive_77 (K : ℕ) (hK : LT.lt.{0} 0 K) : + 0 < OAI.EditApproximation.optimizerTriangularMass K := by + have hproduct : 0 < K * (K + 1) := Nat.mul_pos hK (by omega) + rw [← proof_optimizerTriangularMass_twice_67 K] at hproduct + omega + exact + let mass := OAI.EditApproximation.triangularMassWithWork K + let divided := OAI.EditApproximation.binaryNaturalDivModWithWork integer (OAI.EditApproximation.bitWordValue mass.1) + (⟨OAI.EditApproximation.bitWordValue divided.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 integer (OAI.EditApproximation.bitWordValue mass.1) + (by rw [proof_triangularMassWithWork_value_65]; exact proof_optimizerTriangularMass_positive_77 K hK)).2] + rw [proof_triangularMassWithWork_value_65] + exact Nat.mod_lt _ (proof_optimizerTriangularMass_positive_77 K hK)⟩, + mass.2 + divided.2.2 + Nat.size integer + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def countedPreparedActionReadWithWork {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let coordinates := OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band + let vertices := OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates.1 mass band + let linear := OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.1.get i) + let selected := OAI.EditApproximation.BinaryFraction.selectionWithWork vertices.1 linear.1 G j + (selected.1, coordinates.2 + vertices.2 + linear.2 + selected.2 + 3) + +def countedPreparedActionKernelAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + let coordinates := (OAI.EditApproximation.BinaryFraction.coordinateVectorWithWork band).1 + let vertices := (OAI.EditApproximation.BinaryFraction.countedBandVerticesWithWork coordinates mass band).1 + let linear := (OAI.EditApproximation.vectorMapWithWork _ fun i => + OAI.EditApproximation.BinaryFraction.onlineLinearReadWithWork (fun child => mass.get child) read eta kappa t (coordinates.get i)).1 + OAI.EditApproximation.BinaryFraction.countedBandVerticesAllocation coordinates mass band + + OAI.EditApproximation.vectorMapAllocation _ (fun i => OAI.EditApproximation.BinaryFraction.onlineLinearReadAllocation (fun child => mass.get child) + read footprint eta kappa t (coordinates.get i)) + OAI.EditApproximation.BinaryFraction.selectionAllocation vertices linear G j + +def countedBandActionReadWithWork {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : + Option (Fin M → OAI.EditApproximation.TargetInterval n) × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial + let selected := OAI.EditApproximation.BinaryFraction.countedPreparedActionReadWithWork mass.1 read eta kappa band G j t + (selected.1, mass.2 + selected.2 + 1) + +def countedPreparedActionAllocation {M n : ℕ} (mass : Vector OAI.EditApproximation.BinaryFraction M) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.coordinateVectorAllocation band + OAI.EditApproximation.BinaryFraction.countedPreparedActionKernelAllocation mass read footprint eta kappa band G j t + +def countedSampledOnlineReadWithWork {n M : ℕ} (center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval n) (Fin M × OAI.EditApproximation.TargetInterval n) M × ℕ := + let chosen := OAI.EditApproximation.triangularChoiceWithWork K integer + let selected := OAI.EditApproximation.BinaryFraction.countedBandActionReadWithWork b initial read eta kappa band G chosen.1.val t + let states := selected.1.getD (band.head hne) + (⟨center, OAI.EditApproximation.BinaryFraction.zero, fun i => (i, states i)⟩, chosen.2 + selected.2 + M + 2) + +def countedBandActionAllocation {M n : ℕ} (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (footprint : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (G j t : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band initial initialAllocation + + OAI.EditApproximation.BinaryFraction.countedPreparedActionAllocation (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band initial).1 + read footprint eta kappa band G j t + +def countedSampledOnlineAllocation {n M : ℕ} (_center : OAI.EditApproximation.TargetInterval n) (b : ℕ) + (initial : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : Fin M → OAI.EditApproximation.TargetInterval n → ℕ) + (read : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval n → ℕ) + (eta kappa : OAI.EditApproximation.BinaryFraction) (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (_hne : band ≠ []) + (G K t : ℕ) (integer : Fin (OAI.EditApproximation.optimizerTriangularMass K)) : ℕ := + let chosen := (OAI.EditApproximation.triangularChoiceWithWork K integer).1 + OAI.EditApproximation.triangularChoiceAllocation K integer + + OAI.EditApproximation.BinaryFraction.countedBandActionAllocation b initial initialAllocation read readAllocation eta kappa band G chosen.val t + M + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} + +def rank (tableRank : κ → ℕ) : Sum σ κ → ℕ + | .inl _ => 0 + | .inr key => tableRank key + 1 + +def keyCode (sourceCode : σ → ℕ) (tableCode : κ → ℕ) : Sum σ κ → ℕ + | .inl source => 2 * sourceCode source + | .inr table => 2 * tableCode table + 1 + +def child (tableRank : κ → ℕ) (parent : κ) : + Sum σ {key : κ // tableRank key < tableRank parent} → + {key : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank key < OAI.EditApproximation.SourceRanked.rank (σ := σ) tableRank (.inr parent)} + | .inl source => ⟨.inl source, Nat.zero_lt_succ _⟩ + | .inr table => ⟨.inr table.val, Nat.add_lt_add_right table.property 1⟩ + +def body (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (sourceValue : σ → ℚ) (key : Sum σ κ) : + OAI.EditApproximation.FiniteQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} := + match key with + | .inl source => .done (sourceValue source) + | .inr table => OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.child tableRank table) (tableBody table) + +def bitBody (tableRank : κ → ℕ) + (tableBody : (parent : κ) → OAI.EditApproximation.BitQuery (Sum σ {key : κ // tableRank key < tableRank parent}) OAI.EditApproximation.BinaryFraction) + (sourceValue : σ → OAI.EditApproximation.BinaryFraction × ℕ) (key : Sum σ κ) : + OAI.EditApproximation.BitQuery {next : Sum σ κ // OAI.EditApproximation.SourceRanked.rank tableRank next < OAI.EditApproximation.SourceRanked.rank tableRank key} OAI.EditApproximation.BinaryFraction := + match key with + | .inl source => OAI.EditApproximation.BitQuery.compute (sourceValue source) + | .inr table => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (OAI.EditApproximation.SourceRanked.child tableRank table key, 1)) (tableBody table) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def depth {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => J - entry.1.1.val + | .inr request => request.val.remainingDepth + +def index {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl _ => 0 + | .inr request => request.val.rank T S + 1 + +def rank {M J ny passes copies T S : ℕ} + (request : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) : ℕ := + request.depth + request.index + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def chargedPreviousRead {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hpass : 0 < parent.val.pass) (state : OAI.EditApproximation.TargetInterval ny) (copy : Fin copies) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + .read ⟨Sum.inr (OAI.EditApproximation.chargedPreviousPass parent state copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hpass state).2⟩⟩ .done + +def chargedWarmupChild {M J ny passes copies T S : ℕ} + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) + (input : Fin M × OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + .read ⟨Sum.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ .done + +def chargedSeedQuery {M J ny passes copies T S : ℕ} (N : ℕ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J ny // r.Bounded passes copies T S}) + (state : OAI.EditApproximation.PhysicalEntry M J ny) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + exact + if hn : state.1 = parent.val.node then + if hp : parent.val.pass = 0 then + .read ⟨Sum.inl state, proof_coarse_rank_lt_100 state parent hn⟩ .done + else OAI.EditApproximation.FiniteQuery.collect (OAI.EditApproximation.chargedPreviousRead parent (Nat.pos_of_ne_zero hp) state.2) + (List.finRange copies) fun values => + .done (min N (OAI.EditApproximation.upperMedian (values.map fun value => + ⌈(multiplier (parent.val.pass - 1) : ℚ) * value⌉₊)) : ℕ) + else .done 0 + +def chargedWarmupQuery {α : Type u_1} [DecidableEq α] {M J passes copies T S : ℕ} + (source target : List α) (N P F : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent)} := + if hz : parent.val.index = 0 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else if hbelow : parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + else OAI.EditApproximation.physicalWarmupStepQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) + (OAI.EditApproximation.chargedWarmupChild parent hbelow (Nat.pos_of_ne_zero hz)) parent.val.node parent.val.state + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +abbrev coarseEntryWidth {α : Type u} (x y : List α) : ℕ := max x.length y.length + +abbrev CoarseGuessIndex (n : ℕ) := Fin (Nat.clog 2 n + 1) + +def coarseGuess (n : ℕ) (i : OAI.EditApproximation.CoarseGuessIndex n) : ℕ := 2 ^ i.val + +def coarseEntryTree (B D : ℕ) {α : Type u} (x y : List α) : OAI.EditApproximation.CoarseSourceTree B (Option α) D := + OAI.EditApproximation.coarseSourceTreeOfList B D (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) x) + +noncomputable def coarseInitialMeasure (B D n : ℕ) [NeZero B] + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseGuessIndex n → OAI.EditApproximation.CoarseThresholdDraws B D) := + Measure.pi fun _ => OAI.EditApproximation.coarseDrawMeasure B D + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveChildrenWork {B D : ℕ} {α : Type u} + (Q lam allowance : ℚ) + (work : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ + | [] => 0 + | (child, draw, below) :: rest => + work child below (lam * OAI.EditApproximation.coarseChildThreshold B Q allowance draw) + + coarseActiveChildrenWork Q lam allowance work rest + +abbrev CoarseFullSeedDraws (B : ℕ) {I : Type u_1} {α : Type u_2} (depth : I → ℕ) (x y : I → List α) := + ∀ i, OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) → OAI.EditApproximation.CoarseThresholdDraws B (depth i) + +noncomputable def coarseFullSeedMeasure (B : ℕ) [NeZero B] + {I : Type u_1} {α : Type u_2} [Fintype I] (depth : I → ℕ) (x y : I → List α) + [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] : + Measure (OAI.EditApproximation.CoarseFullSeedDraws B depth x y) := + Measure.pi fun i => OAI.EditApproximation.coarseInitialMeasure B (depth i) (OAI.EditApproximation.coarseEntryWidth (x i) (y i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionAcceptedLaw : Measure (∀ i, Fin (range i)) := + Measure.pi fun i => (PMF.uniformOfFintype (Fin (range i))).toMeasure + +abbrev RejectionRuntimeArray := (ι → ℕ) × (∀ i, Fin (range i)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryMemo + + +def fractionStorage : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction → ℕ + | .empty => 0 + | .node value left right => + 3 + (value.map fun word => word.numerator.bits.length + word.denominator.length + 1).getD 0 + + left.fractionStorage + right.fractionStorage + +def valueStorage {α : Type u_1} (bits : α → ℕ) : OAI.EditApproximation.BinaryMemo α → ℕ + | .empty => 0 + | .node value l r => 3 + (value.map bits).getD 0 + valueStorage bits l + valueStorage bits r + + +end OAI.EditApproximation.BinaryMemo +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def indexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ × ℕ := + match symbol with + | none => (hi - lo, 2) + | some a => OAI.EditApproximation.indexedSingletonCostWithWork table symbolBits positionBits a lo hi + +def integerOccurrenceStorage (source target : List ℤ) : ℕ := + OAI.EditApproximation.BinaryMemo.valueStorage OAI.EditApproximation.PositionCounts.storageBits (OAI.EditApproximation.integerOccurrenceIndex source target) + +def integerStoredDataSpace (source target : List ℤ) : ℕ := + OAI.EditApproximation.storedIntegerBits source + OAI.EditApproximation.storedIntegerBits target + + OAI.EditApproximation.storedNaturalBits (source.map OAI.EditApproximation.integerSymbolCode) + OAI.EditApproximation.storedNaturalBits (target.map OAI.EditApproximation.integerSymbolCode) + + OAI.EditApproximation.integerOccurrenceStorage source target + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def binaryIndexedLeafWithWork (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let result := OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi + (OAI.EditApproximation.BinaryFraction.nat result.1, result.2 + Nat.size result.1 + 2) + +def binaryIndexedLeafAllocation (table : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (symbol : Option ℕ) (lo hi : ℕ) : ℕ := + OAI.EditApproximation.indexedLeafAllocation symbolBits positionBits symbol lo hi + + Nat.size (OAI.EditApproximation.indexedLeafWithWork table symbolBits positionBits symbol lo hi).1 + 2 + +def queryIndexedSliceWithWork (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := + let symbol := OAI.EditApproximation.querySliceHeadWithWork source interval + let result := OAI.EditApproximation.binaryIndexedLeafWithWork occurrence symbolBits positionBits symbol.1 q.lo q.hi + (result.1, symbol.2 + result.2 + 1) + +def queryIndexedSliceAllocation (source : List ℕ) (interval : OAI.EditApproximation.TargetInterval source.length) + (targetLength : ℕ) (q : OAI.EditApproximation.TargetInterval targetLength) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) : ℕ := + interval.lo.bits.length + interval.hi.bits.length + 1 + + OAI.EditApproximation.binaryIndexedLeafAllocation occurrence symbolBits positionBits (OAI.EditApproximation.querySliceHeadWithWork source interval).1 q.lo q.hi + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {n : ℕ} (read : TargetInterval n → List Bool × ℕ) (allocation : TargetInterval n → ℕ) + +def initialGridReadAllocation (P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (radius : ℕ) (q : OAI.EditApproximation.TargetInterval n) (b : ℕ) : ℕ := + let spacing := (OAI.EditApproximation.seedGridSpacingWithWork b P).1 + let points := (OAI.EditApproximation.gridStateBoxWithWork n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.gridStateBoxAllocation n (OAI.EditApproximation.bitWordValue spacing) radius q.lo q.hi + + OAI.EditApproximation.filterAllocation (fun r => ((OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).1, + (OAI.EditApproximation.BinaryFraction.initialCenterGuardWithWork b (OAI.EditApproximation.bitWordValue (read r).1) A).2 + (read r).2)) + (fun r => OAI.EditApproximation.BinaryFraction.initialCenterGuardAllocation b (OAI.EditApproximation.bitWordValue (read r).1) A + allocation r) points + +def initialConeReadAllocation (sourceLength : ℕ) (a L : OAI.EditApproximation.BinaryFraction) (query center : OAI.EditApproximation.TargetInterval n) : ℕ := + allocation center + OAI.EditApproximation.BinaryFraction.initialConeAllocation sourceLength (OAI.EditApproximation.bitWordValue (read center).1) a L query center + +def initialCentersReadAllocation (N P : ℕ) (A : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read q).1 + let scales := (OAI.EditApproximation.dyadicScalesWithWork N).1 + let active := (OAI.EditApproximation.filterWithWork (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) scales).1 + allocation q + OAI.EditApproximation.dyadicScalesAllocation N + + OAI.EditApproximation.filterAllocation (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardWithWork Uq b A) (fun b => OAI.EditApproximation.BinaryFraction.initialScaleGuardAllocation Uq b A) scales + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.initialGridReadWithWork P A read Uq q) + (OAI.EditApproximation.BinaryFraction.initialGridReadAllocation read allocation P A Uq q) active + +def initialMinimumReadAllocation (sourceLength N F : ℕ) (a : OAI.EditApproximation.BinaryFraction) + (query : OAI.EditApproximation.TargetInterval n) (centers : List (OAI.EditApproximation.TargetInterval n)) : ℕ := + let Uq := OAI.EditApproximation.bitWordValue (read query).1 + allocation query + OAI.EditApproximation.naturalEqualAllocation Uq 0 + + if (OAI.EditApproximation.naturalEqualWithWork Uq 0).1 then 0 else + let L := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F)).1 + let coefficient := (OAI.EditApproximation.BinaryFraction.canonicalAddWithWork L OAI.EditApproximation.BinaryFraction.one).1 + let fallback := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork coefficient (OAI.EditApproximation.BinaryFraction.nat N)).1 + let scores := (OAI.EditApproximation.arithmeticMapWithWork (OAI.EditApproximation.BinaryFraction.initialConeReadWithWork sourceLength read a L query) centers).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 32) (OAI.EditApproximation.BinaryFraction.nat F) + OAI.EditApproximation.BinaryFraction.canonicalAddAllocation L OAI.EditApproximation.BinaryFraction.one + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation coefficient (OAI.EditApproximation.BinaryFraction.nat N) + + OAI.EditApproximation.arithmeticMapAllocation (OAI.EditApproximation.BinaryFraction.initialConeReadAllocation read allocation sourceLength a L query) centers + + OAI.EditApproximation.BinaryFraction.minimumAllocation fallback scores + Nat.size F + Nat.size N + +def initialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.initialCentersReadAllocation read allocation N P A query + OAI.EditApproximation.BinaryFraction.initialMinimumReadAllocation read allocation sourceLength N F a + query (OAI.EditApproximation.BinaryFraction.initialCentersReadWithWork N P A read query).1 + +def cachedInitialProgramReadAllocation (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval n) : ℕ := + OAI.EditApproximation.BinaryFraction.finishCachedAllocation (OAI.EditApproximation.BinaryFraction.initialProgramReadWithWork sourceLength N P F A a read query) + (OAI.EditApproximation.BinaryFraction.initialProgramReadAllocation read allocation sourceLength N P F A a query) [true] (by decide) 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +open BinaryFraction + +def onlineParametersAllocation (word : List Bool) : ℕ := + OAI.EditApproximation.bitPowerAllocation word 5 + OAI.EditApproximation.bitPowerAllocation word 4 + 2 + +def refinementDecrementAllocation (word : List Bool) : ℕ := OAI.EditApproximation.bitPowerAllocation word 10 + 1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BinaryFraction + +def scheduledRefinementAllocation (N pass : ℕ) : ℕ := + if pass < OAI.EditApproximation.computedSeedPassCount N then + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.computedSeedInitialExponent N) pass - OAI.EditApproximation.smallLogExponent N : ℕ) : ℤ) + 2 + else 2 + +def refinementBaseAllocation (word : List Bool) : ℕ := + let power := OAI.EditApproximation.bitPowerWithWork word 10 + let increment := OAI.EditApproximation.bitAddWithWork power.1 [true] false + OAI.EditApproximation.bitPowerAllocation word 10 + OAI.EditApproximation.bitAddAllocation power.1 [true] false + + OAI.EditApproximation.trimBitWordAllocation increment.1 + 2 + +def refinementParameterAllocation (N pass : ℕ) (word : List Bool) : ℕ := + OAI.EditApproximation.BinaryFraction.onlineParametersAllocation word + OAI.EditApproximation.scheduledRefinementAllocation N pass + + OAI.EditApproximation.BinaryFraction.refinementDecrementAllocation word + 5 + +def computedQueryPassAllocation (N pass : ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.signedPowerTwoAllocation ((OAI.EditApproximation.dyadicSeedExponent (OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.computedSeedInitialExponent N) pass : ℕ) : ℤ) + + OAI.EditApproximation.refinementParameterAllocation N pass (OAI.EditApproximation.inputSmallLog N).bits + 2 + +def computedQuerySetupAllocation (N : ℕ) : ℕ := + OAI.EditApproximation.vectorMapAllocation (OAI.EditApproximation.computedSeedPassCount N + 1) (fun i => OAI.EditApproximation.computedQueryPassAllocation N i.val) + + OAI.EditApproximation.refinementBaseAllocation (OAI.EditApproximation.inputSmallLog N).bits + 5 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnreducedRational +open Finset + +def nat (n : ℕ) : OAI.EditApproximation.UnreducedRational := ⟨n, 1, by decide⟩ + + +end OAI.EditApproximation.UnreducedRational +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def countedGroupMemberSourceWithWork {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + let result := OAI.EditApproximation.BinaryFraction.groupMemberSourceWithWork scales count connection envelope values + (fun t j => draw t (Fin.cast (heq t) j)) + (result.1, counts.2 + result.2 + 1) + +def roundedBandReadWithWork {n M : ℕ} (exponent b : ℕ) + (band : List (Fin M → OAI.EditApproximation.TargetInterval n)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) : Vector (OAI.EditApproximation.TargetInterval n) M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_lt_eq_true_57 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : a.lt b = true ↔ a.value < b.value := by + simp only [OAI.EditApproximation.UnreducedRational.lt, decide_eq_true_eq, OAI.EditApproximation.UnreducedRational.value] + rw [div_lt_div_iff₀ (by exact_mod_cast a.den_pos : (0 : ℚ) < a.den) + (by exact_mod_cast b.den_pos : (0 : ℚ) < b.den)] + exact_mod_cast (Iff.rfl : a.num * (b.den : ℤ) < b.num * (a.den : ℤ) ↔ _) + have proof_nonzeroWithWork_value_58 (bits : List.{0} Bool) : + (OAI.EditApproximation.SignedBinary.nonzeroWithWork bits).1 = true ↔ OAI.EditApproximation.bitWordValue bits ≠ 0 := by + (simp [OAI.EditApproximation.SignedBinary.nonzeroWithWork, proof_bitCompareWithWork_eq_3, OAI.EditApproximation.bitWordValue]) + have proof_ltWithWork_value_59 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + cases ha : a.negative <;> cases hb : b.negative + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + · (simp only [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, ↓reduceIte, Bool.false_eq_true, + Bool.or_eq_true, proof_nonzeroWithWork_value_58, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude]) + omega + · (simp [OAI.EditApproximation.SignedBinary.ltWithWork, ha, hb, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, proof_bitCompareWithWork_lt_16]) + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_denominatorInteger_value_60 (a : OAI.EditApproximation.BinaryFraction) : + a.denominatorInteger.value = (OAI.EditApproximation.bitWordValue a.denominator : ℤ) := rfl + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_ltWithWork_representation_61 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = a.representation.lt b.representation := by + apply Bool.eq_iff_iff.mpr + rw [proof_lt_eq_true_57] + simp only [OAI.EditApproximation.BinaryFraction.ltWithWork, proof_ltWithWork_value_59, proof_mulWithWork_value_35, + proof_denominatorInteger_value_60, proof_representation_value_32] + unfold OAI.EditApproximation.BinaryFraction.value + rw [div_lt_div_iff₀ (by exact_mod_cast a.denominator_pos : (0 : ℚ) < bitWordValue a.denominator) + (by exact_mod_cast b.denominator_pos : (0 : ℚ) < bitWordValue b.denominator)] + exact_mod_cast (Iff.rfl : + a.numerator.value * (OAI.EditApproximation.bitWordValue b.denominator : ℤ) < + b.numerator.value * (OAI.EditApproximation.bitWordValue a.denominator : ℤ) ↔ _) + have proof_ltWithWork_value_62 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.ltWithWork b).1 = true ↔ a.value < b.value := by + rw [proof_ltWithWork_representation_61, proof_lt_eq_true_57] + rfl + have proof_maxWithWork_value_63 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.maxWithWork a b).1.value = max a.value b.value := by + by_cases h : a.value < b.value + · simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, (proof_ltWithWork_value_62 a b).mpr h, ↓reduceIte, max_eq_right h.le] + · have hb : (a.ltWithWork b).1 = false := Bool.eq_false_iff.mpr (fun hh => h ((proof_ltWithWork_value_62 a b).mp hh)) + simp only [OAI.EditApproximation.BinaryFraction.maxWithWork, hb, Bool.false_eq_true, ↓reduceIte, max_eq_left (le_of_not_gt h)] + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_roundedSpacingWithWork_value_64 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 = ⌈max 1 (theta.value * envelope.value)⌉₊ := by + simp only [OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork, proof_naturalCeilingWithWork_value_31, proof_maxWithWork_value_63, + proof_canonicalMulWithWork_value_45, OAI.EditApproximation.BinaryFraction.one, proof_nat_value_49, Nat.cast_one] + have proof_roundedSpacingWithWork_pos_56 (theta : OAI.EditApproximation.BinaryFraction) (envelope : OAI.EditApproximation.BinaryFraction) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork theta envelope).1 := by + rw [proof_roundedSpacingWithWork_value_64, Nat.ceil_pos] + exact lt_of_lt_of_le (by norm_num : (0 : ℚ) < 1) (le_max_left _ _) + exact + OAI.EditApproximation.vectorMapWithWork M fun i => + let envelope := OAI.EditApproximation.BinaryFraction.bandEnvelopeReadWithWork b band read i + let spacing := OAI.EditApproximation.BinaryFraction.roundedSpacingWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) envelope.1 + let rounded := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) + (proof_roundedSpacingWithWork_pos_56 _ _) (band.head hne i) + (rounded.1, envelope.2 + spacing.2 + rounded.2 + exponent + 3) + +def queryGroupLabelsWithWork (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : List (Fin M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h + let test := OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count.1) M + if test.1 then (List.finRange M, count.2 + test.2 + M + 2) + else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + let labels := OAI.EditApproximation.arithmeticMapWithWork draw indices + (labels.1, count.2 + test.2 + labels.2 + indices.length + 2) + +def queryGroupLabelsAllocation (M Q b : ℕ) (h : OAI.EditApproximation.BinaryFraction) + (_draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let count := (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 + let test := (OAI.EditApproximation.naturalEqualWithWork (OAI.EditApproximation.bitWordValue count) M).1 + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b h + OAI.EditApproximation.naturalEqualAllocation (OAI.EditApproximation.bitWordValue count) M + + if test then M else + let indices := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count) (OAI.EditApproximation.groupSampleCount M Q b h.value) + (proof_groupSampleCountWithWork_value_28 M Q b h) + OAI.EditApproximation.arithmeticMapAllocation allocation indices + 2 * indices.length + +def countedGroupMemberSourceAllocation {M T : ℕ} (Q b : ℕ) (scales : Fin T → OAI.EditApproximation.BinaryFraction) + (connection : OAI.EditApproximation.BinaryFraction) (envelope values : Vector OAI.EditApproximation.BinaryFraction M) + (draw : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (allocation : ∀ t, Fin (OAI.EditApproximation.groupSampleCount M Q b (scales t).value) → ℕ) : ℕ := by + have proof_vectorMapWithWork_value_27 {α : Type 0} (d : ℕ) (f : Fin d → Prod.{0, 0} α ℕ) (i : Fin d) : + (OAI.EditApproximation.vectorMapWithWork d f).1.get i = (f i).1 := by + change (Vector.ofFn f |>.map Prod.fst)[i.val] = _ + simp only [Vector.getElem_map, Vector.getElem_ofFn] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + exact + let counts := OAI.EditApproximation.vectorMapWithWork T fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b (scales t) + let count := fun t => OAI.EditApproximation.bitWordValue (counts.1.get t) + let heq : ∀ t, count t = OAI.EditApproximation.groupSampleCount M Q b (scales t).value := by + intro t + simp only [count, counts, proof_vectorMapWithWork_value_27, proof_groupSampleCountWithWork_value_28] + OAI.EditApproximation.vectorMapAllocation T (fun t => OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b (scales t)) + + OAI.EditApproximation.BinaryFraction.groupMemberSourceAllocation scales count connection envelope values (fun t j => draw t (Fin.cast (heq t) j)) + (fun t j => allocation t (Fin.cast (heq t) j)) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def unskippedGuardReadWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) (_center : OAI.EditApproximation.TargetInterval ny) + (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) + (hne : band ≠ []) (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) : Bool × ℕ := + let envelope := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read + let total := OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope.1 + let fb := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b) + let limit := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb.1 + let sumGuard := OAI.EditApproximation.BinaryFraction.leWithWork total.1 limit.1 + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read + let wideGuard := OAI.EditApproximation.actionMemberWithWork rounded.1.get wide + let gapGuard := OAI.EditApproximation.allWithWork (fun i => + let sourceLength := OAI.EditApproximation.binaryNaturalSubtractWithWork (OAI.EditApproximation.sourceChild parent i).hi (OAI.EditApproximation.sourceChild parent i).lo + let gap := OAI.EditApproximation.BinaryFraction.stateGapWithWork (OAI.EditApproximation.bitWordValue sourceLength.1) (rounded.1.get i) + let bound := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) (envelope.1.get i) + let test := OAI.EditApproximation.BinaryFraction.leWithWork gap.1.absolute bound.1 + (test.1, sourceLength.2 + gap.2 + bound.2 + test.2 + 3)) (List.finRange M) + (sumGuard.1 && wideGuard.1 && gapGuard.1, + envelope.2 + total.2 + fb.2 + limit.2 + sumGuard.2 + rounded.2 + wideGuard.2 + gapGuard.2 + 5) + +def queryGroupInputsWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let labels := OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun i => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1)) labels.1 + (inputs.1, labels.2 + inputs.2 + 1) + +def coarseIndexedRootWithWork {B d : ℕ} (k q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : OAI.EditApproximation.BinaryFraction × ℕ := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_coarseDenominatorWithWork_value_127 (allowanceDen : List.{0} Bool) (q : List.{0} Bool) (L : List.{0} Bool) (branching : List.{0} Bool) (D : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.coarseDenominatorWithWork allowanceDen q L branching D).1 = + OAI.EditApproximation.coarseCommonDenominator (OAI.EditApproximation.bitWordValue allowanceDen) (OAI.EditApproximation.bitWordValue q) + (OAI.EditApproximation.bitWordValue L) (OAI.EditApproximation.bitWordValue branching) D := by + simp only [OAI.EditApproximation.coarseDenominatorWithWork, proof_trimBitWordWithWork_value_6, + proof_bitMulWithWork_value_0, proof_bitPowerWithWork_value_76, OAI.EditApproximation.coarseCommonDenominator] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_coarseRootDenominator_value_128 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 = OAI.EditApproximation.coarseCommonDenominator 1 q L B d := by + simp only [OAI.EditApproximation.BinaryFraction.coarseRootDenominator, proof_coarseDenominatorWithWork_value_127, proof_bitWordValue_bits_15] + have proof_coarseRootDenominator_pos_126 (B : ℕ) (q : ℕ) (L : ℕ) (d : ℕ) (hB : LT.lt.{0} 0 B) (hq : LT.lt.{0} 0 q) (hL : LT.lt.{0} 0 L) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d).1 := by + rw [proof_coarseRootDenominator_value_128] + unfold OAI.EditApproximation.coarseCommonDenominator + positivity + exact + let den := OAI.EditApproximation.BinaryFraction.coarseRootDenominator B q L d + let denPos := proof_coarseRootDenominator_pos_126 B q L d hB hq hL + let two := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos 2 + let allowance := OAI.EditApproximation.BinaryFraction.coarseGridNatWithWork den.1 denPos k + let evaluated := OAI.EditApproximation.BinaryFraction.coarseIndexedWithWork k q L (OAI.EditApproximation.coarseEntryWidth x y) x y two.1 d 0 draws allowance.1 0 + (OAI.EditApproximation.BinaryFraction.coarseBinaryRead evaluated.1 (OAI.EditApproximation.coarseRootShift k).val, + den.2 + two.2 + allowance.2 + evaluated.2 + 1) + +def queryGroupInputsAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (h : OAI.EditApproximation.BinaryFraction) + (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b h.value) → ℕ) : ℕ := + let build := fun i : Fin M => + let states := OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h + let tagged := OAI.EditApproximation.arithmeticMapWithWork (fun r => ((i, r), 1)) states.1 + (tagged.1, states.2 + tagged.2 + 1) + OAI.EditApproximation.BinaryFraction.queryGroupLabelsAllocation M Q b h draw allocation + OAI.EditApproximation.arithmeticFlatMapAllocation build + (fun i => OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesAllocation (ny := ny) parent b exponent cell i h + + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 1) (OAI.EditApproximation.BinaryFraction.queryGroupRoundedStatesWithWork (ny := ny) parent b exponent cell i h).1) + (OAI.EditApproximation.BinaryFraction.queryGroupLabelsWithWork M Q b h draw).1 + +def unskippedGuardReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (_center : OAI.EditApproximation.TargetInterval ny) (b exponent : ℕ) (F : OAI.EditApproximation.BinaryFraction) + (band wide : List (Fin M → OAI.EditApproximation.TargetInterval ny)) (hne : band ≠ []) + (read : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let envelope := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b band read).1 + let total := (OAI.EditApproximation.BinaryFraction.bandMassTotalWithWork envelope).1 + let fb := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork F (OAI.EditApproximation.BinaryFraction.nat b)).1 + let limit := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 64) fb).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b band hne read).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b band read allocation + OAI.EditApproximation.BinaryFraction.bandMassAllocation envelope + + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation F (OAI.EditApproximation.BinaryFraction.nat b) + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.nat 64) fb + OAI.EditApproximation.BinaryFraction.leAllocation total limit + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b band hne read allocation + OAI.EditApproximation.actionMemberAllocation rounded.get wide + + OAI.EditApproximation.allAllocation (OAI.EditApproximation.BinaryFraction.gapGuardAllocation parent envelope rounded) (List.finRange M) + +def queryGroupInputsTransportWithWork {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsWithWork parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def coarseIndexedCandidateWithWork {B d : ℕ} (q L : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B d) : + OAI.EditApproximation.BinaryFraction × ℕ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + let root := OAI.EditApproximation.BinaryFraction.coarseIndexedRootWithWork k q L hB hq hL x y draws + let shifted := OAI.EditApproximation.BinaryFraction.canonicalAddWithWork root.1 (OAI.EditApproximation.BinaryFraction.nat k) + let doubled := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.nat 2) shifted.1 + (doubled.1, root.2 + shifted.2 + doubled.2 + Nat.size k + 3) + +def preparedUnskippedReadAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (center : OAI.EditApproximation.TargetInterval ny) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (readAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) : ℕ := + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read readAllocation + + if hband : band = [] then 0 else + let wide := (OAI.EditApproximation.wideActionGridWithWork M parent center b P).1 + OAI.EditApproximation.wideActionGridAllocation M parent center b P + wide.length + + OAI.EditApproximation.BinaryFraction.unskippedGuardReadAllocation parent center b exponent F band (wide.map Vector.get) hband initial initialAllocation + + if (OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band (wide.map Vector.get) hband initial).1 then 3 else 0 + +def queryGroupInputsTransportAllocation {nx ny M : ℕ} (parent : OAI.EditApproximation.TargetInterval nx) + (b exponent Q : ℕ) (cell : ℕ × ℕ) (word : OAI.EditApproximation.BinaryFraction) (scale : ℚ) + (hv : word.value = scale) (draw : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → Fin M × ℕ) + (allocation : Fin (OAI.EditApproximation.groupSampleCount M Q b scale) → ℕ) : ℕ := + OAI.EditApproximation.BinaryFraction.queryGroupInputsAllocation (ny := ny) parent b exponent Q cell word + (fun sample => draw (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + (fun sample => allocation (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) hv) sample)) + +def preparedUnskippedReadWithWorkRaw {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) (b P exponent : ℕ) (tau F : OAI.EditApproximation.BinaryFraction) + (read initial : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (center : OAI.EditApproximation.TargetInterval ny) : Option (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) read + if hband : band.1 = [] then (none, band.2 + 1) else + let wide := OAI.EditApproximation.wideActionGridWithWork M parent center b P + let guard := OAI.EditApproximation.BinaryFraction.unskippedGuardReadWithWork parent center b exponent F band.1 + (wide.1.map Vector.get) hband initial + if guard.1 = true then + (some ⟨center, band.1, hband⟩, band.2 + wide.2 + guard.2 + wide.1.length + 3) + else (none, band.2 + wide.2 + guard.2 + wide.1.length + 2) + +def coarseIndexedInitialWithWork {B d : ℕ} (q L N : ℕ) + (hB : 0 < B) (hq : 0 < q) (hL : 0 < L) (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ × ℕ := + let long := OAI.EditApproximation.binaryNaturalCompareWithWork (2 * x.length) y.length + if long.1 = .lt then (min N y.length, long.2 + Nat.size N + Nat.size y.length + 4) else + let equal := OAI.EditApproximation.BinaryFraction.naturalListEqualWithWork x y + if equal.1 then (0, long.2 + equal.2 + 3) else + let roots := OAI.EditApproximation.arithmeticMapWithWork (fun i => OAI.EditApproximation.BinaryFraction.coarseIndexedCandidateWithWork q L hB hq hL x y i (draws i)) + (List.finRange (Nat.clog 2 (OAI.EditApproximation.coarseEntryWidth x y) + 1)) + let smallest := OAI.EditApproximation.BinaryFraction.coarseMinimumWithWork roots.1 + let rounded := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork smallest.1 + let result := OAI.EditApproximation.wordMinWithWork N.bits rounded.1 + (OAI.EditApproximation.bitWordValue result.1, long.2 + equal.2 + roots.2 + smallest.2 + rounded.2 + result.2 + Nat.size N + 6) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {ny M T : ℕ} (b exponent Q : ℕ) + (initial current : Fin M → TargetInterval ny → BinaryFraction × ℕ) + (initialAllocation currentAllocation : Fin M → TargetInterval ny → ℕ) + (scales : Fin T → BinaryFraction) + (draw : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M) + (drawSource : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → Fin M × ℕ) + (drawAllocation : ∀ t, Fin (groupSampleCount M Q b (scales t).value) → ℕ) + +def unskippedEstimateSourceWithWorkRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : OAI.EditApproximation.BinaryFraction × ℕ := + let mass := OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial + let values := OAI.EditApproximation.vectorMapWithWork M fun i => current i (rounded.1.get i) + let connection := OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.1.get + let result := OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceWithWork Q b scales connection.1 mass.1 values.1 drawSource + (result.1, mass.2 + rounded.2 + values.2 + connection.2 + result.2 + 5) + +def unskippedEstimateSourceAllocationRaw (member : (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + let mass := (OAI.EditApproximation.BinaryFraction.envelopeVectorReadWithWork b member.actions initial).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b member.actions member.nonempty initial).1 + let values := (OAI.EditApproximation.vectorMapWithWork M (fun i => current i (rounded.get i))).1 + let connection := (OAI.EditApproximation.BinaryFraction.endpointConnectionWithWork member.center rounded.get).1 + OAI.EditApproximation.BinaryFraction.envelopeVectorReadAllocation b member.actions initial initialAllocation + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b member.actions member.nonempty initial initialAllocation + + OAI.EditApproximation.vectorMapAllocation M (fun i => currentAllocation i (rounded.get i)) + + OAI.EditApproximation.BinaryFraction.endpointConnectionAllocation member.center rounded.get + OAI.EditApproximation.BinaryFraction.countedGroupMemberSourceAllocation Q b scales connection mass values drawSource drawAllocation + +def chooseUnskippedSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : (OAI.EditApproximation.RawUnskippedBand M ny) × ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupWithWork members hne + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + +def chooseUnskippedSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) : ℕ := + OAI.EditApproximation.BinaryFraction.selectGroupAllocation members + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceWithWorkRaw b exponent Q initial current scales drawSource) + (OAI.EditApproximation.BinaryFraction.unskippedEstimateSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation) + +def sampledGroupActionSourceWithWorkRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : + OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval ny) (Fin M × OAI.EditApproximation.TargetInterval ny) M × ℕ := + let selected := OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current scales drawSource members hne + let rounded := OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.1.actions selected.1.nonempty initial + let result := OAI.EditApproximation.BinaryFraction.endpointActionWithWork selected.1.center rounded.1.get + (result.1, selected.2 + rounded.2 + result.2 + 3) + +def sampledGroupActionSourceAllocationRaw (members : List (OAI.EditApproximation.RawUnskippedBand M ny)) (hne : members ≠ []) : ℕ := + let selected := (OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceWithWorkRaw b exponent Q initial current + scales drawSource members hne).1 + let rounded := (OAI.EditApproximation.BinaryFraction.roundedBandReadWithWork exponent b selected.actions selected.nonempty initial).1 + OAI.EditApproximation.BinaryFraction.chooseUnskippedSourceAllocationRaw b exponent Q initial current + initialAllocation currentAllocation scales drawSource drawAllocation members + + OAI.EditApproximation.BinaryFraction.roundedBandReadAllocation exponent b selected.actions selected.nonempty initial initialAllocation + + OAI.EditApproximation.BinaryFraction.endpointActionAllocation selected.center rounded.get + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def preparedOnlineReadWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child + let setup := OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band.1 + let G := setup.1 + let accepted := OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G, setup] + rw [proof_onlineIndexSetupWithWork_value_129] + positivity) integer + if hband : band.1 = [] then (none, band.2 + setup.2 + accepted.2 + 1) else + let guard := OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center + if guard.1.isSome then + let sampled := OAI.EditApproximation.BinaryFraction.countedSampledOnlineReadWithWork center b initial table eta kappa band.1 hband + G (G ^ 80) t accepted.1 + (some sampled.1, band.2 + setup.2 + accepted.2 + guard.2 + sampled.2 + 2) + else (none, band.2 + setup.2 + accepted.2 + guard.2 + 1) + +def preparedOnlineReadAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (P F exponent H b : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau eta kappa : OAI.EditApproximation.BinaryFraction) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (table : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) (_hc : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ R) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (tableAllocation : ℕ → Fin M × OAI.EditApproximation.TargetInterval target.length → ℕ) + + + (t : ℕ) (center : OAI.EditApproximation.TargetInterval target.length) (integer : ℕ) : ℕ := by + have proof_arithmeticFlatMapWithWork_value_69 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} (List.{0} β) ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticFlatMapWithWork f values).1 = values.flatMap (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticFlatMapWithWork, ih, List.flatMap_cons] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_memberByWithWork_value_71 {α : Type 0} (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (a : α) (xs : List.{0} α) : + (OAI.EditApproximation.memberByWithWork equal a xs).1 = true ↔ a ∈ xs := by + induction xs with + | nil => simp only [OAI.EditApproximation.memberByWithWork, Bool.false_eq_true, List.not_mem_nil] + | cons b xs ih => simp only [OAI.EditApproximation.memberByWithWork, Bool.or_eq_true, heq, ih, List.mem_cons] + have proof_dedupByWithWork_value_72 {α : Type 0} [instLocal1 : DecidableEq.{0 + 1} α] (equal : α → α → Prod.{0, 0} Bool ℕ) (heq : ∀ (a b : α), Eq.{1} (equal a b).1 Bool.true ↔ Eq.{0 + 1} a b) (xs : List.{0} α) : + (OAI.EditApproximation.dedupByWithWork equal xs).1 = xs.dedup := by + induction xs with + | nil => rfl + | cons a rest ih => + have hm := proof_memberByWithWork_value_71 equal heq a rest + have ht : (OAI.EditApproximation.memberByWithWork equal a rest).1 = decide (a ∈ rest) := + Bool.eq_iff_iff.mpr (by simpa only [decide_eq_true_eq] using hm) + simp only [OAI.EditApproximation.dedupByWithWork, ht, ih, List.dedup_cons, decide_eq_true_eq] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_coordinateEqualWithWork_value_75 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.coordinateEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.coordinateEqualWithWork, Bool.and_eq_true, proof_naturalEqualWithWork_value_74] + constructor + · rintro ⟨⟨hc, hl⟩, hh⟩ + have hi : a.1 = b.1 := Fin.ext hc + have hq : a.2 = b.2 := by + rcases a with ⟨i, q⟩ + rcases b with ⟨j, r⟩ + cases q + cases r + cases hl + cases hh + rfl + exact Prod.ext hi hq + · intro h + subst b + exact ⟨⟨rfl, rfl⟩, rfl⟩ + have proof_bandCoordinatesWithWork_value_68 {M : ℕ} {n : ℕ} (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork band).1 = OAI.EditApproximation.listedBandCoordinates band := by + simp only [OAI.EditApproximation.BinaryFraction.bandCoordinatesWithWork, proof_dedupByWithWork_value_72 _ proof_coordinateEqualWithWork_value_75, + proof_arithmeticFlatMapWithWork_value_69, proof_arithmeticMapWithWork_value_70, OAI.EditApproximation.listedBandCoordinates, + List.ofFn_eq_map] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_onlineIndexSetupWithWork_value_129 {M : ℕ} {n : ℕ} (H : ℕ) (band : List.{0} (Fin M → OAI.EditApproximation.TargetInterval n)) : + (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 = H + (OAI.EditApproximation.listedBandCoordinates band).length + 2 := by + simp only [OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork, proof_binaryNaturalAddWithWork_value_52, proof_bandCoordinatesWithWork_value_68] + exact + let band := (OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadWithWork parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child).1 + let G := (OAI.EditApproximation.BinaryFraction.onlineIndexSetupWithWork H band).1 + let accepted := (OAI.EditApproximation.BinaryFraction.reduceOnlineIntegerWithWork (G ^ 80) (by + dsimp only [G]; rw [proof_onlineIndexSetupWithWork_value_129]; positivity) integer).1 + OAI.EditApproximation.BinaryFraction.preparedRepresentativeReadAllocation parent center (parent.hi - parent.lo) b P + tau (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) child childAllocation + + OAI.EditApproximation.BinaryFraction.onlineIndexSetupAllocation H band + OAI.EditApproximation.reduceOnlineIntegerAllocation (G ^ 80) integer + + if hband : band = [] then 0 else + OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation + + if (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial center).1.isSome then + OAI.EditApproximation.BinaryFraction.countedSampledOnlineAllocation center b initial initialAllocation table tableAllocation eta kappa + band hband G (G ^ 80) t accepted + 1 + else 0 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion + + +inductive Step (substitutions : Bool) {Alpha : Type u} : List Alpha → List Alpha → Prop + | insert (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ q) (p ++ a :: q) + | delete (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ a :: q) (p ++ q) + | substitute (h : substitutions = true) (p q : List Alpha) (a b : Alpha) : + Step substitutions (p ++ a :: q) (p ++ b :: q) + +inductive Script (substitutions : Bool) {Alpha : Type u} : ℕ → List Alpha → List Alpha → Prop + | nil (x : List Alpha) : Script substitutions 0 x x + | cons {n : ℕ} {x y z : List Alpha} (first : OAI.EditDistortion.Step substitutions x y) + (rest : Script substitutions n y z) : Script substitutions (n + 1) x z + +noncomputable def edit {Alpha : Type u} (x y : List Alpha) : ℕ := + sInf {n | Script true n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditDistortion +variable {Alpha : Type u} {s : Bool} + +noncomputable def cost (s : Bool) (x y : List Alpha) : ℕ := sInf {n | Script s n x y} + + +end OAI.EditDistortion +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.CoarseSourceTree +open Finset EditDistortion + +def word {B : ℕ} {α : Type u} : {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → List α + | _, .leaf letter => letter.toList + | _, .branch children => (List.ofFn fun i => word (children i)).flatten + + +end OAI.EditApproximation.CoarseSourceTree +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def coarseLabelCount {B : ℕ} {α : Type u_1} (Q lam : ℚ) : + {d : ℕ} → OAI.EditApproximation.CoarseSourceTree B α d → OAI.EditApproximation.CoarseThresholdDraws B d → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => 0 + | .branch children, (draws, below) => B + + OAI.EditApproximation.coarseLabelChildren Q lam allowance (fun child => coarseLabelCount Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseIndexedEntryBinaryCost (N B d : ℕ) [NeZero B] (x y : List ℕ) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + (OAI.EditApproximation.BinaryFraction.coarseIndexedInitialWithWork (OAI.EditApproximation.inputHeight N ^ 4) (64 * OAI.EditApproximation.inputHeight N) N + (Nat.pos_of_neZero B) (pow_pos (Nat.two_pow_pos _) _) + (Nat.mul_pos (by decide) (Nat.two_pow_pos _)) x y draws).2 + +def coarseInitialLabelCount {α : Type u_1} [DecidableEq α] + (B d : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B d) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseLabelCount Q lam (OAI.EditApproximation.coarseEntryTree B d x y) (draws i) + (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset EditDistortion + +def coarseChildrenCost {B D : ℕ} {α : Type u} (k : ℕ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ) : + List (OAI.EditApproximation.CoarseSourceTree B α D) → ℕ → Fin (2 * k + 1) → ℕ + | [], _, _ => 0 + | child :: rest, start, shift => + univ.inf' univ_nonempty (fun next => value child start next + 2 * Nat.dist shift.val next.val) + + coarseChildrenCost k value rest (start + child.word.length) shift + +def coarseShiftCost {B : ℕ} {α : Type u} [DecidableEq α] (k : ℕ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → ℕ → Fin (2 * k + 1) → ℕ + | _, .leaf none, _, _ => 0 + | _, .leaf (some letter), start, shift => + if (frame[start + shift.val]?.getD none) = some letter then 0 else 1 + | _, .branch children, start, shift => + OAI.EditApproximation.coarseChildrenCost k (fun child => coarseShiftCost k frame child) + (List.ofFn children) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset +open EditDistortion + +instance targetIntervalFintype (n : ℕ) : Fintype (OAI.EditApproximation.TargetInterval n) := by + have proof_targetStates_complete_12 (n : ℕ) (q : OAI.EditApproximation.TargetInterval n) : q ∈ OAI.EditApproximation.targetStates n := by + apply List.mem_flatMap.mpr + refine ⟨q.lo, List.mem_range.mpr (Nat.lt_succ_of_le (q.ordered.trans q.valid)), ?_⟩ + apply List.mem_filterMap.mpr + refine ⟨q.hi, List.mem_range.mpr (Nat.lt_succ_of_le q.valid), ?_⟩ + rw [OAI.EditApproximation.makeTargetState, dite_eq_left (show q.lo ≤ q.hi ∧ q.hi ≤ n from ⟨q.ordered, q.valid⟩)] + exact + Fintype.ofList (OAI.EditApproximation.targetStates n) (proof_targetStates_complete_12 n) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.UnskippedBand +open Finset + +def actions {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) := + OAI.EditApproximation.representativeBandActions source target parent member.center b P tau + ((2 : ℚ) ^ (-(thetaExponent : ℤ))) child + +def envelope {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) (i : Fin M) : ℚ := + OAI.EditApproximation.bandChildEnvelope b member.actions initial i + +def rounded {α : Type u_1} {source target : List α} {M : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {b P thetaExponent : ℕ} + {tau F : ℚ} {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + Fin M → OAI.EditApproximation.TargetInterval target.length := + OAI.EditApproximation.canonicalRoundedBandAction thetaExponent b member.actions member.nonempty initial + +def rationalAction {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} + {parent : OAI.EditApproximation.TargetInterval source.length} {tau F : ℚ} + {child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ} + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) : + OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M := + ⟨member.center, OAI.EditApproximation.endpointActionConnection member.center member.rounded, fun i => (i, member.rounded i)⟩ + + +end OAI.EditApproximation.UnskippedBand +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def unskippedGroupEstimate {T : ℕ} (scales : Fin T → ℚ) (count : Fin T → ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin T, Fin (count scale) → Fin M) : ℚ := + OAI.EditApproximation.groupMemberEstimate scales count (OAI.EditApproximation.endpointActionConnection member.center member.rounded) + member.envelope (fun i => value i (member.rounded i)) draw + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type*} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def groupDyadicScaleAt (M b : ℕ) (F : ℚ) (i : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℚ := + (OAI.EditApproximation.groupDyadicScales M b F).get i + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev CellGroupDraws (M F Q : ℕ) := ∀ b : ℕ, (ℕ × ℕ) → + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M + +abbrev cellScaleReadDraw (M b Q : ℕ) (F : ℚ) := + ∀ (t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length), + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → Fin M × ℕ + +abbrev GroupScalarKey (M F Q : ℕ) := + Σ key : ℕ × (ℕ × ℕ), Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale)) + +abbrev CountedCellGroupDraws (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M × ℕ + +abbrev CellGroupSourceAllocations (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F t)) → ℕ + +abbrev CountedCellGroupAllocations (M F Q : ℕ) := + ∀ b : ℕ, ∀ _cell : ℕ × ℕ, ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → ℕ + +abbrev CellGroupReadDraws (M F Q : ℕ) := ∀ (b : ℕ) (_cell : ℕ × ℕ), + OAI.EditApproximation.cellScaleReadDraw M b Q F + +def groupScalarKeys (M F Q : ℕ) (groups : List (ℕ × (ℕ × ℕ))) : List (OAI.EditApproximation.GroupScalarKey M F Q) := + groups.flatMap fun (key : ℕ × (ℕ × ℕ)) => + (List.finRange (OAI.EditApproximation.groupDyadicScales M key.1 F).length).flatMap + fun (scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length) => + (List.finRange (OAI.EditApproximation.groupSampleCount M Q key.1 (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale))).map + fun sample => Sigma.mk key (Sigma.mk scale sample) + +noncomputable def groupDrawFromValues {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List ℚ) : OAI.EditApproximation.CellGroupDraws M F Q := by + classical + exact fun b cell scale sample => Fin.ofNat M ⌊OAI.EditApproximation.finiteAnswerTable keys values ⟨(b, cell), scale, sample⟩⌋₊ + +def queryGroupKeyEqualWithWork {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : Bool × ℕ := + let scale := OAI.EditApproximation.naturalEqualWithWork a.1.1 b.1.1 + let lo := OAI.EditApproximation.naturalEqualWithWork a.1.2.1 b.1.2.1 + let hi := OAI.EditApproximation.naturalEqualWithWork a.1.2.2 b.1.2.2 + let label := OAI.EditApproximation.naturalEqualWithWork a.2.1.val b.2.1.val + let sample := OAI.EditApproximation.naturalEqualWithWork a.2.2.val b.2.2.val + (scale.1 && lo.1 && hi.1 && label.1 && sample.1, + scale.2 + lo.2 + hi.2 + label.2 + sample.2 + 4) + +def queryGroupKeyEqualAllocation {M F Q : ℕ} (a b : OAI.EditApproximation.GroupScalarKey M F Q) : ℕ := + OAI.EditApproximation.naturalEqualAllocation a.1.1 b.1.1 + OAI.EditApproximation.naturalEqualAllocation a.1.2.1 b.1.2.1 + + OAI.EditApproximation.naturalEqualAllocation a.1.2.2 b.1.2.2 + OAI.EditApproximation.naturalEqualAllocation a.2.1.val b.2.1.val + + OAI.EditApproximation.naturalEqualAllocation a.2.2.val b.2.2.val + 4 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + +open Finset + +def queryGroupKeySamplesWithWork (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : + List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let samples := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, scales.1.length + count.2 + labeled.2 + coordinates.length + 3)) indices + (samples.1, scales.2 + 4 * scales.1.length + samples.2 + eb + 4) + +def querySharedCellInputsWithWork {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1)) indices + (inputs.1, scales.2 + 4 * scales.1.length + inputs.2 + eb + 4) + +def groupKeySampleBlock {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + let labeled := OAI.EditApproximation.arithmeticMapWithWork (fun sample => + ((⟨(b, cell), scale, sample⟩ : OAI.EditApproximation.GroupScalarKey M F Q), 2)) coordinates + (labeled.1, raw.length + count.2 + labeled.2 + coordinates.length + 3) + +def groupKeySampleBlockAllocation {M F Q : ℕ} (b : ℕ) (raw : List OAI.EditApproximation.BinaryFraction) + (hs : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F) (_cell : ℕ × ℕ) + (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_wordMinWithWork_value_29 (a : List.{0} Bool) (b : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.wordMinWithWork a b).1 = min (OAI.EditApproximation.bitWordValue a) (OAI.EditApproximation.bitWordValue b) := by + unfold OAI.EditApproximation.wordMinWithWork + dsimp only + split_ifs with h + · exact (min_eq_left ((proof_wordLEWithWork_value_26 a b).mp h)).symm + · exact (min_eq_right (le_of_not_ge (fun hle => h ((proof_wordLEWithWork_value_26 a b).mpr hle)))).symm + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitCeilDivWithWork_value_30 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitCeilDivWithWork divisor bits).1 = + ⌈((OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor)⌉₊ := by + let q := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + let r := OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 + have h := proof_bitDivModWithWork_value_23 divisor bits hd + have heq : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * q + r := h.1 + have hr : r < OAI.EditApproximation.bitWordValue divisor := h.2 + have hdQ : (0 : ℚ) < OAI.EditApproximation.bitWordValue divisor := by exact_mod_cast hd + unfold OAI.EditApproximation.bitCeilDivWithWork + dsimp only + split_ifs with hz + · have hr0 : r = 0 := by + exact (proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).1 hz + have hratio : (OAI.EditApproximation.bitWordValue bits : ℚ) / OAI.EditApproximation.bitWordValue divisor = (q : ℚ) := by + apply (div_eq_iff hdQ.ne').mpr + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits = q * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr0]) + rw [hratio] + exact (Nat.ceil_natCast q).symm + · have hr0 : r ≠ 0 := by + intro hzero + exact hz ((proof_bitCompareWithWork_eq_3 (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 []).2 hzero) + rw [proof_bitAddWithWork_value_2] + change q + 1 + 0 = _ + simp only [Nat.add_zero] + symm + apply (Nat.ceil_eq_iff (by omega : q + 1 ≠ 0)).mpr + constructor + · simp only [Nat.add_sub_cancel] + rw [lt_div_iff₀ hdQ] + exact_mod_cast (show q * OAI.EditApproximation.bitWordValue divisor < OAI.EditApproximation.bitWordValue bits by + nlinarith only [heq, Nat.pos_of_ne_zero hr0]) + · rw [div_le_iff₀ hdQ] + push_cast + exact_mod_cast (show OAI.EditApproximation.bitWordValue bits ≤ (q + 1) * OAI.EditApproximation.bitWordValue divisor by nlinarith only [heq, hr]) + have proof_naturalCeilingWithWork_value_31 (a : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (a.naturalCeilingWithWork).1 = ⌈a.value⌉₊ := by + cases hs : a.numerator.negative + · simpa only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, Bool.false_eq_true, ↓reduceIte, + OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Int.cast_natCast] using + proof_bitCeilDivWithWork_value_30 a.denominator a.numerator.bits a.denominator_pos + · have hn : a.value ≤ 0 := by + (simp only [OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, ↓reduceIte, Int.cast_neg, Int.cast_natCast]) + exact div_nonpos_of_nonpos_of_nonneg (neg_nonpos.mpr (Nat.cast_nonneg _)) (Nat.cast_nonneg _) + (simp only [OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork, hs, ↓reduceIte, OAI.EditApproximation.bitWordValue]) + exact (Nat.ceil_eq_zero.mpr hn).symm + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_canonicalizeWithWork_representation_34 (a : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalizeWithWork a).1.representation = a.representation := by + apply proof_eq_of_num_den_33 + · (simp only [OAI.EditApproximation.BinaryFraction.canonicalizeWithWork, OAI.EditApproximation.BinaryFraction.representation, OAI.EditApproximation.SignedBinary.value, proof_trimBitWordWithWork_value_6]) + · exact proof_trimBitWordWithWork_value_6 a.denominator + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_mulWithWork_value_35 (a : OAI.EditApproximation.SignedBinary) (b : OAI.EditApproximation.SignedBinary) : + (a.mulWithWork b).1.value = a.value * b.value := by + simp only [OAI.EditApproximation.SignedBinary.mulWithWork, OAI.EditApproximation.SignedBinary.value, proof_bitMulWithWork_value_0] + cases a.negative <;> cases b.negative <;> simp [OAI.EditApproximation.signedMagnitude] + have proof_mulWithWork_representation_36 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.mulWithWork b).1.representation = a.representation.mul b.representation := by + apply proof_eq_of_num_den_33 + · exact proof_mulWithWork_value_35 a.numerator b.numerator + · exact proof_bitMulWithWork_value_0 a.denominator b.denominator + have proof_canonicalMulWithWork_representation_37 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.representation = a.representation.mul b.representation := by + rw [OAI.EditApproximation.BinaryFraction.canonicalMulWithWork, proof_canonicalizeWithWork_representation_34, proof_mulWithWork_representation_36] + have proof_zero_representation_38 : OAI.EditApproximation.BinaryFraction.zero.representation = OAI.EditApproximation.UnreducedRational.zero := by + apply proof_eq_of_num_den_33 <;> rfl + have proof_invWithWork_representation_39 (a : OAI.EditApproximation.BinaryFraction) : + (a.invWithWork).1.representation = a.representation.inv := by + unfold OAI.EditApproximation.BinaryFraction.invWithWork + dsimp only + split_ifs with h + · have hz : OAI.EditApproximation.bitWordValue a.numerator.bits = 0 := by + simpa only [OAI.EditApproximation.bitWordValue] using (proof_bitCompareWithWork_eq_3 a.numerator.bits []).1 h + have hv : a.numerator.value = 0 := by (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hz]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + exact proof_zero_representation_38 + · have hn : OAI.EditApproximation.bitWordValue a.numerator.bits ≠ 0 := by + intro hz + exact h ((proof_bitCompareWithWork_eq_3 a.numerator.bits []).2 (by simpa [OAI.EditApproximation.bitWordValue] using hz)) + have hv : a.numerator.value ≠ 0 := by + cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, hn]) + (simp only [OAI.EditApproximation.UnreducedRational.inv, OAI.EditApproximation.BinaryFraction.representation, hv, ↓reduceDIte]) + apply proof_eq_of_num_den_33 + · cases hs : a.numerator.negative <;> + simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs, Int.sign_natCast_of_ne_zero hn] + · cases hs : a.numerator.negative <;> (simp [OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, hs]) + have proof_divWithWork_representation_40 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (a.divWithWork b).1.representation = a.representation.div b.representation := by + (simp only [OAI.EditApproximation.BinaryFraction.divWithWork, proof_canonicalMulWithWork_representation_37, proof_invWithWork_representation_39, + OAI.EditApproximation.UnreducedRational.div]) + have proof_value_mul_41 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.mul b).value = a.value * b.value := by + simp [OAI.EditApproximation.UnreducedRational.mul, OAI.EditApproximation.UnreducedRational.value, mul_div_mul_comm] + have proof_value_inv_42 (a : OAI.EditApproximation.UnreducedRational) : a.inv.value = a.value⁻¹ := by + by_cases h : a.num = 0 + · simp [OAI.EditApproximation.UnreducedRational.inv, h, OAI.EditApproximation.UnreducedRational.value, OAI.EditApproximation.UnreducedRational.zero] + · have hn : (a.num.natAbs : ℚ) ≠ 0 := by exact_mod_cast (Int.natAbs_pos.mpr h).ne' + have hd : (a.den : ℚ) ≠ 0 := by exact_mod_cast a.den_pos.ne' + have hsign : ((a.num.sign : ℤ) : ℚ) * a.num = (a.num.natAbs : ℚ) := by + simpa only [Int.cast_mul, Int.cast_natCast] using + congrArg (fun z : ℤ => (z : ℚ)) (Int.sign_mul_self_eq_natAbs a.num) + simp only [OAI.EditApproximation.UnreducedRational.inv, h, ↓reduceDIte, OAI.EditApproximation.UnreducedRational.value] + push_cast + apply eq_inv_of_mul_eq_one_left + field_simp [hn, hd] + exact hsign + have proof_value_div_43 (a : OAI.EditApproximation.UnreducedRational) (b : OAI.EditApproximation.UnreducedRational) : (a.div b).value = a.value / b.value := by + simp [proof_value_mul_41, proof_value_inv_42, OAI.EditApproximation.UnreducedRational.div, div_eq_mul_inv] + have proof_divWithWork_value_44 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.divWithWork a b).1.value = a.value / b.value := by + rw [← proof_representation_value_32, proof_divWithWork_representation_40, + proof_value_div_43, proof_representation_value_32, proof_representation_value_32] + have proof_canonicalMulWithWork_value_45 (a : OAI.EditApproximation.BinaryFraction) (b : OAI.EditApproximation.BinaryFraction) : + (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork a b).1.value = a.value * b.value := by + rw [← proof_representation_value_32, proof_canonicalMulWithWork_representation_37, + proof_value_mul_41, proof_representation_value_32, proof_representation_value_32] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_groupSampleCountWithWork_value_28 (M : ℕ) (Q : ℕ) (b : ℕ) (h : OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b h).1 = OAI.EditApproximation.groupSampleCount M Q b h.value := by + simp only [OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork, proof_wordMinWithWork_value_29, proof_bitWordValue_bits_15, + proof_naturalCeilingWithWork_value_31, proof_divWithWork_value_44, proof_canonicalMulWithWork_value_45, + proof_nat_value_49, OAI.EditApproximation.groupSampleCount] + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + exact + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt raw (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let count := OAI.EditApproximation.BinaryFraction.groupSampleCountWithWork M Q b word + let hc : OAI.EditApproximation.bitWordValue count.1 = OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale) := by + rw [proof_groupSampleCountWithWork_value_28, proof_queryScaleAt_value_88] + rfl + let coordinates := OAI.EditApproximation.queryFinRange (OAI.EditApproximation.bitWordValue count.1) + (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) hc + OAI.EditApproximation.BinaryFraction.groupSampleCountAllocation M Q b word + OAI.EditApproximation.arithmeticMapAllocation (fun _ => 2) coordinates + + 2 * coordinates.length + +def querySharedCellInputsAllocation {nx ny : ℕ} (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (exponent : ℕ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → Fin M × ℕ) + (allocation : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M (2 ^ eb) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q (2 ^ eb) (OAI.EditApproximation.groupDyadicScaleAt M (2 ^ eb) F scale)) → ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + have proof_queryScaleAt_value_88 (words : List.{0} OAI.EditApproximation.BinaryFraction) (scales : List.{0} ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) scales) (i : Fin (List.length.{0} scales)) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words scales h i).value = scales[i.val] := by + subst scales + simp only [OAI.EditApproximation.BinaryFraction.queryScaleAt, List.getElem_map] + have proof_queryGroupScaleAt_value_92 (M : ℕ) (b : ℕ) (F : ℕ) (words : List.{0} OAI.EditApproximation.BinaryFraction) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value words) + (OAI.EditApproximation.groupDyadicScales M b ↑F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b ↑F))) : + (OAI.EditApproximation.BinaryFraction.queryScaleAt words (OAI.EditApproximation.groupDyadicScales M b F) h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := + proof_queryScaleAt_value_88 words (OAI.EditApproximation.groupDyadicScales M b F) h i + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + let build := fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + let states := OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportWithWork (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) + (states.1, states.2 + scales.1.length + 1) + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation build (fun scale => + let word := OAI.EditApproximation.BinaryFraction.queryScaleAt scales.1 (OAI.EditApproximation.groupDyadicScales M b F) hs scale + let hv : word.value = OAI.EditApproximation.groupDyadicScaleAt M b F scale := proof_queryGroupScaleAt_value_92 M b F _ hs scale + OAI.EditApproximation.BinaryFraction.queryGroupInputsTransportAllocation (ny := ny) parent b exponent Q cell word + (OAI.EditApproximation.groupDyadicScaleAt M b F scale) hv (draw scale) (allocation scale)) indices + +def queryGroupKeySamplesAllocation (M F Q eM eb eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let b := 2 ^ eb + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let hs : scales.1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b F := by + simpa only [proof_nat_value_49] using proof_computedGroupScales_value_87 M b F eM eb eF hM rfl hF + let hlen : scales.1.length = (OAI.EditApproximation.groupDyadicScales M b F).length := by + simpa only [List.length_map] using congrArg List.length hs + let indices := OAI.EditApproximation.queryFinRange scales.1.length (OAI.EditApproximation.groupDyadicScales M b F).length hlen + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + 2 * scales.1.length + eb + 1 + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.groupKeySampleBlock (Q := Q) b scales.1 hs cell) + (OAI.EditApproximation.BinaryFraction.groupKeySampleBlockAllocation (Q := Q) b scales.1 hs cell) indices + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction + + +def querySharedInputsWithWork {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) : + List (Fin M × OAI.EditApproximation.TargetInterval ny) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let inputs := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4)) scales.1 + let sorted := OAI.EditApproximation.queryOrderedChildInputsWithWork inputs.1 + (sorted.1, scales.2 + radius.2 + inputs.2 + sorted.2 + 3) + +def queryGroupDrawReadWithWork {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : Fin M × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + exact + let word := OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values ⟨(b, cell), scale, sample⟩ + let floor := OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word.1 + let reduced := OAI.EditApproximation.binaryNaturalDivModWithWork (OAI.EditApproximation.bitWordValue floor.1) M + (⟨OAI.EditApproximation.bitWordValue reduced.2.1, by + rw [(proof_binaryNaturalDivModWithWork_spec_24 _ M (NeZero.pos M)).2] + exact Nat.mod_lt _ (NeZero.pos M)⟩, + word.2 + floor.2 + reduced.2.2 + 3) + +def queryGroupSourceKeysWithWork {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) : List (OAI.EditApproximation.GroupScalarKey M F Q) × ℕ := + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value + let keys := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4)) scales.1 + (keys.1, scales.2 + radius.2 + keys.2 + 2) + +def queryGroupDrawReadAllocation {M F Q : ℕ} [NeZero M] + (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) (values : List OAI.EditApproximation.BinaryFraction) + (b : ℕ) (cell : ℕ × ℕ) (scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length) + (sample : Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale))) : ℕ := + let key : OAI.EditApproximation.GroupScalarKey M F Q := ⟨(b, cell), scale, sample⟩ + let word := (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork OAI.EditApproximation.queryGroupKeyEqualWithWork keys values key).1 + let floor := (OAI.EditApproximation.BinaryFraction.naturalFloorWithWork word).1 + OAI.EditApproximation.BinaryFraction.gatheredLookupAllocation OAI.EditApproximation.queryGroupKeyEqualWithWork OAI.EditApproximation.queryGroupKeyEqualAllocation keys values key + + OAI.EditApproximation.BinaryFraction.naturalFloorAllocation word + OAI.EditApproximation.bitDivModAllocation M.bits (OAI.EditApproximation.bitWordValue floor).bits + +def queryGroupSourceKeysAllocation {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a value : OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : ℕ := + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) q + let sources := OAI.EditApproximation.arithmeticFlatMapWithWork (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) cells.1 + (sources.1, side.2 + cells.2 + sources.2 + eb + exponent + 4) + let allocation := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) q).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) q + + OAI.EditApproximation.arithmeticFlatMapAllocation (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesWithWork M F Q eM eb eF hM hF) + (OAI.EditApproximation.BinaryFraction.queryGroupKeySamplesAllocation M F Q eM eb eF hM hF) cells + eb + exponent + 2 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build allocation (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + +def querySharedInputsAllocation {nx ny : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (parent : OAI.EditApproximation.TargetInterval nx) + (a value : OAI.EditApproximation.BinaryFraction) (query : OAI.EditApproximation.TargetInterval ny) (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (allocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) : ℕ := + let scales := (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a value).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork value).1 + let build := fun eb => + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius) query + let states := OAI.EditApproximation.arithmeticFlatMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) cells.1 + (states.1, side.2 + cells.2 + states.2 + eb + exponent + 4) + let alloc := fun eb => + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb))).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat (2 ^ eb)) + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsWithWork (ny := ny) M F Q eM eb eF hM hF parent exponent cell (draw (2 ^ eb) cell)) + (fun cell => OAI.EditApproximation.BinaryFraction.querySharedCellInputsAllocation (ny := ny) M F Q eM eb eF hM hF parent exponent cell + (draw (2 ^ eb) cell) (allocation (2 ^ eb) cell)) cells + eb + exponent + 2 + let inputs := (OAI.EditApproximation.arithmeticFlatMapWithWork build scales).1 + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a value + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation value + + OAI.EditApproximation.arithmeticFlatMapAllocation build alloc scales + OAI.EditApproximation.queryOrderedChildInputsAllocation inputs + +def preparedCellGroupSourceAllocationRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation currentAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + + + (cell : ℕ × ℕ) : ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := (OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell).1 + let members := (OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers).1 + OAI.EditApproximation.BinaryFraction.cellCentersReadAllocation P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial parentAllocation cell + + OAI.EditApproximation.filterMapAllocation (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) + (fun center => OAI.EditApproximation.BinaryFraction.preparedUnskippedReadAllocation parent center b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) + child initial childAllocation initialAllocation) centers + + if hempty : members = [] then 0 else + OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceAllocationRaw b exponent Q initial current initialAllocation currentAllocation + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) + (fun t j => drawAllocation t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members hempty + 1 + +def preparedCellGroupSourceWithWorkRaw {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F exponent Q : ℕ) (_hb : 0 < b) (_hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial current : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R C : ℕ) (_hr : ∀ i q, (child i q).2 ≤ R) (_hi : ∀ i q, (initial i q).2 ≤ C) + (raw : List OAI.EditApproximation.BinaryFraction) (hraw : raw.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_indexedGroupScales_value_130 (raw : List.{0} OAI.EditApproximation.BinaryFraction) (M : ℕ) (b : ℕ) (F : ℚ) (h : Eq.{1} (List.map.{0, 0} OAI.EditApproximation.BinaryFraction.value raw) (OAI.EditApproximation.groupDyadicScales M b F)) (i : Fin (List.length.{0} (OAI.EditApproximation.groupDyadicScales M b F))) : + (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b F h i).value = OAI.EditApproximation.groupDyadicScaleAt M b F i := by + unfold OAI.EditApproximation.BinaryFraction.indexedGroupScales OAI.EditApproximation.groupDyadicScaleAt + simp only [List.get_eq_getElem] + rw [← List.getElem_map OAI.EditApproximation.BinaryFraction.value (l := raw) (i := i.val) (h := by rw [h]; exact i.isLt)] + simp only [h] + exact + let centers := OAI.EditApproximation.BinaryFraction.cellCentersReadWithWork P F b a (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) parentInitial cell + let members := OAI.EditApproximation.filterMapWithWork + (OAI.EditApproximation.BinaryFraction.preparedUnskippedReadWithWorkRaw parent b P exponent tau (OAI.EditApproximation.BinaryFraction.nat F) child initial) centers.1 + if h : members.1 = [] then (none, centers.2 + members.2 + 1) else + let selected := OAI.EditApproximation.BinaryFraction.sampledGroupActionSourceWithWorkRaw b exponent Q initial current (OAI.EditApproximation.BinaryFraction.indexedGroupScales raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw) + (fun t j => draw t (Fin.cast (congrArg (OAI.EditApproximation.groupSampleCount M Q b) + (proof_indexedGroupScales_value_130 raw M b (OAI.EditApproximation.BinaryFraction.nat F).value hraw t)) j)) members.1 h + (some selected.1, centers.2 + members.2 + selected.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def querySharedInputCover {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (N F exponent Q : ℕ) (a : ℚ) + (initial : OAI.EditApproximation.TargetInterval target.length → ℚ) (q : OAI.EditApproximation.TargetInterval target.length) + (draw : OAI.EditApproximation.CellGroupDraws M F Q) : Finset (Fin M × OAI.EditApproximation.TargetInterval target.length) := + (OAI.EditApproximation.localGroupQueryKeys N F exponent a initial q).toFinset.biUnion fun key => + Finset.univ.biUnion fun scale : Fin (OAI.EditApproximation.groupDyadicScales M key.1 F).length => + OAI.EditApproximation.groupCurrentInputCover source target parent key.1 exponent Q key.2 + (OAI.EditApproximation.groupDyadicScaleAt M key.1 F scale) (draw key.1 key.2 scale) + +def coarseThresholdChildrenCost {B D : ℕ} {α : Type u} + (k : ℕ) (Q lam : ℚ) + (value : OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ) + (allowance : ℚ) : + List (OAI.EditApproximation.CoarseSourceTree B α D × Fin B × OAI.EditApproximation.CoarseThresholdDraws B D) → ℕ → Fin (2 * k + 1) → ℚ + | [], _, _ => 0 + | (child, draw, below) :: rest, start, shift => + let threshold := OAI.EditApproximation.coarseChildThreshold B Q allowance draw + let childMinimum := univ.inf' univ_nonempty (fun next => + value child below (lam * threshold) start next + (2 * Nat.dist shift.val next.val : ℕ)) + OAI.EditApproximation.coarseThresholdContribution threshold (allowance / Q) childMinimum + + coarseThresholdChildrenCost k Q lam value allowance rest (start + child.word.length) shift + +def coarseThresholdEstimate {B : ℕ} {α : Type u} [DecidableEq α] + (k : ℕ) (Q lam : ℚ) (frame : List (Option α)) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ → Fin (2 * k + 1) → ℚ + | _, tree, draws, allowance, start, shift => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf letter, _ => (OAI.EditApproximation.coarseShiftCost k frame (.leaf (B := B) letter) start shift : ℚ) + | .branch children, (draws, below) => + OAI.EditApproximation.coarseThresholdChildrenCost k Q lam + (fun child => coarseThresholdEstimate k Q lam frame child) allowance + (List.ofFn fun i => (children i, draws i, below i)) start shift + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory + +abbrev PhysicalScalarIndex (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : Type := + match key with + | .inl _ => Fin R + | .inr group => Σ _time : Fin R, + Σ scale : Fin (OAI.EditApproximation.groupDyadicScales M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q ((OAI.EditApproximation.dyadicScales N).get group.2.1) + (OAI.EditApproximation.groupDyadicScaleAt M ((OAI.EditApproximation.dyadicScales N).get group.2.1) F scale)) + +def computedPhysicalCoarseDepth (source target : List ℕ) (N : ℕ) + (entry : OAI.EditApproximation.PhysicalEntry (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length) : ℕ := + OAI.EditApproximation.computedCoarseDepth N (OAI.EditApproximation.coarseEntryWidth (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi)) + +abbrev PhysicalScalarKey (M J N n exponent F Q R B : ℕ) := + Σ key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B, OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key + +instance physicalScalarIndexFintype (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalCommonKey M J N n exponent B) : + Fintype (OAI.EditApproximation.PhysicalScalarIndex M J N n exponent F Q R B key) := by + cases key <;> dsimp only [OAI.EditApproximation.PhysicalScalarIndex] <;> infer_instance + +def physicalScalarRange (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key.1 with + | .inl online => online.2.val.val + | .inr _ => M + +instance physicalScalarRangeNeZero (M J N n exponent F Q R B : ℕ) [NeZero M] + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + NeZero (OAI.EditApproximation.physicalScalarRange M J N n exponent F Q R B key) := by + rcases key with ⟨key, index⟩ + cases key <;> dsimp only [OAI.EditApproximation.physicalScalarRange] <;> infer_instance + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def queryGroupSourceGather {ι : Type u_1} {β : Type u_2} {n : ℕ} (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) : OAI.EditApproximation.BitQuery ι β := + let query := initial q + .charge query.2 ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a query.1 q)).bind + fun keys => OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + +def physicalScalarCodeWithWork {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ × ℕ := + match key with + | ⟨.inl online, time⟩ => + let entry := OAI.EditApproximation.physicalEntryCodeWithWork (online.1.1.val, online.1.2.2) + let first := OAI.EditApproximation.naturalPairWithWork online.2.val.val time.val + let second := OAI.EditApproximation.naturalPairWithWork online.1.2.1.val first.1 + let last := OAI.EditApproximation.naturalPairWithWork entry.1 second.1 + (2 * last.1, entry.2 + first.2 + second.2 + last.2 + 2) + | ⟨.inr group, index⟩ => + let node := OAI.EditApproximation.physicalNodeCodeWithWork group.1.val + let a := OAI.EditApproximation.naturalPairWithWork index.2.1.val index.2.2.val + let b := OAI.EditApproximation.naturalPairWithWork index.1.val a.1 + let c := OAI.EditApproximation.naturalPairWithWork group.2.2.2.val b.1 + let d := OAI.EditApproximation.naturalPairWithWork group.2.2.1.val c.1 + let e := OAI.EditApproximation.naturalPairWithWork group.2.1.val d.1 + let f := OAI.EditApproximation.naturalPairWithWork node.1 e.1 + (2 * f.1 + 1, node.2 + a.2 + b.2 + c.2 + d.2 + e.2 + f.2 + 3) + +def physicalScalarCodeAllocation {M J N n exponent F Q R B : ℕ} + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, _⟩ => 2 * online.1.1.val.1.val + J + 20 + | ⟨.inr group, _⟩ => 2 * group.1.val.1.val + J + 25 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +abbrev PhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) + +def physicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + if hb : key.1 ∈ OAI.EditApproximation.dyadicScales N then + if hr : 0 < range ∧ range ≤ B then + .read ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 hb, key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range hr.1 hr.2), time⟩ .done + else .done 0 + else .done 0 + +def physicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => .read ⟨.inr key, ⟨time, scale, sample⟩⟩ .done + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +abbrev BitPhysicalGroupQueries (b : ℕ) := + ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction + +def queryPhysicalScalarRead (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.physicalScalarCodeWithWork key).2 + 1) (.read key .done) + +def queryPhysicalScalarGroupQueriesAt (key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent) (time : Fin R) : + OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B ((OAI.EditApproximation.dyadicScales N).get key.2.1) := + fun scale sample => OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inr key, ⟨time, scale, sample⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory +variable {α : Type u_1} {source target : List α} {M b P thetaExponent : ℕ} {parent : TargetInterval source.length} {tau F : ℚ} {child initial : Fin M → TargetInterval target.length → ℚ} + +def dyadicUnskippedGroupEstimate (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (member : OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : ℚ := + OAI.EditApproximation.unskippedGroupEstimate (OAI.EditApproximation.groupDyadicScaleAt M b F) + (fun scale => OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) value member draw + +def chooseUnskippedGroup (Q : ℕ) + (value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) + (members : List (OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial)) + (hnonempty : members ≠ []) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + OAI.EditApproximation.UnskippedBand source target parent b P thetaExponent tau F child initial := + OAI.EditApproximation.selectGroupMember members hnonempty (fun member => OAI.EditApproximation.dyadicUnskippedGroupEstimate Q value member draw) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset + +def chooseCellGroupAction {α : Type u_1} (source target : List α) {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) (b P F thetaExponent Q : ℕ) (tau a : ℚ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → ℚ) + (child initial value : Fin M → OAI.EditApproximation.TargetInterval target.length → ℚ) (cell : ℕ × ℕ) + (draw : ∀ scale : Fin (OAI.EditApproximation.groupDyadicScales M b F).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b F scale)) → Fin M) : + Option (OAI.EditApproximation.RationalBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) := + let members := OAI.EditApproximation.cellUnskippedBands source target parent b P F thetaExponent tau a parentInitial child initial cell + if h : members = [] then none else some (OAI.EditApproximation.chooseUnskippedGroup Q value members h draw).rationalAction + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M : ℕ} (source target : List α) (parent : TargetInterval source.length) (N P F exponent Q : ℕ) (tau a : ℚ) (parentInitial : TargetInterval target.length → ℚ) (child initial current : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalGroupCones_8) "theta" => (2 : ℚ) ^ (-(exponent : ℤ)) + +def localCellGroupActions (q : OAI.EditApproximation.TargetInterval target.length) : List (OAI.EditApproximation.PhysicalRationalAction M target.length) := + ((OAI.EditApproximation.dyadicScales N).filter fun (b : ℕ) => decide + (parentInitial q / (16 * F) ≤ b ∧ (b : ℚ) ≤ 8 * a * parentInitial q)).flatMap fun (b : ℕ) => + (OAI.EditApproximation.localTargetCells (theta * b) ⌈parentInitial q⌉₊ q).filterMap fun cell => + OAI.EditApproximation.chooseCellGroupAction source target parent b P F exponent Q tau a parentInitial + child initial current cell (draw b cell) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localRefinementStepQuery : OAI.EditApproximation.FiniteQuery ι := by + have proof_mixedRadix_injective_84 {radix : ℕ} {lo : ℕ} {lo' : ℕ} {hi : ℕ} {hi' : ℕ} (hlo : LT.lt.{0} lo radix) (hlo' : LT.lt.{0} lo' radix) (heq : Eq.{1} (HAdd.hAdd.{0, 0, 0} lo (HMul.hMul.{0, 0, 0} radix hi)) (HAdd.hAdd.{0, 0, 0} lo' (HMul.hMul.{0, 0, 0} radix hi'))) : lo = lo' ∧ hi = hi' := by + have hmod := congrArg (fun n => n % radix) heq + simp only [Nat.add_mul_mod_self_left, Nat.mod_eq_of_lt hlo, Nat.mod_eq_of_lt hlo'] at hmod + refine ⟨hmod, ?_⟩ + apply Nat.mul_left_cancel (by omega : 0 < radix) + omega + have proof_childInputCode_injective_83 (M : ℕ) (n : ℕ) : + Function.Injective (@OAI.EditApproximation.childInputCode M n) := by + rintro ⟨i, q⟩ ⟨i', q'⟩ heq + obtain ⟨hi, hq⟩ := proof_mixedRadix_injective_84 i.isLt i'.isLt heq + have hqlo : q.lo < n + 1 := by have := q.ordered.trans q.valid; omega + have hqlo' : q'.lo < n + 1 := by have := q'.ordered.trans q'.valid; omega + obtain ⟨hlo, hhi⟩ := proof_mixedRadix_injective_84 hqlo hqlo' hq + have hqeq : q = q' := by cases q; cases q'; cases hlo; cases hhi; rfl + exact Prod.ext (Fin.ext hi) hqeq + have proof_historyInputCode_injective_82 (M : ℕ) (n : ℕ) : + Function.Injective (OAI.EditApproximation.historyInputCode (M := M) (n := n)) := by + rintro ⟨i, s, q⟩ ⟨i', s', q'⟩ heq + have h := Nat.pair_eq_pair.mp heq + have hc := proof_childInputCode_injective_83 M n h.2 + cases hc + cases h.1 + rfl + exact + let earlierKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.historyInputCode (proof_historyInputCode_injective_82 M target.length) + (OAI.EditApproximation.queryEarlierInputCover parent N P F exponent t a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readEarlier earlierKeys fun earlierAnswers => + let earlier := fun i s r => OAI.EditApproximation.finiteAnswerTable earlierKeys earlierAnswers (i, s, r) + let online := OAI.EditApproximation.localOnlineCandidates source target parent N P F exponent H tau a eta kappa + parentInitial child initial earlier (t - 1) integer q + let sharedKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) + (OAI.EditApproximation.querySharedInputCover source target parent N F exponent Q a parentInitial q draw) + OAI.EditApproximation.FiniteQuery.collect readCurrent sharedKeys fun sharedAnswers => + let current := fun i r => OAI.EditApproximation.finiteAnswerTable sharedKeys sharedAnswers (i, r) + let selected := OAI.EditApproximation.localCellGroupActions source target parent N P F exponent Q tau a + parentInitial child initial current draw q + let needed := OAI.EditApproximation.actionCurrentInputCover selected ∪ OAI.EditApproximation.actionCurrentInputCover online + let currentKeys := OAI.EditApproximation.orderedInputs OAI.EditApproximation.childInputCode (proof_childInputCode_injective_83 M target.length) needed + OAI.EditApproximation.FiniteQuery.collect readCurrent currentKeys fun currentAnswers => + let value := OAI.EditApproximation.rationalActionValue (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.finiteAnswerTable currentKeys currentAnswers) q + let fallback := OAI.EditApproximation.rationalBellman parentInitial (fun q r => OAI.EditApproximation.targetEndpointDistance q r) (128 * F) + (OAI.EditApproximation.rationalActualWideActions parent (OAI.EditApproximation.localRefinementRepresentatives N P F a parentInitial q) P) + (fun input => earlier input.1 (t - 1) input.2) q + .done (OAI.EditApproximation.rationalRefinementUpdate delta (OAI.EditApproximation.rationalMinimum fallback (selected.map value)) + (OAI.EditApproximation.rationalOnlineMinimum (online.map value))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (draw : CellGroupDraws M F Q) (q : TargetInterval target.length) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +def localOnlineSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.localOnlineSourceKeys N P F a parentInitial q + OAI.EditApproximation.FiniteQuery.collect + (fun key => readInteger key (OAI.EditApproximation.keyedOnlineSourceRange source target parent P exponent H tau child key)) + keys fun values => + OAI.EditApproximation.localRefinementStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial draw (fun b r => ⌊OAI.EditApproximation.finiteAnswerTable keys values (b, r)⌋₊) q + readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {β : Type u_2} {α : Type u_3} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (a : BinaryFraction) (t : ℕ) (initial : TargetInterval target.length → BinaryFraction × ℕ) (draw : CountedCellGroupDraws M F Q) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (online : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (selected : List (Fin M × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) + (Fin M × TargetInterval target.length) M) × ℕ) (next : List (Fin M × ℕ × TargetInterval target.length) → List BinaryFraction → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (BinaryBellmanAction (TargetInterval target.length) (Fin M × TargetInterval target.length) M) → + List (Fin M × TargetInterval target.length) → List BinaryFraction → BitQuery ι β) + +def queryRefinementGather : OAI.EditApproximation.BitQuery ι β := + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a initial q)).bind + fun earlierKeys => OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys fun earlierWords => + (OAI.EditApproximation.BitQuery.compute (online earlierKeys earlierWords)).bind fun onlineActions => + let word := initial q + .charge word.2 ((OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent + eM eF hM hF parent a word.1 q draw)).bind fun sharedKeys => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys fun sharedWords => + (OAI.EditApproximation.BitQuery.compute (selected sharedKeys sharedWords)).bind fun selectedActions => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun currentKeys => OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + (next earlierKeys earlierWords selectedActions onlineActions currentKeys)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a delta : BinaryFraction) (initial : TargetInterval ny → BinaryFraction × ℕ) (t : ℕ) (earlierKeys : List (Fin M × ℕ × TargetInterval ny)) (earlierWords : List BinaryFraction) (groups online : List (BinaryBellmanAction (TargetInterval ny) (Fin M × TargetInterval ny) M)) (currentKeys : List (Fin M × TargetInterval ny)) (currentWords : List BinaryFraction) (query : TargetInterval ny) + +def queryRefinementFinishWithWork : OAI.EditApproximation.BinaryFraction × ℕ := + let fallback := initial query + let representatives := OAI.EditApproximation.BinaryFraction.localRepresentativeReadWithWork N P F a initial query + let result := OAI.EditApproximation.BinaryFraction.physicalContinuationReadWithWork parent representatives.1 P F delta fallback.1 + (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork earlierKeys earlierWords (t - 1)) + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork currentKeys currentWords input.1 input.2) + groups online query + (result.1, fallback.2 + representatives.2 + result.2 + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (child initial : Fin M → TargetInterval target.length → ℚ) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomSourceStepQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.groupScalarKeys M F Q (OAI.EditApproximation.localGroupQueryKeys N F exponent a parentInitial q) + OAI.EditApproximation.FiniteQuery.collect readGroup keys fun values => + OAI.EditApproximation.localOnlineSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial child initial (OAI.EditApproximation.groupDrawFromValues keys values) q readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (parentInitial : TargetInterval target.length → ℚ) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomBandDataQuery : OAI.EditApproximation.FiniteQuery ι := + let keys := OAI.EditApproximation.refinementBandInputList (M := M) parent N P F exponent a parentInitial q + OAI.EditApproximation.FiniteQuery.collect readMass keys fun massValues => + OAI.EditApproximation.FiniteQuery.collect readInitial keys fun initialValues => + OAI.EditApproximation.localRandomSourceStepQuery source target parent N P F exponent H Q tau a eta kappa delta t + parentInitial (fun i r => OAI.EditApproximation.finiteAnswerTable keys massValues (i, r)) + (fun i r => OAI.EditApproximation.finiteAnswerTable keys initialValues (i, r)) q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type u_2} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (t : ℕ) (readParentInitial : TargetInterval target.length → FiniteQuery ι) (readMass readInitial : Fin M × TargetInterval target.length → FiniteQuery ι) (readGroup : GroupScalarKey M F Q → FiniteQuery ι) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery ι) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → FiniteQuery ι) (readCurrent : (Fin M × TargetInterval target.length) → FiniteQuery ι) + +noncomputable def localRandomDataQuery : OAI.EditApproximation.FiniteQuery ι := + OAI.EditApproximation.FiniteQuery.bind (readParentInitial q) fun value => + let keys := OAI.EditApproximation.refinementInitialSupport N P F exponent a value q + OAI.EditApproximation.FiniteQuery.collect readParentInitial keys fun initialValues => + OAI.EditApproximation.localRandomBandDataQuery source target parent N P F exponent H Q tau a eta kappa delta t + (OAI.EditApproximation.finiteAnswerTable keys initialValues) readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J N n exponent F Q R B : ℕ} + +def physicalScalarCode (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : ℕ := + match key with + | ⟨.inl online, time⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalEntryCode (online.1.1.val, online.1.2.2)) + (Nat.pair online.1.2.1.val (Nat.pair online.2.val.val time.val)) + | ⟨.inr group, index⟩ => 2 * Nat.pair (OAI.EditApproximation.physicalNodeCode group.1.val) + (Nat.pair group.2.1.val (Nat.pair group.2.2.1.val (Nat.pair group.2.2.2.val + (Nat.pair index.1.val (Nat.pair index.2.1.val index.2.2.val))))) + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] +open MeasureTheory ProbabilityTheory + +def physicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : b ∈ OAI.EditApproximation.dyadicScales N then + if hc : cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b hb, + ⟨cell.1, Nat.lt_succ_of_le hc.1⟩, ⟨cell.2, Nat.lt_succ_of_le hc.2⟩) + Eq.mp (congrArg (OAI.EditApproximation.PhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b hb)) (OAI.EditApproximation.physicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done 0 + else fun _ _ => .done 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) [NeZero M] + +def physicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) := + OAI.EditApproximation.physicalScalarGroupQueries M J N n exponent F Q R B node time key.1.1 key.1.2 key.2.1 key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q : ℕ) (tau a eta kappa delta : ℚ) (pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → FiniteQuery σ) (readInteger : (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (q : TargetInterval target.length) + +noncomputable def physicalRandomDataRequestQuery : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) := + OAI.EditApproximation.localRandomDataQuery source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q tau a eta kappa delta t + (fun r => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementMassQuery pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementWarmupRead pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readGroup key)) + (fun key range => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inl (readInteger key range)) q + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementEarlierQuery pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalRefinementCurrentQuery pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type*} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +def physicalInactiveGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S} := + if request.index ≤ T then + OAI.EditApproximation.physicalWarmupRequestQuery source target N P F (factor request.pass) + request.pass request.copy T S request.index request.node request.state + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) + else OAI.EditApproximation.physicalInitialQuery source target N P F (factor request.pass) + (OAI.EditApproximation.globalSeedRead N T S copies multiplier initial request) (request.node, request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomGlobalQuery (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) := by + by_cases hactive : T < request.index ∧ request.node.1.val < J ∧ + ¬ (OAI.EditApproximation.physicalSourceInterval source.length request.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length request.node).lo ≤ 1 + · have ht : 0 < request.index - T := Nat.sub_pos_of_lt hactive.1 + have hrequest : OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node + T (request.index - T) request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + let node : OAI.EditApproximation.PhysicalInternalNode M J := ⟨request.node, hactive.2.1⟩ + let time : Fin R := Fin.ofNat R (request.index - T - 1) + exact OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => ⟨child.val, by simpa only [hrequest] using child.property⟩)) + (OAI.EditApproximation.physicalRandomDataRequestQuery source target N P F exponent H Q tau + (OAI.EditApproximation.refinementFactor (factor request.pass) F) eta kappa delta request.pass request.copy T S + (request.index - T) ht request.node hactive.2.1 + (readGroup request.pass request.copy node time) + (readInteger request.pass request.copy node time) request.state) + · exact OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInactiveGlobalQuery source target N P F T S copies factor multiplier initial request) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.PhysicalTableRequest + + +def entryCapacity (M J n : ℕ) : ℕ := (n + 1) ^ 2 * (M ^ J * (J + 1)) + +def code {M J n : ℕ} (copies T S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : ℕ := + request.index + (T + S + 1) * (request.copy + copies * + (OAI.EditApproximation.physicalEntryCode (request.node, request.state) + OAI.EditApproximation.PhysicalTableRequest.entryCapacity M J n * request.pass)) + + +end OAI.EditApproximation.PhysicalTableRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.SourceRanked +variable {σ : Type u_1} {κ : Type u_2} (tableRank : κ → ℕ) (supported : κ → Prop) + +def supportedChild (parent : κ) : Sum σ {key : κ // tableRank key < tableRank parent} → Prop + | .inl _ => True + | .inr table => supported table.val + +def supportedChildMap (parent : {key : κ // supported key}) : + {key : Sum σ {key : κ // tableRank key < tableRank parent.val} // + OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val key} → + Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val} + | ⟨.inl source, _⟩ => .inl source + | ⟨.inr table, hs⟩ => .inr ⟨⟨table.val, hs⟩, table.property⟩ + +noncomputable def restrictBody + (tableBody : (parent : κ) → OAI.EditApproximation.FiniteQuery (Sum σ {key : κ // tableRank key < tableRank parent})) + (parent : {key : κ // supported key}) : + OAI.EditApproximation.FiniteQuery (Sum σ {key : {key : κ // supported key} // tableRank key.val < tableRank parent.val}) := by + classical + exact OAI.EditApproximation.FiniteQuery.mapKeys (OAI.EditApproximation.SourceRanked.supportedChildMap tableRank supported parent) + (OAI.EditApproximation.FiniteQuery.restrict (OAI.EditApproximation.SourceRanked.supportedChild tableRank supported parent.val) (tableBody parent.val)) + + +end OAI.EditApproximation.SourceRanked +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalRandomBoundedQuery + (request : {request : OAI.EditApproximation.PhysicalTableRequest M J target.length // request.Bounded passes copies T S}) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.Bounded passes copies T S} // child.val.combinedRank T S < request.val.combinedRank T S}) := + OAI.EditApproximation.SourceRanked.restrictBody (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) + (OAI.EditApproximation.physicalRandomGlobalQuery source target N P F exponent H Q T S copies factor multiplier + tau eta kappa delta readGroup readInteger initial) request + +noncomputable def chargedRandomGlobalQuery + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) : + OAI.EditApproximation.FiniteQuery (Sum σ {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < request.rank}) := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + exact + match request with + | .inl entry => .done (initial entry) + | .inr parent => + if parent.val.index ≤ T then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr (OAI.EditApproximation.chargedWarmupQuery source target N P F factor multiplier parent) + else if parent.val.node.1.val < J then + if (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).hi - + (OAI.EditApproximation.physicalSourceInterval source.length parent.val.node).lo ≤ 1 then + OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + else OAI.EditApproximation.FiniteQuery.mapKeys + (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩)) + (OAI.EditApproximation.physicalRandomBoundedQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial parent) + else OAI.EditApproximation.FiniteQuery.mapKeys Sum.inr + (OAI.EditApproximation.physicalInitialQuery source target N P F (factor parent.val.pass) + (OAI.EditApproximation.chargedSeedQuery N multiplier parent) (parent.val.node, parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) + +abbrev PhysicalFamilyScalarKey := Fin (passes + 1) × Fin (copies + 1) × + OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + +abbrev PhysicalFamilyScalarDraw := ∀ key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies, + Fin (OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) +variable (draw : PhysicalFamilyScalarDraw + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + +def physicalFamilyAnswer (key : OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) : ℚ := + (draw key).val + +def physicalFamilyGroupRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + +def physicalFamilyOnlineRead (pass copy : ℕ) (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : OAI.EditApproximation.FiniteQuery (OAI.EditApproximation.PhysicalFamilyScalarKey + (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) := + OAI.EditApproximation.FiniteQuery.mapKeys (fun scalar => (Fin.ofNat (passes + 1) pass, Fin.ofNat (copies + 1) copy, scalar)) + (OAI.EditApproximation.physicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +abbrev QueryFamilyMemoKey := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) + +def queryFamilySourceWordWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : OAI.EditApproximation.BinaryFraction × ℕ := + (OAI.EditApproximation.BinaryFraction.nat (draw key).val, Nat.size (draw key).val + 3) + +def queryFamilyMemoRemaining : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q → ℕ + | .inl _ => 0 + | .inr request => OAI.EditApproximation.chargedPhysicalRemaining request + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +abbrev ComputedFamilySeed (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ClampedPhysicalSeed (OAI.EditApproximation.integerParameters N).M + (OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target.length N + +abbrev ComputedFamilyDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +abbrev ComputedFamilyInput (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedFamilySeed source target N × OAI.EditApproximation.ComputedFamilyDraw source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyEncoding_3) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies + +def physicalFamilyCode (key : Key) : ℕ := + Nat.pair key.1.val (Nat.pair key.2.1.val (OAI.EditApproximation.physicalScalarCode key.2.2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.ChargedPhysicalRequest + + +def code {M J ny passes copies T S : ℕ} : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S → ℕ + | .inl entry => 2 * OAI.EditApproximation.physicalEntryCode entry + | .inr request => 2 * OAI.EditApproximation.PhysicalTableRequest.code copies T S request.val + 1 + + +end OAI.EditApproximation.ChargedPhysicalRequest +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +abbrev ComputedFamilyScalarKey (source target : List ℕ) (N R : ℕ) := + OAI.EditApproximation.PhysicalFamilyScalarKey (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := R) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + +def computedFamilyMemoCode (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ := + OAI.EditApproximation.SourceRanked.keyCode + (OAI.EditApproximation.physicalFamilyCode target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + OAI.EditApproximation.ChargedPhysicalRequest.code + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open EditDistortion Finset MeasureTheory ProbabilityTheory + +def coarseInitialCandidate {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (i : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y)) (draws : OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + let k := OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i + 2 * (OAI.EditApproximation.coarseThresholdEstimate k Q lam + (OAI.EditApproximation.coarseTargetFrame k (OAI.EditApproximation.coarsePadTo (OAI.EditApproximation.coarseEntryWidth x y) y)) + (OAI.EditApproximation.coarseEntryTree B D x y) draws k 0 (OAI.EditApproximation.coarseRootShift k) + k) + +def coarseInitialMinimum {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℚ := + univ.inf' univ_nonempty (fun i => OAI.EditApproximation.coarseInitialCandidate B D Q lam x y i (draws i)) + +def coarseInitialValue {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (N : ℕ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then min N y.length + else if x = y then 0 + else min N ⌈OAI.EditApproximation.coarseInitialMinimum B D Q lam x y draws⌉₊ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Finset MeasureTheory ProbabilityTheory + +def coarseActiveArrayWork {B : ℕ} {α : Type u} (k : ℕ) (Q lam : ℚ) : + {D : ℕ} → OAI.EditApproximation.CoarseSourceTree B α D → OAI.EditApproximation.CoarseThresholdDraws B D → ℚ → ℕ + | _, tree, draws, allowance => + if (tree.word.length : ℚ) ≤ allowance then 0 else + match tree, draws with + | .leaf _, _ => B * (2 * k + 1) + | .branch children, (draws, below) => + B * (2 * k + 1) + + OAI.EditApproximation.coarseActiveChildrenWork Q lam allowance (fun child => coarseActiveArrayWork k Q lam child) + (List.ofFn fun i => (children i, draws i, below i)) + +def coarseFullSeedTable (N B : ℕ) {I : Type u_1} {α : Type u_2} [DecidableEq α] + (depth : I → ℕ) (x y : I → List α) + (draws : OAI.EditApproximation.CoarseFullSeedDraws B depth x y) : I → ℕ := + fun i => OAI.EditApproximation.coarseInitialValue B (depth i) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) N (x i) (y i) (draws i) + +def coarseInitialArrayWork {α : Type u} [DecidableEq α] + (B D : ℕ) (Q lam : ℚ) (x y : List α) + (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth x y) → OAI.EditApproximation.CoarseThresholdDraws B D) : ℕ := + if 2 * x.length < y.length then 0 + else if x = y then 0 + else ∑ i, OAI.EditApproximation.coarseActiveArrayWork (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) Q lam + (OAI.EditApproximation.coarseEntryTree B D x y) (draws i) (OAI.EditApproximation.coarseGuess (OAI.EditApproximation.coarseEntryWidth x y) i) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter +open scoped Topology + +def integerEqualWithWork : List ℤ → List ℤ → Bool × ℕ + | [], [] => (true, 1) + | [], _ :: _ => (false, 1) + | _ :: _, [] => (false, 1) + | x :: xs, y :: ys => + if x = y then + let tail := integerEqualWithWork xs ys + (tail.1, tail.2 + 1) + else (false, 1) + +def integerPreprocessingWork (source target : List ℤ) : ℕ := + (OAI.EditApproximation.integerInputInspectionWithWork source target).2 + + (OAI.EditApproximation.encodeIntegerSymbolsWithWork source).2 + (OAI.EditApproximation.encodeIntegerSymbolsWithWork target).2 + + (OAI.EditApproximation.integerOccurrenceBuildWithWork source target).2 + (OAI.EditApproximation.integerEqualWithWork source target).2 + 1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +abbrev ComputedFamilyMemoKey (source target : List ℕ) (N : ℕ) := + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.ComputedFamilyTableKey source target N) + +def integerPreevaluationWork (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : ℕ := + OAI.EditApproximation.integerPreprocessingWork source target + OAI.EditApproximation.globalParameterWork N + + (OAI.EditApproximation.physicalLargeInputWithWork N epsilon).2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies : ℕ) + +def physicalFamilyCodeWithWork + (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ × ℕ := + let scalar := OAI.EditApproximation.physicalScalarCodeWithWork key.2.2 + let copy := OAI.EditApproximation.naturalPairWithWork key.2.1.val scalar.1 + let pass := OAI.EditApproximation.naturalPairWithWork key.1.val copy.1 + (pass.1, scalar.2 + copy.2 + pass.2 + 2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedFamilyMemoCodeWithWork (source target : List ℕ) (N R : ℕ) : + Sum (OAI.EditApproximation.ComputedFamilyScalarKey source target N R) (OAI.EditApproximation.ComputedFamilyTableKey source target N) → ℕ × ℕ + | .inl key => + let result := OAI.EditApproximation.physicalFamilyCodeWithWork target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) key + (2 * result.1, result.2 + 2) + | .inr key => let result := OAI.EditApproximation.chargedPhysicalCodeWithWork key + (2 * result.1 + 1, result.2 + 3) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueries (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (b : ℕ) (cell : ℕ × ℕ) : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + exact + if hb : (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true then + if hc : (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true then + let key : OAI.EditApproximation.PhysicalLocalGroupKey M J N n exponent := + (node, OAI.EditApproximation.physicalScaleIndex N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb), + ⟨cell.1, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).1⟩, + ⟨cell.2, Nat.lt_succ_of_le ((proof_queryCellValidWithWork_value_102 n exponent cell).mp hc).2⟩) + Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb))) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesAt M J N n exponent F Q R B key time) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + else fun _ _ => .done (OAI.EditApproximation.BinaryFraction.nat 0) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) + +def queryPhysicalScalarGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1.1).2 + + (OAI.EditApproximation.queryCellValidWithWork n exponent key.1.2).2 + 2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time + key.1.1 key.1.2 key.2.1 key.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (M J N n exponent F Q R B : ℕ) +open Finset + +def queryPhysicalScalarOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) OAI.EditApproximation.BinaryFraction := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + exact + .charge ((OAI.EditApproximation.queryScalePresentWithWork N key.1).2 + (OAI.EditApproximation.queryRangeValidWithWork B range).2 + 2) + (if hb : (OAI.EditApproximation.queryScalePresentWithWork N key.1).1 = true then + if hr : (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true then + OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B + ⟨.inl ((node, OAI.EditApproximation.physicalScaleIndex N key.1 ((proof_queryScalePresentWithWork_value_101 N key.1).mp hb), key.2), + OAI.EditApproximation.positiveDrawRangeOfLE B range ((proof_queryRangeValidWithWork_value_107 B range).mp hr).1 + ((proof_queryRangeValidWithWork_value_107 B range).mp hr).2), time⟩ + else .done (OAI.EditApproximation.BinaryFraction.nat 0) + else .done (OAI.EditApproximation.BinaryFraction.nat 0)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagWithWork + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : + OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies × ℕ := + let p := OAI.EditApproximation.queryFinOfNatWithWork (passes + 1) pass (Nat.succ_pos _) + let c := OAI.EditApproximation.queryFinOfNatWithWork (copies + 1) copy (Nat.succ_pos _) + let key := (p.1, c.1, scalar) + (key, p.2 + c.2 + (OAI.EditApproximation.physicalFamilyCodeWithWork target N P F exponent H Q passes copies key).2 + 1) + +def queryFamilyGroupRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key) + +def queryFamilyOnlineRead (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) (range : ℕ) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.BitQuery.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) + node time key range) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +abbrev QueryPhysicalChild := Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J n // + child.combinedRank T S < parent.val.combinedRank T S} + +def querySupportedChildWithWork (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : Bool × ℕ := + match key with + | .inl _ => (true, 1) + | .inr child => OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S child.val + +def queryRestrictPhysicalBody (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) OAI.EditApproximation.BinaryFraction) : + OAI.EditApproximation.BitQuery (Sum σ {child : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (OAI.EditApproximation.SourceRanked.supportedChildMap (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent key, 1)) + (OAI.EditApproximation.BitQuery.restrictWithWork + (OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val) + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent) + (proof_querySupportedChildWithWork_value_108 passes copies T S parent) program) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {α : Type*} (source target : List α) (N P F : ℕ) (A a : BinaryFraction) (reader : TargetInterval target.length → BitQuery ι BinaryFraction) (q : TargetInterval target.length) + +def queryInitialConeProgramAt {n : ℕ} (sourceLength N P F : ℕ) (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (reader q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind fun keys => + OAI.EditApproximation.BitQuery.collect reader keys fun words => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (OAI.EditApproximation.BinaryFraction.queryInitialSeedReadWithWork value q keys words) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) + +def queryChargedRead + (key : {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)}) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + .charge ((OAI.EditApproximation.chargedPhysicalCodeWithWork key.val).2 + 1) (.read key .done) + +def queryChargedPreviousRead (hp : 0 < parent.val.pass) (q : OAI.EditApproximation.TargetInterval n) (copy : Fin copies) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr (OAI.EditApproximation.chargedPreviousPass parent q copy), by + apply proof_table_rank_lt_99 + apply proof_combinedRank_lt_of_progress_80 T S parent.val _ + exact Or.inr ⟨(proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).1.le, + (proof_previousPassRequest_progress_97 T S copy.val parent.val hp q).2⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J n passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J n // r.Bounded passes copies T S}) +open Finset + +def queryChargedSeedAt (N : ℕ) (multiplier : ℕ → ℕ) (q : OAI.EditApproximation.TargetInterval n) : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).2 + 1) + (if hp : (OAI.EditApproximation.naturalEqualWithWork parent.val.pass 0).1 = true then + OAI.EditApproximation.queryChargedRead parent ⟨.inl (parent.val.node, q), proof_coarse_rank_lt_100 _ parent rfl⟩ + else .charge (copies + 1) + (OAI.EditApproximation.BitQuery.collect (OAI.EditApproximation.queryChargedPreviousRead parent + (Nat.pos_of_ne_zero (fun h => hp ((proof_naturalEqualWithWork_value_74 _ _).mpr h))) q) + (List.finRange copies) fun words => OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N (multiplier (parent.val.pass - 1)) words))) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (q : TargetInterval target.length) + +def queryPhysicalInitial : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 2) + (if test.1 then + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.queryIndexedSliceWithWork source interval target.length q + occurrence symbolBits positionBits) + else OAI.EditApproximation.queryInitialConeProgramAt (OAI.EditApproximation.bitWordValue length.1) N P F A a + (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_1} {nx ny M : ℕ} (parent : TargetInterval nx) (N P F : ℕ) (a : BinaryFraction) (initialRead : TargetInterval ny → BitQuery ι BinaryFraction) (childRead : (Fin M × TargetInterval ny) → BitQuery ι BinaryFraction) (q : TargetInterval ny) + +def queryWarmupProgram : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + (initialRead q).bind fun value => + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind fun centers => + OAI.EditApproximation.BitQuery.collect initialRead centers fun words => + let initial := OAI.EditApproximation.BinaryFraction.queryOverrideParentReadWithWork value q centers words + (OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun inputs => OAI.EditApproximation.BitQuery.collect childRead inputs fun childWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun input => OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) q) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J ny passes copies T S : ℕ} (parent : {r : PhysicalTableRequest M J ny // r.Bounded passes copies T S}) (hbelow : parent.val.node.1.val < J) (hindex : 0 < parent.val.index) (input : Fin M × TargetInterval ny) + +def queryChargedWarmupChild : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + exact + OAI.EditApproximation.queryChargedRead parent ⟨.inr ⟨OAI.EditApproximation.PhysicalTableRequest.warmup parent.val.pass parent.val.copy + (OAI.EditApproximation.physicalChild parent.val.node hbelow input.1) (parent.val.index - 1) input.2, + parent.property.1, parent.property.2.1, + (Nat.sub_le _ _).trans parent.property.2.2⟩, by + apply proof_table_rank_lt_99 + exact proof_combinedRank_warmup_child_79 parent.val.pass parent.val.copy T S + parent.val.index parent.val.node hbelow input.1 parent.val.state input.2 hindex⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable (source target : List ℕ) {M J passes copies T S : ℕ} (N P F : ℕ) (A a : BinaryFraction) (multiplier : ℕ → ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded passes copies T S}) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) +open Finset + +def queryChargedWarmup : + OAI.EditApproximation.BitQuery {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (.inr parent)} OAI.EditApproximation.BinaryFraction := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + exact + .charge ((OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).2 + 1) + (if hz : (OAI.EditApproximation.naturalEqualWithWork parent.val.index 0).1 = true then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state + else .charge ((OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).2 + 1) + (if hb : (OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J).1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let test := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + test.2 + 1) + (if test.1 then + OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits + positionBits parent.val.state + else OAI.EditApproximation.queryWarmupProgram interval N P F a + (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits) + (OAI.EditApproximation.queryChargedWarmupChild parent ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb) + (Nat.pos_of_ne_zero (fun h => hz ((proof_naturalEqualWithWork_value_74 _ _).mpr h)))) + parent.val.state) + else OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + parent.val.state)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +abbrev ChargedFamilyQueryKey (parent : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) := + Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S // child.rank < parent.rank} + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {κ : Type u_1} (rank : κ → ℕ) (raw : (key : κ) → BitQuery {child : κ // rank child < rank key} BinaryFraction) (base : List Bool) (hbase : 0 < bitWordValue base) (remaining : κ → ℕ) + +def rankedNormalizeBody (key : κ) : + OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction := + (raw key).normalize base hbase (remaining key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_1} {α : Type u_2} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (readGroup : ℕ → ℕ → PhysicalInternalNode M J → Fin R → GroupScalarKey M F Q → FiniteQuery σ) (readInteger : ℕ → ℕ → PhysicalInternalNode M J → Fin R → + (ℕ × TargetInterval target.length) → ℕ → FiniteQuery σ) (initial : PhysicalEntry M J target.length → ℕ) (sourceAnswer : σ → ℚ) + +noncomputable def chargedRandomMemoEvaluate (bits : ℕ) + (encode : Sum σ (OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length passes copies T S) := + OAI.EditApproximation.rankedMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S passes copies factor multiplier + tau eta kappa delta readGroup readInteger initial) sourceAnswer) + bits encode (.inr request) .empty + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) + +noncomputable def physicalFamilyProgram := + OAI.EditApproximation.chargedRandomGlobalQuery source target N P F exponent H Q T S (passes + 1) copies + factor multiplier tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (OAI.EditApproximation.physicalFamilyOnlineRead (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + initial + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseDraw := OAI.EditApproximation.CoarseFullSeedDraws B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J : ℕ} (source target : List α) (N B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) +open EditDistortion Finset MeasureTheory ProbabilityTheory +open Finset MeasureTheory ProbabilityTheory + +noncomputable def physicalCoarseSeedTable (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : + OAI.EditApproximation.ClampedPhysicalSeed M J target.length N := by + have proof_coarseInitialValue_le_length_111 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) : + OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws ≤ N := by + unfold OAI.EditApproximation.coarseInitialValue + split_ifs + · exact min_le_left _ _ + · exact Nat.zero_le _ + · exact min_le_left _ _ + have proof_trans_112 {Alpha : Type u_1} {s : Bool} {m : ℕ} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} {z : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s m x y) (k : OAI.EditDistortion.Script.{u_1} s n y z) : OAI.EditDistortion.Script s (m + n) x z := by + induction h with + | nil => simpa using k + | @cons l x w y e h ih => + simpa only [Nat.add_right_comm] using OAI.EditDistortion.Script.cons e (ih k) + have proof_to_nil_113 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.Script s x.length x [] := by + induction x with + | nil => exact .nil [] + | cons a x ih => exact .cons (.delete [] x a) ih + have proof_single_114 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Script s 1 x y := + .cons h (.nil y) + have proof_symm_115 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Step.{u_1} s x y) : OAI.EditDistortion.Step s y x := by + cases h with + | insert p q a => exact .delete p q a + | delete p q a => exact .insert p q a + | substitute hs p q a b => exact .substitute hs p q b a + have proof_symm_116 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.Script s n y x := by + induction h with + | nil x => exact .nil x + | cons e h ih => exact (proof_trans_112 ih (proof_single_114 (proof_symm_115 e))) + have proof_exists_script_117 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : ∃ n, OAI.EditDistortion.Script s n x y := + ⟨x.length + y.length, (proof_trans_112 (proof_to_nil_113 x) + (proof_symm_116 (proof_to_nil_113 y)))⟩ + have proof_cost_spec_118 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) (y : List.{u_1} Alpha) : OAI.EditDistortion.Script s (OAI.EditDistortion.cost s x y) x y := + Nat.sInf_mem (proof_exists_script_117 x y) + have proof_eq_of_zero_119 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s 0 x y) : x = y := by + cases h + rfl + have proof_cost_le_120 {Alpha : Type u_1} {s : Bool} {n : ℕ} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} (h : OAI.EditDistortion.Script.{u_1} s n x y) : OAI.EditDistortion.cost s x y ≤ n := + Nat.sInf_le h + have proof_cost_refl_121 {Alpha : Type u_1} {s : Bool} (x : List.{u_1} Alpha) : OAI.EditDistortion.cost s x x = 0 := + Nat.eq_zero_of_le_zero (proof_cost_le_120 (.nil x)) + have proof_cost_eq_zero_iff_122 {Alpha : Type u_1} {s : Bool} {x : List.{u_1} Alpha} {y : List.{u_1} Alpha} : OAI.EditDistortion.cost s x y = 0 ↔ x = y := by + constructor + · intro h + have hc := proof_cost_spec_118 (s := s) x y + rw [h] at hc + exact (proof_eq_of_zero_119 hc) + · rintro rfl + exact proof_cost_refl_121 _ + have proof_coarseInitialValue_zero_123 {α : Type u_1} [instLocal1 : DecidableEq.{u_1 + 1} α] (B : ℕ) (D : ℕ) (Q : ℚ) (lam : ℚ) (N : ℕ) (x : List.{u_1} α) (y : List.{u_1} α) (draws : OAI.EditApproximation.CoarseGuessIndex (OAI.EditApproximation.coarseEntryWidth.{u_1} x y) → + OAI.EditApproximation.CoarseThresholdDraws B D) (hzero : Eq.{1} (OAI.EditDistortion.edit.{u_1} x y) 0) : OAI.EditApproximation.coarseInitialValue B D Q lam N x y draws = 0 := by + have hxy : x = y := (proof_cost_eq_zero_iff_122 (s := true)).mp hzero + subst y + simp only [OAI.EditApproximation.coarseInitialValue, ite_eq_right (by omega : ¬ 2 * x.length < x.length), ite_true] + have proof_computed_fullSeedTable_range_zero_110 (N : ℕ) (B : ℕ) {I : Type 0} {α : Type u_1} [instLocal4 : DecidableEq.{u_1 + 1} α] (depth : I → ℕ) (x : I → List.{u_1} α) (y : I → List.{u_1} α) (draws : OAI.EditApproximation.CoarseFullSeedDraws.{0, u_1} B depth x y) : + ∀ i, OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i ≤ N ∧ + (OAI.EditDistortion.edit (x i) (y i) = 0 → OAI.EditApproximation.coarseFullSeedTable N B depth x y draws i = 0) := by + intro i + exact ⟨proof_coarseInitialValue_le_length_111 _ _ _ _ _ _ _ _, + proof_coarseInitialValue_zero_123 _ _ _ _ _ _ _ _⟩ + exact + fun state => + ⟨OAI.EditApproximation.coarseFullSeedTable N B depth + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.physicalSource source state.1) + (fun state : OAI.EditApproximation.PhysicalEntry M J target.length => OAI.EditApproximation.substring target state.2.lo state.2.hi) draw state, + Nat.lt_succ_of_le ((proof_computed_fullSeedTable_range_zero_110 N B depth _ _ draw state).1)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] [MeasurableSpace (Fin M)] [MeasurableSingletonClass (Fin M)] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Geometry_LocalTraceMemoOutput_5) "passes" => computedSeedPassCount N + +def localFinalRootRequest (hH : 0 < H) (rootQ : OAI.EditApproximation.TargetInterval target.length) : + OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S := + .inr ⟨OAI.EditApproximation.PhysicalTableRequest.refinement passes 0 + (Sigma.mk (Fin.mk 0 (Nat.zero_lt_succ J)) PUnit.unit) T S rootQ, + ⟨Nat.lt_succ_self _, pow_pos hH 2, le_rfl⟩⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +noncomputable def computedFamilyKernelWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (cost : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) : ℕ := + OAI.EditApproximation.rankedMemoKernelWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) cost + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyAddressWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.rankedMemoAddressWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.SourceRanked.body OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.physicalFamilyProgram source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1)) + (OAI.EditApproximation.physicalFamilyAnswer target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) input.2)) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def computedFamilyCoarseCopyStorage (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost + (OAI.EditApproximation.physicalCoarseInputStorage (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target)) + +noncomputable def computedFamilyCoarseArrayCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 37)) + +noncomputable def computedFamilyCoarseScratchCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 181)) + +noncomputable def computedFamilyCoarseControlCapacity (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.computedFamilyKernelWork source target N input (OAI.EditApproximation.coarseHistoryKeyCost (fun _ => (N + 2) ^ 182)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_4) "Seed" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_8) "tau" => RationalParameters.tau (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_9) "eta" => RationalParameters.eta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_10) "kappa" => RationalParameters.kappa (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_11) "delta" => RationalParameters.delta (rationalParameters ell) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_12) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_13) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemo_14) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S + +noncomputable def physicalFamilyMemoResult (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (input : Seed × Family) := + OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) T S (passes + 1) (H ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) tau eta kappa delta + (OAI.EditApproximation.physicalFamilyGroupRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.physicalFamilyOnlineRead target N P ell exponent H (ell ^ 80) passes (H ^ 2)) + (OAI.EditApproximation.clampedSeedNat input.1) + (OAI.EditApproximation.physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes (H ^ 2) input.2) + bits encode (OAI.EditApproximation.localFinalRootRequest target N T S H hH rootQ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Finset +attribute [local instance] Classical.propDecidable + +noncomputable def selectionIndicator (p : Prop) : ℝ := if p then 1 else 0 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +noncomputable def coarseIndexedEntryCostSum {M J B : ℕ} [NeZero B] (source target : List ℕ) + (N : ℕ) (depth : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) + (selected : OAI.EditApproximation.PhysicalEntry M J target.length → Prop) : ℝ := by + classical + exact ∑ entry : OAI.EditApproximation.PhysicalEntry M J target.length, OAI.EditApproximation.selectionIndicator (selected entry) * + (OAI.EditApproximation.coarseIndexedEntryBinaryCost N B (depth entry) (OAI.EditApproximation.physicalSource source entry.1) + (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (draw entry) : ℝ) + +def querySupportedChildAllocation {σ : Type u_1} {M J n : ℕ} (passes copies T S : ℕ) + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J n // r.Bounded passes copies T S}) + (key : OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) : ℕ := + match key with + | .inl _ => 0 + | .inr child => OAI.EditApproximation.queryPhysicalBoundedAllocation passes copies T S child.val + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] +open Finset + +noncomputable def rejectionFailureLaw (i : ι) : Measure ℕ := by + have proof_rejectionWord_range_124 (N : ℕ) (hN : LT.lt.{0} 0 N) : + N ≤ 2 ^ OAI.EditApproximation.rejectionBitCount N ∧ 2 ^ OAI.EditApproximation.rejectionBitCount N < 2 * N := by + constructor + · exact Nat.le_pow_clog (by norm_num) N + · by_cases hNone : N = 1 + · subst N + norm_num [OAI.EditApproximation.rejectionBitCount] + · have hN1 : 1 < N := by omega + have hpred := Nat.pow_pred_clog_lt_self (by norm_num : 1 < 2) hN1 + have hB := Nat.clog_pos (by norm_num : 1 < 2) hN1 + have hpow : 2 ^ OAI.EditApproximation.rejectionBitCount N = 2 ^ (Nat.clog 2 N).pred * 2 := by + rw [OAI.EditApproximation.rejectionBitCount, ← pow_succ] + congr 1 + exact (Nat.succ_pred_eq_of_pos hB).symm + rw [hpow] + omega + exact + geometricMeasure (OAI.EditApproximation.rejectionSuccessParameter (range i) (2 ^ OAI.EditApproximation.rejectionBitCount (range i)) + (Nat.pos_of_ne_zero (NeZero.ne (range i))) + (proof_rejectionWord_range_124 (range i) (Nat.pos_of_ne_zero (NeZero.ne (range i)))).1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {ι : Type u_1} [Fintype ι] (range : ι → ℕ) [∀ i, NeZero (range i)] + +noncomputable def rejectionRuntimeArrayLaw : Measure (OAI.EditApproximation.RejectionRuntimeArray range) := + (Measure.pi (OAI.EditApproximation.rejectionFailureLaw range)).prod (OAI.EditApproximation.rejectionAcceptedLaw range) + +noncomputable def rejectionSelectedBits + (selected : ι → (∀ i, Fin (range i)) → Prop) (execution : OAI.EditApproximation.RejectionRuntimeArray range) : ℝ := + ∑ i, (((execution.1 i : ℝ) + 1) * OAI.EditApproximation.rejectionBitCount (range i)) * + OAI.EditApproximation.selectionIndicator (selected i execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type u_1} {M J R : ℕ} [NeZero M] (target : List α) (N P F exponent H Q passes copies : ℕ) + +abbrev physicalFamilyRange (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : ℕ := + OAI.EditApproximation.physicalScalarRange M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + +instance physicalFamilyRange_neZero (key : OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) : + NeZero (OAI.EditApproximation.physicalFamilyRange target N P F exponent H Q passes copies key) := by + exact OAI.EditApproximation.physicalScalarRangeNeZero M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) key.2.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +abbrev ComputedPhysicalCoarseDraw (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.PhysicalCoarseDraw (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) source target (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +abbrev ComputedRejectionRuntime (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2)) + +noncomputable def computedPhysicalCoarseLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N) := + OAI.EditApproximation.coarseFullSeedMeasure (OAI.EditApproximation.integerParameters N).B (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (fun entry => OAI.EditApproximation.physicalSource source entry.1) + (fun entry => OAI.EditApproximation.substring target entry.2.lo entry.2.hi) + +abbrev ComputedExecutionOutcome (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.ComputedPhysicalCoarseDraw source target N × OAI.EditApproximation.ComputedRejectionRuntime source target N + +noncomputable def computedExecutionLaw (source target : List ℕ) (N : ℕ) : + Measure (OAI.EditApproximation.ComputedExecutionOutcome source target N) := + (OAI.EditApproximation.computedPhysicalCoarseLaw source target N).prod + (OAI.EditApproximation.rejectionRuntimeArrayLaw (OAI.EditApproximation.physicalFamilyRange (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2))) + +abbrev ComputedFullOutcome (source target : List ℕ) (N : ℕ) := + Unit ⊕ OAI.EditApproximation.ComputedExecutionOutcome source target N + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_8) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRuntime_9) "Family" => PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +abbrev PhysicalFamilyRuntimeOutcome := SeedState × OAI.EditApproximation.RejectionRuntimeArray FamilyRange + +def physicalFamilyRuntimeAccepted + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H) : SeedState × Family := + (execution.1, execution.2.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory Filter + +def physicalLargeInput (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : Prop := + (OAI.EditApproximation.inspectAccuracyWithWork (OAI.EditApproximation.inputHeight N) epsilon).1.isSome = true ∧ + OAI.EditApproximation.largeAccuracyInput N epsilon.value ∧ + Nat.size (OAI.EditApproximation.localOnlineMassBound (OAI.EditApproximation.integerParameters N).M (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N)) ≤ OAI.EditApproximation.inputHeight N + +instance physicalLargeInput_decidable (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Decidable (OAI.EditApproximation.physicalLargeInput N epsilon) := inferInstanceAs (Decidable (_ ∧ _ ∧ _)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory ProbabilityTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P T S H : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_4) "SeedState" => ClampedPhysicalSeed M J target.length N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_7) "passes" => computedSeedPassCount N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_8) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_9) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) (H ^ 2) T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyRejectionWork_10) "FamilyRange" => physicalFamilyRange (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes (H ^ 2) + +noncomputable def physicalFamilyMemoBits (hH : 0 < H) (bits : ℕ) + (encode : Sum Key Table → ℕ) (rootQ : OAI.EditApproximation.TargetInterval target.length) (seed : SeedState) + (execution : OAI.EditApproximation.RejectionRuntimeArray FamilyRange) : ℝ := + OAI.EditApproximation.rejectionSelectedBits FamilyRange (fun key accepted => Sum.inl key ∈ + (OAI.EditApproximation.physicalFamilyMemoResult source target N P T S H hH bits encode rootQ (seed, accepted)).freshKeys) + execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyResult (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.physicalFamilyMemoResult source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.finalTargetState target.length) input + +noncomputable def computedFamilyRejectionWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N)) : ℝ := + OAI.EditApproximation.physicalFamilyMemoBits source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.integerParameters N).T + (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) (OAI.EditApproximation.finalTargetState target.length) + execution.1 execution.2 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type u_1} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (B : ℕ) [NeZero B] [MeasurableSpace (Fin B)] [MeasurableSingletonClass (Fin B)] (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalFamilyMemoCoarse_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyMemoCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.coarseInitialArrayWork B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory +variable {α : Type} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P H B : ℕ) (depth : PhysicalEntry M J target.length → ℕ) + +abbrev PhysicalCoarseExecution := OAI.EditApproximation.PhysicalCoarseDraw source target B depth × + OAI.EditApproximation.RejectionRuntimeArray (OAI.EditApproximation.physicalFamilyRange (M := M) (J := J) (R := R) + target N P (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) H + (OAI.EditApproximation.inputSmallLog N ^ 80) (OAI.EditApproximation.computedSeedPassCount N) (H ^ 2)) + +noncomputable def physicalCoarseExecutionProjection + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N P H B depth) : + OAI.EditApproximation.PhysicalFamilyRuntimeOutcome (M := M) (J := J) (R := R) target N P H := + (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth execution.1, execution.2) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def computedExecutionProjection (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.physicalCoarseExecutionProjection (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).B + (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + +noncomputable def computedFullLaw (source target : List ℕ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) : + Measure (OAI.EditApproximation.ComputedFullOutcome source target N) := + if OAI.EditApproximation.physicalLargeInput N epsilon then (OAI.EditApproximation.computedExecutionLaw source target N).map Sum.inr + else Measure.dirac (Sum.inl ()) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionAccepted (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : OAI.EditApproximation.ComputedFamilyInput source target N := + OAI.EditApproximation.physicalFamilyRuntimeAccepted target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.computedExecutionProjection source target N execution) + +noncomputable def computedExecutionRejectionWork (source target : List ℕ) (N : ℕ) : + OAI.EditApproximation.ComputedExecutionOutcome source target N → ℝ := + OAI.EditApproximation.computedFamilyRejectionWork source target N ∘ OAI.EditApproximation.computedExecutionProjection source target N + +def computedFinalRoot (source target : List ℕ) (N : ℕ) : OAI.EditApproximation.ComputedFamilyTableKey source target N := + OAI.EditApproximation.localFinalRootRequest (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) target N + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) + (OAI.EditApproximation.finalTargetState target.length) + +noncomputable def computedExecutionKernelWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + let input := OAI.EditApproximation.computedExecutionAccepted source target N execution + OAI.EditApproximation.computedFamilyKernelWork source target N input (cost input) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionDictionaryWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + (OAI.EditApproximation.computedFamilyResult source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution)).dictionaryVisits + +noncomputable def computedExecutionAddressWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyAddressWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedCoarseWork := + fun draw => OAI.EditApproximation.physicalFamilyMemoCoarseWork source target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + draw B depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) + +noncomputable def symbolicComputedExecutionCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.symbolicComputedCoarseWork source target N depth encode execution.2.2 execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionNonlocalWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionRejectionWork source target N execution + + OAI.EditApproximation.computedExecutionDictionaryWork source target N execution + + OAI.EditApproximation.computedExecutionAddressWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalIndexedCoarseWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyIndexedCoarseWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + OAI.EditApproximation.coarseIndexedEntryCostSum source target N depth coarse + (fun entry => Sum.inr (Sum.inl entry) ∈ result.freshKeys) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionIndexedCoarseWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyIndexedCoarseWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedExecutionIndexedCoarseWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionIndexedCoarseWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) (depth : PhysicalEntry M J target.length → ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_3) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_4) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_5) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_6) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_7) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_8) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarseSamplingWork_9) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarseSamplingWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) (coarse : OAI.EditApproximation.PhysicalCoarseDraw source target B depth) : ℝ := + let initial := OAI.EditApproximation.clampedSeedNat (OAI.EditApproximation.physicalCoarseSeedTable source target N B depth coarse) + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + ((Nat.size B * OAI.EditApproximation.coarseInitialLabelCount B (depth entry) (OAI.EditApproximation.initialThresholdQ N) (OAI.EditApproximation.initialLambda N) + (OAI.EditApproximation.physicalSource source entry.1) (OAI.EditApproximation.substring target entry.2.lo entry.2.hi) (coarse entry) : ℕ) : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter +variable {M J R B : ℕ} [NeZero M] [NeZero R] [NeZero B] (source target : List ℕ) (N : ℕ) (depth : PhysicalEntry M J target.length → ℕ) (encode : Sum (PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N (integerParameters N).P (inputSmallLog N) (40 * smallLogExponent N) + (inputHeight N) (inputSmallLog N ^ 80) (computedSeedPassCount N) (inputHeight N ^ 2)) + (ChargedPhysicalRequest M J target.length (computedSeedPassCount N + 1) + (inputHeight N ^ 2) (integerParameters N).T (integerParameters N).S) → ℕ) + +noncomputable def symbolicComputedExecutionCoarseSamplingWork + (execution : OAI.EditApproximation.PhysicalCoarseExecution (R := R) source target N + (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) B depth) : ℝ := + OAI.EditApproximation.physicalFamilyCoarseSamplingWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) + (OAI.EditApproximation.inputHeight N ^ 2) (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + execution.2.2 depth (16384 * OAI.EditApproximation.inputHeight N + 5) encode + (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length)) execution.1 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionCoarseSamplingWork (source target : List ℕ) (N : ℕ) := + OAI.EditApproximation.symbolicComputedExecutionCoarseSamplingWork (M := (OAI.EditApproximation.integerParameters N).M) + (J := OAI.EditApproximation.intervalTreeDepth (OAI.EditApproximation.integerParameters N).M source.length) (R := OAI.EditApproximation.inputHeight N ^ 2) + (B := (OAI.EditApproximation.integerParameters N).B) source target N (OAI.EditApproximation.computedPhysicalCoarseDepth source target N) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P H T S passes copies : ℕ) (factor : ℕ → ℚ) (multiplier : ℕ → ℕ) (tau eta kappa delta : ℚ) (initial : PhysicalEntry M J target.length → ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P (inputSmallLog N) (40 * smallLogExponent N) H (inputSmallLog N ^ 80) passes copies) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_5) "ell" => inputSmallLog N +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_6) "exponent" => (40 * smallLogExponent N : ℕ) +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_7) "Key" => PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_8) "Table" => ChargedPhysicalRequest M J target.length (passes + 1) copies T S +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_9) "readGroup" => physicalFamilyGroupRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_10) "readInteger" => physicalFamilyOnlineRead (M := M) (J := J) (R := R) + target N P ell exponent H (ell ^ 80) passes copies +local notation (name := source_Combinatorics_EditApproximation_Refinement_PhysicalCoarsePreparation_11) "answer" => physicalFamilyAnswer target N P ell exponent H (ell ^ 80) passes copies draw + +noncomputable def physicalFamilyCoarsePreparationWork (bits : ℕ) (encode : Sum Key Table → ℕ) + (root : Table) : ℝ := + let result := OAI.EditApproximation.chargedRandomMemoEvaluate source target N P ell exponent H (ell ^ 80) + T S (passes + 1) copies factor multiplier tau eta kappa delta readGroup readInteger initial + answer bits encode root + ∑ entry, OAI.EditApproximation.selectionIndicator (Sum.inr (Sum.inl entry) ∈ result.freshKeys) * + (OAI.EditApproximation.physicalCoarsePreparationCost source target entry : ℝ) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def computedFamilyCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℝ := + OAI.EditApproximation.physicalFamilyCoarsePreparationWork source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputHeight N) + (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S (OAI.EditApproximation.computedSeedPassCount N) (OAI.EditApproximation.inputHeight N ^ 2) + (OAI.EditApproximation.scheduledSeedFactor N) (OAI.EditApproximation.scheduledSeedMultiplier N) + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).tau (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).eta + (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).kappa (OAI.EditApproximation.rationalParameters (OAI.EditApproximation.inputSmallLog N)).delta + (OAI.EditApproximation.clampedSeedNat input.1) input.2 (16384 * OAI.EditApproximation.inputHeight N + 5) + (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (OAI.EditApproximation.computedFinalRoot source target N) + +noncomputable def computedExecutionCoarsePreparationWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedFamilyCoarsePreparationWork source target N (OAI.EditApproximation.computedExecutionAccepted source target N execution) + +noncomputable def computedExecutionReadChargedWork (source target : List ℕ) (N : ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionIndexedCoarseWork source target N execution + + OAI.EditApproximation.computedExecutionCoarseSamplingWork source target N execution + + OAI.EditApproximation.computedExecutionNonlocalWork source target N execution + + OAI.EditApproximation.computedExecutionCoarsePreparationWork source target N execution + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory Filter + +noncomputable def computedExecutionTotalWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (execution : OAI.EditApproximation.ComputedExecutionOutcome source target N) : ℝ := + OAI.EditApproximation.computedExecutionReadChargedWork source target N execution + + OAI.EditApproximation.computedExecutionKernelWork source target N cost execution + +noncomputable def computedFullOutputWork (source target : List ℕ) (N : ℕ) + (cost : OAI.EditApproximation.ComputedFamilyInput source target N → OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ) + (setup : ℝ) (shared : ℕ) (output : OAI.EditApproximation.ComputedFamilyInput source target N → ℕ) + (fallbackOutput : ℕ) : OAI.EditApproximation.ComputedFullOutcome source target N → ℝ + | .inl _ => setup + (OAI.EditApproximation.chargedSuffixDP source target).2 + fallbackOutput + | .inr execution => setup + shared + OAI.EditApproximation.computedExecutionTotalWork source target N cost execution + + output (OAI.EditApproximation.computedExecutionAccepted source target N execution) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +variable {α : Type u_1} {M J R : ℕ} (target : List α) (N P F exponent H Q passes copies pass copy : ℕ) + +def queryFamilyTagAllocation + (scalar : OAI.EditApproximation.PhysicalScalarKey M J N target.length exponent F Q R (OAI.EditApproximation.localOnlineMassBound M P H)) : ℕ := + OAI.EditApproximation.binaryNaturalDivAllocation pass (passes + 1) + OAI.EditApproximation.binaryNaturalDivAllocation copy (copies + 1) + + OAI.EditApproximation.physicalScalarCodeAllocation scalar + 9 + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BitQuery.Footprint + + +def rankedBitMemoCells {κ : Type u_1} (rank : κ → ℕ) + (program : (key : κ) → OAI.EditApproximation.BitQuery {child : κ // rank child < rank key} OAI.EditApproximation.BinaryFraction) + (heap : ∀ key, OAI.EditApproximation.BitQuery.Footprint (program key)) + (bits : ℕ) (encode addressCells : κ → ℕ) (key : κ) (memory : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.BinaryFraction) : ℕ := + let found := memory.lookupCosted (OAI.EditApproximation.binaryMemoKey bits (encode key)) + match found.1 with + | some _ => OAI.EditApproximation.memoRequestCells bits (addressCells key) + | none => OAI.EditApproximation.memoRequestCells bits (addressCells key) + (heap key).runCells + (fun child previous => OAI.EditApproximation.rankedBitMemoEvaluate rank program bits encode child.val previous) + (fun child previous => rankedBitMemoCells rank program heap bits encode addressCells child.val previous) + memory +termination_by rank key +decreasing_by exact child.property + + +end OAI.EditApproximation.BitQuery.Footprint +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery + +local instance queryArityNeZero (N : ℕ) : NeZero (OAI.EditApproximation.integerParameters N).M := + ⟨by change 2 ^ (OAI.EditApproximation.heightExponent N / 20) ≠ 0; exact Nat.ne_of_gt (Nat.two_pow_pos _)⟩ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryInitialGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.TargetInterval n) → (reader key).Footprint) + (next : List (OAI.EditApproximation.TargetInterval n) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.TargetInterval n)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryInitialGather N P F exponent hP a q reader next).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialSupportWithWork N P F exponent hP a value q) + (OAI.EditApproximation.BinaryFraction.queryInitialSupportAllocation N P F exponent hP a value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys) + +def queryBandGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny : ℕ} + (M : ℕ) + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent : ℕ) + (hP : 0 < P) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (massReader initialReader : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (massReader key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (initialReader key).Footprint) + (next : List (Fin M × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) → + (mass words : List OAI.EditApproximation.BinaryFraction) → (next keys mass words).Footprint) : (OAI.EditApproximation.queryBandGather M parent N P F exponent hP a initial q massReader initialReader next).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryBandInputsWithWork M parent N P F exponent hP a initial q) + (OAI.EditApproximation.BinaryFraction.queryBandInputsAllocation M parent N P F exponent hP a initial allocation + q)).bind + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect massReader keys fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect massReader hm keys + (fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.collect initialReader keys (next keys mass)) + fun (mass : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.collect initialReader hi keys (next keys mass) (hn keys mass) + +def queryGroupSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {n : ℕ} + (M N F Q exponent eM eF : ℕ) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.TargetInterval n → ℕ) + (q : OAI.EditApproximation.TargetInterval n) + (reader : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (reader key).Footprint) + (next : List (OAI.EditApproximation.GroupScalarKey M F Q) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a initial q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (allocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysWithWork M N F Q exponent eM eF hM hF a (initial q).1 + q) + (OAI.EditApproximation.BinaryFraction.queryGroupSourceKeysAllocation M N F Q exponent eM eF hM hF a + (initial q).1 q)).bind + (fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.collect reader keys (next keys)) + fun (keys : List (OAI.EditApproximation.GroupScalarKey M F Q)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys (next keys) (hn keys)) + +def queryOnlineSourceGatherFootprint + {ι : Type u_1} + {β : Type u_2} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F exponent H : ℕ) + (hP : 0 < P) + (tau a : OAI.EditApproximation.BinaryFraction) + (initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (initialAllocation : OAI.EditApproximation.TargetInterval ny → ℕ) + (child : Fin M → OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ) + (childAllocation : Fin M → OAI.EditApproximation.TargetInterval ny → ℕ) + (q : OAI.EditApproximation.TargetInterval ny) + (reader : ℕ × OAI.EditApproximation.TargetInterval ny → ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (key : ℕ × OAI.EditApproximation.TargetInterval ny) → (range : ℕ) → (reader key range).Footprint) + (next : List (ℕ × OAI.EditApproximation.TargetInterval ny) → + List OAI.EditApproximation.BinaryFraction → OAI.EditApproximation.BitQuery ι β) + (hn : (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) → + (words : List OAI.EditApproximation.BinaryFraction) → (next keys words).Footprint) : (OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a initial child q reader next).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (initialAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysWithWork N P F hP a (initial q).1 q) + (OAI.EditApproximation.BinaryFraction.queryOnlineKeysAllocation N P F hP a (initial q).1 q)).bind + (fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + keys (next keys)) + fun (keys : List (ℕ × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key)).bind + (reader key)) + (fun (key : ℕ × OAI.EditApproximation.TargetInterval ny) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeWithWork parent P exponent H tau child key) + (OAI.EditApproximation.BinaryFraction.queryOnlineRangeAllocation parent P exponent H tau child + childAllocation key)).bind + (reader key) (hr key)) + keys (next keys) (hn keys)) + +def queryPhysicalTableReadFootprint + {M J n : ℕ} + (copies T S : ℕ) + (parent : OAI.EditApproximation.PhysicalTableRequest M J n) + (child : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S r < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent }) : (OAI.EditApproximation.queryPhysicalTableRead copies T S parent child).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalTableCodeAllocation (M := M) (J := J) (n := n) child.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read child OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryMeanReadFootprint + {ι : Type u_1} + (count : ℕ) + (reader : Fin count → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hr : (i : Fin count) → (reader i).Footprint) : (OAI.EditApproximation.queryMeanRead count reader).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf count + (OAI.EditApproximation.BitQuery.Footprint.collect reader hr (List.ofFn fun (i : Fin count) => i) + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryMeanWithWork count words) + (OAI.EditApproximation.BinaryFraction.sumListAllocation words + + (OAI.EditApproximation.BinaryFraction.sumListWithWork words).1.divAllocation + (OAI.EditApproximation.BinaryFraction.nat count) + + count.size)) + +def queryPhysicalScalarReadFootprint + (M J N n exponent F Q R B : ℕ) + (key : OAI.EditApproximation.PhysicalScalarKey M J N n exponent F Q R B) : (OAI.EditApproximation.queryPhysicalScalarRead M J N n exponent F Q R B key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.physicalScalarCodeAllocation key + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryRestrictPhysicalBodyFootprint + {σ : Type u_1} + {M J n : ℕ} + (passes copies T S : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (program : OAI.EditApproximation.BitQuery (OAI.EditApproximation.QueryPhysicalChild (σ := σ) passes copies T S parent) + OAI.EditApproximation.BinaryFraction) + (heap : program.Footprint) : (OAI.EditApproximation.queryRestrictPhysicalBody passes copies T S parent program).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_binaryNaturalAddWithWork_value_52 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalAddWithWork a b).1 = a + b := by + simp [OAI.EditApproximation.binaryNaturalAddWithWork, proof_bitAddWithWork_value_2, proof_bitWordValue_bits_15] + have proof_queryPhysicalBoundedWithWork_value_109 {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J n) : + (OAI.EditApproximation.queryPhysicalBoundedWithWork passes copies T S request).1 = true ↔ + request.Bounded passes copies T S := by + simp only [OAI.EditApproximation.queryPhysicalBoundedWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalAddWithWork_value_52, OAI.EditApproximation.PhysicalTableRequest.Bounded] + tauto + have proof_querySupportedChildWithWork_value_108 {σ : Type u_1} {M : ℕ} {J : ℕ} {n : ℕ} (passes : ℕ) (copies : ℕ) (T : ℕ) (S : ℕ) (parent : Subtype.{1} fun r => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := n) passes copies T S r) (key : OAI.EditApproximation.QueryPhysicalChild.{u_1} (σ := σ) passes copies T S parent) : + (OAI.EditApproximation.querySupportedChildWithWork passes copies T S parent key).1 = true ↔ + OAI.EditApproximation.SourceRanked.supportedChild (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S) + (OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S) parent.val key := by + cases key with + | inl source => exact iff_of_true rfl trivial + | inr child => exact proof_queryPhysicalBoundedWithWork_value_109 passes copies T S child.val + exact + (heap.restrictWithWork _ _ (proof_querySupportedChildWithWork_value_108 passes copies T S parent) + (OAI.EditApproximation.querySupportedChildAllocation passes copies T S parent) + ).mapKeysWithWork _ (fun _ => 1) + +def queryInitialConeProgramAtFootprint + {ι : Type u_1} + {n : ℕ} + (sourceLength N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (reader : OAI.EditApproximation.TargetInterval n → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval n) + (hr : (r : OAI.EditApproximation.TargetInterval n) → (reader r).Footprint) : (OAI.EditApproximation.queryInitialConeProgramAt sourceLength N P F A a reader q).Footprint := +(hr q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q)).bind + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersWithWork N P A value q) + (OAI.EditApproximation.BinaryFraction.queryInitialConeCentersAllocation N P A value q)).bind + (fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.collect reader keys fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (keys : List (OAI.EditApproximation.TargetInterval n)) => + OAI.EditApproximation.BitQuery.Footprint.collect reader hr keys + (fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadWithWork sourceLength N P F A a + (value.queryInitialSeedReadWithWork q keys words) q) + (OAI.EditApproximation.BinaryFraction.cachedInitialProgramReadAllocation + (value.queryInitialSeedReadWithWork q keys words) (value.queryInitialSeedReadAllocation q keys words) + sourceLength N P F A a q) + +def queryChargedReadFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (key : { child : OAI.EditApproximation.ChargedPhysicalRequest M J n passes copies T S // + child.rank < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) }) : (OAI.EditApproximation.queryChargedRead parent key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.chargedPhysicalCodeAllocation (M := M) (J := J) (n := n) (passes := passes) (copies := copies) (T := T) (S := S) key.val + 1) + (OAI.EditApproximation.BitQuery.Footprint.read key OAI.EditApproximation.BitQuery.done + fun (word : OAI.EditApproximation.BinaryFraction) => OAI.EditApproximation.BitQuery.Footprint.done word) + +def queryWarmupProgramFootprint + {ι : Type u_1} + {nx ny M : ℕ} + (parent : OAI.EditApproximation.TargetInterval nx) + (N P F : ℕ) + (a : OAI.EditApproximation.BinaryFraction) + (initialRead : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (childRead : Fin M × OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval ny) + (hi : (r : OAI.EditApproximation.TargetInterval ny) → (initialRead r).Footprint) + (hc : (key : Fin M × OAI.EditApproximation.TargetInterval ny) → (childRead key).Footprint) : (OAI.EditApproximation.queryWarmupProgram parent N P F a initialRead childRead q).Footprint := +(hi q).bind + (fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q)).bind + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (value : OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRawCentersWithWork N P F a value q) + (OAI.EditApproximation.BinaryFraction.queryRawCentersAllocation N P F a value q)).bind + (fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect initialRead centers + fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (centers : List (OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect initialRead hi centers + (fun (words : List OAI.EditApproximation.BinaryFraction) => + have initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q)).bind + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (words : List OAI.EditApproximation.BinaryFraction) => + let initial : OAI.EditApproximation.TargetInterval ny → OAI.EditApproximation.BinaryFraction × ℕ := + value.queryOverrideParentReadWithWork q centers words; + let allocation : OAI.EditApproximation.TargetInterval ny → ℕ := + OAI.EditApproximation.BinaryFraction.queryOverrideParentReadAllocation q centers words; + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsWithWork M parent N P F a initial q) + (OAI.EditApproximation.BinaryFraction.queryWarmupInputsAllocation M parent N P F a initial allocation + q)).bind + (fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.collect childRead inputs + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (inputs : List (Fin M × OAI.EditApproximation.TargetInterval ny)) => + OAI.EditApproximation.BitQuery.Footprint.collect childRead hc inputs + (fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a + (value.queryOverrideParentReadWithWork q centers words) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q)) + fun (childWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.localWarmupReadKernelWithWork parent N P F a initial + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + q) + (OAI.EditApproximation.BinaryFraction.localWarmupReadAllocation parent N P F a initial allocation + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadWithWork inputs childWords input.1 input.2) + (fun (input : Fin M × OAI.EditApproximation.TargetInterval ny) => + OAI.EditApproximation.BinaryFraction.queryChildReadAllocation inputs childWords input.1 input.2) + q) + +def queryPhysicalEarlierReadFootprint + {M J n : ℕ} + (copies pass copy T S t : ℕ) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (q : OAI.EditApproximation.TargetInterval n) + (input : Fin M × ℕ × OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_refinement_history_child_progress_96 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (t : ℕ) (s : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hs : LT.lt.{0} s t) : + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy (OAI.EditApproximation.physicalChild node hbelow i) T s previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.refinement OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.refinement] + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (input.2.1.bits.length + t.bits.length) ?_ + split + · exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryPhysicalScalarOnlineReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval n) + (range : ℕ) : (OAI.EditApproximation.queryPhysicalScalarOnlineRead M J N n exponent F Q R B node time key range).Footprint := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_queryRangeValidWithWork_value_107 (B : ℕ) (range : ℕ) : + (OAI.EditApproximation.queryRangeValidWithWork B range).1 = true ↔ 0 < range ∧ range ≤ B := by + simp only [OAI.EditApproximation.queryRangeValidWithWork, Bool.and_eq_true, decide_eq_true_eq, + proof_binaryNaturalCompareWithWork_lt_53, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.1 + OAI.EditApproximation.queryRangeValidAllocation B range) ?_ + split + · split + · exact OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _ + · exact .done _ + · exact .done _ + +def queryChargedSeedAtFootprint + {M J n passes copies T S : ℕ} + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J n // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (N : ℕ) + (multiplier : ℕ → ℕ) + (q : OAI.EditApproximation.TargetInterval n) : (OAI.EditApproximation.queryChargedSeedAt parent N multiplier q).Footprint := by + have proof_coarse_rank_lt_100 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (entry : OAI.EditApproximation.PhysicalEntry M J ny) (request : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (hnode : Eq.{1} entry.1 request.val.node) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inl entry : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr request) := by + change J - entry.1.1.val + 0 < request.val.remainingDepth + (request.val.rank T S + 1) + rw [hnode] + unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth + omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_rank_lt_previous_pass_98 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} second.pass first.pass) (hindex : LE.le.{0} second.index (HAdd.hAdd.{0, 0, 0} T S)) : + OAI.EditApproximation.PhysicalTableRequest.rank T S second < OAI.EditApproximation.PhysicalTableRequest.rank T S first := by + have hblock : second.pass * (T + S + 1) + second.index < + (second.pass + 1) * (T + S + 1) := by + nlinarith only [hindex] + have hnext := Nat.mul_le_mul_right (T + S + 1) (Nat.succ_le_of_lt hpass) + exact hblock.trans_le (hnext.trans (Nat.le_add_right _ _)) + have proof_previousPassRequest_progress_97 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (copy : ℕ) (parent : OAI.EditApproximation.PhysicalTableRequest M J ny) (hpass : LT.lt.{0} 0 parent.pass) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.previousPassRequest T S copy parent state).remainingDepth = parent.remainingDepth ∧ + (OAI.EditApproximation.previousPassRequest T S copy parent state).rank T S < parent.rank T S := by + refine ⟨rfl, ?_⟩ + exact proof_rank_lt_previous_pass_98 T S parent _ (by + change parent.pass - 1 < parent.pass + omega) le_rfl + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.pass 0) ?_ + split + · exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf copies ?_ + refine OAI.EditApproximation.BitQuery.Footprint.collect _ (fun _ => OAI.EditApproximation.queryChargedReadFootprint parent _) _ _ fun words => ?_ + let factor := multiplier (parent.val.pass - 1) + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.BinaryFraction.querySeedMedianWithWork N factor words) + (OAI.EditApproximation.BinaryFraction.seedMedianAllocation N factor words + + (OAI.EditApproximation.BinaryFraction.seedMedianWithWork N factor words).1.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryFamilyOnlineReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : ℕ × OAI.EditApproximation.TargetInterval target.length) + (range : ℕ) : (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy node time key + range).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarOnlineReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key range) + +def queryPhysicalInitialFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryPhysicalInitial source target N P F A a multiplier parent occurrence symbolBits positionBits + q).Footprint := by + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact OAI.EditApproximation.BitQuery.Footprint.computeOf _ + (OAI.EditApproximation.queryIndexedSliceAllocation source interval target.length q occurrence symbolBits positionBits) + · exact OAI.EditApproximation.queryInitialConeProgramAtFootprint _ N P F A a (OAI.EditApproximation.queryChargedSeedAt parent N multiplier) q + (OAI.EditApproximation.queryChargedSeedAtFootprint parent N multiplier) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset +open MeasureTheory ProbabilityTheory + +def queryPhysicalScalarGroupQueriesFootprint (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) (time : Fin R) (b : ℕ) (cell : ℕ × ℕ) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + (OAI.EditApproximation.queryPhysicalScalarGroupQueries M J N n exponent F Q R B node time b cell s j) := by + have proof_log_two_add_one_eq_size_103 (N : ℕ) (hN : LT.lt.{0} 0 N) : + Nat.log 2 N + 1 = Nat.size N := by + apply Nat.le_antisymm + · have h := Nat.pow_log_le_self 2 hN.ne' + have hlt : Nat.log 2 N < Nat.size N := Nat.lt_size.mpr h + omega + · exact Nat.size_le.mpr (Nat.lt_pow_succ_log_self (by decide : 1 < 2) N) + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_dyadicScalesWithWork_value_104 (N : ℕ) : + (OAI.EditApproximation.dyadicScalesWithWork N).1 = OAI.EditApproximation.dyadicScales N := by + have hcount : max 1 N.bits.length = Nat.log 2 N + 1 := by + by_cases hz : N = 0 + · subst N + decide + · have h := proof_log_two_add_one_eq_size_103 N (Nat.pos_of_ne_zero hz) + have hp := Nat.size_pos.mpr (Nat.pos_of_ne_zero hz) + rw [Nat.size_eq_bits_len, max_eq_right hp, h] + simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, proof_powerTwoWord_value_13, hcount, + OAI.EditApproximation.dyadicScales] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_queryNaturalIndexWithWork_value_105 (a : ℕ) (xs : List.{0} ℕ) : + (OAI.EditApproximation.queryNaturalIndexWithWork a xs).1 = xs.idxOf a := by + induction xs with + | nil => rfl + | cons b xs ih => + simp only [OAI.EditApproximation.queryNaturalIndexWithWork] + by_cases hab : a = b + · subst b + rw [ite_eq_left ((proof_naturalEqualWithWork_value_74 a a).mpr rfl)] + simp + · rw [ite_eq_right (fun h => hab ((proof_naturalEqualWithWork_value_74 a b).mp h))] + simp only [ih, List.idxOf_cons, beq_iff_eq] + rw [ite_eq_right (Ne.symm hab)] + have proof_queryScaleDispatchWithWork_value_106 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScaleDispatchWithWork N b).1 = (OAI.EditApproximation.dyadicScales N).idxOf b := by + simp only [OAI.EditApproximation.queryScaleDispatchWithWork, proof_queryNaturalIndexWithWork_value_105, proof_dyadicScalesWithWork_value_104] + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_queryScalePresentWithWork_value_101 (N : ℕ) (b : ℕ) : + (OAI.EditApproximation.queryScalePresentWithWork N b).1 = true ↔ b ∈ OAI.EditApproximation.dyadicScales N := by + simp only [OAI.EditApproximation.queryScalePresentWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_lt_53, + proof_queryScaleDispatchWithWork_value_106] + have hl : (OAI.EditApproximation.dyadicScales N).length = max 1 N.bits.length := by + rw [← proof_dyadicScalesWithWork_value_104 N] + (simp only [OAI.EditApproximation.dyadicScalesWithWork, proof_arithmeticMapWithWork_value_70, List.length_map, List.length_range]) + rw [← hl] + exact List.idxOf_lt_length_iff + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_binaryNaturalMulWithWork_value_55 (a : ℕ) (b : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalMulWithWork a b).1 = a * b := by + simp [OAI.EditApproximation.binaryNaturalMulWithWork, proof_bitMulWithWork_value_0, proof_bitWordValue_bits_15] + have proof_queryCellValidWithWork_value_102 (n : ℕ) (exponent : ℕ) (cell : Prod.{0, 0} ℕ ℕ) : + (OAI.EditApproximation.queryCellValidWithWork n exponent cell).1 = true ↔ + cell.1 ≤ n * 2 ^ exponent ∧ cell.2 ≤ n * 2 ^ exponent := by + simp only [OAI.EditApproximation.queryCellValidWithWork, Bool.and_eq_true, proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15, + proof_binaryNaturalMulWithWork_value_55, proof_powerTwoWord_value_13] + have proof_physicalScaleIndex_get_93 (N : ℕ) (b : ℕ) (hb : Membership.mem.{0, 0} (OAI.EditApproximation.dyadicScales N) b) : + (OAI.EditApproximation.dyadicScales N).get (OAI.EditApproximation.physicalScaleIndex N b hb) = b := + List.getElem_idxOf (List.idxOf_lt_length_of_mem hb) + have groupTransport (b c : ℕ) (h : b = c) + (actual : OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B b) + (heap : ∀ s j, OAI.EditApproximation.BitQuery.Footprint (actual s j)) : + ∀ s j, OAI.EditApproximation.BitQuery.Footprint + ((Eq.mp (congrArg (OAI.EditApproximation.BitPhysicalGroupQueries M J N n exponent F Q R B) h) actual) s j) := by + cases h + exact heap + intro s j + unfold OAI.EditApproximation.queryPhysicalScalarGroupQueries + split + · rename_i hb + split + · exact groupTransport _ _ + (proof_physicalScaleIndex_get_93 N b ((proof_queryScalePresentWithWork_value_101 N b).mp hb)) _ + (fun _ _ => OAI.EditApproximation.queryPhysicalScalarReadFootprint M J N n exponent F Q R B _) s j + · exact .done _ + · exact .done _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryPhysicalScalarGroupReadFootprint + (M J N n exponent F Q R B : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryPhysicalScalarGroupRead M J N n exponent F Q R B node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.chargeOf + (OAI.EditApproximation.queryScalePresentAllocation N key.fst.1 + + OAI.EditApproximation.queryCellValidAllocation n exponent key.fst.2) + (OAI.EditApproximation.queryPhysicalScalarGroupQueriesFootprint M J N n exponent F Q R B node time key.fst.1 key.fst.2 + key.snd.fst key.snd.snd) + +def queryFamilyGroupReadFootprint + {α : Type u_1} + {M J R : ℕ} + (target : List α) + (N P F exponent H Q passes copies pass copy : ℕ) + (node : OAI.EditApproximation.PhysicalInternalNode M J) + (time : Fin R) + (key : OAI.EditApproximation.GroupScalarKey M F Q) : (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy node time key).Footprint := +OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork + (OAI.EditApproximation.queryFamilyTagWithWork target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryFamilyTagAllocation target N P F exponent H Q passes copies pass copy) + (OAI.EditApproximation.queryPhysicalScalarGroupReadFootprint M J N target.length exponent F Q R + (OAI.EditApproximation.localOnlineMassBound M P H) node time key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryChargedWarmupFootprint + (source target : List ℕ) + {M J passes copies T S : ℕ} + (N P F : ℕ) + (A a : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded passes copies T S r }) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) : (OAI.EditApproximation.queryChargedWarmup source target N P F A a multiplier parent occurrence symbolBits + positionBits).Footprint := by + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have proof_bitCompareWithWork_eq_3 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .eq ↔ OAI.EditApproximation.bitWordValue left = OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_binaryNaturalCompareWithWork_eq_73 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .eq ↔ a = b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_eq_3 a.bits b.bits + have proof_naturalEqualWithWork_value_74 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.naturalEqualWithWork a b).1 = true ↔ a = b := by + simp only [OAI.EditApproximation.naturalEqualWithWork, decide_eq_true_eq, proof_binaryNaturalCompareWithWork_eq_73] + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_warmup_previous_child_progress_81 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState).remainingDepth < + (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state).remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.warmup OAI.EditApproximation.physicalChild + dsimp only + omega + · dsimp only [OAI.EditApproximation.PhysicalTableRequest.rank, OAI.EditApproximation.PhysicalTableRequest.warmup] + omega + have proof_combinedRank_warmup_child_79 {M : ℕ} {J : ℕ} {ny : ℕ} (pass : ℕ) (copy : ℕ) (T : ℕ) (S : ℕ) (j : ℕ) (node : OAI.EditApproximation.PhysicalNode M J) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) (previousState : OAI.EditApproximation.TargetInterval ny) (hj : LT.lt.{0} 0 j) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy (OAI.EditApproximation.physicalChild node hbelow i) (j - 1) previousState) < + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.warmup pass copy node j state) := + proof_combinedRank_lt_of_progress_80 T S _ _ (Or.inr + ⟨(proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).1.le, + (proof_warmup_previous_child_progress_81 pass copy T S j node hbelow i state previousState hj).2⟩) + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F A a multiplier parent occurrence + symbolBits positionBits + unfold OAI.EditApproximation.queryChargedWarmup + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalEqualAllocation parent.val.index 0) ?_ + split + · exact hinit _ + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit _ + · apply OAI.EditApproximation.queryWarmupProgramFootprint + · exact hinit + · intro input + exact OAI.EditApproximation.queryChargedReadFootprint parent _ + · exact hinit _ + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) +open Finset + +def preparedComputedCellSourceWithWorkRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → Fin M × ℕ) + (cell : ℕ × ℕ) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + let scales := OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF + let result := OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceWithWorkRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi scales.1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) draw cell + (result.1, scales.2 + result.2 + 1) + +def preparedLocalGroupScaleSourceWithWorkRawBand (eb : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let word := parentInitial query + let side := OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + let radius := OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork word.1 + let cells := OAI.EditApproximation.BinaryFraction.targetCellsWithWork side.1 (OAI.EditApproximation.bitWordValue radius.1) query + let selected := OAI.EditApproximation.filterMapWithWork (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) cells.1 + (selected.1, word.2 + side.2 + radius.2 + cells.2 + selected.2 + eb + 4) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) + +def preparedLocalCellGroupsSourceWithWorkRawBand (N : ℕ) + (draw : OAI.EditApproximation.CellGroupReadDraws M F Q) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let count := max 1 N.bits.length + let word := parentInitial query + let groups := OAI.EditApproximation.arithmeticFlatMapWithWork (fun eb => + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a word.1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4)) (List.range count) + (groups.1, word.2 + groups.2 + count + N.bits.length + 2) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) + +def preparedLocalOnlineScaleSourceWithWorkRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + Option (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let spacing := OAI.EditApproximation.seedGridSpacingWithWork b P + let center := OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue spacing.1) (proof_seedGridSpacingWithWork_pos_85 b P hP) query + let word := parentInitial center.1 + let eligible := OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a word.1 + if eligible.1 then + let sample := integer b center.1 + let selected := OAI.EditApproximation.BinaryFraction.preparedOnlineReadWithWorkRaw source target parent P F exponent H b (Nat.two_pow_pos e) hP + tau eta kappa child initial table R hc hi t center.1 sample.1 + (selected.1, spacing.2 + center.2 + word.2 + eligible.2 + selected.2 + sample.2 + e + 5) + else (none, spacing.2 + center.2 + word.2 + eligible.2 + e + 3) + +def preparedLocalOnlineActionsSourceWithWorkRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let word := parentInitial query + let scales := OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a word.1 + let selected := OAI.EditApproximation.filterMapWithWork + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) scales.1 + (selected.1, word.2 + scales.2 + selected.2 + 1) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) + +def queryOnlineSelectWithWorkRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer N q + +def queryGroupSelectWithWorkRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi N draw q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (draw : CountedCellGroupDraws M F Q) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRefinementRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRefinementGather source target parent N P F exponent Q eM eF hP hM hF a t parentInitial draw q + readEarlier readCurrent + (fun keys words => OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP + tau a eta kappa parentInitial child initial R hc hi t integer keys words q) + (fun keys words => OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw keys words q) + (fun earlierKeys earlierWords groups online currentKeys currentWords => + OAI.EditApproximation.BitQuery.compute (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta parentInitial + t earlierKeys earlierWords groups online currentKeys currentWords q)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (q : TargetInterval target.length) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalRandomSourcesRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryGroupSourceGather M N F Q exponent eM eF hM hF a parentInitial q readGroup + fun groupKeys groupWords => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun onlineKeys onlineWords => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) + q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) +open Finset + +def queryLocalBandRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGather M parent N P F exponent hP a parentInitial q readMass readInitial + fun keys massWords initialWords => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t parentInitial + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) + (proof_queryChildReadWithWork_budget_131 keys massWords) + (proof_queryChildReadWithWork_budget_131 keys initialWords) + q readGroup readInteger readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {ι : Type u_4} {α : Type u_5} (source target : List α) {M : ℕ} [NeZero M] (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (t : ℕ) (readParent : TargetInterval target.length → BitQuery ι BinaryFraction) (readMass readInitial : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) (readGroup : GroupScalarKey M F Q → BitQuery ι BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery ι BinaryFraction) (q : TargetInterval target.length) (readEarlier : (Fin M × ℕ × TargetInterval target.length) → BitQuery ι BinaryFraction) (readCurrent : (Fin M × TargetInterval target.length) → BitQuery ι BinaryFraction) + +def queryLocalProgramRawBand : OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryInitialGather N P F exponent hP a q readParent fun keys words => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + readMass readInitial readGroup readInteger q readEarlier readCurrent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {σ : Type u_4} {α : Type u_5} (source target : List α) {M J : ℕ} [NeZero M] (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (readGroup : GroupScalarKey M F Q → BitQuery σ BinaryFraction) (readInteger : (ℕ × TargetInterval target.length) → ℕ → BitQuery σ BinaryFraction) (q : TargetInterval target.length) + +def queryPhysicalRandomDataRequestRawBand : + OAI.EditApproximation.BitQuery (Sum σ {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) + OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryLocalProgramRawBand source target (OAI.EditApproximation.physicalSourceInterval source.length node) + N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (fun r => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q node le_rfl 0 (Nat.zero_le T) r)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalMassRead copies pass copy T S t ht node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalWarmupRead copies pass copy T S t ht node q + (OAI.EditApproximation.physicalChild node hbelow input.1) (by change node.1.val ≤ node.1.val + 1; omega) + 0 (Nat.zero_le T) input.2)) + (fun key => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readGroup key)) + (fun key range => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inl key, 1)) (readInteger key range)) q + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalEarlierRead copies pass copy T S t node hbelow q input)) + (fun input => OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalCurrentRead copies pass copy T S t node hbelow q input)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} {M J R : ℕ} [NeZero M] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (passes copies pass copy T S t : ℕ) (ht : 0 < t) (node : PhysicalNode M J) (hbelow : node.1.val < J) (time : Fin R) (q : TargetInterval target.length) + +def queryFamilyRefinementRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // child.combinedRank T S < + (OAI.EditApproximation.PhysicalTableRequest.refinement pass copy node T t q).combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (request : PhysicalTableRequest M J target.length) (hindex : T < request.index) (hbelow : request.node.1.val < J) + +def queryFamilyActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : OAI.EditApproximation.PhysicalTableRequest M J target.length // + child.combinedRank T S < request.combinedRank T S}) OAI.EditApproximation.BinaryFraction := by + have proof_active_request_eq_139 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + have proof_active_request_eqRawBand_138 {α : Type u_4} {M : ℕ} {J : ℕ} (target : List.{u_4} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_4} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => ⟨child.val, by + simpa only [proof_active_request_eqRawBand_138 (target := target) (T := T) (request := request) (hindex := hindex)] using child.property⟩) key, 1)) + (OAI.EditApproximation.queryFamilyRefinementRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {α : Type u_4} [DecidableEq α] {M J R : ℕ} [NeZero M] [NeZero R] (source target : List α) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa delta : BinaryFraction) (T S passes copies : ℕ) (parent : {r : PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) (hindex : T < parent.val.index) (hbelow : parent.val.node.1.val < J) + +def queryFamilyBoundedActiveRawBand : + OAI.EditApproximation.BitQuery (Sum (OAI.EditApproximation.PhysicalFamilyScalarKey (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + {child : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S} // + child.val.combinedRank T S < parent.val.combinedRank T S}) OAI.EditApproximation.BinaryFraction := + OAI.EditApproximation.queryRestrictPhysicalBody (passes + 1) copies T S parent + (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + T S passes copies parent.val hindex hbelow) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) + +def queryChargedFamilyTableRawBand + (parent : {r : OAI.EditApproximation.PhysicalTableRequest M J target.length // r.Bounded (passes + 1) copies T S}) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q (.inr parent)) OAI.EditApproximation.BinaryFraction := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + exact + let index := OAI.EditApproximation.wordLEWithWork parent.val.index.bits T.bits + .charge (index.2 + 1) + (if hi : index.1 = true then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryChargedWarmup source target N P F (A parent.val.pass) (a parent.val.pass) multiplier + parent occurrence symbolBits positionBits) + else let depth := OAI.EditApproximation.binaryNaturalCompareWithWork parent.val.node.1.val J + .charge (depth.2 + 1) + (if hb : depth.1 = .lt then + let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + let length := OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo + let short := OAI.EditApproximation.wordLEWithWork length.1 [true] + .charge (length.2 + short.2 + 1) + (if short.1 then + OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state) + else OAI.EditApproximation.BitQuery.mapKeysWithWork + (fun key => (Sum.map id (fun child => + ⟨Sum.inr child.val, proof_table_rank_lt_99 parent child.val child.property⟩) + key, 1)) + (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent + (Nat.lt_of_not_ge (fun h => hi ((proof_queryNaturalLEWithWork_value_140 parent.val.index T).mpr h))) + ((proof_binaryNaturalCompareWithWork_lt_53 _ _).mp hb))) + else OAI.EditApproximation.BitQuery.mapKeysWithWork (fun key => (Sum.inr key, 1)) + (OAI.EditApproximation.queryPhysicalInitial source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state))) + +def queryChargedFamilyGlobalRawBand + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : + OAI.EditApproximation.BitQuery (OAI.EditApproximation.ChargedFamilyQueryKey (R := R) target N P F exponent H Q request) OAI.EditApproximation.BinaryFraction := + match request with + | .inl entry => OAI.EditApproximation.BitQuery.compute (coarse entry) + | .inr parent => OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +variable {M J R passes copies T S : ℕ} [NeZero M] [NeZero R] (source target : List ℕ) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (A a : ℕ → BinaryFraction) (tau eta kappa delta : BinaryFraction) (multiplier : ℕ → ℕ) (occurrence : BinaryMemo PositionCounts) (symbolBits positionBits : ℕ) (coarse : PhysicalEntry M J target.length → BinaryFraction × ℕ) (draw : PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) + target N P F exponent H Q passes copies) + +def queryFamilyMemoRawRawBand (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) := + OAI.EditApproximation.SourceRanked.bitBody OAI.EditApproximation.ChargedPhysicalRequest.rank + (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse) + (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw) key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def computedQueryMemoNormalizedRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) → OAI.EditApproximation.BitQuery + {child : OAI.EditApproximation.ComputedFamilyMemoKey source target N // + OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank child < OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank key} + OAI.EditApproximation.BinaryFraction := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + OAI.EditApproximation.rankedNormalizeBody (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80)) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +attribute [local instance] queryRoundsNeZero + +def computedQueryMemoResultRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) := + OAI.EditApproximation.rankedBitMemoEvaluate (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +def computedQueryLocalWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : OAI.EditApproximation.ComputedFamilyMemoKey source target N → ℕ := + OAI.EditApproximation.rankedBitLocalWork (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + +def computedQueryAnswerWithWorkRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : List Bool × ℕ := + if source = target then ([], source.length + target.length + 1) + else let result := OAI.EditApproximation.computedQueryMemoResultRawBand source target N occurrence symbolBits positionBits input + let answer := OAI.EditApproximation.BinaryFraction.finalAnswerWithWork N result.value + (answer.1, answer.2 + source.length + target.length + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +def integerQueryLocalWorkRawBand (source target : List ℤ) (N : ℕ) := + OAI.EditApproximation.computedQueryLocalWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation + + +def integerBinaryOutputRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) := + OAI.EditApproximation.computedQueryAnswerWithWorkRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open MeasureTheory + +noncomputable def integerBinaryAnswerRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + | .inr execution => OAI.EditApproximation.bitWordValue (OAI.EditApproximation.integerBinaryOutputRawBand source target N + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).1 + else OAI.EditApproximation.exactSuffixAnswer (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +open Finset + +def preparedComputedCellSourceAllocationRawBand (b eb : ℕ) (hb : b = 2 ^ eb) + (draw : OAI.EditApproximation.cellScaleReadDraw M b Q (OAI.EditApproximation.BinaryFraction.nat F).value) + (drawAllocation : ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ) + (cell : ℕ × ℕ) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + have proof_arithmeticMapWithWork_value_70 {α : Type 0} {β : Type 0} (f : α → Prod.{0, 0} β ℕ) (values : List.{0} α) : + (OAI.EditApproximation.arithmeticMapWithWork f values).1 = values.map (fun a => (f a).1) := by + induction values with + | nil => rfl + | cons a rest ih => simp only [OAI.EditApproximation.arithmeticMapWithWork, ih, List.map_cons] + have proof_powerTwoWord_value_13 (n : ℕ) : OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord n) = 2 ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.powerTwoWord, OAI.EditApproximation.bitWordValue]) + | succ n ih => + (simp only [OAI.EditApproximation.powerTwoWord, List.replicate_succ, List.cons_append, OAI.EditApproximation.bitWordValue, + Bool.toNat_false, zero_add] at *) + rw [ih, pow_succ] + omega + have proof_inversePowerTwo_value_89 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.inversePowerTwo n).value = (2 : ℚ) ^ (-(n : ℤ)) := by + (simp only [OAI.EditApproximation.BinaryFraction.inversePowerTwo, OAI.EditApproximation.BinaryFraction.value, OAI.EditApproximation.SignedBinary.value, OAI.EditApproximation.signedMagnitude, Bool.false_eq_true, + ↓reduceIte, OAI.EditApproximation.bitWordValue, Bool.toNat_true, + Int.cast_natCast, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, zpow_neg, zpow_natCast]) + norm_num [one_div] + have proof_signedPowerTwoWithWork_value_90 (e : ℤ) : + (OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork e).1.value = (2 : ℚ) ^ e := by + unfold OAI.EditApproximation.BinaryFraction.signedPowerTwoWithWork + split_ifs with h + · change (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.powerTwoWord e.toNat) : ℚ) / 1 = (2 : ℚ) ^ e + rw [div_one, proof_powerTwoWord_value_13, Nat.cast_pow, Nat.cast_ofNat, ← zpow_natCast, + Int.toNat_of_nonneg h] + · rw [proof_inversePowerTwo_value_89, Int.toNat_of_nonneg + (show 0 ≤ -e from neg_nonneg.mpr (le_of_lt (lt_of_not_ge h))), neg_neg] + have proof_groupScalesWithWork_value_91 (eM : ℕ) (eb : ℕ) (eF : ℕ) : + ((OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value) = + OAI.EditApproximation.groupDyadicScales (2 ^ eM) (2 ^ eb) ((2 : ℚ) ^ eF) := by + have hlower : ((2 ^ eb : ℕ) : ℚ) / (2 ^ eM : ℕ) = (2 : ℚ) ^ ((eb : ℤ) - eM) := by + rw [Nat.cast_pow, Nat.cast_pow, Nat.cast_ofNat, zpow_sub₀ (by norm_num : (2 : ℚ) ≠ 0), + zpow_natCast, zpow_natCast] + have hupper : (64 : ℚ) * (2 : ℚ) ^ eF * (2 ^ eb : ℕ) = + (2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ) := by + rw [Nat.cast_pow, Nat.cast_ofNat, zpow_natCast, pow_add, pow_add] + norm_num + have hlog : Int.log 2 ((2 : ℚ) ^ ((6 + eF + eb : ℕ) : ℤ)) = ((6 + eF + eb : ℕ) : ℤ) := by + simpa only [Nat.cast_ofNat] using Int.log_zpow (R := ℚ) (by decide : 1 < 2) ((6 + eF + eb : ℕ) : ℤ) + have hclog : Int.clog 2 ((2 : ℚ) ^ ((eb : ℤ) - eM)) = (eb : ℤ) - eM := by + simpa only [Nat.cast_ofNat] using Int.clog_zpow (R := ℚ) (by decide : 1 < 2) ((eb : ℤ) - eM) + simp only [OAI.EditApproximation.BinaryFraction.groupScalesWithWork, proof_arithmeticMapWithWork_value_70, List.map_map, + Function.comp_def, proof_signedPowerTwoWithWork_value_90, OAI.EditApproximation.groupDyadicScales, hlower, hupper, hlog, hclog] + have proof_computedGroupScales_value_87 (M : ℕ) (b : ℕ) (F : ℕ) (eM : ℕ) (eb : ℕ) (eF : ℕ) (hM : Eq.{1} M (HPow.hPow.{0, 0, 0} 2 eM)) (hb : Eq.{1} b (HPow.hPow.{0, 0, 0} 2 eb)) (hF : Eq.{1} F (HPow.hPow.{0, 0, 0} 2 eF)) : + (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1.map OAI.EditApproximation.BinaryFraction.value = OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value := by + rw [proof_nat_value_49, hM, hb, hF, Nat.cast_pow, Nat.cast_ofNat] + exact proof_groupScalesWithWork_value_91 eM eb eF + exact + OAI.EditApproximation.BinaryFraction.groupScalesAllocation eM eb eF + + OAI.EditApproximation.BinaryFraction.preparedCellGroupSourceAllocationRaw source target parent b P F exponent Q + (by rw [hb]; exact Nat.two_pow_pos eb) hP tau a parentInitial child initial current + R R hc hi (OAI.EditApproximation.BinaryFraction.groupScalesWithWork eM eb eF).1 (proof_computedGroupScales_value_87 M b F eM eb eF hM hb hF) + draw parentAllocation childAllocation initialAllocation currentAllocation drawAllocation cell + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type*} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def castGroupSourceAllocationRawBand (b : ℕ) (cell : ℕ × ℕ) : + ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b (OAI.EditApproximation.BinaryFraction.nat F).value).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b (OAI.EditApproximation.BinaryFraction.nat F).value t)) → ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + Eq.mpr (congrArg (fun f => ∀ t : Fin (OAI.EditApproximation.groupDyadicScales M b f).length, + Fin (OAI.EditApproximation.groupSampleCount M Q b (OAI.EditApproximation.groupDyadicScaleAt M b f t)) → ℕ) (proof_nat_value_49 F)) (drawAllocation b cell) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) +open Finset + +def preparedLocalGroupScaleSourceAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_representation_value_32 (a : OAI.EditApproximation.BinaryFraction) : a.representation.value = a.value := rfl + have proof_eq_of_num_den_33 {a : OAI.EditApproximation.UnreducedRational} {b : OAI.EditApproximation.UnreducedRational} (hnum : Eq.{1} a.num b.num) (hden : Eq.{1} a.den b.den) : a = b := by + cases a + cases b + cases hnum + cases hden + rfl + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_value_ofInt_46 (a : ℤ) : (OAI.EditApproximation.SignedBinary.ofInt a).value = a := by + by_cases h : a < 0 + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_true, + ↓reduceIte] using (Int.eq_neg_natAbs_of_nonpos (le_of_lt h)).symm + · simpa only [OAI.EditApproximation.SignedBinary.ofInt, OAI.EditApproximation.SignedBinary.value, proof_bitWordValue_bits_15, OAI.EditApproximation.signedMagnitude, h, decide_false, + Bool.false_eq_true, ↓reduceIte] using (Int.eq_natAbs_of_nonneg (le_of_not_gt h)).symm + have proof_nat_representation_47 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).representation = OAI.EditApproximation.UnreducedRational.nat n := by + apply proof_eq_of_num_den_33 + · change (OAI.EditApproximation.SignedBinary.ofInt (n : ℤ)).value = (n : ℤ) + exact proof_value_ofInt_46 _ + · rfl + have proof_value_nat_48 (n : ℕ) : (OAI.EditApproximation.UnreducedRational.nat n).value = n := by (simp [OAI.EditApproximation.UnreducedRational.nat, OAI.EditApproximation.UnreducedRational.value]) + have proof_nat_value_49 (n : ℕ) : (OAI.EditApproximation.BinaryFraction.nat n).value = (n : ℚ) := by + rw [← proof_representation_value_32, proof_nat_representation_47, proof_value_nat_48] + exact + let b := 2 ^ eb + let side := (OAI.EditApproximation.BinaryFraction.canonicalMulWithWork (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b)).1 + let radius := (OAI.EditApproximation.BinaryFraction.naturalCeilingWithWork (parentInitial query).1).1 + let cells := (OAI.EditApproximation.BinaryFraction.targetCellsWithWork side (OAI.EditApproximation.bitWordValue radius) query).1 + parentAllocation query + OAI.EditApproximation.BinaryFraction.canonicalMulAllocation (OAI.EditApproximation.BinaryFraction.inversePowerTwo exponent) (OAI.EditApproximation.BinaryFraction.nat b) + + OAI.EditApproximation.BinaryFraction.naturalCeilingAllocation (parentInitial query).1 + OAI.EditApproximation.BinaryFraction.targetCellsAllocation side (OAI.EditApproximation.bitWordValue radius) query + + OAI.EditApproximation.filterMapAllocation (fun cell => + OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceWithWorkRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi b eb rfl + (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) cell) + (fun cell => OAI.EditApproximation.BinaryFraction.preparedComputedCellSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + b eb rfl (Eq.mpr (congrArg (OAI.EditApproximation.cellScaleReadDraw M b Q) (proof_nat_value_49 F)) (draw b cell)) + (OAI.EditApproximation.BinaryFraction.castGroupSourceAllocationRawBand F Q drawAllocation b cell) cell) cells + eb + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent Q eM eF : ℕ) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (hP : 0 < P) (tau a : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial current : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation currentAllocation : Fin M → TargetInterval target.length → ℕ) +variable (draw : CellGroupReadDraws M F Q) (drawAllocation : CellGroupSourceAllocations M F Q) + +def localGroupSourceScaleBlockRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : + List (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) (Fin M × OAI.EditApproximation.TargetInterval target.length) M) × ℕ := + let guard := OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1 + if guard.1 then + let selected := OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceWithWorkRawBand source target parent P F exponent Q eM eF + hM hF hP tau a parentInitial child initial current R hc hi eb draw query + (selected.1, guard.2 + selected.2 + eb + 4) + else ([], guard.2 + eb + 4) + +def localGroupSourceScaleBlockAllocationRawBand (eb : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.refinementScaleGuardAllocation F (2 ^ eb) a (parentInitial query).1 + eb + + if (OAI.EditApproximation.BinaryFraction.refinementScaleGuardWithWork F (2 ^ eb) a (parentInitial query).1).1 then + OAI.EditApproximation.BinaryFraction.preparedLocalGroupScaleSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query + else 0 + +def preparedLocalCellGroupsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + let count := max 1 N.bits.length + parentAllocation query + count + N.bits.length + + OAI.EditApproximation.arithmeticFlatMapAllocation + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi draw eb query) + (fun eb => OAI.EditApproximation.BinaryFraction.localGroupSourceScaleBlockAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial current R hc hi parentAllocation childAllocation initialAllocation currentAllocation + draw drawAllocation eb query) (List.range count) + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (P F exponent H : ℕ) (hP : 0 < P) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (table : ℕ → Fin M × TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i q, (child i q).2 ≤ R) (hi : ∀ i q, (initial i q).2 ≤ R) (t : ℕ) (integer : ℕ → TargetInterval target.length → ℕ × ℕ) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) (tableAllocation : ℕ → Fin M × TargetInterval target.length → ℕ) (integerAllocation : ℕ → TargetInterval target.length → ℕ) + +def preparedLocalOnlineScaleSourceAllocationRawBand (e : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := by + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_bitSubtractor_value_17 (a : Bool) (b : Bool) (borrow : Bool) : + a.toNat + 2 * (OAI.EditApproximation.bitBorrow a b borrow).toNat = + b.toNat + borrow.toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat := by + cases a <;> cases b <;> cases borrow <;> decide + have proof_bitSubtractionRippleEquation_18 (a : ℕ) (b : ℕ) (borrow : ℕ) (nextBorrow : ℕ) (difference : ℕ) (left : ℕ) (right : ℕ) (result : ℕ) (tail : ℕ) (htail : Eq.{1} (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} result right) nextBorrow) (HAdd.hAdd.{0, 0, 0} left tail)) (hbit : Eq.{1} (HAdd.hAdd.{0, 0, 0} a (HMul.hMul.{0, 0, 0} 2 nextBorrow)) + (HAdd.hAdd.{0, 0, 0} (HAdd.hAdd.{0, 0, 0} b borrow) difference)) : + (difference + 2 * result) + (b + 2 * right) + borrow = + (a + 2 * left) + 2 * tail := by + omega + have proof_bitSubtractWithWork_value_19 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right borrow).1 + OAI.EditApproximation.bitWordValue right + borrow.toNat = + OAI.EditApproximation.bitWordValue left + 2 ^ max left.length right.length * + (OAI.EditApproximation.bitSubtractWithWork left right borrow).2.1.toNat := by + induction left generalizing right borrow with + | nil => + induction right generalizing borrow with + | nil => (simp [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + have h := ih (OAI.EditApproximation.bitBorrow false b borrow) + have hb := proof_bitSubtractor_value_17 false b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitSubtractNilLeftWithWork, OAI.EditApproximation.bitWordValue, + List.length_nil, List.length_cons, Nat.zero_max, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 0 b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow false b borrow).toNat + (OAI.EditApproximation.bitDifference false b borrow).toNat 0 (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).1) + (2 ^ bs.length * (OAI.EditApproximation.bitSubtractNilLeftWithWork bs (OAI.EditApproximation.bitBorrow false b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons a as ih => + cases right with + | nil => + have h := ih [] (OAI.EditApproximation.bitBorrow a false borrow) + have hb := proof_bitSubtractor_value_17 a false borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_nil, List.length_cons, + Nat.max_zero, pow_succ, Bool.toNat_false] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat 0 borrow.toNat (OAI.EditApproximation.bitBorrow a false borrow).toNat + (OAI.EditApproximation.bitDifference a false borrow).toNat (OAI.EditApproximation.bitWordValue as) 0 + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).1) + (2 ^ as.length * (OAI.EditApproximation.bitSubtractWithWork as [] (OAI.EditApproximation.bitBorrow a false borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_zero, Nat.add_zero, Nat.zero_add, Nat.mul_assoc, + Nat.mul_left_comm] using hs + | cons b bs => + have h := ih bs (OAI.EditApproximation.bitBorrow a b borrow) + have hb := proof_bitSubtractor_value_17 a b borrow + (simp only [OAI.EditApproximation.bitSubtractWithWork, OAI.EditApproximation.bitWordValue, List.length_cons, Nat.succ_max_succ, + pow_succ] at h hb ⊢) + have hs := proof_bitSubtractionRippleEquation_18 a.toNat b.toNat borrow.toNat (OAI.EditApproximation.bitBorrow a b borrow).toNat + (OAI.EditApproximation.bitDifference a b borrow).toNat (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) + (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).1) + (2 ^ max as.length bs.length * (OAI.EditApproximation.bitSubtractWithWork as bs (OAI.EditApproximation.bitBorrow a b borrow)).2.1.toNat) + h hb + simpa only [Nat.mul_assoc, Nat.mul_left_comm] using hs + have proof_bitWordValue_lt_pow_length_20 (bits : List.{0} Bool) : OAI.EditApproximation.bitWordValue bits < 2 ^ bits.length := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitWordValue]) + | cons bit bits ih => + cases bit <;> (simp only [OAI.EditApproximation.bitWordValue, List.length_cons, pow_succ, Bool.toNat_false, Bool.toNat_true]) <;> omega + have proof_bitSubtractWithWork_length_21 (left : List.{0} Bool) (right : List.{0} Bool) (borrow : Bool) : + (OAI.EditApproximation.bitSubtractWithWork left right borrow).1.length = max left.length right.length := by + induction left generalizing right borrow with + | nil => + simp only [OAI.EditApproximation.bitSubtractWithWork] + induction right generalizing borrow with + | nil => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork] + | cons b bs ih => simp [OAI.EditApproximation.bitSubtractNilLeftWithWork, ih] + | cons a as ih => + cases right with + | nil => simp [OAI.EditApproximation.bitSubtractWithWork, ih] + | cons b bs => simp [OAI.EditApproximation.bitSubtractWithWork, ih, Nat.succ_max_succ] + have proof_bitSubtractWithWork_sub_22 (left : List.{0} Bool) (right : List.{0} Bool) (h : LE.le.{0} (OAI.EditApproximation.bitWordValue right) (OAI.EditApproximation.bitWordValue left)) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork left right false).1 = OAI.EditApproximation.bitWordValue left - OAI.EditApproximation.bitWordValue right := by + have hvalue := proof_bitSubtractWithWork_value_19 left right false + have hlt := proof_bitWordValue_lt_pow_length_20 (OAI.EditApproximation.bitSubtractWithWork left right false).1 + rw [proof_bitSubtractWithWork_length_21] at hlt + cases hb : (OAI.EditApproximation.bitSubtractWithWork left right false).2.1 + · simp only [hb, Bool.toNat_false, Nat.mul_zero, Nat.add_zero] at hvalue + omega + · simp only [hb, Bool.toNat_true, Bool.toNat_false, Nat.mul_one, Nat.add_zero] at hvalue + omega + have proof_bitDivModWithWork_value_23 (divisor : List.{0} Bool) (bits : List.{0} Bool) (hd : LT.lt.{0} 0 (OAI.EditApproximation.bitWordValue divisor)) : + OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).1 + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1 < OAI.EditApproximation.bitWordValue divisor := by + induction bits with + | nil => (simp [OAI.EditApproximation.bitDivModWithWork, OAI.EditApproximation.bitWordValue, hd]) + | cons bit bits ih => + let previous := OAI.EditApproximation.bitDivModWithWork divisor bits + let candidate := bit :: previous.2.1 + have hp : OAI.EditApproximation.bitWordValue bits = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue previous.1 + + OAI.EditApproximation.bitWordValue previous.2.1 := ih.1 + have hr : OAI.EditApproximation.bitWordValue previous.2.1 < OAI.EditApproximation.bitWordValue divisor := ih.2 + have hc : OAI.EditApproximation.bitWordValue candidate < 2 * OAI.EditApproximation.bitWordValue divisor := by + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + cases bit <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega + by_cases hlt : (OAI.EditApproximation.bitCompareWithWork candidate divisor).1 = .lt + · have hv := (proof_bitCompareWithWork_lt_16 candidate divisor).1 hlt + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 = .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * + OAI.EditApproximation.bitWordValue (false :: previous.1) + OAI.EditApproximation.bitWordValue candidate ∧ OAI.EditApproximation.bitWordValue candidate < _ + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_false]) + dsimp only [candidate, OAI.EditApproximation.bitWordValue] + nlinarith only [hp] + · exact hv + · have hv : OAI.EditApproximation.bitWordValue divisor ≤ OAI.EditApproximation.bitWordValue candidate := by + exact Nat.le_of_not_gt (fun h => hlt ((proof_bitCompareWithWork_lt_16 candidate divisor).2 h)) + have hs := proof_bitSubtractWithWork_sub_22 candidate divisor hv + simp only [OAI.EditApproximation.bitDivModWithWork, show (OAI.EditApproximation.bitCompareWithWork (bit :: (OAI.EditApproximation.bitDivModWithWork divisor bits).2.1) + divisor).1 ≠ .lt from hlt, ↓reduceIte] + change OAI.EditApproximation.bitWordValue (bit :: bits) = OAI.EditApproximation.bitWordValue divisor * OAI.EditApproximation.bitWordValue (true :: previous.1) + + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitSubtractWithWork candidate divisor false).1 < _ + rw [hs] + constructor + · (simp only [OAI.EditApproximation.bitWordValue, Bool.toNat_true]) + have he := Nat.sub_add_cancel hv + dsimp only [candidate, OAI.EditApproximation.bitWordValue] at he ⊢ + nlinarith only [hp, he] + · omega + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_binaryNaturalDivModWithWork_spec_24 (n : ℕ) (d : ℕ) (hd : LT.lt.{0} 0 d) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).1 = n / d ∧ + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork n d).2.1 = n % d := by + have h := proof_bitDivModWithWork_value_23 d.bits n.bits (by simpa only [proof_bitWordValue_bits_15] using hd) + simp only [proof_bitWordValue_bits_15] at h + have hmod : n % d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).2.1 := by + conv_lhs => rw [h.1] + simp only [Nat.add_mod, Nat.mul_mod_right, Nat.zero_add, Nat.mod_eq_of_lt h.2] + have hdiv : n / d = OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitDivModWithWork d.bits n.bits).1 := by + conv_lhs => rw [h.1] + rw [Nat.mul_add_div hd, Nat.div_eq_of_lt h.2, Nat.add_zero] + exact ⟨hdiv.symm, hmod.symm⟩ + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_seedGridSpacingWithWork_value_86 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 = OAI.EditApproximation.seedGridSpacing b P := by + have hv := (proof_binaryNaturalDivModWithWork_spec_24 b P hP).1 + unfold OAI.EditApproximation.seedGridSpacingWithWork OAI.EditApproximation.seedGridSpacing + dsimp only + split_ifs with ht + · have hq : b / P ≤ 1 := by + have h := (proof_wordLEWithWork_value_26 _ _).mp ht + change OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rwa [hv] at h + rw [max_eq_left hq] + rfl + · have hq : 1 ≤ b / P := by + have h := mt (proof_wordLEWithWork_value_26 _ _).mpr ht + change ¬ OAI.EditApproximation.bitWordValue (OAI.EditApproximation.binaryNaturalDivModWithWork b P).1 ≤ 1 at h + rw [hv] at h + exact Nat.le_of_lt (Nat.lt_of_not_ge h) + rw [max_eq_right hq] + exact hv + have proof_seedGridSpacingWithWork_pos_85 (b : ℕ) (P : ℕ) (hP : LT.lt.{0} 0 P) : + 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1 := by + rw [proof_seedGridSpacingWithWork_value_86 b P hP] + unfold OAI.EditApproximation.seedGridSpacing + omega + exact + let b := 2 ^ e + let center := (OAI.EditApproximation.roundStateWithWork (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) + (proof_seedGridSpacingWithWork_pos_85 b P hP) query).1 + OAI.EditApproximation.seedGridSpacingAllocation b P + OAI.EditApproximation.roundStateAllocation (OAI.EditApproximation.bitWordValue (OAI.EditApproximation.seedGridSpacingWithWork b P).1) query + + parentAllocation center + OAI.EditApproximation.BinaryFraction.centerEligibilityAllocation b F a (parentInitial center).1 + e + + if (OAI.EditApproximation.BinaryFraction.centerEligibilityWithWork b F a (parentInitial center).1).1 then + integerAllocation b center + OAI.EditApproximation.BinaryFraction.preparedOnlineReadAllocationRaw source target parent P F exponent H b + (Nat.two_pow_pos e) hP tau eta kappa child initial table R hc hi + childAllocation initialAllocation tableAllocation t center (integer b center).1 + else 0 + +def preparedLocalOnlineActionsSourceAllocationRawBand (N : ℕ) (query : OAI.EditApproximation.TargetInterval target.length) : ℕ := + parentAllocation query + OAI.EditApproximation.BinaryFraction.queryExponentsAllocation N F a (parentInitial query).1 + + OAI.EditApproximation.filterMapAllocation + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceWithWorkRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer e query) + (fun e => OAI.EditApproximation.BinaryFraction.preparedLocalOnlineScaleSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial table R hc hi t integer parentAllocation childAllocation initialAllocation + tableAllocation integerAllocation e query) + (OAI.EditApproximation.BinaryFraction.queryExponentsWithWork N F a (parentInitial query).1).1 + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation.BinaryFraction +variable {α : Type u_4} (source target : List α) {M : ℕ} (parent : TargetInterval source.length) (N P F exponent H Q eM eF : ℕ) (hP : 0 < P) (hM : M = 2 ^ eM) (hF : F = 2 ^ eF) (tau a eta kappa : BinaryFraction) (parentInitial : TargetInterval target.length → BinaryFraction × ℕ) (child initial : Fin M → TargetInterval target.length → BinaryFraction × ℕ) (R : ℕ) (hc : ∀ i r, (child i r).2 ≤ R) (hi : ∀ i r, (initial i r).2 ≤ R) (parentAllocation : TargetInterval target.length → ℕ) (childAllocation initialAllocation : Fin M → TargetInterval target.length → ℕ) + +def queryOnlineSelectAllocationRawBand (t : ℕ) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (keys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalOnlineActionsSourceAllocationRawBand source target parent P F exponent H hP tau a eta kappa + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryHistoryReadWithWork keys words) R hc hi (t - 1) integer + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryHistoryReadAllocation keys words) + integerAllocation N q + +def queryGroupSelectAllocationRawBand (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (drawAllocation : OAI.EditApproximation.CellGroupSourceAllocations M F Q) + (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) (words : List OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) : ℕ := + OAI.EditApproximation.BinaryFraction.preparedLocalCellGroupsSourceAllocationRawBand source target parent P F exponent Q eM eF hM hF hP tau a + parentInitial child initial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words) R hc hi + parentAllocation childAllocation initialAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys words) + draw drawAllocation N q + + +end OAI.EditApproximation.BinaryFraction +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory + +noncomputable def integerBinaryWorkRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) := + OAI.EditApproximation.computedFullOutputWork (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerQueryLocalWorkRawBand source target N) (OAI.EditApproximation.integerPreevaluationWork source target N epsilon) + (OAI.EditApproximation.computedQuerySetupWithWork N).2 (fun input => (OAI.EditApproximation.integerBinaryOutputRawBand source target N input).2) + (N + 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter + +def integerFinalAllocationRawBand (source target : List ℤ) (N : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if source.map OAI.EditApproximation.integerSymbolCode = target.map OAI.EditApproximation.integerSymbolCode then 0 else + OAI.EditApproximation.BinaryFraction.finalAnswerAllocation N + (OAI.EditApproximation.computedQueryMemoResultRawBand (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N + (OAI.EditApproximation.integerOccurrenceIndex source target) (OAI.EditApproximation.integerInputSymbolBits source target) + (OAI.EditApproximation.integerInputPositionBits target) input).value + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalRefinementFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (draw : OAI.EditApproximation.CountedCellGroupDraws M F Q) + (integer : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (drawAllocation : OAI.EditApproximation.CountedCellGroupAllocations M F Q) + (integerAllocation : ℕ → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + t parentInitial child initial R hc hi draw integer q readEarlier readCurrent).Footprint := +(OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsWithWork M parent N P F exponent t hP a parentInitial q) + (OAI.EditApproximation.BinaryFraction.queryEarlierInputsAllocation M parent N P F exponent t hP a parentInitial + parentAllocation q)).bind + (fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readEarlier earlierKeys + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierKeys : List (Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readEarlier he earlierKeys + (fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q)).bind + fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun (earlierWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.compute + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectWithWorkRawBand source target parent N P F exponent H hP tau a + eta kappa parentInitial child initial R hc hi t integer earlierKeys earlierWords q) + (OAI.EditApproximation.BinaryFraction.queryOnlineSelectAllocationRawBand source target parent N P F exponent H hP tau + a eta kappa parentInitial child initial R hc hi parentAllocation childAllocation initialAllocation t integer + integerAllocation earlierKeys earlierWords q)).bind + (fun + (onlineActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + have word : OAI.EditApproximation.BinaryFraction × ℕ := parentInitial q; + OAI.EditApproximation.BitQuery.charge word.2 + ((OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + word.1 q draw)).bind + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions onlineActions)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions onlineActions currentKeys currentWords + q))) + fun + (online : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + OAI.EditApproximation.BitQuery.Footprint.chargeOf (parentAllocation q) + ((OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.querySharedInputsWithWork M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw) + (OAI.EditApproximation.BinaryFraction.querySharedInputsAllocation M N F Q exponent eM eF hM hF parent a + (parentInitial q).1 q draw drawAllocation)).bind + (fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent sharedKeys + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr sharedKeys + (fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q)).bind + fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun (sharedWords : List OAI.EditApproximation.BinaryFraction) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryGroupSelectWithWorkRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi draw sharedKeys sharedWords q) + (OAI.EditApproximation.BinaryFraction.queryGroupSelectAllocationRawBand source target parent N P F exponent Q + eM eF hP hM hF tau a parentInitial child initial R hc hi parentAllocation childAllocation + initialAllocation draw drawAllocation sharedKeys sharedWords q)).bind + (fun + (selectedActions : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.queryNeededInputsWithWork selectedActions online)).bind + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords selectedActions online currentKeys currentWords q)) + fun + (groups : + List + (OAI.EditApproximation.BinaryBellmanAction (OAI.EditApproximation.TargetInterval target.length) + (Fin M × OAI.EditApproximation.TargetInterval target.length) M)) => + (OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.queryNeededInputsWithWork groups online) + (OAI.EditApproximation.queryNeededInputsAllocation groups online)).bind + (fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.collect readCurrent currentKeys + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentKeys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) => + OAI.EditApproximation.BitQuery.Footprint.collect readCurrent hr currentKeys + (fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.compute + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q)) + fun (currentWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.BitQuery.Footprint.computeOf + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishWithWork parent N P F a delta + parentInitial t earlierKeys earlierWords groups online currentKeys currentWords q) + (OAI.EditApproximation.BinaryFraction.queryRefinementFinishAllocation parent N P F a delta + parentInitial parentAllocation t earlierKeys earlierWords groups online currentKeys currentWords + q)) + +def queryLocalRandomSourcesFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (child initial : Fin M → OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (R : ℕ) + (hc : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (child i r).2 ≤ R) + (hi : ∀ (i : Fin M) (r : OAI.EditApproximation.TargetInterval target.length), (initial i r).2 ≤ R) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (childAllocation initialAllocation : Fin M → OAI.EditApproximation.TargetInterval target.length → ℕ) + (q : OAI.EditApproximation.TargetInterval target.length) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi q readGroup readInteger readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryGroupSourceGatherFootprint M N F Q exponent eM eF hM hF a parentInitial parentAllocation q + readGroup hg + (fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGather parent N P F exponent H hP tau a parentInitial child q readInteger + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (groupKeys : List (OAI.EditApproximation.GroupScalarKey M F Q)) + (groupWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryOnlineSourceGatherFootprint parent N P F exponent H hP tau a parentInitial parentAllocation + child childAllocation q readInteger hz + (fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) q readEarlier + readCurrent) + fun (onlineKeys : List (ℕ × OAI.EditApproximation.TargetInterval target.length)) + (onlineWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRefinementFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta t parentInitial child initial R hc hi + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadWithWork groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadWithWork onlineKeys onlineWords) parentAllocation + childAllocation initialAllocation + (OAI.EditApproximation.BinaryFraction.queryGroupDrawReadAllocation groupKeys groupWords) + (OAI.EditApproximation.BinaryFraction.queryOnlineIntegerReadAllocation onlineKeys onlineWords) q readEarlier + readCurrent he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open Finset + +def queryLocalBandFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (parentInitial : OAI.EditApproximation.TargetInterval target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (parentAllocation : OAI.EditApproximation.TargetInterval target.length → ℕ) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + parentInitial readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := by + have proof_gatheredWordLookupWithWork_cost_132 {κ : Type 0} (equal : κ → κ → Prod.{0, 0} Bool ℕ) (C : ℕ) (hC : ∀ (a b : κ), LE.le.{0} (equal a b).2 C) (keys : List.{0} κ) (values : List.{0} OAI.EditApproximation.BinaryFraction) (query : κ) : + (OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork equal keys values query).2 ≤ 1 + keys.length * (C + 1) := by + induction keys generalizing values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork, List.length_nil, Nat.zero_mul, Nat.add_zero, le_rfl] + | cons key keys ih => + cases values with + | nil => simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork]; omega + | cons value values => + have hc := hC query key + have hi := ih values + simp only [OAI.EditApproximation.BinaryFraction.gatheredWordLookupWithWork] + split_ifs <;> simp only [List.length_cons, Nat.add_mul, Nat.one_mul] <;> omega + have proof_bitCompareWithWork_cost_133 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).2 ≤ 4 * (left.length + right.length) + 1 := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => simp [OAI.EditApproximation.bitCompareNilLeftWithWork] + | cons b bs ih => + simp only [OAI.EditApproximation.bitCompareNilLeftWithWork, List.length_cons, List.length_nil] at * + omega + | cons a as ih => + cases right with + | nil => + have h := ih [] + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons, List.length_nil] at * + omega + | cons b bs => + have h := ih bs + simp only [OAI.EditApproximation.bitCompareWithWork, List.length_cons] at * + omega + have proof_binaryNaturalCompareWithWork_cost_134 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 ≤ 4 * (Nat.size a + Nat.size b) + 1 := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, Nat.size_eq_bits_len] using proof_bitCompareWithWork_cost_133 a.bits b.bits + have proof_naturalEqualWithWork_cost_135 (a : ℕ) (b : ℕ) (B : ℕ) (ha : LE.le.{0} a.size B) (hb : LE.le.{0} b.size B) : + (OAI.EditApproximation.naturalEqualWithWork a b).2 ≤ 8 * B + 2 := by + have h := proof_binaryNaturalCompareWithWork_cost_134 a b + change (OAI.EditApproximation.binaryNaturalCompareWithWork a b).2 + 1 ≤ _ + omega + have proof_coordinateEqualWithWork_cost_136 {M : ℕ} {n : ℕ} (a : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (b : Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n)) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.coordinateEqualWithWork a b).2 ≤ 24 * B + 8 := by + have hc := proof_naturalEqualWithWork_cost_135 a.1.val b.1.val B + ((Nat.size_le_size a.1.isLt.le).trans hM) ((Nat.size_le_size b.1.isLt.le).trans hM) + have hl := proof_naturalEqualWithWork_cost_135 a.2.lo b.2.lo B + ((Nat.size_le_size (a.2.ordered.trans a.2.valid)).trans hn) + ((Nat.size_le_size (b.2.ordered.trans b.2.valid)).trans hn) + have hh := proof_naturalEqualWithWork_cost_135 a.2.hi b.2.hi B + ((Nat.size_le_size a.2.valid).trans hn) ((Nat.size_le_size b.2.valid).trans hn) + change _ + _ + _ + 2 ≤ _ + omega + have proof_queryChildReadWithWork_cost_137 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (values : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (q : OAI.EditApproximation.TargetInterval n) (B : ℕ) (hM : LE.le.{0} M.size B) (hn : LE.le.{0} n.size B) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys values i q).2 ≤ 1 + keys.length * (24 * B + 9) := by + exact proof_gatheredWordLookupWithWork_cost_132 OAI.EditApproximation.coordinateEqualWithWork (24 * B + 8) + (fun a b => proof_coordinateEqualWithWork_cost_136 a b B hM hn) keys values (i, q) + have proof_queryChildReadWithWork_budget_131 {M : ℕ} {n : ℕ} (keys : List.{0} (Prod.{0, 0} (Fin M) (OAI.EditApproximation.TargetInterval n))) (words : List.{0} OAI.EditApproximation.BinaryFraction) (i : Fin M) (r : OAI.EditApproximation.TargetInterval n) : + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys words i r).2 ≤ OAI.EditApproximation.BinaryFraction.queryDataReadBudget M n keys := by + exact proof_queryChildReadWithWork_cost_137 keys words i r _ (Nat.le_max_left _ _) (Nat.le_max_right _ _) + exact + OAI.EditApproximation.queryBandGatherFootprint M parent N P F exponent hP a parentInitial parentAllocation q readMass + readInitial hm hi + (fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) q readGroup + readInteger readEarlier readCurrent) + fun (keys : List (Fin M × OAI.EditApproximation.TargetInterval target.length)) + (massWords initialWords : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalRandomSourcesFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a + eta kappa delta t parentInitial (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadWithWork keys initialWords) + (OAI.EditApproximation.BinaryFraction.queryDataReadBudget M target.length keys) (proof_queryChildReadWithWork_budget_131 keys massWords) (proof_queryChildReadWithWork_budget_131 keys initialWords) + parentAllocation (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys massWords) + (OAI.EditApproximation.BinaryFraction.queryChildReadAllocation keys initialWords) q readGroup readInteger + readEarlier readCurrent hg hz he hr + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def queryLocalProgramFootprintRawBand + {ι : Type u_1} + {α : Type u_2} + (source target : List α) + {M : ℕ} + [NeZero M] + (parent : OAI.EditApproximation.TargetInterval source.length) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (t : ℕ) + (readParent : OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readMass readInitial : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (readEarlier : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (readCurrent : Fin M × OAI.EditApproximation.TargetInterval target.length → + OAI.EditApproximation.BitQuery ι OAI.EditApproximation.BinaryFraction) + (hp : (key : OAI.EditApproximation.TargetInterval target.length) → (readParent key).Footprint) + (hm : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readMass key).Footprint) + (hi : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readInitial key).Footprint) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) + (he : (key : Fin M × ℕ × OAI.EditApproximation.TargetInterval target.length) → (readEarlier key).Footprint) + (hr : (key : Fin M × OAI.EditApproximation.TargetInterval target.length) → (readCurrent key).Footprint) : (OAI.EditApproximation.queryLocalProgramRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + readParent readMass readInitial readGroup readInteger q readEarlier readCurrent).Footprint := +OAI.EditApproximation.queryInitialGatherFootprint N P F exponent hP a q readParent hp + (fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa delta t + (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent) + fun (keys : List (OAI.EditApproximation.TargetInterval target.length)) + (words : List OAI.EditApproximation.BinaryFraction) => + OAI.EditApproximation.queryLocalBandFootprintRawBand source target parent N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta t (OAI.EditApproximation.BinaryFraction.queryParentReadWithWork keys words) + (OAI.EditApproximation.BinaryFraction.queryParentReadAllocation keys words) readMass readInitial readGroup + readInteger q readEarlier readCurrent hm hi hg hz he hr + +def queryPhysicalRandomDataRequestFootprintRawBand + {σ : Type u_1} + {α : Type u_2} + (source target : List α) + {M J : ℕ} + [NeZero M] + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (readGroup : OAI.EditApproximation.GroupScalarKey M F Q → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (readInteger : ℕ × OAI.EditApproximation.TargetInterval target.length → + ℕ → OAI.EditApproximation.BitQuery σ OAI.EditApproximation.BinaryFraction) + (q : OAI.EditApproximation.TargetInterval target.length) + (hg : (key : OAI.EditApproximation.GroupScalarKey M F Q) → (readGroup key).Footprint) + (hz : (key : ℕ × OAI.EditApproximation.TargetInterval target.length) → (range : ℕ) → (readInteger key range).Footprint) : (OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa + delta copies pass copy T S t ht node hbelow readGroup readInteger q).Footprint := by + have proof_combinedRank_lt_of_progress_80 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (first : OAI.EditApproximation.PhysicalTableRequest M J ny) (second : OAI.EditApproximation.PhysicalTableRequest M J ny) (hprogress : LT.lt.{0} second.remainingDepth first.remainingDepth ∧ + LE.le.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first) ∨ + LE.le.{0} second.remainingDepth first.remainingDepth ∧ + LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.rank T S second) + (OAI.EditApproximation.PhysicalTableRequest.rank T S first)) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S second < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S first := by + unfold OAI.EditApproximation.PhysicalTableRequest.combinedRank + rcases hprogress with h | h + · exact Nat.add_lt_add_of_lt_of_le h.1 h.2 + · exact Nat.add_lt_add_of_le_of_lt h.1 h.2 + have proof_sameIndexChild_progress_95 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state).remainingDepth < request.remainingDepth ∧ + OAI.EditApproximation.PhysicalTableRequest.rank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) ≤ OAI.EditApproximation.PhysicalTableRequest.rank T S request := by + constructor + · unfold OAI.EditApproximation.PhysicalTableRequest.remainingDepth OAI.EditApproximation.PhysicalTableRequest.sameIndexChild OAI.EditApproximation.physicalChild + dsimp only + omega + · exact le_rfl + have proof_combinedRank_sameIndexChild_94 {M : ℕ} {J : ℕ} {ny : ℕ} (T : ℕ) (S : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J ny) (hbelow : LT.lt.{0} (↑(Sigma.fst.{0, 0} request.node)) J) (i : Fin M) (state : OAI.EditApproximation.TargetInterval ny) : + OAI.EditApproximation.PhysicalTableRequest.combinedRank T S (OAI.EditApproximation.PhysicalTableRequest.sameIndexChild request hbelow i state) < OAI.EditApproximation.PhysicalTableRequest.combinedRank T S request := + proof_combinedRank_lt_of_progress_80 T S request _ (Or.inl (proof_sameIndexChild_progress_95 T S request hbelow i state)) + unfold OAI.EditApproximation.queryPhysicalRandomDataRequestRawBand + apply OAI.EditApproximation.queryLocalProgramFootprintRawBand + · intro r + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro input + apply OAI.EditApproximation.BitQuery.Footprint.mapKeysWithWork _ (fun _ => 1) + apply OAI.EditApproximation.queryMeanReadFootprint + intro j + exact OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _ + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + · intro key + exact (hg key).mapKeysWithWork _ (fun _ => 1) + · intro key range + exact (hz key range).mapKeysWithWork _ (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalEarlierReadFootprint copies pass copy T S t node hbelow q input).mapKeysWithWork _ + (fun _ => 1) + · intro input + exact (OAI.EditApproximation.queryPhysicalTableReadFootprint copies T S _ _).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyRefinementFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (passes copies pass copy T S t : ℕ) + (ht : 0 < t) + (node : OAI.EditApproximation.PhysicalNode M J) + (hbelow : ↑node.fst < J) + (time : Fin R) + (q : OAI.EditApproximation.TargetInterval target.length) : (OAI.EditApproximation.queryFamilyRefinementRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies pass copy T S t ht node hbelow time q).Footprint := +OAI.EditApproximation.queryPhysicalRandomDataRequestFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta + kappa delta copies pass copy T S t ht node hbelow + (OAI.EditApproximation.queryFamilyGroupRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) + (OAI.EditApproximation.queryFamilyOnlineRead target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ time) q + (OAI.EditApproximation.queryFamilyGroupReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + (OAI.EditApproximation.queryFamilyOnlineReadFootprint target N P F exponent H Q passes copies pass copy ⟨node, hbelow⟩ + time) + +def queryFamilyActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (request : OAI.EditApproximation.PhysicalTableRequest M J target.length) + (hindex : T < request.index) + (hbelow : ↑request.node.fst < J) : (OAI.EditApproximation.queryFamilyActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T S + passes copies request hindex hbelow).Footprint := by + have proof_active_request_eq_145 {α : Type u_1} {M : ℕ} {J : ℕ} (target : List.{u_1} α) (T : ℕ) (request : OAI.EditApproximation.PhysicalTableRequest M J (List.length.{u_1} target)) (hindex : LT.lt.{0} T request.index) : + OAI.EditApproximation.PhysicalTableRequest.refinement request.pass request.copy request.node T (request.index - T) + request.state = request := by + have hi : T + (request.index - T) = request.index := by omega + unfold OAI.EditApproximation.PhysicalTableRequest.refinement + rw [hi] + exact + (OAI.EditApproximation.queryFamilyRefinementFootprintRawBand source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta + passes copies request.pass request.copy T S (request.index - T) (Nat.sub_pos_of_lt hindex) + request.node hbelow (Fin.ofNat R (request.index - T - 1)) request.state).mapKeysWithWork _ (fun _ => 1) + +def queryFamilyBoundedActiveFootprintRawBand + {α : Type u_1} + {M J R : ℕ} + [NeZero M] + [NeZero R] + (source target : List α) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (tau a eta kappa delta : OAI.EditApproximation.BinaryFraction) + (T S passes copies : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) + (hindex : T < parent.val.index) + (hbelow : ↑parent.val.node.fst < J) : (OAI.EditApproximation.queryFamilyBoundedActiveRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF tau a eta kappa delta T + S passes copies parent hindex hbelow).Footprint := + OAI.EditApproximation.queryRestrictPhysicalBodyFootprint (passes + 1) copies T S parent _ + (OAI.EditApproximation.queryFamilyActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau a eta kappa delta T S passes copies parent.val hindex hbelow) + +def queryChargedFamilyTableFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (parent : { r : OAI.EditApproximation.PhysicalTableRequest M J target.length // + OAI.EditApproximation.PhysicalTableRequest.Bounded (passes + 1) copies T S r }) : (OAI.EditApproximation.queryChargedFamilyTableRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits parent).Footprint := by + have proof_table_rank_lt_99 {M : ℕ} {J : ℕ} {ny : ℕ} {passes : ℕ} {copies : ℕ} {T : ℕ} {S : ℕ} (parent : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (child : Subtype.{1} fun request => OAI.EditApproximation.PhysicalTableRequest.Bounded (M := M) (J := J) (ny := ny) passes copies T S request) (h : LT.lt.{0} (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S child.val) + (OAI.EditApproximation.PhysicalTableRequest.combinedRank T S parent.val)) : + OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr child : OAI.EditApproximation.ChargedPhysicalRequest M J ny passes copies T S) < OAI.EditApproximation.ChargedPhysicalRequest.rank (Sum.inr parent) := by + simpa only [OAI.EditApproximation.ChargedPhysicalRequest.rank, OAI.EditApproximation.ChargedPhysicalRequest.depth, OAI.EditApproximation.ChargedPhysicalRequest.index, ← Nat.add_assoc, OAI.EditApproximation.PhysicalTableRequest.combinedRank] using + Nat.add_lt_add_right h 1 + have proof_bitOrdering_matches_4 (high : Ordering) (a : Bool) (b : Bool) (x : ℕ) (y : ℕ) (h : OAI.EditApproximation.orderingMatches high x y) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitOrdering high a b) (a.toNat + 2 * x) (b.toNat + 2 * y) := by + rcases h with ⟨rfl, h⟩ | ⟨rfl, rfl⟩ | ⟨rfl, h⟩ + · exact Or.inl ⟨rfl, by cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩ + · cases a <;> cases b <;> simp [OAI.EditApproximation.bitOrdering, OAI.EditApproximation.orderingMatches] + · exact Or.inr (Or.inr ⟨rfl, by + cases a <;> cases b <;> simp only [Bool.toNat_false, Bool.toNat_true] <;> omega⟩) + have proof_bitCompareWithWork_matches_5 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.orderingMatches (OAI.EditApproximation.bitCompareWithWork left right).1 (OAI.EditApproximation.bitWordValue left) (OAI.EditApproximation.bitWordValue right) := by + induction left generalizing right with + | nil => + simp only [OAI.EditApproximation.bitCompareWithWork] + induction right with + | nil => (simp [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.orderingMatches, OAI.EditApproximation.bitWordValue]) + | cons b bs ih => + simpa only [OAI.EditApproximation.bitCompareNilLeftWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareNilLeftWithWork bs).1 false b 0 (OAI.EditApproximation.bitWordValue bs) ih + | cons a as ih => + cases right with + | nil => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue, Bool.toNat_false, Nat.add_zero, Nat.mul_zero, + Nat.zero_add] using proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as []).1 a false (OAI.EditApproximation.bitWordValue as) 0 (ih []) + | cons b bs => + simpa only [OAI.EditApproximation.bitCompareWithWork, OAI.EditApproximation.bitWordValue] using + proof_bitOrdering_matches_4 (OAI.EditApproximation.bitCompareWithWork as bs).1 a b (OAI.EditApproximation.bitWordValue as) (OAI.EditApproximation.bitWordValue bs) (ih bs) + have proof_bitCompareWithWork_lt_16 (left : List.{0} Bool) (right : List.{0} Bool) : + (OAI.EditApproximation.bitCompareWithWork left right).1 = .lt ↔ OAI.EditApproximation.bitWordValue left < OAI.EditApproximation.bitWordValue right := by + have h := proof_bitCompareWithWork_matches_5 left right + rcases h with ⟨h, hv⟩ | ⟨h, hv⟩ | ⟨h, hv⟩ <;> rw [h] <;> simp_all + all_goals omega + have proof_wordLEWithWork_value_26 (a : List.{0} Bool) (b : List.{0} Bool) : + (OAI.EditApproximation.wordLEWithWork a b).1 = true ↔ OAI.EditApproximation.bitWordValue a ≤ OAI.EditApproximation.bitWordValue b := by + simp only [OAI.EditApproximation.wordLEWithWork, Bool.not_eq_true', decide_eq_false_iff_not, + proof_bitCompareWithWork_lt_16, not_lt] + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_queryNaturalLEWithWork_value_140 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.wordLEWithWork a.bits b.bits).1 = true ↔ a ≤ b := by + simp only [proof_wordLEWithWork_value_26, proof_bitWordValue_bits_15] + have proof_binaryNaturalCompareWithWork_lt_53 (a : ℕ) (b : ℕ) : + (OAI.EditApproximation.binaryNaturalCompareWithWork a b).1 = .lt ↔ a < b := by + simpa only [OAI.EditApproximation.binaryNaturalCompareWithWork, proof_bitWordValue_bits_15] using proof_bitCompareWithWork_lt_16 a.bits b.bits + have hinit := OAI.EditApproximation.queryPhysicalInitialFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits parent.val.state + unfold OAI.EditApproximation.queryChargedFamilyTableRawBand + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.naturalWordLEAllocation parent.val.index.bits T.bits) ?_ + split + · exact (OAI.EditApproximation.queryChargedWarmupFootprint source target N P F (A parent.val.pass) (a parent.val.pass) + multiplier parent occurrence symbolBits positionBits).mapKeysWithWork _ (fun _ => 1) + · refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (parent.val.node.1.val.bits.length + J.bits.length) ?_ + split + · let interval := OAI.EditApproximation.physicalSourceInterval source.length parent.val.node + refine OAI.EditApproximation.BitQuery.Footprint.chargeOf (OAI.EditApproximation.saturatingSubtractAllocation interval.hi interval.lo + + OAI.EditApproximation.naturalWordLEAllocation (OAI.EditApproximation.saturatingSubtractWithWork interval.hi interval.lo).1 [true]) ?_ + split + · exact hinit.mapKeysWithWork _ (fun _ => 1) + · exact (OAI.EditApproximation.queryFamilyBoundedActiveFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + tau (a parent.val.pass) eta kappa delta T S passes copies parent _ _).mapKeysWithWork _ + (fun _ => 1) + · exact hinit.mapKeysWithWork _ (fun _ => 1) + +def queryChargedFamilyGlobalFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (request : OAI.EditApproximation.ChargedPhysicalRequest M J target.length (passes + 1) copies T S) : (OAI.EditApproximation.queryChargedFamilyGlobalRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse request).Footprint := by + cases request with + | inl entry => exact OAI.EditApproximation.BitQuery.Footprint.compute (coarse entry) (allocation entry) + | inr parent => + exact OAI.EditApproximation.queryChargedFamilyTableFootprintRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits parent + +def queryFamilyMemoRawFootprintRawBand + {M J R passes copies T S : ℕ} + [NeZero M] + [NeZero R] + (source target : List ℕ) + (N P F exponent H Q eM eF : ℕ) + (hP : 0 < P) + (hM : M = 2 ^ eM) + (hF : F = 2 ^ eF) + (A a : ℕ → OAI.EditApproximation.BinaryFraction) + (tau eta kappa delta : OAI.EditApproximation.BinaryFraction) + (multiplier : ℕ → ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (coarse : OAI.EditApproximation.PhysicalEntry M J target.length → OAI.EditApproximation.BinaryFraction × ℕ) + (allocation : OAI.EditApproximation.PhysicalEntry M J target.length → ℕ) + (draw : OAI.EditApproximation.PhysicalFamilyScalarDraw (M := M) (J := J) (R := R) target N P F exponent H Q passes copies) + (key : OAI.EditApproximation.QueryFamilyMemoKey (M := M) (J := J) (R := R) (passes := passes) (copies := copies) (T := T) (S := S) target N P F exponent H Q) : (OAI.EditApproximation.queryFamilyMemoRawRawBand (R := R) source target N P F exponent H Q eM eF hP hM hF A a tau eta kappa delta + multiplier occurrence symbolBits positionBits coarse draw key).Footprint := by + cases key with + | inl scalar => + exact OAI.EditApproximation.BitQuery.Footprint.computeOf (OAI.EditApproximation.queryFamilySourceWordWithWork target N P F exponent H Q draw scalar) + (Nat.size (draw scalar).val + 2) + | inr request => + exact (OAI.EditApproximation.queryChargedFamilyGlobalFootprintRawBand source target N P F exponent H Q eM eF hP hM hF + A a tau eta kappa delta multiplier occurrence symbolBits positionBits coarse allocation request).mapKeysWithWork + _ (fun _ => 1) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero +open MeasureTheory ProbabilityTheory + +def computedQueryMemoRawFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoRawRawBand source target N occurrence symbolBits positionBits input key).Footprint := by + have proof_computedParameterP_pos_141 (N : ℕ) : 0 < (OAI.EditApproximation.integerParameters N).P := + Nat.pow_pos (Nat.two_pow_pos _) + exact + OAI.EditApproximation.queryFamilyMemoRawFootprintRawBand source target N (OAI.EditApproximation.integerParameters N).P (OAI.EditApproximation.inputSmallLog N) + (40 * OAI.EditApproximation.smallLogExponent N) (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) + (OAI.EditApproximation.heightExponent N / 20) (OAI.EditApproximation.smallLogExponent N) (proof_computedParameterP_pos_141 N) rfl rfl + (fun pass => (OAI.EditApproximation.scheduledSeedWordWithWork N pass).1) + (fun pass => (OAI.EditApproximation.computedQueryParameters N pass).factor) + (OAI.EditApproximation.computedQueryParameters N 0).tau (OAI.EditApproximation.computedQueryParameters N 0).eta + (OAI.EditApproximation.computedQueryParameters N 0).kappa (OAI.EditApproximation.computedQueryParameters N 0).delta + (OAI.EditApproximation.scheduledSeedMultiplier N) occurrence symbolBits positionBits + (fun entry => (OAI.EditApproximation.BinaryFraction.nat (OAI.EditApproximation.clampedSeedNat input.1 entry), 0)) + (fun _ => 0) input.2 key + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open BitQuery +attribute [local instance] queryArityNeZero queryRoundsNeZero + +def computedQueryMemoFootprintRawBand + (source target : List ℕ) + (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) + (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) + (key : OAI.EditApproximation.ComputedFamilyMemoKey source target N) : (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input + key).Footprint := by + have proof_trimBitWordWithWork_value_6 (bits : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.trimBitWordWithWork bits).1 = OAI.EditApproximation.bitWordValue bits := by + induction bits with + | nil => rfl + | cons bit bits ih => + simp only [OAI.EditApproximation.trimBitWordWithWork] + split_ifs with h + · have ht : OAI.EditApproximation.bitWordValue bits = 0 := by rw [← ih, h.1]; rfl + simp [h.2, OAI.EditApproximation.bitWordValue, ht] + · (simp only [OAI.EditApproximation.bitWordValue, ih]) + have proof_bitAdder_value_1 (a : Bool) (b : Bool) (carry : Bool) : + (OAI.EditApproximation.bitSum a b carry).toNat + 2 * (OAI.EditApproximation.bitCarry a b carry).toNat = + a.toNat + b.toNat + carry.toNat := by + cases a <;> cases b <;> cases carry <;> decide + have proof_bitAddWithWork_value_2 (left : List.{0} Bool) (right : List.{0} Bool) (carry : Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitAddWithWork left right carry).1 = + OAI.EditApproximation.bitWordValue left + OAI.EditApproximation.bitWordValue right + carry.toNat := by + induction left generalizing right carry with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork] + induction right generalizing carry with + | nil => cases carry <;> simp [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue] + | cons b bs ih => + simp only [OAI.EditApproximation.bitAddNilLeftWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 false b carry + simp only [Bool.toNat_false] at h + omega + | cons a as ih => + cases right with + | nil => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a false carry + simp only [Bool.toNat_false] at h + omega + | cons b bs => + simp only [OAI.EditApproximation.bitAddWithWork, OAI.EditApproximation.bitWordValue, ih] + have h := proof_bitAdder_value_1 a b carry + omega + have proof_bitMulWithWork_value_0 (left : List.{0} Bool) (right : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitMulWithWork left right).1 = OAI.EditApproximation.bitWordValue left * OAI.EditApproximation.bitWordValue right := by + induction left with + | nil => simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue] + | cons bit bits ih => + cases bit <;> simp [OAI.EditApproximation.bitMulWithWork, OAI.EditApproximation.bitWordValue, proof_bitAddWithWork_value_2, ih] <;> ring + have proof_bitPowerWithWork_value_76 (base : List.{0} Bool) (n : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.bitPowerWithWork base n).1 = OAI.EditApproximation.bitWordValue base ^ n := by + induction n with + | zero => (simp [OAI.EditApproximation.bitPowerWithWork, OAI.EditApproximation.bitWordValue]) + | succ n ih => + simp only [OAI.EditApproximation.bitPowerWithWork, proof_trimBitWordWithWork_value_6, proof_bitMulWithWork_value_0, ih, pow_succ] + have proof_refinementBaseWithWork_value_143 (ell : List.{0} Bool) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.refinementBaseWithWork ell).1 = OAI.EditApproximation.bitWordValue ell ^ 10 + 1 := by + (simp only [OAI.EditApproximation.refinementBaseWithWork, proof_trimBitWordWithWork_value_6, proof_bitAddWithWork_value_2, + proof_bitPowerWithWork_value_76, OAI.EditApproximation.bitWordValue, Bool.toNat_true, Bool.toNat_false]) + have proof_bitWordValue_bits_15 (n : ℕ) : OAI.EditApproximation.bitWordValue n.bits = n := by + induction n using Nat.binaryRec' with + | zero => simp [OAI.EditApproximation.bitWordValue] + | bit bit n h ih => + rw [Nat.bits_append_bit n bit h] + cases bit <;> simp [OAI.EditApproximation.bitWordValue, ih, Nat.bit, Nat.add_comm] + have proof_computedQueryBase_value_144 (N : ℕ) : + OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) = OAI.EditApproximation.inputSmallLog N ^ 10 + 1 := by + simp only [OAI.EditApproximation.computedQueryBase, proof_refinementBaseWithWork_value_143, proof_bitWordValue_bits_15] + have proof_computedQueryBase_pos_142 (N : ℕ) : 0 < OAI.EditApproximation.bitWordValue (OAI.EditApproximation.computedQueryBase N) := by + rw [proof_computedQueryBase_value_144] + omega + exact + (OAI.EditApproximation.computedQueryMemoRawFootprintRawBand source target N occurrence symbolBits positionBits input + key).normalize + (OAI.EditApproximation.computedQueryBase N) (proof_computedQueryBase_pos_142 N) + (OAI.EditApproximation.queryFamilyMemoRemaining target N (OAI.EditApproximation.integerParameters N).P + (OAI.EditApproximation.inputSmallLog N) (40 * OAI.EditApproximation.smallLogExponent N) + (OAI.EditApproximation.inputHeight N) (OAI.EditApproximation.inputSmallLog N ^ 80) key) + + +end OAI.EditApproximation +end + +section +universe u v w u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 +namespace OAI.EditApproximation +open Filter MeasureTheory +attribute [local instance] queryRoundsNeZero + +def computedQueryTemporaryCellsFootprintRawBand (source target : List ℕ) (N : ℕ) + (occurrence : OAI.EditApproximation.BinaryMemo OAI.EditApproximation.PositionCounts) (symbolBits positionBits : ℕ) + (input : OAI.EditApproximation.ComputedFamilyInput source target N) : ℕ := + OAI.EditApproximation.BitQuery.Footprint.rankedBitMemoCells (OAI.EditApproximation.SourceRanked.rank OAI.EditApproximation.ChargedPhysicalRequest.rank) + (OAI.EditApproximation.computedQueryMemoNormalizedRawBand source target N occurrence symbolBits positionBits input) + (OAI.EditApproximation.computedQueryMemoFootprintRawBand source target N occurrence symbolBits positionBits input) + (16384 * OAI.EditApproximation.inputHeight N + 5) (OAI.EditApproximation.computedFamilyMemoCode source target N (OAI.EditApproximation.inputHeight N ^ 2)) + (fun key => (OAI.EditApproximation.computedFamilyMemoCodeWithWork source target N (OAI.EditApproximation.inputHeight N ^ 2) key).2) + (.inr (OAI.EditApproximation.localFinalRootRequest target N (OAI.EditApproximation.integerParameters N).T (OAI.EditApproximation.integerParameters N).S + (OAI.EditApproximation.inputHeight N) (Nat.two_pow_pos _) (OAI.EditApproximation.finalTargetState target.length))) .empty + +noncomputable def integerAcceptedSpaceTermsFootprintRawBand (source target : List ℤ) (N : ℕ) + (epsilon : OAI.EditApproximation.BinaryFraction) + (input : OAI.EditApproximation.ComputedFamilyInput (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : List ℕ := + let x := source.map OAI.EditApproximation.integerSymbolCode + let y := target.map OAI.EditApproximation.integerSymbolCode + [8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon, + 2 * OAI.EditApproximation.integerStoredDataSpace source target, + OAI.EditApproximation.computedQuerySetupAllocation N, + (OAI.EditApproximation.computedQueryMemoResultRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input).memory.fractionStorage, + OAI.EditApproximation.computedQueryTemporaryCellsFootprintRawBand x y N (OAI.EditApproximation.integerOccurrenceIndex source target) + (OAI.EditApproximation.integerInputSymbolBits source target) (OAI.EditApproximation.integerInputPositionBits target) input, + OAI.EditApproximation.computedFamilyCoarseCopyStorage x y N input, + OAI.EditApproximation.computedFamilyCoarseArrayCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseScratchCapacity x y N input, + OAI.EditApproximation.computedFamilyCoarseControlCapacity x y N input, + 4 * (OAI.EditApproximation.inputHeight N + (OAI.EditApproximation.integerParameters N).B + 4), + OAI.EditApproximation.integerFinalAllocationRawBand source target N input, + 8 * (N + 1)] + +noncomputable def integerBinarySpaceFootprintRawBand (source target : List ℤ) (N : ℕ) (epsilon : OAI.EditApproximation.BinaryFraction) + (outcome : OAI.EditApproximation.ComputedFullOutcome (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N) : ℕ := + if OAI.EditApproximation.physicalLargeInput N epsilon then + match outcome with + | .inl _ => 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + | .inr execution => (OAI.EditApproximation.integerAcceptedSpaceTermsFootprintRawBand source target N epsilon + (OAI.EditApproximation.computedExecutionAccepted _ _ N execution)).sum + else 8 * OAI.EditApproximation.integerPreevaluationWork source target N epsilon + + 2 * OAI.EditApproximation.integerStoredDataSpace source target + + OAI.EditApproximation.suffixDPAllocation (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) + 8 * (N + 1) + +theorem almostLinearEditDistanceRawBand (epsilon : OAI.EditApproximation.BinaryFraction) + (hepsilon : 0 < epsilon.value) (_hepsilonOne : epsilon.value < 1) + : + (∀ (source target : List ℤ) (N : ℕ), source.length + target.length ≤ N → + (2 / 3 : ℝ) ≤ (OAI.EditApproximation.computedFullLaw (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N epsilon).real + {outcome | EditDistortion.edit source target ≤ OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome ∧ + (OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome : ℝ) ≤ + (1 + (epsilon.value : ℝ)) * OAI.EditDistortion.edit source target}) ∧ + (∀ (source target : List ℤ) (N : ℕ), source = target → ∀ outcome, + OAI.EditApproximation.integerBinaryAnswerRawBand source target N epsilon outcome = 0) ∧ + (∀ (C : ℕ) (eta : ℝ), 0 < eta → ∀ᶠ N : ℕ in atTop, + ∀ source target : List ℤ, source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + (∫ outcome, OAI.EditApproximation.integerBinaryWorkRawBand source target N epsilon outcome + ∂OAI.EditApproximation.computedFullLaw (source.map OAI.EditApproximation.integerSymbolCode) (target.map OAI.EditApproximation.integerSymbolCode) N epsilon) ≤ + (N + 2 : ℝ) ^ (1 + eta)) ∧ + (∀ C : ℕ, ∀ᶠ N : ℕ in atTop, ∀ source target : List ℤ, + source.length + target.length ≤ N → + (∀ z ∈ source ++ target, z.natAbs ≤ (N + 2) ^ C) → + ∀ outcome, OAI.EditApproximation.integerBinarySpaceFootprintRawBand source target N epsilon outcome ≤ (N + 2) ^ (C + 65564)) := by + sorry + +end OAI.EditApproximation +end diff --git a/tasks/edit-approximation/tests/grade.py b/tasks/edit-approximation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/edit-approximation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/edit-approximation/tests/task.json b/tasks/edit-approximation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..852e460d9695196ec8690ef465dc699eb01ab4c5 --- /dev/null +++ b/tasks/edit-approximation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EditApproximation", + "comparator": { + "theorem_names": [ + "OAI.EditApproximation.almostLinearEditDistanceRawBand" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 17632 +} \ No newline at end of file diff --git a/tasks/edit-approximation/tests/test.sh b/tasks/edit-approximation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/edit-approximation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/edit-distance/environment/Dockerfile b/tasks/edit-distance/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/edit-distance/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/edit-distance/environment/fetch_mathlib.sh b/tasks/edit-distance/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/edit-distance/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/edit-distance/environment/lake-manifest.json b/tasks/edit-distance/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/edit-distance/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/edit-distance/environment/lakefile.lean b/tasks/edit-distance/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/edit-distance/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/edit-distance/environment/lean_setup.sh b/tasks/edit-distance/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/edit-distance/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/edit-distance/environment/pack_submission.py b/tasks/edit-distance/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/edit-distance/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/edit-distance/instruction.md b/tasks/edit-distance/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..edc4ce5b7c0d86c2a5dc52b5aeecbcb3a7838fc1 --- /dev/null +++ b/tasks/edit-distance/instruction.md @@ -0,0 +1,121 @@ +# openai/math challenge `EditDistance` (family 099) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 099 of the release, *The sharp distortion of edit distance into $\ell_1$* +(Convex and metric geometry). The family as a whole: Determines the least distortion of embedding edit distance on words of length at most $d$ into real $\ell_1$: it is $\exp(\Theta(\sqrt{\log d\,\log\log d}))$. Insertions, deletions and substitutions have unit cost. The constants are uniform over all finite alphabets with at least two symbols, even when the alphabet grows with $d$; binary words already force the lower bound. + +The challenge is `EditDistance`, also at `/opt/openai-math/challenges/EditDistance.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace EditDistortion + +universe u + +/-- A single unit-cost insertion, deletion, or (when enabled) substitution. -/ +inductive Step (substitutions : Bool) {Alpha : Type u} : List Alpha → List Alpha → Prop + | insert (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ q) (p ++ a :: q) + | delete (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ a :: q) (p ++ q) + | substitute (h : substitutions = true) (p q : List Alpha) (a b : Alpha) : + Step substitutions (p ++ a :: q) (p ++ b :: q) + +/-- An unrestricted script of exactly n unit edits. -/ +inductive Script (substitutions : Bool) {Alpha : Type u} : ℕ → List Alpha → List Alpha → Prop + | nil (x : List Alpha) : Script substitutions 0 x x + | cons {n : ℕ} {x y z : List Alpha} (first : Step substitutions x y) + (rest : Script substitutions n y z) : Script substitutions (n + 1) x z + +/-- Minimum script length. Scripts always exist (delete x and insert y). -/ +noncomputable def edit {Alpha : Type u} (x y : List Alpha) : ℕ := + sInf {n | Script true n x y} + +abbrev L1 := lp (fun _ : ℕ => ℝ) 1 + +/-- The product of the two maximal distance ratios. -/ +noncomputable def distortion {X : Type u} (ρ : X → X → ℝ) (f : X ↪ L1) : ℝ := + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ‖f x - f y‖ / ρ x y} * + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ρ x y / ‖f x - f y‖} + +/-- The infimum over injective maps to real absolutely summable sequences. -/ +noncomputable def leastDistortion {X : Type u} (ρ : X → X → ℝ) : ℝ := + sInf (Set.range (distortion ρ)) + +abbrev Words (Alpha : Type u) (d : ℕ) := {x : List Alpha // x.length ≤ d} + +noncomputable def E (Alpha : Type u) (d : ℕ) : ℝ := + leastDistortion (fun x y : Words Alpha d => (edit x.val y.val : ℝ)) + +noncomputable def exponentScale (c : ℝ) (d : ℕ) : ℝ := + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) + +/-- Supremum over finite alphabet cardinalities. -/ +noncomputable def alphabetSup (d : ℕ) : ℝ := + sSup {r : ℝ | ∃ n : ℕ, 2 ≤ n ∧ r = E (Fin n) d} + +/-- A finite nonempty subset of binary words of one common length. -/ +def BinaryWitness (c : ℝ) (d : ℕ) : Prop := + ∃ n : ℕ, n ≤ d ∧ ∃ S : Set (List Bool), S.Finite ∧ S.Nonempty ∧ + (∀ w ∈ S, w.length = n) ∧ + exponentScale c d ≤ leastDistortion (fun x y : S => (edit x.val y.val : ℝ)) + +/-- Uniform two-sided bounds with common positive constants and threshold. -/ +def MainClaim : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ (Alpha : Type u) [Fintype Alpha], 2 ≤ Fintype.card Alpha → + exponentScale c d ≤ E Alpha d ∧ E Alpha d ≤ exponentScale C d) ∧ + BinaryWitness c d ∧ + exponentScale c d ≤ alphabetSup d ∧ alphabetSup d ≤ exponentScale C d + +end EditDistortion + +universe u + +theorem edit_distance_main : EditDistortion.MainClaim.{u} := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EditDistance.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.edit_distance_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/edit-distance/solution/closure.txt b/tasks/edit-distance/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1242c4ba456eb61d44e7a9d50d768f0a263f645f --- /dev/null +++ b/tasks/edit-distance/solution/closure.txt @@ -0,0 +1,46 @@ +OAI.Combinatorics.EditApproximation.Definitions +OAI.Combinatorics.EditDistance.AlphabetLower +OAI.Combinatorics.EditDistance.AlphabetSupremum +OAI.Combinatorics.EditDistance.BinaryCode +OAI.Combinatorics.EditDistance.BinaryEmbedding +OAI.Combinatorics.EditDistance.BlockAlignment +OAI.Combinatorics.EditDistance.CutModels +OAI.Combinatorics.EditDistance.CutRealization +OAI.Combinatorics.EditDistance.Cuts +OAI.Combinatorics.EditDistance.DelimiterAlignment +OAI.Combinatorics.EditDistance.DepthInversion +OAI.Combinatorics.EditDistance.DirectSums +OAI.Combinatorics.EditDistance.Distortion +OAI.Combinatorics.EditDistance.DistortionMonotonicity +OAI.Combinatorics.EditDistance.DyadicScales +OAI.Combinatorics.EditDistance.Families +OAI.Combinatorics.EditDistance.FamilyRecursion +OAI.Combinatorics.EditDistance.FiniteLower +OAI.Combinatorics.EditDistance.FourierAverages +OAI.Combinatorics.EditDistance.FourierCharacters +OAI.Combinatorics.EditDistance.HashCuts +OAI.Combinatorics.EditDistance.Histograms +OAI.Combinatorics.EditDistance.LowerBound +OAI.Combinatorics.EditDistance.LowerDistortion +OAI.Combinatorics.EditDistance.LowerParameters +OAI.Combinatorics.EditDistance.Main +OAI.Combinatorics.EditDistance.MeanHistograms +OAI.Combinatorics.EditDistance.Metric +OAI.Combinatorics.EditDistance.Model +OAI.Combinatorics.EditDistance.PrimeCharacters +OAI.Combinatorics.EditDistance.PrimeDisplacement +OAI.Combinatorics.EditDistance.PrimePeriods +OAI.Combinatorics.EditDistance.PrimePool +OAI.Combinatorics.EditDistance.RecursiveControl +OAI.Combinatorics.EditDistance.RecursiveWords +OAI.Combinatorics.EditDistance.RowAlignment +OAI.Combinatorics.EditDistance.RowConstruction +OAI.Combinatorics.EditDistance.RowSeparation +OAI.Combinatorics.EditDistance.Slots +OAI.Combinatorics.EditDistance.UpperBase +OAI.Combinatorics.EditDistance.UpperBound +OAI.Combinatorics.EditDistance.UpperParameters +OAI.Combinatorics.EditDistance.UpperRecursion +OAI.Combinatorics.EditDistance.WholeMaps +OAI.Combinatorics.EditDistance.WindowRecursion +OAI.Combinatorics.EditDistance.Windows diff --git a/tasks/edit-distance/solution/reference.py b/tasks/edit-distance/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/edit-distance/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/edit-distance/solution/solve.sh b/tasks/edit-distance/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..78528492632b1364a73d7c8d5481670d05979a07 --- /dev/null +++ b/tasks/edit-distance/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EditDistance, i.e. module OAI.Combinatorics.EditDistance.Main and the +# 46 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EditDistance.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EditDistance" diff --git a/tasks/edit-distance/task.toml b/tasks/edit-distance/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fe0e6e5b9ac5aac347bac7286d597ee59d62b886 --- /dev/null +++ b/tasks/edit-distance/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/edit-distance" +version = "1.0.0" +description = "Prove EditDistance (openai/math family 099: The sharp distortion of edit distance into $\\ell_1$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EditDistance.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EditDistance" +family = "099" +family_title = "The sharp distortion of edit distance into $\\ell_1$" +subject = "Convex and metric geometry" +theorems = ["OAI.edit_distance_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EditDistance.Main" +reference_modules = 46 +reference_lean_bytes = 1686015 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1069 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13217 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/edit-distance/tests/Challenge.lean b/tasks/edit-distance/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c4829804568035424bb26401e6adf0f55b7cf0b --- /dev/null +++ b/tasks/edit-distance/tests/Challenge.lean @@ -0,0 +1,70 @@ +import Mathlib + +namespace OAI + +namespace EditDistortion + +universe u + +/-- A single unit-cost insertion, deletion, or (when enabled) substitution. -/ +inductive Step (substitutions : Bool) {Alpha : Type u} : List Alpha → List Alpha → Prop + | insert (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ q) (p ++ a :: q) + | delete (p q : List Alpha) (a : Alpha) : Step substitutions (p ++ a :: q) (p ++ q) + | substitute (h : substitutions = true) (p q : List Alpha) (a b : Alpha) : + Step substitutions (p ++ a :: q) (p ++ b :: q) + +/-- An unrestricted script of exactly n unit edits. -/ +inductive Script (substitutions : Bool) {Alpha : Type u} : ℕ → List Alpha → List Alpha → Prop + | nil (x : List Alpha) : Script substitutions 0 x x + | cons {n : ℕ} {x y z : List Alpha} (first : Step substitutions x y) + (rest : Script substitutions n y z) : Script substitutions (n + 1) x z + +/-- Minimum script length. Scripts always exist (delete x and insert y). -/ +noncomputable def edit {Alpha : Type u} (x y : List Alpha) : ℕ := + sInf {n | Script true n x y} + +abbrev L1 := lp (fun _ : ℕ => ℝ) 1 + +/-- The product of the two maximal distance ratios. -/ +noncomputable def distortion {X : Type u} (ρ : X → X → ℝ) (f : X ↪ L1) : ℝ := + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ‖f x - f y‖ / ρ x y} * + sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ r = ρ x y / ‖f x - f y‖} + +/-- The infimum over injective maps to real absolutely summable sequences. -/ +noncomputable def leastDistortion {X : Type u} (ρ : X → X → ℝ) : ℝ := + sInf (Set.range (distortion ρ)) + +abbrev Words (Alpha : Type u) (d : ℕ) := {x : List Alpha // x.length ≤ d} + +noncomputable def E (Alpha : Type u) (d : ℕ) : ℝ := + leastDistortion (fun x y : Words Alpha d => (edit x.val y.val : ℝ)) + +noncomputable def exponentScale (c : ℝ) (d : ℕ) : ℝ := + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) + +/-- Supremum over finite alphabet cardinalities. -/ +noncomputable def alphabetSup (d : ℕ) : ℝ := + sSup {r : ℝ | ∃ n : ℕ, 2 ≤ n ∧ r = E (Fin n) d} + +/-- A finite nonempty subset of binary words of one common length. -/ +def BinaryWitness (c : ℝ) (d : ℕ) : Prop := + ∃ n : ℕ, n ≤ d ∧ ∃ S : Set (List Bool), S.Finite ∧ S.Nonempty ∧ + (∀ w ∈ S, w.length = n) ∧ + exponentScale c d ≤ leastDistortion (fun x y : S => (edit x.val y.val : ℝ)) + +/-- Uniform two-sided bounds with common positive constants and threshold. -/ +def MainClaim : Prop := + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ (Alpha : Type u) [Fintype Alpha], 2 ≤ Fintype.card Alpha → + exponentScale c d ≤ E Alpha d ∧ E Alpha d ≤ exponentScale C d) ∧ + BinaryWitness c d ∧ + exponentScale c d ≤ alphabetSup d ∧ alphabetSup d ≤ exponentScale C d + +end EditDistortion + +universe u + +theorem edit_distance_main : EditDistortion.MainClaim.{u} := by + sorry + +end OAI diff --git a/tasks/edit-distance/tests/grade.py b/tasks/edit-distance/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/edit-distance/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/edit-distance/tests/task.json b/tasks/edit-distance/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..834d1676a015ed3f407c3116847579d041d4f8b7 --- /dev/null +++ b/tasks/edit-distance/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EditDistance", + "comparator": { + "theorem_names": [ + "OAI.edit_distance_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12317 +} \ No newline at end of file diff --git a/tasks/edit-distance/tests/test.sh b/tasks/edit-distance/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/edit-distance/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/egyptian-fractions/environment/Dockerfile b/tasks/egyptian-fractions/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/egyptian-fractions/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/egyptian-fractions/environment/fetch_mathlib.sh b/tasks/egyptian-fractions/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/egyptian-fractions/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/egyptian-fractions/environment/lake-manifest.json b/tasks/egyptian-fractions/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/egyptian-fractions/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/egyptian-fractions/environment/lakefile.lean b/tasks/egyptian-fractions/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/egyptian-fractions/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/egyptian-fractions/environment/lean_setup.sh b/tasks/egyptian-fractions/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/egyptian-fractions/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/egyptian-fractions/environment/pack_submission.py b/tasks/egyptian-fractions/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/egyptian-fractions/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/egyptian-fractions/instruction.md b/tasks/egyptian-fractions/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dc135cd6e203d972a5ae7a72dbd02bb960a6643b --- /dev/null +++ b/tasks/egyptian-fractions/instruction.md @@ -0,0 +1,175 @@ +# openai/math challenge `EgyptianFractions` (family 025) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 025 of the release, *Erd\H{o}s’s short Egyptian-fraction conjecture* +(Number theory). The family as a whole: Every rational $a/b$ with $1\le a if 1 ≤ a then egyptianLength a b else 0) + +def IsOneExpansion {k : ℕ} (n : Fin k → ℕ) : Prop := + (∀ i, 1 ≤ n i) ∧ StrictMono n ∧ + (∑ i : Fin k, (1 : ℚ) / (n i : ℚ)) = 1 + +def OneExpansions (k : ℕ) : Set (Fin k → ℕ) := + {n | IsOneExpansion n} + +def F (k : ℕ) : ℕ := + (OneExpansions k).ncard + +def D (k : ℕ) : Set ℕ := + {m | 2 ≤ m ∧ ∃ n : Fin k → ℕ, + IsOneExpansion n ∧ ∃ i : Fin k, n i = m} + +def missingDenominators (k : ℕ) : Set ℕ := + {m : ℕ | 2 ≤ m} \ D k + +def v (k : ℕ) : ℕ := + sInf (missingDenominators k) + +def prescribedSlope (k : ℕ) : ℝ := + Real.log (Real.log (v k : ℝ)) / (k : ℝ) + +theorem egyptian_length_is_minimum : + ∀ a b : ℕ, 1 ≤ a → a < b → + (∃ n : Fin (egyptianLength a b) → ℕ, + IsEgyptianExpansion ((a : ℚ) / (b : ℚ)) n) ∧ + (∀ k : ℕ, (∃ n : Fin k → ℕ, + IsEgyptianExpansion ((a : ℚ) / (b : ℚ)) n) → + egyptianLength a b ≤ k) := by + sorry + +theorem main_double_log_order : + ∃ c1 c2 : ℝ, 0 < c1 ∧ 0 < c2 ∧ ∃ b0 : ℕ, + ∀ b : ℕ, b0 ≤ b → + c1 * Real.log (Real.log (b : ℝ)) ≤ (maxEgyptianLength b : ℝ) ∧ + (maxEgyptianLength b : ℝ) ≤ c2 * Real.log (Real.log (b : ℝ)) := by + sorry + +theorem one_expansions_finite_and_bounded : + (∀ k : ℕ, Set.Finite (OneExpansions k) ∧ + F k ≤ k ^ (2 ^ k - 1)) ∧ + (∀ k : ℕ, ∀ n : Fin k → ℕ, IsOneExpansion n → + ∀ i : Fin k, n i ≤ k ^ (2 ^ i.val)) := by + sorry + +theorem counting_double_log_order : + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ k0 : ℕ, + ∀ k : ℕ, k0 ≤ k → + c * (k : ℝ) ≤ Real.log (Real.log (F k : ℝ)) ∧ + Real.log (Real.log (F k : ℝ)) ≤ C * (k : ℝ) := by + sorry + +theorem exact_marker_padding : + ∀ r : ℕ, 3 ≤ r → ∀ n : Fin r → ℕ, IsOneExpansion n → + ∀ m : ℕ, (∃ i : Fin r, n i = m) → + ∃ n' : Fin (r + 1) → ℕ, + IsOneExpansion n' ∧ ∃ i : Fin (r + 1), n' i = m := by + sorry + +theorem every_exact_marker_occurs : + ∀ m : ℕ, 2 ≤ m → ∃ k : ℕ, m ∈ D k := by + sorry + +theorem quantitative_marked_length : + ∀ ε : ℝ, 0 < ε → ∃ mε : ℕ, 2 ≤ mε ∧ + ∀ m : ℕ, mε ≤ m → + ∃ k : ℕ, ∃ n : Fin k → ℕ, + IsOneExpansion n ∧ + (∃ i : Fin k, n i = m) ∧ + (k : ℝ) ≤ (257 / Real.log 2 + ε) * Real.log (Real.log (m : ℝ)) := by + sorry + +theorem missing_denominator_semantics : + ∀ k : ℕ, + Set.Finite (D k) ∧ + (∃ m : ℕ, m ∈ missingDenominators k) ∧ + 2 ≤ v k ∧ v k ∉ D k ∧ + (∀ m : ℕ, 2 ≤ m → m < v k → m ∈ D k) ∧ + (1 ≤ k → v k ≤ 1 + k ^ (2 ^ (k - 1))) := by + sorry + +theorem prescribed_denominator_corollary : + (∃ k0 : ℕ, ∀ k : ℕ, k0 ≤ k → + Real.exp (Real.exp ((k : ℝ) / 600)) ≤ (v k : ℝ) ∧ + v k ≤ 1 + k ^ (2 ^ (k - 1))) ∧ + (Real.log 2 / 257 ≤ Filter.liminf prescribedSlope Filter.atTop ∧ + Filter.liminf prescribedSlope Filter.atTop ≤ + Filter.limsup prescribedSlope Filter.atTop ∧ + Filter.limsup prescribedSlope Filter.atTop ≤ Real.log 2) ∧ + (∀ c : ℝ, c < Real.log 2 / 257 → ∃ k0 : ℕ, + ∀ k : ℕ, k0 ≤ k → + Real.exp (Real.exp (c * (k : ℝ))) ≤ (v k : ℝ)) := by + sorry + +end Problem337 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EgyptianFractions.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Problem337.egyptian_length_is_minimum`, `OAI.Problem337.main_double_log_order`, `OAI.Problem337.one_expansions_finite_and_bounded`, `OAI.Problem337.counting_double_log_order`, `OAI.Problem337.exact_marker_padding`, `OAI.Problem337.every_exact_marker_occurs`, `OAI.Problem337.quantitative_marked_length`, `OAI.Problem337.missing_denominator_semantics`, `OAI.Problem337.prescribed_denominator_corollary` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/egyptian-fractions/solution/closure.txt b/tasks/egyptian-fractions/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..532e0e6d32e29bea6a603932549797b923791799 --- /dev/null +++ b/tasks/egyptian-fractions/solution/closure.txt @@ -0,0 +1,290 @@ +OAI.NumberTheory.EgyptianFractions.BackwardExpansions +OAI.NumberTheory.EgyptianFractions.BadPredecessorCount +OAI.NumberTheory.EgyptianFractions.BilinearFourier +OAI.NumberTheory.EgyptianFractions.BinaryExpansion +OAI.NumberTheory.EgyptianFractions.CeilResidue +OAI.NumberTheory.EgyptianFractions.CleanupApplications +OAI.NumberTheory.EgyptianFractions.CollisionCounting +OAI.NumberTheory.EgyptianFractions.CompositeBadDensity +OAI.NumberTheory.EgyptianFractions.CompositeBadDensityBound +OAI.NumberTheory.EgyptianFractions.CompositeBadModuli +OAI.NumberTheory.EgyptianFractions.CompositeConductorBudget +OAI.NumberTheory.EgyptianFractions.CompositeMarkedReduction +OAI.NumberTheory.EgyptianFractions.CompositeRationalSupply +OAI.NumberTheory.EgyptianFractions.CompositeSpectral +OAI.NumberTheory.EgyptianFractions.CompositeSupplyFinal +OAI.NumberTheory.EgyptianFractions.CompositeSupplySize +OAI.NumberTheory.EgyptianFractions.CompositeUnitMixing +OAI.NumberTheory.EgyptianFractions.ConcreteGoodExposure +OAI.NumberTheory.EgyptianFractions.CorrelationPhase +OAI.NumberTheory.EgyptianFractions.CountingFromMain +OAI.NumberTheory.EgyptianFractions.CountingFromMarkers +OAI.NumberTheory.EgyptianFractions.CountingPadding +OAI.NumberTheory.EgyptianFractions.CountingTransfer +OAI.NumberTheory.EgyptianFractions.CountingUpper +OAI.NumberTheory.EgyptianFractions.CubeFreeDensity +OAI.NumberTheory.EgyptianFractions.CubeFreeRationalSupply +OAI.NumberTheory.EgyptianFractions.CubeFreeSupplyFromExceptions +OAI.NumberTheory.EgyptianFractions.CyclicCeilingCount +OAI.NumberTheory.EgyptianFractions.CyclicDiscrepancy +OAI.NumberTheory.EgyptianFractions.CyclicDiscrepancyAutomatic +OAI.NumberTheory.EgyptianFractions.CyclicInterval +OAI.NumberTheory.EgyptianFractions.CyclicKernel +OAI.NumberTheory.EgyptianFractions.CyclicSmoothing +OAI.NumberTheory.EgyptianFractions.Defs +OAI.NumberTheory.EgyptianFractions.DenominatorBound +OAI.NumberTheory.EgyptianFractions.DenseExpansion +OAI.NumberTheory.EgyptianFractions.DenseModularPair +OAI.NumberTheory.EgyptianFractions.DenseModularSupply +OAI.NumberTheory.EgyptianFractions.DensePairing +OAI.NumberTheory.EgyptianFractions.DensityAssembly +OAI.NumberTheory.EgyptianFractions.DensityLoss +OAI.NumberTheory.EgyptianFractions.DensityMomentBound +OAI.NumberTheory.EgyptianFractions.DensityMomentBridge +OAI.NumberTheory.EgyptianFractions.DensityParameters +OAI.NumberTheory.EgyptianFractions.DescentDecay +OAI.NumberTheory.EgyptianFractions.DescentDepth +OAI.NumberTheory.EgyptianFractions.DescentHolder +OAI.NumberTheory.EgyptianFractions.DescentRecurrence +OAI.NumberTheory.EgyptianFractions.DeterministicMean +OAI.NumberTheory.EgyptianFractions.DeterministicMeanDecay +OAI.NumberTheory.EgyptianFractions.DeterministicPhaseWindow +OAI.NumberTheory.EgyptianFractions.DeterministicReciprocal +OAI.NumberTheory.EgyptianFractions.DeterministicResidueSupply +OAI.NumberTheory.EgyptianFractions.DiscreteFirstDerivative +OAI.NumberTheory.EgyptianFractions.DiscreteSecondDerivative +OAI.NumberTheory.EgyptianFractions.Distinctize +OAI.NumberTheory.EgyptianFractions.DivisorBandDecay +OAI.NumberTheory.EgyptianFractions.DivisorClassAssembly +OAI.NumberTheory.EgyptianFractions.DivisorClasses +OAI.NumberTheory.EgyptianFractions.DivisorCounting +OAI.NumberTheory.EgyptianFractions.DivisorDensity +OAI.NumberTheory.EgyptianFractions.DivisorEnergyNesting +OAI.NumberTheory.EgyptianFractions.DivisorFactorBound +OAI.NumberTheory.EgyptianFractions.DivisorLocalFactor +OAI.NumberTheory.EgyptianFractions.DivisorMomentAbsorption +OAI.NumberTheory.EgyptianFractions.DivisorMomentFinalBudget +OAI.NumberTheory.EgyptianFractions.DivisorPointwiseUniform +OAI.NumberTheory.EgyptianFractions.DivisorPrefixCounting +OAI.NumberTheory.EgyptianFractions.DivisorSplit +OAI.NumberTheory.EgyptianFractions.DivisorSquareMean +OAI.NumberTheory.EgyptianFractions.DyadicBands +OAI.NumberTheory.EgyptianFractions.DyadicSum +OAI.NumberTheory.EgyptianFractions.EgyptianExistence +OAI.NumberTheory.EgyptianFractions.EightProductConductor +OAI.NumberTheory.EgyptianFractions.EightProductRationalSupply +OAI.NumberTheory.EgyptianFractions.ExactPadding +OAI.NumberTheory.EgyptianFractions.ExposedCorrelation +OAI.NumberTheory.EgyptianFractions.FejerBounds +OAI.NumberTheory.EgyptianFractions.FejerBudget +OAI.NumberTheory.EgyptianFractions.FejerExponentialBudget +OAI.NumberTheory.EgyptianFractions.FejerSampleMean +OAI.NumberTheory.EgyptianFractions.FiniteBox +OAI.NumberTheory.EgyptianFractions.FiniteEulerBound +OAI.NumberTheory.EgyptianFractions.FiniteExpansion +OAI.NumberTheory.EgyptianFractions.FiniteExposureAverage +OAI.NumberTheory.EgyptianFractions.FiniteGoodExposure +OAI.NumberTheory.EgyptianFractions.FinitePowerSaving +OAI.NumberTheory.EgyptianFractions.FiniteResidueIndices +OAI.NumberTheory.EgyptianFractions.FirstDerivativeSum +OAI.NumberTheory.EgyptianFractions.FiveProducts +OAI.NumberTheory.EgyptianFractions.FixedSumFinite +OAI.NumberTheory.EgyptianFractions.ForwardDifference +OAI.NumberTheory.EgyptianFractions.FourierCommonRealization +OAI.NumberTheory.EgyptianFractions.FourierFailureBounds +OAI.NumberTheory.EgyptianFractions.FourierFrequencyGap +OAI.NumberTheory.EgyptianFractions.FourierSecondMoment +OAI.NumberTheory.EgyptianFractions.GeometricCharacterBound +OAI.NumberTheory.EgyptianFractions.GeometricRandomRanges +OAI.NumberTheory.EgyptianFractions.GeometricRandomResidues +OAI.NumberTheory.EgyptianFractions.GeometricRawDensity +OAI.NumberTheory.EgyptianFractions.GoodNumeratorSets +OAI.NumberTheory.EgyptianFractions.GreedyBudget +OAI.NumberTheory.EgyptianFractions.GreedyPreparation +OAI.NumberTheory.EgyptianFractions.GreedyStep +OAI.NumberTheory.EgyptianFractions.HammingException +OAI.NumberTheory.EgyptianFractions.HarmonicMoment +OAI.NumberTheory.EgyptianFractions.HarmonicPrefixBudget +OAI.NumberTheory.EgyptianFractions.HighResidueDistribution +OAI.NumberTheory.EgyptianFractions.HitCount +OAI.NumberTheory.EgyptianFractions.HyperbolaCorrelation +OAI.NumberTheory.EgyptianFractions.HyperbolaDyadicBridge +OAI.NumberTheory.EgyptianFractions.HyperbolaTypeII +OAI.NumberTheory.EgyptianFractions.IndependentBlockSelection +OAI.NumberTheory.EgyptianFractions.IntermediateBandBudget +OAI.NumberTheory.EgyptianFractions.IntermediateBandDecay +OAI.NumberTheory.EgyptianFractions.IntermediatePrefixClass +OAI.NumberTheory.EgyptianFractions.IntermediatePrimeClass +OAI.NumberTheory.EgyptianFractions.IteratedDifferencing +OAI.NumberTheory.EgyptianFractions.LargeClassUniform +OAI.NumberTheory.EgyptianFractions.LargePrefixClass +OAI.NumberTheory.EgyptianFractions.LargePrefixHarmonic +OAI.NumberTheory.EgyptianFractions.LargePrimeDivisors +OAI.NumberTheory.EgyptianFractions.LeastResidueBridge +OAI.NumberTheory.EgyptianFractions.LengthBasic +OAI.NumberTheory.EgyptianFractions.LevelFailureMean +OAI.NumberTheory.EgyptianFractions.LogWeightedSums +OAI.NumberTheory.EgyptianFractions.Main +OAI.NumberTheory.EgyptianFractions.MainLowerAppend +OAI.NumberTheory.EgyptianFractions.MainLowerVerified +OAI.NumberTheory.EgyptianFractions.MainUpperReduction +OAI.NumberTheory.EgyptianFractions.MajorArcApproximationBridge +OAI.NumberTheory.EgyptianFractions.MangoldtMajorArcReduction +OAI.NumberTheory.EgyptianFractions.MangoldtMinorArcActual +OAI.NumberTheory.EgyptianFractions.MarkedBudget +OAI.NumberTheory.EgyptianFractions.MarkedCleanup +OAI.NumberTheory.EgyptianFractions.MarkedConstruction +OAI.NumberTheory.EgyptianFractions.MarkedEndgame +OAI.NumberTheory.EgyptianFractions.MarkedFinalReduction +OAI.NumberTheory.EgyptianFractions.MarkedGreedy +OAI.NumberTheory.EgyptianFractions.MarkedGreedyDensity +OAI.NumberTheory.EgyptianFractions.MarkedGreedyLength +OAI.NumberTheory.EgyptianFractions.MarkedGrouping +OAI.NumberTheory.EgyptianFractions.MarkedGroupingFin +OAI.NumberTheory.EgyptianFractions.MarkedGroupingUnits +OAI.NumberTheory.EgyptianFractions.MarkedPrefixBridge +OAI.NumberTheory.EgyptianFractions.MarkedPrimeSupplyReduction +OAI.NumberTheory.EgyptianFractions.MarkedQuantitative +OAI.NumberTheory.EgyptianFractions.MarkedReduction +OAI.NumberTheory.EgyptianFractions.MarkedThreePrimeReduction +OAI.NumberTheory.EgyptianFractions.MarkerCoverage +OAI.NumberTheory.EgyptianFractions.MarkerOccurrence +OAI.NumberTheory.EgyptianFractions.MinorArcApproximation +OAI.NumberTheory.EgyptianFractions.MinorArcBudget +OAI.NumberTheory.EgyptianFractions.MinorArcLogWindow +OAI.NumberTheory.EgyptianFractions.MinorArcMeasure +OAI.NumberTheory.EgyptianFractions.MinorArcRealWindow +OAI.NumberTheory.EgyptianFractions.MinorArcVaughan +OAI.NumberTheory.EgyptianFractions.MissingSemantics +OAI.NumberTheory.EgyptianFractions.MonotoneBlocks +OAI.NumberTheory.EgyptianFractions.OddPrimorial +OAI.NumberTheory.EgyptianFractions.PhaseExtension +OAI.NumberTheory.EgyptianFractions.PrefixGap +OAI.NumberTheory.EgyptianFractions.PrefixGrowth +OAI.NumberTheory.EgyptianFractions.PrescribedAnalysis +OAI.NumberTheory.EgyptianFractions.PrescribedCorollary +OAI.NumberTheory.EgyptianFractions.PrescribedInversion +OAI.NumberTheory.EgyptianFractions.PrimeFactorPrefix +OAI.NumberTheory.EgyptianFractions.PrimeGcdHits +OAI.NumberTheory.EgyptianFractions.PrimeHits +OAI.NumberTheory.EgyptianFractions.PrimeObstruction +OAI.NumberTheory.EgyptianFractions.PrimePool +OAI.NumberTheory.EgyptianFractions.PrimePoolSelection +OAI.NumberTheory.EgyptianFractions.PrimePrefixSize +OAI.NumberTheory.EgyptianFractions.PrimeProductBound +OAI.NumberTheory.EgyptianFractions.PrimeProductFibers +OAI.NumberTheory.EgyptianFractions.PrimeProductGrowth +OAI.NumberTheory.EgyptianFractions.PrimeReciprocalBound +OAI.NumberTheory.EgyptianFractions.PrimeReciprocalSharp +OAI.NumberTheory.EgyptianFractions.PrimeTripleAsymptotics +OAI.NumberTheory.EgyptianFractions.PrimeTripleExclusion +OAI.NumberTheory.EgyptianFractions.RandomCommonRealization +OAI.NumberTheory.EgyptianFractions.RandomCorrelation +OAI.NumberTheory.EgyptianFractions.RandomExposure +OAI.NumberTheory.EgyptianFractions.RandomGcdBound +OAI.NumberTheory.EgyptianFractions.RandomGcdMarginal +OAI.NumberTheory.EgyptianFractions.RandomProductFourier +OAI.NumberTheory.EgyptianFractions.RandomProductParameters +OAI.NumberTheory.EgyptianFractions.RandomResidueRealization +OAI.NumberTheory.EgyptianFractions.RandomSecondMoment +OAI.NumberTheory.EgyptianFractions.RandomSelection +OAI.NumberTheory.EgyptianFractions.RankinAdmissibility +OAI.NumberTheory.EgyptianFractions.RankinBand +OAI.NumberTheory.EgyptianFractions.RationalArcVolume +OAI.NumberTheory.EgyptianFractions.RationalDivisorLift +OAI.NumberTheory.EgyptianFractions.RationalDivisorSupplyAlgebra +OAI.NumberTheory.EgyptianFractions.RationalDivisorSupplyBridge +OAI.NumberTheory.EgyptianFractions.RationalPhaseHyperbola +OAI.NumberTheory.EgyptianFractions.RationalPhaseSpacing +OAI.NumberTheory.EgyptianFractions.RationalSupplyFromThreePrimes +OAI.NumberTheory.EgyptianFractions.RationalSupplyReduction +OAI.NumberTheory.EgyptianFractions.RationalSupplyScaling +OAI.NumberTheory.EgyptianFractions.RawDensityExistence +OAI.NumberTheory.EgyptianFractions.RawDensityParameters +OAI.NumberTheory.EgyptianFractions.RawDensityUpper +OAI.NumberTheory.EgyptianFractions.RealPhaseEnvelope +OAI.NumberTheory.EgyptianFractions.RealTypeI +OAI.NumberTheory.EgyptianFractions.ReciprocalDerivatives +OAI.NumberTheory.EgyptianFractions.ReciprocalDifferencingBudget +OAI.NumberTheory.EgyptianFractions.ReciprocalPhase +OAI.NumberTheory.EgyptianFractions.ReciprocalPhaseCancellation +OAI.NumberTheory.EgyptianFractions.ReciprocalPhasePreparation +OAI.NumberTheory.EgyptianFractions.ReciprocalPhaseRegularity +OAI.NumberTheory.EgyptianFractions.ReciprocalPhaseScale +OAI.NumberTheory.EgyptianFractions.ReciprocalPhaseUniform +OAI.NumberTheory.EgyptianFractions.ReciprocalTerminalSum +OAI.NumberTheory.EgyptianFractions.ReducedCharacter +OAI.NumberTheory.EgyptianFractions.ReducedCollisionFourier +OAI.NumberTheory.EgyptianFractions.RemoveRepetitions +OAI.NumberTheory.EgyptianFractions.RepeatedSquaring +OAI.NumberTheory.EgyptianFractions.ResidueDenominator +OAI.NumberTheory.EgyptianFractions.ResidueDenominatorCertificate +OAI.NumberTheory.EgyptianFractions.ResidueLevels +OAI.NumberTheory.EgyptianFractions.ResidueRegimeSplice +OAI.NumberTheory.EgyptianFractions.ResidueStep +OAI.NumberTheory.EgyptianFractions.ResidueWideDenominator +OAI.NumberTheory.EgyptianFractions.RestrictedRoughAsymptotic +OAI.NumberTheory.EgyptianFractions.RoughDivisorAsymptotic +OAI.NumberTheory.EgyptianFractions.RoughModulusBlocks +OAI.NumberTheory.EgyptianFractions.RoughModulusCollision +OAI.NumberTheory.EgyptianFractions.RoughPart +OAI.NumberTheory.EgyptianFractions.SampleWordTransfer +OAI.NumberTheory.EgyptianFractions.SampledDenominatorCertificate +OAI.NumberTheory.EgyptianFractions.SampledResidueDenominator +OAI.NumberTheory.EgyptianFractions.SecondDerivativeBudget +OAI.NumberTheory.EgyptianFractions.SecondDerivativeTest +OAI.NumberTheory.EgyptianFractions.SecondDifference +OAI.NumberTheory.EgyptianFractions.SecondMomentAssembly +OAI.NumberTheory.EgyptianFractions.SeparatedIntervalCount +OAI.NumberTheory.EgyptianFractions.SimultaneousSelection +OAI.NumberTheory.EgyptianFractions.SmallPrimeClass +OAI.NumberTheory.EgyptianFractions.SmallPrimeDivisors +OAI.NumberTheory.EgyptianFractions.SmallPrimeMoment +OAI.NumberTheory.EgyptianFractions.SmallPrimeRankin +OAI.NumberTheory.EgyptianFractions.SmallPrimeSelectedClass +OAI.NumberTheory.EgyptianFractions.SmoothRankin +OAI.NumberTheory.EgyptianFractions.SmoothRankinBounds +OAI.NumberTheory.EgyptianFractions.SparseBadDivisorTail +OAI.NumberTheory.EgyptianFractions.SplitArithmetic +OAI.NumberTheory.EgyptianFractions.SubcriticalPowerSum +OAI.NumberTheory.EgyptianFractions.SupplyAsymptotics +OAI.NumberTheory.EgyptianFractions.SupplySize +OAI.NumberTheory.EgyptianFractions.TerminalAssembly +OAI.NumberTheory.EgyptianFractions.TerminalBridge +OAI.NumberTheory.EgyptianFractions.TerminalDepth +OAI.NumberTheory.EgyptianFractions.TerminalFiniteBudget +OAI.NumberTheory.EgyptianFractions.TerminalRecursion +OAI.NumberTheory.EgyptianFractions.ThinSupplyBase +OAI.NumberTheory.EgyptianFractions.ThreePrimeAnalyticReduction +OAI.NumberTheory.EgyptianFractions.ThreePrimeContinuousEnergy +OAI.NumberTheory.EgyptianFractions.ThreePrimeContinuousFourier +OAI.NumberTheory.EgyptianFractions.ThreePrimeMangoldt +OAI.NumberTheory.EgyptianFractions.ThreePrimeMangoldtBridge +OAI.NumberTheory.EgyptianFractions.ThreePrimeMangoldtIntegral +OAI.NumberTheory.EgyptianFractions.ThreePrimePartialSummation +OAI.NumberTheory.EgyptianFractions.ThreePrimeSingularSeries +OAI.NumberTheory.EgyptianFractions.ThreePrimeWeighted +OAI.NumberTheory.EgyptianFractions.TruncatedDivisors +OAI.NumberTheory.EgyptianFractions.TypeIIBlockScalar +OAI.NumberTheory.EgyptianFractions.UniformDivisorMoment +OAI.NumberTheory.EgyptianFractions.UniformSecondMoment +OAI.NumberTheory.EgyptianFractions.UpperSlope +OAI.NumberTheory.EgyptianFractions.VanDerCorput +OAI.NumberTheory.EgyptianFractions.VaughanBilinear +OAI.NumberTheory.EgyptianFractions.VaughanCutoff +OAI.NumberTheory.EgyptianFractions.VaughanDecomposition +OAI.NumberTheory.EgyptianFractions.VaughanDyadic +OAI.NumberTheory.EgyptianFractions.VaughanDyadicDecomposition +OAI.NumberTheory.EgyptianFractions.VaughanDyadicEstimate +OAI.NumberTheory.EgyptianFractions.VaughanDyadicUniform +OAI.NumberTheory.EgyptianFractions.VaughanEstimate +OAI.NumberTheory.EgyptianFractions.VaughanHyperbola +OAI.NumberTheory.EgyptianFractions.VaughanHyperbolicNearRational +OAI.NumberTheory.EgyptianFractions.VaughanIdentity +OAI.NumberTheory.EgyptianFractions.VaughanNearRational +OAI.NumberTheory.EgyptianFractions.VaughanOptimized +OAI.NumberTheory.EgyptianFractions.VaughanRealTypeIHyperbolic +OAI.NumberTheory.EgyptianFractions.VaughanTypeI +OAI.NumberTheory.EgyptianFractions.VaughanTypeINormalized +OAI.NumberTheory.EgyptianFractions.VaughanWeighted +OAI.NumberTheory.EgyptianFractions.WeightedBinomial diff --git a/tasks/egyptian-fractions/solution/reference.py b/tasks/egyptian-fractions/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/egyptian-fractions/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/egyptian-fractions/solution/solve.sh b/tasks/egyptian-fractions/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2baebc0b53cae375e859e9c21f0d53baf8ec7f5d --- /dev/null +++ b/tasks/egyptian-fractions/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EgyptianFractions, i.e. module OAI.NumberTheory.EgyptianFractions.Main and the +# 290 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.EgyptianFractions.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EgyptianFractions" diff --git a/tasks/egyptian-fractions/task.toml b/tasks/egyptian-fractions/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca2caaee0ba090c0383002f47bbf799be86b16f9 --- /dev/null +++ b/tasks/egyptian-fractions/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/egyptian-fractions" +version = "1.0.0" +description = "Prove EgyptianFractions (openai/math family 025: Erd\\H{o}s’s short Egyptian-fraction conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EgyptianFractions.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EgyptianFractions" +family = "025" +family_title = "Erd\\H{o}s’s short Egyptian-fraction conjecture" +subject = "Number theory" +theorems = ["OAI.Problem337.egyptian_length_is_minimum", "OAI.Problem337.main_double_log_order", "OAI.Problem337.one_expansions_finite_and_bounded", "OAI.Problem337.counting_double_log_order", "OAI.Problem337.exact_marker_padding", "OAI.Problem337.every_exact_marker_occurs", "OAI.Problem337.quantitative_marked_length", "OAI.Problem337.missing_denominator_semantics", "OAI.Problem337.prescribed_denominator_corollary"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.EgyptianFractions.Main" +reference_modules = 290 +reference_lean_bytes = 1625178 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 763 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13162 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/egyptian-fractions/tests/Challenge.lean b/tasks/egyptian-fractions/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..792eb7539b90cd9f59a8f818c149a3d658fc9ab2 --- /dev/null +++ b/tasks/egyptian-fractions/tests/Challenge.lean @@ -0,0 +1,124 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace Problem337 + +def IsEgyptianExpansion {k : ℕ} (x : ℚ) (n : Fin k → ℕ) : Prop := + (∀ i, 2 ≤ n i) ∧ StrictMono n ∧ + (∑ i : Fin k, (1 : ℚ) / (n i : ℚ)) = x + +def egyptianLengths (a b : ℕ) : Set ℕ := + {k | ∃ n : Fin k → ℕ, + IsEgyptianExpansion ((a : ℚ) / (b : ℚ)) n} + +def egyptianLength (a b : ℕ) : ℕ := + sInf (egyptianLengths a b) + +def maxEgyptianLength (b : ℕ) : ℕ := + (Finset.range b).sup (fun a => if 1 ≤ a then egyptianLength a b else 0) + +def IsOneExpansion {k : ℕ} (n : Fin k → ℕ) : Prop := + (∀ i, 1 ≤ n i) ∧ StrictMono n ∧ + (∑ i : Fin k, (1 : ℚ) / (n i : ℚ)) = 1 + +def OneExpansions (k : ℕ) : Set (Fin k → ℕ) := + {n | IsOneExpansion n} + +def F (k : ℕ) : ℕ := + (OneExpansions k).ncard + +def D (k : ℕ) : Set ℕ := + {m | 2 ≤ m ∧ ∃ n : Fin k → ℕ, + IsOneExpansion n ∧ ∃ i : Fin k, n i = m} + +def missingDenominators (k : ℕ) : Set ℕ := + {m : ℕ | 2 ≤ m} \ D k + +def v (k : ℕ) : ℕ := + sInf (missingDenominators k) + +def prescribedSlope (k : ℕ) : ℝ := + Real.log (Real.log (v k : ℝ)) / (k : ℝ) + +theorem egyptian_length_is_minimum : + ∀ a b : ℕ, 1 ≤ a → a < b → + (∃ n : Fin (egyptianLength a b) → ℕ, + IsEgyptianExpansion ((a : ℚ) / (b : ℚ)) n) ∧ + (∀ k : ℕ, (∃ n : Fin k → ℕ, + IsEgyptianExpansion ((a : ℚ) / (b : ℚ)) n) → + egyptianLength a b ≤ k) := by + sorry + +theorem main_double_log_order : + ∃ c1 c2 : ℝ, 0 < c1 ∧ 0 < c2 ∧ ∃ b0 : ℕ, + ∀ b : ℕ, b0 ≤ b → + c1 * Real.log (Real.log (b : ℝ)) ≤ (maxEgyptianLength b : ℝ) ∧ + (maxEgyptianLength b : ℝ) ≤ c2 * Real.log (Real.log (b : ℝ)) := by + sorry + +theorem one_expansions_finite_and_bounded : + (∀ k : ℕ, Set.Finite (OneExpansions k) ∧ + F k ≤ k ^ (2 ^ k - 1)) ∧ + (∀ k : ℕ, ∀ n : Fin k → ℕ, IsOneExpansion n → + ∀ i : Fin k, n i ≤ k ^ (2 ^ i.val)) := by + sorry + +theorem counting_double_log_order : + ∃ c C : ℝ, 0 < c ∧ 0 < C ∧ ∃ k0 : ℕ, + ∀ k : ℕ, k0 ≤ k → + c * (k : ℝ) ≤ Real.log (Real.log (F k : ℝ)) ∧ + Real.log (Real.log (F k : ℝ)) ≤ C * (k : ℝ) := by + sorry + +theorem exact_marker_padding : + ∀ r : ℕ, 3 ≤ r → ∀ n : Fin r → ℕ, IsOneExpansion n → + ∀ m : ℕ, (∃ i : Fin r, n i = m) → + ∃ n' : Fin (r + 1) → ℕ, + IsOneExpansion n' ∧ ∃ i : Fin (r + 1), n' i = m := by + sorry + +theorem every_exact_marker_occurs : + ∀ m : ℕ, 2 ≤ m → ∃ k : ℕ, m ∈ D k := by + sorry + +theorem quantitative_marked_length : + ∀ ε : ℝ, 0 < ε → ∃ mε : ℕ, 2 ≤ mε ∧ + ∀ m : ℕ, mε ≤ m → + ∃ k : ℕ, ∃ n : Fin k → ℕ, + IsOneExpansion n ∧ + (∃ i : Fin k, n i = m) ∧ + (k : ℝ) ≤ (257 / Real.log 2 + ε) * Real.log (Real.log (m : ℝ)) := by + sorry + +theorem missing_denominator_semantics : + ∀ k : ℕ, + Set.Finite (D k) ∧ + (∃ m : ℕ, m ∈ missingDenominators k) ∧ + 2 ≤ v k ∧ v k ∉ D k ∧ + (∀ m : ℕ, 2 ≤ m → m < v k → m ∈ D k) ∧ + (1 ≤ k → v k ≤ 1 + k ^ (2 ^ (k - 1))) := by + sorry + +theorem prescribed_denominator_corollary : + (∃ k0 : ℕ, ∀ k : ℕ, k0 ≤ k → + Real.exp (Real.exp ((k : ℝ) / 600)) ≤ (v k : ℝ) ∧ + v k ≤ 1 + k ^ (2 ^ (k - 1))) ∧ + (Real.log 2 / 257 ≤ Filter.liminf prescribedSlope Filter.atTop ∧ + Filter.liminf prescribedSlope Filter.atTop ≤ + Filter.limsup prescribedSlope Filter.atTop ∧ + Filter.limsup prescribedSlope Filter.atTop ≤ Real.log 2) ∧ + (∀ c : ℝ, c < Real.log 2 / 257 → ∃ k0 : ℕ, + ∀ k : ℕ, k0 ≤ k → + Real.exp (Real.exp (c * (k : ℝ))) ≤ (v k : ℝ)) := by + sorry + +end Problem337 + +end + +end OAI diff --git a/tasks/egyptian-fractions/tests/grade.py b/tasks/egyptian-fractions/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/egyptian-fractions/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/egyptian-fractions/tests/task.json b/tasks/egyptian-fractions/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..57664f051725e942e3998531004629f93e43a103 --- /dev/null +++ b/tasks/egyptian-fractions/tests/task.json @@ -0,0 +1,23 @@ +{ + "challenge": "EgyptianFractions", + "comparator": { + "theorem_names": [ + "OAI.Problem337.egyptian_length_is_minimum", + "OAI.Problem337.main_double_log_order", + "OAI.Problem337.one_expansions_finite_and_bounded", + "OAI.Problem337.counting_double_log_order", + "OAI.Problem337.exact_marker_padding", + "OAI.Problem337.every_exact_marker_occurs", + "OAI.Problem337.quantitative_marked_length", + "OAI.Problem337.missing_denominator_semantics", + "OAI.Problem337.prescribed_denominator_corollary" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12262 +} \ No newline at end of file diff --git a/tasks/egyptian-fractions/tests/test.sh b/tasks/egyptian-fractions/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/egyptian-fractions/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/eilenberg-ganea/environment/Dockerfile b/tasks/eilenberg-ganea/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/eilenberg-ganea/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/eilenberg-ganea/environment/fetch_mathlib.sh b/tasks/eilenberg-ganea/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/eilenberg-ganea/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/eilenberg-ganea/environment/lake-manifest.json b/tasks/eilenberg-ganea/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/eilenberg-ganea/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/eilenberg-ganea/environment/lakefile.lean b/tasks/eilenberg-ganea/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/eilenberg-ganea/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/eilenberg-ganea/environment/lean_setup.sh b/tasks/eilenberg-ganea/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/eilenberg-ganea/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/eilenberg-ganea/environment/pack_submission.py b/tasks/eilenberg-ganea/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/eilenberg-ganea/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/eilenberg-ganea/instruction.md b/tasks/eilenberg-ganea/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39e8151528dfb0da7632a7c9630e124faa7136e5 --- /dev/null +++ b/tasks/eilenberg-ganea/instruction.md @@ -0,0 +1,175 @@ +# openai/math challenge `EilenbergGanea` (family 249) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 249 of the release, *A finitely generated counterexample to Eilenberg–Ganea* +(Group theory). The family as a whole: Constructs a finitely generated residually finite group with integral cohomological dimension two and geometric dimension three, disproving the Eilenberg–Ganea conjecture. It has no two-dimensional classifying space, even with infinitely many cells. + +The challenge is `EilenbergGanea`, also at `/opt/openai-math/challenges/EilenbergGanea.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Classical Set Topology + +namespace EilenbergGanea + +/-- The signed words encode the relators `x²y⁻⁵` and `x²(yx⁻¹)³`. -/ +def seedWord : Bool → List (Bool × Bool) + | false => [(false, true), (false, true), (true, false), (true, false), + (true, false), (true, false), (true, false)] + | true => [(false, true), (false, true), (true, true), (false, false), + (true, true), (false, false), (true, true), (false, false)] + +def boundaryLength (relation : Bool) : ℕ := 3 * (seedWord relation).length + +abbrev RoseVertex := Option (Bool × Fin 2) +abbrev SeedVertex := RoseVertex ⊕ Bool +abbrev CircleEdge := Bool × Fin 3 +abbrev Sector := (relation : Bool) × Fin (boundaryLength relation) +abbrev SeedEdge := CircleEdge ⊕ Sector +abbrev SeedCell := SeedVertex ⊕ (SeedEdge ⊕ Sector) + +def circleStart (edge : CircleEdge) : RoseVertex := + ![none, some (edge.1, 0), some (edge.1, 1)] edge.2 + +def circleEnd (edge : CircleEdge) : RoseVertex := + ![some (edge.1, 0), some (edge.1, 1), none] edge.2 + +def sectorLetter (sector : Sector) : Bool × Bool := + (seedWord sector.1).get ⟨sector.2.val / 3, by + have bound := sector.2.isLt + dsimp [boundaryLength] at bound + omega⟩ + +def sectorCircleEdge (sector : Sector) : CircleEdge := + ((sectorLetter sector).1, if (sectorLetter sector).2 then + ⟨sector.2.val % 3, Nat.mod_lt _ (by decide)⟩ else + ⟨2 - sector.2.val % 3, by omega⟩) + +def sectorStart (sector : Sector) : RoseVertex := + if (sectorLetter sector).2 then circleStart (sectorCircleEdge sector) + else circleEnd (sectorCircleEdge sector) + +def nextSector (sector : Sector) : Sector := + ⟨sector.1, ⟨(sector.2.val + 1) % boundaryLength sector.1, + Nat.mod_lt _ (by have := sector.2.isLt; omega)⟩⟩ + +def edgeVertices : SeedEdge → Finset SeedVertex + | .inl edge => {.inl (circleStart edge), .inl (circleEnd edge)} + | .inr sector => {.inr sector.1, .inl (sectorStart sector)} + +def sectorEdges (sector : Sector) : Finset SeedEdge := + {.inl (sectorCircleEdge sector), .inr sector, .inr (nextSector sector)} + +def sectorVertices (sector : Sector) : Finset SeedVertex := + (sectorEdges sector).biUnion edgeVertices + +def properFace : SeedCell → SeedCell → Prop + | .inl vertex, .inr (.inl edge) => vertex ∈ edgeVertices edge + | .inl vertex, .inr (.inr sector) => vertex ∈ sectorVertices sector + | .inr (.inl edge), .inr (.inr sector) => edge ∈ sectorEdges sector + | _, _ => False + +/-- Comparability graph of the seven vertices, 51 edges and 45 sectors. -/ +def seedGraph : SimpleGraph SeedCell where + Adj first second := properFace first second ∨ properFace second first + symm := ⟨fun _ _ adjacent => adjacent.elim Or.inr Or.inl⟩ + loopless := ⟨by + intro cell + rcases cell with vertex | cell + · simp [properFace] + · rcases cell with edge | sector <;> simp [properFace]⟩ + +def artinRelations {Vertex : Type*} (graph : SimpleGraph Vertex) : Set (FreeGroup Vertex) := + {word | ∃ first second, graph.Adj first second ∧ + word = FreeGroup.of first * FreeGroup.of second * + (FreeGroup.of first)⁻¹ * (FreeGroup.of second)⁻¹} + +abbrev ArtinGroup {Vertex : Type*} (graph : SimpleGraph Vertex) := + PresentedGroup (artinRelations graph) + +def height {Vertex : Type*} (graph : SimpleGraph Vertex) : + ArtinGroup graph →* Multiplicative ℤ := + PresentedGroup.toGroup (f := fun _ : Vertex => Multiplicative.ofAdd (1 : ℤ)) (by + rintro word ⟨first, second, _, rfl⟩ + simp) + +abbrev SourceGroup := (height seedGraph).ker + +/-- Projective dimension of the trivial integral left group-ring module. -/ +def cohomologicalDimension (GroupType : Type*) [Group GroupType] : WithBot ℕ∞ := + CategoryTheory.projectiveDimension + (ModuleCat.of (MonoidAlgebra ℤ GroupType) + (Representation.trivial ℤ GroupType ℤ).asModule) + +universe u + +/-- Ordinary classifying CW spaces, with no bound on the cardinality of their cells. -/ +def HasClassifyingSpace (GroupType : Type*) [Group GroupType] (dimension : ℕ) : Prop := + ∃ (Space : Type u) (_ : TopologicalSpace Space) (_ : T2Space Space) + (_ : Topology.CWComplex (Set.univ : Set Space)), + (∀ degree : ℕ, dimension < degree → + IsEmpty (Topology.CWComplex.cell (Set.univ : Set Space) degree)) ∧ + PathConnectedSpace Space ∧ + ∃ basepoint : Space, Nonempty (FundamentalGroup Space basepoint ≃* GroupType) ∧ + ∃ (Cover : Type u) (_ : TopologicalSpace Cover), ContractibleSpace Cover ∧ + ∃ projection : Cover → Space, IsCoveringMap projection ∧ Function.Surjective projection + +theorem source_main : + Group.FG SourceGroup ∧ Group.ResiduallyFinite SourceGroup ∧ + cohomologicalDimension SourceGroup = 2 ∧ + HasClassifyingSpace.{0} SourceGroup 3 ∧ + ¬ HasClassifyingSpace.{u} SourceGroup 2 := by + sorry + +end EilenbergGanea + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EilenbergGanea.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EilenbergGanea.source_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/eilenberg-ganea/solution/closure.txt b/tasks/eilenberg-ganea/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..86061eeb103a6df5e1b9701f9757532b9b01003f --- /dev/null +++ b/tasks/eilenberg-ganea/solution/closure.txt @@ -0,0 +1,40 @@ +OAI.AlgebraicTopology.CWComplex.CellularPaths +OAI.AlgebraicTopology.CWComplex.Collar +OAI.AlgebraicTopology.CWComplex.Cover +OAI.AlgebraicTopology.CWComplex.CoverTopology +OAI.AlgebraicTopology.CWComplex.Presentation +OAI.AlgebraicTopology.Cubical.ArtinChains +OAI.AlgebraicTopology.Cubical.Chains +OAI.AlgebraicTopology.Cubical.Descending +OAI.AlgebraicTopology.Cubical.HeightChains +OAI.AlgebraicTopology.Cubical.PathChains +OAI.AlgebraicTopology.Cubical.Realization +OAI.AlgebraicTopology.Cubical.Singular +OAI.AlgebraicTopology.Integral.Contraction +OAI.AlgebraicTopology.Simplicial.Chains +OAI.GroupTheory.Presentation.KernelCycles +OAI.GroupTheory.RightAngledArtin.Basic +OAI.GroupTheory.RightAngledArtin.CubeDescents +OAI.GroupTheory.RightAngledArtin.ResidualFiniteness +OAI.GroupTheory.RightAngledArtin.TraceWords +OAI.Topology.EilenbergGanea.AffineTransport +OAI.Topology.EilenbergGanea.CliqueCohomology +OAI.Topology.EilenbergGanea.CubicalCover +OAI.Topology.EilenbergGanea.Dimension +OAI.Topology.EilenbergGanea.IntegralDegree +OAI.Topology.EilenbergGanea.IntegralModules +OAI.Topology.EilenbergGanea.LevelBasis +OAI.Topology.EilenbergGanea.LevelTransport +OAI.Topology.EilenbergGanea.Main +OAI.Topology.EilenbergGanea.Model +OAI.Topology.EilenbergGanea.PresentationAlignment +OAI.Topology.EilenbergGanea.PresentationComparison +OAI.Topology.EilenbergGanea.Regularization +OAI.Topology.EilenbergGanea.Seed +OAI.Topology.EilenbergGanea.SeedChains +OAI.Topology.EilenbergGanea.SeedConnection +OAI.Topology.EilenbergGanea.SeedContraction +OAI.Topology.EilenbergGanea.SeedHolonomy +OAI.Topology.EilenbergGanea.SmallHolonomy +OAI.Topology.EilenbergGanea.UnitaryWords +OAI.Topology.EilenbergGanea.WordEquations diff --git a/tasks/eilenberg-ganea/solution/reference.py b/tasks/eilenberg-ganea/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/eilenberg-ganea/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/eilenberg-ganea/solution/solve.sh b/tasks/eilenberg-ganea/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ee3aa7cddd8e9e73382667feee1336057b34c901 --- /dev/null +++ b/tasks/eilenberg-ganea/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EilenbergGanea, i.e. module OAI.Topology.EilenbergGanea.Main and the +# 40 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Topology.EilenbergGanea.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EilenbergGanea" diff --git a/tasks/eilenberg-ganea/task.toml b/tasks/eilenberg-ganea/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..15db4d66223cd8ddb88ebc2977340bce8f9b2efe --- /dev/null +++ b/tasks/eilenberg-ganea/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/eilenberg-ganea" +version = "1.0.0" +description = "Prove EilenbergGanea (openai/math family 249: A finitely generated counterexample to Eilenberg–Ganea) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EilenbergGanea.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EilenbergGanea" +family = "249" +family_title = "A finitely generated counterexample to Eilenberg–Ganea" +subject = "Group theory" +theorems = ["OAI.EilenbergGanea.source_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Topology.EilenbergGanea.Main" +reference_modules = 40 +reference_lean_bytes = 1718355 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 4559 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13246 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/eilenberg-ganea/tests/Challenge.lean b/tasks/eilenberg-ganea/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..677151ca9a12208e29f94e5cad9b9735854439d5 --- /dev/null +++ b/tasks/eilenberg-ganea/tests/Challenge.lean @@ -0,0 +1,124 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Classical Set Topology + +namespace EilenbergGanea + +/-- The signed words encode the relators `x²y⁻⁵` and `x²(yx⁻¹)³`. -/ +def seedWord : Bool → List (Bool × Bool) + | false => [(false, true), (false, true), (true, false), (true, false), + (true, false), (true, false), (true, false)] + | true => [(false, true), (false, true), (true, true), (false, false), + (true, true), (false, false), (true, true), (false, false)] + +def boundaryLength (relation : Bool) : ℕ := 3 * (seedWord relation).length + +abbrev RoseVertex := Option (Bool × Fin 2) +abbrev SeedVertex := RoseVertex ⊕ Bool +abbrev CircleEdge := Bool × Fin 3 +abbrev Sector := (relation : Bool) × Fin (boundaryLength relation) +abbrev SeedEdge := CircleEdge ⊕ Sector +abbrev SeedCell := SeedVertex ⊕ (SeedEdge ⊕ Sector) + +def circleStart (edge : CircleEdge) : RoseVertex := + ![none, some (edge.1, 0), some (edge.1, 1)] edge.2 + +def circleEnd (edge : CircleEdge) : RoseVertex := + ![some (edge.1, 0), some (edge.1, 1), none] edge.2 + +def sectorLetter (sector : Sector) : Bool × Bool := + (seedWord sector.1).get ⟨sector.2.val / 3, by + have bound := sector.2.isLt + dsimp [boundaryLength] at bound + omega⟩ + +def sectorCircleEdge (sector : Sector) : CircleEdge := + ((sectorLetter sector).1, if (sectorLetter sector).2 then + ⟨sector.2.val % 3, Nat.mod_lt _ (by decide)⟩ else + ⟨2 - sector.2.val % 3, by omega⟩) + +def sectorStart (sector : Sector) : RoseVertex := + if (sectorLetter sector).2 then circleStart (sectorCircleEdge sector) + else circleEnd (sectorCircleEdge sector) + +def nextSector (sector : Sector) : Sector := + ⟨sector.1, ⟨(sector.2.val + 1) % boundaryLength sector.1, + Nat.mod_lt _ (by have := sector.2.isLt; omega)⟩⟩ + +def edgeVertices : SeedEdge → Finset SeedVertex + | .inl edge => {.inl (circleStart edge), .inl (circleEnd edge)} + | .inr sector => {.inr sector.1, .inl (sectorStart sector)} + +def sectorEdges (sector : Sector) : Finset SeedEdge := + {.inl (sectorCircleEdge sector), .inr sector, .inr (nextSector sector)} + +def sectorVertices (sector : Sector) : Finset SeedVertex := + (sectorEdges sector).biUnion edgeVertices + +def properFace : SeedCell → SeedCell → Prop + | .inl vertex, .inr (.inl edge) => vertex ∈ edgeVertices edge + | .inl vertex, .inr (.inr sector) => vertex ∈ sectorVertices sector + | .inr (.inl edge), .inr (.inr sector) => edge ∈ sectorEdges sector + | _, _ => False + +/-- Comparability graph of the seven vertices, 51 edges and 45 sectors. -/ +def seedGraph : SimpleGraph SeedCell where + Adj first second := properFace first second ∨ properFace second first + symm := ⟨fun _ _ adjacent => adjacent.elim Or.inr Or.inl⟩ + loopless := ⟨by + intro cell + rcases cell with vertex | cell + · simp [properFace] + · rcases cell with edge | sector <;> simp [properFace]⟩ + +def artinRelations {Vertex : Type*} (graph : SimpleGraph Vertex) : Set (FreeGroup Vertex) := + {word | ∃ first second, graph.Adj first second ∧ + word = FreeGroup.of first * FreeGroup.of second * + (FreeGroup.of first)⁻¹ * (FreeGroup.of second)⁻¹} + +abbrev ArtinGroup {Vertex : Type*} (graph : SimpleGraph Vertex) := + PresentedGroup (artinRelations graph) + +def height {Vertex : Type*} (graph : SimpleGraph Vertex) : + ArtinGroup graph →* Multiplicative ℤ := + PresentedGroup.toGroup (f := fun _ : Vertex => Multiplicative.ofAdd (1 : ℤ)) (by + rintro word ⟨first, second, _, rfl⟩ + simp) + +abbrev SourceGroup := (height seedGraph).ker + +/-- Projective dimension of the trivial integral left group-ring module. -/ +def cohomologicalDimension (GroupType : Type*) [Group GroupType] : WithBot ℕ∞ := + CategoryTheory.projectiveDimension + (ModuleCat.of (MonoidAlgebra ℤ GroupType) + (Representation.trivial ℤ GroupType ℤ).asModule) + +universe u + +/-- Ordinary classifying CW spaces, with no bound on the cardinality of their cells. -/ +def HasClassifyingSpace (GroupType : Type*) [Group GroupType] (dimension : ℕ) : Prop := + ∃ (Space : Type u) (_ : TopologicalSpace Space) (_ : T2Space Space) + (_ : Topology.CWComplex (Set.univ : Set Space)), + (∀ degree : ℕ, dimension < degree → + IsEmpty (Topology.CWComplex.cell (Set.univ : Set Space) degree)) ∧ + PathConnectedSpace Space ∧ + ∃ basepoint : Space, Nonempty (FundamentalGroup Space basepoint ≃* GroupType) ∧ + ∃ (Cover : Type u) (_ : TopologicalSpace Cover), ContractibleSpace Cover ∧ + ∃ projection : Cover → Space, IsCoveringMap projection ∧ Function.Surjective projection + +theorem source_main : + Group.FG SourceGroup ∧ Group.ResiduallyFinite SourceGroup ∧ + cohomologicalDimension SourceGroup = 2 ∧ + HasClassifyingSpace.{0} SourceGroup 3 ∧ + ¬ HasClassifyingSpace.{u} SourceGroup 2 := by + sorry + +end EilenbergGanea + +end + +end OAI diff --git a/tasks/eilenberg-ganea/tests/grade.py b/tasks/eilenberg-ganea/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/eilenberg-ganea/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/eilenberg-ganea/tests/task.json b/tasks/eilenberg-ganea/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0a8e657cd7b560c31da977846398af85f23db523 --- /dev/null +++ b/tasks/eilenberg-ganea/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EilenbergGanea", + "comparator": { + "theorem_names": [ + "OAI.EilenbergGanea.source_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12346 +} \ No newline at end of file diff --git a/tasks/eilenberg-ganea/tests/test.sh b/tasks/eilenberg-ganea/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/eilenberg-ganea/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/elasticity-uniqueness/environment/Dockerfile b/tasks/elasticity-uniqueness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/elasticity-uniqueness/environment/fetch_mathlib.sh b/tasks/elasticity-uniqueness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/elasticity-uniqueness/environment/lake-manifest.json b/tasks/elasticity-uniqueness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/elasticity-uniqueness/environment/lakefile.lean b/tasks/elasticity-uniqueness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/elasticity-uniqueness/environment/lean_setup.sh b/tasks/elasticity-uniqueness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/elasticity-uniqueness/environment/pack_submission.py b/tasks/elasticity-uniqueness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/elasticity-uniqueness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/elasticity-uniqueness/instruction.md b/tasks/elasticity-uniqueness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6ce8203f9cc3b176ba318ea534dd60bc954e7d42 --- /dev/null +++ b/tasks/elasticity-uniqueness/instruction.md @@ -0,0 +1,161 @@ +# openai/math challenge `ElasticityUniqueness` (family 372) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 372 of the release, *Global uniqueness in smooth isotropic elasticity* +(Partial differential equations). The family as a whole: Proves that full static boundary displacement-to-traction data determine both smooth real Lame moduli on every bounded connected smooth domain in $\mathbb R^3$, provided $\mu>0$ and $3\lambda+2\mu>0$ on the closure. Neither analyticity, proximity to constant coefficients nor prior knowledge near the boundary is required. + +The challenge is `ElasticityUniqueness`, also at `/opt/openai-math/challenges/ElasticityUniqueness.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Global uniqueness for smooth isotropic elasticity + +The physical Dirichlet-to-Neumann pairing acts on the variational trace +quotient. Its quotient norm is not identified here with boundary-chart +fractional Sobolev norms. +-/ + +noncomputable section +open MeasureTheory Set +open scoped BigOperators + +namespace Elasticity + +abbrev X := EuclideanSpace ℝ (Fin 3) +abbrev V := X + +def coordVector (i : Fin 3) : X := EuclideanSpace.single i 1 + +def SmoothBoundary (Ω : Set X) : Prop := + ∀ x ∈ frontier Ω, ∃ e : OpenPartialHomeomorph X X, + x ∈ e.source ∧ + ContDiffOn ℝ (⊤ : ℕ∞) e e.source ∧ + ContDiffOn ℝ (⊤ : ℕ∞) e.symm e.target ∧ + e x 0 = 0 ∧ + ∀ y ∈ e.source, y ∈ Ω ↔ 0 < e y 0 + +def Domain (Ω : Set X) : Prop := + IsOpen Ω ∧ IsConnected Ω ∧ Bornology.IsBounded Ω ∧ SmoothBoundary Ω + +def SmoothUpTo (Ω : Set X) (f : X → ℝ) : Prop := + ∃ U : Set X, IsOpen U ∧ closure Ω ⊆ U ∧ ContDiffOn ℝ (⊤ : ℕ∞) f U + +def Admissible (Ω : Set X) (lam mu : X → ℝ) : Prop := + SmoothUpTo Ω lam ∧ SmoothUpTo Ω mu ∧ + ∀ x ∈ closure Ω, 0 < mu x ∧ 0 < 3 * lam x + 2 * mu x + +abbrev Ambient (Ω : Set X) := + Lp V 2 (volume.restrict Ω) × (Fin 3 → Lp V 2 (volume.restrict Ω)) + +def coordDeriv (f : X → V) (i : Fin 3) (x : X) : V := + fderiv ℝ f x (coordVector i) + +def SmoothJets (Ω : Set X) : Set (Ambient Ω) := + {j | ∃ (f : X → V) (hf : MemLp f 2 (volume.restrict Ω)) + (hd : ∀ i, MemLp (coordDeriv f i) 2 (volume.restrict Ω)), + ContDiff ℝ (⊤ : ℕ∞) f ∧ + j.1 = hf.toLp f ∧ j.2 = fun i => (hd i).toLp (coordDeriv f i)} + +def TestJets (Ω : Set X) : Set (Ambient Ω) := + {j | ∃ (f : X → V) (hf : MemLp f 2 (volume.restrict Ω)) + (hd : ∀ i, MemLp (coordDeriv f i) 2 (volume.restrict Ω)), + ContDiff ℝ (⊤ : ℕ∞) f ∧ HasCompactSupport f ∧ tsupport f ⊆ Ω ∧ + j.1 = hf.toLp f ∧ j.2 = fun i => (hd i).toLp (coordDeriv f i)} + +abbrev H1 (Ω : Set X) := {j : Ambient Ω // j ∈ closure (SmoothJets Ω)} + +def HasZeroTrace (Ω : Set X) (u : H1 Ω) : Prop := + u.val ∈ closure (TestJets Ω) + +def SameTrace (Ω : Set X) (u v : H1 Ω) : Prop := + u.val - v.val ∈ closure (TestJets Ω) + +abbrev BoundaryData (Ω : Set X) := Quot (SameTrace Ω) + +def trace (Ω : Set X) (u : H1 Ω) : BoundaryData Ω := Quot.mk _ u + +def div (Ω : Set X) (u : H1 Ω) (x : X) : ℝ := + ∑ i, (u.val.2 i x) i + +def strain (Ω : Set X) (u : H1 Ω) (x : X) (i j : Fin 3) : ℝ := + ((u.val.2 j x) i + (u.val.2 i x) j) / 2 + +def energy (Ω : Set X) (lam mu : X → ℝ) (u v : H1 Ω) : ℝ := + ∫ x, (lam x * div Ω u x * div Ω v x + + 2 * mu x * ∑ i, ∑ j, strain Ω u x i j * strain Ω v x i j) + ∂(volume.restrict Ω) + +def WeakSolution (Ω : Set X) (lam mu : X → ℝ) (u : H1 Ω) : Prop := + ∀ v : H1 Ω, HasZeroTrace Ω v → energy Ω lam mu u v = 0 + +def dirichletSolution (Ω : Set X) (lam mu : X → ℝ) + (f : BoundaryData Ω) : H1 Ω := by + classical + exact if h : ∃ u : H1 Ω, trace Ω u = f ∧ WeakSolution Ω lam mu u + then Classical.choose h + else f.out + +def DN (Ω : Set X) (lam mu : X → ℝ) : BoundaryData Ω → BoundaryData Ω → ℝ := + fun f g => energy Ω lam mu (dirichletSolution Ω lam mu f) g.out + +def MainClaim : Prop := + ∀ (Ω : Set X), Domain Ω → + ∀ (lam₁ mu₁ lam₂ mu₂ : X → ℝ), + Admissible Ω lam₁ mu₁ → Admissible Ω lam₂ mu₂ → + DN Ω lam₁ mu₁ = DN Ω lam₂ mu₂ → + (∀ x ∈ Ω, lam₁ x = lam₂ x) ∧ (∀ x ∈ Ω, mu₁ x = mu₂ x) + +theorem global_uniqueness : MainClaim := by + sorry + +end Elasticity + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ElasticityUniqueness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Elasticity.global_uniqueness` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/elasticity-uniqueness/solution/closure.txt b/tasks/elasticity-uniqueness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..47a1cae335adea7bf5576dd65dfbde0548f965f0 --- /dev/null +++ b/tasks/elasticity-uniqueness/solution/closure.txt @@ -0,0 +1,42 @@ +OAI.MathematicalPhysics.Elasticity.Augmented +OAI.MathematicalPhysics.Elasticity.Basic +OAI.MathematicalPhysics.Elasticity.Bessel +OAI.MathematicalPhysics.Elasticity.BoundaryCalculus +OAI.MathematicalPhysics.Elasticity.BoundaryCharts +OAI.MathematicalPhysics.Elasticity.BoundaryData +OAI.MathematicalPhysics.Elasticity.BoundaryEnergy +OAI.MathematicalPhysics.Elasticity.BoundaryJets +OAI.MathematicalPhysics.Elasticity.BoundaryLayers +OAI.MathematicalPhysics.Elasticity.BoundaryPackets +OAI.MathematicalPhysics.Elasticity.BoundaryParametrix +OAI.MathematicalPhysics.Elasticity.BoundarySymbols +OAI.MathematicalPhysics.Elasticity.BoundaryValues +OAI.MathematicalPhysics.Elasticity.CGO +OAI.MathematicalPhysics.Elasticity.Carleman +OAI.MathematicalPhysics.Elasticity.CommonExterior +OAI.MathematicalPhysics.Elasticity.CommonFrame +OAI.MathematicalPhysics.Elasticity.Compact +OAI.MathematicalPhysics.Elasticity.Conic +OAI.MathematicalPhysics.Elasticity.Extension +OAI.MathematicalPhysics.Elasticity.ForcedTransport +OAI.MathematicalPhysics.Elasticity.Holomorphy +OAI.MathematicalPhysics.Elasticity.Homotopy +OAI.MathematicalPhysics.Elasticity.LocalRegularity +OAI.MathematicalPhysics.Elasticity.ODE +OAI.MathematicalPhysics.Elasticity.Parameters +OAI.MathematicalPhysics.Elasticity.PhysicalCGO +OAI.MathematicalPhysics.Elasticity.Planar +OAI.MathematicalPhysics.Elasticity.Recovery +OAI.MathematicalPhysics.Elasticity.Regularity +OAI.MathematicalPhysics.Elasticity.Restriction +OAI.MathematicalPhysics.Elasticity.Rigidity +OAI.MathematicalPhysics.Elasticity.Smoothing +OAI.MathematicalPhysics.Elasticity.Solvability +OAI.MathematicalPhysics.Elasticity.Supported +OAI.MathematicalPhysics.Elasticity.Transfer +OAI.MathematicalPhysics.Elasticity.Transport +OAI.MathematicalPhysics.Elasticity.TransportAlgebra +OAI.MathematicalPhysics.Elasticity.Uniqueness +OAI.MathematicalPhysics.Elasticity.Variational +OAI.MathematicalPhysics.Elasticity.WeakLimits +OAI.MathematicalPhysics.Elasticity.WeakSolutions diff --git a/tasks/elasticity-uniqueness/solution/reference.py b/tasks/elasticity-uniqueness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/elasticity-uniqueness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/elasticity-uniqueness/solution/solve.sh b/tasks/elasticity-uniqueness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7db1d3cf75c74f5687ef9b5c5ed89579adb00cd2 --- /dev/null +++ b/tasks/elasticity-uniqueness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ElasticityUniqueness, i.e. module OAI.MathematicalPhysics.Elasticity.Uniqueness and the +# 42 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.Elasticity.Uniqueness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ElasticityUniqueness" diff --git a/tasks/elasticity-uniqueness/task.toml b/tasks/elasticity-uniqueness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7da657bb5acfe5a0cb9f59448d24c03e8a288178 --- /dev/null +++ b/tasks/elasticity-uniqueness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/elasticity-uniqueness" +version = "1.0.0" +description = "Prove ElasticityUniqueness (openai/math family 372: Global uniqueness in smooth isotropic elasticity) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ElasticityUniqueness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ElasticityUniqueness" +family = "372" +family_title = "Global uniqueness in smooth isotropic elasticity" +subject = "Partial differential equations" +theorems = ["OAI.Elasticity.global_uniqueness"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.Elasticity.Uniqueness" +reference_modules = 42 +reference_lean_bytes = 1608239 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1681 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13147 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/elasticity-uniqueness/tests/Challenge.lean b/tasks/elasticity-uniqueness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6f68a5b3ff2d69b7f43b7d2b3b4576e490b208cc --- /dev/null +++ b/tasks/elasticity-uniqueness/tests/Challenge.lean @@ -0,0 +1,110 @@ +import Mathlib + +namespace OAI + +/-! +# Global uniqueness for smooth isotropic elasticity + +The physical Dirichlet-to-Neumann pairing acts on the variational trace +quotient. Its quotient norm is not identified here with boundary-chart +fractional Sobolev norms. +-/ + +noncomputable section +open MeasureTheory Set +open scoped BigOperators + +namespace Elasticity + +abbrev X := EuclideanSpace ℝ (Fin 3) +abbrev V := X + +def coordVector (i : Fin 3) : X := EuclideanSpace.single i 1 + +def SmoothBoundary (Ω : Set X) : Prop := + ∀ x ∈ frontier Ω, ∃ e : OpenPartialHomeomorph X X, + x ∈ e.source ∧ + ContDiffOn ℝ (⊤ : ℕ∞) e e.source ∧ + ContDiffOn ℝ (⊤ : ℕ∞) e.symm e.target ∧ + e x 0 = 0 ∧ + ∀ y ∈ e.source, y ∈ Ω ↔ 0 < e y 0 + +def Domain (Ω : Set X) : Prop := + IsOpen Ω ∧ IsConnected Ω ∧ Bornology.IsBounded Ω ∧ SmoothBoundary Ω + +def SmoothUpTo (Ω : Set X) (f : X → ℝ) : Prop := + ∃ U : Set X, IsOpen U ∧ closure Ω ⊆ U ∧ ContDiffOn ℝ (⊤ : ℕ∞) f U + +def Admissible (Ω : Set X) (lam mu : X → ℝ) : Prop := + SmoothUpTo Ω lam ∧ SmoothUpTo Ω mu ∧ + ∀ x ∈ closure Ω, 0 < mu x ∧ 0 < 3 * lam x + 2 * mu x + +abbrev Ambient (Ω : Set X) := + Lp V 2 (volume.restrict Ω) × (Fin 3 → Lp V 2 (volume.restrict Ω)) + +def coordDeriv (f : X → V) (i : Fin 3) (x : X) : V := + fderiv ℝ f x (coordVector i) + +def SmoothJets (Ω : Set X) : Set (Ambient Ω) := + {j | ∃ (f : X → V) (hf : MemLp f 2 (volume.restrict Ω)) + (hd : ∀ i, MemLp (coordDeriv f i) 2 (volume.restrict Ω)), + ContDiff ℝ (⊤ : ℕ∞) f ∧ + j.1 = hf.toLp f ∧ j.2 = fun i => (hd i).toLp (coordDeriv f i)} + +def TestJets (Ω : Set X) : Set (Ambient Ω) := + {j | ∃ (f : X → V) (hf : MemLp f 2 (volume.restrict Ω)) + (hd : ∀ i, MemLp (coordDeriv f i) 2 (volume.restrict Ω)), + ContDiff ℝ (⊤ : ℕ∞) f ∧ HasCompactSupport f ∧ tsupport f ⊆ Ω ∧ + j.1 = hf.toLp f ∧ j.2 = fun i => (hd i).toLp (coordDeriv f i)} + +abbrev H1 (Ω : Set X) := {j : Ambient Ω // j ∈ closure (SmoothJets Ω)} + +def HasZeroTrace (Ω : Set X) (u : H1 Ω) : Prop := + u.val ∈ closure (TestJets Ω) + +def SameTrace (Ω : Set X) (u v : H1 Ω) : Prop := + u.val - v.val ∈ closure (TestJets Ω) + +abbrev BoundaryData (Ω : Set X) := Quot (SameTrace Ω) + +def trace (Ω : Set X) (u : H1 Ω) : BoundaryData Ω := Quot.mk _ u + +def div (Ω : Set X) (u : H1 Ω) (x : X) : ℝ := + ∑ i, (u.val.2 i x) i + +def strain (Ω : Set X) (u : H1 Ω) (x : X) (i j : Fin 3) : ℝ := + ((u.val.2 j x) i + (u.val.2 i x) j) / 2 + +def energy (Ω : Set X) (lam mu : X → ℝ) (u v : H1 Ω) : ℝ := + ∫ x, (lam x * div Ω u x * div Ω v x + + 2 * mu x * ∑ i, ∑ j, strain Ω u x i j * strain Ω v x i j) + ∂(volume.restrict Ω) + +def WeakSolution (Ω : Set X) (lam mu : X → ℝ) (u : H1 Ω) : Prop := + ∀ v : H1 Ω, HasZeroTrace Ω v → energy Ω lam mu u v = 0 + +def dirichletSolution (Ω : Set X) (lam mu : X → ℝ) + (f : BoundaryData Ω) : H1 Ω := by + classical + exact if h : ∃ u : H1 Ω, trace Ω u = f ∧ WeakSolution Ω lam mu u + then Classical.choose h + else f.out + +def DN (Ω : Set X) (lam mu : X → ℝ) : BoundaryData Ω → BoundaryData Ω → ℝ := + fun f g => energy Ω lam mu (dirichletSolution Ω lam mu f) g.out + +def MainClaim : Prop := + ∀ (Ω : Set X), Domain Ω → + ∀ (lam₁ mu₁ lam₂ mu₂ : X → ℝ), + Admissible Ω lam₁ mu₁ → Admissible Ω lam₂ mu₂ → + DN Ω lam₁ mu₁ = DN Ω lam₂ mu₂ → + (∀ x ∈ Ω, lam₁ x = lam₂ x) ∧ (∀ x ∈ Ω, mu₁ x = mu₂ x) + +theorem global_uniqueness : MainClaim := by + sorry + +end Elasticity + +end + +end OAI diff --git a/tasks/elasticity-uniqueness/tests/grade.py b/tasks/elasticity-uniqueness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/elasticity-uniqueness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/elasticity-uniqueness/tests/task.json b/tasks/elasticity-uniqueness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a322eb874274c59311227aea5e67b6c01d3c8d8b --- /dev/null +++ b/tasks/elasticity-uniqueness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ElasticityUniqueness", + "comparator": { + "theorem_names": [ + "OAI.Elasticity.global_uniqueness" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12247 +} \ No newline at end of file diff --git a/tasks/elasticity-uniqueness/tests/test.sh b/tasks/elasticity-uniqueness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/elasticity-uniqueness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/elementary-positivity/environment/Dockerfile b/tasks/elementary-positivity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/elementary-positivity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/elementary-positivity/environment/fetch_mathlib.sh b/tasks/elementary-positivity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/elementary-positivity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/elementary-positivity/environment/lake-manifest.json b/tasks/elementary-positivity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/elementary-positivity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/elementary-positivity/environment/lakefile.lean b/tasks/elementary-positivity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/elementary-positivity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/elementary-positivity/environment/lean_setup.sh b/tasks/elementary-positivity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/elementary-positivity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/elementary-positivity/environment/pack_submission.py b/tasks/elementary-positivity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/elementary-positivity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/elementary-positivity/instruction.md b/tasks/elementary-positivity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b82dc159cfbfef7cfc3b2e14f252546ab8d2e82b --- /dev/null +++ b/tasks/elementary-positivity/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `ElementaryPositivity` (family 169) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 169 of the release, *The Shareshian–Wachs $e$-positivity conjecture* +(Combinatorics). The family as a whole: Resolves the elementary-positivity part of the Shareshian–Wachs conjecture: the chromatic quasisymmetric function of every natural unit interval graph has elementary-basis coefficients in $\mathbb N[q]$. The coefficients count explicitly described permutations, giving a combinatorial explanation of positivity. + +The challenge is `ElementaryPositivity`, also at `/opt/openai-math/challenges/ElementaryPositivity.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ElementaryPositivity + +structure NaturalUnitIntervalGraph (n : ℕ) where + h : Fin n → Fin n + increasing : Monotone h + extensive : ∀ i, i ≤ h i + +namespace NaturalUnitIntervalGraph + +variable {n : ℕ} (G : NaturalUnitIntervalGraph n) + +def Edge (i j : Fin n) : Prop := + (i < j ∧ j ≤ G.h i) ∨ (j < i ∧ i ≤ G.h j) + +instance (i j : Fin n) : Decidable (G.Edge i j) := + inferInstanceAs (Decidable ((_ ∧ _) ∨ (_ ∧ _))) + +def Nondescent (σ : Equiv.Perm (Fin n)) : Prop := + ∀ i j : Fin n, i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j) + +instance (σ : Equiv.Perm (Fin n)) : Decidable (G.Nondescent σ) := + inferInstanceAs (Decidable (∀ i j : Fin n, + i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j))) + +def graphInversions (σ : Equiv.Perm (Fin n)) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ σ ij.2 < σ ij.1 ∧ G.Edge (σ ij.1) (σ ij.2)).card + +def Proper {r : ℕ} (f : Fin n → Fin r) : Prop := + ∀ i j : Fin n, G.Edge i j → f i ≠ f j + +instance {r : ℕ} (f : Fin n → Fin r) : Decidable (G.Proper f) := + inferInstanceAs (Decidable (∀ i j : Fin n, G.Edge i j → f i ≠ f j)) + +def coloringAscents {r : ℕ} (f : Fin n → Fin r) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ G.Edge ij.1 ij.2 ∧ f ij.1 < f ij.2).card + +noncomputable def chromatic (r : ℕ) : MvPolynomial (Fin r) (Polynomial ℕ) := + ∑ f ∈ Finset.univ.filter (G.Proper (r := r)), + MvPolynomial.C (Polynomial.X ^ G.coloringAscents f) * + ∏ i : Fin n, MvPolynomial.X (f i) + +structure PermutationWitness where + theta : {σ : Equiv.Perm (Fin n) // G.Nondescent σ} → Nat.Partition n + expansion : ∀ r : ℕ, G.chromatic r = + ∑ σ : {σ : Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X ^ G.graphInversions σ.val) * + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (theta σ) + +end NaturalUnitIntervalGraph +end ElementaryPositivity + +def elementaryPositivityWitness (n : ℕ) + (G : ElementaryPositivity.NaturalUnitIntervalGraph n) : + G.PermutationWitness := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ElementaryPositivity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The definition below must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs, and the body of `OAI.elementaryPositivityWitness`, which you must supply: its type states the claim, so any value of that type proves it. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/elementary-positivity/solution/closure.txt b/tasks/elementary-positivity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..51dfa7de9f0547a7a2658aff0a2c23de73f56c97 --- /dev/null +++ b/tasks/elementary-positivity/solution/closure.txt @@ -0,0 +1,549 @@ +OAI.Combinatorics.Chromatic.GradedAlgebra.BiRegrade +OAI.Combinatorics.Chromatic.GradedAlgebra.BoundedWordLaurent +OAI.Combinatorics.Chromatic.GradedAlgebra.CenterCoefficientMembership +OAI.Combinatorics.Chromatic.GradedAlgebra.ClearedSeparation +OAI.Combinatorics.Chromatic.GradedAlgebra.CompleteUnit +OAI.Combinatorics.Chromatic.GradedAlgebra.ConvolutionPostcomposition +OAI.Combinatorics.Chromatic.GradedAlgebra.CovectorFactor +OAI.Combinatorics.Chromatic.GradedAlgebra.CutoffRow +OAI.Combinatorics.Chromatic.GradedAlgebra.DHomogeneous +OAI.Combinatorics.Chromatic.GradedAlgebra.DegreeSet +OAI.Combinatorics.Chromatic.GradedAlgebra.ElementaryExpressionBounds +OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLaurentFinite +OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLaurentSeries +OAI.Combinatorics.Chromatic.GradedAlgebra.EnergyLimit +OAI.Combinatorics.Chromatic.GradedAlgebra.Eval +OAI.Combinatorics.Chromatic.GradedAlgebra.FiniteCovectorPerturbation +OAI.Combinatorics.Chromatic.GradedAlgebra.FinitelySupportedUnitRows +OAI.Combinatorics.Chromatic.GradedAlgebra.FintypeEnergyProduct +OAI.Combinatorics.Chromatic.GradedAlgebra.GradedBuilders +OAI.Combinatorics.Chromatic.GradedAlgebra.GradedFormalLog +OAI.Combinatorics.Chromatic.GradedAlgebra.HNSeries +OAI.Combinatorics.Chromatic.GradedAlgebra.HalfspacePolynomialCoefficients +OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousBasisFibre +OAI.Combinatorics.Chromatic.GradedAlgebra.HomogeneousElementaryExpressions +OAI.Combinatorics.Chromatic.GradedAlgebra.HomogenizedPolynomialSection +OAI.Combinatorics.Chromatic.GradedAlgebra.InputOrderedProduct +OAI.Combinatorics.Chromatic.GradedAlgebra.IntegerHomogeneous +OAI.Combinatorics.Chromatic.GradedAlgebra.KernelTraceLog +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentAffineCancellation +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentBiTruncation +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentConstantMultiplication +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentContinuity +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentDeshear +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentFilteredMultiplication +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentGeometric +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentHomogenize +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentInfinity +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentMapNaturality +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentProductNaturality +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentPureAction +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRectangularKernel +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegrade +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegradeFinite +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentRegradePure +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentScalarNaturality +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentSigns +OAI.Combinatorics.Chromatic.GradedAlgebra.LaurentUnitSigns +OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedEndpoint +OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedNoCutCone +OAI.Combinatorics.Chromatic.GradedAlgebra.MutatedPureFace +OAI.Combinatorics.Chromatic.GradedAlgebra.MutationCoordinates +OAI.Combinatorics.Chromatic.GradedAlgebra.MutationDegreeBound +OAI.Combinatorics.Chromatic.GradedAlgebra.MutationLaurentTransport +OAI.Combinatorics.Chromatic.GradedAlgebra.MutationOrientedCompatibility +OAI.Combinatorics.Chromatic.GradedAlgebra.MutationRootMap +OAI.Combinatorics.Chromatic.GradedAlgebra.NilpotentLogarithm +OAI.Combinatorics.Chromatic.GradedAlgebra.NilpotentSeriesInverse +OAI.Combinatorics.Chromatic.GradedAlgebra.NoncommExpand +OAI.Combinatorics.Chromatic.GradedAlgebra.NoncommSeriesCalculus +OAI.Combinatorics.Chromatic.GradedAlgebra.NonpHomogenize +OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegrade +OAI.Combinatorics.Chromatic.GradedAlgebra.NonpRegradeFaithful +OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesProductLeading +OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplit +OAI.Combinatorics.Chromatic.GradedAlgebra.PowerSeriesSplitLeading +OAI.Combinatorics.Chromatic.GradedAlgebra.Product +OAI.Combinatorics.Chromatic.GradedAlgebra.ProjectionRecursion +OAI.Combinatorics.Chromatic.GradedAlgebra.PureCoefficient +OAI.Combinatorics.Chromatic.GradedAlgebra.PureComparisonIdentification +OAI.Combinatorics.Chromatic.GradedAlgebra.PureFaceLog +OAI.Combinatorics.Chromatic.GradedAlgebra.PurePolynomialCoefficients +OAI.Combinatorics.Chromatic.GradedAlgebra.QuantumTorusAlgebra +OAI.Combinatorics.Chromatic.GradedAlgebra.QuantumTorusSignFactors +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalCenteredAction +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalLaurentFaithful +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalLaurentScalars +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalPolynomialDivisibility +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalPureCoefficients +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalRegrade +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalShearCocycle +OAI.Combinatorics.Chromatic.GradedAlgebra.RationalShearEmbedding +OAI.Combinatorics.Chromatic.GradedAlgebra.RealRootCoordinates +OAI.Combinatorics.Chromatic.GradedAlgebra.RegradeLog +OAI.Combinatorics.Chromatic.GradedAlgebra.RootCoefficientLocality +OAI.Combinatorics.Chromatic.GradedAlgebra.RootCoefficients +OAI.Combinatorics.Chromatic.GradedAlgebra.RootMutationInventory +OAI.Combinatorics.Chromatic.GradedAlgebra.RootSectionHalfspace +OAI.Combinatorics.Chromatic.GradedAlgebra.RootTruncation +OAI.Combinatorics.Chromatic.GradedAlgebra.RotationLocalPolynomials +OAI.Combinatorics.Chromatic.GradedAlgebra.SeriesApproximation +OAI.Combinatorics.Chromatic.GradedAlgebra.SimpleBinomial +OAI.Combinatorics.Chromatic.GradedAlgebra.SplitContinuity +OAI.Combinatorics.Chromatic.GradedAlgebra.SquarefreeCoefficient +OAI.Combinatorics.Chromatic.GradedAlgebra.Strict +OAI.Combinatorics.Chromatic.GradedAlgebra.StringBackshift +OAI.Combinatorics.Chromatic.GradedAlgebra.StringStripSeries +OAI.Combinatorics.Chromatic.GradedAlgebra.SupportedConvolution +OAI.Combinatorics.Chromatic.GradedAlgebra.TraceLogDerivative +OAI.Combinatorics.Chromatic.GradedAlgebra.TruncatedChart +OAI.Combinatorics.Chromatic.GradedAlgebra.TruncatedPrecisionClosure +OAI.Combinatorics.Chromatic.GradedAlgebra.UnitIndexEnergy +OAI.Combinatorics.Chromatic.GradedAlgebra.UnitSelectionLaurent +OAI.Combinatorics.Chromatic.GradedAlgebra.UnitalProduct +OAI.Combinatorics.Chromatic.GradedAlgebra.WeightedPushTwist +OAI.Combinatorics.Chromatic.GradedAlgebra.WeightedTorusSeries +OAI.Combinatorics.Chromatic.Histories.AnchorEmptyMask +OAI.Combinatorics.Chromatic.Histories.ColorBlockEnergy +OAI.Combinatorics.Chromatic.Histories.ColorWordReordering +OAI.Combinatorics.Chromatic.Histories.CommonHistoryLeaves +OAI.Combinatorics.Chromatic.Histories.GraphCommonHistory +OAI.Combinatorics.Chromatic.Histories.KernelEvaluation +OAI.Combinatorics.Chromatic.Histories.LocalHistoryFormula +OAI.Combinatorics.Chromatic.Histories.PacketSortedWords +OAI.Combinatorics.Chromatic.Histories.ShuffleLeafFiltration +OAI.Combinatorics.Chromatic.Histories.SortedFiberPerm +OAI.Combinatorics.Chromatic.Histories.TriangularCommonHistory +OAI.Combinatorics.Chromatic.Histories.TwoLeafDiagonal +OAI.Combinatorics.Chromatic.Main +OAI.Combinatorics.Chromatic.Model +OAI.Combinatorics.Chromatic.QuantumTorus.Admissible +OAI.Combinatorics.Chromatic.QuantumTorus.ConeSectionDomination +OAI.Combinatorics.Chromatic.QuantumTorus.CovectorPrescriptions +OAI.Combinatorics.Chromatic.QuantumTorus.ExpressionAdditiveOperations +OAI.Combinatorics.Chromatic.QuantumTorus.GeometricMutation +OAI.Combinatorics.Chromatic.QuantumTorus.GlobalFiberBound +OAI.Combinatorics.Chromatic.QuantumTorus.GraphRationalModel +OAI.Combinatorics.Chromatic.QuantumTorus.GraphSquarefreeKernel +OAI.Combinatorics.Chromatic.QuantumTorus.IndependentElement +OAI.Combinatorics.Chromatic.QuantumTorus.IndependentElementReindex +OAI.Combinatorics.Chromatic.QuantumTorus.IndependentSetElements +OAI.Combinatorics.Chromatic.QuantumTorus.IndexedUnit +OAI.Combinatorics.Chromatic.QuantumTorus.InfinityExpansionFaithful +OAI.Combinatorics.Chromatic.QuantumTorus.InfinityUnitAlgebra +OAI.Combinatorics.Chromatic.QuantumTorus.LatticeHahn +OAI.Combinatorics.Chromatic.QuantumTorus.MonomialConjugation +OAI.Combinatorics.Chromatic.QuantumTorus.MutatedCanonicalCharts +OAI.Combinatorics.Chromatic.QuantumTorus.MutatedNegativeCharts +OAI.Combinatorics.Chromatic.QuantumTorus.MutatedSystemIdentification +OAI.Combinatorics.Chromatic.QuantumTorus.MutationConvexSigns +OAI.Combinatorics.Chromatic.QuantumTorus.MutationFiberArithmetic +OAI.Combinatorics.Chromatic.QuantumTorus.MutationInfinityBound +OAI.Combinatorics.Chromatic.QuantumTorus.NearCutGeometry +OAI.Combinatorics.Chromatic.QuantumTorus.NearCutMutation +OAI.Combinatorics.Chromatic.QuantumTorus.NearCutPolynomialSeeds +OAI.Combinatorics.Chromatic.QuantumTorus.NearCutSectionCharts +OAI.Combinatorics.Chromatic.QuantumTorus.NormalizedMonomialAction +OAI.Combinatorics.Chromatic.QuantumTorus.OrbitMonomialSymmetric +OAI.Combinatorics.Chromatic.QuantumTorus.OrderedIndependentProduct +OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryElementaryExpressions +OAI.Combinatorics.Chromatic.QuantumTorus.OrdinaryExpressionNaturality +OAI.Combinatorics.Chromatic.QuantumTorus.PolynomialThetaIdentification +OAI.Combinatorics.Chromatic.QuantumTorus.ProductUnitFiltration +OAI.Combinatorics.Chromatic.QuantumTorus.PureCutTelescoping +OAI.Combinatorics.Chromatic.QuantumTorus.PureFaceProjection +OAI.Combinatorics.Chromatic.QuantumTorus.PureProductSplit +OAI.Combinatorics.Chromatic.QuantumTorus.QuantumTorus +OAI.Combinatorics.Chromatic.QuantumTorus.RationalFiberTorus +OAI.Combinatorics.Chromatic.QuantumTorus.RationalPureAction +OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusEmbedding +OAI.Combinatorics.Chromatic.QuantumTorus.RationalTorusFaithful +OAI.Combinatorics.Chromatic.QuantumTorus.SectionCharts +OAI.Combinatorics.Chromatic.QuantumTorus.SectionMonomialExpansion +OAI.Combinatorics.Chromatic.QuantumTorus.SectionTrace +OAI.Combinatorics.Chromatic.QuantumTorus.SimplePlaneGeometry +OAI.Combinatorics.Chromatic.QuantumTorus.StringLiteralClosure +OAI.Combinatorics.Chromatic.QuantumTorus.StringStripDimension +OAI.Combinatorics.Chromatic.QuantumTorus.StringSumProduct +OAI.Combinatorics.Chromatic.QuantumTorus.StringSumPush +OAI.Combinatorics.Chromatic.QuantumTorus.SymplecticTorusMap +OAI.Combinatorics.Chromatic.QuantumTorus.TorusContinuity +OAI.Combinatorics.Chromatic.QuantumTorus.TorusProjection +OAI.Combinatorics.Chromatic.QuantumTorus.UnitRowSelection +OAI.Combinatorics.Chromatic.QuantumTorus.UpstreamFiber +OAI.Combinatorics.Chromatic.QuantumTorus.UpstreamSimpleFiber +OAI.Combinatorics.Chromatic.QuantumTorus.WeakStrictUnitSelections +OAI.Combinatorics.Chromatic.QuantumTorus.WeakUnitRecursion +OAI.Combinatorics.Chromatic.Shuffle.AllPairDiagonal +OAI.Combinatorics.Chromatic.Shuffle.BothTaylorB +OAI.Combinatorics.Chromatic.Shuffle.CanonicalCard +OAI.Combinatorics.Chromatic.Shuffle.CellLeadingSum +OAI.Combinatorics.Chromatic.Shuffle.CellSeparation +OAI.Combinatorics.Chromatic.Shuffle.CellTransferSeparation +OAI.Combinatorics.Chromatic.Shuffle.CellVars +OAI.Combinatorics.Chromatic.Shuffle.Centers +OAI.Combinatorics.Chromatic.Shuffle.ClearedSeparationB +OAI.Combinatorics.Chromatic.Shuffle.ClearingKernel +OAI.Combinatorics.Chromatic.Shuffle.ColumnTaylor +OAI.Combinatorics.Chromatic.Shuffle.ComponentB +OAI.Combinatorics.Chromatic.Shuffle.CoproductIteration +OAI.Combinatorics.Chromatic.Shuffle.CrossCancellation +OAI.Combinatorics.Chromatic.Shuffle.CrossDifference +OAI.Combinatorics.Chromatic.Shuffle.CrossKernelExplicit +OAI.Combinatorics.Chromatic.Shuffle.CrossPolynomiality +OAI.Combinatorics.Chromatic.Shuffle.CrossScalar +OAI.Combinatorics.Chromatic.Shuffle.Cut +OAI.Combinatorics.Chromatic.Shuffle.CutoffGrid +OAI.Combinatorics.Chromatic.Shuffle.Degree +OAI.Combinatorics.Chromatic.Shuffle.DegreeIdeals +OAI.Combinatorics.Chromatic.Shuffle.Diagonal +OAI.Combinatorics.Chromatic.Shuffle.DimensionColumnLeading +OAI.Combinatorics.Chromatic.Shuffle.DimensionEquivBTrans +OAI.Combinatorics.Chromatic.Shuffle.DimensionEquivS +OAI.Combinatorics.Chromatic.Shuffle.DimensionGrid +OAI.Combinatorics.Chromatic.Shuffle.EulerForm +OAI.Combinatorics.Chromatic.Shuffle.ExtendPolynomial +OAI.Combinatorics.Chromatic.Shuffle.FourAffineKernel +OAI.Combinatorics.Chromatic.Shuffle.FourBraiding +OAI.Combinatorics.Chromatic.Shuffle.FourColumns +OAI.Combinatorics.Chromatic.Shuffle.FourKernelCancellation +OAI.Combinatorics.Chromatic.Shuffle.FourTensorKernel +OAI.Combinatorics.Chromatic.Shuffle.GeometricRootClosure +OAI.Combinatorics.Chromatic.Shuffle.GlobalConvolutionQuotient +OAI.Combinatorics.Chromatic.Shuffle.GlobalConvolutionSeries +OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductCoassociative +OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductCocommutative +OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductIteration +OAI.Combinatorics.Chromatic.Shuffle.GlobalCoproductUnits +OAI.Combinatorics.Chromatic.Shuffle.GlobalHilbertGrading +OAI.Combinatorics.Chromatic.Shuffle.GlobalLocalPrimitives +OAI.Combinatorics.Chromatic.Shuffle.GlobalPBWBasis +OAI.Combinatorics.Chromatic.Shuffle.GlobalPBWIndependent +OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveBracket +OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveGeneration +OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveLog +OAI.Combinatorics.Chromatic.Shuffle.GlobalPrimitiveStrings +OAI.Combinatorics.Chromatic.Shuffle.GlobalSeriesEvaluation +OAI.Combinatorics.Chromatic.Shuffle.GlobalShuffleCoalgebra +OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorDetection +OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorGradeProduct +OAI.Combinatorics.Chromatic.Shuffle.GlobalTensorInduction +OAI.Combinatorics.Chromatic.Shuffle.GlobalTripleGradeInclusion +OAI.Combinatorics.Chromatic.Shuffle.GlobalWordDetection +OAI.Combinatorics.Chromatic.Shuffle.GlobalWordPairing +OAI.Combinatorics.Chromatic.Shuffle.GradeBInternal +OAI.Combinatorics.Chromatic.Shuffle.GradedCoproduct +OAI.Combinatorics.Chromatic.Shuffle.GradedShuffle +OAI.Combinatorics.Chromatic.Shuffle.GridQuotient +OAI.Combinatorics.Chromatic.Shuffle.GridShapeFiltration +OAI.Combinatorics.Chromatic.Shuffle.GridShapeTensor +OAI.Combinatorics.Chromatic.Shuffle.HNDetectorBasics +OAI.Combinatorics.Chromatic.Shuffle.HNDiagonal +OAI.Combinatorics.Chromatic.Shuffle.HNDiagonalConstant +OAI.Combinatorics.Chromatic.Shuffle.HNExpansion +OAI.Combinatorics.Chromatic.Shuffle.HNHilbert +OAI.Combinatorics.Chromatic.Shuffle.HNHomogeneousBasis +OAI.Combinatorics.Chromatic.Shuffle.HNIndependent +OAI.Combinatorics.Chromatic.Shuffle.HNPolynomial +OAI.Combinatorics.Chromatic.Shuffle.HNSlope +OAI.Combinatorics.Chromatic.Shuffle.HNThreshold +OAI.Combinatorics.Chromatic.Shuffle.HNZeroFactor +OAI.Combinatorics.Chromatic.Shuffle.HNZeroRows +OAI.Combinatorics.Chromatic.Shuffle.InfinityLaurentFinite +OAI.Combinatorics.Chromatic.Shuffle.InputOrderedEnergy +OAI.Combinatorics.Chromatic.Shuffle.InputProduct +OAI.Combinatorics.Chromatic.Shuffle.InputTorusEnergy +OAI.Combinatorics.Chromatic.Shuffle.Interaction +OAI.Combinatorics.Chromatic.Shuffle.LabeledPolynomial +OAI.Combinatorics.Chromatic.Shuffle.LaurentIdealCoefficients +OAI.Combinatorics.Chromatic.Shuffle.LaurentKernel +OAI.Combinatorics.Chromatic.Shuffle.LaurentLeading +OAI.Combinatorics.Chromatic.Shuffle.LeadingIndex +OAI.Combinatorics.Chromatic.Shuffle.ManyBlockDiagonal +OAI.Combinatorics.Chromatic.Shuffle.ManyBlockPolynomiality +OAI.Combinatorics.Chromatic.Shuffle.NormalizedTensorSymbol +OAI.Combinatorics.Chromatic.Shuffle.NormalizedTripleSymbol +OAI.Combinatorics.Chromatic.Shuffle.OriginalDegree +OAI.Combinatorics.Chromatic.Shuffle.PackExponentSorting +OAI.Combinatorics.Chromatic.Shuffle.PackOrbitBasis +OAI.Combinatorics.Chromatic.Shuffle.PackSplit +OAI.Combinatorics.Chromatic.Shuffle.PointEvaluation +OAI.Combinatorics.Chromatic.Shuffle.PolynomialExtendInjective +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveBlockRows +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveOperators +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveRootClosure +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveSpace +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveStringBounds +OAI.Combinatorics.Chromatic.Shuffle.PrimitiveUnitRows +OAI.Combinatorics.Chromatic.Shuffle.QuantumTorusTrace +OAI.Combinatorics.Chromatic.Shuffle.QuotientAlg +OAI.Combinatorics.Chromatic.Shuffle.RawGradedAlgebra +OAI.Combinatorics.Chromatic.Shuffle.Realization +OAI.Combinatorics.Chromatic.Shuffle.Regroup +OAI.Combinatorics.Chromatic.Shuffle.RenameFraction +OAI.Combinatorics.Chromatic.Shuffle.RestrictSplit +OAI.Combinatorics.Chromatic.Shuffle.Restriction +OAI.Combinatorics.Chromatic.Shuffle.RestrictionB +OAI.Combinatorics.Chromatic.Shuffle.RestrictionBGraded +OAI.Combinatorics.Chromatic.Shuffle.RestrictionTestHomogeneity +OAI.Combinatorics.Chromatic.Shuffle.ReynoldsS +OAI.Combinatorics.Chromatic.Shuffle.SameDen +OAI.Combinatorics.Chromatic.Shuffle.SeparationCoefficients +OAI.Combinatorics.Chromatic.Shuffle.SeparationHomogeneity +OAI.Combinatorics.Chromatic.Shuffle.ShuffleProjection +OAI.Combinatorics.Chromatic.Shuffle.ShuffleUnits +OAI.Combinatorics.Chromatic.Shuffle.SignedCoproductGridGrade +OAI.Combinatorics.Chromatic.Shuffle.SignedTensorGradeProduct +OAI.Combinatorics.Chromatic.Shuffle.SlopeGridSum +OAI.Combinatorics.Chromatic.Shuffle.Split +OAI.Combinatorics.Chromatic.Shuffle.SumPackCut +OAI.Combinatorics.Chromatic.Shuffle.SymbolDetection +OAI.Combinatorics.Chromatic.Shuffle.SymbolInternalWeight +OAI.Combinatorics.Chromatic.Shuffle.SymbolSwap +OAI.Combinatorics.Chromatic.Shuffle.SymmetricSpace +OAI.Combinatorics.Chromatic.Shuffle.TargetEmbedding +OAI.Combinatorics.Chromatic.Shuffle.TaylorSCoeffHomogeneous +OAI.Combinatorics.Chromatic.Shuffle.TensorColumnNaturality +OAI.Combinatorics.Chromatic.Shuffle.TensorColumnSeriesFiltration +OAI.Combinatorics.Chromatic.Shuffle.TensorDivisibility +OAI.Combinatorics.Chromatic.Shuffle.TensorFiltration +OAI.Combinatorics.Chromatic.Shuffle.TensorMiddleEnd +OAI.Combinatorics.Chromatic.Shuffle.TensorPolynomialAssoc +OAI.Combinatorics.Chromatic.Shuffle.TensorPolynomialBox +OAI.Combinatorics.Chromatic.Shuffle.TensorSymbolSwap +OAI.Combinatorics.Chromatic.Shuffle.TripleAssociativity +OAI.Combinatorics.Chromatic.Shuffle.TripleFiltration +OAI.Combinatorics.Chromatic.Shuffle.TwoTargetFiltration +OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductCoassociative +OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductComparison +OAI.Combinatorics.Chromatic.Shuffle.UnitalCoproductUnits +OAI.Combinatorics.Chromatic.Shuffle.UnitalFiltration +OAI.Combinatorics.Chromatic.Shuffle.UnitalGrade +OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeAlgebra +OAI.Combinatorics.Chromatic.Shuffle.UnitalGradeCoproductUnits +OAI.Combinatorics.Chromatic.Shuffle.UnitalOriginalDegree +OAI.Combinatorics.Chromatic.Shuffle.UnitalShuffleCoproduct +OAI.Combinatorics.Chromatic.Shuffle.UnitalTensorGradeInclusion +OAI.Combinatorics.Chromatic.Shuffle.VariableMean +OAI.Combinatorics.Chromatic.Walls.AdjointExpansion +OAI.Combinatorics.Chromatic.Walls.AffineCutTelescoping +OAI.Combinatorics.Chromatic.Walls.AllOrderSectionLine +OAI.Combinatorics.Chromatic.Walls.Average +OAI.Combinatorics.Chromatic.Walls.BraidingFiltration +OAI.Combinatorics.Chromatic.Walls.CenterCoefficientScalarLinear +OAI.Combinatorics.Chromatic.Walls.CenterLineNaturality +OAI.Combinatorics.Chromatic.Walls.CenterLineSpecialization +OAI.Combinatorics.Chromatic.Walls.CenteredUnitRatio +OAI.Combinatorics.Chromatic.Walls.ChartRefinement +OAI.Combinatorics.Chromatic.Walls.ComparisonLine +OAI.Combinatorics.Chromatic.Walls.ComparisonRefinement +OAI.Combinatorics.Chromatic.Walls.CompleteUnitRecursion +OAI.Combinatorics.Chromatic.Walls.CompletedBiUnit +OAI.Combinatorics.Chromatic.Walls.CompletedCutAction +OAI.Combinatorics.Chromatic.Walls.CompletedInfinityCut +OAI.Combinatorics.Chromatic.Walls.CompletedInverse +OAI.Combinatorics.Chromatic.Walls.CompletedPathAction +OAI.Combinatorics.Chromatic.Walls.CompletedPathIndependence +OAI.Combinatorics.Chromatic.Walls.CompletedPureComparison +OAI.Combinatorics.Chromatic.Walls.CoproductSymbol +OAI.Combinatorics.Chromatic.Walls.CountEmbedding +OAI.Combinatorics.Chromatic.Walls.CountSumDimension +OAI.Combinatorics.Chromatic.Walls.DegreeIsolatedReordering +OAI.Combinatorics.Chromatic.Walls.DirectSumBilinear +OAI.Combinatorics.Chromatic.Walls.DirectSumSubtype +OAI.Combinatorics.Chromatic.Walls.ElementaryMatrixDuality +OAI.Combinatorics.Chromatic.Walls.EulerFiniteProduct +OAI.Combinatorics.Chromatic.Walls.FilteredDualIndependence +OAI.Combinatorics.Chromatic.Walls.FilteredTensorComm +OAI.Combinatorics.Chromatic.Walls.FilteredTensorInsert +OAI.Combinatorics.Chromatic.Walls.FiltrationHomogeneousRank +OAI.Combinatorics.Chromatic.Walls.FiniteElementaryAdjoint +OAI.Combinatorics.Chromatic.Walls.FiniteFiberInfinity +OAI.Combinatorics.Chromatic.Walls.FiniteFibreFinsupp +OAI.Combinatorics.Chromatic.Walls.FiniteLatticePairing +OAI.Combinatorics.Chromatic.Walls.FinitePathPerturbation +OAI.Combinatorics.Chromatic.Walls.FinitePureMutation +OAI.Combinatorics.Chromatic.Walls.FiniteRayGeometry +OAI.Combinatorics.Chromatic.Walls.FiniteRefinementImport +OAI.Combinatorics.Chromatic.Walls.FiniteRefinementImportAll +OAI.Combinatorics.Chromatic.Walls.FiniteReorderingEnergy +OAI.Combinatorics.Chromatic.Walls.FiniteSignCharts +OAI.Combinatorics.Chromatic.Walls.FiniteStringReordering +OAI.Combinatorics.Chromatic.Walls.FiniteWallCrossing +OAI.Combinatorics.Chromatic.Walls.FiniteWallPositive +OAI.Combinatorics.Chromatic.Walls.ForwardChartMutation +OAI.Combinatorics.Chromatic.Walls.ForwardInventoryRotation +OAI.Combinatorics.Chromatic.Walls.ForwardPolynomialMutation +OAI.Combinatorics.Chromatic.Walls.FourCellFactorization +OAI.Combinatorics.Chromatic.Walls.GenericAffineProbes +OAI.Combinatorics.Chromatic.Walls.GenericLineJoining +OAI.Combinatorics.Chromatic.Walls.GeometricFinitePositive +OAI.Combinatorics.Chromatic.Walls.GeometricMutationLines +OAI.Combinatorics.Chromatic.Walls.GlobalWallPositive +OAI.Combinatorics.Chromatic.Walls.Grade +OAI.Combinatorics.Chromatic.Walls.GraphBlockPairing +OAI.Combinatorics.Chromatic.Walls.GraphTriangularEmbedding +OAI.Combinatorics.Chromatic.Walls.Grid +OAI.Combinatorics.Chromatic.Walls.HNGeometry +OAI.Combinatorics.Chromatic.Walls.HNMatrixTriangular +OAI.Combinatorics.Chromatic.Walls.HNRestrictionOrder +OAI.Combinatorics.Chromatic.Walls.HNSpanning +OAI.Combinatorics.Chromatic.Walls.HNTorusFactor +OAI.Combinatorics.Chromatic.Walls.HalfspaceLaurentTransport +OAI.Combinatorics.Chromatic.Walls.IncomingDisplacement +OAI.Combinatorics.Chromatic.Walls.IncomingEquality +OAI.Combinatorics.Chromatic.Walls.IncomingExtremalLocality +OAI.Combinatorics.Chromatic.Walls.IncomingRayElement +OAI.Combinatorics.Chromatic.Walls.IncomingSystem +OAI.Combinatorics.Chromatic.Walls.IncomingTransportTrace +OAI.Combinatorics.Chromatic.Walls.IndependentRotationComparison +OAI.Combinatorics.Chromatic.Walls.InfinityCutCharts +OAI.Combinatorics.Chromatic.Walls.InfinityFiniteLoop +OAI.Combinatorics.Chromatic.Walls.InfinityLine +OAI.Combinatorics.Chromatic.Walls.InfinityPath +OAI.Combinatorics.Chromatic.Walls.IsolatedPositivePlane +OAI.Combinatorics.Chromatic.Walls.IsotropicLiteralPositive +OAI.Combinatorics.Chromatic.Walls.LaurentCompletion +OAI.Combinatorics.Chromatic.Walls.LaurentCompletionFaithful +OAI.Combinatorics.Chromatic.Walls.LaurentFiniteDecorations +OAI.Combinatorics.Chromatic.Walls.LaurentGradedFibers +OAI.Combinatorics.Chromatic.Walls.LaurentLinearNaturality +OAI.Combinatorics.Chromatic.Walls.LaurentPolynomialAction +OAI.Combinatorics.Chromatic.Walls.LaurentPolynomialEnergy +OAI.Combinatorics.Chromatic.Walls.LaurentPositiveDomination +OAI.Combinatorics.Chromatic.Walls.LaurentProjectionFormula +OAI.Combinatorics.Chromatic.Walls.LaurentRayEmbedding +OAI.Combinatorics.Chromatic.Walls.LaurentScalarAction +OAI.Combinatorics.Chromatic.Walls.LineOldTransport +OAI.Combinatorics.Chromatic.Walls.LinearFiltrationBilinear +OAI.Combinatorics.Chromatic.Walls.LinearFiltrationFinite +OAI.Combinatorics.Chromatic.Walls.LinearFiltrationOperators +OAI.Combinatorics.Chromatic.Walls.Mass +OAI.Combinatorics.Chromatic.Walls.MutatedAnchors +OAI.Combinatorics.Chromatic.Walls.MutatedHalfspaceTransport +OAI.Combinatorics.Chromatic.Walls.MutatedIncomingNonpure +OAI.Combinatorics.Chromatic.Walls.MutatedIncomingNonpureRoot +OAI.Combinatorics.Chromatic.Walls.MutatedLineCompletion +OAI.Combinatorics.Chromatic.Walls.MutatedNoCutTransport +OAI.Combinatorics.Chromatic.Walls.MutatedPathCompletion +OAI.Combinatorics.Chromatic.Walls.MutatedPathIndependent +OAI.Combinatorics.Chromatic.Walls.MutatedPureLine +OAI.Combinatorics.Chromatic.Walls.MutatedWallKernel +OAI.Combinatorics.Chromatic.Walls.MutationChamberPaths +OAI.Combinatorics.Chromatic.Walls.MutationEventualIncoming +OAI.Combinatorics.Chromatic.Walls.MutationIncomingFinite +OAI.Combinatorics.Chromatic.Walls.MutationIncomingProbes +OAI.Combinatorics.Chromatic.Walls.MutationInfinityAlgebra +OAI.Combinatorics.Chromatic.Walls.MutationLaurentCompletion +OAI.Combinatorics.Chromatic.Walls.MutationLogCompletion +OAI.Combinatorics.Chromatic.Walls.MutationMonomialAction +OAI.Combinatorics.Chromatic.Walls.MutationRegradeCompatibility +OAI.Combinatorics.Chromatic.Walls.MutationSimpleIncoming +OAI.Combinatorics.Chromatic.Walls.NamedIndependentRotation +OAI.Combinatorics.Chromatic.Walls.NegativeRayCrossing +OAI.Combinatorics.Chromatic.Walls.NonpJoint +OAI.Combinatorics.Chromatic.Walls.OffCutJoint +OAI.Combinatorics.Chromatic.Walls.OrderedRootReordering +OAI.Combinatorics.Chromatic.Walls.Pack +OAI.Combinatorics.Chromatic.Walls.PathOldTransport +OAI.Combinatorics.Chromatic.Walls.PathRoot +OAI.Combinatorics.Chromatic.Walls.PlanarJointFactorization +OAI.Combinatorics.Chromatic.Walls.PlanarRayOrder +OAI.Combinatorics.Chromatic.Walls.PlanarRefinement +OAI.Combinatorics.Chromatic.Walls.PolynomialAdjointCoefficients +OAI.Combinatorics.Chromatic.Walls.PolynomialCoeffLinear +OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingPerturbation +OAI.Combinatorics.Chromatic.Walls.PolynomialIncomingProbes +OAI.Combinatorics.Chromatic.Walls.PolynomialSection +OAI.Combinatorics.Chromatic.Walls.PowerSeriesThreeFactors +OAI.Combinatorics.Chromatic.Walls.PrimitiveStrings +OAI.Combinatorics.Chromatic.Walls.PureActualCoefficients +OAI.Combinatorics.Chromatic.Walls.PureCutFactorization +OAI.Combinatorics.Chromatic.Walls.PureCutGroup +OAI.Combinatorics.Chromatic.Walls.QuantumTorusChartCompletion +OAI.Combinatorics.Chromatic.Walls.QuantumTorusRaySeries +OAI.Combinatorics.Chromatic.Walls.QuantumTorusWallLeading +OAI.Combinatorics.Chromatic.Walls.RationalCocycleExt +OAI.Combinatorics.Chromatic.Walls.RationalCutIdentity +OAI.Combinatorics.Chromatic.Walls.RationalFiberReciprocal +OAI.Combinatorics.Chromatic.Walls.RationalFiberScale +OAI.Combinatorics.Chromatic.Walls.RationalIntervalModel +OAI.Combinatorics.Chromatic.Walls.RationalPureCocycle +OAI.Combinatorics.Chromatic.Walls.RationalReadExt +OAI.Combinatorics.Chromatic.Walls.RationalTensorDetection +OAI.Combinatorics.Chromatic.Walls.RayIncomingIdentification +OAI.Combinatorics.Chromatic.Walls.RayLaurentExpansion +OAI.Combinatorics.Chromatic.Walls.RealLatticeRealization +OAI.Combinatorics.Chromatic.Walls.RefinedLaurent +OAI.Combinatorics.Chromatic.Walls.RefinedTensorDetection +OAI.Combinatorics.Chromatic.Walls.RootClosureFacts +OAI.Combinatorics.Chromatic.Walls.RootLaurentCompletion +OAI.Combinatorics.Chromatic.Walls.RootProducts +OAI.Combinatorics.Chromatic.Walls.SectionGenericPerturbation +OAI.Combinatorics.Chromatic.Walls.SectionIncoming +OAI.Combinatorics.Chromatic.Walls.SectionLineProgram +OAI.Combinatorics.Chromatic.Walls.SectionRayTransition +OAI.Combinatorics.Chromatic.Walls.ShuffleFiltration +OAI.Combinatorics.Chromatic.Walls.ShuffleTensorLinear +OAI.Combinatorics.Chromatic.Walls.SignedMultiplicity +OAI.Combinatorics.Chromatic.Walls.SimpleAdjointFiber +OAI.Combinatorics.Chromatic.Walls.SimpleIncomingData +OAI.Combinatorics.Chromatic.Walls.SimpleIncomingElement +OAI.Combinatorics.Chromatic.Walls.SquarefreeBlocks +OAI.Combinatorics.Chromatic.Walls.StationaryIntegerSequences +OAI.Combinatorics.Chromatic.Walls.StringPositiveFactor +OAI.Combinatorics.Chromatic.Walls.StringRay +OAI.Combinatorics.Chromatic.Walls.StringReorderingEnergy +OAI.Combinatorics.Chromatic.Walls.StringRootClosure +OAI.Combinatorics.Chromatic.Walls.StringStrip +OAI.Combinatorics.Chromatic.Walls.Taylor +OAI.Combinatorics.Chromatic.Walls.TensorAssociatedGrade +OAI.Combinatorics.Chromatic.Walls.TensorFiltrationIdeals +OAI.Combinatorics.Chromatic.Walls.TensorFiltrationInterchange +OAI.Combinatorics.Chromatic.Walls.TensorGradeFiniteSum +OAI.Combinatorics.Chromatic.Walls.TensorGradeFunctor +OAI.Combinatorics.Chromatic.Walls.TensorMiddleFiltration +OAI.Combinatorics.Chromatic.Walls.TensorPolynomialLinear +OAI.Combinatorics.Chromatic.Walls.ThresholdWords +OAI.Combinatorics.Chromatic.Walls.TorusAdjointExpansion +OAI.Combinatorics.Chromatic.Walls.TorusPositive +OAI.Combinatorics.Chromatic.Walls.TranslatedCompletion +OAI.Combinatorics.Chromatic.Walls.TriangularAnchorProjection +OAI.Combinatorics.Chromatic.Walls.TriangularAnchored +OAI.Combinatorics.Chromatic.Walls.TriangularCommutativity +OAI.Combinatorics.Chromatic.Walls.TriangularDirectSum +OAI.Combinatorics.Chromatic.Walls.TriangularGapOrthogonality +OAI.Combinatorics.Chromatic.Walls.TriangularGapPairing +OAI.Combinatorics.Chromatic.Walls.TriangularGapTotals +OAI.Combinatorics.Chromatic.Walls.TriangularGaps +OAI.Combinatorics.Chromatic.Walls.TriangularIncoming +OAI.Combinatorics.Chromatic.Walls.TriangularLateStationarity +OAI.Combinatorics.Chromatic.Walls.TriangularLevelQueues +OAI.Combinatorics.Chromatic.Walls.TriangularLinearIncoming +OAI.Combinatorics.Chromatic.Walls.TriangularLinearSection +OAI.Combinatorics.Chromatic.Walls.TriangularMonomialCriterion +OAI.Combinatorics.Chromatic.Walls.TriangularMonomialProducer +OAI.Combinatorics.Chromatic.Walls.TriangularPeriodTransport +OAI.Combinatorics.Chromatic.Walls.TriangularPolynomialStationarity +OAI.Combinatorics.Chromatic.Walls.TriangularPositivePowers +OAI.Combinatorics.Chromatic.Walls.TriangularScheduledRoots +OAI.Combinatorics.Chromatic.Walls.TripleSymbols +OAI.Combinatorics.Chromatic.Walls.TruncatedFactorization +OAI.Combinatorics.Chromatic.Walls.UnitalCoproductNaturality +OAI.Combinatorics.Chromatic.Walls.UnitalGradeComparison +OAI.Combinatorics.Chromatic.Walls.WallLineInitial +OAI.Combinatorics.Chromatic.Walls.WallRegrade +OAI.Combinatorics.Chromatic.Walls.WallUnitNegative +OAI.Combinatorics.Chromatic.Walls.WallUnits +OAI.Combinatorics.Chromatic.Walls.WeightedCompletion +OAI.Combinatorics.Chromatic.Walls.WeightedInverseAdjoint +OAI.Combinatorics.Chromatic.Walls.WeightedRay +OAI.Combinatorics.Chromatic.Walls.WordLengthFiltration +OAI.Combinatorics.Chromatic.Witness.ElementaryAlphabetRigidity +OAI.Combinatorics.Chromatic.Witness.ElementaryProductDegree +OAI.Combinatorics.Chromatic.Witness.ElementarySingletonCoefficient +OAI.Combinatorics.Chromatic.Witness.GraphDecoratedHistories +OAI.Combinatorics.Chromatic.Witness.GraphRequiredPackets +OAI.Combinatorics.Chromatic.Witness.HistoryMainWitness +OAI.Combinatorics.Chromatic.Witness.ProfilePartition +OAI.Combinatorics.Chromatic.Witness.WitnessTransport diff --git a/tasks/elementary-positivity/solution/reference.py b/tasks/elementary-positivity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/elementary-positivity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/elementary-positivity/solution/solve.sh b/tasks/elementary-positivity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..555602e0e6f5204aba6f99f7eaf6c6c1fc7deb51 --- /dev/null +++ b/tasks/elementary-positivity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ElementaryPositivity, i.e. module OAI.Combinatorics.Chromatic.Main and the +# 549 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Chromatic.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ElementaryPositivity" diff --git a/tasks/elementary-positivity/task.toml b/tasks/elementary-positivity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f264aa085ae29f76a0d6e214d9cc6b72a882a1f --- /dev/null +++ b/tasks/elementary-positivity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/elementary-positivity" +version = "1.0.0" +description = "Prove ElementaryPositivity (openai/math family 169: The Shareshian–Wachs $e$-positivity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ElementaryPositivity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ElementaryPositivity" +family = "169" +family_title = "The Shareshian–Wachs $e$-positivity conjecture" +subject = "Combinatorics" +theorems = [] +definition_holes = ["OAI.elementaryPositivityWitness"] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Chromatic.Main" +reference_modules = 549 +reference_lean_bytes = 3473360 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2371 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14826 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/elementary-positivity/tests/Challenge.lean b/tasks/elementary-positivity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2e90d68d97df418c71af9bf5080711c8a2b349ef --- /dev/null +++ b/tasks/elementary-positivity/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib + +namespace OAI + +namespace ElementaryPositivity + +structure NaturalUnitIntervalGraph (n : ℕ) where + h : Fin n → Fin n + increasing : Monotone h + extensive : ∀ i, i ≤ h i + +namespace NaturalUnitIntervalGraph + +variable {n : ℕ} (G : NaturalUnitIntervalGraph n) + +def Edge (i j : Fin n) : Prop := + (i < j ∧ j ≤ G.h i) ∨ (j < i ∧ i ≤ G.h j) + +instance (i j : Fin n) : Decidable (G.Edge i j) := + inferInstanceAs (Decidable ((_ ∧ _) ∨ (_ ∧ _))) + +def Nondescent (σ : Equiv.Perm (Fin n)) : Prop := + ∀ i j : Fin n, i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j) + +instance (σ : Equiv.Perm (Fin n)) : Decidable (G.Nondescent σ) := + inferInstanceAs (Decidable (∀ i j : Fin n, + i.val + 1 = j.val → σ j < σ i → G.Edge (σ i) (σ j))) + +def graphInversions (σ : Equiv.Perm (Fin n)) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ σ ij.2 < σ ij.1 ∧ G.Edge (σ ij.1) (σ ij.2)).card + +def Proper {r : ℕ} (f : Fin n → Fin r) : Prop := + ∀ i j : Fin n, G.Edge i j → f i ≠ f j + +instance {r : ℕ} (f : Fin n → Fin r) : Decidable (G.Proper f) := + inferInstanceAs (Decidable (∀ i j : Fin n, G.Edge i j → f i ≠ f j)) + +def coloringAscents {r : ℕ} (f : Fin n → Fin r) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ G.Edge ij.1 ij.2 ∧ f ij.1 < f ij.2).card + +noncomputable def chromatic (r : ℕ) : MvPolynomial (Fin r) (Polynomial ℕ) := + ∑ f ∈ Finset.univ.filter (G.Proper (r := r)), + MvPolynomial.C (Polynomial.X ^ G.coloringAscents f) * + ∏ i : Fin n, MvPolynomial.X (f i) + +structure PermutationWitness where + theta : {σ : Equiv.Perm (Fin n) // G.Nondescent σ} → Nat.Partition n + expansion : ∀ r : ℕ, G.chromatic r = + ∑ σ : {σ : Equiv.Perm (Fin n) // G.Nondescent σ}, + MvPolynomial.C (Polynomial.X ^ G.graphInversions σ.val) * + MvPolynomial.esymmPart (Fin r) (Polynomial ℕ) (theta σ) + +end NaturalUnitIntervalGraph +end ElementaryPositivity + +def elementaryPositivityWitness (n : ℕ) + (G : ElementaryPositivity.NaturalUnitIntervalGraph n) : + G.PermutationWitness := by + sorry + +end OAI diff --git a/tasks/elementary-positivity/tests/grade.py b/tasks/elementary-positivity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/elementary-positivity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/elementary-positivity/tests/task.json b/tasks/elementary-positivity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9852f05a1b17e5cba9eef69dfb40b4a62d42d293 --- /dev/null +++ b/tasks/elementary-positivity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ElementaryPositivity", + "comparator": { + "theorem_names": [], + "definition_names": [ + "OAI.elementaryPositivityWitness" + ], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13926 +} \ No newline at end of file diff --git a/tasks/elementary-positivity/tests/test.sh b/tasks/elementary-positivity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/elementary-positivity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/entangled-games/environment/Dockerfile b/tasks/entangled-games/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/entangled-games/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/entangled-games/environment/fetch_mathlib.sh b/tasks/entangled-games/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/entangled-games/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/entangled-games/environment/lake-manifest.json b/tasks/entangled-games/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/entangled-games/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/entangled-games/environment/lakefile.lean b/tasks/entangled-games/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/entangled-games/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/entangled-games/environment/lean_setup.sh b/tasks/entangled-games/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/entangled-games/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/entangled-games/environment/pack_submission.py b/tasks/entangled-games/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/entangled-games/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/entangled-games/instruction.md b/tasks/entangled-games/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd3f0bc6298a1e85be6ede81eb1125b6860f07c8 --- /dev/null +++ b/tasks/entangled-games/instruction.md @@ -0,0 +1,131 @@ +# openai/math challenge `EntangledGames` (family 277) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 277 of the release, *Threshold repetition for entangled games* +(Mathematical physics). The family as a whole: Proves exponential threshold repetition for every finite two-player one-round game: if its entangled value is $v<1$, the probability of winning at least a fraction $v+\delta$ of $k$ independent repetitions decays exponentially in $k$, for $0<\delta<1-v$. Arbitrary joint finite-dimensional entangled strategies and correlated question distributions are allowed. + +The challenge is `EntangledGames`, also at `/opt/openai-math/challenges/EntangledGames.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ComplexOrder + +namespace ThresholdParallelRepetition + +structure Game (x y a b : ℕ) where + questionProb : Fin (x + 1) × Fin (y + 1) → ℝ + questionProb_nonneg : ∀ z, 0 ≤ questionProb z + questionProb_sum : ∑ z, questionProb z = 1 + accepts : Fin (x + 1) → Fin (y + 1) → Fin (a + 1) → Fin (b + 1) → Bool + +structure Strategy (X Y A B : Type) [Fintype A] [Fintype B] where + dimA : ℕ + dimB : ℕ + state : Fin (dimA + 1) × Fin (dimB + 1) → ℂ + state_unit : ∑ i, Complex.normSq (state i) = 1 + alice : X → A → Matrix (Fin (dimA + 1)) (Fin (dimA + 1)) ℂ + bob : Y → B → Matrix (Fin (dimB + 1)) (Fin (dimB + 1)) ℂ + alice_pos : ∀ x a, (alice x a).PosSemidef + bob_pos : ∀ y b, (bob y b).PosSemidef + alice_total : ∀ x, ∑ a, alice x a = 1 + bob_total : ∀ y, ∑ b, bob y b = 1 + +def Strategy.born {X Y A B : Type} [Fintype A] [Fintype B] + (S : Strategy X Y A B) (x : X) (y : Y) (a : A) (b : B) : ℝ := + ∑ i, ∑ j, (star (S.state i) * + (S.alice x a i.1 j.1 * S.bob y b i.2 j.2) * S.state j).re + +abbrev SingleStrategy (x y a b : ℕ) := + Strategy (Fin (x + 1)) (Fin (y + 1)) (Fin (a + 1)) (Fin (b + 1)) + +def successProbability {x y a b : ℕ} (G : Game x y a b) (S : SingleStrategy x y a b) : ℝ := + ∑ z : Fin (x + 1) × Fin (y + 1), G.questionProb z * + ∑ w : Fin (a + 1) × Fin (b + 1), + if G.accepts z.1 z.2 w.1 w.2 then S.born z.1 z.2 w.1 w.2 else 0 + +def entangledValue {x y a b : ℕ} (G : Game x y a b) : ℝ := + sSup (Set.range (successProbability G)) + +abbrev RepeatedStrategy (x y a b k : ℕ) := + Strategy (Fin k → Fin (x + 1)) (Fin k → Fin (y + 1)) + (Fin k → Fin (a + 1)) (Fin k → Fin (b + 1)) + +def wins {x y a b k : ℕ} (G : Game x y a b) + (xs : Fin k → Fin (x + 1)) (ys : Fin k → Fin (y + 1)) + (as : Fin k → Fin (a + 1)) (bs : Fin k → Fin (b + 1)) : ℕ := + ∑ i, if G.accepts (xs i) (ys i) (as i) (bs i) then 1 else 0 + +def thresholdProbability {x y a b k : ℕ} (G : Game x y a b) (δ : ℝ) + (S : RepeatedStrategy x y a b k) : ℝ := + ∑ xs : Fin k → Fin (x + 1), ∑ ys : Fin k → Fin (y + 1), + (∏ i, G.questionProb (xs i, ys i)) * + ∑ as : Fin k → Fin (a + 1), ∑ bs : Fin k → Fin (b + 1), + if ⌈(entangledValue G + δ) * (k : ℝ)⌉₊ ≤ wins G xs ys as bs + then S.born xs ys as bs else 0 + +def thresholdValue {x y a b k : ℕ} (G : Game x y a b) (δ : ℝ) : ℝ := + sSup (Set.range (thresholdProbability (k := k) G δ)) + +theorem threshold_parallel_repetition : + ∃ κ₀ : ℝ, 0 < κ₀ ∧ + ∀ (x y a b : ℕ) (G : Game x y a b), entangledValue G < 1 → + ∀ (δ : ℝ), 0 < δ → δ < 1 - entangledValue G → + ∀ (k : ℕ), 1 ≤ k → + (∀ S : RepeatedStrategy x y a b k, + thresholdProbability G δ S ≤ + Real.exp (-κ₀ * δ ^ 13 / (1 + Real.log (((a + 1) * (b + 1) : ℕ) : ℝ)) * k)) ∧ + thresholdValue (k := k) G δ ≤ + Real.exp (-κ₀ * δ ^ 13 / (1 + Real.log (((a + 1) * (b + 1) : ℕ) : ℝ)) * k) := by + sorry + +end ThresholdParallelRepetition + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EntangledGames.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThresholdParallelRepetition.threshold_parallel_repetition` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/entangled-games/solution/closure.txt b/tasks/entangled-games/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2bd31038f483573b3c2b2654ad71420adfda93a --- /dev/null +++ b/tasks/entangled-games/solution/closure.txt @@ -0,0 +1,30 @@ +OAI.Probability.EntangledGames.Basic +OAI.Probability.EntangledGames.BlockStates +OAI.Probability.EntangledGames.CoherentFilters +OAI.Probability.EntangledGames.ConditionedStep +OAI.Probability.EntangledGames.CorrelatedSampling +OAI.Probability.EntangledGames.EffectExposure +OAI.Probability.EntangledGames.ExponentialBounds +OAI.Probability.EntangledGames.ExposureChain +OAI.Probability.EntangledGames.ExposureData +OAI.Probability.EntangledGames.ExposureErrors +OAI.Probability.EntangledGames.FiniteProbability +OAI.Probability.EntangledGames.FreshStates +OAI.Probability.EntangledGames.HilbertSchmidt +OAI.Probability.EntangledGames.Main +OAI.Probability.EntangledGames.MeasurementTransport +OAI.Probability.EntangledGames.MixedExposure +OAI.Probability.EntangledGames.Model +OAI.Probability.EntangledGames.Purification +OAI.Probability.EntangledGames.Refinement +OAI.Probability.EntangledGames.RelativeEntropy +OAI.Probability.EntangledGames.RepeatedModel +OAI.Probability.EntangledGames.Resampling +OAI.Probability.EntangledGames.Resolvent +OAI.Probability.EntangledGames.Rounding +OAI.Probability.EntangledGames.SamplingStrategy +OAI.Probability.EntangledGames.SpectralBins +OAI.Probability.EntangledGames.SpectralEntropy +OAI.Probability.EntangledGames.StrategyBridge +OAI.Probability.EntangledGames.TestExtraction +OAI.Probability.EntangledGames.TestMoments diff --git a/tasks/entangled-games/solution/reference.py b/tasks/entangled-games/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/entangled-games/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/entangled-games/solution/solve.sh b/tasks/entangled-games/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5d9f4846a44ef18c3ba96efa8ed8f99964ff8cd5 --- /dev/null +++ b/tasks/entangled-games/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EntangledGames, i.e. module OAI.Probability.EntangledGames.Main and the +# 30 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.EntangledGames.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EntangledGames" diff --git a/tasks/entangled-games/task.toml b/tasks/entangled-games/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2349b8df6d75b16c3afc7fa765528feb373d9214 --- /dev/null +++ b/tasks/entangled-games/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/entangled-games" +version = "1.0.0" +description = "Prove EntangledGames (openai/math family 277: Threshold repetition for entangled games) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EntangledGames.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EntangledGames" +family = "277" +family_title = "Threshold repetition for entangled games" +subject = "Mathematical physics" +theorems = ["OAI.ThresholdParallelRepetition.threshold_parallel_repetition"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.EntangledGames.Main" +reference_modules = 30 +reference_lean_bytes = 354352 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 786 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12018 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/entangled-games/tests/Challenge.lean b/tasks/entangled-games/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..efc82ea59c1e011b618542c625432c56ae765c25 --- /dev/null +++ b/tasks/entangled-games/tests/Challenge.lean @@ -0,0 +1,80 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ComplexOrder + +namespace ThresholdParallelRepetition + +structure Game (x y a b : ℕ) where + questionProb : Fin (x + 1) × Fin (y + 1) → ℝ + questionProb_nonneg : ∀ z, 0 ≤ questionProb z + questionProb_sum : ∑ z, questionProb z = 1 + accepts : Fin (x + 1) → Fin (y + 1) → Fin (a + 1) → Fin (b + 1) → Bool + +structure Strategy (X Y A B : Type) [Fintype A] [Fintype B] where + dimA : ℕ + dimB : ℕ + state : Fin (dimA + 1) × Fin (dimB + 1) → ℂ + state_unit : ∑ i, Complex.normSq (state i) = 1 + alice : X → A → Matrix (Fin (dimA + 1)) (Fin (dimA + 1)) ℂ + bob : Y → B → Matrix (Fin (dimB + 1)) (Fin (dimB + 1)) ℂ + alice_pos : ∀ x a, (alice x a).PosSemidef + bob_pos : ∀ y b, (bob y b).PosSemidef + alice_total : ∀ x, ∑ a, alice x a = 1 + bob_total : ∀ y, ∑ b, bob y b = 1 + +def Strategy.born {X Y A B : Type} [Fintype A] [Fintype B] + (S : Strategy X Y A B) (x : X) (y : Y) (a : A) (b : B) : ℝ := + ∑ i, ∑ j, (star (S.state i) * + (S.alice x a i.1 j.1 * S.bob y b i.2 j.2) * S.state j).re + +abbrev SingleStrategy (x y a b : ℕ) := + Strategy (Fin (x + 1)) (Fin (y + 1)) (Fin (a + 1)) (Fin (b + 1)) + +def successProbability {x y a b : ℕ} (G : Game x y a b) (S : SingleStrategy x y a b) : ℝ := + ∑ z : Fin (x + 1) × Fin (y + 1), G.questionProb z * + ∑ w : Fin (a + 1) × Fin (b + 1), + if G.accepts z.1 z.2 w.1 w.2 then S.born z.1 z.2 w.1 w.2 else 0 + +def entangledValue {x y a b : ℕ} (G : Game x y a b) : ℝ := + sSup (Set.range (successProbability G)) + +abbrev RepeatedStrategy (x y a b k : ℕ) := + Strategy (Fin k → Fin (x + 1)) (Fin k → Fin (y + 1)) + (Fin k → Fin (a + 1)) (Fin k → Fin (b + 1)) + +def wins {x y a b k : ℕ} (G : Game x y a b) + (xs : Fin k → Fin (x + 1)) (ys : Fin k → Fin (y + 1)) + (as : Fin k → Fin (a + 1)) (bs : Fin k → Fin (b + 1)) : ℕ := + ∑ i, if G.accepts (xs i) (ys i) (as i) (bs i) then 1 else 0 + +def thresholdProbability {x y a b k : ℕ} (G : Game x y a b) (δ : ℝ) + (S : RepeatedStrategy x y a b k) : ℝ := + ∑ xs : Fin k → Fin (x + 1), ∑ ys : Fin k → Fin (y + 1), + (∏ i, G.questionProb (xs i, ys i)) * + ∑ as : Fin k → Fin (a + 1), ∑ bs : Fin k → Fin (b + 1), + if ⌈(entangledValue G + δ) * (k : ℝ)⌉₊ ≤ wins G xs ys as bs + then S.born xs ys as bs else 0 + +def thresholdValue {x y a b k : ℕ} (G : Game x y a b) (δ : ℝ) : ℝ := + sSup (Set.range (thresholdProbability (k := k) G δ)) + +theorem threshold_parallel_repetition : + ∃ κ₀ : ℝ, 0 < κ₀ ∧ + ∀ (x y a b : ℕ) (G : Game x y a b), entangledValue G < 1 → + ∀ (δ : ℝ), 0 < δ → δ < 1 - entangledValue G → + ∀ (k : ℕ), 1 ≤ k → + (∀ S : RepeatedStrategy x y a b k, + thresholdProbability G δ S ≤ + Real.exp (-κ₀ * δ ^ 13 / (1 + Real.log (((a + 1) * (b + 1) : ℕ) : ℝ)) * k)) ∧ + thresholdValue (k := k) G δ ≤ + Real.exp (-κ₀ * δ ^ 13 / (1 + Real.log (((a + 1) * (b + 1) : ℕ) : ℝ)) * k) := by + sorry + +end ThresholdParallelRepetition + +end + +end OAI diff --git a/tasks/entangled-games/tests/grade.py b/tasks/entangled-games/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/entangled-games/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/entangled-games/tests/task.json b/tasks/entangled-games/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4b4e272f5e379c517c6c93e87bd773bcb6ccb7b5 --- /dev/null +++ b/tasks/entangled-games/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EntangledGames", + "comparator": { + "theorem_names": [ + "OAI.ThresholdParallelRepetition.threshold_parallel_repetition" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11118 +} \ No newline at end of file diff --git a/tasks/entangled-games/tests/test.sh b/tasks/entangled-games/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/entangled-games/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/entropy-photon-number/environment/Dockerfile b/tasks/entropy-photon-number/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/entropy-photon-number/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/entropy-photon-number/environment/fetch_mathlib.sh b/tasks/entropy-photon-number/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/entropy-photon-number/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/entropy-photon-number/environment/lake-manifest.json b/tasks/entropy-photon-number/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/entropy-photon-number/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/entropy-photon-number/environment/lakefile.lean b/tasks/entropy-photon-number/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/entropy-photon-number/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/entropy-photon-number/environment/lean_setup.sh b/tasks/entropy-photon-number/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/entropy-photon-number/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/entropy-photon-number/environment/pack_submission.py b/tasks/entropy-photon-number/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/entropy-photon-number/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/entropy-photon-number/instruction.md b/tasks/entropy-photon-number/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0e85e7d77abbaf2e47674282ab4a71790f01547e --- /dev/null +++ b/tasks/entropy-photon-number/instruction.md @@ -0,0 +1,163 @@ +# openai/math challenge `EntropyPhotonNumber` (family 273) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 273 of the release, *The entropy photon-number inequality* +(Mathematical physics). The family as a whole: Proves the entropy photon-number inequality for beam-splitter mixing of two independent finite-energy bosonic inputs in any finite number of modes: the output\textquotesingle s entropy photon number is at least the transmissivity-weighted average of the inputs\textquotesingle. Arbitrary entanglement within each input is allowed, and product thermal inputs attain equality even when their entropies differ. + +The challenge is `EntropyPhotonNumber`, also at `/opt/openai-math/challenges/EntropyPhotonNumber.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators ComplexConjugate + +namespace EntropyPhotonNumber + +/-- The number-basis indices for `n` bosonic modes. -/ +abbrev NumberIndex (n : ℕ) := Fin n → ℕ + +/-- The full, untruncated bosonic Fock space `ℓ²(ℕⁿ, ℂ)`. -/ +abbrev Fock (n : ℕ) := lp (fun _ : NumberIndex n => ℂ) 2 + +/-- A number-basis vector. -/ +def numberKet {n : ℕ} (k : NumberIndex n) : Fock n := lp.single 2 k 1 + +/-- Matrix entries of an operator in the number basis. -/ +def entry {n : ℕ} (T : Fock n →L[ℂ] Fock n) (k l : NumberIndex n) : ℂ := + inner ℂ (numberKet k) (T (numberKet l)) + +/-- Positive trace-one operators. For a positive bounded operator on this +Hilbert space, summability of its diagonal is the positive trace-class +criterion; `HasSum ... 1` includes summability as well as normalization. -/ +structure State (n : ℕ) where + op : Fock n →L[ℂ] Fock n + positive : op.IsPositive + trace_one : HasSum (fun k => (entry op k k).re) 1 + +/-- Total number of quanta in a number-basis vector. -/ +def totalNumber {n : ℕ} (k : NumberIndex n) : ℕ := ∑ j, k j + +/-- Exactly finiteness of the expectation of the nonnegative number operator. -/ +def FiniteEnergy {n : ℕ} (ρ : State n) : Prop := + Summable (fun k => (totalNumber k : ℝ) * (entry ρ.op k k).re) + +/-- `−Tr ρ log ρ`, using the continuous extension of `−t log t` at zero +and continuous functional calculus for the positive operator `ρ`. -/ +def entropy {n : ℕ} (ρ : State n) : ℝ := + ∑' k, (entry (cfc (fun z : ℂ => (-(z.re * Real.log z.re) : ℂ)) ρ.op) k k).re + +/-- The thermal entropy per mode, with the convention `0 log 0 = 0`. -/ +def g (t : ℝ) : ℝ := (t + 1) * Real.log (t + 1) - t * Real.log t + +/-- The inverse of increasing `g : [0,∞) → [0,∞)`, expressed by its lower +level cut. Only its values on `[0,∞)` occur in the main theorem. -/ +def gInv (s : ℝ) : ℝ := sInf {t : ℝ | 0 ≤ t ∧ s ≤ g t} + +/-- One-mode passive beam-splitter coefficient, in number bases. It is the +coefficient of `(c†)^k (d†)^e` in +`(√η c† − √(1−η) d†)^a (√(1−η) c† + √η d†)^b`, +with the normalized number-vector factorials. -/ +def oneModeBeamCoefficient (η : ℝ) (k e a b : ℕ) : ℝ := + if k + e = a + b then + Real.sqrt (((k.factorial : ℝ) * e.factorial) / (a.factorial * b.factorial)) * + ∑ p ∈ Finset.range (a + 1), ∑ q ∈ Finset.range (b + 1), + if p + q = k then + (a.choose p : ℝ) * b.choose q * + Real.sqrt η ^ p * (-Real.sqrt (1 - η)) ^ (a - p) * + Real.sqrt (1 - η) ^ q * Real.sqrt η ^ (b - q) + else 0 + else 0 + +/-- The same passive rotation is performed on all mode indices. -/ +def beamCoefficient {n : ℕ} (η : ℝ) (k e a b : NumberIndex n) : ℝ := + ∏ j, oneModeBeamCoefficient η (k j) (e j) (a j) (b j) + +/-- Choices of the first input number in the total-number sector of `(k,e)`. -/ +abbrev SectorSplit {n : ℕ} (k e : NumberIndex n) := ∀ j, Fin (k j + e j + 1) + +def splitLeft {n : ℕ} {k e : NumberIndex n} (a : SectorSplit k e) : NumberIndex n := + fun j => a j + +def splitRight {n : ℕ} {k e : NumberIndex n} (a : SectorSplit k e) : NumberIndex n := + fun j => k j + e j - a j + +/-- A single discarded-number diagonal block of `U(ρA ⊗ ρB)U†`. +The sums are finite because passive mixing preserves number in each paired +mode. The two unrestricted density matrices allow all internal entanglement. -/ +def outputBlock {n : ℕ} (η : ℝ) (ρA ρB : State n) + (k l e : NumberIndex n) : ℂ := + ∑ a : SectorSplit k e, ∑ b : SectorSplit l e, + (beamCoefficient η k e (splitLeft a) (splitRight a) : ℂ) * + entry ρA.op (splitLeft a) (splitLeft b) * + entry ρB.op (splitRight a) (splitRight b) * + (beamCoefficient η l e (splitLeft b) (splitRight b) : ℂ) + +/-- Reduced state after passive beam-splitter mixing of independent ports. +The second row of the orthogonal rotation is `(-√(1−η),√η)`; changing its +sign has no effect on this reduced state. `HasSum` records the actual partial +trace, not a default value for a possibly divergent series. -/ +def IsBeamSplitterOutput {n : ℕ} (η : ℝ) (ρA ρB ρC : State n) : Prop := + ∀ k l, HasSum (outputBlock η ρA ρB k l) (entry ρC.op k l) + +/-- The entropy photon-number inequality for arbitrary finite-energy inputs +and any positive finite number of modes. -/ +theorem entropy_photon_number_inequality + (n : ℕ) (hn : 1 ≤ n) (ρA ρB ρC : State n) + (hA : FiniteEnergy ρA) (hB : FiniteEnergy ρB) + (η : ℝ) (hη : η ∈ Set.Icc 0 1) + (hC : IsBeamSplitterOutput η ρA ρB ρC) : + η * gInv (entropy ρA / n) + (1 - η) * gInv (entropy ρB / n) ≤ + gInv (entropy ρC / n) := by + sorry + +end EntropyPhotonNumber + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EntropyPhotonNumber.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EntropyPhotonNumber.entropy_photon_number_inequality` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/entropy-photon-number/solution/closure.txt b/tasks/entropy-photon-number/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..53b3a1a69a82b9179f5cfb6b0a75d19248e376f2 --- /dev/null +++ b/tasks/entropy-photon-number/solution/closure.txt @@ -0,0 +1,26 @@ +OAI.Analysis.DiagonalForms +OAI.Analysis.Herglotz +OAI.Analysis.QuantumTrace.Basic +OAI.Analysis.TensorLp +OAI.InformationTheory.PhotonNumber.Basic +OAI.InformationTheory.PhotonNumber.BeamForms +OAI.InformationTheory.PhotonNumber.BeamTrace +OAI.InformationTheory.PhotonNumber.Continuity +OAI.InformationTheory.PhotonNumber.Contraction +OAI.InformationTheory.PhotonNumber.Duality +OAI.InformationTheory.PhotonNumber.Entropy +OAI.InformationTheory.PhotonNumber.FiniteVariation +OAI.InformationTheory.PhotonNumber.Functions +OAI.InformationTheory.PhotonNumber.Generator +OAI.InformationTheory.PhotonNumber.Gibbs +OAI.InformationTheory.PhotonNumber.GibbsVariational +OAI.InformationTheory.PhotonNumber.Inequality +OAI.InformationTheory.PhotonNumber.Interpolation +OAI.InformationTheory.PhotonNumber.Minimum +OAI.InformationTheory.PhotonNumber.PhysicalMinimum +OAI.InformationTheory.PhotonNumber.SpectralForms +OAI.InformationTheory.PhotonNumber.SpectralLog +OAI.InformationTheory.PhotonNumber.ThermalLimit +OAI.InformationTheory.PhotonNumber.ThermalMetric +OAI.MathematicalPhysics.Fock.Beam +OAI.MathematicalPhysics.Fock.Operators diff --git a/tasks/entropy-photon-number/solution/reference.py b/tasks/entropy-photon-number/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/entropy-photon-number/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/entropy-photon-number/solution/solve.sh b/tasks/entropy-photon-number/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..94019b3dd23a3ad2a5473199fa4bc985cac27957 --- /dev/null +++ b/tasks/entropy-photon-number/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EntropyPhotonNumber, i.e. module OAI.InformationTheory.PhotonNumber.Inequality and the +# 26 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.PhotonNumber.Inequality /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EntropyPhotonNumber" diff --git a/tasks/entropy-photon-number/task.toml b/tasks/entropy-photon-number/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..43e7f232a6b226ef53cfbf2da778ae81ecc3dfbf --- /dev/null +++ b/tasks/entropy-photon-number/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/entropy-photon-number" +version = "1.0.0" +description = "Prove EntropyPhotonNumber (openai/math family 273: The entropy photon-number inequality) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EntropyPhotonNumber.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EntropyPhotonNumber" +family = "273" +family_title = "The entropy photon-number inequality" +subject = "Mathematical physics" +theorems = ["OAI.EntropyPhotonNumber.entropy_photon_number_inequality"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.PhotonNumber.Inequality" +reference_modules = 26 +reference_lean_bytes = 1401086 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 998 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12960 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/entropy-photon-number/tests/Challenge.lean b/tasks/entropy-photon-number/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c628526b1d068d78177afe8f37e3fd9b638d371 --- /dev/null +++ b/tasks/entropy-photon-number/tests/Challenge.lean @@ -0,0 +1,112 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators ComplexConjugate + +namespace EntropyPhotonNumber + +/-- The number-basis indices for `n` bosonic modes. -/ +abbrev NumberIndex (n : ℕ) := Fin n → ℕ + +/-- The full, untruncated bosonic Fock space `ℓ²(ℕⁿ, ℂ)`. -/ +abbrev Fock (n : ℕ) := lp (fun _ : NumberIndex n => ℂ) 2 + +/-- A number-basis vector. -/ +def numberKet {n : ℕ} (k : NumberIndex n) : Fock n := lp.single 2 k 1 + +/-- Matrix entries of an operator in the number basis. -/ +def entry {n : ℕ} (T : Fock n →L[ℂ] Fock n) (k l : NumberIndex n) : ℂ := + inner ℂ (numberKet k) (T (numberKet l)) + +/-- Positive trace-one operators. For a positive bounded operator on this +Hilbert space, summability of its diagonal is the positive trace-class +criterion; `HasSum ... 1` includes summability as well as normalization. -/ +structure State (n : ℕ) where + op : Fock n →L[ℂ] Fock n + positive : op.IsPositive + trace_one : HasSum (fun k => (entry op k k).re) 1 + +/-- Total number of quanta in a number-basis vector. -/ +def totalNumber {n : ℕ} (k : NumberIndex n) : ℕ := ∑ j, k j + +/-- Exactly finiteness of the expectation of the nonnegative number operator. -/ +def FiniteEnergy {n : ℕ} (ρ : State n) : Prop := + Summable (fun k => (totalNumber k : ℝ) * (entry ρ.op k k).re) + +/-- `−Tr ρ log ρ`, using the continuous extension of `−t log t` at zero +and continuous functional calculus for the positive operator `ρ`. -/ +def entropy {n : ℕ} (ρ : State n) : ℝ := + ∑' k, (entry (cfc (fun z : ℂ => (-(z.re * Real.log z.re) : ℂ)) ρ.op) k k).re + +/-- The thermal entropy per mode, with the convention `0 log 0 = 0`. -/ +def g (t : ℝ) : ℝ := (t + 1) * Real.log (t + 1) - t * Real.log t + +/-- The inverse of increasing `g : [0,∞) → [0,∞)`, expressed by its lower +level cut. Only its values on `[0,∞)` occur in the main theorem. -/ +def gInv (s : ℝ) : ℝ := sInf {t : ℝ | 0 ≤ t ∧ s ≤ g t} + +/-- One-mode passive beam-splitter coefficient, in number bases. It is the +coefficient of `(c†)^k (d†)^e` in +`(√η c† − √(1−η) d†)^a (√(1−η) c† + √η d†)^b`, +with the normalized number-vector factorials. -/ +def oneModeBeamCoefficient (η : ℝ) (k e a b : ℕ) : ℝ := + if k + e = a + b then + Real.sqrt (((k.factorial : ℝ) * e.factorial) / (a.factorial * b.factorial)) * + ∑ p ∈ Finset.range (a + 1), ∑ q ∈ Finset.range (b + 1), + if p + q = k then + (a.choose p : ℝ) * b.choose q * + Real.sqrt η ^ p * (-Real.sqrt (1 - η)) ^ (a - p) * + Real.sqrt (1 - η) ^ q * Real.sqrt η ^ (b - q) + else 0 + else 0 + +/-- The same passive rotation is performed on all mode indices. -/ +def beamCoefficient {n : ℕ} (η : ℝ) (k e a b : NumberIndex n) : ℝ := + ∏ j, oneModeBeamCoefficient η (k j) (e j) (a j) (b j) + +/-- Choices of the first input number in the total-number sector of `(k,e)`. -/ +abbrev SectorSplit {n : ℕ} (k e : NumberIndex n) := ∀ j, Fin (k j + e j + 1) + +def splitLeft {n : ℕ} {k e : NumberIndex n} (a : SectorSplit k e) : NumberIndex n := + fun j => a j + +def splitRight {n : ℕ} {k e : NumberIndex n} (a : SectorSplit k e) : NumberIndex n := + fun j => k j + e j - a j + +/-- A single discarded-number diagonal block of `U(ρA ⊗ ρB)U†`. +The sums are finite because passive mixing preserves number in each paired +mode. The two unrestricted density matrices allow all internal entanglement. -/ +def outputBlock {n : ℕ} (η : ℝ) (ρA ρB : State n) + (k l e : NumberIndex n) : ℂ := + ∑ a : SectorSplit k e, ∑ b : SectorSplit l e, + (beamCoefficient η k e (splitLeft a) (splitRight a) : ℂ) * + entry ρA.op (splitLeft a) (splitLeft b) * + entry ρB.op (splitRight a) (splitRight b) * + (beamCoefficient η l e (splitLeft b) (splitRight b) : ℂ) + +/-- Reduced state after passive beam-splitter mixing of independent ports. +The second row of the orthogonal rotation is `(-√(1−η),√η)`; changing its +sign has no effect on this reduced state. `HasSum` records the actual partial +trace, not a default value for a possibly divergent series. -/ +def IsBeamSplitterOutput {n : ℕ} (η : ℝ) (ρA ρB ρC : State n) : Prop := + ∀ k l, HasSum (outputBlock η ρA ρB k l) (entry ρC.op k l) + +/-- The entropy photon-number inequality for arbitrary finite-energy inputs +and any positive finite number of modes. -/ +theorem entropy_photon_number_inequality + (n : ℕ) (hn : 1 ≤ n) (ρA ρB ρC : State n) + (hA : FiniteEnergy ρA) (hB : FiniteEnergy ρB) + (η : ℝ) (hη : η ∈ Set.Icc 0 1) + (hC : IsBeamSplitterOutput η ρA ρB ρC) : + η * gInv (entropy ρA / n) + (1 - η) * gInv (entropy ρB / n) ≤ + gInv (entropy ρC / n) := by + sorry + +end EntropyPhotonNumber + +end + +end OAI diff --git a/tasks/entropy-photon-number/tests/grade.py b/tasks/entropy-photon-number/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/entropy-photon-number/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/entropy-photon-number/tests/task.json b/tasks/entropy-photon-number/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ec6ec285a16d6a83acd54b58ff4da46640aaa142 --- /dev/null +++ b/tasks/entropy-photon-number/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EntropyPhotonNumber", + "comparator": { + "theorem_names": [ + "OAI.EntropyPhotonNumber.entropy_photon_number_inequality" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12060 +} \ No newline at end of file diff --git a/tasks/entropy-photon-number/tests/test.sh b/tasks/entropy-photon-number/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/entropy-photon-number/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-five-color/environment/Dockerfile b/tasks/euclidean-five-color/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-five-color/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-five-color/environment/fetch_mathlib.sh b/tasks/euclidean-five-color/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-five-color/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-five-color/environment/lake-manifest.json b/tasks/euclidean-five-color/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-five-color/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-five-color/environment/lakefile.lean b/tasks/euclidean-five-color/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-five-color/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-five-color/environment/lean_setup.sh b/tasks/euclidean-five-color/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-five-color/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-five-color/environment/pack_submission.py b/tasks/euclidean-five-color/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-five-color/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-five-color/instruction.md b/tasks/euclidean-five-color/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..59c8d143ec75f1b10609876d1234d6e8a5355fe8 --- /dev/null +++ b/tasks/euclidean-five-color/instruction.md @@ -0,0 +1,66 @@ +# openai/math challenge `EuclideanFiveColor` (family 158) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 158 of the release, *The Euclidean plane cannot be colored with five colors* +(Combinatorics). The family as a whole: Proves that every five-coloring of the Euclidean plane has a monochromatic pair at distance one, with no restriction on the color classes. This advances the Hadwiger–Nelson problem: together with the classical seven-coloring, only six and seven remain possible chromatic numbers of the plane. + +The challenge is `EuclideanFiveColor`, also at `/opt/openai-math/challenges/EuclideanFiveColor.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace EuclideanFiveColor + +def ProperColoring (colorCount : ℕ) (coloring : ℂ → Fin colorCount) : Prop := + ∀ point otherPoint : ℂ, ‖point - otherPoint‖ = 1 → coloring point ≠ coloring otherPoint + +theorem no_proper_five_coloring : ¬ ∃ coloring : ℂ → Fin 5, ProperColoring 5 coloring := by + sorry + +end EuclideanFiveColor + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanFiveColor.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanFiveColor.no_proper_five_coloring` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-five-color/solution/closure.txt b/tasks/euclidean-five-color/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d23072e91cb6309c84780c2a8a78de5c3b96ddfa --- /dev/null +++ b/tasks/euclidean-five-color/solution/closure.txt @@ -0,0 +1,70 @@ +OAI.Analysis.PlaneSpectrum.Basic +OAI.Analysis.PlaneSpectrum.Characters +OAI.Analysis.PlaneSpectrum.CircleDecay +OAI.Analysis.PlaneSpectrum.CircleOperator +OAI.Analysis.PlaneSpectrum.ConditionalSpectrum +OAI.Analysis.PlaneSpectrum.Energy +OAI.Analysis.PlaneSpectrum.Ergodicity +OAI.Analysis.PlaneSpectrum.Fourier +OAI.Analysis.PlaneSpectrum.FourierTests +OAI.Analysis.PlaneSpectrum.InvariantMean +OAI.Analysis.PlaneSpectrum.Multipliers +OAI.Analysis.PlaneSpectrum.NumberFields +OAI.Analysis.PlaneSpectrum.PhaseCollision +OAI.Analysis.PlaneSpectrum.PhaseEncoding +OAI.Analysis.PlaneSpectrum.RadialEnergy +OAI.Analysis.PlaneSpectrum.Representations +OAI.Analysis.PlaneSpectrum.Selections +OAI.Analysis.PlaneSpectrum.SmallArcs +OAI.Analysis.PlaneSpectrum.SpectralMeasure +OAI.Geometry.PlaneColoring.Accumulation +OAI.Geometry.PlaneColoring.AngularBoundary +OAI.Geometry.PlaneColoring.BinaryDynamics +OAI.Geometry.PlaneColoring.BinaryPalettes +OAI.Geometry.PlaneColoring.BorelTransfer +OAI.Geometry.PlaneColoring.BoundaryTrace +OAI.Geometry.PlaneColoring.CircleMaps +OAI.Geometry.PlaneColoring.CircleTransport +OAI.Geometry.PlaneColoring.Coloring +OAI.Geometry.PlaneColoring.Compactness +OAI.Geometry.PlaneColoring.ContinuumLimits +OAI.Geometry.PlaneColoring.CyclicCore +OAI.Geometry.PlaneColoring.DiskAverages +OAI.Geometry.PlaneColoring.DiskExtension +OAI.Geometry.PlaneColoring.Exclusion +OAI.Geometry.PlaneColoring.Expansion +OAI.Geometry.PlaneColoring.Five +OAI.Geometry.PlaneColoring.FiveSupport +OAI.Geometry.PlaneColoring.FourContinuity +OAI.Geometry.PlaneColoring.FourTransport +OAI.Geometry.PlaneColoring.FullApproximation +OAI.Geometry.PlaneColoring.GraphCuts +OAI.Geometry.PlaneColoring.GraphPatches +OAI.Geometry.PlaneColoring.GraphRealization +OAI.Geometry.PlaneColoring.HoleApproximation +OAI.Geometry.PlaneColoring.Interfaces +OAI.Geometry.PlaneColoring.Mesh +OAI.Geometry.PlaneColoring.Moser +OAI.Geometry.PlaneColoring.PaletteDensity +OAI.Geometry.PlaneColoring.PaletteTransport +OAI.Geometry.PlaneColoring.Palettes +OAI.Geometry.PlaneColoring.PlanarCovers +OAI.Geometry.PlaneColoring.Rigidity +OAI.Geometry.PlaneColoring.Sectors +OAI.Geometry.PlaneColoring.States +OAI.Geometry.PlaneColoring.Transitions +OAI.Geometry.PlaneColoring.WeakColoring +OAI.MeasureTheory.CompactFactors.AlgebraModels +OAI.MeasureTheory.CompactFactors.Amenability +OAI.MeasureTheory.CompactFactors.Approximation +OAI.MeasureTheory.CompactFactors.BoundedFunctions +OAI.MeasureTheory.CompactFactors.Centers +OAI.MeasureTheory.CompactFactors.ConditionalLimits +OAI.MeasureTheory.CompactFactors.ConditionalSelection +OAI.MeasureTheory.CompactFactors.Factors +OAI.MeasureTheory.CompactFactors.Functions +OAI.MeasureTheory.CompactFactors.Kernels +OAI.MeasureTheory.CompactFactors.RelativeCenters +OAI.MeasureTheory.CompactFactors.RelativeProducts +OAI.MeasureTheory.CompactFactors.Separability +OAI.MeasureTheory.CompactFactors.Stationary diff --git a/tasks/euclidean-five-color/solution/reference.py b/tasks/euclidean-five-color/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-five-color/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-five-color/solution/solve.sh b/tasks/euclidean-five-color/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..70bb9a5698e48eb4889204ecd6d5a3b89fafed97 --- /dev/null +++ b/tasks/euclidean-five-color/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanFiveColor, i.e. module OAI.Geometry.PlaneColoring.Five and the +# 70 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.PlaneColoring.Five /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanFiveColor" diff --git a/tasks/euclidean-five-color/task.toml b/tasks/euclidean-five-color/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9b5c68c899364dd1f0cbd98ed5d51c6b93a599d1 --- /dev/null +++ b/tasks/euclidean-five-color/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-five-color" +version = "1.0.0" +description = "Prove EuclideanFiveColor (openai/math family 158: The Euclidean plane cannot be colored with five colors) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanFiveColor.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanFiveColor" +family = "158" +family_title = "The Euclidean plane cannot be colored with five colors" +subject = "Combinatorics" +theorems = ["OAI.EuclideanFiveColor.no_proper_five_coloring"] +definition_holes = [] +fixed_definitions = ["OAI.EuclideanFiveColor.ProperColoring"] +reference_module = "OAI.Geometry.PlaneColoring.Five" +reference_modules = 70 +reference_lean_bytes = 1548431 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1407 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13093 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-five-color/tests/Challenge.lean b/tasks/euclidean-five-color/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef3885b1086f42d9ba80c2771b238773e9291225 --- /dev/null +++ b/tasks/euclidean-five-color/tests/Challenge.lean @@ -0,0 +1,15 @@ +import Mathlib + +namespace OAI + +namespace EuclideanFiveColor + +def ProperColoring (colorCount : ℕ) (coloring : ℂ → Fin colorCount) : Prop := + ∀ point otherPoint : ℂ, ‖point - otherPoint‖ = 1 → coloring point ≠ coloring otherPoint + +theorem no_proper_five_coloring : ¬ ∃ coloring : ℂ → Fin 5, ProperColoring 5 coloring := by + sorry + +end EuclideanFiveColor + +end OAI diff --git a/tasks/euclidean-five-color/tests/grade.py b/tasks/euclidean-five-color/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-five-color/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-five-color/tests/task.json b/tasks/euclidean-five-color/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..35012f971f6a126eca9e4dbfffc4fadb52da355b --- /dev/null +++ b/tasks/euclidean-five-color/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanFiveColor", + "comparator": { + "theorem_names": [ + "OAI.EuclideanFiveColor.no_proper_five_coloring" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12193 +} \ No newline at end of file diff --git a/tasks/euclidean-five-color/tests/test.sh b/tasks/euclidean-five-color/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-five-color/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey-circle/environment/Dockerfile b/tasks/euclidean-ramsey-circle/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey-circle/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey-circle/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey-circle/environment/lake-manifest.json b/tasks/euclidean-ramsey-circle/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-circle/environment/lakefile.lean b/tasks/euclidean-ramsey-circle/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey-circle/environment/lean_setup.sh b/tasks/euclidean-ramsey-circle/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey-circle/environment/pack_submission.py b/tasks/euclidean-ramsey-circle/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey-circle/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey-circle/instruction.md b/tasks/euclidean-ramsey-circle/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d9d7405243aca42607a30f6b51d7af681e81019c --- /dev/null +++ b/tasks/euclidean-ramsey-circle/instruction.md @@ -0,0 +1,82 @@ +# openai/math challenge `EuclideanRamseyCircle` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamseyCircle`, also at `/opt/openai-math/challenges/EuclideanRamseyCircle.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace CircleConsequence + +/-- Every nonempty set of at most five distinct points on a circle is Ramsey. -/ +theorem at_most_five_circle_points_ramsey {s : ℕ} (a : Fin s → Space 2) + (hs : 0 < s) (hs5 : s ≤ 5) (ha : Function.Injective a) + (hsphere : ∃ c : Space 2, ∃ r : ℝ, ∀ i, dist (a i) c = r) : Ramsey a := by + sorry + +end CircleConsequence +end EuclideanRamsey + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamseyCircle.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.CircleConsequence.at_most_five_circle_points_ramsey` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey-circle/solution/closure.txt b/tasks/euclidean-ramsey-circle/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f973abb99285434f718a5e8b8bb084f6372e5ce --- /dev/null +++ b/tasks/euclidean-ramsey-circle/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.Combinatorics.EuclideanRamsey.AdicLifting +OAI.Combinatorics.EuclideanRamsey.Circle +OAI.Combinatorics.EuclideanRamsey.CircleExtension +OAI.Combinatorics.EuclideanRamsey.CircleGeometry +OAI.Combinatorics.EuclideanRamsey.CircleInterpolation +OAI.Combinatorics.EuclideanRamsey.CircleRows +OAI.Combinatorics.EuclideanRamsey.CircleSpan +OAI.Combinatorics.EuclideanRamsey.ColoringCompactness +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.CornerGroup +OAI.Combinatorics.EuclideanRamsey.CorrectionPaths +OAI.Combinatorics.EuclideanRamsey.DerivedFractions +OAI.Combinatorics.EuclideanRamsey.DifferentialSplitting +OAI.Combinatorics.EuclideanRamsey.Discretization +OAI.Combinatorics.EuclideanRamsey.FiniteEuclidean +OAI.Combinatorics.EuclideanRamsey.GramCompletion +OAI.Combinatorics.EuclideanRamsey.Hessian +OAI.Combinatorics.EuclideanRamsey.LatticeMoments +OAI.Combinatorics.EuclideanRamsey.Main +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.NormalCost +OAI.Combinatorics.EuclideanRamsey.OrbitAveraging +OAI.Combinatorics.EuclideanRamsey.PathFractions +OAI.Combinatorics.EuclideanRamsey.PathSynchronization +OAI.Combinatorics.EuclideanRamsey.PathWords +OAI.Combinatorics.EuclideanRamsey.Quadratic +OAI.Combinatorics.EuclideanRamsey.RationalConvolution +OAI.Combinatorics.EuclideanRamsey.SignedRows +OAI.Combinatorics.EuclideanRamsey.SmoothingKernel +OAI.Combinatorics.EuclideanRamsey.SmoothingMatrix +OAI.Combinatorics.EuclideanRamsey.StencilConvolution +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity +OAI.Combinatorics.EuclideanRamsey.TensorPresentation +OAI.Combinatorics.EuclideanRamsey.UltrafilterStrings diff --git a/tasks/euclidean-ramsey-circle/solution/reference.py b/tasks/euclidean-ramsey-circle/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey-circle/solution/solve.sh b/tasks/euclidean-ramsey-circle/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f673e5ea2cb0df9c361027a2eaf7314e6285ab7b --- /dev/null +++ b/tasks/euclidean-ramsey-circle/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamseyCircle, i.e. module OAI.Combinatorics.EuclideanRamsey.Circle and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.Circle /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamseyCircle" diff --git a/tasks/euclidean-ramsey-circle/task.toml b/tasks/euclidean-ramsey-circle/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f73791d0851de833bb0cbd7a4058bc51daf38179 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey-circle" +version = "1.0.0" +description = "Prove EuclideanRamseyCircle (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamseyCircle.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamseyCircle" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.CircleConsequence.at_most_five_circle_points_ramsey"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.Circle" +reference_modules = 35 +reference_lean_bytes = 318701 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 883 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11986 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey-circle/tests/Challenge.lean b/tasks/euclidean-ramsey-circle/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..182603c4e7f4cf64f3c0113d644ccbeab1fe478f --- /dev/null +++ b/tasks/euclidean-ramsey-circle/tests/Challenge.lean @@ -0,0 +1,31 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace CircleConsequence + +/-- Every nonempty set of at most five distinct points on a circle is Ramsey. -/ +theorem at_most_five_circle_points_ramsey {s : ℕ} (a : Fin s → Space 2) + (hs : 0 < s) (hs5 : s ≤ 5) (ha : Function.Injective a) + (hsphere : ∃ c : Space 2, ∃ r : ℝ, ∀ i, dist (a i) c = r) : Ramsey a := by + sorry + +end CircleConsequence +end EuclideanRamsey + +end + +end OAI diff --git a/tasks/euclidean-ramsey-circle/tests/grade.py b/tasks/euclidean-ramsey-circle/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey-circle/tests/task.json b/tasks/euclidean-ramsey-circle/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..60cd2b2241d6d0f2cf937eb47e4c796480f8a7ce --- /dev/null +++ b/tasks/euclidean-ramsey-circle/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamseyCircle", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.CircleConsequence.at_most_five_circle_points_ramsey" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11086 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-circle/tests/test.sh b/tasks/euclidean-ramsey-circle/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey-circle/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey-nine/environment/Dockerfile b/tasks/euclidean-ramsey-nine/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey-nine/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey-nine/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey-nine/environment/lake-manifest.json b/tasks/euclidean-ramsey-nine/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-nine/environment/lakefile.lean b/tasks/euclidean-ramsey-nine/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey-nine/environment/lean_setup.sh b/tasks/euclidean-ramsey-nine/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey-nine/environment/pack_submission.py b/tasks/euclidean-ramsey-nine/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey-nine/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey-nine/instruction.md b/tasks/euclidean-ramsey-nine/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..993720bd2991f9f5738a785b6e0c041e40900d6b --- /dev/null +++ b/tasks/euclidean-ramsey-nine/instruction.md @@ -0,0 +1,89 @@ +# openai/math challenge `EuclideanRamseyNine` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamseyNine`, also at `/opt/openai-math/challenges/EuclideanRamseyNine.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace NineStatement + +def literalCircleConfig (t : Fin 9 → ℝ) (i : Fin 9) : Space 2 := + WithLp.toLp 2 ![(1 - (t i)^2) / (1 + (t i)^2), + (2 * t i) / (1 + (t i)^2)] + +/-- Nine algebraically independent real parameters give distinct unit-circle +points whose configuration is not Ramsey. -/ +theorem nine_circle_configuration (t : Fin 9 → ℝ) + (ht : AlgebraicIndependent ℚ t) : + Function.Injective (literalCircleConfig t) ∧ + (∀ i, dist (literalCircleConfig t i) 0 = 1) ∧ + ¬ Ramsey (literalCircleConfig t) := by + sorry + +end NineStatement +end EuclideanRamsey + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamseyNine.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.NineStatement.nine_circle_configuration` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey-nine/solution/closure.txt b/tasks/euclidean-ramsey-nine/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1efa15da108f43e844c0e952253763594e0dcf73 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/solution/closure.txt @@ -0,0 +1,16 @@ +OAI.Combinatorics.EuclideanRamsey.CircleExtension +OAI.Combinatorics.EuclideanRamsey.CircleGeometry +OAI.Combinatorics.EuclideanRamsey.CircleInterpolation +OAI.Combinatorics.EuclideanRamsey.CircleSpan +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.IndependentTensor +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.Nine +OAI.Combinatorics.EuclideanRamsey.NineField +OAI.Combinatorics.EuclideanRamsey.NineGeometry +OAI.Combinatorics.EuclideanRamsey.NineGridDeterminant +OAI.Combinatorics.EuclideanRamsey.NineLinearObstruction +OAI.Combinatorics.EuclideanRamsey.NineRationalDeterminant +OAI.Combinatorics.EuclideanRamsey.NineStatement +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity diff --git a/tasks/euclidean-ramsey-nine/solution/reference.py b/tasks/euclidean-ramsey-nine/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey-nine/solution/solve.sh b/tasks/euclidean-ramsey-nine/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a77ce4baf4e06a35562c1e8a28d5fc8c50007d9 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamseyNine, i.e. module OAI.Combinatorics.EuclideanRamsey.NineStatement and the +# 16 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.NineStatement /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamseyNine" diff --git a/tasks/euclidean-ramsey-nine/task.toml b/tasks/euclidean-ramsey-nine/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd50faf4003de9526d503a9cffd888a4dd76e5cd --- /dev/null +++ b/tasks/euclidean-ramsey-nine/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey-nine" +version = "1.0.0" +description = "Prove EuclideanRamseyNine (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamseyNine.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamseyNine" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.NineStatement.nine_circle_configuration"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.NineStatement" +reference_modules = 16 +reference_lean_bytes = 77180 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 600 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11769 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey-nine/tests/Challenge.lean b/tasks/euclidean-ramsey-nine/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b723673ae577d21f103efe850a4295d3137f2d80 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/tests/Challenge.lean @@ -0,0 +1,38 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace NineStatement + +def literalCircleConfig (t : Fin 9 → ℝ) (i : Fin 9) : Space 2 := + WithLp.toLp 2 ![(1 - (t i)^2) / (1 + (t i)^2), + (2 * t i) / (1 + (t i)^2)] + +/-- Nine algebraically independent real parameters give distinct unit-circle +points whose configuration is not Ramsey. -/ +theorem nine_circle_configuration (t : Fin 9 → ℝ) + (ht : AlgebraicIndependent ℚ t) : + Function.Injective (literalCircleConfig t) ∧ + (∀ i, dist (literalCircleConfig t i) 0 = 1) ∧ + ¬ Ramsey (literalCircleConfig t) := by + sorry + +end NineStatement +end EuclideanRamsey + +end + +end OAI diff --git a/tasks/euclidean-ramsey-nine/tests/grade.py b/tasks/euclidean-ramsey-nine/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey-nine/tests/task.json b/tasks/euclidean-ramsey-nine/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d12ee9098e7946838eb5175613e56c27fb15839a --- /dev/null +++ b/tasks/euclidean-ramsey-nine/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamseyNine", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.NineStatement.nine_circle_configuration" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10869 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-nine/tests/test.sh b/tasks/euclidean-ramsey-nine/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey-nine/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey-quadratic/environment/Dockerfile b/tasks/euclidean-ramsey-quadratic/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey-quadratic/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey-quadratic/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey-quadratic/environment/lake-manifest.json b/tasks/euclidean-ramsey-quadratic/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-quadratic/environment/lakefile.lean b/tasks/euclidean-ramsey-quadratic/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey-quadratic/environment/lean_setup.sh b/tasks/euclidean-ramsey-quadratic/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey-quadratic/environment/pack_submission.py b/tasks/euclidean-ramsey-quadratic/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey-quadratic/instruction.md b/tasks/euclidean-ramsey-quadratic/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..306d411ef68b5c02b57d120c8760730dc2fbd580 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `EuclideanRamseyQuadratic` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamseyQuadratic`, also at `/opt/openai-math/challenges/EuclideanRamseyQuadratic.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +def coordinateField {s d : ℕ} (a : Fin s → Space d) : IntermediateField ℚ ℝ := + IntermediateField.adjoin ℚ (Set.range (fun ij : Fin s × Fin d => a ij.1 ij.2)) + +abbrev Coeff {s d : ℕ} (a : Fin s → Space d) := ↥(coordinateField a) + +def coordinate {s d : ℕ} (a : Fin s → Space d) (i : Fin s) (j : Fin d) : Coeff a := + ⟨a i j, IntermediateField.subset_adjoin ℚ _ (Set.mem_range_self (i, j))⟩ + +def augmented {s d : ℕ} (a : Fin s → Space d) (i : Fin s) : Option (Fin d) → Coeff a + | none => 1 + | some j => coordinate a i j + +theorem spherical_quadraticIndependent_ramsey_all {s d : ℕ} + (a : Fin s → Space d) (ha : Function.Injective a) + (hspan : affineSpan ℝ (Set.range a) = ⊤) + (hsphere : ∃ c : Space d, ∃ r : ℝ, ∀ i, dist (a i) c = r) + (hrows : LinearIndependent (Coeff a) + (fun i : Fin s => fun q : Option (Fin d) × Option (Fin d) => + augmented a i q.1 * augmented a i q.2)) : Ramsey a := by + sorry + +end EuclideanRamsey + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamseyQuadratic.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.spherical_quadraticIndependent_ramsey_all` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey-quadratic/solution/closure.txt b/tasks/euclidean-ramsey-quadratic/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c97ac524a1754cfdffab1c64c9ca899345ebe43e --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/solution/closure.txt @@ -0,0 +1,29 @@ +OAI.Combinatorics.EuclideanRamsey.AdicLifting +OAI.Combinatorics.EuclideanRamsey.ColoringCompactness +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.CornerGroup +OAI.Combinatorics.EuclideanRamsey.CorrectionPaths +OAI.Combinatorics.EuclideanRamsey.DerivedFractions +OAI.Combinatorics.EuclideanRamsey.DifferentialSplitting +OAI.Combinatorics.EuclideanRamsey.Discretization +OAI.Combinatorics.EuclideanRamsey.FiniteEuclidean +OAI.Combinatorics.EuclideanRamsey.GramCompletion +OAI.Combinatorics.EuclideanRamsey.Hessian +OAI.Combinatorics.EuclideanRamsey.LatticeMoments +OAI.Combinatorics.EuclideanRamsey.Main +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.NormalCost +OAI.Combinatorics.EuclideanRamsey.OrbitAveraging +OAI.Combinatorics.EuclideanRamsey.PathFractions +OAI.Combinatorics.EuclideanRamsey.PathSynchronization +OAI.Combinatorics.EuclideanRamsey.PathWords +OAI.Combinatorics.EuclideanRamsey.Quadratic +OAI.Combinatorics.EuclideanRamsey.RationalConvolution +OAI.Combinatorics.EuclideanRamsey.SignedRows +OAI.Combinatorics.EuclideanRamsey.SmoothingKernel +OAI.Combinatorics.EuclideanRamsey.SmoothingMatrix +OAI.Combinatorics.EuclideanRamsey.StencilConvolution +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity +OAI.Combinatorics.EuclideanRamsey.TensorPresentation +OAI.Combinatorics.EuclideanRamsey.UltrafilterStrings diff --git a/tasks/euclidean-ramsey-quadratic/solution/reference.py b/tasks/euclidean-ramsey-quadratic/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey-quadratic/solution/solve.sh b/tasks/euclidean-ramsey-quadratic/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..84e2b7a44bfb8a6182b7031d462e9d0dad7f1e84 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamseyQuadratic, i.e. module OAI.Combinatorics.EuclideanRamsey.Quadratic and the +# 29 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.Quadratic /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamseyQuadratic" diff --git a/tasks/euclidean-ramsey-quadratic/task.toml b/tasks/euclidean-ramsey-quadratic/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..56f6ce96d4361059050805a073f41177bee4dc66 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey-quadratic" +version = "1.0.0" +description = "Prove EuclideanRamseyQuadratic (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamseyQuadratic.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamseyQuadratic" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.spherical_quadraticIndependent_ramsey_all"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.Quadratic" +reference_modules = 29 +reference_lean_bytes = 299442 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 672 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11969 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey-quadratic/tests/Challenge.lean b/tasks/euclidean-ramsey-quadratic/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7d4abb76107da15f8d61efceca01cb0f83bfab8a --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +def coordinateField {s d : ℕ} (a : Fin s → Space d) : IntermediateField ℚ ℝ := + IntermediateField.adjoin ℚ (Set.range (fun ij : Fin s × Fin d => a ij.1 ij.2)) + +abbrev Coeff {s d : ℕ} (a : Fin s → Space d) := ↥(coordinateField a) + +def coordinate {s d : ℕ} (a : Fin s → Space d) (i : Fin s) (j : Fin d) : Coeff a := + ⟨a i j, IntermediateField.subset_adjoin ℚ _ (Set.mem_range_self (i, j))⟩ + +def augmented {s d : ℕ} (a : Fin s → Space d) (i : Fin s) : Option (Fin d) → Coeff a + | none => 1 + | some j => coordinate a i j + +theorem spherical_quadraticIndependent_ramsey_all {s d : ℕ} + (a : Fin s → Space d) (ha : Function.Injective a) + (hspan : affineSpan ℝ (Set.range a) = ⊤) + (hsphere : ∃ c : Space d, ∃ r : ℝ, ∀ i, dist (a i) c = r) + (hrows : LinearIndependent (Coeff a) + (fun i : Fin s => fun q : Option (Fin d) × Option (Fin d) => + augmented a i q.1 * augmented a i q.2)) : Ramsey a := by + sorry + +end EuclideanRamsey + +end + +end OAI diff --git a/tasks/euclidean-ramsey-quadratic/tests/grade.py b/tasks/euclidean-ramsey-quadratic/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey-quadratic/tests/task.json b/tasks/euclidean-ramsey-quadratic/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..71d92f5c9008104e66022cd45e61d3133f74bfea --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamseyQuadratic", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.spherical_quadraticIndependent_ramsey_all" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11069 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-quadratic/tests/test.sh b/tasks/euclidean-ramsey-quadratic/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey-quadratic/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey-spherical/environment/Dockerfile b/tasks/euclidean-ramsey-spherical/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey-spherical/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey-spherical/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey-spherical/environment/lake-manifest.json b/tasks/euclidean-ramsey-spherical/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-spherical/environment/lakefile.lean b/tasks/euclidean-ramsey-spherical/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey-spherical/environment/lean_setup.sh b/tasks/euclidean-ramsey-spherical/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey-spherical/environment/pack_submission.py b/tasks/euclidean-ramsey-spherical/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey-spherical/instruction.md b/tasks/euclidean-ramsey-spherical/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b39ab10ba89b364b51d407814411bd1f4a07da42 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/instruction.md @@ -0,0 +1,79 @@ +# openai/math challenge `EuclideanRamseySpherical` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamseySpherical`, also at `/opt/openai-math/challenges/EuclideanRamseySpherical.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped TensorProduct +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +theorem ramsey_cospherical {s d : ℕ} (a : Fin s → Space d) + (ha : Function.Injective a) (hR : Ramsey a) : + EuclideanGeometry.Cospherical (Set.range a) := by + sorry + +end EuclideanRamsey + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamseySpherical.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.ramsey_cospherical` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey-spherical/solution/closure.txt b/tasks/euclidean-ramsey-spherical/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..35da7a6087496c0da71bc203186ac98af2e12a3f --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Combinatorics.EuclideanRamsey.AdicLifting +OAI.Combinatorics.EuclideanRamsey.ColoringCompactness +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.CornerGroup +OAI.Combinatorics.EuclideanRamsey.CorrectionPaths +OAI.Combinatorics.EuclideanRamsey.DerivedFractions +OAI.Combinatorics.EuclideanRamsey.DifferentialSplitting +OAI.Combinatorics.EuclideanRamsey.Discretization +OAI.Combinatorics.EuclideanRamsey.FiniteEuclidean +OAI.Combinatorics.EuclideanRamsey.GramCompletion +OAI.Combinatorics.EuclideanRamsey.Hessian +OAI.Combinatorics.EuclideanRamsey.LatticeMoments +OAI.Combinatorics.EuclideanRamsey.Main +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.NormalCost +OAI.Combinatorics.EuclideanRamsey.OrbitAveraging +OAI.Combinatorics.EuclideanRamsey.PathFractions +OAI.Combinatorics.EuclideanRamsey.PathSynchronization +OAI.Combinatorics.EuclideanRamsey.PathWords +OAI.Combinatorics.EuclideanRamsey.RationalConvolution +OAI.Combinatorics.EuclideanRamsey.SignedRows +OAI.Combinatorics.EuclideanRamsey.SmoothingKernel +OAI.Combinatorics.EuclideanRamsey.SmoothingMatrix +OAI.Combinatorics.EuclideanRamsey.SphereTransport +OAI.Combinatorics.EuclideanRamsey.Spherical +OAI.Combinatorics.EuclideanRamsey.StencilConvolution +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity +OAI.Combinatorics.EuclideanRamsey.TensorPresentation +OAI.Combinatorics.EuclideanRamsey.TensorSphere +OAI.Combinatorics.EuclideanRamsey.UltrafilterStrings diff --git a/tasks/euclidean-ramsey-spherical/solution/reference.py b/tasks/euclidean-ramsey-spherical/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey-spherical/solution/solve.sh b/tasks/euclidean-ramsey-spherical/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e7841c159b6afc2546d7f679faded246eef3a6c0 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamseySpherical, i.e. module OAI.Combinatorics.EuclideanRamsey.Spherical and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.Spherical /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamseySpherical" diff --git a/tasks/euclidean-ramsey-spherical/task.toml b/tasks/euclidean-ramsey-spherical/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d4fef6dc2717bfc9bb58642ab93fc52cf84d1942 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey-spherical" +version = "1.0.0" +description = "Prove EuclideanRamseySpherical (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamseySpherical.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamseySpherical" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.ramsey_cospherical"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.Spherical" +reference_modules = 31 +reference_lean_bytes = 294907 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 735 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11965 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey-spherical/tests/Challenge.lean b/tasks/euclidean-ramsey-spherical/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3b2fc8ae2aece6108641d078b69eb98124798072 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/tests/Challenge.lean @@ -0,0 +1,28 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped TensorProduct +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +theorem ramsey_cospherical {s d : ℕ} (a : Fin s → Space d) + (ha : Function.Injective a) (hR : Ramsey a) : + EuclideanGeometry.Cospherical (Set.range a) := by + sorry + +end EuclideanRamsey + +end + +end OAI diff --git a/tasks/euclidean-ramsey-spherical/tests/grade.py b/tasks/euclidean-ramsey-spherical/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey-spherical/tests/task.json b/tasks/euclidean-ramsey-spherical/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1c2b1ccf0ab38e296f542c8d39b2d175c29a1f1e --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamseySpherical", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.ramsey_cospherical" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11065 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-spherical/tests/test.sh b/tasks/euclidean-ramsey-spherical/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey-spherical/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey-transitive/environment/Dockerfile b/tasks/euclidean-ramsey-transitive/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey-transitive/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey-transitive/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey-transitive/environment/lake-manifest.json b/tasks/euclidean-ramsey-transitive/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-transitive/environment/lakefile.lean b/tasks/euclidean-ramsey-transitive/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey-transitive/environment/lean_setup.sh b/tasks/euclidean-ramsey-transitive/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey-transitive/environment/pack_submission.py b/tasks/euclidean-ramsey-transitive/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey-transitive/instruction.md b/tasks/euclidean-ramsey-transitive/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba9d7685ee68452029793478402241842e8b4e53 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/instruction.md @@ -0,0 +1,81 @@ +# openai/math challenge `EuclideanRamseyTransitive` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamseyTransitive`, also at `/opt/openai-math/challenges/EuclideanRamseyTransitive.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace TransitiveConsequence + +theorem subset_of_finite_transitive_ramsey {s t D : ℕ} + (a : Fin s → Space D) (y : Fin t → Space D) + (hs : 0 < s) (ha : Function.Injective a) (_hy : Function.Injective y) + (htrans : ∀ i j : Fin t, ∃ σ : Equiv.Perm (Fin t), + (∀ k l : Fin t, dist (y (σ k)) (y (σ l)) = dist (y k) (y l)) ∧ σ i = j) + (hsub : Set.range a ⊆ Set.range y) : Ramsey a := by + sorry + +end TransitiveConsequence +end EuclideanRamsey + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamseyTransitive.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.TransitiveConsequence.subset_of_finite_transitive_ramsey` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey-transitive/solution/closure.txt b/tasks/euclidean-ramsey-transitive/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..15ec0f0bda6d828574f9e25cee34d0d0aa45e79b --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/solution/closure.txt @@ -0,0 +1,29 @@ +OAI.Combinatorics.EuclideanRamsey.AdicLifting +OAI.Combinatorics.EuclideanRamsey.ColoringCompactness +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.CornerGroup +OAI.Combinatorics.EuclideanRamsey.CorrectionPaths +OAI.Combinatorics.EuclideanRamsey.DerivedFractions +OAI.Combinatorics.EuclideanRamsey.DifferentialSplitting +OAI.Combinatorics.EuclideanRamsey.Discretization +OAI.Combinatorics.EuclideanRamsey.FiniteEuclidean +OAI.Combinatorics.EuclideanRamsey.GramCompletion +OAI.Combinatorics.EuclideanRamsey.Hessian +OAI.Combinatorics.EuclideanRamsey.LatticeMoments +OAI.Combinatorics.EuclideanRamsey.Main +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.NormalCost +OAI.Combinatorics.EuclideanRamsey.OrbitAveraging +OAI.Combinatorics.EuclideanRamsey.PathFractions +OAI.Combinatorics.EuclideanRamsey.PathSynchronization +OAI.Combinatorics.EuclideanRamsey.PathWords +OAI.Combinatorics.EuclideanRamsey.RationalConvolution +OAI.Combinatorics.EuclideanRamsey.SignedRows +OAI.Combinatorics.EuclideanRamsey.SmoothingKernel +OAI.Combinatorics.EuclideanRamsey.SmoothingMatrix +OAI.Combinatorics.EuclideanRamsey.StencilConvolution +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity +OAI.Combinatorics.EuclideanRamsey.TensorPresentation +OAI.Combinatorics.EuclideanRamsey.Transitive +OAI.Combinatorics.EuclideanRamsey.UltrafilterStrings diff --git a/tasks/euclidean-ramsey-transitive/solution/reference.py b/tasks/euclidean-ramsey-transitive/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey-transitive/solution/solve.sh b/tasks/euclidean-ramsey-transitive/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2a528dcc87614253789fcbd10a29dd210db9c91e --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamseyTransitive, i.e. module OAI.Combinatorics.EuclideanRamsey.Transitive and the +# 29 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.Transitive /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamseyTransitive" diff --git a/tasks/euclidean-ramsey-transitive/task.toml b/tasks/euclidean-ramsey-transitive/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e09612426b51bcec03904416e6973fc2cb5ae760 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey-transitive" +version = "1.0.0" +description = "Prove EuclideanRamseyTransitive (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamseyTransitive.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamseyTransitive" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.TransitiveConsequence.subset_of_finite_transitive_ramsey"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.Transitive" +reference_modules = 29 +reference_lean_bytes = 294470 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1235 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11965 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey-transitive/tests/Challenge.lean b/tasks/euclidean-ramsey-transitive/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a3e0ea5a431606ddf5b8a5b49448878fc2716fcf --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/tests/Challenge.lean @@ -0,0 +1,30 @@ +import Mathlib + +namespace OAI + +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +namespace TransitiveConsequence + +theorem subset_of_finite_transitive_ramsey {s t D : ℕ} + (a : Fin s → Space D) (y : Fin t → Space D) + (hs : 0 < s) (ha : Function.Injective a) (_hy : Function.Injective y) + (htrans : ∀ i j : Fin t, ∃ σ : Equiv.Perm (Fin t), + (∀ k l : Fin t, dist (y (σ k)) (y (σ l)) = dist (y k) (y l)) ∧ σ i = j) + (hsub : Set.range a ⊆ Set.range y) : Ramsey a := by + sorry + +end TransitiveConsequence +end EuclideanRamsey + +end OAI diff --git a/tasks/euclidean-ramsey-transitive/tests/grade.py b/tasks/euclidean-ramsey-transitive/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey-transitive/tests/task.json b/tasks/euclidean-ramsey-transitive/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..903a8a14b12867bf22c331e3f083847aaf67155a --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamseyTransitive", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.TransitiveConsequence.subset_of_finite_transitive_ramsey" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11065 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey-transitive/tests/test.sh b/tasks/euclidean-ramsey-transitive/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey-transitive/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/euclidean-ramsey/environment/Dockerfile b/tasks/euclidean-ramsey/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/euclidean-ramsey/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/euclidean-ramsey/environment/fetch_mathlib.sh b/tasks/euclidean-ramsey/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/euclidean-ramsey/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/euclidean-ramsey/environment/lake-manifest.json b/tasks/euclidean-ramsey/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/euclidean-ramsey/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey/environment/lakefile.lean b/tasks/euclidean-ramsey/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/euclidean-ramsey/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/euclidean-ramsey/environment/lean_setup.sh b/tasks/euclidean-ramsey/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/euclidean-ramsey/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/euclidean-ramsey/environment/pack_submission.py b/tasks/euclidean-ramsey/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/euclidean-ramsey/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/euclidean-ramsey/instruction.md b/tasks/euclidean-ramsey/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ebea6c20b496e60f4af51965d74010ff0ea19852 --- /dev/null +++ b/tasks/euclidean-ramsey/instruction.md @@ -0,0 +1,103 @@ +# openai/math challenge `EuclideanRamsey` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `EuclideanRamsey`, also at `/opt/openai-math/challenges/EuclideanRamsey.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped TensorProduct +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +def coordinateField {s d : ℕ} (a : Fin s → Space d) : IntermediateField ℚ ℝ := + IntermediateField.adjoin ℚ (Set.range (fun ij : Fin s × Fin d => a ij.1 ij.2)) + +abbrev Coeff {s d : ℕ} (a : Fin s → Space d) := ↥(coordinateField a) +abbrev TensorRing {s d : ℕ} (a : Fin s → Space d) := Coeff a ⊗[ℚ] Coeff a + +def coordinate {s d : ℕ} (a : Fin s → Space d) (i : Fin s) (j : Fin d) : Coeff a := + ⟨a i j, IntermediateField.subset_adjoin ℚ _ (Set.mem_range_self (i, j))⟩ + +def augmented {s d : ℕ} (a : Fin s → Space d) (i : Fin s) : Option (Fin d) → Coeff a + | none => 1 + | some j => coordinate a i j + +def multiply {s d : ℕ} (a : Fin s → Space d) : TensorRing a →ₐ[ℚ] Coeff a := + Algebra.TensorProduct.lmul' ℚ + +def FieldCriterion {s d : ℕ} (a : Fin s → Space d) : Prop := + ∃ P : Matrix (Option (Fin d)) (Option (Fin d)) (TensorRing a), + (∀ i : Fin s, ∑ α, ∑ β, + ((augmented a i α) ⊗ₜ[ℚ] (1 : Coeff a)) * P α β * + ((1 : Coeff a) ⊗ₜ[ℚ] (augmented a i β)) = 0) ∧ + (∀ α β : Fin d, multiply a (P (some α) (some β)) = if α = β then 1 else 0) + +theorem classification {s d : ℕ} (a : Fin s → Space d) + (hs : 2 ≤ s) (hd : 1 ≤ d) (ha : Function.Injective a) + (hspan : affineSpan ℝ (Set.range a) = ⊤) : + Ramsey a ↔ FieldCriterion a := by + sorry + +end EuclideanRamsey + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EuclideanRamsey.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanRamsey.classification` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/euclidean-ramsey/solution/closure.txt b/tasks/euclidean-ramsey/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..eb4efa2d2193ec2baf9308fa5acca0c0d9d19635 --- /dev/null +++ b/tasks/euclidean-ramsey/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.Combinatorics.EuclideanRamsey.AdicLifting +OAI.Combinatorics.EuclideanRamsey.ColoringCompactness +OAI.Combinatorics.EuclideanRamsey.Congruence +OAI.Combinatorics.EuclideanRamsey.CornerGroup +OAI.Combinatorics.EuclideanRamsey.CorrectionPaths +OAI.Combinatorics.EuclideanRamsey.DerivedFractions +OAI.Combinatorics.EuclideanRamsey.DifferentialSplitting +OAI.Combinatorics.EuclideanRamsey.Discretization +OAI.Combinatorics.EuclideanRamsey.FiniteEuclidean +OAI.Combinatorics.EuclideanRamsey.GramCompletion +OAI.Combinatorics.EuclideanRamsey.Hessian +OAI.Combinatorics.EuclideanRamsey.LatticeMoments +OAI.Combinatorics.EuclideanRamsey.Main +OAI.Combinatorics.EuclideanRamsey.Model +OAI.Combinatorics.EuclideanRamsey.NormalCost +OAI.Combinatorics.EuclideanRamsey.OrbitAveraging +OAI.Combinatorics.EuclideanRamsey.PathFractions +OAI.Combinatorics.EuclideanRamsey.PathSynchronization +OAI.Combinatorics.EuclideanRamsey.PathWords +OAI.Combinatorics.EuclideanRamsey.RationalConvolution +OAI.Combinatorics.EuclideanRamsey.SignedRows +OAI.Combinatorics.EuclideanRamsey.SmoothingKernel +OAI.Combinatorics.EuclideanRamsey.SmoothingMatrix +OAI.Combinatorics.EuclideanRamsey.StencilConvolution +OAI.Combinatorics.EuclideanRamsey.TensorDescent +OAI.Combinatorics.EuclideanRamsey.TensorNecessity +OAI.Combinatorics.EuclideanRamsey.TensorPresentation +OAI.Combinatorics.EuclideanRamsey.UltrafilterStrings diff --git a/tasks/euclidean-ramsey/solution/reference.py b/tasks/euclidean-ramsey/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/euclidean-ramsey/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/euclidean-ramsey/solution/solve.sh b/tasks/euclidean-ramsey/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..08e51d7c5612dc20ef65b2e5ddeb74d478c828ec --- /dev/null +++ b/tasks/euclidean-ramsey/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EuclideanRamsey, i.e. module OAI.Combinatorics.EuclideanRamsey.Main and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.EuclideanRamsey.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EuclideanRamsey" diff --git a/tasks/euclidean-ramsey/task.toml b/tasks/euclidean-ramsey/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..45739b501b0e4915bc409796528679e1f3f2e8f5 --- /dev/null +++ b/tasks/euclidean-ramsey/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/euclidean-ramsey" +version = "1.0.0" +description = "Prove EuclideanRamsey (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EuclideanRamsey.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EuclideanRamsey" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.EuclideanRamsey.classification"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.EuclideanRamsey.Main" +reference_modules = 28 +reference_lean_bytes = 288245 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1062 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11959 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/euclidean-ramsey/tests/Challenge.lean b/tasks/euclidean-ramsey/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6268acd3bf3f2537607064aae93b425aed117b4c --- /dev/null +++ b/tasks/euclidean-ramsey/tests/Challenge.lean @@ -0,0 +1,52 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped TensorProduct +namespace EuclideanRamsey + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def Congruent {s d D : ℕ} (a : Fin s → Space d) (b : Fin s → Space D) : Prop := + ∀ i j, dist (b i) (b j) = dist (a i) (a j) + +def Ramsey {s d : ℕ} (a : Fin s → Space d) : Prop := + ∀ r : ℕ, 2 ≤ r → ∃ D : ℕ, 1 ≤ D ∧ + ∀ c : Space D → Fin r, ∃ b : Fin s → Space D, + Congruent a b ∧ ∃ k : Fin r, ∀ i, c (b i) = k + +def coordinateField {s d : ℕ} (a : Fin s → Space d) : IntermediateField ℚ ℝ := + IntermediateField.adjoin ℚ (Set.range (fun ij : Fin s × Fin d => a ij.1 ij.2)) + +abbrev Coeff {s d : ℕ} (a : Fin s → Space d) := ↥(coordinateField a) +abbrev TensorRing {s d : ℕ} (a : Fin s → Space d) := Coeff a ⊗[ℚ] Coeff a + +def coordinate {s d : ℕ} (a : Fin s → Space d) (i : Fin s) (j : Fin d) : Coeff a := + ⟨a i j, IntermediateField.subset_adjoin ℚ _ (Set.mem_range_self (i, j))⟩ + +def augmented {s d : ℕ} (a : Fin s → Space d) (i : Fin s) : Option (Fin d) → Coeff a + | none => 1 + | some j => coordinate a i j + +def multiply {s d : ℕ} (a : Fin s → Space d) : TensorRing a →ₐ[ℚ] Coeff a := + Algebra.TensorProduct.lmul' ℚ + +def FieldCriterion {s d : ℕ} (a : Fin s → Space d) : Prop := + ∃ P : Matrix (Option (Fin d)) (Option (Fin d)) (TensorRing a), + (∀ i : Fin s, ∑ α, ∑ β, + ((augmented a i α) ⊗ₜ[ℚ] (1 : Coeff a)) * P α β * + ((1 : Coeff a) ⊗ₜ[ℚ] (augmented a i β)) = 0) ∧ + (∀ α β : Fin d, multiply a (P (some α) (some β)) = if α = β then 1 else 0) + +theorem classification {s d : ℕ} (a : Fin s → Space d) + (hs : 2 ≤ s) (hd : 1 ≤ d) (ha : Function.Injective a) + (hspan : affineSpan ℝ (Set.range a) = ⊤) : + Ramsey a ↔ FieldCriterion a := by + sorry + +end EuclideanRamsey + +end + +end OAI diff --git a/tasks/euclidean-ramsey/tests/grade.py b/tasks/euclidean-ramsey/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/euclidean-ramsey/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/euclidean-ramsey/tests/task.json b/tasks/euclidean-ramsey/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b09885a6ad941ea6edc3da75449cc8b254c66a39 --- /dev/null +++ b/tasks/euclidean-ramsey/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EuclideanRamsey", + "comparator": { + "theorem_names": [ + "OAI.EuclideanRamsey.classification" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11059 +} \ No newline at end of file diff --git a/tasks/euclidean-ramsey/tests/test.sh b/tasks/euclidean-ramsey/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/euclidean-ramsey/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/even-barker/environment/Dockerfile b/tasks/even-barker/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/even-barker/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/even-barker/environment/fetch_mathlib.sh b/tasks/even-barker/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/even-barker/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/even-barker/environment/lake-manifest.json b/tasks/even-barker/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/even-barker/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/even-barker/environment/lakefile.lean b/tasks/even-barker/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/even-barker/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/even-barker/environment/lean_setup.sh b/tasks/even-barker/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/even-barker/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/even-barker/environment/pack_submission.py b/tasks/even-barker/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/even-barker/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/even-barker/instruction.md b/tasks/even-barker/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1cb4882c2cfaf9e457c32962503e5f91e5e8bad0 --- /dev/null +++ b/tasks/even-barker/instruction.md @@ -0,0 +1,79 @@ +# openai/math challenge `EvenBarker` (family 179) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 179 of the release, *The circulant Hadamard conjecture* +(Combinatorics). The family as a whole: Proves that real circulant Hadamard matrices exist exactly in orders $1$ and $4$, resolving the circulant Hadamard conjecture. Together with classical Barker-sequence results, this shows that binary sequences whose nontrivial aperiodic autocorrelations have magnitude at most $1$ exist at lengths $n>1$ exactly when $n\in\{2,3,4,5,7,11,13\}$. + +The challenge is `EvenBarker`, also at `/opt/openai-math/challenges/EvenBarker.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CirculantHadamard + +universe u + +def IsSign {R : Type u} [One R] [Neg R] (x : R) : Prop := + x = 1 ∨ x = -1 + +namespace Barker +open scoped BigOperators + +def aperiodic {n : ℕ} (h : Fin n → ℤ) (k : ℕ) : ℤ := + ∑ j : Fin (n - k), h ⟨j.val, by omega⟩ * h ⟨j.val + k, by omega⟩ + +def IsBarker {n : ℕ} (h : Fin n → ℤ) : Prop := + (∀ j, IsSign (h j)) ∧ ∀ k : ℕ, 0 < k → k < n → |aperiodic h k| ≤ 1 + +theorem even_length_eq_two_or_four {n : ℕ} (h : Fin n → ℤ) + (hnpos : 0 < n) (hn : Even n) (hb : IsBarker h) : n = 2 ∨ n = 4 := by + sorry + +end Barker +end CirculantHadamard + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/EvenBarker.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CirculantHadamard.Barker.even_length_eq_two_or_four` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/even-barker/solution/closure.txt b/tasks/even-barker/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..43917166d6b4fcfbd0c9396469423b3e2215db53 --- /dev/null +++ b/tasks/even-barker/solution/closure.txt @@ -0,0 +1,73 @@ +OAI.LinearAlgebra.Barker.Main +OAI.LinearAlgebra.Barker.Model +OAI.LinearAlgebra.Barker.Parity +OAI.LinearAlgebra.Barker.PeriodicModFour +OAI.LinearAlgebra.Barker.Wraparound +OAI.LinearAlgebra.CirculantHadamard.AlternatingField +OAI.LinearAlgebra.CirculantHadamard.AlternatingLocalization +OAI.LinearAlgebra.CirculantHadamard.AlternatingNorm +OAI.LinearAlgebra.CirculantHadamard.AlternatingProducts +OAI.LinearAlgebra.CirculantHadamard.AlternatingTorsion +OAI.LinearAlgebra.CirculantHadamard.Basic +OAI.LinearAlgebra.CirculantHadamard.BinaryBlocks +OAI.LinearAlgebra.CirculantHadamard.BinaryCharacterSum +OAI.LinearAlgebra.CirculantHadamard.BinaryCoefficients +OAI.LinearAlgebra.CirculantHadamard.BinaryContradiction +OAI.LinearAlgebra.CirculantHadamard.BinaryEvaluation +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalFamily +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalRing +OAI.LinearAlgebra.CirculantHadamard.BinaryLocalization +OAI.LinearAlgebra.CirculantHadamard.BinaryNorms +OAI.LinearAlgebra.CirculantHadamard.BinaryProductTransport +OAI.LinearAlgebra.CirculantHadamard.BinaryResidue +OAI.LinearAlgebra.CirculantHadamard.CoefficientEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluationAt +OAI.LinearAlgebra.CirculantHadamard.CyclicEvaluationProjection +OAI.LinearAlgebra.CirculantHadamard.CyclicNorm +OAI.LinearAlgebra.CirculantHadamard.CyclicPolynomial +OAI.LinearAlgebra.CirculantHadamard.CyclicProjection +OAI.LinearAlgebra.CirculantHadamard.CyclicProjectionPolynomial +OAI.LinearAlgebra.CirculantHadamard.CyclicRing +OAI.LinearAlgebra.CirculantHadamard.CyclicScalarDivision +OAI.LinearAlgebra.CirculantHadamard.CyclotomicAdjoin +OAI.LinearAlgebra.CirculantHadamard.CyclotomicAwayLocal +OAI.LinearAlgebra.CirculantHadamard.CyclotomicFactorDivision +OAI.LinearAlgebra.CirculantHadamard.CyclotomicIntegerEvaluation +OAI.LinearAlgebra.CirculantHadamard.CyclotomicLocalBase +OAI.LinearAlgebra.CirculantHadamard.CyclotomicProjection +OAI.LinearAlgebra.CirculantHadamard.CyclotomicRemainder +OAI.LinearAlgebra.CirculantHadamard.CyclotomicRings +OAI.LinearAlgebra.CirculantHadamard.CyclotomicTorsion +OAI.LinearAlgebra.CirculantHadamard.DyadicRemainder +OAI.LinearAlgebra.CirculantHadamard.FirstOrderResidue +OAI.LinearAlgebra.CirculantHadamard.IntegerLocalDivisibility +OAI.LinearAlgebra.CirculantHadamard.IntegerTwoLocal +OAI.LinearAlgebra.CirculantHadamard.Kronecker +OAI.LinearAlgebra.CirculantHadamard.LocalComparison +OAI.LinearAlgebra.CirculantHadamard.LocalComparisonInduction +OAI.LinearAlgebra.CirculantHadamard.LocalDVR +OAI.LinearAlgebra.CirculantHadamard.LocalizationIntersection +OAI.LinearAlgebra.CirculantHadamard.LocalizationMaps +OAI.LinearAlgebra.CirculantHadamard.Main +OAI.LinearAlgebra.CirculantHadamard.MatrixBridge +OAI.LinearAlgebra.CirculantHadamard.ModEight +OAI.LinearAlgebra.CirculantHadamard.Model +OAI.LinearAlgebra.CirculantHadamard.OrderCyclotomicDivisibility +OAI.LinearAlgebra.CirculantHadamard.OrderDescent +OAI.LinearAlgebra.CirculantHadamard.OrderHalving +OAI.LinearAlgebra.CirculantHadamard.OrderProjection +OAI.LinearAlgebra.CirculantHadamard.OrderReduction +OAI.LinearAlgebra.CirculantHadamard.OrderSquareEven +OAI.LinearAlgebra.CirculantHadamard.PrimeCharacterEvaluations +OAI.LinearAlgebra.CirculantHadamard.PrimeComponents +OAI.LinearAlgebra.CirculantHadamard.ProjectionCoefficients +OAI.LinearAlgebra.CirculantHadamard.ProjectionPairFiber +OAI.LinearAlgebra.CirculantHadamard.RamifiedConjugation +OAI.LinearAlgebra.CirculantHadamard.RamifiedEisenstein +OAI.LinearAlgebra.CirculantHadamard.RamifiedLocal +OAI.LinearAlgebra.CirculantHadamard.RamifiedUnit +OAI.LinearAlgebra.CirculantHadamard.ResidueOneAssociation +OAI.LinearAlgebra.CirculantHadamard.ResidueTorsion +OAI.LinearAlgebra.CirculantHadamard.TwoAdicDecomposition +OAI.LinearAlgebra.CirculantHadamard.Witnesses diff --git a/tasks/even-barker/solution/reference.py b/tasks/even-barker/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/even-barker/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/even-barker/solution/solve.sh b/tasks/even-barker/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d3a56fc77ff8fdbfcff44aa54df02843835ae0e --- /dev/null +++ b/tasks/even-barker/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of EvenBarker, i.e. module OAI.LinearAlgebra.Barker.Main and the +# 73 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.LinearAlgebra.Barker.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of EvenBarker" diff --git a/tasks/even-barker/task.toml b/tasks/even-barker/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..92b1e64add366a00725bf468becd57cf86d10a46 --- /dev/null +++ b/tasks/even-barker/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/even-barker" +version = "1.0.0" +description = "Prove EvenBarker (openai/math family 179: The circulant Hadamard conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/EvenBarker.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "EvenBarker" +family = "179" +family_title = "The circulant Hadamard conjecture" +subject = "Combinatorics" +theorems = ["OAI.CirculantHadamard.Barker.even_length_eq_two_or_four"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.LinearAlgebra.Barker.Main" +reference_modules = 73 +reference_lean_bytes = 410340 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 743 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12069 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/even-barker/tests/Challenge.lean b/tasks/even-barker/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5d8e430bfdd67e6b14800193c65830fc3a18bf43 --- /dev/null +++ b/tasks/even-barker/tests/Challenge.lean @@ -0,0 +1,28 @@ +import Mathlib + +namespace OAI + +namespace CirculantHadamard + +universe u + +def IsSign {R : Type u} [One R] [Neg R] (x : R) : Prop := + x = 1 ∨ x = -1 + +namespace Barker +open scoped BigOperators + +def aperiodic {n : ℕ} (h : Fin n → ℤ) (k : ℕ) : ℤ := + ∑ j : Fin (n - k), h ⟨j.val, by omega⟩ * h ⟨j.val + k, by omega⟩ + +def IsBarker {n : ℕ} (h : Fin n → ℤ) : Prop := + (∀ j, IsSign (h j)) ∧ ∀ k : ℕ, 0 < k → k < n → |aperiodic h k| ≤ 1 + +theorem even_length_eq_two_or_four {n : ℕ} (h : Fin n → ℤ) + (hnpos : 0 < n) (hn : Even n) (hb : IsBarker h) : n = 2 ∨ n = 4 := by + sorry + +end Barker +end CirculantHadamard + +end OAI diff --git a/tasks/even-barker/tests/grade.py b/tasks/even-barker/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/even-barker/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/even-barker/tests/task.json b/tasks/even-barker/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..499c90c97e7bb05828b3e209a8e1545115098cdf --- /dev/null +++ b/tasks/even-barker/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "EvenBarker", + "comparator": { + "theorem_names": [ + "OAI.CirculantHadamard.Barker.even_length_eq_two_or_four" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11169 +} \ No newline at end of file diff --git a/tasks/even-barker/tests/test.sh b/tasks/even-barker/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/even-barker/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/exact-fourier/environment/Dockerfile b/tasks/exact-fourier/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/exact-fourier/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/exact-fourier/environment/fetch_mathlib.sh b/tasks/exact-fourier/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/exact-fourier/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/exact-fourier/environment/lake-manifest.json b/tasks/exact-fourier/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/exact-fourier/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/exact-fourier/environment/lakefile.lean b/tasks/exact-fourier/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/exact-fourier/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/exact-fourier/environment/lean_setup.sh b/tasks/exact-fourier/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/exact-fourier/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/exact-fourier/environment/pack_submission.py b/tasks/exact-fourier/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/exact-fourier/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/exact-fourier/instruction.md b/tasks/exact-fourier/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2feae0f4dfc3fd022f96c81391ceef980c77a5c8 --- /dev/null +++ b/tasks/exact-fourier/instruction.md @@ -0,0 +1,113 @@ +# openai/math challenge `ExactFourier` (family 130) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 130 of the release, *Fourier transforms below $n\log n$* +(Theoretical computer science). The family as a whole: Gives a deterministic length-$n$ discrete Fourier transform algorithm using $O(n(\log n)^{1-\delta})$ operations for every $n$, with explicit $\delta=10^{-13}$. The model uses exact complex arithmetic, unrestricted coefficients and a supplied root of unity, and counts scalar preparation and logarithmic-word indexing. + +The challenge is `ExactFourier`, also at `/opt/openai-math/challenges/ExactFourier.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Scalar circuits for exact discrete Fourier transforms. +No bounds on predetermined complex coefficients, reuse, storage, or conditioning. +-/ + +namespace ExactFourier + +/-- One charged scalar gate, referencing only available values. -/ +inductive Gate (w : ℕ) where + | add (i j : Fin w) + | sub (i j : Fin w) + | scale (c : ℂ) (i : Fin w) + +def Gate.eval {w : ℕ} (v : Fin w → ℂ) : Gate w → ℂ + | .add i j => v i + v j + | .sub i j => v i - v j + | .scale c i => c * v i + +/-- A topologically ordered scalar DAG; available values are never consumed. -/ +inductive Program (n : ℕ) : ℕ → Type where + | nil : Program n 0 + | step {k : ℕ} (p : Program n k) (g : Gate (n + 1 + k)) : Program n (k + 1) + +def Program.eval {n : ℕ} : {k : ℕ} → Program n k → (Fin n → ℂ) → + (Fin (n + 1 + k) → ℂ) + | 0, .nil, x => Fin.snoc x 0 + | _ + 1, .step p g, x => + let v := p.eval x + Fin.snoc v (g.eval v) + +/-- Outputs name available values, so permutations and arbitrary fanout are uncharged. -/ +structure Circuit (n : ℕ) where + size : ℕ + program : Program n size + outputs : Fin n → Fin (n + 1 + size) + +def Circuit.eval {n : ℕ} (C : Circuit n) (x : Fin n → ℂ) : Fin n → ℂ := + fun i => C.program.eval x (C.outputs i) + +noncomputable def zeta (n : ℕ) : ℂ := Complex.exp (2 * Real.pi * Complex.I / (n : ℂ)) +noncomputable def fourierMatrix (n : ℕ) : Matrix (Fin n) (Fin n) ℂ := + fun j k => zeta n ^ (j.val * k.val) + +def Circuit.Computes {n : ℕ} (C : Circuit n) (A : Matrix (Fin n) (Fin n) ℂ) : Prop := + ∀ x, C.eval x = A.mulVec x + +/-- The precise quantified formulation of source theorem `thm:main`. -/ +def MainStatement : Prop := + ∀ c : ℝ, 0 < c → ∀ N₀ : ℕ, 2 ≤ N₀ → ∃ n : ℕ, N₀ ≤ n ∧ + ∃ C : Circuit n, C.Computes (fourierMatrix n) ∧ + (C.size : ℝ) < c * (n : ℝ) * Real.logb 2 (n : ℝ) + +theorem main_theorem : MainStatement := by + sorry + +end ExactFourier + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ExactFourier.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ExactFourier.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/exact-fourier/solution/closure.txt b/tasks/exact-fourier/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8d7d4bc29abe9305196f194fc3d0b4c7fdaa26c2 --- /dev/null +++ b/tasks/exact-fourier/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Computability.FourierCircuit.AmplificationMaster +OAI.Computability.FourierCircuit.Boundary +OAI.Computability.FourierCircuit.BoundaryActiveCircuit +OAI.Computability.FourierCircuit.CascadeLimit +OAI.Computability.FourierCircuit.CascadeWord +OAI.Computability.FourierCircuit.CircuitCost +OAI.Computability.FourierCircuit.CircuitExtensions +OAI.Computability.FourierCircuit.ClearedCircuit +OAI.Computability.FourierCircuit.ComparisonRename +OAI.Computability.FourierCircuit.Core +OAI.Computability.FourierCircuit.DiagonalBlocks +OAI.Computability.FourierCircuit.DisplacementKernel +OAI.Computability.FourierCircuit.FFTCircuit +OAI.Computability.FourierCircuit.FiniteSeparation +OAI.Computability.FourierCircuit.GraphBlocks +OAI.Computability.FourierCircuit.InventoryValidity +OAI.Computability.FourierCircuit.LinearDAG +OAI.Computability.FourierCircuit.LiveSectors +OAI.Computability.FourierCircuit.Main +OAI.Computability.FourierCircuit.MatrixRelabel +OAI.Computability.FourierCircuit.MonomialFeedback +OAI.Computability.FourierCircuit.MonomialTools +OAI.Computability.FourierCircuit.MultiWord +OAI.Computability.FourierCircuit.PackedSchedule +OAI.Computability.FourierCircuit.PairFamilies +OAI.Computability.FourierCircuit.ParameterAlgebra +OAI.Computability.FourierCircuit.PiTensor +OAI.Computability.FourierCircuit.PivotAlgebra +OAI.Computability.FourierCircuit.PivotJoin +OAI.Computability.FourierCircuit.PolynomialClearing +OAI.Computability.FourierCircuit.PortMatrices +OAI.Computability.FourierCircuit.PositiveReach +OAI.Computability.FourierCircuit.Prices +OAI.Computability.FourierCircuit.RationalClearing +OAI.Computability.FourierCircuit.RawPositive +OAI.Computability.FourierCircuit.RawWordBound +OAI.Computability.FourierCircuit.RectStableAlgebra +OAI.Computability.FourierCircuit.Shears +OAI.Computability.FourierCircuit.SignedPrice +OAI.Computability.FourierCircuit.SlotAssembly +OAI.Computability.FourierCircuit.SparseShear +OAI.Computability.FourierCircuit.SparseSpectral +OAI.Computability.FourierCircuit.StreamSeries +OAI.Computability.FourierCircuit.SumFramed +OAI.Computability.FourierCircuit.SymmetricLaplacian +OAI.Computability.FourierCircuit.TensorCostAlgebra +OAI.Computability.FourierCircuit.TensorTools +OAI.Computability.FourierCircuit.ToeplitzCross +OAI.Computability.FourierCircuit.Triangular +OAI.Computability.FourierCircuit.WordScheduling +OAI.Computability.FourierCircuit.Words diff --git a/tasks/exact-fourier/solution/reference.py b/tasks/exact-fourier/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/exact-fourier/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/exact-fourier/solution/solve.sh b/tasks/exact-fourier/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6d78edee4083ca5669de6ba8051fd0e01934978f --- /dev/null +++ b/tasks/exact-fourier/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ExactFourier, i.e. module OAI.Computability.FourierCircuit.Main and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.FourierCircuit.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ExactFourier" diff --git a/tasks/exact-fourier/task.toml b/tasks/exact-fourier/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2b053aa6b76f179eac9e4780a379593c1f464820 --- /dev/null +++ b/tasks/exact-fourier/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/exact-fourier" +version = "1.0.0" +description = "Prove ExactFourier (openai/math family 130: Fourier transforms below $n\\log n$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ExactFourier.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ExactFourier" +family = "130" +family_title = "Fourier transforms below $n\\log n$" +subject = "Theoretical computer science" +theorems = ["OAI.ExactFourier.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.FourierCircuit.Main" +reference_modules = 51 +reference_lean_bytes = 848415 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 765 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12463 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/exact-fourier/tests/Challenge.lean b/tasks/exact-fourier/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..35b81d31dcf1a9b30d0e1511092be5b26f7989d9 --- /dev/null +++ b/tasks/exact-fourier/tests/Challenge.lean @@ -0,0 +1,62 @@ +import Mathlib + +namespace OAI + +/-! +Scalar circuits for exact discrete Fourier transforms. +No bounds on predetermined complex coefficients, reuse, storage, or conditioning. +-/ + +namespace ExactFourier + +/-- One charged scalar gate, referencing only available values. -/ +inductive Gate (w : ℕ) where + | add (i j : Fin w) + | sub (i j : Fin w) + | scale (c : ℂ) (i : Fin w) + +def Gate.eval {w : ℕ} (v : Fin w → ℂ) : Gate w → ℂ + | .add i j => v i + v j + | .sub i j => v i - v j + | .scale c i => c * v i + +/-- A topologically ordered scalar DAG; available values are never consumed. -/ +inductive Program (n : ℕ) : ℕ → Type where + | nil : Program n 0 + | step {k : ℕ} (p : Program n k) (g : Gate (n + 1 + k)) : Program n (k + 1) + +def Program.eval {n : ℕ} : {k : ℕ} → Program n k → (Fin n → ℂ) → + (Fin (n + 1 + k) → ℂ) + | 0, .nil, x => Fin.snoc x 0 + | _ + 1, .step p g, x => + let v := p.eval x + Fin.snoc v (g.eval v) + +/-- Outputs name available values, so permutations and arbitrary fanout are uncharged. -/ +structure Circuit (n : ℕ) where + size : ℕ + program : Program n size + outputs : Fin n → Fin (n + 1 + size) + +def Circuit.eval {n : ℕ} (C : Circuit n) (x : Fin n → ℂ) : Fin n → ℂ := + fun i => C.program.eval x (C.outputs i) + +noncomputable def zeta (n : ℕ) : ℂ := Complex.exp (2 * Real.pi * Complex.I / (n : ℂ)) +noncomputable def fourierMatrix (n : ℕ) : Matrix (Fin n) (Fin n) ℂ := + fun j k => zeta n ^ (j.val * k.val) + +def Circuit.Computes {n : ℕ} (C : Circuit n) (A : Matrix (Fin n) (Fin n) ℂ) : Prop := + ∀ x, C.eval x = A.mulVec x + +/-- The precise quantified formulation of source theorem `thm:main`. -/ +def MainStatement : Prop := + ∀ c : ℝ, 0 < c → ∀ N₀ : ℕ, 2 ≤ N₀ → ∃ n : ℕ, N₀ ≤ n ∧ + ∃ C : Circuit n, C.Computes (fourierMatrix n) ∧ + (C.size : ℝ) < c * (n : ℝ) * Real.logb 2 (n : ℝ) + +theorem main_theorem : MainStatement := by + sorry + +end ExactFourier + +end OAI diff --git a/tasks/exact-fourier/tests/grade.py b/tasks/exact-fourier/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/exact-fourier/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/exact-fourier/tests/task.json b/tasks/exact-fourier/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9b411bbc4a2533d430d903e81013a7a574f4e471 --- /dev/null +++ b/tasks/exact-fourier/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ExactFourier", + "comparator": { + "theorem_names": [ + "OAI.ExactFourier.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11563 +} \ No newline at end of file diff --git a/tasks/exact-fourier/tests/test.sh b/tasks/exact-fourier/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/exact-fourier/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/exact-infiniteness/environment/Dockerfile b/tasks/exact-infiniteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/exact-infiniteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/exact-infiniteness/environment/fetch_mathlib.sh b/tasks/exact-infiniteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/exact-infiniteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/exact-infiniteness/environment/lake-manifest.json b/tasks/exact-infiniteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/exact-infiniteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/exact-infiniteness/environment/lakefile.lean b/tasks/exact-infiniteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/exact-infiniteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/exact-infiniteness/environment/lean_setup.sh b/tasks/exact-infiniteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/exact-infiniteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/exact-infiniteness/environment/pack_submission.py b/tasks/exact-infiniteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/exact-infiniteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/exact-infiniteness/instruction.md b/tasks/exact-infiniteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b8cd34b6a9bec8034e86248f5afc0d1f8400daf1 --- /dev/null +++ b/tasks/exact-infiniteness/instruction.md @@ -0,0 +1,230 @@ +# openai/math challenge `ExactInfiniteness` (family 303) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 303 of the release, *From ordinary to strong pure infiniteness* +(Operator algebras). The family as a whole: Resolves the ordinary-to-strong pure-infiniteness question of Kirchberg and R{\o}rdam for complex $C^*$-algebras. For exact algebras, proper infiniteness of one fixed finite amplification of every positive element also suffices. Consequently, every separable nuclear algebra with this property absorbs $\mathcal O_\infty$, without unitality or simplicity assumptions. + +The challenge is `ExactInfiniteness`, also at `/opt/openai-math/challenges/ExactInfiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +universe u v +open scoped TensorProduct ENNReal ComplexOrder +open UniformSpace +namespace WeakPureInfiniteness + +section CompletedOperators + +variable {domain codomain : Type*} + [NormedAddCommGroup domain] [NormedSpace ℂ domain] + [NormedAddCommGroup codomain] [NormedSpace ℂ codomain] + +lemma norm_completion_le (operator : domain →L[ℂ] codomain) : + ‖operator.completion‖ ≤ ‖operator‖ := by + apply ContinuousLinearMap.opNorm_le_bound _ (norm_nonneg operator) + intro vector + induction vector using Completion.induction_on with + | hp => exact isClosed_le (by fun_prop) (by fun_prop) + | ih vector => simpa using operator.le_opNorm vector + +lemma norm_completion (operator : domain →L[ℂ] codomain) : + ‖operator.completion‖ = ‖operator‖ := by + apply le_antisymm (norm_completion_le operator) + apply ContinuousLinearMap.opNorm_le_bound _ (norm_nonneg _) + intro vector + simpa using operator.completion.le_opNorm (vector : Completion domain) + +end CompletedOperators + +structure ComplexHilbert where + Carrier : Type u + [normedAddCommGroup : NormedAddCommGroup Carrier] + [innerProductSpace : InnerProductSpace ℂ Carrier] + [completeSpace : CompleteSpace Carrier] + +attribute [instance] ComplexHilbert.normedAddCommGroup + ComplexHilbert.innerProductSpace ComplexHilbert.completeSpace +instance : CoeSort ComplexHilbert.{u} (Type u) := ⟨ComplexHilbert.Carrier⟩ + +instance completedTensorCStar (H K : ComplexHilbert.{u}) : + CStarAlgebra (Completion (H ⊗[ℂ] K) →L[ℂ] Completion (H ⊗[ℂ] K)) := inferInstance + +instance hilbertOperatorsCStar (H : ComplexHilbert.{u}) : + CStarAlgebra (H →L[ℂ] H) := inferInstance + +structure SpatialRepresentation (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] where + left : ComplexHilbert.{max u v} + right : ComplexHilbert.{max u v} + leftRep : A →⋆ₙₐ[ℂ] (left →L[ℂ] left) + rightRep : B →⋆ₙₐ[ℂ] (right →L[ℂ] right) + +abbrev SpatialRepresentation.hilbert {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (π : SpatialRepresentation A B) : ComplexHilbert.{max u v} where + Carrier := Completion (π.left ⊗[ℂ] π.right) + +abbrev SpatialRepresentation.space {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (π : SpatialRepresentation A B) := Completion (π.left ⊗[ℂ] π.right) + +def SpatialAmbient (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : Type (max u v + 1) := + lp (fun π : SpatialRepresentation A B => π.space →L[ℂ] π.space) ∞ + +instance spatialAmbientCStar (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalCStarAlgebra (SpatialAmbient A B) := by + unfold SpatialAmbient + infer_instance + +instance spatialAmbientCoeFun (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + CoeFun (SpatialAmbient A B) (fun _ => ∀ π : SpatialRepresentation A B, π.space →L[ℂ] π.space) := + ⟨fun z => z.val⟩ + +def spatialElementary {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (a : A) (b : B) : SpatialAmbient A B := + ⟨fun π => (TensorProduct.mapL (π.leftRep a) (π.rightRep b)).completion, + memℓp_infty ⟨‖a‖ * ‖b‖, by + rintro _ ⟨π, rfl⟩ + dsimp only + rw [norm_completion] + exact (TensorProduct.norm_mapL_le _ _).trans + (mul_le_mul (NonUnitalStarAlgHom.norm_apply_le π.leftRep a) (NonUnitalStarAlgHom.norm_apply_le π.rightRep b) + (norm_nonneg _) (norm_nonneg _))⟩⟩ + +def minimalTensorSubalgebra (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalStarSubalgebra ℂ (SpatialAmbient A B) := + (NonUnitalStarAlgebra.adjoin ℂ (Set.range fun p : A × B => spatialElementary p.1 p.2)).topologicalClosure + +abbrev MinimalTensor (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] := minimalTensorSubalgebra A B + +instance (A : Type u) (B : Type v) [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalCStarAlgebra (MinimalTensor A B) := by + letI : IsClosed ((minimalTensorSubalgebra A B : NonUnitalStarSubalgebra ℂ + (SpatialAmbient A B)) : Set (SpatialAmbient A B)) := + isClosed_closure + exact inferInstance + +section Exactness + +variable {A : Type u} {C D : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra C] [NonUnitalCStarAlgebra D] + +def SpatialRepresentation.precompRight (π : SpatialRepresentation A D) + (q : C →⋆ₙₐ[ℂ] D) : SpatialRepresentation A C where + left := π.left + right := π.right + leftRep := π.leftRep + rightRep := π.rightRep.comp q + +def tensorKernelIdeal (q : C →⋆ₙₐ[ℂ] D) : NonUnitalStarSubalgebra ℂ (SpatialAmbient A C) := + (NonUnitalStarAlgebra.adjoin ℂ + {z | ∃ a : A, ∃ c : C, q c = 0 ∧ z = spatialElementary a c}).topologicalClosure + +end Exactness + +def Exact (A : Type u) [NonUnitalCStarAlgebra A] : Prop := + ∀ (C D : Type u) [NonUnitalCStarAlgebra C] [NonUnitalCStarAlgebra D] + (q : C →⋆ₙₐ[ℂ] D), Function.Surjective q → + ∀ z : MinimalTensor A C, + (∀ π : SpatialRepresentation A D, (z.val : SpatialAmbient A C) (π.precompRight q) = 0) → + z.val ∈ tensorKernelIdeal (A := A) q + +section Definitions + +variable {A : Type*} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] +variable {m k : Type*} [Fintype m] [Fintype k] + +def CuntzSubequiv (a : CStarMatrix m m A) (b : CStarMatrix k k A) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ v : CStarMatrix k m A, ‖v.conjTranspose * b * v - a‖ < ε + +def blockSum (a : CStarMatrix m m A) (b : CStarMatrix k k A) : + CStarMatrix (m ⊕ k) (m ⊕ k) A := + CStarMatrix.ofMatrix (Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a) 0 0 + (CStarMatrix.ofMatrix.symm b)) + +def ProperlyInfinite (a : CStarMatrix m m A) : Prop := + CuntzSubequiv (blockSum a a) a + +def diagonalCopies (n : ℕ) (a : A) : CStarMatrix (Fin n) (Fin n) A := + CStarMatrix.ofMatrix (Matrix.diagonal fun _ => a) + +variable (A) + +def WeaklyPurelyInfinite : Prop := + ∃ n : ℕ, 1 ≤ n ∧ ∀ a : A, 0 ≤ a → a ≠ 0 → ProperlyInfinite (diagonalCopies n a) + +def StronglyPurelyInfinite : Prop := + ∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ ε : ℝ, 0 < ε → + ∃ s t : A, ‖star s * (a * a) * s - a * a‖ < ε ∧ + ‖star t * (b * b) * t - b * b‖ < ε ∧ ‖star s * a * b * t‖ < ε + +end Definitions + +theorem exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any + {A : Type u} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + (hA : Exact A) (hW : WeaklyPurelyInfinite A) {a : A} (ha : 0 ≤ a) : + ProperlyInfinite (diagonalCopies 1 a) := by + sorry + +theorem exact_weaklyPurelyInfinite_stronglyPurelyInfinite + (A : Type u) [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + (hExact : Exact A) (hWeak : WeaklyPurelyInfinite A) : StronglyPurelyInfinite A := by + sorry + +end WeakPureInfiniteness + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ExactInfiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any`, `OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_stronglyPurelyInfinite` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/exact-infiniteness/solution/closure.txt b/tasks/exact-infiniteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..43e5807e9a5d08708269bf2845f71d7b33548162 --- /dev/null +++ b/tasks/exact-infiniteness/solution/closure.txt @@ -0,0 +1,1012 @@ +OAI.Analysis.CStarAlgebra.PureInfiniteness.Avoidance +OAI.Analysis.CStarAlgebra.PureInfiniteness.ChoicePairs +OAI.Analysis.CStarAlgebra.PureInfiniteness.ClosedIdeal +OAI.Analysis.CStarAlgebra.PureInfiniteness.Comparison +OAI.Analysis.CStarAlgebra.PureInfiniteness.Compression +OAI.Analysis.CStarAlgebra.PureInfiniteness.Cutoffs +OAI.Analysis.CStarAlgebra.PureInfiniteness.Defect +OAI.Analysis.CStarAlgebra.PureInfiniteness.Diagonalization +OAI.Analysis.CStarAlgebra.PureInfiniteness.FourChoices +OAI.Analysis.CStarAlgebra.PureInfiniteness.Graph +OAI.Analysis.CStarAlgebra.PureInfiniteness.Hereditary +OAI.Analysis.CStarAlgebra.PureInfiniteness.IdealComparison +OAI.Analysis.CStarAlgebra.PureInfiniteness.IdealDetection +OAI.Analysis.CStarAlgebra.PureInfiniteness.Main +OAI.Analysis.CStarAlgebra.PureInfiniteness.MatrixEntries +OAI.Analysis.CStarAlgebra.PureInfiniteness.Nonvanishing +OAI.Analysis.CStarAlgebra.PureInfiniteness.OrthogonalSlots +OAI.Analysis.CStarAlgebra.PureInfiniteness.PositiveFunctional +OAI.Analysis.CStarAlgebra.PureInfiniteness.Products +OAI.Analysis.CStarAlgebra.PureInfiniteness.Representation +OAI.Analysis.CStarAlgebra.PureInfiniteness.Separation +OAI.Analysis.CStarAlgebra.PureInfiniteness.Shrinking +OAI.Analysis.CStarAlgebra.PureInfiniteness.Signal +OAI.Analysis.CStarAlgebra.PureInfiniteness.Stabilization +OAI.Analysis.CStarAlgebra.PureInfiniteness.Ultrafilter +OAI.Analysis.CharacterCriterion.Definitions +OAI.Analysis.CharacterCriterion.FactorIndependence +OAI.Analysis.CharacterCriterion.MaxTensor +OAI.Analysis.CharacterCriterion.Pauli +OAI.Analysis.IrrationalRotation.Analysis.VonNeumannStrongClosure +OAI.Analysis.IrrationalRotation.Model.Commutant +OAI.Analysis.IrrationalRotation.Model.Hyperfinite +OAI.Analysis.IrrationalRotation.Model.OperatorProperties +OAI.Analysis.IrrationalRotation.Operators.BicommutantAmplification +OAI.Analysis.IrrationalRotation.Operators.BicommutantCyclic +OAI.Analysis.IrrationalRotation.Operators.BicommutantDensity +OAI.Analysis.IrrationalRotation.Operators.BicommutantStrongTopology +OAI.Analysis.IrrationalRotation.Operators.Commutant +OAI.Analysis.JiangSu.Absorption.AbsorptionCriterion +OAI.Analysis.JiangSu.Absorption.ConnectedUnitaryLift +OAI.Analysis.JiangSu.Absorption.FunctionalIntertwining +OAI.Analysis.JiangSu.Absorption.OneSidedIntertwiningChain2 +OAI.Analysis.JiangSu.CStarAlgebras.AmbientIdealConjugation +OAI.Analysis.JiangSu.CStarAlgebras.ApproximateUnitSequence +OAI.Analysis.JiangSu.CStarAlgebras.CStarNormCompletion +OAI.Analysis.JiangSu.CStarAlgebras.CStarPolarNormalization +OAI.Analysis.JiangSu.CStarAlgebras.CompletedRootRank +OAI.Analysis.JiangSu.CStarAlgebras.ContractionLift +OAI.Analysis.JiangSu.CStarAlgebras.CutoffRank +OAI.Analysis.JiangSu.CStarAlgebras.FourEdgeGroupSurgery +OAI.Analysis.JiangSu.CStarAlgebras.PositiveContractionLift +OAI.Analysis.JiangSu.CStarAlgebras.SmoothedIntegerCuts +OAI.Analysis.JiangSu.CStarAlgebras.SourceRankLimit +OAI.Analysis.JiangSu.CStarAlgebras.StateCoefficientApproximation +OAI.Analysis.JiangSu.CentralSequences.NormCentralFunctionalCalculus +OAI.Analysis.JiangSu.CentralSequences.NormCentralSequenceAlgebra +OAI.Analysis.JiangSu.CentralSequences.NormTraceKernelSigma +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerBasic +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerEpsilonTest +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerMaps +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerPositive +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerToTracial +OAI.Analysis.JiangSu.CentralSequences.NormUltrapowerUnitaryLift +OAI.Analysis.JiangSu.CentralSequences.OrderZeroContractiveCut +OAI.Analysis.JiangSu.CentralSequences.QuasicentralFinite +OAI.Analysis.JiangSu.CentralSequences.QuasicentralResolvent +OAI.Analysis.JiangSu.CentralSequences.RelativeCentralMap +OAI.Analysis.JiangSu.CentralSequences.RelativeCentralQuotient +OAI.Analysis.JiangSu.CentralSequences.UnitalTraceKernelSigma +OAI.Analysis.JiangSu.Comparison.CompactComparison +OAI.Analysis.JiangSu.Comparison.Corner +OAI.Analysis.JiangSu.Comparison.CornerComparison +OAI.Analysis.JiangSu.Comparison.CuntzBasic +OAI.Analysis.JiangSu.Comparison.FamilyRanks +OAI.Analysis.JiangSu.Comparison.FiniteCutComparison +OAI.Analysis.JiangSu.Comparison.ProjectionDefect +OAI.Analysis.JiangSu.Comparison.Ranks +OAI.Analysis.JiangSu.Comparison.SemigroupComparisonArithmetic +OAI.Analysis.JiangSu.CuntzSemigroup.CornerRanks +OAI.Analysis.JiangSu.CuntzSemigroup.CuntzOrder +OAI.Analysis.JiangSu.CuntzSemigroup.CuntzRankMonotone +OAI.Analysis.JiangSu.CuntzSemigroup.CuntzRescaling +OAI.Analysis.JiangSu.CuntzSemigroup.FiniteCuntzAlmostUnperforation +OAI.Analysis.JiangSu.CuntzSemigroup.FiniteCuntzStates +OAI.Analysis.JiangSu.CuntzSemigroup.FiniteDimensionRegularization +OAI.Analysis.JiangSu.CuntzSemigroup.MatrixRanks +OAI.Analysis.JiangSu.CuntzSemigroup.SemigroupStates +OAI.Analysis.JiangSu.Excision.ExcisionSoftCompression +OAI.Analysis.JiangSu.Excision.ExcisionUpperCut +OAI.Analysis.JiangSu.Excision.JordanDomination +OAI.Analysis.JiangSu.Excision.PureGNSCommutant +OAI.Analysis.JiangSu.Excision.PureGNSProjections +OAI.Analysis.JiangSu.Excision.PureGNSStrongDensity +OAI.Analysis.JiangSu.Excision.PureStateCarrier +OAI.Analysis.JiangSu.Excision.PureStateNorming +OAI.Analysis.JiangSu.MatrixAlgebras.CompletedCornerRange +OAI.Analysis.JiangSu.MatrixAlgebras.CornerCompression +OAI.Analysis.JiangSu.MatrixAlgebras.FinOneMatrixTransport +OAI.Analysis.JiangSu.MatrixAlgebras.FiniteCorners +OAI.Analysis.JiangSu.MatrixAlgebras.MatrixTraces +OAI.Analysis.JiangSu.MatrixAlgebras.SharedMatrixBridge +OAI.Analysis.JiangSu.Model +OAI.Analysis.JiangSu.Nonunital.ClosedIdealBasic +OAI.Analysis.JiangSu.Nonunital.CommonMinorant +OAI.Analysis.JiangSu.Nonunital.CompactTraceBase +OAI.Analysis.JiangSu.Nonunital.FiniteTraceIdeal +OAI.Analysis.JiangSu.Nonunital.Hereditary +OAI.Analysis.JiangSu.Nonunital.IdealDensity +OAI.Analysis.JiangSu.Nonunital.IsometricHomLimit +OAI.Analysis.JiangSu.Nonunital.LimitTraceRestriction +OAI.Analysis.JiangSu.Nonunital.MatrixComparison +OAI.Analysis.JiangSu.Nonunital.MatrixDiagonal +OAI.Analysis.JiangSu.Nonunital.NonUnitalRoots +OAI.Analysis.JiangSu.Nonunital.NormMaps +OAI.Analysis.JiangSu.Nonunital.QuotientSurjective +OAI.Analysis.JiangSu.Nonunital.RankIdentification +OAI.Analysis.JiangSu.Nonunital.Regularization +OAI.Analysis.JiangSu.Nonunital.RelativeCoefficient +OAI.Analysis.JiangSu.Nonunital.RelativeCommutation +OAI.Analysis.JiangSu.Nonunital.Stabilization +OAI.Analysis.JiangSu.Nonunital.TraceRays +OAI.Analysis.JiangSu.Nonunital.TracialState +OAI.Analysis.JiangSu.Nuclearity.CompletelyPositiveOperations +OAI.Analysis.JiangSu.Nuclearity.NuclearCommutingExtension +OAI.Analysis.JiangSu.Nuclearity.NuclearNormApproximation +OAI.Analysis.JiangSu.TensorProducts.CommutingStarTensor +OAI.Analysis.JiangSu.TensorProducts.FaithfulTensorCrossNorm +OAI.Analysis.JiangSu.TensorProducts.FaithfulTensorExtension +OAI.Analysis.JiangSu.TensorProducts.FiniteHilbertAmplification +OAI.Analysis.JiangSu.TensorProducts.SimpleCStarAlgebraic +OAI.Analysis.JiangSu.TensorProducts.TensorIdeal +OAI.Analysis.JiangSu.TraceCone.AbsoluteComparison +OAI.Analysis.JiangSu.TraceCone.Cuntz +OAI.Analysis.JiangSu.TraceCone.CuntzDenseMaps +OAI.Analysis.JiangSu.TraceCone.CuntzIdentities +OAI.Analysis.JiangSu.TraceCone.MatrixBlockNorm +OAI.Analysis.JiangSu.TraceCone.MatrixCorners +OAI.Analysis.JiangSu.TraceCone.MatrixEmbedding +OAI.Analysis.JiangSu.TraceCone.MatrixEntries +OAI.Analysis.JiangSu.TraceCone.MatrixPositive +OAI.Analysis.JiangSu.TraceCone.MatrixSums +OAI.Analysis.JiangSu.TraceCone.ProductCuts +OAI.Analysis.JiangSu.TraceCone.Pullback +OAI.Analysis.JiangSu.TraceCone.Rank +OAI.Analysis.JiangSu.TraceCone.RankCyclic +OAI.Analysis.JiangSu.TraceCone.Weights +OAI.Analysis.JiangSu.Traces.CompletedSharedTrace +OAI.Analysis.JiangSu.Traces.NormAnnihilatorTraceKernel +OAI.Analysis.JiangSu.Traces.SmallTraceTransfer +OAI.Analysis.JiangSu.Traces.TraceRankApproximation +OAI.Analysis.JiangSu.Traces.UnitalNormToTracial +OAI.Analysis.ModularRecovery.CanonicalCalculus +OAI.Analysis.ModularRecovery.CanonicalGraph +OAI.Analysis.ModularRecovery.CanonicalPolar +OAI.Analysis.ModularRecovery.CanonicalTomita +OAI.Analysis.ModularRecovery.Commutant +OAI.Analysis.ModularRecovery.ErgodicAverages +OAI.Analysis.ModularRecovery.FiniteMoments +OAI.Analysis.ModularRecovery.FourierKernels +OAI.Analysis.ModularRecovery.FourierLocalization +OAI.Analysis.ModularRecovery.FourierOperators +OAI.Analysis.ModularRecovery.FourthMoments +OAI.Analysis.ModularRecovery.GaussianAverages +OAI.Analysis.ModularRecovery.KernelContinuity +OAI.Analysis.ModularRecovery.Mean +OAI.Analysis.ModularRecovery.Model +OAI.Analysis.ModularRecovery.ModularCovariance +OAI.Analysis.ModularRecovery.PolarCutoff +OAI.Analysis.ModularRecovery.PositiveKernels +OAI.Analysis.ModularRecovery.RealGraph +OAI.Analysis.ModularRecovery.Recovery +OAI.Analysis.ModularRecovery.SpectralCalculus +OAI.Analysis.ModularRecovery.StrongIntegrals +OAI.Analysis.ModularRecovery.StrongLimits +OAI.Analysis.ModularRecovery.TomitaFundamental +OAI.Analysis.ModularRecovery.TomitaResolvent +OAI.Analysis.ModularTheory.AlgebraicAdjoint +OAI.Analysis.ModularTheory.AlgebraicNormalForm +OAI.Analysis.ModularTheory.AmplifiedModularAction +OAI.Analysis.ModularTheory.AmplifiedModularExpectation +OAI.Analysis.ModularTheory.CommutantExpectation +OAI.Analysis.ModularTheory.CompressedCorners +OAI.Analysis.ModularTheory.CoreDualAction +OAI.Analysis.ModularTheory.CoreIntegrals +OAI.Analysis.ModularTheory.CoreSeparation +OAI.Analysis.ModularTheory.CoreSquareWeight +OAI.Analysis.ModularTheory.CoreTracial +OAI.Analysis.ModularTheory.CornerGNS +OAI.Analysis.ModularTheory.CornerGNSActions +OAI.Analysis.ModularTheory.CornerGNSRange +OAI.Analysis.ModularTheory.CornerProductNorm +OAI.Analysis.ModularTheory.CornerRepresentation +OAI.Analysis.ModularTheory.CornerRepresentedBound +OAI.Analysis.ModularTheory.CornerRightVectors +OAI.Analysis.ModularTheory.CornerTensorBound +OAI.Analysis.ModularTheory.CornerVectors +OAI.Analysis.ModularTheory.CovariantKernel +OAI.Analysis.ModularTheory.CovariantSlices +OAI.Analysis.ModularTheory.CrossedProduct +OAI.Analysis.ModularTheory.CutoffTotality +OAI.Analysis.ModularTheory.DualAction +OAI.Analysis.ModularTheory.DualKernelPairing +OAI.Analysis.ModularTheory.DualRegularization +OAI.Analysis.ModularTheory.DualUnitary +OAI.Analysis.ModularTheory.FieldPairing +OAI.Analysis.ModularTheory.FiniteAdjoint +OAI.Analysis.ModularTheory.FiniteProjections +OAI.Analysis.ModularTheory.FiniteStates +OAI.Analysis.ModularTheory.FiniteTrace +OAI.Analysis.ModularTheory.FiniteWeightDensity +OAI.Analysis.ModularTheory.FiniteWeightSpace +OAI.Analysis.ModularTheory.FixedPointExpectation +OAI.Analysis.ModularTheory.FixedPointIdentification +OAI.Analysis.ModularTheory.FourierCompression +OAI.Analysis.ModularTheory.FourierOrbit +OAI.Analysis.ModularTheory.FourierTranslation +OAI.Analysis.ModularTheory.GaussianRegularizers +OAI.Analysis.ModularTheory.HalfGraphCutoff +OAI.Analysis.ModularTheory.KernelIdentification +OAI.Analysis.ModularTheory.KernelRegularization +OAI.Analysis.ModularTheory.LpFaithful +OAI.Analysis.ModularTheory.LpGauge +OAI.Analysis.ModularTheory.LpRepresentation +OAI.Analysis.ModularTheory.LpTranslation +OAI.Analysis.ModularTheory.NormalAdjoint +OAI.Analysis.ModularTheory.NormalAdjointMap +OAI.Analysis.ModularTheory.NormalAdjointWeight +OAI.Analysis.ModularTheory.NormalWeightTotality +OAI.Analysis.ModularTheory.OperatorTensorBound +OAI.Analysis.ModularTheory.OriginalNorm +OAI.Analysis.ModularTheory.OriginalRightAction +OAI.Analysis.ModularTheory.ProjectionExhaustion +OAI.Analysis.ModularTheory.RightContinuity +OAI.Analysis.ModularTheory.RightTranslation +OAI.Analysis.ModularTheory.ScalarCompression +OAI.Analysis.ModularTheory.SpectralFourier +OAI.Analysis.ModularTheory.SpectralGaussian +OAI.Analysis.ModularTheory.SpectralShift +OAI.Analysis.ModularTheory.StandardTensorBound +OAI.Analysis.ModularTheory.TomitaLp +OAI.Analysis.ModularTheory.TomitaOrbit +OAI.Analysis.ModularTheory.TomitaRegularizer +OAI.Analysis.ModularTheory.TomitaTime +OAI.Analysis.ModularTheory.TraceConjugation +OAI.Analysis.ModularTheory.TraceExplicitConjugation +OAI.Analysis.ModularTheory.TraceNormalConjugation +OAI.Analysis.ModularTheory.TracialCompression +OAI.Analysis.ModularTheory.TracialCorners +OAI.Analysis.ModularTheory.TracialRightAction +OAI.Analysis.ModularTheory.TranslationCalculus +OAI.Analysis.ModularTheory.TranslationWeight +OAI.Analysis.ModularTheory.WeightAdjointMap +OAI.Analysis.ModularTheory.WeightClosed +OAI.Analysis.ModularTheory.WeightCutoffs +OAI.Analysis.ModularTheory.WeightFaithful +OAI.Analysis.ModularTheory.WeightGNS +OAI.Analysis.ModularTheory.WeightGram +OAI.Analysis.ModularTheory.WeightMonomials +OAI.Analysis.ModularTheory.WeightMonotone +OAI.Analysis.ModularTheory.WeightRightMultiplier +OAI.Analysis.ModularTheory.WeightedDensity +OAI.Analysis.ModularTheory.WeightedFourierBound +OAI.Analysis.ModularTheory.WeightedFourierLimit +OAI.Analysis.ModularTheory.WeightedGaussianKernel +OAI.Analysis.NuclearUltrapower.HilbertSchmidt +OAI.Analysis.Nuclearity.BoundedStarCompletion +OAI.Analysis.Nuclearity.CPBlockSum +OAI.Analysis.Nuclearity.CPFaithfulRestriction +OAI.Analysis.Nuclearity.CPMatrixFunctional +OAI.Analysis.Nuclearity.CPMultiplicativeDefect +OAI.Analysis.Nuclearity.CPNormFromPositive +OAI.Analysis.Nuclearity.CPRepresentationDomain +OAI.Analysis.Nuclearity.CPWeakOperatorUltralimit +OAI.Analysis.Nuclearity.ClosedIdealImage +OAI.Analysis.Nuclearity.CommutantNullCone +OAI.Analysis.Nuclearity.CommutantTensorWitness +OAI.Analysis.Nuclearity.CommutingCPGram +OAI.Analysis.Nuclearity.CommutingChoiFactor +OAI.Analysis.Nuclearity.CommutingCompressionOrder +OAI.Analysis.Nuclearity.CommutingCutZero +OAI.Analysis.Nuclearity.CommutingMatrixNorm +OAI.Analysis.Nuclearity.CommutingMatrixPositive +OAI.Analysis.Nuclearity.CompletedConjugation +OAI.Analysis.Nuclearity.CompletedSpatialSum +OAI.Analysis.Nuclearity.ConeIdealGeneration +OAI.Analysis.Nuclearity.DensePositiveExtension +OAI.Analysis.Nuclearity.DenseUnitalCompletion +OAI.Analysis.Nuclearity.ElementaryGeneratedIdeal +OAI.Analysis.Nuclearity.FactorTensorExtension +OAI.Analysis.Nuclearity.FactorTensorInjection +OAI.Analysis.Nuclearity.FourPositiveParts +OAI.Analysis.Nuclearity.IdealInIdeal +OAI.Analysis.Nuclearity.IdealSeparatingRepresentation +OAI.Analysis.Nuclearity.MatrixCPAmplification +OAI.Analysis.Nuclearity.MatrixCPMapExtension +OAI.Analysis.Nuclearity.MatrixFunctionalCP +OAI.Analysis.Nuclearity.MinimalCornerCompression +OAI.Analysis.Nuclearity.MinimalCornerNorm +OAI.Analysis.Nuclearity.MinimalFactorExtension +OAI.Analysis.Nuclearity.MinimalRightCPMap +OAI.Analysis.Nuclearity.MinimalTensorAlgebraic +OAI.Analysis.Nuclearity.MinimalTensorExtension +OAI.Analysis.Nuclearity.MinimalTensorFactorRestrictions +OAI.Analysis.Nuclearity.MinimalTensorKernelFaithful +OAI.Analysis.Nuclearity.NuclearCoefficientApproximation +OAI.Analysis.Nuclearity.NuclearCommutantExpectation +OAI.Analysis.Nuclearity.NuclearCommutingBound +OAI.Analysis.Nuclearity.NuclearCommutingCP +OAI.Analysis.Nuclearity.NuclearCommutingCPBound +OAI.Analysis.Nuclearity.NuclearCommutingRepresentation +OAI.Analysis.Nuclearity.NuclearConeNullspace +OAI.Analysis.Nuclearity.NuclearQuotientExpectation +OAI.Analysis.Nuclearity.NuclearRepresentedQuotient +OAI.Analysis.Nuclearity.NuclearTensorFunctional +OAI.Analysis.Nuclearity.NuclearTensorOperatorExtension +OAI.Analysis.Nuclearity.NuclearUnitizationCPAP +OAI.Analysis.Nuclearity.PositiveConeIdeal +OAI.Analysis.Nuclearity.PositiveConeNullIdeal +OAI.Analysis.Nuclearity.PositiveConeSeparation +OAI.Analysis.Nuclearity.PositiveFunctionalExtension +OAI.Analysis.Nuclearity.PositiveFunctionalKernel +OAI.Analysis.Nuclearity.PositiveMapAbelianization +OAI.Analysis.Nuclearity.PositiveSpanningSequence +OAI.Analysis.Nuclearity.PositiveSquareNullSpace +OAI.Analysis.Nuclearity.PositiveStateQuotient +OAI.Analysis.Nuclearity.ProductPurePullback +OAI.Analysis.Nuclearity.ProductPureSeparation +OAI.Analysis.Nuclearity.ProductStateFunctional +OAI.Analysis.Nuclearity.ProductStateIdealExcision +OAI.Analysis.Nuclearity.PureProductFunctional +OAI.Analysis.Nuclearity.PureProductIdealDetection +OAI.Analysis.Nuclearity.PureProductRepresentation +OAI.Analysis.Nuclearity.PureStateQuotient +OAI.Analysis.Nuclearity.PureStateRepresentation +OAI.Analysis.Nuclearity.QuotientCPMap +OAI.Analysis.Nuclearity.QuotientCommutingBound +OAI.Analysis.Nuclearity.QuotientTensorNorm +OAI.Analysis.Nuclearity.RepresentedAlgebra +OAI.Analysis.Nuclearity.RepresentedFactorTensor +OAI.Analysis.Nuclearity.RepresentedIdealGeneration +OAI.Analysis.Nuclearity.RepresentedIdealSeparation +OAI.Analysis.Nuclearity.RepresentedImageData +OAI.Analysis.Nuclearity.RepresentedTensorFunctional +OAI.Analysis.Nuclearity.RepresentedTensorKernel +OAI.Analysis.Nuclearity.SpatialCoefficientEstimate +OAI.Analysis.Nuclearity.SpatialEvaluation +OAI.Analysis.Nuclearity.SpatialStateUltralimit +OAI.Analysis.Nuclearity.SpatialTensorFaithful +OAI.Analysis.Nuclearity.SubalgebraTensorNorm +OAI.Analysis.Nuclearity.TensorCoefficientFunctional +OAI.Analysis.Nuclearity.TensorExcisionEstimate +OAI.Analysis.Nuclearity.TensorFixedElement +OAI.Analysis.Nuclearity.TensorFunctionalConjugation +OAI.Analysis.Nuclearity.TensorHalfFlipApplication +OAI.Analysis.Nuclearity.TensorIdealExcisionCut +OAI.Analysis.Nuclearity.TensorMultiplierAction +OAI.Analysis.Nuclearity.TensorSurjectivity +OAI.Analysis.Nuclearity.UnitalCPContraction +OAI.Analysis.Nuclearity.UnitalFaithfulRepresentation +OAI.Analysis.Nuclearity.UnitalIdealQuotient +OAI.Analysis.Nuclearity.UnitalMinimalTensor +OAI.Analysis.Nuclearity.UnitalNuclearTensor +OAI.Analysis.Nuclearity.UnitizedAbelianClosure +OAI.Analysis.Nuclearity.UnitizedCPMap +OAI.Analysis.Nuclearity.UnitizedCoefficientConvexity +OAI.Analysis.Nuclearity.UnitizedCoefficientMaps +OAI.Analysis.Nuclearity.UnitizedCoefficientOneStep +OAI.Analysis.Nuclearity.UnitizedCoefficients +OAI.Analysis.Nuclearity.UnitizedCompression +OAI.Analysis.Nuclearity.UnitizedConeMembership +OAI.Analysis.Nuclearity.UnitizedConeOperations +OAI.Analysis.Nuclearity.UnitizedFiniteCoefficientCone +OAI.Analysis.Nuclearity.UnitizedIdealGeneration +OAI.Analysis.Nuclearity.UnitizedTensorElementary +OAI.Analysis.OInfinity.AffineReflectionPath +OAI.Analysis.OInfinity.BandOperators +OAI.Analysis.OInfinity.BandProducts +OAI.Analysis.OInfinity.BergRotation +OAI.Analysis.OInfinity.BergSeam +OAI.Analysis.OInfinity.BergShift +OAI.Analysis.OInfinity.BergTent +OAI.Analysis.OInfinity.BergTower +OAI.Analysis.OInfinity.BinaryFragmentation +OAI.Analysis.OInfinity.BinaryLeafRows +OAI.Analysis.OInfinity.BufferAbsorption +OAI.Analysis.OInfinity.BufferAnchor +OAI.Analysis.OInfinity.BufferedIteration +OAI.Analysis.OInfinity.BufferedPaths +OAI.Analysis.OInfinity.BufferedProperComparison +OAI.Analysis.OInfinity.BufferedRelativeWitness +OAI.Analysis.OInfinity.BufferedTail +OAI.Analysis.OInfinity.CARCombination +OAI.Analysis.OInfinity.CARShiftModes +OAI.Analysis.OInfinity.CPAP +OAI.Analysis.OInfinity.CancellationBandwidth +OAI.Analysis.OInfinity.CancellationTransport +OAI.Analysis.OInfinity.CanonicalBuffer +OAI.Analysis.OInfinity.CanonicalBufferAbsorption +OAI.Analysis.OInfinity.CanonicalShift +OAI.Analysis.OInfinity.CentralBuffer +OAI.Analysis.OInfinity.CentralBufferImage +OAI.Analysis.OInfinity.CentralIsometries +OAI.Analysis.OInfinity.ClockCancellation +OAI.Analysis.OInfinity.ClockCocycleFamily +OAI.Analysis.OInfinity.ClockCorrection +OAI.Analysis.OInfinity.ClockFragmentation +OAI.Analysis.OInfinity.ClockGram +OAI.Analysis.OInfinity.ClockPolar +OAI.Analysis.OInfinity.ClockTransport +OAI.Analysis.OInfinity.ClockedBands +OAI.Analysis.OInfinity.ClockedCancellation +OAI.Analysis.OInfinity.CocycleCancellation +OAI.Analysis.OInfinity.CocycleCentrality +OAI.Analysis.OInfinity.CocycleFlip +OAI.Analysis.OInfinity.CocycleGluing +OAI.Analysis.OInfinity.CommonCornerShrink +OAI.Analysis.OInfinity.CompressionTransfer +OAI.Analysis.OInfinity.ConnectedCocycleGluing +OAI.Analysis.OInfinity.ConnectedGeneratorWitness +OAI.Analysis.OInfinity.ConnectedHalfFlipGenerators +OAI.Analysis.OInfinity.ConnectedHalfFlipTheorem +OAI.Analysis.OInfinity.ConnectedProperComparison +OAI.Analysis.OInfinity.ConnectedRowCompletion +OAI.Analysis.OInfinity.ControlledAbsorption +OAI.Analysis.OInfinity.CornerContraction +OAI.Analysis.OInfinity.CornerContractionPath +OAI.Analysis.OInfinity.CornerShortPath +OAI.Analysis.OInfinity.CornerStabilization +OAI.Analysis.OInfinity.DyadicProjections +OAI.Analysis.OInfinity.EvenCARRelations +OAI.Analysis.OInfinity.EvenModeCAR +OAI.Analysis.OInfinity.EvenRowCAR +OAI.Analysis.OInfinity.EvenShiftModes +OAI.Analysis.OInfinity.FiniteCAR +OAI.Analysis.OInfinity.FinitePermutation +OAI.Analysis.OInfinity.FiniteRowCompletion +OAI.Analysis.OInfinity.FiniteRowDefect +OAI.Analysis.OInfinity.FiniteRowIsometry +OAI.Analysis.OInfinity.FiniteWords +OAI.Analysis.OInfinity.FixedComplementPaths +OAI.Analysis.OInfinity.FixedSparePath +OAI.Analysis.OInfinity.FixedSpareStabilization +OAI.Analysis.OInfinity.FockCompression +OAI.Analysis.OInfinity.FockConvergence +OAI.Analysis.OInfinity.FockRangeProjection +OAI.Analysis.OInfinity.FockReturn +OAI.Analysis.OInfinity.FockShift +OAI.Analysis.OInfinity.HalfFlipRecursion +OAI.Analysis.OInfinity.IncompleteBinaryPath +OAI.Analysis.OInfinity.IncompleteCocycle +OAI.Analysis.OInfinity.IncompleteTails +OAI.Analysis.OInfinity.IteratedBandTransport +OAI.Analysis.OInfinity.JointClock +OAI.Analysis.OInfinity.JointCycleIdentity +OAI.Analysis.OInfinity.JointRohlin +OAI.Analysis.OInfinity.JointRohlinWitness +OAI.Analysis.OInfinity.JointWordCycle +OAI.Analysis.OInfinity.JordanWigner +OAI.Analysis.OInfinity.JordanWignerEstimates +OAI.Analysis.OInfinity.MaskedBandRows +OAI.Analysis.OInfinity.MaskedRotations +OAI.Analysis.OInfinity.MaskedShift +OAI.Analysis.OInfinity.MixedComplement +OAI.Analysis.OInfinity.MixedNegative +OAI.Analysis.OInfinity.MixedSwap +OAI.Analysis.OInfinity.MixedTower +OAI.Analysis.OInfinity.NegativeBinary +OAI.Analysis.OInfinity.NegativeComparison +OAI.Analysis.OInfinity.NegativeCompletion +OAI.Analysis.OInfinity.NegativeCorner +OAI.Analysis.OInfinity.NegativeGlobal +OAI.Analysis.OInfinity.NuclearModel +OAI.Analysis.OInfinity.ProjectionCorner +OAI.Analysis.OInfinity.ProperBufferAbsorption +OAI.Analysis.OInfinity.RelativeCocycle +OAI.Analysis.OInfinity.RelativeCompletedComparison +OAI.Analysis.OInfinity.RelativeGramCorrection +OAI.Analysis.OInfinity.RelativeUnitaryPath +OAI.Analysis.OInfinity.RohlinGluing +OAI.Analysis.OInfinity.RohlinPartitions +OAI.Analysis.OInfinity.RohlinPolar +OAI.Analysis.OInfinity.RohlinShift +OAI.Analysis.OInfinity.RohlinUnitarity +OAI.Analysis.OInfinity.RowCocycleDefect +OAI.Analysis.OInfinity.RowCompletionBase +OAI.Analysis.OInfinity.RowCompletionBuffer +OAI.Analysis.OInfinity.ShrinkPaths +OAI.Analysis.OInfinity.Simple +OAI.Analysis.OInfinity.TailCancellationWitness +OAI.Analysis.OInfinity.TensorApproximation +OAI.Analysis.OInfinity.TensorGram +OAI.Analysis.OInfinity.TensorNorm +OAI.Analysis.OInfinity.ToeplitzCompression +OAI.Analysis.OInfinity.TransportedBuffer +OAI.Analysis.OInfinity.VacuumBufferAbsorption +OAI.Analysis.OInfinity.VacuumCorner +OAI.Analysis.OInfinity.VacuumSplit +OAI.Analysis.OInfinity.ZeroCorner +OAI.Analysis.OInfinity.ZeroCornerRows +OAI.Analysis.OInfinity.ZeroUnitBuffer +OAI.Analysis.OInfinity.ZeroUnitComparison +OAI.Analysis.OInfinity.ZeroUnitCompletion +OAI.Analysis.OInfinity.ZeroUnitRows +OAI.Analysis.OperatorAlgebra.AntiunitaryCPConjugation +OAI.Analysis.OperatorAlgebra.AntiunitaryOperatorIdentities +OAI.Analysis.OperatorAlgebra.BicommutantStrongStar +OAI.Analysis.OperatorAlgebra.CanonicalLpOperations +OAI.Analysis.OperatorAlgebra.ComplexSymmetricMean +OAI.Analysis.OperatorAlgebra.ContinuousLpFieldNorm +OAI.Analysis.OperatorAlgebra.CyclicCoefficientApproximation +OAI.Analysis.OperatorAlgebra.CyclicGNSUnitary +OAI.Analysis.OperatorAlgebra.CyclicSeparatingCompression +OAI.Analysis.OperatorAlgebra.CyclicStandardIntertwiner +OAI.Analysis.OperatorAlgebra.CyclicStateNorm +OAI.Analysis.OperatorAlgebra.DensityQuadraticCompression +OAI.Analysis.OperatorAlgebra.DensityRootTrace +OAI.Analysis.OperatorAlgebra.DensitySpatialRepresentation +OAI.Analysis.OperatorAlgebra.DensityUnitaryCoefficients +OAI.Analysis.OperatorAlgebra.ExpectationDensityRoots +OAI.Analysis.OperatorAlgebra.ExpectationFiniteDensity +OAI.Analysis.OperatorAlgebra.ExpectationHypertrace +OAI.Analysis.OperatorAlgebra.FiniteHilbertCompression +OAI.Analysis.OperatorAlgebra.FiniteOperatorExtension +OAI.Analysis.OperatorAlgebra.FiniteOperatorPredual +OAI.Analysis.OperatorAlgebra.FinitePredualConjugation +OAI.Analysis.OperatorAlgebra.FiniteVectorDensityTensor +OAI.Analysis.OperatorAlgebra.FunctionalCommutant +OAI.Analysis.OperatorAlgebra.GNSBundledIntertwining +OAI.Analysis.OperatorAlgebra.GNSBundledOperators +OAI.Analysis.OperatorAlgebra.GNSCornerRange +OAI.Analysis.OperatorAlgebra.GNSCyclicRepresentation +OAI.Analysis.OperatorAlgebra.GNSHilbertStructure +OAI.Analysis.OperatorAlgebra.GNSHomIntertwining +OAI.Analysis.OperatorAlgebra.GNSProductNorm +OAI.Analysis.OperatorAlgebra.GNSSeparableCyclic +OAI.Analysis.OperatorAlgebra.GNSSeparatingSequence +OAI.Analysis.OperatorAlgebra.GNSSequenceAmplification +OAI.Analysis.OperatorAlgebra.GNSStandardForm +OAI.Analysis.OperatorAlgebra.GNSVectorDensity +OAI.Analysis.OperatorAlgebra.GaussianConvolutionApproximation +OAI.Analysis.OperatorAlgebra.GaussianKernelFubini +OAI.Analysis.OperatorAlgebra.GaussianSchurFactor +OAI.Analysis.OperatorAlgebra.HilbertDualOperators +OAI.Analysis.OperatorAlgebra.HilbertOperatorExtension +OAI.Analysis.OperatorAlgebra.HilbertProjectionRange +OAI.Analysis.OperatorAlgebra.HilbertSchmidtUnitaryActions +OAI.Analysis.OperatorAlgebra.HilbertTensorExtension +OAI.Analysis.OperatorAlgebra.HypertraceFiniteDensity +OAI.Analysis.OperatorAlgebra.IntegratedModularField +OAI.Analysis.OperatorAlgebra.IntertwinerCommutantCP +OAI.Analysis.OperatorAlgebra.IntertwinerCompression +OAI.Analysis.OperatorAlgebra.IntertwinerTensorCompression +OAI.Analysis.OperatorAlgebra.IsometricCornerExpectation +OAI.Analysis.OperatorAlgebra.IsometricCornerNorm +OAI.Analysis.OperatorAlgebra.IsometricCornerOperators +OAI.Analysis.OperatorAlgebra.KernelIntegralBounds +OAI.Analysis.OperatorAlgebra.LpAlgebraicInstances +OAI.Analysis.OperatorAlgebra.LpFourierCoefficients +OAI.Analysis.OperatorAlgebra.LpFourierIntegral +OAI.Analysis.OperatorAlgebra.LpFourierIntegralAE +OAI.Analysis.OperatorAlgebra.LpOperatorStructure +OAI.Analysis.OperatorAlgebra.LpOperatorTensorBound +OAI.Analysis.OperatorAlgebra.LpTensorFunctoriality +OAI.Analysis.OperatorAlgebra.NormalizedExpectationRoots +OAI.Analysis.OperatorAlgebra.PointwiseAntiunitary +OAI.Analysis.OperatorAlgebra.PointwiseTomita +OAI.Analysis.OperatorAlgebra.ReducedDensityPredual +OAI.Analysis.OperatorAlgebra.ScalarKernelPairing +OAI.Analysis.OperatorAlgebra.ScalarLpContinuousCutoffs +OAI.Analysis.OperatorAlgebra.ScalarLpCutoffConvergence +OAI.Analysis.OperatorAlgebra.ScalarLpIntervalCommutant +OAI.Analysis.OperatorAlgebra.ScalarLpLocalizedFunctions +OAI.Analysis.OperatorAlgebra.ScalarLpMultiplier +OAI.Analysis.OperatorAlgebra.ScalarLpProjection +OAI.Analysis.OperatorAlgebra.ScalarLpStrongConvergence +OAI.Analysis.OperatorAlgebra.ScalarLpSuperlevel +OAI.Analysis.OperatorAlgebra.ScalarOperatorSlices +OAI.Analysis.OperatorAlgebra.ScalarSliceContinuity +OAI.Analysis.OperatorAlgebra.ScalarTranslationConvolution +OAI.Analysis.OperatorAlgebra.ScalarVectorDensity +OAI.Analysis.OperatorAlgebra.ScalarVectorLp +OAI.Analysis.OperatorAlgebra.SmallTimeOperatorAverage +OAI.Analysis.OperatorAlgebra.StandardCommutantOpposite +OAI.Analysis.OperatorAlgebra.StandardMinimalMultiplication +OAI.Analysis.OperatorAlgebra.StandardMultiplicationEvaluation +OAI.Analysis.OperatorAlgebra.StandardTensorCompression +OAI.Analysis.OperatorAlgebra.StrongCompressionBound +OAI.Analysis.OperatorAlgebra.TotalTensorVectors +OAI.Analysis.OperatorAlgebra.TracialBundledFiniteBound +OAI.Analysis.OperatorAlgebra.TracialCanonicalCornerBound +OAI.Analysis.OperatorAlgebra.TracialCornerCompression +OAI.Analysis.OperatorAlgebra.TracialExpectationBound +OAI.Analysis.OperatorAlgebra.TracialGNSIntertwiner +OAI.Analysis.OperatorAlgebra.TracialMinimalBound +OAI.Analysis.OperatorAlgebra.TracialMinimalMultiplication +OAI.Analysis.OperatorAlgebra.TracialProductApproximation +OAI.Analysis.OperatorAlgebra.TracialRepresentedBound +OAI.Analysis.OperatorAlgebra.TracialSpatialApproximation +OAI.Analysis.OperatorAlgebra.TracialSpatialMultiplication +OAI.Analysis.OperatorAlgebra.TracialSpatialState +OAI.Analysis.OperatorAlgebra.TracialSpatialUnitaryState +OAI.Analysis.OperatorAlgebra.TracialStatePullback +OAI.Analysis.OperatorAlgebra.TracialTensorCompletion +OAI.Analysis.OperatorAlgebra.TracialTensorFiniteSum +OAI.Analysis.OperatorAlgebra.TracialTensorVector +OAI.Analysis.OperatorAlgebra.UnitaryMeanCP +OAI.Analysis.OperatorAlgebra.UnitaryMeanExpectation +OAI.Analysis.OperatorAlgebra.UnitaryMeanProperties +OAI.Analysis.OperatorAlgebra.UnitaryMeanRange +OAI.Analysis.OperatorAlgebra.UnitaryOrbitMean +OAI.Analysis.OperatorAlgebra.VectorLpMultiplier +OAI.Analysis.OperatorAlgebra.VectorLpProjection +OAI.Analysis.OperatorAlgebra.VectorLpStrongConvergence +OAI.Analysis.OperatorAlgebra.VonNeumannWeakConvergence +OAI.Analysis.OperatorAlgebra.WeakOperatorUltralimit +OAI.Analysis.PureInfiniteness.AbelianPositiveFixer +OAI.Analysis.PureInfiniteness.AbelianRangeExtension +OAI.Analysis.PureInfiniteness.AbelianizationRelations +OAI.Analysis.PureInfiniteness.Absorption +OAI.Analysis.PureInfiniteness.AbsorptionCanonicalTensor +OAI.Analysis.PureInfiniteness.AbsorptionFromCentralCopy +OAI.Analysis.PureInfiniteness.AbsorptionFromHalfFlip +OAI.Analysis.PureInfiniteness.AbsorptionFromQuotientNuclearity +OAI.Analysis.PureInfiniteness.AbsorptionFromTensorIdeal +OAI.Analysis.PureInfiniteness.AbsorptionMain +OAI.Analysis.PureInfiniteness.ApproximateOneStep +OAI.Analysis.PureInfiniteness.ApproximateUnitConjugation +OAI.Analysis.PureInfiniteness.ApproximatelyInnerCP +OAI.Analysis.PureInfiniteness.BoundedPairDiagonalization +OAI.Analysis.PureInfiniteness.CentralSequenceAbsorption +OAI.Analysis.PureInfiniteness.CoefficientConeClosure +OAI.Analysis.PureInfiniteness.CollapseFiniteCompression +OAI.Analysis.PureInfiniteness.ColumnReturnEstimates +OAI.Analysis.PureInfiniteness.CommutativeCoefficientAlgebra +OAI.Analysis.PureInfiniteness.CommutativeRelativeCopies +OAI.Analysis.PureInfiniteness.CompressedCoefficientAlgebra +OAI.Analysis.PureInfiniteness.CompressionNorms +OAI.Analysis.PureInfiniteness.ConjugateCoefficientTest +OAI.Analysis.PureInfiniteness.ConjugateGeneratedCone +OAI.Analysis.PureInfiniteness.ConnectedUltrapowerLift +OAI.Analysis.PureInfiniteness.ConnectedUnitaryLift +OAI.Analysis.PureInfiniteness.CountableAbelianization +OAI.Analysis.PureInfiniteness.CountableUltrapowerSaturation +OAI.Analysis.PureInfiniteness.CrossCompressionEstimate +OAI.Analysis.PureInfiniteness.CuntzGramMap +OAI.Analysis.PureInfiniteness.CutMatrixDiagonalization +OAI.Analysis.PureInfiniteness.CutSampleReturn +OAI.Analysis.PureInfiniteness.CutSupport +OAI.Analysis.PureInfiniteness.DoubledCorner +OAI.Analysis.PureInfiniteness.ExactCompressionRelations +OAI.Analysis.PureInfiniteness.ExactFiniteAbelianization +OAI.Analysis.PureInfiniteness.FiniteAbelianMerge +OAI.Analysis.PureInfiniteness.FiniteCompressionError +OAI.Analysis.PureInfiniteness.FiniteDensityPowersStormer +OAI.Analysis.PureInfiniteness.FiniteFamilyAbelianization +OAI.Analysis.PureInfiniteness.FiniteJointSubalgebra +OAI.Analysis.PureInfiniteness.FiniteMatrixDiagonalization +OAI.Analysis.PureInfiniteness.FiniteOneStepReduction +OAI.Analysis.PureInfiniteness.FinitePureStateExcision +OAI.Analysis.PureInfiniteness.FiniteRelativeSupport +OAI.Analysis.PureInfiniteness.FiniteSpectralCompression +OAI.Analysis.PureInfiniteness.FiniteTensorApproximation +OAI.Analysis.PureInfiniteness.FiniteUltrapowerSaturation +OAI.Analysis.PureInfiniteness.FunctionalTensorRepresentation +OAI.Analysis.PureInfiniteness.InnerHomCompression +OAI.Analysis.PureInfiniteness.JointSpectralEstimates +OAI.Analysis.PureInfiniteness.JointSpectralPartition +OAI.Analysis.PureInfiniteness.JointSpectralQuadratic +OAI.Analysis.PureInfiniteness.JointSpectralSecondMoment +OAI.Analysis.PureInfiniteness.Main +OAI.Analysis.PureInfiniteness.MappedSpectralEstimates +OAI.Analysis.PureInfiniteness.MultiplierIntertwining +OAI.Analysis.PureInfiniteness.NonunitalContractionLift +OAI.Analysis.PureInfiniteness.NonunitalCrossCompression +OAI.Analysis.PureInfiniteness.NonunitalFiniteCompression +OAI.Analysis.PureInfiniteness.NonunitalFunctionalRepresentation +OAI.Analysis.PureInfiniteness.NonunitalJointPartition +OAI.Analysis.PureInfiniteness.NonunitalSampledRow +OAI.Analysis.PureInfiniteness.NormalizedCornerVector +OAI.Analysis.PureInfiniteness.NormalizedQuadraticEstimate +OAI.Analysis.PureInfiniteness.NormalizedSeparatingSequence +OAI.Analysis.PureInfiniteness.OneStepAbelianRange +OAI.Analysis.PureInfiniteness.OneStepContraction +OAI.Analysis.PureInfiniteness.OneStepPointNormClosure +OAI.Analysis.PureInfiniteness.PointNormFiniteCriterion +OAI.Analysis.PureInfiniteness.RectangularAlgebra +OAI.Analysis.PureInfiniteness.RectangularMaps +OAI.Analysis.PureInfiniteness.RectangularReturnDefect +OAI.Analysis.PureInfiniteness.ReindexGramRow +OAI.Analysis.PureInfiniteness.RelativeCentralCuntz +OAI.Analysis.PureInfiniteness.RelativeCoefficientEnlargement +OAI.Analysis.PureInfiniteness.RelativeCornerSums +OAI.Analysis.PureInfiniteness.RelativeInnerCalculus +OAI.Analysis.PureInfiniteness.RelativeOneStep +OAI.Analysis.PureInfiniteness.RelativeOneStepContraction +OAI.Analysis.PureInfiniteness.RelativeSupportAction +OAI.Analysis.PureInfiniteness.RepeatedSpectralError +OAI.Analysis.PureInfiniteness.ScalarComplement +OAI.Analysis.PureInfiniteness.ScalarSampling +OAI.Analysis.PureInfiniteness.SelfAdjointCoefficientCone +OAI.Analysis.PureInfiniteness.SpectralCharacters +OAI.Analysis.PureInfiniteness.SpectralCopies +OAI.Analysis.PureInfiniteness.SpectralCutReturn +OAI.Analysis.PureInfiniteness.SpectralGrid +OAI.Analysis.PureInfiniteness.SpectralGridCFC +OAI.Analysis.PureInfiniteness.SpectralMaps +OAI.Analysis.PureInfiniteness.SpectralProductCFC +OAI.Analysis.PureInfiniteness.SpectralProductGrid +OAI.Analysis.PureInfiniteness.SpectralRowEstimate +OAI.Analysis.PureInfiniteness.SpectralRowSampling +OAI.Analysis.PureInfiniteness.SpectralSecondMoment +OAI.Analysis.PureInfiniteness.StateCutMass +OAI.Analysis.PureInfiniteness.SupportedPairConstruction +OAI.Analysis.PureInfiniteness.SupportedTwoCopyMap +OAI.Analysis.PureInfiniteness.TailCancellationRows +OAI.Analysis.PureInfiniteness.TwoMatrixNuclear +OAI.Analysis.PureInfiniteness.UltrapowerCopiesApprox +OAI.Analysis.PureInfiniteness.UltrapowerCopiesExact +OAI.Analysis.PureInfiniteness.UltrapowerCopyBounds +OAI.Analysis.PureInfiniteness.UltrapowerFiniteAbelianization +OAI.Analysis.PureInfiniteness.UltrapowerGramCuts +OAI.Analysis.PureInfiniteness.UltrapowerMatrixCut +OAI.Analysis.PureInfiniteness.UltrapowerRelativeGram +OAI.Analysis.PureInfiniteness.UltrapowerSpectralCompression +OAI.Analysis.PureInfiniteness.UnitarySpanEquality +OAI.Analysis.TracialSplitting.BistochasticTests +OAI.Analysis.TracialSplitting.BlockAveraging +OAI.Analysis.TracialSplitting.BlockSampling +OAI.Analysis.TracialSplitting.ChallengeDefinitions +OAI.Analysis.TracialSplitting.CoefficientApproximation +OAI.Analysis.TracialSplitting.CoefficientBounds +OAI.Analysis.TracialSplitting.Completion +OAI.Analysis.TracialSplitting.ConditionalSplitting +OAI.Analysis.TracialSplitting.Diagonalization +OAI.Analysis.TracialSplitting.FaithfulRepresentations +OAI.Analysis.TracialSplitting.FinitePacking +OAI.Analysis.TracialSplitting.FullProjections +OAI.Analysis.TracialSplitting.GNSRepresentations +OAI.Analysis.TracialSplitting.HereditaryAlgebras +OAI.Analysis.TracialSplitting.Hypertraces +OAI.Analysis.TracialSplitting.KrausApproximation +OAI.Analysis.TracialSplitting.MatrixCoefficients +OAI.Analysis.TracialSplitting.MatrixNormalization +OAI.Analysis.TracialSplitting.Model +OAI.Analysis.TracialSplitting.NuclearApproximation +OAI.Analysis.TracialSplitting.NuclearFamilies +OAI.Analysis.TracialSplitting.NuclearTransfer +OAI.Analysis.TracialSplitting.OrthogonalElements +OAI.Analysis.TracialSplitting.OrthogonalPacking +OAI.Analysis.TracialSplitting.PackingEstimates +OAI.Analysis.TracialSplitting.PartitionAveraging +OAI.Analysis.TracialSplitting.PartitionCoupling +OAI.Analysis.TracialSplitting.PreparedBlocks +OAI.Analysis.TracialSplitting.ProjectionFrames +OAI.Analysis.TracialSplitting.ProjectionRounding +OAI.Analysis.TracialSplitting.ProjectionSampling +OAI.Analysis.TracialSplitting.RowEstimates +OAI.Analysis.TracialSplitting.ScalarCompression +OAI.Analysis.TracialSplitting.SimpleIdeals +OAI.Analysis.TracialSplitting.SmallProjections +OAI.Analysis.TracialSplitting.SpatialTensor +OAI.Analysis.TracialSplitting.SpectralBlocks +OAI.Analysis.TracialSplitting.SpectralCutoffs +OAI.Analysis.TracialSplitting.SpectralLayers +OAI.Analysis.TracialSplitting.StateExtension +OAI.Analysis.TracialSplitting.TensorExtension +OAI.Analysis.TracialSplitting.TensorNorms +OAI.Analysis.TracialSplitting.TraceConvexity +OAI.Analysis.TracialSplitting.TraceEstimates +OAI.Analysis.TracialSplitting.TraceNormalization +OAI.Analysis.TracialSplitting.VectorApproximation +OAI.Analysis.TracialSplitting.WeightedFamilies +OAI.Analysis.WeakInfiniteness.AbsorptionCriteria +OAI.Analysis.WeakInfiniteness.AlgebraicTensorSpan +OAI.Analysis.WeakInfiniteness.AnnihilatorStates +OAI.Analysis.WeakInfiniteness.ApproximateCut +OAI.Analysis.WeakInfiniteness.BoundedImplementation +OAI.Analysis.WeakInfiniteness.CPCentralCriterion +OAI.Analysis.WeakInfiniteness.CPCorrection +OAI.Analysis.WeakInfiniteness.CPDefect +OAI.Analysis.WeakInfiniteness.CPSchwarz +OAI.Analysis.WeakInfiniteness.CStarClosedRange +OAI.Analysis.WeakInfiniteness.CentralCopiesTensor +OAI.Analysis.WeakInfiniteness.CentralCuntzWords +OAI.Analysis.WeakInfiniteness.CentralExactPair +OAI.Analysis.WeakInfiniteness.CentralOInfinityCopies +OAI.Analysis.WeakInfiniteness.CentralState +OAI.Analysis.WeakInfiniteness.CentralVacuum +OAI.Analysis.WeakInfiniteness.CentralizationEstimates +OAI.Analysis.WeakInfiniteness.ChoiFactor +OAI.Analysis.WeakInfiniteness.Clipping +OAI.Analysis.WeakInfiniteness.ClippingTools +OAI.Analysis.WeakInfiniteness.ColumnCoreNorm +OAI.Analysis.WeakInfiniteness.ColumnNormalization +OAI.Analysis.WeakInfiniteness.CompatibleInverse +OAI.Analysis.WeakInfiniteness.CompatiblePerturbations +OAI.Analysis.WeakInfiniteness.CompatibleSeparation +OAI.Analysis.WeakInfiniteness.ComplexScalar +OAI.Analysis.WeakInfiniteness.CompressedStates +OAI.Analysis.WeakInfiniteness.CompressionObstruction +OAI.Analysis.WeakInfiniteness.ContinuousDeletion +OAI.Analysis.WeakInfiniteness.CoreSelection +OAI.Analysis.WeakInfiniteness.CrossUniverseKernel +OAI.Analysis.WeakInfiniteness.CrossUniverseKernelHeredity +OAI.Analysis.WeakInfiniteness.CrossUniverseLeftMap +OAI.Analysis.WeakInfiniteness.CrossUniverseSmallExact +OAI.Analysis.WeakInfiniteness.CrossUniverseSupportedSeparation +OAI.Analysis.WeakInfiniteness.CrossUniverseTensorBound +OAI.Analysis.WeakInfiniteness.CrossUniverseTensorLaws +OAI.Analysis.WeakInfiniteness.CrossUniverseTensorMap +OAI.Analysis.WeakInfiniteness.CrossUniverseUniformGap +OAI.Analysis.WeakInfiniteness.CrossUniverseUniformModels +OAI.Analysis.WeakInfiniteness.CuntzComparison +OAI.Analysis.WeakInfiniteness.CuntzCopies +OAI.Analysis.WeakInfiniteness.CuntzPairCorrection +OAI.Analysis.WeakInfiniteness.CutImplementation +OAI.Analysis.WeakInfiniteness.CyclicOrbit +OAI.Analysis.WeakInfiniteness.DetectedSigns +OAI.Analysis.WeakInfiniteness.DiagonalRegular +OAI.Analysis.WeakInfiniteness.ElementaryCP +OAI.Analysis.WeakInfiniteness.ElementaryComparison +OAI.Analysis.WeakInfiniteness.ElementaryIntertwining +OAI.Analysis.WeakInfiniteness.ExactHereditary +OAI.Analysis.WeakInfiniteness.ExactInfiniteness +OAI.Analysis.WeakInfiniteness.FaithfulContractions +OAI.Analysis.WeakInfiniteness.FaithfulRepresentation +OAI.Analysis.WeakInfiniteness.FaithfulTensorNorm +OAI.Analysis.WeakInfiniteness.FellAbsorption +OAI.Analysis.WeakInfiniteness.FinalAssembly +OAI.Analysis.WeakInfiniteness.FiniteComparison +OAI.Analysis.WeakInfiniteness.FiniteCoordinates +OAI.Analysis.WeakInfiniteness.FiniteCoupling +OAI.Analysis.WeakInfiniteness.FiniteDiagonalState +OAI.Analysis.WeakInfiniteness.FiniteGroupTensor +OAI.Analysis.WeakInfiniteness.FiniteReducingModels +OAI.Analysis.WeakInfiniteness.FiniteReducingModelsExtension +OAI.Analysis.WeakInfiniteness.FiniteSelection +OAI.Analysis.WeakInfiniteness.FiniteUnitaryLog +OAI.Analysis.WeakInfiniteness.FirstCoupling +OAI.Analysis.WeakInfiniteness.FixedColumns +OAI.Analysis.WeakInfiniteness.FixedRows +OAI.Analysis.WeakInfiniteness.FourColumnNorm +OAI.Analysis.WeakInfiniteness.FreeFiniteQuotients +OAI.Analysis.WeakInfiniteness.FreeFiniteRepresentations +OAI.Analysis.WeakInfiniteness.FreeTreeNormExtension +OAI.Analysis.WeakInfiniteness.FreeTwistedNorm +OAI.Analysis.WeakInfiniteness.FullGroupAlgebra +OAI.Analysis.WeakInfiniteness.FullGroupDensity +OAI.Analysis.WeakInfiniteness.GroupPolynomials +OAI.Analysis.WeakInfiniteness.GroupRegular +OAI.Analysis.WeakInfiniteness.HalfFlipCriterion +OAI.Analysis.WeakInfiniteness.HalfFlipGenerators +OAI.Analysis.WeakInfiniteness.Hereditary +OAI.Analysis.WeakInfiniteness.HereditaryDeletion +OAI.Analysis.WeakInfiniteness.IdealComparison +OAI.Analysis.WeakInfiniteness.IdealComparison2 +OAI.Analysis.WeakInfiniteness.IdealSeparation +OAI.Analysis.WeakInfiniteness.IdealSpan +OAI.Analysis.WeakInfiniteness.IndividualInfiniteness +OAI.Analysis.WeakInfiniteness.InnerNorm +OAI.Analysis.WeakInfiniteness.InnerSubalgebras +OAI.Analysis.WeakInfiniteness.Intertwining +OAI.Analysis.WeakInfiniteness.IntertwiningConstruction +OAI.Analysis.WeakInfiniteness.IntertwiningEquiv +OAI.Analysis.WeakInfiniteness.IntertwiningLimit +OAI.Analysis.WeakInfiniteness.InvariantSubspaces +OAI.Analysis.WeakInfiniteness.IrreducibleOrbits +OAI.Analysis.WeakInfiniteness.LiftedHilbert +OAI.Analysis.WeakInfiniteness.LocalCommon +OAI.Analysis.WeakInfiniteness.LocalConnection +OAI.Analysis.WeakInfiniteness.LocalConnection2 +OAI.Analysis.WeakInfiniteness.LocalFamily +OAI.Analysis.WeakInfiniteness.LocalPair +OAI.Analysis.WeakInfiniteness.LocalSplitting +OAI.Analysis.WeakInfiniteness.Main +OAI.Analysis.WeakInfiniteness.MapInner +OAI.Analysis.WeakInfiniteness.MatrixCutToolkit +OAI.Analysis.WeakInfiniteness.MatrixHilbert +OAI.Analysis.WeakInfiniteness.MatrixMaps +OAI.Analysis.WeakInfiniteness.MatrixRepresentation +OAI.Analysis.WeakInfiniteness.MatrixTensorCoordinates +OAI.Analysis.WeakInfiniteness.MatrixTensorExact +OAI.Analysis.WeakInfiniteness.NonUnitalClosedRange +OAI.Analysis.WeakInfiniteness.NonUnitalGroupTensor +OAI.Analysis.WeakInfiniteness.NonunitalCentralization +OAI.Analysis.WeakInfiniteness.NonunitalCoefficients +OAI.Analysis.WeakInfiniteness.NonunitalColumn +OAI.Analysis.WeakInfiniteness.NonunitalColumnApproximation +OAI.Analysis.WeakInfiniteness.NonunitalCompression +OAI.Analysis.WeakInfiniteness.NonunitalExactness +OAI.Analysis.WeakInfiniteness.NonunitalGram +OAI.Analysis.WeakInfiniteness.NonunitalHeredity +OAI.Analysis.WeakInfiniteness.NonunitalRealization +OAI.Analysis.WeakInfiniteness.NonunitalSchwarz +OAI.Analysis.WeakInfiniteness.NonunitalSpectralTools +OAI.Analysis.WeakInfiniteness.NonunitalSpectralTools2 +OAI.Analysis.WeakInfiniteness.NormKernelWitness +OAI.Analysis.WeakInfiniteness.NuclearApproximation +OAI.Analysis.WeakInfiniteness.NuclearCP +OAI.Analysis.WeakInfiniteness.NuclearCentralization +OAI.Analysis.WeakInfiniteness.NuclearCoefficients +OAI.Analysis.WeakInfiniteness.NuclearColumn +OAI.Analysis.WeakInfiniteness.NuclearColumnApproximation +OAI.Analysis.WeakInfiniteness.NuclearCompression +OAI.Analysis.WeakInfiniteness.NuclearExact +OAI.Analysis.WeakInfiniteness.NuclearTensorBound +OAI.Analysis.WeakInfiniteness.NuclearTensorMap +OAI.Analysis.WeakInfiniteness.OInfinityCriterion +OAI.Analysis.WeakInfiniteness.OInfinityMap +OAI.Analysis.WeakInfiniteness.OInfinityUniversal +OAI.Analysis.WeakInfiniteness.OperatorReducing +OAI.Analysis.WeakInfiniteness.OrthogonalCores +OAI.Analysis.WeakInfiniteness.OrthogonalPerturbation +OAI.Analysis.WeakInfiniteness.PairUnitary +OAI.Analysis.WeakInfiniteness.PerturbationRows +OAI.Analysis.WeakInfiniteness.Plateau +OAI.Analysis.WeakInfiniteness.PolarCFC +OAI.Analysis.WeakInfiniteness.PolynomialCompression +OAI.Analysis.WeakInfiniteness.PolynomialSpan +OAI.Analysis.WeakInfiniteness.PrimitiveCompactness +OAI.Analysis.WeakInfiniteness.PrimitiveIdealTest +OAI.Analysis.WeakInfiniteness.ProductRepresentation +OAI.Analysis.WeakInfiniteness.PureIrreducible +OAI.Analysis.WeakInfiniteness.PureStates +OAI.Analysis.WeakInfiniteness.QuantitativeAssembly +OAI.Analysis.WeakInfiniteness.QuantitativeSeparation +OAI.Analysis.WeakInfiniteness.RectangularCStar +OAI.Analysis.WeakInfiniteness.RectangularComparison +OAI.Analysis.WeakInfiniteness.RectangularPolar +OAI.Analysis.WeakInfiniteness.ReducedGroupAlgebra +OAI.Analysis.WeakInfiniteness.ReducedOperators +OAI.Analysis.WeakInfiniteness.ReducingColumns +OAI.Analysis.WeakInfiniteness.RelativeAveraging +OAI.Analysis.WeakInfiniteness.ScalarDiagonal +OAI.Analysis.WeakInfiniteness.ScalarHereditary +OAI.Analysis.WeakInfiniteness.ScalingAssembly +OAI.Analysis.WeakInfiniteness.SecondCoupling +OAI.Analysis.WeakInfiniteness.SelectedCoupling +OAI.Analysis.WeakInfiniteness.SeparatedSpectralWindows +OAI.Analysis.WeakInfiniteness.SeparatingPositivesProducer +OAI.Analysis.WeakInfiniteness.SeparationColumnBounds +OAI.Analysis.WeakInfiniteness.SeparationCoreSelection +OAI.Analysis.WeakInfiniteness.SeparationCores +OAI.Analysis.WeakInfiniteness.SeparationCoverage +OAI.Analysis.WeakInfiniteness.SeparationFourColumns +OAI.Analysis.WeakInfiniteness.SeparationMetric +OAI.Analysis.WeakInfiniteness.SeparationNormCoverage +OAI.Analysis.WeakInfiniteness.SeparationPreassembly +OAI.Analysis.WeakInfiniteness.SeparationScalar +OAI.Analysis.WeakInfiniteness.SeparationScalarBounds +OAI.Analysis.WeakInfiniteness.SeparationSupport +OAI.Analysis.WeakInfiniteness.SeparationTransferredCoverage +OAI.Analysis.WeakInfiniteness.SmallCStar +OAI.Analysis.WeakInfiniteness.SmallFree +OAI.Analysis.WeakInfiniteness.SmallPartition +OAI.Analysis.WeakInfiniteness.SpatialVectorStates +OAI.Analysis.WeakInfiniteness.SpectralCut +OAI.Analysis.WeakInfiniteness.SpectralDeletion +OAI.Analysis.WeakInfiniteness.SpectralResidual +OAI.Analysis.WeakInfiniteness.SpectralWindows +OAI.Analysis.WeakInfiniteness.SquareZero +OAI.Analysis.WeakInfiniteness.SquareZero2 +OAI.Analysis.WeakInfiniteness.SquareZero3 +OAI.Analysis.WeakInfiniteness.SquareZero4 +OAI.Analysis.WeakInfiniteness.SquareZero5 +OAI.Analysis.WeakInfiniteness.SquareZero6 +OAI.Analysis.WeakInfiniteness.SquareZeroComparison +OAI.Analysis.WeakInfiniteness.StatePullback +OAI.Analysis.WeakInfiniteness.States +OAI.Analysis.WeakInfiniteness.StrongInfiniteness +OAI.Analysis.WeakInfiniteness.StrongInfinitenessOne +OAI.Analysis.WeakInfiniteness.SupportedCorner +OAI.Analysis.WeakInfiniteness.SupportedExact +OAI.Analysis.WeakInfiniteness.SupportedSeparation +OAI.Analysis.WeakInfiniteness.TensorAbsorption +OAI.Analysis.WeakInfiniteness.TensorCompression +OAI.Analysis.WeakInfiniteness.TensorCut +OAI.Analysis.WeakInfiniteness.TensorDensity +OAI.Analysis.WeakInfiniteness.TensorFlip +OAI.Analysis.WeakInfiniteness.TensorFlipEquivalence +OAI.Analysis.WeakInfiniteness.TensorFoundations +OAI.Analysis.WeakInfiniteness.TensorFunctoriality +OAI.Analysis.WeakInfiniteness.TensorHilbertSum +OAI.Analysis.WeakInfiniteness.TensorIdealCut +OAI.Analysis.WeakInfiniteness.TensorIdealFunctional +OAI.Analysis.WeakInfiniteness.TensorInjectivity +OAI.Analysis.WeakInfiniteness.TensorMatrixNorm +OAI.Analysis.WeakInfiniteness.TensorMultiplier +OAI.Analysis.WeakInfiniteness.TensorNorm +OAI.Analysis.WeakInfiniteness.TensorSubalgebras +OAI.Analysis.WeakInfiniteness.ULiftCStar +OAI.Analysis.WeakInfiniteness.UniformGap +OAI.Analysis.WeakInfiniteness.UniformKernelConvergence +OAI.Analysis.WeakInfiniteness.UniformModels +OAI.Analysis.WeakInfiniteness.UniformPerturbation +OAI.Analysis.WeakInfiniteness.UnitalCuntzEmbedding +OAI.Analysis.WeakInfiniteness.UnitaryIntertwining +OAI.Analysis.WeakInfiniteness.UnitizationExact +OAI.Analysis.WeakInfiniteness.UnitizationTensor +OAI.Analysis.WeakInfiniteness.UniversalFreeEmbedding +OAI.Analysis.WeakInfiniteness.UniversalGroupEmbedding +OAI.Analysis.WeakInfiniteness.UniversalGroupMap +OAI.Analysis.WeakInfiniteness.UniversalGroupNorm +OAI.Analysis.WeakInfiniteness.UniversalMapping +OAI.Analysis.WeakInfiniteness.UniverseCoupling +OAI.Analysis.WeakInfiniteness.UniverseIndividualInfiniteness +OAI.Analysis.WeakInfiniteness.UniversePerturbation +OAI.Analysis.WeakInfiniteness.UniverseSelfadjoint +OAI.Analysis.WeakInfiniteness.UniverseSquareZero +OAI.Analysis.WeakInfiniteness.VectorStates +OAI.Analysis.WeakInfiniteness.WordCompression +OAI.Analysis.WeakInfiniteness.WordTensorDensity diff --git a/tasks/exact-infiniteness/solution/reference.py b/tasks/exact-infiniteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/exact-infiniteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/exact-infiniteness/solution/solve.sh b/tasks/exact-infiniteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a24ef3c092f4485e9c01658b5149bc70c4408d95 --- /dev/null +++ b/tasks/exact-infiniteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ExactInfiniteness, i.e. module OAI.Analysis.WeakInfiniteness.Main and the +# 1012 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.WeakInfiniteness.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ExactInfiniteness" diff --git a/tasks/exact-infiniteness/task.toml b/tasks/exact-infiniteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b0a508c7daf4e58eff27c1a742c917fc6e6afeab --- /dev/null +++ b/tasks/exact-infiniteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/exact-infiniteness" +version = "1.0.0" +description = "Prove ExactInfiniteness (openai/math family 303: From ordinary to strong pure infiniteness) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ExactInfiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ExactInfiniteness" +family = "303" +family_title = "From ordinary to strong pure infiniteness" +subject = "Operator algebras" +theorems = ["OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any", "OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_stronglyPurelyInfinite"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.WeakInfiniteness.Main" +reference_modules = 1012 +reference_lean_bytes = 6724441 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 4206 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17751 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/exact-infiniteness/tests/Challenge.lean b/tasks/exact-infiniteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..120a81f42019fbc086d9f87745be55952c81fe69 --- /dev/null +++ b/tasks/exact-infiniteness/tests/Challenge.lean @@ -0,0 +1,179 @@ +import Mathlib + +namespace OAI + +noncomputable section +universe u v +open scoped TensorProduct ENNReal ComplexOrder +open UniformSpace +namespace WeakPureInfiniteness + +section CompletedOperators + +variable {domain codomain : Type*} + [NormedAddCommGroup domain] [NormedSpace ℂ domain] + [NormedAddCommGroup codomain] [NormedSpace ℂ codomain] + +lemma norm_completion_le (operator : domain →L[ℂ] codomain) : + ‖operator.completion‖ ≤ ‖operator‖ := by + apply ContinuousLinearMap.opNorm_le_bound _ (norm_nonneg operator) + intro vector + induction vector using Completion.induction_on with + | hp => exact isClosed_le (by fun_prop) (by fun_prop) + | ih vector => simpa using operator.le_opNorm vector + +lemma norm_completion (operator : domain →L[ℂ] codomain) : + ‖operator.completion‖ = ‖operator‖ := by + apply le_antisymm (norm_completion_le operator) + apply ContinuousLinearMap.opNorm_le_bound _ (norm_nonneg _) + intro vector + simpa using operator.completion.le_opNorm (vector : Completion domain) + +end CompletedOperators + +structure ComplexHilbert where + Carrier : Type u + [normedAddCommGroup : NormedAddCommGroup Carrier] + [innerProductSpace : InnerProductSpace ℂ Carrier] + [completeSpace : CompleteSpace Carrier] + +attribute [instance] ComplexHilbert.normedAddCommGroup + ComplexHilbert.innerProductSpace ComplexHilbert.completeSpace +instance : CoeSort ComplexHilbert.{u} (Type u) := ⟨ComplexHilbert.Carrier⟩ + +instance completedTensorCStar (H K : ComplexHilbert.{u}) : + CStarAlgebra (Completion (H ⊗[ℂ] K) →L[ℂ] Completion (H ⊗[ℂ] K)) := inferInstance + +instance hilbertOperatorsCStar (H : ComplexHilbert.{u}) : + CStarAlgebra (H →L[ℂ] H) := inferInstance + +structure SpatialRepresentation (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] where + left : ComplexHilbert.{max u v} + right : ComplexHilbert.{max u v} + leftRep : A →⋆ₙₐ[ℂ] (left →L[ℂ] left) + rightRep : B →⋆ₙₐ[ℂ] (right →L[ℂ] right) + +abbrev SpatialRepresentation.hilbert {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (π : SpatialRepresentation A B) : ComplexHilbert.{max u v} where + Carrier := Completion (π.left ⊗[ℂ] π.right) + +abbrev SpatialRepresentation.space {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (π : SpatialRepresentation A B) := Completion (π.left ⊗[ℂ] π.right) + +def SpatialAmbient (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : Type (max u v + 1) := + lp (fun π : SpatialRepresentation A B => π.space →L[ℂ] π.space) ∞ + +instance spatialAmbientCStar (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalCStarAlgebra (SpatialAmbient A B) := by + unfold SpatialAmbient + infer_instance + +instance spatialAmbientCoeFun (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + CoeFun (SpatialAmbient A B) (fun _ => ∀ π : SpatialRepresentation A B, π.space →L[ℂ] π.space) := + ⟨fun z => z.val⟩ + +def spatialElementary {A : Type u} {B : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] + (a : A) (b : B) : SpatialAmbient A B := + ⟨fun π => (TensorProduct.mapL (π.leftRep a) (π.rightRep b)).completion, + memℓp_infty ⟨‖a‖ * ‖b‖, by + rintro _ ⟨π, rfl⟩ + dsimp only + rw [norm_completion] + exact (TensorProduct.norm_mapL_le _ _).trans + (mul_le_mul (NonUnitalStarAlgHom.norm_apply_le π.leftRep a) (NonUnitalStarAlgHom.norm_apply_le π.rightRep b) + (norm_nonneg _) (norm_nonneg _))⟩⟩ + +def minimalTensorSubalgebra (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalStarSubalgebra ℂ (SpatialAmbient A B) := + (NonUnitalStarAlgebra.adjoin ℂ (Set.range fun p : A × B => spatialElementary p.1 p.2)).topologicalClosure + +abbrev MinimalTensor (A : Type u) (B : Type v) + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] := minimalTensorSubalgebra A B + +instance (A : Type u) (B : Type v) [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra B] : + NonUnitalCStarAlgebra (MinimalTensor A B) := by + letI : IsClosed ((minimalTensorSubalgebra A B : NonUnitalStarSubalgebra ℂ + (SpatialAmbient A B)) : Set (SpatialAmbient A B)) := + isClosed_closure + exact inferInstance + +section Exactness + +variable {A : Type u} {C D : Type v} + [NonUnitalCStarAlgebra A] [NonUnitalCStarAlgebra C] [NonUnitalCStarAlgebra D] + +def SpatialRepresentation.precompRight (π : SpatialRepresentation A D) + (q : C →⋆ₙₐ[ℂ] D) : SpatialRepresentation A C where + left := π.left + right := π.right + leftRep := π.leftRep + rightRep := π.rightRep.comp q + +def tensorKernelIdeal (q : C →⋆ₙₐ[ℂ] D) : NonUnitalStarSubalgebra ℂ (SpatialAmbient A C) := + (NonUnitalStarAlgebra.adjoin ℂ + {z | ∃ a : A, ∃ c : C, q c = 0 ∧ z = spatialElementary a c}).topologicalClosure + +end Exactness + +def Exact (A : Type u) [NonUnitalCStarAlgebra A] : Prop := + ∀ (C D : Type u) [NonUnitalCStarAlgebra C] [NonUnitalCStarAlgebra D] + (q : C →⋆ₙₐ[ℂ] D), Function.Surjective q → + ∀ z : MinimalTensor A C, + (∀ π : SpatialRepresentation A D, (z.val : SpatialAmbient A C) (π.precompRight q) = 0) → + z.val ∈ tensorKernelIdeal (A := A) q + +section Definitions + +variable {A : Type*} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] +variable {m k : Type*} [Fintype m] [Fintype k] + +def CuntzSubequiv (a : CStarMatrix m m A) (b : CStarMatrix k k A) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ v : CStarMatrix k m A, ‖v.conjTranspose * b * v - a‖ < ε + +def blockSum (a : CStarMatrix m m A) (b : CStarMatrix k k A) : + CStarMatrix (m ⊕ k) (m ⊕ k) A := + CStarMatrix.ofMatrix (Matrix.fromBlocks (CStarMatrix.ofMatrix.symm a) 0 0 + (CStarMatrix.ofMatrix.symm b)) + +def ProperlyInfinite (a : CStarMatrix m m A) : Prop := + CuntzSubequiv (blockSum a a) a + +def diagonalCopies (n : ℕ) (a : A) : CStarMatrix (Fin n) (Fin n) A := + CStarMatrix.ofMatrix (Matrix.diagonal fun _ => a) + +variable (A) + +def WeaklyPurelyInfinite : Prop := + ∃ n : ℕ, 1 ≤ n ∧ ∀ a : A, 0 ≤ a → a ≠ 0 → ProperlyInfinite (diagonalCopies n a) + +def StronglyPurelyInfinite : Prop := + ∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ ε : ℝ, 0 < ε → + ∃ s t : A, ‖star s * (a * a) * s - a * a‖ < ε ∧ + ‖star t * (b * b) * t - b * b‖ < ε ∧ ‖star s * a * b * t‖ < ε + +end Definitions + +theorem exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any + {A : Type u} [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + (hA : Exact A) (hW : WeaklyPurelyInfinite A) {a : A} (ha : 0 ≤ a) : + ProperlyInfinite (diagonalCopies 1 a) := by + sorry + +theorem exact_weaklyPurelyInfinite_stronglyPurelyInfinite + (A : Type u) [NonUnitalCStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + (hExact : Exact A) (hWeak : WeaklyPurelyInfinite A) : StronglyPurelyInfinite A := by + sorry + +end WeakPureInfiniteness + +end + +end OAI diff --git a/tasks/exact-infiniteness/tests/grade.py b/tasks/exact-infiniteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/exact-infiniteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/exact-infiniteness/tests/task.json b/tasks/exact-infiniteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fb2c2b505e6046eae9dd64292fb99d116bfbc6c6 --- /dev/null +++ b/tasks/exact-infiniteness/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "ExactInfiniteness", + "comparator": { + "theorem_names": [ + "OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_individuallyProperlyInfinite_any", + "OAI.WeakPureInfiniteness.exact_weaklyPurelyInfinite_stronglyPurelyInfinite" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16851 +} \ No newline at end of file diff --git a/tasks/exact-infiniteness/tests/test.sh b/tasks/exact-infiniteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/exact-infiniteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/exact-quantum-factoring/environment/Dockerfile b/tasks/exact-quantum-factoring/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/exact-quantum-factoring/environment/fetch_mathlib.sh b/tasks/exact-quantum-factoring/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/exact-quantum-factoring/environment/lake-manifest.json b/tasks/exact-quantum-factoring/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/exact-quantum-factoring/environment/lakefile.lean b/tasks/exact-quantum-factoring/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/exact-quantum-factoring/environment/lean_setup.sh b/tasks/exact-quantum-factoring/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/exact-quantum-factoring/environment/pack_submission.py b/tasks/exact-quantum-factoring/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/exact-quantum-factoring/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/exact-quantum-factoring/instruction.md b/tasks/exact-quantum-factoring/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..00fab0fc0ef33c2c56d01760973419227936bc5e --- /dev/null +++ b/tasks/exact-quantum-factoring/instruction.md @@ -0,0 +1,205 @@ +# openai/math challenge `ExactQuantumFactoring` (family 279) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 279 of the release, *Exact quantum factoring over a fixed finite gate set* +(Mathematical physics). The family as a whole: Gives a polynomial-time uniform quantum circuit family that outputs the complete prime factorization of every integer with probability one. Both gate count and qubit count are polynomial in the input length, and one fixed finite gate set suffices. + +The challenge is `ExactQuantumFactoring`, also at `/opt/openai-math/challenges/ExactQuantumFactoring.lean`: + +```lean +import Mathlib + +namespace OAI + + + +namespace ExactQuantumFactoring + +open scoped BigOperators + +/-- The five primitive gates exactly as in Section 2. -/ +inductive Primitive where + | not | cnot | toffoli | hadamard | phase + deriving DecidableEq + +def Primitive.arity : Primitive → ℕ + | .not | .hadamard | .phase => 1 + | .cnot => 2 + | .toffoli => 3 + +def Primitive.code : Primitive → ℕ + | .not => 0 | .cnot => 1 | .toffoli => 2 | .hadamard => 3 | .phase => 4 + +/-- An inverse and/or one added control. This is a fixed set of 20 gate names, +not an unbounded-control or arbitrary-angle gate model. -/ +structure Gate where + primitive : Primitive + inverse : Bool + controlled : Bool + deriving DecidableEq + +def Gate.arity (g : Gate) : ℕ := g.primitive.arity + if g.controlled then 1 else 0 + +/-- Matrix entries are indexed by lists in wire order (row first, column second). +Entries on ill-sized lists are irrelevant and set to zero. -/ +noncomputable def Primitive.matrix : Primitive → List Bool → List Bool → ℂ + | .not, [a], [b] => if a = !b then 1 else 0 + | .cnot, [a,b], [c,d] => if a = c ∧ b = Bool.xor c d then 1 else 0 + | .toffoli, [a,b,c], [d,e,f] => + if a = d ∧ b = e ∧ c = Bool.xor f (d && e) then 1 else 0 + | .hadamard, [a], [b] => + (if a && b then -1 else 1) / (Real.sqrt 2 : ℂ) + | .phase, [a], [b] => if a = b then (if b then Complex.I else 1) else 0 + | _, _, _ => 0 + +noncomputable def Gate.baseMatrix (g : Gate) (a b : List Bool) : ℂ := + if g.inverse then star (g.primitive.matrix b a) else g.primitive.matrix a b + +noncomputable def Gate.matrix (g : Gate) (a b : List Bool) : ℂ := + if g.controlled then + match a, b with + | false :: a', false :: b' => if a' = b' then 1 else 0 + | true :: a', true :: b' => g.baseMatrix a' b' + | _, _ => 0 + else g.baseMatrix a b + +/-- A primitive is placed on distinct actual wires, with no operation of +unbounded arity hidden in a circuit instruction. -/ +structure Instruction (q : ℕ) where + gate : Gate + wire : Fin gate.arity → Fin q + distinct : Function.Injective wire + +abbrev Basis (q : ℕ) := Fin q → Bool +abbrev State (q : ℕ) := Basis q → ℂ + +noncomputable def Instruction.matrix {q : ℕ} (o : Instruction q) : + Matrix (Basis q) (Basis q) ℂ := by + classical + exact fun a b => + if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → a i = b i then + o.gate.matrix (List.ofFn (a ∘ o.wire)) (List.ofFn (b ∘ o.wire)) + else 0 + +structure Circuit where + qubits : ℕ + instructions : List (Instruction qubits) + +noncomputable def Circuit.apply (c : Circuit) (ψ : State c.qubits) : State c.qubits := + c.instructions.foldl (fun v o => o.matrix.mulVec v) ψ + +/-- Input wires are first, least significant bit first; all other wires start zero. -/ +def inputBasis (q ℓ N : ℕ) : Basis q := + fun i => if i.val < ℓ then N.testBit i.val else false + +noncomputable def Circuit.outputState (c : Circuit) (ℓ N : ℕ) : State c.qubits := by + classical + exact c.apply (fun x => if x = inputBasis c.qubits ℓ N then 1 else 0) + +/-- The cutoff and padding are the standing parameters in Section 2. -/ +def paddedLength (ℓ : ℕ) : ℕ := max 128 ℓ + +def readBit {q : ℕ} (x : Basis q) (i : ℕ) : Bool := + if h : i < q then x ⟨i,h⟩ else false + +/-- n entries of n bits each, in the n² wires immediately after the input. -/ +def outputList {q : ℕ} (ℓ : ℕ) (x : Basis q) : List ℕ := + let n := paddedLength ℓ + List.ofFn (fun a : Fin n => + ∑ j ∈ Finset.range n, if readBit x (ℓ + a.val * n + j) then 2^j else 0) + +/-- Complete nondecreasing prime factorization, multiplicities included, +padded by zeros, as in Section 6. There is no primality oracle in the circuit. -/ +def CorrectEncoding (N n : ℕ) (xs : List ℕ) : Prop := + ∃ ps : List ℕ, (∀ p ∈ ps, Nat.Prime p) ∧ ps.Pairwise (· ≤ ·) ∧ + ps.prod = N ∧ ps.length ≤ n ∧ xs = ps ++ List.replicate (n - ps.length) 0 + +/-- Unnormalized Born sum on correct outputs; success is exactly one, +not positivity, postselection, or a limiting high probability. -/ +noncomputable def Circuit.correctProbability (c : Circuit) (ℓ N : ℕ) : ℝ := by + classical + exact ∑ x : Basis c.qubits, + if CorrectEncoding N (paddedLength ℓ) (outputList ℓ x) then + Complex.normSq (c.outputState ℓ N x) else 0 + +/-- Unary natural words with delimiters make the circuit description explicit. +Unary wire addresses cause at most polynomial overhead when width is polynomial. -/ +def natWord (k : ℕ) : List Bool := List.replicate k true ++ [false] + +def Instruction.encode {q : ℕ} (o : Instruction q) : List Bool := + natWord o.gate.primitive.code ++ [o.gate.inverse, o.gate.controlled] ++ + (List.ofFn (fun i => o.wire i |>.val)).flatMap natWord + +def Circuit.encode (c : Circuit) : List Bool := + natWord c.qubits ++ natWord c.instructions.length ++ + c.instructions.flatMap Instruction.encode + +/-- A single finite-alphabet classical generator receives only the INPUT LENGTH. +All stack alphabets, states and labels are finite: no large-integer unit-cost +oracle is hidden in TM2 push/branch functions. -/ +def Uniform (family : ℕ → Circuit) : Prop := + ∃ generator : Turing.TM2ComputableInPolyTime + (fun ℓ => List.replicate ℓ true) Circuit.encode family, + ∀ k, Finite (generator.tm.Γ k) + +def PolynomialResources (family : ℕ → Circuit) : Prop := + ∃ bound : Polynomial ℕ, ∀ ℓ, + (family ℓ).qubits ≤ bound.eval ℓ ∧ + (family ℓ).instructions.length ≤ bound.eval ℓ + +/-- Literal main endpoint: one length-uniform family, exact output for EVERY +binary integer N≥2, and worst-case polynomial gates AND qubits. -/ +def MainTheorem : Prop := + ∃ family : ℕ → Circuit, Uniform family ∧ PolynomialResources family ∧ + ∀ (ℓ N : ℕ), 2 ≤ N → N.size = ℓ → + ℓ + (paddedLength ℓ)^2 ≤ (family ℓ).qubits ∧ + (family ℓ).correctProbability ℓ N = 1 + +theorem exact_quantum_factoring : MainTheorem := by + sorry + +end ExactQuantumFactoring + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ExactQuantumFactoring.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ExactQuantumFactoring.exact_quantum_factoring` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/exact-quantum-factoring/solution/closure.txt b/tasks/exact-quantum-factoring/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..85cd6010da660278eb20bbb416fefcf3a395b48f --- /dev/null +++ b/tasks/exact-quantum-factoring/solution/closure.txt @@ -0,0 +1,546 @@ +OAI.Computability.QuantumFactoring.AIGBitArithmeticEmission +OAI.Computability.QuantumFactoring.AIGBounds +OAI.Computability.QuantumFactoring.AIGCompiler +OAI.Computability.QuantumFactoring.AIGDivisionBounds +OAI.Computability.QuantumFactoring.AIGInputs +OAI.Computability.QuantumFactoring.AIGNetworkEmission +OAI.Computability.QuantumFactoring.AIGNetworkProcedure +OAI.Computability.QuantumFactoring.AKSBounds +OAI.Computability.QuantumFactoring.AKSCriteria +OAI.Computability.QuantumFactoring.AKSNetworks +OAI.Computability.QuantumFactoring.ActualDivisorPolynomial +OAI.Computability.QuantumFactoring.AdaptivePrepared +OAI.Computability.QuantumFactoring.AppendRegister +OAI.Computability.QuantumFactoring.ArithmeticBounds +OAI.Computability.QuantumFactoring.ArithmeticPredicates +OAI.Computability.QuantumFactoring.ArithmeticSyntaxEmission +OAI.Computability.QuantumFactoring.AuxiliaryData +OAI.Computability.QuantumFactoring.AuxiliaryProducer +OAI.Computability.QuantumFactoring.AuxiliaryTree +OAI.Computability.QuantumFactoring.Basic +OAI.Computability.QuantumFactoring.BinLabelCircuit +OAI.Computability.QuantumFactoring.BinaryRoots +OAI.Computability.QuantumFactoring.BitArithmetic +OAI.Computability.QuantumFactoring.BitArithmeticDivision +OAI.Computability.QuantumFactoring.BitEncoding +OAI.Computability.QuantumFactoring.BitNumbers +OAI.Computability.QuantumFactoring.BitResidue +OAI.Computability.QuantumFactoring.BitStackAdder +OAI.Computability.QuantumFactoring.BitStackAssociation +OAI.Computability.QuantumFactoring.BitStackBasicProcedures +OAI.Computability.QuantumFactoring.BitStackBinaryBasics +OAI.Computability.QuantumFactoring.BitStackBooleans +OAI.Computability.QuantumFactoring.BitStackBoundedPrime +OAI.Computability.QuantumFactoring.BitStackBoundedUnary +OAI.Computability.QuantumFactoring.BitStackChoice +OAI.Computability.QuantumFactoring.BitStackComposition +OAI.Computability.QuantumFactoring.BitStackConstants +OAI.Computability.QuantumFactoring.BitStackDependentChoice +OAI.Computability.QuantumFactoring.BitStackDivision +OAI.Computability.QuantumFactoring.BitStackFold +OAI.Computability.QuantumFactoring.BitStackFrames +OAI.Computability.QuantumFactoring.BitStackGCD +OAI.Computability.QuantumFactoring.BitStackIncrement +OAI.Computability.QuantumFactoring.BitStackIntegers +OAI.Computability.QuantumFactoring.BitStackIteration +OAI.Computability.QuantumFactoring.BitStackListCode +OAI.Computability.QuantumFactoring.BitStackListFlatten +OAI.Computability.QuantumFactoring.BitStackListFold +OAI.Computability.QuantumFactoring.BitStackListIndex +OAI.Computability.QuantumFactoring.BitStackListLength +OAI.Computability.QuantumFactoring.BitStackListMapIdx +OAI.Computability.QuantumFactoring.BitStackListMapWith +OAI.Computability.QuantumFactoring.BitStackListOps +OAI.Computability.QuantumFactoring.BitStackListWords +OAI.Computability.QuantumFactoring.BitStackLists +OAI.Computability.QuantumFactoring.BitStackMultiplier +OAI.Computability.QuantumFactoring.BitStackNaturals +OAI.Computability.QuantumFactoring.BitStackOptions +OAI.Computability.QuantumFactoring.BitStackPowers +OAI.Computability.QuantumFactoring.BitStackProcedures +OAI.Computability.QuantumFactoring.BitStackProducts +OAI.Computability.QuantumFactoring.BitStackPrograms +OAI.Computability.QuantumFactoring.BitStackQuotation +OAI.Computability.QuantumFactoring.BitStackRationalDivision +OAI.Computability.QuantumFactoring.BitStackRationalFloor +OAI.Computability.QuantumFactoring.BitStackRationalPower +OAI.Computability.QuantumFactoring.BitStackRationals +OAI.Computability.QuantumFactoring.BitStackRelabel +OAI.Computability.QuantumFactoring.BitStackSubtractor +OAI.Computability.QuantumFactoring.BitStackSumInjection +OAI.Computability.QuantumFactoring.BitStackSums +OAI.Computability.QuantumFactoring.BitStackTabulate +OAI.Computability.QuantumFactoring.BitStackTestBit +OAI.Computability.QuantumFactoring.BitStackUnary +OAI.Computability.QuantumFactoring.BitStackWords +OAI.Computability.QuantumFactoring.BooleanAlgebra +OAI.Computability.QuantumFactoring.BooleanCircuit +OAI.Computability.QuantumFactoring.BooleanFold +OAI.Computability.QuantumFactoring.BooleanNetwork +OAI.Computability.QuantumFactoring.BooleanNetworkFurther +OAI.Computability.QuantumFactoring.BooleanOracle +OAI.Computability.QuantumFactoring.BooleanProgram +OAI.Computability.QuantumFactoring.BooleanVector +OAI.Computability.QuantumFactoring.BoundedAKS +OAI.Computability.QuantumFactoring.BoundedStack +OAI.Computability.QuantumFactoring.CRTLevels +OAI.Computability.QuantumFactoring.CanonicalResidueCircuit +OAI.Computability.QuantumFactoring.CanonicalTableEmission +OAI.Computability.QuantumFactoring.CanonicalTransition +OAI.Computability.QuantumFactoring.CanonicalWords +OAI.Computability.QuantumFactoring.ChildQueue +OAI.Computability.QuantumFactoring.ChildQueueBounds +OAI.Computability.QuantumFactoring.ChildQueueCorrect +OAI.Computability.QuantumFactoring.ChildQueueEmission +OAI.Computability.QuantumFactoring.CircuitBooleanEmission +OAI.Computability.QuantumFactoring.CircuitCleanEmission +OAI.Computability.QuantumFactoring.CircuitEmissionBasic +OAI.Computability.QuantumFactoring.CircuitEmissionEncoding +OAI.Computability.QuantumFactoring.CircuitEmissionModel +OAI.Computability.QuantumFactoring.CircuitEncodingSize +OAI.Computability.QuantumFactoring.CircuitFinalEmission +OAI.Computability.QuantumFactoring.CircuitPreparationEmission +OAI.Computability.QuantumFactoring.CircuitProgramEmission +OAI.Computability.QuantumFactoring.CircuitRecursionEmission +OAI.Computability.QuantumFactoring.CircuitSemantics +OAI.Computability.QuantumFactoring.CleanPermutation +OAI.Computability.QuantumFactoring.CleanPermutationEmission +OAI.Computability.QuantumFactoring.ClosedLevelCircuit +OAI.Computability.QuantumFactoring.CoherentSampling +OAI.Computability.QuantumFactoring.CompletedOrderSlots +OAI.Computability.QuantumFactoring.CompletedSplit +OAI.Computability.QuantumFactoring.CompletionEmission +OAI.Computability.QuantumFactoring.CompletionFilterCircuit +OAI.Computability.QuantumFactoring.CompletionFilterPolynomial +OAI.Computability.QuantumFactoring.CompletionPredicateCircuit +OAI.Computability.QuantumFactoring.CompletionPredicateEmission +OAI.Computability.QuantumFactoring.CompletionPreparationEmission +OAI.Computability.QuantumFactoring.ComponentLevelEmission +OAI.Computability.QuantumFactoring.ComponentPhiCircuit +OAI.Computability.QuantumFactoring.ConcreteExpressionResources +OAI.Computability.QuantumFactoring.ContinuedFractionCircuit +OAI.Computability.QuantumFactoring.ContinuedFractionEmission +OAI.Computability.QuantumFactoring.ContinuedFractionPairs +OAI.Computability.QuantumFactoring.ContinuedFractionRecovery +OAI.Computability.QuantumFactoring.ControlledHadamard +OAI.Computability.QuantumFactoring.ControlledTranslation +OAI.Computability.QuantumFactoring.ControllerQueries +OAI.Computability.QuantumFactoring.CoveringPowerEmission +OAI.Computability.QuantumFactoring.CyclicAlgebra +OAI.Computability.QuantumFactoring.CyclicCircuit +OAI.Computability.QuantumFactoring.CyclicConstants +OAI.Computability.QuantumFactoring.CyclicEmission +OAI.Computability.QuantumFactoring.CyclicPowerCircuit +OAI.Computability.QuantumFactoring.CyclicPowerEmission +OAI.Computability.QuantumFactoring.CyclicPrimality +OAI.Computability.QuantumFactoring.CyclicTestBounds +OAI.Computability.QuantumFactoring.CyclicTestCircuit +OAI.Computability.QuantumFactoring.CyclicTestEmission +OAI.Computability.QuantumFactoring.DescendingFilter +OAI.Computability.QuantumFactoring.DescendingFilterEmission +OAI.Computability.QuantumFactoring.DescendingPrefixAutomatic +OAI.Computability.QuantumFactoring.DescendingStepEmission +OAI.Computability.QuantumFactoring.DistinctProductCircuit +OAI.Computability.QuantumFactoring.DistinctProductEmission +OAI.Computability.QuantumFactoring.DivisorData +OAI.Computability.QuantumFactoring.DyadicCompletion +OAI.Computability.QuantumFactoring.DynamicMajorantExpressions +OAI.Computability.QuantumFactoring.Emission +OAI.Computability.QuantumFactoring.EmissionBoundedRecursion +OAI.Computability.QuantumFactoring.EmissionCombinators +OAI.Computability.QuantumFactoring.EmissionDependentLists +OAI.Computability.QuantumFactoring.EmissionFurther +OAI.Computability.QuantumFactoring.EmissionFurther2 +OAI.Computability.QuantumFactoring.EmissionGeneralStages +OAI.Computability.QuantumFactoring.EmissionLengthBounds +OAI.Computability.QuantumFactoring.EmissionLists +OAI.Computability.QuantumFactoring.EmissionPolynomialUnary +OAI.Computability.QuantumFactoring.Emits +OAI.Computability.QuantumFactoring.EncodedStates +OAI.Computability.QuantumFactoring.Exactness +OAI.Computability.QuantumFactoring.ExactnessFurther +OAI.Computability.QuantumFactoring.ExactnessFurther2 +OAI.Computability.QuantumFactoring.ExpressionAt +OAI.Computability.QuantumFactoring.ExpressionPostfix +OAI.Computability.QuantumFactoring.ExpressionPowerEmission +OAI.Computability.QuantumFactoring.ExpressionPredicates +OAI.Computability.QuantumFactoring.ExpressionResources +OAI.Computability.QuantumFactoring.ExpressionSharing +OAI.Computability.QuantumFactoring.ExpressionSyntaxEmission +OAI.Computability.QuantumFactoring.ExpressionTemplateCircuit +OAI.Computability.QuantumFactoring.ExpressionTemplateEmission +OAI.Computability.QuantumFactoring.ExpressionTokenProcedure +OAI.Computability.QuantumFactoring.FactorController +OAI.Computability.QuantumFactoring.FactorEncoding +OAI.Computability.QuantumFactoring.FactorGuess +OAI.Computability.QuantumFactoring.FactorSplitting +OAI.Computability.QuantumFactoring.FactorVerifier +OAI.Computability.QuantumFactoring.FactorVerifierBounds +OAI.Computability.QuantumFactoring.FactorVerifierEmission +OAI.Computability.QuantumFactoring.FactoringCircuit +OAI.Computability.QuantumFactoring.FactoringInputLayout +OAI.Computability.QuantumFactoring.FactoringRelabel +OAI.Computability.QuantumFactoring.FairLabelMass +OAI.Computability.QuantumFactoring.FairOracle +OAI.Computability.QuantumFactoring.FavorableSplit +OAI.Computability.QuantumFactoring.FilterExpressionSyntax +OAI.Computability.QuantumFactoring.FinalPolynomialResources +OAI.Computability.QuantumFactoring.FinalUniformity +OAI.Computability.QuantumFactoring.FirstProperEmission +OAI.Computability.QuantumFactoring.FixedSplit +OAI.Computability.QuantumFactoring.FlatDataPredicates +OAI.Computability.QuantumFactoring.FlatDataView +OAI.Computability.QuantumFactoring.FlatLookupCircuit +OAI.Computability.QuantumFactoring.FlatVerifiedData +OAI.Computability.QuantumFactoring.GateSemantics +OAI.Computability.QuantumFactoring.GcdCircuit +OAI.Computability.QuantumFactoring.GcdEmission +OAI.Computability.QuantumFactoring.HadamardAction +OAI.Computability.QuantumFactoring.HardCofactor +OAI.Computability.QuantumFactoring.HardFilterCircuit +OAI.Computability.QuantumFactoring.HornerEncoding +OAI.Computability.QuantumFactoring.InitialOrderState +OAI.Computability.QuantumFactoring.IntegerExpressions +OAI.Computability.QuantumFactoring.LabelRecoveryCircuit +OAI.Computability.QuantumFactoring.LabelRecoveryEmission +OAI.Computability.QuantumFactoring.LabelValidationCircuit +OAI.Computability.QuantumFactoring.LevelBounds +OAI.Computability.QuantumFactoring.LevelCounts +OAI.Computability.QuantumFactoring.LevelIndependence +OAI.Computability.QuantumFactoring.ListSamplerCircuit +OAI.Computability.QuantumFactoring.ListSamplerEmission +OAI.Computability.QuantumFactoring.ListTransition +OAI.Computability.QuantumFactoring.LoggedExecution +OAI.Computability.QuantumFactoring.MachineInitialization +OAI.Computability.QuantumFactoring.MachineWiringEmission +OAI.Computability.QuantumFactoring.Main +OAI.Computability.QuantumFactoring.MajorantTemplateEmission +OAI.Computability.QuantumFactoring.MaskedPreparation +OAI.Computability.QuantumFactoring.MinimumCandidateCircuit +OAI.Computability.QuantumFactoring.ModularMultiply +OAI.Computability.QuantumFactoring.ModularPower +OAI.Computability.QuantumFactoring.ModularSumEmission +OAI.Computability.QuantumFactoring.NativeAIGAdd +OAI.Computability.QuantumFactoring.NativeAIGAddBounded +OAI.Computability.QuantumFactoring.NativeAIGAddProcedure +OAI.Computability.QuantumFactoring.NativeAIGAddWrapper +OAI.Computability.QuantumFactoring.NativeAIGBinaryInputs +OAI.Computability.QuantumFactoring.NativeAIGBoolean +OAI.Computability.QuantumFactoring.NativeAIGBounds +OAI.Computability.QuantumFactoring.NativeAIGCarry +OAI.Computability.QuantumFactoring.NativeAIGCarryProcedure +OAI.Computability.QuantumFactoring.NativeAIGDiv +OAI.Computability.QuantumFactoring.NativeAIGDivBounded +OAI.Computability.QuantumFactoring.NativeAIGDivOperations +OAI.Computability.QuantumFactoring.NativeAIGDivProcedure +OAI.Computability.QuantumFactoring.NativeAIGDivWrapper +OAI.Computability.QuantumFactoring.NativeAIGEqProcedure +OAI.Computability.QuantumFactoring.NativeAIGExtend +OAI.Computability.QuantumFactoring.NativeAIGFullAdder +OAI.Computability.QuantumFactoring.NativeAIGGateProcedure +OAI.Computability.QuantumFactoring.NativeAIGIf +OAI.Computability.QuantumFactoring.NativeAIGIfProcedure +OAI.Computability.QuantumFactoring.NativeAIGInputs +OAI.Computability.QuantumFactoring.NativeAIGKnownProcedure +OAI.Computability.QuantumFactoring.NativeAIGMod +OAI.Computability.QuantumFactoring.NativeAIGModWrapper +OAI.Computability.QuantumFactoring.NativeAIGModel +OAI.Computability.QuantumFactoring.NativeAIGMul +OAI.Computability.QuantumFactoring.NativeAIGMulBounded +OAI.Computability.QuantumFactoring.NativeAIGMulProcedure +OAI.Computability.QuantumFactoring.NativeAIGMulWrapper +OAI.Computability.QuantumFactoring.NativeAIGNot +OAI.Computability.QuantumFactoring.NativeAIGProcedures +OAI.Computability.QuantumFactoring.NativeAIGShift +OAI.Computability.QuantumFactoring.NativeAIGSub +OAI.Computability.QuantumFactoring.NativeAIGSubProcedure +OAI.Computability.QuantumFactoring.NativeAIGVector +OAI.Computability.QuantumFactoring.NativeAIGVectorBounds +OAI.Computability.QuantumFactoring.NativeAIGZipFold +OAI.Computability.QuantumFactoring.NativeAIGZipFoldProcedure +OAI.Computability.QuantumFactoring.NaturalExpressionCircuit +OAI.Computability.QuantumFactoring.NaturalExpressions +OAI.Computability.QuantumFactoring.NetworkAt +OAI.Computability.QuantumFactoring.NetworkAtArithmetic +OAI.Computability.QuantumFactoring.NetworkCanonicalEmission +OAI.Computability.QuantumFactoring.NetworkDependentEmission +OAI.Computability.QuantumFactoring.NetworkEmissionBasic +OAI.Computability.QuantumFactoring.NetworkEmissionBounds +OAI.Computability.QuantumFactoring.NetworkEmissionCombinators +OAI.Computability.QuantumFactoring.NetworkEmissionModel +OAI.Computability.QuantumFactoring.NetworkEmissionPack +OAI.Computability.QuantumFactoring.NetworkEmissionPair +OAI.Computability.QuantumFactoring.NetworkEmissionProcedures +OAI.Computability.QuantumFactoring.NetworkEmissionRewire +OAI.Computability.QuantumFactoring.NetworkEmissionVector +OAI.Computability.QuantumFactoring.NetworkEmissionWords +OAI.Computability.QuantumFactoring.NetworkExpressionEmission +OAI.Computability.QuantumFactoring.NetworkFiniteExpressionEmission +OAI.Computability.QuantumFactoring.NetworkFoldChoiceEmission +OAI.Computability.QuantumFactoring.NetworkIndexedEmission +OAI.Computability.QuantumFactoring.NetworkListEmission +OAI.Computability.QuantumFactoring.NetworkListOperationsEmission +OAI.Computability.QuantumFactoring.NetworkLoopEmission +OAI.Computability.QuantumFactoring.NetworkModularEmission +OAI.Computability.QuantumFactoring.NetworkModularPowerEmission +OAI.Computability.QuantumFactoring.NetworkPoly +OAI.Computability.QuantumFactoring.NetworkPolyResources +OAI.Computability.QuantumFactoring.NetworkPredicateEmission +OAI.Computability.QuantumFactoring.NetworkRecursionEmission +OAI.Computability.QuantumFactoring.NetworkResizeEmission +OAI.Computability.QuantumFactoring.NetworkSequenceEmission +OAI.Computability.QuantumFactoring.NetworkStackCompiler +OAI.Computability.QuantumFactoring.NodeControlBounds +OAI.Computability.QuantumFactoring.NodeControlCircuit +OAI.Computability.QuantumFactoring.NodeControlEmission +OAI.Computability.QuantumFactoring.NodeMachineEmission +OAI.Computability.QuantumFactoring.NodePreparationPolynomial +OAI.Computability.QuantumFactoring.NodeProgress +OAI.Computability.QuantumFactoring.NodeSplitMachine +OAI.Computability.QuantumFactoring.NodeStateBounds +OAI.Computability.QuantumFactoring.NodeStateCircuit +OAI.Computability.QuantumFactoring.NodeStateEmission +OAI.Computability.QuantumFactoring.NodeStateFailure +OAI.Computability.QuantumFactoring.NodeStateNil +OAI.Computability.QuantumFactoring.NodeVerifiedCircuit +OAI.Computability.QuantumFactoring.OccurrenceQueue +OAI.Computability.QuantumFactoring.OpsEmits +OAI.Computability.QuantumFactoring.OracleLayout +OAI.Computability.QuantumFactoring.OracleReadOnly +OAI.Computability.QuantumFactoring.OrderCandidateLaw +OAI.Computability.QuantumFactoring.OrderDecoderPolynomial +OAI.Computability.QuantumFactoring.OrderSampleCircuit +OAI.Computability.QuantumFactoring.OrderSamplerEmission +OAI.Computability.QuantumFactoring.OrderSamplerMass +OAI.Computability.QuantumFactoring.OrderTransition +OAI.Computability.QuantumFactoring.OrderTrial +OAI.Computability.QuantumFactoring.OrderTrialFurther +OAI.Computability.QuantumFactoring.OrderTrialFurther2 +OAI.Computability.QuantumFactoring.OrderTrialLaw +OAI.Computability.QuantumFactoring.PackedEncoding +OAI.Computability.QuantumFactoring.PackedPrograms +OAI.Computability.QuantumFactoring.ParallelPreparation +OAI.Computability.QuantumFactoring.PerfectPowerCircuit +OAI.Computability.QuantumFactoring.PhaseOracle +OAI.Computability.QuantumFactoring.PhasePreparation +OAI.Computability.QuantumFactoring.PhasePreparationConnection +OAI.Computability.QuantumFactoring.PhysicalAmplification +OAI.Computability.QuantumFactoring.PhysicalCompletionOutput +OAI.Computability.QuantumFactoring.PhysicalDataLog +OAI.Computability.QuantumFactoring.PhysicalListEmission +OAI.Computability.QuantumFactoring.PhysicalListNetworks +OAI.Computability.QuantumFactoring.PhysicalListOutputEmission +OAI.Computability.QuantumFactoring.PhysicalListSlots +OAI.Computability.QuantumFactoring.PhysicalMachine +OAI.Computability.QuantumFactoring.PhysicalMachineMass +OAI.Computability.QuantumFactoring.PhysicalNodeCompletion +OAI.Computability.QuantumFactoring.PhysicalNodeEmission +OAI.Computability.QuantumFactoring.PhysicalNodeKernel +OAI.Computability.QuantumFactoring.PhysicalNodeLaunch +OAI.Computability.QuantumFactoring.PhysicalNodeOutput +OAI.Computability.QuantumFactoring.PhysicalNodeSafety +OAI.Computability.QuantumFactoring.PhysicalOrderDecoder +OAI.Computability.QuantumFactoring.PhysicalOrderEmission +OAI.Computability.QuantumFactoring.PhysicalOrderNetworks +OAI.Computability.QuantumFactoring.PhysicalOrderOutputEmission +OAI.Computability.QuantumFactoring.PhysicalOrderSlots +OAI.Computability.QuantumFactoring.PhysicalSplit +OAI.Computability.QuantumFactoring.PhysicalSplitDecoder +OAI.Computability.QuantumFactoring.PhysicalSplitDecoderEmission +OAI.Computability.QuantumFactoring.PhysicalSplitEmission +OAI.Computability.QuantumFactoring.PhysicalSplitLaunch +OAI.Computability.QuantumFactoring.PhysicalTreeCompletion +OAI.Computability.QuantumFactoring.PhysicalTreeEmission +OAI.Computability.QuantumFactoring.PhysicalTreeLaunch +OAI.Computability.QuantumFactoring.PhysicalTreeMachine +OAI.Computability.QuantumFactoring.PhysicalTreeMass +OAI.Computability.QuantumFactoring.PhysicalTreeQueue +OAI.Computability.QuantumFactoring.PhysicalTrialLaw +OAI.Computability.QuantumFactoring.PolyAt +OAI.Computability.QuantumFactoring.PolyBounds +OAI.Computability.QuantumFactoring.PolySchemaPoly +OAI.Computability.QuantumFactoring.PolynomialExpressionResources +OAI.Computability.QuantumFactoring.PolynomialExpressions +OAI.Computability.QuantumFactoring.PolynomialFilterExpressions +OAI.Computability.QuantumFactoring.PolynomialTemplateEmission +OAI.Computability.QuantumFactoring.PreparationPolynomial +OAI.Computability.QuantumFactoring.PreparedOracle +OAI.Computability.QuantumFactoring.Primality +OAI.Computability.QuantumFactoring.PrimalityArithmetic +OAI.Computability.QuantumFactoring.PrimalityAuxiliaryPrime +OAI.Computability.QuantumFactoring.PrimalityCorrectness +OAI.Computability.QuantumFactoring.PrimalityEmission +OAI.Computability.QuantumFactoring.PrimalityPolynomial +OAI.Computability.QuantumFactoring.PrimalityRootCount +OAI.Computability.QuantumFactoring.PrimeComponentCircuit +OAI.Computability.QuantumFactoring.PrimePowerLevels +OAI.Computability.QuantumFactoring.PrimeRecords +OAI.Computability.QuantumFactoring.Procedure +OAI.Computability.QuantumFactoring.ProcedureFurther +OAI.Computability.QuantumFactoring.ProductStates +OAI.Computability.QuantumFactoring.ProgressionEvaluation +OAI.Computability.QuantumFactoring.ProgressionExpressions +OAI.Computability.QuantumFactoring.ProgressionTemplateEmission +OAI.Computability.QuantumFactoring.ProperDivisorEmission +OAI.Computability.QuantumFactoring.ProvidedSplits +OAI.Computability.QuantumFactoring.QuantumCore +OAI.Computability.QuantumFactoring.QuarterConstantResources +OAI.Computability.QuantumFactoring.QuarterPreparation +OAI.Computability.QuantumFactoring.QuarterRetentionEmission +OAI.Computability.QuantumFactoring.QueueCoverage +OAI.Computability.QuantumFactoring.RationalConditionals +OAI.Computability.QuantumFactoring.RationalEmission +OAI.Computability.QuantumFactoring.RationalExpressionResources +OAI.Computability.QuantumFactoring.RationalExpressions +OAI.Computability.QuantumFactoring.RationalHeightResources +OAI.Computability.QuantumFactoring.RationalPowerCircuit +OAI.Computability.QuantumFactoring.RationalRounding +OAI.Computability.QuantumFactoring.RationalTemplateEmission +OAI.Computability.QuantumFactoring.RawDecoderPolynomial +OAI.Computability.QuantumFactoring.RawListRange +OAI.Computability.QuantumFactoring.RawTrialDecoder +OAI.Computability.QuantumFactoring.RawTrialDecoderEmission +OAI.Computability.QuantumFactoring.RawTrialFields +OAI.Computability.QuantumFactoring.RawTrialFieldsEmission +OAI.Computability.QuantumFactoring.RawTrialLabelCircuit +OAI.Computability.QuantumFactoring.RawTrialLabelEmission +OAI.Computability.QuantumFactoring.ReadOnlyCircuit +OAI.Computability.QuantumFactoring.RecordedHistory +OAI.Computability.QuantumFactoring.RecoveryPolynomial +OAI.Computability.QuantumFactoring.RegisterBasis +OAI.Computability.QuantumFactoring.RegisterCircuit +OAI.Computability.QuantumFactoring.RegisterEncoded +OAI.Computability.QuantumFactoring.RepeatedTrials +OAI.Computability.QuantumFactoring.RetainedArithmeticEmission +OAI.Computability.QuantumFactoring.RetainedCanonical +OAI.Computability.QuantumFactoring.RetainedComponentOrder +OAI.Computability.QuantumFactoring.RetainedFavorable +OAI.Computability.QuantumFactoring.RetainedFavorableCount +OAI.Computability.QuantumFactoring.RetainedFavorableEmission +OAI.Computability.QuantumFactoring.RetainedFavorablePolynomial +OAI.Computability.QuantumFactoring.RetainedFilterPolynomial +OAI.Computability.QuantumFactoring.RetainedListDummy +OAI.Computability.QuantumFactoring.RetainedListFilter +OAI.Computability.QuantumFactoring.RetainedListFilterEmission +OAI.Computability.QuantumFactoring.RetainedNetworkAt +OAI.Computability.QuantumFactoring.RetainedNetworkPolynomial +OAI.Computability.QuantumFactoring.RetainedNodeEmission +OAI.Computability.QuantumFactoring.RetainedNodeFilter +OAI.Computability.QuantumFactoring.RetainedOrderFilter +OAI.Computability.QuantumFactoring.RetainedOrderFilterEmission +OAI.Computability.QuantumFactoring.RetainedOrderTest +OAI.Computability.QuantumFactoring.RetainedPrefixPolynomial +OAI.Computability.QuantumFactoring.RetainedQuarterFilter +OAI.Computability.QuantumFactoring.RetainedQuarterPolynomial +OAI.Computability.QuantumFactoring.RetainedSplitFilter +OAI.Computability.QuantumFactoring.RetainedSplitFilterEmission +OAI.Computability.QuantumFactoring.RetainedSplitPass +OAI.Computability.QuantumFactoring.RetainedSplitPolynomial +OAI.Computability.QuantumFactoring.RetainedTable +OAI.Computability.QuantumFactoring.RetainedTotient +OAI.Computability.QuantumFactoring.RetainedTreeEmission +OAI.Computability.QuantumFactoring.RetainedTreeFilter +OAI.Computability.QuantumFactoring.RetentionCircuit +OAI.Computability.QuantumFactoring.RetentionDenominators +OAI.Computability.QuantumFactoring.RetentionEmission +OAI.Computability.QuantumFactoring.RetentionExpressionResources +OAI.Computability.QuantumFactoring.RetentionExpressions +OAI.Computability.QuantumFactoring.RetentionTemplateEmission +OAI.Computability.QuantumFactoring.RetrospectiveCircuit +OAI.Computability.QuantumFactoring.RetrospectiveLists +OAI.Computability.QuantumFactoring.RetrospectiveNode +OAI.Computability.QuantumFactoring.RetrospectiveOrder +OAI.Computability.QuantumFactoring.RetrospectiveResidues +OAI.Computability.QuantumFactoring.RetrospectiveSlots +OAI.Computability.QuantumFactoring.RetrospectiveStatistics +OAI.Computability.QuantumFactoring.RetrospectiveTree +OAI.Computability.QuantumFactoring.RootCircuit +OAI.Computability.QuantumFactoring.RootCircuitEmission +OAI.Computability.QuantumFactoring.RowNetwork +OAI.Computability.QuantumFactoring.RuntimeListPreparation +OAI.Computability.QuantumFactoring.SamplerDecodeCircuit +OAI.Computability.QuantumFactoring.SamplerDecodeEmission +OAI.Computability.QuantumFactoring.SamplerLabels +OAI.Computability.QuantumFactoring.SignedSyntaxEmission +OAI.Computability.QuantumFactoring.SortedEncoding +OAI.Computability.QuantumFactoring.SortedWords +OAI.Computability.QuantumFactoring.SortingCircuit +OAI.Computability.QuantumFactoring.SortingEmission +OAI.Computability.QuantumFactoring.SplitCandidate +OAI.Computability.QuantumFactoring.SplitDecoderPolynomial +OAI.Computability.QuantumFactoring.SplitHistoryAccess +OAI.Computability.QuantumFactoring.SplitMachineEmission +OAI.Computability.QuantumFactoring.StackEmission +OAI.Computability.QuantumFactoring.StaticMajorantResources +OAI.Computability.QuantumFactoring.StaticPredicates +OAI.Computability.QuantumFactoring.SuperpositionGates +OAI.Computability.QuantumFactoring.SuppliedDivisorCircuit +OAI.Computability.QuantumFactoring.SuppliedDivisorEmission +OAI.Computability.QuantumFactoring.TableArithmeticEmission +OAI.Computability.QuantumFactoring.TableDirectPhi +OAI.Computability.QuantumFactoring.TableFavorable +OAI.Computability.QuantumFactoring.TableFavorableCount +OAI.Computability.QuantumFactoring.TableFavorableEmission +OAI.Computability.QuantumFactoring.TableLevelCircuit +OAI.Computability.QuantumFactoring.TableNetsEmission +OAI.Computability.QuantumFactoring.TableOrder +OAI.Computability.QuantumFactoring.TableOrderCircuit +OAI.Computability.QuantumFactoring.TablePrimeSupport +OAI.Computability.QuantumFactoring.TableScanEmission +OAI.Computability.QuantumFactoring.TableTotient +OAI.Computability.QuantumFactoring.TableTotientCircuit +OAI.Computability.QuantumFactoring.TensorEmission +OAI.Computability.QuantumFactoring.TensorList +OAI.Computability.QuantumFactoring.TensorPreparation +OAI.Computability.QuantumFactoring.TensorWiring +OAI.Computability.QuantumFactoring.ThresholdRetention +OAI.Computability.QuantumFactoring.TotientAccumulator +OAI.Computability.QuantumFactoring.TotientCircuit +OAI.Computability.QuantumFactoring.TraceBounds +OAI.Computability.QuantumFactoring.TransitionEncodingEmission +OAI.Computability.QuantumFactoring.TransitionEqualization +OAI.Computability.QuantumFactoring.TransitionNetworks +OAI.Computability.QuantumFactoring.TransitionWords +OAI.Computability.QuantumFactoring.TreeAmplified +OAI.Computability.QuantumFactoring.TreeFinalResources +OAI.Computability.QuantumFactoring.TreeHistoryAccess +OAI.Computability.QuantumFactoring.TreeHistoryEmission +OAI.Computability.QuantumFactoring.TreeInitialization +OAI.Computability.QuantumFactoring.TreePadding +OAI.Computability.QuantumFactoring.TreePhysicalPreparation +OAI.Computability.QuantumFactoring.TreePreparationEmission +OAI.Computability.QuantumFactoring.TreePreparationPolynomial +OAI.Computability.QuantumFactoring.TreeQuarterPhysical +OAI.Computability.QuantumFactoring.TreeReadOnly +OAI.Computability.QuantumFactoring.TreeReadout +OAI.Computability.QuantumFactoring.TreeReadoutResources +OAI.Computability.QuantumFactoring.TreeRootOutput +OAI.Computability.QuantumFactoring.TreeTableEmission +OAI.Computability.QuantumFactoring.TreeVerificationEmission +OAI.Computability.QuantumFactoring.TrialControlCircuit +OAI.Computability.QuantumFactoring.TrialControlEmission +OAI.Computability.QuantumFactoring.TrialExpressionResources +OAI.Computability.QuantumFactoring.TrialGuessLaw +OAI.Computability.QuantumFactoring.TrialNetworkPolynomial +OAI.Computability.QuantumFactoring.TrialRawPreparation +OAI.Computability.QuantumFactoring.TrialRetentionBounds +OAI.Computability.QuantumFactoring.TriangularAlgebra +OAI.Computability.QuantumFactoring.TriangularCircuit +OAI.Computability.QuantumFactoring.TriangularKernel +OAI.Computability.QuantumFactoring.TriangularNetworkEmission +OAI.Computability.QuantumFactoring.TriangularPaths +OAI.Computability.QuantumFactoring.TriangularPreparation +OAI.Computability.QuantumFactoring.TriangularProgramEmission +OAI.Computability.QuantumFactoring.TwoAdicCircuit +OAI.Computability.QuantumFactoring.UniversalSplit +OAI.Computability.QuantumFactoring.VerifiedRoot +OAI.Computability.QuantumFactoring.VerifiedTableOrder +OAI.Computability.QuantumFactoring.VerifiedTreeBounds +OAI.Computability.QuantumFactoring.VerifiedTreeCompletion +OAI.Computability.QuantumFactoring.WideSplitCircuit +OAI.Computability.QuantumFactoring.WordBlocks +OAI.Computability.QuantumFactoring.WordBlocksEmission +OAI.Computability.QuantumFactoring.WordNetworks +OAI.Computability.QuantumFactoring.WordResize +OAI.Computability.QuantumFactoring.WordSumCircuit +OAI.Computability.QuantumFactoring.ZeroOutside diff --git a/tasks/exact-quantum-factoring/solution/reference.py b/tasks/exact-quantum-factoring/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/exact-quantum-factoring/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/exact-quantum-factoring/solution/solve.sh b/tasks/exact-quantum-factoring/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..05cc75e465f4a862723e4dd3728632fac1da77b1 --- /dev/null +++ b/tasks/exact-quantum-factoring/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ExactQuantumFactoring, i.e. module OAI.Computability.QuantumFactoring.Main and the +# 546 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.QuantumFactoring.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ExactQuantumFactoring" diff --git a/tasks/exact-quantum-factoring/task.toml b/tasks/exact-quantum-factoring/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..576d55d1fb9d0d55391bd2511daf69061e151f47 --- /dev/null +++ b/tasks/exact-quantum-factoring/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/exact-quantum-factoring" +version = "1.0.0" +description = "Prove ExactQuantumFactoring (openai/math family 279: Exact quantum factoring over a fixed finite gate set) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ExactQuantumFactoring.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ExactQuantumFactoring" +family = "279" +family_title = "Exact quantum factoring over a fixed finite gate set" +subject = "Mathematical physics" +theorems = ["OAI.ExactQuantumFactoring.exact_quantum_factoring"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.QuantumFactoring.Main" +reference_modules = 546 +reference_lean_bytes = 2420616 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1227 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13878 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/exact-quantum-factoring/tests/Challenge.lean b/tasks/exact-quantum-factoring/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2072f20cb47134ae2fd8eb213a9c2146e1c02ae4 --- /dev/null +++ b/tasks/exact-quantum-factoring/tests/Challenge.lean @@ -0,0 +1,154 @@ +import Mathlib + +namespace OAI + + + +namespace ExactQuantumFactoring + +open scoped BigOperators + +/-- The five primitive gates exactly as in Section 2. -/ +inductive Primitive where + | not | cnot | toffoli | hadamard | phase + deriving DecidableEq + +def Primitive.arity : Primitive → ℕ + | .not | .hadamard | .phase => 1 + | .cnot => 2 + | .toffoli => 3 + +def Primitive.code : Primitive → ℕ + | .not => 0 | .cnot => 1 | .toffoli => 2 | .hadamard => 3 | .phase => 4 + +/-- An inverse and/or one added control. This is a fixed set of 20 gate names, +not an unbounded-control or arbitrary-angle gate model. -/ +structure Gate where + primitive : Primitive + inverse : Bool + controlled : Bool + deriving DecidableEq + +def Gate.arity (g : Gate) : ℕ := g.primitive.arity + if g.controlled then 1 else 0 + +/-- Matrix entries are indexed by lists in wire order (row first, column second). +Entries on ill-sized lists are irrelevant and set to zero. -/ +noncomputable def Primitive.matrix : Primitive → List Bool → List Bool → ℂ + | .not, [a], [b] => if a = !b then 1 else 0 + | .cnot, [a,b], [c,d] => if a = c ∧ b = Bool.xor c d then 1 else 0 + | .toffoli, [a,b,c], [d,e,f] => + if a = d ∧ b = e ∧ c = Bool.xor f (d && e) then 1 else 0 + | .hadamard, [a], [b] => + (if a && b then -1 else 1) / (Real.sqrt 2 : ℂ) + | .phase, [a], [b] => if a = b then (if b then Complex.I else 1) else 0 + | _, _, _ => 0 + +noncomputable def Gate.baseMatrix (g : Gate) (a b : List Bool) : ℂ := + if g.inverse then star (g.primitive.matrix b a) else g.primitive.matrix a b + +noncomputable def Gate.matrix (g : Gate) (a b : List Bool) : ℂ := + if g.controlled then + match a, b with + | false :: a', false :: b' => if a' = b' then 1 else 0 + | true :: a', true :: b' => g.baseMatrix a' b' + | _, _ => 0 + else g.baseMatrix a b + +/-- A primitive is placed on distinct actual wires, with no operation of +unbounded arity hidden in a circuit instruction. -/ +structure Instruction (q : ℕ) where + gate : Gate + wire : Fin gate.arity → Fin q + distinct : Function.Injective wire + +abbrev Basis (q : ℕ) := Fin q → Bool +abbrev State (q : ℕ) := Basis q → ℂ + +noncomputable def Instruction.matrix {q : ℕ} (o : Instruction q) : + Matrix (Basis q) (Basis q) ℂ := by + classical + exact fun a b => + if ∀ i : Fin q, (∀ j, o.wire j ≠ i) → a i = b i then + o.gate.matrix (List.ofFn (a ∘ o.wire)) (List.ofFn (b ∘ o.wire)) + else 0 + +structure Circuit where + qubits : ℕ + instructions : List (Instruction qubits) + +noncomputable def Circuit.apply (c : Circuit) (ψ : State c.qubits) : State c.qubits := + c.instructions.foldl (fun v o => o.matrix.mulVec v) ψ + +/-- Input wires are first, least significant bit first; all other wires start zero. -/ +def inputBasis (q ℓ N : ℕ) : Basis q := + fun i => if i.val < ℓ then N.testBit i.val else false + +noncomputable def Circuit.outputState (c : Circuit) (ℓ N : ℕ) : State c.qubits := by + classical + exact c.apply (fun x => if x = inputBasis c.qubits ℓ N then 1 else 0) + +/-- The cutoff and padding are the standing parameters in Section 2. -/ +def paddedLength (ℓ : ℕ) : ℕ := max 128 ℓ + +def readBit {q : ℕ} (x : Basis q) (i : ℕ) : Bool := + if h : i < q then x ⟨i,h⟩ else false + +/-- n entries of n bits each, in the n² wires immediately after the input. -/ +def outputList {q : ℕ} (ℓ : ℕ) (x : Basis q) : List ℕ := + let n := paddedLength ℓ + List.ofFn (fun a : Fin n => + ∑ j ∈ Finset.range n, if readBit x (ℓ + a.val * n + j) then 2^j else 0) + +/-- Complete nondecreasing prime factorization, multiplicities included, +padded by zeros, as in Section 6. There is no primality oracle in the circuit. -/ +def CorrectEncoding (N n : ℕ) (xs : List ℕ) : Prop := + ∃ ps : List ℕ, (∀ p ∈ ps, Nat.Prime p) ∧ ps.Pairwise (· ≤ ·) ∧ + ps.prod = N ∧ ps.length ≤ n ∧ xs = ps ++ List.replicate (n - ps.length) 0 + +/-- Unnormalized Born sum on correct outputs; success is exactly one, +not positivity, postselection, or a limiting high probability. -/ +noncomputable def Circuit.correctProbability (c : Circuit) (ℓ N : ℕ) : ℝ := by + classical + exact ∑ x : Basis c.qubits, + if CorrectEncoding N (paddedLength ℓ) (outputList ℓ x) then + Complex.normSq (c.outputState ℓ N x) else 0 + +/-- Unary natural words with delimiters make the circuit description explicit. +Unary wire addresses cause at most polynomial overhead when width is polynomial. -/ +def natWord (k : ℕ) : List Bool := List.replicate k true ++ [false] + +def Instruction.encode {q : ℕ} (o : Instruction q) : List Bool := + natWord o.gate.primitive.code ++ [o.gate.inverse, o.gate.controlled] ++ + (List.ofFn (fun i => o.wire i |>.val)).flatMap natWord + +def Circuit.encode (c : Circuit) : List Bool := + natWord c.qubits ++ natWord c.instructions.length ++ + c.instructions.flatMap Instruction.encode + +/-- A single finite-alphabet classical generator receives only the INPUT LENGTH. +All stack alphabets, states and labels are finite: no large-integer unit-cost +oracle is hidden in TM2 push/branch functions. -/ +def Uniform (family : ℕ → Circuit) : Prop := + ∃ generator : Turing.TM2ComputableInPolyTime + (fun ℓ => List.replicate ℓ true) Circuit.encode family, + ∀ k, Finite (generator.tm.Γ k) + +def PolynomialResources (family : ℕ → Circuit) : Prop := + ∃ bound : Polynomial ℕ, ∀ ℓ, + (family ℓ).qubits ≤ bound.eval ℓ ∧ + (family ℓ).instructions.length ≤ bound.eval ℓ + +/-- Literal main endpoint: one length-uniform family, exact output for EVERY +binary integer N≥2, and worst-case polynomial gates AND qubits. -/ +def MainTheorem : Prop := + ∃ family : ℕ → Circuit, Uniform family ∧ PolynomialResources family ∧ + ∀ (ℓ N : ℕ), 2 ≤ N → N.size = ℓ → + ℓ + (paddedLength ℓ)^2 ≤ (family ℓ).qubits ∧ + (family ℓ).correctProbability ℓ N = 1 + +theorem exact_quantum_factoring : MainTheorem := by + sorry + +end ExactQuantumFactoring + +end OAI diff --git a/tasks/exact-quantum-factoring/tests/grade.py b/tasks/exact-quantum-factoring/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/exact-quantum-factoring/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/exact-quantum-factoring/tests/task.json b/tasks/exact-quantum-factoring/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8a15c2b5e9c538accf820467b9c6480a4b67d8c3 --- /dev/null +++ b/tasks/exact-quantum-factoring/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ExactQuantumFactoring", + "comparator": { + "theorem_names": [ + "OAI.ExactQuantumFactoring.exact_quantum_factoring" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12978 +} \ No newline at end of file diff --git a/tasks/exact-quantum-factoring/tests/test.sh b/tasks/exact-quantum-factoring/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/exact-quantum-factoring/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/factor-generation/environment/Dockerfile b/tasks/factor-generation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/factor-generation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/factor-generation/environment/fetch_mathlib.sh b/tasks/factor-generation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/factor-generation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/factor-generation/environment/lake-manifest.json b/tasks/factor-generation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/factor-generation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/factor-generation/environment/lakefile.lean b/tasks/factor-generation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/factor-generation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/factor-generation/environment/lean_setup.sh b/tasks/factor-generation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/factor-generation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/factor-generation/environment/pack_submission.py b/tasks/factor-generation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/factor-generation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/factor-generation/instruction.md b/tasks/factor-generation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c5a1303b3d054c71d23e786fd2a7a22058bdfa08 --- /dev/null +++ b/tasks/factor-generation/instruction.md @@ -0,0 +1,101 @@ +# openai/math challenge `FactorGeneration` (family 296) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 296 of the release, *The generator problem for finite factors* +(Operator algebras). The family as a whole: Proves that every type $\mathrm{II}_1$ factor with separable predual is generated by a single operator, equivalently by two self-adjoint operators, resolving the generator problem. More strongly, for every irreducible inclusion $P\subset M$ of such factors, the unitaries $u$ with $M=W^*(P,u)$ form a dense $G_\delta$ subset in the trace $2$-norm topology. + +The challenge is `FactorGeneration`, also at `/opt/openai-math/challenges/FactorGeneration.lean`: + +```lean +import Mathlib.Analysis.CStarAlgebra.ContinuousLinearMap +import Mathlib.Analysis.InnerProductSpace.WeakOperatorTopology +import Mathlib.Analysis.VonNeumannAlgebra.Basic + +namespace OAI + +noncomputable section + +namespace Generator + +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +attribute [-instance] instCStarAlgebraContinuousLinearMapComplexIdOfCompleteSpace + +def WOTClosed (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + IsClosed {T : H →WOT[ℂ] H | T.toCLM ∈ S} + +def wstar (s : Set (H →L[ℂ] H)) : StarSubalgebra ℂ (H →L[ℂ] H) := + sInf {S | WOTClosed S ∧ s ⊆ S} + +structure IsII1Factor (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop where + nonzero : (0 : H →L[ℂ] H) ≠ 1 + weaklyClosed : WOTClosed S + factor : ∀ x : S, (∀ y : S, y * x = x * y) → ∃ c : ℂ, x = algebraMap ℂ S c + finite : ∀ v : S, star v * v = 1 → v * star v = 1 + diffuse : ∀ p : S, IsStarProjection p → p ≠ 0 → + ∃ q : S, IsStarProjection q ∧ q ≠ 0 ∧ q ≠ p ∧ p * q = q ∧ q * p = q + +def HasSeparablePredual (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + ∃ (X : Type u) (_ : NormedAddCommGroup X) (_ : NormedSpace ℂ X) + (_ : CompleteSpace X) (_ : TopologicalSpace.SeparableSpace X), + Nonempty (StrongDual ℂ X ≃ₗᵢ⋆[ℂ] S) + +def SinglyGenerated (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + ∃ x ∈ S, wstar {x} = S + +attribute [instance] instCStarAlgebraContinuousLinearMapComplexIdOfCompleteSpace + +theorem single_generation_of_II1_separable_predual + (S : StarSubalgebra ℂ (H →L[ℂ] H)) (hS : IsII1Factor S) + (hsep : HasSeparablePredual S) : SinglyGenerated S := by + sorry + +end Generator + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FactorGeneration.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Generator.single_generation_of_II1_separable_predual` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/factor-generation/solution/closure.txt b/tasks/factor-generation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f362807d7ace8193cb72866a740691fd47062a0 --- /dev/null +++ b/tasks/factor-generation/solution/closure.txt @@ -0,0 +1,93 @@ +OAI.Analysis.FactorGeneration.AmplificationEncoding +OAI.Analysis.FactorGeneration.Bicommutant +OAI.Analysis.FactorGeneration.Coefficients +OAI.Analysis.FactorGeneration.Convolution +OAI.Analysis.FactorGeneration.CoordinatePerturbation +OAI.Analysis.FactorGeneration.CoordinateUnitaries +OAI.Analysis.FactorGeneration.CornerIndependence +OAI.Analysis.FactorGeneration.CornerTrace +OAI.Analysis.FactorGeneration.Correlation +OAI.Analysis.FactorGeneration.CyclicPredual +OAI.Analysis.FactorGeneration.Dimension +OAI.Analysis.FactorGeneration.DyadicComparison +OAI.Analysis.FactorGeneration.EnergyDescent +OAI.Analysis.FactorGeneration.Expectations +OAI.Analysis.FactorGeneration.Exponential +OAI.Analysis.FactorGeneration.FiniteComparison +OAI.Analysis.FactorGeneration.FreeGroupMoments +OAI.Analysis.FactorGeneration.FreeWords +OAI.Analysis.FactorGeneration.FunctionalLimits +OAI.Analysis.FactorGeneration.Generation +OAI.Analysis.FactorGeneration.GroupTrace +OAI.Analysis.FactorGeneration.HaarIndependence +OAI.Analysis.FactorGeneration.HaarPatches +OAI.Analysis.FactorGeneration.HaarSequences +OAI.Analysis.FactorGeneration.HilbertLimits +OAI.Analysis.FactorGeneration.HilbertProjections +OAI.Analysis.FactorGeneration.LaurentAlgebra +OAI.Analysis.FactorGeneration.LaurentMoments +OAI.Analysis.FactorGeneration.LocalPatches +OAI.Analysis.FactorGeneration.LocalQuantization +OAI.Analysis.FactorGeneration.LocalizedStates +OAI.Analysis.FactorGeneration.LongWords +OAI.Analysis.FactorGeneration.Main +OAI.Analysis.FactorGeneration.MatrixAlgebras +OAI.Analysis.FactorGeneration.MatrixEncoding +OAI.Analysis.FactorGeneration.MatrixExpectation +OAI.Analysis.FactorGeneration.MatrixGenerators +OAI.Analysis.FactorGeneration.MatrixRefinement +OAI.Analysis.FactorGeneration.MatrixSequence +OAI.Analysis.FactorGeneration.MatrixUnits +OAI.Analysis.FactorGeneration.MonotoneTrace +OAI.Analysis.FactorGeneration.NormalDimension +OAI.Analysis.FactorGeneration.NormalTrace +OAI.Analysis.FactorGeneration.OperatorLimits +OAI.Analysis.FactorGeneration.OrbitMinima +OAI.Analysis.FactorGeneration.PartialIsometries +OAI.Analysis.FactorGeneration.PartialUnitaries +OAI.Analysis.FactorGeneration.PatchingBounds +OAI.Analysis.FactorGeneration.PatchingWords +OAI.Analysis.FactorGeneration.PerturbationBounds +OAI.Analysis.FactorGeneration.Pinching +OAI.Analysis.FactorGeneration.PredualContinuity +OAI.Analysis.FactorGeneration.PredualOrder +OAI.Analysis.FactorGeneration.PredualRange +OAI.Analysis.FactorGeneration.ProductWords +OAI.Analysis.FactorGeneration.ProjectionComparison +OAI.Analysis.FactorGeneration.ProjectionEncoding +OAI.Analysis.FactorGeneration.ProjectionLimits +OAI.Analysis.FactorGeneration.QuotientCorners +OAI.Analysis.FactorGeneration.QuotientHilbert +OAI.Analysis.FactorGeneration.QuotientRepresentation +OAI.Analysis.FactorGeneration.RelativeGeneration +OAI.Analysis.FactorGeneration.RepresentedCorners +OAI.Analysis.FactorGeneration.RepresentedFreeness +OAI.Analysis.FactorGeneration.ResidualCompletion +OAI.Analysis.FactorGeneration.ResidualEstimates +OAI.Analysis.FactorGeneration.ResidualMoments +OAI.Analysis.FactorGeneration.SpectralApproximation +OAI.Analysis.FactorGeneration.SpectralDimension +OAI.Analysis.FactorGeneration.SpectralPinching +OAI.Analysis.FactorGeneration.SpectralStates +OAI.Analysis.FactorGeneration.SpectralTruncation +OAI.Analysis.FactorGeneration.Subfactors +OAI.Analysis.FactorGeneration.Supports +OAI.Analysis.FactorGeneration.Target +OAI.Analysis.FactorGeneration.TensorRefinement +OAI.Analysis.FactorGeneration.TraceHilbert +OAI.Analysis.FactorGeneration.TraceTopology +OAI.Analysis.FactorGeneration.TraceTransport +OAI.Analysis.FactorGeneration.TracialInclusion +OAI.Analysis.FactorGeneration.Ultrapower +OAI.Analysis.FactorGeneration.UniformPartitions +OAI.Analysis.FactorGeneration.UnitaryMetric +OAI.Analysis.FactorGeneration.WordCorrelation +OAI.Analysis.FactorGeneration.Words +OAI.Analysis.FreeGroupFactor.GlobalODE +OAI.Analysis.FreeGroupFactor.Model +OAI.Analysis.FreeGroupFactor.NCPolynomial +OAI.Analysis.FreeGroupFactor.Operators +OAI.Analysis.FreeGroupFactor.PolynomialFlow +OAI.Analysis.FreeGroupFactor.Taylor +OAI.Analysis.FreeGroupFactor.TraceCocycle +OAI.Analysis.FreeGroupFactor.UnitaryEvaluation diff --git a/tasks/factor-generation/solution/reference.py b/tasks/factor-generation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/factor-generation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/factor-generation/solution/solve.sh b/tasks/factor-generation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7df2f0dca15df196a1103ede0a0cfe6643b8e2b8 --- /dev/null +++ b/tasks/factor-generation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FactorGeneration, i.e. module OAI.Analysis.FactorGeneration.Main and the +# 93 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.FactorGeneration.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FactorGeneration" diff --git a/tasks/factor-generation/task.toml b/tasks/factor-generation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c969122944ab25a8838300e9de48818b26f83f4d --- /dev/null +++ b/tasks/factor-generation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/factor-generation" +version = "1.0.0" +description = "Prove FactorGeneration (openai/math family 296: The generator problem for finite factors) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FactorGeneration.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FactorGeneration" +family = "296" +family_title = "The generator problem for finite factors" +subject = "Operator algebras" +theorems = ["OAI.Generator.single_generation_of_II1_separable_predual"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.FactorGeneration.Main" +reference_modules = 93 +reference_lean_bytes = 1679659 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3699 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13211 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/factor-generation/tests/Challenge.lean b/tasks/factor-generation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a8b9d4d4b4fe8864fdec3053e0bca4b70e197f66 --- /dev/null +++ b/tasks/factor-generation/tests/Challenge.lean @@ -0,0 +1,50 @@ +import Mathlib.Analysis.CStarAlgebra.ContinuousLinearMap +import Mathlib.Analysis.InnerProductSpace.WeakOperatorTopology +import Mathlib.Analysis.VonNeumannAlgebra.Basic + +namespace OAI + +noncomputable section + +namespace Generator + +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +attribute [-instance] instCStarAlgebraContinuousLinearMapComplexIdOfCompleteSpace + +def WOTClosed (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + IsClosed {T : H →WOT[ℂ] H | T.toCLM ∈ S} + +def wstar (s : Set (H →L[ℂ] H)) : StarSubalgebra ℂ (H →L[ℂ] H) := + sInf {S | WOTClosed S ∧ s ⊆ S} + +structure IsII1Factor (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop where + nonzero : (0 : H →L[ℂ] H) ≠ 1 + weaklyClosed : WOTClosed S + factor : ∀ x : S, (∀ y : S, y * x = x * y) → ∃ c : ℂ, x = algebraMap ℂ S c + finite : ∀ v : S, star v * v = 1 → v * star v = 1 + diffuse : ∀ p : S, IsStarProjection p → p ≠ 0 → + ∃ q : S, IsStarProjection q ∧ q ≠ 0 ∧ q ≠ p ∧ p * q = q ∧ q * p = q + +def HasSeparablePredual (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + ∃ (X : Type u) (_ : NormedAddCommGroup X) (_ : NormedSpace ℂ X) + (_ : CompleteSpace X) (_ : TopologicalSpace.SeparableSpace X), + Nonempty (StrongDual ℂ X ≃ₗᵢ⋆[ℂ] S) + +def SinglyGenerated (S : StarSubalgebra ℂ (H →L[ℂ] H)) : Prop := + ∃ x ∈ S, wstar {x} = S + +attribute [instance] instCStarAlgebraContinuousLinearMapComplexIdOfCompleteSpace + +theorem single_generation_of_II1_separable_predual + (S : StarSubalgebra ℂ (H →L[ℂ] H)) (hS : IsII1Factor S) + (hsep : HasSeparablePredual S) : SinglyGenerated S := by + sorry + +end Generator + +end + +end OAI diff --git a/tasks/factor-generation/tests/grade.py b/tasks/factor-generation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/factor-generation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/factor-generation/tests/task.json b/tasks/factor-generation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..deed3d01ec4a5cfd07d5829d1922fc5fb2f5ff9e --- /dev/null +++ b/tasks/factor-generation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FactorGeneration", + "comparator": { + "theorem_names": [ + "OAI.Generator.single_generation_of_II1_separable_predual" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12311 +} \ No newline at end of file diff --git a/tasks/factor-generation/tests/test.sh b/tasks/factor-generation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/factor-generation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/falconer-all-dimensions/environment/Dockerfile b/tasks/falconer-all-dimensions/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/falconer-all-dimensions/environment/fetch_mathlib.sh b/tasks/falconer-all-dimensions/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/falconer-all-dimensions/environment/lake-manifest.json b/tasks/falconer-all-dimensions/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/falconer-all-dimensions/environment/lakefile.lean b/tasks/falconer-all-dimensions/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/falconer-all-dimensions/environment/lean_setup.sh b/tasks/falconer-all-dimensions/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/falconer-all-dimensions/environment/pack_submission.py b/tasks/falconer-all-dimensions/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/falconer-all-dimensions/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/falconer-all-dimensions/instruction.md b/tasks/falconer-all-dimensions/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78fa56025ea196fc5fa54f7bcb442e87d64af36c --- /dev/null +++ b/tasks/falconer-all-dimensions/instruction.md @@ -0,0 +1,70 @@ +# openai/math challenge `FalconerAllDimensions` (family 073) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 073 of the release, *The Falconer distance conjecture* +(Real and complex analysis). The family as a whole: Resolves the Falconer distance conjecture in every dimension $d\ge2$: every compact set $E\subset\mathbb R^d$ with Hausdorff dimension greater than $d/2$ determines a set of Euclidean distances of positive Lebesgue measure. + +The challenge is `FalconerAllDimensions`, also at `/opt/openai-math/challenges/FalconerAllDimensions.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Falconer +open MeasureTheory +open scoped ENNReal + +/-- A compact subset of Euclidean space with Hausdorff dimension greater than +half the ambient dimension determines a distance set of positive Lebesgue measure. -/ +theorem falconer_distance_conjecture : + ∀ (d : ℕ), 2 ≤ d → ∀ E : Set (EuclideanSpace ℝ (Fin d)), IsCompact E → + (d : ℝ≥0∞) / 2 < dimH E → + 0 < volume {r : ℝ | ∃ x ∈ E, ∃ y ∈ E, dist x y = r} := by + sorry + +end Falconer + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FalconerAllDimensions.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Falconer.falconer_distance_conjecture` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/falconer-all-dimensions/solution/closure.txt b/tasks/falconer-all-dimensions/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0933b695f43bc8e0b863729e7c66a72152809e36 --- /dev/null +++ b/tasks/falconer-all-dimensions/solution/closure.txt @@ -0,0 +1,2384 @@ +OAI.MeasureTheory.Falconer.Angular.ActualAngleMasks +OAI.MeasureTheory.Falconer.Angular.ActualAngularDropping +OAI.MeasureTheory.Falconer.Angular.ActualAngularEquation23 +OAI.MeasureTheory.Falconer.Angular.ActualAngularNear +OAI.MeasureTheory.Falconer.Angular.ActualAngularNearDropping +OAI.MeasureTheory.Falconer.Angular.ActualAngularRecursionBound +OAI.MeasureTheory.Falconer.Angular.ActualAngularRegularization +OAI.MeasureTheory.Falconer.Angular.ActualAngularTerminal +OAI.MeasureTheory.Falconer.Angular.ActualAngularTests +OAI.MeasureTheory.Falconer.Angular.ActualFarCircleExpansion +OAI.MeasureTheory.Falconer.Angular.ActualFarStationaryReduction +OAI.MeasureTheory.Falconer.Angular.ActualFourStationarySupport +OAI.MeasureTheory.Falconer.Angular.ActualFullCircleStationary +OAI.MeasureTheory.Falconer.Angular.ActualInactiveCircle +OAI.MeasureTheory.Falconer.Angular.ActualSingleStationaryKernel +OAI.MeasureTheory.Falconer.Angular.ActualStationaryAmplitude +OAI.MeasureTheory.Falconer.Angular.ActualStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.ActualStationaryProductKernel +OAI.MeasureTheory.Falconer.Angular.ActualStationarySpatialIntegrability +OAI.MeasureTheory.Falconer.Angular.ActualTwoPointStationary +OAI.MeasureTheory.Falconer.Angular.AllDimensionalAngularProfileSum +OAI.MeasureTheory.Falconer.Angular.AngleBumpScaling +OAI.MeasureTheory.Falconer.Angular.AngleCoordinateTests +OAI.MeasureTheory.Falconer.Angular.AngleMaskDerivatives +OAI.MeasureTheory.Falconer.Angular.AngleMaskPeriodicity +OAI.MeasureTheory.Falconer.Angular.AngularBinKernel +OAI.MeasureTheory.Falconer.Angular.AngularBinSelection +OAI.MeasureTheory.Falconer.Angular.AngularBootstrap +OAI.MeasureTheory.Falconer.Angular.AngularCellKernels +OAI.MeasureTheory.Falconer.Angular.AngularCellSpatialIntegral +OAI.MeasureTheory.Falconer.Angular.AngularChart +OAI.MeasureTheory.Falconer.Angular.AngularComparableCarrier +OAI.MeasureTheory.Falconer.Angular.AngularCountMean +OAI.MeasureTheory.Falconer.Angular.AngularDifferentialBounds +OAI.MeasureTheory.Falconer.Angular.AngularDifferentialExpr +OAI.MeasureTheory.Falconer.Angular.AngularDroppedMaximum +OAI.MeasureTheory.Falconer.Angular.AngularDyadicSum +OAI.MeasureTheory.Falconer.Angular.AngularEnergyDropping +OAI.MeasureTheory.Falconer.Angular.AngularEnvelope +OAI.MeasureTheory.Falconer.Angular.AngularEnvelopeGraph +OAI.MeasureTheory.Falconer.Angular.AngularFarDepth +OAI.MeasureTheory.Falconer.Angular.AngularFarGeometry +OAI.MeasureTheory.Falconer.Angular.AngularFarSeparation +OAI.MeasureTheory.Falconer.Angular.AngularFarSpatialSum +OAI.MeasureTheory.Falconer.Angular.AngularFarStationaryScale +OAI.MeasureTheory.Falconer.Angular.AngularFourCellMass +OAI.MeasureTheory.Falconer.Angular.AngularFourSpatialIntegral +OAI.MeasureTheory.Falconer.Angular.AngularGainFinite +OAI.MeasureTheory.Falconer.Angular.AngularGrid +OAI.MeasureTheory.Falconer.Angular.AngularIntegrability +OAI.MeasureTheory.Falconer.Angular.AngularIntegrationByParts +OAI.MeasureTheory.Falconer.Angular.AngularJetSymbol +OAI.MeasureTheory.Falconer.Angular.AngularKernelIntegral +OAI.MeasureTheory.Falconer.Angular.AngularLabelEligibility +OAI.MeasureTheory.Falconer.Angular.AngularLengthIntegralPartition +OAI.MeasureTheory.Falconer.Angular.AngularLengthPartition +OAI.MeasureTheory.Falconer.Angular.AngularMeanAssembly +OAI.MeasureTheory.Falconer.Angular.AngularNearIntegral +OAI.MeasureTheory.Falconer.Angular.AngularNearNeighbors +OAI.MeasureTheory.Falconer.Angular.AngularNearProfile +OAI.MeasureTheory.Falconer.Angular.AngularNearProgress +OAI.MeasureTheory.Falconer.Angular.AngularNearSum +OAI.MeasureTheory.Falconer.Angular.AngularNoncomparableCarrier +OAI.MeasureTheory.Falconer.Angular.AngularNonstationary +OAI.MeasureTheory.Falconer.Angular.AngularNonstationaryPower +OAI.MeasureTheory.Falconer.Angular.AngularOccupiedFarPartition +OAI.MeasureTheory.Falconer.Angular.AngularOccupiedPartition +OAI.MeasureTheory.Falconer.Angular.AngularOperatorTerms +OAI.MeasureTheory.Falconer.Angular.AngularOriginalFarPartition +OAI.MeasureTheory.Falconer.Angular.AngularOriginalIntegrability +OAI.MeasureTheory.Falconer.Angular.AngularPair +OAI.MeasureTheory.Falconer.Angular.AngularPairCircleIntegral +OAI.MeasureTheory.Falconer.Angular.AngularPairSwap +OAI.MeasureTheory.Falconer.Angular.AngularParentNearFar +OAI.MeasureTheory.Falconer.Angular.AngularProductEnergyIntegral +OAI.MeasureTheory.Falconer.Angular.AngularProfileSum +OAI.MeasureTheory.Falconer.Angular.AngularRadialKernel +OAI.MeasureTheory.Falconer.Angular.AngularRestrictedIntegralSum +OAI.MeasureTheory.Falconer.Angular.AngularRestrictedKernel +OAI.MeasureTheory.Falconer.Angular.AngularSamples +OAI.MeasureTheory.Falconer.Angular.AngularStateContributions +OAI.MeasureTheory.Falconer.Angular.AngularStateData +OAI.MeasureTheory.Falconer.Angular.AngularStateDropping +OAI.MeasureTheory.Falconer.Angular.AngularStateNearFar +OAI.MeasureTheory.Falconer.Angular.AngularStateSuccessor +OAI.MeasureTheory.Falconer.Angular.AngularStationaryRadialError +OAI.MeasureTheory.Falconer.Angular.AngularStationarySpatial +OAI.MeasureTheory.Falconer.Angular.AngularStripIntervals +OAI.MeasureTheory.Falconer.Angular.AngularStripMeasure +OAI.MeasureTheory.Falconer.Angular.AngularTerminal +OAI.MeasureTheory.Falconer.Angular.AngularTerminalBound +OAI.MeasureTheory.Falconer.Angular.AngularTransform +OAI.MeasureTheory.Falconer.Angular.AngularTransformSplitting +OAI.MeasureTheory.Falconer.Angular.AngularTransportBounds +OAI.MeasureTheory.Falconer.Angular.AngularTubeMean +OAI.MeasureTheory.Falconer.Angular.AngularTubes +OAI.MeasureTheory.Falconer.Angular.AngularUniformAbsorption +OAI.MeasureTheory.Falconer.Angular.AngularWidths +OAI.MeasureTheory.Falconer.Angular.BadDirectionEnvelope +OAI.MeasureTheory.Falconer.Angular.BadDirectionSelection +OAI.MeasureTheory.Falconer.Angular.CapAmplitudeDerivatives +OAI.MeasureTheory.Falconer.Angular.CapCoordinates +OAI.MeasureTheory.Falconer.Angular.CapCrossIntegral +OAI.MeasureTheory.Falconer.Angular.CapDenominator +OAI.MeasureTheory.Falconer.Angular.CapDensityCharge +OAI.MeasureTheory.Falconer.Angular.CapEnergyExpansion +OAI.MeasureTheory.Falconer.Angular.CapLocalization +OAI.MeasureTheory.Falconer.Angular.CapNet +OAI.MeasureTheory.Falconer.Angular.CapPairSymmetry +OAI.MeasureTheory.Falconer.Angular.CapReciprocal +OAI.MeasureTheory.Falconer.Angular.CapScaleGeometry +OAI.MeasureTheory.Falconer.Angular.CapSupport +OAI.MeasureTheory.Falconer.Angular.CapSymbolBounds +OAI.MeasureTheory.Falconer.Angular.CapTransport +OAI.MeasureTheory.Falconer.Angular.CappedActiveCover +OAI.MeasureTheory.Falconer.Angular.CappedOriginalCover +OAI.MeasureTheory.Falconer.Angular.CircleAngularBins +OAI.MeasureTheory.Falconer.Angular.CircleDirectCoefficients +OAI.MeasureTheory.Falconer.Angular.CircleLocalIntegral +OAI.MeasureTheory.Falconer.Angular.CircleMaskCoordinates +OAI.MeasureTheory.Falconer.Angular.CircleMaskSupport +OAI.MeasureTheory.Falconer.Angular.CircleResidualDecay +OAI.MeasureTheory.Falconer.Angular.CircleRotation +OAI.MeasureTheory.Falconer.Angular.CircleStationaryPartition +OAI.MeasureTheory.Falconer.Angular.CircleTests +OAI.MeasureTheory.Falconer.Angular.CommonProfileAngularNear +OAI.MeasureTheory.Falconer.Angular.CompactCircleResidual +OAI.MeasureTheory.Falconer.Angular.CompactStationaryAmplitude +OAI.MeasureTheory.Falconer.Angular.ControlledAngularGain +OAI.MeasureTheory.Falconer.Angular.CubeCapacity +OAI.MeasureTheory.Falconer.Angular.DirectionDistance +OAI.MeasureTheory.Falconer.Angular.DiscardedCapTerm +OAI.MeasureTheory.Falconer.Angular.DyadicCapTerms +OAI.MeasureTheory.Falconer.Angular.DyadicLongitudinal +OAI.MeasureTheory.Falconer.Angular.DyadicPerpendicular +OAI.MeasureTheory.Falconer.Angular.EndpointAngularGain +OAI.MeasureTheory.Falconer.Angular.EndpointAngularParameters +OAI.MeasureTheory.Falconer.Angular.EndpointBadDirections +OAI.MeasureTheory.Falconer.Angular.EvenStartingCaps +OAI.MeasureTheory.Falconer.Angular.FactorizedAngularState +OAI.MeasureTheory.Falconer.Angular.FarAngularStep +OAI.MeasureTheory.Falconer.Angular.FiniteAngularSquare +OAI.MeasureTheory.Falconer.Angular.FlexibleAngularRoot +OAI.MeasureTheory.Falconer.Angular.FourPointCaps +OAI.MeasureTheory.Falconer.Angular.FourStationarySupport +OAI.MeasureTheory.Falconer.Angular.FullCircleDecomposition +OAI.MeasureTheory.Falconer.Angular.FullCircleStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.FullCircleStationaryPower +OAI.MeasureTheory.Falconer.Angular.GlobalCapBounds +OAI.MeasureTheory.Falconer.Angular.GnomonicCap +OAI.MeasureTheory.Falconer.Angular.GnomonicChart +OAI.MeasureTheory.Falconer.Angular.GnomonicCone +OAI.MeasureTheory.Falconer.Angular.GnomonicConeVolume +OAI.MeasureTheory.Falconer.Angular.GnomonicDischarge +OAI.MeasureTheory.Falconer.Angular.GnomonicInverse +OAI.MeasureTheory.Falconer.Angular.GnomonicLaw +OAI.MeasureTheory.Falconer.Angular.GnomonicPairGram +OAI.MeasureTheory.Falconer.Angular.GnomonicPrunedLaw +OAI.MeasureTheory.Falconer.Angular.GnomonicTripleAngle +OAI.MeasureTheory.Falconer.Angular.GnomonicTripleKernel +OAI.MeasureTheory.Falconer.Angular.GoodDirectionMass +OAI.MeasureTheory.Falconer.Angular.GoodProjectionDirections +OAI.MeasureTheory.Falconer.Angular.GraphAngleCharts +OAI.MeasureTheory.Falconer.Angular.GraphAngularCoordinates +OAI.MeasureTheory.Falconer.Angular.GraphRotatedWeights +OAI.MeasureTheory.Falconer.Angular.GraphTorusAngles +OAI.MeasureTheory.Falconer.Angular.IneligibleCapTerms +OAI.MeasureTheory.Falconer.Angular.InheritedAngularSymbols +OAI.MeasureTheory.Falconer.Angular.InheritedCircleRegularity +OAI.MeasureTheory.Falconer.Angular.IntegerCaps +OAI.MeasureTheory.Falconer.Angular.InverseAngularSymbol +OAI.MeasureTheory.Falconer.Angular.InverseCircleArcLength +OAI.MeasureTheory.Falconer.Angular.InverseCircleAssembly +OAI.MeasureTheory.Falconer.Angular.InverseCirclePower +OAI.MeasureTheory.Falconer.Angular.InverseSphereFubini +OAI.MeasureTheory.Falconer.Angular.InverseStationaryCancellation +OAI.MeasureTheory.Falconer.Angular.InverseStationaryCutoff +OAI.MeasureTheory.Falconer.Angular.InverseStationaryOperators +OAI.MeasureTheory.Falconer.Angular.InverseStationaryRemainder +OAI.MeasureTheory.Falconer.Angular.InverseStationaryScales +OAI.MeasureTheory.Falconer.Angular.InverseStationaryTriangle +OAI.MeasureTheory.Falconer.Angular.InverseStationaryWeighted +OAI.MeasureTheory.Falconer.Angular.LocalDirectionPackets +OAI.MeasureTheory.Falconer.Angular.LocalizedStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.LongitudinalCapTerm +OAI.MeasureTheory.Falconer.Angular.LongitudinalCrossTerm +OAI.MeasureTheory.Falconer.Angular.MeasurableAngularJets +OAI.MeasureTheory.Falconer.Angular.MixedCapBounds +OAI.MeasureTheory.Falconer.Angular.MixedCapDenominator +OAI.MeasureTheory.Falconer.Angular.MixedNormalizedCaps +OAI.MeasureTheory.Falconer.Angular.MultiscaleCapMass +OAI.MeasureTheory.Falconer.Angular.NoncomparableSphereKernel +OAI.MeasureTheory.Falconer.Angular.NonendpointAngularGain +OAI.MeasureTheory.Falconer.Angular.NonendpointBadDirections +OAI.MeasureTheory.Falconer.Angular.NormalizedCaps +OAI.MeasureTheory.Falconer.Angular.NormalizedStationaryJet +OAI.MeasureTheory.Falconer.Angular.NorthRotation +OAI.MeasureTheory.Falconer.Angular.OddAuxiliaryCaps +OAI.MeasureTheory.Falconer.Angular.OddOriginalCaps +OAI.MeasureTheory.Falconer.Angular.OriginalAngularKernel +OAI.MeasureTheory.Falconer.Angular.OriginalCapRemoval +OAI.MeasureTheory.Falconer.Angular.OriginalDirectionChart +OAI.MeasureTheory.Falconer.Angular.OriginalFiberCaps +OAI.MeasureTheory.Falconer.Angular.OuterAngularBound +OAI.MeasureTheory.Falconer.Angular.OuterAngularDecay +OAI.MeasureTheory.Falconer.Angular.PeriodicAngularBins +OAI.MeasureTheory.Falconer.Angular.PerpendicularCrossTerm +OAI.MeasureTheory.Falconer.Angular.PolicyAngularBranches +OAI.MeasureTheory.Falconer.Angular.ProjectedDirections +OAI.MeasureTheory.Falconer.Angular.ProjectionAngularGeometry +OAI.MeasureTheory.Falconer.Angular.ProjectionAngularMoment +OAI.MeasureTheory.Falconer.Angular.PublishedGnomonic +OAI.MeasureTheory.Falconer.Angular.PublishedIntegerCaps +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryIdentity +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryL1 +OAI.MeasureTheory.Falconer.Angular.QuantitativeCaps +OAI.MeasureTheory.Falconer.Angular.RadialStationaryProfile +OAI.MeasureTheory.Falconer.Angular.ReciprocalSineBounds +OAI.MeasureTheory.Falconer.Angular.RegularizedAngularNear +OAI.MeasureTheory.Falconer.Angular.RetainedAngularFailure +OAI.MeasureTheory.Falconer.Angular.RetainedSmallSphere +OAI.MeasureTheory.Falconer.Angular.ReverseCapsAllRadii +OAI.MeasureTheory.Falconer.Angular.RootStationaryScale +OAI.MeasureTheory.Falconer.Angular.RotatedActualInactive +OAI.MeasureTheory.Falconer.Angular.RotatedBinPartition +OAI.MeasureTheory.Falconer.Angular.RotatedCircleIntegral +OAI.MeasureTheory.Falconer.Angular.RotatedConeKernel +OAI.MeasureTheory.Falconer.Angular.RotatedGraphEligibility +OAI.MeasureTheory.Falconer.Angular.RotatedInverseCircle +OAI.MeasureTheory.Falconer.Angular.RotatedParallelCandidates +OAI.MeasureTheory.Falconer.Angular.RotatedScaleNonstationary +OAI.MeasureTheory.Falconer.Angular.ScalarAngularShell +OAI.MeasureTheory.Falconer.Angular.ScaledAngularTransport +OAI.MeasureTheory.Falconer.Angular.SelectedAngularBins +OAI.MeasureTheory.Falconer.Angular.SharedAngular +OAI.MeasureTheory.Falconer.Angular.SignedStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.SignedStationaryJet +OAI.MeasureTheory.Falconer.Angular.SignedStationaryRadial +OAI.MeasureTheory.Falconer.Angular.SingleStationaryAngular +OAI.MeasureTheory.Falconer.Angular.SingleStationaryIntegral +OAI.MeasureTheory.Falconer.Angular.SingleStationaryRadial +OAI.MeasureTheory.Falconer.Angular.SmallGnomonicCap +OAI.MeasureTheory.Falconer.Angular.SmoothAngleMask +OAI.MeasureTheory.Falconer.Angular.SmoothCapPartition +OAI.MeasureTheory.Falconer.Angular.SmoothInverseSine +OAI.MeasureTheory.Falconer.Angular.SmoothRotatedCone +OAI.MeasureTheory.Falconer.Angular.SourceAngularDirect +OAI.MeasureTheory.Falconer.Angular.SourceAngularReduction +OAI.MeasureTheory.Falconer.Angular.SphereCapBound +OAI.MeasureTheory.Falconer.Angular.SphereCapBox +OAI.MeasureTheory.Falconer.Angular.SphereCapCenters +OAI.MeasureTheory.Falconer.Angular.SphereChartIntegral +OAI.MeasureTheory.Falconer.Angular.SphereFrequency +OAI.MeasureTheory.Falconer.Angular.SphereInverse +OAI.MeasureTheory.Falconer.Angular.SphereModel +OAI.MeasureTheory.Falconer.Angular.SphereNonstationary +OAI.MeasureTheory.Falconer.Angular.SphereNormalization +OAI.MeasureTheory.Falconer.Angular.SphereOffPole +OAI.MeasureTheory.Falconer.Angular.SphereProduct +OAI.MeasureTheory.Falconer.Angular.SphereRotations +OAI.MeasureTheory.Falconer.Angular.SphereStationary +OAI.MeasureTheory.Falconer.Angular.SphereStationaryAssembly +OAI.MeasureTheory.Falconer.Angular.StationaryApproximantSupport +OAI.MeasureTheory.Falconer.Angular.StationaryArcLength +OAI.MeasureTheory.Falconer.Angular.StationaryChartAmplitude +OAI.MeasureTheory.Falconer.Angular.StationaryChartCutoffs +OAI.MeasureTheory.Falconer.Angular.StationaryChartIntegral +OAI.MeasureTheory.Falconer.Angular.StationaryDifferentialExpr +OAI.MeasureTheory.Falconer.Angular.StationaryJetLocality +OAI.MeasureTheory.Falconer.Angular.StationaryJetOperators +OAI.MeasureTheory.Falconer.Angular.StationaryOppositePhase +OAI.MeasureTheory.Falconer.Angular.StationaryPairGain +OAI.MeasureTheory.Falconer.Angular.StationaryPairSupport +OAI.MeasureTheory.Falconer.Angular.StationaryPowerRate +OAI.MeasureTheory.Falconer.Angular.StationaryProductIntegral +OAI.MeasureTheory.Falconer.Angular.StationaryProductKernel +OAI.MeasureTheory.Falconer.Angular.StationaryRadialCoefficient +OAI.MeasureTheory.Falconer.Angular.StationaryRadialScaling +OAI.MeasureTheory.Falconer.Angular.StationaryRemainderScale +OAI.MeasureTheory.Falconer.Angular.StationarySineChart +OAI.MeasureTheory.Falconer.Angular.SuffixAngularRadius +OAI.MeasureTheory.Falconer.Angular.SuffixDirection +OAI.MeasureTheory.Falconer.Angular.TubeDirectionRobustness +OAI.MeasureTheory.Falconer.Angular.TwoProjectionIntegerCaps +OAI.MeasureTheory.Falconer.Angular.VectorSphereKernel +OAI.MeasureTheory.Falconer.Angular.WitnessDirection +OAI.MeasureTheory.Falconer.Campaign123PlanarFurstenbergProof +OAI.MeasureTheory.Falconer.DistanceSet +OAI.MeasureTheory.Falconer.Estimates.ActualClassFamilies +OAI.MeasureTheory.Falconer.Estimates.ActualClassMass +OAI.MeasureTheory.Falconer.Estimates.ActualComparableDepthSum +OAI.MeasureTheory.Falconer.Estimates.ActualComparableFarError +OAI.MeasureTheory.Falconer.Estimates.ActualDirectBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEquation12 +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEquation20 +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEstimate +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceTerminal +OAI.MeasureTheory.Falconer.Estimates.ActualFarBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualFarEquation24 +OAI.MeasureTheory.Falconer.Estimates.ActualFarPower +OAI.MeasureTheory.Falconer.Estimates.ActualFarSourceBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualFarSourceEquation24 +OAI.MeasureTheory.Falconer.Estimates.ActualFarSpatialError +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableFar +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableMain +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableSpatial +OAI.MeasureTheory.Falconer.Estimates.ActualOuterMasks +OAI.MeasureTheory.Falconer.Estimates.ActualProductEquation13 +OAI.MeasureTheory.Falconer.Estimates.ActualProductEstimate +OAI.MeasureTheory.Falconer.Estimates.ActualRegularizedClasses +OAI.MeasureTheory.Falconer.Estimates.ActualRootEquation21 +OAI.MeasureTheory.Falconer.Estimates.ActualSuccessorUpperBounds +OAI.MeasureTheory.Falconer.Estimates.ActualTransformSplitting +OAI.MeasureTheory.Falconer.Estimates.ActualTwoPointDerivatives +OAI.MeasureTheory.Falconer.Estimates.AdaptedFailure +OAI.MeasureTheory.Falconer.Estimates.AllDimensionalMain +OAI.MeasureTheory.Falconer.Estimates.AllDimensionalOccupiedClasses +OAI.MeasureTheory.Falconer.Estimates.AllDimensionalParallelExceptional +OAI.MeasureTheory.Falconer.Estimates.AllDimensionalRegularizationCardinality +OAI.MeasureTheory.Falconer.Estimates.AllDimensionalRegularizationLabels +OAI.MeasureTheory.Falconer.Estimates.AllDimensions +OAI.MeasureTheory.Falconer.Estimates.AllTestsRestoration +OAI.MeasureTheory.Falconer.Estimates.AnchoredBufferedMasks +OAI.MeasureTheory.Falconer.Estimates.AnchoredMasks +OAI.MeasureTheory.Falconer.Estimates.AnchoredPairFailure +OAI.MeasureTheory.Falconer.Estimates.Assembly +OAI.MeasureTheory.Falconer.Estimates.Availability +OAI.MeasureTheory.Falconer.Estimates.BadTriplePower +OAI.MeasureTheory.Falconer.Estimates.BadTripleRelation +OAI.MeasureTheory.Falconer.Estimates.BuildRegularRefinement +OAI.MeasureTheory.Falconer.Estimates.CellClassifier +OAI.MeasureTheory.Falconer.Estimates.CellwisePairDeletion +OAI.MeasureTheory.Falconer.Estimates.CenteredPacketGain +OAI.MeasureTheory.Falconer.Estimates.CenteredPacketPower +OAI.MeasureTheory.Falconer.Estimates.ChargedPlane +OAI.MeasureTheory.Falconer.Estimates.ChildRetention +OAI.MeasureTheory.Falconer.Estimates.ClassBadRecombination +OAI.MeasureTheory.Falconer.Estimates.ClassPairCandidate +OAI.MeasureTheory.Falconer.Estimates.ClassPairWeights +OAI.MeasureTheory.Falconer.Estimates.ClassPruning +OAI.MeasureTheory.Falconer.Estimates.ClassRecombination +OAI.MeasureTheory.Falconer.Estimates.CoarseFloorPowers +OAI.MeasureTheory.Falconer.Estimates.CoarseFreezingBudget +OAI.MeasureTheory.Falconer.Estimates.CoarsePlanarRounding +OAI.MeasureTheory.Falconer.Estimates.CollisionFubini +OAI.MeasureTheory.Falconer.Estimates.CommonRegularFamily +OAI.MeasureTheory.Falconer.Estimates.CommonRegularReference +OAI.MeasureTheory.Falconer.Estimates.CommonTubeKernel +OAI.MeasureTheory.Falconer.Estimates.CommonTubePacking +OAI.MeasureTheory.Falconer.Estimates.CommonTubePower +OAI.MeasureTheory.Falconer.Estimates.CommonUnbalancedReference +OAI.MeasureTheory.Falconer.Estimates.ComparableBands +OAI.MeasureTheory.Falconer.Estimates.ComparableComplexRebin +OAI.MeasureTheory.Falconer.Estimates.ComparableContributionPartition +OAI.MeasureTheory.Falconer.Estimates.ComparablePositiveRebin +OAI.MeasureTheory.Falconer.Estimates.ComparableProfileFactor +OAI.MeasureTheory.Falconer.Estimates.ConditionalCollision +OAI.MeasureTheory.Falconer.Estimates.ConditionalPlanar +OAI.MeasureTheory.Falconer.Estimates.ConeSections +OAI.MeasureTheory.Falconer.Estimates.ControlledEndpointGain +OAI.MeasureTheory.Falconer.Estimates.CriticalScale +OAI.MeasureTheory.Falconer.Estimates.CrossOriginalKernel +OAI.MeasureTheory.Falconer.Estimates.DescriptorAmbient +OAI.MeasureTheory.Falconer.Estimates.DescriptorEnvelope +OAI.MeasureTheory.Falconer.Estimates.DescriptorExceptional +OAI.MeasureTheory.Falconer.Estimates.DescriptorFiberBad +OAI.MeasureTheory.Falconer.Estimates.DescriptorInverseFactors +OAI.MeasureTheory.Falconer.Estimates.DescriptorInverseRegime +OAI.MeasureTheory.Falconer.Estimates.DescriptorMaskExceptional +OAI.MeasureTheory.Falconer.Estimates.DescriptorMasks +OAI.MeasureTheory.Falconer.Estimates.DescriptorPairBudget +OAI.MeasureTheory.Falconer.Estimates.DescriptorScaledKernel +OAI.MeasureTheory.Falconer.Estimates.DescriptorSeededInverse +OAI.MeasureTheory.Falconer.Estimates.DescriptorTestBad +OAI.MeasureTheory.Falconer.Estimates.DescriptorTests +OAI.MeasureTheory.Falconer.Estimates.DilationNoncharging +OAI.MeasureTheory.Falconer.Estimates.DimensionDescent +OAI.MeasureTheory.Falconer.Estimates.DirectedPacketRows +OAI.MeasureTheory.Falconer.Estimates.DirectedSampledRows +OAI.MeasureTheory.Falconer.Estimates.DistanceActivityStrip +OAI.MeasureTheory.Falconer.Estimates.DistanceCandidateWidth +OAI.MeasureTheory.Falconer.Estimates.DistanceEligibleIndices +OAI.MeasureTheory.Falconer.Estimates.DistanceForm +OAI.MeasureTheory.Falconer.Estimates.DistanceFormFubini +OAI.MeasureTheory.Falconer.Estimates.DistanceFormRemoval +OAI.MeasureTheory.Falconer.Estimates.DistanceMatrixData +OAI.MeasureTheory.Falconer.Estimates.DistanceOccupiedSum +OAI.MeasureTheory.Falconer.Estimates.DistanceProfileFactor +OAI.MeasureTheory.Falconer.Estimates.DistanceWeightSum +OAI.MeasureTheory.Falconer.Estimates.DominatedBand +OAI.MeasureTheory.Falconer.Estimates.DyadicAncestors +OAI.MeasureTheory.Falconer.Estimates.DyadicAveraging +OAI.MeasureTheory.Falconer.Estimates.DyadicCells +OAI.MeasureTheory.Falconer.Estimates.DyadicCenters +OAI.MeasureTheory.Falconer.Estimates.DyadicDisplacements +OAI.MeasureTheory.Falconer.Estimates.DyadicEnergyStep +OAI.MeasureTheory.Falconer.Estimates.DyadicFailedTests +OAI.MeasureTheory.Falconer.Estimates.DyadicLinearApproximation +OAI.MeasureTheory.Falconer.Estimates.DyadicLocalGain +OAI.MeasureTheory.Falconer.Estimates.DyadicLocalization +OAI.MeasureTheory.Falconer.Estimates.DyadicLossAbsorption +OAI.MeasureTheory.Falconer.Estimates.DyadicPolynomialBudget +OAI.MeasureTheory.Falconer.Estimates.DyadicSecantError +OAI.MeasureTheory.Falconer.Estimates.DyadicSlopeEnergy +OAI.MeasureTheory.Falconer.Estimates.DyadicSlopeVariance +OAI.MeasureTheory.Falconer.Estimates.DyadicTree +OAI.MeasureTheory.Falconer.Estimates.Eligibility +OAI.MeasureTheory.Falconer.Estimates.EligibilityExcision +OAI.MeasureTheory.Falconer.Estimates.EndpointApplicationNumerics +OAI.MeasureTheory.Falconer.Estimates.EndpointAvailabilityGain +OAI.MeasureTheory.Falconer.Estimates.EndpointBadTriples +OAI.MeasureTheory.Falconer.Estimates.EndpointCoarsening +OAI.MeasureTheory.Falconer.Estimates.EndpointCountBudget +OAI.MeasureTheory.Falconer.Estimates.EndpointDyadicScale +OAI.MeasureTheory.Falconer.Estimates.EndpointOneScale +OAI.MeasureTheory.Falconer.Estimates.EndpointOrientedGain +OAI.MeasureTheory.Falconer.Estimates.EndpointOriginalMiddle +OAI.MeasureTheory.Falconer.Estimates.EndpointPowerAbsorption +OAI.MeasureTheory.Falconer.Estimates.EndpointRowBudget +OAI.MeasureTheory.Falconer.Estimates.EndpointScaleInputs +OAI.MeasureTheory.Falconer.Estimates.EndpointSelectionLift +OAI.MeasureTheory.Falconer.Estimates.EndpointSelectionLosses +OAI.MeasureTheory.Falconer.Estimates.EndpointSphericalPreparation +OAI.MeasureTheory.Falconer.Estimates.EndpointSubprobability +OAI.MeasureTheory.Falconer.Estimates.EndpointTwoSidedScale +OAI.MeasureTheory.Falconer.Estimates.EnergyOriginalKernel +OAI.MeasureTheory.Falconer.Estimates.EnergySplitting +OAI.MeasureTheory.Falconer.Estimates.EvenPreparation +OAI.MeasureTheory.Falconer.Estimates.FarCellCount +OAI.MeasureTheory.Falconer.Estimates.FarComparableSplit +OAI.MeasureTheory.Falconer.Estimates.FarData +OAI.MeasureTheory.Falconer.Estimates.FarDataBound +OAI.MeasureTheory.Falconer.Estimates.FarEnvelope +OAI.MeasureTheory.Falconer.Estimates.FarError +OAI.MeasureTheory.Falconer.Estimates.FarErrorOrder +OAI.MeasureTheory.Falconer.Estimates.FarKernelDataEstimates +OAI.MeasureTheory.Falconer.Estimates.FarOriginalPartition +OAI.MeasureTheory.Falconer.Estimates.FarPolicyScales +OAI.MeasureTheory.Falconer.Estimates.FarRebin +OAI.MeasureTheory.Falconer.Estimates.FarRegionScales +OAI.MeasureTheory.Falconer.Estimates.FarRegionSplit +OAI.MeasureTheory.Falconer.Estimates.FiberRegularityBudget +OAI.MeasureTheory.Falconer.Estimates.FilteredLimit +OAI.MeasureTheory.Falconer.Estimates.FinePacketCounts +OAI.MeasureTheory.Falconer.Estimates.FiniteAnchorLabels +OAI.MeasureTheory.Falconer.Estimates.FiniteCellwiseCollision +OAI.MeasureTheory.Falconer.Estimates.FiniteClassFactors +OAI.MeasureTheory.Falconer.Estimates.FiniteEnergyRegularity +OAI.MeasureTheory.Falconer.Estimates.FiniteFamilyOverlap +OAI.MeasureTheory.Falconer.Estimates.FiniteHolder +OAI.MeasureTheory.Falconer.Estimates.FiniteNearbyImages +OAI.MeasureTheory.Falconer.Estimates.FiniteOverlap +OAI.MeasureTheory.Falconer.Estimates.FinitePartitionMask +OAI.MeasureTheory.Falconer.Estimates.FinitePopularity +OAI.MeasureTheory.Falconer.Estimates.FiniteSquareIntegrable +OAI.MeasureTheory.Falconer.Estimates.FiniteTripleCounting +OAI.MeasureTheory.Falconer.Estimates.FirstExclusionShift +OAI.MeasureTheory.Falconer.Estimates.FiveInputsMain +OAI.MeasureTheory.Falconer.Estimates.FourInputsMain +OAI.MeasureTheory.Falconer.Estimates.FourPointPartition +OAI.MeasureTheory.Falconer.Estimates.FrechetCompositionScale +OAI.MeasureTheory.Falconer.Estimates.FrechetProductScale +OAI.MeasureTheory.Falconer.Estimates.GeneralColumns +OAI.MeasureTheory.Falconer.Estimates.GeneralRegularFineGain +OAI.MeasureTheory.Falconer.Estimates.GeneralRegularSetAlternative +OAI.MeasureTheory.Falconer.Estimates.GeneralTransverseCount +OAI.MeasureTheory.Falconer.Estimates.GeometricRegularFiber +OAI.MeasureTheory.Falconer.Estimates.GlobalDescriptorBounds +OAI.MeasureTheory.Falconer.Estimates.GoodCoarseRows +OAI.MeasureTheory.Falconer.Estimates.GoodRowSelection +OAI.MeasureTheory.Falconer.Estimates.GoodRowSelectionAE +OAI.MeasureTheory.Falconer.Estimates.IidSampling +OAI.MeasureTheory.Falconer.Estimates.InactivePairMass +OAI.MeasureTheory.Falconer.Estimates.IncidentCoarseRounding +OAI.MeasureTheory.Falconer.Estimates.IndependentClassEquation27 +OAI.MeasureTheory.Falconer.Estimates.IntermediateProfiles +OAI.MeasureTheory.Falconer.Estimates.InterpolatedTubeKernel +OAI.MeasureTheory.Falconer.Estimates.InverseBudget +OAI.MeasureTheory.Falconer.Estimates.InverseClassExpansion +OAI.MeasureTheory.Falconer.Estimates.InverseLeibniz +OAI.MeasureTheory.Falconer.Estimates.InversePowerSum +OAI.MeasureTheory.Falconer.Estimates.InverseScalarPullout +OAI.MeasureTheory.Falconer.Estimates.InverseScale +OAI.MeasureTheory.Falconer.Estimates.KernelL1Comparison +OAI.MeasureTheory.Falconer.Estimates.LaplacianBounds +OAI.MeasureTheory.Falconer.Estimates.LaplacianIsometry +OAI.MeasureTheory.Falconer.Estimates.LinearNonstationary +OAI.MeasureTheory.Falconer.Estimates.LinearPieces +OAI.MeasureTheory.Falconer.Estimates.ListBoundedFunctions +OAI.MeasureTheory.Falconer.Estimates.LocalCellLines +OAI.MeasureTheory.Falconer.Estimates.LocalInverse +OAI.MeasureTheory.Falconer.Estimates.LocalLineResolution +OAI.MeasureTheory.Falconer.Estimates.LocalPacketRegularity +OAI.MeasureTheory.Falconer.Estimates.LocalPacketRows +OAI.MeasureTheory.Falconer.Estimates.LocalPrefixCenters +OAI.MeasureTheory.Falconer.Estimates.LocalizationSum +OAI.MeasureTheory.Falconer.Estimates.MaskLoss +OAI.MeasureTheory.Falconer.Estimates.MaskedLowBand +OAI.MeasureTheory.Falconer.Estimates.MaskedNested +OAI.MeasureTheory.Falconer.Estimates.MixedComposition +OAI.MeasureTheory.Falconer.Estimates.MixedMaskBounds +OAI.MeasureTheory.Falconer.Estimates.MonotoneLowpass +OAI.MeasureTheory.Falconer.Estimates.NearFarSplit +OAI.MeasureTheory.Falconer.Estimates.NearPinDeletion +OAI.MeasureTheory.Falconer.Estimates.NoncomparableCommonBound +OAI.MeasureTheory.Falconer.Estimates.NoncomparableKernelScale +OAI.MeasureTheory.Falconer.Estimates.NoncomparableOriginalPointwise +OAI.MeasureTheory.Falconer.Estimates.NoncomparablePower +OAI.MeasureTheory.Falconer.Estimates.NonendpointAvailabilityGain +OAI.MeasureTheory.Falconer.Estimates.NonendpointOneScale +OAI.MeasureTheory.Falconer.Estimates.NonendpointOriginalMiddle +OAI.MeasureTheory.Falconer.Estimates.NonendpointTwoSidedScale +OAI.MeasureTheory.Falconer.Estimates.NonstationaryPower +OAI.MeasureTheory.Falconer.Estimates.NonstationaryScales +OAI.MeasureTheory.Falconer.Estimates.OccupiedClasses +OAI.MeasureTheory.Falconer.Estimates.OccupiedPacking +OAI.MeasureTheory.Falconer.Estimates.OddDescent +OAI.MeasureTheory.Falconer.Estimates.OddNonchargingPreparation +OAI.MeasureTheory.Falconer.Estimates.OddPreparedPair +OAI.MeasureTheory.Falconer.Estimates.OddProjectedPieces +OAI.MeasureTheory.Falconer.Estimates.OffPoleAmbient +OAI.MeasureTheory.Falconer.Estimates.OneInputMain +OAI.MeasureTheory.Falconer.Estimates.OneScaleParameters +OAI.MeasureTheory.Falconer.Estimates.OrderedLeibniz +OAI.MeasureTheory.Falconer.Estimates.OriginalPairFilter +OAI.MeasureTheory.Falconer.Estimates.OriginalWeakCosts +OAI.MeasureTheory.Falconer.Estimates.OuterChildProfileBound +OAI.MeasureTheory.Falconer.Estimates.OuterDescriptors +OAI.MeasureTheory.Falconer.Estimates.OuterEntryProfile +OAI.MeasureTheory.Falconer.Estimates.OuterMaskFailure +OAI.MeasureTheory.Falconer.Estimates.OuterParameters +OAI.MeasureTheory.Falconer.Estimates.OuterRestrictedConversion +OAI.MeasureTheory.Falconer.Estimates.OuterRootEquation21 +OAI.MeasureTheory.Falconer.Estimates.OuterRootGain +OAI.MeasureTheory.Falconer.Estimates.OuterScalarConversion +OAI.MeasureTheory.Falconer.Estimates.PacketCardinalityScales +OAI.MeasureTheory.Falconer.Estimates.PacketCentering +OAI.MeasureTheory.Falconer.Estimates.PacketGoodRegularFiber +OAI.MeasureTheory.Falconer.Estimates.PacketGrowthGap +OAI.MeasureTheory.Falconer.Estimates.PacketLogBounds +OAI.MeasureTheory.Falconer.Estimates.PacketParameterBounds +OAI.MeasureTheory.Falconer.Estimates.PacketPolynomialLoss +OAI.MeasureTheory.Falconer.Estimates.PacketRepresentativeBand +OAI.MeasureTheory.Falconer.Estimates.PacketResidualRows +OAI.MeasureTheory.Falconer.Estimates.PacketSamplingBudget +OAI.MeasureTheory.Falconer.Estimates.PacketScaleCombination +OAI.MeasureTheory.Falconer.Estimates.Packing +OAI.MeasureTheory.Falconer.Estimates.PairExceptional +OAI.MeasureTheory.Falconer.Estimates.ParallelCandidateCount +OAI.MeasureTheory.Falconer.Estimates.ParallelCount +OAI.MeasureTheory.Falconer.Estimates.ParallelExceptional +OAI.MeasureTheory.Falconer.Estimates.ParallelGood +OAI.MeasureTheory.Falconer.Estimates.ParallelMean +OAI.MeasureTheory.Falconer.Estimates.ParallelNumerics +OAI.MeasureTheory.Falconer.Estimates.ParallelScaleMean +OAI.MeasureTheory.Falconer.Estimates.ParentChildRetention +OAI.MeasureTheory.Falconer.Estimates.ParentPrefixRetention +OAI.MeasureTheory.Falconer.Estimates.ParentRefinedEndpointSelection +OAI.MeasureTheory.Falconer.Estimates.PatchedInverseFactors +OAI.MeasureTheory.Falconer.Estimates.PathDifferenceBound +OAI.MeasureTheory.Falconer.Estimates.PlanarCommonBudget +OAI.MeasureTheory.Falconer.Estimates.PlanarGain +OAI.MeasureTheory.Falconer.Estimates.PlanarGainNumerics +OAI.MeasureTheory.Falconer.Estimates.PlanarLossBudget +OAI.MeasureTheory.Falconer.Estimates.PlanarPathCenters +OAI.MeasureTheory.Falconer.Estimates.PlanarPrefixTruncation +OAI.MeasureTheory.Falconer.Estimates.PlanarQuarter +OAI.MeasureTheory.Falconer.Estimates.PlanarSampling +OAI.MeasureTheory.Falconer.Estimates.PlanarSelectedGain +OAI.MeasureTheory.Falconer.Estimates.PlanarSquash +OAI.MeasureTheory.Falconer.Estimates.PlanarTreeUniformization +OAI.MeasureTheory.Falconer.Estimates.PlanarWeakParameters +OAI.MeasureTheory.Falconer.Estimates.PointSamples +OAI.MeasureTheory.Falconer.Estimates.PolicyCommonBudgets +OAI.MeasureTheory.Falconer.Estimates.PolicyEnergy +OAI.MeasureTheory.Falconer.Estimates.PolicyEnergyInduction +OAI.MeasureTheory.Falconer.Estimates.PolicyEnergySteps +OAI.MeasureTheory.Falconer.Estimates.PolicyFarCoefficients +OAI.MeasureTheory.Falconer.Estimates.PolicyFarRecurrence +OAI.MeasureTheory.Falconer.Estimates.PolicyFarStep +OAI.MeasureTheory.Falconer.Estimates.PolicyLowBand +OAI.MeasureTheory.Falconer.Estimates.PolicyPrefixLowpass +OAI.MeasureTheory.Falconer.Estimates.PolicyPrefixScales +OAI.MeasureTheory.Falconer.Estimates.PolicyRootApplication +OAI.MeasureTheory.Falconer.Estimates.PolicyRootCoefficient +OAI.MeasureTheory.Falconer.Estimates.PolicyRootDecay +OAI.MeasureTheory.Falconer.Estimates.PolicyScalarConversion +OAI.MeasureTheory.Falconer.Estimates.PolicySuffixRecurrence +OAI.MeasureTheory.Falconer.Estimates.PopularRegularity +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceGoodSet +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceJetSupport +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceMasks +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceOriginalSpatial +OAI.MeasureTheory.Falconer.Estimates.PositiveDistancePushforward +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceRebinBound +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceWeight +OAI.MeasureTheory.Falconer.Estimates.PrefixCenters +OAI.MeasureTheory.Falconer.Estimates.PrefixCounting +OAI.MeasureTheory.Falconer.Estimates.PrefixRetention +OAI.MeasureTheory.Falconer.Estimates.PreparedPair +OAI.MeasureTheory.Falconer.Estimates.ProductCandidateWidth +OAI.MeasureTheory.Falconer.Estimates.ProductMatrix +OAI.MeasureTheory.Falconer.Estimates.ProductMatrixIntegrand +OAI.MeasureTheory.Falconer.Estimates.ProductMatrixReindex +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedCount +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedIntegrand +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedSum +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedVertices +OAI.MeasureTheory.Falconer.Estimates.ProductTransformPartition +OAI.MeasureTheory.Falconer.Estimates.ProductWeightSum +OAI.MeasureTheory.Falconer.Estimates.ProfileAffine +OAI.MeasureTheory.Falconer.Estimates.ProfileEnvelopes +OAI.MeasureTheory.Falconer.Estimates.ProfileInterpolation +OAI.MeasureTheory.Falconer.Estimates.ProfileMassError +OAI.MeasureTheory.Falconer.Estimates.ProfilePacking +OAI.MeasureTheory.Falconer.Estimates.ProjectedCompactPieces +OAI.MeasureTheory.Falconer.Estimates.ProjectedIndependentTuples +OAI.MeasureTheory.Falconer.Estimates.ProjectedPacketRows +OAI.MeasureTheory.Falconer.Estimates.ProjectedPair +OAI.MeasureTheory.Falconer.Estimates.ProjectedSubsetRegularity +OAI.MeasureTheory.Falconer.Estimates.PrunedVariation +OAI.MeasureTheory.Falconer.Estimates.Published +OAI.MeasureTheory.Falconer.Estimates.QuadraticBudget +OAI.MeasureTheory.Falconer.Estimates.QuadraticCoefficients +OAI.MeasureTheory.Falconer.Estimates.QuadraticDampingLimit +OAI.MeasureTheory.Falconer.Estimates.QuadraticDifferential +OAI.MeasureTheory.Falconer.Estimates.QuadraticDischarge +OAI.MeasureTheory.Falconer.Estimates.QuadraticTaylorRemainder +OAI.MeasureTheory.Falconer.Estimates.QuantitativeDifferentiation +OAI.MeasureTheory.Falconer.Estimates.QuantitativePacketPoints +OAI.MeasureTheory.Falconer.Estimates.QuarterEndpointMap +OAI.MeasureTheory.Falconer.Estimates.ReachedMasks +OAI.MeasureTheory.Falconer.Estimates.ReducedInputsMain +OAI.MeasureTheory.Falconer.Estimates.RefinedEndpointSelection +OAI.MeasureTheory.Falconer.Estimates.RegularCellConfiguration +OAI.MeasureTheory.Falconer.Estimates.RegularClassSmallTrouble +OAI.MeasureTheory.Falconer.Estimates.RegularClasses +OAI.MeasureTheory.Falconer.Estimates.RegularCoarseCells +OAI.MeasureTheory.Falconer.Estimates.RegularCoarsePreparation +OAI.MeasureTheory.Falconer.Estimates.RegularFineGain +OAI.MeasureTheory.Falconer.Estimates.RegularListRestoration +OAI.MeasureTheory.Falconer.Estimates.RegularOuterMask +OAI.MeasureTheory.Falconer.Estimates.RegularRefinementBound +OAI.MeasureTheory.Falconer.Estimates.RegularRefinementContradiction +OAI.MeasureTheory.Falconer.Estimates.RegularRefinementData +OAI.MeasureTheory.Falconer.Estimates.RegularRefinementPreparation +OAI.MeasureTheory.Falconer.Estimates.RegularRoot +OAI.MeasureTheory.Falconer.Estimates.RegularScaleCoefficients +OAI.MeasureTheory.Falconer.Estimates.RegularSetAlternative +OAI.MeasureTheory.Falconer.Estimates.RegularSourceClasses +OAI.MeasureTheory.Falconer.Estimates.RegularizationCardinality +OAI.MeasureTheory.Falconer.Estimates.RegularizationClasses +OAI.MeasureTheory.Falconer.Estimates.RegularizationCount +OAI.MeasureTheory.Falconer.Estimates.RegularizationLabels +OAI.MeasureTheory.Falconer.Estimates.RegularizationPairBounds +OAI.MeasureTheory.Falconer.Estimates.RegularizationPairMask +OAI.MeasureTheory.Falconer.Estimates.RegularizationProperties +OAI.MeasureTheory.Falconer.Estimates.RegularizationQuantifiers +OAI.MeasureTheory.Falconer.Estimates.RegularizationScales +OAI.MeasureTheory.Falconer.Estimates.RegularizationSelection +OAI.MeasureTheory.Falconer.Estimates.RegularizationSubpower +OAI.MeasureTheory.Falconer.Estimates.RegularizationTestBad +OAI.MeasureTheory.Falconer.Estimates.RegularizationVariation +OAI.MeasureTheory.Falconer.Estimates.RegularizedCellCounts +OAI.MeasureTheory.Falconer.Estimates.RegularizedMass +OAI.MeasureTheory.Falconer.Estimates.RelativePairCore +OAI.MeasureTheory.Falconer.Estimates.RelativeRegularizationGain +OAI.MeasureTheory.Falconer.Estimates.RescaledCellPackets +OAI.MeasureTheory.Falconer.Estimates.RescaledConditional +OAI.MeasureTheory.Falconer.Estimates.RestorationSeries +OAI.MeasureTheory.Falconer.Estimates.RetainedEnergy +OAI.MeasureTheory.Falconer.Estimates.RetainedPairs +OAI.MeasureTheory.Falconer.Estimates.RetainedRegularCells +OAI.MeasureTheory.Falconer.Estimates.RetainedTubeTest +OAI.MeasureTheory.Falconer.Estimates.ReverseLawTransfer +OAI.MeasureTheory.Falconer.Estimates.RootCoefficientSubpower +OAI.MeasureTheory.Falconer.Estimates.RootEquation21 +OAI.MeasureTheory.Falconer.Estimates.RootFiniteSeparation +OAI.MeasureTheory.Falconer.Estimates.RootLeibniz +OAI.MeasureTheory.Falconer.Estimates.RootLeibnizBounds +OAI.MeasureTheory.Falconer.Estimates.RootPairDerivatives +OAI.MeasureTheory.Falconer.Estimates.RootSpatialTerms +OAI.MeasureTheory.Falconer.Estimates.RootSupremum +OAI.MeasureTheory.Falconer.Estimates.RootWeightedDistance +OAI.MeasureTheory.Falconer.Estimates.RootWeightedInverse +OAI.MeasureTheory.Falconer.Estimates.RotatedInverse +OAI.MeasureTheory.Falconer.Estimates.RotatedInverseCoefficient +OAI.MeasureTheory.Falconer.Estimates.RotatedInverseCost +OAI.MeasureTheory.Falconer.Estimates.RotatedInverseExpansion +OAI.MeasureTheory.Falconer.Estimates.RotatedInverseRemainder +OAI.MeasureTheory.Falconer.Estimates.RotatedInverseScalar +OAI.MeasureTheory.Falconer.Estimates.RotatedLaws +OAI.MeasureTheory.Falconer.Estimates.RotatedMaskedRemainder +OAI.MeasureTheory.Falconer.Estimates.RotatedNonstationary +OAI.MeasureTheory.Falconer.Estimates.RotatedTubeData +OAI.MeasureTheory.Falconer.Estimates.RotatedWeightedInverse +OAI.MeasureTheory.Falconer.Estimates.RoundedEndpointGain +OAI.MeasureTheory.Falconer.Estimates.RoundedPlanarObstruction +OAI.MeasureTheory.Falconer.Estimates.RowRegularity +OAI.MeasureTheory.Falconer.Estimates.SampledRowCardinality +OAI.MeasureTheory.Falconer.Estimates.SamplingScales +OAI.MeasureTheory.Falconer.Estimates.SamplingTail +OAI.MeasureTheory.Falconer.Estimates.ScalarActualClusterGain +OAI.MeasureTheory.Falconer.Estimates.ScalarActualPorousGain +OAI.MeasureTheory.Falconer.Estimates.ScalarBinaryEmbedding +OAI.MeasureTheory.Falconer.Estimates.ScalarBinaryGeometric +OAI.MeasureTheory.Falconer.Estimates.ScalarBinaryGrowth +OAI.MeasureTheory.Falconer.Estimates.ScalarBinaryParameters +OAI.MeasureTheory.Falconer.Estimates.ScalarBoundedCoefficients +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchClusterTree +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchMargins +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchSizes +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchTransfer +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchTree +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchedPrefix +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchingSuffix +OAI.MeasureTheory.Falconer.Estimates.ScalarBunchingTotals +OAI.MeasureTheory.Falconer.Estimates.ScalarChildChoice +OAI.MeasureTheory.Falconer.Estimates.ScalarClosestScale +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterBunching +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterGain +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterPathTree +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterPorousGain +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterSums +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterTree +OAI.MeasureTheory.Falconer.Estimates.ScalarClusterWeights +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientAdd +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientClosure +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientExpressions +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientLogBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientMul +OAI.MeasureTheory.Falconer.Estimates.ScalarCoefficientNeg +OAI.MeasureTheory.Falconer.Estimates.ScalarCompressedBunching +OAI.MeasureTheory.Falconer.Estimates.ScalarCompressedLevels +OAI.MeasureTheory.Falconer.Estimates.ScalarCorrelatedWeights +OAI.MeasureTheory.Falconer.Estimates.ScalarDenseGroup +OAI.MeasureTheory.Falconer.Estimates.ScalarDifferenceDoubling +OAI.MeasureTheory.Falconer.Estimates.ScalarDilatedRefinement +OAI.MeasureTheory.Falconer.Estimates.ScalarDilationBound +OAI.MeasureTheory.Falconer.Estimates.ScalarDivideBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarDivideCoefficient +OAI.MeasureTheory.Falconer.Estimates.ScalarDyadicPowers +OAI.MeasureTheory.Falconer.Estimates.ScalarEnergyRefinement +OAI.MeasureTheory.Falconer.Estimates.ScalarErrorBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarForkSumset +OAI.MeasureTheory.Falconer.Estimates.ScalarForwardRegularization +OAI.MeasureTheory.Falconer.Estimates.ScalarGreedyPorousGain +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupOverlap +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupReverseOverlap +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupedGain +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupedHalfGain +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupedPaths +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupedTreeGain +OAI.MeasureTheory.Falconer.Estimates.ScalarGroupedWeights +OAI.MeasureTheory.Falconer.Estimates.ScalarIncrementSelection +OAI.MeasureTheory.Falconer.Estimates.ScalarInitialChildren +OAI.MeasureTheory.Falconer.Estimates.ScalarInitialDyadic +OAI.MeasureTheory.Falconer.Estimates.ScalarInitialGrowth +OAI.MeasureTheory.Falconer.Estimates.ScalarInitialPathChildren +OAI.MeasureTheory.Falconer.Estimates.ScalarInitialRegularization +OAI.MeasureTheory.Falconer.Estimates.ScalarInverseTransfer +OAI.MeasureTheory.Falconer.Estimates.ScalarLevelEnumeration +OAI.MeasureTheory.Falconer.Estimates.ScalarLogAverages +OAI.MeasureTheory.Falconer.Estimates.ScalarLossAbsorption +OAI.MeasureTheory.Falconer.Estimates.ScalarMixedRefinement +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousDoubling +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousEntropy +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousFraction +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousGrowth +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousPowers +OAI.MeasureTheory.Falconer.Estimates.ScalarNonporousTail +OAI.MeasureTheory.Falconer.Estimates.ScalarPairGrouping +OAI.MeasureTheory.Falconer.Estimates.ScalarParameterChoice +OAI.MeasureTheory.Falconer.Estimates.ScalarPartialSums +OAI.MeasureTheory.Falconer.Estimates.ScalarPathCenters +OAI.MeasureTheory.Falconer.Estimates.ScalarPathLevel +OAI.MeasureTheory.Falconer.Estimates.ScalarPathNodes +OAI.MeasureTheory.Falconer.Estimates.ScalarPluennecke +OAI.MeasureTheory.Falconer.Estimates.ScalarPointPaths +OAI.MeasureTheory.Falconer.Estimates.ScalarPorousEndpoints +OAI.MeasureTheory.Falconer.Estimates.ScalarPorousGroupingGain +OAI.MeasureTheory.Falconer.Estimates.ScalarPorousGrowth +OAI.MeasureTheory.Falconer.Estimates.ScalarPorousLevel +OAI.MeasureTheory.Falconer.Estimates.ScalarPorousLevels +OAI.MeasureTheory.Falconer.Estimates.ScalarPrefixEntropy +OAI.MeasureTheory.Falconer.Estimates.ScalarPrefixNonconcentration +OAI.MeasureTheory.Falconer.Estimates.ScalarPrefixTruncation +OAI.MeasureTheory.Falconer.Estimates.ScalarRatioCard +OAI.MeasureTheory.Falconer.Estimates.ScalarRatioFamily +OAI.MeasureTheory.Falconer.Estimates.ScalarRatioTransfer +OAI.MeasureTheory.Falconer.Estimates.ScalarReferenceObstruction +OAI.MeasureTheory.Falconer.Estimates.ScalarRegularizationBudget +OAI.MeasureTheory.Falconer.Estimates.ScalarRegularizedGrowth +OAI.MeasureTheory.Falconer.Estimates.ScalarRepeatedSums +OAI.MeasureTheory.Falconer.Estimates.ScalarResolution +OAI.MeasureTheory.Falconer.Estimates.ScalarReverseGroupedGain +OAI.MeasureTheory.Falconer.Estimates.ScalarReverseGroupedHalfGain +OAI.MeasureTheory.Falconer.Estimates.ScalarReverseGroupedWeights +OAI.MeasureTheory.Falconer.Estimates.ScalarReverseWeights +OAI.MeasureTheory.Falconer.Estimates.ScalarRounding +OAI.MeasureTheory.Falconer.Estimates.ScalarRoundingScale +OAI.MeasureTheory.Falconer.Estimates.ScalarRuzsa +OAI.MeasureTheory.Falconer.Estimates.ScalarScaleAlignment +OAI.MeasureTheory.Falconer.Estimates.ScalarScaledCard +OAI.MeasureTheory.Falconer.Estimates.ScalarSelectedForks +OAI.MeasureTheory.Falconer.Estimates.ScalarSeparatedPathTree +OAI.MeasureTheory.Falconer.Estimates.ScalarSeparatedTree +OAI.MeasureTheory.Falconer.Estimates.ScalarSignedRuzsa +OAI.MeasureTheory.Falconer.Estimates.ScalarSingletonFibers +OAI.MeasureTheory.Falconer.Estimates.ScalarSubsetTransfer +OAI.MeasureTheory.Falconer.Estimates.ScalarSumCells +OAI.MeasureTheory.Falconer.Estimates.ScalarSumsetLogBound +OAI.MeasureTheory.Falconer.Estimates.ScalarSumsetPacking +OAI.MeasureTheory.Falconer.Estimates.ScalarSwitchProgression +OAI.MeasureTheory.Falconer.Estimates.ScalarSwitchSums +OAI.MeasureTheory.Falconer.Estimates.ScalarTaggedPrefix +OAI.MeasureTheory.Falconer.Estimates.ScalarTreeAmplification +OAI.MeasureTheory.Falconer.Estimates.ScalarTreeUniformization +OAI.MeasureTheory.Falconer.Estimates.ScalarUnbalancedRefinement +OAI.MeasureTheory.Falconer.Estimates.ScalarUniformTrim +OAI.MeasureTheory.Falconer.Estimates.ScalarWeakReference +OAI.MeasureTheory.Falconer.Estimates.ScalarWeakRefinement +OAI.MeasureTheory.Falconer.Estimates.ScalarWeakScaleParameters +OAI.MeasureTheory.Falconer.Estimates.ScalarZoom +OAI.MeasureTheory.Falconer.Estimates.ScalarZoomBounds +OAI.MeasureTheory.Falconer.Estimates.ScaleThinning +OAI.MeasureTheory.Falconer.Estimates.ScaleUniformNonstationary +OAI.MeasureTheory.Falconer.Estimates.ScaledInverseRemainder +OAI.MeasureTheory.Falconer.Estimates.ScaledWeightedInverse +OAI.MeasureTheory.Falconer.Estimates.ScopedMaskVariation +OAI.MeasureTheory.Falconer.Estimates.SeededInverse +OAI.MeasureTheory.Falconer.Estimates.SelectBoundedCommonTriple +OAI.MeasureTheory.Falconer.Estimates.SelectCommonTriple +OAI.MeasureTheory.Falconer.Estimates.SelectedDistanceAssembly +OAI.MeasureTheory.Falconer.Estimates.SelectedRegularFiber +OAI.MeasureTheory.Falconer.Estimates.SeparatedInverse +OAI.MeasureTheory.Falconer.Estimates.SeparatedThinning +OAI.MeasureTheory.Falconer.Estimates.SevenInputsMain +OAI.MeasureTheory.Falconer.Estimates.SignedConvolution +OAI.MeasureTheory.Falconer.Estimates.SixInputsMain +OAI.MeasureTheory.Falconer.Estimates.SliceAverage +OAI.MeasureTheory.Falconer.Estimates.SmallUnionLogs +OAI.MeasureTheory.Falconer.Estimates.SmoothCompositionScale +OAI.MeasureTheory.Falconer.Estimates.SmoothConvolution +OAI.MeasureTheory.Falconer.Estimates.SourceAssemblyParameters +OAI.MeasureTheory.Falconer.Estimates.SourceClassMiddleData +OAI.MeasureTheory.Falconer.Estimates.SourceClassOriginalLaws +OAI.MeasureTheory.Falconer.Estimates.SourceCollisionMultiplication +OAI.MeasureTheory.Falconer.Estimates.SourceFamily +OAI.MeasureTheory.Falconer.Estimates.SourceProfileEquation25 +OAI.MeasureTheory.Falconer.Estimates.SourceRelativeRegularization +OAI.MeasureTheory.Falconer.Estimates.SourceRepresentatives +OAI.MeasureTheory.Falconer.Estimates.SourceStateTerminal +OAI.MeasureTheory.Falconer.Estimates.SourceStrongSeparation +OAI.MeasureTheory.Falconer.Estimates.SpatialAnchorMasks +OAI.MeasureTheory.Falconer.Estimates.SpatialAnnulusKernel +OAI.MeasureTheory.Falconer.Estimates.SpatialDistanceFormSeparation +OAI.MeasureTheory.Falconer.Estimates.SpatialEndpoint +OAI.MeasureTheory.Falconer.Estimates.SpatialEndpointFamily +OAI.MeasureTheory.Falconer.Estimates.SpatialLeibnizSubpower +OAI.MeasureTheory.Falconer.Estimates.SpatialPhasedDistanceForm +OAI.MeasureTheory.Falconer.Estimates.SpatialPlancherel +OAI.MeasureTheory.Falconer.Estimates.SpatialSharedBound +OAI.MeasureTheory.Falconer.Estimates.SpatialSharedRegularity +OAI.MeasureTheory.Falconer.Estimates.SphericalEnergy +OAI.MeasureTheory.Falconer.Estimates.SquashGainBudget +OAI.MeasureTheory.Falconer.Estimates.StartingDescent +OAI.MeasureTheory.Falconer.Estimates.StartingPreparation +OAI.MeasureTheory.Falconer.Estimates.SuffixCollision +OAI.MeasureTheory.Falconer.Estimates.SuffixGrouping +OAI.MeasureTheory.Falconer.Estimates.SuffixReduction +OAI.MeasureTheory.Falconer.Estimates.SuffixScales +OAI.MeasureTheory.Falconer.Estimates.TestWidths +OAI.MeasureTheory.Falconer.Estimates.ThreeInputsMain +OAI.MeasureTheory.Falconer.Estimates.ThreeTubePullback +OAI.MeasureTheory.Falconer.Estimates.TransversePhysicalCount +OAI.MeasureTheory.Falconer.Estimates.TripleColumns +OAI.MeasureTheory.Falconer.Estimates.TripleGram +OAI.MeasureTheory.Falconer.Estimates.TripleGramStability +OAI.MeasureTheory.Falconer.Estimates.TroublesomePair +OAI.MeasureTheory.Falconer.Estimates.TruncatedDyadicBound +OAI.MeasureTheory.Falconer.Estimates.TubePacketDilation +OAI.MeasureTheory.Falconer.Estimates.TubeSecondMoment +OAI.MeasureTheory.Falconer.Estimates.TubeUniformization +OAI.MeasureTheory.Falconer.Estimates.TwoInputsMain +OAI.MeasureTheory.Falconer.Estimates.TwoPolicyEnergy +OAI.MeasureTheory.Falconer.Estimates.TwoProjectedLaws +OAI.MeasureTheory.Falconer.Estimates.TwoScaleRatio +OAI.MeasureTheory.Falconer.Estimates.UniformDescriptorFactors +OAI.MeasureTheory.Falconer.Estimates.UniformLowerPlanes +OAI.MeasureTheory.Falconer.Estimates.UniformPacketBounds +OAI.MeasureTheory.Falconer.Estimates.UniformSamples +OAI.MeasureTheory.Falconer.Estimates.UniformScaleCombination +OAI.MeasureTheory.Falconer.Estimates.ValidDescriptors +OAI.MeasureTheory.Falconer.Estimates.WeightedCauchy +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceNestedDomination +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceNestedSupport +OAI.MeasureTheory.Falconer.Estimates.WeightedDistancePushforward +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceSourceMapping +OAI.MeasureTheory.Falconer.Estimates.WeightedDyadicRegularity +OAI.MeasureTheory.Falconer.Estimates.WeightedInverse +OAI.MeasureTheory.Falconer.Estimates.WeightedLowpass +OAI.MeasureTheory.Falconer.Fourier.ActualDistanceLowBand +OAI.MeasureTheory.Falconer.Fourier.ActualSymbolEstimates +OAI.MeasureTheory.Falconer.Fourier.AllDimensionalSpatialFourierIntegration +OAI.MeasureTheory.Falconer.Fourier.AllDimensionalSpatialFourierSeparation +OAI.MeasureTheory.Falconer.Fourier.AmbientSymbols +OAI.MeasureTheory.Falconer.Fourier.AnchorSymbolDropping +OAI.MeasureTheory.Falconer.Fourier.AssemblyCutoff +OAI.MeasureTheory.Falconer.Fourier.BaseJetAmplitude +OAI.MeasureTheory.Falconer.Fourier.BinKernel +OAI.MeasureTheory.Falconer.Fourier.BorelSymbols +OAI.MeasureTheory.Falconer.Fourier.BumpDerivatives +OAI.MeasureTheory.Falconer.Fourier.CellSymbols +OAI.MeasureTheory.Falconer.Fourier.ChartBumps +OAI.MeasureTheory.Falconer.Fourier.ChartDerivatives +OAI.MeasureTheory.Falconer.Fourier.ChartJetOperators +OAI.MeasureTheory.Falconer.Fourier.ChartSymbolControl +OAI.MeasureTheory.Falconer.Fourier.CompactFourierBound +OAI.MeasureTheory.Falconer.Fourier.ComplexMaskJets +OAI.MeasureTheory.Falconer.Fourier.ConeIntegration +OAI.MeasureTheory.Falconer.Fourier.CoordinateIntegral +OAI.MeasureTheory.Falconer.Fourier.DescriptorDerivativeScale +OAI.MeasureTheory.Falconer.Fourier.DescriptorInverseJets +OAI.MeasureTheory.Falconer.Fourier.DescriptorJetMeasurable +OAI.MeasureTheory.Falconer.Fourier.DescriptorJetProduct +OAI.MeasureTheory.Falconer.Fourier.DescriptorJetRemoval +OAI.MeasureTheory.Falconer.Fourier.DescriptorPairDerivativeScale +OAI.MeasureTheory.Falconer.Fourier.DistanceBandKernelBound +OAI.MeasureTheory.Falconer.Fourier.DistanceFourierDifference +OAI.MeasureTheory.Falconer.Fourier.DistanceFrequencyBox +OAI.MeasureTheory.Falconer.Fourier.DistanceFrequencyMajorant +OAI.MeasureTheory.Falconer.Fourier.DistanceKernelSplitting +OAI.MeasureTheory.Falconer.Fourier.DistanceSincCollision +OAI.MeasureTheory.Falconer.Fourier.DistanceSincKernel +OAI.MeasureTheory.Falconer.Fourier.DistanceSincSpectralIdentity +OAI.MeasureTheory.Falconer.Fourier.DyadicTransforms +OAI.MeasureTheory.Falconer.Fourier.EndpointTransform +OAI.MeasureTheory.Falconer.Fourier.EuclideanPolar +OAI.MeasureTheory.Falconer.Fourier.EuclideanSmoothConvolution +OAI.MeasureTheory.Falconer.Fourier.FarCollisionIntegral +OAI.MeasureTheory.Falconer.Fourier.FarIntegralAssembly +OAI.MeasureTheory.Falconer.Fourier.FarTestedIntegral +OAI.MeasureTheory.Falconer.Fourier.FiberSchwartz +OAI.MeasureTheory.Falconer.Fourier.FourStationaryPhases +OAI.MeasureTheory.Falconer.Fourier.FourierBandBound +OAI.MeasureTheory.Falconer.Fourier.FourierBandDecomposition +OAI.MeasureTheory.Falconer.Fourier.FourierConvolution +OAI.MeasureTheory.Falconer.Fourier.FourierEnergy +OAI.MeasureTheory.Falconer.Fourier.FourierLebesgue +OAI.MeasureTheory.Falconer.Fourier.FourierPairing +OAI.MeasureTheory.Falconer.Fourier.FourierSlice +OAI.MeasureTheory.Falconer.Fourier.GaussianRepresentation +OAI.MeasureTheory.Falconer.Fourier.GoodSupportedKernelMajorant +OAI.MeasureTheory.Falconer.Fourier.GraphActualFrequencySupport +OAI.MeasureTheory.Falconer.Fourier.GraphFourPointKernel +OAI.MeasureTheory.Falconer.Fourier.GraphFourSymbolDerivatives +OAI.MeasureTheory.Falconer.Fourier.GraphKernelBounds +OAI.MeasureTheory.Falconer.Fourier.HalfDimensionalFourier +OAI.MeasureTheory.Falconer.Fourier.InheritedSymbolMeasurability +OAI.MeasureTheory.Falconer.Fourier.InheritedSymbolSupport +OAI.MeasureTheory.Falconer.Fourier.IntegratedSmoothing +OAI.MeasureTheory.Falconer.Fourier.InverseClassIntegration +OAI.MeasureTheory.Falconer.Fourier.InverseJetCoefficient +OAI.MeasureTheory.Falconer.Fourier.InverseJetIntegration +OAI.MeasureTheory.Falconer.Fourier.InverseJetShell +OAI.MeasureTheory.Falconer.Fourier.InverseJetState +OAI.MeasureTheory.Falconer.Fourier.InverseJetSupport +OAI.MeasureTheory.Falconer.Fourier.InverseJetSymbols +OAI.MeasureTheory.Falconer.Fourier.InverseJetValues +OAI.MeasureTheory.Falconer.Fourier.InverseMaskJets +OAI.MeasureTheory.Falconer.Fourier.JetAdmissible +OAI.MeasureTheory.Falconer.Fourier.JetChartControl +OAI.MeasureTheory.Falconer.Fourier.JetDerivativeBounds +OAI.MeasureTheory.Falconer.Fourier.JetNormalization +OAI.MeasureTheory.Falconer.Fourier.JetStateAmbient +OAI.MeasureTheory.Falconer.Fourier.JetStateAntipodal +OAI.MeasureTheory.Falconer.Fourier.JetStateBudget +OAI.MeasureTheory.Falconer.Fourier.JetStateBudgetOrder +OAI.MeasureTheory.Falconer.Fourier.JetStateChildren +OAI.MeasureTheory.Falconer.Fourier.JetStateCrossKernel +OAI.MeasureTheory.Falconer.Fourier.JetStateEnvelope +OAI.MeasureTheory.Falconer.Fourier.JetStateFarBand +OAI.MeasureTheory.Falconer.Fourier.JetStateFarExpansion +OAI.MeasureTheory.Falconer.Fourier.JetStateFarKernel +OAI.MeasureTheory.Falconer.Fourier.JetStateFarOriginal +OAI.MeasureTheory.Falconer.Fourier.JetStateFarRemainder +OAI.MeasureTheory.Falconer.Fourier.JetStateFarSupport +OAI.MeasureTheory.Falconer.Fourier.JetStateNear +OAI.MeasureTheory.Falconer.Fourier.JetStateNearFar +OAI.MeasureTheory.Falconer.Fourier.JetStateNoncomparable +OAI.MeasureTheory.Falconer.Fourier.JetStateNoncomparableFull +OAI.MeasureTheory.Falconer.Fourier.JetStateOperations +OAI.MeasureTheory.Falconer.Fourier.JetStateOriginalEnergy +OAI.MeasureTheory.Falconer.Fourier.JetStateSpatialShell +OAI.MeasureTheory.Falconer.Fourier.JetStateStationary +OAI.MeasureTheory.Falconer.Fourier.JointStationaryGeometry +OAI.MeasureTheory.Falconer.Fourier.KernelFourierIdentity +OAI.MeasureTheory.Falconer.Fourier.LaplacianFourier +OAI.MeasureTheory.Falconer.Fourier.LocalStationaryJets +OAI.MeasureTheory.Falconer.Fourier.LowFrequencyKernel +OAI.MeasureTheory.Falconer.Fourier.MaskJetAlgebra +OAI.MeasureTheory.Falconer.Fourier.MaskJetCount +OAI.MeasureTheory.Falconer.Fourier.MaskJetGeometry +OAI.MeasureTheory.Falconer.Fourier.MaskJetIsometry +OAI.MeasureTheory.Falconer.Fourier.MaskJetSeed +OAI.MeasureTheory.Falconer.Fourier.MaskJetSeparation +OAI.MeasureTheory.Falconer.Fourier.MaskedFourier +OAI.MeasureTheory.Falconer.Fourier.MaskedJetBudget +OAI.MeasureTheory.Falconer.Fourier.MaskedStationaryJets +OAI.MeasureTheory.Falconer.Fourier.MatrixCofactorBound +OAI.MeasureTheory.Falconer.Fourier.MeasureKernelConvolution +OAI.MeasureTheory.Falconer.Fourier.MellinGaussian +OAI.MeasureTheory.Falconer.Fourier.MinimalPairSymbol +OAI.MeasureTheory.Falconer.Fourier.NoncomparableOriginalIntegral +OAI.MeasureTheory.Falconer.Fourier.NonstationaryPhase +OAI.MeasureTheory.Falconer.Fourier.NormalizedJetDerivatives +OAI.MeasureTheory.Falconer.Fourier.NormalizedSymbolFactors +OAI.MeasureTheory.Falconer.Fourier.OriginalStationaryPower +OAI.MeasureTheory.Falconer.Fourier.OriginalStationaryReplacement +OAI.MeasureTheory.Falconer.Fourier.OscillatoryExpansion +OAI.MeasureTheory.Falconer.Fourier.OscillatoryTaylor +OAI.MeasureTheory.Falconer.Fourier.ParametricJets +OAI.MeasureTheory.Falconer.Fourier.ParentInactiveKernel +OAI.MeasureTheory.Falconer.Fourier.PhaseIntegration +OAI.MeasureTheory.Falconer.Fourier.PlaneFourierNonstationary +OAI.MeasureTheory.Falconer.Fourier.PoleCutoffs +OAI.MeasureTheory.Falconer.Fourier.PoleStationarySupport +OAI.MeasureTheory.Falconer.Fourier.PolicyJetChildren +OAI.MeasureTheory.Falconer.Fourier.PolicyJetData +OAI.MeasureTheory.Falconer.Fourier.PositiveDistanceSpatialKernel +OAI.MeasureTheory.Falconer.Fourier.PositiveFourier +OAI.MeasureTheory.Falconer.Fourier.ProductFilterIntegral +OAI.MeasureTheory.Falconer.Fourier.ProfileDerivativePoint +OAI.MeasureTheory.Falconer.Fourier.ProfileMergeCutoff +OAI.MeasureTheory.Falconer.Fourier.PublishedQuadraticStationary +OAI.MeasureTheory.Falconer.Fourier.QuadraticGaussianPairing +OAI.MeasureTheory.Falconer.Fourier.QuadraticIntegral +OAI.MeasureTheory.Falconer.Fourier.QuadraticJacobian +OAI.MeasureTheory.Falconer.Fourier.QuadraticKernelBounds +OAI.MeasureTheory.Falconer.Fourier.QuadraticStationary +OAI.MeasureTheory.Falconer.Fourier.ReachedMaskJets +OAI.MeasureTheory.Falconer.Fourier.RootFourierError +OAI.MeasureTheory.Falconer.Fourier.RootKernelTerms +OAI.MeasureTheory.Falconer.Fourier.RootNormalizedKernel +OAI.MeasureTheory.Falconer.Fourier.RootPairSymbols +OAI.MeasureTheory.Falconer.Fourier.RootUniformFourier +OAI.MeasureTheory.Falconer.Fourier.RotatedInverseIntegration +OAI.MeasureTheory.Falconer.Fourier.RotatedInverseSymbols +OAI.MeasureTheory.Falconer.Fourier.RotatedMaskedJetShell +OAI.MeasureTheory.Falconer.Fourier.SafeStationaryChart +OAI.MeasureTheory.Falconer.Fourier.ScaledInverseIntegration +OAI.MeasureTheory.Falconer.Fourier.SchwartzFourierMomentBounds +OAI.MeasureTheory.Falconer.Fourier.SchwartzFourierMoments +OAI.MeasureTheory.Falconer.Fourier.SchwartzLpTests +OAI.MeasureTheory.Falconer.Fourier.SeparatedInverseIntegration +OAI.MeasureTheory.Falconer.Fourier.SeparatedJets +OAI.MeasureTheory.Falconer.Fourier.SignedStationary +OAI.MeasureTheory.Falconer.Fourier.SmoothKernel +OAI.MeasureTheory.Falconer.Fourier.SmoothMask +OAI.MeasureTheory.Falconer.Fourier.SmoothMaskDerivatives +OAI.MeasureTheory.Falconer.Fourier.SmoothReciprocal +OAI.MeasureTheory.Falconer.Fourier.SpatialAnnulusKernel +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierIntegration +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierSeparation +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierTests +OAI.MeasureTheory.Falconer.Fourier.SpatialPhasedSymbols +OAI.MeasureTheory.Falconer.Fourier.SpatialSymbols +OAI.MeasureTheory.Falconer.Fourier.StationaryCoefficients +OAI.MeasureTheory.Falconer.Fourier.StationaryInverse +OAI.MeasureTheory.Falconer.Fourier.StationaryScales +OAI.MeasureTheory.Falconer.Fourier.StationaryTransport +OAI.MeasureTheory.Falconer.Fourier.StationaryWeightCancellation +OAI.MeasureTheory.Falconer.Fourier.SymbolOrder +OAI.MeasureTheory.Falconer.Fourier.SymbolProduct +OAI.MeasureTheory.Falconer.Fourier.SymbolProductBounds +OAI.MeasureTheory.Falconer.Fourier.TwoProfileDerivatives +OAI.MeasureTheory.Falconer.Fourier.TwoProfileInverseIntegration +OAI.MeasureTheory.Falconer.Fourier.UniformJetBudget +OAI.MeasureTheory.Falconer.Fourier.UniformSymbolScale +OAI.MeasureTheory.Falconer.Fourier.WeightedDistanceFourier +OAI.MeasureTheory.Falconer.Fourier.WeightedDistanceLowFrequency +OAI.MeasureTheory.Falconer.Fourier.WeightedDistancePositiveKernel +OAI.MeasureTheory.Falconer.Frostman.AtomlessRadialContinuity +OAI.MeasureTheory.Falconer.Frostman.Capacity +OAI.MeasureTheory.Falconer.Frostman.Content +OAI.MeasureTheory.Falconer.Frostman.ContentBound +OAI.MeasureTheory.Falconer.Frostman.Frostman +OAI.MeasureTheory.Falconer.Frostman.FrostmanProfileCells +OAI.MeasureTheory.Falconer.Frostman.GeometricCapacity +OAI.MeasureTheory.Falconer.Geometry.ActiveCoverScale +OAI.MeasureTheory.Falconer.Geometry.AmbientChartBudget +OAI.MeasureTheory.Falconer.Geometry.BallTruncation +OAI.MeasureTheory.Falconer.Geometry.BinBands +OAI.MeasureTheory.Falconer.Geometry.BinEstimates +OAI.MeasureTheory.Falconer.Geometry.BinOffsets +OAI.MeasureTheory.Falconer.Geometry.Bins +OAI.MeasureTheory.Falconer.Geometry.BoundedChartFineGain +OAI.MeasureTheory.Falconer.Geometry.BoundedProjectionCoordinates +OAI.MeasureTheory.Falconer.Geometry.CellNormalization +OAI.MeasureTheory.Falconer.Geometry.CellNorthFrame +OAI.MeasureTheory.Falconer.Geometry.CellwiseDistanceForm +OAI.MeasureTheory.Falconer.Geometry.ChartCoordinates +OAI.MeasureTheory.Falconer.Geometry.ChartCostMeasurable +OAI.MeasureTheory.Falconer.Geometry.ChartFiniteScaleBounds +OAI.MeasureTheory.Falconer.Geometry.ChartFrame +OAI.MeasureTheory.Falconer.Geometry.ChartGainBudget +OAI.MeasureTheory.Falconer.Geometry.ChartGeometry +OAI.MeasureTheory.Falconer.Geometry.ChartNonstationary +OAI.MeasureTheory.Falconer.Geometry.ChartPairPower +OAI.MeasureTheory.Falconer.Geometry.ChartPairTransfer +OAI.MeasureTheory.Falconer.Geometry.ChooseNonchargingProjection +OAI.MeasureTheory.Falconer.Geometry.CommonNormalizedProjections +OAI.MeasureTheory.Falconer.Geometry.CommonProjectionConfiguration +OAI.MeasureTheory.Falconer.Geometry.CommonProjectionLosses +OAI.MeasureTheory.Falconer.Geometry.CommonRatioProjections +OAI.MeasureTheory.Falconer.Geometry.CommonRectangles +OAI.MeasureTheory.Falconer.Geometry.CommonSmallProjections +OAI.MeasureTheory.Falconer.Geometry.CommonUnbalancedProjections +OAI.MeasureTheory.Falconer.Geometry.CompactMultiplierScale +OAI.MeasureTheory.Falconer.Geometry.CompactQuadraticExpansion +OAI.MeasureTheory.Falconer.Geometry.CompactSublevel +OAI.MeasureTheory.Falconer.Geometry.ComparableCellCounting +OAI.MeasureTheory.Falconer.Geometry.ConditionalBalls +OAI.MeasureTheory.Falconer.Geometry.ConditionalCellGeometry +OAI.MeasureTheory.Falconer.Geometry.ConditionalProjectionBuffer +OAI.MeasureTheory.Falconer.Geometry.ConditionalProjectionTest +OAI.MeasureTheory.Falconer.Geometry.CubeBallBound +OAI.MeasureTheory.Falconer.Geometry.CubeBallPacking +OAI.MeasureTheory.Falconer.Geometry.DyadicBallCount +OAI.MeasureTheory.Falconer.Geometry.DyadicCenterSeparation +OAI.MeasureTheory.Falconer.Geometry.DyadicClasses +OAI.MeasureTheory.Falconer.Geometry.DyadicCube +OAI.MeasureTheory.Falconer.Geometry.DyadicGeometry +OAI.MeasureTheory.Falconer.Geometry.DyadicInverseDistance +OAI.MeasureTheory.Falconer.Geometry.DyadicPacking +OAI.MeasureTheory.Falconer.Geometry.DyadicScaleBallBounds +OAI.MeasureTheory.Falconer.Geometry.DyadicSeparation +OAI.MeasureTheory.Falconer.Geometry.EndpointChartGain +OAI.MeasureTheory.Falconer.Geometry.EndpointChartObstruction +OAI.MeasureTheory.Falconer.Geometry.EndpointChartRadius +OAI.MeasureTheory.Falconer.Geometry.EndpointChartSelection +OAI.MeasureTheory.Falconer.Geometry.EndpointMidscaleCover +OAI.MeasureTheory.Falconer.Geometry.EndpointNormalize +OAI.MeasureTheory.Falconer.Geometry.EuclideanBallNet +OAI.MeasureTheory.Falconer.Geometry.EuclideanCross +OAI.MeasureTheory.Falconer.Geometry.EuclideanLpTrace +OAI.MeasureTheory.Falconer.Geometry.EuclideanMollifier +OAI.MeasureTheory.Falconer.Geometry.EuclideanRieszEnergy +OAI.MeasureTheory.Falconer.Geometry.EuclideanTrace +OAI.MeasureTheory.Falconer.Geometry.EuclideanWeakApproximation +OAI.MeasureTheory.Falconer.Geometry.FactorChartControl +OAI.MeasureTheory.Falconer.Geometry.FarCellGeometry +OAI.MeasureTheory.Falconer.Geometry.FarNormalization +OAI.MeasureTheory.Falconer.Geometry.FarNormalizedBound +OAI.MeasureTheory.Falconer.Geometry.FiniteBinComparison +OAI.MeasureTheory.Falconer.Geometry.FinitePrefixBallBound +OAI.MeasureTheory.Falconer.Geometry.FinitePrefixCover +OAI.MeasureTheory.Falconer.Geometry.FiniteProjectionSublevels +OAI.MeasureTheory.Falconer.Geometry.FiniteScaleBall +OAI.MeasureTheory.Falconer.Geometry.FiniteWeightedProjectionSample +OAI.MeasureTheory.Falconer.Geometry.FixedChartBounds +OAI.MeasureTheory.Falconer.Geometry.FrameEmbedding +OAI.MeasureTheory.Falconer.Geometry.FrequencyGeometry +OAI.MeasureTheory.Falconer.Geometry.FullChartRegularGain +OAI.MeasureTheory.Falconer.Geometry.GeneralFrameBound +OAI.MeasureTheory.Falconer.Geometry.GeneralGridRounding +OAI.MeasureTheory.Falconer.Geometry.GeneralTransverseGrid +OAI.MeasureTheory.Falconer.Geometry.GridBallOverlap +OAI.MeasureTheory.Falconer.Geometry.GridProjectionTransfer +OAI.MeasureTheory.Falconer.Geometry.HalfSlopeGrid +OAI.MeasureTheory.Falconer.Geometry.InactiveBinDecay +OAI.MeasureTheory.Falconer.Geometry.InactiveBinGeometry +OAI.MeasureTheory.Falconer.Geometry.InactiveBinScales +OAI.MeasureTheory.Falconer.Geometry.IntegerBox +OAI.MeasureTheory.Falconer.Geometry.IntegerEnergyRefinement +OAI.MeasureTheory.Falconer.Geometry.IntegerFivePaths +OAI.MeasureTheory.Falconer.Geometry.IntegerFourPaths +OAI.MeasureTheory.Falconer.Geometry.IntegerMixedRefinement +OAI.MeasureTheory.Falconer.Geometry.IntegerRectangle +OAI.MeasureTheory.Falconer.Geometry.IntegerSumEnergy +OAI.MeasureTheory.Falconer.Geometry.LocalPointBalls +OAI.MeasureTheory.Falconer.Geometry.LocalPrefixCover +OAI.MeasureTheory.Falconer.Geometry.MaskedGeometry +OAI.MeasureTheory.Falconer.Geometry.MiddleScaleGeometry +OAI.MeasureTheory.Falconer.Geometry.NonendpointChartGain +OAI.MeasureTheory.Falconer.Geometry.NonstationaryGeometry +OAI.MeasureTheory.Falconer.Geometry.NormalSeparation +OAI.MeasureTheory.Falconer.Geometry.NormalizedDescriptorFamily +OAI.MeasureTheory.Falconer.Geometry.NormalizedGainBudget +OAI.MeasureTheory.Falconer.Geometry.NormalizedInverseFactors +OAI.MeasureTheory.Falconer.Geometry.NormalizedRegularGain +OAI.MeasureTheory.Falconer.Geometry.NormalizedSpatialFactors +OAI.MeasureTheory.Falconer.Geometry.NormalizedTripleGram +OAI.MeasureTheory.Falconer.Geometry.OccupiedCellSeparation +OAI.MeasureTheory.Falconer.Geometry.OneScaleGeometry +OAI.MeasureTheory.Falconer.Geometry.OrthonormalRectangle +OAI.MeasureTheory.Falconer.Geometry.ParentEndpointGeometry +OAI.MeasureTheory.Falconer.Geometry.PiCoordinateSections +OAI.MeasureTheory.Falconer.Geometry.PlanarChartRepair +OAI.MeasureTheory.Falconer.Geometry.PlanarGridCosts +OAI.MeasureTheory.Falconer.Geometry.PlanarGridRegularity +OAI.MeasureTheory.Falconer.Geometry.PlanarGridScales +OAI.MeasureTheory.Falconer.Geometry.PlanarProjectionCoordinates +OAI.MeasureTheory.Falconer.Geometry.PlanarScalarGrid +OAI.MeasureTheory.Falconer.Geometry.PlanarSlopeBalls +OAI.MeasureTheory.Falconer.Geometry.PointBallCounts +OAI.MeasureTheory.Falconer.Geometry.PolynomialNormalization +OAI.MeasureTheory.Falconer.Geometry.PositiveDistanceBins +OAI.MeasureTheory.Falconer.Geometry.ProfileGrid +OAI.MeasureTheory.Falconer.Geometry.ProjectedSeparation +OAI.MeasureTheory.Falconer.Geometry.ProjectionBuffer +OAI.MeasureTheory.Falconer.Geometry.ProjectionCells +OAI.MeasureTheory.Falconer.Geometry.ProjectionCollisionMean +OAI.MeasureTheory.Falconer.Geometry.ProjectionCoordinateBalls +OAI.MeasureTheory.Falconer.Geometry.ProjectionCube +OAI.MeasureTheory.Falconer.Geometry.ProjectionDilation +OAI.MeasureTheory.Falconer.Geometry.ProjectionExceptional +OAI.MeasureTheory.Falconer.Geometry.ProjectionGood +OAI.MeasureTheory.Falconer.Geometry.ProjectionKernel +OAI.MeasureTheory.Falconer.Geometry.ProjectionLaw +OAI.MeasureTheory.Falconer.Geometry.ProjectionPowerBudget +OAI.MeasureTheory.Falconer.Geometry.ProjectionRatioBounds +OAI.MeasureTheory.Falconer.Geometry.ProjectionRatioGeometry +OAI.MeasureTheory.Falconer.Geometry.ProjectionRatioRegularity +OAI.MeasureTheory.Falconer.Geometry.ProjectionRescaling +OAI.MeasureTheory.Falconer.Geometry.ProjectionRows +OAI.MeasureTheory.Falconer.Geometry.ProjectionSampleBudget +OAI.MeasureTheory.Falconer.Geometry.ProjectionSinc +OAI.MeasureTheory.Falconer.Geometry.QuadraticChart +OAI.MeasureTheory.Falconer.Geometry.QuadraticNormalization +OAI.MeasureTheory.Falconer.Geometry.QuarterChartFineGain +OAI.MeasureTheory.Falconer.Geometry.QuarterCoarseCover +OAI.MeasureTheory.Falconer.Geometry.RegularCoordinateRows +OAI.MeasureTheory.Falconer.Geometry.RegularSmallProjections +OAI.MeasureTheory.Falconer.Geometry.RelativeGridError +OAI.MeasureTheory.Falconer.Geometry.RelativePrefixBallBound +OAI.MeasureTheory.Falconer.Geometry.RetainedCoarseCover +OAI.MeasureTheory.Falconer.Geometry.RetainedEndpointGeometry +OAI.MeasureTheory.Falconer.Geometry.RobustProjectionSets +OAI.MeasureTheory.Falconer.Geometry.RootPatchGeometry +OAI.MeasureTheory.Falconer.Geometry.RootSimilarityGeometry +OAI.MeasureTheory.Falconer.Geometry.RoundedProjectionCoordinates +OAI.MeasureTheory.Falconer.Geometry.RowTubeBalls +OAI.MeasureTheory.Falconer.Geometry.SamplingGrid +OAI.MeasureTheory.Falconer.Geometry.ScalarBallCandidates +OAI.MeasureTheory.Falconer.Geometry.ScalarBoundedProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarBunchGeometry +OAI.MeasureTheory.Falconer.Geometry.ScalarBunchNetGain +OAI.MeasureTheory.Falconer.Geometry.ScalarBunchProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarClosureProjections +OAI.MeasureTheory.Falconer.Geometry.ScalarClusterProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarCoverCount +OAI.MeasureTheory.Falconer.Geometry.ScalarCoverStability +OAI.MeasureTheory.Falconer.Geometry.ScalarDyadicProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarForkGeometry +OAI.MeasureTheory.Falconer.Geometry.ScalarGridFibers +OAI.MeasureTheory.Falconer.Geometry.ScalarGridGrouping +OAI.MeasureTheory.Falconer.Geometry.ScalarGridThinning +OAI.MeasureTheory.Falconer.Geometry.ScalarGroupGeometry +OAI.MeasureTheory.Falconer.Geometry.ScalarGroupReverseGeometry +OAI.MeasureTheory.Falconer.Geometry.ScalarGrowthOfCover +OAI.MeasureTheory.Falconer.Geometry.ScalarMaxRatioProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarNetAmplification +OAI.MeasureTheory.Falconer.Geometry.ScalarNetIteration +OAI.MeasureTheory.Falconer.Geometry.ScalarNonporousCover +OAI.MeasureTheory.Falconer.Geometry.ScalarNormalizationCost +OAI.MeasureTheory.Falconer.Geometry.ScalarNormalizedCoefficients +OAI.MeasureTheory.Falconer.Geometry.ScalarNormalizedLogBudget +OAI.MeasureTheory.Falconer.Geometry.ScalarNormalizedProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarProjectionDoubling +OAI.MeasureTheory.Falconer.Geometry.ScalarRationalProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarRoundingBalls +OAI.MeasureTheory.Falconer.Geometry.ScalarRoundingCovers +OAI.MeasureTheory.Falconer.Geometry.ScalarRuzsaCovering +OAI.MeasureTheory.Falconer.Geometry.ScalarSmallSumCover +OAI.MeasureTheory.Falconer.Geometry.ScalarUnitProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarWeakProjection +OAI.MeasureTheory.Falconer.Geometry.ScalarWeakRadiusProjection +OAI.MeasureTheory.Falconer.Geometry.ScaledDyadicPacking +OAI.MeasureTheory.Falconer.Geometry.SeededSeparation +OAI.MeasureTheory.Falconer.Geometry.SelectTransverseChartTriple +OAI.MeasureTheory.Falconer.Geometry.SelectedBinAmplitude +OAI.MeasureTheory.Falconer.Geometry.SelectedChartGeometry +OAI.MeasureTheory.Falconer.Geometry.SelectedChartRelation +OAI.MeasureTheory.Falconer.Geometry.SeparatedDistanceMaximum +OAI.MeasureTheory.Falconer.Geometry.SeparatedProjectionBases +OAI.MeasureTheory.Falconer.Geometry.SeparatedSpatialDistanceForm +OAI.MeasureTheory.Falconer.Geometry.SeparationOrder +OAI.MeasureTheory.Falconer.Geometry.SimilarityGeometry +OAI.MeasureTheory.Falconer.Geometry.SmallChartCube +OAI.MeasureTheory.Falconer.Geometry.SquashCover +OAI.MeasureTheory.Falconer.Geometry.SurfaceTestNorm +OAI.MeasureTheory.Falconer.Geometry.TransverseGridCoordinates +OAI.MeasureTheory.Falconer.Geometry.TripleFrameBound +OAI.MeasureTheory.Falconer.Geometry.TripleGridRounding +OAI.MeasureTheory.Falconer.Geometry.TroublesomeCovers +OAI.MeasureTheory.Falconer.Geometry.TruncatedDyadicBalls +OAI.MeasureTheory.Falconer.Geometry.TubeAnchorNet +OAI.MeasureTheory.Falconer.Geometry.TubeFiberCoordinates +OAI.MeasureTheory.Falconer.Geometry.TwoNormalProjection +OAI.MeasureTheory.Falconer.Geometry.TwoPointTubeGeometry +OAI.MeasureTheory.Falconer.Geometry.TwoProjectionCubes +OAI.MeasureTheory.Falconer.Geometry.TwoProjectionFrame +OAI.MeasureTheory.Falconer.Geometry.TwoProjectionPiecePair +OAI.MeasureTheory.Falconer.Geometry.TwoProjectionPieces +OAI.MeasureTheory.Falconer.Geometry.UnbalancedRatioNormalization +OAI.MeasureTheory.Falconer.Geometry.UniformMiddleGeometry +OAI.MeasureTheory.Falconer.Graphs.ActualDirectGraph +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceChildEnergy +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceDegrees +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceHFGraph +OAI.MeasureTheory.Falconer.Graphs.ActualProductChildEnergy +OAI.MeasureTheory.Falconer.Graphs.ActualProductDegrees +OAI.MeasureTheory.Falconer.Graphs.ActualProductEnergyFinite +OAI.MeasureTheory.Falconer.Graphs.ActualProductGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.AllDimensionalGraphGeometry +OAI.MeasureTheory.Falconer.Graphs.BipartitePivot +OAI.MeasureTheory.Falconer.Graphs.CommonRowNormalization +OAI.MeasureTheory.Falconer.Graphs.CoordinateGraph +OAI.MeasureTheory.Falconer.Graphs.CoordinateGraphObstruction +OAI.MeasureTheory.Falconer.Graphs.DenseGraphComparableParameters +OAI.MeasureTheory.Falconer.Graphs.DenseGraphParameters +OAI.MeasureTheory.Falconer.Graphs.DenseUnbalancedGraph +OAI.MeasureTheory.Falconer.Graphs.DescriptorGraph +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphCross +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphIntegral +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphPointwise +OAI.MeasureTheory.Falconer.Graphs.DistancePairDegree +OAI.MeasureTheory.Falconer.Graphs.DistanceSupportedGraph +OAI.MeasureTheory.Falconer.Graphs.DyadicGraph +OAI.MeasureTheory.Falconer.Graphs.DyadicRowCount +OAI.MeasureTheory.Falconer.Graphs.EligibleDistanceGraphSum +OAI.MeasureTheory.Falconer.Graphs.EligibleDyadicGraph +OAI.MeasureTheory.Falconer.Graphs.EligibleProductGraphSum +OAI.MeasureTheory.Falconer.Graphs.Energy +OAI.MeasureTheory.Falconer.Graphs.FiberEnergy +OAI.MeasureTheory.Falconer.Graphs.FiberPairing +OAI.MeasureTheory.Falconer.Graphs.FiberSlice +OAI.MeasureTheory.Falconer.Graphs.FiberTrace +OAI.MeasureTheory.Falconer.Graphs.FinsetSchur +OAI.MeasureTheory.Falconer.Graphs.FlexibleGraphChild +OAI.MeasureTheory.Falconer.Graphs.GraphActualMixedDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphActualNonedgeGeometry +OAI.MeasureTheory.Falconer.Graphs.GraphActualNonedgeSum +OAI.MeasureTheory.Falconer.Graphs.GraphActualQuadCells +OAI.MeasureTheory.Falconer.Graphs.GraphActualTransport +OAI.MeasureTheory.Falconer.Graphs.GraphAlgebraicDirections +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeRepresentative +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeScale +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeSupport +OAI.MeasureTheory.Falconer.Graphs.GraphBallCover +OAI.MeasureTheory.Falconer.Graphs.GraphBinDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphCartesianSubstitution +OAI.MeasureTheory.Falconer.Graphs.GraphChartIntegral +OAI.MeasureTheory.Falconer.Graphs.GraphChartRegularity +OAI.MeasureTheory.Falconer.Graphs.GraphChartVariation +OAI.MeasureTheory.Falconer.Graphs.GraphCompleteWeightSupport +OAI.MeasureTheory.Falconer.Graphs.GraphConeCutoff +OAI.MeasureTheory.Falconer.Graphs.GraphCoordinateInverse +OAI.MeasureTheory.Falconer.Graphs.GraphDegrees +OAI.MeasureTheory.Falconer.Graphs.GraphDensity +OAI.MeasureTheory.Falconer.Graphs.GraphDerivativeBounds +OAI.MeasureTheory.Falconer.Graphs.GraphDirectionStability +OAI.MeasureTheory.Falconer.Graphs.GraphEndpointContinuity +OAI.MeasureTheory.Falconer.Graphs.GraphEnergyError +OAI.MeasureTheory.Falconer.Graphs.GraphEnergyEstimate +OAI.MeasureTheory.Falconer.Graphs.GraphEtaIntegratedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphEtaNonstationary +OAI.MeasureTheory.Falconer.Graphs.GraphFiberPacking +OAI.MeasureTheory.Falconer.Graphs.GraphFixedCutoffs +OAI.MeasureTheory.Falconer.Graphs.GraphFourMassBound +OAI.MeasureTheory.Falconer.Graphs.GraphFourTransformExpansion +OAI.MeasureTheory.Falconer.Graphs.GraphFourTransformPointIntegral +OAI.MeasureTheory.Falconer.Graphs.GraphGeometry +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalBump +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalChart +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalDomain +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalPhase +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalSupports +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedNonedgePower +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedTransformChart +OAI.MeasureTheory.Falconer.Graphs.GraphLiftInverse +OAI.MeasureTheory.Falconer.Graphs.GraphLiftJacobian +OAI.MeasureTheory.Falconer.Graphs.GraphMixedComposition +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeAmplitude +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeErrorScale +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeFiniteSum +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeGradient +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeIndexCount +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeIntegralErrors +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgePerturbation +OAI.MeasureTheory.Falconer.Graphs.GraphNormalization +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalFubini +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalGraphRemoval +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalNonedgePower +OAI.MeasureTheory.Falconer.Graphs.GraphParentDiameter +OAI.MeasureTheory.Falconer.Graphs.GraphPointIntegralChart +OAI.MeasureTheory.Falconer.Graphs.GraphPolarAnnulus +OAI.MeasureTheory.Falconer.Graphs.GraphPolarJacobian +OAI.MeasureTheory.Falconer.Graphs.GraphPolicyScales +OAI.MeasureTheory.Falconer.Graphs.GraphProductMeasure +OAI.MeasureTheory.Falconer.Graphs.GraphProfileCoefficient +OAI.MeasureTheory.Falconer.Graphs.GraphRetainedEdges +OAI.MeasureTheory.Falconer.Graphs.GraphScalarRegularity +OAI.MeasureTheory.Falconer.Graphs.GraphScaleData +OAI.MeasureTheory.Falconer.Graphs.GraphScaleDirection +OAI.MeasureTheory.Falconer.Graphs.GraphSchur +OAI.MeasureTheory.Falconer.Graphs.GraphSignChart +OAI.MeasureTheory.Falconer.Graphs.GraphSignPartition +OAI.MeasureTheory.Falconer.Graphs.GraphSignSupports +OAI.MeasureTheory.Falconer.Graphs.GraphSliceDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphSpatialFubini +OAI.MeasureTheory.Falconer.Graphs.GraphTestScales +OAI.MeasureTheory.Falconer.Graphs.GraphTorusArcLength +OAI.MeasureTheory.Falconer.Graphs.GraphTransformChart +OAI.MeasureTheory.Falconer.Graphs.GraphTransportIntegrability +OAI.MeasureTheory.Falconer.Graphs.GraphTwoErrors +OAI.MeasureTheory.Falconer.Graphs.GraphWeightDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphZIntegratedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphZNonedgeScale +OAI.MeasureTheory.Falconer.Graphs.GraphZNonstationary +OAI.MeasureTheory.Falconer.Graphs.JetStateGraph +OAI.MeasureTheory.Falconer.Graphs.LocalDistanceCollision +OAI.MeasureTheory.Falconer.Graphs.NearGraph +OAI.MeasureTheory.Falconer.Graphs.OuterGraphData +OAI.MeasureTheory.Falconer.Graphs.OuterGraphStep +OAI.MeasureTheory.Falconer.Graphs.OuterRootGraphBound +OAI.MeasureTheory.Falconer.Graphs.PairCollisionTonelli +OAI.MeasureTheory.Falconer.Graphs.ParentAbsoluteGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ParentGraphEnergy +OAI.MeasureTheory.Falconer.Graphs.ParentGraphIndices +OAI.MeasureTheory.Falconer.Graphs.ParentRetainedEnergy +OAI.MeasureTheory.Falconer.Graphs.PlanarGraphBudgetApplication +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphAt +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphAtRecurrence +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphAtStep +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphData +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphError +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphGeometry +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphRecurrence +OAI.MeasureTheory.Falconer.Graphs.PolicyGraphStep +OAI.MeasureTheory.Falconer.Graphs.PrefixGraphSpecialization +OAI.MeasureTheory.Falconer.Graphs.PrefixSuccessorEnergy +OAI.MeasureTheory.Falconer.Graphs.ProductAbsoluteGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ProductEnergyMaximum +OAI.MeasureTheory.Falconer.Graphs.ProductEnergyTransfer +OAI.MeasureTheory.Falconer.Graphs.ProductGraphEnergy +OAI.MeasureTheory.Falconer.Graphs.ProductGraphIndices +OAI.MeasureTheory.Falconer.Graphs.ProductGraphIntegral +OAI.MeasureTheory.Falconer.Graphs.ProductGraphPointwise +OAI.MeasureTheory.Falconer.Graphs.ProductPairDegree +OAI.MeasureTheory.Falconer.Graphs.ProfileGraph +OAI.MeasureTheory.Falconer.Graphs.ProfileGraphBudget +OAI.MeasureTheory.Falconer.Graphs.ProfileGraphDegree +OAI.MeasureTheory.Falconer.Graphs.ProfileGraphError +OAI.MeasureTheory.Falconer.Graphs.ProfileGraphEstimate +OAI.MeasureTheory.Falconer.Graphs.RecursiveEnergyFamily +OAI.MeasureTheory.Falconer.Graphs.RegularGraphCosts +OAI.MeasureTheory.Falconer.Graphs.RegularGraphObstruction +OAI.MeasureTheory.Falconer.Graphs.RegularGraphRadiusCosts +OAI.MeasureTheory.Falconer.Graphs.RegularUnbalancedGraph +OAI.MeasureTheory.Falconer.Graphs.RootParentEnergy +OAI.MeasureTheory.Falconer.Graphs.RoundedGraphCounts +OAI.MeasureTheory.Falconer.Graphs.RoundedGraphData +OAI.MeasureTheory.Falconer.Graphs.RoundedProjectionGraph +OAI.MeasureTheory.Falconer.Graphs.ScalarGraphCoding +OAI.MeasureTheory.Falconer.Graphs.SmoothFiberEstimate +OAI.MeasureTheory.Falconer.Graphs.SourceSpatialEnergy +OAI.MeasureTheory.Falconer.Graphs.TwoGraphChildren +OAI.MeasureTheory.Falconer.Graphs.TwoGraphScales +OAI.MeasureTheory.Falconer.Graphs.TwoProfileGraph +OAI.MeasureTheory.Falconer.Graphs.UniformDistancePairDegree +OAI.MeasureTheory.Falconer.Graphs.WeakGraphObstruction +OAI.MeasureTheory.Falconer.Graphs.WeakUnbalancedGraph +OAI.MeasureTheory.Falconer.Graphs.WeightedDistanceCoincidence +OAI.MeasureTheory.Falconer.Graphs.WitnessGraph +OAI.MeasureTheory.Falconer.Incidence.AngularTubeCount +OAI.MeasureTheory.Falconer.Incidence.BadRowIncidence +OAI.MeasureTheory.Falconer.Incidence.BlockCellGoodGain +OAI.MeasureTheory.Falconer.Incidence.BlockCellNormalGain +OAI.MeasureTheory.Falconer.Incidence.BlockCellNormalPower +OAI.MeasureTheory.Falconer.Incidence.BlockCellPower +OAI.MeasureTheory.Falconer.Incidence.BlockDepthBracket +OAI.MeasureTheory.Falconer.Incidence.BlockDescendantCounts +OAI.MeasureTheory.Falconer.Incidence.BlockGrid +OAI.MeasureTheory.Falconer.Incidence.BlockIntervalLengths +OAI.MeasureTheory.Falconer.Incidence.BlockLeafCounts +OAI.MeasureTheory.Falconer.Incidence.BlockPrefixBallBound +OAI.MeasureTheory.Falconer.Incidence.BlockPrefixRetention +OAI.MeasureTheory.Falconer.Incidence.BlockProfileBallBound +OAI.MeasureTheory.Falconer.Incidence.BlockProfileCells +OAI.MeasureTheory.Falconer.Incidence.BlockRegularization +OAI.MeasureTheory.Falconer.Incidence.BoundedFrozenHeavyCover +OAI.MeasureTheory.Falconer.Incidence.CenteredPacketPencils +OAI.MeasureTheory.Falconer.Incidence.CenteredPlanarIncidence +OAI.MeasureTheory.Falconer.Incidence.CoarseCellPencils +OAI.MeasureTheory.Falconer.Incidence.CoarsePacketGain +OAI.MeasureTheory.Falconer.Incidence.CoarsePacketParameters +OAI.MeasureTheory.Falconer.Incidence.CoarsePacketPoints +OAI.MeasureTheory.Falconer.Incidence.CoarsePencilSize +OAI.MeasureTheory.Falconer.Incidence.CoarsePencilWeights +OAI.MeasureTheory.Falconer.Incidence.CoarseSquashedPencils +OAI.MeasureTheory.Falconer.Incidence.CoarserPencilDirections +OAI.MeasureTheory.Falconer.Incidence.CommonTripleIncidence +OAI.MeasureTheory.Falconer.Incidence.CommonTubeCount +OAI.MeasureTheory.Falconer.Incidence.CommonTupleIncidence +OAI.MeasureTheory.Falconer.Incidence.ComparableFrozenPencils +OAI.MeasureTheory.Falconer.Incidence.CriticalPencilIncidence +OAI.MeasureTheory.Falconer.Incidence.CubicIncidence +OAI.MeasureTheory.Falconer.Incidence.FiniteBallBounds +OAI.MeasureTheory.Falconer.Incidence.FiniteBallPruning +OAI.MeasureTheory.Falconer.Incidence.FiniteLatticeLoomis +OAI.MeasureTheory.Falconer.Incidence.FiniteLoomisWhitney +OAI.MeasureTheory.Falconer.Incidence.FrozenCoarseConfiguration +OAI.MeasureTheory.Falconer.Incidence.FrozenCoarseObstruction +OAI.MeasureTheory.Falconer.Incidence.FrozenHeavyCover +OAI.MeasureTheory.Falconer.Incidence.FrozenPacketProduct +OAI.MeasureTheory.Falconer.Incidence.FrozenPacketRegularity +OAI.MeasureTheory.Falconer.Incidence.FrozenPacketSelection +OAI.MeasureTheory.Falconer.Incidence.FrozenPacketUpper +OAI.MeasureTheory.Falconer.Incidence.GoodPencilDirections +OAI.MeasureTheory.Falconer.Incidence.GridCount +OAI.MeasureTheory.Falconer.Incidence.IncidenceBucketBudget +OAI.MeasureTheory.Falconer.Incidence.IncidenceMoment +OAI.MeasureTheory.Falconer.Incidence.IncidencePowerBudget +OAI.MeasureTheory.Falconer.Incidence.IncidenceProductChain +OAI.MeasureTheory.Falconer.Incidence.IncidenceSamples +OAI.MeasureTheory.Falconer.Incidence.IncidenceSampling +OAI.MeasureTheory.Falconer.Incidence.IncidenceScaleChoice +OAI.MeasureTheory.Falconer.Incidence.IncidentCoarsePencils +OAI.MeasureTheory.Falconer.Incidence.InterpolatedIncidence +OAI.MeasureTheory.Falconer.Incidence.InterpolatedPencilGain +OAI.MeasureTheory.Falconer.Incidence.LeafCenterIncidence +OAI.MeasureTheory.Falconer.Incidence.LeafIncidenceGain +OAI.MeasureTheory.Falconer.Incidence.LeafMassBins +OAI.MeasureTheory.Falconer.Incidence.LeafPencilTransport +OAI.MeasureTheory.Falconer.Incidence.LeafPrefixPower +OAI.MeasureTheory.Falconer.Incidence.LocalCellIncidence +OAI.MeasureTheory.Falconer.Incidence.LocalPencilPacketGain +OAI.MeasureTheory.Falconer.Incidence.LoomisWhitneyCoordinates +OAI.MeasureTheory.Falconer.Incidence.LoomisWhitneyThree +OAI.MeasureTheory.Falconer.Incidence.NormalProfileIncidence +OAI.MeasureTheory.Falconer.Incidence.NormalizedProductPencils +OAI.MeasureTheory.Falconer.Incidence.OriginalBlockIncidence +OAI.MeasureTheory.Falconer.Incidence.OriginalCoarsePackets +OAI.MeasureTheory.Falconer.Incidence.OriginalPencilEqualization +OAI.MeasureTheory.Falconer.Incidence.PacketRowPencils +OAI.MeasureTheory.Falconer.Incidence.ParentQuarterIncidence +OAI.MeasureTheory.Falconer.Incidence.PencilDirections +OAI.MeasureTheory.Falconer.Incidence.PencilEnergyPruning +OAI.MeasureTheory.Falconer.Incidence.PencilFiberEnergy +OAI.MeasureTheory.Falconer.Incidence.PencilGainAlgebra +OAI.MeasureTheory.Falconer.Incidence.PencilSecondMoment +OAI.MeasureTheory.Falconer.Incidence.PlanarBaselineIncidence +OAI.MeasureTheory.Falconer.Incidence.PlanarIncidence +OAI.MeasureTheory.Falconer.Incidence.PlanarLeafInjection +OAI.MeasureTheory.Falconer.Incidence.PowerIncidenceMass +OAI.MeasureTheory.Falconer.Incidence.ProfileBlockBudget +OAI.MeasureTheory.Falconer.Incidence.PublishedFurstenberg +OAI.MeasureTheory.Falconer.Incidence.PublishedLoomisWhitney +OAI.MeasureTheory.Falconer.Incidence.QuarterPencilGeometry +OAI.MeasureTheory.Falconer.Incidence.QuarterPencils +OAI.MeasureTheory.Falconer.Incidence.RadialBlockDepths +OAI.MeasureTheory.Falconer.Incidence.RadialBlockRadius +OAI.MeasureTheory.Falconer.Incidence.RadialIncidenceBound +OAI.MeasureTheory.Falconer.Incidence.RadialZoomFiniteBalls +OAI.MeasureTheory.Falconer.Incidence.RegularClassRadialIncidence +OAI.MeasureTheory.Falconer.Incidence.RegularCoarsePencils +OAI.MeasureTheory.Falconer.Incidence.RegularEnergyPencils +OAI.MeasureTheory.Falconer.Incidence.RegularProductIncidence +OAI.MeasureTheory.Falconer.Incidence.RelativeBlockBallBound +OAI.MeasureTheory.Falconer.Incidence.RetainedCoarseIncidences +OAI.MeasureTheory.Falconer.Incidence.RoundedBlockIntervals +OAI.MeasureTheory.Falconer.Incidence.RoundedRowPencils +OAI.MeasureTheory.Falconer.Incidence.SampledFurstenberg +OAI.MeasureTheory.Falconer.Incidence.ScalarBlockPruning +OAI.MeasureTheory.Falconer.Incidence.ScalarWeakBlockProjection +OAI.MeasureTheory.Falconer.Incidence.SquashedPencils +OAI.MeasureTheory.Falconer.Incidence.TransverseTubeCount +OAI.MeasureTheory.Falconer.Incidence.TroublesomeIncidence +OAI.MeasureTheory.Falconer.Incidence.TruncatedBlockBall +OAI.MeasureTheory.Falconer.Incidence.TruncatedBlockCover +OAI.MeasureTheory.Falconer.Incidence.TruncatedBlockRatio +OAI.MeasureTheory.Falconer.Incidence.UniformFrozenCells +OAI.MeasureTheory.Falconer.Incidence.UniformSmallCoverPencils +OAI.MeasureTheory.Falconer.Incidence.UpperBlockBracket +OAI.MeasureTheory.Falconer.Incidence.VariableBaselineIncidence +OAI.MeasureTheory.Falconer.Incidence.WeakCoarsePacketGain +OAI.MeasureTheory.Falconer.Incidence.WeightedLoomisBase +OAI.MeasureTheory.Falconer.Incidence.WeightedLoomisStep +OAI.MeasureTheory.Falconer.Incidence.WideProductIncidence +OAI.MeasureTheory.Falconer.Measures.AmbientMaskProductBudget +OAI.MeasureTheory.Falconer.Measures.AmbientProduct +OAI.MeasureTheory.Falconer.Measures.BorelProductPartition +OAI.MeasureTheory.Falconer.Measures.BoundedDualDensity +OAI.MeasureTheory.Falconer.Measures.BudgetedEndpointProduct +OAI.MeasureTheory.Falconer.Measures.CellRefinementMass +OAI.MeasureTheory.Falconer.Measures.CellwiseCollisionPruning +OAI.MeasureTheory.Falconer.Measures.ChartDensityEstimate +OAI.MeasureTheory.Falconer.Measures.ChooseProjectedFrostman +OAI.MeasureTheory.Falconer.Measures.ClassSupport +OAI.MeasureTheory.Falconer.Measures.CollisionDensityCharge +OAI.MeasureTheory.Falconer.Measures.CollisionPruningMultiplication +OAI.MeasureTheory.Falconer.Measures.ComparableIntegralPartition +OAI.MeasureTheory.Falconer.Measures.ComparableNormalization +OAI.MeasureTheory.Falconer.Measures.ConditionalFrostman +OAI.MeasureTheory.Falconer.Measures.CubeMass +OAI.MeasureTheory.Falconer.Measures.CubeProbability +OAI.MeasureTheory.Falconer.Measures.DenseNeighborPruning +OAI.MeasureTheory.Falconer.Measures.DensityCellCharge +OAI.MeasureTheory.Falconer.Measures.DensityTruncation +OAI.MeasureTheory.Falconer.Measures.DescriptorProduct +OAI.MeasureTheory.Falconer.Measures.DistanceMatrixSchur +OAI.MeasureTheory.Falconer.Measures.DistanceMeasure +OAI.MeasureTheory.Falconer.Measures.DistanceSchurIntegral +OAI.MeasureTheory.Falconer.Measures.DistributionAbsoluteContinuity +OAI.MeasureTheory.Falconer.Measures.DyadicIntegralSplitting +OAI.MeasureTheory.Falconer.Measures.DyadicMeasure +OAI.MeasureTheory.Falconer.Measures.DyadicMeasureSplitting +OAI.MeasureTheory.Falconer.Measures.EndpointMassRatios +OAI.MeasureTheory.Falconer.Measures.EndpointScaleProduct +OAI.MeasureTheory.Falconer.Measures.ExceptionalFiberMass +OAI.MeasureTheory.Falconer.Measures.ExtendedDensityNorm +OAI.MeasureTheory.Falconer.Measures.FarOriginalSupport +OAI.MeasureTheory.Falconer.Measures.FiberDensityPruning +OAI.MeasureTheory.Falconer.Measures.FiniteLpIntegral +OAI.MeasureTheory.Falconer.Measures.FiniteMassMultiplication +OAI.MeasureTheory.Falconer.Measures.FiniteMeasureProducts +OAI.MeasureTheory.Falconer.Measures.FiniteProductIntegral +OAI.MeasureTheory.Falconer.Measures.FiniteRelativePruning +OAI.MeasureTheory.Falconer.Measures.FirstExclusionMass +OAI.MeasureTheory.Falconer.Measures.FourCellMeasureSplitting +OAI.MeasureTheory.Falconer.Measures.FourSpatialPairMeasure +OAI.MeasureTheory.Falconer.Measures.FrequencyMeasure +OAI.MeasureTheory.Falconer.Measures.FrostmanDimension +OAI.MeasureTheory.Falconer.Measures.FrostmanDischarge +OAI.MeasureTheory.Falconer.Measures.FrostmanWeakLimit +OAI.MeasureTheory.Falconer.Measures.InactiveBinIntegral +OAI.MeasureTheory.Falconer.Measures.InverseSupport +OAI.MeasureTheory.Falconer.Measures.LiftedProductPartition +OAI.MeasureTheory.Falconer.Measures.LocalPruningGain +OAI.MeasureTheory.Falconer.Measures.MaskProductBudget +OAI.MeasureTheory.Falconer.Measures.MaskSupport +OAI.MeasureTheory.Falconer.Measures.MeanProbability +OAI.MeasureTheory.Falconer.Measures.MonotoneMeasureMass +OAI.MeasureTheory.Falconer.Measures.MultiscaleCollisionMass +OAI.MeasureTheory.Falconer.Measures.MultiscaleDensityPruning +OAI.MeasureTheory.Falconer.Measures.NormAffineRemainder +OAI.MeasureTheory.Falconer.Measures.NormalizedLeibnizAssignment +OAI.MeasureTheory.Falconer.Measures.NormalizedProjectedFrostman +OAI.MeasureTheory.Falconer.Measures.OriginalConditionalFrostman +OAI.MeasureTheory.Falconer.Measures.OriginalCoverRestriction +OAI.MeasureTheory.Falconer.Measures.PairCorePruning +OAI.MeasureTheory.Falconer.Measures.PartitionMaskedMeasure +OAI.MeasureTheory.Falconer.Measures.PopularSquareMass +OAI.MeasureTheory.Falconer.Measures.PrefixMass +OAI.MeasureTheory.Falconer.Measures.ProductCellPartition +OAI.MeasureTheory.Falconer.Measures.ProductMatrixSchur +OAI.MeasureTheory.Falconer.Measures.ProductPartitionMask +OAI.MeasureTheory.Falconer.Measures.ProductProjectionReduction +OAI.MeasureTheory.Falconer.Measures.ProductRestrictionLoss +OAI.MeasureTheory.Falconer.Measures.ProductSchurIntegral +OAI.MeasureTheory.Falconer.Measures.ProjectedSupportPoints +OAI.MeasureTheory.Falconer.Measures.RegularProductParameters +OAI.MeasureTheory.Falconer.Measures.RegularizedMass +OAI.MeasureTheory.Falconer.Measures.RepresentedPruning +OAI.MeasureTheory.Falconer.Measures.RescaledScaleProduct +OAI.MeasureTheory.Falconer.Measures.RootNormalizedCoefficients +OAI.MeasureTheory.Falconer.Measures.RootNormalizedError +OAI.MeasureTheory.Falconer.Measures.RootSimilarityMeasures +OAI.MeasureTheory.Falconer.Measures.ScalarBunchProducts +OAI.MeasureTheory.Falconer.Measures.ScalarBunchPruning +OAI.MeasureTheory.Falconer.Measures.ScalarDensityInverse +OAI.MeasureTheory.Falconer.Measures.ScalarDensityMassControl +OAI.MeasureTheory.Falconer.Measures.ScalarDensityRadius +OAI.MeasureTheory.Falconer.Measures.ScalarDensitySelection +OAI.MeasureTheory.Falconer.Measures.ScalarDensityZoom +OAI.MeasureTheory.Falconer.Measures.ScalarPrefixPruning +OAI.MeasureTheory.Falconer.Measures.ScalarProductBalls +OAI.MeasureTheory.Falconer.Measures.ScalarPruningPreservation +OAI.MeasureTheory.Falconer.Measures.ScalarSingleChildPruning +OAI.MeasureTheory.Falconer.Measures.ScalarSmallZoomMass +OAI.MeasureTheory.Falconer.Measures.ScalarSubsetMass +OAI.MeasureTheory.Falconer.Measures.ScalarTaggedPruning +OAI.MeasureTheory.Falconer.Measures.Schur +OAI.MeasureTheory.Falconer.Measures.SecondProjectedFrostman +OAI.MeasureTheory.Falconer.Measures.SeparatedSupport +OAI.MeasureTheory.Falconer.Measures.SimilarityMeasures +OAI.MeasureTheory.Falconer.Measures.SimultaneousProjectedFrostman +OAI.MeasureTheory.Falconer.Measures.SpatialRestriction +OAI.MeasureTheory.Falconer.Measures.StartingMeasures +OAI.MeasureTheory.Falconer.Measures.SupportPairFilter +OAI.MeasureTheory.Falconer.Measures.TestNormDensity +OAI.MeasureTheory.Falconer.Measures.TestNormMeasurable +OAI.MeasureTheory.Falconer.Measures.TestNormRepresentation +OAI.MeasureTheory.Falconer.Measures.TotalVariation +OAI.MeasureTheory.Falconer.Measures.WeakApproximation +OAI.MeasureTheory.Falconer.Measures.WeakLimit +OAI.MeasureTheory.Falconer.Measures.WeightedIntegralSquare +OAI.MeasureTheory.Falconer.Measures.WideProductParameters +OAI.MeasureTheory.Falconer.Measures.WideProductPower +OAI.MeasureTheory.Falconer.Model +OAI.MeasureTheory.Falconer.Radial.ActualFarRadialError +OAI.MeasureTheory.Falconer.Radial.ActualNoncomparableRadial +OAI.MeasureTheory.Falconer.Radial.ActualSingleRadialError +OAI.MeasureTheory.Falconer.Radial.ActualSuffixProjection +OAI.MeasureTheory.Falconer.Radial.AffineNullTuples +OAI.MeasureTheory.Falconer.Radial.AffinePlaneCover +OAI.MeasureTheory.Falconer.Radial.AffinePlaneFrostman +OAI.MeasureTheory.Falconer.Radial.AffineSlabCluster +OAI.MeasureTheory.Falconer.Radial.AffineSubspaceFrostman +OAI.MeasureTheory.Falconer.Radial.AllDimensionalMollifiedRadialBound +OAI.MeasureTheory.Falconer.Radial.AllDimensionalRadialTestBound +OAI.MeasureTheory.Falconer.Radial.AllDimensionalSmoothRadialEstimate +OAI.MeasureTheory.Falconer.Radial.BoundedHeavyPlateCover +OAI.MeasureTheory.Falconer.Radial.ClassicalAffineDistance +OAI.MeasureTheory.Falconer.Radial.ClasswiseRadialGain +OAI.MeasureTheory.Falconer.Radial.CoarsePlateAffineBound +OAI.MeasureTheory.Falconer.Radial.CoarsePlateCells +OAI.MeasureTheory.Falconer.Radial.CoarsePlateDirections +OAI.MeasureTheory.Falconer.Radial.CoarsePlateFilter +OAI.MeasureTheory.Falconer.Radial.CoarsePlateLimit +OAI.MeasureTheory.Falconer.Radial.CoarsePlatePositive +OAI.MeasureTheory.Falconer.Radial.CoarsePlatePreparation +OAI.MeasureTheory.Falconer.Radial.CoarsePlateSymmetry +OAI.MeasureTheory.Falconer.Radial.ConeRadialIntegral +OAI.MeasureTheory.Falconer.Radial.DyadicHeavyCover +OAI.MeasureTheory.Falconer.Radial.DyadicRadialPruning +OAI.MeasureTheory.Falconer.Radial.EndpointMiddleRadial +OAI.MeasureTheory.Falconer.Radial.EndpointRadialBadDirections +OAI.MeasureTheory.Falconer.Radial.EndpointRadialLosses +OAI.MeasureTheory.Falconer.Radial.EndpointRadialPreparation +OAI.MeasureTheory.Falconer.Radial.EndpointSourceMiddle +OAI.MeasureTheory.Falconer.Radial.EndpointTubeGain +OAI.MeasureTheory.Falconer.Radial.EuclideanRadialDensity +OAI.MeasureTheory.Falconer.Radial.FarRadialIntegral +OAI.MeasureTheory.Falconer.Radial.FarRadialKernel +OAI.MeasureTheory.Falconer.Radial.FinitePlateException +OAI.MeasureTheory.Falconer.Radial.FiniteRadialContinuity +OAI.MeasureTheory.Falconer.Radial.FiniteRadialPruning +OAI.MeasureTheory.Falconer.Radial.FiniteRadialRefinement +OAI.MeasureTheory.Falconer.Radial.FiniteRadialTestEnergy +OAI.MeasureTheory.Falconer.Radial.GeneralPhysicalTubeCover +OAI.MeasureTheory.Falconer.Radial.GeneralTubeMass +OAI.MeasureTheory.Falconer.Radial.GnomonicAffinePlate +OAI.MeasureTheory.Falconer.Radial.GraphRadialNormalization +OAI.MeasureTheory.Falconer.Radial.GraphTorusRadial +OAI.MeasureTheory.Falconer.Radial.HeavyCellRegularity +OAI.MeasureTheory.Falconer.Radial.HeavyCoverCount +OAI.MeasureTheory.Falconer.Radial.HeavyDischarge +OAI.MeasureTheory.Falconer.Radial.HeavyMaximal +OAI.MeasureTheory.Falconer.Radial.HeavyPacketCells +OAI.MeasureTheory.Falconer.Radial.HeavyPlateCells +OAI.MeasureTheory.Falconer.Radial.HeavyPlateCover +OAI.MeasureTheory.Falconer.Radial.HeavyProjectedCover +OAI.MeasureTheory.Falconer.Radial.HeavySelection +OAI.MeasureTheory.Falconer.Radial.HyperplaneEnergy +OAI.MeasureTheory.Falconer.Radial.HyperplaneFiber +OAI.MeasureTheory.Falconer.Radial.HyperplaneFourier +OAI.MeasureTheory.Falconer.Radial.HyperplaneFrame +OAI.MeasureTheory.Falconer.Radial.HyperplaneMixedEnergy +OAI.MeasureTheory.Falconer.Radial.HyperplaneTrace +OAI.MeasureTheory.Falconer.Radial.InitialPlateCover +OAI.MeasureTheory.Falconer.Radial.InitialPlateLoss +OAI.MeasureTheory.Falconer.Radial.LatePlateFiber +OAI.MeasureTheory.Falconer.Radial.LatePlatePowerLoss +OAI.MeasureTheory.Falconer.Radial.LatePlateTail +OAI.MeasureTheory.Falconer.Radial.LinearRadialDecay +OAI.MeasureTheory.Falconer.Radial.LocalRadialPruning +OAI.MeasureTheory.Falconer.Radial.MeasurableTubeCover +OAI.MeasureTheory.Falconer.Radial.MiddleHeavyRadialMass +OAI.MeasureTheory.Falconer.Radial.MiddleRadialPruning +OAI.MeasureTheory.Falconer.Radial.MiddleRadialTransport +OAI.MeasureTheory.Falconer.Radial.MollifiedRadialBound +OAI.MeasureTheory.Falconer.Radial.MultilevelRadialPruning +OAI.MeasureTheory.Falconer.Radial.NoncomparableRadialSymmetry +OAI.MeasureTheory.Falconer.Radial.NonendpointMiddleRadial +OAI.MeasureTheory.Falconer.Radial.NonendpointRadialBadDirections +OAI.MeasureTheory.Falconer.Radial.NonendpointSourceMiddle +OAI.MeasureTheory.Falconer.Radial.NonendpointTubeGain +OAI.MeasureTheory.Falconer.Radial.OccupiedRadialTree +OAI.MeasureTheory.Falconer.Radial.OriginalHeavyPlateCover +OAI.MeasureTheory.Falconer.Radial.OuterRadialCell +OAI.MeasureTheory.Falconer.Radial.OuterRadialPruning +OAI.MeasureTheory.Falconer.Radial.OuterRadialWidths +OAI.MeasureTheory.Falconer.Radial.PhysicalTubeCover +OAI.MeasureTheory.Falconer.Radial.PlanarAETubeGain +OAI.MeasureTheory.Falconer.Radial.PlanarRadialDischarge +OAI.MeasureTheory.Falconer.Radial.PlanarUnitTubeGain +OAI.MeasureTheory.Falconer.Radial.PlateLossSeries +OAI.MeasureTheory.Falconer.Radial.PlatePairLoss +OAI.MeasureTheory.Falconer.Radial.PlatePowerBudget +OAI.MeasureTheory.Falconer.Radial.PlateScaleChoices +OAI.MeasureTheory.Falconer.Radial.PlateScales +OAI.MeasureTheory.Falconer.Radial.PlateZoom +OAI.MeasureTheory.Falconer.Radial.PreparedTubeRelation +OAI.MeasureTheory.Falconer.Radial.ProfileProjectionCollision +OAI.MeasureTheory.Falconer.Radial.ProjectedDiameter +OAI.MeasureTheory.Falconer.Radial.ProjectedHyperplaneNull +OAI.MeasureTheory.Falconer.Radial.ProjectionCellPartition +OAI.MeasureTheory.Falconer.Radial.ProjectionCollisionCount +OAI.MeasureTheory.Falconer.Radial.ProjectionDensity +OAI.MeasureTheory.Falconer.Radial.ProjectionEnergy +OAI.MeasureTheory.Falconer.Radial.ProjectionExceptional +OAI.MeasureTheory.Falconer.Radial.ProjectionMoment +OAI.MeasureTheory.Falconer.Radial.ProjectionShiftedBand +OAI.MeasureTheory.Falconer.Radial.PublishedHeavyPlates +OAI.MeasureTheory.Falconer.Radial.PublishedRadialMoment +OAI.MeasureTheory.Falconer.Radial.RadialAllRadiusBound +OAI.MeasureTheory.Falconer.Radial.RadialAngleCaps +OAI.MeasureTheory.Falconer.Radial.RadialAnglePotential +OAI.MeasureTheory.Falconer.Radial.RadialAtomless +OAI.MeasureTheory.Falconer.Radial.RadialBadWitness +OAI.MeasureTheory.Falconer.Radial.RadialCapCollision +OAI.MeasureTheory.Falconer.Radial.RadialCapExtension +OAI.MeasureTheory.Falconer.Radial.RadialCapMass +OAI.MeasureTheory.Falconer.Radial.RadialCapTube +OAI.MeasureTheory.Falconer.Radial.RadialCollisionDeletion +OAI.MeasureTheory.Falconer.Radial.RadialCollisionMass +OAI.MeasureTheory.Falconer.Radial.RadialCollisionMean +OAI.MeasureTheory.Falconer.Radial.RadialCollisionWidths +OAI.MeasureTheory.Falconer.Radial.RadialContinuity +OAI.MeasureTheory.Falconer.Radial.RadialDensity +OAI.MeasureTheory.Falconer.Radial.RadialDischarge +OAI.MeasureTheory.Falconer.Radial.RadialDistanceError +OAI.MeasureTheory.Falconer.Radial.RadialDyadicBracket +OAI.MeasureTheory.Falconer.Radial.RadialFailureMass +OAI.MeasureTheory.Falconer.Radial.RadialFatou +OAI.MeasureTheory.Falconer.Radial.RadialFreezing +OAI.MeasureTheory.Falconer.Radial.RadialFreezingScales +OAI.MeasureTheory.Falconer.Radial.RadialIntervalEnergy +OAI.MeasureTheory.Falconer.Radial.RadialLocalization +OAI.MeasureTheory.Falconer.Radial.RadialLpEnergy +OAI.MeasureTheory.Falconer.Radial.RadialMeanPowerBound +OAI.MeasureTheory.Falconer.Radial.RadialMeanPowers +OAI.MeasureTheory.Falconer.Radial.RadialMixedEnergy +OAI.MeasureTheory.Falconer.Radial.RadialMomentParameters +OAI.MeasureTheory.Falconer.Radial.RadialMoments +OAI.MeasureTheory.Falconer.Radial.RadialNearBallBounds +OAI.MeasureTheory.Falconer.Radial.RadialNonstationary +OAI.MeasureTheory.Falconer.Radial.RadialPairSeparation +OAI.MeasureTheory.Falconer.Radial.RadialPairSwap +OAI.MeasureTheory.Falconer.Radial.RadialPinScaleBounds +OAI.MeasureTheory.Falconer.Radial.RadialPreparation +OAI.MeasureTheory.Falconer.Radial.RadialProfileGap +OAI.MeasureTheory.Falconer.Radial.RadialProfileProduct +OAI.MeasureTheory.Falconer.Radial.RadialRegularClasses +OAI.MeasureTheory.Falconer.Radial.RadialRemoveDiagonal +OAI.MeasureTheory.Falconer.Radial.RadialScaleIntersection +OAI.MeasureTheory.Falconer.Radial.RadialScaleWindow +OAI.MeasureTheory.Falconer.Radial.RadialShellMeasure +OAI.MeasureTheory.Falconer.Radial.RadialSphereBounds +OAI.MeasureTheory.Falconer.Radial.RadialSphereLaw +OAI.MeasureTheory.Falconer.Radial.RadialTaylor +OAI.MeasureTheory.Falconer.Radial.RadialTestBound +OAI.MeasureTheory.Falconer.Radial.RadialTestEnergy +OAI.MeasureTheory.Falconer.Radial.RadialTestFatou +OAI.MeasureTheory.Falconer.Radial.RadialTestMoment +OAI.MeasureTheory.Falconer.Radial.RadialTestNorm +OAI.MeasureTheory.Falconer.Radial.RadialTonelli +OAI.MeasureTheory.Falconer.Radial.RadialTupleTransversality +OAI.MeasureTheory.Falconer.Radial.RadialWindowAvailability +OAI.MeasureTheory.Falconer.Radial.RadialZoom +OAI.MeasureTheory.Falconer.Radial.RadialZoomBounds +OAI.MeasureTheory.Falconer.Radial.RadialZoomLaw +OAI.MeasureTheory.Falconer.Radial.RadialZoomPruning +OAI.MeasureTheory.Falconer.Radial.RadonLpDensity +OAI.MeasureTheory.Falconer.Radial.RegularClassRadialBudget +OAI.MeasureTheory.Falconer.Radial.RegularizationRadialGain +OAI.MeasureTheory.Falconer.Radial.RelativeClasswiseRadialGain +OAI.MeasureTheory.Falconer.Radial.ReverseRadialGeometry +OAI.MeasureTheory.Falconer.Radial.ReverseRadialMass +OAI.MeasureTheory.Falconer.Radial.ReverseRadialTruncation +OAI.MeasureTheory.Falconer.Radial.ReverseSlabsAllRadii +OAI.MeasureTheory.Falconer.Radial.ScalarAffineCovers +OAI.MeasureTheory.Falconer.Radial.ScalarAffineExceptions +OAI.MeasureTheory.Falconer.Radial.ScalarAffineFibers +OAI.MeasureTheory.Falconer.Radial.SignedRadialKernel +OAI.MeasureTheory.Falconer.Radial.SingleClassRadialGain +OAI.MeasureTheory.Falconer.Radial.SingleScaleWeakRadial +OAI.MeasureTheory.Falconer.Radial.SingleSphereRadial +OAI.MeasureTheory.Falconer.Radial.SingleStationaryRadial +OAI.MeasureTheory.Falconer.Radial.SmallChartWeakRadial +OAI.MeasureTheory.Falconer.Radial.SmoothRadialEstimate +OAI.MeasureTheory.Falconer.Radial.SourceClassOuterRadial +OAI.MeasureTheory.Falconer.Radial.SourceRadialSetup +OAI.MeasureTheory.Falconer.Radial.SphereSlab +OAI.MeasureTheory.Falconer.Radial.StationaryRadialSum +OAI.MeasureTheory.Falconer.Radial.SuffixProjectionWidths +OAI.MeasureTheory.Falconer.Radial.ThinTubeUpgrade +OAI.MeasureTheory.Falconer.Radial.ThreeTubeMass +OAI.MeasureTheory.Falconer.Radial.TubeCoverChoice +OAI.MeasureTheory.Falconer.Radial.TubeCoverEnumeration +OAI.MeasureTheory.Falconer.Radial.TwoSidedRadialIntersection +OAI.MeasureTheory.Falconer.Radial.TwoSlabGeometry +OAI.MeasureTheory.Falconer.Radial.TwoSlabMass +OAI.MeasureTheory.Falconer.Radial.TwoSlabSingleScale +OAI.MeasureTheory.Falconer.Radial.UniformAffineSlabs +OAI.MeasureTheory.Falconer.Radial.UniformOuterRadial +OAI.MeasureTheory.Falconer.Radial.UniformProjectionCollision +OAI.MeasureTheory.Falconer.Radial.UniformRadialRestrictions +OAI.MeasureTheory.Falconer.Radial.UniformVanishingSlabs +OAI.MeasureTheory.Falconer.Radial.UnitHeavyPlateCover +OAI.MeasureTheory.Falconer.Radial.VanishingSlabs +OAI.MeasureTheory.Falconer.Radial.WeakRadial +OAI.MeasureTheory.Falconer.Radial.WeakRadialCapParameters +OAI.MeasureTheory.Falconer.Radial.WeakRadialDeletionBudget +OAI.MeasureTheory.Falconer.Radial.WeakRadialLocalBudget +OAI.MeasureTheory.Falconer.Radial.WeakRadialLosses +OAI.MeasureTheory.Falconer.Radial.WeakRadialParameters +OAI.MeasureTheory.Falconer.Radial.WeakRadialTotalCost +OAI.MeasureTheory.Falconer.Recursion.ActualDistanceRecursionBound +OAI.MeasureTheory.Falconer.Recursion.ActualPolicyPayments +OAI.MeasureTheory.Falconer.Recursion.ActualRecursiveProfile +OAI.MeasureTheory.Falconer.Recursion.ActualSuffixLocalBins +OAI.MeasureTheory.Falconer.Recursion.ActualSuffixReduction +OAI.MeasureTheory.Falconer.Recursion.AnchoredTriplePotential +OAI.MeasureTheory.Falconer.Recursion.BlockLeafCounts +OAI.MeasureTheory.Falconer.Recursion.BlockRegularization +OAI.MeasureTheory.Falconer.Recursion.BoundedPotentialCompact +OAI.MeasureTheory.Falconer.Recursion.BranchAnalyticSuccessors +OAI.MeasureTheory.Falconer.Recursion.BranchCounts +OAI.MeasureTheory.Falconer.Recursion.BranchErrorBounds +OAI.MeasureTheory.Falconer.Recursion.BranchExponent +OAI.MeasureTheory.Falconer.Recursion.BranchExponentAlgebra +OAI.MeasureTheory.Falconer.Recursion.BranchPotential +OAI.MeasureTheory.Falconer.Recursion.BranchRecursionOrder +OAI.MeasureTheory.Falconer.Recursion.BranchRepresentativeCharges +OAI.MeasureTheory.Falconer.Recursion.BranchTransitions +OAI.MeasureTheory.Falconer.Recursion.BranchValidity +OAI.MeasureTheory.Falconer.Recursion.ContactLossBudget +OAI.MeasureTheory.Falconer.Recursion.CriticalPotential +OAI.MeasureTheory.Falconer.Recursion.CriticalScalarPotential +OAI.MeasureTheory.Falconer.Recursion.CriticalTruncatedPotential +OAI.MeasureTheory.Falconer.Recursion.DescriptorGoodTransfer +OAI.MeasureTheory.Falconer.Recursion.DescriptorMaskFailure +OAI.MeasureTheory.Falconer.Recursion.DescriptorMaskSymmetry +OAI.MeasureTheory.Falconer.Recursion.DescriptorMasks +OAI.MeasureTheory.Falconer.Recursion.DimensionalBranchBounds +OAI.MeasureTheory.Falconer.Recursion.DirectPolicyWitness +OAI.MeasureTheory.Falconer.Recursion.DisplacementDepth +OAI.MeasureTheory.Falconer.Recursion.DyadicWindowInterpolation +OAI.MeasureTheory.Falconer.Recursion.EndpointContactGain +OAI.MeasureTheory.Falconer.Recursion.EndpointScaleWindow +OAI.MeasureTheory.Falconer.Recursion.Entry +OAI.MeasureTheory.Falconer.Recursion.FarProfileNormalization +OAI.MeasureTheory.Falconer.Recursion.FiniteCountingPotential +OAI.MeasureTheory.Falconer.Recursion.FiniteCriticalPotential +OAI.MeasureTheory.Falconer.Recursion.FiniteProjectionPotential +OAI.MeasureTheory.Falconer.Recursion.FrequencyIntervals +OAI.MeasureTheory.Falconer.Recursion.FrostmanProfiles +OAI.MeasureTheory.Falconer.Recursion.InheritedEligibleWitness +OAI.MeasureTheory.Falconer.Recursion.InheritedPolicyState +OAI.MeasureTheory.Falconer.Recursion.InitialProfileClass +OAI.MeasureTheory.Falconer.Recursion.InnerProfileGrid +OAI.MeasureTheory.Falconer.Recursion.InteriorPolicy +OAI.MeasureTheory.Falconer.Recursion.IntermediateProfiles +OAI.MeasureTheory.Falconer.Recursion.LeafMassBins +OAI.MeasureTheory.Falconer.Recursion.Ledger +OAI.MeasureTheory.Falconer.Recursion.LocalProfileCounts +OAI.MeasureTheory.Falconer.Recursion.LocalProfileRegularity +OAI.MeasureTheory.Falconer.Recursion.MinimalDescriptorLength +OAI.MeasureTheory.Falconer.Recursion.NonendpointContactGain +OAI.MeasureTheory.Falconer.Recursion.NonendpointScaleWindow +OAI.MeasureTheory.Falconer.Recursion.OrderedEndpointIntervals +OAI.MeasureTheory.Falconer.Recursion.OrderedProfileIntervals +OAI.MeasureTheory.Falconer.Recursion.OrderedProfilePower +OAI.MeasureTheory.Falconer.Recursion.OuterEntryGain +OAI.MeasureTheory.Falconer.Recursion.OuterRecursiveTransport +OAI.MeasureTheory.Falconer.Recursion.ParallelProfile +OAI.MeasureTheory.Falconer.Recursion.ParentBinFamily +OAI.MeasureTheory.Falconer.Recursion.ParentBinSelection +OAI.MeasureTheory.Falconer.Recursion.ParentCellGeometry +OAI.MeasureTheory.Falconer.Recursion.ParentConeGeometry +OAI.MeasureTheory.Falconer.Recursion.ParentConeSource +OAI.MeasureTheory.Falconer.Recursion.ParentDiscardedForm +OAI.MeasureTheory.Falconer.Recursion.ParentHFBridge +OAI.MeasureTheory.Falconer.Recursion.ParentInactiveRemoval +OAI.MeasureTheory.Falconer.Recursion.ParentProfileBounds +OAI.MeasureTheory.Falconer.Recursion.PlanarCriticalPotential +OAI.MeasureTheory.Falconer.Recursion.PlanarWeakDepth +OAI.MeasureTheory.Falconer.Recursion.PointRieszPotential +OAI.MeasureTheory.Falconer.Recursion.PolicyBranchCoefficients +OAI.MeasureTheory.Falconer.Recursion.PolicyDescriptors +OAI.MeasureTheory.Falconer.Recursion.PolicyFarSuccessors +OAI.MeasureTheory.Falconer.Recursion.PolicyInteriorInterval +OAI.MeasureTheory.Falconer.Recursion.PolicyRecursionBounds +OAI.MeasureTheory.Falconer.Recursion.PolicyTerminal +OAI.MeasureTheory.Falconer.Recursion.PolicyWeightedRecursion +OAI.MeasureTheory.Falconer.Recursion.Potential +OAI.MeasureTheory.Falconer.Recursion.PotentialBallBound +OAI.MeasureTheory.Falconer.Recursion.PotentialFrostman +OAI.MeasureTheory.Falconer.Recursion.PotentialPair +OAI.MeasureTheory.Falconer.Recursion.PotentialScale +OAI.MeasureTheory.Falconer.Recursion.PrefixBandAssembly +OAI.MeasureTheory.Falconer.Recursion.PrefixChildDropping +OAI.MeasureTheory.Falconer.Recursion.PrefixCounting +OAI.MeasureTheory.Falconer.Recursion.PrefixInverseSupremum +OAI.MeasureTheory.Falconer.Recursion.PrefixLowMaximum +OAI.MeasureTheory.Falconer.Recursion.PrefixMass +OAI.MeasureTheory.Falconer.Recursion.PrefixPolicyGeometry +OAI.MeasureTheory.Falconer.Recursion.ProductPrefixCount +OAI.MeasureTheory.Falconer.Recursion.ProductRetainedStrip +OAI.MeasureTheory.Falconer.Recursion.ProfileApplicationBudget +OAI.MeasureTheory.Falconer.Recursion.ProfileBalls +OAI.MeasureTheory.Falconer.Recursion.ProfileBetweenNodes +OAI.MeasureTheory.Falconer.Recursion.ProfileBlockRefinement +OAI.MeasureTheory.Falconer.Recursion.ProfileBranchCounts +OAI.MeasureTheory.Falconer.Recursion.ProfileCellFamily +OAI.MeasureTheory.Falconer.Recursion.ProfileChordBounds +OAI.MeasureTheory.Falconer.Recursion.ProfileCompactness +OAI.MeasureTheory.Falconer.Recursion.ProfileContactInterval +OAI.MeasureTheory.Falconer.Recursion.ProfileContactStability +OAI.MeasureTheory.Falconer.Recursion.ProfileDecomposition +OAI.MeasureTheory.Falconer.Recursion.ProfileEndpointBound +OAI.MeasureTheory.Falconer.Recursion.ProfileEndpointStability +OAI.MeasureTheory.Falconer.Recursion.ProfileEntry +OAI.MeasureTheory.Falconer.Recursion.ProfileEnvelopes +OAI.MeasureTheory.Falconer.Recursion.ProfileExcess +OAI.MeasureTheory.Falconer.Recursion.ProfileGainAccounting +OAI.MeasureTheory.Falconer.Recursion.ProfileGainParameters +OAI.MeasureTheory.Falconer.Recursion.ProfileGeometryBudget +OAI.MeasureTheory.Falconer.Recursion.ProfileGeometryPower +OAI.MeasureTheory.Falconer.Recursion.ProfileGoodBound +OAI.MeasureTheory.Falconer.Recursion.ProfileGrid +OAI.MeasureTheory.Falconer.Recursion.ProfileGridCells +OAI.MeasureTheory.Falconer.Recursion.ProfileHighMass +OAI.MeasureTheory.Falconer.Recursion.ProfileIncrementFrostman +OAI.MeasureTheory.Falconer.Recursion.ProfileInterpolation +OAI.MeasureTheory.Falconer.Recursion.ProfileIntervalChain +OAI.MeasureTheory.Falconer.Recursion.ProfileIterationBudget +OAI.MeasureTheory.Falconer.Recursion.ProfileLipschitz +OAI.MeasureTheory.Falconer.Recursion.ProfileLowerBound +OAI.MeasureTheory.Falconer.Recursion.ProfileMergeStep +OAI.MeasureTheory.Falconer.Recursion.ProfileMerging +OAI.MeasureTheory.Falconer.Recursion.ProfileNear +OAI.MeasureTheory.Falconer.Recursion.ProfileNodeValues +OAI.MeasureTheory.Falconer.Recursion.ProfileNormalBound +OAI.MeasureTheory.Falconer.Recursion.ProfileNormalBudget +OAI.MeasureTheory.Falconer.Recursion.ProfilePacking +OAI.MeasureTheory.Falconer.Recursion.ProfilePairMass +OAI.MeasureTheory.Falconer.Recursion.ProfilePrefix +OAI.MeasureTheory.Falconer.Recursion.ProfileRestriction +OAI.MeasureTheory.Falconer.Recursion.ProfileRightContact +OAI.MeasureTheory.Falconer.Recursion.ProfileRoundContact +OAI.MeasureTheory.Falconer.Recursion.ProfileScaleInduction +OAI.MeasureTheory.Falconer.Recursion.ProfileScaleSelection +OAI.MeasureTheory.Falconer.Recursion.ProfileStepBudget +OAI.MeasureTheory.Falconer.Recursion.ProfileSuffixContact +OAI.MeasureTheory.Falconer.Recursion.ProfileSuffixMinimum +OAI.MeasureTheory.Falconer.Recursion.ProfileTelescoping +OAI.MeasureTheory.Falconer.Recursion.ProfileUniformIterationBudget +OAI.MeasureTheory.Falconer.Recursion.ProfileUniformLimit +OAI.MeasureTheory.Falconer.Recursion.ProjectionProfileAlgebra +OAI.MeasureTheory.Falconer.Recursion.ProjectionProfileMean +OAI.MeasureTheory.Falconer.Recursion.ReachedBranchWeights +OAI.MeasureTheory.Falconer.Recursion.ReachedStateRecursion +OAI.MeasureTheory.Falconer.Recursion.RecursiveCellInvariants +OAI.MeasureTheory.Falconer.Recursion.RegularPacketScaleBudget +OAI.MeasureTheory.Falconer.Recursion.RegularizedPotential +OAI.MeasureTheory.Falconer.Recursion.RelativeScaleBudget +OAI.MeasureTheory.Falconer.Recursion.RetainedPairMasks +OAI.MeasureTheory.Falconer.Recursion.RetainedProfileBounds +OAI.MeasureTheory.Falconer.Recursion.RoundedContactWidth +OAI.MeasureTheory.Falconer.Recursion.RoundedHighProfile +OAI.MeasureTheory.Falconer.Recursion.RoundedProfileContact +OAI.MeasureTheory.Falconer.Recursion.RoundedProfileError +OAI.MeasureTheory.Falconer.Recursion.RoundedProfileGain +OAI.MeasureTheory.Falconer.Recursion.RoundedProfilePieces +OAI.MeasureTheory.Falconer.Recursion.ScalarBinaryBranch +OAI.MeasureTheory.Falconer.Recursion.ScalarBranchAccounting +OAI.MeasureTheory.Falconer.Recursion.ScalarBranchGrowth +OAI.MeasureTheory.Falconer.Recursion.ScalarBranchingLevel +OAI.MeasureTheory.Falconer.Recursion.ScalarBunchingLedger +OAI.MeasureTheory.Falconer.Recursion.ScalarPotential +OAI.MeasureTheory.Falconer.Recursion.ScalarTerminalFiberMass +OAI.MeasureTheory.Falconer.Recursion.ScalarTerminalPorousGain +OAI.MeasureTheory.Falconer.Recursion.ScalarTerminalProjection +OAI.MeasureTheory.Falconer.Recursion.ScalarTerminalPruning +OAI.MeasureTheory.Falconer.Recursion.SourceBranchDepth +OAI.MeasureTheory.Falconer.Recursion.SourceClassContact +OAI.MeasureTheory.Falconer.Recursion.SourceClassIntervals +OAI.MeasureTheory.Falconer.Recursion.SourcePrefixReduction +OAI.MeasureTheory.Falconer.Recursion.SourceSuffixReduction +OAI.MeasureTheory.Falconer.Recursion.SuffixBinAssembly +OAI.MeasureTheory.Falconer.Recursion.SuffixBinGeometry +OAI.MeasureTheory.Falconer.Recursion.SuffixCoarseDomination +OAI.MeasureTheory.Falconer.Recursion.SuffixDescriptors +OAI.MeasureTheory.Falconer.Recursion.SuffixDirectionGeometry +OAI.MeasureTheory.Falconer.Recursion.SuffixDistanceTaylor +OAI.MeasureTheory.Falconer.Recursion.SuffixGoodTransport +OAI.MeasureTheory.Falconer.Recursion.SuffixLocalBins +OAI.MeasureTheory.Falconer.Recursion.SuffixNormalization +OAI.MeasureTheory.Falconer.Recursion.SuffixPowerLoss +OAI.MeasureTheory.Falconer.Recursion.SuffixRetainedPairs +OAI.MeasureTheory.Falconer.Recursion.SurfacePotential +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalCost +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalData +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalDyadicGain +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalPower +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalProduct +OAI.MeasureTheory.Falconer.Recursion.ThreeIntervalShift +OAI.MeasureTheory.Falconer.Recursion.TruncatedScalarPotential +OAI.MeasureTheory.Falconer.Recursion.TwoProfileEnergy +OAI.MeasureTheory.Falconer.Recursion.TwoProfileInverse +OAI.MeasureTheory.Falconer.Recursion.TwoProfileInverseCost +OAI.MeasureTheory.Falconer.Recursion.TwoProfileInverseIntegrable +OAI.MeasureTheory.Falconer.Recursion.TwoProfileInverseScalar +OAI.MeasureTheory.Falconer.Recursion.TwoProfileRecursion +OAI.MeasureTheory.Falconer.Recursion.TwoRootGain +OAI.MeasureTheory.Falconer.Recursion.UniformContactDepths +OAI.MeasureTheory.Falconer.Recursion.UniformFrostmanProfiles +OAI.MeasureTheory.Falconer.Recursion.UniformProfileContact +OAI.MeasureTheory.Falconer.Recursion.UniformProfileGain +OAI.MeasureTheory.Falconer.Recursion.UniformScaleBudgets +OAI.MeasureTheory.Falconer.Recursion.UnitProfiles +OAI.MeasureTheory.Falconer.Recursion.WeightedBranchInduction +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellDistance +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellNormalized +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellRebin +OAI.MeasureTheory.Falconer.Shells.ActualHighShellEquation21 +OAI.MeasureTheory.Falconer.Shells.ActualHighShellInverse +OAI.MeasureTheory.Falconer.Shells.ActualRestorationBound +OAI.MeasureTheory.Falconer.Shells.AngularLengthShellCover +OAI.MeasureTheory.Falconer.Shells.AngularShellEnergy +OAI.MeasureTheory.Falconer.Shells.AssemblyErrorBound +OAI.MeasureTheory.Falconer.Shells.AssemblyLosses +OAI.MeasureTheory.Falconer.Shells.ClassPairDistance +OAI.MeasureTheory.Falconer.Shells.ClassPairShell +OAI.MeasureTheory.Falconer.Shells.ContinuousCoefficientShell +OAI.MeasureTheory.Falconer.Shells.DecayEndgame +OAI.MeasureTheory.Falconer.Shells.DescriptorShellRegime +OAI.MeasureTheory.Falconer.Shells.DistanceInverse +OAI.MeasureTheory.Falconer.Shells.DistanceLinearization +OAI.MeasureTheory.Falconer.Shells.EndpointWeightedDistance +OAI.MeasureTheory.Falconer.Shells.FarPositiveSum +OAI.MeasureTheory.Falconer.Shells.FilteredClassShell +OAI.MeasureTheory.Falconer.Shells.FilteredEndpointDistance +OAI.MeasureTheory.Falconer.Shells.FilteredShellEndgame +OAI.MeasureTheory.Falconer.Shells.FiniteShellSum +OAI.MeasureTheory.Falconer.Shells.FiniteSpatialShell +OAI.MeasureTheory.Falconer.Shells.FiniteWeightedShell +OAI.MeasureTheory.Falconer.Shells.FrequencyShell +OAI.MeasureTheory.Falconer.Shells.HalfDimensionalShell +OAI.MeasureTheory.Falconer.Shells.HighShellCoefficientBounds +OAI.MeasureTheory.Falconer.Shells.HighShellCone +OAI.MeasureTheory.Falconer.Shells.HighShellEndpointTerms +OAI.MeasureTheory.Falconer.Shells.HighShellEquation21 +OAI.MeasureTheory.Falconer.Shells.HighShellErrorPower +OAI.MeasureTheory.Falconer.Shells.HighShellFiniteSeparation +OAI.MeasureTheory.Falconer.Shells.HighShellFourierError +OAI.MeasureTheory.Falconer.Shells.HighShellKernelTerms +OAI.MeasureTheory.Falconer.Shells.HighShellLeibnizSymbols +OAI.MeasureTheory.Falconer.Shells.HighShellMainEnergy +OAI.MeasureTheory.Falconer.Shells.HighShellMeasurable +OAI.MeasureTheory.Falconer.Shells.HighShellMixture +OAI.MeasureTheory.Falconer.Shells.HighShellNormalization +OAI.MeasureTheory.Falconer.Shells.HighShellOrderForm +OAI.MeasureTheory.Falconer.Shells.HighShellParentEnergy +OAI.MeasureTheory.Falconer.Shells.HighShellProfileMass +OAI.MeasureTheory.Falconer.Shells.HighShellRadialBounds +OAI.MeasureTheory.Falconer.Shells.HighShellSeparatedTerms +OAI.MeasureTheory.Falconer.Shells.HighShellStationaryScale +OAI.MeasureTheory.Falconer.Shells.HighShellSubpower +OAI.MeasureTheory.Falconer.Shells.HighShellSupremum +OAI.MeasureTheory.Falconer.Shells.InverseClassShell +OAI.MeasureTheory.Falconer.Shells.ListWeightedShell +OAI.MeasureTheory.Falconer.Shells.LocalizedScalarShell +OAI.MeasureTheory.Falconer.Shells.MaskedDistanceBounds +OAI.MeasureTheory.Falconer.Shells.MonotoneShellCriterion +OAI.MeasureTheory.Falconer.Shells.MonotoneShellVariation +OAI.MeasureTheory.Falconer.Shells.NormalizedHighShellError +OAI.MeasureTheory.Falconer.Shells.NormalizedHighShellKernel +OAI.MeasureTheory.Falconer.Shells.NormalizedOuterShell +OAI.MeasureTheory.Falconer.Shells.NormalizedShellCoefficients +OAI.MeasureTheory.Falconer.Shells.OriginalClassDistance +OAI.MeasureTheory.Falconer.Shells.OriginalInverseStateShell +OAI.MeasureTheory.Falconer.Shells.OriginalShellIntegral +OAI.MeasureTheory.Falconer.Shells.PartitionEndpointDistance +OAI.MeasureTheory.Falconer.Shells.PolicyPositiveBand +OAI.MeasureTheory.Falconer.Shells.PolicyPositiveBranches +OAI.MeasureTheory.Falconer.Shells.PolicyPositiveRecurrence +OAI.MeasureTheory.Falconer.Shells.PolicyPrefixShell +OAI.MeasureTheory.Falconer.Shells.PositiveKernel +OAI.MeasureTheory.Falconer.Shells.PositiveLowFrequency +OAI.MeasureTheory.Falconer.Shells.PositiveRestriction +OAI.MeasureTheory.Falconer.Shells.PositiveSpatialKernel +OAI.MeasureTheory.Falconer.Shells.PositiveSuffix +OAI.MeasureTheory.Falconer.Shells.PositiveTerminal +OAI.MeasureTheory.Falconer.Shells.PositiveTests +OAI.MeasureTheory.Falconer.Shells.PrefixHighShell +OAI.MeasureTheory.Falconer.Shells.PreparedEndgame +OAI.MeasureTheory.Falconer.Shells.PublishedClassicalDistance +OAI.MeasureTheory.Falconer.Shells.RadialShellMass +OAI.MeasureTheory.Falconer.Shells.RegularClassShell +OAI.MeasureTheory.Falconer.Shells.RegularOuterShell +OAI.MeasureTheory.Falconer.Shells.RegularRestrictedShell +OAI.MeasureTheory.Falconer.Shells.RegularizationScalarShell +OAI.MeasureTheory.Falconer.Shells.RestorationPowerRate +OAI.MeasureTheory.Falconer.Shells.RestorationSubpower +OAI.MeasureTheory.Falconer.Shells.RestoredMaskCoverage +OAI.MeasureTheory.Falconer.Shells.RestoredShellCandidates +OAI.MeasureTheory.Falconer.Shells.RootEndpointData +OAI.MeasureTheory.Falconer.Shells.RootEndpointTerms +OAI.MeasureTheory.Falconer.Shells.RootHighShellInverse +OAI.MeasureTheory.Falconer.Shells.RootShellData +OAI.MeasureTheory.Falconer.Shells.RootShellMain +OAI.MeasureTheory.Falconer.Shells.RootShellMixture +OAI.MeasureTheory.Falconer.Shells.RootShellOrder +OAI.MeasureTheory.Falconer.Shells.RotatedInverseShell +OAI.MeasureTheory.Falconer.Shells.ScalarPositiveZoom +OAI.MeasureTheory.Falconer.Shells.ScalarShellError +OAI.MeasureTheory.Falconer.Shells.ShellApproximationError +OAI.MeasureTheory.Falconer.Shells.ShellErrorSummability +OAI.MeasureTheory.Falconer.Shells.ShellFrequencyEnergy +OAI.MeasureTheory.Falconer.Shells.ShellFrequencyTests +OAI.MeasureTheory.Falconer.Shells.ShellKernels +OAI.MeasureTheory.Falconer.Shells.ShellMixtures +OAI.MeasureTheory.Falconer.Shells.ShellMultipliers +OAI.MeasureTheory.Falconer.Shells.ShellNonstationary +OAI.MeasureTheory.Falconer.Shells.ShellReconstruction +OAI.MeasureTheory.Falconer.Shells.ShellSummability +OAI.MeasureTheory.Falconer.Shells.ShellTestConvergence +OAI.MeasureTheory.Falconer.Shells.Shells +OAI.MeasureTheory.Falconer.Shells.SmoothShellDomination +OAI.MeasureTheory.Falconer.Shells.SmoothShellPartition +OAI.MeasureTheory.Falconer.Shells.SpatialSharedShell +OAI.MeasureTheory.Falconer.Shells.TwoProfileInverseShell +OAI.MeasureTheory.Falconer.Shells.TwoProfileMaskedShell +OAI.MeasureTheory.Falconer.Shells.TwoRootApproximations +OAI.MeasureTheory.Falconer.Shells.TwoRootCandidates +OAI.MeasureTheory.Falconer.Shells.TwoRootClassMixture +OAI.MeasureTheory.Falconer.Shells.TwoRootMaskCoverage +OAI.MeasureTheory.Falconer.Shells.TwoRootMasks +OAI.MeasureTheory.Falconer.Shells.TwoRootMixtureFinite +OAI.MeasureTheory.Falconer.Shells.TwoRootRestoration +OAI.MeasureTheory.Falconer.Shells.TwoRootShellDecay +OAI.MeasureTheory.Falconer.Shells.TwoSidedShell +OAI.MeasureTheory.Falconer.Shells.UnitPairEndgame +OAI.MeasureTheory.Falconer.Shells.WeightedHighShellInverse +OAI.MeasureTheory.Falconer.Slicing.AffineSliceCoordinates +OAI.MeasureTheory.Falconer.Slicing.CommonSliceSelection +OAI.MeasureTheory.Falconer.Slicing.DyadicSliceCosts +OAI.MeasureTheory.Falconer.Slicing.DyadicSliceSelection +OAI.MeasureTheory.Falconer.Slicing.EndpointSliceCosts +OAI.MeasureTheory.Falconer.Slicing.EndpointSliceObstruction +OAI.MeasureTheory.Falconer.Slicing.GaussianActiveCount +OAI.MeasureTheory.Falconer.Slicing.GaussianActiveCover +OAI.MeasureTheory.Falconer.Slicing.GaussianActiveFamily +OAI.MeasureTheory.Falconer.Slicing.GaussianActiveLoss +OAI.MeasureTheory.Falconer.Slicing.GaussianActiveRelation +OAI.MeasureTheory.Falconer.Slicing.GaussianAmplification +OAI.MeasureTheory.Falconer.Slicing.GaussianBadTripleMass +OAI.MeasureTheory.Falconer.Slicing.GaussianBallMeasurable +OAI.MeasureTheory.Falconer.Slicing.GaussianBallTruncation +OAI.MeasureTheory.Falconer.Slicing.GaussianBand +OAI.MeasureTheory.Falconer.Slicing.GaussianBandLower +OAI.MeasureTheory.Falconer.Slicing.GaussianBandRestriction +OAI.MeasureTheory.Falconer.Slicing.GaussianBox +OAI.MeasureTheory.Falconer.Slicing.GaussianChartPairAverage +OAI.MeasureTheory.Falconer.Slicing.GaussianChartPairKernel +OAI.MeasureTheory.Falconer.Slicing.GaussianChartTripleAverage +OAI.MeasureTheory.Falconer.Slicing.GaussianChartTripleKernelMeasurable +OAI.MeasureTheory.Falconer.Slicing.GaussianCloseBound +OAI.MeasureTheory.Falconer.Slicing.GaussianCloseMass +OAI.MeasureTheory.Falconer.Slicing.GaussianControlledIncidence +OAI.MeasureTheory.Falconer.Slicing.GaussianControlledLedger +OAI.MeasureTheory.Falconer.Slicing.GaussianControlledRows +OAI.MeasureTheory.Falconer.Slicing.GaussianConvolution +OAI.MeasureTheory.Falconer.Slicing.GaussianDamping +OAI.MeasureTheory.Falconer.Slicing.GaussianDensity +OAI.MeasureTheory.Falconer.Slicing.GaussianDyadicGeometry +OAI.MeasureTheory.Falconer.Slicing.GaussianEndpointExclusion +OAI.MeasureTheory.Falconer.Slicing.GaussianEnergy +OAI.MeasureTheory.Falconer.Slicing.GaussianFinitePruning +OAI.MeasureTheory.Falconer.Slicing.GaussianFourier +OAI.MeasureTheory.Falconer.Slicing.GaussianFrostmanTransfer +OAI.MeasureTheory.Falconer.Slicing.GaussianFullRank +OAI.MeasureTheory.Falconer.Slicing.GaussianGram +OAI.MeasureTheory.Falconer.Slicing.GaussianIncidenceAverage +OAI.MeasureTheory.Falconer.Slicing.GaussianIncidenceTail +OAI.MeasureTheory.Falconer.Slicing.GaussianKernelCoordinates +OAI.MeasureTheory.Falconer.Slicing.GaussianKernelGeometry +OAI.MeasureTheory.Falconer.Slicing.GaussianLabelCost +OAI.MeasureTheory.Falconer.Slicing.GaussianLebesgue +OAI.MeasureTheory.Falconer.Slicing.GaussianLocalBand +OAI.MeasureTheory.Falconer.Slicing.GaussianLocalization +OAI.MeasureTheory.Falconer.Slicing.GaussianLossAbsorption +OAI.MeasureTheory.Falconer.Slicing.GaussianMapBalls +OAI.MeasureTheory.Falconer.Slicing.GaussianMass +OAI.MeasureTheory.Falconer.Slicing.GaussianMomentScale +OAI.MeasureTheory.Falconer.Slicing.GaussianMomentWeights +OAI.MeasureTheory.Falconer.Slicing.GaussianMultiband +OAI.MeasureTheory.Falconer.Slicing.GaussianOriginalCosts +OAI.MeasureTheory.Falconer.Slicing.GaussianOriginalSlice +OAI.MeasureTheory.Falconer.Slicing.GaussianOrthogonal +OAI.MeasureTheory.Falconer.Slicing.GaussianPairBand +OAI.MeasureTheory.Falconer.Slicing.GaussianPairGeometry +OAI.MeasureTheory.Falconer.Slicing.GaussianPairRestrictions +OAI.MeasureTheory.Falconer.Slicing.GaussianParameterSupport +OAI.MeasureTheory.Falconer.Slicing.GaussianPlanarChart +OAI.MeasureTheory.Falconer.Slicing.GaussianPlanarExclusion +OAI.MeasureTheory.Falconer.Slicing.GaussianPointBand +OAI.MeasureTheory.Falconer.Slicing.GaussianPointBound +OAI.MeasureTheory.Falconer.Slicing.GaussianPointClose +OAI.MeasureTheory.Falconer.Slicing.GaussianPointCloseBound +OAI.MeasureTheory.Falconer.Slicing.GaussianPointMass +OAI.MeasureTheory.Falconer.Slicing.GaussianPointMoment +OAI.MeasureTheory.Falconer.Slicing.GaussianPointTruncation +OAI.MeasureTheory.Falconer.Slicing.GaussianPolynomialCosts +OAI.MeasureTheory.Falconer.Slicing.GaussianPolynomialSlice +OAI.MeasureTheory.Falconer.Slicing.GaussianPreservesIndependence +OAI.MeasureTheory.Falconer.Slicing.GaussianProjection +OAI.MeasureTheory.Falconer.Slicing.GaussianProjectionEnergy +OAI.MeasureTheory.Falconer.Slicing.GaussianPrunedBalls +OAI.MeasureTheory.Falconer.Slicing.GaussianPrunedIncidence +OAI.MeasureTheory.Falconer.Slicing.GaussianPrunedMass +OAI.MeasureTheory.Falconer.Slicing.GaussianPrunedPair +OAI.MeasureTheory.Falconer.Slicing.GaussianPruningCosts +OAI.MeasureTheory.Falconer.Slicing.GaussianPruningLedger +OAI.MeasureTheory.Falconer.Slicing.GaussianPruningSets +OAI.MeasureTheory.Falconer.Slicing.GaussianRestrictedMass +OAI.MeasureTheory.Falconer.Slicing.GaussianRieszKernel +OAI.MeasureTheory.Falconer.Slicing.GaussianRieszScaling +OAI.MeasureTheory.Falconer.Slicing.GaussianRowDimension +OAI.MeasureTheory.Falconer.Slicing.GaussianRowMap +OAI.MeasureTheory.Falconer.Slicing.GaussianRowStability +OAI.MeasureTheory.Falconer.Slicing.GaussianRows +OAI.MeasureTheory.Falconer.Slicing.GaussianScaleBudget +OAI.MeasureTheory.Falconer.Slicing.GaussianSelectActive +OAI.MeasureTheory.Falconer.Slicing.GaussianSelectActiveCosts +OAI.MeasureTheory.Falconer.Slicing.GaussianSelectPruned +OAI.MeasureTheory.Falconer.Slicing.GaussianSelectPrunedPairCosts +OAI.MeasureTheory.Falconer.Slicing.GaussianShellEnergy +OAI.MeasureTheory.Falconer.Slicing.GaussianSlabBox +OAI.MeasureTheory.Falconer.Slicing.GaussianSliceBound +OAI.MeasureTheory.Falconer.Slicing.GaussianSliceMass +OAI.MeasureTheory.Falconer.Slicing.GaussianSliceMean +OAI.MeasureTheory.Falconer.Slicing.GaussianSliceMoment +OAI.MeasureTheory.Falconer.Slicing.GaussianSliceTail +OAI.MeasureTheory.Falconer.Slicing.GaussianSmoothing +OAI.MeasureTheory.Falconer.Slicing.GaussianSpanRows +OAI.MeasureTheory.Falconer.Slicing.GaussianThreshold +OAI.MeasureTheory.Falconer.Slicing.GaussianTripleBand +OAI.MeasureTheory.Falconer.Slicing.GaussianTripleNormalization +OAI.MeasureTheory.Falconer.Slicing.GaussianTruncatedTriple +OAI.MeasureTheory.Falconer.Slicing.GaussianTubeGeometry +OAI.MeasureTheory.Falconer.Slicing.GaussianVectorBand +OAI.MeasureTheory.Falconer.Slicing.GnomonicSliceLaw +OAI.MeasureTheory.Falconer.Slicing.GramSchmidtMeasurable +OAI.MeasureTheory.Falconer.Slicing.GramSchmidtSlab +OAI.MeasureTheory.Falconer.Slicing.GramSchmidtVolume +OAI.MeasureTheory.Falconer.Slicing.HyperplaneSlice +OAI.MeasureTheory.Falconer.Slicing.HyperplaneSliceEnergy +OAI.MeasureTheory.Falconer.Slicing.OrientedSlice +OAI.MeasureTheory.Falconer.Slicing.OrientedSliceBalls +OAI.MeasureTheory.Falconer.Slicing.OscillatoryGaussian +OAI.MeasureTheory.Falconer.Slicing.PlanarSliceGeometry +OAI.MeasureTheory.Falconer.Slicing.RectangularGramSchmidt +OAI.MeasureTheory.Falconer.Slicing.SlabSliceAverage +OAI.MeasureTheory.Falconer.Slicing.SliceBallTransfer +OAI.MeasureTheory.Falconer.Slicing.SliceBudget +OAI.MeasureTheory.Falconer.Slicing.SliceCoordinates +OAI.MeasureTheory.Falconer.Slicing.SliceDirectionDeletion +OAI.MeasureTheory.Falconer.Slicing.SliceGeometry +OAI.MeasureTheory.Falconer.Slicing.SliceIncidence +OAI.MeasureTheory.Falconer.Slicing.SliceMapBalls +OAI.MeasureTheory.Falconer.Slicing.SliceNormalization +OAI.MeasureTheory.Falconer.Slicing.SlicePruningRatios +OAI.MeasureTheory.Falconer.Slicing.SliceScaling +OAI.MeasureTheory.Falconer.Slicing.SliceSelectionMean +OAI.MeasureTheory.Falconer.Slicing.SliceThreeTubeMass +OAI.MeasureTheory.Falconer.Slicing.SliceTripleStability +OAI.MeasureTheory.Falconer.Slicing.SliceTubeGeometry +OAI.MeasureTheory.Falconer.Slicing.SmallGaussianChart +OAI.MeasureTheory.Falconer.Slicing.TransverseFrame +OAI.MeasureTheory.Falconer.Slicing.UnnormalizedSliceBalls diff --git a/tasks/falconer-all-dimensions/solution/reference.py b/tasks/falconer-all-dimensions/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/falconer-all-dimensions/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/falconer-all-dimensions/solution/solve.sh b/tasks/falconer-all-dimensions/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..10fade8c3413eb2a53bdb3b4b311529a21cc8924 --- /dev/null +++ b/tasks/falconer-all-dimensions/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FalconerAllDimensions, i.e. module OAI.MeasureTheory.Falconer.Campaign123PlanarFurstenbergProof and the +# 2384 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MeasureTheory.Falconer.Campaign123PlanarFurstenbergProof /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FalconerAllDimensions" diff --git a/tasks/falconer-all-dimensions/task.toml b/tasks/falconer-all-dimensions/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..71213c5037211b115e76c9e8c694c127ee188e78 --- /dev/null +++ b/tasks/falconer-all-dimensions/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/falconer-all-dimensions" +version = "1.0.0" +description = "Prove FalconerAllDimensions (openai/math family 073: The Falconer distance conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FalconerAllDimensions.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FalconerAllDimensions" +family = "073" +family_title = "The Falconer distance conjecture" +subject = "Real and complex analysis" +theorems = ["OAI.Falconer.falconer_distance_conjecture"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MeasureTheory.Falconer.Campaign123PlanarFurstenbergProof" +reference_modules = 2384 +reference_lean_bytes = 8957826 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 4645 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19762 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/falconer-all-dimensions/tests/Challenge.lean b/tasks/falconer-all-dimensions/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe48d9e54579aa17007a3c83e639cf63f386ebc7 --- /dev/null +++ b/tasks/falconer-all-dimensions/tests/Challenge.lean @@ -0,0 +1,19 @@ +import Mathlib + +namespace OAI + +namespace Falconer +open MeasureTheory +open scoped ENNReal + +/-- A compact subset of Euclidean space with Hausdorff dimension greater than +half the ambient dimension determines a distance set of positive Lebesgue measure. -/ +theorem falconer_distance_conjecture : + ∀ (d : ℕ), 2 ≤ d → ∀ E : Set (EuclideanSpace ℝ (Fin d)), IsCompact E → + (d : ℝ≥0∞) / 2 < dimH E → + 0 < volume {r : ℝ | ∃ x ∈ E, ∃ y ∈ E, dist x y = r} := by + sorry + +end Falconer + +end OAI diff --git a/tasks/falconer-all-dimensions/tests/grade.py b/tasks/falconer-all-dimensions/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/falconer-all-dimensions/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/falconer-all-dimensions/tests/task.json b/tasks/falconer-all-dimensions/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7a3aa83a0569b4ebb3db93bbb79e2ce30ecd08cd --- /dev/null +++ b/tasks/falconer-all-dimensions/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FalconerAllDimensions", + "comparator": { + "theorem_names": [ + "OAI.Falconer.falconer_distance_conjecture" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18862 +} \ No newline at end of file diff --git a/tasks/falconer-all-dimensions/tests/test.sh b/tasks/falconer-all-dimensions/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/falconer-all-dimensions/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/filling-coefficient/environment/Dockerfile b/tasks/filling-coefficient/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/filling-coefficient/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/filling-coefficient/environment/fetch_mathlib.sh b/tasks/filling-coefficient/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/filling-coefficient/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/filling-coefficient/environment/lake-manifest.json b/tasks/filling-coefficient/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/filling-coefficient/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/filling-coefficient/environment/lakefile.lean b/tasks/filling-coefficient/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/filling-coefficient/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/filling-coefficient/environment/lean_setup.sh b/tasks/filling-coefficient/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/filling-coefficient/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/filling-coefficient/environment/pack_submission.py b/tasks/filling-coefficient/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/filling-coefficient/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/filling-coefficient/instruction.md b/tasks/filling-coefficient/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9249f182724aac6e2a85db4136f0c0d7637c617e --- /dev/null +++ b/tasks/filling-coefficient/instruction.md @@ -0,0 +1,181 @@ +# openai/math challenge `FillingCoefficient` (family 337) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 337 of the release, *Cartan–Hadamard isoperimetry and CAT$(0)$ fillings* +(Differential geometry). The family as a whole: Proves generalized Cartan–Hadamard isoperimetry in every dimension: in a complete simply connected manifold with sectional curvature at most $\kappa\le0$, every finite-volume finite-perimeter set satisfies the sharp comparison with the equal-volume model ball. Bounded positive-volume equality regions for $\kappa=0$ are Euclidean balls. Also proves sharp Euclidean filling bounds for compactly supported integral $n$-cycles, $n\ge2$, in arbitrary proper CAT$(0)$ spaces. + +The challenge is `FillingCoefficient`, also at `/opt/openai-math/challenges/FillingCoefficient.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped Topology ENNReal NNReal + +namespace SharpIntegralFillings + +attribute [local instance] Classical.propDecidable + +universe u + +abbrev Euc (k : ℕ) := EuclideanSpace ℝ (Fin k) +abbrev Functional (X : Type u) (k : ℕ) := (X → ℝ) → (Fin k → X → ℝ) → ℝ + +section MetricCurrents + +variable {X : Type u} [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + +def BoundedLip (b : X → ℝ) : Prop := + (∃ K : ℝ≥0, LipschitzWith K b) ∧ ∃ M : ℝ, ∀ x, |b x| ≤ M + +def Admissible {k : ℕ} (b : X → ℝ) (π : Fin k → X → ℝ) : Prop := + BoundedLip b ∧ ∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i) + +def Controls {k : ℕ} (T : Functional X k) (μ : Measure X) : Prop := + ∀ (b : X → ℝ) (π : Fin k → X → ℝ), BoundedLip b → + (∀ i, LipschitzWith 1 (π i)) → + |T b π| ≤ ∫ x, |b x| ∂μ + +noncomputable def mass {k : ℕ} (T : Functional X k) : ℝ := + sInf {r : ℝ | ∃ μ : Measure X, + IsFiniteMeasure μ ∧ Controls T μ ∧ r = μ.real univ} + +structure IsMetricCurrent {k : ℕ} (T : Functional X k) : Prop where + offDomain : ∀ b π, ¬Admissible b π → T b π = 0 + linearFirst : ∀ b₁ b₂ π (a c : ℝ), BoundedLip b₁ → BoundedLip b₂ → + (∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i)) → + T (fun x => a * b₁ x + c * b₂ x) π = a * T b₁ π + c * T b₂ π + linearCoord : ∀ b π i f (a c : ℝ), Admissible b π → + (∃ K : ℝ≥0, LipschitzWith K f) → + T b (Function.update π i (fun x => a * π i x + c * f x)) = + a * T b π + c * T b (Function.update π i f) + sequentialContinuity : ∀ b π (πs : ℕ → Fin k → X → ℝ), BoundedLip b → + (∀ i, ∃ K : ℝ≥0, ∀ j, LipschitzWith K (πs j i)) → + (∀ i x, Tendsto (fun j => πs j i x) atTop (𝓝 (π i x))) → + Tendsto (fun j => T b (πs j)) atTop (𝓝 (T b π)) + locality : ∀ b π, Admissible b π → + (∃ (i : Fin k) (U : Set X) (c : ℝ), IsOpen U ∧ Function.support b ⊆ U ∧ + ∀ x ∈ U, π i x = c) → T b π = 0 + finiteMass : ∃ μ : Measure X, IsFiniteMeasure μ ∧ Controls T μ + +noncomputable def boundarySucc {k : ℕ} (T : Functional X (k + 1)) : Functional X k := + fun b π => if Admissible b π then T (fun _ => 1) (Matrix.vecCons b π) else 0 + +noncomputable def boundary : {k : ℕ} → Functional X k → Functional X (k - 1) + | 0, _ => fun _ _ => 0 + | _ + 1, T => boundarySucc T + +structure IntegerChart (X : Type u) [MetricSpace X] (k : ℕ) where + domain : Set (Euc k) + borel : MeasurableSet domain + bounded : Bornology.IsBounded domain + param : domain → X + bilipschitz : ∃ L U : ℝ≥0, LipschitzWith L param ∧ AntilipschitzWith U param + multiplicity : Euc k → ℤ + integrable : Integrable (fun z => (multiplicity z : ℝ)) (volume.restrict domain) + +namespace IntegerChart + +variable {k : ℕ} (C : IntegerChart X k) + +noncomputable def scalar (f : X → ℝ) (z : Euc k) : ℝ := + if hz : z ∈ C.domain then f (C.param ⟨z, hz⟩) else 0 + +noncomputable def jacobian (π : Fin k → X → ℝ) (z : Euc k) : ℝ := + Matrix.det (fun i j => + (fderivWithin ℝ (C.scalar (π i)) C.domain z) (EuclideanSpace.single j 1)) + +noncomputable def action : Functional X k := + fun b π => if Admissible b π then + ∫ z in C.domain, (C.multiplicity z : ℝ) * C.scalar b z * C.jacobian π z + else 0 + +def image : Set X := Set.range C.param + +end IntegerChart + +def IntegerRectifiable {k : ℕ} (T : Functional X k) : Prop := + ∃ C : ℕ → IntegerChart X k, + Pairwise (fun i j => Disjoint (C i).image (C j).image) ∧ + (∀ i, IsMetricCurrent (C i).action) ∧ + Summable (fun i => mass (C i).action) ∧ + ∀ b π, T b π = ∑' i, (C i).action b π + +def IsIntegral : (k : ℕ) → Functional X k → Prop + | 0, T => IsMetricCurrent T ∧ IntegerRectifiable T + | _ + 1, T => IsMetricCurrent T ∧ IntegerRectifiable T ∧ + IsMetricCurrent (boundarySucc T) ∧ IntegerRectifiable (boundarySucc T) + +abbrev IntegralCurrent (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + (k : ℕ) := { T : Functional X k // IsIntegral k T } + +def CompactlySupported {k : ℕ} (T : Functional X k) : Prop := + ∃ K : Set X, IsCompact K ∧ + ∀ b π, Admissible b π → (∀ x ∈ K, b x = 0) → T b π = 0 + +def IsCycle {k : ℕ} (T : Functional X k) : Prop := boundary T = fun _ _ => 0 + +end MetricCurrents + +noncomputable def omega (k : ℕ) : ℝ := + (volume (Metric.ball (0 : Euc k) 1)).toReal +noncomputable def sphereArea (n : ℕ) : ℝ := (n + 1 : ℝ) * omega (n + 1) +noncomputable def fillingCoefficient (n : ℕ) : ℝ := + 1 / ((n + 1 : ℝ) * (sphereArea n) ^ (1 / (n : ℝ))) +noncomputable def fillingPower (n : ℕ) : ℝ := (n + 1 : ℝ) / (n : ℝ) + +theorem coefficient_optimal (n : ℕ) (hn : 2 ≤ n) : + ∃ T : IntegralCurrent (Euc (n + 1)) n, + CompactlySupported T.val ∧ IsCycle T.val ∧ 0 < mass T.val ∧ + ∀ S : IntegralCurrent (Euc (n + 1)) (n + 1), + CompactlySupported S.val → boundarySucc S.val = T.val → + fillingCoefficient n * (mass T.val) ^ fillingPower n ≤ mass S.val := by + sorry + +end SharpIntegralFillings + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FillingCoefficient.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SharpIntegralFillings.coefficient_optimal` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/filling-coefficient/solution/closure.txt b/tasks/filling-coefficient/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e19c15b21a8971b9e572bf4d415da2e23939ba30 --- /dev/null +++ b/tasks/filling-coefficient/solution/closure.txt @@ -0,0 +1,112 @@ +OAI.Geometry.IntegralFillings.Charts.ChainRule +OAI.Geometry.IntegralFillings.Charts.ChangeVariables +OAI.Geometry.IntegralFillings.Charts.ContainingCharts +OAI.Geometry.IntegralFillings.Charts.Control +OAI.Geometry.IntegralFillings.Charts.CurrentAxioms +OAI.Geometry.IntegralFillings.Charts.CurrentContinuity +OAI.Geometry.IntegralFillings.Charts.DensityPush +OAI.Geometry.IntegralFillings.Charts.Differentiability +OAI.Geometry.IntegralFillings.Charts.DomainRestriction +OAI.Geometry.IntegralFillings.Charts.ExactMass +OAI.Geometry.IntegralFillings.Charts.Extensions +OAI.Geometry.IntegralFillings.Charts.ExtensionsLimit +OAI.Geometry.IntegralFillings.Charts.HilbertMass +OAI.Geometry.IntegralFillings.Charts.ImageRestriction +OAI.Geometry.IntegralFillings.Charts.IntegerSeries +OAI.Geometry.IntegralFillings.Charts.Jacobian +OAI.Geometry.IntegralFillings.Charts.JacobianBound +OAI.Geometry.IntegralFillings.Charts.LinearMass +OAI.Geometry.IntegralFillings.Charts.MeasurePartition +OAI.Geometry.IntegralFillings.Charts.MultiplicityMass +OAI.Geometry.IntegralFillings.Charts.MultiplicityRestriction +OAI.Geometry.IntegralFillings.Charts.Orientation +OAI.Geometry.IntegralFillings.Charts.OverlapSum +OAI.Geometry.IntegralFillings.Charts.Postcompose +OAI.Geometry.IntegralFillings.Charts.Quadratic +OAI.Geometry.IntegralFillings.Charts.RectifiableMass +OAI.Geometry.IntegralFillings.Charts.Reparametrization +OAI.Geometry.IntegralFillings.Charts.Scalar +OAI.Geometry.IntegralFillings.Charts.ScalarPieces +OAI.Geometry.IntegralFillings.Charts.StraightPieces +OAI.Geometry.IntegralFillings.Charts.Straightening +OAI.Geometry.IntegralFillings.Charts.Transitions +OAI.Geometry.IntegralFillings.Currents.ActionLimits +OAI.Geometry.IntegralFillings.Currents.ActionSeries +OAI.Geometry.IntegralFillings.Currents.Addition +OAI.Geometry.IntegralFillings.Currents.Basic +OAI.Geometry.IntegralFillings.Currents.BorelAction +OAI.Geometry.IntegralFillings.Currents.BoundaryMass +OAI.Geometry.IntegralFillings.Currents.CanonicalMass +OAI.Geometry.IntegralFillings.Currents.ChartSums +OAI.Geometry.IntegralFillings.Currents.ComponentMass +OAI.Geometry.IntegralFillings.Currents.Composition +OAI.Geometry.IntegralFillings.Currents.Contraction +OAI.Geometry.IntegralFillings.Currents.CountableTests +OAI.Geometry.IntegralFillings.Currents.DenseTests +OAI.Geometry.IntegralFillings.Currents.DisjointUnions +OAI.Geometry.IntegralFillings.Currents.IntegralPush +OAI.Geometry.IntegralFillings.Currents.LevelLocality +OAI.Geometry.IntegralFillings.Currents.MassBounds +OAI.Geometry.IntegralFillings.Currents.MassTests +OAI.Geometry.IntegralFillings.Currents.Multilinear +OAI.Geometry.IntegralFillings.Currents.Negation +OAI.Geometry.IntegralFillings.Currents.ProductRule +OAI.Geometry.IntegralFillings.Currents.PushBoundary +OAI.Geometry.IntegralFillings.Currents.Pushforward +OAI.Geometry.IntegralFillings.Currents.Restriction +OAI.Geometry.IntegralFillings.Currents.Summation +OAI.Geometry.IntegralFillings.Currents.TestBounds +OAI.Geometry.IntegralFillings.Currents.WeakClosure +OAI.Geometry.IntegralFillings.Currents.WeakCompactness +OAI.Geometry.IntegralFillings.Currents.WeakMass +OAI.Geometry.IntegralFillings.Currents.WeightedAction +OAI.Geometry.IntegralFillings.Differentiation.Centered +OAI.Geometry.IntegralFillings.Differentiation.CurveSpeed +OAI.Geometry.IntegralFillings.Differentiation.Degenerate +OAI.Geometry.IntegralFillings.Differentiation.Density +OAI.Geometry.IntegralFillings.Differentiation.Directional +OAI.Geometry.IntegralFillings.Differentiation.ErrorModulus +OAI.Geometry.IntegralFillings.Differentiation.FullRank +OAI.Geometry.IntegralFillings.Differentiation.HilbertCharts +OAI.Geometry.IntegralFillings.Differentiation.HilbertPartition +OAI.Geometry.IntegralFillings.Differentiation.LargePieces +OAI.Geometry.IntegralFillings.Differentiation.LocalBounds +OAI.Geometry.IntegralFillings.Differentiation.Parallelogram +OAI.Geometry.IntegralFillings.Differentiation.Partitions +OAI.Geometry.IntegralFillings.Differentiation.ScalarBound +OAI.Geometry.IntegralFillings.Differentiation.Seminorm +OAI.Geometry.IntegralFillings.Differentiation.TwoPoint +OAI.Geometry.IntegralFillings.Geometry.Comparison +OAI.Geometry.IntegralFillings.Geometry.Determinant +OAI.Geometry.IntegralFillings.Geometry.MatrixRows +OAI.Geometry.IntegralFillings.Geometry.Polarization +OAI.Geometry.IntegralFillings.Jacobian.ClosedForms +OAI.Geometry.IntegralFillings.Jacobian.Coordinates +OAI.Geometry.IntegralFillings.Jacobian.HeadEstimates +OAI.Geometry.IntegralFillings.Jacobian.Lipschitz +OAI.Geometry.IntegralFillings.Jacobian.Mixed +OAI.Geometry.IntegralFillings.Jacobian.Smoothing +OAI.Geometry.IntegralFillings.Jacobian.WeakLimits +OAI.Geometry.IntegralFillings.Main +OAI.Geometry.IntegralFillings.Model +OAI.Geometry.IntegralFillings.Optimality.BallBoundary +OAI.Geometry.IntegralFillings.Optimality.BallCoarea +OAI.Geometry.IntegralFillings.Optimality.BallCurrent +OAI.Geometry.IntegralFillings.Optimality.BallStokes +OAI.Geometry.IntegralFillings.Optimality.Calibration +OAI.Geometry.IntegralFillings.Optimality.GoodRadius +OAI.Geometry.IntegralFillings.Slicing.BoundaryTests +OAI.Geometry.IntegralFillings.Slicing.CoordinateChart +OAI.Geometry.IntegralFillings.Slicing.CoordinateCoarea +OAI.Geometry.IntegralFillings.Slicing.CoordinateDerivative +OAI.Geometry.IntegralFillings.Slicing.CoordinateIntegral +OAI.Geometry.IntegralFillings.Slicing.CycleCoarea +OAI.Geometry.IntegralFillings.Slicing.EuclideanSplit +OAI.Geometry.IntegralFillings.Slicing.GeneralCoarea +OAI.Geometry.IntegralFillings.Slicing.NormalRestriction +OAI.Geometry.IntegralFillings.Slicing.ProfileIntegral +OAI.Geometry.IntegralFillings.Slicing.Profiles +OAI.Geometry.IntegralFillings.Slicing.RectifiableCoarea +OAI.Geometry.IntegralFillings.Slicing.ScalarCoarea +OAI.Geometry.IntegralFillings.Slicing.SmoothCutoff +OAI.Geometry.IntegralFillings.Slicing.StripMass diff --git a/tasks/filling-coefficient/solution/reference.py b/tasks/filling-coefficient/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/filling-coefficient/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/filling-coefficient/solution/solve.sh b/tasks/filling-coefficient/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c65322959dd09c8cd2b2fa54cf5f9e0d016ec155 --- /dev/null +++ b/tasks/filling-coefficient/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FillingCoefficient, i.e. module OAI.Geometry.IntegralFillings.Main and the +# 112 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.IntegralFillings.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FillingCoefficient" diff --git a/tasks/filling-coefficient/task.toml b/tasks/filling-coefficient/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c67d3c1e9ae75dc34e147abd9ca9c12d9b2471d1 --- /dev/null +++ b/tasks/filling-coefficient/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/filling-coefficient" +version = "1.0.0" +description = "Prove FillingCoefficient (openai/math family 337: Cartan–Hadamard isoperimetry and CAT$(0)$ fillings) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FillingCoefficient.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FillingCoefficient" +family = "337" +family_title = "Cartan–Hadamard isoperimetry and CAT$(0)$ fillings" +subject = "Differential geometry" +theorems = ["OAI.SharpIntegralFillings.coefficient_optimal"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.IntegralFillings.Main" +reference_modules = 112 +reference_lean_bytes = 696670 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1115 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12327 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/filling-coefficient/tests/Challenge.lean b/tasks/filling-coefficient/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8453c2497c1278e5224b3e08cfced6debe018829 --- /dev/null +++ b/tasks/filling-coefficient/tests/Challenge.lean @@ -0,0 +1,130 @@ +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped Topology ENNReal NNReal + +namespace SharpIntegralFillings + +attribute [local instance] Classical.propDecidable + +universe u + +abbrev Euc (k : ℕ) := EuclideanSpace ℝ (Fin k) +abbrev Functional (X : Type u) (k : ℕ) := (X → ℝ) → (Fin k → X → ℝ) → ℝ + +section MetricCurrents + +variable {X : Type u} [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + +def BoundedLip (b : X → ℝ) : Prop := + (∃ K : ℝ≥0, LipschitzWith K b) ∧ ∃ M : ℝ, ∀ x, |b x| ≤ M + +def Admissible {k : ℕ} (b : X → ℝ) (π : Fin k → X → ℝ) : Prop := + BoundedLip b ∧ ∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i) + +def Controls {k : ℕ} (T : Functional X k) (μ : Measure X) : Prop := + ∀ (b : X → ℝ) (π : Fin k → X → ℝ), BoundedLip b → + (∀ i, LipschitzWith 1 (π i)) → + |T b π| ≤ ∫ x, |b x| ∂μ + +noncomputable def mass {k : ℕ} (T : Functional X k) : ℝ := + sInf {r : ℝ | ∃ μ : Measure X, + IsFiniteMeasure μ ∧ Controls T μ ∧ r = μ.real univ} + +structure IsMetricCurrent {k : ℕ} (T : Functional X k) : Prop where + offDomain : ∀ b π, ¬Admissible b π → T b π = 0 + linearFirst : ∀ b₁ b₂ π (a c : ℝ), BoundedLip b₁ → BoundedLip b₂ → + (∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i)) → + T (fun x => a * b₁ x + c * b₂ x) π = a * T b₁ π + c * T b₂ π + linearCoord : ∀ b π i f (a c : ℝ), Admissible b π → + (∃ K : ℝ≥0, LipschitzWith K f) → + T b (Function.update π i (fun x => a * π i x + c * f x)) = + a * T b π + c * T b (Function.update π i f) + sequentialContinuity : ∀ b π (πs : ℕ → Fin k → X → ℝ), BoundedLip b → + (∀ i, ∃ K : ℝ≥0, ∀ j, LipschitzWith K (πs j i)) → + (∀ i x, Tendsto (fun j => πs j i x) atTop (𝓝 (π i x))) → + Tendsto (fun j => T b (πs j)) atTop (𝓝 (T b π)) + locality : ∀ b π, Admissible b π → + (∃ (i : Fin k) (U : Set X) (c : ℝ), IsOpen U ∧ Function.support b ⊆ U ∧ + ∀ x ∈ U, π i x = c) → T b π = 0 + finiteMass : ∃ μ : Measure X, IsFiniteMeasure μ ∧ Controls T μ + +noncomputable def boundarySucc {k : ℕ} (T : Functional X (k + 1)) : Functional X k := + fun b π => if Admissible b π then T (fun _ => 1) (Matrix.vecCons b π) else 0 + +noncomputable def boundary : {k : ℕ} → Functional X k → Functional X (k - 1) + | 0, _ => fun _ _ => 0 + | _ + 1, T => boundarySucc T + +structure IntegerChart (X : Type u) [MetricSpace X] (k : ℕ) where + domain : Set (Euc k) + borel : MeasurableSet domain + bounded : Bornology.IsBounded domain + param : domain → X + bilipschitz : ∃ L U : ℝ≥0, LipschitzWith L param ∧ AntilipschitzWith U param + multiplicity : Euc k → ℤ + integrable : Integrable (fun z => (multiplicity z : ℝ)) (volume.restrict domain) + +namespace IntegerChart + +variable {k : ℕ} (C : IntegerChart X k) + +noncomputable def scalar (f : X → ℝ) (z : Euc k) : ℝ := + if hz : z ∈ C.domain then f (C.param ⟨z, hz⟩) else 0 + +noncomputable def jacobian (π : Fin k → X → ℝ) (z : Euc k) : ℝ := + Matrix.det (fun i j => + (fderivWithin ℝ (C.scalar (π i)) C.domain z) (EuclideanSpace.single j 1)) + +noncomputable def action : Functional X k := + fun b π => if Admissible b π then + ∫ z in C.domain, (C.multiplicity z : ℝ) * C.scalar b z * C.jacobian π z + else 0 + +def image : Set X := Set.range C.param + +end IntegerChart + +def IntegerRectifiable {k : ℕ} (T : Functional X k) : Prop := + ∃ C : ℕ → IntegerChart X k, + Pairwise (fun i j => Disjoint (C i).image (C j).image) ∧ + (∀ i, IsMetricCurrent (C i).action) ∧ + Summable (fun i => mass (C i).action) ∧ + ∀ b π, T b π = ∑' i, (C i).action b π + +def IsIntegral : (k : ℕ) → Functional X k → Prop + | 0, T => IsMetricCurrent T ∧ IntegerRectifiable T + | _ + 1, T => IsMetricCurrent T ∧ IntegerRectifiable T ∧ + IsMetricCurrent (boundarySucc T) ∧ IntegerRectifiable (boundarySucc T) + +abbrev IntegralCurrent (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + (k : ℕ) := { T : Functional X k // IsIntegral k T } + +def CompactlySupported {k : ℕ} (T : Functional X k) : Prop := + ∃ K : Set X, IsCompact K ∧ + ∀ b π, Admissible b π → (∀ x ∈ K, b x = 0) → T b π = 0 + +def IsCycle {k : ℕ} (T : Functional X k) : Prop := boundary T = fun _ _ => 0 + +end MetricCurrents + +noncomputable def omega (k : ℕ) : ℝ := + (volume (Metric.ball (0 : Euc k) 1)).toReal +noncomputable def sphereArea (n : ℕ) : ℝ := (n + 1 : ℝ) * omega (n + 1) +noncomputable def fillingCoefficient (n : ℕ) : ℝ := + 1 / ((n + 1 : ℝ) * (sphereArea n) ^ (1 / (n : ℝ))) +noncomputable def fillingPower (n : ℕ) : ℝ := (n + 1 : ℝ) / (n : ℝ) + +theorem coefficient_optimal (n : ℕ) (hn : 2 ≤ n) : + ∃ T : IntegralCurrent (Euc (n + 1)) n, + CompactlySupported T.val ∧ IsCycle T.val ∧ 0 < mass T.val ∧ + ∀ S : IntegralCurrent (Euc (n + 1)) (n + 1), + CompactlySupported S.val → boundarySucc S.val = T.val → + fillingCoefficient n * (mass T.val) ^ fillingPower n ≤ mass S.val := by + sorry + +end SharpIntegralFillings + +end OAI diff --git a/tasks/filling-coefficient/tests/grade.py b/tasks/filling-coefficient/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/filling-coefficient/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/filling-coefficient/tests/task.json b/tasks/filling-coefficient/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e582051cd184f2d9343b686cf4fa153424f4dd79 --- /dev/null +++ b/tasks/filling-coefficient/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FillingCoefficient", + "comparator": { + "theorem_names": [ + "OAI.SharpIntegralFillings.coefficient_optimal" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11427 +} \ No newline at end of file diff --git a/tasks/filling-coefficient/tests/test.sh b/tasks/filling-coefficient/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/filling-coefficient/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/finite-circle/environment/Dockerfile b/tasks/finite-circle/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/finite-circle/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/finite-circle/environment/fetch_mathlib.sh b/tasks/finite-circle/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/finite-circle/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/finite-circle/environment/lake-manifest.json b/tasks/finite-circle/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/finite-circle/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/finite-circle/environment/lakefile.lean b/tasks/finite-circle/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/finite-circle/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/finite-circle/environment/lean_setup.sh b/tasks/finite-circle/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/finite-circle/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/finite-circle/environment/pack_submission.py b/tasks/finite-circle/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/finite-circle/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/finite-circle/instruction.md b/tasks/finite-circle/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..329c58d4f77c7acf7f512a9fb445f18a6e6e4c97 --- /dev/null +++ b/tasks/finite-circle/instruction.md @@ -0,0 +1,279 @@ +# openai/math challenge `FiniteCircle` (family 099) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 099 of the release, *The sharp distortion of edit distance into $\ell_1$* +(Convex and metric geometry). The family as a whole: Determines the least distortion of embedding edit distance on words of length at most $d$ into real $\ell_1$: it is $\exp(\Theta(\sqrt{\log d\,\log\log d}))$. Insertions, deletions and substitutions have unit cost. The constants are uniform over all finite alphabets with at least two symbols, even when the alphabet grows with $d$; binary words already force the lower bound. + +The challenge is `FiniteCircle`, also at `/opt/openai-math/challenges/FiniteCircle.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace FiniteCircle + +open scoped BigOperators List + +universe u v + +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (u v : List α) (a : α) : EditStep (u ++ v) (u ++ a :: v) + | delete (u v : List α) (a : α) : EditStep (u ++ a :: v) (u ++ v) + | substitute (u v : List α) (a b : α) : EditStep (u ++ a :: v) (u ++ b :: v) + +inductive EditScript {α : Type u} : ℕ → List α → List α → Prop + | nil (x : List α) : EditScript 0 x x + | cons {n : ℕ} {x y z : List α} : + EditStep x y → EditScript n y z → EditScript (n + 1) x z + +noncomputable def editDistance {α : Type u} (x y : List α) : ℕ := + sInf {n : ℕ | EditScript n x y} + +noncomputable def lcs {α : Type u} (x y : List α) : ℕ := + sSup {n : ℕ | ∃ z : List α, z <+ x ∧ z <+ y ∧ z.length = n} + +noncomputable def deficit {α : Type u} (x y : List α) : ℕ := x.length - lcs x y + +abbrev Words (α : Type u) (d : ℕ) := {x : List α // x.length ≤ d} +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 + +noncomputable def distortion {α : Type u} {X : Type v} (word : X → List α) + (f : X → RealL1) : ℝ := + (sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ + r = ‖f x - f y‖ / (editDistance (word x) (word y) : ℝ)}) * + (sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ + r = (editDistance (word x) (word y) : ℝ) / ‖f x - f y‖}) + +noncomputable def optimalDistortion {α : Type u} {X : Type v} + (word : X → List α) : ℝ := + sInf {D | ∃ f : X → RealL1, Function.Injective f ∧ D = distortion word f} + +noncomputable def E (α : Type u) (d : ℕ) : ℝ := + optimalDistortion (fun x : Words α d => x.val) + +noncomputable def setDistortion (S : Set (List Bool)) : ℝ := + optimalDistortion (fun x : S => x.val) + +noncomputable def alphabetSupremum (d : ℕ) : ℝ := + sSup {r | ∃ A : ℕ, 2 ≤ A ∧ r = E (Fin A) d} + +noncomputable def exponentScale (d : ℕ) : ℝ := + Real.sqrt (Real.log d * Real.log (Real.log d)) + +def encode {α : Type u} {w : ℕ} (c : α → Fin w → Bool) (x : List α) : List Bool := + x.flatMap (fun a => List.ofFn (c a)) + +def interval {α : Type u} {w : ℕ} (c : α → Fin w → Bool) + (a : α) (s len : ℕ) : List Bool := + ((List.ofFn (c a)).drop s).take len + +def OffsetLocal {α : Type u} {w : ℕ} (δ : ℝ) (c : α → Fin w → Bool) : Prop := + ∀ a b : α, a ≠ b → ∀ s t : ℕ, + s + w / 8 ≤ w → t + w / 8 ≤ w → + (lcs (interval c a s (w / 8)) (interval c b t (w / 8)) : ℝ) ≤ + (1 - δ) * (w / 8 : ℕ) + +def indexSpan {w : ℕ} (is : List (Fin w)) : ℕ := + match is with + | [] => 0 + | i :: js => (js.getLastD i).val + 1 - i.val + +def AnchorLocal {α : Type u} {w : ℕ} (ε : ℝ) (c : α → Fin w → Bool) : Prop := + ∀ a b : α, ∀ is js : List (Fin w), + is.Pairwise (fun i j => i.val < j.val) → + js.Pairwise (fun i j => i.val < j.val) → + is.length = js.length → (w : ℝ) / 4 ≤ is.length → + (indexSpan is - is.length : ℕ) ≤ ε * w → + (indexSpan js - js.length : ℕ) ≤ ε * w → + (∀ ij ∈ is.zip js, c a ij.1 = c b ij.2) → + a = b ∧ ∃ i : Fin w, (i, i) ∈ is.zip js + +def SubstitutionBounds {α : Type u} [Fintype α] {w : ℕ} + (a C : ℝ) (c : α → Fin w → Bool) : Prop := + 0 < w ∧ (w : ℝ) ≤ C * Real.log (2 * Fintype.card α) ∧ + (∀ L : ℕ, ∀ x y : List α, x.length = L → y.length = L → + a * w * deficit x y ≤ (deficit (encode c x) (encode c y) : ℝ) ∧ + deficit (encode c x) (encode c y) ≤ w * deficit x y) ∧ + (∀ x y : List α, editDistance (encode c x) (encode c y) ≤ w * editDistance x y) + +def TwoCodes (a C δ ε : ℝ) : Prop := + ∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → + (∃ (w : ℕ) (c : α → Fin w → Bool), + SubstitutionBounds a C c ∧ OffsetLocal δ c) ∧ + (∃ (w : ℕ) (c : α → Fin w → Bool), + SubstitutionBounds a C c ∧ AnchorLocal ε c) + +def period (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : ℕ := ∏ k : Fin h, p l k + +def circleSize (h : ℕ) (p : ℕ → ℕ → ℕ) : ℕ := + 2 * ∏ l : Fin h, period h p (l.val + 1) + +def MaskPrimes (h : ℕ) (p : ℕ → ℕ → ℕ) : Prop := + (∀ l k : Fin h, Nat.Prime (p (l.val + 1) k)) ∧ + Function.Injective (fun lk : Fin h × Fin h => p (lk.1.val + 1) lk.2) ∧ + ∀ l k : Fin h, h ^ 3 ≤ p (l.val + 1) k ∧ p (l.val + 1) k ≤ 2 * h ^ 3 + +def ExcludedPrimes (m : ℕ) (p : ℕ → ℕ → ℕ) : Prop := + (∀ l k : Fin m, Nat.Prime (p (l.val + 1) k)) ∧ + Function.Injective (fun lk : Fin m × Fin m => p (lk.1.val + 1) lk.2) ∧ + ∀ l k : Fin m, m ^ 3 < p (l.val + 1) k ∧ p (l.val + 1) k ≤ m ^ 5 + +abbrev MaskTag (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) := Σ k : Fin h, Fin (p l k) + +def maskTags (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : List (MaskTag h p l) := + (List.ofFn fun k : Fin h => List.ofFn fun b : Fin (p l k) => Sigma.mk k b).flatten + +def MaskAlphabet (h : ℕ) (p : ℕ → ℕ → ℕ) : ℕ → Type + | 0 => Bool + | l + 1 => MaskTag h p (l + 1) × MaskAlphabet h p l + +instance maskAlphabetFintype (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : + Fintype (MaskAlphabet h p l) := by + induction l with + | zero => exact inferInstanceAs (Fintype Bool) + | succ l ih => exact @instFintypeProd _ _ inferInstance ih + +def MaskState (h : ℕ) (p : ℕ → ℕ → ℕ) (M : ℕ) : ℕ → Type + | 0 => ZMod M + | l + 1 => MaskTag h p (l + 1) → MaskState h p M l + +def shiftMaskState (h : ℕ) (p : ℕ → ℕ → ℕ) (M : ℕ) : + (l : ℕ) → MaskState h p M l → ZMod M → MaskState h p M l + | 0, v, θ => (show ZMod M from v) + θ + | l + 1, v, θ => fun j => shiftMaskState h p M l (v j) θ + +def maskGamma (h : ℕ) (p : ℕ → ℕ → ℕ) (M l a : ℕ) + (j : MaskTag h p l) : ZMod M := + (∑ k : Fin h, ((M / p l k * (a % p l k) : ℕ) : ZMod M)) + + ((j.2.val * (M / p l j.1) * (a % p l j.1) : ℕ) : ZMod M) + +def maskWord (h : ℕ) (p : ℕ → ℕ → ℕ) (R M : ℕ) : + (l : ℕ) → MaskState h p M l → List (MaskAlphabet h p l) + | 0, v => (List.range M).map (fun b => decide (((b : ZMod M) - (show ZMod M from v)).val < M / 2)) + | l + 1, v => (List.range (R * period h p (l + 1))).flatMap fun a => + (maskTags h p (l + 1)).flatMap fun j => + (maskWord h p R M l + (shiftMaskState h p M l (v j) (maskGamma h p M (l + 1) a j))).map + (fun x => (j, x)) + +def ExcludedAlphabet (m L : ℕ) : ℕ → Type + | 0 => Fin L × Bool + | l + 1 => Fin m × ExcludedAlphabet m L l + +instance excludedAlphabetFintype (m L l : ℕ) : Fintype (ExcludedAlphabet m L l) := by + induction l with + | zero => exact inferInstanceAs (Fintype (Fin L × Bool)) + | succ l ih => exact @instFintypeProd _ _ inferInstance ih + +def ExcludedState (m L : ℕ) : ℕ → Type + | 0 => ZMod L + | l + 1 => Fin m → ExcludedState m L l + +def shiftExcludedState (m L : ℕ) : + (l : ℕ) → ExcludedState m L l → ZMod L → ExcludedState m L l + | 0, v, θ => (show ZMod L from v) + θ + | l + 1, v, θ => fun i => shiftExcludedState m L l (v i) θ + +def excludedTranslation (m : ℕ) (p : ℕ → ℕ → ℕ) (L l s : ℕ) (i : Fin m) : + ZMod L := ∑ j ∈ Finset.univ.erase i, ((L / p l j * (s % p l j) : ℕ) : ZMod L) + +def excludedWord (m : ℕ) (p : ℕ → ℕ → ℕ) (R L : ℕ) : + (l : ℕ) → ExcludedState m L l → List (ExcludedAlphabet m L l) + | 0, v => List.ofFn fun b : Fin L => + (b, decide (((b.val : ZMod L) - (show ZMod L from v)).val < L / 2)) + | l + 1, v => (List.range (R * period m p (l + 1))).flatMap fun s => + (List.ofFn fun i : Fin m => + (excludedWord m p R L l + (shiftExcludedState m L l (v i) (excludedTranslation m p L (l + 1) s i))).map + (fun x => (i, x))).flatten + +def MaskWitness (a C δ lower : ℝ) (d : ℕ) : Prop := + ∃ h : ℕ, 2 ≤ h ∧ ∃ p : ℕ → ℕ → ℕ, MaskPrimes h p ∧ + ∃ (w : ℕ) (c : MaskAlphabet h p h → Fin w → Bool), + SubstitutionBounds a C c ∧ OffsetLocal δ c ∧ + ∃ n : ℕ, 0 < n ∧ n ≤ d ∧ + (∀ v : MaskState h p (circleSize h p) h, + (encode c (maskWord h p (h ^ (2 * h)) (circleSize h p) h v)).length = n) ∧ + Real.exp (lower * exponentScale d) ≤ setDistortion + (Set.range fun v : MaskState h p (circleSize h p) h => + encode c (maskWord h p (h ^ (2 * h)) (circleSize h p) h v)) + +def ExcludedWitness (a C ε lower : ℝ) (d : ℕ) : Prop := + ∃ m : ℕ, 2 ≤ m ∧ ∃ p : ℕ → ℕ → ℕ, ExcludedPrimes m p ∧ + ∃ (w : ℕ) (c : ExcludedAlphabet m (circleSize m p) m → Fin w → Bool), + SubstitutionBounds a C c ∧ AnchorLocal ε c ∧ + ∃ n : ℕ, 0 < n ∧ n ≤ d ∧ + (∀ v : ExcludedState m (circleSize m p) m, + (encode c (excludedWord m p (m ^ (2 * m)) (circleSize m p) m v)).length = n) ∧ + Real.exp (lower * exponentScale d) ≤ setDistortion + (Set.range fun v : ExcludedState m (circleSize m p) m => + encode c (excludedWord m p (m ^ (2 * m)) (circleSize m p) m v)) + +def UniformUpper (C : ℝ) (d₀ : ℕ) : Prop := + ∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → ∀ d : ℕ, d₀ ≤ d → + ∃ (M : ℕ) (F : Words α d → Fin M → ℝ), ∀ x y : Words α d, + (editDistance x.val y.val : ℝ) ≤ ∑ i, |F x i - F y i| ∧ + (∑ i, |F x i - F y i|) ≤ + Real.exp (C * exponentScale d) * editDistance x.val y.val + +def FullMain : Prop := + ∃ c C a Ccode δ ε : ℝ, ∃ d₀ : ℕ, + 0 < c ∧ 0 < C ∧ 0 < a ∧ 0 < Ccode ∧ 0 < δ ∧ 0 < ε ∧ + TwoCodes a Ccode δ ε ∧ UniformUpper C d₀ ∧ + (∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → ∀ d : ℕ, d₀ ≤ d → + Real.exp (c * exponentScale d) ≤ E α d ∧ + E α d ≤ Real.exp (C * exponentScale d)) ∧ + (∀ d : ℕ, d₀ ≤ d → + MaskWitness a Ccode δ c d ∧ ExcludedWitness a Ccode ε c d ∧ + Real.exp (c * exponentScale d) ≤ alphabetSupremum d ∧ + alphabetSupremum d ≤ Real.exp (C * exponentScale d)) + +end FiniteCircle + +theorem finiteCircle_fullMain : FiniteCircle.FullMain := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FiniteCircle.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.finiteCircle_fullMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/finite-circle/solution/closure.txt b/tasks/finite-circle/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bc1c3e64cf7d0573cba911cf0735c3168dd781ed --- /dev/null +++ b/tasks/finite-circle/solution/closure.txt @@ -0,0 +1,36 @@ +OAI.Combinatorics.FiniteCircle.AnchorRecovery +OAI.Combinatorics.FiniteCircle.BinaryDistortion +OAI.Combinatorics.FiniteCircle.BitCounting +OAI.Combinatorics.FiniteCircle.BlockMatching +OAI.Combinatorics.FiniteCircle.CircleWords +OAI.Combinatorics.FiniteCircle.Codes +OAI.Combinatorics.FiniteCircle.DeficitLower +OAI.Combinatorics.FiniteCircle.Distortion +OAI.Combinatorics.FiniteCircle.DyadicShifts +OAI.Combinatorics.FiniteCircle.Edit +OAI.Combinatorics.FiniteCircle.ExcludedDescent +OAI.Combinatorics.FiniteCircle.ExcludedSeparation +OAI.Combinatorics.FiniteCircle.Fourier +OAI.Combinatorics.FiniteCircle.HistogramEmbedding +OAI.Combinatorics.FiniteCircle.Histograms +OAI.Combinatorics.FiniteCircle.Lower +OAI.Combinatorics.FiniteCircle.Main +OAI.Combinatorics.FiniteCircle.MaskBranching +OAI.Combinatorics.FiniteCircle.MaskDescent +OAI.Combinatorics.FiniteCircle.MaskSeparation +OAI.Combinatorics.FiniteCircle.Matching +OAI.Combinatorics.FiniteCircle.Model +OAI.Combinatorics.FiniteCircle.OffsetRecovery +OAI.Combinatorics.FiniteCircle.Parameters +OAI.Combinatorics.FiniteCircle.Partitions +OAI.Combinatorics.FiniteCircle.PhaseCost +OAI.Combinatorics.FiniteCircle.Primes +OAI.Combinatorics.FiniteCircle.RandomCodes +OAI.Combinatorics.FiniteCircle.Separation +OAI.Combinatorics.FiniteCircle.TaggedRows +OAI.Combinatorics.FiniteCircle.Translations +OAI.Combinatorics.FiniteCircle.TreeBranching +OAI.Combinatorics.FiniteCircle.Upper +OAI.Combinatorics.FiniteCircle.UpperParameters +OAI.Combinatorics.FiniteCircle.WindowMatching +OAI.Combinatorics.FiniteCircle.Windows diff --git a/tasks/finite-circle/solution/reference.py b/tasks/finite-circle/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/finite-circle/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/finite-circle/solution/solve.sh b/tasks/finite-circle/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a2647e504bf3f4248a2f7ddc911125ccc99bea45 --- /dev/null +++ b/tasks/finite-circle/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FiniteCircle, i.e. module OAI.Combinatorics.FiniteCircle.Main and the +# 36 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.FiniteCircle.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FiniteCircle" diff --git a/tasks/finite-circle/task.toml b/tasks/finite-circle/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b8fa521ae7125e75e9151323742151bd22dfb561 --- /dev/null +++ b/tasks/finite-circle/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/finite-circle" +version = "1.0.0" +description = "Prove FiniteCircle (openai/math family 099: The sharp distortion of edit distance into $\\ell_1$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FiniteCircle.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FiniteCircle" +family = "099" +family_title = "The sharp distortion of edit distance into $\\ell_1$" +subject = "Convex and metric geometry" +theorems = ["OAI.finiteCircle_fullMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.FiniteCircle.Main" +reference_modules = 36 +reference_lean_bytes = 458380 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 902 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12112 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/finite-circle/tests/Challenge.lean b/tasks/finite-circle/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..01a33d656d49a0242d822910f2debb08608576ca --- /dev/null +++ b/tasks/finite-circle/tests/Challenge.lean @@ -0,0 +1,228 @@ +import Mathlib + +namespace OAI + +namespace FiniteCircle + +open scoped BigOperators List + +universe u v + +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (u v : List α) (a : α) : EditStep (u ++ v) (u ++ a :: v) + | delete (u v : List α) (a : α) : EditStep (u ++ a :: v) (u ++ v) + | substitute (u v : List α) (a b : α) : EditStep (u ++ a :: v) (u ++ b :: v) + +inductive EditScript {α : Type u} : ℕ → List α → List α → Prop + | nil (x : List α) : EditScript 0 x x + | cons {n : ℕ} {x y z : List α} : + EditStep x y → EditScript n y z → EditScript (n + 1) x z + +noncomputable def editDistance {α : Type u} (x y : List α) : ℕ := + sInf {n : ℕ | EditScript n x y} + +noncomputable def lcs {α : Type u} (x y : List α) : ℕ := + sSup {n : ℕ | ∃ z : List α, z <+ x ∧ z <+ y ∧ z.length = n} + +noncomputable def deficit {α : Type u} (x y : List α) : ℕ := x.length - lcs x y + +abbrev Words (α : Type u) (d : ℕ) := {x : List α // x.length ≤ d} +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 + +noncomputable def distortion {α : Type u} {X : Type v} (word : X → List α) + (f : X → RealL1) : ℝ := + (sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ + r = ‖f x - f y‖ / (editDistance (word x) (word y) : ℝ)}) * + (sSup {r : ℝ | ∃ x y : X, x ≠ y ∧ + r = (editDistance (word x) (word y) : ℝ) / ‖f x - f y‖}) + +noncomputable def optimalDistortion {α : Type u} {X : Type v} + (word : X → List α) : ℝ := + sInf {D | ∃ f : X → RealL1, Function.Injective f ∧ D = distortion word f} + +noncomputable def E (α : Type u) (d : ℕ) : ℝ := + optimalDistortion (fun x : Words α d => x.val) + +noncomputable def setDistortion (S : Set (List Bool)) : ℝ := + optimalDistortion (fun x : S => x.val) + +noncomputable def alphabetSupremum (d : ℕ) : ℝ := + sSup {r | ∃ A : ℕ, 2 ≤ A ∧ r = E (Fin A) d} + +noncomputable def exponentScale (d : ℕ) : ℝ := + Real.sqrt (Real.log d * Real.log (Real.log d)) + +def encode {α : Type u} {w : ℕ} (c : α → Fin w → Bool) (x : List α) : List Bool := + x.flatMap (fun a => List.ofFn (c a)) + +def interval {α : Type u} {w : ℕ} (c : α → Fin w → Bool) + (a : α) (s len : ℕ) : List Bool := + ((List.ofFn (c a)).drop s).take len + +def OffsetLocal {α : Type u} {w : ℕ} (δ : ℝ) (c : α → Fin w → Bool) : Prop := + ∀ a b : α, a ≠ b → ∀ s t : ℕ, + s + w / 8 ≤ w → t + w / 8 ≤ w → + (lcs (interval c a s (w / 8)) (interval c b t (w / 8)) : ℝ) ≤ + (1 - δ) * (w / 8 : ℕ) + +def indexSpan {w : ℕ} (is : List (Fin w)) : ℕ := + match is with + | [] => 0 + | i :: js => (js.getLastD i).val + 1 - i.val + +def AnchorLocal {α : Type u} {w : ℕ} (ε : ℝ) (c : α → Fin w → Bool) : Prop := + ∀ a b : α, ∀ is js : List (Fin w), + is.Pairwise (fun i j => i.val < j.val) → + js.Pairwise (fun i j => i.val < j.val) → + is.length = js.length → (w : ℝ) / 4 ≤ is.length → + (indexSpan is - is.length : ℕ) ≤ ε * w → + (indexSpan js - js.length : ℕ) ≤ ε * w → + (∀ ij ∈ is.zip js, c a ij.1 = c b ij.2) → + a = b ∧ ∃ i : Fin w, (i, i) ∈ is.zip js + +def SubstitutionBounds {α : Type u} [Fintype α] {w : ℕ} + (a C : ℝ) (c : α → Fin w → Bool) : Prop := + 0 < w ∧ (w : ℝ) ≤ C * Real.log (2 * Fintype.card α) ∧ + (∀ L : ℕ, ∀ x y : List α, x.length = L → y.length = L → + a * w * deficit x y ≤ (deficit (encode c x) (encode c y) : ℝ) ∧ + deficit (encode c x) (encode c y) ≤ w * deficit x y) ∧ + (∀ x y : List α, editDistance (encode c x) (encode c y) ≤ w * editDistance x y) + +def TwoCodes (a C δ ε : ℝ) : Prop := + ∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → + (∃ (w : ℕ) (c : α → Fin w → Bool), + SubstitutionBounds a C c ∧ OffsetLocal δ c) ∧ + (∃ (w : ℕ) (c : α → Fin w → Bool), + SubstitutionBounds a C c ∧ AnchorLocal ε c) + +def period (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : ℕ := ∏ k : Fin h, p l k + +def circleSize (h : ℕ) (p : ℕ → ℕ → ℕ) : ℕ := + 2 * ∏ l : Fin h, period h p (l.val + 1) + +def MaskPrimes (h : ℕ) (p : ℕ → ℕ → ℕ) : Prop := + (∀ l k : Fin h, Nat.Prime (p (l.val + 1) k)) ∧ + Function.Injective (fun lk : Fin h × Fin h => p (lk.1.val + 1) lk.2) ∧ + ∀ l k : Fin h, h ^ 3 ≤ p (l.val + 1) k ∧ p (l.val + 1) k ≤ 2 * h ^ 3 + +def ExcludedPrimes (m : ℕ) (p : ℕ → ℕ → ℕ) : Prop := + (∀ l k : Fin m, Nat.Prime (p (l.val + 1) k)) ∧ + Function.Injective (fun lk : Fin m × Fin m => p (lk.1.val + 1) lk.2) ∧ + ∀ l k : Fin m, m ^ 3 < p (l.val + 1) k ∧ p (l.val + 1) k ≤ m ^ 5 + +abbrev MaskTag (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) := Σ k : Fin h, Fin (p l k) + +def maskTags (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : List (MaskTag h p l) := + (List.ofFn fun k : Fin h => List.ofFn fun b : Fin (p l k) => Sigma.mk k b).flatten + +def MaskAlphabet (h : ℕ) (p : ℕ → ℕ → ℕ) : ℕ → Type + | 0 => Bool + | l + 1 => MaskTag h p (l + 1) × MaskAlphabet h p l + +instance maskAlphabetFintype (h : ℕ) (p : ℕ → ℕ → ℕ) (l : ℕ) : + Fintype (MaskAlphabet h p l) := by + induction l with + | zero => exact inferInstanceAs (Fintype Bool) + | succ l ih => exact @instFintypeProd _ _ inferInstance ih + +def MaskState (h : ℕ) (p : ℕ → ℕ → ℕ) (M : ℕ) : ℕ → Type + | 0 => ZMod M + | l + 1 => MaskTag h p (l + 1) → MaskState h p M l + +def shiftMaskState (h : ℕ) (p : ℕ → ℕ → ℕ) (M : ℕ) : + (l : ℕ) → MaskState h p M l → ZMod M → MaskState h p M l + | 0, v, θ => (show ZMod M from v) + θ + | l + 1, v, θ => fun j => shiftMaskState h p M l (v j) θ + +def maskGamma (h : ℕ) (p : ℕ → ℕ → ℕ) (M l a : ℕ) + (j : MaskTag h p l) : ZMod M := + (∑ k : Fin h, ((M / p l k * (a % p l k) : ℕ) : ZMod M)) + + ((j.2.val * (M / p l j.1) * (a % p l j.1) : ℕ) : ZMod M) + +def maskWord (h : ℕ) (p : ℕ → ℕ → ℕ) (R M : ℕ) : + (l : ℕ) → MaskState h p M l → List (MaskAlphabet h p l) + | 0, v => (List.range M).map (fun b => decide (((b : ZMod M) - (show ZMod M from v)).val < M / 2)) + | l + 1, v => (List.range (R * period h p (l + 1))).flatMap fun a => + (maskTags h p (l + 1)).flatMap fun j => + (maskWord h p R M l + (shiftMaskState h p M l (v j) (maskGamma h p M (l + 1) a j))).map + (fun x => (j, x)) + +def ExcludedAlphabet (m L : ℕ) : ℕ → Type + | 0 => Fin L × Bool + | l + 1 => Fin m × ExcludedAlphabet m L l + +instance excludedAlphabetFintype (m L l : ℕ) : Fintype (ExcludedAlphabet m L l) := by + induction l with + | zero => exact inferInstanceAs (Fintype (Fin L × Bool)) + | succ l ih => exact @instFintypeProd _ _ inferInstance ih + +def ExcludedState (m L : ℕ) : ℕ → Type + | 0 => ZMod L + | l + 1 => Fin m → ExcludedState m L l + +def shiftExcludedState (m L : ℕ) : + (l : ℕ) → ExcludedState m L l → ZMod L → ExcludedState m L l + | 0, v, θ => (show ZMod L from v) + θ + | l + 1, v, θ => fun i => shiftExcludedState m L l (v i) θ + +def excludedTranslation (m : ℕ) (p : ℕ → ℕ → ℕ) (L l s : ℕ) (i : Fin m) : + ZMod L := ∑ j ∈ Finset.univ.erase i, ((L / p l j * (s % p l j) : ℕ) : ZMod L) + +def excludedWord (m : ℕ) (p : ℕ → ℕ → ℕ) (R L : ℕ) : + (l : ℕ) → ExcludedState m L l → List (ExcludedAlphabet m L l) + | 0, v => List.ofFn fun b : Fin L => + (b, decide (((b.val : ZMod L) - (show ZMod L from v)).val < L / 2)) + | l + 1, v => (List.range (R * period m p (l + 1))).flatMap fun s => + (List.ofFn fun i : Fin m => + (excludedWord m p R L l + (shiftExcludedState m L l (v i) (excludedTranslation m p L (l + 1) s i))).map + (fun x => (i, x))).flatten + +def MaskWitness (a C δ lower : ℝ) (d : ℕ) : Prop := + ∃ h : ℕ, 2 ≤ h ∧ ∃ p : ℕ → ℕ → ℕ, MaskPrimes h p ∧ + ∃ (w : ℕ) (c : MaskAlphabet h p h → Fin w → Bool), + SubstitutionBounds a C c ∧ OffsetLocal δ c ∧ + ∃ n : ℕ, 0 < n ∧ n ≤ d ∧ + (∀ v : MaskState h p (circleSize h p) h, + (encode c (maskWord h p (h ^ (2 * h)) (circleSize h p) h v)).length = n) ∧ + Real.exp (lower * exponentScale d) ≤ setDistortion + (Set.range fun v : MaskState h p (circleSize h p) h => + encode c (maskWord h p (h ^ (2 * h)) (circleSize h p) h v)) + +def ExcludedWitness (a C ε lower : ℝ) (d : ℕ) : Prop := + ∃ m : ℕ, 2 ≤ m ∧ ∃ p : ℕ → ℕ → ℕ, ExcludedPrimes m p ∧ + ∃ (w : ℕ) (c : ExcludedAlphabet m (circleSize m p) m → Fin w → Bool), + SubstitutionBounds a C c ∧ AnchorLocal ε c ∧ + ∃ n : ℕ, 0 < n ∧ n ≤ d ∧ + (∀ v : ExcludedState m (circleSize m p) m, + (encode c (excludedWord m p (m ^ (2 * m)) (circleSize m p) m v)).length = n) ∧ + Real.exp (lower * exponentScale d) ≤ setDistortion + (Set.range fun v : ExcludedState m (circleSize m p) m => + encode c (excludedWord m p (m ^ (2 * m)) (circleSize m p) m v)) + +def UniformUpper (C : ℝ) (d₀ : ℕ) : Prop := + ∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → ∀ d : ℕ, d₀ ≤ d → + ∃ (M : ℕ) (F : Words α d → Fin M → ℝ), ∀ x y : Words α d, + (editDistance x.val y.val : ℝ) ≤ ∑ i, |F x i - F y i| ∧ + (∑ i, |F x i - F y i|) ≤ + Real.exp (C * exponentScale d) * editDistance x.val y.val + +def FullMain : Prop := + ∃ c C a Ccode δ ε : ℝ, ∃ d₀ : ℕ, + 0 < c ∧ 0 < C ∧ 0 < a ∧ 0 < Ccode ∧ 0 < δ ∧ 0 < ε ∧ + TwoCodes a Ccode δ ε ∧ UniformUpper C d₀ ∧ + (∀ (α : Type) [Fintype α], 2 ≤ Fintype.card α → ∀ d : ℕ, d₀ ≤ d → + Real.exp (c * exponentScale d) ≤ E α d ∧ + E α d ≤ Real.exp (C * exponentScale d)) ∧ + (∀ d : ℕ, d₀ ≤ d → + MaskWitness a Ccode δ c d ∧ ExcludedWitness a Ccode ε c d ∧ + Real.exp (c * exponentScale d) ≤ alphabetSupremum d ∧ + alphabetSupremum d ≤ Real.exp (C * exponentScale d)) + +end FiniteCircle + +theorem finiteCircle_fullMain : FiniteCircle.FullMain := by + sorry + +end OAI diff --git a/tasks/finite-circle/tests/grade.py b/tasks/finite-circle/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/finite-circle/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/finite-circle/tests/task.json b/tasks/finite-circle/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d241ac84bafd62c514f51cb48c338bbe91019ec3 --- /dev/null +++ b/tasks/finite-circle/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FiniteCircle", + "comparator": { + "theorem_names": [ + "OAI.finiteCircle_fullMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11212 +} \ No newline at end of file diff --git a/tasks/finite-circle/tests/test.sh b/tasks/finite-circle/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/finite-circle/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/finite-congruence-graph/environment/Dockerfile b/tasks/finite-congruence-graph/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/finite-congruence-graph/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/finite-congruence-graph/environment/fetch_mathlib.sh b/tasks/finite-congruence-graph/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/finite-congruence-graph/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/finite-congruence-graph/environment/lake-manifest.json b/tasks/finite-congruence-graph/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/finite-congruence-graph/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/finite-congruence-graph/environment/lakefile.lean b/tasks/finite-congruence-graph/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/finite-congruence-graph/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/finite-congruence-graph/environment/lean_setup.sh b/tasks/finite-congruence-graph/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/finite-congruence-graph/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/finite-congruence-graph/environment/pack_submission.py b/tasks/finite-congruence-graph/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/finite-congruence-graph/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/finite-congruence-graph/instruction.md b/tasks/finite-congruence-graph/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1642298fed83af8bce033bc6f3b1ed746e87b5ba --- /dev/null +++ b/tasks/finite-congruence-graph/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `FiniteCongruenceGraph` (family 206) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 206 of the release, *Finite lattice representation: counterexamples and undecidability* +(Algebra). The family as a whole: Some finite lattices are not congruence lattices of any finite algebra, answering the finite lattice representation problem negatively. Moreover, no algorithm decides whether a finite lattice has such a representation, or whether it is a full subgroup interval of a finite group. + +The challenge is `FiniteCongruenceGraph`, also at `/opt/openai-math/challenges/FiniteCongruenceGraph.lean`: + +```lean +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Data.Fintype.Defs +import Mathlib.Data.Setoid.Basic +import Mathlib.Order.Hom.Basic + +namespace OAI + +namespace FiniteCongruence + +structure Algebra (Carrier : Type) where + numOps : ℕ + arity : Fin numOps → ℕ + op : (index : Fin numOps) → (Fin (arity index) → Carrier) → Carrier + +def Compatible {Carrier : Type} (alg : Algebra Carrier) (rel : Setoid Carrier) : Prop := + ∀ (index : Fin alg.numOps) (left right : Fin (alg.arity index) → Carrier), + (∀ coord, rel (left coord) (right coord)) → rel (alg.op index left) (alg.op index right) + +def Congruence {Carrier : Type} (alg : Algebra Carrier) := + {rel : Setoid Carrier // Compatible alg rel} + +instance {Carrier : Type} (alg : Algebra Carrier) : PartialOrder (Congruence alg) := + inferInstanceAs (PartialOrder {rel : Setoid Carrier // Compatible alg rel}) + +def Representable (Lat : Type) [PartialOrder Lat] : Prop := + ∃ size : ℕ, 0 < size ∧ ∃ alg : Algebra (Fin size), Nonempty (Lat ≃o Congruence alg) + +def Admissible {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (placement : Carrier → Carrier) : Prop := + ∀ left right, color (placement left) (placement right) ≤ color left right + +def Marked {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (seeds : Finset (Carrier × Carrier)) (left right : Carrier) : Prop := + ∃ placement : Carrier → Carrier, Admissible color placement ∧ + ∃ edge ∈ seeds, placement edge.1 = left ∧ placement edge.2 = right + +def Connected {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (seeds : Finset (Carrier × Carrier)) (left right : Carrier) : Prop := + Relation.EqvGen (Marked color seeds) left right + +def IsGraphWitness {Lat Carrier : Type} [Lattice Lat] [OrderBot Lat] + (color : Carrier → Carrier → Lat) : Prop := + (∀ left right, color left right = color right left) ∧ + (∀ left right, color left right = ⊥ ↔ left = right) ∧ + (∀ left right middle, color left right ≤ color left middle ⊔ color middle right) ∧ + (∀ lower upper : Lat, ¬ lower ≤ upper → + ∃ left right, color left right ≤ lower ∧ ¬ color left right ≤ upper) ∧ + (∀ seeds : Finset (Carrier × Carrier), seeds.Nonempty → ∀ left right, + color left right ≤ seeds.sup (fun edge => color edge.1 edge.2) → + Connected color seeds left right) + +def HasGraphWitness (Lat : Type) [Lattice Lat] [OrderBot Lat] : Prop := + ∃ size : ℕ, 0 < size ∧ ∃ color : Fin size → Fin size → Lat, IsGraphWitness color + +/-- A finite lattice is representable as the full congruence lattice of a nonempty finite +algebra exactly when it has a finite nonempty colored-graph witness. -/ +theorem graph_criterion (Lat : Type) [Fintype Lat] [Lattice Lat] [OrderBot Lat] : + Representable Lat ↔ HasGraphWitness Lat := by + sorry + +end FiniteCongruence + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FiniteCongruenceGraph.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FiniteCongruence.graph_criterion` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/finite-congruence-graph/solution/closure.txt b/tasks/finite-congruence-graph/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..86c280e35f716ec34eab99da17ba5860ed66bd60 --- /dev/null +++ b/tasks/finite-congruence-graph/solution/closure.txt @@ -0,0 +1,2 @@ +OAI.Algebra.Universal.Congruence +OAI.Algebra.Universal.GraphCriterion diff --git a/tasks/finite-congruence-graph/solution/reference.py b/tasks/finite-congruence-graph/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/finite-congruence-graph/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/finite-congruence-graph/solution/solve.sh b/tasks/finite-congruence-graph/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bad1d43516d884b82bd0b7943e898c67d59dd98a --- /dev/null +++ b/tasks/finite-congruence-graph/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FiniteCongruenceGraph, i.e. module OAI.Algebra.Universal.GraphCriterion and the +# 2 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.Universal.GraphCriterion /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FiniteCongruenceGraph" diff --git a/tasks/finite-congruence-graph/task.toml b/tasks/finite-congruence-graph/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b7724ee54b90cc460d1026e365c87ce445c580c3 --- /dev/null +++ b/tasks/finite-congruence-graph/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/finite-congruence-graph" +version = "1.0.0" +description = "Prove FiniteCongruenceGraph (openai/math family 206: Finite lattice representation: counterexamples and undecidability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FiniteCongruenceGraph.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FiniteCongruenceGraph" +family = "206" +family_title = "Finite lattice representation: counterexamples and undecidability" +subject = "Algebra" +theorems = ["OAI.FiniteCongruence.graph_criterion"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.Universal.GraphCriterion" +reference_modules = 2 +reference_lean_bytes = 22706 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 466 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11720 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/finite-congruence-graph/tests/Challenge.lean b/tasks/finite-congruence-graph/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..99c6b56b02e6c1ee007a0b87352eddff08d5edd8 --- /dev/null +++ b/tasks/finite-congruence-graph/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib.Data.Finset.Lattice.Fold +import Mathlib.Data.Fintype.Defs +import Mathlib.Data.Setoid.Basic +import Mathlib.Order.Hom.Basic + +namespace OAI + +namespace FiniteCongruence + +structure Algebra (Carrier : Type) where + numOps : ℕ + arity : Fin numOps → ℕ + op : (index : Fin numOps) → (Fin (arity index) → Carrier) → Carrier + +def Compatible {Carrier : Type} (alg : Algebra Carrier) (rel : Setoid Carrier) : Prop := + ∀ (index : Fin alg.numOps) (left right : Fin (alg.arity index) → Carrier), + (∀ coord, rel (left coord) (right coord)) → rel (alg.op index left) (alg.op index right) + +def Congruence {Carrier : Type} (alg : Algebra Carrier) := + {rel : Setoid Carrier // Compatible alg rel} + +instance {Carrier : Type} (alg : Algebra Carrier) : PartialOrder (Congruence alg) := + inferInstanceAs (PartialOrder {rel : Setoid Carrier // Compatible alg rel}) + +def Representable (Lat : Type) [PartialOrder Lat] : Prop := + ∃ size : ℕ, 0 < size ∧ ∃ alg : Algebra (Fin size), Nonempty (Lat ≃o Congruence alg) + +def Admissible {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (placement : Carrier → Carrier) : Prop := + ∀ left right, color (placement left) (placement right) ≤ color left right + +def Marked {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (seeds : Finset (Carrier × Carrier)) (left right : Carrier) : Prop := + ∃ placement : Carrier → Carrier, Admissible color placement ∧ + ∃ edge ∈ seeds, placement edge.1 = left ∧ placement edge.2 = right + +def Connected {Lat Carrier : Type} [LE Lat] (color : Carrier → Carrier → Lat) + (seeds : Finset (Carrier × Carrier)) (left right : Carrier) : Prop := + Relation.EqvGen (Marked color seeds) left right + +def IsGraphWitness {Lat Carrier : Type} [Lattice Lat] [OrderBot Lat] + (color : Carrier → Carrier → Lat) : Prop := + (∀ left right, color left right = color right left) ∧ + (∀ left right, color left right = ⊥ ↔ left = right) ∧ + (∀ left right middle, color left right ≤ color left middle ⊔ color middle right) ∧ + (∀ lower upper : Lat, ¬ lower ≤ upper → + ∃ left right, color left right ≤ lower ∧ ¬ color left right ≤ upper) ∧ + (∀ seeds : Finset (Carrier × Carrier), seeds.Nonempty → ∀ left right, + color left right ≤ seeds.sup (fun edge => color edge.1 edge.2) → + Connected color seeds left right) + +def HasGraphWitness (Lat : Type) [Lattice Lat] [OrderBot Lat] : Prop := + ∃ size : ℕ, 0 < size ∧ ∃ color : Fin size → Fin size → Lat, IsGraphWitness color + +/-- A finite lattice is representable as the full congruence lattice of a nonempty finite +algebra exactly when it has a finite nonempty colored-graph witness. -/ +theorem graph_criterion (Lat : Type) [Fintype Lat] [Lattice Lat] [OrderBot Lat] : + Representable Lat ↔ HasGraphWitness Lat := by + sorry + +end FiniteCongruence + +end OAI diff --git a/tasks/finite-congruence-graph/tests/grade.py b/tasks/finite-congruence-graph/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/finite-congruence-graph/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/finite-congruence-graph/tests/task.json b/tasks/finite-congruence-graph/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4cf89e94856c5c31e25ccbd0a3e97d7af66859d0 --- /dev/null +++ b/tasks/finite-congruence-graph/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FiniteCongruenceGraph", + "comparator": { + "theorem_names": [ + "OAI.FiniteCongruence.graph_criterion" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10820 +} \ No newline at end of file diff --git a/tasks/finite-congruence-graph/tests/test.sh b/tasks/finite-congruence-graph/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/finite-congruence-graph/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/finite-entropy-separation/environment/Dockerfile b/tasks/finite-entropy-separation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/finite-entropy-separation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/finite-entropy-separation/environment/fetch_mathlib.sh b/tasks/finite-entropy-separation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/finite-entropy-separation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/finite-entropy-separation/environment/lake-manifest.json b/tasks/finite-entropy-separation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/finite-entropy-separation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/finite-entropy-separation/environment/lakefile.lean b/tasks/finite-entropy-separation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/finite-entropy-separation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/finite-entropy-separation/environment/lean_setup.sh b/tasks/finite-entropy-separation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/finite-entropy-separation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/finite-entropy-separation/environment/pack_submission.py b/tasks/finite-entropy-separation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/finite-entropy-separation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/finite-entropy-separation/instruction.md b/tasks/finite-entropy-separation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e5427c4acf005a65d42901a24a8bcf75494425b6 --- /dev/null +++ b/tasks/finite-entropy-separation/instruction.md @@ -0,0 +1,176 @@ +# openai/math challenge `FiniteEntropySeparation` (family 298) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 298 of the release, *A counterexample to Voiculescu’s free-entropy equality conjecture* +(Operator algebras). The family as a whole: Constructs a bounded self-adjoint tuple in a tracial von Neumann algebra whose microstates and nonmicrostates free entropies satisfy $-\infty<\chi<\chi^*<\infty$. This answers Voiculescu’s finite-entropy equality question negatively: the matrix-approximation and free-Fisher-information definitions differ even when both are finite. + +The challenge is `FiniteEntropySeparation`, also at `/opt/openai-math/challenges/FiniteEntropySeparation.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped ENNReal NNReal ComplexConjugate +open MeasureTheory Filter + +namespace FiniteEntropySeparation + +variable {H : Type} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +structure TracialVector (M : VonNeumannAlgebra H) where + vacuum : H + norm_vacuum : ‖vacuum‖ = 1 + tracial : ∀ A ∈ M, ∀ B ∈ M, + inner ℂ vacuum ((A * B) vacuum) = inner ℂ vacuum ((B * A) vacuum) + separating : ∀ A ∈ M, A vacuum = 0 → A = 0 + +def trace {M : VonNeumannAlgebra H} (τ : TracialVector M) (A : H →L[ℂ] H) : ℂ := + inner ℂ τ.vacuum (A τ.vacuum) + +def wordEval {n : ℕ} (X : Fin n → H →L[ℂ] H) (w : List (Fin n)) : H →L[ℂ] H := + (w.map X).prod + +def wordMoment {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (w : List (Fin n)) : ℂ := trace τ (wordEval X w) + +def FreeSubalgebras {ι : Type} {M : VonNeumannAlgebra H} (τ : TracialVector M) + (A : ι → Subalgebra ℂ (H →L[ℂ] H)) : Prop := + ∀ (k : ℕ), 0 < k → ∀ (j : Fin k → ι) (a : Fin k → H →L[ℂ] H), + (∀ r, a r ∈ A (j r)) → (∀ r, trace τ (a r) = 0) → + (∀ (r : ℕ) (hr : r + 1 < k), + j ⟨r, Nat.lt_trans (Nat.lt_succ_self r) hr⟩ ≠ j ⟨r + 1, hr⟩) → + trace τ (List.ofFn a).prod = 0 + +def FreeStandardNoise {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X S : Fin n → H →L[ℂ] H) : Prop := + (∀ i k, trace τ (S i ^ k) = + if Even k then (catalan (k / 2) : ℂ) else 0) ∧ + FreeSubalgebras τ (fun j : Option (Fin n) => match j with + | none => Algebra.adjoin ℂ (Set.range X) + | some i => Algebra.adjoin ℂ {S i}) + +def polynomialL2 {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : Submodule ℂ H := + (Submodule.span ℂ (Set.range (fun w : List (Fin n) => wordEval X w τ.vacuum))).topologicalClosure + +def derivativeMoment {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (i : Fin n) (w : List (Fin n)) : ℂ := + ∑ r : Fin w.length, if w[r.val] = i then + wordMoment τ X (w.take r.val) * wordMoment τ X (w.drop (r.val + 1)) else 0 + +def ConjugateSystem {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (ξ : Fin n → H) : Prop := + ∀ i, ξ i ∈ polynomialL2 τ X ∧ ∀ w : List (Fin n), + inner ℂ (ξ i) (wordEval X w τ.vacuum) = derivativeMoment τ X i w + +def freeFisher {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : ℝ≥0∞ := + ⨅ (ξ : Fin n → H) (_ : ConjugateSystem τ X ξ), ENNReal.ofReal (∑ i, ‖ξ i‖ ^ 2) + +def heatTuple {n : ℕ} (X S : Fin n → H →L[ℂ] H) (s : ℝ) : + Fin n → H →L[ℂ] H := fun i => X i + (Real.sqrt s : ℂ) • S i + +def chiStar {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X S : Fin n → H →L[ℂ] H) : EReal := + let b : ℝ → ℝ≥0∞ := fun s => ENNReal.ofReal ((n : ℝ) / (1 + s)) + let f : ℝ → ℝ≥0∞ := fun s => freeFisher τ (heatTuple X S s) + ((n / 2 * Real.log (2 * Real.pi * Real.exp 1) : ℝ) : EReal) + + (1 / 2 : EReal) * (∫⁻ s in Set.Ioi (0 : ℝ), b s - f s).toEReal - + (1 / 2 : EReal) * (∫⁻ s in Set.Ioi (0 : ℝ), f s - b s).toEReal + +abbrev MatrixCoordinates (n d : ℕ) := EuclideanSpace ℝ (Fin n × Fin d × Fin d) + +def hermitianMatrix {n d : ℕ} (a : MatrixCoordinates n d) (i : Fin n) : + Matrix (Fin d) (Fin d) ℂ := fun j k => + if j = k then (a (i, j, j) : ℂ) + else if j < k then ((a (i, j, k) : ℂ) + Complex.I * (a (i, k, j) : ℂ)) / Real.sqrt 2 + else ((a (i, k, j) : ℂ) - Complex.I * (a (i, j, k) : ℂ)) / Real.sqrt 2 + +def matrixOpNorm {d : ℕ} (A : Matrix (Fin d) (Fin d) ℂ) : ℝ := + ‖(Matrix.toEuclideanLin A).toContinuousLinearMap‖ + +def matrixMoment {n d : ℕ} (a : MatrixCoordinates n d) (w : List (Fin n)) : ℂ := + (d : ℂ)⁻¹ * Matrix.trace (w.map (hermitianMatrix a)).prod + +def microstates {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (R : ℝ) (m d : ℕ) (ε : ℝ) : Set (MatrixCoordinates n d) := + {a | (∀ i, matrixOpNorm (hermitianMatrix a i) ≤ R) ∧ + ∀ w : List (Fin n), w.length ≤ m → ‖matrixMoment a w - wordMoment τ X w‖ < ε} + +def chiCutoff {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (R : ℝ) : EReal := + ⨅ m : ℕ, ⨅ ε : {ε : ℝ // 0 < ε}, + limsup (fun d : ℕ => + (((((d + 1 : ℕ) : ℝ) ^ 2)⁻¹ : ℝ) : EReal) * + (volume (microstates τ X R m (d + 1) ε.val)).log + + (((n : ℝ) / 2 * Real.log (d + 1) : ℝ) : EReal)) atTop + +def chi {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : EReal := + ⨆ R : {R : ℝ // 0 < R}, chiCutoff τ X R.val + +open MeasureTheory + +theorem main : + ∃ (H : Type) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (M : VonNeumannAlgebra H) (τ : TracialVector M) + (n : ℕ) (X S : Fin n → H →L[ℂ] H), + 2 ≤ n ∧ + (∀ i, X i ∈ M ∧ IsSelfAdjoint (X i)) ∧ + (∀ i, S i ∈ M ∧ IsSelfAdjoint (S i)) ∧ + FreeStandardNoise τ X S ∧ + (⊥ : EReal) < chi τ X ∧ + chi τ X ≤ chiStar τ X S - (1 / 2 : EReal) ∧ + chiStar τ X S - (1 / 2 : EReal) < (⊤ : EReal) := by + sorry + +end FiniteEntropySeparation + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FiniteEntropySeparation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FiniteEntropySeparation.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/finite-entropy-separation/solution/closure.txt b/tasks/finite-entropy-separation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8fbcca858c916e1dc20b37db3992706dc8a6eea --- /dev/null +++ b/tasks/finite-entropy-separation/solution/closure.txt @@ -0,0 +1,153 @@ +OAI.Analysis.FreeEntropy.ActualTuple +OAI.Analysis.FreeEntropy.Basic +OAI.Analysis.FreeEntropy.BilinearNet +OAI.Analysis.FreeEntropy.BlockEnsembleLower +OAI.Analysis.FreeEntropy.BlockEvent +OAI.Analysis.FreeEntropy.BlockEventLower +OAI.Analysis.FreeEntropy.BlockGaussianQuantitative +OAI.Analysis.FreeEntropy.CompactIntegration +OAI.Analysis.FreeEntropy.ComplexPolynomialFunctions +OAI.Analysis.FreeEntropy.CoordinateIBP +OAI.Analysis.FreeEntropy.CoordinateMask +OAI.Analysis.FreeEntropy.CumulantBound +OAI.Analysis.FreeEntropy.CumulantResidual +OAI.Analysis.FreeEntropy.CumulantSeries +OAI.Analysis.FreeEntropy.CutoffSeparation +OAI.Analysis.FreeEntropy.CyclicSeries +OAI.Analysis.FreeEntropy.EmbeddedSeries +OAI.Analysis.FreeEntropy.EntropyDeficit +OAI.Analysis.FreeEntropy.EntropyFiniteness +OAI.Analysis.FreeEntropy.EntropyIntegral +OAI.Analysis.FreeEntropy.EntropyReal +OAI.Analysis.FreeEntropy.EquidiscreteSignal +OAI.Analysis.FreeEntropy.FatouFlow +OAI.Analysis.FreeEntropy.FisherDeficit +OAI.Analysis.FreeEntropy.FisherLaw +OAI.Analysis.FreeEntropy.FisherLiminf +OAI.Analysis.FreeEntropy.FisherResidual +OAI.Analysis.FreeEntropy.FisherTestLimit +OAI.Analysis.FreeEntropy.FisherVariational +OAI.Analysis.FreeEntropy.FlowSeparation +OAI.Analysis.FreeEntropy.FreeEntropyFlow +OAI.Analysis.FreeEntropy.FreeMatrixModels +OAI.Analysis.FreeEntropy.GUEBounds +OAI.Analysis.FreeEntropy.GUEConcentration +OAI.Analysis.FreeEntropy.GUECovariance +OAI.Analysis.FreeEntropy.GUEDerivative +OAI.Analysis.FreeEntropy.GUEFock +OAI.Analysis.FreeEntropy.GUEFreeLaw +OAI.Analysis.FreeEntropy.GUEGradient +OAI.Analysis.FreeEntropy.GUELimit +OAI.Analysis.FreeEntropy.GUEMoments +OAI.Analysis.FreeEntropy.GUEOperatorTail +OAI.Analysis.FreeEntropy.GUESelection +OAI.Analysis.FreeEntropy.GUEStein +OAI.Analysis.FreeEntropy.GaussianAffineVolume +OAI.Analysis.FreeEntropy.GaussianBlockTail +OAI.Analysis.FreeEntropy.GaussianConvolution +OAI.Analysis.FreeEntropy.GaussianConvolutionBounds +OAI.Analysis.FreeEntropy.GaussianCorrection +OAI.Analysis.FreeEntropy.GaussianCrossEntropy +OAI.Analysis.FreeEntropy.GaussianDeBruijn +OAI.Analysis.FreeEntropy.GaussianDecay +OAI.Analysis.FreeEntropy.GaussianDensity +OAI.Analysis.FreeEntropy.GaussianDifferential +OAI.Analysis.FreeEntropy.GaussianEntropyEvent +OAI.Analysis.FreeEntropy.GaussianEntropyIntegrability +OAI.Analysis.FreeEntropy.GaussianFlow +OAI.Analysis.FreeEntropy.GaussianHermite +OAI.Analysis.FreeEntropy.GaussianIBP +OAI.Analysis.FreeEntropy.GaussianKernel +OAI.Analysis.FreeEntropy.GaussianL2Limit +OAI.Analysis.FreeEntropy.GaussianLinearTail +OAI.Analysis.FreeEntropy.GaussianMvStein +OAI.Analysis.FreeEntropy.GaussianProjectionMoments +OAI.Analysis.FreeEntropy.GaussianRegularity +OAI.Analysis.FreeEntropy.GaussianScore +OAI.Analysis.FreeEntropy.GaussianVolume +OAI.Analysis.FreeEntropy.GeometricTail +OAI.Analysis.FreeEntropy.HeatAnalysis +OAI.Analysis.FreeEntropy.HeatCumulants +OAI.Analysis.FreeEntropy.HeatTensor +OAI.Analysis.FreeEntropy.L2Convergence +OAI.Analysis.FreeEntropy.LinearSeries +OAI.Analysis.FreeEntropy.Main +OAI.Analysis.FreeEntropy.MatrixBasis +OAI.Analysis.FreeEntropy.MatrixBasisChart +OAI.Analysis.FreeEntropy.MatrixBilinear +OAI.Analysis.FreeEntropy.MatrixBlockEnergy +OAI.Analysis.FreeEntropy.MatrixBlocks +OAI.Analysis.FreeEntropy.MatrixBounds +OAI.Analysis.FreeEntropy.MatrixChart +OAI.Analysis.FreeEntropy.MatrixChartInverse +OAI.Analysis.FreeEntropy.MatrixFisherLiminf +OAI.Analysis.FreeEntropy.MatrixFisherTest +OAI.Analysis.FreeEntropy.MatrixFlow +OAI.Analysis.FreeEntropy.MatrixHeatLaw +OAI.Analysis.FreeEntropy.MatrixHeatLawMoments +OAI.Analysis.FreeEntropy.MatrixHeatLimit +OAI.Analysis.FreeEntropy.MatrixHilbertSchmidt +OAI.Analysis.FreeEntropy.MatrixOperator +OAI.Analysis.FreeEntropy.MatrixParseval +OAI.Analysis.FreeEntropy.MatrixPolynomial +OAI.Analysis.FreeEntropy.MatrixPolynomialNorm +OAI.Analysis.FreeEntropy.MatrixReparam +OAI.Analysis.FreeEntropy.MatrixRotationBounds +OAI.Analysis.FreeEntropy.MatrixScoreWords +OAI.Analysis.FreeEntropy.MatrixSpectralMoments +OAI.Analysis.FreeEntropy.MatrixTestPolynomial +OAI.Analysis.FreeEntropy.MatrixWordDerivative +OAI.Analysis.FreeEntropy.MicrostatesHeat +OAI.Analysis.FreeEntropy.MicrostatesLogLower +OAI.Analysis.FreeEntropy.MicrostatesLower +OAI.Analysis.FreeEntropy.MicrostatesSelection +OAI.Analysis.FreeEntropy.MixedGaussianSeries +OAI.Analysis.FreeEntropy.Model +OAI.Analysis.FreeEntropy.ModelFlowLimit +OAI.Analysis.FreeEntropy.MonomialSeries +OAI.Analysis.FreeEntropy.NoiseRotation +OAI.Analysis.FreeEntropy.NoiseTensor +OAI.Analysis.FreeEntropy.NormalLaw +OAI.Analysis.FreeEntropy.OptionSeries +OAI.Analysis.FreeEntropy.OrthogonalExpansion +OAI.Analysis.FreeEntropy.PolynomialFunctions +OAI.Analysis.FreeEntropy.PolynomialGrowth +OAI.Analysis.FreeEntropy.RandomHeatConvergence +OAI.Analysis.FreeEntropy.RandomHeatMoments +OAI.Analysis.FreeEntropy.RandomMatrixConvergence +OAI.Analysis.FreeEntropy.RealTail +OAI.Analysis.FreeEntropy.SemicircularSeries +OAI.Analysis.FreeEntropy.SeriesAnalytic +OAI.Analysis.FreeEntropy.SeriesNorm +OAI.Analysis.FreeEntropy.SeriesSummability +OAI.Analysis.FreeEntropy.SeriesWeights +OAI.Analysis.FreeEntropy.Signal +OAI.Analysis.FreeEntropy.SignalCovariance +OAI.Analysis.FreeEntropy.SignalSeries +OAI.Analysis.FreeEntropy.SpectralBlockMask +OAI.Analysis.FreeEntropy.SpectralClustering +OAI.Analysis.FreeEntropy.SpectralMatrixProducer +OAI.Analysis.FreeEntropy.SpectralParameters +OAI.Analysis.FreeEntropy.SpectralTestFunctions +OAI.Analysis.FreeEntropy.TensorConcat +OAI.Analysis.FreeEntropy.TensorFreeness +OAI.Analysis.FreeEntropy.TensorGradient +OAI.Analysis.FreeEntropy.TensorHermite +OAI.Analysis.FreeEntropy.TensorLaw +OAI.Analysis.FreeEntropy.TensorMatrices +OAI.Analysis.FreeEntropy.TensorMatrixModels +OAI.Analysis.FreeEntropy.TensorPoincare +OAI.Analysis.FreeEntropy.TerminalGaussian +OAI.Analysis.FreeEntropy.TotalSecond +OAI.Analysis.FreeEntropy.TracialRealization +OAI.Analysis.FreeEntropy.TwoNoiseFisher +OAI.Analysis.FreeEntropy.UniformConvergence +OAI.Analysis.FreeEntropy.UniformMicrostateTests +OAI.Analysis.FreeEntropy.VectorSeries +OAI.Analysis.FreeEntropy.VolumetricNet +OAI.Analysis.FreeEntropy.WickBound +OAI.Analysis.FreeEntropy.WickCoefficients +OAI.Analysis.FreeEntropy.WickSeries +OAI.Analysis.FreeEntropy.WickTensor +OAI.Analysis.FreeEntropy.WordLinearLaw +OAI.Analysis.FreeEntropy.WordSeries diff --git a/tasks/finite-entropy-separation/solution/reference.py b/tasks/finite-entropy-separation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/finite-entropy-separation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/finite-entropy-separation/solution/solve.sh b/tasks/finite-entropy-separation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b117f7398872b80e64d7d9555840e3de57c28f0a --- /dev/null +++ b/tasks/finite-entropy-separation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FiniteEntropySeparation, i.e. module OAI.Analysis.FreeEntropy.Main and the +# 153 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.FreeEntropy.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FiniteEntropySeparation" diff --git a/tasks/finite-entropy-separation/task.toml b/tasks/finite-entropy-separation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d841fd60688d3ebce6d56eba7f601b66afd101f --- /dev/null +++ b/tasks/finite-entropy-separation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/finite-entropy-separation" +version = "1.0.0" +description = "Prove FiniteEntropySeparation (openai/math family 298: A counterexample to Voiculescu’s free-entropy equality conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FiniteEntropySeparation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FiniteEntropySeparation" +family = "298" +family_title = "A counterexample to Voiculescu’s free-entropy equality conjecture" +subject = "Operator algebras" +theorems = ["OAI.FiniteEntropySeparation.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.FreeEntropy.Main" +reference_modules = 153 +reference_lean_bytes = 786027 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1422 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12407 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/finite-entropy-separation/tests/Challenge.lean b/tasks/finite-entropy-separation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c538a4c995d6bc60df8fd8079933c485cdb09f0 --- /dev/null +++ b/tasks/finite-entropy-separation/tests/Challenge.lean @@ -0,0 +1,125 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped ENNReal NNReal ComplexConjugate +open MeasureTheory Filter + +namespace FiniteEntropySeparation + +variable {H : Type} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +structure TracialVector (M : VonNeumannAlgebra H) where + vacuum : H + norm_vacuum : ‖vacuum‖ = 1 + tracial : ∀ A ∈ M, ∀ B ∈ M, + inner ℂ vacuum ((A * B) vacuum) = inner ℂ vacuum ((B * A) vacuum) + separating : ∀ A ∈ M, A vacuum = 0 → A = 0 + +def trace {M : VonNeumannAlgebra H} (τ : TracialVector M) (A : H →L[ℂ] H) : ℂ := + inner ℂ τ.vacuum (A τ.vacuum) + +def wordEval {n : ℕ} (X : Fin n → H →L[ℂ] H) (w : List (Fin n)) : H →L[ℂ] H := + (w.map X).prod + +def wordMoment {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (w : List (Fin n)) : ℂ := trace τ (wordEval X w) + +def FreeSubalgebras {ι : Type} {M : VonNeumannAlgebra H} (τ : TracialVector M) + (A : ι → Subalgebra ℂ (H →L[ℂ] H)) : Prop := + ∀ (k : ℕ), 0 < k → ∀ (j : Fin k → ι) (a : Fin k → H →L[ℂ] H), + (∀ r, a r ∈ A (j r)) → (∀ r, trace τ (a r) = 0) → + (∀ (r : ℕ) (hr : r + 1 < k), + j ⟨r, Nat.lt_trans (Nat.lt_succ_self r) hr⟩ ≠ j ⟨r + 1, hr⟩) → + trace τ (List.ofFn a).prod = 0 + +def FreeStandardNoise {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X S : Fin n → H →L[ℂ] H) : Prop := + (∀ i k, trace τ (S i ^ k) = + if Even k then (catalan (k / 2) : ℂ) else 0) ∧ + FreeSubalgebras τ (fun j : Option (Fin n) => match j with + | none => Algebra.adjoin ℂ (Set.range X) + | some i => Algebra.adjoin ℂ {S i}) + +def polynomialL2 {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : Submodule ℂ H := + (Submodule.span ℂ (Set.range (fun w : List (Fin n) => wordEval X w τ.vacuum))).topologicalClosure + +def derivativeMoment {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (i : Fin n) (w : List (Fin n)) : ℂ := + ∑ r : Fin w.length, if w[r.val] = i then + wordMoment τ X (w.take r.val) * wordMoment τ X (w.drop (r.val + 1)) else 0 + +def ConjugateSystem {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (ξ : Fin n → H) : Prop := + ∀ i, ξ i ∈ polynomialL2 τ X ∧ ∀ w : List (Fin n), + inner ℂ (ξ i) (wordEval X w τ.vacuum) = derivativeMoment τ X i w + +def freeFisher {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : ℝ≥0∞ := + ⨅ (ξ : Fin n → H) (_ : ConjugateSystem τ X ξ), ENNReal.ofReal (∑ i, ‖ξ i‖ ^ 2) + +def heatTuple {n : ℕ} (X S : Fin n → H →L[ℂ] H) (s : ℝ) : + Fin n → H →L[ℂ] H := fun i => X i + (Real.sqrt s : ℂ) • S i + +def chiStar {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X S : Fin n → H →L[ℂ] H) : EReal := + let b : ℝ → ℝ≥0∞ := fun s => ENNReal.ofReal ((n : ℝ) / (1 + s)) + let f : ℝ → ℝ≥0∞ := fun s => freeFisher τ (heatTuple X S s) + ((n / 2 * Real.log (2 * Real.pi * Real.exp 1) : ℝ) : EReal) + + (1 / 2 : EReal) * (∫⁻ s in Set.Ioi (0 : ℝ), b s - f s).toEReal - + (1 / 2 : EReal) * (∫⁻ s in Set.Ioi (0 : ℝ), f s - b s).toEReal + +abbrev MatrixCoordinates (n d : ℕ) := EuclideanSpace ℝ (Fin n × Fin d × Fin d) + +def hermitianMatrix {n d : ℕ} (a : MatrixCoordinates n d) (i : Fin n) : + Matrix (Fin d) (Fin d) ℂ := fun j k => + if j = k then (a (i, j, j) : ℂ) + else if j < k then ((a (i, j, k) : ℂ) + Complex.I * (a (i, k, j) : ℂ)) / Real.sqrt 2 + else ((a (i, k, j) : ℂ) - Complex.I * (a (i, j, k) : ℂ)) / Real.sqrt 2 + +def matrixOpNorm {d : ℕ} (A : Matrix (Fin d) (Fin d) ℂ) : ℝ := + ‖(Matrix.toEuclideanLin A).toContinuousLinearMap‖ + +def matrixMoment {n d : ℕ} (a : MatrixCoordinates n d) (w : List (Fin n)) : ℂ := + (d : ℂ)⁻¹ * Matrix.trace (w.map (hermitianMatrix a)).prod + +def microstates {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (R : ℝ) (m d : ℕ) (ε : ℝ) : Set (MatrixCoordinates n d) := + {a | (∀ i, matrixOpNorm (hermitianMatrix a i) ≤ R) ∧ + ∀ w : List (Fin n), w.length ≤ m → ‖matrixMoment a w - wordMoment τ X w‖ < ε} + +def chiCutoff {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) (R : ℝ) : EReal := + ⨅ m : ℕ, ⨅ ε : {ε : ℝ // 0 < ε}, + limsup (fun d : ℕ => + (((((d + 1 : ℕ) : ℝ) ^ 2)⁻¹ : ℝ) : EReal) * + (volume (microstates τ X R m (d + 1) ε.val)).log + + (((n : ℝ) / 2 * Real.log (d + 1) : ℝ) : EReal)) atTop + +def chi {M : VonNeumannAlgebra H} (τ : TracialVector M) {n : ℕ} + (X : Fin n → H →L[ℂ] H) : EReal := + ⨆ R : {R : ℝ // 0 < R}, chiCutoff τ X R.val + +open MeasureTheory + +theorem main : + ∃ (H : Type) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (M : VonNeumannAlgebra H) (τ : TracialVector M) + (n : ℕ) (X S : Fin n → H →L[ℂ] H), + 2 ≤ n ∧ + (∀ i, X i ∈ M ∧ IsSelfAdjoint (X i)) ∧ + (∀ i, S i ∈ M ∧ IsSelfAdjoint (S i)) ∧ + FreeStandardNoise τ X S ∧ + (⊥ : EReal) < chi τ X ∧ + chi τ X ≤ chiStar τ X S - (1 / 2 : EReal) ∧ + chiStar τ X S - (1 / 2 : EReal) < (⊤ : EReal) := by + sorry + +end FiniteEntropySeparation + +end + +end OAI diff --git a/tasks/finite-entropy-separation/tests/grade.py b/tasks/finite-entropy-separation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/finite-entropy-separation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/finite-entropy-separation/tests/task.json b/tasks/finite-entropy-separation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..669e96f2b64332eae6b3ef59cfe2ded7a9feb570 --- /dev/null +++ b/tasks/finite-entropy-separation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FiniteEntropySeparation", + "comparator": { + "theorem_names": [ + "OAI.FiniteEntropySeparation.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11507 +} \ No newline at end of file diff --git a/tasks/finite-entropy-separation/tests/test.sh b/tasks/finite-entropy-separation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/finite-entropy-separation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/finite-factor/environment/Dockerfile b/tasks/finite-factor/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/finite-factor/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/finite-factor/environment/fetch_mathlib.sh b/tasks/finite-factor/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/finite-factor/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/finite-factor/environment/lake-manifest.json b/tasks/finite-factor/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/finite-factor/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/finite-factor/environment/lakefile.lean b/tasks/finite-factor/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/finite-factor/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/finite-factor/environment/lean_setup.sh b/tasks/finite-factor/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/finite-factor/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/finite-factor/environment/pack_submission.py b/tasks/finite-factor/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/finite-factor/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/finite-factor/instruction.md b/tasks/finite-factor/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..59a6459f7bebfc1df42c5fafad80d19ea600c9d9 --- /dev/null +++ b/tasks/finite-factor/instruction.md @@ -0,0 +1,97 @@ +# openai/math challenge `FiniteFactor` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `FiniteFactor`, also at `/opt/openai-math/challenges/FiniteFactor.lean`: + +```lean +import Mathlib.Analysis.VonNeumannAlgebra.Basic +import Mathlib.Analysis.SpecialFunctions.Pow.Real + +namespace OAI + +namespace FiniteFactor +open Filter +open scoped Topology +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +/-- A concrete factor has scalar center. -/ +def HasScalarCenter (M : VonNeumannAlgebra H) : Prop := + ∀ a ∈ M, (∀ b ∈ M, a * b = b * a) → ∃ z : ℂ, a = z • (1 : H →L[ℂ] H) + +/-- Finiteness: every isometry in the algebra is unitary. -/ +def IsFiniteAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ v ∈ M, star v * v = 1 → v * star v = 1 + +/-- No nonzero projection is minimal, excluding matrix factors. -/ +def HasNoMinimalProjection (M : VonNeumannAlgebra H) : Prop := + ∀ p ∈ M, IsStarProjection p → p ≠ 0 → + ∃ q ∈ M, IsStarProjection q ∧ q ≠ 0 ∧ q ≠ p ∧ q * p = q + +/-- A separable Banach space whose dual is conjugate-linearly isometric to M. -/ +def HasSeparablePredual (M : VonNeumannAlgebra H) : Prop := + ∃ (E : Type u) (_ : NormedAddCommGroup E) (_ : NormedSpace ℂ E) + (_ : CompleteSpace E) (_ : TopologicalSpace.SeparableSpace E), + Nonempty (StrongDual ℂ E ≃ₗᵢ⋆[ℂ] M.toStarSubalgebra) + +def MainTarget : Prop := + ∃ (H : Type u) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (M : VonNeumannAlgebra H), + HasScalarCenter M ∧ IsFiniteAlgebra M ∧ HasNoMinimalProjection M ∧ + HasSeparablePredual M ∧ + ∃ T : H →L[ℂ] H, T ∈ M ∧ T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + ∀ p ∈ M, IsStarProjection p → (1 - p) * T * p = 0 → p = 0 ∨ p = 1 + +theorem main_theorem : MainTarget.{0} := by + sorry + +end FiniteFactor + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FiniteFactor.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FiniteFactor.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/finite-factor/solution/closure.txt b/tasks/finite-factor/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6e070c446c3c5879e561dd310f0a80901d54371b --- /dev/null +++ b/tasks/finite-factor/solution/closure.txt @@ -0,0 +1,271 @@ +OAI.Analysis.FiniteFactor.BiasedPairs.CommonConull +OAI.Analysis.FiniteFactor.BiasedPairs.Conull +OAI.Analysis.FiniteFactor.BiasedPairs.Measures +OAI.Analysis.FiniteFactor.BiasedPairs.PairIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixDomination +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixLimit +OAI.Analysis.FiniteFactor.BiasedPairs.RealIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.ReferenceDomination +OAI.Analysis.FiniteFactor.BoundedMatrixOperator +OAI.Analysis.FiniteFactor.CompactGraphLusin +OAI.Analysis.FiniteFactor.CompactZeroTransfer +OAI.Analysis.FiniteFactor.Contradiction +OAI.Analysis.FiniteFactor.Convolution +OAI.Analysis.FiniteFactor.CountableMaskedError +OAI.Analysis.FiniteFactor.Coupling.BadEvents +OAI.Analysis.FiniteFactor.Coupling.Bayes +OAI.Analysis.FiniteFactor.Coupling.BlockLimit +OAI.Analysis.FiniteFactor.Coupling.Bounds +OAI.Analysis.FiniteFactor.Coupling.Conditioning +OAI.Analysis.FiniteFactor.Coupling.CoordinateMass +OAI.Analysis.FiniteFactor.Coupling.Crossing +OAI.Analysis.FiniteFactor.Coupling.Density +OAI.Analysis.FiniteFactor.Coupling.FiniteDisintegration +OAI.Analysis.FiniteFactor.Coupling.FiniteLaw +OAI.Analysis.FiniteFactor.Coupling.FinitePosteriorAC +OAI.Analysis.FiniteFactor.Coupling.Infinite +OAI.Analysis.FiniteFactor.Coupling.Law +OAI.Analysis.FiniteFactor.Coupling.Limit +OAI.Analysis.FiniteFactor.Coupling.Marginals +OAI.Analysis.FiniteFactor.Coupling.Mixture +OAI.Analysis.FiniteFactor.Coupling.Noncrossing +OAI.Analysis.FiniteFactor.Coupling.Order +OAI.Analysis.FiniteFactor.Coupling.Parameters +OAI.Analysis.FiniteFactor.Coupling.Prefix +OAI.Analysis.FiniteFactor.Coupling.Products +OAI.Analysis.FiniteFactor.Coupling.TaggedAdmissibility +OAI.Analysis.FiniteFactor.Coupling.VectorBayes +OAI.Analysis.FiniteFactor.CrossedProduct.AngleLaw +OAI.Analysis.FiniteFactor.CrossedProduct.AngleRelations +OAI.Analysis.FiniteFactor.CrossedProduct.AssignedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.Attenuation +OAI.Analysis.FiniteFactor.CrossedProduct.BoundaryEvent +OAI.Analysis.FiniteFactor.CrossedProduct.CappedPair +OAI.Analysis.FiniteFactor.CrossedProduct.CappedTransfer +OAI.Analysis.FiniteFactor.CrossedProduct.CentralDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.CentralScalarField +OAI.Analysis.FiniteFactor.CrossedProduct.Cocycle +OAI.Analysis.FiniteFactor.CrossedProduct.ColumnSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.ConjugationVacuum +OAI.Analysis.FiniteFactor.CrossedProduct.ConvolutionCocycle +OAI.Analysis.FiniteFactor.CrossedProduct.CouplingBudget +OAI.Analysis.FiniteFactor.CrossedProduct.CurrentTaggedEvent +OAI.Analysis.FiniteFactor.CrossedProduct.DiagonalLoss +OAI.Analysis.FiniteFactor.CrossedProduct.EventExpectation +OAI.Analysis.FiniteFactor.CrossedProduct.EventLossAssembly +OAI.Analysis.FiniteFactor.CrossedProduct.EventMassUpper +OAI.Analysis.FiniteFactor.CrossedProduct.EventPositive +OAI.Analysis.FiniteFactor.CrossedProduct.FiberEnergy +OAI.Analysis.FiniteFactor.CrossedProduct.FiberIndicators +OAI.Analysis.FiniteFactor.CrossedProduct.FiberSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.FiberTotal +OAI.Analysis.FiniteFactor.CrossedProduct.FieldAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FieldRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCocycleBounds +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCoefficients +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteVectors +OAI.Analysis.FiniteFactor.CrossedProduct.FloorSupport +OAI.Analysis.FiniteFactor.CrossedProduct.FreeRotation +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundary +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundaryLoss +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBudget +OAI.Analysis.FiniteFactor.CrossedProduct.GeneratedAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.HilbertSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.IndicatorProjection +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantConull +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantProjection +OAI.Analysis.FiniteFactor.CrossedProduct.LusinCompact +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedError +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.MultiplicationAdjoint +OAI.Analysis.FiniteFactor.CrossedProduct.NoMinimalProjection +OAI.Analysis.FiniteFactor.CrossedProduct.NormalFunctionalSpace +OAI.Analysis.FiniteFactor.CrossedProduct.NormalRiesz +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedRatio +OAI.Analysis.FiniteFactor.CrossedProduct.Operator +OAI.Analysis.FiniteFactor.CrossedProduct.OperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.OrbitNormalization +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedSampling +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedTorusSampling +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCount +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCoverage +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseDecay +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseFirst +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseMarginal +OAI.Analysis.FiniteFactor.CrossedProduct.Phases +OAI.Analysis.FiniteFactor.CrossedProduct.Powers +OAI.Analysis.FiniteFactor.CrossedProduct.PredualIdentification +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedBase +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFactor +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFinite +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionColumns +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionConvolution +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionErrors +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionEvent +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPositiveConull +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceMixture +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceOrdered +OAI.Analysis.FiniteFactor.CrossedProduct.Reflection +OAI.Analysis.FiniteFactor.CrossedProduct.ResamplingLaw +OAI.Analysis.FiniteFactor.CrossedProduct.Rotation +OAI.Analysis.FiniteFactor.CrossedProduct.RotationCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.RotationErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCenter +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.SmallPartitionSets +OAI.Analysis.FiniteFactor.CrossedProduct.StageCoupling +OAI.Analysis.FiniteFactor.CrossedProduct.StageOperator +OAI.Analysis.FiniteFactor.CrossedProduct.StagePolynomial +OAI.Analysis.FiniteFactor.CrossedProduct.Stages +OAI.Analysis.FiniteFactor.CrossedProduct.TagGeometry +OAI.Analysis.FiniteFactor.CrossedProduct.TagLaw +OAI.Analysis.FiniteFactor.CrossedProduct.TailTrimming +OAI.Analysis.FiniteFactor.CrossedProduct.TorusCharacters +OAI.Analysis.FiniteFactor.CrossedProduct.TorusErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.TorusModel +OAI.Analysis.FiniteFactor.CrossedProduct.TorusOperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.TorusRotation +OAI.Analysis.FiniteFactor.CrossedProduct.Trace +OAI.Analysis.FiniteFactor.CrossedProduct.TracialRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.Transport +OAI.Analysis.FiniteFactor.CrossedProduct.TruncatedBound +OAI.Analysis.FiniteFactor.CrossedProduct.UncappedPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumFunctional +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumSeparating +OAI.Analysis.FiniteFactor.CrossedProduct.VectorFunctionalRelations +OAI.Analysis.FiniteFactor.CrossedProduct.WeightedShiftField +OAI.Analysis.FiniteFactor.Diffuse.OperatorCesaro +OAI.Analysis.FiniteFactor.Diffuse.OperatorMeanErgodic +OAI.Analysis.FiniteFactor.Diffuse.OperatorSupport +OAI.Analysis.FiniteFactor.Diffuse.ProjectionTrace +OAI.Analysis.FiniteFactor.Diffuse.SmallPartitions +OAI.Analysis.FiniteFactor.Diffuse.SupportLimit +OAI.Analysis.FiniteFactor.Diffuse.SupportTrace +OAI.Analysis.FiniteFactor.Diffuse.TracePowers +OAI.Analysis.FiniteFactor.Fiber.Diagonal +OAI.Analysis.FiniteFactor.Fiber.PairZeroSet +OAI.Analysis.FiniteFactor.Fiber.ProjectionDiagonal +OAI.Analysis.FiniteFactor.Fiber.Shift +OAI.Analysis.FiniteFactor.Fiber.StrongContinuity +OAI.Analysis.FiniteFactor.Fiber.TransportConvolution +OAI.Analysis.FiniteFactor.FiniteMeasureCylinderCriterion +OAI.Analysis.FiniteFactor.FiniteMixtureAlgebra +OAI.Analysis.FiniteFactor.FiniteProductAbsoluteContinuity +OAI.Analysis.FiniteFactor.FiniteProductMixture +OAI.Analysis.FiniteFactor.FiniteSingleTag +OAI.Analysis.FiniteFactor.IndependentCount +OAI.Analysis.FiniteFactor.L2UniformAbsoluteContinuity +OAI.Analysis.FiniteFactor.Main +OAI.Analysis.FiniteFactor.Matrix.Action +OAI.Analysis.FiniteFactor.Matrix.Bounds +OAI.Analysis.FiniteFactor.Matrix.Covariance +OAI.Analysis.FiniteFactor.Matrix.Entries +OAI.Analysis.FiniteFactor.Matrix.Integrals +OAI.Analysis.FiniteFactor.Model +OAI.Analysis.FiniteFactor.OperatorTracialRepresentation +OAI.Analysis.FiniteFactor.OperatorUltraweak +OAI.Analysis.FiniteFactor.OrbitSampling.CompactTorus +OAI.Analysis.FiniteFactor.OrbitSampling.CrossProducts +OAI.Analysis.FiniteFactor.OrbitSampling.Cube +OAI.Analysis.FiniteFactor.OrbitSampling.CutoffMass +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderBasis +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderSystem +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalContribution +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalEvent +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalIntegral +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalLimit +OAI.Analysis.FiniteFactor.OrbitSampling.Discrepancy +OAI.Analysis.FiniteFactor.OrbitSampling.EmpiricalL2 +OAI.Analysis.FiniteFactor.OrbitSampling.Error +OAI.Analysis.FiniteFactor.OrbitSampling.ErrorEvent +OAI.Analysis.FiniteFactor.OrbitSampling.FirstCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.FirstMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.Fourier +OAI.Analysis.FiniteFactor.OrbitSampling.IdealProduct +OAI.Analysis.FiniteFactor.OrbitSampling.IdealRectangleLimit +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMass +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaRectangles +OAI.Analysis.FiniteFactor.OrbitSampling.LimitMeasure +OAI.Analysis.FiniteFactor.OrbitSampling.Measures +OAI.Analysis.FiniteFactor.OrbitSampling.Moments +OAI.Analysis.FiniteFactor.OrbitSampling.OrbitSupport +OAI.Analysis.FiniteFactor.OrbitSampling.OrderedRestriction +OAI.Analysis.FiniteFactor.OrbitSampling.PairMoments +OAI.Analysis.FiniteFactor.OrbitSampling.PhaseSelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.Powers +OAI.Analysis.FiniteFactor.OrbitSampling.ProductError +OAI.Analysis.FiniteFactor.OrbitSampling.ProductMoments +OAI.Analysis.FiniteFactor.OrbitSampling.RationalTests +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleApproximation +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleError +OAI.Analysis.FiniteFactor.OrbitSampling.RotationTransport +OAI.Analysis.FiniteFactor.OrbitSampling.SecondCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.SecondMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.SelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.SelfSummability +OAI.Analysis.FiniteFactor.OrbitSampling.SingleCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.Tail +OAI.Analysis.FiniteFactor.OrbitSampling.TestedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TestedTransport +OAI.Analysis.FiniteFactor.OrbitSampling.TorusLimitMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusSupport +OAI.Analysis.FiniteFactor.OrbitSampling.TriangleLaw +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedWeak +OAI.Analysis.FiniteFactor.OrbitSampling.UniformEvent +OAI.Analysis.FiniteFactor.OrbitSampling.WeakLimit +OAI.Analysis.FiniteFactor.OrbitSampling.WeightedTail +OAI.Analysis.FiniteFactor.OrbitSampling.Weights +OAI.Analysis.FiniteFactor.PeriodizedUniform +OAI.Analysis.FiniteFactor.Polynomial +OAI.Analysis.FiniteFactor.ProductDensityLimit +OAI.Analysis.FiniteFactor.ProductKernel +OAI.Analysis.FiniteFactor.Quasinilpotence +OAI.Analysis.FiniteFactor.Sampling.AveragedTransport +OAI.Analysis.FiniteFactor.Sampling.Cancellation +OAI.Analysis.FiniteFactor.Sampling.FirstDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.FirstInterval +OAI.Analysis.FiniteFactor.Sampling.Fourier +OAI.Analysis.FiniteFactor.Sampling.FourierSum +OAI.Analysis.FiniteFactor.Sampling.IntegratedCorrelation +OAI.Analysis.FiniteFactor.Sampling.IntervalError +OAI.Analysis.FiniteFactor.Sampling.IntervalSums +OAI.Analysis.FiniteFactor.Sampling.Kernel +OAI.Analysis.FiniteFactor.Sampling.KernelTail +OAI.Analysis.FiniteFactor.Sampling.LayerCake +OAI.Analysis.FiniteFactor.Sampling.LayerDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.MixedCorrelation +OAI.Analysis.FiniteFactor.Sampling.OrientedMoments +OAI.Analysis.FiniteFactor.Sampling.Periodization +OAI.Analysis.FiniteFactor.Sampling.ProductError +OAI.Analysis.FiniteFactor.Sampling.Rectangle +OAI.Analysis.FiniteFactor.Sampling.SecondDensity +OAI.Analysis.FiniteFactor.Sampling.SecondDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.SecondInterval +OAI.Analysis.FiniteFactor.Sampling.SecondLevelAE +OAI.Analysis.FiniteFactor.Sampling.SecondLevels +OAI.Analysis.FiniteFactor.Sampling.SecondMoment +OAI.Analysis.FiniteFactor.Sampling.SecondTriangular +OAI.Analysis.FiniteFactor.Sampling.Selection +OAI.Analysis.FiniteFactor.Sampling.SelfMoment +OAI.Analysis.FiniteFactor.Sampling.SmoothedPair +OAI.Analysis.FiniteFactor.Sampling.Smoothing +OAI.Analysis.FiniteFactor.Sampling.SmoothingLaw +OAI.Analysis.FiniteFactor.Sampling.TestedFirstMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSecondMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSelfMoment +OAI.Analysis.FiniteFactor.Sampling.Transport +OAI.Analysis.FiniteFactor.Sampling.WeightTransport +OAI.Analysis.FiniteFactor.Sampling.WeightedCoordinate +OAI.Analysis.FiniteFactor.Sampling.Weights +OAI.Analysis.FiniteFactor.SubmeasureL2Density +OAI.Analysis.FiniteFactor.TagExponentialLower +OAI.Analysis.FiniteFactor.TailEstimate +OAI.Analysis.FiniteFactor.Truncation diff --git a/tasks/finite-factor/solution/reference.py b/tasks/finite-factor/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/finite-factor/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/finite-factor/solution/solve.sh b/tasks/finite-factor/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..978923eacadb6c3221fec2f88600c196274054af --- /dev/null +++ b/tasks/finite-factor/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FiniteFactor, i.e. module OAI.Analysis.FiniteFactor.Main and the +# 271 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.FiniteFactor.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FiniteFactor" diff --git a/tasks/finite-factor/task.toml b/tasks/finite-factor/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a6511e1fd955b302716bb32c9b855d4b05cdfa20 --- /dev/null +++ b/tasks/finite-factor/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/finite-factor" +version = "1.0.0" +description = "Prove FiniteFactor (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FiniteFactor.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FiniteFactor" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.FiniteFactor.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.FiniteFactor.Main" +reference_modules = 271 +reference_lean_bytes = 1113695 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1338 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12702 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/finite-factor/tests/Challenge.lean b/tasks/finite-factor/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e419f31f1b6879e6fb7eecf068e4b21efb687ad7 --- /dev/null +++ b/tasks/finite-factor/tests/Challenge.lean @@ -0,0 +1,46 @@ +import Mathlib.Analysis.VonNeumannAlgebra.Basic +import Mathlib.Analysis.SpecialFunctions.Pow.Real + +namespace OAI + +namespace FiniteFactor +open Filter +open scoped Topology +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +/-- A concrete factor has scalar center. -/ +def HasScalarCenter (M : VonNeumannAlgebra H) : Prop := + ∀ a ∈ M, (∀ b ∈ M, a * b = b * a) → ∃ z : ℂ, a = z • (1 : H →L[ℂ] H) + +/-- Finiteness: every isometry in the algebra is unitary. -/ +def IsFiniteAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ v ∈ M, star v * v = 1 → v * star v = 1 + +/-- No nonzero projection is minimal, excluding matrix factors. -/ +def HasNoMinimalProjection (M : VonNeumannAlgebra H) : Prop := + ∀ p ∈ M, IsStarProjection p → p ≠ 0 → + ∃ q ∈ M, IsStarProjection q ∧ q ≠ 0 ∧ q ≠ p ∧ q * p = q + +/-- A separable Banach space whose dual is conjugate-linearly isometric to M. -/ +def HasSeparablePredual (M : VonNeumannAlgebra H) : Prop := + ∃ (E : Type u) (_ : NormedAddCommGroup E) (_ : NormedSpace ℂ E) + (_ : CompleteSpace E) (_ : TopologicalSpace.SeparableSpace E), + Nonempty (StrongDual ℂ E ≃ₗᵢ⋆[ℂ] M.toStarSubalgebra) + +def MainTarget : Prop := + ∃ (H : Type u) (_ : NormedAddCommGroup H) (_ : InnerProductSpace ℂ H) + (_ : CompleteSpace H) (M : VonNeumannAlgebra H), + HasScalarCenter M ∧ IsFiniteAlgebra M ∧ HasNoMinimalProjection M ∧ + HasSeparablePredual M ∧ + ∃ T : H →L[ℂ] H, T ∈ M ∧ T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + ∀ p ∈ M, IsStarProjection p → (1 - p) * T * p = 0 → p = 0 ∨ p = 1 + +theorem main_theorem : MainTarget.{0} := by + sorry + +end FiniteFactor + +end OAI diff --git a/tasks/finite-factor/tests/grade.py b/tasks/finite-factor/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/finite-factor/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/finite-factor/tests/task.json b/tasks/finite-factor/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d0216fe6a8a8b6366bf64ec92e2a9a657745efad --- /dev/null +++ b/tasks/finite-factor/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FiniteFactor", + "comparator": { + "theorem_names": [ + "OAI.FiniteFactor.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11802 +} \ No newline at end of file diff --git a/tasks/finite-factor/tests/test.sh b/tasks/finite-factor/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/finite-factor/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/finitistic-asymmetry/environment/Dockerfile b/tasks/finitistic-asymmetry/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/finitistic-asymmetry/environment/fetch_mathlib.sh b/tasks/finitistic-asymmetry/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/finitistic-asymmetry/environment/lake-manifest.json b/tasks/finitistic-asymmetry/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/finitistic-asymmetry/environment/lakefile.lean b/tasks/finitistic-asymmetry/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/finitistic-asymmetry/environment/lean_setup.sh b/tasks/finitistic-asymmetry/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/finitistic-asymmetry/environment/pack_submission.py b/tasks/finitistic-asymmetry/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/finitistic-asymmetry/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/finitistic-asymmetry/instruction.md b/tasks/finitistic-asymmetry/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49d79164b7701ce1ec6804a16fc0f53f33cf92fa --- /dev/null +++ b/tasks/finitistic-asymmetry/instruction.md @@ -0,0 +1,92 @@ +# openai/math challenge `FinitisticAsymmetry` (family 198) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 198 of the release, *A counterexample to the little finitistic-dimension conjecture* +(Algebra). The family as a whole: Constructs a finite-dimensional complex algebra whose finite-dimensional modules have unbounded finite projective dimensions. This disproves the little finitistic-dimension conjecture. + +The challenge is `FinitisticAsymmetry`, also at `/opt/openai-math/challenges/FinitisticAsymmetry.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open CategoryTheory + +namespace LittleFinitistic +universe u +variable (A : Type u) [Ring A] + +attribute [-instance] CompletePartialOrder.toSupSet in +def littleFinitisticDimension : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : Module.Finite A M) (_ : projectiveDimension M < ⊤), + projectiveDimension M + +def bigFinitisticDimension : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : projectiveDimension M < ⊤), projectiveDimension M + +def InjectivesGenerate : Prop := + letI := HasDerivedCategory.standard (ModuleCat.{u} A) + ∀ (P : ObjectProperty (DerivedCategory (ModuleCat.{u} A))), + P.IsClosedUnderIsomorphisms → P.IsTriangulated → + (∀ I : Type u, P.IsClosedUnderColimitsOfShape (Discrete I)) → + (∀ (M : ModuleCat.{u} A), Injective M → + P ((DerivedCategory.singleFunctor (ModuleCat.{u} A) 0).obj M)) → + ∀ X, P X + +theorem extreme_left_right_asymmetry : + ∃ (Λ : Type) (_ : Ring Λ) (_ : Algebra ℂ Λ), + FiniteDimensional ℂ Λ ∧ + littleFinitisticDimension Λ = ⊤ ∧ bigFinitisticDimension Λ = ⊤ ∧ + littleFinitisticDimension Λᵐᵒᵖ = 0 ∧ bigFinitisticDimension Λᵐᵒᵖ = 0 ∧ + ¬ InjectivesGenerate Λ ∧ InjectivesGenerate Λᵐᵒᵖ := by + sorry + +end LittleFinitistic + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FinitisticAsymmetry.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LittleFinitistic.extreme_left_right_asymmetry` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/finitistic-asymmetry/solution/closure.txt b/tasks/finitistic-asymmetry/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a301a810588eaf30a4be209ba0609e60bddcca88 --- /dev/null +++ b/tasks/finitistic-asymmetry/solution/closure.txt @@ -0,0 +1,588 @@ +OAI.Algebra.Finitistic.Bar.Balanced +OAI.Algebra.Finitistic.Bar.BalancedTensorFunctor +OAI.Algebra.Finitistic.Bar.Bar +OAI.Algebra.Finitistic.Bar.BarAdditive +OAI.Algebra.Finitistic.Bar.BarBimoduleCongruence +OAI.Algebra.Finitistic.Bar.BarCoordinateNaturality +OAI.Algebra.Finitistic.Bar.BarFunctor +OAI.Algebra.Finitistic.Bar.BarPatternEmbedding +OAI.Algebra.Finitistic.Bar.BlockCoordinateGenerators +OAI.Algebra.Finitistic.Bar.BlockIndexEquiv +OAI.Algebra.Finitistic.Bar.ChainSplitting +OAI.Algebra.Finitistic.Bar.CoproductHomBijections +OAI.Algebra.Finitistic.Bar.CoproductHomotopy +OAI.Algebra.Finitistic.Bar.CountHomologyDetection +OAI.Algebra.Finitistic.Bar.CountProjective +OAI.Algebra.Finitistic.Bar.CountRetracts +OAI.Algebra.Finitistic.Bar.CountTorBounds +OAI.Algebra.Finitistic.Bar.DerivedBarCoproduct +OAI.Algebra.Finitistic.Bar.DerivedCountCoproduct +OAI.Algebra.Finitistic.Bar.DerivedCountShift +OAI.Algebra.Finitistic.Bar.DerivedTensorBarSplitting +OAI.Algebra.Finitistic.Bar.DirectSumCoproduct +OAI.Algebra.Finitistic.Bar.DirectSumExactness +OAI.Algebra.Finitistic.Bar.ExplicitSignedDifferential +OAI.Algebra.Finitistic.Bar.ExtensionColimits +OAI.Algebra.Finitistic.Bar.FiniteBarResolution +OAI.Algebra.Finitistic.Bar.FiniteSumSupport +OAI.Algebra.Finitistic.Bar.FlatSupportedAssembly +OAI.Algebra.Finitistic.Bar.GlobalIndexedComparison +OAI.Algebra.Finitistic.Bar.IndexedAssemblyComparison +OAI.Algebra.Finitistic.Bar.IndexedMultibarTotal +OAI.Algebra.Finitistic.Bar.IndexedPatternEmbedding +OAI.Algebra.Finitistic.Bar.InflatedParityFaces +OAI.Algebra.Finitistic.Bar.IntegerCountObject +OAI.Algebra.Finitistic.Bar.IntegerCountRestriction +OAI.Algebra.Finitistic.Bar.IntegerCountShift +OAI.Algebra.Finitistic.Bar.IntegerDerivedMultibar +OAI.Algebra.Finitistic.Bar.IntegerStalk +OAI.Algebra.Finitistic.Bar.KProjectiveCoproduct +OAI.Algebra.Finitistic.Bar.LeadingBarSuffix +OAI.Algebra.Finitistic.Bar.LeadingSuffixFaces +OAI.Algebra.Finitistic.Bar.LeadingSupportedComparison +OAI.Algebra.Finitistic.Bar.LeadingTotalComparison +OAI.Algebra.Finitistic.Bar.LeadingTotalDifferential +OAI.Algebra.Finitistic.Bar.LeadingTotalEmbedding +OAI.Algebra.Finitistic.Bar.LiteralMultibarCoordinates +OAI.Algebra.Finitistic.Bar.ModuleBlockIndex +OAI.Algebra.Finitistic.Bar.ModuleMultibarCoordinates +OAI.Algebra.Finitistic.Bar.MultibarBlocks +OAI.Algebra.Finitistic.Bar.MultibarDecomposition +OAI.Algebra.Finitistic.Bar.MultibarFlattenDerived +OAI.Algebra.Finitistic.Bar.MultibarIndex +OAI.Algebra.Finitistic.Bar.MultibarSigns +OAI.Algebra.Finitistic.Bar.PatternPrefixCoordinates +OAI.Algebra.Finitistic.Bar.PatternSuffixFaces +OAI.Algebra.Finitistic.Bar.PatternTensorCoherence +OAI.Algebra.Finitistic.Bar.Projection +OAI.Algebra.Finitistic.Bar.ProjectiveTail +OAI.Algebra.Finitistic.Bar.RecursiveBlockIndex +OAI.Algebra.Finitistic.Bar.RecursivePrefixInclusions +OAI.Algebra.Finitistic.Bar.RecursiveSuffixCoefficient +OAI.Algebra.Finitistic.Bar.RecursiveSuffixDifferential +OAI.Algebra.Finitistic.Bar.RecursiveSuffixEmbedding +OAI.Algebra.Finitistic.Bar.RecursiveSuffixFaces +OAI.Algebra.Finitistic.Bar.RecursiveSuffixInduction +OAI.Algebra.Finitistic.Bar.RecursiveSuffixSums +OAI.Algebra.Finitistic.Bar.RecursiveSuffixTotal +OAI.Algebra.Finitistic.Bar.RecursiveTotalDifferential +OAI.Algebra.Finitistic.Bar.RecursiveTotalFlatten +OAI.Algebra.Finitistic.Bar.ResolutionDerived +OAI.Algebra.Finitistic.Bar.SignedBlockExplicit +OAI.Algebra.Finitistic.Bar.SignedBlockModel +OAI.Algebra.Finitistic.Bar.SplitProjectiveTail +OAI.Algebra.Finitistic.Bar.Splitting +OAI.Algebra.Finitistic.Bar.StrictSupportExtension +OAI.Algebra.Finitistic.Bar.SuffixNaturality +OAI.Algebra.Finitistic.Bar.SuffixParityFaces +OAI.Algebra.Finitistic.Bar.SupportedInnerCoordinates +OAI.Algebra.Finitistic.Bar.SupportedOuterCoordinates +OAI.Algebra.Finitistic.Bar.TensorModel +OAI.Algebra.Finitistic.Bar.TotalAdditive +OAI.Algebra.Finitistic.Bar.TotalBar +OAI.Algebra.Finitistic.Bar.TotalBarComparison +OAI.Algebra.Finitistic.Bar.TotalBarContraction +OAI.Algebra.Finitistic.Bar.TotalBarDerived +OAI.Algebra.Finitistic.Bar.TotalBarFunctor +OAI.Algebra.Finitistic.Bar.TotalBarResolution +OAI.Algebra.Finitistic.Bar.TotalBarTensor +OAI.Algebra.Finitistic.Bar.TotalMap +OAI.Algebra.Finitistic.Bar.TwoSided +OAI.Algebra.Finitistic.Bar.TwoSidedBarFunctor +OAI.Algebra.Finitistic.Bar.TwoSidedWeight +OAI.Algebra.Finitistic.Bar.Weight +OAI.Algebra.Finitistic.Basic +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentationEpi +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentationQuasiIso +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentedResolution +OAI.Algebra.Finitistic.Bimodule.BimoduleBalancedTensor +OAI.Algebra.Finitistic.Bimodule.BimoduleBar +OAI.Algebra.Finitistic.Bimodule.BimoduleBarComparisonIso +OAI.Algebra.Finitistic.Bimodule.BimoduleBarComparisonMap +OAI.Algebra.Finitistic.Bimodule.BimoduleBarIteration +OAI.Algebra.Finitistic.Bimodule.BimoduleBarResolution +OAI.Algebra.Finitistic.Bimodule.BimoduleBarStalk +OAI.Algebra.Finitistic.Bimodule.BimoduleBarTensorComparison +OAI.Algebra.Finitistic.Bimodule.BimoduleBoundedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleComparison +OAI.Algebra.Finitistic.Bimodule.BimoduleDerived +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedInterval +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedShift +OAI.Algebra.Finitistic.Bimodule.BimoduleExactRows +OAI.Algebra.Finitistic.Bimodule.BimoduleFiniteRowsAcyclic +OAI.Algebra.Finitistic.Bimodule.BimoduleInputFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleInputNaturality +OAI.Algebra.Finitistic.Bimodule.BimoduleLeftNaturality +OAI.Algebra.Finitistic.Bimodule.BimoduleLeftTotalMap +OAI.Algebra.Finitistic.Bimodule.BimoduleResolutionBarAPI +OAI.Algebra.Finitistic.Bimodule.BimoduleScalarEvaluation +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftCoherence +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftColumns +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftHorizontal +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftTotal +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleDifferential +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleEvaluation +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleTerms +OAI.Algebra.Finitistic.Bimodule.BimoduleStalkTotal +OAI.Algebra.Finitistic.Bimodule.BimoduleTensor +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorAcross +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorUnderlying +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorVertexBridge +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalCoefficient +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalDifferential +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalInsertion +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalShortExact +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalTermMaps +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalTerms +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalUnderlying +OAI.Algebra.Finitistic.Bimodule.BimoduleVertex +OAI.Algebra.Finitistic.Bimodule.BoundedBimoduleDerived +OAI.Algebra.Finitistic.Dimension.PDAllSimples +OAI.Algebra.Finitistic.Dimension.PDBalancedRight +OAI.Algebra.Finitistic.Dimension.PDBarDetection +OAI.Algebra.Finitistic.Dimension.PDBarQuotient +OAI.Algebra.Finitistic.Dimension.PDBarQuotientAction +OAI.Algebra.Finitistic.Dimension.PDBarTensorComparison +OAI.Algebra.Finitistic.Dimension.PDBaseBarConsumer +OAI.Algebra.Finitistic.Dimension.PDCoverRadical +OAI.Algebra.Finitistic.Dimension.PDCovers +OAI.Algebra.Finitistic.Dimension.PDDerivedBarConsumer +OAI.Algebra.Finitistic.Dimension.PDDetection +OAI.Algebra.Finitistic.Dimension.PDDimension +OAI.Algebra.Finitistic.Dimension.PDLowerBound +OAI.Algebra.Finitistic.Dimension.PDMinimalData +OAI.Algebra.Finitistic.Dimension.PDMinimalResolution +OAI.Algebra.Finitistic.Dimension.PDRadical +OAI.Algebra.Finitistic.Dimension.PDResidueAssociativity +OAI.Algebra.Finitistic.Dimension.PDResidueBaseBar +OAI.Algebra.Finitistic.Dimension.PDResidueProjection +OAI.Algebra.Finitistic.Dimension.PDResidueRing +OAI.Algebra.Finitistic.Dimension.PDResidueScalar +OAI.Algebra.Finitistic.Dimension.PDResidueSemisimple +OAI.Algebra.Finitistic.Dimension.PDResidueTensor +OAI.Algebra.Finitistic.Dimension.PDResolutionDetection +OAI.Algebra.Finitistic.Dimension.PDSimpleTensor +OAI.Algebra.Finitistic.Dimension.PDSquareZero +OAI.Algebra.Finitistic.Dimension.PDSquareZeroResidue +OAI.Algebra.Finitistic.Dimension.PDTensorFunctor +OAI.Algebra.Finitistic.Dimension.PDTor +OAI.Algebra.Finitistic.Encoding.ArrowBasisIso +OAI.Algebra.Finitistic.Encoding.AuxiliaryQuadraticPresentation +OAI.Algebra.Finitistic.Encoding.DirectedBound +OAI.Algebra.Finitistic.Encoding.EncodingGenerators +OAI.Algebra.Finitistic.Encoding.EncodingLinearity +OAI.Algebra.Finitistic.Encoding.EncodingModuleAssembly +OAI.Algebra.Finitistic.Encoding.FiniteBasisIso +OAI.Algebra.Finitistic.Encoding.PathBasisIso +OAI.Algebra.Finitistic.Encoding.PresentationReindex +OAI.Algebra.Finitistic.Encoding.QuadraticCoefficients +OAI.Algebra.Finitistic.Encoding.QuadraticEncoding +OAI.Algebra.Finitistic.Encoding.QuadraticPresentation +OAI.Algebra.Finitistic.Encoding.RelationBasisAction +OAI.Algebra.Finitistic.Encoding.RelationBasisCoefficients +OAI.Algebra.Finitistic.Encoding.RelationMatrixSequence +OAI.Algebra.Finitistic.Encoding.RelationPathCoordinates +OAI.Algebra.Finitistic.Encoding.RelationSequence +OAI.Algebra.Finitistic.Encoding.RelationVertexCoordinates +OAI.Algebra.Finitistic.Encoding.RelationVertexSequence +OAI.Algebra.Finitistic.Encoding.ThreeVertexAlgebra +OAI.Algebra.Finitistic.Iteration.AdditiveIterateAmplitude +OAI.Algebra.Finitistic.Iteration.BinomialBiproduct +OAI.Algebra.Finitistic.Iteration.BinomialEvenIteration +OAI.Algebra.Finitistic.Iteration.BinomialIndex +OAI.Algebra.Finitistic.Iteration.BinomialIteration +OAI.Algebra.Finitistic.Iteration.BinomialVanishing +OAI.Algebra.Finitistic.Iteration.FiniteIntegerIterate +OAI.Algebra.Finitistic.Iteration.FunctorObjectIteration +OAI.Algebra.Finitistic.Iteration.IntegerIterateAmplitude +OAI.Algebra.Finitistic.Iteration.IntegerIterateExtinction +OAI.Algebra.Finitistic.Iteration.IntegerIterateSupport +OAI.Algebra.Finitistic.Iteration.ObjectwiseSplitting +OAI.Algebra.Finitistic.Localization.AdditiveSplitImage +OAI.Algebra.Finitistic.Localization.AmbientQuotientEvaluation +OAI.Algebra.Finitistic.Localization.BoundedDerivedEmbedding +OAI.Algebra.Finitistic.Localization.BoundedHomotopy +OAI.Algebra.Finitistic.Localization.BoundedQuotientEvaluation +OAI.Algebra.Finitistic.Localization.BoundedQuotientGenerators +OAI.Algebra.Finitistic.Localization.BoundedRepresentatives +OAI.Algebra.Finitistic.Localization.ChainRepresentatives +OAI.Algebra.Finitistic.Localization.CompletedCornerEvaluation +OAI.Algebra.Finitistic.Localization.CompletedDerivedEvaluation +OAI.Algebra.Finitistic.Localization.CompletedImageEvaluation +OAI.Algebra.Finitistic.Localization.CompletedOddDoubleEvaluation +OAI.Algebra.Finitistic.Localization.CompletedShiftEvaluation +OAI.Algebra.Finitistic.Localization.CompletedShiftedCornerEvaluation +OAI.Algebra.Finitistic.Localization.ConcreteChainRepresentatives +OAI.Algebra.Finitistic.Localization.ConcreteFixedDiagram +OAI.Algebra.Finitistic.Localization.ConcreteQuadraticDiagram +OAI.Algebra.Finitistic.Localization.ConcreteTensorEvaluation +OAI.Algebra.Finitistic.Localization.DerivedActionCompatibility +OAI.Algebra.Finitistic.Localization.DerivedTruncationCohomology +OAI.Algebra.Finitistic.Localization.DiagramEvaluationSquares +OAI.Algebra.Finitistic.Localization.DiagramLifting +OAI.Algebra.Finitistic.Localization.EvaluationFromAlgebra +OAI.Algebra.Finitistic.Localization.EvaluationLinear +OAI.Algebra.Finitistic.Localization.EvaluationModule +OAI.Algebra.Finitistic.Localization.EvaluationVertexDiagram +OAI.Algebra.Finitistic.Localization.FiniteDerivedEvaluation +OAI.Algebra.Finitistic.Localization.FiniteEvaluationTarget +OAI.Algebra.Finitistic.Localization.FiniteProjectiveHomotopy +OAI.Algebra.Finitistic.Localization.FiniteSumTransport +OAI.Algebra.Finitistic.Localization.FiniteSupportReindex +OAI.Algebra.Finitistic.Localization.FixedDiagram +OAI.Algebra.Finitistic.Localization.FormalSummandAction +OAI.Algebra.Finitistic.Localization.HomotopyEvaluation +OAI.Algebra.Finitistic.Localization.HomotopyVertexEvaluation +OAI.Algebra.Finitistic.Localization.IdempotentImageEvaluation +OAI.Algebra.Finitistic.Localization.IntegerExtensionFunctor +OAI.Algebra.Finitistic.Localization.KaroubiEvaluation +OAI.Algebra.Finitistic.Localization.LocalizedEvaluationStructure +OAI.Algebra.Finitistic.Localization.ModuleActionCompatibility +OAI.Algebra.Finitistic.Localization.NativeArrowBridge +OAI.Algebra.Finitistic.Localization.NativeBoundedDerived +OAI.Algebra.Finitistic.Localization.NativeProjectiveModel +OAI.Algebra.Finitistic.Localization.NativeSingleEvaluation +OAI.Algebra.Finitistic.Localization.NormalizedQuotientAction +OAI.Algebra.Finitistic.Localization.OddDouble +OAI.Algebra.Finitistic.Localization.PresentedActionCompatibility +OAI.Algebra.Finitistic.Localization.PresentedQuotientAction +OAI.Algebra.Finitistic.Localization.ProjectiveComplexes +OAI.Algebra.Finitistic.Localization.QuotientAction +OAI.Algebra.Finitistic.Localization.QuotientActionEvaluation +OAI.Algebra.Finitistic.Localization.QuotientRelations +OAI.Algebra.Finitistic.Localization.SignedCochainShift +OAI.Algebra.Finitistic.Localization.SingleDegreeNaturality +OAI.Algebra.Finitistic.Localization.SourceActionEvaluation +OAI.Algebra.Finitistic.Localization.SourceCornerEvaluation +OAI.Algebra.Finitistic.Localization.SourceEvaluation +OAI.Algebra.Finitistic.Localization.SourceImageEvaluation +OAI.Algebra.Finitistic.Localization.SourceLinear +OAI.Algebra.Finitistic.Localization.SourceModelBridge +OAI.Algebra.Finitistic.Localization.SourceOddDoubleEvaluation +OAI.Algebra.Finitistic.Localization.SourceQuotientAction +OAI.Algebra.Finitistic.Localization.SourceShiftLinear +OAI.Algebra.Finitistic.Localization.SourceVerdier +OAI.Algebra.Finitistic.Localization.SplitComponentExact +OAI.Algebra.Finitistic.Localization.TensorCohomologyDiagram +OAI.Algebra.Finitistic.Localization.TensorEvaluationComparison +OAI.Algebra.Finitistic.Localization.TensorEvaluationFunctor +OAI.Algebra.Finitistic.Localization.ThickEvaluation +OAI.Algebra.Finitistic.Localization.TruncationSplitNaturality +OAI.Algebra.Finitistic.Localization.TruncationStalkNaturality +OAI.Algebra.Finitistic.Localization.TwoConeVerdier +OAI.Algebra.Finitistic.Localization.TwoDegreeExtVanishing +OAI.Algebra.Finitistic.Localization.TwoDegreeFormalityNaturality +OAI.Algebra.Finitistic.Localization.TwoDegreeSplitting +OAI.Algebra.Finitistic.Localization.UnderlyingRepresentatives +OAI.Algebra.Finitistic.Localization.VectorComplexFormality +OAI.Algebra.Finitistic.Localization.VectorIdempotentCompleteness +OAI.Algebra.Finitistic.Localization.VerdierEvaluationExact +OAI.Algebra.Finitistic.Main +OAI.Algebra.Finitistic.Ordinary.OrdinaryAssociativeTensorModules +OAI.Algebra.Finitistic.Ordinary.OrdinaryAssociativityNaturality +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedActions +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAssociativeTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAugmentationQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleCoefficientEquiv +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleCoefficients +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleResolutionProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalForget +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockComplexes +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockDerived +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockModules +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainAlgebra +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainDirected +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryCochain +OAI.Algebra.Finitistic.Ordinary.OrdinaryComplexAction +OAI.Algebra.Finitistic.Ordinary.OrdinaryComplexTensorMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryCompression +OAI.Algebra.Finitistic.Ordinary.OrdinaryConeCoordinates +OAI.Algebra.Finitistic.Ordinary.OrdinaryConeQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryDerivedIterates +OAI.Algebra.Finitistic.Ordinary.OrdinaryDerivedSquareComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteColumnComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteConeReindex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteConeTriangular +OAI.Algebra.Finitistic.Ordinary.OrdinaryFinitePiSupport +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteTotalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstBlockTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstBlockTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstComponentExact +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstDerivedCompatibility +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstDerivedRetraction +OAI.Algebra.Finitistic.Ordinary.OrdinaryFixedTensorFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFreeTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFreeTensorExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryFullTensorComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFullTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryFunctorExtension +OAI.Algebra.Finitistic.Ordinary.OrdinaryGenuineBimoduleComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryGlobalDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryIntegerResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryLeftTensorCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryLeftTensorMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryMiddleTensorFunctors +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalComplexMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalForget +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalObjects +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalSingle +OAI.Algebra.Finitistic.Ordinary.OrdinaryPairComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryPairQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductComponent +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductOpposite +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductSecondDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductSplitting +OAI.Algebra.Finitistic.Ordinary.OrdinaryProjectiveTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionExact +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionModels +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryRestrictionHomology +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedRestriction +OAI.Algebra.Finitistic.Ordinary.OrdinaryRightProjective +OAI.Algebra.Finitistic.Ordinary.OrdinarySecondBlockTensor +OAI.Algebra.Finitistic.Ordinary.OrdinarySecondBlockTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryShiftDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryShiftSign +OAI.Algebra.Finitistic.Ordinary.OrdinarySignedExactness +OAI.Algebra.Finitistic.Ordinary.OrdinarySimulationComparison +OAI.Algebra.Finitistic.Ordinary.OrdinarySingleTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinarySingleTensorTotal +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceBimoduleTotal +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceDerivedComparison +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceResolutionModels +OAI.Algebra.Finitistic.Ordinary.OrdinarySupportedExtension +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimap +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimoduleComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimoduleResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorColumnAcyclic +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDerivedFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDifferential +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDirected +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorFiniteMatrix +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorGlobalDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorIdeal +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorIdealActions +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorInputMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorMixedSign +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorResolutionComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorRightRestriction +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalAcyclic +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorVertex +OAI.Algebra.Finitistic.Ordinary.OrdinaryTerminal +OAI.Algebra.Finitistic.Ordinary.OrdinaryTerminalResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTriangularExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryTwoSidedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryVertexCompression +OAI.Algebra.Finitistic.Ordinary.OrdinaryXAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryXBlockComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryXDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryXResolution +OAI.Algebra.Finitistic.Rectification.AdjacentArrowSum +OAI.Algebra.Finitistic.Rectification.ArrowCompatibility +OAI.Algebra.Finitistic.Rectification.ArrowVertex +OAI.Algebra.Finitistic.Rectification.BiprodEvaluationSquare +OAI.Algebra.Finitistic.Rectification.CanonicalArrowCompatibility +OAI.Algebra.Finitistic.Rectification.ColumnComplex +OAI.Algebra.Finitistic.Rectification.ColumnFinite +OAI.Algebra.Finitistic.Rectification.ColumnProperties +OAI.Algebra.Finitistic.Rectification.ConcreteAdjacentGraded +OAI.Algebra.Finitistic.Rectification.CornerArrowCoordinates +OAI.Algebra.Finitistic.Rectification.CornerColumnComplex +OAI.Algebra.Finitistic.Rectification.CornerColumnPaths +OAI.Algebra.Finitistic.Rectification.CornerPathTransport +OAI.Algebra.Finitistic.Rectification.CornerProjection +OAI.Algebra.Finitistic.Rectification.CornerSpaces +OAI.Algebra.Finitistic.Rectification.CornerTensor +OAI.Algebra.Finitistic.Rectification.DiagramAssembly +OAI.Algebra.Finitistic.Rectification.ExactProducts +OAI.Algebra.Finitistic.Rectification.ExternalTensor +OAI.Algebra.Finitistic.Rectification.FiltrationExactness +OAI.Algebra.Finitistic.Rectification.FinalGradedAcyclic +OAI.Algebra.Finitistic.Rectification.FirstVertex +OAI.Algebra.Finitistic.Rectification.FullTensorProperties +OAI.Algebra.Finitistic.Rectification.FullTensorRectification +OAI.Algebra.Finitistic.Rectification.GradedVertexAcyclic +OAI.Algebra.Finitistic.Rectification.InducedColumns +OAI.Algebra.Finitistic.Rectification.InducedDerivedFunctor +OAI.Algebra.Finitistic.Rectification.InducedDiagram +OAI.Algebra.Finitistic.Rectification.InducedRectification +OAI.Algebra.Finitistic.Rectification.LeftVertexHomology +OAI.Algebra.Finitistic.Rectification.RectificationAcyclic +OAI.Algebra.Finitistic.Rectification.RectificationLemma +OAI.Algebra.Finitistic.Rectification.RectificationTotal +OAI.Algebra.Finitistic.Rectification.SecondVertex +OAI.Algebra.Finitistic.Rectification.SourceFiltration +OAI.Algebra.Finitistic.Rectification.SourceFiltrationComplex +OAI.Algebra.Finitistic.Rectification.SourceFiltrationCone +OAI.Algebra.Finitistic.Rectification.SourceFiltrationExact +OAI.Algebra.Finitistic.Rectification.SourceFiltrationReal +OAI.Algebra.Finitistic.Rectification.TensorArrowComparison +OAI.Algebra.Finitistic.Rectification.TensorArrowSum +OAI.Algebra.Finitistic.Rectification.TensorComplex +OAI.Algebra.Finitistic.Rectification.TensorProjection +OAI.Algebra.Finitistic.Rectification.ThirdVertex +OAI.Algebra.Finitistic.Rectification.ThirdVertexFiltration +OAI.Algebra.Finitistic.Rectification.TotalExact +OAI.Algebra.Finitistic.Rectification.TotalFinite +OAI.Algebra.Finitistic.Rectification.TotalFunctorial +OAI.Algebra.Finitistic.Rectification.TotalInterchange +OAI.Algebra.Finitistic.Rectification.VertexCategoricalAssembly +OAI.Algebra.Finitistic.Rectification.VertexColumnComplex +OAI.Algebra.Finitistic.Rectification.VertexColumnModels +OAI.Algebra.Finitistic.Rectification.VertexDecomposition +OAI.Algebra.Finitistic.Rectification.VertexFunctor +OAI.Algebra.Finitistic.Rectification.VertexHomology +OAI.Algebra.Finitistic.Rectification.VertexHomotopyEquivalence +OAI.Algebra.Finitistic.Rectification.VertexModuleAssembly +OAI.Algebra.Finitistic.Rectification.VertexProjectives +OAI.Algebra.Finitistic.Rectification.VertexTensorEvaluation +OAI.Algebra.Finitistic.Rectification.VertexTensorLinear +OAI.Algebra.Finitistic.Rectification.VertexTotalProperties +OAI.Algebra.Finitistic.Rectification.VertexZeroTotal +OAI.Algebra.Finitistic.Rectification.ZeroColumnTotal +OAI.Algebra.Finitistic.Rectification.ZeroLastColumn +OAI.Algebra.Finitistic.Selected.SelectedBarBimodule +OAI.Algebra.Finitistic.Selected.SelectedBarComparison +OAI.Algebra.Finitistic.Selected.SelectedBarPowers +OAI.Algebra.Finitistic.Selected.SelectedBarResolution +OAI.Algebra.Finitistic.Selected.SelectedBarStart +OAI.Algebra.Finitistic.Selected.SelectedBaseIterates +OAI.Algebra.Finitistic.Selected.SelectedChainAction +OAI.Algebra.Finitistic.Selected.SelectedChainDiagram +OAI.Algebra.Finitistic.Selected.SelectedChainHomology +OAI.Algebra.Finitistic.Selected.SelectedCohomologyAssembly +OAI.Algebra.Finitistic.Selected.SelectedCohomologyVanishing +OAI.Algebra.Finitistic.Selected.SelectedCountCohomology +OAI.Algebra.Finitistic.Selected.SelectedCountExtinction +OAI.Algebra.Finitistic.Selected.SelectedCountPDConsumer +OAI.Algebra.Finitistic.Selected.SelectedDerivedFunctor +OAI.Algebra.Finitistic.Selected.SelectedDiagramEvaluation +OAI.Algebra.Finitistic.Selected.SelectedFiniteAmplitude +OAI.Algebra.Finitistic.Selected.SelectedFiniteTensorEvaluation +OAI.Algebra.Finitistic.Selected.SelectedFirstBlockFamily +OAI.Algebra.Finitistic.Selected.SelectedFixedDiagram +OAI.Algebra.Finitistic.Selected.SelectedImageComparison +OAI.Algebra.Finitistic.Selected.SelectedIteration +OAI.Algebra.Finitistic.Selected.SelectedMinimalResolution +OAI.Algebra.Finitistic.Selected.SelectedNativeAction +OAI.Algebra.Finitistic.Selected.SelectedNativeEvaluation +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryAlgebra +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryDimension +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryModules +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryOrbit +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryResolution +OAI.Algebra.Finitistic.Selected.SelectedPDBarConsumer +OAI.Algebra.Finitistic.Selected.SelectedPDConclusion +OAI.Algebra.Finitistic.Selected.SelectedPDDetection +OAI.Algebra.Finitistic.Selected.SelectedPDResidueProjection +OAI.Algebra.Finitistic.Selected.SelectedPDUpperConsumer +OAI.Algebra.Finitistic.Selected.SelectedRealization +OAI.Algebra.Finitistic.Selected.SelectedRectification +OAI.Algebra.Finitistic.Selected.SelectedReferenceCohomology +OAI.Algebra.Finitistic.Selected.SelectedShiftedRealization +OAI.Algebra.Finitistic.Selected.SelectedTargetHomology +OAI.Algebra.Finitistic.Selected.SelectedTensor +OAI.Algebra.Finitistic.Selected.SelectedTensorComparison +OAI.Algebra.Finitistic.Selected.SelectedTensorSplitting +OAI.Algebra.Finitistic.Selected.SelectedUnderlyingHomology +OAI.Algebra.Finitistic.Selected.SelectedVertexTensorEvaluation +OAI.Algebra.Finitistic.Selected.SelectedWindow +OAI.Algebra.Finitistic.Selection.AuxiliaryGroupAlgebraPresentation +OAI.Algebra.Finitistic.Selection.CharacterModule +OAI.Algebra.Finitistic.Selection.FinitePresentation +OAI.Algebra.Finitistic.Selection.FiniteQuotient +OAI.Algebra.Finitistic.Selection.FiniteSelectionFamily +OAI.Algebra.Finitistic.Selection.GroupAlgebraPresentation +OAI.Algebra.Finitistic.Selection.GroupSelection +OAI.Algebra.Finitistic.Selection.MatrixModel +OAI.Algebra.Finitistic.Selection.SelectionAlgebra +OAI.Algebra.Finitistic.Selection.SelectionCharacter +OAI.Algebra.Finitistic.Selection.SelectionEncoding +OAI.Algebra.Finitistic.Selection.SelectionIteration +OAI.Algebra.Finitistic.Selection.TestModules +OAI.Algebra.Finitistic.Tensor.BalancedFreeLeft +OAI.Algebra.Finitistic.Tensor.BalancedProjectiveLeft +OAI.Algebra.Finitistic.Tensor.BalancedTensor +OAI.Algebra.Finitistic.Tensor.BalancedTensorMaps +OAI.Algebra.Finitistic.Tensor.BalancedVertexFunctor +OAI.Algebra.Finitistic.Tensor.BalancedVertexImage +OAI.Algebra.Finitistic.Tensor.IdempotentTensor +OAI.Algebra.Finitistic.Tensor.IdempotentTensorMaps +OAI.Algebra.FinitisticAsymmetry.Asymmetry +OAI.Algebra.FinitisticAsymmetry.Augmentation.Directed +OAI.Algebra.FinitisticAsymmetry.Augmentation.SplitBasic +OAI.Algebra.FinitisticAsymmetry.Derived.BoundedGeneration +OAI.Algebra.FinitisticAsymmetry.Derived.ComplexSums +OAI.Algebra.FinitisticAsymmetry.Derived.Coproducts +OAI.Algebra.FinitisticAsymmetry.Derived.DerivedSums +OAI.Algebra.FinitisticAsymmetry.Derived.ExactExtension +OAI.Algebra.FinitisticAsymmetry.Derived.LocalizingRetracts +OAI.Algebra.FinitisticAsymmetry.Derived.ModuleGeneration +OAI.Algebra.FinitisticAsymmetry.Derived.ModuleSums +OAI.Algebra.FinitisticAsymmetry.Derived.Telescopes +OAI.Algebra.FinitisticAsymmetry.Derived.Truncations +OAI.Algebra.FinitisticAsymmetry.Derived.UpperTruncation +OAI.Algebra.FinitisticAsymmetry.Kasch.FiniteDimension +OAI.Algebra.FinitisticAsymmetry.Kasch.ProjectiveSplitting +OAI.Algebra.FinitisticAsymmetry.Kasch.Radical +OAI.Algebra.FinitisticAsymmetry.Main +OAI.Algebra.FinitisticAsymmetry.Model +OAI.Algebra.FinitisticAsymmetry.Nakayama.Coinduction +OAI.Algebra.FinitisticAsymmetry.Nakayama.Minimality +OAI.Algebra.FinitisticAsymmetry.Nakayama.Modules +OAI.Algebra.FinitisticAsymmetry.Rickard.FiniteFamilies +OAI.Algebra.FinitisticAsymmetry.Rickard.InjectiveSums +OAI.Algebra.FinitisticAsymmetry.Rickard.NonGeneration +OAI.Algebra.FinitisticAsymmetry.Rickard.Orthogonal +OAI.Algebra.FinitisticAsymmetry.Rickard.OrthogonalStalks +OAI.Algebra.FinitisticAsymmetry.Rickard.ReducedProducts +OAI.Algebra.FinitisticAsymmetry.Rickard.ResolutionFamily +OAI.Algebra.FinitisticAsymmetry.Transport.DerivedEquivalence +OAI.Algebra.FinitisticAsymmetry.Transport.DiagramMaps +OAI.Algebra.FinitisticAsymmetry.Transport.FiniteModules +OAI.Algebra.FinitisticAsymmetry.Transport.InjectiveGeneration +OAI.Algebra.FinitisticAsymmetry.Transport.ProjectiveDimension +OAI.Algebra.FinitisticAsymmetry.Transport.ScalarRestriction +OAI.Algebra.FinitisticAsymmetry.Triangular.Algebra +OAI.Algebra.FinitisticAsymmetry.Triangular.Augmentation +OAI.Algebra.FinitisticAsymmetry.Triangular.Generation +OAI.Algebra.FinitisticAsymmetry.Triangular.InjectiveCorners +OAI.Algebra.FinitisticAsymmetry.Triangular.InjectiveResolution +OAI.Algebra.FinitisticAsymmetry.Triangular.Socle +OAI.Algebra.FinitisticAsymmetry.ZeroDimensions diff --git a/tasks/finitistic-asymmetry/solution/reference.py b/tasks/finitistic-asymmetry/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/finitistic-asymmetry/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/finitistic-asymmetry/solution/solve.sh b/tasks/finitistic-asymmetry/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..21078e8a86badbc6fbc98d7e56dc10e09e81e691 --- /dev/null +++ b/tasks/finitistic-asymmetry/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FinitisticAsymmetry, i.e. module OAI.Algebra.FinitisticAsymmetry.Main and the +# 588 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.FinitisticAsymmetry.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FinitisticAsymmetry" diff --git a/tasks/finitistic-asymmetry/task.toml b/tasks/finitistic-asymmetry/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..896c0c3a37620f5fa7a77cdda630b3f345357f30 --- /dev/null +++ b/tasks/finitistic-asymmetry/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/finitistic-asymmetry" +version = "1.0.0" +description = "Prove FinitisticAsymmetry (openai/math family 198: A counterexample to the little finitistic-dimension conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FinitisticAsymmetry.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FinitisticAsymmetry" +family = "198" +family_title = "A counterexample to the little finitistic-dimension conjecture" +subject = "Algebra" +theorems = ["OAI.LittleFinitistic.extreme_left_right_asymmetry"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.FinitisticAsymmetry.Main" +reference_modules = 588 +reference_lean_bytes = 2251227 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2003 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13726 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/finitistic-asymmetry/tests/Challenge.lean b/tasks/finitistic-asymmetry/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4870c0c503c37dd908b25a348245b95dbc13ddab --- /dev/null +++ b/tasks/finitistic-asymmetry/tests/Challenge.lean @@ -0,0 +1,41 @@ +import Mathlib + +namespace OAI + +noncomputable section +open CategoryTheory + +namespace LittleFinitistic +universe u +variable (A : Type u) [Ring A] + +attribute [-instance] CompletePartialOrder.toSupSet in +def littleFinitisticDimension : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : Module.Finite A M) (_ : projectiveDimension M < ⊤), + projectiveDimension M + +def bigFinitisticDimension : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : projectiveDimension M < ⊤), projectiveDimension M + +def InjectivesGenerate : Prop := + letI := HasDerivedCategory.standard (ModuleCat.{u} A) + ∀ (P : ObjectProperty (DerivedCategory (ModuleCat.{u} A))), + P.IsClosedUnderIsomorphisms → P.IsTriangulated → + (∀ I : Type u, P.IsClosedUnderColimitsOfShape (Discrete I)) → + (∀ (M : ModuleCat.{u} A), Injective M → + P ((DerivedCategory.singleFunctor (ModuleCat.{u} A) 0).obj M)) → + ∀ X, P X + +theorem extreme_left_right_asymmetry : + ∃ (Λ : Type) (_ : Ring Λ) (_ : Algebra ℂ Λ), + FiniteDimensional ℂ Λ ∧ + littleFinitisticDimension Λ = ⊤ ∧ bigFinitisticDimension Λ = ⊤ ∧ + littleFinitisticDimension Λᵐᵒᵖ = 0 ∧ bigFinitisticDimension Λᵐᵒᵖ = 0 ∧ + ¬ InjectivesGenerate Λ ∧ InjectivesGenerate Λᵐᵒᵖ := by + sorry + +end LittleFinitistic + +end + +end OAI diff --git a/tasks/finitistic-asymmetry/tests/grade.py b/tasks/finitistic-asymmetry/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/finitistic-asymmetry/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/finitistic-asymmetry/tests/task.json b/tasks/finitistic-asymmetry/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c4335c81deb6f664f9dc065983251e4fa6fad1dc --- /dev/null +++ b/tasks/finitistic-asymmetry/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FinitisticAsymmetry", + "comparator": { + "theorem_names": [ + "OAI.LittleFinitistic.extreme_left_right_asymmetry" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12826 +} \ No newline at end of file diff --git a/tasks/finitistic-asymmetry/tests/test.sh b/tasks/finitistic-asymmetry/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/finitistic-asymmetry/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/fixed-clause-threshold/environment/Dockerfile b/tasks/fixed-clause-threshold/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/fixed-clause-threshold/environment/fetch_mathlib.sh b/tasks/fixed-clause-threshold/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/fixed-clause-threshold/environment/lake-manifest.json b/tasks/fixed-clause-threshold/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/fixed-clause-threshold/environment/lakefile.lean b/tasks/fixed-clause-threshold/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/fixed-clause-threshold/environment/lean_setup.sh b/tasks/fixed-clause-threshold/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/fixed-clause-threshold/environment/pack_submission.py b/tasks/fixed-clause-threshold/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/fixed-clause-threshold/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/fixed-clause-threshold/instruction.md b/tasks/fixed-clause-threshold/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68bd2c6213dd2cc14554e8340129e507c2c2a370 --- /dev/null +++ b/tasks/fixed-clause-threshold/instruction.md @@ -0,0 +1,107 @@ +# openai/math challenge `FixedClauseThreshold` (family 235) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 235 of the release, *Random-SAT thresholds, sharp variance and computability* +(Probability and statistical mechanics). The family as a whole: For random $k$-SAT with independent uniformly signed proper clauses sampled with replacement, proves finite positive limiting thresholds and hitting-time variance $\Theta_k(n)$ for every fixed $k\ge3$, and computability of the 3-SAT threshold. We credit Gaia Carenini with priority for resolving the threshold-existence conjecture in her concurrent \href{https://eccc.weizmann.ac.il/report/2026/229/}{ECCC TR26-229}, made public October 5, 2026; this family supplies another proof and the sharper variance and computability results. + +The challenge is `FixedClauseThreshold`, also at `/opt/openai-math/challenges/FixedClauseThreshold.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Proper clauses choose distinct variables uniformly and give them independent fair +signs. Formulas consist of independent uniform whole-clause draws with replacement. +Their satisfiability probability is the literal finite cardinality ratio. +For zero clauses this probability is one, including when there are fewer variables +than literals per clause. When there are fewer variables than literals per clause +and the clause count is positive, the ensemble is empty and its probability is zero +by the convention that division by zero is zero. + +For each fixed clause size at least three, one positive finite real threshold +governs the limits at every fixed density below or above it. There is no assertion +at the critical density, no explicit threshold value, and no varying-size claim. +-/ + +namespace FixedClauseThreshold + +abbrev Assignment (n : ℕ) := Fin n → Bool + +abbrev ProperClause (n k : ℕ) := + { C : Fin n → Option Bool // (Finset.univ.filter fun i => (C i).isSome).card = k } + +abbrev Formula (n k m : ℕ) := Fin m → ProperClause n k + +def SatisfiesClause {n k : ℕ} (σ : Assignment n) (C : ProperClause n k) : Prop := + ∃ i : Fin n, C.val i = some (σ i) + +def Satisfies {n k m : ℕ} (σ : Assignment n) (F : Formula n k m) : Prop := + ∀ j, SatisfiesClause σ (F j) + +def Satisfiable {n k m : ℕ} (F : Formula n k m) : Prop := + ∃ σ : Assignment n, Satisfies σ F + +noncomputable def properSATProbability (n k m : ℕ) : ℝ := by + classical + exact (Fintype.card { F : Formula n k m // Satisfiable F } : ℝ) / + (Fintype.card (Formula n k m) : ℝ) + +def HasLimitingThreshold (k : ℕ) : Prop := + ∃ α : ℝ, 0 < α ∧ + (∀ c : ℝ, 0 ≤ c → c < α → + Filter.Tendsto (fun n : ℕ => properSATProbability n k ⌊c * (n : ℝ)⌋₊) + Filter.atTop (nhds 1)) ∧ + (∀ c : ℝ, α < c → + Filter.Tendsto (fun n : ℕ => properSATProbability n k ⌊c * (n : ℝ)⌋₊) + Filter.atTop (nhds 0)) + +theorem main (k : ℕ) (hk : 3 ≤ k) : HasLimitingThreshold k := by + sorry + +end FixedClauseThreshold + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FixedClauseThreshold.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FixedClauseThreshold.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/fixed-clause-threshold/solution/closure.txt b/tasks/fixed-clause-threshold/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cab124c51ca6d0d0f75d479cc68aff2f38047bb9 --- /dev/null +++ b/tasks/fixed-clause-threshold/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.Probability.RandomSAT.Binomial +OAI.Probability.RandomSAT.CenterBounds +OAI.Probability.RandomSAT.CenterComparison +OAI.Probability.RandomSAT.ClauseProcess +OAI.Probability.RandomSAT.Clauses +OAI.Probability.RandomSAT.Concentration +OAI.Probability.RandomSAT.Convergence +OAI.Probability.RandomSAT.FiniteMean +OAI.Probability.RandomSAT.Forcing +OAI.Probability.RandomSAT.Interpolation +OAI.Probability.RandomSAT.Main +OAI.Probability.RandomSAT.Model +OAI.Probability.RandomSAT.Replacement +OAI.Probability.RandomSAT.Transfer +OAI.Probability.RandomSAT.Variance diff --git a/tasks/fixed-clause-threshold/solution/reference.py b/tasks/fixed-clause-threshold/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/fixed-clause-threshold/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/fixed-clause-threshold/solution/solve.sh b/tasks/fixed-clause-threshold/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f663c8fbc58e1763e8628e7d409d7880dfb45f89 --- /dev/null +++ b/tasks/fixed-clause-threshold/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FixedClauseThreshold, i.e. module OAI.Probability.RandomSAT.Main and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.RandomSAT.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FixedClauseThreshold" diff --git a/tasks/fixed-clause-threshold/task.toml b/tasks/fixed-clause-threshold/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..be17ee862b055298f97d313dc1d185529c7cadef --- /dev/null +++ b/tasks/fixed-clause-threshold/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/fixed-clause-threshold" +version = "1.0.0" +description = "Prove FixedClauseThreshold (openai/math family 235: Random-SAT thresholds, sharp variance and computability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FixedClauseThreshold.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FixedClauseThreshold" +family = "235" +family_title = "Random-SAT thresholds, sharp variance and computability" +subject = "Probability and statistical mechanics" +theorems = ["OAI.FixedClauseThreshold.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.RandomSAT.Main" +reference_modules = 15 +reference_lean_bytes = 215586 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 655 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11894 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/fixed-clause-threshold/tests/Challenge.lean b/tasks/fixed-clause-threshold/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d2f3438b04de4f842960a03718ffbd084b00bd7 --- /dev/null +++ b/tasks/fixed-clause-threshold/tests/Challenge.lean @@ -0,0 +1,56 @@ +import Mathlib + +namespace OAI + +/-! +Proper clauses choose distinct variables uniformly and give them independent fair +signs. Formulas consist of independent uniform whole-clause draws with replacement. +Their satisfiability probability is the literal finite cardinality ratio. +For zero clauses this probability is one, including when there are fewer variables +than literals per clause. When there are fewer variables than literals per clause +and the clause count is positive, the ensemble is empty and its probability is zero +by the convention that division by zero is zero. + +For each fixed clause size at least three, one positive finite real threshold +governs the limits at every fixed density below or above it. There is no assertion +at the critical density, no explicit threshold value, and no varying-size claim. +-/ + +namespace FixedClauseThreshold + +abbrev Assignment (n : ℕ) := Fin n → Bool + +abbrev ProperClause (n k : ℕ) := + { C : Fin n → Option Bool // (Finset.univ.filter fun i => (C i).isSome).card = k } + +abbrev Formula (n k m : ℕ) := Fin m → ProperClause n k + +def SatisfiesClause {n k : ℕ} (σ : Assignment n) (C : ProperClause n k) : Prop := + ∃ i : Fin n, C.val i = some (σ i) + +def Satisfies {n k m : ℕ} (σ : Assignment n) (F : Formula n k m) : Prop := + ∀ j, SatisfiesClause σ (F j) + +def Satisfiable {n k m : ℕ} (F : Formula n k m) : Prop := + ∃ σ : Assignment n, Satisfies σ F + +noncomputable def properSATProbability (n k m : ℕ) : ℝ := by + classical + exact (Fintype.card { F : Formula n k m // Satisfiable F } : ℝ) / + (Fintype.card (Formula n k m) : ℝ) + +def HasLimitingThreshold (k : ℕ) : Prop := + ∃ α : ℝ, 0 < α ∧ + (∀ c : ℝ, 0 ≤ c → c < α → + Filter.Tendsto (fun n : ℕ => properSATProbability n k ⌊c * (n : ℝ)⌋₊) + Filter.atTop (nhds 1)) ∧ + (∀ c : ℝ, α < c → + Filter.Tendsto (fun n : ℕ => properSATProbability n k ⌊c * (n : ℝ)⌋₊) + Filter.atTop (nhds 0)) + +theorem main (k : ℕ) (hk : 3 ≤ k) : HasLimitingThreshold k := by + sorry + +end FixedClauseThreshold + +end OAI diff --git a/tasks/fixed-clause-threshold/tests/grade.py b/tasks/fixed-clause-threshold/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/fixed-clause-threshold/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/fixed-clause-threshold/tests/task.json b/tasks/fixed-clause-threshold/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..918bd9b0e043715f714076bdb4cafa2de7866c4d --- /dev/null +++ b/tasks/fixed-clause-threshold/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FixedClauseThreshold", + "comparator": { + "theorem_names": [ + "OAI.FixedClauseThreshold.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10994 +} \ No newline at end of file diff --git a/tasks/fixed-clause-threshold/tests/test.sh b/tasks/fixed-clause-threshold/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/fixed-clause-threshold/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/fkcrt/environment/Dockerfile b/tasks/fkcrt/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/fkcrt/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/fkcrt/environment/fetch_mathlib.sh b/tasks/fkcrt/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/fkcrt/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/fkcrt/environment/lake-manifest.json b/tasks/fkcrt/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/fkcrt/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/fkcrt/environment/lakefile.lean b/tasks/fkcrt/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/fkcrt/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/fkcrt/environment/lean_setup.sh b/tasks/fkcrt/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/fkcrt/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/fkcrt/environment/pack_submission.py b/tasks/fkcrt/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/fkcrt/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/fkcrt/instruction.md b/tasks/fkcrt/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..dda23913b435b6305f78b4cc93585f77d2a10f64 --- /dev/null +++ b/tasks/fkcrt/instruction.md @@ -0,0 +1,265 @@ +# openai/math challenge `FKCRT` (family 211) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 211 of the release, *Geometry, diffusion, and spectra of random planar maps* +(Probability and statistical mechanics). The family as a whole: Critical Fortuin–Kasteleyn planar maps converge to Liouville quantum gravity spheres for $04$, establishing the surface-to-tree geometric transition. For FK–Ising and spanning-tree-weighted maps, stationary random walks converge to Liouville Brownian motion on the limiting sphere. The FK–Ising spectral result also gives convergence of eigenvalues and heat traces, using the stated Brownian/LQG inputs. + +The challenge is `FKCRT`, also at `/opt/openai-math/challenges/FKCRT.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Finite Fortuin–Kasteleyn maps and the Brownian continuum random tree. + +All combinatorial maps below have a distinguished dart 0 and are quotiented +by orientation-preserving dart relabellings fixing that dart. A rotation system +with Euler characteristic 2 encodes precisely a connected oriented-sphere map. +No simplicity restriction is imposed. Vertices and edges are rotation and +edge-reversal orbits, respectively. Every edge subset is included in the law. +The index n here represents source size n+1, so the limit is through ALL +positive edge sizes, not a subsequence. + +MetricMeasureData packages the actual distance, measurable space and measure, +without using arbitrary representatives of measure-preserving isometry classes +as a global typeclass. Valid objects are compact metric probability spaces. +The GHP extended distance is the infimum over common isometric embeddings, +represented by pseudometrics on the disjoint union; zero cross distances simply +identify points in the common ambient space. Tests are bounded functions +continuous for that distance on valid objects. Thus GHP convergence is written +in its bounded-continuous-test (weak distributional convergence) definition. + +A standard normalized Brownian excursion is represented in its standard +three-dimensional Bessel-bridge realization: the norm of three independent +standard Brownian bridges of duration 1. No rescaling of the excursion is used. +-/ + +noncomputable section +open Set Filter MeasureTheory ProbabilityTheory +open scoped Topology BigOperators ENNReal NNReal + +namespace FKCRT + +abbrev Dart (n : ℕ) := Fin (2 * (n + 1)) + +abbrev Orbit {n : ℕ} (s : Equiv.Perm (Dart n)) := + Quotient (Equiv.Perm.SameCycle.setoid s) + +def orbit {n : ℕ} (s : Equiv.Perm (Dart n)) (d : Dart n) : Orbit s := + Quotient.mk _ d + +instance {n : ℕ} (s : Equiv.Perm (Dart n)) : Fintype (Orbit s) := Fintype.ofFinite _ + +/-- The spanning graph with precisely the edges in A, with loops omitted only +from adjacency: they still exist as edge orbits, have FK weight, and contribute +two darts to the degree measure. Omitting loops does not change distance or k. -/ +def spanningGraph {n : ℕ} (a s : Equiv.Perm (Dart n)) (A : Set (Orbit a)) : + SimpleGraph (Orbit s) := + SimpleGraph.fromRel fun v w => + ∃ d : Dart n, orbit a d ∈ A ∧ orbit s d = v ∧ orbit s (a d) = w + +/-- Labelled connected orientable genus-zero rotation systems. -/ +def MapConditions {n : ℕ} (P : Equiv.Perm (Dart n) × Equiv.Perm (Dart n)) : Prop := + Function.Involutive P.1 ∧ (∀ d, P.1 d ≠ d) ∧ + (spanningGraph P.1 P.2 Set.univ).Connected ∧ + Nat.card (Orbit P.2) + Nat.card (Orbit (P.2 * P.1)) = n + 3 + +abbrev LabelledMap (n : ℕ) := + {P : Equiv.Perm (Dart n) × Equiv.Perm (Dart n) // MapConditions P} + +/-- Root-preserving isomorphism of oriented maps (both dart permutations intertwine). -/ +def MapIso {n : ℕ} (M N : LabelledMap n) : Prop := + ∃ r : Equiv.Perm (Dart n), r 0 = 0 ∧ + (∀ d, N.val.1 (r d) = r (M.val.1 d)) ∧ + (∀ d, N.val.2 (r d) = r (M.val.2 d)) + +abbrev RootedMap (n : ℕ) := Quotient (Relation.EqvGen.setoid (@MapIso n)) + +instance (n : ℕ) : Fintype (RootedMap n) := Fintype.ofFinite _ + +def reversal {n : ℕ} (M : RootedMap n) : Equiv.Perm (Dart n) := M.out.val.1 + +def rotation {n : ℕ} (M : RootedMap n) : Equiv.Perm (Dart n) := M.out.val.2 + +abbrev Vertex {n : ℕ} (M : RootedMap n) := Orbit (rotation M) +abbrev Edge {n : ℕ} (M : RootedMap n) := Orbit (reversal M) + +def graph {n : ℕ} (M : RootedMap n) (A : Set (Edge M)) : SimpleGraph (Vertex M) := + spanningGraph (reversal M) (rotation M) A + +/-- The source k_M(A), including isolated vertices. -/ +def clusterCount {n : ℕ} (M : RootedMap n) (A : Finset (Edge M)) : ℕ := + Nat.card (graph M (A : Set (Edge M))).ConnectedComponent + +/-- Exact decorated finite-map weight from eq:finite-law. -/ +def fkWeight {n : ℕ} (q : ℝ) (M : RootedMap n) (A : Finset (Edge M)) : ℝ := + Real.rpow q ((clusterCount M A : ℝ) + + ((A.card : ℝ) - (Nat.card (Vertex M) : ℝ)) / 2) + +def partition (q : ℝ) (n : ℕ) : ℝ := + ∑ M : RootedMap n, ∑ A : Finset (Edge M), fkWeight q M A + +/-- Unbundled presentation of a measured metric space; validity is specified below. -/ +structure MetricMeasureData where + Carrier : Type + distance : Carrier → Carrier → ℝ + measurableSpace : MeasurableSpace Carrier + mass : @Measure Carrier measurableSpace + +/-- Exactly compact metric probability spaces, with their Borel sigma algebras. -/ +def MetricMeasureData.Valid (X : MetricMeasureData) : Prop := + ∃ m : MetricSpace X.Carrier, + letI := m + (∀ x y, dist x y = X.distance x y) ∧ + CompactSpace X.Carrier ∧ X.measurableSpace = borel X.Carrier ∧ + X.mass Set.univ = 1 + +/-- Normalized degree measure is uniform dart mass pushed to vertices. -/ +def degreeMass {n : ℕ} (M : RootedMap n) : + @Measure (Vertex M) ⊤ := + letI : MeasurableSpace (Vertex M) := ⊤ + ∑ d : Dart n, ENNReal.ofReal (1 / (2 * (n + 1) : ℝ)) • + Measure.dirac (orbit (rotation M) d) + +/-- Root and decoration are not included in the metric probability space. -/ +def mapSpace {n : ℕ} (scale : ℝ) (M : RootedMap n) : MetricMeasureData where + Carrier := Vertex M + distance v w := scale * ((graph M Set.univ).dist v w : ℝ) + measurableSpace := ⊤ + mass := degreeMass M + +/-- An ambient pseudometric on the disjoint union giving isometric embeddings. -/ +def Amalgamates (X Y : MetricMeasureData) + (m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier)) : Prop := + letI := m + (∀ x x', dist (Sum.inl x : X.Carrier ⊕ Y.Carrier) (Sum.inl x') = X.distance x x') ∧ + (∀ y y', dist (Sum.inr y : X.Carrier ⊕ Y.Carrier) (Sum.inr y') = Y.distance y y') + +def ambientCost (X Y : MetricMeasureData) + (m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier)) : ℝ≥0∞ := + letI := m + letI : MeasurableSpace (X.Carrier ⊕ Y.Carrier) := borel _ + max (Metric.hausdorffEDist (Set.range (Sum.inl : X.Carrier → X.Carrier ⊕ Y.Carrier)) + (Set.range (Sum.inr : Y.Carrier → X.Carrier ⊕ Y.Carrier))) + (levyProkhorovEDist + (@Measure.map X.Carrier (X.Carrier ⊕ Y.Carrier) X.measurableSpace + (borel _) Sum.inl X.mass) + (@Measure.map Y.Carrier (X.Carrier ⊕ Y.Carrier) Y.measurableSpace + (borel _) Sum.inr Y.mass)) + +/-- The common-isometric-embedding definition of the source GHP distance. -/ +def ghpEDist (X Y : MetricMeasureData) : ℝ≥0∞ := + ⨅ m : {m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier) // Amalgamates X Y m}, + ambientCost X Y m.val + +/-- Bounded continuous tests on compact metric probability spaces modulo +measure-preserving isometry, expressed on presentations. -/ +def IsGHPTest (F : MetricMeasureData → ℝ) : Prop := + (∃ C : ℝ, ∀ X, |F X| ≤ C) ∧ + ∀ X, X.Valid → ∀ ε : ℝ, 0 < ε → ∃ δ : ℝ, 0 < δ ∧ + ∀ Y, Y.Valid → ghpEDist X Y < ENNReal.ofReal δ → |F Y - F X| < ε + +/-- Source excursion pseudometric, with the closed interval minimum. -/ +def excursionDist (e : unitInterval → ℝ) (s t : unitInterval) : ℝ := + e s + e t - 2 * sInf (e '' Set.uIcc s t) + +abbrev ExcursionTree (e : unitInterval → ℝ) := + Quotient (Relation.EqvGen.setoid (fun s t => excursionDist e s t = 0)) + +def treeProjection (e : unitInterval → ℝ) (t : unitInterval) : ExcursionTree e := + Quotient.mk _ t + +/-- The quotient by d_e=0, its induced metric, and pushforward of uniform time. +The equivalence closure is redundant for continuous e; the induced distance +is independent of representatives, as required by the pseudometric proof. -/ +def treeSpace (e : unitInterval → ℝ) : MetricMeasureData := + letI : TopologicalSpace (ExcursionTree e) := + TopologicalSpace.coinduced (treeProjection e) inferInstance + letI : MeasurableSpace (ExcursionTree e) := borel _ + { Carrier := ExcursionTree e + distance := fun x y => excursionDist e x.out y.out + measurableSpace := borel _ + mass := Measure.map (treeProjection e) (volume : Measure unitInterval) } + +/-- Standard normalized excursion, realized as the 3D Bessel bridge. -/ +def standardExcursion {Ω : Type} (B : Fin 3 → ℝ≥0 → Ω → ℝ) (ω : Ω) + (t : unitInterval) : ℝ := + Real.sqrt (∑ i : Fin 3, (B i ⟨(t : ℝ), t.property.1⟩ ω - + (t : ℝ) * B i 1 ω) ^ 2) + +/-- Exact expectation under the finite law, with n+1 edges. -/ +def finiteExpectation (q scale : ℝ) (n : ℕ) (F : MetricMeasureData → ℝ) : ℝ := + ∑ M : RootedMap n, ∑ A : Finset (Edge M), + (fkWeight q M A / partition q n) * F (mapSpace scale M) + +def brownianExpectation {Ω : Type} [MeasurableSpace Ω] (P : Measure Ω) + (B : Fin 3 → ℝ≥0 → Ω → ℝ) (F : MetricMeasureData → ℝ) : ℝ := + ∫ ω, F (treeSpace (standardExcursion B ω)) ∂P + +/-- thm:main. The quantifiers over Brownian realizations express that the limit +is the standard excursion-tree law, not a coupling-specific object. -/ +def MainStatement : Prop := + ∀ q : ℝ, 4 < q → ∃ c : ℝ, 0 < c ∧ + ∀ (Ω : Type) (mΩ : MeasurableSpace Ω) (P : @Measure Ω mΩ), + @IsProbabilityMeasure Ω mΩ P → + ∀ B : Fin 3 → ℝ≥0 → Ω → ℝ, + (∀ i, @IsBrownianReal Ω mΩ (B i) P) → + @iIndepFun Ω (Fin 3) mΩ (fun _ => ℝ≥0 → ℝ) (fun _ => inferInstance) + (fun i ω t => B i t ω) P → + ∀ F : MetricMeasureData → ℝ, IsGHPTest F → + Tendsto (fun n : ℕ => finiteExpectation q (c / Real.sqrt (n + 1)) n F) + atTop (𝓝 (@brownianExpectation Ω mΩ P B F)) + + +/-- Finite FK maps converge in GHP distribution to the standard Brownian CRT. -/ +theorem finite_fk_maps_converge_to_brownian_crt : MainStatement := by + sorry + +end FKCRT +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FKCRT.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FKCRT.finite_fk_maps_converge_to_brownian_crt` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/fkcrt/solution/closure.txt b/tasks/fkcrt/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6f375676b719511a0cb76ddcf0385f68102a067 --- /dev/null +++ b/tasks/fkcrt/solution/closure.txt @@ -0,0 +1,61 @@ +OAI.Probability.FKMaps.BlockCritical +OAI.Probability.FKMaps.BlockLaw +OAI.Probability.FKMaps.BridgeLimit +OAI.Probability.FKMaps.CanonicalBijection +OAI.Probability.FKMaps.ConditionedTrees +OAI.Probability.FKMaps.ConditionedWalk +OAI.Probability.FKMaps.Convergence +OAI.Probability.FKMaps.CoreCompression +OAI.Probability.FKMaps.CoreMetric +OAI.Probability.FKMaps.CoreWords +OAI.Probability.FKMaps.CornerInsertion +OAI.Probability.FKMaps.CornerInverse +OAI.Probability.FKMaps.CornerMass +OAI.Probability.FKMaps.ExcursionGeometry +OAI.Probability.FKMaps.ExcursionKernel +OAI.Probability.FKMaps.ExcursionLaw +OAI.Probability.FKMaps.FiniteLaw +OAI.Probability.FKMaps.GHPBounds +OAI.Probability.FKMaps.GraphWedge +OAI.Probability.FKMaps.HeightBounds +OAI.Probability.FKMaps.HeightCoding +OAI.Probability.FKMaps.HeightTightness +OAI.Probability.FKMaps.Inventory +OAI.Probability.FKMaps.InventoryDrift +OAI.Probability.FKMaps.InventoryRenewal +OAI.Probability.FKMaps.InventoryStopping +OAI.Probability.FKMaps.LadderCuts +OAI.Probability.FKMaps.LadderRecords +OAI.Probability.FKMaps.MapCycles +OAI.Probability.FKMaps.MapEncoding +OAI.Probability.FKMaps.MarkedBounds +OAI.Probability.FKMaps.MarkedSpines +OAI.Probability.FKMaps.Matching +OAI.Probability.FKMaps.MeasuredCoding +OAI.Probability.FKMaps.MetricLimit +OAI.Probability.FKMaps.Model +OAI.Probability.FKMaps.NodeMetric +OAI.Probability.FKMaps.NodeOrder +OAI.Probability.FKMaps.Noncrossing +OAI.Probability.FKMaps.Offspring +OAI.Probability.FKMaps.PathCLT +OAI.Probability.FKMaps.PieceLaws +OAI.Probability.FKMaps.PieceWalks +OAI.Probability.FKMaps.PlanarActivity +OAI.Probability.FKMaps.PlaneTrees +OAI.Probability.FKMaps.RadialBridge +OAI.Probability.FKMaps.RootedLaw +OAI.Probability.FKMaps.SeamLengths +OAI.Probability.FKMaps.SimpleWalk +OAI.Probability.FKMaps.SpineBounds +OAI.Probability.FKMaps.SpineMoments +OAI.Probability.FKMaps.StationaryCuts +OAI.Probability.FKMaps.TourActivity +OAI.Probability.FKMaps.TraceLimit +OAI.Probability.FKMaps.TreeCode +OAI.Probability.FKMaps.UniformSeams +OAI.Probability.FKMaps.Vervaat +OAI.Probability.FKMaps.WalkBounds +OAI.Probability.FKMaps.WordCoefficients +OAI.Probability.FKMaps.WordLaw +OAI.Probability.FKMaps.WordMaps diff --git a/tasks/fkcrt/solution/reference.py b/tasks/fkcrt/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/fkcrt/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/fkcrt/solution/solve.sh b/tasks/fkcrt/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cc1aea509894e4d739aca83116737c29a55b3384 --- /dev/null +++ b/tasks/fkcrt/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FKCRT, i.e. module OAI.Probability.FKMaps.Convergence and the +# 61 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.FKMaps.Convergence /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FKCRT" diff --git a/tasks/fkcrt/task.toml b/tasks/fkcrt/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..14c406a474b463d01db4e41c50bd1c63891b13c7 --- /dev/null +++ b/tasks/fkcrt/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/fkcrt" +version = "1.0.0" +description = "Prove FKCRT (openai/math family 211: Geometry, diffusion, and spectra of random planar maps) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FKCRT.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FKCRT" +family = "211" +family_title = "Geometry, diffusion, and spectra of random planar maps" +subject = "Probability and statistical mechanics" +theorems = ["OAI.FKCRT.finite_fk_maps_converge_to_brownian_crt"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.FKMaps.Convergence" +reference_modules = 61 +reference_lean_bytes = 1877777 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1071 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13389 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/fkcrt/tests/Challenge.lean b/tasks/fkcrt/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6de8bdf8338daf8b10380195a55011dd7278e7e3 --- /dev/null +++ b/tasks/fkcrt/tests/Challenge.lean @@ -0,0 +1,214 @@ +import Mathlib + +namespace OAI + +/-! +Finite Fortuin–Kasteleyn maps and the Brownian continuum random tree. + +All combinatorial maps below have a distinguished dart 0 and are quotiented +by orientation-preserving dart relabellings fixing that dart. A rotation system +with Euler characteristic 2 encodes precisely a connected oriented-sphere map. +No simplicity restriction is imposed. Vertices and edges are rotation and +edge-reversal orbits, respectively. Every edge subset is included in the law. +The index n here represents source size n+1, so the limit is through ALL +positive edge sizes, not a subsequence. + +MetricMeasureData packages the actual distance, measurable space and measure, +without using arbitrary representatives of measure-preserving isometry classes +as a global typeclass. Valid objects are compact metric probability spaces. +The GHP extended distance is the infimum over common isometric embeddings, +represented by pseudometrics on the disjoint union; zero cross distances simply +identify points in the common ambient space. Tests are bounded functions +continuous for that distance on valid objects. Thus GHP convergence is written +in its bounded-continuous-test (weak distributional convergence) definition. + +A standard normalized Brownian excursion is represented in its standard +three-dimensional Bessel-bridge realization: the norm of three independent +standard Brownian bridges of duration 1. No rescaling of the excursion is used. +-/ + +noncomputable section +open Set Filter MeasureTheory ProbabilityTheory +open scoped Topology BigOperators ENNReal NNReal + +namespace FKCRT + +abbrev Dart (n : ℕ) := Fin (2 * (n + 1)) + +abbrev Orbit {n : ℕ} (s : Equiv.Perm (Dart n)) := + Quotient (Equiv.Perm.SameCycle.setoid s) + +def orbit {n : ℕ} (s : Equiv.Perm (Dart n)) (d : Dart n) : Orbit s := + Quotient.mk _ d + +instance {n : ℕ} (s : Equiv.Perm (Dart n)) : Fintype (Orbit s) := Fintype.ofFinite _ + +/-- The spanning graph with precisely the edges in A, with loops omitted only +from adjacency: they still exist as edge orbits, have FK weight, and contribute +two darts to the degree measure. Omitting loops does not change distance or k. -/ +def spanningGraph {n : ℕ} (a s : Equiv.Perm (Dart n)) (A : Set (Orbit a)) : + SimpleGraph (Orbit s) := + SimpleGraph.fromRel fun v w => + ∃ d : Dart n, orbit a d ∈ A ∧ orbit s d = v ∧ orbit s (a d) = w + +/-- Labelled connected orientable genus-zero rotation systems. -/ +def MapConditions {n : ℕ} (P : Equiv.Perm (Dart n) × Equiv.Perm (Dart n)) : Prop := + Function.Involutive P.1 ∧ (∀ d, P.1 d ≠ d) ∧ + (spanningGraph P.1 P.2 Set.univ).Connected ∧ + Nat.card (Orbit P.2) + Nat.card (Orbit (P.2 * P.1)) = n + 3 + +abbrev LabelledMap (n : ℕ) := + {P : Equiv.Perm (Dart n) × Equiv.Perm (Dart n) // MapConditions P} + +/-- Root-preserving isomorphism of oriented maps (both dart permutations intertwine). -/ +def MapIso {n : ℕ} (M N : LabelledMap n) : Prop := + ∃ r : Equiv.Perm (Dart n), r 0 = 0 ∧ + (∀ d, N.val.1 (r d) = r (M.val.1 d)) ∧ + (∀ d, N.val.2 (r d) = r (M.val.2 d)) + +abbrev RootedMap (n : ℕ) := Quotient (Relation.EqvGen.setoid (@MapIso n)) + +instance (n : ℕ) : Fintype (RootedMap n) := Fintype.ofFinite _ + +def reversal {n : ℕ} (M : RootedMap n) : Equiv.Perm (Dart n) := M.out.val.1 + +def rotation {n : ℕ} (M : RootedMap n) : Equiv.Perm (Dart n) := M.out.val.2 + +abbrev Vertex {n : ℕ} (M : RootedMap n) := Orbit (rotation M) +abbrev Edge {n : ℕ} (M : RootedMap n) := Orbit (reversal M) + +def graph {n : ℕ} (M : RootedMap n) (A : Set (Edge M)) : SimpleGraph (Vertex M) := + spanningGraph (reversal M) (rotation M) A + +/-- The source k_M(A), including isolated vertices. -/ +def clusterCount {n : ℕ} (M : RootedMap n) (A : Finset (Edge M)) : ℕ := + Nat.card (graph M (A : Set (Edge M))).ConnectedComponent + +/-- Exact decorated finite-map weight from eq:finite-law. -/ +def fkWeight {n : ℕ} (q : ℝ) (M : RootedMap n) (A : Finset (Edge M)) : ℝ := + Real.rpow q ((clusterCount M A : ℝ) + + ((A.card : ℝ) - (Nat.card (Vertex M) : ℝ)) / 2) + +def partition (q : ℝ) (n : ℕ) : ℝ := + ∑ M : RootedMap n, ∑ A : Finset (Edge M), fkWeight q M A + +/-- Unbundled presentation of a measured metric space; validity is specified below. -/ +structure MetricMeasureData where + Carrier : Type + distance : Carrier → Carrier → ℝ + measurableSpace : MeasurableSpace Carrier + mass : @Measure Carrier measurableSpace + +/-- Exactly compact metric probability spaces, with their Borel sigma algebras. -/ +def MetricMeasureData.Valid (X : MetricMeasureData) : Prop := + ∃ m : MetricSpace X.Carrier, + letI := m + (∀ x y, dist x y = X.distance x y) ∧ + CompactSpace X.Carrier ∧ X.measurableSpace = borel X.Carrier ∧ + X.mass Set.univ = 1 + +/-- Normalized degree measure is uniform dart mass pushed to vertices. -/ +def degreeMass {n : ℕ} (M : RootedMap n) : + @Measure (Vertex M) ⊤ := + letI : MeasurableSpace (Vertex M) := ⊤ + ∑ d : Dart n, ENNReal.ofReal (1 / (2 * (n + 1) : ℝ)) • + Measure.dirac (orbit (rotation M) d) + +/-- Root and decoration are not included in the metric probability space. -/ +def mapSpace {n : ℕ} (scale : ℝ) (M : RootedMap n) : MetricMeasureData where + Carrier := Vertex M + distance v w := scale * ((graph M Set.univ).dist v w : ℝ) + measurableSpace := ⊤ + mass := degreeMass M + +/-- An ambient pseudometric on the disjoint union giving isometric embeddings. -/ +def Amalgamates (X Y : MetricMeasureData) + (m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier)) : Prop := + letI := m + (∀ x x', dist (Sum.inl x : X.Carrier ⊕ Y.Carrier) (Sum.inl x') = X.distance x x') ∧ + (∀ y y', dist (Sum.inr y : X.Carrier ⊕ Y.Carrier) (Sum.inr y') = Y.distance y y') + +def ambientCost (X Y : MetricMeasureData) + (m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier)) : ℝ≥0∞ := + letI := m + letI : MeasurableSpace (X.Carrier ⊕ Y.Carrier) := borel _ + max (Metric.hausdorffEDist (Set.range (Sum.inl : X.Carrier → X.Carrier ⊕ Y.Carrier)) + (Set.range (Sum.inr : Y.Carrier → X.Carrier ⊕ Y.Carrier))) + (levyProkhorovEDist + (@Measure.map X.Carrier (X.Carrier ⊕ Y.Carrier) X.measurableSpace + (borel _) Sum.inl X.mass) + (@Measure.map Y.Carrier (X.Carrier ⊕ Y.Carrier) Y.measurableSpace + (borel _) Sum.inr Y.mass)) + +/-- The common-isometric-embedding definition of the source GHP distance. -/ +def ghpEDist (X Y : MetricMeasureData) : ℝ≥0∞ := + ⨅ m : {m : PseudoMetricSpace (X.Carrier ⊕ Y.Carrier) // Amalgamates X Y m}, + ambientCost X Y m.val + +/-- Bounded continuous tests on compact metric probability spaces modulo +measure-preserving isometry, expressed on presentations. -/ +def IsGHPTest (F : MetricMeasureData → ℝ) : Prop := + (∃ C : ℝ, ∀ X, |F X| ≤ C) ∧ + ∀ X, X.Valid → ∀ ε : ℝ, 0 < ε → ∃ δ : ℝ, 0 < δ ∧ + ∀ Y, Y.Valid → ghpEDist X Y < ENNReal.ofReal δ → |F Y - F X| < ε + +/-- Source excursion pseudometric, with the closed interval minimum. -/ +def excursionDist (e : unitInterval → ℝ) (s t : unitInterval) : ℝ := + e s + e t - 2 * sInf (e '' Set.uIcc s t) + +abbrev ExcursionTree (e : unitInterval → ℝ) := + Quotient (Relation.EqvGen.setoid (fun s t => excursionDist e s t = 0)) + +def treeProjection (e : unitInterval → ℝ) (t : unitInterval) : ExcursionTree e := + Quotient.mk _ t + +/-- The quotient by d_e=0, its induced metric, and pushforward of uniform time. +The equivalence closure is redundant for continuous e; the induced distance +is independent of representatives, as required by the pseudometric proof. -/ +def treeSpace (e : unitInterval → ℝ) : MetricMeasureData := + letI : TopologicalSpace (ExcursionTree e) := + TopologicalSpace.coinduced (treeProjection e) inferInstance + letI : MeasurableSpace (ExcursionTree e) := borel _ + { Carrier := ExcursionTree e + distance := fun x y => excursionDist e x.out y.out + measurableSpace := borel _ + mass := Measure.map (treeProjection e) (volume : Measure unitInterval) } + +/-- Standard normalized excursion, realized as the 3D Bessel bridge. -/ +def standardExcursion {Ω : Type} (B : Fin 3 → ℝ≥0 → Ω → ℝ) (ω : Ω) + (t : unitInterval) : ℝ := + Real.sqrt (∑ i : Fin 3, (B i ⟨(t : ℝ), t.property.1⟩ ω - + (t : ℝ) * B i 1 ω) ^ 2) + +/-- Exact expectation under the finite law, with n+1 edges. -/ +def finiteExpectation (q scale : ℝ) (n : ℕ) (F : MetricMeasureData → ℝ) : ℝ := + ∑ M : RootedMap n, ∑ A : Finset (Edge M), + (fkWeight q M A / partition q n) * F (mapSpace scale M) + +def brownianExpectation {Ω : Type} [MeasurableSpace Ω] (P : Measure Ω) + (B : Fin 3 → ℝ≥0 → Ω → ℝ) (F : MetricMeasureData → ℝ) : ℝ := + ∫ ω, F (treeSpace (standardExcursion B ω)) ∂P + +/-- thm:main. The quantifiers over Brownian realizations express that the limit +is the standard excursion-tree law, not a coupling-specific object. -/ +def MainStatement : Prop := + ∀ q : ℝ, 4 < q → ∃ c : ℝ, 0 < c ∧ + ∀ (Ω : Type) (mΩ : MeasurableSpace Ω) (P : @Measure Ω mΩ), + @IsProbabilityMeasure Ω mΩ P → + ∀ B : Fin 3 → ℝ≥0 → Ω → ℝ, + (∀ i, @IsBrownianReal Ω mΩ (B i) P) → + @iIndepFun Ω (Fin 3) mΩ (fun _ => ℝ≥0 → ℝ) (fun _ => inferInstance) + (fun i ω t => B i t ω) P → + ∀ F : MetricMeasureData → ℝ, IsGHPTest F → + Tendsto (fun n : ℕ => finiteExpectation q (c / Real.sqrt (n + 1)) n F) + atTop (𝓝 (@brownianExpectation Ω mΩ P B F)) + + +/-- Finite FK maps converge in GHP distribution to the standard Brownian CRT. -/ +theorem finite_fk_maps_converge_to_brownian_crt : MainStatement := by + sorry + +end FKCRT +end + +end OAI diff --git a/tasks/fkcrt/tests/grade.py b/tasks/fkcrt/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/fkcrt/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/fkcrt/tests/task.json b/tasks/fkcrt/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cdf3c70377d3f255d133f4d098b9826fb9f130a2 --- /dev/null +++ b/tasks/fkcrt/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FKCRT", + "comparator": { + "theorem_names": [ + "OAI.FKCRT.finite_fk_maps_converge_to_brownian_crt" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12489 +} \ No newline at end of file diff --git a/tasks/fkcrt/tests/test.sh b/tasks/fkcrt/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/fkcrt/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/forced-navier-stokes-computation/environment/Dockerfile b/tasks/forced-navier-stokes-computation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/forced-navier-stokes-computation/environment/fetch_mathlib.sh b/tasks/forced-navier-stokes-computation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/forced-navier-stokes-computation/environment/lake-manifest.json b/tasks/forced-navier-stokes-computation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/forced-navier-stokes-computation/environment/lakefile.lean b/tasks/forced-navier-stokes-computation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/forced-navier-stokes-computation/environment/lean_setup.sh b/tasks/forced-navier-stokes-computation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/forced-navier-stokes-computation/environment/pack_submission.py b/tasks/forced-navier-stokes-computation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/forced-navier-stokes-computation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/forced-navier-stokes-computation/instruction.md b/tasks/forced-navier-stokes-computation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4c353bd18db4e5f34a1384c634376ab20b7fda99 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/instruction.md @@ -0,0 +1,283 @@ +# openai/math challenge `ForcedNavierStokesComputation` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `ForcedNavierStokesComputation`, also at `/opt/openai-math/challenges/ForcedNavierStokesComputation.lean`: + +```lean +import Mathlib + +/-! A single main result: effective forced Navier–Stokes computation detected by a +fixed particle entering a fixed open box, exactly when the encoded machine halts. -/ + +namespace OAI.BalancedTransport +namespace Recorder +inductive Direction where + | stay | left | right + deriving DecidableEq + +structure Transition (Q Γ : Type*) where + state : Q + write : Γ + move : Direction +end Recorder + +structure FiniteMachine where + states : ℕ + symbols : ℕ + initial : Fin (states + 1) + blank : Fin (symbols + 1) + transition : Fin (states + 1) → Fin (symbols + 1) → + Option (Recorder.Transition (Fin (states + 1)) (Fin (symbols + 1))) + +abbrev Input (M : FiniteMachine) := List (Fin (M.symbols + 1)) + +structure TapeConfiguration (M : FiniteMachine) where + state : Fin (M.states + 1) + head : ℤ + tape : ℤ → Fin (M.symbols + 1) + +def initialConfiguration (M : FiniteMachine) (w : Input M) : TapeConfiguration M := + ⟨M.initial, 0, fun z => if 0 ≤ z then w[z.toNat]?.getD M.blank else M.blank⟩ + +def machineStep (M : FiniteMachine) (c : TapeConfiguration M) : Option (TapeConfiguration M) := + (M.transition c.state (c.tape c.head)).map fun v => + ⟨v.state, c.head + (match v.move with | .stay => 0 | .left => -1 | .right => 1), + Function.update c.tape c.head v.write⟩ + +def Halts (M : FiniteMachine) (w : Input M) : Prop := + ∃ c, Relation.ReflTransGen (fun c d => machineStep M c = some d) + (initialConfiguration M w) c ∧ machineStep M c = none + +def Recorder.Direction.number : Recorder.Direction → ℕ + | .stay => 0 + | .left => 1 + | .right => 2 + +def FiniteMachine.code (M : FiniteMachine) : ℕ := + Encodable.encode (M.states, M.symbols, M.initial.val, M.blank.val, + (List.finRange (M.states + 1)).map fun q => + (List.finRange (M.symbols + 1)).map fun a => + (M.transition q a).map fun v => (v.state.val, v.write.val, v.move.number)) + +def inputCode (M : FiniteMachine) (w : Input M) : ℕ := + Encodable.encode (M.code, w.map Fin.val) + +abbrev Space := Fin 3 → ℝ +abbrev Field (F : Type*) := ℝ → Space → F +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev Family (F : Type*) := (M : FiniteMachine) → Input M → F +abbrev MaterialFlow := ℝ → Space → Space +abbrev MultiIndex := List (Option (Fin 3)) +abbrev RationalPoint := ℚ × (Fin 3 → ℚ) + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] + +def timeD (v : Field F) : Field F := + fun t x => derivWithin (fun s => v s x) (Set.Ici 0) t + +def spaceD (i : Fin 3) (v : Field F) : Field F := + fun t x => fderiv ℝ (v t) x (Pi.single i 1) + +def mixedD : MultiIndex → Field F → Field F + | [], v => v + | none :: a, v => timeD (mixedD a v) + | some i :: a, v => spaceD i (mixedD a v) + +def spatialD : List (Fin 3) → Field F → Field F + | [], v => v + | i :: a, v => spaceD i (spatialD a v) + +def Smooth (v : Field F) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) (fun z : ℝ × Space => v z.1 z.2) (Set.Ici 0 ×ˢ Set.univ) + +def BoundedMixed (v : Field F) : Prop := + ∀ a : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ ∀ t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ C + +def CH (k : ℕ) (v : Field F) : Prop := + ∀ a : List (Fin 3), a.length ≤ k → + ∃ V : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → (V t : Space → F) =ᵐ[volume] spatialD a v t + +def C1L2 (v : Field F) : Prop := + ∃ V W : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ ContinuousOn W (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → + (V t : Space → F) =ᵐ[volume] v t ∧ + (W t : Space → F) =ᵐ[volume] timeD v t ∧ + HasDerivWithinAt V (W t) (Set.Ici 0) t + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i, spaceD i u t x i + +def laplacian (u : Velocity) : Velocity := + fun t x => ∑ i, spaceD i (spaceD i u) t x + +def convection (u : Velocity) : Velocity := + fun t x => ∑ i, (u t x i) • spaceD i u t x + +def gradient (p : Pressure) (t : ℝ) (x : Space) : Space := + fun i => spaceD i p t x + +def affineForce (f₀ f₁ : Velocity) (ν : ℝ) : Velocity := + fun t x => f₀ t x + ν • f₁ t x + +def inertialCoefficient (u : Velocity) : Velocity := + fun t x => timeD u t x + convection u t x + +def viscousCoefficient (u : Velocity) : Velocity := + fun t x => -laplacian u t x + +def ZeroDataSolution (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + Smooth u ∧ Smooth p ∧ + (∀ x, u 0 x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, div u t x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, + timeD u t x + convection u t x = + -gradient p t x + ν • laplacian u t x + f t x) + +def BoundedOnFiniteSlabs (u : Velocity) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, 0 ≤ C ∧ + ∀ t ∈ Set.Icc (0 : ℝ) T, ∀ x, + ‖u t x‖ ≤ C ∧ ∀ i : Fin 3, ‖spaceD i u t x‖ ≤ C + +def ComparisonClass (u : Velocity) (p : Pressure) : Prop := + CH 2 u ∧ C1L2 u ∧ BoundedOnFiniteSlabs u ∧ + ∃ c : ℝ → ℝ, CH 1 (fun t x => p t x - c t) + +def UniqueInComparison (ν : ℝ) (f U : Velocity) : Prop := + ∀ u p, ZeroDataSolution ν f u p → ComparisonClass u p → + (∀ t, 0 ≤ t → ∀ x, u t x = U t x) ∧ + (∀ t, 0 ≤ t → ∀ x y, p t x = p t y) + +def CommonCompactSupport (U f₀ f₁ : Velocity) : Prop := + ∃ K : Set Space, IsCompact K ∧ + ∀ t, 0 ≤ t → ∀ x, x ∉ K → U t x = 0 ∧ f₀ t x = 0 ∧ f₁ t x = 0 + +def PeriodicAfterOne (v : Velocity) : Prop := + ∀ t, 1 ≤ t → ∀ x, v (t + 1) x = v t x + +def IsMaterialFlow (u : Velocity) (X : MaterialFlow) : Prop := + (∀ a, X 0 a = a) ∧ + ∀ a t, 0 ≤ t → HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t + +def fixedLabel : Space := ![4, 0, 0] + +def observer : Set Space := + Set.pi Set.univ (fun _ : Fin 3 => Set.Ioo (-1 : ℝ) 2) + +def rationalSpace (x : Fin 3 → ℚ) : Space := fun i => (x i : ℝ) + +def error (n : ℕ) : ℝ := (2 : ℝ)⁻¹ ^ n + +def EffectiveFamily (v : Family Velocity) : Prop := + ∃ E : (ℕ × MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : (ℕ × MultiIndex) → ℕ, + ∃ R : ℕ → ℕ, + Computable E ∧ Computable b ∧ Computable R ∧ + (∀ M w a z n, 0 ≤ z.1 → ∀ i, + |(E (inputCode M w, a, z, n) i : ℝ) - + mixedD a (v M w) (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ M w a t, 0 ≤ t → ∀ x, + ‖mixedD a (v M w) t x‖ ≤ (b (inputCode M w, a) : ℝ)) ∧ + (∀ M w t, 0 ≤ t → ∀ x, + (R (inputCode M w) : ℝ) < ‖x‖ → v M w t x = 0) + +def EffectiveFieldIn (O : Set (ℕ →. ℕ)) (v : Velocity) : Prop := + ∃ E : (MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : MultiIndex → ℕ, + ComputableIn O E ∧ ComputableIn O b ∧ + (∀ a z n, 0 ≤ z.1 → ∀ i, + |(E (a, z, n) i : ℝ) - + mixedD a v (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ a t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ (b a : ℝ)) + +def RealName (name : ℕ → ℚ) (x : ℝ) : Prop := + ∀ n, |(name n : ℝ) - x| ≤ error n + +def ComputableReal (x : ℝ) : Prop := + ∃ name : ℕ → ℚ, Computable name ∧ RealName name x + +def nameOracle (name : ℕ → ℚ) : ℕ →. ℕ := + fun n => Part.some (Encodable.encode (name n)) + +end + +theorem balanced_three_stack_realization : + ∃ U f₀ f₁ : Family Velocity, + ∃ X : Family MaterialFlow, + ∃ repeated : FiniteMachine → Velocity, + EffectiveFamily U ∧ EffectiveFamily f₀ ∧ EffectiveFamily f₁ ∧ + (∀ M, Function.Periodic (repeated M) 1) ∧ + ∀ (M : FiniteMachine) (w : Input M), + Smooth (U M w) ∧ Smooth (f₀ M w) ∧ Smooth (f₁ M w) ∧ + f₀ M w = inertialCoefficient (U M w) ∧ + f₁ M w = viscousCoefficient (U M w) ∧ + CommonCompactSupport (U M w) (f₀ M w) (f₁ M w) ∧ + BoundedMixed (U M w) ∧ + PeriodicAfterOne (U M w) ∧ + (∀ t, 1 ≤ t → ∀ x, U M w t x = repeated M t x) ∧ + ComparisonClass (U M w) (fun _ _ => 0) ∧ + IsMaterialFlow (U M w) (X M w) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ X M w t fixedLabel ∈ observer) ↔ Halts M w) ∧ + ∀ ν : ℝ, 0 < ν → + let f := affineForce (f₀ M w) (f₁ M w) ν + ZeroDataSolution ν f (U M w) (fun _ _ => 0) ∧ + Smooth f ∧ BoundedMixed f ∧ PeriodicAfterOne f ∧ + UniqueInComparison ν f (U M w) ∧ + (ComputableReal ν → EffectiveFieldIn ∅ f) ∧ + (∀ name : ℕ → ℚ, RealName name ν → EffectiveFieldIn {nameOracle name} f) := by + sorry + +end OAI.BalancedTransport +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ForcedNavierStokesComputation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BalancedTransport.balanced_three_stack_realization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/forced-navier-stokes-computation/solution/closure.txt b/tasks/forced-navier-stokes-computation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6d87f6d4892f06758dccc01aa579cbfcd6c64dd5 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/solution/closure.txt @@ -0,0 +1,60 @@ +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.BoxCoding +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Bridge +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.CompactFamilies +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Comparison +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.CompiledGeometry +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ComputabilityRules +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ComputableInitial +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Deformation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveArithmetic +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveConstruction +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveExp +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveGluing +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EffectiveLog +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Elementary +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryCalculus +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryFields +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryMotion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryParking +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryRouting +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ElementaryTemplate +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Energy +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EnergyCurve +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.EnergySlice +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FieldBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FiniteSimulator +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.FlatBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Loading +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MachineHalting +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MachineRecursion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Material +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Model +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Motion +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MotionField +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericAlgebra +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericBounds +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericDifferentiation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericEvaluation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericPrograms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.NumericScopes +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.OracleComputability +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Parking +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Periodic +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.PrefixCoding +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RationalAlgorithms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Realization +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RecorderRules +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RecorderSimulation +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RelativeForce +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.ResidualRegularity +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.RhoAlgorithms +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Routing +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Sobolev +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.TemporalJets +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.TimeRegularity +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.UniversalInput +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.UniversalMachine +OAI.MathematicalPhysics.NavierStokes.BalancedTransport.Work diff --git a/tasks/forced-navier-stokes-computation/solution/reference.py b/tasks/forced-navier-stokes-computation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/forced-navier-stokes-computation/solution/solve.sh b/tasks/forced-navier-stokes-computation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..173236b14558c2336b15c0c6134e5014974194be --- /dev/null +++ b/tasks/forced-navier-stokes-computation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ForcedNavierStokesComputation, i.e. module OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult and the +# 60 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ForcedNavierStokesComputation" diff --git a/tasks/forced-navier-stokes-computation/task.toml b/tasks/forced-navier-stokes-computation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..aaa9aad5ae055df3d3f6ec3b35c2e770537c29b7 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/forced-navier-stokes-computation" +version = "1.0.0" +description = "Prove ForcedNavierStokesComputation (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ForcedNavierStokesComputation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ForcedNavierStokesComputation" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.BalancedTransport.balanced_three_stack_realization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.NavierStokes.BalancedTransport.MainResult" +reference_modules = 60 +reference_lean_bytes = 495983 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 547 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12146 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/forced-navier-stokes-computation/tests/Challenge.lean b/tasks/forced-navier-stokes-computation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e45e84a8afc62fa9bd7752250ec9b74ffb1f7904 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/tests/Challenge.lean @@ -0,0 +1,232 @@ +import Mathlib + +/-! A single main result: effective forced Navier–Stokes computation detected by a +fixed particle entering a fixed open box, exactly when the encoded machine halts. -/ + +namespace OAI.BalancedTransport +namespace Recorder +inductive Direction where + | stay | left | right + deriving DecidableEq + +structure Transition (Q Γ : Type*) where + state : Q + write : Γ + move : Direction +end Recorder + +structure FiniteMachine where + states : ℕ + symbols : ℕ + initial : Fin (states + 1) + blank : Fin (symbols + 1) + transition : Fin (states + 1) → Fin (symbols + 1) → + Option (Recorder.Transition (Fin (states + 1)) (Fin (symbols + 1))) + +abbrev Input (M : FiniteMachine) := List (Fin (M.symbols + 1)) + +structure TapeConfiguration (M : FiniteMachine) where + state : Fin (M.states + 1) + head : ℤ + tape : ℤ → Fin (M.symbols + 1) + +def initialConfiguration (M : FiniteMachine) (w : Input M) : TapeConfiguration M := + ⟨M.initial, 0, fun z => if 0 ≤ z then w[z.toNat]?.getD M.blank else M.blank⟩ + +def machineStep (M : FiniteMachine) (c : TapeConfiguration M) : Option (TapeConfiguration M) := + (M.transition c.state (c.tape c.head)).map fun v => + ⟨v.state, c.head + (match v.move with | .stay => 0 | .left => -1 | .right => 1), + Function.update c.tape c.head v.write⟩ + +def Halts (M : FiniteMachine) (w : Input M) : Prop := + ∃ c, Relation.ReflTransGen (fun c d => machineStep M c = some d) + (initialConfiguration M w) c ∧ machineStep M c = none + +def Recorder.Direction.number : Recorder.Direction → ℕ + | .stay => 0 + | .left => 1 + | .right => 2 + +def FiniteMachine.code (M : FiniteMachine) : ℕ := + Encodable.encode (M.states, M.symbols, M.initial.val, M.blank.val, + (List.finRange (M.states + 1)).map fun q => + (List.finRange (M.symbols + 1)).map fun a => + (M.transition q a).map fun v => (v.state.val, v.write.val, v.move.number)) + +def inputCode (M : FiniteMachine) (w : Input M) : ℕ := + Encodable.encode (M.code, w.map Fin.val) + +abbrev Space := Fin 3 → ℝ +abbrev Field (F : Type*) := ℝ → Space → F +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev Family (F : Type*) := (M : FiniteMachine) → Input M → F +abbrev MaterialFlow := ℝ → Space → Space +abbrev MultiIndex := List (Option (Fin 3)) +abbrev RationalPoint := ℚ × (Fin 3 → ℚ) + +noncomputable section + +open MeasureTheory +open scoped ENNReal + +variable {F : Type*} [NormedAddCommGroup F] [NormedSpace ℝ F] + +def timeD (v : Field F) : Field F := + fun t x => derivWithin (fun s => v s x) (Set.Ici 0) t + +def spaceD (i : Fin 3) (v : Field F) : Field F := + fun t x => fderiv ℝ (v t) x (Pi.single i 1) + +def mixedD : MultiIndex → Field F → Field F + | [], v => v + | none :: a, v => timeD (mixedD a v) + | some i :: a, v => spaceD i (mixedD a v) + +def spatialD : List (Fin 3) → Field F → Field F + | [], v => v + | i :: a, v => spaceD i (spatialD a v) + +def Smooth (v : Field F) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) (fun z : ℝ × Space => v z.1 z.2) (Set.Ici 0 ×ˢ Set.univ) + +def BoundedMixed (v : Field F) : Prop := + ∀ a : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ ∀ t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ C + +def CH (k : ℕ) (v : Field F) : Prop := + ∀ a : List (Fin 3), a.length ≤ k → + ∃ V : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → (V t : Space → F) =ᵐ[volume] spatialD a v t + +def C1L2 (v : Field F) : Prop := + ∃ V W : ℝ → Lp F 2 (volume : Measure Space), + ContinuousOn V (Set.Ici 0) ∧ ContinuousOn W (Set.Ici 0) ∧ + ∀ t, 0 ≤ t → + (V t : Space → F) =ᵐ[volume] v t ∧ + (W t : Space → F) =ᵐ[volume] timeD v t ∧ + HasDerivWithinAt V (W t) (Set.Ici 0) t + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i, spaceD i u t x i + +def laplacian (u : Velocity) : Velocity := + fun t x => ∑ i, spaceD i (spaceD i u) t x + +def convection (u : Velocity) : Velocity := + fun t x => ∑ i, (u t x i) • spaceD i u t x + +def gradient (p : Pressure) (t : ℝ) (x : Space) : Space := + fun i => spaceD i p t x + +def affineForce (f₀ f₁ : Velocity) (ν : ℝ) : Velocity := + fun t x => f₀ t x + ν • f₁ t x + +def inertialCoefficient (u : Velocity) : Velocity := + fun t x => timeD u t x + convection u t x + +def viscousCoefficient (u : Velocity) : Velocity := + fun t x => -laplacian u t x + +def ZeroDataSolution (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + Smooth u ∧ Smooth p ∧ + (∀ x, u 0 x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, div u t x = 0) ∧ + (∀ t, 0 ≤ t → ∀ x, + timeD u t x + convection u t x = + -gradient p t x + ν • laplacian u t x + f t x) + +def BoundedOnFiniteSlabs (u : Velocity) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ C : ℝ, 0 ≤ C ∧ + ∀ t ∈ Set.Icc (0 : ℝ) T, ∀ x, + ‖u t x‖ ≤ C ∧ ∀ i : Fin 3, ‖spaceD i u t x‖ ≤ C + +def ComparisonClass (u : Velocity) (p : Pressure) : Prop := + CH 2 u ∧ C1L2 u ∧ BoundedOnFiniteSlabs u ∧ + ∃ c : ℝ → ℝ, CH 1 (fun t x => p t x - c t) + +def UniqueInComparison (ν : ℝ) (f U : Velocity) : Prop := + ∀ u p, ZeroDataSolution ν f u p → ComparisonClass u p → + (∀ t, 0 ≤ t → ∀ x, u t x = U t x) ∧ + (∀ t, 0 ≤ t → ∀ x y, p t x = p t y) + +def CommonCompactSupport (U f₀ f₁ : Velocity) : Prop := + ∃ K : Set Space, IsCompact K ∧ + ∀ t, 0 ≤ t → ∀ x, x ∉ K → U t x = 0 ∧ f₀ t x = 0 ∧ f₁ t x = 0 + +def PeriodicAfterOne (v : Velocity) : Prop := + ∀ t, 1 ≤ t → ∀ x, v (t + 1) x = v t x + +def IsMaterialFlow (u : Velocity) (X : MaterialFlow) : Prop := + (∀ a, X 0 a = a) ∧ + ∀ a t, 0 ≤ t → HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t + +def fixedLabel : Space := ![4, 0, 0] + +def observer : Set Space := + Set.pi Set.univ (fun _ : Fin 3 => Set.Ioo (-1 : ℝ) 2) + +def rationalSpace (x : Fin 3 → ℚ) : Space := fun i => (x i : ℝ) + +def error (n : ℕ) : ℝ := (2 : ℝ)⁻¹ ^ n + +def EffectiveFamily (v : Family Velocity) : Prop := + ∃ E : (ℕ × MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : (ℕ × MultiIndex) → ℕ, + ∃ R : ℕ → ℕ, + Computable E ∧ Computable b ∧ Computable R ∧ + (∀ M w a z n, 0 ≤ z.1 → ∀ i, + |(E (inputCode M w, a, z, n) i : ℝ) - + mixedD a (v M w) (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ M w a t, 0 ≤ t → ∀ x, + ‖mixedD a (v M w) t x‖ ≤ (b (inputCode M w, a) : ℝ)) ∧ + (∀ M w t, 0 ≤ t → ∀ x, + (R (inputCode M w) : ℝ) < ‖x‖ → v M w t x = 0) + +def EffectiveFieldIn (O : Set (ℕ →. ℕ)) (v : Velocity) : Prop := + ∃ E : (MultiIndex × RationalPoint × ℕ) → (Fin 3 → ℚ), + ∃ b : MultiIndex → ℕ, + ComputableIn O E ∧ ComputableIn O b ∧ + (∀ a z n, 0 ≤ z.1 → ∀ i, + |(E (a, z, n) i : ℝ) - + mixedD a v (z.1 : ℝ) (rationalSpace z.2) i| ≤ error n) ∧ + (∀ a t, 0 ≤ t → ∀ x, ‖mixedD a v t x‖ ≤ (b a : ℝ)) + +def RealName (name : ℕ → ℚ) (x : ℝ) : Prop := + ∀ n, |(name n : ℝ) - x| ≤ error n + +def ComputableReal (x : ℝ) : Prop := + ∃ name : ℕ → ℚ, Computable name ∧ RealName name x + +def nameOracle (name : ℕ → ℚ) : ℕ →. ℕ := + fun n => Part.some (Encodable.encode (name n)) + +end + +theorem balanced_three_stack_realization : + ∃ U f₀ f₁ : Family Velocity, + ∃ X : Family MaterialFlow, + ∃ repeated : FiniteMachine → Velocity, + EffectiveFamily U ∧ EffectiveFamily f₀ ∧ EffectiveFamily f₁ ∧ + (∀ M, Function.Periodic (repeated M) 1) ∧ + ∀ (M : FiniteMachine) (w : Input M), + Smooth (U M w) ∧ Smooth (f₀ M w) ∧ Smooth (f₁ M w) ∧ + f₀ M w = inertialCoefficient (U M w) ∧ + f₁ M w = viscousCoefficient (U M w) ∧ + CommonCompactSupport (U M w) (f₀ M w) (f₁ M w) ∧ + BoundedMixed (U M w) ∧ + PeriodicAfterOne (U M w) ∧ + (∀ t, 1 ≤ t → ∀ x, U M w t x = repeated M t x) ∧ + ComparisonClass (U M w) (fun _ _ => 0) ∧ + IsMaterialFlow (U M w) (X M w) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ X M w t fixedLabel ∈ observer) ↔ Halts M w) ∧ + ∀ ν : ℝ, 0 < ν → + let f := affineForce (f₀ M w) (f₁ M w) ν + ZeroDataSolution ν f (U M w) (fun _ _ => 0) ∧ + Smooth f ∧ BoundedMixed f ∧ PeriodicAfterOne f ∧ + UniqueInComparison ν f (U M w) ∧ + (ComputableReal ν → EffectiveFieldIn ∅ f) ∧ + (∀ name : ℕ → ℚ, RealName name ν → EffectiveFieldIn {nameOracle name} f) := by + sorry + +end OAI.BalancedTransport diff --git a/tasks/forced-navier-stokes-computation/tests/grade.py b/tasks/forced-navier-stokes-computation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/forced-navier-stokes-computation/tests/task.json b/tasks/forced-navier-stokes-computation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9edceff4cc1f0eac5ccc59f9fb49742d65ff8b71 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ForcedNavierStokesComputation", + "comparator": { + "theorem_names": [ + "OAI.BalancedTransport.balanced_three_stack_realization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11246 +} \ No newline at end of file diff --git a/tasks/forced-navier-stokes-computation/tests/test.sh b/tasks/forced-navier-stokes-computation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/forced-navier-stokes-computation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/forest-space/environment/Dockerfile b/tasks/forest-space/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/forest-space/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/forest-space/environment/fetch_mathlib.sh b/tasks/forest-space/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/forest-space/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/forest-space/environment/lake-manifest.json b/tasks/forest-space/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/forest-space/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/forest-space/environment/lakefile.lean b/tasks/forest-space/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/forest-space/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/forest-space/environment/lean_setup.sh b/tasks/forest-space/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/forest-space/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/forest-space/environment/pack_submission.py b/tasks/forest-space/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/forest-space/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/forest-space/instruction.md b/tasks/forest-space/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bd81fe9f171dd98f07c4cb5616e5f1c6927c8b11 --- /dev/null +++ b/tasks/forest-space/instruction.md @@ -0,0 +1,519 @@ +# openai/math challenge `ForestSpace` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `ForestSpace`, also at `/opt/openai-math/challenges/ForestSpace.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +namespace ForestSpace + +attribute [local instance] Classical.propDecidable + +section ModulusDefinitions + +variable (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] + +/-- The closed finite-codimensional subspaces. -/ +def Cofinite : Type := + {F : Submodule ℝ E // IsClosed (F : Set E) ∧ FiniteDimensional ℝ (E ⧸ F)} + +/-- The inner one-sided excess values and their infimum. -/ +def aucValues (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : Set ℝ := + {a | ∃ y : E, y ∈ F.val ∧ N y = 1 ∧ a = N (x + t • y) - 1} + +noncomputable def aucInner (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : ℝ := + sInf (aucValues E N t x F) + +noncomputable def aucCenter (N : E → ℝ) (t : ℝ) (x : E) : ℝ := + sSup (Set.range (aucInner E N t x)) + +/-- The one-sided asymptotic uniform convexity modulus, with the order +of infimum, supremum and infimum. -/ +noncomputable def aucModulus (N : E → ℝ) (t : ℝ) : ℝ := + sInf {a | ∃ x : E, N x = 1 ∧ a = aucCenter E N t x} + +/-- The inner averaged signed excess; it is not replaced by a maximum. -/ +def averageValues (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : Set ℝ := + {a | ∃ y : E, y ∈ F.val ∧ N y = 1 ∧ + a = (N (x+t•y) + N (x-t•y))/((2 : ℕ) : ℝ) - 1} + +noncomputable def averageInner (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : ℝ := + sInf (averageValues E N t x F) + +noncomputable def averageCenter (N : E → ℝ) (t : ℝ) (x : E) : ℝ := + sSup (Set.range (averageInner E N t x)) + +/-- The averaged asymptotic midpoint modulus. -/ +noncomputable def averageModulus (N : E → ℝ) (t : ℝ) : ℝ := + sInf {a | ∃ x : E, N x = 1 ∧ a = averageCenter E N t x} + +end ModulusDefinitions + +/-- An equivalent norm is kept as its exact real seminorm, with explicit positive +comparison constants. The lower inequality makes it a norm. -/ +structure EquivalentNorm (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] + (α β : ℝ) where + N : Seminorm ℝ E + alpha_pos : 0 < α + alpha_le_beta : α ≤ β + lower : ∀ x : E, α*‖x‖ ≤ N x + upper : ∀ x : E, N x ≤ β*‖x‖ + +/-- Canonical (not merely abstract) reflexivity. -/ +def Reflexive (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ E) + +/-- AUC requires positivity at every strictly positive parameter. -/ +def IsAUC {E : Type} [NormedAddCommGroup E] [NormedSpace ℝ E] (N : E → ℝ) : Prop := + ∀ t : ℝ, 0 < t → 0 < aucModulus E N t + +/-- A finite, order-convex chain. The empty chain is a harmless zero test. -/ +def IsSegment {V : Type} [PartialOrder V] (S : Finset V) : Prop := + (∀ a ∈ S, ∀ b ∈ S, a ≤ b ∨ b ≤ a) ∧ + (∀ a ∈ S, ∀ b ∈ S, ∀ c, a ≤ c → c ≤ b → c ∈ S) + +/-- The sum of coordinates over a segment. -/ +def segSum {V : Type} (u : V → ℝ) (S : Finset V) : ℝ := ∑ v ∈ S, u v + +/-- Squared bound on every disjoint family of segment tests. -/ +def TestBound {V : Type} [PartialOrder V] (u : V → ℝ) (C : ℝ) : Prop := + ∀ (ι : Type) (_ : Fintype ι) (S : ι → Finset V), + (∀ i, IsSegment (S i)) → Pairwise (fun i j => Disjoint (S i) (S j)) → + ∑ i, segSum u (S i) ^ 2 ≤ C + +section SegmentNorm + +variable {V : Type} [PartialOrder V] + +/-- All squared disjoint-segment tests. Quantifying over finite index types +is equivalent to families S₁,...,Sₘ; a zero-sized family +adds only zero to the set of test values. -/ +def testValues (u : V → ℝ) : Set ℝ := + {r | ∃ (ι : Type) (_ : Fintype ι) (S : ι → Finset V), + (∀ i, IsSegment (S i)) ∧ Pairwise (fun i j => Disjoint (S i) (S j)) ∧ + r = ∑ i, segSum u (S i) ^ 2} + +noncomputable def squareSup (u : V → ℝ) : ℝ := sSup (testValues u) + +/-- Exactly the disjoint-segment norm, written as the square root of its +squared testing supremum. -/ +noncomputable def rho (u : V → ℝ) : ℝ := Real.sqrt (squareSup u) + +noncomputable def l1size (u : V →₀ ℝ) : ℝ := ∑ v ∈ u.support, |u v| + +end SegmentNorm + +/-- The disjoint-segment seminorm on finite coordinate vectors. -/ +def segmentSeminorm (V : Type) [PartialOrder V] : Seminorm ℝ (V →₀ ℝ) := by + have segSum_zero [PartialOrder V] (S : Finset V) : segSum (0 : V → ℝ) S = 0 := by + simp [segSum] + have segSum_add [PartialOrder V] (u v : V → ℝ) (S : Finset V) : + segSum (u + v) S = segSum u S + segSum v S := by + simp [segSum, Finset.sum_add_distrib] + have segSum_smul [PartialOrder V] (a : ℝ) (u : V → ℝ) (S : Finset V) : + segSum (a • u) S = a * segSum u S := by + simp [segSum, Finset.mul_sum] + have TestBound.nonneg {u : V → ℝ} {C : ℝ} (h : TestBound u C) : 0 ≤ C := by + simpa using h PEmpty inferInstance PEmpty.elim (by simp) (by simp [Pairwise]) + have TestBound.zero : TestBound (0 : V → ℝ) 0 := by + intro ι inst S hS hd + simp [segSum] + have TestBound.smul {u : V → ℝ} {C : ℝ} (h : TestBound u C) (a : ℝ) : + TestBound (a • u) (a ^ 2 * C) := by + intro ι inst S hS hd + have hh := mul_le_mul_of_nonneg_left (h ι inst S hS hd) (sq_nonneg a) + simpa only [segSum_smul, mul_pow, Finset.mul_sum] using hh + have TestBound.add {u v : V → ℝ} {A B : ℝ} + (hu : TestBound u (A ^ 2)) (hv : TestBound v (B ^ 2)) + (hA : 0 ≤ A) (hB : 0 ≤ B) : TestBound (u + v) ((A + B) ^ 2) := by + intro ι inst S hS hd + have h₁ := hu ι inst S hS hd + have h₂ := hv ι inst S hS hd + have hc := Real.sum_mul_le_sqrt_mul_sqrt (univ : Finset ι) + (fun i => segSum u (S i)) (fun i => segSum v (S i)) + have hs₁ : Real.sqrt (∑ i, segSum u (S i) ^ 2) ≤ A := + (Real.sqrt_le_iff).2 ⟨hA, h₁⟩ + have hs₂ : Real.sqrt (∑ i, segSum v (S i) ^ 2) ≤ B := + (Real.sqrt_le_iff).2 ⟨hB, h₂⟩ + have hc' : ∑ i, segSum u (S i) * segSum v (S i) ≤ A * B := + hc.trans (mul_le_mul hs₁ hs₂ (Real.sqrt_nonneg _) hA) + have he : (∑ i, segSum (u + v) (S i) ^ 2) = + (∑ i, segSum u (S i) ^ 2) + 2 * (∑ i, segSum u (S i) * segSum v (S i)) + + (∑ i, segSum v (S i) ^ 2) := by + simp only [segSum_add, add_sq, Finset.sum_add_distrib, Finset.mul_sum] + congr 1 + congr 1 + apply Finset.sum_congr rfl + intro i hi + ring + rw [he] + nlinarith + have zero_mem_testValues (u : V → ℝ) : 0 ∈ testValues u := by + refine ⟨PEmpty, inferInstance, PEmpty.elim, by simp, by simp [Pairwise], ?_⟩ + simp [segSum] + have TestBound.bddAbove {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + BddAbove (testValues u) := by + refine ⟨C, ?_⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have TestBound.squareSup_le {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + squareSup u ≤ C := by + apply csSup_le ⟨0, zero_mem_testValues u⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have testBound_squareSup {u : V → ℝ} (hu : ∃ C, TestBound u C) : + TestBound u (squareSup u) := by + intro ι inst S hs hd + exact le_csSup (TestBound.bddAbove hu.choose_spec) ⟨ι, inst, S, hs, hd, rfl⟩ + have squareSup_nonneg {u : V → ℝ} (hu : ∃ C, TestBound u C) : 0 ≤ squareSup u := + TestBound.nonneg (testBound_squareSup hu) + have rho_nonneg (u : V → ℝ) : 0 ≤ rho u := Real.sqrt_nonneg _ + have rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : rho u ^ 2 = squareSup u := + Real.sq_sqrt (squareSup_nonneg hu) + have testBound_rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : TestBound u (rho u ^ 2) := by + rw [rho_sq hu] + exact testBound_squareSup hu + have rho_le_of_testBound {u : V → ℝ} {C : ℝ} (hC : 0 ≤ C) + (hu : TestBound u (C ^ 2)) : rho u ≤ C := + Real.sqrt_le_iff.mpr ⟨hC, TestBound.squareSup_le hu⟩ + have rho_add_le {u v : V → ℝ} (hu : ∃ C, TestBound u C) (hv : ∃ C, TestBound v C) : + rho (u + v) ≤ rho u + rho v := + rho_le_of_testBound (add_nonneg (rho_nonneg u) (rho_nonneg v)) + (TestBound.add (testBound_rho_sq hu) (testBound_rho_sq hv) (rho_nonneg u) (rho_nonneg v)) + have rho_smul_le {u : V → ℝ} (hu : ∃ C, TestBound u C) (a : ℝ) : + rho (a • u) ≤ |a| * rho u := by + apply rho_le_of_testBound (mul_nonneg (abs_nonneg a) (rho_nonneg u)) + have hh := TestBound.smul (testBound_rho_sq hu) a + simpa only [mul_pow, sq_abs] using hh + have rho_zero : rho (0 : V → ℝ) = 0 := by + apply le_antisymm _ (rho_nonneg _) + apply rho_le_of_testBound (C := 0) (by norm_num) + simpa using (TestBound.zero : TestBound (0 : V → ℝ) 0) + have l1size_nonneg [PartialOrder V] (u : V →₀ ℝ) : 0 ≤ l1size u := + sum_nonneg (fun vertex _ => abs_nonneg (u vertex)) + have finset_abs_sum_le_l1size [PartialOrder V] (u : V →₀ ℝ) (S : Finset V) : + ∑ v ∈ S, |u v| ≤ l1size u := by + have he : (∑ v ∈ S ∪ u.support, |u v|) = l1size u := by + symm + apply sum_subset subset_union_right + intro v hv hn + rw [Finsupp.notMem_support_iff.mp hn, abs_zero] + rw [← he] + exact sum_le_sum_of_subset_of_nonneg subset_union_left (fun v hv hn => abs_nonneg _) + have testBound_l1size (u : V →₀ ℝ) : TestBound u (l1size u ^ 2) := by + intro ι inst S hS hd + have habs : (∑ i, |segSum u (S i)|) ≤ l1size u := by + calc + (∑ i, |segSum u (S i)|) ≤ ∑ i, ∑ v ∈ S i, |u v| := + sum_le_sum fun i hi => abs_sum_le_sum_abs _ _ + _ = ∑ v ∈ univ.biUnion S, |u v| := + (sum_biUnion (by intro i hi j hj hij; exact hd hij)).symm + _ ≤ l1size u := finset_abs_sum_le_l1size u _ + have hsq := sum_sq_le_sq_sum_of_nonneg + (s := (univ : Finset ι)) (f := fun i => |segSum u (S i)|) (fun i hi => abs_nonneg _) + simp only [sq_abs] at hsq + have hnonneg : 0 ≤ ∑ i, |segSum u (S i)| := sum_nonneg (fun i hi => abs_nonneg _) + nlinarith [l1size_nonneg u] + have finsupp_has_testBound (u : V →₀ ℝ) : ∃ C, TestBound u C := ⟨_, testBound_l1size u⟩ + exact Seminorm.ofSMulLE (fun u : V →₀ ℝ => rho u) rho_zero + (fun u v => rho_add_le (finsupp_has_testBound u) (finsupp_has_testBound v)) + (fun a u => by simpa only [Real.norm_eq_abs, Finsupp.coe_smul] using rho_smul_le (finsupp_has_testBound u) a) + +/-- Finite coordinate vectors with the segment norm (a type synonym prevents +clashes with any other norm on finitely supported functions). -/ +def TestVector (V : Type) := V →₀ ℝ + +namespace TestVector + +variable {V : Type} + +instance : AddCommGroup (TestVector V) := inferInstanceAs (AddCommGroup (V →₀ ℝ)) + +instance : Module ℝ (TestVector V) := inferInstanceAs (Module ℝ (V →₀ ℝ)) + +def toFinsupp (u : TestVector V) : V →₀ ℝ := u + +instance : CoeFun (TestVector V) (fun _ => V → ℝ) := ⟨fun u => u.toFinsupp⟩ + +variable [PartialOrder V] + +instance : Norm (TestVector V) := ⟨fun u => rho u⟩ + +instance : NormedAddCommGroup (TestVector V) := by + have isSegment_singleton (v : V) : IsSegment ({v} : Finset V) := by + constructor + · intro a ha b hb + simp only [mem_singleton] at ha hb + subst a + subst b + exact Or.inl le_rfl + · intro a ha b hb c hac hcb + simp only [mem_singleton] at ha hb ⊢ + subst a + subst b + exact le_antisymm hcb hac + have TestBound.nonneg {u : V → ℝ} {C : ℝ} (h : TestBound u C) : 0 ≤ C := by + simpa using h PEmpty inferInstance PEmpty.elim (by simp) (by simp [Pairwise]) + have TestBound.single {u : V → ℝ} {C : ℝ} (h : TestBound u C) + {S : Finset V} (hS : IsSegment S) : segSum u S ^ 2 ≤ C := by + simpa using h Unit inferInstance (fun _ => S) (fun _ => hS) + (by simp [Pairwise]) + have TestBound.bddAbove {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + BddAbove (testValues u) := by + refine ⟨C, ?_⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have testBound_squareSup {u : V → ℝ} (hu : ∃ C, TestBound u C) : + TestBound u (squareSup u) := by + intro ι inst S hs hd + exact le_csSup (TestBound.bddAbove hu.choose_spec) ⟨ι, inst, S, hs, hd, rfl⟩ + have squareSup_nonneg {u : V → ℝ} (hu : ∃ C, TestBound u C) : 0 ≤ squareSup u := + TestBound.nonneg (testBound_squareSup hu) + have rho_nonneg (u : V → ℝ) : 0 ≤ rho u := Real.sqrt_nonneg _ + have rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : rho u ^ 2 = squareSup u := + Real.sq_sqrt (squareSup_nonneg hu) + have testBound_rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : TestBound u (rho u ^ 2) := by + rw [rho_sq hu] + exact testBound_squareSup hu + have coordinate_le_rho {u : V → ℝ} (hu : ∃ C, TestBound u C) (v : V) : + |u v| ≤ rho u := by + have hh := TestBound.single (testBound_rho_sq hu) (isSegment_singleton v) + simp only [segSum, sum_singleton] at hh + exact (sq_le_sq₀ (abs_nonneg _) (rho_nonneg _)).mp (by simpa only [sq_abs] using hh) + have l1size_nonneg [PartialOrder V] (u : V →₀ ℝ) : 0 ≤ l1size u := + sum_nonneg (fun vertex _ => abs_nonneg (u vertex)) + have finset_abs_sum_le_l1size [PartialOrder V] (u : V →₀ ℝ) (S : Finset V) : + ∑ v ∈ S, |u v| ≤ l1size u := by + have he : (∑ v ∈ S ∪ u.support, |u v|) = l1size u := by + symm + apply sum_subset subset_union_right + intro v hv hn + rw [Finsupp.notMem_support_iff.mp hn, abs_zero] + rw [← he] + exact sum_le_sum_of_subset_of_nonneg subset_union_left (fun v hv hn => abs_nonneg _) + have testBound_l1size (u : V →₀ ℝ) : TestBound u (l1size u ^ 2) := by + intro ι inst S hS hd + have habs : (∑ i, |segSum u (S i)|) ≤ l1size u := by + calc + (∑ i, |segSum u (S i)|) ≤ ∑ i, ∑ v ∈ S i, |u v| := + sum_le_sum fun i hi => abs_sum_le_sum_abs _ _ + _ = ∑ v ∈ univ.biUnion S, |u v| := + (sum_biUnion (by intro i hi j hj hij; exact hd hij)).symm + _ ≤ l1size u := finset_abs_sum_le_l1size u _ + have hsq := sum_sq_le_sq_sum_of_nonneg + (s := (univ : Finset ι)) (f := fun i => |segSum u (S i)|) (fun i hi => abs_nonneg _) + simp only [sq_abs] at hsq + have hnonneg : 0 ≤ ∑ i, |segSum u (S i)| := sum_nonneg (fun i hi => abs_nonneg _) + nlinarith [l1size_nonneg u] + have finsupp_has_testBound (u : V →₀ ℝ) : ∃ C, TestBound u C := ⟨_, testBound_l1size u⟩ + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg u := apply_nonneg (segmentSeminorm V) u.toFinsupp + norm_triangle u v := map_add_le_add (segmentSeminorm V) u.toFinsupp v.toFinsupp + norm_smul a u := map_smul_eq_mul (segmentSeminorm V) a u.toFinsupp + norm_eq_zero_iff u := ⟨by + intro h + apply Finsupp.ext + intro v + have hh := coordinate_le_rho (finsupp_has_testBound u.toFinsupp) v + change rho u.toFinsupp = 0 at h + rw [h] at hh + exact abs_nonpos_iff.mp hh, by + rintro rfl + exact map_zero (segmentSeminorm V)⟩ } + +instance : NormedSpace ℝ (TestVector V) where + norm_smul_le a u := le_of_eq (map_smul_eq_mul (segmentSeminorm V) a u.toFinsupp) + +end TestVector + +/-- J(T), completion of the finite-support disjoint-segment norm. -/ +abbrev J (V : Type) [PartialOrder V] := UniformSpace.Completion (TestVector V) + +/-- The full continuous dual, used for the finite-height forest example. -/ +abbrev FullDual (V : Type) [PartialOrder V] := StrongDual ℝ (J V) + +section CoordinateCompletion + +variable {W : no_index Type} [PartialOrder W] + +instance fullDualAddCommGroup : AddCommGroup (FullDual W) := + inferInstanceAs (AddCommGroup (StrongDual ℝ (J W))) + +end CoordinateCompletion + +/-- Finite words, ordered by extension, including the empty root. -/ +structure Word where + letters : List ℕ + deriving DecidableEq + +namespace Word + +instance : PartialOrder Word where + le a b := a.letters <+: b.letters + le_refl _ := List.prefix_rfl + le_trans _ _ _ := List.IsPrefix.trans + le_antisymm a b hab hba := by + have h := hab.eq_of_length (Nat.le_antisymm hab.length_le hba.length_le) + cases a; cases b; cases h; rfl + +end Word + +/-- A disjoint forest: one copy of `Nat^{≤h}` for every `h≥1`. -/ +structure Vertex where + height : ℕ + positive : 1 ≤ height + word : Word + bounded : word.letters.length ≤ height + deriving DecidableEq + +namespace Vertex + +instance : PartialOrder Vertex where + le a b := a.height = b.height ∧ a.word ≤ b.word + le_refl _ := ⟨rfl,le_rfl⟩ + le_trans a b c hab hbc := ⟨hab.1.trans hbc.1,hab.2.trans hbc.2⟩ + le_antisymm a b hab hba := by + obtain ⟨hh, hw⟩ := hab + have he := le_antisymm hw hba.2 + cases a; cases b; cases hh; cases he; rfl + +end Vertex + +namespace Diamond + +/-- An oriented edge enumeration; only the associated undirected unit-edge +simple graph is used for distances. -/ +structure Network where + V : Type + E : Type + left : E → V + right : E → V + distinct : ∀ e, left e ≠ right e + +namespace Network + +variable (A : Network) + +def graph : SimpleGraph A.V where + Adj u v := ∃ e : A.E, (A.left e = u ∧ A.right e = v) ∨ + (A.right e = u ∧ A.left e = v) + symm := ⟨by + rintro u v ⟨e,h | h⟩ + · exact ⟨e,Or.inr ⟨h.2,h.1⟩⟩ + · exact ⟨e,Or.inl ⟨h.2,h.1⟩⟩⟩ + loopless := ⟨by + rintro u ⟨e,h | h⟩ + · exact A.distinct e (h.1.trans h.2.symm) + · exact A.distinct e (h.2.trans h.1.symm)⟩ + +/-- Every edge is replaced by countably many internally disjoint two-edge +paths. All old vertices remain, and each pair (edge,index) is a new midpoint. -/ +@[reducible] def refine : Network where + V := Sum A.V (A.E × ℕ) + E := A.E × ℕ × Bool + left e := if e.2.2 then Sum.inr (e.1,e.2.1) else Sum.inl (A.left e.1) + right e := if e.2.2 then Sum.inl (A.right e.1) else Sum.inr (e.1,e.2.1) + distinct := by rintro ⟨e,j,b⟩; cases b <;> simp + +/-- Iterating the very same edge replacement, starting from an arbitrary +network. This recursion groups the first replacement before the remaining ones. -/ +@[reducible] def iterate : Network → ℕ → Network + | A,0 => A + | A,n+1 => iterate A.refine n + +end Network + +/-- D₀ is precisely one edge. -/ +@[reducible] def base : Network where + V := Bool + E := Unit + left _ := false + right _ := true + distinct _ := by decide + +/-- Countably branching diamonds, all current edges of length one. -/ +@[reducible] def diamond (k : ℕ) := base.iterate k + +/-- The shortest-path distance, via Mathlib's actual graph distance. -/ +def distance (k : ℕ) (u v : (diamond k).V) : ℝ := ((diamond k).graph.dist u v : ℝ) +variable {E : Type} [NormedAddCommGroup E] [NormedSpace ℝ E] + +/-- The distortion convention, including its arbitrary positive scale. -/ +def EmbeddingBound (k : ℕ) (f : (diamond k).V → E) (C : ℝ) : Prop := + ∃ s : ℝ, 0 < s ∧ ∀ u v, + s*distance k u v ≤ ‖f u-f v‖ ∧ ‖f u-f v‖ ≤ C*s*distance k u v + +end Diamond + +/-- The space +is the full continuous dual of the specified segment-norm completion, not the +coordinate completion in place of that dual. -/ +theorem main_theorem : + (¬FiniteDimensional ℝ (FullDual Vertex)) ∧ + TopologicalSpace.SeparableSpace (FullDual Vertex) ∧ + Reflexive (FullDual Vertex) ∧ + (∀ (α β : ℝ) (R : EquivalentNorm (FullDual Vertex) α β), ¬IsAUC R.N) ∧ + (∀ t : ℝ, 0 < t → + Real.sqrt (1+t^2/12)-1 ≤ averageModulus (FullDual Vertex) norm t) ∧ + (∀ (k : ℕ) (f : (Diamond.diamond k).V → FullDual Vertex) (C : ℝ), + Diamond.EmbeddingBound k f C → Real.sqrt (1+(k:ℝ)/12) ≤ C) := by + sorry + +end ForestSpace + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ForestSpace.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ForestSpace.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/forest-space/solution/closure.txt b/tasks/forest-space/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..edafc7412b88ba425a9420aece427b897685d81c --- /dev/null +++ b/tasks/forest-space/solution/closure.txt @@ -0,0 +1,20 @@ +OAI.Analysis.ForestSpace.Completion +OAI.Analysis.ForestSpace.Components +OAI.Analysis.ForestSpace.Coordinates +OAI.Analysis.ForestSpace.Diamonds +OAI.Analysis.ForestSpace.Distortion +OAI.Analysis.ForestSpace.Exhaustions +OAI.Analysis.ForestSpace.FiniteGeometry +OAI.Analysis.ForestSpace.FullDual +OAI.Analysis.ForestSpace.Lens +OAI.Analysis.ForestSpace.Main +OAI.Analysis.ForestSpace.Moduli +OAI.Analysis.ForestSpace.ModulusProofs +OAI.Analysis.ForestSpace.Norm +OAI.Analysis.ForestSpace.Paired +OAI.Analysis.ForestSpace.Polar +OAI.Analysis.ForestSpace.Projections +OAI.Analysis.ForestSpace.Reflexivity +OAI.Analysis.ForestSpace.Renorming +OAI.Analysis.ForestSpace.Segments +OAI.Analysis.ForestSpace.Trees diff --git a/tasks/forest-space/solution/reference.py b/tasks/forest-space/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/forest-space/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/forest-space/solution/solve.sh b/tasks/forest-space/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b48128bb9e35536ae9bb7424814c41664747608 --- /dev/null +++ b/tasks/forest-space/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ForestSpace, i.e. module OAI.Analysis.ForestSpace.Main and the +# 20 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.ForestSpace.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ForestSpace" diff --git a/tasks/forest-space/task.toml b/tasks/forest-space/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f45277a486b330b5c8f7364f28911fcf0986a257 --- /dev/null +++ b/tasks/forest-space/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/forest-space" +version = "1.0.0" +description = "Prove ForestSpace (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ForestSpace.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ForestSpace" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.ForestSpace.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.ForestSpace.Main" +reference_modules = 20 +reference_lean_bytes = 195404 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 741 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11875 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/forest-space/tests/Challenge.lean b/tasks/forest-space/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c44f14ccdd1a6285776bd991bf5f80ce607e5e00 --- /dev/null +++ b/tasks/forest-space/tests/Challenge.lean @@ -0,0 +1,468 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +open Finset + +namespace ForestSpace + +attribute [local instance] Classical.propDecidable + +section ModulusDefinitions + +variable (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] + +/-- The closed finite-codimensional subspaces. -/ +def Cofinite : Type := + {F : Submodule ℝ E // IsClosed (F : Set E) ∧ FiniteDimensional ℝ (E ⧸ F)} + +/-- The inner one-sided excess values and their infimum. -/ +def aucValues (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : Set ℝ := + {a | ∃ y : E, y ∈ F.val ∧ N y = 1 ∧ a = N (x + t • y) - 1} + +noncomputable def aucInner (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : ℝ := + sInf (aucValues E N t x F) + +noncomputable def aucCenter (N : E → ℝ) (t : ℝ) (x : E) : ℝ := + sSup (Set.range (aucInner E N t x)) + +/-- The one-sided asymptotic uniform convexity modulus, with the order +of infimum, supremum and infimum. -/ +noncomputable def aucModulus (N : E → ℝ) (t : ℝ) : ℝ := + sInf {a | ∃ x : E, N x = 1 ∧ a = aucCenter E N t x} + +/-- The inner averaged signed excess; it is not replaced by a maximum. -/ +def averageValues (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : Set ℝ := + {a | ∃ y : E, y ∈ F.val ∧ N y = 1 ∧ + a = (N (x+t•y) + N (x-t•y))/((2 : ℕ) : ℝ) - 1} + +noncomputable def averageInner (N : E → ℝ) (t : ℝ) (x : E) (F : Cofinite E) : ℝ := + sInf (averageValues E N t x F) + +noncomputable def averageCenter (N : E → ℝ) (t : ℝ) (x : E) : ℝ := + sSup (Set.range (averageInner E N t x)) + +/-- The averaged asymptotic midpoint modulus. -/ +noncomputable def averageModulus (N : E → ℝ) (t : ℝ) : ℝ := + sInf {a | ∃ x : E, N x = 1 ∧ a = averageCenter E N t x} + +end ModulusDefinitions + +/-- An equivalent norm is kept as its exact real seminorm, with explicit positive +comparison constants. The lower inequality makes it a norm. -/ +structure EquivalentNorm (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] + (α β : ℝ) where + N : Seminorm ℝ E + alpha_pos : 0 < α + alpha_le_beta : α ≤ β + lower : ∀ x : E, α*‖x‖ ≤ N x + upper : ∀ x : E, N x ≤ β*‖x‖ + +/-- Canonical (not merely abstract) reflexivity. -/ +def Reflexive (E : Type) [NormedAddCommGroup E] [NormedSpace ℝ E] : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ E) + +/-- AUC requires positivity at every strictly positive parameter. -/ +def IsAUC {E : Type} [NormedAddCommGroup E] [NormedSpace ℝ E] (N : E → ℝ) : Prop := + ∀ t : ℝ, 0 < t → 0 < aucModulus E N t + +/-- A finite, order-convex chain. The empty chain is a harmless zero test. -/ +def IsSegment {V : Type} [PartialOrder V] (S : Finset V) : Prop := + (∀ a ∈ S, ∀ b ∈ S, a ≤ b ∨ b ≤ a) ∧ + (∀ a ∈ S, ∀ b ∈ S, ∀ c, a ≤ c → c ≤ b → c ∈ S) + +/-- The sum of coordinates over a segment. -/ +def segSum {V : Type} (u : V → ℝ) (S : Finset V) : ℝ := ∑ v ∈ S, u v + +/-- Squared bound on every disjoint family of segment tests. -/ +def TestBound {V : Type} [PartialOrder V] (u : V → ℝ) (C : ℝ) : Prop := + ∀ (ι : Type) (_ : Fintype ι) (S : ι → Finset V), + (∀ i, IsSegment (S i)) → Pairwise (fun i j => Disjoint (S i) (S j)) → + ∑ i, segSum u (S i) ^ 2 ≤ C + +section SegmentNorm + +variable {V : Type} [PartialOrder V] + +/-- All squared disjoint-segment tests. Quantifying over finite index types +is equivalent to families S₁,...,Sₘ; a zero-sized family +adds only zero to the set of test values. -/ +def testValues (u : V → ℝ) : Set ℝ := + {r | ∃ (ι : Type) (_ : Fintype ι) (S : ι → Finset V), + (∀ i, IsSegment (S i)) ∧ Pairwise (fun i j => Disjoint (S i) (S j)) ∧ + r = ∑ i, segSum u (S i) ^ 2} + +noncomputable def squareSup (u : V → ℝ) : ℝ := sSup (testValues u) + +/-- Exactly the disjoint-segment norm, written as the square root of its +squared testing supremum. -/ +noncomputable def rho (u : V → ℝ) : ℝ := Real.sqrt (squareSup u) + +noncomputable def l1size (u : V →₀ ℝ) : ℝ := ∑ v ∈ u.support, |u v| + +end SegmentNorm + +/-- The disjoint-segment seminorm on finite coordinate vectors. -/ +def segmentSeminorm (V : Type) [PartialOrder V] : Seminorm ℝ (V →₀ ℝ) := by + have segSum_zero [PartialOrder V] (S : Finset V) : segSum (0 : V → ℝ) S = 0 := by + simp [segSum] + have segSum_add [PartialOrder V] (u v : V → ℝ) (S : Finset V) : + segSum (u + v) S = segSum u S + segSum v S := by + simp [segSum, Finset.sum_add_distrib] + have segSum_smul [PartialOrder V] (a : ℝ) (u : V → ℝ) (S : Finset V) : + segSum (a • u) S = a * segSum u S := by + simp [segSum, Finset.mul_sum] + have TestBound.nonneg {u : V → ℝ} {C : ℝ} (h : TestBound u C) : 0 ≤ C := by + simpa using h PEmpty inferInstance PEmpty.elim (by simp) (by simp [Pairwise]) + have TestBound.zero : TestBound (0 : V → ℝ) 0 := by + intro ι inst S hS hd + simp [segSum] + have TestBound.smul {u : V → ℝ} {C : ℝ} (h : TestBound u C) (a : ℝ) : + TestBound (a • u) (a ^ 2 * C) := by + intro ι inst S hS hd + have hh := mul_le_mul_of_nonneg_left (h ι inst S hS hd) (sq_nonneg a) + simpa only [segSum_smul, mul_pow, Finset.mul_sum] using hh + have TestBound.add {u v : V → ℝ} {A B : ℝ} + (hu : TestBound u (A ^ 2)) (hv : TestBound v (B ^ 2)) + (hA : 0 ≤ A) (hB : 0 ≤ B) : TestBound (u + v) ((A + B) ^ 2) := by + intro ι inst S hS hd + have h₁ := hu ι inst S hS hd + have h₂ := hv ι inst S hS hd + have hc := Real.sum_mul_le_sqrt_mul_sqrt (univ : Finset ι) + (fun i => segSum u (S i)) (fun i => segSum v (S i)) + have hs₁ : Real.sqrt (∑ i, segSum u (S i) ^ 2) ≤ A := + (Real.sqrt_le_iff).2 ⟨hA, h₁⟩ + have hs₂ : Real.sqrt (∑ i, segSum v (S i) ^ 2) ≤ B := + (Real.sqrt_le_iff).2 ⟨hB, h₂⟩ + have hc' : ∑ i, segSum u (S i) * segSum v (S i) ≤ A * B := + hc.trans (mul_le_mul hs₁ hs₂ (Real.sqrt_nonneg _) hA) + have he : (∑ i, segSum (u + v) (S i) ^ 2) = + (∑ i, segSum u (S i) ^ 2) + 2 * (∑ i, segSum u (S i) * segSum v (S i)) + + (∑ i, segSum v (S i) ^ 2) := by + simp only [segSum_add, add_sq, Finset.sum_add_distrib, Finset.mul_sum] + congr 1 + congr 1 + apply Finset.sum_congr rfl + intro i hi + ring + rw [he] + nlinarith + have zero_mem_testValues (u : V → ℝ) : 0 ∈ testValues u := by + refine ⟨PEmpty, inferInstance, PEmpty.elim, by simp, by simp [Pairwise], ?_⟩ + simp [segSum] + have TestBound.bddAbove {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + BddAbove (testValues u) := by + refine ⟨C, ?_⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have TestBound.squareSup_le {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + squareSup u ≤ C := by + apply csSup_le ⟨0, zero_mem_testValues u⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have testBound_squareSup {u : V → ℝ} (hu : ∃ C, TestBound u C) : + TestBound u (squareSup u) := by + intro ι inst S hs hd + exact le_csSup (TestBound.bddAbove hu.choose_spec) ⟨ι, inst, S, hs, hd, rfl⟩ + have squareSup_nonneg {u : V → ℝ} (hu : ∃ C, TestBound u C) : 0 ≤ squareSup u := + TestBound.nonneg (testBound_squareSup hu) + have rho_nonneg (u : V → ℝ) : 0 ≤ rho u := Real.sqrt_nonneg _ + have rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : rho u ^ 2 = squareSup u := + Real.sq_sqrt (squareSup_nonneg hu) + have testBound_rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : TestBound u (rho u ^ 2) := by + rw [rho_sq hu] + exact testBound_squareSup hu + have rho_le_of_testBound {u : V → ℝ} {C : ℝ} (hC : 0 ≤ C) + (hu : TestBound u (C ^ 2)) : rho u ≤ C := + Real.sqrt_le_iff.mpr ⟨hC, TestBound.squareSup_le hu⟩ + have rho_add_le {u v : V → ℝ} (hu : ∃ C, TestBound u C) (hv : ∃ C, TestBound v C) : + rho (u + v) ≤ rho u + rho v := + rho_le_of_testBound (add_nonneg (rho_nonneg u) (rho_nonneg v)) + (TestBound.add (testBound_rho_sq hu) (testBound_rho_sq hv) (rho_nonneg u) (rho_nonneg v)) + have rho_smul_le {u : V → ℝ} (hu : ∃ C, TestBound u C) (a : ℝ) : + rho (a • u) ≤ |a| * rho u := by + apply rho_le_of_testBound (mul_nonneg (abs_nonneg a) (rho_nonneg u)) + have hh := TestBound.smul (testBound_rho_sq hu) a + simpa only [mul_pow, sq_abs] using hh + have rho_zero : rho (0 : V → ℝ) = 0 := by + apply le_antisymm _ (rho_nonneg _) + apply rho_le_of_testBound (C := 0) (by norm_num) + simpa using (TestBound.zero : TestBound (0 : V → ℝ) 0) + have l1size_nonneg [PartialOrder V] (u : V →₀ ℝ) : 0 ≤ l1size u := + sum_nonneg (fun vertex _ => abs_nonneg (u vertex)) + have finset_abs_sum_le_l1size [PartialOrder V] (u : V →₀ ℝ) (S : Finset V) : + ∑ v ∈ S, |u v| ≤ l1size u := by + have he : (∑ v ∈ S ∪ u.support, |u v|) = l1size u := by + symm + apply sum_subset subset_union_right + intro v hv hn + rw [Finsupp.notMem_support_iff.mp hn, abs_zero] + rw [← he] + exact sum_le_sum_of_subset_of_nonneg subset_union_left (fun v hv hn => abs_nonneg _) + have testBound_l1size (u : V →₀ ℝ) : TestBound u (l1size u ^ 2) := by + intro ι inst S hS hd + have habs : (∑ i, |segSum u (S i)|) ≤ l1size u := by + calc + (∑ i, |segSum u (S i)|) ≤ ∑ i, ∑ v ∈ S i, |u v| := + sum_le_sum fun i hi => abs_sum_le_sum_abs _ _ + _ = ∑ v ∈ univ.biUnion S, |u v| := + (sum_biUnion (by intro i hi j hj hij; exact hd hij)).symm + _ ≤ l1size u := finset_abs_sum_le_l1size u _ + have hsq := sum_sq_le_sq_sum_of_nonneg + (s := (univ : Finset ι)) (f := fun i => |segSum u (S i)|) (fun i hi => abs_nonneg _) + simp only [sq_abs] at hsq + have hnonneg : 0 ≤ ∑ i, |segSum u (S i)| := sum_nonneg (fun i hi => abs_nonneg _) + nlinarith [l1size_nonneg u] + have finsupp_has_testBound (u : V →₀ ℝ) : ∃ C, TestBound u C := ⟨_, testBound_l1size u⟩ + exact Seminorm.ofSMulLE (fun u : V →₀ ℝ => rho u) rho_zero + (fun u v => rho_add_le (finsupp_has_testBound u) (finsupp_has_testBound v)) + (fun a u => by simpa only [Real.norm_eq_abs, Finsupp.coe_smul] using rho_smul_le (finsupp_has_testBound u) a) + +/-- Finite coordinate vectors with the segment norm (a type synonym prevents +clashes with any other norm on finitely supported functions). -/ +def TestVector (V : Type) := V →₀ ℝ + +namespace TestVector + +variable {V : Type} + +instance : AddCommGroup (TestVector V) := inferInstanceAs (AddCommGroup (V →₀ ℝ)) + +instance : Module ℝ (TestVector V) := inferInstanceAs (Module ℝ (V →₀ ℝ)) + +def toFinsupp (u : TestVector V) : V →₀ ℝ := u + +instance : CoeFun (TestVector V) (fun _ => V → ℝ) := ⟨fun u => u.toFinsupp⟩ + +variable [PartialOrder V] + +instance : Norm (TestVector V) := ⟨fun u => rho u⟩ + +instance : NormedAddCommGroup (TestVector V) := by + have isSegment_singleton (v : V) : IsSegment ({v} : Finset V) := by + constructor + · intro a ha b hb + simp only [mem_singleton] at ha hb + subst a + subst b + exact Or.inl le_rfl + · intro a ha b hb c hac hcb + simp only [mem_singleton] at ha hb ⊢ + subst a + subst b + exact le_antisymm hcb hac + have TestBound.nonneg {u : V → ℝ} {C : ℝ} (h : TestBound u C) : 0 ≤ C := by + simpa using h PEmpty inferInstance PEmpty.elim (by simp) (by simp [Pairwise]) + have TestBound.single {u : V → ℝ} {C : ℝ} (h : TestBound u C) + {S : Finset V} (hS : IsSegment S) : segSum u S ^ 2 ≤ C := by + simpa using h Unit inferInstance (fun _ => S) (fun _ => hS) + (by simp [Pairwise]) + have TestBound.bddAbove {u : V → ℝ} {C : ℝ} (h : TestBound u C) : + BddAbove (testValues u) := by + refine ⟨C, ?_⟩ + rintro r ⟨ι, inst, S, hs, hd, rfl⟩ + exact h ι inst S hs hd + have testBound_squareSup {u : V → ℝ} (hu : ∃ C, TestBound u C) : + TestBound u (squareSup u) := by + intro ι inst S hs hd + exact le_csSup (TestBound.bddAbove hu.choose_spec) ⟨ι, inst, S, hs, hd, rfl⟩ + have squareSup_nonneg {u : V → ℝ} (hu : ∃ C, TestBound u C) : 0 ≤ squareSup u := + TestBound.nonneg (testBound_squareSup hu) + have rho_nonneg (u : V → ℝ) : 0 ≤ rho u := Real.sqrt_nonneg _ + have rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : rho u ^ 2 = squareSup u := + Real.sq_sqrt (squareSup_nonneg hu) + have testBound_rho_sq {u : V → ℝ} (hu : ∃ C, TestBound u C) : TestBound u (rho u ^ 2) := by + rw [rho_sq hu] + exact testBound_squareSup hu + have coordinate_le_rho {u : V → ℝ} (hu : ∃ C, TestBound u C) (v : V) : + |u v| ≤ rho u := by + have hh := TestBound.single (testBound_rho_sq hu) (isSegment_singleton v) + simp only [segSum, sum_singleton] at hh + exact (sq_le_sq₀ (abs_nonneg _) (rho_nonneg _)).mp (by simpa only [sq_abs] using hh) + have l1size_nonneg [PartialOrder V] (u : V →₀ ℝ) : 0 ≤ l1size u := + sum_nonneg (fun vertex _ => abs_nonneg (u vertex)) + have finset_abs_sum_le_l1size [PartialOrder V] (u : V →₀ ℝ) (S : Finset V) : + ∑ v ∈ S, |u v| ≤ l1size u := by + have he : (∑ v ∈ S ∪ u.support, |u v|) = l1size u := by + symm + apply sum_subset subset_union_right + intro v hv hn + rw [Finsupp.notMem_support_iff.mp hn, abs_zero] + rw [← he] + exact sum_le_sum_of_subset_of_nonneg subset_union_left (fun v hv hn => abs_nonneg _) + have testBound_l1size (u : V →₀ ℝ) : TestBound u (l1size u ^ 2) := by + intro ι inst S hS hd + have habs : (∑ i, |segSum u (S i)|) ≤ l1size u := by + calc + (∑ i, |segSum u (S i)|) ≤ ∑ i, ∑ v ∈ S i, |u v| := + sum_le_sum fun i hi => abs_sum_le_sum_abs _ _ + _ = ∑ v ∈ univ.biUnion S, |u v| := + (sum_biUnion (by intro i hi j hj hij; exact hd hij)).symm + _ ≤ l1size u := finset_abs_sum_le_l1size u _ + have hsq := sum_sq_le_sq_sum_of_nonneg + (s := (univ : Finset ι)) (f := fun i => |segSum u (S i)|) (fun i hi => abs_nonneg _) + simp only [sq_abs] at hsq + have hnonneg : 0 ≤ ∑ i, |segSum u (S i)| := sum_nonneg (fun i hi => abs_nonneg _) + nlinarith [l1size_nonneg u] + have finsupp_has_testBound (u : V →₀ ℝ) : ∃ C, TestBound u C := ⟨_, testBound_l1size u⟩ + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg u := apply_nonneg (segmentSeminorm V) u.toFinsupp + norm_triangle u v := map_add_le_add (segmentSeminorm V) u.toFinsupp v.toFinsupp + norm_smul a u := map_smul_eq_mul (segmentSeminorm V) a u.toFinsupp + norm_eq_zero_iff u := ⟨by + intro h + apply Finsupp.ext + intro v + have hh := coordinate_le_rho (finsupp_has_testBound u.toFinsupp) v + change rho u.toFinsupp = 0 at h + rw [h] at hh + exact abs_nonpos_iff.mp hh, by + rintro rfl + exact map_zero (segmentSeminorm V)⟩ } + +instance : NormedSpace ℝ (TestVector V) where + norm_smul_le a u := le_of_eq (map_smul_eq_mul (segmentSeminorm V) a u.toFinsupp) + +end TestVector + +/-- J(T), completion of the finite-support disjoint-segment norm. -/ +abbrev J (V : Type) [PartialOrder V] := UniformSpace.Completion (TestVector V) + +/-- The full continuous dual, used for the finite-height forest example. -/ +abbrev FullDual (V : Type) [PartialOrder V] := StrongDual ℝ (J V) + +section CoordinateCompletion + +variable {W : no_index Type} [PartialOrder W] + +instance fullDualAddCommGroup : AddCommGroup (FullDual W) := + inferInstanceAs (AddCommGroup (StrongDual ℝ (J W))) + +end CoordinateCompletion + +/-- Finite words, ordered by extension, including the empty root. -/ +structure Word where + letters : List ℕ + deriving DecidableEq + +namespace Word + +instance : PartialOrder Word where + le a b := a.letters <+: b.letters + le_refl _ := List.prefix_rfl + le_trans _ _ _ := List.IsPrefix.trans + le_antisymm a b hab hba := by + have h := hab.eq_of_length (Nat.le_antisymm hab.length_le hba.length_le) + cases a; cases b; cases h; rfl + +end Word + +/-- A disjoint forest: one copy of `Nat^{≤h}` for every `h≥1`. -/ +structure Vertex where + height : ℕ + positive : 1 ≤ height + word : Word + bounded : word.letters.length ≤ height + deriving DecidableEq + +namespace Vertex + +instance : PartialOrder Vertex where + le a b := a.height = b.height ∧ a.word ≤ b.word + le_refl _ := ⟨rfl,le_rfl⟩ + le_trans a b c hab hbc := ⟨hab.1.trans hbc.1,hab.2.trans hbc.2⟩ + le_antisymm a b hab hba := by + obtain ⟨hh, hw⟩ := hab + have he := le_antisymm hw hba.2 + cases a; cases b; cases hh; cases he; rfl + +end Vertex + +namespace Diamond + +/-- An oriented edge enumeration; only the associated undirected unit-edge +simple graph is used for distances. -/ +structure Network where + V : Type + E : Type + left : E → V + right : E → V + distinct : ∀ e, left e ≠ right e + +namespace Network + +variable (A : Network) + +def graph : SimpleGraph A.V where + Adj u v := ∃ e : A.E, (A.left e = u ∧ A.right e = v) ∨ + (A.right e = u ∧ A.left e = v) + symm := ⟨by + rintro u v ⟨e,h | h⟩ + · exact ⟨e,Or.inr ⟨h.2,h.1⟩⟩ + · exact ⟨e,Or.inl ⟨h.2,h.1⟩⟩⟩ + loopless := ⟨by + rintro u ⟨e,h | h⟩ + · exact A.distinct e (h.1.trans h.2.symm) + · exact A.distinct e (h.2.trans h.1.symm)⟩ + +/-- Every edge is replaced by countably many internally disjoint two-edge +paths. All old vertices remain, and each pair (edge,index) is a new midpoint. -/ +@[reducible] def refine : Network where + V := Sum A.V (A.E × ℕ) + E := A.E × ℕ × Bool + left e := if e.2.2 then Sum.inr (e.1,e.2.1) else Sum.inl (A.left e.1) + right e := if e.2.2 then Sum.inl (A.right e.1) else Sum.inr (e.1,e.2.1) + distinct := by rintro ⟨e,j,b⟩; cases b <;> simp + +/-- Iterating the very same edge replacement, starting from an arbitrary +network. This recursion groups the first replacement before the remaining ones. -/ +@[reducible] def iterate : Network → ℕ → Network + | A,0 => A + | A,n+1 => iterate A.refine n + +end Network + +/-- D₀ is precisely one edge. -/ +@[reducible] def base : Network where + V := Bool + E := Unit + left _ := false + right _ := true + distinct _ := by decide + +/-- Countably branching diamonds, all current edges of length one. -/ +@[reducible] def diamond (k : ℕ) := base.iterate k + +/-- The shortest-path distance, via Mathlib's actual graph distance. -/ +def distance (k : ℕ) (u v : (diamond k).V) : ℝ := ((diamond k).graph.dist u v : ℝ) +variable {E : Type} [NormedAddCommGroup E] [NormedSpace ℝ E] + +/-- The distortion convention, including its arbitrary positive scale. -/ +def EmbeddingBound (k : ℕ) (f : (diamond k).V → E) (C : ℝ) : Prop := + ∃ s : ℝ, 0 < s ∧ ∀ u v, + s*distance k u v ≤ ‖f u-f v‖ ∧ ‖f u-f v‖ ≤ C*s*distance k u v + +end Diamond + +/-- The space +is the full continuous dual of the specified segment-norm completion, not the +coordinate completion in place of that dual. -/ +theorem main_theorem : + (¬FiniteDimensional ℝ (FullDual Vertex)) ∧ + TopologicalSpace.SeparableSpace (FullDual Vertex) ∧ + Reflexive (FullDual Vertex) ∧ + (∀ (α β : ℝ) (R : EquivalentNorm (FullDual Vertex) α β), ¬IsAUC R.N) ∧ + (∀ t : ℝ, 0 < t → + Real.sqrt (1+t^2/12)-1 ≤ averageModulus (FullDual Vertex) norm t) ∧ + (∀ (k : ℕ) (f : (Diamond.diamond k).V → FullDual Vertex) (C : ℝ), + Diamond.EmbeddingBound k f C → Real.sqrt (1+(k:ℝ)/12) ≤ C) := by + sorry + +end ForestSpace + +end + +end OAI diff --git a/tasks/forest-space/tests/grade.py b/tasks/forest-space/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/forest-space/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/forest-space/tests/task.json b/tasks/forest-space/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f6e4f6bcb38b7bc1af13e3ae6f09765170894c83 --- /dev/null +++ b/tasks/forest-space/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ForestSpace", + "comparator": { + "theorem_names": [ + "OAI.ForestSpace.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10975 +} \ No newline at end of file diff --git a/tasks/forest-space/tests/test.sh b/tasks/forest-space/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/forest-space/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/formula-hitting/environment/Dockerfile b/tasks/formula-hitting/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/formula-hitting/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/formula-hitting/environment/fetch_mathlib.sh b/tasks/formula-hitting/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/formula-hitting/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/formula-hitting/environment/lake-manifest.json b/tasks/formula-hitting/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/formula-hitting/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/formula-hitting/environment/lakefile.lean b/tasks/formula-hitting/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/formula-hitting/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/formula-hitting/environment/lean_setup.sh b/tasks/formula-hitting/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/formula-hitting/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/formula-hitting/environment/pack_submission.py b/tasks/formula-hitting/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/formula-hitting/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/formula-hitting/instruction.md b/tasks/formula-hitting/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d73f261bfd80d88577115acc9a4f47cbf842b04a --- /dev/null +++ b/tasks/formula-hitting/instruction.md @@ -0,0 +1,117 @@ +# openai/math challenge `FormulaHitting` (family 116) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 116 of the release, *Uniform identity testing for noncommutative formulas* +(Theoretical computer science). The family as a whole: For each characteristic, constructs in deterministic polynomial bit time a polynomial-dimensional matrix tuple detecting every nonzero division-free noncommutative formula of bounded size over any field of that characteristic. Rational formulas over $\mathbb Q$ also admit polynomial-size hitting lists whenever they have a defined rational-matrix evaluation. + +The challenge is `FormulaHitting`, also at `/opt/openai-math/challenges/FormulaHitting.lean`: + +```lean +import Mathlib.Data.Matrix.Basic +import Mathlib.Data.Rat.Defs + +namespace OAI + +namespace NCHitting + +abbrev Word (n : ℕ) := List (Fin n) +abbrev WordSeries (F : Type*) (n : ℕ) := Word n → F + +def convolution {F : Type*} {n : ℕ} [Semiring F] + (f g : WordSeries F n) : Word n → F + | [] => f [] * g [] + | i :: w => f [] * g (i :: w) + convolution (fun v => f (i :: v)) g w + +inductive Formula (F : Type*) (n : ℕ) where + | scalar : F → Formula F n + | var : Fin n → Formula F n + | add : Formula F n → Formula F n → Formula F n + | mul : Formula F n → Formula F n → Formula F n + +namespace Formula + +def size {F : Type*} {n : ℕ} : Formula F n → ℕ + | scalar _ => 1 + | var _ => 1 + | add f g => f.size + g.size + 1 + | mul f g => f.size + g.size + 1 + +noncomputable def coeff {F : Type*} {n : ℕ} [Semiring F] : + Formula F n → WordSeries F n + | scalar a => fun w => if w = [] then a else 0 + | var i => fun w => if w = [i] then 1 else 0 + | add f g => fun w => coeff f w + coeff g w + | mul f g => convolution (coeff f) (coeff g) + +def eval {F A : Type*} {n : ℕ} [Semiring A] + (scalarMap : F → A) (T : Fin n → A) : Formula F n → A + | scalar a => scalarMap a + | var i => T i + | add f g => eval scalarMap T f + eval scalarMap T g + | mul f g => eval scalarMap T f * eval scalarMap T g + +end Formula + +def dimension (n s : ℕ) : ℕ := if n = 1 ∧ s = 1 then 1 else 2 * n * s ^ 2 + +def matrixEntry (i r q : ℕ) : ℚ := + if q < r then (-1 : ℚ) ^ (r - q - 1) / ((r : ℚ) * (i : ℚ) ^ (r - q)) + else 0 + +def generator (n s : ℕ) : Fin n → Matrix (Fin (dimension n s)) (Fin (dimension n s)) ℚ := + fun i r q => if n = 1 ∧ s = 1 then 1 else matrixEntry (i.val + 1) r.val q.val + +universe u_2 + +theorem universal_hitting (n s : ℕ) (hn : 1 ≤ n) (hs : 1 ≤ s) + (F : Type u_2) [Field F] [CharZero F] (f : Formula F n) + (hsize : f.size ≤ s) (hf : ∃ w, f.coeff w ≠ 0) : + f.eval (Matrix.scalar (Fin (dimension n s))) + (fun i r q => (generator n s i r q : F)) ≠ 0 := by + sorry + +end NCHitting + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FormulaHitting.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.NCHitting.universal_hitting` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/formula-hitting/solution/closure.txt b/tasks/formula-hitting/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ed56332ea8f0e9c6d7f481974d95fd36059e5f74 --- /dev/null +++ b/tasks/formula-hitting/solution/closure.txt @@ -0,0 +1,24 @@ +OAI.Algebra.FormulaHitting.DimensionBound +OAI.Algebra.FormulaHitting.Evaluation +OAI.Algebra.FormulaHitting.Formula +OAI.Algebra.FormulaHitting.FormulaSeries +OAI.Algebra.FormulaHitting.Generator +OAI.Algebra.FormulaHitting.Hitting +OAI.Algebra.FormulaHitting.Independence +OAI.Algebra.FormulaHitting.JetMatrix +OAI.Algebra.FormulaHitting.MinorFactor +OAI.Algebra.FormulaHitting.Minors +OAI.Algebra.FormulaHitting.Model +OAI.Algebra.FormulaHitting.Multiplicity +OAI.Algebra.FormulaHitting.NumeratorRows +OAI.Algebra.FormulaHitting.OrderBasis +OAI.Algebra.FormulaHitting.RationalTransfer +OAI.Algebra.FormulaHitting.Representation +OAI.Algebra.FormulaHitting.ScaledDerivatives +OAI.Algebra.FormulaHitting.Series +OAI.Algebra.FormulaHitting.SeriesFaithfulness +OAI.Algebra.FormulaHitting.System +OAI.Algebra.FormulaHitting.SystemOutput +OAI.Algebra.FormulaHitting.WordIndependence +OAI.Algebra.FormulaHitting.Wronskian +OAI.Algebra.FormulaHitting.WronskianBound diff --git a/tasks/formula-hitting/solution/reference.py b/tasks/formula-hitting/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/formula-hitting/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/formula-hitting/solution/solve.sh b/tasks/formula-hitting/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9a0b12b1a7c2618a587b9486f84a30c9e073320c --- /dev/null +++ b/tasks/formula-hitting/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FormulaHitting, i.e. module OAI.Algebra.FormulaHitting.Hitting and the +# 24 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.FormulaHitting.Hitting /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FormulaHitting" diff --git a/tasks/formula-hitting/task.toml b/tasks/formula-hitting/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0c59e187351d7fb4ed53ac8fa3c20140ef0718d4 --- /dev/null +++ b/tasks/formula-hitting/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/formula-hitting" +version = "1.0.0" +description = "Prove FormulaHitting (openai/math family 116: Uniform identity testing for noncommutative formulas) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FormulaHitting.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FormulaHitting" +family = "116" +family_title = "Uniform identity testing for noncommutative formulas" +subject = "Theoretical computer science" +theorems = ["OAI.NCHitting.universal_hitting"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.FormulaHitting.Hitting" +reference_modules = 24 +reference_lean_bytes = 123728 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 637 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11811 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/formula-hitting/tests/Challenge.lean b/tasks/formula-hitting/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c184de016d7f0265b9745e52a0b3540beb63da3 --- /dev/null +++ b/tasks/formula-hitting/tests/Challenge.lean @@ -0,0 +1,66 @@ +import Mathlib.Data.Matrix.Basic +import Mathlib.Data.Rat.Defs + +namespace OAI + +namespace NCHitting + +abbrev Word (n : ℕ) := List (Fin n) +abbrev WordSeries (F : Type*) (n : ℕ) := Word n → F + +def convolution {F : Type*} {n : ℕ} [Semiring F] + (f g : WordSeries F n) : Word n → F + | [] => f [] * g [] + | i :: w => f [] * g (i :: w) + convolution (fun v => f (i :: v)) g w + +inductive Formula (F : Type*) (n : ℕ) where + | scalar : F → Formula F n + | var : Fin n → Formula F n + | add : Formula F n → Formula F n → Formula F n + | mul : Formula F n → Formula F n → Formula F n + +namespace Formula + +def size {F : Type*} {n : ℕ} : Formula F n → ℕ + | scalar _ => 1 + | var _ => 1 + | add f g => f.size + g.size + 1 + | mul f g => f.size + g.size + 1 + +noncomputable def coeff {F : Type*} {n : ℕ} [Semiring F] : + Formula F n → WordSeries F n + | scalar a => fun w => if w = [] then a else 0 + | var i => fun w => if w = [i] then 1 else 0 + | add f g => fun w => coeff f w + coeff g w + | mul f g => convolution (coeff f) (coeff g) + +def eval {F A : Type*} {n : ℕ} [Semiring A] + (scalarMap : F → A) (T : Fin n → A) : Formula F n → A + | scalar a => scalarMap a + | var i => T i + | add f g => eval scalarMap T f + eval scalarMap T g + | mul f g => eval scalarMap T f * eval scalarMap T g + +end Formula + +def dimension (n s : ℕ) : ℕ := if n = 1 ∧ s = 1 then 1 else 2 * n * s ^ 2 + +def matrixEntry (i r q : ℕ) : ℚ := + if q < r then (-1 : ℚ) ^ (r - q - 1) / ((r : ℚ) * (i : ℚ) ^ (r - q)) + else 0 + +def generator (n s : ℕ) : Fin n → Matrix (Fin (dimension n s)) (Fin (dimension n s)) ℚ := + fun i r q => if n = 1 ∧ s = 1 then 1 else matrixEntry (i.val + 1) r.val q.val + +universe u_2 + +theorem universal_hitting (n s : ℕ) (hn : 1 ≤ n) (hs : 1 ≤ s) + (F : Type u_2) [Field F] [CharZero F] (f : Formula F n) + (hsize : f.size ≤ s) (hf : ∃ w, f.coeff w ≠ 0) : + f.eval (Matrix.scalar (Fin (dimension n s))) + (fun i r q => (generator n s i r q : F)) ≠ 0 := by + sorry + +end NCHitting + +end OAI diff --git a/tasks/formula-hitting/tests/grade.py b/tasks/formula-hitting/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/formula-hitting/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/formula-hitting/tests/task.json b/tasks/formula-hitting/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..76a1058bb9717e47c633850b3b06cb32a515d0eb --- /dev/null +++ b/tasks/formula-hitting/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FormulaHitting", + "comparator": { + "theorem_names": [ + "OAI.NCHitting.universal_hitting" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10911 +} \ No newline at end of file diff --git a/tasks/formula-hitting/tests/test.sh b/tasks/formula-hitting/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/formula-hitting/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/foulkes-howe/environment/Dockerfile b/tasks/foulkes-howe/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/foulkes-howe/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/foulkes-howe/environment/fetch_mathlib.sh b/tasks/foulkes-howe/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/foulkes-howe/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/foulkes-howe/environment/lake-manifest.json b/tasks/foulkes-howe/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/foulkes-howe/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/foulkes-howe/environment/lakefile.lean b/tasks/foulkes-howe/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/foulkes-howe/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/foulkes-howe/environment/lean_setup.sh b/tasks/foulkes-howe/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/foulkes-howe/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/foulkes-howe/environment/pack_submission.py b/tasks/foulkes-howe/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/foulkes-howe/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/foulkes-howe/instruction.md b/tasks/foulkes-howe/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8631a3847378658dd9401bf659d4e424ad0de029 --- /dev/null +++ b/tasks/foulkes-howe/instruction.md @@ -0,0 +1,101 @@ +# openai/math challenge `FoulkesHowe` (family 210) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 210 of the release, *Foulkes’ conjecture for sixth powers and quadratic stabilization* +(Algebra). The family as a whole: Proves the sixth case of Foulkes’ conjecture: $\operatorname{Sym}^6(\operatorname{Sym}^bV)$ embeds equivariantly in $\operatorname{Sym}^b(\operatorname{Sym}^6V)$ for every $b\ge6$ and finite-dimensional complex $V$. More generally, the canonical multiplication map $\operatorname{Sym}^b(\operatorname{Sym}^aV)\to\operatorname{Sym}^a(\operatorname{Sym}^bV)$ is surjective for $a\ge2$ and $b\ge a(a-1)$, giving dimension-independent quadratic stabilization. + +The challenge is `FoulkesHowe`, also at `/opt/openai-math/challenges/FoulkesHowe.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u + +namespace Problem346 + +def symMonomialRaw (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin n → V) : SymmetricAlgebra ℂ V := + ∏ i : Fin n, SymmetricAlgebra.ι ℂ V (v i) + +def symPowSubmodule (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] : + Submodule ℂ (SymmetricAlgebra ℂ V) := + Submodule.span ℂ (Set.range (symMonomialRaw n V)) + +abbrev SymPow (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] := + ↥(symPowSubmodule n V) + +def symMonomial (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin n → V) : SymPow n V := + ⟨symMonomialRaw n V v, Submodule.subset_span (Set.mem_range_self v)⟩ + +def foulkesFormula (a b : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin b → Fin a → V) : SymPow a (SymPow b V) := by + classical + exact + ((a.factorial : ℂ) ^ b)⁻¹ • + ∑ σ : Fin b → Equiv.Perm (Fin a), + symMonomial a (SymPow b V) + (fun i => symMonomial b V (fun j => v j ((σ j) i))) + +def IsFoulkesMap (a b : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (μ : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V)) : Prop := + ∀ v : Fin b → Fin a → V, + μ (symMonomial b (SymPow a V) (fun j => symMonomial a V (v j))) = + foulkesFormula a b V v + +theorem canonical_foulkes_howe_surjective : + ∀ (V : Type u) [AddCommGroup V] [Module ℂ V] [FiniteDimensional ℂ V] (a b : ℕ), 2 ≤ a → a * (a - 1) ≤ b → ∃ μ : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V), IsFoulkesMap a b V μ ∧ Function.Surjective μ ∧ ∀ ν : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V), IsFoulkesMap a b V ν → ν = μ := by + sorry + +end Problem346 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FoulkesHowe.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem346.canonical_foulkes_howe_surjective` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/foulkes-howe/solution/closure.txt b/tasks/foulkes-howe/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3ef6d33cd5011887a7a9968a0284b29eebf8cc03 --- /dev/null +++ b/tasks/foulkes-howe/solution/closure.txt @@ -0,0 +1,63 @@ +OAI.RepresentationTheory.FoulkesHowe.Actions +OAI.RepresentationTheory.FoulkesHowe.AlgebraEvaluation +OAI.RepresentationTheory.FoulkesHowe.Annihilator +OAI.RepresentationTheory.FoulkesHowe.BackwardCancellation +OAI.RepresentationTheory.FoulkesHowe.BinaryFactorization +OAI.RepresentationTheory.FoulkesHowe.BinaryVanishing +OAI.RepresentationTheory.FoulkesHowe.BlockInjectivity +OAI.RepresentationTheory.FoulkesHowe.BlockWeight +OAI.RepresentationTheory.FoulkesHowe.CanonicalMap +OAI.RepresentationTheory.FoulkesHowe.DegreeOne +OAI.RepresentationTheory.FoulkesHowe.DerivationInjectivity +OAI.RepresentationTheory.FoulkesHowe.DiagonalCoefficient +OAI.RepresentationTheory.FoulkesHowe.DiagonalPolarization +OAI.RepresentationTheory.FoulkesHowe.DualEmbedding +OAI.RepresentationTheory.FoulkesHowe.EncodedCancellation +OAI.RepresentationTheory.FoulkesHowe.EncodingHomogeneous +OAI.RepresentationTheory.FoulkesHowe.FiniteDimension +OAI.RepresentationTheory.FoulkesHowe.FirstCounts +OAI.RepresentationTheory.FoulkesHowe.FirstLabels +OAI.RepresentationTheory.FoulkesHowe.FirstPolynomial +OAI.RepresentationTheory.FoulkesHowe.FirstTransfer +OAI.RepresentationTheory.FoulkesHowe.FlattenedForm +OAI.RepresentationTheory.FoulkesHowe.FoulkesDiagonal +OAI.RepresentationTheory.FoulkesHowe.FoulkesMultilinear +OAI.RepresentationTheory.FoulkesHowe.FoulkesSymmetries +OAI.RepresentationTheory.FoulkesHowe.Functoriality +OAI.RepresentationTheory.FoulkesHowe.GeneratorLift +OAI.RepresentationTheory.FoulkesHowe.GridCancellation +OAI.RepresentationTheory.FoulkesHowe.LinearCase +OAI.RepresentationTheory.FoulkesHowe.Model +OAI.RepresentationTheory.FoulkesHowe.MonomialCut +OAI.RepresentationTheory.FoulkesHowe.MonomialMultilinear +OAI.RepresentationTheory.FoulkesHowe.MultilinearPolynomial +OAI.RepresentationTheory.FoulkesHowe.Multiplication +OAI.RepresentationTheory.FoulkesHowe.Naturality +OAI.RepresentationTheory.FoulkesHowe.PairingConstruction +OAI.RepresentationTheory.FoulkesHowe.PermanentPairing +OAI.RepresentationTheory.FoulkesHowe.PlethysmDual +OAI.RepresentationTheory.FoulkesHowe.Polarization +OAI.RepresentationTheory.FoulkesHowe.PolynomialShift +OAI.RepresentationTheory.FoulkesHowe.PowerSpan +OAI.RepresentationTheory.FoulkesHowe.ProductVanishing +OAI.RepresentationTheory.FoulkesHowe.SecondCounts +OAI.RepresentationTheory.FoulkesHowe.SecondEndpoints +OAI.RepresentationTheory.FoulkesHowe.SecondLabels +OAI.RepresentationTheory.FoulkesHowe.SecondSwap +OAI.RepresentationTheory.FoulkesHowe.SecondTransfer +OAI.RepresentationTheory.FoulkesHowe.ShiftInjectivity +OAI.RepresentationTheory.FoulkesHowe.ShiftNilpotence +OAI.RepresentationTheory.FoulkesHowe.SlotDerivative +OAI.RepresentationTheory.FoulkesHowe.Spanning +OAI.RepresentationTheory.FoulkesHowe.SpanningAgreement +OAI.RepresentationTheory.FoulkesHowe.Stabilization +OAI.RepresentationTheory.FoulkesHowe.Surjectivity +OAI.RepresentationTheory.FoulkesHowe.SymmetricDual +OAI.RepresentationTheory.FoulkesHowe.SymmetricLift +OAI.RepresentationTheory.FoulkesHowe.TensorPresentation +OAI.RepresentationTheory.FoulkesHowe.TransferDerivative +OAI.RepresentationTheory.FoulkesHowe.TransferEndpoints +OAI.RepresentationTheory.FoulkesHowe.Vanishing +OAI.RepresentationTheory.FoulkesHowe.VanishingFirst +OAI.RepresentationTheory.FoulkesHowe.VanishingInduction +OAI.RepresentationTheory.FoulkesHowe.VanishingOne diff --git a/tasks/foulkes-howe/solution/reference.py b/tasks/foulkes-howe/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/foulkes-howe/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/foulkes-howe/solution/solve.sh b/tasks/foulkes-howe/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cd328eb7473701366361b540dacad20d6969d920 --- /dev/null +++ b/tasks/foulkes-howe/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FoulkesHowe, i.e. module OAI.RepresentationTheory.FoulkesHowe.Stabilization and the +# 63 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RepresentationTheory.FoulkesHowe.Stabilization /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FoulkesHowe" diff --git a/tasks/foulkes-howe/task.toml b/tasks/foulkes-howe/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..810a1b48787909c59a5f3f678e33057eeb2f803f --- /dev/null +++ b/tasks/foulkes-howe/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/foulkes-howe" +version = "1.0.0" +description = "Prove FoulkesHowe (openai/math family 210: Foulkes’ conjecture for sixth powers and quadratic stabilization) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FoulkesHowe.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FoulkesHowe" +family = "210" +family_title = "Foulkes’ conjecture for sixth powers and quadratic stabilization" +subject = "Algebra" +theorems = ["OAI.Problem346.canonical_foulkes_howe_surjective"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RepresentationTheory.FoulkesHowe.Stabilization" +reference_modules = 63 +reference_lean_bytes = 197207 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1045 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11877 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/foulkes-howe/tests/Challenge.lean b/tasks/foulkes-howe/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2320f7269dac7ccd52e0a49325ae4acc7e28432e --- /dev/null +++ b/tasks/foulkes-howe/tests/Challenge.lean @@ -0,0 +1,50 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators +universe u + +namespace Problem346 + +def symMonomialRaw (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin n → V) : SymmetricAlgebra ℂ V := + ∏ i : Fin n, SymmetricAlgebra.ι ℂ V (v i) + +def symPowSubmodule (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] : + Submodule ℂ (SymmetricAlgebra ℂ V) := + Submodule.span ℂ (Set.range (symMonomialRaw n V)) + +abbrev SymPow (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] := + ↥(symPowSubmodule n V) + +def symMonomial (n : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin n → V) : SymPow n V := + ⟨symMonomialRaw n V v, Submodule.subset_span (Set.mem_range_self v)⟩ + +def foulkesFormula (a b : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (v : Fin b → Fin a → V) : SymPow a (SymPow b V) := by + classical + exact + ((a.factorial : ℂ) ^ b)⁻¹ • + ∑ σ : Fin b → Equiv.Perm (Fin a), + symMonomial a (SymPow b V) + (fun i => symMonomial b V (fun j => v j ((σ j) i))) + +def IsFoulkesMap (a b : ℕ) (V : Type u) [AddCommGroup V] [Module ℂ V] + (μ : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V)) : Prop := + ∀ v : Fin b → Fin a → V, + μ (symMonomial b (SymPow a V) (fun j => symMonomial a V (v j))) = + foulkesFormula a b V v + +theorem canonical_foulkes_howe_surjective : + ∀ (V : Type u) [AddCommGroup V] [Module ℂ V] [FiniteDimensional ℂ V] (a b : ℕ), 2 ≤ a → a * (a - 1) ≤ b → ∃ μ : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V), IsFoulkesMap a b V μ ∧ Function.Surjective μ ∧ ∀ ν : SymPow b (SymPow a V) →ₗ[ℂ] SymPow a (SymPow b V), IsFoulkesMap a b V ν → ν = μ := by + sorry + +end Problem346 + +end + +end OAI diff --git a/tasks/foulkes-howe/tests/grade.py b/tasks/foulkes-howe/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/foulkes-howe/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/foulkes-howe/tests/task.json b/tasks/foulkes-howe/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1630b272bd6db086a273496c467cc2c5a9b6fd9c --- /dev/null +++ b/tasks/foulkes-howe/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FoulkesHowe", + "comparator": { + "theorem_names": [ + "OAI.Problem346.canonical_foulkes_howe_surjective" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10977 +} \ No newline at end of file diff --git a/tasks/foulkes-howe/tests/test.sh b/tasks/foulkes-howe/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/foulkes-howe/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/four-row-permanent/environment/Dockerfile b/tasks/four-row-permanent/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/four-row-permanent/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/four-row-permanent/environment/fetch_mathlib.sh b/tasks/four-row-permanent/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/four-row-permanent/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/four-row-permanent/environment/lake-manifest.json b/tasks/four-row-permanent/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/four-row-permanent/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/four-row-permanent/environment/lakefile.lean b/tasks/four-row-permanent/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/four-row-permanent/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/four-row-permanent/environment/lean_setup.sh b/tasks/four-row-permanent/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/four-row-permanent/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/four-row-permanent/environment/pack_submission.py b/tasks/four-row-permanent/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/four-row-permanent/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/four-row-permanent/instruction.md b/tasks/four-row-permanent/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..890cb173c3752b3e4993f9d8b04edfc557f54c0a --- /dev/null +++ b/tasks/four-row-permanent/instruction.md @@ -0,0 +1,99 @@ +# openai/math challenge `FourRowPermanent` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `FourRowPermanent`, also at `/opt/openai-math/challenges/FourRowPermanent.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# A robust four-row permanent inequality + +`Fin 4` labels four sites. A law is represented by real probability masses; +`IsProbability` asserts nonnegativity and total mass one. All row norms use +the uniform counting normalization. +-/ + +noncomputable section +namespace FourRow +open scoped BigOperators + +abbrev Site := Fin 4 +abbrev Perm := Equiv.Perm Site +abbrev Law := Perm → ℝ +abbrev Functions := Site → Site → ℝ + +def IsProbability (ν : Law) : Prop := + (∀ π, 0 ≤ ν π) ∧ ∑ π, ν π = 1 + +def UniformMarginals (ν : Law) : Prop := + ∀ i j : Site, ∑ π, (if π i = j then ν π else 0) = 1 / 4 + +def totalVariation (ν : Law) : ℝ := + (∑ π, |ν π - 1 / 24|) / 2 + +def lpNorm (p : ℝ) (f : Site → ℝ) : ℝ := + ((∑ j, (f j) ^ p) / 4) ^ (1 / p) + +def permanentExpectation (ν : Law) (f : Functions) : ℝ := + ∑ π, ν π * ∏ i, f i (π i) + +theorem robust_permanent : + ∃ p₀ : ℝ, 4 / 3 < p₀ ∧ p₀ < 2 ∧ + ∃ ε : ℝ, 0 < ε ∧ ∀ ν : Law, + IsProbability ν → totalVariation ν < ε → UniformMarginals ν → + ∀ f : Functions, (∀ i j, 0 ≤ f i j) → + permanentExpectation ν f ≤ ∏ i, lpNorm p₀ (f i) := by + sorry + +end FourRow +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FourRowPermanent.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FourRow.robust_permanent` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/four-row-permanent/solution/closure.txt b/tasks/four-row-permanent/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8738b9ac810d3a5926438180c89b9df9bb5fb1ad --- /dev/null +++ b/tasks/four-row-permanent/solution/closure.txt @@ -0,0 +1,5 @@ +OAI.Combinatorics.Permanent.Main +OAI.Combinatorics.Permanent.Model +OAI.Combinatorics.Permanent.Norm +OAI.Combinatorics.Permanent.Perturbation +OAI.Combinatorics.Permanent.Stability diff --git a/tasks/four-row-permanent/solution/reference.py b/tasks/four-row-permanent/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/four-row-permanent/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/four-row-permanent/solution/solve.sh b/tasks/four-row-permanent/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..09ac1a54e6162a8b06758c2fab0f1ba991633a8a --- /dev/null +++ b/tasks/four-row-permanent/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FourRowPermanent, i.e. module OAI.Combinatorics.Permanent.Main and the +# 5 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Permanent.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FourRowPermanent" diff --git a/tasks/four-row-permanent/task.toml b/tasks/four-row-permanent/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..83a6964974d8f41b26a9c47a1bac7c67d783e52c --- /dev/null +++ b/tasks/four-row-permanent/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/four-row-permanent" +version = "1.0.0" +description = "Prove FourRowPermanent (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FourRowPermanent.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FourRowPermanent" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.FourRow.robust_permanent"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Permanent.Main" +reference_modules = 5 +reference_lean_bytes = 24646 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 788 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11722 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/four-row-permanent/tests/Challenge.lean b/tasks/four-row-permanent/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0d58c8b146ddadde68e2ee900133094c0f2bda25 --- /dev/null +++ b/tasks/four-row-permanent/tests/Challenge.lean @@ -0,0 +1,48 @@ +import Mathlib + +namespace OAI + +/-! +# A robust four-row permanent inequality + +`Fin 4` labels four sites. A law is represented by real probability masses; +`IsProbability` asserts nonnegativity and total mass one. All row norms use +the uniform counting normalization. +-/ + +noncomputable section +namespace FourRow +open scoped BigOperators + +abbrev Site := Fin 4 +abbrev Perm := Equiv.Perm Site +abbrev Law := Perm → ℝ +abbrev Functions := Site → Site → ℝ + +def IsProbability (ν : Law) : Prop := + (∀ π, 0 ≤ ν π) ∧ ∑ π, ν π = 1 + +def UniformMarginals (ν : Law) : Prop := + ∀ i j : Site, ∑ π, (if π i = j then ν π else 0) = 1 / 4 + +def totalVariation (ν : Law) : ℝ := + (∑ π, |ν π - 1 / 24|) / 2 + +def lpNorm (p : ℝ) (f : Site → ℝ) : ℝ := + ((∑ j, (f j) ^ p) / 4) ^ (1 / p) + +def permanentExpectation (ν : Law) (f : Functions) : ℝ := + ∑ π, ν π * ∏ i, f i (π i) + +theorem robust_permanent : + ∃ p₀ : ℝ, 4 / 3 < p₀ ∧ p₀ < 2 ∧ + ∃ ε : ℝ, 0 < ε ∧ ∀ ν : Law, + IsProbability ν → totalVariation ν < ε → UniformMarginals ν → + ∀ f : Functions, (∀ i j, 0 ≤ f i j) → + permanentExpectation ν f ≤ ∏ i, lpNorm p₀ (f i) := by + sorry + +end FourRow +end + +end OAI diff --git a/tasks/four-row-permanent/tests/grade.py b/tasks/four-row-permanent/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/four-row-permanent/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/four-row-permanent/tests/task.json b/tasks/four-row-permanent/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ac9eb5243a34eb3f4c823b50001dc56b35fad7b2 --- /dev/null +++ b/tasks/four-row-permanent/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FourRowPermanent", + "comparator": { + "theorem_names": [ + "OAI.FourRow.robust_permanent" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10822 +} \ No newline at end of file diff --git a/tasks/four-row-permanent/tests/test.sh b/tasks/four-row-permanent/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/four-row-permanent/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/free-ising/environment/Dockerfile b/tasks/free-ising/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/free-ising/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/free-ising/environment/fetch_mathlib.sh b/tasks/free-ising/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/free-ising/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/free-ising/environment/lake-manifest.json b/tasks/free-ising/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/free-ising/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/free-ising/environment/lakefile.lean b/tasks/free-ising/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/free-ising/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/free-ising/environment/lean_setup.sh b/tasks/free-ising/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/free-ising/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/free-ising/environment/pack_submission.py b/tasks/free-ising/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/free-ising/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/free-ising/instruction.md b/tasks/free-ising/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f145319d5640f734246224fece056305c90f0e8f --- /dev/null +++ b/tasks/free-ising/instruction.md @@ -0,0 +1,146 @@ +# openai/math challenge `FreeIsing` (family 236) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 236 of the release, *The factor-of-IID threshold for free Ising states on trees* +(Probability and statistical mechanics). The family as a whole: Determines when the free zero-field ferromagnetic Ising state on the infinite $d$-regular tree is a factor of independent vertex labels: exactly when $\tanh\beta\le(d-1)^{-1/2}$, including equality, for $d\ge3$ and $\beta\ge0$. The construction uses no root and is almost surely equivariant for each fixed tree automorphism, resolving the ferromagnetic case of Lyons's question. + +The challenge is `FreeIsing`, also at `/opt/openai-math/challenges/FreeIsing.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory + +namespace Problem367 + +abbrev TreeVertex (d : ℕ) := + {word : List (Fin d) // List.IsChain (fun first second : Fin d => first ≠ second) word} + +def treeAdj {d : ℕ} (u v : TreeVertex d) : Prop := + (∃ c : Fin d, v.1 = u.1 ++ [c]) ∨ + (∃ c : Fin d, u.1 = v.1 ++ [c]) + +structure TreeAut (d : ℕ) where + toEquiv : TreeVertex d ≃ TreeVertex d + map_adj : ∀ u v, treeAdj (toEquiv u) (toEquiv v) ↔ treeAdj u v + +def relabel {d : ℕ} {α : Type*} (g : TreeAut d) + (x : TreeVertex d → α) : TreeVertex d → α := + fun v => x (g.toEquiv.symm v) + +inductive IsingSpin where + | neg + | pos + deriving DecidableEq + +protected abbrev IsingSpin.enumList : List IsingSpin := [.neg, .pos] + +protected theorem IsingSpin.enumList_getElem?_ctorIdx_eq (x : IsingSpin) : + IsingSpin.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem IsingSpin.enumList_nodup : IsingSpin.enumList.Nodup := by decide + +instance : Fintype IsingSpin where + elems := ⟨IsingSpin.enumList, IsingSpin.enumList_nodup⟩ + complete x := by cases x <;> decide + +instance isingSpinMeasurable : MeasurableSpace IsingSpin := ⊤ + +def uniform01 : Measure ℝ := + volume.restrict (Set.Icc (0 : ℝ) 1) + +instance uniform01Probability : IsProbabilityMeasure uniform01 where + measure_univ := by simp [uniform01] + +def labelMeasure (d : ℕ) : Measure (TreeVertex d → ℝ) := by + classical + exact Measure.infinitePi (fun _ : TreeVertex d => uniform01) + +def ConnectedFinset {d : ℕ} (D : Finset (TreeVertex d)) : Prop := + D.Nonempty ∧ + ∀ u ∈ D, ∀ v ∈ D, + Relation.ReflTransGen + (fun x y : TreeVertex d => x ∈ D ∧ y ∈ D ∧ treeAdj x y) u v + +def inducedEdges {d : ℕ} (D : Finset (TreeVertex d)) : + Finset (TreeVertex d × TreeVertex d) := by + classical + exact (D.product D).filter (fun e => + treeAdj e.1 e.2 ∧ e.1.1.length < e.2.1.length) + +def freeCylinderWeight {d : ℕ} (theta : ℝ) + (D : Finset (TreeVertex d)) (eta : TreeVertex d → IsingSpin) : ENNReal := + ENNReal.ofReal + ((1 / 2 : ℝ) * + Finset.prod (inducedEdges D) (fun e => + (1 + (if eta e.1 = eta e.2 then theta else -theta)) / 2)) + +def HasFreeIsingLaw {d : ℕ} (theta : ℝ) + (mu : Measure (TreeVertex d → IsingSpin)) : Prop := + ∀ (D : Finset (TreeVertex d)), ConnectedFinset D → + ∀ eta : TreeVertex d → IsingSpin, + mu {x | ∀ v ∈ D, x v = eta v} = freeCylinderWeight theta D eta + +def IsFactorOfIID (d : ℕ) (theta : ℝ) : Prop := + ∃ Phi : (TreeVertex d → ℝ) → (TreeVertex d → IsingSpin), + Measurable Phi ∧ + HasFreeIsingLaw theta (Measure.map Phi (labelMeasure d)) ∧ + ∀ g : TreeAut d, + ∀ᵐ U ∂labelMeasure d, Phi (relabel g U) = relabel g (Phi U) + +theorem free_ising_factor_iff_threshold : + ∀ (d : ℕ) (beta : ℝ), 3 ≤ d → 0 ≤ beta → (IsFactorOfIID d (Real.tanh beta) ↔ Real.tanh beta ≤ 1 / Real.sqrt ((d : ℝ) - 1)) := by + sorry + +end Problem367 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FreeIsing.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem367.free_ising_factor_iff_threshold` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/free-ising/solution/closure.txt b/tasks/free-ising/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..56c4b9252a124383f92cef994dedca20cc6a07f7 --- /dev/null +++ b/tasks/free-ising/solution/closure.txt @@ -0,0 +1,891 @@ +OAI.Probability.FreeIsing.Brownian.ArbitraryHorizon +OAI.Probability.FreeIsing.Brownian.ArrayCompensator +OAI.Probability.FreeIsing.Brownian.ArrayCrossIsometry +OAI.Probability.FreeIsing.Brownian.ArrayFiltrationIntegral +OAI.Probability.FreeIsing.Brownian.ArrayInnovation +OAI.Probability.FreeIsing.Brownian.ArrayIntegralCompletion +OAI.Probability.FreeIsing.Brownian.ArrayLaw +OAI.Probability.FreeIsing.Brownian.ArrayMoments +OAI.Probability.FreeIsing.Brownian.ArrayObservation +OAI.Probability.FreeIsing.Brownian.ArraySimpleIntegral +OAI.Probability.FreeIsing.Brownian.Bridge +OAI.Probability.FreeIsing.Brownian.Characterization +OAI.Probability.FreeIsing.Brownian.CoefficientApproximationIdentification +OAI.Probability.FreeIsing.Brownian.ContinuousAssociativity +OAI.Probability.FreeIsing.Brownian.ContinuousCompensator +OAI.Probability.FreeIsing.Brownian.ContinuousCross +OAI.Probability.FreeIsing.Brownian.ContinuousExistence +OAI.Probability.FreeIsing.Brownian.ContinuousIntegral +OAI.Probability.FreeIsing.Brownian.ContinuousRowCompletion +OAI.Probability.FreeIsing.Brownian.ContinuousSpatialIntegral +OAI.Probability.FreeIsing.Brownian.DenseModification +OAI.Probability.FreeIsing.Brownian.DriftMoments +OAI.Probability.FreeIsing.Brownian.DyadicMoments +OAI.Probability.FreeIsing.Brownian.EntropyEnergy +OAI.Probability.FreeIsing.Brownian.Existence +OAI.Probability.FreeIsing.Brownian.FiltrationIntegral +OAI.Probability.FreeIsing.Brownian.FiltrationIntegralProperties +OAI.Probability.FreeIsing.Brownian.FiltrationSquare +OAI.Probability.FreeIsing.Brownian.FiltrationUniformIntegral +OAI.Probability.FreeIsing.Brownian.FourthMoment +OAI.Probability.FreeIsing.Brownian.GlobalCompensator +OAI.Probability.FreeIsing.Brownian.GridRefinement +OAI.Probability.FreeIsing.Brownian.Information +OAI.Probability.FreeIsing.Brownian.Innovation +OAI.Probability.FreeIsing.Brownian.IntegralCompensator +OAI.Probability.FreeIsing.Brownian.IntegralContinuitySupport +OAI.Probability.FreeIsing.Brownian.IntegralHorizon +OAI.Probability.FreeIsing.Brownian.IntegralProcess +OAI.Probability.FreeIsing.Brownian.IntegralProperties +OAI.Probability.FreeIsing.Brownian.IntegralTransport +OAI.Probability.FreeIsing.Brownian.LinearCombination +OAI.Probability.FreeIsing.Brownian.Martingale +OAI.Probability.FreeIsing.Brownian.MeanSquareDescent +OAI.Probability.FreeIsing.Brownian.MeanSquarePullback +OAI.Probability.FreeIsing.Brownian.Observation +OAI.Probability.FreeIsing.Brownian.PathLikelihood +OAI.Probability.FreeIsing.Brownian.PosteriorBareResponse +OAI.Probability.FreeIsing.Brownian.PosteriorField +OAI.Probability.FreeIsing.Brownian.PosteriorMoments +OAI.Probability.FreeIsing.Brownian.RandomEvaluation +OAI.Probability.FreeIsing.Brownian.RationalHorizon +OAI.Probability.FreeIsing.Brownian.ResponseTransport +OAI.Probability.FreeIsing.Brownian.RowComparisonConstruction +OAI.Probability.FreeIsing.Brownian.RowEnergyCompletion +OAI.Probability.FreeIsing.Brownian.SimpleIntegral +OAI.Probability.FreeIsing.Brownian.SpatialAssociativity +OAI.Probability.FreeIsing.Brownian.SpatialCompensator +OAI.Probability.FreeIsing.Brownian.SpatialIntegral +OAI.Probability.FreeIsing.Brownian.SpatialPrimitive +OAI.Probability.FreeIsing.Brownian.SpinRecovery +OAI.Probability.FreeIsing.Brownian.StoppedIsometry +OAI.Probability.FreeIsing.Brownian.UniformErrorContinuity +OAI.Probability.FreeIsing.Brownian.UniformGrid +OAI.Probability.FreeIsing.Brownian.UniformIntegral +OAI.Probability.FreeIsing.Brownian.UniformIsometry +OAI.Probability.FreeIsing.Brownian.UniformSumCongruence +OAI.Probability.FreeIsing.Cavity.Array +OAI.Probability.FreeIsing.Cavity.ArraySmallLogLoss +OAI.Probability.FreeIsing.Cavity.ArtanhFusion +OAI.Probability.FreeIsing.Cavity.BaseMoments +OAI.Probability.FreeIsing.Cavity.BinaryMixture +OAI.Probability.FreeIsing.Cavity.FieldL2Limit +OAI.Probability.FreeIsing.Cavity.Homeomorph +OAI.Probability.FreeIsing.Cavity.LogOdds +OAI.Probability.FreeIsing.Cavity.MomentRecurrence +OAI.Probability.FreeIsing.Cavity.MomentTail +OAI.Probability.FreeIsing.Cavity.MomentTransport +OAI.Probability.FreeIsing.Cavity.Pair +OAI.Probability.FreeIsing.Conditioning.Attenuation +OAI.Probability.FreeIsing.Conditioning.BroadcastFamilyConditional +OAI.Probability.FreeIsing.Conditioning.CenteredCopyDifference +OAI.Probability.FreeIsing.Conditioning.Characteristic +OAI.Probability.FreeIsing.Conditioning.ComponentConditionalRecursionInputs +OAI.Probability.FreeIsing.Conditioning.ComponentInformation +OAI.Probability.FreeIsing.Conditioning.ComponentInformationUpper +OAI.Probability.FreeIsing.Conditioning.ConstructedConditionalCopies +OAI.Probability.FreeIsing.Conditioning.ConstructedContinuousCopies +OAI.Probability.FreeIsing.Conditioning.ContinuousCopyImmersion +OAI.Probability.FreeIsing.Conditioning.ContinuousCopyIndependence +OAI.Probability.FreeIsing.Conditioning.Copies +OAI.Probability.FreeIsing.Conditioning.CopyArrayBrownian +OAI.Probability.FreeIsing.Conditioning.CopyBrownian +OAI.Probability.FreeIsing.Conditioning.CopyCompensatedSquare +OAI.Probability.FreeIsing.Conditioning.CopyDifference +OAI.Probability.FreeIsing.Conditioning.CopyFiltration +OAI.Probability.FreeIsing.Conditioning.CopyImmersion +OAI.Probability.FreeIsing.Conditioning.CopyIntegralTransport +OAI.Probability.FreeIsing.Conditioning.CopyInvariance +OAI.Probability.FreeIsing.Conditioning.CopyRowConstruction +OAI.Probability.FreeIsing.Conditioning.CopyVariance +OAI.Probability.FreeIsing.Conditioning.CovarianceLimit +OAI.Probability.FreeIsing.Conditioning.CutLevelConditionalMean +OAI.Probability.FreeIsing.Conditioning.Descent +OAI.Probability.FreeIsing.Conditioning.DiscreteConditioning +OAI.Probability.FreeIsing.Conditioning.FactorRecovery +OAI.Probability.FreeIsing.Conditioning.FamilyConditionalPullback +OAI.Probability.FreeIsing.Conditioning.FiniteBayes +OAI.Probability.FreeIsing.Conditioning.FiniteBayesCondExp +OAI.Probability.FreeIsing.Conditioning.FiniteBayesExp +OAI.Probability.FreeIsing.Conditioning.FiniteEntropySmallTime +OAI.Probability.FreeIsing.Conditioning.FiniteFieldEntropyExpectation +OAI.Probability.FreeIsing.Conditioning.FiniteObservationInformation +OAI.Probability.FreeIsing.Conditioning.Fubini +OAI.Probability.FreeIsing.Conditioning.GaussianVector +OAI.Probability.FreeIsing.Conditioning.InformationTransport +OAI.Probability.FreeIsing.Conditioning.InnovationConditionalMoments +OAI.Probability.FreeIsing.Conditioning.KernelConditionalExpectation +OAI.Probability.FreeIsing.Conditioning.KernelExtensionConditionalExpectation +OAI.Probability.FreeIsing.Conditioning.Naturality +OAI.Probability.FreeIsing.Conditioning.NoisyBranchConditionalLaw +OAI.Probability.FreeIsing.Conditioning.NoisyCopyDifference +OAI.Probability.FreeIsing.Conditioning.ObservationCopyStationarity +OAI.Probability.FreeIsing.Conditioning.ObservationInformation +OAI.Probability.FreeIsing.Conditioning.PlantedInformation +OAI.Probability.FreeIsing.Conditioning.Product +OAI.Probability.FreeIsing.Conditioning.Pullback +OAI.Probability.FreeIsing.Conditioning.Regrouping +OAI.Probability.FreeIsing.Conditioning.SelectedFieldConditionedMoments +OAI.Probability.FreeIsing.Conditioning.SelectedPosteriorEvenConditioning +OAI.Probability.FreeIsing.Conditioning.ShiftedLoss +OAI.Probability.FreeIsing.Conditioning.SideSignalLoss +OAI.Probability.FreeIsing.Conditioning.StatisticLoss +OAI.Probability.FreeIsing.Conditioning.StrictPosteriorInformation +OAI.Probability.FreeIsing.Critical.Branching +OAI.Probability.FreeIsing.Critical.CanonicalResponse +OAI.Probability.FreeIsing.Critical.CanonicalRowEnergy +OAI.Probability.FreeIsing.Critical.ClusterFactorEnvironment +OAI.Probability.FreeIsing.Critical.CodedPercolation +OAI.Probability.FreeIsing.Critical.Comparison +OAI.Probability.FreeIsing.Critical.Endgame +OAI.Probability.FreeIsing.Critical.GlobalEndgame +OAI.Probability.FreeIsing.Critical.Information +OAI.Probability.FreeIsing.Critical.NoisePathConstants +OAI.Probability.FreeIsing.Critical.NormalizedEnergy +OAI.Probability.FreeIsing.Critical.Percolation +OAI.Probability.FreeIsing.Critical.Reduction +OAI.Probability.FreeIsing.Critical.ResponseIntrinsic +OAI.Probability.FreeIsing.Critical.ResponseTimeEnergy +OAI.Probability.FreeIsing.Critical.TimeUniqueness +OAI.Probability.FreeIsing.Energy.ActualCriticalFieldMoments +OAI.Probability.FreeIsing.Energy.ArtanhResponseCoefficients +OAI.Probability.FreeIsing.Energy.Attenuation +OAI.Probability.FreeIsing.Energy.AttenuationMoments +OAI.Probability.FreeIsing.Energy.AttenuationProduct +OAI.Probability.FreeIsing.Energy.CompensatedSquareEnergy +OAI.Probability.FreeIsing.Energy.ComponentCovariance +OAI.Probability.FreeIsing.Energy.CoupledAttenuation +OAI.Probability.FreeIsing.Energy.CoupledResponseRows +OAI.Probability.FreeIsing.Energy.CrossEnergyRiemann +OAI.Probability.FreeIsing.Energy.DiscrepancyEnergy +OAI.Probability.FreeIsing.Energy.DiscrepancyRowEnergy +OAI.Probability.FreeIsing.Energy.DriftSquareEnergy +OAI.Probability.FreeIsing.Energy.EnergyLimit +OAI.Probability.FreeIsing.Energy.EnergyRiemannApproximation +OAI.Probability.FreeIsing.Energy.FiniteIsingCrossEnergy +OAI.Probability.FreeIsing.Energy.FiniteIsingEnergyLimit +OAI.Probability.FreeIsing.Energy.FiniteIsingFieldEnergy +OAI.Probability.FreeIsing.Energy.FiniteLeafCovariance +OAI.Probability.FreeIsing.Energy.FreeLawLocalCovariance +OAI.Probability.FreeIsing.Energy.IndependentMoments +OAI.Probability.FreeIsing.Energy.LinearTiltVariance +OAI.Probability.FreeIsing.Energy.MixedCrossEnergyRiemann +OAI.Probability.FreeIsing.Energy.MixedMoments +OAI.Probability.FreeIsing.Energy.MomentCombinatorics +OAI.Probability.FreeIsing.Energy.MomentInduction +OAI.Probability.FreeIsing.Energy.MomentTail +OAI.Probability.FreeIsing.Energy.NNRealBoundedDriftEnergy +OAI.Probability.FreeIsing.Energy.NoisyLocalCovariance +OAI.Probability.FreeIsing.Energy.NormalizedCriticalInitialEnergy +OAI.Probability.FreeIsing.Energy.NormalizedInfiniteTimeEnergy +OAI.Probability.FreeIsing.Energy.NormalizedResponseEnergy +OAI.Probability.FreeIsing.Energy.NormalizedResponseLimit +OAI.Probability.FreeIsing.Energy.NormalizedResponseTime +OAI.Probability.FreeIsing.Energy.OptionResponseReindex +OAI.Probability.FreeIsing.Energy.OrderedAttenuation +OAI.Probability.FreeIsing.Energy.ProgressiveIsingCovariance +OAI.Probability.FreeIsing.Energy.RelabeledComponentAttenuation +OAI.Probability.FreeIsing.Energy.ResponseSourceInvariance +OAI.Probability.FreeIsing.Energy.RowEnergyConvergence +OAI.Probability.FreeIsing.Energy.RowEnergyL1 +OAI.Probability.FreeIsing.Energy.SelectedCriticalFieldMoments +OAI.Probability.FreeIsing.Energy.ShiftedFieldVariance +OAI.Probability.FreeIsing.Energy.SubcriticalResponseComparison +OAI.Probability.FreeIsing.Energy.TiltedVariance +OAI.Probability.FreeIsing.Energy.TimeRowEnergyHasSum +OAI.Probability.FreeIsing.Energy.UniformResponseMoments +OAI.Probability.FreeIsing.Estimates.AEModification +OAI.Probability.FreeIsing.Estimates.AbsoluteContinuity +OAI.Probability.FreeIsing.Estimates.ArrayInnovationLaw +OAI.Probability.FreeIsing.Estimates.ArrayInnovationProjection +OAI.Probability.FreeIsing.Estimates.ArtanhTaylor +OAI.Probability.FreeIsing.Estimates.BalancedLatentMean +OAI.Probability.FreeIsing.Estimates.BoundedAverageConcentration +OAI.Probability.FreeIsing.Estimates.BoundedInnovationDrift +OAI.Probability.FreeIsing.Estimates.CenteredLocalDensity +OAI.Probability.FreeIsing.Estimates.CenteredWordAction +OAI.Probability.FreeIsing.Estimates.ChainMarginals +OAI.Probability.FreeIsing.Estimates.CharacteristicRecurrence +OAI.Probability.FreeIsing.Estimates.ClippedArtanhWeight +OAI.Probability.FreeIsing.Estimates.CoefficientTerminalCompletion +OAI.Probability.FreeIsing.Estimates.ColorAutomorphisms +OAI.Probability.FreeIsing.Estimates.CompensatedSquareLimit +OAI.Probability.FreeIsing.Estimates.ComponentFieldConsequences +OAI.Probability.FreeIsing.Estimates.ComponentFieldRecursion +OAI.Probability.FreeIsing.Estimates.ComponentFusionRecurrence +OAI.Probability.FreeIsing.Estimates.ComponentGibbsLimit +OAI.Probability.FreeIsing.Estimates.ComponentPairCount +OAI.Probability.FreeIsing.Estimates.ConstructedArtanhFormula +OAI.Probability.FreeIsing.Estimates.ContinuousCoefficientModulus +OAI.Probability.FreeIsing.Estimates.ContinuousHorizonGluing +OAI.Probability.FreeIsing.Estimates.ContinuousModification +OAI.Probability.FreeIsing.Estimates.ContinuousOptionalStopping +OAI.Probability.FreeIsing.Estimates.CountableProjective +OAI.Probability.FreeIsing.Estimates.CoupledCriticalComparison +OAI.Probability.FreeIsing.Estimates.CoupledSmallLogLoss +OAI.Probability.FreeIsing.Estimates.CylinderAutomorphism +OAI.Probability.FreeIsing.Estimates.CylinderBasics +OAI.Probability.FreeIsing.Estimates.DependentInfinitePiPair +OAI.Probability.FreeIsing.Estimates.DependentWeight +OAI.Probability.FreeIsing.Estimates.DiscrepancyDensityModification +OAI.Probability.FreeIsing.Estimates.DyadicContinuity +OAI.Probability.FreeIsing.Estimates.DyadicIncrementControl +OAI.Probability.FreeIsing.Estimates.EndpointScale +OAI.Probability.FreeIsing.Estimates.EndpointSums +OAI.Probability.FreeIsing.Estimates.EndpointTimeScale +OAI.Probability.FreeIsing.Estimates.ExponentialTaylor +OAI.Probability.FreeIsing.Estimates.FairSpin +OAI.Probability.FreeIsing.Estimates.FilteredFutureIndependence +OAI.Probability.FreeIsing.Estimates.FiniteBondMask +OAI.Probability.FreeIsing.Estimates.FiniteCavity +OAI.Probability.FreeIsing.Estimates.FiniteCavityComponents +OAI.Probability.FreeIsing.Estimates.FiniteChain +OAI.Probability.FreeIsing.Estimates.FiniteComponentFields +OAI.Probability.FreeIsing.Estimates.FiniteComponentGeometry +OAI.Probability.FreeIsing.Estimates.FiniteCoordinateApproximation +OAI.Probability.FreeIsing.Estimates.FiniteCoordinateRepresentation +OAI.Probability.FreeIsing.Estimates.FiniteGibbsField +OAI.Probability.FreeIsing.Estimates.FiniteIsingCompensatedSquare +OAI.Probability.FreeIsing.Estimates.FiniteIsingInnovation +OAI.Probability.FreeIsing.Estimates.FiniteIsingSplit +OAI.Probability.FreeIsing.Estimates.FiniteIsingZeroField +OAI.Probability.FreeIsing.Estimates.FiniteMarginals +OAI.Probability.FreeIsing.Estimates.FiniteMarkerRank +OAI.Probability.FreeIsing.Estimates.FiniteSpinCoupling +OAI.Probability.FreeIsing.Estimates.FiniteWeightNormalization +OAI.Probability.FreeIsing.Estimates.FreeIsingMeasure +OAI.Probability.FreeIsing.Estimates.FreeLawStationarity +OAI.Probability.FreeIsing.Estimates.FreeLawSymmetry +OAI.Probability.FreeIsing.Estimates.FreeLawUnique +OAI.Probability.FreeIsing.Estimates.IndependentEnlargement +OAI.Probability.FreeIsing.Estimates.IndependentLabelSampler +OAI.Probability.FreeIsing.Estimates.IndependentOwnFamily +OAI.Probability.FreeIsing.Estimates.InfiniteBlockIndependence +OAI.Probability.FreeIsing.Estimates.InfiniteComponentCavity +OAI.Probability.FreeIsing.Estimates.InfinitePiPair +OAI.Probability.FreeIsing.Estimates.InhomogeneousSpinChain +OAI.Probability.FreeIsing.Estimates.InnovationCharacteristic +OAI.Probability.FreeIsing.Estimates.IntegrableTimePrimitive +OAI.Probability.FreeIsing.Estimates.IntervalSumIntegrable +OAI.Probability.FreeIsing.Estimates.KernelCompatibility +OAI.Probability.FreeIsing.Estimates.LabelDecomposition +OAI.Probability.FreeIsing.Estimates.LatentFamilyIndependence +OAI.Probability.FreeIsing.Estimates.LatentProductIndependence +OAI.Probability.FreeIsing.Estimates.LawUniqueness +OAI.Probability.FreeIsing.Estimates.LeafDeletion +OAI.Probability.FreeIsing.Estimates.LeafWeights +OAI.Probability.FreeIsing.Estimates.LiftGram +OAI.Probability.FreeIsing.Estimates.LinearEstimator +OAI.Probability.FreeIsing.Estimates.LocalColorAutomorphisms +OAI.Probability.FreeIsing.Estimates.LocalCorrelation +OAI.Probability.FreeIsing.Estimates.LocalizedArtanhFormula +OAI.Probability.FreeIsing.Estimates.LogInterpolation +OAI.Probability.FreeIsing.Estimates.MeanSquareContinuity +OAI.Probability.FreeIsing.Estimates.MeasurableConnectivity +OAI.Probability.FreeIsing.Estimates.MessageFunction +OAI.Probability.FreeIsing.Estimates.NNRealArtanhFormula +OAI.Probability.FreeIsing.Estimates.NonbacktrackingAssembly +OAI.Probability.FreeIsing.Estimates.NonbacktrackingComplement +OAI.Probability.FreeIsing.Estimates.NonbacktrackingDecay +OAI.Probability.FreeIsing.Estimates.NonbacktrackingLiftBound +OAI.Probability.FreeIsing.Estimates.NonbacktrackingOperator +OAI.Probability.FreeIsing.Estimates.NonnegativeSeriesL1 +OAI.Probability.FreeIsing.Estimates.NormalizedCriticalRowConvergence +OAI.Probability.FreeIsing.Estimates.NormalizedPositiveWindowRow +OAI.Probability.FreeIsing.Estimates.NormalizedSubcriticalRowConvergence +OAI.Probability.FreeIsing.Estimates.NormalizedThresholdRowConvergence +OAI.Probability.FreeIsing.Estimates.ObservableDisintegration +OAI.Probability.FreeIsing.Estimates.Osgood +OAI.Probability.FreeIsing.Estimates.OsgoodIntegration +OAI.Probability.FreeIsing.Estimates.PairCorrelation +OAI.Probability.FreeIsing.Estimates.PairedFiniteField +OAI.Probability.FreeIsing.Estimates.PastCompatibility +OAI.Probability.FreeIsing.Estimates.ProgressiveArrayInnovation +OAI.Probability.FreeIsing.Estimates.ProgressivePrimitive +OAI.Probability.FreeIsing.Estimates.ProgressivePrimitiveFubini +OAI.Probability.FreeIsing.Estimates.ProgressiveTimePrimitive +OAI.Probability.FreeIsing.Estimates.ProgressiveVersionPushforward +OAI.Probability.FreeIsing.Estimates.ProjectiveExtension +OAI.Probability.FreeIsing.Estimates.RadialRepresentation +OAI.Probability.FreeIsing.Estimates.RadialSummability +OAI.Probability.FreeIsing.Estimates.RadialWalk +OAI.Probability.FreeIsing.Estimates.RandomIndexSampling +OAI.Probability.FreeIsing.Estimates.RelabelMeasure +OAI.Probability.FreeIsing.Estimates.RoundedStoppingTimes +OAI.Probability.FreeIsing.Estimates.SelectedComponentFusion +OAI.Probability.FreeIsing.Estimates.SeparatedLocalSupports +OAI.Probability.FreeIsing.Estimates.SharedInnovationBounds +OAI.Probability.FreeIsing.Estimates.SupercriticalProfile +OAI.Probability.FreeIsing.Estimates.TerminalSufficiency +OAI.Probability.FreeIsing.Estimates.ThresholdArithmetic +OAI.Probability.FreeIsing.Estimates.TwoSeparatorRegression +OAI.Probability.FreeIsing.Estimates.UniformSampler +OAI.Probability.FreeIsing.Estimates.UniformTwist +OAI.Probability.FreeIsing.Estimates.WeightedOrbitAverage +OAI.Probability.FreeIsing.Estimates.WeightedPrimitiveApproximation +OAI.Probability.FreeIsing.Factors.ContinuousRecovery +OAI.Probability.FreeIsing.Factors.CoordinateNaturality +OAI.Probability.FreeIsing.Factors.DiagonalRecovery +OAI.Probability.FreeIsing.Factors.InfiniteCavityNaturality +OAI.Probability.FreeIsing.Factors.InnovationFactorRecovery +OAI.Probability.FreeIsing.Factors.Necessity +OAI.Probability.FreeIsing.Factors.Observable +OAI.Probability.FreeIsing.Factors.ObservableFactorRecovery +OAI.Probability.FreeIsing.Factors.ObservableWord +OAI.Probability.FreeIsing.Factors.Product +OAI.Probability.FreeIsing.Factors.RecoveryEquivariance +OAI.Probability.FreeIsing.Factors.SubcriticalFactor +OAI.Probability.FreeIsing.Factors.Transfer +OAI.Probability.FreeIsing.Factors.Transport +OAI.Probability.FreeIsing.Factors.ZeroFactor +OAI.Probability.FreeIsing.Gaussian.ArrayCharacterization +OAI.Probability.FreeIsing.Gaussian.Attenuation +OAI.Probability.FreeIsing.Gaussian.BernoulliCopyDifference +OAI.Probability.FreeIsing.Gaussian.BernoulliSpectral +OAI.Probability.FreeIsing.Gaussian.BinaryFusion +OAI.Probability.FreeIsing.Gaussian.BinaryFusionInformation +OAI.Probability.FreeIsing.Gaussian.BinaryFusionJointLaw +OAI.Probability.FreeIsing.Gaussian.BinaryFusionMixture +OAI.Probability.FreeIsing.Gaussian.BinaryFusionPosterior +OAI.Probability.FreeIsing.Gaussian.BinaryPosteriorResponseBound +OAI.Probability.FreeIsing.Gaussian.BinaryRegression +OAI.Probability.FreeIsing.Gaussian.BinarySignalDensity +OAI.Probability.FreeIsing.Gaussian.BinarySignalFusion +OAI.Probability.FreeIsing.Gaussian.ComponentSignalAttenuation +OAI.Probability.FreeIsing.Gaussian.ConditionalNoise +OAI.Probability.FreeIsing.Gaussian.ContinuousNoiseSplit +OAI.Probability.FreeIsing.Gaussian.CutChannels +OAI.Probability.FreeIsing.Gaussian.FiniteFieldGaussianEnergy +OAI.Probability.FreeIsing.Gaussian.FiniteGaussianPlanted +OAI.Probability.FreeIsing.Gaussian.FiniteGaussianPosterior +OAI.Probability.FreeIsing.Gaussian.FiniteIsingGaussianEnergy +OAI.Probability.FreeIsing.Gaussian.FiniteIsingGaussianTesting +OAI.Probability.FreeIsing.Gaussian.FiniteSignalFieldRecursion +OAI.Probability.FreeIsing.Gaussian.FiniteSignalInformation +OAI.Probability.FreeIsing.Gaussian.FreeLawNoise +OAI.Probability.FreeIsing.Gaussian.GlobalFreeLawNoise +OAI.Probability.FreeIsing.Gaussian.IncrementLikelihood +OAI.Probability.FreeIsing.Gaussian.IntegrationByParts +OAI.Probability.FreeIsing.Gaussian.InwardCutConcentration +OAI.Probability.FreeIsing.Gaussian.InwardGaussianCutChannels +OAI.Probability.FreeIsing.Gaussian.InwardGaussianCutMean +OAI.Probability.FreeIsing.Gaussian.InwardProducts +OAI.Probability.FreeIsing.Gaussian.Likelihood +OAI.Probability.FreeIsing.Gaussian.LinearSignalTilt +OAI.Probability.FreeIsing.Gaussian.MarkovSideSignalLoss +OAI.Probability.FreeIsing.Gaussian.Moments +OAI.Probability.FreeIsing.Gaussian.NoiseAverageL2 +OAI.Probability.FreeIsing.Gaussian.NoiseSlope +OAI.Probability.FreeIsing.Gaussian.NoiseTransfer +OAI.Probability.FreeIsing.Gaussian.Observation +OAI.Probability.FreeIsing.Gaussian.ObservationDerivative +OAI.Probability.FreeIsing.Gaussian.PathAttenuation +OAI.Probability.FreeIsing.Gaussian.PiIntegrationByParts +OAI.Probability.FreeIsing.Gaussian.PosteriorBareResponse +OAI.Probability.FreeIsing.Gaussian.RerootedFreeLawNoise +OAI.Probability.FreeIsing.Gaussian.SideSignalLoss +OAI.Probability.FreeIsing.Gaussian.SiteInformation +OAI.Probability.FreeIsing.Gaussian.SmallBall +OAI.Probability.FreeIsing.Gaussian.StatisticSideSignalLoss +OAI.Probability.FreeIsing.Gaussian.TreeCovariance +OAI.Probability.FreeIsing.Gaussian.TreeEnergy +OAI.Probability.FreeIsing.Gaussian.TreeResponse +OAI.Probability.FreeIsing.Gaussian.TreeResponseEnergy +OAI.Probability.FreeIsing.Gaussian.TreeResponseMixture +OAI.Probability.FreeIsing.Gaussian.TreeResponseNaturality +OAI.Probability.FreeIsing.Gaussian.TreeResponseObservedPosterior +OAI.Probability.FreeIsing.Gaussian.TreeResponsePlanted +OAI.Probability.FreeIsing.Gaussian.TreeResponsePosterior +OAI.Probability.FreeIsing.Gaussian.TreeResponseRootEnergy +OAI.Probability.FreeIsing.Gaussian.TreeResponseRootPosterior +OAI.Probability.FreeIsing.Gaussian.TreeResponseSource +OAI.Probability.FreeIsing.Gaussian.TreeResponseVarianceComparison +OAI.Probability.FreeIsing.Gaussian.TreeResponseVarianceMixture +OAI.Probability.FreeIsing.Gaussian.VarianceLower +OAI.Probability.FreeIsing.Gibbs.CompensatedSquare +OAI.Probability.FreeIsing.Gibbs.CovarianceCompensator +OAI.Probability.FreeIsing.Gibbs.CovarianceCompensatorPaths +OAI.Probability.FreeIsing.Gibbs.CovarianceCriticalEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceCriticalRowConvergence +OAI.Probability.FreeIsing.Gibbs.CovarianceEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceIntrinsicEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceL2Limit +OAI.Probability.FreeIsing.Gibbs.CovarianceNativeRowCauchy +OAI.Probability.FreeIsing.Gibbs.CovarianceRowCauchy +OAI.Probability.FreeIsing.Gibbs.CovarianceStrictConvergence +OAI.Probability.FreeIsing.Gibbs.CovarianceStrictEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceUniformEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceWindowEnergy +OAI.Probability.FreeIsing.Gibbs.CovarianceZero +OAI.Probability.FreeIsing.Gibbs.Leaf +OAI.Probability.FreeIsing.Gibbs.LeafMessage +OAI.Probability.FreeIsing.Gibbs.PosteriorSymmetry +OAI.Probability.FreeIsing.Gibbs.SpinMeanL2Limit +OAI.Probability.FreeIsing.Gibbs.Weights +OAI.Probability.FreeIsing.Ising.ActualVarianceAnalysis +OAI.Probability.FreeIsing.Ising.ArtanhConstruction +OAI.Probability.FreeIsing.Ising.CanonicalArtanh +OAI.Probability.FreeIsing.Ising.CanonicalArtanhDenseIdentification +OAI.Probability.FreeIsing.Ising.CanonicalArtanhIdentification +OAI.Probability.FreeIsing.Ising.CanonicalClippedWeight +OAI.Probability.FreeIsing.Ising.CanonicalContinuousFields +OAI.Probability.FreeIsing.Ising.CanonicalCoordinateIdentification +OAI.Probability.FreeIsing.Ising.CanonicalCovarianceIntegrals +OAI.Probability.FreeIsing.Ising.CanonicalCovariancePullback +OAI.Probability.FreeIsing.Ising.CanonicalDriftRegularity +OAI.Probability.FreeIsing.Ising.CanonicalFieldNaturality +OAI.Probability.FreeIsing.Ising.CanonicalIntegralRepresentation +OAI.Probability.FreeIsing.Ising.CanonicalLocalSquare +OAI.Probability.FreeIsing.Ising.CanonicalMartingales +OAI.Probability.FreeIsing.Ising.CanonicalNormalizedField +OAI.Probability.FreeIsing.Ising.CanonicalPosteriorStops +OAI.Probability.FreeIsing.Ising.CanonicalResponseIntegrals +OAI.Probability.FreeIsing.Ising.CavityTailTransport +OAI.Probability.FreeIsing.Ising.CommonStopBounds +OAI.Probability.FreeIsing.Ising.ConditionalCopyBounds +OAI.Probability.FreeIsing.Ising.ContinuousCopyCoefficients +OAI.Probability.FreeIsing.Ising.ContinuousCopyDensity +OAI.Probability.FreeIsing.Ising.ContinuousCovarianceIntegral +OAI.Probability.FreeIsing.Ising.ContinuousPosterior +OAI.Probability.FreeIsing.Ising.ContinuousResponseAlgebra +OAI.Probability.FreeIsing.Ising.ContinuousResponseEnergy +OAI.Probability.FreeIsing.Ising.ContinuousRootResponse +OAI.Probability.FreeIsing.Ising.CoordinateCompletion +OAI.Probability.FreeIsing.Ising.CoordinateIntegrals +OAI.Probability.FreeIsing.Ising.CopiedDriftDecomposition +OAI.Probability.FreeIsing.Ising.CopyBrownian +OAI.Probability.FreeIsing.Ising.CopyCanonicalStops +OAI.Probability.FreeIsing.Ising.CopyCavityBounds +OAI.Probability.FreeIsing.Ising.CopyCriticalSpatialBounds +OAI.Probability.FreeIsing.Ising.CopyCriticalSpatialEstimates +OAI.Probability.FreeIsing.Ising.CopyEdgeCorrelations +OAI.Probability.FreeIsing.Ising.CopyEdgeVariance +OAI.Probability.FreeIsing.Ising.CopyEnergyIntegrability +OAI.Probability.FreeIsing.Ising.CopyFixedPathBound +OAI.Probability.FreeIsing.Ising.CopyGeodesicCorrelations +OAI.Probability.FreeIsing.Ising.CopyInformationBound +OAI.Probability.FreeIsing.Ising.CopyIntegralLimits +OAI.Probability.FreeIsing.Ising.CopyLinearLongBound +OAI.Probability.FreeIsing.Ising.CopyMartingaleImmersion +OAI.Probability.FreeIsing.Ising.CopyNoiseLongBound +OAI.Probability.FreeIsing.Ising.CopyObservables +OAI.Probability.FreeIsing.Ising.CopyOrbitAverage +OAI.Probability.FreeIsing.Ising.CopyPathBounds +OAI.Probability.FreeIsing.Ising.CopyPathVariance +OAI.Probability.FreeIsing.Ising.CopyPathVector +OAI.Probability.FreeIsing.Ising.CopyPathWeightNaturality +OAI.Probability.FreeIsing.Ising.CopyProductDrift +OAI.Probability.FreeIsing.Ising.CopyProductPathBound +OAI.Probability.FreeIsing.Ising.CopyProductVariance +OAI.Probability.FreeIsing.Ising.CopyResponseIdentification +OAI.Probability.FreeIsing.Ising.CopyResponseRowPaths +OAI.Probability.FreeIsing.Ising.CopyResponseRowSummability +OAI.Probability.FreeIsing.Ising.CopyShellEnergies +OAI.Probability.FreeIsing.Ising.CopySmallLogLoss +OAI.Probability.FreeIsing.Ising.CopySmallTime +OAI.Probability.FreeIsing.Ising.CopySpatialEndpoints +OAI.Probability.FreeIsing.Ising.CopySpectral +OAI.Probability.FreeIsing.Ising.CopySquareDensity +OAI.Probability.FreeIsing.Ising.CopyStationarity +OAI.Probability.FreeIsing.Ising.CopyStoppedEnergy +OAI.Probability.FreeIsing.Ising.CopyStrictComparison +OAI.Probability.FreeIsing.Ising.CopyVarianceContinuity +OAI.Probability.FreeIsing.Ising.CopyVarianceEquation +OAI.Probability.FreeIsing.Ising.CopyVarianceRegularity +OAI.Probability.FreeIsing.Ising.CopyWeightedCut +OAI.Probability.FreeIsing.Ising.CopyWeightedPathCut +OAI.Probability.FreeIsing.Ising.CovarianceTimeL2 +OAI.Probability.FreeIsing.Ising.CovarianceTotalEnergy +OAI.Probability.FreeIsing.Ising.CriticalCopyEndgame +OAI.Probability.FreeIsing.Ising.CriticalSmallLogLoss +OAI.Probability.FreeIsing.Ising.CriticalSpatialRecovery +OAI.Probability.FreeIsing.Ising.FiniteCovarianceEnergy +OAI.Probability.FreeIsing.Ising.GaussianPosterior +OAI.Probability.FreeIsing.Ising.Innovation +OAI.Probability.FreeIsing.Ising.InnovationIndependence +OAI.Probability.FreeIsing.Ising.InnovationLaw +OAI.Probability.FreeIsing.Ising.JoinedResponseIntegrals +OAI.Probability.FreeIsing.Ising.LocalizedArtanh +OAI.Probability.FreeIsing.Ising.LogGaussianTail +OAI.Probability.FreeIsing.Ising.LogWeightedOrbitCut +OAI.Probability.FreeIsing.Ising.MixedFiltering +OAI.Probability.FreeIsing.Ising.NoiseTwoTails +OAI.Probability.FreeIsing.Ising.ObservationComparison +OAI.Probability.FreeIsing.Ising.ObservationFactor +OAI.Probability.FreeIsing.Ising.ObservationIndependence +OAI.Probability.FreeIsing.Ising.ObservationInnovation +OAI.Probability.FreeIsing.Ising.ObservationLaw +OAI.Probability.FreeIsing.Ising.ObservationPosteriorMartingale +OAI.Probability.FreeIsing.Ising.ObservationPosteriorTransport +OAI.Probability.FreeIsing.Ising.ObservationRecovery +OAI.Probability.FreeIsing.Ising.ObservationResponseEnergy +OAI.Probability.FreeIsing.Ising.OrientedGaussianTail +OAI.Probability.FreeIsing.Ising.OrientedNoiseSplit +OAI.Probability.FreeIsing.Ising.OrientedPath +OAI.Probability.FreeIsing.Ising.OrientedPathWeights +OAI.Probability.FreeIsing.Ising.OrientedPrefixWeights +OAI.Probability.FreeIsing.Ising.OrientedStemTail +OAI.Probability.FreeIsing.Ising.ParameterRange +OAI.Probability.FreeIsing.Ising.PathReversalTransport +OAI.Probability.FreeIsing.Ising.PosteriorEnergyRegularity +OAI.Probability.FreeIsing.Ising.PosteriorIntegralRepresentation +OAI.Probability.FreeIsing.Ising.PosteriorL2Continuity +OAI.Probability.FreeIsing.Ising.PosteriorRightContinuation +OAI.Probability.FreeIsing.Ising.RootAttenuation +OAI.Probability.FreeIsing.Ising.RootDoubleExponential +OAI.Probability.FreeIsing.Ising.RootGaussianCut +OAI.Probability.FreeIsing.Ising.RootWeightedCut +OAI.Probability.FreeIsing.Ising.SharpVarianceRecovery +OAI.Probability.FreeIsing.Ising.StemRerootAverage +OAI.Probability.FreeIsing.Ising.StoppedDifferenceBounds +OAI.Probability.FreeIsing.Ising.StoppedSquareAssembly +OAI.Probability.FreeIsing.Ising.StrictFactorRecovery +OAI.Probability.FreeIsing.Ising.WalkObstruction +OAI.Probability.FreeIsing.Main +OAI.Probability.FreeIsing.Martingales.ArtanhMartingaleFormula +OAI.Probability.FreeIsing.Martingales.BoundedMartingaleDriftEnergy +OAI.Probability.FreeIsing.Martingales.BoundedMartingaleVariation +OAI.Probability.FreeIsing.Martingales.BracketIsometry +OAI.Probability.FreeIsing.Martingales.CharacteristicStep +OAI.Probability.FreeIsing.Martingales.CoefficientApproximation +OAI.Probability.FreeIsing.Martingales.ContinuousL2Limit +OAI.Probability.FreeIsing.Martingales.ContinuousLimit +OAI.Probability.FreeIsing.Martingales.ContinuousMartingaleVariation +OAI.Probability.FreeIsing.Martingales.ContinuousMaximal +OAI.Probability.FreeIsing.Martingales.ContinuousPosteriorMartingale +OAI.Probability.FreeIsing.Martingales.ContinuousSelection +OAI.Probability.FreeIsing.Martingales.ContinuousSubsequence +OAI.Probability.FreeIsing.Martingales.DominatedMartingaleRightContinuation +OAI.Probability.FreeIsing.Martingales.DriftEnergy +OAI.Probability.FreeIsing.Martingales.GaussianCriterion +OAI.Probability.FreeIsing.Martingales.InnovationMartingale +OAI.Probability.FreeIsing.Martingales.IntegerIdentification +OAI.Probability.FreeIsing.Martingales.IntegralStability +OAI.Probability.FreeIsing.Martingales.L2Closure +OAI.Probability.FreeIsing.Martingales.L2MartingaleRightContinuation +OAI.Probability.FreeIsing.Martingales.PredictableL2Completion +OAI.Probability.FreeIsing.Martingales.PredictableMeshApproximation +OAI.Probability.FreeIsing.Martingales.PredictableVersion +OAI.Probability.FreeIsing.Martingales.Pushforward +OAI.Probability.FreeIsing.Martingales.QuadraticVariation +OAI.Probability.FreeIsing.Martingales.RandomEvaluation +OAI.Probability.FreeIsing.Martingales.RightContinuation +OAI.Probability.FreeIsing.Martingales.SpatialCompensator +OAI.Probability.FreeIsing.Martingales.SpatialLimit +OAI.Probability.FreeIsing.Martingales.SpatialPredictableL2 +OAI.Probability.FreeIsing.Martingales.SpatialRandomEvaluation +OAI.Probability.FreeIsing.Martingales.SquareMaximal +OAI.Probability.FreeIsing.Martingales.StoppedDiscrepancyEnergy +OAI.Probability.FreeIsing.Martingales.StoppedEnergyRiemann +OAI.Probability.FreeIsing.Martingales.StoppedIdentityExhaustion +OAI.Probability.FreeIsing.Martingales.StoppedMartingaleL2 +OAI.Probability.FreeIsing.Martingales.StoppedProcessExhaustion +OAI.Probability.FreeIsing.Martingales.StoppedProcessTransport +OAI.Probability.FreeIsing.Martingales.StoppedRowNormalization +OAI.Probability.FreeIsing.Martingales.StoppedSpatialAssociativity +OAI.Probability.FreeIsing.Martingales.StoppedTimePrimitive +OAI.Probability.FreeIsing.Martingales.StrongMaximal +OAI.Probability.FreeIsing.Martingales.TaylorRemainder +OAI.Probability.FreeIsing.Martingales.TransformL2 +OAI.Probability.FreeIsing.Martingales.UniformIntegral +OAI.Probability.FreeIsing.Model +OAI.Probability.FreeIsing.Posterior.ArrayPosteriorCovarianceStationarity +OAI.Probability.FreeIsing.Posterior.ArrayPosteriorStationarity +OAI.Probability.FreeIsing.Posterior.BranchObservationRegression +OAI.Probability.FreeIsing.Posterior.ChildObservationRegression +OAI.Probability.FreeIsing.Posterior.CompensatorStopping +OAI.Probability.FreeIsing.Posterior.ComponentObservationDecomposition +OAI.Probability.FreeIsing.Posterior.ComponentObservationIndependence +OAI.Probability.FreeIsing.Posterior.ComponentObservationRegression +OAI.Probability.FreeIsing.Posterior.ComponentPosteriorStationarity +OAI.Probability.FreeIsing.Posterior.ComponentPosteriorTilt +OAI.Probability.FreeIsing.Posterior.ConePosteriorRegression +OAI.Probability.FreeIsing.Posterior.ContinuousObservationHistory +OAI.Probability.FreeIsing.Posterior.ContinuousPosteriorInterior +OAI.Probability.FreeIsing.Posterior.ContinuousPosteriorNaturality +OAI.Probability.FreeIsing.Posterior.ContinuousPosteriorStopping +OAI.Probability.FreeIsing.Posterior.CopyBounds +OAI.Probability.FreeIsing.Posterior.DerivativeBounds +OAI.Probability.FreeIsing.Posterior.FieldCalculus +OAI.Probability.FreeIsing.Posterior.FieldL2Limit +OAI.Probability.FreeIsing.Posterior.FieldMoments +OAI.Probability.FreeIsing.Posterior.Fields +OAI.Probability.FreeIsing.Posterior.FilteringArrayCrossLimit +OAI.Probability.FreeIsing.Posterior.FilteringCrossEnergy +OAI.Probability.FreeIsing.Posterior.FilteringCrossLimit +OAI.Probability.FreeIsing.Posterior.FilteringRepresentationClosure +OAI.Probability.FreeIsing.Posterior.FilteringSimpleCrossEnergy +OAI.Probability.FreeIsing.Posterior.FiniteIsingFilteringRepresentation +OAI.Probability.FreeIsing.Posterior.FinitePosterior +OAI.Probability.FreeIsing.Posterior.FinitePosteriorVarianceInverse +OAI.Probability.FreeIsing.Posterior.FusionSup +OAI.Probability.FreeIsing.Posterior.GaussianEnergy +OAI.Probability.FreeIsing.Posterior.GaussianEnergyIntegral +OAI.Probability.FreeIsing.Posterior.GaussianGradient +OAI.Probability.FreeIsing.Posterior.GaussianTesting +OAI.Probability.FreeIsing.Posterior.GaussianTimeDerivative +OAI.Probability.FreeIsing.Posterior.InfinitePosteriorField +OAI.Probability.FreeIsing.Posterior.InteriorLocalization +OAI.Probability.FreeIsing.Posterior.LatentObservationIndependence +OAI.Probability.FreeIsing.Posterior.Limit +OAI.Probability.FreeIsing.Posterior.LipschitzObservationDerivative +OAI.Probability.FreeIsing.Posterior.MixedFilteringCrossLimit +OAI.Probability.FreeIsing.Posterior.NormalizedObservationRowConvergence +OAI.Probability.FreeIsing.Posterior.NormalizedPosteriorLimit +OAI.Probability.FreeIsing.Posterior.NormalizedPosteriorRowConvergence +OAI.Probability.FreeIsing.Posterior.ObservationFactorRecovery +OAI.Probability.FreeIsing.Posterior.ObservationLawSpectral +OAI.Probability.FreeIsing.Posterior.ObservationMoments +OAI.Probability.FreeIsing.Posterior.ObservationStepApproximation +OAI.Probability.FreeIsing.Posterior.PathPosteriorResponse +OAI.Probability.FreeIsing.Posterior.PlantedArrayCrossEnergy +OAI.Probability.FreeIsing.Posterior.PlantedBridge +OAI.Probability.FreeIsing.Posterior.PlantedBridgeInfinite +OAI.Probability.FreeIsing.Posterior.PlantedBridgeVector +OAI.Probability.FreeIsing.Posterior.PlantedEdgeRegression +OAI.Probability.FreeIsing.Posterior.PlantedStationarity +OAI.Probability.FreeIsing.Posterior.PlantedSufficiency +OAI.Probability.FreeIsing.Posterior.PlantedSufficiencyVector +OAI.Probability.FreeIsing.Posterior.PlantedSymmetry +OAI.Probability.FreeIsing.Posterior.ProgressiveIsingPosterior +OAI.Probability.FreeIsing.Posterior.ProjectedObservationRecovery +OAI.Probability.FreeIsing.Posterior.ResponseCapRate +OAI.Probability.FreeIsing.Posterior.ResponseTruncation +OAI.Probability.FreeIsing.Posterior.SelectedPosteriorChannels +OAI.Probability.FreeIsing.Posterior.SelectedPosteriorField +OAI.Probability.FreeIsing.Posterior.SelectedPosteriorLimit +OAI.Probability.FreeIsing.Posterior.SelectedPosteriorStationarity +OAI.Probability.FreeIsing.Posterior.SelectedPosteriorSymmetry +OAI.Probability.FreeIsing.Posterior.Smooth +OAI.Probability.FreeIsing.Posterior.SqrtObservationDerivative +OAI.Probability.FreeIsing.Posterior.Stationarity +OAI.Probability.FreeIsing.Posterior.StatisticTilt +OAI.Probability.FreeIsing.Posterior.StoppingTimes +OAI.Probability.FreeIsing.Posterior.StrictPosteriorIncrements +OAI.Probability.FreeIsing.Posterior.SubsetPosteriorSymmetry +OAI.Probability.FreeIsing.Posterior.Symmetry +OAI.Probability.FreeIsing.Posterior.TimeL2Continuity +OAI.Probability.FreeIsing.Posterior.UniformTimeApproximation +OAI.Probability.FreeIsing.Posterior.VarianceInverse +OAI.Probability.FreeIsing.Posterior.VarianceInverseLimit +OAI.Probability.FreeIsing.Posterior.VarianceInverseTimeLimit +OAI.Probability.FreeIsing.Posterior.VarianceTimeIntegral +OAI.Probability.FreeIsing.Posterior.VarianceTruncation +OAI.Probability.FreeIsing.Spectral.ChebyshevRecurrence +OAI.Probability.FreeIsing.Spectral.ColoredKoopman +OAI.Probability.FreeIsing.Spectral.ContinuousL2Stopping +OAI.Probability.FreeIsing.Spectral.DifferenceKoopman +OAI.Probability.FreeIsing.Spectral.FreeLawSpectral +OAI.Probability.FreeIsing.Spectral.KoopmanInvolutions +OAI.Probability.FreeIsing.Spectral.L2CompensatedDensityStopping +OAI.Probability.FreeIsing.Spectral.L2CompensatedSquareStopping +OAI.Probability.FreeIsing.Spectral.LocalOrthogonality +OAI.Probability.FreeIsing.Spectral.NoisyLawSpectral +OAI.Probability.FreeIsing.Spectral.OrthogonalBlocks +OAI.Probability.FreeIsing.Spectral.OrthogonalRowIdentification +OAI.Probability.FreeIsing.Spectral.PowerObstruction +OAI.Probability.FreeIsing.Spectral.RadialPowerGrowth +OAI.Probability.FreeIsing.Spectral.RealChebyshevBound +OAI.Probability.FreeIsing.Spectral.SpectralClosure +OAI.Probability.FreeIsing.Spectral.SpectralTransfer +OAI.Probability.FreeIsing.Spectral.StablePowerTransport +OAI.Probability.FreeIsing.Spins.Chain +OAI.Probability.FreeIsing.Spins.Flip +OAI.Probability.FreeIsing.Spins.Kernel +OAI.Probability.FreeIsing.Spins.Moments +OAI.Probability.FreeIsing.Spins.ObservationFusion +OAI.Probability.FreeIsing.Spins.ObservationLaw +OAI.Probability.FreeIsing.Spins.PosteriorCertification +OAI.Probability.FreeIsing.Spins.PosteriorFusion +OAI.Probability.FreeIsing.Spins.PosteriorLaw +OAI.Probability.FreeIsing.Spins.PosteriorTilt +OAI.Probability.FreeIsing.Spins.ProductLaw +OAI.Probability.FreeIsing.Spins.Recovery +OAI.Probability.FreeIsing.Spins.Twist +OAI.Probability.FreeIsing.Stochastic.ActualCriticalBrownianFieldMoments +OAI.Probability.FreeIsing.Stochastic.BinaryFusionIntegral +OAI.Probability.FreeIsing.Stochastic.CompensatorVariation +OAI.Probability.FreeIsing.Stochastic.ContinuousCopyBrownian +OAI.Probability.FreeIsing.Stochastic.FiniteBrownianPlanted +OAI.Probability.FreeIsing.Stochastic.FiniteBrownianPosterior +OAI.Probability.FreeIsing.Stochastic.FiniteCoordinateFiltration +OAI.Probability.FreeIsing.Stochastic.FiniteFieldEntropyIntegral +OAI.Probability.FreeIsing.Stochastic.FiniteIsingBrownianEnergy +OAI.Probability.FreeIsing.Stochastic.FiniteIsingBrownianHistory +OAI.Probability.FreeIsing.Stochastic.FiniteIsingBrownianPosterior +OAI.Probability.FreeIsing.Stochastic.FiniteIsingFilteringIntegral +OAI.Probability.FreeIsing.Stochastic.FiniteLawIntegral +OAI.Probability.FreeIsing.Stochastic.FiniteObservationFiltrationLimit +OAI.Probability.FreeIsing.Stochastic.FinitePosteriorVarianceBrownian +OAI.Probability.FreeIsing.Stochastic.GrowingFiltrationMartingale +OAI.Probability.FreeIsing.Stochastic.IntegralAssociativityLimit +OAI.Probability.FreeIsing.Stochastic.NormalizedBrownianVarianceComparison +OAI.Probability.FreeIsing.Stochastic.PlantedBrownianLinearCombination +OAI.Probability.FreeIsing.Stochastic.PlantedStoppedBrownianSquare +OAI.Probability.FreeIsing.Stochastic.RandomRiemannCompensator +OAI.Probability.FreeIsing.Stochastic.RandomStoppedBrownianIntegral +OAI.Probability.FreeIsing.Stochastic.RandomStoppedSimpleIntegral +OAI.Probability.FreeIsing.Stochastic.SelectedBrownianFieldLaw +OAI.Probability.FreeIsing.Stochastic.SelectedBrownianJointLaw +OAI.Probability.FreeIsing.Stochastic.SelectedBrownianSufficiency +OAI.Probability.FreeIsing.Stochastic.SelectedCompensator +OAI.Probability.FreeIsing.Stochastic.SimpleIntegralAssociativity +OAI.Probability.FreeIsing.Stochastic.SimpleIntegralIsometry +OAI.Probability.FreeIsing.Stochastic.StoppedBrownianArraySquare +OAI.Probability.FreeIsing.Stochastic.StoppedBrownianCross +OAI.Probability.FreeIsing.Stochastic.StoppedBrownianIntegral +OAI.Probability.FreeIsing.Stochastic.StoppedBrownianSquare +OAI.Probability.FreeIsing.Stochastic.StoppedIntegralAssociativity +OAI.Probability.FreeIsing.Stochastic.StoppedIntegralLocality +OAI.Probability.FreeIsing.Stochastic.StoppedL2Compensator +OAI.Probability.FreeIsing.Stochastic.StoppedSimpleIntegral +OAI.Probability.FreeIsing.Stochastic.StrictBrownianResponseEnergy +OAI.Probability.FreeIsing.Stochastic.WienerSampler +OAI.Probability.FreeIsing.Support +OAI.Probability.FreeIsing.Trees.ActualCutWeightedAverage +OAI.Probability.FreeIsing.Trees.AutDistance +OAI.Probability.FreeIsing.Trees.BranchFlipGeometry +OAI.Probability.FreeIsing.Trees.BranchingExtinction +OAI.Probability.FreeIsing.Trees.BranchingSurvivalLaw +OAI.Probability.FreeIsing.Trees.BroadcastBlockIndependence +OAI.Probability.FreeIsing.Trees.BroadcastBranchFamily +OAI.Probability.FreeIsing.Trees.BroadcastBranchLabels +OAI.Probability.FreeIsing.Trees.BroadcastConeLocality +OAI.Probability.FreeIsing.Trees.BroadcastConeMarkov +OAI.Probability.FreeIsing.Trees.BroadcastJointLaw +OAI.Probability.FreeIsing.Trees.BroadcastLocality +OAI.Probability.FreeIsing.Trees.BroadcastOutsideCone +OAI.Probability.FreeIsing.Trees.CanonicalPathResponse +OAI.Probability.FreeIsing.Trees.Cardinality +OAI.Probability.FreeIsing.Trees.ClusterColorMarginal +OAI.Probability.FreeIsing.Trees.ClusterComponentCount +OAI.Probability.FreeIsing.Trees.ClusterFactorAssembly +OAI.Probability.FreeIsing.Trees.ClusterFactorEnvironment +OAI.Probability.FreeIsing.Trees.ClusterFactorMap +OAI.Probability.FreeIsing.Trees.ClusterInputSampler +OAI.Probability.FreeIsing.Trees.ClusterRestriction +OAI.Probability.FreeIsing.Trees.CodedPercolation +OAI.Probability.FreeIsing.Trees.ColoredEdgeDecay +OAI.Probability.FreeIsing.Trees.ColoredEdgeLifts +OAI.Probability.FreeIsing.Trees.ColoredPathAverage +OAI.Probability.FreeIsing.Trees.ColoredPathCoefficients +OAI.Probability.FreeIsing.Trees.ColoredPathCount +OAI.Probability.FreeIsing.Trees.ColoredPathEndpoints +OAI.Probability.FreeIsing.Trees.ConeCoding +OAI.Probability.FreeIsing.Trees.ConeComplementField +OAI.Probability.FreeIsing.Trees.ConeComplementFusion +OAI.Probability.FreeIsing.Trees.ConeComponentAttenuation +OAI.Probability.FreeIsing.Trees.ConePercolation +OAI.Probability.FreeIsing.Trees.ConeSelectedFieldAttenuation +OAI.Probability.FreeIsing.Trees.ConeSelectedFusion +OAI.Probability.FreeIsing.Trees.ConeSubsetFusion +OAI.Probability.FreeIsing.Trees.ConeSurvival +OAI.Probability.FreeIsing.Trees.ConnectedExhaustion +OAI.Probability.FreeIsing.Trees.ConnectedHull +OAI.Probability.FreeIsing.Trees.ConnectedPercolation +OAI.Probability.FreeIsing.Trees.CoordinateResponse +OAI.Probability.FreeIsing.Trees.CoupledPathDrift +OAI.Probability.FreeIsing.Trees.CoupledPathProducts +OAI.Probability.FreeIsing.Trees.CoupledPathVariance +OAI.Probability.FreeIsing.Trees.CutContinuationChannels +OAI.Probability.FreeIsing.Trees.CutContinuations +OAI.Probability.FreeIsing.Trees.CutLevelBranchIndependence +OAI.Probability.FreeIsing.Trees.CutLevelConcentration +OAI.Probability.FreeIsing.Trees.EdgeCylinders +OAI.Probability.FreeIsing.Trees.EdgeIIDLaw +OAI.Probability.FreeIsing.Trees.EdgeLabelCoding +OAI.Probability.FreeIsing.Trees.EdgePercolationLaw +OAI.Probability.FreeIsing.Trees.EncodedClusterLaw +OAI.Probability.FreeIsing.Trees.EndpointFromPaths +OAI.Probability.FreeIsing.Trees.Escape +OAI.Probability.FreeIsing.Trees.FiniteClusterLaw +OAI.Probability.FreeIsing.Trees.FiniteClusterSelector +OAI.Probability.FreeIsing.Trees.FiniteClusterSelectorLaw +OAI.Probability.FreeIsing.Trees.FinitePathCutCost +OAI.Probability.FreeIsing.Trees.FinitePathGibbs +OAI.Probability.FreeIsing.Trees.FreeIsingBranchFamily +OAI.Probability.FreeIsing.Trees.FreeLawConeMarkov +OAI.Probability.FreeIsing.Trees.GeodesicPrefix +OAI.Probability.FreeIsing.Trees.GibbsAutomorphism +OAI.Probability.FreeIsing.Trees.GibbsCovariance +OAI.Probability.FreeIsing.Trees.GibbsField +OAI.Probability.FreeIsing.Trees.GibbsMarginal +OAI.Probability.FreeIsing.Trees.HalfPathDecay +OAI.Probability.FreeIsing.Trees.IncidentEdges +OAI.Probability.FreeIsing.Trees.IndexedPathVariance +OAI.Probability.FreeIsing.Trees.InfiniteCanonicalPathResponse +OAI.Probability.FreeIsing.Trees.InfiniteConeCavity +OAI.Probability.FreeIsing.Trees.InfiniteInwardCavity +OAI.Probability.FreeIsing.Trees.InnovationPathMap +OAI.Probability.FreeIsing.Trees.InwardCutChannels +OAI.Probability.FreeIsing.Trees.InwardCutCost +OAI.Probability.FreeIsing.Trees.InwardCutFields +OAI.Probability.FreeIsing.Trees.InwardCutProducts +OAI.Probability.FreeIsing.Trees.Koopman +OAI.Probability.FreeIsing.Trees.LawDecay +OAI.Probability.FreeIsing.Trees.LawSpectral +OAI.Probability.FreeIsing.Trees.LeafCovariance +OAI.Probability.FreeIsing.Trees.LeafMarginal +OAI.Probability.FreeIsing.Trees.NoisyBranchIndependence +OAI.Probability.FreeIsing.Trees.NoisyBranchSeparation +OAI.Probability.FreeIsing.Trees.NoisyBranchTransport +OAI.Probability.FreeIsing.Trees.NoisyConeSeparation +OAI.Probability.FreeIsing.Trees.NoisyCutLevelIndependence +OAI.Probability.FreeIsing.Trees.NoisyEdgeDecay +OAI.Probability.FreeIsing.Trees.NoisyPathLocality +OAI.Probability.FreeIsing.Trees.NoisyRootIndependence +OAI.Probability.FreeIsing.Trees.OpenClusterGeometry +OAI.Probability.FreeIsing.Trees.OrbitAverage +OAI.Probability.FreeIsing.Trees.Parents +OAI.Probability.FreeIsing.Trees.PathAverageWeight +OAI.Probability.FreeIsing.Trees.PathCutCost +OAI.Probability.FreeIsing.Trees.PathCutoff +OAI.Probability.FreeIsing.Trees.PathCylinders +OAI.Probability.FreeIsing.Trees.PathGibbs +OAI.Probability.FreeIsing.Trees.PathHomogeneity +OAI.Probability.FreeIsing.Trees.PathPrefix +OAI.Probability.FreeIsing.Trees.PathRerooting +OAI.Probability.FreeIsing.Trees.PathResponse +OAI.Probability.FreeIsing.Trees.PathReverseRerooting +OAI.Probability.FreeIsing.Trees.PathSideBranches +OAI.Probability.FreeIsing.Trees.PathSideInwardLocality +OAI.Probability.FreeIsing.Trees.PathSideLocality +OAI.Probability.FreeIsing.Trees.PathSideReroot +OAI.Probability.FreeIsing.Trees.PathSplit +OAI.Probability.FreeIsing.Trees.PathSums +OAI.Probability.FreeIsing.Trees.PathVariance +OAI.Probability.FreeIsing.Trees.PercolationFiniteness +OAI.Probability.FreeIsing.Trees.PercolationSurvival +OAI.Probability.FreeIsing.Trees.RadialEnergy +OAI.Probability.FreeIsing.Trees.Regularity +OAI.Probability.FreeIsing.Trees.ResponseAutomorphism +OAI.Probability.FreeIsing.Trees.ResponseFieldBound +OAI.Probability.FreeIsing.Trees.ResponseLeaf +OAI.Probability.FreeIsing.Trees.ResponseRowEnergy +OAI.Probability.FreeIsing.Trees.ResponseSourceInvariance +OAI.Probability.FreeIsing.Trees.RestrictedCutCardinality +OAI.Probability.FreeIsing.Trees.RootComponentAttenuation +OAI.Probability.FreeIsing.Trees.RootCorrelation +OAI.Probability.FreeIsing.Trees.RootCovariance +OAI.Probability.FreeIsing.Trees.RootRegression +OAI.Probability.FreeIsing.Trees.RootedBroadcast +OAI.Probability.FreeIsing.Trees.RootedBroadcastLaw +OAI.Probability.FreeIsing.Trees.RootedGeometry +OAI.Probability.FreeIsing.Trees.RootedProjectivity +OAI.Probability.FreeIsing.Trees.RootedTransitivity +OAI.Probability.FreeIsing.Trees.RowEnergyCutoff +OAI.Probability.FreeIsing.Trees.SelectedInwardPathAttenuation +OAI.Probability.FreeIsing.Trees.SelectedPathAttenuation +OAI.Probability.FreeIsing.Trees.SelectedPathLocality +OAI.Probability.FreeIsing.Trees.SelectedPathSegmentAttenuation +OAI.Probability.FreeIsing.Trees.Shells +OAI.Probability.FreeIsing.Trees.SpinEncoding +OAI.Probability.FreeIsing.Trees.StemRerootAverage +OAI.Probability.FreeIsing.Trees.SubcriticalClusters +OAI.Probability.FreeIsing.Trees.SubcriticalPathSums +OAI.Probability.FreeIsing.Trees.Transitivity +OAI.Probability.FreeIsing.Trees.WeightEncoding +OAI.Probability.FreeIsing.Trees.WeightedPathSummation +OAI.Probability.FreeIsing.Trees.WeightedShellSummation +OAI.Probability.FreeIsing.Trees.WordAction +OAI.Probability.FreeIsing.Trees.WordCancellation diff --git a/tasks/free-ising/solution/reference.py b/tasks/free-ising/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/free-ising/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/free-ising/solution/solve.sh b/tasks/free-ising/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9b1fd3b25dce8eff87e65dafff5355a6b7c80992 --- /dev/null +++ b/tasks/free-ising/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FreeIsing, i.e. module OAI.Probability.FreeIsing.Main and the +# 891 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.FreeIsing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FreeIsing" diff --git a/tasks/free-ising/task.toml b/tasks/free-ising/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fc357e9ec322b2531d613d267c0c442dd28571c2 --- /dev/null +++ b/tasks/free-ising/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/free-ising" +version = "1.0.0" +description = "Prove FreeIsing (openai/math family 236: The factor-of-IID threshold for free Ising states on trees) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FreeIsing.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FreeIsing" +family = "236" +family_title = "The factor-of-IID threshold for free Ising states on trees" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Problem367.free_ising_factor_iff_threshold"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.FreeIsing.Main" +reference_modules = 891 +reference_lean_bytes = 5530584 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2215 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 16677 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/free-ising/tests/Challenge.lean b/tasks/free-ising/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..fa9db545bea8cd0291e8ad2dd025c95ce62499ef --- /dev/null +++ b/tasks/free-ising/tests/Challenge.lean @@ -0,0 +1,95 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory + +namespace Problem367 + +abbrev TreeVertex (d : ℕ) := + {word : List (Fin d) // List.IsChain (fun first second : Fin d => first ≠ second) word} + +def treeAdj {d : ℕ} (u v : TreeVertex d) : Prop := + (∃ c : Fin d, v.1 = u.1 ++ [c]) ∨ + (∃ c : Fin d, u.1 = v.1 ++ [c]) + +structure TreeAut (d : ℕ) where + toEquiv : TreeVertex d ≃ TreeVertex d + map_adj : ∀ u v, treeAdj (toEquiv u) (toEquiv v) ↔ treeAdj u v + +def relabel {d : ℕ} {α : Type*} (g : TreeAut d) + (x : TreeVertex d → α) : TreeVertex d → α := + fun v => x (g.toEquiv.symm v) + +inductive IsingSpin where + | neg + | pos + deriving DecidableEq + +protected abbrev IsingSpin.enumList : List IsingSpin := [.neg, .pos] + +protected theorem IsingSpin.enumList_getElem?_ctorIdx_eq (x : IsingSpin) : + IsingSpin.enumList[x.ctorIdx]? = some x := by + cases x <;> rfl + +protected theorem IsingSpin.enumList_nodup : IsingSpin.enumList.Nodup := by decide + +instance : Fintype IsingSpin where + elems := ⟨IsingSpin.enumList, IsingSpin.enumList_nodup⟩ + complete x := by cases x <;> decide + +instance isingSpinMeasurable : MeasurableSpace IsingSpin := ⊤ + +def uniform01 : Measure ℝ := + volume.restrict (Set.Icc (0 : ℝ) 1) + +instance uniform01Probability : IsProbabilityMeasure uniform01 where + measure_univ := by simp [uniform01] + +def labelMeasure (d : ℕ) : Measure (TreeVertex d → ℝ) := by + classical + exact Measure.infinitePi (fun _ : TreeVertex d => uniform01) + +def ConnectedFinset {d : ℕ} (D : Finset (TreeVertex d)) : Prop := + D.Nonempty ∧ + ∀ u ∈ D, ∀ v ∈ D, + Relation.ReflTransGen + (fun x y : TreeVertex d => x ∈ D ∧ y ∈ D ∧ treeAdj x y) u v + +def inducedEdges {d : ℕ} (D : Finset (TreeVertex d)) : + Finset (TreeVertex d × TreeVertex d) := by + classical + exact (D.product D).filter (fun e => + treeAdj e.1 e.2 ∧ e.1.1.length < e.2.1.length) + +def freeCylinderWeight {d : ℕ} (theta : ℝ) + (D : Finset (TreeVertex d)) (eta : TreeVertex d → IsingSpin) : ENNReal := + ENNReal.ofReal + ((1 / 2 : ℝ) * + Finset.prod (inducedEdges D) (fun e => + (1 + (if eta e.1 = eta e.2 then theta else -theta)) / 2)) + +def HasFreeIsingLaw {d : ℕ} (theta : ℝ) + (mu : Measure (TreeVertex d → IsingSpin)) : Prop := + ∀ (D : Finset (TreeVertex d)), ConnectedFinset D → + ∀ eta : TreeVertex d → IsingSpin, + mu {x | ∀ v ∈ D, x v = eta v} = freeCylinderWeight theta D eta + +def IsFactorOfIID (d : ℕ) (theta : ℝ) : Prop := + ∃ Phi : (TreeVertex d → ℝ) → (TreeVertex d → IsingSpin), + Measurable Phi ∧ + HasFreeIsingLaw theta (Measure.map Phi (labelMeasure d)) ∧ + ∀ g : TreeAut d, + ∀ᵐ U ∂labelMeasure d, Phi (relabel g U) = relabel g (Phi U) + +theorem free_ising_factor_iff_threshold : + ∀ (d : ℕ) (beta : ℝ), 3 ≤ d → 0 ≤ beta → (IsFactorOfIID d (Real.tanh beta) ↔ Real.tanh beta ≤ 1 / Real.sqrt ((d : ℝ) - 1)) := by + sorry + +end Problem367 + +end + +end OAI diff --git a/tasks/free-ising/tests/grade.py b/tasks/free-ising/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/free-ising/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/free-ising/tests/task.json b/tasks/free-ising/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..905c5c664cc0afaf56a77b287d9b339e72f764c0 --- /dev/null +++ b/tasks/free-ising/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FreeIsing", + "comparator": { + "theorem_names": [ + "OAI.Problem367.free_ising_factor_iff_threshold" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 15777 +} \ No newline at end of file diff --git a/tasks/free-ising/tests/test.sh b/tasks/free-ising/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/free-ising/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/free-uniform-spanning-forest/environment/Dockerfile b/tasks/free-uniform-spanning-forest/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/free-uniform-spanning-forest/environment/fetch_mathlib.sh b/tasks/free-uniform-spanning-forest/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/free-uniform-spanning-forest/environment/lake-manifest.json b/tasks/free-uniform-spanning-forest/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/free-uniform-spanning-forest/environment/lakefile.lean b/tasks/free-uniform-spanning-forest/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/free-uniform-spanning-forest/environment/lean_setup.sh b/tasks/free-uniform-spanning-forest/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/free-uniform-spanning-forest/environment/pack_submission.py b/tasks/free-uniform-spanning-forest/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/free-uniform-spanning-forest/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/free-uniform-spanning-forest/instruction.md b/tasks/free-uniform-spanning-forest/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..129ab4ba3730ff2c6ea2d4d03bc8fbff19af39f9 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/instruction.md @@ -0,0 +1,200 @@ +# openai/math challenge `FreeUniformSpanningForest` (family 231) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 231 of the release, *The free uniform spanning forest is a factor of IID* +(Probability and statistical mechanics). The family as a whole: On every infinite connected locally finite simple unweighted graph, the free uniform spanning forest is a factor of independent vertex labels, by one isomorphism-equivariant rule using no root. Translation-invariant strongly Rayleigh binary processes on every countable group, including invariant determinantal processes with Hermitian positive-contraction kernels, are also factors of IID. + +The challenge is `FreeUniformSpanningForest`, also at `/opt/openai-math/challenges/FreeUniformSpanningForest.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal Topology + +namespace Problem336 + +abbrev GraphCode := + {a : ℕ → ℕ → Bool // + (∀ u, a u u = false) ∧ (∀ u v, a u v = a v u)} + +abbrev EdgeCode := {p : ℕ × ℕ // p.1 < p.2} + +abbrev EdgeConfiguration := EdgeCode → Bool + +abbrev FactorRule := GraphCode → (ℕ → ℝ) → EdgeCode → Bool + +abbrev FiniteSubgraphCode := Finset ℕ × Finset (ℕ × ℕ) + +def Adj (G : GraphCode) (u v : ℕ) : Prop := G.1 u v = true + +def GraphConnected (G : GraphCode) : Prop := + ∀ u v, Relation.ReflTransGen (fun x y => Adj G x y) u v + +def GraphLocallyFinite (G : GraphCode) : Prop := + ∀ u, Set.Finite {v : ℕ | Adj G u v} + +def mkEdge (u v : ℕ) (h : u ≠ v) : EdgeCode := by + by_cases huv : u < v + · exact ⟨(u, v), huv⟩ + · exact ⟨(v, u), lt_of_le_of_ne (Nat.le_of_not_gt huv) (Ne.symm h)⟩ + +def rawPair (u v : ℕ) : ℕ × ℕ := + if u < v then (u, v) else (v, u) + +def relabelGraph (σ : Equiv ℕ ℕ) (G : GraphCode) : GraphCode := + ⟨fun u v => G.1 (σ.symm u) (σ.symm v), by + constructor + · intro u + exact G.2.1 (σ.symm u) + · intro u v + exact G.2.2 (σ.symm u) (σ.symm v)⟩ + +def relabelLabels (σ : Equiv ℕ ℕ) (U : ℕ → ℝ) : ℕ → ℝ := + fun u => U (σ.symm u) + +def mapEdge (σ : Equiv ℕ ℕ) (e : EdgeCode) : EdgeCode := + mkEdge (σ e.1.1) (σ e.1.2) (by + intro h + apply Nat.ne_of_lt e.2 + exact σ.injective h) + +def RuleBorel (Phi : FactorRule) : Prop := + Measurable + (fun q : GraphCode × ((ℕ → ℝ) × EdgeCode) => + Phi q.1 q.2.1 q.2.2) + +def RuleEquivariant (Phi : FactorRule) : Prop := + ∀ (σ : Equiv ℕ ℕ) (G : GraphCode) (U : ℕ → ℝ) (e : EdgeCode), + Phi (relabelGraph σ G) (relabelLabels σ U) (mapEdge σ e) = + Phi G U e + +def TreeAdj (T : Finset (ℕ × ℕ)) (u v : ℕ) : Prop := + rawPair u v ∈ T + +def SubgraphAdj (K : FiniteSubgraphCode) (u v : ℕ) : Prop := + u ∈ K.1 ∧ v ∈ K.1 ∧ rawPair u v ∈ K.2 + +def TreeOn (K : FiniteSubgraphCode) + (T : Finset (ℕ × ℕ)) : Prop := + T ⊆ K.2 ∧ + T.card + 1 = K.1.card ∧ + ∀ u ∈ K.1, ∀ v ∈ K.1, + Relation.ReflTransGen (TreeAdj T) u v + +def spanningTrees (K : FiniteSubgraphCode) : + Finset (Finset (ℕ × ℕ)) := by + classical + exact K.2.powerset.filter (TreeOn K) + +def ustCylinder (K : FiniteSubgraphCode) + (A B : Finset EdgeCode) : ℝ≥0∞ := by + classical + let all := spanningTrees K + let good := all.filter (fun T => + (∀ e ∈ A, e.1 ∈ T) ∧ (∀ e ∈ B, e.1 ∉ T)) + exact (good.card : ℝ≥0∞) / (all.card : ℝ≥0∞) + +def IsFiniteConnectedSubgraph + (G : GraphCode) (K : FiniteSubgraphCode) : Prop := + K.1.Nonempty ∧ + (∀ p ∈ K.2, + p.1 ∈ K.1 ∧ p.2 ∈ K.1 ∧ p.1 < p.2 ∧ Adj G p.1 p.2) ∧ + ∀ u ∈ K.1, ∀ v ∈ K.1, + Relation.ReflTransGen (SubgraphAdj K) u v + +def IsConnectedExhaustion + (G : GraphCode) (H : ℕ → FiniteSubgraphCode) : Prop := + (∀ n, IsFiniteConnectedSubgraph G (H n)) ∧ + (∀ n, (H n).1 ⊆ (H (n + 1)).1 ∧ + (H n).2 ⊆ (H (n + 1)).2) ∧ + (∀ u v, u < v → Adj G u v → + ∃ n, (u, v) ∈ (H n).2) + +def uniform01 : Measure ℝ := + volume.restrict (Set.Icc (0 : ℝ) 1) + +def IsVertexIID {Ω : Type} [MeasurableSpace Ω] + (P : Measure Ω) (U : ℕ → Ω → ℝ) : Prop := + (∀ i, Measurable (U i)) ∧ + ∀ (s : Finset ℕ) (A : ℕ → Set ℝ), + (∀ i ∈ s, MeasurableSet (A i)) → + P {ω | ∀ i ∈ s, U i ω ∈ A i} = + Finset.prod s (fun i => uniform01 (A i)) + +def HasFUSFLaw {Ω : Type} [MeasurableSpace Ω] + (G : GraphCode) (P : Measure Ω) + (X : Ω → EdgeConfiguration) : Prop := + (∀ e, Measurable (fun ω => X ω e)) ∧ + ∀ (H : ℕ → FiniteSubgraphCode), IsConnectedExhaustion G H → + ∀ (A B : Finset EdgeCode), + Filter.Tendsto + (fun n => ustCylinder (H n) A B) + Filter.atTop + (nhds (P {ω | + (∀ e ∈ A, X ω e = true) ∧ + (∀ e ∈ B, X ω e = false)})) + +def WorksOnGraph (Phi : FactorRule) (G : GraphCode) : Prop := + GraphConnected G → GraphLocallyFinite G → + ∀ (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) + (U : ℕ → Ω → ℝ), + IsVertexIID P U → + HasFUSFLaw G P + (fun ω e => Phi G (fun v => U v ω) e) + +theorem fusf_is_factor_iid : + ∃ Phi : FactorRule, RuleBorel Phi ∧ RuleEquivariant Phi ∧ ∀ G : GraphCode, WorksOnGraph Phi G := by + sorry + +end Problem336 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/FreeUniformSpanningForest.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem336.fusf_is_factor_iid` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/free-uniform-spanning-forest/solution/closure.txt b/tasks/free-uniform-spanning-forest/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f94cc6a73efa17a4fb1118ae6f712fcd6b135c99 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/solution/closure.txt @@ -0,0 +1,224 @@ +OAI.Probability.SpanningForest.AlgebraicCycleSpace +OAI.Probability.SpanningForest.AllPairAllocation +OAI.Probability.SpanningForest.AllPairFactorAssembly +OAI.Probability.SpanningForest.AllPairIID +OAI.Probability.SpanningForest.AllPairIntrinsicBridge +OAI.Probability.SpanningForest.AllPairObservation +OAI.Probability.SpanningForest.AllPairPicardDecoder +OAI.Probability.SpanningForest.AllPairPosteriorDrift +OAI.Probability.SpanningForest.AllPairWiener +OAI.Probability.SpanningForest.AnalyticSupport +OAI.Probability.SpanningForest.BinaryGaussianPosterior +OAI.Probability.SpanningForest.BinaryLawUnique +OAI.Probability.SpanningForest.BinaryWeakConvergence +OAI.Probability.SpanningForest.BitRecovery +OAI.Probability.SpanningForest.BorelExhaustion +OAI.Probability.SpanningForest.BorelFUSFKernel +OAI.Probability.SpanningForest.BorelFiniteChoice +OAI.Probability.SpanningForest.BrownianBridge +OAI.Probability.SpanningForest.BrownianCanonicalPosterior +OAI.Probability.SpanningForest.BrownianFamilyIdentification +OAI.Probability.SpanningForest.BrownianFamilyNoise +OAI.Probability.SpanningForest.BrownianFamilyPast +OAI.Probability.SpanningForest.BrownianFinitePosterior +OAI.Probability.SpanningForest.BrownianPosteriorReduction +OAI.Probability.SpanningForest.BrownianReference +OAI.Probability.SpanningForest.BrownianSublinear +OAI.Probability.SpanningForest.CanonicalBrownianReference +OAI.Probability.SpanningForest.CanonicalBrownianSampler +OAI.Probability.SpanningForest.CanonicalDecoder +OAI.Probability.SpanningForest.CanonicalDrift +OAI.Probability.SpanningForest.CanonicalFUSFLaw +OAI.Probability.SpanningForest.CanonicalIID +OAI.Probability.SpanningForest.CanonicalPosteriorIdentification +OAI.Probability.SpanningForest.CanonicalPosteriorMartingale +OAI.Probability.SpanningForest.CauchyBinet +OAI.Probability.SpanningForest.CharacteristicRemainder +OAI.Probability.SpanningForest.CharacteristicTaylor +OAI.Probability.SpanningForest.CodeLaplacian +OAI.Probability.SpanningForest.CodeTransferKernel +OAI.Probability.SpanningForest.CodedIncidenceMinors +OAI.Probability.SpanningForest.CodedInclusion +OAI.Probability.SpanningForest.CodedMarginal +OAI.Probability.SpanningForest.CodedMatrixTree +OAI.Probability.SpanningForest.CodedTransferBridge +OAI.Probability.SpanningForest.CodedTransferProjection +OAI.Probability.SpanningForest.ConditionalInnovation +OAI.Probability.SpanningForest.ContinuousPathLaw +OAI.Probability.SpanningForest.ContinuousPathLimit +OAI.Probability.SpanningForest.ContinuousPathSampler +OAI.Probability.SpanningForest.CoordinateTruncation +OAI.Probability.SpanningForest.CountableBrownian +OAI.Probability.SpanningForest.CountableProjective +OAI.Probability.SpanningForest.CylinderKernel +OAI.Probability.SpanningForest.CylinderLimitMeasure +OAI.Probability.SpanningForest.DecoderBundle +OAI.Probability.SpanningForest.DecoderPathSpace +OAI.Probability.SpanningForest.DecoderRestriction +OAI.Probability.SpanningForest.Definitions +OAI.Probability.SpanningForest.DenseBrownian +OAI.Probability.SpanningForest.DenseGaussianModification +OAI.Probability.SpanningForest.DeterminantalResponse +OAI.Probability.SpanningForest.DisconnectedIncidence +OAI.Probability.SpanningForest.DyadicGaussianBound +OAI.Probability.SpanningForest.DyadicInterpolation +OAI.Probability.SpanningForest.DyadicPathLimit +OAI.Probability.SpanningForest.DyadicTimes +OAI.Probability.SpanningForest.EdgeAction +OAI.Probability.SpanningForest.EdgeAllocation +OAI.Probability.SpanningForest.EdgeAllocationMeasurable +OAI.Probability.SpanningForest.EdgeIID +OAI.Probability.SpanningForest.EdgeUniformRule +OAI.Probability.SpanningForest.EquivariantFUSFKernel +OAI.Probability.SpanningForest.Exhaustion +OAI.Probability.SpanningForest.ExhaustionExistence +OAI.Probability.SpanningForest.ExponentialFamily +OAI.Probability.SpanningForest.FUSFExistenceReduction +OAI.Probability.SpanningForest.FUSFLawSupport +OAI.Probability.SpanningForest.FUSFLawUnique +OAI.Probability.SpanningForest.FUSFPosteriorResponse +OAI.Probability.SpanningForest.FUSFRelabelMeasure +OAI.Probability.SpanningForest.Factor +OAI.Probability.SpanningForest.FactorAssembly +OAI.Probability.SpanningForest.FactorLawTransport +OAI.Probability.SpanningForest.FactorReadout +OAI.Probability.SpanningForest.FactorSampler +OAI.Probability.SpanningForest.FinalFactor +OAI.Probability.SpanningForest.FiniteCycleIncidence +OAI.Probability.SpanningForest.FiniteGaussianPosterior +OAI.Probability.SpanningForest.FiniteGradientResponse +OAI.Probability.SpanningForest.FiniteIncidenceBridge +OAI.Probability.SpanningForest.FiniteKernelBridge +OAI.Probability.SpanningForest.FiniteKernelEmbedding +OAI.Probability.SpanningForest.FiniteKernelSupport +OAI.Probability.SpanningForest.FiniteObservationReduction +OAI.Probability.SpanningForest.FinitePosterior +OAI.Probability.SpanningForest.FinitePosteriorTilt +OAI.Probability.SpanningForest.FiniteProductDensity +OAI.Probability.SpanningForest.FiniteResponse +OAI.Probability.SpanningForest.FiniteTiltLimit +OAI.Probability.SpanningForest.FiniteTiltMeasure +OAI.Probability.SpanningForest.FiniteUSTIntegrals +OAI.Probability.SpanningForest.FiniteUSTLimit +OAI.Probability.SpanningForest.FiniteUSTMeasure +OAI.Probability.SpanningForest.FiniteUSTProbability +OAI.Probability.SpanningForest.FiniteUSTRelabel +OAI.Probability.SpanningForest.FullObservationPosterior +OAI.Probability.SpanningForest.GaussianBoundedCorrection +OAI.Probability.SpanningForest.GaussianLikelihood +OAI.Probability.SpanningForest.GaussianMomentScaling +OAI.Probability.SpanningForest.GaussianObservationDensity +OAI.Probability.SpanningForest.GaussianObservationKernel +OAI.Probability.SpanningForest.GaussianPosteriorAllTime +OAI.Probability.SpanningForest.GaussianSum +OAI.Probability.SpanningForest.GeneratorExhaustion +OAI.Probability.SpanningForest.GibbsField +OAI.Probability.SpanningForest.GibbsResponse +OAI.Probability.SpanningForest.GlobalWiener +OAI.Probability.SpanningForest.GramDeterminantUpdate +OAI.Probability.SpanningForest.GraphBalls +OAI.Probability.SpanningForest.GraphBorel +OAI.Probability.SpanningForest.GraphCoordinateTruncation +OAI.Probability.SpanningForest.GraphDomain +OAI.Probability.SpanningForest.GraphEncoding +OAI.Probability.SpanningForest.GraphFUSFLaw +OAI.Probability.SpanningForest.GraphFreeKernel +OAI.Probability.SpanningForest.GraphLaw +OAI.Probability.SpanningForest.GraphTreePosterior +OAI.Probability.SpanningForest.GraphTreePosteriorEquiv +OAI.Probability.SpanningForest.GraphTreeResponse +OAI.Probability.SpanningForest.HilbertBundle +OAI.Probability.SpanningForest.IIDBlocks +OAI.Probability.SpanningForest.IncidenceCirculation +OAI.Probability.SpanningForest.IncidenceMinorClassification +OAI.Probability.SpanningForest.IncidenceResponse +OAI.Probability.SpanningForest.IncidenceUnimodular +OAI.Probability.SpanningForest.InclusionPolynomial +OAI.Probability.SpanningForest.IndependentProcessVectors +OAI.Probability.SpanningForest.InducedCode +OAI.Probability.SpanningForest.InnovationAdapted +OAI.Probability.SpanningForest.InnovationErrorRate +OAI.Probability.SpanningForest.InnovationFiniteGaussian +OAI.Probability.SpanningForest.InnovationGaussianLaw +OAI.Probability.SpanningForest.InnovationGaussianObservation +OAI.Probability.SpanningForest.InnovationGaussianProcess +OAI.Probability.SpanningForest.InnovationIdentification +OAI.Probability.SpanningForest.InnovationLawIdentification +OAI.Probability.SpanningForest.InnovationMartingale +OAI.Probability.SpanningForest.InnovationMean +OAI.Probability.SpanningForest.InnovationMoments +OAI.Probability.SpanningForest.InnovationPhaseRecurrence +OAI.Probability.SpanningForest.InnovationProcessLaw +OAI.Probability.SpanningForest.InnovationProjection +OAI.Probability.SpanningForest.InnovationStep +OAI.Probability.SpanningForest.InnovationSubdivision +OAI.Probability.SpanningForest.InnovationTaylor +OAI.Probability.SpanningForest.IntrinsicBridge +OAI.Probability.SpanningForest.IntrinsicExhaustion +OAI.Probability.SpanningForest.IntrinsicHalfResponse +OAI.Probability.SpanningForest.IntrinsicPosteriorDrift +OAI.Probability.SpanningForest.IntrinsicPosteriorIdentification +OAI.Probability.SpanningForest.IntrinsicRelabel +OAI.Probability.SpanningForest.IntrinsicTreeDrift +OAI.Probability.SpanningForest.JointInnovationLaw +OAI.Probability.SpanningForest.JointProcessLaw +OAI.Probability.SpanningForest.LabelNoCollision +OAI.Probability.SpanningForest.LawLimits +OAI.Probability.SpanningForest.MarkedGram +OAI.Probability.SpanningForest.MatrixTreeSupport +OAI.Probability.SpanningForest.NoCollisionExtension +OAI.Probability.SpanningForest.ObservationPosterior +OAI.Probability.SpanningForest.ObservedBrownianMartingale +OAI.Probability.SpanningForest.OrderedMinorCounting +OAI.Probability.SpanningForest.PathConcatenation +OAI.Probability.SpanningForest.Picard +OAI.Probability.SpanningForest.PicardBounds +OAI.Probability.SpanningForest.PicardNonnegativeSampler +OAI.Probability.SpanningForest.PicardNonnegativeTime +OAI.Probability.SpanningForest.PicardSamplerLaw +OAI.Probability.SpanningForest.PicardSolution +OAI.Probability.SpanningForest.PicardUniqueness +OAI.Probability.SpanningForest.PolynomialGramUpdate +OAI.Probability.SpanningForest.PosteriorDrift +OAI.Probability.SpanningForest.PosteriorIndependentExtension +OAI.Probability.SpanningForest.PosteriorNullCoordinates +OAI.Probability.SpanningForest.PosteriorSupport +OAI.Probability.SpanningForest.PosteriorTiltLimit +OAI.Probability.SpanningForest.ProjectionLimit +OAI.Probability.SpanningForest.RandomReindex +OAI.Probability.SpanningForest.RandomSelection +OAI.Probability.SpanningForest.RawInnovationSampler +OAI.Probability.SpanningForest.ReducedCycleKernel +OAI.Probability.SpanningForest.ReducedLaplacian +OAI.Probability.SpanningForest.Relabeling +OAI.Probability.SpanningForest.ResponseLipschitz +OAI.Probability.SpanningForest.RuleExtension +OAI.Probability.SpanningForest.SampledPathConcatenation +OAI.Probability.SpanningForest.SampledUnitPath +OAI.Probability.SpanningForest.SchauderTail +OAI.Probability.SpanningForest.SchauderTents +OAI.Probability.SpanningForest.SlopeReadout +OAI.Probability.SpanningForest.StochasticBundle +OAI.Probability.SpanningForest.SubtypeSubsetSums +OAI.Probability.SpanningForest.Theory +OAI.Probability.SpanningForest.TiltResponse +OAI.Probability.SpanningForest.TotalTreeResponse +OAI.Probability.SpanningForest.TransferCurrent +OAI.Probability.SpanningForest.TransferCurrentLipschitz +OAI.Probability.SpanningForest.TransferProjection +OAI.Probability.SpanningForest.TreePosteriorBridge +OAI.Probability.SpanningForest.USTCylinder +OAI.Probability.SpanningForest.USTDeterminant +OAI.Probability.SpanningForest.USTFiniteDeterminantal +OAI.Probability.SpanningForest.USTFiniteTilt +OAI.Probability.SpanningForest.USTInclusionCount +OAI.Probability.SpanningForest.USTPosteriorResponse +OAI.Probability.SpanningForest.USTResponse +OAI.Probability.SpanningForest.UniformSampler +OAI.Probability.SpanningForest.WeightedCauchyBinet +OAI.Probability.SpanningForest.WeightedInnovation +OAI.Probability.SpanningForest.WeightedTreeBorel +OAI.Probability.SpanningForest.WeightedTreeEquiv +OAI.Probability.SpanningForest.WeightedTreeResponse +OAI.Probability.SpanningForest.WeightedTreeTransport +OAI.Probability.SpanningForest.WienerSampler diff --git a/tasks/free-uniform-spanning-forest/solution/reference.py b/tasks/free-uniform-spanning-forest/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/free-uniform-spanning-forest/solution/solve.sh b/tasks/free-uniform-spanning-forest/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0460e76e6b9585314b0ce0193a77dc78726bdec3 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of FreeUniformSpanningForest, i.e. module OAI.Probability.SpanningForest.Factor and the +# 224 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SpanningForest.Factor /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of FreeUniformSpanningForest" diff --git a/tasks/free-uniform-spanning-forest/task.toml b/tasks/free-uniform-spanning-forest/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7a52ae8dca2de95582dbf24e4b7714ce333e4662 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/free-uniform-spanning-forest" +version = "1.0.0" +description = "Prove FreeUniformSpanningForest (openai/math family 231: The free uniform spanning forest is a factor of IID) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/FreeUniformSpanningForest.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "FreeUniformSpanningForest" +family = "231" +family_title = "The free uniform spanning forest is a factor of IID" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Problem336.fusf_is_factor_iid"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SpanningForest.Factor" +reference_modules = 224 +reference_lean_bytes = 1069516 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1286 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12662 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/free-uniform-spanning-forest/tests/Challenge.lean b/tasks/free-uniform-spanning-forest/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b453c8048e79875ea822e1fd651f39158d27720a --- /dev/null +++ b/tasks/free-uniform-spanning-forest/tests/Challenge.lean @@ -0,0 +1,149 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal Topology + +namespace Problem336 + +abbrev GraphCode := + {a : ℕ → ℕ → Bool // + (∀ u, a u u = false) ∧ (∀ u v, a u v = a v u)} + +abbrev EdgeCode := {p : ℕ × ℕ // p.1 < p.2} + +abbrev EdgeConfiguration := EdgeCode → Bool + +abbrev FactorRule := GraphCode → (ℕ → ℝ) → EdgeCode → Bool + +abbrev FiniteSubgraphCode := Finset ℕ × Finset (ℕ × ℕ) + +def Adj (G : GraphCode) (u v : ℕ) : Prop := G.1 u v = true + +def GraphConnected (G : GraphCode) : Prop := + ∀ u v, Relation.ReflTransGen (fun x y => Adj G x y) u v + +def GraphLocallyFinite (G : GraphCode) : Prop := + ∀ u, Set.Finite {v : ℕ | Adj G u v} + +def mkEdge (u v : ℕ) (h : u ≠ v) : EdgeCode := by + by_cases huv : u < v + · exact ⟨(u, v), huv⟩ + · exact ⟨(v, u), lt_of_le_of_ne (Nat.le_of_not_gt huv) (Ne.symm h)⟩ + +def rawPair (u v : ℕ) : ℕ × ℕ := + if u < v then (u, v) else (v, u) + +def relabelGraph (σ : Equiv ℕ ℕ) (G : GraphCode) : GraphCode := + ⟨fun u v => G.1 (σ.symm u) (σ.symm v), by + constructor + · intro u + exact G.2.1 (σ.symm u) + · intro u v + exact G.2.2 (σ.symm u) (σ.symm v)⟩ + +def relabelLabels (σ : Equiv ℕ ℕ) (U : ℕ → ℝ) : ℕ → ℝ := + fun u => U (σ.symm u) + +def mapEdge (σ : Equiv ℕ ℕ) (e : EdgeCode) : EdgeCode := + mkEdge (σ e.1.1) (σ e.1.2) (by + intro h + apply Nat.ne_of_lt e.2 + exact σ.injective h) + +def RuleBorel (Phi : FactorRule) : Prop := + Measurable + (fun q : GraphCode × ((ℕ → ℝ) × EdgeCode) => + Phi q.1 q.2.1 q.2.2) + +def RuleEquivariant (Phi : FactorRule) : Prop := + ∀ (σ : Equiv ℕ ℕ) (G : GraphCode) (U : ℕ → ℝ) (e : EdgeCode), + Phi (relabelGraph σ G) (relabelLabels σ U) (mapEdge σ e) = + Phi G U e + +def TreeAdj (T : Finset (ℕ × ℕ)) (u v : ℕ) : Prop := + rawPair u v ∈ T + +def SubgraphAdj (K : FiniteSubgraphCode) (u v : ℕ) : Prop := + u ∈ K.1 ∧ v ∈ K.1 ∧ rawPair u v ∈ K.2 + +def TreeOn (K : FiniteSubgraphCode) + (T : Finset (ℕ × ℕ)) : Prop := + T ⊆ K.2 ∧ + T.card + 1 = K.1.card ∧ + ∀ u ∈ K.1, ∀ v ∈ K.1, + Relation.ReflTransGen (TreeAdj T) u v + +def spanningTrees (K : FiniteSubgraphCode) : + Finset (Finset (ℕ × ℕ)) := by + classical + exact K.2.powerset.filter (TreeOn K) + +def ustCylinder (K : FiniteSubgraphCode) + (A B : Finset EdgeCode) : ℝ≥0∞ := by + classical + let all := spanningTrees K + let good := all.filter (fun T => + (∀ e ∈ A, e.1 ∈ T) ∧ (∀ e ∈ B, e.1 ∉ T)) + exact (good.card : ℝ≥0∞) / (all.card : ℝ≥0∞) + +def IsFiniteConnectedSubgraph + (G : GraphCode) (K : FiniteSubgraphCode) : Prop := + K.1.Nonempty ∧ + (∀ p ∈ K.2, + p.1 ∈ K.1 ∧ p.2 ∈ K.1 ∧ p.1 < p.2 ∧ Adj G p.1 p.2) ∧ + ∀ u ∈ K.1, ∀ v ∈ K.1, + Relation.ReflTransGen (SubgraphAdj K) u v + +def IsConnectedExhaustion + (G : GraphCode) (H : ℕ → FiniteSubgraphCode) : Prop := + (∀ n, IsFiniteConnectedSubgraph G (H n)) ∧ + (∀ n, (H n).1 ⊆ (H (n + 1)).1 ∧ + (H n).2 ⊆ (H (n + 1)).2) ∧ + (∀ u v, u < v → Adj G u v → + ∃ n, (u, v) ∈ (H n).2) + +def uniform01 : Measure ℝ := + volume.restrict (Set.Icc (0 : ℝ) 1) + +def IsVertexIID {Ω : Type} [MeasurableSpace Ω] + (P : Measure Ω) (U : ℕ → Ω → ℝ) : Prop := + (∀ i, Measurable (U i)) ∧ + ∀ (s : Finset ℕ) (A : ℕ → Set ℝ), + (∀ i ∈ s, MeasurableSet (A i)) → + P {ω | ∀ i ∈ s, U i ω ∈ A i} = + Finset.prod s (fun i => uniform01 (A i)) + +def HasFUSFLaw {Ω : Type} [MeasurableSpace Ω] + (G : GraphCode) (P : Measure Ω) + (X : Ω → EdgeConfiguration) : Prop := + (∀ e, Measurable (fun ω => X ω e)) ∧ + ∀ (H : ℕ → FiniteSubgraphCode), IsConnectedExhaustion G H → + ∀ (A B : Finset EdgeCode), + Filter.Tendsto + (fun n => ustCylinder (H n) A B) + Filter.atTop + (nhds (P {ω | + (∀ e ∈ A, X ω e = true) ∧ + (∀ e ∈ B, X ω e = false)})) + +def WorksOnGraph (Phi : FactorRule) (G : GraphCode) : Prop := + GraphConnected G → GraphLocallyFinite G → + ∀ (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) + (U : ℕ → Ω → ℝ), + IsVertexIID P U → + HasFUSFLaw G P + (fun ω e => Phi G (fun v => U v ω) e) + +theorem fusf_is_factor_iid : + ∃ Phi : FactorRule, RuleBorel Phi ∧ RuleEquivariant Phi ∧ ∀ G : GraphCode, WorksOnGraph Phi G := by + sorry + +end Problem336 + +end + +end OAI diff --git a/tasks/free-uniform-spanning-forest/tests/grade.py b/tasks/free-uniform-spanning-forest/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/free-uniform-spanning-forest/tests/task.json b/tasks/free-uniform-spanning-forest/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8fb201106cc0fd5d993e26c7bf5b530cec055c5a --- /dev/null +++ b/tasks/free-uniform-spanning-forest/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "FreeUniformSpanningForest", + "comparator": { + "theorem_names": [ + "OAI.Problem336.fusf_is_factor_iid" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11762 +} \ No newline at end of file diff --git a/tasks/free-uniform-spanning-forest/tests/test.sh b/tasks/free-uniform-spanning-forest/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/free-uniform-spanning-forest/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gamma-passage/environment/Dockerfile b/tasks/gamma-passage/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gamma-passage/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gamma-passage/environment/fetch_mathlib.sh b/tasks/gamma-passage/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gamma-passage/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gamma-passage/environment/lake-manifest.json b/tasks/gamma-passage/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gamma-passage/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gamma-passage/environment/lakefile.lean b/tasks/gamma-passage/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gamma-passage/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gamma-passage/environment/lean_setup.sh b/tasks/gamma-passage/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gamma-passage/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gamma-passage/environment/pack_submission.py b/tasks/gamma-passage/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gamma-passage/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gamma-passage/instruction.md b/tasks/gamma-passage/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61a9436775a9d95dead2c96e120c1c927f6f5e47 --- /dev/null +++ b/tasks/gamma-passage/instruction.md @@ -0,0 +1,163 @@ +# openai/math challenge `GammaPassage` (family 212) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 212 of the release, *No bigeodesics and smooth limit shapes in planar first-passage percolation* +(Probability and statistical mechanics). The family as a whole: Proves that planar first-passage percolation has no doubly infinite geodesic for iid nonnegative nonatomic edge weights when the minimum of four weights has finite second moment. For exponential weights, the limit shape is strictly convex with $C^1$ boundary. Differentiability also holds for every Gamma law with positive shape and rate. + +The challenge is `GammaPassage`, also at `/opt/openai-math/challenges/GammaPassage.lean`: + +```lean +import Mathlib.Algebra.BigOperators.Group.List.Basic +import Mathlib.Algebra.Group.Prod +import Mathlib.Analysis.Calculus.ContDiff.Defs +import Mathlib.Analysis.Calculus.Deriv.Basic +import Mathlib.Analysis.Calculus.FDeriv.Basic +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Probability.Distributions.Gamma +import Mathlib.Probability.Independence.Basic + +namespace OAI + +namespace PlanarFPP + +open Set MeasureTheory ProbabilityTheory Filter +open scoped Topology + +abbrev Vertex := ℤ × ℤ + +abbrev Edge := Vertex × Bool + +inductive Step where + | east | west | north | south + deriving DecidableEq + +def Step.delta : Step → Vertex + | .east => (1, 0) + | .west => (-1, 0) + | .north => (0, 1) + | .south => (0, -1) + +def Step.edge (p : Vertex) : Step → Edge + | .east => (p, false) + | .west => (p + (-1, 0), false) + | .north => (p, true) + | .south => (p + (0, -1), true) + +def displacement (ds : List Step) : Vertex := (ds.map Step.delta).sum + +def pathCost (τ : Edge → ℝ) (p : Vertex) : List Step → ℝ + | [] => 0 + | d :: ds => τ (d.edge p) + pathCost τ (p + d.delta) ds + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +noncomputable def latticeFloor (v : Plane) : Vertex := (⌊v 0⌋, ⌊v 1⌋) + +noncomputable def passageTime (τ : Edge → ℝ) (p q : Vertex) : ℝ := + sInf {t | ∃ ds : List Step, p + displacement ds = q ∧ pathCost τ p ds = t} + +structure TimeConstantNorm (μ : Plane → ℝ) : Prop where + nonneg : ∀ v, 0 ≤ μ v + zero_iff : ∀ v, μ v = 0 ↔ v = 0 + triangle : ∀ v w, μ (v + w) ≤ μ v + μ w + homogeneous : ∀ (a : ℝ) v, μ (a • v) = |a| * μ v + +def IsTimeConstant {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) (μ : Plane → ℝ) : Prop := + ∀ v : Plane, ∀ᵐ ω ∂P, + Tendsto (fun t : ℝ => passageTime (fun e => τ e ω) (0, 0) + (latticeFloor (t • v)) / t) atTop (𝓝 (μ v)) + +def DifferentiableAwayFromOrigin (μ : Plane → ℝ) : Prop := + ∀ v : Plane, v ≠ 0 → ∃ ℓ : Plane →L[ℝ] ℝ, HasFDerivAt μ ℓ v + +end PlanarFPP + +namespace GammaFPP + +open Set MeasureTheory ProbabilityTheory PlanarFPP + +structure IidEnvironment {Ω : Type*} [MeasurableSpace Ω] + (ν : Measure ℝ) (P : Measure Ω) (τ : PlanarFPP.Edge → Ω → ℝ) : Prop where + probability : IsProbabilityMeasure P + measurable : ∀ e, Measurable (τ e) + independent : iIndepFun τ P + marginal : ∀ e, Measure.map (τ e) P = ν + + +abbrev GammaEnvironment {Ω : Type*} [MeasurableSpace Ω] + (shape rate : ℝ) (P : Measure Ω) (τ : PlanarFPP.Edge → Ω → ℝ) := + IidEnvironment (gammaMeasure shape rate) P τ + + +/-- A regular C¹ parametrization of the curve near a point, with a continuous inverse. -/ +def HasC1CurveChart (S : Set Plane) (v : Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ v ∈ S ∧ ∃ γ : ℝ → Plane, ∃ θ : Plane → ℝ, + ContDiff ℝ 1 γ ∧ ContinuousOn θ U ∧ + (∀ t, γ t ∈ S ∩ U) ∧ (∀ t, θ (γ t)=t) ∧ + (∀ z ∈ S ∩ U, γ (θ z)=z) ∧ + (∀ t, ∃ d : Plane, HasDerivAt γ d t ∧ d ≠ 0) + +/-- The Gamma theorem: an actual deterministic passage-time limit norm exists +for every positive shape and rate and every iid environment with that law. +Its Frechet differentiability and literal unit-ball boundary charts are +conclusions. No shape theorem, norm, or no-corner hypothesis is supplied. -/ +def GammaDifferentiabilityTarget : Prop := + ∀ (shape rate : ℝ), 0 < shape → 0 < rate → + ∀ (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) + (τ : PlanarFPP.Edge → Ω → ℝ), + GammaEnvironment shape rate P τ → + ∃ μ : Plane → ℝ, + TimeConstantNorm μ ∧ IsTimeConstant P τ μ ∧ + DifferentiableAwayFromOrigin μ ∧ + ∀ v ∈ frontier {z : Plane | μ z ≤ 1}, + HasC1CurveChart (frontier {z : Plane | μ z ≤ 1}) v + +theorem gamma_differentiability : GammaDifferentiabilityTarget := by + sorry + +end GammaFPP + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GammaPassage.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GammaFPP.gamma_differentiability` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gamma-passage/solution/closure.txt b/tasks/gamma-passage/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e972ee7e7756fceffe75dcf0d595f413ba42197 --- /dev/null +++ b/tasks/gamma-passage/solution/closure.txt @@ -0,0 +1,203 @@ +OAI.Probability.FirstPassage.CoordinateTails +OAI.Probability.FirstPassage.ExtremeSlopes +OAI.Probability.FirstPassage.LocalDifferentiability +OAI.Probability.FirstPassage.PassageTime +OAI.Probability.FirstPassage.PathWitnesses +OAI.Probability.FirstPassage.Paths +OAI.Probability.FirstPassage.PlaneGeometry +OAI.Probability.FirstPassage.PositiveMoment +OAI.Probability.FirstPassage.ProbabilityFoundations +OAI.Probability.FirstPassage.Reversal +OAI.Probability.FirstPassage.SpatialModulus +OAI.Probability.FirstPassage.SupportContactEstimate +OAI.Probability.FirstPassage.Supports +OAI.Probability.FirstPassage.Target +OAI.Probability.FirstPassage.TiltPath +OAI.Probability.FirstPassage.Translation +OAI.Probability.FirstPassage.WitnessDecomposition +OAI.Probability.GammaPassage.ASMeanBridge +OAI.Probability.GammaPassage.ActualNoCorner +OAI.Probability.GammaPassage.ActualTimeConstant +OAI.Probability.GammaPassage.ActualWitnessScale +OAI.Probability.GammaPassage.AnalyticCore +OAI.Probability.GammaPassage.AnalyticEndgame +OAI.Probability.GammaPassage.AnalyticSpecialization +OAI.Probability.GammaPassage.BKBitLaw +OAI.Probability.GammaPassage.BKContinuous +OAI.Probability.GammaPassage.BKDyadic +OAI.Probability.GammaPassage.BKFamilies +OAI.Probability.GammaPassage.BKForcing +OAI.Probability.GammaPassage.BKLimit +OAI.Probability.GammaPassage.BKPathMeasurability +OAI.Probability.GammaPassage.BKPrimitives +OAI.Probability.GammaPassage.BKRepeated +OAI.Probability.GammaPassage.BKRounded +OAI.Probability.GammaPassage.BallTravel +OAI.Probability.GammaPassage.BallTravelGeometry +OAI.Probability.GammaPassage.BoundaryCycles +OAI.Probability.GammaPassage.BoundaryGeometry +OAI.Probability.GammaPassage.BoundaryWinding +OAI.Probability.GammaPassage.CDF +OAI.Probability.GammaPassage.CharacteristicLengths +OAI.Probability.GammaPassage.CheapLongTrails +OAI.Probability.GammaPassage.CheapPath +OAI.Probability.GammaPassage.CheapPathCounting +OAI.Probability.GammaPassage.CheapPathDecay +OAI.Probability.GammaPassage.ConcentrationScale +OAI.Probability.GammaPassage.ConnectorContact +OAI.Probability.GammaPassage.ConnectorEvents +OAI.Probability.GammaPassage.ConnectorGeometry +OAI.Probability.GammaPassage.ContiguousWitnesses +OAI.Probability.GammaPassage.ContourCounts +OAI.Probability.GammaPassage.ContourEnumeration +OAI.Probability.GammaPassage.ContourLocalization +OAI.Probability.GammaPassage.CoordinateTails +OAI.Probability.GammaPassage.CrossingChain +OAI.Probability.GammaPassage.CrossingEndpointBounds +OAI.Probability.GammaPassage.CrossingEvents +OAI.Probability.GammaPassage.CrossingLocalized +OAI.Probability.GammaPassage.CrossingTilt +OAI.Probability.GammaPassage.Differentiability +OAI.Probability.GammaPassage.DyadicDerivativeBound +OAI.Probability.GammaPassage.DyadicRanks +OAI.Probability.GammaPassage.EnclosingContour +OAI.Probability.GammaPassage.EndpointAsymptotics +OAI.Probability.GammaPassage.EndpointBlocks +OAI.Probability.GammaPassage.EndpointBounds +OAI.Probability.GammaPassage.EndpointCoarse +OAI.Probability.GammaPassage.EndpointCoarseGeometry +OAI.Probability.GammaPassage.EndpointConnection +OAI.Probability.GammaPassage.EndpointEntrance +OAI.Probability.GammaPassage.EndpointEvents +OAI.Probability.GammaPassage.EndpointExit +OAI.Probability.GammaPassage.EndpointExtensions +OAI.Probability.GammaPassage.EndpointGeometry +OAI.Probability.GammaPassage.EndpointLimit +OAI.Probability.GammaPassage.EndpointMesh +OAI.Probability.GammaPassage.EndpointNet +OAI.Probability.GammaPassage.EndpointProbability +OAI.Probability.GammaPassage.EndpointRecords +OAI.Probability.GammaPassage.EndpointTail +OAI.Probability.GammaPassage.EndpointTranslationProbability +OAI.Probability.GammaPassage.Environment +OAI.Probability.GammaPassage.EnvironmentScaling +OAI.Probability.GammaPassage.ExponentialIncrement +OAI.Probability.GammaPassage.FiniteEdgeTilt +OAI.Probability.GammaPassage.FiniteMoments +OAI.Probability.GammaPassage.FiniteSumIntegrability +OAI.Probability.GammaPassage.FiniteTails +OAI.Probability.GammaPassage.FiniteTilt +OAI.Probability.GammaPassage.FiniteWaypoints +OAI.Probability.GammaPassage.FirstMoment +OAI.Probability.GammaPassage.GlobalCenteredConcentration +OAI.Probability.GammaPassage.GlobalConcentration +OAI.Probability.GammaPassage.GoodSiteBlocks +OAI.Probability.GammaPassage.GoodSiteEvents +OAI.Probability.GammaPassage.GoodSitePaths +OAI.Probability.GammaPassage.GoodSiteProbability +OAI.Probability.GammaPassage.GoodSiteTrials +OAI.Probability.GammaPassage.GridAttachments +OAI.Probability.GammaPassage.GridConnection +OAI.Probability.GammaPassage.GridCounting +OAI.Probability.GammaPassage.GridEvents +OAI.Probability.GammaPassage.GridGeometry +OAI.Probability.GammaPassage.GridIndependence +OAI.Probability.GammaPassage.GridMeshes +OAI.Probability.GammaPassage.GridTail +OAI.Probability.GammaPassage.GridVerticalPaths +OAI.Probability.GammaPassage.HighDensityOriented +OAI.Probability.GammaPassage.LocalCenteredCGF +OAI.Probability.GammaPassage.LocalCenteredConcentration +OAI.Probability.GammaPassage.LocalCoordinateDomination +OAI.Probability.GammaPassage.LocalExponentialEnergy +OAI.Probability.GammaPassage.LocalGlobalEquality +OAI.Probability.GammaPassage.LocalIntegrability +OAI.Probability.GammaPassage.LocalLawTransfer +OAI.Probability.GammaPassage.LocalMeanGap +OAI.Probability.GammaPassage.LocalPassageMGF +OAI.Probability.GammaPassage.LocalRegularity +OAI.Probability.GammaPassage.LocalResamplingExponential +OAI.Probability.GammaPassage.LocalResamplingModel +OAI.Probability.GammaPassage.LocalTrailCandidates +OAI.Probability.GammaPassage.LocalTrailPassage +OAI.Probability.GammaPassage.LocalizationProbability +OAI.Probability.GammaPassage.LoopErasure +OAI.Probability.GammaPassage.MGF +OAI.Probability.GammaPassage.MGFDerivative +OAI.Probability.GammaPassage.MeanAlgebra +OAI.Probability.GammaPassage.MeanLimit +OAI.Probability.GammaPassage.MeanLipschitz +OAI.Probability.GammaPassage.MeanNorm +OAI.Probability.GammaPassage.MeanNormSwap +OAI.Probability.GammaPassage.MeanPairSeminorm +OAI.Probability.GammaPassage.MeanPositive +OAI.Probability.GammaPassage.MeanSwap +OAI.Probability.GammaPassage.MovingOrigin +OAI.Probability.GammaPassage.NoCornerContradiction +OAI.Probability.GammaPassage.OrientedCompactness +OAI.Probability.GammaPassage.OrientedProbability +OAI.Probability.GammaPassage.OrientedSelection +OAI.Probability.GammaPassage.OriginEscape +OAI.Probability.GammaPassage.OriginEscapeLower +OAI.Probability.GammaPassage.PassageLowerBound +OAI.Probability.GammaPassage.PathChain +OAI.Probability.GammaPassage.PathColumnCrossing +OAI.Probability.GammaPassage.PathIntegrability +OAI.Probability.GammaPassage.PathSecondMoment +OAI.Probability.GammaPassage.PathSubpaths +OAI.Probability.GammaPassage.Quantile +OAI.Probability.GammaPassage.RareFast +OAI.Probability.GammaPassage.RareFastEvents +OAI.Probability.GammaPassage.RationalMean +OAI.Probability.GammaPassage.RationalMeanAlgebra +OAI.Probability.GammaPassage.RealDirectionBridge +OAI.Probability.GammaPassage.RealDirectionGeometry +OAI.Probability.GammaPassage.RealMeanExtension +OAI.Probability.GammaPassage.RecordGridProbability +OAI.Probability.GammaPassage.RecordScales +OAI.Probability.GammaPassage.ResamplingEnergyIdentity +OAI.Probability.GammaPassage.Scaling +OAI.Probability.GammaPassage.ScalingLaw +OAI.Probability.GammaPassage.SequenceSummability +OAI.Probability.GammaPassage.ShapeDeficit +OAI.Probability.GammaPassage.ShortCrossingGeometry +OAI.Probability.GammaPassage.ShortCrossingProbability +OAI.Probability.GammaPassage.SourceConnector +OAI.Probability.GammaPassage.SourceTilt +OAI.Probability.GammaPassage.SpatialBadPathCover +OAI.Probability.GammaPassage.SpatialChunkGeometry +OAI.Probability.GammaPassage.SpatialChunkWitness +OAI.Probability.GammaPassage.SpatialChunks +OAI.Probability.GammaPassage.SpatialCrossingGeometry +OAI.Probability.GammaPassage.SpatialEntropyProbability +OAI.Probability.GammaPassage.SpatialFirstExit +OAI.Probability.GammaPassage.SpatialModulus +OAI.Probability.GammaPassage.SpatialPositiveChunk +OAI.Probability.GammaPassage.SpatialRareProbability +OAI.Probability.GammaPassage.SpatialWitnessCounts +OAI.Probability.GammaPassage.SpatialWitnessProbability +OAI.Probability.GammaPassage.SpatialWitnesses +OAI.Probability.GammaPassage.SquareLoops +OAI.Probability.GammaPassage.Stationarity +OAI.Probability.GammaPassage.SurvivalQuantile +OAI.Probability.GammaPassage.SurvivalRank +OAI.Probability.GammaPassage.SurvivalRounding +OAI.Probability.GammaPassage.Target +OAI.Probability.GammaPassage.TiltComparison +OAI.Probability.GammaPassage.TiltDensity +OAI.Probability.GammaPassage.TiltEnvelope +OAI.Probability.GammaPassage.TiltMoment +OAI.Probability.GammaPassage.TiltRegionCount +OAI.Probability.GammaPassage.TubeDeterministic +OAI.Probability.GammaPassage.TubeTravel +OAI.Probability.GammaPassage.UniformShape +OAI.Probability.GammaPassage.UniformShapeGeometry +OAI.Probability.GammaPassage.Waypoints +OAI.Probability.GammaPassage.WitnessBorelCantelli +OAI.Probability.GammaPassage.WitnessEntropy +OAI.Probability.GammaPassage.WitnessSelection +OAI.Probability.LatticePassage.BoundedEfronStein +OAI.Probability.LatticePassage.EfronStein +OAI.Probability.LatticePassage.FiniteVariance +OAI.Probability.LatticePassage.ProductVariance +OAI.Probability.LatticePassage.ResamplingSymmetry diff --git a/tasks/gamma-passage/solution/reference.py b/tasks/gamma-passage/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gamma-passage/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gamma-passage/solution/solve.sh b/tasks/gamma-passage/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e74cdef9836fac6a39230d2abd33f9afe6190970 --- /dev/null +++ b/tasks/gamma-passage/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GammaPassage, i.e. module OAI.Probability.GammaPassage.Differentiability and the +# 203 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.GammaPassage.Differentiability /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GammaPassage" diff --git a/tasks/gamma-passage/task.toml b/tasks/gamma-passage/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cf7ac24f5dab58d54b6d5cca19f841c49142ca15 --- /dev/null +++ b/tasks/gamma-passage/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gamma-passage" +version = "1.0.0" +description = "Prove GammaPassage (openai/math family 212: No bigeodesics and smooth limit shapes in planar first-passage percolation) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GammaPassage.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GammaPassage" +family = "212" +family_title = "No bigeodesics and smooth limit shapes in planar first-passage percolation" +subject = "Probability and statistical mechanics" +theorems = ["OAI.GammaFPP.gamma_differentiability"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.GammaPassage.Differentiability" +reference_modules = 203 +reference_lean_bytes = 947238 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 800 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12552 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gamma-passage/tests/Challenge.lean b/tasks/gamma-passage/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6b2a0bc5cb47eae4ea01c65bdcf3b41b7a025573 --- /dev/null +++ b/tasks/gamma-passage/tests/Challenge.lean @@ -0,0 +1,112 @@ +import Mathlib.Algebra.BigOperators.Group.List.Basic +import Mathlib.Algebra.Group.Prod +import Mathlib.Analysis.Calculus.ContDiff.Defs +import Mathlib.Analysis.Calculus.Deriv.Basic +import Mathlib.Analysis.Calculus.FDeriv.Basic +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Probability.Distributions.Gamma +import Mathlib.Probability.Independence.Basic + +namespace OAI + +namespace PlanarFPP + +open Set MeasureTheory ProbabilityTheory Filter +open scoped Topology + +abbrev Vertex := ℤ × ℤ + +abbrev Edge := Vertex × Bool + +inductive Step where + | east | west | north | south + deriving DecidableEq + +def Step.delta : Step → Vertex + | .east => (1, 0) + | .west => (-1, 0) + | .north => (0, 1) + | .south => (0, -1) + +def Step.edge (p : Vertex) : Step → Edge + | .east => (p, false) + | .west => (p + (-1, 0), false) + | .north => (p, true) + | .south => (p + (0, -1), true) + +def displacement (ds : List Step) : Vertex := (ds.map Step.delta).sum + +def pathCost (τ : Edge → ℝ) (p : Vertex) : List Step → ℝ + | [] => 0 + | d :: ds => τ (d.edge p) + pathCost τ (p + d.delta) ds + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +noncomputable def latticeFloor (v : Plane) : Vertex := (⌊v 0⌋, ⌊v 1⌋) + +noncomputable def passageTime (τ : Edge → ℝ) (p q : Vertex) : ℝ := + sInf {t | ∃ ds : List Step, p + displacement ds = q ∧ pathCost τ p ds = t} + +structure TimeConstantNorm (μ : Plane → ℝ) : Prop where + nonneg : ∀ v, 0 ≤ μ v + zero_iff : ∀ v, μ v = 0 ↔ v = 0 + triangle : ∀ v w, μ (v + w) ≤ μ v + μ w + homogeneous : ∀ (a : ℝ) v, μ (a • v) = |a| * μ v + +def IsTimeConstant {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) (μ : Plane → ℝ) : Prop := + ∀ v : Plane, ∀ᵐ ω ∂P, + Tendsto (fun t : ℝ => passageTime (fun e => τ e ω) (0, 0) + (latticeFloor (t • v)) / t) atTop (𝓝 (μ v)) + +def DifferentiableAwayFromOrigin (μ : Plane → ℝ) : Prop := + ∀ v : Plane, v ≠ 0 → ∃ ℓ : Plane →L[ℝ] ℝ, HasFDerivAt μ ℓ v + +end PlanarFPP + +namespace GammaFPP + +open Set MeasureTheory ProbabilityTheory PlanarFPP + +structure IidEnvironment {Ω : Type*} [MeasurableSpace Ω] + (ν : Measure ℝ) (P : Measure Ω) (τ : PlanarFPP.Edge → Ω → ℝ) : Prop where + probability : IsProbabilityMeasure P + measurable : ∀ e, Measurable (τ e) + independent : iIndepFun τ P + marginal : ∀ e, Measure.map (τ e) P = ν + + +abbrev GammaEnvironment {Ω : Type*} [MeasurableSpace Ω] + (shape rate : ℝ) (P : Measure Ω) (τ : PlanarFPP.Edge → Ω → ℝ) := + IidEnvironment (gammaMeasure shape rate) P τ + + +/-- A regular C¹ parametrization of the curve near a point, with a continuous inverse. -/ +def HasC1CurveChart (S : Set Plane) (v : Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ v ∈ S ∧ ∃ γ : ℝ → Plane, ∃ θ : Plane → ℝ, + ContDiff ℝ 1 γ ∧ ContinuousOn θ U ∧ + (∀ t, γ t ∈ S ∩ U) ∧ (∀ t, θ (γ t)=t) ∧ + (∀ z ∈ S ∩ U, γ (θ z)=z) ∧ + (∀ t, ∃ d : Plane, HasDerivAt γ d t ∧ d ≠ 0) + +/-- The Gamma theorem: an actual deterministic passage-time limit norm exists +for every positive shape and rate and every iid environment with that law. +Its Frechet differentiability and literal unit-ball boundary charts are +conclusions. No shape theorem, norm, or no-corner hypothesis is supplied. -/ +def GammaDifferentiabilityTarget : Prop := + ∀ (shape rate : ℝ), 0 < shape → 0 < rate → + ∀ (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) + (τ : PlanarFPP.Edge → Ω → ℝ), + GammaEnvironment shape rate P τ → + ∃ μ : Plane → ℝ, + TimeConstantNorm μ ∧ IsTimeConstant P τ μ ∧ + DifferentiableAwayFromOrigin μ ∧ + ∀ v ∈ frontier {z : Plane | μ z ≤ 1}, + HasC1CurveChart (frontier {z : Plane | μ z ≤ 1}) v + +theorem gamma_differentiability : GammaDifferentiabilityTarget := by + sorry + +end GammaFPP + +end OAI diff --git a/tasks/gamma-passage/tests/grade.py b/tasks/gamma-passage/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gamma-passage/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gamma-passage/tests/task.json b/tasks/gamma-passage/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fb8c3f6a4bc4bd54106d7f653a69a96395076e2c --- /dev/null +++ b/tasks/gamma-passage/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GammaPassage", + "comparator": { + "theorem_names": [ + "OAI.GammaFPP.gamma_differentiability" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11652 +} \ No newline at end of file diff --git a/tasks/gamma-passage/tests/test.sh b/tasks/gamma-passage/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gamma-passage/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gaussian-finite-entropy/environment/Dockerfile b/tasks/gaussian-finite-entropy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gaussian-finite-entropy/environment/fetch_mathlib.sh b/tasks/gaussian-finite-entropy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gaussian-finite-entropy/environment/lake-manifest.json b/tasks/gaussian-finite-entropy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gaussian-finite-entropy/environment/lakefile.lean b/tasks/gaussian-finite-entropy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gaussian-finite-entropy/environment/lean_setup.sh b/tasks/gaussian-finite-entropy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gaussian-finite-entropy/environment/pack_submission.py b/tasks/gaussian-finite-entropy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gaussian-finite-entropy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gaussian-finite-entropy/instruction.md b/tasks/gaussian-finite-entropy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..70a2841e9a2d0a260fd837b4b898c72c86dcc816 --- /dev/null +++ b/tasks/gaussian-finite-entropy/instruction.md @@ -0,0 +1,256 @@ +# openai/math challenge `GaussianFiniteEntropy` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `GaussianFiniteEntropy`, also at `/opt/openai-math/challenges/GaussianFiniteEntropy.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set +open scoped BigOperators ENNReal + +namespace RepeatedLocalization + +abbrev Coordinate (n : ℕ) := Fin n → ℝ +abbrev GaussianBlock (n : ℕ) := Fin (n / 16) → Fin (n + 1) → ℝ +abbrev Label (n : ℕ) := Fin (n / 16) → ℝ +abbrev History (N t : ℕ) := Fin t → Fin N +abbrev Cell (n : ℕ) := Σ J : ℕ, Fin n → Fin (2 ^ J) + +instance cellMeasurableSpace (n : ℕ) : MeasurableSpace (Cell n) := ⊤ + +noncomputable def initialCube (n : ℕ) : Set (Coordinate n) := + Set.pi Set.univ (fun _ => Set.Ico (-1 / (2 * Real.sqrt n)) (1 / (2 * Real.sqrt n))) + +noncomputable def cubePrior (n : ℕ) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (initialCube n) + +noncomputable def chart {n : ℕ} (z : Coordinate n) : Fin (n + 1) → ℝ := + Fin.lastCases (Real.sqrt (1 - ∑ a, (z a) ^ 2)) z + +noncomputable def cellSet {n : ℕ} (Q : Cell n) : Set (Coordinate n) := + {z | ∀ a, -1 / (2 * Real.sqrt n) + (Q.2 a : ℝ) / (Real.sqrt n * (2 : ℝ) ^ Q.1) ≤ z a ∧ + z a < -1 / (2 * Real.sqrt n) + ((Q.2 a : ℝ) + 1) / (Real.sqrt n * (2 : ℝ) ^ Q.1)} + +def rootCell (n : ℕ) : Cell n := ⟨0, fun _ => 0⟩ + +noncomputable def gaussianBlockLaw (n : ℕ) : Measure (GaussianBlock n) := + Measure.pi (fun _ => Measure.pi (fun _ => gaussianReal 0 1)) + +noncomputable def exactLabel {n : ℕ} (X : GaussianBlock n) (z : Coordinate n) : Label n := + fun row => ∑ a, X row a * chart z a + +structure BlockRule (n N : ℕ) where + prob : (GaussianBlock n × Label n) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun data => prob data w) + nonneg : ∀ data w, 0 ≤ prob data w + sum_one : ∀ data, ∑ w, prob data w = 1 + +abbrev Rules (n N t : ℕ) := ∀ i : Fin t, History N i.val → BlockRule n N + +def past {N t : ℕ} (w : History N t) (i : Fin t) : History N i.val := + fun j => w ⟨j.val, Nat.lt_trans j.isLt i.isLt⟩ + +def through {N t : ℕ} (w : History N t) (i : Fin t) : History N (i.val + 1) := + fun j => w ⟨j.val, Nat.lt_of_lt_of_le j.isLt i.isLt⟩ + +noncomputable def blockProbability {n N : ℕ} (rule : BlockRule n N) + (z : Coordinate n) (w : Fin N) : ℝ := + ∫ X, rule.prob (X, exactLabel X z) w ∂gaussianBlockLaw n + +noncomputable def historyLikelihood {n N t : ℕ} (rules : Rules n N t) + (z : Coordinate n) (w : History N t) : ℝ := + ∏ i, blockProbability (rules i (past w i)) z (w i) + +noncomputable def experimentLaw {n N t : ℕ} (rules : Rules n N t) : + Measure (Coordinate n × History N t) := + ∑ w : History N t, + ((cubePrior n).withDensity (fun z => ENNReal.ofReal (historyLikelihood rules z w))).map + (fun z => (z, w)) + +abbrev Disclosure (n N t : ℕ) := ∀ i : Fin t, Coordinate n → History N (i.val + 1) → Cell n + +def ValidDisclosure {n N t : ℕ} (Q : Disclosure n N t) : Prop := + (∀ i, Measurable (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)) ∧ + (∀ i, (Set.range (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)).Finite) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i, + z ∈ cellSet (Q i z (through w i)) ∧ cellSet (Q i z (through w i)) ⊆ initialCube n) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i j : Fin t, i ≤ j → + cellSet (Q j z (through w j)) ⊆ cellSet (Q i z (through w i))) + +noncomputable def transcriptMap {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : Coordinate n × (History N t × (Fin t → Cell n)) := + (zw.1, (zw.2, fun i => Q i zw.1 (through zw.2 i))) + +noncomputable def augmentedLaw {n N t : ℕ} (rules : Rules n N t) (Q : Disclosure n N t) := + (experimentLaw rules).map (transcriptMap Q) + +noncomputable def mutualInformation {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] + (μ : Measure (α × β)) : ℝ≥0∞ := + InformationTheory.klDiv μ ((μ.map Prod.fst).prod (μ.map Prod.snd)) + +noncomputable def finalLevel {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : ℕ := + if ht : 0 < t then + let i : Fin t := ⟨t - 1, by omega⟩ + (Q i zw.1 (through zw.2 i)).1 + else 0 + +def MainStatement : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ n₀ : ℕ, ∀ C₀ : ℝ, 0 < C₀ → + ∃ C : ℝ, 0 < C ∧ ∀ (n N t : ℕ), n₀ ≤ n → 1 ≤ N → ∀ rules : Rules n N t, + (2 / (n / 8 : ℕ) + Real.exp (-c * (n / 16 : ℕ))) * Real.log N ≤ C₀ * (n + 1) → + ∃ Q : Disclosure n N t, ValidDisclosure Q ∧ + mutualInformation (augmentedLaw rules Q) ≤ ENNReal.ofReal (C * (n + 1) * t) ∧ + (∫ zw, (finalLevel Q zw : ℝ) ∂experimentLaw rules) ≤ C * t + +namespace FiniteEntropy + +noncomputable def uniformCell {n : ℕ} (Q : Cell n) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (cellSet Q) + +def Descendant {n : ℕ} (Q R : Cell n) : Prop := + Q.1 ≤ R.1 ∧ cellSet R ⊆ cellSet Q + +noncomputable def threshold (n h : ℕ) : ℝ := (2:ℝ)^(-(n:ℝ)*h/2) + +def Heavy {n : ℕ} (P : Measure (Coordinate n)) (Q R : Cell n) : Prop := + Descendant Q R ∧ Q.1 < R.1 ∧ threshold n (R.1-Q.1) < (P (cellSet R)).toReal + +def FirstHeavy {n : ℕ} (P : Measure (Coordinate n)) (Q R : Cell n) : Prop := + Heavy P Q R ∧ ∀ E : Cell n, Heavy P Q E → Descendant E R → E = R + +noncomputable def residual {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Set (Coordinate n) := + cellSet Q \ ⋃ R : {R : Cell n // FirstHeavy P Q R}, cellSet R.val + +abbrev Letter (n : ℕ) := Option (Cell n) +abbrev Log (n : ℕ) := List (Letter n) +instance logMeasurableSpace (n : ℕ) : MeasurableSpace (Log n) := ⊤ + +noncomputable def branch {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Letter n → Set (Coordinate n) := by + classical + exact fun + | none => residual P Q + | some R => if FirstHeavy P Q R then cellSet R else ∅ + +noncomputable def attemptLetter {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) + (z : Coordinate n) : Letter n := by + classical + exact if h : ∃ R : Cell n, FirstHeavy P Q R ∧ z ∈ cellSet R then some h.choose else none + +structure State (n : ℕ) where + cell : Cell n + event : Set (Coordinate n) + stopped : Bool + +noncomputable def update {n : ℕ} (P : Measure (Coordinate n)) (s : State n) (a : Letter n) : State n := + if s.stopped then s else + let μ := ProbabilityTheory.cond P s.event + let E := branch μ s.cell a + { cell := a.getD s.cell + event := s.event ∩ E + stopped := if a = none then decide ((1/2:ℝ) ≤ (μ E).toReal) else false } + +noncomputable def state {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : State n := + h.foldl (update P) ⟨Q,cellSet Q,false⟩ + +noncomputable def run {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : ℕ → Coordinate n → Log n + | 0, _ => [] + | N+1, z => + let h := run P Q N z + let s := state P Q h + if s.stopped then h else + h ++ [attemptLetter (ProbabilityTheory.cond P s.event) s.cell z] + +def Terminates {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : Prop := + ∃ N, (state P Q (run P Q N z)).stopped = true + +noncomputable def attempts {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : ℕ := by + classical + exact if h : Terminates P Q z then Nat.find h else 0 + +noncomputable def terminalLog {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : Log n := + run P Q (attempts P Q z) z + +noncomputable def terminalCell {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : Cell n := + (state P Q h).cell + +noncomputable def terminalLaw {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : Measure (Coordinate n) := + ProbabilityTheory.cond P {z | terminalLog P Q z = h} + +noncomputable def depth {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : ℕ := + (terminalCell P Q (terminalLog P Q z)).1-Q.1 + +def Regular {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Prop := + P (cellSet Q) = 1 ∧ ∀ R : Cell n, Descendant Q R → Q.1 < R.1 → + (P (cellSet R)).toReal ≤ 2 * threshold n (R.1-Q.1) + +def FiniteEntropyStatement : Prop := + ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → ∀ Q : Cell n, ∀ P : Measure (Coordinate n), + IsProbabilityMeasure P → P ≪ uniformCell Q → InformationTheory.klDiv P (uniformCell Q) ≠ ∞ → + (∀ᵐ z ∂P, Terminates P Q z) ∧ Measurable (terminalLog P Q) ∧ + (∀ h : Log n, P {z | terminalLog P Q z = h} ≠ 0 → + Descendant Q (terminalCell P Q h) ∧ Regular (terminalLaw P Q h) (terminalCell P Q h)) ∧ + Integrable (fun z => (depth P Q z : ℝ)) P ∧ + Integrable (fun z => (attempts P Q z : ℝ)) P ∧ + (∫ z,(attempts P Q z : ℝ) ∂P) ≤ 2*(1+∫ z,(depth P Q z : ℝ) ∂P) ∧ + (∫⁻ z,InformationTheory.klDiv (terminalLaw P Q (terminalLog P Q z)) + (uniformCell (terminalCell P Q (terminalLog P Q z))) ∂P) + + ENNReal.ofReal ((Real.log 2/4)*n*(∫ z,(depth P Q z : ℝ) ∂P)) ≤ + InformationTheory.klDiv P (uniformCell Q) + ENNReal.ofReal (2/Real.exp 1) + +theorem finite_expected_regularization : FiniteEntropyStatement := by + sorry + +end FiniteEntropy + +end RepeatedLocalization + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GaussianFiniteEntropy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RepeatedLocalization.FiniteEntropy.finite_expected_regularization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gaussian-finite-entropy/solution/closure.txt b/tasks/gaussian-finite-entropy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9e1d33417f4e45e8f1b20fca2cae98a3779814c0 --- /dev/null +++ b/tasks/gaussian-finite-entropy/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.Probability.Localization.Cells +OAI.Probability.Localization.ConditionalLaws +OAI.Probability.Localization.CountableIntegrals +OAI.Probability.Localization.EntropyBudget +OAI.Probability.Localization.EntropyChain +OAI.Probability.Localization.Experiment +OAI.Probability.Localization.FirstHeavy +OAI.Probability.Localization.History +OAI.Probability.Localization.Main +OAI.Probability.Localization.Model +OAI.Probability.Localization.RewardBounds +OAI.Probability.Localization.Rewards +OAI.Probability.Localization.TerminalBudget +OAI.Probability.Localization.Termination +OAI.Probability.Localization.TruncatedBounds diff --git a/tasks/gaussian-finite-entropy/solution/reference.py b/tasks/gaussian-finite-entropy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gaussian-finite-entropy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gaussian-finite-entropy/solution/solve.sh b/tasks/gaussian-finite-entropy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1aa8c7ceea7ce2c59524379bc03612fb34cb9556 --- /dev/null +++ b/tasks/gaussian-finite-entropy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GaussianFiniteEntropy, i.e. module OAI.Probability.Localization.Main and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Localization.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GaussianFiniteEntropy" diff --git a/tasks/gaussian-finite-entropy/task.toml b/tasks/gaussian-finite-entropy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a4ee2171268f558e39bd3d8f4159460554a5416 --- /dev/null +++ b/tasks/gaussian-finite-entropy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gaussian-finite-entropy" +version = "1.0.0" +description = "Prove GaussianFiniteEntropy (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GaussianFiniteEntropy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GaussianFiniteEntropy" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.RepeatedLocalization.FiniteEntropy.finite_expected_regularization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Localization.Main" +reference_modules = 15 +reference_lean_bytes = 116875 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 870 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11805 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gaussian-finite-entropy/tests/Challenge.lean b/tasks/gaussian-finite-entropy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ad8a3f5e4aefdc97908deeacd5bdddd3745344a0 --- /dev/null +++ b/tasks/gaussian-finite-entropy/tests/Challenge.lean @@ -0,0 +1,205 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set +open scoped BigOperators ENNReal + +namespace RepeatedLocalization + +abbrev Coordinate (n : ℕ) := Fin n → ℝ +abbrev GaussianBlock (n : ℕ) := Fin (n / 16) → Fin (n + 1) → ℝ +abbrev Label (n : ℕ) := Fin (n / 16) → ℝ +abbrev History (N t : ℕ) := Fin t → Fin N +abbrev Cell (n : ℕ) := Σ J : ℕ, Fin n → Fin (2 ^ J) + +instance cellMeasurableSpace (n : ℕ) : MeasurableSpace (Cell n) := ⊤ + +noncomputable def initialCube (n : ℕ) : Set (Coordinate n) := + Set.pi Set.univ (fun _ => Set.Ico (-1 / (2 * Real.sqrt n)) (1 / (2 * Real.sqrt n))) + +noncomputable def cubePrior (n : ℕ) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (initialCube n) + +noncomputable def chart {n : ℕ} (z : Coordinate n) : Fin (n + 1) → ℝ := + Fin.lastCases (Real.sqrt (1 - ∑ a, (z a) ^ 2)) z + +noncomputable def cellSet {n : ℕ} (Q : Cell n) : Set (Coordinate n) := + {z | ∀ a, -1 / (2 * Real.sqrt n) + (Q.2 a : ℝ) / (Real.sqrt n * (2 : ℝ) ^ Q.1) ≤ z a ∧ + z a < -1 / (2 * Real.sqrt n) + ((Q.2 a : ℝ) + 1) / (Real.sqrt n * (2 : ℝ) ^ Q.1)} + +def rootCell (n : ℕ) : Cell n := ⟨0, fun _ => 0⟩ + +noncomputable def gaussianBlockLaw (n : ℕ) : Measure (GaussianBlock n) := + Measure.pi (fun _ => Measure.pi (fun _ => gaussianReal 0 1)) + +noncomputable def exactLabel {n : ℕ} (X : GaussianBlock n) (z : Coordinate n) : Label n := + fun row => ∑ a, X row a * chart z a + +structure BlockRule (n N : ℕ) where + prob : (GaussianBlock n × Label n) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun data => prob data w) + nonneg : ∀ data w, 0 ≤ prob data w + sum_one : ∀ data, ∑ w, prob data w = 1 + +abbrev Rules (n N t : ℕ) := ∀ i : Fin t, History N i.val → BlockRule n N + +def past {N t : ℕ} (w : History N t) (i : Fin t) : History N i.val := + fun j => w ⟨j.val, Nat.lt_trans j.isLt i.isLt⟩ + +def through {N t : ℕ} (w : History N t) (i : Fin t) : History N (i.val + 1) := + fun j => w ⟨j.val, Nat.lt_of_lt_of_le j.isLt i.isLt⟩ + +noncomputable def blockProbability {n N : ℕ} (rule : BlockRule n N) + (z : Coordinate n) (w : Fin N) : ℝ := + ∫ X, rule.prob (X, exactLabel X z) w ∂gaussianBlockLaw n + +noncomputable def historyLikelihood {n N t : ℕ} (rules : Rules n N t) + (z : Coordinate n) (w : History N t) : ℝ := + ∏ i, blockProbability (rules i (past w i)) z (w i) + +noncomputable def experimentLaw {n N t : ℕ} (rules : Rules n N t) : + Measure (Coordinate n × History N t) := + ∑ w : History N t, + ((cubePrior n).withDensity (fun z => ENNReal.ofReal (historyLikelihood rules z w))).map + (fun z => (z, w)) + +abbrev Disclosure (n N t : ℕ) := ∀ i : Fin t, Coordinate n → History N (i.val + 1) → Cell n + +def ValidDisclosure {n N t : ℕ} (Q : Disclosure n N t) : Prop := + (∀ i, Measurable (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)) ∧ + (∀ i, (Set.range (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)).Finite) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i, + z ∈ cellSet (Q i z (through w i)) ∧ cellSet (Q i z (through w i)) ⊆ initialCube n) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i j : Fin t, i ≤ j → + cellSet (Q j z (through w j)) ⊆ cellSet (Q i z (through w i))) + +noncomputable def transcriptMap {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : Coordinate n × (History N t × (Fin t → Cell n)) := + (zw.1, (zw.2, fun i => Q i zw.1 (through zw.2 i))) + +noncomputable def augmentedLaw {n N t : ℕ} (rules : Rules n N t) (Q : Disclosure n N t) := + (experimentLaw rules).map (transcriptMap Q) + +noncomputable def mutualInformation {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] + (μ : Measure (α × β)) : ℝ≥0∞ := + InformationTheory.klDiv μ ((μ.map Prod.fst).prod (μ.map Prod.snd)) + +noncomputable def finalLevel {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : ℕ := + if ht : 0 < t then + let i : Fin t := ⟨t - 1, by omega⟩ + (Q i zw.1 (through zw.2 i)).1 + else 0 + +def MainStatement : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ n₀ : ℕ, ∀ C₀ : ℝ, 0 < C₀ → + ∃ C : ℝ, 0 < C ∧ ∀ (n N t : ℕ), n₀ ≤ n → 1 ≤ N → ∀ rules : Rules n N t, + (2 / (n / 8 : ℕ) + Real.exp (-c * (n / 16 : ℕ))) * Real.log N ≤ C₀ * (n + 1) → + ∃ Q : Disclosure n N t, ValidDisclosure Q ∧ + mutualInformation (augmentedLaw rules Q) ≤ ENNReal.ofReal (C * (n + 1) * t) ∧ + (∫ zw, (finalLevel Q zw : ℝ) ∂experimentLaw rules) ≤ C * t + +namespace FiniteEntropy + +noncomputable def uniformCell {n : ℕ} (Q : Cell n) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (cellSet Q) + +def Descendant {n : ℕ} (Q R : Cell n) : Prop := + Q.1 ≤ R.1 ∧ cellSet R ⊆ cellSet Q + +noncomputable def threshold (n h : ℕ) : ℝ := (2:ℝ)^(-(n:ℝ)*h/2) + +def Heavy {n : ℕ} (P : Measure (Coordinate n)) (Q R : Cell n) : Prop := + Descendant Q R ∧ Q.1 < R.1 ∧ threshold n (R.1-Q.1) < (P (cellSet R)).toReal + +def FirstHeavy {n : ℕ} (P : Measure (Coordinate n)) (Q R : Cell n) : Prop := + Heavy P Q R ∧ ∀ E : Cell n, Heavy P Q E → Descendant E R → E = R + +noncomputable def residual {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Set (Coordinate n) := + cellSet Q \ ⋃ R : {R : Cell n // FirstHeavy P Q R}, cellSet R.val + +abbrev Letter (n : ℕ) := Option (Cell n) +abbrev Log (n : ℕ) := List (Letter n) +instance logMeasurableSpace (n : ℕ) : MeasurableSpace (Log n) := ⊤ + +noncomputable def branch {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Letter n → Set (Coordinate n) := by + classical + exact fun + | none => residual P Q + | some R => if FirstHeavy P Q R then cellSet R else ∅ + +noncomputable def attemptLetter {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) + (z : Coordinate n) : Letter n := by + classical + exact if h : ∃ R : Cell n, FirstHeavy P Q R ∧ z ∈ cellSet R then some h.choose else none + +structure State (n : ℕ) where + cell : Cell n + event : Set (Coordinate n) + stopped : Bool + +noncomputable def update {n : ℕ} (P : Measure (Coordinate n)) (s : State n) (a : Letter n) : State n := + if s.stopped then s else + let μ := ProbabilityTheory.cond P s.event + let E := branch μ s.cell a + { cell := a.getD s.cell + event := s.event ∩ E + stopped := if a = none then decide ((1/2:ℝ) ≤ (μ E).toReal) else false } + +noncomputable def state {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : State n := + h.foldl (update P) ⟨Q,cellSet Q,false⟩ + +noncomputable def run {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : ℕ → Coordinate n → Log n + | 0, _ => [] + | N+1, z => + let h := run P Q N z + let s := state P Q h + if s.stopped then h else + h ++ [attemptLetter (ProbabilityTheory.cond P s.event) s.cell z] + +def Terminates {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : Prop := + ∃ N, (state P Q (run P Q N z)).stopped = true + +noncomputable def attempts {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : ℕ := by + classical + exact if h : Terminates P Q z then Nat.find h else 0 + +noncomputable def terminalLog {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : Log n := + run P Q (attempts P Q z) z + +noncomputable def terminalCell {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : Cell n := + (state P Q h).cell + +noncomputable def terminalLaw {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (h : Log n) : Measure (Coordinate n) := + ProbabilityTheory.cond P {z | terminalLog P Q z = h} + +noncomputable def depth {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) (z : Coordinate n) : ℕ := + (terminalCell P Q (terminalLog P Q z)).1-Q.1 + +def Regular {n : ℕ} (P : Measure (Coordinate n)) (Q : Cell n) : Prop := + P (cellSet Q) = 1 ∧ ∀ R : Cell n, Descendant Q R → Q.1 < R.1 → + (P (cellSet R)).toReal ≤ 2 * threshold n (R.1-Q.1) + +def FiniteEntropyStatement : Prop := + ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → ∀ Q : Cell n, ∀ P : Measure (Coordinate n), + IsProbabilityMeasure P → P ≪ uniformCell Q → InformationTheory.klDiv P (uniformCell Q) ≠ ∞ → + (∀ᵐ z ∂P, Terminates P Q z) ∧ Measurable (terminalLog P Q) ∧ + (∀ h : Log n, P {z | terminalLog P Q z = h} ≠ 0 → + Descendant Q (terminalCell P Q h) ∧ Regular (terminalLaw P Q h) (terminalCell P Q h)) ∧ + Integrable (fun z => (depth P Q z : ℝ)) P ∧ + Integrable (fun z => (attempts P Q z : ℝ)) P ∧ + (∫ z,(attempts P Q z : ℝ) ∂P) ≤ 2*(1+∫ z,(depth P Q z : ℝ) ∂P) ∧ + (∫⁻ z,InformationTheory.klDiv (terminalLaw P Q (terminalLog P Q z)) + (uniformCell (terminalCell P Q (terminalLog P Q z))) ∂P) + + ENNReal.ofReal ((Real.log 2/4)*n*(∫ z,(depth P Q z : ℝ) ∂P)) ≤ + InformationTheory.klDiv P (uniformCell Q) + ENNReal.ofReal (2/Real.exp 1) + +theorem finite_expected_regularization : FiniteEntropyStatement := by + sorry + +end FiniteEntropy + +end RepeatedLocalization + +end OAI diff --git a/tasks/gaussian-finite-entropy/tests/grade.py b/tasks/gaussian-finite-entropy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gaussian-finite-entropy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gaussian-finite-entropy/tests/task.json b/tasks/gaussian-finite-entropy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0dac5d00e30e8fb73286d776be838fe27dcca822 --- /dev/null +++ b/tasks/gaussian-finite-entropy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GaussianFiniteEntropy", + "comparator": { + "theorem_names": [ + "OAI.RepeatedLocalization.FiniteEntropy.finite_expected_regularization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 10905 +} \ No newline at end of file diff --git a/tasks/gaussian-finite-entropy/tests/test.sh b/tasks/gaussian-finite-entropy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gaussian-finite-entropy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gaussian-information/environment/Dockerfile b/tasks/gaussian-information/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gaussian-information/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gaussian-information/environment/fetch_mathlib.sh b/tasks/gaussian-information/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gaussian-information/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gaussian-information/environment/lake-manifest.json b/tasks/gaussian-information/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gaussian-information/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gaussian-information/environment/lakefile.lean b/tasks/gaussian-information/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gaussian-information/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gaussian-information/environment/lean_setup.sh b/tasks/gaussian-information/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gaussian-information/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gaussian-information/environment/pack_submission.py b/tasks/gaussian-information/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gaussian-information/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gaussian-information/instruction.md b/tasks/gaussian-information/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6bc222bad9652271c6023c8f60b22ad334b9a395 --- /dev/null +++ b/tasks/gaussian-information/instruction.md @@ -0,0 +1,255 @@ +# openai/math challenge `GaussianInformation` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `GaussianInformation`, also at `/opt/openai-math/challenges/GaussianInformation.lean`: + +```lean +import Mathlib + +namespace OAI + + +open MeasureTheory ProbabilityTheory Set +open scoped BigOperators ENNReal + +namespace RepeatedLocalization + +abbrev Coordinate (n : ℕ) := Fin n → ℝ +abbrev GaussianBlock (n : ℕ) := Fin (n / 16) → Fin (n + 1) → ℝ +abbrev Label (n : ℕ) := Fin (n / 16) → ℝ +abbrev History (N t : ℕ) := Fin t → Fin N +abbrev Cell (n : ℕ) := Σ J : ℕ, Fin n → Fin (2 ^ J) + +instance cellMeasurableSpace (n : ℕ) : MeasurableSpace (Cell n) := ⊤ + +noncomputable def initialCube (n : ℕ) : Set (Coordinate n) := + Set.pi Set.univ (fun _ => Set.Ico (-1 / (2 * Real.sqrt n)) (1 / (2 * Real.sqrt n))) + +noncomputable def cubePrior (n : ℕ) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (initialCube n) + +noncomputable def chart {n : ℕ} (z : Coordinate n) : Fin (n + 1) → ℝ := + Fin.lastCases (Real.sqrt (1 - ∑ a, (z a) ^ 2)) z + +noncomputable def cellSet {n : ℕ} (Q : Cell n) : Set (Coordinate n) := + {z | ∀ a, -1 / (2 * Real.sqrt n) + (Q.2 a : ℝ) / (Real.sqrt n * (2 : ℝ) ^ Q.1) ≤ z a ∧ + z a < -1 / (2 * Real.sqrt n) + ((Q.2 a : ℝ) + 1) / (Real.sqrt n * (2 : ℝ) ^ Q.1)} + +def rootCell (n : ℕ) : Cell n := ⟨0, fun _ => 0⟩ + +noncomputable def gaussianBlockLaw (n : ℕ) : Measure (GaussianBlock n) := + Measure.pi (fun _ => Measure.pi (fun _ => gaussianReal 0 1)) + +noncomputable def exactLabel {n : ℕ} (X : GaussianBlock n) (z : Coordinate n) : Label n := + fun row => ∑ a, X row a * chart z a + +structure BlockRule (n N : ℕ) where + prob : (GaussianBlock n × Label n) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun data => prob data w) + nonneg : ∀ data w, 0 ≤ prob data w + sum_one : ∀ data, ∑ w, prob data w = 1 + +abbrev Rules (n N t : ℕ) := ∀ i : Fin t, History N i.val → BlockRule n N + +def past {N t : ℕ} (w : History N t) (i : Fin t) : History N i.val := + fun j => w ⟨j.val, Nat.lt_trans j.isLt i.isLt⟩ + +def through {N t : ℕ} (w : History N t) (i : Fin t) : History N (i.val + 1) := + fun j => w ⟨j.val, Nat.lt_of_lt_of_le j.isLt i.isLt⟩ + +noncomputable def blockProbability {n N : ℕ} (rule : BlockRule n N) + (z : Coordinate n) (w : Fin N) : ℝ := + ∫ X, rule.prob (X, exactLabel X z) w ∂gaussianBlockLaw n + +noncomputable def historyLikelihood {n N t : ℕ} (rules : Rules n N t) + (z : Coordinate n) (w : History N t) : ℝ := + ∏ i, blockProbability (rules i (past w i)) z (w i) + +noncomputable def experimentLaw {n N t : ℕ} (rules : Rules n N t) : + Measure (Coordinate n × History N t) := + ∑ w : History N t, + ((cubePrior n).withDensity (fun z => ENNReal.ofReal (historyLikelihood rules z w))).map + (fun z => (z, w)) + +abbrev Disclosure (n N t : ℕ) := ∀ i : Fin t, Coordinate n → History N (i.val + 1) → Cell n + +def ValidDisclosure {n N t : ℕ} (Q : Disclosure n N t) : Prop := + (∀ i, Measurable (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)) ∧ + (∀ i, (Set.range (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)).Finite) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i, + z ∈ cellSet (Q i z (through w i)) ∧ cellSet (Q i z (through w i)) ⊆ initialCube n) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i j : Fin t, i ≤ j → + cellSet (Q j z (through w j)) ⊆ cellSet (Q i z (through w i))) + +noncomputable def transcriptMap {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : Coordinate n × (History N t × (Fin t → Cell n)) := + (zw.1, (zw.2, fun i => Q i zw.1 (through zw.2 i))) + +noncomputable def augmentedLaw {n N t : ℕ} (rules : Rules n N t) (Q : Disclosure n N t) := + (experimentLaw rules).map (transcriptMap Q) + +noncomputable def mutualInformation {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] + (μ : Measure (α × β)) : ℝ≥0∞ := + InformationTheory.klDiv μ ((μ.map Prod.fst).prod (μ.map Prod.snd)) + +noncomputable def finalLevel {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : ℕ := + if ht : 0 < t then + let i : Fin t := ⟨t - 1, by omega⟩ + (Q i zw.1 (through zw.2 i)).1 + else 0 + +def MainStatement : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ n₀ : ℕ, ∀ C₀ : ℝ, 0 < C₀ → + ∃ C : ℝ, 0 < C ∧ ∀ (n N t : ℕ), n₀ ≤ n → 1 ≤ N → ∀ rules : Rules n N t, + (2 / (n / 8 : ℕ) + Real.exp (-c * (n / 16 : ℕ))) * Real.log N ≤ C₀ * (n + 1) → + ∃ Q : Disclosure n N t, ValidDisclosure Q ∧ + mutualInformation (augmentedLaw rules Q) ≤ ENNReal.ofReal (C * (n + 1) * t) ∧ + (∫ zw, (finalLevel Q zw : ℝ) ∂experimentLaw rules) ≤ C * t + +theorem repeated_localization : MainStatement := by + sorry + +end RepeatedLocalization + + +open MeasureTheory Metric +open scoped ENNReal +namespace AllScaleInverseVolume +local instance namedAtLeastTwoTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev Ambient (d : ℕ) := EuclideanSpace ℝ (Fin d) + +noncomputable local instance ambientSub (d : ℕ) : Sub (Ambient d) where + sub vector other := WithLp.toLp (2 : ℝ≥0∞) + (WithLp.ofLp (p := (2 : ℝ≥0∞)) vector - WithLp.ofLp (p := (2 : ℝ≥0∞)) other) + +noncomputable local instance ambientInner (d : ℕ) : Inner ℝ (Ambient d) where + inner vector other := ∑ coordinate : Fin d, + inner ℝ (WithLp.ofLp (p := (2 : ℝ≥0∞)) vector coordinate) + (WithLp.ofLp (p := (2 : ℝ≥0∞)) other coordinate) + +noncomputable def gramVolume {d k : ℕ} (u : Ambient d) (z : Fin k → Ambient d) : ℝ := + Real.sqrt (Matrix.gram ℝ (fun i => z i-u)).det +noncomputable def inverseVolume {d : ℕ} (u : Ambient d) (z : Fin (d/100) → Ambient d) : ℝ≥0∞ := + ((ENNReal.ofReal (gramVolume u z))⁻¹)^(d/100) +def BallBound {d : ℕ} (ν : Measure (Ambient d)) : Prop := + ∀ (x : Ambient d) (r : ℝ), 0 < r → + ν (ball x r) ≤ ENNReal.ofReal (r^(((d:ℝ)-1)/2)) +def InverseVolumeStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ ν : Measure (Ambient d), IsProbabilityMeasure ν → BallBound ν → + ∀ u : Ambient d, (∫⁻ z,inverseVolume u z ∂Measure.pi (fun _ : Fin (d/100) => ν)) ≤ + ENNReal.ofReal (Real.exp (C*d*(d/100:ℕ))) +theorem inverse_volume_without_support : InverseVolumeStatement := by + sorry +end AllScaleInverseVolume + + +open MeasureTheory ProbabilityTheory Metric Set +open scoped ENNReal +namespace KernelPotential +local instance namedAtLeastTwoTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev Ambient (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Rows (d : ℕ) := Fin (d/16) → Fin d → ℝ +noncomputable def radial {d : ℕ} (x : Ambient d) : Ambient d := ‖x‖⁻¹ • x +noncomputable def sphereProbability (d : ℕ) : Measure (Ambient d) := + ((volume (ball (0 : Ambient d) 1))⁻¹ • volume.restrict (ball (0 : Ambient d) 1)).map radial +noncomputable def J {d : ℕ} (ν : Measure (Ambient d)) (s : Ambient d) : ℝ≥0∞ := + ∫⁻ u,((ENNReal.ofReal ‖u-s‖)⁻¹)^(2*(d/16)) ∂ν +noncomputable def B {d : ℕ} (ν : Measure (Ambient d)) : ℝ := + ∫ s, Real.log ((J ν s).toReal) ∂ν +noncomputable def Phi {d : ℕ} (ν : Measure (Ambient d)) : ℝ := + (InformationTheory.klDiv ν (sphereProbability d)).toReal - B ν + +def BoundedDensity {d : ℕ} (ν : Measure (Ambient d)) : Prop := + ∃ H : ℝ, 0 < H ∧ ν ≤ ENNReal.ofReal H • sphereProbability d + +noncomputable def rowLaw (d : ℕ) : Measure (Rows d) := + Measure.pi (fun _ : Fin (d/16) => Measure.pi (fun _ : Fin d => gaussianReal 0 1)) +noncomputable def labels {d : ℕ} (a : Rows d) (s : Ambient d) : Fin (d/16) → ℝ := + fun i => ∑ j,a i j*s j +structure BlockRule (d N : ℕ) where + prob : (Fin N × (Rows d × (Fin (d/16) → ℝ))) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun x => prob x w) + nonneg_prob : ∀ x w, 0 ≤ prob x w + sum_prob : ∀ x, ∑ w,prob x w=1 + +noncomputable def outgoingLaw {d N : ℕ} (μ : Measure (Ambient d × Fin N)) + (rule : BlockRule d N) : Measure (Ambient d × Fin N) := + ∑ w : Fin N, ((μ.prod (rowLaw d)).withDensity (fun x => + ENNReal.ofReal (rule.prob (x.1.2,x.2,labels x.2 x.1.1) w))).map (fun x => (x.1.1,w)) +noncomputable def component {d N : ℕ} (μ : Measure (Ambient d × Fin N)) (v : Fin N) : + Measure (Ambient d) := (μ.restrict {x|x.2=v}).map Prod.fst +noncomputable def posterior {d N : ℕ} (μ : Measure (Ambient d × Fin N)) (v : Fin N) : + Measure (Ambient d) := (component μ v univ)⁻¹ • component μ v +noncomputable def averagePhi {d N : ℕ} (μ : Measure (Ambient d × Fin N)) : ℝ := + ∑ v : Fin N, (component μ v univ).toReal * Phi (posterior μ v) + +def CoercivityStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ ν : Measure (Ambient d), IsProbabilityMeasure ν → BoundedDensity ν → + (1/2:ℝ)*(InformationTheory.klDiv ν (sphereProbability d)).toReal-C*d ≤ Phi ν) ∧ + Phi (sphereProbability d) ≤ (2*(d/16):ℕ)*Real.log 2 ∧ + (∀ (q : ℕ) (w : Fin q → ℝ), (∀ i,0 ≤ w i) → (∑ i,w i)=1 → + ∀ ν : Fin q → Measure (Ambient d), (∀ i,IsProbabilityMeasure (ν i)) → + (∀ i,BoundedDensity (ν i)) → + Phi (∑ i,ENNReal.ofReal (w i) • ν i) ≤ ∑ i,w i*Phi (ν i)) + +def DriftStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ N : ℕ, 1 ≤ N → + Real.log N ≤ (d:ℝ)^2 → ∀ μ : Measure (Ambient d × Fin N), IsProbabilityMeasure μ → + μ.map Prod.fst=sphereProbability d → ∀ rule : BlockRule d N, + averagePhi (outgoingLaw μ rule) ≤ averagePhi μ+C*d + +theorem kernel_coercivity : CoercivityStatement := by sorry +theorem actual_row_drift : DriftStatement := by sorry +end KernelPotential + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GaussianInformation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.RepeatedLocalization.repeated_localization`, `OAI.AllScaleInverseVolume.inverse_volume_without_support`, `OAI.KernelPotential.kernel_coercivity`, `OAI.KernelPotential.actual_row_drift` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gaussian-information/solution/closure.txt b/tasks/gaussian-information/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd396dd2b8bc77ed44199f7073bcaff21f0e36ef --- /dev/null +++ b/tasks/gaussian-information/solution/closure.txt @@ -0,0 +1,111 @@ +OAI.Probability.GaussianInformation.Dyadic.BallVolume +OAI.Probability.GaussianInformation.Dyadic.BlockInformation +OAI.Probability.GaussianInformation.Dyadic.BoxKernels +OAI.Probability.GaussianInformation.Dyadic.ChannelEntropy +OAI.Probability.GaussianInformation.Dyadic.ChannelProducts +OAI.Probability.GaussianInformation.Dyadic.ChartGeometry +OAI.Probability.GaussianInformation.Dyadic.ConditionalMoments +OAI.Probability.GaussianInformation.Dyadic.Covers +OAI.Probability.GaussianInformation.Dyadic.Entropy +OAI.Probability.GaussianInformation.Dyadic.GaussianImages +OAI.Probability.GaussianInformation.Dyadic.GaussianTails +OAI.Probability.GaussianInformation.Dyadic.GramVolume +OAI.Probability.GaussianInformation.Dyadic.GridSpread +OAI.Probability.GaussianInformation.Dyadic.HeavyCells +OAI.Probability.GaussianInformation.Dyadic.History +OAI.Probability.GaussianInformation.Dyadic.LabelBounds +OAI.Probability.GaussianInformation.Dyadic.Main +OAI.Probability.GaussianInformation.Dyadic.MixtureBounds +OAI.Probability.GaussianInformation.Dyadic.PosteriorChannels +OAI.Probability.GaussianInformation.Dyadic.ProjectionMoments +OAI.Probability.GaussianInformation.Dyadic.ProjectionTests +OAI.Probability.GaussianInformation.Dyadic.QuadraticBounds +OAI.Probability.GaussianInformation.Dyadic.Realization +OAI.Probability.GaussianInformation.Dyadic.RealizationStep +OAI.Probability.GaussianInformation.Dyadic.Refinement +OAI.Probability.GaussianInformation.Dyadic.RefinementCost +OAI.Probability.GaussianInformation.Dyadic.ReplicaMoments +OAI.Probability.GaussianInformation.Dyadic.ScoreBounds +OAI.Probability.GaussianInformation.Dyadic.SmallBalls +OAI.Probability.GaussianInformation.Dyadic.StateExpectation +OAI.Probability.GaussianInformation.Dyadic.StateInformation +OAI.Probability.GaussianInformation.Dyadic.TranscriptLaw +OAI.Probability.GaussianInformation.Dyadic.Tubes +OAI.Probability.GaussianInformation.Inverse.ClippedMoments +OAI.Probability.GaussianInformation.Inverse.DyadicBins +OAI.Probability.GaussianInformation.Inverse.Ellipsoids +OAI.Probability.GaussianInformation.Inverse.ExponentBounds +OAI.Probability.GaussianInformation.Inverse.GramVolume +OAI.Probability.GaussianInformation.Inverse.GreedyOrder +OAI.Probability.GaussianInformation.Inverse.InverseMoments +OAI.Probability.GaussianInformation.Inverse.Main +OAI.Probability.GaussianInformation.Inverse.Model +OAI.Probability.GaussianInformation.Inverse.Orthogonal +OAI.Probability.GaussianInformation.Inverse.StageEvents +OAI.Probability.GaussianInformation.Inverse.Tubes +OAI.Probability.GaussianInformation.Kernel.Bayes +OAI.Probability.GaussianInformation.Kernel.BayesContinuity +OAI.Probability.GaussianInformation.Kernel.BayesEnergy +OAI.Probability.GaussianInformation.Kernel.BorelDrift +OAI.Probability.GaussianInformation.Kernel.BoxKernels +OAI.Probability.GaussianInformation.Kernel.Coercivity +OAI.Probability.GaussianInformation.Kernel.Compensation +OAI.Probability.GaussianInformation.Kernel.ConditionalCharge +OAI.Probability.GaussianInformation.Kernel.ContinuousDrift +OAI.Probability.GaussianInformation.Kernel.Covers +OAI.Probability.GaussianInformation.Kernel.DriftCutoff +OAI.Probability.GaussianInformation.Kernel.EnergyBayes +OAI.Probability.GaussianInformation.Kernel.Entropy +OAI.Probability.GaussianInformation.Kernel.EntropyComparison +OAI.Probability.GaussianInformation.Kernel.EntropyDrift +OAI.Probability.GaussianInformation.Kernel.GaussianImages +OAI.Probability.GaussianInformation.Kernel.GaussianReference +OAI.Probability.GaussianInformation.Kernel.GaussianRows +OAI.Probability.GaussianInformation.Kernel.GeneralDrift +OAI.Probability.GaussianInformation.Kernel.GramVolume +OAI.Probability.GaussianInformation.Kernel.JointCompensation +OAI.Probability.GaussianInformation.Kernel.JointEntropy +OAI.Probability.GaussianInformation.Kernel.JointRules +OAI.Probability.GaussianInformation.Kernel.LocalEnergy +OAI.Probability.GaussianInformation.Kernel.LocalRules +OAI.Probability.GaussianInformation.Kernel.Main +OAI.Probability.GaussianInformation.Kernel.MassContinuity +OAI.Probability.GaussianInformation.Kernel.MassPotential +OAI.Probability.GaussianInformation.Kernel.MessageComponents +OAI.Probability.GaussianInformation.Kernel.MixedMoments +OAI.Probability.GaussianInformation.Kernel.MixedProjection +OAI.Probability.GaussianInformation.Kernel.Mixtures +OAI.Probability.GaussianInformation.Kernel.Model +OAI.Probability.GaussianInformation.Kernel.NoiseContinuity +OAI.Probability.GaussianInformation.Kernel.NoiseLaw +OAI.Probability.GaussianInformation.Kernel.NoisyCharge +OAI.Probability.GaussianInformation.Kernel.NoisyMoments +OAI.Probability.GaussianInformation.Kernel.NoisyProjection +OAI.Probability.GaussianInformation.Kernel.NoisyReference +OAI.Probability.GaussianInformation.Kernel.NoisyRules +OAI.Probability.GaussianInformation.Kernel.NoisySums +OAI.Probability.GaussianInformation.Kernel.OutgoingLaws +OAI.Probability.GaussianInformation.Kernel.PairReference +OAI.Probability.GaussianInformation.Kernel.PositiveRules +OAI.Probability.GaussianInformation.Kernel.PotentialContinuity +OAI.Probability.GaussianInformation.Kernel.ProjectionMoments +OAI.Probability.GaussianInformation.Kernel.ReferenceBounds +OAI.Probability.GaussianInformation.Kernel.ReferenceCharge +OAI.Probability.GaussianInformation.Kernel.ReferenceDensity +OAI.Probability.GaussianInformation.Kernel.ReferenceMarginals +OAI.Probability.GaussianInformation.Kernel.ReferenceMoments +OAI.Probability.GaussianInformation.Kernel.ReferenceShift +OAI.Probability.GaussianInformation.Kernel.ReplicaMoments +OAI.Probability.GaussianInformation.Kernel.Reweighting +OAI.Probability.GaussianInformation.Kernel.RowConcatenation +OAI.Probability.GaussianInformation.Kernel.SampleEquivalence +OAI.Probability.GaussianInformation.Kernel.SampleLaw +OAI.Probability.GaussianInformation.Kernel.ScaledReference +OAI.Probability.GaussianInformation.Kernel.Scaling +OAI.Probability.GaussianInformation.Kernel.SimplexApproximation +OAI.Probability.GaussianInformation.Kernel.SmallBalls +OAI.Probability.GaussianInformation.Kernel.Sphere +OAI.Probability.GaussianInformation.Main +OAI.Probability.Localization.Cells +OAI.Probability.Localization.Experiment +OAI.Probability.Localization.Model diff --git a/tasks/gaussian-information/solution/reference.py b/tasks/gaussian-information/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gaussian-information/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gaussian-information/solution/solve.sh b/tasks/gaussian-information/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..945ff956c67571510e81f268ec0df2b5fc96f00b --- /dev/null +++ b/tasks/gaussian-information/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GaussianInformation, i.e. module OAI.Probability.GaussianInformation.Main and the +# 111 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.GaussianInformation.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GaussianInformation" diff --git a/tasks/gaussian-information/task.toml b/tasks/gaussian-information/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4c101a32285efdd6fb766b29560a396d0c45d81c --- /dev/null +++ b/tasks/gaussian-information/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gaussian-information" +version = "1.0.0" +description = "Prove GaussianInformation (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GaussianInformation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GaussianInformation" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.RepeatedLocalization.repeated_localization", "OAI.AllScaleInverseVolume.inverse_volume_without_support", "OAI.KernelPotential.kernel_coercivity", "OAI.KernelPotential.actual_row_drift"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.GaussianInformation.Main" +reference_modules = 111 +reference_lean_bytes = 782263 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1216 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12404 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gaussian-information/tests/Challenge.lean b/tasks/gaussian-information/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..13a121157428c9655083cb192d78cfc503e2174a --- /dev/null +++ b/tasks/gaussian-information/tests/Challenge.lean @@ -0,0 +1,204 @@ +import Mathlib + +namespace OAI + + +open MeasureTheory ProbabilityTheory Set +open scoped BigOperators ENNReal + +namespace RepeatedLocalization + +abbrev Coordinate (n : ℕ) := Fin n → ℝ +abbrev GaussianBlock (n : ℕ) := Fin (n / 16) → Fin (n + 1) → ℝ +abbrev Label (n : ℕ) := Fin (n / 16) → ℝ +abbrev History (N t : ℕ) := Fin t → Fin N +abbrev Cell (n : ℕ) := Σ J : ℕ, Fin n → Fin (2 ^ J) + +instance cellMeasurableSpace (n : ℕ) : MeasurableSpace (Cell n) := ⊤ + +noncomputable def initialCube (n : ℕ) : Set (Coordinate n) := + Set.pi Set.univ (fun _ => Set.Ico (-1 / (2 * Real.sqrt n)) (1 / (2 * Real.sqrt n))) + +noncomputable def cubePrior (n : ℕ) : Measure (Coordinate n) := + ProbabilityTheory.cond volume (initialCube n) + +noncomputable def chart {n : ℕ} (z : Coordinate n) : Fin (n + 1) → ℝ := + Fin.lastCases (Real.sqrt (1 - ∑ a, (z a) ^ 2)) z + +noncomputable def cellSet {n : ℕ} (Q : Cell n) : Set (Coordinate n) := + {z | ∀ a, -1 / (2 * Real.sqrt n) + (Q.2 a : ℝ) / (Real.sqrt n * (2 : ℝ) ^ Q.1) ≤ z a ∧ + z a < -1 / (2 * Real.sqrt n) + ((Q.2 a : ℝ) + 1) / (Real.sqrt n * (2 : ℝ) ^ Q.1)} + +def rootCell (n : ℕ) : Cell n := ⟨0, fun _ => 0⟩ + +noncomputable def gaussianBlockLaw (n : ℕ) : Measure (GaussianBlock n) := + Measure.pi (fun _ => Measure.pi (fun _ => gaussianReal 0 1)) + +noncomputable def exactLabel {n : ℕ} (X : GaussianBlock n) (z : Coordinate n) : Label n := + fun row => ∑ a, X row a * chart z a + +structure BlockRule (n N : ℕ) where + prob : (GaussianBlock n × Label n) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun data => prob data w) + nonneg : ∀ data w, 0 ≤ prob data w + sum_one : ∀ data, ∑ w, prob data w = 1 + +abbrev Rules (n N t : ℕ) := ∀ i : Fin t, History N i.val → BlockRule n N + +def past {N t : ℕ} (w : History N t) (i : Fin t) : History N i.val := + fun j => w ⟨j.val, Nat.lt_trans j.isLt i.isLt⟩ + +def through {N t : ℕ} (w : History N t) (i : Fin t) : History N (i.val + 1) := + fun j => w ⟨j.val, Nat.lt_of_lt_of_le j.isLt i.isLt⟩ + +noncomputable def blockProbability {n N : ℕ} (rule : BlockRule n N) + (z : Coordinate n) (w : Fin N) : ℝ := + ∫ X, rule.prob (X, exactLabel X z) w ∂gaussianBlockLaw n + +noncomputable def historyLikelihood {n N t : ℕ} (rules : Rules n N t) + (z : Coordinate n) (w : History N t) : ℝ := + ∏ i, blockProbability (rules i (past w i)) z (w i) + +noncomputable def experimentLaw {n N t : ℕ} (rules : Rules n N t) : + Measure (Coordinate n × History N t) := + ∑ w : History N t, + ((cubePrior n).withDensity (fun z => ENNReal.ofReal (historyLikelihood rules z w))).map + (fun z => (z, w)) + +abbrev Disclosure (n N t : ℕ) := ∀ i : Fin t, Coordinate n → History N (i.val + 1) → Cell n + +def ValidDisclosure {n N t : ℕ} (Q : Disclosure n N t) : Prop := + (∀ i, Measurable (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)) ∧ + (∀ i, (Set.range (fun zh : Coordinate n × History N (i.val + 1) => Q i zh.1 zh.2)).Finite) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i, + z ∈ cellSet (Q i z (through w i)) ∧ cellSet (Q i z (through w i)) ⊆ initialCube n) ∧ + (∀ z ∈ initialCube n, ∀ w : History N t, ∀ i j : Fin t, i ≤ j → + cellSet (Q j z (through w j)) ⊆ cellSet (Q i z (through w i))) + +noncomputable def transcriptMap {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : Coordinate n × (History N t × (Fin t → Cell n)) := + (zw.1, (zw.2, fun i => Q i zw.1 (through zw.2 i))) + +noncomputable def augmentedLaw {n N t : ℕ} (rules : Rules n N t) (Q : Disclosure n N t) := + (experimentLaw rules).map (transcriptMap Q) + +noncomputable def mutualInformation {α β : Type*} [MeasurableSpace α] [MeasurableSpace β] + (μ : Measure (α × β)) : ℝ≥0∞ := + InformationTheory.klDiv μ ((μ.map Prod.fst).prod (μ.map Prod.snd)) + +noncomputable def finalLevel {n N t : ℕ} (Q : Disclosure n N t) + (zw : Coordinate n × History N t) : ℕ := + if ht : 0 < t then + let i : Fin t := ⟨t - 1, by omega⟩ + (Q i zw.1 (through zw.2 i)).1 + else 0 + +def MainStatement : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ n₀ : ℕ, ∀ C₀ : ℝ, 0 < C₀ → + ∃ C : ℝ, 0 < C ∧ ∀ (n N t : ℕ), n₀ ≤ n → 1 ≤ N → ∀ rules : Rules n N t, + (2 / (n / 8 : ℕ) + Real.exp (-c * (n / 16 : ℕ))) * Real.log N ≤ C₀ * (n + 1) → + ∃ Q : Disclosure n N t, ValidDisclosure Q ∧ + mutualInformation (augmentedLaw rules Q) ≤ ENNReal.ofReal (C * (n + 1) * t) ∧ + (∫ zw, (finalLevel Q zw : ℝ) ∂experimentLaw rules) ≤ C * t + +theorem repeated_localization : MainStatement := by + sorry + +end RepeatedLocalization + + +open MeasureTheory Metric +open scoped ENNReal +namespace AllScaleInverseVolume +local instance namedAtLeastTwoTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev Ambient (d : ℕ) := EuclideanSpace ℝ (Fin d) + +noncomputable local instance ambientSub (d : ℕ) : Sub (Ambient d) where + sub vector other := WithLp.toLp (2 : ℝ≥0∞) + (WithLp.ofLp (p := (2 : ℝ≥0∞)) vector - WithLp.ofLp (p := (2 : ℝ≥0∞)) other) + +noncomputable local instance ambientInner (d : ℕ) : Inner ℝ (Ambient d) where + inner vector other := ∑ coordinate : Fin d, + inner ℝ (WithLp.ofLp (p := (2 : ℝ≥0∞)) vector coordinate) + (WithLp.ofLp (p := (2 : ℝ≥0∞)) other coordinate) + +noncomputable def gramVolume {d k : ℕ} (u : Ambient d) (z : Fin k → Ambient d) : ℝ := + Real.sqrt (Matrix.gram ℝ (fun i => z i-u)).det +noncomputable def inverseVolume {d : ℕ} (u : Ambient d) (z : Fin (d/100) → Ambient d) : ℝ≥0∞ := + ((ENNReal.ofReal (gramVolume u z))⁻¹)^(d/100) +def BallBound {d : ℕ} (ν : Measure (Ambient d)) : Prop := + ∀ (x : Ambient d) (r : ℝ), 0 < r → + ν (ball x r) ≤ ENNReal.ofReal (r^(((d:ℝ)-1)/2)) +def InverseVolumeStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ ν : Measure (Ambient d), IsProbabilityMeasure ν → BallBound ν → + ∀ u : Ambient d, (∫⁻ z,inverseVolume u z ∂Measure.pi (fun _ : Fin (d/100) => ν)) ≤ + ENNReal.ofReal (Real.exp (C*d*(d/100:ℕ))) +theorem inverse_volume_without_support : InverseVolumeStatement := by + sorry +end AllScaleInverseVolume + + +open MeasureTheory ProbabilityTheory Metric Set +open scoped ENNReal +namespace KernelPotential +local instance namedAtLeastTwoTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev Ambient (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Rows (d : ℕ) := Fin (d/16) → Fin d → ℝ +noncomputable def radial {d : ℕ} (x : Ambient d) : Ambient d := ‖x‖⁻¹ • x +noncomputable def sphereProbability (d : ℕ) : Measure (Ambient d) := + ((volume (ball (0 : Ambient d) 1))⁻¹ • volume.restrict (ball (0 : Ambient d) 1)).map radial +noncomputable def J {d : ℕ} (ν : Measure (Ambient d)) (s : Ambient d) : ℝ≥0∞ := + ∫⁻ u,((ENNReal.ofReal ‖u-s‖)⁻¹)^(2*(d/16)) ∂ν +noncomputable def B {d : ℕ} (ν : Measure (Ambient d)) : ℝ := + ∫ s, Real.log ((J ν s).toReal) ∂ν +noncomputable def Phi {d : ℕ} (ν : Measure (Ambient d)) : ℝ := + (InformationTheory.klDiv ν (sphereProbability d)).toReal - B ν + +def BoundedDensity {d : ℕ} (ν : Measure (Ambient d)) : Prop := + ∃ H : ℝ, 0 < H ∧ ν ≤ ENNReal.ofReal H • sphereProbability d + +noncomputable def rowLaw (d : ℕ) : Measure (Rows d) := + Measure.pi (fun _ : Fin (d/16) => Measure.pi (fun _ : Fin d => gaussianReal 0 1)) +noncomputable def labels {d : ℕ} (a : Rows d) (s : Ambient d) : Fin (d/16) → ℝ := + fun i => ∑ j,a i j*s j +structure BlockRule (d N : ℕ) where + prob : (Fin N × (Rows d × (Fin (d/16) → ℝ))) → Fin N → ℝ + measurable_prob : ∀ w, Measurable (fun x => prob x w) + nonneg_prob : ∀ x w, 0 ≤ prob x w + sum_prob : ∀ x, ∑ w,prob x w=1 + +noncomputable def outgoingLaw {d N : ℕ} (μ : Measure (Ambient d × Fin N)) + (rule : BlockRule d N) : Measure (Ambient d × Fin N) := + ∑ w : Fin N, ((μ.prod (rowLaw d)).withDensity (fun x => + ENNReal.ofReal (rule.prob (x.1.2,x.2,labels x.2 x.1.1) w))).map (fun x => (x.1.1,w)) +noncomputable def component {d N : ℕ} (μ : Measure (Ambient d × Fin N)) (v : Fin N) : + Measure (Ambient d) := (μ.restrict {x|x.2=v}).map Prod.fst +noncomputable def posterior {d N : ℕ} (μ : Measure (Ambient d × Fin N)) (v : Fin N) : + Measure (Ambient d) := (component μ v univ)⁻¹ • component μ v +noncomputable def averagePhi {d N : ℕ} (μ : Measure (Ambient d × Fin N)) : ℝ := + ∑ v : Fin N, (component μ v univ).toReal * Phi (posterior μ v) + +def CoercivityStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ ν : Measure (Ambient d), IsProbabilityMeasure ν → BoundedDensity ν → + (1/2:ℝ)*(InformationTheory.klDiv ν (sphereProbability d)).toReal-C*d ≤ Phi ν) ∧ + Phi (sphereProbability d) ≤ (2*(d/16):ℕ)*Real.log 2 ∧ + (∀ (q : ℕ) (w : Fin q → ℝ), (∀ i,0 ≤ w i) → (∑ i,w i)=1 → + ∀ ν : Fin q → Measure (Ambient d), (∀ i,IsProbabilityMeasure (ν i)) → + (∀ i,BoundedDensity (ν i)) → + Phi (∑ i,ENNReal.ofReal (w i) • ν i) ≤ ∑ i,w i*Phi (ν i)) + +def DriftStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ N : ℕ, 1 ≤ N → + Real.log N ≤ (d:ℝ)^2 → ∀ μ : Measure (Ambient d × Fin N), IsProbabilityMeasure μ → + μ.map Prod.fst=sphereProbability d → ∀ rule : BlockRule d N, + averagePhi (outgoingLaw μ rule) ≤ averagePhi μ+C*d + +theorem kernel_coercivity : CoercivityStatement := by sorry +theorem actual_row_drift : DriftStatement := by sorry +end KernelPotential + +end OAI diff --git a/tasks/gaussian-information/tests/grade.py b/tasks/gaussian-information/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gaussian-information/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gaussian-information/tests/task.json b/tasks/gaussian-information/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f9a17a84f3f673c5f5f0110099a4d7f5ec3812ae --- /dev/null +++ b/tasks/gaussian-information/tests/task.json @@ -0,0 +1,18 @@ +{ + "challenge": "GaussianInformation", + "comparator": { + "theorem_names": [ + "OAI.RepeatedLocalization.repeated_localization", + "OAI.AllScaleInverseVolume.inverse_volume_without_support", + "OAI.KernelPotential.kernel_coercivity", + "OAI.KernelPotential.actual_row_drift" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11504 +} \ No newline at end of file diff --git a/tasks/gaussian-information/tests/test.sh b/tasks/gaussian-information/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gaussian-information/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gaussian-moat/environment/Dockerfile b/tasks/gaussian-moat/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gaussian-moat/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gaussian-moat/environment/fetch_mathlib.sh b/tasks/gaussian-moat/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gaussian-moat/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gaussian-moat/environment/lake-manifest.json b/tasks/gaussian-moat/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gaussian-moat/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gaussian-moat/environment/lakefile.lean b/tasks/gaussian-moat/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gaussian-moat/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gaussian-moat/environment/lean_setup.sh b/tasks/gaussian-moat/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gaussian-moat/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gaussian-moat/environment/pack_submission.py b/tasks/gaussian-moat/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gaussian-moat/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gaussian-moat/instruction.md b/tasks/gaussian-moat/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd811e00638c22a64ce7091d0b6db9b4be25d98e --- /dev/null +++ b/tasks/gaussian-moat/instruction.md @@ -0,0 +1,92 @@ +# openai/math challenge `GaussianMoat` (family 028) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 028 of the release, *The Gaussian moat conjecture* +(Number theory). The family as a whole: Proves the Gaussian moat conjecture: no infinite walk through distinct Gaussian primes can have uniformly bounded steps. More strongly, for every distance bound $D$, the graph joining Gaussian primes at distance at most $D$ has uniformly bounded finite component sizes, depending only on $D$, including primes on the coordinate axes. + +The challenge is `GaussianMoat`, also at `/opt/openai-math/challenges/GaussianMoat.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace GaussianMoat + +abbrev PrimeVertex := {z : GaussianInt // Irreducible z} + +noncomputable def primeGraph (D : ℝ) : SimpleGraph PrimeVertex where + Adj p q := p ≠ q ∧ dist (p.val : ℂ) (q.val : ℂ) ≤ D + symm := by + constructor + intro p q h + exact ⟨h.1.symm, by simpa only [dist_comm] using h.2⟩ + loopless := by + constructor + intro p h + exact h.1 rfl + +def component (D : ℝ) (p : PrimeVertex) : Set PrimeVertex := + {q | (primeGraph D).Reachable p q} + +def MainEndpoint : Prop := + ∀ (D : ℝ) (z : ℕ → GaussianInt), + (∀ t, Irreducible (z t)) → Function.Injective z → + (∀ t, dist (z (t + 1) : ℂ) (z t : ℂ) ≤ D) → False + +def UniformEndpoint : Prop := + ∀ D : ℝ, ∃ B : ℕ, + (∀ p : PrimeVertex, (component D p).Finite ∧ (component D p).ncard ≤ B) ∧ + (∀ (n : ℕ) (z : Fin n → GaussianInt), + (∀ i, Irreducible (z i)) → Function.Injective z → + (∀ i j : Fin n, j.val = i.val + 1 → dist (z j : ℂ) (z i : ℂ) ≤ D) → + n ≤ B) + +theorem fullMain : MainEndpoint ∧ UniformEndpoint := by + sorry + +end GaussianMoat + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GaussianMoat.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GaussianMoat.fullMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gaussian-moat/solution/closure.txt b/tasks/gaussian-moat/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5918e28f461938f658f2de25ff5502183b645226 --- /dev/null +++ b/tasks/gaussian-moat/solution/closure.txt @@ -0,0 +1,41 @@ +OAI.NumberTheory.GaussianMoat.AccurateScales +OAI.NumberTheory.GaussianMoat.BackwardCoverage +OAI.NumberTheory.GaussianMoat.BatchCertificate +OAI.NumberTheory.GaussianMoat.BatchParameters +OAI.NumberTheory.GaussianMoat.BooleanCube +OAI.NumberTheory.GaussianMoat.CommonBlocks +OAI.NumberTheory.GaussianMoat.ConditionalSampling +OAI.NumberTheory.GaussianMoat.DenseBins +OAI.NumberTheory.GaussianMoat.DifferenceSampling +OAI.NumberTheory.GaussianMoat.DyadicSieve +OAI.NumberTheory.GaussianMoat.EntropyBand +OAI.NumberTheory.GaussianMoat.FiniteEntropy +OAI.NumberTheory.GaussianMoat.FiniteLaw +OAI.NumberTheory.GaussianMoat.FreshEntropy +OAI.NumberTheory.GaussianMoat.GroupCoverage +OAI.NumberTheory.GaussianMoat.Information +OAI.NumberTheory.GaussianMoat.InformationTelescope +OAI.NumberTheory.GaussianMoat.KernelComposition +OAI.NumberTheory.GaussianMoat.LatticeComponents +OAI.NumberTheory.GaussianMoat.Main +OAI.NumberTheory.GaussianMoat.Model +OAI.NumberTheory.GaussianMoat.MultiscaleSchedule +OAI.NumberTheory.GaussianMoat.PassingInformation +OAI.NumberTheory.GaussianMoat.PointEnrichment +OAI.NumberTheory.GaussianMoat.PosteriorSampling +OAI.NumberTheory.GaussianMoat.PrimeMass +OAI.NumberTheory.GaussianMoat.ResidueQuotient +OAI.NumberTheory.GaussianMoat.SeparatedParameters +OAI.NumberTheory.GaussianMoat.SieveCertificate +OAI.NumberTheory.GaussianMoat.SieveSmoothing +OAI.NumberTheory.GaussianMoat.SignConcentration +OAI.NumberTheory.GaussianMoat.SignedArithmetic +OAI.NumberTheory.GaussianMoat.SignedGeometry +OAI.NumberTheory.GaussianMoat.SignedResidues +OAI.NumberTheory.GaussianMoat.Smoothing +OAI.NumberTheory.GaussianMoat.TimeLaw +OAI.NumberTheory.GaussianMoat.WalkGeometry +OAI.NumberTheory.GaussianMoat.WalkPackage +OAI.NumberTheory.GaussianMoat.WalkWords +OAI.NumberTheory.GaussianMoat.WindowBatch +OAI.NumberTheory.GaussianMoat.WindowParameters diff --git a/tasks/gaussian-moat/solution/reference.py b/tasks/gaussian-moat/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gaussian-moat/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gaussian-moat/solution/solve.sh b/tasks/gaussian-moat/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c88c33b1707d9f0781170b759bbb6c47cd96c292 --- /dev/null +++ b/tasks/gaussian-moat/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GaussianMoat, i.e. module OAI.NumberTheory.GaussianMoat.Main and the +# 41 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.GaussianMoat.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GaussianMoat" diff --git a/tasks/gaussian-moat/task.toml b/tasks/gaussian-moat/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9e212d4b24f4adb00ef919c7f01466ddd28af411 --- /dev/null +++ b/tasks/gaussian-moat/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gaussian-moat" +version = "1.0.0" +description = "Prove GaussianMoat (openai/math family 028: The Gaussian moat conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GaussianMoat.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GaussianMoat" +family = "028" +family_title = "The Gaussian moat conjecture" +subject = "Number theory" +theorems = ["OAI.GaussianMoat.fullMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.GaussianMoat.Main" +reference_modules = 41 +reference_lean_bytes = 598190 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1157 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12238 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gaussian-moat/tests/Challenge.lean b/tasks/gaussian-moat/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..758b2f13cb75832c8a42f850ecdca6a3534da835 --- /dev/null +++ b/tasks/gaussian-moat/tests/Challenge.lean @@ -0,0 +1,41 @@ +import Mathlib + +namespace OAI + +namespace GaussianMoat + +abbrev PrimeVertex := {z : GaussianInt // Irreducible z} + +noncomputable def primeGraph (D : ℝ) : SimpleGraph PrimeVertex where + Adj p q := p ≠ q ∧ dist (p.val : ℂ) (q.val : ℂ) ≤ D + symm := by + constructor + intro p q h + exact ⟨h.1.symm, by simpa only [dist_comm] using h.2⟩ + loopless := by + constructor + intro p h + exact h.1 rfl + +def component (D : ℝ) (p : PrimeVertex) : Set PrimeVertex := + {q | (primeGraph D).Reachable p q} + +def MainEndpoint : Prop := + ∀ (D : ℝ) (z : ℕ → GaussianInt), + (∀ t, Irreducible (z t)) → Function.Injective z → + (∀ t, dist (z (t + 1) : ℂ) (z t : ℂ) ≤ D) → False + +def UniformEndpoint : Prop := + ∀ D : ℝ, ∃ B : ℕ, + (∀ p : PrimeVertex, (component D p).Finite ∧ (component D p).ncard ≤ B) ∧ + (∀ (n : ℕ) (z : Fin n → GaussianInt), + (∀ i, Irreducible (z i)) → Function.Injective z → + (∀ i j : Fin n, j.val = i.val + 1 → dist (z j : ℂ) (z i : ℂ) ≤ D) → + n ≤ B) + +theorem fullMain : MainEndpoint ∧ UniformEndpoint := by + sorry + +end GaussianMoat + +end OAI diff --git a/tasks/gaussian-moat/tests/grade.py b/tasks/gaussian-moat/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gaussian-moat/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gaussian-moat/tests/task.json b/tasks/gaussian-moat/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..45e4c03cc793d7ca2ea8c94a88943f87078b34e5 --- /dev/null +++ b/tasks/gaussian-moat/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GaussianMoat", + "comparator": { + "theorem_names": [ + "OAI.GaussianMoat.fullMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11338 +} \ No newline at end of file diff --git a/tasks/gaussian-moat/tests/test.sh b/tasks/gaussian-moat/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gaussian-moat/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gaussian-propeller/environment/Dockerfile b/tasks/gaussian-propeller/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gaussian-propeller/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gaussian-propeller/environment/fetch_mathlib.sh b/tasks/gaussian-propeller/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gaussian-propeller/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gaussian-propeller/environment/lake-manifest.json b/tasks/gaussian-propeller/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gaussian-propeller/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gaussian-propeller/environment/lakefile.lean b/tasks/gaussian-propeller/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gaussian-propeller/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gaussian-propeller/environment/lean_setup.sh b/tasks/gaussian-propeller/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gaussian-propeller/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gaussian-propeller/environment/pack_submission.py b/tasks/gaussian-propeller/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gaussian-propeller/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gaussian-propeller/instruction.md b/tasks/gaussian-propeller/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..675fab4cb53dfd3c44c7deb6cc419fc656028cc3 --- /dev/null +++ b/tasks/gaussian-propeller/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `GaussianPropeller` (family 096) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 096 of the release, *The Gaussian propeller conjecture* +(Convex and metric geometry). The family as a whole: Proves that the sum of squared Gaussian first moments of any finite measurable partition is at most $9/(8\pi)$. In dimension at least two, three planar sectors of angle $2\pi/3$, extended orthogonally, attain the bound. Combined with the separate Unique Games theorem, this proves NP-hardness of improving the loss factor $(8\pi/9)(1-1/k)$ for identity-target kernel clustering with fixed $k\ge3$ on rational centered positive semidefinite inputs. + +The challenge is `GaussianPropeller`, also at `/opt/openai-math/challenges/GaussianPropeller.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +namespace GaussianPropeller + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +noncomputable def gaussian (d : ℕ) : Measure (Space d) := stdGaussian (Space d) + +def IsPartition {d k : ℕ} (A : Fin k → Set (Space d)) : Prop := + (∀ i, MeasurableSet (A i)) ∧ ∀ᵐ x ∂gaussian d, ∃! i, x ∈ A i + +noncomputable def centroid {d : ℕ} (A : Set (Space d)) : Space d := + ∫ x in A, x ∂gaussian d + +noncomputable def value {d k : ℕ} (A : Fin k → Set (Space d)) : ℝ := + ∑ i, ‖centroid (A i)‖ ^ 2 + +def coord {d : ℕ} (j : ℕ) (x : Space d) : ℝ := + if h : j < d then x ⟨j, h⟩ else 0 + +noncomputable def propeller (d k : ℕ) (i : Fin k) : Set (Space d) := + if i.val = 0 then {x | |coord 1 x| ≤ Real.sqrt 3 * coord 0 x} + else if i.val = 1 then {x | 0 ≤ coord 1 x ∧ Real.sqrt 3 * coord 0 x ≤ coord 1 x} + else if i.val = 2 then {x | coord 1 x ≤ 0 ∧ Real.sqrt 3 * coord 0 x ≤ -coord 1 x} + else ∅ + +def AllPartitions : Prop := + (∀ (d k : ℕ), 0 < d → 0 < k → ∀ A : Fin k → Set (Space d), + IsPartition A → value A ≤ 9 / (8 * Real.pi)) ∧ + (∀ (d k : ℕ), 2 ≤ d → 3 ≤ k → + IsPartition (propeller d k) ∧ value (propeller d k) = 9 / (8 * Real.pi)) + +theorem all_partitions : AllPartitions := by + sorry + +end GaussianPropeller + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GaussianPropeller.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GaussianPropeller.all_partitions` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gaussian-propeller/solution/closure.txt b/tasks/gaussian-propeller/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a4662240a8178fa47c43d625c4674d62611c1280 --- /dev/null +++ b/tasks/gaussian-propeller/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Probability.GaussianPropeller.Analytic +OAI.Probability.GaussianPropeller.Attainment +OAI.Probability.GaussianPropeller.CapBounds +OAI.Probability.GaussianPropeller.CapCertificates +OAI.Probability.GaussianPropeller.CapIntegral +OAI.Probability.GaussianPropeller.CapNumeric +OAI.Probability.GaussianPropeller.CapReduction +OAI.Probability.GaussianPropeller.CellBounds +OAI.Probability.GaussianPropeller.ConeConcavity +OAI.Probability.GaussianPropeller.ConeReduction +OAI.Probability.GaussianPropeller.Configuration +OAI.Probability.GaussianPropeller.Coordinates +OAI.Probability.GaussianPropeller.Deletion +OAI.Probability.GaussianPropeller.Dual +OAI.Probability.GaussianPropeller.Elimination +OAI.Probability.GaussianPropeller.FourAlgebra +OAI.Probability.GaussianPropeller.FourCells +OAI.Probability.GaussianPropeller.FourReduction +OAI.Probability.GaussianPropeller.GaussianCoordinates +OAI.Probability.GaussianPropeller.Geometry +OAI.Probability.GaussianPropeller.Gram +OAI.Probability.GaussianPropeller.HeatConvolution +OAI.Probability.GaussianPropeller.HeatMaximum +OAI.Probability.GaussianPropeller.LargeCertificates +OAI.Probability.GaussianPropeller.LossCertificates +OAI.Probability.GaussianPropeller.Main +OAI.Probability.GaussianPropeller.Mills +OAI.Probability.GaussianPropeller.Model +OAI.Probability.GaussianPropeller.Moments +OAI.Probability.GaussianPropeller.OneCell +OAI.Probability.GaussianPropeller.PairBounds +OAI.Probability.GaussianPropeller.PairIntegral +OAI.Probability.GaussianPropeller.Polar +OAI.Probability.GaussianPropeller.ProbabilityBounds +OAI.Probability.GaussianPropeller.Quantile +OAI.Probability.GaussianPropeller.QuantileCalculus +OAI.Probability.GaussianPropeller.QuarticCertificates +OAI.Probability.GaussianPropeller.ResidualBounds +OAI.Probability.GaussianPropeller.Scalar +OAI.Probability.GaussianPropeller.SmallCell +OAI.Probability.GaussianPropeller.SmallCertificates +OAI.Probability.GaussianPropeller.SmoothedConcavity +OAI.Probability.GaussianPropeller.SoftMinimum +OAI.Probability.GaussianPropeller.SpanReduction +OAI.Probability.GaussianPropeller.Stein +OAI.Probability.GaussianPropeller.Taylor +OAI.Probability.GaussianPropeller.Translation diff --git a/tasks/gaussian-propeller/solution/reference.py b/tasks/gaussian-propeller/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gaussian-propeller/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gaussian-propeller/solution/solve.sh b/tasks/gaussian-propeller/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..facc91e4091af59b2000fe99622d0955311cd928 --- /dev/null +++ b/tasks/gaussian-propeller/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GaussianPropeller, i.e. module OAI.Probability.GaussianPropeller.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.GaussianPropeller.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GaussianPropeller" diff --git a/tasks/gaussian-propeller/task.toml b/tasks/gaussian-propeller/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..42d3256369cc89fb8dc2f7dcb80e740863b49a8e --- /dev/null +++ b/tasks/gaussian-propeller/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gaussian-propeller" +version = "1.0.0" +description = "Prove GaussianPropeller (openai/math family 096: The Gaussian propeller conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GaussianPropeller.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GaussianPropeller" +family = "096" +family_title = "The Gaussian propeller conjecture" +subject = "Convex and metric geometry" +theorems = ["OAI.GaussianPropeller.all_partitions"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.GaussianPropeller.Main" +reference_modules = 47 +reference_lean_bytes = 583488 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1095 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12225 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gaussian-propeller/tests/Challenge.lean b/tasks/gaussian-propeller/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b16dd477960a2d45f91ec59cc60a2e1518384efd --- /dev/null +++ b/tasks/gaussian-propeller/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory +open scoped ENNReal + +namespace GaussianPropeller + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +noncomputable def gaussian (d : ℕ) : Measure (Space d) := stdGaussian (Space d) + +def IsPartition {d k : ℕ} (A : Fin k → Set (Space d)) : Prop := + (∀ i, MeasurableSet (A i)) ∧ ∀ᵐ x ∂gaussian d, ∃! i, x ∈ A i + +noncomputable def centroid {d : ℕ} (A : Set (Space d)) : Space d := + ∫ x in A, x ∂gaussian d + +noncomputable def value {d k : ℕ} (A : Fin k → Set (Space d)) : ℝ := + ∑ i, ‖centroid (A i)‖ ^ 2 + +def coord {d : ℕ} (j : ℕ) (x : Space d) : ℝ := + if h : j < d then x ⟨j, h⟩ else 0 + +noncomputable def propeller (d k : ℕ) (i : Fin k) : Set (Space d) := + if i.val = 0 then {x | |coord 1 x| ≤ Real.sqrt 3 * coord 0 x} + else if i.val = 1 then {x | 0 ≤ coord 1 x ∧ Real.sqrt 3 * coord 0 x ≤ coord 1 x} + else if i.val = 2 then {x | coord 1 x ≤ 0 ∧ Real.sqrt 3 * coord 0 x ≤ -coord 1 x} + else ∅ + +def AllPartitions : Prop := + (∀ (d k : ℕ), 0 < d → 0 < k → ∀ A : Fin k → Set (Space d), + IsPartition A → value A ≤ 9 / (8 * Real.pi)) ∧ + (∀ (d k : ℕ), 2 ≤ d → 3 ≤ k → + IsPartition (propeller d k) ∧ value (propeller d k) = 9 / (8 * Real.pi)) + +theorem all_partitions : AllPartitions := by + sorry + +end GaussianPropeller + +end OAI diff --git a/tasks/gaussian-propeller/tests/grade.py b/tasks/gaussian-propeller/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gaussian-propeller/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gaussian-propeller/tests/task.json b/tasks/gaussian-propeller/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5e86182a2c61d1c360c31fc9900355220d56ad25 --- /dev/null +++ b/tasks/gaussian-propeller/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GaussianPropeller", + "comparator": { + "theorem_names": [ + "OAI.GaussianPropeller.all_partitions" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11325 +} \ No newline at end of file diff --git a/tasks/gaussian-propeller/tests/test.sh b/tasks/gaussian-propeller/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gaussian-propeller/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gaussian-replacement/environment/Dockerfile b/tasks/gaussian-replacement/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gaussian-replacement/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gaussian-replacement/environment/fetch_mathlib.sh b/tasks/gaussian-replacement/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gaussian-replacement/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gaussian-replacement/environment/lake-manifest.json b/tasks/gaussian-replacement/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gaussian-replacement/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gaussian-replacement/environment/lakefile.lean b/tasks/gaussian-replacement/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gaussian-replacement/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gaussian-replacement/environment/lean_setup.sh b/tasks/gaussian-replacement/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gaussian-replacement/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gaussian-replacement/environment/pack_submission.py b/tasks/gaussian-replacement/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gaussian-replacement/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gaussian-replacement/instruction.md b/tasks/gaussian-replacement/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..461a86e47c23f6c5f4f7ba6573c3e70c92f29f59 --- /dev/null +++ b/tasks/gaussian-replacement/instruction.md @@ -0,0 +1,575 @@ +# openai/math challenge `GaussianReplacement` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `GaussianReplacement`, also at `/opt/openai-math/challenges/GaussianReplacement.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter InformationTheory +open scoped ENNReal NNReal RealInnerProductSpace Topology + +noncomputable section + +namespace CurrentProjection + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev Rows (k d : ℕ) := Fin k → Vector d + +def uniformSphere (d : ℕ) : Measure (Sphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def gaussianRows (k d : ℕ) : Measure (Rows k d) := + Measure.pi fun _ => stdGaussian (Vector d) + +def label {k d : ℕ} (g : Rows k d) (s : Vector d) : Fin k → ℝ := + fun i => ⟪s, g i⟫ + +def LocalGrowth {d : ℕ} (ρ : Measure (Sphere d)) (a : ℕ) (B : ℝ) : Prop := + ∀ z : Vector d, ∀ t : ℝ, 0 < t → + ρ {u | dist (u : Vector d) z ≤ t} ≤ ENNReal.ofReal (B * t ^ a) + +def cubeAverage {k d : ℕ} (ρ : Measure (Sphere d)) (g : Rows k d) + (y : Fin k → ℝ) (δ : ℝ) : ℝ≥0∞ := + ENNReal.ofReal ((2 * δ)⁻¹ ^ k) * + ρ {u | ∀ i, |label g (u : Vector d) i - y i| ≤ δ} + +def exactDensity {k d : ℕ} (ρ : Measure (Sphere d)) (g : Rows k d) + (y : Fin k → ℝ) : ℝ≥0∞ := by + classical + let f := fun j : ℕ => (cubeAverage ρ g y (1 / (j : ℝ))).toReal + exact if h : ∃ L : ℝ, Tendsto f atTop (𝓝 L) then ENNReal.ofReal h.choose else 0 + +def AdmissibleDimensions (d m r q : ℕ) : Prop := + 1 ≤ m ∧ 1 ≤ r ∧ 1 ≤ q ∧ m + r < d - 1 ∧ m + r - m - (q - 1) ≥ 1 + +def momentConstant (C : ℝ) (d : ℕ) (B D : ℝ) : ℝ≥0∞ := + ENNReal.ofReal (Real.exp (C * d) * B * (1 + max (Real.log (D / B)) 0)) + +def MixedMomentMain : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (d m r q : ℕ), AdmissibleDimensions d m r q → + ∀ (ρ : Measure (Sphere d)), IsFiniteMeasure ρ → + ∀ (B D : ℝ), 0 < B → 0 < D → LocalGrowth ρ (m+r) B → LocalGrowth ρ (d-1) D → + (∀ (s : Sphere d) (δ : ℝ), 0 < δ → + (∫⁻ X, (∫⁻ Z, cubeAverage ρ (Fin.append X Z) + (label (Fin.append X Z) (s : Vector d)) δ ∂gaussianRows r d)^q + ∂gaussianRows m d) ≤ (momentConstant C d B D)^q) ∧ + (ρ ≪ uniformSphere d → ∃ E : Set (Sphere d), MeasurableSet E ∧ ρ E = 0 ∧ + ∀ s ∉ E, + (∀ᵐ G ∂gaussianRows (m+r) d, + Tendsto (fun δ : ℝ => cubeAverage ρ G (label G (s : Vector d)) δ) + (𝓝[>] 0) (𝓝 (exactDensity ρ G (label G (s : Vector d))))) ∧ + ((∫⁻ X, (∫⁻ Z, exactDensity ρ (Fin.append X Z) + (label (Fin.append X Z) (s : Vector d)) ∂gaussianRows r d)^q + ∂gaussianRows m d) ≤ (momentConstant C d B D)^q) ∧ + (ρ ≠ 0 → ∀ᵐ G ∂gaussianRows (m+r) d, + 0 < exactDensity ρ G (label G (s : Vector d)) ∧ + exactDensity ρ G (label G (s : Vector d)) < ∞)) + +instance gaussianRows_isProbabilityMeasure (k d : ℕ) : IsProbabilityMeasure (gaussianRows k d) := by + unfold gaussianRows + infer_instance + +lemma measurable_own_label {k d : ℕ} : + Measurable (fun z : Rows k d × Sphere d => label z.1 (z.2:Vector d)) := by + apply Measurable.of_eval + intro i + exact (continuous_inner.comp <| (continuous_subtype_val.comp continuous_snd).prodMk + ((continuous_apply i).comp continuous_fst)).measurable + +def swapLast {A B C : Type*} [MeasurableSpace A] [MeasurableSpace B] [MeasurableSpace C] : + (A × B) × C ≃ᵐ (A × C) × B where + toFun p := ((p.1.1,p.2),p.1.2) + invFun p := ((p.1.1,p.2),p.1.2) + left_inv _ := rfl + right_inv _ := rfl + measurable_toFun := (measurable_fst.fst.prodMk measurable_snd).prodMk measurable_fst.snd + measurable_invFun := (measurable_fst.fst.prodMk measurable_snd).prodMk measurable_fst.snd + +def rowInformation {S W X : Type*} [MeasurableSpace S] [MeasurableSpace W] + [MeasurableSpace X] (P : Measure ((S×W)×X)) (γ : Measure X) : ℝ≥0∞ := + klDiv P (P.fst.prod γ) + +noncomputable def shannonEntropy {W : Type*} [MeasurableSpace W] (π : Measure W) : ℝ≥0∞ := + ∫⁻ w, ENNReal.ofReal (-Real.log (π {w}).toReal) ∂π + +def conditionalMutualInformation {Z A B : Type*} [MeasurableSpace Z] + [MeasurableSpace A] [MeasurableSpace B] [StandardBorelSpace A] [StandardBorelSpace B] + (P : Measure (Z×(A×B))) [IsFiniteMeasure P] : ℝ≥0∞ := by + classical + exact if h : Nonempty (A×B) then + letI := h + InformationTheory.klDiv P (P.fst ⊗ₘ (P.condKernel.fst ×ₖ P.condKernel.snd)) + else 0 + +def actualExperiment {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d × W) × Rows m d)) : + Measure (((Sphere d × W) × Rows m d) × Rows r d) := P.prod (gaussianRows r d) + +instance actualExperiment_isProbabilityMeasure {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure (actualExperiment (r:=r) P) := + inferInstanceAs (IsProbabilityMeasure (P.prod (gaussianRows r d))) + +def actualObservation {d m r : ℕ} {W : Type*} + (p : ((Sphere d × W) × Rows m d) × Rows r d) : + (Rows (m+r) d × W) × (Fin (m+r) → ℝ) := + ((Fin.append p.1.2 p.2,p.1.1.2), label (Fin.append p.1.2 p.2) (p.1.1.1 : Vector d)) + +instance actualObservation_isProbabilityMeasure {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure ((actualExperiment (r:=r) P).map actualObservation) := + inferInstance + +def selectedCube {k d : ℕ} {W : Type*} (ρ : W → Measure (Sphere d)) (δ : ℝ) + (z : (Rows k d×W)×(Fin k → ℝ)) : ℝ≥0∞ := cubeAverage (ρ z.1.2) z.1.1 z.2 δ + +def selectedExact {k d : ℕ} {W : Type*} (ρ : W → Measure (Sphere d)) + (z : (Rows k d×W)×(Fin k → ℝ)) : ℝ≥0∞ := exactDensity (ρ z.1.2) z.1.1 z.2 + +def momentBound (C : ℝ) (d : ℕ) (B D : ℝ) : ℝ := + Real.exp (C*d)*B*(1+max (Real.log (D/B)) 0) + +def logPositive (x : ℝ≥0∞) : ℝ := max (Real.log x.toReal) 0 + +def logNegative (x : ℝ≥0∞) : ℝ≥0∞ := if x = 0 then ∞ else ENNReal.ofReal (-Real.log x.toReal) + +def extendedLogExpectation {A : Type*} [MeasurableSpace A] (μ : Measure A) + (f : A → ℝ≥0∞) : EReal := + ((∫⁻ a, ENNReal.ofReal (logPositive (f a)) ∂μ) : EReal) - + ((∫⁻ a, logNegative (f a) ∂μ) : EReal) + +def PositiveMessage {W : Type*} [MeasurableSpace W] (π : Measure W) := {w : W // 0 < π {w}} + +def completeFamily {W : Type*} [MeasurableSpace W] {T : Type*} (π : Measure W) + (f : PositiveMessage π → T) (t₀ : T) (w : W) : T := + if h : 0 < π {w} then f ⟨w,h⟩ else t₀ + +structure ActualRowConclusion {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ρ : W → Measure (Sphere d)) (B D : W → ℝ) : Prop where + row_finite : rowInformation P (gaussianRows m d) ≠ ∞ + row_le_entropy : (rowInformation P (gaussianRows m d)).toReal ≤ + (shannonEntropy (P.map swapLast).snd).toReal + conditional_density : ∀ᵐ gw ∂((actualExperiment (r:=r) P).map actualObservation).fst, + ((actualExperiment (r:=r) P).map actualObservation).condKernel gw ≪ volume + actual_limit : ∀ᵐ p ∂actualExperiment (r:=r) P, + Tendsto (fun j : ℕ => selectedCube ρ (1/(j:ℝ)) (actualObservation p)) atTop + (𝓝 (selectedExact ρ (actualObservation p))) + smoothed_bound : ∀ δ : ℝ, 0 < δ → + Integrable (fun p => Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) ∧ + (∫ p, Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + exact_integrable : Integrable (fun p => Real.log (1+(selectedExact ρ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) + exact_bound : (∫ p, Real.log (1+(selectedExact ρ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + entropy_bound : (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst ≤ + (shannonEntropy (P.map swapLast).snd).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + positive_log_integrable : Integrable (fun p => logPositive (selectedExact ρ (actualObservation p))) + (actualExperiment (r:=r) P) + extended_log_bound : extendedLogExpectation (actualExperiment (r:=r) P) + (fun p => selectedExact ρ (actualObservation p)) ≤ + (((rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst) : EReal) + +def actualConditionalRowInformation {d m : ℕ} {W : Type*} [MeasurableSpace W] + [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsFiniteMeasure P] : ℝ≥0∞ := + conditionalMutualInformation (P.map (fun p => (p.1.1,(p.2,p.1.2)))) + +structure ActualRowSourceConclusion {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ρ : W → Measure (Sphere d)) (B D : W → ℝ) : Prop where + row_finite : actualConditionalRowInformation P ≠ ∞ + row_le_entropy : (actualConditionalRowInformation P).toReal ≤ + (shannonEntropy (P.map swapLast).snd).toReal + conditional_density : ∀ᵐ gw ∂((actualExperiment (r:=r) P).map actualObservation).fst, + ((actualExperiment (r:=r) P).map actualObservation).condKernel gw ≪ volume + actual_limit : ∀ᵐ p ∂actualExperiment (r:=r) P, + Tendsto (fun j : ℕ => selectedCube ρ (1/(j:ℝ)) (actualObservation p)) atTop + (𝓝 (selectedExact ρ (actualObservation p))) + smoothed_bound : ∀ δ : ℝ, 0 < δ → + Integrable (fun p => Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) ∧ + (∫ p, Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + exact_integrable : Integrable (fun p => Real.log (1+(selectedExact ρ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) + exact_bound : (∫ p, Real.log (1+(selectedExact ρ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + entropy_bound : (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst ≤ + (shannonEntropy (P.map swapLast).snd).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + positive_log_integrable : Integrable (fun p => logPositive (selectedExact ρ (actualObservation p))) + (actualExperiment (r:=r) P) + extended_log_bound : extendedLogExpectation (actualExperiment (r:=r) P) + (fun p => selectedExact ρ (actualObservation p)) ≤ + (((actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst) : EReal) + +def alignedExperiment {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) : Measure ((Sphere d×W)×Rows (m+r) d) := + (actualExperiment (r:=r) P).map (fun p => (p.1.1,Fin.append p.1.2 p.2)) + +instance alignedExperiment_probability {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure (alignedExperiment (r:=r) P) := by + unfold alignedExperiment + infer_instance + +def exposedJointMap {d k : ℕ} {W : Type*} (p : (Sphere d×W)×Rows k d) : + (Rows k d×(Fin k → ℝ))×(Sphere d×W) := ((p.2,label p.2 (p.1.1:Vector d)),p.1) + +def exposedInformation {d k : ℕ} {W : Type*} [MeasurableSpace W] [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows k d)) [IsFiniteMeasure P] : ℝ≥0∞ := + conditionalMutualInformation (P.map exposedJointMap) + +def CriticalComparisonMain : Prop := + ∃ (K : ℝ) (d₀ : ℕ), 0 < K ∧ ∀ (d : ℕ), d₀ ≤ d → + ∀ (W : Type) [MeasurableSpace W] [Countable W] [MeasurableSingletonClass W], + ∀ (P : Measure ((Sphere d×W)×Rows (d/10) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/10) d) → + shannonEntropy (P.map swapLast).snd ≤ ENNReal.ofReal ((d:ℝ)^2) → + exposedInformation (P.fst.prod (gaussianRows (d/10+(d/2-d/10)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/2-d/10) P) + ENNReal.ofReal (K*d) + +def OneLevelComparisonMain : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ ∀ d, d₀ ≤ d → + ∀ (U : Type) [MeasurableSpace U] [Finite U] [MeasurableSingletonClass U], + ∀ (P : Measure ((Sphere d×U)×Rows (d/32) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/32) d) → + exposedInformation (P.fst.prod (gaussianRows (d/32+(d/4-d/32)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/4-d/32) P) + + ENNReal.ofReal (C*((d:ℝ)+Real.log (1+(d:ℝ)+(shannonEntropy P.fst.snd).toReal)+ + (shannonEntropy P.fst.snd).toReal/(d:ℝ))) + +def TwoLabelComparisonMain : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ ∀ d, d₀ ≤ d → + ∀ (V : Type) [MeasurableSpace V] [Finite V] [MeasurableSingletonClass V], + ∀ (P : Measure ((Sphere d×V)×Rows (d/8) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/8) d) → + shannonEntropy P.fst.snd ≤ ENNReal.ofReal ((d:ℝ)^2) → + exposedInformation (P.fst.prod (gaussianRows (d/8+(d/2-d/8)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/2-d/8) P) + ENNReal.ofReal (C*d) + +def blockInput {d m : ℕ} {U : Type*} (z : (Sphere d × U) × Rows m d) : + U × (Rows m d × (Fin m → ℝ)) := + (z.1.2, z.2, label z.2 (z.1.1 : Vector d)) + +lemma measurable_blockInput {d m : ℕ} {U : Type*} [MeasurableSpace U] : + Measurable (blockInput (d:=d) (m:=m) (U:=U)) := by + exact measurable_fst.snd.prodMk (measurable_snd.prodMk + ((measurable_own_label (d:=d) (k:=m)).comp + (measurable_snd.prodMk measurable_fst.fst))) + +def blockLaw {d m : ℕ} {U V : Type*} [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) : + Measure (((Sphere d × U) × Rows m d) × V) := + (P.prod (gaussianRows m d)) ⊗ₘ κ.comap blockInput measurable_blockInput + +instance blockLaw_probability {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) [IsProbabilityMeasure P] + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ] : + IsProbabilityMeasure (blockLaw P κ) := by + unfold blockLaw + infer_instance + +def endingSignalLaw {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) : Measure (Sphere d × V) := + (blockLaw P κ).map (fun z => (z.1.1.1, z.2)) + +instance endingSignalLaw_probability {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) [IsProbabilityMeasure P] + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ] : + IsProbabilityMeasure (endingSignalLaw P κ) := by + unfold endingSignalLaw + infer_instance + +def freshInformation {d : ℕ} {U : Type*} [MeasurableSpace U] [StandardBorelSpace U] + (P : Measure (Sphere d × U)) [IsFiniteMeasure P] (k : ℕ) : ℝ≥0∞ := + exposedInformation (P.prod (gaussianRows k d)) + +def hybridFirst (d : ℕ) : ℕ := (d+3)/4 + +def hybridLast (d : ℕ) : ℕ := d/2 + +def hybridCount (d : ℕ) : ℕ := hybridLast d - hybridFirst d + 1 + +def averagedFreshInformation {d : ℕ} {U : Type*} + [MeasurableSpace U] [StandardBorelSpace U] + (P : Measure (Sphere d × U)) [IsFiniteMeasure P] : ℝ := + (∑ k ∈ Finset.Icc (hybridFirst d) (hybridLast d), (freshInformation P k).toReal) / + hybridCount d + +def HybridBlockMain : Prop := + ∃ (C C' : ℝ) (d₀ : ℕ), 0 < C ∧ 0 < C' ∧ ∀ d, d₀ ≤ d → + ∀ m, 1 ≤ m → m ≤ d/8 → + ∀ (U V : Type) [Fintype U] [Fintype V] + [MeasurableSpace U] [MeasurableSpace V] + [MeasurableSingletonClass U] [MeasurableSingletonClass V], + ∀ (P : Measure (Sphere d × U)) [IsProbabilityMeasure P], + P.fst = uniformSphere d → + ∀ (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ], + ∀ (B : ℝ), 0 ≤ B → + shannonEntropy (endingSignalLaw P κ).snd ≤ ENNReal.ofReal B → + averagedFreshInformation (endingSignalLaw P κ) - averagedFreshInformation P ≤ + C*m + (m:ℝ) / hybridCount d * (C + B / (d/8:ℕ)) + B / (d/32:ℕ) ∧ + (B ≤ (d:ℝ)^2 → + averagedFreshInformation (endingSignalLaw P κ) - averagedFreshInformation P ≤ C'*d) + +def FiberBlockMain : Prop := + ∃ (K : ℝ) (d₀ : ℕ), 0 < K ∧ ∀ d, d₀ ≤ d → + ∀ (U V : Type) [Fintype U] [Fintype V] + [MeasurableSpace U] [MeasurableSpace V] + [MeasurableSingletonClass U] [MeasurableSingletonClass V], + ∀ (P : Measure (Sphere d×U)) [IsProbabilityMeasure P], + P.fst = uniformSphere d → + ∀ (κ : Kernel (U×(Rows (d/10) d×(Fin (d/10)→ℝ))) V) [IsMarkovKernel κ], + ∀ N : ℕ, 1 ≤ N → Fintype.card V ≤ N → Real.log N ≤ (d:ℝ)^2 → + freshInformation (endingSignalLaw P κ) (d/3) ≤ freshInformation P (d/3) + ENNReal.ofReal (K*d) + +def dependentMapKernel {A B D : Type*} [MeasurableSpace A] [MeasurableSpace B] + [MeasurableSpace D] (κ : Kernel A B) (f : A×B → D) : Kernel A D := + (Kernel.id ×ₖ κ).map f + +def fiberObservationLaw (d k : ℕ) : Measure ((Rows k d×(Fin k→ℝ))×Sphere d) := + ((gaussianRows k d).prod (uniformSphere d)).map + (fun z => ((z.1,label z.1 (z.2:Vector d)),z.2)) + +instance uniformSphere_finite (d : ℕ) : IsFiniteMeasure (uniformSphere d) := by + constructor + unfold uniformSphere + rw [Measure.smul_apply, smul_eq_mul] + exact lt_of_le_of_lt (ENNReal.inv_mul_le_one _) ENNReal.one_lt_top + +instance fiberObservationLaw_finite (d k : ℕ) : IsFiniteMeasure (fiberObservationLaw d k) := by + unfold fiberObservationLaw + infer_instance + +lemma sphere_standardBorel (d : ℕ) : StandardBorelSpace (Sphere d) := + Metric.isClosed_sphere.measurableSet.standardBorel + +def sphericalFiberKernel (d k : ℕ) [sphereNonempty : Nonempty (Sphere d)] : + Kernel (Rows k d×(Fin k→ℝ)) (Sphere d) := + @Measure.condKernel (Rows k d×(Fin k→ℝ)) (Sphere d) _ _ + (sphere_standardBorel d) sphereNonempty + (fiberObservationLaw d k) (fiberObservationLaw_finite d k) + +instance sphericalFiberKernel_markov (d k : ℕ) [Nonempty (Sphere d)] : + IsMarkovKernel (sphericalFiberKernel d k) := by + unfold sphericalFiberKernel + infer_instance + +def fiberTwoPointLeft (d k : ℕ) [Nonempty (Sphere d)] : Measure (Rows k d×(Sphere d×Sphere d)) := + ((((gaussianRows k d).prod (uniformSphere d)).withDensity + (fun z => exactDensity (uniformSphere d) z.1 (label z.1 (z.2:Vector d)))) ⊗ₘ + ((sphericalFiberKernel d k).comap (fun z => (z.1,label z.1 (z.2:Vector d))) + (measurable_fst.prodMk measurable_own_label))).map + (fun z => (z.1.1,(z.1.2,z.2))) + +def perpendicularRow {d : ℕ} (v g : Vector d) : Vector d := + letI : NormedAddCommGroup (Vector d) := PiLp.normedAddCommGroup 2 (fun _ : Fin d => ℝ) + letI : InnerProductSpace ℝ (Vector d) := PiLp.innerProductSpace (fun _ : Fin d => ℝ) + g - (⟪v,g⟫ / ‖v‖^2) • v + +def perpendicularRowsKernel (d k : ℕ) : Kernel (Sphere d×Sphere d) (Rows k d) := + dependentMapKernel (Kernel.const (Sphere d×Sphere d) (gaussianRows k d)) + (fun z => fun i => perpendicularRow ((z.1.1:Vector d)-(z.1.2:Vector d)) (z.2 i)) + +def fiberTwoPointConstant (k : ℕ) : ℝ≥0∞ := + letI : OfNat ℝ 2 := @instOfNatAtLeastTwo ℝ 2 Real.instNatCast inferInstance + letI : Mul ℝ := Real.instMul + letI : Inv ℝ := Real.instInv + letI : Pow ℝ ℕ := @NPow.toPow ℝ Real.instMonoid.toNPow + ENNReal.ofReal ((Real.sqrt (2*Real.pi))⁻¹ ^ k) + +def fiberDistanceWeight {d : ℕ} (k : ℕ) (z : Sphere d×Sphere d) : ℝ≥0∞ := + (ENNReal.ofReal ‖(z.1:Vector d)-(z.2:Vector d)‖)⁻¹ ^ k + +def fiberTwoPointRight (d k : ℕ) : Measure (Rows k d×(Sphere d×Sphere d)) := + letI : IsScalarTower ℝ≥0∞ ℝ≥0∞ ℝ≥0∞ := Semigroup.isScalarTower + fiberTwoPointConstant k • + Measure.map (Prod.swap : (Sphere d×Sphere d)×Rows k d → Rows k d×(Sphere d×Sphere d)) + (Measure.compProd + (Measure.withDensity (Measure.prod (uniformSphere d) (uniformSphere d)) + (fiberDistanceWeight k)) + (perpendicularRowsKernel d k)) + +lemma uniformSphere_probability_of_pos {d : ℕ} (hd : 0 < d) : + IsProbabilityMeasure (uniformSphere d) := by + let : Nonempty (Fin d) := ⟨⟨0, hd⟩⟩ + constructor + rw [uniformSphere, Measure.smul_apply, smul_eq_mul] + apply ENNReal.inv_mul_cancel _ (measure_ne_top _ _) + rw [Measure.toSphere_apply_univ] + exact mul_ne_zero + (by exact_mod_cast (Module.finrank_pos (R := ℝ) (M := Vector d)).ne') + (Metric.measure_ball_pos volume 0 zero_lt_one).ne' + + +def FiberTwoPointMain : Prop := + ∀ (d k : ℕ) (_hk : 1 ≤ k) (hkd : k < d-1), + letI : IsProbabilityMeasure (uniformSphere d) := + uniformSphere_probability_of_pos (by omega) + letI : Nonempty (Sphere d) := nonempty_of_isProbabilityMeasure (uniformSphere d) + IsFiniteMeasure (fiberTwoPointLeft d k) ∧ IsFiniteMeasure (fiberTwoPointRight d k) ∧ + fiberTwoPointLeft d k = fiberTwoPointRight d k + +theorem mixedMomentMain : MixedMomentMain := by + sorry + +theorem actualRowMain {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [Countable W] [MeasurableSingletonClass W] + (hdim : AdmissibleDimensions d m r q) + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (H : ℝ) (hν : ν ≤ ENNReal.ofReal H • uniformSphere d) + (hEntropy : shannonEntropy (P.map swapLast).snd ≠ ∞) + (ρ : PositiveMessage (P.map swapLast).snd → Measure (Sphere d)) + [∀ w, IsFiniteMeasure (ρ w)] + (_hρac : ∀ w, ρ w ≪ uniformSphere d) + (B D : PositiveMessage (P.map swapLast).snd → ℝ) + (hB : ∀ w, 0 < B w) (hD : ∀ w, 0 < D w) + (hgB : ∀ w, LocalGrowth (ρ w) (m+r) (B w)) + (hgD : ∀ w, LocalGrowth (ρ w) (d-1) (D w)) + (hCI : Integrable (fun sw : Sphere d×W => Real.log (1+momentBound 9 d + (completeFamily (P.map swapLast).snd B 1 sw.2) (completeFamily (P.map swapLast).snd D 1 sw.2))) P.fst) : + ActualRowConclusion (r:=r) (q:=q) P (completeFamily (P.map swapLast).snd ρ 0) + (completeFamily (P.map swapLast).snd B 1) (completeFamily (P.map swapLast).snd D 1) := by + sorry + +theorem actualRowRefinement {d m : ℕ} {W E : Type*} [MeasurableSpace W] + [MeasurableSpace E] [Countable W] [MeasurableSingletonClass W] + [Countable E] [MeasurableSingletonClass E] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (e : Sphere d×W → E) (he : Measurable e) + (_hEntropy : shannonEntropy + ((P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))).map swapLast).snd ≠ ∞) : + rowInformation (P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))) (gaussianRows m d) = + rowInformation P (gaussianRows m d) := by + sorry + +theorem actualRowSourceMain {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [Countable W] [MeasurableSingletonClass W] + (hdim : AdmissibleDimensions d m r q) + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (H : ℝ) (hν : ν ≤ ENNReal.ofReal H • uniformSphere d) + (hEntropy : shannonEntropy (P.map swapLast).snd ≠ ∞) + (ρ : PositiveMessage (P.map swapLast).snd → Measure (Sphere d)) + [∀ w, IsFiniteMeasure (ρ w)] + (_hρac : ∀ w, ρ w ≪ uniformSphere d) + (B D : PositiveMessage (P.map swapLast).snd → ℝ) + (hB : ∀ w, 0 < B w) (hD : ∀ w, 0 < D w) + (hgB : ∀ w, LocalGrowth (ρ w) (m+r) (B w)) + (hgD : ∀ w, LocalGrowth (ρ w) (d-1) (D w)) + (hCI : Integrable (fun sw : Sphere d×W => Real.log (1+momentBound 9 d + (completeFamily (P.map swapLast).snd B 1 sw.2) (completeFamily (P.map swapLast).snd D 1 sw.2))) P.fst) : + ActualRowSourceConclusion (r:=r) (q:=q) P (completeFamily (P.map swapLast).snd ρ 0) + (completeFamily (P.map swapLast).snd B 1) (completeFamily (P.map swapLast).snd D 1) := by + sorry + +theorem actualRowSourceRefinement {d m : ℕ} {W E : Type*} [MeasurableSpace W] + [MeasurableSpace E] [Countable W] [MeasurableSingletonClass W] + [Countable E] [MeasurableSingletonClass E] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (e : Sphere d×W → E) (he : Measurable e) + (hEntropy : shannonEntropy + ((P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))).map swapLast).snd ≠ ∞) : + actualConditionalRowInformation (P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))) = + actualConditionalRowInformation P := by + sorry + +theorem criticalComparisonMain : CriticalComparisonMain := by + sorry + +theorem oneLevelComparisonMain : OneLevelComparisonMain := by + sorry + +theorem twoLabelComparisonMain : TwoLabelComparisonMain := by + sorry + +theorem hybridBlockMain : HybridBlockMain := by + sorry + +theorem fiberTwoPointMain : FiberTwoPointMain := by + sorry + +theorem fiberBlockMain : FiberBlockMain := by + sorry + +end CurrentProjection + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GaussianReplacement.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.CurrentProjection.mixedMomentMain`, `OAI.CurrentProjection.actualRowMain`, `OAI.CurrentProjection.actualRowRefinement`, `OAI.CurrentProjection.actualRowSourceMain`, `OAI.CurrentProjection.actualRowSourceRefinement`, `OAI.CurrentProjection.criticalComparisonMain`, `OAI.CurrentProjection.oneLevelComparisonMain`, `OAI.CurrentProjection.twoLabelComparisonMain`, `OAI.CurrentProjection.hybridBlockMain`, `OAI.CurrentProjection.fiberTwoPointMain`, `OAI.CurrentProjection.fiberBlockMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gaussian-replacement/solution/closure.txt b/tasks/gaussian-replacement/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..71a4a78db84d24574b93efb85274dc18abeaee89 --- /dev/null +++ b/tasks/gaussian-replacement/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.Probability.GaussianReplacement.ActualRow +OAI.Probability.GaussianReplacement.ArrayBounds +OAI.Probability.GaussianReplacement.Basic +OAI.Probability.GaussianReplacement.Comparison +OAI.Probability.GaussianReplacement.ConditionalInfo +OAI.Probability.GaussianReplacement.ConditionalLaw +OAI.Probability.GaussianReplacement.CriticalEntropy +OAI.Probability.GaussianReplacement.CriticalGeometry +OAI.Probability.GaussianReplacement.Density +OAI.Probability.GaussianReplacement.Entropy +OAI.Probability.GaussianReplacement.FiberBlock +OAI.Probability.GaussianReplacement.FiberConditional +OAI.Probability.GaussianReplacement.FiberEquality +OAI.Probability.GaussianReplacement.FiberGeometry +OAI.Probability.GaussianReplacement.FiberModel +OAI.Probability.GaussianReplacement.FreshRows +OAI.Probability.GaussianReplacement.Geometry +OAI.Probability.GaussianReplacement.Gram +OAI.Probability.GaussianReplacement.Hybrid +OAI.Probability.GaussianReplacement.HybridModel +OAI.Probability.GaussianReplacement.Information +OAI.Probability.GaussianReplacement.KernelGeometry +OAI.Probability.GaussianReplacement.KernelVolume +OAI.Probability.GaussianReplacement.MixedGeometry +OAI.Probability.GaussianReplacement.MixedReplica +OAI.Probability.GaussianReplacement.Mixture +OAI.Probability.GaussianReplacement.Observation +OAI.Probability.GaussianReplacement.Posterior +OAI.Probability.GaussianReplacement.Reference +OAI.Probability.GaussianReplacement.Refinement +OAI.Probability.GaussianReplacement.RowOrder +OAI.Probability.GaussianReplacement.Slab +OAI.Probability.GaussianReplacement.Sphere +OAI.Probability.GaussianReplacement.Telescopes +OAI.Probability.GaussianReplacement.Tilt diff --git a/tasks/gaussian-replacement/solution/reference.py b/tasks/gaussian-replacement/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gaussian-replacement/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gaussian-replacement/solution/solve.sh b/tasks/gaussian-replacement/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..34a23c10fc9c41eaf3408895669ac273320243c7 --- /dev/null +++ b/tasks/gaussian-replacement/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GaussianReplacement, i.e. module OAI.Probability.GaussianReplacement.FiberEquality and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.GaussianReplacement.FiberEquality /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GaussianReplacement" diff --git a/tasks/gaussian-replacement/task.toml b/tasks/gaussian-replacement/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..66d8cb254422851509090dc3315dd56bf61d78ed --- /dev/null +++ b/tasks/gaussian-replacement/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gaussian-replacement" +version = "1.0.0" +description = "Prove GaussianReplacement (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GaussianReplacement.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GaussianReplacement" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.CurrentProjection.mixedMomentMain", "OAI.CurrentProjection.actualRowMain", "OAI.CurrentProjection.actualRowRefinement", "OAI.CurrentProjection.actualRowSourceMain", "OAI.CurrentProjection.actualRowSourceRefinement", "OAI.CurrentProjection.criticalComparisonMain", "OAI.CurrentProjection.oneLevelComparisonMain", "OAI.CurrentProjection.twoLabelComparisonMain", "OAI.CurrentProjection.hybridBlockMain", "OAI.CurrentProjection.fiberTwoPointMain", "OAI.CurrentProjection.fiberBlockMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.GaussianReplacement.FiberEquality" +reference_modules = 35 +reference_lean_bytes = 760043 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1104 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12384 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gaussian-replacement/tests/Challenge.lean b/tasks/gaussian-replacement/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5853b619cbf223a36963bc5c7c542debb9b3f3ee --- /dev/null +++ b/tasks/gaussian-replacement/tests/Challenge.lean @@ -0,0 +1,524 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter InformationTheory +open scoped ENNReal NNReal RealInnerProductSpace Topology + +noncomputable section + +namespace CurrentProjection + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev Rows (k d : ℕ) := Fin k → Vector d + +def uniformSphere (d : ℕ) : Measure (Sphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def gaussianRows (k d : ℕ) : Measure (Rows k d) := + Measure.pi fun _ => stdGaussian (Vector d) + +def label {k d : ℕ} (g : Rows k d) (s : Vector d) : Fin k → ℝ := + fun i => ⟪s, g i⟫ + +def LocalGrowth {d : ℕ} (ρ : Measure (Sphere d)) (a : ℕ) (B : ℝ) : Prop := + ∀ z : Vector d, ∀ t : ℝ, 0 < t → + ρ {u | dist (u : Vector d) z ≤ t} ≤ ENNReal.ofReal (B * t ^ a) + +def cubeAverage {k d : ℕ} (ρ : Measure (Sphere d)) (g : Rows k d) + (y : Fin k → ℝ) (δ : ℝ) : ℝ≥0∞ := + ENNReal.ofReal ((2 * δ)⁻¹ ^ k) * + ρ {u | ∀ i, |label g (u : Vector d) i - y i| ≤ δ} + +def exactDensity {k d : ℕ} (ρ : Measure (Sphere d)) (g : Rows k d) + (y : Fin k → ℝ) : ℝ≥0∞ := by + classical + let f := fun j : ℕ => (cubeAverage ρ g y (1 / (j : ℝ))).toReal + exact if h : ∃ L : ℝ, Tendsto f atTop (𝓝 L) then ENNReal.ofReal h.choose else 0 + +def AdmissibleDimensions (d m r q : ℕ) : Prop := + 1 ≤ m ∧ 1 ≤ r ∧ 1 ≤ q ∧ m + r < d - 1 ∧ m + r - m - (q - 1) ≥ 1 + +def momentConstant (C : ℝ) (d : ℕ) (B D : ℝ) : ℝ≥0∞ := + ENNReal.ofReal (Real.exp (C * d) * B * (1 + max (Real.log (D / B)) 0)) + +def MixedMomentMain : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (d m r q : ℕ), AdmissibleDimensions d m r q → + ∀ (ρ : Measure (Sphere d)), IsFiniteMeasure ρ → + ∀ (B D : ℝ), 0 < B → 0 < D → LocalGrowth ρ (m+r) B → LocalGrowth ρ (d-1) D → + (∀ (s : Sphere d) (δ : ℝ), 0 < δ → + (∫⁻ X, (∫⁻ Z, cubeAverage ρ (Fin.append X Z) + (label (Fin.append X Z) (s : Vector d)) δ ∂gaussianRows r d)^q + ∂gaussianRows m d) ≤ (momentConstant C d B D)^q) ∧ + (ρ ≪ uniformSphere d → ∃ E : Set (Sphere d), MeasurableSet E ∧ ρ E = 0 ∧ + ∀ s ∉ E, + (∀ᵐ G ∂gaussianRows (m+r) d, + Tendsto (fun δ : ℝ => cubeAverage ρ G (label G (s : Vector d)) δ) + (𝓝[>] 0) (𝓝 (exactDensity ρ G (label G (s : Vector d))))) ∧ + ((∫⁻ X, (∫⁻ Z, exactDensity ρ (Fin.append X Z) + (label (Fin.append X Z) (s : Vector d)) ∂gaussianRows r d)^q + ∂gaussianRows m d) ≤ (momentConstant C d B D)^q) ∧ + (ρ ≠ 0 → ∀ᵐ G ∂gaussianRows (m+r) d, + 0 < exactDensity ρ G (label G (s : Vector d)) ∧ + exactDensity ρ G (label G (s : Vector d)) < ∞)) + +instance gaussianRows_isProbabilityMeasure (k d : ℕ) : IsProbabilityMeasure (gaussianRows k d) := by + unfold gaussianRows + infer_instance + +lemma measurable_own_label {k d : ℕ} : + Measurable (fun z : Rows k d × Sphere d => label z.1 (z.2:Vector d)) := by + apply Measurable.of_eval + intro i + exact (continuous_inner.comp <| (continuous_subtype_val.comp continuous_snd).prodMk + ((continuous_apply i).comp continuous_fst)).measurable + +def swapLast {A B C : Type*} [MeasurableSpace A] [MeasurableSpace B] [MeasurableSpace C] : + (A × B) × C ≃ᵐ (A × C) × B where + toFun p := ((p.1.1,p.2),p.1.2) + invFun p := ((p.1.1,p.2),p.1.2) + left_inv _ := rfl + right_inv _ := rfl + measurable_toFun := (measurable_fst.fst.prodMk measurable_snd).prodMk measurable_fst.snd + measurable_invFun := (measurable_fst.fst.prodMk measurable_snd).prodMk measurable_fst.snd + +def rowInformation {S W X : Type*} [MeasurableSpace S] [MeasurableSpace W] + [MeasurableSpace X] (P : Measure ((S×W)×X)) (γ : Measure X) : ℝ≥0∞ := + klDiv P (P.fst.prod γ) + +noncomputable def shannonEntropy {W : Type*} [MeasurableSpace W] (π : Measure W) : ℝ≥0∞ := + ∫⁻ w, ENNReal.ofReal (-Real.log (π {w}).toReal) ∂π + +def conditionalMutualInformation {Z A B : Type*} [MeasurableSpace Z] + [MeasurableSpace A] [MeasurableSpace B] [StandardBorelSpace A] [StandardBorelSpace B] + (P : Measure (Z×(A×B))) [IsFiniteMeasure P] : ℝ≥0∞ := by + classical + exact if h : Nonempty (A×B) then + letI := h + InformationTheory.klDiv P (P.fst ⊗ₘ (P.condKernel.fst ×ₖ P.condKernel.snd)) + else 0 + +def actualExperiment {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d × W) × Rows m d)) : + Measure (((Sphere d × W) × Rows m d) × Rows r d) := P.prod (gaussianRows r d) + +instance actualExperiment_isProbabilityMeasure {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure (actualExperiment (r:=r) P) := + inferInstanceAs (IsProbabilityMeasure (P.prod (gaussianRows r d))) + +def actualObservation {d m r : ℕ} {W : Type*} + (p : ((Sphere d × W) × Rows m d) × Rows r d) : + (Rows (m+r) d × W) × (Fin (m+r) → ℝ) := + ((Fin.append p.1.2 p.2,p.1.1.2), label (Fin.append p.1.2 p.2) (p.1.1.1 : Vector d)) + +instance actualObservation_isProbabilityMeasure {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure ((actualExperiment (r:=r) P).map actualObservation) := + inferInstance + +def selectedCube {k d : ℕ} {W : Type*} (ρ : W → Measure (Sphere d)) (δ : ℝ) + (z : (Rows k d×W)×(Fin k → ℝ)) : ℝ≥0∞ := cubeAverage (ρ z.1.2) z.1.1 z.2 δ + +def selectedExact {k d : ℕ} {W : Type*} (ρ : W → Measure (Sphere d)) + (z : (Rows k d×W)×(Fin k → ℝ)) : ℝ≥0∞ := exactDensity (ρ z.1.2) z.1.1 z.2 + +def momentBound (C : ℝ) (d : ℕ) (B D : ℝ) : ℝ := + Real.exp (C*d)*B*(1+max (Real.log (D/B)) 0) + +def logPositive (x : ℝ≥0∞) : ℝ := max (Real.log x.toReal) 0 + +def logNegative (x : ℝ≥0∞) : ℝ≥0∞ := if x = 0 then ∞ else ENNReal.ofReal (-Real.log x.toReal) + +def extendedLogExpectation {A : Type*} [MeasurableSpace A] (μ : Measure A) + (f : A → ℝ≥0∞) : EReal := + ((∫⁻ a, ENNReal.ofReal (logPositive (f a)) ∂μ) : EReal) - + ((∫⁻ a, logNegative (f a) ∂μ) : EReal) + +def PositiveMessage {W : Type*} [MeasurableSpace W] (π : Measure W) := {w : W // 0 < π {w}} + +def completeFamily {W : Type*} [MeasurableSpace W] {T : Type*} (π : Measure W) + (f : PositiveMessage π → T) (t₀ : T) (w : W) : T := + if h : 0 < π {w} then f ⟨w,h⟩ else t₀ + +structure ActualRowConclusion {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ρ : W → Measure (Sphere d)) (B D : W → ℝ) : Prop where + row_finite : rowInformation P (gaussianRows m d) ≠ ∞ + row_le_entropy : (rowInformation P (gaussianRows m d)).toReal ≤ + (shannonEntropy (P.map swapLast).snd).toReal + conditional_density : ∀ᵐ gw ∂((actualExperiment (r:=r) P).map actualObservation).fst, + ((actualExperiment (r:=r) P).map actualObservation).condKernel gw ≪ volume + actual_limit : ∀ᵐ p ∂actualExperiment (r:=r) P, + Tendsto (fun j : ℕ => selectedCube ρ (1/(j:ℝ)) (actualObservation p)) atTop + (𝓝 (selectedExact ρ (actualObservation p))) + smoothed_bound : ∀ δ : ℝ, 0 < δ → + Integrable (fun p => Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) ∧ + (∫ p, Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + exact_integrable : Integrable (fun p => Real.log (1+(selectedExact ρ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) + exact_bound : (∫ p, Real.log (1+(selectedExact ρ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + entropy_bound : (rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst ≤ + (shannonEntropy (P.map swapLast).snd).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + positive_log_integrable : Integrable (fun p => logPositive (selectedExact ρ (actualObservation p))) + (actualExperiment (r:=r) P) + extended_log_bound : extendedLogExpectation (actualExperiment (r:=r) P) + (fun p => selectedExact ρ (actualObservation p)) ≤ + (((rowInformation P (gaussianRows m d)).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst) : EReal) + +def actualConditionalRowInformation {d m : ℕ} {W : Type*} [MeasurableSpace W] + [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsFiniteMeasure P] : ℝ≥0∞ := + conditionalMutualInformation (P.map (fun p => (p.1.1,(p.2,p.1.2)))) + +structure ActualRowSourceConclusion {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ρ : W → Measure (Sphere d)) (B D : W → ℝ) : Prop where + row_finite : actualConditionalRowInformation P ≠ ∞ + row_le_entropy : (actualConditionalRowInformation P).toReal ≤ + (shannonEntropy (P.map swapLast).snd).toReal + conditional_density : ∀ᵐ gw ∂((actualExperiment (r:=r) P).map actualObservation).fst, + ((actualExperiment (r:=r) P).map actualObservation).condKernel gw ≪ volume + actual_limit : ∀ᵐ p ∂actualExperiment (r:=r) P, + Tendsto (fun j : ℕ => selectedCube ρ (1/(j:ℝ)) (actualObservation p)) atTop + (𝓝 (selectedExact ρ (actualObservation p))) + smoothed_bound : ∀ δ : ℝ, 0 < δ → + Integrable (fun p => Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) ∧ + (∫ p, Real.log (1+(selectedCube ρ δ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + exact_integrable : Integrable (fun p => Real.log (1+(selectedExact ρ (actualObservation p)).toReal)) + (actualExperiment (r:=r) P) + exact_bound : (∫ p, Real.log (1+(selectedExact ρ (actualObservation p)).toReal) ∂actualExperiment (r:=r) P) ≤ + (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + entropy_bound : (actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst ≤ + (shannonEntropy (P.map swapLast).snd).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst + positive_log_integrable : Integrable (fun p => logPositive (selectedExact ρ (actualObservation p))) + (actualExperiment (r:=r) P) + extended_log_bound : extendedLogExpectation (actualExperiment (r:=r) P) + (fun p => selectedExact ρ (actualObservation p)) ≤ + (((actualConditionalRowInformation P).toReal/q + + ∫ sw : Sphere d×W, Real.log (1+momentBound 9 d (B sw.2) (D sw.2)) ∂P.fst) : EReal) + +def alignedExperiment {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) : Measure ((Sphere d×W)×Rows (m+r) d) := + (actualExperiment (r:=r) P).map (fun p => (p.1.1,Fin.append p.1.2 p.2)) + +instance alignedExperiment_probability {d m r : ℕ} {W : Type*} [MeasurableSpace W] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] : + IsProbabilityMeasure (alignedExperiment (r:=r) P) := by + unfold alignedExperiment + infer_instance + +def exposedJointMap {d k : ℕ} {W : Type*} (p : (Sphere d×W)×Rows k d) : + (Rows k d×(Fin k → ℝ))×(Sphere d×W) := ((p.2,label p.2 (p.1.1:Vector d)),p.1) + +def exposedInformation {d k : ℕ} {W : Type*} [MeasurableSpace W] [StandardBorelSpace W] + (P : Measure ((Sphere d×W)×Rows k d)) [IsFiniteMeasure P] : ℝ≥0∞ := + conditionalMutualInformation (P.map exposedJointMap) + +def CriticalComparisonMain : Prop := + ∃ (K : ℝ) (d₀ : ℕ), 0 < K ∧ ∀ (d : ℕ), d₀ ≤ d → + ∀ (W : Type) [MeasurableSpace W] [Countable W] [MeasurableSingletonClass W], + ∀ (P : Measure ((Sphere d×W)×Rows (d/10) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/10) d) → + shannonEntropy (P.map swapLast).snd ≤ ENNReal.ofReal ((d:ℝ)^2) → + exposedInformation (P.fst.prod (gaussianRows (d/10+(d/2-d/10)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/2-d/10) P) + ENNReal.ofReal (K*d) + +def OneLevelComparisonMain : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ ∀ d, d₀ ≤ d → + ∀ (U : Type) [MeasurableSpace U] [Finite U] [MeasurableSingletonClass U], + ∀ (P : Measure ((Sphere d×U)×Rows (d/32) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/32) d) → + exposedInformation (P.fst.prod (gaussianRows (d/32+(d/4-d/32)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/4-d/32) P) + + ENNReal.ofReal (C*((d:ℝ)+Real.log (1+(d:ℝ)+(shannonEntropy P.fst.snd).toReal)+ + (shannonEntropy P.fst.snd).toReal/(d:ℝ))) + +def TwoLabelComparisonMain : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ ∀ d, d₀ ≤ d → + ∀ (V : Type) [MeasurableSpace V] [Finite V] [MeasurableSingletonClass V], + ∀ (P : Measure ((Sphere d×V)×Rows (d/8) d)) [IsProbabilityMeasure P], + (P.map swapLast).fst = (uniformSphere d).prod (gaussianRows (d/8) d) → + shannonEntropy P.fst.snd ≤ ENNReal.ofReal ((d:ℝ)^2) → + exposedInformation (P.fst.prod (gaussianRows (d/8+(d/2-d/8)) d)) ≤ + exposedInformation (alignedExperiment (r:=d/2-d/8) P) + ENNReal.ofReal (C*d) + +def blockInput {d m : ℕ} {U : Type*} (z : (Sphere d × U) × Rows m d) : + U × (Rows m d × (Fin m → ℝ)) := + (z.1.2, z.2, label z.2 (z.1.1 : Vector d)) + +lemma measurable_blockInput {d m : ℕ} {U : Type*} [MeasurableSpace U] : + Measurable (blockInput (d:=d) (m:=m) (U:=U)) := by + exact measurable_fst.snd.prodMk (measurable_snd.prodMk + ((measurable_own_label (d:=d) (k:=m)).comp + (measurable_snd.prodMk measurable_fst.fst))) + +def blockLaw {d m : ℕ} {U V : Type*} [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) : + Measure (((Sphere d × U) × Rows m d) × V) := + (P.prod (gaussianRows m d)) ⊗ₘ κ.comap blockInput measurable_blockInput + +instance blockLaw_probability {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) [IsProbabilityMeasure P] + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ] : + IsProbabilityMeasure (blockLaw P κ) := by + unfold blockLaw + infer_instance + +def endingSignalLaw {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) : Measure (Sphere d × V) := + (blockLaw P κ).map (fun z => (z.1.1.1, z.2)) + +instance endingSignalLaw_probability {d m : ℕ} {U V : Type*} + [MeasurableSpace U] [MeasurableSpace V] + (P : Measure (Sphere d × U)) [IsProbabilityMeasure P] + (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ] : + IsProbabilityMeasure (endingSignalLaw P κ) := by + unfold endingSignalLaw + infer_instance + +def freshInformation {d : ℕ} {U : Type*} [MeasurableSpace U] [StandardBorelSpace U] + (P : Measure (Sphere d × U)) [IsFiniteMeasure P] (k : ℕ) : ℝ≥0∞ := + exposedInformation (P.prod (gaussianRows k d)) + +def hybridFirst (d : ℕ) : ℕ := (d+3)/4 + +def hybridLast (d : ℕ) : ℕ := d/2 + +def hybridCount (d : ℕ) : ℕ := hybridLast d - hybridFirst d + 1 + +def averagedFreshInformation {d : ℕ} {U : Type*} + [MeasurableSpace U] [StandardBorelSpace U] + (P : Measure (Sphere d × U)) [IsFiniteMeasure P] : ℝ := + (∑ k ∈ Finset.Icc (hybridFirst d) (hybridLast d), (freshInformation P k).toReal) / + hybridCount d + +def HybridBlockMain : Prop := + ∃ (C C' : ℝ) (d₀ : ℕ), 0 < C ∧ 0 < C' ∧ ∀ d, d₀ ≤ d → + ∀ m, 1 ≤ m → m ≤ d/8 → + ∀ (U V : Type) [Fintype U] [Fintype V] + [MeasurableSpace U] [MeasurableSpace V] + [MeasurableSingletonClass U] [MeasurableSingletonClass V], + ∀ (P : Measure (Sphere d × U)) [IsProbabilityMeasure P], + P.fst = uniformSphere d → + ∀ (κ : Kernel (U × (Rows m d × (Fin m → ℝ))) V) [IsMarkovKernel κ], + ∀ (B : ℝ), 0 ≤ B → + shannonEntropy (endingSignalLaw P κ).snd ≤ ENNReal.ofReal B → + averagedFreshInformation (endingSignalLaw P κ) - averagedFreshInformation P ≤ + C*m + (m:ℝ) / hybridCount d * (C + B / (d/8:ℕ)) + B / (d/32:ℕ) ∧ + (B ≤ (d:ℝ)^2 → + averagedFreshInformation (endingSignalLaw P κ) - averagedFreshInformation P ≤ C'*d) + +def FiberBlockMain : Prop := + ∃ (K : ℝ) (d₀ : ℕ), 0 < K ∧ ∀ d, d₀ ≤ d → + ∀ (U V : Type) [Fintype U] [Fintype V] + [MeasurableSpace U] [MeasurableSpace V] + [MeasurableSingletonClass U] [MeasurableSingletonClass V], + ∀ (P : Measure (Sphere d×U)) [IsProbabilityMeasure P], + P.fst = uniformSphere d → + ∀ (κ : Kernel (U×(Rows (d/10) d×(Fin (d/10)→ℝ))) V) [IsMarkovKernel κ], + ∀ N : ℕ, 1 ≤ N → Fintype.card V ≤ N → Real.log N ≤ (d:ℝ)^2 → + freshInformation (endingSignalLaw P κ) (d/3) ≤ freshInformation P (d/3) + ENNReal.ofReal (K*d) + +def dependentMapKernel {A B D : Type*} [MeasurableSpace A] [MeasurableSpace B] + [MeasurableSpace D] (κ : Kernel A B) (f : A×B → D) : Kernel A D := + (Kernel.id ×ₖ κ).map f + +def fiberObservationLaw (d k : ℕ) : Measure ((Rows k d×(Fin k→ℝ))×Sphere d) := + ((gaussianRows k d).prod (uniformSphere d)).map + (fun z => ((z.1,label z.1 (z.2:Vector d)),z.2)) + +instance uniformSphere_finite (d : ℕ) : IsFiniteMeasure (uniformSphere d) := by + constructor + unfold uniformSphere + rw [Measure.smul_apply, smul_eq_mul] + exact lt_of_le_of_lt (ENNReal.inv_mul_le_one _) ENNReal.one_lt_top + +instance fiberObservationLaw_finite (d k : ℕ) : IsFiniteMeasure (fiberObservationLaw d k) := by + unfold fiberObservationLaw + infer_instance + +lemma sphere_standardBorel (d : ℕ) : StandardBorelSpace (Sphere d) := + Metric.isClosed_sphere.measurableSet.standardBorel + +def sphericalFiberKernel (d k : ℕ) [sphereNonempty : Nonempty (Sphere d)] : + Kernel (Rows k d×(Fin k→ℝ)) (Sphere d) := + @Measure.condKernel (Rows k d×(Fin k→ℝ)) (Sphere d) _ _ + (sphere_standardBorel d) sphereNonempty + (fiberObservationLaw d k) (fiberObservationLaw_finite d k) + +instance sphericalFiberKernel_markov (d k : ℕ) [Nonempty (Sphere d)] : + IsMarkovKernel (sphericalFiberKernel d k) := by + unfold sphericalFiberKernel + infer_instance + +def fiberTwoPointLeft (d k : ℕ) [Nonempty (Sphere d)] : Measure (Rows k d×(Sphere d×Sphere d)) := + ((((gaussianRows k d).prod (uniformSphere d)).withDensity + (fun z => exactDensity (uniformSphere d) z.1 (label z.1 (z.2:Vector d)))) ⊗ₘ + ((sphericalFiberKernel d k).comap (fun z => (z.1,label z.1 (z.2:Vector d))) + (measurable_fst.prodMk measurable_own_label))).map + (fun z => (z.1.1,(z.1.2,z.2))) + +def perpendicularRow {d : ℕ} (v g : Vector d) : Vector d := + letI : NormedAddCommGroup (Vector d) := PiLp.normedAddCommGroup 2 (fun _ : Fin d => ℝ) + letI : InnerProductSpace ℝ (Vector d) := PiLp.innerProductSpace (fun _ : Fin d => ℝ) + g - (⟪v,g⟫ / ‖v‖^2) • v + +def perpendicularRowsKernel (d k : ℕ) : Kernel (Sphere d×Sphere d) (Rows k d) := + dependentMapKernel (Kernel.const (Sphere d×Sphere d) (gaussianRows k d)) + (fun z => fun i => perpendicularRow ((z.1.1:Vector d)-(z.1.2:Vector d)) (z.2 i)) + +def fiberTwoPointConstant (k : ℕ) : ℝ≥0∞ := + letI : OfNat ℝ 2 := @instOfNatAtLeastTwo ℝ 2 Real.instNatCast inferInstance + letI : Mul ℝ := Real.instMul + letI : Inv ℝ := Real.instInv + letI : Pow ℝ ℕ := @NPow.toPow ℝ Real.instMonoid.toNPow + ENNReal.ofReal ((Real.sqrt (2*Real.pi))⁻¹ ^ k) + +def fiberDistanceWeight {d : ℕ} (k : ℕ) (z : Sphere d×Sphere d) : ℝ≥0∞ := + (ENNReal.ofReal ‖(z.1:Vector d)-(z.2:Vector d)‖)⁻¹ ^ k + +def fiberTwoPointRight (d k : ℕ) : Measure (Rows k d×(Sphere d×Sphere d)) := + letI : IsScalarTower ℝ≥0∞ ℝ≥0∞ ℝ≥0∞ := Semigroup.isScalarTower + fiberTwoPointConstant k • + Measure.map (Prod.swap : (Sphere d×Sphere d)×Rows k d → Rows k d×(Sphere d×Sphere d)) + (Measure.compProd + (Measure.withDensity (Measure.prod (uniformSphere d) (uniformSphere d)) + (fiberDistanceWeight k)) + (perpendicularRowsKernel d k)) + +lemma uniformSphere_probability_of_pos {d : ℕ} (hd : 0 < d) : + IsProbabilityMeasure (uniformSphere d) := by + let : Nonempty (Fin d) := ⟨⟨0, hd⟩⟩ + constructor + rw [uniformSphere, Measure.smul_apply, smul_eq_mul] + apply ENNReal.inv_mul_cancel _ (measure_ne_top _ _) + rw [Measure.toSphere_apply_univ] + exact mul_ne_zero + (by exact_mod_cast (Module.finrank_pos (R := ℝ) (M := Vector d)).ne') + (Metric.measure_ball_pos volume 0 zero_lt_one).ne' + + +def FiberTwoPointMain : Prop := + ∀ (d k : ℕ) (_hk : 1 ≤ k) (hkd : k < d-1), + letI : IsProbabilityMeasure (uniformSphere d) := + uniformSphere_probability_of_pos (by omega) + letI : Nonempty (Sphere d) := nonempty_of_isProbabilityMeasure (uniformSphere d) + IsFiniteMeasure (fiberTwoPointLeft d k) ∧ IsFiniteMeasure (fiberTwoPointRight d k) ∧ + fiberTwoPointLeft d k = fiberTwoPointRight d k + +theorem mixedMomentMain : MixedMomentMain := by + sorry + +theorem actualRowMain {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [Countable W] [MeasurableSingletonClass W] + (hdim : AdmissibleDimensions d m r q) + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (H : ℝ) (hν : ν ≤ ENNReal.ofReal H • uniformSphere d) + (hEntropy : shannonEntropy (P.map swapLast).snd ≠ ∞) + (ρ : PositiveMessage (P.map swapLast).snd → Measure (Sphere d)) + [∀ w, IsFiniteMeasure (ρ w)] + (_hρac : ∀ w, ρ w ≪ uniformSphere d) + (B D : PositiveMessage (P.map swapLast).snd → ℝ) + (hB : ∀ w, 0 < B w) (hD : ∀ w, 0 < D w) + (hgB : ∀ w, LocalGrowth (ρ w) (m+r) (B w)) + (hgD : ∀ w, LocalGrowth (ρ w) (d-1) (D w)) + (hCI : Integrable (fun sw : Sphere d×W => Real.log (1+momentBound 9 d + (completeFamily (P.map swapLast).snd B 1 sw.2) (completeFamily (P.map swapLast).snd D 1 sw.2))) P.fst) : + ActualRowConclusion (r:=r) (q:=q) P (completeFamily (P.map swapLast).snd ρ 0) + (completeFamily (P.map swapLast).snd B 1) (completeFamily (P.map swapLast).snd D 1) := by + sorry + +theorem actualRowRefinement {d m : ℕ} {W E : Type*} [MeasurableSpace W] + [MeasurableSpace E] [Countable W] [MeasurableSingletonClass W] + [Countable E] [MeasurableSingletonClass E] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (e : Sphere d×W → E) (he : Measurable e) + (_hEntropy : shannonEntropy + ((P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))).map swapLast).snd ≠ ∞) : + rowInformation (P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))) (gaussianRows m d) = + rowInformation P (gaussianRows m d) := by + sorry + +theorem actualRowSourceMain {d m r q : ℕ} {W : Type*} [MeasurableSpace W] + [Countable W] [MeasurableSingletonClass W] + (hdim : AdmissibleDimensions d m r q) + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (H : ℝ) (hν : ν ≤ ENNReal.ofReal H • uniformSphere d) + (hEntropy : shannonEntropy (P.map swapLast).snd ≠ ∞) + (ρ : PositiveMessage (P.map swapLast).snd → Measure (Sphere d)) + [∀ w, IsFiniteMeasure (ρ w)] + (_hρac : ∀ w, ρ w ≪ uniformSphere d) + (B D : PositiveMessage (P.map swapLast).snd → ℝ) + (hB : ∀ w, 0 < B w) (hD : ∀ w, 0 < D w) + (hgB : ∀ w, LocalGrowth (ρ w) (m+r) (B w)) + (hgD : ∀ w, LocalGrowth (ρ w) (d-1) (D w)) + (hCI : Integrable (fun sw : Sphere d×W => Real.log (1+momentBound 9 d + (completeFamily (P.map swapLast).snd B 1 sw.2) (completeFamily (P.map swapLast).snd D 1 sw.2))) P.fst) : + ActualRowSourceConclusion (r:=r) (q:=q) P (completeFamily (P.map swapLast).snd ρ 0) + (completeFamily (P.map swapLast).snd B 1) (completeFamily (P.map swapLast).snd D 1) := by + sorry + +theorem actualRowSourceRefinement {d m : ℕ} {W E : Type*} [MeasurableSpace W] + [MeasurableSpace E] [Countable W] [MeasurableSingletonClass W] + [Countable E] [MeasurableSingletonClass E] + (P : Measure ((Sphere d×W)×Rows m d)) [IsProbabilityMeasure P] + (ν : Measure (Sphere d)) [IsProbabilityMeasure ν] + (hInd : (P.map swapLast).fst = ν.prod (gaussianRows m d)) + (e : Sphere d×W → E) (he : Measurable e) + (hEntropy : shannonEntropy + ((P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))).map swapLast).snd ≠ ∞) : + actualConditionalRowInformation (P.map (fun p => ((p.1.1,(p.1.2,e p.1)),p.2))) = + actualConditionalRowInformation P := by + sorry + +theorem criticalComparisonMain : CriticalComparisonMain := by + sorry + +theorem oneLevelComparisonMain : OneLevelComparisonMain := by + sorry + +theorem twoLabelComparisonMain : TwoLabelComparisonMain := by + sorry + +theorem hybridBlockMain : HybridBlockMain := by + sorry + +theorem fiberTwoPointMain : FiberTwoPointMain := by + sorry + +theorem fiberBlockMain : FiberBlockMain := by + sorry + +end CurrentProjection + +end + +end OAI diff --git a/tasks/gaussian-replacement/tests/grade.py b/tasks/gaussian-replacement/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gaussian-replacement/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gaussian-replacement/tests/task.json b/tasks/gaussian-replacement/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1b72a954bab482f72391aefeb38484b5fc7e1ff1 --- /dev/null +++ b/tasks/gaussian-replacement/tests/task.json @@ -0,0 +1,25 @@ +{ + "challenge": "GaussianReplacement", + "comparator": { + "theorem_names": [ + "OAI.CurrentProjection.mixedMomentMain", + "OAI.CurrentProjection.actualRowMain", + "OAI.CurrentProjection.actualRowRefinement", + "OAI.CurrentProjection.actualRowSourceMain", + "OAI.CurrentProjection.actualRowSourceRefinement", + "OAI.CurrentProjection.criticalComparisonMain", + "OAI.CurrentProjection.oneLevelComparisonMain", + "OAI.CurrentProjection.twoLabelComparisonMain", + "OAI.CurrentProjection.hybridBlockMain", + "OAI.CurrentProjection.fiberTwoPointMain", + "OAI.CurrentProjection.fiberBlockMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11484 +} \ No newline at end of file diff --git a/tasks/gaussian-replacement/tests/test.sh b/tasks/gaussian-replacement/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gaussian-replacement/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/general-mahler/environment/Dockerfile b/tasks/general-mahler/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/general-mahler/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/general-mahler/environment/fetch_mathlib.sh b/tasks/general-mahler/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/general-mahler/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/general-mahler/environment/lake-manifest.json b/tasks/general-mahler/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/general-mahler/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/general-mahler/environment/lakefile.lean b/tasks/general-mahler/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/general-mahler/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/general-mahler/environment/lean_setup.sh b/tasks/general-mahler/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/general-mahler/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/general-mahler/environment/pack_submission.py b/tasks/general-mahler/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/general-mahler/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/general-mahler/instruction.md b/tasks/general-mahler/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1c44a8c16a96cb116fdb7d2777d8bcf3f36c50ab --- /dev/null +++ b/tasks/general-mahler/instruction.md @@ -0,0 +1,89 @@ +# openai/math challenge `GeneralMahler` (family 087) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 087 of the release, *The Mahler conjectures and symplectic width* +(Convex and metric geometry). The family as a whole: Resolves the symmetric and nonsymmetric geometric Mahler conjectures in every dimension, with Hanner polytopes and simplices as the respective volume-product minimizers and all equality cases classified. The corresponding sharp functional Mahler inequalities also hold. For $n\ge2$, every symmetric polar product $K\times K^\circ$ in dimension $2n$ has Gromov width $4$. + +The challenge is `GeneralMahler`, also at `/opt/openai-math/challenges/GeneralMahler.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace GeneralMahler + +abbrev Rn (n : ℕ) := EuclideanSpace ℝ (Fin n) + +/-- The polar of a convex body translated by an interior center. -/ +def polarAt {n : ℕ} (K : Set (Rn n)) (z : Rn n) : Set (Rn n) := + {y | ∀ x ∈ K, ⟪y, x - z⟫ ≤ 1} + +/-- The volume product minimized over the interior centers of the body. -/ +def volumeProduct {n : ℕ} (K : Set (EuclideanSpace ℝ (Fin n))) : ℝ := + sInf ((fun z => (volume K).toReal * (volume (polarAt K z)).toReal) '' + interior K) + +/-- The sharp general Mahler inequality, with equality exactly for simplices. -/ +theorem general_mahler {n : ℕ} (hn : 1 ≤ n) + (K : Set (EuclideanSpace ℝ (Fin n))) + (hcompact : IsCompact K) (hconvex : Convex ℝ K) + (hinterior : (interior K).Nonempty) : + ((n : ℝ) + 1) ^ (n + 1) / (Nat.factorial n : ℝ) ^ 2 ≤ volumeProduct K ∧ + (volumeProduct K = ((n : ℝ) + 1) ^ (n + 1) / (Nat.factorial n : ℝ) ^ 2 ↔ + ∃ vertices : Fin (n + 1) → EuclideanSpace ℝ (Fin n), + AffineIndependent ℝ vertices ∧ K = convexHull ℝ (range vertices)) := by + sorry + +end GeneralMahler + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GeneralMahler.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GeneralMahler.general_mahler` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/general-mahler/solution/closure.txt b/tasks/general-mahler/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1de78856df8e79d18c90b61fdb325ad9a608550c --- /dev/null +++ b/tasks/general-mahler/solution/closure.txt @@ -0,0 +1,302 @@ +OAI.Geometry.Convex.GeneralMahler.Angle +OAI.Geometry.Convex.GeneralMahler.AngleIntegral +OAI.Geometry.Convex.GeneralMahler.Beta +OAI.Geometry.Convex.GeneralMahler.BiWeight +OAI.Geometry.Convex.GeneralMahler.Bias +OAI.Geometry.Convex.GeneralMahler.BoundField +OAI.Geometry.Convex.GeneralMahler.Brouwer.Color +OAI.Geometry.Convex.GeneralMahler.Brouwer.Fixed +OAI.Geometry.Convex.GeneralMahler.Brouwer.Ghost +OAI.Geometry.Convex.GeneralMahler.Brouwer.Grid +OAI.Geometry.Convex.GeneralMahler.Brouwer.Scarf +OAI.Geometry.Convex.GeneralMahler.Brouwer.Simplex +OAI.Geometry.Convex.GeneralMahler.Budget.Blocks +OAI.Geometry.Convex.GeneralMahler.Budget.Degree +OAI.Geometry.Convex.GeneralMahler.Budget.Eq19 +OAI.Geometry.Convex.GeneralMahler.Budget.Eq23 +OAI.Geometry.Convex.GeneralMahler.Budget.Extract +OAI.Geometry.Convex.GeneralMahler.Budget.FinalR +OAI.Geometry.Convex.GeneralMahler.Budget.Klimit +OAI.Geometry.Convex.GeneralMahler.Budget.Major +OAI.Geometry.Convex.GeneralMahler.Budget.Parity +OAI.Geometry.Convex.GeneralMahler.Budget.Penalty +OAI.Geometry.Convex.GeneralMahler.Budget.Roots +OAI.Geometry.Convex.GeneralMahler.Budget.Segment +OAI.Geometry.Convex.GeneralMahler.Budget.Tbound +OAI.Geometry.Convex.GeneralMahler.CDF +OAI.Geometry.Convex.GeneralMahler.Compare +OAI.Geometry.Convex.GeneralMahler.Cone +OAI.Geometry.Convex.GeneralMahler.Contact +OAI.Geometry.Convex.GeneralMahler.CovHerm +OAI.Geometry.Convex.GeneralMahler.Cutoff +OAI.Geometry.Convex.GeneralMahler.DefectIBP +OAI.Geometry.Convex.GeneralMahler.DefectLayer +OAI.Geometry.Convex.GeneralMahler.Density +OAI.Geometry.Convex.GeneralMahler.Edge +OAI.Geometry.Convex.GeneralMahler.EdgeBand +OAI.Geometry.Convex.GeneralMahler.EntScalar +OAI.Geometry.Convex.GeneralMahler.Entropy +OAI.Geometry.Convex.GeneralMahler.EntropyMap +OAI.Geometry.Convex.GeneralMahler.Eq13 +OAI.Geometry.Convex.GeneralMahler.Eq14 +OAI.Geometry.Convex.GeneralMahler.Eq18 +OAI.Geometry.Convex.GeneralMahler.EvalGap +OAI.Geometry.Convex.GeneralMahler.Field +OAI.Geometry.Convex.GeneralMahler.FormLin +OAI.Geometry.Convex.GeneralMahler.FormSquare +OAI.Geometry.Convex.GeneralMahler.Forms +OAI.Geometry.Convex.GeneralMahler.Frame.Diagonal +OAI.Geometry.Convex.GeneralMahler.Frame.Sec +OAI.Geometry.Convex.GeneralMahler.Frame.Selector +OAI.Geometry.Convex.GeneralMahler.GainFinal +OAI.Geometry.Convex.GeneralMahler.GainIndent +OAI.Geometry.Convex.GeneralMahler.GaussianTail +OAI.Geometry.Convex.GeneralMahler.GradientLayer +OAI.Geometry.Convex.GeneralMahler.Growth +OAI.Geometry.Convex.GeneralMahler.HLayer +OAI.Geometry.Convex.GeneralMahler.HMatrix +OAI.Geometry.Convex.GeneralMahler.Hermite.Dense +OAI.Geometry.Convex.GeneralMahler.Hermite.Gradient +OAI.Geometry.Convex.GeneralMahler.Hermite.H +OAI.Geometry.Convex.GeneralMahler.Hermite.L2 +OAI.Geometry.Convex.GeneralMahler.Hermite.Multi +OAI.Geometry.Convex.GeneralMahler.Hermite.Pair +OAI.Geometry.Convex.GeneralMahler.IBP +OAI.Geometry.Convex.GeneralMahler.InPoint +OAI.Geometry.Convex.GeneralMahler.InTail +OAI.Geometry.Convex.GeneralMahler.Indicator +OAI.Geometry.Convex.GeneralMahler.Intervals.Basic +OAI.Geometry.Convex.GeneralMahler.Intervals.Chord +OAI.Geometry.Convex.GeneralMahler.Intervals.Elem +OAI.Geometry.Convex.GeneralMahler.Intervals.JCalc +OAI.Geometry.Convex.GeneralMahler.Intervals.Jet +OAI.Geometry.Convex.GeneralMahler.Intervals.Log +OAI.Geometry.Convex.GeneralMahler.Intervals.Trig +OAI.Geometry.Convex.GeneralMahler.Inward +OAI.Geometry.Convex.GeneralMahler.Kernel +OAI.Geometry.Convex.GeneralMahler.LFun +OAI.Geometry.Convex.GeneralMahler.Laplace +OAI.Geometry.Convex.GeneralMahler.LayerMeasure +OAI.Geometry.Convex.GeneralMahler.Lift +OAI.Geometry.Convex.GeneralMahler.LinTest +OAI.Geometry.Convex.GeneralMahler.Linear.Comm +OAI.Geometry.Convex.GeneralMahler.Linear.Eq25 +OAI.Geometry.Convex.GeneralMahler.Linear.Eq26 +OAI.Geometry.Convex.GeneralMahler.Linear.Eq27 +OAI.Geometry.Convex.GeneralMahler.Linear.Final +OAI.Geometry.Convex.GeneralMahler.Linear.Gauss +OAI.Geometry.Convex.GeneralMahler.Linear.Gram +OAI.Geometry.Convex.GeneralMahler.Linear.Nu +OAI.Geometry.Convex.GeneralMahler.Linear.Powers +OAI.Geometry.Convex.GeneralMahler.Linear.Segments +OAI.Geometry.Convex.GeneralMahler.Linear.SpectralIBP +OAI.Geometry.Convex.GeneralMahler.LogDet +OAI.Geometry.Convex.GeneralMahler.LogPath +OAI.Geometry.Convex.GeneralMahler.LowDegree +OAI.Geometry.Convex.GeneralMahler.Main +OAI.Geometry.Convex.GeneralMahler.Matrix +OAI.Geometry.Convex.GeneralMahler.MatrixBox +OAI.Geometry.Convex.GeneralMahler.MatrixDeriv +OAI.Geometry.Convex.GeneralMahler.Middle.Bound2 +OAI.Geometry.Convex.GeneralMahler.Middle.Cells +OAI.Geometry.Convex.GeneralMahler.Middle.Features +OAI.Geometry.Convex.GeneralMahler.Middle.Good +OAI.Geometry.Convex.GeneralMahler.Middle.Identity +OAI.Geometry.Convex.GeneralMahler.Middle.Poly +OAI.Geometry.Convex.GeneralMahler.Middle.Prefix +OAI.Geometry.Convex.GeneralMahler.Middle.Ratio +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse0 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse1 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse10 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse11 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse12 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse13 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse14 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse15 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse16 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse17 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse18 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse19 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse2 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse20 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse21 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse22 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse23 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse24 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse25 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse26 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse27 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse28 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse29 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse3 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse30 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse31 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse32 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse33 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse34 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse4 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse5 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse6 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse7 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse8 +OAI.Geometry.Convex.GeneralMahler.Middle.Rfalse9 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue0 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue1 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue10 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue11 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue12 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue13 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue14 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue15 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue16 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue17 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue18 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue19 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue2 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue20 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue21 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue22 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue23 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue24 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue25 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue26 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue27 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue28 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue29 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue3 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue30 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue31 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue32 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue33 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue34 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue4 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue5 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue6 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue7 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue8 +OAI.Geometry.Convex.GeneralMahler.Middle.Rtrue9 +OAI.Geometry.Convex.GeneralMahler.Middle.Tab +OAI.Geometry.Convex.GeneralMahler.Middle.Tiles +OAI.Geometry.Convex.GeneralMahler.Middle.Trap +OAI.Geometry.Convex.GeneralMahler.Middle.Traversal +OAI.Geometry.Convex.GeneralMahler.Middle.Verified +OAI.Geometry.Convex.GeneralMahler.Mills +OAI.Geometry.Convex.GeneralMahler.MillsLog +OAI.Geometry.Convex.GeneralMahler.MixedField +OAI.Geometry.Convex.GeneralMahler.Moving +OAI.Geometry.Convex.GeneralMahler.Normalize +OAI.Geometry.Convex.GeneralMahler.NtLayer +OAI.Geometry.Convex.GeneralMahler.Orthant +OAI.Geometry.Convex.GeneralMahler.Packet +OAI.Geometry.Convex.GeneralMahler.ParamA +OAI.Geometry.Convex.GeneralMahler.ParamMoment +OAI.Geometry.Convex.GeneralMahler.Parameter +OAI.Geometry.Convex.GeneralMahler.Polar +OAI.Geometry.Convex.GeneralMahler.Prim +OAI.Geometry.Convex.GeneralMahler.ProfileGrowth +OAI.Geometry.Convex.GeneralMahler.Profiles +OAI.Geometry.Convex.GeneralMahler.Proj +OAI.Geometry.Convex.GeneralMahler.ProjMean +OAI.Geometry.Convex.GeneralMahler.ProjParts +OAI.Geometry.Convex.GeneralMahler.Qprimitive +OAI.Geometry.Convex.GeneralMahler.Rapid +OAI.Geometry.Convex.GeneralMahler.Reduction +OAI.Geometry.Convex.GeneralMahler.Rigid.Axes +OAI.Geometry.Convex.GeneralMahler.Rigid.Basis +OAI.Geometry.Convex.GeneralMahler.Rigid.Rays +OAI.Geometry.Convex.GeneralMahler.Rigid.Support +OAI.Geometry.Convex.GeneralMahler.Santalo +OAI.Geometry.Convex.GeneralMahler.Scalar.AllNodes +OAI.Geometry.Convex.GeneralMahler.Scalar.BoxJ +OAI.Geometry.Convex.GeneralMahler.Scalar.Circle +OAI.Geometry.Convex.GeneralMahler.Scalar.Data +OAI.Geometry.Convex.GeneralMahler.Scalar.Grid +OAI.Geometry.Convex.GeneralMahler.Scalar.HBox +OAI.Geometry.Convex.GeneralMahler.Scalar.HSeries +OAI.Geometry.Convex.GeneralMahler.Scalar.Integr +OAI.Geometry.Convex.GeneralMahler.Scalar.LapBox +OAI.Geometry.Convex.GeneralMahler.Scalar.LayerAlg +OAI.Geometry.Convex.GeneralMahler.Scalar.LayerProof +OAI.Geometry.Convex.GeneralMahler.Scalar.Moments +OAI.Geometry.Convex.GeneralMahler.Scalar.NodesTbl +OAI.Geometry.Convex.GeneralMahler.Scalar.Pass +OAI.Geometry.Convex.GeneralMahler.Scalar.QuantJ +OAI.Geometry.Convex.GeneralMahler.Scalar.RealJ +OAI.Geometry.Convex.GeneralMahler.Scalar.Regular +OAI.Geometry.Convex.GeneralMahler.Scalar.Run0 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run100 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run120 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run140 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run160 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run180 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run20 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run200 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run220 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run240 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run260 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run280 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run300 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run320 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run340 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run360 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run380 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run40 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run400 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run420 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run440 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run460 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run480 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run500 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run520 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run540 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run560 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run580 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run60 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run600 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run620 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run640 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run660 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run680 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run700 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run720 +OAI.Geometry.Convex.GeneralMahler.Scalar.Run80 +OAI.Geometry.Convex.GeneralMahler.Scalar.Stable +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.Base +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.Coords +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.Enclose +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.Limit +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.PassTail +OAI.Geometry.Convex.GeneralMahler.Scalar.Tail.Tower +OAI.Geometry.Convex.GeneralMahler.Scalar.Universal +OAI.Geometry.Convex.GeneralMahler.ScalarForm +OAI.Geometry.Convex.GeneralMahler.Scatter +OAI.Geometry.Convex.GeneralMahler.ScatterField +OAI.Geometry.Convex.GeneralMahler.Segment.All +OAI.Geometry.Convex.GeneralMahler.Segment.Average +OAI.Geometry.Convex.GeneralMahler.Segment.Chord +OAI.Geometry.Convex.GeneralMahler.Segment.Cost +OAI.Geometry.Convex.GeneralMahler.Segment.Disp +OAI.Geometry.Convex.GeneralMahler.Segment.Distant +OAI.Geometry.Convex.GeneralMahler.Segment.Element +OAI.Geometry.Convex.GeneralMahler.Segment.FarArc +OAI.Geometry.Convex.GeneralMahler.Segment.First +OAI.Geometry.Convex.GeneralMahler.Segment.Mean +OAI.Geometry.Convex.GeneralMahler.Segment.Omega +OAI.Geometry.Convex.GeneralMahler.Segment.Phase +OAI.Geometry.Convex.GeneralMahler.Segment.Positive +OAI.Geometry.Convex.GeneralMahler.Segment.Short +OAI.Geometry.Convex.GeneralMahler.Segment.Small +OAI.Geometry.Convex.GeneralMahler.Segment.Stats +OAI.Geometry.Convex.GeneralMahler.ShiftBound +OAI.Geometry.Convex.GeneralMahler.SimplexCone +OAI.Geometry.Convex.GeneralMahler.SimplexVolume +OAI.Geometry.Convex.GeneralMahler.Smoothing +OAI.Geometry.Convex.GeneralMahler.Spectral +OAI.Geometry.Convex.GeneralMahler.TestFun +OAI.Geometry.Convex.GeneralMahler.Theorem +OAI.Geometry.Convex.GeneralMahler.Threshold +OAI.Geometry.Convex.GeneralMahler.TraceOrder +OAI.Geometry.Convex.GeneralMahler.Transform +OAI.Geometry.Convex.GeneralMahler.Update +OAI.Geometry.Convex.GeneralMahler.Variation +OAI.Geometry.Convex.GeneralMahler.pRapid diff --git a/tasks/general-mahler/solution/reference.py b/tasks/general-mahler/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/general-mahler/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/general-mahler/solution/solve.sh b/tasks/general-mahler/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6874852fab952eeebb5d6cfa88a47464e43aa7c2 --- /dev/null +++ b/tasks/general-mahler/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GeneralMahler, i.e. module OAI.Geometry.Convex.GeneralMahler.Theorem and the +# 302 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.Convex.GeneralMahler.Theorem /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GeneralMahler" diff --git a/tasks/general-mahler/task.toml b/tasks/general-mahler/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2edb9db73cf0f066df835a60768912c622a89cfe --- /dev/null +++ b/tasks/general-mahler/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/general-mahler" +version = "1.0.0" +description = "Prove GeneralMahler (openai/math family 087: The Mahler conjectures and symplectic width) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GeneralMahler.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GeneralMahler" +family = "087" +family_title = "The Mahler conjectures and symplectic width" +subject = "Convex and metric geometry" +theorems = ["OAI.GeneralMahler.general_mahler"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.Convex.GeneralMahler.Theorem" +reference_modules = 302 +reference_lean_bytes = 2142572 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 5069 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13628 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/general-mahler/tests/Challenge.lean b/tasks/general-mahler/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c44124bf2cf547a348e648e57854cd6bf3c872a7 --- /dev/null +++ b/tasks/general-mahler/tests/Challenge.lean @@ -0,0 +1,38 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace GeneralMahler + +abbrev Rn (n : ℕ) := EuclideanSpace ℝ (Fin n) + +/-- The polar of a convex body translated by an interior center. -/ +def polarAt {n : ℕ} (K : Set (Rn n)) (z : Rn n) : Set (Rn n) := + {y | ∀ x ∈ K, ⟪y, x - z⟫ ≤ 1} + +/-- The volume product minimized over the interior centers of the body. -/ +def volumeProduct {n : ℕ} (K : Set (EuclideanSpace ℝ (Fin n))) : ℝ := + sInf ((fun z => (volume K).toReal * (volume (polarAt K z)).toReal) '' + interior K) + +/-- The sharp general Mahler inequality, with equality exactly for simplices. -/ +theorem general_mahler {n : ℕ} (hn : 1 ≤ n) + (K : Set (EuclideanSpace ℝ (Fin n))) + (hcompact : IsCompact K) (hconvex : Convex ℝ K) + (hinterior : (interior K).Nonempty) : + ((n : ℝ) + 1) ^ (n + 1) / (Nat.factorial n : ℝ) ^ 2 ≤ volumeProduct K ∧ + (volumeProduct K = ((n : ℝ) + 1) ^ (n + 1) / (Nat.factorial n : ℝ) ^ 2 ↔ + ∃ vertices : Fin (n + 1) → EuclideanSpace ℝ (Fin n), + AffineIndependent ℝ vertices ∧ K = convexHull ℝ (range vertices)) := by + sorry + +end GeneralMahler + +end + +end OAI diff --git a/tasks/general-mahler/tests/grade.py b/tasks/general-mahler/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/general-mahler/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/general-mahler/tests/task.json b/tasks/general-mahler/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d9833f82714f8f2d4a3ceeb31967ae4e9ce544cf --- /dev/null +++ b/tasks/general-mahler/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GeneralMahler", + "comparator": { + "theorem_names": [ + "OAI.GeneralMahler.general_mahler" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12728 +} \ No newline at end of file diff --git a/tasks/general-mahler/tests/test.sh b/tasks/general-mahler/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/general-mahler/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/generalized-star-height/environment/Dockerfile b/tasks/generalized-star-height/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/generalized-star-height/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/generalized-star-height/environment/fetch_mathlib.sh b/tasks/generalized-star-height/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/generalized-star-height/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/generalized-star-height/environment/lake-manifest.json b/tasks/generalized-star-height/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/generalized-star-height/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/generalized-star-height/environment/lakefile.lean b/tasks/generalized-star-height/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/generalized-star-height/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/generalized-star-height/environment/lean_setup.sh b/tasks/generalized-star-height/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/generalized-star-height/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/generalized-star-height/environment/pack_submission.py b/tasks/generalized-star-height/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/generalized-star-height/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/generalized-star-height/instruction.md b/tasks/generalized-star-height/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..30d20581d9a5a2f424eb43111c7d2fcda643e782 --- /dev/null +++ b/tasks/generalized-star-height/instruction.md @@ -0,0 +1,99 @@ +# openai/math challenge `GeneralizedStarHeight` (family 134) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 134 of the release, *Generalized star height at most three* +(Theoretical computer science). The family as a whole: Every regular language over a finite alphabet has a generalized regular expression with at most three nested Kleene stars, allowing union, concatenation and complement over the same alphabet. This establishes an absolute bound independent of automaton size, resolving the uniform-boundedness version of the generalized star-height problem. + +The challenge is `GeneralizedStarHeight`, also at `/opt/openai-math/challenges/GeneralizedStarHeight.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace GeneralizedStarHeight + +universe u + +inductive Expression (Alphabet : Type u) : Type u + | zero : Expression Alphabet + | one : Expression Alphabet + | letter : Alphabet → Expression Alphabet + | union : Expression Alphabet → Expression Alphabet → Expression Alphabet + | concat : Expression Alphabet → Expression Alphabet → Expression Alphabet + | compl : Expression Alphabet → Expression Alphabet + | star : Expression Alphabet → Expression Alphabet + +namespace Expression + +open scoped Computability + +def language {Alphabet : Type u} : Expression Alphabet → Language Alphabet + | .zero => 0 + | .one => 1 + | .letter a => {[a]} + | .union P Q => P.language + Q.language + | .concat P Q => P.language * Q.language + | .compl P => P.languageᶜ + | .star P => P.language∗ + +def height {Alphabet : Type u} : Expression Alphabet → ℕ + | .zero | .one | .letter _ => 0 + | .union P Q | .concat P Q => max P.height Q.height + | .compl P => P.height + | .star P => 1 + P.height + +end Expression + +def HasHeightAtMost {Alphabet : Type u} (L : Language Alphabet) (n : ℕ) : Prop := + ∃ P : Expression Alphabet, P.language = L ∧ P.height ≤ n + +theorem main {Alphabet : Type u} [Finite Alphabet] (L : Language Alphabet) (hL : L.IsRegular) : + HasHeightAtMost L 3 := by + sorry + +end GeneralizedStarHeight + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GeneralizedStarHeight.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GeneralizedStarHeight.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/generalized-star-height/solution/closure.txt b/tasks/generalized-star-height/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c9f437178b443fa6c7928166ec3ea81620ab8c9a --- /dev/null +++ b/tasks/generalized-star-height/solution/closure.txt @@ -0,0 +1,37 @@ +OAI.Computability.StarHeight.Actions +OAI.Computability.StarHeight.AffineClock +OAI.Computability.StarHeight.Avoidance +OAI.Computability.StarHeight.BoundarySnapshots +OAI.Computability.StarHeight.CanonicalEpisodes +OAI.Computability.StarHeight.ClockResidues +OAI.Computability.StarHeight.EndSearch +OAI.Computability.StarHeight.EpisodeHeight +OAI.Computability.StarHeight.Episodes +OAI.Computability.StarHeight.ExceptionalOrigins +OAI.Computability.StarHeight.Height +OAI.Computability.StarHeight.LateSchedule +OAI.Computability.StarHeight.Main +OAI.Computability.StarHeight.MarkerSearch +OAI.Computability.StarHeight.Markers +OAI.Computability.StarHeight.Model +OAI.Computability.StarHeight.ObservedActions +OAI.Computability.StarHeight.ObservedLanguages +OAI.Computability.StarHeight.OriginBounds +OAI.Computability.StarHeight.OriginSplicing +OAI.Computability.StarHeight.PeriodicLanguages +OAI.Computability.StarHeight.PeriodicSplicing +OAI.Computability.StarHeight.Recognition +OAI.Computability.StarHeight.RegularLanguages +OAI.Computability.StarHeight.RobustClock +OAI.Computability.StarHeight.ScheduleClock +OAI.Computability.StarHeight.ShiftTable +OAI.Computability.StarHeight.SplitLanguages +OAI.Computability.StarHeight.SplitMetadata +OAI.Computability.StarHeight.StreamRecovery +OAI.Computability.StarHeight.StreamSplicing +OAI.Computability.StarHeight.StreamTranslation +OAI.Computability.StarHeight.SuffixDecoder +OAI.Computability.StarHeight.TagPartitions +OAI.Computability.StarHeight.Translation +OAI.Computability.StarHeight.UsableCopies +OAI.Computability.StarHeight.WordStreams diff --git a/tasks/generalized-star-height/solution/reference.py b/tasks/generalized-star-height/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/generalized-star-height/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/generalized-star-height/solution/solve.sh b/tasks/generalized-star-height/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..38d97a79206b717996c51e921ac1ce30924dee20 --- /dev/null +++ b/tasks/generalized-star-height/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GeneralizedStarHeight, i.e. module OAI.Computability.StarHeight.Main and the +# 37 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.StarHeight.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GeneralizedStarHeight" diff --git a/tasks/generalized-star-height/task.toml b/tasks/generalized-star-height/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b68defacd5d84965e551a1722f2ce615c89ebc3 --- /dev/null +++ b/tasks/generalized-star-height/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/generalized-star-height" +version = "1.0.0" +description = "Prove GeneralizedStarHeight (openai/math family 134: Generalized star height at most three) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GeneralizedStarHeight.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GeneralizedStarHeight" +family = "134" +family_title = "Generalized star height at most three" +subject = "Theoretical computer science" +theorems = ["OAI.GeneralizedStarHeight.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.StarHeight.Main" +reference_modules = 37 +reference_lean_bytes = 522626 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 852 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12170 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/generalized-star-height/tests/Challenge.lean b/tasks/generalized-star-height/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..83f6eb37ef3b31ddc55152df57c6ed06d1e6b168 --- /dev/null +++ b/tasks/generalized-star-height/tests/Challenge.lean @@ -0,0 +1,48 @@ +import Mathlib + +namespace OAI + +namespace GeneralizedStarHeight + +universe u + +inductive Expression (Alphabet : Type u) : Type u + | zero : Expression Alphabet + | one : Expression Alphabet + | letter : Alphabet → Expression Alphabet + | union : Expression Alphabet → Expression Alphabet → Expression Alphabet + | concat : Expression Alphabet → Expression Alphabet → Expression Alphabet + | compl : Expression Alphabet → Expression Alphabet + | star : Expression Alphabet → Expression Alphabet + +namespace Expression + +open scoped Computability + +def language {Alphabet : Type u} : Expression Alphabet → Language Alphabet + | .zero => 0 + | .one => 1 + | .letter a => {[a]} + | .union P Q => P.language + Q.language + | .concat P Q => P.language * Q.language + | .compl P => P.languageᶜ + | .star P => P.language∗ + +def height {Alphabet : Type u} : Expression Alphabet → ℕ + | .zero | .one | .letter _ => 0 + | .union P Q | .concat P Q => max P.height Q.height + | .compl P => P.height + | .star P => 1 + P.height + +end Expression + +def HasHeightAtMost {Alphabet : Type u} (L : Language Alphabet) (n : ℕ) : Prop := + ∃ P : Expression Alphabet, P.language = L ∧ P.height ≤ n + +theorem main {Alphabet : Type u} [Finite Alphabet] (L : Language Alphabet) (hL : L.IsRegular) : + HasHeightAtMost L 3 := by + sorry + +end GeneralizedStarHeight + +end OAI diff --git a/tasks/generalized-star-height/tests/grade.py b/tasks/generalized-star-height/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/generalized-star-height/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/generalized-star-height/tests/task.json b/tasks/generalized-star-height/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b8f2ead770cf42e74fd20ba7a8e95005726b02cb --- /dev/null +++ b/tasks/generalized-star-height/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GeneralizedStarHeight", + "comparator": { + "theorem_names": [ + "OAI.GeneralizedStarHeight.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11270 +} \ No newline at end of file diff --git a/tasks/generalized-star-height/tests/test.sh b/tasks/generalized-star-height/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/generalized-star-height/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/gotsman-linial/environment/Dockerfile b/tasks/gotsman-linial/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/gotsman-linial/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/gotsman-linial/environment/fetch_mathlib.sh b/tasks/gotsman-linial/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/gotsman-linial/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/gotsman-linial/environment/lake-manifest.json b/tasks/gotsman-linial/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/gotsman-linial/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/gotsman-linial/environment/lakefile.lean b/tasks/gotsman-linial/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/gotsman-linial/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/gotsman-linial/environment/lean_setup.sh b/tasks/gotsman-linial/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/gotsman-linial/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/gotsman-linial/environment/pack_submission.py b/tasks/gotsman-linial/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/gotsman-linial/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/gotsman-linial/instruction.md b/tasks/gotsman-linial/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..28089886cedb3067c59a2b2eecd1b62445414b84 --- /dev/null +++ b/tasks/gotsman-linial/instruction.md @@ -0,0 +1,105 @@ +# openai/math challenge `GotsmanLinial` (family 127) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 127 of the release, *The asymptotic Gotsman–Linial conjecture* +(Theoretical computer science). The family as a whole: Proves that a degree-at-most-$d$ polynomial threshold function on the uniform $n$-dimensional Boolean cube has average sensitivity at most $8d\sqrt n$, uniformly for $1\le d\le n$. Average sensitivity counts expected output changes under single-bit flips. This establishes the asymptotic Gotsman–Linial conjecture, allowing polynomial zeros with $\operatorname{sign}(0)=1$. + +The challenge is `GotsmanLinial`, also at `/opt/openai-math/challenges/GotsmanLinial.lean`: + +```lean +import Mathlib.Algebra.MvPolynomial.Degrees +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Tactic.NormNum + +namespace OAI + +open scoped BigOperators + +namespace LeanBlast.GotsmanLinial + +abbrev Cube (n : ℕ) := Fin n → Bool + +def cubeCoord {n : ℕ} (x : Cube n) (i : Fin n) : ℝ := + if x i then 1 else -1 + +def flip {n : ℕ} (i : Fin n) (x : Cube n) : Cube n := + Function.update x i (!(x i)) + +noncomputable def thresholdSign (t : ℝ) : ℝ := + if 0 ≤ t then 1 else -1 + +noncomputable def sensitiveVertices {n : ℕ} (f : Cube n → ℝ) (i : Fin n) : + Finset (Cube n) := by + classical + exact Finset.univ.filter fun x => f x ≠ f (flip i x) + +noncomputable def averageSensitivity {n : ℕ} (f : Cube n → ℝ) : ℝ := + ∑ i : Fin n, ((sensitiveVertices f i).card : ℝ) / (2 : ℝ) ^ n + +def IsMultilinear {n : ℕ} (p : MvPolynomial (Fin n) ℝ) : Prop := + ∀ m ∈ p.support, ∀ i : Fin n, m i ≤ 1 + +noncomputable def polynomialValue {n : ℕ} (p : MvPolynomial (Fin n) ℝ) + (x : Cube n) : ℝ := + MvPolynomial.eval (cubeCoord x) p + +noncomputable def polynomialThreshold {n : ℕ} (p : MvPolynomial (Fin n) ℝ) : + Cube n → ℝ := + fun x => thresholdSign (polynomialValue p x) + +def GotsmanLinialStatement : Prop := + ∀ (n d : ℕ), 1 ≤ n → 1 ≤ d → d ≤ n → + ∀ p : MvPolynomial (Fin n) ℝ, + IsMultilinear p → p.totalDegree ≤ d → + averageSensitivity (polynomialThreshold p) ≤ 8 * (d : ℝ) * Real.sqrt (n : ℝ) + +theorem gotsmanLinialStatement : GotsmanLinialStatement := by + sorry + +end LeanBlast.GotsmanLinial + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GotsmanLinial.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LeanBlast.GotsmanLinial.gotsmanLinialStatement` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/gotsman-linial/solution/closure.txt b/tasks/gotsman-linial/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..56ba111e312db52b3c4e2fc4942a7a552d36fdf3 --- /dev/null +++ b/tasks/gotsman-linial/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.Combinatorics.GotsmanLinial.BinomialMoments +OAI.Combinatorics.GotsmanLinial.BlockCoupling +OAI.Combinatorics.GotsmanLinial.BlockVanishing +OAI.Combinatorics.GotsmanLinial.Commutator +OAI.Combinatorics.GotsmanLinial.CoordinateDegree +OAI.Combinatorics.GotsmanLinial.CoordinateMultipliers +OAI.Combinatorics.GotsmanLinial.CubeOperators +OAI.Combinatorics.GotsmanLinial.EdgeRecovery +OAI.Combinatorics.GotsmanLinial.FiniteCoupling +OAI.Combinatorics.GotsmanLinial.GradingShift +OAI.Combinatorics.GotsmanLinial.HilbertSchmidt +OAI.Combinatorics.GotsmanLinial.Main +OAI.Combinatorics.GotsmanLinial.Model +OAI.Combinatorics.GotsmanLinial.PolynomialDegree +OAI.Combinatorics.GotsmanLinial.ProjectionBlocks +OAI.Combinatorics.GotsmanLinial.ProjectionTrace +OAI.Combinatorics.GotsmanLinial.ScalarIncrements +OAI.Combinatorics.GotsmanLinial.SignParity +OAI.Combinatorics.GotsmanLinial.Statement +OAI.Combinatorics.GotsmanLinial.Walsh +OAI.Combinatorics.GotsmanLinial.WalshDimensions +OAI.Combinatorics.GotsmanLinial.WeightedGrading diff --git a/tasks/gotsman-linial/solution/reference.py b/tasks/gotsman-linial/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/gotsman-linial/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/gotsman-linial/solution/solve.sh b/tasks/gotsman-linial/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..976729274923c4de2cade1966f0b1205e7054a06 --- /dev/null +++ b/tasks/gotsman-linial/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GotsmanLinial, i.e. module OAI.Combinatorics.GotsmanLinial.Main and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.GotsmanLinial.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GotsmanLinial" diff --git a/tasks/gotsman-linial/task.toml b/tasks/gotsman-linial/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a82b5eaebec4bb6e6507a3b8084460a1752309c9 --- /dev/null +++ b/tasks/gotsman-linial/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/gotsman-linial" +version = "1.0.0" +description = "Prove GotsmanLinial (openai/math family 127: The asymptotic Gotsman–Linial conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GotsmanLinial.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GotsmanLinial" +family = "127" +family_title = "The asymptotic Gotsman–Linial conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.LeanBlast.GotsmanLinial.gotsmanLinialStatement"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.GotsmanLinial.Main" +reference_modules = 22 +reference_lean_bytes = 172016 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 728 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11854 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/gotsman-linial/tests/Challenge.lean b/tasks/gotsman-linial/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..98080b0b24e286e5802b8aef4f155ae11ceeb802 --- /dev/null +++ b/tasks/gotsman-linial/tests/Challenge.lean @@ -0,0 +1,54 @@ +import Mathlib.Algebra.MvPolynomial.Degrees +import Mathlib.Algebra.BigOperators.Field +import Mathlib.Data.Fintype.BigOperators +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Tactic.NormNum + +namespace OAI + +open scoped BigOperators + +namespace LeanBlast.GotsmanLinial + +abbrev Cube (n : ℕ) := Fin n → Bool + +def cubeCoord {n : ℕ} (x : Cube n) (i : Fin n) : ℝ := + if x i then 1 else -1 + +def flip {n : ℕ} (i : Fin n) (x : Cube n) : Cube n := + Function.update x i (!(x i)) + +noncomputable def thresholdSign (t : ℝ) : ℝ := + if 0 ≤ t then 1 else -1 + +noncomputable def sensitiveVertices {n : ℕ} (f : Cube n → ℝ) (i : Fin n) : + Finset (Cube n) := by + classical + exact Finset.univ.filter fun x => f x ≠ f (flip i x) + +noncomputable def averageSensitivity {n : ℕ} (f : Cube n → ℝ) : ℝ := + ∑ i : Fin n, ((sensitiveVertices f i).card : ℝ) / (2 : ℝ) ^ n + +def IsMultilinear {n : ℕ} (p : MvPolynomial (Fin n) ℝ) : Prop := + ∀ m ∈ p.support, ∀ i : Fin n, m i ≤ 1 + +noncomputable def polynomialValue {n : ℕ} (p : MvPolynomial (Fin n) ℝ) + (x : Cube n) : ℝ := + MvPolynomial.eval (cubeCoord x) p + +noncomputable def polynomialThreshold {n : ℕ} (p : MvPolynomial (Fin n) ℝ) : + Cube n → ℝ := + fun x => thresholdSign (polynomialValue p x) + +def GotsmanLinialStatement : Prop := + ∀ (n d : ℕ), 1 ≤ n → 1 ≤ d → d ≤ n → + ∀ p : MvPolynomial (Fin n) ℝ, + IsMultilinear p → p.totalDegree ≤ d → + averageSensitivity (polynomialThreshold p) ≤ 8 * (d : ℝ) * Real.sqrt (n : ℝ) + +theorem gotsmanLinialStatement : GotsmanLinialStatement := by + sorry + +end LeanBlast.GotsmanLinial + +end OAI diff --git a/tasks/gotsman-linial/tests/grade.py b/tasks/gotsman-linial/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/gotsman-linial/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/gotsman-linial/tests/task.json b/tasks/gotsman-linial/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a7cc7247def03d7cf4d2d5dd8c18ee6d180be272 --- /dev/null +++ b/tasks/gotsman-linial/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GotsmanLinial", + "comparator": { + "theorem_names": [ + "OAI.LeanBlast.GotsmanLinial.gotsmanLinialStatement" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10954 +} \ No newline at end of file diff --git a/tasks/gotsman-linial/tests/test.sh b/tasks/gotsman-linial/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/gotsman-linial/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/graham-spherical/environment/Dockerfile b/tasks/graham-spherical/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/graham-spherical/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/graham-spherical/environment/fetch_mathlib.sh b/tasks/graham-spherical/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/graham-spherical/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/graham-spherical/environment/lake-manifest.json b/tasks/graham-spherical/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/graham-spherical/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/graham-spherical/environment/lakefile.lean b/tasks/graham-spherical/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/graham-spherical/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/graham-spherical/environment/lean_setup.sh b/tasks/graham-spherical/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/graham-spherical/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/graham-spherical/environment/pack_submission.py b/tasks/graham-spherical/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/graham-spherical/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/graham-spherical/instruction.md b/tasks/graham-spherical/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..27e2431bc5c2e9a7d8265dcda784a086a0459792 --- /dev/null +++ b/tasks/graham-spherical/instruction.md @@ -0,0 +1,116 @@ +# openai/math challenge `GrahamSpherical` (family 172) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 172 of the release, *Classification of finite Euclidean Ramsey configurations* +(Combinatorics). The family as a whole: Classifies finite point configurations that occur monochromatically, at their original scale, in every finite coloring of sufficiently high-dimensional Euclidean space. The characterization is an algebraic condition over the coordinate field. It also disproves the Leader–Russell–Walters conjecture that every such configuration is a subset of a finite transitive set. + +The challenge is `GrahamSpherical`, also at `/opt/openai-math/challenges/GrahamSpherical.lean`: + +```lean +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Topology.Algebra.InfiniteSum.Real + +namespace OAI + +noncomputable section + +namespace GrahamSpherical + +abbrev Point (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev Label := Fin 3 × Fin 4 + +def parameter : ℝ := ∑' m : ℕ, 1 / (10 : ℝ) ^ ((m + 1).factorial) + +def u : ℝ := (1 - parameter ^ 2) / (1 + parameter ^ 2) +def v : ℝ := (2 * parameter) / (1 + parameter ^ 2) + +def squareCoordinate (q : Fin 4) : Fin 2 → ℝ := + if q = 0 then ![1, 0] else + if q = 1 then ![-1, 0] else + if q = 2 then ![0, 1] else ![0, -1] + +def coordinates (i : Label) : Fin 2 → ℝ := + let q := squareCoordinate i.2 + if i.1 = 0 then ![u * q 0 - v * q 1, v * q 0 + u * q 1] else + if i.1 = 1 then ![u * q 0 + v * q 1, -v * q 0 + u * q 1] else q + +def vertex (i : Label) : Point 2 := WithLp.toLp 2 (coordinates i) + +def witness : Set (Point 2) := Set.range vertex + +def AvoidsCopy {d n r : ℕ} (X : Set (Point d)) (color : Point n → Fin r) : Prop := + ¬ ∃ f : X → Point n, Isometry f ∧ ∃ c : Fin r, ∀ x, color (f x) = c + +def EuclideanRamsey {d : ℕ} (X : Set (Point d)) : Prop := + ∀ r : ℕ, 0 < r → ∃ n : ℕ, 0 < n ∧ + ∀ color : Point n → Fin r, + ∃ f : X → Point n, Isometry f ∧ ∃ c : Fin r, ∀ x, color (f x) = c + +end GrahamSpherical + +end + +namespace GrahamSpherical.Specification + +def FullAuthoredResult : Prop := + witness.ncard = 12 ∧ + witness ⊆ Metric.sphere (0 : Point 2) 1 ∧ + (∀ n : ℕ, 0 < n → ∃ color : Point n → Fin 50, AvoidsCopy witness color) ∧ + ¬ EuclideanRamsey witness + +end GrahamSpherical.Specification + +noncomputable section + +namespace GrahamSpherical + +theorem full_main : Specification.FullAuthoredResult := by + sorry + +end GrahamSpherical + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GrahamSpherical.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GrahamSpherical.full_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/graham-spherical/solution/closure.txt b/tasks/graham-spherical/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8f64ee9e024942a224d205dfaa88ad83d9d44d4a --- /dev/null +++ b/tasks/graham-spherical/solution/closure.txt @@ -0,0 +1,18 @@ +OAI.Combinatorics.SphericalRamsey.AffineCopy +OAI.Combinatorics.SphericalRamsey.AffineCopyCore +OAI.Combinatorics.SphericalRamsey.AlgebraicExtension +OAI.Combinatorics.SphericalRamsey.BasisDerivation +OAI.Combinatorics.SphericalRamsey.Coloring +OAI.Combinatorics.SphericalRamsey.CopyInvariant +OAI.Combinatorics.SphericalRamsey.DerivationCoordinates +OAI.Combinatorics.SphericalRamsey.EnergyIdentity +OAI.Combinatorics.SphericalRamsey.Main +OAI.Combinatorics.SphericalRamsey.Model +OAI.Combinatorics.SphericalRamsey.MonochromaticObstruction +OAI.Combinatorics.SphericalRamsey.Parameter +OAI.Combinatorics.SphericalRamsey.Ramsey +OAI.Combinatorics.SphericalRamsey.RealDerivation +OAI.Combinatorics.SphericalRamsey.RealTranscendenceBasis +OAI.Combinatorics.SphericalRamsey.Specification +OAI.Combinatorics.SphericalRamsey.WitnessCoordinates +OAI.Combinatorics.SphericalRamsey.WitnessScalars diff --git a/tasks/graham-spherical/solution/reference.py b/tasks/graham-spherical/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/graham-spherical/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/graham-spherical/solution/solve.sh b/tasks/graham-spherical/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5ba8da70d256b7fcd4abd23a66db139e843cce3c --- /dev/null +++ b/tasks/graham-spherical/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GrahamSpherical, i.e. module OAI.Combinatorics.SphericalRamsey.Main and the +# 18 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.SphericalRamsey.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GrahamSpherical" diff --git a/tasks/graham-spherical/task.toml b/tasks/graham-spherical/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a595b1f861680710eb15d6608c20266d336e0d68 --- /dev/null +++ b/tasks/graham-spherical/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/graham-spherical" +version = "1.0.0" +description = "Prove GrahamSpherical (openai/math family 172: Classification of finite Euclidean Ramsey configurations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GrahamSpherical.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GrahamSpherical" +family = "172" +family_title = "Classification of finite Euclidean Ramsey configurations" +subject = "Combinatorics" +theorems = ["OAI.GrahamSpherical.full_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.SphericalRamsey.Main" +reference_modules = 18 +reference_lean_bytes = 38396 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 751 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11734 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/graham-spherical/tests/Challenge.lean b/tasks/graham-spherical/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..374d630d3bdc64c298ff362e778d9a967509f331 --- /dev/null +++ b/tasks/graham-spherical/tests/Challenge.lean @@ -0,0 +1,65 @@ +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Topology.Algebra.InfiniteSum.Real + +namespace OAI + +noncomputable section + +namespace GrahamSpherical + +abbrev Point (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev Label := Fin 3 × Fin 4 + +def parameter : ℝ := ∑' m : ℕ, 1 / (10 : ℝ) ^ ((m + 1).factorial) + +def u : ℝ := (1 - parameter ^ 2) / (1 + parameter ^ 2) +def v : ℝ := (2 * parameter) / (1 + parameter ^ 2) + +def squareCoordinate (q : Fin 4) : Fin 2 → ℝ := + if q = 0 then ![1, 0] else + if q = 1 then ![-1, 0] else + if q = 2 then ![0, 1] else ![0, -1] + +def coordinates (i : Label) : Fin 2 → ℝ := + let q := squareCoordinate i.2 + if i.1 = 0 then ![u * q 0 - v * q 1, v * q 0 + u * q 1] else + if i.1 = 1 then ![u * q 0 + v * q 1, -v * q 0 + u * q 1] else q + +def vertex (i : Label) : Point 2 := WithLp.toLp 2 (coordinates i) + +def witness : Set (Point 2) := Set.range vertex + +def AvoidsCopy {d n r : ℕ} (X : Set (Point d)) (color : Point n → Fin r) : Prop := + ¬ ∃ f : X → Point n, Isometry f ∧ ∃ c : Fin r, ∀ x, color (f x) = c + +def EuclideanRamsey {d : ℕ} (X : Set (Point d)) : Prop := + ∀ r : ℕ, 0 < r → ∃ n : ℕ, 0 < n ∧ + ∀ color : Point n → Fin r, + ∃ f : X → Point n, Isometry f ∧ ∃ c : Fin r, ∀ x, color (f x) = c + +end GrahamSpherical + +end + +namespace GrahamSpherical.Specification + +def FullAuthoredResult : Prop := + witness.ncard = 12 ∧ + witness ⊆ Metric.sphere (0 : Point 2) 1 ∧ + (∀ n : ℕ, 0 < n → ∃ color : Point n → Fin 50, AvoidsCopy witness color) ∧ + ¬ EuclideanRamsey witness + +end GrahamSpherical.Specification + +noncomputable section + +namespace GrahamSpherical + +theorem full_main : Specification.FullAuthoredResult := by + sorry + +end GrahamSpherical + +end + +end OAI diff --git a/tasks/graham-spherical/tests/grade.py b/tasks/graham-spherical/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/graham-spherical/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/graham-spherical/tests/task.json b/tasks/graham-spherical/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6b0935a973bc11fb7060f4bbc0f51f70fafa7d7c --- /dev/null +++ b/tasks/graham-spherical/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GrahamSpherical", + "comparator": { + "theorem_names": [ + "OAI.GrahamSpherical.full_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10834 +} \ No newline at end of file diff --git a/tasks/graham-spherical/tests/test.sh b/tasks/graham-spherical/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/graham-spherical/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/grothendieck-elementary-expansion/environment/Dockerfile b/tasks/grothendieck-elementary-expansion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/grothendieck-elementary-expansion/environment/fetch_mathlib.sh b/tasks/grothendieck-elementary-expansion/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/grothendieck-elementary-expansion/environment/lake-manifest.json b/tasks/grothendieck-elementary-expansion/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/grothendieck-elementary-expansion/environment/lakefile.lean b/tasks/grothendieck-elementary-expansion/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/grothendieck-elementary-expansion/environment/lean_setup.sh b/tasks/grothendieck-elementary-expansion/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/grothendieck-elementary-expansion/environment/pack_submission.py b/tasks/grothendieck-elementary-expansion/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/grothendieck-elementary-expansion/instruction.md b/tasks/grothendieck-elementary-expansion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc6ea87bee33d1034074cf3df01086e40bc94856 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/instruction.md @@ -0,0 +1,527 @@ +# openai/math challenge `GrothendieckElementaryExpansion` (family 312) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 312 of the release, *The Grothendieck homotopy hypothesis* +(Topology). The family as a whole: Proves the Grothendieck homotopy hypothesis for $\infty$-groupoids associated with every Grothendieck coherator in the Ara–Henry convention: these algebraic objects recover the homotopy theory of spaces. + +The challenge is `GrothendieckElementaryExpansion`, also at `/opt/openai-math/challenges/GrothendieckElementaryExpansion.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u v w + +namespace Grothendieck + +structure GlobularSet where + Cell : ℕ → Type u + source : ∀ n, Cell (n + 1) → Cell n + target : ∀ n, Cell (n + 1) → Cell n + source_source : ∀ n x, source n (source (n + 1) x) = source n (target (n + 1) x) + target_source : ∀ n x, target n (source (n + 1) x) = target n (target (n + 1) x) + +namespace GlobularSet + +@[ext] +structure Hom (X Y : GlobularSet.{u}) where + app : ∀ n, X.Cell n → Y.Cell n + source_app : ∀ n x, app n (X.source n x) = Y.source n (app (n + 1) x) + target_app : ∀ n x, app n (X.target n x) = Y.target n (app (n + 1) x) + +def Parallel (X : GlobularSet.{u}) : ∀ n, X.Cell n → X.Cell n → Prop + | 0, _, _ => True + | n + 1, x, y => X.source n x = X.source n y ∧ X.target n x = X.target n y + +def Joined (X : GlobularSet.{u}) (n : ℕ) (x y : X.Cell n) : Prop := + ∃ h : X.Cell (n + 1), X.source n h = x ∧ X.target n h = y + +def Boundary (X : GlobularSet.{u}) : ℕ → Type u + | 0 => PUnit + | n + 1 => { p : X.Cell n × X.Cell n // X.Parallel n p.1 p.2 } + +def boundary (X : GlobularSet.{u}) : ∀ n, X.Cell n → X.Boundary n + | 0, _ => PUnit.unit + | n + 1, x => ⟨(X.source n x, X.target n x), by + cases n with + | zero => trivial + | succ n => exact ⟨X.source_source n x, X.target_source n x⟩⟩ + +def Hom.boundaryMap {X Y : GlobularSet.{u}} (f : Hom X Y) : ∀ n, X.Boundary n → Y.Boundary n + | 0, _ => PUnit.unit + | n + 1, b => ⟨(f.app n b.1.1, f.app n b.1.2), by + cases n with + | zero => trivial + | succ n => + exact ⟨by rw [← f.source_app, ← f.source_app, b.2.1], + by rw [← f.target_app, ← f.target_app, b.2.2]⟩⟩ + +end GlobularSet + +open CategoryTheory CategoryTheory.Limits Opposite + +@[ext] +structure Globe where + dim : ℕ + +namespace Globe + +inductive Face : ℕ → ℕ → Type + | id (n : ℕ) : Face n n + | face {m n : ℕ} (lt : m < n) (side : Bool) : Face m n + +namespace Face + +def comp {m n k : ℕ} : Face m n → Face n k → Face m k + | .id _, g => g + | .face h b, .id _ => .face h b + | .face h b, .face h' _ => .face (h.trans h') b + +end Face + +instance : Category Globe where + Hom m n := Face m.dim n.dim + id m := .id m.dim + comp := Face.comp + id_comp _ := rfl + comp_id {X Y} f := by cases X; cases Y; cases f <;> rfl + assoc {W X Y Z} f g h := by + cases W; cases X; cases Y; cases Z + cases f <;> cases g <;> cases h <;> rfl + +def face {m n : ℕ} (h : m < n) (side : Bool) : Globe.mk m ⟶ Globe.mk n := + Face.face h side + +def source (n : ℕ) : Globe.mk n ⟶ Globe.mk (n + 1) := face (Nat.lt_succ_self n) false + +def target (n : ℕ) : Globe.mk n ⟶ Globe.mk (n + 1) := face (Nat.lt_succ_self n) true + +end Globe + +abbrev GlobularPresheaf := Globeᵒᵖ ⥤ Type u + +namespace GlobularPresheaf + +def underlying (X : GlobularPresheaf.{u}) : GlobularSet.{u} where + Cell n := X.obj (op (Globe.mk n)) + source n := X.map (Globe.source n).op + target n := X.map (Globe.target n).op + source_source n x := by + have h := congrArg (fun f => X.map f) (congrArg Quiver.Hom.op (show Globe.source n ≫ Globe.source (n + 1) = Globe.source n ≫ Globe.target (n + 1) from rfl)) + simpa only [op_comp, X.map_comp, types_comp_apply] using ConcreteCategory.congr_hom h x + target_source n x := by + have h := congrArg (fun f => X.map f) (congrArg Quiver.Hom.op (show Globe.target n ≫ Globe.source (n + 1) = Globe.target n ≫ Globe.target (n + 1) from rfl)) + simpa only [op_comp, X.map_comp, types_comp_apply] using ConcreteCategory.congr_hom h x + +def underlyingMap {X Y : GlobularPresheaf.{u}} (f : X ⟶ Y) : X.underlying.Hom Y.underlying where + app n := f.app (op (Globe.mk n)) + source_app n x := by + exact ConcreteCategory.congr_hom (f.naturality (Globe.source n).op) x + target_app n x := by + exact ConcreteCategory.congr_hom (f.naturality (Globe.target n).op) x + +def disk (n : ℕ) : GlobularPresheaf.{u} := uliftYoneda.{u}.obj (Globe.mk n) + +def face {m n : ℕ} (h : m < n) (side : Bool) : disk.{u} m ⟶ disk.{u} n := + uliftYoneda.{u}.map (Globe.face h side) + +end GlobularPresheaf + +inductive Table : ℕ → Type + | globe (n : ℕ) : Table n + | attach {last : ℕ} (T : Table last) (b h : ℕ) (left : b < last) (right : b < h) : Table h + +namespace Table + +def height : {n : ℕ} → Table n → ℕ + | _, .globe n => n + | _, .attach T _ h _ _ => max T.height h + +noncomputable def realizeWithLast : {n : ℕ} → Table n → + (Σ X : GlobularPresheaf.{0}, GlobularPresheaf.disk n ⟶ X) + | _, .globe n => ⟨GlobularPresheaf.disk n, 𝟙 _⟩ + | _, .attach T _ h hl hr => + let prev := T.realizeWithLast + let f := GlobularPresheaf.face hl true ≫ prev.2 + let g := GlobularPresheaf.face hr false + ⟨pushout f g, pushout.inr f g⟩ + +noncomputable def realize {n} (T : Table n) : GlobularPresheaf.{0} := T.realizeWithLast.1 + +noncomputable def lastInclusion {n} (T : Table n) : GlobularPresheaf.disk n ⟶ T.realize := + T.realizeWithLast.2 + +end Table + +abbrev Shape := Σ n, Table n + +namespace Shape + +noncomputable def realize (S : Shape) : GlobularPresheaf.{0} := S.2.realize + +def height (S : Shape) : ℕ := S.2.height + +def globe (n : ℕ) : Shape := ⟨n, Table.globe n⟩ + +noncomputable instance : Category Shape where + Hom S T := S.realize ⟶ T.realize + id S := 𝟙 S.realize + comp f g := f ≫ g + id_comp := Category.id_comp + comp_id := Category.comp_id + assoc := Category.assoc + +noncomputable def face {m n : ℕ} (h : m < n) (side : Bool) : globe m ⟶ globe n := + GlobularPresheaf.face h side + +noncomputable def source (n : ℕ) : globe n ⟶ globe (n + 1) := face (Nat.lt_succ_self n) false + +noncomputable def target (n : ℕ) : globe n ⟶ globe (n + 1) := face (Nat.lt_succ_self n) true + +def attach (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : Shape := + ⟨h, Table.attach S.2 b h hl hr⟩ + +noncomputable def seam (S : Shape) {b : ℕ} (hl : b < S.1) : globe b ⟶ S := + show GlobularPresheaf.disk b ⟶ S.realize from + GlobularPresheaf.face hl true ≫ S.2.lastInclusion + +noncomputable def inl (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : + S ⟶ S.attach b h hl hr := + pushout.inl (GlobularPresheaf.face hl true ≫ S.2.lastInclusion) + (GlobularPresheaf.face hr false) + +noncomputable def inr (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : + globe h ⟶ S.attach b h hl hr := + pushout.inr (GlobularPresheaf.face hl true ≫ S.2.lastInclusion) + (GlobularPresheaf.face hr false) + +end Shape + +structure TheoryData where + Hom : Shape → Shape → Type v + id : ∀ S, Hom S S + comp : ∀ {S T U}, Hom S T → Hom T U → Hom S U + id_comp : ∀ {S T} (f : Hom S T), comp (id S) f = f + comp_id : ∀ {S T} (f : Hom S T), comp f (id T) = f + assoc : ∀ {R S T U} (f : Hom R S) (g : Hom S T) (h : Hom T U), + comp (comp f g) h = comp f (comp g h) + base : ∀ {S T}, (S ⟶ T) → Hom S T + base_id : ∀ S, base (𝟙 S) = id S + base_comp : ∀ {R S T} (f : R ⟶ S) (g : S ⟶ T), base (f ≫ g) = comp (base f) (base g) + +namespace TheoryData + +structure Obj (C : TheoryData.{v}) where + shape : Shape + +instance (C : TheoryData.{v}) : Category C.Obj where + Hom S T := C.Hom S.shape T.shape + id S := C.id S.shape + comp f g := C.comp f g + id_comp := C.id_comp + comp_id := C.comp_id + assoc := C.assoc + +noncomputable def arity (C : TheoryData.{v}) : Shape ⥤ C.Obj where + obj S := ⟨S⟩ + map f := C.base f + map_id := C.base_id + map_comp := C.base_comp + +def PreservesGlobularSums (C : TheoryData.{v}) : Prop := + ∀ (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h), + IsPushout (C.arity.map (S.seam hl)) (C.arity.map (Shape.face hr false)) + (C.arity.map (S.inl b h hl hr)) (C.arity.map (S.inr b h hl hr)) + +end TheoryData + +structure GlobularTheory extends TheoryData.{v} where + sums : toTheoryData.PreservesGlobularSums + +namespace GlobularTheory + +abbrev Obj (C : GlobularTheory.{v}) := C.toTheoryData.Obj + +@[ext] +structure Morphism (C D : GlobularTheory.{v}) where + map : ∀ {S T}, C.Hom S T → D.Hom S T + map_id : ∀ S, map (C.id S) = D.id S + map_comp : ∀ {R S T} (f : C.Hom R S) (g : C.Hom S T), + map (C.comp f g) = D.comp (map f) (map g) + map_base : ∀ {S T} (f : S ⟶ T), map (C.base f) = D.base f + +namespace Morphism + +def id (C : GlobularTheory.{v}) : Morphism C C where + map f := f + map_id _ := rfl + map_comp _ _ := rfl + map_base _ := rfl + +def comp {C D E : GlobularTheory.{v}} (f : Morphism C D) (g : Morphism D E) : Morphism C E where + map a := g.map (f.map a) + map_id S := by rw [f.map_id, g.map_id] + map_comp a b := by rw [f.map_comp, g.map_comp] + map_base a := by rw [f.map_base, g.map_base] + +end Morphism + +def Parallel (C : GlobularTheory.{v}) {S : Shape} : + ∀ n, C.Hom (Shape.globe n) S → C.Hom (Shape.globe n) S → Prop + | 0, _, _ => True + | n + 1, f, g => + C.comp (C.base (Shape.source n)) f = C.comp (C.base (Shape.source n)) g ∧ + C.comp (C.base (Shape.target n)) f = C.comp (C.base (Shape.target n)) g + +structure AdmissiblePair (C : GlobularTheory.{v}) where + n : ℕ + arity : Shape + height : arity.height ≤ n + 1 + source : C.Hom (Shape.globe n) arity + target : C.Hom (Shape.globe n) arity + parallel : C.Parallel n source target + +def Fills {C D : GlobularTheory.{v}} (f : Morphism C D) (p : C.AdmissiblePair) + (z : D.Hom (Shape.globe (p.n + 1)) p.arity) : Prop := + D.comp (D.base (Shape.source p.n)) z = f.map p.source ∧ + D.comp (D.base (Shape.target p.n)) z = f.map p.target + +def IsFreeExtension {C D : GlobularTheory.{v}} (f : Morphism C D) + (G : Type v) (pair : G → C.AdmissiblePair) + (filler : ∀ g, D.Hom (Shape.globe ((pair g).n + 1)) (pair g).arity) : Prop := + (∀ g, Fills f (pair g) (filler g)) ∧ + ∀ (E : GlobularTheory.{v}) (a : Morphism C E) + (chosen : ∀ g, E.Hom (Shape.globe ((pair g).n + 1)) (pair g).arity), + (∀ g, Fills a (pair g) (chosen g)) → + ∃! b : Morphism D E, f.comp b = a ∧ ∀ g, b.map (filler g) = chosen g + +structure CellularPresentation (C : GlobularTheory.{v}) where + stage : ℕ → GlobularTheory.{v} + initial : ∀ D : GlobularTheory.{v}, Nonempty (Unique (Morphism (stage 0) D)) + step : ∀ r, Morphism (stage r) (stage (r + 1)) + generators : ℕ → Type v + pair : ∀ r, generators r → (stage r).AdmissiblePair + filler : ∀ r g, (stage (r + 1)).Hom (Shape.globe ((pair r g).n + 1)) (pair r g).arity + free : ∀ r, IsFreeExtension (step r) (generators r) (pair r) (filler r) + inclusion : ∀ r, Morphism (stage r) C + compatible : ∀ r, (step r).comp (inclusion (r + 1)) = inclusion r + colimit : ∀ (D : GlobularTheory.{v}) (a : ∀ r, Morphism (stage r) D), + (∀ r, (step r).comp (a (r + 1)) = a r) → + ∃! b : Morphism C D, ∀ r, (inclusion r).comp b = a r + +def IsCoherator (C : GlobularTheory.{v}) : Prop := + Nonempty C.CellularPresentation ∧ + ∀ p : C.AdmissiblePair, ∃ z, Fills (Morphism.id C) p z + +noncomputable def shapeGlobes : Globe ⥤ Shape where + obj n := Shape.globe n.dim + map f := uliftYoneda.map f + map_id n := by exact uliftYoneda.map_id n + map_comp f g := by exact uliftYoneda.map_comp f g + +noncomputable def globes (C : GlobularTheory.{v}) : Globe ⥤ C.Obj := + shapeGlobes ⋙ C.toTheoryData.arity + +structure Model (C : GlobularTheory.{v}) where + presheaf : C.Objᵒᵖ ⥤ Type v + sums : ∀ (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h), + IsPullback + (presheaf.map (C.toTheoryData.arity.map (S.inl b h hl hr)).op) + (presheaf.map (C.toTheoryData.arity.map (S.inr b h hl hr)).op) + (presheaf.map (C.toTheoryData.arity.map (S.seam hl)).op) + (presheaf.map (C.toTheoryData.arity.map (Shape.face hr false)).op) + +namespace Model + +instance (C : GlobularTheory.{v}) : Category C.Model where + Hom X Y := X.presheaf ⟶ Y.presheaf + id X := 𝟙 X.presheaf + comp f g := f ≫ g + id_comp := Category.id_comp + comp_id := Category.comp_id + assoc := Category.assoc + +noncomputable def underlying {C : GlobularTheory.{v}} (X : C.Model) : GlobularSet.{v} := + GlobularPresheaf.underlying (C.globes.op ⋙ X.presheaf) + +noncomputable def underlyingMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) : + X.underlying.Hom Y.underlying := + GlobularPresheaf.underlyingMap (Functor.whiskerLeft C.globes.op f) + +noncomputable def freeShape (C : GlobularTheory.{v}) (S : Shape) : C.Model where + presheaf := yoneda.obj ⟨S⟩ + sums T b h hl hr := ((C.sums T b h hl hr).op.map (yoneda.obj ⟨S⟩)).flip + +noncomputable def disk (C : GlobularTheory.{v}) (n : ℕ) : C.Model := + freeShape C (Shape.globe n) + +noncomputable def J (C : GlobularTheory.{v}) (n : ℕ) : disk C n ⟶ disk C (n + 1) := + show (disk C n).presheaf ⟶ (disk C (n + 1)).presheaf from + yoneda.map (C.toTheoryData.arity.map (Shape.source n)) + +structure BoundaryAttachment {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) where + index : Type v + dimension : index → ℕ + boundary : ∀ k, X.underlying.Boundary (dimension k) + cell : ∀ k, Y.underlying.Cell (dimension k) + cell_boundary : ∀ k, Y.underlying.boundary _ (cell k) = + (underlyingMap f).boundaryMap _ (boundary k) + universal : ∀ (Z : C.Model) (g : X ⟶ Z) + (z : ∀ k, Z.underlying.Cell (dimension k)), + (∀ k, Z.underlying.boundary _ (z k) = (underlyingMap g).boundaryMap _ (boundary k)) → + ∃! h : Y ⟶ Z, f ≫ h = g ∧ ∀ k, (underlyingMap h).app _ (cell k) = z k + +structure CellularPresentation {C : GlobularTheory.{v}} (X : C.Model) where + order : Type v + linearOrder : LinearOrder order + orderBot : OrderBot order + succOrder : SuccOrder order + wellFoundedLT : WellFoundedLT order + initial : C.Model + isInitial : IsInitial initial + start : initial ⟶ X + chain : @TransfiniteCompositionOfShape _ _ order linearOrder orderBot + _ _ start succOrder wellFoundedLT + attachment : ∀ j, ¬ IsMax j → BoundaryAttachment + (chain.F.map (homOfLE (Order.le_succ j))) + +def IsCellular {C : GlobularTheory.{v}} (X : C.Model) : Prop := Nonempty X.CellularPresentation + +end Model + +def unitPair (C : GlobularTheory.{v}) (n : ℕ) : C.AdmissiblePair where + n := n + arity := Shape.globe n + height := Nat.le_succ n + source := C.id (Shape.globe n) + target := C.id (Shape.globe n) + parallel := by cases n <;> simp [Parallel] + +noncomputable def unit (C : GlobularTheory.{v}) (hC : C.IsCoherator) (n : ℕ) : + C.Hom (Shape.globe (n + 1)) (Shape.globe n) := Classical.choose (hC.2 (C.unitPair n)) + +def Model.eval {C : GlobularTheory.{v}} (X : C.Model) {S T : Shape} (f : C.Hom S T) : + X.presheaf.obj (op (⟨T⟩ : C.Obj)) → X.presheaf.obj (op (⟨S⟩ : C.Obj)) := + X.presheaf.map (show (⟨S⟩ : C.Obj) ⟶ ⟨T⟩ from f).op + +noncomputable def Model.unitCell {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (n : ℕ) (x : X.underlying.Cell n) : X.underlying.Cell (n + 1) := + X.eval (C.unit hC n) x + +noncomputable def Model.baseCell {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) : ∀ n, X.underlying.Cell n + | 0 => x + | n + 1 => X.unitCell hC n (X.baseCell hC x n) + +def Model.Loops {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) (n : ℕ) : Type v := + { z : X.underlying.Cell (n + 1) // X.underlying.source n z = X.baseCell hC x n ∧ + X.underlying.target n z = X.baseCell hC x n } + +def Model.Components {C : GlobularTheory.{v}} (X : C.Model) : Type v := + Quot (X.underlying.Joined 0) + +def Model.HomotopyGroup {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) (n : ℕ) : Type v := + Quot (fun a b : X.Loops hC x n => X.underlying.Joined (n + 1) a.1 b.1) + +noncomputable def Model.loopsMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) + (hC : C.IsCoherator) (x : X.underlying.Cell 0) (n : ℕ) : + X.Loops hC x n → Y.Loops hC ((underlyingMap f).app 0 x) n := by + have hb : ∀ k, (underlyingMap f).app k (X.baseCell hC x k) = + Y.baseCell hC ((underlyingMap f).app 0 x) k := by + intro k + induction k with + | zero => rfl + | succ k ih => + have h := ConcreteCategory.congr_hom (f.naturality + (show (op (⟨Shape.globe k⟩ : C.Obj)) ⟶ op ⟨Shape.globe (k+1)⟩ from + Quiver.Hom.op (C.unit hC k))) (X.baseCell hC x k) + change (underlyingMap f).app (k+1) (X.unitCell hC k (X.baseCell hC x k)) = + Y.unitCell hC k ((underlyingMap f).app k (X.baseCell hC x k)) at h + simpa only [baseCell, ih] using h + exact fun z => ⟨(underlyingMap f).app (n + 1) z.1, + by rw [← (underlyingMap f).source_app, z.2.1, hb], + by rw [← (underlyingMap f).target_app, z.2.2, hb]⟩ + +noncomputable def Model.componentsMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) : + X.Components → Y.Components := + Quot.map ((underlyingMap f).app 0) (by + rintro _ _ ⟨h, hs, ht⟩ + exact ⟨(underlyingMap f).app _ h, + by rw [← (underlyingMap f).source_app, hs], + by rw [← (underlyingMap f).target_app, ht]⟩) + +noncomputable def Model.homotopyMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) + (hC : C.IsCoherator) (x : X.underlying.Cell 0) (n : ℕ) : + X.HomotopyGroup hC x n → Y.HomotopyGroup hC ((underlyingMap f).app 0 x) n := + Quot.map (loopsMap f hC x n) (by + rintro _ _ ⟨h, hs, ht⟩ + exact ⟨(underlyingMap f).app _ h, + by rw [← (underlyingMap f).source_app, hs]; rfl, + by rw [← (underlyingMap f).target_app, ht]; rfl⟩) + +def Model.WeakEquivalence {C : GlobularTheory.{v}} (hC : C.IsCoherator) {X Y : C.Model} + (f : X ⟶ Y) : Prop := + Function.Bijective (componentsMap f) ∧ + ∀ (x : X.underlying.Cell 0) (n : ℕ), Function.Bijective (homotopyMap f hC x n) + +end GlobularTheory + +open CategoryTheory CategoryTheory.Limits + +theorem elementary_expansion (C : GlobularTheory.{v}) (hC : C.IsCoherator) + (X : C.Model) (hX : X.IsCellular) (n : ℕ) + (a : GlobularTheory.Model.disk C n ⟶ X) + (Y : C.Model) (i : X ⟶ Y) + (b : GlobularTheory.Model.disk C (n + 1) ⟶ Y) + (square : IsPushout a (GlobularTheory.Model.J C n) i b) : + GlobularTheory.Model.WeakEquivalence hC i := by + sorry + +end Grothendieck + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GrothendieckElementaryExpansion.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Grothendieck.elementary_expansion` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/grothendieck-elementary-expansion/solution/closure.txt b/tasks/grothendieck-elementary-expansion/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..647e7a008b3e6c9a38fc45c37671d1d0fec4fbc2 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/solution/closure.txt @@ -0,0 +1,58 @@ +OAI.CategoryTheory.Globular.Basic +OAI.CategoryTheory.Globular.Boundary +OAI.CategoryTheory.Globular.BoundaryCells +OAI.CategoryTheory.Globular.Coglobular +OAI.CategoryTheory.Globular.Colimits +OAI.CategoryTheory.Globular.Composition +OAI.CategoryTheory.Globular.CriticalJoint +OAI.CategoryTheory.Globular.Cutoff +OAI.CategoryTheory.Globular.CutoffCells +OAI.CategoryTheory.Globular.CutoffExistence +OAI.CategoryTheory.Globular.CutoffExpansion +OAI.CategoryTheory.Globular.CylinderContractibility +OAI.CategoryTheory.Globular.CylinderExtension +OAI.CategoryTheory.Globular.CylinderFramework +OAI.CategoryTheory.Globular.CylinderGluing +OAI.CategoryTheory.Globular.CylinderInterpretation +OAI.CategoryTheory.Globular.CylinderJointUpper +OAI.CategoryTheory.Globular.CylinderLifting +OAI.CategoryTheory.Globular.CylinderObjects +OAI.CategoryTheory.Globular.CylinderPathLifting +OAI.CategoryTheory.Globular.CylinderPresentations +OAI.CategoryTheory.Globular.CylinderShapes +OAI.CategoryTheory.Globular.CylinderSplitting +OAI.CategoryTheory.Globular.CylinderTheory +OAI.CategoryTheory.Globular.Density +OAI.CategoryTheory.Globular.DiskComparison +OAI.CategoryTheory.Globular.DiskRealization +OAI.CategoryTheory.Globular.ElementaryExpansion +OAI.CategoryTheory.Globular.Expansion +OAI.CategoryTheory.Globular.Factorization +OAI.CategoryTheory.Globular.Fillers +OAI.CategoryTheory.Globular.FrameJoint +OAI.CategoryTheory.Globular.FrameMaps +OAI.CategoryTheory.Globular.FrameOperations +OAI.CategoryTheory.Globular.FrameRealization +OAI.CategoryTheory.Globular.FullCylinder +OAI.CategoryTheory.Globular.Groupoid +OAI.CategoryTheory.Globular.Homotopy +OAI.CategoryTheory.Globular.HomotopyGroups +OAI.CategoryTheory.Globular.LinearCells +OAI.CategoryTheory.Globular.LinearShape +OAI.CategoryTheory.Globular.Main +OAI.CategoryTheory.Globular.Model +OAI.CategoryTheory.Globular.OneSidedPresentation +OAI.CategoryTheory.Globular.Realization +OAI.CategoryTheory.Globular.ReflectedCylinder +OAI.CategoryTheory.Globular.Reflection +OAI.CategoryTheory.Globular.RelativeLifting +OAI.CategoryTheory.Globular.ReverseWhisker +OAI.CategoryTheory.Globular.ShapeFrame +OAI.CategoryTheory.Globular.SkeletalPresentation +OAI.CategoryTheory.Globular.SmallFree +OAI.CategoryTheory.Globular.SmallObject +OAI.CategoryTheory.Globular.SpineWhisker +OAI.CategoryTheory.Globular.Spines +OAI.CategoryTheory.Globular.Tree +OAI.CategoryTheory.Globular.Whisker +OAI.CategoryTheory.Globular.WhiskerUniverse diff --git a/tasks/grothendieck-elementary-expansion/solution/reference.py b/tasks/grothendieck-elementary-expansion/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/grothendieck-elementary-expansion/solution/solve.sh b/tasks/grothendieck-elementary-expansion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f459bef127dcc884b3d4d085bc84399054f3d0f6 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GrothendieckElementaryExpansion, i.e. module OAI.CategoryTheory.Globular.Main and the +# 58 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.CategoryTheory.Globular.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GrothendieckElementaryExpansion" diff --git a/tasks/grothendieck-elementary-expansion/task.toml b/tasks/grothendieck-elementary-expansion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..141e8813d9928c7b987d960d560a917510a38e5e --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/grothendieck-elementary-expansion" +version = "1.0.0" +description = "Prove GrothendieckElementaryExpansion (openai/math family 312: The Grothendieck homotopy hypothesis) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "topology"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GrothendieckElementaryExpansion.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GrothendieckElementaryExpansion" +family = "312" +family_title = "The Grothendieck homotopy hypothesis" +subject = "Topology" +theorems = ["OAI.Grothendieck.elementary_expansion"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.CategoryTheory.Globular.Main" +reference_modules = 58 +reference_lean_bytes = 580875 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1113 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12222 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/grothendieck-elementary-expansion/tests/Challenge.lean b/tasks/grothendieck-elementary-expansion/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6d29a8739830ee5d52483648037eccde4677add2 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/tests/Challenge.lean @@ -0,0 +1,476 @@ +import Mathlib + +namespace OAI + +universe u v w + +namespace Grothendieck + +structure GlobularSet where + Cell : ℕ → Type u + source : ∀ n, Cell (n + 1) → Cell n + target : ∀ n, Cell (n + 1) → Cell n + source_source : ∀ n x, source n (source (n + 1) x) = source n (target (n + 1) x) + target_source : ∀ n x, target n (source (n + 1) x) = target n (target (n + 1) x) + +namespace GlobularSet + +@[ext] +structure Hom (X Y : GlobularSet.{u}) where + app : ∀ n, X.Cell n → Y.Cell n + source_app : ∀ n x, app n (X.source n x) = Y.source n (app (n + 1) x) + target_app : ∀ n x, app n (X.target n x) = Y.target n (app (n + 1) x) + +def Parallel (X : GlobularSet.{u}) : ∀ n, X.Cell n → X.Cell n → Prop + | 0, _, _ => True + | n + 1, x, y => X.source n x = X.source n y ∧ X.target n x = X.target n y + +def Joined (X : GlobularSet.{u}) (n : ℕ) (x y : X.Cell n) : Prop := + ∃ h : X.Cell (n + 1), X.source n h = x ∧ X.target n h = y + +def Boundary (X : GlobularSet.{u}) : ℕ → Type u + | 0 => PUnit + | n + 1 => { p : X.Cell n × X.Cell n // X.Parallel n p.1 p.2 } + +def boundary (X : GlobularSet.{u}) : ∀ n, X.Cell n → X.Boundary n + | 0, _ => PUnit.unit + | n + 1, x => ⟨(X.source n x, X.target n x), by + cases n with + | zero => trivial + | succ n => exact ⟨X.source_source n x, X.target_source n x⟩⟩ + +def Hom.boundaryMap {X Y : GlobularSet.{u}} (f : Hom X Y) : ∀ n, X.Boundary n → Y.Boundary n + | 0, _ => PUnit.unit + | n + 1, b => ⟨(f.app n b.1.1, f.app n b.1.2), by + cases n with + | zero => trivial + | succ n => + exact ⟨by rw [← f.source_app, ← f.source_app, b.2.1], + by rw [← f.target_app, ← f.target_app, b.2.2]⟩⟩ + +end GlobularSet + +open CategoryTheory CategoryTheory.Limits Opposite + +@[ext] +structure Globe where + dim : ℕ + +namespace Globe + +inductive Face : ℕ → ℕ → Type + | id (n : ℕ) : Face n n + | face {m n : ℕ} (lt : m < n) (side : Bool) : Face m n + +namespace Face + +def comp {m n k : ℕ} : Face m n → Face n k → Face m k + | .id _, g => g + | .face h b, .id _ => .face h b + | .face h b, .face h' _ => .face (h.trans h') b + +end Face + +instance : Category Globe where + Hom m n := Face m.dim n.dim + id m := .id m.dim + comp := Face.comp + id_comp _ := rfl + comp_id {X Y} f := by cases X; cases Y; cases f <;> rfl + assoc {W X Y Z} f g h := by + cases W; cases X; cases Y; cases Z + cases f <;> cases g <;> cases h <;> rfl + +def face {m n : ℕ} (h : m < n) (side : Bool) : Globe.mk m ⟶ Globe.mk n := + Face.face h side + +def source (n : ℕ) : Globe.mk n ⟶ Globe.mk (n + 1) := face (Nat.lt_succ_self n) false + +def target (n : ℕ) : Globe.mk n ⟶ Globe.mk (n + 1) := face (Nat.lt_succ_self n) true + +end Globe + +abbrev GlobularPresheaf := Globeᵒᵖ ⥤ Type u + +namespace GlobularPresheaf + +def underlying (X : GlobularPresheaf.{u}) : GlobularSet.{u} where + Cell n := X.obj (op (Globe.mk n)) + source n := X.map (Globe.source n).op + target n := X.map (Globe.target n).op + source_source n x := by + have h := congrArg (fun f => X.map f) (congrArg Quiver.Hom.op (show Globe.source n ≫ Globe.source (n + 1) = Globe.source n ≫ Globe.target (n + 1) from rfl)) + simpa only [op_comp, X.map_comp, types_comp_apply] using ConcreteCategory.congr_hom h x + target_source n x := by + have h := congrArg (fun f => X.map f) (congrArg Quiver.Hom.op (show Globe.target n ≫ Globe.source (n + 1) = Globe.target n ≫ Globe.target (n + 1) from rfl)) + simpa only [op_comp, X.map_comp, types_comp_apply] using ConcreteCategory.congr_hom h x + +def underlyingMap {X Y : GlobularPresheaf.{u}} (f : X ⟶ Y) : X.underlying.Hom Y.underlying where + app n := f.app (op (Globe.mk n)) + source_app n x := by + exact ConcreteCategory.congr_hom (f.naturality (Globe.source n).op) x + target_app n x := by + exact ConcreteCategory.congr_hom (f.naturality (Globe.target n).op) x + +def disk (n : ℕ) : GlobularPresheaf.{u} := uliftYoneda.{u}.obj (Globe.mk n) + +def face {m n : ℕ} (h : m < n) (side : Bool) : disk.{u} m ⟶ disk.{u} n := + uliftYoneda.{u}.map (Globe.face h side) + +end GlobularPresheaf + +inductive Table : ℕ → Type + | globe (n : ℕ) : Table n + | attach {last : ℕ} (T : Table last) (b h : ℕ) (left : b < last) (right : b < h) : Table h + +namespace Table + +def height : {n : ℕ} → Table n → ℕ + | _, .globe n => n + | _, .attach T _ h _ _ => max T.height h + +noncomputable def realizeWithLast : {n : ℕ} → Table n → + (Σ X : GlobularPresheaf.{0}, GlobularPresheaf.disk n ⟶ X) + | _, .globe n => ⟨GlobularPresheaf.disk n, 𝟙 _⟩ + | _, .attach T _ h hl hr => + let prev := T.realizeWithLast + let f := GlobularPresheaf.face hl true ≫ prev.2 + let g := GlobularPresheaf.face hr false + ⟨pushout f g, pushout.inr f g⟩ + +noncomputable def realize {n} (T : Table n) : GlobularPresheaf.{0} := T.realizeWithLast.1 + +noncomputable def lastInclusion {n} (T : Table n) : GlobularPresheaf.disk n ⟶ T.realize := + T.realizeWithLast.2 + +end Table + +abbrev Shape := Σ n, Table n + +namespace Shape + +noncomputable def realize (S : Shape) : GlobularPresheaf.{0} := S.2.realize + +def height (S : Shape) : ℕ := S.2.height + +def globe (n : ℕ) : Shape := ⟨n, Table.globe n⟩ + +noncomputable instance : Category Shape where + Hom S T := S.realize ⟶ T.realize + id S := 𝟙 S.realize + comp f g := f ≫ g + id_comp := Category.id_comp + comp_id := Category.comp_id + assoc := Category.assoc + +noncomputable def face {m n : ℕ} (h : m < n) (side : Bool) : globe m ⟶ globe n := + GlobularPresheaf.face h side + +noncomputable def source (n : ℕ) : globe n ⟶ globe (n + 1) := face (Nat.lt_succ_self n) false + +noncomputable def target (n : ℕ) : globe n ⟶ globe (n + 1) := face (Nat.lt_succ_self n) true + +def attach (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : Shape := + ⟨h, Table.attach S.2 b h hl hr⟩ + +noncomputable def seam (S : Shape) {b : ℕ} (hl : b < S.1) : globe b ⟶ S := + show GlobularPresheaf.disk b ⟶ S.realize from + GlobularPresheaf.face hl true ≫ S.2.lastInclusion + +noncomputable def inl (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : + S ⟶ S.attach b h hl hr := + pushout.inl (GlobularPresheaf.face hl true ≫ S.2.lastInclusion) + (GlobularPresheaf.face hr false) + +noncomputable def inr (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h) : + globe h ⟶ S.attach b h hl hr := + pushout.inr (GlobularPresheaf.face hl true ≫ S.2.lastInclusion) + (GlobularPresheaf.face hr false) + +end Shape + +structure TheoryData where + Hom : Shape → Shape → Type v + id : ∀ S, Hom S S + comp : ∀ {S T U}, Hom S T → Hom T U → Hom S U + id_comp : ∀ {S T} (f : Hom S T), comp (id S) f = f + comp_id : ∀ {S T} (f : Hom S T), comp f (id T) = f + assoc : ∀ {R S T U} (f : Hom R S) (g : Hom S T) (h : Hom T U), + comp (comp f g) h = comp f (comp g h) + base : ∀ {S T}, (S ⟶ T) → Hom S T + base_id : ∀ S, base (𝟙 S) = id S + base_comp : ∀ {R S T} (f : R ⟶ S) (g : S ⟶ T), base (f ≫ g) = comp (base f) (base g) + +namespace TheoryData + +structure Obj (C : TheoryData.{v}) where + shape : Shape + +instance (C : TheoryData.{v}) : Category C.Obj where + Hom S T := C.Hom S.shape T.shape + id S := C.id S.shape + comp f g := C.comp f g + id_comp := C.id_comp + comp_id := C.comp_id + assoc := C.assoc + +noncomputable def arity (C : TheoryData.{v}) : Shape ⥤ C.Obj where + obj S := ⟨S⟩ + map f := C.base f + map_id := C.base_id + map_comp := C.base_comp + +def PreservesGlobularSums (C : TheoryData.{v}) : Prop := + ∀ (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h), + IsPushout (C.arity.map (S.seam hl)) (C.arity.map (Shape.face hr false)) + (C.arity.map (S.inl b h hl hr)) (C.arity.map (S.inr b h hl hr)) + +end TheoryData + +structure GlobularTheory extends TheoryData.{v} where + sums : toTheoryData.PreservesGlobularSums + +namespace GlobularTheory + +abbrev Obj (C : GlobularTheory.{v}) := C.toTheoryData.Obj + +@[ext] +structure Morphism (C D : GlobularTheory.{v}) where + map : ∀ {S T}, C.Hom S T → D.Hom S T + map_id : ∀ S, map (C.id S) = D.id S + map_comp : ∀ {R S T} (f : C.Hom R S) (g : C.Hom S T), + map (C.comp f g) = D.comp (map f) (map g) + map_base : ∀ {S T} (f : S ⟶ T), map (C.base f) = D.base f + +namespace Morphism + +def id (C : GlobularTheory.{v}) : Morphism C C where + map f := f + map_id _ := rfl + map_comp _ _ := rfl + map_base _ := rfl + +def comp {C D E : GlobularTheory.{v}} (f : Morphism C D) (g : Morphism D E) : Morphism C E where + map a := g.map (f.map a) + map_id S := by rw [f.map_id, g.map_id] + map_comp a b := by rw [f.map_comp, g.map_comp] + map_base a := by rw [f.map_base, g.map_base] + +end Morphism + +def Parallel (C : GlobularTheory.{v}) {S : Shape} : + ∀ n, C.Hom (Shape.globe n) S → C.Hom (Shape.globe n) S → Prop + | 0, _, _ => True + | n + 1, f, g => + C.comp (C.base (Shape.source n)) f = C.comp (C.base (Shape.source n)) g ∧ + C.comp (C.base (Shape.target n)) f = C.comp (C.base (Shape.target n)) g + +structure AdmissiblePair (C : GlobularTheory.{v}) where + n : ℕ + arity : Shape + height : arity.height ≤ n + 1 + source : C.Hom (Shape.globe n) arity + target : C.Hom (Shape.globe n) arity + parallel : C.Parallel n source target + +def Fills {C D : GlobularTheory.{v}} (f : Morphism C D) (p : C.AdmissiblePair) + (z : D.Hom (Shape.globe (p.n + 1)) p.arity) : Prop := + D.comp (D.base (Shape.source p.n)) z = f.map p.source ∧ + D.comp (D.base (Shape.target p.n)) z = f.map p.target + +def IsFreeExtension {C D : GlobularTheory.{v}} (f : Morphism C D) + (G : Type v) (pair : G → C.AdmissiblePair) + (filler : ∀ g, D.Hom (Shape.globe ((pair g).n + 1)) (pair g).arity) : Prop := + (∀ g, Fills f (pair g) (filler g)) ∧ + ∀ (E : GlobularTheory.{v}) (a : Morphism C E) + (chosen : ∀ g, E.Hom (Shape.globe ((pair g).n + 1)) (pair g).arity), + (∀ g, Fills a (pair g) (chosen g)) → + ∃! b : Morphism D E, f.comp b = a ∧ ∀ g, b.map (filler g) = chosen g + +structure CellularPresentation (C : GlobularTheory.{v}) where + stage : ℕ → GlobularTheory.{v} + initial : ∀ D : GlobularTheory.{v}, Nonempty (Unique (Morphism (stage 0) D)) + step : ∀ r, Morphism (stage r) (stage (r + 1)) + generators : ℕ → Type v + pair : ∀ r, generators r → (stage r).AdmissiblePair + filler : ∀ r g, (stage (r + 1)).Hom (Shape.globe ((pair r g).n + 1)) (pair r g).arity + free : ∀ r, IsFreeExtension (step r) (generators r) (pair r) (filler r) + inclusion : ∀ r, Morphism (stage r) C + compatible : ∀ r, (step r).comp (inclusion (r + 1)) = inclusion r + colimit : ∀ (D : GlobularTheory.{v}) (a : ∀ r, Morphism (stage r) D), + (∀ r, (step r).comp (a (r + 1)) = a r) → + ∃! b : Morphism C D, ∀ r, (inclusion r).comp b = a r + +def IsCoherator (C : GlobularTheory.{v}) : Prop := + Nonempty C.CellularPresentation ∧ + ∀ p : C.AdmissiblePair, ∃ z, Fills (Morphism.id C) p z + +noncomputable def shapeGlobes : Globe ⥤ Shape where + obj n := Shape.globe n.dim + map f := uliftYoneda.map f + map_id n := by exact uliftYoneda.map_id n + map_comp f g := by exact uliftYoneda.map_comp f g + +noncomputable def globes (C : GlobularTheory.{v}) : Globe ⥤ C.Obj := + shapeGlobes ⋙ C.toTheoryData.arity + +structure Model (C : GlobularTheory.{v}) where + presheaf : C.Objᵒᵖ ⥤ Type v + sums : ∀ (S : Shape) (b h : ℕ) (hl : b < S.1) (hr : b < h), + IsPullback + (presheaf.map (C.toTheoryData.arity.map (S.inl b h hl hr)).op) + (presheaf.map (C.toTheoryData.arity.map (S.inr b h hl hr)).op) + (presheaf.map (C.toTheoryData.arity.map (S.seam hl)).op) + (presheaf.map (C.toTheoryData.arity.map (Shape.face hr false)).op) + +namespace Model + +instance (C : GlobularTheory.{v}) : Category C.Model where + Hom X Y := X.presheaf ⟶ Y.presheaf + id X := 𝟙 X.presheaf + comp f g := f ≫ g + id_comp := Category.id_comp + comp_id := Category.comp_id + assoc := Category.assoc + +noncomputable def underlying {C : GlobularTheory.{v}} (X : C.Model) : GlobularSet.{v} := + GlobularPresheaf.underlying (C.globes.op ⋙ X.presheaf) + +noncomputable def underlyingMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) : + X.underlying.Hom Y.underlying := + GlobularPresheaf.underlyingMap (Functor.whiskerLeft C.globes.op f) + +noncomputable def freeShape (C : GlobularTheory.{v}) (S : Shape) : C.Model where + presheaf := yoneda.obj ⟨S⟩ + sums T b h hl hr := ((C.sums T b h hl hr).op.map (yoneda.obj ⟨S⟩)).flip + +noncomputable def disk (C : GlobularTheory.{v}) (n : ℕ) : C.Model := + freeShape C (Shape.globe n) + +noncomputable def J (C : GlobularTheory.{v}) (n : ℕ) : disk C n ⟶ disk C (n + 1) := + show (disk C n).presheaf ⟶ (disk C (n + 1)).presheaf from + yoneda.map (C.toTheoryData.arity.map (Shape.source n)) + +structure BoundaryAttachment {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) where + index : Type v + dimension : index → ℕ + boundary : ∀ k, X.underlying.Boundary (dimension k) + cell : ∀ k, Y.underlying.Cell (dimension k) + cell_boundary : ∀ k, Y.underlying.boundary _ (cell k) = + (underlyingMap f).boundaryMap _ (boundary k) + universal : ∀ (Z : C.Model) (g : X ⟶ Z) + (z : ∀ k, Z.underlying.Cell (dimension k)), + (∀ k, Z.underlying.boundary _ (z k) = (underlyingMap g).boundaryMap _ (boundary k)) → + ∃! h : Y ⟶ Z, f ≫ h = g ∧ ∀ k, (underlyingMap h).app _ (cell k) = z k + +structure CellularPresentation {C : GlobularTheory.{v}} (X : C.Model) where + order : Type v + linearOrder : LinearOrder order + orderBot : OrderBot order + succOrder : SuccOrder order + wellFoundedLT : WellFoundedLT order + initial : C.Model + isInitial : IsInitial initial + start : initial ⟶ X + chain : @TransfiniteCompositionOfShape _ _ order linearOrder orderBot + _ _ start succOrder wellFoundedLT + attachment : ∀ j, ¬ IsMax j → BoundaryAttachment + (chain.F.map (homOfLE (Order.le_succ j))) + +def IsCellular {C : GlobularTheory.{v}} (X : C.Model) : Prop := Nonempty X.CellularPresentation + +end Model + +def unitPair (C : GlobularTheory.{v}) (n : ℕ) : C.AdmissiblePair where + n := n + arity := Shape.globe n + height := Nat.le_succ n + source := C.id (Shape.globe n) + target := C.id (Shape.globe n) + parallel := by cases n <;> simp [Parallel] + +noncomputable def unit (C : GlobularTheory.{v}) (hC : C.IsCoherator) (n : ℕ) : + C.Hom (Shape.globe (n + 1)) (Shape.globe n) := Classical.choose (hC.2 (C.unitPair n)) + +def Model.eval {C : GlobularTheory.{v}} (X : C.Model) {S T : Shape} (f : C.Hom S T) : + X.presheaf.obj (op (⟨T⟩ : C.Obj)) → X.presheaf.obj (op (⟨S⟩ : C.Obj)) := + X.presheaf.map (show (⟨S⟩ : C.Obj) ⟶ ⟨T⟩ from f).op + +noncomputable def Model.unitCell {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (n : ℕ) (x : X.underlying.Cell n) : X.underlying.Cell (n + 1) := + X.eval (C.unit hC n) x + +noncomputable def Model.baseCell {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) : ∀ n, X.underlying.Cell n + | 0 => x + | n + 1 => X.unitCell hC n (X.baseCell hC x n) + +def Model.Loops {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) (n : ℕ) : Type v := + { z : X.underlying.Cell (n + 1) // X.underlying.source n z = X.baseCell hC x n ∧ + X.underlying.target n z = X.baseCell hC x n } + +def Model.Components {C : GlobularTheory.{v}} (X : C.Model) : Type v := + Quot (X.underlying.Joined 0) + +def Model.HomotopyGroup {C : GlobularTheory.{v}} (X : C.Model) (hC : C.IsCoherator) + (x : X.underlying.Cell 0) (n : ℕ) : Type v := + Quot (fun a b : X.Loops hC x n => X.underlying.Joined (n + 1) a.1 b.1) + +noncomputable def Model.loopsMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) + (hC : C.IsCoherator) (x : X.underlying.Cell 0) (n : ℕ) : + X.Loops hC x n → Y.Loops hC ((underlyingMap f).app 0 x) n := by + have hb : ∀ k, (underlyingMap f).app k (X.baseCell hC x k) = + Y.baseCell hC ((underlyingMap f).app 0 x) k := by + intro k + induction k with + | zero => rfl + | succ k ih => + have h := ConcreteCategory.congr_hom (f.naturality + (show (op (⟨Shape.globe k⟩ : C.Obj)) ⟶ op ⟨Shape.globe (k+1)⟩ from + Quiver.Hom.op (C.unit hC k))) (X.baseCell hC x k) + change (underlyingMap f).app (k+1) (X.unitCell hC k (X.baseCell hC x k)) = + Y.unitCell hC k ((underlyingMap f).app k (X.baseCell hC x k)) at h + simpa only [baseCell, ih] using h + exact fun z => ⟨(underlyingMap f).app (n + 1) z.1, + by rw [← (underlyingMap f).source_app, z.2.1, hb], + by rw [← (underlyingMap f).target_app, z.2.2, hb]⟩ + +noncomputable def Model.componentsMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) : + X.Components → Y.Components := + Quot.map ((underlyingMap f).app 0) (by + rintro _ _ ⟨h, hs, ht⟩ + exact ⟨(underlyingMap f).app _ h, + by rw [← (underlyingMap f).source_app, hs], + by rw [← (underlyingMap f).target_app, ht]⟩) + +noncomputable def Model.homotopyMap {C : GlobularTheory.{v}} {X Y : C.Model} (f : X ⟶ Y) + (hC : C.IsCoherator) (x : X.underlying.Cell 0) (n : ℕ) : + X.HomotopyGroup hC x n → Y.HomotopyGroup hC ((underlyingMap f).app 0 x) n := + Quot.map (loopsMap f hC x n) (by + rintro _ _ ⟨h, hs, ht⟩ + exact ⟨(underlyingMap f).app _ h, + by rw [← (underlyingMap f).source_app, hs]; rfl, + by rw [← (underlyingMap f).target_app, ht]; rfl⟩) + +def Model.WeakEquivalence {C : GlobularTheory.{v}} (hC : C.IsCoherator) {X Y : C.Model} + (f : X ⟶ Y) : Prop := + Function.Bijective (componentsMap f) ∧ + ∀ (x : X.underlying.Cell 0) (n : ℕ), Function.Bijective (homotopyMap f hC x n) + +end GlobularTheory + +open CategoryTheory CategoryTheory.Limits + +theorem elementary_expansion (C : GlobularTheory.{v}) (hC : C.IsCoherator) + (X : C.Model) (hX : X.IsCellular) (n : ℕ) + (a : GlobularTheory.Model.disk C n ⟶ X) + (Y : C.Model) (i : X ⟶ Y) + (b : GlobularTheory.Model.disk C (n + 1) ⟶ Y) + (square : IsPushout a (GlobularTheory.Model.J C n) i b) : + GlobularTheory.Model.WeakEquivalence hC i := by + sorry + +end Grothendieck + +end OAI diff --git a/tasks/grothendieck-elementary-expansion/tests/grade.py b/tasks/grothendieck-elementary-expansion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/grothendieck-elementary-expansion/tests/task.json b/tasks/grothendieck-elementary-expansion/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..538b1ae19feee9805a9dd0860bcaac48e06396f0 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GrothendieckElementaryExpansion", + "comparator": { + "theorem_names": [ + "OAI.Grothendieck.elementary_expansion" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11322 +} \ No newline at end of file diff --git a/tasks/grothendieck-elementary-expansion/tests/test.sh b/tasks/grothendieck-elementary-expansion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/grothendieck-elementary-expansion/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/group-ring-determinant/environment/Dockerfile b/tasks/group-ring-determinant/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/group-ring-determinant/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/group-ring-determinant/environment/fetch_mathlib.sh b/tasks/group-ring-determinant/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/group-ring-determinant/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/group-ring-determinant/environment/lake-manifest.json b/tasks/group-ring-determinant/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/group-ring-determinant/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/group-ring-determinant/environment/lakefile.lean b/tasks/group-ring-determinant/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/group-ring-determinant/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/group-ring-determinant/environment/lean_setup.sh b/tasks/group-ring-determinant/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/group-ring-determinant/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/group-ring-determinant/environment/pack_submission.py b/tasks/group-ring-determinant/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/group-ring-determinant/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/group-ring-determinant/instruction.md b/tasks/group-ring-determinant/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..da42e3326fda2b3aee973859207b0daaafd67439 --- /dev/null +++ b/tasks/group-ring-determinant/instruction.md @@ -0,0 +1,110 @@ +# openai/math challenge `GroupRingDeterminant` (family 197) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 197 of the release, *Nonsofic groups and group-ring counterexamples* +(Algebra). The family as a whole: Constructs a finitely presented torsion-free nonsofic group whose group algebra over $\mathbb F_2$ is not directly finite, disproving Kaplansky's conjecture even without torsion. Companion examples give injective nonsurjective cellular automata on all configurations, refuting Gottschalk's surjunctivity conjecture. Another counterexample is an integral group-ring matrix, invertible over the rational group ring, with Fuglede–Kadison determinant strictly between zero and one, disproving the unrestricted Determinant Conjecture. + +The challenge is `GroupRingDeterminant`, also at `/opt/openai-math/challenges/GroupRingDeterminant.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators + +namespace GroupRingDeterminant + +/-- The Hilbert space l²(G)^n, with the product coordinates flattened. -/ +abbrev Hilbert (G : Type) (n : ℕ) := lp (fun _ : Fin n × G => ℂ) 2 + +/-- The identity vector in component i. -/ +def identityVector {G : Type} [Group G] {n : ℕ} (i : Fin n) : Hilbert G n := + by + classical + exact lp.single 2 (i, 1) 1 + +/-- The unnormalized matrix trace, linear in its operator argument. -/ +def groupTrace {G : Type} [Group G] {n : ℕ} + (T : Hilbert G n →L[ℂ] Hilbert G n) : ℂ := + ∑ i : Fin n, inner ℂ (identityVector i) (T (identityVector i)) + +/-- The invertible-case Fuglede--Kadison determinant. +It is used below only for invertible regular operators. -/ +def fkDet {G : Type} [Group G] {n : ℕ} + (T : Hilbert G n →L[ℂ] Hilbert G n) : ℝ := + Real.exp ((groupTrace (CFC.log (star T * T))).re / 2) + +/-- Exact coordinate specification of the bounded left-regular operator of A. -/ +def IsRegularOperator {G : Type} [Group G] {n : ℕ} + (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) + (T : Hilbert G n →L[ℂ] Hilbert G n) : Prop := + ∀ (ξ : Hilbert G n) (i : Fin n) (h : G), + (T ξ) (i, h) = ∑ j : Fin n, + (A i j).coeff.sum fun g z => (z : ℂ) * ξ (j, g⁻¹ * h) + +/-- Coefficientwise extension from the integral to the rational group ring. -/ +def rationalMatrix {G : Type} [Group G] {n : ℕ} + (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) : + Matrix (Fin n) (Fin n) (MonoidAlgebra ℚ G) := + A.map (MonoidAlgebra.mapRingHom G (Int.castRingHom ℚ)) + +/-- An integral group-ring matrix with rational and bounded inverses and determinant in (0, 1). -/ +def MainStatement : Prop := + ∃ (G : Type) (_ : Group G) (_ : Group.FG G) (n : ℕ), + 1 ≤ n ∧ ∃ (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) + (T : Hilbert G n →L[ℂ] Hilbert G n), + IsUnit (rationalMatrix A) ∧ IsRegularOperator A T ∧ IsUnit T ∧ + 0 < fkDet T ∧ fkDet T < 1 + +theorem main : MainStatement := by + sorry + +end GroupRingDeterminant + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/GroupRingDeterminant.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.GroupRingDeterminant.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/group-ring-determinant/solution/closure.txt b/tasks/group-ring-determinant/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6a93620755432208e32a2c1ae5084016ac8683c6 --- /dev/null +++ b/tasks/group-ring-determinant/solution/closure.txt @@ -0,0 +1,155 @@ +OAI.Analysis.GroupDeterminants.BinaryMatrices +OAI.Analysis.GroupDeterminants.ClosedAlgebra +OAI.Analysis.GroupDeterminants.ClosedTrace +OAI.Analysis.GroupDeterminants.CompanionTransfer +OAI.Analysis.GroupDeterminants.ComplexRepresentation +OAI.Analysis.GroupDeterminants.CyclicAverage +OAI.Analysis.GroupDeterminants.DefectProjections +OAI.Analysis.GroupDeterminants.Defects +OAI.Analysis.GroupDeterminants.FiniteFields +OAI.Analysis.GroupDeterminants.GroupAlgebraStar +OAI.Analysis.GroupDeterminants.IndexedRepresentation +OAI.Analysis.GroupDeterminants.IntegralTransfer +OAI.Analysis.GroupDeterminants.LampCoefficients +OAI.Analysis.GroupDeterminants.LampDenominators +OAI.Analysis.GroupDeterminants.LampProjections +OAI.Analysis.GroupDeterminants.Lamps +OAI.Analysis.GroupDeterminants.LogSeries +OAI.Analysis.GroupDeterminants.Main +OAI.Analysis.GroupDeterminants.Model +OAI.Analysis.GroupDeterminants.ModularLifting +OAI.Analysis.GroupDeterminants.ProductSupport +OAI.Analysis.GroupDeterminants.ProjectionCriterion +OAI.Analysis.GroupDeterminants.ProjectionData +OAI.Analysis.GroupDeterminants.ProjectionLog +OAI.Analysis.GroupDeterminants.RationalRepresentation +OAI.Analysis.GroupDeterminants.RegularAdjoint +OAI.Analysis.GroupDeterminants.RegularOperators +OAI.Analysis.GroupDeterminants.RegularTrace +OAI.Analysis.GroupDeterminants.ShearTrace +OAI.Analysis.GroupDeterminants.TraceLog +OAI.Analysis.GroupDeterminants.TransferAlgebra +OAI.Analysis.GroupDeterminants.TransferTrace +OAI.Analysis.GroupDeterminants.WeightedProjections +OAI.Analysis.GroupDeterminants.WeightedTrace +OAI.RingTheory.DirectFiniteness.AffineLines +OAI.RingTheory.DirectFiniteness.AlgebraicCriterion +OAI.RingTheory.DirectFiniteness.AlgebraicPacking +OAI.RingTheory.DirectFiniteness.Alteration +OAI.RingTheory.DirectFiniteness.AssignedDevelopment +OAI.RingTheory.DirectFiniteness.BalanceCoarsening +OAI.RingTheory.DirectFiniteness.BalanceDetachment +OAI.RingTheory.DirectFiniteness.BalanceObstruction +OAI.RingTheory.DirectFiniteness.BalanceRestriction +OAI.RingTheory.DirectFiniteness.BoundaryCycles +OAI.RingTheory.DirectFiniteness.BoundaryFilling +OAI.RingTheory.DirectFiniteness.BoundarySplitting +OAI.RingTheory.DirectFiniteness.CandidateBounds +OAI.RingTheory.DirectFiniteness.CandidateClassification +OAI.RingTheory.DirectFiniteness.CandidateCounting +OAI.RingTheory.DirectFiniteness.CandidateDependencies +OAI.RingTheory.DirectFiniteness.CandidateGeometry +OAI.RingTheory.DirectFiniteness.CandidateModel +OAI.RingTheory.DirectFiniteness.CandidateRelations +OAI.RingTheory.DirectFiniteness.CharacterFormulas +OAI.RingTheory.DirectFiniteness.CharacterIdempotents +OAI.RingTheory.DirectFiniteness.CharacterTwist +OAI.RingTheory.DirectFiniteness.ChosenCriterion +OAI.RingTheory.DirectFiniteness.CoordinateCharacters +OAI.RingTheory.DirectFiniteness.CycleFactorization +OAI.RingTheory.DirectFiniteness.CycleSplitting +OAI.RingTheory.DirectFiniteness.CycleSums +OAI.RingTheory.DirectFiniteness.CyclicLabels +OAI.RingTheory.DirectFiniteness.DetachmentGenus +OAI.RingTheory.DirectFiniteness.DiagramDeletion +OAI.RingTheory.DirectFiniteness.DiagramInsertion +OAI.RingTheory.DirectFiniteness.DiagramJoining +OAI.RingTheory.DirectFiniteness.DiagramObstruction +OAI.RingTheory.DirectFiniteness.DiagramReduction +OAI.RingTheory.DirectFiniteness.DirectionCompleteness +OAI.RingTheory.DirectFiniteness.DirectionFrame +OAI.RingTheory.DirectFiniteness.DirectionSpaces +OAI.RingTheory.DirectFiniteness.EulerBound +OAI.RingTheory.DirectFiniteness.EventLoad +OAI.RingTheory.DirectFiniteness.FieldExtensions +OAI.RingTheory.DirectFiniteness.FiniteAffine +OAI.RingTheory.DirectFiniteness.FiniteBlock +OAI.RingTheory.DirectFiniteness.FiniteGeneration +OAI.RingTheory.DirectFiniteness.FiniteParameters +OAI.RingTheory.DirectFiniteness.FrameExistence +OAI.RingTheory.DirectFiniteness.FrameTransport +OAI.RingTheory.DirectFiniteness.GluedGroup +OAI.RingTheory.DirectFiniteness.GluedWords +OAI.RingTheory.DirectFiniteness.GroupEmbedding +OAI.RingTheory.DirectFiniteness.HoleEvents +OAI.RingTheory.DirectFiniteness.HoleExistence +OAI.RingTheory.DirectFiniteness.HoleNumerics +OAI.RingTheory.DirectFiniteness.HoleSelection +OAI.RingTheory.DirectFiniteness.IncidenceCycles +OAI.RingTheory.DirectFiniteness.IncidenceDirections +OAI.RingTheory.DirectFiniteness.LabelSupport +OAI.RingTheory.DirectFiniteness.LexicographicOrder +OAI.RingTheory.DirectFiniteness.Main +OAI.RingTheory.DirectFiniteness.MatrixBlock +OAI.RingTheory.DirectFiniteness.Model +OAI.RingTheory.DirectFiniteness.ModelPartition +OAI.RingTheory.DirectFiniteness.MultiHNN +OAI.RingTheory.DirectFiniteness.OneCandidateCounting +OAI.RingTheory.DirectFiniteness.OpenDiagrams +OAI.RingTheory.DirectFiniteness.PackingFormulas +OAI.RingTheory.DirectFiniteness.Pairing +OAI.RingTheory.DirectFiniteness.ParameterBounds +OAI.RingTheory.DirectFiniteness.PartialPartition +OAI.RingTheory.DirectFiniteness.PartitionMerging +OAI.RingTheory.DirectFiniteness.PlanarBalance +OAI.RingTheory.DirectFiniteness.PlanarDiagrams +OAI.RingTheory.DirectFiniteness.PlaneOperators +OAI.RingTheory.DirectFiniteness.PrescribedData +OAI.RingTheory.DirectFiniteness.PrescribedDirections +OAI.RingTheory.DirectFiniteness.PrescribedFields +OAI.RingTheory.DirectFiniteness.PrescribedIncidence +OAI.RingTheory.DirectFiniteness.PrescribedOutputs +OAI.RingTheory.DirectFiniteness.PrescribedPairing +OAI.RingTheory.DirectFiniteness.PrescribedParameters +OAI.RingTheory.DirectFiniteness.PrescribedSearch +OAI.RingTheory.DirectFiniteness.PrescribedSlots +OAI.RingTheory.DirectFiniteness.PrescribedSubfield +OAI.RingTheory.DirectFiniteness.PrimeCertificate +OAI.RingTheory.DirectFiniteness.ProductAlgebras +OAI.RingTheory.DirectFiniteness.QuotientField +OAI.RingTheory.DirectFiniteness.Rectangular +OAI.RingTheory.DirectFiniteness.ReducedWalks +OAI.RingTheory.DirectFiniteness.ReplacementGeometry +OAI.RingTheory.DirectFiniteness.ReplacementPolygon +OAI.RingTheory.DirectFiniteness.RibbonDetachment +OAI.RingTheory.DirectFiniteness.RibbonGeometry +OAI.RingTheory.DirectFiniteness.RibbonRestriction +OAI.RingTheory.DirectFiniteness.RibbonSplitting +OAI.RingTheory.DirectFiniteness.RibbonSums +OAI.RingTheory.DirectFiniteness.RibbonWheels +OAI.RingTheory.DirectFiniteness.ScalarFormulas +OAI.RingTheory.DirectFiniteness.ScalarWitnesses +OAI.RingTheory.DirectFiniteness.ShortIndependence +OAI.RingTheory.DirectFiniteness.ShortRelators +OAI.RingTheory.DirectFiniteness.SimplexBound +OAI.RingTheory.DirectFiniteness.SlabAssembly +OAI.RingTheory.DirectFiniteness.SlabAvoidance +OAI.RingTheory.DirectFiniteness.SlabEvents +OAI.RingTheory.DirectFiniteness.SlabHoleEvents +OAI.RingTheory.DirectFiniteness.SlabKeys +OAI.RingTheory.DirectFiniteness.SlabLoad +OAI.RingTheory.DirectFiniteness.SlabNumerics +OAI.RingTheory.DirectFiniteness.SlabPartition +OAI.RingTheory.DirectFiniteness.SlabPatch +OAI.RingTheory.DirectFiniteness.TradeDegree +OAI.RingTheory.DirectFiniteness.TradeFamily +OAI.RingTheory.DirectFiniteness.TradeGirth +OAI.RingTheory.DirectFiniteness.TradeLines +OAI.RingTheory.DirectFiniteness.TradePolygon +OAI.RingTheory.DirectFiniteness.TranslatedUnits +OAI.RingTheory.DirectFiniteness.VertexMerging +OAI.RingTheory.DirectFiniteness.WeightTransfer +OAI.RingTheory.DirectFiniteness.WordCycles +OAI.RingTheory.DirectFiniteness.WordDiagrams +OAI.RingTheory.DirectFiniteness.WordReduction +OAI.RingTheory.DirectFiniteness.WordWheels diff --git a/tasks/group-ring-determinant/solution/reference.py b/tasks/group-ring-determinant/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/group-ring-determinant/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/group-ring-determinant/solution/solve.sh b/tasks/group-ring-determinant/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..377da66d7e389bb836d7d5563fe525ebb098fc66 --- /dev/null +++ b/tasks/group-ring-determinant/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of GroupRingDeterminant, i.e. module OAI.Analysis.GroupDeterminants.Main and the +# 155 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.GroupDeterminants.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of GroupRingDeterminant" diff --git a/tasks/group-ring-determinant/task.toml b/tasks/group-ring-determinant/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee7a59c20f1a016f1749868d15c3ea22d6c7c902 --- /dev/null +++ b/tasks/group-ring-determinant/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/group-ring-determinant" +version = "1.0.0" +description = "Prove GroupRingDeterminant (openai/math family 197: Nonsofic groups and group-ring counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/GroupRingDeterminant.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "GroupRingDeterminant" +family = "197" +family_title = "Nonsofic groups and group-ring counterexamples" +subject = "Algebra" +theorems = ["OAI.GroupRingDeterminant.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.GroupDeterminants.Main" +reference_modules = 155 +reference_lean_bytes = 680917 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1695 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12312 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/group-ring-determinant/tests/Challenge.lean b/tasks/group-ring-determinant/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..565a9603826ed4033e6aa35abd52a80b39bcc0f5 --- /dev/null +++ b/tasks/group-ring-determinant/tests/Challenge.lean @@ -0,0 +1,59 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators + +namespace GroupRingDeterminant + +/-- The Hilbert space l²(G)^n, with the product coordinates flattened. -/ +abbrev Hilbert (G : Type) (n : ℕ) := lp (fun _ : Fin n × G => ℂ) 2 + +/-- The identity vector in component i. -/ +def identityVector {G : Type} [Group G] {n : ℕ} (i : Fin n) : Hilbert G n := + by + classical + exact lp.single 2 (i, 1) 1 + +/-- The unnormalized matrix trace, linear in its operator argument. -/ +def groupTrace {G : Type} [Group G] {n : ℕ} + (T : Hilbert G n →L[ℂ] Hilbert G n) : ℂ := + ∑ i : Fin n, inner ℂ (identityVector i) (T (identityVector i)) + +/-- The invertible-case Fuglede--Kadison determinant. +It is used below only for invertible regular operators. -/ +def fkDet {G : Type} [Group G] {n : ℕ} + (T : Hilbert G n →L[ℂ] Hilbert G n) : ℝ := + Real.exp ((groupTrace (CFC.log (star T * T))).re / 2) + +/-- Exact coordinate specification of the bounded left-regular operator of A. -/ +def IsRegularOperator {G : Type} [Group G] {n : ℕ} + (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) + (T : Hilbert G n →L[ℂ] Hilbert G n) : Prop := + ∀ (ξ : Hilbert G n) (i : Fin n) (h : G), + (T ξ) (i, h) = ∑ j : Fin n, + (A i j).coeff.sum fun g z => (z : ℂ) * ξ (j, g⁻¹ * h) + +/-- Coefficientwise extension from the integral to the rational group ring. -/ +def rationalMatrix {G : Type} [Group G] {n : ℕ} + (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) : + Matrix (Fin n) (Fin n) (MonoidAlgebra ℚ G) := + A.map (MonoidAlgebra.mapRingHom G (Int.castRingHom ℚ)) + +/-- An integral group-ring matrix with rational and bounded inverses and determinant in (0, 1). -/ +def MainStatement : Prop := + ∃ (G : Type) (_ : Group G) (_ : Group.FG G) (n : ℕ), + 1 ≤ n ∧ ∃ (A : Matrix (Fin n) (Fin n) (MonoidAlgebra ℤ G)) + (T : Hilbert G n →L[ℂ] Hilbert G n), + IsUnit (rationalMatrix A) ∧ IsRegularOperator A T ∧ IsUnit T ∧ + 0 < fkDet T ∧ fkDet T < 1 + +theorem main : MainStatement := by + sorry + +end GroupRingDeterminant + +end + +end OAI diff --git a/tasks/group-ring-determinant/tests/grade.py b/tasks/group-ring-determinant/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/group-ring-determinant/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/group-ring-determinant/tests/task.json b/tasks/group-ring-determinant/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..47cc0a38990eae4cc7270c9d132c2418f992978b --- /dev/null +++ b/tasks/group-ring-determinant/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "GroupRingDeterminant", + "comparator": { + "theorem_names": [ + "OAI.GroupRingDeterminant.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11412 +} \ No newline at end of file diff --git a/tasks/group-ring-determinant/tests/test.sh b/tasks/group-ring-determinant/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/group-ring-determinant/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hadamard-cube-fiber/environment/Dockerfile b/tasks/hadamard-cube-fiber/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hadamard-cube-fiber/environment/fetch_mathlib.sh b/tasks/hadamard-cube-fiber/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hadamard-cube-fiber/environment/lake-manifest.json b/tasks/hadamard-cube-fiber/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hadamard-cube-fiber/environment/lakefile.lean b/tasks/hadamard-cube-fiber/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hadamard-cube-fiber/environment/lean_setup.sh b/tasks/hadamard-cube-fiber/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hadamard-cube-fiber/environment/pack_submission.py b/tasks/hadamard-cube-fiber/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hadamard-cube-fiber/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hadamard-cube-fiber/instruction.md b/tasks/hadamard-cube-fiber/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f32f296339e046ac851b122049484350aab915a1 --- /dev/null +++ b/tasks/hadamard-cube-fiber/instruction.md @@ -0,0 +1,88 @@ +# openai/math challenge `HadamardCubeFiber` (family 266) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 266 of the release, *Exactly three mutually unbiased bases in dimension six* +(Mathematical physics). The family as a whole: Proves $N(6)=3$, resolving Zauner\textquotesingle s dimension-six mutually unbiased bases conjecture: three such bases exist in $\mathbb C^6$, but four cannot. The exclusion is a complete certified computation under the stated binary64 arithmetic and compiler conditions. An independent companion proves the Matolcsi–Ruzsa–Weiner Fourier-vanishing conjecture for order-six complex Hadamard matrices outside Tao\textquotesingle s cubic equivalence class. + +The challenge is `HadamardCubeFiber`, also at `/opt/openai-math/challenges/HadamardCubeFiber.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Cancellation of row ratios on a prescribed cubic fibre. -/ + +open scoped BigOperators Matrix + +namespace HadamardSix + +abbrev Index := Fin 6 +abbrev Matrix6 := Matrix Index Index ℂ + +def Unimodular (H : Matrix6) : Prop := ∀ i j, ‖H i j‖ = 1 + +def IsComplexHadamard (H : Matrix6) : Prop := + Unimodular H ∧ H.conjTranspose * H = (6 : ℂ) • (1 : Matrix6) + +def entrywiseSquare (H : Matrix6) : Matrix6 := fun i j => H i j ^ 2 + +noncomputable def cubeFiber (v : Index → ℂ) (z : ℂ) : Finset Index := by + classical + exact Finset.univ.filter (fun i => v i ^ 3 = z) + +noncomputable def rowRatio (H : Matrix6) (i j : Index) : Index → ℂ := + fun k => H i k * star (H j k) + +lemma rowRatio_cubeFiber_sum_zero {H : Matrix6} (hH : IsComplexHadamard H) + (hs : IsComplexHadamard (entrywiseSquare H)) {i j : Index} (hij : i ≠ j) + (a b : ℂ) (hne : a ≠ b) + (hab : ∀ k, rowRatio H i j k ^ 3 = a ∨ rowRatio H i j k ^ 3 = b) : + ∑ k ∈ cubeFiber (rowRatio H i j) a, H i k * star (H j k) = 0 := by + sorry + +end HadamardSix + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HadamardCubeFiber.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HadamardSix.rowRatio_cubeFiber_sum_zero` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hadamard-cube-fiber/solution/closure.txt b/tasks/hadamard-cube-fiber/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..224f5df3cbf20324f82b2998c7d06be0000140e2 --- /dev/null +++ b/tasks/hadamard-cube-fiber/solution/closure.txt @@ -0,0 +1,6 @@ +OAI.LinearAlgebra.Hadamard.Basic +OAI.LinearAlgebra.Hadamard.CubeFibers +OAI.LinearAlgebra.Hadamard.Equivalence +OAI.LinearAlgebra.Hadamard.Fourier +OAI.LinearAlgebra.Hadamard.Main +OAI.LinearAlgebra.Hadamard.Polynomials diff --git a/tasks/hadamard-cube-fiber/solution/reference.py b/tasks/hadamard-cube-fiber/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hadamard-cube-fiber/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hadamard-cube-fiber/solution/solve.sh b/tasks/hadamard-cube-fiber/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..93e1d05d17f393aa7f37e3706b57b58c077a7329 --- /dev/null +++ b/tasks/hadamard-cube-fiber/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HadamardCubeFiber, i.e. module OAI.LinearAlgebra.Hadamard.Main and the +# 6 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.LinearAlgebra.Hadamard.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HadamardCubeFiber" diff --git a/tasks/hadamard-cube-fiber/task.toml b/tasks/hadamard-cube-fiber/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c35a58360c669cbd1b5923b6e138193db3063fb --- /dev/null +++ b/tasks/hadamard-cube-fiber/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hadamard-cube-fiber" +version = "1.0.0" +description = "Prove HadamardCubeFiber (openai/math family 266: Exactly three mutually unbiased bases in dimension six) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HadamardCubeFiber.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HadamardCubeFiber" +family = "266" +family_title = "Exactly three mutually unbiased bases in dimension six" +subject = "Mathematical physics" +theorems = ["OAI.HadamardSix.rowRatio_cubeFiber_sum_zero"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.LinearAlgebra.Hadamard.Main" +reference_modules = 6 +reference_lean_bytes = 39551 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 462 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11735 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hadamard-cube-fiber/tests/Challenge.lean b/tasks/hadamard-cube-fiber/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..815e8a2d54b071bf057655eddf2301ac544d84c4 --- /dev/null +++ b/tasks/hadamard-cube-fiber/tests/Challenge.lean @@ -0,0 +1,37 @@ +import Mathlib + +namespace OAI + +/-! Cancellation of row ratios on a prescribed cubic fibre. -/ + +open scoped BigOperators Matrix + +namespace HadamardSix + +abbrev Index := Fin 6 +abbrev Matrix6 := Matrix Index Index ℂ + +def Unimodular (H : Matrix6) : Prop := ∀ i j, ‖H i j‖ = 1 + +def IsComplexHadamard (H : Matrix6) : Prop := + Unimodular H ∧ H.conjTranspose * H = (6 : ℂ) • (1 : Matrix6) + +def entrywiseSquare (H : Matrix6) : Matrix6 := fun i j => H i j ^ 2 + +noncomputable def cubeFiber (v : Index → ℂ) (z : ℂ) : Finset Index := by + classical + exact Finset.univ.filter (fun i => v i ^ 3 = z) + +noncomputable def rowRatio (H : Matrix6) (i j : Index) : Index → ℂ := + fun k => H i k * star (H j k) + +lemma rowRatio_cubeFiber_sum_zero {H : Matrix6} (hH : IsComplexHadamard H) + (hs : IsComplexHadamard (entrywiseSquare H)) {i j : Index} (hij : i ≠ j) + (a b : ℂ) (hne : a ≠ b) + (hab : ∀ k, rowRatio H i j k ^ 3 = a ∨ rowRatio H i j k ^ 3 = b) : + ∑ k ∈ cubeFiber (rowRatio H i j) a, H i k * star (H j k) = 0 := by + sorry + +end HadamardSix + +end OAI diff --git a/tasks/hadamard-cube-fiber/tests/grade.py b/tasks/hadamard-cube-fiber/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hadamard-cube-fiber/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hadamard-cube-fiber/tests/task.json b/tasks/hadamard-cube-fiber/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4525c327e8d2c14675dfdae4aaa6bfd3f65bebd5 --- /dev/null +++ b/tasks/hadamard-cube-fiber/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HadamardCubeFiber", + "comparator": { + "theorem_names": [ + "OAI.HadamardSix.rowRatio_cubeFiber_sum_zero" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10835 +} \ No newline at end of file diff --git a/tasks/hadamard-cube-fiber/tests/test.sh b/tasks/hadamard-cube-fiber/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hadamard-cube-fiber/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/halving-lines/environment/Dockerfile b/tasks/halving-lines/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/halving-lines/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/halving-lines/environment/fetch_mathlib.sh b/tasks/halving-lines/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/halving-lines/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/halving-lines/environment/lake-manifest.json b/tasks/halving-lines/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/halving-lines/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/halving-lines/environment/lakefile.lean b/tasks/halving-lines/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/halving-lines/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/halving-lines/environment/lean_setup.sh b/tasks/halving-lines/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/halving-lines/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/halving-lines/environment/pack_submission.py b/tasks/halving-lines/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/halving-lines/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/halving-lines/instruction.md b/tasks/halving-lines/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..43ddd00c5fd237202541cf6f6c20e6e2b29d8b27 --- /dev/null +++ b/tasks/halving-lines/instruction.md @@ -0,0 +1,107 @@ +# openai/math challenge `HalvingLines` (family 183) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 183 of the release, *Power savings for planar halving lines and $k$-sets* +(Combinatorics). The family as a whole: Improves the planar halving-line bound to $O(n^{4/3-\varepsilon})$ for sets with no three collinear and an absolute $\varepsilon>0$. More generally, an $n$-point set with no three collinear has $O(n(k+1)^{1/3-\varepsilon_0})$ strictly separable $k$-subsets for $1\le k\le n/2$, with an absolute $\varepsilon_0>0$. The constants and positive exponents are nonquantitative. + +The challenge is `HalvingLines`, also at `/opt/openai-math/challenges/HalvingLines.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PlanarHalving + +abbrev Point := ℝ × ℝ + +def orient (p q r : Point) : ℝ := + (q.1 - p.1) * (r.2 - p.2) - (q.2 - p.2) * (r.1 - p.1) + +def GeneralPosition {n : ℕ} (P : Fin n → Point) : Prop := + Function.Injective P ∧ ∀ i j l, i ≠ j → j ≠ l → i ≠ l → + orient (P i) (P j) (P l) ≠ 0 + +noncomputable def sideCount {n : ℕ} (P : Fin n → Point) (i j : Fin n) : ℕ := + (Finset.univ.filter fun l => 0 < orient (P i) (P j) (P l)).card + +noncomputable def halvingCount {n : ℕ} (P : Fin n → Point) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ sideCount P ij.1 ij.2 = (n - 2) / 2 ∧ + sideCount P ij.2 ij.1 = (n - 2) / 2).card + +noncomputable def slope (p q : Point) : ℝ := (q.2 - p.2) / (q.1 - p.1) + +def Generic {n : ℕ} (P : Fin n → Point) : Prop := + GeneralPosition P ∧ + (∀ i j, i ≠ j → (P i).1 ≠ (P j).1) ∧ + (∀ i j a b, i < j → a < b → slope (P i) (P j) = slope (P a) (P b) → + i = a ∧ j = b) ∧ + (∀ i j a b c d, i < j → a < b → c < d → + (i, j) ≠ (a, b) → (c, d) ≠ (i, j) → (c, d) ≠ (a, b) → + ∀ z : Point, z ∈ openSegment ℝ (P i) (P j) → + z ∈ openSegment ℝ (P a) (P b) → z ∉ segment ℝ (P c) (P d)) + +noncomputable def belowCount {n : ℕ} (P : Fin n → Point) (i j : Fin n) : ℕ := + let s := slope (P i) (P j) + (Finset.univ.filter fun l => (P l).2 - s * (P l).1 < + (P i).2 - s * (P i).1).card + +noncomputable def switchCount {n : ℕ} (P : Fin n → Point) (k : ℕ) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ 0 < k ∧ k < n ∧ belowCount P ij.1 ij.2 = k - 1).card + +theorem power_bounds : + (∃ ε : ℝ, 0 < ε ∧ ∃ C : ℝ, ∃ n₀ : ℕ, + ∀ n : ℕ, Even n → n₀ ≤ n → ∀ P : Fin n → Point, + GeneralPosition P → (halvingCount P : ℝ) ≤ C * (n : ℝ) ^ ((4 : ℝ) / 3 - ε)) ∧ + (∃ ε : ℝ, 0 < ε ∧ ∃ C : ℝ, + ∀ n : ℕ, 1 ≤ n → ∀ P : Fin n → Point, Generic P → + ∀ k : ℕ, k ≤ n → (switchCount P k : ℝ) ≤ C * (n : ℝ) ^ ((4 : ℝ) / 3 - ε)) := + sorry + +end PlanarHalving + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HalvingLines.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarHalving.power_bounds` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/halving-lines/solution/closure.txt b/tasks/halving-lines/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..abb534859c55be1812777c22368b8f0651031b47 --- /dev/null +++ b/tasks/halving-lines/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Combinatorics.HalvingLines.Activity +OAI.Combinatorics.HalvingLines.ActivityRetention +OAI.Combinatorics.HalvingLines.AtomicBounds +OAI.Combinatorics.HalvingLines.Basic +OAI.Combinatorics.HalvingLines.Batches +OAI.Combinatorics.HalvingLines.Boundary +OAI.Combinatorics.HalvingLines.BoundaryTokens +OAI.Combinatorics.HalvingLines.Calculus +OAI.Combinatorics.HalvingLines.ChainDrawing +OAI.Combinatorics.HalvingLines.Chains +OAI.Combinatorics.HalvingLines.Compactness +OAI.Combinatorics.HalvingLines.Continuity +OAI.Combinatorics.HalvingLines.CrossingEstimate +OAI.Combinatorics.HalvingLines.Curves +OAI.Combinatorics.HalvingLines.Decomposition +OAI.Combinatorics.HalvingLines.Densities +OAI.Combinatorics.HalvingLines.Derivatives +OAI.Combinatorics.HalvingLines.Directions +OAI.Combinatorics.HalvingLines.Enhancement +OAI.Combinatorics.HalvingLines.Foliations +OAI.Combinatorics.HalvingLines.Greedy +OAI.Combinatorics.HalvingLines.Intersections +OAI.Combinatorics.HalvingLines.Labels +OAI.Combinatorics.HalvingLines.LocalZoom +OAI.Combinatorics.HalvingLines.Main +OAI.Combinatorics.HalvingLines.MassEstimates +OAI.Combinatorics.HalvingLines.MeasureBounds +OAI.Combinatorics.HalvingLines.Model +OAI.Combinatorics.HalvingLines.Noncollapse +OAI.Combinatorics.HalvingLines.Packing +OAI.Combinatorics.HalvingLines.Partition +OAI.Combinatorics.HalvingLines.PathLimits +OAI.Combinatorics.HalvingLines.Perturbation +OAI.Combinatorics.HalvingLines.PlaneGraph +OAI.Combinatorics.HalvingLines.RankCoordinates +OAI.Combinatorics.HalvingLines.RankMeasures +OAI.Combinatorics.HalvingLines.Recurrence +OAI.Combinatorics.HalvingLines.Rigidity +OAI.Combinatorics.HalvingLines.SeparatedWindows +OAI.Combinatorics.HalvingLines.SpatialMass +OAI.Combinatorics.HalvingLines.Sweep +OAI.Combinatorics.HalvingLines.ThinStrips +OAI.Combinatorics.HalvingLines.Tokens +OAI.Combinatorics.HalvingLines.WindowMeasures +OAI.Combinatorics.HalvingLines.Windows +OAI.Combinatorics.HalvingLines.Zoom +OAI.Combinatorics.HalvingLines.ZoomControl diff --git a/tasks/halving-lines/solution/reference.py b/tasks/halving-lines/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/halving-lines/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/halving-lines/solution/solve.sh b/tasks/halving-lines/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2cfc4b7f768414072bf0aba0c8d0ece5a224d47e --- /dev/null +++ b/tasks/halving-lines/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HalvingLines, i.e. module OAI.Combinatorics.HalvingLines.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.HalvingLines.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HalvingLines" diff --git a/tasks/halving-lines/task.toml b/tasks/halving-lines/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a61c77fe28b9d90d3ac2a0189bed9df9afb3bd14 --- /dev/null +++ b/tasks/halving-lines/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/halving-lines" +version = "1.0.0" +description = "Prove HalvingLines (openai/math family 183: Power savings for planar halving lines and $k$-sets) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HalvingLines.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HalvingLines" +family = "183" +family_title = "Power savings for planar halving lines and $k$-sets" +subject = "Combinatorics" +theorems = ["OAI.PlanarHalving.power_bounds"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.HalvingLines.Main" +reference_modules = 47 +reference_lean_bytes = 886978 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 894 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12498 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/halving-lines/tests/Challenge.lean b/tasks/halving-lines/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..08385f589feaadece48b5b05fc727af00fab5d62 --- /dev/null +++ b/tasks/halving-lines/tests/Challenge.lean @@ -0,0 +1,56 @@ +import Mathlib + +namespace OAI + +namespace PlanarHalving + +abbrev Point := ℝ × ℝ + +def orient (p q r : Point) : ℝ := + (q.1 - p.1) * (r.2 - p.2) - (q.2 - p.2) * (r.1 - p.1) + +def GeneralPosition {n : ℕ} (P : Fin n → Point) : Prop := + Function.Injective P ∧ ∀ i j l, i ≠ j → j ≠ l → i ≠ l → + orient (P i) (P j) (P l) ≠ 0 + +noncomputable def sideCount {n : ℕ} (P : Fin n → Point) (i j : Fin n) : ℕ := + (Finset.univ.filter fun l => 0 < orient (P i) (P j) (P l)).card + +noncomputable def halvingCount {n : ℕ} (P : Fin n → Point) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ sideCount P ij.1 ij.2 = (n - 2) / 2 ∧ + sideCount P ij.2 ij.1 = (n - 2) / 2).card + +noncomputable def slope (p q : Point) : ℝ := (q.2 - p.2) / (q.1 - p.1) + +def Generic {n : ℕ} (P : Fin n → Point) : Prop := + GeneralPosition P ∧ + (∀ i j, i ≠ j → (P i).1 ≠ (P j).1) ∧ + (∀ i j a b, i < j → a < b → slope (P i) (P j) = slope (P a) (P b) → + i = a ∧ j = b) ∧ + (∀ i j a b c d, i < j → a < b → c < d → + (i, j) ≠ (a, b) → (c, d) ≠ (i, j) → (c, d) ≠ (a, b) → + ∀ z : Point, z ∈ openSegment ℝ (P i) (P j) → + z ∈ openSegment ℝ (P a) (P b) → z ∉ segment ℝ (P c) (P d)) + +noncomputable def belowCount {n : ℕ} (P : Fin n → Point) (i j : Fin n) : ℕ := + let s := slope (P i) (P j) + (Finset.univ.filter fun l => (P l).2 - s * (P l).1 < + (P i).2 - s * (P i).1).card + +noncomputable def switchCount {n : ℕ} (P : Fin n → Point) (k : ℕ) : ℕ := + (Finset.univ.filter fun ij : Fin n × Fin n => + ij.1 < ij.2 ∧ 0 < k ∧ k < n ∧ belowCount P ij.1 ij.2 = k - 1).card + +theorem power_bounds : + (∃ ε : ℝ, 0 < ε ∧ ∃ C : ℝ, ∃ n₀ : ℕ, + ∀ n : ℕ, Even n → n₀ ≤ n → ∀ P : Fin n → Point, + GeneralPosition P → (halvingCount P : ℝ) ≤ C * (n : ℝ) ^ ((4 : ℝ) / 3 - ε)) ∧ + (∃ ε : ℝ, 0 < ε ∧ ∃ C : ℝ, + ∀ n : ℕ, 1 ≤ n → ∀ P : Fin n → Point, Generic P → + ∀ k : ℕ, k ≤ n → (switchCount P k : ℝ) ≤ C * (n : ℝ) ^ ((4 : ℝ) / 3 - ε)) := + sorry + +end PlanarHalving + +end OAI diff --git a/tasks/halving-lines/tests/grade.py b/tasks/halving-lines/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/halving-lines/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/halving-lines/tests/task.json b/tasks/halving-lines/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..673dce1553e1fe95d766eff50c7775243d36b762 --- /dev/null +++ b/tasks/halving-lines/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HalvingLines", + "comparator": { + "theorem_names": [ + "OAI.PlanarHalving.power_bounds" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11598 +} \ No newline at end of file diff --git a/tasks/halving-lines/tests/test.sh b/tasks/halving-lines/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/halving-lines/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hard-sphere/environment/Dockerfile b/tasks/hard-sphere/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hard-sphere/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hard-sphere/environment/fetch_mathlib.sh b/tasks/hard-sphere/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hard-sphere/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hard-sphere/environment/lake-manifest.json b/tasks/hard-sphere/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hard-sphere/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hard-sphere/environment/lakefile.lean b/tasks/hard-sphere/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hard-sphere/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hard-sphere/environment/lean_setup.sh b/tasks/hard-sphere/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hard-sphere/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hard-sphere/environment/pack_submission.py b/tasks/hard-sphere/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hard-sphere/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hard-sphere/instruction.md b/tasks/hard-sphere/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5a1cbe6115c64d47abfd3432485ef74c3aa47a49 --- /dev/null +++ b/tasks/hard-sphere/instruction.md @@ -0,0 +1,437 @@ +# openai/math challenge `HardSphere` (family 267) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 267 of the release, *Positive-temperature Bose–Einstein condensation and quantum depletion* +(Mathematical physics). The family as a whole: Proves Bose–Einstein condensation for the exact canonical Gibbs state of the three-dimensional hard-sphere gas: each fixed exclusion distance and sufficiently small fixed density admit a strictly positive temperature, independent of volume, with positive condensate fraction in the thermodynamic limit. At zero temperature, proves the Bogoliubov leading quantum-depletion law for hard spheres and fixed bounded nonnegative radial finite-range potentials of positive scattering length, taking the thermodynamic limit before the dilute limit. + +The challenge is `HardSphere`, also at `/opt/openai-math/challenges/HardSphere.lean`: + +```lean +import Mathlib + +/-! +# Ground-state condensation in the dilute hard-sphere gas + +The main result covers all pure ground states and all density operators supported on + the ground space. In particular it covers the normalized ground-space projection. +Only the definitions needed to state this result are retained below. +-/ + +noncomputable section +open MeasureTheory Filter Set +open scoped ENNReal Topology BigOperators InnerProductSpace ComplexOrder NNReal + +namespace OAI.HardSphere + +abbrev Length := {L : ℝ // 0 < L} + +instance lengthPositive (L : Length) : Fact (0 < L.val) := ⟨L.property⟩ + +abbrev Torus (L : Length) := Fin 3 → AddCircle L.val + +abbrev Configuration (N : ℕ) (L : Length) := Fin N → Torus L + +abbrev LiftedConfiguration (N : ℕ) := Fin N → Fin 3 → ℝ + +abbrev Direction (N : ℕ) := Fin N × Fin 3 + +def torusDistance (L : Length) (x y : Torus L) : ℝ := + Real.sqrt (∑ j : Fin 3, dist (x j) (y j) ^ 2) + +def allowed (N : ℕ) (L : Length) (a : ℝ) : Set (Configuration N L) := + {X | ∀ i j : Fin N, i < j → a < torusDistance L (X i) (X j)} + +def project (N : ℕ) (L : Length) (X : LiftedConfiguration N) : Configuration N L := + fun i j ↦ (X i j : AddCircle L.val) + +def representative (N : ℕ) (L : Length) (X : Configuration N L) : LiftedConfiguration N := + fun i j ↦ (AddCircle.equivIco L.val 0 (X i j)).val + +def coordDerivative (N : ℕ) (L : Length) (f : Configuration N L → ℂ) + (p : Direction N) (X : Configuration N L) : ℂ := + fderiv ℝ (fun Y : LiftedConfiguration N ↦ f (project N L Y)) + (representative N L X) (Pi.single p.1 (Pi.single p.2 1)) + +abbrev ScalarL2 (N : ℕ) (L : Length) : Type := + Lp ℂ 2 (volume : Measure (Configuration N L)) + +abbrev Jet (N : ℕ) (L : Length) := + ScalarL2 N L × (Direction N → ScalarL2 N L) + +structure SmoothTest (N : ℕ) (L : Length) (a : ℝ) where + toFun : Configuration N L → ℂ + smooth : ContDiff ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) (fun X : LiftedConfiguration N ↦ toFun (project N L X)) + compact : HasCompactSupport toFun + support_allowed : tsupport toFun ⊆ allowed N L a + memLp : MemLp toFun (2 : ℕ) (volume : Measure (Configuration N L)) + partial_memLp : ∀ p : Direction N, MemLp (coordDerivative N L toFun p) (2 : ℕ) volume + +def SmoothTest.jet {N : ℕ} {L : Length} {a : ℝ} (f : SmoothTest N L a) : Jet N L := + (f.memLp.toLp f.toFun, fun p ↦ (f.partial_memLp p).toLp (coordDerivative N L f.toFun p)) + +def dirichletDomain (N : ℕ) (L : Length) (a : ℝ) : Set (Jet N L) := + closure (Set.range (SmoothTest.jet (N := N) (L := L) (a := a))) + +def energy {N : ℕ} {L : Length} (u : Jet N L) : ℝ := + ∑ p : Direction N, ‖u.2 p‖ ^ 2 + +def bosonic {N : ℕ} {L : Length} (ψ : ScalarL2 N L) : Prop := + ∀ σ : Equiv.Perm (Fin N), + (fun X : Configuration N L ↦ ψ (fun i ↦ X (σ i))) =ᵐ[volume] ψ + +def IsGroundVector (N : ℕ) (L : Length) (a : ℝ) (u : Jet N L) : Prop := + u ∈ dirichletDomain N L a ∧ bosonic u.1 ∧ ‖u.1‖ = 1 ∧ + ∀ v ∈ dirichletDomain N L a, bosonic v.1 → ‖v.1‖ = 1 → energy u ≤ energy v + +def insertFirst {N : ℕ} (hN : 0 < N) {L : Length} + (x : Torus L) (Y : Configuration (N - 1) L) : Configuration N L := + fun i ↦ Fin.cons (α := fun _ ↦ Torus L) x Y (Fin.cast (Nat.sub_add_cancel (Nat.succ_le_of_lt hN)).symm i) + +def occupation {N : ℕ} (hN : 0 < N) {L : Length} (ψ : ScalarL2 N L) : ℝ := + (L.val ^ 3)⁻¹ * ∫ Y : Configuration (N - 1) L, + ‖∫ x : Torus L, ψ (insertFirst hN x Y)‖ ^ 2 + +namespace Density +variable (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def basisSet : Set H := (exists_hilbertBasis (𝕜:=ℂ) (E:=H)).choose + +def basis : HilbertBasis (basisSet H) ℂ H := + (exists_hilbertBasis (𝕜:=ℂ) (E:=H)).choose_spec.choose + +structure Operator where + toCLM : H →L[ℂ] H + positive : 0≤toCLM + trace_one : HasSum (fun i : basisSet H ↦ (inner ℂ (basis H i) (toCLM (basis H i))).re) 1 + +variable {H K : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + +def Operator.compressionTrace (T : Operator H) (A : H →L[ℂ] K) : ℝ := + let adjoint := DFunLike.coe (F := (H →L[ℂ] K) ≃ₗᵢ⋆[ℂ] K →L[ℂ] H) + (β := fun _ ↦ K →L[ℂ] H) ContinuousLinearMap.adjoint A + ∑' j : basisSet K,(inner ℂ (adjoint (basis K j)) (T.toCLM (adjoint (basis K j)))).re + +end Density + +namespace Orbital + +def sliceIntegral {N : ℕ} (hN : 0 omega + | succ n => + unfold insertFirst + have h := (cons_preserving (n:=n) L).comp + (Measure.measurePreserving_swap (μ:=(volume : Measure (Torus L))) (ν:=volume)) + convert h using 1 <;> simp [Function.comp_def] + + have bathFirst_preserving {N : ℕ} (hN : 0 omega + | succ n => + unfold insertFirst + have h := (cons_preserving (n:=n) L).comp + (Measure.measurePreserving_swap (μ:=(volume : Measure (Torus L))) (ν:=volume)) + convert h using 1 <;> simp [Function.comp_def] + + have bathFirst_preserving {N : ℕ} (hN : 0 omega + | succ n => + convert (MeasurableEquiv.piFinSuccAbove (fun _ : Fin (n+1) ↦ Torus L) 0).symm.measurableEmbedding.comp + (MeasurableEquiv.prodComm (α:=Configuration n L) (β:=Torus L)).measurableEmbedding using 1 <;> try rfl + funext p i + simp [insertFirst,MeasurableEquiv.piFinSuccAbove,MeasurableEquiv.prodComm]) + (fun X ↦ ‖ψ X‖^2) + rw [hm,Measure.real,volume_torus,ENNReal.toReal_ofReal (by positivity : 0≤L.val^3)] at hbound + unfold occupation + change (L.val^3)⁻¹*(∫Y,‖∫x,f (Y,x)‖^2)≤‖ψ‖^2 + calc + _ ≤ (L.val^3)⁻¹*(L.val^3*‖ψ‖^2) := mul_le_mul_of_nonneg_left hbound (by positivity) + _ = _ := by rw [←mul_assoc,inv_mul_cancel₀ (pow_ne_zero _ L.property.ne'),one_mul] + + have map_ae {N : ℕ} (hN : 0` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hard-sphere/solution/closure.txt b/tasks/hard-sphere/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a97d77149fc6427039367c6ea4d7b9665407214b --- /dev/null +++ b/tasks/hard-sphere/solution/closure.txt @@ -0,0 +1,466 @@ +OAI.Analysis.HardSphere.Allocation.AllocatedLinearity +OAI.Analysis.HardSphere.Allocation.Allocation +OAI.Analysis.HardSphere.Allocation.AllocationJoint +OAI.Analysis.HardSphere.Allocation.CertificateMeasurable +OAI.Analysis.HardSphere.Allocation.CertificateSix +OAI.Analysis.HardSphere.Allocation.CertificateSupply +OAI.Analysis.HardSphere.Allocation.CertificateTrialGeometry +OAI.Analysis.HardSphere.Allocation.CertificateUseful +OAI.Analysis.HardSphere.Allocation.CertificateWindow +OAI.Analysis.HardSphere.Allocation.CoarsePhysical +OAI.Analysis.HardSphere.Allocation.FinsetSeparatedNet +OAI.Analysis.HardSphere.Allocation.GroupJoint +OAI.Analysis.HardSphere.Allocation.LabelEncounterAverage +OAI.Analysis.HardSphere.Allocation.NearLift +OAI.Analysis.HardSphere.Allocation.NormalizedNearestSeparated +OAI.Analysis.HardSphere.Allocation.PhysicalAffinitySum +OAI.Analysis.HardSphere.Allocation.PhysicalAmbientRN +OAI.Analysis.HardSphere.Allocation.PhysicalAssembly +OAI.Analysis.HardSphere.Allocation.PhysicalAverageMoment +OAI.Analysis.HardSphere.Allocation.PhysicalBranchEstimates +OAI.Analysis.HardSphere.Allocation.PhysicalBranchLaw +OAI.Analysis.HardSphere.Allocation.PhysicalCellUniform +OAI.Analysis.HardSphere.Allocation.PhysicalCodedMoment +OAI.Analysis.HardSphere.Allocation.PhysicalDatum +OAI.Analysis.HardSphere.Allocation.PhysicalDisintegration +OAI.Analysis.HardSphere.Allocation.PhysicalFamilyLikelihood +OAI.Analysis.HardSphere.Allocation.PhysicalGroundSupply +OAI.Analysis.HardSphere.Allocation.PhysicalGroupComparison +OAI.Analysis.HardSphere.Allocation.PhysicalLabelLaw +OAI.Analysis.HardSphere.Allocation.PhysicalLifted +OAI.Analysis.HardSphere.Allocation.PhysicalLikelihood +OAI.Analysis.HardSphere.Allocation.PhysicalMidpointReference +OAI.Analysis.HardSphere.Allocation.PhysicalMixedObservation +OAI.Analysis.HardSphere.Allocation.PhysicalObservedMass +OAI.Analysis.HardSphere.Allocation.PhysicalObservedMixture +OAI.Analysis.HardSphere.Allocation.PhysicalPairedRoute +OAI.Analysis.HardSphere.Allocation.PhysicalPrimary +OAI.Analysis.HardSphere.Allocation.PhysicalProjectedPrimary +OAI.Analysis.HardSphere.Allocation.PhysicalReference +OAI.Analysis.HardSphere.Allocation.PhysicalReferenceRaw +OAI.Analysis.HardSphere.Allocation.PhysicalRouteAuxiliary +OAI.Analysis.HardSphere.Allocation.PhysicalRouteFactors +OAI.Analysis.HardSphere.Allocation.PhysicalRouteGeometry +OAI.Analysis.HardSphere.Allocation.PhysicalRouteMass +OAI.Analysis.HardSphere.Allocation.PhysicalSupply +OAI.Analysis.HardSphere.Allocation.PhysicalSupported +OAI.Analysis.HardSphere.Allocation.PhysicalTaggedDensity +OAI.Analysis.HardSphere.Allocation.PhysicalTaggedObservation +OAI.Analysis.HardSphere.Allocation.PhysicalTargets +OAI.Analysis.HardSphere.Allocation.PhysicalVertex +OAI.Analysis.HardSphere.Allocation.RouteCenters +OAI.Analysis.HardSphere.Allocation.RouteFields +OAI.Analysis.HardSphere.Allocation.SeparatedPhysical +OAI.Analysis.HardSphere.Allocation.SpatialSeparatedCloseJoint +OAI.Analysis.HardSphere.Allocation.TaggedReference +OAI.Analysis.HardSphere.Allocation.TargetSupply +OAI.Analysis.HardSphere.Allocation.WeightedExpose +OAI.Analysis.HardSphere.Bridges.AccessibleAuxiliary +OAI.Analysis.HardSphere.Bridges.ActualReverse +OAI.Analysis.HardSphere.Bridges.AffineVolume +OAI.Analysis.HardSphere.Bridges.BridgeAssemble +OAI.Analysis.HardSphere.Bridges.BridgeAverage +OAI.Analysis.HardSphere.Bridges.BridgeBlocks +OAI.Analysis.HardSphere.Bridges.BridgeHighMoment +OAI.Analysis.HardSphere.Bridges.BridgeMoment +OAI.Analysis.HardSphere.Bridges.BridgeNoise +OAI.Analysis.HardSphere.Bridges.BridgeReference +OAI.Analysis.HardSphere.Bridges.BridgeResidual +OAI.Analysis.HardSphere.Bridges.BridgeSplit +OAI.Analysis.HardSphere.Bridges.BridgeStrongRegular +OAI.Analysis.HardSphere.Bridges.BridgeWiener +OAI.Analysis.HardSphere.Bridges.BridgeWindow +OAI.Analysis.HardSphere.Bridges.CollisionBudget +OAI.Analysis.HardSphere.Bridges.ConfinedLift +OAI.Analysis.HardSphere.Bridges.EarlyTorusHit +OAI.Analysis.HardSphere.Bridges.EndpointTail +OAI.Analysis.HardSphere.Bridges.ExposedReference +OAI.Analysis.HardSphere.Bridges.GaussianDensity +OAI.Analysis.HardSphere.Bridges.GaussianMixture +OAI.Analysis.HardSphere.Bridges.GaussianPacking +OAI.Analysis.HardSphere.Bridges.Geometry +OAI.Analysis.HardSphere.Bridges.GroundBridge +OAI.Analysis.HardSphere.Bridges.IncrementMoment +OAI.Analysis.HardSphere.Bridges.Index +OAI.Analysis.HardSphere.Bridges.JointCollision +OAI.Analysis.HardSphere.Bridges.LocalReference +OAI.Analysis.HardSphere.Bridges.MeshCollision +OAI.Analysis.HardSphere.Bridges.MeshLegHit +OAI.Analysis.HardSphere.Bridges.Moment8 +OAI.Analysis.HardSphere.Bridges.NormalizedPrefix +OAI.Analysis.HardSphere.Bridges.NumericalSupply +OAI.Analysis.HardSphere.Bridges.PairSubtype +OAI.Analysis.HardSphere.Bridges.PairedMarginal +OAI.Analysis.HardSphere.Bridges.PartialIndex +OAI.Analysis.HardSphere.Bridges.PeriodShift +OAI.Analysis.HardSphere.Bridges.PhaseBridge +OAI.Analysis.HardSphere.Bridges.PhysicalEndpoint +OAI.Analysis.HardSphere.Bridges.PhysicalFactorChecks +OAI.Analysis.HardSphere.Bridges.PhysicalInsertion +OAI.Analysis.HardSphere.Bridges.PhysicalInsertionBound +OAI.Analysis.HardSphere.Bridges.PhysicalLegCollision +OAI.Analysis.HardSphere.Bridges.PhysicalPair +OAI.Analysis.HardSphere.Bridges.PhysicalSecondMoment +OAI.Analysis.HardSphere.Bridges.PhysicalSparse +OAI.Analysis.HardSphere.Bridges.PhysicalSuccess +OAI.Analysis.HardSphere.Bridges.PhysicalTrialTail +OAI.Analysis.HardSphere.Bridges.PrefixMap +OAI.Analysis.HardSphere.Bridges.PrimaryObserved +OAI.Analysis.HardSphere.Bridges.ReferenceHit +OAI.Analysis.HardSphere.Bridges.ReversePair +OAI.Analysis.HardSphere.Bridges.ReverseTime +OAI.Analysis.HardSphere.Bridges.RouteAuxiliary +OAI.Analysis.HardSphere.Bridges.RouteFrozen +OAI.Analysis.HardSphere.Bridges.RouteInsertion +OAI.Analysis.HardSphere.Bridges.RouteMarginals +OAI.Analysis.HardSphere.Bridges.RouteMass +OAI.Analysis.HardSphere.Bridges.RouteSecondMoment +OAI.Analysis.HardSphere.Bridges.SegmentMeasurable +OAI.Analysis.HardSphere.Bridges.SegmentSimplify +OAI.Analysis.HardSphere.Bridges.SelectedReverse +OAI.Analysis.HardSphere.Bridges.SupplyIntegral +OAI.Analysis.HardSphere.Bridges.TorusLocalBridge +OAI.Analysis.HardSphere.Bridges.TrialCutoff +OAI.Analysis.HardSphere.Bridges.TrialHitMeasure +OAI.Analysis.HardSphere.Bridges.TrialScalarBound +OAI.Analysis.HardSphere.Bridges.WienerGaussian +OAI.Analysis.HardSphere.Bridges.WienerStart +OAI.Analysis.HardSphere.Capacity.IntegralMulSq +OAI.Analysis.HardSphere.Capacity.SectorActiveCapacity +OAI.Analysis.HardSphere.Collisions.BalancedInsertion +OAI.Analysis.HardSphere.Collisions.FirstCoordinate +OAI.Analysis.HardSphere.Collisions.Insertion +OAI.Analysis.HardSphere.Collisions.InsertionCount +OAI.Analysis.HardSphere.Collisions.InsertionMassIntegrable +OAI.Analysis.HardSphere.Collisions.InsertionProducer +OAI.Analysis.HardSphere.Collisions.IntegrableCompInsertNth +OAI.Analysis.HardSphere.Collisions.IteratedInsertion +OAI.Analysis.HardSphere.Collisions.LocalInsertion +OAI.Analysis.HardSphere.Collisions.NormalizedInsertion +OAI.Analysis.HardSphere.Collisions.PartialPhysicalLaw +OAI.Analysis.HardSphere.Collisions.PhysicalCollision +OAI.Analysis.HardSphere.Collisions.PhysicalCollisionReference +OAI.Analysis.HardSphere.Comparison.ActiveLabels +OAI.Analysis.HardSphere.Comparison.ActualCommon +OAI.Analysis.HardSphere.Comparison.ActualOutside +OAI.Analysis.HardSphere.Comparison.Affinity +OAI.Analysis.HardSphere.Comparison.AffinityNormalization +OAI.Analysis.HardSphere.Comparison.CellAffinity +OAI.Analysis.HardSphere.Comparison.ConditionalLikelihood +OAI.Analysis.HardSphere.Comparison.ConditionalTagDensity +OAI.Analysis.HardSphere.Comparison.DensityForcesTwoParticles +OAI.Analysis.HardSphere.Comparison.ExactFiberLikelihood +OAI.Analysis.HardSphere.Comparison.FDerivIntegral +OAI.Analysis.HardSphere.Comparison.FiberNormalize +OAI.Analysis.HardSphere.Comparison.FiniteFiberSum +OAI.Analysis.HardSphere.Comparison.FrozenLikelihood +OAI.Analysis.HardSphere.Comparison.IntegratedFiber +OAI.Analysis.HardSphere.Comparison.KilledLaplace +OAI.Analysis.HardSphere.Comparison.LabelMoment +OAI.Analysis.HardSphere.Comparison.LaplaceIntegrand +OAI.Analysis.HardSphere.Comparison.LocalMoment +OAI.Analysis.HardSphere.Comparison.MixtureMoment +OAI.Analysis.HardSphere.Comparison.ParameterTarget +OAI.Analysis.HardSphere.Comparison.PartialLabelMoment +OAI.Analysis.HardSphere.Comparison.PermutationPullbackComp +OAI.Analysis.HardSphere.Comparison.PhysicalAffinity +OAI.Analysis.HardSphere.Comparison.PhysicalCellReference +OAI.Analysis.HardSphere.Comparison.PhysicalObservedLaw +OAI.Analysis.HardSphere.Comparison.PiAC +OAI.Analysis.HardSphere.Comparison.RawAngleLiftSumSquares +OAI.Analysis.HardSphere.Comparison.RouteRN +OAI.Analysis.HardSphere.Comparison.SafeMass +OAI.Analysis.HardSphere.Comparison.SumMoment +OAI.Analysis.HardSphere.Comparison.TaggedMoment +OAI.Analysis.HardSphere.Comparison.TaggedObserved +OAI.Analysis.HardSphere.CondensationDefinitions +OAI.Analysis.HardSphere.Conditioning.BathPhase +OAI.Analysis.HardSphere.Conditioning.ConditionTransport +OAI.Analysis.HardSphere.Conditioning.ConditionedCommon +OAI.Analysis.HardSphere.Conditioning.ExtraReference +OAI.Analysis.HardSphere.Conditioning.FiberDisintegrate +OAI.Analysis.HardSphere.Conditioning.GlobalExposure +OAI.Analysis.HardSphere.Conditioning.LintegralReferenceMeasure +OAI.Analysis.HardSphere.Conditioning.PairCloseLabels +OAI.Analysis.HardSphere.Conditioning.PairFiber +OAI.Analysis.HardSphere.Conditioning.PairedChecks +OAI.Analysis.HardSphere.Conditioning.PartialAlgebra +OAI.Analysis.HardSphere.Conditioning.PermutationObserved +OAI.Analysis.HardSphere.Conditioning.Phase +OAI.Analysis.HardSphere.Conditioning.PhaseMeasure +OAI.Analysis.HardSphere.Conditioning.PhaseTransfer +OAI.Analysis.HardSphere.Conditioning.PhysicalFullReference +OAI.Analysis.HardSphere.Conditioning.PhysicalObservation +OAI.Analysis.HardSphere.Conditioning.PhysicalPhase +OAI.Analysis.HardSphere.Conditioning.PhysicalRoute +OAI.Analysis.HardSphere.Conditioning.PrimaryProduct +OAI.Analysis.HardSphere.Conditioning.ProductExpose +OAI.Analysis.HardSphere.Conditioning.ProductNormalize +OAI.Analysis.HardSphere.Conditioning.ReferenceResample +OAI.Analysis.HardSphere.Conditioning.RestrictedMeasure +OAI.Analysis.HardSphere.Conditioning.RetainedObservation +OAI.Analysis.HardSphere.Conditioning.ReverseConfigurationPath +OAI.Analysis.HardSphere.Conditioning.RouteMatches +OAI.Analysis.HardSphere.Conditioning.RouteObservation +OAI.Analysis.HardSphere.Conditioning.RoutePartition +OAI.Analysis.HardSphere.Conditioning.Sampling +OAI.Analysis.HardSphere.Conditioning.SharedRoute +OAI.Analysis.HardSphere.Conditioning.SharedTransport +OAI.Analysis.HardSphere.Conditioning.SlotMultiplicity +OAI.Analysis.HardSphere.Conditioning.SupportedPair +OAI.Analysis.HardSphere.Conditioning.SymmetricTag +OAI.Analysis.HardSphere.Conditioning.TagPushforward +OAI.Analysis.HardSphere.Conditioning.UnitPairCount +OAI.Analysis.HardSphere.Conditioning.WeightedUnitPairCount +OAI.Analysis.HardSphere.Cutoffs.ChordLift +OAI.Analysis.HardSphere.Cutoffs.CloseLabels +OAI.Analysis.HardSphere.Cutoffs.CubicMoment +OAI.Analysis.HardSphere.Cutoffs.DiameterTail +OAI.Analysis.HardSphere.Cutoffs.DifferentialFormula +OAI.Analysis.HardSphere.Cutoffs.Failure +OAI.Analysis.HardSphere.Cutoffs.Mesh +OAI.Analysis.HardSphere.Cutoffs.MeshEvents +OAI.Analysis.HardSphere.Cutoffs.MeshMoment +OAI.Analysis.HardSphere.Cutoffs.Near +OAI.Analysis.HardSphere.Cutoffs.PathDiameter +OAI.Analysis.HardSphere.Cutoffs.PathLift +OAI.Analysis.HardSphere.Cutoffs.RawAngleLift +OAI.Analysis.HardSphere.Cutoffs.RegularTail +OAI.Analysis.HardSphere.Cutoffs.RegularizationWeight +OAI.Analysis.HardSphere.Cutoffs.Regularize +OAI.Analysis.HardSphere.Cutoffs.SmoothCutoff +OAI.Analysis.HardSphere.Cutoffs.StandardRegular +OAI.Analysis.HardSphere.Cutoffs.ThreeTorus +OAI.Analysis.HardSphere.Density.DensityBounds +OAI.Analysis.HardSphere.Density.DensityLinearity +OAI.Analysis.HardSphere.Density.DensityOperators +OAI.Analysis.HardSphere.Density.GroundProjection +OAI.Analysis.HardSphere.Density.GroundSpace +OAI.Analysis.HardSphere.FormDomain.AeGradientPhase +OAI.Analysis.HardSphere.FormDomain.AeSelfGradientSquare +OAI.Analysis.HardSphere.FormDomain.Basic +OAI.Analysis.HardSphere.FormDomain.CoordDerivativeParticleLocality +OAI.Analysis.HardSphere.FormDomain.DirichletScalarInjective +OAI.Analysis.HardSphere.FormDomain.Energy +OAI.Analysis.HardSphere.FormDomain.EnergyInsertionJet +OAI.Analysis.HardSphere.FormDomain.EnergyParallelogram +OAI.Analysis.HardSphere.FormDomain.HilbertJet +OAI.Analysis.HardSphere.FormDomain.RawCutoffGradientIntegral +OAI.Analysis.HardSphere.FormDomain.RayleighLarger +OAI.Analysis.HardSphere.FormDomain.RmsPermuteFunBosonic +OAI.Analysis.HardSphere.FormDomain.Slice +OAI.Analysis.HardSphere.Fourier.ArgumentAdd +OAI.Analysis.HardSphere.Fourier.CharacterDerivativeFactor +OAI.Analysis.HardSphere.Fourier.FreeCompactForm +OAI.Analysis.HardSphere.Geometry.AddedSites +OAI.Analysis.HardSphere.Geometry.AllowedProjection +OAI.Analysis.HardSphere.Geometry.AnimalFamily +OAI.Analysis.HardSphere.Geometry.AuxiliaryChecks +OAI.Analysis.HardSphere.Geometry.AvoidanceReflectionNorm +OAI.Analysis.HardSphere.Geometry.BadComponent +OAI.Analysis.HardSphere.Geometry.BadGraph +OAI.Analysis.HardSphere.Geometry.BinaryValue +OAI.Analysis.HardSphere.Geometry.BoxWeight +OAI.Analysis.HardSphere.Geometry.BufferedAllowed +OAI.Analysis.HardSphere.Geometry.CandidateConstant +OAI.Analysis.HardSphere.Geometry.CenteredCircleLift +OAI.Analysis.HardSphere.Geometry.CoeScalar +OAI.Analysis.HardSphere.Geometry.ConfigurationPath +OAI.Analysis.HardSphere.Geometry.CoordinateLine +OAI.Analysis.HardSphere.Geometry.CoordinateLineConsSucc +OAI.Analysis.HardSphere.Geometry.CubeCell +OAI.Analysis.HardSphere.Geometry.DeficiencyPenalty +OAI.Analysis.HardSphere.Geometry.DependentChecks +OAI.Analysis.HardSphere.Geometry.DiscreteTorus +OAI.Analysis.HardSphere.Geometry.EndpointDanger +OAI.Analysis.HardSphere.Geometry.EndpointLift +OAI.Analysis.HardSphere.Geometry.EndpointsExterior +OAI.Analysis.HardSphere.Geometry.EnnrealTsumFinset +OAI.Analysis.HardSphere.Geometry.EuclideanTorus +OAI.Analysis.HardSphere.Geometry.ExpWeightedMultiplier +OAI.Analysis.HardSphere.Geometry.FilledRegion +OAI.Analysis.HardSphere.Geometry.FinsetEraseRecursion +OAI.Analysis.HardSphere.Geometry.FinsetEraseRecursion2 +OAI.Analysis.HardSphere.Geometry.FinsetProd +OAI.Analysis.HardSphere.Geometry.FirstVariation +OAI.Analysis.HardSphere.Geometry.FlattenLinear +OAI.Analysis.HardSphere.Geometry.FreePathExpectation +OAI.Analysis.HardSphere.Geometry.FrozenChecks +OAI.Analysis.HardSphere.Geometry.GeneratorScalar +OAI.Analysis.HardSphere.Geometry.GraphLiftHeatBound +OAI.Analysis.HardSphere.Geometry.GridActivePenalty +OAI.Analysis.HardSphere.Geometry.GridAlignment +OAI.Analysis.HardSphere.Geometry.GridAllocation +OAI.Analysis.HardSphere.Geometry.GridCorner +OAI.Analysis.HardSphere.Geometry.GridNear +OAI.Analysis.HardSphere.Geometry.GroundPathWeight +OAI.Analysis.HardSphere.Geometry.GroundPositionLaw +OAI.Analysis.HardSphere.Geometry.HalfShiftCover +OAI.Analysis.HardSphere.Geometry.HeadLift +OAI.Analysis.HardSphere.Geometry.HeatScalar +OAI.Analysis.HardSphere.Geometry.InjectiveNear +OAI.Analysis.HardSphere.Geometry.InnerClmRealRight +OAI.Analysis.HardSphere.Geometry.IntegralConfigurationCons +OAI.Analysis.HardSphere.Geometry.JoinConfiguration +OAI.Analysis.HardSphere.Geometry.KilledAverage +OAI.Analysis.HardSphere.Geometry.KilledEigenvector +OAI.Analysis.HardSphere.Geometry.KilledObservable +OAI.Analysis.HardSphere.Geometry.LabelLift +OAI.Analysis.HardSphere.Geometry.LargeParentMarked +OAI.Analysis.HardSphere.Geometry.LiftedBadComponent +OAI.Analysis.HardSphere.Geometry.LocalAE +OAI.Analysis.HardSphere.Geometry.LocalCheck +OAI.Analysis.HardSphere.Geometry.LocalCloseLabels +OAI.Analysis.HardSphere.Geometry.LocalCloseLabelsMeasurable +OAI.Analysis.HardSphere.Geometry.LocalizedNearLabels +OAI.Analysis.HardSphere.Geometry.MicroCubeCover +OAI.Analysis.HardSphere.Geometry.MicroPeriod +OAI.Analysis.HardSphere.Geometry.MollifiedCloseCountMultiplier +OAI.Analysis.HardSphere.Geometry.MollifiedCloseJoint +OAI.Analysis.HardSphere.Geometry.NominalDrift +OAI.Analysis.HardSphere.Geometry.NormSqIntegral +OAI.Analysis.HardSphere.Geometry.NormSqLpIntegral +OAI.Analysis.HardSphere.Geometry.NormalizationDerivative +OAI.Analysis.HardSphere.Geometry.PairHistory +OAI.Analysis.HardSphere.Geometry.ParentStep +OAI.Analysis.HardSphere.Geometry.ParticleGradSq +OAI.Analysis.HardSphere.Geometry.PartitionErrorIntegral +OAI.Analysis.HardSphere.Geometry.PathEncounter +OAI.Analysis.HardSphere.Geometry.PathPermutation +OAI.Analysis.HardSphere.Geometry.PathSlots +OAI.Analysis.HardSphere.Geometry.PhysicalGeometry +OAI.Analysis.HardSphere.Geometry.PhysicalPathComparison +OAI.Analysis.HardSphere.Geometry.Point +OAI.Analysis.HardSphere.Geometry.PointFin +OAI.Analysis.HardSphere.Geometry.PositiveTimeSeqTendsto +OAI.Analysis.HardSphere.Geometry.RadialIndicator +OAI.Analysis.HardSphere.Geometry.RadiusLaw +OAI.Analysis.HardSphere.Geometry.RadiusPotential +OAI.Analysis.HardSphere.Geometry.RawAngleLift +OAI.Analysis.HardSphere.Geometry.RealComp +OAI.Analysis.HardSphere.Geometry.RoundBox +OAI.Analysis.HardSphere.Geometry.ScalarNormSqIntegral +OAI.Analysis.HardSphere.Geometry.ScalarPartitionIms +OAI.Analysis.HardSphere.Geometry.SelectedEnergyAddCompl +OAI.Analysis.HardSphere.Geometry.SelectedUnitCellPenalty +OAI.Analysis.HardSphere.Geometry.SharedFixed +OAI.Analysis.HardSphere.Geometry.SharedIdentities +OAI.Analysis.HardSphere.Geometry.ShiftClose +OAI.Analysis.HardSphere.Geometry.Sigma +OAI.Analysis.HardSphere.Geometry.SimplePath +OAI.Analysis.HardSphere.Geometry.SiteCube +OAI.Analysis.HardSphere.Geometry.SiteGroups +OAI.Analysis.HardSphere.Geometry.SliceNormSq +OAI.Analysis.HardSphere.Geometry.SmallComponent +OAI.Analysis.HardSphere.Geometry.SmoothMultiplier +OAI.Analysis.HardSphere.Geometry.SmoothSiteWeight +OAI.Analysis.HardSphere.Geometry.SmoothSpatialCountMgf +OAI.Analysis.HardSphere.Geometry.SparseChecks +OAI.Analysis.HardSphere.Geometry.SpatialGridCloseProbability +OAI.Analysis.HardSphere.Geometry.SpatialPartitionEnergy +OAI.Analysis.HardSphere.Geometry.SpatialScalarSquare +OAI.Analysis.HardSphere.Geometry.SqTwiceSqAbs +OAI.Analysis.HardSphere.Geometry.StarGraph +OAI.Analysis.HardSphere.Geometry.StarOffsets +OAI.Analysis.HardSphere.Geometry.SubcubeBase +OAI.Analysis.HardSphere.Geometry.SubsetPointLinear +OAI.Analysis.HardSphere.Geometry.TestVector +OAI.Analysis.HardSphere.Geometry.TorusBall +OAI.Analysis.HardSphere.Geometry.TorusLiftBox +OAI.Analysis.HardSphere.Geometry.TorusNear +OAI.Analysis.HardSphere.Geometry.UniformBath +OAI.Analysis.HardSphere.Geometry.UnitCenter +OAI.Analysis.HardSphere.Geometry.Vertex +OAI.Analysis.HardSphere.Kernels.ExposedPhysicalPair +OAI.Analysis.HardSphere.Kernels.ExposedTrials +OAI.Analysis.HardSphere.Kernels.FiniteKernelPi +OAI.Analysis.HardSphere.Kernels.KernelDensity +OAI.Analysis.HardSphere.Kernels.KernelPi +OAI.Analysis.HardSphere.Kernels.ParameterPair +OAI.Analysis.HardSphere.Kernels.ParameterSuccess +OAI.Analysis.HardSphere.Kernels.ParametricTrial +OAI.Analysis.HardSphere.Kernels.TrialKernel +OAI.Analysis.HardSphere.Kernels.TrialObserved +OAI.Analysis.HardSphere.Main +OAI.Analysis.HardSphere.Model +OAI.Analysis.HardSphere.Operators.CompactFormCutoff +OAI.Analysis.HardSphere.Operators.FormResolventNormEnergy +OAI.Analysis.HardSphere.Operators.FreeResolventDenseRange +OAI.Analysis.HardSphere.Operators.FreeTransition +OAI.Analysis.HardSphere.Operators.KilledTransitionAdd +OAI.Analysis.HardSphere.Operators.KilledTransitionContinuousAe +OAI.Analysis.HardSphere.Operators.KilledTransitionFormHeat +OAI.Analysis.HardSphere.Operators.Regularize +OAI.Analysis.HardSphere.Operators.SemigroupLaplaceCommute +OAI.Analysis.HardSphere.Operators.SemigroupLaplaceDerivWithin +OAI.Analysis.HardSphere.Operators.Stationary +OAI.Analysis.HardSphere.Operators.TransitionDerivative +OAI.Analysis.HardSphere.Orbitals.Bump +OAI.Analysis.HardSphere.Orbitals.CellPartition +OAI.Analysis.HardSphere.Orbitals.CenteredCell +OAI.Analysis.HardSphere.Orbitals.Chi +OAI.Analysis.HardSphere.Orbitals.Chi2 +OAI.Analysis.HardSphere.Orbitals.FieldApply +OAI.Analysis.HardSphere.Orbitals.FreePathLawFiniteDeletion +OAI.Analysis.HardSphere.Orbitals.GridLowStationary +OAI.Analysis.HardSphere.Orbitals.Joint +OAI.Analysis.HardSphere.Orbitals.Joint2 +OAI.Analysis.HardSphere.Orbitals.JointEmptyScalar +OAI.Analysis.HardSphere.Orbitals.OrbitalOperator +OAI.Analysis.HardSphere.Orbitals.PhysicalOrbitalReference +OAI.Analysis.HardSphere.Orbitals.Profile +OAI.Analysis.HardSphere.Orbitals.SelectedDeletion +OAI.Analysis.HardSphere.Orbitals.StrongContractionLimitDense +OAI.Analysis.HardSphere.PathBounds.CertificateUnion +OAI.Analysis.HardSphere.PathBounds.CloseTailBaseTendsto +OAI.Analysis.HardSphere.PathBounds.ConfigurationTailLp +OAI.Analysis.HardSphere.PathBounds.ExpNatTail +OAI.Analysis.HardSphere.PathBounds.FiberDerivativeMulTailLocal +OAI.Analysis.HardSphere.PathBounds.FreeVisitProbability +OAI.Analysis.HardSphere.PathBounds.FreeVisitTravel +OAI.Analysis.HardSphere.PathBounds.GridTailTransfer +OAI.Analysis.HardSphere.PathBounds.InteractingVisits +OAI.Analysis.HardSphere.PathBounds.LatticeExponentialSum +OAI.Analysis.HardSphere.PathBounds.PathTailConstant +OAI.Analysis.HardSphere.PathBounds.PhysicalVisitTails +OAI.Analysis.HardSphere.PathBounds.RegularVisitors +OAI.Analysis.HardSphere.PathBounds.ShiftInteracting +OAI.Analysis.HardSphere.PathBounds.ShiftTails +OAI.Analysis.HardSphere.PathBounds.ShiftUniformMGF +OAI.Analysis.HardSphere.PathBounds.SingleVisitDefect +OAI.Analysis.HardSphere.PathBounds.UniformVisitMGF +OAI.Analysis.HardSphere.PathBounds.VisitCounts +OAI.Analysis.HardSphere.PathBounds.VisitPacking +OAI.Analysis.HardSphere.Paths.AcceptedIntegrand +OAI.Analysis.HardSphere.Paths.Admissible +OAI.Analysis.HardSphere.Paths.AdmissiblePair +OAI.Analysis.HardSphere.Paths.Index +OAI.Analysis.HardSphere.Paths.LevelList +OAI.Analysis.HardSphere.Paths.LiftedSkeleton +OAI.Analysis.HardSphere.Paths.NearPotential +OAI.Analysis.HardSphere.Paths.SimpleRouteGeometry +OAI.Analysis.HardSphere.Paths.SkeletonHitConstant +OAI.Analysis.HardSphere.Paths.TimeGaps +OAI.Analysis.HardSphere.Rescaling.PhysicalRescaling +OAI.Analysis.HardSphere.Rescaling.PhysicalUnitary +OAI.Analysis.HardSphere.Thermodynamics.BridgeScaleTail +OAI.Analysis.HardSphere.Thermodynamics.CutoffAsymptotics +OAI.Analysis.HardSphere.Thermodynamics.FiniteScaledBox +OAI.Analysis.HardSphere.Thermodynamics.LowCountAbove +OAI.Analysis.HardSphere.Thermodynamics.MixedCondensation +OAI.Analysis.HardSphere.Thermodynamics.NearGridScale +OAI.Analysis.HardSphere.Thermodynamics.OccupationBound +OAI.Analysis.HardSphere.Thermodynamics.PhysicalNumeric +OAI.Analysis.HardSphere.Thermodynamics.PhysicalParameters +OAI.Analysis.HardSphere.Thermodynamics.PhysicalPhaseWindow +OAI.Analysis.HardSphere.Thermodynamics.PhysicalRescaleDomain +OAI.Analysis.HardSphere.Thermodynamics.PhysicalRescaleLp +OAI.Analysis.HardSphere.Thermodynamics.PhysicalScaleData +OAI.Analysis.HardSphere.Thermodynamics.PhysicalUniformModulus +OAI.Analysis.HardSphere.Thermodynamics.ScaledJointLowCounts +OAI.Analysis.HardSphere.Thermodynamics.ShiftCloseTail +OAI.Analysis.HardSphere.Thermodynamics.SpatialCloseScale +OAI.Analysis.HardSphere.Thermodynamics.SpatialCloseScale2 +OAI.Analysis.HardSphere.Thermodynamics.SupplyCalibration +OAI.Analysis.HardSphere.Thermodynamics.ThermodynamicCalibration +OAI.Analysis.HardSphere.Thermodynamics.TrialScale diff --git a/tasks/hard-sphere/solution/reference.py b/tasks/hard-sphere/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hard-sphere/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hard-sphere/solution/solve.sh b/tasks/hard-sphere/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..758bd7a716eccf7915b71e8e9621f01666bb9b68 --- /dev/null +++ b/tasks/hard-sphere/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HardSphere, i.e. module OAI.Analysis.HardSphere.Main and the +# 466 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.HardSphere.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HardSphere" diff --git a/tasks/hard-sphere/task.toml b/tasks/hard-sphere/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0f5f93fcea96a9ab2f250dd87f448a30b96be0da --- /dev/null +++ b/tasks/hard-sphere/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hard-sphere" +version = "1.0.0" +description = "Prove HardSphere (openai/math family 267: Positive-temperature Bose–Einstein condensation and quantum depletion) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HardSphere.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HardSphere" +family = "267" +family_title = "Positive-temperature Bose–Einstein condensation and quantum depletion" +subject = "Mathematical physics" +theorems = ["OAI.HardSphere.condensation_with_mixed"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.HardSphere.Main" +reference_modules = 466 +reference_lean_bytes = 3471981 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1367 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14824 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hard-sphere/tests/Challenge.lean b/tasks/hard-sphere/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8d6d8cdb24ca58dcdb60c6de7a02ae1e1d6bfd85 --- /dev/null +++ b/tasks/hard-sphere/tests/Challenge.lean @@ -0,0 +1,386 @@ +import Mathlib + +/-! +# Ground-state condensation in the dilute hard-sphere gas + +The main result covers all pure ground states and all density operators supported on + the ground space. In particular it covers the normalized ground-space projection. +Only the definitions needed to state this result are retained below. +-/ + +noncomputable section +open MeasureTheory Filter Set +open scoped ENNReal Topology BigOperators InnerProductSpace ComplexOrder NNReal + +namespace OAI.HardSphere + +abbrev Length := {L : ℝ // 0 < L} + +instance lengthPositive (L : Length) : Fact (0 < L.val) := ⟨L.property⟩ + +abbrev Torus (L : Length) := Fin 3 → AddCircle L.val + +abbrev Configuration (N : ℕ) (L : Length) := Fin N → Torus L + +abbrev LiftedConfiguration (N : ℕ) := Fin N → Fin 3 → ℝ + +abbrev Direction (N : ℕ) := Fin N × Fin 3 + +def torusDistance (L : Length) (x y : Torus L) : ℝ := + Real.sqrt (∑ j : Fin 3, dist (x j) (y j) ^ 2) + +def allowed (N : ℕ) (L : Length) (a : ℝ) : Set (Configuration N L) := + {X | ∀ i j : Fin N, i < j → a < torusDistance L (X i) (X j)} + +def project (N : ℕ) (L : Length) (X : LiftedConfiguration N) : Configuration N L := + fun i j ↦ (X i j : AddCircle L.val) + +def representative (N : ℕ) (L : Length) (X : Configuration N L) : LiftedConfiguration N := + fun i j ↦ (AddCircle.equivIco L.val 0 (X i j)).val + +def coordDerivative (N : ℕ) (L : Length) (f : Configuration N L → ℂ) + (p : Direction N) (X : Configuration N L) : ℂ := + fderiv ℝ (fun Y : LiftedConfiguration N ↦ f (project N L Y)) + (representative N L X) (Pi.single p.1 (Pi.single p.2 1)) + +abbrev ScalarL2 (N : ℕ) (L : Length) : Type := + Lp ℂ 2 (volume : Measure (Configuration N L)) + +abbrev Jet (N : ℕ) (L : Length) := + ScalarL2 N L × (Direction N → ScalarL2 N L) + +structure SmoothTest (N : ℕ) (L : Length) (a : ℝ) where + toFun : Configuration N L → ℂ + smooth : ContDiff ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) (fun X : LiftedConfiguration N ↦ toFun (project N L X)) + compact : HasCompactSupport toFun + support_allowed : tsupport toFun ⊆ allowed N L a + memLp : MemLp toFun (2 : ℕ) (volume : Measure (Configuration N L)) + partial_memLp : ∀ p : Direction N, MemLp (coordDerivative N L toFun p) (2 : ℕ) volume + +def SmoothTest.jet {N : ℕ} {L : Length} {a : ℝ} (f : SmoothTest N L a) : Jet N L := + (f.memLp.toLp f.toFun, fun p ↦ (f.partial_memLp p).toLp (coordDerivative N L f.toFun p)) + +def dirichletDomain (N : ℕ) (L : Length) (a : ℝ) : Set (Jet N L) := + closure (Set.range (SmoothTest.jet (N := N) (L := L) (a := a))) + +def energy {N : ℕ} {L : Length} (u : Jet N L) : ℝ := + ∑ p : Direction N, ‖u.2 p‖ ^ 2 + +def bosonic {N : ℕ} {L : Length} (ψ : ScalarL2 N L) : Prop := + ∀ σ : Equiv.Perm (Fin N), + (fun X : Configuration N L ↦ ψ (fun i ↦ X (σ i))) =ᵐ[volume] ψ + +def IsGroundVector (N : ℕ) (L : Length) (a : ℝ) (u : Jet N L) : Prop := + u ∈ dirichletDomain N L a ∧ bosonic u.1 ∧ ‖u.1‖ = 1 ∧ + ∀ v ∈ dirichletDomain N L a, bosonic v.1 → ‖v.1‖ = 1 → energy u ≤ energy v + +def insertFirst {N : ℕ} (hN : 0 < N) {L : Length} + (x : Torus L) (Y : Configuration (N - 1) L) : Configuration N L := + fun i ↦ Fin.cons (α := fun _ ↦ Torus L) x Y (Fin.cast (Nat.sub_add_cancel (Nat.succ_le_of_lt hN)).symm i) + +def occupation {N : ℕ} (hN : 0 < N) {L : Length} (ψ : ScalarL2 N L) : ℝ := + (L.val ^ 3)⁻¹ * ∫ Y : Configuration (N - 1) L, + ‖∫ x : Torus L, ψ (insertFirst hN x Y)‖ ^ 2 + +namespace Density +variable (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def basisSet : Set H := (exists_hilbertBasis (𝕜:=ℂ) (E:=H)).choose + +def basis : HilbertBasis (basisSet H) ℂ H := + (exists_hilbertBasis (𝕜:=ℂ) (E:=H)).choose_spec.choose + +structure Operator where + toCLM : H →L[ℂ] H + positive : 0≤toCLM + trace_one : HasSum (fun i : basisSet H ↦ (inner ℂ (basis H i) (toCLM (basis H i))).re) 1 + +variable {H K : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + +def Operator.compressionTrace (T : Operator H) (A : H →L[ℂ] K) : ℝ := + let adjoint := DFunLike.coe (F := (H →L[ℂ] K) ≃ₗᵢ⋆[ℂ] K →L[ℂ] H) + (β := fun _ ↦ K →L[ℂ] H) ContinuousLinearMap.adjoint A + ∑' j : basisSet K,(inner ℂ (adjoint (basis K j)) (T.toCLM (adjoint (basis K j)))).re + +end Density + +namespace Orbital + +def sliceIntegral {N : ℕ} (hN : 0 omega + | succ n => + unfold insertFirst + have h := (cons_preserving (n:=n) L).comp + (Measure.measurePreserving_swap (μ:=(volume : Measure (Torus L))) (ν:=volume)) + convert h using 1 <;> simp [Function.comp_def] + + have bathFirst_preserving {N : ℕ} (hN : 0 omega + | succ n => + unfold insertFirst + have h := (cons_preserving (n:=n) L).comp + (Measure.measurePreserving_swap (μ:=(volume : Measure (Torus L))) (ν:=volume)) + convert h using 1 <;> simp [Function.comp_def] + + have bathFirst_preserving {N : ℕ} (hN : 0 omega + | succ n => + convert (MeasurableEquiv.piFinSuccAbove (fun _ : Fin (n+1) ↦ Torus L) 0).symm.measurableEmbedding.comp + (MeasurableEquiv.prodComm (α:=Configuration n L) (β:=Torus L)).measurableEmbedding using 1 <;> try rfl + funext p i + simp [insertFirst,MeasurableEquiv.piFinSuccAbove,MeasurableEquiv.prodComm]) + (fun X ↦ ‖ψ X‖^2) + rw [hm,Measure.real,volume_torus,ENNReal.toReal_ofReal (by positivity : 0≤L.val^3)] at hbound + unfold occupation + change (L.val^3)⁻¹*(∫Y,‖∫x,f (Y,x)‖^2)≤‖ψ‖^2 + calc + _ ≤ (L.val^3)⁻¹*(L.val^3*‖ψ‖^2) := mul_le_mul_of_nonneg_left hbound (by positivity) + _ = _ := by rw [←mul_assoc,inv_mul_cancel₀ (pow_ne_zero _ L.property.ne'),one_mul] + + have map_ae {N : ℕ} (hN : 0 Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hard-sphere/tests/task.json b/tasks/hard-sphere/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e5a9b48c685338087bde7c84ce33e8c717b35131 --- /dev/null +++ b/tasks/hard-sphere/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HardSphere", + "comparator": { + "theorem_names": [ + "OAI.HardSphere.condensation_with_mixed" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13924 +} \ No newline at end of file diff --git a/tasks/hard-sphere/tests/test.sh b/tasks/hard-sphere/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hard-sphere/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/harmonic-artin/environment/Dockerfile b/tasks/harmonic-artin/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/harmonic-artin/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/harmonic-artin/environment/fetch_mathlib.sh b/tasks/harmonic-artin/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/harmonic-artin/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/harmonic-artin/environment/lake-manifest.json b/tasks/harmonic-artin/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/harmonic-artin/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/harmonic-artin/environment/lakefile.lean b/tasks/harmonic-artin/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/harmonic-artin/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/harmonic-artin/environment/lean_setup.sh b/tasks/harmonic-artin/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/harmonic-artin/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/harmonic-artin/environment/pack_submission.py b/tasks/harmonic-artin/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/harmonic-artin/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/harmonic-artin/instruction.md b/tasks/harmonic-artin/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8bf8f6b7b81734f833fb300c604d66f9e2206ebd --- /dev/null +++ b/tasks/harmonic-artin/instruction.md @@ -0,0 +1,116 @@ +# openai/math challenge `HarmonicArtin` (family 254) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 254 of the release, *Classifying spaces and geometric obstructions for Artin groups* +(Group theory). The family as a whole: The Salvetti complex of every finite-rank Artin group is aspherical, proving the Artin $K(\pi,1)$ conjecture. Arbitrary intersections of its parabolic subgroups are parabolic, proving the Parabolic Intersection Conjecture. An explicit Artin group admits no proper cocompact isometric action on any nonempty proper CAT$(0)$ space. + +The challenge is `HarmonicArtin`, also at `/opt/openai-math/challenges/HarmonicArtin.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace HarmonicArtin + +universe u + +variable {S : Type u} + +def alternating (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def braidRelators (M : CoxeterMatrix S) : Set (FreeGroup S) := + Set.range fun st : S × S => + alternating st.1 st.2 (M st.1 st.2) * + (alternating st.2 st.1 (M st.1 st.2))⁻¹ + +abbrev Artin (M : CoxeterMatrix S) := PresentedGroup (braidRelators M) + +def generator (M : CoxeterMatrix S) (s : S) : Artin M := PresentedGroup.of s + +def coxeterParabolic (M : CoxeterMatrix S) (T : Set S) : Subgroup M.Group := + Subgroup.closure (M.simple '' T) + +def IsSpherical (M : CoxeterMatrix S) (T : Set S) : Prop := + Finite (coxeterParabolic M T) + +abbrev SphericalType (M : CoxeterMatrix S) := {T : Set S // IsSpherical M T} + +abbrev LiftedCell (M : CoxeterMatrix S) := Artin M × SphericalType M + +def wordArtin (M : CoxeterMatrix S) (w : List S) : Artin M := + (w.map (generator M)).prod + +def wordCoxeter (M : CoxeterMatrix S) (w : List S) : M.Group := + (w.map M.simple).prod + +def LiftedFace (M : CoxeterMatrix S) (a b : LiftedCell M) : Prop := + a.2.1 ⊆ b.2.1 ∧ ∃ w : List S, + (∀ s ∈ w, s ∈ b.2.1) ∧ + M.toCoxeterSystem.length (wordCoxeter M w) = w.length ∧ + (∀ v : coxeterParabolic M a.2.1, + M.toCoxeterSystem.length (wordCoxeter M w) ≤ + M.toCoxeterSystem.length (wordCoxeter M w * v)) ∧ + a.1 = b.1 * wordArtin M w + +instance (M : CoxeterMatrix S) : Preorder (LiftedCell M) where + le := Relation.ReflTransGen (LiftedFace M) + le_refl _ := Relation.ReflTransGen.refl + le_trans _ _ _ := Relation.ReflTransGen.trans + +noncomputable def SalvettiCover (M : CoxeterMatrix S) : TopCat := + SSet.toTop.obj (CategoryTheory.nerve (LiftedCell M)) + +/-- The full lifted spherical-cell realization is contractible for every +Coxeter matrix with finitely many standard generators. -/ +theorem salvetti_cover_contractible [Finite S] (M : CoxeterMatrix S) : + ContractibleSpace (SalvettiCover M) := by + sorry + +end HarmonicArtin + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HarmonicArtin.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HarmonicArtin.salvetti_cover_contractible` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/harmonic-artin/solution/closure.txt b/tasks/harmonic-artin/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..892da7c765c0e04c7af3804fadaa4ca6ed16a6b1 --- /dev/null +++ b/tasks/harmonic-artin/solution/closure.txt @@ -0,0 +1,660 @@ +OAI.Topology.ArtinGroups.Cancellation.BlockPivot +OAI.Topology.ArtinGroups.Cancellation.CornerInverse +OAI.Topology.ArtinGroups.Cancellation.CornerRemainder +OAI.Topology.ArtinGroups.Cancellation.ReducedDifferential +OAI.Topology.ArtinGroups.Cancellation.ReducedDifferential2 +OAI.Topology.ArtinGroups.Cancellation.Remainder +OAI.Topology.ArtinGroups.Cancellation.Retained +OAI.Topology.ArtinGroups.Cancellation.ScalarPivot +OAI.Topology.ArtinGroups.Cancellation.SphericalPositiveCancelLeft +OAI.Topology.ArtinGroups.Cancellation.SphericalPositiveCancelMonoid +OAI.Topology.ArtinGroups.Complexes.ActedIndex +OAI.Topology.ArtinGroups.Complexes.ArrowShift +OAI.Topology.ArtinGroups.Complexes.BasedComplexComplex +OAI.Topology.ArtinGroups.Complexes.BlockClosed +OAI.Topology.ArtinGroups.Complexes.BottomScalarCycleInjective +OAI.Topology.ArtinGroups.Complexes.BottomScalarCycleZero +OAI.Topology.ArtinGroups.Complexes.BottomSocleZero +OAI.Topology.ArtinGroups.Complexes.BottomSocleZeroTest +OAI.Topology.ArtinGroups.Complexes.CanonicalLowReflectedHigh +OAI.Topology.ArtinGroups.Complexes.CanonicalWordLow +OAI.Topology.ArtinGroups.Complexes.Capped +OAI.Topology.ArtinGroups.Complexes.CochainSignSubOne +OAI.Topology.ArtinGroups.Complexes.CoconePlacement +OAI.Topology.ArtinGroups.Complexes.CoefficientIncoming +OAI.Topology.ArtinGroups.Complexes.CoefficientSocle +OAI.Topology.ArtinGroups.Complexes.CoefficientSocleRestrictLayer +OAI.Topology.ArtinGroups.Complexes.CoefficientTopDual +OAI.Topology.ArtinGroups.Complexes.CoefficientTopDualRestrict +OAI.Topology.ArtinGroups.Complexes.ColorBoundary +OAI.Topology.ArtinGroups.Complexes.ColorReduction +OAI.Topology.ArtinGroups.Complexes.ColorRestrictionTopZero +OAI.Topology.ArtinGroups.Complexes.ColorSupport +OAI.Topology.ArtinGroups.Complexes.CommuteTwistSwap +OAI.Topology.ArtinGroups.Complexes.ComplexPacketLowerBound +OAI.Topology.ArtinGroups.Complexes.ComplexPacketPreserves +OAI.Topology.ArtinGroups.Complexes.Cone +OAI.Topology.ArtinGroups.Complexes.Cone2 +OAI.Topology.ArtinGroups.Complexes.ConeMap +OAI.Topology.ArtinGroups.Complexes.ConePlacement +OAI.Topology.ArtinGroups.Complexes.CornerPath +OAI.Topology.ArtinGroups.Complexes.CorrectionBoundary +OAI.Topology.ArtinGroups.Complexes.DiagonalVertex +OAI.Topology.ArtinGroups.Complexes.Differential +OAI.Topology.ArtinGroups.Complexes.DifferentialMulExtendLayer +OAI.Topology.ArtinGroups.Complexes.DownClosed +OAI.Topology.ArtinGroups.Complexes.EmptyTestIndex +OAI.Topology.ArtinGroups.Complexes.EqualColorPair +OAI.Topology.ArtinGroups.Complexes.ExtendLayer +OAI.Topology.ArtinGroups.Complexes.FamilySubobjectMiddleLower +OAI.Topology.ArtinGroups.Complexes.FiniteFamilyLevelSupport +OAI.Topology.ArtinGroups.Complexes.FiniteHomotopySetoid +OAI.Topology.ArtinGroups.Complexes.FiniteSum +OAI.Topology.ArtinGroups.Complexes.FiniteSum2 +OAI.Topology.ArtinGroups.Complexes.FrameCappedInjection +OAI.Topology.ArtinGroups.Complexes.FrameModelLayerMiddle +OAI.Topology.ArtinGroups.Complexes.FrameModelNegativeHom +OAI.Topology.ArtinGroups.Complexes.GeneratorArray +OAI.Topology.ArtinGroups.Complexes.GeneratorArray2 +OAI.Topology.ArtinGroups.Complexes.GeneratorArrayZeroCap +OAI.Topology.ArtinGroups.Complexes.GeneratorArrayZeroLevel +OAI.Topology.ArtinGroups.Complexes.GeneratorTokenTest +OAI.Topology.ArtinGroups.Complexes.GeneratorVector +OAI.Topology.ArtinGroups.Complexes.GeneratorVectorPos +OAI.Topology.ArtinGroups.Complexes.GeneratorVectorPureLayer +OAI.Topology.ArtinGroups.Complexes.HighConeIndex +OAI.Topology.ArtinGroups.Complexes.HighConeRetainedPure +OAI.Topology.ArtinGroups.Complexes.HighDualCycleZero +OAI.Topology.ArtinGroups.Complexes.HighestLocalGeneratorTest +OAI.Topology.ArtinGroups.Complexes.HomDetector +OAI.Topology.ArtinGroups.Complexes.HomDimension +OAI.Topology.ArtinGroups.Complexes.HomDimension2 +OAI.Topology.ArtinGroups.Complexes.HomDimensionDual +OAI.Topology.ArtinGroups.Complexes.HomDimensionRetract +OAI.Topology.ArtinGroups.Complexes.HomDimensionZeroCycles +OAI.Topology.ArtinGroups.Complexes.HomDimensionZeroHom +OAI.Topology.ArtinGroups.Complexes.HomInternalSupport +OAI.Topology.ArtinGroups.Complexes.HomMono +OAI.Topology.ArtinGroups.Complexes.HomOperator +OAI.Topology.ArtinGroups.Complexes.HomPath +OAI.Topology.ArtinGroups.Complexes.HomSpace +OAI.Topology.ArtinGroups.Complexes.HomSpaceDuality +OAI.Topology.ArtinGroups.Complexes.HomSpaceMul +OAI.Topology.ArtinGroups.Complexes.HomSpacePairing +OAI.Topology.ArtinGroups.Complexes.HomStep +OAI.Topology.ArtinGroups.Complexes.HomotopyConeMap +OAI.Topology.ArtinGroups.Complexes.Identity +OAI.Topology.ArtinGroups.Complexes.Initial +OAI.Topology.ArtinGroups.Complexes.InitialHomSpaceNegative +OAI.Topology.ArtinGroups.Complexes.InitialProbeTestUpper +OAI.Topology.ArtinGroups.Complexes.InitialProjective +OAI.Topology.ArtinGroups.Complexes.InverseHomMatrix +OAI.Topology.ArtinGroups.Complexes.InverseMatrix +OAI.Topology.ArtinGroups.Complexes.InverseTwistDifferential +OAI.Topology.ArtinGroups.Complexes.InverseTwistIdentity +OAI.Topology.ArtinGroups.Complexes.InverseTwistIndex +OAI.Topology.ArtinGroups.Complexes.InverseTwistMap +OAI.Topology.ArtinGroups.Complexes.InverseTwistPlacement +OAI.Topology.ArtinGroups.Complexes.InverseWordAction +OAI.Topology.ArtinGroups.Complexes.InverseWordActionAppend +OAI.Topology.ArtinGroups.Complexes.IsolatedIndexCycle +OAI.Topology.ArtinGroups.Complexes.LayerConeEquivalence +OAI.Topology.ArtinGroups.Complexes.LayerSocleDimensionLayer +OAI.Topology.ArtinGroups.Complexes.LayerSocleDimensionSum +OAI.Topology.ArtinGroups.Complexes.LayerTotalHomDimension +OAI.Topology.ArtinGroups.Complexes.LayerVector +OAI.Topology.ArtinGroups.Complexes.LeftMatrix +OAI.Topology.ArtinGroups.Complexes.LevelArrayBelow +OAI.Topology.ArtinGroups.Complexes.LevelArrayComplexMinimal +OAI.Topology.ArtinGroups.Complexes.LevelArrayMinimalApply +OAI.Topology.ArtinGroups.Complexes.LowMatrix +OAI.Topology.ArtinGroups.Complexes.LowerTruncation +OAI.Topology.ArtinGroups.Complexes.LowerTruncationLayerFloor +OAI.Topology.ArtinGroups.Complexes.LowerTruncationSum +OAI.Topology.ArtinGroups.Complexes.MatrixOneMulExtend +OAI.Topology.ArtinGroups.Complexes.Middle +OAI.Topology.ArtinGroups.Complexes.MinimalEmbedding +OAI.Topology.ArtinGroups.Complexes.MinimalGeneratorDualCycle +OAI.Topology.ArtinGroups.Complexes.MinimalModel +OAI.Topology.ArtinGroups.Complexes.MinimalModelEquivalence +OAI.Topology.ArtinGroups.Complexes.NegativeAmplitudeCoreIndex +OAI.Topology.ArtinGroups.Complexes.NegativeConeIndex +OAI.Topology.ArtinGroups.Complexes.NegativeHomTransformReflect +OAI.Topology.ArtinGroups.Complexes.NegativeTwistCapDisjoint +OAI.Topology.ArtinGroups.Complexes.NegativeTwistLoweredGenerator +OAI.Topology.ArtinGroups.Complexes.NegativeTwistModern +OAI.Topology.ArtinGroups.Complexes.NormalizedInverseTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.NormalizedReverseTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.OptionSumEquiv +OAI.Topology.ArtinGroups.Complexes.OutsideCap +OAI.Topology.ArtinGroups.Complexes.PacketConsEquiv +OAI.Topology.ArtinGroups.Complexes.PacketLayerLowerTruncation +OAI.Topology.ArtinGroups.Complexes.PacketPermAction +OAI.Topology.ArtinGroups.Complexes.PacketPermEnumeration +OAI.Topology.ArtinGroups.Complexes.PacketPermExterior +OAI.Topology.ArtinGroups.Complexes.PacketPermPreservesOpen +OAI.Topology.ArtinGroups.Complexes.PacketPermReindex +OAI.Topology.ArtinGroups.Complexes.PacketTwistRaisedGenerator +OAI.Topology.ArtinGroups.Complexes.PacketTwistRaisedGenerator2 +OAI.Topology.ArtinGroups.Complexes.PacketTwistTopZero +OAI.Topology.ArtinGroups.Complexes.PlacedProjective +OAI.Topology.ArtinGroups.Complexes.PlacementSignedWeight +OAI.Topology.ArtinGroups.Complexes.PositiveConeIndex +OAI.Topology.ArtinGroups.Complexes.PositiveHomTransform +OAI.Topology.ArtinGroups.Complexes.PositiveTopDivisor +OAI.Topology.ArtinGroups.Complexes.PositiveTwistFiberEquiv +OAI.Topology.ArtinGroups.Complexes.PositiveTwistHomotopy +OAI.Topology.ArtinGroups.Complexes.PositiveTwistLowerBound +OAI.Topology.ArtinGroups.Complexes.PositiveTwistModern +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest2 +OAI.Topology.ArtinGroups.Complexes.PositiveTwistOtherTest3 +OAI.Topology.ArtinGroups.Complexes.PositiveTwistRaisedGenerator +OAI.Topology.ArtinGroups.Complexes.PositiveTwistUnshiftedLayer +OAI.Topology.ArtinGroups.Complexes.PositiveWord +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionAppend +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionOrthogonal +OAI.Topology.ArtinGroups.Complexes.PositiveWordActionTest +OAI.Topology.ArtinGroups.Complexes.PositiveWordLowerBound +OAI.Topology.ArtinGroups.Complexes.ProbeFixedNoDiagonal +OAI.Topology.ArtinGroups.Complexes.ProbeHomDimensionGenerator +OAI.Topology.ArtinGroups.Complexes.ProbeOrbitGeneratorExterior +OAI.Topology.ArtinGroups.Complexes.ProbeOrbitLevelDual +OAI.Topology.ArtinGroups.Complexes.PureCoefficientCohomology +OAI.Topology.ArtinGroups.Complexes.PureHomSpaceHomogeneous +OAI.Topology.ArtinGroups.Complexes.PureLayerSelf +OAI.Topology.ArtinGroups.Complexes.PureSupportedCycles +OAI.Topology.ArtinGroups.Complexes.PureTotalHomEuler +OAI.Topology.ArtinGroups.Complexes.PureUpperBoundariesZero +OAI.Topology.ArtinGroups.Complexes.ReducedAmplitudeTwistLevel +OAI.Topology.ArtinGroups.Complexes.ReducedNegativeAmplitudeTwist +OAI.Topology.ArtinGroups.Complexes.ReducedNoTopDivisor +OAI.Topology.ArtinGroups.Complexes.Refl +OAI.Topology.ArtinGroups.Complexes.Reindex +OAI.Topology.ArtinGroups.Complexes.ReindexConeIsomorphism +OAI.Topology.ArtinGroups.Complexes.ReindexHomOperator +OAI.Topology.ArtinGroups.Complexes.RestrictExtendLayerMul +OAI.Topology.ArtinGroups.Complexes.RestrictLayer +OAI.Topology.ArtinGroups.Complexes.ReverseTwistDifferential +OAI.Topology.ArtinGroups.Complexes.ReverseTwistIndexEquiv +OAI.Topology.ArtinGroups.Complexes.ReverseTwistProjection +OAI.Topology.ArtinGroups.Complexes.ReverseTwistProjectionCommute +OAI.Topology.ArtinGroups.Complexes.ScalarExactNotZero +OAI.Topology.ArtinGroups.Complexes.ScalarKernel +OAI.Topology.ArtinGroups.Complexes.ScalarSupported +OAI.Topology.ArtinGroups.Complexes.ScalarSupportedCochainShift +OAI.Topology.ArtinGroups.Complexes.ScalarSupportedTokenShift +OAI.Topology.ArtinGroups.Complexes.SecondaryLayer +OAI.Topology.ArtinGroups.Complexes.Shift +OAI.Topology.ArtinGroups.Complexes.SubobjectMiddleLowerBound +OAI.Topology.ArtinGroups.Complexes.Subrepresentation +OAI.Topology.ArtinGroups.Complexes.Sum +OAI.Topology.ArtinGroups.Complexes.SumTestEquiv +OAI.Topology.ArtinGroups.Complexes.SumTruncationEquiv +OAI.Topology.ArtinGroups.Complexes.SummandSecondary +OAI.Topology.ArtinGroups.Complexes.SupportedCoefficientCycles +OAI.Topology.ArtinGroups.Complexes.TargetLow +OAI.Topology.ArtinGroups.Complexes.TermwiseSplitInjection +OAI.Topology.ArtinGroups.Complexes.Test +OAI.Topology.ArtinGroups.Complexes.TestComplexVertexDifferential +OAI.Topology.ArtinGroups.Complexes.TestExact +OAI.Topology.ArtinGroups.Complexes.TestUpperBound +OAI.Topology.ArtinGroups.Complexes.TokenShift +OAI.Topology.ArtinGroups.Complexes.TotalHomDimensionReading +OAI.Topology.ArtinGroups.Complexes.TotalVector +OAI.Topology.ArtinGroups.Complexes.TotalVectorLayer +OAI.Topology.ArtinGroups.Complexes.TwistNewTestIndex +OAI.Topology.ArtinGroups.Complexes.UnfoldedCartanSymm +OAI.Topology.ArtinGroups.Complexes.UnfoldedPresentation +OAI.Topology.ArtinGroups.Complexes.UpperBound +OAI.Topology.ArtinGroups.Complexes.WordInverseModel +OAI.Topology.ArtinGroups.Coxeter.AltList +OAI.Topology.ArtinGroups.Coxeter.AltListMap +OAI.Topology.ArtinGroups.Coxeter.AltListPairDescent +OAI.Topology.ArtinGroups.Coxeter.AltListReduced +OAI.Topology.ArtinGroups.Coxeter.AltNext +OAI.Topology.ArtinGroups.Coxeter.AlternatingLiftProd +OAI.Topology.ArtinGroups.Coxeter.AlternatingNextRoot +OAI.Topology.ArtinGroups.Coxeter.AmbientCoxeterFace +OAI.Topology.ArtinGroups.Coxeter.ArtinCoxeter +OAI.Topology.ArtinGroups.Coxeter.BraidCoreFirstTarget +OAI.Topology.ArtinGroups.Coxeter.BraidCoreIndex +OAI.Topology.ArtinGroups.Coxeter.BraidCorePlacement +OAI.Topology.ArtinGroups.Coxeter.BraidFirstPivot +OAI.Topology.ArtinGroups.Coxeter.BraidSecondPivot +OAI.Topology.ArtinGroups.Coxeter.CanonicalReducedWordLow +OAI.Topology.ArtinGroups.Coxeter.CommonWeakPrefixMaximal +OAI.Topology.ArtinGroups.Coxeter.InverseParabolicMinimum +OAI.Topology.ArtinGroups.Coxeter.OrdinaryCoxeterMatrix +OAI.Topology.ArtinGroups.Coxeter.OrdinaryTwistBraid +OAI.Topology.ArtinGroups.Coxeter.Parabolic +OAI.Topology.ArtinGroups.Coxeter.ParabolicLongest +OAI.Topology.ArtinGroups.Coxeter.ParabolicProductMap +OAI.Topology.ArtinGroups.Coxeter.PositiveBraidRel +OAI.Topology.ArtinGroups.Coxeter.PositiveBraidRelations +OAI.Topology.ArtinGroups.Coxeter.ReducedWordProperty +OAI.Topology.ArtinGroups.Coxeter.RestrictedMatrix +OAI.Topology.ArtinGroups.Coxeter.RightParabolicDecomposition +OAI.Topology.ArtinGroups.Coxeter.Signs +OAI.Topology.ArtinGroups.Coxeter.VertexCoxeterFace +OAI.Topology.ArtinGroups.Coxeter.WeakPrefix +OAI.Topology.ArtinGroups.Coxeter.WordProdEquiv +OAI.Topology.ArtinGroups.DeligneDefinitions +OAI.Topology.ArtinGroups.Diagrams.Circle +OAI.Topology.ArtinGroups.Diagrams.CongrEquiv +OAI.Topology.ArtinGroups.Diagrams.Index +OAI.Topology.ArtinGroups.Diagrams.Relation +OAI.Topology.ArtinGroups.Diagrams.ReverseDifferential +OAI.Topology.ArtinGroups.Diagrams.SupportedKernel +OAI.Topology.ArtinGroups.Diagrams.TransposeConjugateEquiv +OAI.Topology.ArtinGroups.Functors.BasePath +OAI.Topology.ArtinGroups.Functors.ColorPacketPerm +OAI.Topology.ArtinGroups.Functors.ComplexInitial +OAI.Topology.ArtinGroups.Functors.ComplexLowerTruncation +OAI.Topology.ArtinGroups.Functors.ComplexPureLayer +OAI.Topology.ArtinGroups.Functors.ConeIndexEquiv +OAI.Topology.ArtinGroups.Functors.CoordinateExpansion +OAI.Topology.ArtinGroups.Functors.Evaluation +OAI.Topology.ArtinGroups.Functors.GeneratorVectorComplex +OAI.Topology.ArtinGroups.Functors.HomDimensionFlexible +OAI.Topology.ArtinGroups.Functors.HomDualSupportedCycles +OAI.Topology.ArtinGroups.Functors.HomSupportedCyclesEquiv +OAI.Topology.ArtinGroups.Functors.HomSwitchMap +OAI.Topology.ArtinGroups.Functors.Index +OAI.Topology.ArtinGroups.Functors.LayerIndexEquiv +OAI.Topology.ArtinGroups.Functors.LeftHomIndex +OAI.Topology.ArtinGroups.Functors.LeftHomPlacement +OAI.Topology.ArtinGroups.Functors.LeftPacketIndex +OAI.Topology.ArtinGroups.Functors.LeftSocleIndexEquiv +OAI.Topology.ArtinGroups.Functors.LevelGeneratorEquiv +OAI.Topology.ArtinGroups.Functors.OrbitHomZeroAbove +OAI.Topology.ArtinGroups.Functors.PacketSwitchMatrix +OAI.Topology.ArtinGroups.Functors.PacketTwistComparison +OAI.Topology.ArtinGroups.Functors.Path +OAI.Topology.ArtinGroups.Functors.Path2 +OAI.Topology.ArtinGroups.Functors.PathImage +OAI.Topology.ArtinGroups.Functors.PathMarked +OAI.Topology.ArtinGroups.Functors.PathSwitchEquiv +OAI.Topology.ArtinGroups.Functors.Placement +OAI.Topology.ArtinGroups.Functors.ProbeEmbeddingMap +OAI.Topology.ArtinGroups.Functors.ReversibleQuiverMap +OAI.Topology.ArtinGroups.Functors.SectorInverse +OAI.Topology.ArtinGroups.Functors.SeedEquiv +OAI.Topology.ArtinGroups.Functors.SignedPacketPerm +OAI.Topology.ArtinGroups.Functors.SignedPerm +OAI.Topology.ArtinGroups.Functors.SupportedCycles +OAI.Topology.ArtinGroups.Functors.TermwiseSplitInjection +OAI.Topology.ArtinGroups.Functors.TestIndex +OAI.Topology.ArtinGroups.Functors.TestIndex2 +OAI.Topology.ArtinGroups.Functors.TopZeroProbeSocle +OAI.Topology.ArtinGroups.Functors.TruncationIndexEquiv +OAI.Topology.ArtinGroups.Functors.TwistProdGeneratorExterior +OAI.Topology.ArtinGroups.Functors.WordOrbitCountAdjacency +OAI.Topology.ArtinGroups.Functors.WordOrbitSocleAdjacency +OAI.Topology.ArtinGroups.Functors.WordPacketPermAppend +OAI.Topology.ArtinGroups.Functors.ZigzagLinear +OAI.Topology.ArtinGroups.Geometry.Cartan +OAI.Topology.ArtinGroups.Geometry.CartanForm +OAI.Topology.ArtinGroups.Geometry.CartanOffNonpos +OAI.Topology.ArtinGroups.Geometry.CartanRestricted +OAI.Topology.ArtinGroups.Geometry.ChamberCovector +OAI.Topology.ArtinGroups.Geometry.ChamberInequalitiesConvexHull +OAI.Topology.ArtinGroups.Geometry.ChamberPoint +OAI.Topology.ArtinGroups.Geometry.ChamberPointUnique +OAI.Topology.ArtinGroups.Geometry.ConvexHullSupportedComp +OAI.Topology.ArtinGroups.Geometry.ConvexInclusion +OAI.Topology.ArtinGroups.Geometry.ConvexWord +OAI.Topology.ArtinGroups.Geometry.CoordinateExtension +OAI.Topology.ArtinGroups.Geometry.DihedralScalar +OAI.Topology.ArtinGroups.Geometry.FiniteHalfspaceBoundaryStep +OAI.Topology.ArtinGroups.Geometry.FiniteSetCenter +OAI.Topology.ArtinGroups.Geometry.Form +OAI.Topology.ArtinGroups.Geometry.InteriorConvexHullReindex +OAI.Topology.ArtinGroups.Geometry.InvariantForm +OAI.Topology.ArtinGroups.Geometry.LinearConvexHull +OAI.Topology.ArtinGroups.Geometry.LongestMulSelf +OAI.Topology.ArtinGroups.Geometry.OrbitHalfspace +OAI.Topology.ArtinGroups.Geometry.PermutahedronBallHomeomorph +OAI.Topology.ArtinGroups.Geometry.ProbeConvexEuler +OAI.Topology.ArtinGroups.Geometry.Reflect +OAI.Topology.ArtinGroups.Geometry.RestrictionLength +OAI.Topology.ArtinGroups.Geometry.RootCoeffAltExtension +OAI.Topology.ArtinGroups.Geometry.RootNonnegAscent +OAI.Topology.ArtinGroups.Geometry.RootNonposDescent +OAI.Topology.ArtinGroups.Geometry.RootPair +OAI.Topology.ArtinGroups.Geometry.RootRowOrthogonalWord +OAI.Topology.ArtinGroups.Geometry.SphericalCartanPos +OAI.Topology.ArtinGroups.Geometry.SphericalCartanPos2 +OAI.Topology.ArtinGroups.Geometry.SphericalChamberConvexHull +OAI.Topology.ArtinGroups.Geometry.StrictChamber +OAI.Topology.ArtinGroups.Geometry.StrictLinearBoundInterior +OAI.Topology.ArtinGroups.Geometry.TrigPhasePower +OAI.Topology.ArtinGroups.Geometry.TrigPhaseSqPrimitive +OAI.Topology.ArtinGroups.Harmonic.AllEligibleLower +OAI.Topology.ArtinGroups.Harmonic.ArtinAction +OAI.Topology.ArtinGroups.Harmonic.ArtinActionWordArtin +OAI.Topology.ArtinGroups.Harmonic.ArtinReindex +OAI.Topology.ArtinGroups.Harmonic.BinaryProductBoundary +OAI.Topology.ArtinGroups.Harmonic.Block +OAI.Topology.ArtinGroups.Harmonic.BottomWordNil +OAI.Topology.ArtinGroups.Harmonic.Candidate +OAI.Topology.ArtinGroups.Harmonic.CandidateBlockNonpos +OAI.Topology.ArtinGroups.Harmonic.CandidateCapped +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLow +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLowCount +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionLowExpansion +OAI.Topology.ArtinGroups.Harmonic.CanonicalFusionMultiplicity +OAI.Topology.ArtinGroups.Harmonic.CanonicalLowSupport +OAI.Topology.ArtinGroups.Harmonic.CappedCandidate +OAI.Topology.ArtinGroups.Harmonic.CappedReflectedHigh +OAI.Topology.ArtinGroups.Harmonic.CartanCommutingZero +OAI.Topology.ArtinGroups.Harmonic.CartanPairingSymm +OAI.Topology.ArtinGroups.Harmonic.Characteristic +OAI.Topology.ArtinGroups.Harmonic.CharacteristicSaturatedInterior +OAI.Topology.ArtinGroups.Harmonic.ConeAttachmentRel +OAI.Topology.ArtinGroups.Harmonic.Contradiction +OAI.Topology.ArtinGroups.Harmonic.Coset +OAI.Topology.ArtinGroups.Harmonic.CosetBelow +OAI.Topology.ArtinGroups.Harmonic.CosetExteriorCap +OAI.Topology.ArtinGroups.Harmonic.CosetOrbit +OAI.Topology.ArtinGroups.Harmonic.CosetOrbitCap +OAI.Topology.ArtinGroups.Harmonic.CosetProfile +OAI.Topology.ArtinGroups.Harmonic.CosetSignUpperTie +OAI.Topology.ArtinGroups.Harmonic.CosetSum +OAI.Topology.ArtinGroups.Harmonic.CosetVectorNullPatch +OAI.Topology.ArtinGroups.Harmonic.CosetVertex +OAI.Topology.ArtinGroups.Harmonic.Crossing +OAI.Topology.ArtinGroups.Harmonic.DimensionNonneg +OAI.Topology.ArtinGroups.Harmonic.DimensionPosMultiplicityPos +OAI.Topology.ArtinGroups.Harmonic.Earlier +OAI.Topology.ArtinGroups.Harmonic.EarlierLinkSubtypeIso +OAI.Topology.ArtinGroups.Harmonic.EarlierLower +OAI.Topology.ArtinGroups.Harmonic.EarlierLowerOrderIso +OAI.Topology.ArtinGroups.Harmonic.EarlierUpper +OAI.Topology.ArtinGroups.Harmonic.EarlyDelay +OAI.Topology.ArtinGroups.Harmonic.EigenvectorProportional +OAI.Topology.ArtinGroups.Harmonic.Eligible +OAI.Topology.ArtinGroups.Harmonic.EligibleFactor +OAI.Topology.ArtinGroups.Harmonic.EligibleLeftNonempty +OAI.Topology.ArtinGroups.Harmonic.EligibleWithin +OAI.Topology.ArtinGroups.Harmonic.Extend +OAI.Topology.ArtinGroups.Harmonic.FamilySocleFiniteTermination +OAI.Topology.ArtinGroups.Harmonic.FiniteArtinPositiveLeft +OAI.Topology.ArtinGroups.Harmonic.FiniteChainEnum +OAI.Topology.ArtinGroups.Harmonic.FiniteFusionEdge +OAI.Topology.ArtinGroups.Harmonic.FinsuppMapDomainFiber +OAI.Topology.ArtinGroups.Harmonic.FoldedCartan +OAI.Topology.ArtinGroups.Harmonic.FoldedSphericalPos +OAI.Topology.ArtinGroups.Harmonic.FrameFamily +OAI.Topology.ArtinGroups.Harmonic.FrameFamilyCapTop +OAI.Topology.ArtinGroups.Harmonic.FrameFamilyTopProportional +OAI.Topology.ArtinGroups.Harmonic.FusionColorRegion +OAI.Topology.ArtinGroups.Harmonic.FusionColorWord +OAI.Topology.ArtinGroups.Harmonic.FusionExpandedWordAction +OAI.Topology.ArtinGroups.Harmonic.FusionExpandedWordPerm +OAI.Topology.ArtinGroups.Harmonic.FusionExpressionAction +OAI.Topology.ArtinGroups.Harmonic.FusionExpressionOrbit +OAI.Topology.ArtinGroups.Harmonic.FusionFactorStep +OAI.Topology.ArtinGroups.Harmonic.FusionFold +OAI.Topology.ArtinGroups.Harmonic.FusionIntegralCartan +OAI.Topology.ArtinGroups.Harmonic.FusionLabel +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitCapMove +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorSecondary +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorSubobject +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitColorTop +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitModel +OAI.Topology.ArtinGroups.Harmonic.FusionOrbitMultiplicity +OAI.Topology.ArtinGroups.Harmonic.FusionPacketAction +OAI.Topology.ArtinGroups.Harmonic.FusionPacketLayerExterior +OAI.Topology.ArtinGroups.Harmonic.FusionPacketOrbit +OAI.Topology.ArtinGroups.Harmonic.FusionPacketPerm +OAI.Topology.ArtinGroups.Harmonic.FusionProfilePositiveEvery +OAI.Topology.ArtinGroups.Harmonic.FusionQuiverCartan +OAI.Topology.ArtinGroups.Harmonic.FusionQuiverSimpleEdge +OAI.Topology.ArtinGroups.Harmonic.FusionRest +OAI.Topology.ArtinGroups.Harmonic.FusionSignedPacketExterior +OAI.Topology.ArtinGroups.Harmonic.FusionSubobjectCartanInequality +OAI.Topology.ArtinGroups.Harmonic.FusionVertex +OAI.Topology.ArtinGroups.Harmonic.FusionZeroLabel +OAI.Topology.ArtinGroups.Harmonic.GeneratorPlacement +OAI.Topology.ArtinGroups.Harmonic.GroupProbeEuler +OAI.Topology.ArtinGroups.Harmonic.Harmonic +OAI.Topology.ArtinGroups.Harmonic.HarmonicExtension +OAI.Topology.ArtinGroups.Harmonic.HarmonicUpperAntitone +OAI.Topology.ArtinGroups.Harmonic.Incidence +OAI.Topology.ArtinGroups.Harmonic.IncidentNonnegRowPositive +OAI.Topology.ArtinGroups.Harmonic.Initial +OAI.Topology.ArtinGroups.Harmonic.InitialProbe +OAI.Topology.ArtinGroups.Harmonic.InjectiveFinrankOne +OAI.Topology.ArtinGroups.Harmonic.InsertOldIso +OAI.Topology.ArtinGroups.Harmonic.IntegerUpward +OAI.Topology.ArtinGroups.Harmonic.IntegralQuadratic +OAI.Topology.ArtinGroups.Harmonic.IntegralRowReflect +OAI.Topology.ArtinGroups.Harmonic.IntegralRowReflectApply +OAI.Topology.ArtinGroups.Harmonic.IsolatedBoundaryAbsent +OAI.Topology.ArtinGroups.Harmonic.IsolatedHarmonicLayer +OAI.Topology.ArtinGroups.Harmonic.IsolatedIterationData +OAI.Topology.ArtinGroups.Harmonic.LateDelay +OAI.Topology.ArtinGroups.Harmonic.LayerExpression +OAI.Topology.ArtinGroups.Harmonic.LeftSector +OAI.Topology.ArtinGroups.Harmonic.Level +OAI.Topology.ArtinGroups.Harmonic.LiftedDeck +OAI.Topology.ArtinGroups.Harmonic.LiftedDeckOrderHom +OAI.Topology.ArtinGroups.Harmonic.LiftedPuncturedBoundary +OAI.Topology.ArtinGroups.Harmonic.LowerIneligibleLater +OAI.Topology.ArtinGroups.Harmonic.MapPacket +OAI.Topology.ArtinGroups.Harmonic.MaximalReducedMonoidPrefix +OAI.Topology.ArtinGroups.Harmonic.MaximalReducedPositivePrefix +OAI.Topology.ArtinGroups.Harmonic.MultiplicitySum +OAI.Topology.ArtinGroups.Harmonic.MultiplicityZero +OAI.Topology.ArtinGroups.Harmonic.NegativePrepend +OAI.Topology.ArtinGroups.Harmonic.NeighborhoodProject +OAI.Topology.ArtinGroups.Harmonic.NullPatch +OAI.Topology.ArtinGroups.Harmonic.NullPatch2 +OAI.Topology.ArtinGroups.Harmonic.OrderMappingCylinder +OAI.Topology.ArtinGroups.Harmonic.PacketWord +OAI.Topology.ArtinGroups.Harmonic.PeakSupport +OAI.Topology.ArtinGroups.Harmonic.PlacementLevelFiberSum +OAI.Topology.ArtinGroups.Harmonic.PositiveComponent +OAI.Topology.ArtinGroups.Harmonic.PositiveComponentPositive +OAI.Topology.ArtinGroups.Harmonic.PositiveDegreeHom +OAI.Topology.ArtinGroups.Harmonic.PositiveDegreeSublevelFinite +OAI.Topology.ArtinGroups.Harmonic.PositiveDescentSet +OAI.Topology.ArtinGroups.Harmonic.PositiveEarlierLinkUpper +OAI.Topology.ArtinGroups.Harmonic.PositiveGradientStep +OAI.Topology.ArtinGroups.Harmonic.PositiveHead +OAI.Topology.ArtinGroups.Harmonic.PositiveLiftSimple +OAI.Topology.ArtinGroups.Harmonic.PositiveMatchingTypeKey +OAI.Topology.ArtinGroups.Harmonic.PositivePrefix +OAI.Topology.ArtinGroups.Harmonic.PositivePrefixMulLeft +OAI.Topology.ArtinGroups.Harmonic.PositiveRegion +OAI.Topology.ArtinGroups.Harmonic.PositiveRegionDeckIso +OAI.Topology.ArtinGroups.Harmonic.PositiveReverseHom +OAI.Topology.ArtinGroups.Harmonic.PositiveSimpleLiftMul +OAI.Topology.ArtinGroups.Harmonic.PositiveSupportComponent +OAI.Topology.ArtinGroups.Harmonic.PositiveUpperBoundaryRank +OAI.Topology.ArtinGroups.Harmonic.PositiveUpperBoundaryRestriction +OAI.Topology.ArtinGroups.Harmonic.PositiveWord +OAI.Topology.ArtinGroups.Harmonic.PredAboveSuccSucc +OAI.Topology.ArtinGroups.Harmonic.PrincipalOrderIso +OAI.Topology.ArtinGroups.Harmonic.PrismFlag +OAI.Topology.ArtinGroups.Harmonic.PrismGrid +OAI.Topology.ArtinGroups.Harmonic.PrismPrefix +OAI.Topology.ArtinGroups.Harmonic.PrismSimplexZero +OAI.Topology.ArtinGroups.Harmonic.ProbeActionEmbeddedHom +OAI.Topology.ArtinGroups.Harmonic.ProbeActionLevelExterior +OAI.Topology.ArtinGroups.Harmonic.ProbeActionTotalHom +OAI.Topology.ArtinGroups.Harmonic.ProbeCoreInclusion +OAI.Topology.ArtinGroups.Harmonic.ProbeCoreTermNonpos +OAI.Topology.ArtinGroups.Harmonic.ProbeFixedDiagonal +OAI.Topology.ArtinGroups.Harmonic.ProbeFixedOutside +OAI.Topology.ArtinGroups.Harmonic.ProbeOrbitAbsent +OAI.Topology.ArtinGroups.Harmonic.ProbePacket +OAI.Topology.ArtinGroups.Harmonic.ProbePacketExterior +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWord +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordAppend +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordInitial +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordLeft +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordMonoid +OAI.Topology.ArtinGroups.Harmonic.ProbePositiveWordPositive +OAI.Topology.ArtinGroups.Harmonic.ProbeRaiseLower +OAI.Topology.ArtinGroups.Harmonic.ProductBoxSlice +OAI.Topology.ArtinGroups.Harmonic.PuncturedBoundaryIso +OAI.Topology.ArtinGroups.Harmonic.QuantumNumber +OAI.Topology.ArtinGroups.Harmonic.ReducedExpression +OAI.Topology.ArtinGroups.Harmonic.ResidueActive +OAI.Topology.ArtinGroups.Harmonic.ResidueActiveEmpty +OAI.Topology.ArtinGroups.Harmonic.ResidueAllowed +OAI.Topology.ArtinGroups.Harmonic.ResidueEarlierLower +OAI.Topology.ArtinGroups.Harmonic.ResidueEarlierLowerIso +OAI.Topology.ArtinGroups.Harmonic.ResidueHeightZeroVector +OAI.Topology.ArtinGroups.Harmonic.ResidueRank +OAI.Topology.ArtinGroups.Harmonic.ResidueSingleOpen +OAI.Topology.ArtinGroups.Harmonic.ResidueZeroLowerIso +OAI.Topology.ArtinGroups.Harmonic.RestrictedArtinHom +OAI.Topology.ArtinGroups.Harmonic.RestrictedArtinHomSpherical +OAI.Topology.ArtinGroups.Harmonic.RestrictionHomRange +OAI.Topology.ArtinGroups.Harmonic.RootExtension +OAI.Topology.ArtinGroups.Harmonic.RootInclusionRange +OAI.Topology.ArtinGroups.Harmonic.RowReflect +OAI.Topology.ArtinGroups.Harmonic.RowReflectWordReverse +OAI.Topology.ArtinGroups.Harmonic.SecondaryAsSum +OAI.Topology.ArtinGroups.Harmonic.SignedLetter +OAI.Topology.ArtinGroups.Harmonic.SimpleFrontLink +OAI.Topology.ArtinGroups.Harmonic.SimplexSupport +OAI.Topology.ArtinGroups.Harmonic.SpecialResidueRank +OAI.Topology.ArtinGroups.Harmonic.SphericalFoldedMatrix +OAI.Topology.ArtinGroups.Harmonic.SphericalLongest +OAI.Topology.ArtinGroups.Harmonic.SphericalPacketWordProperty +OAI.Topology.ArtinGroups.Harmonic.SphericalPair +OAI.Topology.ArtinGroups.Harmonic.SphericalPositiveCommonMultiple +OAI.Topology.ArtinGroups.Harmonic.SphericalTypeReindex +OAI.Topology.ArtinGroups.Harmonic.Stage +OAI.Topology.ArtinGroups.Harmonic.StringAdjacent +OAI.Topology.ArtinGroups.Harmonic.SumNeighborsSubtype +OAI.Topology.ArtinGroups.Harmonic.SwitchIndex +OAI.Topology.ArtinGroups.Harmonic.TieCode +OAI.Topology.ArtinGroups.Harmonic.TopBlockMatchingKey +OAI.Topology.ArtinGroups.Harmonic.TypeComponent +OAI.Topology.ArtinGroups.Harmonic.TypedRightCoset +OAI.Topology.ArtinGroups.Harmonic.UnfoldedColorOrthogonal +OAI.Topology.ArtinGroups.Harmonic.UnfoldedFullWordMem +OAI.Topology.ArtinGroups.Harmonic.UnfoldedHom +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusion +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusionRange +OAI.Topology.ArtinGroups.Harmonic.UnfoldedInclusionRangeMono +OAI.Topology.ArtinGroups.Harmonic.UnfoldedMatrix +OAI.Topology.ArtinGroups.Harmonic.UnionCarrier +OAI.Topology.ArtinGroups.Harmonic.WordArtinSubtypeMem +OAI.Topology.ArtinGroups.Harmonic.WordFrontData +OAI.Topology.ArtinGroups.Main +OAI.Topology.ArtinGroups.Model +OAI.Topology.ArtinGroups.Quivers.ClosedNeighborhood +OAI.Topology.ArtinGroups.Quivers.CoefficientMatrix +OAI.Topology.ArtinGroups.Quivers.CornerPath +OAI.Topology.ArtinGroups.Quivers.CornerScalar +OAI.Topology.ArtinGroups.Quivers.CotestPlacement +OAI.Topology.ArtinGroups.Quivers.Dual +OAI.Topology.ArtinGroups.Quivers.EdgeContraction +OAI.Topology.ArtinGroups.Quivers.ExtArrow +OAI.Topology.ArtinGroups.Quivers.Iso +OAI.Topology.ArtinGroups.Quivers.LengthCases +OAI.Topology.ArtinGroups.Quivers.Level +OAI.Topology.ArtinGroups.Quivers.LinearMatrix +OAI.Topology.ArtinGroups.Quivers.OffDiagonalVertexZero +OAI.Topology.ArtinGroups.Quivers.OrthogonalVertices +OAI.Topology.ArtinGroups.Quivers.PacketIndex +OAI.Topology.ArtinGroups.Quivers.Path +OAI.Topology.ArtinGroups.Quivers.PathTwo +OAI.Topology.ArtinGroups.Quivers.PathTwoSelf +OAI.Topology.ArtinGroups.Quivers.PathZero +OAI.Topology.ArtinGroups.Quivers.ProbeCartanCore +OAI.Topology.ArtinGroups.Quivers.ProbeLeaf +OAI.Topology.ArtinGroups.Quivers.ProbeSimpleEdge +OAI.Topology.ArtinGroups.Quivers.ProbeSwapIso +OAI.Topology.ArtinGroups.Quivers.ProbeVertex +OAI.Topology.ArtinGroups.Quivers.Reduction +OAI.Topology.ArtinGroups.Quivers.ReversibleQuiver +OAI.Topology.ArtinGroups.Quivers.ScalarCornerMatrixDegree +OAI.Topology.ArtinGroups.Quivers.SelfCornerEquiv +OAI.Topology.ArtinGroups.Quivers.SignDiagonal +OAI.Topology.ArtinGroups.Quivers.SimpleEdge +OAI.Topology.ArtinGroups.Quivers.SmulMul +OAI.Topology.ArtinGroups.Quivers.StringArrow +OAI.Topology.ArtinGroups.Quivers.TestIndex +OAI.Topology.ArtinGroups.Quivers.TestPlacement +OAI.Topology.ArtinGroups.Quivers.TestTransform +OAI.Topology.ArtinGroups.Quivers.TokenTestVector +OAI.Topology.ArtinGroups.Quivers.TraceLinear +OAI.Topology.ArtinGroups.Quivers.UnitTestVector +OAI.Topology.ArtinGroups.Quivers.VertexHom +OAI.Topology.ArtinGroups.Quivers.VertexIdMulPath +OAI.Topology.ArtinGroups.Quivers.VertexLinear +OAI.Topology.ArtinGroups.Quivers.VertexMinimal +OAI.Topology.ArtinGroups.Realizations.AffineWeightMax +OAI.Topology.ArtinGroups.Realizations.CellDeligne +OAI.Topology.ArtinGroups.Realizations.CellIndex +OAI.Topology.ArtinGroups.Realizations.CellIndexTypeInjective +OAI.Topology.ArtinGroups.Realizations.CellInteriorChart +OAI.Topology.ArtinGroups.Realizations.CellUnion +OAI.Topology.ArtinGroups.Realizations.ConeWeights +OAI.Topology.ArtinGroups.Realizations.ContractionPoint +OAI.Topology.ArtinGroups.Realizations.DeligneRankBound +OAI.Topology.ArtinGroups.Realizations.DirectedCoverSequence +OAI.Topology.ArtinGroups.Realizations.EarlierUpperContractible +OAI.Topology.ArtinGroups.Realizations.FiniteWeightedNatSums +OAI.Topology.ArtinGroups.Realizations.FiniteWeightsCompact +OAI.Topology.ArtinGroups.Realizations.FrameFamilyWeightedLevel +OAI.Topology.ArtinGroups.Realizations.FullSphericalCell +OAI.Topology.ArtinGroups.Realizations.FusionWeightSplit +OAI.Topology.ArtinGroups.Realizations.FusionWeightedHom +OAI.Topology.ArtinGroups.Realizations.LiftedFaceChart +OAI.Topology.ArtinGroups.Realizations.LiftedWeightStar +OAI.Topology.ArtinGroups.Realizations.ModelFaceHomeomorph +OAI.Topology.ArtinGroups.Realizations.MulBlockDiagonal'Entry +OAI.Topology.ArtinGroups.Realizations.NegativeBlockContractible +OAI.Topology.ArtinGroups.Realizations.NerveChain +OAI.Topology.ArtinGroups.Realizations.NerveOrderMap +OAI.Topology.ArtinGroups.Realizations.NerveOrderRetractionEquiv +OAI.Topology.ArtinGroups.Realizations.NervePrismPatch +OAI.Topology.ArtinGroups.Realizations.NervePrismValue +OAI.Topology.ArtinGroups.Realizations.NoncriticalPositiveCell +OAI.Topology.ArtinGroups.Realizations.OrderWeights +OAI.Topology.ArtinGroups.Realizations.OrderWeightsContractibleLower +OAI.Topology.ArtinGroups.Realizations.OrderWeightsContractibleLower2 +OAI.Topology.ArtinGroups.Realizations.OrderWeightsContractibleUnique +OAI.Topology.ArtinGroups.Realizations.PartialEquivContinuousSymm +OAI.Topology.ArtinGroups.Realizations.PositiveCellPoset +OAI.Topology.ArtinGroups.Realizations.PositiveCellPoset2 +OAI.Topology.ArtinGroups.Realizations.PositiveFullCell +OAI.Topology.ArtinGroups.Realizations.PositiveLiftedCell +OAI.Topology.ArtinGroups.Realizations.PositiveRootCell +OAI.Topology.ArtinGroups.Realizations.QuotientFinrankKer +OAI.Topology.ArtinGroups.Realizations.RealizeSimplex +OAI.Topology.ArtinGroups.Realizations.RestrictedCellEmbedding +OAI.Topology.ArtinGroups.Realizations.RestrictedLiftedCell +OAI.Topology.ArtinGroups.Realizations.RestrictedLiftedContractible +OAI.Topology.ArtinGroups.Realizations.SalvettiCoverContractible +OAI.Topology.ArtinGroups.Realizations.SalvettiProjection +OAI.Topology.ArtinGroups.Realizations.WeightAffineValue +OAI.Topology.ArtinGroups.Realizations.WeightAttach +OAI.Topology.ArtinGroups.Realizations.WeightCarrier +OAI.Topology.ArtinGroups.Realizations.WeightChainCover +OAI.Topology.ArtinGroups.Realizations.WeightColor +OAI.Topology.ArtinGroups.Realizations.WeightDim +OAI.Topology.ArtinGroups.Realizations.WeightDual +OAI.Topology.ArtinGroups.Realizations.WeightEarlierLower +OAI.Topology.ArtinGroups.Realizations.WeightHomeomorph +OAI.Topology.ArtinGroups.Realizations.WeightInclusion +OAI.Topology.ArtinGroups.Realizations.WeightInsertRetract +OAI.Topology.ArtinGroups.Realizations.WeightJoinKey +OAI.Topology.ArtinGroups.Realizations.WeightLinearLinkInverse +OAI.Topology.ArtinGroups.Realizations.WeightMap +OAI.Topology.ArtinGroups.Realizations.WeightMapCover +OAI.Topology.ArtinGroups.Realizations.WeightOld +OAI.Topology.ArtinGroups.Realizations.WeightPrincipalProjection +OAI.Topology.ArtinGroups.Realizations.WeightRetractionPiece +OAI.Topology.ArtinGroups.Realizations.WeightUpperCone +OAI.Topology.ArtinGroups.Realizations.WeightVertexRetract +OAI.Topology.ArtinGroups.Realizations.WeightedCounts +OAI.Topology.ArtinGroups.Realizations.WeightedReflectedHigh diff --git a/tasks/harmonic-artin/solution/reference.py b/tasks/harmonic-artin/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/harmonic-artin/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/harmonic-artin/solution/solve.sh b/tasks/harmonic-artin/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..93e8f5c049523a31d3aba326fcb12dbf9c0130eb --- /dev/null +++ b/tasks/harmonic-artin/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HarmonicArtin, i.e. module OAI.Topology.ArtinGroups.Main and the +# 660 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Topology.ArtinGroups.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HarmonicArtin" diff --git a/tasks/harmonic-artin/task.toml b/tasks/harmonic-artin/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..925b2ec2d0347e41bae646129528cadc1aee27f0 --- /dev/null +++ b/tasks/harmonic-artin/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/harmonic-artin" +version = "1.0.0" +description = "Prove HarmonicArtin (openai/math family 254: Classifying spaces and geometric obstructions for Artin groups) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HarmonicArtin.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HarmonicArtin" +family = "254" +family_title = "Classifying spaces and geometric obstructions for Artin groups" +subject = "Group theory" +theorems = ["OAI.HarmonicArtin.salvetti_cover_contractible"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Topology.ArtinGroups.Main" +reference_modules = 660 +reference_lean_bytes = 2801461 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1612 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14221 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/harmonic-artin/tests/Challenge.lean b/tasks/harmonic-artin/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1e9134ddc8003b8cea85271c56f613b425bbec67 --- /dev/null +++ b/tasks/harmonic-artin/tests/Challenge.lean @@ -0,0 +1,65 @@ +import Mathlib + +namespace OAI + +namespace HarmonicArtin + +universe u + +variable {S : Type u} + +def alternating (s t : S) : ℕ → FreeGroup S + | 0 => 1 + | n + 1 => FreeGroup.of s * alternating t s n + +def braidRelators (M : CoxeterMatrix S) : Set (FreeGroup S) := + Set.range fun st : S × S => + alternating st.1 st.2 (M st.1 st.2) * + (alternating st.2 st.1 (M st.1 st.2))⁻¹ + +abbrev Artin (M : CoxeterMatrix S) := PresentedGroup (braidRelators M) + +def generator (M : CoxeterMatrix S) (s : S) : Artin M := PresentedGroup.of s + +def coxeterParabolic (M : CoxeterMatrix S) (T : Set S) : Subgroup M.Group := + Subgroup.closure (M.simple '' T) + +def IsSpherical (M : CoxeterMatrix S) (T : Set S) : Prop := + Finite (coxeterParabolic M T) + +abbrev SphericalType (M : CoxeterMatrix S) := {T : Set S // IsSpherical M T} + +abbrev LiftedCell (M : CoxeterMatrix S) := Artin M × SphericalType M + +def wordArtin (M : CoxeterMatrix S) (w : List S) : Artin M := + (w.map (generator M)).prod + +def wordCoxeter (M : CoxeterMatrix S) (w : List S) : M.Group := + (w.map M.simple).prod + +def LiftedFace (M : CoxeterMatrix S) (a b : LiftedCell M) : Prop := + a.2.1 ⊆ b.2.1 ∧ ∃ w : List S, + (∀ s ∈ w, s ∈ b.2.1) ∧ + M.toCoxeterSystem.length (wordCoxeter M w) = w.length ∧ + (∀ v : coxeterParabolic M a.2.1, + M.toCoxeterSystem.length (wordCoxeter M w) ≤ + M.toCoxeterSystem.length (wordCoxeter M w * v)) ∧ + a.1 = b.1 * wordArtin M w + +instance (M : CoxeterMatrix S) : Preorder (LiftedCell M) where + le := Relation.ReflTransGen (LiftedFace M) + le_refl _ := Relation.ReflTransGen.refl + le_trans _ _ _ := Relation.ReflTransGen.trans + +noncomputable def SalvettiCover (M : CoxeterMatrix S) : TopCat := + SSet.toTop.obj (CategoryTheory.nerve (LiftedCell M)) + +/-- The full lifted spherical-cell realization is contractible for every +Coxeter matrix with finitely many standard generators. -/ +theorem salvetti_cover_contractible [Finite S] (M : CoxeterMatrix S) : + ContractibleSpace (SalvettiCover M) := by + sorry + +end HarmonicArtin + +end OAI diff --git a/tasks/harmonic-artin/tests/grade.py b/tasks/harmonic-artin/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/harmonic-artin/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/harmonic-artin/tests/task.json b/tasks/harmonic-artin/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d56ce73823705680f2fc3448bb8cba1b352b6307 --- /dev/null +++ b/tasks/harmonic-artin/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HarmonicArtin", + "comparator": { + "theorem_names": [ + "OAI.HarmonicArtin.salvetti_cover_contractible" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13321 +} \ No newline at end of file diff --git a/tasks/harmonic-artin/tests/test.sh b/tasks/harmonic-artin/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/harmonic-artin/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/harmonic-growth/environment/Dockerfile b/tasks/harmonic-growth/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/harmonic-growth/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/harmonic-growth/environment/fetch_mathlib.sh b/tasks/harmonic-growth/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/harmonic-growth/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/harmonic-growth/environment/lake-manifest.json b/tasks/harmonic-growth/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/harmonic-growth/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/harmonic-growth/environment/lakefile.lean b/tasks/harmonic-growth/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/harmonic-growth/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/harmonic-growth/environment/lean_setup.sh b/tasks/harmonic-growth/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/harmonic-growth/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/harmonic-growth/environment/pack_submission.py b/tasks/harmonic-growth/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/harmonic-growth/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/harmonic-growth/instruction.md b/tasks/harmonic-growth/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34f94637721d3eb86e541cceb5ab02926bfdd6a0 --- /dev/null +++ b/tasks/harmonic-growth/instruction.md @@ -0,0 +1,159 @@ +# openai/math challenge `HarmonicGrowth` (family 361) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 361 of the release, *Counterexamples to Yau's harmonic dimension bound* +(Differential geometry). The family as a whole: Disproves Yau's proposed Euclidean dimension bound for harmonic functions of integer growth on manifolds with nonnegative Ricci curvature. For every sufficiently large integer $k$, a complete smooth metric on $\mathbb R^3$ has at least $(k+2)^2$ independent harmonic functions of growth at most $k$, exceeding the Euclidean count $(k+1)^2$. The metric may depend on $k$. + +The challenge is `HarmonicGrowth`, also at `/opt/openai-math/challenges/HarmonicGrowth.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Filter MeasureTheory +open scoped BigOperators Topology ENNReal ContDiff + +namespace HarmonicCounterexample + +abbrev Space (n : ℕ) := Fin n → ℝ +abbrev Mat (n : ℕ) := Matrix (Fin n) (Fin n) ℝ + +/-- A genuine smooth positive definite covariant metric tensor on R^n. -/ +structure SmoothMetric (n : ℕ) where + coeff : Space n → Mat n + smooth : ∀ i j, ContDiff ℝ ∞ (fun x => coeff x i j) + positive : ∀ x, (coeff x).PosDef + +/-- The coordinate directional derivative. -/ +def coordDeriv {n : ℕ} (i : Fin n) (f : Space n → ℝ) (x : Space n) : ℝ := + fderiv ℝ f x (Pi.single i 1) + +/-- Levi-Civita connection in the single global Cartesian chart. -/ +def christoffel {n : ℕ} (g : SmoothMetric n) (x : Space n) + (k i j : Fin n) : ℝ := + (1 / 2 : ℝ) * ∑ l, (g.coeff x)⁻¹ k l * + (coordDeriv i (fun y => g.coeff y j l) x + + coordDeriv j (fun y => g.coeff y i l) x - + coordDeriv l (fun y => g.coeff y i j) x) + +/-- Ricci tensor, with the convention in which the round sphere has positive Ricci. -/ +def ricci {n : ℕ} (g : SmoothMetric n) (x : Space n) (i j : Fin n) : ℝ := + (∑ k, (coordDeriv k (fun y => christoffel g y k i j) x - + coordDeriv j (fun y => christoffel g y k i k) x)) + + ∑ k, ∑ l, (christoffel g x k i j * christoffel g x l k l - + christoffel g x l i k * christoffel g x k j l) + +def RicciNonnegative {n : ℕ} (g : SmoothMetric n) : Prop := + ∀ (x v : Space n), 0 ≤ ∑ i, ∑ j, ricci g x i j * v i * v j + +/-- Trace of the covariant Hessian, i.e. the Laplace-Beltrami operator. -/ +def laplaceBeltrami {n : ℕ} (g : SmoothMetric n) (u : Space n → ℝ) + (x : Space n) : ℝ := + ∑ i, ∑ j, (g.coeff x)⁻¹ i j * + (coordDeriv i (coordDeriv j u) x - ∑ k, christoffel g x k i j * coordDeriv k u x) + +/-- Riemannian length of a path on the unit parameter interval. -/ +def pathLength {n : ℕ} (g : SmoothMetric n) (γ : ℝ → Space n) : ℝ := + ∫ t in (0 : ℝ)..1, Real.sqrt + (∑ i, ∑ j, g.coeff (γ t) i j * deriv γ t i * deriv γ t j) + +/-- Infimum of smooth path lengths, the intrinsic Riemannian distance. -/ +def distance {n : ℕ} (g : SmoothMetric n) (x y : Space n) : ℝ := + sInf {L : ℝ | ∃ γ : ℝ → Space n, + ContDiff ℝ 1 γ ∧ γ 0 = x ∧ γ 1 = y ∧ L = pathLength g γ} + +/-- Sequential metric completeness, for the intrinsic distance, not the background one. -/ +def Complete {n : ℕ} (g : SmoothMetric n) : Prop := + ∀ z : ℕ → Space n, + (∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ p ≥ N, ∀ q ≥ N, distance g (z p) (z q) < ε) → + ∃ x : Space n, ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ p ≥ N, distance g (z p) x < ε + +def EuclideanNearOrigin {n : ℕ} (g : SmoothMetric n) : Prop := + ∃ ε : ℝ, 0 < ε ∧ ∀ x : Space n, (∑ i, x i ^ 2) < ε ^ 2 → g.coeff x = 1 + +/-- Riemannian measure of the intrinsic open ball, retaining infinite values. -/ +def ballVolume {n : ℕ} (g : SmoothMetric n) (R : ℝ) : ℝ≥0∞ := + ∫⁻ x in {x : Space n | distance g 0 x < R}, + ENNReal.ofReal (Real.sqrt (g.coeff x).det) ∂volume + +/-- The ordinary Euclidean unit ball volume, in Cartesian Lebesgue measure. -/ +def omega (n : ℕ) : ℝ≥0∞ := + volume {x : Space n | (∑ i, x i ^ 2) < 1} + +/-- The volume-ratio limit is finite, positive, and strictly below one. -/ +def PositiveSubunitAVR {n : ℕ} (g : SmoothMetric n) : Prop := + ∃ a : ℝ, 0 < a ∧ a < 1 ∧ + Tendsto (fun R : ℝ => ballVolume g R / (omega n * ENNReal.ofReal (R ^ n))) + atTop (𝓝 (ENNReal.ofReal a)) + +/-- Membership in the actual space H_k, with the bound required at every point. -/ +def HarmonicGrowth {n : ℕ} (g : SmoothMetric n) (k : ℕ) (u : Space n → ℝ) : Prop := + ContDiff ℝ ∞ u ∧ (∀ x, laplaceBeltrami g u x = 0) ∧ + ∃ C : ℝ, 0 ≤ C ∧ ∀ x, |u x| ≤ C * (1 + distance g 0 x) ^ k + + +def euclideanDimension (n k : ℕ) : ℕ := + (n + k - 1).choose k + (n + k - 2).choose (k - 1) + +/-- The manuscript's unconditional main existence claim. -/ +def MainClaim : Prop := + ∃ (n k : ℕ) (g : SmoothMetric n), Even n ∧ 8 ≤ n ∧ 2 ≤ k ∧ + Complete g ∧ RicciNonnegative g ∧ EuclideanNearOrigin g ∧ PositiveSubunitAVR g ∧ + ∃ u : Fin (euclideanDimension n k + 1) → (Space n → ℝ), + LinearIndependent ℝ u ∧ ∀ i, HarmonicGrowth g k (u i) + + + +axiom mainStatement : MainClaim + +theorem main : MainClaim := mainStatement + +end HarmonicCounterexample + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HarmonicGrowth.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HarmonicCounterexample.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/harmonic-growth/solution/closure.txt b/tasks/harmonic-growth/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1113c46880fb79746e13dbff07e41e6739aa944d --- /dev/null +++ b/tasks/harmonic-growth/solution/closure.txt @@ -0,0 +1,36 @@ +OAI.Geometry.HarmonicGrowth.Angular +OAI.Geometry.HarmonicGrowth.AngularStream +OAI.Geometry.HarmonicGrowth.AngularTrace +OAI.Geometry.HarmonicGrowth.Attainment +OAI.Geometry.HarmonicGrowth.Basic +OAI.Geometry.HarmonicGrowth.Berger +OAI.Geometry.HarmonicGrowth.ComplexHarmonics +OAI.Geometry.HarmonicGrowth.ControlWords +OAI.Geometry.HarmonicGrowth.Counting +OAI.Geometry.HarmonicGrowth.Curvature +OAI.Geometry.HarmonicGrowth.Cycling +OAI.Geometry.HarmonicGrowth.Damping +OAI.Geometry.HarmonicGrowth.EndpointBounds +OAI.Geometry.HarmonicGrowth.Flow +OAI.Geometry.HarmonicGrowth.GlobalControl +OAI.Geometry.HarmonicGrowth.Growth +OAI.Geometry.HarmonicGrowth.HopfSpectrum +OAI.Geometry.HarmonicGrowth.InsertedWord +OAI.Geometry.HarmonicGrowth.Intrinsic +OAI.Geometry.HarmonicGrowth.LieGeneration +OAI.Geometry.HarmonicGrowth.LieSaturation +OAI.Geometry.HarmonicGrowth.Main +OAI.Geometry.HarmonicGrowth.PolarGeometry +OAI.Geometry.HarmonicGrowth.PolynomialControl +OAI.Geometry.HarmonicGrowth.Profiles +OAI.Geometry.HarmonicGrowth.PulseODE +OAI.Geometry.HarmonicGrowth.PulseSystem +OAI.Geometry.HarmonicGrowth.RealForms +OAI.Geometry.HarmonicGrowth.Realization +OAI.Geometry.HarmonicGrowth.ScalarODE +OAI.Geometry.HarmonicGrowth.SmoothWord +OAI.Geometry.HarmonicGrowth.SpectralSelection +OAI.Geometry.HarmonicGrowth.StreamData +OAI.Geometry.HarmonicGrowth.Taylor +OAI.Geometry.HarmonicGrowth.Transmission +OAI.Geometry.HarmonicGrowth.Variation diff --git a/tasks/harmonic-growth/solution/reference.py b/tasks/harmonic-growth/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/harmonic-growth/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/harmonic-growth/solution/solve.sh b/tasks/harmonic-growth/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..479a4fb785bf95430f75acfbc6abbb70edc243d9 --- /dev/null +++ b/tasks/harmonic-growth/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HarmonicGrowth, i.e. module OAI.Geometry.HarmonicGrowth.Main and the +# 36 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.HarmonicGrowth.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HarmonicGrowth" diff --git a/tasks/harmonic-growth/task.toml b/tasks/harmonic-growth/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4fad6de8d95fc3e74d85792bb070c8889797ff03 --- /dev/null +++ b/tasks/harmonic-growth/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/harmonic-growth" +version = "1.0.0" +description = "Prove HarmonicGrowth (openai/math family 361: Counterexamples to Yau's harmonic dimension bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HarmonicGrowth.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HarmonicGrowth" +family = "361" +family_title = "Counterexamples to Yau's harmonic dimension bound" +subject = "Differential geometry" +theorems = ["OAI.HarmonicCounterexample.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.HarmonicGrowth.Main" +reference_modules = 36 +reference_lean_bytes = 1683568 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1761 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13215 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/harmonic-growth/tests/Challenge.lean b/tasks/harmonic-growth/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca69bf3398e3841bae4fdbb4619528bba36e3255 --- /dev/null +++ b/tasks/harmonic-growth/tests/Challenge.lean @@ -0,0 +1,108 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Filter MeasureTheory +open scoped BigOperators Topology ENNReal ContDiff + +namespace HarmonicCounterexample + +abbrev Space (n : ℕ) := Fin n → ℝ +abbrev Mat (n : ℕ) := Matrix (Fin n) (Fin n) ℝ + +/-- A genuine smooth positive definite covariant metric tensor on R^n. -/ +structure SmoothMetric (n : ℕ) where + coeff : Space n → Mat n + smooth : ∀ i j, ContDiff ℝ ∞ (fun x => coeff x i j) + positive : ∀ x, (coeff x).PosDef + +/-- The coordinate directional derivative. -/ +def coordDeriv {n : ℕ} (i : Fin n) (f : Space n → ℝ) (x : Space n) : ℝ := + fderiv ℝ f x (Pi.single i 1) + +/-- Levi-Civita connection in the single global Cartesian chart. -/ +def christoffel {n : ℕ} (g : SmoothMetric n) (x : Space n) + (k i j : Fin n) : ℝ := + (1 / 2 : ℝ) * ∑ l, (g.coeff x)⁻¹ k l * + (coordDeriv i (fun y => g.coeff y j l) x + + coordDeriv j (fun y => g.coeff y i l) x - + coordDeriv l (fun y => g.coeff y i j) x) + +/-- Ricci tensor, with the convention in which the round sphere has positive Ricci. -/ +def ricci {n : ℕ} (g : SmoothMetric n) (x : Space n) (i j : Fin n) : ℝ := + (∑ k, (coordDeriv k (fun y => christoffel g y k i j) x - + coordDeriv j (fun y => christoffel g y k i k) x)) + + ∑ k, ∑ l, (christoffel g x k i j * christoffel g x l k l - + christoffel g x l i k * christoffel g x k j l) + +def RicciNonnegative {n : ℕ} (g : SmoothMetric n) : Prop := + ∀ (x v : Space n), 0 ≤ ∑ i, ∑ j, ricci g x i j * v i * v j + +/-- Trace of the covariant Hessian, i.e. the Laplace-Beltrami operator. -/ +def laplaceBeltrami {n : ℕ} (g : SmoothMetric n) (u : Space n → ℝ) + (x : Space n) : ℝ := + ∑ i, ∑ j, (g.coeff x)⁻¹ i j * + (coordDeriv i (coordDeriv j u) x - ∑ k, christoffel g x k i j * coordDeriv k u x) + +/-- Riemannian length of a path on the unit parameter interval. -/ +def pathLength {n : ℕ} (g : SmoothMetric n) (γ : ℝ → Space n) : ℝ := + ∫ t in (0 : ℝ)..1, Real.sqrt + (∑ i, ∑ j, g.coeff (γ t) i j * deriv γ t i * deriv γ t j) + +/-- Infimum of smooth path lengths, the intrinsic Riemannian distance. -/ +def distance {n : ℕ} (g : SmoothMetric n) (x y : Space n) : ℝ := + sInf {L : ℝ | ∃ γ : ℝ → Space n, + ContDiff ℝ 1 γ ∧ γ 0 = x ∧ γ 1 = y ∧ L = pathLength g γ} + +/-- Sequential metric completeness, for the intrinsic distance, not the background one. -/ +def Complete {n : ℕ} (g : SmoothMetric n) : Prop := + ∀ z : ℕ → Space n, + (∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ p ≥ N, ∀ q ≥ N, distance g (z p) (z q) < ε) → + ∃ x : Space n, ∀ ε : ℝ, 0 < ε → ∃ N : ℕ, ∀ p ≥ N, distance g (z p) x < ε + +def EuclideanNearOrigin {n : ℕ} (g : SmoothMetric n) : Prop := + ∃ ε : ℝ, 0 < ε ∧ ∀ x : Space n, (∑ i, x i ^ 2) < ε ^ 2 → g.coeff x = 1 + +/-- Riemannian measure of the intrinsic open ball, retaining infinite values. -/ +def ballVolume {n : ℕ} (g : SmoothMetric n) (R : ℝ) : ℝ≥0∞ := + ∫⁻ x in {x : Space n | distance g 0 x < R}, + ENNReal.ofReal (Real.sqrt (g.coeff x).det) ∂volume + +/-- The ordinary Euclidean unit ball volume, in Cartesian Lebesgue measure. -/ +def omega (n : ℕ) : ℝ≥0∞ := + volume {x : Space n | (∑ i, x i ^ 2) < 1} + +/-- The volume-ratio limit is finite, positive, and strictly below one. -/ +def PositiveSubunitAVR {n : ℕ} (g : SmoothMetric n) : Prop := + ∃ a : ℝ, 0 < a ∧ a < 1 ∧ + Tendsto (fun R : ℝ => ballVolume g R / (omega n * ENNReal.ofReal (R ^ n))) + atTop (𝓝 (ENNReal.ofReal a)) + +/-- Membership in the actual space H_k, with the bound required at every point. -/ +def HarmonicGrowth {n : ℕ} (g : SmoothMetric n) (k : ℕ) (u : Space n → ℝ) : Prop := + ContDiff ℝ ∞ u ∧ (∀ x, laplaceBeltrami g u x = 0) ∧ + ∃ C : ℝ, 0 ≤ C ∧ ∀ x, |u x| ≤ C * (1 + distance g 0 x) ^ k + + +def euclideanDimension (n k : ℕ) : ℕ := + (n + k - 1).choose k + (n + k - 2).choose (k - 1) + +/-- The manuscript's unconditional main existence claim. -/ +def MainClaim : Prop := + ∃ (n k : ℕ) (g : SmoothMetric n), Even n ∧ 8 ≤ n ∧ 2 ≤ k ∧ + Complete g ∧ RicciNonnegative g ∧ EuclideanNearOrigin g ∧ PositiveSubunitAVR g ∧ + ∃ u : Fin (euclideanDimension n k + 1) → (Space n → ℝ), + LinearIndependent ℝ u ∧ ∀ i, HarmonicGrowth g k (u i) + + + +axiom mainStatement : MainClaim + +theorem main : MainClaim := mainStatement + +end HarmonicCounterexample + +end + +end OAI diff --git a/tasks/harmonic-growth/tests/grade.py b/tasks/harmonic-growth/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/harmonic-growth/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/harmonic-growth/tests/task.json b/tasks/harmonic-growth/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..13041ae07f31f0cea4fbd60c36b83a34dc2a0f70 --- /dev/null +++ b/tasks/harmonic-growth/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HarmonicGrowth", + "comparator": { + "theorem_names": [ + "OAI.HarmonicCounterexample.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12315 +} \ No newline at end of file diff --git a/tasks/harmonic-growth/tests/test.sh b/tasks/harmonic-growth/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/harmonic-growth/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/heilbronn-triangle/environment/Dockerfile b/tasks/heilbronn-triangle/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/heilbronn-triangle/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/heilbronn-triangle/environment/fetch_mathlib.sh b/tasks/heilbronn-triangle/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/heilbronn-triangle/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/heilbronn-triangle/environment/lake-manifest.json b/tasks/heilbronn-triangle/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/heilbronn-triangle/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/heilbronn-triangle/environment/lakefile.lean b/tasks/heilbronn-triangle/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/heilbronn-triangle/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/heilbronn-triangle/environment/lean_setup.sh b/tasks/heilbronn-triangle/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/heilbronn-triangle/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/heilbronn-triangle/environment/pack_submission.py b/tasks/heilbronn-triangle/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/heilbronn-triangle/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/heilbronn-triangle/instruction.md b/tasks/heilbronn-triangle/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e3169d38558f95a1e935ec161ce3fc6cb867bd16 --- /dev/null +++ b/tasks/heilbronn-triangle/instruction.md @@ -0,0 +1,119 @@ +# openai/math challenge `HeilbronnTriangle` (family 191) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 191 of the release, *A power improvement in the Heilbronn triangle problem* +(Combinatorics). The family as a whole: For every sufficiently large $n$, constructs $n$ points in the unit square such that every triangle has area at least $n^{-2+c}$ for one absolute $c>0$. This disproves the conjectured almost-$n^{-2}$ upper bound in Heilbronn's triangle problem, which asks how large the smallest determined triangle can be. + +The challenge is `HeilbronnTriangle`, also at `/opt/openai-math/challenges/HeilbronnTriangle.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem355 + +abbrev Point := ℝ × ℝ + +def triangleArea (p q r : Point) : ℝ := + abs ((q.1 - p.1) * (r.2 - p.2) - (q.2 - p.2) * (r.1 - p.1)) / 2 + +def pointInUnitSquare (p : Point) : Prop := + 0 ≤ p.1 ∧ p.1 ≤ 1 ∧ 0 ≤ p.2 ∧ p.2 ≤ 1 + +def pointsInUnitSquare (P : Finset Point) : Prop := by + classical + exact ∀ p, p ∈ P → pointInUnitSquare p + +def triangleAreasAtLeast (P : Finset Point) (a : ℝ) : Prop := by + classical + exact ∀ p, p ∈ P → ∀ q, q ∈ P → ∀ r, r ∈ P → + p ≠ q → p ≠ r → q ≠ r → a ≤ triangleArea p q r + +def hasTriangleAreaAtMost (P : Finset Point) (a : ℝ) : Prop := by + classical + exact ∃ p, p ∈ P ∧ ∃ q, q ∈ P ∧ ∃ r, r ∈ P ∧ + p ≠ q ∧ p ≠ r ∧ q ≠ r ∧ triangleArea p q r ≤ a + +def heilbronnD : ℕ := 41 + +def heilbronnM : ℕ := Nat.choose (4 * heilbronnD - 1) heilbronnD + +def heilbronnT : ℕ := Nat.choose heilbronnM 3 + +def heilbronnK : ℕ := heilbronnT ^ 2 + 1 + +def heilbronnExponent : ℝ := + 1 / (100000 * (heilbronnK : ℝ)) + +def eventualAlmostUpperBound (epsilon : ℝ) : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ n0 : ℕ, ∀ n : ℕ, n0 ≤ n → 3 ≤ n → + ∀ P : Finset Point, P.card = n → pointsInUnitSquare P → + hasTriangleAreaAtMost P + (C * Real.rpow (n : ℝ) (-2 + epsilon)) + +attribute [local irreducible] Problem355.heilbronnT + Problem355.heilbronnM + +theorem heilbronn_power_lower_bound : + 0 < heilbronnExponent ∧ ∃ n : ℕ → ℕ, ∃ P : ℕ → Finset Point, + Filter.Tendsto n Filter.atTop Filter.atTop ∧ ∀ j : ℕ, + 3 ≤ n j ∧ (P j).card = n j ∧ pointsInUnitSquare (P j) ∧ + triangleAreasAtLeast (P j) + (Real.rpow (n j : ℝ) (-2 + heilbronnExponent)) := by + sorry + +theorem almost_n_minus_two_refuted : + 0 < heilbronnExponent / 2 ∧ + ¬ eventualAlmostUpperBound (heilbronnExponent / 2) := by + sorry + +end Problem355 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HeilbronnTriangle.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Problem355.heilbronn_power_lower_bound`, `OAI.Problem355.almost_n_minus_two_refuted` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/heilbronn-triangle/solution/closure.txt b/tasks/heilbronn-triangle/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c432ac1c657b4c600be8aa47e25cef692e469d97 --- /dev/null +++ b/tasks/heilbronn-triangle/solution/closure.txt @@ -0,0 +1,195 @@ +OAI.Geometry.HeilbronnTriangle.ActualPointLaw +OAI.Geometry.HeilbronnTriangle.ActualPointLawTriples +OAI.Geometry.HeilbronnTriangle.ActualWeightedFiberCount +OAI.Geometry.HeilbronnTriangle.AffineShellCount +OAI.Geometry.HeilbronnTriangle.AffineTripleOrbit +OAI.Geometry.HeilbronnTriangle.AllowedShifts +OAI.Geometry.HeilbronnTriangle.AlterationAsymptotics +OAI.Geometry.HeilbronnTriangle.AnisotropicCount +OAI.Geometry.HeilbronnTriangle.AnisotropicDyadic +OAI.Geometry.HeilbronnTriangle.AnisotropicGeometry +OAI.Geometry.HeilbronnTriangle.AnisotropicPlaneData +OAI.Geometry.HeilbronnTriangle.AuxiliaryAffineWeights +OAI.Geometry.HeilbronnTriangle.AuxiliaryCap +OAI.Geometry.HeilbronnTriangle.AuxiliaryIntegralSupport +OAI.Geometry.HeilbronnTriangle.AuxiliarySamplingLaw +OAI.Geometry.HeilbronnTriangle.AuxiliarySamplingSupport +OAI.Geometry.HeilbronnTriangle.AuxiliarySet +OAI.Geometry.HeilbronnTriangle.AuxiliarySupport +OAI.Geometry.HeilbronnTriangle.AuxiliaryThreeCase +OAI.Geometry.HeilbronnTriangle.AuxiliaryWeights +OAI.Geometry.HeilbronnTriangle.AuxiliaryZeroCount +OAI.Geometry.HeilbronnTriangle.AuxiliaryZeroWeights +OAI.Geometry.HeilbronnTriangle.AveragedBadTripleBound +OAI.Geometry.HeilbronnTriangle.BadTripleAverage +OAI.Geometry.HeilbronnTriangle.CRTLifting +OAI.Geometry.HeilbronnTriangle.CapInBox +OAI.Geometry.HeilbronnTriangle.ConditionalBadTripleBound +OAI.Geometry.HeilbronnTriangle.ConditionalDigits +OAI.Geometry.HeilbronnTriangle.ConditionalMatrix +OAI.Geometry.HeilbronnTriangle.ConditionalSamples +OAI.Geometry.HeilbronnTriangle.ConditionalSmith +OAI.Geometry.HeilbronnTriangle.CrossNormal +OAI.Geometry.HeilbronnTriangle.Definitions +OAI.Geometry.HeilbronnTriangle.Deletion +OAI.Geometry.HeilbronnTriangle.DesignatedCoefficient +OAI.Geometry.HeilbronnTriangle.DeterminantCoefficients +OAI.Geometry.HeilbronnTriangle.DeterminantFibers +OAI.Geometry.HeilbronnTriangle.DeterminantResidue +OAI.Geometry.HeilbronnTriangle.DiagonalDetImage +OAI.Geometry.HeilbronnTriangle.DiagonalKernel +OAI.Geometry.HeilbronnTriangle.DiagonalStabilizer +OAI.Geometry.HeilbronnTriangle.DigitBadTripleAverage +OAI.Geometry.HeilbronnTriangle.DigitColumnLaw +OAI.Geometry.HeilbronnTriangle.DigitEncoding +OAI.Geometry.HeilbronnTriangle.DigitObstruction +OAI.Geometry.HeilbronnTriangle.DigitUniqueness +OAI.Geometry.HeilbronnTriangle.DigitUnits +OAI.Geometry.HeilbronnTriangle.DividingPivot +OAI.Geometry.HeilbronnTriangle.DivisorMoment +OAI.Geometry.HeilbronnTriangle.EncodedDeterminant +OAI.Geometry.HeilbronnTriangle.EqualCoordinatePacking +OAI.Geometry.HeilbronnTriangle.EqualCoordinatePlane +OAI.Geometry.HeilbronnTriangle.ExactPlaneCovolume +OAI.Geometry.HeilbronnTriangle.FinalSampling +OAI.Geometry.HeilbronnTriangle.FinalScaling +OAI.Geometry.HeilbronnTriangle.FinalScalingBridge +OAI.Geometry.HeilbronnTriangle.FiniteFieldLabels +OAI.Geometry.HeilbronnTriangle.FiniteIndexPlane +OAI.Geometry.HeilbronnTriangle.FiniteMixtures +OAI.Geometry.HeilbronnTriangle.FixedDetLattice +OAI.Geometry.HeilbronnTriangle.FixedDetReduction +OAI.Geometry.HeilbronnTriangle.FullIntegralLattice +OAI.Geometry.HeilbronnTriangle.GcdPairCount +OAI.Geometry.HeilbronnTriangle.GeometricAlteration +OAI.Geometry.HeilbronnTriangle.HomogeneousGeometry +OAI.Geometry.HeilbronnTriangle.IndependentTupleCard +OAI.Geometry.HeilbronnTriangle.IntegerMatrixEvents +OAI.Geometry.HeilbronnTriangle.IntegerMatrixFibers +OAI.Geometry.HeilbronnTriangle.IntegerNormalGroups +OAI.Geometry.HeilbronnTriangle.IntegerPlaneEstimates +OAI.Geometry.HeilbronnTriangle.IntegerPointLaw +OAI.Geometry.HeilbronnTriangle.IntegerPointLawPairs +OAI.Geometry.HeilbronnTriangle.IntegerPointLawTriples +OAI.Geometry.HeilbronnTriangle.IntegerSampling +OAI.Geometry.HeilbronnTriangle.IntegerSamplingPairs +OAI.Geometry.HeilbronnTriangle.IntegerSharedCollisions +OAI.Geometry.HeilbronnTriangle.IntegralAmbientLattice +OAI.Geometry.HeilbronnTriangle.IntegralKernelMoment +OAI.Geometry.HeilbronnTriangle.IntegralPlaneDeterminant +OAI.Geometry.HeilbronnTriangle.IntegralPlaneLattice +OAI.Geometry.HeilbronnTriangle.IntegralPlaneReduction +OAI.Geometry.HeilbronnTriangle.LabelResidues +OAI.Geometry.HeilbronnTriangle.LatticeBox +OAI.Geometry.HeilbronnTriangle.LatticeCoordinates +OAI.Geometry.HeilbronnTriangle.LatticeLowerProduct +OAI.Geometry.HeilbronnTriangle.LatticeMoment +OAI.Geometry.HeilbronnTriangle.LatticePacking +OAI.Geometry.HeilbronnTriangle.LatticeReciprocal +OAI.Geometry.HeilbronnTriangle.LatticeResidues +OAI.Geometry.HeilbronnTriangle.LatticeShell +OAI.Geometry.HeilbronnTriangle.LatticeSplit +OAI.Geometry.HeilbronnTriangle.LiftCollisions +OAI.Geometry.HeilbronnTriangle.LiftedBadEvent +OAI.Geometry.HeilbronnTriangle.LiftingProbability +OAI.Geometry.HeilbronnTriangle.Main +OAI.Geometry.HeilbronnTriangle.MainDigitLaw +OAI.Geometry.HeilbronnTriangle.MainDigitObstruction +OAI.Geometry.HeilbronnTriangle.MainDigitOrbitObstruction +OAI.Geometry.HeilbronnTriangle.MainOrbitObstruction +OAI.Geometry.HeilbronnTriangle.MainResidueSystem +OAI.Geometry.HeilbronnTriangle.MatrixAffineShell +OAI.Geometry.HeilbronnTriangle.MatrixSpecialRankTwo +OAI.Geometry.HeilbronnTriangle.MinorInvariant +OAI.Geometry.HeilbronnTriangle.MonomialCount +OAI.Geometry.HeilbronnTriangle.NonzeroAuxiliaryCount +OAI.Geometry.HeilbronnTriangle.NonzeroWeightedCount +OAI.Geometry.HeilbronnTriangle.NormDecomposition +OAI.Geometry.HeilbronnTriangle.NormDeterminant +OAI.Geometry.HeilbronnTriangle.NormEncoding +OAI.Geometry.HeilbronnTriangle.NormFoundation +OAI.Geometry.HeilbronnTriangle.NormHomogeneity +OAI.Geometry.HeilbronnTriangle.NormPolynomial +OAI.Geometry.HeilbronnTriangle.NormalFiberCount +OAI.Geometry.HeilbronnTriangle.NormalGroupCount +OAI.Geometry.HeilbronnTriangle.OrbitCardinality +OAI.Geometry.HeilbronnTriangle.OrbitEstimate +OAI.Geometry.HeilbronnTriangle.OrbitRowLattice +OAI.Geometry.HeilbronnTriangle.OrbitSampling +OAI.Geometry.HeilbronnTriangle.OrbitUniform +OAI.Geometry.HeilbronnTriangle.PairingDivisor +OAI.Geometry.HeilbronnTriangle.PairingMoment +OAI.Geometry.HeilbronnTriangle.ParameterConclusion +OAI.Geometry.HeilbronnTriangle.ParameterSampling +OAI.Geometry.HeilbronnTriangle.ParameterSequence +OAI.Geometry.HeilbronnTriangle.Parameters +OAI.Geometry.HeilbronnTriangle.PivotAssembly +OAI.Geometry.HeilbronnTriangle.PlaneCount +OAI.Geometry.HeilbronnTriangle.PlaneCovolume +OAI.Geometry.HeilbronnTriangle.PlaneFiberAssembly +OAI.Geometry.HeilbronnTriangle.PlaneFunctional +OAI.Geometry.HeilbronnTriangle.PlaneLines +OAI.Geometry.HeilbronnTriangle.PlaneRadius +OAI.Geometry.HeilbronnTriangle.PlaneReduction +OAI.Geometry.HeilbronnTriangle.PlaneRowTransport +OAI.Geometry.HeilbronnTriangle.PointLawBadTripleBound +OAI.Geometry.HeilbronnTriangle.PolynomialCoefficients +OAI.Geometry.HeilbronnTriangle.PowerGap +OAI.Geometry.HeilbronnTriangle.PrescribedDigits +OAI.Geometry.HeilbronnTriangle.PrimeLiftParameters +OAI.Geometry.HeilbronnTriangle.PrimeParameters +OAI.Geometry.HeilbronnTriangle.PrimePowerData +OAI.Geometry.HeilbronnTriangle.PrimePowerFactors +OAI.Geometry.HeilbronnTriangle.PrimePowerGL +OAI.Geometry.HeilbronnTriangle.PrimePowerRowData +OAI.Geometry.HeilbronnTriangle.PrimitiveLine +OAI.Geometry.HeilbronnTriangle.PrimitiveNormal +OAI.Geometry.HeilbronnTriangle.PrimitiveVector +OAI.Geometry.HeilbronnTriangle.ProjectiveBadEvent +OAI.Geometry.HeilbronnTriangle.ProportionalPairs +OAI.Geometry.HeilbronnTriangle.RandomAlteration +OAI.Geometry.HeilbronnTriangle.RankOneMinors +OAI.Geometry.HeilbronnTriangle.Refutation +OAI.Geometry.HeilbronnTriangle.RepeatedLabels +OAI.Geometry.HeilbronnTriangle.RowLattice +OAI.Geometry.HeilbronnTriangle.RowLatticeEqualShell +OAI.Geometry.HeilbronnTriangle.RowLatticeMatrices +OAI.Geometry.HeilbronnTriangle.SampleDeletion +OAI.Geometry.HeilbronnTriangle.SampleUpper +OAI.Geometry.HeilbronnTriangle.SamplingErrors +OAI.Geometry.HeilbronnTriangle.SharedGeometricAlteration +OAI.Geometry.HeilbronnTriangle.ShortKernelVectors +OAI.Geometry.HeilbronnTriangle.ShortRelations +OAI.Geometry.HeilbronnTriangle.ShortestIntegralVector +OAI.Geometry.HeilbronnTriangle.SmallDeterminantReduction +OAI.Geometry.HeilbronnTriangle.SmallDeterminantWeight +OAI.Geometry.HeilbronnTriangle.SmithDigitMoment +OAI.Geometry.HeilbronnTriangle.SpecialNormals +OAI.Geometry.HeilbronnTriangle.SpecialRankTwo +OAI.Geometry.HeilbronnTriangle.StabilizerConjugation +OAI.Geometry.HeilbronnTriangle.SuccessiveBox +OAI.Geometry.HeilbronnTriangle.SuccessiveEstimates +OAI.Geometry.HeilbronnTriangle.SuccessiveMinima +OAI.Geometry.HeilbronnTriangle.SuccessiveTransport +OAI.Geometry.HeilbronnTriangle.SuccessiveVectors +OAI.Geometry.HeilbronnTriangle.TranslateAverage +OAI.Geometry.HeilbronnTriangle.TripleEnumeration +OAI.Geometry.HeilbronnTriangle.TwoByTwoPivot +OAI.Geometry.HeilbronnTriangle.TwoByTwoSmith +OAI.Geometry.HeilbronnTriangle.TypedFixedFiberCount +OAI.Geometry.HeilbronnTriangle.UniformAction +OAI.Geometry.HeilbronnTriangle.UniformFixedFiberCount +OAI.Geometry.HeilbronnTriangle.WeightedNormalReduction +OAI.Geometry.HeilbronnTriangle.WeightedZeroPartition +OAI.Geometry.HeilbronnTriangle.ZModAnnihilator +OAI.Geometry.HeilbronnTriangle.ZeroAffineShell +OAI.Geometry.HeilbronnTriangle.ZeroCombinedShell +OAI.Geometry.HeilbronnTriangle.ZeroCountNormalization +OAI.Geometry.HeilbronnTriangle.ZeroDeterminantCount +OAI.Geometry.HeilbronnTriangle.ZeroEqualAdditional +OAI.Geometry.HeilbronnTriangle.ZeroEqualMatrices +OAI.Geometry.HeilbronnTriangle.ZeroGlobalCount +OAI.Geometry.HeilbronnTriangle.ZeroMomentSum +OAI.Geometry.HeilbronnTriangle.ZeroNormalDyadic +OAI.Geometry.HeilbronnTriangle.ZeroRowData +OAI.Geometry.HeilbronnTriangle.ZeroThreeCasePartition diff --git a/tasks/heilbronn-triangle/solution/reference.py b/tasks/heilbronn-triangle/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/heilbronn-triangle/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/heilbronn-triangle/solution/solve.sh b/tasks/heilbronn-triangle/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..951b714b81ace199a7e3179f83ecc7b0ce0f620c --- /dev/null +++ b/tasks/heilbronn-triangle/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HeilbronnTriangle, i.e. module OAI.Geometry.HeilbronnTriangle.Main and the +# 195 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.HeilbronnTriangle.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HeilbronnTriangle" diff --git a/tasks/heilbronn-triangle/task.toml b/tasks/heilbronn-triangle/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e608650877ff0f65f55f1a611fbe2fcca8d40e0 --- /dev/null +++ b/tasks/heilbronn-triangle/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/heilbronn-triangle" +version = "1.0.0" +description = "Prove HeilbronnTriangle (openai/math family 191: A power improvement in the Heilbronn triangle problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HeilbronnTriangle.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HeilbronnTriangle" +family = "191" +family_title = "A power improvement in the Heilbronn triangle problem" +subject = "Combinatorics" +theorems = ["OAI.Problem355.heilbronn_power_lower_bound", "OAI.Problem355.almost_n_minus_two_refuted"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.HeilbronnTriangle.Main" +reference_modules = 195 +reference_lean_bytes = 1015459 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1117 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12613 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/heilbronn-triangle/tests/Challenge.lean b/tasks/heilbronn-triangle/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4be52210e8909c3b2c80fd3ffb472aaab09be4d2 --- /dev/null +++ b/tasks/heilbronn-triangle/tests/Challenge.lean @@ -0,0 +1,68 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem355 + +abbrev Point := ℝ × ℝ + +def triangleArea (p q r : Point) : ℝ := + abs ((q.1 - p.1) * (r.2 - p.2) - (q.2 - p.2) * (r.1 - p.1)) / 2 + +def pointInUnitSquare (p : Point) : Prop := + 0 ≤ p.1 ∧ p.1 ≤ 1 ∧ 0 ≤ p.2 ∧ p.2 ≤ 1 + +def pointsInUnitSquare (P : Finset Point) : Prop := by + classical + exact ∀ p, p ∈ P → pointInUnitSquare p + +def triangleAreasAtLeast (P : Finset Point) (a : ℝ) : Prop := by + classical + exact ∀ p, p ∈ P → ∀ q, q ∈ P → ∀ r, r ∈ P → + p ≠ q → p ≠ r → q ≠ r → a ≤ triangleArea p q r + +def hasTriangleAreaAtMost (P : Finset Point) (a : ℝ) : Prop := by + classical + exact ∃ p, p ∈ P ∧ ∃ q, q ∈ P ∧ ∃ r, r ∈ P ∧ + p ≠ q ∧ p ≠ r ∧ q ≠ r ∧ triangleArea p q r ≤ a + +def heilbronnD : ℕ := 41 + +def heilbronnM : ℕ := Nat.choose (4 * heilbronnD - 1) heilbronnD + +def heilbronnT : ℕ := Nat.choose heilbronnM 3 + +def heilbronnK : ℕ := heilbronnT ^ 2 + 1 + +def heilbronnExponent : ℝ := + 1 / (100000 * (heilbronnK : ℝ)) + +def eventualAlmostUpperBound (epsilon : ℝ) : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ n0 : ℕ, ∀ n : ℕ, n0 ≤ n → 3 ≤ n → + ∀ P : Finset Point, P.card = n → pointsInUnitSquare P → + hasTriangleAreaAtMost P + (C * Real.rpow (n : ℝ) (-2 + epsilon)) + +attribute [local irreducible] Problem355.heilbronnT + Problem355.heilbronnM + +theorem heilbronn_power_lower_bound : + 0 < heilbronnExponent ∧ ∃ n : ℕ → ℕ, ∃ P : ℕ → Finset Point, + Filter.Tendsto n Filter.atTop Filter.atTop ∧ ∀ j : ℕ, + 3 ≤ n j ∧ (P j).card = n j ∧ pointsInUnitSquare (P j) ∧ + triangleAreasAtLeast (P j) + (Real.rpow (n j : ℝ) (-2 + heilbronnExponent)) := by + sorry + +theorem almost_n_minus_two_refuted : + 0 < heilbronnExponent / 2 ∧ + ¬ eventualAlmostUpperBound (heilbronnExponent / 2) := by + sorry + +end Problem355 + +end + +end OAI diff --git a/tasks/heilbronn-triangle/tests/grade.py b/tasks/heilbronn-triangle/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/heilbronn-triangle/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/heilbronn-triangle/tests/task.json b/tasks/heilbronn-triangle/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ca9e84bd1826da8a54a2fd1d4f92d5928680ceca --- /dev/null +++ b/tasks/heilbronn-triangle/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "HeilbronnTriangle", + "comparator": { + "theorem_names": [ + "OAI.Problem355.heilbronn_power_lower_bound", + "OAI.Problem355.almost_n_minus_two_refuted" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11713 +} \ No newline at end of file diff --git a/tasks/heilbronn-triangle/tests/test.sh b/tasks/heilbronn-triangle/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/heilbronn-triangle/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/heisenberg/environment/Dockerfile b/tasks/heisenberg/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/heisenberg/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/heisenberg/environment/fetch_mathlib.sh b/tasks/heisenberg/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/heisenberg/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/heisenberg/environment/lake-manifest.json b/tasks/heisenberg/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/heisenberg/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/heisenberg/environment/lakefile.lean b/tasks/heisenberg/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/heisenberg/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/heisenberg/environment/lean_setup.sh b/tasks/heisenberg/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/heisenberg/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/heisenberg/environment/pack_submission.py b/tasks/heisenberg/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/heisenberg/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/heisenberg/instruction.md b/tasks/heisenberg/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..41066260d7b2c4325f047f27a1db2f403de4a0f4 --- /dev/null +++ b/tasks/heisenberg/instruction.md @@ -0,0 +1,269 @@ +# openai/math challenge `Heisenberg` (family 271) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 271 of the release, *Bloch's law and spontaneous ferromagnetic order* +(Mathematical physics). The family as a whole: Proves Bloch's $T^{3/2}$ law with its exact coefficient for three-dimensional quantum Heisenberg ferromagnets at every positive quantum spin, allowing nonnegative symmetric finite-range couplings whose support generates $\mathbb Z^3$. The thermodynamic limit precedes the zero-field derivative and low-temperature limit. The family also proves spontaneous magnetization for nearest-neighbor models in every dimension $d\ge3$ and determines the first lattice correction for three-dimensional nearest-neighbor couplings. + +The challenge is `Heisenberg`, also at `/opt/openai-math/challenges/Heisenberg.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u v + + +open scoped ComplexConjugate ENNReal Classical + +namespace Heisenberg + +abbrev L2 (ι : Type u) := lp (fun _ : ι => ℂ) 2 + +def l2Reindex {ι : Type u} {κ : Type v} (e : ι ≃ κ) : L2 ι ≃ₗᵢ[ℂ] L2 κ where + toFun f := ⟨fun j => f (e.symm j), by + apply memℓp_gen + exact e.symm.summable_iff.mpr ((lp.memℓp f).summable (by norm_num))⟩ + invFun f := ⟨fun i => f (e i), by + apply memℓp_gen + exact e.summable_iff.mpr ((lp.memℓp f).summable (by norm_num))⟩ + left_inv f := by ext i; simp + right_inv f := by ext j; simp + map_add' f g := by ext j; rfl + map_smul' c f := by ext j; rfl + norm_map' f := by + rw [lp.norm_eq_tsum_rpow (by norm_num), lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.symm.tsum_eq (fun i => ‖f i‖ ^ (2 : ℝ≥0∞).toReal) + +def l2Projection {ι : Type u} (p : ι → Prop) : L2 ι →L[ℂ] L2 ι := by + classical + let f : L2 ι →ₗ[ℂ] L2 ι := + { toFun := fun v => ⟨fun i => if p i then v i else 0, + (lp.memℓp v).mono' (fun i => by split_ifs <;> simp)⟩ + map_add' := fun v w => by + ext i + change (if p i then v i + w i else 0) = + (if p i then v i else 0) + (if p i then w i else 0) + by_cases h : p i <;> simp [h] + map_smul' := fun c v => by ext i; by_cases h : p i <;> simp [h] } + exact f.mkContinuous 1 (fun v => by + simpa only [one_mul] using lp.norm_mono (by norm_num : (2 : ℝ≥0∞) ≠ 0) + (x := f v) (y := v) (fun i => by + change ‖if p i then v i else 0‖ ≤ ‖v i‖ + split_ifs <;> simp)) + +abbrev Site (d : ℕ) := Fin d → ℤ +abbrev Level (ℓ : ℕ) := Fin (ℓ + 1) +abbrev Configuration (d ℓ : ℕ) := Site d →₀ Level ℓ +abbrev SpinHilbert (d ℓ : ℕ) := L2 (Configuration d ℓ) +abbrev SpinOperator (d ℓ : ℕ) := SpinHilbert d ℓ →L[ℂ] SpinHilbert d ℓ + +def configPerm (d ℓ : ℕ) (x : Site d) (σ : Equiv.Perm (Level ℓ)) : + Equiv.Perm (Configuration d ℓ) where + toFun c := c.update x (σ (c x)) + invFun c := c.update x (σ.symm (c x)) + left_inv c := by + classical + ext y + by_cases h : y = x <;> simp [Finsupp.update_apply, h] + right_inv c := by + classical + ext y + by_cases h : y = x <;> simp [Finsupp.update_apply, h] + +def matrixUnit (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) : SpinOperator d ℓ := + (l2Projection (fun c : Configuration d ℓ => c x = a)).comp + (l2Reindex (configPerm d ℓ x (Equiv.swap a b))).toContinuousLinearEquiv.toContinuousLinearMap + +def operatorRelabel (d ℓ : ℕ) (e : Equiv.Perm (Site d)) : + SpinOperator d ℓ ≃⋆ₐ[ℂ] SpinOperator d ℓ := + (l2Reindex (Finsupp.equivCongrLeft e)).conjStarAlgEquiv + +def quasiLocalAlgebra (d ℓ : ℕ) : StarSubalgebra ℂ (SpinOperator d ℓ) := + (StarAlgebra.adjoin ℂ {A | ∃ x a b, A = matrixUnit d ℓ x a b}).topologicalClosure + +abbrev QuasiLocal (d ℓ : ℕ) := quasiLocalAlgebra d ℓ + +def localUnit (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) : QuasiLocal d ℓ := + ⟨matrixUnit d ℓ x a b, (StarSubalgebra.le_topologicalClosure _) + (StarAlgebra.subset_adjoin ℂ _ ⟨x, a, b, rfl⟩)⟩ + +def translation (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ →⋆ₐ[ℂ] QuasiLocal d ℓ := by + have l2Reindex_apply {ι : Type} {κ : Type} (e : ι ≃ κ) (f : L2 ι) (j : κ) : + l2Reindex e f j = f (e.symm j) := rfl + have l2Projection_apply {ι : Type} (p : ι → Prop) (v : L2 ι) (i : ι) : + l2Projection p v i = if p i then v i else 0 := by classical rfl + have matrixUnit_apply (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) + (v : SpinHilbert d ℓ) (c : Configuration d ℓ) : + matrixUnit d ℓ x a b v c = if c x = a then v (c.update x b) else 0 := by + simp only [matrixUnit, ContinuousLinearMap.comp_apply, l2Projection_apply] + split_ifs with h + · change v (c.update x ((Equiv.swap a b).symm (c x))) = v (c.update x b) + simp [h] + · rfl + have l2Reindex_symm_apply {ι : Type} {κ : Type} (e : ι ≃ κ) (v : L2 κ) (i : ι) : + (l2Reindex e).symm v i = v (e i) := rfl + have relabel_matrixUnit (d ℓ : ℕ) (e : Equiv.Perm (Site d)) + (x : Site d) (a b : Level ℓ) : + operatorRelabel d ℓ e (matrixUnit d ℓ x a b) = matrixUnit d ℓ (e x) a b := by + ext v c + simp only [operatorRelabel, LinearIsometryEquiv.conjStarAlgEquiv_apply_apply, + l2Reindex_apply, matrixUnit_apply] + change (if c (e x) = a then + (l2Reindex (Finsupp.equivCongrLeft e)).symm v + (((Finsupp.equivCongrLeft e).symm c).update x b) else 0) = _ + rw [l2Reindex_symm_apply] + by_cases h : c (e x) = a + · simp only [h, ite_eq_left] + apply congrArg v + ext y + simp only [Finsupp.equivCongrLeft_apply, Finsupp.equivMapDomain_apply, + Finsupp.update_apply] + by_cases hy : y = e x + · subst y; simp + · have hy' : e.symm y ≠ x := fun hxy => hy (by simpa using congrArg e hxy) + simp [hy, hy'] + · simp only [h, ite_false] + have relabel_mem (d ℓ : ℕ) (e : Equiv.Perm (Site d)) + {A : SpinOperator d ℓ} (hA : A ∈ quasiLocalAlgebra d ℓ) : + operatorRelabel d ℓ e A ∈ quasiLocalAlgebra d ℓ := by + let f := (operatorRelabel d ℓ e).toStarAlgHom + have h : StarAlgebra.adjoin ℂ {A | ∃ x a b, A = matrixUnit d ℓ x a b} ≤ + (quasiLocalAlgebra d ℓ).comap f := by + apply StarAlgebra.adjoin_le + rintro _ ⟨x, a, b, rfl⟩ + change operatorRelabel d ℓ e (matrixUnit d ℓ x a b) ∈ quasiLocalAlgebra d ℓ + rw [relabel_matrixUnit] + exact (localUnit d ℓ (e x) a b).property + have hc : IsClosed ((quasiLocalAlgebra d ℓ).comap f : Set (SpinOperator d ℓ)) := + (StarSubalgebra.isClosed_topologicalClosure _).preimage + (StarAlgEquiv.isometry (operatorRelabel d ℓ e)).continuous + exact StarSubalgebra.topologicalClosure_minimal h hc hA + exact let f := (operatorRelabel d ℓ (Equiv.addLeft x)).toStarAlgHom + (f.comp (quasiLocalAlgebra d ℓ).subtype).codRestrict (quasiLocalAlgebra d ℓ) + (fun A => relabel_mem d ℓ (Equiv.addLeft x) A.property) + +def magneticLevel (ℓ : ℕ) (k : Level ℓ) : ℝ := (k : ℝ) - (ℓ : ℝ) / 2 + +def spinZ (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + ∑ k : Level ℓ, (magneticLevel ℓ k : ℂ) • localUnit d ℓ x k k + +def spinPlus (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + ∑ k : Fin ℓ, + (Real.sqrt ((ℓ / 2 : ℝ) * (ℓ / 2 + 1) - + magneticLevel ℓ k.castSucc * (magneticLevel ℓ k.castSucc + 1)) : ℂ) • + localUnit d ℓ x k.succ k.castSucc + +def spinMinus (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := star (spinPlus d ℓ x) + +def spinX (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + (1 / 2 : ℂ) • (spinPlus d ℓ x + spinMinus d ℓ x) + +def spinY (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + (1 / (2 * Complex.I) : ℂ) • (spinPlus d ℓ x - spinMinus d ℓ x) + +def NearestNeighbor {d : ℕ} (x y : Site d) : Prop := + ∑ i : Fin d, |x i - y i| = (1 : ℤ) + +def volumeEdges {d : ℕ} (Λ : Finset (Site d)) : Finset (Site d × Site d) := + (Λ ×ˢ Λ).filter fun p => NearestNeighbor p.1 p.2 ∧ WellOrderingRel p.1 p.2 + +def hamiltonian (d ℓ : ℕ) (Λ : Finset (Site d)) : QuasiLocal d ℓ := + -∑ e ∈ volumeEdges Λ, + (spinX d ℓ e.1 * spinX d ℓ e.2 + spinY d ℓ e.1 * spinY d ℓ e.2 + + spinZ d ℓ e.1 * spinZ d ℓ e.2) + +def box (d n : ℕ) : Finset (Site d) := + Fintype.piFinset fun _ : Fin d => Finset.Icc (-(n : ℤ)) (n : ℤ) + +def finiteDynamics (d ℓ : ℕ) (Λ : Finset (Site d)) (t : ℝ) + (A : QuasiLocal d ℓ) : QuasiLocal d ℓ := + NormedSpace.exp ((Complex.I * (t : ℂ)) • hamiltonian d ℓ Λ) * A * + NormedSpace.exp ((-(Complex.I * (t : ℂ))) • hamiltonian d ℓ Λ) + +def dynamics (d ℓ : ℕ) (t : ℝ) (A : QuasiLocal d ℓ) : QuasiLocal d ℓ := + Filter.limUnder Filter.atTop (fun n : ℕ => finiteDynamics d ℓ (box d n) t A) + +def DynamicsConverges (d ℓ : ℕ) : Prop := + ∀ (t : ℝ) (A : QuasiLocal d ℓ), + Filter.Tendsto (fun n : ℕ => finiteDynamics d ℓ (box d n) t A) + Filter.atTop (nhds (dynamics d ℓ t A)) + +structure State (d ℓ : ℕ) where + functional : QuasiLocal d ℓ →L[ℂ] ℂ + normalized : functional 1 = 1 + positive : ∀ A, (functional (star A * A)).im = 0 ∧ + 0 ≤ (functional (star A * A)).re + +def TranslationInvariant {d ℓ : ℕ} (ω : State d ℓ) : Prop := + ∀ (x : Site d) (A : QuasiLocal d ℓ), ω.functional (translation d ℓ x A) = ω.functional A + +def IsKMS {d ℓ : ℕ} (β : ℝ) (ω : State d ℓ) : Prop := + 0 < β ∧ ∀ A B : QuasiLocal d ℓ, ∃ F : ℂ → ℂ, + ContinuousOn F {z | 0 ≤ z.im ∧ z.im ≤ β} ∧ + DifferentiableOn ℂ F {z | 0 < z.im ∧ z.im < β} ∧ + (∃ C : ℝ, ∀ z : ℂ, 0 ≤ z.im → z.im ≤ β → ‖F z‖ ≤ C) ∧ + (∀ t : ℝ, F t = ω.functional (A * dynamics d ℓ t B)) ∧ + (∀ t : ℝ, F ((t : ℂ) + Complex.I * β) = ω.functional (dynamics d ℓ t B * A)) + +open scoped Classical BigOperators ComplexConjugate +open Filter Topology + +theorem spontaneous_magnetization (d ℓ : ℕ) (hd : 3≤d) (hℓ : 1≤ℓ) : + DynamicsConverges d ℓ ∧ + ∃ β₀ : ℝ,0<β₀ ∧ ∀ β : ℝ,β₀≤β → + ∃ ω : State d ℓ,TranslationInvariant ω ∧ IsKMS β ω ∧ + (ω.functional (spinZ d ℓ 0)).im=0 ∧ + (ℓ:ℝ)/8≤(ω.functional (spinZ d ℓ 0)).re := by + sorry + +end Heisenberg + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Heisenberg.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Heisenberg.spontaneous_magnetization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/heisenberg/solution/closure.txt b/tasks/heisenberg/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7a84f7b7cdb4334292df50c72ddf96413da48980 --- /dev/null +++ b/tasks/heisenberg/solution/closure.txt @@ -0,0 +1,128 @@ +OAI.MathematicalPhysics.Heisenberg.AveragedEnergy +OAI.MathematicalPhysics.Heisenberg.BootstrapMeshBounds +OAI.MathematicalPhysics.Heisenberg.BootstrapParameters +OAI.MathematicalPhysics.Heisenberg.BoundaryMesh +OAI.MathematicalPhysics.Heisenberg.BoundaryPartition +OAI.MathematicalPhysics.Heisenberg.BoundaryWitness +OAI.MathematicalPhysics.Heisenberg.BoundedStrip +OAI.MathematicalPhysics.Heisenberg.ClockInsertions +OAI.MathematicalPhysics.Heisenberg.ClockTails +OAI.MathematicalPhysics.Heisenberg.ClockWitnesses +OAI.MathematicalPhysics.Heisenberg.ColorClockLimit +OAI.MathematicalPhysics.Heisenberg.CompletedSurface +OAI.MathematicalPhysics.Heisenberg.CompletionFactor +OAI.MathematicalPhysics.Heisenberg.ConditionalMoments +OAI.MathematicalPhysics.Heisenberg.CrossingTails +OAI.MathematicalPhysics.Heisenberg.CubeSelection +OAI.MathematicalPhysics.Heisenberg.CubeSurface +OAI.MathematicalPhysics.Heisenberg.CutColors +OAI.MathematicalPhysics.Heisenberg.CutContractions +OAI.MathematicalPhysics.Heisenberg.CycleWeights +OAI.MathematicalPhysics.Heisenberg.CyclicEnergy +OAI.MathematicalPhysics.Heisenberg.DeterminantExposure +OAI.MathematicalPhysics.Heisenberg.ExchangeCycles +OAI.MathematicalPhysics.Heisenberg.ExchangeDeterminants +OAI.MathematicalPhysics.Heisenberg.ExchangeOnMesh +OAI.MathematicalPhysics.Heisenberg.ExponentialEvolution +OAI.MathematicalPhysics.Heisenberg.ExposedEnergy +OAI.MathematicalPhysics.Heisenberg.FiniteAverage +OAI.MathematicalPhysics.Heisenberg.FiniteHistories +OAI.MathematicalPhysics.Heisenberg.FiniteTilt +OAI.MathematicalPhysics.Heisenberg.FirstReturns +OAI.MathematicalPhysics.Heisenberg.FlowCongestion +OAI.MathematicalPhysics.Heisenberg.FlowRouting +OAI.MathematicalPhysics.Heisenberg.GibbsLimits +OAI.MathematicalPhysics.Heisenberg.HistoryMarginals +OAI.MathematicalPhysics.Heisenberg.HittingEnergy +OAI.MathematicalPhysics.Heisenberg.HittingKernels +OAI.MathematicalPhysics.Heisenberg.HoleReturns +OAI.MathematicalPhysics.Heisenberg.HullComponents +OAI.MathematicalPhysics.Heisenberg.HullRouting +OAI.MathematicalPhysics.Heisenberg.KilledContractions +OAI.MathematicalPhysics.Heisenberg.LatticeCuts +OAI.MathematicalPhysics.Heisenberg.LatticeFlows +OAI.MathematicalPhysics.Heisenberg.LatticeHulls +OAI.MathematicalPhysics.Heisenberg.LatticePaths +OAI.MathematicalPhysics.Heisenberg.LatticeRegularity +OAI.MathematicalPhysics.Heisenberg.LayerEnergy +OAI.MathematicalPhysics.Heisenberg.LayerExposure +OAI.MathematicalPhysics.Heisenberg.LayerRegularity +OAI.MathematicalPhysics.Heisenberg.LocalAlgebra +OAI.MathematicalPhysics.Heisenberg.LocalDynamics +OAI.MathematicalPhysics.Heisenberg.Main +OAI.MathematicalPhysics.Heisenberg.MatrixUnitLift +OAI.MathematicalPhysics.Heisenberg.MatrixUnitTrace +OAI.MathematicalPhysics.Heisenberg.MatrixWeights +OAI.MathematicalPhysics.Heisenberg.MeanLeakage +OAI.MathematicalPhysics.Heisenberg.MeshCompletion +OAI.MathematicalPhysics.Heisenberg.MeshCutProduct +OAI.MathematicalPhysics.Heisenberg.MeshMatrixSurface +OAI.MathematicalPhysics.Heisenberg.MeshPin +OAI.MathematicalPhysics.Heisenberg.MeshProduct +OAI.MathematicalPhysics.Heisenberg.MeshRoom +OAI.MathematicalPhysics.Heisenberg.MeshSurface +OAI.MathematicalPhysics.Heisenberg.Model +OAI.MathematicalPhysics.Heisenberg.NetworkEnergy +OAI.MathematicalPhysics.Heisenberg.OnsiteSwaps +OAI.MathematicalPhysics.Heisenberg.PeriodicCount +OAI.MathematicalPhysics.Heisenberg.PeriodicLeakage +OAI.MathematicalPhysics.Heisenberg.PeriodicReturnEstimate +OAI.MathematicalPhysics.Heisenberg.PermutationSymbols +OAI.MathematicalPhysics.Heisenberg.PhysicalClock +OAI.MathematicalPhysics.Heisenberg.PhysicalSpectral +OAI.MathematicalPhysics.Heisenberg.PhysicalSurface +OAI.MathematicalPhysics.Heisenberg.PhysicalTilt +OAI.MathematicalPhysics.Heisenberg.PinBridge +OAI.MathematicalPhysics.Heisenberg.PinDensity +OAI.MathematicalPhysics.Heisenberg.PinSplicing +OAI.MathematicalPhysics.Heisenberg.PinSymmetrization +OAI.MathematicalPhysics.Heisenberg.PinnedColors +OAI.MathematicalPhysics.Heisenberg.PinnedMagnetization +OAI.MathematicalPhysics.Heisenberg.PolynomialLimits +OAI.MathematicalPhysics.Heisenberg.QuietSweeps +OAI.MathematicalPhysics.Heisenberg.RectangularExp +OAI.MathematicalPhysics.Heisenberg.RegularComponents +OAI.MathematicalPhysics.Heisenberg.RegularKernels +OAI.MathematicalPhysics.Heisenberg.RegularPin +OAI.MathematicalPhysics.Heisenberg.ReturnConditioning +OAI.MathematicalPhysics.Heisenberg.ReversedExposure +OAI.MathematicalPhysics.Heisenberg.RoundEnergy +OAI.MathematicalPhysics.Heisenberg.RoutedDissipation +OAI.MathematicalPhysics.Heisenberg.RoutedNetworks +OAI.MathematicalPhysics.Heisenberg.ScheduledResiduals +OAI.MathematicalPhysics.Heisenberg.SerialBlocks +OAI.MathematicalPhysics.Heisenberg.SimultaneousPins +OAI.MathematicalPhysics.Heisenberg.SlotColorTrace +OAI.MathematicalPhysics.Heisenberg.SlotOnMesh +OAI.MathematicalPhysics.Heisenberg.SparseCrossings +OAI.MathematicalPhysics.Heisenberg.SparseEnergy +OAI.MathematicalPhysics.Heisenberg.SpatialClocks +OAI.MathematicalPhysics.Heisenberg.SpectralTransfer +OAI.MathematicalPhysics.Heisenberg.SpinAverage +OAI.MathematicalPhysics.Heisenberg.SpinAverageBoundary +OAI.MathematicalPhysics.Heisenberg.SpinAveragedKMS +OAI.MathematicalPhysics.Heisenberg.SpinBulk +OAI.MathematicalPhysics.Heisenberg.SpinCubeAverage +OAI.MathematicalPhysics.Heisenberg.SpinDeep +OAI.MathematicalPhysics.Heisenberg.SpinDirected +OAI.MathematicalPhysics.Heisenberg.SpinExhaustion +OAI.MathematicalPhysics.Heisenberg.SpinField +OAI.MathematicalPhysics.Heisenberg.SpinFieldDynamics +OAI.MathematicalPhysics.Heisenberg.SpinFieldUniform +OAI.MathematicalPhysics.Heisenberg.SpinMatrixConservation +OAI.MathematicalPhysics.Heisenberg.SpinMatrixTrace +OAI.MathematicalPhysics.Heisenberg.SpinPhysicalOperators +OAI.MathematicalPhysics.Heisenberg.SpinTensorRepresentation +OAI.MathematicalPhysics.Heisenberg.SpinTranslations +OAI.MathematicalPhysics.Heisenberg.StablePinLaw +OAI.MathematicalPhysics.Heisenberg.StablePolynomials +OAI.MathematicalPhysics.Heisenberg.StableSections +OAI.MathematicalPhysics.Heisenberg.StateCompactness +OAI.MathematicalPhysics.Heisenberg.SurfaceTail +OAI.MathematicalPhysics.Heisenberg.SymmetrizedSurface +OAI.MathematicalPhysics.Heisenberg.TensorLift +OAI.MathematicalPhysics.Heisenberg.TensorLiftIndex +OAI.MathematicalPhysics.Heisenberg.TensorUnitSystem +OAI.MathematicalPhysics.Heisenberg.ThermodynamicDynamics +OAI.MathematicalPhysics.Heisenberg.TwoEndedReturns +OAI.MathematicalPhysics.Heisenberg.WeightedLeakage diff --git a/tasks/heisenberg/solution/reference.py b/tasks/heisenberg/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/heisenberg/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/heisenberg/solution/solve.sh b/tasks/heisenberg/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..dad8e6d5a0152e9bfeb92564b77caddc7f25238c --- /dev/null +++ b/tasks/heisenberg/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Heisenberg, i.e. module OAI.MathematicalPhysics.Heisenberg.Main and the +# 128 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.Heisenberg.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Heisenberg" diff --git a/tasks/heisenberg/task.toml b/tasks/heisenberg/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e9b2c584b8b2da94a6c88cf41a948e837f1a81c0 --- /dev/null +++ b/tasks/heisenberg/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/heisenberg" +version = "1.0.0" +description = "Prove Heisenberg (openai/math family 271: Bloch's law and spontaneous ferromagnetic order) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Heisenberg.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Heisenberg" +family = "271" +family_title = "Bloch's law and spontaneous ferromagnetic order" +subject = "Mathematical physics" +theorems = ["OAI.Heisenberg.spontaneous_magnetization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.Heisenberg.Main" +reference_modules = 128 +reference_lean_bytes = 1109282 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1829 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12698 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/heisenberg/tests/Challenge.lean b/tasks/heisenberg/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..424dcf04cd29937e2846b951e7586dedb97ce2b5 --- /dev/null +++ b/tasks/heisenberg/tests/Challenge.lean @@ -0,0 +1,218 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u v + + +open scoped ComplexConjugate ENNReal Classical + +namespace Heisenberg + +abbrev L2 (ι : Type u) := lp (fun _ : ι => ℂ) 2 + +def l2Reindex {ι : Type u} {κ : Type v} (e : ι ≃ κ) : L2 ι ≃ₗᵢ[ℂ] L2 κ where + toFun f := ⟨fun j => f (e.symm j), by + apply memℓp_gen + exact e.symm.summable_iff.mpr ((lp.memℓp f).summable (by norm_num))⟩ + invFun f := ⟨fun i => f (e i), by + apply memℓp_gen + exact e.summable_iff.mpr ((lp.memℓp f).summable (by norm_num))⟩ + left_inv f := by ext i; simp + right_inv f := by ext j; simp + map_add' f g := by ext j; rfl + map_smul' c f := by ext j; rfl + norm_map' f := by + rw [lp.norm_eq_tsum_rpow (by norm_num), lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.symm.tsum_eq (fun i => ‖f i‖ ^ (2 : ℝ≥0∞).toReal) + +def l2Projection {ι : Type u} (p : ι → Prop) : L2 ι →L[ℂ] L2 ι := by + classical + let f : L2 ι →ₗ[ℂ] L2 ι := + { toFun := fun v => ⟨fun i => if p i then v i else 0, + (lp.memℓp v).mono' (fun i => by split_ifs <;> simp)⟩ + map_add' := fun v w => by + ext i + change (if p i then v i + w i else 0) = + (if p i then v i else 0) + (if p i then w i else 0) + by_cases h : p i <;> simp [h] + map_smul' := fun c v => by ext i; by_cases h : p i <;> simp [h] } + exact f.mkContinuous 1 (fun v => by + simpa only [one_mul] using lp.norm_mono (by norm_num : (2 : ℝ≥0∞) ≠ 0) + (x := f v) (y := v) (fun i => by + change ‖if p i then v i else 0‖ ≤ ‖v i‖ + split_ifs <;> simp)) + +abbrev Site (d : ℕ) := Fin d → ℤ +abbrev Level (ℓ : ℕ) := Fin (ℓ + 1) +abbrev Configuration (d ℓ : ℕ) := Site d →₀ Level ℓ +abbrev SpinHilbert (d ℓ : ℕ) := L2 (Configuration d ℓ) +abbrev SpinOperator (d ℓ : ℕ) := SpinHilbert d ℓ →L[ℂ] SpinHilbert d ℓ + +def configPerm (d ℓ : ℕ) (x : Site d) (σ : Equiv.Perm (Level ℓ)) : + Equiv.Perm (Configuration d ℓ) where + toFun c := c.update x (σ (c x)) + invFun c := c.update x (σ.symm (c x)) + left_inv c := by + classical + ext y + by_cases h : y = x <;> simp [Finsupp.update_apply, h] + right_inv c := by + classical + ext y + by_cases h : y = x <;> simp [Finsupp.update_apply, h] + +def matrixUnit (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) : SpinOperator d ℓ := + (l2Projection (fun c : Configuration d ℓ => c x = a)).comp + (l2Reindex (configPerm d ℓ x (Equiv.swap a b))).toContinuousLinearEquiv.toContinuousLinearMap + +def operatorRelabel (d ℓ : ℕ) (e : Equiv.Perm (Site d)) : + SpinOperator d ℓ ≃⋆ₐ[ℂ] SpinOperator d ℓ := + (l2Reindex (Finsupp.equivCongrLeft e)).conjStarAlgEquiv + +def quasiLocalAlgebra (d ℓ : ℕ) : StarSubalgebra ℂ (SpinOperator d ℓ) := + (StarAlgebra.adjoin ℂ {A | ∃ x a b, A = matrixUnit d ℓ x a b}).topologicalClosure + +abbrev QuasiLocal (d ℓ : ℕ) := quasiLocalAlgebra d ℓ + +def localUnit (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) : QuasiLocal d ℓ := + ⟨matrixUnit d ℓ x a b, (StarSubalgebra.le_topologicalClosure _) + (StarAlgebra.subset_adjoin ℂ _ ⟨x, a, b, rfl⟩)⟩ + +def translation (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ →⋆ₐ[ℂ] QuasiLocal d ℓ := by + have l2Reindex_apply {ι : Type} {κ : Type} (e : ι ≃ κ) (f : L2 ι) (j : κ) : + l2Reindex e f j = f (e.symm j) := rfl + have l2Projection_apply {ι : Type} (p : ι → Prop) (v : L2 ι) (i : ι) : + l2Projection p v i = if p i then v i else 0 := by classical rfl + have matrixUnit_apply (d ℓ : ℕ) (x : Site d) (a b : Level ℓ) + (v : SpinHilbert d ℓ) (c : Configuration d ℓ) : + matrixUnit d ℓ x a b v c = if c x = a then v (c.update x b) else 0 := by + simp only [matrixUnit, ContinuousLinearMap.comp_apply, l2Projection_apply] + split_ifs with h + · change v (c.update x ((Equiv.swap a b).symm (c x))) = v (c.update x b) + simp [h] + · rfl + have l2Reindex_symm_apply {ι : Type} {κ : Type} (e : ι ≃ κ) (v : L2 κ) (i : ι) : + (l2Reindex e).symm v i = v (e i) := rfl + have relabel_matrixUnit (d ℓ : ℕ) (e : Equiv.Perm (Site d)) + (x : Site d) (a b : Level ℓ) : + operatorRelabel d ℓ e (matrixUnit d ℓ x a b) = matrixUnit d ℓ (e x) a b := by + ext v c + simp only [operatorRelabel, LinearIsometryEquiv.conjStarAlgEquiv_apply_apply, + l2Reindex_apply, matrixUnit_apply] + change (if c (e x) = a then + (l2Reindex (Finsupp.equivCongrLeft e)).symm v + (((Finsupp.equivCongrLeft e).symm c).update x b) else 0) = _ + rw [l2Reindex_symm_apply] + by_cases h : c (e x) = a + · simp only [h, ite_eq_left] + apply congrArg v + ext y + simp only [Finsupp.equivCongrLeft_apply, Finsupp.equivMapDomain_apply, + Finsupp.update_apply] + by_cases hy : y = e x + · subst y; simp + · have hy' : e.symm y ≠ x := fun hxy => hy (by simpa using congrArg e hxy) + simp [hy, hy'] + · simp only [h, ite_false] + have relabel_mem (d ℓ : ℕ) (e : Equiv.Perm (Site d)) + {A : SpinOperator d ℓ} (hA : A ∈ quasiLocalAlgebra d ℓ) : + operatorRelabel d ℓ e A ∈ quasiLocalAlgebra d ℓ := by + let f := (operatorRelabel d ℓ e).toStarAlgHom + have h : StarAlgebra.adjoin ℂ {A | ∃ x a b, A = matrixUnit d ℓ x a b} ≤ + (quasiLocalAlgebra d ℓ).comap f := by + apply StarAlgebra.adjoin_le + rintro _ ⟨x, a, b, rfl⟩ + change operatorRelabel d ℓ e (matrixUnit d ℓ x a b) ∈ quasiLocalAlgebra d ℓ + rw [relabel_matrixUnit] + exact (localUnit d ℓ (e x) a b).property + have hc : IsClosed ((quasiLocalAlgebra d ℓ).comap f : Set (SpinOperator d ℓ)) := + (StarSubalgebra.isClosed_topologicalClosure _).preimage + (StarAlgEquiv.isometry (operatorRelabel d ℓ e)).continuous + exact StarSubalgebra.topologicalClosure_minimal h hc hA + exact let f := (operatorRelabel d ℓ (Equiv.addLeft x)).toStarAlgHom + (f.comp (quasiLocalAlgebra d ℓ).subtype).codRestrict (quasiLocalAlgebra d ℓ) + (fun A => relabel_mem d ℓ (Equiv.addLeft x) A.property) + +def magneticLevel (ℓ : ℕ) (k : Level ℓ) : ℝ := (k : ℝ) - (ℓ : ℝ) / 2 + +def spinZ (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + ∑ k : Level ℓ, (magneticLevel ℓ k : ℂ) • localUnit d ℓ x k k + +def spinPlus (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + ∑ k : Fin ℓ, + (Real.sqrt ((ℓ / 2 : ℝ) * (ℓ / 2 + 1) - + magneticLevel ℓ k.castSucc * (magneticLevel ℓ k.castSucc + 1)) : ℂ) • + localUnit d ℓ x k.succ k.castSucc + +def spinMinus (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := star (spinPlus d ℓ x) + +def spinX (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + (1 / 2 : ℂ) • (spinPlus d ℓ x + spinMinus d ℓ x) + +def spinY (d ℓ : ℕ) (x : Site d) : QuasiLocal d ℓ := + (1 / (2 * Complex.I) : ℂ) • (spinPlus d ℓ x - spinMinus d ℓ x) + +def NearestNeighbor {d : ℕ} (x y : Site d) : Prop := + ∑ i : Fin d, |x i - y i| = (1 : ℤ) + +def volumeEdges {d : ℕ} (Λ : Finset (Site d)) : Finset (Site d × Site d) := + (Λ ×ˢ Λ).filter fun p => NearestNeighbor p.1 p.2 ∧ WellOrderingRel p.1 p.2 + +def hamiltonian (d ℓ : ℕ) (Λ : Finset (Site d)) : QuasiLocal d ℓ := + -∑ e ∈ volumeEdges Λ, + (spinX d ℓ e.1 * spinX d ℓ e.2 + spinY d ℓ e.1 * spinY d ℓ e.2 + + spinZ d ℓ e.1 * spinZ d ℓ e.2) + +def box (d n : ℕ) : Finset (Site d) := + Fintype.piFinset fun _ : Fin d => Finset.Icc (-(n : ℤ)) (n : ℤ) + +def finiteDynamics (d ℓ : ℕ) (Λ : Finset (Site d)) (t : ℝ) + (A : QuasiLocal d ℓ) : QuasiLocal d ℓ := + NormedSpace.exp ((Complex.I * (t : ℂ)) • hamiltonian d ℓ Λ) * A * + NormedSpace.exp ((-(Complex.I * (t : ℂ))) • hamiltonian d ℓ Λ) + +def dynamics (d ℓ : ℕ) (t : ℝ) (A : QuasiLocal d ℓ) : QuasiLocal d ℓ := + Filter.limUnder Filter.atTop (fun n : ℕ => finiteDynamics d ℓ (box d n) t A) + +def DynamicsConverges (d ℓ : ℕ) : Prop := + ∀ (t : ℝ) (A : QuasiLocal d ℓ), + Filter.Tendsto (fun n : ℕ => finiteDynamics d ℓ (box d n) t A) + Filter.atTop (nhds (dynamics d ℓ t A)) + +structure State (d ℓ : ℕ) where + functional : QuasiLocal d ℓ →L[ℂ] ℂ + normalized : functional 1 = 1 + positive : ∀ A, (functional (star A * A)).im = 0 ∧ + 0 ≤ (functional (star A * A)).re + +def TranslationInvariant {d ℓ : ℕ} (ω : State d ℓ) : Prop := + ∀ (x : Site d) (A : QuasiLocal d ℓ), ω.functional (translation d ℓ x A) = ω.functional A + +def IsKMS {d ℓ : ℕ} (β : ℝ) (ω : State d ℓ) : Prop := + 0 < β ∧ ∀ A B : QuasiLocal d ℓ, ∃ F : ℂ → ℂ, + ContinuousOn F {z | 0 ≤ z.im ∧ z.im ≤ β} ∧ + DifferentiableOn ℂ F {z | 0 < z.im ∧ z.im < β} ∧ + (∃ C : ℝ, ∀ z : ℂ, 0 ≤ z.im → z.im ≤ β → ‖F z‖ ≤ C) ∧ + (∀ t : ℝ, F t = ω.functional (A * dynamics d ℓ t B)) ∧ + (∀ t : ℝ, F ((t : ℂ) + Complex.I * β) = ω.functional (dynamics d ℓ t B * A)) + +open scoped Classical BigOperators ComplexConjugate +open Filter Topology + +theorem spontaneous_magnetization (d ℓ : ℕ) (hd : 3≤d) (hℓ : 1≤ℓ) : + DynamicsConverges d ℓ ∧ + ∃ β₀ : ℝ,0<β₀ ∧ ∀ β : ℝ,β₀≤β → + ∃ ω : State d ℓ,TranslationInvariant ω ∧ IsKMS β ω ∧ + (ω.functional (spinZ d ℓ 0)).im=0 ∧ + (ℓ:ℝ)/8≤(ω.functional (spinZ d ℓ 0)).re := by + sorry + +end Heisenberg + +end + +end OAI diff --git a/tasks/heisenberg/tests/grade.py b/tasks/heisenberg/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/heisenberg/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/heisenberg/tests/task.json b/tasks/heisenberg/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4ffcec637de1ee964772033fc5c4a0469baac222 --- /dev/null +++ b/tasks/heisenberg/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Heisenberg", + "comparator": { + "theorem_names": [ + "OAI.Heisenberg.spontaneous_magnetization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11798 +} \ No newline at end of file diff --git a/tasks/heisenberg/tests/test.sh b/tasks/heisenberg/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/heisenberg/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/henon-emden/environment/Dockerfile b/tasks/henon-emden/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/henon-emden/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/henon-emden/environment/fetch_mathlib.sh b/tasks/henon-emden/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/henon-emden/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/henon-emden/environment/lake-manifest.json b/tasks/henon-emden/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/henon-emden/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/henon-emden/environment/lakefile.lean b/tasks/henon-emden/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/henon-emden/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/henon-emden/environment/lean_setup.sh b/tasks/henon-emden/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/henon-emden/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/henon-emden/environment/pack_submission.py b/tasks/henon-emden/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/henon-emden/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/henon-emden/instruction.md b/tasks/henon-emden/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..19549346fc46dccc07ec908a950f62e2a8f32aa5 --- /dev/null +++ b/tasks/henon-emden/instruction.md @@ -0,0 +1,82 @@ +# openai/math challenge `HenonEmden` (family 370) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 370 of the release, *The subcritical Lane–Emden and Henon–Lane–Emden conjectures* +(Partial differential equations). The family as a whole: Resolves the subcritical Lane–Emden conjecture and its weighted Henon extension. For $n\ge2$, $p,q>0$ and real $A,B$, the system $-\Delta u=|x|^A v^p$, $-\Delta v=|x|^B u^q$ has no positive entire solution when $(n+A)/(p+1)+(n+B)/(q+1)>n-2$, with solutions continuous at the origin and classical elsewhere. No symmetry or growth assumption is needed. Known radial existence gives the exact existence criterion for $n\ge3$ and $A,B>-2$. + +The challenge is `HenonEmden`, also at `/opt/openai-math/challenges/HenonEmden.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace HenonLaneEmden + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +structure IsSolution (n : ℕ) (p q A B : ℝ) (u v : Space n → ℝ) : Prop where + continuous_u : Continuous u + continuous_v : Continuous v + regular_u : ContDiffOn ℝ 2 u ({0}ᶜ : Set (Space n)) + regular_v : ContDiffOn ℝ 2 v ({0}ᶜ : Set (Space n)) + positive_u : ∀ x, 0 < u x + positive_v : ∀ x, 0 < v x + equation_u : ∀ x, x ≠ 0 → + -(Laplacian.laplacian u) x = Real.rpow ‖x‖ A * Real.rpow (v x) p + equation_v : ∀ x, x ≠ 0 → + -(Laplacian.laplacian v) x = Real.rpow ‖x‖ B * Real.rpow (u x) q + +def Subcritical (n : ℕ) (p q A B : ℝ) : Prop := + ((n : ℝ) + A) / (p + 1) + ((n : ℝ) + B) / (q + 1) > (n : ℝ) - (1 + 1) + +theorem main_nonexistence (n : ℕ) (hn : 2 ≤ n) (p q A B : ℝ) + (hp : 0 < p) (hq : 0 < q) (hsub : Subcritical n p q A B) : + ¬ ∃ u v : Space n → ℝ, IsSolution n p q A B u v := by + sorry + +end HenonLaneEmden + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HenonEmden.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HenonLaneEmden.main_nonexistence` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/henon-emden/solution/closure.txt b/tasks/henon-emden/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e9662d64217cefd6f9b40f6d9b6790d1146414b7 --- /dev/null +++ b/tasks/henon-emden/solution/closure.txt @@ -0,0 +1,96 @@ +OAI.Analysis.HenonEmden.AdaptiveCaps +OAI.Analysis.HenonEmden.Angular +OAI.Analysis.HenonEmden.AngularBounds +OAI.Analysis.HenonEmden.AngularIntegration +OAI.Analysis.HenonEmden.AngularLoss +OAI.Analysis.HenonEmden.AngularMeasurability +OAI.Analysis.HenonEmden.AngularPressure +OAI.Analysis.HenonEmden.CapContinuity +OAI.Analysis.HenonEmden.CapGeometry +OAI.Analysis.HenonEmden.CapLoss +OAI.Analysis.HenonEmden.CapMismatch +OAI.Analysis.HenonEmden.CapOscillation +OAI.Analysis.HenonEmden.CapWeights +OAI.Analysis.HenonEmden.ComponentWeights +OAI.Analysis.HenonEmden.Components +OAI.Analysis.HenonEmden.Cutoff +OAI.Analysis.HenonEmden.CutoffOscillation +OAI.Analysis.HenonEmden.CutoffSmooth +OAI.Analysis.HenonEmden.CutoffTaylor +OAI.Analysis.HenonEmden.DirectionalPressure +OAI.Analysis.HenonEmden.Distribution +OAI.Analysis.HenonEmden.Endpoints +OAI.Analysis.HenonEmden.Energy +OAI.Analysis.HenonEmden.FarInteraction +OAI.Analysis.HenonEmden.FarLocalization +OAI.Analysis.HenonEmden.FundamentalSolution +OAI.Analysis.HenonEmden.GlobalLoss +OAI.Analysis.HenonEmden.Gradients +OAI.Analysis.HenonEmden.Harmonic +OAI.Analysis.HenonEmden.IntegratedPressure +OAI.Analysis.HenonEmden.IntegratedRecovery +OAI.Analysis.HenonEmden.Interaction +OAI.Analysis.HenonEmden.InteractionBounds +OAI.Analysis.HenonEmden.Intervals +OAI.Analysis.HenonEmden.KernelBalls +OAI.Analysis.HenonEmden.LayerAssembly +OAI.Analysis.HenonEmden.LayerIntegration +OAI.Analysis.HenonEmden.LayerPressure +OAI.Analysis.HenonEmden.LayerRecovery +OAI.Analysis.HenonEmden.LayerSplit +OAI.Analysis.HenonEmden.LineCoordinates +OAI.Analysis.HenonEmden.LocalizationIntegral +OAI.Analysis.HenonEmden.Main +OAI.Analysis.HenonEmden.MassGrowth +OAI.Analysis.HenonEmden.MeasureShuffle +OAI.Analysis.HenonEmden.Model +OAI.Analysis.HenonEmden.Mollification +OAI.Analysis.HenonEmden.NearLocalization +OAI.Analysis.HenonEmden.NewtonBounds +OAI.Analysis.HenonEmden.NewtonPotential +OAI.Analysis.HenonEmden.OriginBounds +OAI.Analysis.HenonEmden.OriginCutoff +OAI.Analysis.HenonEmden.OriginVirial +OAI.Analysis.HenonEmden.PDEPressure +OAI.Analysis.HenonEmden.PairPressure +OAI.Analysis.HenonEmden.PairRecovery +OAI.Analysis.HenonEmden.Polar +OAI.Analysis.HenonEmden.PotentialContinuity +OAI.Analysis.HenonEmden.PressureEstimate +OAI.Analysis.HenonEmden.PressureMismatch +OAI.Analysis.HenonEmden.PressureRecovery +OAI.Analysis.HenonEmden.ProductBounds +OAI.Analysis.HenonEmden.RadialCalculus +OAI.Analysis.HenonEmden.RadialGeometry +OAI.Analysis.HenonEmden.RadialGradient +OAI.Analysis.HenonEmden.RadialIntegration +OAI.Analysis.HenonEmden.RadialJoint +OAI.Analysis.HenonEmden.RadialKernel +OAI.Analysis.HenonEmden.RadialODE +OAI.Analysis.HenonEmden.RadialTaylor +OAI.Analysis.HenonEmden.RealInteraction +OAI.Analysis.HenonEmden.RelativeLocalization +OAI.Analysis.HenonEmden.RelativePressure +OAI.Analysis.HenonEmden.RootRecovery +OAI.Analysis.HenonEmden.Scaling +OAI.Analysis.HenonEmden.ShortComponents +OAI.Analysis.HenonEmden.SourceEndpoints +OAI.Analysis.HenonEmden.SourceMass +OAI.Analysis.HenonEmden.Sources +OAI.Analysis.HenonEmden.SpatialComponents +OAI.Analysis.HenonEmden.SpatialEndpoints +OAI.Analysis.HenonEmden.SpatialPressure +OAI.Analysis.HenonEmden.SphereCaps +OAI.Analysis.HenonEmden.SphereFlux +OAI.Analysis.HenonEmden.SphereMean +OAI.Analysis.HenonEmden.SymmetricVirial +OAI.Analysis.HenonEmden.Tails +OAI.Analysis.HenonEmden.Tonelli +OAI.Analysis.HenonEmden.UniformBounds +OAI.Analysis.HenonEmden.UniformEnergy +OAI.Analysis.HenonEmden.VirialCalculus +OAI.Analysis.HenonEmden.WeakForm +OAI.Analysis.HenonEmden.WeakOrigin +OAI.Analysis.HenonEmden.WeightedEndpoints +OAI.Analysis.HenonEmden.WeightedEnergy +OAI.Analysis.HenonEmden.WeightedVirial diff --git a/tasks/henon-emden/solution/reference.py b/tasks/henon-emden/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/henon-emden/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/henon-emden/solution/solve.sh b/tasks/henon-emden/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d9efb9d3ee75abffe2d0061de421e9528c135334 --- /dev/null +++ b/tasks/henon-emden/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HenonEmden, i.e. module OAI.Analysis.HenonEmden.Main and the +# 96 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.HenonEmden.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HenonEmden" diff --git a/tasks/henon-emden/task.toml b/tasks/henon-emden/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..52529f271ac9a7afd4cdf9942b448e60610edcbe --- /dev/null +++ b/tasks/henon-emden/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/henon-emden" +version = "1.0.0" +description = "Prove HenonEmden (openai/math family 370: The subcritical Lane–Emden and Henon–Lane–Emden conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HenonEmden.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HenonEmden" +family = "370" +family_title = "The subcritical Lane–Emden and Henon–Lane–Emden conjectures" +subject = "Partial differential equations" +theorems = ["OAI.HenonLaneEmden.main_nonexistence"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.HenonEmden.Main" +reference_modules = 96 +reference_lean_bytes = 645822 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1094 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12281 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/henon-emden/tests/Challenge.lean b/tasks/henon-emden/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6481354cae9713ce9f1e0db2ec5eb06a42c649ef --- /dev/null +++ b/tasks/henon-emden/tests/Challenge.lean @@ -0,0 +1,31 @@ +import Mathlib + +namespace OAI + +namespace HenonLaneEmden + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +structure IsSolution (n : ℕ) (p q A B : ℝ) (u v : Space n → ℝ) : Prop where + continuous_u : Continuous u + continuous_v : Continuous v + regular_u : ContDiffOn ℝ 2 u ({0}ᶜ : Set (Space n)) + regular_v : ContDiffOn ℝ 2 v ({0}ᶜ : Set (Space n)) + positive_u : ∀ x, 0 < u x + positive_v : ∀ x, 0 < v x + equation_u : ∀ x, x ≠ 0 → + -(Laplacian.laplacian u) x = Real.rpow ‖x‖ A * Real.rpow (v x) p + equation_v : ∀ x, x ≠ 0 → + -(Laplacian.laplacian v) x = Real.rpow ‖x‖ B * Real.rpow (u x) q + +def Subcritical (n : ℕ) (p q A B : ℝ) : Prop := + ((n : ℝ) + A) / (p + 1) + ((n : ℝ) + B) / (q + 1) > (n : ℝ) - (1 + 1) + +theorem main_nonexistence (n : ℕ) (hn : 2 ≤ n) (p q A B : ℝ) + (hp : 0 < p) (hq : 0 < q) (hsub : Subcritical n p q A B) : + ¬ ∃ u v : Space n → ℝ, IsSolution n p q A B u v := by + sorry + +end HenonLaneEmden + +end OAI diff --git a/tasks/henon-emden/tests/grade.py b/tasks/henon-emden/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/henon-emden/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/henon-emden/tests/task.json b/tasks/henon-emden/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7db2340b239fac3b83bc48fcf79489f3d1170565 --- /dev/null +++ b/tasks/henon-emden/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HenonEmden", + "comparator": { + "theorem_names": [ + "OAI.HenonLaneEmden.main_nonexistence" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11381 +} \ No newline at end of file diff --git a/tasks/henon-emden/tests/test.sh b/tasks/henon-emden/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/henon-emden/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hilbert-crouzeix/environment/Dockerfile b/tasks/hilbert-crouzeix/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hilbert-crouzeix/environment/fetch_mathlib.sh b/tasks/hilbert-crouzeix/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hilbert-crouzeix/environment/lake-manifest.json b/tasks/hilbert-crouzeix/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hilbert-crouzeix/environment/lakefile.lean b/tasks/hilbert-crouzeix/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hilbert-crouzeix/environment/lean_setup.sh b/tasks/hilbert-crouzeix/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hilbert-crouzeix/environment/pack_submission.py b/tasks/hilbert-crouzeix/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hilbert-crouzeix/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hilbert-crouzeix/instruction.md b/tasks/hilbert-crouzeix/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..50dbe5468084df8159c0f101f01a95a3dab65040 --- /dev/null +++ b/tasks/hilbert-crouzeix/instruction.md @@ -0,0 +1,194 @@ +# openai/math challenge `HilbertCrouzeix` (family 325) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 325 of the release, *The complete Crouzeix conjecture* +(Functional analysis). The family as a whole: Resolves the complete Crouzeix conjecture: for every bounded operator $A$ on a complex Hilbert space and every finite matrix-valued polynomial $P$, one has $\lVert P[A]\rVert\le2\sup_{z\in W(A)}\lVert P(z)\rVert$, where $W(A)$ is the numerical range. The constant $2$ is sharp, independent of the matrix size, and valid in infinite dimensions. + +The challenge is `HilbertCrouzeix`, also at `/opt/openai-math/challenges/HilbertCrouzeix.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Complex Set +open scoped TensorProduct Matrix.Norms.L2Operator Classical ComplexConjugate + +namespace HilbertCrouzeix + +universe u + +abbrev Coeff (m : ℕ) := Matrix (Fin m) (Fin m) ℂ +abbrev CoeffSpace (m : ℕ) := EuclideanSpace ℂ (Fin m) + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +def numericalRange (A : H →L[ℂ] H) : Set ℂ := + {z | ∃ x : H, ‖x‖ = 1 ∧ inner ℂ x (A x) = z} + +def numericalClosure (A : H →L[ℂ] H) : Set ℂ := closure (numericalRange A) + +abbrev Amplification (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (m : ℕ) := UniformSpace.Completion (H ⊗[ℂ] CoeffSpace m) + +def tensorOp {m : ℕ} (A : H →L[ℂ] H) (B : Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + (TensorProduct.mapL A (Matrix.toEuclideanCLM (n := Fin m) (𝕜 := ℂ) B)).completion + +def matrixPolynomial {m d : ℕ} (B : Fin (d + 1) → Coeff m) (z : ℂ) : Coeff m := + ∑ k : Fin (d + 1), z ^ k.val • B k + +def polynomialEval {m d : ℕ} (A : H →L[ℂ] H) (B : Fin (d + 1) → Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ k : Fin (d + 1), tensorOp (A ^ k.val) (B k) + +def normSup {E : Type*} [Norm E] (S : Set ℂ) (f : ℂ → E) : ℝ := + if S.Nonempty then sSup ((fun z => ‖f z‖) '' S) else 0 +def contourIntegral {E : Type*} [NormedAddCommGroup E] [NormedSpace ℂ E] + (γ : ℝ → ℂ) (f : ℂ → E) : E := + ∫ t : ℝ in (0 : ℝ)..1, deriv γ t • f (γ t) + +def contourIndex (γ : ℝ → ℂ) (z : ℂ) : ℂ := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ * contourIntegral γ (fun w => (w - z)⁻¹) + +def IsCauchyContour (K U : Set ℂ) (γ : ℝ → ℂ) : Prop := + ContDiff ℝ 1 γ ∧ γ 0 = γ 1 ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, γ t ∈ U \ K) ∧ + (∀ z ∈ K, contourIndex γ z = 1) ∧ + (∀ z ∉ U, contourIndex γ z = 0) + +def chosenContour (K U : Set ℂ) : ℝ → ℂ := + Classical.epsilon (IsCauchyContour K U) + +variable [CompleteSpace H] + +def dunfordIntegral (A : H →L[ℂ] H) (γ : ℝ → ℂ) (f : ℂ → ℂ) : H →L[ℂ] H := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ • + contourIntegral γ (fun z => f z • resolvent A z) + +def holomorphicCalculus (A : H →L[ℂ] H) (U : Set ℂ) (f : ℂ → ℂ) : H →L[ℂ] H := + dunfordIntegral A (chosenContour (numericalClosure A) U) f + +def matrixUnit {m : ℕ} (i j : Fin m) : Coeff m := Matrix.single i j 1 + +def holomorphicEval {m : ℕ} (A : H →L[ℂ] H) (U : Set ℂ) (F : ℂ → Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ i : Fin m, ∑ j : Fin m, + tensorOp (holomorphicCalculus A U (fun z => F z i j)) (matrixUnit i j) +abbrev RationalMatrix (m : ℕ) := Matrix (Fin m) (Fin m) (RatFunc ℂ) + +def poleFreeSet {m : ℕ} (R : RationalMatrix m) : Set ℂ := + {z | ∀ i j, (R i j).denom.eval z ≠ 0} + +def rationalFunction {m : ℕ} (R : RationalMatrix m) (z : ℂ) : Coeff m := + fun i j => RatFunc.eval (RingHom.id ℂ) z (R i j) + +def rationalCalculus (A : H →L[ℂ] H) (r : RatFunc ℂ) : H →L[ℂ] H := + Polynomial.aeval A r.num * Ring.inverse (Polynomial.aeval A r.denom) + +def rationalEval {m : ℕ} (A : H →L[ℂ] H) (R : RationalMatrix m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ i : Fin m, ∑ j : Fin m, tensorOp (rationalCalculus A (R i j)) (matrixUnit i j) +def ZeroConclusion (A : H →L[ℂ] H) : Prop := + numericalRange A = ∅ ∧ + (∀ (m : ℕ) (F : ℂ → Coeff m), normSup (numericalRange A) F = 0) ∧ + ∀ (m : ℕ), 0 < m → + (∀ T : Amplification H m →L[ℂ] Amplification H m, T = 0) ∧ + (∀ (d : ℕ) (B : Fin (d + 1) → Coeff m), polynomialEval A B = 0 ∧ + ‖polynomialEval A B‖ ≤ 2 * normSup (numericalRange A) (matrixPolynomial B)) ∧ + (∀ (U : Set ℂ) (F : ℂ → Coeff m), holomorphicEval A U F = 0 ∧ + ‖holomorphicEval A U F‖ ≤ 2 * normSup (numericalRange A) F) ∧ + (∀ (R : RationalMatrix m), rationalEval A R = 0 ∧ + ‖rationalEval A R‖ ≤ 2 * normSup (numericalRange A) (rationalFunction R)) + +section CompressionDefinitions +omit [CompleteSpace H] + +def compression (A : H →L[ℂ] H) (E : Submodule ℂ H) [E.HasOrthogonalProjection] : + E →L[ℂ] E := E.orthogonalProjectionOnto.comp (A.comp E.subtypeL) +def completedIsometry {V : Type*} {W : Type*} + [NormedAddCommGroup V] [NormedAddCommGroup W] [NormedSpace ℂ V] [NormedSpace ℂ W] + (f : V →ₗᵢ[ℂ] W) : UniformSpace.Completion V →ₗᵢ[ℂ] UniformSpace.Completion W := + { f.toContinuousLinearMap.completion.toLinearMap with + norm_map' := f.isometry.completion_map.norm_map_of_map_zero + (f.toContinuousLinearMap.completion.map_zero) } + +def tensorInclusion (E : Submodule ℂ H) (m : ℕ) : + Amplification E m →ₗᵢ[ℂ] Amplification H m := + completedIsometry (TensorProduct.mapIsometry E.subtypeₗᵢ (.id : CoeffSpace m →ₗᵢ[ℂ] CoeffSpace m)) + +end CompressionDefinitions + +theorem numericalClosure_geometry (A : H →L[ℂ] H) : + IsCompact (numericalClosure A) ∧ Convex ℝ (numericalClosure A) ∧ + spectrum ℂ A ⊆ numericalClosure A := by + sorry + +omit [CompleteSpace H] in +theorem exists_finite_compression {m d : ℕ} (A : H →L[ℂ] H) + (B : Fin (d + 1) → Coeff m) (ξ : H ⊗[ℂ] CoeffSpace m) : + ∃ (E : Submodule ℂ H) (hE : FiniteDimensional ℂ E), + letI : FiniteDimensional ℂ E := hE + ∃ η : Amplification E m, + tensorInclusion E m η = (↑ξ : Amplification H m) ∧ + tensorInclusion E m (polynomialEval (compression A E) B η) = + polynomialEval A B (↑ξ) := by + sorry + +theorem rational_denominator_isUnit [Nontrivial H] (A : H →L[ℂ] H) + {m : ℕ} (R : RationalMatrix m) (hR : numericalClosure A ⊆ poleFreeSet R) + (i j : Fin m) : IsUnit (Polynomial.aeval A (R i j).denom) := by + sorry + +theorem zeroConclusion [Subsingleton H] (A : H →L[ℂ] H) : ZeroConclusion A := by + sorry + +end HilbertCrouzeix + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HilbertCrouzeix.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.HilbertCrouzeix.numericalClosure_geometry`, `OAI.HilbertCrouzeix.exists_finite_compression`, `OAI.HilbertCrouzeix.rational_denominator_isUnit`, `OAI.HilbertCrouzeix.zeroConclusion` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hilbert-crouzeix/solution/closure.txt b/tasks/hilbert-crouzeix/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4f07d587774b48e50d0be2fef77363f581bd6da2 --- /dev/null +++ b/tasks/hilbert-crouzeix/solution/closure.txt @@ -0,0 +1,7 @@ +OAI.Analysis.HilbertCrouzeix.Calculus +OAI.Analysis.HilbertCrouzeix.Compression +OAI.Analysis.HilbertCrouzeix.Definitions +OAI.Analysis.HilbertCrouzeix.Main +OAI.Analysis.HilbertCrouzeix.NumericalRange +OAI.Analysis.HilbertCrouzeix.Sharpness +OAI.Analysis.HilbertCrouzeix.Spectrum diff --git a/tasks/hilbert-crouzeix/solution/reference.py b/tasks/hilbert-crouzeix/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hilbert-crouzeix/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hilbert-crouzeix/solution/solve.sh b/tasks/hilbert-crouzeix/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6c41b2b81e877753cff93e60ac6913c321fcb472 --- /dev/null +++ b/tasks/hilbert-crouzeix/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HilbertCrouzeix, i.e. module OAI.Analysis.HilbertCrouzeix.Main and the +# 7 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.HilbertCrouzeix.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HilbertCrouzeix" diff --git a/tasks/hilbert-crouzeix/task.toml b/tasks/hilbert-crouzeix/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..629a79fc11fd621ee24f4afdf8bbd065dda8e8d5 --- /dev/null +++ b/tasks/hilbert-crouzeix/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hilbert-crouzeix" +version = "1.0.0" +description = "Prove HilbertCrouzeix (openai/math family 325: The complete Crouzeix conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HilbertCrouzeix.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HilbertCrouzeix" +family = "325" +family_title = "The complete Crouzeix conjecture" +subject = "Functional analysis" +theorems = ["OAI.HilbertCrouzeix.numericalClosure_geometry", "OAI.HilbertCrouzeix.exists_finite_compression", "OAI.HilbertCrouzeix.rational_denominator_isUnit", "OAI.HilbertCrouzeix.zeroConclusion"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.HilbertCrouzeix.Main" +reference_modules = 7 +reference_lean_bytes = 36730 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 927 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11733 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hilbert-crouzeix/tests/Challenge.lean b/tasks/hilbert-crouzeix/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ca3a09958ae50cde644182589149a90199e763a --- /dev/null +++ b/tasks/hilbert-crouzeix/tests/Challenge.lean @@ -0,0 +1,143 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Complex Set +open scoped TensorProduct Matrix.Norms.L2Operator Classical ComplexConjugate + +namespace HilbertCrouzeix + +universe u + +abbrev Coeff (m : ℕ) := Matrix (Fin m) (Fin m) ℂ +abbrev CoeffSpace (m : ℕ) := EuclideanSpace ℂ (Fin m) + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +def numericalRange (A : H →L[ℂ] H) : Set ℂ := + {z | ∃ x : H, ‖x‖ = 1 ∧ inner ℂ x (A x) = z} + +def numericalClosure (A : H →L[ℂ] H) : Set ℂ := closure (numericalRange A) + +abbrev Amplification (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + (m : ℕ) := UniformSpace.Completion (H ⊗[ℂ] CoeffSpace m) + +def tensorOp {m : ℕ} (A : H →L[ℂ] H) (B : Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + (TensorProduct.mapL A (Matrix.toEuclideanCLM (n := Fin m) (𝕜 := ℂ) B)).completion + +def matrixPolynomial {m d : ℕ} (B : Fin (d + 1) → Coeff m) (z : ℂ) : Coeff m := + ∑ k : Fin (d + 1), z ^ k.val • B k + +def polynomialEval {m d : ℕ} (A : H →L[ℂ] H) (B : Fin (d + 1) → Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ k : Fin (d + 1), tensorOp (A ^ k.val) (B k) + +def normSup {E : Type*} [Norm E] (S : Set ℂ) (f : ℂ → E) : ℝ := + if S.Nonempty then sSup ((fun z => ‖f z‖) '' S) else 0 +def contourIntegral {E : Type*} [NormedAddCommGroup E] [NormedSpace ℂ E] + (γ : ℝ → ℂ) (f : ℂ → E) : E := + ∫ t : ℝ in (0 : ℝ)..1, deriv γ t • f (γ t) + +def contourIndex (γ : ℝ → ℂ) (z : ℂ) : ℂ := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ * contourIntegral γ (fun w => (w - z)⁻¹) + +def IsCauchyContour (K U : Set ℂ) (γ : ℝ → ℂ) : Prop := + ContDiff ℝ 1 γ ∧ γ 0 = γ 1 ∧ + (∀ t ∈ Set.Icc (0 : ℝ) 1, γ t ∈ U \ K) ∧ + (∀ z ∈ K, contourIndex γ z = 1) ∧ + (∀ z ∉ U, contourIndex γ z = 0) + +def chosenContour (K U : Set ℂ) : ℝ → ℂ := + Classical.epsilon (IsCauchyContour K U) + +variable [CompleteSpace H] + +def dunfordIntegral (A : H →L[ℂ] H) (γ : ℝ → ℂ) (f : ℂ → ℂ) : H →L[ℂ] H := + (2 * (Real.pi : ℂ) * Complex.I)⁻¹ • + contourIntegral γ (fun z => f z • resolvent A z) + +def holomorphicCalculus (A : H →L[ℂ] H) (U : Set ℂ) (f : ℂ → ℂ) : H →L[ℂ] H := + dunfordIntegral A (chosenContour (numericalClosure A) U) f + +def matrixUnit {m : ℕ} (i j : Fin m) : Coeff m := Matrix.single i j 1 + +def holomorphicEval {m : ℕ} (A : H →L[ℂ] H) (U : Set ℂ) (F : ℂ → Coeff m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ i : Fin m, ∑ j : Fin m, + tensorOp (holomorphicCalculus A U (fun z => F z i j)) (matrixUnit i j) +abbrev RationalMatrix (m : ℕ) := Matrix (Fin m) (Fin m) (RatFunc ℂ) + +def poleFreeSet {m : ℕ} (R : RationalMatrix m) : Set ℂ := + {z | ∀ i j, (R i j).denom.eval z ≠ 0} + +def rationalFunction {m : ℕ} (R : RationalMatrix m) (z : ℂ) : Coeff m := + fun i j => RatFunc.eval (RingHom.id ℂ) z (R i j) + +def rationalCalculus (A : H →L[ℂ] H) (r : RatFunc ℂ) : H →L[ℂ] H := + Polynomial.aeval A r.num * Ring.inverse (Polynomial.aeval A r.denom) + +def rationalEval {m : ℕ} (A : H →L[ℂ] H) (R : RationalMatrix m) : + Amplification H m →L[ℂ] Amplification H m := + ∑ i : Fin m, ∑ j : Fin m, tensorOp (rationalCalculus A (R i j)) (matrixUnit i j) +def ZeroConclusion (A : H →L[ℂ] H) : Prop := + numericalRange A = ∅ ∧ + (∀ (m : ℕ) (F : ℂ → Coeff m), normSup (numericalRange A) F = 0) ∧ + ∀ (m : ℕ), 0 < m → + (∀ T : Amplification H m →L[ℂ] Amplification H m, T = 0) ∧ + (∀ (d : ℕ) (B : Fin (d + 1) → Coeff m), polynomialEval A B = 0 ∧ + ‖polynomialEval A B‖ ≤ 2 * normSup (numericalRange A) (matrixPolynomial B)) ∧ + (∀ (U : Set ℂ) (F : ℂ → Coeff m), holomorphicEval A U F = 0 ∧ + ‖holomorphicEval A U F‖ ≤ 2 * normSup (numericalRange A) F) ∧ + (∀ (R : RationalMatrix m), rationalEval A R = 0 ∧ + ‖rationalEval A R‖ ≤ 2 * normSup (numericalRange A) (rationalFunction R)) + +section CompressionDefinitions +omit [CompleteSpace H] + +def compression (A : H →L[ℂ] H) (E : Submodule ℂ H) [E.HasOrthogonalProjection] : + E →L[ℂ] E := E.orthogonalProjectionOnto.comp (A.comp E.subtypeL) +def completedIsometry {V : Type*} {W : Type*} + [NormedAddCommGroup V] [NormedAddCommGroup W] [NormedSpace ℂ V] [NormedSpace ℂ W] + (f : V →ₗᵢ[ℂ] W) : UniformSpace.Completion V →ₗᵢ[ℂ] UniformSpace.Completion W := + { f.toContinuousLinearMap.completion.toLinearMap with + norm_map' := f.isometry.completion_map.norm_map_of_map_zero + (f.toContinuousLinearMap.completion.map_zero) } + +def tensorInclusion (E : Submodule ℂ H) (m : ℕ) : + Amplification E m →ₗᵢ[ℂ] Amplification H m := + completedIsometry (TensorProduct.mapIsometry E.subtypeₗᵢ (.id : CoeffSpace m →ₗᵢ[ℂ] CoeffSpace m)) + +end CompressionDefinitions + +theorem numericalClosure_geometry (A : H →L[ℂ] H) : + IsCompact (numericalClosure A) ∧ Convex ℝ (numericalClosure A) ∧ + spectrum ℂ A ⊆ numericalClosure A := by + sorry + +omit [CompleteSpace H] in +theorem exists_finite_compression {m d : ℕ} (A : H →L[ℂ] H) + (B : Fin (d + 1) → Coeff m) (ξ : H ⊗[ℂ] CoeffSpace m) : + ∃ (E : Submodule ℂ H) (hE : FiniteDimensional ℂ E), + letI : FiniteDimensional ℂ E := hE + ∃ η : Amplification E m, + tensorInclusion E m η = (↑ξ : Amplification H m) ∧ + tensorInclusion E m (polynomialEval (compression A E) B η) = + polynomialEval A B (↑ξ) := by + sorry + +theorem rational_denominator_isUnit [Nontrivial H] (A : H →L[ℂ] H) + {m : ℕ} (R : RationalMatrix m) (hR : numericalClosure A ⊆ poleFreeSet R) + (i j : Fin m) : IsUnit (Polynomial.aeval A (R i j).denom) := by + sorry + +theorem zeroConclusion [Subsingleton H] (A : H →L[ℂ] H) : ZeroConclusion A := by + sorry + +end HilbertCrouzeix + +end + +end OAI diff --git a/tasks/hilbert-crouzeix/tests/grade.py b/tasks/hilbert-crouzeix/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hilbert-crouzeix/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hilbert-crouzeix/tests/task.json b/tasks/hilbert-crouzeix/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dbace11d455384a63d1dcd882502c2cbf8391d3c --- /dev/null +++ b/tasks/hilbert-crouzeix/tests/task.json @@ -0,0 +1,18 @@ +{ + "challenge": "HilbertCrouzeix", + "comparator": { + "theorem_names": [ + "OAI.HilbertCrouzeix.numericalClosure_geometry", + "OAI.HilbertCrouzeix.exists_finite_compression", + "OAI.HilbertCrouzeix.rational_denominator_isUnit", + "OAI.HilbertCrouzeix.zeroConclusion" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10833 +} \ No newline at end of file diff --git a/tasks/hilbert-crouzeix/tests/test.sh b/tasks/hilbert-crouzeix/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hilbert-crouzeix/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/honeycomb-bridge-finiteness/environment/Dockerfile b/tasks/honeycomb-bridge-finiteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/honeycomb-bridge-finiteness/environment/fetch_mathlib.sh b/tasks/honeycomb-bridge-finiteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/honeycomb-bridge-finiteness/environment/lake-manifest.json b/tasks/honeycomb-bridge-finiteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/honeycomb-bridge-finiteness/environment/lakefile.lean b/tasks/honeycomb-bridge-finiteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/honeycomb-bridge-finiteness/environment/lean_setup.sh b/tasks/honeycomb-bridge-finiteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/honeycomb-bridge-finiteness/environment/pack_submission.py b/tasks/honeycomb-bridge-finiteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/honeycomb-bridge-finiteness/instruction.md b/tasks/honeycomb-bridge-finiteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3aeea59f221d3e333f65708bd8898c145092baad --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/instruction.md @@ -0,0 +1,116 @@ +# openai/math challenge `HoneycombBridgeFiniteness` (family 237) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 237 of the release, *The three-quarter diameter exponent for honeycomb walks* +(Probability and statistical mechanics). The family as a whole: Proves the diameter form of Nienhuis's predicted three-quarter exponent: a uniformly chosen $n$-step self-avoiding walk on the honeycomb lattice has diameter $n^{3/4+o(1)}$. Its local mass and covering numbers have exponent $4/3$. These estimates hold at every sufficiently large fixed length, simultaneously across scales, with arbitrarily high polynomial probability. + +The challenge is `HoneycombBridgeFiniteness`, also at `/opt/openai-math/challenges/HoneycombBridgeFiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PolynomialVacuumBridge.Corridor + +inductive Vertex where + | up (i j : ℤ) + | down (i j : ℤ) + deriving DecidableEq + +noncomputable def position : Vertex → ℝ × ℝ + | .up i j => ((i : ℝ) + (j : ℝ) / 2, + ((j : ℝ) + 1 / 3) * (Real.sqrt 3 / 2)) + | .down i j => ((i : ℝ) + (j : ℝ) / 2 + 1 / 2, + ((j : ℝ) + 2 / 3) * (Real.sqrt 3 / 2)) + +def adjacent : Vertex → Vertex → Prop + | .up i j, .down k l => + (k = i ∧ l = j - 1) ∨ (k = i ∧ l = j) ∨ (k = i - 1 ∧ l = j) + | .down k l, .up i j => + (k = i ∧ l = j - 1) ∨ (k = i ∧ l = j) ∨ (k = i - 1 ∧ l = j) + | _, _ => False + +noncomputable def criticalActivity : ℝ := (2 * Real.cos (Real.pi / 8))⁻¹ +noncomputable def layer (vertex : Vertex) : ℤ := + Vertex.rec (fun _ vertical => vertical) (fun _ vertical => vertical) vertex + +structure BridgePath (h : ℕ) where + vertices : List Vertex + distinct : vertices.Nodup + connected : vertices.IsChain adjacent + source : vertices.head? = some (.up 0 0) + terminal : ∃ i : ℤ, vertices.getLast? = some (.down i ((h : ℤ) - 1)) + inStrip : ∀ v ∈ vertices, 0 ≤ layer v ∧ layer v < (h : ℤ) + +noncomputable def weight {h : ℕ} (p : BridgePath h) : ℝ := + criticalActivity ^ p.vertices.length + +noncomputable def firstLengthWeight {h : ℕ} (p : BridgePath h) : ℝ := + (p.vertices.length : ℝ) * weight p + +noncomputable def bridgeMass (h : ℕ) : ℝ := ∑' p : BridgePath h, weight p +noncomputable def InLogCorridor {h : ℕ} (p : BridgePath h) : Prop := + ∀ v ∈ p.vertices, |(position v).1| ≤ (h : ℝ) * (Real.log (h : ℝ)) ^ 2 + +def ConfinedBridgePath (h : ℕ) := {p : BridgePath h // InLogCorridor p} + +noncomputable def confinedMass (h : ℕ) : ℝ := + ∑' p : ConfinedBridgePath h, weight p.val +def FiniteBridgeSums : Prop := + ∀ h : ℕ, 1 ≤ h → + Summable (weight (h := h)) ∧ Summable (firstLengthWeight (h := h)) ∧ + Summable (fun p : BridgePath h => firstLengthWeight p / bridgeMass h) ∧ + Summable (fun p : ConfinedBridgePath h => weight p.val) ∧ + Summable (fun p : ConfinedBridgePath h => firstLengthWeight p.val) ∧ + Summable (fun p : ConfinedBridgePath h => firstLengthWeight p.val / confinedMass h) + + +theorem finite_bridge_sums : FiniteBridgeSums := by + sorry + +end PolynomialVacuumBridge.Corridor + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HoneycombBridgeFiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PolynomialVacuumBridge.Corridor.finite_bridge_sums` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/honeycomb-bridge-finiteness/solution/closure.txt b/tasks/honeycomb-bridge-finiteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..46eb6f9c7491b7bb8eb1f46df7c5dc8d2d483e37 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/solution/closure.txt @@ -0,0 +1,43 @@ +OAI.Combinatorics.HoneycombCorridor.Basic +OAI.Combinatorics.HoneycombCorridor.BoundaryArcs +OAI.Combinatorics.HoneycombCorridor.BoundaryCharge +OAI.Combinatorics.HoneycombCorridor.BoundaryContainment +OAI.Combinatorics.HoneycombCorridor.BoundaryFlux +OAI.Combinatorics.HoneycombCorridor.BridgeFiniteness +OAI.Combinatorics.HoneycombCorridor.Bridges +OAI.Combinatorics.HoneycombCorridor.Cells +OAI.Combinatorics.HoneycombCorridor.CollisionCancellation +OAI.Combinatorics.HoneycombCorridor.CollisionGrouping +OAI.Combinatorics.HoneycombCorridor.CollisionHistories +OAI.Combinatorics.HoneycombCorridor.CollisionPhase +OAI.Combinatorics.HoneycombCorridor.CollisionStems +OAI.Combinatorics.HoneycombCorridor.CollisionWeights +OAI.Combinatorics.HoneycombCorridor.Contours +OAI.Combinatorics.HoneycombCorridor.ConvexCuts +OAI.Combinatorics.HoneycombCorridor.ConvexDomains +OAI.Combinatorics.HoneycombCorridor.Convexity +OAI.Combinatorics.HoneycombCorridor.Currents +OAI.Combinatorics.HoneycombCorridor.Curvature +OAI.Combinatorics.HoneycombCorridor.CycleSplice +OAI.Combinatorics.HoneycombCorridor.EdgeFlow +OAI.Combinatorics.HoneycombCorridor.EulerRank +OAI.Combinatorics.HoneycombCorridor.Excursions +OAI.Combinatorics.HoneycombCorridor.FaceBoundary +OAI.Combinatorics.HoneycombCorridor.Incidence +OAI.Combinatorics.HoneycombCorridor.IntegerPotential +OAI.Combinatorics.HoneycombCorridor.LateralLength +OAI.Combinatorics.HoneycombCorridor.LateralMass +OAI.Combinatorics.HoneycombCorridor.PolygonGeometry +OAI.Combinatorics.HoneycombCorridor.PolygonNesting +OAI.Combinatorics.HoneycombCorridor.PolygonSize +OAI.Combinatorics.HoneycombCorridor.Polygons +OAI.Combinatorics.HoneycombCorridor.PotentialSupport +OAI.Combinatorics.HoneycombCorridor.RationalPotential +OAI.Combinatorics.HoneycombCorridor.RaySeparation +OAI.Combinatorics.HoneycombCorridor.Reflection +OAI.Combinatorics.HoneycombCorridor.ReturnCycles +OAI.Combinatorics.HoneycombCorridor.SpatialDecay +OAI.Combinatorics.HoneycombCorridor.StripDecay +OAI.Combinatorics.HoneycombCorridor.StripWindows +OAI.Combinatorics.HoneycombCorridor.Traversals +OAI.Combinatorics.HoneycombCorridor.VisitRecursion diff --git a/tasks/honeycomb-bridge-finiteness/solution/reference.py b/tasks/honeycomb-bridge-finiteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/honeycomb-bridge-finiteness/solution/solve.sh b/tasks/honeycomb-bridge-finiteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..da589d39b5762dc8afbbf268af215bd27d241e35 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HoneycombBridgeFiniteness, i.e. module OAI.Combinatorics.HoneycombCorridor.BridgeFiniteness and the +# 43 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.HoneycombCorridor.BridgeFiniteness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HoneycombBridgeFiniteness" diff --git a/tasks/honeycomb-bridge-finiteness/task.toml b/tasks/honeycomb-bridge-finiteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bc943a0906e79aa00694ffbc19d3d1a6edbf13d3 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/honeycomb-bridge-finiteness" +version = "1.0.0" +description = "Prove HoneycombBridgeFiniteness (openai/math family 237: The three-quarter diameter exponent for honeycomb walks) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HoneycombBridgeFiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HoneycombBridgeFiniteness" +family = "237" +family_title = "The three-quarter diameter exponent for honeycomb walks" +subject = "Probability and statistical mechanics" +theorems = ["OAI.PolynomialVacuumBridge.Corridor.finite_bridge_sums"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.HoneycombCorridor.BridgeFiniteness" +reference_modules = 43 +reference_lean_bytes = 322795 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 711 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11990 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/honeycomb-bridge-finiteness/tests/Challenge.lean b/tasks/honeycomb-bridge-finiteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a75590bb581ff45f3b4b5b364c57dbdeae982381 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/tests/Challenge.lean @@ -0,0 +1,65 @@ +import Mathlib + +namespace OAI + +namespace PolynomialVacuumBridge.Corridor + +inductive Vertex where + | up (i j : ℤ) + | down (i j : ℤ) + deriving DecidableEq + +noncomputable def position : Vertex → ℝ × ℝ + | .up i j => ((i : ℝ) + (j : ℝ) / 2, + ((j : ℝ) + 1 / 3) * (Real.sqrt 3 / 2)) + | .down i j => ((i : ℝ) + (j : ℝ) / 2 + 1 / 2, + ((j : ℝ) + 2 / 3) * (Real.sqrt 3 / 2)) + +def adjacent : Vertex → Vertex → Prop + | .up i j, .down k l => + (k = i ∧ l = j - 1) ∨ (k = i ∧ l = j) ∨ (k = i - 1 ∧ l = j) + | .down k l, .up i j => + (k = i ∧ l = j - 1) ∨ (k = i ∧ l = j) ∨ (k = i - 1 ∧ l = j) + | _, _ => False + +noncomputable def criticalActivity : ℝ := (2 * Real.cos (Real.pi / 8))⁻¹ +noncomputable def layer (vertex : Vertex) : ℤ := + Vertex.rec (fun _ vertical => vertical) (fun _ vertical => vertical) vertex + +structure BridgePath (h : ℕ) where + vertices : List Vertex + distinct : vertices.Nodup + connected : vertices.IsChain adjacent + source : vertices.head? = some (.up 0 0) + terminal : ∃ i : ℤ, vertices.getLast? = some (.down i ((h : ℤ) - 1)) + inStrip : ∀ v ∈ vertices, 0 ≤ layer v ∧ layer v < (h : ℤ) + +noncomputable def weight {h : ℕ} (p : BridgePath h) : ℝ := + criticalActivity ^ p.vertices.length + +noncomputable def firstLengthWeight {h : ℕ} (p : BridgePath h) : ℝ := + (p.vertices.length : ℝ) * weight p + +noncomputable def bridgeMass (h : ℕ) : ℝ := ∑' p : BridgePath h, weight p +noncomputable def InLogCorridor {h : ℕ} (p : BridgePath h) : Prop := + ∀ v ∈ p.vertices, |(position v).1| ≤ (h : ℝ) * (Real.log (h : ℝ)) ^ 2 + +def ConfinedBridgePath (h : ℕ) := {p : BridgePath h // InLogCorridor p} + +noncomputable def confinedMass (h : ℕ) : ℝ := + ∑' p : ConfinedBridgePath h, weight p.val +def FiniteBridgeSums : Prop := + ∀ h : ℕ, 1 ≤ h → + Summable (weight (h := h)) ∧ Summable (firstLengthWeight (h := h)) ∧ + Summable (fun p : BridgePath h => firstLengthWeight p / bridgeMass h) ∧ + Summable (fun p : ConfinedBridgePath h => weight p.val) ∧ + Summable (fun p : ConfinedBridgePath h => firstLengthWeight p.val) ∧ + Summable (fun p : ConfinedBridgePath h => firstLengthWeight p.val / confinedMass h) + + +theorem finite_bridge_sums : FiniteBridgeSums := by + sorry + +end PolynomialVacuumBridge.Corridor + +end OAI diff --git a/tasks/honeycomb-bridge-finiteness/tests/grade.py b/tasks/honeycomb-bridge-finiteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/honeycomb-bridge-finiteness/tests/task.json b/tasks/honeycomb-bridge-finiteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c7da7bae5e903467421f425a7dccc9526b489ff9 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HoneycombBridgeFiniteness", + "comparator": { + "theorem_names": [ + "OAI.PolynomialVacuumBridge.Corridor.finite_bridge_sums" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11090 +} \ No newline at end of file diff --git a/tasks/honeycomb-bridge-finiteness/tests/test.sh b/tasks/honeycomb-bridge-finiteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/honeycomb-bridge-finiteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/honeycomb-free-energy/environment/Dockerfile b/tasks/honeycomb-free-energy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/honeycomb-free-energy/environment/fetch_mathlib.sh b/tasks/honeycomb-free-energy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/honeycomb-free-energy/environment/lake-manifest.json b/tasks/honeycomb-free-energy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/honeycomb-free-energy/environment/lakefile.lean b/tasks/honeycomb-free-energy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/honeycomb-free-energy/environment/lean_setup.sh b/tasks/honeycomb-free-energy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/honeycomb-free-energy/environment/pack_submission.py b/tasks/honeycomb-free-energy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/honeycomb-free-energy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/honeycomb-free-energy/instruction.md b/tasks/honeycomb-free-energy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a720a9f0f13a0d5872069333cbfa85f52bcc7dc --- /dev/null +++ b/tasks/honeycomb-free-energy/instruction.md @@ -0,0 +1,123 @@ +# openai/math challenge `HoneycombFreeEnergy` (family 237) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 237 of the release, *The three-quarter diameter exponent for honeycomb walks* +(Probability and statistical mechanics). The family as a whole: Proves the diameter form of Nienhuis's predicted three-quarter exponent: a uniformly chosen $n$-step self-avoiding walk on the honeycomb lattice has diameter $n^{3/4+o(1)}$. Its local mass and covering numbers have exponent $4/3$. These estimates hold at every sufficiently large fixed length, simultaneously across scales, with arbitrarily high polynomial probability. + +The challenge is `HoneycombFreeEnergy`, also at `/opt/openai-math/challenges/HoneycombFreeEnergy.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Existence of the fixed-length forced free energy of honeycomb walks. -/ + +noncomputable section +open scoped ENNReal Topology +open Filter + +namespace HoneycombForce + +structure Vertex where + col : ℤ + row : ℤ + up : Bool + deriving DecidableEq + +def up (i j : ℤ) : Vertex := ⟨i, j, true⟩ + +def down (i j : ℤ) : Vertex := ⟨i, j, false⟩ + +def rowSpacing : ℝ := Real.sqrt 3 / 2 + +def position (v : Vertex) : ℂ := + if v.up then + ⟨(v.col : ℝ) + (v.row : ℝ) / 2 + 1/2, + rowSpacing * ((v.row : ℝ) + 1/3)⟩ + else + ⟨(v.col : ℝ) + (v.row : ℝ) / 2 + 1, + rowSpacing * ((v.row : ℝ) + 2/3)⟩ + +def rho : ℝ := (Real.sqrt (2 + Real.sqrt 2))⁻¹ + +def neighbors (v : Vertex) : Finset Vertex := + if v.up then + {down v.col (v.row-1), down v.col v.row, down (v.col-1) v.row} + else + {up v.col (v.row+1), up v.col v.row, up (v.col+1) v.row} + +def walkLists (o : Vertex) : ℕ → Finset (List Vertex) + | 0 => {[o]} + | n+1 => (neighbors o).biUnion (fun v => (walkLists v n).image (List.cons o)) + +def saws (o : Vertex) (n : ℕ) : Finset (List Vertex) := + (walkLists o n).filter List.Nodup + +def endpoint (o : Vertex) (γ : List Vertex) : Vertex := γ.getLastD o + +def displacement (o : Vertex) (γ : List Vertex) : ℂ := + position (endpoint o γ) - position o + +def projection (e z : ℂ) : ℝ := (star e * z).re + +def partition (o : Vertex) (e : ℂ) (s : ℝ) (n : ℕ) : ℝ := + ∑ γ ∈ saws o n, rho ^ n * Real.exp (s * projection e (displacement o γ)) + +def logPartition (o : Vertex) (e : ℂ) (s : ℝ) (n : ℕ) : ℝ := + Real.log (partition o e s n) / (n : ℝ) + +def freeEnergy (o : Vertex) (e : ℂ) (s : ℝ) : ℝ := + Filter.limUnder atTop (logPartition o e s) + +theorem logPartition_tendsto (o : Vertex) (e : ℂ) (s : ℝ) : + Tendsto (logPartition o e s) atTop (𝓝 (freeEnergy o e s)) := by + sorry + +end HoneycombForce + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HoneycombFreeEnergy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HoneycombForce.logPartition_tendsto` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/honeycomb-free-energy/solution/closure.txt b/tasks/honeycomb-free-energy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0c4077bb315646657c1c974d7b2a0a7c50ead1f4 --- /dev/null +++ b/tasks/honeycomb-free-energy/solution/closure.txt @@ -0,0 +1 @@ +OAI.Probability.Honeycomb.FreeEnergy diff --git a/tasks/honeycomb-free-energy/solution/reference.py b/tasks/honeycomb-free-energy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/honeycomb-free-energy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/honeycomb-free-energy/solution/solve.sh b/tasks/honeycomb-free-energy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..be54568c492f32877787b51d5c65ecfd1356c0f5 --- /dev/null +++ b/tasks/honeycomb-free-energy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HoneycombFreeEnergy, i.e. module OAI.Probability.Honeycomb.FreeEnergy and the +# 1 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Honeycomb.FreeEnergy /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HoneycombFreeEnergy" diff --git a/tasks/honeycomb-free-energy/task.toml b/tasks/honeycomb-free-energy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ea1efa2f1093f8fc57d8faa15209b0ceb3c2f4a --- /dev/null +++ b/tasks/honeycomb-free-energy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/honeycomb-free-energy" +version = "1.0.0" +description = "Prove HoneycombFreeEnergy (openai/math family 237: The three-quarter diameter exponent for honeycomb walks) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HoneycombFreeEnergy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HoneycombFreeEnergy" +family = "237" +family_title = "The three-quarter diameter exponent for honeycomb walks" +subject = "Probability and statistical mechanics" +theorems = ["OAI.HoneycombForce.logPartition_tendsto"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Honeycomb.FreeEnergy" +reference_modules = 1 +reference_lean_bytes = 41826 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 812 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11737 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/honeycomb-free-energy/tests/Challenge.lean b/tasks/honeycomb-free-energy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2fe6b6cb2fb920565023a128d80f3427723ecac --- /dev/null +++ b/tasks/honeycomb-free-energy/tests/Challenge.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +/-! Existence of the fixed-length forced free energy of honeycomb walks. -/ + +noncomputable section +open scoped ENNReal Topology +open Filter + +namespace HoneycombForce + +structure Vertex where + col : ℤ + row : ℤ + up : Bool + deriving DecidableEq + +def up (i j : ℤ) : Vertex := ⟨i, j, true⟩ + +def down (i j : ℤ) : Vertex := ⟨i, j, false⟩ + +def rowSpacing : ℝ := Real.sqrt 3 / 2 + +def position (v : Vertex) : ℂ := + if v.up then + ⟨(v.col : ℝ) + (v.row : ℝ) / 2 + 1/2, + rowSpacing * ((v.row : ℝ) + 1/3)⟩ + else + ⟨(v.col : ℝ) + (v.row : ℝ) / 2 + 1, + rowSpacing * ((v.row : ℝ) + 2/3)⟩ + +def rho : ℝ := (Real.sqrt (2 + Real.sqrt 2))⁻¹ + +def neighbors (v : Vertex) : Finset Vertex := + if v.up then + {down v.col (v.row-1), down v.col v.row, down (v.col-1) v.row} + else + {up v.col (v.row+1), up v.col v.row, up (v.col+1) v.row} + +def walkLists (o : Vertex) : ℕ → Finset (List Vertex) + | 0 => {[o]} + | n+1 => (neighbors o).biUnion (fun v => (walkLists v n).image (List.cons o)) + +def saws (o : Vertex) (n : ℕ) : Finset (List Vertex) := + (walkLists o n).filter List.Nodup + +def endpoint (o : Vertex) (γ : List Vertex) : Vertex := γ.getLastD o + +def displacement (o : Vertex) (γ : List Vertex) : ℂ := + position (endpoint o γ) - position o + +def projection (e z : ℂ) : ℝ := (star e * z).re + +def partition (o : Vertex) (e : ℂ) (s : ℝ) (n : ℕ) : ℝ := + ∑ γ ∈ saws o n, rho ^ n * Real.exp (s * projection e (displacement o γ)) + +def logPartition (o : Vertex) (e : ℂ) (s : ℝ) (n : ℕ) : ℝ := + Real.log (partition o e s n) / (n : ℝ) + +def freeEnergy (o : Vertex) (e : ℂ) (s : ℝ) : ℝ := + Filter.limUnder atTop (logPartition o e s) + +theorem logPartition_tendsto (o : Vertex) (e : ℂ) (s : ℝ) : + Tendsto (logPartition o e s) atTop (𝓝 (freeEnergy o e s)) := by + sorry + +end HoneycombForce + +end + +end OAI diff --git a/tasks/honeycomb-free-energy/tests/grade.py b/tasks/honeycomb-free-energy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/honeycomb-free-energy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/honeycomb-free-energy/tests/task.json b/tasks/honeycomb-free-energy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4f35b346d45f7d84de1bcdc0e490d3c3657a2841 --- /dev/null +++ b/tasks/honeycomb-free-energy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HoneycombFreeEnergy", + "comparator": { + "theorem_names": [ + "OAI.HoneycombForce.logPartition_tendsto" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10837 +} \ No newline at end of file diff --git a/tasks/honeycomb-free-energy/tests/test.sh b/tasks/honeycomb-free-energy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/honeycomb-free-energy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hot-spots/environment/Dockerfile b/tasks/hot-spots/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hot-spots/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hot-spots/environment/fetch_mathlib.sh b/tasks/hot-spots/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hot-spots/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hot-spots/environment/lake-manifest.json b/tasks/hot-spots/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hot-spots/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hot-spots/environment/lakefile.lean b/tasks/hot-spots/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hot-spots/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hot-spots/environment/lean_setup.sh b/tasks/hot-spots/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hot-spots/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hot-spots/environment/pack_submission.py b/tasks/hot-spots/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hot-spots/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hot-spots/instruction.md b/tasks/hot-spots/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..11ecb3f7c3bb82e120b233a8e691a1009765ba9c --- /dev/null +++ b/tasks/hot-spots/instruction.md @@ -0,0 +1,108 @@ +# openai/math challenge `HotSpots` (family 369) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 369 of the release, *The hot spots conjecture for simply connected planar domains* +(Partial differential equations). The family as a whole: Proves a strict form of Burdzy's simply connected hot spots conjecture. On every smooth bounded simply connected planar domain, each nonzero eigenfunction for the first positive Neumann eigenvalue has no interior critical point, so all global extrema lie on the boundary. Eigenvalue multiplicity is allowed. + +The challenge is `HotSpots`, also at `/opt/openai-math/challenges/HotSpots.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory +open scoped ContDiff + +namespace StrictHotSpots + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def SmoothBoundary (Ω : Set Plane) : Prop := + ∀ p ∈ frontier Ω, ∃ (U : Set Plane) (ρ : Plane → ℝ), + IsOpen U ∧ p ∈ U ∧ ContDiffOn ℝ ∞ ρ U ∧ + fderiv ℝ ρ p ≠ 0 ∧ ρ p = 0 ∧ + Ω ∩ U = {x | ρ x < 0} ∩ U + +def AdmissibleDomain (Ω : Set Plane) : Prop := + Ω.Nonempty ∧ IsOpen Ω ∧ Bornology.IsBounded Ω ∧ + IsSimplyConnected Ω ∧ SmoothBoundary Ω + +def HasH1Gradient (Ω : Set Plane) (v : Plane → ℝ) (g : Plane → Plane) : Prop := + MemLp v 2 (volume.restrict Ω) ∧ MemLp g 2 (volume.restrict Ω) ∧ + ∀ φ : Plane → ℝ, ContDiff ℝ ∞ φ → HasCompactSupport φ → tsupport φ ⊆ Ω → + ∀ e : Plane, + (∫ x in Ω, v x * (fderiv ℝ φ x) e) = + -(∫ x in Ω, (inner ℝ (g x) e) * φ x) + +def rayleighValues (Ω : Set Plane) : Set ℝ := + {r | ∃ (v : Plane → ℝ) (g : Plane → Plane), + HasH1Gradient Ω v g ∧ (∫ x in Ω, v x) = 0 ∧ + 0 < (∫ x in Ω, (v x) ^ 2) ∧ + r = (∫ x in Ω, ‖g x‖ ^ 2) / (∫ x in Ω, (v x) ^ 2)} + +def firstPositiveNeumannValue (Ω : Set Plane) : ℝ := sInf (rayleighValues Ω) + +def InFirstNeumannEigenspace (Ω : Set Plane) (u : Plane → ℝ) : Prop := + ContDiffOn ℝ ∞ u (closure Ω) ∧ HasH1Gradient Ω u (gradient u) ∧ + (∫ x in Ω, u x) = 0 ∧ + ∀ (v : Plane → ℝ) (g : Plane → Plane), HasH1Gradient Ω v g → + (∫ x in Ω, inner ℝ (gradient u x) (g x)) = + firstPositiveNeumannValue Ω * (∫ x in Ω, u x * v x) + +def MainConclusion (Ω : Set Plane) (u : Plane → ℝ) : Prop := + (∀ x ∈ Ω, gradient u x ≠ 0) ∧ + ∀ x ∈ Ω, sInf (u '' frontier Ω) < u x ∧ u x < sSup (u '' frontier Ω) + +theorem main_theorem (Ω : Set Plane) (hΩ : AdmissibleDomain Ω) + (u : Plane → ℝ) (hu : InFirstNeumannEigenspace Ω u) + (hne : ∃ x ∈ Ω, u x ≠ 0) : MainConclusion Ω u := by + sorry + +end StrictHotSpots +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HotSpots.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StrictHotSpots.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hot-spots/solution/closure.txt b/tasks/hot-spots/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6dd958fb7ead2c622855324d321958f11c797c4a --- /dev/null +++ b/tasks/hot-spots/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Analysis.HotSpots.Basic +OAI.Analysis.HotSpots.BoundaryEnergy +OAI.Analysis.HotSpots.BoundaryKernel +OAI.Analysis.HotSpots.Cauchy +OAI.Analysis.HotSpots.ClosedChart +OAI.Analysis.HotSpots.ClosedSolution +OAI.Analysis.HotSpots.Conformal +OAI.Analysis.HotSpots.Dirichlet +OAI.Analysis.HotSpots.DiskKernel +OAI.Analysis.HotSpots.Douglas +OAI.Analysis.HotSpots.DouglasEnergy +OAI.Analysis.HotSpots.Eigenfunction +OAI.Analysis.HotSpots.Green +OAI.Analysis.HotSpots.GreenOperator +OAI.Analysis.HotSpots.GreenSolution +OAI.Analysis.HotSpots.Helmholtz +OAI.Analysis.HotSpots.Hodge +OAI.Analysis.HotSpots.KernelLimit +OAI.Analysis.HotSpots.Main +OAI.Analysis.HotSpots.Multiplicity +OAI.Analysis.HotSpots.Multiplier +OAI.Analysis.HotSpots.Poisson +OAI.Analysis.HotSpots.Potentials +OAI.Analysis.HotSpots.Pullback +OAI.Analysis.HotSpots.Reciprocal +OAI.Analysis.HotSpots.Riemann +OAI.Analysis.HotSpots.Sobolev +OAI.Analysis.HotSpots.Trace +OAI.Analysis.HotSpots.TraceRank +OAI.Analysis.HotSpots.Variational +OAI.Analysis.HotSpots.VectorEnergy diff --git a/tasks/hot-spots/solution/reference.py b/tasks/hot-spots/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hot-spots/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hot-spots/solution/solve.sh b/tasks/hot-spots/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d80bd789eb73a514d0dc8481ba86b259bb55259 --- /dev/null +++ b/tasks/hot-spots/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HotSpots, i.e. module OAI.Analysis.HotSpots.Main and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.HotSpots.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HotSpots" diff --git a/tasks/hot-spots/task.toml b/tasks/hot-spots/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..968ffe3c861c742ad35d5eadbf33d4cdecd1e12e --- /dev/null +++ b/tasks/hot-spots/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hot-spots" +version = "1.0.0" +description = "Prove HotSpots (openai/math family 369: The hot spots conjecture for simply connected planar domains) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HotSpots.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HotSpots" +family = "369" +family_title = "The hot spots conjecture for simply connected planar domains" +subject = "Partial differential equations" +theorems = ["OAI.StrictHotSpots.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.HotSpots.Main" +reference_modules = 31 +reference_lean_bytes = 1382075 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1437 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12943 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hot-spots/tests/Challenge.lean b/tasks/hot-spots/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e8c905519d515e23be329f1e4a544618a9d2397 --- /dev/null +++ b/tasks/hot-spots/tests/Challenge.lean @@ -0,0 +1,57 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory +open scoped ContDiff + +namespace StrictHotSpots + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def SmoothBoundary (Ω : Set Plane) : Prop := + ∀ p ∈ frontier Ω, ∃ (U : Set Plane) (ρ : Plane → ℝ), + IsOpen U ∧ p ∈ U ∧ ContDiffOn ℝ ∞ ρ U ∧ + fderiv ℝ ρ p ≠ 0 ∧ ρ p = 0 ∧ + Ω ∩ U = {x | ρ x < 0} ∩ U + +def AdmissibleDomain (Ω : Set Plane) : Prop := + Ω.Nonempty ∧ IsOpen Ω ∧ Bornology.IsBounded Ω ∧ + IsSimplyConnected Ω ∧ SmoothBoundary Ω + +def HasH1Gradient (Ω : Set Plane) (v : Plane → ℝ) (g : Plane → Plane) : Prop := + MemLp v 2 (volume.restrict Ω) ∧ MemLp g 2 (volume.restrict Ω) ∧ + ∀ φ : Plane → ℝ, ContDiff ℝ ∞ φ → HasCompactSupport φ → tsupport φ ⊆ Ω → + ∀ e : Plane, + (∫ x in Ω, v x * (fderiv ℝ φ x) e) = + -(∫ x in Ω, (inner ℝ (g x) e) * φ x) + +def rayleighValues (Ω : Set Plane) : Set ℝ := + {r | ∃ (v : Plane → ℝ) (g : Plane → Plane), + HasH1Gradient Ω v g ∧ (∫ x in Ω, v x) = 0 ∧ + 0 < (∫ x in Ω, (v x) ^ 2) ∧ + r = (∫ x in Ω, ‖g x‖ ^ 2) / (∫ x in Ω, (v x) ^ 2)} + +def firstPositiveNeumannValue (Ω : Set Plane) : ℝ := sInf (rayleighValues Ω) + +def InFirstNeumannEigenspace (Ω : Set Plane) (u : Plane → ℝ) : Prop := + ContDiffOn ℝ ∞ u (closure Ω) ∧ HasH1Gradient Ω u (gradient u) ∧ + (∫ x in Ω, u x) = 0 ∧ + ∀ (v : Plane → ℝ) (g : Plane → Plane), HasH1Gradient Ω v g → + (∫ x in Ω, inner ℝ (gradient u x) (g x)) = + firstPositiveNeumannValue Ω * (∫ x in Ω, u x * v x) + +def MainConclusion (Ω : Set Plane) (u : Plane → ℝ) : Prop := + (∀ x ∈ Ω, gradient u x ≠ 0) ∧ + ∀ x ∈ Ω, sInf (u '' frontier Ω) < u x ∧ u x < sSup (u '' frontier Ω) + +theorem main_theorem (Ω : Set Plane) (hΩ : AdmissibleDomain Ω) + (u : Plane → ℝ) (hu : InFirstNeumannEigenspace Ω u) + (hne : ∃ x ∈ Ω, u x ≠ 0) : MainConclusion Ω u := by + sorry + +end StrictHotSpots +end + +end OAI diff --git a/tasks/hot-spots/tests/grade.py b/tasks/hot-spots/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hot-spots/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hot-spots/tests/task.json b/tasks/hot-spots/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6b165e92e149b80b9308ae0596e2df0e32ba851e --- /dev/null +++ b/tasks/hot-spots/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HotSpots", + "comparator": { + "theorem_names": [ + "OAI.StrictHotSpots.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12043 +} \ No newline at end of file diff --git a/tasks/hot-spots/tests/test.sh b/tasks/hot-spots/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hot-spots/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hyperbolic-cones/environment/Dockerfile b/tasks/hyperbolic-cones/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hyperbolic-cones/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hyperbolic-cones/environment/fetch_mathlib.sh b/tasks/hyperbolic-cones/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hyperbolic-cones/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hyperbolic-cones/environment/lake-manifest.json b/tasks/hyperbolic-cones/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hyperbolic-cones/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hyperbolic-cones/environment/lakefile.lean b/tasks/hyperbolic-cones/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hyperbolic-cones/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hyperbolic-cones/environment/lean_setup.sh b/tasks/hyperbolic-cones/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hyperbolic-cones/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hyperbolic-cones/environment/pack_submission.py b/tasks/hyperbolic-cones/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hyperbolic-cones/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hyperbolic-cones/instruction.md b/tasks/hyperbolic-cones/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e7943a04fa9835662c8fbc3d82520b16308082f6 --- /dev/null +++ b/tasks/hyperbolic-cones/instruction.md @@ -0,0 +1,132 @@ +# openai/math challenge `HyperbolicCones` (family 095) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 095 of the release, *Hyperbolicity cones without semidefinite lifts* +(Convex and metric geometry). The family as a whole: Disproves the Projected Lax conjecture: some hyperbolicity cones are not spectrahedral shadows. The examples admit no exact finite affine semidefinite lift, regardless of the number of auxiliary variables or the real coefficients used. This also disproves the generalized Lax conjecture that every hyperbolicity cone is spectrahedral. + +The challenge is `HyperbolicCones`, also at `/opt/openai-math/challenges/HyperbolicCones.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Matrix.Norms.L2Operator + +universe u + +namespace Paper256 + +abbrev Mat (n : ℕ) (R : Type u) := Matrix (Fin n) (Fin n) R + +abbrev Sym (n : ℕ) := selfAdjoint (Mat n ℝ) + +instance instFiniteDimensionalSym (n : ℕ) : FiniteDimensional ℝ (Sym n) := + FiniteDimensional.finiteDimensional_submodule (selfAdjoint.submodule ℝ (Mat n ℝ)) + +abbrev Ambient := (Sym 4 × Sym 4) × (Fin 3 → ℝ) + +abbrev SymIndex := {ij : Fin 4 × Fin 4 // ij.1 ≤ ij.2} + +abbrev Coord := (SymIndex ⊕ SymIndex) ⊕ Fin 3 + +def qMatrix {R : Type u} [CommRing R] (y : Fin 3 → R) : Mat 3 R := + fun i j => if i = j then y i ^ 2 + y (i + 1) ^ 2 else -(y i * y j) + +def phi {R : Type u} [CommRing R] (y : Fin 3 → R) (X : Mat 4 R) : Mat 4 R := + fun i j => Fin.cases + (Fin.cases + (Matrix.trace (qMatrix y * X.submatrix Fin.succ Fin.succ)) + (fun j => -(∑ k, X 0 k.succ * qMatrix y k j)) j) + (fun i => Fin.cases + (-(∑ k, qMatrix y i k * X k.succ 0)) + (fun j => X 0 0 * qMatrix y i j) j) i + +def matrixValue {R : Type u} [CommRing R] + (X Z : Mat 4 R) (y : Fin 3 → R) : R := + Matrix.det ((Matrix.det X) • Z - phi y (Matrix.adjugate X)) + +def symmetricCoordinates {R : Type u} (v : SymIndex → R) : Mat 4 R := + fun i j => if h : i ≤ j then v ⟨(i, j), h⟩ + else v ⟨(j, i), le_of_lt (lt_of_not_ge h)⟩ + +def polynomial : MvPolynomial Coord ℝ := + matrixValue + (symmetricCoordinates fun ij => MvPolynomial.X (Sum.inl (Sum.inl ij))) + (symmetricCoordinates fun ij => MvPolynomial.X (Sum.inl (Sum.inr ij))) + (fun i => MvPolynomial.X (Sum.inr i)) + +def coordinates (x : Ambient) : Coord → ℝ := + Sum.elim (Sum.elim + (fun ij => (x.1.1 : Mat 4 ℝ) ij.val.1 ij.val.2) + (fun ij => (x.1.2 : Mat 4 ℝ) ij.val.1 ij.val.2)) x.2 + +def basePoint : Ambient := ((1, 1), 0) + +def linePolynomial (x : Ambient) : Polynomial ℝ := + MvPolynomial.eval₂ Polynomial.C + (fun i => Polynomial.C (coordinates basePoint i) * Polynomial.X - + Polynomial.C (coordinates x i)) polynomial + +def cone : Set Ambient := + {x | ∀ t : ℂ, (linePolynomial x).aeval t = 0 → t.im = 0 ∧ 0 ≤ t.re} + +theorem main_result : + Module.finrank ℝ Ambient = 23 ∧ + polynomial.IsHomogeneous 20 ∧ + polynomial.totalDegree = 20 ∧ + MvPolynomial.eval (coordinates basePoint) polynomial = 1 ∧ + (∀ (x : Ambient) (z : ℂ), (linePolynomial x).aeval z = 0 → z.im = 0) ∧ + ∀ (N : ℕ) (_hN : 0 < N) (L : Ambient →ₗ[ℝ] Sym N), + cone ≠ {x | (L x : Mat N ℝ).PosSemidef} := by + sorry + +end Paper256 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HyperbolicCones.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Paper256.main_result` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hyperbolic-cones/solution/closure.txt b/tasks/hyperbolic-cones/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1d1c1718cb3181228de328c158774ca0b231fdc8 --- /dev/null +++ b/tasks/hyperbolic-cones/solution/closure.txt @@ -0,0 +1,86 @@ +OAI.Analysis.HyperbolicCones.BlockNormalization +OAI.Analysis.HyperbolicCones.BlockReduction +OAI.Analysis.HyperbolicCones.BlockScaling +OAI.Analysis.HyperbolicCones.ComplexPositive +OAI.Analysis.HyperbolicCones.CompressionBasic +OAI.Analysis.HyperbolicCones.ConeContinuity +OAI.Analysis.HyperbolicCones.ConeInterior +OAI.Analysis.HyperbolicCones.ConeMatrix +OAI.Analysis.HyperbolicCones.ConePositive +OAI.Analysis.HyperbolicCones.ConeRoots +OAI.Analysis.HyperbolicCones.ConeZero +OAI.Analysis.HyperbolicCones.CongruenceMaps +OAI.Analysis.HyperbolicCones.Coordinates +OAI.Analysis.HyperbolicCones.Deformation +OAI.Analysis.HyperbolicCones.DeformationBasic +OAI.Analysis.HyperbolicCones.DeformationCone +OAI.Analysis.HyperbolicCones.DeformationFamily +OAI.Analysis.HyperbolicCones.DeformationRoots +OAI.Analysis.HyperbolicCones.FiniteTopology +OAI.Analysis.HyperbolicCones.FormBasic +OAI.Analysis.HyperbolicCones.FormPositive +OAI.Analysis.HyperbolicCones.FormRigidity +OAI.Analysis.HyperbolicCones.GramProjection +OAI.Analysis.HyperbolicCones.Hyperbolicity +OAI.Analysis.HyperbolicCones.InverseOrder +OAI.Analysis.HyperbolicCones.KernelLimit +OAI.Analysis.HyperbolicCones.KernelLocal +OAI.Analysis.HyperbolicCones.KernelSmooth +OAI.Analysis.HyperbolicCones.KernelSpectrum +OAI.Analysis.HyperbolicCones.KernelTangent +OAI.Analysis.HyperbolicCones.LineEvaluation +OAI.Analysis.HyperbolicCones.LinePolynomial +OAI.Analysis.HyperbolicCones.LineShift +OAI.Analysis.HyperbolicCones.Main +OAI.Analysis.HyperbolicCones.MatrixBasic +OAI.Analysis.HyperbolicCones.MatrixComplex +OAI.Analysis.HyperbolicCones.MatrixLinear +OAI.Analysis.HyperbolicCones.MatrixPositive +OAI.Analysis.HyperbolicCones.MatrixResolvent +OAI.Analysis.HyperbolicCones.MaxEigenvalue +OAI.Analysis.HyperbolicCones.Model +OAI.Analysis.HyperbolicCones.NormCongruence +OAI.Analysis.HyperbolicCones.NormIdentity +OAI.Analysis.HyperbolicCones.NormLimits +OAI.Analysis.HyperbolicCones.NormThreshold +OAI.Analysis.HyperbolicCones.OperatorEntries +OAI.Analysis.HyperbolicCones.Pencil +OAI.Analysis.HyperbolicCones.PencilBlocks +OAI.Analysis.HyperbolicCones.PencilCompression +OAI.Analysis.HyperbolicCones.PencilConjugation +OAI.Analysis.HyperbolicCones.PencilKernel +OAI.Analysis.HyperbolicCones.PencilLimit +OAI.Analysis.HyperbolicCones.PencilOrder +OAI.Analysis.HyperbolicCones.PencilRecovery +OAI.Analysis.HyperbolicCones.PencilRegularization +OAI.Analysis.HyperbolicCones.PencilRepresentation +OAI.Analysis.HyperbolicCones.PencilSplit +OAI.Analysis.HyperbolicCones.PencilTopology +OAI.Analysis.HyperbolicCones.PolynomialBasic +OAI.Analysis.HyperbolicCones.PolynomialEvaluation +OAI.Analysis.HyperbolicCones.PolynomialHomogeneous +OAI.Analysis.HyperbolicCones.PolynomialScaling +OAI.Analysis.HyperbolicCones.PositiveCore +OAI.Analysis.HyperbolicCones.PositiveMaps +OAI.Analysis.HyperbolicCones.PositivePath +OAI.Analysis.HyperbolicCones.QuadraticDeformation +OAI.Analysis.HyperbolicCones.RankNorm +OAI.Analysis.HyperbolicCones.RawBlocks +OAI.Analysis.HyperbolicCones.RescalingBasic +OAI.Analysis.HyperbolicCones.ResidualBound +OAI.Analysis.HyperbolicCones.ResidualOrder +OAI.Analysis.HyperbolicCones.ScalingAlgebra +OAI.Analysis.HyperbolicCones.ShiftValue +OAI.Analysis.HyperbolicCones.SpectralBounds +OAI.Analysis.HyperbolicCones.SpectralContinuity +OAI.Analysis.HyperbolicCones.SpectralProjection +OAI.Analysis.HyperbolicCones.SplitAssembly +OAI.Analysis.HyperbolicCones.SplitBasic +OAI.Analysis.HyperbolicCones.SplitFrame +OAI.Analysis.HyperbolicCones.StrictBlock +OAI.Analysis.HyperbolicCones.TangentBasic +OAI.Analysis.HyperbolicCones.TangentIdentity +OAI.Analysis.HyperbolicCones.TangentLimit +OAI.Analysis.HyperbolicCones.TangentObstruction +OAI.Analysis.HyperbolicCones.TangentRigidity +OAI.Analysis.HyperbolicCones.ZeroPolynomial diff --git a/tasks/hyperbolic-cones/solution/reference.py b/tasks/hyperbolic-cones/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hyperbolic-cones/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hyperbolic-cones/solution/solve.sh b/tasks/hyperbolic-cones/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a64e155490c6ba626144676e95f9eb77fdbbee09 --- /dev/null +++ b/tasks/hyperbolic-cones/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HyperbolicCones, i.e. module OAI.Analysis.HyperbolicCones.Main and the +# 86 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.HyperbolicCones.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HyperbolicCones" diff --git a/tasks/hyperbolic-cones/task.toml b/tasks/hyperbolic-cones/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49e6d49107818a9c9c59db0a75bc95adca2f70a6 --- /dev/null +++ b/tasks/hyperbolic-cones/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hyperbolic-cones" +version = "1.0.0" +description = "Prove HyperbolicCones (openai/math family 095: Hyperbolicity cones without semidefinite lifts) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HyperbolicCones.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HyperbolicCones" +family = "095" +family_title = "Hyperbolicity cones without semidefinite lifts" +subject = "Convex and metric geometry" +theorems = ["OAI.Paper256.main_result"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.HyperbolicCones.Main" +reference_modules = 86 +reference_lean_bytes = 217979 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 849 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11896 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hyperbolic-cones/tests/Challenge.lean b/tasks/hyperbolic-cones/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dc28ca17123c4692c941ada8ca4366e47b2a032 --- /dev/null +++ b/tasks/hyperbolic-cones/tests/Challenge.lean @@ -0,0 +1,81 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Matrix.Norms.L2Operator + +universe u + +namespace Paper256 + +abbrev Mat (n : ℕ) (R : Type u) := Matrix (Fin n) (Fin n) R + +abbrev Sym (n : ℕ) := selfAdjoint (Mat n ℝ) + +instance instFiniteDimensionalSym (n : ℕ) : FiniteDimensional ℝ (Sym n) := + FiniteDimensional.finiteDimensional_submodule (selfAdjoint.submodule ℝ (Mat n ℝ)) + +abbrev Ambient := (Sym 4 × Sym 4) × (Fin 3 → ℝ) + +abbrev SymIndex := {ij : Fin 4 × Fin 4 // ij.1 ≤ ij.2} + +abbrev Coord := (SymIndex ⊕ SymIndex) ⊕ Fin 3 + +def qMatrix {R : Type u} [CommRing R] (y : Fin 3 → R) : Mat 3 R := + fun i j => if i = j then y i ^ 2 + y (i + 1) ^ 2 else -(y i * y j) + +def phi {R : Type u} [CommRing R] (y : Fin 3 → R) (X : Mat 4 R) : Mat 4 R := + fun i j => Fin.cases + (Fin.cases + (Matrix.trace (qMatrix y * X.submatrix Fin.succ Fin.succ)) + (fun j => -(∑ k, X 0 k.succ * qMatrix y k j)) j) + (fun i => Fin.cases + (-(∑ k, qMatrix y i k * X k.succ 0)) + (fun j => X 0 0 * qMatrix y i j) j) i + +def matrixValue {R : Type u} [CommRing R] + (X Z : Mat 4 R) (y : Fin 3 → R) : R := + Matrix.det ((Matrix.det X) • Z - phi y (Matrix.adjugate X)) + +def symmetricCoordinates {R : Type u} (v : SymIndex → R) : Mat 4 R := + fun i j => if h : i ≤ j then v ⟨(i, j), h⟩ + else v ⟨(j, i), le_of_lt (lt_of_not_ge h)⟩ + +def polynomial : MvPolynomial Coord ℝ := + matrixValue + (symmetricCoordinates fun ij => MvPolynomial.X (Sum.inl (Sum.inl ij))) + (symmetricCoordinates fun ij => MvPolynomial.X (Sum.inl (Sum.inr ij))) + (fun i => MvPolynomial.X (Sum.inr i)) + +def coordinates (x : Ambient) : Coord → ℝ := + Sum.elim (Sum.elim + (fun ij => (x.1.1 : Mat 4 ℝ) ij.val.1 ij.val.2) + (fun ij => (x.1.2 : Mat 4 ℝ) ij.val.1 ij.val.2)) x.2 + +def basePoint : Ambient := ((1, 1), 0) + +def linePolynomial (x : Ambient) : Polynomial ℝ := + MvPolynomial.eval₂ Polynomial.C + (fun i => Polynomial.C (coordinates basePoint i) * Polynomial.X - + Polynomial.C (coordinates x i)) polynomial + +def cone : Set Ambient := + {x | ∀ t : ℂ, (linePolynomial x).aeval t = 0 → t.im = 0 ∧ 0 ≤ t.re} + +theorem main_result : + Module.finrank ℝ Ambient = 23 ∧ + polynomial.IsHomogeneous 20 ∧ + polynomial.totalDegree = 20 ∧ + MvPolynomial.eval (coordinates basePoint) polynomial = 1 ∧ + (∀ (x : Ambient) (z : ℂ), (linePolynomial x).aeval z = 0 → z.im = 0) ∧ + ∀ (N : ℕ) (_hN : 0 < N) (L : Ambient →ₗ[ℝ] Sym N), + cone ≠ {x | (L x : Mat N ℝ).PosSemidef} := by + sorry + +end Paper256 + +end + +end OAI diff --git a/tasks/hyperbolic-cones/tests/grade.py b/tasks/hyperbolic-cones/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hyperbolic-cones/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hyperbolic-cones/tests/task.json b/tasks/hyperbolic-cones/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d60d89d2bf4fcf3ddeb7b4cfbab41e0ebc459eb3 --- /dev/null +++ b/tasks/hyperbolic-cones/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HyperbolicCones", + "comparator": { + "theorem_names": [ + "OAI.Paper256.main_result" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10996 +} \ No newline at end of file diff --git a/tasks/hyperbolic-cones/tests/test.sh b/tasks/hyperbolic-cones/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hyperbolic-cones/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hyperbolic-obstruction/environment/Dockerfile b/tasks/hyperbolic-obstruction/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hyperbolic-obstruction/environment/fetch_mathlib.sh b/tasks/hyperbolic-obstruction/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hyperbolic-obstruction/environment/lake-manifest.json b/tasks/hyperbolic-obstruction/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hyperbolic-obstruction/environment/lakefile.lean b/tasks/hyperbolic-obstruction/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hyperbolic-obstruction/environment/lean_setup.sh b/tasks/hyperbolic-obstruction/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hyperbolic-obstruction/environment/pack_submission.py b/tasks/hyperbolic-obstruction/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hyperbolic-obstruction/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hyperbolic-obstruction/instruction.md b/tasks/hyperbolic-obstruction/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b88c6c048e329d1b3c63a7ec40776bb4e28448fc --- /dev/null +++ b/tasks/hyperbolic-obstruction/instruction.md @@ -0,0 +1,214 @@ +# openai/math challenge `HyperbolicObstruction` (family 257) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 257 of the release, *A hyperbolic group with no geometric CAT(0) action* +(Group theory). The family as a whole: Answers negatively whether every word-hyperbolic group is a CAT(0) group. Constructs one with a finite classifying space but no proper cocompact isometric action on any proper complete $\operatorname{CAT}(0)$ space, in any dimension. + +The challenge is `HyperbolicObstruction`, also at `/opt/openai-math/challenges/HyperbolicObstruction.lean`: + +```lean +import Mathlib + +namespace OAI + + + +section + +section + +/-! +Finite complexes are standard barycentric realizations of finite abstract +simplicial complexes. Area-counted elementary edge homotopies encode the +usual triangular disk diagrams, allowing spurs and collapsed edges. Null edge +loops (equivalently closed lifts to the universal cover) are those admitting +such a disk, without any area bound. Asphericity is vanishing of all higher +homotopy groups of this finite polyhedron. The CAT conditions use the standard +squared-distance / hyperbolic-cosh comparison formulations. +-/ + +noncomputable section +open scoped Topology ContinuousMap + +namespace HyperbolicObstruction + +structure FiniteComplex where + n : ℕ + complex : AbstractSimplicialComplex (Fin n) + +namespace FiniteComplex + +abbrev Vertex (K : FiniteComplex) := Fin K.n + +def Carrier (K : FiniteComplex) := + {x : K.Vertex → ℝ // (∀ i, 0 ≤ x i) ∧ (∑ i, x i) = 1 ∧ + ∃ s ∈ K.complex.faces, ∀ i, i ∉ s → x i = 0} + +instance (K : FiniteComplex) : TopologicalSpace K.Carrier := + inferInstanceAs (TopologicalSpace (Subtype _)) + +def Edge (K : FiniteComplex) (a b : K.Vertex) : Prop := + {a, b} ∈ K.complex.faces + +def EdgePath (K : FiniteComplex) : List K.Vertex → Prop + | [] => False + | [_] => True + | a :: b :: t => K.Edge a b ∧ K.EdgePath (b :: t) + +def Closed (K : FiniteComplex) (p : List K.Vertex) : Prop := + ∃ a t, p = a :: (t ++ [a]) ∨ p = [a] + +/-- An elementary disk move. A noncollapsed triangular face costs one; + a spur or a collapsed edge costs zero. Contexts are unchanged. -/ +inductive DiskMove (K : FiniteComplex) : List K.Vertex → List K.Vertex → ℕ → Prop + | stutter (l r) (a) : + DiskMove K (l ++ [a, a] ++ r) (l ++ [a] ++ r) 0 + | spur (l r) (a b) (h : K.Edge a b) : + DiskMove K (l ++ [a, b, a] ++ r) (l ++ [a] ++ r) 0 + | triangle (l r) (a b c) (h : {a, b, c} ∈ K.complex.faces) + (hne : ({a, b, c} : Finset K.Vertex).card = 3) : + DiskMove K (l ++ [a, b, c] ++ r) (l ++ [a, c] ++ r) 1 + +/-- A disk certificate obtained by elementary triangle attachments/removals, + with spurs/collapses allowed. The index is the number of triangular faces. -/ +inductive DiskHomotopy (K : FiniteComplex) : List K.Vertex → List K.Vertex → ℕ → Prop + | refl (p) : DiskHomotopy K p p 0 + | move {p q n} : DiskMove K p q n → DiskHomotopy K p q n + | symm {p q n} : DiskHomotopy K p q n → DiskHomotopy K q p n + | trans {p q r m n} : DiskHomotopy K p q m → DiskHomotopy K q r n → + DiskHomotopy K p r (m + n) + +def Disk (K : FiniteComplex) (p : List K.Vertex) (faces : ℕ) : Prop := + ∃ a, K.DiskHomotopy p [a] faces + +def LinearDiskFilling (K : FiniteComplex) (C : ℝ) : Prop := + ∀ p, K.EdgePath p → K.Closed p → (∃ a, K.Disk p a) → + ∃ a, K.Disk p a ∧ (a : ℝ) ≤ C * (p.length - 1 : ℕ) + +def Aspherical (K : FiniteComplex) (x : K.Carrier) : Prop := + ∀ n : ℕ, Subsingleton (HomotopyGroup.Pi (n + 2) K.Carrier x) + +end FiniteComplex + +/-- A constant-speed metric segment, parametrized on [0,1]. -/ +def IsSegment {X : Type*} [MetricSpace X] (γ : ℝ → X) (x y : X) : Prop := + γ 0 = x ∧ γ 1 = y ∧ + ∀ s ∈ Set.Icc (0 : ℝ) 1, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist (γ s) (γ t) = |s - t| * dist x y + +def IsGeodesic (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y + +/-- The CN characterization of CAT(0), with whole metric segments. -/ +def CATZero (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y ∧ + ∀ z : X, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist z (γ t) ^ 2 ≤ (1 - t) * dist z x ^ 2 + t * dist z y ^ 2 - + t * (1 - t) * dist x y ^ 2 + +/-- The hyperbolic-cosh midpoint characterization of CAT(-1). -/ +def CATNegOne (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y ∧ + ∀ z : X, Real.cosh (dist z (γ (1 / 2))) ≤ + (Real.cosh (dist z x) + Real.cosh (dist z y)) / + (2 * Real.cosh (dist x y / 2)) + +/-- A proper, cocompact isometric action of a discrete group. -/ +structure GeometricAction (G X : Type*) [Group G] [MetricSpace X] where + act : G →* (X ≃ᵢ X) + proper : ∀ C : Set X, IsCompact C → + {g : G | ∃ x ∈ C, act g x ∈ C}.Finite + cocompact : ∃ C : Set X, IsCompact C ∧ ∀ x : X, ∃ g : G, ∃ y ∈ C, act g y = x + +universe u + +def NoGeometricCATZeroAction (G : Type*) [Group G] : Prop := + ∀ (X : Type u) (_ : MetricSpace X), Nonempty X → ProperSpace X → CompleteSpace X → + CATZero X → IsEmpty (GeometricAction G X) + +def WordLength {G : Type*} [Group G] (S : Finset G) (g : G) : ℕ := + sInf {n | ∃ w : List G, w.length = n ∧ + (∀ a ∈ w, a ∈ S ∨ a⁻¹ ∈ S) ∧ w.prod = g} + +def WordDistance {G : Type*} [Group G] (S : Finset G) (g h : G) : ℝ := + WordLength S (g⁻¹ * h) + +/-- Four-point word hyperbolicity, for some finite generating set. -/ +def WordHyperbolic (G : Type*) [Group G] : Prop := + ∃ S : Finset G, Subgroup.closure (S : Set G) = ⊤ ∧ + ∃ δ : ℝ, 0 ≤ δ ∧ ∀ a b c d : G, + WordDistance S a c + WordDistance S b d ≤ + max (WordDistance S a b + WordDistance S c d) + (WordDistance S a d + WordDistance S b c) + 2 * δ + +/-- A metric on the given finite polyhedron, not on a different topology. -/ +def CompatibleLocallyCATNegOne (K : FiniteComplex) : Prop := + ∃ m : MetricSpace K.Carrier, + m.toUniformSpace.toTopologicalSpace = (inferInstance : TopologicalSpace K.Carrier) ∧ + (letI := m + IsGeodesic K.Carrier ∧ ∀ x : K.Carrier, ∃ r : ℝ, 0 < r ∧ + CATNegOne (Metric.ball x r)) + +/-- A finite aspherical complex with hyperbolic fundamental group, no geometric CAT(0) +action, and no homotopy equivalent finite complex admitting a locally CAT(-1) metric. -/ +def MainStatement : Prop := + ∃ K : FiniteComplex, ∃ x : K.Carrier, ∃ C : ℝ, + ConnectedSpace K.Carrier ∧ K.Aspherical x ∧ 0 ≤ C ∧ K.LinearDiskFilling C ∧ + NoGeometricCATZeroAction.{u} (FundamentalGroup K.Carrier x) ∧ + WordHyperbolic (FundamentalGroup K.Carrier x) ∧ + ∀ L : FiniteComplex, Nonempty (K.Carrier ≃ₕ L.Carrier) → + ¬ CompatibleLocallyCATNegOne L + + +theorem main : MainStatement.{u} := by sorry + +end HyperbolicObstruction + + +end +end +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HyperbolicObstruction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.HyperbolicObstruction.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hyperbolic-obstruction/solution/closure.txt b/tasks/hyperbolic-obstruction/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9b72cd8bf14e6c3188ec9744249ee009cd68743d --- /dev/null +++ b/tasks/hyperbolic-obstruction/solution/closure.txt @@ -0,0 +1,417 @@ +OAI.Geometry.HyperbolicGroups.ActualContact +OAI.Geometry.HyperbolicGroups.ActualDegree +OAI.Geometry.HyperbolicGroups.ActualFaceCounts +OAI.Geometry.HyperbolicGroups.ActualFragment +OAI.Geometry.HyperbolicGroups.ActualLabel +OAI.Geometry.HyperbolicGroups.ActualLayers +OAI.Geometry.HyperbolicGroups.ActualLiftedChain +OAI.Geometry.HyperbolicGroups.ActualOccurrenceShape +OAI.Geometry.HyperbolicGroups.ActualPartition +OAI.Geometry.HyperbolicGroups.ActualPosition +OAI.Geometry.HyperbolicGroups.ActualRawAccount +OAI.Geometry.HyperbolicGroups.ActualRawCount +OAI.Geometry.HyperbolicGroups.ActualWeights +OAI.Geometry.HyperbolicGroups.AnnularSeparator +OAI.Geometry.HyperbolicGroups.BFSLevels +OAI.Geometry.HyperbolicGroups.BFSTree +OAI.Geometry.HyperbolicGroups.BalancedGrouping +OAI.Geometry.HyperbolicGroups.BasedSquareContraction +OAI.Geometry.HyperbolicGroups.BasedTriangleContraction +OAI.Geometry.HyperbolicGroups.Basic +OAI.Geometry.HyperbolicGroups.BigonRemove +OAI.Geometry.HyperbolicGroups.BoundaryEnumeration +OAI.Geometry.HyperbolicGroups.BoundaryEraseList +OAI.Geometry.HyperbolicGroups.BoundaryFold +OAI.Geometry.HyperbolicGroups.BoundaryGraphWalk +OAI.Geometry.HyperbolicGroups.BoundaryIndex +OAI.Geometry.HyperbolicGroups.BoundaryLift +OAI.Geometry.HyperbolicGroups.BoundaryList +OAI.Geometry.HyperbolicGroups.BoundaryRotation +OAI.Geometry.HyperbolicGroups.BoundarySplice +OAI.Geometry.HyperbolicGroups.Budget +OAI.Geometry.HyperbolicGroups.CATZero +OAI.Geometry.HyperbolicGroups.CATZeroFurther +OAI.Geometry.HyperbolicGroups.Candidate +OAI.Geometry.HyperbolicGroups.CellularFilling +OAI.Geometry.HyperbolicGroups.Chernoff +OAI.Geometry.HyperbolicGroups.ClosedCoverGluing +OAI.Geometry.HyperbolicGroups.Coincidence +OAI.Geometry.HyperbolicGroups.ColoredApex +OAI.Geometry.HyperbolicGroups.CompactLocalCATGeometric +OAI.Geometry.HyperbolicGroups.Concentration +OAI.Geometry.HyperbolicGroups.ConditionalStar +OAI.Geometry.HyperbolicGroups.Conditioning +OAI.Geometry.HyperbolicGroups.ConeApexProducer +OAI.Geometry.HyperbolicGroups.ConeCellCollapse +OAI.Geometry.HyperbolicGroups.ConeCellTarget +OAI.Geometry.HyperbolicGroups.ConeCellWalk +OAI.Geometry.HyperbolicGroups.ConeCover +OAI.Geometry.HyperbolicGroups.ConeData +OAI.Geometry.HyperbolicGroups.ConeDecorationGroup +OAI.Geometry.HyperbolicGroups.ConeDiskNormal +OAI.Geometry.HyperbolicGroups.ConeExteriorWalk +OAI.Geometry.HyperbolicGroups.ConeFanCorner +OAI.Geometry.HyperbolicGroups.ConeFanGroup +OAI.Geometry.HyperbolicGroups.ConeFrozenTarget +OAI.Geometry.HyperbolicGroups.ConeFullNormal +OAI.Geometry.HyperbolicGroups.ConeGraph +OAI.Geometry.HyperbolicGroups.ConeLetterCollapse +OAI.Geometry.HyperbolicGroups.ConeMappedWalk +OAI.Geometry.HyperbolicGroups.ConePresentationGroup +OAI.Geometry.HyperbolicGroups.ConeSkeleton +OAI.Geometry.HyperbolicGroups.ConeTopCollapse +OAI.Geometry.HyperbolicGroups.ConeTopGroup +OAI.Geometry.HyperbolicGroups.ConeWalkTarget +OAI.Geometry.HyperbolicGroups.ConnectedLevels +OAI.Geometry.HyperbolicGroups.ContactCapacity +OAI.Geometry.HyperbolicGroups.CoreFan +OAI.Geometry.HyperbolicGroups.CoreWordGraph +OAI.Geometry.HyperbolicGroups.Cost +OAI.Geometry.HyperbolicGroups.CouplingError +OAI.Geometry.HyperbolicGroups.CoverBoundary +OAI.Geometry.HyperbolicGroups.CubicalHomotopyExtension +OAI.Geometry.HyperbolicGroups.CycleCount +OAI.Geometry.HyperbolicGroups.CycleDecomposition +OAI.Geometry.HyperbolicGroups.CyclicLink +OAI.Geometry.HyperbolicGroups.CyclicTriangleBoundary +OAI.Geometry.HyperbolicGroups.CyclicTriangleCochains +OAI.Geometry.HyperbolicGroups.DevelopmentCATZero +OAI.Geometry.HyperbolicGroups.DevelopmentDeck +OAI.Geometry.HyperbolicGroups.DevelopmentGeodesic +OAI.Geometry.HyperbolicGroups.DevelopmentGeometricAction +OAI.Geometry.HyperbolicGroups.DevelopmentProper +OAI.Geometry.HyperbolicGroups.DevelopmentRadial +OAI.Geometry.HyperbolicGroups.Deviation +OAI.Geometry.HyperbolicGroups.DiagonalSampling +OAI.Geometry.HyperbolicGroups.DiagramSampling +OAI.Geometry.HyperbolicGroups.DipoleChain +OAI.Geometry.HyperbolicGroups.DipoleRemove +OAI.Geometry.HyperbolicGroups.DipoleStepChain +OAI.Geometry.HyperbolicGroups.DipoleSwitch +OAI.Geometry.HyperbolicGroups.Distinct +OAI.Geometry.HyperbolicGroups.EdgeChain +OAI.Geometry.HyperbolicGroups.EdgeContraction +OAI.Geometry.HyperbolicGroups.EdgeCoordinates +OAI.Geometry.HyperbolicGroups.EdgeErase +OAI.Geometry.HyperbolicGroups.EdgeEraseBoundary +OAI.Geometry.HyperbolicGroups.EdgeEraseComponents +OAI.Geometry.HyperbolicGroups.EdgeEraseCount +OAI.Geometry.HyperbolicGroups.EdgeEraseGenus +OAI.Geometry.HyperbolicGroups.EdgeMerge +OAI.Geometry.HyperbolicGroups.EdgeMergeComponents +OAI.Geometry.HyperbolicGroups.ElementaryCone +OAI.Geometry.HyperbolicGroups.ElementaryCover +OAI.Geometry.HyperbolicGroups.Exceptional +OAI.Geometry.HyperbolicGroups.ExtensionConditioning +OAI.Geometry.HyperbolicGroups.ExtensionMargin +OAI.Geometry.HyperbolicGroups.ExteriorTarget +OAI.Geometry.HyperbolicGroups.FaceChainSelection +OAI.Geometry.HyperbolicGroups.FaceSplice +OAI.Geometry.HyperbolicGroups.FaceSplit +OAI.Geometry.HyperbolicGroups.FaceWalk +OAI.Geometry.HyperbolicGroups.FanActivation +OAI.Geometry.HyperbolicGroups.FanApex +OAI.Geometry.HyperbolicGroups.FanRoute +OAI.Geometry.HyperbolicGroups.FiberLaw +OAI.Geometry.HyperbolicGroups.FiniteFanData +OAI.Geometry.HyperbolicGroups.FiniteFlatFacets +OAI.Geometry.HyperbolicGroups.FiniteLaw +OAI.Geometry.HyperbolicGroups.FiniteMassTransfer +OAI.Geometry.HyperbolicGroups.FinitePolygonModel +OAI.Geometry.HyperbolicGroups.FinitePolygonVoltage +OAI.Geometry.HyperbolicGroups.FinitePolyhedron +OAI.Geometry.HyperbolicGroups.FinitePolyhedronDeck +OAI.Geometry.HyperbolicGroups.FinitePolyhedronEdgePaths +OAI.Geometry.HyperbolicGroups.FinitePolyhedronLocal +OAI.Geometry.HyperbolicGroups.FinitePolyhedronMonodromy +OAI.Geometry.HyperbolicGroups.FinitePolyhedronPathAlgebra +OAI.Geometry.HyperbolicGroups.FinitePolyhedronPaths +OAI.Geometry.HyperbolicGroups.FinitePolyhedronVoltage +OAI.Geometry.HyperbolicGroups.FiniteSampling +OAI.Geometry.HyperbolicGroups.FiniteSelection +OAI.Geometry.HyperbolicGroups.Fragment +OAI.Geometry.HyperbolicGroups.FragmentSlots +OAI.Geometry.HyperbolicGroups.FrozenCancel +OAI.Geometry.HyperbolicGroups.FrozenFaceSide +OAI.Geometry.HyperbolicGroups.FrozenPrevious +OAI.Geometry.HyperbolicGroups.FrozenSideExists +OAI.Geometry.HyperbolicGroups.FrozenWalk +OAI.Geometry.HyperbolicGroups.FullWalkNormal +OAI.Geometry.HyperbolicGroups.GeneralSwitch +OAI.Geometry.HyperbolicGroups.GenericMoment +OAI.Geometry.HyperbolicGroups.GenericTable +OAI.Geometry.HyperbolicGroups.GeometricAction +OAI.Geometry.HyperbolicGroups.GeometricSpaceTransport +OAI.Geometry.HyperbolicGroups.GlobalClosedPicture +OAI.Geometry.HyperbolicGroups.Graph +OAI.Geometry.HyperbolicGroups.GraphAction +OAI.Geometry.HyperbolicGroups.GraphGroupWalk +OAI.Geometry.HyperbolicGroups.GraphLimit +OAI.Geometry.HyperbolicGroups.GraphSeparatorTransfer +OAI.Geometry.HyperbolicGroups.GraphSquares +OAI.Geometry.HyperbolicGroups.GraphSubpairing +OAI.Geometry.HyperbolicGroups.GraphSubstitution +OAI.Geometry.HyperbolicGroups.GraphWordFilling +OAI.Geometry.HyperbolicGroups.HSpaceFundamental +OAI.Geometry.HyperbolicGroups.HSpacePathObstruction +OAI.Geometry.HyperbolicGroups.IncidenceTemplate +OAI.Geometry.HyperbolicGroups.IndexedBoundaryPullback +OAI.Geometry.HyperbolicGroups.IndexedDiskUniqueness +OAI.Geometry.HyperbolicGroups.IndexedFace +OAI.Geometry.HyperbolicGroups.IndexedFanCards +OAI.Geometry.HyperbolicGroups.IndexedFanCounts +OAI.Geometry.HyperbolicGroups.IndexedFillingValue +OAI.Geometry.HyperbolicGroups.IndexedPayment +OAI.Geometry.HyperbolicGroups.IndexedPictureAppend +OAI.Geometry.HyperbolicGroups.IndexedPictureBasic +OAI.Geometry.HyperbolicGroups.IndexedPictureClosed +OAI.Geometry.HyperbolicGroups.IndexedPictureExistence +OAI.Geometry.HyperbolicGroups.IndexedPictureFold +OAI.Geometry.HyperbolicGroups.IndexedPictureReduction +OAI.Geometry.HyperbolicGroups.IndexedWordPicture +OAI.Geometry.HyperbolicGroups.IntegralCellularBoundary +OAI.Geometry.HyperbolicGroups.InvolutionPairs +OAI.Geometry.HyperbolicGroups.LeafFiber +OAI.Geometry.HyperbolicGroups.LeafMargin +OAI.Geometry.HyperbolicGroups.LetterCover +OAI.Geometry.HyperbolicGroups.LetterNormalPicture +OAI.Geometry.HyperbolicGroups.LiftedBasis +OAI.Geometry.HyperbolicGroups.LiftedClosedPicture +OAI.Geometry.HyperbolicGroups.LiftedDiagramSampling +OAI.Geometry.HyperbolicGroups.LinkApex +OAI.Geometry.HyperbolicGroups.LocalGeodesic +OAI.Geometry.HyperbolicGroups.LocalGeodesicContraction +OAI.Geometry.HyperbolicGroups.LocalGeodesicCover +OAI.Geometry.HyperbolicGroups.LocalGeodesicDistance +OAI.Geometry.HyperbolicGroups.LocalGeodesicLength +OAI.Geometry.HyperbolicGroups.LocalGeodesicRebase +OAI.Geometry.HyperbolicGroups.LocalGeodesicTopology +OAI.Geometry.HyperbolicGroups.LocalSegmentContinuation +OAI.Geometry.HyperbolicGroups.LocalSegmentTools +OAI.Geometry.HyperbolicGroups.LocalWeightedRank +OAI.Geometry.HyperbolicGroups.LoopSpaceReversal +OAI.Geometry.HyperbolicGroups.MacroCertificate +OAI.Geometry.HyperbolicGroups.MacroCycle +OAI.Geometry.HyperbolicGroups.MacroExceptional +OAI.Geometry.HyperbolicGroups.MacroFaceFilling +OAI.Geometry.HyperbolicGroups.MacroGroup +OAI.Geometry.HyperbolicGroups.MacroRadialIndex +OAI.Geometry.HyperbolicGroups.MacroWalk +OAI.Geometry.HyperbolicGroups.Main +OAI.Geometry.HyperbolicGroups.MappedCancellation +OAI.Geometry.HyperbolicGroups.MappedPicture +OAI.Geometry.HyperbolicGroups.MergeWalk +OAI.Geometry.HyperbolicGroups.MetricHexagon +OAI.Geometry.HyperbolicGroups.MetricProduct +OAI.Geometry.HyperbolicGroups.Moment +OAI.Geometry.HyperbolicGroups.NormalCell +OAI.Geometry.HyperbolicGroups.NormalDiskArea +OAI.Geometry.HyperbolicGroups.NormalFaceFilling +OAI.Geometry.HyperbolicGroups.Normalization +OAI.Geometry.HyperbolicGroups.Occurrence +OAI.Geometry.HyperbolicGroups.OneFaceFilling +OAI.Geometry.HyperbolicGroups.OrbitLimit +OAI.Geometry.HyperbolicGroups.OriginalLinearFilling +OAI.Geometry.HyperbolicGroups.OutsideComponentFilling +OAI.Geometry.HyperbolicGroups.PairingForest +OAI.Geometry.HyperbolicGroups.PairingTreeCotree +OAI.Geometry.HyperbolicGroups.ParameterizedSquareFilling +OAI.Geometry.HyperbolicGroups.PathHomotopyTopology +OAI.Geometry.HyperbolicGroups.PathInSet +OAI.Geometry.HyperbolicGroups.PathLocalToGlobal +OAI.Geometry.HyperbolicGroups.PermErase +OAI.Geometry.HyperbolicGroups.PermErasePair +OAI.Geometry.HyperbolicGroups.PermEuler +OAI.Geometry.HyperbolicGroups.PermSwitch +OAI.Geometry.HyperbolicGroups.PictureBFSSeparator +OAI.Geometry.HyperbolicGroups.PictureBoundaryHull +OAI.Geometry.HyperbolicGroups.PictureBoundaryParity +OAI.Geometry.HyperbolicGroups.PictureComponentGraph +OAI.Geometry.HyperbolicGroups.PictureContact +OAI.Geometry.HyperbolicGroups.PictureCotreeColor +OAI.Geometry.HyperbolicGroups.PictureCotreeTree +OAI.Geometry.HyperbolicGroups.PictureDual +OAI.Geometry.HyperbolicGroups.PictureEuler +OAI.Geometry.HyperbolicGroups.PictureFaceCorners +OAI.Geometry.HyperbolicGroups.PictureFillingAlgebra +OAI.Geometry.HyperbolicGroups.PictureFullSeparator +OAI.Geometry.HyperbolicGroups.PictureGenus +OAI.Geometry.HyperbolicGroups.PictureLeaf +OAI.Geometry.HyperbolicGroups.PictureMap +OAI.Geometry.HyperbolicGroups.PictureMapFurther +OAI.Geometry.HyperbolicGroups.PictureMirror +OAI.Geometry.HyperbolicGroups.PictureOutsideColor +OAI.Geometry.HyperbolicGroups.PicturePartition +OAI.Geometry.HyperbolicGroups.PicturePlanarSeparator +OAI.Geometry.HyperbolicGroups.PictureRadiusSeparator +OAI.Geometry.HyperbolicGroups.PictureRestrict +OAI.Geometry.HyperbolicGroups.PictureRootSeparator +OAI.Geometry.HyperbolicGroups.PictureSqrtSeparator +OAI.Geometry.HyperbolicGroups.PictureStarGraph +OAI.Geometry.HyperbolicGroups.PictureSum +OAI.Geometry.HyperbolicGroups.PictureTriangulation +OAI.Geometry.HyperbolicGroups.PictureTriangulationEuler +OAI.Geometry.HyperbolicGroups.PictureUnderlyingGraph +OAI.Geometry.HyperbolicGroups.PictureVertexBoundary +OAI.Geometry.HyperbolicGroups.PictureVertexCut +OAI.Geometry.HyperbolicGroups.Pinned +OAI.Geometry.HyperbolicGroups.PlanarEdgeOrdering +OAI.Geometry.HyperbolicGroups.PlanarFacePartition +OAI.Geometry.HyperbolicGroups.PlanarPartitionBridge +OAI.Geometry.HyperbolicGroups.PlanarSubpairing +OAI.Geometry.HyperbolicGroups.PolygonBoundaryList +OAI.Geometry.HyperbolicGroups.PolygonContraction +OAI.Geometry.HyperbolicGroups.PolygonCornerPrimitive +OAI.Geometry.HyperbolicGroups.PolygonDiskProducer +OAI.Geometry.HyperbolicGroups.PolygonFilling +OAI.Geometry.HyperbolicGroups.PolygonLiftedCochain +OAI.Geometry.HyperbolicGroups.PolygonSphere +OAI.Geometry.HyperbolicGroups.PolygonSphereFurther +OAI.Geometry.HyperbolicGroups.PolygonTarget +OAI.Geometry.HyperbolicGroups.PolygonTriangleCochains +OAI.Geometry.HyperbolicGroups.PolygonTriangles +OAI.Geometry.HyperbolicGroups.Polygons +OAI.Geometry.HyperbolicGroups.Presentation +OAI.Geometry.HyperbolicGroups.PresentationDisk +OAI.Geometry.HyperbolicGroups.PrismConcat +OAI.Geometry.HyperbolicGroups.ProtectedNormal +OAI.Geometry.HyperbolicGroups.QuotientSum +OAI.Geometry.HyperbolicGroups.Random +OAI.Geometry.HyperbolicGroups.RankCollection +OAI.Geometry.HyperbolicGroups.RankSampling +OAI.Geometry.HyperbolicGroups.RankSelection +OAI.Geometry.HyperbolicGroups.RelativeApexAggregate +OAI.Geometry.HyperbolicGroups.RelativeApexLocal +OAI.Geometry.HyperbolicGroups.RelativeApexProducer +OAI.Geometry.HyperbolicGroups.RelativeContact +OAI.Geometry.HyperbolicGroups.RelativeDegree +OAI.Geometry.HyperbolicGroups.RelativeExceptional +OAI.Geometry.HyperbolicGroups.RelativeFaceCounts +OAI.Geometry.HyperbolicGroups.RelativeFaceSide +OAI.Geometry.HyperbolicGroups.RelativeFanCapacity +OAI.Geometry.HyperbolicGroups.RelativeFanLink +OAI.Geometry.HyperbolicGroups.RelativeFragment +OAI.Geometry.HyperbolicGroups.RelativeFrozenSide +OAI.Geometry.HyperbolicGroups.RelativeGlobalStep +OAI.Geometry.HyperbolicGroups.RelativeInstanceAt +OAI.Geometry.HyperbolicGroups.RelativeInteriorCount +OAI.Geometry.HyperbolicGroups.RelativeLayers +OAI.Geometry.HyperbolicGroups.RelativeMacroPolygon +OAI.Geometry.HyperbolicGroups.RelativeMultiplicity +OAI.Geometry.HyperbolicGroups.RelativePartition +OAI.Geometry.HyperbolicGroups.RelativePartitionEstimate +OAI.Geometry.HyperbolicGroups.RelativePayment +OAI.Geometry.HyperbolicGroups.RelativeRadialBoundary +OAI.Geometry.HyperbolicGroups.RelativeRawAccount +OAI.Geometry.HyperbolicGroups.RelativeRawCount +OAI.Geometry.HyperbolicGroups.RelativeRawPosition +OAI.Geometry.HyperbolicGroups.RelativeSlots +OAI.Geometry.HyperbolicGroups.RelativeSmallPartition +OAI.Geometry.HyperbolicGroups.RelativeTopTurns +OAI.Geometry.HyperbolicGroups.RelativeTriangleTransport +OAI.Geometry.HyperbolicGroups.RelativeTurnTransport +OAI.Geometry.HyperbolicGroups.RelativeWeights +OAI.Geometry.HyperbolicGroups.RestrictOccurrence +OAI.Geometry.HyperbolicGroups.SamplingStage +OAI.Geometry.HyperbolicGroups.SelectedPresentation +OAI.Geometry.HyperbolicGroups.Selection +OAI.Geometry.HyperbolicGroups.SeparatorBudget +OAI.Geometry.HyperbolicGroups.SeparatorComponents +OAI.Geometry.HyperbolicGroups.SeparatorCutoff +OAI.Geometry.HyperbolicGroups.SeparatorDecomposition +OAI.Geometry.HyperbolicGroups.SeparatorGrouping +OAI.Geometry.HyperbolicGroups.SeparatorRecursion +OAI.Geometry.HyperbolicGroups.SetoidGlue +OAI.Geometry.HyperbolicGroups.SetoidRestrict +OAI.Geometry.HyperbolicGroups.Shape +OAI.Geometry.HyperbolicGroups.ShortSegmentLift +OAI.Geometry.HyperbolicGroups.SimpleLetterPresentation +OAI.Geometry.HyperbolicGroups.SimplexCoordinates +OAI.Geometry.HyperbolicGroups.SixCounts +OAI.Geometry.HyperbolicGroups.SixRows +OAI.Geometry.HyperbolicGroups.SmallSimplexCoordinates +OAI.Geometry.HyperbolicGroups.SquareBoundaryExtension +OAI.Geometry.HyperbolicGroups.SquarePathFilling +OAI.Geometry.HyperbolicGroups.StarActual +OAI.Geometry.HyperbolicGroups.StarBudget +OAI.Geometry.HyperbolicGroups.StarCoupling +OAI.Geometry.HyperbolicGroups.StarError +OAI.Geometry.HyperbolicGroups.StarFiber +OAI.Geometry.HyperbolicGroups.StarIncidence +OAI.Geometry.HyperbolicGroups.StarMean +OAI.Geometry.HyperbolicGroups.StarModel +OAI.Geometry.HyperbolicGroups.StarModelFurther +OAI.Geometry.HyperbolicGroups.StarRate +OAI.Geometry.HyperbolicGroups.StarVariance +OAI.Geometry.HyperbolicGroups.StationaryInterpolation +OAI.Geometry.HyperbolicGroups.StepChain +OAI.Geometry.HyperbolicGroups.SubpairingCopies +OAI.Geometry.HyperbolicGroups.SubpairingDarts +OAI.Geometry.HyperbolicGroups.SubpairingGraph +OAI.Geometry.HyperbolicGroups.SubpairingTree +OAI.Geometry.HyperbolicGroups.TableSelection +OAI.Geometry.HyperbolicGroups.TangentCone +OAI.Geometry.HyperbolicGroups.TangentRay +OAI.Geometry.HyperbolicGroups.Template +OAI.Geometry.HyperbolicGroups.Test +OAI.Geometry.HyperbolicGroups.TreeCentroid +OAI.Geometry.HyperbolicGroups.TreeCentroidComponents +OAI.Geometry.HyperbolicGroups.TreeCentroidCut +OAI.Geometry.HyperbolicGroups.TreeHull +OAI.Geometry.HyperbolicGroups.TreePathHull +OAI.Geometry.HyperbolicGroups.TreePathIntDepth +OAI.Geometry.HyperbolicGroups.TreeSubpairingLift +OAI.Geometry.HyperbolicGroups.TriangleCoordinates +OAI.Geometry.HyperbolicGroups.TriangleEdgeIntersection +OAI.Geometry.HyperbolicGroups.TriangleHomotopyExtension +OAI.Geometry.HyperbolicGroups.TriangleSquare +OAI.Geometry.HyperbolicGroups.TriangleSquareFurther +OAI.Geometry.HyperbolicGroups.UniformGeodesicProper +OAI.Geometry.HyperbolicGroups.UniformMetricCover +OAI.Geometry.HyperbolicGroups.VoltageCellGluing +OAI.Geometry.HyperbolicGroups.VoltageClosedCells +OAI.Geometry.HyperbolicGroups.VoltageEdgeAgreement +OAI.Geometry.HyperbolicGroups.VoltageEdgeCorrection +OAI.Geometry.HyperbolicGroups.VoltageEdges +OAI.Geometry.HyperbolicGroups.VoltageFacePrisms +OAI.Geometry.HyperbolicGroups.VoltageGraphHomotopy +OAI.Geometry.HyperbolicGroups.VoltagePrismGluing +OAI.Geometry.HyperbolicGroups.VoltageTriangleContraction +OAI.Geometry.HyperbolicGroups.VoltageTriangleHomotopy +OAI.Geometry.HyperbolicGroups.VoltageTriangles +OAI.Geometry.HyperbolicGroups.WalkApexAggregate +OAI.Geometry.HyperbolicGroups.WalkCancel +OAI.Geometry.HyperbolicGroups.WalkCell +OAI.Geometry.HyperbolicGroups.WalkClasses +OAI.Geometry.HyperbolicGroups.WalkConeLink +OAI.Geometry.HyperbolicGroups.WalkCover +OAI.Geometry.HyperbolicGroups.WalkFacePosition +OAI.Geometry.HyperbolicGroups.WalkFanCapacity +OAI.Geometry.HyperbolicGroups.WalkFanCorner +OAI.Geometry.HyperbolicGroups.WalkFanIncoming +OAI.Geometry.HyperbolicGroups.WalkFragment +OAI.Geometry.HyperbolicGroups.WalkInstanceAt +OAI.Geometry.HyperbolicGroups.WalkMultiplicity +OAI.Geometry.HyperbolicGroups.WalkNormal +OAI.Geometry.HyperbolicGroups.WalkPayment +OAI.Geometry.HyperbolicGroups.WalkRadial +OAI.Geometry.HyperbolicGroups.WalkRadialBoundary +OAI.Geometry.HyperbolicGroups.WalkRawPosition +OAI.Geometry.HyperbolicGroups.WalkTopTurns +OAI.Geometry.HyperbolicGroups.WalkTriangleTransport +OAI.Geometry.HyperbolicGroups.WalkTurnTransport +OAI.Geometry.HyperbolicGroups.WeightedCoincidence +OAI.Geometry.HyperbolicGroups.WeightedRank +OAI.Geometry.HyperbolicGroups.WordDisk +OAI.Geometry.HyperbolicGroups.WordPicture +OAI.Geometry.HyperbolicGroups.WordPictureAppend +OAI.Geometry.HyperbolicGroups.WordPictureArea +OAI.Geometry.HyperbolicGroups.WordPictureBase +OAI.Geometry.HyperbolicGroups.WordPictureCell +OAI.Geometry.HyperbolicGroups.WordPictureExist +OAI.Geometry.HyperbolicGroups.WordPictureFilling +OAI.Geometry.HyperbolicGroups.WordPictureFold +OAI.Geometry.HyperbolicGroups.WordPictureLiteral +OAI.Geometry.HyperbolicGroups.WordPictureMarked +OAI.Geometry.HyperbolicGroups.WordPicturePeel +OAI.Geometry.HyperbolicGroups.WordSubstitution diff --git a/tasks/hyperbolic-obstruction/solution/reference.py b/tasks/hyperbolic-obstruction/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hyperbolic-obstruction/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hyperbolic-obstruction/solution/solve.sh b/tasks/hyperbolic-obstruction/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a3a02c888597c08491bb9ec453066927068dc353 --- /dev/null +++ b/tasks/hyperbolic-obstruction/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HyperbolicObstruction, i.e. module OAI.Geometry.HyperbolicGroups.Main and the +# 417 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.HyperbolicGroups.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HyperbolicObstruction" diff --git a/tasks/hyperbolic-obstruction/task.toml b/tasks/hyperbolic-obstruction/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ab3564f63bd5a11f0a08db72499a5a306367032 --- /dev/null +++ b/tasks/hyperbolic-obstruction/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hyperbolic-obstruction" +version = "1.0.0" +description = "Prove HyperbolicObstruction (openai/math family 257: A hyperbolic group with no geometric CAT(0) action) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HyperbolicObstruction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HyperbolicObstruction" +family = "257" +family_title = "A hyperbolic group with no geometric CAT(0) action" +subject = "Group theory" +theorems = ["OAI.HyperbolicObstruction.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.HyperbolicGroups.Main" +reference_modules = 417 +reference_lean_bytes = 2430541 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1194 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13887 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hyperbolic-obstruction/tests/Challenge.lean b/tasks/hyperbolic-obstruction/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..48a977c226cfce90f8ffe3cb503be7508b31ced3 --- /dev/null +++ b/tasks/hyperbolic-obstruction/tests/Challenge.lean @@ -0,0 +1,163 @@ +import Mathlib + +namespace OAI + + + +section + +section + +/-! +Finite complexes are standard barycentric realizations of finite abstract +simplicial complexes. Area-counted elementary edge homotopies encode the +usual triangular disk diagrams, allowing spurs and collapsed edges. Null edge +loops (equivalently closed lifts to the universal cover) are those admitting +such a disk, without any area bound. Asphericity is vanishing of all higher +homotopy groups of this finite polyhedron. The CAT conditions use the standard +squared-distance / hyperbolic-cosh comparison formulations. +-/ + +noncomputable section +open scoped Topology ContinuousMap + +namespace HyperbolicObstruction + +structure FiniteComplex where + n : ℕ + complex : AbstractSimplicialComplex (Fin n) + +namespace FiniteComplex + +abbrev Vertex (K : FiniteComplex) := Fin K.n + +def Carrier (K : FiniteComplex) := + {x : K.Vertex → ℝ // (∀ i, 0 ≤ x i) ∧ (∑ i, x i) = 1 ∧ + ∃ s ∈ K.complex.faces, ∀ i, i ∉ s → x i = 0} + +instance (K : FiniteComplex) : TopologicalSpace K.Carrier := + inferInstanceAs (TopologicalSpace (Subtype _)) + +def Edge (K : FiniteComplex) (a b : K.Vertex) : Prop := + {a, b} ∈ K.complex.faces + +def EdgePath (K : FiniteComplex) : List K.Vertex → Prop + | [] => False + | [_] => True + | a :: b :: t => K.Edge a b ∧ K.EdgePath (b :: t) + +def Closed (K : FiniteComplex) (p : List K.Vertex) : Prop := + ∃ a t, p = a :: (t ++ [a]) ∨ p = [a] + +/-- An elementary disk move. A noncollapsed triangular face costs one; + a spur or a collapsed edge costs zero. Contexts are unchanged. -/ +inductive DiskMove (K : FiniteComplex) : List K.Vertex → List K.Vertex → ℕ → Prop + | stutter (l r) (a) : + DiskMove K (l ++ [a, a] ++ r) (l ++ [a] ++ r) 0 + | spur (l r) (a b) (h : K.Edge a b) : + DiskMove K (l ++ [a, b, a] ++ r) (l ++ [a] ++ r) 0 + | triangle (l r) (a b c) (h : {a, b, c} ∈ K.complex.faces) + (hne : ({a, b, c} : Finset K.Vertex).card = 3) : + DiskMove K (l ++ [a, b, c] ++ r) (l ++ [a, c] ++ r) 1 + +/-- A disk certificate obtained by elementary triangle attachments/removals, + with spurs/collapses allowed. The index is the number of triangular faces. -/ +inductive DiskHomotopy (K : FiniteComplex) : List K.Vertex → List K.Vertex → ℕ → Prop + | refl (p) : DiskHomotopy K p p 0 + | move {p q n} : DiskMove K p q n → DiskHomotopy K p q n + | symm {p q n} : DiskHomotopy K p q n → DiskHomotopy K q p n + | trans {p q r m n} : DiskHomotopy K p q m → DiskHomotopy K q r n → + DiskHomotopy K p r (m + n) + +def Disk (K : FiniteComplex) (p : List K.Vertex) (faces : ℕ) : Prop := + ∃ a, K.DiskHomotopy p [a] faces + +def LinearDiskFilling (K : FiniteComplex) (C : ℝ) : Prop := + ∀ p, K.EdgePath p → K.Closed p → (∃ a, K.Disk p a) → + ∃ a, K.Disk p a ∧ (a : ℝ) ≤ C * (p.length - 1 : ℕ) + +def Aspherical (K : FiniteComplex) (x : K.Carrier) : Prop := + ∀ n : ℕ, Subsingleton (HomotopyGroup.Pi (n + 2) K.Carrier x) + +end FiniteComplex + +/-- A constant-speed metric segment, parametrized on [0,1]. -/ +def IsSegment {X : Type*} [MetricSpace X] (γ : ℝ → X) (x y : X) : Prop := + γ 0 = x ∧ γ 1 = y ∧ + ∀ s ∈ Set.Icc (0 : ℝ) 1, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist (γ s) (γ t) = |s - t| * dist x y + +def IsGeodesic (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y + +/-- The CN characterization of CAT(0), with whole metric segments. -/ +def CATZero (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y ∧ + ∀ z : X, ∀ t ∈ Set.Icc (0 : ℝ) 1, + dist z (γ t) ^ 2 ≤ (1 - t) * dist z x ^ 2 + t * dist z y ^ 2 - + t * (1 - t) * dist x y ^ 2 + +/-- The hyperbolic-cosh midpoint characterization of CAT(-1). -/ +def CATNegOne (X : Type*) [MetricSpace X] : Prop := + ∀ x y : X, ∃ γ, IsSegment γ x y ∧ + ∀ z : X, Real.cosh (dist z (γ (1 / 2))) ≤ + (Real.cosh (dist z x) + Real.cosh (dist z y)) / + (2 * Real.cosh (dist x y / 2)) + +/-- A proper, cocompact isometric action of a discrete group. -/ +structure GeometricAction (G X : Type*) [Group G] [MetricSpace X] where + act : G →* (X ≃ᵢ X) + proper : ∀ C : Set X, IsCompact C → + {g : G | ∃ x ∈ C, act g x ∈ C}.Finite + cocompact : ∃ C : Set X, IsCompact C ∧ ∀ x : X, ∃ g : G, ∃ y ∈ C, act g y = x + +universe u + +def NoGeometricCATZeroAction (G : Type*) [Group G] : Prop := + ∀ (X : Type u) (_ : MetricSpace X), Nonempty X → ProperSpace X → CompleteSpace X → + CATZero X → IsEmpty (GeometricAction G X) + +def WordLength {G : Type*} [Group G] (S : Finset G) (g : G) : ℕ := + sInf {n | ∃ w : List G, w.length = n ∧ + (∀ a ∈ w, a ∈ S ∨ a⁻¹ ∈ S) ∧ w.prod = g} + +def WordDistance {G : Type*} [Group G] (S : Finset G) (g h : G) : ℝ := + WordLength S (g⁻¹ * h) + +/-- Four-point word hyperbolicity, for some finite generating set. -/ +def WordHyperbolic (G : Type*) [Group G] : Prop := + ∃ S : Finset G, Subgroup.closure (S : Set G) = ⊤ ∧ + ∃ δ : ℝ, 0 ≤ δ ∧ ∀ a b c d : G, + WordDistance S a c + WordDistance S b d ≤ + max (WordDistance S a b + WordDistance S c d) + (WordDistance S a d + WordDistance S b c) + 2 * δ + +/-- A metric on the given finite polyhedron, not on a different topology. -/ +def CompatibleLocallyCATNegOne (K : FiniteComplex) : Prop := + ∃ m : MetricSpace K.Carrier, + m.toUniformSpace.toTopologicalSpace = (inferInstance : TopologicalSpace K.Carrier) ∧ + (letI := m + IsGeodesic K.Carrier ∧ ∀ x : K.Carrier, ∃ r : ℝ, 0 < r ∧ + CATNegOne (Metric.ball x r)) + +/-- A finite aspherical complex with hyperbolic fundamental group, no geometric CAT(0) +action, and no homotopy equivalent finite complex admitting a locally CAT(-1) metric. -/ +def MainStatement : Prop := + ∃ K : FiniteComplex, ∃ x : K.Carrier, ∃ C : ℝ, + ConnectedSpace K.Carrier ∧ K.Aspherical x ∧ 0 ≤ C ∧ K.LinearDiskFilling C ∧ + NoGeometricCATZeroAction.{u} (FundamentalGroup K.Carrier x) ∧ + WordHyperbolic (FundamentalGroup K.Carrier x) ∧ + ∀ L : FiniteComplex, Nonempty (K.Carrier ≃ₕ L.Carrier) → + ¬ CompatibleLocallyCATNegOne L + + +theorem main : MainStatement.{u} := by sorry + +end HyperbolicObstruction + + +end +end +end + +end OAI diff --git a/tasks/hyperbolic-obstruction/tests/grade.py b/tasks/hyperbolic-obstruction/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hyperbolic-obstruction/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hyperbolic-obstruction/tests/task.json b/tasks/hyperbolic-obstruction/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..64f3676c4abbc9e0d0db3b4ae077e8433461bc4d --- /dev/null +++ b/tasks/hyperbolic-obstruction/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HyperbolicObstruction", + "comparator": { + "theorem_names": [ + "OAI.HyperbolicObstruction.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12987 +} \ No newline at end of file diff --git a/tasks/hyperbolic-obstruction/tests/test.sh b/tasks/hyperbolic-obstruction/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hyperbolic-obstruction/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/hyperinvariant-subspaces/environment/Dockerfile b/tasks/hyperinvariant-subspaces/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/hyperinvariant-subspaces/environment/fetch_mathlib.sh b/tasks/hyperinvariant-subspaces/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/hyperinvariant-subspaces/environment/lake-manifest.json b/tasks/hyperinvariant-subspaces/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/hyperinvariant-subspaces/environment/lakefile.lean b/tasks/hyperinvariant-subspaces/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/hyperinvariant-subspaces/environment/lean_setup.sh b/tasks/hyperinvariant-subspaces/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/hyperinvariant-subspaces/environment/pack_submission.py b/tasks/hyperinvariant-subspaces/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/hyperinvariant-subspaces/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/hyperinvariant-subspaces/instruction.md b/tasks/hyperinvariant-subspaces/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..284e07f2ca1a4a1661e3dddb9369672ba4f1949f --- /dev/null +++ b/tasks/hyperinvariant-subspaces/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `HyperinvariantSubspaces` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `HyperinvariantSubspaces`, also at `/opt/openai-math/challenges/HyperinvariantSubspaces.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Hyperinvariant + +open Filter +open scoped Topology + +universe u + +section + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def commutant (T : H →L[ℂ] H) : Subalgebra ℂ (H →L[ℂ] H) := + Subalgebra.centralizer ℂ ({T} : Set (H →L[ℂ] H)) + +def TransitiveCommutant (T : H →L[ℂ] H) : Prop := + ∀ K : Submodule ℂ H, IsClosed (K : Set H) → + (∀ A : H →L[ℂ] H, A * T = T * A → ∀ x ∈ K, A x ∈ K) → + K = ⊥ ∨ K = ⊤ + +@[instance_reducible] def strongOperatorTopology : TopologicalSpace (H →L[ℂ] H) := + TopologicalSpace.induced (fun A : H →L[ℂ] H => (fun x : H => A x)) inferInstance + +def FullClaim : Prop := + ∃ T : H →L[ℂ] H, T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + TransitiveCommutant T ∧ commutant T ≠ ⊤ ∧ + @IsClosed (H →L[ℂ] H) strongOperatorTopology (commutant T : Set (H →L[ℂ] H)) + +end + +variable (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] [TopologicalSpace.SeparableSpace H] + +theorem main_theorem (hInf : ¬FiniteDimensional ℂ H) : FullClaim (H := H) := by + sorry + +end Hyperinvariant + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/HyperinvariantSubspaces.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Hyperinvariant.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/hyperinvariant-subspaces/solution/closure.txt b/tasks/hyperinvariant-subspaces/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1607b65d7d5c570bb0e8dbf7dd400eb19fc108c7 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/solution/closure.txt @@ -0,0 +1,277 @@ +OAI.Analysis.FiniteFactor.BiasedPairs.CommonConull +OAI.Analysis.FiniteFactor.BiasedPairs.Conull +OAI.Analysis.FiniteFactor.BiasedPairs.Measures +OAI.Analysis.FiniteFactor.BiasedPairs.PairIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixDomination +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixLimit +OAI.Analysis.FiniteFactor.BiasedPairs.RealIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.ReferenceDomination +OAI.Analysis.FiniteFactor.BoundedMatrixOperator +OAI.Analysis.FiniteFactor.CompactGraphLusin +OAI.Analysis.FiniteFactor.CompactZeroTransfer +OAI.Analysis.FiniteFactor.Contradiction +OAI.Analysis.FiniteFactor.Convolution +OAI.Analysis.FiniteFactor.CountableMaskedError +OAI.Analysis.FiniteFactor.Coupling.BadEvents +OAI.Analysis.FiniteFactor.Coupling.Bayes +OAI.Analysis.FiniteFactor.Coupling.BlockLimit +OAI.Analysis.FiniteFactor.Coupling.Bounds +OAI.Analysis.FiniteFactor.Coupling.Conditioning +OAI.Analysis.FiniteFactor.Coupling.CoordinateMass +OAI.Analysis.FiniteFactor.Coupling.Crossing +OAI.Analysis.FiniteFactor.Coupling.Density +OAI.Analysis.FiniteFactor.Coupling.FiniteDisintegration +OAI.Analysis.FiniteFactor.Coupling.FiniteLaw +OAI.Analysis.FiniteFactor.Coupling.FinitePosteriorAC +OAI.Analysis.FiniteFactor.Coupling.Infinite +OAI.Analysis.FiniteFactor.Coupling.Law +OAI.Analysis.FiniteFactor.Coupling.Limit +OAI.Analysis.FiniteFactor.Coupling.Marginals +OAI.Analysis.FiniteFactor.Coupling.Mixture +OAI.Analysis.FiniteFactor.Coupling.Noncrossing +OAI.Analysis.FiniteFactor.Coupling.Order +OAI.Analysis.FiniteFactor.Coupling.Parameters +OAI.Analysis.FiniteFactor.Coupling.Prefix +OAI.Analysis.FiniteFactor.Coupling.Products +OAI.Analysis.FiniteFactor.Coupling.TaggedAdmissibility +OAI.Analysis.FiniteFactor.Coupling.VectorBayes +OAI.Analysis.FiniteFactor.CrossedProduct.AngleLaw +OAI.Analysis.FiniteFactor.CrossedProduct.AngleRelations +OAI.Analysis.FiniteFactor.CrossedProduct.AssignedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.Attenuation +OAI.Analysis.FiniteFactor.CrossedProduct.BoundaryEvent +OAI.Analysis.FiniteFactor.CrossedProduct.CappedPair +OAI.Analysis.FiniteFactor.CrossedProduct.CappedTransfer +OAI.Analysis.FiniteFactor.CrossedProduct.CentralDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.CentralScalarField +OAI.Analysis.FiniteFactor.CrossedProduct.Cocycle +OAI.Analysis.FiniteFactor.CrossedProduct.ColumnSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.ConjugationVacuum +OAI.Analysis.FiniteFactor.CrossedProduct.ConvolutionCocycle +OAI.Analysis.FiniteFactor.CrossedProduct.CouplingBudget +OAI.Analysis.FiniteFactor.CrossedProduct.CurrentTaggedEvent +OAI.Analysis.FiniteFactor.CrossedProduct.DiagonalLoss +OAI.Analysis.FiniteFactor.CrossedProduct.EventExpectation +OAI.Analysis.FiniteFactor.CrossedProduct.EventLossAssembly +OAI.Analysis.FiniteFactor.CrossedProduct.EventMassUpper +OAI.Analysis.FiniteFactor.CrossedProduct.EventPositive +OAI.Analysis.FiniteFactor.CrossedProduct.FiberEnergy +OAI.Analysis.FiniteFactor.CrossedProduct.FiberIndicators +OAI.Analysis.FiniteFactor.CrossedProduct.FiberSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.FiberTotal +OAI.Analysis.FiniteFactor.CrossedProduct.FieldAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FieldRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCocycleBounds +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCoefficients +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteVectors +OAI.Analysis.FiniteFactor.CrossedProduct.FloorSupport +OAI.Analysis.FiniteFactor.CrossedProduct.FreeRotation +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundary +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundaryLoss +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBudget +OAI.Analysis.FiniteFactor.CrossedProduct.GeneratedAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.HilbertSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.IndicatorProjection +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantConull +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantProjection +OAI.Analysis.FiniteFactor.CrossedProduct.LusinCompact +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedError +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.MultiplicationAdjoint +OAI.Analysis.FiniteFactor.CrossedProduct.NoMinimalProjection +OAI.Analysis.FiniteFactor.CrossedProduct.NormalFunctionalSpace +OAI.Analysis.FiniteFactor.CrossedProduct.NormalRiesz +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedRatio +OAI.Analysis.FiniteFactor.CrossedProduct.Operator +OAI.Analysis.FiniteFactor.CrossedProduct.OperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.OrbitNormalization +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedSampling +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedTorusSampling +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCount +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCoverage +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseDecay +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseFirst +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseMarginal +OAI.Analysis.FiniteFactor.CrossedProduct.Phases +OAI.Analysis.FiniteFactor.CrossedProduct.Powers +OAI.Analysis.FiniteFactor.CrossedProduct.PredualIdentification +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedBase +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFactor +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFinite +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionColumns +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionConvolution +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionErrors +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionEvent +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPositiveConull +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceMixture +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceOrdered +OAI.Analysis.FiniteFactor.CrossedProduct.Reflection +OAI.Analysis.FiniteFactor.CrossedProduct.ResamplingLaw +OAI.Analysis.FiniteFactor.CrossedProduct.Rotation +OAI.Analysis.FiniteFactor.CrossedProduct.RotationCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.RotationErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCenter +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.SmallPartitionSets +OAI.Analysis.FiniteFactor.CrossedProduct.StageCoupling +OAI.Analysis.FiniteFactor.CrossedProduct.StageOperator +OAI.Analysis.FiniteFactor.CrossedProduct.StagePolynomial +OAI.Analysis.FiniteFactor.CrossedProduct.Stages +OAI.Analysis.FiniteFactor.CrossedProduct.TagGeometry +OAI.Analysis.FiniteFactor.CrossedProduct.TagLaw +OAI.Analysis.FiniteFactor.CrossedProduct.TailTrimming +OAI.Analysis.FiniteFactor.CrossedProduct.TorusCharacters +OAI.Analysis.FiniteFactor.CrossedProduct.TorusErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.TorusModel +OAI.Analysis.FiniteFactor.CrossedProduct.TorusOperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.TorusRotation +OAI.Analysis.FiniteFactor.CrossedProduct.Trace +OAI.Analysis.FiniteFactor.CrossedProduct.TracialRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.Transport +OAI.Analysis.FiniteFactor.CrossedProduct.TruncatedBound +OAI.Analysis.FiniteFactor.CrossedProduct.UncappedPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumFunctional +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumSeparating +OAI.Analysis.FiniteFactor.CrossedProduct.VectorFunctionalRelations +OAI.Analysis.FiniteFactor.CrossedProduct.WeightedShiftField +OAI.Analysis.FiniteFactor.Diffuse.OperatorCesaro +OAI.Analysis.FiniteFactor.Diffuse.OperatorMeanErgodic +OAI.Analysis.FiniteFactor.Diffuse.OperatorSupport +OAI.Analysis.FiniteFactor.Diffuse.ProjectionTrace +OAI.Analysis.FiniteFactor.Diffuse.SmallPartitions +OAI.Analysis.FiniteFactor.Diffuse.SupportLimit +OAI.Analysis.FiniteFactor.Diffuse.SupportTrace +OAI.Analysis.FiniteFactor.Diffuse.TracePowers +OAI.Analysis.FiniteFactor.Fiber.Diagonal +OAI.Analysis.FiniteFactor.Fiber.PairZeroSet +OAI.Analysis.FiniteFactor.Fiber.ProjectionDiagonal +OAI.Analysis.FiniteFactor.Fiber.Shift +OAI.Analysis.FiniteFactor.Fiber.StrongContinuity +OAI.Analysis.FiniteFactor.Fiber.TransportConvolution +OAI.Analysis.FiniteFactor.FiniteMeasureCylinderCriterion +OAI.Analysis.FiniteFactor.FiniteMixtureAlgebra +OAI.Analysis.FiniteFactor.FiniteProductAbsoluteContinuity +OAI.Analysis.FiniteFactor.FiniteProductMixture +OAI.Analysis.FiniteFactor.FiniteSingleTag +OAI.Analysis.FiniteFactor.IndependentCount +OAI.Analysis.FiniteFactor.L2UniformAbsoluteContinuity +OAI.Analysis.FiniteFactor.Matrix.Action +OAI.Analysis.FiniteFactor.Matrix.Bounds +OAI.Analysis.FiniteFactor.Matrix.Covariance +OAI.Analysis.FiniteFactor.Matrix.Entries +OAI.Analysis.FiniteFactor.Matrix.Integrals +OAI.Analysis.FiniteFactor.Model +OAI.Analysis.FiniteFactor.OperatorTracialRepresentation +OAI.Analysis.FiniteFactor.OperatorUltraweak +OAI.Analysis.FiniteFactor.OrbitSampling.CompactTorus +OAI.Analysis.FiniteFactor.OrbitSampling.CrossProducts +OAI.Analysis.FiniteFactor.OrbitSampling.Cube +OAI.Analysis.FiniteFactor.OrbitSampling.CutoffMass +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderBasis +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderSystem +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalContribution +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalEvent +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalIntegral +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalLimit +OAI.Analysis.FiniteFactor.OrbitSampling.Discrepancy +OAI.Analysis.FiniteFactor.OrbitSampling.EmpiricalL2 +OAI.Analysis.FiniteFactor.OrbitSampling.Error +OAI.Analysis.FiniteFactor.OrbitSampling.ErrorEvent +OAI.Analysis.FiniteFactor.OrbitSampling.FirstCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.FirstMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.Fourier +OAI.Analysis.FiniteFactor.OrbitSampling.IdealProduct +OAI.Analysis.FiniteFactor.OrbitSampling.IdealRectangleLimit +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMass +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaRectangles +OAI.Analysis.FiniteFactor.OrbitSampling.LimitMeasure +OAI.Analysis.FiniteFactor.OrbitSampling.Measures +OAI.Analysis.FiniteFactor.OrbitSampling.Moments +OAI.Analysis.FiniteFactor.OrbitSampling.OrbitSupport +OAI.Analysis.FiniteFactor.OrbitSampling.OrderedRestriction +OAI.Analysis.FiniteFactor.OrbitSampling.PairMoments +OAI.Analysis.FiniteFactor.OrbitSampling.PhaseSelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.Powers +OAI.Analysis.FiniteFactor.OrbitSampling.ProductError +OAI.Analysis.FiniteFactor.OrbitSampling.ProductMoments +OAI.Analysis.FiniteFactor.OrbitSampling.RationalTests +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleApproximation +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleError +OAI.Analysis.FiniteFactor.OrbitSampling.RotationTransport +OAI.Analysis.FiniteFactor.OrbitSampling.SecondCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.SecondMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.SelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.SelfSummability +OAI.Analysis.FiniteFactor.OrbitSampling.SingleCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.Tail +OAI.Analysis.FiniteFactor.OrbitSampling.TestedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TestedTransport +OAI.Analysis.FiniteFactor.OrbitSampling.TorusLimitMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusSupport +OAI.Analysis.FiniteFactor.OrbitSampling.TriangleLaw +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedWeak +OAI.Analysis.FiniteFactor.OrbitSampling.UniformEvent +OAI.Analysis.FiniteFactor.OrbitSampling.WeakLimit +OAI.Analysis.FiniteFactor.OrbitSampling.WeightedTail +OAI.Analysis.FiniteFactor.OrbitSampling.Weights +OAI.Analysis.FiniteFactor.PeriodizedUniform +OAI.Analysis.FiniteFactor.Polynomial +OAI.Analysis.FiniteFactor.ProductDensityLimit +OAI.Analysis.FiniteFactor.ProductKernel +OAI.Analysis.FiniteFactor.Quasinilpotence +OAI.Analysis.FiniteFactor.Sampling.AveragedTransport +OAI.Analysis.FiniteFactor.Sampling.Cancellation +OAI.Analysis.FiniteFactor.Sampling.FirstDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.FirstInterval +OAI.Analysis.FiniteFactor.Sampling.Fourier +OAI.Analysis.FiniteFactor.Sampling.FourierSum +OAI.Analysis.FiniteFactor.Sampling.IntegratedCorrelation +OAI.Analysis.FiniteFactor.Sampling.IntervalError +OAI.Analysis.FiniteFactor.Sampling.IntervalSums +OAI.Analysis.FiniteFactor.Sampling.Kernel +OAI.Analysis.FiniteFactor.Sampling.KernelTail +OAI.Analysis.FiniteFactor.Sampling.LayerCake +OAI.Analysis.FiniteFactor.Sampling.LayerDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.MixedCorrelation +OAI.Analysis.FiniteFactor.Sampling.OrientedMoments +OAI.Analysis.FiniteFactor.Sampling.Periodization +OAI.Analysis.FiniteFactor.Sampling.ProductError +OAI.Analysis.FiniteFactor.Sampling.Rectangle +OAI.Analysis.FiniteFactor.Sampling.SecondDensity +OAI.Analysis.FiniteFactor.Sampling.SecondDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.SecondInterval +OAI.Analysis.FiniteFactor.Sampling.SecondLevelAE +OAI.Analysis.FiniteFactor.Sampling.SecondLevels +OAI.Analysis.FiniteFactor.Sampling.SecondMoment +OAI.Analysis.FiniteFactor.Sampling.SecondTriangular +OAI.Analysis.FiniteFactor.Sampling.Selection +OAI.Analysis.FiniteFactor.Sampling.SelfMoment +OAI.Analysis.FiniteFactor.Sampling.SmoothedPair +OAI.Analysis.FiniteFactor.Sampling.Smoothing +OAI.Analysis.FiniteFactor.Sampling.SmoothingLaw +OAI.Analysis.FiniteFactor.Sampling.TestedFirstMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSecondMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSelfMoment +OAI.Analysis.FiniteFactor.Sampling.Transport +OAI.Analysis.FiniteFactor.Sampling.WeightTransport +OAI.Analysis.FiniteFactor.Sampling.WeightedCoordinate +OAI.Analysis.FiniteFactor.Sampling.Weights +OAI.Analysis.FiniteFactor.SubmeasureL2Density +OAI.Analysis.FiniteFactor.TagExponentialLower +OAI.Analysis.FiniteFactor.TailEstimate +OAI.Analysis.FiniteFactor.Truncation +OAI.Analysis.Hyperinvariant.CommutantTopology +OAI.Analysis.Hyperinvariant.HilbertClassification +OAI.Analysis.Hyperinvariant.Main +OAI.Analysis.Hyperinvariant.ProjectionBridge +OAI.Analysis.Hyperinvariant.Specification +OAI.Analysis.Hyperinvariant.Transport +OAI.Analysis.Hyperinvariant.Witness diff --git a/tasks/hyperinvariant-subspaces/solution/reference.py b/tasks/hyperinvariant-subspaces/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/hyperinvariant-subspaces/solution/solve.sh b/tasks/hyperinvariant-subspaces/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..65489cfc0967244f47cb4795f0fc09b86eb71270 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of HyperinvariantSubspaces, i.e. module OAI.Analysis.Hyperinvariant.Main and the +# 277 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Hyperinvariant.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of HyperinvariantSubspaces" diff --git a/tasks/hyperinvariant-subspaces/task.toml b/tasks/hyperinvariant-subspaces/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..25540fd4d1ac31737c9e3d35b2010aeae328b543 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/hyperinvariant-subspaces" +version = "1.0.0" +description = "Prove HyperinvariantSubspaces (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/HyperinvariantSubspaces.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "HyperinvariantSubspaces" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.Hyperinvariant.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Hyperinvariant.Main" +reference_modules = 277 +reference_lean_bytes = 1129103 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1437 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12716 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/hyperinvariant-subspaces/tests/Challenge.lean b/tasks/hyperinvariant-subspaces/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f6554418d3aa78d365a3e5ce16fe57081f59413b --- /dev/null +++ b/tasks/hyperinvariant-subspaces/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +namespace Hyperinvariant + +open Filter +open scoped Topology + +universe u + +section + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def commutant (T : H →L[ℂ] H) : Subalgebra ℂ (H →L[ℂ] H) := + Subalgebra.centralizer ℂ ({T} : Set (H →L[ℂ] H)) + +def TransitiveCommutant (T : H →L[ℂ] H) : Prop := + ∀ K : Submodule ℂ H, IsClosed (K : Set H) → + (∀ A : H →L[ℂ] H, A * T = T * A → ∀ x ∈ K, A x ∈ K) → + K = ⊥ ∨ K = ⊤ + +@[instance_reducible] def strongOperatorTopology : TopologicalSpace (H →L[ℂ] H) := + TopologicalSpace.induced (fun A : H →L[ℂ] H => (fun x : H => A x)) inferInstance + +def FullClaim : Prop := + ∃ T : H →L[ℂ] H, T ≠ 0 ∧ + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) ∧ + TransitiveCommutant T ∧ commutant T ≠ ⊤ ∧ + @IsClosed (H →L[ℂ] H) strongOperatorTopology (commutant T : Set (H →L[ℂ] H)) + +end + +variable (H : Type u) [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] [TopologicalSpace.SeparableSpace H] + +theorem main_theorem (hInf : ¬FiniteDimensional ℂ H) : FullClaim (H := H) := by + sorry + +end Hyperinvariant + +end OAI diff --git a/tasks/hyperinvariant-subspaces/tests/grade.py b/tasks/hyperinvariant-subspaces/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/hyperinvariant-subspaces/tests/task.json b/tasks/hyperinvariant-subspaces/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..16d4d83378368aa1de12760960a25235458d2837 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "HyperinvariantSubspaces", + "comparator": { + "theorem_names": [ + "OAI.Hyperinvariant.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11816 +} \ No newline at end of file diff --git a/tasks/hyperinvariant-subspaces/tests/test.sh b/tasks/hyperinvariant-subspaces/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/hyperinvariant-subspaces/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/independent-products/environment/Dockerfile b/tasks/independent-products/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/independent-products/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/independent-products/environment/fetch_mathlib.sh b/tasks/independent-products/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/independent-products/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/independent-products/environment/lake-manifest.json b/tasks/independent-products/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/independent-products/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/independent-products/environment/lakefile.lean b/tasks/independent-products/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/independent-products/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/independent-products/environment/lean_setup.sh b/tasks/independent-products/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/independent-products/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/independent-products/environment/pack_submission.py b/tasks/independent-products/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/independent-products/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/independent-products/instruction.md b/tasks/independent-products/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..75c2d27ec04fd4045a21acab99bbd3a67b2f3fd8 --- /dev/null +++ b/tasks/independent-products/instruction.md @@ -0,0 +1,171 @@ +# openai/math challenge `IndependentProducts` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `IndependentProducts`, also at `/opt/openai-math/challenges/IndependentProducts.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal Topology + +universe uX + +namespace IndependentProducts + +/-- The tree of finite sequences of positive integers. -/ +abbrev Vertex := List ℕ+ +/-- Coordinates are attached only to nonroot vertices. -/ +abbrev Edge := {v : Vertex // v ≠ []} +abbrev Sample := Edge → ℝ + +/-- The product law of independent copies of the multiplier. -/ +def productMeasure (μ : Measure ℝ) : Measure Sample := + Measure.infinitePi (fun _ : Edge => μ) + +/-- The nonroot prefix ending at position `j`. -/ +def pathPrefix (v : Vertex) (j : Fin v.length) : Edge := + ⟨v.take (j.val + 1), by + intro h + have hl := congrArg List.length h + simp only [List.length_take, List.length_nil] at hl + have := j.isLt + omega⟩ + +/-- Root product is the empty product 1; every other product uses the path prefixes. -/ +def pathProduct (v : Vertex) (ω : Sample) : ℝ := + ∏ j : Fin v.length, ω (pathPrefix v j) + +/-- The closed real L1 span of the path products. -/ +def productSpan (μ : Measure ℝ) : Submodule ℝ (Lp ℝ 1 (productMeasure μ)) := + (Submodule.span ℝ {f : Lp ℝ 1 (productMeasure μ) | ∃ v : Vertex, + (f : Sample → ℝ) =ᵐ[productMeasure μ] pathProduct v}).topologicalClosure + +/-- Positivity, nonconstancy, mean one, and finite second moment of the multiplier law. -/ +structure MultiplierHypotheses (μ : Measure ℝ) : Prop where + probability : IsProbabilityMeasure μ + positive : ∀ᵐ w ∂μ, 0 < w + nonconstant : ∀ c : ℝ, ¬ (∀ᵐ w ∂μ, w = c) + mean_one : ∫ w, w ∂μ = 1 + second_moment : MemLp (fun w : ℝ => w) 2 μ + +variable (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Closed subspaces of finite codimension, with respect to the inherited topology. -/ +def CofiniteSubspaces : Set (Submodule ℝ X) := + {F | IsClosed (F : Set X) ∧ FiniteDimensional ℝ (X ⧸ F)} + +/-- The averaged asymptotic midpoint modulus, with directions of norm at least 1. -/ +def averagedMidpointModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x : X, N x = 1 ∧ r = + sSup {a | ∃ F ∈ CofiniteSubspaces X, a = + sInf {b | ∃ y : X, y ∈ F ∧ 1 ≤ N y ∧ + b = (N (x + t • y) + N (x - t • y)) / 2 - 1}}} + +/-- The usual one-sided modulus, whose directions have norm exactly 1. -/ +def oneSidedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x : X, N x = 1 ∧ r = + sSup {a | ∃ F ∈ CofiniteSubspaces X, a = + sInf {b | ∃ y : X, y ∈ F ∧ N y = 1 ∧ b = N (x + t • y) - 1}}} + +/-- A seminorm with these bounds is a genuine norm equivalent to the original norm. -/ +def IsEquivalentNorm (N : Seminorm ℝ X) : Prop := + ∃ a b : ℝ, 0 < a ∧ a ≤ b ∧ ∀ x, a * ‖x‖ ≤ N x ∧ N x ≤ b * ‖x‖ + +def IsAUC (N : Seminorm ℝ X) : Prop := ∀ t : ℝ, 0 < t → 0 < oneSidedModulus X N t + +/-- Gaussian-tail probability, in real rather than extended-nonnegative-real notation. -/ +def gaussianTail (r : ℝ) : ℝ := + (gaussianReal 0 1 {x : ℝ | r ≤ |x|}).toReal + +/-- The Gaussian excess constant at threshold twice the parameter. -/ +def excessConstant (K : ℝ) : ℝ := + (1 / 16 : ℝ) * ∫ x : ℝ, max (|x| - 2 * K) 0 ∂gaussianReal 0 1 + +/-- The density exp(-w) on the positive half-line. -/ +def exponentialLaw : Measure ℝ := expMeasure 1 + +/-- The law of the square of a standard real Gaussian. -/ +def gaussianSquareLaw : Measure ℝ := (gaussianReal 0 1).map (fun x : ℝ => x ^ 2) + +theorem main_general (μ : Measure ℝ) (hμ : MultiplierHypotheses μ) : + ¬ FiniteDimensional ℝ (productSpan μ) ∧ + ∀ N : Seminorm ℝ (productSpan μ), + IsEquivalentNorm (productSpan μ) N → ¬ IsAUC (productSpan μ) N := by + sorry + +theorem main_exponential (t : ℝ) (ht : 0 < t) : + (7 * t / 30) * excessConstant (10 / t) ≤ + averagedMidpointModulus (productSpan exponentialLaw) + (normSeminorm ℝ (productSpan exponentialLaw)) t ∧ + 0 < (7 * t / 30) * excessConstant (10 / t) := by + sorry + +theorem main_gaussian_24 (t : ℝ) (ht : 0 < t) : + gaussianTail (4 * Real.sqrt 2 * (2 + Real.sqrt 2) / t) / 8 ≤ + averagedMidpointModulus (productSpan gaussianSquareLaw) + (normSeminorm ℝ (productSpan gaussianSquareLaw)) t ∧ + 0 < gaussianTail (4 * Real.sqrt 2 * (2 + Real.sqrt 2) / t) / 8 := by + sorry + +theorem main_gaussian_12 (t : ℝ) (ht : 0 < t) : + gaussianTail (8 * Real.sqrt 6 / t) / 4 ≤ + averagedMidpointModulus (productSpan gaussianSquareLaw) + (normSeminorm ℝ (productSpan gaussianSquareLaw)) t ∧ + 0 < gaussianTail (8 * Real.sqrt 6 / t) / 4 := by + sorry + +end IndependentProducts + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IndependentProducts.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.IndependentProducts.main_general`, `OAI.IndependentProducts.main_exponential`, `OAI.IndependentProducts.main_gaussian_24`, `OAI.IndependentProducts.main_gaussian_12` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/independent-products/solution/closure.txt b/tasks/independent-products/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e8808ce08f405dc26c30c1ee418c52abf6437d5a --- /dev/null +++ b/tasks/independent-products/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.Analysis.ProductSpaces.AffineBounds +OAI.Analysis.ProductSpaces.ClosedTails +OAI.Analysis.ProductSpaces.CoefficientBounds +OAI.Analysis.ProductSpaces.CoefficientLaw +OAI.Analysis.ProductSpaces.ConditionalBounds +OAI.Analysis.ProductSpaces.ExponentialExcess +OAI.Analysis.ProductSpaces.ExponentialLaw +OAI.Analysis.ProductSpaces.ExponentialMixture +OAI.Analysis.ProductSpaces.FiniteHeads +OAI.Analysis.ProductSpaces.GaussianBounds +OAI.Analysis.ProductSpaces.GaussianExcess +OAI.Analysis.ProductSpaces.GaussianMoments +OAI.Analysis.ProductSpaces.Main +OAI.Analysis.ProductSpaces.MidpointModulus +OAI.Analysis.ProductSpaces.Model +OAI.Analysis.ProductSpaces.PathMoments +OAI.Analysis.ProductSpaces.RandomSigns +OAI.Analysis.ProductSpaces.Resampling +OAI.Analysis.ProductSpaces.ScalarBounds +OAI.Analysis.ProductSpaces.TailCoefficients +OAI.Analysis.ProductSpaces.TreeObstruction +OAI.Analysis.ProductSpaces.WeakNullity diff --git a/tasks/independent-products/solution/reference.py b/tasks/independent-products/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/independent-products/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/independent-products/solution/solve.sh b/tasks/independent-products/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..215e18a4cd0860fdedbf5dddb09ff9e012a8e7e7 --- /dev/null +++ b/tasks/independent-products/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IndependentProducts, i.e. module OAI.Analysis.ProductSpaces.Main and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.ProductSpaces.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IndependentProducts" diff --git a/tasks/independent-products/task.toml b/tasks/independent-products/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8c27a6f80e9c26d05b720ce912f09a250bf37d06 --- /dev/null +++ b/tasks/independent-products/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/independent-products" +version = "1.0.0" +description = "Prove IndependentProducts (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IndependentProducts.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IndependentProducts" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.IndependentProducts.main_general", "OAI.IndependentProducts.main_exponential", "OAI.IndependentProducts.main_gaussian_24", "OAI.IndependentProducts.main_gaussian_12"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.ProductSpaces.Main" +reference_modules = 22 +reference_lean_bytes = 178152 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 656 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11860 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/independent-products/tests/Challenge.lean b/tasks/independent-products/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ce22548dc3c27f0344bd01b844aea9341999e626 --- /dev/null +++ b/tasks/independent-products/tests/Challenge.lean @@ -0,0 +1,120 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal Topology + +universe uX + +namespace IndependentProducts + +/-- The tree of finite sequences of positive integers. -/ +abbrev Vertex := List ℕ+ +/-- Coordinates are attached only to nonroot vertices. -/ +abbrev Edge := {v : Vertex // v ≠ []} +abbrev Sample := Edge → ℝ + +/-- The product law of independent copies of the multiplier. -/ +def productMeasure (μ : Measure ℝ) : Measure Sample := + Measure.infinitePi (fun _ : Edge => μ) + +/-- The nonroot prefix ending at position `j`. -/ +def pathPrefix (v : Vertex) (j : Fin v.length) : Edge := + ⟨v.take (j.val + 1), by + intro h + have hl := congrArg List.length h + simp only [List.length_take, List.length_nil] at hl + have := j.isLt + omega⟩ + +/-- Root product is the empty product 1; every other product uses the path prefixes. -/ +def pathProduct (v : Vertex) (ω : Sample) : ℝ := + ∏ j : Fin v.length, ω (pathPrefix v j) + +/-- The closed real L1 span of the path products. -/ +def productSpan (μ : Measure ℝ) : Submodule ℝ (Lp ℝ 1 (productMeasure μ)) := + (Submodule.span ℝ {f : Lp ℝ 1 (productMeasure μ) | ∃ v : Vertex, + (f : Sample → ℝ) =ᵐ[productMeasure μ] pathProduct v}).topologicalClosure + +/-- Positivity, nonconstancy, mean one, and finite second moment of the multiplier law. -/ +structure MultiplierHypotheses (μ : Measure ℝ) : Prop where + probability : IsProbabilityMeasure μ + positive : ∀ᵐ w ∂μ, 0 < w + nonconstant : ∀ c : ℝ, ¬ (∀ᵐ w ∂μ, w = c) + mean_one : ∫ w, w ∂μ = 1 + second_moment : MemLp (fun w : ℝ => w) 2 μ + +variable (X : Type uX) [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Closed subspaces of finite codimension, with respect to the inherited topology. -/ +def CofiniteSubspaces : Set (Submodule ℝ X) := + {F | IsClosed (F : Set X) ∧ FiniteDimensional ℝ (X ⧸ F)} + +/-- The averaged asymptotic midpoint modulus, with directions of norm at least 1. -/ +def averagedMidpointModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x : X, N x = 1 ∧ r = + sSup {a | ∃ F ∈ CofiniteSubspaces X, a = + sInf {b | ∃ y : X, y ∈ F ∧ 1 ≤ N y ∧ + b = (N (x + t • y) + N (x - t • y)) / 2 - 1}}} + +/-- The usual one-sided modulus, whose directions have norm exactly 1. -/ +def oneSidedModulus (N : Seminorm ℝ X) (t : ℝ) : ℝ := + sInf {r | ∃ x : X, N x = 1 ∧ r = + sSup {a | ∃ F ∈ CofiniteSubspaces X, a = + sInf {b | ∃ y : X, y ∈ F ∧ N y = 1 ∧ b = N (x + t • y) - 1}}} + +/-- A seminorm with these bounds is a genuine norm equivalent to the original norm. -/ +def IsEquivalentNorm (N : Seminorm ℝ X) : Prop := + ∃ a b : ℝ, 0 < a ∧ a ≤ b ∧ ∀ x, a * ‖x‖ ≤ N x ∧ N x ≤ b * ‖x‖ + +def IsAUC (N : Seminorm ℝ X) : Prop := ∀ t : ℝ, 0 < t → 0 < oneSidedModulus X N t + +/-- Gaussian-tail probability, in real rather than extended-nonnegative-real notation. -/ +def gaussianTail (r : ℝ) : ℝ := + (gaussianReal 0 1 {x : ℝ | r ≤ |x|}).toReal + +/-- The Gaussian excess constant at threshold twice the parameter. -/ +def excessConstant (K : ℝ) : ℝ := + (1 / 16 : ℝ) * ∫ x : ℝ, max (|x| - 2 * K) 0 ∂gaussianReal 0 1 + +/-- The density exp(-w) on the positive half-line. -/ +def exponentialLaw : Measure ℝ := expMeasure 1 + +/-- The law of the square of a standard real Gaussian. -/ +def gaussianSquareLaw : Measure ℝ := (gaussianReal 0 1).map (fun x : ℝ => x ^ 2) + +theorem main_general (μ : Measure ℝ) (hμ : MultiplierHypotheses μ) : + ¬ FiniteDimensional ℝ (productSpan μ) ∧ + ∀ N : Seminorm ℝ (productSpan μ), + IsEquivalentNorm (productSpan μ) N → ¬ IsAUC (productSpan μ) N := by + sorry + +theorem main_exponential (t : ℝ) (ht : 0 < t) : + (7 * t / 30) * excessConstant (10 / t) ≤ + averagedMidpointModulus (productSpan exponentialLaw) + (normSeminorm ℝ (productSpan exponentialLaw)) t ∧ + 0 < (7 * t / 30) * excessConstant (10 / t) := by + sorry + +theorem main_gaussian_24 (t : ℝ) (ht : 0 < t) : + gaussianTail (4 * Real.sqrt 2 * (2 + Real.sqrt 2) / t) / 8 ≤ + averagedMidpointModulus (productSpan gaussianSquareLaw) + (normSeminorm ℝ (productSpan gaussianSquareLaw)) t ∧ + 0 < gaussianTail (4 * Real.sqrt 2 * (2 + Real.sqrt 2) / t) / 8 := by + sorry + +theorem main_gaussian_12 (t : ℝ) (ht : 0 < t) : + gaussianTail (8 * Real.sqrt 6 / t) / 4 ≤ + averagedMidpointModulus (productSpan gaussianSquareLaw) + (normSeminorm ℝ (productSpan gaussianSquareLaw)) t ∧ + 0 < gaussianTail (8 * Real.sqrt 6 / t) / 4 := by + sorry + +end IndependentProducts + +end + +end OAI diff --git a/tasks/independent-products/tests/grade.py b/tasks/independent-products/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/independent-products/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/independent-products/tests/task.json b/tasks/independent-products/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9b8060dff64f53d62687f4e178e88c621b6f5acc --- /dev/null +++ b/tasks/independent-products/tests/task.json @@ -0,0 +1,18 @@ +{ + "challenge": "IndependentProducts", + "comparator": { + "theorem_names": [ + "OAI.IndependentProducts.main_general", + "OAI.IndependentProducts.main_exponential", + "OAI.IndependentProducts.main_gaussian_24", + "OAI.IndependentProducts.main_gaussian_12" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10960 +} \ No newline at end of file diff --git a/tasks/independent-products/tests/test.sh b/tasks/independent-products/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/independent-products/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/independent-sets/environment/Dockerfile b/tasks/independent-sets/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/independent-sets/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/independent-sets/environment/fetch_mathlib.sh b/tasks/independent-sets/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/independent-sets/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/independent-sets/environment/lake-manifest.json b/tasks/independent-sets/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/independent-sets/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/independent-sets/environment/lakefile.lean b/tasks/independent-sets/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/independent-sets/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/independent-sets/environment/lean_setup.sh b/tasks/independent-sets/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/independent-sets/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/independent-sets/environment/pack_submission.py b/tasks/independent-sets/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/independent-sets/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/independent-sets/instruction.md b/tasks/independent-sets/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fad8d9ddafa88b0d6e647685a4b31dcbbda16bfc --- /dev/null +++ b/tasks/independent-sets/instruction.md @@ -0,0 +1,135 @@ +# openai/math challenge `IndependentSets` (family 106) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 106 of the release, *Hardness of coloring three-colorable graphs* +(Theoretical computer science). The family as a whole: It is NP-hard to color a three-colorable graph using any fixed number $c\ge3$ of colors. More strongly, for every fixed $0<\delta<1/3$, a deterministic polynomial-time reduction from $3$SAT produces simple unweighted graphs that are three-colorable in the satisfiable case and have no independent set of size $\delta n$ otherwise, where $n$ is the number of vertices. + +The challenge is `IndependentSets`, also at `/opt/openai-math/challenges/IndependentSets.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace LargeIndependentSets + +structure Literal where + name : ℕ + positive : Bool + deriving DecidableEq + +structure Formula where + clauses : List (List Literal) + width : ∀ C ∈ clauses, C.length ≤ 3 + +def Formula.Satisfiable (φ : Formula) : Prop := + ∃ assignment : ℕ → Bool, ∀ C ∈ φ.clauses, + ∃ l ∈ C, assignment l.name = l.positive + +/-- Binary framing: `true,b` for a payload bit and `false` as terminator. -/ +def frame : List Bool → List Bool + | [] => [false] + | b :: bs => true :: b :: frame bs + +def nameBits (n : ℕ) : List Bool := frame n.bits + +def literalBits (l : Literal) : List Bool := l.positive :: nameBits l.name + +def clauseBits (C : List Literal) : List Bool := + nameBits C.length ++ C.flatMap literalBits + +def formulaBits (φ : Formula) : List Bool := + nameBits φ.clauses.length ++ φ.clauses.flatMap clauseBits + +/-- A nonempty, finite, simple, undirected, unweighted graph. -/ +structure Graph where + vertices : ℕ + nonempty : 0 < vertices + adj : Fin vertices → Fin vertices → Bool + symm : ∀ u v, adj u v = adj v u + loopless : ∀ u, adj u u = false + +def Graph.Independent (G : Graph) (S : Finset (Fin G.vertices)) : Prop := + ∀ u ∈ S, ∀ v ∈ S, u ≠ v → G.adj u v = false + +instance (G : Graph) (S : Finset (Fin G.vertices)) : Decidable (G.Independent S) := + inferInstanceAs (Decidable (∀ u ∈ S, ∀ v ∈ S, u ≠ v → G.adj u v = false)) + +def Graph.independenceNumber (G : Graph) : ℕ := + ((Finset.univ : Finset (Fin G.vertices)).powerset.filter G.Independent).sup Finset.card + +def Graph.ThreeColorable (G : Graph) : Prop := + ∃ color : Fin G.vertices → Fin 3, + ∀ u v, G.adj u v = true → color u ≠ color v + +/-- Full explicit adjacency matrix, row-major, with binary vertex count. -/ +def graphBits (G : Graph) : List Bool := + nameBits G.vertices ++ (List.finRange G.vertices).flatMap + (fun u => (List.finRange G.vertices).map (G.adj u)) + +open scoped Classical +noncomputable section + +/-- Polynomial-time graph reduction with a real independence-ratio threshold. -/ +structure RealGraphReduction (δ : ℝ) where + reduce : List Bool → Graph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) graphBits reduce + finiteAlphabets : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + outputBound : Polynomial ℕ + outputSize : ∀ b, (graphBits (reduce b)).length ≤ outputBound.eval b.length + completeness : ∀ φ : Formula, φ.Satisfiable → (reduce (formulaBits φ)).ThreeColorable + soundness : ∀ φ : Formula, ¬φ.Satisfiable → + ((reduce (formulaBits φ)).independenceNumber : ℝ) < + δ * (reduce (formulaBits φ)).vertices + +/-- Real-threshold graph reduction with explicit binary runtime and output-size bounds. -/ +theorem mainTheoremReal : + ∀ δ : ℝ, 0 < δ → δ < 1 / 3 → Nonempty (RealGraphReduction δ) := by + sorry + +end +end LargeIndependentSets + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IndependentSets.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LargeIndependentSets.mainTheoremReal` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/independent-sets/solution/closure.txt b/tasks/independent-sets/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..78982de8727b0cded6102bd38200d7b1da1cc0f3 --- /dev/null +++ b/tasks/independent-sets/solution/closure.txt @@ -0,0 +1,454 @@ +OAI.Combinatorics.IndependentSets.Encoding.BinaryCoordinates +OAI.Combinatorics.IndependentSets.Encoding.BinaryEvents +OAI.Combinatorics.IndependentSets.Encoding.BinaryNameTables +OAI.Combinatorics.IndependentSets.Encoding.BinaryNormalize +OAI.Combinatorics.IndependentSets.Encoding.BinarySyntax +OAI.Combinatorics.IndependentSets.Encoding.BitsValue +OAI.Combinatorics.IndependentSets.Encoding.Bounds +OAI.Combinatorics.IndependentSets.Encoding.Completion +OAI.Combinatorics.IndependentSets.Encoding.Concrete +OAI.Combinatorics.IndependentSets.Encoding.Encoding +OAI.Combinatorics.IndependentSets.Encoding.FinalTableFormula +OAI.Combinatorics.IndependentSets.Encoding.FormulaEncoding +OAI.Combinatorics.IndependentSets.Encoding.GameEncoding +OAI.Combinatorics.IndependentSets.Encoding.GapFormula +OAI.Combinatorics.IndependentSets.Encoding.GeometryExpr +OAI.Combinatorics.IndependentSets.Encoding.GraphPrinter +OAI.Combinatorics.IndependentSets.Encoding.GraphTableComplexity +OAI.Combinatorics.IndependentSets.Encoding.LogSum +OAI.Combinatorics.IndependentSets.Encoding.Normalizer +OAI.Combinatorics.IndependentSets.Encoding.Occurrences +OAI.Combinatorics.IndependentSets.Encoding.PortTableEncoding +OAI.Combinatorics.IndependentSets.Encoding.Target +OAI.Combinatorics.IndependentSets.Encoding.TargetFormula +OAI.Combinatorics.IndependentSets.Encoding.TargetLCExpr +OAI.Combinatorics.IndependentSets.Expansion.Capped +OAI.Combinatorics.IndependentSets.Expansion.CayleySpectral +OAI.Combinatorics.IndependentSets.Expansion.CayleyTailCount +OAI.Combinatorics.IndependentSets.Expansion.CloudRounding +OAI.Combinatorics.IndependentSets.Expansion.DegreeReplacement +OAI.Combinatorics.IndependentSets.Expansion.ExpanderFamily +OAI.Combinatorics.IndependentSets.Expansion.ExpanderRowControl +OAI.Combinatorics.IndependentSets.Expansion.ExpanderTableEnumeration +OAI.Combinatorics.IndependentSets.Expansion.ExpanderTableWords +OAI.Combinatorics.IndependentSets.Expansion.ExpanderTables +OAI.Combinatorics.IndependentSets.Expansion.Expanders +OAI.Combinatorics.IndependentSets.Expansion.Finite +OAI.Combinatorics.IndependentSets.Expansion.Finite2 +OAI.Combinatorics.IndependentSets.Expansion.GraphRounding +OAI.Combinatorics.IndependentSets.Expansion.Indicators +OAI.Combinatorics.IndependentSets.Expansion.LazySmoothing +OAI.Combinatorics.IndependentSets.Expansion.LazySpectral +OAI.Combinatorics.IndependentSets.Expansion.Overlay +OAI.Combinatorics.IndependentSets.Expansion.PortTableLookup +OAI.Combinatorics.IndependentSets.Expansion.PortTables +OAI.Combinatorics.IndependentSets.Expansion.PoweringDecoding +OAI.Combinatorics.IndependentSets.Expansion.PoweringEnumeration +OAI.Combinatorics.IndependentSets.Expansion.PoweringFieldPlan +OAI.Combinatorics.IndependentSets.Expansion.PoweringGap +OAI.Combinatorics.IndependentSets.Expansion.PoweringGlobalConfiguration +OAI.Combinatorics.IndependentSets.Expansion.PoweringInitializeFrame +OAI.Combinatorics.IndependentSets.Expansion.PoweringLabels +OAI.Combinatorics.IndependentSets.Expansion.PoweringLazy +OAI.Combinatorics.IndependentSets.Expansion.PoweringNumeric +OAI.Combinatorics.IndependentSets.Expansion.PoweringOpinionTables +OAI.Combinatorics.IndependentSets.Expansion.PoweringOpinions +OAI.Combinatorics.IndependentSets.Expansion.PoweringPlanBudget +OAI.Combinatorics.IndependentSets.Expansion.PoweringPolynomialBudget +OAI.Combinatorics.IndependentSets.Expansion.PoweringPortReindex +OAI.Combinatorics.IndependentSets.Expansion.PoweringReturn +OAI.Combinatorics.IndependentSets.Expansion.PoweringRowData +OAI.Combinatorics.IndependentSets.Expansion.PoweringTableLayout +OAI.Combinatorics.IndependentSets.Expansion.PoweringTableSemantics +OAI.Combinatorics.IndependentSets.Expansion.PoweringTables +OAI.Combinatorics.IndependentSets.Expansion.PoweringTest +OAI.Combinatorics.IndependentSets.Expansion.PoweringWalks +OAI.Combinatorics.IndependentSets.Expansion.PoweringWitness +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingFamilyBridge +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingInternalRows +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingLazyWords +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingLevels +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingOverlayTables +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingOverlayWords +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingPaddingOffsets +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingPaddingTables +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingPaddingWords +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingRegularBounds +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingRegularLoopWords +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingRegularTables +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingRegularWords +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingStageMaps +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingTableSpectral +OAI.Combinatorics.IndependentSets.Expansion.PreprocessingTables +OAI.Combinatorics.IndependentSets.Expansion.Profiles +OAI.Combinatorics.IndependentSets.Expansion.Regularization +OAI.Combinatorics.IndependentSets.Expansion.RoundComputation +OAI.Combinatorics.IndependentSets.Expansion.Row +OAI.Combinatorics.IndependentSets.Expansion.SpectralReturn +OAI.Combinatorics.IndependentSets.Expansion.Supported +OAI.Combinatorics.IndependentSets.Expansion.Supported2 +OAI.Combinatorics.IndependentSets.Expansion.ZigzagSpectral +OAI.Combinatorics.IndependentSets.Fourier.Contexts +OAI.Combinatorics.IndependentSets.Fourier.Decoder +OAI.Combinatorics.IndependentSets.Fourier.EmptyContext +OAI.Combinatorics.IndependentSets.Fourier.FoldedEquation +OAI.Combinatorics.IndependentSets.Fourier.Folding +OAI.Combinatorics.IndependentSets.Fourier.Fourier +OAI.Combinatorics.IndependentSets.Fourier.FourierResponse +OAI.Combinatorics.IndependentSets.Fourier.Game +OAI.Combinatorics.IndependentSets.Fourier.GameDecoder +OAI.Combinatorics.IndependentSets.Fourier.Gap +OAI.Combinatorics.IndependentSets.Fourier.HonestTest +OAI.Combinatorics.IndependentSets.Fourier.LocalEquations +OAI.Combinatorics.IndependentSets.Fourier.NumberedStorage +OAI.Combinatorics.IndependentSets.Fourier.Soundness +OAI.Combinatorics.IndependentSets.Fourier.Walsh +OAI.Combinatorics.IndependentSets.Fourier.Walsh2 +OAI.Combinatorics.IndependentSets.Geometry.CoordinateAverage +OAI.Combinatorics.IndependentSets.Geometry.CoordinateDerivative +OAI.Combinatorics.IndependentSets.Geometry.CoordinateMean +OAI.Combinatorics.IndependentSets.Geometry.DeletedLayerEquiv +OAI.Combinatorics.IndependentSets.Geometry.EmbeddingLayerLaw +OAI.Combinatorics.IndependentSets.Geometry.GeometryAntipodes +OAI.Combinatorics.IndependentSets.Geometry.GeometryDistance +OAI.Combinatorics.IndependentSets.Geometry.GeometryInitialize +OAI.Combinatorics.IndependentSets.Geometry.GeometryLink +OAI.Combinatorics.IndependentSets.Geometry.GeometryLocations +OAI.Combinatorics.IndependentSets.Geometry.GeometryNaming +OAI.Combinatorics.IndependentSets.Geometry.GeometryOutput +OAI.Combinatorics.IndependentSets.Geometry.NoUniformlyBadFinitePatterns +OAI.Combinatorics.IndependentSets.Geometry.PatternInvariant +OAI.Combinatorics.IndependentSets.Geometry.RationalLaw +OAI.Combinatorics.IndependentSets.Geometry.RationalSimplexApproximation +OAI.Combinatorics.IndependentSets.Geometry.SumCoordinateNorm +OAI.Combinatorics.IndependentSets.Geometry.Uniform +OAI.Combinatorics.IndependentSets.Geometry.Witness +OAI.Combinatorics.IndependentSets.Machines.Alphabet +OAI.Combinatorics.IndependentSets.Machines.AmbientRelation +OAI.Combinatorics.IndependentSets.Machines.Basic +OAI.Combinatorics.IndependentSets.Machines.BitValue +OAI.Combinatorics.IndependentSets.Machines.Block +OAI.Combinatorics.IndependentSets.Machines.Command +OAI.Combinatorics.IndependentSets.Machines.ComputeTime +OAI.Combinatorics.IndependentSets.Machines.Copy +OAI.Combinatorics.IndependentSets.Machines.CoreInputTapes +OAI.Combinatorics.IndependentSets.Machines.Correct +OAI.Combinatorics.IndependentSets.Machines.Enumeration +OAI.Combinatorics.IndependentSets.Machines.Execution +OAI.Combinatorics.IndependentSets.Machines.ExprDrop +OAI.Combinatorics.IndependentSets.Machines.ExprTables +OAI.Combinatorics.IndependentSets.Machines.FinalCNFComputation +OAI.Combinatorics.IndependentSets.Machines.FinalCNFHeader +OAI.Combinatorics.IndependentSets.Machines.FinalCNFLoop +OAI.Combinatorics.IndependentSets.Machines.FinalCNFMachine +OAI.Combinatorics.IndependentSets.Machines.FinalCNFOutput +OAI.Combinatorics.IndependentSets.Machines.FinalCNFRow +OAI.Combinatorics.IndependentSets.Machines.FinalCNFRowPlan +OAI.Combinatorics.IndependentSets.Machines.FinalCNFRowTrace +OAI.Combinatorics.IndependentSets.Machines.FinalCNFStream +OAI.Combinatorics.IndependentSets.Machines.FinalLabel +OAI.Combinatorics.IndependentSets.Machines.FramedLen +OAI.Combinatorics.IndependentSets.Machines.GraphCounterFinish +OAI.Combinatorics.IndependentSets.Machines.GraphCounterModel +OAI.Combinatorics.IndependentSets.Machines.GraphCounterPrefix +OAI.Combinatorics.IndependentSets.Machines.GraphCounterStart +OAI.Combinatorics.IndependentSets.Machines.HeaderStates +OAI.Combinatorics.IndependentSets.Machines.Initialization +OAI.Combinatorics.IndependentSets.Machines.Label +OAI.Combinatorics.IndependentSets.Machines.LengthLoop +OAI.Combinatorics.IndependentSets.Machines.Machine +OAI.Combinatorics.IndependentSets.Machines.Machine2 +OAI.Combinatorics.IndependentSets.Machines.MachineAffineLookup +OAI.Combinatorics.IndependentSets.Machines.MachineAlphabetTransport +OAI.Combinatorics.IndependentSets.Machines.MachineAppend +OAI.Combinatorics.IndependentSets.Machines.MachineCeilingPower +OAI.Combinatorics.IndependentSets.Machines.MachineCloudCount +OAI.Combinatorics.IndependentSets.Machines.MachineCloudPadding +OAI.Combinatorics.IndependentSets.Machines.MachineCloudPrefix +OAI.Combinatorics.IndependentSets.Machines.MachineCloudRank +OAI.Combinatorics.IndependentSets.Machines.MachineCloudSelect +OAI.Combinatorics.IndependentSets.Machines.MachineCompare +OAI.Combinatorics.IndependentSets.Machines.MachineComposition +OAI.Combinatorics.IndependentSets.Machines.MachineControl +OAI.Combinatorics.IndependentSets.Machines.MachineCopy +OAI.Combinatorics.IndependentSets.Machines.MachineDrain +OAI.Combinatorics.IndependentSets.Machines.MachineDrainMany +OAI.Combinatorics.IndependentSets.Machines.MachineDummyRows +OAI.Combinatorics.IndependentSets.Machines.MachineEmbedding +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyAffine +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyBounds +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyCycle +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyLoop +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyProgram +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyTapes +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderFamilyTransfer +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRow +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRowDivision +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRowEmit +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRowFrames +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRowLookup +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderRowProgram +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderTable +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderTableBoundary +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderTableLoop +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderTableProgram +OAI.Combinatorics.IndependentSets.Machines.MachineExpanderTableRows +OAI.Combinatorics.IndependentSets.Machines.MachineFieldProfile +OAI.Combinatorics.IndependentSets.Machines.MachineFiniteAlphabet +OAI.Combinatorics.IndependentSets.Machines.MachineFiniteSequence +OAI.Combinatorics.IndependentSets.Machines.MachineFiniteTable +OAI.Combinatorics.IndependentSets.Machines.MachineFixedBlockMap +OAI.Combinatorics.IndependentSets.Machines.MachineFixedDivMod +OAI.Combinatorics.IndependentSets.Machines.MachineInitialHeaders +OAI.Combinatorics.IndependentSets.Machines.MachineLazyTableRuntime +OAI.Combinatorics.IndependentSets.Machines.MachineLogCounter +OAI.Combinatorics.IndependentSets.Machines.MachineLookup +OAI.Combinatorics.IndependentSets.Machines.MachineLookupCore +OAI.Combinatorics.IndependentSets.Machines.MachineLookupDiscard +OAI.Combinatorics.IndependentSets.Machines.MachineLookupSpec +OAI.Combinatorics.IndependentSets.Machines.MachineOverlayRows +OAI.Combinatorics.IndependentSets.Machines.MachinePaddedExpanderFamilyBounds +OAI.Combinatorics.IndependentSets.Machines.MachinePaddedExpanderFamilyFrames +OAI.Combinatorics.IndependentSets.Machines.MachinePaddedExpanderFamilyProgram +OAI.Combinatorics.IndependentSets.Machines.MachinePaddedOverlay +OAI.Combinatorics.IndependentSets.Machines.MachinePaddedOverlayRuntime +OAI.Combinatorics.IndependentSets.Machines.MachinePaddingBounds +OAI.Combinatorics.IndependentSets.Machines.MachinePaddingCertificate +OAI.Combinatorics.IndependentSets.Machines.MachinePaddingRows +OAI.Combinatorics.IndependentSets.Machines.MachinePortReindex +OAI.Combinatorics.IndependentSets.Machines.MachinePreservingLookupClean +OAI.Combinatorics.IndependentSets.Machines.MachineRegularDummyRow +OAI.Combinatorics.IndependentSets.Machines.MachineRegularExecutionBounds +OAI.Combinatorics.IndependentSets.Machines.MachineRegularFamily +OAI.Combinatorics.IndependentSets.Machines.MachineRegularLift +OAI.Combinatorics.IndependentSets.Machines.MachineRegularMetadata +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOriginalBody +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOriginalClean +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOriginalRow +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOwnerBody +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOwnerBodyBounds +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOwnerCleanup +OAI.Combinatorics.IndependentSets.Machines.MachineRegularOwnerProgram +OAI.Combinatorics.IndependentSets.Machines.MachineRegularTableBounds +OAI.Combinatorics.IndependentSets.Machines.MachineRegularTableRuntime +OAI.Combinatorics.IndependentSets.Machines.MachineRegularTableTrace +OAI.Combinatorics.IndependentSets.Machines.MachineRegularVertexBlock +OAI.Combinatorics.IndependentSets.Machines.MachineRepeat +OAI.Combinatorics.IndependentSets.Machines.MachineReverse +OAI.Combinatorics.IndependentSets.Machines.MachineSequential +OAI.Combinatorics.IndependentSets.Machines.MachineStateEquiv +OAI.Combinatorics.IndependentSets.Machines.MachineStateFrame +OAI.Combinatorics.IndependentSets.Machines.MachineSubroutine +OAI.Combinatorics.IndependentSets.Machines.MachineTableRows +OAI.Combinatorics.IndependentSets.Machines.MachineTransducer +OAI.Combinatorics.IndependentSets.Machines.MachineTransducerCopy +OAI.Combinatorics.IndependentSets.Machines.MachineTransfer +OAI.Combinatorics.IndependentSets.Machines.MachineUnaryAdd +OAI.Combinatorics.IndependentSets.Machines.MachineUnaryAffine +OAI.Combinatorics.IndependentSets.Machines.MachineUnaryCounter +OAI.Combinatorics.IndependentSets.Machines.MachineUnaryEqualityBit +OAI.Combinatorics.IndependentSets.Machines.MachineUnaryLess +OAI.Combinatorics.IndependentSets.Machines.MachineVertexPadding +OAI.Combinatorics.IndependentSets.Machines.OldSelectSteps +OAI.Combinatorics.IndependentSets.Machines.OwnerData +OAI.Combinatorics.IndependentSets.Machines.PCPGapMachine +OAI.Combinatorics.IndependentSets.Machines.PhasePolynomial +OAI.Combinatorics.IndependentSets.Machines.Placement +OAI.Combinatorics.IndependentSets.Machines.PoweringGlobalEnumeration +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineEqualityField +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineField +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineFinish +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineGlobal +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineInitialize +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineLoop +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineOuterLoop +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRelationField +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRotor +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRow +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRowBody +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRowHeaders +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineRuntime +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineTapes +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineVertex +OAI.Combinatorics.IndependentSets.Machines.PoweringMachineWord +OAI.Combinatorics.IndependentSets.Machines.PoweringRuntimeBudget +OAI.Combinatorics.IndependentSets.Machines.Printer +OAI.Combinatorics.IndependentSets.Machines.ProfileMachine +OAI.Combinatorics.IndependentSets.Machines.PushWord +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineBudget +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineCleanup +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineFinish +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineLoop +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineLoopData +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineReadClause +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineRows +OAI.Combinatorics.IndependentSets.Machines.RawInitialMachineStart +OAI.Combinatorics.IndependentSets.Machines.Remaining +OAI.Combinatorics.IndependentSets.Machines.Remaining2 +OAI.Combinatorics.IndependentSets.Machines.Represented +OAI.Combinatorics.IndependentSets.Machines.Restrict +OAI.Combinatorics.IndependentSets.Machines.Reverse +OAI.Combinatorics.IndependentSets.Machines.Runtime +OAI.Combinatorics.IndependentSets.Machines.SelectAlphabet +OAI.Combinatorics.IndependentSets.Machines.Structural +OAI.Combinatorics.IndependentSets.Machines.TableIterationFiniteAlphabet +OAI.Combinatorics.IndependentSets.Machines.Tape +OAI.Combinatorics.IndependentSets.Machines.Tape2 +OAI.Combinatorics.IndependentSets.Machines.Tape3 +OAI.Combinatorics.IndependentSets.Machines.TargetLCMachine +OAI.Combinatorics.IndependentSets.Machines.ValuePolynomial +OAI.Combinatorics.IndependentSets.Machines.VertexLabel +OAI.Combinatorics.IndependentSets.Main +OAI.Combinatorics.IndependentSets.Model +OAI.Combinatorics.IndependentSets.PCP.Addresses +OAI.Combinatorics.IndependentSets.PCP.AlphabetGraph +OAI.Combinatorics.IndependentSets.PCP.AlphabetGraphBounds +OAI.Combinatorics.IndependentSets.PCP.AlphabetReduction +OAI.Combinatorics.IndependentSets.PCP.AlphabetRetraction +OAI.Combinatorics.IndependentSets.PCP.Ambient +OAI.Combinatorics.IndependentSets.PCP.AmplificationIteration +OAI.Combinatorics.IndependentSets.PCP.AmplificationRound +OAI.Combinatorics.IndependentSets.PCP.AssignmentTester +OAI.Combinatorics.IndependentSets.PCP.Body +OAI.Combinatorics.IndependentSets.PCP.BoundedIteration +OAI.Combinatorics.IndependentSets.PCP.CircleRound +OAI.Combinatorics.IndependentSets.PCP.ClausePolynomial +OAI.Combinatorics.IndependentSets.PCP.ClauseVerifier +OAI.Combinatorics.IndependentSets.PCP.Cleanup +OAI.Combinatorics.IndependentSets.PCP.CloneGap +OAI.Combinatorics.IndependentSets.PCP.CodeComposition +OAI.Combinatorics.IndependentSets.PCP.CompareLoop +OAI.Combinatorics.IndependentSets.PCP.ConstraintGraph +OAI.Combinatorics.IndependentSets.PCP.Driver +OAI.Combinatorics.IndependentSets.PCP.EmitRows +OAI.Combinatorics.IndependentSets.PCP.Emitter +OAI.Combinatorics.IndependentSets.PCP.Enumeration +OAI.Combinatorics.IndependentSets.PCP.FinalBooleanVerifier +OAI.Combinatorics.IndependentSets.PCP.FinalCNF +OAI.Combinatorics.IndependentSets.PCP.FinalCNFPattern +OAI.Combinatorics.IndependentSets.PCP.FinalCNFTableAdapter +OAI.Combinatorics.IndependentSets.PCP.FinalCNFTemplate +OAI.Combinatorics.IndependentSets.PCP.Finish +OAI.Combinatorics.IndependentSets.PCP.Gap +OAI.Combinatorics.IndependentSets.PCP.GenericGraphTables +OAI.Combinatorics.IndependentSets.PCP.GeometryPointTable +OAI.Combinatorics.IndependentSets.PCP.GraphIterationBounds +OAI.Combinatorics.IndependentSets.PCP.GraphTables +OAI.Combinatorics.IndependentSets.PCP.InitialGraph +OAI.Combinatorics.IndependentSets.PCP.Input +OAI.Combinatorics.IndependentSets.PCP.LCTable +OAI.Combinatorics.IndependentSets.PCP.LabelCoverData +OAI.Combinatorics.IndependentSets.PCP.Lookup +OAI.Combinatorics.IndependentSets.PCP.LoopInitialization +OAI.Combinatorics.IndependentSets.PCP.Minimum +OAI.Combinatorics.IndependentSets.PCP.NameCompaction +OAI.Combinatorics.IndependentSets.PCP.PCPIteration +OAI.Combinatorics.IndependentSets.PCP.Queries +OAI.Combinatorics.IndependentSets.PCP.QueryIncidence +OAI.Combinatorics.IndependentSets.PCP.RawInitialTables +OAI.Combinatorics.IndependentSets.PCP.ReadRelation +OAI.Combinatorics.IndependentSets.PCP.Redirect +OAI.Combinatorics.IndependentSets.PCP.RoundGap +OAI.Combinatorics.IndependentSets.PCP.RoundTableGap +OAI.Combinatorics.IndependentSets.PCP.Semantics +OAI.Combinatorics.IndependentSets.PCP.Semantics2 +OAI.Combinatorics.IndependentSets.PCP.Setup +OAI.Combinatorics.IndependentSets.PCP.TableIteration +OAI.Combinatorics.IndependentSets.PCP.TargetLC +OAI.Combinatorics.IndependentSets.PCP.VerifierCNF +OAI.Combinatorics.IndependentSets.PCP.VertexPadding +OAI.Combinatorics.IndependentSets.Reduction.ArbitraryRealJunta +OAI.Combinatorics.IndependentSets.Reduction.AuxiliaryJointMeasurable +OAI.Combinatorics.IndependentSets.Reduction.Bits +OAI.Combinatorics.IndependentSets.Reduction.CellLaw +OAI.Combinatorics.IndependentSets.Reduction.Circle +OAI.Combinatorics.IndependentSets.Reduction.CircleCost +OAI.Combinatorics.IndependentSets.Reduction.ClampCube +OAI.Combinatorics.IndependentSets.Reduction.Cube +OAI.Combinatorics.IndependentSets.Reduction.DeletedProjection +OAI.Combinatorics.IndependentSets.Reduction.DiscreteBoundAuxiliary +OAI.Combinatorics.IndependentSets.Reduction.DyadicPrecision +OAI.Combinatorics.IndependentSets.Reduction.EnumerationSimple +OAI.Combinatorics.IndependentSets.Reduction.ExtendPartialIso +OAI.Combinatorics.IndependentSets.Reduction.ExtensionLaw +OAI.Combinatorics.IndependentSets.Reduction.FiniteNoise +OAI.Combinatorics.IndependentSets.Reduction.FiniteParameterSelection +OAI.Combinatorics.IndependentSets.Reduction.FiniteScan +OAI.Combinatorics.IndependentSets.Reduction.FloydLoop +OAI.Combinatorics.IndependentSets.Reduction.FrameNonempty +OAI.Combinatorics.IndependentSets.Reduction.Full +OAI.Combinatorics.IndependentSets.Reduction.FullAbsorptionSquare +OAI.Combinatorics.IndependentSets.Reduction.GraphReduction +OAI.Combinatorics.IndependentSets.Reduction.Heavy +OAI.Combinatorics.IndependentSets.Reduction.IndexedBlocks +OAI.Combinatorics.IndependentSets.Reduction.InfluenceSqParamMeasurable +OAI.Combinatorics.IndependentSets.Reduction.IntegerEdgeTest +OAI.Combinatorics.IndependentSets.Reduction.Law +OAI.Combinatorics.IndependentSets.Reduction.ListIndex +OAI.Combinatorics.IndependentSets.Reduction.MapEquiv +OAI.Combinatorics.IndependentSets.Reduction.Mix +OAI.Combinatorics.IndependentSets.Reduction.Mixed +OAI.Combinatorics.IndependentSets.Reduction.OccurrenceTuple +OAI.Combinatorics.IndependentSets.Reduction.PairEnergy +OAI.Combinatorics.IndependentSets.Reduction.Parameters +OAI.Combinatorics.IndependentSets.Reduction.RestrictionLawBad +OAI.Combinatorics.IndependentSets.Reduction.RowBitsEquiv +OAI.Combinatorics.IndependentSets.Reduction.SamplerParameters +OAI.Combinatorics.IndependentSets.Reduction.Simple +OAI.Combinatorics.IndependentSets.Reduction.SimplexLaw +OAI.Combinatorics.IndependentSets.Reduction.SliceDifferenceVariation +OAI.Combinatorics.IndependentSets.Reduction.Small +OAI.Combinatorics.IndependentSets.Reduction.SquareNorm +OAI.Combinatorics.IndependentSets.Reduction.StoredFloyd +OAI.Combinatorics.IndependentSets.Reduction.SubchainBase +OAI.Combinatorics.IndependentSets.Reduction.SubchainView +OAI.Combinatorics.IndependentSets.Reduction.SwapCoords +OAI.Combinatorics.IndependentSets.Reduction.SwapOccurrence +OAI.Combinatorics.IndependentSets.Reduction.TargetRead +OAI.Combinatorics.IndependentSets.Reduction.ThresholdDecidable +OAI.Combinatorics.IndependentSets.Reduction.Total +OAI.Combinatorics.IndependentSets.Reduction.UniformLaw +OAI.Combinatorics.IndependentSets.Reduction.WalkLength +OAI.Combinatorics.IndependentSets.Repetition.ActualGame +OAI.Combinatorics.IndependentSets.Repetition.Basic +OAI.Combinatorics.IndependentSets.Repetition.Basic2 +OAI.Combinatorics.IndependentSets.Repetition.CayleySampling +OAI.Combinatorics.IndependentSets.Repetition.Conditionals +OAI.Combinatorics.IndependentSets.Repetition.CoordinateCompletion +OAI.Combinatorics.IndependentSets.Repetition.DistributionIdentities +OAI.Combinatorics.IndependentSets.Repetition.Finite +OAI.Combinatorics.IndependentSets.Repetition.FiniteGame +OAI.Combinatorics.IndependentSets.Repetition.FiniteTrials +OAI.Combinatorics.IndependentSets.Repetition.KernelSampling +OAI.Combinatorics.IndependentSets.Repetition.LocalSimulation +OAI.Combinatorics.IndependentSets.Repetition.MaskedVariation +OAI.Combinatorics.IndependentSets.Repetition.Mixture +OAI.Combinatorics.IndependentSets.Repetition.Overlap +OAI.Combinatorics.IndependentSets.Repetition.PartialReveal +OAI.Combinatorics.IndependentSets.Repetition.Pinsker +OAI.Combinatorics.IndependentSets.Repetition.ProfileBounds +OAI.Combinatorics.IndependentSets.Repetition.ProfileCorrection +OAI.Combinatorics.IndependentSets.Repetition.QuestionMarginal +OAI.Combinatorics.IndependentSets.Repetition.Rectangle +OAI.Combinatorics.IndependentSets.Repetition.Rectangle2 +OAI.Combinatorics.IndependentSets.Repetition.Reindexing +OAI.Combinatorics.IndependentSets.Repetition.RepetitionUpper +OAI.Combinatorics.IndependentSets.Repetition.Reveal +OAI.Combinatorics.IndependentSets.Repetition.RevealFactorization +OAI.Combinatorics.IndependentSets.Repetition.Sampling +OAI.Combinatorics.IndependentSets.Repetition.Scalar +OAI.Combinatorics.IndependentSets.Repetition.ScalarCell +OAI.Combinatorics.IndependentSets.Repetition.ScalarSampleInfluence +OAI.Combinatorics.IndependentSets.Repetition.SelectedCompletionGame +OAI.Combinatorics.IndependentSets.Repetition.SelectedInformation +OAI.Combinatorics.IndependentSets.Repetition.SelectedJoint +OAI.Combinatorics.IndependentSets.Repetition.SelectedJointGame +OAI.Combinatorics.IndependentSets.Repetition.SelectedMarginal +OAI.Combinatorics.IndependentSets.Repetition.SelectedProfileBudget +OAI.Combinatorics.IndependentSets.Repetition.SelectedProfiles +OAI.Combinatorics.IndependentSets.Repetition.SelectionSequence +OAI.Combinatorics.IndependentSets.Repetition.SharedSampling +OAI.Combinatorics.IndependentSets.Repetition.SideInformation +OAI.Combinatorics.IndependentSets.Repetition.TotalVariation +OAI.Combinatorics.IndependentSets.Repetition.TraceLaw +OAI.Combinatorics.IndependentSets.Repetition.Value diff --git a/tasks/independent-sets/solution/reference.py b/tasks/independent-sets/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/independent-sets/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/independent-sets/solution/solve.sh b/tasks/independent-sets/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a09df04cca0d74b5d613a62f9e4baa6c5795995 --- /dev/null +++ b/tasks/independent-sets/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IndependentSets, i.e. module OAI.Combinatorics.IndependentSets.Main and the +# 454 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.IndependentSets.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IndependentSets" diff --git a/tasks/independent-sets/task.toml b/tasks/independent-sets/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3348b41588020b607b8df4f7a2558b88ec612471 --- /dev/null +++ b/tasks/independent-sets/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/independent-sets" +version = "1.0.0" +description = "Prove IndependentSets (openai/math family 106: Hardness of coloring three-colorable graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IndependentSets.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IndependentSets" +family = "106" +family_title = "Hardness of coloring three-colorable graphs" +subject = "Theoretical computer science" +theorems = ["OAI.LargeIndependentSets.mainTheoremReal"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.IndependentSets.Main" +reference_modules = 454 +reference_lean_bytes = 4478613 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1201 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15730 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/independent-sets/tests/Challenge.lean b/tasks/independent-sets/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..abd303379190bee16aebeb850981c36ba9415b52 --- /dev/null +++ b/tasks/independent-sets/tests/Challenge.lean @@ -0,0 +1,84 @@ +import Mathlib + +namespace OAI + +namespace LargeIndependentSets + +structure Literal where + name : ℕ + positive : Bool + deriving DecidableEq + +structure Formula where + clauses : List (List Literal) + width : ∀ C ∈ clauses, C.length ≤ 3 + +def Formula.Satisfiable (φ : Formula) : Prop := + ∃ assignment : ℕ → Bool, ∀ C ∈ φ.clauses, + ∃ l ∈ C, assignment l.name = l.positive + +/-- Binary framing: `true,b` for a payload bit and `false` as terminator. -/ +def frame : List Bool → List Bool + | [] => [false] + | b :: bs => true :: b :: frame bs + +def nameBits (n : ℕ) : List Bool := frame n.bits + +def literalBits (l : Literal) : List Bool := l.positive :: nameBits l.name + +def clauseBits (C : List Literal) : List Bool := + nameBits C.length ++ C.flatMap literalBits + +def formulaBits (φ : Formula) : List Bool := + nameBits φ.clauses.length ++ φ.clauses.flatMap clauseBits + +/-- A nonempty, finite, simple, undirected, unweighted graph. -/ +structure Graph where + vertices : ℕ + nonempty : 0 < vertices + adj : Fin vertices → Fin vertices → Bool + symm : ∀ u v, adj u v = adj v u + loopless : ∀ u, adj u u = false + +def Graph.Independent (G : Graph) (S : Finset (Fin G.vertices)) : Prop := + ∀ u ∈ S, ∀ v ∈ S, u ≠ v → G.adj u v = false + +instance (G : Graph) (S : Finset (Fin G.vertices)) : Decidable (G.Independent S) := + inferInstanceAs (Decidable (∀ u ∈ S, ∀ v ∈ S, u ≠ v → G.adj u v = false)) + +def Graph.independenceNumber (G : Graph) : ℕ := + ((Finset.univ : Finset (Fin G.vertices)).powerset.filter G.Independent).sup Finset.card + +def Graph.ThreeColorable (G : Graph) : Prop := + ∃ color : Fin G.vertices → Fin 3, + ∀ u v, G.adj u v = true → color u ≠ color v + +/-- Full explicit adjacency matrix, row-major, with binary vertex count. -/ +def graphBits (G : Graph) : List Bool := + nameBits G.vertices ++ (List.finRange G.vertices).flatMap + (fun u => (List.finRange G.vertices).map (G.adj u)) + +open scoped Classical +noncomputable section + +/-- Polynomial-time graph reduction with a real independence-ratio threshold. -/ +structure RealGraphReduction (δ : ℝ) where + reduce : List Bool → Graph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) graphBits reduce + finiteAlphabets : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + outputBound : Polynomial ℕ + outputSize : ∀ b, (graphBits (reduce b)).length ≤ outputBound.eval b.length + completeness : ∀ φ : Formula, φ.Satisfiable → (reduce (formulaBits φ)).ThreeColorable + soundness : ∀ φ : Formula, ¬φ.Satisfiable → + ((reduce (formulaBits φ)).independenceNumber : ℝ) < + δ * (reduce (formulaBits φ)).vertices + +/-- Real-threshold graph reduction with explicit binary runtime and output-size bounds. -/ +theorem mainTheoremReal : + ∀ δ : ℝ, 0 < δ → δ < 1 / 3 → Nonempty (RealGraphReduction δ) := by + sorry + +end +end LargeIndependentSets + +end OAI diff --git a/tasks/independent-sets/tests/grade.py b/tasks/independent-sets/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/independent-sets/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/independent-sets/tests/task.json b/tasks/independent-sets/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c2aa8fb4da37c3cb634e01b59fe183aa0bce1748 --- /dev/null +++ b/tasks/independent-sets/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "IndependentSets", + "comparator": { + "theorem_names": [ + "OAI.LargeIndependentSets.mainTheoremReal" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14830 +} \ No newline at end of file diff --git a/tasks/independent-sets/tests/test.sh b/tasks/independent-sets/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/independent-sets/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/individual-strong-infiniteness/environment/Dockerfile b/tasks/individual-strong-infiniteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/individual-strong-infiniteness/environment/fetch_mathlib.sh b/tasks/individual-strong-infiniteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/individual-strong-infiniteness/environment/lake-manifest.json b/tasks/individual-strong-infiniteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/individual-strong-infiniteness/environment/lakefile.lean b/tasks/individual-strong-infiniteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/individual-strong-infiniteness/environment/lean_setup.sh b/tasks/individual-strong-infiniteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/individual-strong-infiniteness/environment/pack_submission.py b/tasks/individual-strong-infiniteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/individual-strong-infiniteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/individual-strong-infiniteness/instruction.md b/tasks/individual-strong-infiniteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8a6376ec080b28fd9c08baa64ba9dff6577d7f4e --- /dev/null +++ b/tasks/individual-strong-infiniteness/instruction.md @@ -0,0 +1,384 @@ +# openai/math challenge `IndividualStrongInfiniteness` (family 303) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 303 of the release, *From ordinary to strong pure infiniteness* +(Operator algebras). The family as a whole: Resolves the ordinary-to-strong pure-infiniteness question of Kirchberg and R{\o}rdam for complex $C^*$-algebras. For exact algebras, proper infiniteness of one fixed finite amplification of every positive element also suffices. Consequently, every separable nuclear algebra with this property absorbs $\mathcal O_\infty$, without unitality or simplicity assumptions. + +The challenge is `IndividualStrongInfiniteness`, also at `/opt/openai-math/challenges/IndividualStrongInfiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Filter +open scoped Topology CStarAlgebra ComplexOrder InnerProductSpace + +namespace MainGap +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +def scalarCorner (h : A) : CStarMatrix (Fin 1) (Fin 1) A := + CStarMatrix.ofMatrix (fun _ _ => h) + +def doubleCorner (h : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix (Matrix.diagonal (fun _ => h)) + +def Diagonalization (a b c : A) (ε : ℝ) : Prop := + ∃ s t : A, + ‖star s * a * s - a‖ < ε ∧ + ‖star t * b * t - b‖ < ε ∧ + ‖star s * c * t‖ < ε + +def UnrestrictedDiagonalization (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ c : A, ∀ ε : ℝ, 0 < ε → + Diagonalization a b c ε + +def StronglyPurelyInfinite (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ x y : A, 0 ≤ x → 0 ≤ y → ∀ ε : ℝ, 0 < ε → + Diagonalization (x * x) (y * y) (x * y) ε + +end MainGap + +noncomputable section +open Filter +open scoped Topology +namespace MainGap.Stable +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +abbrev Mat (A : Type*) (n : ℕ) := CStarMatrix (Fin n) (Fin n) A + +def pad {n m : ℕ} (_ : n ≤ m) (x : Mat A n) : Mat A m := + CStarMatrix.ofMatrix fun i j => + if hi : i.val < n then if hj : j.val < n then x ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0 + +@[simp] lemma pad_entry {n m : ℕ} (h : n ≤ m) (x : Mat A n) (i j : Fin m) : + pad h x i j = (if hi : i.val < n then if hj : j.val < n then x ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0) := rfl + +@[simp] lemma pad_apply {n m : ℕ} (h : n ≤ m) (x : Mat A n) (i j : Fin n) : + pad h x (Fin.castLE h i) (Fin.castLE h j) = x i j := by simp [pad_entry] + +lemma sum_pad {n m : ℕ} (h : n ≤ m) {B : Type*} [AddCommMonoid B] (f : Fin n → B) : + ∑ k : Fin m, (if hk : k.val < n then f ⟨k,hk⟩ else 0) = ∑ k : Fin n, f k := by + classical + symm + apply Finset.sum_bij_ne_zero (fun i _ _ => Fin.castLE h i) + · simp + · intro i _ _ j _ _ hij + exact Fin.ext (congrArg (fun k : Fin m => k.val) hij) + · intro j _ hj0 + have hj : j.val < n := by + by_contra hn + simp [hn] at hj0 + exact ⟨⟨j,hj⟩, Finset.mem_univ _, by simpa [hj] using hj0, rfl⟩ + · intro i _ _ + simp + +lemma pad_mul {n m : ℕ} (h : n ≤ m) (x y : Mat A n) : + pad h (x*y) = pad h x * pad h y := by + ext i j + by_cases hi : i.val < n <;> by_cases hj : j.val < n + · simp only [pad_entry, dite_eq_left hi, dite_eq_left hj, + CStarMatrix.mul_apply] + rw [← sum_pad h (fun k => x ⟨i,hi⟩ k * y k ⟨j,hj⟩)] + apply Finset.sum_congr rfl + intro k _ + by_cases hk : k.val < n <;> simp [hk] + · simp [pad_entry, hi, hj, CStarMatrix.mul_apply] + · simp [pad_entry, hi, CStarMatrix.mul_apply] + · simp [pad_entry, hi, CStarMatrix.mul_apply] + +def padHom {n m : ℕ} (h : n ≤ m) : Mat A n →⋆ₙₐ[ℂ] Mat A m where + toFun := pad h + map_zero' := by ext i j; simp [pad_entry] + map_add' x y := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj] + map_mul' := pad_mul h + map_smul' c x := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj] + map_star' x := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj, CStarMatrix.star_apply] + +lemma pad_injective {n m : ℕ} (h : n ≤ m) : Function.Injective (pad (A := A) h) := by + intro x y hxy + ext i j + have hh := congrArg (fun z : Mat A m => z (Fin.castLE h i) (Fin.castLE h j)) hxy + simpa using hh + +lemma norm_pad {n m : ℕ} (h : n ≤ m) (x : Mat A n) : ‖pad h x‖ = ‖x‖ := + NonUnitalStarAlgHom.norm_map (padHom h) (pad_injective h) x + +lemma pad_self (n : ℕ) (x : Mat A n) : pad le_rfl x = x := by + ext i j + simp [pad_entry] + +lemma pad_pad {n m k : ℕ} (h : n ≤ m) (h' : m ≤ k) (x : Mat A n) : + pad h' (pad h x) = pad (h.trans h') x := by + ext i j + by_cases hi : i.val < n <;> by_cases hj : j.val < n + · have hi' : i.val < m := lt_of_lt_of_le hi h + have hj' : j.val < m := lt_of_lt_of_le hj h + simp [pad_entry, hi, hj, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hj, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hi', hj'] + +instance pad_directedSystem : DirectedSystem (Mat A) (fun _ _ h => padHom h) where + map_self := fun {_} x => pad_self _ x + map_map := fun {_ _ _} h h' x => pad_pad h h' x + +abbrev Algebraic (A : Type*) [NonUnitalCStarAlgebra A] := + DirectLimit (Mat A) (fun _ _ h => padHom h) + +local instance matLinear (n m : ℕ) : + LinearMapClass (Mat A n →⋆ₙₐ[ℂ] Mat A m) ℂ (Mat A n) (Mat A m) where + map_add f x y := f.map_add x y + map_smulₛₗ f c x := f.map_smul c x + +instance : Module ℂ (Algebraic A) := DirectLimit.instModule + +instance : Norm (Algebraic A) where + norm := DirectLimit.lift _ (fun _ x => ‖x‖) (fun _ _ h x => (norm_pad h x).symm) + +@[simp] lemma norm_mk (n : ℕ) (x : Mat A n) : + ‖(⟦⟨n,x⟩⟧ : Algebraic A)‖ = ‖x‖ := rfl + +lemma normedCore : NormedSpace.Core ℂ (Algebraic A) where + norm_nonneg := DirectLimit.induction _ fun n x => norm_nonneg x + norm_smul c := DirectLimit.induction _ fun n x => by + rw [DirectLimit.smul_def, norm_mk, norm_mk, norm_smul] + norm_triangle := DirectLimit.induction₂ _ fun n x y => by + rw [DirectLimit.add_def, norm_mk, norm_mk, norm_mk] + exact norm_add_le x y + norm_eq_zero_iff := DirectLimit.induction _ fun n x => by + rw [norm_mk, norm_eq_zero] + constructor + · rintro rfl + exact (DirectLimit.zero_def (f := fun _ _ h => padHom (A := A) h) n).symm + · intro h + apply pad_injective (le_rfl : n ≤ n) + have hi := DirectLimit.mk_injective (fun _ _ h => padHom (A := A) h) (fun _ _ h => pad_injective h) n + exact congrArg (pad le_rfl) (hi (h.trans (DirectLimit.zero_def (f := fun _ _ h => padHom (A := A) h) n))) + +instance : NormedAddCommGroup (Algebraic A) := .ofCore (𝕜 := ℂ) (normedCore (A := A)) +instance : NormedSpace ℂ (Algebraic A) := .ofCore (normedCore (A := A)) +instance : NonUnitalNormedRing (Algebraic A) where + dist_eq _ _ := rfl + norm_mul_le := DirectLimit.induction₂ _ fun n x y => by + rw [DirectLimit.mul_def, norm_mk, norm_mk, norm_mk] + exact norm_mul_le x y +instance : CStarRing (Algebraic A) where + norm_mul_self_le := DirectLimit.induction _ fun n x => by + rw [DirectLimit.star_def, DirectLimit.mul_def, norm_mk, norm_mk] + exact CStarRing.norm_mul_self_le x + +def cornerAlg (n : ℕ) : Mat A n →⋆ₙₐ[ℂ] Algebraic A where + __ := DirectLimit.NonUnitalAlgebra.of (Mat A) (fun _ _ h => padHom h) n + map_star' _ := rfl + +@[simp] lemma cornerAlg_apply (n : ℕ) (x : Mat A n) : + cornerAlg n x = (⟦⟨n,x⟩⟧ : Algebraic A) := rfl + +lemma cornerAlg_isometry (n : ℕ) : Isometry (cornerAlg (A := A) n) := + AddMonoidHomClass.isometry_of_norm (cornerAlg n) (fun _ => rfl) + +abbrev Stabilization (A : Type*) [NonUnitalCStarAlgebra A] := UniformSpace.Completion (Algebraic A) + +local instance algebraicTopology : TopologicalSpace (Algebraic A) := + (inferInstance : PseudoMetricSpace (Algebraic A)).toUniformSpace.toTopologicalSpace + +open UniformSpace +open UniformSpace.Completion + +instance : Mul (Stabilization A) := + ⟨Function.curry <| (isDenseInducing_coe.prodMap isDenseInducing_coe).extend + ((↑) ∘ Function.uncurry (· * · : Algebraic A → Algebraic A → Algebraic A))⟩ + +@[simp, norm_cast] lemma coe_mul_stable (x y : Algebraic A) : + ((x*y : Algebraic A) : Stabilization A) = (x : Stabilization A) * (y : Stabilization A) := + ((isDenseInducing_coe.prodMap isDenseInducing_coe).extend_eq + ((continuous_coe _).comp continuous_mul) (x,y)).symm + +instance : ContinuousMul (Stabilization A) where + continuous_mul := by + let m := (AddMonoidHom.mul : Algebraic A →+ Algebraic A →+ Algebraic A).compr₂ toCompl + have hh : Continuous fun p : Algebraic A × Algebraic A => m p.1 p.2 := + (continuous_coe _).comp continuous_mul + have di : IsDenseInducing (toCompl : Algebraic A → Stabilization A) := isDenseInducing_coe + exact di.extend_Z_bilin di hh + +instance : NonUnitalRing (Stabilization A) where + __ : AddCommGroup (Stabilization A) := inferInstance + zero_mul x := Completion.induction_on x (isClosed_eq (by fun_prop) continuous_const) + fun x => by rw [← coe_zero, ← coe_mul_stable, zero_mul] + mul_zero x := Completion.induction_on x (isClosed_eq (by fun_prop) continuous_const) + fun x => by rw [← coe_zero, ← coe_mul_stable, mul_zero] + mul_assoc x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, mul_assoc] + left_distrib x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_add, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_add, mul_add] + right_distrib x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_add, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_add, add_mul] + +instance : NonUnitalNormedRing (Stabilization A) where + dist_eq := dist_eq_norm_neg_add + norm_mul_le x y := Completion.induction_on₂ x y + (isClosed_le (by fun_prop) (by fun_prop)) fun x y => by + simpa only [← coe_mul_stable, norm_coe] using norm_mul_le x y + +instance : Star (Stabilization A) := ⟨Completion.map (star : Algebraic A → Algebraic A)⟩ + +@[simp, norm_cast] lemma coe_star_stable (x : Algebraic A) : + ((star x : Algebraic A) : Stabilization A) = star (x : Stabilization A) := + (Completion.map_coe star_isometry.uniformContinuous x).symm + +instance : ContinuousStar (Stabilization A) where + continuous_star := Completion.continuous_map + +instance : StarRing (Stabilization A) where + star_involutive x := Completion.induction_on x + (isClosed_eq (by fun_prop) continuous_id) fun x => by + rw [← coe_star_stable, ← coe_star_stable, star_star] + star_add x y := Completion.induction_on₂ x y + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y => by + rw [← coe_add, ← coe_star_stable, ← coe_star_stable, ← coe_star_stable, ← coe_add, star_add] + star_mul x y := Completion.induction_on₂ x y + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y => by + rw [← coe_mul_stable, ← coe_star_stable, ← coe_star_stable, ← coe_star_stable, + ← coe_mul_stable, star_mul] + +instance : CStarRing (Stabilization A) where + norm_mul_self_le x := Completion.induction_on x + (isClosed_le (by fun_prop) (by fun_prop)) fun x => by + simpa only [← coe_star_stable, ← coe_mul_stable, norm_coe] using CStarRing.norm_mul_self_le x + +instance : IsScalarTower ℂ (Stabilization A) (Stabilization A) where + smul_assoc c x y := by + change (c • x) * y = c • (x*y) + refine Completion.induction_on₂ x y ?_ ?_ + · exact isClosed_eq ((continuous_fst.const_smul c).mul continuous_snd) + ((continuous_fst.mul continuous_snd).const_smul c) + · intro x y + rw [← coe_smul, ← coe_mul_stable, ← coe_mul_stable, ← coe_smul, smul_mul_assoc] + +instance : SMulCommClass ℂ (Stabilization A) (Stabilization A) where + smul_comm c x y := by + change c • (x*y) = x * (c • y) + refine Completion.induction_on₂ x y ?_ ?_ + · exact isClosed_eq ((continuous_fst.mul continuous_snd).const_smul c) + (continuous_fst.mul (continuous_snd.const_smul c)) + · intro x y + rw [← coe_mul_stable, ← coe_smul, ← coe_smul, ← coe_mul_stable, mul_smul_comm] + +instance : StarModule ℂ (Stabilization A) where + star_smul c x := by + refine Completion.induction_on x ?_ ?_ + · exact isClosed_eq (continuous_star.comp (continuous_const_smul c)) + (continuous_star.const_smul (star c)) + · intro x + rw [← coe_smul, ← coe_star_stable, ← coe_star_stable, ← coe_smul, star_smul] + +@[instance_reducible] def stabilizationCStarAlgebra : NonUnitalCStarAlgebra (Stabilization A) where + +def corner (n : ℕ) : Mat A n →⋆ₙₐ[ℂ] Stabilization A where + toFun x := (cornerAlg n x : Stabilization A) + map_zero' := by rw [map_zero, coe_zero] + map_add' x y := by simp [map_add, coe_add] + map_mul' x y := by simp [map_mul] + map_smul' c x := by simp [map_smul, coe_smul] + map_star' x := by simp [map_star] + +@[simp] lemma corner_apply (n : ℕ) (x : Mat A n) : + corner n x = (cornerAlg n x : Stabilization A) := rfl + +lemma norm_corner (n : ℕ) (x : Mat A n) : ‖corner n x‖ = ‖x‖ := by + rw [corner_apply, norm_coe, cornerAlg_apply, norm_mk] + +lemma corner_isometry (n : ℕ) : Isometry (corner (A := A) n) := + AddMonoidHomClass.isometry_of_norm (corner n) (norm_corner n) + +lemma corner_pad {n m : ℕ} (h : n ≤ m) (x : Mat A n) : + corner m (pad h x) = corner n x := by + change ((⟦⟨m,padHom h x⟩⟧ : Algebraic A) : Stabilization A) = + ((⟦⟨n,x⟩⟧ : Algebraic A) : Stabilization A) + rw [DirectLimit.mk_apply] + +end MainGap.Stable + +namespace MainGap.Manuscript +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +def CuntzLE (d v : Stable.Stabilization A) : Prop := + ∃ r : ℕ → Stable.Stabilization A, + Tendsto (fun j => star (r j) * v * r j) atTop (𝓝 d) + +def ProperlyInfinite (h : A) : Prop := + CuntzLE ((⟦⟨2, MainGap.doubleCorner h⟩⟧ : Stable.Algebraic A) : Stable.Stabilization A) + ((⟦⟨1, MainGap.scalarCorner h⟩⟧ : Stable.Algebraic A) : Stable.Stabilization A) + +def PropertyP (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ h : A, 0 ≤ h → ProperlyInfinite h + +theorem individual_to_strong_main (hP : PropertyP A) : + (∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ c : A, ∀ ε : ℝ, 0 < ε → + ∃ s t : A, + ‖star s * a * s - a‖ < ε ∧ + ‖star t * b * t - b‖ < ε ∧ + ‖star s * c * t‖ < ε) ∧ + MainGap.StronglyPurelyInfinite A := by + sorry + +end MainGap.Manuscript + +end +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IndividualStrongInfiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MainGap.Manuscript.individual_to_strong_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/individual-strong-infiniteness/solution/closure.txt b/tasks/individual-strong-infiniteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2c19c6e9a6f3d796c35191c9005c9bbf44dfd90 --- /dev/null +++ b/tasks/individual-strong-infiniteness/solution/closure.txt @@ -0,0 +1,25 @@ +OAI.Analysis.CStarAlgebra.PureInfiniteness.Avoidance +OAI.Analysis.CStarAlgebra.PureInfiniteness.ChoicePairs +OAI.Analysis.CStarAlgebra.PureInfiniteness.ClosedIdeal +OAI.Analysis.CStarAlgebra.PureInfiniteness.Comparison +OAI.Analysis.CStarAlgebra.PureInfiniteness.Compression +OAI.Analysis.CStarAlgebra.PureInfiniteness.Cutoffs +OAI.Analysis.CStarAlgebra.PureInfiniteness.Defect +OAI.Analysis.CStarAlgebra.PureInfiniteness.Diagonalization +OAI.Analysis.CStarAlgebra.PureInfiniteness.FourChoices +OAI.Analysis.CStarAlgebra.PureInfiniteness.Graph +OAI.Analysis.CStarAlgebra.PureInfiniteness.Hereditary +OAI.Analysis.CStarAlgebra.PureInfiniteness.IdealComparison +OAI.Analysis.CStarAlgebra.PureInfiniteness.IdealDetection +OAI.Analysis.CStarAlgebra.PureInfiniteness.Main +OAI.Analysis.CStarAlgebra.PureInfiniteness.MatrixEntries +OAI.Analysis.CStarAlgebra.PureInfiniteness.Nonvanishing +OAI.Analysis.CStarAlgebra.PureInfiniteness.OrthogonalSlots +OAI.Analysis.CStarAlgebra.PureInfiniteness.PositiveFunctional +OAI.Analysis.CStarAlgebra.PureInfiniteness.Products +OAI.Analysis.CStarAlgebra.PureInfiniteness.Representation +OAI.Analysis.CStarAlgebra.PureInfiniteness.Separation +OAI.Analysis.CStarAlgebra.PureInfiniteness.Shrinking +OAI.Analysis.CStarAlgebra.PureInfiniteness.Signal +OAI.Analysis.CStarAlgebra.PureInfiniteness.Stabilization +OAI.Analysis.CStarAlgebra.PureInfiniteness.Ultrafilter diff --git a/tasks/individual-strong-infiniteness/solution/reference.py b/tasks/individual-strong-infiniteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/individual-strong-infiniteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/individual-strong-infiniteness/solution/solve.sh b/tasks/individual-strong-infiniteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..87f25f1a7e9211f29b325961823d4244097d4e2b --- /dev/null +++ b/tasks/individual-strong-infiniteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IndividualStrongInfiniteness, i.e. module OAI.Analysis.CStarAlgebra.PureInfiniteness.Main and the +# 25 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.CStarAlgebra.PureInfiniteness.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IndividualStrongInfiniteness" diff --git a/tasks/individual-strong-infiniteness/task.toml b/tasks/individual-strong-infiniteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..447d4b73f9101fa0b1f6c7f548a65a9abbf08308 --- /dev/null +++ b/tasks/individual-strong-infiniteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/individual-strong-infiniteness" +version = "1.0.0" +description = "Prove IndividualStrongInfiniteness (openai/math family 303: From ordinary to strong pure infiniteness) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IndividualStrongInfiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IndividualStrongInfiniteness" +family = "303" +family_title = "From ordinary to strong pure infiniteness" +subject = "Operator algebras" +theorems = ["OAI.MainGap.Manuscript.individual_to_strong_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.CStarAlgebra.PureInfiniteness.Main" +reference_modules = 25 +reference_lean_bytes = 283030 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 965 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11954 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/individual-strong-infiniteness/tests/Challenge.lean b/tasks/individual-strong-infiniteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..25c47f6ec748564ecb84b2b0676a727bd9fc5147 --- /dev/null +++ b/tasks/individual-strong-infiniteness/tests/Challenge.lean @@ -0,0 +1,333 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Filter +open scoped Topology CStarAlgebra ComplexOrder InnerProductSpace + +namespace MainGap +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +def scalarCorner (h : A) : CStarMatrix (Fin 1) (Fin 1) A := + CStarMatrix.ofMatrix (fun _ _ => h) + +def doubleCorner (h : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix (Matrix.diagonal (fun _ => h)) + +def Diagonalization (a b c : A) (ε : ℝ) : Prop := + ∃ s t : A, + ‖star s * a * s - a‖ < ε ∧ + ‖star t * b * t - b‖ < ε ∧ + ‖star s * c * t‖ < ε + +def UnrestrictedDiagonalization (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ c : A, ∀ ε : ℝ, 0 < ε → + Diagonalization a b c ε + +def StronglyPurelyInfinite (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ x y : A, 0 ≤ x → 0 ≤ y → ∀ ε : ℝ, 0 < ε → + Diagonalization (x * x) (y * y) (x * y) ε + +end MainGap + +noncomputable section +open Filter +open scoped Topology +namespace MainGap.Stable +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +abbrev Mat (A : Type*) (n : ℕ) := CStarMatrix (Fin n) (Fin n) A + +def pad {n m : ℕ} (_ : n ≤ m) (x : Mat A n) : Mat A m := + CStarMatrix.ofMatrix fun i j => + if hi : i.val < n then if hj : j.val < n then x ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0 + +@[simp] lemma pad_entry {n m : ℕ} (h : n ≤ m) (x : Mat A n) (i j : Fin m) : + pad h x i j = (if hi : i.val < n then if hj : j.val < n then x ⟨i,hi⟩ ⟨j,hj⟩ else 0 else 0) := rfl + +@[simp] lemma pad_apply {n m : ℕ} (h : n ≤ m) (x : Mat A n) (i j : Fin n) : + pad h x (Fin.castLE h i) (Fin.castLE h j) = x i j := by simp [pad_entry] + +lemma sum_pad {n m : ℕ} (h : n ≤ m) {B : Type*} [AddCommMonoid B] (f : Fin n → B) : + ∑ k : Fin m, (if hk : k.val < n then f ⟨k,hk⟩ else 0) = ∑ k : Fin n, f k := by + classical + symm + apply Finset.sum_bij_ne_zero (fun i _ _ => Fin.castLE h i) + · simp + · intro i _ _ j _ _ hij + exact Fin.ext (congrArg (fun k : Fin m => k.val) hij) + · intro j _ hj0 + have hj : j.val < n := by + by_contra hn + simp [hn] at hj0 + exact ⟨⟨j,hj⟩, Finset.mem_univ _, by simpa [hj] using hj0, rfl⟩ + · intro i _ _ + simp + +lemma pad_mul {n m : ℕ} (h : n ≤ m) (x y : Mat A n) : + pad h (x*y) = pad h x * pad h y := by + ext i j + by_cases hi : i.val < n <;> by_cases hj : j.val < n + · simp only [pad_entry, dite_eq_left hi, dite_eq_left hj, + CStarMatrix.mul_apply] + rw [← sum_pad h (fun k => x ⟨i,hi⟩ k * y k ⟨j,hj⟩)] + apply Finset.sum_congr rfl + intro k _ + by_cases hk : k.val < n <;> simp [hk] + · simp [pad_entry, hi, hj, CStarMatrix.mul_apply] + · simp [pad_entry, hi, CStarMatrix.mul_apply] + · simp [pad_entry, hi, CStarMatrix.mul_apply] + +def padHom {n m : ℕ} (h : n ≤ m) : Mat A n →⋆ₙₐ[ℂ] Mat A m where + toFun := pad h + map_zero' := by ext i j; simp [pad_entry] + map_add' x y := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj] + map_mul' := pad_mul h + map_smul' c x := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj] + map_star' x := by ext i j; by_cases hi : i.val < n <;> by_cases hj : j.val < n <;> simp [pad_entry, hi, hj, CStarMatrix.star_apply] + +lemma pad_injective {n m : ℕ} (h : n ≤ m) : Function.Injective (pad (A := A) h) := by + intro x y hxy + ext i j + have hh := congrArg (fun z : Mat A m => z (Fin.castLE h i) (Fin.castLE h j)) hxy + simpa using hh + +lemma norm_pad {n m : ℕ} (h : n ≤ m) (x : Mat A n) : ‖pad h x‖ = ‖x‖ := + NonUnitalStarAlgHom.norm_map (padHom h) (pad_injective h) x + +lemma pad_self (n : ℕ) (x : Mat A n) : pad le_rfl x = x := by + ext i j + simp [pad_entry] + +lemma pad_pad {n m k : ℕ} (h : n ≤ m) (h' : m ≤ k) (x : Mat A n) : + pad h' (pad h x) = pad (h.trans h') x := by + ext i j + by_cases hi : i.val < n <;> by_cases hj : j.val < n + · have hi' : i.val < m := lt_of_lt_of_le hi h + have hj' : j.val < m := lt_of_lt_of_le hj h + simp [pad_entry, hi, hj, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hj, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hi', hj'] + · by_cases hi' : i.val < m <;> by_cases hj' : j.val < m <;> simp [pad_entry, hi, hi', hj'] + +instance pad_directedSystem : DirectedSystem (Mat A) (fun _ _ h => padHom h) where + map_self := fun {_} x => pad_self _ x + map_map := fun {_ _ _} h h' x => pad_pad h h' x + +abbrev Algebraic (A : Type*) [NonUnitalCStarAlgebra A] := + DirectLimit (Mat A) (fun _ _ h => padHom h) + +local instance matLinear (n m : ℕ) : + LinearMapClass (Mat A n →⋆ₙₐ[ℂ] Mat A m) ℂ (Mat A n) (Mat A m) where + map_add f x y := f.map_add x y + map_smulₛₗ f c x := f.map_smul c x + +instance : Module ℂ (Algebraic A) := DirectLimit.instModule + +instance : Norm (Algebraic A) where + norm := DirectLimit.lift _ (fun _ x => ‖x‖) (fun _ _ h x => (norm_pad h x).symm) + +@[simp] lemma norm_mk (n : ℕ) (x : Mat A n) : + ‖(⟦⟨n,x⟩⟧ : Algebraic A)‖ = ‖x‖ := rfl + +lemma normedCore : NormedSpace.Core ℂ (Algebraic A) where + norm_nonneg := DirectLimit.induction _ fun n x => norm_nonneg x + norm_smul c := DirectLimit.induction _ fun n x => by + rw [DirectLimit.smul_def, norm_mk, norm_mk, norm_smul] + norm_triangle := DirectLimit.induction₂ _ fun n x y => by + rw [DirectLimit.add_def, norm_mk, norm_mk, norm_mk] + exact norm_add_le x y + norm_eq_zero_iff := DirectLimit.induction _ fun n x => by + rw [norm_mk, norm_eq_zero] + constructor + · rintro rfl + exact (DirectLimit.zero_def (f := fun _ _ h => padHom (A := A) h) n).symm + · intro h + apply pad_injective (le_rfl : n ≤ n) + have hi := DirectLimit.mk_injective (fun _ _ h => padHom (A := A) h) (fun _ _ h => pad_injective h) n + exact congrArg (pad le_rfl) (hi (h.trans (DirectLimit.zero_def (f := fun _ _ h => padHom (A := A) h) n))) + +instance : NormedAddCommGroup (Algebraic A) := .ofCore (𝕜 := ℂ) (normedCore (A := A)) +instance : NormedSpace ℂ (Algebraic A) := .ofCore (normedCore (A := A)) +instance : NonUnitalNormedRing (Algebraic A) where + dist_eq _ _ := rfl + norm_mul_le := DirectLimit.induction₂ _ fun n x y => by + rw [DirectLimit.mul_def, norm_mk, norm_mk, norm_mk] + exact norm_mul_le x y +instance : CStarRing (Algebraic A) where + norm_mul_self_le := DirectLimit.induction _ fun n x => by + rw [DirectLimit.star_def, DirectLimit.mul_def, norm_mk, norm_mk] + exact CStarRing.norm_mul_self_le x + +def cornerAlg (n : ℕ) : Mat A n →⋆ₙₐ[ℂ] Algebraic A where + __ := DirectLimit.NonUnitalAlgebra.of (Mat A) (fun _ _ h => padHom h) n + map_star' _ := rfl + +@[simp] lemma cornerAlg_apply (n : ℕ) (x : Mat A n) : + cornerAlg n x = (⟦⟨n,x⟩⟧ : Algebraic A) := rfl + +lemma cornerAlg_isometry (n : ℕ) : Isometry (cornerAlg (A := A) n) := + AddMonoidHomClass.isometry_of_norm (cornerAlg n) (fun _ => rfl) + +abbrev Stabilization (A : Type*) [NonUnitalCStarAlgebra A] := UniformSpace.Completion (Algebraic A) + +local instance algebraicTopology : TopologicalSpace (Algebraic A) := + (inferInstance : PseudoMetricSpace (Algebraic A)).toUniformSpace.toTopologicalSpace + +open UniformSpace +open UniformSpace.Completion + +instance : Mul (Stabilization A) := + ⟨Function.curry <| (isDenseInducing_coe.prodMap isDenseInducing_coe).extend + ((↑) ∘ Function.uncurry (· * · : Algebraic A → Algebraic A → Algebraic A))⟩ + +@[simp, norm_cast] lemma coe_mul_stable (x y : Algebraic A) : + ((x*y : Algebraic A) : Stabilization A) = (x : Stabilization A) * (y : Stabilization A) := + ((isDenseInducing_coe.prodMap isDenseInducing_coe).extend_eq + ((continuous_coe _).comp continuous_mul) (x,y)).symm + +instance : ContinuousMul (Stabilization A) where + continuous_mul := by + let m := (AddMonoidHom.mul : Algebraic A →+ Algebraic A →+ Algebraic A).compr₂ toCompl + have hh : Continuous fun p : Algebraic A × Algebraic A => m p.1 p.2 := + (continuous_coe _).comp continuous_mul + have di : IsDenseInducing (toCompl : Algebraic A → Stabilization A) := isDenseInducing_coe + exact di.extend_Z_bilin di hh + +instance : NonUnitalRing (Stabilization A) where + __ : AddCommGroup (Stabilization A) := inferInstance + zero_mul x := Completion.induction_on x (isClosed_eq (by fun_prop) continuous_const) + fun x => by rw [← coe_zero, ← coe_mul_stable, zero_mul] + mul_zero x := Completion.induction_on x (isClosed_eq (by fun_prop) continuous_const) + fun x => by rw [← coe_zero, ← coe_mul_stable, mul_zero] + mul_assoc x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, mul_assoc] + left_distrib x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_add, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_add, mul_add] + right_distrib x y z := Completion.induction_on₃ x y z + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y z => by + rw [← coe_add, ← coe_mul_stable, ← coe_mul_stable, ← coe_mul_stable, ← coe_add, add_mul] + +instance : NonUnitalNormedRing (Stabilization A) where + dist_eq := dist_eq_norm_neg_add + norm_mul_le x y := Completion.induction_on₂ x y + (isClosed_le (by fun_prop) (by fun_prop)) fun x y => by + simpa only [← coe_mul_stable, norm_coe] using norm_mul_le x y + +instance : Star (Stabilization A) := ⟨Completion.map (star : Algebraic A → Algebraic A)⟩ + +@[simp, norm_cast] lemma coe_star_stable (x : Algebraic A) : + ((star x : Algebraic A) : Stabilization A) = star (x : Stabilization A) := + (Completion.map_coe star_isometry.uniformContinuous x).symm + +instance : ContinuousStar (Stabilization A) where + continuous_star := Completion.continuous_map + +instance : StarRing (Stabilization A) where + star_involutive x := Completion.induction_on x + (isClosed_eq (by fun_prop) continuous_id) fun x => by + rw [← coe_star_stable, ← coe_star_stable, star_star] + star_add x y := Completion.induction_on₂ x y + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y => by + rw [← coe_add, ← coe_star_stable, ← coe_star_stable, ← coe_star_stable, ← coe_add, star_add] + star_mul x y := Completion.induction_on₂ x y + (isClosed_eq (by fun_prop) (by fun_prop)) fun x y => by + rw [← coe_mul_stable, ← coe_star_stable, ← coe_star_stable, ← coe_star_stable, + ← coe_mul_stable, star_mul] + +instance : CStarRing (Stabilization A) where + norm_mul_self_le x := Completion.induction_on x + (isClosed_le (by fun_prop) (by fun_prop)) fun x => by + simpa only [← coe_star_stable, ← coe_mul_stable, norm_coe] using CStarRing.norm_mul_self_le x + +instance : IsScalarTower ℂ (Stabilization A) (Stabilization A) where + smul_assoc c x y := by + change (c • x) * y = c • (x*y) + refine Completion.induction_on₂ x y ?_ ?_ + · exact isClosed_eq ((continuous_fst.const_smul c).mul continuous_snd) + ((continuous_fst.mul continuous_snd).const_smul c) + · intro x y + rw [← coe_smul, ← coe_mul_stable, ← coe_mul_stable, ← coe_smul, smul_mul_assoc] + +instance : SMulCommClass ℂ (Stabilization A) (Stabilization A) where + smul_comm c x y := by + change c • (x*y) = x * (c • y) + refine Completion.induction_on₂ x y ?_ ?_ + · exact isClosed_eq ((continuous_fst.mul continuous_snd).const_smul c) + (continuous_fst.mul (continuous_snd.const_smul c)) + · intro x y + rw [← coe_mul_stable, ← coe_smul, ← coe_smul, ← coe_mul_stable, mul_smul_comm] + +instance : StarModule ℂ (Stabilization A) where + star_smul c x := by + refine Completion.induction_on x ?_ ?_ + · exact isClosed_eq (continuous_star.comp (continuous_const_smul c)) + (continuous_star.const_smul (star c)) + · intro x + rw [← coe_smul, ← coe_star_stable, ← coe_star_stable, ← coe_smul, star_smul] + +@[instance_reducible] def stabilizationCStarAlgebra : NonUnitalCStarAlgebra (Stabilization A) where + +def corner (n : ℕ) : Mat A n →⋆ₙₐ[ℂ] Stabilization A where + toFun x := (cornerAlg n x : Stabilization A) + map_zero' := by rw [map_zero, coe_zero] + map_add' x y := by simp [map_add, coe_add] + map_mul' x y := by simp [map_mul] + map_smul' c x := by simp [map_smul, coe_smul] + map_star' x := by simp [map_star] + +@[simp] lemma corner_apply (n : ℕ) (x : Mat A n) : + corner n x = (cornerAlg n x : Stabilization A) := rfl + +lemma norm_corner (n : ℕ) (x : Mat A n) : ‖corner n x‖ = ‖x‖ := by + rw [corner_apply, norm_coe, cornerAlg_apply, norm_mk] + +lemma corner_isometry (n : ℕ) : Isometry (corner (A := A) n) := + AddMonoidHomClass.isometry_of_norm (corner n) (norm_corner n) + +lemma corner_pad {n m : ℕ} (h : n ≤ m) (x : Mat A n) : + corner m (pad h x) = corner n x := by + change ((⟦⟨m,padHom h x⟩⟧ : Algebraic A) : Stabilization A) = + ((⟦⟨n,x⟩⟧ : Algebraic A) : Stabilization A) + rw [DirectLimit.mk_apply] + +end MainGap.Stable + +namespace MainGap.Manuscript +variable {A : Type*} [NonUnitalCStarAlgebra A] +local instance positivityOrder : PartialOrder A := CStarAlgebra.spectralOrder A +local instance positivityStarOrder : StarOrderedRing A := CStarAlgebra.spectralOrderedRing A + +def CuntzLE (d v : Stable.Stabilization A) : Prop := + ∃ r : ℕ → Stable.Stabilization A, + Tendsto (fun j => star (r j) * v * r j) atTop (𝓝 d) + +def ProperlyInfinite (h : A) : Prop := + CuntzLE ((⟦⟨2, MainGap.doubleCorner h⟩⟧ : Stable.Algebraic A) : Stable.Stabilization A) + ((⟦⟨1, MainGap.scalarCorner h⟩⟧ : Stable.Algebraic A) : Stable.Stabilization A) + +def PropertyP (A : Type*) [NonUnitalCStarAlgebra A] : Prop := + ∀ h : A, 0 ≤ h → ProperlyInfinite h + +theorem individual_to_strong_main (hP : PropertyP A) : + (∀ a b : A, 0 ≤ a → 0 ≤ b → ∀ c : A, ∀ ε : ℝ, 0 < ε → + ∃ s t : A, + ‖star s * a * s - a‖ < ε ∧ + ‖star t * b * t - b‖ < ε ∧ + ‖star s * c * t‖ < ε) ∧ + MainGap.StronglyPurelyInfinite A := by + sorry + +end MainGap.Manuscript + +end +end + +end OAI diff --git a/tasks/individual-strong-infiniteness/tests/grade.py b/tasks/individual-strong-infiniteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/individual-strong-infiniteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/individual-strong-infiniteness/tests/task.json b/tasks/individual-strong-infiniteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..14a5f19f11847898d612c77f45cf6721d3572238 --- /dev/null +++ b/tasks/individual-strong-infiniteness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "IndividualStrongInfiniteness", + "comparator": { + "theorem_names": [ + "OAI.MainGap.Manuscript.individual_to_strong_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11054 +} \ No newline at end of file diff --git a/tasks/individual-strong-infiniteness/tests/test.sh b/tasks/individual-strong-infiniteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/individual-strong-infiniteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/infinite-matroid-corollaries/environment/Dockerfile b/tasks/infinite-matroid-corollaries/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/infinite-matroid-corollaries/environment/fetch_mathlib.sh b/tasks/infinite-matroid-corollaries/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/infinite-matroid-corollaries/environment/lake-manifest.json b/tasks/infinite-matroid-corollaries/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/infinite-matroid-corollaries/environment/lakefile.lean b/tasks/infinite-matroid-corollaries/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/infinite-matroid-corollaries/environment/lean_setup.sh b/tasks/infinite-matroid-corollaries/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/infinite-matroid-corollaries/environment/pack_submission.py b/tasks/infinite-matroid-corollaries/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/infinite-matroid-corollaries/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/infinite-matroid-corollaries/instruction.md b/tasks/infinite-matroid-corollaries/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e3d826212a6b36ae8ef322f40f19542b1f66b94b --- /dev/null +++ b/tasks/infinite-matroid-corollaries/instruction.md @@ -0,0 +1,179 @@ +# openai/math challenge `InfiniteMatroidCorollaries` (family 185) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 185 of the release, *Counterexamples to infinite matroid intersection and packing/covering* +(Combinatorics). The family as a whole: Disproves the unrestricted infinite matroid intersection and packing/covering conjectures in ZFC, using two self-dual partitional matroids on a countably infinite ground set. The same examples answer Joo’s partitional-matroid question negatively. They are neither finitary nor cofinitary, so Nash-Williams’ original finitary conjecture remains outside the result. + +The challenge is `InfiniteMatroidCorollaries`, also at `/opt/openai-math/challenges/InfiniteMatroidCorollaries.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace InfiniteMatroidCounterexample +open Set Matroid + +abbrev D := (m : ℕ) × ((Fin m → Bool) → Bool) +abbrev E0 := D × Bool +abbrev E := ℤ × D + +def contractOnto {α : Type*} (M : Matroid α) (C : Set α) : Matroid α := + (M.dual ↾ C).dual + +def HasPackingCovering {α : Type*} (M₀ M₁ : Matroid α) : Prop := + ∃ P C S₀ S₁ I₀ I₁ : Set α, + Disjoint P C ∧ P ∪ C = M₀.E ∧ M₁.E = M₀.E ∧ + S₀ ⊆ P ∧ S₁ ⊆ P ∧ Disjoint S₀ S₁ ∧ + (M₀ ↾ P).Spanning S₀ ∧ (M₁ ↾ P).Spanning S₁ ∧ + I₀ ⊆ C ∧ I₁ ⊆ C ∧ + (contractOnto M₀ C).Indep I₀ ∧ + (contractOnto M₁ C).Indep I₁ ∧ I₀ ∪ I₁ = C + +def bundleAt (n : ℤ) (b : Bool) : ℤ := + if n < 0 then (if b then n - 1 else n) else (if b then n else n - 1) + +def parityBit (p : Bool) : ℤ := if p then 1 else 0 +abbrev Vertex (p : Bool) := {n : ℤ // n % 2 = parityBit p} + +def componentMap {α : Type*} {p : Bool} (v : Vertex p) (x : α × Bool) : ℤ × α := + (bundleAt v x.2,x.1) + +def globalComponentMap (α : Type*) (p : Bool) (x : Vertex p × (α × Bool)) : ℤ × α := + componentMap x.1 x.2 + +noncomputable def componentEquiv (α : Type*) (p : Bool) : (Vertex p × (α × Bool)) ≃ (ℤ × α) := + Equiv.ofBijective (globalComponentMap α p) (by + have bundleAt_bounds (n : ℤ) (b : Bool) : n - 1 ≤ bundleAt n b ∧ bundleAt n b ≤ n := by + unfold bundleAt + split_ifs <;> omega + have bundleAt_injective (n : ℤ) : Function.Injective (bundleAt n) := by + intro b c h + cases b <;> cases c <;> simp_all [bundleAt] <;> split_ifs at h <;> omega + have bundleAt_right (n : ℤ) : ∃ b, bundleAt n b = n := by + by_cases h : n < 0 + · exact ⟨false,by simp [bundleAt,h]⟩ + · exact ⟨true,by simp [bundleAt,h]⟩ + have bundleAt_left (n : ℤ) : ∃ b, bundleAt n b = n - 1 := by + by_cases h : n < 0 + · exact ⟨true,by simp [bundleAt,h]⟩ + · exact ⟨false,by simp [bundleAt,h]⟩ + + have globalComponentMap_injective : + Function.Injective (globalComponentMap α p) := by + rintro ⟨⟨n,hn⟩,d,b⟩ ⟨⟨m,hm⟩,e,c⟩ h + have hnm : bundleAt n b = bundleAt m c := congrArg Prod.fst h + have hde : d = e := congrArg Prod.snd h + have hb := bundleAt_bounds n b + have hc := bundleAt_bounds m c + have hnm' : n = m := by omega + subst m + have hbc := bundleAt_injective n hnm + subst e; subst c + rfl + + have globalComponentMap_surjective : + Function.Surjective (globalComponentMap α p) := by + rintro ⟨n,d⟩ + by_cases hn : n % 2 = parityBit p + · obtain ⟨b,hb⟩ := bundleAt_right n + exact ⟨(⟨n,hn⟩,d,b),by simp [globalComponentMap,componentMap,hb]⟩ + · have hn' : (n+1) % 2 = parityBit p := by + cases p <;> simp only [parityBit,Bool.false_eq_true,ite_false,ite_true] at hn ⊢ <;> omega + obtain ⟨b,hb⟩ := bundleAt_left (n+1) + exact ⟨(⟨n+1,hn'⟩,d,b),by simp [globalComponentMap,componentMap,hb]⟩ + exact ⟨globalComponentMap_injective, globalComponentMap_surjective⟩) + +noncomputable def rayMatroid {α : Type*} (Q : Matroid (α × Bool)) (p : Bool) : Matroid (ℤ × α) := + (Matroid.sum' (fun _ : Vertex p ↦ Q)).mapEquiv (componentEquiv α p) + +def IsUniform {α : Type*} (M : Matroid α) : Prop := + ∀ X ⊆ M.E, M.Indep X ∨ M.Spanning X + +def IsPartitional {α : Type} (M : Matroid α) : Prop := + ∃ (ι : Type) (β : ι → Type) (N : ∀ i, Matroid (β i)) (e : (Σ i, β i) ≃ α), + (∀ i, IsUniform (N i)) ∧ M = (Matroid.sigma N).mapEquiv e + +def HasIntersection {α : Type*} (M N : Matroid α) : Prop := + ∃ J J₀ J₁ : Set α, M.Indep J ∧ N.Indep J ∧ + Disjoint J₀ J₁ ∧ J₀ ∪ J₁ = J ∧ M.closure J₀ ∪ N.closure J₁ = M.E + +def FamilyCovering {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + ∃ I : ι → Set α, (∀ i, (M i).Indep (I i)) ∧ (⋃ i, I i) = F + +def FamilyPacking {α ι : Type*} (M : ι → Matroid α) : Prop := + ∃ S : ι → Set α, (Pairwise fun i j ↦ Disjoint (S i) (S j)) ∧ + ∀ i, (M i).Spanning (S i) + +def CoveringConjectureFor {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + FamilyCovering F M ↔ ∀ Y ⊆ F, + FamilyPacking (fun i ↦ M i ↾ Y) → FamilyCovering Y (fun i ↦ M i ↾ Y) + +def PackingConjectureFor {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + FamilyPacking M ↔ ∀ Y ⊆ F, + FamilyCovering Y (fun i ↦ contractOnto (M i) Y) → + FamilyPacking (fun i ↦ contractOnto (M i) Y) + +theorem partitional_intersection_counterexample : + Countable E ∧ Infinite E ∧ + ∃ Q : Matroid E0, Q.E = univ ∧ Q.dual = Q ∧ IsUniform Q ∧ + let M₀ := rayMatroid Q false + let M₁ := rayMatroid Q true + M₀.E = univ ∧ M₁.E = univ ∧ M₀.dual = M₀ ∧ M₁.dual = M₁ ∧ + IsPartitional M₀ ∧ IsPartitional M₁ ∧ + (∀ I₀ I₁ : Set E, M₀.Indep I₀ → M₁.Indep I₁ → I₀ ∪ I₁ ≠ univ) ∧ + ¬ HasPackingCovering M₀ M₁ ∧ ¬ HasIntersection M₀ M₁ := by + sorry + +theorem separate_covering_packing_counterexamples : + (∃ (F : Set E) (M : Bool → Matroid E), + (∀ i, (M i).E = F) ∧ ¬ CoveringConjectureFor F M) ∧ + (∃ (F : Set E) (M : Bool → Matroid E), + (∀ i, (M i).E = F) ∧ ¬ PackingConjectureFor F M) := by + sorry + +end InfiniteMatroidCounterexample + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/InfiniteMatroidCorollaries.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.InfiniteMatroidCounterexample.partitional_intersection_counterexample`, `OAI.InfiniteMatroidCounterexample.separate_covering_packing_counterexamples` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/infinite-matroid-corollaries/solution/closure.txt b/tasks/infinite-matroid-corollaries/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c0defb935f8a33026a19ecbfc56e1ffb1933dd3e --- /dev/null +++ b/tasks/infinite-matroid-corollaries/solution/closure.txt @@ -0,0 +1,33 @@ +OAI.Combinatorics.InfiniteMatroid.Basic +OAI.Combinatorics.InfiniteMatroid.BasisExtension +OAI.Combinatorics.InfiniteMatroid.BlockDensity +OAI.Combinatorics.InfiniteMatroid.Cardinality +OAI.Combinatorics.InfiniteMatroid.Cesaro +OAI.Combinatorics.InfiniteMatroid.Columns +OAI.Combinatorics.InfiniteMatroid.Corollaries +OAI.Combinatorics.InfiniteMatroid.CorollaryModel +OAI.Combinatorics.InfiniteMatroid.CoveringReduction +OAI.Combinatorics.InfiniteMatroid.DensityIdeal +OAI.Combinatorics.InfiniteMatroid.DoubleRay +OAI.Combinatorics.InfiniteMatroid.FiniteCounting +OAI.Combinatorics.InfiniteMatroid.Ideals +OAI.Combinatorics.InfiniteMatroid.Interpolation +OAI.Combinatorics.InfiniteMatroid.IntersectionReduction +OAI.Combinatorics.InfiniteMatroid.LocalBases +OAI.Combinatorics.InfiniteMatroid.Main +OAI.Combinatorics.InfiniteMatroid.Matroid +OAI.Combinatorics.InfiniteMatroid.OrdinalRank +OAI.Combinatorics.InfiniteMatroid.PackingCovering +OAI.Combinatorics.InfiniteMatroid.PairDuality +OAI.Combinatorics.InfiniteMatroid.Partitional +OAI.Combinatorics.InfiniteMatroid.ProbeLimits +OAI.Combinatorics.InfiniteMatroid.Prototype +OAI.Combinatorics.InfiniteMatroid.PrototypeExtension +OAI.Combinatorics.InfiniteMatroid.RankDescent +OAI.Combinatorics.InfiniteMatroid.Reservations +OAI.Combinatorics.InfiniteMatroid.SeparateCounterexamples +OAI.Combinatorics.InfiniteMatroid.Separation +OAI.Combinatorics.InfiniteMatroid.SparsePerturbation +OAI.Combinatorics.InfiniteMatroid.TransfiniteConstruction +OAI.Combinatorics.InfiniteMatroid.Waves +OAI.Combinatorics.InfiniteMatroid.Zones diff --git a/tasks/infinite-matroid-corollaries/solution/reference.py b/tasks/infinite-matroid-corollaries/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/infinite-matroid-corollaries/solution/solve.sh b/tasks/infinite-matroid-corollaries/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..477e6b92ffabcf8d76a734a02af8a4fb9881ad36 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of InfiniteMatroidCorollaries, i.e. module OAI.Combinatorics.InfiniteMatroid.Corollaries and the +# 33 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.InfiniteMatroid.Corollaries /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of InfiniteMatroidCorollaries" diff --git a/tasks/infinite-matroid-corollaries/task.toml b/tasks/infinite-matroid-corollaries/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c313a9cc8041de8709e5cd271a41a1664993b4c1 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/infinite-matroid-corollaries" +version = "1.0.0" +description = "Prove InfiniteMatroidCorollaries (openai/math family 185: Counterexamples to infinite matroid intersection and packing/covering) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/InfiniteMatroidCorollaries.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "InfiniteMatroidCorollaries" +family = "185" +family_title = "Counterexamples to infinite matroid intersection and packing/covering" +subject = "Combinatorics" +theorems = ["OAI.InfiniteMatroidCounterexample.partitional_intersection_counterexample", "OAI.InfiniteMatroidCounterexample.separate_covering_packing_counterexamples"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.InfiniteMatroid.Corollaries" +reference_modules = 33 +reference_lean_bytes = 193312 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 637 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11873 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/infinite-matroid-corollaries/tests/Challenge.lean b/tasks/infinite-matroid-corollaries/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..31b5edd2923687af9c9a8936d270ce1d126355f8 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/tests/Challenge.lean @@ -0,0 +1,128 @@ +import Mathlib + +namespace OAI + +namespace InfiniteMatroidCounterexample +open Set Matroid + +abbrev D := (m : ℕ) × ((Fin m → Bool) → Bool) +abbrev E0 := D × Bool +abbrev E := ℤ × D + +def contractOnto {α : Type*} (M : Matroid α) (C : Set α) : Matroid α := + (M.dual ↾ C).dual + +def HasPackingCovering {α : Type*} (M₀ M₁ : Matroid α) : Prop := + ∃ P C S₀ S₁ I₀ I₁ : Set α, + Disjoint P C ∧ P ∪ C = M₀.E ∧ M₁.E = M₀.E ∧ + S₀ ⊆ P ∧ S₁ ⊆ P ∧ Disjoint S₀ S₁ ∧ + (M₀ ↾ P).Spanning S₀ ∧ (M₁ ↾ P).Spanning S₁ ∧ + I₀ ⊆ C ∧ I₁ ⊆ C ∧ + (contractOnto M₀ C).Indep I₀ ∧ + (contractOnto M₁ C).Indep I₁ ∧ I₀ ∪ I₁ = C + +def bundleAt (n : ℤ) (b : Bool) : ℤ := + if n < 0 then (if b then n - 1 else n) else (if b then n else n - 1) + +def parityBit (p : Bool) : ℤ := if p then 1 else 0 +abbrev Vertex (p : Bool) := {n : ℤ // n % 2 = parityBit p} + +def componentMap {α : Type*} {p : Bool} (v : Vertex p) (x : α × Bool) : ℤ × α := + (bundleAt v x.2,x.1) + +def globalComponentMap (α : Type*) (p : Bool) (x : Vertex p × (α × Bool)) : ℤ × α := + componentMap x.1 x.2 + +noncomputable def componentEquiv (α : Type*) (p : Bool) : (Vertex p × (α × Bool)) ≃ (ℤ × α) := + Equiv.ofBijective (globalComponentMap α p) (by + have bundleAt_bounds (n : ℤ) (b : Bool) : n - 1 ≤ bundleAt n b ∧ bundleAt n b ≤ n := by + unfold bundleAt + split_ifs <;> omega + have bundleAt_injective (n : ℤ) : Function.Injective (bundleAt n) := by + intro b c h + cases b <;> cases c <;> simp_all [bundleAt] <;> split_ifs at h <;> omega + have bundleAt_right (n : ℤ) : ∃ b, bundleAt n b = n := by + by_cases h : n < 0 + · exact ⟨false,by simp [bundleAt,h]⟩ + · exact ⟨true,by simp [bundleAt,h]⟩ + have bundleAt_left (n : ℤ) : ∃ b, bundleAt n b = n - 1 := by + by_cases h : n < 0 + · exact ⟨true,by simp [bundleAt,h]⟩ + · exact ⟨false,by simp [bundleAt,h]⟩ + + have globalComponentMap_injective : + Function.Injective (globalComponentMap α p) := by + rintro ⟨⟨n,hn⟩,d,b⟩ ⟨⟨m,hm⟩,e,c⟩ h + have hnm : bundleAt n b = bundleAt m c := congrArg Prod.fst h + have hde : d = e := congrArg Prod.snd h + have hb := bundleAt_bounds n b + have hc := bundleAt_bounds m c + have hnm' : n = m := by omega + subst m + have hbc := bundleAt_injective n hnm + subst e; subst c + rfl + + have globalComponentMap_surjective : + Function.Surjective (globalComponentMap α p) := by + rintro ⟨n,d⟩ + by_cases hn : n % 2 = parityBit p + · obtain ⟨b,hb⟩ := bundleAt_right n + exact ⟨(⟨n,hn⟩,d,b),by simp [globalComponentMap,componentMap,hb]⟩ + · have hn' : (n+1) % 2 = parityBit p := by + cases p <;> simp only [parityBit,Bool.false_eq_true,ite_false,ite_true] at hn ⊢ <;> omega + obtain ⟨b,hb⟩ := bundleAt_left (n+1) + exact ⟨(⟨n+1,hn'⟩,d,b),by simp [globalComponentMap,componentMap,hb]⟩ + exact ⟨globalComponentMap_injective, globalComponentMap_surjective⟩) + +noncomputable def rayMatroid {α : Type*} (Q : Matroid (α × Bool)) (p : Bool) : Matroid (ℤ × α) := + (Matroid.sum' (fun _ : Vertex p ↦ Q)).mapEquiv (componentEquiv α p) + +def IsUniform {α : Type*} (M : Matroid α) : Prop := + ∀ X ⊆ M.E, M.Indep X ∨ M.Spanning X + +def IsPartitional {α : Type} (M : Matroid α) : Prop := + ∃ (ι : Type) (β : ι → Type) (N : ∀ i, Matroid (β i)) (e : (Σ i, β i) ≃ α), + (∀ i, IsUniform (N i)) ∧ M = (Matroid.sigma N).mapEquiv e + +def HasIntersection {α : Type*} (M N : Matroid α) : Prop := + ∃ J J₀ J₁ : Set α, M.Indep J ∧ N.Indep J ∧ + Disjoint J₀ J₁ ∧ J₀ ∪ J₁ = J ∧ M.closure J₀ ∪ N.closure J₁ = M.E + +def FamilyCovering {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + ∃ I : ι → Set α, (∀ i, (M i).Indep (I i)) ∧ (⋃ i, I i) = F + +def FamilyPacking {α ι : Type*} (M : ι → Matroid α) : Prop := + ∃ S : ι → Set α, (Pairwise fun i j ↦ Disjoint (S i) (S j)) ∧ + ∀ i, (M i).Spanning (S i) + +def CoveringConjectureFor {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + FamilyCovering F M ↔ ∀ Y ⊆ F, + FamilyPacking (fun i ↦ M i ↾ Y) → FamilyCovering Y (fun i ↦ M i ↾ Y) + +def PackingConjectureFor {α ι : Type*} (F : Set α) (M : ι → Matroid α) : Prop := + FamilyPacking M ↔ ∀ Y ⊆ F, + FamilyCovering Y (fun i ↦ contractOnto (M i) Y) → + FamilyPacking (fun i ↦ contractOnto (M i) Y) + +theorem partitional_intersection_counterexample : + Countable E ∧ Infinite E ∧ + ∃ Q : Matroid E0, Q.E = univ ∧ Q.dual = Q ∧ IsUniform Q ∧ + let M₀ := rayMatroid Q false + let M₁ := rayMatroid Q true + M₀.E = univ ∧ M₁.E = univ ∧ M₀.dual = M₀ ∧ M₁.dual = M₁ ∧ + IsPartitional M₀ ∧ IsPartitional M₁ ∧ + (∀ I₀ I₁ : Set E, M₀.Indep I₀ → M₁.Indep I₁ → I₀ ∪ I₁ ≠ univ) ∧ + ¬ HasPackingCovering M₀ M₁ ∧ ¬ HasIntersection M₀ M₁ := by + sorry + +theorem separate_covering_packing_counterexamples : + (∃ (F : Set E) (M : Bool → Matroid E), + (∀ i, (M i).E = F) ∧ ¬ CoveringConjectureFor F M) ∧ + (∃ (F : Set E) (M : Bool → Matroid E), + (∀ i, (M i).E = F) ∧ ¬ PackingConjectureFor F M) := by + sorry + +end InfiniteMatroidCounterexample + +end OAI diff --git a/tasks/infinite-matroid-corollaries/tests/grade.py b/tasks/infinite-matroid-corollaries/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/infinite-matroid-corollaries/tests/task.json b/tasks/infinite-matroid-corollaries/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1c79514739ba2b3d54d280419730c9f7e676c2b9 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "InfiniteMatroidCorollaries", + "comparator": { + "theorem_names": [ + "OAI.InfiniteMatroidCounterexample.partitional_intersection_counterexample", + "OAI.InfiniteMatroidCounterexample.separate_covering_packing_counterexamples" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 10973 +} \ No newline at end of file diff --git a/tasks/infinite-matroid-corollaries/tests/test.sh b/tasks/infinite-matroid-corollaries/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/infinite-matroid-corollaries/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/infinite-matroid/environment/Dockerfile b/tasks/infinite-matroid/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/infinite-matroid/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/infinite-matroid/environment/fetch_mathlib.sh b/tasks/infinite-matroid/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/infinite-matroid/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/infinite-matroid/environment/lake-manifest.json b/tasks/infinite-matroid/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/infinite-matroid/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/infinite-matroid/environment/lakefile.lean b/tasks/infinite-matroid/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/infinite-matroid/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/infinite-matroid/environment/lean_setup.sh b/tasks/infinite-matroid/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/infinite-matroid/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/infinite-matroid/environment/pack_submission.py b/tasks/infinite-matroid/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/infinite-matroid/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/infinite-matroid/instruction.md b/tasks/infinite-matroid/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65a4741716690cd5bd99e5b60f4ceb6e58f6e8e3 --- /dev/null +++ b/tasks/infinite-matroid/instruction.md @@ -0,0 +1,85 @@ +# openai/math challenge `InfiniteMatroid` (family 185) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 185 of the release, *Counterexamples to infinite matroid intersection and packing/covering* +(Combinatorics). The family as a whole: Disproves the unrestricted infinite matroid intersection and packing/covering conjectures in ZFC, using two self-dual partitional matroids on a countably infinite ground set. The same examples answer Joo’s partitional-matroid question negatively. They are neither finitary nor cofinitary, so Nash-Williams’ original finitary conjecture remains outside the result. + +The challenge is `InfiniteMatroid`, also at `/opt/openai-math/challenges/InfiniteMatroid.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace InfiniteMatroidCounterexample +open Matroid + +abbrev D := (m : ℕ) × ((Fin m → Bool) → Bool) +abbrev E := ℤ × D + +def contractOnto {α : Type*} (M : Matroid α) (C : Set α) : Matroid α := + (M.dual ↾ C).dual + +def HasPackingCovering {α : Type*} (M₀ M₁ : Matroid α) : Prop := + ∃ P C S₀ S₁ I₀ I₁ : Set α, + Disjoint P C ∧ P ∪ C = M₀.E ∧ M₁.E = M₀.E ∧ + S₀ ⊆ P ∧ S₁ ⊆ P ∧ Disjoint S₀ S₁ ∧ + (M₀ ↾ P).Spanning S₀ ∧ (M₁ ↾ P).Spanning S₁ ∧ + I₀ ⊆ C ∧ I₁ ⊆ C ∧ + (contractOnto M₀ C).Indep I₀ ∧ + (contractOnto M₁ C).Indep I₁ ∧ I₀ ∪ I₁ = C + +theorem main : + Countable E ∧ Infinite E ∧ + ∃ M₀ M₁ : Matroid E, + M₀.E = Set.univ ∧ M₁.E = Set.univ ∧ + M₀.dual = M₀ ∧ M₁.dual = M₁ ∧ + (∀ I₀ I₁ : Set E, M₀.Indep I₀ → M₁.Indep I₁ → I₀ ∪ I₁ ≠ Set.univ) ∧ + ¬ HasPackingCovering M₀ M₁ := by + sorry + +end InfiniteMatroidCounterexample + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/InfiniteMatroid.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.InfiniteMatroidCounterexample.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/infinite-matroid/solution/closure.txt b/tasks/infinite-matroid/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..89d36f3da3b7f5bae27c79af04e7d0aa3ee69985 --- /dev/null +++ b/tasks/infinite-matroid/solution/closure.txt @@ -0,0 +1,25 @@ +OAI.Combinatorics.InfiniteMatroid.Basic +OAI.Combinatorics.InfiniteMatroid.BasisExtension +OAI.Combinatorics.InfiniteMatroid.BlockDensity +OAI.Combinatorics.InfiniteMatroid.Cardinality +OAI.Combinatorics.InfiniteMatroid.Cesaro +OAI.Combinatorics.InfiniteMatroid.Columns +OAI.Combinatorics.InfiniteMatroid.DensityIdeal +OAI.Combinatorics.InfiniteMatroid.DoubleRay +OAI.Combinatorics.InfiniteMatroid.FiniteCounting +OAI.Combinatorics.InfiniteMatroid.Ideals +OAI.Combinatorics.InfiniteMatroid.Interpolation +OAI.Combinatorics.InfiniteMatroid.LocalBases +OAI.Combinatorics.InfiniteMatroid.Main +OAI.Combinatorics.InfiniteMatroid.Matroid +OAI.Combinatorics.InfiniteMatroid.OrdinalRank +OAI.Combinatorics.InfiniteMatroid.PackingCovering +OAI.Combinatorics.InfiniteMatroid.ProbeLimits +OAI.Combinatorics.InfiniteMatroid.Prototype +OAI.Combinatorics.InfiniteMatroid.PrototypeExtension +OAI.Combinatorics.InfiniteMatroid.RankDescent +OAI.Combinatorics.InfiniteMatroid.Reservations +OAI.Combinatorics.InfiniteMatroid.Separation +OAI.Combinatorics.InfiniteMatroid.SparsePerturbation +OAI.Combinatorics.InfiniteMatroid.TransfiniteConstruction +OAI.Combinatorics.InfiniteMatroid.Zones diff --git a/tasks/infinite-matroid/solution/reference.py b/tasks/infinite-matroid/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/infinite-matroid/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/infinite-matroid/solution/solve.sh b/tasks/infinite-matroid/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3e30021d0f4cd52fdce4da90c68ac58cbebe8802 --- /dev/null +++ b/tasks/infinite-matroid/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of InfiniteMatroid, i.e. module OAI.Combinatorics.InfiniteMatroid.Main and the +# 25 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.InfiniteMatroid.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of InfiniteMatroid" diff --git a/tasks/infinite-matroid/task.toml b/tasks/infinite-matroid/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..47b8eff0f7acfb20d1a98ab55919ea677d8213b2 --- /dev/null +++ b/tasks/infinite-matroid/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/infinite-matroid" +version = "1.0.0" +description = "Prove InfiniteMatroid (openai/math family 185: Counterexamples to infinite matroid intersection and packing/covering) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/InfiniteMatroid.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "InfiniteMatroid" +family = "185" +family_title = "Counterexamples to infinite matroid intersection and packing/covering" +subject = "Combinatorics" +theorems = ["OAI.InfiniteMatroidCounterexample.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.InfiniteMatroid.Main" +reference_modules = 25 +reference_lean_bytes = 174500 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 667 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11857 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/infinite-matroid/tests/Challenge.lean b/tasks/infinite-matroid/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f9253fd9949297356bc99360d3ffa54a88b944f3 --- /dev/null +++ b/tasks/infinite-matroid/tests/Challenge.lean @@ -0,0 +1,34 @@ +import Mathlib + +namespace OAI + +namespace InfiniteMatroidCounterexample +open Matroid + +abbrev D := (m : ℕ) × ((Fin m → Bool) → Bool) +abbrev E := ℤ × D + +def contractOnto {α : Type*} (M : Matroid α) (C : Set α) : Matroid α := + (M.dual ↾ C).dual + +def HasPackingCovering {α : Type*} (M₀ M₁ : Matroid α) : Prop := + ∃ P C S₀ S₁ I₀ I₁ : Set α, + Disjoint P C ∧ P ∪ C = M₀.E ∧ M₁.E = M₀.E ∧ + S₀ ⊆ P ∧ S₁ ⊆ P ∧ Disjoint S₀ S₁ ∧ + (M₀ ↾ P).Spanning S₀ ∧ (M₁ ↾ P).Spanning S₁ ∧ + I₀ ⊆ C ∧ I₁ ⊆ C ∧ + (contractOnto M₀ C).Indep I₀ ∧ + (contractOnto M₁ C).Indep I₁ ∧ I₀ ∪ I₁ = C + +theorem main : + Countable E ∧ Infinite E ∧ + ∃ M₀ M₁ : Matroid E, + M₀.E = Set.univ ∧ M₁.E = Set.univ ∧ + M₀.dual = M₀ ∧ M₁.dual = M₁ ∧ + (∀ I₀ I₁ : Set E, M₀.Indep I₀ → M₁.Indep I₁ → I₀ ∪ I₁ ≠ Set.univ) ∧ + ¬ HasPackingCovering M₀ M₁ := by + sorry + +end InfiniteMatroidCounterexample + +end OAI diff --git a/tasks/infinite-matroid/tests/grade.py b/tasks/infinite-matroid/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/infinite-matroid/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/infinite-matroid/tests/task.json b/tasks/infinite-matroid/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..97798f42937e626547bbb23c0f9586e663bcf36a --- /dev/null +++ b/tasks/infinite-matroid/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "InfiniteMatroid", + "comparator": { + "theorem_names": [ + "OAI.InfiniteMatroidCounterexample.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10957 +} \ No newline at end of file diff --git a/tasks/infinite-matroid/tests/test.sh b/tasks/infinite-matroid/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/infinite-matroid/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/interpolated-factors/environment/Dockerfile b/tasks/interpolated-factors/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/interpolated-factors/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/interpolated-factors/environment/fetch_mathlib.sh b/tasks/interpolated-factors/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/interpolated-factors/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/interpolated-factors/environment/lake-manifest.json b/tasks/interpolated-factors/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/interpolated-factors/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/interpolated-factors/environment/lakefile.lean b/tasks/interpolated-factors/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/interpolated-factors/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/interpolated-factors/environment/lean_setup.sh b/tasks/interpolated-factors/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/interpolated-factors/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/interpolated-factors/environment/pack_submission.py b/tasks/interpolated-factors/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/interpolated-factors/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/interpolated-factors/instruction.md b/tasks/interpolated-factors/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0a7edda4223e9d369423232db00d6963eca066fc --- /dev/null +++ b/tasks/interpolated-factors/instruction.md @@ -0,0 +1,276 @@ +# openai/math challenge `InterpolatedFactors` (family 287) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 287 of the release, *All nonabelian free group factors are isomorphic* +(Operator algebras). The family as a whole: Resolves the free group factor isomorphism problem: $L(\mathbb F_2)\cong L(\mathbb F_3)$, and hence all interpolated free group factors, including $L(\mathbb F_\infty)$, are isomorphic. Their common factor has fundamental group $\mathbb R_{>0}$. + +The challenge is `InterpolatedFactors`, also at `/opt/openai-math/challenges/InterpolatedFactors.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace FreeGroupFactorMain + +universe u uG + +open scoped ENNReal + +abbrev GroupHilbert (G : Type u) := lp (fun _ : G => ℂ) 2 +abbrev GroupOperator (G : Type u) := GroupHilbert G →L[ℂ] GroupHilbert G + +def leftTranslations (G : Type u) [Group G] : Set (GroupOperator G) := + {T | ∃ g : G, ∀ (ξ : GroupHilbert G) (h : G), (T ξ) h = ξ (g⁻¹ * h)} + +def groupVonNeumann (G : Type u) [Group G] : StarSubalgebra ℂ (GroupOperator G) := + StarSubalgebra.centralizer ℂ + (StarSubalgebra.centralizer ℂ (leftTranslations G) : Set (GroupOperator G)) + +def canonicalTrace {G : Type u} [Group G] (T : groupVonNeumann G) : ℂ := by + classical + exact ((T : GroupOperator G) (lp.single 2 (1 : G) (1 : ℂ))) 1 + +@[instance_reducible] def ultraweakOperatorTopology (G : Type u) : TopologicalSpace (GroupOperator G) := + ⨅ (ξ : lp (fun _ : ℕ => GroupHilbert G) 2) + (η : lp (fun _ : ℕ => GroupHilbert G) 2), + TopologicalSpace.induced + (fun T : GroupOperator G => ∑' k : ℕ, inner ℂ (η k) (T (ξ k))) + inferInstance + +@[instance_reducible] def groupUltraweakTopology (G : Type u) [Group G] : + TopologicalSpace (groupVonNeumann G) := + TopologicalSpace.induced (fun T : groupVonNeumann G => (T : GroupOperator G)) + (ultraweakOperatorTopology G) + +abbrev FreeGroupRank (n : ℕ) := FreeGroup (Fin n) + +instance groupVN_isClosed (G : Type uG) [Group G] : + IsClosed (groupVonNeumann G : Set (GroupOperator G)) := by + unfold groupVonNeumann + rw [StarSubalgebra.coe_centralizer] + exact Set.isClosed_centralizer _ + +instance groupVN_CStarAlgebra (G : Type uG) [Group G] : + CStarAlgebra (groupVonNeumann G) := inferInstance + +end FreeGroupFactorMain + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11 u_42 u_43 + +namespace FreeGroupFactorMain.Amplification + +open scoped ENNReal + +section +variable {A : Type u_1} {B : Type u_2} [CStarAlgebra A] [CStarAlgebra B] + +def cornerSubalgebra (p : A) (hp : IsStarProjection p) : NonUnitalStarSubalgebra ℂ A where + carrier := {x | p*x=x ∧ x*p=x} + zero_mem' := by simp + add_mem' hx hy := by constructor <;> simp [mul_add,add_mul,hx.1,hx.2,hy.1,hy.2] + mul_mem' hx hy := by + constructor + · rw [← mul_assoc,hx.1] + · rw [mul_assoc,hy.2] + smul_mem' c x hx := by + constructor + · rw [mul_smul_comm,hx.1] + · rw [smul_mul_assoc,hx.2] + star_mem' hx := by + constructor + · simpa only [star_mul,hp.isSelfAdjoint.star_eq] using congrArg star hx.2 + · simpa only [star_mul,hp.isSelfAdjoint.star_eq] using congrArg star hx.1 + +abbrev Corner (p : A) (hp : IsStarProjection p) := ↥(cornerSubalgebra p hp) + +instance cornerClosed (p : A) (hp : IsStarProjection p) : + IsClosed (cornerSubalgebra p hp : Set A) := + (isClosed_eq (continuous_const.mul continuous_id) continuous_id).inter + (isClosed_eq (continuous_id.mul continuous_const) continuous_id) + +instance cornerSemiring (p : A) (hp : IsStarProjection p) : Semiring (Corner p hp) where + __ : NonUnitalSemiring (Corner p hp) := inferInstance + one := ⟨p,hp.isIdempotentElem.eq,hp.isIdempotentElem.eq⟩ + one_mul x := Subtype.ext x.property.1 + mul_one x := Subtype.ext x.property.2 + +instance cornerRing (p : A) (hp : IsStarProjection p) : Ring (Corner p hp) where + __ : Semiring (Corner p hp) := inferInstance + __ : NonUnitalRing (Corner p hp) := inferInstance + +instance cornerAlgebra (p : A) (hp : IsStarProjection p) : Algebra ℂ (Corner p hp) := + Algebra.ofModule smul_mul_assoc mul_smul_comm + +instance cornerNormedRing (p : A) (hp : IsStarProjection p) : NormedRing (Corner p hp) where + __ : Ring (Corner p hp) := inferInstance + __ : NonUnitalNormedRing (Corner p hp) := inferInstance + +instance cornerCStarAlgebra (p : A) (hp : IsStarProjection p) : CStarAlgebra (Corner p hp) where + __ : NonUnitalCStarAlgebra (Corner p hp) := inferInstance + __ : NormedRing (Corner p hp) := inferInstance + __ : Algebra ℂ (Corner p hp) := inferInstance + norm_smul_le := norm_smul_le + +end + +section +variable {A : Type u_3} {B : Type u_4} [CStarAlgebra A] [CStarAlgebra B] + +@[instance_reducible] def cornerTopology (𝒯 : TopologicalSpace A) + (p : A) (hp : IsStarProjection p) : TopologicalSpace (Corner p hp) := + TopologicalSpace.induced (fun x : Corner p hp => (x : A)) 𝒯 + +def normalizedCornerTrace (τ : A → ℂ) (t : ℝ) (p : A) (hp : IsStarProjection p) + (x : Corner p hp) : ℂ := (t : ℂ)⁻¹ * τ x + +end + +def stabilizedRightTranslations (G : Type u_5) [Group G] : Set (GroupOperator (ℕ × G)) := + {T | ∃ g : G, ∀ (ξ : GroupHilbert (ℕ × G)) (x : ℕ × G), + T ξ x = ξ (x.1,x.2*g)} + +def stabilization (G : Type u_6) [Group G] : StarSubalgebra ℂ (GroupOperator (ℕ × G)) := + StarSubalgebra.centralizer ℂ (stabilizedRightTranslations G) + +instance stabilization_isClosed (G : Type u_7) [Group G] : + IsClosed (stabilization G : Set (GroupOperator (ℕ × G))) := by + rw [stabilization,StarSubalgebra.coe_centralizer] + exact Set.isClosed_centralizer _ + +instance stabilization_CStarAlgebra (G : Type u_8) [Group G] : CStarAlgebra (stabilization G) := + inferInstance + +def stabilizedProjectionTrace {G : Type u_9} [Group G] (p : stabilization G) : ℝ≥0∞ := by + classical + exact ∑' k : ℕ, ENNReal.ofReal (‖(p : GroupOperator (ℕ × G)) + (lp.single 2 (k,1) (1 : ℂ))‖ ^ 2) + +def stabilizedTrace {G : Type u_10} [Group G] (T : stabilization G) : ℂ := by + classical + exact ∑' k : ℕ, inner ℂ (lp.single 2 (k,1) (1 : ℂ)) + ((T : GroupOperator (ℕ × G)) (lp.single 2 (k,1) (1 : ℂ))) + +@[instance_reducible] def stabilizationTopology (G : Type u_11) [Group G] : + TopologicalSpace (stabilization G) := + TopologicalSpace.induced (fun T : stabilization G => (T : GroupOperator (ℕ × G))) + (ultraweakOperatorTopology (ℕ × G)) + +section +variable {A : Type u_42} {B : Type u_43} [CStarAlgebra A] [CStarAlgebra B] + +structure NormalTracialEquiv (τA : A → ℂ) (τB : B → ℂ) + (𝒯A : TopologicalSpace A) (𝒯B : TopologicalSpace B) where + equiv : A ≃⋆ₐ[ℂ] B + trace_eq : ∀x,τB (equiv x)=τA x + normal : @Continuous _ _ 𝒯A 𝒯B equiv + inverse_normal : @Continuous _ _ 𝒯B 𝒯A equiv.symm + +end + +end FreeGroupFactorMain.Amplification + +namespace FreeGroupFactorMain.Interpolation + +open Amplification +open scoped ENNReal + +abbrev RankTwoProjection := {p : stabilization (FreeGroupRank 2) // IsStarProjection p} + +instance rankTwoProjectionInhabited : Inhabited RankTwoProjection := + ⟨⟨0,IsStarProjection.zero _⟩⟩ + +def selectedProjection (a : ℝ) : RankTwoProjection := + Classical.epsilon (fun p : RankTwoProjection => stabilizedProjectionTrace p.val=ENNReal.ofReal a) + +def interpolationScale (r : ℝ) : ℝ := (Real.sqrt (r-1))⁻¹ + +inductive Model where + | integer (n : ℕ) + | continuous (r : ℝ) + | infinity + +def Model.Algebra : Model → Type + | .integer n => groupVonNeumann (FreeGroupRank n) + | .continuous r => Corner (selectedProjection (interpolationScale r)).val + (selectedProjection (interpolationScale r)).property + | .infinity => groupVonNeumann (FreeGroup ℕ) + +instance modelCStarAlgebra (m : Model) : CStarAlgebra m.Algebra := by + cases m <;> dsimp only [Model.Algebra] <;> infer_instance + +def Model.trace : (m : Model) → m.Algebra → ℂ + | .integer _ => canonicalTrace + | .continuous r => normalizedCornerTrace stabilizedTrace (interpolationScale r) + (selectedProjection (interpolationScale r)).val (selectedProjection (interpolationScale r)).property + | .infinity => canonicalTrace + +@[instance_reducible] def Model.topology : (m : Model) → TopologicalSpace m.Algebra + | .integer n => groupUltraweakTopology (FreeGroupRank n) + | .continuous r => cornerTopology (stabilizationTopology (FreeGroupRank 2)) + (selectedProjection (interpolationScale r)).val (selectedProjection (interpolationScale r)).property + | .infinity => groupUltraweakTopology (FreeGroup ℕ) + +def parameterModel (r : ℝ≥0∞) : Model := by + classical + exact if r=⊤ then .infinity else + if h : ∃n : ℕ,r=(n:ℝ≥0∞) then .integer h.choose else .continuous r.toReal + +abbrev InterpolatedFactor (r : ℝ≥0∞) := (parameterModel r).Algebra +abbrev interpolatedTrace (r : ℝ≥0∞) := (parameterModel r).trace +abbrev interpolatedTopology (r : ℝ≥0∞) := (parameterModel r).topology + +theorem allInterpolatedIsomorphic (r s : ℝ≥0∞) (hr : 1` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/interpolated-factors/solution/closure.txt b/tasks/interpolated-factors/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a43902f2e49af09b441d1ea101b17aba2a819f3d --- /dev/null +++ b/tasks/interpolated-factors/solution/closure.txt @@ -0,0 +1,77 @@ +OAI.Analysis.FreeGroupFactor.Cocycles +OAI.Analysis.FreeGroupFactor.FiniteActive +OAI.Analysis.FreeGroupFactor.FiniteMoments +OAI.Analysis.FreeGroupFactor.FiniteRank +OAI.Analysis.FreeGroupFactor.FreeSum +OAI.Analysis.FreeGroupFactor.Generation +OAI.Analysis.FreeGroupFactor.GlobalODE +OAI.Analysis.FreeGroupFactor.InfiniteGeneration +OAI.Analysis.FreeGroupFactor.LaurentApproximation +OAI.Analysis.FreeGroupFactor.LocalAutomorphism +OAI.Analysis.FreeGroupFactor.Main +OAI.Analysis.FreeGroupFactor.Model +OAI.Analysis.FreeGroupFactor.MomentFlow +OAI.Analysis.FreeGroupFactor.NCPolynomial +OAI.Analysis.FreeGroupFactor.Nielsen +OAI.Analysis.FreeGroupFactor.NormalExtension +OAI.Analysis.FreeGroupFactor.Operators +OAI.Analysis.FreeGroupFactor.PolynomialFlow +OAI.Analysis.FreeGroupFactor.RadialCoefficients +OAI.Analysis.FreeGroupFactor.RankTwoCoefficients +OAI.Analysis.FreeGroupFactor.RankTwoCounting +OAI.Analysis.FreeGroupFactor.RankTwoWords +OAI.Analysis.FreeGroupFactor.Reducing +OAI.Analysis.FreeGroupFactor.SmallCocycle +OAI.Analysis.FreeGroupFactor.Taylor +OAI.Analysis.FreeGroupFactor.TraceCocycle +OAI.Analysis.FreeGroupFactor.UnitaryEvaluation +OAI.Analysis.InterpolatedFactors.Absorption +OAI.Analysis.InterpolatedFactors.Ambient +OAI.Analysis.InterpolatedFactors.AmbientSystem +OAI.Analysis.InterpolatedFactors.Basic +OAI.Analysis.InterpolatedFactors.CornerGaussian +OAI.Analysis.InterpolatedFactors.CornerGeneration +OAI.Analysis.InterpolatedFactors.CornerIndex +OAI.Analysis.InterpolatedFactors.CornerRange +OAI.Analysis.InterpolatedFactors.CornerRepresentation +OAI.Analysis.InterpolatedFactors.CornerStabilization +OAI.Analysis.InterpolatedFactors.Cyclic +OAI.Analysis.InterpolatedFactors.Diagonal +OAI.Analysis.InterpolatedFactors.Diffuse +OAI.Analysis.InterpolatedFactors.DoubleTrace +OAI.Analysis.InterpolatedFactors.FiniteCorners +OAI.Analysis.InterpolatedFactors.Fock +OAI.Analysis.InterpolatedFactors.Fresh +OAI.Analysis.InterpolatedFactors.Gaussian +OAI.Analysis.InterpolatedFactors.GaussianAlgebra +OAI.Analysis.InterpolatedFactors.GroupBridge +OAI.Analysis.InterpolatedFactors.Haar +OAI.Analysis.InterpolatedFactors.Interpolation +OAI.Analysis.InterpolatedFactors.InverseRecognition +OAI.Analysis.InterpolatedFactors.Jacobi +OAI.Analysis.InterpolatedFactors.Matrices +OAI.Analysis.InterpolatedFactors.MatrixNormal +OAI.Analysis.InterpolatedFactors.Mixed +OAI.Analysis.InterpolatedFactors.NormalEquiv +OAI.Analysis.InterpolatedFactors.NormalTransport +OAI.Analysis.InterpolatedFactors.OperatorSums +OAI.Analysis.InterpolatedFactors.PairedAbsorption +OAI.Analysis.InterpolatedFactors.Polar +OAI.Analysis.InterpolatedFactors.Positive +OAI.Analysis.InterpolatedFactors.Recognition +OAI.Analysis.InterpolatedFactors.RelativeClosure +OAI.Analysis.InterpolatedFactors.Rerouting +OAI.Analysis.InterpolatedFactors.Restriction +OAI.Analysis.InterpolatedFactors.Rotations +OAI.Analysis.InterpolatedFactors.ScalarGeneration +OAI.Analysis.InterpolatedFactors.ScalarSystem +OAI.Analysis.InterpolatedFactors.Scaling +OAI.Analysis.InterpolatedFactors.Spatial +OAI.Analysis.InterpolatedFactors.Spectral +OAI.Analysis.InterpolatedFactors.Splitting +OAI.Analysis.InterpolatedFactors.Stabilization +OAI.Analysis.InterpolatedFactors.StabilizationIso +OAI.Analysis.InterpolatedFactors.Subalgebras +OAI.Analysis.InterpolatedFactors.Ultraweak +OAI.Analysis.InterpolatedFactors.UniformSpectral +OAI.Analysis.InterpolatedFactors.WeightedCorner diff --git a/tasks/interpolated-factors/solution/reference.py b/tasks/interpolated-factors/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/interpolated-factors/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/interpolated-factors/solution/solve.sh b/tasks/interpolated-factors/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0211cb8a9eff89b8714b37affc6ab43697bfff25 --- /dev/null +++ b/tasks/interpolated-factors/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of InterpolatedFactors, i.e. module OAI.Analysis.InterpolatedFactors.Interpolation and the +# 77 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.InterpolatedFactors.Interpolation /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of InterpolatedFactors" diff --git a/tasks/interpolated-factors/task.toml b/tasks/interpolated-factors/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4ca2a17181519780e26842cee91fb055906c53fd --- /dev/null +++ b/tasks/interpolated-factors/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/interpolated-factors" +version = "1.0.0" +description = "Prove InterpolatedFactors (openai/math family 287: All nonabelian free group factors are isomorphic) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/InterpolatedFactors.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "InterpolatedFactors" +family = "287" +family_title = "All nonabelian free group factors are isomorphic" +subject = "Operator algebras" +theorems = ["OAI.FreeGroupFactorMain.Interpolation.allInterpolatedIsomorphic"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.InterpolatedFactors.Interpolation" +reference_modules = 77 +reference_lean_bytes = 1249281 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1971 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12824 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/interpolated-factors/tests/Challenge.lean b/tasks/interpolated-factors/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0075fd568149594df4dc90ff7228d86b12b97381 --- /dev/null +++ b/tasks/interpolated-factors/tests/Challenge.lean @@ -0,0 +1,225 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace FreeGroupFactorMain + +universe u uG + +open scoped ENNReal + +abbrev GroupHilbert (G : Type u) := lp (fun _ : G => ℂ) 2 +abbrev GroupOperator (G : Type u) := GroupHilbert G →L[ℂ] GroupHilbert G + +def leftTranslations (G : Type u) [Group G] : Set (GroupOperator G) := + {T | ∃ g : G, ∀ (ξ : GroupHilbert G) (h : G), (T ξ) h = ξ (g⁻¹ * h)} + +def groupVonNeumann (G : Type u) [Group G] : StarSubalgebra ℂ (GroupOperator G) := + StarSubalgebra.centralizer ℂ + (StarSubalgebra.centralizer ℂ (leftTranslations G) : Set (GroupOperator G)) + +def canonicalTrace {G : Type u} [Group G] (T : groupVonNeumann G) : ℂ := by + classical + exact ((T : GroupOperator G) (lp.single 2 (1 : G) (1 : ℂ))) 1 + +@[instance_reducible] def ultraweakOperatorTopology (G : Type u) : TopologicalSpace (GroupOperator G) := + ⨅ (ξ : lp (fun _ : ℕ => GroupHilbert G) 2) + (η : lp (fun _ : ℕ => GroupHilbert G) 2), + TopologicalSpace.induced + (fun T : GroupOperator G => ∑' k : ℕ, inner ℂ (η k) (T (ξ k))) + inferInstance + +@[instance_reducible] def groupUltraweakTopology (G : Type u) [Group G] : + TopologicalSpace (groupVonNeumann G) := + TopologicalSpace.induced (fun T : groupVonNeumann G => (T : GroupOperator G)) + (ultraweakOperatorTopology G) + +abbrev FreeGroupRank (n : ℕ) := FreeGroup (Fin n) + +instance groupVN_isClosed (G : Type uG) [Group G] : + IsClosed (groupVonNeumann G : Set (GroupOperator G)) := by + unfold groupVonNeumann + rw [StarSubalgebra.coe_centralizer] + exact Set.isClosed_centralizer _ + +instance groupVN_CStarAlgebra (G : Type uG) [Group G] : + CStarAlgebra (groupVonNeumann G) := inferInstance + +end FreeGroupFactorMain + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11 u_42 u_43 + +namespace FreeGroupFactorMain.Amplification + +open scoped ENNReal + +section +variable {A : Type u_1} {B : Type u_2} [CStarAlgebra A] [CStarAlgebra B] + +def cornerSubalgebra (p : A) (hp : IsStarProjection p) : NonUnitalStarSubalgebra ℂ A where + carrier := {x | p*x=x ∧ x*p=x} + zero_mem' := by simp + add_mem' hx hy := by constructor <;> simp [mul_add,add_mul,hx.1,hx.2,hy.1,hy.2] + mul_mem' hx hy := by + constructor + · rw [← mul_assoc,hx.1] + · rw [mul_assoc,hy.2] + smul_mem' c x hx := by + constructor + · rw [mul_smul_comm,hx.1] + · rw [smul_mul_assoc,hx.2] + star_mem' hx := by + constructor + · simpa only [star_mul,hp.isSelfAdjoint.star_eq] using congrArg star hx.2 + · simpa only [star_mul,hp.isSelfAdjoint.star_eq] using congrArg star hx.1 + +abbrev Corner (p : A) (hp : IsStarProjection p) := ↥(cornerSubalgebra p hp) + +instance cornerClosed (p : A) (hp : IsStarProjection p) : + IsClosed (cornerSubalgebra p hp : Set A) := + (isClosed_eq (continuous_const.mul continuous_id) continuous_id).inter + (isClosed_eq (continuous_id.mul continuous_const) continuous_id) + +instance cornerSemiring (p : A) (hp : IsStarProjection p) : Semiring (Corner p hp) where + __ : NonUnitalSemiring (Corner p hp) := inferInstance + one := ⟨p,hp.isIdempotentElem.eq,hp.isIdempotentElem.eq⟩ + one_mul x := Subtype.ext x.property.1 + mul_one x := Subtype.ext x.property.2 + +instance cornerRing (p : A) (hp : IsStarProjection p) : Ring (Corner p hp) where + __ : Semiring (Corner p hp) := inferInstance + __ : NonUnitalRing (Corner p hp) := inferInstance + +instance cornerAlgebra (p : A) (hp : IsStarProjection p) : Algebra ℂ (Corner p hp) := + Algebra.ofModule smul_mul_assoc mul_smul_comm + +instance cornerNormedRing (p : A) (hp : IsStarProjection p) : NormedRing (Corner p hp) where + __ : Ring (Corner p hp) := inferInstance + __ : NonUnitalNormedRing (Corner p hp) := inferInstance + +instance cornerCStarAlgebra (p : A) (hp : IsStarProjection p) : CStarAlgebra (Corner p hp) where + __ : NonUnitalCStarAlgebra (Corner p hp) := inferInstance + __ : NormedRing (Corner p hp) := inferInstance + __ : Algebra ℂ (Corner p hp) := inferInstance + norm_smul_le := norm_smul_le + +end + +section +variable {A : Type u_3} {B : Type u_4} [CStarAlgebra A] [CStarAlgebra B] + +@[instance_reducible] def cornerTopology (𝒯 : TopologicalSpace A) + (p : A) (hp : IsStarProjection p) : TopologicalSpace (Corner p hp) := + TopologicalSpace.induced (fun x : Corner p hp => (x : A)) 𝒯 + +def normalizedCornerTrace (τ : A → ℂ) (t : ℝ) (p : A) (hp : IsStarProjection p) + (x : Corner p hp) : ℂ := (t : ℂ)⁻¹ * τ x + +end + +def stabilizedRightTranslations (G : Type u_5) [Group G] : Set (GroupOperator (ℕ × G)) := + {T | ∃ g : G, ∀ (ξ : GroupHilbert (ℕ × G)) (x : ℕ × G), + T ξ x = ξ (x.1,x.2*g)} + +def stabilization (G : Type u_6) [Group G] : StarSubalgebra ℂ (GroupOperator (ℕ × G)) := + StarSubalgebra.centralizer ℂ (stabilizedRightTranslations G) + +instance stabilization_isClosed (G : Type u_7) [Group G] : + IsClosed (stabilization G : Set (GroupOperator (ℕ × G))) := by + rw [stabilization,StarSubalgebra.coe_centralizer] + exact Set.isClosed_centralizer _ + +instance stabilization_CStarAlgebra (G : Type u_8) [Group G] : CStarAlgebra (stabilization G) := + inferInstance + +def stabilizedProjectionTrace {G : Type u_9} [Group G] (p : stabilization G) : ℝ≥0∞ := by + classical + exact ∑' k : ℕ, ENNReal.ofReal (‖(p : GroupOperator (ℕ × G)) + (lp.single 2 (k,1) (1 : ℂ))‖ ^ 2) + +def stabilizedTrace {G : Type u_10} [Group G] (T : stabilization G) : ℂ := by + classical + exact ∑' k : ℕ, inner ℂ (lp.single 2 (k,1) (1 : ℂ)) + ((T : GroupOperator (ℕ × G)) (lp.single 2 (k,1) (1 : ℂ))) + +@[instance_reducible] def stabilizationTopology (G : Type u_11) [Group G] : + TopologicalSpace (stabilization G) := + TopologicalSpace.induced (fun T : stabilization G => (T : GroupOperator (ℕ × G))) + (ultraweakOperatorTopology (ℕ × G)) + +section +variable {A : Type u_42} {B : Type u_43} [CStarAlgebra A] [CStarAlgebra B] + +structure NormalTracialEquiv (τA : A → ℂ) (τB : B → ℂ) + (𝒯A : TopologicalSpace A) (𝒯B : TopologicalSpace B) where + equiv : A ≃⋆ₐ[ℂ] B + trace_eq : ∀x,τB (equiv x)=τA x + normal : @Continuous _ _ 𝒯A 𝒯B equiv + inverse_normal : @Continuous _ _ 𝒯B 𝒯A equiv.symm + +end + +end FreeGroupFactorMain.Amplification + +namespace FreeGroupFactorMain.Interpolation + +open Amplification +open scoped ENNReal + +abbrev RankTwoProjection := {p : stabilization (FreeGroupRank 2) // IsStarProjection p} + +instance rankTwoProjectionInhabited : Inhabited RankTwoProjection := + ⟨⟨0,IsStarProjection.zero _⟩⟩ + +def selectedProjection (a : ℝ) : RankTwoProjection := + Classical.epsilon (fun p : RankTwoProjection => stabilizedProjectionTrace p.val=ENNReal.ofReal a) + +def interpolationScale (r : ℝ) : ℝ := (Real.sqrt (r-1))⁻¹ + +inductive Model where + | integer (n : ℕ) + | continuous (r : ℝ) + | infinity + +def Model.Algebra : Model → Type + | .integer n => groupVonNeumann (FreeGroupRank n) + | .continuous r => Corner (selectedProjection (interpolationScale r)).val + (selectedProjection (interpolationScale r)).property + | .infinity => groupVonNeumann (FreeGroup ℕ) + +instance modelCStarAlgebra (m : Model) : CStarAlgebra m.Algebra := by + cases m <;> dsimp only [Model.Algebra] <;> infer_instance + +def Model.trace : (m : Model) → m.Algebra → ℂ + | .integer _ => canonicalTrace + | .continuous r => normalizedCornerTrace stabilizedTrace (interpolationScale r) + (selectedProjection (interpolationScale r)).val (selectedProjection (interpolationScale r)).property + | .infinity => canonicalTrace + +@[instance_reducible] def Model.topology : (m : Model) → TopologicalSpace m.Algebra + | .integer n => groupUltraweakTopology (FreeGroupRank n) + | .continuous r => cornerTopology (stabilizationTopology (FreeGroupRank 2)) + (selectedProjection (interpolationScale r)).val (selectedProjection (interpolationScale r)).property + | .infinity => groupUltraweakTopology (FreeGroup ℕ) + +def parameterModel (r : ℝ≥0∞) : Model := by + classical + exact if r=⊤ then .infinity else + if h : ∃n : ℕ,r=(n:ℝ≥0∞) then .integer h.choose else .continuous r.toReal + +abbrev InterpolatedFactor (r : ℝ≥0∞) := (parameterModel r).Algebra +abbrev interpolatedTrace (r : ℝ≥0∞) := (parameterModel r).trace +abbrev interpolatedTopology (r : ℝ≥0∞) := (parameterModel r).topology + +theorem allInterpolatedIsomorphic (r s : ℝ≥0∞) (hr : 1 Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/interpolated-factors/tests/task.json b/tasks/interpolated-factors/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..228969c823951527e85695b74d3af0c579f19eca --- /dev/null +++ b/tasks/interpolated-factors/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "InterpolatedFactors", + "comparator": { + "theorem_names": [ + "OAI.FreeGroupFactorMain.Interpolation.allInterpolatedIsomorphic" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11924 +} \ No newline at end of file diff --git a/tasks/interpolated-factors/tests/test.sh b/tasks/interpolated-factors/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/interpolated-factors/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/irrational-rotation/environment/Dockerfile b/tasks/irrational-rotation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/irrational-rotation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/irrational-rotation/environment/fetch_mathlib.sh b/tasks/irrational-rotation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/irrational-rotation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/irrational-rotation/environment/lake-manifest.json b/tasks/irrational-rotation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/irrational-rotation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/irrational-rotation/environment/lakefile.lean b/tasks/irrational-rotation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/irrational-rotation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/irrational-rotation/environment/lean_setup.sh b/tasks/irrational-rotation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/irrational-rotation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/irrational-rotation/environment/pack_submission.py b/tasks/irrational-rotation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/irrational-rotation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/irrational-rotation/instruction.md b/tasks/irrational-rotation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..104024d5fe282ceccd03b696ffeb2519f4bdaee3 --- /dev/null +++ b/tasks/irrational-rotation/instruction.md @@ -0,0 +1,900 @@ +# openai/math challenge `IrrationalRotation` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `IrrationalRotation`, also at `/opt/openai-math/challenges/IrrationalRotation.lean`: + +```lean +import Mathlib + +namespace OAI + +section +noncomputable section +open Filter MeasureTheory +open scoped ENNReal Topology + +namespace Invariant233 + +abbrev Circle := AddCircle (1 : ℝ) + +def circleMeasure : Measure Circle := volume + +def negLogCost (t : ℝ) : ℝ≥0∞ := + if t = 0 then ∞ else ENNReal.ofReal (-Real.log |t|) + +def HasNegInfiniteLogIntegral {X : Type*} [MeasurableSpace X] + (μ : Measure X) (f : X → ℝ) : Prop := + (∫⁻ x, negLogCost (f x) ∂μ) = ∞ + +def scalarWeightDeterminant {X : Type*} [MeasurableSpace X] + (μ : Measure X) (f : X → ℝ) : ℝ≥0∞ := + EReal.exp (-((∫⁻ x, negLogCost (f x) ∂μ) : EReal)) + +def NormQuasinilpotent {A : Type*} [NormedRing A] (T : A) : Prop := + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) + +def IsContinuousCircleWeight (f : Circle → ℝ) : Prop := + Continuous f ∧ (∀ x, 0 ≤ f x ∧ f x ≤ 1) ∧ + (∀ x, f x = 0 ↔ x = 0) ∧ HasNegInfiniteLogIntegral circleMeasure f + +end Invariant233 + +end +end + +section +noncomputable section +open scoped ENNReal +namespace Invariant233.WeightedShift + +abbrev Hilbert := lp (fun _ : ℤ => ℂ) 2 +abbrev Weight := lp (fun _ : ℤ => ℂ) ∞ + +def reindex (e : Equiv.Perm ℤ) : Hilbert ≃ₗᵢ[ℂ] Hilbert where + toFun ξ := ⟨fun k => ξ (e k), memℓp_gen <| + (e.summable_iff).2 ((lp.memℓp ξ).summable (by norm_num))⟩ + invFun ξ := ⟨fun k => ξ (e.symm k), memℓp_gen <| + (e.symm.summable_iff).2 ((lp.memℓp ξ).summable (by norm_num))⟩ + left_inv ξ := by ext k; simp + right_inv ξ := by ext k; simp + map_add' ξ η := by ext k; rfl + map_smul' c ξ := by ext k; rfl + norm_map' ξ := by + rw [lp.norm_eq_tsum_rpow (by norm_num), lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.tsum_eq (fun k => ‖ξ k‖ ^ (2 : ENNReal).toReal) + +def shift (m : ℤ) : Hilbert ≃ₗᵢ[ℂ] Hilbert := reindex (Equiv.addRight (-m)) + +def diagonal (w : Weight) : Hilbert →L[ℂ] Hilbert := + lp.mapCLM 2 (fun k => w k • ContinuousLinearMap.id ℂ ℂ) (norm_nonneg w) + (fun k => by + let : T0Space ℂ := @MetricSpace.instT0Space ℂ Complex.instNormedAddCommGroup.toMetricSpace + simpa [norm_smul] using lp.norm_apply_le_norm (by simp) w k) + +def diagonalAlgHom : Weight →ₐ[ℂ] (Hilbert →L[ℂ] Hilbert) where + toFun := diagonal + map_one' := by + ext ξ k + change (1 : ℂ) * ξ k = ξ k + exact one_mul _ + map_mul' w v := by + ext ξ k + change (w k * v k) * ξ k = w k * (v k * ξ k) + exact mul_assoc _ _ _ + map_zero' := by + ext ξ k + change (0 : ℂ) * ξ k = 0 + exact zero_mul _ + map_add' w v := by + ext ξ k + change (w k + v k) * ξ k = w k * ξ k + v k * ξ k + exact add_mul _ _ _ + commutes' c := by + ext ξ k + change c * ξ k = c * ξ k + rfl + +def translate (w : Weight) (m : ℤ) : Weight := + ⟨fun k => w (k + m), memℓp_infty <| by + refine ⟨‖w‖, ?_⟩ + rintro r ⟨k, rfl⟩ + exact lp.norm_apply_le_norm (by simp) w (k + m)⟩ + +def operator (w : Weight) : Hilbert →L[ℂ] Hilbert := + (shift 1).toLinearIsometry.toContinuousLinearMap.comp (diagonal w) + +def orbitProduct (w : Weight) (n : ℕ) : Weight := + ⟨fun k => ∏ j ∈ Finset.range n, w (k + j), memℓp_infty <| by + refine ⟨‖w‖ ^ n, ?_⟩ + rintro r ⟨k, rfl⟩ + calc + ‖∏ j ∈ Finset.range n, w (k + j)‖ ≤ + ∏ j ∈ Finset.range n, ‖w (k + j)‖ := le_of_eq (norm_prod _ _) + _ ≤ ∏ _j ∈ Finset.range n, ‖w‖ := by + apply Finset.prod_le_prod₀ + · intro j hj; exact norm_nonneg _ + · intro j hj; exact lp.norm_apply_le_norm (by simp) w _ + _ = ‖w‖ ^ n := by simp⟩ + +def tailWeight (m : ℤ) : Weight := + ⟨fun k => if m ≤ k then 1 else 0, memℓp_infty <| by + refine ⟨1, ?_⟩ + rintro r ⟨k, rfl⟩ + by_cases h : m ≤ k <;> simp [h]⟩ + +def tailProjection (m : ℤ) : Hilbert →L[ℂ] Hilbert := diagonal (tailWeight m) + +end Invariant233.WeightedShift + +end +end + +section +open scoped Pointwise + +namespace Invariant233 + +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] + +local instance instStarModuleGenerated : StarModule ℂ (H →L[ℂ] H) := + ContinuousLinearMap.instStarModuleId + +noncomputable def vonNeumannGenerated (s : Set (H →L[ℂ] H)) : VonNeumannAlgebra H where + toStarSubalgebra := + StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) + centralizer_centralizer' := by + change Set.centralizer (Set.centralizer + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : + Set (H →L[ℂ] H))) = _ + rw [StarSubalgebra.coe_centralizer_centralizer] + rw [Set.centralizer_centralizer_centralizer] + exact (StarSubalgebra.coe_centralizer_centralizer ℂ s).symm + +end Invariant233 + +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal lp Topology + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace Invariant233.WeightedShift +variable {X : Type*} [MeasurableSpace X] {μ : Measure X} + +theorem diagonal_value (w : Weight) (v : Hilbert) (i : ℤ) : + diagonal w v i = w i * v i := rfl + +theorem diagonal_bound (w : Weight) (C : ℝ) (hw : ‖w‖ ≤ C) (v : Hilbert) : + ‖diagonal w v‖ ≤ C * ‖v‖ := by + apply (diagonal w).le_of_opNorm_le + exact (lp.norm_mapCLM_le 2 _ (norm_nonneg w) _).trans hw + +theorem diagonal_aestronglyMeasurable (a : X → Weight) (C : ℝ) (_hC : 0 ≤ C) + (_ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + {f : X → Hilbert} (hf : AEStronglyMeasurable f μ) : + AEStronglyMeasurable (fun x => diagonal (a x) (f x)) μ := by + classical + let : Nonempty (Finset ℤ) := ⟨∅⟩ + let F : Finset ℤ → X → Hilbert := + fun s => ∑ i ∈ s, fun x => lp.single 2 i (a x i * f x i) + apply aestronglyMeasurable_of_tendsto_ae (atTop : Filter (Finset ℤ)) + (f := F) + · intro s + apply Finset.aestronglyMeasurable_sum + intro i hi + exact (lp.singleContinuousLinearMap ℂ (fun _ : ℤ => ℂ) 2 i).continuous.comp_aestronglyMeasurable + ((hm i).mul ((lp.evalCLM ℂ (fun _ : ℤ => ℂ) 2 i).continuous.comp_aestronglyMeasurable hf)) + · apply Filter.Eventually.of_forall + intro x + simpa only [F, Finset.sum_apply, diagonal_value, HasSum, SummationFilter.unconditional] using + lp.hasSum_single (by norm_num) (diagonal (a x) (f x)) + +def fieldDiagonalVec (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + (f : Lp (Hilbert) 2 μ) : Lp (Hilbert) 2 μ := + ((Lp.memLp f).of_le_mul + (diagonal_aestronglyMeasurable a C hC ha hm (Lp.aestronglyMeasurable f)) + (Filter.Eventually.of_forall fun x => diagonal_bound (a x) C (ha x) (f x))).toLp _ + +theorem fieldDiagonalVec_ae (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + (f : Lp (Hilbert) 2 μ) : + fieldDiagonalVec a C hC ha hm f =ᵐ[μ] + fun x => diagonal (a x) (f x) := + MemLp.coeFn_toLp _ + +def fieldDiagonalLinear (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) : + Lp (Hilbert) 2 μ →ₗ[ℂ] Lp (Hilbert) 2 μ where + toFun := fieldDiagonalVec a C hC ha hm + map_add' f g := by + apply Lp.ext + filter_upwards [fieldDiagonalVec_ae a C hC ha hm (f + g), + fieldDiagonalVec_ae a C hC ha hm f, fieldDiagonalVec_ae a C hC ha hm g, + Lp.coeFn_add f g, Lp.coeFn_add + (fieldDiagonalVec a C hC ha hm f) (fieldDiagonalVec a C hC ha hm g)] + with x hfg hf hg hsum hout + simp only [Pi.add_apply] at hsum hout + rw [hfg, hout, hf, hg, hsum, map_add] + map_smul' c f := by + change fieldDiagonalVec a C hC ha hm (c • f) = c • fieldDiagonalVec a C hC ha hm f + apply Lp.ext + filter_upwards [fieldDiagonalVec_ae a C hC ha hm (c • f), + fieldDiagonalVec_ae a C hC ha hm f, Lp.coeFn_smul c f, + Lp.coeFn_smul c (fieldDiagonalVec a C hC ha hm f)] with x hcf hf hsmul hout + simp only [Pi.smul_apply] at hsmul hout + rw [hcf, hout, hf, hsmul, map_smul] + +def fieldDiagonal (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) : + Lp (Hilbert) 2 μ →L[ℂ] Lp (Hilbert) 2 μ := + (fieldDiagonalLinear a C hC ha hm).mkContinuous C (by + intro f + apply Lp.norm_le_mul_norm_of_ae_le_mul + change ∀ᵐ x ∂μ, ‖fieldDiagonalVec a C hC ha hm f x‖ ≤ C * ‖f x‖ + filter_upwards [fieldDiagonalVec_ae a C hC ha hm f] with x hx + rw [hx] + exact diagonal_bound (a x) C (ha x) (f x)) + +end Invariant233.WeightedShift + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace Invariant233.Rotation + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +instance circleMeasure_probability : IsProbabilityMeasure circleMeasure := by + constructor + change volume (Set.univ : Set Circle) = 1 + exact UnitAddCircle.measure_univ + +abbrev Fiber := WeightedShift.Hilbert +abbrev Hilbert := MeasureTheory.Lp Fiber 2 circleMeasure + +def action (θ : ℝ) (k : ℤ) (x : Circle) : Circle := + x + k • (θ : Circle) + +def U : Hilbert →L[ℂ] Hilbert := + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap.compLpL 2 circleMeasure + +def orbitWeight (θ : ℝ) (a : C(Circle, ℂ)) (x : Circle) : WeightedShift.Weight := + ⟨fun k => a (action θ k x), memℓp_infty <| by + refine ⟨‖a‖, ?_⟩ + rintro r ⟨k, rfl⟩ + exact a.norm_coe_le_norm _⟩ + +def character : C(Circle, ℂ) := fourier 1 + +def representation (θ : ℝ) (a : C(Circle, ℂ)) : Hilbert →L[ℂ] Hilbert := + WeightedShift.fieldDiagonal (orbitWeight θ a) ‖a‖ (norm_nonneg a) + (fun x => lp.norm_le_of_forall_le (norm_nonneg a) (fun k => a.norm_coe_le_norm _)) + (fun k => by + let : T0Space ℝ := @MetricSpace.instT0Space ℝ Real.metricSpace + let : T0Space ℂ := @MetricSpace.instT0Space ℂ Complex.instNormedAddCommGroup.toMetricSpace + change AEStronglyMeasurable (fun x : Circle => a (x + k • (θ : Circle))) circleMeasure + exact (a.continuous.comp (continuous_id.add continuous_const)).aestronglyMeasurable) + +def V (θ : ℝ) : Hilbert →L[ℂ] Hilbert := representation θ character + +def algebra (θ : ℝ) : VonNeumannAlgebra Hilbert := + vonNeumannGenerated ({U, V θ} : Set (Hilbert →L[ℂ] Hilbert)) + +def weighted (θ : ℝ) (a : C(Circle, ℂ)) : Hilbert →L[ℂ] Hilbert := + U * representation θ a + +def complexWeight (f : C(Circle, ℝ)) : C(Circle, ℂ) := + ⟨fun x => (f x : ℂ), Complex.continuous_ofReal.comp f.continuous⟩ + +def weightedReal (θ : ℝ) (f : C(Circle, ℝ)) : Hilbert →L[ℂ] Hilbert := + weighted θ (complexWeight f) + +def vacuum : Hilbert := Lp.const 2 circleMeasure (lp.single 2 (0 : ℤ) (1 : ℂ)) + +def vacuumFunctional (T : Hilbert →L[ℂ] Hilbert) : ℂ := inner ℂ vacuum (T vacuum) + +end Invariant233.Rotation + +end +end + +section +noncomputable section +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] + +def HasOnlyTrivialInvariantProjections (M : VonNeumannAlgebra H) + (T : H →L[ℂ] H) : Prop := + ∀ p : H →L[ℂ] H, p ∈ M → IsStarProjection p → + (1 - p) * T * p = 0 → p = 0 ∨ p = 1 + +def IsProjectionAtom (M : VonNeumannAlgebra H) (p : H →L[ℂ] H) : Prop := + p ∈ M ∧ IsStarProjection p ∧ p ≠ 0 ∧ + ∀ q : H →L[ℂ] H, q ∈ M → IsStarProjection q → q * p = q → + q = 0 ∨ q = p + +def IsAtomicVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ p : H →L[ℂ] H, p ∈ M → IsStarProjection p → p ≠ 0 → + ∃ q : H →L[ℂ] H, IsProjectionAtom M q ∧ q * p = q + +def IsAbelianVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ A B : H →L[ℂ] H, A ∈ M → B ∈ M → Commute A B + +def IsDiffuseVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ p : H →L[ℂ] H, ¬ IsProjectionAtom M p + +def IsFactor (M : VonNeumannAlgebra H) : Prop := + Nontrivial H ∧ ∀ A : H →L[ℂ] H, A ∈ M → + (∀ B : H →L[ℂ] H, B ∈ M → Commute A B) → + ∃ c : ℂ, A = c • (1 : H →L[ℂ] H) + +def vectorTrace (ξ : H) (A : H →L[ℂ] H) : ℂ := + @inner ℂ H InnerProductSpace.toInner ξ (A ξ) + +def IsFaithfulTracialVector (M : VonNeumannAlgebra H) (ξ : H) : Prop := + ‖ξ‖ = 1 ∧ + (∀ A B : H →L[ℂ] H, A ∈ M → B ∈ M → + vectorTrace ξ (A * B) = vectorTrace ξ (B * A)) ∧ + (∀ A : H →L[ℂ] H, A ∈ M → A.IsPositive → + vectorTrace ξ A = 0 → A = 0) + +def IsTypeII1FactorWithVector (M : VonNeumannAlgebra H) (ξ : H) : Prop := + IsFactor M ∧ IsDiffuseVonNeumannAlgebra M ∧ IsFaithfulTracialVector M ξ + +local instance instNormedAlgebraPredual : NormedAlgebra ℂ (H →L[ℂ] H) := + ContinuousLinearMap.toNormedAlgebra + +def HasSeparablePredual (M : VonNeumannAlgebra H) : Prop := + ∃ (X : Type u) (_ : NormedAddCommGroup X) (_ : NormedSpace ℂ X) + (_ : CompleteSpace X) (_ : TopologicalSpace.SeparableSpace X), + Nonempty (StrongDual ℂ X ≃ₗᵢ[ℂ] M.toStarSubalgebra) + +end Invariant233 + +end +end + +section +noncomputable section + +open MeasureTheory +open scoped ENNReal + +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +structure TracialState (A : Type*) [CStarAlgebra A] where + toContinuousLinearMap : A →L[ℂ] ℂ + map_one : toContinuousLinearMap 1 = 1 + map_star : ∀ a, toContinuousLinearMap (star a) = star (toContinuousLinearMap a) + positive : ∀ a, 0 ≤ (toContinuousLinearMap (star a * a)).re + tracial : ∀ a b, toContinuousLinearMap (a * b) = toContinuousLinearMap (b * a) + +namespace TracialState + +variable {A : Type*} [CStarAlgebra A] + +instance : CoeFun (TracialState A) (fun _ => A → ℂ) := + ⟨fun τ => τ.toContinuousLinearMap⟩ + +end TracialState + +def fugledeKadisonDeterminant {A : Type*} [CStarAlgebra A] + (τ : TracialState A) (a : A) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, + ENNReal.ofReal (Real.exp ((τ (CFC.log (star a * a + (ε.val : ℝ) • (1 : A)))).re / 2)) + +def logarithmicPotentialDeterminant (μ : Measure ℂ) (z : ℂ) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, + ENNReal.ofReal (Real.exp ((∫ w, Real.log (‖w - z‖ ^ 2 + ε.val) ∂μ) / 2)) + +def IsBrownMeasure {A : Type*} [CStarAlgebra A] + (τ : TracialState A) (a : A) (μ : Measure ℂ) : Prop := + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ + ∀ z : ℂ, fugledeKadisonDeterminant τ (a - algebraMap ℂ A z) = + logarithmicPotentialDeterminant μ z + +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233 +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def vectorFugledeKadisonDeterminant (ξ : H) (T : H →L[ℂ] H) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, ENNReal.ofReal + (Real.exp ((vectorTrace ξ (CFC.log (star T * T + ε.val • (1 : H →L[ℂ] H)))).re / 2)) + +def IsVectorBrownMeasure (ξ : H) (T : H →L[ℂ] H) (μ : Measure ℂ) : Prop := + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ ∀ z : ℂ, + vectorFugledeKadisonDeterminant ξ (T - z • (1 : H →L[ℂ] H)) = + logarithmicPotentialDeterminant μ z + +def operatorModulus (T : H →L[ℂ] H) : H →L[ℂ] H := CFC.sqrt (star T * T) + +def HasCountablyAtomicSpectralType (B : H →L[ℂ] H) : Prop := + ∃ S : Set ℂ, S.Countable ∧ + (⨆ z : S, Module.End.eigenspace B.toLinearMap z.val).topologicalClosure = ⊤ + +def polarConjugate (U B : H →L[ℂ] H) (n : ℤ) : H →L[ℂ] H := + if 0 ≤ n then U ^ n.toNat * B * star U ^ n.toNat + else star U ^ (-n).toNat * B * U ^ (-n).toNat + +def finitePolarAlgebra (U B : H →L[ℂ] H) (F : Finset ℤ) : VonNeumannAlgebra H := + vonNeumannGenerated {A | ∃ n ∈ F, A = polarConjugate U B n} + +def fullPolarAlgebra (U B : H →L[ℂ] H) : VonNeumannAlgebra H := + vonNeumannGenerated (Set.range (polarConjugate U B)) + +def ProductPolarStructure (U T : H →L[ℂ] H) : Prop := + star U * U = 1 ∧ U * star U = 1 ∧ T = U * operatorModulus T ∧ + Function.Injective (operatorModulus T) ∧ HasCountablyAtomicSpectralType (operatorModulus T) ∧ + (∀ F : Finset ℤ, + IsAbelianVonNeumannAlgebra (finitePolarAlgebra U (operatorModulus T) F) ∧ + IsAtomicVonNeumannAlgebra (finitePolarAlgebra U (operatorModulus T) F)) ∧ + IsAbelianVonNeumannAlgebra (fullPolarAlgebra U (operatorModulus T)) ∧ + IsDiffuseVonNeumannAlgebra (fullPolarAlgebra U (operatorModulus T)) + +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def circleRepresentative (x : Circle) : ℝ := + (AddCircle.equivIco (1 : ℝ) 0 x).val + +instance circleMeasure_probability : IsProbabilityMeasure circleMeasure := by + constructor + simp [circleMeasure, Circle, AddCircle.measure_univ] + +namespace ProductModel + +abbrev Base := ℕ → Circle + +def baseMeasure : Measure Base := Measure.infinitePi (fun _ : ℕ => circleMeasure) + +instance baseMeasure_probability : IsProbabilityMeasure baseMeasure := by + unfold baseMeasure + infer_instance + +def Ordered (x y : Base) : Prop := + ∀ i, circleRepresentative (x i) ≤ circleRepresentative (y i) + +def rotation (θ : ℕ → ℝ) (x : Base) : Base := + fun i => x i + (θ i : Circle) + +def rotationIterate (θ : ℕ → ℝ) (k : ℤ) (x : Base) : Base := + fun i => x i + ((k : ℝ) * θ i : ℝ) + +def logarithmicCost (θ c : ℕ → ℝ) (x : Base) : ℝ≥0∞ := + ∑' i, ENNReal.ofReal (c i * (⌊circleRepresentative (x i) + θ i⌋ : ℤ)) + +def weight (θ c : ℕ → ℝ) (x : Base) : ℝ := + (EReal.exp (-(logarithmicCost θ c x : EReal))).toReal + +def JointlyRationallyIndependent (θ : ℕ → ℝ) : Prop := + LinearIndependent ℚ (fun i : Option ℕ => i.elim 1 θ) + +def AdmissibleAnglesAndCosts (θ c : ℕ → ℝ) : Prop := + (∀ i, 0 < θ i ∧ θ i < 1 ∧ 0 < c i) ∧ + Summable θ ∧ JointlyRationallyIndependent θ + +abbrev Fiber := @lp ℤ (fun _ => ℂ) (fun _ => Complex.instNormedAddCommGroup) 2 +abbrev Hilbert := + @MeasureTheory.Lp Base Fiber MeasurableSpace.pi + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + 2 baseMeasure + +end ProductModel +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233.ProductModel + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +theorem measurable_rep : Measurable circleRepresentative := + measurable_subtype_coe.comp (AddCircle.measurableEquivIco (T := (1 : ℝ)) 0).measurable + +theorem measurable_iterate (θ : ℕ → ℝ) (k : ℤ) : + Measurable (rotationIterate θ k) := by + let : T0Space ℝ := @MetricSpace.instT0Space ℝ Real.metricSpace + let : BorelSpace Circle := QuotientAddGroup.borelSpace + let : ContinuousAdd Circle := + (QuotientAddGroup.instIsTopologicalAddGroup (AddSubgroup.zmultiples (1 : ℝ))).toContinuousAdd + let : MeasurableAdd Circle := ContinuousAdd.measurableAdd + apply Measurable.of_eval + intro i + exact (measurable_pi_apply i).add_const _ + +theorem measurable_cost (θ c : ℕ → ℝ) : Measurable (logarithmicCost θ c) := by + apply Measurable.tsum + intro i + have hm : Measurable (fun x : Base => circleRepresentative (x i) + θ i) := + (measurable_rep.comp (measurable_pi_apply i)).add_const (θ i) + have hc : Measurable (fun x : Base => (⌊circleRepresentative (x i) + θ i⌋ : ℝ)) := + (measurable_of_countable (fun z : ℤ => (z : ℝ))).comp hm.floor + exact (measurable_const.mul hc).ennreal_ofReal + +theorem weight_measurable (θ c : ℕ → ℝ) : Measurable (weight θ c) := by + exact (measurable_cost θ c).coe_ereal_ennreal.neg.ereal_exp.ennreal_toReal + +theorem weight_nonneg (θ c : ℕ → ℝ) (x : Base) : 0 ≤ weight θ c x := + ENNReal.toReal_nonneg + +theorem weight_le_one (θ c : ℕ → ℝ) (x : Base) : weight θ c x ≤ 1 := by + have h : EReal.exp (-(logarithmicCost θ c x : EReal)) ≤ 1 := by + rw [← EReal.exp_zero] + apply EReal.exp_le_exp_iff.mpr + exact EReal.neg_le_zero.mpr (EReal.coe_ennreal_nonneg (logarithmicCost θ c x)) + exact (ENNReal.toReal_mono (by simp) h).trans (by simp) + +def shiftOperator : Hilbert →L[ℂ] Hilbert := + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap.compLpL 2 baseMeasure + +def multiplierField (θ : ℕ → ℝ) (g : Base → ℂ) (C : ℝ) + (hb : ∀ x, ‖g x‖ ≤ C) (x : Base) : WeightedShift.Weight := + ⟨fun k => g (rotationIterate θ k x), memℓp_infty <| by + refine ⟨C, ?_⟩ + rintro r ⟨k, rfl⟩ + exact hb _⟩ + +def multiplier (θ : ℕ → ℝ) (g : Base → ℂ) (C : ℝ) (hC : 0 ≤ C) + (hg : Measurable g) (hb : ∀ x, ‖g x‖ ≤ C) : Hilbert →L[ℂ] Hilbert := + WeightedShift.fieldDiagonal (multiplierField θ g C hb) C hC + (fun _x => lp.norm_le_of_forall_le hC (fun _k => hb _)) + (fun k => (hg.comp (measurable_iterate θ k)).aestronglyMeasurable) + +def multiplierGenerators (θ : ℕ → ℝ) : Set (Hilbert →L[ℂ] Hilbert) := + {A | ∃ (g : Base → ℂ) (C : ℝ) (hC : 0 ≤ C) (hg : Measurable g) + (hb : ∀ x, ‖g x‖ ≤ C), A = multiplier θ g C hC hg hb} + +def factor (θ : ℕ → ℝ) : VonNeumannAlgebra Hilbert := + vonNeumannGenerated ({shiftOperator} ∪ multiplierGenerators θ) + +def traceVector : Hilbert := Lp.const 2 baseMeasure (lp.single 2 0 (1 : ℂ)) + +theorem measurable_complexWeight (θ c : ℕ → ℝ) : + Measurable (fun x => (weight θ c x : ℂ)) := + (weight_measurable θ c).complex_ofReal + +theorem norm_complexWeight_le_one (θ c : ℕ → ℝ) (x : Base) : + ‖(weight θ c x : ℂ)‖ ≤ 1 := by + simpa only [Complex.norm_real, Real.norm_eq_abs, abs_of_nonneg (weight_nonneg θ c x)] + using weight_le_one θ c x + +local instance instNormedAddCommGroupProductWeightedOperator : NormedAddCommGroup Hilbert := + @MeasureTheory.Lp.instNormedAddCommGroup Base Fiber MeasurableSpace.pi 2 baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + fact_one_le_two_ennreal + +local instance instInnerProductSpaceProductWeightedOperator : + @InnerProductSpace ℂ Hilbert Complex.instRCLike + instNormedAddCommGroupProductWeightedOperator.toSeminormedAddCommGroup := + @MeasureTheory.L2.innerProductSpace Base Fiber ℂ Complex.instRCLike MeasurableSpace.pi + baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + (@lp.instInnerProductSpace ℤ ℂ Complex.instRCLike (fun _ => ℂ) + (fun _ => Complex.instNormedAddCommGroup) + (fun _ => @RCLike.innerProductSpace ℂ Complex.instRCLike)) + +local instance instTopologicalSpaceProductWeightedOperator : TopologicalSpace Hilbert := + instNormedAddCommGroupProductWeightedOperator.toUniformSpace.toTopologicalSpace + +local instance instAddCommMonoidProductWeightedOperator : AddCommMonoid Hilbert := + instNormedAddCommGroupProductWeightedOperator.toAddCommGroup.toAddCommMonoid + +local instance instModuleProductWeightedOperator : Module ℂ Hilbert := + instInnerProductSpaceProductWeightedOperator.toNormedSpace.toModule + +local notation "weightedOperatorSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring + +local notation "weightedOperatorScalarIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ weightedOperatorSemiring) + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def weightedOperator (θ c : ℕ → ℝ) : + @ContinuousLinearMap ℂ ℂ weightedOperatorSemiring weightedOperatorSemiring + weightedOperatorScalarIdentity + Hilbert instTopologicalSpaceProductWeightedOperator instAddCommMonoidProductWeightedOperator + Hilbert instTopologicalSpaceProductWeightedOperator instAddCommMonoidProductWeightedOperator + instModuleProductWeightedOperator instModuleProductWeightedOperator := + let compose := fun (Scalar : Type) [Semiring Scalar] (Space : Type) + [TopologicalSpace Space] [AddCommMonoid Space] [Module Scalar Space] + (left right : Space →L[Scalar] Space) => left ∘L right + @compose ℂ weightedOperatorSemiring Hilbert instTopologicalSpaceProductWeightedOperator + instAddCommMonoidProductWeightedOperator instModuleProductWeightedOperator + shiftOperator (multiplier θ (fun x => (weight θ c x : ℂ)) 1 zero_le_one + (measurable_complexWeight θ c) (norm_complexWeight_le_one θ c)) + +end Invariant233.ProductModel + +end +end + +section +noncomputable section +open Filter MeasureTheory +open scoped ENNReal Topology BigOperators + +namespace Invariant233.ProductModel + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev EndpointPair := Base × Base + +def selectedEndpoint (I : Finset ℕ) (x z : Base) : Base := + fun i => if i ∈ I then z i else x i + +def triangularEvent (I : Finset ℕ) : Set EndpointPair := + {xz | ∀ i ∈ I, circleRepresentative (xz.1 i) < circleRepresentative (xz.2 i)} + +def triangularLaw (I : Finset ℕ) : Measure EndpointPair := + Measure.map (fun xz : EndpointPair => (xz.1, selectedEndpoint I xz.1 xz.2)) + ((baseMeasure.prod baseMeasure).restrict (triangularEvent I)) + +def triangularFirstDensity (I : Finset ℕ) (x : Base) : ℝ := + ∏ i ∈ I, (1 - circleRepresentative (x i)) + +def triangularSecondDensity (I : Finset ℕ) (y : Base) : ℝ := + ∏ i ∈ I, circleRepresentative (y i) + +def TriangularLawProperties (I : Finset ℕ) : Prop := + IsFiniteMeasure (triangularLaw I) ∧ + triangularLaw I Set.univ = (1 / 2 : ℝ≥0∞) ^ I.card ∧ + (triangularLaw I).map Prod.fst = + baseMeasure.withDensity (fun x => ENNReal.ofReal (triangularFirstDensity I x)) ∧ + (triangularLaw I).map Prod.snd = + baseMeasure.withDensity (fun y => ENNReal.ofReal (triangularSecondDensity I y)) ∧ + (∀ᵐ xy ∂triangularLaw I, Ordered xy.1 xy.2) ∧ + (∀ x, 0 ≤ triangularFirstDensity I x ∧ triangularFirstDensity I x ≤ 1) ∧ + (∀ y, 0 ≤ triangularSecondDensity I y ∧ triangularSecondDensity I y ≤ 1) + +def WeaklyConverges (η : ℕ → Measure EndpointPair) (ν : Measure EndpointPair) : Prop := + ∀ φ : C(EndpointPair, ℝ), + Tendsto (fun l => ∫ xy, φ xy ∂η l) atTop (𝓝 (∫ xy, φ xy ∂ν)) + +def SupportedOnPositiveOrderedOrbitPairs (θ : ℕ → ℝ) (η : Measure EndpointPair) : Prop := + ∃ N : Finset ℕ, (∀ n ∈ N, 0 < n) ∧ + ∀ᵐ xy ∂η, Ordered xy.1 xy.2 ∧ + ∃ n ∈ N, xy.2 = rotationIterate θ (n : ℤ) xy.1 + +def HasUniformL2Marginals (η : ℕ → Measure EndpointPair) : Prop := + ∃ H : ℝ, 0 ≤ H ∧ ∀ l, ∃ f g : Lp ℝ 2 baseMeasure, + (∀ᵐ x ∂baseMeasure, 0 ≤ f x) ∧ (∀ᵐ y ∂baseMeasure, 0 ≤ g y) ∧ + (η l).map Prod.fst = baseMeasure.withDensity (fun x => ENNReal.ofReal (f x)) ∧ + (η l).map Prod.snd = baseMeasure.withDensity (fun y => ENNReal.ofReal (g y)) ∧ + ‖f‖ ≤ H ∧ ‖g‖ ≤ H + +def OrderedOrbitSampling (θ : ℕ → ℝ) (I : Finset ℕ) : Prop := + ∃ η : ℕ → Measure EndpointPair, + (∀ l, IsFiniteMeasure (η l)) ∧ + (∀ l, SupportedOnPositiveOrderedOrbitPairs θ (η l)) ∧ + HasUniformL2Marginals η ∧ WeaklyConverges η (triangularLaw I) + +def HasAllFiniteCoordinateSampling (θ : ℕ → ℝ) : Prop := + ∀ I : Finset ℕ, OrderedOrbitSampling θ I + +end Invariant233.ProductModel + +end +end + +section +noncomputable section +open MeasureTheory +namespace Invariant233.ProductModel + +def IsCovariantFieldRepresentation (θ : ℕ → ℝ) (A : Hilbert →L[ℂ] Hilbert) + (F : Base → Fiber →L[ℂ] Fiber) (B : ℝ) : Prop := + 0 ≤ B ∧ (∀ x, ‖F x‖ ≤ B) ∧ + (∀ v : Fiber, StronglyMeasurable (fun x => F x v)) ∧ + (∀ f : Hilbert, A f =ᵐ[baseMeasure] fun x => F x (f x)) ∧ + (∀ᵐ x ∂baseMeasure, + F (rotation θ x) = + (WeightedShift.shift (-1)).toLinearIsometry.toContinuousLinearMap * F x * + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap) + +def centralDiagonalIntegral (F : Base → Fiber →L[ℂ] Fiber) : ℂ := + ∫ x, inner ℂ (lp.single 2 0 (1 : ℂ) : Fiber) + (F x (lp.single 2 0 (1 : ℂ) : Fiber)) ∂baseMeasure + +end Invariant233.ProductModel + +end +end + +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def Rotation.IsContinuousCounterexample (θ : ℝ) (f : C(Circle, ℝ)) : Prop := + IsContinuousCircleWeight f ∧ + let operator : Rotation.Hilbert →L[ℂ] Rotation.Hilbert := Rotation.weightedReal θ f + let factor : VonNeumannAlgebra Rotation.Hilbert := Rotation.algebra θ + operator ∈ factor ∧ + HasOnlyTrivialInvariantProjections (H := Rotation.Hilbert) factor operator ∧ + operator ≠ 0 ∧ + NormQuasinilpotent (A := Rotation.Hilbert →L[ℂ] Rotation.Hilbert) operator ∧ + vectorFugledeKadisonDeterminant (H := Rotation.Hilbert) Rotation.vacuum operator = 0 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +local instance ProductModel.instFactOneLeTwoCounterexample : + Fact (1 ≤ (2 : ENNReal)) := ⟨by norm_num⟩ + +abbrev ProductModel.CounterexampleFiber : Type := + @lp ℤ (fun _ => ℂ) (fun _ => Complex.instNormedAddCommGroup) 2 + +abbrev ProductModel.CounterexampleHilbert : Type := + @MeasureTheory.Lp ProductModel.Base ProductModel.CounterexampleFiber MeasurableSpace.pi + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + 2 ProductModel.baseMeasure + +instance ProductModel.instCompleteSpaceHilbertCounterexample : + CompleteSpace ProductModel.CounterexampleHilbert := inferInstance + +def ProductOperatorProperties {H : Type*} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] (factor : VonNeumannAlgebra H) + (traceVector : H) (shift operator : H →L[ℂ] H) : Prop := + IsTypeII1FactorWithVector factor traceVector ∧ + HasSeparablePredual factor ∧ + operator ∈ factor ∧ operator ≠ 0 ∧ + NormQuasinilpotent operator ∧ + vectorFugledeKadisonDeterminant traceVector operator = 0 ∧ + spectrum ℂ operator = {0} ∧ + IsVectorBrownMeasure traceVector operator (MeasureTheory.Measure.dirac 0) ∧ + HasOnlyTrivialInvariantProjections factor operator ∧ + ProductPolarStructure shift operator + +@[instance_reducible] +noncomputable def ProductModel.counterexampleHilbertNormedAddCommGroup : + NormedAddCommGroup ProductModel.CounterexampleHilbert := + @MeasureTheory.Lp.instNormedAddCommGroup ProductModel.Base ProductModel.CounterexampleFiber + MeasurableSpace.pi 2 ProductModel.baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + ProductModel.instFactOneLeTwoCounterexample + +@[instance_reducible] +noncomputable def ProductModel.counterexampleHilbertInnerProductSpace : + @InnerProductSpace ℂ ProductModel.CounterexampleHilbert Complex.instRCLike + ProductModel.counterexampleHilbertNormedAddCommGroup.toSeminormedAddCommGroup := + @MeasureTheory.L2.innerProductSpace ProductModel.Base ProductModel.CounterexampleFiber ℂ + Complex.instRCLike MeasurableSpace.pi ProductModel.baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + (@lp.instInnerProductSpace ℤ ℂ Complex.instRCLike (fun _ => ℂ) + (fun _ => Complex.instNormedAddCommGroup) + (fun _ => @RCLike.innerProductSpace ℂ Complex.instRCLike)) + +def ProductModel.HasCounterexampleOperator (θ c : ℕ → ℝ) : Prop := + @ProductOperatorProperties ProductModel.CounterexampleHilbert + ProductModel.counterexampleHilbertNormedAddCommGroup + ProductModel.counterexampleHilbertInnerProductSpace + ProductModel.instCompleteSpaceHilbertCounterexample (ProductModel.factor θ) + ProductModel.traceVector ProductModel.shiftOperator (ProductModel.weightedOperator θ c) + +def ProductModel.IsCounterexampleRealization (θ c : ℕ → ℝ) : Prop := + ProductModel.AdmissibleAnglesAndCosts θ c ∧ + ProductModel.HasAllFiniteCoordinateSampling θ ∧ + Filter.Eventually (fun x : ProductModel.Base => 0 < ProductModel.weight θ c x) + (@MeasureTheory.ae ProductModel.Base + (@MeasureTheory.Measure ProductModel.Base MeasurableSpace.pi) + MeasureTheory.Measure.instFunLike MeasureTheory.Measure.instOuterMeasureClass + ProductModel.baseMeasure) ∧ + @HasNegInfiniteLogIntegral ProductModel.Base MeasurableSpace.pi + ProductModel.baseMeasure (ProductModel.weight θ c) ∧ + ProductModel.HasCounterexampleOperator θ c + +end Invariant233 + +namespace Invariant233.Results + +theorem prescribed_irrational_counterexample (θ : ℝ) + (hθ0 : 0 < θ) (hθ1 : θ < 1) (hθ : Irrational θ) : + ∃ f : C(Circle, ℝ), Rotation.IsContinuousCounterexample θ f := by + sorry + +theorem product_realization : + ∃ θ c : ℕ → ℝ, ProductModel.IsCounterexampleRealization θ c := by + sorry + +end Invariant233.Results + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IrrationalRotation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Invariant233.Results.prescribed_irrational_counterexample`, `OAI.Invariant233.Results.product_realization` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/irrational-rotation/solution/closure.txt b/tasks/irrational-rotation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ce676d923842ea52194e3b5c7e145f6f577ed0ef --- /dev/null +++ b/tasks/irrational-rotation/solution/closure.txt @@ -0,0 +1,735 @@ +OAI.Analysis.IrrationalRotation.Analysis.BVDiscrepancy +OAI.Analysis.IrrationalRotation.Analysis.BackgroundBumps +OAI.Analysis.IrrationalRotation.Analysis.BackgroundCost +OAI.Analysis.IrrationalRotation.Analysis.BackgroundTransfer +OAI.Analysis.IrrationalRotation.Analysis.BanachPeriodicIntervalDiscrepancy +OAI.Analysis.IrrationalRotation.Analysis.BlockAngleConstruction +OAI.Analysis.IrrationalRotation.Analysis.BlockAverageSum +OAI.Analysis.IrrationalRotation.Analysis.BlockReciprocalSum +OAI.Analysis.IrrationalRotation.Analysis.BlockedEventConditions +OAI.Analysis.IrrationalRotation.Analysis.BlockedPositiveEvent +OAI.Analysis.IrrationalRotation.Analysis.BlockedSourceEvent +OAI.Analysis.IrrationalRotation.Analysis.BlockedSourceTransport +OAI.Analysis.IrrationalRotation.Analysis.BoundedLusinApproximation +OAI.Analysis.IrrationalRotation.Analysis.CappedRatios +OAI.Analysis.IrrationalRotation.Analysis.ChoKoLeeComparison +OAI.Analysis.IrrationalRotation.Analysis.ChoKoLeeCompleteComparison +OAI.Analysis.IrrationalRotation.Analysis.ClosedRangeTransport +OAI.Analysis.IrrationalRotation.Analysis.CompactTransfer +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualComplete +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualCore +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualEvaluation +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualModels +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualRepresentation +OAI.Analysis.IrrationalRotation.Analysis.ConcretePredualSeparable +OAI.Analysis.IrrationalRotation.Analysis.ConcreteTagEvent +OAI.Analysis.IrrationalRotation.Analysis.ConsecutiveBlocks +OAI.Analysis.IrrationalRotation.Analysis.ContinuityCoboundary +OAI.Analysis.IrrationalRotation.Analysis.ContinuousConstruction +OAI.Analysis.IrrationalRotation.Analysis.ContinuousCounterexampleAssembly +OAI.Analysis.IrrationalRotation.Analysis.ConvolutionContradiction +OAI.Analysis.IrrationalRotation.Analysis.ConvolutionRatios +OAI.Analysis.IrrationalRotation.Analysis.ConvolutionUniformConstant +OAI.Analysis.IrrationalRotation.Analysis.CountableGraphTransfer +OAI.Analysis.IrrationalRotation.Analysis.CrossingAvoidance +OAI.Analysis.IrrationalRotation.Analysis.DensityMeasureConvergence +OAI.Analysis.IrrationalRotation.Analysis.DensityTransport +OAI.Analysis.IrrationalRotation.Analysis.DiffuseFromSmallPartitions +OAI.Analysis.IrrationalRotation.Analysis.DominatedL2Density +OAI.Analysis.IrrationalRotation.Analysis.EndpointIntervalBounds +OAI.Analysis.IrrationalRotation.Analysis.EndpointKernelGeometry +OAI.Analysis.IrrationalRotation.Analysis.EndpointLoss +OAI.Analysis.IrrationalRotation.Analysis.ErgodicAtoms +OAI.Analysis.IrrationalRotation.Analysis.ExponentialDecay +OAI.Analysis.IrrationalRotation.Analysis.ExtendedExponential +OAI.Analysis.IrrationalRotation.Analysis.FejerApproximation +OAI.Analysis.IrrationalRotation.Analysis.FejerBanachApproximation +OAI.Analysis.IrrationalRotation.Analysis.FejerKernel +OAI.Analysis.IrrationalRotation.Analysis.FiberCentrality +OAI.Analysis.IrrationalRotation.Analysis.FieldCentrality +OAI.Analysis.IrrationalRotation.Analysis.FieldCovariance +OAI.Analysis.IrrationalRotation.Analysis.FieldHalflineNonmembership +OAI.Analysis.IrrationalRotation.Analysis.FieldKoopman +OAI.Analysis.IrrationalRotation.Analysis.FieldKoopmanGenerated +OAI.Analysis.IrrationalRotation.Analysis.FieldMultiplierAdjoint +OAI.Analysis.IrrationalRotation.Analysis.FieldMultiplierCutoff +OAI.Analysis.IrrationalRotation.Analysis.FieldPositivity +OAI.Analysis.IrrationalRotation.Analysis.FieldPowerBounds +OAI.Analysis.IrrationalRotation.Analysis.FieldShiftMoments +OAI.Analysis.IrrationalRotation.Analysis.FieldUnboundedMultiplier +OAI.Analysis.IrrationalRotation.Analysis.FieldVectorState +OAI.Analysis.IrrationalRotation.Analysis.FieldsNorm +OAI.Analysis.IrrationalRotation.Analysis.FiniteConvolution +OAI.Analysis.IrrationalRotation.Analysis.FiniteConvolutionMeasurability +OAI.Analysis.IrrationalRotation.Analysis.FiniteKernelMixture +OAI.Analysis.IrrationalRotation.Analysis.FiniteOrbitAtomic +OAI.Analysis.IrrationalRotation.Analysis.FiniteTestSelection +OAI.Analysis.IrrationalRotation.Analysis.FiniteUniformLaw +OAI.Analysis.IrrationalRotation.Analysis.FiniteWindowIntegralLower +OAI.Analysis.IrrationalRotation.Analysis.FrequencySplice +OAI.Analysis.IrrationalRotation.Analysis.FrequencyTower +OAI.Analysis.IrrationalRotation.Analysis.GeneratedVonNeumann +OAI.Analysis.IrrationalRotation.Analysis.GeometricAverage +OAI.Analysis.IrrationalRotation.Analysis.GraphMeasureConvergence +OAI.Analysis.IrrationalRotation.Analysis.IndividualLusin +OAI.Analysis.IrrationalRotation.Analysis.InfiniteRatioCaps +OAI.Analysis.IrrationalRotation.Analysis.IntervalIndicatorTranslation +OAI.Analysis.IrrationalRotation.Analysis.InvariantConull +OAI.Analysis.IrrationalRotation.Analysis.InvariantConullCore +OAI.Analysis.IrrationalRotation.Analysis.L2UniformAbsoluteContinuity +OAI.Analysis.IrrationalRotation.Analysis.LaurentNoncancellation +OAI.Analysis.IrrationalRotation.Analysis.LaurentWindow +OAI.Analysis.IrrationalRotation.Analysis.LimitLaw +OAI.Analysis.IrrationalRotation.Analysis.LusinCompact +OAI.Analysis.IrrationalRotation.Analysis.MaskedCauchySchwarz +OAI.Analysis.IrrationalRotation.Analysis.MaskedConvolutionTail +OAI.Analysis.IrrationalRotation.Analysis.MaskedTail +OAI.Analysis.IrrationalRotation.Analysis.ModuloIntervalMeasure +OAI.Analysis.IrrationalRotation.Analysis.MultiplicationPurePoint +OAI.Analysis.IrrationalRotation.Analysis.NestedReturnSegments +OAI.Analysis.IrrationalRotation.Analysis.NonnegativeCostIntegral +OAI.Analysis.IrrationalRotation.Analysis.ObservationConditioning +OAI.Analysis.IrrationalRotation.Analysis.OmittedEvents +OAI.Analysis.IrrationalRotation.Analysis.OrbitFiberNull +OAI.Analysis.IrrationalRotation.Analysis.OrbitInvariance +OAI.Analysis.IrrationalRotation.Analysis.OrbitMeasurable +OAI.Analysis.IrrationalRotation.Analysis.OrbitPartition +OAI.Analysis.IrrationalRotation.Analysis.OrdinaryTailNonmembership +OAI.Analysis.IrrationalRotation.Analysis.OrdinaryTailSubspaces +OAI.Analysis.IrrationalRotation.Analysis.ParameterAttenuationConsequences +OAI.Analysis.IrrationalRotation.Analysis.ParameterConvolutionIdentity +OAI.Analysis.IrrationalRotation.Analysis.ParameterOrbitIdentity +OAI.Analysis.IrrationalRotation.Analysis.ParameterSmoothing +OAI.Analysis.IrrationalRotation.Analysis.ParameterTailAttenuation +OAI.Analysis.IrrationalRotation.Analysis.ParameterTails +OAI.Analysis.IrrationalRotation.Analysis.PeriodicIntervalDiscrepancy +OAI.Analysis.IrrationalRotation.Analysis.PointwiseConvolution +OAI.Analysis.IrrationalRotation.Analysis.PurePointDiffuse +OAI.Analysis.IrrationalRotation.Analysis.QuantizedDensity +OAI.Analysis.IrrationalRotation.Analysis.RationalGraphRatioCaps +OAI.Analysis.IrrationalRotation.Analysis.RationalGraphTrimming +OAI.Analysis.IrrationalRotation.Analysis.RationalGraphTrimmingMeasure +OAI.Analysis.IrrationalRotation.Analysis.RationalGraphs +OAI.Analysis.IrrationalRotation.Analysis.RealDensityLp +OAI.Analysis.IrrationalRotation.Analysis.RealTriangularLaw +OAI.Analysis.IrrationalRotation.Analysis.RecursiveReturnTowerFits +OAI.Analysis.IrrationalRotation.Analysis.RecursiveReturnTowers +OAI.Analysis.IrrationalRotation.Analysis.RelocationSeries +OAI.Analysis.IrrationalRotation.Analysis.RepresentedFieldInvariance +OAI.Analysis.IrrationalRotation.Analysis.RepresentedInvariance +OAI.Analysis.IrrationalRotation.Analysis.SawtoothSmoothing +OAI.Analysis.IrrationalRotation.Analysis.ScalarBVDiscrepancy +OAI.Analysis.IrrationalRotation.Analysis.ScalarEndpointDensity +OAI.Analysis.IrrationalRotation.Analysis.ScalarEndpointKernelBounds +OAI.Analysis.IrrationalRotation.Analysis.ScalarFieldLift +OAI.Analysis.IrrationalRotation.Analysis.ScalarKernelEstimates +OAI.Analysis.IrrationalRotation.Analysis.ScalarKernelMomentNumerics +OAI.Analysis.IrrationalRotation.Analysis.ScalarKernelMomentRates +OAI.Analysis.IrrationalRotation.Analysis.ScalarMultiplier +OAI.Analysis.IrrationalRotation.Analysis.ScalarMultiplierFields +OAI.Analysis.IrrationalRotation.Analysis.ScalarRectangleDiscrepancy +OAI.Analysis.IrrationalRotation.Analysis.SeparatedPowers +OAI.Analysis.IrrationalRotation.Analysis.SeparatingVectorStrongConvergence +OAI.Analysis.IrrationalRotation.Analysis.SimultaneousLusin +OAI.Analysis.IrrationalRotation.Analysis.SquaredIntegralLp +OAI.Analysis.IrrationalRotation.Analysis.StrictlyPositiveNormalization +OAI.Analysis.IrrationalRotation.Analysis.StrongContinuityFromColumns +OAI.Analysis.IrrationalRotation.Analysis.StrongFieldContinuity +OAI.Analysis.IrrationalRotation.Analysis.StrongFieldMeasurability +OAI.Analysis.IrrationalRotation.Analysis.StrongFourierRecovery +OAI.Analysis.IrrationalRotation.Analysis.StrongLusin +OAI.Analysis.IrrationalRotation.Analysis.TaggedEventBounds +OAI.Analysis.IrrationalRotation.Analysis.TaggedThresholdCrossing +OAI.Analysis.IrrationalRotation.Analysis.TailScaleCover +OAI.Analysis.IrrationalRotation.Analysis.TestedKernelUnifiedMoments +OAI.Analysis.IrrationalRotation.Analysis.TestedTriangularMoments +OAI.Analysis.IrrationalRotation.Analysis.TestedTriangularVariation +OAI.Analysis.IrrationalRotation.Analysis.TowerApproximationBounds +OAI.Analysis.IrrationalRotation.Analysis.TowerCyclicShift +OAI.Analysis.IrrationalRotation.Analysis.TowerItineraryFits +OAI.Analysis.IrrationalRotation.Analysis.TowerItineraryRefinement +OAI.Analysis.IrrationalRotation.Analysis.TowerMatrixUnits +OAI.Analysis.IrrationalRotation.Analysis.TowerRefinement +OAI.Analysis.IrrationalRotation.Analysis.TransferSupport +OAI.Analysis.IrrationalRotation.Analysis.TriangularEndpointKernel +OAI.Analysis.IrrationalRotation.Analysis.TriangularLawMass +OAI.Analysis.IrrationalRotation.Analysis.TriangularLawProperties +OAI.Analysis.IrrationalRotation.Analysis.TriangularMarginals +OAI.Analysis.IrrationalRotation.Analysis.TriangularProbability +OAI.Analysis.IrrationalRotation.Analysis.TriangularSecondMarginal +OAI.Analysis.IrrationalRotation.Analysis.TriangularTestedVariation +OAI.Analysis.IrrationalRotation.Analysis.TrimmingWeakLimits +OAI.Analysis.IrrationalRotation.Analysis.TruncatedLogIntegral +OAI.Analysis.IrrationalRotation.Analysis.TruncationEvent +OAI.Analysis.IrrationalRotation.Analysis.UniformAbsoluteContinuity +OAI.Analysis.IrrationalRotation.Analysis.UniformAbsoluteContinuityLimits +OAI.Analysis.IrrationalRotation.Analysis.UniformIntervalFourier +OAI.Analysis.IrrationalRotation.Analysis.UniformQuantization +OAI.Analysis.IrrationalRotation.Analysis.UnitaryTransport +OAI.Analysis.IrrationalRotation.Analysis.VaryingMapWeakLimit +OAI.Analysis.IrrationalRotation.Analysis.VonNeumannStrongClosure +OAI.Analysis.IrrationalRotation.Analysis.WeakConvergenceAEContinuous +OAI.Analysis.IrrationalRotation.Couplings.BlockProductCoupling +OAI.Analysis.IrrationalRotation.Couplings.BlockedCouplingDensity +OAI.Analysis.IrrationalRotation.Couplings.BlockedCouplingEnergy +OAI.Analysis.IrrationalRotation.Couplings.BlockedProductCoupling +OAI.Analysis.IrrationalRotation.Couplings.CircleConditionalAttenuation +OAI.Analysis.IrrationalRotation.Couplings.CircleConditionalConvolutionData +OAI.Analysis.IrrationalRotation.Couplings.CircleConditionalLabels +OAI.Analysis.IrrationalRotation.Couplings.CircleConditionalProbabilities +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingAttenuation +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingConditioning +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingCrossings +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingDisintegration +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingForcing +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingHybrid +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingLaw +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingNonterminal +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingOrder +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingParameters +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingSupport +OAI.Analysis.IrrationalRotation.Couplings.CircleCouplingTagSupport +OAI.Analysis.IrrationalRotation.Couplings.CircleDigitCoupling +OAI.Analysis.IrrationalRotation.Couplings.ConditionalAvoidance +OAI.Analysis.IrrationalRotation.Couplings.ConditionalConvolution +OAI.Analysis.IrrationalRotation.Couplings.ConditionalConvolutionPointwise +OAI.Analysis.IrrationalRotation.Couplings.ConditionalCrossingAvoidance +OAI.Analysis.IrrationalRotation.Couplings.ConditionalEventBridge +OAI.Analysis.IrrationalRotation.Couplings.ConditionalKernelSupport +OAI.Analysis.IrrationalRotation.Couplings.ConditionalL2Tail +OAI.Analysis.IrrationalRotation.Couplings.ConditionalMaskedTail +OAI.Analysis.IrrationalRotation.Couplings.ConditionalObservationTransport +OAI.Analysis.IrrationalRotation.Couplings.CouplingMarginalBounds +OAI.Analysis.IrrationalRotation.Couplings.CouplingMixture +OAI.Analysis.IrrationalRotation.Couplings.FiniteConditionalAttenuation +OAI.Analysis.IrrationalRotation.Couplings.MixedRadixHybridLaw +OAI.Analysis.IrrationalRotation.Couplings.OneCoordinateConditional +OAI.Analysis.IrrationalRotation.Couplings.OneCoordinateCoupling +OAI.Analysis.IrrationalRotation.Couplings.PrefixHybrid +OAI.Analysis.IrrationalRotation.Couplings.PrefixPairIdentity +OAI.Analysis.IrrationalRotation.Couplings.ProductBiasedIdentity +OAI.Analysis.IrrationalRotation.Couplings.ProductBiasedIdentityFromTriangular +OAI.Analysis.IrrationalRotation.Couplings.ProductBiasedPrefixTransfer +OAI.Analysis.IrrationalRotation.Couplings.ProductConditionalAttenuation +OAI.Analysis.IrrationalRotation.Couplings.ProductConditionalCrossing +OAI.Analysis.IrrationalRotation.Couplings.ProductConditionalData +OAI.Analysis.IrrationalRotation.Couplings.ProductConditionalEvents +OAI.Analysis.IrrationalRotation.Couplings.ProductConditionalKernels +OAI.Analysis.IrrationalRotation.Couplings.ProductCoupling +OAI.Analysis.IrrationalRotation.Couplings.ProductCouplingCircle +OAI.Analysis.IrrationalRotation.Couplings.ProductCouplingCircleSource +OAI.Analysis.IrrationalRotation.Couplings.ProductCouplingPrefix +OAI.Analysis.IrrationalRotation.Couplings.ProductDensity +OAI.Analysis.IrrationalRotation.Couplings.ProductDensityLimit +OAI.Analysis.IrrationalRotation.Couplings.ProductPairIdentity +OAI.Analysis.IrrationalRotation.Couplings.ProductSourceConditionalData +OAI.Analysis.IrrationalRotation.Couplings.SourceCouplingMarginals +OAI.Analysis.IrrationalRotation.Main +OAI.Analysis.IrrationalRotation.Model.AffiliatedTransport +OAI.Analysis.IrrationalRotation.Model.Analytic +OAI.Analysis.IrrationalRotation.Model.BackgroundData +OAI.Analysis.IrrationalRotation.Model.BlockProductCoupling +OAI.Analysis.IrrationalRotation.Model.BlockedProductCoupling +OAI.Analysis.IrrationalRotation.Model.BlockedSourceEvent +OAI.Analysis.IrrationalRotation.Model.CharacterLaw +OAI.Analysis.IrrationalRotation.Model.CircleConditionalLabels +OAI.Analysis.IrrationalRotation.Model.CircleCoupling +OAI.Analysis.IrrationalRotation.Model.CircleDigitCoupling +OAI.Analysis.IrrationalRotation.Model.CircleDigitMarginals +OAI.Analysis.IrrationalRotation.Model.CircleOrderedCoupling +OAI.Analysis.IrrationalRotation.Model.CircleParameters +OAI.Analysis.IrrationalRotation.Model.CircleRationalGraphs +OAI.Analysis.IrrationalRotation.Model.CircleSamplingGraph +OAI.Analysis.IrrationalRotation.Model.CircleSamplingStage +OAI.Analysis.IrrationalRotation.Model.CircleSmoothing +OAI.Analysis.IrrationalRotation.Model.CircleTailAttenuation +OAI.Analysis.IrrationalRotation.Model.CircleTruncation +OAI.Analysis.IrrationalRotation.Model.CircleTruncationEvent +OAI.Analysis.IrrationalRotation.Model.CircleWeights +OAI.Analysis.IrrationalRotation.Model.ColumnOperator +OAI.Analysis.IrrationalRotation.Model.Commutant +OAI.Analysis.IrrationalRotation.Model.CompactTransfer +OAI.Analysis.IrrationalRotation.Model.ConcreteSpectral +OAI.Analysis.IrrationalRotation.Model.ConditionalConvolution +OAI.Analysis.IrrationalRotation.Model.Conjugation +OAI.Analysis.IrrationalRotation.Model.ConjugationDefect +OAI.Analysis.IrrationalRotation.Model.ContinuityCoboundary +OAI.Analysis.IrrationalRotation.Model.ContinuousConstruction +OAI.Analysis.IrrationalRotation.Model.ContinuousCounterexample +OAI.Analysis.IrrationalRotation.Model.CouplingMarginalBounds +OAI.Analysis.IrrationalRotation.Model.CouplingMixture +OAI.Analysis.IrrationalRotation.Model.Diagonal +OAI.Analysis.IrrationalRotation.Model.DiagonalGauge +OAI.Analysis.IrrationalRotation.Model.Fejer +OAI.Analysis.IrrationalRotation.Model.FejerApproximation +OAI.Analysis.IrrationalRotation.Model.FieldDiagonal +OAI.Analysis.IrrationalRotation.Model.FieldOperator +OAI.Analysis.IrrationalRotation.Model.FieldUnboundedMultiplier +OAI.Analysis.IrrationalRotation.Model.FieldWeightedShift +OAI.Analysis.IrrationalRotation.Model.FiniteConvolution +OAI.Analysis.IrrationalRotation.Model.FiniteKernelMixture +OAI.Analysis.IrrationalRotation.Model.GeneratedVonNeumann +OAI.Analysis.IrrationalRotation.Model.Hyperfinite +OAI.Analysis.IrrationalRotation.Model.IndependentKernelProduct +OAI.Analysis.IrrationalRotation.Model.JointEigenspace +OAI.Analysis.IrrationalRotation.Model.LaurentConvolution +OAI.Analysis.IrrationalRotation.Model.MixedRadix +OAI.Analysis.IrrationalRotation.Model.MixedRadixCircle +OAI.Analysis.IrrationalRotation.Model.MixedRadixProbability +OAI.Analysis.IrrationalRotation.Model.NormalAffiliation +OAI.Analysis.IrrationalRotation.Model.OneCoordinateConditional +OAI.Analysis.IrrationalRotation.Model.OneCoordinateCoupling +OAI.Analysis.IrrationalRotation.Model.OperatorProperties +OAI.Analysis.IrrationalRotation.Model.OrbitMeasurable +OAI.Analysis.IrrationalRotation.Model.ParameterCircleOperator +OAI.Analysis.IrrationalRotation.Model.ParameterCircleWeights +OAI.Analysis.IrrationalRotation.Model.ParameterSmoothing +OAI.Analysis.IrrationalRotation.Model.PhaseBlocks +OAI.Analysis.IrrationalRotation.Model.PhaseFailure +OAI.Analysis.IrrationalRotation.Model.PositiveDiagonalModel +OAI.Analysis.IrrationalRotation.Model.PrefixDomination +OAI.Analysis.IrrationalRotation.Model.PrefixHybrid +OAI.Analysis.IrrationalRotation.Model.Product +OAI.Analysis.IrrationalRotation.Model.ProductBase +OAI.Analysis.IrrationalRotation.Model.ProductCharacters +OAI.Analysis.IrrationalRotation.Model.ProductCocycle +OAI.Analysis.IrrationalRotation.Model.ProductCoupling +OAI.Analysis.IrrationalRotation.Model.ProductCouplingCircle +OAI.Analysis.IrrationalRotation.Model.ProductFactorStructure +OAI.Analysis.IrrationalRotation.Model.ProductIdealSampling +OAI.Analysis.IrrationalRotation.Model.ProductPairIdentity +OAI.Analysis.IrrationalRotation.Model.ProductPowers +OAI.Analysis.IrrationalRotation.Model.ProductPrefixDomination +OAI.Analysis.IrrationalRotation.Model.ProductSampling +OAI.Analysis.IrrationalRotation.Model.ProductScaleSampling +OAI.Analysis.IrrationalRotation.Model.ProductScales +OAI.Analysis.IrrationalRotation.Model.ProductTailTrimming +OAI.Analysis.IrrationalRotation.Model.RationalGraphTrimming +OAI.Analysis.IrrationalRotation.Model.RealTriangularLaw +OAI.Analysis.IrrationalRotation.Model.Rotation +OAI.Analysis.IrrationalRotation.Model.RotationLInfinity +OAI.Analysis.IrrationalRotation.Model.RotationMeasurable +OAI.Analysis.IrrationalRotation.Model.RotationTransfer +OAI.Analysis.IrrationalRotation.Model.SamplingTests +OAI.Analysis.IrrationalRotation.Model.SawtoothSmoothing +OAI.Analysis.IrrationalRotation.Model.ScalarEndpointDensity +OAI.Analysis.IrrationalRotation.Model.ScalarKernelEstimates +OAI.Analysis.IrrationalRotation.Model.ScalarMultiplier +OAI.Analysis.IrrationalRotation.Model.ScalarSampling +OAI.Analysis.IrrationalRotation.Model.ScalarSamplingEstimates +OAI.Analysis.IrrationalRotation.Model.ShiftedPullback +OAI.Analysis.IrrationalRotation.Model.SourceCouplingMarginals +OAI.Analysis.IrrationalRotation.Model.SourceProductTail +OAI.Analysis.IrrationalRotation.Model.Spectral +OAI.Analysis.IrrationalRotation.Model.SpectralCutoff +OAI.Analysis.IrrationalRotation.Model.StrictPhase +OAI.Analysis.IrrationalRotation.Model.TailSubspace +OAI.Analysis.IrrationalRotation.Model.TrialSampling +OAI.Analysis.IrrationalRotation.Model.TrimmedCircleSamplingGraph +OAI.Analysis.IrrationalRotation.Model.UniformIntervalPhase +OAI.Analysis.IrrationalRotation.Model.UniformQuantization +OAI.Analysis.IrrationalRotation.Model.UnrestrictedDiagonal +OAI.Analysis.IrrationalRotation.Model.VectorTraceState +OAI.Analysis.IrrationalRotation.Model.WeightedShift +OAI.Analysis.IrrationalRotation.Operators.AffiliatedTraceCutoffs +OAI.Analysis.IrrationalRotation.Operators.AffiliatedTransport +OAI.Analysis.IrrationalRotation.Operators.AffiliatedTransportSupplement +OAI.Analysis.IrrationalRotation.Operators.BicommutantAmplification +OAI.Analysis.IrrationalRotation.Operators.BicommutantCyclic +OAI.Analysis.IrrationalRotation.Operators.BicommutantDensity +OAI.Analysis.IrrationalRotation.Operators.BicommutantStrongTopology +OAI.Analysis.IrrationalRotation.Operators.BlockedProjectionWindow +OAI.Analysis.IrrationalRotation.Operators.BoundedRangeTrace +OAI.Analysis.IrrationalRotation.Operators.ColumnOperator +OAI.Analysis.IrrationalRotation.Operators.Commutant +OAI.Analysis.IrrationalRotation.Operators.CommutantAlgebra +OAI.Analysis.IrrationalRotation.Operators.CommutantProper +OAI.Analysis.IrrationalRotation.Operators.Conjugation +OAI.Analysis.IrrationalRotation.Operators.ConjugationDefect +OAI.Analysis.IrrationalRotation.Operators.ContinuousProjectionTransport +OAI.Analysis.IrrationalRotation.Operators.CovariantTracialVector +OAI.Analysis.IrrationalRotation.Operators.FaithfulProjectionTrace +OAI.Analysis.IrrationalRotation.Operators.FieldOperator +OAI.Analysis.IrrationalRotation.Operators.FieldProjections +OAI.Analysis.IrrationalRotation.Operators.FieldTraceCyclic +OAI.Analysis.IrrationalRotation.Operators.FieldTraceFaithfulness +OAI.Analysis.IrrationalRotation.Operators.FiniteConvolutionAlgebra +OAI.Analysis.IrrationalRotation.Operators.FullAffiliatedTransport +OAI.Analysis.IrrationalRotation.Operators.HilbertConjugationExistence +OAI.Analysis.IrrationalRotation.Operators.HilbertConsequence +OAI.Analysis.IrrationalRotation.Operators.HilbertModelSize +OAI.Analysis.IrrationalRotation.Operators.HyperfiniteCriterion +OAI.Analysis.IrrationalRotation.Operators.HyperinvariantProjection +OAI.Analysis.IrrationalRotation.Operators.JointEigenprojection +OAI.Analysis.IrrationalRotation.Operators.JointEigenspaceAlgebra +OAI.Analysis.IrrationalRotation.Operators.JointProjectionAtomic +OAI.Analysis.IrrationalRotation.Operators.LpOperatorExt +OAI.Analysis.IrrationalRotation.Operators.NormalAffiliatedTransport +OAI.Analysis.IrrationalRotation.Operators.NormalTracialTransport +OAI.Analysis.IrrationalRotation.Operators.OperatorCompactTransfer +OAI.Analysis.IrrationalRotation.Operators.ProjectionAtomOrbit +OAI.Analysis.IrrationalRotation.Operators.ProjectionFieldRepresentative +OAI.Analysis.IrrationalRotation.Operators.ProjectionMeetTrace +OAI.Analysis.IrrationalRotation.Operators.ProjectionTruncationMass +OAI.Analysis.IrrationalRotation.Operators.RepresentedCommutation +OAI.Analysis.IrrationalRotation.Operators.RepresentedFieldCommutation +OAI.Analysis.IrrationalRotation.Operators.ScalarMultiplierCommutation +OAI.Analysis.IrrationalRotation.Operators.StrongOperatorConvergence +OAI.Analysis.IrrationalRotation.Operators.StrongOperatorIntegral +OAI.Analysis.IrrationalRotation.Operators.TowerBlockAlgebras +OAI.Analysis.IrrationalRotation.Operators.TowerTraceBounds +OAI.Analysis.IrrationalRotation.Operators.TracialLogDerivative +OAI.Analysis.IrrationalRotation.Operators.TracialLogNormSquare +OAI.Analysis.IrrationalRotation.Operators.TracialNormSquareDerivative +OAI.Analysis.IrrationalRotation.Operators.TracialProjectionTransport +OAI.Analysis.IrrationalRotation.Operators.TracialVectorSeparating +OAI.Analysis.IrrationalRotation.Operators.VectorTraceState +OAI.Analysis.IrrationalRotation.PrescribedAngle +OAI.Analysis.IrrationalRotation.PrescribedAngleConditional +OAI.Analysis.IrrationalRotation.Product.CoordinateSwap +OAI.Analysis.IrrationalRotation.Product.FiniteProductAbsoluteContinuity +OAI.Analysis.IrrationalRotation.Product.IndependentAngles +OAI.Analysis.IrrationalRotation.Product.IndependentCoordinateConditioning +OAI.Analysis.IrrationalRotation.Product.IndependentKernelProduct +OAI.Analysis.IrrationalRotation.Product.IndependentMissBounds +OAI.Analysis.IrrationalRotation.Product.IndependentRotation +OAI.Analysis.IrrationalRotation.Product.OneCoordinateCrossing +OAI.Analysis.IrrationalRotation.Product.OneCoordinateDensity +OAI.Analysis.IrrationalRotation.Product.ProductBaseDynamics +OAI.Analysis.IrrationalRotation.Product.ProductBlockCost +OAI.Analysis.IrrationalRotation.Product.ProductCircleConditioning +OAI.Analysis.IrrationalRotation.Product.ProductCocycle +OAI.Analysis.IrrationalRotation.Product.ProductCocycleInterchange +OAI.Analysis.IrrationalRotation.Product.ProductCocycleWindow +OAI.Analysis.IrrationalRotation.Product.ProductConvolutionIdentity +OAI.Analysis.IrrationalRotation.Product.ProductCoordinateSplit +OAI.Analysis.IrrationalRotation.Product.ProductCovariance +OAI.Analysis.IrrationalRotation.Product.ProductDiffuse +OAI.Analysis.IrrationalRotation.Product.ProductErgodicity +OAI.Analysis.IrrationalRotation.Product.ProductFactorComplete +OAI.Analysis.IrrationalRotation.Product.ProductFactorSource +OAI.Analysis.IrrationalRotation.Product.ProductFieldConverse +OAI.Analysis.IrrationalRotation.Product.ProductFieldDiagonals +OAI.Analysis.IrrationalRotation.Product.ProductFieldRepresentation +OAI.Analysis.IrrationalRotation.Product.ProductFields +OAI.Analysis.IrrationalRotation.Product.ProductGaugeFourier +OAI.Analysis.IrrationalRotation.Product.ProductHilbert +OAI.Analysis.IrrationalRotation.Product.ProductIdealCylinderLimit +OAI.Analysis.IrrationalRotation.Product.ProductInvariantProjectionObstruction +OAI.Analysis.IrrationalRotation.Product.ProductLogIntegral +OAI.Analysis.IrrationalRotation.Product.ProductMultiplierFunctionalCalculus +OAI.Analysis.IrrationalRotation.Product.ProductNorm +OAI.Analysis.IrrationalRotation.Product.ProductObstructionConstant +OAI.Analysis.IrrationalRotation.Product.ProductOrbitFiberNull +OAI.Analysis.IrrationalRotation.Product.ProductOrbitL2Marginals +OAI.Analysis.IrrationalRotation.Product.ProductOrbitMarginals +OAI.Analysis.IrrationalRotation.Product.ProductOrbitPair +OAI.Analysis.IrrationalRotation.Product.ProductOrbitTests +OAI.Analysis.IrrationalRotation.Product.ProductPairRatios +OAI.Analysis.IrrationalRotation.Product.ProductPairTransfer +OAI.Analysis.IrrationalRotation.Product.ProductPositiveDiagonal +OAI.Analysis.IrrationalRotation.Product.ProductPowerIdentity +OAI.Analysis.IrrationalRotation.Product.ProductProjectionFields +OAI.Analysis.IrrationalRotation.Product.ProductRealizationAssembly +OAI.Analysis.IrrationalRotation.Product.ProductScalarity +OAI.Analysis.IrrationalRotation.Product.ProductScaleCocycleWindow +OAI.Analysis.IrrationalRotation.Product.ProductScaleConsequences +OAI.Analysis.IrrationalRotation.Product.ProductScaleConstruction +OAI.Analysis.IrrationalRotation.Product.ProductScaleRealization +OAI.Analysis.IrrationalRotation.Product.ProductScaleTagAttenuation +OAI.Analysis.IrrationalRotation.Product.ProductScaleTail +OAI.Analysis.IrrationalRotation.Product.ProductScaleTailAssignment +OAI.Analysis.IrrationalRotation.Product.ProductScaleTailAttenuation +OAI.Analysis.IrrationalRotation.Product.ProductSourceAngleLaw +OAI.Analysis.IrrationalRotation.Product.ProductSourceTagAttenuation +OAI.Analysis.IrrationalRotation.Product.ProductSupport +OAI.Analysis.IrrationalRotation.Product.ProductTailScaleCover +OAI.Analysis.IrrationalRotation.Product.ProductTailTrimming +OAI.Analysis.IrrationalRotation.Product.ProductTestedExpectationSummability +OAI.Analysis.IrrationalRotation.Product.ProductTestedKernelMoments +OAI.Analysis.IrrationalRotation.Product.ProductTracialInputs +OAI.Analysis.IrrationalRotation.Product.ProductTracialVector +OAI.Analysis.IrrationalRotation.Product.ProductWeightBridge +OAI.Analysis.IrrationalRotation.Product.ProductWeightNonconstant +OAI.Analysis.IrrationalRotation.Product.SourceProductTailAttenuation +OAI.Analysis.IrrationalRotation.Product.SourceProductTailRealization +OAI.Analysis.IrrationalRotation.Rotation.ActualRotationCentrality +OAI.Analysis.IrrationalRotation.Rotation.AnalyticWeightBridge +OAI.Analysis.IrrationalRotation.Rotation.BlockedCircleEvent +OAI.Analysis.IrrationalRotation.Rotation.CanonicalCircleCoefficients +OAI.Analysis.IrrationalRotation.Rotation.CanonicalCircleFiniteLower +OAI.Analysis.IrrationalRotation.Rotation.CircleBackgroundBumps +OAI.Analysis.IrrationalRotation.Rotation.CircleBackgroundCost +OAI.Analysis.IrrationalRotation.Rotation.CircleCocycle +OAI.Analysis.IrrationalRotation.Rotation.CircleCocycleWindow +OAI.Analysis.IrrationalRotation.Rotation.CircleCurrentBlockEvent +OAI.Analysis.IrrationalRotation.Rotation.CircleErgodicity +OAI.Analysis.IrrationalRotation.Rotation.CircleFiberDecay +OAI.Analysis.IrrationalRotation.Rotation.CircleFlattenedCosts +OAI.Analysis.IrrationalRotation.Rotation.CircleFutureEndpointLoss +OAI.Analysis.IrrationalRotation.Rotation.CircleKernelConvolution +OAI.Analysis.IrrationalRotation.Rotation.CircleMarginalBudget +OAI.Analysis.IrrationalRotation.Rotation.CircleMarginalDensity +OAI.Analysis.IrrationalRotation.Rotation.CircleMeasurableObstruction +OAI.Analysis.IrrationalRotation.Rotation.CircleObstruction +OAI.Analysis.IrrationalRotation.Rotation.CircleOrderedTransfer +OAI.Analysis.IrrationalRotation.Rotation.CircleParameterBlocks +OAI.Analysis.IrrationalRotation.Rotation.CircleParameterConsequences +OAI.Analysis.IrrationalRotation.Rotation.CircleParameterRecursion +OAI.Analysis.IrrationalRotation.Rotation.CircleParametersExistence +OAI.Analysis.IrrationalRotation.Rotation.CircleQuantizedMarginals +OAI.Analysis.IrrationalRotation.Rotation.CircleRationalGraphApproximants +OAI.Analysis.IrrationalRotation.Rotation.CircleRationalGraphCaps +OAI.Analysis.IrrationalRotation.Rotation.CircleRationalGraphFields +OAI.Analysis.IrrationalRotation.Rotation.CircleRationalGraphTransfer +OAI.Analysis.IrrationalRotation.Rotation.CircleRawTagEvent +OAI.Analysis.IrrationalRotation.Rotation.CircleRepresentative +OAI.Analysis.IrrationalRotation.Rotation.CircleSmoothing +OAI.Analysis.IrrationalRotation.Rotation.CircleTailAttenuation +OAI.Analysis.IrrationalRotation.Rotation.CircleTailExceptionalFamilies +OAI.Analysis.IrrationalRotation.Rotation.CircleTruncationBound +OAI.Analysis.IrrationalRotation.Rotation.CircleTruncationEvent +OAI.Analysis.IrrationalRotation.Rotation.CircleTruncationIntegral +OAI.Analysis.IrrationalRotation.Rotation.CircleTruncationMass +OAI.Analysis.IrrationalRotation.Rotation.CircleWeightDecay +OAI.Analysis.IrrationalRotation.Rotation.CircleWeightSupport +OAI.Analysis.IrrationalRotation.Rotation.CocycleSupport +OAI.Analysis.IrrationalRotation.Rotation.CocycleWindowBounds +OAI.Analysis.IrrationalRotation.Rotation.ContinuousCircleImage +OAI.Analysis.IrrationalRotation.Rotation.ContinuousWeightAssembly +OAI.Analysis.IrrationalRotation.Rotation.ContinuousWeightOperatorBridge +OAI.Analysis.IrrationalRotation.Rotation.ContinuousWeightParameterBridge +OAI.Analysis.IrrationalRotation.Rotation.DiagonalContinuity +OAI.Analysis.IrrationalRotation.Rotation.DiagonalGauge +OAI.Analysis.IrrationalRotation.Rotation.ExponentialWeight +OAI.Analysis.IrrationalRotation.Rotation.FieldDiagonal +OAI.Analysis.IrrationalRotation.Rotation.FieldDiagonalConvergence +OAI.Analysis.IrrationalRotation.Rotation.FieldKoopmanDiagonal +OAI.Analysis.IrrationalRotation.Rotation.FieldWeightedShiftHalfline +OAI.Analysis.IrrationalRotation.Rotation.FieldWeightedShiftPowers +OAI.Analysis.IrrationalRotation.Rotation.FiniteSupportCocycle +OAI.Analysis.IrrationalRotation.Rotation.FiniteSupportWeights +OAI.Analysis.IrrationalRotation.Rotation.FloorCocycle +OAI.Analysis.IrrationalRotation.Rotation.GaugeFourierDiagonal +OAI.Analysis.IrrationalRotation.Rotation.ParameterCircleCocycle +OAI.Analysis.IrrationalRotation.Rotation.ParameterCircleReindex +OAI.Analysis.IrrationalRotation.Rotation.ParameterPositiveDiagonal +OAI.Analysis.IrrationalRotation.Rotation.PositiveDiagonal +OAI.Analysis.IrrationalRotation.Rotation.PositiveDiagonalAlgebra +OAI.Analysis.IrrationalRotation.Rotation.PositiveDiagonalFields +OAI.Analysis.IrrationalRotation.Rotation.PositiveDiagonalRepresentatives +OAI.Analysis.IrrationalRotation.Rotation.ProjectionCocycleWindow +OAI.Analysis.IrrationalRotation.Rotation.ProjectionDiagonal +OAI.Analysis.IrrationalRotation.Rotation.ProjectionDiagonalPropagation +OAI.Analysis.IrrationalRotation.Rotation.RealWeightedPositiveDiagonal +OAI.Analysis.IrrationalRotation.Rotation.RepresentedPositiveDiagonal +OAI.Analysis.IrrationalRotation.Rotation.Rotation +OAI.Analysis.IrrationalRotation.Rotation.RotationAlgebra +OAI.Analysis.IrrationalRotation.Rotation.RotationCenter +OAI.Analysis.IrrationalRotation.Rotation.RotationDecay +OAI.Analysis.IrrationalRotation.Rotation.RotationDiagonalState +OAI.Analysis.IrrationalRotation.Rotation.RotationDiffuse +OAI.Analysis.IrrationalRotation.Rotation.RotationFactorStructure +OAI.Analysis.IrrationalRotation.Rotation.RotationFieldRepresentation +OAI.Analysis.IrrationalRotation.Rotation.RotationFields +OAI.Analysis.IrrationalRotation.Rotation.RotationFiniteReturnTowers +OAI.Analysis.IrrationalRotation.Rotation.RotationHalfline +OAI.Analysis.IrrationalRotation.Rotation.RotationHilbert +OAI.Analysis.IrrationalRotation.Rotation.RotationHyperfinite +OAI.Analysis.IrrationalRotation.Rotation.RotationHyperfiniteCriterion +OAI.Analysis.IrrationalRotation.Rotation.RotationLInfinity +OAI.Analysis.IrrationalRotation.Rotation.RotationMeasurable +OAI.Analysis.IrrationalRotation.Rotation.RotationMeasurableLaws +OAI.Analysis.IrrationalRotation.Rotation.RotationNonzero +OAI.Analysis.IrrationalRotation.Rotation.RotationProjectionTransport +OAI.Analysis.IrrationalRotation.Rotation.RotationRecursiveTowerAssembly +OAI.Analysis.IrrationalRotation.Rotation.RotationReturnTowers +OAI.Analysis.IrrationalRotation.Rotation.RotationSetProjections +OAI.Analysis.IrrationalRotation.Rotation.RotationShrinkingBases +OAI.Analysis.IrrationalRotation.Rotation.RotationTowerAlgebras +OAI.Analysis.IrrationalRotation.Rotation.RotationTowerApproximation +OAI.Analysis.IrrationalRotation.Rotation.RotationTowerCyclicApproximation +OAI.Analysis.IrrationalRotation.Rotation.RotationTowerHyperfiniteAssembly +OAI.Analysis.IrrationalRotation.Rotation.RotationTrace +OAI.Analysis.IrrationalRotation.Rotation.RotationTransfer +OAI.Analysis.IrrationalRotation.Rotation.RotationTransferIntertwining +OAI.Analysis.IrrationalRotation.Rotation.RotationTransferTrace +OAI.Analysis.IrrationalRotation.Rotation.TowerDiagonalApproximation +OAI.Analysis.IrrationalRotation.Rotation.UniformRotationAverage +OAI.Analysis.IrrationalRotation.Rotation.UnrestrictedDiagonal +OAI.Analysis.IrrationalRotation.Rotation.WeightedGraphMarginals +OAI.Analysis.IrrationalRotation.Rotation.WeightedOrbitInvariance +OAI.Analysis.IrrationalRotation.Rotation.WeightedShiftAlgebra +OAI.Analysis.IrrationalRotation.Rotation.WeightedShiftCentrality +OAI.Analysis.IrrationalRotation.Rotation.WeightedShiftHalfline +OAI.Analysis.IrrationalRotation.Rotation.WeightedShiftPowers +OAI.Analysis.IrrationalRotation.Sampling.BlockPhaseConstruction +OAI.Analysis.IrrationalRotation.Sampling.CharacterLawConvergence +OAI.Analysis.IrrationalRotation.Sampling.CharacterPhaseRealization +OAI.Analysis.IrrationalRotation.Sampling.CharacterSamplingLimit +OAI.Analysis.IrrationalRotation.Sampling.CharacterSamplingStage +OAI.Analysis.IrrationalRotation.Sampling.CharacterWeakConvergence +OAI.Analysis.IrrationalRotation.Sampling.CircleCharacterDynamics +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitCrossings +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitDensity +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitDisintegration +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitEndpointLoss +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitEnergy +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitGeometry +OAI.Analysis.IrrationalRotation.Sampling.CircleDigitMarginalLaws +OAI.Analysis.IrrationalRotation.Sampling.CirclePhaseSummability +OAI.Analysis.IrrationalRotation.Sampling.CirclePhaseTails +OAI.Analysis.IrrationalRotation.Sampling.CircleRationalSamplingIndex +OAI.Analysis.IrrationalRotation.Sampling.CircleSamplingGraph +OAI.Analysis.IrrationalRotation.Sampling.CircleSamplingGraphLimits +OAI.Analysis.IrrationalRotation.Sampling.CircleSamplingKernelBridge +OAI.Analysis.IrrationalRotation.Sampling.CircleSamplingLp +OAI.Analysis.IrrationalRotation.Sampling.CircleSamplingStageSupply +OAI.Analysis.IrrationalRotation.Sampling.DigitAveraging +OAI.Analysis.IrrationalRotation.Sampling.ErgodicCharacterCriterion +OAI.Analysis.IrrationalRotation.Sampling.FinitePrefixLaw +OAI.Analysis.IrrationalRotation.Sampling.FourierSampling +OAI.Analysis.IrrationalRotation.Sampling.IntegerPhaseWindow +OAI.Analysis.IrrationalRotation.Sampling.LargePhaseAssembly +OAI.Analysis.IrrationalRotation.Sampling.MixedRadix +OAI.Analysis.IrrationalRotation.Sampling.MixedRadixCircle +OAI.Analysis.IrrationalRotation.Sampling.MixedRadixHaarLaw +OAI.Analysis.IrrationalRotation.Sampling.MixedRadixLaw +OAI.Analysis.IrrationalRotation.Sampling.MixedRadixNonterminal +OAI.Analysis.IrrationalRotation.Sampling.MixedRadixTransport +OAI.Analysis.IrrationalRotation.Sampling.NonresonantPhaseTrials +OAI.Analysis.IrrationalRotation.Sampling.OrthogonalPrefixLimit +OAI.Analysis.IrrationalRotation.Sampling.PhaseBlockWeight +OAI.Analysis.IrrationalRotation.Sampling.PhaseFailureSummability +OAI.Analysis.IrrationalRotation.Sampling.PhaseRanges +OAI.Analysis.IrrationalRotation.Sampling.PrefixCocycleCap +OAI.Analysis.IrrationalRotation.Sampling.PrefixCompactTransfer +OAI.Analysis.IrrationalRotation.Sampling.PrefixDomination +OAI.Analysis.IrrationalRotation.Sampling.PrefixReferenceCompletion +OAI.Analysis.IrrationalRotation.Sampling.PrefixReferenceIdentification +OAI.Analysis.IrrationalRotation.Sampling.PrescribedPhaseRealization +OAI.Analysis.IrrationalRotation.Sampling.PrescribedSamplingStage +OAI.Analysis.IrrationalRotation.Sampling.ProductCharacters +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingKernel +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingLimit +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingOrder +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingProduct +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingRectangles +OAI.Analysis.IrrationalRotation.Sampling.ProductIdealSamplingScales +OAI.Analysis.IrrationalRotation.Sampling.ProductInfiniteSamplingMoments +OAI.Analysis.IrrationalRotation.Sampling.ProductPrefixCircle +OAI.Analysis.IrrationalRotation.Sampling.ProductPrefixDomination +OAI.Analysis.IrrationalRotation.Sampling.ProductSampling +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingAbsoluteContinuity +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingAsymptotics +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingCoordinateScales +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingCylinderWeights +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingEstimates +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingExpectedTransport +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingIdealBounds +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingMoments +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingNumericalBudget +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingNumericalMajorant +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingPhaseMoments +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingPhaseScale +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingScaleTrimming +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingSourceAlmostSure +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingSourceWeak +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingTailReindex +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingTestAlmostSure +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingTestCongruence +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingTestIntegrability +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingTrimming +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingUniformL2 +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingUnitTests +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingWeightAssembly +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingWeightMeasurability +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingWeightScalarBridge +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingWeightTests +OAI.Analysis.IrrationalRotation.Sampling.ProductSamplingWeights +OAI.Analysis.IrrationalRotation.Sampling.ProductScaleSampling +OAI.Analysis.IrrationalRotation.Sampling.ProductSourceSamplingAssembly +OAI.Analysis.IrrationalRotation.Sampling.ProductSourceSamplingEnergy +OAI.Analysis.IrrationalRotation.Sampling.ProductSourceSamplingFinal +OAI.Analysis.IrrationalRotation.Sampling.ProductSourceSamplingL2 +OAI.Analysis.IrrationalRotation.Sampling.ProductStrictPhaseBounds +OAI.Analysis.IrrationalRotation.Sampling.RationalGraphSampling +OAI.Analysis.IrrationalRotation.Sampling.SamplingAlmostSure +OAI.Analysis.IrrationalRotation.Sampling.SamplingAsymptotics +OAI.Analysis.IrrationalRotation.Sampling.SamplingCylinderError +OAI.Analysis.IrrationalRotation.Sampling.SamplingCylinderWeak +OAI.Analysis.IrrationalRotation.Sampling.SamplingErrorSummability +OAI.Analysis.IrrationalRotation.Sampling.SamplingHorizon +OAI.Analysis.IrrationalRotation.Sampling.SamplingMeanSquare +OAI.Analysis.IrrationalRotation.Sampling.SamplingMomentBounds +OAI.Analysis.IrrationalRotation.Sampling.SamplingOrbitWeak +OAI.Analysis.IrrationalRotation.Sampling.SamplingTestContinuity +OAI.Analysis.IrrationalRotation.Sampling.SamplingTestLimit +OAI.Analysis.IrrationalRotation.Sampling.SamplingTestTrialBridge +OAI.Analysis.IrrationalRotation.Sampling.ScalarSampling +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingContinuity +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingEndpointVariation +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingEstimates +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingFull +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingJensen +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingMomentConsequences +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingNumerics +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingPairMoments +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingSeparated +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingShear +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingTestVariation +OAI.Analysis.IrrationalRotation.Sampling.ScalarSamplingVariation +OAI.Analysis.IrrationalRotation.Sampling.SeparatedCharacterFrequencies +OAI.Analysis.IrrationalRotation.Sampling.StrictPhaseStability +OAI.Analysis.IrrationalRotation.Sampling.StrictPhaseTrials +OAI.Analysis.IrrationalRotation.Sampling.SyndeticSampling +OAI.Analysis.IrrationalRotation.Sampling.TestedSamplingMoments +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingActualMoments +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingIdealMoments +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingMoments +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingPowers +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingScalar +OAI.Analysis.IrrationalRotation.Sampling.TrialSamplingSelection +OAI.Analysis.IrrationalRotation.Sampling.TrimmedCircleSamplingGraph +OAI.Analysis.IrrationalRotation.Sampling.UniformIntervalPhase +OAI.Analysis.IrrationalRotation.Spectral.AffiliatedPositiveResolvent +OAI.Analysis.IrrationalRotation.Spectral.BrownDiracReduction +OAI.Analysis.IrrationalRotation.Spectral.CFCLogSeries +OAI.Analysis.IrrationalRotation.Spectral.DeterminantHomogeneity +OAI.Analysis.IrrationalRotation.Spectral.DeterminantWeightBridge +OAI.Analysis.IrrationalRotation.Spectral.FieldDiagonalPolar +OAI.Analysis.IrrationalRotation.Spectral.FieldResolvent +OAI.Analysis.IrrationalRotation.Spectral.FieldResolventTransport +OAI.Analysis.IrrationalRotation.Spectral.InvertibleDeterminant +OAI.Analysis.IrrationalRotation.Spectral.PartialResolventCalculus +OAI.Analysis.IrrationalRotation.Spectral.PhaseBlockQuasinilpotent +OAI.Analysis.IrrationalRotation.Spectral.PolarFactor +OAI.Analysis.IrrationalRotation.Spectral.PolarStructure +OAI.Analysis.IrrationalRotation.Spectral.PositivePartialResolvent +OAI.Analysis.IrrationalRotation.Spectral.ProductBlockQuasinilpotent +OAI.Analysis.IrrationalRotation.Spectral.ProductBrownMeasure +OAI.Analysis.IrrationalRotation.Spectral.ProductDeterminant +OAI.Analysis.IrrationalRotation.Spectral.ProductFinitePolar +OAI.Analysis.IrrationalRotation.Spectral.ProductPolarAssembly +OAI.Analysis.IrrationalRotation.Spectral.ProductPolarComplete +OAI.Analysis.IrrationalRotation.Spectral.ProductPolarDiffuse +OAI.Analysis.IrrationalRotation.Spectral.ProductPolarModulusComplex +OAI.Analysis.IrrationalRotation.Spectral.ProductPolarRange +OAI.Analysis.IrrationalRotation.Spectral.ProductQuasinilpotent +OAI.Analysis.IrrationalRotation.Spectral.ProductSpectralBundle +OAI.Analysis.IrrationalRotation.Spectral.ProductWeightPolar +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentBrown +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentCommuting +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentDeterminantReduction +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentNonscalar +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentSeries +OAI.Analysis.IrrationalRotation.Spectral.QuasinilpotentTraceDerivative +OAI.Analysis.IrrationalRotation.Spectral.RotationDeterminant +OAI.Analysis.IrrationalRotation.Spectral.RotationQuasinilpotent +OAI.Analysis.IrrationalRotation.Spectral.RotationResolvent +OAI.Analysis.IrrationalRotation.Spectral.ScalarDeterminantZero +OAI.Analysis.IrrationalRotation.Spectral.Spectral +OAI.Analysis.IrrationalRotation.Spectral.SpectralNaturality +OAI.Analysis.IrrationalRotation.Spectral.TracialInvertibleDeterminant +OAI.Analysis.IrrationalRotation.Spectral.VectorSpectral +OAI.Analysis.IrrationalRotation.Spectral.WeightedShiftPolar diff --git a/tasks/irrational-rotation/solution/reference.py b/tasks/irrational-rotation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/irrational-rotation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/irrational-rotation/solution/solve.sh b/tasks/irrational-rotation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..322460982edb2ed412183ee2d4754746df06384f --- /dev/null +++ b/tasks/irrational-rotation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IrrationalRotation, i.e. module OAI.Analysis.IrrationalRotation.Main and the +# 735 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.IrrationalRotation.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IrrationalRotation" diff --git a/tasks/irrational-rotation/task.toml b/tasks/irrational-rotation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d08b6be76e045c64009b6499dcb1b262e8002a32 --- /dev/null +++ b/tasks/irrational-rotation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/irrational-rotation" +version = "1.0.0" +description = "Prove IrrationalRotation (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IrrationalRotation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IrrationalRotation" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.Invariant233.Results.prescribed_irrational_counterexample", "OAI.Invariant233.Results.product_realization"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.IrrationalRotation.Main" +reference_modules = 735 +reference_lean_bytes = 3645017 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1441 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14980 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/irrational-rotation/tests/Challenge.lean b/tasks/irrational-rotation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..000d6f0765e02c85a8646c1df0e14fc862d217e4 --- /dev/null +++ b/tasks/irrational-rotation/tests/Challenge.lean @@ -0,0 +1,849 @@ +import Mathlib + +namespace OAI + +section +noncomputable section +open Filter MeasureTheory +open scoped ENNReal Topology + +namespace Invariant233 + +abbrev Circle := AddCircle (1 : ℝ) + +def circleMeasure : Measure Circle := volume + +def negLogCost (t : ℝ) : ℝ≥0∞ := + if t = 0 then ∞ else ENNReal.ofReal (-Real.log |t|) + +def HasNegInfiniteLogIntegral {X : Type*} [MeasurableSpace X] + (μ : Measure X) (f : X → ℝ) : Prop := + (∫⁻ x, negLogCost (f x) ∂μ) = ∞ + +def scalarWeightDeterminant {X : Type*} [MeasurableSpace X] + (μ : Measure X) (f : X → ℝ) : ℝ≥0∞ := + EReal.exp (-((∫⁻ x, negLogCost (f x) ∂μ) : EReal)) + +def NormQuasinilpotent {A : Type*} [NormedRing A] (T : A) : Prop := + Tendsto (fun n : ℕ => ‖T ^ n‖ ^ (1 / (n : ℝ))) atTop (𝓝 0) + +def IsContinuousCircleWeight (f : Circle → ℝ) : Prop := + Continuous f ∧ (∀ x, 0 ≤ f x ∧ f x ≤ 1) ∧ + (∀ x, f x = 0 ↔ x = 0) ∧ HasNegInfiniteLogIntegral circleMeasure f + +end Invariant233 + +end +end + +section +noncomputable section +open scoped ENNReal +namespace Invariant233.WeightedShift + +abbrev Hilbert := lp (fun _ : ℤ => ℂ) 2 +abbrev Weight := lp (fun _ : ℤ => ℂ) ∞ + +def reindex (e : Equiv.Perm ℤ) : Hilbert ≃ₗᵢ[ℂ] Hilbert where + toFun ξ := ⟨fun k => ξ (e k), memℓp_gen <| + (e.summable_iff).2 ((lp.memℓp ξ).summable (by norm_num))⟩ + invFun ξ := ⟨fun k => ξ (e.symm k), memℓp_gen <| + (e.symm.summable_iff).2 ((lp.memℓp ξ).summable (by norm_num))⟩ + left_inv ξ := by ext k; simp + right_inv ξ := by ext k; simp + map_add' ξ η := by ext k; rfl + map_smul' c ξ := by ext k; rfl + norm_map' ξ := by + rw [lp.norm_eq_tsum_rpow (by norm_num), lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.tsum_eq (fun k => ‖ξ k‖ ^ (2 : ENNReal).toReal) + +def shift (m : ℤ) : Hilbert ≃ₗᵢ[ℂ] Hilbert := reindex (Equiv.addRight (-m)) + +def diagonal (w : Weight) : Hilbert →L[ℂ] Hilbert := + lp.mapCLM 2 (fun k => w k • ContinuousLinearMap.id ℂ ℂ) (norm_nonneg w) + (fun k => by + let : T0Space ℂ := @MetricSpace.instT0Space ℂ Complex.instNormedAddCommGroup.toMetricSpace + simpa [norm_smul] using lp.norm_apply_le_norm (by simp) w k) + +def diagonalAlgHom : Weight →ₐ[ℂ] (Hilbert →L[ℂ] Hilbert) where + toFun := diagonal + map_one' := by + ext ξ k + change (1 : ℂ) * ξ k = ξ k + exact one_mul _ + map_mul' w v := by + ext ξ k + change (w k * v k) * ξ k = w k * (v k * ξ k) + exact mul_assoc _ _ _ + map_zero' := by + ext ξ k + change (0 : ℂ) * ξ k = 0 + exact zero_mul _ + map_add' w v := by + ext ξ k + change (w k + v k) * ξ k = w k * ξ k + v k * ξ k + exact add_mul _ _ _ + commutes' c := by + ext ξ k + change c * ξ k = c * ξ k + rfl + +def translate (w : Weight) (m : ℤ) : Weight := + ⟨fun k => w (k + m), memℓp_infty <| by + refine ⟨‖w‖, ?_⟩ + rintro r ⟨k, rfl⟩ + exact lp.norm_apply_le_norm (by simp) w (k + m)⟩ + +def operator (w : Weight) : Hilbert →L[ℂ] Hilbert := + (shift 1).toLinearIsometry.toContinuousLinearMap.comp (diagonal w) + +def orbitProduct (w : Weight) (n : ℕ) : Weight := + ⟨fun k => ∏ j ∈ Finset.range n, w (k + j), memℓp_infty <| by + refine ⟨‖w‖ ^ n, ?_⟩ + rintro r ⟨k, rfl⟩ + calc + ‖∏ j ∈ Finset.range n, w (k + j)‖ ≤ + ∏ j ∈ Finset.range n, ‖w (k + j)‖ := le_of_eq (norm_prod _ _) + _ ≤ ∏ _j ∈ Finset.range n, ‖w‖ := by + apply Finset.prod_le_prod₀ + · intro j hj; exact norm_nonneg _ + · intro j hj; exact lp.norm_apply_le_norm (by simp) w _ + _ = ‖w‖ ^ n := by simp⟩ + +def tailWeight (m : ℤ) : Weight := + ⟨fun k => if m ≤ k then 1 else 0, memℓp_infty <| by + refine ⟨1, ?_⟩ + rintro r ⟨k, rfl⟩ + by_cases h : m ≤ k <;> simp [h]⟩ + +def tailProjection (m : ℤ) : Hilbert →L[ℂ] Hilbert := diagonal (tailWeight m) + +end Invariant233.WeightedShift + +end +end + +section +open scoped Pointwise + +namespace Invariant233 + +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] + +local instance instStarModuleGenerated : StarModule ℂ (H →L[ℂ] H) := + ContinuousLinearMap.instStarModuleId + +noncomputable def vonNeumannGenerated (s : Set (H →L[ℂ] H)) : VonNeumannAlgebra H where + toStarSubalgebra := + StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) + centralizer_centralizer' := by + change Set.centralizer (Set.centralizer + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : + Set (H →L[ℂ] H))) = _ + rw [StarSubalgebra.coe_centralizer_centralizer] + rw [Set.centralizer_centralizer_centralizer] + exact (StarSubalgebra.coe_centralizer_centralizer ℂ s).symm + +end Invariant233 + +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal lp Topology + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace Invariant233.WeightedShift +variable {X : Type*} [MeasurableSpace X] {μ : Measure X} + +theorem diagonal_value (w : Weight) (v : Hilbert) (i : ℤ) : + diagonal w v i = w i * v i := rfl + +theorem diagonal_bound (w : Weight) (C : ℝ) (hw : ‖w‖ ≤ C) (v : Hilbert) : + ‖diagonal w v‖ ≤ C * ‖v‖ := by + apply (diagonal w).le_of_opNorm_le + exact (lp.norm_mapCLM_le 2 _ (norm_nonneg w) _).trans hw + +theorem diagonal_aestronglyMeasurable (a : X → Weight) (C : ℝ) (_hC : 0 ≤ C) + (_ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + {f : X → Hilbert} (hf : AEStronglyMeasurable f μ) : + AEStronglyMeasurable (fun x => diagonal (a x) (f x)) μ := by + classical + let : Nonempty (Finset ℤ) := ⟨∅⟩ + let F : Finset ℤ → X → Hilbert := + fun s => ∑ i ∈ s, fun x => lp.single 2 i (a x i * f x i) + apply aestronglyMeasurable_of_tendsto_ae (atTop : Filter (Finset ℤ)) + (f := F) + · intro s + apply Finset.aestronglyMeasurable_sum + intro i hi + exact (lp.singleContinuousLinearMap ℂ (fun _ : ℤ => ℂ) 2 i).continuous.comp_aestronglyMeasurable + ((hm i).mul ((lp.evalCLM ℂ (fun _ : ℤ => ℂ) 2 i).continuous.comp_aestronglyMeasurable hf)) + · apply Filter.Eventually.of_forall + intro x + simpa only [F, Finset.sum_apply, diagonal_value, HasSum, SummationFilter.unconditional] using + lp.hasSum_single (by norm_num) (diagonal (a x) (f x)) + +def fieldDiagonalVec (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + (f : Lp (Hilbert) 2 μ) : Lp (Hilbert) 2 μ := + ((Lp.memLp f).of_le_mul + (diagonal_aestronglyMeasurable a C hC ha hm (Lp.aestronglyMeasurable f)) + (Filter.Eventually.of_forall fun x => diagonal_bound (a x) C (ha x) (f x))).toLp _ + +theorem fieldDiagonalVec_ae (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) + (f : Lp (Hilbert) 2 μ) : + fieldDiagonalVec a C hC ha hm f =ᵐ[μ] + fun x => diagonal (a x) (f x) := + MemLp.coeFn_toLp _ + +def fieldDiagonalLinear (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) : + Lp (Hilbert) 2 μ →ₗ[ℂ] Lp (Hilbert) 2 μ where + toFun := fieldDiagonalVec a C hC ha hm + map_add' f g := by + apply Lp.ext + filter_upwards [fieldDiagonalVec_ae a C hC ha hm (f + g), + fieldDiagonalVec_ae a C hC ha hm f, fieldDiagonalVec_ae a C hC ha hm g, + Lp.coeFn_add f g, Lp.coeFn_add + (fieldDiagonalVec a C hC ha hm f) (fieldDiagonalVec a C hC ha hm g)] + with x hfg hf hg hsum hout + simp only [Pi.add_apply] at hsum hout + rw [hfg, hout, hf, hg, hsum, map_add] + map_smul' c f := by + change fieldDiagonalVec a C hC ha hm (c • f) = c • fieldDiagonalVec a C hC ha hm f + apply Lp.ext + filter_upwards [fieldDiagonalVec_ae a C hC ha hm (c • f), + fieldDiagonalVec_ae a C hC ha hm f, Lp.coeFn_smul c f, + Lp.coeFn_smul c (fieldDiagonalVec a C hC ha hm f)] with x hcf hf hsmul hout + simp only [Pi.smul_apply] at hsmul hout + rw [hcf, hout, hf, hsmul, map_smul] + +def fieldDiagonal (a : X → Weight) (C : ℝ) (hC : 0 ≤ C) + (ha : ∀ x, ‖a x‖ ≤ C) + (hm : ∀ i, AEStronglyMeasurable (fun x => a x i) μ) : + Lp (Hilbert) 2 μ →L[ℂ] Lp (Hilbert) 2 μ := + (fieldDiagonalLinear a C hC ha hm).mkContinuous C (by + intro f + apply Lp.norm_le_mul_norm_of_ae_le_mul + change ∀ᵐ x ∂μ, ‖fieldDiagonalVec a C hC ha hm f x‖ ≤ C * ‖f x‖ + filter_upwards [fieldDiagonalVec_ae a C hC ha hm f] with x hx + rw [hx] + exact diagonal_bound (a x) C (ha x) (f x)) + +end Invariant233.WeightedShift + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace Invariant233.Rotation + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +instance circleMeasure_probability : IsProbabilityMeasure circleMeasure := by + constructor + change volume (Set.univ : Set Circle) = 1 + exact UnitAddCircle.measure_univ + +abbrev Fiber := WeightedShift.Hilbert +abbrev Hilbert := MeasureTheory.Lp Fiber 2 circleMeasure + +def action (θ : ℝ) (k : ℤ) (x : Circle) : Circle := + x + k • (θ : Circle) + +def U : Hilbert →L[ℂ] Hilbert := + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap.compLpL 2 circleMeasure + +def orbitWeight (θ : ℝ) (a : C(Circle, ℂ)) (x : Circle) : WeightedShift.Weight := + ⟨fun k => a (action θ k x), memℓp_infty <| by + refine ⟨‖a‖, ?_⟩ + rintro r ⟨k, rfl⟩ + exact a.norm_coe_le_norm _⟩ + +def character : C(Circle, ℂ) := fourier 1 + +def representation (θ : ℝ) (a : C(Circle, ℂ)) : Hilbert →L[ℂ] Hilbert := + WeightedShift.fieldDiagonal (orbitWeight θ a) ‖a‖ (norm_nonneg a) + (fun x => lp.norm_le_of_forall_le (norm_nonneg a) (fun k => a.norm_coe_le_norm _)) + (fun k => by + let : T0Space ℝ := @MetricSpace.instT0Space ℝ Real.metricSpace + let : T0Space ℂ := @MetricSpace.instT0Space ℂ Complex.instNormedAddCommGroup.toMetricSpace + change AEStronglyMeasurable (fun x : Circle => a (x + k • (θ : Circle))) circleMeasure + exact (a.continuous.comp (continuous_id.add continuous_const)).aestronglyMeasurable) + +def V (θ : ℝ) : Hilbert →L[ℂ] Hilbert := representation θ character + +def algebra (θ : ℝ) : VonNeumannAlgebra Hilbert := + vonNeumannGenerated ({U, V θ} : Set (Hilbert →L[ℂ] Hilbert)) + +def weighted (θ : ℝ) (a : C(Circle, ℂ)) : Hilbert →L[ℂ] Hilbert := + U * representation θ a + +def complexWeight (f : C(Circle, ℝ)) : C(Circle, ℂ) := + ⟨fun x => (f x : ℂ), Complex.continuous_ofReal.comp f.continuous⟩ + +def weightedReal (θ : ℝ) (f : C(Circle, ℝ)) : Hilbert →L[ℂ] Hilbert := + weighted θ (complexWeight f) + +def vacuum : Hilbert := Lp.const 2 circleMeasure (lp.single 2 (0 : ℤ) (1 : ℂ)) + +def vacuumFunctional (T : Hilbert →L[ℂ] Hilbert) : ℂ := inner ℂ vacuum (T vacuum) + +end Invariant233.Rotation + +end +end + +section +noncomputable section +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +universe u + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] + +def HasOnlyTrivialInvariantProjections (M : VonNeumannAlgebra H) + (T : H →L[ℂ] H) : Prop := + ∀ p : H →L[ℂ] H, p ∈ M → IsStarProjection p → + (1 - p) * T * p = 0 → p = 0 ∨ p = 1 + +def IsProjectionAtom (M : VonNeumannAlgebra H) (p : H →L[ℂ] H) : Prop := + p ∈ M ∧ IsStarProjection p ∧ p ≠ 0 ∧ + ∀ q : H →L[ℂ] H, q ∈ M → IsStarProjection q → q * p = q → + q = 0 ∨ q = p + +def IsAtomicVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ p : H →L[ℂ] H, p ∈ M → IsStarProjection p → p ≠ 0 → + ∃ q : H →L[ℂ] H, IsProjectionAtom M q ∧ q * p = q + +def IsAbelianVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ A B : H →L[ℂ] H, A ∈ M → B ∈ M → Commute A B + +def IsDiffuseVonNeumannAlgebra (M : VonNeumannAlgebra H) : Prop := + ∀ p : H →L[ℂ] H, ¬ IsProjectionAtom M p + +def IsFactor (M : VonNeumannAlgebra H) : Prop := + Nontrivial H ∧ ∀ A : H →L[ℂ] H, A ∈ M → + (∀ B : H →L[ℂ] H, B ∈ M → Commute A B) → + ∃ c : ℂ, A = c • (1 : H →L[ℂ] H) + +def vectorTrace (ξ : H) (A : H →L[ℂ] H) : ℂ := + @inner ℂ H InnerProductSpace.toInner ξ (A ξ) + +def IsFaithfulTracialVector (M : VonNeumannAlgebra H) (ξ : H) : Prop := + ‖ξ‖ = 1 ∧ + (∀ A B : H →L[ℂ] H, A ∈ M → B ∈ M → + vectorTrace ξ (A * B) = vectorTrace ξ (B * A)) ∧ + (∀ A : H →L[ℂ] H, A ∈ M → A.IsPositive → + vectorTrace ξ A = 0 → A = 0) + +def IsTypeII1FactorWithVector (M : VonNeumannAlgebra H) (ξ : H) : Prop := + IsFactor M ∧ IsDiffuseVonNeumannAlgebra M ∧ IsFaithfulTracialVector M ξ + +local instance instNormedAlgebraPredual : NormedAlgebra ℂ (H →L[ℂ] H) := + ContinuousLinearMap.toNormedAlgebra + +def HasSeparablePredual (M : VonNeumannAlgebra H) : Prop := + ∃ (X : Type u) (_ : NormedAddCommGroup X) (_ : NormedSpace ℂ X) + (_ : CompleteSpace X) (_ : TopologicalSpace.SeparableSpace X), + Nonempty (StrongDual ℂ X ≃ₗᵢ[ℂ] M.toStarSubalgebra) + +end Invariant233 + +end +end + +section +noncomputable section + +open MeasureTheory +open scoped ENNReal + +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +structure TracialState (A : Type*) [CStarAlgebra A] where + toContinuousLinearMap : A →L[ℂ] ℂ + map_one : toContinuousLinearMap 1 = 1 + map_star : ∀ a, toContinuousLinearMap (star a) = star (toContinuousLinearMap a) + positive : ∀ a, 0 ≤ (toContinuousLinearMap (star a * a)).re + tracial : ∀ a b, toContinuousLinearMap (a * b) = toContinuousLinearMap (b * a) + +namespace TracialState + +variable {A : Type*} [CStarAlgebra A] + +instance : CoeFun (TracialState A) (fun _ => A → ℂ) := + ⟨fun τ => τ.toContinuousLinearMap⟩ + +end TracialState + +def fugledeKadisonDeterminant {A : Type*} [CStarAlgebra A] + (τ : TracialState A) (a : A) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, + ENNReal.ofReal (Real.exp ((τ (CFC.log (star a * a + (ε.val : ℝ) • (1 : A)))).re / 2)) + +def logarithmicPotentialDeterminant (μ : Measure ℂ) (z : ℂ) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, + ENNReal.ofReal (Real.exp ((∫ w, Real.log (‖w - z‖ ^ 2 + ε.val) ∂μ) / 2)) + +def IsBrownMeasure {A : Type*} [CStarAlgebra A] + (τ : TracialState A) (a : A) (μ : Measure ℂ) : Prop := + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ + ∀ z : ℂ, fugledeKadisonDeterminant τ (a - algebraMap ℂ A z) = + logarithmicPotentialDeterminant μ z + +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233 +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def vectorFugledeKadisonDeterminant (ξ : H) (T : H →L[ℂ] H) : ℝ≥0∞ := + ⨅ ε : {r : ℝ // 0 < r}, ENNReal.ofReal + (Real.exp ((vectorTrace ξ (CFC.log (star T * T + ε.val • (1 : H →L[ℂ] H)))).re / 2)) + +def IsVectorBrownMeasure (ξ : H) (T : H →L[ℂ] H) (μ : Measure ℂ) : Prop := + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ ∀ z : ℂ, + vectorFugledeKadisonDeterminant ξ (T - z • (1 : H →L[ℂ] H)) = + logarithmicPotentialDeterminant μ z + +def operatorModulus (T : H →L[ℂ] H) : H →L[ℂ] H := CFC.sqrt (star T * T) + +def HasCountablyAtomicSpectralType (B : H →L[ℂ] H) : Prop := + ∃ S : Set ℂ, S.Countable ∧ + (⨆ z : S, Module.End.eigenspace B.toLinearMap z.val).topologicalClosure = ⊤ + +def polarConjugate (U B : H →L[ℂ] H) (n : ℤ) : H →L[ℂ] H := + if 0 ≤ n then U ^ n.toNat * B * star U ^ n.toNat + else star U ^ (-n).toNat * B * U ^ (-n).toNat + +def finitePolarAlgebra (U B : H →L[ℂ] H) (F : Finset ℤ) : VonNeumannAlgebra H := + vonNeumannGenerated {A | ∃ n ∈ F, A = polarConjugate U B n} + +def fullPolarAlgebra (U B : H →L[ℂ] H) : VonNeumannAlgebra H := + vonNeumannGenerated (Set.range (polarConjugate U B)) + +def ProductPolarStructure (U T : H →L[ℂ] H) : Prop := + star U * U = 1 ∧ U * star U = 1 ∧ T = U * operatorModulus T ∧ + Function.Injective (operatorModulus T) ∧ HasCountablyAtomicSpectralType (operatorModulus T) ∧ + (∀ F : Finset ℤ, + IsAbelianVonNeumannAlgebra (finitePolarAlgebra U (operatorModulus T) F) ∧ + IsAtomicVonNeumannAlgebra (finitePolarAlgebra U (operatorModulus T) F)) ∧ + IsAbelianVonNeumannAlgebra (fullPolarAlgebra U (operatorModulus T)) ∧ + IsDiffuseVonNeumannAlgebra (fullPolarAlgebra U (operatorModulus T)) + +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def circleRepresentative (x : Circle) : ℝ := + (AddCircle.equivIco (1 : ℝ) 0 x).val + +instance circleMeasure_probability : IsProbabilityMeasure circleMeasure := by + constructor + simp [circleMeasure, Circle, AddCircle.measure_univ] + +namespace ProductModel + +abbrev Base := ℕ → Circle + +def baseMeasure : Measure Base := Measure.infinitePi (fun _ : ℕ => circleMeasure) + +instance baseMeasure_probability : IsProbabilityMeasure baseMeasure := by + unfold baseMeasure + infer_instance + +def Ordered (x y : Base) : Prop := + ∀ i, circleRepresentative (x i) ≤ circleRepresentative (y i) + +def rotation (θ : ℕ → ℝ) (x : Base) : Base := + fun i => x i + (θ i : Circle) + +def rotationIterate (θ : ℕ → ℝ) (k : ℤ) (x : Base) : Base := + fun i => x i + ((k : ℝ) * θ i : ℝ) + +def logarithmicCost (θ c : ℕ → ℝ) (x : Base) : ℝ≥0∞ := + ∑' i, ENNReal.ofReal (c i * (⌊circleRepresentative (x i) + θ i⌋ : ℤ)) + +def weight (θ c : ℕ → ℝ) (x : Base) : ℝ := + (EReal.exp (-(logarithmicCost θ c x : EReal))).toReal + +def JointlyRationallyIndependent (θ : ℕ → ℝ) : Prop := + LinearIndependent ℚ (fun i : Option ℕ => i.elim 1 θ) + +def AdmissibleAnglesAndCosts (θ c : ℕ → ℝ) : Prop := + (∀ i, 0 < θ i ∧ θ i < 1 ∧ 0 < c i) ∧ + Summable θ ∧ JointlyRationallyIndependent θ + +abbrev Fiber := @lp ℤ (fun _ => ℂ) (fun _ => Complex.instNormedAddCommGroup) 2 +abbrev Hilbert := + @MeasureTheory.Lp Base Fiber MeasurableSpace.pi + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + 2 baseMeasure + +end ProductModel +end Invariant233 + +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace Invariant233.ProductModel + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +theorem measurable_rep : Measurable circleRepresentative := + measurable_subtype_coe.comp (AddCircle.measurableEquivIco (T := (1 : ℝ)) 0).measurable + +theorem measurable_iterate (θ : ℕ → ℝ) (k : ℤ) : + Measurable (rotationIterate θ k) := by + let : T0Space ℝ := @MetricSpace.instT0Space ℝ Real.metricSpace + let : BorelSpace Circle := QuotientAddGroup.borelSpace + let : ContinuousAdd Circle := + (QuotientAddGroup.instIsTopologicalAddGroup (AddSubgroup.zmultiples (1 : ℝ))).toContinuousAdd + let : MeasurableAdd Circle := ContinuousAdd.measurableAdd + apply Measurable.of_eval + intro i + exact (measurable_pi_apply i).add_const _ + +theorem measurable_cost (θ c : ℕ → ℝ) : Measurable (logarithmicCost θ c) := by + apply Measurable.tsum + intro i + have hm : Measurable (fun x : Base => circleRepresentative (x i) + θ i) := + (measurable_rep.comp (measurable_pi_apply i)).add_const (θ i) + have hc : Measurable (fun x : Base => (⌊circleRepresentative (x i) + θ i⌋ : ℝ)) := + (measurable_of_countable (fun z : ℤ => (z : ℝ))).comp hm.floor + exact (measurable_const.mul hc).ennreal_ofReal + +theorem weight_measurable (θ c : ℕ → ℝ) : Measurable (weight θ c) := by + exact (measurable_cost θ c).coe_ereal_ennreal.neg.ereal_exp.ennreal_toReal + +theorem weight_nonneg (θ c : ℕ → ℝ) (x : Base) : 0 ≤ weight θ c x := + ENNReal.toReal_nonneg + +theorem weight_le_one (θ c : ℕ → ℝ) (x : Base) : weight θ c x ≤ 1 := by + have h : EReal.exp (-(logarithmicCost θ c x : EReal)) ≤ 1 := by + rw [← EReal.exp_zero] + apply EReal.exp_le_exp_iff.mpr + exact EReal.neg_le_zero.mpr (EReal.coe_ennreal_nonneg (logarithmicCost θ c x)) + exact (ENNReal.toReal_mono (by simp) h).trans (by simp) + +def shiftOperator : Hilbert →L[ℂ] Hilbert := + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap.compLpL 2 baseMeasure + +def multiplierField (θ : ℕ → ℝ) (g : Base → ℂ) (C : ℝ) + (hb : ∀ x, ‖g x‖ ≤ C) (x : Base) : WeightedShift.Weight := + ⟨fun k => g (rotationIterate θ k x), memℓp_infty <| by + refine ⟨C, ?_⟩ + rintro r ⟨k, rfl⟩ + exact hb _⟩ + +def multiplier (θ : ℕ → ℝ) (g : Base → ℂ) (C : ℝ) (hC : 0 ≤ C) + (hg : Measurable g) (hb : ∀ x, ‖g x‖ ≤ C) : Hilbert →L[ℂ] Hilbert := + WeightedShift.fieldDiagonal (multiplierField θ g C hb) C hC + (fun _x => lp.norm_le_of_forall_le hC (fun _k => hb _)) + (fun k => (hg.comp (measurable_iterate θ k)).aestronglyMeasurable) + +def multiplierGenerators (θ : ℕ → ℝ) : Set (Hilbert →L[ℂ] Hilbert) := + {A | ∃ (g : Base → ℂ) (C : ℝ) (hC : 0 ≤ C) (hg : Measurable g) + (hb : ∀ x, ‖g x‖ ≤ C), A = multiplier θ g C hC hg hb} + +def factor (θ : ℕ → ℝ) : VonNeumannAlgebra Hilbert := + vonNeumannGenerated ({shiftOperator} ∪ multiplierGenerators θ) + +def traceVector : Hilbert := Lp.const 2 baseMeasure (lp.single 2 0 (1 : ℂ)) + +theorem measurable_complexWeight (θ c : ℕ → ℝ) : + Measurable (fun x => (weight θ c x : ℂ)) := + (weight_measurable θ c).complex_ofReal + +theorem norm_complexWeight_le_one (θ c : ℕ → ℝ) (x : Base) : + ‖(weight θ c x : ℂ)‖ ≤ 1 := by + simpa only [Complex.norm_real, Real.norm_eq_abs, abs_of_nonneg (weight_nonneg θ c x)] + using weight_le_one θ c x + +local instance instNormedAddCommGroupProductWeightedOperator : NormedAddCommGroup Hilbert := + @MeasureTheory.Lp.instNormedAddCommGroup Base Fiber MeasurableSpace.pi 2 baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + fact_one_le_two_ennreal + +local instance instInnerProductSpaceProductWeightedOperator : + @InnerProductSpace ℂ Hilbert Complex.instRCLike + instNormedAddCommGroupProductWeightedOperator.toSeminormedAddCommGroup := + @MeasureTheory.L2.innerProductSpace Base Fiber ℂ Complex.instRCLike MeasurableSpace.pi + baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) fact_one_le_two_ennreal) + (@lp.instInnerProductSpace ℤ ℂ Complex.instRCLike (fun _ => ℂ) + (fun _ => Complex.instNormedAddCommGroup) + (fun _ => @RCLike.innerProductSpace ℂ Complex.instRCLike)) + +local instance instTopologicalSpaceProductWeightedOperator : TopologicalSpace Hilbert := + instNormedAddCommGroupProductWeightedOperator.toUniformSpace.toTopologicalSpace + +local instance instAddCommMonoidProductWeightedOperator : AddCommMonoid Hilbert := + instNormedAddCommGroupProductWeightedOperator.toAddCommGroup.toAddCommMonoid + +local instance instModuleProductWeightedOperator : Module ℂ Hilbert := + instInnerProductSpaceProductWeightedOperator.toNormedSpace.toModule + +local notation "weightedOperatorSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring + +local notation "weightedOperatorScalarIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ weightedOperatorSemiring) + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def weightedOperator (θ c : ℕ → ℝ) : + @ContinuousLinearMap ℂ ℂ weightedOperatorSemiring weightedOperatorSemiring + weightedOperatorScalarIdentity + Hilbert instTopologicalSpaceProductWeightedOperator instAddCommMonoidProductWeightedOperator + Hilbert instTopologicalSpaceProductWeightedOperator instAddCommMonoidProductWeightedOperator + instModuleProductWeightedOperator instModuleProductWeightedOperator := + let compose := fun (Scalar : Type) [Semiring Scalar] (Space : Type) + [TopologicalSpace Space] [AddCommMonoid Space] [Module Scalar Space] + (left right : Space →L[Scalar] Space) => left ∘L right + @compose ℂ weightedOperatorSemiring Hilbert instTopologicalSpaceProductWeightedOperator + instAddCommMonoidProductWeightedOperator instModuleProductWeightedOperator + shiftOperator (multiplier θ (fun x => (weight θ c x : ℂ)) 1 zero_le_one + (measurable_complexWeight θ c) (norm_complexWeight_le_one θ c)) + +end Invariant233.ProductModel + +end +end + +section +noncomputable section +open Filter MeasureTheory +open scoped ENNReal Topology BigOperators + +namespace Invariant233.ProductModel + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev EndpointPair := Base × Base + +def selectedEndpoint (I : Finset ℕ) (x z : Base) : Base := + fun i => if i ∈ I then z i else x i + +def triangularEvent (I : Finset ℕ) : Set EndpointPair := + {xz | ∀ i ∈ I, circleRepresentative (xz.1 i) < circleRepresentative (xz.2 i)} + +def triangularLaw (I : Finset ℕ) : Measure EndpointPair := + Measure.map (fun xz : EndpointPair => (xz.1, selectedEndpoint I xz.1 xz.2)) + ((baseMeasure.prod baseMeasure).restrict (triangularEvent I)) + +def triangularFirstDensity (I : Finset ℕ) (x : Base) : ℝ := + ∏ i ∈ I, (1 - circleRepresentative (x i)) + +def triangularSecondDensity (I : Finset ℕ) (y : Base) : ℝ := + ∏ i ∈ I, circleRepresentative (y i) + +def TriangularLawProperties (I : Finset ℕ) : Prop := + IsFiniteMeasure (triangularLaw I) ∧ + triangularLaw I Set.univ = (1 / 2 : ℝ≥0∞) ^ I.card ∧ + (triangularLaw I).map Prod.fst = + baseMeasure.withDensity (fun x => ENNReal.ofReal (triangularFirstDensity I x)) ∧ + (triangularLaw I).map Prod.snd = + baseMeasure.withDensity (fun y => ENNReal.ofReal (triangularSecondDensity I y)) ∧ + (∀ᵐ xy ∂triangularLaw I, Ordered xy.1 xy.2) ∧ + (∀ x, 0 ≤ triangularFirstDensity I x ∧ triangularFirstDensity I x ≤ 1) ∧ + (∀ y, 0 ≤ triangularSecondDensity I y ∧ triangularSecondDensity I y ≤ 1) + +def WeaklyConverges (η : ℕ → Measure EndpointPair) (ν : Measure EndpointPair) : Prop := + ∀ φ : C(EndpointPair, ℝ), + Tendsto (fun l => ∫ xy, φ xy ∂η l) atTop (𝓝 (∫ xy, φ xy ∂ν)) + +def SupportedOnPositiveOrderedOrbitPairs (θ : ℕ → ℝ) (η : Measure EndpointPair) : Prop := + ∃ N : Finset ℕ, (∀ n ∈ N, 0 < n) ∧ + ∀ᵐ xy ∂η, Ordered xy.1 xy.2 ∧ + ∃ n ∈ N, xy.2 = rotationIterate θ (n : ℤ) xy.1 + +def HasUniformL2Marginals (η : ℕ → Measure EndpointPair) : Prop := + ∃ H : ℝ, 0 ≤ H ∧ ∀ l, ∃ f g : Lp ℝ 2 baseMeasure, + (∀ᵐ x ∂baseMeasure, 0 ≤ f x) ∧ (∀ᵐ y ∂baseMeasure, 0 ≤ g y) ∧ + (η l).map Prod.fst = baseMeasure.withDensity (fun x => ENNReal.ofReal (f x)) ∧ + (η l).map Prod.snd = baseMeasure.withDensity (fun y => ENNReal.ofReal (g y)) ∧ + ‖f‖ ≤ H ∧ ‖g‖ ≤ H + +def OrderedOrbitSampling (θ : ℕ → ℝ) (I : Finset ℕ) : Prop := + ∃ η : ℕ → Measure EndpointPair, + (∀ l, IsFiniteMeasure (η l)) ∧ + (∀ l, SupportedOnPositiveOrderedOrbitPairs θ (η l)) ∧ + HasUniformL2Marginals η ∧ WeaklyConverges η (triangularLaw I) + +def HasAllFiniteCoordinateSampling (θ : ℕ → ℝ) : Prop := + ∀ I : Finset ℕ, OrderedOrbitSampling θ I + +end Invariant233.ProductModel + +end +end + +section +noncomputable section +open MeasureTheory +namespace Invariant233.ProductModel + +def IsCovariantFieldRepresentation (θ : ℕ → ℝ) (A : Hilbert →L[ℂ] Hilbert) + (F : Base → Fiber →L[ℂ] Fiber) (B : ℝ) : Prop := + 0 ≤ B ∧ (∀ x, ‖F x‖ ≤ B) ∧ + (∀ v : Fiber, StronglyMeasurable (fun x => F x v)) ∧ + (∀ f : Hilbert, A f =ᵐ[baseMeasure] fun x => F x (f x)) ∧ + (∀ᵐ x ∂baseMeasure, + F (rotation θ x) = + (WeightedShift.shift (-1)).toLinearIsometry.toContinuousLinearMap * F x * + (WeightedShift.shift 1).toLinearIsometry.toContinuousLinearMap) + +def centralDiagonalIntegral (F : Base → Fiber →L[ℂ] Fiber) : ℂ := + ∫ x, inner ℂ (lp.single 2 0 (1 : ℂ) : Fiber) + (F x (lp.single 2 0 (1 : ℂ) : Fiber)) ∂baseMeasure + +end Invariant233.ProductModel + +end +end + +namespace Invariant233 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def Rotation.IsContinuousCounterexample (θ : ℝ) (f : C(Circle, ℝ)) : Prop := + IsContinuousCircleWeight f ∧ + let operator : Rotation.Hilbert →L[ℂ] Rotation.Hilbert := Rotation.weightedReal θ f + let factor : VonNeumannAlgebra Rotation.Hilbert := Rotation.algebra θ + operator ∈ factor ∧ + HasOnlyTrivialInvariantProjections (H := Rotation.Hilbert) factor operator ∧ + operator ≠ 0 ∧ + NormQuasinilpotent (A := Rotation.Hilbert →L[ℂ] Rotation.Hilbert) operator ∧ + vectorFugledeKadisonDeterminant (H := Rotation.Hilbert) Rotation.vacuum operator = 0 + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +local instance ProductModel.instFactOneLeTwoCounterexample : + Fact (1 ≤ (2 : ENNReal)) := ⟨by norm_num⟩ + +abbrev ProductModel.CounterexampleFiber : Type := + @lp ℤ (fun _ => ℂ) (fun _ => Complex.instNormedAddCommGroup) 2 + +abbrev ProductModel.CounterexampleHilbert : Type := + @MeasureTheory.Lp ProductModel.Base ProductModel.CounterexampleFiber MeasurableSpace.pi + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + 2 ProductModel.baseMeasure + +instance ProductModel.instCompleteSpaceHilbertCounterexample : + CompleteSpace ProductModel.CounterexampleHilbert := inferInstance + +def ProductOperatorProperties {H : Type*} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] (factor : VonNeumannAlgebra H) + (traceVector : H) (shift operator : H →L[ℂ] H) : Prop := + IsTypeII1FactorWithVector factor traceVector ∧ + HasSeparablePredual factor ∧ + operator ∈ factor ∧ operator ≠ 0 ∧ + NormQuasinilpotent operator ∧ + vectorFugledeKadisonDeterminant traceVector operator = 0 ∧ + spectrum ℂ operator = {0} ∧ + IsVectorBrownMeasure traceVector operator (MeasureTheory.Measure.dirac 0) ∧ + HasOnlyTrivialInvariantProjections factor operator ∧ + ProductPolarStructure shift operator + +@[instance_reducible] +noncomputable def ProductModel.counterexampleHilbertNormedAddCommGroup : + NormedAddCommGroup ProductModel.CounterexampleHilbert := + @MeasureTheory.Lp.instNormedAddCommGroup ProductModel.Base ProductModel.CounterexampleFiber + MeasurableSpace.pi 2 ProductModel.baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + ProductModel.instFactOneLeTwoCounterexample + +@[instance_reducible] +noncomputable def ProductModel.counterexampleHilbertInnerProductSpace : + @InnerProductSpace ℂ ProductModel.CounterexampleHilbert Complex.instRCLike + ProductModel.counterexampleHilbertNormedAddCommGroup.toSeminormedAddCommGroup := + @MeasureTheory.L2.innerProductSpace ProductModel.Base ProductModel.CounterexampleFiber ℂ + Complex.instRCLike MeasurableSpace.pi ProductModel.baseMeasure + (@lp.normedAddCommGroup ℤ (fun _ => ℂ) 2 + (fun _ => Complex.instNormedAddCommGroup) ProductModel.instFactOneLeTwoCounterexample) + (@lp.instInnerProductSpace ℤ ℂ Complex.instRCLike (fun _ => ℂ) + (fun _ => Complex.instNormedAddCommGroup) + (fun _ => @RCLike.innerProductSpace ℂ Complex.instRCLike)) + +def ProductModel.HasCounterexampleOperator (θ c : ℕ → ℝ) : Prop := + @ProductOperatorProperties ProductModel.CounterexampleHilbert + ProductModel.counterexampleHilbertNormedAddCommGroup + ProductModel.counterexampleHilbertInnerProductSpace + ProductModel.instCompleteSpaceHilbertCounterexample (ProductModel.factor θ) + ProductModel.traceVector ProductModel.shiftOperator (ProductModel.weightedOperator θ c) + +def ProductModel.IsCounterexampleRealization (θ c : ℕ → ℝ) : Prop := + ProductModel.AdmissibleAnglesAndCosts θ c ∧ + ProductModel.HasAllFiniteCoordinateSampling θ ∧ + Filter.Eventually (fun x : ProductModel.Base => 0 < ProductModel.weight θ c x) + (@MeasureTheory.ae ProductModel.Base + (@MeasureTheory.Measure ProductModel.Base MeasurableSpace.pi) + MeasureTheory.Measure.instFunLike MeasureTheory.Measure.instOuterMeasureClass + ProductModel.baseMeasure) ∧ + @HasNegInfiniteLogIntegral ProductModel.Base MeasurableSpace.pi + ProductModel.baseMeasure (ProductModel.weight θ c) ∧ + ProductModel.HasCounterexampleOperator θ c + +end Invariant233 + +namespace Invariant233.Results + +theorem prescribed_irrational_counterexample (θ : ℝ) + (hθ0 : 0 < θ) (hθ1 : θ < 1) (hθ : Irrational θ) : + ∃ f : C(Circle, ℝ), Rotation.IsContinuousCounterexample θ f := by + sorry + +theorem product_realization : + ∃ θ c : ℕ → ℝ, ProductModel.IsCounterexampleRealization θ c := by + sorry + +end Invariant233.Results + +end OAI diff --git a/tasks/irrational-rotation/tests/grade.py b/tasks/irrational-rotation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/irrational-rotation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/irrational-rotation/tests/task.json b/tasks/irrational-rotation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ed07ac68fbf0dbd2f84635cff8299218abfb2a84 --- /dev/null +++ b/tasks/irrational-rotation/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "IrrationalRotation", + "comparator": { + "theorem_names": [ + "OAI.Invariant233.Results.prescribed_irrational_counterexample", + "OAI.Invariant233.Results.product_realization" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14080 +} \ No newline at end of file diff --git a/tasks/irrational-rotation/tests/test.sh b/tasks/irrational-rotation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/irrational-rotation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/irrational-triangle-billiard/environment/Dockerfile b/tasks/irrational-triangle-billiard/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/irrational-triangle-billiard/environment/fetch_mathlib.sh b/tasks/irrational-triangle-billiard/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/irrational-triangle-billiard/environment/lake-manifest.json b/tasks/irrational-triangle-billiard/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/irrational-triangle-billiard/environment/lakefile.lean b/tasks/irrational-triangle-billiard/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/irrational-triangle-billiard/environment/lean_setup.sh b/tasks/irrational-triangle-billiard/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/irrational-triangle-billiard/environment/pack_submission.py b/tasks/irrational-triangle-billiard/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/irrational-triangle-billiard/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/irrational-triangle-billiard/instruction.md b/tasks/irrational-triangle-billiard/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1109497d4c51221a9d02c44a34232ca5ffd5ed29 --- /dev/null +++ b/tasks/irrational-triangle-billiard/instruction.md @@ -0,0 +1,177 @@ +# openai/math challenge `IrrationalTriangleBilliard` (family 150) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 150 of the release, *Weak mixing of irrational triangular billiards* +(Dynamical systems and ergodic theory). The family as a whole: Proves that the billiard flow in every nondegenerate Euclidean triangle with at least one angle irrational relative to $\pi$ is weakly mixing for normalized area times uniform direction. This strengthens ergodicity on the entire irrational-angle class, with no genericity or Diophantine restrictions. + +The challenge is `IrrationalTriangleBilliard`, also at `/opt/openai-math/challenges/IrrationalTriangleBilliard.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +The phase space is represented in the ambient plane × circle, with measure +supported on the interior of the triangle. Values on side-collision states +at a fixed time are immaterial to the modulo-null-set conclusion. The +trajectories themselves include the collisions and impose specular reflection. +-/ + +open MeasureTheory Set +open scoped ENNReal symmDiff + +noncomputable section + +namespace TriangularBilliards + +/-- Three affinely independent vertices in the Euclidean plane. -/ +structure Triangle where + vertex : Fin 3 → ℂ + nondegenerate : AffineIndependent ℝ vertex + +namespace Triangle + +/-- The open table; the complex plane carries its ordinary real Euclidean metric. -/ +def table (Q : Triangle) : Set ℂ := interior (convexHull ℝ (range Q.vertex)) + +/-- The open side from vertex `i` to the next vertex, indexed cyclically. -/ +def side (Q : Triangle) (i : Fin 3) : Set ℂ := + openSegment ℝ (Q.vertex i) (Q.vertex (i + 1)) + +/-- A tangent vector to side `i`, with no choice of inward or outward normal. -/ +def tangent (Q : Triangle) (i : Fin 3) : ℂ := Q.vertex (i + 1) - Q.vertex i + +/-- Interior angle at vertex `i`. -/ +def angle (Q : Triangle) (i : Fin 3) : ℝ := + InnerProductGeometry.angle (Q.vertex (i + 1) - Q.vertex i) + (Q.vertex (i + 2) - Q.vertex i) + +def HasIrrationalAngle (Q : Triangle) : Prop := + ∃ i : Fin 3, Irrational (Q.angle i / Real.pi) + +end Triangle + +/-- Reflection in the real line spanned by the nonzero tangent `e`. +In coordinates with `e` real this is complex conjugation, preserving the +tangential component and reversing the normal component. -/ +def reflect (e v : ℂ) : ℂ := (e / star e) * star v + +instance circleMeasurableSpace : MeasurableSpace Circle := borel Circle + +instance circleBorelSpace : BorelSpace Circle := ⟨rfl⟩ + +abbrev Phase := ℂ × Circle + +/-- A complete nonsingular billiard trajectory, indexed by its collisions. +Flight zero contains the initial time strictly. Both ends of the collision +time sequence are unbounded; collisions occur only in open sides, never +vertices. These are geometric conditions, not ergodicity/analytic assumptions. -/ +structure FlightChain (Q : Triangle) (z : Phase) where + time : ℤ → ℝ + point : ℤ → ℂ + direction : ℤ → Circle + wall : ℤ → Fin 3 + increasing : StrictMono time + unbounded_below : ∀ t : ℝ, ∃ n : ℤ, time n < t + unbounded_above : ∀ t : ℝ, ∃ n : ℤ, t < time n + zero_before : time 0 < 0 + zero_after : 0 < time 1 + on_side : ∀ n : ℤ, point n ∈ Q.side (wall n) + flight : ∀ n : ℤ, + point (n + 1) = point n + (time (n + 1) - time n) • (direction n : ℂ) + inside : ∀ (n : ℤ) (t : ℝ), time n < t → t < time (n + 1) → + point n + (t - time n) • (direction n : ℂ) ∈ Q.table + start_point : z.1 = point 0 + (-time 0) • (direction 0 : ℂ) + start_direction : z.2 = direction 0 + specular : ∀ n : ℤ, + (direction n : ℂ) = reflect (Q.tangent (wall n)) (direction (n - 1) : ℂ) + +/-- The geometric state on a chain, using outgoing velocity at a collision. -/ +def FlightChain.at {Q : Triangle} {z : Phase} (c : FlightChain Q z) (t : ℝ) : Phase := by + classical + exact if h : ∃ n : ℤ, c.time n ≤ t ∧ t < c.time (n + 1) then + let n := Classical.choose h + (c.point n + (t - c.time n) • (c.direction n : ℂ), c.direction n) + else z + +/-- The actual specular flow on complete regular chains. Singular initial +states are assigned their initial state; the theorem must prove these form +a null set. No nonemptiness of the regular set is postulated. -/ +def billiardFlow (Q : Triangle) (t : ℝ) (z : Phase) : Phase := by + classical + exact if h : Nonempty (FlightChain Q z) then (Classical.choice h).at t else z + +/-- Uniform angular probability, parameterized by [0,2π). -/ +def angularMeasure : Measure Circle := + Measure.map Circle.exp + ((ENNReal.ofReal (2 * Real.pi))⁻¹ • volume.restrict (Ico 0 (2 * Real.pi))) + +/-- Exactly normalized area in the open table times uniform angular measure. -/ +def phaseMeasure (Q : Triangle) : Measure Phase := + ((volume Q.table)⁻¹ • volume.restrict Q.table).prod angularMeasure + +/-- The main conclusion, together with the geometric/nonvacuity guarantees +needed by the concrete definition of the actual two-sided billiard. -/ + +def MainConclusion (Q : Triangle) : Prop := + phaseMeasure Q univ = 1 ∧ + (∀ᵐ z ∂phaseMeasure Q, Nonempty (FlightChain Q z)) ∧ + (∀ (z : Phase) (c d : FlightChain Q z), c = d) ∧ + (∀ t : ℝ, MeasurePreserving (billiardFlow Q t) (phaseMeasure Q) (phaseMeasure Q)) ∧ + (∀ s t : ℝ, billiardFlow Q (s + t) =ᵐ[phaseMeasure Q] + (billiardFlow Q s ∘ billiardFlow Q t)) ∧ + (∀ A : Set Phase, MeasurableSet A → + (∀ t : ℝ, phaseMeasure Q (((billiardFlow Q t) ⁻¹' A) ∆ A) = 0) → + phaseMeasure Q A = 0 ∨ phaseMeasure Q A = 1) + +theorem irrational_triangle_billiard (Q : Triangle) (hQ : Q.HasIrrationalAngle) : + MainConclusion Q := by + sorry + +end TriangularBilliards +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IrrationalTriangleBilliard.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TriangularBilliards.irrational_triangle_billiard` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/irrational-triangle-billiard/solution/closure.txt b/tasks/irrational-triangle-billiard/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..56f862c6a145695daa40ded6ea45d5e8e2988b79 --- /dev/null +++ b/tasks/irrational-triangle-billiard/solution/closure.txt @@ -0,0 +1,39 @@ +OAI.Dynamics.TriangleBilliards.AngularMeasure +OAI.Dynamics.TriangleBilliards.CircleFourier +OAI.Dynamics.TriangleBilliards.ClearanceAverages +OAI.Dynamics.TriangleBilliards.ClearanceSmoothing +OAI.Dynamics.TriangleBilliards.CollisionEscape +OAI.Dynamics.TriangleBilliards.CovariantGenerators +OAI.Dynamics.TriangleBilliards.DerivativeAdjoints +OAI.Dynamics.TriangleBilliards.DoubleFlow +OAI.Dynamics.TriangleBilliards.FlightUniqueness +OAI.Dynamics.TriangleBilliards.FourierEnergy +OAI.Dynamics.TriangleBilliards.FourierTails +OAI.Dynamics.TriangleBilliards.Generators +OAI.Dynamics.TriangleBilliards.Geometry +OAI.Dynamics.TriangleBilliards.HilbertFlow +OAI.Dynamics.TriangleBilliards.KernelAdjoints +OAI.Dynamics.TriangleBilliards.KernelBounds +OAI.Dynamics.TriangleBilliards.Koopman +OAI.Dynamics.TriangleBilliards.Localization +OAI.Dynamics.TriangleBilliards.LongTrajectories +OAI.Dynamics.TriangleBilliards.Main +OAI.Dynamics.TriangleBilliards.MeasurableFlow +OAI.Dynamics.TriangleBilliards.MeasurePreservation +OAI.Dynamics.TriangleBilliards.Model +OAI.Dynamics.TriangleBilliards.ReflectedSmoothing +OAI.Dynamics.TriangleBilliards.RegularRays +OAI.Dynamics.TriangleBilliards.RegularizedModes +OAI.Dynamics.TriangleBilliards.SeamEnergy +OAI.Dynamics.TriangleBilliards.SecondDerivatives +OAI.Dynamics.TriangleBilliards.SmoothingApproximation +OAI.Dynamics.TriangleBilliards.SmoothingGenerators +OAI.Dynamics.TriangleBilliards.SmoothingLimits +OAI.Dynamics.TriangleBilliards.SmoothingLp +OAI.Dynamics.TriangleBilliards.SpatialConstancy +OAI.Dynamics.TriangleBilliards.SpatialRigidity +OAI.Dynamics.TriangleBilliards.SpatialSmoothing +OAI.Dynamics.TriangleBilliards.TransverseFlow +OAI.Dynamics.TriangleBilliards.Unfolding +OAI.Dynamics.TriangleBilliards.WeakCompactness +OAI.Dynamics.TriangleBilliards.WeakGenerators diff --git a/tasks/irrational-triangle-billiard/solution/reference.py b/tasks/irrational-triangle-billiard/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/irrational-triangle-billiard/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/irrational-triangle-billiard/solution/solve.sh b/tasks/irrational-triangle-billiard/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ad81440075cd4c856af207b8e401cc2d7f0ba0e1 --- /dev/null +++ b/tasks/irrational-triangle-billiard/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IrrationalTriangleBilliard, i.e. module OAI.Dynamics.TriangleBilliards.Main and the +# 39 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.TriangleBilliards.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IrrationalTriangleBilliard" diff --git a/tasks/irrational-triangle-billiard/task.toml b/tasks/irrational-triangle-billiard/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..65c47a38b55165b28bce296dd7c049846bf0aab9 --- /dev/null +++ b/tasks/irrational-triangle-billiard/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/irrational-triangle-billiard" +version = "1.0.0" +description = "Prove IrrationalTriangleBilliard (openai/math family 150: Weak mixing of irrational triangular billiards) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IrrationalTriangleBilliard.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IrrationalTriangleBilliard" +family = "150" +family_title = "Weak mixing of irrational triangular billiards" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.TriangularBilliards.irrational_triangle_billiard"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.TriangleBilliards.Main" +reference_modules = 39 +reference_lean_bytes = 594085 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 820 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12234 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/irrational-triangle-billiard/tests/Challenge.lean b/tasks/irrational-triangle-billiard/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c6a31c100effc9528ebb602b3c401d2176aee0c8 --- /dev/null +++ b/tasks/irrational-triangle-billiard/tests/Challenge.lean @@ -0,0 +1,126 @@ +import Mathlib + +namespace OAI + +/-! +The phase space is represented in the ambient plane × circle, with measure +supported on the interior of the triangle. Values on side-collision states +at a fixed time are immaterial to the modulo-null-set conclusion. The +trajectories themselves include the collisions and impose specular reflection. +-/ + +open MeasureTheory Set +open scoped ENNReal symmDiff + +noncomputable section + +namespace TriangularBilliards + +/-- Three affinely independent vertices in the Euclidean plane. -/ +structure Triangle where + vertex : Fin 3 → ℂ + nondegenerate : AffineIndependent ℝ vertex + +namespace Triangle + +/-- The open table; the complex plane carries its ordinary real Euclidean metric. -/ +def table (Q : Triangle) : Set ℂ := interior (convexHull ℝ (range Q.vertex)) + +/-- The open side from vertex `i` to the next vertex, indexed cyclically. -/ +def side (Q : Triangle) (i : Fin 3) : Set ℂ := + openSegment ℝ (Q.vertex i) (Q.vertex (i + 1)) + +/-- A tangent vector to side `i`, with no choice of inward or outward normal. -/ +def tangent (Q : Triangle) (i : Fin 3) : ℂ := Q.vertex (i + 1) - Q.vertex i + +/-- Interior angle at vertex `i`. -/ +def angle (Q : Triangle) (i : Fin 3) : ℝ := + InnerProductGeometry.angle (Q.vertex (i + 1) - Q.vertex i) + (Q.vertex (i + 2) - Q.vertex i) + +def HasIrrationalAngle (Q : Triangle) : Prop := + ∃ i : Fin 3, Irrational (Q.angle i / Real.pi) + +end Triangle + +/-- Reflection in the real line spanned by the nonzero tangent `e`. +In coordinates with `e` real this is complex conjugation, preserving the +tangential component and reversing the normal component. -/ +def reflect (e v : ℂ) : ℂ := (e / star e) * star v + +instance circleMeasurableSpace : MeasurableSpace Circle := borel Circle + +instance circleBorelSpace : BorelSpace Circle := ⟨rfl⟩ + +abbrev Phase := ℂ × Circle + +/-- A complete nonsingular billiard trajectory, indexed by its collisions. +Flight zero contains the initial time strictly. Both ends of the collision +time sequence are unbounded; collisions occur only in open sides, never +vertices. These are geometric conditions, not ergodicity/analytic assumptions. -/ +structure FlightChain (Q : Triangle) (z : Phase) where + time : ℤ → ℝ + point : ℤ → ℂ + direction : ℤ → Circle + wall : ℤ → Fin 3 + increasing : StrictMono time + unbounded_below : ∀ t : ℝ, ∃ n : ℤ, time n < t + unbounded_above : ∀ t : ℝ, ∃ n : ℤ, t < time n + zero_before : time 0 < 0 + zero_after : 0 < time 1 + on_side : ∀ n : ℤ, point n ∈ Q.side (wall n) + flight : ∀ n : ℤ, + point (n + 1) = point n + (time (n + 1) - time n) • (direction n : ℂ) + inside : ∀ (n : ℤ) (t : ℝ), time n < t → t < time (n + 1) → + point n + (t - time n) • (direction n : ℂ) ∈ Q.table + start_point : z.1 = point 0 + (-time 0) • (direction 0 : ℂ) + start_direction : z.2 = direction 0 + specular : ∀ n : ℤ, + (direction n : ℂ) = reflect (Q.tangent (wall n)) (direction (n - 1) : ℂ) + +/-- The geometric state on a chain, using outgoing velocity at a collision. -/ +def FlightChain.at {Q : Triangle} {z : Phase} (c : FlightChain Q z) (t : ℝ) : Phase := by + classical + exact if h : ∃ n : ℤ, c.time n ≤ t ∧ t < c.time (n + 1) then + let n := Classical.choose h + (c.point n + (t - c.time n) • (c.direction n : ℂ), c.direction n) + else z + +/-- The actual specular flow on complete regular chains. Singular initial +states are assigned their initial state; the theorem must prove these form +a null set. No nonemptiness of the regular set is postulated. -/ +def billiardFlow (Q : Triangle) (t : ℝ) (z : Phase) : Phase := by + classical + exact if h : Nonempty (FlightChain Q z) then (Classical.choice h).at t else z + +/-- Uniform angular probability, parameterized by [0,2π). -/ +def angularMeasure : Measure Circle := + Measure.map Circle.exp + ((ENNReal.ofReal (2 * Real.pi))⁻¹ • volume.restrict (Ico 0 (2 * Real.pi))) + +/-- Exactly normalized area in the open table times uniform angular measure. -/ +def phaseMeasure (Q : Triangle) : Measure Phase := + ((volume Q.table)⁻¹ • volume.restrict Q.table).prod angularMeasure + +/-- The main conclusion, together with the geometric/nonvacuity guarantees +needed by the concrete definition of the actual two-sided billiard. -/ + +def MainConclusion (Q : Triangle) : Prop := + phaseMeasure Q univ = 1 ∧ + (∀ᵐ z ∂phaseMeasure Q, Nonempty (FlightChain Q z)) ∧ + (∀ (z : Phase) (c d : FlightChain Q z), c = d) ∧ + (∀ t : ℝ, MeasurePreserving (billiardFlow Q t) (phaseMeasure Q) (phaseMeasure Q)) ∧ + (∀ s t : ℝ, billiardFlow Q (s + t) =ᵐ[phaseMeasure Q] + (billiardFlow Q s ∘ billiardFlow Q t)) ∧ + (∀ A : Set Phase, MeasurableSet A → + (∀ t : ℝ, phaseMeasure Q (((billiardFlow Q t) ⁻¹' A) ∆ A) = 0) → + phaseMeasure Q A = 0 ∨ phaseMeasure Q A = 1) + +theorem irrational_triangle_billiard (Q : Triangle) (hQ : Q.HasIrrationalAngle) : + MainConclusion Q := by + sorry + +end TriangularBilliards +end + +end OAI diff --git a/tasks/irrational-triangle-billiard/tests/grade.py b/tasks/irrational-triangle-billiard/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/irrational-triangle-billiard/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/irrational-triangle-billiard/tests/task.json b/tasks/irrational-triangle-billiard/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..67426da809df4428caaad2d3cf5a572ca2544ab4 --- /dev/null +++ b/tasks/irrational-triangle-billiard/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "IrrationalTriangleBilliard", + "comparator": { + "theorem_names": [ + "OAI.TriangularBilliards.irrational_triangle_billiard" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11334 +} \ No newline at end of file diff --git a/tasks/irrational-triangle-billiard/tests/test.sh b/tasks/irrational-triangle-billiard/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/irrational-triangle-billiard/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ising-finiteness/environment/Dockerfile b/tasks/ising-finiteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ising-finiteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ising-finiteness/environment/fetch_mathlib.sh b/tasks/ising-finiteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ising-finiteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ising-finiteness/environment/lake-manifest.json b/tasks/ising-finiteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ising-finiteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ising-finiteness/environment/lakefile.lean b/tasks/ising-finiteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ising-finiteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ising-finiteness/environment/lean_setup.sh b/tasks/ising-finiteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ising-finiteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ising-finiteness/environment/pack_submission.py b/tasks/ising-finiteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ising-finiteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ising-finiteness/instruction.md b/tasks/ising-finiteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac060f6fd1601fd6671772988d35dbfd32e6c7fb --- /dev/null +++ b/tasks/ising-finiteness/instruction.md @@ -0,0 +1,145 @@ +# openai/math challenge `IsingFiniteness` (family 222) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 222 of the release, *Perceptron free energies and microscopic jamming* +(Probability and statistical mechanics). The family as a whole: Determines finite-temperature variational free energies for Gaussian Ising perceptrons with bounded Borel log-potentials and Gaussian spherical perceptrons with bounded continuous potentials, at every positive pattern density. A spherical extension treats bi-orthogonally invariant disorder with compact limiting singular-value distributions and no outliers. At margin $-1$, the quadratic-penalty spherical model has a sharp feasibility threshold and limiting gap and force laws, with system size, zero temperature, and critical density taken in that order. + +The challenge is `IsingFiniteness`, also at `/opt/openai-math/challenges/IsingFiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped BigOperators Topology ENNReal + +noncomputable section +namespace IsingPerceptron + +def gaussianTransform (s d : ℝ) (U : ℝ → ℝ) (x : ℝ) : ℝ := + if d = 0 then ∫ z, U (x + Real.sqrt s * z) ∂gaussianReal 0 1 + else (Real.log (∫ z, Real.exp (d * U (x + Real.sqrt s * z)) + ∂gaussianReal 0 1)) / d + +structure Partition where + levels : ℕ + positive : 0 < levels + cut : Fin (levels + 1) → ℝ + ordered : StrictMono cut + first : cut ⟨0, Nat.zero_lt_succ levels⟩ = 0 + last : cut ⟨levels, Nat.lt_succ_self levels⟩ = 1 + +structure FieldStep where + partition : Partition + value : Fin partition.levels → ℝ + nonneg : ∀ i, 0 ≤ value i + ordered : Monotone value + + +def stepAt (h : FieldStep) (i : ℕ) : ℝ := + if hi : i < h.partition.levels then h.value ⟨i, hi⟩ else 0 + + + +def stepFunction (h : FieldStep) (u : ℝ) : ℝ := + ∑ i : Fin h.partition.levels, + if h.partition.cut i.castSucc < u ∧ u < h.partition.cut i.succ then h.value i else 0 + + +def fieldRecursion (h : FieldStep) : ℝ := + let k := h.partition.levels + let increments := List.ofFn (fun i : Fin k => + (stepAt h i - (if i.val = 0 then 0 else stepAt h (i.val - 1)), + h.partition.cut i.castSucc)) + increments.foldr (fun sd U => gaussianTransform sd.1 sd.2 U) + (fun x => Real.log (Real.cosh x) - stepAt h (k - 1) / 2) 0 + +def pathMeasure : Measure ℝ := volume.restrict (Set.Ioo (0 : ℝ) 1) + + +structure OverlapPath where + val : ℝ →ₘ[pathMeasure] ℝ + admissible : ∃ q : ℝ → ℝ, + (q =ᵐ[pathMeasure] val) ∧ MonotoneOn q (Set.Ioo 0 1) ∧ + ∀ u ∈ Set.Ioo (0 : ℝ) 1, q u ∈ Set.Icc (0 : ℝ) 1 + + +def cellAverage (q : OverlapPath) (k i : ℕ) : ℝ := + (k : ℝ) * ∫ u in Set.Ioo ((i : ℝ) / k) (((i : ℝ) + 1) / k), + q.val u ∂pathMeasure + + + +def uniformPattern (f : ℝ → ℝ) (q : OverlapPath) (n : ℕ) : ℝ := + let k := n + 1 + let levelVal := fun i => if i < k then cellAverage q k i else 1 + let increments := List.ofFn (fun i : Fin (k + 1) => + (levelVal i - (if i.val = 0 then 0 else levelVal (i.val - 1)), (i : ℝ) / k)) + increments.foldr (fun sd U => gaussianTransform sd.1 sd.2 U) f 0 + + + +def patternFunctional (f : ℝ → ℝ) (q : OverlapPath) : ℝ := + Filter.limUnder atTop (uniformPattern f q) + + + +def isingEntropy (q : OverlapPath) : EReal := + ⨆ h : FieldStep, + ((fieldRecursion h + (∫ u, stepFunction h u * q.val u ∂pathMeasure) / 2 : ℝ) : EReal) + +def variationalValue (α : ℝ) (f : ℝ → ℝ) : EReal := + ⨅ q : OverlapPath, (α * patternFunctional f q : ℝ) + isingEntropy q + +theorem variationalValue_real_of_continuous {α : ℝ} (hα : 0 ≤ α) + {f : ℝ → ℝ} (hf : Continuous f) (hbounded : ∃ K : ℝ, ∀ x, |f x| ≤ K) : + ∃ p : ℝ, variationalValue α f = (p : EReal) := by + sorry + +end IsingPerceptron +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IsingFiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.IsingPerceptron.variationalValue_real_of_continuous` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ising-finiteness/solution/closure.txt b/tasks/ising-finiteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cce3a1a7f0692c3946be3e6c8d185509269444b8 --- /dev/null +++ b/tasks/ising-finiteness/solution/closure.txt @@ -0,0 +1,45 @@ +OAI.Probability.IsingPerceptron.ArrayGeometry +OAI.Probability.IsingPerceptron.ArraySynchronization +OAI.Probability.IsingPerceptron.BoundedTiltAverage +OAI.Probability.IsingPerceptron.CascadeFreshMoments +OAI.Probability.IsingPerceptron.CascadePair +OAI.Probability.IsingPerceptron.ChildLabel +OAI.Probability.IsingPerceptron.ContactFaces +OAI.Probability.IsingPerceptron.ConvexDerivativeFluctuation +OAI.Probability.IsingPerceptron.CountableMonomialGG +OAI.Probability.IsingPerceptron.EnergyShift +OAI.Probability.IsingPerceptron.EnrichedCGF +OAI.Probability.IsingPerceptron.EnrichedFieldCap +OAI.Probability.IsingPerceptron.EnrichedGGFinite +OAI.Probability.IsingPerceptron.FieldChain +OAI.Probability.IsingPerceptron.FiniteGaussianVariation +OAI.Probability.IsingPerceptron.GaussianFamilyGenerator +OAI.Probability.IsingPerceptron.GaussianIntegration +OAI.Probability.IsingPerceptron.GaussianMomentTest +OAI.Probability.IsingPerceptron.JointGGClosure +OAI.Probability.IsingPerceptron.JointShapes +OAI.Probability.IsingPerceptron.LabeledSampling +OAI.Probability.IsingPerceptron.LintegralGammaKernel +OAI.Probability.IsingPerceptron.MapWithDensityEquiv +OAI.Probability.IsingPerceptron.MarkedPartitionNumerator +OAI.Probability.IsingPerceptron.MemLpOfAbsBound +OAI.Probability.IsingPerceptron.MomentLogLimit +OAI.Probability.IsingPerceptron.MonomialGgAtMinimum +OAI.Probability.IsingPerceptron.NamespaceSplit +OAI.Probability.IsingPerceptron.NextRowJoin +OAI.Probability.IsingPerceptron.NoiseGibbsRegular +OAI.Probability.IsingPerceptron.NoiseTreeKeep +OAI.Probability.IsingPerceptron.NormalizedRestrictionPi +OAI.Probability.IsingPerceptron.OrderedQuantile +OAI.Probability.IsingPerceptron.PartitionPowLe +OAI.Probability.IsingPerceptron.PoissonCloud +OAI.Probability.IsingPerceptron.ReplicaEnergyCovarianceBound +OAI.Probability.IsingPerceptron.RetainedDisplacement +OAI.Probability.IsingPerceptron.SamplingIndependent +OAI.Probability.IsingPerceptron.TiltedLabelLaw +OAI.Probability.IsingPerceptron.TimeIncrement +OAI.Probability.IsingPerceptron.VarianceDerivative +OAI.Probability.IsingPerceptron.VarianceOfConditionalCenterBound +OAI.Probability.IsingPerceptron.VariationalDefs +OAI.Probability.IsingPerceptron.VariationalFiniteness +OAI.Probability.IsingPerceptron.WeightedPartitionNumeratorIncrement diff --git a/tasks/ising-finiteness/solution/reference.py b/tasks/ising-finiteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ising-finiteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ising-finiteness/solution/solve.sh b/tasks/ising-finiteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..185a9516a10c3173c08dcc023933ebf3de4809c8 --- /dev/null +++ b/tasks/ising-finiteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IsingFiniteness, i.e. module OAI.Probability.IsingPerceptron.VariationalFiniteness and the +# 45 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.IsingPerceptron.VariationalFiniteness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IsingFiniteness" diff --git a/tasks/ising-finiteness/task.toml b/tasks/ising-finiteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dbff606b86d94cbc015e70ad7c41d055d76f8036 --- /dev/null +++ b/tasks/ising-finiteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ising-finiteness" +version = "1.0.0" +description = "Prove IsingFiniteness (openai/math family 222: Perceptron free energies and microscopic jamming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IsingFiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IsingFiniteness" +family = "222" +family_title = "Perceptron free energies and microscopic jamming" +subject = "Probability and statistical mechanics" +theorems = ["OAI.IsingPerceptron.variationalValue_real_of_continuous"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.IsingPerceptron.VariationalFiniteness" +reference_modules = 45 +reference_lean_bytes = 1494396 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 958 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13044 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ising-finiteness/tests/Challenge.lean b/tasks/ising-finiteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0374f095bb59fa18877420d08d5696c2c9cb256a --- /dev/null +++ b/tasks/ising-finiteness/tests/Challenge.lean @@ -0,0 +1,94 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped BigOperators Topology ENNReal + +noncomputable section +namespace IsingPerceptron + +def gaussianTransform (s d : ℝ) (U : ℝ → ℝ) (x : ℝ) : ℝ := + if d = 0 then ∫ z, U (x + Real.sqrt s * z) ∂gaussianReal 0 1 + else (Real.log (∫ z, Real.exp (d * U (x + Real.sqrt s * z)) + ∂gaussianReal 0 1)) / d + +structure Partition where + levels : ℕ + positive : 0 < levels + cut : Fin (levels + 1) → ℝ + ordered : StrictMono cut + first : cut ⟨0, Nat.zero_lt_succ levels⟩ = 0 + last : cut ⟨levels, Nat.lt_succ_self levels⟩ = 1 + +structure FieldStep where + partition : Partition + value : Fin partition.levels → ℝ + nonneg : ∀ i, 0 ≤ value i + ordered : Monotone value + + +def stepAt (h : FieldStep) (i : ℕ) : ℝ := + if hi : i < h.partition.levels then h.value ⟨i, hi⟩ else 0 + + + +def stepFunction (h : FieldStep) (u : ℝ) : ℝ := + ∑ i : Fin h.partition.levels, + if h.partition.cut i.castSucc < u ∧ u < h.partition.cut i.succ then h.value i else 0 + + +def fieldRecursion (h : FieldStep) : ℝ := + let k := h.partition.levels + let increments := List.ofFn (fun i : Fin k => + (stepAt h i - (if i.val = 0 then 0 else stepAt h (i.val - 1)), + h.partition.cut i.castSucc)) + increments.foldr (fun sd U => gaussianTransform sd.1 sd.2 U) + (fun x => Real.log (Real.cosh x) - stepAt h (k - 1) / 2) 0 + +def pathMeasure : Measure ℝ := volume.restrict (Set.Ioo (0 : ℝ) 1) + + +structure OverlapPath where + val : ℝ →ₘ[pathMeasure] ℝ + admissible : ∃ q : ℝ → ℝ, + (q =ᵐ[pathMeasure] val) ∧ MonotoneOn q (Set.Ioo 0 1) ∧ + ∀ u ∈ Set.Ioo (0 : ℝ) 1, q u ∈ Set.Icc (0 : ℝ) 1 + + +def cellAverage (q : OverlapPath) (k i : ℕ) : ℝ := + (k : ℝ) * ∫ u in Set.Ioo ((i : ℝ) / k) (((i : ℝ) + 1) / k), + q.val u ∂pathMeasure + + + +def uniformPattern (f : ℝ → ℝ) (q : OverlapPath) (n : ℕ) : ℝ := + let k := n + 1 + let levelVal := fun i => if i < k then cellAverage q k i else 1 + let increments := List.ofFn (fun i : Fin (k + 1) => + (levelVal i - (if i.val = 0 then 0 else levelVal (i.val - 1)), (i : ℝ) / k)) + increments.foldr (fun sd U => gaussianTransform sd.1 sd.2 U) f 0 + + + +def patternFunctional (f : ℝ → ℝ) (q : OverlapPath) : ℝ := + Filter.limUnder atTop (uniformPattern f q) + + + +def isingEntropy (q : OverlapPath) : EReal := + ⨆ h : FieldStep, + ((fieldRecursion h + (∫ u, stepFunction h u * q.val u ∂pathMeasure) / 2 : ℝ) : EReal) + +def variationalValue (α : ℝ) (f : ℝ → ℝ) : EReal := + ⨅ q : OverlapPath, (α * patternFunctional f q : ℝ) + isingEntropy q + +theorem variationalValue_real_of_continuous {α : ℝ} (hα : 0 ≤ α) + {f : ℝ → ℝ} (hf : Continuous f) (hbounded : ∃ K : ℝ, ∀ x, |f x| ≤ K) : + ∃ p : ℝ, variationalValue α f = (p : EReal) := by + sorry + +end IsingPerceptron +end + +end OAI diff --git a/tasks/ising-finiteness/tests/grade.py b/tasks/ising-finiteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ising-finiteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ising-finiteness/tests/task.json b/tasks/ising-finiteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e36e7412b633ac78f93f20c0dca26c6acde3fc68 --- /dev/null +++ b/tasks/ising-finiteness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "IsingFiniteness", + "comparator": { + "theorem_names": [ + "OAI.IsingPerceptron.variationalValue_real_of_continuous" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12144 +} \ No newline at end of file diff --git a/tasks/ising-finiteness/tests/test.sh b/tasks/ising-finiteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ising-finiteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/isometric-immersion/environment/Dockerfile b/tasks/isometric-immersion/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/isometric-immersion/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/isometric-immersion/environment/fetch_mathlib.sh b/tasks/isometric-immersion/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/isometric-immersion/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/isometric-immersion/environment/lake-manifest.json b/tasks/isometric-immersion/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/isometric-immersion/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/isometric-immersion/environment/lakefile.lean b/tasks/isometric-immersion/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/isometric-immersion/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/isometric-immersion/environment/lean_setup.sh b/tasks/isometric-immersion/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/isometric-immersion/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/isometric-immersion/environment/pack_submission.py b/tasks/isometric-immersion/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/isometric-immersion/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/isometric-immersion/instruction.md b/tasks/isometric-immersion/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..627d8915be1d3b9e03df4968532ca845cee3fc1e --- /dev/null +++ b/tasks/isometric-immersion/instruction.md @@ -0,0 +1,113 @@ +# openai/math challenge `IsometricImmersion` (family 334) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 334 of the release, *A smooth surface metric with no local immersion in $\mathbb R^3$* +(Differential geometry). The family as a whole: Constructs a smooth positive-definite metric on $(-1,1)^2$ for which no neighborhood of the origin admits a smooth isometric immersion into $\mathbb R^3$. This answers the unrestricted smooth local isometric realization problem for surfaces negatively, even after shrinking the neighborhood. + +The challenge is `IsometricImmersion`, also at `/opt/openai-math/challenges/IsometricImmersion.lean`: + +```lean +import Mathlib.Analysis.InnerProductSpace.Calculus +import Mathlib.LinearAlgebra.Matrix.PosDef +import Mathlib.LinearAlgebra.Matrix.NonsingularInverse +import Mathlib.Geometry.Manifold.ContMDiff.NormedSpace +import Mathlib.Geometry.Manifold.MFDeriv.FDeriv + +namespace OAI + +noncomputable section +open Set TopologicalSpace +open scoped ContDiff Topology Manifold Matrix + +namespace SmoothLocal.Geometry + +abbrev Coord := Fin 2 → ℝ + +abbrev Ambient := EuclideanSpace ℝ (Fin 3) + +def square : Set Coord := {p | ∀ i, p i ∈ Set.Ioo (-1 : ℝ) 1} + +def LocalSmoothPositive (U : Opens Coord) + (g : U → Matrix (Fin 2) (Fin 2) ℝ) : Prop := + (∀ i j, ContMDiff 𝓘(ℝ, Coord) 𝓘(ℝ, ℝ) ∞ (fun p => g p i j)) ∧ + ∀ p, (g p).PosDef + +end SmoothLocal.Geometry + +namespace SmoothLocal.ODE +open SmoothLocal.Geometry + +theorem coordinate_square_isOpen : IsOpen square := by + have heq : square = ⋂ i : Fin 2, + (fun p : Coord => p i) ⁻¹' Ioo (-1 : ℝ) 1 := by + ext p + simp [square] + rw [heq] + exact isOpen_iInter_of_finite (fun i => isOpen_Ioo.preimage (continuous_apply i)) + +end SmoothLocal.ODE + +namespace SmoothLocal.Geometry + +def coordinateSquareOpen : Opens Coord := + ⟨square, SmoothLocal.ODE.coordinate_square_isOpen⟩ + +theorem exists_local_metric_without_local_immersion : + ∃ g : coordinateSquareOpen → Matrix (Fin 2) (Fin 2) ℝ, + LocalSmoothPositive coordinateSquareOpen g ∧ + ∀ U : Opens Coord, ∀ hUS : (U : Set Coord) ⊆ square, + (0 : Coord) ∈ U → ∀ F : U → Ambient, + ¬ (ContMDiff 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) ∞ F ∧ + ∀ p : U, ∀ v w : Coord, + (inner ℝ : Ambient → Ambient → ℝ) (mfderiv 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) F p v) + (mfderiv 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) F p w) = + v ⬝ᵥ (g ⟨p, hUS p.property⟩ *ᵥ w)) := by + sorry + +end SmoothLocal.Geometry + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/IsometricImmersion.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SmoothLocal.Geometry.exists_local_metric_without_local_immersion` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/isometric-immersion/solution/closure.txt b/tasks/isometric-immersion/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b60a6738c1800aaae14fcb5c8da999fa27d523f --- /dev/null +++ b/tasks/isometric-immersion/solution/closure.txt @@ -0,0 +1,446 @@ +OAI.Geometry.IsometricImmersion.Assembly.AccumulatingDisks +OAI.Geometry.IsometricImmersion.Assembly.AssembledImmersionHeight +OAI.Geometry.IsometricImmersion.Assembly.AssemblyProfiles +OAI.Geometry.IsometricImmersion.Assembly.DiagonalAmplitudes +OAI.Geometry.IsometricImmersion.Assembly.DisjointTensorAssembly +OAI.Geometry.IsometricImmersion.Assembly.EnumeratedPatchTensors +OAI.Geometry.IsometricImmersion.Assembly.FinalMetric +OAI.Geometry.IsometricImmersion.Assembly.FlatPatchSum +OAI.Geometry.IsometricImmersion.Assembly.InitialAssemblyMetric +OAI.Geometry.IsometricImmersion.Assembly.SelectedPatchObstructions +OAI.Geometry.IsometricImmersion.Assembly.SupportedMetricJets +OAI.Geometry.IsometricImmersion.Assembly.SupportedNeighborhoods +OAI.Geometry.IsometricImmersion.Assembly.SupportedPerturbations +OAI.Geometry.IsometricImmersion.Assembly.SupportedSmoothComplete +OAI.Geometry.IsometricImmersion.Assembly.TensorSeriesLocality +OAI.Geometry.IsometricImmersion.Calculus.AffineCovariantHessian +OAI.Geometry.IsometricImmersion.Calculus.AffineHessian +OAI.Geometry.IsometricImmersion.Calculus.AffineTensorJetBounds +OAI.Geometry.IsometricImmersion.Calculus.BoundedClassInitialJet +OAI.Geometry.IsometricImmersion.Calculus.ClosedSquareJetBounds +OAI.Geometry.IsometricImmersion.Calculus.CoordinateDerivatives +OAI.Geometry.IsometricImmersion.Calculus.CoordinateJetBounds +OAI.Geometry.IsometricImmersion.Calculus.CoordinateJetNorm +OAI.Geometry.IsometricImmersion.Calculus.CoordinateJetReverseNorm +OAI.Geometry.IsometricImmersion.Calculus.ExtremumHessian +OAI.Geometry.IsometricImmersion.Calculus.FinitePrimitive +OAI.Geometry.IsometricImmersion.Calculus.FiniteUpperMetricJets +OAI.Geometry.IsometricImmersion.Calculus.HessianCommutator +OAI.Geometry.IsometricImmersion.Calculus.HessianJetBounds +OAI.Geometry.IsometricImmersion.Calculus.HessianQuotientLowBounds +OAI.Geometry.IsometricImmersion.Calculus.HessianTransport +OAI.Geometry.IsometricImmersion.Calculus.HorizontalJetCalculus +OAI.Geometry.IsometricImmersion.Calculus.JointDerivative +OAI.Geometry.IsometricImmersion.Calculus.MetricInverseJetBounds +OAI.Geometry.IsometricImmersion.Calculus.MetricTwoJet +OAI.Geometry.IsometricImmersion.Calculus.MixedCoordinateCalculus +OAI.Geometry.IsometricImmersion.Calculus.MovingFirstJetBase +OAI.Geometry.IsometricImmersion.Calculus.MovingIntervalCalculus +OAI.Geometry.IsometricImmersion.Calculus.NormalDerivative +OAI.Geometry.IsometricImmersion.Calculus.NormedCoordinateCalculus +OAI.Geometry.IsometricImmersion.Calculus.QuotientCalculus +OAI.Geometry.IsometricImmersion.Calculus.QuotientLowBounds +OAI.Geometry.IsometricImmersion.Calculus.QuotientLowRecurrence +OAI.Geometry.IsometricImmersion.Calculus.SecondJetExtraction +OAI.Geometry.IsometricImmersion.Calculus.ShearHeightJets +OAI.Geometry.IsometricImmersion.Calculus.ShearMetricFullJets +OAI.Geometry.IsometricImmersion.Calculus.ShearMetricJets +OAI.Geometry.IsometricImmersion.Calculus.ShearedMetricFiniteJets +OAI.Geometry.IsometricImmersion.Calculus.SmoothCurry +OAI.Geometry.IsometricImmersion.Calculus.SmoothMetricJet +OAI.Geometry.IsometricImmersion.Calculus.StateJetSegment +OAI.Geometry.IsometricImmersion.Calculus.VerticalSliceJets +OAI.Geometry.IsometricImmersion.Caps.ActualClassTwoSidedCauchy +OAI.Geometry.IsometricImmersion.Caps.ActualFiniteCapMetricBounds +OAI.Geometry.IsometricImmersion.Caps.ActualFiniteLowerCutBounds +OAI.Geometry.IsometricImmersion.Caps.ActualLowerCutImage +OAI.Geometry.IsometricImmersion.Caps.ActualOffPulseCauchy +OAI.Geometry.IsometricImmersion.Caps.ActualPulseCapSeparation +OAI.Geometry.IsometricImmersion.Caps.ActualUpperOffPulseCauchy +OAI.Geometry.IsometricImmersion.Caps.AllOrderCapEstimate +OAI.Geometry.IsometricImmersion.Caps.AllOrderPhysicalCap +OAI.Geometry.IsometricImmersion.Caps.BoundedClassCapData +OAI.Geometry.IsometricImmersion.Caps.BoundedClassCapRadius +OAI.Geometry.IsometricImmersion.Caps.BoundedClassReflection +OAI.Geometry.IsometricImmersion.Caps.BoundedPatchCauchy +OAI.Geometry.IsometricImmersion.Caps.C8ActualCapEstimate +OAI.Geometry.IsometricImmersion.Caps.CapAreaFormula +OAI.Geometry.IsometricImmersion.Caps.CapCutoffGeometry +OAI.Geometry.IsometricImmersion.Caps.CapCutoffRectangle +OAI.Geometry.IsometricImmersion.Caps.CapDensityBounds +OAI.Geometry.IsometricImmersion.Caps.CapEllipticOverlap +OAI.Geometry.IsometricImmersion.Caps.CapFlow +OAI.Geometry.IsometricImmersion.Caps.CapFlowCoordinateJets +OAI.Geometry.IsometricImmersion.Caps.CapFlowJetBounds +OAI.Geometry.IsometricImmersion.Caps.CapFlowUniqueness +OAI.Geometry.IsometricImmersion.Caps.CapGradientTransport +OAI.Geometry.IsometricImmersion.Caps.CapInductionData +OAI.Geometry.IsometricImmersion.Caps.CapInteriorEnergy +OAI.Geometry.IsometricImmersion.Caps.CapJacobian +OAI.Geometry.IsometricImmersion.Caps.CapL2Basics +OAI.Geometry.IsometricImmersion.Caps.CapOverlapCosts +OAI.Geometry.IsometricImmersion.Caps.CapReciprocalBounds +OAI.Geometry.IsometricImmersion.Caps.CapReflectionCalculus +OAI.Geometry.IsometricImmersion.Caps.CapReflectionGeometry +OAI.Geometry.IsometricImmersion.Caps.CauchyReflection +OAI.Geometry.IsometricImmersion.Caps.ConstructedCapArea +OAI.Geometry.IsometricImmersion.Caps.ConstructedCapGradient +OAI.Geometry.IsometricImmersion.Caps.EllipticAbsorption +OAI.Geometry.IsometricImmersion.Caps.EllipticApplication +OAI.Geometry.IsometricImmersion.Caps.EllipticC1 +OAI.Geometry.IsometricImmersion.Caps.EllipticCutoff +OAI.Geometry.IsometricImmersion.Caps.EllipticCutoffEdge +OAI.Geometry.IsometricImmersion.Caps.EllipticEnergy +OAI.Geometry.IsometricImmersion.Caps.EllipticGradient +OAI.Geometry.IsometricImmersion.Caps.EllipticRatio +OAI.Geometry.IsometricImmersion.Caps.EnergyCauchySchwarz +OAI.Geometry.IsometricImmersion.Caps.FiniteCapInduction +OAI.Geometry.IsometricImmersion.Caps.FiniteCapPointwise +OAI.Geometry.IsometricImmersion.Caps.FixedMetricLowerCap +OAI.Geometry.IsometricImmersion.Caps.FixedRadiusOffPulseCauchy +OAI.Geometry.IsometricImmersion.Caps.HeightCapLowData +OAI.Geometry.IsometricImmersion.Caps.IntegratedCapOverlap +OAI.Geometry.IsometricImmersion.Caps.LowerCapInduction +OAI.Geometry.IsometricImmersion.Caps.NestedCapRectangles +OAI.Geometry.IsometricImmersion.Caps.OpenCapFlowUniqueness +OAI.Geometry.IsometricImmersion.Caps.PhysicalCapTransport +OAI.Geometry.IsometricImmersion.Caps.PulseCapSeparation +OAI.Geometry.IsometricImmersion.Caps.PulseReflection +OAI.Geometry.IsometricImmersion.Caps.QPointwiseCauchyJets +OAI.Geometry.IsometricImmersion.Caps.ReflectedActualCapFlow +OAI.Geometry.IsometricImmersion.Caps.UniformOriginalDataCapEstimate +OAI.Geometry.IsometricImmersion.Caps.UpperCapMetricJets +OAI.Geometry.IsometricImmersion.Caps.UpperCapWords +OAI.Geometry.IsometricImmersion.Caps.VaryingCapInduction +OAI.Geometry.IsometricImmersion.Caps.VaryingMetricLowerCap +OAI.Geometry.IsometricImmersion.Caps.VaryingMetricUpperCap +OAI.Geometry.IsometricImmersion.Comparison.ActualClassComparisonGradient +OAI.Geometry.IsometricImmersion.Comparison.ActualClassComparisonMoment +OAI.Geometry.IsometricImmersion.Comparison.ActualClassComparisonSourceBound +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonCoefficientData +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonEnergy +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonEquation +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonGradient +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonSource +OAI.Geometry.IsometricImmersion.Comparison.ActualComparisonTestCost +OAI.Geometry.IsometricImmersion.Comparison.ActualUniformComparisonGradient +OAI.Geometry.IsometricImmersion.Comparison.BoundedClassApproximation +OAI.Geometry.IsometricImmersion.Comparison.ClosureMetricApproximation +OAI.Geometry.IsometricImmersion.Comparison.ComparisonCoefficientBounds +OAI.Geometry.IsometricImmersion.Comparison.ComparisonCoefficientDerivative +OAI.Geometry.IsometricImmersion.Comparison.ComparisonCoefficientSmooth +OAI.Geometry.IsometricImmersion.Comparison.ComparisonEnergyScaling +OAI.Geometry.IsometricImmersion.Comparison.ComparisonGradientSlice +OAI.Geometry.IsometricImmersion.Comparison.ComparisonPulseGeometry +OAI.Geometry.IsometricImmersion.Comparison.ComparisonSourceBounds +OAI.Geometry.IsometricImmersion.Comparison.ComparisonUpperVelocity +OAI.Geometry.IsometricImmersion.Comparison.CurvatureComparisonControl +OAI.Geometry.IsometricImmersion.Comparison.CurvatureFullJetComparison +OAI.Geometry.IsometricImmersion.Comparison.FiniteApproximationJets +OAI.Geometry.IsometricImmersion.Comparison.OriginalClassComparisonWithLow +OAI.Geometry.IsometricImmersion.Comparison.PulseClosureApproximation +OAI.Geometry.IsometricImmersion.Comparison.QApproximationMargins +OAI.Geometry.IsometricImmersion.Comparison.QFirstJetComparison +OAI.Geometry.IsometricImmersion.Comparison.QMetricApproximationInputs +OAI.Geometry.IsometricImmersion.Comparison.ShearFirstJetComparison +OAI.Geometry.IsometricImmersion.CoordinateMain +OAI.Geometry.IsometricImmersion.Coordinates.ActualCentralShearMargins +OAI.Geometry.IsometricImmersion.Coordinates.ActualFiniteShearedCutBounds +OAI.Geometry.IsometricImmersion.Coordinates.ActualPatchQRectangle +OAI.Geometry.IsometricImmersion.Coordinates.ActualReferenceSegment +OAI.Geometry.IsometricImmersion.Coordinates.ActualShearHyperbolicity +OAI.Geometry.IsometricImmersion.Coordinates.AffinePatchSquares +OAI.Geometry.IsometricImmersion.Coordinates.AffinePullback +OAI.Geometry.IsometricImmersion.Coordinates.AffinePushforward +OAI.Geometry.IsometricImmersion.Coordinates.BoundedClassSlabSmallness +OAI.Geometry.IsometricImmersion.Coordinates.BoundedPatchSlabGeometry +OAI.Geometry.IsometricImmersion.Coordinates.CoordinateFirstBounds +OAI.Geometry.IsometricImmersion.Coordinates.CoordinateSwap +OAI.Geometry.IsometricImmersion.Coordinates.ExteriorAnnuli +OAI.Geometry.IsometricImmersion.Coordinates.ExteriorCenterNets +OAI.Geometry.IsometricImmersion.Coordinates.OrientationNet +OAI.Geometry.IsometricImmersion.Coordinates.OrientedCenterNets +OAI.Geometry.IsometricImmersion.Coordinates.OrientedPatchSquares +OAI.Geometry.IsometricImmersion.Coordinates.PatchAddressModel +OAI.Geometry.IsometricImmersion.Coordinates.PatchGeometry +OAI.Geometry.IsometricImmersion.Coordinates.RoundDisk +OAI.Geometry.IsometricImmersion.Coordinates.ShearSpeedBounds +OAI.Geometry.IsometricImmersion.Curvature.AffineConnection +OAI.Geometry.IsometricImmersion.Curvature.AffineCurvature +OAI.Geometry.IsometricImmersion.Curvature.CurvatureFirstBounds +OAI.Geometry.IsometricImmersion.Curvature.CurvatureLowerTube +OAI.Geometry.IsometricImmersion.Curvature.CurvatureParameter +OAI.Geometry.IsometricImmersion.Curvature.CurvatureParameterJets +OAI.Geometry.IsometricImmersion.Curvature.DiskCurvatureProfiles +OAI.Geometry.IsometricImmersion.Curvature.GaussConnection +OAI.Geometry.IsometricImmersion.Curvature.GaussEquation +OAI.Geometry.IsometricImmersion.Curvature.GaussFormula +OAI.Geometry.IsometricImmersion.Curvature.InitialCurvature +OAI.Geometry.IsometricImmersion.Curvature.IntrinsicCurvature +OAI.Geometry.IsometricImmersion.Curvature.MetricCurvatureJet +OAI.Geometry.IsometricImmersion.Curvature.NegativeCurvatureHeight +OAI.Geometry.IsometricImmersion.Curvature.PatchCurvatureProfiles +OAI.Geometry.IsometricImmersion.Curvature.PrescribedCurvature +OAI.Geometry.IsometricImmersion.Darboux.ActualDriftCoefficients +OAI.Geometry.IsometricImmersion.Darboux.ActualDriftEquation +OAI.Geometry.IsometricImmersion.Darboux.ActualHighDrift +OAI.Geometry.IsometricImmersion.Darboux.CurvaturePrincipalPart +OAI.Geometry.IsometricImmersion.Darboux.DarbouxEquation +OAI.Geometry.IsometricImmersion.Darboux.DarbouxJet +OAI.Geometry.IsometricImmersion.Darboux.Drift +OAI.Geometry.IsometricImmersion.Darboux.DriftBounds +OAI.Geometry.IsometricImmersion.Darboux.DriftOperatorIdentity +OAI.Geometry.IsometricImmersion.Darboux.DriftTransportAlgebra +OAI.Geometry.IsometricImmersion.Darboux.HeightEquation +OAI.Geometry.IsometricImmersion.Darboux.HeightPrincipalBounds +OAI.Geometry.IsometricImmersion.Darboux.MixedDarbouxElimination +OAI.Geometry.IsometricImmersion.Darboux.ModelPrincipal +OAI.Geometry.IsometricImmersion.Darboux.QActualSegmentTransfer +OAI.Geometry.IsometricImmersion.Darboux.QClosedStripMargins +OAI.Geometry.IsometricImmersion.Darboux.QCoefficientTube +OAI.Geometry.IsometricImmersion.Darboux.QContainingRectangle +OAI.Geometry.IsometricImmersion.Darboux.QEnergyApplication +OAI.Geometry.IsometricImmersion.Darboux.QFiniteActual +OAI.Geometry.IsometricImmersion.Darboux.QFirstJetEnergy +OAI.Geometry.IsometricImmersion.Darboux.QFirstJetFunctions +OAI.Geometry.IsometricImmersion.Darboux.QFirstSpatialBounds +OAI.Geometry.IsometricImmersion.Darboux.QHighEquation +OAI.Geometry.IsometricImmersion.Darboux.QInitialEnergy +OAI.Geometry.IsometricImmersion.Darboux.QLowActualBounds +OAI.Geometry.IsometricImmersion.Darboux.QMetricDensityDecomposition +OAI.Geometry.IsometricImmersion.Darboux.QMetricFirstErrorBound +OAI.Geometry.IsometricImmersion.Darboux.QMetricJetTransfer +OAI.Geometry.IsometricImmersion.Darboux.QMomentAbsorption +OAI.Geometry.IsometricImmersion.Darboux.QPositiveFloor +OAI.Geometry.IsometricImmersion.Darboux.QPrincipal +OAI.Geometry.IsometricImmersion.Darboux.QReferenceInitialTolerance +OAI.Geometry.IsometricImmersion.Darboux.QResidualActive +OAI.Geometry.IsometricImmersion.Darboux.QResidualFactors +OAI.Geometry.IsometricImmersion.Darboux.QResidualL2 +OAI.Geometry.IsometricImmersion.Darboux.QSameStripMargins +OAI.Geometry.IsometricImmersion.Darboux.QSegmentAveraging +OAI.Geometry.IsometricImmersion.Darboux.QSegmentDomain +OAI.Geometry.IsometricImmersion.Darboux.QSegmentMargins +OAI.Geometry.IsometricImmersion.Darboux.QSpatialFiniteInduction +OAI.Geometry.IsometricImmersion.Darboux.QSpatialInductionStep +OAI.Geometry.IsometricImmersion.Darboux.QSpatialJets +OAI.Geometry.IsometricImmersion.Darboux.QSpatialPointwise +OAI.Geometry.IsometricImmersion.Darboux.QSpatialRestriction +OAI.Geometry.IsometricImmersion.Darboux.QSpatialSlabData +OAI.Geometry.IsometricImmersion.Darboux.QStripJetControl +OAI.Geometry.IsometricImmersion.Darboux.SixVariableDarboux +OAI.Geometry.IsometricImmersion.Darboux.SixVariableLinearization +OAI.Geometry.IsometricImmersion.Darboux.SixVariableQ +OAI.Geometry.IsometricImmersion.Darboux.SwappedDarboux +OAI.Geometry.IsometricImmersion.Darboux.TransverseCoefficient +OAI.Geometry.IsometricImmersion.Energy.ActualRemainderL2 +OAI.Geometry.IsometricImmersion.Energy.DirectedBounds +OAI.Geometry.IsometricImmersion.Energy.DirectedCoercivity +OAI.Geometry.IsometricImmersion.Energy.DirectedCutoffBalance +OAI.Geometry.IsometricImmersion.Energy.DirectedDefectCost +OAI.Geometry.IsometricImmersion.Energy.DirectedEdgeDefect +OAI.Geometry.IsometricImmersion.Energy.DirectedFarNegative +OAI.Geometry.IsometricImmersion.Energy.DirectedFluxCost +OAI.Geometry.IsometricImmersion.Energy.DirectedIntegralEstimate +OAI.Geometry.IsometricImmersion.Energy.DirectedParameterChoice +OAI.Geometry.IsometricImmersion.Energy.DirectedWeightJetCost +OAI.Geometry.IsometricImmersion.Energy.FiniteProductL2 +OAI.Geometry.IsometricImmersion.Energy.FiniteSumL2 +OAI.Geometry.IsometricImmersion.Energy.FixedMetricMixedL2 +OAI.Geometry.IsometricImmersion.Energy.HeightEnergy +OAI.Geometry.IsometricImmersion.Energy.HeightEnergyJetBounds +OAI.Geometry.IsometricImmersion.Energy.HyperbolicEnergyDensity +OAI.Geometry.IsometricImmersion.Energy.LocalQResidualL2 +OAI.Geometry.IsometricImmersion.Energy.LocalizedRemainderL2 +OAI.Geometry.IsometricImmersion.Energy.MixedDerivativeL2 +OAI.Geometry.IsometricImmersion.Energy.MixedRemainderL2 +OAI.Geometry.IsometricImmersion.Energy.MovingEnergyGradient +OAI.Geometry.IsometricImmersion.Energy.MovingEnergyPropagation +OAI.Geometry.IsometricImmersion.Energy.MovingHyperbolicEnergy +OAI.Geometry.IsometricImmersion.Energy.MovingIntervalSobolev +OAI.Geometry.IsometricImmersion.Energy.MovingIntervalSourceL2 +OAI.Geometry.IsometricImmersion.Energy.MovingSlabEnergy +OAI.Geometry.IsometricImmersion.Energy.MultiplierAbsorption +OAI.Geometry.IsometricImmersion.Energy.MultiplierDivergence +OAI.Geometry.IsometricImmersion.Energy.MultiplierIntegral +OAI.Geometry.IsometricImmersion.Energy.PatchDirectedCoercivity +OAI.Geometry.IsometricImmersion.Energy.RectangleSobolev +OAI.Geometry.IsometricImmersion.Energy.RectangleSobolevOne +OAI.Geometry.IsometricImmersion.Energy.RegionSobolev +OAI.Geometry.IsometricImmersion.Energy.SqrtEnergyGronwall +OAI.Geometry.IsometricImmersion.Energy.WeightPrimitive +OAI.Geometry.IsometricImmersion.Energy.WeightPrimitiveParameter +OAI.Geometry.IsometricImmersion.Energy.WeightedMultiplier +OAI.Geometry.IsometricImmersion.Estimates.ActualHighEquation +OAI.Geometry.IsometricImmersion.Estimates.ActualQApplicability +OAI.Geometry.IsometricImmersion.Estimates.ActualQCompactBounds +OAI.Geometry.IsometricImmersion.Estimates.ActualQMomentLower +OAI.Geometry.IsometricImmersion.Estimates.ActualQMomentPositive +OAI.Geometry.IsometricImmersion.Estimates.ActualQPointBounds +OAI.Geometry.IsometricImmersion.Estimates.ActualQWeightedRemainder +OAI.Geometry.IsometricImmersion.Estimates.ActualRemainderFactors +OAI.Geometry.IsometricImmersion.Estimates.ActualRemainderRegularity +OAI.Geometry.IsometricImmersion.Estimates.BoundedClassHyperbolicity +OAI.Geometry.IsometricImmersion.Estimates.BoundedClassQFloor +OAI.Geometry.IsometricImmersion.Estimates.BoundedClassQLow +OAI.Geometry.IsometricImmersion.Estimates.FixedRadiusCutBounds +OAI.Geometry.IsometricImmersion.Estimates.HighFactorOrders +OAI.Geometry.IsometricImmersion.Estimates.LargestBlockLinearization +OAI.Geometry.IsometricImmersion.Estimates.MixedRemainderFactors +OAI.Geometry.IsometricImmersion.Estimates.MovingSourceBounds +OAI.Geometry.IsometricImmersion.Estimates.RemainderAreaBudget +OAI.Geometry.IsometricImmersion.Estimates.UniversalQRaw +OAI.Geometry.IsometricImmersion.Flows.ActualFlowHighEquation +OAI.Geometry.IsometricImmersion.Flows.CompactParameterIntegral +OAI.Geometry.IsometricImmersion.Flows.ConstructedHeightFlow +OAI.Geometry.IsometricImmersion.Flows.Existence +OAI.Geometry.IsometricImmersion.Flows.FiniteMetricChosenFlow +OAI.Geometry.IsometricImmersion.Flows.FlowBounds +OAI.Geometry.IsometricImmersion.Flows.FlowChart +OAI.Geometry.IsometricImmersion.Flows.FlowCurvature +OAI.Geometry.IsometricImmersion.Flows.FlowExistence +OAI.Geometry.IsometricImmersion.Flows.FlowHeightCoefficients +OAI.Geometry.IsometricImmersion.Flows.FlowImageFirstBounds +OAI.Geometry.IsometricImmersion.Flows.FlowImageMargin +OAI.Geometry.IsometricImmersion.Flows.FlowInverse +OAI.Geometry.IsometricImmersion.Flows.FlowJointSmooth +OAI.Geometry.IsometricImmersion.Flows.FlowLowBounds +OAI.Geometry.IsometricImmersion.Flows.FlowParameter +OAI.Geometry.IsometricImmersion.Flows.FlowParameterContinuity +OAI.Geometry.IsometricImmersion.Flows.FlowSecondVariation +OAI.Geometry.IsometricImmersion.Flows.FlowSobolev +OAI.Geometry.IsometricImmersion.Flows.FlowThirdVariation +OAI.Geometry.IsometricImmersion.Flows.FlowTimeVariation +OAI.Geometry.IsometricImmersion.Flows.FlowTransport +OAI.Geometry.IsometricImmersion.Flows.FlowVariation +OAI.Geometry.IsometricImmersion.Flows.HeightFlowBoundTools +OAI.Geometry.IsometricImmersion.Flows.HeightFlowUniformBounds +OAI.Geometry.IsometricImmersion.Flows.PatchFlowCoercivity +OAI.Geometry.IsometricImmersion.Flows.PicardFamily +OAI.Geometry.IsometricImmersion.Flows.UniformRichPatchFlow +OAI.Geometry.IsometricImmersion.Flows.VaryingMetricChosenFlow +OAI.Geometry.IsometricImmersion.Immersions.ActualHeight +OAI.Geometry.IsometricImmersion.Immersions.ActualShearHeight +OAI.Geometry.IsometricImmersion.Immersions.BoundaryNormal +OAI.Geometry.IsometricImmersion.Immersions.BoundedHeightClasses +OAI.Geometry.IsometricImmersion.Immersions.CompactBoundaryExtremum +OAI.Geometry.IsometricImmersion.Immersions.FiniteHeight +OAI.Geometry.IsometricImmersion.Immersions.HeightCoefficientClosedBounds +OAI.Geometry.IsometricImmersion.Immersions.HeightCoefficientRegularity +OAI.Geometry.IsometricImmersion.Immersions.HeightNorm +OAI.Geometry.IsometricImmersion.Immersions.HeightNumericParameters +OAI.Geometry.IsometricImmersion.Immersions.HeightPFirstBounds +OAI.Geometry.IsometricImmersion.Immersions.InducedMetric +OAI.Geometry.IsometricImmersion.Immersions.NormalField +OAI.Geometry.IsometricImmersion.Immersions.NormalSpace +OAI.Geometry.IsometricImmersion.Immersions.OrientedHeightPullback +OAI.Geometry.IsometricImmersion.Immersions.RankOne2 +OAI.Geometry.IsometricImmersion.Immersions.RankOneOrientation +OAI.Geometry.IsometricImmersion.LocalDomains +OAI.Geometry.IsometricImmersion.Main +OAI.Geometry.IsometricImmersion.Metric +OAI.Geometry.IsometricImmersion.Metrics.ActualLowMetricBudget +OAI.Geometry.IsometricImmersion.Metrics.ActualLowMetricFloor +OAI.Geometry.IsometricImmersion.Metrics.ActualTestMetricPositive +OAI.Geometry.IsometricImmersion.Metrics.AffineTensorNeighborhood +OAI.Geometry.IsometricImmersion.Metrics.FixedMetricRemainder +OAI.Geometry.IsometricImmersion.Metrics.LocalMetricPCoefficients +OAI.Geometry.IsometricImmersion.Metrics.LocalMetricQActive +OAI.Geometry.IsometricImmersion.Metrics.LocalMetricQFull +OAI.Geometry.IsometricImmersion.Metrics.MetricCompatibility +OAI.Geometry.IsometricImmersion.Metrics.MetricHorizontalRequests +OAI.Geometry.IsometricImmersion.Metrics.MetricLocality +OAI.Geometry.IsometricImmersion.Metrics.MetricPBundleBounds +OAI.Geometry.IsometricImmersion.Metrics.MetricPatchOpen +OAI.Geometry.IsometricImmersion.Metrics.MetricQSpatialBundle +OAI.Geometry.IsometricImmersion.Metrics.MetricSmoothness +OAI.Geometry.IsometricImmersion.Metrics.ModelCoercivity +OAI.Geometry.IsometricImmersion.Metrics.ModelMetric +OAI.Geometry.IsometricImmersion.Metrics.ModelProfile +OAI.Geometry.IsometricImmersion.Metrics.PatchTensorPositivity +OAI.Geometry.IsometricImmersion.Metrics.PatchTensorRestriction +OAI.Geometry.IsometricImmersion.Metrics.RemainderCoefficientBounds +OAI.Geometry.IsometricImmersion.Metrics.SmoothMetricRestriction +OAI.Geometry.IsometricImmersion.Metrics.StateCoefficientTube +OAI.Geometry.IsometricImmersion.Metrics.UniversalMetricP +OAI.Geometry.IsometricImmersion.Metrics.UniversalMetricQ +OAI.Geometry.IsometricImmersion.Metrics.WarpedMetric +OAI.Geometry.IsometricImmersion.Obstructions.BoundedClassNowhereDense +OAI.Geometry.IsometricImmersion.Obstructions.BoundedClassTopology +OAI.Geometry.IsometricImmersion.Obstructions.DiskBoundaryObstruction +OAI.Geometry.IsometricImmersion.Obstructions.LocalAdmissibility +OAI.Geometry.IsometricImmersion.Obstructions.PatchAdmissibility +OAI.Geometry.IsometricImmersion.Obstructions.PatchAdmissibilityRestriction +OAI.Geometry.IsometricImmersion.Obstructions.PatchObstructionSet +OAI.Geometry.IsometricImmersion.Obstructions.PatchResidualTheorem +OAI.Geometry.IsometricImmersion.Obstructions.SmallPatchObstruction +OAI.Geometry.IsometricImmersion.Obstructions.UniversalPatchSelection +OAI.Geometry.IsometricImmersion.Pulses.ActualClassQForcingMoment +OAI.Geometry.IsometricImmersion.Pulses.ActualForcingCoefficient +OAI.Geometry.IsometricImmersion.Pulses.ActualForcingMoment +OAI.Geometry.IsometricImmersion.Pulses.ActualPulseMetricCloseness +OAI.Geometry.IsometricImmersion.Pulses.ActualQPulseForcing +OAI.Geometry.IsometricImmersion.Pulses.ActualQPulseForcingGlobal +OAI.Geometry.IsometricImmersion.Pulses.ActualTwoSidedPulseSeparation +OAI.Geometry.IsometricImmersion.Pulses.CutoffEdgeMoment +OAI.Geometry.IsometricImmersion.Pulses.FiniteOscillatoryMoment +OAI.Geometry.IsometricImmersion.Pulses.ForcingCoefficientSign +OAI.Geometry.IsometricImmersion.Pulses.OffPulseMetricBounds +OAI.Geometry.IsometricImmersion.Pulses.OriginalPulseExclusion +OAI.Geometry.IsometricImmersion.Pulses.PulseActualDensity +OAI.Geometry.IsometricImmersion.Pulses.PulseCurvaturePrincipal +OAI.Geometry.IsometricImmersion.Pulses.PulseDensityGlobal +OAI.Geometry.IsometricImmersion.Pulses.PulseDensitySlab +OAI.Geometry.IsometricImmersion.Pulses.PulseDerivativeBounds +OAI.Geometry.IsometricImmersion.Pulses.PulseEdgeReferenceDistance +OAI.Geometry.IsometricImmersion.Pulses.PulseFirstJetControl +OAI.Geometry.IsometricImmersion.Pulses.PulseFlowDistance +OAI.Geometry.IsometricImmersion.Pulses.PulseMoment +OAI.Geometry.IsometricImmersion.Pulses.PulseMomentError +OAI.Geometry.IsometricImmersion.Pulses.PulseMomentGeometry +OAI.Geometry.IsometricImmersion.Pulses.PulseNeighborhood +OAI.Geometry.IsometricImmersion.Pulses.PulseNeighborhoodAdapters +OAI.Geometry.IsometricImmersion.Pulses.PulseOperatorMoment +OAI.Geometry.IsometricImmersion.Pulses.PulseProfiles +OAI.Geometry.IsometricImmersion.Pulses.PulseScalarContradiction +OAI.Geometry.IsometricImmersion.Pulses.PulseSecondXi +OAI.Geometry.IsometricImmersion.Pulses.PulseSpatialParts +OAI.Geometry.IsometricImmersion.Pulses.PulseTemporalMoment +OAI.Geometry.IsometricImmersion.Pulses.PulseTemporalParts +OAI.Geometry.IsometricImmersion.Pulses.PulseTestEnergy +OAI.Geometry.IsometricImmersion.Pulses.QPulseFirstJetBudget +OAI.Geometry.IsometricImmersion.Pulses.QReferenceForcingMargins +OAI.Geometry.IsometricImmersion.Pulses.ReferencePulseEdgeInitial +OAI.Geometry.IsometricImmersion.Pulses.ShearedPulseRegions +OAI.Geometry.IsometricImmersion.Taylor.ActualDarbouxFaa +OAI.Geometry.IsometricImmersion.Taylor.ActualTaylorFiniteJets +OAI.Geometry.IsometricImmersion.Taylor.ActualUniformTaylorPulse +OAI.Geometry.IsometricImmersion.Taylor.ActualUniformTaylorRich +OAI.Geometry.IsometricImmersion.Taylor.ChainResidual +OAI.Geometry.IsometricImmersion.Taylor.ChainTermDerivative +OAI.Geometry.IsometricImmersion.Taylor.FiniteTaylorComparison +OAI.Geometry.IsometricImmersion.Taylor.ScalarChainExpansion +OAI.Geometry.IsometricImmersion.Taylor.TaylorCauchyData +OAI.Geometry.IsometricImmersion.Taylor.TaylorCoefficientBounds +OAI.Geometry.IsometricImmersion.Taylor.TaylorInitialStateBound +OAI.Geometry.IsometricImmersion.Taylor.TaylorInitialVelocity +OAI.Geometry.IsometricImmersion.Taylor.TaylorJetStability +OAI.Geometry.IsometricImmersion.Taylor.TaylorPolynomialJetBounds +OAI.Geometry.IsometricImmersion.Taylor.TaylorQJetBounds +OAI.Geometry.IsometricImmersion.Taylor.TaylorRemainderBound +OAI.Geometry.IsometricImmersion.Taylor.TaylorResidual +OAI.Geometry.IsometricImmersion.Taylor.TaylorSeparatedProduct +OAI.Geometry.IsometricImmersion.Taylor.TaylorUpperCauchyBounds +OAI.Geometry.IsometricImmersion.Taylor.TimeTaylorKernel +OAI.Geometry.IsometricImmersion.Taylor.TopChainExtraction +OAI.Geometry.IsometricImmersion.Taylor.UniformTaylorDenominator +OAI.Geometry.IsometricImmersion.Taylor.UniformTaylorPolynomial +OAI.Geometry.IsometricImmersion.Taylor.UniformTaylorPulse +OAI.Geometry.IsometricImmersion.Taylor.UniformTaylorStrip +OAI.Geometry.IsometricImmersion.Volterra.VolterraDifferentiation +OAI.Geometry.IsometricImmersion.Volterra.VolterraGlue +OAI.Geometry.IsometricImmersion.Volterra.VolterraInverse +OAI.Geometry.IsometricImmersion.Volterra.VolterraJointSmooth +OAI.Geometry.IsometricImmersion.Volterra.VolterraOperator +OAI.Geometry.IsometricImmersion.Volterra.VolterraParameterJets +OAI.Geometry.IsometricImmersion.Volterra.VolterraPositive diff --git a/tasks/isometric-immersion/solution/reference.py b/tasks/isometric-immersion/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/isometric-immersion/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/isometric-immersion/solution/solve.sh b/tasks/isometric-immersion/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8e1edb2674360fef48258f73c7dc8fee46e0606a --- /dev/null +++ b/tasks/isometric-immersion/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of IsometricImmersion, i.e. module OAI.Geometry.IsometricImmersion.Main and the +# 446 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.IsometricImmersion.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of IsometricImmersion" diff --git a/tasks/isometric-immersion/task.toml b/tasks/isometric-immersion/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e4646d31a260ee843212f124e38a15384257ce1 --- /dev/null +++ b/tasks/isometric-immersion/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/isometric-immersion" +version = "1.0.0" +description = "Prove IsometricImmersion (openai/math family 334: A smooth surface metric with no local immersion in $\\mathbb R^3$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/IsometricImmersion.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "IsometricImmersion" +family = "334" +family_title = "A smooth surface metric with no local immersion in $\\mathbb R^3$" +subject = "Differential geometry" +theorems = ["OAI.SmoothLocal.Geometry.exists_local_metric_without_local_immersion"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.IsometricImmersion.Main" +reference_modules = 446 +reference_lean_bytes = 2824652 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1242 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14242 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/isometric-immersion/tests/Challenge.lean b/tasks/isometric-immersion/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9b41ea032ce83b10a0df6e06f30c23cde9dde2e3 --- /dev/null +++ b/tasks/isometric-immersion/tests/Challenge.lean @@ -0,0 +1,62 @@ +import Mathlib.Analysis.InnerProductSpace.Calculus +import Mathlib.LinearAlgebra.Matrix.PosDef +import Mathlib.LinearAlgebra.Matrix.NonsingularInverse +import Mathlib.Geometry.Manifold.ContMDiff.NormedSpace +import Mathlib.Geometry.Manifold.MFDeriv.FDeriv + +namespace OAI + +noncomputable section +open Set TopologicalSpace +open scoped ContDiff Topology Manifold Matrix + +namespace SmoothLocal.Geometry + +abbrev Coord := Fin 2 → ℝ + +abbrev Ambient := EuclideanSpace ℝ (Fin 3) + +def square : Set Coord := {p | ∀ i, p i ∈ Set.Ioo (-1 : ℝ) 1} + +def LocalSmoothPositive (U : Opens Coord) + (g : U → Matrix (Fin 2) (Fin 2) ℝ) : Prop := + (∀ i j, ContMDiff 𝓘(ℝ, Coord) 𝓘(ℝ, ℝ) ∞ (fun p => g p i j)) ∧ + ∀ p, (g p).PosDef + +end SmoothLocal.Geometry + +namespace SmoothLocal.ODE +open SmoothLocal.Geometry + +theorem coordinate_square_isOpen : IsOpen square := by + have heq : square = ⋂ i : Fin 2, + (fun p : Coord => p i) ⁻¹' Ioo (-1 : ℝ) 1 := by + ext p + simp [square] + rw [heq] + exact isOpen_iInter_of_finite (fun i => isOpen_Ioo.preimage (continuous_apply i)) + +end SmoothLocal.ODE + +namespace SmoothLocal.Geometry + +def coordinateSquareOpen : Opens Coord := + ⟨square, SmoothLocal.ODE.coordinate_square_isOpen⟩ + +theorem exists_local_metric_without_local_immersion : + ∃ g : coordinateSquareOpen → Matrix (Fin 2) (Fin 2) ℝ, + LocalSmoothPositive coordinateSquareOpen g ∧ + ∀ U : Opens Coord, ∀ hUS : (U : Set Coord) ⊆ square, + (0 : Coord) ∈ U → ∀ F : U → Ambient, + ¬ (ContMDiff 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) ∞ F ∧ + ∀ p : U, ∀ v w : Coord, + (inner ℝ : Ambient → Ambient → ℝ) (mfderiv 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) F p v) + (mfderiv 𝓘(ℝ, Coord) 𝓘(ℝ, Ambient) F p w) = + v ⬝ᵥ (g ⟨p, hUS p.property⟩ *ᵥ w)) := by + sorry + +end SmoothLocal.Geometry + +end + +end OAI diff --git a/tasks/isometric-immersion/tests/grade.py b/tasks/isometric-immersion/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/isometric-immersion/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/isometric-immersion/tests/task.json b/tasks/isometric-immersion/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a66f63662aabb9f2f61123e16974647dec3df0d7 --- /dev/null +++ b/tasks/isometric-immersion/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "IsometricImmersion", + "comparator": { + "theorem_names": [ + "OAI.SmoothLocal.Geometry.exists_local_metric_without_local_immersion" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13342 +} \ No newline at end of file diff --git a/tasks/isometric-immersion/tests/test.sh b/tasks/isometric-immersion/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/isometric-immersion/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/k-median-recovery/environment/Dockerfile b/tasks/k-median-recovery/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/k-median-recovery/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/k-median-recovery/environment/fetch_mathlib.sh b/tasks/k-median-recovery/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/k-median-recovery/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/k-median-recovery/environment/lake-manifest.json b/tasks/k-median-recovery/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/k-median-recovery/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/k-median-recovery/environment/lakefile.lean b/tasks/k-median-recovery/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/k-median-recovery/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/k-median-recovery/environment/lean_setup.sh b/tasks/k-median-recovery/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/k-median-recovery/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/k-median-recovery/environment/pack_submission.py b/tasks/k-median-recovery/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/k-median-recovery/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/k-median-recovery/instruction.md b/tasks/k-median-recovery/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bc7e927836e4a602ffbddafe6f2497c0554a9676 --- /dev/null +++ b/tasks/k-median-recovery/instruction.md @@ -0,0 +1,158 @@ +# openai/math challenge `KMedianRecovery` (family 125) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 125 of the release, *The approximation threshold for metric $k$-median* +(Theoretical computer science). The family as a whole: Gives a deterministic polynomial-time $(1+2/e+\varepsilon)$-approximation for finite rational metric $k$-median with specified candidate facilities, for every fixed $\varepsilon>0$. Assuming $P\ne NP$, the optimal infimum approximation factor is $1+2/e$. + +The challenge is `KMedianRecovery`, also at `/opt/openai-math/challenges/KMedianRecovery.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MetricKMedianRecovery + +structure RationalMetricInput where + pointCount : ℕ + distance : Fin pointCount → Fin pointCount → ℚ + clients : Finset (Fin pointCount) + facilities : Finset (Fin pointCount) + budget : ℕ + facilities_nonempty : facilities.Nonempty + budget_pos : 0 < budget + covered : clients ∪ facilities = Finset.univ + distance_nonneg : ∀ x y, 0 ≤ distance x y + distance_self : ∀ x, distance x x = 0 + distance_symm : ∀ x y, distance x y = distance y x + distance_triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +namespace RationalMetricInput + +def size (I : RationalMetricInput) : ℕ := I.clients.card + I.facilities.card + +def Feasible (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : Prop := + S ⊆ I.facilities ∧ S.card ≤ I.budget ∧ (I.clients.Nonempty → S.Nonempty) + +def cost (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : ℚ := + if hS : S.Nonempty then ∑ p ∈ I.clients, S.inf' hS (I.distance p) else 0 + +def comparisonSets (I : RationalMetricInput) : Finset (Finset (Fin I.pointCount)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.budget) + +lemma comparisonSets_nonempty (I : RationalMetricInput) : I.comparisonSets.Nonempty := by + obtain ⟨i, hi⟩ := I.facilities_nonempty + refine ⟨{i}, ?_⟩ + simp only [comparisonSets, Finset.mem_filter, Finset.mem_powerset, + Finset.singleton_subset_iff, Finset.singleton_nonempty, Finset.card_singleton, true_and] + exact ⟨hi, I.budget_pos⟩ + +def optimum (I : RationalMetricInput) : ℚ := + I.comparisonSets.inf' I.comparisonSets_nonempty I.cost + +def natBits (n : ℕ) : List Bool := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +def rationalBits (r : ℚ) : List Bool := + [decide (r < 0)] ++ natBits r.num.natAbs ++ natBits r.den + +def bits (I : RationalMetricInput) : List Bool := + natBits I.pointCount ++ natBits I.budget ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.pointCount => + (List.ofFn (fun j : Fin I.pointCount => rationalBits (I.distance i j))).flatten)).flatten + +def decodeOutput (I : RationalMetricInput) (out : List Bool) : Finset (Fin I.pointCount) := + I.facilities.filter (fun i => out[i.val]?.getD false = true) + +end RationalMetricInput + +def pairBits (p : List Bool × List Bool) : List Bool := + p.1.flatMap (fun b => [true, b]) ++ [false] ++ p.2 + +structure BinaryRandomizedAlgorithm where + randomBits : Polynomial ℕ + run : List Bool × List Bool → List Bool + computation : Turing.TM2ComputableInPolyTime pairBits id run + finiteWorkAlphabet : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + +namespace BinaryRandomizedAlgorithm + +def bitCount (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) : ℕ := + A.randomBits.eval I.bits.length + +abbrev Seed (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) := + Fin (A.bitCount I) → Bool + +def output (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) (s : A.Seed I) : + Finset (Fin I.pointCount) := + I.decodeOutput (A.run (I.bits, List.ofFn s)) + +noncomputable def successProbability (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) + (bound : ℝ) : ℝ := by + classical + exact ((Finset.univ.filter (fun s : A.Seed I => (I.cost (A.output I s) : ℝ) ≤ bound)).card : ℝ) / + 2 ^ (A.bitCount I) + +noncomputable def expectedCost (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) : ℝ := + (∑ s : A.Seed I, (I.cost (A.output I s) : ℝ)) / 2 ^ (A.bitCount I) + +end BinaryRandomizedAlgorithm + +def globalApplicationClaim : Prop := + ∃ σ : ℝ, 0 < σ ∧ ∀ a : ℝ, 0 < a → ∃ A : BinaryRandomizedAlgorithm, + (∀ (I : RationalMetricInput) (s : A.Seed I), I.Feasible (A.output I s)) ∧ + (∀ I : RationalMetricInput, + 1 - Real.rpow ((I.size : ℝ) + 2) (-a) ≤ + A.successProbability I ((2 - σ) * (I.optimum : ℝ))) ∧ + (∀ I : RationalMetricInput, A.expectedCost I ≤ (2 - σ) * (I.optimum : ℝ)) + +theorem global_application : globalApplicationClaim := by + sorry + +end MetricKMedianRecovery + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KMedianRecovery.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MetricKMedianRecovery.global_application` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/k-median-recovery/solution/closure.txt b/tasks/k-median-recovery/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..45603383bde434580ae5755bbfef8c16ae24c823 --- /dev/null +++ b/tasks/k-median-recovery/solution/closure.txt @@ -0,0 +1,506 @@ +OAI.Combinatorics.KMedianRecovery.Algorithms.BudgetBound +OAI.Combinatorics.KMedianRecovery.Algorithms.CandidateSanitize +OAI.Combinatorics.KMedianRecovery.Algorithms.CompletionAlgorithm +OAI.Combinatorics.KMedianRecovery.Algorithms.CompletionResultGuarantee +OAI.Combinatorics.KMedianRecovery.Algorithms.ExtendBudget +OAI.Combinatorics.KMedianRecovery.Algorithms.FinalBudgetPos +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalCall +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalOuter +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalOuterProbability +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalPolynomialFairExperiment +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalRawFairExperiment +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalRoundMetric +OAI.Combinatorics.KMedianRecovery.Algorithms.GlobalZero +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralAll +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralDispatchGuarantee +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralDispatchLaws +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralPrecision +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralProgram +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryAll +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryAmplified +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryDemand +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryFeasible +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryGuesses +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryMachine +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoveryRepeat +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoverySelection +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoverySemantics +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralRecoverySuccess +OAI.Combinatorics.KMedianRecovery.Algorithms.IntegralUniform +OAI.Combinatorics.KMedianRecovery.Algorithms.LocalIntegral +OAI.Combinatorics.KMedianRecovery.Branching.Blue +OAI.Combinatorics.KMedianRecovery.Branching.BlueBlocksMachine +OAI.Combinatorics.KMedianRecovery.Branching.BlueChoice +OAI.Combinatorics.KMedianRecovery.Branching.BlueDPValue +OAI.Combinatorics.KMedianRecovery.Branching.BlueItem +OAI.Combinatorics.KMedianRecovery.Branching.BlueLookup +OAI.Combinatorics.KMedianRecovery.Branching.BlueMerge +OAI.Combinatorics.KMedianRecovery.Branching.BlueNextTable +OAI.Combinatorics.KMedianRecovery.Branching.BluePlan +OAI.Combinatorics.KMedianRecovery.Branching.BlueProgram +OAI.Combinatorics.KMedianRecovery.Branching.BlueTable +OAI.Combinatorics.KMedianRecovery.Branching.BlueTableSize +OAI.Combinatorics.KMedianRecovery.Branching.BranchBalls +OAI.Combinatorics.KMedianRecovery.Branching.BranchChecksCorrect +OAI.Combinatorics.KMedianRecovery.Branching.BranchContext +OAI.Combinatorics.KMedianRecovery.Branching.BranchObjective +OAI.Combinatorics.KMedianRecovery.Branching.BranchPhysical +OAI.Combinatorics.KMedianRecovery.Branching.BranchPrefix +OAI.Combinatorics.KMedianRecovery.Branching.BranchSeedLayout +OAI.Combinatorics.KMedianRecovery.Branching.BranchTapeBound +OAI.Combinatorics.KMedianRecovery.Branching.BranchTapeSuccess +OAI.Combinatorics.KMedianRecovery.Branching.BranchWeights +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalChoice +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalExpected +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalOutput +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalRawPrep +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalResources +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalRule +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalScore +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalSize +OAI.Combinatorics.KMedianRecovery.Branching.CategoricalTable +OAI.Combinatorics.KMedianRecovery.Branching.CompletionBits +OAI.Combinatorics.KMedianRecovery.Branching.CompletionBound +OAI.Combinatorics.KMedianRecovery.Branching.CompletionCoefficient +OAI.Combinatorics.KMedianRecovery.Branching.CompletionExponential +OAI.Combinatorics.KMedianRecovery.Branching.CompletionFair +OAI.Combinatorics.KMedianRecovery.Branching.CompletionFairCorrect +OAI.Combinatorics.KMedianRecovery.Branching.CompletionFillMath +OAI.Combinatorics.KMedianRecovery.Branching.CompletionIndex +OAI.Combinatorics.KMedianRecovery.Branching.CompletionRealize +OAI.Combinatorics.KMedianRecovery.Branching.CompletionRealizeMath +OAI.Combinatorics.KMedianRecovery.Branching.CopyAge +OAI.Combinatorics.KMedianRecovery.Branching.CopyComparison +OAI.Combinatorics.KMedianRecovery.Branching.CopyComputes +OAI.Combinatorics.KMedianRecovery.Branching.CopyGround +OAI.Combinatorics.KMedianRecovery.Branching.DesignatedBranchSuccess +OAI.Combinatorics.KMedianRecovery.Branching.EnumerateBranches +OAI.Combinatorics.KMedianRecovery.Branching.FairZeroCompletion +OAI.Combinatorics.KMedianRecovery.Branching.FavorableReady +OAI.Combinatorics.KMedianRecovery.Branching.ObservableCapacity +OAI.Combinatorics.KMedianRecovery.Branching.ObservableSuccessfulCompletion +OAI.Combinatorics.KMedianRecovery.Branching.ObservableSuccessfulProbability +OAI.Combinatorics.KMedianRecovery.Branching.PopulationBridge +OAI.Combinatorics.KMedianRecovery.Branching.PopulationMachine +OAI.Combinatorics.KMedianRecovery.Branching.RandomizedZeroBranch +OAI.Combinatorics.KMedianRecovery.Branching.RationalBranch +OAI.Combinatorics.KMedianRecovery.Branching.RationalSurrogate +OAI.Combinatorics.KMedianRecovery.Branching.SampledSurrogate +OAI.Combinatorics.KMedianRecovery.Branching.SuccessfulCompletionCharge +OAI.Combinatorics.KMedianRecovery.Branching.SuccessfulFavorableProbability +OAI.Combinatorics.KMedianRecovery.Branching.SurrogateRealization +OAI.Combinatorics.KMedianRecovery.Branching.ZeroSuccessfulCompletion +OAI.Combinatorics.KMedianRecovery.Encoding.BitsInjective +OAI.Combinatorics.KMedianRecovery.Encoding.BoundedNatWord +OAI.Combinatorics.KMedianRecovery.Encoding.ColorLabelMachine +OAI.Combinatorics.KMedianRecovery.Encoding.CoupledEncode +OAI.Combinatorics.KMedianRecovery.Encoding.CutMatrix +OAI.Combinatorics.KMedianRecovery.Encoding.DivNatWords +OAI.Combinatorics.KMedianRecovery.Encoding.DuplicateMatrix +OAI.Combinatorics.KMedianRecovery.Encoding.Encode +OAI.Combinatorics.KMedianRecovery.Encoding.Encode2 +OAI.Combinatorics.KMedianRecovery.Encoding.Encode3 +OAI.Combinatorics.KMedianRecovery.Encoding.EntryIndex +OAI.Combinatorics.KMedianRecovery.Encoding.ExchangeIndex +OAI.Combinatorics.KMedianRecovery.Encoding.FinSetDecode +OAI.Combinatorics.KMedianRecovery.Encoding.FinSets +OAI.Combinatorics.KMedianRecovery.Encoding.HistoryBits +OAI.Combinatorics.KMedianRecovery.Encoding.IndexedFiniteExperiment +OAI.Combinatorics.KMedianRecovery.Encoding.InstructionBits +OAI.Combinatorics.KMedianRecovery.Encoding.LabelLookup +OAI.Combinatorics.KMedianRecovery.Encoding.LabelMember +OAI.Combinatorics.KMedianRecovery.Encoding.LabelOrder +OAI.Combinatorics.KMedianRecovery.Encoding.LabelRange +OAI.Combinatorics.KMedianRecovery.Encoding.LabelSize +OAI.Combinatorics.KMedianRecovery.Encoding.LengthEncode +OAI.Combinatorics.KMedianRecovery.Encoding.MaskOutput +OAI.Combinatorics.KMedianRecovery.Encoding.Matrix +OAI.Combinatorics.KMedianRecovery.Encoding.MatrixRows +OAI.Combinatorics.KMedianRecovery.Encoding.NatWords +OAI.Combinatorics.KMedianRecovery.Encoding.OptionEncode +OAI.Combinatorics.KMedianRecovery.Encoding.PrecisionBits +OAI.Combinatorics.KMedianRecovery.Encoding.PushWord +OAI.Combinatorics.KMedianRecovery.Encoding.RationalBest +OAI.Combinatorics.KMedianRecovery.Encoding.RationalBottomIndices +OAI.Combinatorics.KMedianRecovery.Encoding.RationalCap +OAI.Combinatorics.KMedianRecovery.Encoding.RationalConstants +OAI.Combinatorics.KMedianRecovery.Encoding.RationalInflatedShape +OAI.Combinatorics.KMedianRecovery.Encoding.RationalLeaves +OAI.Combinatorics.KMedianRecovery.Encoding.RationalMenus +OAI.Combinatorics.KMedianRecovery.Encoding.RationalSlack +OAI.Combinatorics.KMedianRecovery.Encoding.RationalSort +OAI.Combinatorics.KMedianRecovery.Encoding.RationalStream +OAI.Combinatorics.KMedianRecovery.Encoding.RecoveryIndex +OAI.Combinatorics.KMedianRecovery.Encoding.Reencode +OAI.Combinatorics.KMedianRecovery.Encoding.RowEncode +OAI.Combinatorics.KMedianRecovery.Encoding.SortedRepresentative +OAI.Combinatorics.KMedianRecovery.Encoding.StateBits +OAI.Combinatorics.KMedianRecovery.Encoding.StateBits2 +OAI.Combinatorics.KMedianRecovery.Encoding.UnaryParser +OAI.Combinatorics.KMedianRecovery.Encoding.UniformBits +OAI.Combinatorics.KMedianRecovery.Encoding.UniformWord +OAI.Combinatorics.KMedianRecovery.Encoding.WordExtras +OAI.Combinatorics.KMedianRecovery.Encoding.WordSubsets +OAI.Combinatorics.KMedianRecovery.Encoding.WordTake +OAI.Combinatorics.KMedianRecovery.Encoding.Words +OAI.Combinatorics.KMedianRecovery.Geometry.AllBadCostBound +OAI.Combinatorics.KMedianRecovery.Geometry.ClusterCost +OAI.Combinatorics.KMedianRecovery.Geometry.ExecutionClusterCostOne +OAI.Combinatorics.KMedianRecovery.Geometry.FamilyMetric +OAI.Combinatorics.KMedianRecovery.Geometry.IndexedCost +OAI.Combinatorics.KMedianRecovery.Geometry.LeafDistances +OAI.Combinatorics.KMedianRecovery.Geometry.LocalBest +OAI.Combinatorics.KMedianRecovery.Geometry.LocalCandidates +OAI.Combinatorics.KMedianRecovery.Geometry.LocalFuel +OAI.Combinatorics.KMedianRecovery.Geometry.LocalIndex +OAI.Combinatorics.KMedianRecovery.Geometry.LocalRefineMachine +OAI.Combinatorics.KMedianRecovery.Geometry.LocalSets +OAI.Combinatorics.KMedianRecovery.Geometry.LocalTransport +OAI.Combinatorics.KMedianRecovery.Geometry.Metric +OAI.Combinatorics.KMedianRecovery.Geometry.MetricAnchor +OAI.Combinatorics.KMedianRecovery.Geometry.MetricArrays +OAI.Combinatorics.KMedianRecovery.Geometry.MetricCost +OAI.Combinatorics.KMedianRecovery.Geometry.MetricCost2 +OAI.Combinatorics.KMedianRecovery.Geometry.MetricParser +OAI.Combinatorics.KMedianRecovery.Geometry.Nearest +OAI.Combinatorics.KMedianRecovery.Geometry.NearestDistance +OAI.Combinatorics.KMedianRecovery.Geometry.NearestHeight +OAI.Combinatorics.KMedianRecovery.Geometry.NearestImage +OAI.Combinatorics.KMedianRecovery.Geometry.NearestImages +OAI.Combinatorics.KMedianRecovery.Geometry.NearestInsertEqual +OAI.Combinatorics.KMedianRecovery.Geometry.NearestLeafMachine +OAI.Combinatorics.KMedianRecovery.Geometry.NearestMap +OAI.Combinatorics.KMedianRecovery.Geometry.OptimumClusterSeparation +OAI.Combinatorics.KMedianRecovery.Geometry.OptimumMinCard +OAI.Combinatorics.KMedianRecovery.Geometry.RealCost +OAI.Combinatorics.KMedianRecovery.Geometry.RoundingArithmetic +OAI.Combinatorics.KMedianRecovery.Geometry.RoundingMatrix +OAI.Combinatorics.KMedianRecovery.Geometry.RoundingPrecision +OAI.Combinatorics.KMedianRecovery.Machines.ActionMachine +OAI.Combinatorics.KMedianRecovery.Machines.BisectionMachine +OAI.Combinatorics.KMedianRecovery.Machines.CappedFold +OAI.Combinatorics.KMedianRecovery.Machines.CorrectionSize +OAI.Combinatorics.KMedianRecovery.Machines.CoupledLoop +OAI.Combinatorics.KMedianRecovery.Machines.CoupledPrimitives +OAI.Combinatorics.KMedianRecovery.Machines.DeleteFold +OAI.Combinatorics.KMedianRecovery.Machines.DeleteSize +OAI.Combinatorics.KMedianRecovery.Machines.FiniteMachine +OAI.Combinatorics.KMedianRecovery.Machines.FirstSize +OAI.Combinatorics.KMedianRecovery.Machines.GridMachine +OAI.Combinatorics.KMedianRecovery.Machines.InitialLoop +OAI.Combinatorics.KMedianRecovery.Machines.LengthQuery +OAI.Combinatorics.KMedianRecovery.Machines.LoopInput +OAI.Combinatorics.KMedianRecovery.Machines.LoopInput2 +OAI.Combinatorics.KMedianRecovery.Machines.LoopInvariant +OAI.Combinatorics.KMedianRecovery.Machines.LoopMachine +OAI.Combinatorics.KMedianRecovery.Machines.LoopSize +OAI.Combinatorics.KMedianRecovery.Machines.MatchFold +OAI.Combinatorics.KMedianRecovery.Machines.MatchSize +OAI.Combinatorics.KMedianRecovery.Machines.MenuMachine +OAI.Combinatorics.KMedianRecovery.Machines.MergeResources +OAI.Combinatorics.KMedianRecovery.Machines.NormalizationMachine +OAI.Combinatorics.KMedianRecovery.Machines.Program +OAI.Combinatorics.KMedianRecovery.Machines.Program2 +OAI.Combinatorics.KMedianRecovery.Machines.ProjectionMachine +OAI.Combinatorics.KMedianRecovery.Machines.RecoveryOptionMachine +OAI.Combinatorics.KMedianRecovery.Machines.RecoveryTape +OAI.Combinatorics.KMedianRecovery.Machines.RefineMachine +OAI.Combinatorics.KMedianRecovery.Machines.ResolveMachine +OAI.Combinatorics.KMedianRecovery.Machines.ResolveResources +OAI.Combinatorics.KMedianRecovery.Machines.ScanMachine +OAI.Combinatorics.KMedianRecovery.Machines.SensitiveMachine +OAI.Combinatorics.KMedianRecovery.Machines.SizeBitLength +OAI.Combinatorics.KMedianRecovery.Machines.SliceFold +OAI.Combinatorics.KMedianRecovery.Machines.StartResources +OAI.Combinatorics.KMedianRecovery.Machines.StepMachine +OAI.Combinatorics.KMedianRecovery.Machines.SubProgram +OAI.Combinatorics.KMedianRecovery.Machines.SuffixMachine +OAI.Combinatorics.KMedianRecovery.Main +OAI.Combinatorics.KMedianRecovery.Model +OAI.Combinatorics.KMedianRecovery.Recovery.ActiveInsert +OAI.Combinatorics.KMedianRecovery.Recovery.Advance +OAI.Combinatorics.KMedianRecovery.Recovery.AffineLogBound +OAI.Combinatorics.KMedianRecovery.Recovery.AllBad +OAI.Combinatorics.KMedianRecovery.Recovery.Answer +OAI.Combinatorics.KMedianRecovery.Recovery.Average +OAI.Combinatorics.KMedianRecovery.Recovery.AveragePrecomposeEmbedding +OAI.Combinatorics.KMedianRecovery.Recovery.BadClientWeighted +OAI.Combinatorics.KMedianRecovery.Recovery.Ball +OAI.Combinatorics.KMedianRecovery.Recovery.BallSet +OAI.Combinatorics.KMedianRecovery.Recovery.Basic +OAI.Combinatorics.KMedianRecovery.Recovery.Basic2 +OAI.Combinatorics.KMedianRecovery.Recovery.BestDesignation +OAI.Combinatorics.KMedianRecovery.Recovery.BestFallback +OAI.Combinatorics.KMedianRecovery.Recovery.BitCount +OAI.Combinatorics.KMedianRecovery.Recovery.BlindUpdate +OAI.Combinatorics.KMedianRecovery.Recovery.Blocks +OAI.Combinatorics.KMedianRecovery.Recovery.BorrowBit +OAI.Combinatorics.KMedianRecovery.Recovery.BottomMath +OAI.Combinatorics.KMedianRecovery.Recovery.BoundOp +OAI.Combinatorics.KMedianRecovery.Recovery.BoundRow +OAI.Combinatorics.KMedianRecovery.Recovery.BoundedDecision +OAI.Combinatorics.KMedianRecovery.Recovery.BoundedMinimizingExtreme +OAI.Combinatorics.KMedianRecovery.Recovery.CanonicalParents +OAI.Combinatorics.KMedianRecovery.Recovery.Cap +OAI.Combinatorics.KMedianRecovery.Recovery.CenterUpdate +OAI.Combinatorics.KMedianRecovery.Recovery.Cf +OAI.Combinatorics.KMedianRecovery.Recovery.Chosen +OAI.Combinatorics.KMedianRecovery.Recovery.Claim +OAI.Combinatorics.KMedianRecovery.Recovery.ClassFilter +OAI.Combinatorics.KMedianRecovery.Recovery.ClassSlotsMem +OAI.Combinatorics.KMedianRecovery.Recovery.CloseSandwich +OAI.Combinatorics.KMedianRecovery.Recovery.Cluster +OAI.Combinatorics.KMedianRecovery.Recovery.CommonDen +OAI.Combinatorics.KMedianRecovery.Recovery.CommonL +OAI.Combinatorics.KMedianRecovery.Recovery.Computes +OAI.Combinatorics.KMedianRecovery.Recovery.CoordinateRow +OAI.Combinatorics.KMedianRecovery.Recovery.Copies +OAI.Combinatorics.KMedianRecovery.Recovery.CountedTrace +OAI.Combinatorics.KMedianRecovery.Recovery.Coupled +OAI.Combinatorics.KMedianRecovery.Recovery.CoupledFinish +OAI.Combinatorics.KMedianRecovery.Recovery.CoupledInitial +OAI.Combinatorics.KMedianRecovery.Recovery.CoupledLeaf +OAI.Combinatorics.KMedianRecovery.Recovery.CoupledResolve +OAI.Combinatorics.KMedianRecovery.Recovery.CoveredCenter +OAI.Combinatorics.KMedianRecovery.Recovery.CrossCount +OAI.Combinatorics.KMedianRecovery.Recovery.CrossEdge +OAI.Combinatorics.KMedianRecovery.Recovery.Data +OAI.Combinatorics.KMedianRecovery.Recovery.DataHeight +OAI.Combinatorics.KMedianRecovery.Recovery.DecisionOps +OAI.Combinatorics.KMedianRecovery.Recovery.Destination +OAI.Combinatorics.KMedianRecovery.Recovery.DestinationFacility +OAI.Combinatorics.KMedianRecovery.Recovery.Destinations +OAI.Combinatorics.KMedianRecovery.Recovery.DigitBit +OAI.Combinatorics.KMedianRecovery.Recovery.DirectionChoiceErrors +OAI.Combinatorics.KMedianRecovery.Recovery.DisjointFiniteExperiment +OAI.Combinatorics.KMedianRecovery.Recovery.DisjointPool +OAI.Combinatorics.KMedianRecovery.Recovery.DyadicExponent +OAI.Combinatorics.KMedianRecovery.Recovery.DyadicGrid +OAI.Combinatorics.KMedianRecovery.Recovery.DyadicLookup +OAI.Combinatorics.KMedianRecovery.Recovery.EllipsoidForms +OAI.Combinatorics.KMedianRecovery.Recovery.Entry +OAI.Combinatorics.KMedianRecovery.Recovery.EntryFreeMono +OAI.Combinatorics.KMedianRecovery.Recovery.EntryReplay +OAI.Combinatorics.KMedianRecovery.Recovery.EnumeratedBest +OAI.Combinatorics.KMedianRecovery.Recovery.EnumeratedRow +OAI.Combinatorics.KMedianRecovery.Recovery.EvalTrans +OAI.Combinatorics.KMedianRecovery.Recovery.ExchangeAddNonempty +OAI.Combinatorics.KMedianRecovery.Recovery.ExecutionState +OAI.Combinatorics.KMedianRecovery.Recovery.FacePoint +OAI.Combinatorics.KMedianRecovery.Recovery.FaceSelection +OAI.Combinatorics.KMedianRecovery.Recovery.Failure +OAI.Combinatorics.KMedianRecovery.Recovery.FilterItem +OAI.Combinatorics.KMedianRecovery.Recovery.FinImages +OAI.Combinatorics.KMedianRecovery.Recovery.FinishPhase +OAI.Combinatorics.KMedianRecovery.Recovery.FinishSpec +OAI.Combinatorics.KMedianRecovery.Recovery.Finished +OAI.Combinatorics.KMedianRecovery.Recovery.FiniteContext +OAI.Combinatorics.KMedianRecovery.Recovery.FiniteContinuation +OAI.Combinatorics.KMedianRecovery.Recovery.FiniteCross +OAI.Combinatorics.KMedianRecovery.Recovery.FirstPresent +OAI.Combinatorics.KMedianRecovery.Recovery.FnProdEnum +OAI.Combinatorics.KMedianRecovery.Recovery.Form +OAI.Combinatorics.KMedianRecovery.Recovery.FormTrans +OAI.Combinatorics.KMedianRecovery.Recovery.FrameStacks +OAI.Combinatorics.KMedianRecovery.Recovery.Freeze +OAI.Combinatorics.KMedianRecovery.Recovery.Fuel +OAI.Combinatorics.KMedianRecovery.Recovery.GetRow +OAI.Combinatorics.KMedianRecovery.Recovery.GetRow2 +OAI.Combinatorics.KMedianRecovery.Recovery.GreedyOutputExpected +OAI.Combinatorics.KMedianRecovery.Recovery.Grid +OAI.Combinatorics.KMedianRecovery.Recovery.GridFloor +OAI.Combinatorics.KMedianRecovery.Recovery.Guide +OAI.Combinatorics.KMedianRecovery.Recovery.Height +OAI.Combinatorics.KMedianRecovery.Recovery.HitsState +OAI.Combinatorics.KMedianRecovery.Recovery.IfNat +OAI.Combinatorics.KMedianRecovery.Recovery.ImageClass +OAI.Combinatorics.KMedianRecovery.Recovery.ImagePhaseUnion +OAI.Combinatorics.KMedianRecovery.Recovery.IncomingSwapBound +OAI.Combinatorics.KMedianRecovery.Recovery.InflationPos +OAI.Combinatorics.KMedianRecovery.Recovery.InitialAuto +OAI.Combinatorics.KMedianRecovery.Recovery.InitialCorrect +OAI.Combinatorics.KMedianRecovery.Recovery.InitialCoupling +OAI.Combinatorics.KMedianRecovery.Recovery.InitialCoupling2 +OAI.Combinatorics.KMedianRecovery.Recovery.InitialPack +OAI.Combinatorics.KMedianRecovery.Recovery.InitialProject +OAI.Combinatorics.KMedianRecovery.Recovery.InitialRows +OAI.Combinatorics.KMedianRecovery.Recovery.InitialState +OAI.Combinatorics.KMedianRecovery.Recovery.InitialState2 +OAI.Combinatorics.KMedianRecovery.Recovery.Iterate +OAI.Combinatorics.KMedianRecovery.Recovery.IterationBlocks +OAI.Combinatorics.KMedianRecovery.Recovery.KindRows +OAI.Combinatorics.KMedianRecovery.Recovery.Leaf +OAI.Combinatorics.KMedianRecovery.Recovery.LeafBracket +OAI.Combinatorics.KMedianRecovery.Recovery.LeafOrder +OAI.Combinatorics.KMedianRecovery.Recovery.LeafOutcome +OAI.Combinatorics.KMedianRecovery.Recovery.LeafReplay +OAI.Combinatorics.KMedianRecovery.Recovery.LeftNum +OAI.Combinatorics.KMedianRecovery.Recovery.LengthCandidates +OAI.Combinatorics.KMedianRecovery.Recovery.LengthHeight +OAI.Combinatorics.KMedianRecovery.Recovery.LengthPolynomial +OAI.Combinatorics.KMedianRecovery.Recovery.LengthSearch +OAI.Combinatorics.KMedianRecovery.Recovery.ListSetExtra +OAI.Combinatorics.KMedianRecovery.Recovery.Live +OAI.Combinatorics.KMedianRecovery.Recovery.LogSubsetBound +OAI.Combinatorics.KMedianRecovery.Recovery.LowCandidate +OAI.Combinatorics.KMedianRecovery.Recovery.Map +OAI.Combinatorics.KMedianRecovery.Recovery.MaximalSuperset +OAI.Combinatorics.KMedianRecovery.Recovery.MergeCross +OAI.Combinatorics.KMedianRecovery.Recovery.MergePath +OAI.Combinatorics.KMedianRecovery.Recovery.MergeRefine +OAI.Combinatorics.KMedianRecovery.Recovery.Min +OAI.Combinatorics.KMedianRecovery.Recovery.Mono +OAI.Combinatorics.KMedianRecovery.Recovery.Mul +OAI.Combinatorics.KMedianRecovery.Recovery.MulComputes +OAI.Combinatorics.KMedianRecovery.Recovery.NatConnection +OAI.Combinatorics.KMedianRecovery.Recovery.NearEligible +OAI.Combinatorics.KMedianRecovery.Recovery.NearMass +OAI.Combinatorics.KMedianRecovery.Recovery.Next +OAI.Combinatorics.KMedianRecovery.Recovery.Normalize +OAI.Combinatorics.KMedianRecovery.Recovery.NormalizeInput +OAI.Combinatorics.KMedianRecovery.Recovery.NumAbs +OAI.Combinatorics.KMedianRecovery.Recovery.OneStepLower +OAI.Combinatorics.KMedianRecovery.Recovery.Op +OAI.Combinatorics.KMedianRecovery.Recovery.Op2 +OAI.Combinatorics.KMedianRecovery.Recovery.Order +OAI.Combinatorics.KMedianRecovery.Recovery.OrderedMaximum +OAI.Combinatorics.KMedianRecovery.Recovery.OrientedSearch +OAI.Combinatorics.KMedianRecovery.Recovery.Pack +OAI.Combinatorics.KMedianRecovery.Recovery.Pack10 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack11 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack2 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack3 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack4 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack5 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack6 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack7 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack8 +OAI.Combinatorics.KMedianRecovery.Recovery.Pack9 +OAI.Combinatorics.KMedianRecovery.Recovery.PartitionPullback +OAI.Combinatorics.KMedianRecovery.Recovery.PathBounds +OAI.Combinatorics.KMedianRecovery.Recovery.PhasesBounded +OAI.Combinatorics.KMedianRecovery.Recovery.PlanResult +OAI.Combinatorics.KMedianRecovery.Recovery.PolynomialProduct +OAI.Combinatorics.KMedianRecovery.Recovery.Pool +OAI.Combinatorics.KMedianRecovery.Recovery.PowerBound +OAI.Combinatorics.KMedianRecovery.Recovery.ProcessOutputs +OAI.Combinatorics.KMedianRecovery.Recovery.Produce +OAI.Combinatorics.KMedianRecovery.Recovery.Project +OAI.Combinatorics.KMedianRecovery.Recovery.QuadSmulVec +OAI.Combinatorics.KMedianRecovery.Recovery.RawCount +OAI.Combinatorics.KMedianRecovery.Recovery.RawRun +OAI.Combinatorics.KMedianRecovery.Recovery.RawSlices +OAI.Combinatorics.KMedianRecovery.Recovery.RawUnary +OAI.Combinatorics.KMedianRecovery.Recovery.ReachFar +OAI.Combinatorics.KMedianRecovery.Recovery.ReadUnary +OAI.Combinatorics.KMedianRecovery.Recovery.RealFilling +OAI.Combinatorics.KMedianRecovery.Recovery.RealVector +OAI.Combinatorics.KMedianRecovery.Recovery.RealizationChargingAssignment +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryCandidates +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryContext +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryEnumeration +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryFeasible +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryGuesses +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryRepeat +OAI.Combinatorics.KMedianRecovery.Recovery.RecoverySuccess +OAI.Combinatorics.KMedianRecovery.Recovery.RecoveryTrialUniformExponential +OAI.Combinatorics.KMedianRecovery.Recovery.Rectangular +OAI.Combinatorics.KMedianRecovery.Recovery.ReferenceBridge +OAI.Combinatorics.KMedianRecovery.Recovery.RefineMath +OAI.Combinatorics.KMedianRecovery.Recovery.Region +OAI.Combinatorics.KMedianRecovery.Recovery.RegularCardBounds +OAI.Combinatorics.KMedianRecovery.Recovery.RegularChain +OAI.Combinatorics.KMedianRecovery.Recovery.RegularMap +OAI.Combinatorics.KMedianRecovery.Recovery.Removal +OAI.Combinatorics.KMedianRecovery.Recovery.RemovalReplay +OAI.Combinatorics.KMedianRecovery.Recovery.ReverseRow +OAI.Combinatorics.KMedianRecovery.Recovery.Row +OAI.Combinatorics.KMedianRecovery.Recovery.RowInput +OAI.Combinatorics.KMedianRecovery.Recovery.Score +OAI.Combinatorics.KMedianRecovery.Recovery.SetFunction +OAI.Combinatorics.KMedianRecovery.Recovery.ShortPrice +OAI.Combinatorics.KMedianRecovery.Recovery.SingleRadiusRatio +OAI.Combinatorics.KMedianRecovery.Recovery.SmallSubsets +OAI.Combinatorics.KMedianRecovery.Recovery.SortMath +OAI.Combinatorics.KMedianRecovery.Recovery.SqNorm +OAI.Combinatorics.KMedianRecovery.Recovery.Stack +OAI.Combinatorics.KMedianRecovery.Recovery.Stack2 +OAI.Combinatorics.KMedianRecovery.Recovery.StackLength +OAI.Combinatorics.KMedianRecovery.Recovery.State +OAI.Combinatorics.KMedianRecovery.Recovery.State2 +OAI.Combinatorics.KMedianRecovery.Recovery.Step +OAI.Combinatorics.KMedianRecovery.Recovery.Step2 +OAI.Combinatorics.KMedianRecovery.Recovery.StepPack +OAI.Combinatorics.KMedianRecovery.Recovery.StepThen +OAI.Combinatorics.KMedianRecovery.Recovery.Store +OAI.Combinatorics.KMedianRecovery.Recovery.Store2 +OAI.Combinatorics.KMedianRecovery.Recovery.StoredForms +OAI.Combinatorics.KMedianRecovery.Recovery.SubsetSubtypeRepresentative +OAI.Combinatorics.KMedianRecovery.Recovery.Success +OAI.Combinatorics.KMedianRecovery.Recovery.SwapOriginal +OAI.Combinatorics.KMedianRecovery.Recovery.Table +OAI.Combinatorics.KMedianRecovery.Recovery.TableValue +OAI.Combinatorics.KMedianRecovery.Recovery.Threshold +OAI.Combinatorics.KMedianRecovery.Recovery.ThresholdTimesPower +OAI.Combinatorics.KMedianRecovery.Recovery.ToleranceReciprocalBound +OAI.Combinatorics.KMedianRecovery.Recovery.TotalAssignmentExcess +OAI.Combinatorics.KMedianRecovery.Recovery.Value +OAI.Combinatorics.KMedianRecovery.Recovery.Values +OAI.Combinatorics.KMedianRecovery.Recovery.VectorHeight +OAI.Combinatorics.KMedianRecovery.Recovery.Virtual +OAI.Combinatorics.KMedianRecovery.Recovery.VirtualCast +OAI.Combinatorics.KMedianRecovery.Recovery.ZeroClasses +OAI.Combinatorics.KMedianRecovery.Recovery.ZeroObjective +OAI.Combinatorics.KMedianRecovery.Sampling.ExtractPrefix +OAI.Combinatorics.KMedianRecovery.Sampling.FairPrefix +OAI.Combinatorics.KMedianRecovery.Sampling.InverseCDF +OAI.Combinatorics.KMedianRecovery.Sampling.Kernel +OAI.Combinatorics.KMedianRecovery.Sampling.MetricBestProbability +OAI.Combinatorics.KMedianRecovery.Sampling.PrefixData +OAI.Combinatorics.KMedianRecovery.Sampling.PrefixFreeMono +OAI.Combinatorics.KMedianRecovery.Sampling.ProbabilityCompEquiv +OAI.Combinatorics.KMedianRecovery.Sampling.ProbabilityProd +OAI.Combinatorics.KMedianRecovery.Sampling.RationalSampling +OAI.Combinatorics.KMedianRecovery.Sampling.RealizedKernel +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerContext +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerDraw +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerLaw +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerParameters +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerPrefixSuccess +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerResources +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerTraceMachine +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerUpdate +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerUpdateParts +OAI.Combinatorics.KMedianRecovery.Sampling.SamplerWeights +OAI.Combinatorics.KMedianRecovery.Sampling.SamplingPotential +OAI.Combinatorics.KMedianRecovery.Sampling.SamplingRate +OAI.Combinatorics.KMedianRecovery.Sampling.SamplingReference +OAI.Combinatorics.KMedianRecovery.Sampling.SamplingStateMachine +OAI.Combinatorics.KMedianRecovery.Sampling.SeedTensor +OAI.Combinatorics.KMedianRecovery.Sampling.TensorEquiv +OAI.Combinatorics.KMedianRecovery.Sampling.TerminalPrefix +OAI.Combinatorics.KMedianRecovery.Sampling.ZeroFairSuccess +OAI.Combinatorics.KMedianRecovery.Strictness.AssignmentChargesNonneg +OAI.Combinatorics.KMedianRecovery.Strictness.BaselineDual +OAI.Combinatorics.KMedianRecovery.Strictness.BidBound +OAI.Combinatorics.KMedianRecovery.Strictness.BidPoly +OAI.Combinatorics.KMedianRecovery.Strictness.ClientCharge +OAI.Combinatorics.KMedianRecovery.Strictness.Clipped +OAI.Combinatorics.KMedianRecovery.Strictness.ClippedBid +OAI.Combinatorics.KMedianRecovery.Strictness.ClippedMap +OAI.Combinatorics.KMedianRecovery.Strictness.Dual +OAI.Combinatorics.KMedianRecovery.Strictness.DualReindex +OAI.Combinatorics.KMedianRecovery.Strictness.IndexedPaymentCoeff +OAI.Combinatorics.KMedianRecovery.Strictness.LinearPayment +OAI.Combinatorics.KMedianRecovery.Strictness.MetricSurplus +OAI.Combinatorics.KMedianRecovery.Strictness.NormalizedDual +OAI.Combinatorics.KMedianRecovery.Strictness.OpenPaymentZero +OAI.Combinatorics.KMedianRecovery.Strictness.OpenableMap +OAI.Combinatorics.KMedianRecovery.Strictness.RegularDualWitness +OAI.Combinatorics.KMedianRecovery.Strictness.RestrictBits +OAI.Combinatorics.KMedianRecovery.Strictness.SortedDual +OAI.Combinatorics.KMedianRecovery.Strictness.StrictnessGap +OAI.Combinatorics.KMedianRecovery.Strictness.StrictnessGapPos +OAI.Combinatorics.KMedianRecovery.Strictness.SurplusPostprocess +OAI.Combinatorics.KMedianRecovery.Strictness.ValidExecutionClusterStrictness +OAI.Combinatorics.KMedianRecovery.Strictness.ValidExecutionFinalDual diff --git a/tasks/k-median-recovery/solution/reference.py b/tasks/k-median-recovery/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/k-median-recovery/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/k-median-recovery/solution/solve.sh b/tasks/k-median-recovery/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..32344c415aff887f7fe351bd662bb2c233be1609 --- /dev/null +++ b/tasks/k-median-recovery/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KMedianRecovery, i.e. module OAI.Combinatorics.KMedianRecovery.Main and the +# 506 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.KMedianRecovery.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KMedianRecovery" diff --git a/tasks/k-median-recovery/task.toml b/tasks/k-median-recovery/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d2ed944e1f1bcf4ad0f5424996a0aed917abc601 --- /dev/null +++ b/tasks/k-median-recovery/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/k-median-recovery" +version = "1.0.0" +description = "Prove KMedianRecovery (openai/math family 125: The approximation threshold for metric $k$-median) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KMedianRecovery.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KMedianRecovery" +family = "125" +family_title = "The approximation threshold for metric $k$-median" +subject = "Theoretical computer science" +theorems = ["OAI.MetricKMedianRecovery.global_application"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.KMedianRecovery.Main" +reference_modules = 506 +reference_lean_bytes = 3720803 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1362 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15048 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/k-median-recovery/tests/Challenge.lean b/tasks/k-median-recovery/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..05a0f2df5a0661399fd3499ec7bd0d217f87a4f7 --- /dev/null +++ b/tasks/k-median-recovery/tests/Challenge.lean @@ -0,0 +1,107 @@ +import Mathlib + +namespace OAI + +namespace MetricKMedianRecovery + +structure RationalMetricInput where + pointCount : ℕ + distance : Fin pointCount → Fin pointCount → ℚ + clients : Finset (Fin pointCount) + facilities : Finset (Fin pointCount) + budget : ℕ + facilities_nonempty : facilities.Nonempty + budget_pos : 0 < budget + covered : clients ∪ facilities = Finset.univ + distance_nonneg : ∀ x y, 0 ≤ distance x y + distance_self : ∀ x, distance x x = 0 + distance_symm : ∀ x y, distance x y = distance y x + distance_triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +namespace RationalMetricInput + +def size (I : RationalMetricInput) : ℕ := I.clients.card + I.facilities.card + +def Feasible (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : Prop := + S ⊆ I.facilities ∧ S.card ≤ I.budget ∧ (I.clients.Nonempty → S.Nonempty) + +def cost (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : ℚ := + if hS : S.Nonempty then ∑ p ∈ I.clients, S.inf' hS (I.distance p) else 0 + +def comparisonSets (I : RationalMetricInput) : Finset (Finset (Fin I.pointCount)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.budget) + +lemma comparisonSets_nonempty (I : RationalMetricInput) : I.comparisonSets.Nonempty := by + obtain ⟨i, hi⟩ := I.facilities_nonempty + refine ⟨{i}, ?_⟩ + simp only [comparisonSets, Finset.mem_filter, Finset.mem_powerset, + Finset.singleton_subset_iff, Finset.singleton_nonempty, Finset.card_singleton, true_and] + exact ⟨hi, I.budget_pos⟩ + +def optimum (I : RationalMetricInput) : ℚ := + I.comparisonSets.inf' I.comparisonSets_nonempty I.cost + +def natBits (n : ℕ) : List Bool := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +def rationalBits (r : ℚ) : List Bool := + [decide (r < 0)] ++ natBits r.num.natAbs ++ natBits r.den + +def bits (I : RationalMetricInput) : List Bool := + natBits I.pointCount ++ natBits I.budget ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.pointCount => + (List.ofFn (fun j : Fin I.pointCount => rationalBits (I.distance i j))).flatten)).flatten + +def decodeOutput (I : RationalMetricInput) (out : List Bool) : Finset (Fin I.pointCount) := + I.facilities.filter (fun i => out[i.val]?.getD false = true) + +end RationalMetricInput + +def pairBits (p : List Bool × List Bool) : List Bool := + p.1.flatMap (fun b => [true, b]) ++ [false] ++ p.2 + +structure BinaryRandomizedAlgorithm where + randomBits : Polynomial ℕ + run : List Bool × List Bool → List Bool + computation : Turing.TM2ComputableInPolyTime pairBits id run + finiteWorkAlphabet : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + +namespace BinaryRandomizedAlgorithm + +def bitCount (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) : ℕ := + A.randomBits.eval I.bits.length + +abbrev Seed (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) := + Fin (A.bitCount I) → Bool + +def output (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) (s : A.Seed I) : + Finset (Fin I.pointCount) := + I.decodeOutput (A.run (I.bits, List.ofFn s)) + +noncomputable def successProbability (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) + (bound : ℝ) : ℝ := by + classical + exact ((Finset.univ.filter (fun s : A.Seed I => (I.cost (A.output I s) : ℝ) ≤ bound)).card : ℝ) / + 2 ^ (A.bitCount I) + +noncomputable def expectedCost (A : BinaryRandomizedAlgorithm) (I : RationalMetricInput) : ℝ := + (∑ s : A.Seed I, (I.cost (A.output I s) : ℝ)) / 2 ^ (A.bitCount I) + +end BinaryRandomizedAlgorithm + +def globalApplicationClaim : Prop := + ∃ σ : ℝ, 0 < σ ∧ ∀ a : ℝ, 0 < a → ∃ A : BinaryRandomizedAlgorithm, + (∀ (I : RationalMetricInput) (s : A.Seed I), I.Feasible (A.output I s)) ∧ + (∀ I : RationalMetricInput, + 1 - Real.rpow ((I.size : ℝ) + 2) (-a) ≤ + A.successProbability I ((2 - σ) * (I.optimum : ℝ))) ∧ + (∀ I : RationalMetricInput, A.expectedCost I ≤ (2 - σ) * (I.optimum : ℝ)) + +theorem global_application : globalApplicationClaim := by + sorry + +end MetricKMedianRecovery + +end OAI diff --git a/tasks/k-median-recovery/tests/grade.py b/tasks/k-median-recovery/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/k-median-recovery/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/k-median-recovery/tests/task.json b/tasks/k-median-recovery/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b47bbb0a770a98a15fc0e05865315a8afc29a065 --- /dev/null +++ b/tasks/k-median-recovery/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KMedianRecovery", + "comparator": { + "theorem_names": [ + "OAI.MetricKMedianRecovery.global_application" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14148 +} \ No newline at end of file diff --git a/tasks/k-median-recovery/tests/test.sh b/tasks/k-median-recovery/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/k-median-recovery/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/k-median-refined-recovery/environment/Dockerfile b/tasks/k-median-refined-recovery/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/k-median-refined-recovery/environment/fetch_mathlib.sh b/tasks/k-median-refined-recovery/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/k-median-refined-recovery/environment/lake-manifest.json b/tasks/k-median-refined-recovery/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/k-median-refined-recovery/environment/lakefile.lean b/tasks/k-median-refined-recovery/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/k-median-refined-recovery/environment/lean_setup.sh b/tasks/k-median-refined-recovery/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/k-median-refined-recovery/environment/pack_submission.py b/tasks/k-median-refined-recovery/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/k-median-refined-recovery/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/k-median-refined-recovery/instruction.md b/tasks/k-median-refined-recovery/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..99c6b11c2492ffbd329f8df35c9bbf84d84ed701 --- /dev/null +++ b/tasks/k-median-refined-recovery/instruction.md @@ -0,0 +1,218 @@ +# openai/math challenge `KMedianRefinedRecovery` (family 125) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 125 of the release, *The approximation threshold for metric $k$-median* +(Theoretical computer science). The family as a whole: Gives a deterministic polynomial-time $(1+2/e+\varepsilon)$-approximation for finite rational metric $k$-median with specified candidate facilities, for every fixed $\varepsilon>0$. Assuming $P\ne NP$, the optimal infimum approximation factor is $1+2/e$. + +The challenge is `KMedianRefinedRecovery`, also at `/opt/openai-math/challenges/KMedianRefinedRecovery.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MetricKMedianRecovery + +structure RationalMetricInput where + pointCount : ℕ + distance : Fin pointCount → Fin pointCount → ℚ + clients : Finset (Fin pointCount) + facilities : Finset (Fin pointCount) + budget : ℕ + facilities_nonempty : facilities.Nonempty + budget_pos : 0 < budget + covered : clients ∪ facilities = Finset.univ + distance_nonneg : ∀ x y, 0 ≤ distance x y + distance_self : ∀ x, distance x x = 0 + distance_symm : ∀ x y, distance x y = distance y x + distance_triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +namespace RationalMetricInput + +def size (I : RationalMetricInput) : ℕ := I.clients.card + I.facilities.card + +def Feasible (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : Prop := + S ⊆ I.facilities ∧ S.card ≤ I.budget ∧ (I.clients.Nonempty → S.Nonempty) + +def cost (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : ℚ := + if hS : S.Nonempty then ∑ p ∈ I.clients, S.inf' hS (I.distance p) else 0 + +def natBits (n : ℕ) : List Bool := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +def rationalBits (r : ℚ) : List Bool := + [decide (r < 0)] ++ natBits r.num.natAbs ++ natBits r.den + +def bits (I : RationalMetricInput) : List Bool := + natBits I.pointCount ++ natBits I.budget ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.pointCount => + (List.ofFn (fun j : Fin I.pointCount => rationalBits (I.distance i j))).flatten)).flatten + +def decodeOutput (I : RationalMetricInput) (out : List Bool) : Finset (Fin I.pointCount) := + I.facilities.filter (fun i => out[i.val]?.getD false = true) + +end RationalMetricInput + +def pairBits (p : List Bool × List Bool) : List Bool := + p.1.flatMap (fun b => [true, b]) ++ [false] ++ p.2 + +structure BinaryRandomizedAlgorithm where + randomBits : Polynomial ℕ + run : List Bool × List Bool → List Bool + computation : Turing.TM2ComputableInPolyTime pairBits id run + finiteWorkAlphabet : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + + +end MetricKMedianRecovery + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace MetricKMedianRecovery.RefinedRecovery + +structure Input where + metric : RationalMetricInput + disjoint : Disjoint metric.clients metric.facilities + integral : ∀ x y, ∃ z : ℕ, metric.distance x y = (z : ℚ) + positive : ∀ x y, x ≠ y → 0 < metric.distance x y + anchor : Finset (Fin metric.pointCount) + anchor_subset : anchor ⊆ metric.facilities + anchor_card : anchor.card = metric.budget + +namespace Input +abbrev Point (I : Input) := Fin I.metric.pointCount + +def size (I : Input) : ℕ := I.metric.size + +def Bounded (I : Input) (bound : Polynomial ℕ) : Prop := + ∀ x y, I.metric.distance x y ≤ ((bound.eval I.size : ℕ) : ℚ) + +noncomputable def assign (I : Input) (O : Finset I.Point) (p : I.Point) : I.Point := + if h : O.Nonempty then + Classical.choose (Finset.exists_min_image O + (fun i => toLex (I.metric.distance p i, i)) h) + else p + +noncomputable def cluster (I : Input) (O : Finset I.Point) (i : I.Point) : Finset I.Point := + I.metric.clients.filter (fun p => I.assign O p = i) + +noncomputable def clusterCost (I : Input) (O : Finset I.Point) (i : I.Point) : ℝ := + ∑ p ∈ I.cluster O i, (I.metric.distance p i : ℝ) + +def anchorBits (I : Input) : List Bool := + List.ofFn (fun i : I.Point => decide (i ∈ I.anchor)) + +end Input + +structure Certificate (I : Input) (μ : ℚ) (L₀ : ℝ) where + centers : Finset I.Point + centers_subset : centers ⊆ I.metric.facilities + same_card : centers.card = I.anchor.card + positive_cost : 0 < (I.metric.cost centers : ℝ) + good : Finset I.Point + good_subset : good ⊆ centers + proxy : I.Point → I.Point + proxy_mem : ∀ i ∈ good, proxy i ∈ I.anchor + proxy_inj : Set.InjOn proxy (↑good) + proxy_cost : (∑ i ∈ good, ∑ p ∈ I.cluster centers i, + (I.metric.distance p (proxy i) : ℝ)) ≤ + (∑ i ∈ good, I.clusterCost centers i) + (μ : ℝ) * (I.metric.cost centers : ℝ) + few_bad : (((centers \ good).card : ℕ) : ℝ) ≤ L₀ * Real.log (I.size : ℝ) + +noncomputable def precision (ζ : ℝ) : ℕ := + ⌈Real.log (1 / ζ) / Real.log 2⌉₊ + +noncomputable def queryBits (I : Input) (ζ : ℝ) : List Bool := + pairBits (I.metric.bits, I.anchorBits ++ List.replicate (precision ζ) true) + +noncomputable def seedLength (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) : ℕ := + A.randomBits.eval (queryBits I ζ).length + +abbrev Seed (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) := + Fin (seedLength A I ζ) → Bool + +noncomputable def output (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) + (s : Seed A I ζ) : Finset I.Point := + I.metric.decodeOutput (A.run (queryBits I ζ, List.ofFn s)) + +noncomputable def successProbability (A : BinaryRandomizedAlgorithm) (I : Input) + (ζ target : ℝ) : ℝ := by + classical + exact ((Finset.univ.filter (fun s : Seed A I ζ => + (I.metric.cost (output A I ζ s) : ℝ) ≤ target)).card : ℝ) / + 2 ^ seedLength A I ζ + +noncomputable def workBound (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) : ℕ := + (queryBits I ζ).length + seedLength A I ζ + + A.computation.time.eval (pairBits + (queryBits I ζ, List.replicate (seedLength A I ζ) false)).length + +def PolynomialWork (A : BinaryRandomizedAlgorithm) (bound : Polynomial ℕ) : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ d : ℕ, + ∀ I : Input, I.Bounded bound → ∀ ζ : ℝ, 0 < ζ → ζ < 1 → + (workBound A I ζ : ℝ) ≤ + c * ((I.size : ℝ) + 1) ^ d * (1 + Real.log (1 / ζ)) ^ d + + +end MetricKMedianRecovery.RefinedRecovery + +namespace MetricKMedianRecovery.RefinedRecovery + +theorem refined_recovery : + ∀ (bound : Polynomial ℕ) (ε L₀ : ℝ) (μ : ℚ), + 0 < ε → 0 < L₀ → 0 < μ → μ ≤ 1/4 → (μ : ℝ) ≤ ε/12 → + ∃ A : BinaryRandomizedAlgorithm, + PolynomialWork A bound ∧ + ∀ I : Input, I.Bounded bound → ∀ ζ : ℝ, 0 < ζ → ζ < 1 → + (∀ s : Seed A I ζ, I.metric.Feasible (output A I ζ s)) ∧ + (∀ C : Certificate I μ L₀, + 1 - ζ ≤ successProbability A I ζ + ((1 + 2 / Real.exp 1 + ε) * (I.metric.cost C.centers : ℝ))) := by + sorry + +end MetricKMedianRecovery.RefinedRecovery + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KMedianRefinedRecovery.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MetricKMedianRecovery.RefinedRecovery.refined_recovery` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/k-median-refined-recovery/solution/closure.txt b/tasks/k-median-refined-recovery/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c4418b3a600187ce5de287011076b85f9b98a5a --- /dev/null +++ b/tasks/k-median-refined-recovery/solution/closure.txt @@ -0,0 +1,586 @@ +OAI.Combinatorics.KMedian.Analysis.AnalyticEnvelopes +OAI.Combinatorics.KMedian.Analysis.BernsteinFalse +OAI.Combinatorics.KMedian.Analysis.BernsteinTrue +OAI.Combinatorics.KMedian.Analysis.CertificatePolynomials +OAI.Combinatorics.KMedian.Analysis.ChargeTransfer +OAI.Combinatorics.KMedian.Analysis.Coefficients +OAI.Combinatorics.KMedian.Analysis.ComparisonCertificates +OAI.Combinatorics.KMedian.Analysis.FiniteAverages +OAI.Combinatorics.KMedian.Analysis.FiniteComparison +OAI.Combinatorics.KMedian.Analysis.NormalizedTransfer +OAI.Combinatorics.KMedian.Analysis.PolynomialBounds +OAI.Combinatorics.KMedian.Analysis.QuadraticEnvelopes +OAI.Combinatorics.KMedian.Analysis.RowComparison +OAI.Combinatorics.KMedian.Analysis.ScalarCertificates +OAI.Combinatorics.KMedian.Analysis.ScalarTransfer +OAI.Combinatorics.KMedian.Analysis.TaylorBounds +OAI.Combinatorics.KMedian.Analysis.TaylorExpansion +OAI.Combinatorics.KMedian.Binary.BinaryAddition +OAI.Combinatorics.KMedian.Binary.BinaryAutoExtras +OAI.Combinatorics.KMedian.Binary.BinaryAutoFiniteLists +OAI.Combinatorics.KMedian.Binary.BinaryAutomatic +OAI.Combinatorics.KMedian.Binary.BinaryBooleanLists +OAI.Combinatorics.KMedian.Binary.BinaryDivision +OAI.Combinatorics.KMedian.Binary.BinaryDyadicPowers +OAI.Combinatorics.KMedian.Binary.BinaryFloor +OAI.Combinatorics.KMedian.Binary.BinaryGCD +OAI.Combinatorics.KMedian.Binary.BinaryGuard +OAI.Combinatorics.KMedian.Binary.BinaryGuardTotal +OAI.Combinatorics.KMedian.Binary.BinaryInteger +OAI.Combinatorics.KMedian.Binary.BinaryIntegerHeight +OAI.Combinatorics.KMedian.Binary.BinaryIterations +OAI.Combinatorics.KMedian.Binary.BinaryListContext +OAI.Combinatorics.KMedian.Binary.BinaryListExtras +OAI.Combinatorics.KMedian.Binary.BinaryListFold +OAI.Combinatorics.KMedian.Binary.BinaryListIndex +OAI.Combinatorics.KMedian.Binary.BinaryListIndices +OAI.Combinatorics.KMedian.Binary.BinaryListMap +OAI.Combinatorics.KMedian.Binary.BinaryListMapTotal +OAI.Combinatorics.KMedian.Binary.BinaryListSelection +OAI.Combinatorics.KMedian.Binary.BinaryListZip +OAI.Combinatorics.KMedian.Binary.BinaryLists +OAI.Combinatorics.KMedian.Binary.BinaryMatrix +OAI.Combinatorics.KMedian.Binary.BinaryMultiplication +OAI.Combinatorics.KMedian.Binary.BinaryNatSum +OAI.Combinatorics.KMedian.Binary.BinaryNatural +OAI.Combinatorics.KMedian.Binary.BinaryPredicates +OAI.Combinatorics.KMedian.Binary.BinaryRational +OAI.Combinatorics.KMedian.Binary.BinaryRationalFold +OAI.Combinatorics.KMedian.Binary.BinaryRationalHeight +OAI.Combinatorics.KMedian.Binary.BinaryRepeat +OAI.Combinatorics.KMedian.Binary.BinarySubtraction +OAI.Combinatorics.KMedian.Binary.BinaryWords +OAI.Combinatorics.KMedian.Binary.BooleanComposition +OAI.Combinatorics.KMedian.Binary.BooleanEmbedding +OAI.Combinatorics.KMedian.Binary.BooleanEncoding +OAI.Combinatorics.KMedian.Binary.BooleanFinite +OAI.Combinatorics.KMedian.Binary.BooleanListPrimitives +OAI.Combinatorics.KMedian.Binary.BooleanLoop +OAI.Combinatorics.KMedian.Binary.BooleanLoopFrom +OAI.Combinatorics.KMedian.Binary.BooleanMachine +OAI.Combinatorics.KMedian.Binary.BooleanMonomials +OAI.Combinatorics.KMedian.Binary.BooleanParallelTransducer +OAI.Combinatorics.KMedian.Binary.BooleanPolynomial +OAI.Combinatorics.KMedian.Binary.BooleanProducts +OAI.Combinatorics.KMedian.Binary.BooleanRecode +OAI.Combinatorics.KMedian.Binary.BooleanReverse +OAI.Combinatorics.KMedian.Binary.BooleanSum +OAI.Combinatorics.KMedian.Binary.BooleanThread +OAI.Combinatorics.KMedian.Binary.BooleanTransducer +OAI.Combinatorics.KMedian.Binary.InstanceParserProgram +OAI.Combinatorics.KMedian.Binary.NumericParserProgram +OAI.Combinatorics.KMedian.Binary.SequentialParserProgram +OAI.Combinatorics.KMedian.Compression.AffineElimination +OAI.Combinatorics.KMedian.Compression.AffineKernel +OAI.Combinatorics.KMedian.Compression.AffineListCompiler +OAI.Combinatorics.KMedian.Compression.AffineListOperations +OAI.Combinatorics.KMedian.Compression.BoundedDependence +OAI.Combinatorics.KMedian.Compression.CircuitBitBound +OAI.Combinatorics.KMedian.Compression.CompressionBinaryProgram +OAI.Combinatorics.KMedian.Compression.CompressionBounds +OAI.Combinatorics.KMedian.Compression.CompressionListStep +OAI.Combinatorics.KMedian.Compression.ComputedAffineKernel +OAI.Combinatorics.KMedian.Compression.ComputedCompression +OAI.Combinatorics.KMedian.Compression.ComputedCompressionStep +OAI.Combinatorics.KMedian.Compression.ComputedElimination +OAI.Combinatorics.KMedian.Compression.ComputedIntegerKernel +OAI.Combinatorics.KMedian.Compression.ComputedPivot +OAI.Combinatorics.KMedian.Compression.DependentIntegerKernel +OAI.Combinatorics.KMedian.Compression.FinsetVectorExtension +OAI.Combinatorics.KMedian.Compression.FullIntegerKernel +OAI.Combinatorics.KMedian.Compression.GaussianBinaryProgram +OAI.Combinatorics.KMedian.Compression.GaussianCircuit +OAI.Combinatorics.KMedian.Compression.GaussianInputBounds +OAI.Combinatorics.KMedian.Compression.GaussianKernel +OAI.Combinatorics.KMedian.Compression.GaussianListCompiler +OAI.Combinatorics.KMedian.Compression.GaussianListMachine +OAI.Combinatorics.KMedian.Compression.GaussianListOperations +OAI.Combinatorics.KMedian.Compression.GaussianListPivot +OAI.Combinatorics.KMedian.Compression.GaussianListRun +OAI.Combinatorics.KMedian.Compression.GaussianListSemantics +OAI.Combinatorics.KMedian.Compression.GaussianListSize +OAI.Combinatorics.KMedian.Compression.GaussianResidualCertificate +OAI.Combinatorics.KMedian.Compression.GaussianResidualHeight +OAI.Combinatorics.KMedian.Compression.GaussianStates +OAI.Combinatorics.KMedian.Compression.GaussianTabulated +OAI.Combinatorics.KMedian.Compression.GramBounds +OAI.Combinatorics.KMedian.Compression.GramDependence +OAI.Combinatorics.KMedian.Compression.IntegerCoefficientBounds +OAI.Combinatorics.KMedian.Compression.IntegerKernelProgram +OAI.Combinatorics.KMedian.Compression.IntegerListProgram +OAI.Combinatorics.KMedian.Compression.IntegerRationalCompression +OAI.Combinatorics.KMedian.Compression.RationalCompression +OAI.Combinatorics.KMedian.Compression.RationalIntegerLaw +OAI.Combinatorics.KMedian.Compression.RationalKernelHeightSupport +OAI.Combinatorics.KMedian.Compression.RationalOperationHeight +OAI.Combinatorics.KMedian.Compression.RationalScaling +OAI.Combinatorics.KMedian.Geometry.BoundFreeCompression +OAI.Combinatorics.KMedian.Geometry.BundleRounding +OAI.Combinatorics.KMedian.Geometry.ChunkCharges +OAI.Combinatorics.KMedian.Geometry.ComputedInstanceAlgorithm +OAI.Combinatorics.KMedian.Geometry.ComputedRationalCompression +OAI.Combinatorics.KMedian.Geometry.FilteredMoments +OAI.Combinatorics.KMedian.Geometry.FixedBatchTransition +OAI.Combinatorics.KMedian.Geometry.GraphComparison +OAI.Combinatorics.KMedian.Geometry.GraphLaw +OAI.Combinatorics.KMedian.Geometry.GraphListOperations +OAI.Combinatorics.KMedian.Geometry.GraphMoments +OAI.Combinatorics.KMedian.Geometry.GraphRunHeight +OAI.Combinatorics.KMedian.Geometry.GreedyCompletion +OAI.Combinatorics.KMedian.Geometry.GreedyPacking +OAI.Combinatorics.KMedian.Geometry.IntegerBranching +OAI.Combinatorics.KMedian.Geometry.ListSigma +OAI.Combinatorics.KMedian.Geometry.MomentAnalysis +OAI.Combinatorics.KMedian.Geometry.NearestFillingFormula +OAI.Combinatorics.KMedian.Geometry.NearestFractional +OAI.Combinatorics.KMedian.Geometry.NearestReindex +OAI.Combinatorics.KMedian.Geometry.PotentialBounds +OAI.Combinatorics.KMedian.Geometry.RationalAllParameters +OAI.Combinatorics.KMedian.Geometry.RationalBrackets +OAI.Combinatorics.KMedian.Geometry.RationalBundleGeometry +OAI.Combinatorics.KMedian.Geometry.RationalCompletedCost +OAI.Combinatorics.KMedian.Geometry.RationalFractionalInput +OAI.Combinatorics.KMedian.Geometry.RationalFractionalScan +OAI.Combinatorics.KMedian.Geometry.RationalGeometryScan +OAI.Combinatorics.KMedian.Geometry.RationalGridRound +OAI.Combinatorics.KMedian.Geometry.RationalHistoryCompletion +OAI.Combinatorics.KMedian.Geometry.RationalHistorySelection +OAI.Combinatorics.KMedian.Geometry.RationalHistoryValid +OAI.Combinatorics.KMedian.Geometry.RationalImageCost +OAI.Combinatorics.KMedian.Geometry.RationalIndexedCost +OAI.Combinatorics.KMedian.Geometry.RationalInstanceCost +OAI.Combinatorics.KMedian.Geometry.RationalIntervals +OAI.Combinatorics.KMedian.Geometry.RationalNearestCopies +OAI.Combinatorics.KMedian.Geometry.RationalParameterizedHistory +OAI.Combinatorics.KMedian.Geometry.RationalSparseTaper +OAI.Combinatorics.KMedian.Geometry.RationalSplitEnumeration +OAI.Combinatorics.KMedian.Geometry.RationalSplitInput +OAI.Combinatorics.KMedian.Geometry.RationalSplitting +OAI.Combinatorics.KMedian.Geometry.RationalUnitInput +OAI.Combinatorics.KMedian.Geometry.RationalUnitScan +OAI.Combinatorics.KMedian.Geometry.SortedListEncoding +OAI.Combinatorics.KMedian.Geometry.TimeAdvance +OAI.Combinatorics.KMedian.Geometry.TrimIntegerLaw +OAI.Combinatorics.KMedian.Geometry.UniformDrift +OAI.Combinatorics.KMedian.Instance +OAI.Combinatorics.KMedian.Main +OAI.Combinatorics.KMedian.Model +OAI.Combinatorics.KMedian.Optimization.ApproximateFractional +OAI.Combinatorics.KMedian.Optimization.ApproximateLPSelection +OAI.Combinatorics.KMedian.Optimization.ApproximationListProgram +OAI.Combinatorics.KMedian.Optimization.ApproximationSlack +OAI.Combinatorics.KMedian.Optimization.ComputedNearest +OAI.Combinatorics.KMedian.Optimization.DualListCompiler +OAI.Combinatorics.KMedian.Optimization.DualListOperations +OAI.Combinatorics.KMedian.Optimization.FractionalDual +OAI.Combinatorics.KMedian.Optimization.FractionalInputProgram +OAI.Combinatorics.KMedian.Optimization.FractionalListChecks +OAI.Combinatorics.KMedian.Optimization.FractionalScanProgram +OAI.Combinatorics.KMedian.Optimization.FractionalSelectProgram +OAI.Combinatorics.KMedian.Optimization.GradientDenominator +OAI.Combinatorics.KMedian.Optimization.IndexedInstanceLP +OAI.Combinatorics.KMedian.Optimization.IntegralFractionalComparison +OAI.Combinatorics.KMedian.Optimization.LPBinaryInput +OAI.Combinatorics.KMedian.Optimization.LPBinaryStart +OAI.Combinatorics.KMedian.Optimization.LPBinaryTrajectory +OAI.Combinatorics.KMedian.Optimization.LPListFacts +OAI.Combinatorics.KMedian.Optimization.LPMinimumSelection +OAI.Combinatorics.KMedian.Optimization.MatrixNormalization +OAI.Combinatorics.KMedian.Optimization.OptimizationBitBound +OAI.Combinatorics.KMedian.Optimization.ProjectedSubgradient +OAI.Combinatorics.KMedian.Optimization.RationalArgmin +OAI.Combinatorics.KMedian.Optimization.SimplexDiameter +OAI.Combinatorics.KMedian.Optimization.SimplexListProgram +OAI.Combinatorics.KMedian.Optimization.SimplexProjection +OAI.Combinatorics.KMedian.Optimization.SubgradientDenominator +OAI.Combinatorics.KMedian.Optimization.SubgradientTrajectoryHeight +OAI.Combinatorics.KMedian.Optimization.TruncatedListCompiler +OAI.Combinatorics.KMedian.Optimization.TruncatedListOperations +OAI.Combinatorics.KMedian.Optimization.TruncatedObjective +OAI.Combinatorics.KMedian.Optimization.TruncatedOptimization +OAI.Combinatorics.KMedian.Optimization.TruncatedRepair +OAI.Combinatorics.KMedian.Optimization.ZeroCostBranch +OAI.Combinatorics.KMedian.Preparation.AssignmentCopies +OAI.Combinatorics.KMedian.Preparation.AssignmentRepair +OAI.Combinatorics.KMedian.Preparation.CoupledGeometry +OAI.Combinatorics.KMedian.Preparation.CoupledNoise +OAI.Combinatorics.KMedian.Preparation.CoupledPreparation +OAI.Combinatorics.KMedian.Preparation.CoupledReindex +OAI.Combinatorics.KMedian.Preparation.CoupledWeights +OAI.Combinatorics.KMedian.Preparation.DistantAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyBall +OAI.Combinatorics.KMedian.Preparation.NearestAssignmentGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationClientAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationCostGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationDeficits +OAI.Combinatorics.KMedian.Preparation.PreparationGrid +OAI.Combinatorics.KMedian.Preparation.PreparationInner +OAI.Combinatorics.KMedian.Preparation.PreparationMoments +OAI.Combinatorics.KMedian.Preparation.PreparationNoise +OAI.Combinatorics.KMedian.Preparation.PreparationOldCost +OAI.Combinatorics.KMedian.Preparation.PreparationOutcome +OAI.Combinatorics.KMedian.Preparation.PreparationOuter +OAI.Combinatorics.KMedian.Preparation.PreparationParameters +OAI.Combinatorics.KMedian.Preparation.PreparationRescaling +OAI.Combinatorics.KMedian.Preparation.PreparationStars +OAI.Combinatorics.KMedian.Preparation.PreparationSubsetNoise +OAI.Combinatorics.KMedian.Preparation.PreparedDataOperations +OAI.Combinatorics.KMedian.Preparation.PreparedKernelProgram +OAI.Combinatorics.KMedian.Preparation.PreparedLawProgram +OAI.Combinatorics.KMedian.Preparation.PreparedScanProgram +OAI.Combinatorics.KMedian.Preparation.RationalPreparedScan +OAI.Combinatorics.KMedian.Preparation.RationalRepresentatives +OAI.Combinatorics.KMedian.Preparation.RationalSupplierPreparation +OAI.Combinatorics.KMedian.Preparation.RationalSupplierScan +OAI.Combinatorics.KMedian.Preparation.RepresentativeBundles +OAI.Combinatorics.KMedian.Preparation.RepresentativeGeometry +OAI.Combinatorics.KMedian.Preparation.RepresentativeProgram +OAI.Combinatorics.KMedian.Preparation.RetainedActivations +OAI.Combinatorics.KMedian.Preparation.SelectedPreparationOutcome +OAI.Combinatorics.KMedian.Preparation.ShortfallByDeviation +OAI.Combinatorics.KMedian.Preparation.SupplierAllocation +OAI.Combinatorics.KMedian.Preparation.SupplierCharges +OAI.Combinatorics.KMedian.Preparation.SupplierGeometry +OAI.Combinatorics.KMedian.Preparation.SupplierListOperations +OAI.Combinatorics.KMedian.Preparation.SupplierMap +OAI.Combinatorics.KMedian.Preparation.SupplierPreparationProgram +OAI.Combinatorics.KMedian.Preparation.SupplierScanProgram +OAI.Combinatorics.KMedian.Preparation.SupportRepair +OAI.Combinatorics.KMedian.Probability.BernoulliBatches +OAI.Combinatorics.KMedian.Probability.BernoulliListOperations +OAI.Combinatorics.KMedian.Probability.BernoulliPolynomial +OAI.Combinatorics.KMedian.Probability.BernoulliRealTransfer +OAI.Combinatorics.KMedian.Probability.BernoulliReindex +OAI.Combinatorics.KMedian.Probability.BernoulliRunHeight +OAI.Combinatorics.KMedian.Probability.BernoulliRunProgram +OAI.Combinatorics.KMedian.Probability.BernoulliSquare +OAI.Combinatorics.KMedian.Probability.BernoulliStepProgram +OAI.Combinatorics.KMedian.Probability.BernoulliVariance +OAI.Combinatorics.KMedian.Probability.Conditioning +OAI.Combinatorics.KMedian.Probability.FiniteClipping +OAI.Combinatorics.KMedian.Probability.FiniteJoint +OAI.Combinatorics.KMedian.Probability.FiniteKernels +OAI.Combinatorics.KMedian.Probability.FiniteLawConstructions +OAI.Combinatorics.KMedian.Probability.FiniteLaws +OAI.Combinatorics.KMedian.Probability.FiniteProcess +OAI.Combinatorics.KMedian.Probability.FiniteVariance +OAI.Combinatorics.KMedian.Probability.NegativeStars +OAI.Combinatorics.KMedian.Probability.NonnegativeRounding +OAI.Combinatorics.KMedian.Probability.ProbabilitySupport +OAI.Combinatorics.KMedian.Probability.PushforwardLaw +OAI.Combinatorics.KMedian.Probability.SignedPartial +OAI.Combinatorics.KMedian.Probability.SignedStars +OAI.Combinatorics.KMedian.Probability.SumLaws +OAI.Combinatorics.KMedian.Probability.SupportedLaw +OAI.Combinatorics.KMedian.Process.ActionDegrees +OAI.Combinatorics.KMedian.Process.ActionTransitionList +OAI.Combinatorics.KMedian.Process.ActualActions +OAI.Combinatorics.KMedian.Process.AdaptiveCount +OAI.Combinatorics.KMedian.Process.AveragedCount +OAI.Combinatorics.KMedian.Process.AveragedDrift +OAI.Combinatorics.KMedian.Process.AveragedGenerator +OAI.Combinatorics.KMedian.Process.BackupGeometry +OAI.Combinatorics.KMedian.Process.BackupInvariant +OAI.Combinatorics.KMedian.Process.BatchActionArrays +OAI.Combinatorics.KMedian.Process.BatchActionCodes +OAI.Combinatorics.KMedian.Process.BatchActionList +OAI.Combinatorics.KMedian.Process.BatchEstimate +OAI.Combinatorics.KMedian.Process.BatchGraphData +OAI.Combinatorics.KMedian.Process.BatchOrdinalArrays +OAI.Combinatorics.KMedian.Process.BatchOrdinalCodes +OAI.Combinatorics.KMedian.Process.BatchProposalProgram +OAI.Combinatorics.KMedian.Process.BatchUniform +OAI.Combinatorics.KMedian.Process.ConditionalRoundDrift +OAI.Combinatorics.KMedian.Process.CopyGraphProgram +OAI.Combinatorics.KMedian.Process.CopyListEncoding +OAI.Combinatorics.KMedian.Process.CopyNearestProgram +OAI.Combinatorics.KMedian.Process.CopyNextProgram +OAI.Combinatorics.KMedian.Process.CopyRound +OAI.Combinatorics.KMedian.Process.CopyState +OAI.Combinatorics.KMedian.Process.CopyTransport +OAI.Combinatorics.KMedian.Process.CountGeometry +OAI.Combinatorics.KMedian.Process.CountInstantiation +OAI.Combinatorics.KMedian.Process.CountListOperations +OAI.Combinatorics.KMedian.Process.CountRunHeight +OAI.Combinatorics.KMedian.Process.CountRunProgram +OAI.Combinatorics.KMedian.Process.CountSize +OAI.Combinatorics.KMedian.Process.CountSource +OAI.Combinatorics.KMedian.Process.CountStepProgram +OAI.Combinatorics.KMedian.Process.CountTail +OAI.Combinatorics.KMedian.Process.CountVariance +OAI.Combinatorics.KMedian.Process.CountsMaskProgram +OAI.Combinatorics.KMedian.Process.ErasureDecay +OAI.Combinatorics.KMedian.Process.FiniteGraph +OAI.Combinatorics.KMedian.Process.ForceBatchBound +OAI.Combinatorics.KMedian.Process.ForcedLocal +OAI.Combinatorics.KMedian.Process.ForcedTransition +OAI.Combinatorics.KMedian.Process.FrozenBatchBound +OAI.Combinatorics.KMedian.Process.FullBatchBound +OAI.Combinatorics.KMedian.Process.GeneratorAverage +OAI.Combinatorics.KMedian.Process.GeneratorBound +OAI.Combinatorics.KMedian.Process.GroupCap +OAI.Combinatorics.KMedian.Process.HeavyActions +OAI.Combinatorics.KMedian.Process.LocalBatchUniform +OAI.Combinatorics.KMedian.Process.LocalForceScale +OAI.Combinatorics.KMedian.Process.PhaseBatchBound +OAI.Combinatorics.KMedian.Process.PhysicalBatchLaw +OAI.Combinatorics.KMedian.Process.PhysicalBatchList +OAI.Combinatorics.KMedian.Process.PhysicalBatchProgram +OAI.Combinatorics.KMedian.Process.PhysicalBatchUpdateProgram +OAI.Combinatorics.KMedian.Process.PhysicalCountGeometry +OAI.Combinatorics.KMedian.Process.PhysicalCountLaw +OAI.Combinatorics.KMedian.Process.PhysicalHistoriesProgram +OAI.Combinatorics.KMedian.Process.PhysicalOldMass +OAI.Combinatorics.KMedian.Process.PhysicalPotential +OAI.Combinatorics.KMedian.Process.PhysicalProcess +OAI.Combinatorics.KMedian.Process.PhysicalRound +OAI.Combinatorics.KMedian.Process.PhysicalRoundProgram +OAI.Combinatorics.KMedian.Process.PhysicalState +OAI.Combinatorics.KMedian.Process.ProcessCompletion +OAI.Combinatorics.KMedian.Process.QuadraticCount +OAI.Combinatorics.KMedian.Process.RoundCountsProgram +OAI.Combinatorics.KMedian.Process.RoundParameters +OAI.Combinatorics.KMedian.Process.RoundWithCount +OAI.Combinatorics.KMedian.Process.RoundingCoordinateHeight +OAI.Combinatorics.KMedian.Process.RoundingListOperations +OAI.Combinatorics.KMedian.Process.RoundingRunHeight +OAI.Combinatorics.KMedian.Process.RoundingRunProgram +OAI.Combinatorics.KMedian.Process.RoundingStateCompiler +OAI.Combinatorics.KMedian.Process.RoundingUniformStep +OAI.Combinatorics.KMedian.Process.SourceAverage +OAI.Combinatorics.KMedian.Process.SourceBalance +OAI.Combinatorics.KMedian.Process.SourceDriftLaw +OAI.Combinatorics.KMedian.Process.SourceGenerator +OAI.Combinatorics.KMedian.Process.StateInvariants +OAI.Combinatorics.KMedian.Process.SurvivalProbability +OAI.Combinatorics.KMedian.Process.Taper +OAI.Combinatorics.KMedian.Process.TaperAllProgram +OAI.Combinatorics.KMedian.Process.TaperData +OAI.Combinatorics.KMedian.Process.TaperGraph +OAI.Combinatorics.KMedian.Process.TaperGraphProgram +OAI.Combinatorics.KMedian.Process.TaperListProgram +OAI.Combinatorics.KMedian.Process.TaperReindex +OAI.Combinatorics.KMedian.Process.UnbalancedActions +OAI.Combinatorics.KMedian.Programs.BoundedEnumerationProgram +OAI.Combinatorics.KMedian.Programs.BranchProgram +OAI.Combinatorics.KMedian.Programs.BundleGeometryProgram +OAI.Combinatorics.KMedian.Programs.BundlesProgram +OAI.Combinatorics.KMedian.Programs.CardinalRoundProgram +OAI.Combinatorics.KMedian.Programs.DependentSparseProgram +OAI.Combinatorics.KMedian.Programs.FinalSelectionProgram +OAI.Combinatorics.KMedian.Programs.FinsetMaskProgram +OAI.Combinatorics.KMedian.Programs.GraphLawProgram +OAI.Combinatorics.KMedian.Programs.GraphRunProgram +OAI.Combinatorics.KMedian.Programs.GraphStepProgram +OAI.Combinatorics.KMedian.Programs.GreedyPackingProgram +OAI.Combinatorics.KMedian.Programs.HistorySelectionProgram +OAI.Combinatorics.KMedian.Programs.InstanceComputedPseudo +OAI.Combinatorics.KMedian.Programs.InstanceDataProgram +OAI.Combinatorics.KMedian.Programs.InstanceFractionalRound +OAI.Combinatorics.KMedian.Programs.InstanceRoundProgram +OAI.Combinatorics.KMedian.Programs.InstanceRounding +OAI.Combinatorics.KMedian.Programs.InstanceZeroProgram +OAI.Combinatorics.KMedian.Programs.LastFractionProgram +OAI.Combinatorics.KMedian.Programs.MaskBestProgram +OAI.Combinatorics.KMedian.Programs.MaximumProgram +OAI.Combinatorics.KMedian.Programs.NearestListProgram +OAI.Combinatorics.KMedian.Programs.NearestMaskProgram +OAI.Combinatorics.KMedian.Programs.OriginalMaskProgram +OAI.Combinatorics.KMedian.Programs.OuterLawProgram +OAI.Combinatorics.KMedian.Programs.PivotListProgram +OAI.Combinatorics.KMedian.Programs.RationalFeatureProgram +OAI.Combinatorics.KMedian.Programs.RationalSortProgram +OAI.Combinatorics.KMedian.Programs.RestrictionProgram +OAI.Combinatorics.KMedian.Programs.ScaleListProgram +OAI.Combinatorics.KMedian.Programs.ScoreProgram +OAI.Combinatorics.KMedian.Programs.SplitListProgram +OAI.Combinatorics.KMedian.Programs.StarActivationProgram +OAI.Combinatorics.KMedian.Programs.TaggedBestProgram +OAI.Combinatorics.KMedian.Programs.UnitGeometryProgram +OAI.Combinatorics.KMedian.Programs.UnitRepresentativeProgram +OAI.Combinatorics.KMedian.Programs.UnitScanProgram +OAI.Combinatorics.KMedian.Reduction.BadCenterBound +OAI.Combinatorics.KMedian.Reduction.BudgetReduction +OAI.Combinatorics.KMedian.Reduction.CloseFromServing +OAI.Combinatorics.KMedian.Reduction.CompletionEndpoint +OAI.Combinatorics.KMedian.Reduction.CompletionEnumeration +OAI.Combinatorics.KMedian.Reduction.CompletionGeometry +OAI.Combinatorics.KMedian.Reduction.CompletionMaskProgram +OAI.Combinatorics.KMedian.Reduction.CompletionProgram +OAI.Combinatorics.KMedian.Reduction.CompletionSelection +OAI.Combinatorics.KMedian.Reduction.DeletionEndpoint +OAI.Combinatorics.KMedian.Reduction.DeletionGeometry +OAI.Combinatorics.KMedian.Reduction.DeletionHistory +OAI.Combinatorics.KMedian.Reduction.DeletionProgram +OAI.Combinatorics.KMedian.Reduction.LocalCompletion +OAI.Combinatorics.KMedian.Reduction.LocalCompletionProgram +OAI.Combinatorics.KMedian.Reduction.NormalizationGuesses +OAI.Combinatorics.KMedian.Reduction.OrdinaryListProgram +OAI.Combinatorics.KMedian.Reduction.RadiusPacking +OAI.Combinatorics.KMedian.Reduction.RationalCompletion +OAI.Combinatorics.KMedian.Reduction.RationalDeletion +OAI.Combinatorics.KMedian.Reduction.RationalGreedyCompletion +OAI.Combinatorics.KMedian.Reduction.RationalLocalChoice +OAI.Combinatorics.KMedian.Reduction.RationalThreshold +OAI.Combinatorics.KMedian.Reduction.ReductionClosure +OAI.Combinatorics.KMedian.Reduction.ReductionCostProgram +OAI.Combinatorics.KMedian.Reduction.ReductionOutcomesProgram +OAI.Combinatorics.KMedian.Reduction.Sparsification +OAI.Combinatorics.KMedian.Reduction.SparsifyEnumeration +OAI.Combinatorics.KMedian.Rounding.ExactRounding +OAI.Combinatorics.KMedian.Rounding.ExceptionalStar +OAI.Combinatorics.KMedian.Rounding.GridClipping +OAI.Combinatorics.KMedian.Rounding.GridDataProgram +OAI.Combinatorics.KMedian.Rounding.GridEndpoint +OAI.Combinatorics.KMedian.Rounding.GridRounding +OAI.Combinatorics.KMedian.Rounding.GridRoundingProgram +OAI.Combinatorics.KMedian.Rounding.IntegerSimplexProjection +OAI.Combinatorics.KMedian.Rounding.MarginalRounding +OAI.Combinatorics.KMedian.Rounding.RationalBatchData +OAI.Combinatorics.KMedian.Rounding.RationalBatchEnumeration +OAI.Combinatorics.KMedian.Rounding.RationalBatchFacts +OAI.Combinatorics.KMedian.Rounding.RationalCopyTransition +OAI.Combinatorics.KMedian.Rounding.RationalLastFraction +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraph +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraphInstance +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistorySurvival +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalInvariant +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalKernel +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalReplay +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalProposalBound +OAI.Combinatorics.KMedian.Rounding.RationalProposalCount +OAI.Combinatorics.KMedian.Rounding.RationalProposalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalRetain +OAI.Combinatorics.KMedian.Rounding.RationalRoundEvents +OAI.Combinatorics.KMedian.Rounding.RationalRoundParameters +OAI.Combinatorics.KMedian.Rounding.RationalRounding +OAI.Combinatorics.KMedian.Rounding.RationalSignedStep +OAI.Combinatorics.KMedian.Rounding.RationalSignedTerminal +OAI.Combinatorics.KMedian.Rounding.RationalTaper +OAI.Combinatorics.KMedian.Rounding.RationalTaperAffine +OAI.Combinatorics.KMedian.Rounding.RationalTaperCandidates +OAI.Combinatorics.KMedian.Rounding.RationalTaperData +OAI.Combinatorics.KMedian.Rounding.RationalTaperZero +OAI.Combinatorics.KMedian.Rounding.RationalWeightedInvariants +OAI.Combinatorics.KMedian.Rounding.RationalWeightedStep +OAI.Combinatorics.KMedian.Rounding.SignedGridInvariant +OAI.Combinatorics.KMedian.Rounding.SignedListOperations +OAI.Combinatorics.KMedian.Rounding.SignedPreparationProgram +OAI.Combinatorics.KMedian.Rounding.SignedRoundProgram +OAI.Combinatorics.KMedian.Rounding.SignedTerminalProgram +OAI.Combinatorics.KMedian.Rounding.TargetSubset +OAI.Combinatorics.KMedian.Rounding.TargetSubsetProgram +OAI.Combinatorics.KMedian.Rounding.UniformSplitRounding +OAI.Combinatorics.KMedian.Rounding.WeightedGridInvariant +OAI.Combinatorics.KMedian.Rounding.WeightedPartial +OAI.Combinatorics.KMedian.Rounding.WeightedRounding +OAI.Combinatorics.KMedian.Sparse.SparseAffineMoments +OAI.Combinatorics.KMedian.Sparse.SparseAlgorithm +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliFeatures +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliRun +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSubsets +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSupport +OAI.Combinatorics.KMedian.Sparse.SparseBind +OAI.Combinatorics.KMedian.Sparse.SparseBindProgram +OAI.Combinatorics.KMedian.Sparse.SparseBoundedCount +OAI.Combinatorics.KMedian.Sparse.SparseBoundedDrift +OAI.Combinatorics.KMedian.Sparse.SparseBoundedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseBranchProgram +OAI.Combinatorics.KMedian.Sparse.SparseBundleEncoding +OAI.Combinatorics.KMedian.Sparse.SparseBundleLaw +OAI.Combinatorics.KMedian.Sparse.SparseCardinalFixed +OAI.Combinatorics.KMedian.Sparse.SparseCardinalRounding +OAI.Combinatorics.KMedian.Sparse.SparseCompressProgram +OAI.Combinatorics.KMedian.Sparse.SparseConditionalCount +OAI.Combinatorics.KMedian.Sparse.SparseConditionalRoundDrift +OAI.Combinatorics.KMedian.Sparse.SparseCountFeatures +OAI.Combinatorics.KMedian.Sparse.SparseCountInstantiation +OAI.Combinatorics.KMedian.Sparse.SparseCountRun +OAI.Combinatorics.KMedian.Sparse.SparseCountStatistic +OAI.Combinatorics.KMedian.Sparse.SparseCoupledPreparation +OAI.Combinatorics.KMedian.Sparse.SparseDeletion +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedBatch +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedCount +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedEstimate +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFrozen +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFull +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraph +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedMixture +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseFiltered +OAI.Combinatorics.KMedian.Sparse.SparseGraphFeatures +OAI.Combinatorics.KMedian.Sparse.SparseGraphLaw +OAI.Combinatorics.KMedian.Sparse.SparseGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseGraphRun +OAI.Combinatorics.KMedian.Sparse.SparseGridRounding +OAI.Combinatorics.KMedian.Sparse.SparseGridZero +OAI.Combinatorics.KMedian.Sparse.SparseHistories +OAI.Combinatorics.KMedian.Sparse.SparseHistoryBounds +OAI.Combinatorics.KMedian.Sparse.SparseIntegerLaw +OAI.Combinatorics.KMedian.Sparse.SparseIterationHeight +OAI.Combinatorics.KMedian.Sparse.SparseListTrim +OAI.Combinatorics.KMedian.Sparse.SparseLocalBatch +OAI.Combinatorics.KMedian.Sparse.SparseMap +OAI.Combinatorics.KMedian.Sparse.SparseMapBind +OAI.Combinatorics.KMedian.Sparse.SparseMarginal +OAI.Combinatorics.KMedian.Sparse.SparseMarginalTools +OAI.Combinatorics.KMedian.Sparse.SparseMixProgram +OAI.Combinatorics.KMedian.Sparse.SparseMixture +OAI.Combinatorics.KMedian.Sparse.SparseMomentAlgebra +OAI.Combinatorics.KMedian.Sparse.SparseNonnegativeSupport +OAI.Combinatorics.KMedian.Sparse.SparseOuterCounts +OAI.Combinatorics.KMedian.Sparse.SparseOuterLaw +OAI.Combinatorics.KMedian.Sparse.SparseOuterMoments +OAI.Combinatorics.KMedian.Sparse.SparseOuterReal +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalBatch +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalCount +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalSurvival +OAI.Combinatorics.KMedian.Sparse.SparsePreparedBudget +OAI.Combinatorics.KMedian.Sparse.SparsePreparedLaw +OAI.Combinatorics.KMedian.Sparse.SparsePreparedMoments +OAI.Combinatorics.KMedian.Sparse.SparsePreparedProbability +OAI.Combinatorics.KMedian.Sparse.SparseProduct +OAI.Combinatorics.KMedian.Sparse.SparseProductProgram +OAI.Combinatorics.KMedian.Sparse.SparseRealExpectation +OAI.Combinatorics.KMedian.Sparse.SparseRealLaw +OAI.Combinatorics.KMedian.Sparse.SparseReduction +OAI.Combinatorics.KMedian.Sparse.SparseRescaledInner +OAI.Combinatorics.KMedian.Sparse.SparseSelect +OAI.Combinatorics.KMedian.Sparse.SparseSignedBudget +OAI.Combinatorics.KMedian.Sparse.SparseSignedFixed +OAI.Combinatorics.KMedian.Sparse.SparseSignedPartial +OAI.Combinatorics.KMedian.Sparse.SparseSignedPreparation +OAI.Combinatorics.KMedian.Sparse.SparseSignedRounding +OAI.Combinatorics.KMedian.Sparse.SparseStarActivation +OAI.Combinatorics.KMedian.Sparse.SparseSupplierSupport +OAI.Combinatorics.KMedian.Sparse.SparseSupport +OAI.Combinatorics.KMedian.Sparse.SparseSurvival +OAI.Combinatorics.KMedian.Sparse.SparseTable +OAI.Combinatorics.KMedian.Sparse.SparseTargetSubset +OAI.Combinatorics.KMedian.Sparse.SparseWeightedPartial +OAI.Combinatorics.KMedian.Sparse.SparseWeightedRounding +OAI.Combinatorics.KMedianRecovery.Encoding.Reencode +OAI.Combinatorics.KMedianRecovery.Geometry.NearestDistance +OAI.Combinatorics.KMedianRecovery.Machines.Program +OAI.Combinatorics.KMedianRecovery.Model +OAI.Combinatorics.KMedianRecovery.Recovery.ExecutionState +OAI.Combinatorics.KMedianRecovery.Recovery.Form +OAI.Combinatorics.KMedianRecovery.Recovery.Row +OAI.Combinatorics.KMedianRecovery.Recovery.Stack +OAI.Combinatorics.KMedianRecovery.Recovery.StackLength +OAI.Combinatorics.KMedianRecovery.Recovery.StepThen +OAI.Combinatorics.KMedianRecovery.Refined.CheckedInput +OAI.Combinatorics.KMedianRecovery.Refined.ConditionalRecovery +OAI.Combinatorics.KMedianRecovery.Refined.Model +OAI.Combinatorics.KMedianRecovery.Refined.Recovery +OAI.Combinatorics.KMedianRecovery.Refined.ThresholdInput +OAI.Combinatorics.KMedianRecovery.Refined.Work +OAI.Combinatorics.KMedianRecovery.Sampling.ExtractPrefix diff --git a/tasks/k-median-refined-recovery/solution/reference.py b/tasks/k-median-refined-recovery/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/k-median-refined-recovery/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/k-median-refined-recovery/solution/solve.sh b/tasks/k-median-refined-recovery/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f970639602487e234a30c930306d5df831848d27 --- /dev/null +++ b/tasks/k-median-refined-recovery/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KMedianRefinedRecovery, i.e. module OAI.Combinatorics.KMedianRecovery.Refined.Recovery and the +# 586 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.KMedianRecovery.Refined.Recovery /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KMedianRefinedRecovery" diff --git a/tasks/k-median-refined-recovery/task.toml b/tasks/k-median-refined-recovery/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d669f2399325c90a9f9fc74392b6960bc2a3616d --- /dev/null +++ b/tasks/k-median-refined-recovery/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/k-median-refined-recovery" +version = "1.0.0" +description = "Prove KMedianRefinedRecovery (openai/math family 125: The approximation threshold for metric $k$-median) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KMedianRefinedRecovery.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KMedianRefinedRecovery" +family = "125" +family_title = "The approximation threshold for metric $k$-median" +subject = "Theoretical computer science" +theorems = ["OAI.MetricKMedianRecovery.RefinedRecovery.refined_recovery"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.KMedianRecovery.Refined.Recovery" +reference_modules = 586 +reference_lean_bytes = 2580016 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1849 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14022 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/k-median-refined-recovery/tests/Challenge.lean b/tasks/k-median-refined-recovery/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..24a108afa2d33ba0f54926a51e5de42f05beb1c0 --- /dev/null +++ b/tasks/k-median-refined-recovery/tests/Challenge.lean @@ -0,0 +1,167 @@ +import Mathlib + +namespace OAI + +namespace MetricKMedianRecovery + +structure RationalMetricInput where + pointCount : ℕ + distance : Fin pointCount → Fin pointCount → ℚ + clients : Finset (Fin pointCount) + facilities : Finset (Fin pointCount) + budget : ℕ + facilities_nonempty : facilities.Nonempty + budget_pos : 0 < budget + covered : clients ∪ facilities = Finset.univ + distance_nonneg : ∀ x y, 0 ≤ distance x y + distance_self : ∀ x, distance x x = 0 + distance_symm : ∀ x y, distance x y = distance y x + distance_triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +namespace RationalMetricInput + +def size (I : RationalMetricInput) : ℕ := I.clients.card + I.facilities.card + +def Feasible (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : Prop := + S ⊆ I.facilities ∧ S.card ≤ I.budget ∧ (I.clients.Nonempty → S.Nonempty) + +def cost (I : RationalMetricInput) (S : Finset (Fin I.pointCount)) : ℚ := + if hS : S.Nonempty then ∑ p ∈ I.clients, S.inf' hS (I.distance p) else 0 + +def natBits (n : ℕ) : List Bool := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +def rationalBits (r : ℚ) : List Bool := + [decide (r < 0)] ++ natBits r.num.natAbs ++ natBits r.den + +def bits (I : RationalMetricInput) : List Bool := + natBits I.pointCount ++ natBits I.budget ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.pointCount => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.pointCount => + (List.ofFn (fun j : Fin I.pointCount => rationalBits (I.distance i j))).flatten)).flatten + +def decodeOutput (I : RationalMetricInput) (out : List Bool) : Finset (Fin I.pointCount) := + I.facilities.filter (fun i => out[i.val]?.getD false = true) + +end RationalMetricInput + +def pairBits (p : List Bool × List Bool) : List Bool := + p.1.flatMap (fun b => [true, b]) ++ [false] ++ p.2 + +structure BinaryRandomizedAlgorithm where + randomBits : Polynomial ℕ + run : List Bool × List Bool → List Bool + computation : Turing.TM2ComputableInPolyTime pairBits id run + finiteWorkAlphabet : ∀ k : computation.tm.K, Finite (computation.tm.Γ k) + + +end MetricKMedianRecovery + +run_elab Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace MetricKMedianRecovery.RefinedRecovery + +structure Input where + metric : RationalMetricInput + disjoint : Disjoint metric.clients metric.facilities + integral : ∀ x y, ∃ z : ℕ, metric.distance x y = (z : ℚ) + positive : ∀ x y, x ≠ y → 0 < metric.distance x y + anchor : Finset (Fin metric.pointCount) + anchor_subset : anchor ⊆ metric.facilities + anchor_card : anchor.card = metric.budget + +namespace Input +abbrev Point (I : Input) := Fin I.metric.pointCount + +def size (I : Input) : ℕ := I.metric.size + +def Bounded (I : Input) (bound : Polynomial ℕ) : Prop := + ∀ x y, I.metric.distance x y ≤ ((bound.eval I.size : ℕ) : ℚ) + +noncomputable def assign (I : Input) (O : Finset I.Point) (p : I.Point) : I.Point := + if h : O.Nonempty then + Classical.choose (Finset.exists_min_image O + (fun i => toLex (I.metric.distance p i, i)) h) + else p + +noncomputable def cluster (I : Input) (O : Finset I.Point) (i : I.Point) : Finset I.Point := + I.metric.clients.filter (fun p => I.assign O p = i) + +noncomputable def clusterCost (I : Input) (O : Finset I.Point) (i : I.Point) : ℝ := + ∑ p ∈ I.cluster O i, (I.metric.distance p i : ℝ) + +def anchorBits (I : Input) : List Bool := + List.ofFn (fun i : I.Point => decide (i ∈ I.anchor)) + +end Input + +structure Certificate (I : Input) (μ : ℚ) (L₀ : ℝ) where + centers : Finset I.Point + centers_subset : centers ⊆ I.metric.facilities + same_card : centers.card = I.anchor.card + positive_cost : 0 < (I.metric.cost centers : ℝ) + good : Finset I.Point + good_subset : good ⊆ centers + proxy : I.Point → I.Point + proxy_mem : ∀ i ∈ good, proxy i ∈ I.anchor + proxy_inj : Set.InjOn proxy (↑good) + proxy_cost : (∑ i ∈ good, ∑ p ∈ I.cluster centers i, + (I.metric.distance p (proxy i) : ℝ)) ≤ + (∑ i ∈ good, I.clusterCost centers i) + (μ : ℝ) * (I.metric.cost centers : ℝ) + few_bad : (((centers \ good).card : ℕ) : ℝ) ≤ L₀ * Real.log (I.size : ℝ) + +noncomputable def precision (ζ : ℝ) : ℕ := + ⌈Real.log (1 / ζ) / Real.log 2⌉₊ + +noncomputable def queryBits (I : Input) (ζ : ℝ) : List Bool := + pairBits (I.metric.bits, I.anchorBits ++ List.replicate (precision ζ) true) + +noncomputable def seedLength (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) : ℕ := + A.randomBits.eval (queryBits I ζ).length + +abbrev Seed (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) := + Fin (seedLength A I ζ) → Bool + +noncomputable def output (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) + (s : Seed A I ζ) : Finset I.Point := + I.metric.decodeOutput (A.run (queryBits I ζ, List.ofFn s)) + +noncomputable def successProbability (A : BinaryRandomizedAlgorithm) (I : Input) + (ζ target : ℝ) : ℝ := by + classical + exact ((Finset.univ.filter (fun s : Seed A I ζ => + (I.metric.cost (output A I ζ s) : ℝ) ≤ target)).card : ℝ) / + 2 ^ seedLength A I ζ + +noncomputable def workBound (A : BinaryRandomizedAlgorithm) (I : Input) (ζ : ℝ) : ℕ := + (queryBits I ζ).length + seedLength A I ζ + + A.computation.time.eval (pairBits + (queryBits I ζ, List.replicate (seedLength A I ζ) false)).length + +def PolynomialWork (A : BinaryRandomizedAlgorithm) (bound : Polynomial ℕ) : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ d : ℕ, + ∀ I : Input, I.Bounded bound → ∀ ζ : ℝ, 0 < ζ → ζ < 1 → + (workBound A I ζ : ℝ) ≤ + c * ((I.size : ℝ) + 1) ^ d * (1 + Real.log (1 / ζ)) ^ d + + +end MetricKMedianRecovery.RefinedRecovery + +namespace MetricKMedianRecovery.RefinedRecovery + +theorem refined_recovery : + ∀ (bound : Polynomial ℕ) (ε L₀ : ℝ) (μ : ℚ), + 0 < ε → 0 < L₀ → 0 < μ → μ ≤ 1/4 → (μ : ℝ) ≤ ε/12 → + ∃ A : BinaryRandomizedAlgorithm, + PolynomialWork A bound ∧ + ∀ I : Input, I.Bounded bound → ∀ ζ : ℝ, 0 < ζ → ζ < 1 → + (∀ s : Seed A I ζ, I.metric.Feasible (output A I ζ s)) ∧ + (∀ C : Certificate I μ L₀, + 1 - ζ ≤ successProbability A I ζ + ((1 + 2 / Real.exp 1 + ε) * (I.metric.cost C.centers : ℝ))) := by + sorry + +end MetricKMedianRecovery.RefinedRecovery + +end OAI diff --git a/tasks/k-median-refined-recovery/tests/grade.py b/tasks/k-median-refined-recovery/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/k-median-refined-recovery/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/k-median-refined-recovery/tests/task.json b/tasks/k-median-refined-recovery/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8770dcf3895c118ea433eef36f2603e8eea5d8c3 --- /dev/null +++ b/tasks/k-median-refined-recovery/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KMedianRefinedRecovery", + "comparator": { + "theorem_names": [ + "OAI.MetricKMedianRecovery.RefinedRecovery.refined_recovery" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13122 +} \ No newline at end of file diff --git a/tasks/k-median-refined-recovery/tests/test.sh b/tasks/k-median-refined-recovery/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/k-median-refined-recovery/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/k-median-threshold/environment/Dockerfile b/tasks/k-median-threshold/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/k-median-threshold/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/k-median-threshold/environment/fetch_mathlib.sh b/tasks/k-median-threshold/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/k-median-threshold/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/k-median-threshold/environment/lake-manifest.json b/tasks/k-median-threshold/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/k-median-threshold/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/k-median-threshold/environment/lakefile.lean b/tasks/k-median-threshold/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/k-median-threshold/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/k-median-threshold/environment/lean_setup.sh b/tasks/k-median-threshold/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/k-median-threshold/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/k-median-threshold/environment/pack_submission.py b/tasks/k-median-threshold/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/k-median-threshold/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/k-median-threshold/instruction.md b/tasks/k-median-threshold/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6fe7f18fabecc45e842f7162cc86dd069534ebc6 --- /dev/null +++ b/tasks/k-median-threshold/instruction.md @@ -0,0 +1,158 @@ +# openai/math challenge `KMedianThreshold` (family 125) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 125 of the release, *The approximation threshold for metric $k$-median* +(Theoretical computer science). The family as a whole: Gives a deterministic polynomial-time $(1+2/e+\varepsilon)$-approximation for finite rational metric $k$-median with specified candidate facilities, for every fixed $\varepsilon>0$. Assuming $P\ne NP$, the optimal infimum approximation factor is $1+2/e$. + +The challenge is `KMedianThreshold`, also at `/opt/openai-math/challenges/KMedianThreshold.lean`: + +```lean +import Mathlib + +namespace OAI + +section +section +namespace MetricKMedian + +structure Instance where + n : ℕ + distance : Fin n → Fin n → ℚ + clients : Finset (Fin n) + facilities : Finset (Fin n) + k : ℕ + distance_nonneg : ∀ i j, 0 ≤ distance i j + distance_eq_zero : ∀ i j, distance i j = 0 ↔ i = j + distance_symm : ∀ i j, distance i j = distance j i + distance_triangle : ∀ i j h, distance i h ≤ distance i j + distance j h + k_pos : 1 ≤ k + k_le : k ≤ facilities.card + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length true ++ [false] ++ n.bits + +def encodeRat (q : ℚ) : List Bool := + [decide (q.num < 0)] ++ encodeNat q.num.natAbs ++ encodeNat q.den + +def encodeInstance (I : Instance) : List Bool := + encodeNat I.n ++ encodeNat I.k ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.n => + (List.ofFn (fun j : Fin I.n => encodeRat (I.distance i j))).flatten)).flatten + +noncomputable def nearest (I : Instance) (j : Fin I.n) (S : Finset (Fin I.n)) : ℝ := + if h : S.Nonempty then + (S.image (fun i => (I.distance j i : ℝ))).min' (h.image _) + else 0 + +noncomputable def cost (I : Instance) (S : Finset (Fin I.n)) : ℝ := + ∑ j ∈ I.clients, nearest I j S + +def feasibleSets (I : Instance) : Finset (Finset (Fin I.n)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.k) + +noncomputable def optimum (I : Instance) : ℝ := + if h : (feasibleSets I).Nonempty then + ((feasibleSets I).image (cost I)).min' (h.image _) + else 0 + +def Correct (epsilon : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ (1 + 2 / Real.exp 1 + epsilon) * optimum I + +end MetricKMedian +end +end + +namespace MetricKMedian +namespace Complexity +/-- Polynomial-time computation with every physical work alphabet finite. -/ +def FinitePolyTime {α β : Type} (ea : α → List Bool) (eb : β → List Bool) + (f : α → β) : Prop := + ∃ p : Turing.TM2ComputableInPolyTime ea eb f, + ∀ k : p.tm.K, Finite (p.tm.Γ k) + +abbrev Word := List Bool +abbrev Language := Set Word + +def encodeBit (b : Bool) : Word := [b] + +def encodePair (x : Word × Word) : Word := + encodeNat x.1.length ++ x.1 ++ x.2 + +def P : Set Language := {L | ∃ decideL : Word → Bool, + FinitePolyTime id encodeBit decideL ∧ ∀ x, decideL x = true ↔ x ∈ L} + +def NP : Set Language := {L | ∃ (verify : Word × Word → Bool) (p : Polynomial ℕ), + FinitePolyTime encodePair encodeBit verify ∧ + ∀ x, x ∈ L ↔ ∃ w : Word, w.length ≤ p.eval x.length ∧ verify (x, w) = true} + +/-- Separation of deterministic polynomial time from finite-verifier nondeterministic polynomial time. -/ +def PNeNP : Prop := P ≠ NP + +end Complexity +/-- An actual nonempty feasible facility set, encoded by its membership mask. -/ +def FactorCorrect (α : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ α * optimum I + +/-- Deterministic polynomial-time approximation factors for arbitrary specified clients and facilities. -/ +def approximationFactors : Set ℝ := {α | ∃ algorithm : Instance → List Bool, + Complexity.FinitePolyTime encodeInstance id algorithm ∧ + ∀ I, FactorCorrect α I (algorithm I)} + +end MetricKMedian + +namespace MetricKMedian +/-- The deterministic approximation threshold is an infimum; its attainment is not asserted. -/ +theorem threshold (h : Complexity.PNeNP) : + sInf approximationFactors=1+2/Real.exp 1 := by + sorry +end MetricKMedian + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KMedianThreshold.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MetricKMedian.threshold` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/k-median-threshold/solution/closure.txt b/tasks/k-median-threshold/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..45676483a8a00a4134a578326c0ad753d90d3c0c --- /dev/null +++ b/tasks/k-median-threshold/solution/closure.txt @@ -0,0 +1,765 @@ +OAI.Combinatorics.KMedian.Amplification.Amplifier +OAI.Combinatorics.KMedian.Amplification.AmplifierCompiler +OAI.Combinatorics.KMedian.Amplification.AmplifierGuard +OAI.Combinatorics.KMedian.Amplification.AmplifierIteration +OAI.Combinatorics.KMedian.Amplification.AmplifierProgram +OAI.Combinatorics.KMedian.Amplification.AmplifierSize +OAI.Combinatorics.KMedian.Amplification.AmplifierTableSize +OAI.Combinatorics.KMedian.Amplification.CSPMix +OAI.Combinatorics.KMedian.Amplification.FlexibleAmplifier +OAI.Combinatorics.KMedian.Amplification.FlexibleBound +OAI.Combinatorics.KMedian.Amplification.FlexibleCloud +OAI.Combinatorics.KMedian.Amplification.FlexibleComplete +OAI.Combinatorics.KMedian.Amplification.FlexibleRegularization +OAI.Combinatorics.KMedian.Amplification.LabelTransport +OAI.Combinatorics.KMedian.Amplification.Majority +OAI.Combinatorics.KMedian.Amplification.PaddedAlphabet +OAI.Combinatorics.KMedian.Amplification.PaddedPowered +OAI.Combinatorics.KMedian.Amplification.PaddingSound +OAI.Combinatorics.KMedian.Amplification.PaddingSpec +OAI.Combinatorics.KMedian.Amplification.PowerCompleteness +OAI.Combinatorics.KMedian.Amplification.PowerPrograms +OAI.Combinatorics.KMedian.Amplification.PowerSpec +OAI.Combinatorics.KMedian.Amplification.PowerTable +OAI.Combinatorics.KMedian.Amplification.PoweredAlphabet +OAI.Combinatorics.KMedian.Amplification.PoweringBound +OAI.Combinatorics.KMedian.Amplification.PoweringConstruction +OAI.Combinatorics.KMedian.Amplification.PoweringMean +OAI.Combinatorics.KMedian.Amplification.PoweringMoment +OAI.Combinatorics.KMedian.Amplification.PoweringObjects +OAI.Combinatorics.KMedian.Amplification.RegularGraphLaws +OAI.Combinatorics.KMedian.Amplification.RegularPrograms +OAI.Combinatorics.KMedian.Amplification.RegularSpec +OAI.Combinatorics.KMedian.Amplification.RegularizationObjects +OAI.Combinatorics.KMedian.Amplification.RegularizationSound +OAI.Combinatorics.KMedian.Amplification.TestSum +OAI.Combinatorics.KMedian.Analysis.AnalyticEnvelopes +OAI.Combinatorics.KMedian.Analysis.BernsteinFalse +OAI.Combinatorics.KMedian.Analysis.BernsteinTrue +OAI.Combinatorics.KMedian.Analysis.CertificatePolynomials +OAI.Combinatorics.KMedian.Analysis.ChargeTransfer +OAI.Combinatorics.KMedian.Analysis.Coefficients +OAI.Combinatorics.KMedian.Analysis.ComparisonCertificates +OAI.Combinatorics.KMedian.Analysis.FiniteAverages +OAI.Combinatorics.KMedian.Analysis.FiniteComparison +OAI.Combinatorics.KMedian.Analysis.NormalizedTransfer +OAI.Combinatorics.KMedian.Analysis.PolynomialBounds +OAI.Combinatorics.KMedian.Analysis.QuadraticEnvelopes +OAI.Combinatorics.KMedian.Analysis.RowComparison +OAI.Combinatorics.KMedian.Analysis.ScalarCertificates +OAI.Combinatorics.KMedian.Analysis.ScalarTransfer +OAI.Combinatorics.KMedian.Analysis.TaylorBounds +OAI.Combinatorics.KMedian.Analysis.TaylorExpansion +OAI.Combinatorics.KMedian.Binary.BinaryAddition +OAI.Combinatorics.KMedian.Binary.BinaryAutoExtras +OAI.Combinatorics.KMedian.Binary.BinaryAutoFiniteLists +OAI.Combinatorics.KMedian.Binary.BinaryAutomatic +OAI.Combinatorics.KMedian.Binary.BinaryBooleanLists +OAI.Combinatorics.KMedian.Binary.BinaryDivision +OAI.Combinatorics.KMedian.Binary.BinaryDyadicPowers +OAI.Combinatorics.KMedian.Binary.BinaryFloor +OAI.Combinatorics.KMedian.Binary.BinaryGCD +OAI.Combinatorics.KMedian.Binary.BinaryGuard +OAI.Combinatorics.KMedian.Binary.BinaryGuardTotal +OAI.Combinatorics.KMedian.Binary.BinaryInteger +OAI.Combinatorics.KMedian.Binary.BinaryIntegerHeight +OAI.Combinatorics.KMedian.Binary.BinaryIterations +OAI.Combinatorics.KMedian.Binary.BinaryListContext +OAI.Combinatorics.KMedian.Binary.BinaryListExtras +OAI.Combinatorics.KMedian.Binary.BinaryListFold +OAI.Combinatorics.KMedian.Binary.BinaryListIndex +OAI.Combinatorics.KMedian.Binary.BinaryListIndices +OAI.Combinatorics.KMedian.Binary.BinaryListMap +OAI.Combinatorics.KMedian.Binary.BinaryListMapTotal +OAI.Combinatorics.KMedian.Binary.BinaryListSelection +OAI.Combinatorics.KMedian.Binary.BinaryListZip +OAI.Combinatorics.KMedian.Binary.BinaryLists +OAI.Combinatorics.KMedian.Binary.BinaryMatrix +OAI.Combinatorics.KMedian.Binary.BinaryMultiplication +OAI.Combinatorics.KMedian.Binary.BinaryNatSum +OAI.Combinatorics.KMedian.Binary.BinaryNatural +OAI.Combinatorics.KMedian.Binary.BinaryPredicates +OAI.Combinatorics.KMedian.Binary.BinaryRational +OAI.Combinatorics.KMedian.Binary.BinaryRationalFold +OAI.Combinatorics.KMedian.Binary.BinaryRationalHeight +OAI.Combinatorics.KMedian.Binary.BinaryRepeat +OAI.Combinatorics.KMedian.Binary.BinarySubtraction +OAI.Combinatorics.KMedian.Binary.BinaryWords +OAI.Combinatorics.KMedian.Binary.BooleanComposition +OAI.Combinatorics.KMedian.Binary.BooleanEmbedding +OAI.Combinatorics.KMedian.Binary.BooleanEncoding +OAI.Combinatorics.KMedian.Binary.BooleanFinite +OAI.Combinatorics.KMedian.Binary.BooleanListPrimitives +OAI.Combinatorics.KMedian.Binary.BooleanLoop +OAI.Combinatorics.KMedian.Binary.BooleanLoopFrom +OAI.Combinatorics.KMedian.Binary.BooleanMachine +OAI.Combinatorics.KMedian.Binary.BooleanMonomials +OAI.Combinatorics.KMedian.Binary.BooleanParallelTransducer +OAI.Combinatorics.KMedian.Binary.BooleanPolynomial +OAI.Combinatorics.KMedian.Binary.BooleanProducts +OAI.Combinatorics.KMedian.Binary.BooleanRecode +OAI.Combinatorics.KMedian.Binary.BooleanReverse +OAI.Combinatorics.KMedian.Binary.BooleanSum +OAI.Combinatorics.KMedian.Binary.BooleanThread +OAI.Combinatorics.KMedian.Binary.BooleanTransducer +OAI.Combinatorics.KMedian.Binary.InstanceParserProgram +OAI.Combinatorics.KMedian.Binary.NumericParserProgram +OAI.Combinatorics.KMedian.Binary.SequentialParserProgram +OAI.Combinatorics.KMedian.Compression.AffineElimination +OAI.Combinatorics.KMedian.Compression.AffineKernel +OAI.Combinatorics.KMedian.Compression.AffineListCompiler +OAI.Combinatorics.KMedian.Compression.AffineListOperations +OAI.Combinatorics.KMedian.Compression.BoundedDependence +OAI.Combinatorics.KMedian.Compression.CircuitBitBound +OAI.Combinatorics.KMedian.Compression.CompressionBinaryProgram +OAI.Combinatorics.KMedian.Compression.CompressionBounds +OAI.Combinatorics.KMedian.Compression.CompressionListStep +OAI.Combinatorics.KMedian.Compression.ComputedAffineKernel +OAI.Combinatorics.KMedian.Compression.ComputedCompression +OAI.Combinatorics.KMedian.Compression.ComputedCompressionStep +OAI.Combinatorics.KMedian.Compression.ComputedElimination +OAI.Combinatorics.KMedian.Compression.ComputedIntegerKernel +OAI.Combinatorics.KMedian.Compression.ComputedPivot +OAI.Combinatorics.KMedian.Compression.DependentIntegerKernel +OAI.Combinatorics.KMedian.Compression.FinsetVectorExtension +OAI.Combinatorics.KMedian.Compression.FullIntegerKernel +OAI.Combinatorics.KMedian.Compression.GaussianBinaryProgram +OAI.Combinatorics.KMedian.Compression.GaussianCircuit +OAI.Combinatorics.KMedian.Compression.GaussianInputBounds +OAI.Combinatorics.KMedian.Compression.GaussianKernel +OAI.Combinatorics.KMedian.Compression.GaussianListCompiler +OAI.Combinatorics.KMedian.Compression.GaussianListMachine +OAI.Combinatorics.KMedian.Compression.GaussianListOperations +OAI.Combinatorics.KMedian.Compression.GaussianListPivot +OAI.Combinatorics.KMedian.Compression.GaussianListRun +OAI.Combinatorics.KMedian.Compression.GaussianListSemantics +OAI.Combinatorics.KMedian.Compression.GaussianListSize +OAI.Combinatorics.KMedian.Compression.GaussianResidualCertificate +OAI.Combinatorics.KMedian.Compression.GaussianResidualHeight +OAI.Combinatorics.KMedian.Compression.GaussianStates +OAI.Combinatorics.KMedian.Compression.GaussianTabulated +OAI.Combinatorics.KMedian.Compression.GramBounds +OAI.Combinatorics.KMedian.Compression.GramDependence +OAI.Combinatorics.KMedian.Compression.IntegerCoefficientBounds +OAI.Combinatorics.KMedian.Compression.IntegerKernelProgram +OAI.Combinatorics.KMedian.Compression.IntegerListProgram +OAI.Combinatorics.KMedian.Compression.IntegerRationalCompression +OAI.Combinatorics.KMedian.Compression.RationalCompression +OAI.Combinatorics.KMedian.Compression.RationalIntegerLaw +OAI.Combinatorics.KMedian.Compression.RationalKernelHeightSupport +OAI.Combinatorics.KMedian.Compression.RationalOperationHeight +OAI.Combinatorics.KMedian.Compression.RationalScaling +OAI.Combinatorics.KMedian.CookLevin.CookAmplify +OAI.Combinatorics.KMedian.CookLevin.CookBoundaryProgram +OAI.Combinatorics.KMedian.CookLevin.CookBox +OAI.Combinatorics.KMedian.CookLevin.CookClockProgram +OAI.Combinatorics.KMedian.CookLevin.CookLevin +OAI.Combinatorics.KMedian.CookLevin.CookSize +OAI.Combinatorics.KMedian.CookLevin.CookTable +OAI.Combinatorics.KMedian.CookLevin.FiniteConstraints +OAI.Combinatorics.KMedian.CookLevin.InitialAlphabet +OAI.Combinatorics.KMedian.CookLevin.InitialSize +OAI.Combinatorics.KMedian.CookLevin.InitialTable +OAI.Combinatorics.KMedian.CookLevin.SeedInput +OAI.Combinatorics.KMedian.CookLevin.SemanticProjection +OAI.Combinatorics.KMedian.CookLevin.TM2Locality +OAI.Combinatorics.KMedian.CookLevin.TM2Response +OAI.Combinatorics.KMedian.CookLevin.TableauBoundary +OAI.Combinatorics.KMedian.CookLevin.TableauCorrect +OAI.Combinatorics.KMedian.CookLevin.TableauDirectories +OAI.Combinatorics.KMedian.CookLevin.TableauDirectoryProgram +OAI.Combinatorics.KMedian.CookLevin.TableauEndpoints +OAI.Combinatorics.KMedian.CookLevin.TableauLocal +OAI.Combinatorics.KMedian.CookLevin.TableauQueryProgram +OAI.Combinatorics.KMedian.CookLevin.TableauRelationProgram +OAI.Combinatorics.KMedian.CookLevin.TableauRows +OAI.Combinatorics.KMedian.CookLevin.TableauRun +OAI.Combinatorics.KMedian.CookLevin.TableauSystem +OAI.Combinatorics.KMedian.Expanders.Cayley +OAI.Combinatorics.KMedian.Expanders.Cloud +OAI.Combinatorics.KMedian.Expanders.CloudCopies +OAI.Combinatorics.KMedian.Expanders.CloudEmbedding +OAI.Combinatorics.KMedian.Expanders.CloudOrder +OAI.Combinatorics.KMedian.Expanders.CloudPrograms +OAI.Combinatorics.KMedian.Expanders.CloudSpec +OAI.Combinatorics.KMedian.Expanders.EqualityExpansion +OAI.Combinatorics.KMedian.Expanders.ExpanderCompiler +OAI.Combinatorics.KMedian.Expanders.ExpanderFamily +OAI.Combinatorics.KMedian.Expanders.ExpanderGuard +OAI.Combinatorics.KMedian.Expanders.ExpanderIndex +OAI.Combinatorics.KMedian.Expanders.ExpanderStep +OAI.Combinatorics.KMedian.Expanders.ExpanderTables +OAI.Combinatorics.KMedian.Expanders.GraphExtend +OAI.Combinatorics.KMedian.Expanders.GraphMix +OAI.Combinatorics.KMedian.Expanders.GraphProducts +OAI.Combinatorics.KMedian.Expanders.GraphRelabel +OAI.Combinatorics.KMedian.Expanders.L2 +OAI.Combinatorics.KMedian.Expanders.PathCount +OAI.Combinatorics.KMedian.Expanders.PortWalk +OAI.Combinatorics.KMedian.Expanders.Rademacher +OAI.Combinatorics.KMedian.Expanders.SmallBias +OAI.Combinatorics.KMedian.Expanders.SpectralWalk +OAI.Combinatorics.KMedian.Expanders.Stopped +OAI.Combinatorics.KMedian.Expanders.WalkMoments +OAI.Combinatorics.KMedian.Expanders.WalkSegments +OAI.Combinatorics.KMedian.Expanders.Walsh +OAI.Combinatorics.KMedian.Expanders.Zigzag +OAI.Combinatorics.KMedian.Geometry.BoundFreeCompression +OAI.Combinatorics.KMedian.Geometry.BundleRounding +OAI.Combinatorics.KMedian.Geometry.ChunkCharges +OAI.Combinatorics.KMedian.Geometry.ComputedInstanceAlgorithm +OAI.Combinatorics.KMedian.Geometry.ComputedRationalCompression +OAI.Combinatorics.KMedian.Geometry.FilteredMoments +OAI.Combinatorics.KMedian.Geometry.FixedBatchTransition +OAI.Combinatorics.KMedian.Geometry.GraphComparison +OAI.Combinatorics.KMedian.Geometry.GraphLaw +OAI.Combinatorics.KMedian.Geometry.GraphListOperations +OAI.Combinatorics.KMedian.Geometry.GraphMoments +OAI.Combinatorics.KMedian.Geometry.GraphRunHeight +OAI.Combinatorics.KMedian.Geometry.GreedyCompletion +OAI.Combinatorics.KMedian.Geometry.GreedyPacking +OAI.Combinatorics.KMedian.Geometry.IntegerBranching +OAI.Combinatorics.KMedian.Geometry.ListSigma +OAI.Combinatorics.KMedian.Geometry.MomentAnalysis +OAI.Combinatorics.KMedian.Geometry.NearestFillingFormula +OAI.Combinatorics.KMedian.Geometry.NearestFractional +OAI.Combinatorics.KMedian.Geometry.NearestReindex +OAI.Combinatorics.KMedian.Geometry.PotentialBounds +OAI.Combinatorics.KMedian.Geometry.RationalAllParameters +OAI.Combinatorics.KMedian.Geometry.RationalBrackets +OAI.Combinatorics.KMedian.Geometry.RationalBundleGeometry +OAI.Combinatorics.KMedian.Geometry.RationalCompletedCost +OAI.Combinatorics.KMedian.Geometry.RationalFractionalInput +OAI.Combinatorics.KMedian.Geometry.RationalFractionalScan +OAI.Combinatorics.KMedian.Geometry.RationalGeometryScan +OAI.Combinatorics.KMedian.Geometry.RationalGridRound +OAI.Combinatorics.KMedian.Geometry.RationalHistoryCompletion +OAI.Combinatorics.KMedian.Geometry.RationalHistorySelection +OAI.Combinatorics.KMedian.Geometry.RationalHistoryValid +OAI.Combinatorics.KMedian.Geometry.RationalImageCost +OAI.Combinatorics.KMedian.Geometry.RationalIndexedCost +OAI.Combinatorics.KMedian.Geometry.RationalInstanceCost +OAI.Combinatorics.KMedian.Geometry.RationalIntervals +OAI.Combinatorics.KMedian.Geometry.RationalNearestCopies +OAI.Combinatorics.KMedian.Geometry.RationalParameterizedHistory +OAI.Combinatorics.KMedian.Geometry.RationalSparseTaper +OAI.Combinatorics.KMedian.Geometry.RationalSplitEnumeration +OAI.Combinatorics.KMedian.Geometry.RationalSplitInput +OAI.Combinatorics.KMedian.Geometry.RationalSplitting +OAI.Combinatorics.KMedian.Geometry.RationalUnitInput +OAI.Combinatorics.KMedian.Geometry.RationalUnitScan +OAI.Combinatorics.KMedian.Geometry.SortedListEncoding +OAI.Combinatorics.KMedian.Geometry.TimeAdvance +OAI.Combinatorics.KMedian.Geometry.TrimIntegerLaw +OAI.Combinatorics.KMedian.Geometry.UniformDrift +OAI.Combinatorics.KMedian.Hardness.Analysis +OAI.Combinatorics.KMedian.Hardness.Classes +OAI.Combinatorics.KMedian.Hardness.Composition +OAI.Combinatorics.KMedian.Hardness.Constants +OAI.Combinatorics.KMedian.Hardness.Coverage +OAI.Combinatorics.KMedian.Hardness.Encoding +OAI.Combinatorics.KMedian.Hardness.Lists +OAI.Combinatorics.KMedian.Hardness.Model +OAI.Combinatorics.KMedian.Hardness.Partition +OAI.Combinatorics.KMedian.Hardness.PartitionAverage +OAI.Combinatorics.KMedian.Hardness.Projection +OAI.Combinatorics.KMedian.Hardness.ProjectionEncoding +OAI.Combinatorics.KMedian.Hardness.ProjectionInput +OAI.Combinatorics.KMedian.Hardness.ProjectionReduction +OAI.Combinatorics.KMedian.Hardness.Reduction +OAI.Combinatorics.KMedian.Hardness.Sampling +OAI.Combinatorics.KMedian.Hardness.SamplingCounts +OAI.Combinatorics.KMedian.Hardness.Threads +OAI.Combinatorics.KMedian.Hardness.TwoChoices +OAI.Combinatorics.KMedian.Hardness.Verdict +OAI.Combinatorics.KMedian.Instance +OAI.Combinatorics.KMedian.Machines.AdviceInstances +OAI.Combinatorics.KMedian.Machines.AlphabetIndex +OAI.Combinatorics.KMedian.Machines.AlphabetSpec +OAI.Combinatorics.KMedian.Machines.AlphabetTable +OAI.Combinatorics.KMedian.Machines.BinaryReindex +OAI.Combinatorics.KMedian.Machines.BlendCompiler +OAI.Combinatorics.KMedian.Machines.BlendSpec +OAI.Combinatorics.KMedian.Machines.BlockRotation +OAI.Combinatorics.KMedian.Machines.Box +OAI.Combinatorics.KMedian.Machines.CSPTableBounds +OAI.Combinatorics.KMedian.Machines.CardBounds +OAI.Combinatorics.KMedian.Machines.CutLaws +OAI.Combinatorics.KMedian.Machines.FiniteBoundaryPrograms +OAI.Combinatorics.KMedian.Machines.FiniteCases +OAI.Combinatorics.KMedian.Machines.FiniteCompiler +OAI.Combinatorics.KMedian.Machines.FiniteCoordinates +OAI.Combinatorics.KMedian.Machines.FiniteFilterProgram +OAI.Combinatorics.KMedian.Machines.FixedImpossible +OAI.Combinatorics.KMedian.Machines.GridTables +OAI.Combinatorics.KMedian.Machines.Hardcoded +OAI.Combinatorics.KMedian.Machines.Iteration +OAI.Combinatorics.KMedian.Machines.IterationPolynomial +OAI.Combinatorics.KMedian.Machines.ListAllProgram +OAI.Combinatorics.KMedian.Machines.ListCompiler +OAI.Combinatorics.KMedian.Machines.LocalCompiler +OAI.Combinatorics.KMedian.Machines.LocalSpec +OAI.Combinatorics.KMedian.Machines.MatchingLaws +OAI.Combinatorics.KMedian.Machines.MatchingSpec +OAI.Combinatorics.KMedian.Machines.Ordered +OAI.Combinatorics.KMedian.Machines.OrderedLists +OAI.Combinatorics.KMedian.Machines.RawCSP +OAI.Combinatorics.KMedian.Machines.RawRotation +OAI.Combinatorics.KMedian.Machines.RawSquare +OAI.Combinatorics.KMedian.Machines.RawWalk +OAI.Combinatorics.KMedian.Machines.RectTables +OAI.Combinatorics.KMedian.Machines.RelabelTables +OAI.Combinatorics.KMedian.Machines.RotationBounds +OAI.Combinatorics.KMedian.Machines.RotationExt +OAI.Combinatorics.KMedian.Machines.TableBuilders +OAI.Combinatorics.KMedian.Machines.TableCounts +OAI.Combinatorics.KMedian.Machines.TablePromises +OAI.Combinatorics.KMedian.Machines.UnaryPolynomial +OAI.Combinatorics.KMedian.Machines.VertexMap +OAI.Combinatorics.KMedian.Main +OAI.Combinatorics.KMedian.Model +OAI.Combinatorics.KMedian.Optimization.ApproximateFractional +OAI.Combinatorics.KMedian.Optimization.ApproximateLPSelection +OAI.Combinatorics.KMedian.Optimization.ApproximationListProgram +OAI.Combinatorics.KMedian.Optimization.ApproximationSlack +OAI.Combinatorics.KMedian.Optimization.ComputedNearest +OAI.Combinatorics.KMedian.Optimization.DualListCompiler +OAI.Combinatorics.KMedian.Optimization.DualListOperations +OAI.Combinatorics.KMedian.Optimization.FractionalDual +OAI.Combinatorics.KMedian.Optimization.FractionalInputProgram +OAI.Combinatorics.KMedian.Optimization.FractionalListChecks +OAI.Combinatorics.KMedian.Optimization.FractionalScanProgram +OAI.Combinatorics.KMedian.Optimization.FractionalSelectProgram +OAI.Combinatorics.KMedian.Optimization.GradientDenominator +OAI.Combinatorics.KMedian.Optimization.IndexedInstanceLP +OAI.Combinatorics.KMedian.Optimization.IntegralFractionalComparison +OAI.Combinatorics.KMedian.Optimization.LPBinaryInput +OAI.Combinatorics.KMedian.Optimization.LPBinaryStart +OAI.Combinatorics.KMedian.Optimization.LPBinaryTrajectory +OAI.Combinatorics.KMedian.Optimization.LPListFacts +OAI.Combinatorics.KMedian.Optimization.LPMinimumSelection +OAI.Combinatorics.KMedian.Optimization.MatrixNormalization +OAI.Combinatorics.KMedian.Optimization.OptimizationBitBound +OAI.Combinatorics.KMedian.Optimization.ProjectedSubgradient +OAI.Combinatorics.KMedian.Optimization.RationalArgmin +OAI.Combinatorics.KMedian.Optimization.SimplexDiameter +OAI.Combinatorics.KMedian.Optimization.SimplexListProgram +OAI.Combinatorics.KMedian.Optimization.SimplexProjection +OAI.Combinatorics.KMedian.Optimization.SubgradientDenominator +OAI.Combinatorics.KMedian.Optimization.SubgradientTrajectoryHeight +OAI.Combinatorics.KMedian.Optimization.TruncatedListCompiler +OAI.Combinatorics.KMedian.Optimization.TruncatedListOperations +OAI.Combinatorics.KMedian.Optimization.TruncatedObjective +OAI.Combinatorics.KMedian.Optimization.TruncatedOptimization +OAI.Combinatorics.KMedian.Optimization.TruncatedRepair +OAI.Combinatorics.KMedian.Optimization.ZeroCostBranch +OAI.Combinatorics.KMedian.PCP.AlphabetReduction +OAI.Combinatorics.KMedian.PCP.BinaryReduction +OAI.Combinatorics.KMedian.PCP.Boundary +OAI.Combinatorics.KMedian.PCP.FiniteTest +OAI.Combinatorics.KMedian.PCP.GlobalRegularization +OAI.Combinatorics.KMedian.PCP.Hadamard +OAI.Combinatorics.KMedian.PCP.Linearity +OAI.Combinatorics.KMedian.PCP.LocalReduction +OAI.Combinatorics.KMedian.PCP.PathTable +OAI.Combinatorics.KMedian.PCP.Quadratic +OAI.Combinatorics.KMedian.PCP.QuadraticEncoding +OAI.Combinatorics.KMedian.PCP.Queries +OAI.Combinatorics.KMedian.PCP.Tester +OAI.Combinatorics.KMedian.PCP.UniformProjection +OAI.Combinatorics.KMedian.Preparation.AssignmentCopies +OAI.Combinatorics.KMedian.Preparation.AssignmentRepair +OAI.Combinatorics.KMedian.Preparation.CoupledGeometry +OAI.Combinatorics.KMedian.Preparation.CoupledNoise +OAI.Combinatorics.KMedian.Preparation.CoupledPreparation +OAI.Combinatorics.KMedian.Preparation.CoupledReindex +OAI.Combinatorics.KMedian.Preparation.CoupledWeights +OAI.Combinatorics.KMedian.Preparation.DistantAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyBall +OAI.Combinatorics.KMedian.Preparation.NearestAssignmentGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationClientAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationCostGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationDeficits +OAI.Combinatorics.KMedian.Preparation.PreparationGrid +OAI.Combinatorics.KMedian.Preparation.PreparationInner +OAI.Combinatorics.KMedian.Preparation.PreparationMoments +OAI.Combinatorics.KMedian.Preparation.PreparationNoise +OAI.Combinatorics.KMedian.Preparation.PreparationOldCost +OAI.Combinatorics.KMedian.Preparation.PreparationOutcome +OAI.Combinatorics.KMedian.Preparation.PreparationOuter +OAI.Combinatorics.KMedian.Preparation.PreparationParameters +OAI.Combinatorics.KMedian.Preparation.PreparationRescaling +OAI.Combinatorics.KMedian.Preparation.PreparationStars +OAI.Combinatorics.KMedian.Preparation.PreparationSubsetNoise +OAI.Combinatorics.KMedian.Preparation.PreparedDataOperations +OAI.Combinatorics.KMedian.Preparation.PreparedKernelProgram +OAI.Combinatorics.KMedian.Preparation.PreparedLawProgram +OAI.Combinatorics.KMedian.Preparation.PreparedScanProgram +OAI.Combinatorics.KMedian.Preparation.RationalPreparedScan +OAI.Combinatorics.KMedian.Preparation.RationalRepresentatives +OAI.Combinatorics.KMedian.Preparation.RationalSupplierPreparation +OAI.Combinatorics.KMedian.Preparation.RationalSupplierScan +OAI.Combinatorics.KMedian.Preparation.RepresentativeBundles +OAI.Combinatorics.KMedian.Preparation.RepresentativeGeometry +OAI.Combinatorics.KMedian.Preparation.RepresentativeProgram +OAI.Combinatorics.KMedian.Preparation.RetainedActivations +OAI.Combinatorics.KMedian.Preparation.SelectedPreparationOutcome +OAI.Combinatorics.KMedian.Preparation.ShortfallByDeviation +OAI.Combinatorics.KMedian.Preparation.SupplierAllocation +OAI.Combinatorics.KMedian.Preparation.SupplierCharges +OAI.Combinatorics.KMedian.Preparation.SupplierGeometry +OAI.Combinatorics.KMedian.Preparation.SupplierListOperations +OAI.Combinatorics.KMedian.Preparation.SupplierMap +OAI.Combinatorics.KMedian.Preparation.SupplierPreparationProgram +OAI.Combinatorics.KMedian.Preparation.SupplierScanProgram +OAI.Combinatorics.KMedian.Preparation.SupportRepair +OAI.Combinatorics.KMedian.Probability.BernoulliBatches +OAI.Combinatorics.KMedian.Probability.BernoulliListOperations +OAI.Combinatorics.KMedian.Probability.BernoulliPolynomial +OAI.Combinatorics.KMedian.Probability.BernoulliRealTransfer +OAI.Combinatorics.KMedian.Probability.BernoulliReindex +OAI.Combinatorics.KMedian.Probability.BernoulliRunHeight +OAI.Combinatorics.KMedian.Probability.BernoulliRunProgram +OAI.Combinatorics.KMedian.Probability.BernoulliSquare +OAI.Combinatorics.KMedian.Probability.BernoulliStepProgram +OAI.Combinatorics.KMedian.Probability.BernoulliVariance +OAI.Combinatorics.KMedian.Probability.Conditioning +OAI.Combinatorics.KMedian.Probability.FiniteClipping +OAI.Combinatorics.KMedian.Probability.FiniteJoint +OAI.Combinatorics.KMedian.Probability.FiniteKernels +OAI.Combinatorics.KMedian.Probability.FiniteLawConstructions +OAI.Combinatorics.KMedian.Probability.FiniteLaws +OAI.Combinatorics.KMedian.Probability.FiniteProcess +OAI.Combinatorics.KMedian.Probability.FiniteVariance +OAI.Combinatorics.KMedian.Probability.NegativeStars +OAI.Combinatorics.KMedian.Probability.NonnegativeRounding +OAI.Combinatorics.KMedian.Probability.ProbabilitySupport +OAI.Combinatorics.KMedian.Probability.PushforwardLaw +OAI.Combinatorics.KMedian.Probability.SignedPartial +OAI.Combinatorics.KMedian.Probability.SignedStars +OAI.Combinatorics.KMedian.Probability.SumLaws +OAI.Combinatorics.KMedian.Probability.SupportedLaw +OAI.Combinatorics.KMedian.Process.ActionDegrees +OAI.Combinatorics.KMedian.Process.ActionTransitionList +OAI.Combinatorics.KMedian.Process.ActualActions +OAI.Combinatorics.KMedian.Process.AdaptiveCount +OAI.Combinatorics.KMedian.Process.AveragedCount +OAI.Combinatorics.KMedian.Process.AveragedDrift +OAI.Combinatorics.KMedian.Process.AveragedGenerator +OAI.Combinatorics.KMedian.Process.BackupGeometry +OAI.Combinatorics.KMedian.Process.BackupInvariant +OAI.Combinatorics.KMedian.Process.BatchActionArrays +OAI.Combinatorics.KMedian.Process.BatchActionCodes +OAI.Combinatorics.KMedian.Process.BatchActionList +OAI.Combinatorics.KMedian.Process.BatchEstimate +OAI.Combinatorics.KMedian.Process.BatchGraphData +OAI.Combinatorics.KMedian.Process.BatchOrdinalArrays +OAI.Combinatorics.KMedian.Process.BatchOrdinalCodes +OAI.Combinatorics.KMedian.Process.BatchProposalProgram +OAI.Combinatorics.KMedian.Process.BatchUniform +OAI.Combinatorics.KMedian.Process.ConditionalRoundDrift +OAI.Combinatorics.KMedian.Process.CopyGraphProgram +OAI.Combinatorics.KMedian.Process.CopyListEncoding +OAI.Combinatorics.KMedian.Process.CopyNearestProgram +OAI.Combinatorics.KMedian.Process.CopyNextProgram +OAI.Combinatorics.KMedian.Process.CopyRound +OAI.Combinatorics.KMedian.Process.CopyState +OAI.Combinatorics.KMedian.Process.CopyTransport +OAI.Combinatorics.KMedian.Process.CountGeometry +OAI.Combinatorics.KMedian.Process.CountInstantiation +OAI.Combinatorics.KMedian.Process.CountListOperations +OAI.Combinatorics.KMedian.Process.CountRunHeight +OAI.Combinatorics.KMedian.Process.CountRunProgram +OAI.Combinatorics.KMedian.Process.CountSize +OAI.Combinatorics.KMedian.Process.CountSource +OAI.Combinatorics.KMedian.Process.CountStepProgram +OAI.Combinatorics.KMedian.Process.CountTail +OAI.Combinatorics.KMedian.Process.CountVariance +OAI.Combinatorics.KMedian.Process.CountsMaskProgram +OAI.Combinatorics.KMedian.Process.ErasureDecay +OAI.Combinatorics.KMedian.Process.FiniteGraph +OAI.Combinatorics.KMedian.Process.ForceBatchBound +OAI.Combinatorics.KMedian.Process.ForcedLocal +OAI.Combinatorics.KMedian.Process.ForcedTransition +OAI.Combinatorics.KMedian.Process.FrozenBatchBound +OAI.Combinatorics.KMedian.Process.FullBatchBound +OAI.Combinatorics.KMedian.Process.GeneratorAverage +OAI.Combinatorics.KMedian.Process.GeneratorBound +OAI.Combinatorics.KMedian.Process.GroupCap +OAI.Combinatorics.KMedian.Process.HeavyActions +OAI.Combinatorics.KMedian.Process.LocalBatchUniform +OAI.Combinatorics.KMedian.Process.LocalForceScale +OAI.Combinatorics.KMedian.Process.PhaseBatchBound +OAI.Combinatorics.KMedian.Process.PhysicalBatchLaw +OAI.Combinatorics.KMedian.Process.PhysicalBatchList +OAI.Combinatorics.KMedian.Process.PhysicalBatchProgram +OAI.Combinatorics.KMedian.Process.PhysicalBatchUpdateProgram +OAI.Combinatorics.KMedian.Process.PhysicalCountGeometry +OAI.Combinatorics.KMedian.Process.PhysicalCountLaw +OAI.Combinatorics.KMedian.Process.PhysicalHistoriesProgram +OAI.Combinatorics.KMedian.Process.PhysicalOldMass +OAI.Combinatorics.KMedian.Process.PhysicalPotential +OAI.Combinatorics.KMedian.Process.PhysicalProcess +OAI.Combinatorics.KMedian.Process.PhysicalRound +OAI.Combinatorics.KMedian.Process.PhysicalRoundProgram +OAI.Combinatorics.KMedian.Process.PhysicalState +OAI.Combinatorics.KMedian.Process.ProcessCompletion +OAI.Combinatorics.KMedian.Process.QuadraticCount +OAI.Combinatorics.KMedian.Process.RoundCountsProgram +OAI.Combinatorics.KMedian.Process.RoundParameters +OAI.Combinatorics.KMedian.Process.RoundWithCount +OAI.Combinatorics.KMedian.Process.RoundingCoordinateHeight +OAI.Combinatorics.KMedian.Process.RoundingListOperations +OAI.Combinatorics.KMedian.Process.RoundingRunHeight +OAI.Combinatorics.KMedian.Process.RoundingRunProgram +OAI.Combinatorics.KMedian.Process.RoundingStateCompiler +OAI.Combinatorics.KMedian.Process.RoundingUniformStep +OAI.Combinatorics.KMedian.Process.SourceAverage +OAI.Combinatorics.KMedian.Process.SourceBalance +OAI.Combinatorics.KMedian.Process.SourceDriftLaw +OAI.Combinatorics.KMedian.Process.SourceGenerator +OAI.Combinatorics.KMedian.Process.StateInvariants +OAI.Combinatorics.KMedian.Process.SurvivalProbability +OAI.Combinatorics.KMedian.Process.Taper +OAI.Combinatorics.KMedian.Process.TaperAllProgram +OAI.Combinatorics.KMedian.Process.TaperData +OAI.Combinatorics.KMedian.Process.TaperGraph +OAI.Combinatorics.KMedian.Process.TaperGraphProgram +OAI.Combinatorics.KMedian.Process.TaperListProgram +OAI.Combinatorics.KMedian.Process.TaperReindex +OAI.Combinatorics.KMedian.Process.UnbalancedActions +OAI.Combinatorics.KMedian.Programs.BoundedEnumerationProgram +OAI.Combinatorics.KMedian.Programs.BranchProgram +OAI.Combinatorics.KMedian.Programs.BundleGeometryProgram +OAI.Combinatorics.KMedian.Programs.BundlesProgram +OAI.Combinatorics.KMedian.Programs.CardinalRoundProgram +OAI.Combinatorics.KMedian.Programs.DependentSparseProgram +OAI.Combinatorics.KMedian.Programs.FinalSelectionProgram +OAI.Combinatorics.KMedian.Programs.FinsetMaskProgram +OAI.Combinatorics.KMedian.Programs.GraphLawProgram +OAI.Combinatorics.KMedian.Programs.GraphRunProgram +OAI.Combinatorics.KMedian.Programs.GraphStepProgram +OAI.Combinatorics.KMedian.Programs.GreedyPackingProgram +OAI.Combinatorics.KMedian.Programs.HistorySelectionProgram +OAI.Combinatorics.KMedian.Programs.InstanceComputedPseudo +OAI.Combinatorics.KMedian.Programs.InstanceDataProgram +OAI.Combinatorics.KMedian.Programs.InstanceFractionalRound +OAI.Combinatorics.KMedian.Programs.InstanceRoundProgram +OAI.Combinatorics.KMedian.Programs.InstanceRounding +OAI.Combinatorics.KMedian.Programs.InstanceZeroProgram +OAI.Combinatorics.KMedian.Programs.LastFractionProgram +OAI.Combinatorics.KMedian.Programs.MaskBestProgram +OAI.Combinatorics.KMedian.Programs.MaximumProgram +OAI.Combinatorics.KMedian.Programs.NearestListProgram +OAI.Combinatorics.KMedian.Programs.NearestMaskProgram +OAI.Combinatorics.KMedian.Programs.OriginalMaskProgram +OAI.Combinatorics.KMedian.Programs.OuterLawProgram +OAI.Combinatorics.KMedian.Programs.PivotListProgram +OAI.Combinatorics.KMedian.Programs.RationalFeatureProgram +OAI.Combinatorics.KMedian.Programs.RationalSortProgram +OAI.Combinatorics.KMedian.Programs.RestrictionProgram +OAI.Combinatorics.KMedian.Programs.ScaleListProgram +OAI.Combinatorics.KMedian.Programs.ScoreProgram +OAI.Combinatorics.KMedian.Programs.SplitListProgram +OAI.Combinatorics.KMedian.Programs.StarActivationProgram +OAI.Combinatorics.KMedian.Programs.TaggedBestProgram +OAI.Combinatorics.KMedian.Programs.UnitGeometryProgram +OAI.Combinatorics.KMedian.Programs.UnitRepresentativeProgram +OAI.Combinatorics.KMedian.Programs.UnitScanProgram +OAI.Combinatorics.KMedian.Projection.Bound +OAI.Combinatorics.KMedian.Projection.CSPProjection +OAI.Combinatorics.KMedian.Projection.CodingLaws +OAI.Combinatorics.KMedian.Projection.Contraction +OAI.Combinatorics.KMedian.Projection.Expansion +OAI.Combinatorics.KMedian.Projection.IncidenceExpansion +OAI.Combinatorics.KMedian.Projection.IncidenceOperator +OAI.Combinatorics.KMedian.Projection.Input +OAI.Combinatorics.KMedian.Projection.MassNormalize +OAI.Combinatorics.KMedian.Projection.Norm +OAI.Combinatorics.KMedian.Projection.Operator +OAI.Combinatorics.KMedian.Projection.PowerTable +OAI.Combinatorics.KMedian.Projection.Product +OAI.Combinatorics.KMedian.Projection.ProductTable +OAI.Combinatorics.KMedian.Projection.Promises +OAI.Combinatorics.KMedian.Projection.RegularTable +OAI.Combinatorics.KMedian.Projection.Reindex +OAI.Combinatorics.KMedian.Projection.RepairProgram +OAI.Combinatorics.KMedian.Projection.Repeat +OAI.Combinatorics.KMedian.Projection.Rounding +OAI.Combinatorics.KMedian.Projection.RowsBuild +OAI.Combinatorics.KMedian.Projection.Seed +OAI.Combinatorics.KMedian.Projection.SeedCombinators +OAI.Combinatorics.KMedian.Projection.SeedSound +OAI.Combinatorics.KMedian.Projection.SeedTables +OAI.Combinatorics.KMedian.Projection.Tables +OAI.Combinatorics.KMedian.Projection.Tensor +OAI.Combinatorics.KMedian.Projection.ToInput +OAI.Combinatorics.KMedian.Reduction.BadCenterBound +OAI.Combinatorics.KMedian.Reduction.BudgetReduction +OAI.Combinatorics.KMedian.Reduction.CloseFromServing +OAI.Combinatorics.KMedian.Reduction.CompletionEndpoint +OAI.Combinatorics.KMedian.Reduction.CompletionEnumeration +OAI.Combinatorics.KMedian.Reduction.CompletionGeometry +OAI.Combinatorics.KMedian.Reduction.CompletionMaskProgram +OAI.Combinatorics.KMedian.Reduction.CompletionProgram +OAI.Combinatorics.KMedian.Reduction.CompletionSelection +OAI.Combinatorics.KMedian.Reduction.DeletionEndpoint +OAI.Combinatorics.KMedian.Reduction.DeletionGeometry +OAI.Combinatorics.KMedian.Reduction.DeletionHistory +OAI.Combinatorics.KMedian.Reduction.DeletionProgram +OAI.Combinatorics.KMedian.Reduction.LocalCompletion +OAI.Combinatorics.KMedian.Reduction.LocalCompletionProgram +OAI.Combinatorics.KMedian.Reduction.NormalizationGuesses +OAI.Combinatorics.KMedian.Reduction.OrdinaryListProgram +OAI.Combinatorics.KMedian.Reduction.RadiusPacking +OAI.Combinatorics.KMedian.Reduction.RationalCompletion +OAI.Combinatorics.KMedian.Reduction.RationalDeletion +OAI.Combinatorics.KMedian.Reduction.RationalGreedyCompletion +OAI.Combinatorics.KMedian.Reduction.RationalLocalChoice +OAI.Combinatorics.KMedian.Reduction.RationalThreshold +OAI.Combinatorics.KMedian.Reduction.ReductionClosure +OAI.Combinatorics.KMedian.Reduction.ReductionCostProgram +OAI.Combinatorics.KMedian.Reduction.ReductionOutcomesProgram +OAI.Combinatorics.KMedian.Reduction.Sparsification +OAI.Combinatorics.KMedian.Reduction.SparsifyEnumeration +OAI.Combinatorics.KMedian.Rounding.ExactRounding +OAI.Combinatorics.KMedian.Rounding.ExceptionalStar +OAI.Combinatorics.KMedian.Rounding.GridClipping +OAI.Combinatorics.KMedian.Rounding.GridDataProgram +OAI.Combinatorics.KMedian.Rounding.GridEndpoint +OAI.Combinatorics.KMedian.Rounding.GridRounding +OAI.Combinatorics.KMedian.Rounding.GridRoundingProgram +OAI.Combinatorics.KMedian.Rounding.IntegerSimplexProjection +OAI.Combinatorics.KMedian.Rounding.MarginalRounding +OAI.Combinatorics.KMedian.Rounding.RationalBatchData +OAI.Combinatorics.KMedian.Rounding.RationalBatchEnumeration +OAI.Combinatorics.KMedian.Rounding.RationalBatchFacts +OAI.Combinatorics.KMedian.Rounding.RationalCopyTransition +OAI.Combinatorics.KMedian.Rounding.RationalLastFraction +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraph +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraphInstance +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistorySurvival +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalInvariant +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalKernel +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalReplay +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalProposalBound +OAI.Combinatorics.KMedian.Rounding.RationalProposalCount +OAI.Combinatorics.KMedian.Rounding.RationalProposalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalRetain +OAI.Combinatorics.KMedian.Rounding.RationalRoundEvents +OAI.Combinatorics.KMedian.Rounding.RationalRoundParameters +OAI.Combinatorics.KMedian.Rounding.RationalRounding +OAI.Combinatorics.KMedian.Rounding.RationalSignedStep +OAI.Combinatorics.KMedian.Rounding.RationalSignedTerminal +OAI.Combinatorics.KMedian.Rounding.RationalTaper +OAI.Combinatorics.KMedian.Rounding.RationalTaperAffine +OAI.Combinatorics.KMedian.Rounding.RationalTaperCandidates +OAI.Combinatorics.KMedian.Rounding.RationalTaperData +OAI.Combinatorics.KMedian.Rounding.RationalTaperZero +OAI.Combinatorics.KMedian.Rounding.RationalWeightedInvariants +OAI.Combinatorics.KMedian.Rounding.RationalWeightedStep +OAI.Combinatorics.KMedian.Rounding.SignedGridInvariant +OAI.Combinatorics.KMedian.Rounding.SignedListOperations +OAI.Combinatorics.KMedian.Rounding.SignedPreparationProgram +OAI.Combinatorics.KMedian.Rounding.SignedRoundProgram +OAI.Combinatorics.KMedian.Rounding.SignedTerminalProgram +OAI.Combinatorics.KMedian.Rounding.TargetSubset +OAI.Combinatorics.KMedian.Rounding.TargetSubsetProgram +OAI.Combinatorics.KMedian.Rounding.UniformSplitRounding +OAI.Combinatorics.KMedian.Rounding.WeightedGridInvariant +OAI.Combinatorics.KMedian.Rounding.WeightedPartial +OAI.Combinatorics.KMedian.Rounding.WeightedRounding +OAI.Combinatorics.KMedian.Sparse.SparseAffineMoments +OAI.Combinatorics.KMedian.Sparse.SparseAlgorithm +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliFeatures +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliRun +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSubsets +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSupport +OAI.Combinatorics.KMedian.Sparse.SparseBind +OAI.Combinatorics.KMedian.Sparse.SparseBindProgram +OAI.Combinatorics.KMedian.Sparse.SparseBoundedCount +OAI.Combinatorics.KMedian.Sparse.SparseBoundedDrift +OAI.Combinatorics.KMedian.Sparse.SparseBoundedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseBranchProgram +OAI.Combinatorics.KMedian.Sparse.SparseBundleEncoding +OAI.Combinatorics.KMedian.Sparse.SparseBundleLaw +OAI.Combinatorics.KMedian.Sparse.SparseCardinalFixed +OAI.Combinatorics.KMedian.Sparse.SparseCardinalRounding +OAI.Combinatorics.KMedian.Sparse.SparseCompressProgram +OAI.Combinatorics.KMedian.Sparse.SparseConditionalCount +OAI.Combinatorics.KMedian.Sparse.SparseConditionalRoundDrift +OAI.Combinatorics.KMedian.Sparse.SparseCountFeatures +OAI.Combinatorics.KMedian.Sparse.SparseCountInstantiation +OAI.Combinatorics.KMedian.Sparse.SparseCountRun +OAI.Combinatorics.KMedian.Sparse.SparseCountStatistic +OAI.Combinatorics.KMedian.Sparse.SparseCoupledPreparation +OAI.Combinatorics.KMedian.Sparse.SparseDeletion +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedBatch +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedCount +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedEstimate +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFrozen +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFull +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraph +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedMixture +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseFiltered +OAI.Combinatorics.KMedian.Sparse.SparseGraphFeatures +OAI.Combinatorics.KMedian.Sparse.SparseGraphLaw +OAI.Combinatorics.KMedian.Sparse.SparseGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseGraphRun +OAI.Combinatorics.KMedian.Sparse.SparseGridRounding +OAI.Combinatorics.KMedian.Sparse.SparseGridZero +OAI.Combinatorics.KMedian.Sparse.SparseHistories +OAI.Combinatorics.KMedian.Sparse.SparseHistoryBounds +OAI.Combinatorics.KMedian.Sparse.SparseIntegerLaw +OAI.Combinatorics.KMedian.Sparse.SparseIterationHeight +OAI.Combinatorics.KMedian.Sparse.SparseListTrim +OAI.Combinatorics.KMedian.Sparse.SparseLocalBatch +OAI.Combinatorics.KMedian.Sparse.SparseMap +OAI.Combinatorics.KMedian.Sparse.SparseMapBind +OAI.Combinatorics.KMedian.Sparse.SparseMarginal +OAI.Combinatorics.KMedian.Sparse.SparseMarginalTools +OAI.Combinatorics.KMedian.Sparse.SparseMixProgram +OAI.Combinatorics.KMedian.Sparse.SparseMixture +OAI.Combinatorics.KMedian.Sparse.SparseMomentAlgebra +OAI.Combinatorics.KMedian.Sparse.SparseNonnegativeSupport +OAI.Combinatorics.KMedian.Sparse.SparseOuterCounts +OAI.Combinatorics.KMedian.Sparse.SparseOuterLaw +OAI.Combinatorics.KMedian.Sparse.SparseOuterMoments +OAI.Combinatorics.KMedian.Sparse.SparseOuterReal +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalBatch +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalCount +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalSurvival +OAI.Combinatorics.KMedian.Sparse.SparsePreparedBudget +OAI.Combinatorics.KMedian.Sparse.SparsePreparedLaw +OAI.Combinatorics.KMedian.Sparse.SparsePreparedMoments +OAI.Combinatorics.KMedian.Sparse.SparsePreparedProbability +OAI.Combinatorics.KMedian.Sparse.SparseProduct +OAI.Combinatorics.KMedian.Sparse.SparseProductProgram +OAI.Combinatorics.KMedian.Sparse.SparseRealExpectation +OAI.Combinatorics.KMedian.Sparse.SparseRealLaw +OAI.Combinatorics.KMedian.Sparse.SparseReduction +OAI.Combinatorics.KMedian.Sparse.SparseRescaledInner +OAI.Combinatorics.KMedian.Sparse.SparseSelect +OAI.Combinatorics.KMedian.Sparse.SparseSignedBudget +OAI.Combinatorics.KMedian.Sparse.SparseSignedFixed +OAI.Combinatorics.KMedian.Sparse.SparseSignedPartial +OAI.Combinatorics.KMedian.Sparse.SparseSignedPreparation +OAI.Combinatorics.KMedian.Sparse.SparseSignedRounding +OAI.Combinatorics.KMedian.Sparse.SparseStarActivation +OAI.Combinatorics.KMedian.Sparse.SparseSupplierSupport +OAI.Combinatorics.KMedian.Sparse.SparseSupport +OAI.Combinatorics.KMedian.Sparse.SparseSurvival +OAI.Combinatorics.KMedian.Sparse.SparseTable +OAI.Combinatorics.KMedian.Sparse.SparseTargetSubset +OAI.Combinatorics.KMedian.Sparse.SparseWeightedPartial +OAI.Combinatorics.KMedian.Sparse.SparseWeightedRounding +OAI.Combinatorics.KMedian.Threshold diff --git a/tasks/k-median-threshold/solution/reference.py b/tasks/k-median-threshold/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/k-median-threshold/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/k-median-threshold/solution/solve.sh b/tasks/k-median-threshold/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6fd34b496a97ae9a23d09faabd3a49d24e4fe884 --- /dev/null +++ b/tasks/k-median-threshold/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KMedianThreshold, i.e. module OAI.Combinatorics.KMedian.Threshold and the +# 765 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.KMedian.Threshold /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KMedianThreshold" diff --git a/tasks/k-median-threshold/task.toml b/tasks/k-median-threshold/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a88d56029c5465d47461d0fc3e586a64c3572fc1 --- /dev/null +++ b/tasks/k-median-threshold/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/k-median-threshold" +version = "1.0.0" +description = "Prove KMedianThreshold (openai/math family 125: The approximation threshold for metric $k$-median) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KMedianThreshold.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KMedianThreshold" +family = "125" +family_title = "The approximation threshold for metric $k$-median" +subject = "Theoretical computer science" +theorems = ["OAI.MetricKMedian.threshold"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.KMedian.Threshold" +reference_modules = 765 +reference_lean_bytes = 3236997 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2259 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14613 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/k-median-threshold/tests/Challenge.lean b/tasks/k-median-threshold/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d01bc34ac725698ac0bd8a5a9ca167c00ec1ced9 --- /dev/null +++ b/tasks/k-median-threshold/tests/Challenge.lean @@ -0,0 +1,107 @@ +import Mathlib + +namespace OAI + +section +section +namespace MetricKMedian + +structure Instance where + n : ℕ + distance : Fin n → Fin n → ℚ + clients : Finset (Fin n) + facilities : Finset (Fin n) + k : ℕ + distance_nonneg : ∀ i j, 0 ≤ distance i j + distance_eq_zero : ∀ i j, distance i j = 0 ↔ i = j + distance_symm : ∀ i j, distance i j = distance j i + distance_triangle : ∀ i j h, distance i h ≤ distance i j + distance j h + k_pos : 1 ≤ k + k_le : k ≤ facilities.card + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length true ++ [false] ++ n.bits + +def encodeRat (q : ℚ) : List Bool := + [decide (q.num < 0)] ++ encodeNat q.num.natAbs ++ encodeNat q.den + +def encodeInstance (I : Instance) : List Bool := + encodeNat I.n ++ encodeNat I.k ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.n => + (List.ofFn (fun j : Fin I.n => encodeRat (I.distance i j))).flatten)).flatten + +noncomputable def nearest (I : Instance) (j : Fin I.n) (S : Finset (Fin I.n)) : ℝ := + if h : S.Nonempty then + (S.image (fun i => (I.distance j i : ℝ))).min' (h.image _) + else 0 + +noncomputable def cost (I : Instance) (S : Finset (Fin I.n)) : ℝ := + ∑ j ∈ I.clients, nearest I j S + +def feasibleSets (I : Instance) : Finset (Finset (Fin I.n)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.k) + +noncomputable def optimum (I : Instance) : ℝ := + if h : (feasibleSets I).Nonempty then + ((feasibleSets I).image (cost I)).min' (h.image _) + else 0 + +def Correct (epsilon : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ (1 + 2 / Real.exp 1 + epsilon) * optimum I + +end MetricKMedian +end +end + +namespace MetricKMedian +namespace Complexity +/-- Polynomial-time computation with every physical work alphabet finite. -/ +def FinitePolyTime {α β : Type} (ea : α → List Bool) (eb : β → List Bool) + (f : α → β) : Prop := + ∃ p : Turing.TM2ComputableInPolyTime ea eb f, + ∀ k : p.tm.K, Finite (p.tm.Γ k) + +abbrev Word := List Bool +abbrev Language := Set Word + +def encodeBit (b : Bool) : Word := [b] + +def encodePair (x : Word × Word) : Word := + encodeNat x.1.length ++ x.1 ++ x.2 + +def P : Set Language := {L | ∃ decideL : Word → Bool, + FinitePolyTime id encodeBit decideL ∧ ∀ x, decideL x = true ↔ x ∈ L} + +def NP : Set Language := {L | ∃ (verify : Word × Word → Bool) (p : Polynomial ℕ), + FinitePolyTime encodePair encodeBit verify ∧ + ∀ x, x ∈ L ↔ ∃ w : Word, w.length ≤ p.eval x.length ∧ verify (x, w) = true} + +/-- Separation of deterministic polynomial time from finite-verifier nondeterministic polynomial time. -/ +def PNeNP : Prop := P ≠ NP + +end Complexity +/-- An actual nonempty feasible facility set, encoded by its membership mask. -/ +def FactorCorrect (α : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ α * optimum I + +/-- Deterministic polynomial-time approximation factors for arbitrary specified clients and facilities. -/ +def approximationFactors : Set ℝ := {α | ∃ algorithm : Instance → List Bool, + Complexity.FinitePolyTime encodeInstance id algorithm ∧ + ∀ I, FactorCorrect α I (algorithm I)} + +end MetricKMedian + +namespace MetricKMedian +/-- The deterministic approximation threshold is an infimum; its attainment is not asserted. -/ +theorem threshold (h : Complexity.PNeNP) : + sInf approximationFactors=1+2/Real.exp 1 := by + sorry +end MetricKMedian + +end OAI diff --git a/tasks/k-median-threshold/tests/grade.py b/tasks/k-median-threshold/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/k-median-threshold/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/k-median-threshold/tests/task.json b/tasks/k-median-threshold/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f09be062ac3683b64d24dd0f2e6ddd1351ff0347 --- /dev/null +++ b/tasks/k-median-threshold/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KMedianThreshold", + "comparator": { + "theorem_names": [ + "OAI.MetricKMedian.threshold" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 13713 +} \ No newline at end of file diff --git a/tasks/k-median-threshold/tests/test.sh b/tasks/k-median-threshold/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/k-median-threshold/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/k-server/environment/Dockerfile b/tasks/k-server/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/k-server/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/k-server/environment/fetch_mathlib.sh b/tasks/k-server/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/k-server/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/k-server/environment/lake-manifest.json b/tasks/k-server/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/k-server/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/k-server/environment/lakefile.lean b/tasks/k-server/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/k-server/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/k-server/environment/lean_setup.sh b/tasks/k-server/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/k-server/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/k-server/environment/pack_submission.py b/tasks/k-server/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/k-server/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/k-server/instruction.md b/tasks/k-server/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..08b3d503d9a7ce7cc9a7c1c20b16eba8f76aaa97 --- /dev/null +++ b/tasks/k-server/instruction.md @@ -0,0 +1,120 @@ +# openai/math challenge `KServer` (family 110) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 110 of the release, *Optimal-order randomized $k$-server on arbitrary metrics* +(Theoretical computer science). The family as a whole: Establishes a randomized competitive ratio $O(\log^2(k+1))$ for $k$-server on every metric space, matching the worst-case lower-bound order. One policy serves every finite oblivious request sequence, including on infinite unbounded metrics. On finite rational metrics, a uniform implementation has polynomial preprocessing and per-request bit cost in the input length and $\log(t+1)$ at request $t$, with a finite instance-dependent additive movement constant. + +The challenge is `KServer`, also at `/opt/openai-math/challenges/KServer.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace KServer + +universe u + +abbrev Configuration (k : ℕ) (X : Type u) := Fin k → X + +def LabelDistribution (k : ℕ) := + {probability : Fin k → ℝ // + (∀ label, 0 ≤ probability label) ∧ ∑ label, probability label = 1} + +abbrev Policy (k : ℕ) (X : Type u) := + List (X × Fin k) → X → LabelDistribution k + +def serve {k : ℕ} {X : Type u} (s : Configuration k X) + (label : Fin k) (request : X) : Configuration k X := + Function.update s label request + +def serviceCost {k : ℕ} {X : Type u} [MetricSpace X] + (s : Configuration k X) : (requests : List X) → (Fin requests.length → Fin k) → ℝ + | [], _ => 0 + | request :: requests, labels => + dist (s (labels 0)) request + + serviceCost (serve s (labels 0) request) requests (fun index => labels index.succ) + +def pathProbability {k : ℕ} {X : Type u} (A : Policy k X) + (history : List (X × Fin k)) : + (requests : List X) → (Fin requests.length → Fin k) → ℝ + | [], _ => 1 + | request :: requests, labels => + (A history request).val (labels 0) * + pathProbability A (history ++ [(request, labels 0)]) requests + (fun index => labels index.succ) + +def expectedCost {k : ℕ} {X : Type u} [MetricSpace X] + (A : Policy k X) (s : Configuration k X) (requests : List X) : ℝ := + ∑ labels : Fin requests.length → Fin k, + pathProbability A [] requests labels * serviceCost s requests labels + +def optimalCost {k : ℕ} {X : Type u} [MetricSpace X] + (s : Configuration k X) (requests : List X) : ℝ := + sInf (Set.range (serviceCost s requests)) + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (k : ℕ), 2 ≤ k → + ∀ (X : Type u) (_ : MetricSpace X), + (∃ embedding : Fin (k + 1) → X, Function.Injective embedding) → + ∀ s : Configuration k X, + ∃ A : Policy k X, ∃ B : ℝ, + 0 ≤ B ∧ (Function.Injective s → B = 0) ∧ + ∀ requests : List X, + expectedCost A s requests ≤ + C * (Real.log (k + 1)) ^ 2 * optimalCost s requests + B + +theorem main_theorem : MainStatement.{u} := by + sorry + +end KServer + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KServer.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KServer.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/k-server/solution/closure.txt b/tasks/k-server/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4e956437f1865ec89a47f7db05ade589e2ea3fca --- /dev/null +++ b/tasks/k-server/solution/closure.txt @@ -0,0 +1,37 @@ +OAI.Combinatorics.KServer.Allocation +OAI.Combinatorics.KServer.AllocationBudget +OAI.Combinatorics.KServer.AllocationCausality +OAI.Combinatorics.KServer.AllocationMovement +OAI.Combinatorics.KServer.AllocationSchedule +OAI.Combinatorics.KServer.Amplification +OAI.Combinatorics.KServer.AnchorTravel +OAI.Combinatorics.KServer.Basic +OAI.Combinatorics.KServer.Behavior +OAI.Combinatorics.KServer.Caps +OAI.Combinatorics.KServer.CausalRounding +OAI.Combinatorics.KServer.Coarse +OAI.Combinatorics.KServer.Experiments +OAI.Combinatorics.KServer.FiniteLaw +OAI.Combinatorics.KServer.Hierarchy +OAI.Combinatorics.KServer.JointBudget +OAI.Combinatorics.KServer.JointExperiment +OAI.Combinatorics.KServer.JointTravel +OAI.Combinatorics.KServer.Main +OAI.Combinatorics.KServer.MetricMatching +OAI.Combinatorics.KServer.MetricService +OAI.Combinatorics.KServer.Minimization +OAI.Combinatorics.KServer.OutputDynamics +OAI.Combinatorics.KServer.OutputRules +OAI.Combinatorics.KServer.PartitionBudget +OAI.Combinatorics.KServer.Partitions +OAI.Combinatorics.KServer.Potential +OAI.Combinatorics.KServer.PrefixAllocation +OAI.Combinatorics.KServer.RankProportions +OAI.Combinatorics.KServer.Ranks +OAI.Combinatorics.KServer.RosterEdits +OAI.Combinatorics.KServer.Rosters +OAI.Combinatorics.KServer.Rounding +OAI.Combinatorics.KServer.ScheduleBudget +OAI.Combinatorics.KServer.Simplex +OAI.Combinatorics.KServer.Tiers +OAI.Combinatorics.KServer.Trees diff --git a/tasks/k-server/solution/reference.py b/tasks/k-server/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/k-server/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/k-server/solution/solve.sh b/tasks/k-server/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..45777770e269b375dd7a90af54673efa3f083e23 --- /dev/null +++ b/tasks/k-server/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KServer, i.e. module OAI.Combinatorics.KServer.Main and the +# 37 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.KServer.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KServer" diff --git a/tasks/k-server/task.toml b/tasks/k-server/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1a99c574dd1a85ca8bb3eee956b18cb3320ffa2d --- /dev/null +++ b/tasks/k-server/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/k-server" +version = "1.0.0" +description = "Prove KServer (openai/math family 110: Optimal-order randomized $k$-server on arbitrary metrics) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KServer.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KServer" +family = "110" +family_title = "Optimal-order randomized $k$-server on arbitrary metrics" +subject = "Theoretical computer science" +theorems = ["OAI.KServer.main_theorem"] +definition_holes = [] +fixed_definitions = ["OAI.KServer.Configuration", "OAI.KServer.LabelDistribution", "OAI.KServer.Policy", "OAI.KServer.serve", "OAI.KServer.serviceCost", "OAI.KServer.pathProbability", "OAI.KServer.expectedCost", "OAI.KServer.optimalCost", "OAI.KServer.MainStatement"] +reference_module = "OAI.Combinatorics.KServer.Main" +reference_modules = 37 +reference_lean_bytes = 1783312 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 587 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13304 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/k-server/tests/Challenge.lean b/tasks/k-server/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9c7d0901a84441ba64d4e09f480f92049c35de2c --- /dev/null +++ b/tasks/k-server/tests/Challenge.lean @@ -0,0 +1,69 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace KServer + +universe u + +abbrev Configuration (k : ℕ) (X : Type u) := Fin k → X + +def LabelDistribution (k : ℕ) := + {probability : Fin k → ℝ // + (∀ label, 0 ≤ probability label) ∧ ∑ label, probability label = 1} + +abbrev Policy (k : ℕ) (X : Type u) := + List (X × Fin k) → X → LabelDistribution k + +def serve {k : ℕ} {X : Type u} (s : Configuration k X) + (label : Fin k) (request : X) : Configuration k X := + Function.update s label request + +def serviceCost {k : ℕ} {X : Type u} [MetricSpace X] + (s : Configuration k X) : (requests : List X) → (Fin requests.length → Fin k) → ℝ + | [], _ => 0 + | request :: requests, labels => + dist (s (labels 0)) request + + serviceCost (serve s (labels 0) request) requests (fun index => labels index.succ) + +def pathProbability {k : ℕ} {X : Type u} (A : Policy k X) + (history : List (X × Fin k)) : + (requests : List X) → (Fin requests.length → Fin k) → ℝ + | [], _ => 1 + | request :: requests, labels => + (A history request).val (labels 0) * + pathProbability A (history ++ [(request, labels 0)]) requests + (fun index => labels index.succ) + +def expectedCost {k : ℕ} {X : Type u} [MetricSpace X] + (A : Policy k X) (s : Configuration k X) (requests : List X) : ℝ := + ∑ labels : Fin requests.length → Fin k, + pathProbability A [] requests labels * serviceCost s requests labels + +def optimalCost {k : ℕ} {X : Type u} [MetricSpace X] + (s : Configuration k X) (requests : List X) : ℝ := + sInf (Set.range (serviceCost s requests)) + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (k : ℕ), 2 ≤ k → + ∀ (X : Type u) (_ : MetricSpace X), + (∃ embedding : Fin (k + 1) → X, Function.Injective embedding) → + ∀ s : Configuration k X, + ∃ A : Policy k X, ∃ B : ℝ, + 0 ≤ B ∧ (Function.Injective s → B = 0) ∧ + ∀ requests : List X, + expectedCost A s requests ≤ + C * (Real.log (k + 1)) ^ 2 * optimalCost s requests + B + +theorem main_theorem : MainStatement.{u} := by + sorry + +end KServer + +end + +end OAI diff --git a/tasks/k-server/tests/grade.py b/tasks/k-server/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/k-server/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/k-server/tests/task.json b/tasks/k-server/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..182af961f290bdaf106f48b06516a6e74715e0cd --- /dev/null +++ b/tasks/k-server/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KServer", + "comparator": { + "theorem_names": [ + "OAI.KServer.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12404 +} \ No newline at end of file diff --git a/tasks/k-server/tests/test.sh b/tasks/k-server/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/k-server/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kadison-ringrose/environment/Dockerfile b/tasks/kadison-ringrose/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kadison-ringrose/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kadison-ringrose/environment/fetch_mathlib.sh b/tasks/kadison-ringrose/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kadison-ringrose/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kadison-ringrose/environment/lake-manifest.json b/tasks/kadison-ringrose/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kadison-ringrose/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kadison-ringrose/environment/lakefile.lean b/tasks/kadison-ringrose/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kadison-ringrose/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kadison-ringrose/environment/lean_setup.sh b/tasks/kadison-ringrose/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kadison-ringrose/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kadison-ringrose/environment/pack_submission.py b/tasks/kadison-ringrose/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kadison-ringrose/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kadison-ringrose/instruction.md b/tasks/kadison-ringrose/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2fe3a599208f456885e63d9aed55f0fd9f804f0d --- /dev/null +++ b/tasks/kadison-ringrose/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `KadisonRingrose` (family 295) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 295 of the release, *The Kadison–Ringrose cohomology conjecture* +(Operator algebras). The family as a whole: Proves that every bounded Hochschild cocycle of degree at least two on a complex von Neumann algebra, with coefficients in the algebra itself, has a bounded primitive. Equivalently, all higher bounded Hochschild cohomology groups vanish, resolving the Kadison–Ringrose conjecture. + +The challenge is `KadisonRingrose`, also at `/opt/openai-math/challenges/KadisonRingrose.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Every ordinary bounded higher Hochschild cocycle of a complex von Neumann +algebra is the coboundary of a bounded cochain with values in the same algebra. -/ + +noncomputable section + +namespace BoundedHochschild + +abbrev Cochain (M : Type*) [NormedAddCommGroup M] [NormedSpace ℂ M] (n : ℕ) := + ContinuousMultilinearMap ℂ (fun _ : Fin n => M) M + +def mergeInputs {M : Type*} [Mul M] {n : ℕ} + (v : Fin (n + 1) → M) (j : Fin n) : Fin n → M := + fun i => if i < j then v i.castSucc + else if i = j then v i.castSucc * v i.succ else v i.succ + +noncomputable def differentialValue {M : Type*} [NormedRing M] [NormedAlgebra ℂ M] + {n : ℕ} (f : Cochain M n) (v : Fin (n + 1) → M) : M := + v 0 * f (fun i => v i.succ) + + ∑ j : Fin n, ((-1 : ℂ) ^ (j.val + 1)) • f (mergeInputs v j) + + ((-1 : ℂ) ^ (n + 1)) • (f (fun i => v i.castSucc) * v (Fin.last n)) + +namespace KadisonRingrose + +universe u + +theorem main_result + {M : Type u} [CStarAlgebra M] [PartialOrder M] [StarOrderedRing M] [WStarAlgebra M] + (n : ℕ) (f : Cochain M (n + 2)) + (hf : ∀ x : Fin (n + 3) → M, differentialValue f x = 0) : + ∃ g : Cochain M (n + 1), ∀ x : Fin (n + 2) → M, + differentialValue g x = f x := by + sorry + +end KadisonRingrose +end BoundedHochschild + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KadisonRingrose.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.BoundedHochschild.KadisonRingrose.main_result` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kadison-ringrose/solution/closure.txt b/tasks/kadison-ringrose/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..05089050b3baaf3c656810675b6da32d17a3f0c6 --- /dev/null +++ b/tasks/kadison-ringrose/solution/closure.txt @@ -0,0 +1,372 @@ +OAI.Analysis.BoundedHochschild.AbelianCentralSupport +OAI.Analysis.BoundedHochschild.AbelianComparison +OAI.Analysis.BoundedHochschild.AbelianPartitions +OAI.Analysis.BoundedHochschild.AbelianPrimitives +OAI.Analysis.BoundedHochschild.AbelianProjectionForms +OAI.Analysis.BoundedHochschild.AbelianSupportEquivalence +OAI.Analysis.BoundedHochschild.AbelianTypeI +OAI.Analysis.BoundedHochschild.AdditivePositiveSupport +OAI.Analysis.BoundedHochschild.AlgebraicMatrixPrimitives +OAI.Analysis.BoundedHochschild.AlternatingMoments +OAI.Analysis.BoundedHochschild.AsymptoticRigidity +OAI.Analysis.BoundedHochschild.AveragedBarFaces +OAI.Analysis.BoundedHochschild.AveragingOrbitFactorization +OAI.Analysis.BoundedHochschild.BarDifferential +OAI.Analysis.BoundedHochschild.BarInsertionFaces +OAI.Analysis.BoundedHochschild.BarInsertionFormula +OAI.Analysis.BoundedHochschild.BlockSpans +OAI.Analysis.BoundedHochschild.CStarQuotients +OAI.Analysis.BoundedHochschild.Catalan +OAI.Analysis.BoundedHochschild.CatalanWords +OAI.Analysis.BoundedHochschild.CenterAveragingReduction +OAI.Analysis.BoundedHochschild.CentralBlockSpans +OAI.Analysis.BoundedHochschild.CentralBlockUnitaries +OAI.Analysis.BoundedHochschild.CentralColumnCuts +OAI.Analysis.BoundedHochschild.CentralComparison +OAI.Analysis.BoundedHochschild.CentralHomotopy +OAI.Analysis.BoundedHochschild.CentralPrimitives +OAI.Analysis.BoundedHochschild.CentralProjectionPartitions +OAI.Analysis.BoundedHochschild.CentralProjectionSuprema +OAI.Analysis.BoundedHochschild.CentralRowCompression +OAI.Analysis.BoundedHochschild.CentralSeparation +OAI.Analysis.BoundedHochschild.CentralSupportCuts +OAI.Analysis.BoundedHochschild.CentralSupportNormalizedRows +OAI.Analysis.BoundedHochschild.CentralSupportRows +OAI.Analysis.BoundedHochschild.CentralTypeIIInheritance +OAI.Analysis.BoundedHochschild.CentralVanishing +OAI.Analysis.BoundedHochschild.ClassicalVanishingReduction +OAI.Analysis.BoundedHochschild.CochainAverages +OAI.Analysis.BoundedHochschild.CochainLimitDifferential +OAI.Analysis.BoundedHochschild.CochainLimits +OAI.Analysis.BoundedHochschild.CochainTransportFaces +OAI.Analysis.BoundedHochschild.CochainTransportMiddle +OAI.Analysis.BoundedHochschild.Cochains +OAI.Analysis.BoundedHochschild.CocycleNormalParts +OAI.Analysis.BoundedHochschild.CollisionBounds +OAI.Analysis.BoundedHochschild.ColumnRowEstimates +OAI.Analysis.BoundedHochschild.CommutantQuantization +OAI.Analysis.BoundedHochschild.CompactConvexCenter +OAI.Analysis.BoundedHochschild.CompactFamilyAverages +OAI.Analysis.BoundedHochschild.CompactInvariantSets +OAI.Analysis.BoundedHochschild.CompleteAdditivity +OAI.Analysis.BoundedHochschild.CompletelyBoundedArithmetic +OAI.Analysis.BoundedHochschild.CompletelyBoundedFactorization +OAI.Analysis.BoundedHochschild.CompletelyBoundedLastSlices +OAI.Analysis.BoundedHochschild.CompletelyBoundedMapSpace +OAI.Analysis.BoundedHochschild.CompletelyBoundedPrimitives +OAI.Analysis.BoundedHochschild.CompletelyBoundedRows +OAI.Analysis.BoundedHochschild.CompletelyPositiveCompression +OAI.Analysis.BoundedHochschild.CompletelyPositiveLimits +OAI.Analysis.BoundedHochschild.CompletelyPositiveNorm +OAI.Analysis.BoundedHochschild.CompressedAveragingNorms +OAI.Analysis.BoundedHochschild.Conditional +OAI.Analysis.BoundedHochschild.CornerEquivalences +OAI.Analysis.BoundedHochschild.CornerUnitaryExtension +OAI.Analysis.BoundedHochschild.Corners +OAI.Analysis.BoundedHochschild.CountableColumnRegrouping +OAI.Analysis.BoundedHochschild.CountableDiagonalOperators +OAI.Analysis.BoundedHochschild.CountableMatrixAverage +OAI.Analysis.BoundedHochschild.CountableMatrixBarOperators +OAI.Analysis.BoundedHochschild.CountableMatrixCorners +OAI.Analysis.BoundedHochschild.CountableMatrixGroups +OAI.Analysis.BoundedHochschild.CountableMatrixHomotopy +OAI.Analysis.BoundedHochschild.CountableMatrixPrimitives +OAI.Analysis.BoundedHochschild.CountableMatrixProjection +OAI.Analysis.BoundedHochschild.CountableMatrixSpan +OAI.Analysis.BoundedHochschild.CountableMatrixSubalgebra +OAI.Analysis.BoundedHochschild.CountableMatrixTypeI +OAI.Analysis.BoundedHochschild.DiffuseProjections +OAI.Analysis.BoundedHochschild.Dixmier +OAI.Analysis.BoundedHochschild.DoubleCoordinates +OAI.Analysis.BoundedHochschild.EncodedMapFamilies +OAI.Analysis.BoundedHochschild.ExponentialLifts +OAI.Analysis.BoundedHochschild.FactorCandidateCompactness +OAI.Analysis.BoundedHochschild.FactorFinitePaths +OAI.Analysis.BoundedHochschild.FactorizedProjectionDefects +OAI.Analysis.BoundedHochschild.FiniteBarCancellation +OAI.Analysis.BoundedHochschild.FiniteBarHomotopy +OAI.Analysis.BoundedHochschild.FiniteCentralDecomposition +OAI.Analysis.BoundedHochschild.FiniteCoefficientExtension +OAI.Analysis.BoundedHochschild.FiniteColumnCorners +OAI.Analysis.BoundedHochschild.FiniteCompressionExtension +OAI.Analysis.BoundedHochschild.FiniteConstraints +OAI.Analysis.BoundedHochschild.FiniteCornerGroups +OAI.Analysis.BoundedHochschild.FiniteCountableComparison +OAI.Analysis.BoundedHochschild.FiniteFunctionAverages +OAI.Analysis.BoundedHochschild.FiniteGroupBarOperators +OAI.Analysis.BoundedHochschild.FiniteGroupCochainAverages +OAI.Analysis.BoundedHochschild.FiniteGroupCochainChainMap +OAI.Analysis.BoundedHochschild.FiniteGroupModuleAverages +OAI.Analysis.BoundedHochschild.FiniteGroupMultimodularity +OAI.Analysis.BoundedHochschild.FiniteGroupPrefixAverages +OAI.Analysis.BoundedHochschild.FiniteIncreasingComparison +OAI.Analysis.BoundedHochschild.FiniteModuleAverages +OAI.Analysis.BoundedHochschild.FiniteMoments +OAI.Analysis.BoundedHochschild.FiniteNormalOrbit +OAI.Analysis.BoundedHochschild.FiniteNormalState +OAI.Analysis.BoundedHochschild.FiniteNormalTrace +OAI.Analysis.BoundedHochschild.FinitePaths +OAI.Analysis.BoundedHochschild.FinitePhases +OAI.Analysis.BoundedHochschild.FinitePositiveExtension +OAI.Analysis.BoundedHochschild.FiniteProjectionAbsoluteContinuity +OAI.Analysis.BoundedHochschild.FiniteProjectionEquivalence +OAI.Analysis.BoundedHochschild.FiniteProjectionExtension +OAI.Analysis.BoundedHochschild.FiniteRightAveraging +OAI.Analysis.BoundedHochschild.FiniteTraceCover +OAI.Analysis.BoundedHochschild.FiniteTracialDecomposition +OAI.Analysis.BoundedHochschild.FiniteTypeIPieces +OAI.Analysis.BoundedHochschild.FiniteTypeIVanishing +OAI.Analysis.BoundedHochschild.FiniteUnitaryPrimitives +OAI.Analysis.BoundedHochschild.FirstLetter +OAI.Analysis.BoundedHochschild.FixedFactorizationLimits +OAI.Analysis.BoundedHochschild.FlipMatrixNesting +OAI.Analysis.BoundedHochschild.Frames +OAI.Analysis.BoundedHochschild.FreeCoefficients +OAI.Analysis.BoundedHochschild.FreeHaarFamilies +OAI.Analysis.BoundedHochschild.FreeWords +OAI.Analysis.BoundedHochschild.Haagerup +OAI.Analysis.BoundedHochschild.HarmonicSums +OAI.Analysis.BoundedHochschild.HomogeneousCornerTransport +OAI.Analysis.BoundedHochschild.HomogeneousTypeI +OAI.Analysis.BoundedHochschild.HomogeneousTypeIPrimitives +OAI.Analysis.BoundedHochschild.IncrementalPatching +OAI.Analysis.BoundedHochschild.InfiniteAveragingLimits +OAI.Analysis.BoundedHochschild.InfiniteCentralReduction +OAI.Analysis.BoundedHochschild.InfiniteInvariantFamilies +OAI.Analysis.BoundedHochschild.InfiniteMatrixColumns +OAI.Analysis.BoundedHochschild.InfiniteOperatorRows +OAI.Analysis.BoundedHochschild.InfinitePairChains +OAI.Analysis.BoundedHochschild.InfiniteRepresentedAverages +OAI.Analysis.BoundedHochschild.InfiniteRepresentedFamilies +OAI.Analysis.BoundedHochschild.IsometricFixedPoint +OAI.Analysis.BoundedHochschild.IsometryAbsorption +OAI.Analysis.BoundedHochschild.IsometryDefectColumns +OAI.Analysis.BoundedHochschild.JointAveragingRelations +OAI.Analysis.BoundedHochschild.LeftSandwichAverages +OAI.Analysis.BoundedHochschild.LiftedOrbitRealization +OAI.Analysis.BoundedHochschild.Liouville +OAI.Analysis.BoundedHochschild.Main +OAI.Analysis.BoundedHochschild.MainResult +OAI.Analysis.BoundedHochschild.Martingales +OAI.Analysis.BoundedHochschild.MatrixAmplification +OAI.Analysis.BoundedHochschild.MatrixAverageLimits +OAI.Analysis.BoundedHochschild.MatrixBarLimits +OAI.Analysis.BoundedHochschild.MatrixBlockGroups +OAI.Analysis.BoundedHochschild.MatrixCommutants +OAI.Analysis.BoundedHochschild.MatrixCornerCommutant +OAI.Analysis.BoundedHochschild.MatrixDilation +OAI.Analysis.BoundedHochschild.MatrixDisplacement +OAI.Analysis.BoundedHochschild.MatrixFunctionalDilation +OAI.Analysis.BoundedHochschild.MatrixRightAveraging +OAI.Analysis.BoundedHochschild.MatrixScalarColumns +OAI.Analysis.BoundedHochschild.MatrixSectionAveraging +OAI.Analysis.BoundedHochschild.MatrixSystems +OAI.Analysis.BoundedHochschild.MaximalInfiniteProjection +OAI.Analysis.BoundedHochschild.MinimalIsometricOrbit +OAI.Analysis.BoundedHochschild.MinimalProjectionNorms +OAI.Analysis.BoundedHochschild.MinimalRepresentedAverages +OAI.Analysis.BoundedHochschild.MinimalRightAverages +OAI.Analysis.BoundedHochschild.MixedWords +OAI.Analysis.BoundedHochschild.MomentNorms +OAI.Analysis.BoundedHochschild.MonotoneLimits +OAI.Analysis.BoundedHochschild.MultimodularCofaces +OAI.Analysis.BoundedHochschild.MultimodularColumns +OAI.Analysis.BoundedHochschild.MultimodularEndFaces +OAI.Analysis.BoundedHochschild.MultimodularGenerators +OAI.Analysis.BoundedHochschild.MultimodularInsertion +OAI.Analysis.BoundedHochschild.MultimodularMatrixBound +OAI.Analysis.BoundedHochschild.MultimodularMergeBalance +OAI.Analysis.BoundedHochschild.MultimodularMerges +OAI.Analysis.BoundedHochschild.MultimodularNormalReduction +OAI.Analysis.BoundedHochschild.MultimodularTransport +OAI.Analysis.BoundedHochschild.NestedMatrixAmplification +OAI.Analysis.BoundedHochschild.NormalBarOperators +OAI.Analysis.BoundedHochschild.NormalCochainTransport +OAI.Analysis.BoundedHochschild.NormalFactorCandidates +OAI.Analysis.BoundedHochschild.NormalGNSConvergence +OAI.Analysis.BoundedHochschild.NormalGNSMatrices +OAI.Analysis.BoundedHochschild.NormalGNSRepresentation +OAI.Analysis.BoundedHochschild.NormalGNSWeakTopology +OAI.Analysis.BoundedHochschild.NormalInfiniteAverages +OAI.Analysis.BoundedHochschild.NormalModulus +OAI.Analysis.BoundedHochschild.NormalMultimodularClosure +OAI.Analysis.BoundedHochschild.NormalMultimodularity +OAI.Analysis.BoundedHochschild.NormalMultiplication +OAI.Analysis.BoundedHochschild.NormalOperators +OAI.Analysis.BoundedHochschild.NormalOrbitHull +OAI.Analysis.BoundedHochschild.NormalOrbitInvariance +OAI.Analysis.BoundedHochschild.NormalOrderIntervals +OAI.Analysis.BoundedHochschild.NormalStatePartitions +OAI.Analysis.BoundedHochschild.NormalTraceFaithfulness +OAI.Analysis.BoundedHochschild.NormalVectors +OAI.Analysis.BoundedHochschild.OperatorPrimitives +OAI.Analysis.BoundedHochschild.OperatorRowAverages +OAI.Analysis.BoundedHochschild.OperatorSystemCompression +OAI.Analysis.BoundedHochschild.OperatorSystemExtension +OAI.Analysis.BoundedHochschild.OperatorSystemFunctionals +OAI.Analysis.BoundedHochschild.OperatorSystemMatrices +OAI.Analysis.BoundedHochschild.OperatorTransport +OAI.Analysis.BoundedHochschild.OperatorTypeI +OAI.Analysis.BoundedHochschild.OrthogonalPartialIsoSums +OAI.Analysis.BoundedHochschild.OrthogonalProjectionSums +OAI.Analysis.BoundedHochschild.OrthogonalProjectionTails +OAI.Analysis.BoundedHochschild.PartialIsoCornerEquivalence +OAI.Analysis.BoundedHochschild.PartialIsoProducts +OAI.Analysis.BoundedHochschild.PartialIsometries +OAI.Analysis.BoundedHochschild.PartialIsometryChains +OAI.Analysis.BoundedHochschild.PartialUnitaries +OAI.Analysis.BoundedHochschild.PathStages +OAI.Analysis.BoundedHochschild.PathWords +OAI.Analysis.BoundedHochschild.PaulsenEntries +OAI.Analysis.BoundedHochschild.PaulsenExtension +OAI.Analysis.BoundedHochschild.PaulsenMatrixBlocks +OAI.Analysis.BoundedHochschild.PaulsenPositivity +OAI.Analysis.BoundedHochschild.PaulsenSystem +OAI.Analysis.BoundedHochschild.PolarApproximation +OAI.Analysis.BoundedHochschild.PositiveBlockRegularization +OAI.Analysis.BoundedHochschild.PositiveBlockTransfer +OAI.Analysis.BoundedHochschild.PositiveBlocks +OAI.Analysis.BoundedHochschild.PositiveCompleteAdditivity +OAI.Analysis.BoundedHochschild.PositiveCompression +OAI.Analysis.BoundedHochschild.PositiveDecomposition +OAI.Analysis.BoundedHochschild.PositiveKernelActions +OAI.Analysis.BoundedHochschild.PositiveKernelMatrices +OAI.Analysis.BoundedHochschild.PositiveKernelSpace +OAI.Analysis.BoundedHochschild.PositiveNormalParts +OAI.Analysis.BoundedHochschild.PositiveOrbitCompactness +OAI.Analysis.BoundedHochschild.PositiveProjectionGap +OAI.Analysis.BoundedHochschild.PositiveUnitBlocks +OAI.Analysis.BoundedHochschild.PowerRigidity +OAI.Analysis.BoundedHochschild.PrimitiveAverages +OAI.Analysis.BoundedHochschild.ProductTaylor +OAI.Analysis.BoundedHochschild.ProjectionChainSuprema +OAI.Analysis.BoundedHochschild.ProjectionDefectRigidity +OAI.Analysis.BoundedHochschild.ProjectionJoinComparison +OAI.Analysis.BoundedHochschild.ProjectionModuleMaps +OAI.Analysis.BoundedHochschild.ProjectionNormGap +OAI.Analysis.BoundedHochschild.ProjectionPositivity +OAI.Analysis.BoundedHochschild.ProjectionSequenceLimits +OAI.Analysis.BoundedHochschild.ProperlyInfiniteColumns +OAI.Analysis.BoundedHochschild.ProperlyInfiniteCorners +OAI.Analysis.BoundedHochschild.ProperlyInfiniteIsometries +OAI.Analysis.BoundedHochschild.ProperlyInfiniteMatrixSystems +OAI.Analysis.BoundedHochschild.ProperlyInfinitePrimitives +OAI.Analysis.BoundedHochschild.PublishedInputs +OAI.Analysis.BoundedHochschild.RankOneQuantization +OAI.Analysis.BoundedHochschild.RareScales +OAI.Analysis.BoundedHochschild.RectangularWeakCompactness +OAI.Analysis.BoundedHochschild.RelativeQuantization +OAI.Analysis.BoundedHochschild.RepresentedAveragingAlgebra +OAI.Analysis.BoundedHochschild.RepresentedAveragingConvexity +OAI.Analysis.BoundedHochschild.RepresentedAveragingOrbit +OAI.Analysis.BoundedHochschild.RepresentedPositiveGap +OAI.Analysis.BoundedHochschild.RepresentedRightAverages +OAI.Analysis.BoundedHochschild.RightAveragingAlgebra +OAI.Analysis.BoundedHochschild.RightAveragingOrbit +OAI.Analysis.BoundedHochschild.RightModuleAveragingExistence +OAI.Analysis.BoundedHochschild.RightModuleFixedPoints +OAI.Analysis.BoundedHochschild.RightModuleProjection +OAI.Analysis.BoundedHochschild.RowDefectCompletion +OAI.Analysis.BoundedHochschild.ScalarMatrixActions +OAI.Analysis.BoundedHochschild.ScalarPositiveBlocks +OAI.Analysis.BoundedHochschild.SeparablePrimitives +OAI.Analysis.BoundedHochschild.SignedMatrixUnitaries +OAI.Analysis.BoundedHochschild.SimultaneousModuleAverages +OAI.Analysis.BoundedHochschild.SpectralProjections +OAI.Analysis.BoundedHochschild.StarPreduals +OAI.Analysis.BoundedHochschild.StinespringBounds +OAI.Analysis.BoundedHochschild.StinespringEmbedding +OAI.Analysis.BoundedHochschild.StinespringKernel +OAI.Analysis.BoundedHochschild.StinespringLeftAction +OAI.Analysis.BoundedHochschild.StinespringRepresentation +OAI.Analysis.BoundedHochschild.StinespringStar +OAI.Analysis.BoundedHochschild.StrongRowDefect +OAI.Analysis.BoundedHochschild.SubalgebraMatrixColumns +OAI.Analysis.BoundedHochschild.SubnormalizedOperatorRows +OAI.Analysis.BoundedHochschild.TraceExpectations +OAI.Analysis.BoundedHochschild.TraceFreeComparison +OAI.Analysis.BoundedHochschild.TraceFreeHalving +OAI.Analysis.BoundedHochschild.TraceFreeProjectionJoins +OAI.Analysis.BoundedHochschild.TraceFreeSeparation +OAI.Analysis.BoundedHochschild.TracialCoverReduction +OAI.Analysis.BoundedHochschild.TracialDecomposition +OAI.Analysis.BoundedHochschild.TracialModulus +OAI.Analysis.BoundedHochschild.TracialTypeIHomogeneousPiece +OAI.Analysis.BoundedHochschild.TypeICentralDecomposition +OAI.Analysis.BoundedHochschild.TypeICentralPieces +OAI.Analysis.BoundedHochschild.TypeICentralSupport +OAI.Analysis.BoundedHochschild.TypeIColumnArithmetic +OAI.Analysis.BoundedHochschild.TypeIColumnExtension +OAI.Analysis.BoundedHochschild.TypeIICharacterization +OAI.Analysis.BoundedHochschild.TypeIIDefinitions +OAI.Analysis.BoundedHochschild.TypeIIStructure +OAI.Analysis.BoundedHochschild.TypeIMatrixColumns +OAI.Analysis.BoundedHochschild.UltrapowerMoments +OAI.Analysis.BoundedHochschild.Ultrapowers +OAI.Analysis.BoundedHochschild.UniformProjectionSums +OAI.Analysis.BoundedHochschild.UnitInsertionFaces +OAI.Analysis.BoundedHochschild.UnitalPositiveExtension +OAI.Analysis.BoundedHochschild.UnitaryLifts +OAI.Analysis.BoundedHochschild.UnitaryPredualAction +OAI.Analysis.BoundedHochschild.UnitaryPrefixDeletion +OAI.Analysis.BoundedHochschild.UniversalGNSRepresentation +OAI.Analysis.BoundedHochschild.WalkEndpoints +OAI.Analysis.BoundedHochschild.WalkLabels +OAI.Analysis.BoundedHochschild.WalkSelection +OAI.Analysis.BoundedHochschild.WeakAlgebras +OAI.Analysis.BoundedHochschild.WeakCompactFragment +OAI.Analysis.BoundedHochschild.WeakCompletelyBoundedClosure +OAI.Analysis.BoundedHochschild.WeakIsometricFixedPoint +OAI.Analysis.BoundedHochschild.WeakOperatorCompactness +OAI.Analysis.BoundedHochschild.WeakPredual +OAI.Analysis.BoundedHochschild.WeakRepresentationAverages +OAI.Analysis.BoundedHochschild.WeakRightAveraging +OAI.Analysis.BoundedHochschild.WeakSubspaces +OAI.Analysis.FactorGeneration.OperatorLimits +OAI.Analysis.Naimark.Basic +OAI.Analysis.Naimark.States +OAI.Analysis.TracialCohomology.BidualApproximation +OAI.Analysis.TracialCohomology.BilinearModulus +OAI.Analysis.TracialCohomology.CenterExtensions +OAI.Analysis.TracialCohomology.CenterQuantization +OAI.Analysis.TracialCohomology.CenterTrace +OAI.Analysis.TracialCohomology.CentralMatrices +OAI.Analysis.TracialCohomology.Cohomology +OAI.Analysis.TracialCohomology.CornerComparison +OAI.Analysis.TracialCohomology.CornerTraces +OAI.Analysis.TracialCohomology.Corners +OAI.Analysis.TracialCohomology.DominatedFactorization +OAI.Analysis.TracialCohomology.Expectations +OAI.Analysis.TracialCohomology.FinitePaths +OAI.Analysis.TracialCohomology.FreeSeparation +OAI.Analysis.TracialCohomology.FreshBounds +OAI.Analysis.TracialCohomology.GoodExtensions +OAI.Analysis.TracialCohomology.HilbertFactorization +OAI.Analysis.TracialCohomology.HilbertNormalParts +OAI.Analysis.TracialCohomology.Homogeneous +OAI.Analysis.TracialCohomology.InteriorHomotopy +OAI.Analysis.TracialCohomology.LocalQuantization +OAI.Analysis.TracialCohomology.MarkedWords +OAI.Analysis.TracialCohomology.Matrices +OAI.Analysis.TracialCohomology.MatrixExtensions +OAI.Analysis.TracialCohomology.MatrixNorms +OAI.Analysis.TracialCohomology.MatrixRepresentations +OAI.Analysis.TracialCohomology.MixedWords +OAI.Analysis.TracialCohomology.NormalPreservation +OAI.Analysis.TracialCohomology.NormalReduction +OAI.Analysis.TracialCohomology.PartialRepresentations +OAI.Analysis.TracialCohomology.Partitions +OAI.Analysis.TracialCohomology.PatchBounds +OAI.Analysis.TracialCohomology.PatchConstruction +OAI.Analysis.TracialCohomology.PatchTraces +OAI.Analysis.TracialCohomology.ProjectionEstimates +OAI.Analysis.TracialCohomology.RandomSigns +OAI.Analysis.TracialCohomology.RepresentationLimits +OAI.Analysis.TracialCohomology.ResidualFilling +OAI.Analysis.TracialCohomology.SlotHomotopy +OAI.Analysis.TracialCohomology.SmallExpectations +OAI.Analysis.TracialCohomology.TracialPrimitives +OAI.Analysis.TracialCohomology.TypeII +OAI.Analysis.TracialCohomology.Vanishing +OAI.Analysis.TracialCohomology.WordQuantization +OAI.Analysis.WeakInfiniteness.MatrixRepresentation diff --git a/tasks/kadison-ringrose/solution/reference.py b/tasks/kadison-ringrose/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kadison-ringrose/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kadison-ringrose/solution/solve.sh b/tasks/kadison-ringrose/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..df5b2fa5a359e01e57b7aeaf3805f425f84aaa10 --- /dev/null +++ b/tasks/kadison-ringrose/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KadisonRingrose, i.e. module OAI.Analysis.BoundedHochschild.MainResult and the +# 372 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BoundedHochschild.MainResult /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KadisonRingrose" diff --git a/tasks/kadison-ringrose/task.toml b/tasks/kadison-ringrose/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..23bc1f6ea2b7095ed60e787d764df453264309ee --- /dev/null +++ b/tasks/kadison-ringrose/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kadison-ringrose" +version = "1.0.0" +description = "Prove KadisonRingrose (openai/math family 295: The Kadison–Ringrose cohomology conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KadisonRingrose.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KadisonRingrose" +family = "295" +family_title = "The Kadison–Ringrose cohomology conjecture" +subject = "Operator algebras" +theorems = ["OAI.BoundedHochschild.KadisonRingrose.main_result"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BoundedHochschild.MainResult" +reference_modules = 372 +reference_lean_bytes = 2793925 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1352 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14214 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kadison-ringrose/tests/Challenge.lean b/tasks/kadison-ringrose/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d962126578d6a04bd6220fa45a4c1a6aac35e3f2 --- /dev/null +++ b/tasks/kadison-ringrose/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +/-! Every ordinary bounded higher Hochschild cocycle of a complex von Neumann +algebra is the coboundary of a bounded cochain with values in the same algebra. -/ + +noncomputable section + +namespace BoundedHochschild + +abbrev Cochain (M : Type*) [NormedAddCommGroup M] [NormedSpace ℂ M] (n : ℕ) := + ContinuousMultilinearMap ℂ (fun _ : Fin n => M) M + +def mergeInputs {M : Type*} [Mul M] {n : ℕ} + (v : Fin (n + 1) → M) (j : Fin n) : Fin n → M := + fun i => if i < j then v i.castSucc + else if i = j then v i.castSucc * v i.succ else v i.succ + +noncomputable def differentialValue {M : Type*} [NormedRing M] [NormedAlgebra ℂ M] + {n : ℕ} (f : Cochain M n) (v : Fin (n + 1) → M) : M := + v 0 * f (fun i => v i.succ) + + ∑ j : Fin n, ((-1 : ℂ) ^ (j.val + 1)) • f (mergeInputs v j) + + ((-1 : ℂ) ^ (n + 1)) • (f (fun i => v i.castSucc) * v (Fin.last n)) + +namespace KadisonRingrose + +universe u + +theorem main_result + {M : Type u} [CStarAlgebra M] [PartialOrder M] [StarOrderedRing M] [WStarAlgebra M] + (n : ℕ) (f : Cochain M (n + 2)) + (hf : ∀ x : Fin (n + 3) → M, differentialValue f x = 0) : + ∃ g : Cochain M (n + 1), ∀ x : Fin (n + 2) → M, + differentialValue g x = f x := by + sorry + +end KadisonRingrose +end BoundedHochschild + +end + +end OAI diff --git a/tasks/kadison-ringrose/tests/grade.py b/tasks/kadison-ringrose/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kadison-ringrose/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kadison-ringrose/tests/task.json b/tasks/kadison-ringrose/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ff15b2a9cffe8d72f8fec1f2814ed675d6a6cbd0 --- /dev/null +++ b/tasks/kadison-ringrose/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KadisonRingrose", + "comparator": { + "theorem_names": [ + "OAI.BoundedHochschild.KadisonRingrose.main_result" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13314 +} \ No newline at end of file diff --git a/tasks/kadison-ringrose/tests/test.sh b/tasks/kadison-ringrose/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kadison-ringrose/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kadison-similarity/environment/Dockerfile b/tasks/kadison-similarity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kadison-similarity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kadison-similarity/environment/fetch_mathlib.sh b/tasks/kadison-similarity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kadison-similarity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kadison-similarity/environment/lake-manifest.json b/tasks/kadison-similarity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kadison-similarity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kadison-similarity/environment/lakefile.lean b/tasks/kadison-similarity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kadison-similarity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kadison-similarity/environment/lean_setup.sh b/tasks/kadison-similarity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kadison-similarity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kadison-similarity/environment/pack_submission.py b/tasks/kadison-similarity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kadison-similarity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kadison-similarity/instruction.md b/tasks/kadison-similarity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..77d7cd5dbfe234c9bf36aac0146ea5d20d9cfeac --- /dev/null +++ b/tasks/kadison-similarity/instruction.md @@ -0,0 +1,173 @@ +# openai/math challenge `KadisonSimilarity` (family 288) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 288 of the release, *Kadison's similarity conjecture* +(Operator algebras). The family as a whole: Proves Kadison's similarity conjecture: every bounded complex-linear unital algebra homomorphism from a unital complex $C^*$-algebra to operators on a Hilbert space becomes a $*$-homomorphism after conjugation by a bounded invertible operator. + +The challenge is `KadisonSimilarity`, also at `/opt/openai-math/challenges/KadisonSimilarity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace KadisonSimilarity + +universe u v + +section Homomorphisms + +variable (A H : Type*) [CStarAlgebra A] + [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +abbrev BoundedUnitalHom := + {π : A →ₐ[ℂ] (H →L[ℂ] H) // Continuous π} + +def SimilarToStar (π : BoundedUnitalHom A H) : Prop := + ∃ S : (H →L[ℂ] H)ˣ, ∀ a : A, + (S : H →L[ℂ] H) * π.1 (star a) * (↑S⁻¹ : H →L[ℂ] H) = + star ((S : H →L[ℂ] H) * π.1 a * (↑S⁻¹ : H →L[ℂ] H)) + +end Homomorphisms + +section Commutators + +variable {R : Type*} [NormedRing R] + +def commutator (S T : R) : R := S * T - T * S + +end Commutators + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +section + +attribute [-instance] NonUnitalCStarAlgebra.toNormedSpace + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev HilbertCopies (H : Type u) (n : ℕ) := PiLp 2 (fun _ : Fin n => H) + +def matrixOperator {n : ℕ} (X : Matrix (Fin n) (Fin n) (H →L[ℂ] H)) : + HilbertCopies H n →L[ℂ] HilbertCopies H n := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin n => H)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi fun i => + ∑ j : Fin n, (X i j).comp (PiLp.proj 2 (fun _ : Fin n => H) j)) + +def amplify (Y : H →L[ℂ] H) (n : ℕ) : + HilbertCopies H n →L[ℂ] HilbertCopies H n := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin n => H)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi fun i => Y.comp (PiLp.proj 2 (fun _ : Fin n => H) i)) + +def innerDerivation (Y : H →L[ℂ] H) : + (H →L[ℂ] H) →L[ℂ] (H →L[ℂ] H) := + ContinuousLinearMap.mul ℂ (H →L[ℂ] H) Y - + (ContinuousLinearMap.mul ℂ (H →L[ℂ] H)).flip Y + +variable [CompleteSpace H] + +def scalarCommutatorNorm (P : VonNeumannAlgebra H) (Y : H →L[ℂ] H) : ℝ := by + let : SeminormedAddCommGroup P.toStarSubalgebra.toSubalgebra.toSubmodule := inferInstance + let : NormedSpace ℂ P.toStarSubalgebra.toSubalgebra.toSubmodule := inferInstance + exact ‖(innerDerivation Y).comp P.toStarSubalgebra.toSubalgebra.toSubmodule.subtypeL‖ + +def CommutatorEstimate (P : VonNeumannAlgebra H) (C : ℝ) : Prop := + ∀ (Y : H →L[ℂ] H) (n : ℕ) (X : Matrix (Fin n) (Fin n) (H →L[ℂ] H)), + (∀ i j, X i j ∈ P) → + ‖commutator (amplify Y n) (matrixOperator X)‖ ≤ + C * scalarCommutatorNorm P Y * ‖matrixOperator X‖ + +def UniformCommutatorEstimate (C : ℝ) : Prop := + ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (P : VonNeumannAlgebra K), CommutatorEstimate P C + +def UniversalCommutatorTheorem : Prop := ∃ C : ℝ, 0 ≤ C ∧ UniformCommutatorEstimate.{u} C + +def SimilarityTheorem : Prop := + ∀ (A : Type u) [CStarAlgebra A] (K : Type v) [NormedAddCommGroup K] + [InnerProductSpace ℂ K] [CompleteSpace K] (π : BoundedUnitalHom A K), + SimilarToStar A K π + +abbrev CommutantProjection (M : VonNeumannAlgebra H) := + {e : H →L[ℂ] H // e ∈ M.commutant ∧ star e = e ∧ e * e = e} + +def offDiagonalSeminorm (M : VonNeumannAlgebra H) (T : H →L[ℂ] H) : ℝ := + sSup (Set.range fun e : CommutantProjection M => + ‖(1 - (e : H →L[ℂ] H)) * T * (e : H →L[ℂ] H)‖) + +def UniversalHyperreflexivity (C : ℝ) : Prop := + ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (M : VonNeumannAlgebra K) (T : K →L[ℂ] K), + Metric.infDist T (M : Set (K →L[ℂ] K)) ≤ 2 * C * offDiagonalSeminorm M T + +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def rowConstant : ℝ := 4 * Real.sqrt 2 +def cyclicConstant : ℝ := (1 + 4 * rowConstant) ^ 2 +def cornerConstant : ℝ := 6 * Real.pi ^ 2 * (1 + 4 * cyclicConstant) +def factorConstant : ℝ := max (max (3 * cornerConstant + 2) (1 + 2 * rowConstant)) 2 +def universalConstant : ℝ := 3 * factorConstant + 2 + +/-- One absolute constant controls every finite matrix commutator. -/ +theorem universalCommutatorTheorem : UniversalCommutatorTheorem.{u} := by + sorry + +/-- Every von Neumann algebra has hyperreflexivity constant at most `2 * universalConstant`. -/ +theorem universalHyperreflexivity : UniversalHyperreflexivity.{u} universalConstant := by + sorry + +/-- Every bounded unital representation is similar to a star representation. -/ +theorem similarityTheorem : SimilarityTheorem.{u,v} := by + sorry + +end KadisonSimilarity + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KadisonSimilarity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.KadisonSimilarity.universalCommutatorTheorem`, `OAI.KadisonSimilarity.universalHyperreflexivity`, `OAI.KadisonSimilarity.similarityTheorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kadison-similarity/solution/closure.txt b/tasks/kadison-similarity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..50a0fcef4383cd5ec4a1a052a9d36e9d3f0c0c68 --- /dev/null +++ b/tasks/kadison-similarity/solution/closure.txt @@ -0,0 +1,816 @@ +OAI.Analysis.BoundedHochschild.AbelianCentralSupport +OAI.Analysis.BoundedHochschild.AbelianComparison +OAI.Analysis.BoundedHochschild.AbelianPartitions +OAI.Analysis.BoundedHochschild.AbelianPrimitives +OAI.Analysis.BoundedHochschild.AbelianProjectionForms +OAI.Analysis.BoundedHochschild.AbelianSupportEquivalence +OAI.Analysis.BoundedHochschild.AdditivePositiveSupport +OAI.Analysis.BoundedHochschild.AlternatingMoments +OAI.Analysis.BoundedHochschild.AsymptoticRigidity +OAI.Analysis.BoundedHochschild.BarDifferential +OAI.Analysis.BoundedHochschild.BlockSpans +OAI.Analysis.BoundedHochschild.CStarQuotients +OAI.Analysis.BoundedHochschild.Catalan +OAI.Analysis.BoundedHochschild.CatalanWords +OAI.Analysis.BoundedHochschild.CenterAveragingReduction +OAI.Analysis.BoundedHochschild.CentralBlockSpans +OAI.Analysis.BoundedHochschild.CentralBlockUnitaries +OAI.Analysis.BoundedHochschild.CentralColumnCuts +OAI.Analysis.BoundedHochschild.CentralComparison +OAI.Analysis.BoundedHochschild.CentralHomotopy +OAI.Analysis.BoundedHochschild.CentralPrimitives +OAI.Analysis.BoundedHochschild.CentralProjectionPartitions +OAI.Analysis.BoundedHochschild.CentralProjectionSuprema +OAI.Analysis.BoundedHochschild.CentralSeparation +OAI.Analysis.BoundedHochschild.CentralSupportCuts +OAI.Analysis.BoundedHochschild.CentralTypeIIInheritance +OAI.Analysis.BoundedHochschild.CochainAverages +OAI.Analysis.BoundedHochschild.CochainLimitDifferential +OAI.Analysis.BoundedHochschild.CochainLimits +OAI.Analysis.BoundedHochschild.Cochains +OAI.Analysis.BoundedHochschild.CocycleNormalParts +OAI.Analysis.BoundedHochschild.CollisionBounds +OAI.Analysis.BoundedHochschild.ColumnRowEstimates +OAI.Analysis.BoundedHochschild.CommutantQuantization +OAI.Analysis.BoundedHochschild.CompactConvexCenter +OAI.Analysis.BoundedHochschild.CompactInvariantSets +OAI.Analysis.BoundedHochschild.CompleteAdditivity +OAI.Analysis.BoundedHochschild.CompletelyBoundedFactorization +OAI.Analysis.BoundedHochschild.CompletelyBoundedRows +OAI.Analysis.BoundedHochschild.CompletelyPositiveCompression +OAI.Analysis.BoundedHochschild.CompletelyPositiveLimits +OAI.Analysis.BoundedHochschild.CompletelyPositiveNorm +OAI.Analysis.BoundedHochschild.Conditional +OAI.Analysis.BoundedHochschild.CornerEquivalences +OAI.Analysis.BoundedHochschild.Corners +OAI.Analysis.BoundedHochschild.CountableColumnRegrouping +OAI.Analysis.BoundedHochschild.DiffuseProjections +OAI.Analysis.BoundedHochschild.Dixmier +OAI.Analysis.BoundedHochschild.DoubleCoordinates +OAI.Analysis.BoundedHochschild.ExponentialLifts +OAI.Analysis.BoundedHochschild.FactorFinitePaths +OAI.Analysis.BoundedHochschild.FiniteCentralDecomposition +OAI.Analysis.BoundedHochschild.FiniteCoefficientExtension +OAI.Analysis.BoundedHochschild.FiniteCompressionExtension +OAI.Analysis.BoundedHochschild.FiniteConstraints +OAI.Analysis.BoundedHochschild.FiniteCountableComparison +OAI.Analysis.BoundedHochschild.FiniteIncreasingComparison +OAI.Analysis.BoundedHochschild.FiniteMoments +OAI.Analysis.BoundedHochschild.FiniteNormalOrbit +OAI.Analysis.BoundedHochschild.FiniteNormalState +OAI.Analysis.BoundedHochschild.FiniteNormalTrace +OAI.Analysis.BoundedHochschild.FinitePaths +OAI.Analysis.BoundedHochschild.FinitePhases +OAI.Analysis.BoundedHochschild.FinitePositiveExtension +OAI.Analysis.BoundedHochschild.FiniteProjectionAbsoluteContinuity +OAI.Analysis.BoundedHochschild.FiniteProjectionEquivalence +OAI.Analysis.BoundedHochschild.FiniteProjectionExtension +OAI.Analysis.BoundedHochschild.FiniteRightAveraging +OAI.Analysis.BoundedHochschild.FiniteTraceCover +OAI.Analysis.BoundedHochschild.FiniteTracialDecomposition +OAI.Analysis.BoundedHochschild.FiniteTypeIPieces +OAI.Analysis.BoundedHochschild.FiniteTypeIVanishing +OAI.Analysis.BoundedHochschild.FiniteUnitaryPrimitives +OAI.Analysis.BoundedHochschild.FirstLetter +OAI.Analysis.BoundedHochschild.FlipMatrixNesting +OAI.Analysis.BoundedHochschild.Frames +OAI.Analysis.BoundedHochschild.FreeCoefficients +OAI.Analysis.BoundedHochschild.FreeHaarFamilies +OAI.Analysis.BoundedHochschild.FreeWords +OAI.Analysis.BoundedHochschild.Haagerup +OAI.Analysis.BoundedHochschild.HarmonicSums +OAI.Analysis.BoundedHochschild.HomogeneousCornerTransport +OAI.Analysis.BoundedHochschild.HomogeneousTypeI +OAI.Analysis.BoundedHochschild.HomogeneousTypeIPrimitives +OAI.Analysis.BoundedHochschild.IncrementalPatching +OAI.Analysis.BoundedHochschild.InfiniteCentralReduction +OAI.Analysis.BoundedHochschild.InfiniteMatrixColumns +OAI.Analysis.BoundedHochschild.InfinitePairChains +OAI.Analysis.BoundedHochschild.IsometricFixedPoint +OAI.Analysis.BoundedHochschild.IsometryAbsorption +OAI.Analysis.BoundedHochschild.IsometryDefectColumns +OAI.Analysis.BoundedHochschild.Liouville +OAI.Analysis.BoundedHochschild.Martingales +OAI.Analysis.BoundedHochschild.MatrixAmplification +OAI.Analysis.BoundedHochschild.MatrixBlockGroups +OAI.Analysis.BoundedHochschild.MatrixCommutants +OAI.Analysis.BoundedHochschild.MatrixCornerCommutant +OAI.Analysis.BoundedHochschild.MatrixDilation +OAI.Analysis.BoundedHochschild.MatrixDisplacement +OAI.Analysis.BoundedHochschild.MatrixFunctionalDilation +OAI.Analysis.BoundedHochschild.MatrixScalarColumns +OAI.Analysis.BoundedHochschild.MatrixSystems +OAI.Analysis.BoundedHochschild.MaximalInfiniteProjection +OAI.Analysis.BoundedHochschild.MinimalIsometricOrbit +OAI.Analysis.BoundedHochschild.MixedWords +OAI.Analysis.BoundedHochschild.MomentNorms +OAI.Analysis.BoundedHochschild.MonotoneLimits +OAI.Analysis.BoundedHochschild.NestedMatrixAmplification +OAI.Analysis.BoundedHochschild.NormalModulus +OAI.Analysis.BoundedHochschild.NormalMultiplication +OAI.Analysis.BoundedHochschild.NormalOperators +OAI.Analysis.BoundedHochschild.NormalOrbitHull +OAI.Analysis.BoundedHochschild.NormalOrbitInvariance +OAI.Analysis.BoundedHochschild.NormalOrderIntervals +OAI.Analysis.BoundedHochschild.NormalTraceFaithfulness +OAI.Analysis.BoundedHochschild.NormalVectors +OAI.Analysis.BoundedHochschild.OperatorPrimitives +OAI.Analysis.BoundedHochschild.OperatorSystemCompression +OAI.Analysis.BoundedHochschild.OperatorSystemExtension +OAI.Analysis.BoundedHochschild.OperatorSystemFunctionals +OAI.Analysis.BoundedHochschild.OperatorSystemMatrices +OAI.Analysis.BoundedHochschild.OperatorTransport +OAI.Analysis.BoundedHochschild.OrthogonalPartialIsoSums +OAI.Analysis.BoundedHochschild.OrthogonalProjectionSums +OAI.Analysis.BoundedHochschild.OrthogonalProjectionTails +OAI.Analysis.BoundedHochschild.PartialIsoCornerEquivalence +OAI.Analysis.BoundedHochschild.PartialIsoProducts +OAI.Analysis.BoundedHochschild.PartialIsometries +OAI.Analysis.BoundedHochschild.PartialIsometryChains +OAI.Analysis.BoundedHochschild.PartialUnitaries +OAI.Analysis.BoundedHochschild.PathStages +OAI.Analysis.BoundedHochschild.PathWords +OAI.Analysis.BoundedHochschild.PaulsenEntries +OAI.Analysis.BoundedHochschild.PaulsenExtension +OAI.Analysis.BoundedHochschild.PaulsenMatrixBlocks +OAI.Analysis.BoundedHochschild.PaulsenPositivity +OAI.Analysis.BoundedHochschild.PaulsenSystem +OAI.Analysis.BoundedHochschild.PolarApproximation +OAI.Analysis.BoundedHochschild.PositiveBlockRegularization +OAI.Analysis.BoundedHochschild.PositiveBlockTransfer +OAI.Analysis.BoundedHochschild.PositiveBlocks +OAI.Analysis.BoundedHochschild.PositiveCompleteAdditivity +OAI.Analysis.BoundedHochschild.PositiveCompression +OAI.Analysis.BoundedHochschild.PositiveDecomposition +OAI.Analysis.BoundedHochschild.PositiveKernelActions +OAI.Analysis.BoundedHochschild.PositiveKernelMatrices +OAI.Analysis.BoundedHochschild.PositiveKernelSpace +OAI.Analysis.BoundedHochschild.PositiveNormalParts +OAI.Analysis.BoundedHochschild.PositiveOrbitCompactness +OAI.Analysis.BoundedHochschild.PositiveUnitBlocks +OAI.Analysis.BoundedHochschild.PowerRigidity +OAI.Analysis.BoundedHochschild.PrimitiveAverages +OAI.Analysis.BoundedHochschild.ProductTaylor +OAI.Analysis.BoundedHochschild.ProjectionChainSuprema +OAI.Analysis.BoundedHochschild.ProjectionJoinComparison +OAI.Analysis.BoundedHochschild.ProjectionPositivity +OAI.Analysis.BoundedHochschild.ProjectionSequenceLimits +OAI.Analysis.BoundedHochschild.ProperlyInfiniteColumns +OAI.Analysis.BoundedHochschild.ProperlyInfiniteCorners +OAI.Analysis.BoundedHochschild.ProperlyInfiniteIsometries +OAI.Analysis.BoundedHochschild.ProperlyInfiniteMatrixSystems +OAI.Analysis.BoundedHochschild.PublishedInputs +OAI.Analysis.BoundedHochschild.RankOneQuantization +OAI.Analysis.BoundedHochschild.RareScales +OAI.Analysis.BoundedHochschild.RelativeQuantization +OAI.Analysis.BoundedHochschild.ScalarMatrixActions +OAI.Analysis.BoundedHochschild.ScalarPositiveBlocks +OAI.Analysis.BoundedHochschild.SeparablePrimitives +OAI.Analysis.BoundedHochschild.SignedMatrixUnitaries +OAI.Analysis.BoundedHochschild.SpectralProjections +OAI.Analysis.BoundedHochschild.StarPreduals +OAI.Analysis.BoundedHochschild.StinespringBounds +OAI.Analysis.BoundedHochschild.StinespringEmbedding +OAI.Analysis.BoundedHochschild.StinespringKernel +OAI.Analysis.BoundedHochschild.StinespringLeftAction +OAI.Analysis.BoundedHochschild.StinespringRepresentation +OAI.Analysis.BoundedHochschild.StinespringStar +OAI.Analysis.BoundedHochschild.TraceExpectations +OAI.Analysis.BoundedHochschild.TraceFreeComparison +OAI.Analysis.BoundedHochschild.TraceFreeHalving +OAI.Analysis.BoundedHochschild.TraceFreeProjectionJoins +OAI.Analysis.BoundedHochschild.TraceFreeSeparation +OAI.Analysis.BoundedHochschild.TracialCoverReduction +OAI.Analysis.BoundedHochschild.TracialDecomposition +OAI.Analysis.BoundedHochschild.TracialModulus +OAI.Analysis.BoundedHochschild.TracialTypeIHomogeneousPiece +OAI.Analysis.BoundedHochschild.TypeICentralDecomposition +OAI.Analysis.BoundedHochschild.TypeICentralPieces +OAI.Analysis.BoundedHochschild.TypeICentralSupport +OAI.Analysis.BoundedHochschild.TypeIColumnArithmetic +OAI.Analysis.BoundedHochschild.TypeIColumnExtension +OAI.Analysis.BoundedHochschild.TypeIICharacterization +OAI.Analysis.BoundedHochschild.TypeIIDefinitions +OAI.Analysis.BoundedHochschild.TypeIIStructure +OAI.Analysis.BoundedHochschild.TypeIMatrixColumns +OAI.Analysis.BoundedHochschild.UltrapowerMoments +OAI.Analysis.BoundedHochschild.Ultrapowers +OAI.Analysis.BoundedHochschild.UniformProjectionSums +OAI.Analysis.BoundedHochschild.UnitalPositiveExtension +OAI.Analysis.BoundedHochschild.UnitaryLifts +OAI.Analysis.BoundedHochschild.UnitaryPredualAction +OAI.Analysis.BoundedHochschild.WalkEndpoints +OAI.Analysis.BoundedHochschild.WalkLabels +OAI.Analysis.BoundedHochschild.WalkSelection +OAI.Analysis.BoundedHochschild.WeakAlgebras +OAI.Analysis.BoundedHochschild.WeakCompactFragment +OAI.Analysis.BoundedHochschild.WeakIsometricFixedPoint +OAI.Analysis.BoundedHochschild.WeakPredual +OAI.Analysis.BoundedHochschild.WeakSubspaces +OAI.Analysis.FactorGeneration.Bicommutant +OAI.Analysis.FactorGeneration.CornerTrace +OAI.Analysis.FactorGeneration.EnergyDescent +OAI.Analysis.FactorGeneration.Expectations +OAI.Analysis.FactorGeneration.FunctionalLimits +OAI.Analysis.FactorGeneration.GroupTrace +OAI.Analysis.FactorGeneration.HilbertLimits +OAI.Analysis.FactorGeneration.MatrixAlgebras +OAI.Analysis.FactorGeneration.MatrixRefinement +OAI.Analysis.FactorGeneration.MatrixSequence +OAI.Analysis.FactorGeneration.MatrixUnits +OAI.Analysis.FactorGeneration.OperatorLimits +OAI.Analysis.FactorGeneration.OrbitMinima +OAI.Analysis.FactorGeneration.PartialIsometries +OAI.Analysis.FactorGeneration.PartialUnitaries +OAI.Analysis.FactorGeneration.Pinching +OAI.Analysis.FactorGeneration.ProjectionComparison +OAI.Analysis.FactorGeneration.ProjectionLimits +OAI.Analysis.FactorGeneration.SpectralApproximation +OAI.Analysis.FactorGeneration.SpectralPinching +OAI.Analysis.FactorGeneration.SpectralTruncation +OAI.Analysis.FactorGeneration.Subfactors +OAI.Analysis.FactorGeneration.Supports +OAI.Analysis.FactorGeneration.Target +OAI.Analysis.FactorGeneration.TraceTopology +OAI.Analysis.FactorGeneration.TracialInclusion +OAI.Analysis.FactorGeneration.Ultrapower +OAI.Analysis.FactorGeneration.UniformPartitions +OAI.Analysis.FactorGeneration.UnitaryMetric +OAI.Analysis.FreeGroupFactor.GlobalODE +OAI.Analysis.FreeGroupFactor.Model +OAI.Analysis.FreeGroupFactor.NCPolynomial +OAI.Analysis.FreeGroupFactor.Operators +OAI.Analysis.FreeGroupFactor.PolynomialFlow +OAI.Analysis.FreeGroupFactor.Taylor +OAI.Analysis.FreeGroupFactor.TraceCocycle +OAI.Analysis.FreeGroupFactor.UnitaryEvaluation +OAI.Analysis.KadisonSimilarity.ConditionalMain +OAI.Analysis.KadisonSimilarity.Constants +OAI.Analysis.KadisonSimilarity.Derivation.BoundedHomRestriction +OAI.Analysis.KadisonSimilarity.Derivation.BoundedHomRow +OAI.Analysis.KadisonSimilarity.Derivation.CStarRowSquare +OAI.Analysis.KadisonSimilarity.Derivation.ColumnCompression +OAI.Analysis.KadisonSimilarity.Derivation.CommonCyclicEmbedding +OAI.Analysis.KadisonSimilarity.Derivation.CommonCyclicIntertwining +OAI.Analysis.KadisonSimilarity.Derivation.CountableCyclicDecomposition +OAI.Analysis.KadisonSimilarity.Derivation.CyclicApproximation +OAI.Analysis.KadisonSimilarity.Derivation.CyclicColumnPolar +OAI.Analysis.KadisonSimilarity.Derivation.CyclicColumnTests +OAI.Analysis.KadisonSimilarity.Derivation.CyclicCommutativeModel +OAI.Analysis.KadisonSimilarity.Derivation.CyclicDecomposition +OAI.Analysis.KadisonSimilarity.Derivation.CyclicDerivations +OAI.Analysis.KadisonSimilarity.Derivation.CyclicFactorization +OAI.Analysis.KadisonSimilarity.Derivation.CyclicGraphEmbedding +OAI.Analysis.KadisonSimilarity.Derivation.CyclicGraphSequences +OAI.Analysis.KadisonSimilarity.Derivation.CyclicSpectralIsometry +OAI.Analysis.KadisonSimilarity.Derivation.CyclicSpectralSum +OAI.Analysis.KadisonSimilarity.Derivation.CyclicStandardEmbedding +OAI.Analysis.KadisonSimilarity.Derivation.CyclicSummandColumns +OAI.Analysis.KadisonSimilarity.Derivation.DerivationDefectSpace +OAI.Analysis.KadisonSimilarity.Derivation.DerivationEndgame +OAI.Analysis.KadisonSimilarity.Derivation.Derivations +OAI.Analysis.KadisonSimilarity.Derivation.DiagonalMatrixNorm +OAI.Analysis.KadisonSimilarity.Derivation.DicksonAdjoint +OAI.Analysis.KadisonSimilarity.Derivation.DicksonDischarge +OAI.Analysis.KadisonSimilarity.Derivation.DicksonRow +OAI.Analysis.KadisonSimilarity.Derivation.FactorizationGeometry +OAI.Analysis.KadisonSimilarity.Derivation.FactorizationSpace +OAI.Analysis.KadisonSimilarity.Derivation.FinalDerivations +OAI.Analysis.KadisonSimilarity.Derivation.FiniteDerivationColumns +OAI.Analysis.KadisonSimilarity.Derivation.GrothendieckMatrix +OAI.Analysis.KadisonSimilarity.Derivation.GrothendieckUltrapower +OAI.Analysis.KadisonSimilarity.Derivation.HomPolarBound +OAI.Analysis.KadisonSimilarity.Derivation.NormAttainingGrothendieck +OAI.Analysis.KadisonSimilarity.Derivation.NormalCyclicGraph +OAI.Analysis.KadisonSimilarity.Derivation.OrbitSquareNormalization +OAI.Analysis.KadisonSimilarity.Derivation.QuadraticSandwich +OAI.Analysis.KadisonSimilarity.Derivation.RectangularDerivations +OAI.Analysis.KadisonSimilarity.Derivation.SharpDerivationImplementation +OAI.Analysis.KadisonSimilarity.Derivation.TracialCornerCyclicity +OAI.Analysis.KadisonSimilarity.FreeProduct.ActualArcCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.AngularCutLimit +OAI.Analysis.KadisonSimilarity.FreeProduct.AngularIntegralBounds +OAI.Analysis.KadisonSimilarity.FreeProduct.ArcCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.ArcFourier +OAI.Analysis.KadisonSimilarity.FreeProduct.BaseCommutatorCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.BaseSymmetry +OAI.Analysis.KadisonSimilarity.FreeProduct.CanonicalFreeCornerCore +OAI.Analysis.KadisonSimilarity.FreeProduct.CanonicalFreeCornerEstimate +OAI.Analysis.KadisonSimilarity.FreeProduct.CanonicalFreeFactorComparison +OAI.Analysis.KadisonSimilarity.FreeProduct.CommonFieldCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.CompactHaarIntegrability +OAI.Analysis.KadisonSimilarity.FreeProduct.CompressionProjectionTransport +OAI.Analysis.KadisonSimilarity.FreeProduct.CompressionSetup +OAI.Analysis.KadisonSimilarity.FreeProduct.ConcreteDihedralSpectralArc +OAI.Analysis.KadisonSimilarity.FreeProduct.ConcreteHaarDischarge +OAI.Analysis.KadisonSimilarity.FreeProduct.ConcreteRepeatedPropagation +OAI.Analysis.KadisonSimilarity.FreeProduct.ConstantConjugateFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralArcProjection +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralColumnIdentification +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralContinuousMoments +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralCornerDensity +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralCornerWords +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralCutMoments +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralFourier +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralHaarFunctionalCalculus +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralPolynomialMoments +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralPositiveDensity +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralWordAlgebra +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralWordColumn +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralWordIsometries +OAI.Analysis.KadisonSimilarity.FreeProduct.DihedralWordOrthogonality +OAI.Analysis.KadisonSimilarity.FreeProduct.DyadicHaarUnitary +OAI.Analysis.KadisonSimilarity.FreeProduct.EmbeddedWordActions +OAI.Analysis.KadisonSimilarity.FreeProduct.EmbeddedWordClassification +OAI.Analysis.KadisonSimilarity.FreeProduct.EmbeddedWordStructure +OAI.Analysis.KadisonSimilarity.FreeProduct.EvenAlternatingWords +OAI.Analysis.KadisonSimilarity.FreeProduct.ExpectationWordClosure +OAI.Analysis.KadisonSimilarity.FreeProduct.FiniteFactorFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCentralWords +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCompressionDischarge +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCompressionGeometry +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeConjugateWords +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCornerApplication +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCornerEndgame +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCreationDischarge +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeCreationOperators +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeDihedral +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeExpectation +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeFactorCenter +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeHeadCoordinates +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeLeadingWords +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeMatrixBaseAction +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeMatrixConjugation +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeMatrixConjugationUnitary +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeMatrixExtension +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeMatrixFactorAction +OAI.Analysis.KadisonSimilarity.FreeProduct.FreePairWords +OAI.Analysis.KadisonSimilarity.FreeProduct.FreePrefixIsometry +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeProductAutomorphisms +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeProductMatrixContinuity +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeProductMatrixExtension +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeWordExpectation +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeWordHilbert +OAI.Analysis.KadisonSimilarity.FreeProduct.FreeWordInnerProducts +OAI.Analysis.KadisonSimilarity.FreeProduct.GeneratedCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.GeneratedDihedralAlgebras +OAI.Analysis.KadisonSimilarity.FreeProduct.GeneratedWordDensity +OAI.Analysis.KadisonSimilarity.FreeProduct.HaarCornerLetters +OAI.Analysis.KadisonSimilarity.FreeProduct.HaarSymmetrization +OAI.Analysis.KadisonSimilarity.FreeProduct.HankelBounds +OAI.Analysis.KadisonSimilarity.FreeProduct.HankelCommutator +OAI.Analysis.KadisonSimilarity.FreeProduct.HankelOperator +OAI.Analysis.KadisonSimilarity.FreeProduct.LeadingWordGeometry +OAI.Analysis.KadisonSimilarity.FreeProduct.LocalFreeCornerInputs +OAI.Analysis.KadisonSimilarity.FreeProduct.MatrixFreeCornerApplication +OAI.Analysis.KadisonSimilarity.FreeProduct.MatrixSourceFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.NormalFreeDihedral +OAI.Analysis.KadisonSimilarity.FreeProduct.NormalInclusionFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.NormalSpectralArc +OAI.Analysis.KadisonSimilarity.FreeProduct.OrthogonalWordLevels +OAI.Analysis.KadisonSimilarity.FreeProduct.Propagation +OAI.Analysis.KadisonSimilarity.FreeProduct.PropagationTheorem +OAI.Analysis.KadisonSimilarity.FreeProduct.PublishedWordCreation +OAI.Analysis.KadisonSimilarity.FreeProduct.ReducedWordAutomorphisms +OAI.Analysis.KadisonSimilarity.FreeProduct.ReducedWordModel +OAI.Analysis.KadisonSimilarity.FreeProduct.ScalarFreeMonotone +OAI.Analysis.KadisonSimilarity.FreeProduct.SmallFreeCornerData +OAI.Analysis.KadisonSimilarity.FreeProduct.SmallFreeCornerTransport +OAI.Analysis.KadisonSimilarity.FreeProduct.SourceConjugateFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.SpectralArc +OAI.Analysis.KadisonSimilarity.FreeProduct.SpectralArcResolvents +OAI.Analysis.KadisonSimilarity.FreeProduct.SpectralArcTransport +OAI.Analysis.KadisonSimilarity.FreeProduct.StrongCompressionTransfer +OAI.Analysis.KadisonSimilarity.FreeProduct.SymmetryExpectation +OAI.Analysis.KadisonSimilarity.FreeProduct.SymmetryWordAlgebra +OAI.Analysis.KadisonSimilarity.FreeProduct.SymmetryWordRange +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialArcCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialAutomorphismWords +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialDihedralColumns +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialDihedralEndgame +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialEmbeddedWordStructure +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialFreeCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialFreeCornerEstimate +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialFreeCornerModel +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialFreeCornerTheorem +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialHaarPerturbation +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialHaarWordColumns +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialHomCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialInclusionFreeness +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialPropagation +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialPropagationEndgame +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialRepeatedWords +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialSpectralCompression +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialSymmetryDilation +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialSymmetryExtraction +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialWordActions +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialWordBase +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialWordDensity +OAI.Analysis.KadisonSimilarity.FreeProduct.TracialWordIsometry +OAI.Analysis.KadisonSimilarity.FreeProduct.UltrapowerFreePositionTransfer +OAI.Analysis.KadisonSimilarity.FreeProduct.WordBaseCoordinates +OAI.Analysis.KadisonSimilarity.FreeProduct.WordLevelClassification +OAI.Analysis.KadisonSimilarity.FreeProduct.WordLevelRepeatedOperators +OAI.Analysis.KadisonSimilarity.FreeProduct.WordMultiplicities +OAI.Analysis.KadisonSimilarity.FreeProduct.WordPrefixRealization +OAI.Analysis.KadisonSimilarity.FreeProduct.WordPropagationTransfer +OAI.Analysis.KadisonSimilarity.Hyperreflexivity +OAI.Analysis.KadisonSimilarity.OperatorAlgebra +OAI.Analysis.KadisonSimilarity.Representation.AEColumnOperator +OAI.Analysis.KadisonSimilarity.Representation.AERepresentationAgreement +OAI.Analysis.KadisonSimilarity.Representation.AEStarRepresentation +OAI.Analysis.KadisonSimilarity.Representation.AdjointCommutators +OAI.Analysis.KadisonSimilarity.Representation.Amplification +OAI.Analysis.KadisonSimilarity.Representation.AmplifiedNormalRange +OAI.Analysis.KadisonSimilarity.Representation.BoundedMeasurableField +OAI.Analysis.KadisonSimilarity.Representation.CStarCorner +OAI.Analysis.KadisonSimilarity.Representation.CanonicalBaseExpectation +OAI.Analysis.KadisonSimilarity.Representation.CanonicalGeneratedModel +OAI.Analysis.KadisonSimilarity.Representation.CanonicalGeneratedOperators +OAI.Analysis.KadisonSimilarity.Representation.CenteredBaseDensity +OAI.Analysis.KadisonSimilarity.Representation.CenteredProjectionNorm +OAI.Analysis.KadisonSimilarity.Representation.CentralDecomposition +OAI.Analysis.KadisonSimilarity.Representation.CentralDecompositionTests +OAI.Analysis.KadisonSimilarity.Representation.CentralFactorAssembly +OAI.Analysis.KadisonSimilarity.Representation.CentralSymmetrization +OAI.Analysis.KadisonSimilarity.Representation.ClosedFamilySpan +OAI.Analysis.KadisonSimilarity.Representation.CommonCentralData +OAI.Analysis.KadisonSimilarity.Representation.CommonCommutantFields +OAI.Analysis.KadisonSimilarity.Representation.CommonFiberFactors +OAI.Analysis.KadisonSimilarity.Representation.CommonFiberRepresentations +OAI.Analysis.KadisonSimilarity.Representation.CommonRankOneClosure +OAI.Analysis.KadisonSimilarity.Representation.CommonSpectralCommutant +OAI.Analysis.KadisonSimilarity.Representation.CommonSpectralMeasure +OAI.Analysis.KadisonSimilarity.Representation.CompressedBicommutant +OAI.Analysis.KadisonSimilarity.Representation.CompressedFieldNorm +OAI.Analysis.KadisonSimilarity.Representation.ConcreteIrreducibleSubfactor +OAI.Analysis.KadisonSimilarity.Representation.ConcretePredual +OAI.Analysis.KadisonSimilarity.Representation.ConcretePredualDuality +OAI.Analysis.KadisonSimilarity.Representation.ConcretePredualRestriction +OAI.Analysis.KadisonSimilarity.Representation.ContinuousFieldCommutation +OAI.Analysis.KadisonSimilarity.Representation.ContinuousL2Multiplication +OAI.Analysis.KadisonSimilarity.Representation.ConullFieldExtension +OAI.Analysis.KadisonSimilarity.Representation.ConullRepresentationExtension +OAI.Analysis.KadisonSimilarity.Representation.ConullStarRepresentations +OAI.Analysis.KadisonSimilarity.Representation.CountableAmplification +OAI.Analysis.KadisonSimilarity.Representation.CountableDenseStarSubring +OAI.Analysis.KadisonSimilarity.Representation.CountableFiberTests +OAI.Analysis.KadisonSimilarity.Representation.CountableLpSubsequence +OAI.Analysis.KadisonSimilarity.Representation.CountableProjectionJoin +OAI.Analysis.KadisonSimilarity.Representation.CountablyGeneratedCStarAlgebra +OAI.Analysis.KadisonSimilarity.Representation.DecomposableColumns +OAI.Analysis.KadisonSimilarity.Representation.DenseFamilyIsometry +OAI.Analysis.KadisonSimilarity.Representation.DenseLinearOperator +OAI.Analysis.KadisonSimilarity.Representation.DenseStarRepresentation +OAI.Analysis.KadisonSimilarity.Representation.DiagonalFiberRepresentations +OAI.Analysis.KadisonSimilarity.Representation.DiagonalFieldAction +OAI.Analysis.KadisonSimilarity.Representation.DiagonalFieldAdjoint +OAI.Analysis.KadisonSimilarity.Representation.DiagonalFieldAlgebra +OAI.Analysis.KadisonSimilarity.Representation.DiagonalOperatorField +OAI.Analysis.KadisonSimilarity.Representation.DominatedVectorRealization +OAI.Analysis.KadisonSimilarity.Representation.DyadicCornerHom +OAI.Analysis.KadisonSimilarity.Representation.DyadicPhases +OAI.Analysis.KadisonSimilarity.Representation.FactorAssembly +OAI.Analysis.KadisonSimilarity.Representation.FieldWeakClosure +OAI.Analysis.KadisonSimilarity.Representation.FiniteAmplificationReduction +OAI.Analysis.KadisonSimilarity.Representation.FiniteOrbitComparison +OAI.Analysis.KadisonSimilarity.Representation.FiniteOrbitSubspace +OAI.Analysis.KadisonSimilarity.Representation.FiniteStandardEstimate +OAI.Analysis.KadisonSimilarity.Representation.FiniteSymmetrization +OAI.Analysis.KadisonSimilarity.Representation.FiniteTypeIEstimate +OAI.Analysis.KadisonSimilarity.Representation.FiniteTypeIStructure +OAI.Analysis.KadisonSimilarity.Representation.GeneratedEmbeddings +OAI.Analysis.KadisonSimilarity.Representation.GeneratedNormalRange +OAI.Analysis.KadisonSimilarity.Representation.GlobalFiberRestriction +OAI.Analysis.KadisonSimilarity.Representation.HilbertSumIsometries +OAI.Analysis.KadisonSimilarity.Representation.IntertwinerExtension +OAI.Analysis.KadisonSimilarity.Representation.IntertwinerPolar +OAI.Analysis.KadisonSimilarity.Representation.IsometricFieldClosure +OAI.Analysis.KadisonSimilarity.Representation.IsometricTransfer +OAI.Analysis.KadisonSimilarity.Representation.JointFiberCommutants +OAI.Analysis.KadisonSimilarity.Representation.JointFiberFactorCriterion +OAI.Analysis.KadisonSimilarity.Representation.JointFiberRestriction +OAI.Analysis.KadisonSimilarity.Representation.JointRankOneFactors +OAI.Analysis.KadisonSimilarity.Representation.KaplanskyColumns +OAI.Analysis.KadisonSimilarity.Representation.KaplanskyDischarge +OAI.Analysis.KadisonSimilarity.Representation.KaplanskyGeneral +OAI.Analysis.KadisonSimilarity.Representation.KaplanskySelfAdjoint +OAI.Analysis.KadisonSimilarity.Representation.KaplanskyStrongSequence +OAI.Analysis.KadisonSimilarity.Representation.KaplanskyTransform +OAI.Analysis.KadisonSimilarity.Representation.L2FiniteCopies +OAI.Analysis.KadisonSimilarity.Representation.L2HilbertSum +OAI.Analysis.KadisonSimilarity.Representation.L2Localization +OAI.Analysis.KadisonSimilarity.Representation.L2ScalarIntertwining +OAI.Analysis.KadisonSimilarity.Representation.LocalizedL2Bound +OAI.Analysis.KadisonSimilarity.Representation.MonotoneProjectionLimits +OAI.Analysis.KadisonSimilarity.Representation.NonseparableReduction +OAI.Analysis.KadisonSimilarity.Representation.NonunitalRangeRepresentation +OAI.Analysis.KadisonSimilarity.Representation.NormalFactorGeneration +OAI.Analysis.KadisonSimilarity.Representation.NormalOrthogonalUnitaries +OAI.Analysis.KadisonSimilarity.Representation.NormalRepresentationReduction +OAI.Analysis.KadisonSimilarity.Representation.NormalSpectralTruncation +OAI.Analysis.KadisonSimilarity.Representation.NormalStandardEmbedding +OAI.Analysis.KadisonSimilarity.Representation.NormalSupportTransport +OAI.Analysis.KadisonSimilarity.Representation.NormalizedContractions +OAI.Analysis.KadisonSimilarity.Representation.OrthogonalColumns +OAI.Analysis.KadisonSimilarity.Representation.PolarPartialIsometry +OAI.Analysis.KadisonSimilarity.Representation.ProjectionCentralData +OAI.Analysis.KadisonSimilarity.Representation.ProjectionCommutators +OAI.Analysis.KadisonSimilarity.Representation.ProjectionComparisonTransport +OAI.Analysis.KadisonSimilarity.Representation.ProjectionFieldClosure +OAI.Analysis.KadisonSimilarity.Representation.ProjectionFieldReduction +OAI.Analysis.KadisonSimilarity.Representation.ProjectionRankOne +OAI.Analysis.KadisonSimilarity.Representation.ProperlyInfiniteEstimate +OAI.Analysis.KadisonSimilarity.Representation.ProperlyInfiniteStructure +OAI.Analysis.KadisonSimilarity.Representation.QuantitativeImplementation +OAI.Analysis.KadisonSimilarity.Representation.RadonNikodymCoordinates +OAI.Analysis.KadisonSimilarity.Representation.RankOneFactorCriterion +OAI.Analysis.KadisonSimilarity.Representation.ReducedCreationBlocks +OAI.Analysis.KadisonSimilarity.Representation.ReducingRepresentationTransfer +OAI.Analysis.KadisonSimilarity.Representation.RegularizedPolarFactor +OAI.Analysis.KadisonSimilarity.Representation.RepresentationCenterTransport +OAI.Analysis.KadisonSimilarity.Representation.RepresentedFiniteSymmetrization +OAI.Analysis.KadisonSimilarity.Representation.RestrictedNormality +OAI.Analysis.KadisonSimilarity.Representation.ScalarHilbertSeparability +OAI.Analysis.KadisonSimilarity.Representation.ScalarKaplansky +OAI.Analysis.KadisonSimilarity.Representation.ScalarLocalizationApproximation +OAI.Analysis.KadisonSimilarity.Representation.ScalarLocalizationLimit +OAI.Analysis.KadisonSimilarity.Representation.SelfAdjointStrongDensity +OAI.Analysis.KadisonSimilarity.Representation.SeparableConcretePredual +OAI.Analysis.KadisonSimilarity.Representation.SeparableContractionTests +OAI.Analysis.KadisonSimilarity.Representation.SeparableModelConstruction +OAI.Analysis.KadisonSimilarity.Representation.SeparableReducingTest +OAI.Analysis.KadisonSimilarity.Representation.SeparableRepresentationTests +OAI.Analysis.KadisonSimilarity.Representation.SimultaneousSymmetrization +OAI.Analysis.KadisonSimilarity.Representation.SpectralBaseTopology +OAI.Analysis.KadisonSimilarity.Representation.SpectralCutBounds +OAI.Analysis.KadisonSimilarity.Representation.SpectralDensityIsometry +OAI.Analysis.KadisonSimilarity.Representation.SpectralIntertwining +OAI.Analysis.KadisonSimilarity.Representation.SpectralRoundingDischarge +OAI.Analysis.KadisonSimilarity.Representation.SpectralStepDischarge +OAI.Analysis.KadisonSimilarity.Representation.SpectralSteps +OAI.Analysis.KadisonSimilarity.Representation.SpectralSupportLimit +OAI.Analysis.KadisonSimilarity.Representation.SquareArrayPadding +OAI.Analysis.KadisonSimilarity.Representation.StandardEmbeddingAssembly +OAI.Analysis.KadisonSimilarity.Representation.StrongApplyLimits +OAI.Analysis.KadisonSimilarity.Representation.SubalgebraNormality +OAI.Analysis.KadisonSimilarity.Representation.SupportedFiberAlgebra +OAI.Analysis.KadisonSimilarity.Representation.SupportedFieldRecovery +OAI.Analysis.KadisonSimilarity.Representation.SupportedRankOneMembership +OAI.Analysis.KadisonSimilarity.Representation.UnitalizedExtension +OAI.Analysis.KadisonSimilarity.Representation.UnitaryNormalRange +OAI.Analysis.KadisonSimilarity.Representation.UnitizationFiberClosure +OAI.Analysis.KadisonSimilarity.Representation.UnitizationProjection +OAI.Analysis.KadisonSimilarity.Representation.VectorL2Multiplication +OAI.Analysis.KadisonSimilarity.Representation.VectorL2Representation +OAI.Analysis.KadisonSimilarity.Representation.VectorSpectralMeasure +OAI.Analysis.KadisonSimilarity.Representation.WeakOperatorCompactness +OAI.Analysis.KadisonSimilarity.Representation.WeakOperatorIntegral +OAI.Analysis.KadisonSimilarity.Representation.WeakOperatorLimits +OAI.Analysis.KadisonSimilarity.Similarity.AmplifyExponential +OAI.Analysis.KadisonSimilarity.Similarity.ArvesonCompleteNorm +OAI.Analysis.KadisonSimilarity.Similarity.ArvesonDischarge +OAI.Analysis.KadisonSimilarity.Similarity.ArvesonLowerBound +OAI.Analysis.KadisonSimilarity.Similarity.CompleteNorm +OAI.Analysis.KadisonSimilarity.Similarity.CompletelyBounded +OAI.Analysis.KadisonSimilarity.Similarity.CompletelyBoundedImplementation +OAI.Analysis.KadisonSimilarity.Similarity.CyclicSimilarity +OAI.Analysis.KadisonSimilarity.Similarity.ExponentialSimilarity +OAI.Analysis.KadisonSimilarity.Similarity.FiniteCyclicSimilarity +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergCompleteBound +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergConjugation +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergEndgame +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergExponentialNorm +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergIntegral +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergNumerics +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergScalarDerivation +OAI.Analysis.KadisonSimilarity.Similarity.KirchbergUniformBound +OAI.Analysis.KadisonSimilarity.Similarity.PaulsenDischarge +OAI.Analysis.KadisonSimilarity.Similarity.PositiveSimilarity +OAI.Analysis.KadisonSimilarity.Similarity.SharpCompletelyBoundedDerivation +OAI.Analysis.KadisonSimilarity.Similarity.SimilarityCompleteBound +OAI.Analysis.KadisonSimilarity.Similarity.SimilarityMetric +OAI.Analysis.KadisonSimilarity.Similarity.SimilarityRetract +OAI.Analysis.KadisonSimilarity.Similarity.SimilarityUniverseTransfer +OAI.Analysis.KadisonSimilarity.Tensor.EndpointBounds +OAI.Analysis.KadisonSimilarity.Tensor.EndpointClassification +OAI.Analysis.KadisonSimilarity.Tensor.EndpointDensity +OAI.Analysis.KadisonSimilarity.Tensor.EndpointPairings +OAI.Analysis.KadisonSimilarity.Tensor.EndpointTensors +OAI.Analysis.KadisonSimilarity.Tensor.InvariantCoefficients +OAI.Analysis.KadisonSimilarity.Tensor.InvariantCycles +OAI.Analysis.KadisonSimilarity.Tensor.InvariantForms +OAI.Analysis.KadisonSimilarity.Tensor.InvariantIntertwiners +OAI.Analysis.KadisonSimilarity.Tensor.InvariantTensors +OAI.Analysis.KadisonSimilarity.Tensor.MultiplicityClassification +OAI.Analysis.KadisonSimilarity.Tensor.OrthogonalConstantPairing +OAI.Analysis.KadisonSimilarity.Tensor.PairingLabels +OAI.Analysis.KadisonSimilarity.Tensor.StableMatrixStages +OAI.Analysis.KadisonSimilarity.Tensor.SubalgebraCentralPairing +OAI.Analysis.KadisonSimilarity.Tensor.TensorClassification +OAI.Analysis.KadisonSimilarity.Tensor.TensorCoefficientMatrix +OAI.Analysis.KadisonSimilarity.Tensor.TensorCommutantExtension +OAI.Analysis.KadisonSimilarity.Tensor.TensorDensity +OAI.Analysis.KadisonSimilarity.Tensor.TensorDiagonalWeights +OAI.Analysis.KadisonSimilarity.Tensor.TensorHeadSlices +OAI.Analysis.KadisonSimilarity.Tensor.TensorMatrixAlgebra +OAI.Analysis.KadisonSimilarity.Tensor.TensorPacketDensity +OAI.Analysis.KadisonSimilarity.Tensor.TensorPairings +OAI.Analysis.KadisonSimilarity.Tensor.TensorPermutations +OAI.Analysis.KadisonSimilarity.Tensor.TensorSlices +OAI.Analysis.KadisonSimilarity.Tensor.TensorStableSpanning +OAI.Analysis.KadisonSimilarity.Tensor.TensorWords +OAI.Analysis.KadisonSimilarity.Tracial.BoundedMatrixHom +OAI.Analysis.KadisonSimilarity.Tracial.CStarMatrixPadding +OAI.Analysis.KadisonSimilarity.Tracial.CentralCStarSource +OAI.Analysis.KadisonSimilarity.Tracial.CofinalMatrixTowers +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteFiniteFactorModel +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteFullColumn +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteGNSNormality +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteHalfProjection +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteMatrixTower +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteProjectionComparison +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteRealSequence +OAI.Analysis.KadisonSimilarity.Tracial.ConcreteTracialExpectation +OAI.Analysis.KadisonSimilarity.Tracial.ConjugateMomentCriterion +OAI.Analysis.KadisonSimilarity.Tracial.ConstantMomentLimit +OAI.Analysis.KadisonSimilarity.Tracial.ConstantMomentTransport +OAI.Analysis.KadisonSimilarity.Tracial.CornerTraceScaling +OAI.Analysis.KadisonSimilarity.Tracial.DenseMomentExtension +OAI.Analysis.KadisonSimilarity.Tracial.DiffuseProjectionStructure +OAI.Analysis.KadisonSimilarity.Tracial.FiniteFactorApplication +OAI.Analysis.KadisonSimilarity.Tracial.FiniteFactorPresentation +OAI.Analysis.KadisonSimilarity.Tracial.FiniteFactorSymmetrization +OAI.Analysis.KadisonSimilarity.Tracial.FiniteFactorTrace +OAI.Analysis.KadisonSimilarity.Tracial.FullColumnTheorem +OAI.Analysis.KadisonSimilarity.Tracial.FullColumns +OAI.Analysis.KadisonSimilarity.Tracial.GNSProjectionContinuity +OAI.Analysis.KadisonSimilarity.Tracial.GNSSeparableTransport +OAI.Analysis.KadisonSimilarity.Tracial.GNSTracialGeometry +OAI.Analysis.KadisonSimilarity.Tracial.GNSVectorDensity +OAI.Analysis.KadisonSimilarity.Tracial.GeneratedFiniteFactorModel +OAI.Analysis.KadisonSimilarity.Tracial.GeneratedGNSModels +OAI.Analysis.KadisonSimilarity.Tracial.GeneratedGNSRecovery +OAI.Analysis.KadisonSimilarity.Tracial.IntegerMomentMaps +OAI.Analysis.KadisonSimilarity.Tracial.IntegerMomentScaling +OAI.Analysis.KadisonSimilarity.Tracial.IsometricMatrixExtension +OAI.Analysis.KadisonSimilarity.Tracial.JointCStarSource +OAI.Analysis.KadisonSimilarity.Tracial.MatrixArrayFlattening +OAI.Analysis.KadisonSimilarity.Tracial.MatrixConjugateAutomorphism +OAI.Analysis.KadisonSimilarity.Tracial.MatrixCornerFrames +OAI.Analysis.KadisonSimilarity.Tracial.MatrixDiagonalEmbedding +OAI.Analysis.KadisonSimilarity.Tracial.MatrixDiffuseSource +OAI.Analysis.KadisonSimilarity.Tracial.MatrixExpectationIdentification +OAI.Analysis.KadisonSimilarity.Tracial.MatrixGNSNormality +OAI.Analysis.KadisonSimilarity.Tracial.MatrixGNSRecovery +OAI.Analysis.KadisonSimilarity.Tracial.MatrixPopaPosition +OAI.Analysis.KadisonSimilarity.Tracial.MatrixRelativeCommutant +OAI.Analysis.KadisonSimilarity.Tracial.MatrixSmallCorner +OAI.Analysis.KadisonSimilarity.Tracial.MatrixStageGrowth +OAI.Analysis.KadisonSimilarity.Tracial.MatrixSubfactorTransfer +OAI.Analysis.KadisonSimilarity.Tracial.MatrixTraceUniqueness +OAI.Analysis.KadisonSimilarity.Tracial.MatrixTracialGNS +OAI.Analysis.KadisonSimilarity.Tracial.MatrixTracialInputTransport +OAI.Analysis.KadisonSimilarity.Tracial.MatrixUnitCoordinates +OAI.Analysis.KadisonSimilarity.Tracial.MatrixUnitFamilies +OAI.Analysis.KadisonSimilarity.Tracial.MatrixVonNeumannRange +OAI.Analysis.KadisonSimilarity.Tracial.NormalRealSequence +OAI.Analysis.KadisonSimilarity.Tracial.NormalSmallCorners +OAI.Analysis.KadisonSimilarity.Tracial.NormalTracialExpectations +OAI.Analysis.KadisonSimilarity.Tracial.NormalTracialGeometry +OAI.Analysis.KadisonSimilarity.Tracial.NormalTracialInclusionModel +OAI.Analysis.KadisonSimilarity.Tracial.OppositeTracialGeometry +OAI.Analysis.KadisonSimilarity.Tracial.PopaConjugatePosition +OAI.Analysis.KadisonSimilarity.Tracial.PredualGNSNormality +OAI.Analysis.KadisonSimilarity.Tracial.PredualGNSSeparable +OAI.Analysis.KadisonSimilarity.Tracial.ProjectionJoinTrace +OAI.Analysis.KadisonSimilarity.Tracial.ProjectionTraceContinuity +OAI.Analysis.KadisonSimilarity.Tracial.QuotientMomentLimit +OAI.Analysis.KadisonSimilarity.Tracial.RelativeMatrixQuantization +OAI.Analysis.KadisonSimilarity.Tracial.SmallTraceFrames +OAI.Analysis.KadisonSimilarity.Tracial.SourceAllMoments +OAI.Analysis.KadisonSimilarity.Tracial.SourceConstantMoments +OAI.Analysis.KadisonSimilarity.Tracial.SourceCornerQuantization +OAI.Analysis.KadisonSimilarity.Tracial.SourceIncrementalPatching +OAI.Analysis.KadisonSimilarity.Tracial.SourceMomentConstruction +OAI.Analysis.KadisonSimilarity.Tracial.SourceMomentSequence +OAI.Analysis.KadisonSimilarity.Tracial.SourcePartialUnitaries +OAI.Analysis.KadisonSimilarity.Tracial.SourceQuotientMoments +OAI.Analysis.KadisonSimilarity.Tracial.SourceUltrapowerInclusion +OAI.Analysis.KadisonSimilarity.Tracial.SourceUnitaryMoments +OAI.Analysis.KadisonSimilarity.Tracial.SourceWeakPowers +OAI.Analysis.KadisonSimilarity.Tracial.TraceDenseContractions +OAI.Analysis.KadisonSimilarity.Tracial.TracialAdjointBounds +OAI.Analysis.KadisonSimilarity.Tracial.TracialAutomorphisms +OAI.Analysis.KadisonSimilarity.Tracial.TracialBaseGeometry +OAI.Analysis.KadisonSimilarity.Tracial.TracialBaseSpace +OAI.Analysis.KadisonSimilarity.Tracial.TracialBoundedBalls +OAI.Analysis.KadisonSimilarity.Tracial.TracialCommutantTrace +OAI.Analysis.KadisonSimilarity.Tracial.TracialCommutationDischarge +OAI.Analysis.KadisonSimilarity.Tracial.TracialCornerEstimate +OAI.Analysis.KadisonSimilarity.Tracial.TracialCornerExpectations +OAI.Analysis.KadisonSimilarity.Tracial.TracialCornerHilbert +OAI.Analysis.KadisonSimilarity.Tracial.TracialCornerRepresentations +OAI.Analysis.KadisonSimilarity.Tracial.TracialCornerTransport +OAI.Analysis.KadisonSimilarity.Tracial.TracialCreationCoordinates +OAI.Analysis.KadisonSimilarity.Tracial.TracialEmbeddingBalls +OAI.Analysis.KadisonSimilarity.Tracial.TracialEmbeddingTransport +OAI.Analysis.KadisonSimilarity.Tracial.TracialExpectations +OAI.Analysis.KadisonSimilarity.Tracial.TracialFactorComparison +OAI.Analysis.KadisonSimilarity.Tracial.TracialGeneratedAlgebra +OAI.Analysis.KadisonSimilarity.Tracial.TracialGeneratedNormalClosure +OAI.Analysis.KadisonSimilarity.Tracial.TracialGeometrySupport +OAI.Analysis.KadisonSimilarity.Tracial.TracialHalfProjectionData +OAI.Analysis.KadisonSimilarity.Tracial.TracialHeadCoordinates +OAI.Analysis.KadisonSimilarity.Tracial.TracialIncludedCorners +OAI.Analysis.KadisonSimilarity.Tracial.TracialInclusionModel +OAI.Analysis.KadisonSimilarity.Tracial.TracialInclusionNormality +OAI.Analysis.KadisonSimilarity.Tracial.TracialInclusionQuantization +OAI.Analysis.KadisonSimilarity.Tracial.TracialInputTransport +OAI.Analysis.KadisonSimilarity.Tracial.TracialL2Closure +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixCenter +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixColumns +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixCovariance +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixDiffuse +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixRealization +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixSymmetrization +OAI.Analysis.KadisonSimilarity.Tracial.TracialMatrixTower +OAI.Analysis.KadisonSimilarity.Tracial.TracialMomentContinuity +OAI.Analysis.KadisonSimilarity.Tracial.TracialNormalSpan +OAI.Analysis.KadisonSimilarity.Tracial.TracialNormalityCriterion +OAI.Analysis.KadisonSimilarity.Tracial.TracialProjectionLifting +OAI.Analysis.KadisonSimilarity.Tracial.TracialRightSupportDischarge +OAI.Analysis.KadisonSimilarity.Tracial.TracialSmallColumn +OAI.Analysis.KadisonSimilarity.Tracial.TracialSmallCornerTransfer +OAI.Analysis.KadisonSimilarity.Tracial.TracialSpectralColumns +OAI.Analysis.KadisonSimilarity.Tracial.TracialSpectralNorm +OAI.Analysis.KadisonSimilarity.Tracial.TracialSpectralTest +OAI.Analysis.KadisonSimilarity.Tracial.TracialStageCommutation +OAI.Analysis.KadisonSimilarity.Tracial.TracialSubalgebraModels +OAI.Analysis.KadisonSimilarity.Tracial.TracialSubalgebraTransfer +OAI.Analysis.KadisonSimilarity.Tracial.TracialSupportedColumns +OAI.Analysis.KadisonSimilarity.Tracial.TracialUltrapowerActions +OAI.Analysis.KadisonSimilarity.Tracial.TracialUltrapowerConstants +OAI.Analysis.KadisonSimilarity.Tracial.TracialUltrapowerCorners +OAI.Analysis.KadisonSimilarity.Tracial.TracialUltrapowerGNS +OAI.Analysis.KadisonSimilarity.Tracial.TracialUltrapowerHom +OAI.Analysis.KadisonSimilarity.Tracial.UltrapowerCommutators +OAI.Analysis.KadisonSimilarity.Tracial.UltrapowerConstants +OAI.Analysis.KadisonSimilarity.Tracial.UltrapowerGeneratedTransfer +OAI.Analysis.KadisonSimilarity.Tracial.UltrapowerNormality +OAI.Analysis.KadisonSimilarity.Tracial.UltrapowerTraceBalls +OAI.Analysis.KadisonSimilarity.UnconditionalMain +OAI.Analysis.KadisonSimilarity.UnconditionalSimilarity +OAI.Analysis.Naimark.Basic +OAI.Analysis.Naimark.States +OAI.Analysis.NuclearUltrapower.HilbertUltraproduct +OAI.Analysis.TracialCohomology.BidualApproximation +OAI.Analysis.TracialCohomology.BilinearModulus +OAI.Analysis.TracialCohomology.CenterExtensions +OAI.Analysis.TracialCohomology.CenterQuantization +OAI.Analysis.TracialCohomology.CenterTrace +OAI.Analysis.TracialCohomology.CentralMatrices +OAI.Analysis.TracialCohomology.Cohomology +OAI.Analysis.TracialCohomology.CornerComparison +OAI.Analysis.TracialCohomology.CornerTraces +OAI.Analysis.TracialCohomology.Corners +OAI.Analysis.TracialCohomology.DominatedFactorization +OAI.Analysis.TracialCohomology.Expectations +OAI.Analysis.TracialCohomology.FinitePaths +OAI.Analysis.TracialCohomology.FreeSeparation +OAI.Analysis.TracialCohomology.FreshBounds +OAI.Analysis.TracialCohomology.GoodExtensions +OAI.Analysis.TracialCohomology.HilbertFactorization +OAI.Analysis.TracialCohomology.HilbertNormalParts +OAI.Analysis.TracialCohomology.Homogeneous +OAI.Analysis.TracialCohomology.InteriorHomotopy +OAI.Analysis.TracialCohomology.LocalQuantization +OAI.Analysis.TracialCohomology.MarkedWords +OAI.Analysis.TracialCohomology.Matrices +OAI.Analysis.TracialCohomology.MatrixExtensions +OAI.Analysis.TracialCohomology.MatrixNorms +OAI.Analysis.TracialCohomology.MatrixRepresentations +OAI.Analysis.TracialCohomology.MixedWords +OAI.Analysis.TracialCohomology.NormalPreservation +OAI.Analysis.TracialCohomology.NormalReduction +OAI.Analysis.TracialCohomology.PartialRepresentations +OAI.Analysis.TracialCohomology.Partitions +OAI.Analysis.TracialCohomology.PatchBounds +OAI.Analysis.TracialCohomology.PatchConstruction +OAI.Analysis.TracialCohomology.PatchTraces +OAI.Analysis.TracialCohomology.ProjectionEstimates +OAI.Analysis.TracialCohomology.RandomSigns +OAI.Analysis.TracialCohomology.RepresentationLimits +OAI.Analysis.TracialCohomology.ResidualFilling +OAI.Analysis.TracialCohomology.SlotHomotopy +OAI.Analysis.TracialCohomology.SmallExpectations +OAI.Analysis.TracialCohomology.TracialPrimitives +OAI.Analysis.TracialCohomology.TypeII +OAI.Analysis.TracialCohomology.Vanishing +OAI.Analysis.TracialCohomology.WordQuantization +OAI.Analysis.Unitarizability.Cocycle +OAI.Analysis.Unitarizability.Model +OAI.Analysis.Unitarizability.Triangular +OAI.Analysis.WeakInfiniteness.MatrixRepresentation diff --git a/tasks/kadison-similarity/solution/reference.py b/tasks/kadison-similarity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kadison-similarity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kadison-similarity/solution/solve.sh b/tasks/kadison-similarity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6cdc4bb1da8ea88c959aeaced384bc69ef5d811e --- /dev/null +++ b/tasks/kadison-similarity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KadisonSimilarity, i.e. module OAI.Analysis.KadisonSimilarity.UnconditionalSimilarity and the +# 816 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.KadisonSimilarity.UnconditionalSimilarity /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KadisonSimilarity" diff --git a/tasks/kadison-similarity/task.toml b/tasks/kadison-similarity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7fd529c6e1472ee75b7c257e7c1128afcd2e1917 --- /dev/null +++ b/tasks/kadison-similarity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kadison-similarity" +version = "1.0.0" +description = "Prove KadisonSimilarity (openai/math family 288: Kadison's similarity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KadisonSimilarity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KadisonSimilarity" +family = "288" +family_title = "Kadison's similarity conjecture" +subject = "Operator algebras" +theorems = ["OAI.KadisonSimilarity.universalCommutatorTheorem", "OAI.KadisonSimilarity.universalHyperreflexivity", "OAI.KadisonSimilarity.similarityTheorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.KadisonSimilarity.UnconditionalSimilarity" +reference_modules = 816 +reference_lean_bytes = 5791602 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3415 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 16912 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kadison-similarity/tests/Challenge.lean b/tasks/kadison-similarity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..62538591f6e231a1babb1bc8bdda23720135e367 --- /dev/null +++ b/tasks/kadison-similarity/tests/Challenge.lean @@ -0,0 +1,122 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace KadisonSimilarity + +universe u v + +section Homomorphisms + +variable (A H : Type*) [CStarAlgebra A] + [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +abbrev BoundedUnitalHom := + {π : A →ₐ[ℂ] (H →L[ℂ] H) // Continuous π} + +def SimilarToStar (π : BoundedUnitalHom A H) : Prop := + ∃ S : (H →L[ℂ] H)ˣ, ∀ a : A, + (S : H →L[ℂ] H) * π.1 (star a) * (↑S⁻¹ : H →L[ℂ] H) = + star ((S : H →L[ℂ] H) * π.1 a * (↑S⁻¹ : H →L[ℂ] H)) + +end Homomorphisms + +section Commutators + +variable {R : Type*} [NormedRing R] + +def commutator (S T : R) : R := S * T - T * S + +end Commutators + +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + +section + +attribute [-instance] NonUnitalCStarAlgebra.toNormedSpace + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +abbrev HilbertCopies (H : Type u) (n : ℕ) := PiLp 2 (fun _ : Fin n => H) + +def matrixOperator {n : ℕ} (X : Matrix (Fin n) (Fin n) (H →L[ℂ] H)) : + HilbertCopies H n →L[ℂ] HilbertCopies H n := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin n => H)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi fun i => + ∑ j : Fin n, (X i j).comp (PiLp.proj 2 (fun _ : Fin n => H) j)) + +def amplify (Y : H →L[ℂ] H) (n : ℕ) : + HilbertCopies H n →L[ℂ] HilbertCopies H n := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin n => H)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi fun i => Y.comp (PiLp.proj 2 (fun _ : Fin n => H) i)) + +def innerDerivation (Y : H →L[ℂ] H) : + (H →L[ℂ] H) →L[ℂ] (H →L[ℂ] H) := + ContinuousLinearMap.mul ℂ (H →L[ℂ] H) Y - + (ContinuousLinearMap.mul ℂ (H →L[ℂ] H)).flip Y + +variable [CompleteSpace H] + +def scalarCommutatorNorm (P : VonNeumannAlgebra H) (Y : H →L[ℂ] H) : ℝ := by + let : SeminormedAddCommGroup P.toStarSubalgebra.toSubalgebra.toSubmodule := inferInstance + let : NormedSpace ℂ P.toStarSubalgebra.toSubalgebra.toSubmodule := inferInstance + exact ‖(innerDerivation Y).comp P.toStarSubalgebra.toSubalgebra.toSubmodule.subtypeL‖ + +def CommutatorEstimate (P : VonNeumannAlgebra H) (C : ℝ) : Prop := + ∀ (Y : H →L[ℂ] H) (n : ℕ) (X : Matrix (Fin n) (Fin n) (H →L[ℂ] H)), + (∀ i j, X i j ∈ P) → + ‖commutator (amplify Y n) (matrixOperator X)‖ ≤ + C * scalarCommutatorNorm P Y * ‖matrixOperator X‖ + +def UniformCommutatorEstimate (C : ℝ) : Prop := + ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (P : VonNeumannAlgebra K), CommutatorEstimate P C + +def UniversalCommutatorTheorem : Prop := ∃ C : ℝ, 0 ≤ C ∧ UniformCommutatorEstimate.{u} C + +def SimilarityTheorem : Prop := + ∀ (A : Type u) [CStarAlgebra A] (K : Type v) [NormedAddCommGroup K] + [InnerProductSpace ℂ K] [CompleteSpace K] (π : BoundedUnitalHom A K), + SimilarToStar A K π + +abbrev CommutantProjection (M : VonNeumannAlgebra H) := + {e : H →L[ℂ] H // e ∈ M.commutant ∧ star e = e ∧ e * e = e} + +def offDiagonalSeminorm (M : VonNeumannAlgebra H) (T : H →L[ℂ] H) : ℝ := + sSup (Set.range fun e : CommutantProjection M => + ‖(1 - (e : H →L[ℂ] H)) * T * (e : H →L[ℂ] H)‖) + +def UniversalHyperreflexivity (C : ℝ) : Prop := + ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (M : VonNeumannAlgebra K) (T : K →L[ℂ] K), + Metric.infDist T (M : Set (K →L[ℂ] K)) ≤ 2 * C * offDiagonalSeminorm M T + +end + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def rowConstant : ℝ := 4 * Real.sqrt 2 +def cyclicConstant : ℝ := (1 + 4 * rowConstant) ^ 2 +def cornerConstant : ℝ := 6 * Real.pi ^ 2 * (1 + 4 * cyclicConstant) +def factorConstant : ℝ := max (max (3 * cornerConstant + 2) (1 + 2 * rowConstant)) 2 +def universalConstant : ℝ := 3 * factorConstant + 2 + +/-- One absolute constant controls every finite matrix commutator. -/ +theorem universalCommutatorTheorem : UniversalCommutatorTheorem.{u} := by + sorry + +/-- Every von Neumann algebra has hyperreflexivity constant at most `2 * universalConstant`. -/ +theorem universalHyperreflexivity : UniversalHyperreflexivity.{u} universalConstant := by + sorry + +/-- Every bounded unital representation is similar to a star representation. -/ +theorem similarityTheorem : SimilarityTheorem.{u,v} := by + sorry + +end KadisonSimilarity + +end + +end OAI diff --git a/tasks/kadison-similarity/tests/grade.py b/tasks/kadison-similarity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kadison-similarity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kadison-similarity/tests/task.json b/tasks/kadison-similarity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7eedea2ce9fd7a2454c12176c38177eee83f99ab --- /dev/null +++ b/tasks/kadison-similarity/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "KadisonSimilarity", + "comparator": { + "theorem_names": [ + "OAI.KadisonSimilarity.universalCommutatorTheorem", + "OAI.KadisonSimilarity.universalHyperreflexivity", + "OAI.KadisonSimilarity.similarityTheorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16012 +} \ No newline at end of file diff --git a/tasks/kadison-similarity/tests/test.sh b/tasks/kadison-similarity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kadison-similarity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kahler-splitting/environment/Dockerfile b/tasks/kahler-splitting/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kahler-splitting/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kahler-splitting/environment/fetch_mathlib.sh b/tasks/kahler-splitting/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kahler-splitting/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kahler-splitting/environment/lake-manifest.json b/tasks/kahler-splitting/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kahler-splitting/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kahler-splitting/environment/lakefile.lean b/tasks/kahler-splitting/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kahler-splitting/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kahler-splitting/environment/lean_setup.sh b/tasks/kahler-splitting/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kahler-splitting/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kahler-splitting/environment/pack_submission.py b/tasks/kahler-splitting/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kahler-splitting/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kahler-splitting/instruction.md b/tasks/kahler-splitting/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d901c946d45c41020c2b9a6953da7f4506bb8e9a --- /dev/null +++ b/tasks/kahler-splitting/instruction.md @@ -0,0 +1,190 @@ +# openai/math challenge `KahlerSplitting` (family 052) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 052 of the release, *Tangent-bundle splittings and universal covers* +(Algebraic and complex geometry). The family as a whole: A splitting of the tangent bundle of a compact Kahler manifold into two integrable holomorphic subbundles induces a compatible product decomposition of its universal cover, proving the two-summand form of Beauville's splitting conjecture. On smooth rationally connected projective manifolds, both summands are automatically integrable, establishing Horing's conjecture and the corresponding product decomposition. + +The challenge is `KahlerSplitting`, also at `/opt/openai-math/challenges/KahlerSplitting.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Manifold ContDiff +open Set + +namespace UniversalCoverSplitting + +universe u v + +abbrev Model (n : ℕ) := Fin n → ℂ +abbrev model (n : ℕ) := 𝓘(ℂ, Model n) + +structure ComplexManifold (n : ℕ) where + Carrier : Type u + [topology : TopologicalSpace Carrier] + [charted : ChartedSpace (Model n) Carrier] + [hausdorff : T2Space Carrier] + [secondCountable : SecondCountableTopology Carrier] + [complexSmooth : IsManifold (model n) ∞ Carrier] + +attribute [instance] ComplexManifold.topology ComplexManifold.charted + ComplexManifold.hausdorff ComplexManifold.secondCountable ComplexManifold.complexSmooth + +variable {n r₁ r₂ : ℕ} + +abbrev Tangent (X : ComplexManifold.{u} n) (x : X.Carrier) := TangentSpace (model n) x +abbrev RealMetricField (X : ComplexManifold.{u} n) := + ∀ x : X.Carrier, Tangent X x →ₗ[ℝ] Tangent X x →ₗ[ℝ] ℝ + +def metricInChart {X : ComplexManifold.{u} n} (g : RealMetricField X) + (c : X.Carrier) (z u v : Model n) : ℝ := + let e := extChartAt (model n) c + let q := mfderiv (model n) (model n) e.symm z + g (e.symm z) (q u) (q v) + +def fundamentalInChart {X : ComplexManifold.{u} n} (g : RealMetricField X) + (c : X.Carrier) (z u v : Model n) : ℝ := + metricInChart g c z (Complex.I • u) v + +structure KahlerMetric (X : ComplexManifold.{u} n) where + metric : RealMetricField X + symmetric : ∀ x u v, metric x u v = metric x v u + positive : ∀ x u, u ≠ 0 → 0 < metric x u u + hermitian : ∀ x u v, metric x (Complex.I • u) (Complex.I • v) = metric x u v + smooth : ∀ c u v, ContDiffOn ℝ ∞ (fun z ↦ metricInChart metric c z u v) + (extChartAt (model n) c).target + closed : ∀ c z, z ∈ (extChartAt (model n) c).target → ∀ u v w : Model n, + fderiv ℝ (fun y ↦ fundamentalInChart metric c y v w) z u + + fderiv ℝ (fun y ↦ fundamentalInChart metric c y w u) z v + + fderiv ℝ (fun y ↦ fundamentalInChart metric c y u v) z w = 0 + +abbrev ProjectionField (X : ComplexManifold.{u} n) := + ∀ x : X.Carrier, Tangent X x →L[ℂ] Tangent X x + +def projectionInChart {X : ComplexManifold.{u} n} (P : ProjectionField X) + (c : X.Carrier) (z : Model n) : Model n →L[ℂ] Model n := + let e := extChartAt (model n) c + (mfderiv (model n) (model n) e (e.symm z)).comp + ((P (e.symm z)).comp (mfderiv (model n) (model n) e.symm z)) + +def HolomorphicProjection {X : ComplexManifold.{u} n} (P : ProjectionField X) : Prop := + ∀ c, DifferentiableOn ℂ (projectionInChart P c) (extChartAt (model n) c).target + +def Integrable {X : ComplexManifold.{u} n} (P : ProjectionField X) : Prop := + ∀ c U, IsOpen U → U ⊆ (extChartAt (model n) c).target → + ∀ V W : Model n → Model n, + DifferentiableOn ℂ V U → DifferentiableOn ℂ W U → + (∀ z ∈ U, projectionInChart P c z (V z) = V z) → + (∀ z ∈ U, projectionInChart P c z (W z) = W z) → + ∀ z ∈ U, projectionInChart P c z (VectorField.lieBracket ℂ V W z) = + VectorField.lieBracket ℂ V W z + +structure HolomorphicSplitting (X : ComplexManifold.{u} n) (r₁ r₂ : ℕ) where + projection : ProjectionField X + idempotent : ∀ x v, projection x (projection x v) = projection x v + holomorphic : HolomorphicProjection projection + first_rank : ∀ x, Module.finrank ℂ (LinearMap.range (projection x).toLinearMap) = r₁ + second_rank : ∀ x, Module.finrank ℂ (LinearMap.ker (projection x).toLinearMap) = r₂ + +def complementaryProjection {X : ComplexManifold.{u} n} + (S : HolomorphicSplitting X r₁ r₂) : ProjectionField X := + fun x ↦ ContinuousLinearMap.id ℂ (Tangent X x) - S.projection x + +def LocalBiholomorphism {X : ComplexManifold.{u} n} {Z : ComplexManifold.{v} n} + (π : Z.Carrier → X.Carrier) : Prop := + ∀ z, ∃ e : OpenPartialHomeomorph Z.Carrier X.Carrier, + z ∈ e.source ∧ (∀ w ∈ e.source, e w = π w) ∧ + MDifferentiableOn (model n) (model n) e e.source ∧ + MDifferentiableOn (model n) (model n) e.symm e.target + +structure OrdinaryUniversalCover (X : ComplexManifold.{u} n) + (Z : ComplexManifold.{v} n) where + projection : Z.Carrier → X.Carrier + covering : IsCoveringMap projection + [connected : ConnectedSpace Z.Carrier] + [simplyConnected : SimplyConnectedSpace Z.Carrier] + liftedComplexStructure : LocalBiholomorphism projection + +def CompatibleProduct {X : ComplexManifold.{u} n} {Z : ComplexManifold.{v} n} + (S : HolomorphicSplitting X r₁ r₂) (π : OrdinaryUniversalCover X Z) + (Y₁ : ComplexManifold.{v} r₁) (Y₂ : ComplexManifold.{v} r₂) : Prop := + ∃ Φ : Z.Carrier ≃ₜ (Y₁.Carrier × Y₂.Carrier), + MDifferentiable (model n) ((model r₁).prod (model r₂)) Φ ∧ + MDifferentiable ((model r₁).prod (model r₂)) (model n) Φ.symm ∧ + (∀ z, Submodule.map + (mfderiv (model n) ((model r₁).prod (model r₂)) Φ z).toLinearMap + (Submodule.comap (mfderiv (model n) (model n) π.projection z).toLinearMap + (LinearMap.range (S.projection (π.projection z)).toLinearMap)) = + LinearMap.ker (ContinuousLinearMap.snd ℂ (Model r₁) (Model r₂)).toLinearMap) ∧ + (∀ z, Submodule.map + (mfderiv (model n) ((model r₁).prod (model r₂)) Φ z).toLinearMap + (Submodule.comap (mfderiv (model n) (model n) π.projection z).toLinearMap + (LinearMap.ker (S.projection (π.projection z)).toLinearMap)) = + LinearMap.ker (ContinuousLinearMap.fst ℂ (Model r₁) (Model r₂)).toLinearMap) + +open Set +open scoped Manifold ContDiff +variable {n r₁ r₂ : ℕ} + +theorem main (X : ComplexManifold.{u} n) [CompactSpace X.Carrier] + [ConnectedSpace X.Carrier] (hn : 2 ≤ n) (hr₁ : 0 < r₁) (hr₂ : 0 < r₂) + (g : KahlerMetric X) (S : HolomorphicSplitting X r₁ r₂) + (h₁ : Integrable S.projection) (h₂ : Integrable (complementaryProjection S)) + (Z : ComplexManifold.{v} n) (π : OrdinaryUniversalCover X Z) : + ∃ (Y₁ : ComplexManifold.{v} r₁) (Y₂ : ComplexManifold.{v} r₂), + ConnectedSpace Y₁.Carrier ∧ ConnectedSpace Y₂.Carrier ∧ + SimplyConnectedSpace Y₁.Carrier ∧ SimplyConnectedSpace Y₂.Carrier ∧ + CompatibleProduct S π Y₁ Y₂ := by + sorry + +end UniversalCoverSplitting + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KahlerSplitting.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.UniversalCoverSplitting.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kahler-splitting/solution/closure.txt b/tasks/kahler-splitting/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f47a31e081c7ae047d8431796b9b1d01c44c4092 --- /dev/null +++ b/tasks/kahler-splitting/solution/closure.txt @@ -0,0 +1,46 @@ +OAI.Geometry.KahlerSplitting.AreaBounds +OAI.Geometry.KahlerSplitting.AxisContinuation +OAI.Geometry.KahlerSplitting.Biholomorphism +OAI.Geometry.KahlerSplitting.BlockMaps +OAI.Geometry.KahlerSplitting.BoundaryExtension +OAI.Geometry.KahlerSplitting.BoxGluing +OAI.Geometry.KahlerSplitting.Boxes +OAI.Geometry.KahlerSplitting.ClosedForm +OAI.Geometry.KahlerSplitting.CommutingFlows +OAI.Geometry.KahlerSplitting.CompactCurves +OAI.Geometry.KahlerSplitting.ContinuousBoxes +OAI.Geometry.KahlerSplitting.DiskArea +OAI.Geometry.KahlerSplitting.DiskAxes +OAI.Geometry.KahlerSplitting.EtaleGerms +OAI.Geometry.KahlerSplitting.FixedManifolds +OAI.Geometry.KahlerSplitting.FlowVariation +OAI.Geometry.KahlerSplitting.FormDerivatives +OAI.Geometry.KahlerSplitting.Frobenius +OAI.Geometry.KahlerSplitting.GermTransport +OAI.Geometry.KahlerSplitting.GlobalProjections +OAI.Geometry.KahlerSplitting.Grid +OAI.Geometry.KahlerSplitting.HolomorphicIdentity +OAI.Geometry.KahlerSplitting.Main +OAI.Geometry.KahlerSplitting.MetricBounds +OAI.Geometry.KahlerSplitting.MixedShell +OAI.Geometry.KahlerSplitting.Model +OAI.Geometry.KahlerSplitting.Monodromy +OAI.Geometry.KahlerSplitting.MovingStokes +OAI.Geometry.KahlerSplitting.ParameterGrid +OAI.Geometry.KahlerSplitting.PathBoxes +OAI.Geometry.KahlerSplitting.PathDerivatives +OAI.Geometry.KahlerSplitting.PathLifts +OAI.Geometry.KahlerSplitting.Picard +OAI.Geometry.KahlerSplitting.PlaqueCharts +OAI.Geometry.KahlerSplitting.PolydiskAxes +OAI.Geometry.KahlerSplitting.ProductCharts +OAI.Geometry.KahlerSplitting.ProductLocal +OAI.Geometry.KahlerSplitting.ProductRetracts +OAI.Geometry.KahlerSplitting.ProjectionImages +OAI.Geometry.KahlerSplitting.Removable +OAI.Geometry.KahlerSplitting.RetractCharts +OAI.Geometry.KahlerSplitting.ShellFilling +OAI.Geometry.KahlerSplitting.SmallAnnuli +OAI.Geometry.KahlerSplitting.SmallArea +OAI.Geometry.KahlerSplitting.Superellipsoids +OAI.Geometry.KahlerSplitting.SwapSplitting diff --git a/tasks/kahler-splitting/solution/reference.py b/tasks/kahler-splitting/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kahler-splitting/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kahler-splitting/solution/solve.sh b/tasks/kahler-splitting/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..28f87ea132a228bd5a563b5a07d0b98920225e4a --- /dev/null +++ b/tasks/kahler-splitting/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KahlerSplitting, i.e. module OAI.Geometry.KahlerSplitting.Main and the +# 46 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.KahlerSplitting.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KahlerSplitting" diff --git a/tasks/kahler-splitting/task.toml b/tasks/kahler-splitting/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32be6c19abbdc0976947a4f441c1d8ddc18aec68 --- /dev/null +++ b/tasks/kahler-splitting/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kahler-splitting" +version = "1.0.0" +description = "Prove KahlerSplitting (openai/math family 052: Tangent-bundle splittings and universal covers) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KahlerSplitting.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KahlerSplitting" +family = "052" +family_title = "Tangent-bundle splittings and universal covers" +subject = "Algebraic and complex geometry" +theorems = ["OAI.UniversalCoverSplitting.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.KahlerSplitting.Main" +reference_modules = 46 +reference_lean_bytes = 726796 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1239 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12354 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kahler-splitting/tests/Challenge.lean b/tasks/kahler-splitting/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2a65c1ad6815602906d6c2ce11af6200942fba5 --- /dev/null +++ b/tasks/kahler-splitting/tests/Challenge.lean @@ -0,0 +1,139 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped Manifold ContDiff +open Set + +namespace UniversalCoverSplitting + +universe u v + +abbrev Model (n : ℕ) := Fin n → ℂ +abbrev model (n : ℕ) := 𝓘(ℂ, Model n) + +structure ComplexManifold (n : ℕ) where + Carrier : Type u + [topology : TopologicalSpace Carrier] + [charted : ChartedSpace (Model n) Carrier] + [hausdorff : T2Space Carrier] + [secondCountable : SecondCountableTopology Carrier] + [complexSmooth : IsManifold (model n) ∞ Carrier] + +attribute [instance] ComplexManifold.topology ComplexManifold.charted + ComplexManifold.hausdorff ComplexManifold.secondCountable ComplexManifold.complexSmooth + +variable {n r₁ r₂ : ℕ} + +abbrev Tangent (X : ComplexManifold.{u} n) (x : X.Carrier) := TangentSpace (model n) x +abbrev RealMetricField (X : ComplexManifold.{u} n) := + ∀ x : X.Carrier, Tangent X x →ₗ[ℝ] Tangent X x →ₗ[ℝ] ℝ + +def metricInChart {X : ComplexManifold.{u} n} (g : RealMetricField X) + (c : X.Carrier) (z u v : Model n) : ℝ := + let e := extChartAt (model n) c + let q := mfderiv (model n) (model n) e.symm z + g (e.symm z) (q u) (q v) + +def fundamentalInChart {X : ComplexManifold.{u} n} (g : RealMetricField X) + (c : X.Carrier) (z u v : Model n) : ℝ := + metricInChart g c z (Complex.I • u) v + +structure KahlerMetric (X : ComplexManifold.{u} n) where + metric : RealMetricField X + symmetric : ∀ x u v, metric x u v = metric x v u + positive : ∀ x u, u ≠ 0 → 0 < metric x u u + hermitian : ∀ x u v, metric x (Complex.I • u) (Complex.I • v) = metric x u v + smooth : ∀ c u v, ContDiffOn ℝ ∞ (fun z ↦ metricInChart metric c z u v) + (extChartAt (model n) c).target + closed : ∀ c z, z ∈ (extChartAt (model n) c).target → ∀ u v w : Model n, + fderiv ℝ (fun y ↦ fundamentalInChart metric c y v w) z u + + fderiv ℝ (fun y ↦ fundamentalInChart metric c y w u) z v + + fderiv ℝ (fun y ↦ fundamentalInChart metric c y u v) z w = 0 + +abbrev ProjectionField (X : ComplexManifold.{u} n) := + ∀ x : X.Carrier, Tangent X x →L[ℂ] Tangent X x + +def projectionInChart {X : ComplexManifold.{u} n} (P : ProjectionField X) + (c : X.Carrier) (z : Model n) : Model n →L[ℂ] Model n := + let e := extChartAt (model n) c + (mfderiv (model n) (model n) e (e.symm z)).comp + ((P (e.symm z)).comp (mfderiv (model n) (model n) e.symm z)) + +def HolomorphicProjection {X : ComplexManifold.{u} n} (P : ProjectionField X) : Prop := + ∀ c, DifferentiableOn ℂ (projectionInChart P c) (extChartAt (model n) c).target + +def Integrable {X : ComplexManifold.{u} n} (P : ProjectionField X) : Prop := + ∀ c U, IsOpen U → U ⊆ (extChartAt (model n) c).target → + ∀ V W : Model n → Model n, + DifferentiableOn ℂ V U → DifferentiableOn ℂ W U → + (∀ z ∈ U, projectionInChart P c z (V z) = V z) → + (∀ z ∈ U, projectionInChart P c z (W z) = W z) → + ∀ z ∈ U, projectionInChart P c z (VectorField.lieBracket ℂ V W z) = + VectorField.lieBracket ℂ V W z + +structure HolomorphicSplitting (X : ComplexManifold.{u} n) (r₁ r₂ : ℕ) where + projection : ProjectionField X + idempotent : ∀ x v, projection x (projection x v) = projection x v + holomorphic : HolomorphicProjection projection + first_rank : ∀ x, Module.finrank ℂ (LinearMap.range (projection x).toLinearMap) = r₁ + second_rank : ∀ x, Module.finrank ℂ (LinearMap.ker (projection x).toLinearMap) = r₂ + +def complementaryProjection {X : ComplexManifold.{u} n} + (S : HolomorphicSplitting X r₁ r₂) : ProjectionField X := + fun x ↦ ContinuousLinearMap.id ℂ (Tangent X x) - S.projection x + +def LocalBiholomorphism {X : ComplexManifold.{u} n} {Z : ComplexManifold.{v} n} + (π : Z.Carrier → X.Carrier) : Prop := + ∀ z, ∃ e : OpenPartialHomeomorph Z.Carrier X.Carrier, + z ∈ e.source ∧ (∀ w ∈ e.source, e w = π w) ∧ + MDifferentiableOn (model n) (model n) e e.source ∧ + MDifferentiableOn (model n) (model n) e.symm e.target + +structure OrdinaryUniversalCover (X : ComplexManifold.{u} n) + (Z : ComplexManifold.{v} n) where + projection : Z.Carrier → X.Carrier + covering : IsCoveringMap projection + [connected : ConnectedSpace Z.Carrier] + [simplyConnected : SimplyConnectedSpace Z.Carrier] + liftedComplexStructure : LocalBiholomorphism projection + +def CompatibleProduct {X : ComplexManifold.{u} n} {Z : ComplexManifold.{v} n} + (S : HolomorphicSplitting X r₁ r₂) (π : OrdinaryUniversalCover X Z) + (Y₁ : ComplexManifold.{v} r₁) (Y₂ : ComplexManifold.{v} r₂) : Prop := + ∃ Φ : Z.Carrier ≃ₜ (Y₁.Carrier × Y₂.Carrier), + MDifferentiable (model n) ((model r₁).prod (model r₂)) Φ ∧ + MDifferentiable ((model r₁).prod (model r₂)) (model n) Φ.symm ∧ + (∀ z, Submodule.map + (mfderiv (model n) ((model r₁).prod (model r₂)) Φ z).toLinearMap + (Submodule.comap (mfderiv (model n) (model n) π.projection z).toLinearMap + (LinearMap.range (S.projection (π.projection z)).toLinearMap)) = + LinearMap.ker (ContinuousLinearMap.snd ℂ (Model r₁) (Model r₂)).toLinearMap) ∧ + (∀ z, Submodule.map + (mfderiv (model n) ((model r₁).prod (model r₂)) Φ z).toLinearMap + (Submodule.comap (mfderiv (model n) (model n) π.projection z).toLinearMap + (LinearMap.ker (S.projection (π.projection z)).toLinearMap)) = + LinearMap.ker (ContinuousLinearMap.fst ℂ (Model r₁) (Model r₂)).toLinearMap) + +open Set +open scoped Manifold ContDiff +variable {n r₁ r₂ : ℕ} + +theorem main (X : ComplexManifold.{u} n) [CompactSpace X.Carrier] + [ConnectedSpace X.Carrier] (hn : 2 ≤ n) (hr₁ : 0 < r₁) (hr₂ : 0 < r₂) + (g : KahlerMetric X) (S : HolomorphicSplitting X r₁ r₂) + (h₁ : Integrable S.projection) (h₂ : Integrable (complementaryProjection S)) + (Z : ComplexManifold.{v} n) (π : OrdinaryUniversalCover X Z) : + ∃ (Y₁ : ComplexManifold.{v} r₁) (Y₂ : ComplexManifold.{v} r₂), + ConnectedSpace Y₁.Carrier ∧ ConnectedSpace Y₂.Carrier ∧ + SimplyConnectedSpace Y₁.Carrier ∧ SimplyConnectedSpace Y₂.Carrier ∧ + CompatibleProduct S π Y₁ Y₂ := by + sorry + +end UniversalCoverSplitting + +end + +end OAI diff --git a/tasks/kahler-splitting/tests/grade.py b/tasks/kahler-splitting/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kahler-splitting/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kahler-splitting/tests/task.json b/tasks/kahler-splitting/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1ebead7838efb80d3ed418e109234148d725a003 --- /dev/null +++ b/tasks/kahler-splitting/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KahlerSplitting", + "comparator": { + "theorem_names": [ + "OAI.UniversalCoverSplitting.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11454 +} \ No newline at end of file diff --git a/tasks/kahler-splitting/tests/test.sh b/tasks/kahler-splitting/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kahler-splitting/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kaplansky-direct-finiteness/environment/Dockerfile b/tasks/kaplansky-direct-finiteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kaplansky-direct-finiteness/environment/fetch_mathlib.sh b/tasks/kaplansky-direct-finiteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kaplansky-direct-finiteness/environment/lake-manifest.json b/tasks/kaplansky-direct-finiteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kaplansky-direct-finiteness/environment/lakefile.lean b/tasks/kaplansky-direct-finiteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kaplansky-direct-finiteness/environment/lean_setup.sh b/tasks/kaplansky-direct-finiteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kaplansky-direct-finiteness/environment/pack_submission.py b/tasks/kaplansky-direct-finiteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kaplansky-direct-finiteness/instruction.md b/tasks/kaplansky-direct-finiteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..76ad239e20bf0fed9b8194314a64afb1eaab8f64 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/instruction.md @@ -0,0 +1,68 @@ +# openai/math challenge `KaplanskyDirectFiniteness` (family 197) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 197 of the release, *Nonsofic groups and group-ring counterexamples* +(Algebra). The family as a whole: Constructs a finitely presented torsion-free nonsofic group whose group algebra over $\mathbb F_2$ is not directly finite, disproving Kaplansky's conjecture even without torsion. Companion examples give injective nonsurjective cellular automata on all configurations, refuting Gottschalk's surjunctivity conjecture. Another counterexample is an integral group-ring matrix, invertible over the rational group ring, with Fuglede–Kadison determinant strictly between zero and one, disproving the unrestricted Determinant Conjecture. + +The challenge is `KaplanskyDirectFiniteness`, also at `/opt/openai-math/challenges/KaplanskyDirectFiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace KaplanskyCounterexample + +def MainClaim : Prop := + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K 2), + ∃ (G : Type) (_ : Group G) (_ : Group.FG G), + ∃ a b : MonoidAlgebra K G, a * b = 1 ∧ b * a ≠ 1 + +theorem main_theorem : MainClaim := by + sorry + +end KaplanskyCounterexample + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KaplanskyDirectFiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KaplanskyCounterexample.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kaplansky-direct-finiteness/solution/closure.txt b/tasks/kaplansky-direct-finiteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbf677f0686f0fe6111e46c637d184f7dbb2028b --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/solution/closure.txt @@ -0,0 +1,121 @@ +OAI.RingTheory.DirectFiniteness.AffineLines +OAI.RingTheory.DirectFiniteness.AlgebraicCriterion +OAI.RingTheory.DirectFiniteness.AlgebraicPacking +OAI.RingTheory.DirectFiniteness.Alteration +OAI.RingTheory.DirectFiniteness.AssignedDevelopment +OAI.RingTheory.DirectFiniteness.BalanceCoarsening +OAI.RingTheory.DirectFiniteness.BalanceDetachment +OAI.RingTheory.DirectFiniteness.BalanceObstruction +OAI.RingTheory.DirectFiniteness.BalanceRestriction +OAI.RingTheory.DirectFiniteness.BoundaryCycles +OAI.RingTheory.DirectFiniteness.BoundaryFilling +OAI.RingTheory.DirectFiniteness.BoundarySplitting +OAI.RingTheory.DirectFiniteness.CandidateBounds +OAI.RingTheory.DirectFiniteness.CandidateClassification +OAI.RingTheory.DirectFiniteness.CandidateCounting +OAI.RingTheory.DirectFiniteness.CandidateDependencies +OAI.RingTheory.DirectFiniteness.CandidateGeometry +OAI.RingTheory.DirectFiniteness.CandidateModel +OAI.RingTheory.DirectFiniteness.CandidateRelations +OAI.RingTheory.DirectFiniteness.CharacterFormulas +OAI.RingTheory.DirectFiniteness.CharacterIdempotents +OAI.RingTheory.DirectFiniteness.CharacterTwist +OAI.RingTheory.DirectFiniteness.ChosenCriterion +OAI.RingTheory.DirectFiniteness.CoordinateCharacters +OAI.RingTheory.DirectFiniteness.CycleFactorization +OAI.RingTheory.DirectFiniteness.CycleSplitting +OAI.RingTheory.DirectFiniteness.CycleSums +OAI.RingTheory.DirectFiniteness.CyclicLabels +OAI.RingTheory.DirectFiniteness.DetachmentGenus +OAI.RingTheory.DirectFiniteness.DiagramDeletion +OAI.RingTheory.DirectFiniteness.DiagramInsertion +OAI.RingTheory.DirectFiniteness.DiagramJoining +OAI.RingTheory.DirectFiniteness.DiagramObstruction +OAI.RingTheory.DirectFiniteness.DiagramReduction +OAI.RingTheory.DirectFiniteness.DirectionCompleteness +OAI.RingTheory.DirectFiniteness.DirectionFrame +OAI.RingTheory.DirectFiniteness.DirectionSpaces +OAI.RingTheory.DirectFiniteness.EulerBound +OAI.RingTheory.DirectFiniteness.EventLoad +OAI.RingTheory.DirectFiniteness.FieldExtensions +OAI.RingTheory.DirectFiniteness.FiniteAffine +OAI.RingTheory.DirectFiniteness.FiniteBlock +OAI.RingTheory.DirectFiniteness.FiniteGeneration +OAI.RingTheory.DirectFiniteness.FiniteParameters +OAI.RingTheory.DirectFiniteness.FrameExistence +OAI.RingTheory.DirectFiniteness.FrameTransport +OAI.RingTheory.DirectFiniteness.GluedGroup +OAI.RingTheory.DirectFiniteness.GluedWords +OAI.RingTheory.DirectFiniteness.GroupEmbedding +OAI.RingTheory.DirectFiniteness.HoleEvents +OAI.RingTheory.DirectFiniteness.HoleExistence +OAI.RingTheory.DirectFiniteness.HoleNumerics +OAI.RingTheory.DirectFiniteness.HoleSelection +OAI.RingTheory.DirectFiniteness.IncidenceCycles +OAI.RingTheory.DirectFiniteness.IncidenceDirections +OAI.RingTheory.DirectFiniteness.LabelSupport +OAI.RingTheory.DirectFiniteness.LexicographicOrder +OAI.RingTheory.DirectFiniteness.Main +OAI.RingTheory.DirectFiniteness.MatrixBlock +OAI.RingTheory.DirectFiniteness.Model +OAI.RingTheory.DirectFiniteness.ModelPartition +OAI.RingTheory.DirectFiniteness.MultiHNN +OAI.RingTheory.DirectFiniteness.OneCandidateCounting +OAI.RingTheory.DirectFiniteness.OpenDiagrams +OAI.RingTheory.DirectFiniteness.PackingFormulas +OAI.RingTheory.DirectFiniteness.Pairing +OAI.RingTheory.DirectFiniteness.ParameterBounds +OAI.RingTheory.DirectFiniteness.PartialPartition +OAI.RingTheory.DirectFiniteness.PartitionMerging +OAI.RingTheory.DirectFiniteness.PlanarBalance +OAI.RingTheory.DirectFiniteness.PlanarDiagrams +OAI.RingTheory.DirectFiniteness.PlaneOperators +OAI.RingTheory.DirectFiniteness.PrescribedData +OAI.RingTheory.DirectFiniteness.PrescribedDirections +OAI.RingTheory.DirectFiniteness.PrescribedFields +OAI.RingTheory.DirectFiniteness.PrescribedIncidence +OAI.RingTheory.DirectFiniteness.PrescribedOutputs +OAI.RingTheory.DirectFiniteness.PrescribedPairing +OAI.RingTheory.DirectFiniteness.PrescribedParameters +OAI.RingTheory.DirectFiniteness.PrescribedSearch +OAI.RingTheory.DirectFiniteness.PrescribedSlots +OAI.RingTheory.DirectFiniteness.PrescribedSubfield +OAI.RingTheory.DirectFiniteness.PrimeCertificate +OAI.RingTheory.DirectFiniteness.ProductAlgebras +OAI.RingTheory.DirectFiniteness.QuotientField +OAI.RingTheory.DirectFiniteness.Rectangular +OAI.RingTheory.DirectFiniteness.ReducedWalks +OAI.RingTheory.DirectFiniteness.ReplacementGeometry +OAI.RingTheory.DirectFiniteness.ReplacementPolygon +OAI.RingTheory.DirectFiniteness.RibbonDetachment +OAI.RingTheory.DirectFiniteness.RibbonGeometry +OAI.RingTheory.DirectFiniteness.RibbonRestriction +OAI.RingTheory.DirectFiniteness.RibbonSplitting +OAI.RingTheory.DirectFiniteness.RibbonSums +OAI.RingTheory.DirectFiniteness.RibbonWheels +OAI.RingTheory.DirectFiniteness.ScalarFormulas +OAI.RingTheory.DirectFiniteness.ScalarWitnesses +OAI.RingTheory.DirectFiniteness.ShortIndependence +OAI.RingTheory.DirectFiniteness.ShortRelators +OAI.RingTheory.DirectFiniteness.SimplexBound +OAI.RingTheory.DirectFiniteness.SlabAssembly +OAI.RingTheory.DirectFiniteness.SlabAvoidance +OAI.RingTheory.DirectFiniteness.SlabEvents +OAI.RingTheory.DirectFiniteness.SlabHoleEvents +OAI.RingTheory.DirectFiniteness.SlabKeys +OAI.RingTheory.DirectFiniteness.SlabLoad +OAI.RingTheory.DirectFiniteness.SlabNumerics +OAI.RingTheory.DirectFiniteness.SlabPartition +OAI.RingTheory.DirectFiniteness.SlabPatch +OAI.RingTheory.DirectFiniteness.TradeDegree +OAI.RingTheory.DirectFiniteness.TradeFamily +OAI.RingTheory.DirectFiniteness.TradeGirth +OAI.RingTheory.DirectFiniteness.TradeLines +OAI.RingTheory.DirectFiniteness.TradePolygon +OAI.RingTheory.DirectFiniteness.TranslatedUnits +OAI.RingTheory.DirectFiniteness.VertexMerging +OAI.RingTheory.DirectFiniteness.WeightTransfer +OAI.RingTheory.DirectFiniteness.WordCycles +OAI.RingTheory.DirectFiniteness.WordDiagrams +OAI.RingTheory.DirectFiniteness.WordReduction +OAI.RingTheory.DirectFiniteness.WordWheels diff --git a/tasks/kaplansky-direct-finiteness/solution/reference.py b/tasks/kaplansky-direct-finiteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kaplansky-direct-finiteness/solution/solve.sh b/tasks/kaplansky-direct-finiteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..cfb1717f3c364aaa13ec9dd8a0325705ef18b5fb --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KaplanskyDirectFiniteness, i.e. module OAI.RingTheory.DirectFiniteness.Main and the +# 121 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.DirectFiniteness.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KaplanskyDirectFiniteness" diff --git a/tasks/kaplansky-direct-finiteness/task.toml b/tasks/kaplansky-direct-finiteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2fc01fd5db99856df1ee8729291072ce9dcab9e1 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kaplansky-direct-finiteness" +version = "1.0.0" +description = "Prove KaplanskyDirectFiniteness (openai/math family 197: Nonsofic groups and group-ring counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KaplanskyDirectFiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KaplanskyDirectFiniteness" +family = "197" +family_title = "Nonsofic groups and group-ring counterexamples" +subject = "Algebra" +theorems = ["OAI.KaplanskyCounterexample.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.DirectFiniteness.Main" +reference_modules = 121 +reference_lean_bytes = 544294 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1170 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12189 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kaplansky-direct-finiteness/tests/Challenge.lean b/tasks/kaplansky-direct-finiteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3c79842accde59474d4b5a873bf23ef70f89238d --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/tests/Challenge.lean @@ -0,0 +1,17 @@ +import Mathlib + +namespace OAI + +namespace KaplanskyCounterexample + +def MainClaim : Prop := + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K 2), + ∃ (G : Type) (_ : Group G) (_ : Group.FG G), + ∃ a b : MonoidAlgebra K G, a * b = 1 ∧ b * a ≠ 1 + +theorem main_theorem : MainClaim := by + sorry + +end KaplanskyCounterexample + +end OAI diff --git a/tasks/kaplansky-direct-finiteness/tests/grade.py b/tasks/kaplansky-direct-finiteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kaplansky-direct-finiteness/tests/task.json b/tasks/kaplansky-direct-finiteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..98b68a51d4128b94d1f9e07e6984468c08acbcfc --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KaplanskyDirectFiniteness", + "comparator": { + "theorem_names": [ + "OAI.KaplanskyCounterexample.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11289 +} \ No newline at end of file diff --git a/tasks/kaplansky-direct-finiteness/tests/test.sh b/tasks/kaplansky-direct-finiteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kaplansky-direct-finiteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kaplansky-finitely-presented/environment/Dockerfile b/tasks/kaplansky-finitely-presented/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kaplansky-finitely-presented/environment/fetch_mathlib.sh b/tasks/kaplansky-finitely-presented/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kaplansky-finitely-presented/environment/lake-manifest.json b/tasks/kaplansky-finitely-presented/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kaplansky-finitely-presented/environment/lakefile.lean b/tasks/kaplansky-finitely-presented/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kaplansky-finitely-presented/environment/lean_setup.sh b/tasks/kaplansky-finitely-presented/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kaplansky-finitely-presented/environment/pack_submission.py b/tasks/kaplansky-finitely-presented/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kaplansky-finitely-presented/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kaplansky-finitely-presented/instruction.md b/tasks/kaplansky-finitely-presented/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a03e3841e3722593c3b2d83ed303ad80cb748e70 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/instruction.md @@ -0,0 +1,65 @@ +# openai/math challenge `KaplanskyFinitelyPresented` (family 197) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 197 of the release, *Nonsofic groups and group-ring counterexamples* +(Algebra). The family as a whole: Constructs a finitely presented torsion-free nonsofic group whose group algebra over $\mathbb F_2$ is not directly finite, disproving Kaplansky's conjecture even without torsion. Companion examples give injective nonsurjective cellular automata on all configurations, refuting Gottschalk's surjunctivity conjecture. Another counterexample is an integral group-ring matrix, invertible over the rational group ring, with Fuglede–Kadison determinant strictly between zero and one, disproving the unrestricted Determinant Conjecture. + +The challenge is `KaplanskyFinitelyPresented`, also at `/opt/openai-math/challenges/KaplanskyFinitelyPresented.lean`: + +```lean +import Mathlib + +namespace OAI.KaplanskyCounterexample + +/-- A finite characteristic-two field and a finitely presented group with odd-prime +order torsion give a counterexample to direct finiteness (paper, Theorem 1.1). -/ +theorem finitelyPresented_counterexample : + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K 2), + ∃ (G : Type) (_ : Group G) (_ : Group.IsFinitelyPresented G), + (∃ (ℓ : ℕ) (_ : ℓ.Prime) (_ : Odd ℓ) (g : G), orderOf g = ℓ) ∧ + ∃ a_out b_out : MonoidAlgebra K G, a_out * b_out = 1 ∧ b_out * a_out ≠ 1 := by + sorry + +end OAI.KaplanskyCounterexample +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KaplanskyFinitelyPresented.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KaplanskyCounterexample.finitelyPresented_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kaplansky-finitely-presented/solution/closure.txt b/tasks/kaplansky-finitely-presented/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2b518507ac7596780498ecdffe2ed7dc98c0eb8b --- /dev/null +++ b/tasks/kaplansky-finitely-presented/solution/closure.txt @@ -0,0 +1,126 @@ +OAI.RingTheory.DirectFiniteness.AffineLines +OAI.RingTheory.DirectFiniteness.AlgebraicCriterion +OAI.RingTheory.DirectFiniteness.AlgebraicPacking +OAI.RingTheory.DirectFiniteness.Alteration +OAI.RingTheory.DirectFiniteness.AssignedDevelopment +OAI.RingTheory.DirectFiniteness.BalanceCoarsening +OAI.RingTheory.DirectFiniteness.BalanceDetachment +OAI.RingTheory.DirectFiniteness.BalanceObstruction +OAI.RingTheory.DirectFiniteness.BalanceRestriction +OAI.RingTheory.DirectFiniteness.BoundaryCycles +OAI.RingTheory.DirectFiniteness.BoundaryFilling +OAI.RingTheory.DirectFiniteness.BoundarySplitting +OAI.RingTheory.DirectFiniteness.CandidateBounds +OAI.RingTheory.DirectFiniteness.CandidateClassification +OAI.RingTheory.DirectFiniteness.CandidateCounting +OAI.RingTheory.DirectFiniteness.CandidateDependencies +OAI.RingTheory.DirectFiniteness.CandidateGeometry +OAI.RingTheory.DirectFiniteness.CandidateModel +OAI.RingTheory.DirectFiniteness.CandidateRelations +OAI.RingTheory.DirectFiniteness.CharacterFormulas +OAI.RingTheory.DirectFiniteness.CharacterIdempotents +OAI.RingTheory.DirectFiniteness.CharacterTwist +OAI.RingTheory.DirectFiniteness.ChosenCriterion +OAI.RingTheory.DirectFiniteness.CoordinateCharacters +OAI.RingTheory.DirectFiniteness.CycleFactorization +OAI.RingTheory.DirectFiniteness.CycleSplitting +OAI.RingTheory.DirectFiniteness.CycleSums +OAI.RingTheory.DirectFiniteness.CyclicLabels +OAI.RingTheory.DirectFiniteness.DetachmentGenus +OAI.RingTheory.DirectFiniteness.DiagramDeletion +OAI.RingTheory.DirectFiniteness.DiagramInsertion +OAI.RingTheory.DirectFiniteness.DiagramJoining +OAI.RingTheory.DirectFiniteness.DiagramObstruction +OAI.RingTheory.DirectFiniteness.DiagramReduction +OAI.RingTheory.DirectFiniteness.DirectionCompleteness +OAI.RingTheory.DirectFiniteness.DirectionFrame +OAI.RingTheory.DirectFiniteness.DirectionSpaces +OAI.RingTheory.DirectFiniteness.EulerBound +OAI.RingTheory.DirectFiniteness.EventLoad +OAI.RingTheory.DirectFiniteness.FieldExtensions +OAI.RingTheory.DirectFiniteness.FiniteAffine +OAI.RingTheory.DirectFiniteness.FiniteBlock +OAI.RingTheory.DirectFiniteness.FiniteGeneration +OAI.RingTheory.DirectFiniteness.FiniteParameters +OAI.RingTheory.DirectFiniteness.FinitePresentation +OAI.RingTheory.DirectFiniteness.FinitelyPresented +OAI.RingTheory.DirectFiniteness.FrameExistence +OAI.RingTheory.DirectFiniteness.FrameTransport +OAI.RingTheory.DirectFiniteness.GluedGroup +OAI.RingTheory.DirectFiniteness.GluedWords +OAI.RingTheory.DirectFiniteness.GroupEmbedding +OAI.RingTheory.DirectFiniteness.HNNPresentation +OAI.RingTheory.DirectFiniteness.HoleEvents +OAI.RingTheory.DirectFiniteness.HoleExistence +OAI.RingTheory.DirectFiniteness.HoleNumerics +OAI.RingTheory.DirectFiniteness.HoleSelection +OAI.RingTheory.DirectFiniteness.IncidenceCycles +OAI.RingTheory.DirectFiniteness.IncidenceDirections +OAI.RingTheory.DirectFiniteness.LabelSupport +OAI.RingTheory.DirectFiniteness.LexicographicOrder +OAI.RingTheory.DirectFiniteness.Main +OAI.RingTheory.DirectFiniteness.MatrixBlock +OAI.RingTheory.DirectFiniteness.Model +OAI.RingTheory.DirectFiniteness.ModelPartition +OAI.RingTheory.DirectFiniteness.MultiHNN +OAI.RingTheory.DirectFiniteness.OddTorsion +OAI.RingTheory.DirectFiniteness.OneCandidateCounting +OAI.RingTheory.DirectFiniteness.OpenDiagrams +OAI.RingTheory.DirectFiniteness.PackingFormulas +OAI.RingTheory.DirectFiniteness.Pairing +OAI.RingTheory.DirectFiniteness.ParameterBounds +OAI.RingTheory.DirectFiniteness.PartialPartition +OAI.RingTheory.DirectFiniteness.PartitionMerging +OAI.RingTheory.DirectFiniteness.PlanarBalance +OAI.RingTheory.DirectFiniteness.PlanarDiagrams +OAI.RingTheory.DirectFiniteness.PlaneOperators +OAI.RingTheory.DirectFiniteness.PrescribedData +OAI.RingTheory.DirectFiniteness.PrescribedDirections +OAI.RingTheory.DirectFiniteness.PrescribedFields +OAI.RingTheory.DirectFiniteness.PrescribedIncidence +OAI.RingTheory.DirectFiniteness.PrescribedOutputs +OAI.RingTheory.DirectFiniteness.PrescribedPairing +OAI.RingTheory.DirectFiniteness.PrescribedParameters +OAI.RingTheory.DirectFiniteness.PrescribedPresentation +OAI.RingTheory.DirectFiniteness.PrescribedSearch +OAI.RingTheory.DirectFiniteness.PrescribedSlots +OAI.RingTheory.DirectFiniteness.PrescribedSubfield +OAI.RingTheory.DirectFiniteness.PrimeCertificate +OAI.RingTheory.DirectFiniteness.ProductAlgebras +OAI.RingTheory.DirectFiniteness.QuotientField +OAI.RingTheory.DirectFiniteness.Rectangular +OAI.RingTheory.DirectFiniteness.ReducedWalks +OAI.RingTheory.DirectFiniteness.ReplacementGeometry +OAI.RingTheory.DirectFiniteness.ReplacementPolygon +OAI.RingTheory.DirectFiniteness.RibbonDetachment +OAI.RingTheory.DirectFiniteness.RibbonGeometry +OAI.RingTheory.DirectFiniteness.RibbonRestriction +OAI.RingTheory.DirectFiniteness.RibbonSplitting +OAI.RingTheory.DirectFiniteness.RibbonSums +OAI.RingTheory.DirectFiniteness.RibbonWheels +OAI.RingTheory.DirectFiniteness.ScalarFormulas +OAI.RingTheory.DirectFiniteness.ScalarWitnesses +OAI.RingTheory.DirectFiniteness.ShortIndependence +OAI.RingTheory.DirectFiniteness.ShortRelators +OAI.RingTheory.DirectFiniteness.SimplexBound +OAI.RingTheory.DirectFiniteness.SlabAssembly +OAI.RingTheory.DirectFiniteness.SlabAvoidance +OAI.RingTheory.DirectFiniteness.SlabEvents +OAI.RingTheory.DirectFiniteness.SlabHoleEvents +OAI.RingTheory.DirectFiniteness.SlabKeys +OAI.RingTheory.DirectFiniteness.SlabLoad +OAI.RingTheory.DirectFiniteness.SlabNumerics +OAI.RingTheory.DirectFiniteness.SlabPartition +OAI.RingTheory.DirectFiniteness.SlabPatch +OAI.RingTheory.DirectFiniteness.TradeDegree +OAI.RingTheory.DirectFiniteness.TradeFamily +OAI.RingTheory.DirectFiniteness.TradeGirth +OAI.RingTheory.DirectFiniteness.TradeLines +OAI.RingTheory.DirectFiniteness.TradePolygon +OAI.RingTheory.DirectFiniteness.TranslatedUnits +OAI.RingTheory.DirectFiniteness.VertexMerging +OAI.RingTheory.DirectFiniteness.WeightTransfer +OAI.RingTheory.DirectFiniteness.WordCycles +OAI.RingTheory.DirectFiniteness.WordDiagrams +OAI.RingTheory.DirectFiniteness.WordReduction +OAI.RingTheory.DirectFiniteness.WordWheels diff --git a/tasks/kaplansky-finitely-presented/solution/reference.py b/tasks/kaplansky-finitely-presented/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kaplansky-finitely-presented/solution/solve.sh b/tasks/kaplansky-finitely-presented/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e5d28ac851a27e0efc7cdb0b19168fa3e26e2e53 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KaplanskyFinitelyPresented, i.e. module OAI.RingTheory.DirectFiniteness.FinitelyPresented and the +# 126 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.DirectFiniteness.FinitelyPresented /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KaplanskyFinitelyPresented" diff --git a/tasks/kaplansky-finitely-presented/task.toml b/tasks/kaplansky-finitely-presented/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f37d227cd731f1ea392bcaa7bcbe3f68384f9c02 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kaplansky-finitely-presented" +version = "1.0.0" +description = "Prove KaplanskyFinitelyPresented (openai/math family 197: Nonsofic groups and group-ring counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KaplanskyFinitelyPresented.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KaplanskyFinitelyPresented" +family = "197" +family_title = "Nonsofic groups and group-ring counterexamples" +subject = "Algebra" +theorems = ["OAI.KaplanskyCounterexample.finitelyPresented_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.DirectFiniteness.FinitelyPresented" +reference_modules = 126 +reference_lean_bytes = 556097 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1470 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12200 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kaplansky-finitely-presented/tests/Challenge.lean b/tasks/kaplansky-finitely-presented/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5eb5f9cacc7b82fa773f498285cd0c2b9806d972 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/tests/Challenge.lean @@ -0,0 +1,14 @@ +import Mathlib + +namespace OAI.KaplanskyCounterexample + +/-- A finite characteristic-two field and a finitely presented group with odd-prime +order torsion give a counterexample to direct finiteness (paper, Theorem 1.1). -/ +theorem finitelyPresented_counterexample : + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K 2), + ∃ (G : Type) (_ : Group G) (_ : Group.IsFinitelyPresented G), + (∃ (ℓ : ℕ) (_ : ℓ.Prime) (_ : Odd ℓ) (g : G), orderOf g = ℓ) ∧ + ∃ a_out b_out : MonoidAlgebra K G, a_out * b_out = 1 ∧ b_out * a_out ≠ 1 := by + sorry + +end OAI.KaplanskyCounterexample diff --git a/tasks/kaplansky-finitely-presented/tests/grade.py b/tasks/kaplansky-finitely-presented/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kaplansky-finitely-presented/tests/task.json b/tasks/kaplansky-finitely-presented/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..751e5fd07bb16939eff19f60f0a1c403d5714de4 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KaplanskyFinitelyPresented", + "comparator": { + "theorem_names": [ + "OAI.KaplanskyCounterexample.finitelyPresented_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11300 +} \ No newline at end of file diff --git a/tasks/kaplansky-finitely-presented/tests/test.sh b/tasks/kaplansky-finitely-presented/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kaplansky-finitely-presented/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kaplansky-quasitrace/environment/Dockerfile b/tasks/kaplansky-quasitrace/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kaplansky-quasitrace/environment/fetch_mathlib.sh b/tasks/kaplansky-quasitrace/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kaplansky-quasitrace/environment/lake-manifest.json b/tasks/kaplansky-quasitrace/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kaplansky-quasitrace/environment/lakefile.lean b/tasks/kaplansky-quasitrace/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kaplansky-quasitrace/environment/lean_setup.sh b/tasks/kaplansky-quasitrace/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kaplansky-quasitrace/environment/pack_submission.py b/tasks/kaplansky-quasitrace/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kaplansky-quasitrace/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kaplansky-quasitrace/instruction.md b/tasks/kaplansky-quasitrace/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a1dbe96bdca2cb7aaf0c720a34eb48e073598941 --- /dev/null +++ b/tasks/kaplansky-quasitrace/instruction.md @@ -0,0 +1,106 @@ +# openai/math challenge `KaplanskyQuasitrace` (family 294) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 294 of the release, *A counterexample to Kaplansky's quasitrace conjecture* +(Operator algebras). The family as a whole: Disproves Kaplansky's quasitrace conjecture by constructing a separable unital complex $C^*$-algebra admitting normalized $2$-quasitraces, all of which are nonadditive. As a consequence, two unital simple stably finite $C^*$-algebras can have a properly infinite minimal tensor product, with one factor $C_r^*(\mathbb F_2)$. + +The challenge is `KaplanskyQuasitrace`, also at `/opt/openai-math/challenges/KaplanskyQuasitrace.lean`: + +```lean +import Mathlib.Algebra.Order.Star.Basic +import Mathlib.Analysis.CStarAlgebra.Classes +import Mathlib.Analysis.CStarAlgebra.CStarMatrix + +namespace OAI + +noncomputable section + +open scoped ComplexOrder + +namespace Kaplansky + +variable {A : Type*} [CStarAlgebra A] + +structure OneQuasitrace (A : Type*) [CStarAlgebra A] where + toFun : A → ℂ + square_nonneg : ∀ x, 0 ≤ toFun (star x * x) + square_swap : ∀ x, toFun (star x * x) = toFun (x * star x) + real_imag : ∀ h k, IsSelfAdjoint h → IsSelfAdjoint k → + toFun (h + Complex.I • k) = toFun h + Complex.I * toFun k + abelian_linear : ∀ S : NonUnitalStarSubalgebra ℂ A, + IsClosed (S : Set A) → (∀ x y : S, x * y = y * x) → + ∃ f : S →ₗ[ℂ] ℂ, ∀ x : S, f x = toFun x + +instance : CoeFun (OneQuasitrace A) (fun _ => A → ℂ) := ⟨OneQuasitrace.toFun⟩ + +def OneQuasitrace.Normalized (τ : OneQuasitrace A) : Prop := τ 1 = 1 + +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +def upperLeft (a : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix fun i j => if i = 0 ∧ j = 0 then a else 0 + +def OneQuasitrace.IsTwo (τ : OneQuasitrace A) : Prop := + ∃ σ : OneQuasitrace (CStarMatrix (Fin 2) (Fin 2) A), ∀ a, σ (upperLeft a) = τ a + +def PositiveContraction (a : A) : Prop := (∃ x, a = star x * x) ∧ ‖a‖ ≤ 1 + +def MainTarget : Prop := + ∃ (A : Type) (inst : CStarAlgebra A), + letI := inst + TopologicalSpace.SeparableSpace A ∧ + (∃ τ : OneQuasitrace A, τ.Normalized ∧ τ.IsTwo) ∧ + ∃ a b : A, PositiveContraction a ∧ PositiveContraction b ∧ + ∀ τ : OneQuasitrace A, τ.Normalized → τ.IsTwo → + (1 : ℝ) / 144 ≤ (τ (a+b) - τ a - τ b).re + +theorem kaplansky_quasitrace_counterexample : MainTarget := by + sorry + +end Kaplansky + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KaplanskyQuasitrace.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Kaplansky.kaplansky_quasitrace_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kaplansky-quasitrace/solution/closure.txt b/tasks/kaplansky-quasitrace/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3c5d66f200515fba806288c7897cb67cf849ae3 --- /dev/null +++ b/tasks/kaplansky-quasitrace/solution/closure.txt @@ -0,0 +1,123 @@ +OAI.Algebra.OrderedStates.RationalCone +OAI.Algebra.OrderedStates.Semigroup +OAI.AlgebraicTopology.IntegralHomology.AffineAvoidance +OAI.AlgebraicTopology.IntegralHomology.Compactification +OAI.AlgebraicTopology.IntegralHomology.Connected +OAI.AlgebraicTopology.IntegralHomology.Equivalence +OAI.AlgebraicTopology.IntegralHomology.Excision +OAI.AlgebraicTopology.IntegralHomology.FiniteCover +OAI.AlgebraicTopology.IntegralHomology.FrameNormalization +OAI.AlgebraicTopology.IntegralHomology.GraphCover +OAI.AlgebraicTopology.IntegralHomology.GraphNormalization +OAI.AlgebraicTopology.IntegralHomology.HyperplaneFiber +OAI.AlgebraicTopology.IntegralHomology.HyperplaneLocal +OAI.AlgebraicTopology.IntegralHomology.LineNormalization +OAI.AlgebraicTopology.IntegralHomology.MayerVietoris +OAI.AlgebraicTopology.IntegralHomology.Obstruction +OAI.AlgebraicTopology.IntegralHomology.OpenUnion +OAI.AlgebraicTopology.IntegralHomology.Product +OAI.AlgebraicTopology.IntegralHomology.ProductCover +OAI.AlgebraicTopology.IntegralHomology.ProjectiveClass +OAI.AlgebraicTopology.IntegralHomology.ProjectiveLocal +OAI.AlgebraicTopology.IntegralHomology.ProjectivePuncture +OAI.AlgebraicTopology.IntegralHomology.Quotient +OAI.AlgebraicTopology.IntegralHomology.Relative +OAI.AlgebraicTopology.IntegralHomology.Sections +OAI.AlgebraicTopology.IntegralHomology.Simplex +OAI.AlgebraicTopology.IntegralHomology.SmallChains +OAI.AlgebraicTopology.IntegralHomology.SmallExcision +OAI.AlgebraicTopology.IntegralHomology.Smallness +OAI.AlgebraicTopology.IntegralHomology.Sphere +OAI.AlgebraicTopology.IntegralHomology.Subdivision +OAI.AlgebraicTopology.IntegralHomology.Thom +OAI.AlgebraicTopology.IntegralHomology.TupleChains +OAI.Analysis.Cuntz.Commutative +OAI.Analysis.Cuntz.Comparison +OAI.Analysis.Cuntz.Content +OAI.Analysis.Cuntz.Cutoff +OAI.Analysis.Cuntz.Distribution +OAI.Analysis.Cuntz.Measure +OAI.Analysis.Cuntz.Monoid +OAI.Analysis.Cuntz.Quasitrace +OAI.Analysis.Cuntz.Regularization +OAI.Analysis.Cuntz.RegularizedState +OAI.Analysis.Cuntz.Spectral +OAI.Analysis.Cuntz.SquareCutoff +OAI.Analysis.Cuntz.Squares +OAI.Analysis.Cuntz.State +OAI.Analysis.Cuntz.Translation +OAI.Analysis.Kaplansky.ActualAlgebra +OAI.Analysis.Kaplansky.BundlePolynomials +OAI.Analysis.Kaplansky.BundleWords +OAI.Analysis.Kaplansky.Main +OAI.Analysis.Kaplansky.MatrixImage +OAI.Analysis.Kaplansky.MatrixTest +OAI.Analysis.Kaplansky.Operators +OAI.Analysis.Kaplansky.PolynomialTest +OAI.Analysis.Kaplansky.Polynomials +OAI.Analysis.Kaplansky.Products +OAI.Analysis.Kaplansky.Shift +OAI.Analysis.Kaplansky.ShiftAlgebra +OAI.Analysis.Kaplansky.TestAlgebra +OAI.Analysis.Kaplansky.Words +OAI.Analysis.MatrixScaling.Bounds +OAI.Analysis.MatrixScaling.Canonical +OAI.Analysis.MatrixScaling.Continuous +OAI.Analysis.MatrixScaling.Critical +OAI.Analysis.MatrixScaling.Determinant +OAI.Analysis.MatrixScaling.Expansion +OAI.Analysis.MatrixScaling.Geodesic +OAI.Analysis.MatrixScaling.Gram +OAI.Analysis.MatrixScaling.Minimizer +OAI.Analysis.MatrixScaling.Spectrum +OAI.Analysis.Quasitrace.Basic +OAI.Analysis.Quasitrace.Compactness +OAI.Analysis.Quasitrace.Defect +OAI.Analysis.Quasitrace.Extension +OAI.Analysis.Quasitrace.Infiniteness +OAI.Analysis.Quasitrace.Matrix +OAI.Analysis.Quasitrace.Order +OAI.Geometry.BundleTests.Assembly +OAI.Geometry.BundleTests.Base +OAI.Geometry.BundleTests.Bundles +OAI.Geometry.BundleTests.Complement +OAI.Geometry.BundleTests.Multiplicities +OAI.Geometry.BundleTests.Normalization +OAI.Geometry.BundleTests.Normalized +OAI.Geometry.BundleTests.Obstruction +OAI.Geometry.BundleTests.Retained +OAI.Geometry.BundleTests.Sequence +OAI.Geometry.BundleTests.Smooth +OAI.Geometry.BundleTests.Twisted +OAI.Geometry.ComplexBundle.Avoidance +OAI.Geometry.ComplexBundle.BundleIncidence +OAI.Geometry.ComplexBundle.Complement +OAI.Geometry.ComplexBundle.Coordinates +OAI.Geometry.ComplexBundle.CoordinatesMetric +OAI.Geometry.ComplexBundle.DirectSum +OAI.Geometry.ComplexBundle.Evaluation +OAI.Geometry.ComplexBundle.Frames +OAI.Geometry.ComplexBundle.Grassmann +OAI.Geometry.ComplexBundle.GrassmannManifold +OAI.Geometry.ComplexBundle.Hom +OAI.Geometry.ComplexBundle.Hyperplane +OAI.Geometry.ComplexBundle.HyperplaneProduct +OAI.Geometry.ComplexBundle.Incidence +OAI.Geometry.ComplexBundle.Kernel +OAI.Geometry.ComplexBundle.LineStage +OAI.Geometry.ComplexBundle.Maps +OAI.Geometry.ComplexBundle.OpenIncidence +OAI.Geometry.ComplexBundle.Orthonormal +OAI.Geometry.ComplexBundle.PointExpansion +OAI.Geometry.ComplexBundle.Projection +OAI.Geometry.ComplexBundle.ProjectionBundle +OAI.Geometry.ComplexBundle.Projective +OAI.Geometry.ComplexBundle.Pullback +OAI.Geometry.ComplexBundle.RealModel +OAI.Geometry.ComplexBundle.Replacement +OAI.Geometry.ComplexBundle.Sections +OAI.Geometry.ComplexBundle.SmoothLine +OAI.Geometry.ComplexBundle.StageMaps +OAI.Geometry.ComplexBundle.Tensor +OAI.Geometry.ComplexBundle.Tuples +OAI.Geometry.ComplexBundle.ZeroSign diff --git a/tasks/kaplansky-quasitrace/solution/reference.py b/tasks/kaplansky-quasitrace/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kaplansky-quasitrace/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kaplansky-quasitrace/solution/solve.sh b/tasks/kaplansky-quasitrace/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c98d6b48abb92b1c03250782a58eeeb47f6625be --- /dev/null +++ b/tasks/kaplansky-quasitrace/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KaplanskyQuasitrace, i.e. module OAI.Analysis.Kaplansky.Main and the +# 123 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Kaplansky.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KaplanskyQuasitrace" diff --git a/tasks/kaplansky-quasitrace/task.toml b/tasks/kaplansky-quasitrace/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7da866cddbe4e68a7282a95a7d32fa145c03bc2e --- /dev/null +++ b/tasks/kaplansky-quasitrace/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kaplansky-quasitrace" +version = "1.0.0" +description = "Prove KaplanskyQuasitrace (openai/math family 294: A counterexample to Kaplansky's quasitrace conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KaplanskyQuasitrace.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KaplanskyQuasitrace" +family = "294" +family_title = "A counterexample to Kaplansky's quasitrace conjecture" +subject = "Operator algebras" +theorems = ["OAI.Kaplansky.kaplansky_quasitrace_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Kaplansky.Main" +reference_modules = 123 +reference_lean_bytes = 1501004 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 993 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13050 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kaplansky-quasitrace/tests/Challenge.lean b/tasks/kaplansky-quasitrace/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..00e9ac6caf61bb945684394040ecafa76ce9574d --- /dev/null +++ b/tasks/kaplansky-quasitrace/tests/Challenge.lean @@ -0,0 +1,55 @@ +import Mathlib.Algebra.Order.Star.Basic +import Mathlib.Analysis.CStarAlgebra.Classes +import Mathlib.Analysis.CStarAlgebra.CStarMatrix + +namespace OAI + +noncomputable section + +open scoped ComplexOrder + +namespace Kaplansky + +variable {A : Type*} [CStarAlgebra A] + +structure OneQuasitrace (A : Type*) [CStarAlgebra A] where + toFun : A → ℂ + square_nonneg : ∀ x, 0 ≤ toFun (star x * x) + square_swap : ∀ x, toFun (star x * x) = toFun (x * star x) + real_imag : ∀ h k, IsSelfAdjoint h → IsSelfAdjoint k → + toFun (h + Complex.I • k) = toFun h + Complex.I * toFun k + abelian_linear : ∀ S : NonUnitalStarSubalgebra ℂ A, + IsClosed (S : Set A) → (∀ x y : S, x * y = y * x) → + ∃ f : S →ₗ[ℂ] ℂ, ∀ x : S, f x = toFun x + +instance : CoeFun (OneQuasitrace A) (fun _ => A → ℂ) := ⟨OneQuasitrace.toFun⟩ + +def OneQuasitrace.Normalized (τ : OneQuasitrace A) : Prop := τ 1 = 1 + +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +def upperLeft (a : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix fun i j => if i = 0 ∧ j = 0 then a else 0 + +def OneQuasitrace.IsTwo (τ : OneQuasitrace A) : Prop := + ∃ σ : OneQuasitrace (CStarMatrix (Fin 2) (Fin 2) A), ∀ a, σ (upperLeft a) = τ a + +def PositiveContraction (a : A) : Prop := (∃ x, a = star x * x) ∧ ‖a‖ ≤ 1 + +def MainTarget : Prop := + ∃ (A : Type) (inst : CStarAlgebra A), + letI := inst + TopologicalSpace.SeparableSpace A ∧ + (∃ τ : OneQuasitrace A, τ.Normalized ∧ τ.IsTwo) ∧ + ∃ a b : A, PositiveContraction a ∧ PositiveContraction b ∧ + ∀ τ : OneQuasitrace A, τ.Normalized → τ.IsTwo → + (1 : ℝ) / 144 ≤ (τ (a+b) - τ a - τ b).re + +theorem kaplansky_quasitrace_counterexample : MainTarget := by + sorry + +end Kaplansky + +end + +end OAI diff --git a/tasks/kaplansky-quasitrace/tests/grade.py b/tasks/kaplansky-quasitrace/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kaplansky-quasitrace/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kaplansky-quasitrace/tests/task.json b/tasks/kaplansky-quasitrace/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a29568b57486c92c5762327ed84e7ee0d27a4523 --- /dev/null +++ b/tasks/kaplansky-quasitrace/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KaplanskyQuasitrace", + "comparator": { + "theorem_names": [ + "OAI.Kaplansky.kaplansky_quasitrace_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12150 +} \ No newline at end of file diff --git a/tasks/kaplansky-quasitrace/tests/test.sh b/tasks/kaplansky-quasitrace/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kaplansky-quasitrace/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kaplansky-stable-finiteness/environment/Dockerfile b/tasks/kaplansky-stable-finiteness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kaplansky-stable-finiteness/environment/fetch_mathlib.sh b/tasks/kaplansky-stable-finiteness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kaplansky-stable-finiteness/environment/lake-manifest.json b/tasks/kaplansky-stable-finiteness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kaplansky-stable-finiteness/environment/lakefile.lean b/tasks/kaplansky-stable-finiteness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kaplansky-stable-finiteness/environment/lean_setup.sh b/tasks/kaplansky-stable-finiteness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kaplansky-stable-finiteness/environment/pack_submission.py b/tasks/kaplansky-stable-finiteness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kaplansky-stable-finiteness/instruction.md b/tasks/kaplansky-stable-finiteness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89413ac858a75eed6ecc49db2b0a2e2b78bf5f87 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/instruction.md @@ -0,0 +1,298 @@ +# openai/math challenge `KaplanskyStableFiniteness` (family 294) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 294 of the release, *A counterexample to Kaplansky's quasitrace conjecture* +(Operator algebras). The family as a whole: Disproves Kaplansky's quasitrace conjecture by constructing a separable unital complex $C^*$-algebra admitting normalized $2$-quasitraces, all of which are nonadditive. As a consequence, two unital simple stably finite $C^*$-algebras can have a properly infinite minimal tensor product, with one factor $C_r^*(\mathbb F_2)$. + +The challenge is `KaplanskyStableFiniteness`, also at `/opt/openai-math/challenges/KaplanskyStableFiniteness.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + + +namespace KaplanskyConsequences +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +namespace Regular +variable {ι : Type*} {H : Type*} [NormedAddCommGroup H] + +abbrev HilbertSum (ι H : Type*) [NormedAddCommGroup H] := lp (fun _ : ι => H) 2 + +lemma reindex_mem (e : ι ≃ ι) (x : HilbertSum ι H) : + Memℓp (fun i => x (e i)) 2 := by + apply memℓp_gen + exact e.summable_iff.2 ((memℓp_gen_iff (by norm_num)).1 (lp.memℓp x)) + +variable [InnerProductSpace ℂ H] + +def reindex (e : ι ≃ ι) : HilbertSum ι H ≃ₗᵢ[ℂ] HilbertSum ι H where + toFun x := ⟨fun i => x (e.symm i), reindex_mem e.symm x⟩ + invFun x := ⟨fun i => x (e i), reindex_mem e x⟩ + left_inv x := by ext; simp + right_inv x := by ext; simp + map_add' x y := by ext; rfl + map_smul' r x := by ext; rfl + norm_map' x := by + rw [lp.norm_eq_tsum_rpow (by norm_num),lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.symm.tsum_eq (fun i => ‖x i‖ ^ (2 : ℝ≥0∞).toReal) + +@[simp] lemma reindex_apply (e : ι ≃ ι) (x : HilbertSum ι H) (i : ι) : + reindex e x i = x (e.symm i) := rfl + +variable {G : Type*} [Group G] + +def left (g : G) : HilbertSum G H →L[ℂ] HilbertSum G H := + (reindex (Equiv.mulLeft g)).toLinearIsometry.toContinuousLinearMap + +@[simp] lemma left_apply (g h : G) (x : HilbertSum G H) : left g x h = x (g⁻¹*h) := rfl + +lemma left_one : left (H := H) (1 : G) = 1 := by ext x h; simp +lemma left_mul (g h : G) : left (H := H) (g*h) = left g * left h := by + ext x k + simp [mul_assoc] + +variable [CompleteSpace H] + +lemma left_star (g : G) : star (left (H := H) g) = left g⁻¹ := by + symm + apply (ContinuousLinearMap.eq_adjoint_iff _ _).2 + intro x y + change inner ℂ (left g⁻¹ x) y = inner ℂ x (left g y) + rw [lp.inner_eq_tsum,lp.inner_eq_tsum] + simpa [left_apply,mul_assoc] using + (Equiv.mulLeft g).tsum_eq (fun i => inner ℂ (x i) (y (g⁻¹*i))) + +def Algebra (G : Type*) [Group G] : StarSubalgebra ℂ (HilbertSum G ℂ →L[ℂ] HilbertSum G ℂ) := + (StarAlgebra.adjoin ℂ (Set.range (left (H := ℂ) (G := G)))).topologicalClosure + +instance : IsClosed (Algebra G : Set (HilbertSum G ℂ →L[ℂ] HilbertSum G ℂ)) := + StarSubalgebra.isClosed_topologicalClosure _ + +instance : CStarAlgebra (Algebra G) := inferInstance + +def generator (g : G) : Algebra G := + ⟨left g,StarSubalgebra.le_topologicalClosure _ + (StarAlgebra.subset_adjoin ℂ _ ⟨g,rfl⟩)⟩ + +end Regular +end KaplanskyConsequences + + +namespace KaplanskyConsequences.Regular +abbrev F2 := FreeGroup (Fin 2) + + +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +attribute [local instance] Classical.propDecidable +variable {G H : Type*} [Group G] [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] + +def diagonal (T : H →L[ℂ] H) : HilbertSum G H →L[ℂ] HilbertSum G H := + lp.mapCLM 2 (fun _ => T) (norm_nonneg T) (fun _ => le_rfl) + +end KaplanskyConsequences.Regular + + +namespace Kaplansky + +section + +section +open scoped ComplexOrder IsMulCommutative + + +variable {A : Type*} [CStarAlgebra A] + +structure OneQuasitrace (A : Type*) [CStarAlgebra A] where + toFun : A → ℂ + square_nonneg : ∀ x, 0 ≤ toFun (star x * x) + square_swap : ∀ x, toFun (star x * x) = toFun (x * star x) + real_imag : ∀ h k, IsSelfAdjoint h → IsSelfAdjoint k → + toFun (h + Complex.I • k) = toFun h + Complex.I * toFun k + abelian_linear : ∀ S : NonUnitalStarSubalgebra ℂ A, + IsClosed (S : Set A) → (∀ x y : S, x * y = y * x) → + ∃ f : S →ₗ[ℂ] ℂ, ∀ x : S, f x = toFun x + +instance : CoeFun (OneQuasitrace A) (fun _ => A → ℂ) := ⟨OneQuasitrace.toFun⟩ + +def OneQuasitrace.Normalized (τ : OneQuasitrace A) : Prop := τ 1 = 1 + +end + + +open scoped ComplexOrder CStarAlgebra +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] + +def ProperlyInfinite (A : Type*) [CStarAlgebra A] : Prop := + ∃ s t : A, star s*s = 1 ∧ star t*t = 1 ∧ star s*t = 0 + +end + + +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] + +def upperLeft (a : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix fun i j => if i = 0 ∧ j = 0 then a else 0 + +def OneQuasitrace.IsTwo (τ : OneQuasitrace A) : Prop := + ∃ σ : OneQuasitrace (CStarMatrix (Fin 2) (Fin 2) A), ∀ a, σ (upperLeft a) = τ a + +end Kaplansky + + +namespace KaplanskyConsequences + +section +open scoped ComplexOrder +open Metric Topology +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +structure ClosedStarIdeal (A : Type*) [CStarAlgebra A] extends NonUnitalStarSubalgebra ℂ A where + mul_mem_left : ∀ (a b : A), b ∈ toNonUnitalStarSubalgebra → a * b ∈ toNonUnitalStarSubalgebra + mul_mem_right : ∀ (a b : A), a ∈ toNonUnitalStarSubalgebra → a * b ∈ toNonUnitalStarSubalgebra + closed : IsClosed (toNonUnitalStarSubalgebra : Set A) + +end + + +open scoped ComplexOrder +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +def StablyFinite (A : Type*) [CStarAlgebra A] : Prop := + ∀ n : ℕ, 0 < n → ∀ v : CStarMatrix (Fin n) (Fin n) A, + star v * v = 1 → v * star v = 1 + +structure TracialState (A : Type*) [CStarAlgebra A] where + functional : A →ₚ[ℂ] ℂ + normalized : functional 1 = 1 + tracial : ∀ a b, functional (a * b) = functional (b * a) + +def TraceFreeStablyFinite : Prop := + ∃ (A : Type) (inst : CStarAlgebra A), + letI := inst + Nontrivial A ∧ TopologicalSpace.SeparableSpace A ∧ StablyFinite A ∧ + IsEmpty (TracialState A) + +end KaplanskyConsequences + +namespace KaplanskyConsequences.Regular +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +attribute [local instance] Classical.propDecidable +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] +variable {G H : Type*} [Group G] [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def tensorAlgebra (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : + StarSubalgebra ℂ (HilbertSum G H →L[ℂ] HilbertSum G H) := + (StarAlgebra.adjoin ℂ (Set.range (fun a => diagonal (G:=G) (ρ a)) ∪ Set.range (left (G:=G) (H:=H)))).topologicalClosure + +instance (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : + IsClosed (tensorAlgebra (G:=G) ρ : Set (HilbertSum G H →L[ℂ] HilbertSum G H)) := + StarSubalgebra.isClosed_topologicalClosure _ +instance (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : CStarAlgebra (tensorAlgebra (G:=G) ρ) := inferInstance + +end KaplanskyConsequences.Regular + +namespace KaplanskyConsequences + +section + +section +open Kaplansky Regular + +def ReducedQuasitraceLoss : Prop := + ∃ (B : Type) (instB : CStarAlgebra B), + letI := instB + Nontrivial B ∧ TopologicalSpace.SeparableSpace B ∧ + (∃ τ : OneQuasitrace B, τ.Normalized ∧ τ.IsTwo) ∧ + ∃ (H : Type) (instH : NormedAddCommGroup H) (innerH : InnerProductSpace ℂ H), + letI := instH + letI := innerH + ∃ (completeH : CompleteSpace H), + letI := completeH + ∃ ρ : B →⋆ₐ[ℂ] (H →L[ℂ] H), Function.Injective ρ ∧ + ProperlyInfinite (tensorAlgebra (G:=F2) ρ) ∧ + ¬ ∃ τ : OneQuasitrace (tensorAlgebra (G:=F2) ρ), τ.Normalized ∧ τ.IsTwo +end + +open Kaplansky Regular + +def CStarSimple (A : Type*) [CStarAlgebra A] : Prop := + ∀ I : ClosedStarIdeal A, + (∀ a : A, a ∈ I.toNonUnitalStarSubalgebra → a = 0) ∨ + (∀ a : A, a ∈ I.toNonUnitalStarSubalgebra) + +def SimpleStableTensorCounterexample : Prop := + CStarSimple (Algebra F2) ∧ StablyFinite (Algebra F2) ∧ + ∃ (M : Type) (instM : CStarAlgebra M), + letI := instM + Nontrivial M ∧ CStarSimple M ∧ StablyFinite M ∧ + ∃ (H : Type) (instH : NormedAddCommGroup H) (innerH : InnerProductSpace ℂ H), + letI := instH + letI := innerH + ∃ (completeH : CompleteSpace H), + letI := completeH + ∃ ρ : M →⋆ₐ[ℂ] (H →L[ℂ] H), Function.Injective ρ ∧ + ProperlyInfinite (tensorAlgebra (G:=F2) ρ) +end + + +def StableFinitenessBundle : Prop := + SimpleStableTensorCounterexample ∧ ReducedQuasitraceLoss ∧ TraceFreeStablyFinite + +theorem stable_finiteness_bundle : StableFinitenessBundle := by + sorry + +end KaplanskyConsequences + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KaplanskyStableFiniteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KaplanskyConsequences.stable_finiteness_bundle` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kaplansky-stable-finiteness/solution/closure.txt b/tasks/kaplansky-stable-finiteness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4782665a8806077b6a4d81420896d971a2258010 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/solution/closure.txt @@ -0,0 +1,181 @@ +OAI.Algebra.OrderedStates.RationalCone +OAI.Algebra.OrderedStates.Semigroup +OAI.AlgebraicTopology.IntegralHomology.AffineAvoidance +OAI.AlgebraicTopology.IntegralHomology.Compactification +OAI.AlgebraicTopology.IntegralHomology.Connected +OAI.AlgebraicTopology.IntegralHomology.Equivalence +OAI.AlgebraicTopology.IntegralHomology.Excision +OAI.AlgebraicTopology.IntegralHomology.FiniteCover +OAI.AlgebraicTopology.IntegralHomology.FrameNormalization +OAI.AlgebraicTopology.IntegralHomology.GraphCover +OAI.AlgebraicTopology.IntegralHomology.GraphNormalization +OAI.AlgebraicTopology.IntegralHomology.HyperplaneFiber +OAI.AlgebraicTopology.IntegralHomology.HyperplaneLocal +OAI.AlgebraicTopology.IntegralHomology.LineNormalization +OAI.AlgebraicTopology.IntegralHomology.MayerVietoris +OAI.AlgebraicTopology.IntegralHomology.Obstruction +OAI.AlgebraicTopology.IntegralHomology.OpenUnion +OAI.AlgebraicTopology.IntegralHomology.Product +OAI.AlgebraicTopology.IntegralHomology.ProductCover +OAI.AlgebraicTopology.IntegralHomology.ProjectiveClass +OAI.AlgebraicTopology.IntegralHomology.ProjectiveLocal +OAI.AlgebraicTopology.IntegralHomology.ProjectivePuncture +OAI.AlgebraicTopology.IntegralHomology.Quotient +OAI.AlgebraicTopology.IntegralHomology.Relative +OAI.AlgebraicTopology.IntegralHomology.Sections +OAI.AlgebraicTopology.IntegralHomology.Simplex +OAI.AlgebraicTopology.IntegralHomology.SmallChains +OAI.AlgebraicTopology.IntegralHomology.SmallExcision +OAI.AlgebraicTopology.IntegralHomology.Smallness +OAI.AlgebraicTopology.IntegralHomology.Sphere +OAI.AlgebraicTopology.IntegralHomology.Subdivision +OAI.AlgebraicTopology.IntegralHomology.Thom +OAI.AlgebraicTopology.IntegralHomology.TupleChains +OAI.Analysis.Cuntz.Commutative +OAI.Analysis.Cuntz.Comparison +OAI.Analysis.Cuntz.Content +OAI.Analysis.Cuntz.Cutoff +OAI.Analysis.Cuntz.Distribution +OAI.Analysis.Cuntz.Measure +OAI.Analysis.Cuntz.Monoid +OAI.Analysis.Cuntz.Quasitrace +OAI.Analysis.Cuntz.Regularization +OAI.Analysis.Cuntz.RegularizedState +OAI.Analysis.Cuntz.Spectral +OAI.Analysis.Cuntz.SquareCutoff +OAI.Analysis.Cuntz.Squares +OAI.Analysis.Cuntz.State +OAI.Analysis.Cuntz.Translation +OAI.Analysis.Kaplansky.ActualAlgebra +OAI.Analysis.Kaplansky.BundlePolynomials +OAI.Analysis.Kaplansky.BundleWords +OAI.Analysis.Kaplansky.Main +OAI.Analysis.Kaplansky.MatrixImage +OAI.Analysis.Kaplansky.MatrixTest +OAI.Analysis.Kaplansky.Operators +OAI.Analysis.Kaplansky.PolynomialTest +OAI.Analysis.Kaplansky.Polynomials +OAI.Analysis.Kaplansky.Products +OAI.Analysis.Kaplansky.Quotient.ClosedStarQuotient +OAI.Analysis.Kaplansky.Quotient.Extraction +OAI.Analysis.Kaplansky.Quotient.FiniteQuotient +OAI.Analysis.Kaplansky.Quotient.MatrixKernel +OAI.Analysis.Kaplansky.Quotient.MaximalClosedIdeal +OAI.Analysis.Kaplansky.Quotient.NullIdeal +OAI.Analysis.Kaplansky.Quotient.QuotientStable +OAI.Analysis.Kaplansky.Quotient.TracePullback +OAI.Analysis.Kaplansky.Regular.CStarEstimates +OAI.Analysis.Kaplansky.Regular.FreeEstimates +OAI.Analysis.Kaplansky.Regular.FreeFamily +OAI.Analysis.Kaplansky.Regular.FreeNormal +OAI.Analysis.Kaplansky.Regular.FreeWord +OAI.Analysis.Kaplansky.Regular.HilbertTensorModel +OAI.Analysis.Kaplansky.Regular.NearGram +OAI.Analysis.Kaplansky.Regular.PowersAverageBound +OAI.Analysis.Kaplansky.Regular.PowersAverages +OAI.Analysis.Kaplansky.Regular.PowersAveraging +OAI.Analysis.Kaplansky.Regular.PowersOperators +OAI.Analysis.Kaplansky.Regular.PowersPartition +OAI.Analysis.Kaplansky.Regular.PowersSimple +OAI.Analysis.Kaplansky.Regular.ReducedPolynomials +OAI.Analysis.Kaplansky.Regular.ReducedStable +OAI.Analysis.Kaplansky.Regular.ReducedTensor +OAI.Analysis.Kaplansky.Regular.ReducedTrace +OAI.Analysis.Kaplansky.Regular.RegularOperators +OAI.Analysis.Kaplansky.Regular.SlotEstimates +OAI.Analysis.Kaplansky.Shift +OAI.Analysis.Kaplansky.ShiftAlgebra +OAI.Analysis.Kaplansky.StableFiniteness +OAI.Analysis.Kaplansky.StableFiniteness.Definitions +OAI.Analysis.Kaplansky.StableFiniteness.FaithfulRepresentation +OAI.Analysis.Kaplansky.StableFiniteness.QuasitraceLoss +OAI.Analysis.Kaplansky.StableFiniteness.ScalarTower +OAI.Analysis.Kaplansky.StableFiniteness.SimpleAmbient +OAI.Analysis.Kaplansky.StableFiniteness.SimpleReduction +OAI.Analysis.Kaplansky.StableFiniteness.SimpleRepresentation +OAI.Analysis.Kaplansky.StableFiniteness.SimpleTensor +OAI.Analysis.Kaplansky.StableFiniteness.StateExists +OAI.Analysis.Kaplansky.StableFiniteness.TraceFree +OAI.Analysis.Kaplansky.StableFiniteness.TracialStable +OAI.Analysis.Kaplansky.TestAlgebra +OAI.Analysis.Kaplansky.Ultrapower.ApproxPolar +OAI.Analysis.Kaplansky.Ultrapower.Construction +OAI.Analysis.Kaplansky.Ultrapower.CornerPolarCut +OAI.Analysis.Kaplansky.Ultrapower.DenseUnits +OAI.Analysis.Kaplansky.Ultrapower.MatrixDenseUnits +OAI.Analysis.Kaplansky.Ultrapower.Maximal +OAI.Analysis.Kaplansky.Ultrapower.PartialCorners +OAI.Analysis.Kaplansky.Ultrapower.PartialIsometry +OAI.Analysis.Kaplansky.Ultrapower.Polar +OAI.Analysis.Kaplansky.Ultrapower.PolarDefect +OAI.Analysis.Kaplansky.Ultrapower.PolarScalar +OAI.Analysis.Kaplansky.Ultrapower.QuasiFinite +OAI.Analysis.Kaplansky.Ultrapower.QuasiNull +OAI.Analysis.Kaplansky.Ultrapower.QuasiValue +OAI.Analysis.Kaplansky.Ultrapower.Quotient +OAI.Analysis.Kaplansky.Ultrapower.UltraDiagonal +OAI.Analysis.Kaplansky.Ultrapower.UltraSaturation +OAI.Analysis.Kaplansky.Ultrapower.Unitary +OAI.Analysis.Kaplansky.Ultrapower.Wandering +OAI.Analysis.Kaplansky.Words +OAI.Analysis.MatrixScaling.Bounds +OAI.Analysis.MatrixScaling.Canonical +OAI.Analysis.MatrixScaling.Continuous +OAI.Analysis.MatrixScaling.Critical +OAI.Analysis.MatrixScaling.Determinant +OAI.Analysis.MatrixScaling.Expansion +OAI.Analysis.MatrixScaling.Geodesic +OAI.Analysis.MatrixScaling.Gram +OAI.Analysis.MatrixScaling.Minimizer +OAI.Analysis.MatrixScaling.Spectrum +OAI.Analysis.Quasitrace.Basic +OAI.Analysis.Quasitrace.Compactness +OAI.Analysis.Quasitrace.Defect +OAI.Analysis.Quasitrace.Extension +OAI.Analysis.Quasitrace.Infiniteness +OAI.Analysis.Quasitrace.Matrix +OAI.Analysis.Quasitrace.Order +OAI.Geometry.BundleTests.Assembly +OAI.Geometry.BundleTests.Base +OAI.Geometry.BundleTests.Bundles +OAI.Geometry.BundleTests.Complement +OAI.Geometry.BundleTests.Multiplicities +OAI.Geometry.BundleTests.Normalization +OAI.Geometry.BundleTests.Normalized +OAI.Geometry.BundleTests.Obstruction +OAI.Geometry.BundleTests.Retained +OAI.Geometry.BundleTests.Sequence +OAI.Geometry.BundleTests.Smooth +OAI.Geometry.BundleTests.Twisted +OAI.Geometry.ComplexBundle.Avoidance +OAI.Geometry.ComplexBundle.BundleIncidence +OAI.Geometry.ComplexBundle.Complement +OAI.Geometry.ComplexBundle.Coordinates +OAI.Geometry.ComplexBundle.CoordinatesMetric +OAI.Geometry.ComplexBundle.DirectSum +OAI.Geometry.ComplexBundle.Evaluation +OAI.Geometry.ComplexBundle.Frames +OAI.Geometry.ComplexBundle.Grassmann +OAI.Geometry.ComplexBundle.GrassmannManifold +OAI.Geometry.ComplexBundle.Hom +OAI.Geometry.ComplexBundle.Hyperplane +OAI.Geometry.ComplexBundle.HyperplaneProduct +OAI.Geometry.ComplexBundle.Incidence +OAI.Geometry.ComplexBundle.Kernel +OAI.Geometry.ComplexBundle.LineStage +OAI.Geometry.ComplexBundle.Maps +OAI.Geometry.ComplexBundle.OpenIncidence +OAI.Geometry.ComplexBundle.Orthonormal +OAI.Geometry.ComplexBundle.PointExpansion +OAI.Geometry.ComplexBundle.Projection +OAI.Geometry.ComplexBundle.ProjectionBundle +OAI.Geometry.ComplexBundle.Projective +OAI.Geometry.ComplexBundle.Pullback +OAI.Geometry.ComplexBundle.RealModel +OAI.Geometry.ComplexBundle.Replacement +OAI.Geometry.ComplexBundle.Sections +OAI.Geometry.ComplexBundle.SmoothLine +OAI.Geometry.ComplexBundle.StageMaps +OAI.Geometry.ComplexBundle.Tensor +OAI.Geometry.ComplexBundle.Tuples +OAI.Geometry.ComplexBundle.ZeroSign diff --git a/tasks/kaplansky-stable-finiteness/solution/reference.py b/tasks/kaplansky-stable-finiteness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kaplansky-stable-finiteness/solution/solve.sh b/tasks/kaplansky-stable-finiteness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..58df895e79afc868f7e98b485e8e6b09dcf5cc94 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KaplanskyStableFiniteness, i.e. module OAI.Analysis.Kaplansky.StableFiniteness and the +# 181 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Kaplansky.StableFiniteness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KaplanskyStableFiniteness" diff --git a/tasks/kaplansky-stable-finiteness/task.toml b/tasks/kaplansky-stable-finiteness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..464e038226ded5258f6e09664c79c85446df8389 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kaplansky-stable-finiteness" +version = "1.0.0" +description = "Prove KaplanskyStableFiniteness (openai/math family 294: A counterexample to Kaplansky's quasitrace conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KaplanskyStableFiniteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KaplanskyStableFiniteness" +family = "294" +family_title = "A counterexample to Kaplansky's quasitrace conjecture" +subject = "Operator algebras" +theorems = ["OAI.KaplanskyConsequences.stable_finiteness_bundle"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Kaplansky.StableFiniteness" +reference_modules = 181 +reference_lean_bytes = 1739197 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1007 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13265 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kaplansky-stable-finiteness/tests/Challenge.lean b/tasks/kaplansky-stable-finiteness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..58e769b5bf6b6ace29fe6252a4778a70f8643630 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/tests/Challenge.lean @@ -0,0 +1,247 @@ +import Mathlib + +namespace OAI + +noncomputable section + + +namespace KaplanskyConsequences +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +namespace Regular +variable {ι : Type*} {H : Type*} [NormedAddCommGroup H] + +abbrev HilbertSum (ι H : Type*) [NormedAddCommGroup H] := lp (fun _ : ι => H) 2 + +lemma reindex_mem (e : ι ≃ ι) (x : HilbertSum ι H) : + Memℓp (fun i => x (e i)) 2 := by + apply memℓp_gen + exact e.summable_iff.2 ((memℓp_gen_iff (by norm_num)).1 (lp.memℓp x)) + +variable [InnerProductSpace ℂ H] + +def reindex (e : ι ≃ ι) : HilbertSum ι H ≃ₗᵢ[ℂ] HilbertSum ι H where + toFun x := ⟨fun i => x (e.symm i), reindex_mem e.symm x⟩ + invFun x := ⟨fun i => x (e i), reindex_mem e x⟩ + left_inv x := by ext; simp + right_inv x := by ext; simp + map_add' x y := by ext; rfl + map_smul' r x := by ext; rfl + norm_map' x := by + rw [lp.norm_eq_tsum_rpow (by norm_num),lp.norm_eq_tsum_rpow (by norm_num)] + congr 1 + exact e.symm.tsum_eq (fun i => ‖x i‖ ^ (2 : ℝ≥0∞).toReal) + +@[simp] lemma reindex_apply (e : ι ≃ ι) (x : HilbertSum ι H) (i : ι) : + reindex e x i = x (e.symm i) := rfl + +variable {G : Type*} [Group G] + +def left (g : G) : HilbertSum G H →L[ℂ] HilbertSum G H := + (reindex (Equiv.mulLeft g)).toLinearIsometry.toContinuousLinearMap + +@[simp] lemma left_apply (g h : G) (x : HilbertSum G H) : left g x h = x (g⁻¹*h) := rfl + +lemma left_one : left (H := H) (1 : G) = 1 := by ext x h; simp +lemma left_mul (g h : G) : left (H := H) (g*h) = left g * left h := by + ext x k + simp [mul_assoc] + +variable [CompleteSpace H] + +lemma left_star (g : G) : star (left (H := H) g) = left g⁻¹ := by + symm + apply (ContinuousLinearMap.eq_adjoint_iff _ _).2 + intro x y + change inner ℂ (left g⁻¹ x) y = inner ℂ x (left g y) + rw [lp.inner_eq_tsum,lp.inner_eq_tsum] + simpa [left_apply,mul_assoc] using + (Equiv.mulLeft g).tsum_eq (fun i => inner ℂ (x i) (y (g⁻¹*i))) + +def Algebra (G : Type*) [Group G] : StarSubalgebra ℂ (HilbertSum G ℂ →L[ℂ] HilbertSum G ℂ) := + (StarAlgebra.adjoin ℂ (Set.range (left (H := ℂ) (G := G)))).topologicalClosure + +instance : IsClosed (Algebra G : Set (HilbertSum G ℂ →L[ℂ] HilbertSum G ℂ)) := + StarSubalgebra.isClosed_topologicalClosure _ + +instance : CStarAlgebra (Algebra G) := inferInstance + +def generator (g : G) : Algebra G := + ⟨left g,StarSubalgebra.le_topologicalClosure _ + (StarAlgebra.subset_adjoin ℂ _ ⟨g,rfl⟩)⟩ + +end Regular +end KaplanskyConsequences + + +namespace KaplanskyConsequences.Regular +abbrev F2 := FreeGroup (Fin 2) + + +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +attribute [local instance] Classical.propDecidable +variable {G H : Type*} [Group G] [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] + +def diagonal (T : H →L[ℂ] H) : HilbertSum G H →L[ℂ] HilbertSum G H := + lp.mapCLM 2 (fun _ => T) (norm_nonneg T) (fun _ => le_rfl) + +end KaplanskyConsequences.Regular + + +namespace Kaplansky + +section + +section +open scoped ComplexOrder IsMulCommutative + + +variable {A : Type*} [CStarAlgebra A] + +structure OneQuasitrace (A : Type*) [CStarAlgebra A] where + toFun : A → ℂ + square_nonneg : ∀ x, 0 ≤ toFun (star x * x) + square_swap : ∀ x, toFun (star x * x) = toFun (x * star x) + real_imag : ∀ h k, IsSelfAdjoint h → IsSelfAdjoint k → + toFun (h + Complex.I • k) = toFun h + Complex.I * toFun k + abelian_linear : ∀ S : NonUnitalStarSubalgebra ℂ A, + IsClosed (S : Set A) → (∀ x y : S, x * y = y * x) → + ∃ f : S →ₗ[ℂ] ℂ, ∀ x : S, f x = toFun x + +instance : CoeFun (OneQuasitrace A) (fun _ => A → ℂ) := ⟨OneQuasitrace.toFun⟩ + +def OneQuasitrace.Normalized (τ : OneQuasitrace A) : Prop := τ 1 = 1 + +end + + +open scoped ComplexOrder CStarAlgebra +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] + +def ProperlyInfinite (A : Type*) [CStarAlgebra A] : Prop := + ∃ s t : A, star s*s = 1 ∧ star t*t = 1 ∧ star s*t = 0 + +end + + +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] + +def upperLeft (a : A) : CStarMatrix (Fin 2) (Fin 2) A := + CStarMatrix.ofMatrix fun i j => if i = 0 ∧ j = 0 then a else 0 + +def OneQuasitrace.IsTwo (τ : OneQuasitrace A) : Prop := + ∃ σ : OneQuasitrace (CStarMatrix (Fin 2) (Fin 2) A), ∀ a, σ (upperLeft a) = τ a + +end Kaplansky + + +namespace KaplanskyConsequences + +section +open scoped ComplexOrder +open Metric Topology +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +structure ClosedStarIdeal (A : Type*) [CStarAlgebra A] extends NonUnitalStarSubalgebra ℂ A where + mul_mem_left : ∀ (a b : A), b ∈ toNonUnitalStarSubalgebra → a * b ∈ toNonUnitalStarSubalgebra + mul_mem_right : ∀ (a b : A), a ∈ toNonUnitalStarSubalgebra → a * b ∈ toNonUnitalStarSubalgebra + closed : IsClosed (toNonUnitalStarSubalgebra : Set A) + +end + + +open scoped ComplexOrder +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing + +def StablyFinite (A : Type*) [CStarAlgebra A] : Prop := + ∀ n : ℕ, 0 < n → ∀ v : CStarMatrix (Fin n) (Fin n) A, + star v * v = 1 → v * star v = 1 + +structure TracialState (A : Type*) [CStarAlgebra A] where + functional : A →ₚ[ℂ] ℂ + normalized : functional 1 = 1 + tracial : ∀ a b, functional (a * b) = functional (b * a) + +def TraceFreeStablyFinite : Prop := + ∃ (A : Type) (inst : CStarAlgebra A), + letI := inst + Nontrivial A ∧ TopologicalSpace.SeparableSpace A ∧ StablyFinite A ∧ + IsEmpty (TracialState A) + +end KaplanskyConsequences + +namespace KaplanskyConsequences.Regular +open scoped ComplexOrder InnerProductSpace BigOperators ENNReal +attribute [local instance] Classical.propDecidable +attribute [local instance] CStarAlgebra.spectralOrder CStarAlgebra.spectralOrderedRing +variable {A : Type*} [CStarAlgebra A] +variable {G H : Type*} [Group G] [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +def tensorAlgebra (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : + StarSubalgebra ℂ (HilbertSum G H →L[ℂ] HilbertSum G H) := + (StarAlgebra.adjoin ℂ (Set.range (fun a => diagonal (G:=G) (ρ a)) ∪ Set.range (left (G:=G) (H:=H)))).topologicalClosure + +instance (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : + IsClosed (tensorAlgebra (G:=G) ρ : Set (HilbertSum G H →L[ℂ] HilbertSum G H)) := + StarSubalgebra.isClosed_topologicalClosure _ +instance (ρ : A →⋆ₐ[ℂ] (H →L[ℂ] H)) : CStarAlgebra (tensorAlgebra (G:=G) ρ) := inferInstance + +end KaplanskyConsequences.Regular + +namespace KaplanskyConsequences + +section + +section +open Kaplansky Regular + +def ReducedQuasitraceLoss : Prop := + ∃ (B : Type) (instB : CStarAlgebra B), + letI := instB + Nontrivial B ∧ TopologicalSpace.SeparableSpace B ∧ + (∃ τ : OneQuasitrace B, τ.Normalized ∧ τ.IsTwo) ∧ + ∃ (H : Type) (instH : NormedAddCommGroup H) (innerH : InnerProductSpace ℂ H), + letI := instH + letI := innerH + ∃ (completeH : CompleteSpace H), + letI := completeH + ∃ ρ : B →⋆ₐ[ℂ] (H →L[ℂ] H), Function.Injective ρ ∧ + ProperlyInfinite (tensorAlgebra (G:=F2) ρ) ∧ + ¬ ∃ τ : OneQuasitrace (tensorAlgebra (G:=F2) ρ), τ.Normalized ∧ τ.IsTwo +end + +open Kaplansky Regular + +def CStarSimple (A : Type*) [CStarAlgebra A] : Prop := + ∀ I : ClosedStarIdeal A, + (∀ a : A, a ∈ I.toNonUnitalStarSubalgebra → a = 0) ∨ + (∀ a : A, a ∈ I.toNonUnitalStarSubalgebra) + +def SimpleStableTensorCounterexample : Prop := + CStarSimple (Algebra F2) ∧ StablyFinite (Algebra F2) ∧ + ∃ (M : Type) (instM : CStarAlgebra M), + letI := instM + Nontrivial M ∧ CStarSimple M ∧ StablyFinite M ∧ + ∃ (H : Type) (instH : NormedAddCommGroup H) (innerH : InnerProductSpace ℂ H), + letI := instH + letI := innerH + ∃ (completeH : CompleteSpace H), + letI := completeH + ∃ ρ : M →⋆ₐ[ℂ] (H →L[ℂ] H), Function.Injective ρ ∧ + ProperlyInfinite (tensorAlgebra (G:=F2) ρ) +end + + +def StableFinitenessBundle : Prop := + SimpleStableTensorCounterexample ∧ ReducedQuasitraceLoss ∧ TraceFreeStablyFinite + +theorem stable_finiteness_bundle : StableFinitenessBundle := by + sorry + +end KaplanskyConsequences + +end + +end OAI diff --git a/tasks/kaplansky-stable-finiteness/tests/grade.py b/tasks/kaplansky-stable-finiteness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kaplansky-stable-finiteness/tests/task.json b/tasks/kaplansky-stable-finiteness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cf35b99d71c464dc82fda49b364b72615a52cb56 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KaplanskyStableFiniteness", + "comparator": { + "theorem_names": [ + "OAI.KaplanskyConsequences.stable_finiteness_bundle" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12365 +} \ No newline at end of file diff --git a/tasks/kaplansky-stable-finiteness/tests/test.sh b/tasks/kaplansky-stable-finiteness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kaplansky-stable-finiteness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kervaire/environment/Dockerfile b/tasks/kervaire/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kervaire/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kervaire/environment/fetch_mathlib.sh b/tasks/kervaire/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kervaire/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kervaire/environment/lake-manifest.json b/tasks/kervaire/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kervaire/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kervaire/environment/lakefile.lean b/tasks/kervaire/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kervaire/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kervaire/environment/lean_setup.sh b/tasks/kervaire/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kervaire/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kervaire/environment/pack_submission.py b/tasks/kervaire/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kervaire/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kervaire/instruction.md b/tasks/kervaire/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f05d8ae0d44d69105f3861a1ccf6c0945c4d6dde --- /dev/null +++ b/tasks/kervaire/instruction.md @@ -0,0 +1,90 @@ +# openai/math challenge `Kervaire` (family 256) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 256 of the release, *Howie's conjecture on equations over groups* +(Group theory). The family as a whole: Proves that every finite system of equations over an arbitrary group whose exponent-sum matrix has full row rank over $\mathbb Q$ has a simultaneous solution in an overgroup, resolving Howie's conjecture. The coefficient group embeds in the presented quotient. A companion proves Kervaire's conjecture: adjoining one generator and one relation cannot trivialize a nontrivial group. + +The challenge is `Kervaire`, also at `/opt/openai-math/challenges/Kervaire.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Kervaire + +universe u + +abbrev WordGroup (A : Type u) [Group A] := Monoid.Coprod A (Multiplicative ℤ) + +def exponentSum {A : Type u} [Group A] (w : WordGroup A) : ℤ := + Multiplicative.toAdd (Monoid.Coprod.snd w) + +def Unimodular {A : Type u} [Group A] (w : WordGroup A) : Prop := + exponentSum w = 1 ∨ exponentSum w = -1 + +def relatorClosure {A : Type u} [Group A] (w : WordGroup A) : Subgroup (WordGroup A) := + Subgroup.normalClosure ({w} : Set (WordGroup A)) + +instance {A : Type u} [Group A] (w : WordGroup A) : (relatorClosure w).Normal := + inferInstanceAs (Subgroup.normalClosure ({w} : Set (WordGroup A))).Normal + +abbrev RelatorQuotient {A : Type u} [Group A] (w : WordGroup A) := + WordGroup A ⧸ relatorClosure w + +def coefficientMap {A : Type u} [Group A] (w : WordGroup A) : A →* RelatorQuotient w := + (QuotientGroup.mk' (relatorClosure w)).comp Monoid.Coprod.inl + +theorem coefficient_injective (A : Type u) [Group A] (w : WordGroup A) + (hw : Unimodular w) : Function.Injective (coefficientMap w) := by + sorry + +end Kervaire + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Kervaire.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Kervaire.coefficient_injective` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kervaire/solution/closure.txt b/tasks/kervaire/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fbe026b1cf18a4297cd441d118b342d722a5aec8 --- /dev/null +++ b/tasks/kervaire/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.GroupTheory.Kervaire.Annulus +OAI.GroupTheory.Kervaire.BoundaryFlow +OAI.GroupTheory.Kervaire.Capping +OAI.GroupTheory.Kervaire.Circles +OAI.GroupTheory.Kervaire.ComponentFibers +OAI.GroupTheory.Kervaire.Components +OAI.GroupTheory.Kervaire.Conjugation +OAI.GroupTheory.Kervaire.CurrentExistence +OAI.GroupTheory.Kervaire.CurrentPullback +OAI.GroupTheory.Kervaire.FixedSpaces +OAI.GroupTheory.Kervaire.HaarCurrents +OAI.GroupTheory.Kervaire.IncidenceDegree +OAI.GroupTheory.Kervaire.IncidenceSpaces +OAI.GroupTheory.Kervaire.IncidenceTangent +OAI.GroupTheory.Kervaire.Inversion +OAI.GroupTheory.Kervaire.Main +OAI.GroupTheory.Kervaire.MatrixShifts +OAI.GroupTheory.Kervaire.MatrixTrace +OAI.GroupTheory.Kervaire.MixingOperators +OAI.GroupTheory.Kervaire.Model +OAI.GroupTheory.Kervaire.OuterRibbon +OAI.GroupTheory.Kervaire.PermutationCycles +OAI.GroupTheory.Kervaire.PhaseDimension +OAI.GroupTheory.Kervaire.PhaseFaithfulness +OAI.GroupTheory.Kervaire.PhaseGrids +OAI.GroupTheory.Kervaire.PhaseNaturality +OAI.GroupTheory.Kervaire.PhaseSubadditivity +OAI.GroupTheory.Kervaire.Realization +OAI.GroupTheory.Kervaire.Reductions +OAI.GroupTheory.Kervaire.RegularOperators +OAI.GroupTheory.Kervaire.RelatorRigidity +OAI.GroupTheory.Kervaire.RibbonProducts +OAI.GroupTheory.Kervaire.RibbonRigidity +OAI.GroupTheory.Kervaire.ScalarPhase +OAI.GroupTheory.Kervaire.SignedIncidence +OAI.GroupTheory.Kervaire.SpectralApproximation +OAI.GroupTheory.Kervaire.SpectralLogarithm +OAI.GroupTheory.Kervaire.SpectralMeasures +OAI.GroupTheory.Kervaire.Splicing +OAI.GroupTheory.Kervaire.StrongLimits +OAI.GroupTheory.Kervaire.Suppression +OAI.GroupTheory.Kervaire.TraceCalculus +OAI.GroupTheory.Kervaire.Traversal +OAI.GroupTheory.Kervaire.UnitaryHomotopy +OAI.GroupTheory.Kervaire.VertexJoin +OAI.GroupTheory.Kervaire.WeightedCycles +OAI.GroupTheory.Kervaire.WordNormalization diff --git a/tasks/kervaire/solution/reference.py b/tasks/kervaire/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kervaire/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kervaire/solution/solve.sh b/tasks/kervaire/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..35ab9f936c8d8928a09b3c9929e4a1fd6b7ed067 --- /dev/null +++ b/tasks/kervaire/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Kervaire, i.e. module OAI.GroupTheory.Kervaire.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.Kervaire.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Kervaire" diff --git a/tasks/kervaire/task.toml b/tasks/kervaire/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ed0cd1bcbb8a200e85ce30fe3ea63c7891e315b7 --- /dev/null +++ b/tasks/kervaire/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kervaire" +version = "1.0.0" +description = "Prove Kervaire (openai/math family 256: Howie's conjecture on equations over groups) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Kervaire.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Kervaire" +family = "256" +family_title = "Howie's conjecture on equations over groups" +subject = "Group theory" +theorems = ["OAI.Kervaire.coefficient_injective"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.Kervaire.Main" +reference_modules = 47 +reference_lean_bytes = 508441 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1057 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12157 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kervaire/tests/Challenge.lean b/tasks/kervaire/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..faf3e5c7338cd5d4d9ed496aa39d5699301f5704 --- /dev/null +++ b/tasks/kervaire/tests/Challenge.lean @@ -0,0 +1,39 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Kervaire + +universe u + +abbrev WordGroup (A : Type u) [Group A] := Monoid.Coprod A (Multiplicative ℤ) + +def exponentSum {A : Type u} [Group A] (w : WordGroup A) : ℤ := + Multiplicative.toAdd (Monoid.Coprod.snd w) + +def Unimodular {A : Type u} [Group A] (w : WordGroup A) : Prop := + exponentSum w = 1 ∨ exponentSum w = -1 + +def relatorClosure {A : Type u} [Group A] (w : WordGroup A) : Subgroup (WordGroup A) := + Subgroup.normalClosure ({w} : Set (WordGroup A)) + +instance {A : Type u} [Group A] (w : WordGroup A) : (relatorClosure w).Normal := + inferInstanceAs (Subgroup.normalClosure ({w} : Set (WordGroup A))).Normal + +abbrev RelatorQuotient {A : Type u} [Group A] (w : WordGroup A) := + WordGroup A ⧸ relatorClosure w + +def coefficientMap {A : Type u} [Group A] (w : WordGroup A) : A →* RelatorQuotient w := + (QuotientGroup.mk' (relatorClosure w)).comp Monoid.Coprod.inl + +theorem coefficient_injective (A : Type u) [Group A] (w : WordGroup A) + (hw : Unimodular w) : Function.Injective (coefficientMap w) := by + sorry + +end Kervaire + +end + +end OAI diff --git a/tasks/kervaire/tests/grade.py b/tasks/kervaire/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kervaire/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kervaire/tests/task.json b/tasks/kervaire/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..12b8dfd2a0c28eea78ad91790eec428c93f5be75 --- /dev/null +++ b/tasks/kervaire/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Kervaire", + "comparator": { + "theorem_names": [ + "OAI.Kervaire.coefficient_injective" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11257 +} \ No newline at end of file diff --git a/tasks/kervaire/tests/test.sh b/tasks/kervaire/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kervaire/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/kl-invariance/environment/Dockerfile b/tasks/kl-invariance/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/kl-invariance/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/kl-invariance/environment/fetch_mathlib.sh b/tasks/kl-invariance/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/kl-invariance/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/kl-invariance/environment/lake-manifest.json b/tasks/kl-invariance/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/kl-invariance/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/kl-invariance/environment/lakefile.lean b/tasks/kl-invariance/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/kl-invariance/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/kl-invariance/environment/lean_setup.sh b/tasks/kl-invariance/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/kl-invariance/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/kl-invariance/environment/pack_submission.py b/tasks/kl-invariance/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/kl-invariance/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/kl-invariance/instruction.md b/tasks/kl-invariance/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8706f085ebbf8a09c57d0c30130bd3f9221da7cb --- /dev/null +++ b/tasks/kl-invariance/instruction.md @@ -0,0 +1,150 @@ +# openai/math challenge `KLInvariance` (family 168) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 168 of the release, *Combinatorial invariance of Kazhdan–Lusztig polynomials* +(Combinatorics). The family as a whole: Resolves the full combinatorial invariance conjecture: isomorphic Bruhat intervals in arbitrary Coxeter systems have identical equal-parameter Kazhdan–Lusztig polynomials. Thus the abstract order of the interval determines the polynomial, even across different Coxeter systems. + +The challenge is `KLInvariance`, also at `/opt/openai-math/challenges/KLInvariance.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace KLInvariance + +open Polynomial + +universe u v u' v' + +variable {B : Type u} {W : Type v} [Group W] {M : CoxeterMatrix B} + +/-- An upward edge in the *strong* Bruhat graph, with left reflection labels. -/ +def BruhatStep (cs : CoxeterSystem M W) (x y : W) : Prop := + cs.length x < cs.length y ∧ ∃ t : W, cs.IsReflection t ∧ y = t * x + +/-- The actual strong Bruhat order, not the weak order. -/ +def BruhatLE (cs : CoxeterSystem M W) : W → W → Prop := + Relation.ReflTransGen (BruhatStep cs) + +/-- The unlabelled interval, including both endpoints. -/ +def Interval (cs : CoxeterSystem M W) (u b : W) := + {x : W // BruhatLE cs u x ∧ BruhatLE cs x b} + +instance intervalOrder (cs : CoxeterSystem M W) (u b : W) : + PartialOrder (Interval cs u b) where + le left right := BruhatLE cs left.val right.val + le_refl _ := Relation.ReflTransGen.refl + le_trans _ _ _ forward backward := forward.trans backward + le_antisymm left right forward backward := by + apply Subtype.ext + have length_mono : ∀ {lower upper : W}, BruhatLE cs lower upper → + cs.length lower ≤ cs.length upper := by + intro lower upper relation + induction relation using Relation.ReflTransGen.head_induction_on with + | refl => exact le_rfl + | head step _ rest => exact le_trans step.1.le rest + by_contra distinct + rcases forward.cases_head with same | ⟨middle, step, rest⟩ + · exact distinct same + · exact (not_lt_of_ge (length_mono backward)) + (lt_of_lt_of_le step.1 (length_mono rest)) + +/-- `d(x,y)` in the manuscript, used only for comparable endpoints. -/ +noncomputable def rankDifference (cs : CoxeterSystem M W) (x y : W) : ℕ := + cs.length y - cs.length x + +abbrev PolynomialFamilies (W : Type v) := (W → W → ℤ[X]) × (W → W → ℤ[X]) + +/-- Exact equal-parameter normalization in the introduction. +The first family is R and the second is P. `reflect d p` is `q^d p(q⁻¹)` +when `p.natDegree ≤ d`, which follows here from the degree bound (or the +diagonal normalization). The sum is over the real Bruhat interval; +its finiteness is a separate theorem, not a different definition of order. -/ +structure NormalizedKL (cs : CoxeterSystem M W) (RP : PolynomialFamilies W) : Prop where + R_diagonal : ∀ x, RP.1 x x = 1 + R_zero : ∀ x y, ¬ BruhatLE cs x y → RP.1 x y = 0 + R_recursion : ∀ x y i, cs.length (cs.simple i * y) < cs.length y → + RP.1 x y = + if cs.length (cs.simple i * x) < cs.length x then + RP.1 (cs.simple i * x) (cs.simple i * y) + else + (X - 1) * RP.1 x (cs.simple i * y) + + X * RP.1 (cs.simple i * x) (cs.simple i * y) + P_diagonal : ∀ x, RP.2 x x = 1 + P_zero : ∀ x y, ¬ BruhatLE cs x y → RP.2 x y = 0 + P_degree : ∀ x y, BruhatLE cs x y → x ≠ y → + 2 * (RP.2 x y).natDegree < rankDifference cs x y + reciprocity : ∀ x y, BruhatLE cs x y → + reflect (rankDifference cs x y) (RP.2 x y) = + ∑ᶠ z : Interval cs x y, RP.1 x z.val * RP.2 z.val y + +/-- The polynomial families selected by their equal-parameter normalization. -/ +noncomputable def klFamilies (cs : CoxeterSystem M W) : PolynomialFamilies W := + Classical.epsilon (NormalizedKL cs) + +noncomputable def klPolynomial (cs : CoxeterSystem M W) (x y : W) : ℤ[X] := + (klFamilies cs).2 x y + +end KLInvariance + +namespace KLInvariance + +universe u v u' v' + +variable {B : Type u} {W : Type v} [Group W] {M : CoxeterMatrix B} + +theorem combinatorial_invariance + {B' : Type u'} {W' : Type v'} [Group W'] {M' : CoxeterMatrix B'} + (cs : CoxeterSystem M W) (cs' : CoxeterSystem M' W') + {u b : W} {u' b' : W'} + (hub : BruhatLE cs u b) (hub' : BruhatLE cs' u' b') + (ι : Interval cs u b ≃o Interval cs' u' b') : + klPolynomial cs u b = klPolynomial cs' u' b' := by + sorry + +end KLInvariance + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/KLInvariance.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.KLInvariance.combinatorial_invariance` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/kl-invariance/solution/closure.txt b/tasks/kl-invariance/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd4d89b8b0fd06dd56f6d484d07cd45ced67b017 --- /dev/null +++ b/tasks/kl-invariance/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.RepresentationTheory.KazhdanLusztig.BalancedPairings +OAI.RepresentationTheory.KazhdanLusztig.BottSamelson +OAI.RepresentationTheory.KazhdanLusztig.Bruhat +OAI.RepresentationTheory.KazhdanLusztig.CanonicalKL +OAI.RepresentationTheory.KazhdanLusztig.CharacterReciprocity +OAI.RepresentationTheory.KazhdanLusztig.Comparison +OAI.RepresentationTheory.KazhdanLusztig.Coxeter +OAI.RepresentationTheory.KazhdanLusztig.Decomposition +OAI.RepresentationTheory.KazhdanLusztig.Dihedral +OAI.RepresentationTheory.KazhdanLusztig.DihedralIntervals +OAI.RepresentationTheory.KazhdanLusztig.DyerPaths +OAI.RepresentationTheory.KazhdanLusztig.EdgeLocalization +OAI.RepresentationTheory.KazhdanLusztig.Frobenius +OAI.RepresentationTheory.KazhdanLusztig.GradedModules +OAI.RepresentationTheory.KazhdanLusztig.GradedSheaves +OAI.RepresentationTheory.KazhdanLusztig.Hecke +OAI.RepresentationTheory.KazhdanLusztig.HilbertSeries +OAI.RepresentationTheory.KazhdanLusztig.IntegralPairings +OAI.RepresentationTheory.KazhdanLusztig.Invariance +OAI.RepresentationTheory.KazhdanLusztig.MinimalExtensions +OAI.RepresentationTheory.KazhdanLusztig.Model +OAI.RepresentationTheory.KazhdanLusztig.ModuleAlgebra +OAI.RepresentationTheory.KazhdanLusztig.OrdinaryR +OAI.RepresentationTheory.KazhdanLusztig.PlaneLocalization +OAI.RepresentationTheory.KazhdanLusztig.PositiveTransfer +OAI.RepresentationTheory.KazhdanLusztig.ReflectionOrders +OAI.RepresentationTheory.KazhdanLusztig.ReflectionPlane +OAI.RepresentationTheory.KazhdanLusztig.ReflectionSchedules +OAI.RepresentationTheory.KazhdanLusztig.SheafMorphisms +OAI.RepresentationTheory.KazhdanLusztig.Sheaves +OAI.RepresentationTheory.KazhdanLusztig.SimultaneousInvariance +OAI.RepresentationTheory.KazhdanLusztig.Support +OAI.RepresentationTheory.KazhdanLusztig.TerminalKernels +OAI.RepresentationTheory.KazhdanLusztig.Tits diff --git a/tasks/kl-invariance/solution/reference.py b/tasks/kl-invariance/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/kl-invariance/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/kl-invariance/solution/solve.sh b/tasks/kl-invariance/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..20e966f74007df7f8372d0a281cc999e8fa1a84d --- /dev/null +++ b/tasks/kl-invariance/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of KLInvariance, i.e. module OAI.RepresentationTheory.KazhdanLusztig.Invariance and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RepresentationTheory.KazhdanLusztig.Invariance /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of KLInvariance" diff --git a/tasks/kl-invariance/task.toml b/tasks/kl-invariance/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a08afbfef755fef62adb4da5b65e1b33073506a5 --- /dev/null +++ b/tasks/kl-invariance/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/kl-invariance" +version = "1.0.0" +description = "Prove KLInvariance (openai/math family 168: Combinatorial invariance of Kazhdan–Lusztig polynomials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/KLInvariance.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "KLInvariance" +family = "168" +family_title = "Combinatorial invariance of Kazhdan–Lusztig polynomials" +subject = "Combinatorics" +theorems = ["OAI.KLInvariance.combinatorial_invariance"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RepresentationTheory.KazhdanLusztig.Invariance" +reference_modules = 34 +reference_lean_bytes = 1831275 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1717 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13348 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/kl-invariance/tests/Challenge.lean b/tasks/kl-invariance/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b95edb136e81b3885e2febde719356b4d0adee2d --- /dev/null +++ b/tasks/kl-invariance/tests/Challenge.lean @@ -0,0 +1,99 @@ +import Mathlib + +namespace OAI + +namespace KLInvariance + +open Polynomial + +universe u v u' v' + +variable {B : Type u} {W : Type v} [Group W] {M : CoxeterMatrix B} + +/-- An upward edge in the *strong* Bruhat graph, with left reflection labels. -/ +def BruhatStep (cs : CoxeterSystem M W) (x y : W) : Prop := + cs.length x < cs.length y ∧ ∃ t : W, cs.IsReflection t ∧ y = t * x + +/-- The actual strong Bruhat order, not the weak order. -/ +def BruhatLE (cs : CoxeterSystem M W) : W → W → Prop := + Relation.ReflTransGen (BruhatStep cs) + +/-- The unlabelled interval, including both endpoints. -/ +def Interval (cs : CoxeterSystem M W) (u b : W) := + {x : W // BruhatLE cs u x ∧ BruhatLE cs x b} + +instance intervalOrder (cs : CoxeterSystem M W) (u b : W) : + PartialOrder (Interval cs u b) where + le left right := BruhatLE cs left.val right.val + le_refl _ := Relation.ReflTransGen.refl + le_trans _ _ _ forward backward := forward.trans backward + le_antisymm left right forward backward := by + apply Subtype.ext + have length_mono : ∀ {lower upper : W}, BruhatLE cs lower upper → + cs.length lower ≤ cs.length upper := by + intro lower upper relation + induction relation using Relation.ReflTransGen.head_induction_on with + | refl => exact le_rfl + | head step _ rest => exact le_trans step.1.le rest + by_contra distinct + rcases forward.cases_head with same | ⟨middle, step, rest⟩ + · exact distinct same + · exact (not_lt_of_ge (length_mono backward)) + (lt_of_lt_of_le step.1 (length_mono rest)) + +/-- `d(x,y)` in the manuscript, used only for comparable endpoints. -/ +noncomputable def rankDifference (cs : CoxeterSystem M W) (x y : W) : ℕ := + cs.length y - cs.length x + +abbrev PolynomialFamilies (W : Type v) := (W → W → ℤ[X]) × (W → W → ℤ[X]) + +/-- Exact equal-parameter normalization in the introduction. +The first family is R and the second is P. `reflect d p` is `q^d p(q⁻¹)` +when `p.natDegree ≤ d`, which follows here from the degree bound (or the +diagonal normalization). The sum is over the real Bruhat interval; +its finiteness is a separate theorem, not a different definition of order. -/ +structure NormalizedKL (cs : CoxeterSystem M W) (RP : PolynomialFamilies W) : Prop where + R_diagonal : ∀ x, RP.1 x x = 1 + R_zero : ∀ x y, ¬ BruhatLE cs x y → RP.1 x y = 0 + R_recursion : ∀ x y i, cs.length (cs.simple i * y) < cs.length y → + RP.1 x y = + if cs.length (cs.simple i * x) < cs.length x then + RP.1 (cs.simple i * x) (cs.simple i * y) + else + (X - 1) * RP.1 x (cs.simple i * y) + + X * RP.1 (cs.simple i * x) (cs.simple i * y) + P_diagonal : ∀ x, RP.2 x x = 1 + P_zero : ∀ x y, ¬ BruhatLE cs x y → RP.2 x y = 0 + P_degree : ∀ x y, BruhatLE cs x y → x ≠ y → + 2 * (RP.2 x y).natDegree < rankDifference cs x y + reciprocity : ∀ x y, BruhatLE cs x y → + reflect (rankDifference cs x y) (RP.2 x y) = + ∑ᶠ z : Interval cs x y, RP.1 x z.val * RP.2 z.val y + +/-- The polynomial families selected by their equal-parameter normalization. -/ +noncomputable def klFamilies (cs : CoxeterSystem M W) : PolynomialFamilies W := + Classical.epsilon (NormalizedKL cs) + +noncomputable def klPolynomial (cs : CoxeterSystem M W) (x y : W) : ℤ[X] := + (klFamilies cs).2 x y + +end KLInvariance + +namespace KLInvariance + +universe u v u' v' + +variable {B : Type u} {W : Type v} [Group W] {M : CoxeterMatrix B} + +theorem combinatorial_invariance + {B' : Type u'} {W' : Type v'} [Group W'] {M' : CoxeterMatrix B'} + (cs : CoxeterSystem M W) (cs' : CoxeterSystem M' W') + {u b : W} {u' b' : W'} + (hub : BruhatLE cs u b) (hub' : BruhatLE cs' u' b') + (ι : Interval cs u b ≃o Interval cs' u' b') : + klPolynomial cs u b = klPolynomial cs' u' b' := by + sorry + +end KLInvariance + +end OAI diff --git a/tasks/kl-invariance/tests/grade.py b/tasks/kl-invariance/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/kl-invariance/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/kl-invariance/tests/task.json b/tasks/kl-invariance/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..628935e8f809faa3ab22c1ff81338706913804f5 --- /dev/null +++ b/tasks/kl-invariance/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "KLInvariance", + "comparator": { + "theorem_names": [ + "OAI.KLInvariance.combinatorial_invariance" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12448 +} \ No newline at end of file diff --git a/tasks/kl-invariance/tests/test.sh b/tasks/kl-invariance/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/kl-invariance/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/laughlin-fock/environment/Dockerfile b/tasks/laughlin-fock/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/laughlin-fock/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/laughlin-fock/environment/fetch_mathlib.sh b/tasks/laughlin-fock/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/laughlin-fock/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/laughlin-fock/environment/lake-manifest.json b/tasks/laughlin-fock/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/laughlin-fock/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/laughlin-fock/environment/lakefile.lean b/tasks/laughlin-fock/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/laughlin-fock/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/laughlin-fock/environment/lean_setup.sh b/tasks/laughlin-fock/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/laughlin-fock/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/laughlin-fock/environment/pack_submission.py b/tasks/laughlin-fock/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/laughlin-fock/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/laughlin-fock/instruction.md b/tasks/laughlin-fock/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..218447972abfaf19d9d057584e7649abe726721f --- /dev/null +++ b/tasks/laughlin-fock/instruction.md @@ -0,0 +1,117 @@ +# openai/math challenge `LaughlinFock` (family 269) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 269 of the release, *The Laughlin gap and stability under scalar disorder* +(Mathematical physics). The family as a whole: Proves the fermionic Laughlin spectral-gap conjecture for the full $V_1$ interaction at filling $1/3$ on the round sphere. The unique ground state remains uniformly gapped under sufficiently weak bounded real scalar one-body potentials projected to the lowest Landau level. Both the gap and disorder threshold are uniform over all sufficiently large particle numbers and all normalized potential profiles. + +The challenge is `LaughlinFock`, also at `/opt/openai-math/challenges/LaughlinFock.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! The spherical V₁ Hamiltonian inequality on the full fermionic Fock space. -/ + +noncomputable section + +namespace Laughlin + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + +end Laughlin + +run_cmd Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace LaughlinFock + +open scoped BigOperators Matrix ComplexConjugate ComplexOrder + +abbrev Orbital (Q : ℕ) := Fin (Q + 1) +abbrev Occupation (Q : ℕ) := Finset (Orbital Q) +abbrev FockMatrix (Q : ℕ) := Matrix (Occupation Q) (Occupation Q) ℂ + +def tensorPairCoefficient (Q p : ℕ) (i j : Orbital Q) : ℝ := + _root_.OAI.Laughlin.pairCoefficient Q p i j + +def pairCoefficient (Q p : ℕ) (i j : Orbital Q) : ℝ := + Real.sqrt 2 * tensorPairCoefficient Q p i j + +def annihilator (Q : ℕ) (j : Orbital Q) : FockMatrix Q := fun A B => + if j ∈ B ∧ A = B.erase j then + (-1 : ℂ) ^ (B.filter (fun i => i < j)).card + else 0 + +def pairAnnihilator (Q p : ℕ) : FockMatrix Q := + ∑ i : Orbital Q, ∑ j : Orbital Q, + if i < j then + (pairCoefficient Q p i j : ℂ) • (annihilator Q j * annihilator Q i) + else 0 + +def hamiltonian (Q : ℕ) : FockMatrix Q := + ∑ p ∈ Finset.range (2 * Q - 1), + (pairAnnihilator Q p)ᴴ * pairAnnihilator Q p + +def gammaStar : ℝ := 4616733319001 / 10 ^ 14 + +def FockInequality (Q : ℕ) (γ : ℝ) : Prop := + (hamiltonian Q * hamiltonian Q - γ • hamiltonian Q).PosSemidef + +theorem thm_fock (γ : ℝ) (hγ : 0 < γ) (hγStar : γ < gammaStar) : + ∃ Qγ : ℤ, 1 ≤ Qγ ∧ ∀ Q : ℤ, Qγ ≤ Q → FockInequality Q.toNat γ := by + sorry + +end LaughlinFock + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LaughlinFock.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LaughlinFock.thm_fock` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/laughlin-fock/solution/closure.txt b/tasks/laughlin-fock/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..144e17cf68afd072efb56bb3b1afac03330c8262 --- /dev/null +++ b/tasks/laughlin-fock/solution/closure.txt @@ -0,0 +1,293 @@ +OAI.Analysis.Laughlin.Model +OAI.Analysis.LaughlinFock.AllowanceOrbit +OAI.Analysis.LaughlinFock.Assembly +OAI.Analysis.LaughlinFock.AveragedOperators +OAI.Analysis.LaughlinFock.Averaging +OAI.Analysis.LaughlinFock.BesselComparison +OAI.Analysis.LaughlinFock.Certificate01 +OAI.Analysis.LaughlinFock.Certificate02 +OAI.Analysis.LaughlinFock.Certificate03 +OAI.Analysis.LaughlinFock.Certificate04 +OAI.Analysis.LaughlinFock.Certificate05 +OAI.Analysis.LaughlinFock.Certificate05Data +OAI.Analysis.LaughlinFock.Certificate06 +OAI.Analysis.LaughlinFock.Certificate07 +OAI.Analysis.LaughlinFock.Certificate07Data +OAI.Analysis.LaughlinFock.Certificate08 +OAI.Analysis.LaughlinFock.Certificate08Data +OAI.Analysis.LaughlinFock.Certificate09 +OAI.Analysis.LaughlinFock.Certificate09Data +OAI.Analysis.LaughlinFock.Certificate10 +OAI.Analysis.LaughlinFock.Certificate10Data +OAI.Analysis.LaughlinFock.Certificate11 +OAI.Analysis.LaughlinFock.Certificate11Data +OAI.Analysis.LaughlinFock.Certificate12 +OAI.Analysis.LaughlinFock.Certificate12Data +OAI.Analysis.LaughlinFock.Certificate13 +OAI.Analysis.LaughlinFock.Certificate13Data +OAI.Analysis.LaughlinFock.Certificate14 +OAI.Analysis.LaughlinFock.Certificate14Data +OAI.Analysis.LaughlinFock.Certificate15 +OAI.Analysis.LaughlinFock.Certificate15Data +OAI.Analysis.LaughlinFock.Certificate16 +OAI.Analysis.LaughlinFock.Certificate16Data +OAI.Analysis.LaughlinFock.Certificate17 +OAI.Analysis.LaughlinFock.Certificate17Data +OAI.Analysis.LaughlinFock.Certificate18 +OAI.Analysis.LaughlinFock.Certificate18Data +OAI.Analysis.LaughlinFock.Certificate19 +OAI.Analysis.LaughlinFock.Certificate19Data +OAI.Analysis.LaughlinFock.Certificate20 +OAI.Analysis.LaughlinFock.Certificate20Data +OAI.Analysis.LaughlinFock.Certificate21 +OAI.Analysis.LaughlinFock.Certificate21Data +OAI.Analysis.LaughlinFock.Certificate22 +OAI.Analysis.LaughlinFock.Certificate22Data +OAI.Analysis.LaughlinFock.Certificate23 +OAI.Analysis.LaughlinFock.Certificate23Data +OAI.Analysis.LaughlinFock.CertificateRows +OAI.Analysis.LaughlinFock.CopyAverage +OAI.Analysis.LaughlinFock.CopyNormalization +OAI.Analysis.LaughlinFock.CopyVectors +OAI.Analysis.LaughlinFock.CoupledLie +OAI.Analysis.LaughlinFock.CouplingTables +OAI.Analysis.LaughlinFock.Covariance +OAI.Analysis.LaughlinFock.CreationRows +OAI.Analysis.LaughlinFock.CrossOrbit +OAI.Analysis.LaughlinFock.EntryEnumeration +OAI.Analysis.LaughlinFock.ExchangeSpectrum +OAI.Analysis.LaughlinFock.FastCoupling +OAI.Analysis.LaughlinFock.FastTrace +OAI.Analysis.LaughlinFock.FastWedge +OAI.Analysis.LaughlinFock.FasterTrace +OAI.Analysis.LaughlinFock.FermionOperators +OAI.Analysis.LaughlinFock.FiniteComparison +OAI.Analysis.LaughlinFock.FiniteCoupling +OAI.Analysis.LaughlinFock.Flow +OAI.Analysis.LaughlinFock.FockRotations +OAI.Analysis.LaughlinFock.FourBasis +OAI.Analysis.LaughlinFock.FourBound +OAI.Analysis.LaughlinFock.FourCoefficients +OAI.Analysis.LaughlinFock.FourCopies +OAI.Analysis.LaughlinFock.FourHighest +OAI.Analysis.LaughlinFock.FourLie +OAI.Analysis.LaughlinFock.FourRetained +OAI.Analysis.LaughlinFock.FourTrace +OAI.Analysis.LaughlinFock.FourTraces +OAI.Analysis.LaughlinFock.GramCache +OAI.Analysis.LaughlinFock.GramCompression +OAI.Analysis.LaughlinFock.HighestTails +OAI.Analysis.LaughlinFock.IntegerCompression +OAI.Analysis.LaughlinFock.IntegerCoupling +OAI.Analysis.LaughlinFock.IntegerFour +OAI.Analysis.LaughlinFock.LDL +OAI.Analysis.LaughlinFock.LadderCalculus +OAI.Analysis.LaughlinFock.LocalEnergy +OAI.Analysis.LaughlinFock.Main +OAI.Analysis.LaughlinFock.Model +OAI.Analysis.LaughlinFock.NormalOrdering +OAI.Analysis.LaughlinFock.NullComponents +OAI.Analysis.LaughlinFock.NumericTrace +OAI.Analysis.LaughlinFock.OscillatorLimit +OAI.Analysis.LaughlinFock.PairDecomposition +OAI.Analysis.LaughlinFock.PairIdentification +OAI.Analysis.LaughlinFock.PairLie +OAI.Analysis.LaughlinFock.PairNormalization +OAI.Analysis.LaughlinFock.PairOrbit +OAI.Analysis.LaughlinFock.PartsTrace +OAI.Analysis.LaughlinFock.PolynomialPositivity +OAI.Analysis.LaughlinFock.PositiveIntegrals +OAI.Analysis.LaughlinFock.RationalCoupling +OAI.Analysis.LaughlinFock.RationalFour +OAI.Analysis.LaughlinFock.RationalThree +OAI.Analysis.LaughlinFock.RationalWedge +OAI.Analysis.LaughlinFock.RectangularOrbit +OAI.Analysis.LaughlinFock.RelativePerturbation +OAI.Analysis.LaughlinFock.RelativeTransfer +OAI.Analysis.LaughlinFock.Rotations +OAI.Analysis.LaughlinFock.RowTraces +OAI.Analysis.LaughlinFock.ScalarAction +OAI.Analysis.LaughlinFock.Sparse0801 +OAI.Analysis.LaughlinFock.Sparse0802 +OAI.Analysis.LaughlinFock.Sparse0803 +OAI.Analysis.LaughlinFock.Sparse0804 +OAI.Analysis.LaughlinFock.Sparse0805 +OAI.Analysis.LaughlinFock.Sparse0806 +OAI.Analysis.LaughlinFock.Sparse0807 +OAI.Analysis.LaughlinFock.Sparse0808 +OAI.Analysis.LaughlinFock.Sparse0809 +OAI.Analysis.LaughlinFock.Sparse0810 +OAI.Analysis.LaughlinFock.Sparse0811 +OAI.Analysis.LaughlinFock.Sparse0812 +OAI.Analysis.LaughlinFock.Sparse0813 +OAI.Analysis.LaughlinFock.Sparse0814 +OAI.Analysis.LaughlinFock.Sparse0815 +OAI.Analysis.LaughlinFock.Sparse0816 +OAI.Analysis.LaughlinFock.Sparse0817 +OAI.Analysis.LaughlinFock.Sparse0818 +OAI.Analysis.LaughlinFock.Sparse0819 +OAI.Analysis.LaughlinFock.Sparse0820 +OAI.Analysis.LaughlinFock.Sparse0821 +OAI.Analysis.LaughlinFock.Sparse0822 +OAI.Analysis.LaughlinFock.Sparse0823 +OAI.Analysis.LaughlinFock.Sparse0824 +OAI.Analysis.LaughlinFock.Sparse0825 +OAI.Analysis.LaughlinFock.Sparse0826 +OAI.Analysis.LaughlinFock.Sparse0827 +OAI.Analysis.LaughlinFock.Sparse0828 +OAI.Analysis.LaughlinFock.Sparse0829 +OAI.Analysis.LaughlinFock.Sparse0830 +OAI.Analysis.LaughlinFock.Sparse0831 +OAI.Analysis.LaughlinFock.Sparse0832 +OAI.Analysis.LaughlinFock.Sparse0833 +OAI.Analysis.LaughlinFock.Sparse0901 +OAI.Analysis.LaughlinFock.Sparse0902 +OAI.Analysis.LaughlinFock.Sparse0903 +OAI.Analysis.LaughlinFock.Sparse0904 +OAI.Analysis.LaughlinFock.Sparse0905 +OAI.Analysis.LaughlinFock.Sparse0906 +OAI.Analysis.LaughlinFock.Sparse0907 +OAI.Analysis.LaughlinFock.Sparse0908 +OAI.Analysis.LaughlinFock.Sparse0909 +OAI.Analysis.LaughlinFock.Sparse0910 +OAI.Analysis.LaughlinFock.Sparse0911 +OAI.Analysis.LaughlinFock.Sparse0912 +OAI.Analysis.LaughlinFock.Sparse0913 +OAI.Analysis.LaughlinFock.Sparse0914 +OAI.Analysis.LaughlinFock.Sparse0915 +OAI.Analysis.LaughlinFock.Sparse0916 +OAI.Analysis.LaughlinFock.Sparse0917 +OAI.Analysis.LaughlinFock.Sparse0918 +OAI.Analysis.LaughlinFock.Sparse0919 +OAI.Analysis.LaughlinFock.Sparse0920 +OAI.Analysis.LaughlinFock.Sparse0921 +OAI.Analysis.LaughlinFock.Sparse0922 +OAI.Analysis.LaughlinFock.Sparse0923 +OAI.Analysis.LaughlinFock.Sparse0924 +OAI.Analysis.LaughlinFock.Sparse0925 +OAI.Analysis.LaughlinFock.Sparse0926 +OAI.Analysis.LaughlinFock.Sparse0927 +OAI.Analysis.LaughlinFock.Sparse0928 +OAI.Analysis.LaughlinFock.Sparse0929 +OAI.Analysis.LaughlinFock.Sparse0930 +OAI.Analysis.LaughlinFock.Sparse1001 +OAI.Analysis.LaughlinFock.Sparse1002 +OAI.Analysis.LaughlinFock.Sparse1003 +OAI.Analysis.LaughlinFock.Sparse1004 +OAI.Analysis.LaughlinFock.Sparse1005 +OAI.Analysis.LaughlinFock.Sparse1006 +OAI.Analysis.LaughlinFock.Sparse1007 +OAI.Analysis.LaughlinFock.Sparse1008 +OAI.Analysis.LaughlinFock.Sparse1009 +OAI.Analysis.LaughlinFock.Sparse1010 +OAI.Analysis.LaughlinFock.Sparse1011 +OAI.Analysis.LaughlinFock.Sparse1012 +OAI.Analysis.LaughlinFock.Sparse1013 +OAI.Analysis.LaughlinFock.Sparse1014 +OAI.Analysis.LaughlinFock.Sparse1015 +OAI.Analysis.LaughlinFock.Sparse1016 +OAI.Analysis.LaughlinFock.Sparse1017 +OAI.Analysis.LaughlinFock.Sparse1018 +OAI.Analysis.LaughlinFock.Sparse1019 +OAI.Analysis.LaughlinFock.Sparse1020 +OAI.Analysis.LaughlinFock.Sparse1021 +OAI.Analysis.LaughlinFock.Sparse1022 +OAI.Analysis.LaughlinFock.Sparse1023 +OAI.Analysis.LaughlinFock.Sparse1024 +OAI.Analysis.LaughlinFock.Sparse1025 +OAI.Analysis.LaughlinFock.Sparse1026 +OAI.Analysis.LaughlinFock.Sparse1027 +OAI.Analysis.LaughlinFock.Sparse1101 +OAI.Analysis.LaughlinFock.Sparse1102 +OAI.Analysis.LaughlinFock.Sparse1103 +OAI.Analysis.LaughlinFock.Sparse1104 +OAI.Analysis.LaughlinFock.Sparse1105 +OAI.Analysis.LaughlinFock.Sparse1106 +OAI.Analysis.LaughlinFock.Sparse1107 +OAI.Analysis.LaughlinFock.Sparse1108 +OAI.Analysis.LaughlinFock.Sparse1109 +OAI.Analysis.LaughlinFock.Sparse1110 +OAI.Analysis.LaughlinFock.Sparse1111 +OAI.Analysis.LaughlinFock.Sparse1112 +OAI.Analysis.LaughlinFock.Sparse1113 +OAI.Analysis.LaughlinFock.Sparse1114 +OAI.Analysis.LaughlinFock.Sparse1115 +OAI.Analysis.LaughlinFock.Sparse1116 +OAI.Analysis.LaughlinFock.Sparse1117 +OAI.Analysis.LaughlinFock.Sparse1118 +OAI.Analysis.LaughlinFock.Sparse1119 +OAI.Analysis.LaughlinFock.Sparse1120 +OAI.Analysis.LaughlinFock.Sparse1121 +OAI.Analysis.LaughlinFock.Sparse1122 +OAI.Analysis.LaughlinFock.Sparse1123 +OAI.Analysis.LaughlinFock.Sparse1124 +OAI.Analysis.LaughlinFock.Sparse1301 +OAI.Analysis.LaughlinFock.Sparse1302 +OAI.Analysis.LaughlinFock.Sparse1303 +OAI.Analysis.LaughlinFock.Sparse1304 +OAI.Analysis.LaughlinFock.Sparse1305 +OAI.Analysis.LaughlinFock.Sparse1306 +OAI.Analysis.LaughlinFock.Sparse1307 +OAI.Analysis.LaughlinFock.Sparse1308 +OAI.Analysis.LaughlinFock.Sparse1309 +OAI.Analysis.LaughlinFock.Sparse1310 +OAI.Analysis.LaughlinFock.Sparse1311 +OAI.Analysis.LaughlinFock.Sparse1312 +OAI.Analysis.LaughlinFock.Sparse1313 +OAI.Analysis.LaughlinFock.Sparse1314 +OAI.Analysis.LaughlinFock.Sparse1315 +OAI.Analysis.LaughlinFock.Sparse1316 +OAI.Analysis.LaughlinFock.Sparse1317 +OAI.Analysis.LaughlinFock.Sparse1401 +OAI.Analysis.LaughlinFock.Sparse1402 +OAI.Analysis.LaughlinFock.Sparse1403 +OAI.Analysis.LaughlinFock.Sparse1404 +OAI.Analysis.LaughlinFock.Sparse1405 +OAI.Analysis.LaughlinFock.Sparse1406 +OAI.Analysis.LaughlinFock.Sparse1407 +OAI.Analysis.LaughlinFock.Sparse1408 +OAI.Analysis.LaughlinFock.Sparse1409 +OAI.Analysis.LaughlinFock.Sparse1410 +OAI.Analysis.LaughlinFock.Sparse1411 +OAI.Analysis.LaughlinFock.Sparse1412 +OAI.Analysis.LaughlinFock.Sparse1413 +OAI.Analysis.LaughlinFock.Sparse1501 +OAI.Analysis.LaughlinFock.Sparse1502 +OAI.Analysis.LaughlinFock.Sparse1503 +OAI.Analysis.LaughlinFock.Sparse1504 +OAI.Analysis.LaughlinFock.Sparse1505 +OAI.Analysis.LaughlinFock.Sparse1506 +OAI.Analysis.LaughlinFock.Sparse1507 +OAI.Analysis.LaughlinFock.Sparse1508 +OAI.Analysis.LaughlinFock.Sparse1601 +OAI.Analysis.LaughlinFock.Sparse1602 +OAI.Analysis.LaughlinFock.Sparse1603 +OAI.Analysis.LaughlinFock.Sparse1604 +OAI.Analysis.LaughlinFock.Sparse1605 +OAI.Analysis.LaughlinFock.Sparse1701 +OAI.Analysis.LaughlinFock.Sparse1702 +OAI.Analysis.LaughlinFock.Sparse1703 +OAI.Analysis.LaughlinFock.Sparse1801 +OAI.Analysis.LaughlinFock.Sparse1802 +OAI.Analysis.LaughlinFock.Sparse19 +OAI.Analysis.LaughlinFock.Sparse20 +OAI.Analysis.LaughlinFock.Sparse21 +OAI.Analysis.LaughlinFock.Sparse22 +OAI.Analysis.LaughlinFock.Sparse23 +OAI.Analysis.LaughlinFock.SparseTrace +OAI.Analysis.LaughlinFock.SphereScaling +OAI.Analysis.LaughlinFock.SpinSchur +OAI.Analysis.LaughlinFock.SpinTails +OAI.Analysis.LaughlinFock.SquareSplitting +OAI.Analysis.LaughlinFock.SwapCompression +OAI.Analysis.LaughlinFock.TableTrace +OAI.Analysis.LaughlinFock.TailOrbit +OAI.Analysis.LaughlinFock.TensorBasis +OAI.Analysis.LaughlinFock.ThreeCertificate +OAI.Analysis.LaughlinFock.ThreeGram +OAI.Analysis.LaughlinFock.ThreeOrbit +OAI.Analysis.LaughlinFock.ThreeRows +OAI.Analysis.LaughlinFock.ThreeSpectrum +OAI.Analysis.LaughlinFock.ThreeTraces +OAI.Analysis.LaughlinFock.TraceSymmetry +OAI.Analysis.LaughlinFock.WedgeLie diff --git a/tasks/laughlin-fock/solution/reference.py b/tasks/laughlin-fock/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/laughlin-fock/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/laughlin-fock/solution/solve.sh b/tasks/laughlin-fock/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4a30f1ba25fc2a6dae95270cfca6a26ff6f89aaa --- /dev/null +++ b/tasks/laughlin-fock/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LaughlinFock, i.e. module OAI.Analysis.LaughlinFock.Main and the +# 293 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LaughlinFock.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LaughlinFock" diff --git a/tasks/laughlin-fock/task.toml b/tasks/laughlin-fock/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f4a849c566eeb376be18f3dc47ecdd83956fb142 --- /dev/null +++ b/tasks/laughlin-fock/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/laughlin-fock" +version = "1.0.0" +description = "Prove LaughlinFock (openai/math family 269: The Laughlin gap and stability under scalar disorder) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LaughlinFock.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LaughlinFock" +family = "269" +family_title = "The Laughlin gap and stability under scalar disorder" +subject = "Mathematical physics" +theorems = ["OAI.LaughlinFock.thm_fock"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LaughlinFock.Main" +reference_modules = 293 +reference_lean_bytes = 8419306 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 6546 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19277 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/laughlin-fock/tests/Challenge.lean b/tasks/laughlin-fock/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..de3481d7be603f60000e70a9fc36050a44574b46 --- /dev/null +++ b/tasks/laughlin-fock/tests/Challenge.lean @@ -0,0 +1,66 @@ +import Mathlib + +namespace OAI + +/-! The spherical V₁ Hamiltonian inequality on the full fermionic Fock space. -/ + +noncomputable section + +namespace Laughlin + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + +end Laughlin + +run_cmd Lean.modifyEnv fun environment => Lean.Meta.auxLemmasExt.setState environment {} + +namespace LaughlinFock + +open scoped BigOperators Matrix ComplexConjugate ComplexOrder + +abbrev Orbital (Q : ℕ) := Fin (Q + 1) +abbrev Occupation (Q : ℕ) := Finset (Orbital Q) +abbrev FockMatrix (Q : ℕ) := Matrix (Occupation Q) (Occupation Q) ℂ + +def tensorPairCoefficient (Q p : ℕ) (i j : Orbital Q) : ℝ := + _root_.OAI.Laughlin.pairCoefficient Q p i j + +def pairCoefficient (Q p : ℕ) (i j : Orbital Q) : ℝ := + Real.sqrt 2 * tensorPairCoefficient Q p i j + +def annihilator (Q : ℕ) (j : Orbital Q) : FockMatrix Q := fun A B => + if j ∈ B ∧ A = B.erase j then + (-1 : ℂ) ^ (B.filter (fun i => i < j)).card + else 0 + +def pairAnnihilator (Q p : ℕ) : FockMatrix Q := + ∑ i : Orbital Q, ∑ j : Orbital Q, + if i < j then + (pairCoefficient Q p i j : ℂ) • (annihilator Q j * annihilator Q i) + else 0 + +def hamiltonian (Q : ℕ) : FockMatrix Q := + ∑ p ∈ Finset.range (2 * Q - 1), + (pairAnnihilator Q p)ᴴ * pairAnnihilator Q p + +def gammaStar : ℝ := 4616733319001 / 10 ^ 14 + +def FockInequality (Q : ℕ) (γ : ℝ) : Prop := + (hamiltonian Q * hamiltonian Q - γ • hamiltonian Q).PosSemidef + +theorem thm_fock (γ : ℝ) (hγ : 0 < γ) (hγStar : γ < gammaStar) : + ∃ Qγ : ℤ, 1 ≤ Qγ ∧ ∀ Q : ℤ, Qγ ≤ Q → FockInequality Q.toNat γ := by + sorry + +end LaughlinFock + +end + +end OAI diff --git a/tasks/laughlin-fock/tests/grade.py b/tasks/laughlin-fock/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/laughlin-fock/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/laughlin-fock/tests/task.json b/tasks/laughlin-fock/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..38f7b1100463f05de36ac63ab17c9f14d756e936 --- /dev/null +++ b/tasks/laughlin-fock/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LaughlinFock", + "comparator": { + "theorem_names": [ + "OAI.LaughlinFock.thm_fock" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18377 +} \ No newline at end of file diff --git a/tasks/laughlin-fock/tests/test.sh b/tasks/laughlin-fock/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/laughlin-fock/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/laughlin-gap/environment/Dockerfile b/tasks/laughlin-gap/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/laughlin-gap/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/laughlin-gap/environment/fetch_mathlib.sh b/tasks/laughlin-gap/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/laughlin-gap/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/laughlin-gap/environment/lake-manifest.json b/tasks/laughlin-gap/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/laughlin-gap/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/laughlin-gap/environment/lakefile.lean b/tasks/laughlin-gap/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/laughlin-gap/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/laughlin-gap/environment/lean_setup.sh b/tasks/laughlin-gap/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/laughlin-gap/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/laughlin-gap/environment/pack_submission.py b/tasks/laughlin-gap/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/laughlin-gap/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/laughlin-gap/instruction.md b/tasks/laughlin-gap/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26f68831151edd7c69fa4e5ef5546320a9dd24d8 --- /dev/null +++ b/tasks/laughlin-gap/instruction.md @@ -0,0 +1,134 @@ +# openai/math challenge `LaughlinGap` (family 269) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 269 of the release, *The Laughlin gap and stability under scalar disorder* +(Mathematical physics). The family as a whole: Proves the fermionic Laughlin spectral-gap conjecture for the full $V_1$ interaction at filling $1/3$ on the round sphere. The unique ground state remains uniformly gapped under sufficiently weak bounded real scalar one-body potentials projected to the lowest Landau level. Both the gap and disorder threshold are uniform over all sufficiently large particle numbers and all normalized potential profiles. + +The challenge is `LaughlinGap`, also at `/opt/openai-math/challenges/LaughlinGap.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators + +abbrev Configuration (N Q : ℕ) := Fin N → Fin (Q+1) +abbrev State (N Q : ℕ) := Configuration N Q → ℂ + + +def Antisymmetric {N Q : ℕ} (ψ : State N Q) : Prop := + ∀ (i j : Fin N), i ≠ j → ∀ a, ψ (a ∘ Equiv.swap i j) = -ψ a + + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + + + +noncomputable def pairAmplitude {N Q : ℕ} (ψ : State N Q) + (i j : Fin N) (p : ℕ) (a : Configuration N Q) : ℂ := + ∑ x : Fin (Q+1), ∑ y : Fin (Q+1), + (pairCoefficient Q p x y : ℂ) * ψ (Function.update (Function.update a i x) j y) + + + +noncomputable def energy {N Q : ℕ} (ψ : State N Q) : ℝ := + ∑ i : Fin N, ∑ j : Fin N, if i < j then + ∑ p ∈ Finset.range (2*Q-1), ∑ a : Configuration N Q, + if a i = 0 ∧ a j = 0 then ‖pairAmplitude ψ i j p a‖ ^ 2 else 0 + else 0 + +abbrev SpinorVariables (N : ℕ) := Fin N × Bool + + +noncomputable def bracket {N : ℕ} (i j : Fin N) : MvPolynomial (SpinorVariables N) ℂ := + MvPolynomial.X (i,false) * MvPolynomial.X (j,true) - + MvPolynomial.X (j,false) * MvPolynomial.X (i,true) + + +noncomputable def laughlinPolynomial (N : ℕ) : MvPolynomial (SpinorVariables N) ℂ := + ∏ i : Fin N, ∏ j : Fin N, if i < j then bracket i j ^ 3 else 1 + + +noncomputable def monomialExponent {N Q : ℕ} (a : Configuration N Q) : SpinorVariables N →₀ ℕ := + Finsupp.onFinset Finset.univ + (fun ib => if ib.2 then (a ib.1).val else Q - (a ib.1).val) + (by intro; simp) + + + +noncomputable def laughlinVector (N Q : ℕ) : State N Q := fun a => + (laughlinPolynomial N).coeff (monomialExponent a) / + ((∏ i : Fin N, Real.sqrt (Nat.choose Q (a i).val : ℝ) : ℝ) : ℂ) + + + +noncomputable def distanceToLaughlinSq {N Q : ℕ} (ψ : State N Q) : ℝ := + sInf (Set.range (fun c : ℂ => ∑ a : Configuration N Q, + ‖ψ a - c * laughlinVector N Q a‖ ^ 2)) +end Laughlin + +namespace LaughlinGap +export _root_.OAI.Laughlin (Configuration State Antisymmetric pairCoefficient pairAmplitude energy SpinorVariables bracket laughlinPolynomial monomialExponent laughlinVector distanceToLaughlinSq) + +def MainTarget : Prop := + ∃ N₀ : ℕ, 2 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∀ ψ : State N (3*(N-1)), Antisymmetric ψ → + (1/25 : ℝ) * distanceToLaughlinSq ψ ≤ energy ψ + +theorem thm_main : MainTarget := by + sorry + +end LaughlinGap + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LaughlinGap.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LaughlinGap.thm_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/laughlin-gap/solution/closure.txt b/tasks/laughlin-gap/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..aec5d648320cfbde5f0fa4f78953580b08dfea4a --- /dev/null +++ b/tasks/laughlin-gap/solution/closure.txt @@ -0,0 +1,106 @@ +OAI.Analysis.Laughlin.EnergyNonnegative +OAI.Analysis.Laughlin.Model +OAI.Analysis.LaughlinGap.AuxiliaryComparison +OAI.Analysis.LaughlinGap.Averaging +OAI.Analysis.LaughlinGap.Basic +OAI.Analysis.LaughlinGap.CachedIntegerRows +OAI.Analysis.LaughlinGap.Certificate10 +OAI.Analysis.LaughlinGap.Certificate11 +OAI.Analysis.LaughlinGap.Certificate12 +OAI.Analysis.LaughlinGap.Certificate13 +OAI.Analysis.LaughlinGap.Certificate14 +OAI.Analysis.LaughlinGap.Certificate15 +OAI.Analysis.LaughlinGap.Certificate16 +OAI.Analysis.LaughlinGap.Certificate17 +OAI.Analysis.LaughlinGap.Certificate18 +OAI.Analysis.LaughlinGap.Certificate19 +OAI.Analysis.LaughlinGap.Certificate20 +OAI.Analysis.LaughlinGap.Certificate21 +OAI.Analysis.LaughlinGap.Certificate22 +OAI.Analysis.LaughlinGap.Certificate23 +OAI.Analysis.LaughlinGap.Certificate5 +OAI.Analysis.LaughlinGap.Certificate6 +OAI.Analysis.LaughlinGap.Certificate7 +OAI.Analysis.LaughlinGap.Certificate8 +OAI.Analysis.LaughlinGap.Certificate9 +OAI.Analysis.LaughlinGap.CheckedTables +OAI.Analysis.LaughlinGap.Contraction +OAI.Analysis.LaughlinGap.CovariantFamily +OAI.Analysis.LaughlinGap.CovariantLift +OAI.Analysis.LaughlinGap.Creation +OAI.Analysis.LaughlinGap.ExactRows +OAI.Analysis.LaughlinGap.ExtendedPair +OAI.Analysis.LaughlinGap.ExteriorTermExpansion +OAI.Analysis.LaughlinGap.FastCoupling +OAI.Analysis.LaughlinGap.FastFourKeys +OAI.Analysis.LaughlinGap.Four +OAI.Analysis.LaughlinGap.FourAllowance +OAI.Analysis.LaughlinGap.FourAveraging +OAI.Analysis.LaughlinGap.FourBound +OAI.Analysis.LaughlinGap.FourBoundCore +OAI.Analysis.LaughlinGap.FourComparison +OAI.Analysis.LaughlinGap.FourHighest +OAI.Analysis.LaughlinGap.FourSpin +OAI.Analysis.LaughlinGap.FourTables +OAI.Analysis.LaughlinGap.FourTransfer +OAI.Analysis.LaughlinGap.GlobalBound +OAI.Analysis.LaughlinGap.GlobalBoundCore +OAI.Analysis.LaughlinGap.HighestRatios +OAI.Analysis.LaughlinGap.IntegerFourRows +OAI.Analysis.LaughlinGap.IntertwinerAveraging +OAI.Analysis.LaughlinGap.IntertwiningSpin +OAI.Analysis.LaughlinGap.IrrepAveraging +OAI.Analysis.LaughlinGap.LowNested +OAI.Analysis.LaughlinGap.Main +OAI.Analysis.LaughlinGap.NestedAveraging +OAI.Analysis.LaughlinGap.NestedSpin +OAI.Analysis.LaughlinGap.NormalOrder +OAI.Analysis.LaughlinGap.Occupation +OAI.Analysis.LaughlinGap.PairDecomposition +OAI.Analysis.LaughlinGap.PairEndpoints +OAI.Analysis.LaughlinGap.PairEnergy +OAI.Analysis.LaughlinGap.PairSpin +OAI.Analysis.LaughlinGap.PhysicalAveraging +OAI.Analysis.LaughlinGap.PhysicalSpinSpectrum +OAI.Analysis.LaughlinGap.RationalCoupling +OAI.Analysis.LaughlinGap.RationalCreatedGram +OAI.Analysis.LaughlinGap.RationalExterior +OAI.Analysis.LaughlinGap.RationalFourCertificate +OAI.Analysis.LaughlinGap.RationalFourCoefficients +OAI.Analysis.LaughlinGap.RationalFourComputable +OAI.Analysis.LaughlinGap.RationalFourRows +OAI.Analysis.LaughlinGap.RationalRowComputable +OAI.Analysis.LaughlinGap.RationalRows +OAI.Analysis.LaughlinGap.RealOccupation +OAI.Analysis.LaughlinGap.RealPositivity +OAI.Analysis.LaughlinGap.RealSpinSquare +OAI.Analysis.LaughlinGap.SpectralBound +OAI.Analysis.LaughlinGap.SpinAveraging +OAI.Analysis.LaughlinGap.SpinWork +OAI.Analysis.LaughlinGap.SumTable10 +OAI.Analysis.LaughlinGap.SumTable11 +OAI.Analysis.LaughlinGap.SumTable12 +OAI.Analysis.LaughlinGap.SumTable13 +OAI.Analysis.LaughlinGap.SumTable14 +OAI.Analysis.LaughlinGap.SumTable15 +OAI.Analysis.LaughlinGap.SumTable16 +OAI.Analysis.LaughlinGap.SumTable17 +OAI.Analysis.LaughlinGap.SumTable18 +OAI.Analysis.LaughlinGap.SumTable19 +OAI.Analysis.LaughlinGap.SumTable20 +OAI.Analysis.LaughlinGap.SumTable21 +OAI.Analysis.LaughlinGap.SumTable22 +OAI.Analysis.LaughlinGap.SumTable23 +OAI.Analysis.LaughlinGap.SumTable5 +OAI.Analysis.LaughlinGap.SumTable7 +OAI.Analysis.LaughlinGap.SumTable8 +OAI.Analysis.LaughlinGap.SumTable9 +OAI.Analysis.LaughlinGap.TensorSpin +OAI.Analysis.LaughlinGap.ThreeAveraging +OAI.Analysis.LaughlinGap.ThreeBounds +OAI.Analysis.LaughlinGap.ThreeComparison +OAI.Analysis.LaughlinGap.ThreeGram +OAI.Analysis.LaughlinGap.ThreeSpectrum +OAI.Analysis.LaughlinGap.ThreeSpin +OAI.Analysis.LaughlinGap.WedgeIdentification +OAI.Analysis.LaughlinGap.ZeroCertificates diff --git a/tasks/laughlin-gap/solution/reference.py b/tasks/laughlin-gap/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/laughlin-gap/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/laughlin-gap/solution/solve.sh b/tasks/laughlin-gap/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e0f895a633a3b9a619d5613e687dcc3afcc3c95a --- /dev/null +++ b/tasks/laughlin-gap/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LaughlinGap, i.e. module OAI.Analysis.LaughlinGap.Main and the +# 106 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LaughlinGap.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LaughlinGap" diff --git a/tasks/laughlin-gap/task.toml b/tasks/laughlin-gap/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8abe6a2b531b5dceceaa2a596935330033b39077 --- /dev/null +++ b/tasks/laughlin-gap/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/laughlin-gap" +version = "1.0.0" +description = "Prove LaughlinGap (openai/math family 269: The Laughlin gap and stability under scalar disorder) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LaughlinGap.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LaughlinGap" +family = "269" +family_title = "The Laughlin gap and stability under scalar disorder" +subject = "Mathematical physics" +theorems = ["OAI.LaughlinGap.thm_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LaughlinGap.Main" +reference_modules = 106 +reference_lean_bytes = 2339387 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 5587 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13805 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/laughlin-gap/tests/Challenge.lean b/tasks/laughlin-gap/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4512a852b1f35ec8055a31d3e18ed7b615ee772f --- /dev/null +++ b/tasks/laughlin-gap/tests/Challenge.lean @@ -0,0 +1,83 @@ +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators + +abbrev Configuration (N Q : ℕ) := Fin N → Fin (Q+1) +abbrev State (N Q : ℕ) := Configuration N Q → ℂ + + +def Antisymmetric {N Q : ℕ} (ψ : State N Q) : Prop := + ∀ (i j : Fin N), i ≠ j → ∀ a, ψ (a ∘ Equiv.swap i j) = -ψ a + + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + + + +noncomputable def pairAmplitude {N Q : ℕ} (ψ : State N Q) + (i j : Fin N) (p : ℕ) (a : Configuration N Q) : ℂ := + ∑ x : Fin (Q+1), ∑ y : Fin (Q+1), + (pairCoefficient Q p x y : ℂ) * ψ (Function.update (Function.update a i x) j y) + + + +noncomputable def energy {N Q : ℕ} (ψ : State N Q) : ℝ := + ∑ i : Fin N, ∑ j : Fin N, if i < j then + ∑ p ∈ Finset.range (2*Q-1), ∑ a : Configuration N Q, + if a i = 0 ∧ a j = 0 then ‖pairAmplitude ψ i j p a‖ ^ 2 else 0 + else 0 + +abbrev SpinorVariables (N : ℕ) := Fin N × Bool + + +noncomputable def bracket {N : ℕ} (i j : Fin N) : MvPolynomial (SpinorVariables N) ℂ := + MvPolynomial.X (i,false) * MvPolynomial.X (j,true) - + MvPolynomial.X (j,false) * MvPolynomial.X (i,true) + + +noncomputable def laughlinPolynomial (N : ℕ) : MvPolynomial (SpinorVariables N) ℂ := + ∏ i : Fin N, ∏ j : Fin N, if i < j then bracket i j ^ 3 else 1 + + +noncomputable def monomialExponent {N Q : ℕ} (a : Configuration N Q) : SpinorVariables N →₀ ℕ := + Finsupp.onFinset Finset.univ + (fun ib => if ib.2 then (a ib.1).val else Q - (a ib.1).val) + (by intro; simp) + + + +noncomputable def laughlinVector (N Q : ℕ) : State N Q := fun a => + (laughlinPolynomial N).coeff (monomialExponent a) / + ((∏ i : Fin N, Real.sqrt (Nat.choose Q (a i).val : ℝ) : ℝ) : ℂ) + + + +noncomputable def distanceToLaughlinSq {N Q : ℕ} (ψ : State N Q) : ℝ := + sInf (Set.range (fun c : ℂ => ∑ a : Configuration N Q, + ‖ψ a - c * laughlinVector N Q a‖ ^ 2)) +end Laughlin + +namespace LaughlinGap +export _root_.OAI.Laughlin (Configuration State Antisymmetric pairCoefficient pairAmplitude energy SpinorVariables bracket laughlinPolynomial monomialExponent laughlinVector distanceToLaughlinSq) + +def MainTarget : Prop := + ∃ N₀ : ℕ, 2 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∀ ψ : State N (3*(N-1)), Antisymmetric ψ → + (1/25 : ℝ) * distanceToLaughlinSq ψ ≤ energy ψ + +theorem thm_main : MainTarget := by + sorry + +end LaughlinGap + +end OAI diff --git a/tasks/laughlin-gap/tests/grade.py b/tasks/laughlin-gap/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/laughlin-gap/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/laughlin-gap/tests/task.json b/tasks/laughlin-gap/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..494bd10b639ca8ff9299b5d8f79b90aa5cd2d139 --- /dev/null +++ b/tasks/laughlin-gap/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LaughlinGap", + "comparator": { + "theorem_names": [ + "OAI.LaughlinGap.thm_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12905 +} \ No newline at end of file diff --git a/tasks/laughlin-gap/tests/test.sh b/tasks/laughlin-gap/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/laughlin-gap/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/laughlin-planar/environment/Dockerfile b/tasks/laughlin-planar/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/laughlin-planar/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/laughlin-planar/environment/fetch_mathlib.sh b/tasks/laughlin-planar/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/laughlin-planar/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/laughlin-planar/environment/lake-manifest.json b/tasks/laughlin-planar/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/laughlin-planar/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/laughlin-planar/environment/lakefile.lean b/tasks/laughlin-planar/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/laughlin-planar/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/laughlin-planar/environment/lean_setup.sh b/tasks/laughlin-planar/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/laughlin-planar/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/laughlin-planar/environment/pack_submission.py b/tasks/laughlin-planar/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/laughlin-planar/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/laughlin-planar/instruction.md b/tasks/laughlin-planar/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..63e8873d4fee327433726d18bc099362e97a6e01 --- /dev/null +++ b/tasks/laughlin-planar/instruction.md @@ -0,0 +1,133 @@ +# openai/math challenge `LaughlinPlanar` (family 269) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 269 of the release, *The Laughlin gap and stability under scalar disorder* +(Mathematical physics). The family as a whole: Proves the fermionic Laughlin spectral-gap conjecture for the full $V_1$ interaction at filling $1/3$ on the round sphere. The unique ground state remains uniformly gapped under sufficiently weak bounded real scalar one-body potentials projected to the lowest Landau level. Both the gap and disorder threshold are uniform over all sufficiently large particle numbers and all normalized potential profiles. + +The challenge is `LaughlinPlanar`, also at `/opt/openai-math/challenges/LaughlinPlanar.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators Matrix ENNReal + +noncomputable def gammaStar : ℝ := 4616733319001 / 10^14 + +noncomputable def pairLimitCoefficient (p x y : ℕ) : ℝ := + if x+y = p+1 then + ((x : ℝ)-(y : ℝ)) * Real.sqrt ((p.factorial : ℝ) / + (((2 : ℕ) : ℝ)^p * (x.factorial : ℝ) * (y.factorial : ℝ))) / Real.sqrt (2 : ℕ) + else 0 + +namespace Fock + +abbrev Orbital (Q : ℕ) := Fin (Q+1) → ℂ +abbrev Space (Q : ℕ) := ExteriorAlgebra ℂ (Orbital Q) + +noncomputable def annihilate {Q : ℕ} (i : Fin (Q+1)) : Module.End ℂ (Space Q) := + CliffordAlgebra.contractLeft (Q := (0 : QuadraticForm ℂ (Orbital Q))) (LinearMap.proj i) + +noncomputable def occupationBasis (Q : ℕ) : + Module.Basis (Finset (Fin (Q+1))) ℂ (Space Q) := + (Pi.basisFun ℂ (Fin (Q+1))).ExteriorAlgebra + +def OccupationBidegree (Q n w : ℕ) (x : Space Q) : Prop := + ∀ A : Finset (Fin (Q+1)), (A.card ≠ n ∨ (∑ i ∈ A, i.val) ≠ w) → + (occupationBasis Q).repr x A = 0 + +end Fock + +namespace Planar +open Fock + +abbrev Occupations (L : ℕ) := Finset (Fin (L+1)) + +noncomputable def pairMatrix (L : ℕ) (c : Fin (L+1) → Fin (L+1) → ℂ) : + Matrix (Occupations L) (Occupations L) ℂ := fun A B => + ∑ i, ∑ j, c i j * (occupationBasis L).repr + (annihilate j (annihilate i (occupationBasis L B))) A + +noncomputable def planarCoefficient (p i j : ℕ) : ℂ := + ((pairLimitCoefficient p i j / Real.sqrt (2 : ℕ) : ℝ) : ℂ) + +noncomputable def planarPairMatrix (L p : ℕ) : Matrix (Occupations L) (Occupations L) ℂ := + pairMatrix L (fun i j => planarCoefficient p i.val j.val) + +noncomputable def planarHamiltonian (L : ℕ) : Matrix (Occupations L) (Occupations L) ℂ := + ∑ p ∈ Finset.range (2*L+1), (planarPairMatrix L p)ᴴ * planarPairMatrix L p + +noncomputable def pairEnergy (L : ℕ) + (P : ℕ → Matrix (Occupations L) (Occupations L) ℂ) (x : Occupations L → ℂ) : ℝ := + ∑ p ∈ Finset.range (2*L+1), ∑ A, ‖(P p *ᵥ x) A‖^2 + +noncomputable def squareNorm (L : ℕ) (H : Matrix (Occupations L) (Occupations L) ℂ) + (x : Occupations L → ℂ) : ℝ := ∑ A, ‖(H *ᵥ x) A‖^2 + +/-- Occupation coefficients with fixed particle number in every homogeneous degree. -/ +structure HomogeneousState (N : ℕ) where + block : (L : ℕ) → Space L + homogeneous : ∀ L, OccupationBidegree L N L (block L) + +noncomputable def fullEnergy {N : ℕ} (ψ : HomogeneousState N) : ℝ≥0∞ := + ∑' L, ENNReal.ofReal (pairEnergy L (planarPairMatrix L) + (fun A => (occupationBasis L).repr (ψ.block L) A)) + +noncomputable def fullSquareNorm {N : ℕ} (ψ : HomogeneousState N) : ℝ≥0∞ := + ∑' L, ENNReal.ofReal (squareNorm L (planarHamiltonian L) + (fun A => (occupationBasis L).repr (ψ.block L) A)) + +end Planar + +/-- The planar endpoint inequality in the homogeneous occupation representation. -/ +theorem planar_gap {N : ℕ} (ψ : Planar.HomogeneousState N) : + ENNReal.ofReal gammaStar * Planar.fullEnergy ψ ≤ Planar.fullSquareNorm ψ := by + sorry + +end Laughlin + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LaughlinPlanar.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Laughlin.planar_gap` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/laughlin-planar/solution/closure.txt b/tasks/laughlin-planar/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dfacaf6900f0288527efe70382b12cbfd8ab7e3d --- /dev/null +++ b/tasks/laughlin-planar/solution/closure.txt @@ -0,0 +1,1279 @@ +OAI.Analysis.Laughlin.Asymptotics.Basic +OAI.Analysis.Laughlin.Asymptotics.Bound +OAI.Analysis.Laughlin.Asymptotics.Convergence +OAI.Analysis.Laughlin.Asymptotics.FiniteReindex +OAI.Analysis.Laughlin.Asymptotics.HighestCouplingLimit +OAI.Analysis.Laughlin.Asymptotics.Limit +OAI.Analysis.Laughlin.Asymptotics.LimitFourLocalSum +OAI.Analysis.Laughlin.Asymptotics.LocalDiagonalLimit +OAI.Analysis.Laughlin.Asymptotics.LocalMetricLimit +OAI.Analysis.Laughlin.Asymptotics.Perturbation +OAI.Analysis.Laughlin.Asymptotics.ScalarBudget +OAI.Analysis.Laughlin.Asymptotics.TruncatedMetricPerturbation +OAI.Analysis.Laughlin.Asymptotics.TruncatedScaling +OAI.Analysis.Laughlin.Asymptotics.UpperSpinCurve +OAI.Analysis.Laughlin.Asymptotics.UpperSpinDynamics +OAI.Analysis.Laughlin.Charge.Comparison +OAI.Analysis.Laughlin.Charge.FiniteGap +OAI.Analysis.Laughlin.Charge.LaughlinGround +OAI.Analysis.Laughlin.Charge.Model +OAI.Analysis.Laughlin.Charge.Number +OAI.Analysis.Laughlin.Charge.Overlap +OAI.Analysis.Laughlin.Charge.Recursion +OAI.Analysis.Laughlin.Charge.Sectors +OAI.Analysis.Laughlin.Charge.Tensor +OAI.Analysis.Laughlin.Charge.UniformGap +OAI.Analysis.Laughlin.EnergyNonnegative +OAI.Analysis.Laughlin.Exterior.FamilyCovariance +OAI.Analysis.Laughlin.Exterior.FourConjugation +OAI.Analysis.Laughlin.Exterior.OccupationDiagonal +OAI.Analysis.Laughlin.Exterior.OccupationMetric +OAI.Analysis.Laughlin.Exterior.PairConjugation +OAI.Analysis.Laughlin.Exterior.Scaling +OAI.Analysis.Laughlin.Exterior.ScalingWedge +OAI.Analysis.Laughlin.Exterior.SpinAction +OAI.Analysis.Laughlin.Exterior.SpinUnitary +OAI.Analysis.Laughlin.Exterior.VectorAdjoint +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram111112 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram131313 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram131314 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram151515 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram151516 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram171717 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram171718 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram191919 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram191920 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram212121 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram212122 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram21Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram232323 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL050511 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL11Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0523Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0723Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow092 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0923Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow093 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow102 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow103 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow112 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow113 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow114 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow115 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1523Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1723Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1923Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.Data09 +OAI.Analysis.Laughlin.FiniteFlux.Data10 +OAI.Analysis.Laughlin.FiniteFlux.Data11 +OAI.Analysis.Laughlin.FiniteFlux.Data12 +OAI.Analysis.Laughlin.FiniteFlux.Data13 +OAI.Analysis.Laughlin.FiniteFlux.Data14 +OAI.Analysis.Laughlin.FiniteFlux.Data15 +OAI.Analysis.Laughlin.FiniteFlux.Data16 +OAI.Analysis.Laughlin.FiniteFlux.Data17 +OAI.Analysis.Laughlin.FiniteFlux.Data18 +OAI.Analysis.Laughlin.FiniteFlux.Data19 +OAI.Analysis.Laughlin.FiniteFlux.Data20 +OAI.Analysis.Laughlin.FiniteFlux.Data21 +OAI.Analysis.Laughlin.FiniteFlux.Data22 +OAI.Analysis.Laughlin.FiniteFlux.Data23 +OAI.Analysis.Laughlin.FiniteFlux.Error05 +OAI.Analysis.Laughlin.FiniteFlux.Error07 +OAI.Analysis.Laughlin.FiniteFlux.Error08 +OAI.Analysis.Laughlin.FiniteFlux.Gram07 +OAI.Analysis.Laughlin.FiniteFlux.Gram072 +OAI.Analysis.Laughlin.FiniteFlux.Gram08 +OAI.Analysis.Laughlin.FiniteFlux.Gram082 +OAI.Analysis.Laughlin.FiniteFlux.GramData09 +OAI.Analysis.Laughlin.FiniteFlux.GramData10 +OAI.Analysis.Laughlin.FiniteFlux.GramData11 +OAI.Analysis.Laughlin.FiniteFlux.GramData12 +OAI.Analysis.Laughlin.FiniteFlux.GramData13 +OAI.Analysis.Laughlin.FiniteFlux.GramData14 +OAI.Analysis.Laughlin.FiniteFlux.GramData15 +OAI.Analysis.Laughlin.FiniteFlux.GramData16 +OAI.Analysis.Laughlin.FiniteFlux.GramData17 +OAI.Analysis.Laughlin.FiniteFlux.GramData18 +OAI.Analysis.Laughlin.FiniteFlux.GramData19 +OAI.Analysis.Laughlin.FiniteFlux.GramData20 +OAI.Analysis.Laughlin.FiniteFlux.GramData21 +OAI.Analysis.Laughlin.FiniteFlux.GramData22 +OAI.Analysis.Laughlin.FiniteFlux.GramData23 +OAI.Analysis.Laughlin.FiniteFlux.LDL08 +OAI.Analysis.Laughlin.FiniteFlux.LDLData08 +OAI.Analysis.Laughlin.FiniteFlux.LDLData09 +OAI.Analysis.Laughlin.FiniteFlux.LDLData10 +OAI.Analysis.Laughlin.FiniteFlux.LDLData11 +OAI.Analysis.Laughlin.FiniteFlux.LDLData12 +OAI.Analysis.Laughlin.FiniteFlux.LDLData13 +OAI.Analysis.Laughlin.FiniteFlux.LDLData14 +OAI.Analysis.Laughlin.FiniteFlux.LDLData15 +OAI.Analysis.Laughlin.FiniteFlux.LDLData16 +OAI.Analysis.Laughlin.FiniteFlux.LDLData17 +OAI.Analysis.Laughlin.FiniteFlux.LDLData18 +OAI.Analysis.Laughlin.FiniteFlux.LDLData19 +OAI.Analysis.Laughlin.FiniteFlux.LDLData20 +OAI.Analysis.Laughlin.FiniteFlux.LDLData21 +OAI.Analysis.Laughlin.FiniteFlux.LDLData22 +OAI.Analysis.Laughlin.FiniteFlux.LDLData23 +OAI.Analysis.Laughlin.FiniteFlux.Positive05 +OAI.Analysis.Laughlin.FiniteFlux.Positive07 +OAI.Analysis.Laughlin.FiniteFlux.Positive08 +OAI.Analysis.Laughlin.FiniteFlux.Positive09 +OAI.Analysis.Laughlin.FiniteFlux.Positive10 +OAI.Analysis.Laughlin.FiniteFlux.Positive11 +OAI.Analysis.Laughlin.FiniteFlux.Positive12 +OAI.Analysis.Laughlin.FiniteFlux.Positive13 +OAI.Analysis.Laughlin.FiniteFlux.Positive14 +OAI.Analysis.Laughlin.FiniteFlux.Positive15 +OAI.Analysis.Laughlin.FiniteFlux.Positive16 +OAI.Analysis.Laughlin.FiniteFlux.Positive17 +OAI.Analysis.Laughlin.FiniteFlux.Positive18 +OAI.Analysis.Laughlin.FiniteFlux.Positive19 +OAI.Analysis.Laughlin.FiniteFlux.Positive20 +OAI.Analysis.Laughlin.FiniteFlux.Positive21 +OAI.Analysis.Laughlin.FiniteFlux.Positive22 +OAI.Analysis.Laughlin.FiniteFlux.Positive23 +OAI.Analysis.Laughlin.FiniteFlux.Quadruples08 +OAI.Analysis.Laughlin.FiniteFlux.Row0301007 +OAI.Analysis.Laughlin.FiniteFlux.Row0301107 +OAI.Analysis.Laughlin.FiniteFlux.Row0301207 +OAI.Analysis.Laughlin.FiniteFlux.Row0301307 +OAI.Analysis.Laughlin.FiniteFlux.Row0301407 +OAI.Analysis.Laughlin.FiniteFlux.Row0301507 +OAI.Analysis.Laughlin.FiniteFlux.Row0301607 +OAI.Analysis.Laughlin.FiniteFlux.Row05 +OAI.Analysis.Laughlin.FiniteFlux.Row0501007 +OAI.Analysis.Laughlin.FiniteFlux.Row0501107 +OAI.Analysis.Laughlin.FiniteFlux.Row0501207 +OAI.Analysis.Laughlin.FiniteFlux.Row0501307 +OAI.Analysis.Laughlin.FiniteFlux.Row0501407 +OAI.Analysis.Laughlin.FiniteFlux.Row0501507 +OAI.Analysis.Laughlin.FiniteFlux.Row0501607 +OAI.Analysis.Laughlin.FiniteFlux.Row0503007 +OAI.Analysis.Laughlin.FiniteFlux.Row0503107 +OAI.Analysis.Laughlin.FiniteFlux.Row0503207 +OAI.Analysis.Laughlin.FiniteFlux.Row0503307 +OAI.Analysis.Laughlin.FiniteFlux.Row0503407 +OAI.Analysis.Laughlin.FiniteFlux.Row0503507 +OAI.Analysis.Laughlin.FiniteFlux.Row0503607 +OAI.Analysis.Laughlin.FiniteFlux.Row052 +OAI.Analysis.Laughlin.FiniteFlux.Row07 +OAI.Analysis.Laughlin.FiniteFlux.Row0701007 +OAI.Analysis.Laughlin.FiniteFlux.Row0701107 +OAI.Analysis.Laughlin.FiniteFlux.Row0701207 +OAI.Analysis.Laughlin.FiniteFlux.Row0701307 +OAI.Analysis.Laughlin.FiniteFlux.Row0701407 +OAI.Analysis.Laughlin.FiniteFlux.Row0701507 +OAI.Analysis.Laughlin.FiniteFlux.Row0701607 +OAI.Analysis.Laughlin.FiniteFlux.Row0703007 +OAI.Analysis.Laughlin.FiniteFlux.Row0703107 +OAI.Analysis.Laughlin.FiniteFlux.Row0703207 +OAI.Analysis.Laughlin.FiniteFlux.Row0703307 +OAI.Analysis.Laughlin.FiniteFlux.Row0703407 +OAI.Analysis.Laughlin.FiniteFlux.Row0703507 +OAI.Analysis.Laughlin.FiniteFlux.Row0703607 +OAI.Analysis.Laughlin.FiniteFlux.Row0705007 +OAI.Analysis.Laughlin.FiniteFlux.Row0705107 +OAI.Analysis.Laughlin.FiniteFlux.Row0705207 +OAI.Analysis.Laughlin.FiniteFlux.Row0705307 +OAI.Analysis.Laughlin.FiniteFlux.Row0705407 +OAI.Analysis.Laughlin.FiniteFlux.Row0705507 +OAI.Analysis.Laughlin.FiniteFlux.Row0705607 +OAI.Analysis.Laughlin.FiniteFlux.Row072 +OAI.Analysis.Laughlin.FiniteFlux.Row073 +OAI.Analysis.Laughlin.FiniteFlux.Row08 +OAI.Analysis.Laughlin.FiniteFlux.Row082 +OAI.Analysis.Laughlin.FiniteFlux.Row083 +OAI.Analysis.Laughlin.Fock.Adjoint +OAI.Analysis.Laughlin.Fock.Annihilation +OAI.Analysis.Laughlin.Fock.Bidegree +OAI.Analysis.Laughlin.Fock.ContractionBound +OAI.Analysis.Laughlin.Fock.Coordinates +OAI.Analysis.Laughlin.Fock.Creation +OAI.Analysis.Laughlin.Fock.EigenvalueGap +OAI.Analysis.Laughlin.Fock.EnergyRotation +OAI.Analysis.Laughlin.Fock.FourLabels +OAI.Analysis.Laughlin.Fock.HaarQuadratic +OAI.Analysis.Laughlin.Fock.Hamiltonian +OAI.Analysis.Laughlin.Fock.Inner +OAI.Analysis.Laughlin.Fock.LaughlinGap +OAI.Analysis.Laughlin.Fock.MatrixQuadratic +OAI.Analysis.Laughlin.Fock.ModeEmbedding +OAI.Analysis.Laughlin.Fock.NormalSquare +OAI.Analysis.Laughlin.Fock.OrbitIntegration +OAI.Analysis.Laughlin.Fock.PairNormalization +OAI.Analysis.Laughlin.Fock.Perturbation +OAI.Analysis.Laughlin.Fock.Quadruple +OAI.Analysis.Laughlin.Fock.RankOneHaar +OAI.Analysis.Laughlin.Fock.SharpGap +OAI.Analysis.Laughlin.Fock.SpectralDistance +OAI.Analysis.Laughlin.Fock.SpinContinuity +OAI.Analysis.Laughlin.Fock.SpinRepresentation +OAI.Analysis.Laughlin.Fock.UnitaryFamilies +OAI.Analysis.Laughlin.FourBody.All +OAI.Analysis.Laughlin.FourBody.Assembly +OAI.Analysis.Laughlin.FourBody.Basic +OAI.Analysis.Laughlin.FourBody.BesselAllowance +OAI.Analysis.Laughlin.FourBody.CARReadout +OAI.Analysis.Laughlin.FourBody.CoefficientLimit +OAI.Analysis.Laughlin.FourBody.CoefficientNorm +OAI.Analysis.Laughlin.FourBody.Coefficients +OAI.Analysis.Laughlin.FourBody.ColumnExpansion +OAI.Analysis.Laughlin.FourBody.Copies +OAI.Analysis.Laughlin.FourBody.CopyAlgebra +OAI.Analysis.Laughlin.FourBody.CopyFormAllowance +OAI.Analysis.Laughlin.FourBody.CopyOperatorHaar +OAI.Analysis.Laughlin.FourBody.CopyOrthogonality +OAI.Analysis.Laughlin.FourBody.CoupledBasis +OAI.Analysis.Laughlin.FourBody.EndExpansion +OAI.Analysis.Laughlin.FourBody.ErrorCertificate +OAI.Analysis.Laughlin.FourBody.ErrorLimit +OAI.Analysis.Laughlin.FourBody.ErrorMatrix +OAI.Analysis.Laughlin.FourBody.Estimate +OAI.Analysis.Laughlin.FourBody.Expansion +OAI.Analysis.Laughlin.FourBody.FactorialCoefficient +OAI.Analysis.Laughlin.FourBody.Fast +OAI.Analysis.Laughlin.FourBody.FastChoose +OAI.Analysis.Laughlin.FourBody.FockCovariance +OAI.Analysis.Laughlin.FourBody.Formula +OAI.Analysis.Laughlin.FourBody.GlobalFock +OAI.Analysis.Laughlin.FourBody.GlobalHaar +OAI.Analysis.Laughlin.FourBody.GramCompute +OAI.Analysis.Laughlin.FourBody.GroupIntertwining +OAI.Analysis.Laughlin.FourBody.HaarAllowance +OAI.Analysis.Laughlin.FourBody.HaarTransfer +OAI.Analysis.Laughlin.FourBody.Hermitian +OAI.Analysis.Laughlin.FourBody.HighestFock +OAI.Analysis.Laughlin.FourBody.Integral +OAI.Analysis.Laughlin.FourBody.Levels +OAI.Analysis.Laughlin.FourBody.LimitCARReadout +OAI.Analysis.Laughlin.FourBody.LimitPositive +OAI.Analysis.Laughlin.FourBody.LocalNormalization +OAI.Analysis.Laughlin.FourBody.Matrix +OAI.Analysis.Laughlin.FourBody.MatrixCompute +OAI.Analysis.Laughlin.FourBody.MiddleForm +OAI.Analysis.Laughlin.FourBody.MiddleLimit +OAI.Analysis.Laughlin.FourBody.MultiplicityHaar +OAI.Analysis.Laughlin.FourBody.NormalForm +OAI.Analysis.Laughlin.FourBody.NumericBridge +OAI.Analysis.Laughlin.FourBody.OccupationCoefficient +OAI.Analysis.Laughlin.FourBody.PairTarget +OAI.Analysis.Laughlin.FourBody.Parity +OAI.Analysis.Laughlin.FourBody.PhysicalAllowance +OAI.Analysis.Laughlin.FourBody.PhysicalCertificate +OAI.Analysis.Laughlin.FourBody.PhysicalColumn +OAI.Analysis.Laughlin.FourBody.PhysicalGram +OAI.Analysis.Laughlin.FourBody.PhysicalMatrix +OAI.Analysis.Laughlin.FourBody.PhysicalSlaterReadout +OAI.Analysis.Laughlin.FourBody.PhysicalTrace +OAI.Analysis.Laughlin.FourBody.Quadruples +OAI.Analysis.Laughlin.FourBody.RadicalCancellation +OAI.Analysis.Laughlin.FourBody.RadicalCoefficient +OAI.Analysis.Laughlin.FourBody.RetainedComparison +OAI.Analysis.Laughlin.FourBody.RetainedInclusions +OAI.Analysis.Laughlin.FourBody.RetainedIndex +OAI.Analysis.Laughlin.FourBody.RetainedReconstruction +OAI.Analysis.Laughlin.FourBody.RetainedSum +OAI.Analysis.Laughlin.FourBody.RowBridge +OAI.Analysis.Laughlin.FourBody.RowCompute +OAI.Analysis.Laughlin.FourBody.Scaled +OAI.Analysis.Laughlin.FourBody.ScaledAll +OAI.Analysis.Laughlin.FourBody.SignedCoordinates +OAI.Analysis.Laughlin.FourBody.SlaterCoefficient +OAI.Analysis.Laughlin.FourBody.SlaterRadical +OAI.Analysis.Laughlin.FourBody.SliceCoefficient +OAI.Analysis.Laughlin.FourBody.Square +OAI.Analysis.Laughlin.FourBody.Support +OAI.Analysis.Laughlin.FourBody.Symmetry +OAI.Analysis.Laughlin.FourBody.TargetBound +OAI.Analysis.Laughlin.FourBody.TargetResolution +OAI.Analysis.Laughlin.FourBody.TensorIntertwining +OAI.Analysis.Laughlin.FourBody.TotalAllowance +OAI.Analysis.Laughlin.FourBody.TotalTransfer +OAI.Analysis.Laughlin.FourBody.TraceReadout +OAI.Analysis.Laughlin.FourBody.TransferCoefficients +OAI.Analysis.Laughlin.FourBody.TransferConjugation +OAI.Analysis.Laughlin.FourBody.Ungroup +OAI.Analysis.Laughlin.FourBody.UniformTransfer +OAI.Analysis.Laughlin.FourBody.WedgeCompression +OAI.Analysis.Laughlin.FourBody.WeightSlice +OAI.Analysis.Laughlin.FourBody.WeightedReadout +OAI.Analysis.Laughlin.GapEstimates +OAI.Analysis.Laughlin.Main +OAI.Analysis.Laughlin.Model +OAI.Analysis.Laughlin.Operators.CAR +OAI.Analysis.Laughlin.Operators.Certificate +OAI.Analysis.Laughlin.Operators.CollectionAnnihilatorBound +OAI.Analysis.Laughlin.Operators.ComplexCompression +OAI.Analysis.Laughlin.Operators.CopyQuadraticMatrix +OAI.Analysis.Laughlin.Operators.Energy +OAI.Analysis.Laughlin.Operators.FourOccupationEquiv +OAI.Analysis.Laughlin.Operators.GenericPhysicalResolution +OAI.Analysis.Laughlin.Operators.GlobalPairCube +OAI.Analysis.Laughlin.Operators.GramReadout +OAI.Analysis.Laughlin.Operators.LocalFourCardinality +OAI.Analysis.Laughlin.Operators.LocalFourIndexEquiv +OAI.Analysis.Laughlin.Operators.MatrixCongruence +OAI.Analysis.Laughlin.Operators.MatrixMetricError +OAI.Analysis.Laughlin.Operators.MatrixPhysicalCompression +OAI.Analysis.Laughlin.Operators.NormalCertificate +OAI.Analysis.Laughlin.Operators.NormalOrder +OAI.Analysis.Laughlin.Operators.NormalOrderFour +OAI.Analysis.Laughlin.Operators.OrthonormalRows +OAI.Analysis.Laughlin.Operators.PairNormalOrder +OAI.Analysis.Laughlin.Operators.PhysicalCoupling +OAI.Analysis.Laughlin.Operators.PhysicalFockGap +OAI.Analysis.Laughlin.Operators.PhysicalPairCounting +OAI.Analysis.Laughlin.Operators.PhysicalPairKernel +OAI.Analysis.Laughlin.Operators.PhysicalPairRotation +OAI.Analysis.Laughlin.Operators.PositiveFockLift +OAI.Analysis.Laughlin.Operators.RationalPSD +OAI.Analysis.Laughlin.Operators.RealComplexMatrixPositive +OAI.Analysis.Laughlin.Operators.RowNormalSquare +OAI.Analysis.Laughlin.Operators.SevenSquareAverage +OAI.Analysis.Laughlin.Operators.SpectralKernelDistance +OAI.Analysis.Laughlin.Operators.SymmetricPairSum +OAI.Analysis.Laughlin.Operators.TruncatedConjugation +OAI.Analysis.Laughlin.Operators.TruncatedFourCopy +OAI.Analysis.Laughlin.Operators.TruncatedPairReturn +OAI.Analysis.Laughlin.Operators.WedgePairRepresentation +OAI.Analysis.Laughlin.Operators.WedgePairRotation +OAI.Analysis.Laughlin.Operators.WeightedOccupationNorm +OAI.Analysis.Laughlin.Pair.AffineChart +OAI.Analysis.Laughlin.Pair.AffineKernel +OAI.Analysis.Laughlin.Pair.AffinePolynomial +OAI.Analysis.Laughlin.Pair.Binomial +OAI.Analysis.Laughlin.Pair.CoefficientSquare +OAI.Analysis.Laughlin.Pair.Conjugation +OAI.Analysis.Laughlin.Pair.CoupledBasis +OAI.Analysis.Laughlin.Pair.CoupledIsometry +OAI.Analysis.Laughlin.Pair.CoupledOne +OAI.Analysis.Laughlin.Pair.CoupledParity +OAI.Analysis.Laughlin.Pair.DiagonalCube +OAI.Analysis.Laughlin.Pair.EnergyReturn +OAI.Analysis.Laughlin.Pair.ExteriorRotation +OAI.Analysis.Laughlin.Pair.FactorBounds +OAI.Analysis.Laughlin.Pair.FactorLimit +OAI.Analysis.Laughlin.Pair.FockCovariance +OAI.Analysis.Laughlin.Pair.FockHaar +OAI.Analysis.Laughlin.Pair.HomogeneousCube +OAI.Analysis.Laughlin.Pair.Homogenize +OAI.Analysis.Laughlin.Pair.LadderIntertwining +OAI.Analysis.Laughlin.Pair.LoweringAlgebra +OAI.Analysis.Laughlin.Pair.Moment +OAI.Analysis.Laughlin.Pair.MomentKernel +OAI.Analysis.Laughlin.Pair.NormalOrder +OAI.Analysis.Laughlin.Pair.Normalization +OAI.Analysis.Laughlin.Pair.NormalizedLadder +OAI.Analysis.Laughlin.Pair.Orthonormality +OAI.Analysis.Laughlin.Pair.PolynomialBridge +OAI.Analysis.Laughlin.Pair.PolynomialLadder +OAI.Analysis.Laughlin.Pair.PolynomialRaising +OAI.Analysis.Laughlin.Pair.Spectators +OAI.Analysis.Laughlin.Pair.SpinorCube +OAI.Analysis.Laughlin.Pair.TensorBoundary +OAI.Analysis.Laughlin.Pair.TensorLower +OAI.Analysis.Laughlin.Pair.TensorRaise +OAI.Analysis.Laughlin.Planar.DegreeRestriction +OAI.Analysis.Laughlin.Planar.Forms +OAI.Analysis.Laughlin.Planar.Model +OAI.Analysis.Laughlin.Planar.Restriction +OAI.Analysis.Laughlin.Polynomial.AntisymmetricCoordinates +OAI.Analysis.Laughlin.Polynomial.BracketCoprime +OAI.Analysis.Laughlin.Polynomial.BracketIrreducible +OAI.Analysis.Laughlin.Polynomial.BracketProductDivisibility +OAI.Analysis.Laughlin.Polynomial.LaughlinAntisymmetry +OAI.Analysis.Laughlin.Polynomial.LaughlinDegree +OAI.Analysis.Laughlin.Polynomial.LaughlinMultidegree +OAI.Analysis.Laughlin.Polynomial.OscillatorPolynomial +OAI.Analysis.Laughlin.Polynomial.OscillatorPolynomialLadder +OAI.Analysis.Laughlin.Polynomial.PhysicalLaughlinKernel +OAI.Analysis.Laughlin.Polynomial.Polynomial +OAI.Analysis.Laughlin.Polynomial.PolynomialMatrixODE +OAI.Analysis.Laughlin.Polynomial.SourceEqualSpinPolynomial +OAI.Analysis.Laughlin.Polynomial.SourceIntegerPolynomial +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorCoordinates +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorOrbit +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorRange +OAI.Analysis.Laughlin.Spin.Array +OAI.Analysis.Laughlin.Spin.ArrayLimit +OAI.Analysis.Laughlin.Spin.Basic +OAI.Analysis.Laughlin.Spin.Basis +OAI.Analysis.Laughlin.Spin.Basis2 +OAI.Analysis.Laughlin.Spin.BinomialWeights +OAI.Analysis.Laughlin.Spin.Compact +OAI.Analysis.Laughlin.Spin.CompactAverage +OAI.Analysis.Laughlin.Spin.CopySchur +OAI.Analysis.Laughlin.Spin.DescendantNorm +OAI.Analysis.Laughlin.Spin.Disjoint +OAI.Analysis.Laughlin.Spin.EmbeddedSpinHaar +OAI.Analysis.Laughlin.Spin.Endpoint +OAI.Analysis.Laughlin.Spin.GeneralSpinAction +OAI.Analysis.Laughlin.Spin.GenericNormalizedLadder +OAI.Analysis.Laughlin.Spin.GenericOrthogonality +OAI.Analysis.Laughlin.Spin.Haar +OAI.Analysis.Laughlin.Spin.HaarOrthogonality +OAI.Analysis.Laughlin.Spin.Highest +OAI.Analysis.Laughlin.Spin.Highest2 +OAI.Analysis.Laughlin.Spin.HighestSpace +OAI.Analysis.Laughlin.Spin.Intertwining +OAI.Analysis.Laughlin.Spin.LadderGroupIntertwining +OAI.Analysis.Laughlin.Spin.LadderMatrix +OAI.Analysis.Laughlin.Spin.LoweringLimit +OAI.Analysis.Laughlin.Spin.MatrixAverage +OAI.Analysis.Laughlin.Spin.Mixing +OAI.Analysis.Laughlin.Spin.Multidegree +OAI.Analysis.Laughlin.Spin.OrbitalExpansion +OAI.Analysis.Laughlin.Spin.Orthogonal +OAI.Analysis.Laughlin.Spin.OscillatorHighest +OAI.Analysis.Laughlin.Spin.OscillatorHighestNormalization +OAI.Analysis.Laughlin.Spin.PairDecomposition +OAI.Analysis.Laughlin.Spin.ParticleSpinAction +OAI.Analysis.Laughlin.Spin.Polynomial +OAI.Analysis.Laughlin.Spin.Polynomial2 +OAI.Analysis.Laughlin.Spin.PolynomialDegree +OAI.Analysis.Laughlin.Spin.RectangularAverage +OAI.Analysis.Laughlin.Spin.RelativeHighest +OAI.Analysis.Laughlin.Spin.Representation +OAI.Analysis.Laughlin.Spin.Sandwich +OAI.Analysis.Laughlin.Spin.ScaleLimit +OAI.Analysis.Laughlin.Spin.Schur +OAI.Analysis.Laughlin.Spin.Sl2DescendantNorm +OAI.Analysis.Laughlin.Spin.Sl2Matrix +OAI.Analysis.Laughlin.Spin.Sl2Orthogonal +OAI.Analysis.Laughlin.Spin.Specializations +OAI.Analysis.Laughlin.Spin.Support +OAI.Analysis.Laughlin.Spin.TensorAction +OAI.Analysis.Laughlin.Spin.Torus +OAI.Analysis.Laughlin.Spin.TotalSl2Matrix +OAI.Analysis.Laughlin.Spin.TripleLadderIntertwining +OAI.Analysis.Laughlin.Spin.TwoBodyCertificateHaar +OAI.Analysis.Laughlin.Spin.WeightSlice +OAI.Analysis.Laughlin.Tensor.Antisymmetry +OAI.Analysis.Laughlin.Tensor.ExteriorAdjoint +OAI.Analysis.Laughlin.Tensor.ExteriorContraction +OAI.Analysis.Laughlin.Tensor.ExteriorIsometry +OAI.Analysis.Laughlin.Tensor.ExteriorRotation +OAI.Analysis.Laughlin.Tensor.FockEnergy +OAI.Analysis.Laughlin.Tensor.KernelReadout +OAI.Analysis.Laughlin.Tensor.PairContraction +OAI.Analysis.Laughlin.Tensor.PolynomialRealization +OAI.Analysis.Laughlin.Tensor.WeightProducts +OAI.Analysis.Laughlin.ThreeBody.Basic +OAI.Analysis.Laughlin.ThreeBody.Contraction +OAI.Analysis.Laughlin.ThreeBody.Descendants +OAI.Analysis.Laughlin.ThreeBody.FockBudget +OAI.Analysis.Laughlin.ThreeBody.FockComparison +OAI.Analysis.Laughlin.ThreeBody.FockHaar +OAI.Analysis.Laughlin.ThreeBody.FockNull +OAI.Analysis.Laughlin.ThreeBody.FockTail +OAI.Analysis.Laughlin.ThreeBody.Gram +OAI.Analysis.Laughlin.ThreeBody.GramSlice +OAI.Analysis.Laughlin.ThreeBody.GroupIntertwining +OAI.Analysis.Laughlin.ThreeBody.HaarBlocks +OAI.Analysis.Laughlin.ThreeBody.HaarNormalization +OAI.Analysis.Laughlin.ThreeBody.HighestEigen +OAI.Analysis.Laughlin.ThreeBody.HighestFock +OAI.Analysis.Laughlin.ThreeBody.HighestReadout +OAI.Analysis.Laughlin.ThreeBody.HighestRow +OAI.Analysis.Laughlin.ThreeBody.IntegerPolynomial +OAI.Analysis.Laughlin.ThreeBody.LevelTrace +OAI.Analysis.Laughlin.ThreeBody.NullFormula +OAI.Analysis.Laughlin.ThreeBody.NullSectors +OAI.Analysis.Laughlin.ThreeBody.PairAction +OAI.Analysis.Laughlin.ThreeBody.PhysicalKernel +OAI.Analysis.Laughlin.ThreeBody.PhysicalMatrix +OAI.Analysis.Laughlin.ThreeBody.PhysicalTrace +OAI.Analysis.Laughlin.ThreeBody.PolynomialCoefficient +OAI.Analysis.Laughlin.ThreeBody.ProjectorBound +OAI.Analysis.Laughlin.ThreeBody.Radical +OAI.Analysis.Laughlin.ThreeBody.RankTrace +OAI.Analysis.Laughlin.ThreeBody.SourceExpansion +OAI.Analysis.Laughlin.ThreeBody.SpinCovariance +OAI.Analysis.Laughlin.ThreeBody.SpinProjectors +OAI.Analysis.Laughlin.ThreeBody.TraceCertificate +OAI.Analysis.Laughlin.ThreeBody.TraceComparison +OAI.Analysis.Laughlin.ThreeBody.TraceLimit +OAI.Analysis.Laughlin.ThreeBody.TraceReadout +OAI.Analysis.Laughlin.UniformGap diff --git a/tasks/laughlin-planar/solution/reference.py b/tasks/laughlin-planar/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/laughlin-planar/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/laughlin-planar/solution/solve.sh b/tasks/laughlin-planar/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..27b702ac6b8955946ada815c22770e551408e0c4 --- /dev/null +++ b/tasks/laughlin-planar/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LaughlinPlanar, i.e. module OAI.Analysis.Laughlin.UniformGap and the +# 1279 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Laughlin.UniformGap /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LaughlinPlanar" diff --git a/tasks/laughlin-planar/task.toml b/tasks/laughlin-planar/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5b7276db2fccd43f5478f9bbd53c34b493758f8b --- /dev/null +++ b/tasks/laughlin-planar/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/laughlin-planar" +version = "1.0.0" +description = "Prove LaughlinPlanar (openai/math family 269: The Laughlin gap and stability under scalar disorder) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LaughlinPlanar.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LaughlinPlanar" +family = "269" +family_title = "The Laughlin gap and stability under scalar disorder" +subject = "Mathematical physics" +theorems = ["OAI.Laughlin.planar_gap"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Laughlin.UniformGap" +reference_modules = 1279 +reference_lean_bytes = 3060235 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 7126 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14454 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/laughlin-planar/tests/Challenge.lean b/tasks/laughlin-planar/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..37ba51305eee1df7b49f98a1689513cef42f7ca2 --- /dev/null +++ b/tasks/laughlin-planar/tests/Challenge.lean @@ -0,0 +1,82 @@ +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators Matrix ENNReal + +noncomputable def gammaStar : ℝ := 4616733319001 / 10^14 + +noncomputable def pairLimitCoefficient (p x y : ℕ) : ℝ := + if x+y = p+1 then + ((x : ℝ)-(y : ℝ)) * Real.sqrt ((p.factorial : ℝ) / + (((2 : ℕ) : ℝ)^p * (x.factorial : ℝ) * (y.factorial : ℝ))) / Real.sqrt (2 : ℕ) + else 0 + +namespace Fock + +abbrev Orbital (Q : ℕ) := Fin (Q+1) → ℂ +abbrev Space (Q : ℕ) := ExteriorAlgebra ℂ (Orbital Q) + +noncomputable def annihilate {Q : ℕ} (i : Fin (Q+1)) : Module.End ℂ (Space Q) := + CliffordAlgebra.contractLeft (Q := (0 : QuadraticForm ℂ (Orbital Q))) (LinearMap.proj i) + +noncomputable def occupationBasis (Q : ℕ) : + Module.Basis (Finset (Fin (Q+1))) ℂ (Space Q) := + (Pi.basisFun ℂ (Fin (Q+1))).ExteriorAlgebra + +def OccupationBidegree (Q n w : ℕ) (x : Space Q) : Prop := + ∀ A : Finset (Fin (Q+1)), (A.card ≠ n ∨ (∑ i ∈ A, i.val) ≠ w) → + (occupationBasis Q).repr x A = 0 + +end Fock + +namespace Planar +open Fock + +abbrev Occupations (L : ℕ) := Finset (Fin (L+1)) + +noncomputable def pairMatrix (L : ℕ) (c : Fin (L+1) → Fin (L+1) → ℂ) : + Matrix (Occupations L) (Occupations L) ℂ := fun A B => + ∑ i, ∑ j, c i j * (occupationBasis L).repr + (annihilate j (annihilate i (occupationBasis L B))) A + +noncomputable def planarCoefficient (p i j : ℕ) : ℂ := + ((pairLimitCoefficient p i j / Real.sqrt (2 : ℕ) : ℝ) : ℂ) + +noncomputable def planarPairMatrix (L p : ℕ) : Matrix (Occupations L) (Occupations L) ℂ := + pairMatrix L (fun i j => planarCoefficient p i.val j.val) + +noncomputable def planarHamiltonian (L : ℕ) : Matrix (Occupations L) (Occupations L) ℂ := + ∑ p ∈ Finset.range (2*L+1), (planarPairMatrix L p)ᴴ * planarPairMatrix L p + +noncomputable def pairEnergy (L : ℕ) + (P : ℕ → Matrix (Occupations L) (Occupations L) ℂ) (x : Occupations L → ℂ) : ℝ := + ∑ p ∈ Finset.range (2*L+1), ∑ A, ‖(P p *ᵥ x) A‖^2 + +noncomputable def squareNorm (L : ℕ) (H : Matrix (Occupations L) (Occupations L) ℂ) + (x : Occupations L → ℂ) : ℝ := ∑ A, ‖(H *ᵥ x) A‖^2 + +/-- Occupation coefficients with fixed particle number in every homogeneous degree. -/ +structure HomogeneousState (N : ℕ) where + block : (L : ℕ) → Space L + homogeneous : ∀ L, OccupationBidegree L N L (block L) + +noncomputable def fullEnergy {N : ℕ} (ψ : HomogeneousState N) : ℝ≥0∞ := + ∑' L, ENNReal.ofReal (pairEnergy L (planarPairMatrix L) + (fun A => (occupationBasis L).repr (ψ.block L) A)) + +noncomputable def fullSquareNorm {N : ℕ} (ψ : HomogeneousState N) : ℝ≥0∞ := + ∑' L, ENNReal.ofReal (squareNorm L (planarHamiltonian L) + (fun A => (occupationBasis L).repr (ψ.block L) A)) + +end Planar + +/-- The planar endpoint inequality in the homogeneous occupation representation. -/ +theorem planar_gap {N : ℕ} (ψ : Planar.HomogeneousState N) : + ENNReal.ofReal gammaStar * Planar.fullEnergy ψ ≤ Planar.fullSquareNorm ψ := by + sorry + +end Laughlin + +end OAI diff --git a/tasks/laughlin-planar/tests/grade.py b/tasks/laughlin-planar/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/laughlin-planar/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/laughlin-planar/tests/task.json b/tasks/laughlin-planar/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dcfd2e64051781fc0c5c67d8bcfab85bcee908c5 --- /dev/null +++ b/tasks/laughlin-planar/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LaughlinPlanar", + "comparator": { + "theorem_names": [ + "OAI.Laughlin.planar_gap" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13554 +} \ No newline at end of file diff --git a/tasks/laughlin-planar/tests/test.sh b/tasks/laughlin-planar/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/laughlin-planar/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/laughlin/environment/Dockerfile b/tasks/laughlin/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/laughlin/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/laughlin/environment/fetch_mathlib.sh b/tasks/laughlin/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/laughlin/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/laughlin/environment/lake-manifest.json b/tasks/laughlin/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/laughlin/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/laughlin/environment/lakefile.lean b/tasks/laughlin/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/laughlin/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/laughlin/environment/lean_setup.sh b/tasks/laughlin/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/laughlin/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/laughlin/environment/pack_submission.py b/tasks/laughlin/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/laughlin/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/laughlin/instruction.md b/tasks/laughlin/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a9027c3f88d13d9ae382eba18b1d37322addc95 --- /dev/null +++ b/tasks/laughlin/instruction.md @@ -0,0 +1,117 @@ +# openai/math challenge `Laughlin` (family 269) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 269 of the release, *The Laughlin gap and stability under scalar disorder* +(Mathematical physics). The family as a whole: Proves the fermionic Laughlin spectral-gap conjecture for the full $V_1$ interaction at filling $1/3$ on the round sphere. The unique ground state remains uniformly gapped under sufficiently weak bounded real scalar one-body potentials projected to the lowest Landau level. Both the gap and disorder threshold are uniform over all sufficiently large particle numbers and all normalized potential profiles. + +The challenge is `Laughlin`, also at `/opt/openai-math/challenges/Laughlin.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators + +abbrev Configuration (N Q : ℕ) := Fin N → Fin (Q+1) +abbrev State (N Q : ℕ) := Configuration N Q → ℂ + +def Antisymmetric {N Q : ℕ} (ψ : State N Q) : Prop := + ∀ (i j : Fin N), i ≠ j → ∀ a, ψ (a ∘ Equiv.swap i j) = -ψ a + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + +noncomputable def pairAmplitude {N Q : ℕ} (ψ : State N Q) + (i j : Fin N) (p : ℕ) (a : Configuration N Q) : ℂ := + ∑ x : Fin (Q+1), ∑ y : Fin (Q+1), + (pairCoefficient Q p x y : ℂ) * ψ (Function.update (Function.update a i x) j y) + +noncomputable def energy {N Q : ℕ} (ψ : State N Q) : ℝ := + ∑ i : Fin N, ∑ j : Fin N, if i < j then + ∑ p ∈ Finset.range (2*Q-1), ∑ a : Configuration N Q, + if a i = 0 ∧ a j = 0 then ‖pairAmplitude ψ i j p a‖ ^ 2 else 0 + else 0 + +abbrev SpinorVariables (N : ℕ) := Fin N × Bool + +noncomputable def bracket {N : ℕ} (i j : Fin N) : MvPolynomial (SpinorVariables N) ℂ := + MvPolynomial.X (i,false) * MvPolynomial.X (j,true) - + MvPolynomial.X (j,false) * MvPolynomial.X (i,true) + +noncomputable def laughlinPolynomial (N : ℕ) : MvPolynomial (SpinorVariables N) ℂ := + ∏ i : Fin N, ∏ j : Fin N, if i < j then bracket i j ^ 3 else 1 + +noncomputable def monomialExponent {N Q : ℕ} (a : Configuration N Q) : SpinorVariables N →₀ ℕ := + Finsupp.onFinset Finset.univ + (fun ib => if ib.2 then (a ib.1).val else Q - (a ib.1).val) + (by intro; simp) + +noncomputable def laughlinVector (N Q : ℕ) : State N Q := fun a => + (laughlinPolynomial N).coeff (monomialExponent a) / + ((∏ i : Fin N, Real.sqrt (Nat.choose Q (a i).val : ℝ) : ℝ) : ℂ) + +noncomputable def distanceToLaughlinSq {N Q : ℕ} (ψ : State N Q) : ℝ := + sInf (Set.range (fun c : ℂ => ∑ a : Configuration N Q, + ‖ψ a - c * laughlinVector N Q a‖ ^ 2)) + +def MainTarget : Prop := + ∃ N₀ : ℕ, 2 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∀ ψ : State N (3*(N-1)), Antisymmetric ψ → + (1/100 : ℝ) * distanceToLaughlinSq ψ ≤ energy ψ + +theorem mainTarget_proved : MainTarget := by + sorry + +end Laughlin + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Laughlin.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Laughlin.mainTarget_proved` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/laughlin/solution/closure.txt b/tasks/laughlin/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3aee3c872f7bdc41995c6c21dbdd56f6e5461ec0 --- /dev/null +++ b/tasks/laughlin/solution/closure.txt @@ -0,0 +1,1258 @@ +OAI.Analysis.Laughlin.Asymptotics.Basic +OAI.Analysis.Laughlin.Asymptotics.Bound +OAI.Analysis.Laughlin.Asymptotics.Convergence +OAI.Analysis.Laughlin.Asymptotics.FiniteReindex +OAI.Analysis.Laughlin.Asymptotics.HighestCouplingLimit +OAI.Analysis.Laughlin.Asymptotics.Limit +OAI.Analysis.Laughlin.Asymptotics.LimitFourLocalSum +OAI.Analysis.Laughlin.Asymptotics.LocalDiagonalLimit +OAI.Analysis.Laughlin.Asymptotics.LocalMetricLimit +OAI.Analysis.Laughlin.Asymptotics.Perturbation +OAI.Analysis.Laughlin.Asymptotics.ScalarBudget +OAI.Analysis.Laughlin.Asymptotics.TruncatedMetricPerturbation +OAI.Analysis.Laughlin.Asymptotics.TruncatedScaling +OAI.Analysis.Laughlin.Asymptotics.UpperSpinCurve +OAI.Analysis.Laughlin.Asymptotics.UpperSpinDynamics +OAI.Analysis.Laughlin.EnergyNonnegative +OAI.Analysis.Laughlin.Exterior.FamilyCovariance +OAI.Analysis.Laughlin.Exterior.FourConjugation +OAI.Analysis.Laughlin.Exterior.OccupationDiagonal +OAI.Analysis.Laughlin.Exterior.OccupationMetric +OAI.Analysis.Laughlin.Exterior.PairConjugation +OAI.Analysis.Laughlin.Exterior.Scaling +OAI.Analysis.Laughlin.Exterior.ScalingWedge +OAI.Analysis.Laughlin.Exterior.SpinAction +OAI.Analysis.Laughlin.Exterior.SpinUnitary +OAI.Analysis.Laughlin.Exterior.VectorAdjoint +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram01Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram03Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram05Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram07Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram09Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram111112 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram11Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram131313 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram131314 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram13Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram151515 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram151516 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram15Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram171717 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram171718 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram17Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram191919 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram191920 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram19Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram212121 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram212122 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram21Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeGram232323 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL00Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL01Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL02Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL03Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL04Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL050511 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL05Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL06Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL07Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL08Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL09Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL10Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeLDL11Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeQuadruples23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0101Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0103Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0105Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0107Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0109Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0111Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0113Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0115Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0117Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0119Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0303Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0305Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0307Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0309Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0311Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0313Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0315Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0317Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0319Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0321Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0505Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0507Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0509Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0511Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0513Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0515Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0517Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0519Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0521Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0523Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0707Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0709Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0711Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0713Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0715Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0717Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0719Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0721Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0723Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow09 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0909Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0911Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0913Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0915Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0917Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0919Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow092 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0921Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow0923Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow093 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow10 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow102 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow103 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow11 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch12 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1111Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1113Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1115Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1117Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1119Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow112 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow113 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow114 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow115 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch13 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch14 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1313Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1315Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1317Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1319Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1321Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch15 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch16 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1515Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1517Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1519Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1521Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1523Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch17 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch18 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1717Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1719Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1721Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1723Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch19 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch20 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1919Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1921Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow1923Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch21 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch22 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2121Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2123Batch23 +OAI.Analysis.Laughlin.FiniteFlux.ComputeRow2323Batch23 +OAI.Analysis.Laughlin.FiniteFlux.Data09 +OAI.Analysis.Laughlin.FiniteFlux.Data10 +OAI.Analysis.Laughlin.FiniteFlux.Data11 +OAI.Analysis.Laughlin.FiniteFlux.Data12 +OAI.Analysis.Laughlin.FiniteFlux.Data13 +OAI.Analysis.Laughlin.FiniteFlux.Data14 +OAI.Analysis.Laughlin.FiniteFlux.Data15 +OAI.Analysis.Laughlin.FiniteFlux.Data16 +OAI.Analysis.Laughlin.FiniteFlux.Data17 +OAI.Analysis.Laughlin.FiniteFlux.Data18 +OAI.Analysis.Laughlin.FiniteFlux.Data19 +OAI.Analysis.Laughlin.FiniteFlux.Data20 +OAI.Analysis.Laughlin.FiniteFlux.Data21 +OAI.Analysis.Laughlin.FiniteFlux.Data22 +OAI.Analysis.Laughlin.FiniteFlux.Data23 +OAI.Analysis.Laughlin.FiniteFlux.Error05 +OAI.Analysis.Laughlin.FiniteFlux.Error07 +OAI.Analysis.Laughlin.FiniteFlux.Error08 +OAI.Analysis.Laughlin.FiniteFlux.Gram07 +OAI.Analysis.Laughlin.FiniteFlux.Gram072 +OAI.Analysis.Laughlin.FiniteFlux.Gram08 +OAI.Analysis.Laughlin.FiniteFlux.Gram082 +OAI.Analysis.Laughlin.FiniteFlux.GramData09 +OAI.Analysis.Laughlin.FiniteFlux.GramData10 +OAI.Analysis.Laughlin.FiniteFlux.GramData11 +OAI.Analysis.Laughlin.FiniteFlux.GramData12 +OAI.Analysis.Laughlin.FiniteFlux.GramData13 +OAI.Analysis.Laughlin.FiniteFlux.GramData14 +OAI.Analysis.Laughlin.FiniteFlux.GramData15 +OAI.Analysis.Laughlin.FiniteFlux.GramData16 +OAI.Analysis.Laughlin.FiniteFlux.GramData17 +OAI.Analysis.Laughlin.FiniteFlux.GramData18 +OAI.Analysis.Laughlin.FiniteFlux.GramData19 +OAI.Analysis.Laughlin.FiniteFlux.GramData20 +OAI.Analysis.Laughlin.FiniteFlux.GramData21 +OAI.Analysis.Laughlin.FiniteFlux.GramData22 +OAI.Analysis.Laughlin.FiniteFlux.GramData23 +OAI.Analysis.Laughlin.FiniteFlux.LDL08 +OAI.Analysis.Laughlin.FiniteFlux.LDLData08 +OAI.Analysis.Laughlin.FiniteFlux.LDLData09 +OAI.Analysis.Laughlin.FiniteFlux.LDLData10 +OAI.Analysis.Laughlin.FiniteFlux.LDLData11 +OAI.Analysis.Laughlin.FiniteFlux.LDLData12 +OAI.Analysis.Laughlin.FiniteFlux.LDLData13 +OAI.Analysis.Laughlin.FiniteFlux.LDLData14 +OAI.Analysis.Laughlin.FiniteFlux.LDLData15 +OAI.Analysis.Laughlin.FiniteFlux.LDLData16 +OAI.Analysis.Laughlin.FiniteFlux.LDLData17 +OAI.Analysis.Laughlin.FiniteFlux.LDLData18 +OAI.Analysis.Laughlin.FiniteFlux.LDLData19 +OAI.Analysis.Laughlin.FiniteFlux.LDLData20 +OAI.Analysis.Laughlin.FiniteFlux.LDLData21 +OAI.Analysis.Laughlin.FiniteFlux.LDLData22 +OAI.Analysis.Laughlin.FiniteFlux.LDLData23 +OAI.Analysis.Laughlin.FiniteFlux.Positive05 +OAI.Analysis.Laughlin.FiniteFlux.Positive07 +OAI.Analysis.Laughlin.FiniteFlux.Positive08 +OAI.Analysis.Laughlin.FiniteFlux.Positive09 +OAI.Analysis.Laughlin.FiniteFlux.Positive10 +OAI.Analysis.Laughlin.FiniteFlux.Positive11 +OAI.Analysis.Laughlin.FiniteFlux.Positive12 +OAI.Analysis.Laughlin.FiniteFlux.Positive13 +OAI.Analysis.Laughlin.FiniteFlux.Positive14 +OAI.Analysis.Laughlin.FiniteFlux.Positive15 +OAI.Analysis.Laughlin.FiniteFlux.Positive16 +OAI.Analysis.Laughlin.FiniteFlux.Positive17 +OAI.Analysis.Laughlin.FiniteFlux.Positive18 +OAI.Analysis.Laughlin.FiniteFlux.Positive19 +OAI.Analysis.Laughlin.FiniteFlux.Positive20 +OAI.Analysis.Laughlin.FiniteFlux.Positive21 +OAI.Analysis.Laughlin.FiniteFlux.Positive22 +OAI.Analysis.Laughlin.FiniteFlux.Positive23 +OAI.Analysis.Laughlin.FiniteFlux.Quadruples08 +OAI.Analysis.Laughlin.FiniteFlux.Row0301007 +OAI.Analysis.Laughlin.FiniteFlux.Row0301107 +OAI.Analysis.Laughlin.FiniteFlux.Row0301207 +OAI.Analysis.Laughlin.FiniteFlux.Row0301307 +OAI.Analysis.Laughlin.FiniteFlux.Row0301407 +OAI.Analysis.Laughlin.FiniteFlux.Row0301507 +OAI.Analysis.Laughlin.FiniteFlux.Row0301607 +OAI.Analysis.Laughlin.FiniteFlux.Row05 +OAI.Analysis.Laughlin.FiniteFlux.Row0501007 +OAI.Analysis.Laughlin.FiniteFlux.Row0501107 +OAI.Analysis.Laughlin.FiniteFlux.Row0501207 +OAI.Analysis.Laughlin.FiniteFlux.Row0501307 +OAI.Analysis.Laughlin.FiniteFlux.Row0501407 +OAI.Analysis.Laughlin.FiniteFlux.Row0501507 +OAI.Analysis.Laughlin.FiniteFlux.Row0501607 +OAI.Analysis.Laughlin.FiniteFlux.Row0503007 +OAI.Analysis.Laughlin.FiniteFlux.Row0503107 +OAI.Analysis.Laughlin.FiniteFlux.Row0503207 +OAI.Analysis.Laughlin.FiniteFlux.Row0503307 +OAI.Analysis.Laughlin.FiniteFlux.Row0503407 +OAI.Analysis.Laughlin.FiniteFlux.Row0503507 +OAI.Analysis.Laughlin.FiniteFlux.Row0503607 +OAI.Analysis.Laughlin.FiniteFlux.Row052 +OAI.Analysis.Laughlin.FiniteFlux.Row07 +OAI.Analysis.Laughlin.FiniteFlux.Row0701007 +OAI.Analysis.Laughlin.FiniteFlux.Row0701107 +OAI.Analysis.Laughlin.FiniteFlux.Row0701207 +OAI.Analysis.Laughlin.FiniteFlux.Row0701307 +OAI.Analysis.Laughlin.FiniteFlux.Row0701407 +OAI.Analysis.Laughlin.FiniteFlux.Row0701507 +OAI.Analysis.Laughlin.FiniteFlux.Row0701607 +OAI.Analysis.Laughlin.FiniteFlux.Row0703007 +OAI.Analysis.Laughlin.FiniteFlux.Row0703107 +OAI.Analysis.Laughlin.FiniteFlux.Row0703207 +OAI.Analysis.Laughlin.FiniteFlux.Row0703307 +OAI.Analysis.Laughlin.FiniteFlux.Row0703407 +OAI.Analysis.Laughlin.FiniteFlux.Row0703507 +OAI.Analysis.Laughlin.FiniteFlux.Row0703607 +OAI.Analysis.Laughlin.FiniteFlux.Row0705007 +OAI.Analysis.Laughlin.FiniteFlux.Row0705107 +OAI.Analysis.Laughlin.FiniteFlux.Row0705207 +OAI.Analysis.Laughlin.FiniteFlux.Row0705307 +OAI.Analysis.Laughlin.FiniteFlux.Row0705407 +OAI.Analysis.Laughlin.FiniteFlux.Row0705507 +OAI.Analysis.Laughlin.FiniteFlux.Row0705607 +OAI.Analysis.Laughlin.FiniteFlux.Row072 +OAI.Analysis.Laughlin.FiniteFlux.Row073 +OAI.Analysis.Laughlin.FiniteFlux.Row08 +OAI.Analysis.Laughlin.FiniteFlux.Row082 +OAI.Analysis.Laughlin.FiniteFlux.Row083 +OAI.Analysis.Laughlin.Fock.Adjoint +OAI.Analysis.Laughlin.Fock.Annihilation +OAI.Analysis.Laughlin.Fock.Bidegree +OAI.Analysis.Laughlin.Fock.ContractionBound +OAI.Analysis.Laughlin.Fock.Coordinates +OAI.Analysis.Laughlin.Fock.Creation +OAI.Analysis.Laughlin.Fock.EigenvalueGap +OAI.Analysis.Laughlin.Fock.EnergyRotation +OAI.Analysis.Laughlin.Fock.FourLabels +OAI.Analysis.Laughlin.Fock.HaarQuadratic +OAI.Analysis.Laughlin.Fock.Hamiltonian +OAI.Analysis.Laughlin.Fock.Inner +OAI.Analysis.Laughlin.Fock.MatrixQuadratic +OAI.Analysis.Laughlin.Fock.NormalSquare +OAI.Analysis.Laughlin.Fock.OrbitIntegration +OAI.Analysis.Laughlin.Fock.PairNormalization +OAI.Analysis.Laughlin.Fock.Perturbation +OAI.Analysis.Laughlin.Fock.Quadruple +OAI.Analysis.Laughlin.Fock.RankOneHaar +OAI.Analysis.Laughlin.Fock.SpectralDistance +OAI.Analysis.Laughlin.Fock.SpinContinuity +OAI.Analysis.Laughlin.Fock.SpinRepresentation +OAI.Analysis.Laughlin.Fock.UnitaryFamilies +OAI.Analysis.Laughlin.FourBody.All +OAI.Analysis.Laughlin.FourBody.Assembly +OAI.Analysis.Laughlin.FourBody.Basic +OAI.Analysis.Laughlin.FourBody.CARReadout +OAI.Analysis.Laughlin.FourBody.CoefficientLimit +OAI.Analysis.Laughlin.FourBody.CoefficientNorm +OAI.Analysis.Laughlin.FourBody.Coefficients +OAI.Analysis.Laughlin.FourBody.ColumnExpansion +OAI.Analysis.Laughlin.FourBody.Copies +OAI.Analysis.Laughlin.FourBody.CopyAlgebra +OAI.Analysis.Laughlin.FourBody.CopyFormAllowance +OAI.Analysis.Laughlin.FourBody.CopyOperatorHaar +OAI.Analysis.Laughlin.FourBody.CopyOrthogonality +OAI.Analysis.Laughlin.FourBody.CoupledBasis +OAI.Analysis.Laughlin.FourBody.EndExpansion +OAI.Analysis.Laughlin.FourBody.ErrorCertificate +OAI.Analysis.Laughlin.FourBody.ErrorLimit +OAI.Analysis.Laughlin.FourBody.ErrorMatrix +OAI.Analysis.Laughlin.FourBody.Estimate +OAI.Analysis.Laughlin.FourBody.Expansion +OAI.Analysis.Laughlin.FourBody.FactorialCoefficient +OAI.Analysis.Laughlin.FourBody.Fast +OAI.Analysis.Laughlin.FourBody.FastChoose +OAI.Analysis.Laughlin.FourBody.FockCovariance +OAI.Analysis.Laughlin.FourBody.Formula +OAI.Analysis.Laughlin.FourBody.GlobalFock +OAI.Analysis.Laughlin.FourBody.GlobalHaar +OAI.Analysis.Laughlin.FourBody.GramCompute +OAI.Analysis.Laughlin.FourBody.GroupIntertwining +OAI.Analysis.Laughlin.FourBody.HaarAllowance +OAI.Analysis.Laughlin.FourBody.HaarTransfer +OAI.Analysis.Laughlin.FourBody.Hermitian +OAI.Analysis.Laughlin.FourBody.HighestFock +OAI.Analysis.Laughlin.FourBody.Integral +OAI.Analysis.Laughlin.FourBody.Levels +OAI.Analysis.Laughlin.FourBody.LimitCARReadout +OAI.Analysis.Laughlin.FourBody.LimitPositive +OAI.Analysis.Laughlin.FourBody.LocalNormalization +OAI.Analysis.Laughlin.FourBody.Matrix +OAI.Analysis.Laughlin.FourBody.MatrixCompute +OAI.Analysis.Laughlin.FourBody.MiddleForm +OAI.Analysis.Laughlin.FourBody.MiddleLimit +OAI.Analysis.Laughlin.FourBody.MultiplicityHaar +OAI.Analysis.Laughlin.FourBody.NormalForm +OAI.Analysis.Laughlin.FourBody.NumericBridge +OAI.Analysis.Laughlin.FourBody.OccupationCoefficient +OAI.Analysis.Laughlin.FourBody.PairTarget +OAI.Analysis.Laughlin.FourBody.Parity +OAI.Analysis.Laughlin.FourBody.PhysicalAllowance +OAI.Analysis.Laughlin.FourBody.PhysicalCertificate +OAI.Analysis.Laughlin.FourBody.PhysicalColumn +OAI.Analysis.Laughlin.FourBody.PhysicalGram +OAI.Analysis.Laughlin.FourBody.PhysicalMatrix +OAI.Analysis.Laughlin.FourBody.PhysicalSlaterReadout +OAI.Analysis.Laughlin.FourBody.PhysicalTrace +OAI.Analysis.Laughlin.FourBody.Quadruples +OAI.Analysis.Laughlin.FourBody.RadicalCancellation +OAI.Analysis.Laughlin.FourBody.RadicalCoefficient +OAI.Analysis.Laughlin.FourBody.RetainedComparison +OAI.Analysis.Laughlin.FourBody.RetainedInclusions +OAI.Analysis.Laughlin.FourBody.RetainedIndex +OAI.Analysis.Laughlin.FourBody.RetainedReconstruction +OAI.Analysis.Laughlin.FourBody.RetainedSum +OAI.Analysis.Laughlin.FourBody.RowBridge +OAI.Analysis.Laughlin.FourBody.RowCompute +OAI.Analysis.Laughlin.FourBody.Scaled +OAI.Analysis.Laughlin.FourBody.ScaledAll +OAI.Analysis.Laughlin.FourBody.SignedCoordinates +OAI.Analysis.Laughlin.FourBody.SlaterCoefficient +OAI.Analysis.Laughlin.FourBody.SlaterRadical +OAI.Analysis.Laughlin.FourBody.SliceCoefficient +OAI.Analysis.Laughlin.FourBody.Square +OAI.Analysis.Laughlin.FourBody.Support +OAI.Analysis.Laughlin.FourBody.Symmetry +OAI.Analysis.Laughlin.FourBody.TargetBound +OAI.Analysis.Laughlin.FourBody.TargetResolution +OAI.Analysis.Laughlin.FourBody.TensorIntertwining +OAI.Analysis.Laughlin.FourBody.TotalAllowance +OAI.Analysis.Laughlin.FourBody.TotalTransfer +OAI.Analysis.Laughlin.FourBody.TraceReadout +OAI.Analysis.Laughlin.FourBody.TransferCoefficients +OAI.Analysis.Laughlin.FourBody.TransferConjugation +OAI.Analysis.Laughlin.FourBody.Ungroup +OAI.Analysis.Laughlin.FourBody.UniformTransfer +OAI.Analysis.Laughlin.FourBody.WedgeCompression +OAI.Analysis.Laughlin.FourBody.WeightSlice +OAI.Analysis.Laughlin.FourBody.WeightedReadout +OAI.Analysis.Laughlin.Main +OAI.Analysis.Laughlin.Model +OAI.Analysis.Laughlin.Operators.CAR +OAI.Analysis.Laughlin.Operators.Certificate +OAI.Analysis.Laughlin.Operators.CollectionAnnihilatorBound +OAI.Analysis.Laughlin.Operators.ComplexCompression +OAI.Analysis.Laughlin.Operators.CopyQuadraticMatrix +OAI.Analysis.Laughlin.Operators.Energy +OAI.Analysis.Laughlin.Operators.FourOccupationEquiv +OAI.Analysis.Laughlin.Operators.GenericPhysicalResolution +OAI.Analysis.Laughlin.Operators.GlobalPairCube +OAI.Analysis.Laughlin.Operators.GramReadout +OAI.Analysis.Laughlin.Operators.LocalFourCardinality +OAI.Analysis.Laughlin.Operators.LocalFourIndexEquiv +OAI.Analysis.Laughlin.Operators.MatrixCongruence +OAI.Analysis.Laughlin.Operators.MatrixMetricError +OAI.Analysis.Laughlin.Operators.MatrixPhysicalCompression +OAI.Analysis.Laughlin.Operators.NormalCertificate +OAI.Analysis.Laughlin.Operators.NormalOrder +OAI.Analysis.Laughlin.Operators.NormalOrderFour +OAI.Analysis.Laughlin.Operators.PairNormalOrder +OAI.Analysis.Laughlin.Operators.PhysicalCoupling +OAI.Analysis.Laughlin.Operators.PhysicalFockGap +OAI.Analysis.Laughlin.Operators.PhysicalPairCounting +OAI.Analysis.Laughlin.Operators.PhysicalPairKernel +OAI.Analysis.Laughlin.Operators.PhysicalPairRotation +OAI.Analysis.Laughlin.Operators.PositiveFockLift +OAI.Analysis.Laughlin.Operators.RationalPSD +OAI.Analysis.Laughlin.Operators.RealComplexMatrixPositive +OAI.Analysis.Laughlin.Operators.RowNormalSquare +OAI.Analysis.Laughlin.Operators.SevenSquareAverage +OAI.Analysis.Laughlin.Operators.SpectralKernelDistance +OAI.Analysis.Laughlin.Operators.SymmetricPairSum +OAI.Analysis.Laughlin.Operators.TruncatedConjugation +OAI.Analysis.Laughlin.Operators.TruncatedFourCopy +OAI.Analysis.Laughlin.Operators.TruncatedPairReturn +OAI.Analysis.Laughlin.Operators.WedgePairRepresentation +OAI.Analysis.Laughlin.Operators.WedgePairRotation +OAI.Analysis.Laughlin.Operators.WeightedOccupationNorm +OAI.Analysis.Laughlin.Pair.AffineChart +OAI.Analysis.Laughlin.Pair.AffineKernel +OAI.Analysis.Laughlin.Pair.AffinePolynomial +OAI.Analysis.Laughlin.Pair.Binomial +OAI.Analysis.Laughlin.Pair.CoefficientSquare +OAI.Analysis.Laughlin.Pair.Conjugation +OAI.Analysis.Laughlin.Pair.CoupledBasis +OAI.Analysis.Laughlin.Pair.CoupledIsometry +OAI.Analysis.Laughlin.Pair.CoupledOne +OAI.Analysis.Laughlin.Pair.CoupledParity +OAI.Analysis.Laughlin.Pair.DiagonalCube +OAI.Analysis.Laughlin.Pair.EnergyReturn +OAI.Analysis.Laughlin.Pair.ExteriorRotation +OAI.Analysis.Laughlin.Pair.FactorBounds +OAI.Analysis.Laughlin.Pair.FactorLimit +OAI.Analysis.Laughlin.Pair.FockCovariance +OAI.Analysis.Laughlin.Pair.FockHaar +OAI.Analysis.Laughlin.Pair.HomogeneousCube +OAI.Analysis.Laughlin.Pair.Homogenize +OAI.Analysis.Laughlin.Pair.LadderIntertwining +OAI.Analysis.Laughlin.Pair.LoweringAlgebra +OAI.Analysis.Laughlin.Pair.Moment +OAI.Analysis.Laughlin.Pair.MomentKernel +OAI.Analysis.Laughlin.Pair.NormalOrder +OAI.Analysis.Laughlin.Pair.Normalization +OAI.Analysis.Laughlin.Pair.NormalizedLadder +OAI.Analysis.Laughlin.Pair.Orthonormality +OAI.Analysis.Laughlin.Pair.PolynomialBridge +OAI.Analysis.Laughlin.Pair.PolynomialLadder +OAI.Analysis.Laughlin.Pair.PolynomialRaising +OAI.Analysis.Laughlin.Pair.Spectators +OAI.Analysis.Laughlin.Pair.SpinorCube +OAI.Analysis.Laughlin.Pair.TensorBoundary +OAI.Analysis.Laughlin.Pair.TensorLower +OAI.Analysis.Laughlin.Pair.TensorRaise +OAI.Analysis.Laughlin.Polynomial.AntisymmetricCoordinates +OAI.Analysis.Laughlin.Polynomial.BracketCoprime +OAI.Analysis.Laughlin.Polynomial.BracketIrreducible +OAI.Analysis.Laughlin.Polynomial.BracketProductDivisibility +OAI.Analysis.Laughlin.Polynomial.LaughlinAntisymmetry +OAI.Analysis.Laughlin.Polynomial.LaughlinDegree +OAI.Analysis.Laughlin.Polynomial.LaughlinMultidegree +OAI.Analysis.Laughlin.Polynomial.OscillatorPolynomial +OAI.Analysis.Laughlin.Polynomial.OscillatorPolynomialLadder +OAI.Analysis.Laughlin.Polynomial.PhysicalLaughlinKernel +OAI.Analysis.Laughlin.Polynomial.Polynomial +OAI.Analysis.Laughlin.Polynomial.PolynomialMatrixODE +OAI.Analysis.Laughlin.Polynomial.SourceEqualSpinPolynomial +OAI.Analysis.Laughlin.Polynomial.SourceIntegerPolynomial +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorCoordinates +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorOrbit +OAI.Analysis.Laughlin.Polynomial.SymmetricTensorRange +OAI.Analysis.Laughlin.Spin.Array +OAI.Analysis.Laughlin.Spin.ArrayLimit +OAI.Analysis.Laughlin.Spin.Basic +OAI.Analysis.Laughlin.Spin.Basis +OAI.Analysis.Laughlin.Spin.Basis2 +OAI.Analysis.Laughlin.Spin.BinomialWeights +OAI.Analysis.Laughlin.Spin.Compact +OAI.Analysis.Laughlin.Spin.CompactAverage +OAI.Analysis.Laughlin.Spin.CopySchur +OAI.Analysis.Laughlin.Spin.DescendantNorm +OAI.Analysis.Laughlin.Spin.Disjoint +OAI.Analysis.Laughlin.Spin.EmbeddedSpinHaar +OAI.Analysis.Laughlin.Spin.Endpoint +OAI.Analysis.Laughlin.Spin.GeneralSpinAction +OAI.Analysis.Laughlin.Spin.GenericNormalizedLadder +OAI.Analysis.Laughlin.Spin.GenericOrthogonality +OAI.Analysis.Laughlin.Spin.Haar +OAI.Analysis.Laughlin.Spin.HaarOrthogonality +OAI.Analysis.Laughlin.Spin.Highest +OAI.Analysis.Laughlin.Spin.Highest2 +OAI.Analysis.Laughlin.Spin.HighestSpace +OAI.Analysis.Laughlin.Spin.Intertwining +OAI.Analysis.Laughlin.Spin.LadderGroupIntertwining +OAI.Analysis.Laughlin.Spin.LadderMatrix +OAI.Analysis.Laughlin.Spin.LoweringLimit +OAI.Analysis.Laughlin.Spin.MatrixAverage +OAI.Analysis.Laughlin.Spin.Mixing +OAI.Analysis.Laughlin.Spin.Multidegree +OAI.Analysis.Laughlin.Spin.OrbitalExpansion +OAI.Analysis.Laughlin.Spin.Orthogonal +OAI.Analysis.Laughlin.Spin.OscillatorHighest +OAI.Analysis.Laughlin.Spin.OscillatorHighestNormalization +OAI.Analysis.Laughlin.Spin.PairDecomposition +OAI.Analysis.Laughlin.Spin.ParticleSpinAction +OAI.Analysis.Laughlin.Spin.Polynomial +OAI.Analysis.Laughlin.Spin.Polynomial2 +OAI.Analysis.Laughlin.Spin.PolynomialDegree +OAI.Analysis.Laughlin.Spin.RectangularAverage +OAI.Analysis.Laughlin.Spin.RelativeHighest +OAI.Analysis.Laughlin.Spin.Representation +OAI.Analysis.Laughlin.Spin.Sandwich +OAI.Analysis.Laughlin.Spin.ScaleLimit +OAI.Analysis.Laughlin.Spin.Schur +OAI.Analysis.Laughlin.Spin.Sl2DescendantNorm +OAI.Analysis.Laughlin.Spin.Sl2Matrix +OAI.Analysis.Laughlin.Spin.Sl2Orthogonal +OAI.Analysis.Laughlin.Spin.Specializations +OAI.Analysis.Laughlin.Spin.Support +OAI.Analysis.Laughlin.Spin.TensorAction +OAI.Analysis.Laughlin.Spin.Torus +OAI.Analysis.Laughlin.Spin.TotalSl2Matrix +OAI.Analysis.Laughlin.Spin.TripleLadderIntertwining +OAI.Analysis.Laughlin.Spin.TwoBodyCertificateHaar +OAI.Analysis.Laughlin.Spin.WeightSlice +OAI.Analysis.Laughlin.Tensor.Antisymmetry +OAI.Analysis.Laughlin.Tensor.ExteriorAdjoint +OAI.Analysis.Laughlin.Tensor.ExteriorContraction +OAI.Analysis.Laughlin.Tensor.ExteriorIsometry +OAI.Analysis.Laughlin.Tensor.ExteriorRotation +OAI.Analysis.Laughlin.Tensor.FockEnergy +OAI.Analysis.Laughlin.Tensor.KernelReadout +OAI.Analysis.Laughlin.Tensor.PairContraction +OAI.Analysis.Laughlin.Tensor.PolynomialRealization +OAI.Analysis.Laughlin.Tensor.WeightProducts +OAI.Analysis.Laughlin.ThreeBody.Basic +OAI.Analysis.Laughlin.ThreeBody.Contraction +OAI.Analysis.Laughlin.ThreeBody.Descendants +OAI.Analysis.Laughlin.ThreeBody.FockBudget +OAI.Analysis.Laughlin.ThreeBody.FockComparison +OAI.Analysis.Laughlin.ThreeBody.FockHaar +OAI.Analysis.Laughlin.ThreeBody.FockNull +OAI.Analysis.Laughlin.ThreeBody.FockTail +OAI.Analysis.Laughlin.ThreeBody.Gram +OAI.Analysis.Laughlin.ThreeBody.GramSlice +OAI.Analysis.Laughlin.ThreeBody.GroupIntertwining +OAI.Analysis.Laughlin.ThreeBody.HaarBlocks +OAI.Analysis.Laughlin.ThreeBody.HaarNormalization +OAI.Analysis.Laughlin.ThreeBody.HighestEigen +OAI.Analysis.Laughlin.ThreeBody.HighestFock +OAI.Analysis.Laughlin.ThreeBody.HighestReadout +OAI.Analysis.Laughlin.ThreeBody.HighestRow +OAI.Analysis.Laughlin.ThreeBody.IntegerPolynomial +OAI.Analysis.Laughlin.ThreeBody.LevelTrace +OAI.Analysis.Laughlin.ThreeBody.NullFormula +OAI.Analysis.Laughlin.ThreeBody.NullSectors +OAI.Analysis.Laughlin.ThreeBody.PairAction +OAI.Analysis.Laughlin.ThreeBody.PhysicalKernel +OAI.Analysis.Laughlin.ThreeBody.PhysicalMatrix +OAI.Analysis.Laughlin.ThreeBody.PhysicalTrace +OAI.Analysis.Laughlin.ThreeBody.PolynomialCoefficient +OAI.Analysis.Laughlin.ThreeBody.ProjectorBound +OAI.Analysis.Laughlin.ThreeBody.Radical +OAI.Analysis.Laughlin.ThreeBody.RankTrace +OAI.Analysis.Laughlin.ThreeBody.SourceExpansion +OAI.Analysis.Laughlin.ThreeBody.SpinCovariance +OAI.Analysis.Laughlin.ThreeBody.SpinProjectors +OAI.Analysis.Laughlin.ThreeBody.TraceCertificate +OAI.Analysis.Laughlin.ThreeBody.TraceComparison +OAI.Analysis.Laughlin.ThreeBody.TraceLimit +OAI.Analysis.Laughlin.ThreeBody.TraceReadout diff --git a/tasks/laughlin/solution/reference.py b/tasks/laughlin/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/laughlin/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/laughlin/solution/solve.sh b/tasks/laughlin/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..696a8e0f74992553f5f94facdf3df2e8183975d4 --- /dev/null +++ b/tasks/laughlin/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Laughlin, i.e. module OAI.Analysis.Laughlin.Main and the +# 1258 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Laughlin.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Laughlin" diff --git a/tasks/laughlin/task.toml b/tasks/laughlin/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..250f92f9e46e47f6e26dc214a4d35f2d8d884232 --- /dev/null +++ b/tasks/laughlin/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/laughlin" +version = "1.0.0" +description = "Prove Laughlin (openai/math family 269: The Laughlin gap and stability under scalar disorder) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Laughlin.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Laughlin" +family = "269" +family_title = "The Laughlin gap and stability under scalar disorder" +subject = "Mathematical physics" +theorems = ["OAI.Laughlin.mainTarget_proved"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Laughlin.Main" +reference_modules = 1258 +reference_lean_bytes = 2971285 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 6718 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14374 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/laughlin/tests/Challenge.lean b/tasks/laughlin/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca7d6f7f749474da08c81e28d874eb00b3e96bb4 --- /dev/null +++ b/tasks/laughlin/tests/Challenge.lean @@ -0,0 +1,66 @@ +import Mathlib + +namespace OAI + +namespace Laughlin +open scoped BigOperators + +abbrev Configuration (N Q : ℕ) := Fin N → Fin (Q+1) +abbrev State (N Q : ℕ) := Configuration N Q → ℂ + +def Antisymmetric {N Q : ℕ} (ψ : State N Q) : Prop := + ∀ (i j : Fin N), i ≠ j → ∀ a, ψ (a ∘ Equiv.swap i j) = -ψ a + +noncomputable def pairCoefficient (Q p : ℕ) (x y : Fin (Q+1)) : ℝ := + if x.val + y.val = p+1 then + ((x.val : ℝ) - (y.val : ℝ)) * + Real.sqrt (((Q.descFactorial x.val : ℝ) * (Q.descFactorial y.val : ℝ) * + (p.factorial : ℝ)) / + ((Q : ℝ) * ((2*Q-2).descFactorial p : ℝ) * + (x.val.factorial : ℝ) * (y.val.factorial : ℝ))) / Real.sqrt 2 + else 0 + +noncomputable def pairAmplitude {N Q : ℕ} (ψ : State N Q) + (i j : Fin N) (p : ℕ) (a : Configuration N Q) : ℂ := + ∑ x : Fin (Q+1), ∑ y : Fin (Q+1), + (pairCoefficient Q p x y : ℂ) * ψ (Function.update (Function.update a i x) j y) + +noncomputable def energy {N Q : ℕ} (ψ : State N Q) : ℝ := + ∑ i : Fin N, ∑ j : Fin N, if i < j then + ∑ p ∈ Finset.range (2*Q-1), ∑ a : Configuration N Q, + if a i = 0 ∧ a j = 0 then ‖pairAmplitude ψ i j p a‖ ^ 2 else 0 + else 0 + +abbrev SpinorVariables (N : ℕ) := Fin N × Bool + +noncomputable def bracket {N : ℕ} (i j : Fin N) : MvPolynomial (SpinorVariables N) ℂ := + MvPolynomial.X (i,false) * MvPolynomial.X (j,true) - + MvPolynomial.X (j,false) * MvPolynomial.X (i,true) + +noncomputable def laughlinPolynomial (N : ℕ) : MvPolynomial (SpinorVariables N) ℂ := + ∏ i : Fin N, ∏ j : Fin N, if i < j then bracket i j ^ 3 else 1 + +noncomputable def monomialExponent {N Q : ℕ} (a : Configuration N Q) : SpinorVariables N →₀ ℕ := + Finsupp.onFinset Finset.univ + (fun ib => if ib.2 then (a ib.1).val else Q - (a ib.1).val) + (by intro; simp) + +noncomputable def laughlinVector (N Q : ℕ) : State N Q := fun a => + (laughlinPolynomial N).coeff (monomialExponent a) / + ((∏ i : Fin N, Real.sqrt (Nat.choose Q (a i).val : ℝ) : ℝ) : ℂ) + +noncomputable def distanceToLaughlinSq {N Q : ℕ} (ψ : State N Q) : ℝ := + sInf (Set.range (fun c : ℂ => ∑ a : Configuration N Q, + ‖ψ a - c * laughlinVector N Q a‖ ^ 2)) + +def MainTarget : Prop := + ∃ N₀ : ℕ, 2 ≤ N₀ ∧ ∀ N : ℕ, N₀ ≤ N → + ∀ ψ : State N (3*(N-1)), Antisymmetric ψ → + (1/100 : ℝ) * distanceToLaughlinSq ψ ≤ energy ψ + +theorem mainTarget_proved : MainTarget := by + sorry + +end Laughlin + +end OAI diff --git a/tasks/laughlin/tests/grade.py b/tasks/laughlin/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/laughlin/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/laughlin/tests/task.json b/tasks/laughlin/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2cc07f0696f2a0d7643a27e9355b3759bb1eaa8f --- /dev/null +++ b/tasks/laughlin/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Laughlin", + "comparator": { + "theorem_names": [ + "OAI.Laughlin.mainTarget_proved" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13474 +} \ No newline at end of file diff --git a/tasks/laughlin/tests/test.sh b/tasks/laughlin/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/laughlin/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/lieb-thirring/environment/Dockerfile b/tasks/lieb-thirring/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/lieb-thirring/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/lieb-thirring/environment/fetch_mathlib.sh b/tasks/lieb-thirring/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/lieb-thirring/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/lieb-thirring/environment/lake-manifest.json b/tasks/lieb-thirring/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/lieb-thirring/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/lieb-thirring/environment/lakefile.lean b/tasks/lieb-thirring/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/lieb-thirring/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/lieb-thirring/environment/lean_setup.sh b/tasks/lieb-thirring/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/lieb-thirring/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/lieb-thirring/environment/pack_submission.py b/tasks/lieb-thirring/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/lieb-thirring/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/lieb-thirring/instruction.md b/tasks/lieb-thirring/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..edb67e6fa824dd82dd707523f1308e56c249266e --- /dev/null +++ b/tasks/lieb-thirring/instruction.md @@ -0,0 +1,151 @@ +# openai/math challenge `LiebThirring` (family 262) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 262 of the release, *Sharp one-dimensional Lieb–Thirring inequalities* +(Mathematical physics). The family as a whole: Proves the sharp one-dimensional Lieb–Thirring inequality for $1/2<\gamma<3/2$ and arbitrary finite-matrix potentials $W\ge0$ with $\int\operatorname{tr}(W^{\gamma+1/2})<\infty$: the optimal constant is the scalar one-bound-state value, independent of matrix size. All equality cases are direct sums, in one constant unitary basis, of scalar $\operatorname{sech}^2$ solitons with independent scales and centers, and zero channels. + +The challenge is `LiebThirring`, also at `/opt/openai-math/challenges/LiebThirring.lean`: + +```lean +import Mathlib + +namespace OAI + + +/-! +The form domain is H¹(R;C), represented by an L² function together with its L² +weak derivative. Null-set changes do not affect any definition below. +`negativeMoment` is the extended nonnegative sum over negative eigenvalues, +counting multiplicities: equivalently the supremum over all finite orthonormal +families of weak eigenfunctions of the form. This does not assume in advance +finiteness of the moment or a finite number of eigenvalues. +-/ + + +noncomputable section +open MeasureTheory +open scoped ENNReal Matrix.Norms.L2Operator +open Matrix + +namespace SharpLiebThirring + +structure H1 where + val : ℝ → ℂ + grad : ℝ → ℂ + val_memLp : MemLp val 2 volume + grad_memLp : MemLp grad 2 volume + weak_derivative : ∀ φ : ℝ → ℂ, ContDiff ℝ (↑(⊤ : ℕ∞) : WithTop ℕ∞) φ → HasCompactSupport φ → + (∫ x : ℝ, val x * deriv φ x) = -(∫ x : ℝ, grad x * φ x) + +def l2Pairing (u v : H1) : ℂ := ∫ x : ℝ, star (u.val x) * v.val x + +/-- The polarized form of -d²/dx² - W, on exactly H¹. -/ +def schrodingerForm (W : ℝ → ℝ) (u v : H1) : ℂ := + (∫ x : ℝ, star (u.grad x) * v.grad x) - + ∫ x : ℝ, (W x : ℂ) * star (u.val x) * v.val x + +/-- Weak eigenfunction at the negative energy -k². -/ +def IsNegativeEigenfunction (W : ℝ → ℝ) (k : ℝ) (u : H1) : Prop := + 0 < k ∧ ∀ v : H1, schrodingerForm W v u = -(k ^ 2 : ℝ) * l2Pairing v u + +def IsOrthonormalFamily {N : ℕ} (u : Fin N → H1) : Prop := + ∀ i j, l2Pairing (u i) (u j) = if i = j then 1 else 0 + +/-- An unlimited finite-family-size supremum, in ℝ≥0∞, includes the entire sum. -/ +def negativeMoment (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ⨆ (N : ℕ) (u : Fin N → H1) (k : Fin N → ℝ) + (_ : IsOrthonormalFamily u) (_ : ∀ i, IsNegativeEigenfunction W (k i) (u i)), + ∑ i, (ENNReal.ofReal (k i)) ^ (2 * γ) + +/-- The moment retaining at most one negative eigenvalue. -/ +def oneStateMoment (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ⨆ (u : H1) (k : ℝ) (_ : l2Pairing u u = 1) + (_ : IsNegativeEigenfunction W k u), (ENNReal.ofReal k) ^ (2 * γ) + +def Admissible (γ : ℝ) (W : ℝ → ℝ) : Prop := + (∀ᵐ x : ℝ, 0 ≤ W x) ∧ MemLp W (ENNReal.ofReal (γ + 1 / 2)) volume + +def potentialMass (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ∫⁻ x : ℝ, (ENNReal.ofReal (W x)) ^ (γ + 1 / 2) + +def semiclassicalConstant (γ : ℝ) : ℝ := + Real.Gamma (γ + 1) / (2 * Real.sqrt Real.pi * Real.Gamma (γ + 3 / 2)) + +def sharpConstant (γ : ℝ) : ℝ := + 2 * ((γ - 1 / 2) / (γ + 1 / 2)) ^ (γ - 1 / 2) * semiclassicalConstant γ + +def optimalConstant (γ : ℝ) : ℝ≥0∞ := + ⨆ (W : ℝ → ℝ) (_ : Admissible γ W) (_ : 0 < potentialMass γ W), + negativeMoment γ W / potentialMass γ W + +def oneStateConstant (γ : ℝ) : ℝ≥0∞ := + ⨆ (W : ℝ → ℝ) (_ : Admissible γ W) (_ : 0 < potentialMass γ W), + oneStateMoment γ W / potentialMass γ W + +def equalityPotential (γ : ℝ) (x : ℝ) : ℝ := + let r := (γ - 1 / 2)⁻¹ + (r + 1) * (Real.cosh (r * x))⁻¹ ^ 2 + +/-- The full spectral bound, optimal constants, and attainment at the explicit potential. -/ +def MainClaim : Prop := + ∀ γ : ℝ, 1 / 2 < γ → γ < 3 / 2 → + (∀ W : ℝ → ℝ, Admissible γ W → + negativeMoment γ W ≤ ENNReal.ofReal (sharpConstant γ) * potentialMass γ W) ∧ + optimalConstant γ = ENNReal.ofReal (sharpConstant γ) ∧ + oneStateConstant γ = ENNReal.ofReal (sharpConstant γ) ∧ + Admissible γ (equalityPotential γ) ∧ + 0 < potentialMass γ (equalityPotential γ) ∧ + negativeMoment γ (equalityPotential γ) = + ENNReal.ofReal (sharpConstant γ) * potentialMass γ (equalityPotential γ) + +/-- Full sharp Lieb–Thirring bound, both optimal constants, and equality at the +explicit potential; no finite spectral cutoff is imposed. -/ +theorem sharp_lieb_thirring : MainClaim := by + sorry + +end SharpLiebThirring +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LiebThirring.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SharpLiebThirring.sharp_lieb_thirring` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/lieb-thirring/solution/closure.txt b/tasks/lieb-thirring/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cd06ac665dd8c26fe2a76c8a20a009de8ac812de --- /dev/null +++ b/tasks/lieb-thirring/solution/closure.txt @@ -0,0 +1,38 @@ +OAI.Analysis.LiebThirring.ActionBounds +OAI.Analysis.LiebThirring.ActionPenalty +OAI.Analysis.LiebThirring.BoundState +OAI.Analysis.LiebThirring.BoundaryParity +OAI.Analysis.LiebThirring.BoundaryValues +OAI.Analysis.LiebThirring.ComplexFamilies +OAI.Analysis.LiebThirring.ConnectingPath +OAI.Analysis.LiebThirring.Continuation +OAI.Analysis.LiebThirring.CubeFlags +OAI.Analysis.LiebThirring.CutoffEnergy +OAI.Analysis.LiebThirring.EnergyAlgebra +OAI.Analysis.LiebThirring.EquivariantFlags +OAI.Analysis.LiebThirring.ExtremizerMass +OAI.Analysis.LiebThirring.FieldFlow +OAI.Analysis.LiebThirring.FieldLimit +OAI.Analysis.LiebThirring.FieldPrimitive +OAI.Analysis.LiebThirring.FieldRegularity +OAI.Analysis.LiebThirring.FiniteParity +OAI.Analysis.LiebThirring.FlagApproximation +OAI.Analysis.LiebThirring.FlagGeometry +OAI.Analysis.LiebThirring.FlowContinuation +OAI.Analysis.LiebThirring.FreeLocus +OAI.Analysis.LiebThirring.Gamma +OAI.Analysis.LiebThirring.GenericPosition +OAI.Analysis.LiebThirring.InitialOrbit +OAI.Analysis.LiebThirring.IntervalAction +OAI.Analysis.LiebThirring.Main +OAI.Analysis.LiebThirring.MatrixFlow +OAI.Analysis.LiebThirring.MatrixOrder +OAI.Analysis.LiebThirring.MatrixTangent +OAI.Analysis.LiebThirring.Model +OAI.Analysis.LiebThirring.MomentBound +OAI.Analysis.LiebThirring.QuadraticForms +OAI.Analysis.LiebThirring.RankOne +OAI.Analysis.LiebThirring.ResolventCalculus +OAI.Analysis.LiebThirring.RowSigns +OAI.Analysis.LiebThirring.SobolevProjection +OAI.Analysis.LiebThirring.SpectralTrials diff --git a/tasks/lieb-thirring/solution/reference.py b/tasks/lieb-thirring/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/lieb-thirring/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/lieb-thirring/solution/solve.sh b/tasks/lieb-thirring/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..80fba503438e47b8353dd62760307ce40220c2ad --- /dev/null +++ b/tasks/lieb-thirring/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LiebThirring, i.e. module OAI.Analysis.LiebThirring.Main and the +# 38 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LiebThirring.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LiebThirring" diff --git a/tasks/lieb-thirring/task.toml b/tasks/lieb-thirring/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..39e1bdc7ebfd2df2a505232ac519f40bbb13435c --- /dev/null +++ b/tasks/lieb-thirring/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/lieb-thirring" +version = "1.0.0" +description = "Prove LiebThirring (openai/math family 262: Sharp one-dimensional Lieb–Thirring inequalities) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LiebThirring.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LiebThirring" +family = "262" +family_title = "Sharp one-dimensional Lieb–Thirring inequalities" +subject = "Mathematical physics" +theorems = ["OAI.SharpLiebThirring.sharp_lieb_thirring"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LiebThirring.Main" +reference_modules = 38 +reference_lean_bytes = 654331 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1327 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12288 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/lieb-thirring/tests/Challenge.lean b/tasks/lieb-thirring/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..dce59855cb6b3554256c2a6b0eb45dc113047015 --- /dev/null +++ b/tasks/lieb-thirring/tests/Challenge.lean @@ -0,0 +1,100 @@ +import Mathlib + +namespace OAI + + +/-! +The form domain is H¹(R;C), represented by an L² function together with its L² +weak derivative. Null-set changes do not affect any definition below. +`negativeMoment` is the extended nonnegative sum over negative eigenvalues, +counting multiplicities: equivalently the supremum over all finite orthonormal +families of weak eigenfunctions of the form. This does not assume in advance +finiteness of the moment or a finite number of eigenvalues. +-/ + + +noncomputable section +open MeasureTheory +open scoped ENNReal Matrix.Norms.L2Operator +open Matrix + +namespace SharpLiebThirring + +structure H1 where + val : ℝ → ℂ + grad : ℝ → ℂ + val_memLp : MemLp val 2 volume + grad_memLp : MemLp grad 2 volume + weak_derivative : ∀ φ : ℝ → ℂ, ContDiff ℝ (↑(⊤ : ℕ∞) : WithTop ℕ∞) φ → HasCompactSupport φ → + (∫ x : ℝ, val x * deriv φ x) = -(∫ x : ℝ, grad x * φ x) + +def l2Pairing (u v : H1) : ℂ := ∫ x : ℝ, star (u.val x) * v.val x + +/-- The polarized form of -d²/dx² - W, on exactly H¹. -/ +def schrodingerForm (W : ℝ → ℝ) (u v : H1) : ℂ := + (∫ x : ℝ, star (u.grad x) * v.grad x) - + ∫ x : ℝ, (W x : ℂ) * star (u.val x) * v.val x + +/-- Weak eigenfunction at the negative energy -k². -/ +def IsNegativeEigenfunction (W : ℝ → ℝ) (k : ℝ) (u : H1) : Prop := + 0 < k ∧ ∀ v : H1, schrodingerForm W v u = -(k ^ 2 : ℝ) * l2Pairing v u + +def IsOrthonormalFamily {N : ℕ} (u : Fin N → H1) : Prop := + ∀ i j, l2Pairing (u i) (u j) = if i = j then 1 else 0 + +/-- An unlimited finite-family-size supremum, in ℝ≥0∞, includes the entire sum. -/ +def negativeMoment (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ⨆ (N : ℕ) (u : Fin N → H1) (k : Fin N → ℝ) + (_ : IsOrthonormalFamily u) (_ : ∀ i, IsNegativeEigenfunction W (k i) (u i)), + ∑ i, (ENNReal.ofReal (k i)) ^ (2 * γ) + +/-- The moment retaining at most one negative eigenvalue. -/ +def oneStateMoment (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ⨆ (u : H1) (k : ℝ) (_ : l2Pairing u u = 1) + (_ : IsNegativeEigenfunction W k u), (ENNReal.ofReal k) ^ (2 * γ) + +def Admissible (γ : ℝ) (W : ℝ → ℝ) : Prop := + (∀ᵐ x : ℝ, 0 ≤ W x) ∧ MemLp W (ENNReal.ofReal (γ + 1 / 2)) volume + +def potentialMass (γ : ℝ) (W : ℝ → ℝ) : ℝ≥0∞ := + ∫⁻ x : ℝ, (ENNReal.ofReal (W x)) ^ (γ + 1 / 2) + +def semiclassicalConstant (γ : ℝ) : ℝ := + Real.Gamma (γ + 1) / (2 * Real.sqrt Real.pi * Real.Gamma (γ + 3 / 2)) + +def sharpConstant (γ : ℝ) : ℝ := + 2 * ((γ - 1 / 2) / (γ + 1 / 2)) ^ (γ - 1 / 2) * semiclassicalConstant γ + +def optimalConstant (γ : ℝ) : ℝ≥0∞ := + ⨆ (W : ℝ → ℝ) (_ : Admissible γ W) (_ : 0 < potentialMass γ W), + negativeMoment γ W / potentialMass γ W + +def oneStateConstant (γ : ℝ) : ℝ≥0∞ := + ⨆ (W : ℝ → ℝ) (_ : Admissible γ W) (_ : 0 < potentialMass γ W), + oneStateMoment γ W / potentialMass γ W + +def equalityPotential (γ : ℝ) (x : ℝ) : ℝ := + let r := (γ - 1 / 2)⁻¹ + (r + 1) * (Real.cosh (r * x))⁻¹ ^ 2 + +/-- The full spectral bound, optimal constants, and attainment at the explicit potential. -/ +def MainClaim : Prop := + ∀ γ : ℝ, 1 / 2 < γ → γ < 3 / 2 → + (∀ W : ℝ → ℝ, Admissible γ W → + negativeMoment γ W ≤ ENNReal.ofReal (sharpConstant γ) * potentialMass γ W) ∧ + optimalConstant γ = ENNReal.ofReal (sharpConstant γ) ∧ + oneStateConstant γ = ENNReal.ofReal (sharpConstant γ) ∧ + Admissible γ (equalityPotential γ) ∧ + 0 < potentialMass γ (equalityPotential γ) ∧ + negativeMoment γ (equalityPotential γ) = + ENNReal.ofReal (sharpConstant γ) * potentialMass γ (equalityPotential γ) + +/-- Full sharp Lieb–Thirring bound, both optimal constants, and equality at the +explicit potential; no finite spectral cutoff is imposed. -/ +theorem sharp_lieb_thirring : MainClaim := by + sorry + +end SharpLiebThirring +end + +end OAI diff --git a/tasks/lieb-thirring/tests/grade.py b/tasks/lieb-thirring/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/lieb-thirring/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/lieb-thirring/tests/task.json b/tasks/lieb-thirring/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5ac5576b0f33d9fd52b63ea80bfa452b19dbaf71 --- /dev/null +++ b/tasks/lieb-thirring/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LiebThirring", + "comparator": { + "theorem_names": [ + "OAI.SharpLiebThirring.sharp_lieb_thirring" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11388 +} \ No newline at end of file diff --git a/tasks/lieb-thirring/tests/test.sh b/tasks/lieb-thirring/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/lieb-thirring/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/lipschitz-equivalence/environment/Dockerfile b/tasks/lipschitz-equivalence/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/lipschitz-equivalence/environment/fetch_mathlib.sh b/tasks/lipschitz-equivalence/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/lipschitz-equivalence/environment/lake-manifest.json b/tasks/lipschitz-equivalence/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/lipschitz-equivalence/environment/lakefile.lean b/tasks/lipschitz-equivalence/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/lipschitz-equivalence/environment/lean_setup.sh b/tasks/lipschitz-equivalence/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/lipschitz-equivalence/environment/pack_submission.py b/tasks/lipschitz-equivalence/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/lipschitz-equivalence/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/lipschitz-equivalence/instruction.md b/tasks/lipschitz-equivalence/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6cf3de6a6f3557cb54ff6c20201b77e3c3c3093a --- /dev/null +++ b/tasks/lipschitz-equivalence/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `LipschitzEquivalence` (family 324) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 324 of the release, *Lipschitz equivalence without linear isomorphism* +(Functional analysis). The family as a whole: Constructs separable real Banach spaces that are globally bi-Lipschitz equivalent but not linearly isomorphic, resolving the separable Lipschitz-isomorphism problem negatively. Thus even the complete metric structure up to bi-Lipschitz equivalence does not determine a separable Banach space's linear isomorphism class. + +The challenge is `LipschitzEquivalence`, also at `/opt/openai-math/challenges/LipschitzEquivalence.lean`: + +```lean +import Mathlib + +namespace OAI + +universe uE uF + +noncomputable section +namespace LipschitzCounterexample + +abbrev RealL2 := lp (fun _ : ℕ => ℝ) 2 +abbrev C0L2 := ZeroAtInftyContinuousMap ℕ RealL2 + +structure SeparableRealBanach where + Carrier : Type + [normedAddCommGroup : NormedAddCommGroup Carrier] + [normedSpace : NormedSpace ℝ Carrier] + [completeSpace : CompleteSpace Carrier] + [separableSpace : TopologicalSpace.SeparableSpace Carrier] + +attribute [instance] SeparableRealBanach.normedAddCommGroup + SeparableRealBanach.normedSpace SeparableRealBanach.completeSpace + SeparableRealBanach.separableSpace + +def ContainsLinearCopy (E : Type uE) (F : Type uF) [NormedAddCommGroup E] [NormedSpace ℝ E] + [NormedAddCommGroup F] [NormedSpace ℝ F] : Prop := + ∃ (T : E →L[ℝ] F) (a : ℝ), 0 < a ∧ ∀ x : E, a * ‖x‖ ≤ ‖T x‖ + +def MainClaim : Prop := + ∃ X Y : SeparableRealBanach, + ∃ Ψ : X.Carrier ≃ Y.Carrier, + (∀ s t : X.Carrier, + (4 / 21 : ℝ) * ‖s - t‖ ≤ ‖Ψ s - Ψ t‖ ∧ + ‖Ψ s - Ψ t‖ ≤ (76 / 25 : ℝ) * ‖s - t‖) ∧ + IsEmpty (X.Carrier ≃L[ℝ] Y.Carrier) ∧ + Nonempty (C0L2 →ₗᵢ[ℝ] X.Carrier) ∧ + ¬ ContainsLinearCopy C0L2 Y.Carrier + +theorem main : MainClaim := by + sorry + +end LipschitzCounterexample +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LipschitzEquivalence.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LipschitzCounterexample.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/lipschitz-equivalence/solution/closure.txt b/tasks/lipschitz-equivalence/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2bb29bce1fb20199d27e7212ef6e1d4df664a6b --- /dev/null +++ b/tasks/lipschitz-equivalence/solution/closure.txt @@ -0,0 +1,60 @@ +OAI.Analysis.LipschitzEquivalence.BanachAssembly +OAI.Analysis.LipschitzEquivalence.BidualSeparation +OAI.Analysis.LipschitzEquivalence.BlockSelection +OAI.Analysis.LipschitzEquivalence.CauchyApproximation +OAI.Analysis.LipschitzEquivalence.CauchyReduction +OAI.Analysis.LipschitzEquivalence.CompactHilbertWSC +OAI.Analysis.LipschitzEquivalence.CompactLipschitz +OAI.Analysis.LipschitzEquivalence.CompactLocalization +OAI.Analysis.LipschitzEquivalence.CompactReduction +OAI.Analysis.LipschitzEquivalence.CompactSupports +OAI.Analysis.LipschitzEquivalence.CompleteContinuity +OAI.Analysis.LipschitzEquivalence.DetectingSequence +OAI.Analysis.LipschitzEquivalence.EnergyEstimates +OAI.Analysis.LipschitzEquivalence.FiniteApproximants +OAI.Analysis.LipschitzEquivalence.FiniteMultipliers +OAI.Analysis.LipschitzEquivalence.FiniteReduction +OAI.Analysis.LipschitzEquivalence.FiniteRows +OAI.Analysis.LipschitzEquivalence.FreeSpace +OAI.Analysis.LipschitzEquivalence.GlobalInverse +OAI.Analysis.LipschitzEquivalence.GraphEmbedding +OAI.Analysis.LipschitzEquivalence.GraphEquivalence +OAI.Analysis.LipschitzEquivalence.GraphObstruction +OAI.Analysis.LipschitzEquivalence.HilbertBijection +OAI.Analysis.LipschitzEquivalence.HilbertBlocks +OAI.Analysis.LipschitzEquivalence.HilbertDecomposition +OAI.Analysis.LipschitzEquivalence.InverseTails +OAI.Analysis.LipschitzEquivalence.LinearizationContinuity +OAI.Analysis.LipschitzEquivalence.LocalLipschitz +OAI.Analysis.LipschitzEquivalence.LocalOrthogonality +OAI.Analysis.LipschitzEquivalence.Localization +OAI.Analysis.LipschitzEquivalence.Main +OAI.Analysis.LipschitzEquivalence.Model +OAI.Analysis.LipschitzEquivalence.MolecularApproximation +OAI.Analysis.LipschitzEquivalence.MovingSlots +OAI.Analysis.LipschitzEquivalence.Multipliers +OAI.Analysis.LipschitzEquivalence.NullSequences +OAI.Analysis.LipschitzEquivalence.PairingEstimates +OAI.Analysis.LipschitzEquivalence.RadialBudget +OAI.Analysis.LipschitzEquivalence.RadiusReduction +OAI.Analysis.LipschitzEquivalence.RotatingStages +OAI.Analysis.LipschitzEquivalence.Schur +OAI.Analysis.LipschitzEquivalence.SelectionStep +OAI.Analysis.LipschitzEquivalence.SeparableCoordinates +OAI.Analysis.LipschitzEquivalence.SeparatingCoordinates +OAI.Analysis.LipschitzEquivalence.ShrinkingCutoffs +OAI.Analysis.LipschitzEquivalence.SlotBudget +OAI.Analysis.LipschitzEquivalence.SlotRadii +OAI.Analysis.LipschitzEquivalence.SlowAngles +OAI.Analysis.LipschitzEquivalence.SmoothCalculus +OAI.Analysis.LipschitzEquivalence.SmoothHilbert +OAI.Analysis.LipschitzEquivalence.SmoothMultiplier +OAI.Analysis.LipschitzEquivalence.SmoothRows +OAI.Analysis.LipschitzEquivalence.SupportedDuality +OAI.Analysis.LipschitzEquivalence.TriangularDuals +OAI.Analysis.LipschitzEquivalence.WUCDuals +OAI.Analysis.LipschitzEquivalence.WUCFunctions +OAI.Analysis.LipschitzEquivalence.WUCOperator +OAI.Analysis.LipschitzEquivalence.WeakCauchy +OAI.Analysis.LipschitzEquivalence.WeakSums +OAI.Analysis.LipschitzEquivalence.WeightedGraph diff --git a/tasks/lipschitz-equivalence/solution/reference.py b/tasks/lipschitz-equivalence/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/lipschitz-equivalence/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/lipschitz-equivalence/solution/solve.sh b/tasks/lipschitz-equivalence/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f5fc88c2f4611b5a1aff5e1e83f28d6311f0b639 --- /dev/null +++ b/tasks/lipschitz-equivalence/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LipschitzEquivalence, i.e. module OAI.Analysis.LipschitzEquivalence.Main and the +# 60 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LipschitzEquivalence.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LipschitzEquivalence" diff --git a/tasks/lipschitz-equivalence/task.toml b/tasks/lipschitz-equivalence/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49e466fd53b08c0b66c4d110927a8b004814151d --- /dev/null +++ b/tasks/lipschitz-equivalence/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/lipschitz-equivalence" +version = "1.0.0" +description = "Prove LipschitzEquivalence (openai/math family 324: Lipschitz equivalence without linear isomorphism) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LipschitzEquivalence.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LipschitzEquivalence" +family = "324" +family_title = "Lipschitz equivalence without linear isomorphism" +subject = "Functional analysis" +theorems = ["OAI.LipschitzCounterexample.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LipschitzEquivalence.Main" +reference_modules = 60 +reference_lean_bytes = 475733 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1251 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12128 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/lipschitz-equivalence/tests/Challenge.lean b/tasks/lipschitz-equivalence/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e039fab26d766460d46663f2cedb0310630c17a --- /dev/null +++ b/tasks/lipschitz-equivalence/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +universe uE uF + +noncomputable section +namespace LipschitzCounterexample + +abbrev RealL2 := lp (fun _ : ℕ => ℝ) 2 +abbrev C0L2 := ZeroAtInftyContinuousMap ℕ RealL2 + +structure SeparableRealBanach where + Carrier : Type + [normedAddCommGroup : NormedAddCommGroup Carrier] + [normedSpace : NormedSpace ℝ Carrier] + [completeSpace : CompleteSpace Carrier] + [separableSpace : TopologicalSpace.SeparableSpace Carrier] + +attribute [instance] SeparableRealBanach.normedAddCommGroup + SeparableRealBanach.normedSpace SeparableRealBanach.completeSpace + SeparableRealBanach.separableSpace + +def ContainsLinearCopy (E : Type uE) (F : Type uF) [NormedAddCommGroup E] [NormedSpace ℝ E] + [NormedAddCommGroup F] [NormedSpace ℝ F] : Prop := + ∃ (T : E →L[ℝ] F) (a : ℝ), 0 < a ∧ ∀ x : E, a * ‖x‖ ≤ ‖T x‖ + +def MainClaim : Prop := + ∃ X Y : SeparableRealBanach, + ∃ Ψ : X.Carrier ≃ Y.Carrier, + (∀ s t : X.Carrier, + (4 / 21 : ℝ) * ‖s - t‖ ≤ ‖Ψ s - Ψ t‖ ∧ + ‖Ψ s - Ψ t‖ ≤ (76 / 25 : ℝ) * ‖s - t‖) ∧ + IsEmpty (X.Carrier ≃L[ℝ] Y.Carrier) ∧ + Nonempty (C0L2 →ₗᵢ[ℝ] X.Carrier) ∧ + ¬ ContainsLinearCopy C0L2 Y.Carrier + +theorem main : MainClaim := by + sorry + +end LipschitzCounterexample +end + +end OAI diff --git a/tasks/lipschitz-equivalence/tests/grade.py b/tasks/lipschitz-equivalence/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/lipschitz-equivalence/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/lipschitz-equivalence/tests/task.json b/tasks/lipschitz-equivalence/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ce2fe5c4d9e181786e43b7e7ccc3391a34d0df04 --- /dev/null +++ b/tasks/lipschitz-equivalence/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LipschitzEquivalence", + "comparator": { + "theorem_names": [ + "OAI.LipschitzCounterexample.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11228 +} \ No newline at end of file diff --git a/tasks/lipschitz-equivalence/tests/test.sh b/tasks/lipschitz-equivalence/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/lipschitz-equivalence/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/lipschitz-hilbert/environment/Dockerfile b/tasks/lipschitz-hilbert/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/lipschitz-hilbert/environment/fetch_mathlib.sh b/tasks/lipschitz-hilbert/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/lipschitz-hilbert/environment/lake-manifest.json b/tasks/lipschitz-hilbert/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/lipschitz-hilbert/environment/lakefile.lean b/tasks/lipschitz-hilbert/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/lipschitz-hilbert/environment/lean_setup.sh b/tasks/lipschitz-hilbert/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/lipschitz-hilbert/environment/pack_submission.py b/tasks/lipschitz-hilbert/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/lipschitz-hilbert/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/lipschitz-hilbert/instruction.md b/tasks/lipschitz-hilbert/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..925de435d52e8c78d177efde4d1e9dee63c9cf8b --- /dev/null +++ b/tasks/lipschitz-hilbert/instruction.md @@ -0,0 +1,131 @@ +# openai/math challenge `LipschitzHilbert` (family 083) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 083 of the release, *Stein's conjecture for Hilbert transforms along Lipschitz directions* +(Real and complex analysis). The family as a whole: Proves a uniform strong $L^2$ bound for the planar Hilbert transform along any Lipschitz unit vector field, at integration lengths bounded by an absolute multiple of its reciprocal Lipschitz constant. The estimate is uniform over inner truncations and yields an $L^2$-bounded principal-value operator, establishing Stein's weak-type conjecture at this short scale. + +The challenge is `LipschitzHilbert`, also at `/opt/openai-math/challenges/LipschitzHilbert.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +/- Use the normed-field structure on ℂ for real scalar multiplication. -/ +attribute [-instance] instCommCStarAlgebraComplex + +open MeasureTheory Set +open scoped ENNReal NNReal + +namespace LipschitzHilbert + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev DirectionPlane := EuclideanSpace ℝ (Fin 2) + +def sample (v : DirectionPlane → DirectionPlane) (t : ℝ) (x : DirectionPlane) : + DirectionPlane := x - t • v x + +/-- The symmetrized form of the hard-truncated directional integral. -/ +def shortTransform (v : DirectionPlane → DirectionPlane) (ε a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + ∫ t in ε..a, t⁻¹ • (f (sample v t x) - f (sample v (-t) x)) + +def directionalKernel (v : DirectionPlane → DirectionPlane) + (f : DirectionPlane → ℂ) (x : DirectionPlane) (t : ℝ) : ℂ := + t⁻¹ • f (sample v t x) + +/-- The two hard-cutoff intervals in the directional Hilbert transform. -/ +def twoSidedTruncation (v : DirectionPlane → DirectionPlane) (ε a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + (∫ t in -a..-ε, directionalKernel v f x t) + + ∫ t in ε..a, directionalKernel v f x t + +/-- The symmetric quotient extended continuously at zero for smooth inputs. -/ +def smoothPrincipalValue (v : DirectionPlane → DirectionPlane) (a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + let g := fun t : ℝ => f (sample v t x)-f (sample v (-t) x) + ∫ t in (0:ℝ)..a, Function.update (fun t => t⁻¹ • g t) 0 (deriv g 0) t + +attribute [instance] instCommCStarAlgebraComplex + +def ShortHilbertConclusion (a : ℝ) (C : ℝ≥0) : Prop := + ∀ v : Plane → Plane, LipschitzWith 1 v → (∀ x, ‖v x‖=1) → + (∀ epsilon : ℝ, 0` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/lipschitz-hilbert/solution/closure.txt b/tasks/lipschitz-hilbert/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cfee7b79366ed1f89f6fc34bb4b7fa1747a7a0ef --- /dev/null +++ b/tasks/lipschitz-hilbert/solution/closure.txt @@ -0,0 +1,1910 @@ +OAI.Analysis.LipschitzHilbert.ConditionalMain +OAI.Analysis.LipschitzHilbert.Estimates.ActualBinPairing +OAI.Analysis.LipschitzHilbert.Estimates.ActualBinReconstruction +OAI.Analysis.LipschitzHilbert.Estimates.ActualErrorSource +OAI.Analysis.LipschitzHilbert.Estimates.AdmissibleListCount +OAI.Analysis.LipschitzHilbert.Estimates.AllDyadicWeakL1 +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeAllWeights +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeApproximation +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeApproximationL1 +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeClassBound +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeClassCount +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeClassSum +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeDiscardedSum +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeDisparity +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeEnergy +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeErrorDecay +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeLevelL1 +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeLp +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeMatrixBound +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeMatrixNormalization +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeNormalizedEnergy +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeRetainedDecay +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeRetainedSum +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeTailCost +OAI.Analysis.LipschitzHilbert.Estimates.AmplitudeTailParameters +OAI.Analysis.LipschitzHilbert.Estimates.AveragedSquareMoment +OAI.Analysis.LipschitzHilbert.Estimates.BinCarleson +OAI.Analysis.LipschitzHilbert.Estimates.BinErrorParameters +OAI.Analysis.LipschitzHilbert.Estimates.BinaryDensityBound +OAI.Analysis.LipschitzHilbert.Estimates.BoundedDuality +OAI.Analysis.LipschitzHilbert.Estimates.BoundedProjectedOutput +OAI.Analysis.LipschitzHilbert.Estimates.BoundedSupportedCoordinates +OAI.Analysis.LipschitzHilbert.Estimates.BoxPolynomialWeight +OAI.Analysis.LipschitzHilbert.Estimates.BoxSynthesisEnergy +OAI.Analysis.LipschitzHilbert.Estimates.BoxVariationWeights +OAI.Analysis.LipschitzHilbert.Estimates.CarlesonExponential +OAI.Analysis.LipschitzHilbert.Estimates.CarlesonProductEnergy +OAI.Analysis.LipschitzHilbert.Estimates.CarlesonSorting +OAI.Analysis.LipschitzHilbert.Estimates.CarrierSlopeMotion +OAI.Analysis.LipschitzHilbert.Estimates.ChartPullback +OAI.Analysis.LipschitzHilbert.Estimates.ClippedAverage +OAI.Analysis.LipschitzHilbert.Estimates.ClippedSlopeBox +OAI.Analysis.LipschitzHilbert.Estimates.CoefficientDecomposition +OAI.Analysis.LipschitzHilbert.Estimates.CoefficientPolarization +OAI.Analysis.LipschitzHilbert.Estimates.ColoredPlanarEnergy +OAI.Analysis.LipschitzHilbert.Estimates.CompactCompositionCommutator +OAI.Analysis.LipschitzHilbert.Estimates.CompactMollification +OAI.Analysis.LipschitzHilbert.Estimates.CompactMollificationFamily +OAI.Analysis.LipschitzHilbert.Estimates.CompactMollificationL2 +OAI.Analysis.LipschitzHilbert.Estimates.CompactMollificationSupport +OAI.Analysis.LipschitzHilbert.Estimates.CompactWitness +OAI.Analysis.LipschitzHilbert.Estimates.ComparableCommutatorSum +OAI.Analysis.LipschitzHilbert.Estimates.ComparableDerivativeSum +OAI.Analysis.LipschitzHilbert.Estimates.ComparableDerivativeSupport +OAI.Analysis.LipschitzHilbert.Estimates.ComparableSelectedSlab +OAI.Analysis.LipschitzHilbert.Estimates.ComplexVariation +OAI.Analysis.LipschitzHilbert.Estimates.ComplexVariationCoordinates +OAI.Analysis.LipschitzHilbert.Estimates.ConditionalSlopeOperator +OAI.Analysis.LipschitzHilbert.Estimates.ConditionalSlopePrincipalValue +OAI.Analysis.LipschitzHilbert.Estimates.ConditionalUniformTruncation +OAI.Analysis.LipschitzHilbert.Estimates.ConditionalVariableEndpoints +OAI.Analysis.LipschitzHilbert.Estimates.ConstructedCovariantTop +OAI.Analysis.LipschitzHilbert.Estimates.ConstructedGlobalNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.ConstructedSynthesisNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.ConstructedTopFamily +OAI.Analysis.LipschitzHilbert.Estimates.ConstructedTopNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.ContinuousBMOMoments +OAI.Analysis.LipschitzHilbert.Estimates.ContinuousBMOTail +OAI.Analysis.LipschitzHilbert.Estimates.CountGeometryParameters +OAI.Analysis.LipschitzHilbert.Estimates.CountParameters +OAI.Analysis.LipschitzHilbert.Estimates.CountThreshold +OAI.Analysis.LipschitzHilbert.Estimates.CountableCarleson +OAI.Analysis.LipschitzHilbert.Estimates.CountingDiscard +OAI.Analysis.LipschitzHilbert.Estimates.CubicDualityEstimate +OAI.Analysis.LipschitzHilbert.Estimates.DampedSimplexBounds +OAI.Analysis.LipschitzHilbert.Estimates.DisjointIntervalVariation +OAI.Analysis.LipschitzHilbert.Estimates.DyadicErrorProfile +OAI.Analysis.LipschitzHilbert.Estimates.DyadicErrorSource +OAI.Analysis.LipschitzHilbert.Estimates.DyadicLongScales +OAI.Analysis.LipschitzHilbert.Estimates.DyadicMeasureClass +OAI.Analysis.LipschitzHilbert.Estimates.DyadicSmoothEmbedding +OAI.Analysis.LipschitzHilbert.Estimates.DyadicSquareWeakL1 +OAI.Analysis.LipschitzHilbert.Estimates.DyadicWeakL1 +OAI.Analysis.LipschitzHilbert.Estimates.EndpointWeightBounds +OAI.Analysis.LipschitzHilbert.Estimates.EnvelopeDerivative +OAI.Analysis.LipschitzHilbert.Estimates.EnvelopeSynthesis +OAI.Analysis.LipschitzHilbert.Estimates.ErrorSourceBridge +OAI.Analysis.LipschitzHilbert.Estimates.ErrorSynthesisVariation +OAI.Analysis.LipschitzHilbert.Estimates.ExponentialThreshold +OAI.Analysis.LipschitzHilbert.Estimates.ExponentialVariation +OAI.Analysis.LipschitzHilbert.Estimates.FatTopTail +OAI.Analysis.LipschitzHilbert.Estimates.FiniteAmplitudeGeometric +OAI.Analysis.LipschitzHilbert.Estimates.FiniteBinCommutator +OAI.Analysis.LipschitzHilbert.Estimates.FiniteCarlesonEmbedding +OAI.Analysis.LipschitzHilbert.Estimates.FiniteClassRegroup +OAI.Analysis.LipschitzHilbert.Estimates.FiniteCommutatorSquare +OAI.Analysis.LipschitzHilbert.Estimates.FiniteEnergySchur +OAI.Analysis.LipschitzHilbert.Estimates.FiniteLogAmplitudeSum +OAI.Analysis.LipschitzHilbert.Estimates.FiniteMatrixDiscard +OAI.Analysis.LipschitzHilbert.Estimates.FiniteMeasureLepingle +OAI.Analysis.LipschitzHilbert.Estimates.FiniteMultiplierRecombination +OAI.Analysis.LipschitzHilbert.Estimates.FiniteNarrowPartition +OAI.Analysis.LipschitzHilbert.Estimates.FiniteRemovalIteration +OAI.Analysis.LipschitzHilbert.Estimates.FiniteRestrictedStrong +OAI.Analysis.LipschitzHilbert.Estimates.FiniteRestrictedStrongNull +OAI.Analysis.LipschitzHilbert.Estimates.FiniteSchur +OAI.Analysis.LipschitzHilbert.Estimates.FiniteSignedEnergy +OAI.Analysis.LipschitzHilbert.Estimates.FiniteSignedFunctions +OAI.Analysis.LipschitzHilbert.Estimates.FiniteSlopeGeometry +OAI.Analysis.LipschitzHilbert.Estimates.FiniteSmoothProduct +OAI.Analysis.LipschitzHilbert.Estimates.FiniteUnitAverage +OAI.Analysis.LipschitzHilbert.Estimates.FiniteUnitAverageL1 +OAI.Analysis.LipschitzHilbert.Estimates.FiniteVariation +OAI.Analysis.LipschitzHilbert.Estimates.FirstArrival +OAI.Analysis.LipschitzHilbert.Estimates.FirstExceed +OAI.Analysis.LipschitzHilbert.Estimates.FrozenSlopeMultiplier +OAI.Analysis.LipschitzHilbert.Estimates.GeometricScaleWeights +OAI.Analysis.LipschitzHilbert.Estimates.GeometricTailExponential +OAI.Analysis.LipschitzHilbert.Estimates.GeometricTailMoments +OAI.Analysis.LipschitzHilbert.Estimates.GlobalExceptionalArea +OAI.Analysis.LipschitzHilbert.Estimates.GlobalLocalNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.GlobalNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.GlobalTopBoxes +OAI.Analysis.LipschitzHilbert.Estimates.HalfPowerDualTest +OAI.Analysis.LipschitzHilbert.Estimates.HardyPairL4 +OAI.Analysis.LipschitzHilbert.Estimates.Hellinger +OAI.Analysis.LipschitzHilbert.Estimates.HilbertArbitraryEndpoint +OAI.Analysis.LipschitzHilbert.Estimates.HilbertEndpointCases +OAI.Analysis.LipschitzHilbert.Estimates.HilbertFiniteFourth +OAI.Analysis.LipschitzHilbert.Estimates.HilbertFiniteL2 +OAI.Analysis.LipschitzHilbert.Estimates.HilbertSharpPairing +OAI.Analysis.LipschitzHilbert.Estimates.HilbertSignFourth +OAI.Analysis.LipschitzHilbert.Estimates.HilbertTimeDecomposition +OAI.Analysis.LipschitzHilbert.Estimates.HilbertTimeProfile +OAI.Analysis.LipschitzHilbert.Estimates.HilbertVariation +OAI.Analysis.LipschitzHilbert.Estimates.HorizontalDilation +OAI.Analysis.LipschitzHilbert.Estimates.HorizontalHilbertLp +OAI.Analysis.LipschitzHilbert.Estimates.HorizontalHilbertPairing +OAI.Analysis.LipschitzHilbert.Estimates.HorizontalHilbertProof +OAI.Analysis.LipschitzHilbert.Estimates.IntGeometricSum +OAI.Analysis.LipschitzHilbert.Estimates.IntegerSlopeMultiplicity +OAI.Analysis.LipschitzHilbert.Estimates.IntegralMinkowski +OAI.Analysis.LipschitzHilbert.Estimates.IntervalOscillation +OAI.Analysis.LipschitzHilbert.Estimates.IntervalPoincare +OAI.Analysis.LipschitzHilbert.Estimates.IntervalPolarization +OAI.Analysis.LipschitzHilbert.Estimates.IntervalSegmentCharging +OAI.Analysis.LipschitzHilbert.Estimates.JointLatticeAverage +OAI.Analysis.LipschitzHilbert.Estimates.L1MultiplierDominatedLimit +OAI.Analysis.LipschitzHilbert.Estimates.L2Conjugation +OAI.Analysis.LipschitzHilbert.Estimates.L2Indicator +OAI.Analysis.LipschitzHilbert.Estimates.L2IndicatorAlgebra +OAI.Analysis.LipschitzHilbert.Estimates.L2SpatialPartition +OAI.Analysis.LipschitzHilbert.Estimates.LaminarCarleson +OAI.Analysis.LipschitzHilbert.Estimates.LaminarChains +OAI.Analysis.LipschitzHilbert.Estimates.LaminarWeakL1 +OAI.Analysis.LipschitzHilbert.Estimates.LayerEnergyMoments +OAI.Analysis.LipschitzHilbert.Estimates.LepingleIntervals +OAI.Analysis.LipschitzHilbert.Estimates.LepingleProof +OAI.Analysis.LipschitzHilbert.Estimates.LipschitzCompositionCommutator +OAI.Analysis.LipschitzHilbert.Estimates.LocalSelectedWidths +OAI.Analysis.LipschitzHilbert.Estimates.LocalizedEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.LocalizedMihlinProfile +OAI.Analysis.LipschitzHilbert.Estimates.LocalizedSelectorDerivative +OAI.Analysis.LipschitzHilbert.Estimates.LocalizedSubbandOperator +OAI.Analysis.LipschitzHilbert.Estimates.LogEnergy +OAI.Analysis.LipschitzHilbert.Estimates.LogEnergyGradient +OAI.Analysis.LipschitzHilbert.Estimates.LongDyadicSum +OAI.Analysis.LipschitzHilbert.Estimates.LongHilbertPairing +OAI.Analysis.LipschitzHilbert.Estimates.LongScaleVariation +OAI.Analysis.LipschitzHilbert.Estimates.MarkedCost +OAI.Analysis.LipschitzHilbert.Estimates.MarkedShells +OAI.Analysis.LipschitzHilbert.Estimates.MartingaleExitTimes +OAI.Analysis.LipschitzHilbert.Estimates.MartingaleGeometricTail +OAI.Analysis.LipschitzHilbert.Estimates.MartingaleGoodLambda +OAI.Analysis.LipschitzHilbert.Estimates.MartingaleLocalMaximal +OAI.Analysis.LipschitzHilbert.Estimates.MartingaleMaximalL2 +OAI.Analysis.LipschitzHilbert.Estimates.MaskComparison +OAI.Analysis.LipschitzHilbert.Estimates.MaskIntegral +OAI.Analysis.LipschitzHilbert.Estimates.MaskNormalization +OAI.Analysis.LipschitzHilbert.Estimates.MaskParameters +OAI.Analysis.LipschitzHilbert.Estimates.MaximalContainmentExclusion +OAI.Analysis.LipschitzHilbert.Estimates.MaximalL2Energy +OAI.Analysis.LipschitzHilbert.Estimates.MeanOscillation +OAI.Analysis.LipschitzHilbert.Estimates.MeasureClassLog +OAI.Analysis.LipschitzHilbert.Estimates.MihlinPVCommutator +OAI.Analysis.LipschitzHilbert.Estimates.MihlinTimeCommutator +OAI.Analysis.LipschitzHilbert.Estimates.MixedNorms +OAI.Analysis.LipschitzHilbert.Estimates.MixedTopTail +OAI.Analysis.LipschitzHilbert.Estimates.MomentSuperlevel +OAI.Analysis.LipschitzHilbert.Estimates.MonotoneCoefficientSum +OAI.Analysis.LipschitzHilbert.Estimates.MovingExponentialWeights +OAI.Analysis.LipschitzHilbert.Estimates.MovingSegmentLogs +OAI.Analysis.LipschitzHilbert.Estimates.MovingSegmentWeights +OAI.Analysis.LipschitzHilbert.Estimates.MovingWeightBudget +OAI.Analysis.LipschitzHilbert.Estimates.MultiplierError +OAI.Analysis.LipschitzHilbert.Estimates.NarrowPartitionBound +OAI.Analysis.LipschitzHilbert.Estimates.NarrowPartitionReconstruction +OAI.Analysis.LipschitzHilbert.Estimates.NarrowWindowNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.NeighborhoodEnergy +OAI.Analysis.LipschitzHilbert.Estimates.NeighborhoodExceptional +OAI.Analysis.LipschitzHilbert.Estimates.NeighborhoodGeometric +OAI.Analysis.LipschitzHilbert.Estimates.NestedAverage +OAI.Analysis.LipschitzHilbert.Estimates.NestedPerturbation +OAI.Analysis.LipschitzHilbert.Estimates.NormalizedLatticeAverage +OAI.Analysis.LipschitzHilbert.Estimates.NormalizedLatticeSpectrum +OAI.Analysis.LipschitzHilbert.Estimates.NormalizedProfileBudget +OAI.Analysis.LipschitzHilbert.Estimates.OperatorConjugation +OAI.Analysis.LipschitzHilbert.Estimates.OrderDistribution +OAI.Analysis.LipschitzHilbert.Estimates.OrdinaryModelConstruction +OAI.Analysis.LipschitzHilbert.Estimates.OrdinaryModelConstructionCost +OAI.Analysis.LipschitzHilbert.Estimates.OrdinaryModelNumerics +OAI.Analysis.LipschitzHilbert.Estimates.OriginalRecovery +OAI.Analysis.LipschitzHilbert.Estimates.ParityPartialSums +OAI.Analysis.LipschitzHilbert.Estimates.PartitionIntegral +OAI.Analysis.LipschitzHilbert.Estimates.PerturbedLepingle +OAI.Analysis.LipschitzHilbert.Estimates.PhysicalBinAdjoint +OAI.Analysis.LipschitzHilbert.Estimates.PlanarChangeVariables +OAI.Analysis.LipschitzHilbert.Estimates.PlanarCoefficientBudget +OAI.Analysis.LipschitzHilbert.Estimates.PlanarCoefficientNorm +OAI.Analysis.LipschitzHilbert.Estimates.PlanarColoredVectorEnergy +OAI.Analysis.LipschitzHilbert.Estimates.PlanarFixedScaleEnergy +OAI.Analysis.LipschitzHilbert.Estimates.PlanarHorizontalRescale +OAI.Analysis.LipschitzHilbert.Estimates.PlanarPairingEnergy +OAI.Analysis.LipschitzHilbert.Estimates.PlanarProfileBounds +OAI.Analysis.LipschitzHilbert.Estimates.PlanarProfilePolarization +OAI.Analysis.LipschitzHilbert.Estimates.PlanarSeparatedEnergy +OAI.Analysis.LipschitzHilbert.Estimates.PlaneCoordinates +OAI.Analysis.LipschitzHilbert.Estimates.PlaneSlopeLipschitz +OAI.Analysis.LipschitzHilbert.Estimates.PolynomialEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.PolynomialLocalization +OAI.Analysis.LipschitzHilbert.Estimates.PolynomialMomentBound +OAI.Analysis.LipschitzHilbert.Estimates.PopularCountDiscard +OAI.Analysis.LipschitzHilbert.Estimates.PopularGroups +OAI.Analysis.LipschitzHilbert.Estimates.PopularTopCount +OAI.Analysis.LipschitzHilbert.Estimates.PopularTopCountPowers +OAI.Analysis.LipschitzHilbert.Estimates.PopularTopMask +OAI.Analysis.LipschitzHilbert.Estimates.PositiveAuxiliaryAverages +OAI.Analysis.LipschitzHilbert.Estimates.PositiveErrorMajorant +OAI.Analysis.LipschitzHilbert.Estimates.PrincipalTimeMoment +OAI.Analysis.LipschitzHilbert.Estimates.PrincipalValueProfileCommutator +OAI.Analysis.LipschitzHilbert.Estimates.ProductPVContinuity +OAI.Analysis.LipschitzHilbert.Estimates.ProductPVPointwiseBound +OAI.Analysis.LipschitzHilbert.Estimates.ProductPerturbation +OAI.Analysis.LipschitzHilbert.Estimates.ProductSlopePVTruncation +OAI.Analysis.LipschitzHilbert.Estimates.ProductSlopePrincipalValue +OAI.Analysis.LipschitzHilbert.Estimates.ProductSlopePrincipalValueBound +OAI.Analysis.LipschitzHilbert.Estimates.PublishedHilbertInput +OAI.Analysis.LipschitzHilbert.Estimates.PublishedInputs +OAI.Analysis.LipschitzHilbert.Estimates.RadialShrink +OAI.Analysis.LipschitzHilbert.Estimates.RankedMaximal +OAI.Analysis.LipschitzHilbert.Estimates.RawBMOMoments +OAI.Analysis.LipschitzHilbert.Estimates.RealFiniteVariation +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceAnalysis +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceCarleson +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceChart +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceException +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceFamilyException +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceSynthesis +OAI.Analysis.LipschitzHilbert.Estimates.ReferenceSynthesisL1 +OAI.Analysis.LipschitzHilbert.Estimates.RelativeExitEnergy +OAI.Analysis.LipschitzHilbert.Estimates.RelativeExitIntervals +OAI.Analysis.LipschitzHilbert.Estimates.RelativeExitScales +OAI.Analysis.LipschitzHilbert.Estimates.RelativeMartingaleExits +OAI.Analysis.LipschitzHilbert.Estimates.RelativePartitionVariation +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedLogDensity +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedLogNumerics +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedStrongForm +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedStrongLp +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedStrongOperator +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedTestApproximation +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedTestOpenApproximation +OAI.Analysis.LipschitzHilbert.Estimates.RestrictedTopWeakTwo +OAI.Analysis.LipschitzHilbert.Estimates.RetainedAmplitudeMatrix +OAI.Analysis.LipschitzHilbert.Estimates.RootTailGluing +OAI.Analysis.LipschitzHilbert.Estimates.ScalarRestrictedStrong +OAI.Analysis.LipschitzHilbert.Estimates.ScaledUnitSelector +OAI.Analysis.LipschitzHilbert.Estimates.ScaledWindowSpectrum +OAI.Analysis.LipschitzHilbert.Estimates.SectionMeasure +OAI.Analysis.LipschitzHilbert.Estimates.SegmentAmplitudes +OAI.Analysis.LipschitzHilbert.Estimates.SegmentCharging +OAI.Analysis.LipschitzHilbert.Estimates.SegmentWeights +OAI.Analysis.LipschitzHilbert.Estimates.SelectedCoefficientDerivative +OAI.Analysis.LipschitzHilbert.Estimates.SelectedScaleDerivative +OAI.Analysis.LipschitzHilbert.Estimates.SelectedTopInterval +OAI.Analysis.LipschitzHilbert.Estimates.SelfEnergy +OAI.Analysis.LipschitzHilbert.Estimates.SeparatedPlanarSynthesis +OAI.Analysis.LipschitzHilbert.Estimates.SeparatedSampling +OAI.Analysis.LipschitzHilbert.Estimates.SeparatedWitnessCount +OAI.Analysis.LipschitzHilbert.Estimates.SequenceExponents +OAI.Analysis.LipschitzHilbert.Estimates.SequenceNorms +OAI.Analysis.LipschitzHilbert.Estimates.SharpHilbertFourth +OAI.Analysis.LipschitzHilbert.Estimates.SharpHilbertL2 +OAI.Analysis.LipschitzHilbert.Estimates.SharpHilbertThird +OAI.Analysis.LipschitzHilbert.Estimates.SharpHilbertThreeHalves +OAI.Analysis.LipschitzHilbert.Estimates.SharpRemainderDecay +OAI.Analysis.LipschitzHilbert.Estimates.SharpTimeMoment +OAI.Analysis.LipschitzHilbert.Estimates.SharpTimeParameters +OAI.Analysis.LipschitzHilbert.Estimates.SharpTimeSplit +OAI.Analysis.LipschitzHilbert.Estimates.ShearedEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.ShearedLatticePeriodization +OAI.Analysis.LipschitzHilbert.Estimates.ShiftedBlocks +OAI.Analysis.LipschitzHilbert.Estimates.ShortBoxEstimate +OAI.Analysis.LipschitzHilbert.Estimates.ShortHorizontalLocalization +OAI.Analysis.LipschitzHilbert.Estimates.ShortL2Operator +OAI.Analysis.LipschitzHilbert.Estimates.ShortPositiveBoxes +OAI.Analysis.LipschitzHilbert.Estimates.ShortPositiveEnergy +OAI.Analysis.LipschitzHilbert.Estimates.ShortPositiveSquare +OAI.Analysis.LipschitzHilbert.Estimates.ShortSlopeCommutation +OAI.Analysis.LipschitzHilbert.Estimates.ShortSlopeL1 +OAI.Analysis.LipschitzHilbert.Estimates.ShortSlopeLp +OAI.Analysis.LipschitzHilbert.Estimates.ShortSlopeLpRealization +OAI.Analysis.LipschitzHilbert.Estimates.ShortSlopeOperator +OAI.Analysis.LipschitzHilbert.Estimates.ShortTimeAverageEnergy +OAI.Analysis.LipschitzHilbert.Estimates.ShortTimeAverageL1 +OAI.Analysis.LipschitzHilbert.Estimates.ShortTimeParameters +OAI.Analysis.LipschitzHilbert.Estimates.ShortTransformExtension +OAI.Analysis.LipschitzHilbert.Estimates.ShortTransformMeasurable +OAI.Analysis.LipschitzHilbert.Estimates.SignedPVCommutator +OAI.Analysis.LipschitzHilbert.Estimates.SimplexBarycenter +OAI.Analysis.LipschitzHilbert.Estimates.SimultaneousCount +OAI.Analysis.LipschitzHilbert.Estimates.SimultaneousCountPowers +OAI.Analysis.LipschitzHilbert.Estimates.SlicedIntegral +OAI.Analysis.LipschitzHilbert.Estimates.SlopeAdmissibility +OAI.Analysis.LipschitzHilbert.Estimates.SlopeBoxHorizontalRescale +OAI.Analysis.LipschitzHilbert.Estimates.SlopeBoxMask +OAI.Analysis.LipschitzHilbert.Estimates.SlopeMaskIntegral +OAI.Analysis.LipschitzHilbert.Estimates.SlopeOrthonormal +OAI.Analysis.LipschitzHilbert.Estimates.SlopePartition +OAI.Analysis.LipschitzHilbert.Estimates.SlopeTopNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.SmoothCarlesonEnergy +OAI.Analysis.LipschitzHilbert.Estimates.SmoothCarlesonEstimate +OAI.Analysis.LipschitzHilbert.Estimates.SmoothCarlesonSynthesis +OAI.Analysis.LipschitzHilbert.Estimates.SmoothPrincipalValue +OAI.Analysis.LipschitzHilbert.Estimates.SmoothPrincipalValueBound +OAI.Analysis.LipschitzHilbert.Estimates.SmoothPrincipalValueExtension +OAI.Analysis.LipschitzHilbert.Estimates.SmoothedCommutatorDecomposition +OAI.Analysis.LipschitzHilbert.Estimates.SmoothedCommutatorEnergy +OAI.Analysis.LipschitzHilbert.Estimates.SnappedLattice +OAI.Analysis.LipschitzHilbert.Estimates.SquareMaximalWeakL1 +OAI.Analysis.LipschitzHilbert.Estimates.SquareMean +OAI.Analysis.LipschitzHilbert.Estimates.SquareTailLayer +OAI.Analysis.LipschitzHilbert.Estimates.StoppedMartingaleChain +OAI.Analysis.LipschitzHilbert.Estimates.StoppedMartingaleEnergy +OAI.Analysis.LipschitzHilbert.Estimates.StoppedScalarExpansion +OAI.Analysis.LipschitzHilbert.Estimates.StoppingScaleIntervals +OAI.Analysis.LipschitzHilbert.Estimates.StripSubdivision +OAI.Analysis.LipschitzHilbert.Estimates.StrongOperatorDerivative +OAI.Analysis.LipschitzHilbert.Estimates.SummationByParts +OAI.Analysis.LipschitzHilbert.Estimates.SupportedInnerIntegral +OAI.Analysis.LipschitzHilbert.Estimates.SynthesisPolarization +OAI.Analysis.LipschitzHilbert.Estimates.TailLimit +OAI.Analysis.LipschitzHilbert.Estimates.TerminalFlow +OAI.Analysis.LipschitzHilbert.Estimates.TestingWeakTwo +OAI.Analysis.LipschitzHilbert.Estimates.ThinTopTail +OAI.Analysis.LipschitzHilbert.Estimates.ThreeInputMain +OAI.Analysis.LipschitzHilbert.Estimates.ThresholdSynthesis +OAI.Analysis.LipschitzHilbert.Estimates.TileLatticeEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.TimeEndpointComparison +OAI.Analysis.LipschitzHilbert.Estimates.TimeErrorEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.TopAmplitudeBound +OAI.Analysis.LipschitzHilbert.Estimates.TopAreaAverage +OAI.Analysis.LipschitzHilbert.Estimates.TopAreaDiscard +OAI.Analysis.LipschitzHilbert.Estimates.TopBoxDecay +OAI.Analysis.LipschitzHilbert.Estimates.TopBoxPolynomial +OAI.Analysis.LipschitzHilbert.Estimates.TopCovariantContinuity +OAI.Analysis.LipschitzHilbert.Estimates.TopCovariantData +OAI.Analysis.LipschitzHilbert.Estimates.TopCovariantHorizontalRescale +OAI.Analysis.LipschitzHilbert.Estimates.TopDilatedTesting +OAI.Analysis.LipschitzHilbert.Estimates.TopDilationTail +OAI.Analysis.LipschitzHilbert.Estimates.TopDyadicDomination +OAI.Analysis.LipschitzHilbert.Estimates.TopEnvelopeDerivative +OAI.Analysis.LipschitzHilbert.Estimates.TopFamilyException +OAI.Analysis.LipschitzHilbert.Estimates.TopIntervalHorizontalRescale +OAI.Analysis.LipschitzHilbert.Estimates.TopLatticeDecay +OAI.Analysis.LipschitzHilbert.Estimates.TopLogAbsorption +OAI.Analysis.LipschitzHilbert.Estimates.TopMaskApproximation +OAI.Analysis.LipschitzHilbert.Estimates.TopMovingLogAbsorption +OAI.Analysis.LipschitzHilbert.Estimates.TopNeighborhood +OAI.Analysis.LipschitzHilbert.Estimates.TopPolynomialDecay +OAI.Analysis.LipschitzHilbert.Estimates.TopRawHorizontalRescale +OAI.Analysis.LipschitzHilbert.Estimates.TopShape +OAI.Analysis.LipschitzHilbert.Estimates.TopThreshold +OAI.Analysis.LipschitzHilbert.Estimates.TopWeakTwo +OAI.Analysis.LipschitzHilbert.Estimates.TopWeight +OAI.Analysis.LipschitzHilbert.Estimates.TopWeightIntegral +OAI.Analysis.LipschitzHilbert.Estimates.TopWeightedInterval +OAI.Analysis.LipschitzHilbert.Estimates.TopWeightedPair +OAI.Analysis.LipschitzHilbert.Estimates.TopWindowMoments +OAI.Analysis.LipschitzHilbert.Estimates.TotalBinError +OAI.Analysis.LipschitzHilbert.Estimates.TotalBinErrorScale +OAI.Analysis.LipschitzHilbert.Estimates.Truncation +OAI.Analysis.LipschitzHilbert.Estimates.TwoPointEnvelope +OAI.Analysis.LipschitzHilbert.Estimates.UniformPlanarRawBounds +OAI.Analysis.LipschitzHilbert.Estimates.UniformPolynomialMoments +OAI.Analysis.LipschitzHilbert.Estimates.UniformTranslatedProfileBounds +OAI.Analysis.LipschitzHilbert.Estimates.VariableEndpointOperator +OAI.Analysis.LipschitzHilbert.Estimates.VariationContinuous +OAI.Analysis.LipschitzHilbert.Estimates.VariationDifference +OAI.Analysis.LipschitzHilbert.Estimates.VariationDisjointExact +OAI.Analysis.LipschitzHilbert.Estimates.VariationIntervals +OAI.Analysis.LipschitzHilbert.Estimates.VariationMeanOscillation +OAI.Analysis.LipschitzHilbert.Estimates.VariationMeasurable +OAI.Analysis.LipschitzHilbert.Estimates.VariationPerturbation +OAI.Analysis.LipschitzHilbert.Estimates.VariationScalar +OAI.Analysis.LipschitzHilbert.Estimates.VariationSubsequence +OAI.Analysis.LipschitzHilbert.Estimates.VariationSum +OAI.Analysis.LipschitzHilbert.Estimates.VeryShortHilbertError +OAI.Analysis.LipschitzHilbert.Estimates.WeakTwoIntegral +OAI.Analysis.LipschitzHilbert.Estimates.WeightedAmplitudeMotion +OAI.Analysis.LipschitzHilbert.Estimates.WeightedAverage +OAI.Analysis.LipschitzHilbert.Estimates.WeightedCauchySchwarz +OAI.Analysis.LipschitzHilbert.Estimates.WeightedDilationLayer +OAI.Analysis.LipschitzHilbert.Estimates.WeightedExceptionalArea +OAI.Analysis.LipschitzHilbert.Estimates.WeightedIntegral +OAI.Analysis.LipschitzHilbert.Estimates.WeightedMomentIndex +OAI.Analysis.LipschitzHilbert.Estimates.WeightedOrder +OAI.Analysis.LipschitzHilbert.Estimates.WeightedReferenceVariation +OAI.Analysis.LipschitzHilbert.Estimates.WeightedTranslatedProfiles +OAI.Analysis.LipschitzHilbert.Estimates.WitnessBinCount +OAI.Analysis.LipschitzHilbert.Estimates.WitnessInterval +OAI.Analysis.LipschitzHilbert.Estimates.WitnessTransfer +OAI.Analysis.LipschitzHilbert.Fourier.ActualBandHigh +OAI.Analysis.LipschitzHilbert.Fourier.ActualCutoffBandHigh +OAI.Analysis.LipschitzHilbert.Fourier.ActualErrorConvolution +OAI.Analysis.LipschitzHilbert.Fourier.ActualScalarBandBounds +OAI.Analysis.LipschitzHilbert.Fourier.AnnularBandL1 +OAI.Analysis.LipschitzHilbert.Fourier.AnnularBinMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.AnnularBinPairing +OAI.Analysis.LipschitzHilbert.Fourier.AnnularBoundedSynthesis +OAI.Analysis.LipschitzHilbert.Fourier.AnnularCutoffConstruction +OAI.Analysis.LipschitzHilbert.Fourier.AnnularEnlargement +OAI.Analysis.LipschitzHilbert.Fourier.AnnularFrequencyEnvelope +OAI.Analysis.LipschitzHilbert.Fourier.AnnularL2Resolution +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPVCommutatorSquare +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPVFromNarrow +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPVPartialBound +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPVReconstruction +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPartitionIdentities +OAI.Analysis.LipschitzHilbert.Fourier.AnnularPositiveCutoff +OAI.Analysis.LipschitzHilbert.Fourier.AnnularResolutionSymbols +OAI.Analysis.LipschitzHilbert.Fourier.AnnularSchwartzResolution +OAI.Analysis.LipschitzHilbert.Fourier.AnnularSelector +OAI.Analysis.LipschitzHilbert.Fourier.AnnularSlopePartition +OAI.Analysis.LipschitzHilbert.Fourier.AnnularSquareBound +OAI.Analysis.LipschitzHilbert.Fourier.AnnularSymbolForm +OAI.Analysis.LipschitzHilbert.Fourier.BandAmplitudeError +OAI.Analysis.LipschitzHilbert.Fourier.BandAmplitudeHigh +OAI.Analysis.LipschitzHilbert.Fourier.BandAmplitudeSum +OAI.Analysis.LipschitzHilbert.Fourier.BandAverageComparison +OAI.Analysis.LipschitzHilbert.Fourier.BandFiniteAmplitudeBound +OAI.Analysis.LipschitzHilbert.Fourier.BandL2Pairing +OAI.Analysis.LipschitzHilbert.Fourier.BandMeasurableHigh +OAI.Analysis.LipschitzHilbert.Fourier.BandOrthogonality +OAI.Analysis.LipschitzHilbert.Fourier.BandProjectedHigh +OAI.Analysis.LipschitzHilbert.Fourier.BandRetainedApproximation +OAI.Analysis.LipschitzHilbert.Fourier.BandRetainedDecay +OAI.Analysis.LipschitzHilbert.Fourier.BandToFullProof +OAI.Analysis.LipschitzHilbert.Fourier.BoundedConvolutionComposition +OAI.Analysis.LipschitzHilbert.Fourier.BoundedConvolutionL2 +OAI.Analysis.LipschitzHilbert.Fourier.BoundedConvolutionL4 +OAI.Analysis.LipschitzHilbert.Fourier.BoundedFrequencyMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.BoundedVerticalMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.CenteredBandProjection +OAI.Analysis.LipschitzHilbert.Fourier.ComplexBandAverage +OAI.Analysis.LipschitzHilbert.Fourier.ComplexLineAverage +OAI.Analysis.LipschitzHilbert.Fourier.ConvolutionBasicL1 +OAI.Analysis.LipschitzHilbert.Fourier.ConvolutionLayerTail +OAI.Analysis.LipschitzHilbert.Fourier.ConvolutionPowerTail +OAI.Analysis.LipschitzHilbert.Fourier.ConvolutionThird +OAI.Analysis.LipschitzHilbert.Fourier.CoordinateFourierSupport +OAI.Analysis.LipschitzHilbert.Fourier.CovariantLineMotion +OAI.Analysis.LipschitzHilbert.Fourier.DemodulatedVertical +OAI.Analysis.LipschitzHilbert.Fourier.DominatedKernelAverage +OAI.Analysis.LipschitzHilbert.Fourier.DyadicAnnularSeparation +OAI.Analysis.LipschitzHilbert.Fourier.DyadicAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.DyadicCommutatorCutoff +OAI.Analysis.LipschitzHilbert.Fourier.DyadicKernelTelescoping +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineBad +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineCarleson +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineCount +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineCountableTail +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineFiniteTail +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineMaximal +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineNesting +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineResolution +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineRootCount +OAI.Analysis.LipschitzHilbert.Fourier.DyadicLineRoots +OAI.Analysis.LipschitzHilbert.Fourier.DyadicProjectionCarleson +OAI.Analysis.LipschitzHilbert.Fourier.DyadicResolutionSymbol +OAI.Analysis.LipschitzHilbert.Fourier.DyadicSmoothCutoff +OAI.Analysis.LipschitzHilbert.Fourier.ErrorLineConcentration +OAI.Analysis.LipschitzHilbert.Fourier.FiniteBandDerivative +OAI.Analysis.LipschitzHilbert.Fourier.FiniteBandMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.FiniteLineAverage +OAI.Analysis.LipschitzHilbert.Fourier.FiniteLineCells +OAI.Analysis.LipschitzHilbert.Fourier.FiniteNormalizedKernelForm +OAI.Analysis.LipschitzHilbert.Fourier.FiniteSeparatedSymbolBound +OAI.Analysis.LipschitzHilbert.Fourier.FiniteSeparatedSymbolBoundL1 +OAI.Analysis.LipschitzHilbert.Fourier.FiniteTimeKernelMoment +OAI.Analysis.LipschitzHilbert.Fourier.FiniteUnitSymbolPairing +OAI.Analysis.LipschitzHilbert.Fourier.FiniteUnitSymbolPairingL1 +OAI.Analysis.LipschitzHilbert.Fourier.FiniteVerticalBins +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingConvolution +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingKernel +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingMeasure +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingMixture +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingScale +OAI.Analysis.LipschitzHilbert.Fourier.FourierAveragingTail +OAI.Analysis.LipschitzHilbert.Fourier.FourierHomogeneity +OAI.Analysis.LipschitzHilbert.Fourier.FourierKernelFirstMoment +OAI.Analysis.LipschitzHilbert.Fourier.FrequencyKernelTranslations +OAI.Analysis.LipschitzHilbert.Fourier.FrequencyProfileNormalization +OAI.Analysis.LipschitzHilbert.Fourier.GeneralAnnularComparison +OAI.Analysis.LipschitzHilbert.Fourier.GeneralAnnularErrors +OAI.Analysis.LipschitzHilbert.Fourier.GeneralAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.GlobalAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.GlobalBandLocalization +OAI.Analysis.LipschitzHilbert.Fourier.GlobalBandOperator +OAI.Analysis.LipschitzHilbert.Fourier.GlobalBandPrincipalValue +OAI.Analysis.LipschitzHilbert.Fourier.HighFrequencyAverage +OAI.Analysis.LipschitzHilbert.Fourier.HilbertAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.HilbertCutoffDerivative +OAI.Analysis.LipschitzHilbert.Fourier.HilbertCutoffNormalization +OAI.Analysis.LipschitzHilbert.Fourier.HilbertCutoffProfile +OAI.Analysis.LipschitzHilbert.Fourier.HilbertFiniteSymbol +OAI.Analysis.LipschitzHilbert.Fourier.HilbertFourierGain +OAI.Analysis.LipschitzHilbert.Fourier.KernelAverageBound +OAI.Analysis.LipschitzHilbert.Fourier.KernelAverageEnergy +OAI.Analysis.LipschitzHilbert.Fourier.KernelAverageL1 +OAI.Analysis.LipschitzHilbert.Fourier.KernelDifferencePairing +OAI.Analysis.LipschitzHilbert.Fourier.KernelPairing +OAI.Analysis.LipschitzHilbert.Fourier.L1FactoredConvolution +OAI.Analysis.LipschitzHilbert.Fourier.L1FourierConvolution +OAI.Analysis.LipschitzHilbert.Fourier.L1FrequencyMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.L1MultiplierLinearity +OAI.Analysis.LipschitzHilbert.Fourier.LatticeCoefficientConvolution +OAI.Analysis.LipschitzHilbert.Fourier.LineAnnularSum +OAI.Analysis.LipschitzHilbert.Fourier.LineBandedCommutatorEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineBoundedCommutatorL2 +OAI.Analysis.LipschitzHilbert.Fourier.LineCommutatorCoefficientLimit +OAI.Analysis.LipschitzHilbert.Fourier.LineCommutatorDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineCommutatorEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineCommutatorLinearity +OAI.Analysis.LipschitzHilbert.Fourier.LineCompositionLimit +OAI.Analysis.LipschitzHilbert.Fourier.LineConjugationBound +OAI.Analysis.LipschitzHilbert.Fourier.LineConjugationDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionContinuity +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionFourth +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionL4 +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionLocal +OAI.Analysis.LipschitzHilbert.Fourier.LineConvolutionPairing +OAI.Analysis.LipschitzHilbert.Fourier.LineCountSlab +OAI.Analysis.LipschitzHilbert.Fourier.LineCounting +OAI.Analysis.LipschitzHilbert.Fourier.LineDerivativeCommutatorL2 +OAI.Analysis.LipschitzHilbert.Fourier.LineDyadicReconstructionEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineDyadicSpectrum +OAI.Analysis.LipschitzHilbert.Fourier.LineDyadicTelescoping +OAI.Analysis.LipschitzHilbert.Fourier.LineFrequencyProjection +OAI.Analysis.LipschitzHilbert.Fourier.LineGeometricSchur +OAI.Analysis.LipschitzHilbert.Fourier.LineHighLowEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineHighLowSpectrum +OAI.Analysis.LipschitzHilbert.Fourier.LineHighLowSum +OAI.Analysis.LipschitzHilbert.Fourier.LineKernelCancellation +OAI.Analysis.LipschitzHilbert.Fourier.LineKernelDecay +OAI.Analysis.LipschitzHilbert.Fourier.LineKernelMaximal +OAI.Analysis.LipschitzHilbert.Fourier.LineKernelOscillation +OAI.Analysis.LipschitzHilbert.Fourier.LineKernelScaling +OAI.Analysis.LipschitzHilbert.Fourier.LineLatticeEnvelope +OAI.Analysis.LipschitzHilbert.Fourier.LineLocalizedMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.LineLowHighCommutator +OAI.Analysis.LipschitzHilbert.Fourier.LineLowHighSpectrum +OAI.Analysis.LipschitzHilbert.Fourier.LineLowHighSum +OAI.Analysis.LipschitzHilbert.Fourier.LineLowpassCell +OAI.Analysis.LipschitzHilbert.Fourier.LineLpDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineMollification +OAI.Analysis.LipschitzHilbert.Fourier.LineNeighborhoodMoments +OAI.Analysis.LipschitzHilbert.Fourier.LineProductSpectrum +OAI.Analysis.LipschitzHilbert.Fourier.LineProjectionDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineProjectionFourth +OAI.Analysis.LipschitzHilbert.Fourier.LineProjectionKernel +OAI.Analysis.LipschitzHilbert.Fourier.LineProjectionLipschitz +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingDecay +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingEnergy +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingGenerator +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingHomeomorph +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingInverse +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingInverseDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingKernelCommutator +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingSchwartz +OAI.Analysis.LipschitzHilbert.Fourier.LineSamplingStrongDerivative +OAI.Analysis.LipschitzHilbert.Fourier.LineSchwartzCommutatorEstimate +OAI.Analysis.LipschitzHilbert.Fourier.LineSchwartzPairing +OAI.Analysis.LipschitzHilbert.Fourier.LineSmoothCarleson +OAI.Analysis.LipschitzHilbert.Fourier.LineTiling +OAI.Analysis.LipschitzHilbert.Fourier.LineWeightAverage +OAI.Analysis.LipschitzHilbert.Fourier.LocalAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.LocalizedAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.LocalizedBandOperator +OAI.Analysis.LipschitzHilbert.Fourier.LocalizedBandStrong +OAI.Analysis.LipschitzHilbert.Fourier.LocalizedSymbolIdentity +OAI.Analysis.LipschitzHilbert.Fourier.LocalizedSymbolOperator +OAI.Analysis.LipschitzHilbert.Fourier.LongLineVariation +OAI.Analysis.LipschitzHilbert.Fourier.LongPositiveConvolution +OAI.Analysis.LipschitzHilbert.Fourier.MeasureClassKernel +OAI.Analysis.LipschitzHilbert.Fourier.ModulatedInverse +OAI.Analysis.LipschitzHilbert.Fourier.ModulatedInverseL1 +OAI.Analysis.LipschitzHilbert.Fourier.NarrowBandCutoff +OAI.Analysis.LipschitzHilbert.Fourier.NegativeBandOperator +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedBandProjection +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedBandSymbol +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedBasicConvolution +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedConvolutionForm +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedHighConvolution +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedReverseConvolution +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolBasicL1 +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolFamily +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolForm +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolFormL1 +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolHighL1 +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolRepresentation +OAI.Analysis.LipschitzHilbert.Fourier.NormalizedSymbolReverseL1 +OAI.Analysis.LipschitzHilbert.Fourier.PVCommutatorSymbolLinearity +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedAnnularBasicL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedAnnularForm +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedAnnularFormL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedAnnularHighL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedAnnularReverseL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedBandForm +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedBandFormL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedFrequencyL1 +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedFrequencySymbol +OAI.Analysis.LipschitzHilbert.Fourier.PartitionedSymbolIdentity +OAI.Analysis.LipschitzHilbert.Fourier.PhysicalPlanarJet +OAI.Analysis.LipschitzHilbert.Fourier.PlanarCovariantJet +OAI.Analysis.LipschitzHilbert.Fourier.PlanarModulatedJet +OAI.Analysis.LipschitzHilbert.Fourier.PlanarPositiveConvolution +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSchwartzDecay +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSchwartzInversion +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSchwartzSlice +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSliceFourier +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSliceFourierBasic +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSliceFourierDerivative +OAI.Analysis.LipschitzHilbert.Fourier.PlanarSliceFourierSupport +OAI.Analysis.LipschitzHilbert.Fourier.PlaneLineWeakL1 +OAI.Analysis.LipschitzHilbert.Fourier.PlaneVerticalLipschitz +OAI.Analysis.LipschitzHilbert.Fourier.PolynomialLineFamily +OAI.Analysis.LipschitzHilbert.Fourier.PositiveConvolution +OAI.Analysis.LipschitzHilbert.Fourier.PositiveConvolutionOscillation +OAI.Analysis.LipschitzHilbert.Fourier.PositiveLineKernel +OAI.Analysis.LipschitzHilbert.Fourier.PositiveLineMaximal +OAI.Analysis.LipschitzHilbert.Fourier.ProductPVLinear +OAI.Analysis.LipschitzHilbert.Fourier.ProductPVVerticalDecay +OAI.Analysis.LipschitzHilbert.Fourier.Projection +OAI.Analysis.LipschitzHilbert.Fourier.ProjectionFiberGeometry +OAI.Analysis.LipschitzHilbert.Fourier.PublishedBandReductionInput +OAI.Analysis.LipschitzHilbert.Fourier.RectangularFrequencyCutoff +OAI.Analysis.LipschitzHilbert.Fourier.ReferenceLineCount +OAI.Analysis.LipschitzHilbert.Fourier.ReflectedBandProjection +OAI.Analysis.LipschitzHilbert.Fourier.RescaledAnnularSymbol +OAI.Analysis.LipschitzHilbert.Fourier.RescaledPartitionedSymbol +OAI.Analysis.LipschitzHilbert.Fourier.RestrictedSchwartzSizes +OAI.Analysis.LipschitzHilbert.Fourier.ScalarBandKernel +OAI.Analysis.LipschitzHilbert.Fourier.ScalarLineVariation +OAI.Analysis.LipschitzHilbert.Fourier.ScaledAnnularVariation +OAI.Analysis.LipschitzHilbert.Fourier.ScaledConvolutionLimits +OAI.Analysis.LipschitzHilbert.Fourier.ScaledFrequencyWindows +OAI.Analysis.LipschitzHilbert.Fourier.ScaledWindowFourier +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzBandEnergy +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzBandPrimitive +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzConjugation +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzDilation +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzGlobalLipschitz +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzProfileBounds +OAI.Analysis.LipschitzHilbert.Fourier.SchwartzVerticalProjection +OAI.Analysis.LipschitzHilbert.Fourier.SeparatedSymbolFourier +OAI.Analysis.LipschitzHilbert.Fourier.SeparatedSymbolOperator +OAI.Analysis.LipschitzHilbert.Fourier.SeparatedSymbolPairing +OAI.Analysis.LipschitzHilbert.Fourier.SeparatedSymbolPairingL1 +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandHigh +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandHighAll +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandMeasurableRestricted +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandRestrictedLog +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandScalarEndpoints +OAI.Analysis.LipschitzHilbert.Fourier.SharpBandUniformHigh +OAI.Analysis.LipschitzHilbert.Fourier.SharpKernelComparison +OAI.Analysis.LipschitzHilbert.Fourier.SharpKernelL1 +OAI.Analysis.LipschitzHilbert.Fourier.SharpKernelSymmetrization +OAI.Analysis.LipschitzHilbert.Fourier.SharpVerticalCommutator +OAI.Analysis.LipschitzHilbert.Fourier.ShiftedLineAverage +OAI.Analysis.LipschitzHilbert.Fourier.ShortKernelPairing +OAI.Analysis.LipschitzHilbert.Fourier.ShortLineVariation +OAI.Analysis.LipschitzHilbert.Fourier.ShortPositiveConvolution +OAI.Analysis.LipschitzHilbert.Fourier.ShortSlopeLinearity +OAI.Analysis.LipschitzHilbert.Fourier.ShortVerticalDifference +OAI.Analysis.LipschitzHilbert.Fourier.ShortVerticalDifferenceL1 +OAI.Analysis.LipschitzHilbert.Fourier.ShortVerticalError +OAI.Analysis.LipschitzHilbert.Fourier.SignedAnnularOperator +OAI.Analysis.LipschitzHilbert.Fourier.SignedAnnularSymbol +OAI.Analysis.LipschitzHilbert.Fourier.SimpleFourierPairing +OAI.Analysis.LipschitzHilbert.Fourier.SincMask +OAI.Analysis.LipschitzHilbert.Fourier.SincMaskFourier +OAI.Analysis.LipschitzHilbert.Fourier.SincMaskMotion +OAI.Analysis.LipschitzHilbert.Fourier.SincMaskSchwartz +OAI.Analysis.LipschitzHilbert.Fourier.SincMaskSpectrum +OAI.Analysis.LipschitzHilbert.Fourier.SincMaskedLine +OAI.Analysis.LipschitzHilbert.Fourier.SkippedLineAverage +OAI.Analysis.LipschitzHilbert.Fourier.SmoothPrincipalValueLinear +OAI.Analysis.LipschitzHilbert.Fourier.SmoothSlopeSymbol +OAI.Analysis.LipschitzHilbert.Fourier.SquareLineConcentration +OAI.Analysis.LipschitzHilbert.Fourier.StripProjection +OAI.Analysis.LipschitzHilbert.Fourier.SymbolAverageBound +OAI.Analysis.LipschitzHilbert.Fourier.SymbolSlice +OAI.Analysis.LipschitzHilbert.Fourier.SymbolWeights +OAI.Analysis.LipschitzHilbert.Fourier.TileEnvelopeKernel +OAI.Analysis.LipschitzHilbert.Fourier.UniformLineMoments +OAI.Analysis.LipschitzHilbert.Fourier.UnitConvolutionParameter +OAI.Analysis.LipschitzHilbert.Fourier.UnitConvolutionWeight +OAI.Analysis.LipschitzHilbert.Fourier.UnitConvolutionWeightL1 +OAI.Analysis.LipschitzHilbert.Fourier.UnitSymbolPairing +OAI.Analysis.LipschitzHilbert.Fourier.UnitSymbolPairingL1 +OAI.Analysis.LipschitzHilbert.Fourier.VariableEndpointKernel +OAI.Analysis.LipschitzHilbert.Fourier.VariationLineBMO +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBernstein +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinAdjoint +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinCommutator +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinCost +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinEnergy +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinKernel +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinLpEnergy +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinLpReconstruction +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinPlateau +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinProfile +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinReconstruction +OAI.Analysis.LipschitzHilbert.Fourier.VerticalBinVector +OAI.Analysis.LipschitzHilbert.Fourier.VerticalCommutatorAverage +OAI.Analysis.LipschitzHilbert.Fourier.VerticalCommutatorEnergy +OAI.Analysis.LipschitzHilbert.Fourier.VerticalConvolutionL1 +OAI.Analysis.LipschitzHilbert.Fourier.VerticalConvolutionL2 +OAI.Analysis.LipschitzHilbert.Fourier.VerticalConvolutionLp +OAI.Analysis.LipschitzHilbert.Fourier.VerticalConvolutionPVLimit +OAI.Analysis.LipschitzHilbert.Fourier.VerticalDifferenceEnergy +OAI.Analysis.LipschitzHilbert.Fourier.VerticalErrorSources +OAI.Analysis.LipschitzHilbert.Fourier.VerticalHorizontalCutoff +OAI.Analysis.LipschitzHilbert.Fourier.VerticalInverseMultiplier +OAI.Analysis.LipschitzHilbert.Fourier.VerticalKernelMoment +OAI.Analysis.LipschitzHilbert.Fourier.VerticalL2Projection +OAI.Analysis.LipschitzHilbert.Fourier.VerticalMoment +OAI.Analysis.LipschitzHilbert.Fourier.VerticalNeighborhood +OAI.Analysis.LipschitzHilbert.Fourier.VerticalProjectionAlgebra +OAI.Analysis.LipschitzHilbert.Fourier.VerticalProjectionDerivative +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSamplingCommutator +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSamplingDifference +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSamplingGeometry +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSamplingMihlin +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSecantEnergy +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSelfAdjoint +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSlopeCommutation +OAI.Analysis.LipschitzHilbert.Fourier.VerticalSymbolBound +OAI.Analysis.LipschitzHilbert.Fourier.VerticalWeight +OAI.Analysis.LipschitzHilbert.Fourier.VerticalWindowRescaling +OAI.Analysis.LipschitzHilbert.Fourier.VerticalWindowRescalingL1 +OAI.Analysis.LipschitzHilbert.Fourier.WitnessLineAverage +OAI.Analysis.LipschitzHilbert.Fourier.WitnessProjection +OAI.Analysis.LipschitzHilbert.Geometry.BinaryFarMass +OAI.Analysis.LipschitzHilbert.Geometry.ClippedEnclosure +OAI.Analysis.LipschitzHilbert.Geometry.CompactDirectionCutoff +OAI.Analysis.LipschitzHilbert.Geometry.ConditionalUnitDirection +OAI.Analysis.LipschitzHilbert.Geometry.DilatedRectangleInterior +OAI.Analysis.LipschitzHilbert.Geometry.DirectionChartSampling +OAI.Analysis.LipschitzHilbert.Geometry.DirectionDilation +OAI.Analysis.LipschitzHilbert.Geometry.DyadicLineCover +OAI.Analysis.LipschitzHilbert.Geometry.DyadicNearbyInputs +OAI.Analysis.LipschitzHilbert.Geometry.DyadicProjectionPacking +OAI.Analysis.LipschitzHilbert.Geometry.FarGroupEnergy +OAI.Analysis.LipschitzHilbert.Geometry.FarLineLower +OAI.Analysis.LipschitzHilbert.Geometry.FarPairEnergy +OAI.Analysis.LipschitzHilbert.Geometry.FarSelectionGeometry +OAI.Analysis.LipschitzHilbert.Geometry.FarSlabExclusion +OAI.Analysis.LipschitzHilbert.Geometry.FarSlabGeometry +OAI.Analysis.LipschitzHilbert.Geometry.FarSlabLineSum +OAI.Analysis.LipschitzHilbert.Geometry.FarStripGeometry +OAI.Analysis.LipschitzHilbert.Geometry.FatEnclosure +OAI.Analysis.LipschitzHilbert.Geometry.FatRectangleSum +OAI.Analysis.LipschitzHilbert.Geometry.FiniteCarlesonPacking +OAI.Analysis.LipschitzHilbert.Geometry.FiniteOutputCover +OAI.Analysis.LipschitzHilbert.Geometry.FiniteSpectralOverlap +OAI.Analysis.LipschitzHilbert.Geometry.FiniteTransverseDirections +OAI.Analysis.LipschitzHilbert.Geometry.FrozenDirection +OAI.Analysis.LipschitzHilbert.Geometry.GeometricSpectralOverlap +OAI.Analysis.LipschitzHilbert.Geometry.HorizontalStripCover +OAI.Analysis.LipschitzHilbert.Geometry.LaceyLiCoveringReduction +OAI.Analysis.LipschitzHilbert.Geometry.LaceyLiGeometry +OAI.Analysis.LipschitzHilbert.Geometry.LaceyLiPacking +OAI.Analysis.LipschitzHilbert.Geometry.LaceyLiProof +OAI.Analysis.LipschitzHilbert.Geometry.LaceyLiSelectionCover +OAI.Analysis.LipschitzHilbert.Geometry.LineConvolutionFar +OAI.Analysis.LipschitzHilbert.Geometry.LocalFarExclusion +OAI.Analysis.LipschitzHilbert.Geometry.LocalMinimaSelection +OAI.Analysis.LipschitzHilbert.Geometry.NearPairEnergy +OAI.Analysis.LipschitzHilbert.Geometry.NearRectangleLine +OAI.Analysis.LipschitzHilbert.Geometry.NearRectangleSection +OAI.Analysis.LipschitzHilbert.Geometry.NearRectangleSum +OAI.Analysis.LipschitzHilbert.Geometry.NearSelectionBound +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataDirectionLabelCount +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataDirectionLatticeCount +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataFarGram +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataReferenceSelection +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSelectionRecords +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSignedInteractionPacking +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSignedPacketPacking +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSignedSelectedFarBound +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSizeSelectionEnergy +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataSizeSelectionOrder +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataTreeFarEnergy +OAI.Analysis.LipschitzHilbert.Geometry.PacketDataTwoSidedSelection +OAI.Analysis.LipschitzHilbert.Geometry.PopularGroupDirections +OAI.Analysis.LipschitzHilbert.Geometry.PositiveRectangleAuxiliary +OAI.Analysis.LipschitzHilbert.Geometry.ProjectedPopularityPacking +OAI.Analysis.LipschitzHilbert.Geometry.ProjectionGroupSelection +OAI.Analysis.LipschitzHilbert.Geometry.RectangleArea +OAI.Analysis.LipschitzHilbert.Geometry.RectangleAuxiliary +OAI.Analysis.LipschitzHilbert.Geometry.RectangleCountingEnergy +OAI.Analysis.LipschitzHilbert.Geometry.RectangleCoverSelection +OAI.Analysis.LipschitzHilbert.Geometry.RectangleDilation +OAI.Analysis.LipschitzHilbert.Geometry.RectangleIndicator +OAI.Analysis.LipschitzHilbert.Geometry.RectangleLastSelected +OAI.Analysis.LipschitzHilbert.Geometry.RectangleLineCoordinates +OAI.Analysis.LipschitzHilbert.Geometry.RectanglePairEnergy +OAI.Analysis.LipschitzHilbert.Geometry.RectangleProjection +OAI.Analysis.LipschitzHilbert.Geometry.SelectedCountingEnergy +OAI.Analysis.LipschitzHilbert.Geometry.SelectedFarFamily +OAI.Analysis.LipschitzHilbert.Geometry.SelectedFarOverlap +OAI.Analysis.LipschitzHilbert.Geometry.SeparatedPacking +OAI.Analysis.LipschitzHilbert.Geometry.SlopeDirection +OAI.Analysis.LipschitzHilbert.Geometry.SlopeRectangle +OAI.Analysis.LipschitzHilbert.Geometry.SmoothDirectionApproximation +OAI.Analysis.LipschitzHilbert.Geometry.SourceDirectionLabelCount +OAI.Analysis.LipschitzHilbert.Geometry.SourceDirectionLatticeCount +OAI.Analysis.LipschitzHilbert.Geometry.SourceFarGramReduction +OAI.Analysis.LipschitzHilbert.Geometry.SourceFarLinear +OAI.Analysis.LipschitzHilbert.Geometry.SourcePackingIntegral +OAI.Analysis.LipschitzHilbert.Geometry.SourceScalePacking +OAI.Analysis.LipschitzHilbert.Geometry.SourceSelectedFarBound +OAI.Analysis.LipschitzHilbert.Geometry.SourceSelectedInteractionPacking +OAI.Analysis.LipschitzHilbert.Geometry.SourceSelectedPacketPacking +OAI.Analysis.LipschitzHilbert.Geometry.SourceSelectionBoxGeometry +OAI.Analysis.LipschitzHilbert.Geometry.SourceSelectionRecords +OAI.Analysis.LipschitzHilbert.Geometry.SourceShortTreeOverlap +OAI.Analysis.LipschitzHilbert.Geometry.SourceSignedInteractionPacking +OAI.Analysis.LipschitzHilbert.Geometry.SourceSignedPacketPacking +OAI.Analysis.LipschitzHilbert.Geometry.SourceSignedSelectedFarBound +OAI.Analysis.LipschitzHilbert.Geometry.SourceSizeSelectionEnergy +OAI.Analysis.LipschitzHilbert.Geometry.SourceSizeSelectionOrder +OAI.Analysis.LipschitzHilbert.Geometry.SourceThreeGridCover +OAI.Analysis.LipschitzHilbert.Geometry.SourceTransversePacketEnergy +OAI.Analysis.LipschitzHilbert.Geometry.SourceTransverseTail +OAI.Analysis.LipschitzHilbert.Geometry.SourceTransverseTreeMaximal +OAI.Analysis.LipschitzHilbert.Geometry.SourceTransverseTreeVariation +OAI.Analysis.LipschitzHilbert.Geometry.SourceTreeFarEnergy +OAI.Analysis.LipschitzHilbert.Geometry.SourceTwoSidedSizeSelection +OAI.Analysis.LipschitzHilbert.Geometry.SourceWhitneyPacking +OAI.Analysis.LipschitzHilbert.Geometry.TopDilationPacking +OAI.Analysis.LipschitzHilbert.Geometry.TransverseBoxDecay +OAI.Analysis.LipschitzHilbert.Geometry.UniformNearSelection +OAI.Analysis.LipschitzHilbert.Geometry.UnitDirectionCharts +OAI.Analysis.LipschitzHilbert.Geometry.VerticalRectangle +OAI.Analysis.LipschitzHilbert.Main +OAI.Analysis.LipschitzHilbert.OneInputMain +OAI.Analysis.LipschitzHilbert.Packets.AnalyzedGlobalNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.AnalyzedLineFamily +OAI.Analysis.LipschitzHilbert.Packets.AnalyzedLineMoments +OAI.Analysis.LipschitzHilbert.Packets.AnalyzedNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.AnalyzedReplacement +OAI.Analysis.LipschitzHilbert.Packets.AnalyzingBilinear +OAI.Analysis.LipschitzHilbert.Packets.AnalyzingCoefficientNorm +OAI.Analysis.LipschitzHilbert.Packets.AnalyzingCoefficients +OAI.Analysis.LipschitzHilbert.Packets.AnalyzingProfileNormalization +OAI.Analysis.LipschitzHilbert.Packets.AnnularEnlargedFrame +OAI.Analysis.LipschitzHilbert.Packets.AnnularLowerFrame +OAI.Analysis.LipschitzHilbert.Packets.AnnularPacketGeometry +OAI.Analysis.LipschitzHilbert.Packets.BoxPacketVariation +OAI.Analysis.LipschitzHilbert.Packets.ConvolutionPacketProfile +OAI.Analysis.LipschitzHilbert.Packets.ConvolutionPacketSchwartz +OAI.Analysis.LipschitzHilbert.Packets.ConvolutionPacketSpectrum +OAI.Analysis.LipschitzHilbert.Packets.FactoredMultiplierPackets +OAI.Analysis.LipschitzHilbert.Packets.FiniteNormalizedPacketLattice +OAI.Analysis.LipschitzHilbert.Packets.FinitePacketSites +OAI.Analysis.LipschitzHilbert.Packets.HilbertPacketLinearity +OAI.Analysis.LipschitzHilbert.Packets.HilbertPacketSums +OAI.Analysis.LipschitzHilbert.Packets.JointPacketAverage +OAI.Analysis.LipschitzHilbert.Packets.JointVectorPacketAverage +OAI.Analysis.LipschitzHilbert.Packets.LineConvolutionFrame +OAI.Analysis.LipschitzHilbert.Packets.LinePacketFamily +OAI.Analysis.LipschitzHilbert.Packets.LinePacketReplacement +OAI.Analysis.LipschitzHilbert.Packets.NormalizedPacketKernelForm +OAI.Analysis.LipschitzHilbert.Packets.NormalizedPacketLattice +OAI.Analysis.LipschitzHilbert.Packets.NormalizedPacketProfiles +OAI.Analysis.LipschitzHilbert.Packets.NormalizedPacketSpectrum +OAI.Analysis.LipschitzHilbert.Packets.PacketBinAnnulus +OAI.Analysis.LipschitzHilbert.Packets.PacketBoxes +OAI.Analysis.LipschitzHilbert.Packets.PacketConvolution +OAI.Analysis.LipschitzHilbert.Packets.PacketDataActualPacketRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataActualReferenceArea +OAI.Analysis.LipschitzHilbert.Packets.PacketDataActualReferenceCentral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataActualReferenceEvents +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAdjoint +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAdjointEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAdjointPairingBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAdjointPolarization +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedBoundaryError +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedBoundaryGain +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedBoundaryPrefix +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedLabelCount +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedLabelCountAt +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedLinearEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedMarkedPath +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedMaskRemoval +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedMaskSums +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedModelInterval +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedParentCentralGain +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedParentCentralInputs +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedParentMarkedBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedParentPhysicalPlane +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedParentVertexIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedPathIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedPhysical +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedPlaneIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedReference +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSelectorCentralGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSelectorControlledGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSelectorGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSelectorJointGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedStoppedBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSupportedGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedSupportedPath +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopAlternate +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopBands +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopFamily +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopReference +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTopSelector +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedTubeEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PacketDataAssignedVertexPath +OAI.Analysis.LipschitzHilbert.Packets.PacketDataBasicPairing +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCappedRemovalStep +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCoefficient +OAI.Analysis.LipschitzHilbert.Packets.PacketDataConeSingleScale +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCrossForm +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCrossPairingBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCrossProductForm +OAI.Analysis.LipschitzHilbert.Packets.PacketDataCrossValue +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDeletionForest +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDeletionTreeEstimate +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensity +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityCentralGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityForest +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityForestIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityGoodRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityJetNormalization +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityPopularRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensityRemovalIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDensitySelectorGoodSet +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDropDensity +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDropPackets +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDropSize +OAI.Analysis.LipschitzHilbert.Packets.PacketDataDropTreeTransport +OAI.Analysis.LipschitzHilbert.Packets.PacketDataEnclosingScale +OAI.Analysis.LipschitzHilbert.Packets.PacketDataFiniteSizeBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataHighDensityEnergyRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataHighDensityPopularRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataInteractionGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataIntrinsicCrossEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataIntrinsicDensityPairing +OAI.Analysis.LipschitzHilbert.Packets.PacketDataIntrinsicReverse +OAI.Analysis.LipschitzHilbert.Packets.PacketDataJetBudget +OAI.Analysis.LipschitzHilbert.Packets.PacketDataJetControl +OAI.Analysis.LipschitzHilbert.Packets.PacketDataKernelForm +OAI.Analysis.LipschitzHilbert.Packets.PacketDataLabelScaleEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataLatticeSites +OAI.Analysis.LipschitzHilbert.Packets.PacketDataMaskedBand +OAI.Analysis.LipschitzHilbert.Packets.PacketDataMaskedValue +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelBilinearRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelConfig +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelCostPolynomial +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelDegenerateCases +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelEstimate +OAI.Analysis.LipschitzHilbert.Packets.PacketDataModelRestriction +OAI.Analysis.LipschitzHilbert.Packets.PacketDataNormalizedRemovalStep +OAI.Analysis.LipschitzHilbert.Packets.PacketDataOrdinaryDensityForest +OAI.Analysis.LipschitzHilbert.Packets.PacketDataOrdinaryRemovalStep +OAI.Analysis.LipschitzHilbert.Packets.PacketDataOriginalIntegrability +OAI.Analysis.LipschitzHilbert.Packets.PacketDataOriginalParentMarkedPath +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPackedPairing +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPacketGram +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPacketRecovery +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPacketScaleCount +OAI.Analysis.LipschitzHilbert.Packets.PacketDataParentFullResidual +OAI.Analysis.LipschitzHilbert.Packets.PacketDataParentReference +OAI.Analysis.LipschitzHilbert.Packets.PacketDataParentResidualReference +OAI.Analysis.LipschitzHilbert.Packets.PacketDataParentResidualSquare +OAI.Analysis.LipschitzHilbert.Packets.PacketDataParentStoppedBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPartial +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPathRegularity +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPhysicalPropagatedTail +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPhysicalResidualNorm +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPhysicalUnaryEndpoint +OAI.Analysis.LipschitzHilbert.Packets.PacketDataPolarization +OAI.Analysis.LipschitzHilbert.Packets.PacketDataRecenteredBoundedSize +OAI.Analysis.LipschitzHilbert.Packets.PacketDataRecenteredReferenceConditions +OAI.Analysis.LipschitzHilbert.Packets.PacketDataRecenteredSelector +OAI.Analysis.LipschitzHilbert.Packets.PacketDataRecordedEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceBand +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceConditions +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceCross +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceMasked +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceProperties +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReferenceSelectedVariation +OAI.Analysis.LipschitzHilbert.Packets.PacketDataReverseCost +OAI.Analysis.LipschitzHilbert.Packets.PacketDataRootedTree +OAI.Analysis.LipschitzHilbert.Packets.PacketDataScaleGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataScaleRestriction +OAI.Analysis.LipschitzHilbert.Packets.PacketDataScaleRestrictionSums +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedArea +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedBoxSeparation +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedCoefficientBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedConstants +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedDuality +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedGram +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedPackets +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedPartial +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedPrefix +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedQuadratic +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedRecordSums +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedReference +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedScale +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedSum +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSelectedTree +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSignedBoxSeparation +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSignedSelectedArea +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSignedSelectedSynthesis +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSignedSizeTest +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSignedTopGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSizeOnePacket +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSizeRemovalIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSizeStopping +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSizeTest +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSpatialTree +OAI.Analysis.LipschitzHilbert.Packets.PacketDataStoppingPrefix +OAI.Analysis.LipschitzHilbert.Packets.PacketDataSupportedAssignedConcentration +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTopEstimate +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTopReferenceGeometry +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTreeSize +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTrimInteractions +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTwoSidedRemovedIntegral +OAI.Analysis.LipschitzHilbert.Packets.PacketDataTwoSidedSizeArea +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformBoundedSize +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformCappedStep +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformCrossEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformCrossReverse +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformReverseDisparity +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniformReverseModel +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniversalAdjointEnergy +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniversalBound +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniversalEstimate +OAI.Analysis.LipschitzHilbert.Packets.PacketDataUniversalNormalizedStep +OAI.Analysis.LipschitzHilbert.Packets.PacketDataVectorEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PacketDataWeightedMaximal +OAI.Analysis.LipschitzHilbert.Packets.PacketDataZeroDensity +OAI.Analysis.LipschitzHilbert.Packets.PacketFrequencyInputL1 +OAI.Analysis.LipschitzHilbert.Packets.PacketIntervalNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.PacketLatticeAverage +OAI.Analysis.LipschitzHilbert.Packets.PacketLatticeData +OAI.Analysis.LipschitzHilbert.Packets.PacketLatticeRestriction +OAI.Analysis.LipschitzHilbert.Packets.PacketLineConcentration +OAI.Analysis.LipschitzHilbert.Packets.PacketPolarization +OAI.Analysis.LipschitzHilbert.Packets.PacketReferenceSpectrum +OAI.Analysis.LipschitzHilbert.Packets.PacketVectorDerivative +OAI.Analysis.LipschitzHilbert.Packets.ParityPackets +OAI.Analysis.LipschitzHilbert.Packets.PhysicalPacketSpectrum +OAI.Analysis.LipschitzHilbert.Packets.PhysicalPlanarPacket +OAI.Analysis.LipschitzHilbert.Packets.PhysicalTopDerivative +OAI.Analysis.LipschitzHilbert.Packets.PlanarFrequencyPackets +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketContinuity +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketDerivative +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketDifferentiation +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketEnvelope +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketFamily +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketLocality +OAI.Analysis.LipschitzHilbert.Packets.PlanarPacketScaling +OAI.Analysis.LipschitzHilbert.Packets.PolynomialPacket +OAI.Analysis.LipschitzHilbert.Packets.PositivePacketDerivative +OAI.Analysis.LipschitzHilbert.Packets.PositivePacketSquare +OAI.Analysis.LipschitzHilbert.Packets.ReferencePacketFamily +OAI.Analysis.LipschitzHilbert.Packets.ScaledPlanarPacket +OAI.Analysis.LipschitzHilbert.Packets.SchwartzPacketDecay +OAI.Analysis.LipschitzHilbert.Packets.SeparatedPacketForm +OAI.Analysis.LipschitzHilbert.Packets.ShortPacketBoxes +OAI.Analysis.LipschitzHilbert.Packets.SourceAssignedPacketSum +OAI.Analysis.LipschitzHilbert.Packets.SourceBoundaryPacketError +OAI.Analysis.LipschitzHilbert.Packets.SourceBoundaryPacketRegroup +OAI.Analysis.LipschitzHilbert.Packets.SourceDensityPacketGeometry +OAI.Analysis.LipschitzHilbert.Packets.SourceDropPackets +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenCellIntegral +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenCenteredCoefficient +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenCoefficientEnergy +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenDensitySum +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenLongInterval +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenProfile +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenSpectrum +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenTreeEstimate +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenTreeGlobal +OAI.Analysis.LipschitzHilbert.Packets.SourceFrozenWhitneyLocal +OAI.Analysis.LipschitzHilbert.Packets.SourceLabeledPacketRestriction +OAI.Analysis.LipschitzHilbert.Packets.SourceLatticePacket +OAI.Analysis.LipschitzHilbert.Packets.SourcePackedPacketPairing +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketDensity +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketGram +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketLongCell +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketMotionBudget +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketOwnDensity +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketPathProduct +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketRegroup +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketScaleCount +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketShear +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketShortSum +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketSpectrum +OAI.Analysis.LipschitzHilbert.Packets.SourcePacketStoppedBound +OAI.Analysis.LipschitzHilbert.Packets.SourcePhysicalPacketAssembly +OAI.Analysis.LipschitzHilbert.Packets.SourceReferencePacketEnvelope +OAI.Analysis.LipschitzHilbert.Packets.SourceRestrictedPacketAmplitude +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectedPackets +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorCoefficientNorm +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentration +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationActive +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationCentered +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationCenteredFamily +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorBudget +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorFamily +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorMoments +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorPhysical +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorRaw +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationErrorSynthesis +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationFamily +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationJets +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationJoint +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationMain +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationMainSlots +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationSpectral +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationSplit +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorConcentrationWeighted +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorDerivative +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorEnvelope +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorInsignificant +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorMarkedIntegral +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorMotion +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorNodeEnvelope +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorOffchild +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorPhysicalMotion +OAI.Analysis.LipschitzHilbert.Packets.SourceSelectorPlaneIntegral +OAI.Analysis.LipschitzHilbert.Packets.SourceSizeOnePacket +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedAnalyzedGlobal +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedAnalyzedNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedBandStops +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentration +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationCentered +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationFamily +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationMain +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationMainSlots +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationSpectral +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedConcentrationWeighted +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedCovariantRescale +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedErrorFamily +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedErrorPhysical +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedErrorRaw +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedErrorSynthesis +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedGrid +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedInhabitedGeometry +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedLabeledGeometry +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedLatticeData +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedLineNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedLinearEnvelope +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedMoments +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedPacketData +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedPacketNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedPolynomialMoments +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedRawRescale +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorDerivative +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorInsignificant +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorIntervalMotion +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorMarkedIntegral +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorMotion +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSelectorPlaneIntegral +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedSynthesisNeighborhood +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedTreeMaximal +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedWeightedDerivative +OAI.Analysis.LipschitzHilbert.Packets.SourceSupportedWeightedMaximal +OAI.Analysis.LipschitzHilbert.Packets.SourceTreePacketPath +OAI.Analysis.LipschitzHilbert.Packets.TopCovariantPacket +OAI.Analysis.LipschitzHilbert.Packets.TopPacketWindow +OAI.Analysis.LipschitzHilbert.Packets.TopRawPacketData +OAI.Analysis.LipschitzHilbert.Packets.TopWeightedPacket +OAI.Analysis.LipschitzHilbert.Packets.UniformAnalyzedLine +OAI.Analysis.LipschitzHilbert.Packets.UnitPacketSelector +OAI.Analysis.LipschitzHilbert.Packets.VariationPacketL1 +OAI.Analysis.LipschitzHilbert.Packets.VerticalFrameBound +OAI.Analysis.LipschitzHilbert.Packets.VerticalFrameSynthesis +OAI.Analysis.LipschitzHilbert.Packets.WeightedPacketEnergy +OAI.Analysis.LipschitzHilbert.Phase.ActualBandDiagonal +OAI.Analysis.LipschitzHilbert.Phase.AngularAmplitudeIdentity +OAI.Analysis.LipschitzHilbert.Phase.AngularAnalyticWeight +OAI.Analysis.LipschitzHilbert.Phase.AngularBinOverlap +OAI.Analysis.LipschitzHilbert.Phase.AngularBinTransfer +OAI.Analysis.LipschitzHilbert.Phase.AngularBins +OAI.Analysis.LipschitzHilbert.Phase.AngularBoundary +OAI.Analysis.LipschitzHilbert.Phase.AngularBoundaryDistance +OAI.Analysis.LipschitzHilbert.Phase.AngularBoundaryLocality +OAI.Analysis.LipschitzHilbert.Phase.AngularBoundaryNull +OAI.Analysis.LipschitzHilbert.Phase.AngularCommonTranslation +OAI.Analysis.LipschitzHilbert.Phase.AngularConservation +OAI.Analysis.LipschitzHilbert.Phase.AngularCountBridge +OAI.Analysis.LipschitzHilbert.Phase.AngularErrorConvolution +OAI.Analysis.LipschitzHilbert.Phase.AngularErrorFamily +OAI.Analysis.LipschitzHilbert.Phase.AngularErrorMoments +OAI.Analysis.LipschitzHilbert.Phase.AngularExceptionCount +OAI.Analysis.LipschitzHilbert.Phase.AngularGeometry +OAI.Analysis.LipschitzHilbert.Phase.AngularGraphMass +OAI.Analysis.LipschitzHilbert.Phase.AngularGraphPrediction +OAI.Analysis.LipschitzHilbert.Phase.AngularGrid +OAI.Analysis.LipschitzHilbert.Phase.AngularLineCounting +OAI.Analysis.LipschitzHilbert.Phase.AngularLossMotion +OAI.Analysis.LipschitzHilbert.Phase.AngularMassMotion +OAI.Analysis.LipschitzHilbert.Phase.AngularNormalization +OAI.Analysis.LipschitzHilbert.Phase.AngularPacketAmplitude +OAI.Analysis.LipschitzHilbert.Phase.AngularPathLossMotion +OAI.Analysis.LipschitzHilbert.Phase.AngularPathNormalization +OAI.Analysis.LipschitzHilbert.Phase.AngularSegmentWeight +OAI.Analysis.LipschitzHilbert.Phase.AngularSnapshot +OAI.Analysis.LipschitzHilbert.Phase.AngularSourceAmplitude +OAI.Analysis.LipschitzHilbert.Phase.AngularSourceWeight +OAI.Analysis.LipschitzHilbert.Phase.AngularStopping +OAI.Analysis.LipschitzHilbert.Phase.AngularTranslationMeasurable +OAI.Analysis.LipschitzHilbert.Phase.BandDiagonalBasicL1 +OAI.Analysis.LipschitzHilbert.Phase.BandDiagonalHighL1 +OAI.Analysis.LipschitzHilbert.Phase.BandDiagonalReverseL1 +OAI.Analysis.LipschitzHilbert.Phase.DampedSimplexInterpolation +OAI.Analysis.LipschitzHilbert.Phase.DiagonalAmplitudeLimit +OAI.Analysis.LipschitzHilbert.Phase.DiagonalAmplitudeReconstruction +OAI.Analysis.LipschitzHilbert.Phase.DiagonalCarrier +OAI.Analysis.LipschitzHilbert.Phase.DiagonalGeometryChoice +OAI.Analysis.LipschitzHilbert.Phase.DiagonalPhaseSelection +OAI.Analysis.LipschitzHilbert.Phase.DominantCoefficient +OAI.Analysis.LipschitzHilbert.Phase.DominantNormalization +OAI.Analysis.LipschitzHilbert.Phase.DominantPathComparison +OAI.Analysis.LipschitzHilbert.Phase.DominantPredictionBlend +OAI.Analysis.LipschitzHilbert.Phase.FiniteDiagonalBandL1 +OAI.Analysis.LipschitzHilbert.Phase.FiniteDiagonalBasicL1 +OAI.Analysis.LipschitzHilbert.Phase.FiniteDiagonalHighL1 +OAI.Analysis.LipschitzHilbert.Phase.FiniteDiagonalReverseL1 +OAI.Analysis.LipschitzHilbert.Phase.FiniteFourierGain +OAI.Analysis.LipschitzHilbert.Phase.FiniteInterpolation +OAI.Analysis.LipschitzHilbert.Phase.FourthMoment +OAI.Analysis.LipschitzHilbert.Phase.FrequencyQuantiles +OAI.Analysis.LipschitzHilbert.Phase.GaussianPhaseDamping +OAI.Analysis.LipschitzHilbert.Phase.GraphPhaseAverage +OAI.Analysis.LipschitzHilbert.Phase.GraphPhasePrediction +OAI.Analysis.LipschitzHilbert.Phase.GraphPredictionFactor +OAI.Analysis.LipschitzHilbert.Phase.HomogeneousFourthMoment +OAI.Analysis.LipschitzHilbert.Phase.ImprovedFourthMoment +OAI.Analysis.LipschitzHilbert.Phase.InterpolationFamily +OAI.Analysis.LipschitzHilbert.Phase.LineGridPrediction +OAI.Analysis.LipschitzHilbert.Phase.LocalPredictionAssembly +OAI.Analysis.LipschitzHilbert.Phase.LocalSkippedPrediction +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularAssignment +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularBasicPairing +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularCover +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularHighPairing +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularModel +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularPartition +OAI.Analysis.LipschitzHilbert.Phase.PacketAngularReversePairing +OAI.Analysis.LipschitzHilbert.Phase.PacketDataSelectionAngularGeometry +OAI.Analysis.LipschitzHilbert.Phase.PacketDataSignedAngularGeometry +OAI.Analysis.LipschitzHilbert.Phase.PhaseCombinatorics +OAI.Analysis.LipschitzHilbert.Phase.PhaseMotion +OAI.Analysis.LipschitzHilbert.Phase.PhaseSelection +OAI.Analysis.LipschitzHilbert.Phase.PlanarSliceFourierAngular +OAI.Analysis.LipschitzHilbert.Phase.PredictionBlend +OAI.Analysis.LipschitzHilbert.Phase.PredictionCells +OAI.Analysis.LipschitzHilbert.Phase.PredictionNormalization +OAI.Analysis.LipschitzHilbert.Phase.QuantileGap +OAI.Analysis.LipschitzHilbert.Phase.Quantiles +OAI.Analysis.LipschitzHilbert.Phase.ScalarBandDiagonal +OAI.Analysis.LipschitzHilbert.Phase.ScalarPhase +OAI.Analysis.LipschitzHilbert.Phase.SimplexTubeInterpolation +OAI.Analysis.LipschitzHilbert.Phase.SourceActivePrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceAmplitudeInterpolation +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularAmplitude +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularEnvelope +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularErrorTail +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularFrozenEstimate +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularFrozenIntegration +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularGridRebase +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularIdentity +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularLongCellMask +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularOrdinaryTree +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularScales +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularSupport +OAI.Analysis.LipschitzHilbert.Phase.SourceAngularTreeSplit +OAI.Analysis.LipschitzHilbert.Phase.SourceBalancedPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceBlockPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceDominantBlend +OAI.Analysis.LipschitzHilbert.Phase.SourceDominantGrid +OAI.Analysis.LipschitzHilbert.Phase.SourceDominantPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceDominantValues +OAI.Analysis.LipschitzHilbert.Phase.SourceEmptyPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceFinitePhaseInterpolation +OAI.Analysis.LipschitzHilbert.Phase.SourceFullAngularGrid +OAI.Analysis.LipschitzHilbert.Phase.SourceGridPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceLabeledAngularErrorData +OAI.Analysis.LipschitzHilbert.Phase.SourceLocalPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourceMarkedPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourcePathPhaseMotion +OAI.Analysis.LipschitzHilbert.Phase.SourcePathPrediction +OAI.Analysis.LipschitzHilbert.Phase.SourcePhaseNorm +OAI.Analysis.LipschitzHilbert.Phase.SourcePhaseParameters +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictableAmplitudeMotion +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictableDecay +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictableLength +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictablePacketMotion +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionDecay +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionIntegral +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionMotion +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionParameters +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionShrink +OAI.Analysis.LipschitzHilbert.Phase.SourcePredictionValues +OAI.Analysis.LipschitzHilbert.Phase.SourceRootPathInterpolation +OAI.Analysis.LipschitzHilbert.Phase.SourceSelectionAngularGeometry +OAI.Analysis.LipschitzHilbert.Phase.SourceSelectorBlockPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSelectorPathPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSelectorReversePathPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSelectorWindowPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSignedAngularGeometry +OAI.Analysis.LipschitzHilbert.Phase.SourceSupportedSelectorBlockPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSupportedSelectorPathPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSupportedSelectorReversePathPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceSupportedSelectorWindowPredictor +OAI.Analysis.LipschitzHilbert.Phase.SourceTypeUniformInterpolation +OAI.Analysis.LipschitzHilbert.Phase.TiledPredictionIntegral +OAI.Analysis.LipschitzHilbert.Trees.AmplitudeMassTails +OAI.Analysis.LipschitzHilbert.Trees.BadStripMass +OAI.Analysis.LipschitzHilbert.Trees.BoundaryDepthCrossing +OAI.Analysis.LipschitzHilbert.Trees.BoundaryDistanceAverage +OAI.Analysis.LipschitzHilbert.Trees.BoundaryErrorFubini +OAI.Analysis.LipschitzHilbert.Trees.BoundaryTelescoping +OAI.Analysis.LipschitzHilbert.Trees.ComplementaryMass +OAI.Analysis.LipschitzHilbert.Trees.DyadicLineGrid +OAI.Analysis.LipschitzHilbert.Trees.EventMass +OAI.Analysis.LipschitzHilbert.Trees.FiniteGoodPath +OAI.Analysis.LipschitzHilbert.Trees.FiniteLineGrid +OAI.Analysis.LipschitzHilbert.Trees.FixedPathAverage +OAI.Analysis.LipschitzHilbert.Trees.FourGridBandErrors +OAI.Analysis.LipschitzHilbert.Trees.GeometricBoundaryDepth +OAI.Analysis.LipschitzHilbert.Trees.GraphPathBaseline +OAI.Analysis.LipschitzHilbert.Trees.HierarchyNormalization +OAI.Analysis.LipschitzHilbert.Trees.HierarchyVariation +OAI.Analysis.LipschitzHilbert.Trees.HierarchyWeights +OAI.Analysis.LipschitzHilbert.Trees.LineGridBMO +OAI.Analysis.LipschitzHilbert.Trees.LineGridBMO_Tail +OAI.Analysis.LipschitzHilbert.Trees.LineGridConditionalBMO +OAI.Analysis.LipschitzHilbert.Trees.LineGridLimit +OAI.Analysis.LipschitzHilbert.Trees.LineGridMartingale +OAI.Analysis.LipschitzHilbert.Trees.LineGridPoincare +OAI.Analysis.LipschitzHilbert.Trees.LineGridPrimitive +OAI.Analysis.LipschitzHilbert.Trees.LineSamplingL2Path +OAI.Analysis.LipschitzHilbert.Trees.LineSamplingPath +OAI.Analysis.LipschitzHilbert.Trees.PathCoefficient +OAI.Analysis.LipschitzHilbert.Trees.PathDrops +OAI.Analysis.LipschitzHilbert.Trees.PathExpansion +OAI.Analysis.LipschitzHilbert.Trees.ResidualBlocks +OAI.Analysis.LipschitzHilbert.Trees.ResidualBudget +OAI.Analysis.LipschitzHilbert.Trees.ResidualOscillation +OAI.Analysis.LipschitzHilbert.Trees.SegmentMassSum +OAI.Analysis.LipschitzHilbert.Trees.SlopePartitionGrid +OAI.Analysis.LipschitzHilbert.Trees.SourceAdjointPairingBound +OAI.Analysis.LipschitzHilbert.Trees.SourceAllDyadicMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceAllStrongMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeAssembly +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeBounds +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeEntire +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeExhaustion +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeExponential +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeMeasurable +OAI.Analysis.LipschitzHilbert.Trees.SourceAmplitudeMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedBoundaryPrefix +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedLabelCount +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedLabelCountAt +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedLinearEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedMarkedBound +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedMarkedPath +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedMaskSums +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedModelInterval +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedParentCentralGain +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedParentCentralInputs +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedParentMarkedBound +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedParentPhysicalPlane +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedParentVertexIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedPathIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedPlaneIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedPlanePath +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedStoppedBound +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedStoppedInputs +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedSupportedGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedSupportedPath +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopFamily +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopOffchild +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopPhysical +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopReference +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTopSelector +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedTubeEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceAssignedVertexPath +OAI.Analysis.LipschitzHilbert.Trees.SourceAveraging +OAI.Analysis.LipschitzHilbert.Trees.SourceAxisMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceBadEventUnion +OAI.Analysis.LipschitzHilbert.Trees.SourceBalancedBlend +OAI.Analysis.LipschitzHilbert.Trees.SourceBalancedGrid +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockChildren +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockConservation +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockDisintegration +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockException +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockGraph +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockLineGrid +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockModulus +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockPathMass +OAI.Analysis.LipschitzHilbert.Trees.SourceBlockPathMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryDeficit +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryEntropy +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryEntropyError +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryErrorDecay +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryExpectedLoss +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryIntegrability +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryIntegratedError +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryIntegratedGain +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryJointMeasurable +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryLossBounds +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryMajorant +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryRadial +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryRadius +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryScales +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundaryTotalError +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundedDuality +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundedInputEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceBoundedTreeSize +OAI.Analysis.LipschitzHilbert.Trees.SourceBoxIntegralComparison +OAI.Analysis.LipschitzHilbert.Trees.SourceBoxReproduction +OAI.Analysis.LipschitzHilbert.Trees.SourceBoxSupremum +OAI.Analysis.LipschitzHilbert.Trees.SourceBoxSupremumEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceCappedStepArithmetic +OAI.Analysis.LipschitzHilbert.Trees.SourceCarrierFreeEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceCellMarking +OAI.Analysis.LipschitzHilbert.Trees.SourceCellPolynomial +OAI.Analysis.LipschitzHilbert.Trees.SourceCenteredCoefficient +OAI.Analysis.LipschitzHilbert.Trees.SourceCenteredMaskedVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceCenteredSquareBound +OAI.Analysis.LipschitzHilbert.Trees.SourceCenteredSquareTail +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralBudgetAE +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralHolder +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralHolderAE +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralPathGain +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralPowerGain +OAI.Analysis.LipschitzHilbert.Trees.SourceCentralRootBudgetAE +OAI.Analysis.LipschitzHilbert.Trees.SourceCoefficientIntegrability +OAI.Analysis.LipschitzHilbert.Trees.SourceCommonTerminalIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceComparablePlanarGram +OAI.Analysis.LipschitzHilbert.Trees.SourceCoordinateSpectrum +OAI.Analysis.LipschitzHilbert.Trees.SourceCountParameters +OAI.Analysis.LipschitzHilbert.Trees.SourceCovariantTop +OAI.Analysis.LipschitzHilbert.Trees.SourceCrossAdjointEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceCrossConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceCrossDerivative +OAI.Analysis.LipschitzHilbert.Trees.SourceCrudeMassBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceCrudeMoment +OAI.Analysis.LipschitzHilbert.Trees.SourceCrudeMomentAE +OAI.Analysis.LipschitzHilbert.Trees.SourceDeletionForest +OAI.Analysis.LipschitzHilbert.Trees.SourceDeletionTreeEstimate +OAI.Analysis.LipschitzHilbert.Trees.SourceDemodulatedCellEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceDemodulatedFourier +OAI.Analysis.LipschitzHilbert.Trees.SourceDemodulatedLong +OAI.Analysis.LipschitzHilbert.Trees.SourceDemodulatedSynthesis +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityForest +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityForestIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityKeepers +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityModel +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityPowerForest +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityRadius +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityRebase +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityRemovalIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityScaledForest +OAI.Analysis.LipschitzHilbert.Trees.SourceDensitySpatialCost +OAI.Analysis.LipschitzHilbert.Trees.SourceDensityTail +OAI.Analysis.LipschitzHilbert.Trees.SourceDropDensity +OAI.Analysis.LipschitzHilbert.Trees.SourceDropSize +OAI.Analysis.LipschitzHilbert.Trees.SourceDropTreeTransport +OAI.Analysis.LipschitzHilbert.Trees.SourceEitherGrid +OAI.Analysis.LipschitzHilbert.Trees.SourceEnclosingScale +OAI.Analysis.LipschitzHilbert.Trees.SourceEnvelopeWeightComparison +OAI.Analysis.LipschitzHilbert.Trees.SourceErrorSupported +OAI.Analysis.LipschitzHilbert.Trees.SourceErrorTail +OAI.Analysis.LipschitzHilbert.Trees.SourceExponentialIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceFiberGram +OAI.Analysis.LipschitzHilbert.Trees.SourceFiniteExponentialIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceFiniteLongTree +OAI.Analysis.LipschitzHilbert.Trees.SourceFiniteSizeBound +OAI.Analysis.LipschitzHilbert.Trees.SourceFiniteThresholdLevels +OAI.Analysis.LipschitzHilbert.Trees.SourceFixedException +OAI.Analysis.LipschitzHilbert.Trees.SourceFourPolarizedConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceGlobalDyadicMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceGoodPathArea +OAI.Analysis.LipschitzHilbert.Trees.SourceGoodPathBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceGoodPathSet +OAI.Analysis.LipschitzHilbert.Trees.SourceGramGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceGramMargin +OAI.Analysis.LipschitzHilbert.Trees.SourceGramSchur +OAI.Analysis.LipschitzHilbert.Trees.SourceGridParameters +OAI.Analysis.LipschitzHilbert.Trees.SourceHighDensityForest +OAI.Analysis.LipschitzHilbert.Trees.SourceInhabitedLabels +OAI.Analysis.LipschitzHilbert.Trees.SourceInsignificantShrink +OAI.Analysis.LipschitzHilbert.Trees.SourceInteractionGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceKernelIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceKernelShells +OAI.Analysis.LipschitzHilbert.Trees.SourceL2Gram +OAI.Analysis.LipschitzHilbert.Trees.SourceL2Sums +OAI.Analysis.LipschitzHilbert.Trees.SourceLabelScaleEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledActiveCardTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledActiveReference +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledActiveSpectrum +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledAdjointPolarization +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledCoefficientSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledComparableEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledCrossIdentity +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledCrossResidual +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledDerivative +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledErrorBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledErrorConvolution +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledErrorFamily +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledErrorPhysicalTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledErrorTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledGoodEvents +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledGoodQuantities +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledGoodTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMainRestriction +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMainSlots +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMainTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMaskedSlots +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledMultiscaleEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledNarrowTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledPolarization +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledPositiveSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledRawEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledRecenter +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledResidualEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledResidualThreshold +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledScaleEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledSelectedVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledSpectralGoodTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledStoppingVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledSynthesisEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledTopSum +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledUniformErrorTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledUniformGoodTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledVariationSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceLabeledVariationTail +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeMultiscaleEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticePolarization +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticePolarizationSpectrum +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeRawData +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeScaleEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLatticeSpectrum +OAI.Analysis.LipschitzHilbert.Trees.SourceLengthRestriction +OAI.Analysis.LipschitzHilbert.Trees.SourceLineGrid +OAI.Analysis.LipschitzHilbert.Trees.SourceLineMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceLineRescale +OAI.Analysis.LipschitzHilbert.Trees.SourceLineWindow +OAI.Analysis.LipschitzHilbert.Trees.SourceLocalLabelEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLocalLabelVectorEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLogMass +OAI.Analysis.LipschitzHilbert.Trees.SourceLongCellEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceLongCellMask +OAI.Analysis.LipschitzHilbert.Trees.SourceLongErrorGlobal +OAI.Analysis.LipschitzHilbert.Trees.SourceLongPrefixes +OAI.Analysis.LipschitzHilbert.Trees.SourceLongTreeSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceLongTreeSupport +OAI.Analysis.LipschitzHilbert.Trees.SourceLpDamping +OAI.Analysis.LipschitzHilbert.Trees.SourceLpExhaustion +OAI.Analysis.LipschitzHilbert.Trees.SourceMarkedFactorsIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceMarkedIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceMarkedResidual +OAI.Analysis.LipschitzHilbert.Trees.SourceMarkedStop +OAI.Analysis.LipschitzHilbert.Trees.SourceMarkingParameters +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskTail +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedAmplitude +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedFrozenEstimate +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedPhysicalMoments +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedPhysicalTail +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedReference +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedSynthesis +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedTreeSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceMaskedVariationTail +OAI.Analysis.LipschitzHilbert.Trees.SourceMassStopping +OAI.Analysis.LipschitzHilbert.Trees.SourceMaximalBound +OAI.Analysis.LipschitzHilbert.Trees.SourceMixedReference +OAI.Analysis.LipschitzHilbert.Trees.SourceModelDegenerateCases +OAI.Analysis.LipschitzHilbert.Trees.SourceModelThresholdScale +OAI.Analysis.LipschitzHilbert.Trees.SourceMonotoneMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceMotionBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceMovingException +OAI.Analysis.LipschitzHilbert.Trees.SourceMovingWeights +OAI.Analysis.LipschitzHilbert.Trees.SourceNodeMeasurable +OAI.Analysis.LipschitzHilbert.Trees.SourceNodeRatio +OAI.Analysis.LipschitzHilbert.Trees.SourceNormalizedDecay +OAI.Analysis.LipschitzHilbert.Trees.SourceNormalizedMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceNormalizedRemovalStep +OAI.Analysis.LipschitzHilbert.Trees.SourceOffchildMask +OAI.Analysis.LipschitzHilbert.Trees.SourceOffchildRegroup +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryAdjoint +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryAdjointEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryDensityForest +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryModelBound +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryModelConfig +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryModelEstimate +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryRemovalStep +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinarySizeStopping +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinarySizeTest +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryTreeEstimate +OAI.Analysis.LipschitzHilbert.Trees.SourceOrdinaryTreeIdentity +OAI.Analysis.LipschitzHilbert.Trees.SourceOriginalIntegrability +OAI.Analysis.LipschitzHilbert.Trees.SourceOriginalMarkedPath +OAI.Analysis.LipschitzHilbert.Trees.SourceOriginalParentMarkedPath +OAI.Analysis.LipschitzHilbert.Trees.SourceOriginalPathRegularity +OAI.Analysis.LipschitzHilbert.Trees.SourceOriginalRecovery +OAI.Analysis.LipschitzHilbert.Trees.SourcePackedEnvelopeEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceParameters +OAI.Analysis.LipschitzHilbert.Trees.SourceParentFullResidual +OAI.Analysis.LipschitzHilbert.Trees.SourceParentReferenceEvents +OAI.Analysis.LipschitzHilbert.Trees.SourceParentResidualReference +OAI.Analysis.LipschitzHilbert.Trees.SourceParentResidualSquare +OAI.Analysis.LipschitzHilbert.Trees.SourceParentStoppedBound +OAI.Analysis.LipschitzHilbert.Trees.SourceParentWidth +OAI.Analysis.LipschitzHilbert.Trees.SourcePathAmplitudeCongr +OAI.Analysis.LipschitzHilbert.Trees.SourcePathCoefficientMotion +OAI.Analysis.LipschitzHilbert.Trees.SourcePathCostBudget +OAI.Analysis.LipschitzHilbert.Trees.SourcePathCountInvariant +OAI.Analysis.LipschitzHilbert.Trees.SourcePathDropMotion +OAI.Analysis.LipschitzHilbert.Trees.SourcePathIntegrand +OAI.Analysis.LipschitzHilbert.Trees.SourcePathProduct +OAI.Analysis.LipschitzHilbert.Trees.SourcePathValues +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalAmplitudeMeasurable +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalAmplitudeMotion +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalCellMarking +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalCoefficient +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalFullResidual +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalGoodPath +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalGoodResidual +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalInsignificant +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalNormalizedMotion +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalOffchildGrouping +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalPathAssembly +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalPositiveScale +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalPowerGain +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalPropagatedTail +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalReferenceSquare +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalResidualNorm +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalResidualSquare +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalShiftedResidual +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalSingleScale +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalSquareTail +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalStoppedBound +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalTail +OAI.Analysis.LipschitzHilbert.Trees.SourcePhysicalUnaryEndpoint +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarGramSchur +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarKernelBound +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarPlancherel +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarPolynomial +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarSynthesis +OAI.Analysis.LipschitzHilbert.Trees.SourcePlanarVectorReproduction +OAI.Analysis.LipschitzHilbert.Trees.SourcePlaneIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourcePlaneWeightCost +OAI.Analysis.LipschitzHilbert.Trees.SourcePolarizedCoefficient +OAI.Analysis.LipschitzHilbert.Trees.SourcePolarizedInterval +OAI.Analysis.LipschitzHilbert.Trees.SourcePolynomialGoodPathArea +OAI.Analysis.LipschitzHilbert.Trees.SourcePolynomialMassLog +OAI.Analysis.LipschitzHilbert.Trees.SourcePolynomialReferenceArea +OAI.Analysis.LipschitzHilbert.Trees.SourcePolynomialSelectedGoodPath +OAI.Analysis.LipschitzHilbert.Trees.SourcePositiveSelectedSynthesis +OAI.Analysis.LipschitzHilbert.Trees.SourcePropagatedTailBound +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialAverage +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialLoss +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialMassBounds +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialScales +OAI.Analysis.LipschitzHilbert.Trees.SourceRadialTelescoping +OAI.Analysis.LipschitzHilbert.Trees.SourceRecenterTransport +OAI.Analysis.LipschitzHilbert.Trees.SourceRecenteredSelectedTree +OAI.Analysis.LipschitzHilbert.Trees.SourceRecenteredTreeData +OAI.Analysis.LipschitzHilbert.Trees.SourceReciprocalWeightEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceRecordedEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceBandAll +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceBounds +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceCoordinates +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceLabelCount +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceLattice +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceMainRestriction +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceMask +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceMasks +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceMoments +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceOrdinaryTree +OAI.Analysis.LipschitzHilbert.Trees.SourceReferencePhysicalIdentity +OAI.Analysis.LipschitzHilbert.Trees.SourceReferencePolynomialTail +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceRestriction +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceSelectedVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceSelectorGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceTail +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceTailOrder +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceThreshold +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceTreeSize +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceUnion +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceWeightedMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceReferenceWindowBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceReproduction +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualBlockBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualBlockGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualCostBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualEnvelopes +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualMask +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualPolynomial +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualPropagation +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualSquare +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceResidualWeightBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceRestrictedGram +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseBlocks +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseCellMarking +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseDropComparison +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseMarkedIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseSnapshot +OAI.Analysis.LipschitzHilbert.Trees.SourceReverseWeights +OAI.Analysis.LipschitzHilbert.Trees.SourceRootCells +OAI.Analysis.LipschitzHilbert.Trees.SourceRootIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceRootedSelectedTree +OAI.Analysis.LipschitzHilbert.Trees.SourceScaleGramSplit +OAI.Analysis.LipschitzHilbert.Trees.SourceScaleRestriction +OAI.Analysis.LipschitzHilbert.Trees.SourceScaleRestrictionSums +OAI.Analysis.LipschitzHilbert.Trees.SourceScaledTopGood +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedArea +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedBoxSeparation +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedCoefficientBound +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedDuality +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedEnvelopeEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedFamily +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedGoodEvent +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedGoodPathArea +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedGram +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedPrefix +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedQuadratic +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedRecordSums +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedReferenceData +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedReferenceGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedResidualSquare +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedScale +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedTopEstimate +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedTopGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceSelectedTreeData +OAI.Analysis.LipschitzHilbert.Trees.SourceSharedGoodPath +OAI.Analysis.LipschitzHilbert.Trees.SourceSharpDensityForest +OAI.Analysis.LipschitzHilbert.Trees.SourceShearedEnvelopeEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftNormalization +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftSimplex +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftedCellMotion +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftedDrop +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftedReferenceVariation +OAI.Analysis.LipschitzHilbert.Trees.SourceShiftedScales +OAI.Analysis.LipschitzHilbert.Trees.SourceShortDyadicBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceShortTreeGlobal +OAI.Analysis.LipschitzHilbert.Trees.SourceShortTreeIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceShortTreeSum +OAI.Analysis.LipschitzHilbert.Trees.SourceSignedBoxSeparation +OAI.Analysis.LipschitzHilbert.Trees.SourceSignedSelectedArea +OAI.Analysis.LipschitzHilbert.Trees.SourceSignedSelectedSynthesis +OAI.Analysis.LipschitzHilbert.Trees.SourceSignedTopGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceSimplexLp +OAI.Analysis.LipschitzHilbert.Trees.SourceSimplexLpExhaustion +OAI.Analysis.LipschitzHilbert.Trees.SourceSimplexLpOn +OAI.Analysis.LipschitzHilbert.Trees.SourceSimultaneousCount +OAI.Analysis.LipschitzHilbert.Trees.SourceSingleScaleEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceSizeRemovalIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceSlopeLabels +OAI.Analysis.LipschitzHilbert.Trees.SourceSlotTails +OAI.Analysis.LipschitzHilbert.Trees.SourceSlottedCoefficient +OAI.Analysis.LipschitzHilbert.Trees.SourceSlottedConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceSlottedLattice +OAI.Analysis.LipschitzHilbert.Trees.SourceSnapshotAmplitudeScale +OAI.Analysis.LipschitzHilbert.Trees.SourceSnapshotChoice +OAI.Analysis.LipschitzHilbert.Trees.SourceSnapshotPolynomial +OAI.Analysis.LipschitzHilbert.Trees.SourceSnapshotSize +OAI.Analysis.LipschitzHilbert.Trees.SourceSnapshotWindow +OAI.Analysis.LipschitzHilbert.Trees.SourceSpatialSelectedTree +OAI.Analysis.LipschitzHilbert.Trees.SourceSpatialSubdivision +OAI.Analysis.LipschitzHilbert.Trees.SourceSpatialTreePieces +OAI.Analysis.LipschitzHilbert.Trees.SourceStepArithmetic +OAI.Analysis.LipschitzHilbert.Trees.SourceStopCostBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedAmplitude +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedError +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedMarking +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedMassPower +OAI.Analysis.LipschitzHilbert.Trees.SourceStoppedRecurrence +OAI.Analysis.LipschitzHilbert.Trees.SourceStrongDyadicMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceTerminalScale +OAI.Analysis.LipschitzHilbert.Trees.SourceThreeGridMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceThreeGridPlane +OAI.Analysis.LipschitzHilbert.Trees.SourceThresholdSum +OAI.Analysis.LipschitzHilbert.Trees.SourceThresholdWeights +OAI.Analysis.LipschitzHilbert.Trees.SourceTiledLineIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceTopConcentration +OAI.Analysis.LipschitzHilbert.Trees.SourceTopGood +OAI.Analysis.LipschitzHilbert.Trees.SourceTopReferenceGeometry +OAI.Analysis.LipschitzHilbert.Trees.SourceTopWeightTransfer +OAI.Analysis.LipschitzHilbert.Trees.SourceTotalWeightBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeCellDensity +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeCellGluing +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeCells +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeConservation +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeDensityTerm +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeErrorIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeExitBound +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeExpansion +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeForestIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeGoodPaths +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeMomentBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeProbability +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeSelectorError +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeSpectrum +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeVertexIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceTreeVertexMoment +OAI.Analysis.LipschitzHilbert.Trees.SourceTrimInteractions +OAI.Analysis.LipschitzHilbert.Trees.SourceTwoSidedRemovedIntegral +OAI.Analysis.LipschitzHilbert.Trees.SourceTwoSidedSizeArea +OAI.Analysis.LipschitzHilbert.Trees.SourceTypeUniformCentral +OAI.Analysis.LipschitzHilbert.Trees.SourceTypeUniformMoments +OAI.Analysis.LipschitzHilbert.Trees.SourceUnaryErrorBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceUniformDamping +OAI.Analysis.LipschitzHilbert.Trees.SourceUnsignedSizeMonotone +OAI.Analysis.LipschitzHilbert.Trees.SourceVectorEnvelope +OAI.Analysis.LipschitzHilbert.Trees.SourceVectorPolynomial +OAI.Analysis.LipschitzHilbert.Trees.SourceVectorReproduction +OAI.Analysis.LipschitzHilbert.Trees.SourceVectorSchwartz +OAI.Analysis.LipschitzHilbert.Trees.SourceVectorSlices +OAI.Analysis.LipschitzHilbert.Trees.SourceVertexConstantBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceVertexPlaneParameters +OAI.Analysis.LipschitzHilbert.Trees.SourceVerticalDemodulation +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightPointwiseBudget +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedBadPath +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedCellSupremum +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedEnvelopeKernel +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedPairing +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedTreeEnergy +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedTreeMajorant +OAI.Analysis.LipschitzHilbert.Trees.SourceWeightedTreeMaximal +OAI.Analysis.LipschitzHilbert.Trees.SourceWhitneyDensityTest +OAI.Analysis.LipschitzHilbert.Trees.SourceWhitneyGluing +OAI.Analysis.LipschitzHilbert.Trees.SourceWhitneyIntervals +OAI.Analysis.LipschitzHilbert.Trees.SourceWhitneySummation +OAI.Analysis.LipschitzHilbert.Trees.SourceWideLogMass +OAI.Analysis.LipschitzHilbert.Trees.SourceWindowAverage +OAI.Analysis.LipschitzHilbert.Trees.SourceZeroDensity +OAI.Analysis.LipschitzHilbert.Trees.StripMassOperations +OAI.Analysis.LipschitzHilbert.Trees.ThreeGridWeakL1 +OAI.Analysis.LipschitzHilbert.Trees.UnaryEnergy +OAI.Analysis.LipschitzHilbert.Trees.UnaryPartitionSum +OAI.Analysis.LipschitzHilbert.Trees.UnaryPropagation +OAI.Analysis.LipschitzHilbert.Trees.UnaryRunCharging +OAI.Analysis.LipschitzHilbert.Trees.UnaryRunResidual +OAI.Analysis.LipschitzHilbert.Trees.UnaryRunVariation +OAI.Analysis.LipschitzHilbert.Trees.UnaryRuns +OAI.Analysis.LipschitzHilbert.Trees.UnarySegmentEstimate +OAI.Analysis.LipschitzHilbert.Trees.UnarySegmentation +OAI.Analysis.LipschitzHilbert.Trees.UnaryTelescope +OAI.Analysis.LipschitzHilbert.Trees.VertexIntegration +OAI.Analysis.LipschitzHilbert.TwoInputMain diff --git a/tasks/lipschitz-hilbert/solution/reference.py b/tasks/lipschitz-hilbert/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/lipschitz-hilbert/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/lipschitz-hilbert/solution/solve.sh b/tasks/lipschitz-hilbert/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3cfd6c014e519e763869df8c86a002ef07b8cce --- /dev/null +++ b/tasks/lipschitz-hilbert/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LipschitzHilbert, i.e. module OAI.Analysis.LipschitzHilbert.Main and the +# 1910 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LipschitzHilbert.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LipschitzHilbert" diff --git a/tasks/lipschitz-hilbert/task.toml b/tasks/lipschitz-hilbert/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..960669e9ab15c08c987b273e508211f494c59fd7 --- /dev/null +++ b/tasks/lipschitz-hilbert/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/lipschitz-hilbert" +version = "1.0.0" +description = "Prove LipschitzHilbert (openai/math family 083: Stein's conjecture for Hilbert transforms along Lipschitz directions) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LipschitzHilbert.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LipschitzHilbert" +family = "083" +family_title = "Stein's conjecture for Hilbert transforms along Lipschitz directions" +subject = "Real and complex analysis" +theorems = ["OAI.LipschitzHilbert.main", "OAI.LipschitzHilbert.uniform_truncation"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LipschitzHilbert.Main" +reference_modules = 1910 +reference_lean_bytes = 9262948 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2945 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 20036 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/lipschitz-hilbert/tests/Challenge.lean b/tasks/lipschitz-hilbert/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0104a3198408ffd2a33a8fee86e35dc2e65882b0 --- /dev/null +++ b/tasks/lipschitz-hilbert/tests/Challenge.lean @@ -0,0 +1,80 @@ +import Mathlib + +namespace OAI + +noncomputable section + +/- Use the normed-field structure on ℂ for real scalar multiplication. -/ +attribute [-instance] instCommCStarAlgebraComplex + +open MeasureTheory Set +open scoped ENNReal NNReal + +namespace LipschitzHilbert + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev DirectionPlane := EuclideanSpace ℝ (Fin 2) + +def sample (v : DirectionPlane → DirectionPlane) (t : ℝ) (x : DirectionPlane) : + DirectionPlane := x - t • v x + +/-- The symmetrized form of the hard-truncated directional integral. -/ +def shortTransform (v : DirectionPlane → DirectionPlane) (ε a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + ∫ t in ε..a, t⁻¹ • (f (sample v t x) - f (sample v (-t) x)) + +def directionalKernel (v : DirectionPlane → DirectionPlane) + (f : DirectionPlane → ℂ) (x : DirectionPlane) (t : ℝ) : ℂ := + t⁻¹ • f (sample v t x) + +/-- The two hard-cutoff intervals in the directional Hilbert transform. -/ +def twoSidedTruncation (v : DirectionPlane → DirectionPlane) (ε a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + (∫ t in -a..-ε, directionalKernel v f x t) + + ∫ t in ε..a, directionalKernel v f x t + +/-- The symmetric quotient extended continuously at zero for smooth inputs. -/ +def smoothPrincipalValue (v : DirectionPlane → DirectionPlane) (a : ℝ) + (f : DirectionPlane → ℂ) (x : DirectionPlane) : ℂ := + let g := fun t : ℝ => f (sample v t x)-f (sample v (-t) x) + ∫ t in (0:ℝ)..a, Function.update (fun t => t⁻¹ • g t) 0 (deriv g 0) t + +attribute [instance] instCommCStarAlgebraComplex + +def ShortHilbertConclusion (a : ℝ) (C : ℝ≥0) : Prop := + ∀ v : Plane → Plane, LipschitzWith 1 v → (∀ x, ‖v x‖=1) → + (∀ epsilon : ℝ, 0 Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/lipschitz-hilbert/tests/task.json b/tasks/lipschitz-hilbert/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d4ddf5da67cfc243b0c7bceee181949f514a54f6 --- /dev/null +++ b/tasks/lipschitz-hilbert/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "LipschitzHilbert", + "comparator": { + "theorem_names": [ + "OAI.LipschitzHilbert.main", + "OAI.LipschitzHilbert.uniform_truncation" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 19136 +} \ No newline at end of file diff --git a/tasks/lipschitz-hilbert/tests/test.sh b/tasks/lipschitz-hilbert/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/lipschitz-hilbert/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/list-hadwiger/environment/Dockerfile b/tasks/list-hadwiger/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/list-hadwiger/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/list-hadwiger/environment/fetch_mathlib.sh b/tasks/list-hadwiger/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/list-hadwiger/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/list-hadwiger/environment/lake-manifest.json b/tasks/list-hadwiger/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/list-hadwiger/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/list-hadwiger/environment/lakefile.lean b/tasks/list-hadwiger/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/list-hadwiger/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/list-hadwiger/environment/lean_setup.sh b/tasks/list-hadwiger/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/list-hadwiger/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/list-hadwiger/environment/pack_submission.py b/tasks/list-hadwiger/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/list-hadwiger/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/list-hadwiger/instruction.md b/tasks/list-hadwiger/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bdadb9477d3c2cb3fa2e7eaa5a3d96fc03ce1b69 --- /dev/null +++ b/tasks/list-hadwiger/instruction.md @@ -0,0 +1,86 @@ +# openai/math challenge `ListHadwiger` (family 157) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 157 of the release, *Counterexamples to the Hadwiger and Colin de Verdiere conjectures* +(Combinatorics). The family as a whole: Disproves Hadwiger's conjecture even for fractional coloring: arbitrarily large finite simple graphs with independence number at most two satisfy $\chi_f(G)>h(G)$, where $h(G)$ is the largest clique-minor order. Also disproves the fractional Colin de Verdiere chromatic bound $\chi_f(G)\le\mu(G)+1$. In the positive direction, every finite nonempty graph satisfies $\chi_{\mathrm{list}}(G)\le C h(G)$ for a universal constant $C$. + +The challenge is `ListHadwiger`, also at `/opt/openai-math/challenges/ListHadwiger.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace LinearListHadwiger + +def ListColorable {V : Type} (G : SimpleGraph V) {Color : Type} + (L : V → Finset Color) : Prop := + ∃ c : V → Color, (∀ v, c v ∈ L v) ∧ ∀ ⦃v w⦄, G.Adj v w → c v ≠ c w + +def Choosable {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∀ (Color : Type) (L : V → Finset Color), (∀ v, k ≤ (L v).card) → ListColorable G L + +noncomputable def listChromaticNumber {V : Type} (G : SimpleGraph V) : ℕ := + sInf {k : ℕ | Choosable G k} + +def HasCliqueMinor {V : Type} (G : SimpleGraph V) (t : ℕ) : Prop := + ∃ B : Fin t → Set V, + (∀ i, (G.induce (B i)).Connected) ∧ + (∀ i j, i ≠ j → Disjoint (B i) (B j)) ∧ + (∀ i j, i ≠ j → ∃ v ∈ B i, ∃ w ∈ B j, G.Adj v w) + +noncomputable def hadwigerNumber {V : Type} (G : SimpleGraph V) : ℕ := + sSup {t : ℕ | HasCliqueMinor G t} + +def MainStatement : Prop := + ∃ C : ℕ, 1 ≤ C ∧ ∀ (V : Type) [Fintype V] [Nonempty V] (G : SimpleGraph V), + listChromaticNumber G ≤ C * hadwigerNumber G + +theorem main_theorem : MainStatement := by + sorry + +end LinearListHadwiger + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ListHadwiger.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LinearListHadwiger.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/list-hadwiger/solution/closure.txt b/tasks/list-hadwiger/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0aa44c5040802faa273ab253ad6fe6540d5447fe --- /dev/null +++ b/tasks/list-hadwiger/solution/closure.txt @@ -0,0 +1,53 @@ +OAI.Combinatorics.ListHadwiger.Assembly +OAI.Combinatorics.ListHadwiger.BagAssembly +OAI.Combinatorics.ListHadwiger.BagContraction +OAI.Combinatorics.ListHadwiger.Basic +OAI.Combinatorics.ListHadwiger.CoarseDensity +OAI.Combinatorics.ListHadwiger.ColorBins +OAI.Combinatorics.ListHadwiger.Concentration +OAI.Combinatorics.ListHadwiger.Connectivity +OAI.Combinatorics.ListHadwiger.ConnectivityTests +OAI.Combinatorics.ListHadwiger.Density +OAI.Combinatorics.ListHadwiger.District +OAI.Combinatorics.ListHadwiger.DistrictAssembly +OAI.Combinatorics.ListHadwiger.DistrictPaths +OAI.Combinatorics.ListHadwiger.EggCover +OAI.Combinatorics.ListHadwiger.Eligibility +OAI.Combinatorics.ListHadwiger.Exchanges +OAI.Combinatorics.ListHadwiger.Footprint +OAI.Combinatorics.ListHadwiger.Fractional +OAI.Combinatorics.ListHadwiger.FractionalSampling +OAI.Combinatorics.ListHadwiger.History +OAI.Combinatorics.ListHadwiger.HistoryBounds +OAI.Combinatorics.ListHadwiger.Incidence +OAI.Combinatorics.ListHadwiger.Knitting +OAI.Combinatorics.ListHadwiger.Main +OAI.Combinatorics.ListHadwiger.MinorModels +OAI.Combinatorics.ListHadwiger.Model +OAI.Combinatorics.ListHadwiger.PairedSources +OAI.Combinatorics.ListHadwiger.Palette +OAI.Combinatorics.ListHadwiger.PaletteSampling +OAI.Combinatorics.ListHadwiger.PathPacking +OAI.Combinatorics.ListHadwiger.Recursion +OAI.Combinatorics.ListHadwiger.RecursiveDistricts +OAI.Combinatorics.ListHadwiger.RecursiveGeometry +OAI.Combinatorics.ListHadwiger.RecursiveInduction +OAI.Combinatorics.ListHadwiger.RecursiveJunction +OAI.Combinatorics.ListHadwiger.Reduction +OAI.Combinatorics.ListHadwiger.RoleRouting +OAI.Combinatorics.ListHadwiger.Routing +OAI.Combinatorics.ListHadwiger.SamplingBounds +OAI.Combinatorics.ListHadwiger.SamplingConnectivity +OAI.Combinatorics.ListHadwiger.Separability +OAI.Combinatorics.ListHadwiger.Separators +OAI.Combinatorics.ListHadwiger.SmallList +OAI.Combinatorics.ListHadwiger.Stage +OAI.Combinatorics.ListHadwiger.StageAdvance +OAI.Combinatorics.ListHadwiger.StageDeletion +OAI.Combinatorics.ListHadwiger.StageExtension +OAI.Combinatorics.ListHadwiger.StagePacking +OAI.Combinatorics.ListHadwiger.StageSampling +OAI.Combinatorics.ListHadwiger.StageSeparation +OAI.Combinatorics.ListHadwiger.TerminalGrouping +OAI.Combinatorics.ListHadwiger.Thinning +OAI.Combinatorics.ListHadwiger.WeightedBound diff --git a/tasks/list-hadwiger/solution/reference.py b/tasks/list-hadwiger/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/list-hadwiger/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/list-hadwiger/solution/solve.sh b/tasks/list-hadwiger/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9aa32c3e32416cc07e0672627edbd8594c332e36 --- /dev/null +++ b/tasks/list-hadwiger/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ListHadwiger, i.e. module OAI.Combinatorics.ListHadwiger.Main and the +# 53 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ListHadwiger.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ListHadwiger" diff --git a/tasks/list-hadwiger/task.toml b/tasks/list-hadwiger/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ff1186f4fabe1048f27e07000a2f311d63f5ae4 --- /dev/null +++ b/tasks/list-hadwiger/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/list-hadwiger" +version = "1.0.0" +description = "Prove ListHadwiger (openai/math family 157: Counterexamples to the Hadwiger and Colin de Verdiere conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ListHadwiger.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ListHadwiger" +family = "157" +family_title = "Counterexamples to the Hadwiger and Colin de Verdiere conjectures" +subject = "Combinatorics" +theorems = ["OAI.LinearListHadwiger.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ListHadwiger.Main" +reference_modules = 53 +reference_lean_bytes = 902720 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 715 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12512 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/list-hadwiger/tests/Challenge.lean b/tasks/list-hadwiger/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2cc8e2f95d30d190301838e270a7c08d761c7ae8 --- /dev/null +++ b/tasks/list-hadwiger/tests/Challenge.lean @@ -0,0 +1,35 @@ +import Mathlib + +namespace OAI + +namespace LinearListHadwiger + +def ListColorable {V : Type} (G : SimpleGraph V) {Color : Type} + (L : V → Finset Color) : Prop := + ∃ c : V → Color, (∀ v, c v ∈ L v) ∧ ∀ ⦃v w⦄, G.Adj v w → c v ≠ c w + +def Choosable {V : Type} (G : SimpleGraph V) (k : ℕ) : Prop := + ∀ (Color : Type) (L : V → Finset Color), (∀ v, k ≤ (L v).card) → ListColorable G L + +noncomputable def listChromaticNumber {V : Type} (G : SimpleGraph V) : ℕ := + sInf {k : ℕ | Choosable G k} + +def HasCliqueMinor {V : Type} (G : SimpleGraph V) (t : ℕ) : Prop := + ∃ B : Fin t → Set V, + (∀ i, (G.induce (B i)).Connected) ∧ + (∀ i j, i ≠ j → Disjoint (B i) (B j)) ∧ + (∀ i j, i ≠ j → ∃ v ∈ B i, ∃ w ∈ B j, G.Adj v w) + +noncomputable def hadwigerNumber {V : Type} (G : SimpleGraph V) : ℕ := + sSup {t : ℕ | HasCliqueMinor G t} + +def MainStatement : Prop := + ∃ C : ℕ, 1 ≤ C ∧ ∀ (V : Type) [Fintype V] [Nonempty V] (G : SimpleGraph V), + listChromaticNumber G ≤ C * hadwigerNumber G + +theorem main_theorem : MainStatement := by + sorry + +end LinearListHadwiger + +end OAI diff --git a/tasks/list-hadwiger/tests/grade.py b/tasks/list-hadwiger/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/list-hadwiger/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/list-hadwiger/tests/task.json b/tasks/list-hadwiger/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..53f693a102b2d44d783377389cea2953c5d83091 --- /dev/null +++ b/tasks/list-hadwiger/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ListHadwiger", + "comparator": { + "theorem_names": [ + "OAI.LinearListHadwiger.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11612 +} \ No newline at end of file diff --git a/tasks/list-hadwiger/tests/test.sh b/tasks/list-hadwiger/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/list-hadwiger/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/little-finitistic/environment/Dockerfile b/tasks/little-finitistic/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/little-finitistic/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/little-finitistic/environment/fetch_mathlib.sh b/tasks/little-finitistic/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/little-finitistic/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/little-finitistic/environment/lake-manifest.json b/tasks/little-finitistic/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/little-finitistic/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/little-finitistic/environment/lakefile.lean b/tasks/little-finitistic/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/little-finitistic/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/little-finitistic/environment/lean_setup.sh b/tasks/little-finitistic/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/little-finitistic/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/little-finitistic/environment/pack_submission.py b/tasks/little-finitistic/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/little-finitistic/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/little-finitistic/instruction.md b/tasks/little-finitistic/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cf542f95a08e2b202196d2c3edc06dc0ff3bd4ce --- /dev/null +++ b/tasks/little-finitistic/instruction.md @@ -0,0 +1,88 @@ +# openai/math challenge `LittleFinitistic` (family 198) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 198 of the release, *A counterexample to the little finitistic-dimension conjecture* +(Algebra). The family as a whole: Constructs a finite-dimensional complex algebra whose finite-dimensional modules have unbounded finite projective dimensions. This disproves the little finitistic-dimension conjecture. + +The challenge is `LittleFinitistic`, also at `/opt/openai-math/challenges/LittleFinitistic.lean`: + +```lean +import Mathlib.Algebra.Category.ModuleCat.Abelian +import Mathlib.CategoryTheory.Abelian.Projective.Dimension +import Mathlib.Basic.Complex.Basic +import Mathlib.LinearAlgebra.FiniteDimensional.Defs +import Mathlib.RingTheory.Finiteness.Defs + +namespace OAI + +noncomputable section + +open CategoryTheory + +namespace LittleFinitistic + +universe u + +def littleFinitisticDimension (A : Type u) [Ring A] : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : Module.Finite A M) (_ : projectiveDimension M < ⊤), + projectiveDimension M + +namespace Main + +theorem exists_counterexample : + ∃ (A : Type) (_ : Ring A) (_ : Algebra ℂ A), + FiniteDimensional ℂ A ∧ littleFinitisticDimension A = ⊤ ∧ + ∀ m : ℕ, 0 < m → ∃ N : ModuleCat.{0} A, Module.Finite A N ∧ + ((2*m-2 : ℕ) : WithBot ℕ∞) ≤ projectiveDimension N ∧ + projectiveDimension N < ⊤ := by + sorry + +end Main + +end LittleFinitistic + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LittleFinitistic.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LittleFinitistic.Main.exists_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/little-finitistic/solution/closure.txt b/tasks/little-finitistic/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c25f01e33267394314d80f5f5f9c4ffd735e6cec --- /dev/null +++ b/tasks/little-finitistic/solution/closure.txt @@ -0,0 +1,546 @@ +OAI.Algebra.Finitistic.Bar.Balanced +OAI.Algebra.Finitistic.Bar.BalancedTensorFunctor +OAI.Algebra.Finitistic.Bar.Bar +OAI.Algebra.Finitistic.Bar.BarAdditive +OAI.Algebra.Finitistic.Bar.BarBimoduleCongruence +OAI.Algebra.Finitistic.Bar.BarCoordinateNaturality +OAI.Algebra.Finitistic.Bar.BarFunctor +OAI.Algebra.Finitistic.Bar.BarPatternEmbedding +OAI.Algebra.Finitistic.Bar.BlockCoordinateGenerators +OAI.Algebra.Finitistic.Bar.BlockIndexEquiv +OAI.Algebra.Finitistic.Bar.ChainSplitting +OAI.Algebra.Finitistic.Bar.CoproductHomBijections +OAI.Algebra.Finitistic.Bar.CoproductHomotopy +OAI.Algebra.Finitistic.Bar.CountHomologyDetection +OAI.Algebra.Finitistic.Bar.CountProjective +OAI.Algebra.Finitistic.Bar.CountRetracts +OAI.Algebra.Finitistic.Bar.CountTorBounds +OAI.Algebra.Finitistic.Bar.DerivedBarCoproduct +OAI.Algebra.Finitistic.Bar.DerivedCountCoproduct +OAI.Algebra.Finitistic.Bar.DerivedCountShift +OAI.Algebra.Finitistic.Bar.DerivedTensorBarSplitting +OAI.Algebra.Finitistic.Bar.DirectSumCoproduct +OAI.Algebra.Finitistic.Bar.DirectSumExactness +OAI.Algebra.Finitistic.Bar.ExplicitSignedDifferential +OAI.Algebra.Finitistic.Bar.ExtensionColimits +OAI.Algebra.Finitistic.Bar.FiniteBarResolution +OAI.Algebra.Finitistic.Bar.FiniteSumSupport +OAI.Algebra.Finitistic.Bar.FlatSupportedAssembly +OAI.Algebra.Finitistic.Bar.GlobalIndexedComparison +OAI.Algebra.Finitistic.Bar.IndexedAssemblyComparison +OAI.Algebra.Finitistic.Bar.IndexedMultibarTotal +OAI.Algebra.Finitistic.Bar.IndexedPatternEmbedding +OAI.Algebra.Finitistic.Bar.InflatedParityFaces +OAI.Algebra.Finitistic.Bar.IntegerCountObject +OAI.Algebra.Finitistic.Bar.IntegerCountRestriction +OAI.Algebra.Finitistic.Bar.IntegerCountShift +OAI.Algebra.Finitistic.Bar.IntegerDerivedMultibar +OAI.Algebra.Finitistic.Bar.IntegerStalk +OAI.Algebra.Finitistic.Bar.KProjectiveCoproduct +OAI.Algebra.Finitistic.Bar.LeadingBarSuffix +OAI.Algebra.Finitistic.Bar.LeadingSuffixFaces +OAI.Algebra.Finitistic.Bar.LeadingSupportedComparison +OAI.Algebra.Finitistic.Bar.LeadingTotalComparison +OAI.Algebra.Finitistic.Bar.LeadingTotalDifferential +OAI.Algebra.Finitistic.Bar.LeadingTotalEmbedding +OAI.Algebra.Finitistic.Bar.LiteralMultibarCoordinates +OAI.Algebra.Finitistic.Bar.ModuleBlockIndex +OAI.Algebra.Finitistic.Bar.ModuleMultibarCoordinates +OAI.Algebra.Finitistic.Bar.MultibarBlocks +OAI.Algebra.Finitistic.Bar.MultibarDecomposition +OAI.Algebra.Finitistic.Bar.MultibarFlattenDerived +OAI.Algebra.Finitistic.Bar.MultibarIndex +OAI.Algebra.Finitistic.Bar.MultibarSigns +OAI.Algebra.Finitistic.Bar.PatternPrefixCoordinates +OAI.Algebra.Finitistic.Bar.PatternSuffixFaces +OAI.Algebra.Finitistic.Bar.PatternTensorCoherence +OAI.Algebra.Finitistic.Bar.Projection +OAI.Algebra.Finitistic.Bar.ProjectiveTail +OAI.Algebra.Finitistic.Bar.RecursiveBlockIndex +OAI.Algebra.Finitistic.Bar.RecursivePrefixInclusions +OAI.Algebra.Finitistic.Bar.RecursiveSuffixCoefficient +OAI.Algebra.Finitistic.Bar.RecursiveSuffixDifferential +OAI.Algebra.Finitistic.Bar.RecursiveSuffixEmbedding +OAI.Algebra.Finitistic.Bar.RecursiveSuffixFaces +OAI.Algebra.Finitistic.Bar.RecursiveSuffixInduction +OAI.Algebra.Finitistic.Bar.RecursiveSuffixSums +OAI.Algebra.Finitistic.Bar.RecursiveSuffixTotal +OAI.Algebra.Finitistic.Bar.RecursiveTotalDifferential +OAI.Algebra.Finitistic.Bar.RecursiveTotalFlatten +OAI.Algebra.Finitistic.Bar.ResolutionDerived +OAI.Algebra.Finitistic.Bar.SignedBlockExplicit +OAI.Algebra.Finitistic.Bar.SignedBlockModel +OAI.Algebra.Finitistic.Bar.SplitProjectiveTail +OAI.Algebra.Finitistic.Bar.Splitting +OAI.Algebra.Finitistic.Bar.StrictSupportExtension +OAI.Algebra.Finitistic.Bar.SuffixNaturality +OAI.Algebra.Finitistic.Bar.SuffixParityFaces +OAI.Algebra.Finitistic.Bar.SupportedInnerCoordinates +OAI.Algebra.Finitistic.Bar.SupportedOuterCoordinates +OAI.Algebra.Finitistic.Bar.TensorModel +OAI.Algebra.Finitistic.Bar.TotalAdditive +OAI.Algebra.Finitistic.Bar.TotalBar +OAI.Algebra.Finitistic.Bar.TotalBarComparison +OAI.Algebra.Finitistic.Bar.TotalBarContraction +OAI.Algebra.Finitistic.Bar.TotalBarDerived +OAI.Algebra.Finitistic.Bar.TotalBarFunctor +OAI.Algebra.Finitistic.Bar.TotalBarResolution +OAI.Algebra.Finitistic.Bar.TotalBarTensor +OAI.Algebra.Finitistic.Bar.TotalMap +OAI.Algebra.Finitistic.Bar.TwoSided +OAI.Algebra.Finitistic.Bar.TwoSidedBarFunctor +OAI.Algebra.Finitistic.Bar.TwoSidedWeight +OAI.Algebra.Finitistic.Bar.Weight +OAI.Algebra.Finitistic.Basic +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentationEpi +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentationQuasiIso +OAI.Algebra.Finitistic.Bimodule.BimoduleAugmentedResolution +OAI.Algebra.Finitistic.Bimodule.BimoduleBalancedTensor +OAI.Algebra.Finitistic.Bimodule.BimoduleBar +OAI.Algebra.Finitistic.Bimodule.BimoduleBarComparisonIso +OAI.Algebra.Finitistic.Bimodule.BimoduleBarComparisonMap +OAI.Algebra.Finitistic.Bimodule.BimoduleBarIteration +OAI.Algebra.Finitistic.Bimodule.BimoduleBarResolution +OAI.Algebra.Finitistic.Bimodule.BimoduleBarStalk +OAI.Algebra.Finitistic.Bimodule.BimoduleBarTensorComparison +OAI.Algebra.Finitistic.Bimodule.BimoduleBoundedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleComparison +OAI.Algebra.Finitistic.Bimodule.BimoduleDerived +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedInterval +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleDerivedShift +OAI.Algebra.Finitistic.Bimodule.BimoduleExactRows +OAI.Algebra.Finitistic.Bimodule.BimoduleFiniteRowsAcyclic +OAI.Algebra.Finitistic.Bimodule.BimoduleInputFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleInputNaturality +OAI.Algebra.Finitistic.Bimodule.BimoduleLeftNaturality +OAI.Algebra.Finitistic.Bimodule.BimoduleLeftTotalMap +OAI.Algebra.Finitistic.Bimodule.BimoduleResolutionBarAPI +OAI.Algebra.Finitistic.Bimodule.BimoduleScalarEvaluation +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftCoherence +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftColumns +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftHorizontal +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftTotal +OAI.Algebra.Finitistic.Bimodule.BimoduleShiftedPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleDifferential +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleEvaluation +OAI.Algebra.Finitistic.Bimodule.BimoduleSingleTerms +OAI.Algebra.Finitistic.Bimodule.BimoduleStalkTotal +OAI.Algebra.Finitistic.Bimodule.BimoduleTensor +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorAcross +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorUnderlying +OAI.Algebra.Finitistic.Bimodule.BimoduleTensorVertexBridge +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalCoefficient +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalDifferential +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalFunctor +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalInsertion +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalPresentation +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalShortExact +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalTermMaps +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalTerms +OAI.Algebra.Finitistic.Bimodule.BimoduleTotalUnderlying +OAI.Algebra.Finitistic.Bimodule.BimoduleVertex +OAI.Algebra.Finitistic.Bimodule.BoundedBimoduleDerived +OAI.Algebra.Finitistic.Dimension.PDAllSimples +OAI.Algebra.Finitistic.Dimension.PDBalancedRight +OAI.Algebra.Finitistic.Dimension.PDBarDetection +OAI.Algebra.Finitistic.Dimension.PDBarQuotient +OAI.Algebra.Finitistic.Dimension.PDBarQuotientAction +OAI.Algebra.Finitistic.Dimension.PDBarTensorComparison +OAI.Algebra.Finitistic.Dimension.PDBaseBarConsumer +OAI.Algebra.Finitistic.Dimension.PDCoverRadical +OAI.Algebra.Finitistic.Dimension.PDCovers +OAI.Algebra.Finitistic.Dimension.PDDerivedBarConsumer +OAI.Algebra.Finitistic.Dimension.PDDetection +OAI.Algebra.Finitistic.Dimension.PDDimension +OAI.Algebra.Finitistic.Dimension.PDLowerBound +OAI.Algebra.Finitistic.Dimension.PDMinimalData +OAI.Algebra.Finitistic.Dimension.PDMinimalResolution +OAI.Algebra.Finitistic.Dimension.PDRadical +OAI.Algebra.Finitistic.Dimension.PDResidueAssociativity +OAI.Algebra.Finitistic.Dimension.PDResidueBaseBar +OAI.Algebra.Finitistic.Dimension.PDResidueProjection +OAI.Algebra.Finitistic.Dimension.PDResidueRing +OAI.Algebra.Finitistic.Dimension.PDResidueScalar +OAI.Algebra.Finitistic.Dimension.PDResidueSemisimple +OAI.Algebra.Finitistic.Dimension.PDResidueTensor +OAI.Algebra.Finitistic.Dimension.PDResolutionDetection +OAI.Algebra.Finitistic.Dimension.PDSimpleTensor +OAI.Algebra.Finitistic.Dimension.PDSquareZero +OAI.Algebra.Finitistic.Dimension.PDSquareZeroResidue +OAI.Algebra.Finitistic.Dimension.PDTensorFunctor +OAI.Algebra.Finitistic.Dimension.PDTor +OAI.Algebra.Finitistic.Encoding.ArrowBasisIso +OAI.Algebra.Finitistic.Encoding.AuxiliaryQuadraticPresentation +OAI.Algebra.Finitistic.Encoding.DirectedBound +OAI.Algebra.Finitistic.Encoding.EncodingGenerators +OAI.Algebra.Finitistic.Encoding.EncodingLinearity +OAI.Algebra.Finitistic.Encoding.EncodingModuleAssembly +OAI.Algebra.Finitistic.Encoding.FiniteBasisIso +OAI.Algebra.Finitistic.Encoding.PathBasisIso +OAI.Algebra.Finitistic.Encoding.PresentationReindex +OAI.Algebra.Finitistic.Encoding.QuadraticCoefficients +OAI.Algebra.Finitistic.Encoding.QuadraticEncoding +OAI.Algebra.Finitistic.Encoding.QuadraticPresentation +OAI.Algebra.Finitistic.Encoding.RelationBasisAction +OAI.Algebra.Finitistic.Encoding.RelationBasisCoefficients +OAI.Algebra.Finitistic.Encoding.RelationMatrixSequence +OAI.Algebra.Finitistic.Encoding.RelationPathCoordinates +OAI.Algebra.Finitistic.Encoding.RelationSequence +OAI.Algebra.Finitistic.Encoding.RelationVertexCoordinates +OAI.Algebra.Finitistic.Encoding.RelationVertexSequence +OAI.Algebra.Finitistic.Encoding.ThreeVertexAlgebra +OAI.Algebra.Finitistic.Iteration.AdditiveIterateAmplitude +OAI.Algebra.Finitistic.Iteration.BinomialBiproduct +OAI.Algebra.Finitistic.Iteration.BinomialEvenIteration +OAI.Algebra.Finitistic.Iteration.BinomialIndex +OAI.Algebra.Finitistic.Iteration.BinomialIteration +OAI.Algebra.Finitistic.Iteration.BinomialVanishing +OAI.Algebra.Finitistic.Iteration.FiniteIntegerIterate +OAI.Algebra.Finitistic.Iteration.FunctorObjectIteration +OAI.Algebra.Finitistic.Iteration.IntegerIterateAmplitude +OAI.Algebra.Finitistic.Iteration.IntegerIterateExtinction +OAI.Algebra.Finitistic.Iteration.IntegerIterateSupport +OAI.Algebra.Finitistic.Iteration.ObjectwiseSplitting +OAI.Algebra.Finitistic.Localization.AdditiveSplitImage +OAI.Algebra.Finitistic.Localization.AmbientQuotientEvaluation +OAI.Algebra.Finitistic.Localization.BoundedDerivedEmbedding +OAI.Algebra.Finitistic.Localization.BoundedHomotopy +OAI.Algebra.Finitistic.Localization.BoundedQuotientEvaluation +OAI.Algebra.Finitistic.Localization.BoundedQuotientGenerators +OAI.Algebra.Finitistic.Localization.BoundedRepresentatives +OAI.Algebra.Finitistic.Localization.ChainRepresentatives +OAI.Algebra.Finitistic.Localization.CompletedCornerEvaluation +OAI.Algebra.Finitistic.Localization.CompletedDerivedEvaluation +OAI.Algebra.Finitistic.Localization.CompletedImageEvaluation +OAI.Algebra.Finitistic.Localization.CompletedOddDoubleEvaluation +OAI.Algebra.Finitistic.Localization.CompletedShiftEvaluation +OAI.Algebra.Finitistic.Localization.CompletedShiftedCornerEvaluation +OAI.Algebra.Finitistic.Localization.ConcreteChainRepresentatives +OAI.Algebra.Finitistic.Localization.ConcreteFixedDiagram +OAI.Algebra.Finitistic.Localization.ConcreteQuadraticDiagram +OAI.Algebra.Finitistic.Localization.ConcreteTensorEvaluation +OAI.Algebra.Finitistic.Localization.DerivedActionCompatibility +OAI.Algebra.Finitistic.Localization.DerivedTruncationCohomology +OAI.Algebra.Finitistic.Localization.DiagramEvaluationSquares +OAI.Algebra.Finitistic.Localization.DiagramLifting +OAI.Algebra.Finitistic.Localization.EvaluationFromAlgebra +OAI.Algebra.Finitistic.Localization.EvaluationLinear +OAI.Algebra.Finitistic.Localization.EvaluationModule +OAI.Algebra.Finitistic.Localization.EvaluationVertexDiagram +OAI.Algebra.Finitistic.Localization.FiniteDerivedEvaluation +OAI.Algebra.Finitistic.Localization.FiniteEvaluationTarget +OAI.Algebra.Finitistic.Localization.FiniteProjectiveHomotopy +OAI.Algebra.Finitistic.Localization.FiniteSumTransport +OAI.Algebra.Finitistic.Localization.FiniteSupportReindex +OAI.Algebra.Finitistic.Localization.FixedDiagram +OAI.Algebra.Finitistic.Localization.FormalSummandAction +OAI.Algebra.Finitistic.Localization.HomotopyEvaluation +OAI.Algebra.Finitistic.Localization.HomotopyVertexEvaluation +OAI.Algebra.Finitistic.Localization.IdempotentImageEvaluation +OAI.Algebra.Finitistic.Localization.IntegerExtensionFunctor +OAI.Algebra.Finitistic.Localization.KaroubiEvaluation +OAI.Algebra.Finitistic.Localization.LocalizedEvaluationStructure +OAI.Algebra.Finitistic.Localization.ModuleActionCompatibility +OAI.Algebra.Finitistic.Localization.NativeArrowBridge +OAI.Algebra.Finitistic.Localization.NativeBoundedDerived +OAI.Algebra.Finitistic.Localization.NativeProjectiveModel +OAI.Algebra.Finitistic.Localization.NativeSingleEvaluation +OAI.Algebra.Finitistic.Localization.NormalizedQuotientAction +OAI.Algebra.Finitistic.Localization.OddDouble +OAI.Algebra.Finitistic.Localization.PresentedActionCompatibility +OAI.Algebra.Finitistic.Localization.PresentedQuotientAction +OAI.Algebra.Finitistic.Localization.ProjectiveComplexes +OAI.Algebra.Finitistic.Localization.QuotientAction +OAI.Algebra.Finitistic.Localization.QuotientActionEvaluation +OAI.Algebra.Finitistic.Localization.QuotientRelations +OAI.Algebra.Finitistic.Localization.SignedCochainShift +OAI.Algebra.Finitistic.Localization.SingleDegreeNaturality +OAI.Algebra.Finitistic.Localization.SourceActionEvaluation +OAI.Algebra.Finitistic.Localization.SourceCornerEvaluation +OAI.Algebra.Finitistic.Localization.SourceEvaluation +OAI.Algebra.Finitistic.Localization.SourceImageEvaluation +OAI.Algebra.Finitistic.Localization.SourceLinear +OAI.Algebra.Finitistic.Localization.SourceModelBridge +OAI.Algebra.Finitistic.Localization.SourceOddDoubleEvaluation +OAI.Algebra.Finitistic.Localization.SourceQuotientAction +OAI.Algebra.Finitistic.Localization.SourceShiftLinear +OAI.Algebra.Finitistic.Localization.SourceVerdier +OAI.Algebra.Finitistic.Localization.SplitComponentExact +OAI.Algebra.Finitistic.Localization.TensorCohomologyDiagram +OAI.Algebra.Finitistic.Localization.TensorEvaluationComparison +OAI.Algebra.Finitistic.Localization.TensorEvaluationFunctor +OAI.Algebra.Finitistic.Localization.ThickEvaluation +OAI.Algebra.Finitistic.Localization.TruncationSplitNaturality +OAI.Algebra.Finitistic.Localization.TruncationStalkNaturality +OAI.Algebra.Finitistic.Localization.TwoConeVerdier +OAI.Algebra.Finitistic.Localization.TwoDegreeExtVanishing +OAI.Algebra.Finitistic.Localization.TwoDegreeFormalityNaturality +OAI.Algebra.Finitistic.Localization.TwoDegreeSplitting +OAI.Algebra.Finitistic.Localization.UnderlyingRepresentatives +OAI.Algebra.Finitistic.Localization.VectorComplexFormality +OAI.Algebra.Finitistic.Localization.VectorIdempotentCompleteness +OAI.Algebra.Finitistic.Localization.VerdierEvaluationExact +OAI.Algebra.Finitistic.Main +OAI.Algebra.Finitistic.Ordinary.OrdinaryAssociativeTensorModules +OAI.Algebra.Finitistic.Ordinary.OrdinaryAssociativityNaturality +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedActions +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBalancedCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAssociativeTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleAugmentationQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleCoefficientEquiv +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleCoefficients +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleResolutionProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTensorTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalAssociativity +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalForget +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryBimoduleTotalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockComplexes +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockDerived +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockModules +OAI.Algebra.Finitistic.Ordinary.OrdinaryBlockTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainAlgebra +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainDirected +OAI.Algebra.Finitistic.Ordinary.OrdinaryChainResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryCochain +OAI.Algebra.Finitistic.Ordinary.OrdinaryComplexAction +OAI.Algebra.Finitistic.Ordinary.OrdinaryComplexTensorMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryCompression +OAI.Algebra.Finitistic.Ordinary.OrdinaryConeCoordinates +OAI.Algebra.Finitistic.Ordinary.OrdinaryConeQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryDerivedIterates +OAI.Algebra.Finitistic.Ordinary.OrdinaryDerivedSquareComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteColumnComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteConeReindex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteConeTriangular +OAI.Algebra.Finitistic.Ordinary.OrdinaryFinitePiSupport +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryFiniteTotalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstBlockTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstBlockTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstComponentExact +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstDerivedCompatibility +OAI.Algebra.Finitistic.Ordinary.OrdinaryFirstDerivedRetraction +OAI.Algebra.Finitistic.Ordinary.OrdinaryFixedTensorFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFreeTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryFreeTensorExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryFullTensorComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryFullTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinaryFunctorExtension +OAI.Algebra.Finitistic.Ordinary.OrdinaryGenuineBimoduleComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryGlobalDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryIntegerResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryLeftTensorCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryLeftTensorMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryMiddleTensorFunctors +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalComplexMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalForget +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalObjects +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryOffDiagonalSingle +OAI.Algebra.Finitistic.Ordinary.OrdinaryPairComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryPairQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductComponent +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductOpposite +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductProjective +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductSecondDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryProductSplitting +OAI.Algebra.Finitistic.Ordinary.OrdinaryProjectiveTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionExact +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionModels +OAI.Algebra.Finitistic.Ordinary.OrdinaryResolutionQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryRestrictionHomology +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedBimodule +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedCongruence +OAI.Algebra.Finitistic.Ordinary.OrdinaryRetainedRestriction +OAI.Algebra.Finitistic.Ordinary.OrdinaryRightProjective +OAI.Algebra.Finitistic.Ordinary.OrdinarySecondBlockTensor +OAI.Algebra.Finitistic.Ordinary.OrdinarySecondBlockTotal +OAI.Algebra.Finitistic.Ordinary.OrdinaryShiftDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryShiftSign +OAI.Algebra.Finitistic.Ordinary.OrdinarySignedExactness +OAI.Algebra.Finitistic.Ordinary.OrdinarySimulationComparison +OAI.Algebra.Finitistic.Ordinary.OrdinarySingleTensorTerms +OAI.Algebra.Finitistic.Ordinary.OrdinarySingleTensorTotal +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceBimoduleTotal +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceDerivedComparison +OAI.Algebra.Finitistic.Ordinary.OrdinarySourceResolutionModels +OAI.Algebra.Finitistic.Ordinary.OrdinarySupportedExtension +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimap +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimoduleComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorBimoduleResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorColumnAcyclic +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDerivedFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDifferential +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorDirected +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorFiniteMatrix +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorGlobalDimension +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorIdeal +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorIdealActions +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorInputMaps +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorMixedSign +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorResolutionComplex +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorRightRestriction +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalAcyclic +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalFunctor +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorTotalQuasiIso +OAI.Algebra.Finitistic.Ordinary.OrdinaryTensorVertex +OAI.Algebra.Finitistic.Ordinary.OrdinaryTerminal +OAI.Algebra.Finitistic.Ordinary.OrdinaryTerminalResolution +OAI.Algebra.Finitistic.Ordinary.OrdinaryTriangularExactness +OAI.Algebra.Finitistic.Ordinary.OrdinaryTwoSidedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryVertexCompression +OAI.Algebra.Finitistic.Ordinary.OrdinaryXAugmentation +OAI.Algebra.Finitistic.Ordinary.OrdinaryXBlockComparison +OAI.Algebra.Finitistic.Ordinary.OrdinaryXDerivedTensor +OAI.Algebra.Finitistic.Ordinary.OrdinaryXResolution +OAI.Algebra.Finitistic.Rectification.AdjacentArrowSum +OAI.Algebra.Finitistic.Rectification.ArrowCompatibility +OAI.Algebra.Finitistic.Rectification.ArrowVertex +OAI.Algebra.Finitistic.Rectification.BiprodEvaluationSquare +OAI.Algebra.Finitistic.Rectification.CanonicalArrowCompatibility +OAI.Algebra.Finitistic.Rectification.ColumnComplex +OAI.Algebra.Finitistic.Rectification.ColumnFinite +OAI.Algebra.Finitistic.Rectification.ColumnProperties +OAI.Algebra.Finitistic.Rectification.ConcreteAdjacentGraded +OAI.Algebra.Finitistic.Rectification.CornerArrowCoordinates +OAI.Algebra.Finitistic.Rectification.CornerColumnComplex +OAI.Algebra.Finitistic.Rectification.CornerColumnPaths +OAI.Algebra.Finitistic.Rectification.CornerPathTransport +OAI.Algebra.Finitistic.Rectification.CornerProjection +OAI.Algebra.Finitistic.Rectification.CornerSpaces +OAI.Algebra.Finitistic.Rectification.CornerTensor +OAI.Algebra.Finitistic.Rectification.DiagramAssembly +OAI.Algebra.Finitistic.Rectification.ExactProducts +OAI.Algebra.Finitistic.Rectification.ExternalTensor +OAI.Algebra.Finitistic.Rectification.FiltrationExactness +OAI.Algebra.Finitistic.Rectification.FinalGradedAcyclic +OAI.Algebra.Finitistic.Rectification.FirstVertex +OAI.Algebra.Finitistic.Rectification.FullTensorProperties +OAI.Algebra.Finitistic.Rectification.FullTensorRectification +OAI.Algebra.Finitistic.Rectification.GradedVertexAcyclic +OAI.Algebra.Finitistic.Rectification.InducedColumns +OAI.Algebra.Finitistic.Rectification.InducedDerivedFunctor +OAI.Algebra.Finitistic.Rectification.InducedDiagram +OAI.Algebra.Finitistic.Rectification.InducedRectification +OAI.Algebra.Finitistic.Rectification.LeftVertexHomology +OAI.Algebra.Finitistic.Rectification.RectificationAcyclic +OAI.Algebra.Finitistic.Rectification.RectificationLemma +OAI.Algebra.Finitistic.Rectification.RectificationTotal +OAI.Algebra.Finitistic.Rectification.SecondVertex +OAI.Algebra.Finitistic.Rectification.SourceFiltration +OAI.Algebra.Finitistic.Rectification.SourceFiltrationComplex +OAI.Algebra.Finitistic.Rectification.SourceFiltrationCone +OAI.Algebra.Finitistic.Rectification.SourceFiltrationExact +OAI.Algebra.Finitistic.Rectification.SourceFiltrationReal +OAI.Algebra.Finitistic.Rectification.TensorArrowComparison +OAI.Algebra.Finitistic.Rectification.TensorArrowSum +OAI.Algebra.Finitistic.Rectification.TensorComplex +OAI.Algebra.Finitistic.Rectification.TensorProjection +OAI.Algebra.Finitistic.Rectification.ThirdVertex +OAI.Algebra.Finitistic.Rectification.ThirdVertexFiltration +OAI.Algebra.Finitistic.Rectification.TotalExact +OAI.Algebra.Finitistic.Rectification.TotalFinite +OAI.Algebra.Finitistic.Rectification.TotalFunctorial +OAI.Algebra.Finitistic.Rectification.TotalInterchange +OAI.Algebra.Finitistic.Rectification.VertexCategoricalAssembly +OAI.Algebra.Finitistic.Rectification.VertexColumnComplex +OAI.Algebra.Finitistic.Rectification.VertexColumnModels +OAI.Algebra.Finitistic.Rectification.VertexDecomposition +OAI.Algebra.Finitistic.Rectification.VertexFunctor +OAI.Algebra.Finitistic.Rectification.VertexHomology +OAI.Algebra.Finitistic.Rectification.VertexHomotopyEquivalence +OAI.Algebra.Finitistic.Rectification.VertexModuleAssembly +OAI.Algebra.Finitistic.Rectification.VertexProjectives +OAI.Algebra.Finitistic.Rectification.VertexTensorEvaluation +OAI.Algebra.Finitistic.Rectification.VertexTensorLinear +OAI.Algebra.Finitistic.Rectification.VertexTotalProperties +OAI.Algebra.Finitistic.Rectification.VertexZeroTotal +OAI.Algebra.Finitistic.Rectification.ZeroColumnTotal +OAI.Algebra.Finitistic.Rectification.ZeroLastColumn +OAI.Algebra.Finitistic.Selected.SelectedBarBimodule +OAI.Algebra.Finitistic.Selected.SelectedBarComparison +OAI.Algebra.Finitistic.Selected.SelectedBarPowers +OAI.Algebra.Finitistic.Selected.SelectedBarResolution +OAI.Algebra.Finitistic.Selected.SelectedBarStart +OAI.Algebra.Finitistic.Selected.SelectedBaseIterates +OAI.Algebra.Finitistic.Selected.SelectedChainAction +OAI.Algebra.Finitistic.Selected.SelectedChainDiagram +OAI.Algebra.Finitistic.Selected.SelectedChainHomology +OAI.Algebra.Finitistic.Selected.SelectedCohomologyAssembly +OAI.Algebra.Finitistic.Selected.SelectedCohomologyVanishing +OAI.Algebra.Finitistic.Selected.SelectedCountCohomology +OAI.Algebra.Finitistic.Selected.SelectedCountExtinction +OAI.Algebra.Finitistic.Selected.SelectedCountPDConsumer +OAI.Algebra.Finitistic.Selected.SelectedDerivedFunctor +OAI.Algebra.Finitistic.Selected.SelectedDiagramEvaluation +OAI.Algebra.Finitistic.Selected.SelectedFiniteAmplitude +OAI.Algebra.Finitistic.Selected.SelectedFiniteTensorEvaluation +OAI.Algebra.Finitistic.Selected.SelectedFirstBlockFamily +OAI.Algebra.Finitistic.Selected.SelectedFixedDiagram +OAI.Algebra.Finitistic.Selected.SelectedImageComparison +OAI.Algebra.Finitistic.Selected.SelectedIteration +OAI.Algebra.Finitistic.Selected.SelectedMinimalResolution +OAI.Algebra.Finitistic.Selected.SelectedNativeAction +OAI.Algebra.Finitistic.Selected.SelectedNativeEvaluation +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryAlgebra +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryDimension +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryModules +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryOrbit +OAI.Algebra.Finitistic.Selected.SelectedOrdinaryResolution +OAI.Algebra.Finitistic.Selected.SelectedPDBarConsumer +OAI.Algebra.Finitistic.Selected.SelectedPDConclusion +OAI.Algebra.Finitistic.Selected.SelectedPDDetection +OAI.Algebra.Finitistic.Selected.SelectedPDResidueProjection +OAI.Algebra.Finitistic.Selected.SelectedPDUpperConsumer +OAI.Algebra.Finitistic.Selected.SelectedRealization +OAI.Algebra.Finitistic.Selected.SelectedRectification +OAI.Algebra.Finitistic.Selected.SelectedReferenceCohomology +OAI.Algebra.Finitistic.Selected.SelectedShiftedRealization +OAI.Algebra.Finitistic.Selected.SelectedTargetHomology +OAI.Algebra.Finitistic.Selected.SelectedTensor +OAI.Algebra.Finitistic.Selected.SelectedTensorComparison +OAI.Algebra.Finitistic.Selected.SelectedTensorSplitting +OAI.Algebra.Finitistic.Selected.SelectedUnderlyingHomology +OAI.Algebra.Finitistic.Selected.SelectedVertexTensorEvaluation +OAI.Algebra.Finitistic.Selected.SelectedWindow +OAI.Algebra.Finitistic.Selection.AuxiliaryGroupAlgebraPresentation +OAI.Algebra.Finitistic.Selection.CharacterModule +OAI.Algebra.Finitistic.Selection.FinitePresentation +OAI.Algebra.Finitistic.Selection.FiniteQuotient +OAI.Algebra.Finitistic.Selection.FiniteSelectionFamily +OAI.Algebra.Finitistic.Selection.GroupAlgebraPresentation +OAI.Algebra.Finitistic.Selection.GroupSelection +OAI.Algebra.Finitistic.Selection.MatrixModel +OAI.Algebra.Finitistic.Selection.SelectionAlgebra +OAI.Algebra.Finitistic.Selection.SelectionCharacter +OAI.Algebra.Finitistic.Selection.SelectionEncoding +OAI.Algebra.Finitistic.Selection.SelectionIteration +OAI.Algebra.Finitistic.Selection.TestModules +OAI.Algebra.Finitistic.Tensor.BalancedFreeLeft +OAI.Algebra.Finitistic.Tensor.BalancedProjectiveLeft +OAI.Algebra.Finitistic.Tensor.BalancedTensor +OAI.Algebra.Finitistic.Tensor.BalancedTensorMaps +OAI.Algebra.Finitistic.Tensor.BalancedVertexFunctor +OAI.Algebra.Finitistic.Tensor.BalancedVertexImage +OAI.Algebra.Finitistic.Tensor.IdempotentTensor +OAI.Algebra.Finitistic.Tensor.IdempotentTensorMaps diff --git a/tasks/little-finitistic/solution/reference.py b/tasks/little-finitistic/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/little-finitistic/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/little-finitistic/solution/solve.sh b/tasks/little-finitistic/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d3178b170aa1c7c5c7217692c828133314ba10a8 --- /dev/null +++ b/tasks/little-finitistic/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LittleFinitistic, i.e. module OAI.Algebra.Finitistic.Main and the +# 546 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.Finitistic.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LittleFinitistic" diff --git a/tasks/little-finitistic/task.toml b/tasks/little-finitistic/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f25c23db87a02d65e2d65f45af516df5ec2ccc4d --- /dev/null +++ b/tasks/little-finitistic/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/little-finitistic" +version = "1.0.0" +description = "Prove LittleFinitistic (openai/math family 198: A counterexample to the little finitistic-dimension conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LittleFinitistic.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LittleFinitistic" +family = "198" +family_title = "A counterexample to the little finitistic-dimension conjecture" +subject = "Algebra" +theorems = ["OAI.LittleFinitistic.Main.exists_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.Finitistic.Main" +reference_modules = 546 +reference_lean_bytes = 2050368 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1694 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13545 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/little-finitistic/tests/Challenge.lean b/tasks/little-finitistic/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d9cff5c1fd669aa3e691750554e7427e0e2da46 --- /dev/null +++ b/tasks/little-finitistic/tests/Challenge.lean @@ -0,0 +1,37 @@ +import Mathlib.Algebra.Category.ModuleCat.Abelian +import Mathlib.CategoryTheory.Abelian.Projective.Dimension +import Mathlib.Basic.Complex.Basic +import Mathlib.LinearAlgebra.FiniteDimensional.Defs +import Mathlib.RingTheory.Finiteness.Defs + +namespace OAI + +noncomputable section + +open CategoryTheory + +namespace LittleFinitistic + +universe u + +def littleFinitisticDimension (A : Type u) [Ring A] : WithBot ℕ∞ := + ⨆ (M : ModuleCat.{u} A) (_ : Module.Finite A M) (_ : projectiveDimension M < ⊤), + projectiveDimension M + +namespace Main + +theorem exists_counterexample : + ∃ (A : Type) (_ : Ring A) (_ : Algebra ℂ A), + FiniteDimensional ℂ A ∧ littleFinitisticDimension A = ⊤ ∧ + ∀ m : ℕ, 0 < m → ∃ N : ModuleCat.{0} A, Module.Finite A N ∧ + ((2*m-2 : ℕ) : WithBot ℕ∞) ≤ projectiveDimension N ∧ + projectiveDimension N < ⊤ := by + sorry + +end Main + +end LittleFinitistic + +end + +end OAI diff --git a/tasks/little-finitistic/tests/grade.py b/tasks/little-finitistic/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/little-finitistic/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/little-finitistic/tests/task.json b/tasks/little-finitistic/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fe58430beb5365e21913dc4c1c32eeee83c67832 --- /dev/null +++ b/tasks/little-finitistic/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LittleFinitistic", + "comparator": { + "theorem_names": [ + "OAI.LittleFinitistic.Main.exists_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12645 +} \ No newline at end of file diff --git a/tasks/little-finitistic/tests/test.sh b/tasks/little-finitistic/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/little-finitistic/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/littlewood-finite-flatness/environment/Dockerfile b/tasks/littlewood-finite-flatness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/littlewood-finite-flatness/environment/fetch_mathlib.sh b/tasks/littlewood-finite-flatness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/littlewood-finite-flatness/environment/lake-manifest.json b/tasks/littlewood-finite-flatness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/littlewood-finite-flatness/environment/lakefile.lean b/tasks/littlewood-finite-flatness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/littlewood-finite-flatness/environment/lean_setup.sh b/tasks/littlewood-finite-flatness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/littlewood-finite-flatness/environment/pack_submission.py b/tasks/littlewood-finite-flatness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/littlewood-finite-flatness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/littlewood-finite-flatness/instruction.md b/tasks/littlewood-finite-flatness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..abda124860e9230f9a09e321c25af558142702ab --- /dev/null +++ b/tasks/littlewood-finite-flatness/instruction.md @@ -0,0 +1,92 @@ +# openai/math challenge `LittlewoodFiniteFlatness` (family 076) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 076 of the release, *Ultraflat real Littlewood polynomials* +(Real and complex analysis). The family as a whole: Constructs polynomials with $N$ consecutive coefficients in $\{-1,1\}$ whose modulus is $(1+o(1))\sqrt N$ uniformly on the entire unit circle, for every sufficiently large integer length $N$. Thus real Littlewood polynomials are ultraflat, including at the real endpoints. Their binary merit factors tend to infinity, disproving Turyn's bounded-merit-factor conjecture. + +The challenge is `LittlewoodFiniteFlatness`, also at `/opt/openai-math/challenges/LittlewoodFiniteFlatness.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Filter Complex +open scoped BigOperators Topology ComplexConjugate + +namespace AsymptoticallyMinimalLittlewoodFiniteFlatness + +/-- The consecutive-degree polynomial of a real coefficient family. -/ +def littlewoodValue {N : ℕ} (ε : Fin N → ℝ) (z : ℂ) : ℂ := + ∑ k : Fin N, (ε k : ℂ) * z ^ (k : ℕ) + +/-- Every coefficient is a real sign. -/ +def IsRealSigning {N : ℕ} (ε : Fin N → ℝ) : Prop := + ∀ k, ε k = -1 ∨ ε k = 1 + +def MainStatement : Prop := + ∃ ε : (N : ℕ) → Fin N → ℝ, + (∀ N : ℕ, IsRealSigning (ε N)) ∧ + ∀ p : ℝ, 0 < p → + Filter.Tendsto + (fun N : ℕ => + ∫ t : UnitAddCircle, + Real.rpow + |‖littlewoodValue (ε N) (fourier (1 : ℤ) t)‖ / + Real.sqrt (N : ℝ) - 1| + p + ∂AddCircle.haarAddCircle) + Filter.atTop (𝓝 (0 : ℝ)) + +/-- One all-length real-sign family for every finite positive real exponent. -/ +theorem main : MainStatement := by + sorry + +end AsymptoticallyMinimalLittlewoodFiniteFlatness + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LittlewoodFiniteFlatness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AsymptoticallyMinimalLittlewoodFiniteFlatness.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/littlewood-finite-flatness/solution/closure.txt b/tasks/littlewood-finite-flatness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fb2dca269a2fd09acfb656646e3bcc52eae5fdc9 --- /dev/null +++ b/tasks/littlewood-finite-flatness/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.Analysis.Littlewood.AlmostSign +OAI.Analysis.Littlewood.Averages +OAI.Analysis.Littlewood.BinaryPacket +OAI.Analysis.Littlewood.BlockSampling +OAI.Analysis.Littlewood.Chunks +OAI.Analysis.Littlewood.Curvature +OAI.Analysis.Littlewood.Cutoff +OAI.Analysis.Littlewood.DependentMoments +OAI.Analysis.Littlewood.FiniteFlatness +OAI.Analysis.Littlewood.FiniteRank +OAI.Analysis.Littlewood.FlatnessModel +OAI.Analysis.Littlewood.Gaussian +OAI.Analysis.Littlewood.IntervalPacking +OAI.Analysis.Littlewood.Main +OAI.Analysis.Littlewood.Matching +OAI.Analysis.Littlewood.MinimizingFamily +OAI.Analysis.Littlewood.ModeSampling +OAI.Analysis.Littlewood.Model +OAI.Analysis.Littlewood.Nibble +OAI.Analysis.Littlewood.ProductProbability +OAI.Analysis.Littlewood.QuadraticTail +OAI.Analysis.Littlewood.Rounding +OAI.Analysis.Littlewood.SamplingEnergy +OAI.Analysis.Littlewood.SamplingTail +OAI.Analysis.Littlewood.SlotGraph +OAI.Analysis.Littlewood.SlotParameters +OAI.Analysis.Littlewood.Spreading +OAI.MeasureTheory.Integral.BoundedMoments diff --git a/tasks/littlewood-finite-flatness/solution/reference.py b/tasks/littlewood-finite-flatness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/littlewood-finite-flatness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/littlewood-finite-flatness/solution/solve.sh b/tasks/littlewood-finite-flatness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e39b4f915e0b86e217405c805dc3592153d6a16 --- /dev/null +++ b/tasks/littlewood-finite-flatness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LittlewoodFiniteFlatness, i.e. module OAI.Analysis.Littlewood.FiniteFlatness and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Littlewood.FiniteFlatness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LittlewoodFiniteFlatness" diff --git a/tasks/littlewood-finite-flatness/task.toml b/tasks/littlewood-finite-flatness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e9cc4cfa51d20a4018a4912edb11861caaa33c2b --- /dev/null +++ b/tasks/littlewood-finite-flatness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/littlewood-finite-flatness" +version = "1.0.0" +description = "Prove LittlewoodFiniteFlatness (openai/math family 076: Ultraflat real Littlewood polynomials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LittlewoodFiniteFlatness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LittlewoodFiniteFlatness" +family = "076" +family_title = "Ultraflat real Littlewood polynomials" +subject = "Real and complex analysis" +theorems = ["OAI.AsymptoticallyMinimalLittlewoodFiniteFlatness.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Littlewood.FiniteFlatness" +reference_modules = 28 +reference_lean_bytes = 449707 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 855 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12104 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/littlewood-finite-flatness/tests/Challenge.lean b/tasks/littlewood-finite-flatness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..227cea052a4418099425ed51ccb79e44ae0c891c --- /dev/null +++ b/tasks/littlewood-finite-flatness/tests/Challenge.lean @@ -0,0 +1,41 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Filter Complex +open scoped BigOperators Topology ComplexConjugate + +namespace AsymptoticallyMinimalLittlewoodFiniteFlatness + +/-- The consecutive-degree polynomial of a real coefficient family. -/ +def littlewoodValue {N : ℕ} (ε : Fin N → ℝ) (z : ℂ) : ℂ := + ∑ k : Fin N, (ε k : ℂ) * z ^ (k : ℕ) + +/-- Every coefficient is a real sign. -/ +def IsRealSigning {N : ℕ} (ε : Fin N → ℝ) : Prop := + ∀ k, ε k = -1 ∨ ε k = 1 + +def MainStatement : Prop := + ∃ ε : (N : ℕ) → Fin N → ℝ, + (∀ N : ℕ, IsRealSigning (ε N)) ∧ + ∀ p : ℝ, 0 < p → + Filter.Tendsto + (fun N : ℕ => + ∫ t : UnitAddCircle, + Real.rpow + |‖littlewoodValue (ε N) (fourier (1 : ℤ) t)‖ / + Real.sqrt (N : ℝ) - 1| + p + ∂AddCircle.haarAddCircle) + Filter.atTop (𝓝 (0 : ℝ)) + +/-- One all-length real-sign family for every finite positive real exponent. -/ +theorem main : MainStatement := by + sorry + +end AsymptoticallyMinimalLittlewoodFiniteFlatness + +end + +end OAI diff --git a/tasks/littlewood-finite-flatness/tests/grade.py b/tasks/littlewood-finite-flatness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/littlewood-finite-flatness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/littlewood-finite-flatness/tests/task.json b/tasks/littlewood-finite-flatness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4e57223924827978bfb1f98afe5e9cbec95d2414 --- /dev/null +++ b/tasks/littlewood-finite-flatness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LittlewoodFiniteFlatness", + "comparator": { + "theorem_names": [ + "OAI.AsymptoticallyMinimalLittlewoodFiniteFlatness.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11204 +} \ No newline at end of file diff --git a/tasks/littlewood-finite-flatness/tests/test.sh b/tasks/littlewood-finite-flatness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/littlewood-finite-flatness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/log-brunn-minkowski/environment/Dockerfile b/tasks/log-brunn-minkowski/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/log-brunn-minkowski/environment/fetch_mathlib.sh b/tasks/log-brunn-minkowski/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/log-brunn-minkowski/environment/lake-manifest.json b/tasks/log-brunn-minkowski/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/log-brunn-minkowski/environment/lakefile.lean b/tasks/log-brunn-minkowski/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/log-brunn-minkowski/environment/lean_setup.sh b/tasks/log-brunn-minkowski/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/log-brunn-minkowski/environment/pack_submission.py b/tasks/log-brunn-minkowski/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/log-brunn-minkowski/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/log-brunn-minkowski/instruction.md b/tasks/log-brunn-minkowski/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2b2b08b1f5bdb096bee72bd016bd5e0ecc7c05ac --- /dev/null +++ b/tasks/log-brunn-minkowski/instruction.md @@ -0,0 +1,92 @@ +# openai/math challenge `LogBrunnMinkowski` (family 091) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 091 of the release, *The logarithmic Brunn–Minkowski conjecture* +(Convex and metric geometry). The family as a whole: Proves the logarithmic Brunn–Minkowski inequality for origin-symmetric convex bodies in every dimension, and the scalar-dilation B-conjecture for all even log-concave Radon measures. For Lebesgue volume it also proves the additive $L_p$ Brunn–Minkowski inequality for full-dimensional origin-symmetric convex bodies throughout $0 ⟪x, u⟫_ℝ) '' K) + +def wulff {n : ℕ} (f : Space n → ℝ) : Set (Space n) := + {x | ∀ u, ‖u‖ = 1 → ⟪x, u⟫_ℝ ≤ f u} + +def logCombination {n : ℕ} (K L : Set (Space n)) (t : ℝ) : + Set (Space n) := + wulff (fun u => (support K u) ^ (1 - t) * (support L u) ^ t) + +theorem main (n : ℕ) (hn : 1 ≤ n) (K L : Set (Space n)) + (hK : IsConvexBody K) (hL : IsConvexBody L) + (hsK : OriginSymmetric K) (hsL : OriginSymmetric L) + (t : ℝ) (ht0 : 0 ≤ t) (ht1 : t ≤ 1) : + (volume K) ^ (1 - t) * (volume L) ^ t ≤ volume (logCombination K L t) := by + sorry + +end LogBrunnMinkowski + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LogBrunnMinkowski.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LogBrunnMinkowski.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/log-brunn-minkowski/solution/closure.txt b/tasks/log-brunn-minkowski/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4e0f7b1293ba0e661e6bbfcc069fd92d0a4d43e0 --- /dev/null +++ b/tasks/log-brunn-minkowski/solution/closure.txt @@ -0,0 +1 @@ +OAI.Geometry.LogVolume.BrunnMinkowski diff --git a/tasks/log-brunn-minkowski/solution/reference.py b/tasks/log-brunn-minkowski/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/log-brunn-minkowski/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/log-brunn-minkowski/solution/solve.sh b/tasks/log-brunn-minkowski/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ca5aa718c5d2c3effb2b4d17e4cbeb4bdbebd18d --- /dev/null +++ b/tasks/log-brunn-minkowski/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LogBrunnMinkowski, i.e. module OAI.Geometry.LogVolume.BrunnMinkowski and the +# 1 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.LogVolume.BrunnMinkowski /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LogBrunnMinkowski" diff --git a/tasks/log-brunn-minkowski/task.toml b/tasks/log-brunn-minkowski/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6b12f51ce244fd6f12f91486d0d0a3c9670e2874 --- /dev/null +++ b/tasks/log-brunn-minkowski/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/log-brunn-minkowski" +version = "1.0.0" +description = "Prove LogBrunnMinkowski (openai/math family 091: The logarithmic Brunn–Minkowski conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LogBrunnMinkowski.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LogBrunnMinkowski" +family = "091" +family_title = "The logarithmic Brunn–Minkowski conjecture" +subject = "Convex and metric geometry" +theorems = ["OAI.LogBrunnMinkowski.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.LogVolume.BrunnMinkowski" +reference_modules = 1 +reference_lean_bytes = 1228745 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 898 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12805 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/log-brunn-minkowski/tests/Challenge.lean b/tasks/log-brunn-minkowski/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a40e4c0e7c1cd07231a2335927d8c3588a9115cd --- /dev/null +++ b/tasks/log-brunn-minkowski/tests/Challenge.lean @@ -0,0 +1,41 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped ENNReal InnerProductSpace + +namespace LogBrunnMinkowski + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def IsConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def OriginSymmetric {n : ℕ} (K : Set (Space n)) : Prop := + ∀ x, x ∈ K ↔ -x ∈ K + +def support {n : ℕ} (K : Set (Space n)) (u : Space n) : ℝ := + sSup ((fun x : Space n => ⟪x, u⟫_ℝ) '' K) + +def wulff {n : ℕ} (f : Space n → ℝ) : Set (Space n) := + {x | ∀ u, ‖u‖ = 1 → ⟪x, u⟫_ℝ ≤ f u} + +def logCombination {n : ℕ} (K L : Set (Space n)) (t : ℝ) : + Set (Space n) := + wulff (fun u => (support K u) ^ (1 - t) * (support L u) ^ t) + +theorem main (n : ℕ) (hn : 1 ≤ n) (K L : Set (Space n)) + (hK : IsConvexBody K) (hL : IsConvexBody L) + (hsK : OriginSymmetric K) (hsL : OriginSymmetric L) + (t : ℝ) (ht0 : 0 ≤ t) (ht1 : t ≤ 1) : + (volume K) ^ (1 - t) * (volume L) ^ t ≤ volume (logCombination K L t) := by + sorry + +end LogBrunnMinkowski + +end + +end OAI diff --git a/tasks/log-brunn-minkowski/tests/grade.py b/tasks/log-brunn-minkowski/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/log-brunn-minkowski/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/log-brunn-minkowski/tests/task.json b/tasks/log-brunn-minkowski/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5e4e4438e9960c50d5691cbc26c176c4f9392bd4 --- /dev/null +++ b/tasks/log-brunn-minkowski/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LogBrunnMinkowski", + "comparator": { + "theorem_names": [ + "OAI.LogBrunnMinkowski.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11905 +} \ No newline at end of file diff --git a/tasks/log-brunn-minkowski/tests/test.sh b/tasks/log-brunn-minkowski/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/log-brunn-minkowski/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/log-concave-query/environment/Dockerfile b/tasks/log-concave-query/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/log-concave-query/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/log-concave-query/environment/fetch_mathlib.sh b/tasks/log-concave-query/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/log-concave-query/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/log-concave-query/environment/lake-manifest.json b/tasks/log-concave-query/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/log-concave-query/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/log-concave-query/environment/lakefile.lean b/tasks/log-concave-query/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/log-concave-query/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/log-concave-query/environment/lean_setup.sh b/tasks/log-concave-query/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/log-concave-query/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/log-concave-query/environment/pack_submission.py b/tasks/log-concave-query/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/log-concave-query/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/log-concave-query/instruction.md b/tasks/log-concave-query/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a928578feb9e1d35b9632c1fbea58a9ecc4e9a0 --- /dev/null +++ b/tasks/log-concave-query/instruction.md @@ -0,0 +1,144 @@ +# openai/math challenge `LogConcaveQuery` (family 139) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 139 of the release, *Subpolynomial queries for log-concave sampling* +(Theoretical computer science). The family as a whole: For $C^2$ potentials with a supplied minimizer and $I\preceq\nabla^2V\preceq2I$, proves that sampling within total variation $1/10$ requires only $C_\varepsilon d^\varepsilon$ exact value-and-gradient queries for every fixed $\varepsilon>0$. The bound holds on every run, with unrestricted computation between queries. A logarithmic lower bound also holds, so the optimal power-law exponent in this oracle model is zero. + +The challenge is `LogConcaveQuery`, also at `/opt/openai-math/challenges/LogConcaveQuery.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter +open scoped ENNReal NNReal Topology + +namespace LogConcaveSampling + +abbrev Point (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Reply (d : ℕ) := ℝ × Point d +abbrev Transcript (d q : ℕ) := Fin q → Reply d + +/-- Normalized twice continuously differentiable potentials with Hessian between the identity and twice the identity. -/ +structure Admissible {d : ℕ} (V : Point d → ℝ) : Prop where + smooth : ContDiff ℝ 2 V + value_zero : V 0 = 0 + gradient_zero : gradient V 0 = 0 + hessian_bounds : ∀ x v : Point d, + ‖v‖ ^ 2 ≤ inner ℝ v (fderiv ℝ (gradient V) x v) ∧ + inner ℝ v (fderiv ℝ (gradient V) x v) ≤ 2 * ‖v‖ ^ 2 + +/-- The unnormalized Gibbs density relative to Euclidean volume. -/ +def gibbsDensity {d : ℕ} (V : Point d → ℝ) (x : Point d) : ℝ≥0∞ := + ENNReal.ofReal (Real.exp (-V x)) + +def partition {d : ℕ} (V : Point d → ℝ) : ℝ≥0∞ := + ∫⁻ x, gibbsDensity V x ∂volume + +/-- The Gibbs probability law, normalized by its partition function. -/ +def gibbs {d : ℕ} (V : Point d → ℝ) : Measure (Point d) := + (partition V)⁻¹ • volume.withDensity (gibbsDensity V) + +def TVAtMost {E : Type*} [MeasurableSpace E] + (μ ν : Measure E) (ε : ℝ) : Prop := + ∀ s : Set E, MeasurableSet s → |μ.real s - ν.real s| ≤ ε + +def firstOrderReply {d : ℕ} (V : Point d → ℝ) (x : Point d) : Reply d := + (V x, gradient V x) + +/-- Measurable adaptive queries and output, parametrized by private randomness. -/ +structure OracleAlgorithm (Ω : Type*) [MeasurableSpace Ω] (d q : ℕ) where + query : Fin q → Ω × Transcript d q → Point d + query_measurable : ∀ i, Measurable (query i) + output : Ω × Transcript d q → Point d + output_measurable : Measurable output + +def OracleAlgorithm.history {Ω : Type*} [MeasurableSpace Ω] {d q : ℕ} + (A : OracleAlgorithm Ω d q) (V : Point d → ℝ) (ω : Ω) : ℕ → Transcript d q + | 0 => 0 + | n + 1 => + let h := A.history V ω n + if hn : n < q then + Function.update h ⟨n, hn⟩ (firstOrderReply V (A.query ⟨n, hn⟩ (ω, h))) + else h + +def OracleAlgorithm.run {Ω : Type*} [MeasurableSpace Ω] {d q : ℕ} + (A : OracleAlgorithm Ω d q) (V : Point d → ℝ) (ω : Ω) : Point d := + A.output (ω, A.history V ω q) + +/-- A uniform sampler with a deterministic query budget on every execution and total-variation error at most one tenth. -/ +def CanSample (d q : ℕ) : Prop := + ∃ (Ω : Type) (_ : MeasurableSpace Ω) (μ : Measure Ω) + (_ : IsProbabilityMeasure μ) (A : OracleAlgorithm Ω d q), + ∀ V : Point d → ℝ, Admissible V → + Measurable (A.run V) ∧ TVAtMost (μ.map (A.run V)) (gibbs V) (1 / 10) + +/-- The smallest feasible integer query budget, or infinity when no budget is feasible. -/ +def queryComplexity (d : ℕ) : ℕ∞ := + sInf ((fun q : ℕ => (q : ℕ∞)) '' {q | CanSample d q}) + +/-- The quantified dimension-exponent upper bound with every positive exponent slack. -/ +def ExponentBound (γ : ℝ) : Prop := + 0 ≤ γ ∧ ∀ ε : ℝ, 0 < ε → ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (queryComplexity d).toENNReal ≤ ENNReal.ofReal ((d : ℝ) ^ (γ + ε)) + +def gammaStar : ℝ := sInf {γ : ℝ | ExponentBound γ} + +theorem exact_source_main : + (∀ ε : ℝ, 0 < ε → ∃ C : ℝ, ∀ d : ℕ, 2 ≤ d → + (queryComplexity d).toENNReal ≤ ENNReal.ofReal (C * (d : ℝ) ^ ε)) ∧ + (∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, 2 ≤ d₀ ∧ ∀ d : ℕ, d₀ ≤ d → + ENNReal.ofReal (c * Real.log (d : ℝ)) ≤ (queryComplexity d).toENNReal) ∧ + gammaStar = 0 := by + sorry + +end LogConcaveSampling + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LogConcaveQuery.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LogConcaveSampling.exact_source_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/log-concave-query/solution/closure.txt b/tasks/log-concave-query/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a41164e85fd7f814958c3d3c4ebd16fac4860e3 --- /dev/null +++ b/tasks/log-concave-query/solution/closure.txt @@ -0,0 +1,326 @@ +OAI.Probability.LogConcave.Analysis.AffinePotential +OAI.Probability.LogConcave.Analysis.CenteringPotential +OAI.Probability.LogConcave.Analysis.CompactGibbsIbp +OAI.Probability.LogConcave.Analysis.ConditionalPotential +OAI.Probability.LogConcave.Analysis.EulerDrift +OAI.Probability.LogConcave.Analysis.GaussianAffineNormMoment +OAI.Probability.LogConcave.Analysis.GaussianCoefficient +OAI.Probability.LogConcave.Analysis.GaussianMarginalLowerTail +OAI.Probability.LogConcave.Analysis.GaussianPairSumLaw +OAI.Probability.LogConcave.Analysis.GaussianProposalPotential +OAI.Probability.LogConcave.Analysis.GibbsOpenPos +OAI.Probability.LogConcave.Analysis.GibbsProportional +OAI.Probability.LogConcave.Analysis.GrowthInnerGradient +OAI.Probability.LogConcave.Analysis.InterpolationHessianBudget +OAI.Probability.LogConcave.Analysis.InterpolationPotential +OAI.Probability.LogConcave.Analysis.Law +OAI.Probability.LogConcave.Analysis.Operator +OAI.Probability.LogConcave.Analysis.Poincare +OAI.Probability.LogConcave.Analysis.PoincareVectorVariance +OAI.Probability.LogConcave.Analysis.PrimitivePotentialModeBounds +OAI.Probability.LogConcave.Analysis.ProductPotentialMeasurable +OAI.Probability.LogConcave.Analysis.ProposalLog +OAI.Probability.LogConcave.Analysis.SymmetricGradientDerivative +OAI.Probability.LogConcave.Complexity.CenteringStateBudget +OAI.Probability.LogConcave.Complexity.CenteringStateBudgetNonneg +OAI.Probability.LogConcave.Complexity.Envelope +OAI.Probability.LogConcave.Complexity.EventuallySequences +OAI.Probability.LogConcave.Complexity.HarmonicCorrectionBudget +OAI.Probability.LogConcave.Complexity.KernelActionNormalizedBudget +OAI.Probability.LogConcave.Complexity.KernelActionRmsBudget +OAI.Probability.LogConcave.Complexity.KernelAnalyticBudget +OAI.Probability.LogConcave.Complexity.KernelAnalyticNormalizedBudget +OAI.Probability.LogConcave.Complexity.KernelValueRmsBudget +OAI.Probability.LogConcave.Complexity.OccurrenceBudget +OAI.Probability.LogConcave.Complexity.PolynomialBudget +OAI.Probability.LogConcave.Complexity.ProbabilityRmsBudget +OAI.Probability.LogConcave.Complexity.ProductEnergyBudgetScaled +OAI.Probability.LogConcave.Complexity.SingleCellBasisBudget +OAI.Probability.LogConcave.Complexity.TerminalDerivativeBudget +OAI.Probability.LogConcave.Complexity.VelocityNormalizedBudgetCalibrated +OAI.Probability.LogConcave.Dynamics.AbsorbFixed +OAI.Probability.LogConcave.Dynamics.ActualJointCenteringFlow +OAI.Probability.LogConcave.Dynamics.ConditionalHarmonicFlow +OAI.Probability.LogConcave.Dynamics.Curve +OAI.Probability.LogConcave.Dynamics.DistanceCoupled +OAI.Probability.LogConcave.Dynamics.FlowRestrict +OAI.Probability.LogConcave.Dynamics.FullProbabilityFlow +OAI.Probability.LogConcave.Dynamics.HarmonicFlow +OAI.Probability.LogConcave.Dynamics.IntegralLipschitz +OAI.Probability.LogConcave.Dynamics.JointHarmonicFlow +OAI.Probability.LogConcave.Dynamics.NormSubSqThree +OAI.Probability.LogConcave.Dynamics.ObservableIntegralMeasurable +OAI.Probability.LogConcave.Dynamics.ProbabilityFlowGrowth +OAI.Probability.LogConcave.Dynamics.ProbabilityFlowIntegral +OAI.Probability.LogConcave.Dynamics.ProbabilityFlowPushforward +OAI.Probability.LogConcave.Dynamics.SameLaw +OAI.Probability.LogConcave.Dynamics.SharedLipschitz +OAI.Probability.LogConcave.Dynamics.SmoothFlowJoint +OAI.Probability.LogConcave.Dynamics.SpaceTimeForward +OAI.Probability.LogConcave.Dynamics.Squared +OAI.Probability.LogConcave.Dynamics.StationaryIntegral +OAI.Probability.LogConcave.Dynamics.StationaryPath +OAI.Probability.LogConcave.Dynamics.TriangularEquiv +OAI.Probability.LogConcave.Dynamics.Truncated +OAI.Probability.LogConcave.Dynamics.VariationalField +OAI.Probability.LogConcave.JetEstimates.AllSplitBound +OAI.Probability.LogConcave.JetEstimates.ArrayComponentPolySmooth +OAI.Probability.LogConcave.JetEstimates.ArrayMatrix +OAI.Probability.LogConcave.JetEstimates.ArrayRelabel +OAI.Probability.LogConcave.JetEstimates.AssignmentsFinset +OAI.Probability.LogConcave.JetEstimates.Bound +OAI.Probability.LogConcave.JetEstimates.ClosedWireLintegralBound +OAI.Probability.LogConcave.JetEstimates.CompLinear +OAI.Probability.LogConcave.JetEstimates.ContractLeftSplit +OAI.Probability.LogConcave.JetEstimates.CrossMoment +OAI.Probability.LogConcave.JetEstimates.DirLogLaplace +OAI.Probability.LogConcave.JetEstimates.Extend +OAI.Probability.LogConcave.JetEstimates.Extension +OAI.Probability.LogConcave.JetEstimates.FlowJetMajorant +OAI.Probability.LogConcave.JetEstimates.ForestTensor +OAI.Probability.LogConcave.JetEstimates.GadjScalar +OAI.Probability.LogConcave.JetEstimates.Growth +OAI.Probability.LogConcave.JetEstimates.JetCompactIntegral +OAI.Probability.LogConcave.JetEstimates.JetCongrList +OAI.Probability.LogConcave.JetEstimates.JetMapPositions +OAI.Probability.LogConcave.JetEstimates.JetMaterial +OAI.Probability.LogConcave.JetEstimates.JetNormalizedLaplaceMoments +OAI.Probability.LogConcave.JetEstimates.JetRightSlice +OAI.Probability.LogConcave.JetEstimates.Lipschitz +OAI.Probability.LogConcave.JetEstimates.LogDegree +OAI.Probability.LogConcave.JetEstimates.Material +OAI.Probability.LogConcave.JetEstimates.MatrixArray +OAI.Probability.LogConcave.JetEstimates.Mdir +OAI.Probability.LogConcave.JetEstimates.MixedJetAdd +OAI.Probability.LogConcave.JetEstimates.MultisetProd +OAI.Probability.LogConcave.JetEstimates.MultisetProd2 +OAI.Probability.LogConcave.JetEstimates.NormalizedLaplace +OAI.Probability.LogConcave.JetEstimates.PolyC1 +OAI.Probability.LogConcave.JetEstimates.PolySmooth +OAI.Probability.LogConcave.JetEstimates.ProperSplit +OAI.Probability.LogConcave.JetEstimates.ProperSplitCard +OAI.Probability.LogConcave.JetEstimates.Reindex +OAI.Probability.LogConcave.JetEstimates.ReindexedMatrix +OAI.Probability.LogConcave.JetEstimates.Slice +OAI.Probability.LogConcave.JetEstimates.SmoothTensorCurve +OAI.Probability.LogConcave.JetEstimates.SpaceBasis +OAI.Probability.LogConcave.JetEstimates.SplitBundle +OAI.Probability.LogConcave.JetEstimates.SplitIndex +OAI.Probability.LogConcave.JetEstimates.Squared +OAI.Probability.LogConcave.JetEstimates.TensorExpression +OAI.Probability.LogConcave.JetEstimates.TensorTerm +OAI.Probability.LogConcave.JetEstimates.WireStep +OAI.Probability.LogConcave.LowerBounds.CouplingNoise +OAI.Probability.LogConcave.LowerBounds.DensityCoefficient +OAI.Probability.LogConcave.LowerBounds.FrameTransport +OAI.Probability.LogConcave.LowerBounds.HardEigenOutput +OAI.Probability.LogConcave.LowerBounds.LinearHistory +OAI.Probability.LogConcave.LowerBounds.PrefixSpace +OAI.Probability.LogConcave.LowerBounds.RevealRotation +OAI.Probability.LogConcave.LowerBounds.RotationIsometry +OAI.Probability.LogConcave.LowerBounds.RoundFrames +OAI.Probability.LogConcave.LowerBounds.SpectrumOperator +OAI.Probability.LogConcave.LowerBounds.Theta +OAI.Probability.LogConcave.LowerBounds.TranscriptRejection +OAI.Probability.LogConcave.LowerBounds.WeightedEvaluation +OAI.Probability.LogConcave.Main +OAI.Probability.LogConcave.Model +OAI.Probability.LogConcave.Numerics.BaseVariation +OAI.Probability.LogConcave.Numerics.BaseVariationCenters +OAI.Probability.LogConcave.Numerics.Basis +OAI.Probability.LogConcave.Numerics.BasisDerivative +OAI.Probability.LogConcave.Numerics.CenterValuesMono +OAI.Probability.LogConcave.Numerics.CenteringStateQuadratureBudget +OAI.Probability.LogConcave.Numerics.CenteringVelocityPicard +OAI.Probability.LogConcave.Numerics.CentersBoundPicard +OAI.Probability.LogConcave.Numerics.ChainTaylor +OAI.Probability.LogConcave.Numerics.ChildNoise +OAI.Probability.LogConcave.Numerics.CompileDeclaredRootNormalized +OAI.Probability.LogConcave.Numerics.CompileDeclaredRootShift +OAI.Probability.LogConcave.Numerics.CompositeAngle +OAI.Probability.LogConcave.Numerics.Correction +OAI.Probability.LogConcave.Numerics.Cost +OAI.Probability.LogConcave.Numerics.DerivSetIntegral +OAI.Probability.LogConcave.Numerics.EvalLipschitz +OAI.Probability.LogConcave.Numerics.Forward +OAI.Probability.LogConcave.Numerics.GradientBound +OAI.Probability.LogConcave.Numerics.KernelActionPicardRms +OAI.Probability.LogConcave.Numerics.KernelCorrectionPicard +OAI.Probability.LogConcave.Numerics.LogMeshLength +OAI.Probability.LogConcave.Numerics.MeanTree +OAI.Probability.LogConcave.Numerics.NodeLp +OAI.Probability.LogConcave.Numerics.NodePolynomial +OAI.Probability.LogConcave.Numerics.NodesContinuous +OAI.Probability.LogConcave.Numerics.NormSubSqTwo +OAI.Probability.LogConcave.Numerics.OrdinaryDerivativeWeight +OAI.Probability.LogConcave.Numerics.ParametricFDeriv +OAI.Probability.LogConcave.Numerics.Picard +OAI.Probability.LogConcave.Numerics.ReanchorWeight +OAI.Probability.LogConcave.Numerics.Remainder +OAI.Probability.LogConcave.Numerics.RowGaussian +OAI.Probability.LogConcave.Numerics.RowTape +OAI.Probability.LogConcave.Numerics.ScalarPicard +OAI.Probability.LogConcave.Numerics.TaylorRemainderRms +OAI.Probability.LogConcave.Numerics.TwoendsContinuous +OAI.Probability.LogConcave.Numerics.VelocityWorkCoefficient +OAI.Probability.LogConcave.OraclePrograms.CalibratedMeanCircuit +OAI.Probability.LogConcave.OraclePrograms.CenteringMeanCircuit +OAI.Probability.LogConcave.OraclePrograms.CenteringMeanCircuitFull +OAI.Probability.LogConcave.OraclePrograms.CircuitBoundUpto +OAI.Probability.LogConcave.OraclePrograms.CircuitD +OAI.Probability.LogConcave.OraclePrograms.CircuitParameters +OAI.Probability.LogConcave.OraclePrograms.DampingCoefficient +OAI.Probability.LogConcave.OraclePrograms.Expression +OAI.Probability.LogConcave.OraclePrograms.Fresh +OAI.Probability.LogConcave.OraclePrograms.FullTape +OAI.Probability.LogConcave.OraclePrograms.IndependentSeq +OAI.Probability.LogConcave.OraclePrograms.MeanCorrect +OAI.Probability.LogConcave.OraclePrograms.MeanSize +OAI.Probability.LogConcave.OraclePrograms.MeanTreeBase +OAI.Probability.LogConcave.OraclePrograms.NoisyCenterSquaredError +OAI.Probability.LogConcave.OraclePrograms.NoisyCircuit +OAI.Probability.LogConcave.OraclePrograms.PairDistBounds +OAI.Probability.LogConcave.OraclePrograms.PrimitiveProducer +OAI.Probability.LogConcave.OraclePrograms.Program +OAI.Probability.LogConcave.OraclePrograms.ReservedProgram +OAI.Probability.LogConcave.OraclePrograms.RoutineBudget +OAI.Probability.LogConcave.OraclePrograms.RoutineKind +OAI.Probability.LogConcave.OraclePrograms.SampleCorrect +OAI.Probability.LogConcave.OraclePrograms.SampleParentEquivariant +OAI.Probability.LogConcave.OraclePrograms.SeedProgram +OAI.Probability.LogConcave.OraclePrograms.Shape +OAI.Probability.LogConcave.OraclePrograms.ShiftInvariant +OAI.Probability.LogConcave.OraclePrograms.SlotTransformAddShift +OAI.Probability.LogConcave.OraclePrograms.StandaloneCorrect +OAI.Probability.LogConcave.OraclePrograms.TerminalMean +OAI.Probability.LogConcave.OraclePrograms.TerminalMeanEquivariant +OAI.Probability.LogConcave.OraclePrograms.TerminalMeanProgram +OAI.Probability.LogConcave.OraclePrograms.TopProgram +OAI.Probability.LogConcave.OraclePrograms.TvPre +OAI.Probability.LogConcave.Sampling.AdjointCoordinateContinuous +OAI.Probability.LogConcave.Sampling.AdjointCoordinateProductLeft +OAI.Probability.LogConcave.Sampling.AnalyticBase +OAI.Probability.LogConcave.Sampling.AnchorGauge +OAI.Probability.LogConcave.Sampling.AngleNodes +OAI.Probability.LogConcave.Sampling.AverageLipschitz +OAI.Probability.LogConcave.Sampling.CenteringJointLaw +OAI.Probability.LogConcave.Sampling.CenteringOutputLaw +OAI.Probability.LogConcave.Sampling.CenteringVelocityInterpolationRms +OAI.Probability.LogConcave.Sampling.CenteringVelocityJoint +OAI.Probability.LogConcave.Sampling.ChangingChain +OAI.Probability.LogConcave.Sampling.ClosedFieldMean +OAI.Probability.LogConcave.Sampling.ComposedJetMajorant +OAI.Probability.LogConcave.Sampling.ConditionalFieldMean +OAI.Probability.LogConcave.Sampling.ConditionalMeanArray +OAI.Probability.LogConcave.Sampling.ConditionalMeanScalar +OAI.Probability.LogConcave.Sampling.ConditionalPositionMoment +OAI.Probability.LogConcave.Sampling.ConditionalSlotEmbedding +OAI.Probability.LogConcave.Sampling.ContinuousFirstOrderReply +OAI.Probability.LogConcave.Sampling.CoordinateProjection +OAI.Probability.LogConcave.Sampling.CoordinateRank +OAI.Probability.LogConcave.Sampling.Correlation +OAI.Probability.LogConcave.Sampling.Directional +OAI.Probability.LogConcave.Sampling.DirectionalAdjointCoordinate +OAI.Probability.LogConcave.Sampling.DirectionalBasisSum +OAI.Probability.LogConcave.Sampling.FDerivTimePartial +OAI.Probability.LogConcave.Sampling.FinSnocSlots +OAI.Probability.LogConcave.Sampling.FinsetSumSum +OAI.Probability.LogConcave.Sampling.HarmonicKernel +OAI.Probability.LogConcave.Sampling.HarmonicMeanDefect +OAI.Probability.LogConcave.Sampling.HarmonicMeanTaylorRms +OAI.Probability.LogConcave.Sampling.HarmonicPositionDeriv +OAI.Probability.LogConcave.Sampling.HarmonicStationaryMoment +OAI.Probability.LogConcave.Sampling.IdentityOutputEmbedding +OAI.Probability.LogConcave.Sampling.InnerBasisCoordinate +OAI.Probability.LogConcave.Sampling.InterpolationResidual +OAI.Probability.LogConcave.Sampling.IterTensorLie +OAI.Probability.LogConcave.Sampling.Jet +OAI.Probability.LogConcave.Sampling.JointConditionalLawProperties +OAI.Probability.LogConcave.Sampling.JointInterpolationLaw +OAI.Probability.LogConcave.Sampling.JointMeanMaterial +OAI.Probability.LogConcave.Sampling.JointPosition +OAI.Probability.LogConcave.Sampling.JointSpace +OAI.Probability.LogConcave.Sampling.JointU +OAI.Probability.LogConcave.Sampling.KernelTransportAction +OAI.Probability.LogConcave.Sampling.LintegralFinNatProd +OAI.Probability.LogConcave.Sampling.LogMeshCountRate +OAI.Probability.LogConcave.Sampling.Map +OAI.Probability.LogConcave.Sampling.MapProdFiberLaw +OAI.Probability.LogConcave.Sampling.MapProdSecondFiber +OAI.Probability.LogConcave.Sampling.MaterialScalar +OAI.Probability.LogConcave.Sampling.MatrixArrayAdjoint +OAI.Probability.LogConcave.Sampling.MatrixColor +OAI.Probability.LogConcave.Sampling.MeanMaterialL2 +OAI.Probability.LogConcave.Sampling.MeanMaterialVector +OAI.Probability.LogConcave.Sampling.MeasureSmoothLipschitz +OAI.Probability.LogConcave.Sampling.MixingEnvelope +OAI.Probability.LogConcave.Sampling.NaturalMomentNorm +OAI.Probability.LogConcave.Sampling.NoiseKernel +OAI.Probability.LogConcave.Sampling.NormalizedDirection +OAI.Probability.LogConcave.Sampling.NormalizedScoreMajorant +OAI.Probability.LogConcave.Sampling.NormalizedTensor +OAI.Probability.LogConcave.Sampling.NormalizedTensorMajorantScale +OAI.Probability.LogConcave.Sampling.NumericalLayerCount +OAI.Probability.LogConcave.Sampling.NumericalScalars +OAI.Probability.LogConcave.Sampling.PairGauge +OAI.Probability.LogConcave.Sampling.PiAppendLaw +OAI.Probability.LogConcave.Sampling.PolynomialGrowth +OAI.Probability.LogConcave.Sampling.PosteriorJointIntegral +OAI.Probability.LogConcave.Sampling.PrependTape +OAI.Probability.LogConcave.Sampling.Primitive +OAI.Probability.LogConcave.Sampling.PrimitiveExpectedField +OAI.Probability.LogConcave.Sampling.PrimitiveExpectedFieldLipschitz +OAI.Probability.LogConcave.Sampling.PrimitiveField +OAI.Probability.LogConcave.Sampling.ProbabilityEndpoint +OAI.Probability.LogConcave.Sampling.ProbabilityInitialRms +OAI.Probability.LogConcave.Sampling.ProbabilityNodes +OAI.Probability.LogConcave.Sampling.ProbabilityNormalizedTerm +OAI.Probability.LogConcave.Sampling.ProbabilityTransportTrajectory +OAI.Probability.LogConcave.Sampling.ProbabilityVelocity +OAI.Probability.LogConcave.Sampling.ProdMapEventReal +OAI.Probability.LogConcave.Sampling.QuadraticExpectation +OAI.Probability.LogConcave.Sampling.Reindex +OAI.Probability.LogConcave.Sampling.SampleCorrelation +OAI.Probability.LogConcave.Sampling.ScaledMeanJet +OAI.Probability.LogConcave.Sampling.ScoreAugmented +OAI.Probability.LogConcave.Sampling.ScoreSlots +OAI.Probability.LogConcave.Sampling.SkewCenteringField +OAI.Probability.LogConcave.Sampling.SkewCenteringFieldSmooth +OAI.Probability.LogConcave.Sampling.SmoothTimeLocalization +OAI.Probability.LogConcave.Sampling.SpatialJacobianTimeDeriv +OAI.Probability.LogConcave.Sampling.SpatialTensor +OAI.Probability.LogConcave.Sampling.SpatialTensorArrayBound +OAI.Probability.LogConcave.Sampling.SpatialTensorContinuous +OAI.Probability.LogConcave.Sampling.SpatialTransport +OAI.Probability.LogConcave.Sampling.StateLaw +OAI.Probability.LogConcave.Sampling.StationaryMeanTarget +OAI.Probability.LogConcave.Sampling.StationaryTensorVectorRms +OAI.Probability.LogConcave.Sampling.TapeSnocEquiv +OAI.Probability.LogConcave.Sampling.TensorGrad +OAI.Probability.LogConcave.Sampling.TensorVector +OAI.Probability.LogConcave.Sampling.TerminalActionChainQuotient +OAI.Probability.LogConcave.Sampling.TerminalBackward +OAI.Probability.LogConcave.Sampling.TerminalJacobianInverse +OAI.Probability.LogConcave.Sampling.TerminalMean +OAI.Probability.LogConcave.Sampling.TerminalTransportConstant +OAI.Probability.LogConcave.Sampling.TiltedExpectation +OAI.Probability.LogConcave.Sampling.TimeBump +OAI.Probability.LogConcave.Sampling.TopScale +OAI.Probability.LogConcave.Sampling.TranslationIntegrationByParts +OAI.Probability.LogConcave.Sampling.TransportCorrectionMajorant +OAI.Probability.LogConcave.Sampling.TransportMajorant +OAI.Probability.LogConcave.Sampling.UnitUniform +OAI.Probability.LogConcave.Sampling.VelocityJointLip +OAI.Probability.LogConcave.TensorGraphs.AdjointMatrix +OAI.Probability.LogConcave.TensorGraphs.Chain +OAI.Probability.LogConcave.TensorGraphs.ColoringSplit +OAI.Probability.LogConcave.TensorGraphs.FieldPosition +OAI.Probability.LogConcave.TensorGraphs.HessianIncidenceTensor +OAI.Probability.LogConcave.TensorGraphs.HessianIncidentEquiv +OAI.Probability.LogConcave.TensorGraphs.History +OAI.Probability.LogConcave.TensorGraphs.IncidentMatrix +OAI.Probability.LogConcave.TensorGraphs.Inside +OAI.Probability.LogConcave.TensorGraphs.Live +OAI.Probability.LogConcave.TensorGraphs.PrimaryPositionTensor +OAI.Probability.LogConcave.TensorGraphs.RankEquiv +OAI.Probability.LogConcave.TensorGraphs.Vertex diff --git a/tasks/log-concave-query/solution/reference.py b/tasks/log-concave-query/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/log-concave-query/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/log-concave-query/solution/solve.sh b/tasks/log-concave-query/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..beb60d104afc195f4ebd416e20810e0cc91a2a47 --- /dev/null +++ b/tasks/log-concave-query/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LogConcaveQuery, i.e. module OAI.Probability.LogConcave.Main and the +# 326 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.LogConcave.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LogConcaveQuery" diff --git a/tasks/log-concave-query/task.toml b/tasks/log-concave-query/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f5ec49a6dd4f1ef99bb22bf726753f28dcc8e2c1 --- /dev/null +++ b/tasks/log-concave-query/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/log-concave-query" +version = "1.0.0" +description = "Prove LogConcaveQuery (openai/math family 139: Subpolynomial queries for log-concave sampling) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LogConcaveQuery.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LogConcaveQuery" +family = "139" +family_title = "Subpolynomial queries for log-concave sampling" +subject = "Theoretical computer science" +theorems = ["OAI.LogConcaveSampling.exact_source_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.LogConcave.Main" +reference_modules = 326 +reference_lean_bytes = 3000883 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1278 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14400 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/log-concave-query/tests/Challenge.lean b/tasks/log-concave-query/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb5e705b7f6a62aee93a071473d7a06d9dc735d3 --- /dev/null +++ b/tasks/log-concave-query/tests/Challenge.lean @@ -0,0 +1,93 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory Filter +open scoped ENNReal NNReal Topology + +namespace LogConcaveSampling + +abbrev Point (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Reply (d : ℕ) := ℝ × Point d +abbrev Transcript (d q : ℕ) := Fin q → Reply d + +/-- Normalized twice continuously differentiable potentials with Hessian between the identity and twice the identity. -/ +structure Admissible {d : ℕ} (V : Point d → ℝ) : Prop where + smooth : ContDiff ℝ 2 V + value_zero : V 0 = 0 + gradient_zero : gradient V 0 = 0 + hessian_bounds : ∀ x v : Point d, + ‖v‖ ^ 2 ≤ inner ℝ v (fderiv ℝ (gradient V) x v) ∧ + inner ℝ v (fderiv ℝ (gradient V) x v) ≤ 2 * ‖v‖ ^ 2 + +/-- The unnormalized Gibbs density relative to Euclidean volume. -/ +def gibbsDensity {d : ℕ} (V : Point d → ℝ) (x : Point d) : ℝ≥0∞ := + ENNReal.ofReal (Real.exp (-V x)) + +def partition {d : ℕ} (V : Point d → ℝ) : ℝ≥0∞ := + ∫⁻ x, gibbsDensity V x ∂volume + +/-- The Gibbs probability law, normalized by its partition function. -/ +def gibbs {d : ℕ} (V : Point d → ℝ) : Measure (Point d) := + (partition V)⁻¹ • volume.withDensity (gibbsDensity V) + +def TVAtMost {E : Type*} [MeasurableSpace E] + (μ ν : Measure E) (ε : ℝ) : Prop := + ∀ s : Set E, MeasurableSet s → |μ.real s - ν.real s| ≤ ε + +def firstOrderReply {d : ℕ} (V : Point d → ℝ) (x : Point d) : Reply d := + (V x, gradient V x) + +/-- Measurable adaptive queries and output, parametrized by private randomness. -/ +structure OracleAlgorithm (Ω : Type*) [MeasurableSpace Ω] (d q : ℕ) where + query : Fin q → Ω × Transcript d q → Point d + query_measurable : ∀ i, Measurable (query i) + output : Ω × Transcript d q → Point d + output_measurable : Measurable output + +def OracleAlgorithm.history {Ω : Type*} [MeasurableSpace Ω] {d q : ℕ} + (A : OracleAlgorithm Ω d q) (V : Point d → ℝ) (ω : Ω) : ℕ → Transcript d q + | 0 => 0 + | n + 1 => + let h := A.history V ω n + if hn : n < q then + Function.update h ⟨n, hn⟩ (firstOrderReply V (A.query ⟨n, hn⟩ (ω, h))) + else h + +def OracleAlgorithm.run {Ω : Type*} [MeasurableSpace Ω] {d q : ℕ} + (A : OracleAlgorithm Ω d q) (V : Point d → ℝ) (ω : Ω) : Point d := + A.output (ω, A.history V ω q) + +/-- A uniform sampler with a deterministic query budget on every execution and total-variation error at most one tenth. -/ +def CanSample (d q : ℕ) : Prop := + ∃ (Ω : Type) (_ : MeasurableSpace Ω) (μ : Measure Ω) + (_ : IsProbabilityMeasure μ) (A : OracleAlgorithm Ω d q), + ∀ V : Point d → ℝ, Admissible V → + Measurable (A.run V) ∧ TVAtMost (μ.map (A.run V)) (gibbs V) (1 / 10) + +/-- The smallest feasible integer query budget, or infinity when no budget is feasible. -/ +def queryComplexity (d : ℕ) : ℕ∞ := + sInf ((fun q : ℕ => (q : ℕ∞)) '' {q | CanSample d q}) + +/-- The quantified dimension-exponent upper bound with every positive exponent slack. -/ +def ExponentBound (γ : ℝ) : Prop := + 0 ≤ γ ∧ ∀ ε : ℝ, 0 < ε → ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (queryComplexity d).toENNReal ≤ ENNReal.ofReal ((d : ℝ) ^ (γ + ε)) + +def gammaStar : ℝ := sInf {γ : ℝ | ExponentBound γ} + +theorem exact_source_main : + (∀ ε : ℝ, 0 < ε → ∃ C : ℝ, ∀ d : ℕ, 2 ≤ d → + (queryComplexity d).toENNReal ≤ ENNReal.ofReal (C * (d : ℝ) ^ ε)) ∧ + (∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, 2 ≤ d₀ ∧ ∀ d : ℕ, d₀ ≤ d → + ENNReal.ofReal (c * Real.log (d : ℝ)) ≤ (queryComplexity d).toENNReal) ∧ + gammaStar = 0 := by + sorry + +end LogConcaveSampling + +end + +end OAI diff --git a/tasks/log-concave-query/tests/grade.py b/tasks/log-concave-query/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/log-concave-query/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/log-concave-query/tests/task.json b/tasks/log-concave-query/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..84c6522d5025a2f03d16b81f961512002094271d --- /dev/null +++ b/tasks/log-concave-query/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LogConcaveQuery", + "comparator": { + "theorem_names": [ + "OAI.LogConcaveSampling.exact_source_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13500 +} \ No newline at end of file diff --git a/tasks/log-concave-query/tests/test.sh b/tasks/log-concave-query/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/log-concave-query/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/log-kodaira-fiber-negative/environment/Dockerfile b/tasks/log-kodaira-fiber-negative/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/log-kodaira-fiber-negative/environment/fetch_mathlib.sh b/tasks/log-kodaira-fiber-negative/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/log-kodaira-fiber-negative/environment/lake-manifest.json b/tasks/log-kodaira-fiber-negative/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/log-kodaira-fiber-negative/environment/lakefile.lean b/tasks/log-kodaira-fiber-negative/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/log-kodaira-fiber-negative/environment/lean_setup.sh b/tasks/log-kodaira-fiber-negative/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/log-kodaira-fiber-negative/environment/pack_submission.py b/tasks/log-kodaira-fiber-negative/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/log-kodaira-fiber-negative/instruction.md b/tasks/log-kodaira-fiber-negative/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e6a02846fa6afe259db4ab47f4cac119fb974b69 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/instruction.md @@ -0,0 +1,296 @@ +# openai/math challenge `LogKodairaFiberNegative` (family 033) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 033 of the release, *Campana's orbifold Iitaka conjecture and logarithmic subadditivity* +(Algebraic and complex geometry). The family as a whole: Proves Campana's orbifold Iitaka subadditivity conjecture for smooth Fujiki-class-$\mathcal C$ manifolds with rational simple-normal-crossing boundaries. For projective fibrations $f:U\to V$ of smooth complex quasi-projective varieties with connected fibers, general fiber $F$, and $\bar\kappa(V)\ge0$, proves Popa's inequality $\bar\kappa(U)\ge\kappa(F)+\max\{\bar\kappa(V),\operatorname{Var}(f)\}$, where variation measures the whole geometric generic fiber. + +The challenge is `LogKodairaFiberNegative`, also at `/opt/openai-math/challenges/LogKodairaFiberNegative.lean`: + +```lean +import Mathlib + +namespace OAI + + + +noncomputable section + +open CategoryTheory AlgebraicGeometry +open scoped TensorProduct + +namespace ReverseLogKodaira + +attribute [local instance] MvPolynomial.gradedAlgebra + +abbrev complexBase : Scheme := Spec (CommRingCat.of ℂ) + +abbrev projectiveGrading (N : ℕ) := MvPolynomial.homogeneousSubmodule (Fin (N + 1)) ℂ + +abbrev complexProjectiveSpace (N : ℕ) : Scheme := Proj (projectiveGrading N) + +def projectiveConstants (N : ℕ) : ℂ →+* projectiveGrading N 0 where + toFun r := ⟨MvPolynomial.C r, MvPolynomial.isHomogeneous_C (Fin (N + 1)) r⟩ + map_zero' := Subtype.ext (map_zero MvPolynomial.C) + map_one' := Subtype.ext (map_one MvPolynomial.C) + map_add' x y := Subtype.ext (map_add MvPolynomial.C x y) + map_mul' x y := Subtype.ext (map_mul MvPolynomial.C x y) + +def complexProjectiveStructure (N : ℕ) : complexProjectiveSpace N ⟶ complexBase := + Proj.toSpecZero (projectiveGrading N) ≫ Spec.map (CommRingCat.ofHom (projectiveConstants N)) + + +structure SmoothProjectiveVariety where + scheme : Scheme + structural : scheme ⟶ complexBase + dimension : ℕ + integral : IsIntegral scheme + smooth : SmoothOfRelativeDimension dimension structural + projective : ∃ (N : ℕ) (i : scheme ⟶ complexProjectiveSpace N), + IsClosedImmersion i ∧ i ≫ complexProjectiveStructure N = structural + +attribute [instance] SmoothProjectiveVariety.integral SmoothProjectiveVariety.smooth + +namespace SmoothProjectiveVariety + +instance (X : SmoothProjectiveVariety) : Smooth X.structural := + SmoothOfRelativeDimension.smooth X.dimension X.structural + + +def globalConstants (X : SmoothProjectiveVariety) : ℂ →+* Γ(X.scheme, ⊤) := + X.structural.appTop.hom.comp (Scheme.ΓSpecIso (CommRingCat.of ℂ)).inv.hom + + +def constants (X : SmoothProjectiveVariety) (U : X.scheme.Opens) : ℂ →+* Γ(X.scheme, U) := + (X.scheme.presheaf.map (homOfLE (le_top (a := U))).op).hom.comp X.globalConstants + +instance (X : SmoothProjectiveVariety) (U : X.scheme.Opens) : Algebra ℂ Γ(X.scheme, U) := + (X.constants U).toAlgebra + +instance (X : SmoothProjectiveVariety) : Nonempty (⊤ : X.scheme.Opens) := + ⟨⟨genericPoint X.scheme, by trivial⟩⟩ + + +def functionFieldConstants (X : SmoothProjectiveVariety) : ℂ →+* X.scheme.functionField := + (X.scheme.germToFunctionField ⊤).hom.comp X.globalConstants + +instance (X : SmoothProjectiveVariety) : Algebra ℂ X.scheme.functionField := + X.functionFieldConstants.toAlgebra + +lemma germ_constants (X : SmoothProjectiveVariety) (U : X.scheme.Opens) [Nonempty U] (c : ℂ) : + algebraMap Γ(X.scheme, U) X.scheme.functionField (algebraMap ℂ Γ(X.scheme, U) c) = + algebraMap ℂ X.scheme.functionField c := by + change X.scheme.presheaf.germ U (genericPoint X.scheme) _ + (X.scheme.presheaf.map (homOfLE (le_top (a := U))).op (X.globalConstants c)) = + X.scheme.presheaf.germ ⊤ (genericPoint X.scheme) _ (X.globalConstants c) + exact X.scheme.presheaf.germ_res_apply (homOfLE le_top) (genericPoint X.scheme) _ _ + +instance (X : SmoothProjectiveVariety) (U : X.scheme.Opens) [Nonempty U] : + IsScalarTower ℂ Γ(X.scheme, U) X.scheme.functionField := + IsScalarTower.of_algebraMap_eq fun c => (X.germ_constants U c).symm + +abbrev RationalCanonical (X : SmoothProjectiveVariety) := + ⋀[X.scheme.functionField]^X.dimension (KaehlerDifferential ℂ X.scheme.functionField) + +abbrev RationalPluriform (X : SmoothProjectiveVariety) (m : ℕ) := + ⨂[X.scheme.functionField]^m X.RationalCanonical + +instance (X : SmoothProjectiveVariety) (m : ℕ) : AddCommGroup (X.RationalPluriform m) := + Module.addCommMonoidToAddCommGroup X.scheme.functionField + +def regularPluriformLattice (X : SmoothProjectiveVariety) (U : X.scheme.affineOpens) + [Nonempty U.1] (m : ℕ) : Submodule Γ(X.scheme, U.1) (X.RationalPluriform m) := + Submodule.span Γ(X.scheme, U.1) <| Set.range fun a : Fin m → Fin X.dimension → Γ(X.scheme, U.1) => + PiTensorProduct.tprod X.scheme.functionField fun j => + exteriorPower.ιMulti X.scheme.functionField X.dimension fun i => + KaehlerDifferential.D ℂ X.scheme.functionField (algebraMap _ _ (a j i)) + + + +def IsCartierIdeal (X : SmoothProjectiveVariety) (I : X.scheme.IdealSheafData) : Prop := + ∀ x : X.scheme, ∃ (U : X.scheme.affineOpens), x ∈ U.1 ∧ + ∃ t : Γ(X.scheme, U.1), t ≠ 0 ∧ I.ideal U = Ideal.span {t} + +structure ReducedSNCBoundary (X : SmoothProjectiveVariety) where + count : ℕ + components : Fin count → X.scheme.IdealSheafData + cartier : ∀ i, X.IsCartierIdeal (components i) + transverse : ∀ S : Finset (Fin count), S.Nonempty → + IsEmpty ((S.sup components).subscheme) ∨ + (S.card ≤ X.dimension ∧ SmoothOfRelativeDimension (X.dimension - S.card) + ((S.sup components).subschemeι ≫ X.structural)) + union_cartier : X.IsCartierIdeal (∏ i, components i) + +namespace ReducedSNCBoundary + +def ideal {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : X.scheme.IdealSheafData := + ∏ i, E.components i + + +def support {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : Set X.scheme := + E.ideal.support + +def IsLogPluriform {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) + (m : ℕ) (s : X.RationalPluriform m) : Prop := + ∀ (U : X.scheme.affineOpens) (_ : Nonempty U.1) (t : Γ(X.scheme, U.1)), + t ≠ 0 → E.ideal.ideal U = Ideal.span {t} → + (algebraMap Γ(X.scheme, U.1) X.scheme.functionField t)^m • s ∈ + X.regularPluriformLattice U m + +lemma isLogPluriform_zero {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) : + E.IsLogPluriform m 0 := by + intro U hU t ht hI + simp only [smul_zero, Submodule.zero_mem] + +lemma isLogPluriform_add {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) + {s r : X.RationalPluriform m} (hs : E.IsLogPluriform m s) (hr : E.IsLogPluriform m r) : + E.IsLogPluriform m (s + r) := by + intro U hU t ht hI + simpa only [smul_add] using (X.regularPluriformLattice U m).add_mem + (hs U hU t ht hI) (hr U hU t ht hI) + +lemma isLogPluriform_smul {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) + (c : ℂ) {s : X.RationalPluriform m} (hs : E.IsLogPluriform m s) : + E.IsLogPluriform m (c • s) := by + intro U hU t ht hI + have h := (X.regularPluriformLattice U m).smul_mem + (algebraMap ℂ Γ(X.scheme, U.1) c) (hs U hU t ht hI) + rw [IsScalarTower.algebraMap_smul Γ(X.scheme, U.1)] at h + rwa [smul_comm c] at h + + + +def sections {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) : + Submodule ℂ (X.RationalPluriform m) where + carrier := E.IsLogPluriform m + zero_mem' := E.isLogPluriform_zero m + add_mem' := E.isLogPluriform_add m + smul_mem' := E.isLogPluriform_smul m + + + +def HasImageDimensionAtLeast {X : SmoothProjectiveVariety} + (E : X.ReducedSNCBoundary) (k : ℕ) : Prop := + ∃ (m : ℕ), 0 < m ∧ ∃ s : X.RationalPluriform m, + s ∈ E.sections m ∧ s ≠ 0 ∧ ∃ r : Fin k → X.scheme.functionField, + AlgebraicIndependent ℂ r ∧ ∀ i, r i • s ∈ E.sections m + + + +def kodaira {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : WithBot ℕ∞ := + ⨆ (k : ℕ) (_ : E.HasImageDimensionAtLeast k), ((k : ℕ∞) : WithBot ℕ∞) + +end ReducedSNCBoundary + + +structure ComplexPoint (X : SmoothProjectiveVariety) where + hom : complexBase ⟶ X.scheme + over_base : hom ≫ X.structural = 𝟙 complexBase + + +def complexBasePoint : complexBase := ⟨⊥, Ideal.isPrime_bot⟩ + + +def ComplexPoint.point {X : SmoothProjectiveVariety} (y : X.ComplexPoint) : X.scheme := + y.hom complexBasePoint + + +def ReducedSNCBoundary.complement {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : + X.scheme.Opens := E.ideal.support.compl + + + +structure BoundaryFibration (X Y : SmoothProjectiveVariety) + (E : X.ReducedSNCBoundary) (D : Y.ReducedSNCBoundary) where + hom : X.scheme ⟶ Y.scheme + over_base : hom ≫ Y.structural = X.structural + surjective : Surjective hom + connected : ∀ y : Y.ComplexPoint, ConnectedSpace ↥(CategoryTheory.Limits.pullback hom y.hom) + support : hom ⁻¹' D.support ⊆ E.support + + + +structure StratumSmoothFibration (X Y : SmoothProjectiveVariety) + (E : X.ReducedSNCBoundary) (D : Y.ReducedSNCBoundary) + extends BoundaryFibration X Y E D where + smooth : Smooth (hom.resLE D.complement (hom ⁻¹ᵁ D.complement) le_rfl) + strata : ∀ (S : Finset (Fin E.count)), S.Nonempty → + Smooth (((S.sup E.components).subschemeι ≫ hom).resLE D.complement + (((S.sup E.components).subschemeι ≫ hom) ⁻¹ᵁ D.complement) le_rfl) + + + +structure FiberModel {X Y : SmoothProjectiveVariety} {E : X.ReducedSNCBoundary} + {D : Y.ReducedSNCBoundary} (f : BoundaryFibration X Y E D) (y : Y.ComplexPoint) where + variety : SmoothProjectiveVariety + inclusion : variety.scheme ⟶ X.scheme + square : IsPullback inclusion variety.structural f.hom y.hom + boundary : variety.ReducedSNCBoundary + boundary_pullback : boundary.ideal = E.ideal.comap inclusion + + + +def VeryGenerally (Y : SmoothProjectiveVariety) (P : Y.ComplexPoint → Prop) : Prop := + ∃ Z : ℕ → TopologicalSpace.Closeds Y.scheme, + (∀ n, Z n ≠ ⊤) ∧ ∀ y : Y.ComplexPoint, (∀ n, y.point ∉ Z n) → P y + +end SmoothProjectiveVariety + +end ReverseLogKodaira + +namespace ReverseLogKodaira.SmoothProjectiveVariety + +theorem veryGenerally_fiber_negative_branch + {X Y : SmoothProjectiveVariety} {E : X.ReducedSNCBoundary} {D : Y.ReducedSNCBoundary} + (f : StratumSmoothFibration X Y E D) : + VeryGenerally Y fun y => y.point ∈ D.complement ∧ + ∀ F : FiberModel f.toBoundaryFibration y, F.boundary.kodaira = ⊥ → + E.kodaira = D.kodaira + F.boundary.kodaira ∧ + ∀ (m : ℕ), 0 < m → ∀ s : X.RationalPluriform m, s ∈ E.sections m → s = 0 := by sorry + +end ReverseLogKodaira.SmoothProjectiveVariety + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/LogKodairaFiberNegative.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ReverseLogKodaira.SmoothProjectiveVariety.veryGenerally_fiber_negative_branch` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/log-kodaira-fiber-negative/solution/closure.txt b/tasks/log-kodaira-fiber-negative/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ac4df0d18e512e5c46ca9727189fb4357b3c589c --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/solution/closure.txt @@ -0,0 +1,14 @@ +OAI.AlgebraicGeometry.LogKodaira.Adjunction +OAI.AlgebraicGeometry.LogKodaira.BaseChange +OAI.AlgebraicGeometry.LogKodaira.Basic +OAI.AlgebraicGeometry.LogKodaira.BoundaryPullback +OAI.AlgebraicGeometry.LogKodaira.FiberCharts +OAI.AlgebraicGeometry.LogKodaira.FiberNegative +OAI.AlgebraicGeometry.LogKodaira.GlobalSpecialization +OAI.AlgebraicGeometry.LogKodaira.LatticeBaseChange +OAI.AlgebraicGeometry.LogKodaira.LocalCanonical +OAI.AlgebraicGeometry.LogKodaira.LogLattice +OAI.AlgebraicGeometry.LogKodaira.NonzeroFiber +OAI.AlgebraicGeometry.LogKodaira.RelativeCanonical +OAI.AlgebraicGeometry.LogKodaira.SmoothCharts +OAI.AlgebraicGeometry.LogKodaira.Specialization diff --git a/tasks/log-kodaira-fiber-negative/solution/reference.py b/tasks/log-kodaira-fiber-negative/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/log-kodaira-fiber-negative/solution/solve.sh b/tasks/log-kodaira-fiber-negative/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a56016adff9eea33aa69cf8dd99c23bc8e83c4ef --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of LogKodairaFiberNegative, i.e. module OAI.AlgebraicGeometry.LogKodaira.FiberNegative and the +# 14 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.AlgebraicGeometry.LogKodaira.FiberNegative /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of LogKodairaFiberNegative" diff --git a/tasks/log-kodaira-fiber-negative/task.toml b/tasks/log-kodaira-fiber-negative/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d1a0163fbcd98bceecd963de4f5ea0eccc961bd8 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/log-kodaira-fiber-negative" +version = "1.0.0" +description = "Prove LogKodairaFiberNegative (openai/math family 033: Campana's orbifold Iitaka conjecture and logarithmic subadditivity) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/LogKodairaFiberNegative.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "LogKodairaFiberNegative" +family = "033" +family_title = "Campana's orbifold Iitaka conjecture and logarithmic subadditivity" +subject = "Algebraic and complex geometry" +theorems = ["OAI.ReverseLogKodaira.SmoothProjectiveVariety.veryGenerally_fiber_negative_branch"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.AlgebraicGeometry.LogKodaira.FiberNegative" +reference_modules = 14 +reference_lean_bytes = 176794 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 813 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11859 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/log-kodaira-fiber-negative/tests/Challenge.lean b/tasks/log-kodaira-fiber-negative/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..399a9de26676b0fcf9e7e89ae6b5e31474109111 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/tests/Challenge.lean @@ -0,0 +1,245 @@ +import Mathlib + +namespace OAI + + + +noncomputable section + +open CategoryTheory AlgebraicGeometry +open scoped TensorProduct + +namespace ReverseLogKodaira + +attribute [local instance] MvPolynomial.gradedAlgebra + +abbrev complexBase : Scheme := Spec (CommRingCat.of ℂ) + +abbrev projectiveGrading (N : ℕ) := MvPolynomial.homogeneousSubmodule (Fin (N + 1)) ℂ + +abbrev complexProjectiveSpace (N : ℕ) : Scheme := Proj (projectiveGrading N) + +def projectiveConstants (N : ℕ) : ℂ →+* projectiveGrading N 0 where + toFun r := ⟨MvPolynomial.C r, MvPolynomial.isHomogeneous_C (Fin (N + 1)) r⟩ + map_zero' := Subtype.ext (map_zero MvPolynomial.C) + map_one' := Subtype.ext (map_one MvPolynomial.C) + map_add' x y := Subtype.ext (map_add MvPolynomial.C x y) + map_mul' x y := Subtype.ext (map_mul MvPolynomial.C x y) + +def complexProjectiveStructure (N : ℕ) : complexProjectiveSpace N ⟶ complexBase := + Proj.toSpecZero (projectiveGrading N) ≫ Spec.map (CommRingCat.ofHom (projectiveConstants N)) + + +structure SmoothProjectiveVariety where + scheme : Scheme + structural : scheme ⟶ complexBase + dimension : ℕ + integral : IsIntegral scheme + smooth : SmoothOfRelativeDimension dimension structural + projective : ∃ (N : ℕ) (i : scheme ⟶ complexProjectiveSpace N), + IsClosedImmersion i ∧ i ≫ complexProjectiveStructure N = structural + +attribute [instance] SmoothProjectiveVariety.integral SmoothProjectiveVariety.smooth + +namespace SmoothProjectiveVariety + +instance (X : SmoothProjectiveVariety) : Smooth X.structural := + SmoothOfRelativeDimension.smooth X.dimension X.structural + + +def globalConstants (X : SmoothProjectiveVariety) : ℂ →+* Γ(X.scheme, ⊤) := + X.structural.appTop.hom.comp (Scheme.ΓSpecIso (CommRingCat.of ℂ)).inv.hom + + +def constants (X : SmoothProjectiveVariety) (U : X.scheme.Opens) : ℂ →+* Γ(X.scheme, U) := + (X.scheme.presheaf.map (homOfLE (le_top (a := U))).op).hom.comp X.globalConstants + +instance (X : SmoothProjectiveVariety) (U : X.scheme.Opens) : Algebra ℂ Γ(X.scheme, U) := + (X.constants U).toAlgebra + +instance (X : SmoothProjectiveVariety) : Nonempty (⊤ : X.scheme.Opens) := + ⟨⟨genericPoint X.scheme, by trivial⟩⟩ + + +def functionFieldConstants (X : SmoothProjectiveVariety) : ℂ →+* X.scheme.functionField := + (X.scheme.germToFunctionField ⊤).hom.comp X.globalConstants + +instance (X : SmoothProjectiveVariety) : Algebra ℂ X.scheme.functionField := + X.functionFieldConstants.toAlgebra + +lemma germ_constants (X : SmoothProjectiveVariety) (U : X.scheme.Opens) [Nonempty U] (c : ℂ) : + algebraMap Γ(X.scheme, U) X.scheme.functionField (algebraMap ℂ Γ(X.scheme, U) c) = + algebraMap ℂ X.scheme.functionField c := by + change X.scheme.presheaf.germ U (genericPoint X.scheme) _ + (X.scheme.presheaf.map (homOfLE (le_top (a := U))).op (X.globalConstants c)) = + X.scheme.presheaf.germ ⊤ (genericPoint X.scheme) _ (X.globalConstants c) + exact X.scheme.presheaf.germ_res_apply (homOfLE le_top) (genericPoint X.scheme) _ _ + +instance (X : SmoothProjectiveVariety) (U : X.scheme.Opens) [Nonempty U] : + IsScalarTower ℂ Γ(X.scheme, U) X.scheme.functionField := + IsScalarTower.of_algebraMap_eq fun c => (X.germ_constants U c).symm + +abbrev RationalCanonical (X : SmoothProjectiveVariety) := + ⋀[X.scheme.functionField]^X.dimension (KaehlerDifferential ℂ X.scheme.functionField) + +abbrev RationalPluriform (X : SmoothProjectiveVariety) (m : ℕ) := + ⨂[X.scheme.functionField]^m X.RationalCanonical + +instance (X : SmoothProjectiveVariety) (m : ℕ) : AddCommGroup (X.RationalPluriform m) := + Module.addCommMonoidToAddCommGroup X.scheme.functionField + +def regularPluriformLattice (X : SmoothProjectiveVariety) (U : X.scheme.affineOpens) + [Nonempty U.1] (m : ℕ) : Submodule Γ(X.scheme, U.1) (X.RationalPluriform m) := + Submodule.span Γ(X.scheme, U.1) <| Set.range fun a : Fin m → Fin X.dimension → Γ(X.scheme, U.1) => + PiTensorProduct.tprod X.scheme.functionField fun j => + exteriorPower.ιMulti X.scheme.functionField X.dimension fun i => + KaehlerDifferential.D ℂ X.scheme.functionField (algebraMap _ _ (a j i)) + + + +def IsCartierIdeal (X : SmoothProjectiveVariety) (I : X.scheme.IdealSheafData) : Prop := + ∀ x : X.scheme, ∃ (U : X.scheme.affineOpens), x ∈ U.1 ∧ + ∃ t : Γ(X.scheme, U.1), t ≠ 0 ∧ I.ideal U = Ideal.span {t} + +structure ReducedSNCBoundary (X : SmoothProjectiveVariety) where + count : ℕ + components : Fin count → X.scheme.IdealSheafData + cartier : ∀ i, X.IsCartierIdeal (components i) + transverse : ∀ S : Finset (Fin count), S.Nonempty → + IsEmpty ((S.sup components).subscheme) ∨ + (S.card ≤ X.dimension ∧ SmoothOfRelativeDimension (X.dimension - S.card) + ((S.sup components).subschemeι ≫ X.structural)) + union_cartier : X.IsCartierIdeal (∏ i, components i) + +namespace ReducedSNCBoundary + +def ideal {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : X.scheme.IdealSheafData := + ∏ i, E.components i + + +def support {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : Set X.scheme := + E.ideal.support + +def IsLogPluriform {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) + (m : ℕ) (s : X.RationalPluriform m) : Prop := + ∀ (U : X.scheme.affineOpens) (_ : Nonempty U.1) (t : Γ(X.scheme, U.1)), + t ≠ 0 → E.ideal.ideal U = Ideal.span {t} → + (algebraMap Γ(X.scheme, U.1) X.scheme.functionField t)^m • s ∈ + X.regularPluriformLattice U m + +lemma isLogPluriform_zero {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) : + E.IsLogPluriform m 0 := by + intro U hU t ht hI + simp only [smul_zero, Submodule.zero_mem] + +lemma isLogPluriform_add {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) + {s r : X.RationalPluriform m} (hs : E.IsLogPluriform m s) (hr : E.IsLogPluriform m r) : + E.IsLogPluriform m (s + r) := by + intro U hU t ht hI + simpa only [smul_add] using (X.regularPluriformLattice U m).add_mem + (hs U hU t ht hI) (hr U hU t ht hI) + +lemma isLogPluriform_smul {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) + (c : ℂ) {s : X.RationalPluriform m} (hs : E.IsLogPluriform m s) : + E.IsLogPluriform m (c • s) := by + intro U hU t ht hI + have h := (X.regularPluriformLattice U m).smul_mem + (algebraMap ℂ Γ(X.scheme, U.1) c) (hs U hU t ht hI) + rw [IsScalarTower.algebraMap_smul Γ(X.scheme, U.1)] at h + rwa [smul_comm c] at h + + + +def sections {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) (m : ℕ) : + Submodule ℂ (X.RationalPluriform m) where + carrier := E.IsLogPluriform m + zero_mem' := E.isLogPluriform_zero m + add_mem' := E.isLogPluriform_add m + smul_mem' := E.isLogPluriform_smul m + + + +def HasImageDimensionAtLeast {X : SmoothProjectiveVariety} + (E : X.ReducedSNCBoundary) (k : ℕ) : Prop := + ∃ (m : ℕ), 0 < m ∧ ∃ s : X.RationalPluriform m, + s ∈ E.sections m ∧ s ≠ 0 ∧ ∃ r : Fin k → X.scheme.functionField, + AlgebraicIndependent ℂ r ∧ ∀ i, r i • s ∈ E.sections m + + + +def kodaira {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : WithBot ℕ∞ := + ⨆ (k : ℕ) (_ : E.HasImageDimensionAtLeast k), ((k : ℕ∞) : WithBot ℕ∞) + +end ReducedSNCBoundary + + +structure ComplexPoint (X : SmoothProjectiveVariety) where + hom : complexBase ⟶ X.scheme + over_base : hom ≫ X.structural = 𝟙 complexBase + + +def complexBasePoint : complexBase := ⟨⊥, Ideal.isPrime_bot⟩ + + +def ComplexPoint.point {X : SmoothProjectiveVariety} (y : X.ComplexPoint) : X.scheme := + y.hom complexBasePoint + + +def ReducedSNCBoundary.complement {X : SmoothProjectiveVariety} (E : X.ReducedSNCBoundary) : + X.scheme.Opens := E.ideal.support.compl + + + +structure BoundaryFibration (X Y : SmoothProjectiveVariety) + (E : X.ReducedSNCBoundary) (D : Y.ReducedSNCBoundary) where + hom : X.scheme ⟶ Y.scheme + over_base : hom ≫ Y.structural = X.structural + surjective : Surjective hom + connected : ∀ y : Y.ComplexPoint, ConnectedSpace ↥(CategoryTheory.Limits.pullback hom y.hom) + support : hom ⁻¹' D.support ⊆ E.support + + + +structure StratumSmoothFibration (X Y : SmoothProjectiveVariety) + (E : X.ReducedSNCBoundary) (D : Y.ReducedSNCBoundary) + extends BoundaryFibration X Y E D where + smooth : Smooth (hom.resLE D.complement (hom ⁻¹ᵁ D.complement) le_rfl) + strata : ∀ (S : Finset (Fin E.count)), S.Nonempty → + Smooth (((S.sup E.components).subschemeι ≫ hom).resLE D.complement + (((S.sup E.components).subschemeι ≫ hom) ⁻¹ᵁ D.complement) le_rfl) + + + +structure FiberModel {X Y : SmoothProjectiveVariety} {E : X.ReducedSNCBoundary} + {D : Y.ReducedSNCBoundary} (f : BoundaryFibration X Y E D) (y : Y.ComplexPoint) where + variety : SmoothProjectiveVariety + inclusion : variety.scheme ⟶ X.scheme + square : IsPullback inclusion variety.structural f.hom y.hom + boundary : variety.ReducedSNCBoundary + boundary_pullback : boundary.ideal = E.ideal.comap inclusion + + + +def VeryGenerally (Y : SmoothProjectiveVariety) (P : Y.ComplexPoint → Prop) : Prop := + ∃ Z : ℕ → TopologicalSpace.Closeds Y.scheme, + (∀ n, Z n ≠ ⊤) ∧ ∀ y : Y.ComplexPoint, (∀ n, y.point ∉ Z n) → P y + +end SmoothProjectiveVariety + +end ReverseLogKodaira + +namespace ReverseLogKodaira.SmoothProjectiveVariety + +theorem veryGenerally_fiber_negative_branch + {X Y : SmoothProjectiveVariety} {E : X.ReducedSNCBoundary} {D : Y.ReducedSNCBoundary} + (f : StratumSmoothFibration X Y E D) : + VeryGenerally Y fun y => y.point ∈ D.complement ∧ + ∀ F : FiberModel f.toBoundaryFibration y, F.boundary.kodaira = ⊥ → + E.kodaira = D.kodaira + F.boundary.kodaira ∧ + ∀ (m : ℕ), 0 < m → ∀ s : X.RationalPluriform m, s ∈ E.sections m → s = 0 := by sorry + +end ReverseLogKodaira.SmoothProjectiveVariety + +end + +end OAI diff --git a/tasks/log-kodaira-fiber-negative/tests/grade.py b/tasks/log-kodaira-fiber-negative/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/log-kodaira-fiber-negative/tests/task.json b/tasks/log-kodaira-fiber-negative/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4e176e6004e51dd506d4a015fc692c3705f32641 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "LogKodairaFiberNegative", + "comparator": { + "theorem_names": [ + "OAI.ReverseLogKodaira.SmoothProjectiveVariety.veryGenerally_fiber_negative_branch" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10959 +} \ No newline at end of file diff --git a/tasks/log-kodaira-fiber-negative/tests/test.sh b/tasks/log-kodaira-fiber-negative/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/log-kodaira-fiber-negative/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/mahler-conjecture/environment/Dockerfile b/tasks/mahler-conjecture/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/mahler-conjecture/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/mahler-conjecture/environment/fetch_mathlib.sh b/tasks/mahler-conjecture/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/mahler-conjecture/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/mahler-conjecture/environment/lake-manifest.json b/tasks/mahler-conjecture/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/mahler-conjecture/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/mahler-conjecture/environment/lakefile.lean b/tasks/mahler-conjecture/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/mahler-conjecture/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/mahler-conjecture/environment/lean_setup.sh b/tasks/mahler-conjecture/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/mahler-conjecture/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/mahler-conjecture/environment/pack_submission.py b/tasks/mahler-conjecture/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/mahler-conjecture/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/mahler-conjecture/instruction.md b/tasks/mahler-conjecture/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..feddd3d5fea14ecce5b39574c76fbdfc7e337ffe --- /dev/null +++ b/tasks/mahler-conjecture/instruction.md @@ -0,0 +1,77 @@ +# openai/math challenge `MahlerConjecture` (family 087) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 087 of the release, *The Mahler conjectures and symplectic width* +(Convex and metric geometry). The family as a whole: Resolves the symmetric and nonsymmetric geometric Mahler conjectures in every dimension, with Hanner polytopes and simplices as the respective volume-product minimizers and all equality cases classified. The corresponding sharp functional Mahler inequalities also hold. For $n\ge2$, every symmetric polar product $K\times K^\circ$ in dimension $2n$ has Gromov width $4$. + +The challenge is `MahlerConjecture`, also at `/opt/openai-math/challenges/MahlerConjecture.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace SymmetricMahler + +variable {I : Type*} [Fintype I] + +def coordinatePolar (K : Set (I → ℝ)) : Set (I → ℝ) := + {p | ∀ v ∈ K, (∑ i, p i*v i) ≤ 1} + +noncomputable section +open Set MeasureTheory + +theorem symmetric_mahler {n : ℕ} (hn : 1 ≤ n) + {K : Set (Fin n → ℝ)} (hK : IsCompact K) (hconv : Convex ℝ K) + (hsym : ∀ x ∈ K, -x ∈ K) (hint : (interior K).Nonempty) : + (4:ℝ)^n/(Nat.factorial n:ℝ) ≤ + (volume K).toReal*(volume (coordinatePolar K)).toReal := by + sorry + +end + +end SymmetricMahler + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MahlerConjecture.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SymmetricMahler.symmetric_mahler` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/mahler-conjecture/solution/closure.txt b/tasks/mahler-conjecture/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..942422ca7f7b1d18be5b8ecb0866c90c60657da7 --- /dev/null +++ b/tasks/mahler-conjecture/solution/closure.txt @@ -0,0 +1,229 @@ +OAI.Analysis.Mahler.ActualFiniteStrips +OAI.Analysis.Mahler.ActualVerticalPrimitive +OAI.Analysis.Mahler.AngularEndpoint +OAI.Analysis.Mahler.AngularFibers +OAI.Analysis.Mahler.AngularGeometry +OAI.Analysis.Mahler.AngularIntegrals +OAI.Analysis.Mahler.AngularStrip +OAI.Analysis.Mahler.BasisContinuousWedge +OAI.Analysis.Mahler.BoundaryJet +OAI.Analysis.Mahler.ChartExtension +OAI.Analysis.Mahler.ChartStokes +OAI.Analysis.Mahler.ClosedBoundaryStokes +OAI.Analysis.Mahler.ClosedWedgePowers +OAI.Analysis.Mahler.CompactFluxDifferentiation +OAI.Analysis.Mahler.CompactIntegral +OAI.Analysis.Mahler.ComplexCoordinates +OAI.Analysis.Mahler.ComplexStripMap +OAI.Analysis.Mahler.ComplexVolume +OAI.Analysis.Mahler.ConformalInjectivity +OAI.Analysis.Mahler.ConformalInverse +OAI.Analysis.Mahler.ConformalRadialRegularity +OAI.Analysis.Mahler.ConformalSeries +OAI.Analysis.Mahler.ContinuousWedge +OAI.Analysis.Mahler.ContinuousWedgeDerivative +OAI.Analysis.Mahler.ConvexApproximation +OAI.Analysis.Mahler.ConvexCompletion +OAI.Analysis.Mahler.ConvexENNRealTransfer +OAI.Analysis.Mahler.ConvexGeometry +OAI.Analysis.Mahler.ConvexMain +OAI.Analysis.Mahler.ConvexMassReduction +OAI.Analysis.Mahler.ConvexPolarBody +OAI.Analysis.Mahler.ConvexSequence +OAI.Analysis.Mahler.ConvexTransfer +OAI.Analysis.Mahler.CoordinateAnnulus +OAI.Analysis.Mahler.CoordinateBall +OAI.Analysis.Mahler.CoordinateEuclidean +OAI.Analysis.Mahler.CoordinateSphere +OAI.Analysis.Mahler.CovectorVolume +OAI.Analysis.Mahler.DCForms +OAI.Analysis.Mahler.DCRegularity +OAI.Analysis.Mahler.DilationTransport +OAI.Analysis.Mahler.ErrorBound +OAI.Analysis.Mahler.EuclideanMassDensity +OAI.Analysis.Mahler.EuclideanRegularLevels +OAI.Analysis.Mahler.EuclideanSpecialMap +OAI.Analysis.Mahler.ExactFormCoordinates +OAI.Analysis.Mahler.ExactSphereFluxBridge +OAI.Analysis.Mahler.ExactSphereStokes +OAI.Analysis.Mahler.ExteriorAlternatization +OAI.Analysis.Mahler.ExteriorCoefficient +OAI.Analysis.Mahler.ExteriorCoordinates +OAI.Analysis.Mahler.ExteriorDirectional +OAI.Analysis.Mahler.ExteriorFlux +OAI.Analysis.Mahler.ExteriorHessian +OAI.Analysis.Mahler.ExteriorLeibnizTwo +OAI.Analysis.Mahler.ExteriorPower +OAI.Analysis.Mahler.FiberEndpoint +OAI.Analysis.Mahler.FiberHeight +OAI.Analysis.Mahler.FiberPreimageEndpoint +OAI.Analysis.Mahler.FiberPrimitive +OAI.Analysis.Mahler.FiniteStripReduction +OAI.Analysis.Mahler.FiniteStrips +OAI.Analysis.Mahler.FluxVariation +OAI.Analysis.Mahler.FormLocalization +OAI.Analysis.Mahler.FormStokes +OAI.Analysis.Mahler.GlobalFiberParametrization +OAI.Analysis.Mahler.GlobalPlanarBound +OAI.Analysis.Mahler.GlobalPlanarMonotonicity +OAI.Analysis.Mahler.GlobalVerticalGeometry +OAI.Analysis.Mahler.HalfspaceStokes +OAI.Analysis.Mahler.HemisphereArea +OAI.Analysis.Mahler.HemisphereChart +OAI.Analysis.Mahler.HemisphereFlux +OAI.Analysis.Mahler.HemisphereJacobian +OAI.Analysis.Mahler.HemisphereMeasure +OAI.Analysis.Mahler.Hessian +OAI.Analysis.Mahler.HolomorphicLogC2 +OAI.Analysis.Mahler.HolomorphicRegularity +OAI.Analysis.Mahler.HomogeneousCircleIntegral +OAI.Analysis.Mahler.HomogeneousDeformation +OAI.Analysis.Mahler.HomogeneousDensityVariation +OAI.Analysis.Mahler.HomogeneousEndpoint +OAI.Analysis.Mahler.HomogeneousFlux +OAI.Analysis.Mahler.HomogeneousFluxDifferentiation +OAI.Analysis.Mahler.HomogeneousFluxFTC +OAI.Analysis.Mahler.HomogeneousMassAssembly +OAI.Analysis.Mahler.HomogeneousPrimitiveRegularity +OAI.Analysis.Mahler.HomogeneousSmoothForms +OAI.Analysis.Mahler.HomogeneousSphereIntegral +OAI.Analysis.Mahler.HomogeneousTransgression +OAI.Analysis.Mahler.HomogeneousTransgressionFTC +OAI.Analysis.Mahler.HomogeneousVariationCoefficient +OAI.Analysis.Mahler.HorizontalForms +OAI.Analysis.Mahler.ImplicitAngle +OAI.Analysis.Mahler.InteriorStokes +OAI.Analysis.Mahler.InverseRadialRegularity +OAI.Analysis.Mahler.Jacobian +OAI.Analysis.Mahler.LevelFace +OAI.Analysis.Mahler.LevelForms +OAI.Analysis.Mahler.LogDilation +OAI.Analysis.Mahler.LogJet +OAI.Analysis.Mahler.LogNormSquare +OAI.Analysis.Mahler.LogScalarJet +OAI.Analysis.Mahler.LogUniform +OAI.Analysis.Mahler.MainTheorem +OAI.Analysis.Mahler.MassLimit +OAI.Analysis.Mahler.MassTarget +OAI.Analysis.Mahler.MatrixExteriorPower +OAI.Analysis.Mahler.MatrixHessian +OAI.Analysis.Mahler.NormExteriorPower +OAI.Analysis.Mahler.NormSquareForm +OAI.Analysis.Mahler.NormSquareJet +OAI.Analysis.Mahler.OpenExteriorNormalization +OAI.Analysis.Mahler.OpenHessian +OAI.Analysis.Mahler.OrientedChartIntegral +OAI.Analysis.Mahler.OrientedSphereDensity +OAI.Analysis.Mahler.PairExteriorBridge +OAI.Analysis.Mahler.PairTransgression +OAI.Analysis.Mahler.PlanarDensity +OAI.Analysis.Mahler.PlanarErrorRate +OAI.Analysis.Mahler.PlanarEstimates +OAI.Analysis.Mahler.PlanarIntegralRegularity +OAI.Analysis.Mahler.PlanarRegularity +OAI.Analysis.Mahler.PlanarSymmetry +OAI.Analysis.Mahler.Positivity +OAI.Analysis.Mahler.PowerTransgression +OAI.Analysis.Mahler.PrimitiveBound +OAI.Analysis.Mahler.PrimitiveEquality +OAI.Analysis.Mahler.PrimitiveRegularity +OAI.Analysis.Mahler.PullbackRegularity +OAI.Analysis.Mahler.PunctureCutoff +OAI.Analysis.Mahler.PuncturedBallStokes +OAI.Analysis.Mahler.PuncturedSublevelStokes +OAI.Analysis.Mahler.RadialBridge +OAI.Analysis.Mahler.RadialPrimitiveDeriv +OAI.Analysis.Mahler.RawAlternatingCalculus +OAI.Analysis.Mahler.RawAlternationDerivative +OAI.Analysis.Mahler.RawClosedPower +OAI.Analysis.Mahler.RawClosedProduct +OAI.Analysis.Mahler.RawCoefficientDerivative +OAI.Analysis.Mahler.RawExteriorPower +OAI.Analysis.Mahler.RawReindexedDerivative +OAI.Analysis.Mahler.RealLogBridge +OAI.Analysis.Mahler.ReferencePole +OAI.Analysis.Mahler.ReferencePoleFrame +OAI.Analysis.Mahler.ReferenceSphere +OAI.Analysis.Mahler.ReferenceSphereIntegral +OAI.Analysis.Mahler.RegularBoundaryAtlas +OAI.Analysis.Mahler.RegularChartStokes +OAI.Analysis.Mahler.RegularLevelCharts +OAI.Analysis.Mahler.RegularMassReduction +OAI.Analysis.Mahler.RegularPartition +OAI.Analysis.Mahler.RegularStokesAssembly +OAI.Analysis.Mahler.RegularSublevel +OAI.Analysis.Mahler.RescaledHolomorphic +OAI.Analysis.Mahler.RescaledMassMap +OAI.Analysis.Mahler.RescalingEstimates +OAI.Analysis.Mahler.ShellRegularity +OAI.Analysis.Mahler.SineBound +OAI.Analysis.Mahler.SmallSphereLimits +OAI.Analysis.Mahler.SourceBoundaryIntegral +OAI.Analysis.Mahler.SourceCanonicalMeasure +OAI.Analysis.Mahler.SourceCoordinateExterior +OAI.Analysis.Mahler.SourceCoordinateForms +OAI.Analysis.Mahler.SourceCoordinateMeasure +OAI.Analysis.Mahler.SourceExteriorDerivative +OAI.Analysis.Mahler.SourceFluxCoordinates +OAI.Analysis.Mahler.SourceFluxRegularity +OAI.Analysis.Mahler.SourceFullExterior +OAI.Analysis.Mahler.SourceHomogeneous +OAI.Analysis.Mahler.SourceLevelFlux +OAI.Analysis.Mahler.SourceLogC2 +OAI.Analysis.Mahler.SourcePrimitiveStokes +OAI.Analysis.Mahler.SourceRadiusFlux +OAI.Analysis.Mahler.SourceRawCoefficient +OAI.Analysis.Mahler.SourceRawJets +OAI.Analysis.Mahler.SourceRawOrientation +OAI.Analysis.Mahler.SourceRealExterior +OAI.Analysis.Mahler.SourceRegularFlux +OAI.Analysis.Mahler.SourceRegularLimit +OAI.Analysis.Mahler.SourceRegularMass +OAI.Analysis.Mahler.SourceRescaling +OAI.Analysis.Mahler.SourceSphereLimit +OAI.Analysis.Mahler.SourceStokes +OAI.Analysis.Mahler.SourceTopCoordinates +OAI.Analysis.Mahler.SpecialJacobian +OAI.Analysis.Mahler.SpecialLeadingTerm +OAI.Analysis.Mahler.SpecialMassBridge +OAI.Analysis.Mahler.SpecialMassHypotheses +OAI.Analysis.Mahler.SpecialSourceMass +OAI.Analysis.Mahler.SphereAreaTransport +OAI.Analysis.Mahler.SphereCoordinateIntegral +OAI.Analysis.Mahler.SphereDensityBridge +OAI.Analysis.Mahler.SphereDensityRestriction +OAI.Analysis.Mahler.SphereFlux +OAI.Analysis.Mahler.SphereFluxDifferentiation +OAI.Analysis.Mahler.SphereFluxIntegral +OAI.Analysis.Mahler.SphereFluxLimit +OAI.Analysis.Mahler.SphereForms +OAI.Analysis.Mahler.SphereNormalization +OAI.Analysis.Mahler.SphereOrientation +OAI.Analysis.Mahler.SphereRadius +OAI.Analysis.Mahler.SphereTransport +OAI.Analysis.Mahler.SphereVolumeOrientation +OAI.Analysis.Mahler.StripCompactSublevels +OAI.Analysis.Mahler.StripDifferential +OAI.Analysis.Mahler.StripGeometry +OAI.Analysis.Mahler.StripJacobian +OAI.Analysis.Mahler.StripLevelGeometry +OAI.Analysis.Mahler.StripMassExhaustion +OAI.Analysis.Mahler.StripRankGeometry +OAI.Analysis.Mahler.StripRegularLevels +OAI.Analysis.Mahler.StripRegularValues +OAI.Analysis.Mahler.StripSublevelTopology +OAI.Analysis.Mahler.StripVolume +OAI.Analysis.Mahler.TailIntegral +OAI.Analysis.Mahler.UniformError +OAI.Analysis.Mahler.UniformJet +OAI.Analysis.Mahler.UnitaryReference +OAI.Analysis.Mahler.VerticalRadius +OAI.Analysis.Mahler.VerticalSpeed +OAI.Analysis.Mahler.WedgeAlgebra +OAI.Analysis.Mahler.WedgeAssociativity +OAI.Analysis.Mahler.WedgeCalculus +OAI.Analysis.Mahler.WedgeDecomposition +OAI.Analysis.Mahler.WedgeEven +OAI.Analysis.Mahler.WedgeOne +OAI.Analysis.Mahler.WedgeTwoDifferentialAlgebra +OAI.Analysis.Mahler.WedgeUnit diff --git a/tasks/mahler-conjecture/solution/reference.py b/tasks/mahler-conjecture/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/mahler-conjecture/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/mahler-conjecture/solution/solve.sh b/tasks/mahler-conjecture/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4f768b755218151c175af77c99695b4d5789d87f --- /dev/null +++ b/tasks/mahler-conjecture/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MahlerConjecture, i.e. module OAI.Analysis.Mahler.MainTheorem and the +# 229 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Mahler.MainTheorem /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MahlerConjecture" diff --git a/tasks/mahler-conjecture/task.toml b/tasks/mahler-conjecture/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..77127cdb347a620b2ccba9d81def1f0ad35b111d --- /dev/null +++ b/tasks/mahler-conjecture/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/mahler-conjecture" +version = "1.0.0" +description = "Prove MahlerConjecture (openai/math family 087: The Mahler conjectures and symplectic width) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MahlerConjecture.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MahlerConjecture" +family = "087" +family_title = "The Mahler conjectures and symplectic width" +subject = "Convex and metric geometry" +theorems = ["OAI.SymmetricMahler.symmetric_mahler"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Mahler.MainTheorem" +reference_modules = 229 +reference_lean_bytes = 995887 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 968 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12596 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/mahler-conjecture/tests/Challenge.lean b/tasks/mahler-conjecture/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bb8fd407424ca2e0a71dc34fa6d60cf8ce84bd8d --- /dev/null +++ b/tasks/mahler-conjecture/tests/Challenge.lean @@ -0,0 +1,26 @@ +import Mathlib + +namespace OAI + +namespace SymmetricMahler + +variable {I : Type*} [Fintype I] + +def coordinatePolar (K : Set (I → ℝ)) : Set (I → ℝ) := + {p | ∀ v ∈ K, (∑ i, p i*v i) ≤ 1} + +noncomputable section +open Set MeasureTheory + +theorem symmetric_mahler {n : ℕ} (hn : 1 ≤ n) + {K : Set (Fin n → ℝ)} (hK : IsCompact K) (hconv : Convex ℝ K) + (hsym : ∀ x ∈ K, -x ∈ K) (hint : (interior K).Nonempty) : + (4:ℝ)^n/(Nat.factorial n:ℝ) ≤ + (volume K).toReal*(volume (coordinatePolar K)).toReal := by + sorry + +end + +end SymmetricMahler + +end OAI diff --git a/tasks/mahler-conjecture/tests/grade.py b/tasks/mahler-conjecture/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/mahler-conjecture/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mahler-conjecture/tests/task.json b/tasks/mahler-conjecture/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3bb7877557e49e1c15b04dbd95700d8a1fc80320 --- /dev/null +++ b/tasks/mahler-conjecture/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MahlerConjecture", + "comparator": { + "theorem_names": [ + "OAI.SymmetricMahler.symmetric_mahler" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11696 +} \ No newline at end of file diff --git a/tasks/mahler-conjecture/tests/test.sh b/tasks/mahler-conjecture/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/mahler-conjecture/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/markov-type/environment/Dockerfile b/tasks/markov-type/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/markov-type/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/markov-type/environment/fetch_mathlib.sh b/tasks/markov-type/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/markov-type/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/markov-type/environment/lake-manifest.json b/tasks/markov-type/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/markov-type/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/markov-type/environment/lakefile.lean b/tasks/markov-type/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/markov-type/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/markov-type/environment/lean_setup.sh b/tasks/markov-type/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/markov-type/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/markov-type/environment/pack_submission.py b/tasks/markov-type/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/markov-type/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/markov-type/instruction.md b/tasks/markov-type/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..003def36708aef3be580386720e8e256a8661b5c --- /dev/null +++ b/tasks/markov-type/instruction.md @@ -0,0 +1,130 @@ +# openai/math challenge `MarkovType` (family 327) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 327 of the release, *Markov type characterizes superreflexivity* +(Functional analysis). The family as a whole: Proves that every real Banach space with Markov type $p$ for some $p>1$ admits an equivalent uniformly convex norm, answering Naor's renorming question. Together with the known converse, this characterizes superreflexivity by nontrivial Markov type. + +The challenge is `MarkovType`, also at `/opt/openai-math/challenges/MarkovType.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace MarkovSuperreflexivity + +structure FiniteReversibleChain (S : Type*) [Fintype S] where + π : S → ℝ + P : S → S → ℝ + π_nonneg : ∀ s, 0 ≤ π s + sum_π : ∑ s, π s = 1 + P_nonneg : ∀ s t, 0 ≤ P s t + sum_P : ∀ s, ∑ t, P s t = 1 + balance : ∀ s t, π s * P s t = π t * P t s + +abbrev StatePath (S : Type*) (n : ℕ) := Fin (n + 1) → S + +def pathWeight {S : Type*} [Fintype S] + (C : FiniteReversibleChain S) (n : ℕ) (ω : StatePath S n) : ℝ := + C.π (ω 0) * ∏ i : Fin n, C.P (ω i.castSucc) (ω i.succ) + +def stateCost {S X : Type*} [Fintype S] [NormedAddCommGroup X] + (C : FiniteReversibleChain S) (f : S → X) (p : ℝ) (n : ℕ) : ℝ := + ∑ ω : StatePath S n, + pathWeight C n ω * Real.rpow (‖f (ω (Fin.last n)) - f (ω 0)‖) p + +def MarkovTypeWith (p K : ℝ) (X : Type*) [NormedAddCommGroup X] : Prop := + 0 < p ∧ 0 < K ∧ + ∀ (m : ℕ) (C : FiniteReversibleChain (Fin m)) (f : Fin m → X) (n : ℕ), + 1 ≤ n → stateCost C f p n ≤ Real.rpow K p * (n : ℝ) * stateCost C f p 1 + +def HasMarkovType (p : ℝ) (X : Type*) [NormedAddCommGroup X] : Prop := + ∃ K : ℝ, MarkovTypeWith p K X + +def HasNontrivialMarkovType (X : Type*) [NormedAddCommGroup X] : Prop := + ∃ p : ℝ, 1 < p ∧ HasMarkovType p X + +section + +universe u + +variable (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] + +structure EquivalentNorm where + p : Seminorm ℝ X + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + upper_pos : 0 < upper + lower_bound : ∀ x, lower * ‖x‖ ≤ p x + upper_bound : ∀ x, p x ≤ upper * ‖x‖ + +variable {X} + +def UniformConvex (p : Seminorm ℝ X) : Prop := + ∀ ε : ℝ, 0 < ε → ε ≤ 2 → ∃ δ : ℝ, 0 < δ ∧ + ∀ x y : X, p x ≤ 1 → p y ≤ 1 → ε ≤ p (x - y) → + p ((1 / 2 : ℝ) • (x + y)) ≤ 1 - δ + +def HasEquivalentUCNorm (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∃ N : EquivalentNorm X, UniformConvex N.p + +end + +variable {X : Type*} [NormedAddCommGroup X] [NormedSpace ℝ X] + +theorem hasNontrivialMarkovType_iff_hasEquivalentUCNorm [CompleteSpace X] : + HasNontrivialMarkovType X ↔ HasEquivalentUCNorm X := by + sorry + +end MarkovSuperreflexivity + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MarkovType.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MarkovSuperreflexivity.hasNontrivialMarkovType_iff_hasEquivalentUCNorm` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/markov-type/solution/closure.txt b/tasks/markov-type/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0a8d1edcf5794680ab5014a2c126db05fcf723ad --- /dev/null +++ b/tasks/markov-type/solution/closure.txt @@ -0,0 +1,207 @@ +OAI.Analysis.MarkovType.AlternatingNorm +OAI.Analysis.MarkovType.AntitoneSeminormLimit +OAI.Analysis.MarkovType.C00FiniteCoordinates +OAI.Analysis.MarkovType.ChartAveraging +OAI.Analysis.MarkovType.ChartChain +OAI.Analysis.MarkovType.ChartPathProbability +OAI.Analysis.MarkovType.ChartTransport +OAI.Analysis.MarkovType.CoefficientBasic +OAI.Analysis.MarkovType.CoefficientBlockGain +OAI.Analysis.MarkovType.CoefficientBlockIteration +OAI.Analysis.MarkovType.CoefficientBlockPartition +OAI.Analysis.MarkovType.CoefficientConsecutiveBlocks +OAI.Analysis.MarkovType.CoefficientFunctional +OAI.Analysis.MarkovType.CoefficientGrid +OAI.Analysis.MarkovType.CoefficientLowerPower +OAI.Analysis.MarkovType.CoefficientQuotientGain +OAI.Analysis.MarkovType.CoefficientSelectedBlocks +OAI.Analysis.MarkovType.CoefficientSequenceOps +OAI.Analysis.MarkovType.CoefficientThresholdCount +OAI.Analysis.MarkovType.CoordinateFactorization +OAI.Analysis.MarkovType.CoordinateRepresentability +OAI.Analysis.MarkovType.CubeNotJConvex +OAI.Analysis.MarkovType.DenseFiniteApproximation +OAI.Analysis.MarkovType.DyadicBellman +OAI.Analysis.MarkovType.DyadicBlockCoordinates +OAI.Analysis.MarkovType.DyadicConvexPotential +OAI.Analysis.MarkovType.DyadicCotypeDuality +OAI.Analysis.MarkovType.DyadicIndependentBlocks +OAI.Analysis.MarkovType.DyadicInterpolation +OAI.Analysis.MarkovType.DyadicSmoothRenorming +OAI.Analysis.MarkovType.DyadicSynthesisPairing +OAI.Analysis.MarkovType.DyadicTree +OAI.Analysis.MarkovType.DyadicTreeMartingale +OAI.Analysis.MarkovType.DyadicWeakAmplification +OAI.Analysis.MarkovType.DyadicWeakMaxDefinition +OAI.Analysis.MarkovType.DyadicWeakMaxFromUpperL2 +OAI.Analysis.MarkovType.DyadicWeakType +OAI.Analysis.MarkovType.EndNorm +OAI.Analysis.MarkovType.FailureJApproximation +OAI.Analysis.MarkovType.FailureJTriangular +OAI.Analysis.MarkovType.FiniteAnnihilator +OAI.Analysis.MarkovType.FiniteAveraging +OAI.Analysis.MarkovType.FiniteBoundedEnergy +OAI.Analysis.MarkovType.FiniteBoundedEnergyScale +OAI.Analysis.MarkovType.FiniteChains +OAI.Analysis.MarkovType.FiniteCharts +OAI.Analysis.MarkovType.FiniteConditionalAverage +OAI.Analysis.MarkovType.FiniteConditionalMartingale +OAI.Analysis.MarkovType.FiniteCoordinateSupport +OAI.Analysis.MarkovType.FiniteCoupling +OAI.Analysis.MarkovType.FiniteCubeBound +OAI.Analysis.MarkovType.FiniteDualNorming +OAI.Analysis.MarkovType.FiniteDyadicMartingale +OAI.Analysis.MarkovType.FiniteDyadicProbability +OAI.Analysis.MarkovType.FiniteFirstCrossing +OAI.Analysis.MarkovType.FiniteGeometricBands +OAI.Analysis.MarkovType.FiniteGoldstine +OAI.Analysis.MarkovType.FiniteIndependentCopies +OAI.Analysis.MarkovType.FiniteL2 +OAI.Analysis.MarkovType.FiniteL2CoefficientAdapter +OAI.Analysis.MarkovType.FiniteL2IsometryTransport +OAI.Analysis.MarkovType.FiniteLowerL2Cotype +OAI.Analysis.MarkovType.FiniteMarcinkiewicz +OAI.Analysis.MarkovType.FiniteMartingaleBasic +OAI.Analysis.MarkovType.FiniteMartingaleConditional +OAI.Analysis.MarkovType.FiniteMartingaleDuality +OAI.Analysis.MarkovType.FiniteMartingaleExtrapolation +OAI.Analysis.MarkovType.FiniteMartingaleMaximal +OAI.Analysis.MarkovType.FiniteMartingalePairing +OAI.Analysis.MarkovType.FiniteMartingaleTransport +OAI.Analysis.MarkovType.FiniteMatching +OAI.Analysis.MarkovType.FiniteNormApproximation +OAI.Analysis.MarkovType.FinitePaths +OAI.Analysis.MarkovType.FinitePowerIntegrals +OAI.Analysis.MarkovType.FinitePowerMeanBound +OAI.Analysis.MarkovType.FinitePredictableSelection +OAI.Analysis.MarkovType.FinitePredictableTransform +OAI.Analysis.MarkovType.FiniteProbability +OAI.Analysis.MarkovType.FiniteRamsey +OAI.Analysis.MarkovType.FiniteRepresentation +OAI.Analysis.MarkovType.FiniteSelectionCompression +OAI.Analysis.MarkovType.FiniteSelectionCounter +OAI.Analysis.MarkovType.FiniteSeparation +OAI.Analysis.MarkovType.FiniteSmoothMoments +OAI.Analysis.MarkovType.FiniteStoppingTime +OAI.Analysis.MarkovType.FiniteTailAmplification +OAI.Analysis.MarkovType.FiniteTailCorrection +OAI.Analysis.MarkovType.FiniteTruncationTail +OAI.Analysis.MarkovType.FiniteWalk +OAI.Analysis.MarkovType.FiniteWalkCoordinates +OAI.Analysis.MarkovType.FiniteWalkMoment +OAI.Analysis.MarkovType.FiniteWalkWitness +OAI.Analysis.MarkovType.FiniteWeightedHolder +OAI.Analysis.MarkovType.FinitelyRepresentable +OAI.Analysis.MarkovType.FinitelyRepresentableEmbedding +OAI.Analysis.MarkovType.ForwardBound +OAI.Analysis.MarkovType.FourLetters +OAI.Analysis.MarkovType.GeometricThresholdPowerSum +OAI.Analysis.MarkovType.HomogeneousPotential +OAI.Analysis.MarkovType.HomogeneousRows +OAI.Analysis.MarkovType.IntegerCocycle +OAI.Analysis.MarkovType.InterleavedCuts +OAI.Analysis.MarkovType.JConvexityBasic +OAI.Analysis.MarkovType.JConvexityFiniteRepresentability +OAI.Analysis.MarkovType.JConvexityReflexivity +OAI.Analysis.MarkovType.JConvexityScalarSquares +OAI.Analysis.MarkovType.JConvexitySquareAverage +OAI.Analysis.MarkovType.JamesCubeImprovement +OAI.Analysis.MarkovType.JamesEnflo +OAI.Analysis.MarkovType.LatticeCosts +OAI.Analysis.MarkovType.LatticeCubes +OAI.Analysis.MarkovType.LatticeLift +OAI.Analysis.MarkovType.LatticePaths +OAI.Analysis.MarkovType.Main +OAI.Analysis.MarkovType.MarkedChains +OAI.Analysis.MarkovType.MarkedLetters +OAI.Analysis.MarkovType.MarkedMoments +OAI.Analysis.MarkovType.MarkedPaths +OAI.Analysis.MarkovType.MarkovFiniteRepresentability +OAI.Analysis.MarkovType.MarkovObstruction +OAI.Analysis.MarkovType.MarkovReflexivity +OAI.Analysis.MarkovType.MarkovRenorming +OAI.Analysis.MarkovType.MarkovTransport +OAI.Analysis.MarkovType.MidpointPotential +OAI.Analysis.MarkovType.NormCompression +OAI.Analysis.MarkovType.NormedC00 +OAI.Analysis.MarkovType.OddEdgeTransfer +OAI.Analysis.MarkovType.OrbitDisplacement +OAI.Analysis.MarkovType.OrderedBoundedCubes +OAI.Analysis.MarkovType.OrderedCoordinates +OAI.Analysis.MarkovType.OrderedJColumns +OAI.Analysis.MarkovType.OrderedMarkovTransfer +OAI.Analysis.MarkovType.OrderedNorm +OAI.Analysis.MarkovType.OrderedNormConstruction +OAI.Analysis.MarkovType.OrderedNormStructural +OAI.Analysis.MarkovType.OrderedSequences +OAI.Analysis.MarkovType.PeriodicArcs +OAI.Analysis.MarkovType.PeriodicOrderIso +OAI.Analysis.MarkovType.PisierPowerRenorming +OAI.Analysis.MarkovType.PowerConvexity +OAI.Analysis.MarkovType.PowerGrowth +OAI.Analysis.MarkovType.PowerRenormingFromDyadic +OAI.Analysis.MarkovType.PowerSmoothness +OAI.Analysis.MarkovType.PrefixBlocks +OAI.Analysis.MarkovType.PrefixIndicators +OAI.Analysis.MarkovType.Renormed +OAI.Analysis.MarkovType.RenormedGeometry +OAI.Analysis.MarkovType.RenormingBasic +OAI.Analysis.MarkovType.ReversibleMartingales +OAI.Analysis.MarkovType.ScalarPowerRemainder +OAI.Analysis.MarkovType.ScalarUltralimit +OAI.Analysis.MarkovType.SelectedRows +OAI.Analysis.MarkovType.SeminormUltralimit +OAI.Analysis.MarkovType.SeminormUniformApproximation +OAI.Analysis.MarkovType.SequenceL2JConvex +OAI.Analysis.MarkovType.SmoothMarkovType +OAI.Analysis.MarkovType.SmoothRenormed +OAI.Analysis.MarkovType.SmoothnessBounds +OAI.Analysis.MarkovType.SpreadingConstruction +OAI.Analysis.MarkovType.SpreadingCoordinateEmbedding +OAI.Analysis.MarkovType.SpreadingLimit +OAI.Analysis.MarkovType.SpreadingLimitCauchy +OAI.Analysis.MarkovType.SpreadingLimitDiagonal +OAI.Analysis.MarkovType.SpreadingLimitEmbedding +OAI.Analysis.MarkovType.SpreadingLimitReal +OAI.Analysis.MarkovType.SpreadingLimitUniform +OAI.Analysis.MarkovType.SpreadingModel +OAI.Analysis.MarkovType.StructuralL2Estimates +OAI.Analysis.MarkovType.SubdivisionAverage +OAI.Analysis.MarkovType.SubdivisionInvariantBlocks +OAI.Analysis.MarkovType.SubdivisionLimit +OAI.Analysis.MarkovType.SubdivisionMergeConvex +OAI.Analysis.MarkovType.SubdivisionMergeCoordinates +OAI.Analysis.MarkovType.SubdivisionNearIsometry +OAI.Analysis.MarkovType.SubdivisionOperators +OAI.Analysis.MarkovType.SubdivisionOrderedNorm +OAI.Analysis.MarkovType.SubdivisionProfileDefs +OAI.Analysis.MarkovType.SubdivisionProfileExpansion +OAI.Analysis.MarkovType.SubdivisionProfiles +OAI.Analysis.MarkovType.SubdivisionSameSign +OAI.Analysis.MarkovType.SubdivisionSpreading +OAI.Analysis.MarkovType.TailMoment +OAI.Analysis.MarkovType.TriangularArrays +OAI.Analysis.MarkovType.TriangularBasic +OAI.Analysis.MarkovType.TriangularCompletion +OAI.Analysis.MarkovType.TriangularCoordinateEmbeddings +OAI.Analysis.MarkovType.TriangularCounterexample +OAI.Analysis.MarkovType.TriangularLimitSeminorm +OAI.Analysis.MarkovType.TriangularNonreflexivity +OAI.Analysis.MarkovType.TriangularPrefix +OAI.Analysis.MarkovType.TriangularQuotient +OAI.Analysis.MarkovType.TriangularReflexivity +OAI.Analysis.MarkovType.TriangularRepresentability +OAI.Analysis.MarkovType.TriangularTransport +OAI.Analysis.MarkovType.TwoLevels +OAI.Analysis.MarkovType.UniformSmoothNonsquare +OAI.Analysis.MarkovType.WalkDisplacement +OAI.Analysis.MarkovType.WalkDrift +OAI.Analysis.MarkovType.WalkLabels +OAI.Analysis.MarkovType.WalkLandmarks +OAI.Analysis.MarkovType.WalkMarkedDisplacement +OAI.Analysis.MarkovType.WalkParameters +OAI.Analysis.MarkovType.WalkPrefixLevels +OAI.Analysis.MarkovType.WalkTransport +OAI.Analysis.MarkovType.WeightedEvents +OAI.Analysis.MarkovType.WordAction +OAI.Analysis.MarkovType.WordReduction diff --git a/tasks/markov-type/solution/reference.py b/tasks/markov-type/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/markov-type/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/markov-type/solution/solve.sh b/tasks/markov-type/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..745cb36249705319f4c175175bb1b02c960deddd --- /dev/null +++ b/tasks/markov-type/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MarkovType, i.e. module OAI.Analysis.MarkovType.Main and the +# 207 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.MarkovType.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MarkovType" diff --git a/tasks/markov-type/task.toml b/tasks/markov-type/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7da874d1340ffa5bc9fe915d27b33dbc5b0884f3 --- /dev/null +++ b/tasks/markov-type/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/markov-type" +version = "1.0.0" +description = "Prove MarkovType (openai/math family 327: Markov type characterizes superreflexivity) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MarkovType.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MarkovType" +family = "327" +family_title = "Markov type characterizes superreflexivity" +subject = "Functional analysis" +theorems = ["OAI.MarkovSuperreflexivity.hasNontrivialMarkovType_iff_hasEquivalentUCNorm"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.MarkovType.Main" +reference_modules = 207 +reference_lean_bytes = 1098511 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 926 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12688 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/markov-type/tests/Challenge.lean b/tasks/markov-type/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5fcf3818f09073764b6be28ecaf25acb2a432d30 --- /dev/null +++ b/tasks/markov-type/tests/Challenge.lean @@ -0,0 +1,79 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace MarkovSuperreflexivity + +structure FiniteReversibleChain (S : Type*) [Fintype S] where + π : S → ℝ + P : S → S → ℝ + π_nonneg : ∀ s, 0 ≤ π s + sum_π : ∑ s, π s = 1 + P_nonneg : ∀ s t, 0 ≤ P s t + sum_P : ∀ s, ∑ t, P s t = 1 + balance : ∀ s t, π s * P s t = π t * P t s + +abbrev StatePath (S : Type*) (n : ℕ) := Fin (n + 1) → S + +def pathWeight {S : Type*} [Fintype S] + (C : FiniteReversibleChain S) (n : ℕ) (ω : StatePath S n) : ℝ := + C.π (ω 0) * ∏ i : Fin n, C.P (ω i.castSucc) (ω i.succ) + +def stateCost {S X : Type*} [Fintype S] [NormedAddCommGroup X] + (C : FiniteReversibleChain S) (f : S → X) (p : ℝ) (n : ℕ) : ℝ := + ∑ ω : StatePath S n, + pathWeight C n ω * Real.rpow (‖f (ω (Fin.last n)) - f (ω 0)‖) p + +def MarkovTypeWith (p K : ℝ) (X : Type*) [NormedAddCommGroup X] : Prop := + 0 < p ∧ 0 < K ∧ + ∀ (m : ℕ) (C : FiniteReversibleChain (Fin m)) (f : Fin m → X) (n : ℕ), + 1 ≤ n → stateCost C f p n ≤ Real.rpow K p * (n : ℝ) * stateCost C f p 1 + +def HasMarkovType (p : ℝ) (X : Type*) [NormedAddCommGroup X] : Prop := + ∃ K : ℝ, MarkovTypeWith p K X + +def HasNontrivialMarkovType (X : Type*) [NormedAddCommGroup X] : Prop := + ∃ p : ℝ, 1 < p ∧ HasMarkovType p X + +section + +universe u + +variable (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] + +structure EquivalentNorm where + p : Seminorm ℝ X + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + upper_pos : 0 < upper + lower_bound : ∀ x, lower * ‖x‖ ≤ p x + upper_bound : ∀ x, p x ≤ upper * ‖x‖ + +variable {X} + +def UniformConvex (p : Seminorm ℝ X) : Prop := + ∀ ε : ℝ, 0 < ε → ε ≤ 2 → ∃ δ : ℝ, 0 < δ ∧ + ∀ x y : X, p x ≤ 1 → p y ≤ 1 → ε ≤ p (x - y) → + p ((1 / 2 : ℝ) • (x + y)) ≤ 1 - δ + +def HasEquivalentUCNorm (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] : Prop := + ∃ N : EquivalentNorm X, UniformConvex N.p + +end + +variable {X : Type*} [NormedAddCommGroup X] [NormedSpace ℝ X] + +theorem hasNontrivialMarkovType_iff_hasEquivalentUCNorm [CompleteSpace X] : + HasNontrivialMarkovType X ↔ HasEquivalentUCNorm X := by + sorry + +end MarkovSuperreflexivity + +end + +end OAI diff --git a/tasks/markov-type/tests/grade.py b/tasks/markov-type/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/markov-type/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/markov-type/tests/task.json b/tasks/markov-type/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9183a668a94d77047fd5ab8a6c132c688848ff94 --- /dev/null +++ b/tasks/markov-type/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MarkovType", + "comparator": { + "theorem_names": [ + "OAI.MarkovSuperreflexivity.hasNontrivialMarkovType_iff_hasEquivalentUCNorm" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11788 +} \ No newline at end of file diff --git a/tasks/markov-type/tests/test.sh b/tasks/markov-type/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/markov-type/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/mass-action/environment/Dockerfile b/tasks/mass-action/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/mass-action/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/mass-action/environment/fetch_mathlib.sh b/tasks/mass-action/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/mass-action/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/mass-action/environment/lake-manifest.json b/tasks/mass-action/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/mass-action/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/mass-action/environment/lakefile.lean b/tasks/mass-action/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/mass-action/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/mass-action/environment/lean_setup.sh b/tasks/mass-action/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/mass-action/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/mass-action/environment/pack_submission.py b/tasks/mass-action/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/mass-action/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/mass-action/instruction.md b/tasks/mass-action/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..45e383b3d6603e6377e601020981c68b5eca27bf --- /dev/null +++ b/tasks/mass-action/instruction.md @@ -0,0 +1,111 @@ +# openai/math challenge `MassAction` (family 149) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 149 of the release, *Permanence for weakly reversible reaction networks* +(Dynamical systems and ergodic theory). The family as a whole: Proves the permanence conjecture for every finite weakly reversible mass-action system with fixed positive rate constants. Every positive stoichiometric compatibility class, even an unbounded one, has a common compact convex forward-invariant absorbing set. All positive trajectories in that class therefore eventually share positive lower and finite upper concentration bounds. + +The challenge is `MassAction`, also at `/opt/openai-math/challenges/MassAction.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem326 + +structure ReactionNetwork (d : ℕ) where + complexes : Finset (Fin d → ℕ) + reactions : Finset ((Fin d → ℕ) × (Fin d → ℕ)) + source_mem : ∀ e ∈ reactions, e.1 ∈ complexes + target_mem : ∀ e ∈ reactions, e.2 ∈ complexes + source_ne_target : ∀ e ∈ reactions, e.1 ≠ e.2 + +abbrev Reaction {d : ℕ} (N : ReactionNetwork d) := + {e : (Fin d → ℕ) × (Fin d → ℕ) // e ∈ N.reactions} + +def HasReaction {d : ℕ} (N : ReactionNetwork d) + (y z : Fin d → ℕ) : Prop := + (y, z) ∈ N.reactions + +def WeaklyReversible {d : ℕ} (N : ReactionNetwork d) : Prop := + ∀ e : Reaction N, + Relation.TransGen (HasReaction N) e.val.2 e.val.1 + +def monomial {d : ℕ} (x : Fin d → ℝ) (y : Fin d → ℕ) : ℝ := + Finset.univ.prod (fun i => x i ^ y i) + +def massAction {d : ℕ} (N : ReactionNetwork d) + (κ : Reaction N → ℝ) (x : Fin d → ℝ) : Fin d → ℝ := + fun i => Finset.univ.sum (fun e : Reaction N => + κ e * monomial x e.val.1 * + ((e.val.2 i : ℝ) - (e.val.1 i : ℝ))) + +def PositiveState {d : ℕ} (x : Fin d → ℝ) : Prop := + ∀ i, 0 < x i + +def IsGlobalForwardSolution {d : ℕ} (N : ReactionNetwork d) + (κ : Reaction N → ℝ) (x0 : Fin d → ℝ) + (x : ℝ → (Fin d → ℝ)) : Prop := + x 0 = x0 ∧ + ∀ t : ℝ, 0 ≤ t → + HasDerivAt x (massAction N κ (x t)) t + +theorem global_bounded_persistent_solution : + ∀ (d : ℕ) (N : ReactionNetwork d) (κ : Reaction N → ℝ), + 0 < d → WeaklyReversible N → (∀ e, 0 < κ e) → + ∀ x0 : Fin d → ℝ, PositiveState x0 → + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + (∃ x : ℝ → (Fin d → ℝ), IsGlobalForwardSolution N κ x0 x) ∧ + ∀ x : ℝ → (Fin d → ℝ), IsGlobalForwardSolution N κ x0 x → + ∀ t : ℝ, 0 ≤ t → ∀ i : Fin d, ε ≤ x t i ∧ x t i ≤ ε⁻¹ := by + sorry + +end Problem326 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MassAction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem326.global_bounded_persistent_solution` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/mass-action/solution/closure.txt b/tasks/mass-action/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f82b857bea621944f25ecd320c0adc6d8479465f --- /dev/null +++ b/tasks/mass-action/solution/closure.txt @@ -0,0 +1,71 @@ +OAI.Analysis.MassAction.ActiveBranchMinimum +OAI.Analysis.MassAction.ActivityLimits +OAI.Analysis.MassAction.AffineApproximation +OAI.Analysis.MassAction.AffineCertificateBridge +OAI.Analysis.MassAction.AffineCertificateGluing +OAI.Analysis.MassAction.AffineCertificates +OAI.Analysis.MassAction.AffineExistence +OAI.Analysis.MassAction.AffineFamilyGluing +OAI.Analysis.MassAction.AffineGlobalAssembly +OAI.Analysis.MassAction.AffineGlobalGluing +OAI.Analysis.MassAction.AffineGluing +OAI.Analysis.MassAction.AffineLayers +OAI.Analysis.MassAction.AffineLimitSet +OAI.Analysis.MassAction.AffineLocalBand +OAI.Analysis.MassAction.AffineLocalConstructor +OAI.Analysis.MassAction.AffineLocalization +OAI.Analysis.MassAction.AffineNeighborhood +OAI.Analysis.MassAction.AffinePolytope +OAI.Analysis.MassAction.AffineSignGap +OAI.Analysis.MassAction.AffineTrajectory +OAI.Analysis.MassAction.AffineUniformCertificate +OAI.Analysis.MassAction.BarrierGeometry +OAI.Analysis.MassAction.BarrierInvariance +OAI.Analysis.MassAction.BarrierTrapping +OAI.Analysis.MassAction.CanonicalLocalConstructor +OAI.Analysis.MassAction.ClampExtension +OAI.Analysis.MassAction.CompactBounds +OAI.Analysis.MassAction.CompactContinuation +OAI.Analysis.MassAction.CompactInvariance +OAI.Analysis.MassAction.CompleteAffine +OAI.Analysis.MassAction.CoordinateEmbedding +OAI.Analysis.MassAction.CutDecomposition +OAI.Analysis.MassAction.CutFlux +OAI.Analysis.MassAction.ExponentAsymptotics +OAI.Analysis.MassAction.FiniteMinimum +OAI.Analysis.MassAction.FirstExit +OAI.Analysis.MassAction.FixedMinimum +OAI.Analysis.MassAction.FixedMinimumCertificate +OAI.Analysis.MassAction.FixedMinimumEstimates +OAI.Analysis.MassAction.GlueCurves +OAI.Analysis.MassAction.GlueLocalCertificates +OAI.Analysis.MassAction.IntervalChain +OAI.Analysis.MassAction.IntervalGluing +OAI.Analysis.MassAction.LabelTrajectory +OAI.Analysis.MassAction.LayerSequence +OAI.Analysis.MassAction.LocalCertificateRadius +OAI.Analysis.MassAction.LocalExistence +OAI.Analysis.MassAction.Main +OAI.Analysis.MassAction.MassActionDot +OAI.Analysis.MassAction.MassActionFlux +OAI.Analysis.MassAction.MassActionRegularity +OAI.Analysis.MassAction.Model +OAI.Analysis.MassAction.MonomialOrder +OAI.Analysis.MassAction.NetworkApproximation +OAI.Analysis.MassAction.NetworkBarrier +OAI.Analysis.MassAction.ODEConcatenation +OAI.Analysis.MassAction.ODEGlobal +OAI.Analysis.MassAction.ODEUniqueness +OAI.Analysis.MassAction.PlateauCertificate +OAI.Analysis.MassAction.PlateauGeometry +OAI.Analysis.MassAction.PolyhedronGeometry +OAI.Analysis.MassAction.PowerAsymptotics +OAI.Analysis.MassAction.ReciprocalBox +OAI.Analysis.MassAction.SignTolerance +OAI.Analysis.MassAction.SmallParameter +OAI.Analysis.MassAction.SolutionUniqueness +OAI.Analysis.MassAction.TypeFamily +OAI.Analysis.MassAction.TypeFamilyCertificate +OAI.Analysis.MassAction.UniformActivity +OAI.Analysis.MassAction.UniformAffineData +OAI.Analysis.MassAction.UniformOffsetDecay diff --git a/tasks/mass-action/solution/reference.py b/tasks/mass-action/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/mass-action/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/mass-action/solution/solve.sh b/tasks/mass-action/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..def4dc09c76790d63f97d9c13aaed79c9e173fc2 --- /dev/null +++ b/tasks/mass-action/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MassAction, i.e. module OAI.Analysis.MassAction.Main and the +# 71 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.MassAction.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MassAction" diff --git a/tasks/mass-action/task.toml b/tasks/mass-action/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e059258fc499bf041f7300f176767a3bbc76d3fa --- /dev/null +++ b/tasks/mass-action/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/mass-action" +version = "1.0.0" +description = "Prove MassAction (openai/math family 149: Permanence for weakly reversible reaction networks) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MassAction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MassAction" +family = "149" +family_title = "Permanence for weakly reversible reaction networks" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.Problem326.global_bounded_persistent_solution"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.MassAction.Main" +reference_modules = 71 +reference_lean_bytes = 328720 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 751 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11995 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/mass-action/tests/Challenge.lean b/tasks/mass-action/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..838d6cd67700dc8f843c67cd5cb334a5ec4b7d86 --- /dev/null +++ b/tasks/mass-action/tests/Challenge.lean @@ -0,0 +1,60 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem326 + +structure ReactionNetwork (d : ℕ) where + complexes : Finset (Fin d → ℕ) + reactions : Finset ((Fin d → ℕ) × (Fin d → ℕ)) + source_mem : ∀ e ∈ reactions, e.1 ∈ complexes + target_mem : ∀ e ∈ reactions, e.2 ∈ complexes + source_ne_target : ∀ e ∈ reactions, e.1 ≠ e.2 + +abbrev Reaction {d : ℕ} (N : ReactionNetwork d) := + {e : (Fin d → ℕ) × (Fin d → ℕ) // e ∈ N.reactions} + +def HasReaction {d : ℕ} (N : ReactionNetwork d) + (y z : Fin d → ℕ) : Prop := + (y, z) ∈ N.reactions + +def WeaklyReversible {d : ℕ} (N : ReactionNetwork d) : Prop := + ∀ e : Reaction N, + Relation.TransGen (HasReaction N) e.val.2 e.val.1 + +def monomial {d : ℕ} (x : Fin d → ℝ) (y : Fin d → ℕ) : ℝ := + Finset.univ.prod (fun i => x i ^ y i) + +def massAction {d : ℕ} (N : ReactionNetwork d) + (κ : Reaction N → ℝ) (x : Fin d → ℝ) : Fin d → ℝ := + fun i => Finset.univ.sum (fun e : Reaction N => + κ e * monomial x e.val.1 * + ((e.val.2 i : ℝ) - (e.val.1 i : ℝ))) + +def PositiveState {d : ℕ} (x : Fin d → ℝ) : Prop := + ∀ i, 0 < x i + +def IsGlobalForwardSolution {d : ℕ} (N : ReactionNetwork d) + (κ : Reaction N → ℝ) (x0 : Fin d → ℝ) + (x : ℝ → (Fin d → ℝ)) : Prop := + x 0 = x0 ∧ + ∀ t : ℝ, 0 ≤ t → + HasDerivAt x (massAction N κ (x t)) t + +theorem global_bounded_persistent_solution : + ∀ (d : ℕ) (N : ReactionNetwork d) (κ : Reaction N → ℝ), + 0 < d → WeaklyReversible N → (∀ e, 0 < κ e) → + ∀ x0 : Fin d → ℝ, PositiveState x0 → + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + (∃ x : ℝ → (Fin d → ℝ), IsGlobalForwardSolution N κ x0 x) ∧ + ∀ x : ℝ → (Fin d → ℝ), IsGlobalForwardSolution N κ x0 x → + ∀ t : ℝ, 0 ≤ t → ∀ i : Fin d, ε ≤ x t i ∧ x t i ≤ ε⁻¹ := by + sorry + +end Problem326 + +end + +end OAI diff --git a/tasks/mass-action/tests/grade.py b/tasks/mass-action/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/mass-action/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/mass-action/tests/task.json b/tasks/mass-action/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..43554b46f3953c78fc936232b604f3df9a12ab0e --- /dev/null +++ b/tasks/mass-action/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MassAction", + "comparator": { + "theorem_names": [ + "OAI.Problem326.global_bounded_persistent_solution" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11095 +} \ No newline at end of file diff --git a/tasks/mass-action/tests/test.sh b/tasks/mass-action/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/mass-action/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matching-affine-lift/environment/Dockerfile b/tasks/matching-affine-lift/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matching-affine-lift/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matching-affine-lift/environment/fetch_mathlib.sh b/tasks/matching-affine-lift/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matching-affine-lift/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matching-affine-lift/environment/lake-manifest.json b/tasks/matching-affine-lift/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matching-affine-lift/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matching-affine-lift/environment/lakefile.lean b/tasks/matching-affine-lift/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matching-affine-lift/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matching-affine-lift/environment/lean_setup.sh b/tasks/matching-affine-lift/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matching-affine-lift/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matching-affine-lift/environment/pack_submission.py b/tasks/matching-affine-lift/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matching-affine-lift/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matching-affine-lift/instruction.md b/tasks/matching-affine-lift/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0c8f57d1e6353fed33c66d9257a36f95b8cacee8 --- /dev/null +++ b/tasks/matching-affine-lift/instruction.md @@ -0,0 +1,86 @@ +# openai/math challenge `MatchingAffineLift` (family 126) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 126 of the release, *Exponential semidefinite complexity of perfect matching* +(Theoretical computer science). The family as a whole: Proves that every exact semidefinite lift of the perfect matching polytope has exponential size, answering Rothvoss's polynomial-size lift question negatively. The bound holds even for the positive semidefinite rank of its odd-cut slack matrix after any fixed shift $0<\rho<1$, allowing arbitrary real positive semidefinite factors. + +The challenge is `MatchingAffineLift`, also at `/opt/openai-math/challenges/MatchingAffineLift.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PerfectMatchingPSD + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +def IsPerfectMatching {n : ℕ} (M : Finset (Edge n)) : Prop := + ∀ v : Fin n, (M.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 + +abbrev PerfectMatching (n : ℕ) := + {M : Finset (Edge n) // IsPerfectMatching M} + +noncomputable def matchingPoint {n : ℕ} (M : PerfectMatching n) : Edge n → ℝ := by + classical + exact fun e => if e ∈ M.1 then 1 else 0 + +noncomputable def matchingPolytope (n : ℕ) : Set (Edge n → ℝ) := + convexHull ℝ (Set.range (matchingPoint (n := n))) + +def HasAffineLift (n r : ℕ) : Prop := + ∃ (L : AffineSubspace ℝ (Matrix (Fin r) (Fin r) ℝ)) + (T : Matrix (Fin r) (Fin r) ℝ →ᵃ[ℝ] (Edge n → ℝ)), + T '' {X | X ∈ L ∧ X.PosSemidef} = matchingPolytope n + +theorem affine_lift_lower_bound : + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → ∀ r : ℕ, + HasAffineLift n r → (n : ℝ) ^ C < (r : ℝ) := by + sorry + +end PerfectMatchingPSD + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatchingAffineLift.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PerfectMatchingPSD.affine_lift_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matching-affine-lift/solution/closure.txt b/tasks/matching-affine-lift/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..357bfdf340fbfab1d89420ff6c7e4f093cd5956f --- /dev/null +++ b/tasks/matching-affine-lift/solution/closure.txt @@ -0,0 +1,66 @@ +OAI.Combinatorics.MatchingPSD.AdmissiblePoints +OAI.Combinatorics.MatchingPSD.AdmissibleTables +OAI.Combinatorics.MatchingPSD.AffineCertificate +OAI.Combinatorics.MatchingPSD.AffineFactorization +OAI.Combinatorics.MatchingPSD.AffineLift +OAI.Combinatorics.MatchingPSD.AffineModel +OAI.Combinatorics.MatchingPSD.AffineSlacks +OAI.Combinatorics.MatchingPSD.AffineSums +OAI.Combinatorics.MatchingPSD.BitTests +OAI.Combinatorics.MatchingPSD.CellAverages +OAI.Combinatorics.MatchingPSD.CellDecoder +OAI.Combinatorics.MatchingPSD.CellLowerBound +OAI.Combinatorics.MatchingPSD.ColorPolynomials +OAI.Combinatorics.MatchingPSD.ColoringCounts +OAI.Combinatorics.MatchingPSD.CommonSelection +OAI.Combinatorics.MatchingPSD.CrossSelection +OAI.Combinatorics.MatchingPSD.CutGeometry +OAI.Combinatorics.MatchingPSD.DeterminantNormalization +OAI.Combinatorics.MatchingPSD.DiagonalCone +OAI.Combinatorics.MatchingPSD.DominationDecoder +OAI.Combinatorics.MatchingPSD.EdgeMonomials +OAI.Combinatorics.MatchingPSD.EdgeProducts +OAI.Combinatorics.MatchingPSD.EquivariantCompression +OAI.Combinatorics.MatchingPSD.FiberAverages +OAI.Combinatorics.MatchingPSD.FiniteFactorization +OAI.Combinatorics.MatchingPSD.GlobalGeometry +OAI.Combinatorics.MatchingPSD.GoodCells +OAI.Combinatorics.MatchingPSD.IncidenceKernels +OAI.Combinatorics.MatchingPSD.Involutions +OAI.Combinatorics.MatchingPSD.Main +OAI.Combinatorics.MatchingPSD.MatchingConversion +OAI.Combinatorics.MatchingPSD.MatchingFibers +OAI.Combinatorics.MatchingPSD.MatchingIncidence +OAI.Combinatorics.MatchingPSD.MatrixAverages +OAI.Combinatorics.MatchingPSD.MatrixBounds +OAI.Combinatorics.MatchingPSD.MatrixInterpolation +OAI.Combinatorics.MatchingPSD.Model +OAI.Combinatorics.MatchingPSD.NormalizedFactors +OAI.Combinatorics.MatchingPSD.NumericalBounds +OAI.Combinatorics.MatchingPSD.OrthogonalCone +OAI.Combinatorics.MatchingPSD.PSDCompression +OAI.Combinatorics.MatchingPSD.PSDDuality +OAI.Combinatorics.MatchingPSD.PSDEvaluation +OAI.Combinatorics.MatchingPSD.PSDTopology +OAI.Combinatorics.MatchingPSD.Padding +OAI.Combinatorics.MatchingPSD.Pairings +OAI.Combinatorics.MatchingPSD.Parameters +OAI.Combinatorics.MatchingPSD.PartialColorings +OAI.Combinatorics.MatchingPSD.PermutationSmoothing +OAI.Combinatorics.MatchingPSD.PolynomialInterpolation +OAI.Combinatorics.MatchingPSD.PolynomialSpaces +OAI.Combinatorics.MatchingPSD.RepresentationDimension +OAI.Combinatorics.MatchingPSD.ScalarSmoothing +OAI.Combinatorics.MatchingPSD.SequentialTests +OAI.Combinatorics.MatchingPSD.SimultaneousSmoothing +OAI.Combinatorics.MatchingPSD.SpectralContraction +OAI.Combinatorics.MatchingPSD.SpectralMultiplicity +OAI.Combinatorics.MatchingPSD.SquareRootDisturbance +OAI.Combinatorics.MatchingPSD.TableCoordinates +OAI.Combinatorics.MatchingPSD.TableGeometry +OAI.Combinatorics.MatchingPSD.TableMoments +OAI.Combinatorics.MatchingPSD.TablePolynomials +OAI.Combinatorics.MatchingPSD.TensorBounds +OAI.Combinatorics.MatchingPSD.TightMatchings +OAI.Combinatorics.MatchingPSD.TransitionMatrices +OAI.Combinatorics.MatchingPSD.TypeProbabilities diff --git a/tasks/matching-affine-lift/solution/reference.py b/tasks/matching-affine-lift/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matching-affine-lift/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matching-affine-lift/solution/solve.sh b/tasks/matching-affine-lift/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..592e4afe55665da3b5e125aa407fc7c85fe4d580 --- /dev/null +++ b/tasks/matching-affine-lift/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatchingAffineLift, i.e. module OAI.Combinatorics.MatchingPSD.AffineLift and the +# 66 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatchingPSD.AffineLift /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatchingAffineLift" diff --git a/tasks/matching-affine-lift/task.toml b/tasks/matching-affine-lift/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..67b8d201eec3afdc4f4968822998b29313c9ea93 --- /dev/null +++ b/tasks/matching-affine-lift/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matching-affine-lift" +version = "1.0.0" +description = "Prove MatchingAffineLift (openai/math family 126: Exponential semidefinite complexity of perfect matching) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatchingAffineLift.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatchingAffineLift" +family = "126" +family_title = "Exponential semidefinite complexity of perfect matching" +subject = "Theoretical computer science" +theorems = ["OAI.PerfectMatchingPSD.affine_lift_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatchingPSD.AffineLift" +reference_modules = 66 +reference_lean_bytes = 322172 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 905 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11989 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matching-affine-lift/tests/Challenge.lean b/tasks/matching-affine-lift/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b79e0344201a5c668b1046424c5fcad5ee6ac5b --- /dev/null +++ b/tasks/matching-affine-lift/tests/Challenge.lean @@ -0,0 +1,35 @@ +import Mathlib + +namespace OAI + +namespace PerfectMatchingPSD + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +def IsPerfectMatching {n : ℕ} (M : Finset (Edge n)) : Prop := + ∀ v : Fin n, (M.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 + +abbrev PerfectMatching (n : ℕ) := + {M : Finset (Edge n) // IsPerfectMatching M} + +noncomputable def matchingPoint {n : ℕ} (M : PerfectMatching n) : Edge n → ℝ := by + classical + exact fun e => if e ∈ M.1 then 1 else 0 + +noncomputable def matchingPolytope (n : ℕ) : Set (Edge n → ℝ) := + convexHull ℝ (Set.range (matchingPoint (n := n))) + +def HasAffineLift (n r : ℕ) : Prop := + ∃ (L : AffineSubspace ℝ (Matrix (Fin r) (Fin r) ℝ)) + (T : Matrix (Fin r) (Fin r) ℝ →ᵃ[ℝ] (Edge n → ℝ)), + T '' {X | X ∈ L ∧ X.PosSemidef} = matchingPolytope n + +theorem affine_lift_lower_bound : + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → ∀ r : ℕ, + HasAffineLift n r → (n : ℝ) ^ C < (r : ℝ) := by + sorry + +end PerfectMatchingPSD + +end OAI diff --git a/tasks/matching-affine-lift/tests/grade.py b/tasks/matching-affine-lift/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matching-affine-lift/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matching-affine-lift/tests/task.json b/tasks/matching-affine-lift/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..611995fd9833ca61102c3c5bee80023373249429 --- /dev/null +++ b/tasks/matching-affine-lift/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatchingAffineLift", + "comparator": { + "theorem_names": [ + "OAI.PerfectMatchingPSD.affine_lift_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11089 +} \ No newline at end of file diff --git a/tasks/matching-affine-lift/tests/test.sh b/tasks/matching-affine-lift/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matching-affine-lift/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matching-entropy-bounds/environment/Dockerfile b/tasks/matching-entropy-bounds/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matching-entropy-bounds/environment/fetch_mathlib.sh b/tasks/matching-entropy-bounds/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matching-entropy-bounds/environment/lake-manifest.json b/tasks/matching-entropy-bounds/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matching-entropy-bounds/environment/lakefile.lean b/tasks/matching-entropy-bounds/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matching-entropy-bounds/environment/lean_setup.sh b/tasks/matching-entropy-bounds/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matching-entropy-bounds/environment/pack_submission.py b/tasks/matching-entropy-bounds/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matching-entropy-bounds/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matching-entropy-bounds/instruction.md b/tasks/matching-entropy-bounds/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..720df74273c6a0501e9df7dbe27ce33b9fe7011d --- /dev/null +++ b/tasks/matching-entropy-bounds/instruction.md @@ -0,0 +1,135 @@ +# openai/math challenge `MatchingEntropyBounds` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `MatchingEntropyBounds`, also at `/opt/openai-math/challenges/MatchingEntropyBounds.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uIndex uι + +namespace MatchingEntropyBounds + +structure LooplessGraph (V : Type uV) (E : Type uE) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +instance incidentDecidable (G : LooplessGraph V E) (v : V) (e : E) : + Decidable (G.Incident v e) := inferInstanceAs (Decidable (G.left e = v ∨ G.right e = v)) + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +def mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (e : E) : ℝ := + ∑ M, p M * G.indicator M e + +end LooplessGraph + +def probabilitySimplex (Index : Type uIndex) [Fintype Index] : Set (Index → ℝ) := + {weights | (∀ index, 0 ≤ weights index) ∧ ∑ index, weights index = 1} + +def LooplessGraph.feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : Set (G.Matching → ℝ) := + {p | p ∈ probabilitySimplex G.Matching ∧ G.mean p = y} + +def entropy {ι : Type uι} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + +namespace Refined + +def complementEntropy (x : E → ℝ) : ℝ := entropy (fun e => 1 - x e) + +end Refined + +open Module Matrix + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +open LooplessGraph + +theorem Refined.pointwise_entropy (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + entropy x - (2 - 2 / (m : ℝ)) * complementEntropy x ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ entropy x := by + sorry + +end MatchingEntropyBounds + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatchingEntropyBounds.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MatchingEntropyBounds.Refined.pointwise_entropy` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matching-entropy-bounds/solution/closure.txt b/tasks/matching-entropy-bounds/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3edc93c985105d3d2696b18f54dcef44e970f41e --- /dev/null +++ b/tasks/matching-entropy-bounds/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.Combinatorics.MatchingEntropy.Basic +OAI.Combinatorics.MatchingEntropy.Calculus +OAI.Combinatorics.MatchingEntropy.Components +OAI.Combinatorics.MatchingEntropy.Continuity +OAI.Combinatorics.MatchingEntropy.Contraction +OAI.Combinatorics.MatchingEntropy.Counting +OAI.Combinatorics.MatchingEntropy.Coupling +OAI.Combinatorics.MatchingEntropy.Covariance +OAI.Combinatorics.MatchingEntropy.Degenerate +OAI.Combinatorics.MatchingEntropy.Duality +OAI.Combinatorics.MatchingEntropy.EdgeReduction +OAI.Combinatorics.MatchingEntropy.EightVertex +OAI.Combinatorics.MatchingEntropy.Entropy +OAI.Combinatorics.MatchingEntropy.EntropyUpper +OAI.Combinatorics.MatchingEntropy.ExpansionSequences +OAI.Combinatorics.MatchingEntropy.Face +OAI.Combinatorics.MatchingEntropy.FractionalReduction +OAI.Combinatorics.MatchingEntropy.KleeSharpness +OAI.Combinatorics.MatchingEntropy.Main +OAI.Combinatorics.MatchingEntropy.MatchingCovariance +OAI.Combinatorics.MatchingEntropy.MinimalFace +OAI.Combinatorics.MatchingEntropy.Model +OAI.Combinatorics.MatchingEntropy.OddCuts +OAI.Combinatorics.MatchingEntropy.Optimizer +OAI.Combinatorics.MatchingEntropy.Pointwise +OAI.Combinatorics.MatchingEntropy.Polyhedron +OAI.Combinatorics.MatchingEntropy.Polytope +OAI.Combinatorics.MatchingEntropy.RefinedVariation +OAI.Combinatorics.MatchingEntropy.SeparableBound +OAI.Combinatorics.MatchingEntropy.SeparableCovariance +OAI.Combinatorics.MatchingEntropy.SeparableVariation +OAI.Combinatorics.MatchingEntropy.SharpRank +OAI.Combinatorics.MatchingEntropy.Simplex +OAI.Combinatorics.MatchingEntropy.TriangleExpansion +OAI.Combinatorics.MatchingEntropy.WeightedSpectrum diff --git a/tasks/matching-entropy-bounds/solution/reference.py b/tasks/matching-entropy-bounds/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matching-entropy-bounds/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matching-entropy-bounds/solution/solve.sh b/tasks/matching-entropy-bounds/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..54851601d4f502e413960fb7fc23dc000555c695 --- /dev/null +++ b/tasks/matching-entropy-bounds/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatchingEntropyBounds, i.e. module OAI.Combinatorics.MatchingEntropy.Main and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatchingEntropy.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatchingEntropyBounds" diff --git a/tasks/matching-entropy-bounds/task.toml b/tasks/matching-entropy-bounds/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5a594232ed89fbbb3335f3bc0c542ba4536d1198 --- /dev/null +++ b/tasks/matching-entropy-bounds/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matching-entropy-bounds" +version = "1.0.0" +description = "Prove MatchingEntropyBounds (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatchingEntropyBounds.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatchingEntropyBounds" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.MatchingEntropyBounds.Refined.pointwise_entropy"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatchingEntropy.Main" +reference_modules = 35 +reference_lean_bytes = 345956 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 808 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12011 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matching-entropy-bounds/tests/Challenge.lean b/tasks/matching-entropy-bounds/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..872b7b216a1290086b3cf2adb965cdb3b6210b30 --- /dev/null +++ b/tasks/matching-entropy-bounds/tests/Challenge.lean @@ -0,0 +1,84 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uIndex uι + +namespace MatchingEntropyBounds + +structure LooplessGraph (V : Type uV) (E : Type uE) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +instance incidentDecidable (G : LooplessGraph V E) (v : V) (e : E) : + Decidable (G.Incident v e) := inferInstanceAs (Decidable (G.left e = v ∨ G.right e = v)) + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +def mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (e : E) : ℝ := + ∑ M, p M * G.indicator M e + +end LooplessGraph + +def probabilitySimplex (Index : Type uIndex) [Fintype Index] : Set (Index → ℝ) := + {weights | (∀ index, 0 ≤ weights index) ∧ ∑ index, weights index = 1} + +def LooplessGraph.feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : Set (G.Matching → ℝ) := + {p | p ∈ probabilitySimplex G.Matching ∧ G.mean p = y} + +def entropy {ι : Type uι} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + +namespace Refined + +def complementEntropy (x : E → ℝ) : ℝ := entropy (fun e => 1 - x e) + +end Refined + +open Module Matrix + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +open LooplessGraph + +theorem Refined.pointwise_entropy (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) (hPM : Nonempty G.Matching) + (x : E → ℝ) (hx : x ∈ G.polytope) : + entropy x - (2 - 2 / (m : ℝ)) * complementEntropy x ≤ maxMatchingEntropy G x ∧ + maxMatchingEntropy G x ≤ entropy x := by + sorry + +end MatchingEntropyBounds + +end + +end OAI diff --git a/tasks/matching-entropy-bounds/tests/grade.py b/tasks/matching-entropy-bounds/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matching-entropy-bounds/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matching-entropy-bounds/tests/task.json b/tasks/matching-entropy-bounds/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..73aa355dc7fe6b2ae96e63e7b36e8f53d4773641 --- /dev/null +++ b/tasks/matching-entropy-bounds/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatchingEntropyBounds", + "comparator": { + "theorem_names": [ + "OAI.MatchingEntropyBounds.Refined.pointwise_entropy" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11111 +} \ No newline at end of file diff --git a/tasks/matching-entropy-bounds/tests/test.sh b/tasks/matching-entropy-bounds/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matching-entropy-bounds/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matching-entropy/environment/Dockerfile b/tasks/matching-entropy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matching-entropy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matching-entropy/environment/fetch_mathlib.sh b/tasks/matching-entropy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matching-entropy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matching-entropy/environment/lake-manifest.json b/tasks/matching-entropy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matching-entropy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matching-entropy/environment/lakefile.lean b/tasks/matching-entropy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matching-entropy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matching-entropy/environment/lean_setup.sh b/tasks/matching-entropy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matching-entropy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matching-entropy/environment/pack_submission.py b/tasks/matching-entropy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matching-entropy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matching-entropy/instruction.md b/tasks/matching-entropy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c389445a07942c1e86ff97ab11489650a6b27fd6 --- /dev/null +++ b/tasks/matching-entropy/instruction.md @@ -0,0 +1,120 @@ +# openai/math challenge `MatchingEntropy` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `MatchingEntropy`, also at `/opt/openai-math/challenges/MatchingEntropy.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace MatchingEntropy + +/-- Nonnegative real weights with total mass one. -/ +def probabilitySimplex (Index : Type*) [Fintype Index] : Set (Index → ℝ) := + {weights | (∀ index, 0 ≤ weights index) ∧ ∑ index, weights index = 1} + +structure LooplessGraph (V E : Type*) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +def mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (e : E) : ℝ := + ∑ M, p M * G.indicator M e + +def feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : Set (G.Matching → ℝ) := + {p | p ∈ probabilitySimplex G.Matching ∧ G.mean p = y} + +end LooplessGraph + +def entropy {ι : Type*} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def marginalEntropy (y : E → ℝ) : ℝ := entropy y + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + +/-- Main entropy comparison, for every marginal in the actual matching polytope. -/ +theorem entropy_main (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) + (hPM : Nonempty G.Matching) (y : E → ℝ) (hy : y ∈ G.polytope) : + marginalEntropy y - maxMatchingEntropy G y ≤ + 8 * (m : ℝ) * (1 - Real.exp (-marginalEntropy y / (m : ℝ))) := by + sorry + +end MatchingEntropy + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatchingEntropy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MatchingEntropy.entropy_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matching-entropy/solution/closure.txt b/tasks/matching-entropy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a0a6eb71e6225c14b988f04277ea4bbf23f67040 --- /dev/null +++ b/tasks/matching-entropy/solution/closure.txt @@ -0,0 +1,18 @@ +OAI.Combinatorics.PerfectMatching.Basic +OAI.Combinatorics.PerfectMatching.Calculus +OAI.Combinatorics.PerfectMatching.Continuity +OAI.Combinatorics.PerfectMatching.Contraction +OAI.Combinatorics.PerfectMatching.Coupling +OAI.Combinatorics.PerfectMatching.Covariance +OAI.Combinatorics.PerfectMatching.Duality +OAI.Combinatorics.PerfectMatching.Entropy +OAI.Combinatorics.PerfectMatching.Face +OAI.Combinatorics.PerfectMatching.Main +OAI.Combinatorics.PerfectMatching.MatchingCovariance +OAI.Combinatorics.PerfectMatching.Model +OAI.Combinatorics.PerfectMatching.OddCuts +OAI.Combinatorics.PerfectMatching.Optimizer +OAI.Combinatorics.PerfectMatching.Polyhedron +OAI.Combinatorics.PerfectMatching.Polytope +OAI.Combinatorics.PerfectMatching.SecondVariation +OAI.Combinatorics.PerfectMatching.Simplex diff --git a/tasks/matching-entropy/solution/reference.py b/tasks/matching-entropy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matching-entropy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matching-entropy/solution/solve.sh b/tasks/matching-entropy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc657c20e16300ef3b06d706c87daf7e1fec72c7 --- /dev/null +++ b/tasks/matching-entropy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatchingEntropy, i.e. module OAI.Combinatorics.PerfectMatching.Main and the +# 18 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.PerfectMatching.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatchingEntropy" diff --git a/tasks/matching-entropy/task.toml b/tasks/matching-entropy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c7f8332be8ebbde1af1579a1a68f7f156fb412e7 --- /dev/null +++ b/tasks/matching-entropy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matching-entropy" +version = "1.0.0" +description = "Prove MatchingEntropy (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatchingEntropy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatchingEntropy" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.MatchingEntropy.entropy_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.PerfectMatching.Main" +reference_modules = 18 +reference_lean_bytes = 156848 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 607 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11841 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matching-entropy/tests/Challenge.lean b/tasks/matching-entropy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5a182adf8a965dfe19480688fd98783720db86e6 --- /dev/null +++ b/tasks/matching-entropy/tests/Challenge.lean @@ -0,0 +1,69 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace MatchingEntropy + +/-- Nonnegative real weights with total mass one. -/ +def probabilitySimplex (Index : Type*) [Fintype Index] : Set (Index → ℝ) := + {weights | (∀ index, 0 ≤ weights index) ∧ ∑ index, weights index = 1} + +structure LooplessGraph (V E : Type*) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +def mean (G : LooplessGraph V E) (p : G.Matching → ℝ) (e : E) : ℝ := + ∑ M, p M * G.indicator M e + +def feasibleLaws (G : LooplessGraph V E) (y : E → ℝ) : Set (G.Matching → ℝ) := + {p | p ∈ probabilitySimplex G.Matching ∧ G.mean p = y} + +end LooplessGraph + +def entropy {ι : Type*} [Fintype ι] (p : ι → ℝ) : ℝ := + ∑ i, Real.negMulLog (p i) + +def marginalEntropy (y : E → ℝ) : ℝ := entropy y + +def maxMatchingEntropy (G : LooplessGraph V E) (y : E → ℝ) : ℝ := + sSup (entropy '' G.feasibleLaws y) + +/-- Main entropy comparison, for every marginal in the actual matching polytope. -/ +theorem entropy_main (G : LooplessGraph V E) (m : ℕ) + (hm : 0 < m) (hV : Fintype.card V = 2 * m) + (hPM : Nonempty G.Matching) (y : E → ℝ) (hy : y ∈ G.polytope) : + marginalEntropy y - maxMatchingEntropy G y ≤ + 8 * (m : ℝ) * (1 - Real.exp (-marginalEntropy y / (m : ℝ))) := by + sorry + +end MatchingEntropy + +end + +end OAI diff --git a/tasks/matching-entropy/tests/grade.py b/tasks/matching-entropy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matching-entropy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matching-entropy/tests/task.json b/tasks/matching-entropy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b6df4fddbd5fe0efba36323302cd4c171c116be3 --- /dev/null +++ b/tasks/matching-entropy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatchingEntropy", + "comparator": { + "theorem_names": [ + "OAI.MatchingEntropy.entropy_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10941 +} \ No newline at end of file diff --git a/tasks/matching-entropy/tests/test.sh b/tasks/matching-entropy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matching-entropy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matching-fpras/environment/Dockerfile b/tasks/matching-fpras/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matching-fpras/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matching-fpras/environment/fetch_mathlib.sh b/tasks/matching-fpras/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matching-fpras/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matching-fpras/environment/lake-manifest.json b/tasks/matching-fpras/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matching-fpras/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matching-fpras/environment/lakefile.lean b/tasks/matching-fpras/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matching-fpras/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matching-fpras/environment/lean_setup.sh b/tasks/matching-fpras/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matching-fpras/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matching-fpras/environment/pack_submission.py b/tasks/matching-fpras/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matching-fpras/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matching-fpras/instruction.md b/tasks/matching-fpras/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d8079582f150ad3fd385be1b7f390f64529d3fc --- /dev/null +++ b/tasks/matching-fpras/instruction.md @@ -0,0 +1,161 @@ +# openai/math challenge `MatchingFPRAS` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `MatchingFPRAS`, also at `/opt/openai-math/challenges/MatchingFPRAS.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MatchingFPRAS + +/-- Each unordered edge is represented once, by increasing endpoints. -/ +structure GraphInput where + n : ℕ + edges : Finset (Fin n × Fin n) + increasing : ∀ e ∈ edges, e.1 < e.2 + +/-- Exactly one selected edge is incident to every vertex. -/ +def Perfect (G : GraphInput) (M : Finset (Fin G.n × Fin G.n)) : Prop := + M ⊆ G.edges ∧ ∀ v : Fin G.n, ∃! e, e ∈ M ∧ (e.1 = v ∨ e.2 = v) + +noncomputable def perfectMatchings (G : GraphInput) : Finset (Finset (Fin G.n × Fin G.n)) := + by + classical + exact G.edges.powerset.filter (Perfect G) + +/-- The exact unweighted count, including the empty graph. -/ +noncomputable def Z (G : GraphInput) : ℕ := (perfectMatchings G).card + +abbrev Symbol := Fin 8 + +/-- Binary numeral followed by a delimiter. Tape blank is 0; bits use 1 and 2. -/ +def encodeNat (n : ℕ) : List Symbol := + (Nat.bits n).map (fun b => if b then 2 else 1) ++ [3] + +def encodeInt (z : ℤ) : List Symbol := + (if z < 0 then [5] else [4]) ++ encodeNat z.natAbs + +/-- A rational encoded by its reduced numerator and positive denominator. -/ +def encodeRat (q : ℚ) : List Symbol := encodeInt q.num ++ encodeNat q.den + +/-- Explicit sparse graph encoding, then the two rational parameters. -/ +def encodeInput (G : GraphInput) (ε δ : ℚ) : List Symbol := + encodeNat G.n ++ encodeNat G.edges.card ++ + (((G.edges.map toLex.toEmbedding).sort (· ≤ ·)).flatMap fun e => + encodeNat (ofLex e).1.val ++ encodeNat (ofLex e).2.val) ++ + encodeRat ε ++ encodeRat δ + +/-- A uniform randomized Post-Turing machine: a single finite transition table. -/ +structure RandomMachine where + states : ℕ + transition : Fin (states + 1) → Symbol → Bool → + Option (Fin (states + 1) × Turing.TM0.Stmt Symbol) + +structure Configuration (A : RandomMachine) where + state : Option (Fin (A.states + 1)) + tape : Turing.Tape Symbol + +/-- A halted configuration is absorbing. Each nonhalting tick is exactly one +write or one move, or the detection of halt. -/ +def tick (A : RandomMachine) (c : Configuration A) (bit : Bool) : Configuration A := + match c.state with + | none => c + | some s => match A.transition s c.tape.head bit with + | none => ⟨none, c.tape⟩ + | some (s', action) => + ⟨some s', match action with + | .move d => c.tape.move d + | .write a => c.tape.write a⟩ + +def initial (A : RandomMachine) (input : List Symbol) : Configuration A := + ⟨some 0, Turing.Tape.mk₁ input⟩ + +/-- Bounded execution on a finite prefix of the random tape. -/ +def run (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) : Configuration A := + (List.ofFn bits).foldl (tick A) (initial A input) + +def Outputs (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) (q : ℚ) : Prop := + (run A input bits).state = none ∧ + (run A input bits).tape.right₀ = Turing.ListBlank.mk (encodeRat q) + +/-- A fixed-degree polynomial in input bits, ε⁻¹, and log δ⁻¹. +Natural ceilings and binary ceiling-log change this bound only by constants. -/ +def timeBound (C d : ℕ) (G : GraphInput) (ε δ : ℚ) : ℕ := + C * ((encodeInput G ε δ).length + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodTapes (A : RandomMachine) (G : GraphInput) (ε δ : ℚ) + (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + Outputs A (encodeInput G ε δ) bits q ∧ + (1 - ε) * (Z G : ℚ) ≤ q ∧ q ≤ (1 + ε) * (Z G : ℚ) + +/-- A uniform approximation scheme using independent fair bits. All tapes halt +within the fixed polynomial bound and return a nonnegative rational. +A zero count always produces encoded zero. -/ +def MainStatement : Prop := + ∃ (A : RandomMachine) (C d : ℕ), 0 < C ∧ + ∀ (G : GraphInput) (ε δ : ℚ), 0 < ε → ε < 1 → 0 < δ → δ < 1 / 2 → + let t := timeBound C d G ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ Outputs A (encodeInput G ε δ) bits q) ∧ + (Z G = 0 → ∀ bits : Fin t → Bool, Outputs A (encodeInput G ε δ) bits 0) ∧ + ((goodTapes A G ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + + +/-- A fully polynomial randomized approximation scheme for perfect matchings +in every finite simple undirected graph. -/ +theorem thm_main : MainStatement := by + sorry + +end MatchingFPRAS + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatchingFPRAS.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MatchingFPRAS.thm_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matching-fpras/solution/closure.txt b/tasks/matching-fpras/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..efed05aad89d5e58c1e125978a2b06ad3de3cba8 --- /dev/null +++ b/tasks/matching-fpras/solution/closure.txt @@ -0,0 +1,415 @@ +OAI.Combinatorics.MatchingCount.Algorithm.AffineWeights +OAI.Combinatorics.MatchingCount.Algorithm.Algorithm +OAI.Combinatorics.MatchingCount.Algorithm.AlgorithmLaw +OAI.Combinatorics.MatchingCount.Algorithm.EmpiricalDenom +OAI.Combinatorics.MatchingCount.Algorithm.FiniteStage +OAI.Combinatorics.MatchingCount.Algorithm.FiniteTrial +OAI.Combinatorics.MatchingCount.Algorithm.FiniteTrialLaw +OAI.Combinatorics.MatchingCount.Algorithm.Guard +OAI.Combinatorics.MatchingCount.Algorithm.GuardBudget +OAI.Combinatorics.MatchingCount.Algorithm.GuardProbability +OAI.Combinatorics.MatchingCount.Algorithm.OnlineAmplification +OAI.Combinatorics.MatchingCount.Algorithm.OnlineCoolingSchedule +OAI.Combinatorics.MatchingCount.Algorithm.OnlineGuard +OAI.Combinatorics.MatchingCount.Algorithm.OnlineGuardLaw +OAI.Combinatorics.MatchingCount.Algorithm.OnlineHistorySize +OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitial +OAI.Combinatorics.MatchingCount.Algorithm.OnlineInitialLaw +OAI.Combinatorics.MatchingCount.Algorithm.OnlineLadderSchedule +OAI.Combinatorics.MatchingCount.Algorithm.OnlineLaw +OAI.Combinatorics.MatchingCount.Algorithm.OnlineMedian +OAI.Combinatorics.MatchingCount.Algorithm.OnlinePowerSearch +OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequest +OAI.Combinatorics.MatchingCount.Algorithm.OnlineRequestLaw +OAI.Combinatorics.MatchingCount.Algorithm.OnlineSampleCount +OAI.Combinatorics.MatchingCount.Algorithm.OnlineScheduleNat +OAI.Combinatorics.MatchingCount.Algorithm.OnlineStage +OAI.Combinatorics.MatchingCount.Algorithm.OnlineTransitionLaw +OAI.Combinatorics.MatchingCount.Algorithm.OnlineTrial +OAI.Combinatorics.MatchingCount.Algorithm.OnlineTrialLaw +OAI.Combinatorics.MatchingCount.Algorithm.OutputLengthBound +OAI.Combinatorics.MatchingCount.Algorithm.RationalCounts +OAI.Combinatorics.MatchingCount.Algorithm.RationalEstimator +OAI.Combinatorics.MatchingCount.Algorithm.RationalObservables +OAI.Combinatorics.MatchingCount.Algorithm.RationalScale +OAI.Combinatorics.MatchingCount.Algorithm.RationalStart +OAI.Combinatorics.MatchingCount.Algorithm.RationalUpdate +OAI.Combinatorics.MatchingCount.Algorithm.RelabelWeights +OAI.Combinatorics.MatchingCount.Algorithm.SortedList +OAI.Combinatorics.MatchingCount.Algorithm.TreeCertificate +OAI.Combinatorics.MatchingCount.Algorithm.TreeEstimator +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedCertificate +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedMarked +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedPrepared +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedStage +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedTop +OAI.Combinatorics.MatchingCount.Algorithm.TreeGeneratedUpdate +OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStage +OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatistics +OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericStatisticsCorrect +OAI.Combinatorics.MatchingCount.Algorithm.TreeNumericSummaries +OAI.Combinatorics.MatchingCount.Algorithm.TreeObservables +OAI.Combinatorics.MatchingCount.Algorithm.TreeObservablesCorrect +OAI.Combinatorics.MatchingCount.Algorithm.TreeReweight +OAI.Combinatorics.MatchingCount.Algorithm.TreeReweightTable +OAI.Combinatorics.MatchingCount.Algorithm.TreeScaling +OAI.Combinatorics.MatchingCount.Algorithm.TreeScalingCorrect +OAI.Combinatorics.MatchingCount.Algorithm.TreeStageActivity +OAI.Combinatorics.MatchingCount.Algorithm.TreeStageStatistics +OAI.Combinatorics.MatchingCount.Algorithm.TreeStageStatisticsCorrect +OAI.Combinatorics.MatchingCount.Algorithm.TreeStageUpdateCorrect +OAI.Combinatorics.MatchingCount.Algorithm.TreeStatistics +OAI.Combinatorics.MatchingCount.Algorithm.TreeTierWeights +OAI.Combinatorics.MatchingCount.Algorithm.TreeWeights +OAI.Combinatorics.MatchingCount.Algorithm.TreeWeightsCorrect +OAI.Combinatorics.MatchingCount.Arithmetic.ArithmeticSize +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryAddition +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryCompare +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryCopy +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryDivision +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryIncrement +OAI.Combinatorics.MatchingCount.Arithmetic.BinaryNormalize +OAI.Combinatorics.MatchingCount.Arithmetic.BinarySubtract +OAI.Combinatorics.MatchingCount.Arithmetic.OnlineFractionParam +OAI.Combinatorics.MatchingCount.Arithmetic.PostAddition +OAI.Combinatorics.MatchingCount.Arithmetic.PostComparison +OAI.Combinatorics.MatchingCount.Arithmetic.SubtractProc +OAI.Combinatorics.MatchingCount.Arithmetic.TreeAdaptiveArithmetic +OAI.Combinatorics.MatchingCount.Arithmetic.TreeCompare +OAI.Combinatorics.MatchingCount.Arithmetic.TreeDivision +OAI.Combinatorics.MatchingCount.Arithmetic.TreeDyadic +OAI.Combinatorics.MatchingCount.Arithmetic.TreeFraction +OAI.Combinatorics.MatchingCount.Arithmetic.TreeFractionExtra +OAI.Combinatorics.MatchingCount.Arithmetic.TreeGCD +OAI.Combinatorics.MatchingCount.Arithmetic.TreeMultiply +OAI.Combinatorics.MatchingCount.Arithmetic.TreeNatDivision +OAI.Combinatorics.MatchingCount.Arithmetic.TreeNumberOps +OAI.Combinatorics.MatchingCount.Arithmetic.TreeStateNormalize +OAI.Combinatorics.MatchingCount.Arithmetic.TreeSubtract +OAI.Combinatorics.MatchingCount.Complexity.AlphabetCompilerCost +OAI.Combinatorics.MatchingCount.Complexity.ComputeCost +OAI.Combinatorics.MatchingCount.Complexity.GuardMachineBase +OAI.Combinatorics.MatchingCount.Complexity.OnlineCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineFoldCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineFrameCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineHistoryCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineInitialCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineInitialDataCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineRequestCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineRunCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineSampleCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineScheduleCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineStageCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineTraverseCost +OAI.Combinatorics.MatchingCount.Complexity.OnlineWordCost +OAI.Combinatorics.MatchingCount.Complexity.OriginalCost +OAI.Combinatorics.MatchingCount.Complexity.PhysicalCost +OAI.Combinatorics.MatchingCount.Complexity.StackCompilerCost +OAI.Combinatorics.MatchingCount.Complexity.TreeChoiceCosts +OAI.Combinatorics.MatchingCount.Complexity.TreeCostMeasure +OAI.Combinatorics.MatchingCount.Complexity.TreeCostTactic +OAI.Combinatorics.MatchingCount.Complexity.TreeFractionCosts +OAI.Combinatorics.MatchingCount.Complexity.TreeNumericCosts +OAI.Combinatorics.MatchingCount.Complexity.TreePolyTactic +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomial +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialArithmetic +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialCollections +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialDivision +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGCD +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialGrid +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLists +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialLoop +OAI.Combinatorics.MatchingCount.Complexity.TreePolynomialSums +OAI.Combinatorics.MatchingCount.Graphs.AdaptiveStream +OAI.Combinatorics.MatchingCount.Graphs.Admissible +OAI.Combinatorics.MatchingCount.Graphs.ArcData +OAI.Combinatorics.MatchingCount.Graphs.ColoredEdge +OAI.Combinatorics.MatchingCount.Graphs.CompleteGraph +OAI.Combinatorics.MatchingCount.Graphs.Cumulative +OAI.Combinatorics.MatchingCount.Graphs.Cycle +OAI.Combinatorics.MatchingCount.Graphs.Density +OAI.Combinatorics.MatchingCount.Graphs.Edge +OAI.Combinatorics.MatchingCount.Graphs.Edge2 +OAI.Combinatorics.MatchingCount.Graphs.EdgeLow +OAI.Combinatorics.MatchingCount.Graphs.EnlargementRun +OAI.Combinatorics.MatchingCount.Graphs.Evolve +OAI.Combinatorics.MatchingCount.Graphs.ExperimentSupport +OAI.Combinatorics.MatchingCount.Graphs.FillHoles +OAI.Combinatorics.MatchingCount.Graphs.FirstHoleSortedCons +OAI.Combinatorics.MatchingCount.Graphs.Height +OAI.Combinatorics.MatchingCount.Graphs.HoleBlocks +OAI.Combinatorics.MatchingCount.Graphs.HoleStrength +OAI.Combinatorics.MatchingCount.Graphs.Incident +OAI.Combinatorics.MatchingCount.Graphs.IndexedCycle +OAI.Combinatorics.MatchingCount.Graphs.LabelCycle +OAI.Combinatorics.MatchingCount.Graphs.LabelOrder +OAI.Combinatorics.MatchingCount.Graphs.Marked +OAI.Combinatorics.MatchingCount.Graphs.MatchingMap +OAI.Combinatorics.MatchingCount.Graphs.Mate +OAI.Combinatorics.MatchingCount.Graphs.OnlineGraphInvariant +OAI.Combinatorics.MatchingCount.Graphs.Output +OAI.Combinatorics.MatchingCount.Graphs.PM +OAI.Combinatorics.MatchingCount.Graphs.PathActivity +OAI.Combinatorics.MatchingCount.Graphs.PathStrength +OAI.Combinatorics.MatchingCount.Graphs.Profile +OAI.Combinatorics.MatchingCount.Graphs.PushedFlow +OAI.Combinatorics.MatchingCount.Graphs.RatWeight +OAI.Combinatorics.MatchingCount.Graphs.RelabelMore +OAI.Combinatorics.MatchingCount.Graphs.Related +OAI.Combinatorics.MatchingCount.Graphs.Related2 +OAI.Combinatorics.MatchingCount.Graphs.RemainingBags +OAI.Combinatorics.MatchingCount.Graphs.RowPeak +OAI.Combinatorics.MatchingCount.Graphs.SafeSwitch +OAI.Combinatorics.MatchingCount.Graphs.SafeTrace +OAI.Combinatorics.MatchingCount.Graphs.Sets +OAI.Combinatorics.MatchingCount.Graphs.SumLiftMate +OAI.Combinatorics.MatchingCount.Graphs.ThresholdGraph +OAI.Combinatorics.MatchingCount.Graphs.TreeBagBuild +OAI.Combinatorics.MatchingCount.Graphs.TreeBagCorrect +OAI.Combinatorics.MatchingCount.Graphs.TreeBagTable +OAI.Combinatorics.MatchingCount.Graphs.TreeBags +OAI.Combinatorics.MatchingCount.Graphs.TreeCycleTable +OAI.Combinatorics.MatchingCount.Graphs.TreeGeometry +OAI.Combinatorics.MatchingCount.Graphs.TreeHeight +OAI.Combinatorics.MatchingCount.Graphs.TreeHierarchyReindex +OAI.Combinatorics.MatchingCount.Graphs.TreeHierarchyRoot +OAI.Combinatorics.MatchingCount.Graphs.TreeInitialMatching +OAI.Combinatorics.MatchingCount.Graphs.TreeMatchingCheck +OAI.Combinatorics.MatchingCount.Graphs.TreeProfile +OAI.Combinatorics.MatchingCount.Graphs.TreeRankPlan +OAI.Combinatorics.MatchingCount.Graphs.TreeSwitchRaw +OAI.Combinatorics.MatchingCount.Graphs.TreeSwitchValid +OAI.Combinatorics.MatchingCount.Graphs.Vertex +OAI.Combinatorics.MatchingCount.Machines.BoolPostCompiler +OAI.Combinatorics.MatchingCount.Machines.CoinTM1 +OAI.Combinatorics.MatchingCount.Machines.CoinTM1Finite +OAI.Combinatorics.MatchingCount.Machines.FiniteStore +OAI.Combinatorics.MatchingCount.Machines.OnlineBounds +OAI.Combinatorics.MatchingCount.Machines.OnlineCase +OAI.Combinatorics.MatchingCount.Machines.OnlineControl +OAI.Combinatorics.MatchingCount.Machines.OnlineFold +OAI.Combinatorics.MatchingCount.Machines.OnlineFrame +OAI.Combinatorics.MatchingCount.Machines.OnlinePhysicalProgram +OAI.Combinatorics.MatchingCount.Machines.OnlineTraverse +OAI.Combinatorics.MatchingCount.Machines.OnlineTree +OAI.Combinatorics.MatchingCount.Machines.OnlineUniform +OAI.Combinatorics.MatchingCount.Machines.PhysicalPost +OAI.Combinatorics.MatchingCount.Machines.PhysicalProcess +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgram +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramMap +OAI.Combinatorics.MatchingCount.Machines.PhysicalProgramSeal +OAI.Combinatorics.MatchingCount.Machines.PhysicalRestriction +OAI.Combinatorics.MatchingCount.Machines.PhysicalSequential +OAI.Combinatorics.MatchingCount.Machines.ProgramComposition +OAI.Combinatorics.MatchingCount.Machines.RegisterControl +OAI.Combinatorics.MatchingCount.Machines.RegisterProc +OAI.Combinatorics.MatchingCount.Machines.RegisterStructured +OAI.Combinatorics.MatchingCount.Machines.RegisterTree +OAI.Combinatorics.MatchingCount.Machines.SupportedCompiler +OAI.Combinatorics.MatchingCount.Machines.TableLookup +OAI.Combinatorics.MatchingCount.Machines.TreeBindings +OAI.Combinatorics.MatchingCount.Machines.TreeBottleneck +OAI.Combinatorics.MatchingCount.Machines.TreeBottleneckCorrect +OAI.Combinatorics.MatchingCount.Machines.TreeBuild +OAI.Combinatorics.MatchingCount.Machines.TreeCanonical +OAI.Combinatorics.MatchingCount.Machines.TreeCappedAssembly +OAI.Combinatorics.MatchingCount.Machines.TreeCertify +OAI.Combinatorics.MatchingCount.Machines.TreeChoice +OAI.Combinatorics.MatchingCount.Machines.TreeClippedCorrect +OAI.Combinatorics.MatchingCount.Machines.TreeClippedRun +OAI.Combinatorics.MatchingCount.Machines.TreeClosureReindex +OAI.Combinatorics.MatchingCount.Machines.TreeColex +OAI.Combinatorics.MatchingCount.Machines.TreeColor +OAI.Combinatorics.MatchingCount.Machines.TreeColorRaw +OAI.Combinatorics.MatchingCount.Machines.TreeColoredIndex +OAI.Combinatorics.MatchingCount.Machines.TreeCompiler +OAI.Combinatorics.MatchingCount.Machines.TreeEnumeration +OAI.Combinatorics.MatchingCount.Machines.TreeFastChoose +OAI.Combinatorics.MatchingCount.Machines.TreeFastLookup +OAI.Combinatorics.MatchingCount.Machines.TreeFinite +OAI.Combinatorics.MatchingCount.Machines.TreeFiniteCollections +OAI.Combinatorics.MatchingCount.Machines.TreeFiniteOps +OAI.Combinatorics.MatchingCount.Machines.TreeFold +OAI.Combinatorics.MatchingCount.Machines.TreeFrame +OAI.Combinatorics.MatchingCount.Machines.TreeFunction +OAI.Combinatorics.MatchingCount.Machines.TreeGuideTables +OAI.Combinatorics.MatchingCount.Machines.TreeHistorySize +OAI.Combinatorics.MatchingCount.Machines.TreeIndex +OAI.Combinatorics.MatchingCount.Machines.TreeInitial +OAI.Combinatorics.MatchingCount.Machines.TreeLabelCorrect +OAI.Combinatorics.MatchingCount.Machines.TreeLabelTable +OAI.Combinatorics.MatchingCount.Machines.TreeLanguage +OAI.Combinatorics.MatchingCount.Machines.TreeList +OAI.Combinatorics.MatchingCount.Machines.TreeListMore +OAI.Combinatorics.MatchingCount.Machines.TreeListOps +OAI.Combinatorics.MatchingCount.Machines.TreeLookup +OAI.Combinatorics.MatchingCount.Machines.TreeMachine +OAI.Combinatorics.MatchingCount.Machines.TreeMarkTable +OAI.Combinatorics.MatchingCount.Machines.TreeMatrix +OAI.Combinatorics.MatchingCount.Machines.TreeMetadata +OAI.Combinatorics.MatchingCount.Machines.TreeNaturalComb +OAI.Combinatorics.MatchingCount.Machines.TreeNumberedSets +OAI.Combinatorics.MatchingCount.Machines.TreeOrderedTransport +OAI.Combinatorics.MatchingCount.Machines.TreePairProposal +OAI.Combinatorics.MatchingCount.Machines.TreeParentTable +OAI.Combinatorics.MatchingCount.Machines.TreePartialChoice +OAI.Combinatorics.MatchingCount.Machines.TreePhantom +OAI.Combinatorics.MatchingCount.Machines.TreePortion +OAI.Combinatorics.MatchingCount.Machines.TreePostRealization +OAI.Combinatorics.MatchingCount.Machines.TreePredicate +OAI.Combinatorics.MatchingCount.Machines.TreeProgramUnique +OAI.Combinatorics.MatchingCount.Machines.TreeQuad +OAI.Combinatorics.MatchingCount.Machines.TreeQuadDistinct +OAI.Combinatorics.MatchingCount.Machines.TreeRationalWeight +OAI.Combinatorics.MatchingCount.Machines.TreeReach +OAI.Combinatorics.MatchingCount.Machines.TreeReachCorrect +OAI.Combinatorics.MatchingCount.Machines.TreeRefresh +OAI.Combinatorics.MatchingCount.Machines.TreeRefreshCatalog +OAI.Combinatorics.MatchingCount.Machines.TreeRefreshIndexed +OAI.Combinatorics.MatchingCount.Machines.TreeRefreshNumbered +OAI.Combinatorics.MatchingCount.Machines.TreeRefreshTables +OAI.Combinatorics.MatchingCount.Machines.TreeRepeat +OAI.Combinatorics.MatchingCount.Machines.TreeScaleStateUpdate +OAI.Combinatorics.MatchingCount.Machines.TreeSlotIndex +OAI.Combinatorics.MatchingCount.Machines.TreeSlotWeight +OAI.Combinatorics.MatchingCount.Machines.TreeStart +OAI.Combinatorics.MatchingCount.Machines.TreeStateTable +OAI.Combinatorics.MatchingCount.Machines.TreeSum +OAI.Combinatorics.MatchingCount.Machines.TreeTransfer +OAI.Combinatorics.MatchingCount.Machines.TreeTyped +OAI.Combinatorics.MatchingCount.Machines.TreeWeightTable +OAI.Combinatorics.MatchingCount.Machines.Wrapper +OAI.Combinatorics.MatchingCount.Main +OAI.Combinatorics.MatchingCount.Model +OAI.Combinatorics.MatchingCount.Probability.AdaptiveLaw +OAI.Combinatorics.MatchingCount.Probability.FinitePMF +OAI.Combinatorics.MatchingCount.Probability.LocalVariance +OAI.Combinatorics.MatchingCount.Probability.MainLaw +OAI.Combinatorics.MatchingCount.Probability.Marking +OAI.Combinatorics.MatchingCount.Probability.Mean +OAI.Combinatorics.MatchingCount.Probability.OnlineLawBridge +OAI.Combinatorics.MatchingCount.Probability.OnlineLayerLaw +OAI.Combinatorics.MatchingCount.Probability.OnlineSampleLaw +OAI.Combinatorics.MatchingCount.Probability.Tv +OAI.Combinatorics.MatchingCount.Probability.Variance +OAI.Combinatorics.MatchingCount.Sampling.AssignmentEquiv +OAI.Combinatorics.MatchingCount.Sampling.Certify +OAI.Combinatorics.MatchingCount.Sampling.ChosenChord +OAI.Combinatorics.MatchingCount.Sampling.ClippedEnvelope +OAI.Combinatorics.MatchingCount.Sampling.Component +OAI.Combinatorics.MatchingCount.Sampling.ComponentOrder +OAI.Combinatorics.MatchingCount.Sampling.Components +OAI.Combinatorics.MatchingCount.Sampling.Corner +OAI.Combinatorics.MatchingCount.Sampling.DPEnvelope +OAI.Combinatorics.MatchingCount.Sampling.DiscreteLadderSteps +OAI.Combinatorics.MatchingCount.Sampling.EndpointPair +OAI.Combinatorics.MatchingCount.Sampling.Endpoints +OAI.Combinatorics.MatchingCount.Sampling.Endpoints2 +OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler +OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler2 +OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler3 +OAI.Combinatorics.MatchingCount.Sampling.FiniteSampler4 +OAI.Combinatorics.MatchingCount.Sampling.IntervalPattern +OAI.Combinatorics.MatchingCount.Sampling.LadderL +OAI.Combinatorics.MatchingCount.Sampling.MarkBridge +OAI.Combinatorics.MatchingCount.Sampling.MetropolisChoice +OAI.Combinatorics.MatchingCount.Sampling.OnlineSample +OAI.Combinatorics.MatchingCount.Sampling.PM +OAI.Combinatorics.MatchingCount.Sampling.PairStep +OAI.Combinatorics.MatchingCount.Sampling.Plan +OAI.Combinatorics.MatchingCount.Sampling.RankOrder +OAI.Combinatorics.MatchingCount.Sampling.Relabel +OAI.Combinatorics.MatchingCount.Sampling.RelabelMarking +OAI.Combinatorics.MatchingCount.Sampling.RelationDestinations +OAI.Combinatorics.MatchingCount.Sampling.Sewn +OAI.Combinatorics.MatchingCount.Sampling.Span +OAI.Combinatorics.MatchingCount.Sampling.Sym2Order +OAI.Combinatorics.MatchingCount.Sampling.TableMarking +OAI.Combinatorics.MatchingCount.Sampling.Through +OAI.Combinatorics.MatchingCount.Sampling.TierClamp +OAI.Combinatorics.MatchingCount.Sampling.TreeCategorical +OAI.Combinatorics.MatchingCount.Sampling.TreeCategoricalValues +OAI.Combinatorics.MatchingCount.Sampling.TreeClippedDP +OAI.Combinatorics.MatchingCount.Sampling.TreeDPCount +OAI.Combinatorics.MatchingCount.Sampling.TreeDPCounts +OAI.Combinatorics.MatchingCount.Sampling.TreeDPEntry +OAI.Combinatorics.MatchingCount.Sampling.TreeDPProgram +OAI.Combinatorics.MatchingCount.Sampling.TreeDPRepresentation +OAI.Combinatorics.MatchingCount.Sampling.TreeFastDPEntry +OAI.Combinatorics.MatchingCount.Sampling.TreeFastDescent +OAI.Combinatorics.MatchingCount.Sampling.TreeFastSample +OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnit +OAI.Combinatorics.MatchingCount.Sampling.TreeFastUnitCorrect +OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPair +OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairCorrect +OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairPost +OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairResult +OAI.Combinatorics.MatchingCount.Sampling.TreeIndexedPairUniform +OAI.Combinatorics.MatchingCount.Sampling.TreeLadder +OAI.Combinatorics.MatchingCount.Sampling.TreeLadderContext +OAI.Combinatorics.MatchingCount.Sampling.TreeLadderIndexed +OAI.Combinatorics.MatchingCount.Sampling.TreeLadderPost +OAI.Combinatorics.MatchingCount.Sampling.TreeLocalSampler +OAI.Combinatorics.MatchingCount.Sampling.TreeMarking +OAI.Combinatorics.MatchingCount.Sampling.TreeNumericLadder +OAI.Combinatorics.MatchingCount.Sampling.TreeNumericMarking +OAI.Combinatorics.MatchingCount.Sampling.TreeOptions +OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsAccept +OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsFinite +OAI.Combinatorics.MatchingCount.Sampling.TreeOptionsMaps +OAI.Combinatorics.MatchingCount.Sampling.TreePairStep +OAI.Combinatorics.MatchingCount.Sampling.TreePairTable +OAI.Combinatorics.MatchingCount.Sampling.TreePrepareLadder +OAI.Combinatorics.MatchingCount.Sampling.TreePrepared +OAI.Combinatorics.MatchingCount.Sampling.TreePreparedMarked +OAI.Combinatorics.MatchingCount.Sampling.TreePreparedTop +OAI.Combinatorics.MatchingCount.Sampling.TreeProbe +OAI.Combinatorics.MatchingCount.Sampling.TreeSamplerRows +OAI.Combinatorics.MatchingCount.Sampling.TreeScan +OAI.Combinatorics.MatchingCount.Sampling.TreeScanChoice +OAI.Combinatorics.MatchingCount.Sampling.TreeScanRun +OAI.Combinatorics.MatchingCount.Sampling.TreeUnitAssemble +OAI.Combinatorics.MatchingCount.Sampling.TreeUnitBranch +OAI.Combinatorics.MatchingCount.Sampling.TreeUnitCorrect +OAI.Combinatorics.MatchingCount.Sampling.TreeUnitDraw +OAI.Combinatorics.MatchingCount.Sampling.TreeUnitSampler +OAI.Combinatorics.MatchingCount.Sampling.Underlying +OAI.Combinatorics.MatchingCount.Tapes.BlockMap +OAI.Combinatorics.MatchingCount.Tapes.Codec +OAI.Combinatorics.MatchingCount.Tapes.CoinAlphabet +OAI.Combinatorics.MatchingCount.Tapes.CoinStack +OAI.Combinatorics.MatchingCount.Tapes.CoinSupport +OAI.Combinatorics.MatchingCount.Tapes.FixedAlphabetCompiler +OAI.Combinatorics.MatchingCount.Tapes.FixedEncoding +OAI.Combinatorics.MatchingCount.Tapes.GuardBits +OAI.Combinatorics.MatchingCount.Tapes.Input +OAI.Combinatorics.MatchingCount.Tapes.Online +OAI.Combinatorics.MatchingCount.Tapes.OnlineComposition +OAI.Combinatorics.MatchingCount.Tapes.OnlineStackCompiler +OAI.Combinatorics.MatchingCount.Tapes.OnlineWord +OAI.Combinatorics.MatchingCount.Tapes.Packed +OAI.Combinatorics.MatchingCount.Tapes.PackedExecution +OAI.Combinatorics.MatchingCount.Tapes.PackedInverse +OAI.Combinatorics.MatchingCount.Tapes.Parse +OAI.Combinatorics.MatchingCount.Tapes.Physical +OAI.Combinatorics.MatchingCount.Tapes.PhysicalAlphabet +OAI.Combinatorics.MatchingCount.Tapes.ProductBits +OAI.Combinatorics.MatchingCount.Tapes.RandomReservoir +OAI.Combinatorics.MatchingCount.Tapes.RandomWord +OAI.Combinatorics.MatchingCount.Tapes.RandomWordLaw +OAI.Combinatorics.MatchingCount.Tapes.RunBits +OAI.Combinatorics.MatchingCount.Tapes.StackEmbedding +OAI.Combinatorics.MatchingCount.Tapes.StackLens +OAI.Combinatorics.MatchingCount.Tapes.StackWords +OAI.Combinatorics.MatchingCount.Tapes.TapeTools +OAI.Combinatorics.MatchingCount.Tapes.TreeAddBits +OAI.Combinatorics.MatchingCount.Tapes.TreeBits +OAI.Combinatorics.MatchingCount.Tapes.TreeEncodingInjective +OAI.Combinatorics.MatchingCount.Tapes.TreeErasure +OAI.Combinatorics.MatchingCount.Tapes.TreeErasurePrimitives +OAI.Combinatorics.MatchingCount.Tapes.TreeNumberedCodec +OAI.Combinatorics.MatchingCount.Tapes.TreeSparseCertificate +OAI.Combinatorics.MatchingCount.Tapes.TreeSparseComponents +OAI.Combinatorics.MatchingCount.Tapes.TreeSparseNeighbors +OAI.Combinatorics.MatchingCount.Tapes.TreeSparseStage +OAI.Combinatorics.MatchingCount.Tapes.WordOps diff --git a/tasks/matching-fpras/solution/reference.py b/tasks/matching-fpras/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matching-fpras/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matching-fpras/solution/solve.sh b/tasks/matching-fpras/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b0e36fb2a6936c565c19b8df759b98ec101d9e5 --- /dev/null +++ b/tasks/matching-fpras/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatchingFPRAS, i.e. module OAI.Combinatorics.MatchingCount.Main and the +# 415 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatchingCount.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatchingFPRAS" diff --git a/tasks/matching-fpras/task.toml b/tasks/matching-fpras/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..59e984e5a66ed30481417c059b66959b84b0d0ca --- /dev/null +++ b/tasks/matching-fpras/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matching-fpras" +version = "1.0.0" +description = "Prove MatchingFPRAS (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatchingFPRAS.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatchingFPRAS" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.MatchingFPRAS.thm_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatchingCount.Main" +reference_modules = 415 +reference_lean_bytes = 3091883 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1267 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14482 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matching-fpras/tests/Challenge.lean b/tasks/matching-fpras/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..453b4a578bff8914eac4b180ab9901d570b4fc03 --- /dev/null +++ b/tasks/matching-fpras/tests/Challenge.lean @@ -0,0 +1,110 @@ +import Mathlib + +namespace OAI + +namespace MatchingFPRAS + +/-- Each unordered edge is represented once, by increasing endpoints. -/ +structure GraphInput where + n : ℕ + edges : Finset (Fin n × Fin n) + increasing : ∀ e ∈ edges, e.1 < e.2 + +/-- Exactly one selected edge is incident to every vertex. -/ +def Perfect (G : GraphInput) (M : Finset (Fin G.n × Fin G.n)) : Prop := + M ⊆ G.edges ∧ ∀ v : Fin G.n, ∃! e, e ∈ M ∧ (e.1 = v ∨ e.2 = v) + +noncomputable def perfectMatchings (G : GraphInput) : Finset (Finset (Fin G.n × Fin G.n)) := + by + classical + exact G.edges.powerset.filter (Perfect G) + +/-- The exact unweighted count, including the empty graph. -/ +noncomputable def Z (G : GraphInput) : ℕ := (perfectMatchings G).card + +abbrev Symbol := Fin 8 + +/-- Binary numeral followed by a delimiter. Tape blank is 0; bits use 1 and 2. -/ +def encodeNat (n : ℕ) : List Symbol := + (Nat.bits n).map (fun b => if b then 2 else 1) ++ [3] + +def encodeInt (z : ℤ) : List Symbol := + (if z < 0 then [5] else [4]) ++ encodeNat z.natAbs + +/-- A rational encoded by its reduced numerator and positive denominator. -/ +def encodeRat (q : ℚ) : List Symbol := encodeInt q.num ++ encodeNat q.den + +/-- Explicit sparse graph encoding, then the two rational parameters. -/ +def encodeInput (G : GraphInput) (ε δ : ℚ) : List Symbol := + encodeNat G.n ++ encodeNat G.edges.card ++ + (((G.edges.map toLex.toEmbedding).sort (· ≤ ·)).flatMap fun e => + encodeNat (ofLex e).1.val ++ encodeNat (ofLex e).2.val) ++ + encodeRat ε ++ encodeRat δ + +/-- A uniform randomized Post-Turing machine: a single finite transition table. -/ +structure RandomMachine where + states : ℕ + transition : Fin (states + 1) → Symbol → Bool → + Option (Fin (states + 1) × Turing.TM0.Stmt Symbol) + +structure Configuration (A : RandomMachine) where + state : Option (Fin (A.states + 1)) + tape : Turing.Tape Symbol + +/-- A halted configuration is absorbing. Each nonhalting tick is exactly one +write or one move, or the detection of halt. -/ +def tick (A : RandomMachine) (c : Configuration A) (bit : Bool) : Configuration A := + match c.state with + | none => c + | some s => match A.transition s c.tape.head bit with + | none => ⟨none, c.tape⟩ + | some (s', action) => + ⟨some s', match action with + | .move d => c.tape.move d + | .write a => c.tape.write a⟩ + +def initial (A : RandomMachine) (input : List Symbol) : Configuration A := + ⟨some 0, Turing.Tape.mk₁ input⟩ + +/-- Bounded execution on a finite prefix of the random tape. -/ +def run (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) : Configuration A := + (List.ofFn bits).foldl (tick A) (initial A input) + +def Outputs (A : RandomMachine) (input : List Symbol) {t : ℕ} + (bits : Fin t → Bool) (q : ℚ) : Prop := + (run A input bits).state = none ∧ + (run A input bits).tape.right₀ = Turing.ListBlank.mk (encodeRat q) + +/-- A fixed-degree polynomial in input bits, ε⁻¹, and log δ⁻¹. +Natural ceilings and binary ceiling-log change this bound only by constants. -/ +def timeBound (C d : ℕ) (G : GraphInput) (ε δ : ℚ) : ℕ := + C * ((encodeInput G ε δ).length + ⌈ε⁻¹⌉₊ + Nat.clog 2 ⌈δ⁻¹⌉₊ + 1) ^ d + +noncomputable def goodTapes (A : RandomMachine) (G : GraphInput) (ε δ : ℚ) + (t : ℕ) : Finset (Fin t → Bool) := by + classical + exact Finset.univ.filter fun bits => ∃ q : ℚ, + Outputs A (encodeInput G ε δ) bits q ∧ + (1 - ε) * (Z G : ℚ) ≤ q ∧ q ≤ (1 + ε) * (Z G : ℚ) + +/-- A uniform approximation scheme using independent fair bits. All tapes halt +within the fixed polynomial bound and return a nonnegative rational. +A zero count always produces encoded zero. -/ +def MainStatement : Prop := + ∃ (A : RandomMachine) (C d : ℕ), 0 < C ∧ + ∀ (G : GraphInput) (ε δ : ℚ), 0 < ε → ε < 1 → 0 < δ → δ < 1 / 2 → + let t := timeBound C d G ε δ + (∀ bits : Fin t → Bool, ∃ q : ℚ, 0 ≤ q ∧ Outputs A (encodeInput G ε δ) bits q) ∧ + (Z G = 0 → ∀ bits : Fin t → Bool, Outputs A (encodeInput G ε δ) bits 0) ∧ + ((goodTapes A G ε δ t).card : ℚ) / (2 : ℚ) ^ t ≥ 1 - δ + + +/-- A fully polynomial randomized approximation scheme for perfect matchings +in every finite simple undirected graph. -/ +theorem thm_main : MainStatement := by + sorry + +end MatchingFPRAS + +end OAI diff --git a/tasks/matching-fpras/tests/grade.py b/tasks/matching-fpras/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matching-fpras/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matching-fpras/tests/task.json b/tasks/matching-fpras/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..101df303b9f4a375a04320e16f21a2d919983e51 --- /dev/null +++ b/tasks/matching-fpras/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatchingFPRAS", + "comparator": { + "theorem_names": [ + "OAI.MatchingFPRAS.thm_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13582 +} \ No newline at end of file diff --git a/tasks/matching-fpras/tests/test.sh b/tasks/matching-fpras/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matching-fpras/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matching-psd/environment/Dockerfile b/tasks/matching-psd/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matching-psd/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matching-psd/environment/fetch_mathlib.sh b/tasks/matching-psd/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matching-psd/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matching-psd/environment/lake-manifest.json b/tasks/matching-psd/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matching-psd/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matching-psd/environment/lakefile.lean b/tasks/matching-psd/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matching-psd/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matching-psd/environment/lean_setup.sh b/tasks/matching-psd/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matching-psd/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matching-psd/environment/pack_submission.py b/tasks/matching-psd/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matching-psd/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matching-psd/instruction.md b/tasks/matching-psd/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3c39a2c16981206e4985d9ac67f11e63ae1cd0c --- /dev/null +++ b/tasks/matching-psd/instruction.md @@ -0,0 +1,106 @@ +# openai/math challenge `MatchingPSD` (family 126) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 126 of the release, *Exponential semidefinite complexity of perfect matching* +(Theoretical computer science). The family as a whole: Proves that every exact semidefinite lift of the perfect matching polytope has exponential size, answering Rothvoss's polynomial-size lift question negatively. The bound holds even for the positive semidefinite rank of its odd-cut slack matrix after any fixed shift $0<\rho<1$, allowing arbitrary real positive semidefinite factors. + +The challenge is `MatchingPSD`, also at `/opt/openai-math/challenges/MatchingPSD.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PerfectMatchingPSD + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +def IsPerfectMatching {n : ℕ} (M : Finset (Edge n)) : Prop := + ∀ v : Fin n, (M.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 + +abbrev PerfectMatching (n : ℕ) := + {M : Finset (Edge n) // IsPerfectMatching M} + +abbrev OddCut (n : ℕ) := {U : Finset (Fin n) // Odd U.card} + +abbrev Row (n : ℕ) := Edge n ⊕ OddCut n + +def Crosses {n : ℕ} (U : Finset (Fin n)) (e : Edge n) : Prop := + (e.1.1 ∈ U ∧ e.1.2 ∉ U) ∨ (e.1.1 ∉ U ∧ e.1.2 ∈ U) + +noncomputable def crossingCount {n : ℕ} (U : Finset (Fin n)) + (M : PerfectMatching n) : ℕ := by + classical + exact (M.1.filter (Crosses U)).card + +noncomputable def slack {n : ℕ} (i : Row n) (M : PerfectMatching n) : ℝ := by + classical + exact match i with + | Sum.inl e => if e ∈ M.1 then 1 else 0 + | Sum.inr U => (crossingCount U.1 M : ℝ) - 1 + +/-- Real PSD factors of order `r`, without equivariance or rank-one restrictions. -/ +def HasFactorization (n r : ℕ) : Prop := + ∃ (A : Row n → Matrix (Fin r) (Fin r) ℝ) + (B : PerfectMatching n → Matrix (Fin r) (Fin r) ℝ), + (∀ i, (A i).PosSemidef) ∧ (∀ M, (B M).PosSemidef) ∧ + ∀ i M, slack i M = Matrix.trace (A i * B M) + +/-- The least positive order of a real PSD factorization. -/ +noncomputable def psdRank (n : ℕ) : ℕ := + sInf {r : ℕ | 0 < r ∧ HasFactorization n r} + +/-- Every positive real power is eventually smaller than the PSD rank, +uniformly over all even vertex counts. The exponentiation is real `rpow`. -/ +def MainClaim : Prop := + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → (n : ℝ) ^ C < (psdRank n : ℝ) + +theorem main : MainClaim := by + sorry + +end PerfectMatchingPSD + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatchingPSD.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PerfectMatchingPSD.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matching-psd/solution/closure.txt b/tasks/matching-psd/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..874aad2510c05ca9784e7f781bb3e56279c40a1d --- /dev/null +++ b/tasks/matching-psd/solution/closure.txt @@ -0,0 +1,53 @@ +OAI.Combinatorics.MatchingPSD.AdmissiblePoints +OAI.Combinatorics.MatchingPSD.AdmissibleTables +OAI.Combinatorics.MatchingPSD.BitTests +OAI.Combinatorics.MatchingPSD.CellAverages +OAI.Combinatorics.MatchingPSD.CellDecoder +OAI.Combinatorics.MatchingPSD.CellLowerBound +OAI.Combinatorics.MatchingPSD.ColorPolynomials +OAI.Combinatorics.MatchingPSD.ColoringCounts +OAI.Combinatorics.MatchingPSD.CommonSelection +OAI.Combinatorics.MatchingPSD.CrossSelection +OAI.Combinatorics.MatchingPSD.CutGeometry +OAI.Combinatorics.MatchingPSD.DeterminantNormalization +OAI.Combinatorics.MatchingPSD.DominationDecoder +OAI.Combinatorics.MatchingPSD.EdgeMonomials +OAI.Combinatorics.MatchingPSD.EdgeProducts +OAI.Combinatorics.MatchingPSD.EquivariantCompression +OAI.Combinatorics.MatchingPSD.FiberAverages +OAI.Combinatorics.MatchingPSD.FiniteFactorization +OAI.Combinatorics.MatchingPSD.GlobalGeometry +OAI.Combinatorics.MatchingPSD.GoodCells +OAI.Combinatorics.MatchingPSD.IncidenceKernels +OAI.Combinatorics.MatchingPSD.Involutions +OAI.Combinatorics.MatchingPSD.Main +OAI.Combinatorics.MatchingPSD.MatchingConversion +OAI.Combinatorics.MatchingPSD.MatchingFibers +OAI.Combinatorics.MatchingPSD.MatchingIncidence +OAI.Combinatorics.MatchingPSD.MatrixAverages +OAI.Combinatorics.MatchingPSD.MatrixBounds +OAI.Combinatorics.MatchingPSD.MatrixInterpolation +OAI.Combinatorics.MatchingPSD.Model +OAI.Combinatorics.MatchingPSD.NormalizedFactors +OAI.Combinatorics.MatchingPSD.NumericalBounds +OAI.Combinatorics.MatchingPSD.Padding +OAI.Combinatorics.MatchingPSD.Pairings +OAI.Combinatorics.MatchingPSD.Parameters +OAI.Combinatorics.MatchingPSD.PartialColorings +OAI.Combinatorics.MatchingPSD.PermutationSmoothing +OAI.Combinatorics.MatchingPSD.PolynomialInterpolation +OAI.Combinatorics.MatchingPSD.PolynomialSpaces +OAI.Combinatorics.MatchingPSD.RepresentationDimension +OAI.Combinatorics.MatchingPSD.ScalarSmoothing +OAI.Combinatorics.MatchingPSD.SequentialTests +OAI.Combinatorics.MatchingPSD.SimultaneousSmoothing +OAI.Combinatorics.MatchingPSD.SpectralContraction +OAI.Combinatorics.MatchingPSD.SpectralMultiplicity +OAI.Combinatorics.MatchingPSD.SquareRootDisturbance +OAI.Combinatorics.MatchingPSD.TableCoordinates +OAI.Combinatorics.MatchingPSD.TableGeometry +OAI.Combinatorics.MatchingPSD.TableMoments +OAI.Combinatorics.MatchingPSD.TablePolynomials +OAI.Combinatorics.MatchingPSD.TensorBounds +OAI.Combinatorics.MatchingPSD.TransitionMatrices +OAI.Combinatorics.MatchingPSD.TypeProbabilities diff --git a/tasks/matching-psd/solution/reference.py b/tasks/matching-psd/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matching-psd/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matching-psd/solution/solve.sh b/tasks/matching-psd/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1a814c7cde97d99c552bb709d94abf1dcb71aaeb --- /dev/null +++ b/tasks/matching-psd/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatchingPSD, i.e. module OAI.Combinatorics.MatchingPSD.Main and the +# 53 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatchingPSD.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatchingPSD" diff --git a/tasks/matching-psd/task.toml b/tasks/matching-psd/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f94160610bc6761b2c140ceb63c793e5d6c39d35 --- /dev/null +++ b/tasks/matching-psd/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matching-psd" +version = "1.0.0" +description = "Prove MatchingPSD (openai/math family 126: Exponential semidefinite complexity of perfect matching) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatchingPSD.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatchingPSD" +family = "126" +family_title = "Exponential semidefinite complexity of perfect matching" +subject = "Theoretical computer science" +theorems = ["OAI.PerfectMatchingPSD.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatchingPSD.Main" +reference_modules = 53 +reference_lean_bytes = 296495 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 855 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11966 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matching-psd/tests/Challenge.lean b/tasks/matching-psd/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ee2c4baa6d65e22c04da68186f6afb2e59953baa --- /dev/null +++ b/tasks/matching-psd/tests/Challenge.lean @@ -0,0 +1,55 @@ +import Mathlib + +namespace OAI + +namespace PerfectMatchingPSD + +abbrev Edge (n : ℕ) := {p : Fin n × Fin n // p.1 < p.2} + +def IsPerfectMatching {n : ℕ} (M : Finset (Edge n)) : Prop := + ∀ v : Fin n, (M.filter fun e => e.1.1 = v ∨ e.1.2 = v).card = 1 + +abbrev PerfectMatching (n : ℕ) := + {M : Finset (Edge n) // IsPerfectMatching M} + +abbrev OddCut (n : ℕ) := {U : Finset (Fin n) // Odd U.card} + +abbrev Row (n : ℕ) := Edge n ⊕ OddCut n + +def Crosses {n : ℕ} (U : Finset (Fin n)) (e : Edge n) : Prop := + (e.1.1 ∈ U ∧ e.1.2 ∉ U) ∨ (e.1.1 ∉ U ∧ e.1.2 ∈ U) + +noncomputable def crossingCount {n : ℕ} (U : Finset (Fin n)) + (M : PerfectMatching n) : ℕ := by + classical + exact (M.1.filter (Crosses U)).card + +noncomputable def slack {n : ℕ} (i : Row n) (M : PerfectMatching n) : ℝ := by + classical + exact match i with + | Sum.inl e => if e ∈ M.1 then 1 else 0 + | Sum.inr U => (crossingCount U.1 M : ℝ) - 1 + +/-- Real PSD factors of order `r`, without equivariance or rank-one restrictions. -/ +def HasFactorization (n r : ℕ) : Prop := + ∃ (A : Row n → Matrix (Fin r) (Fin r) ℝ) + (B : PerfectMatching n → Matrix (Fin r) (Fin r) ℝ), + (∀ i, (A i).PosSemidef) ∧ (∀ M, (B M).PosSemidef) ∧ + ∀ i M, slack i M = Matrix.trace (A i * B M) + +/-- The least positive order of a real PSD factorization. -/ +noncomputable def psdRank (n : ℕ) : ℕ := + sInf {r : ℕ | 0 < r ∧ HasFactorization n r} + +/-- Every positive real power is eventually smaller than the PSD rank, +uniformly over all even vertex counts. The exponentiation is real `rpow`. -/ +def MainClaim : Prop := + ∀ C : ℝ, 0 < C → ∃ n₀ : ℕ, 4 ≤ n₀ ∧ + ∀ n : ℕ, n₀ ≤ n → Even n → (n : ℝ) ^ C < (psdRank n : ℝ) + +theorem main : MainClaim := by + sorry + +end PerfectMatchingPSD + +end OAI diff --git a/tasks/matching-psd/tests/grade.py b/tasks/matching-psd/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matching-psd/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matching-psd/tests/task.json b/tasks/matching-psd/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dddd0508218f0eeb94972846cc0aa00778e8913a --- /dev/null +++ b/tasks/matching-psd/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatchingPSD", + "comparator": { + "theorem_names": [ + "OAI.PerfectMatchingPSD.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11066 +} \ No newline at end of file diff --git a/tasks/matching-psd/tests/test.sh b/tasks/matching-psd/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matching-psd/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matrix-fields/environment/Dockerfile b/tasks/matrix-fields/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matrix-fields/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matrix-fields/environment/fetch_mathlib.sh b/tasks/matrix-fields/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matrix-fields/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matrix-fields/environment/lake-manifest.json b/tasks/matrix-fields/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matrix-fields/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matrix-fields/environment/lakefile.lean b/tasks/matrix-fields/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matrix-fields/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matrix-fields/environment/lean_setup.sh b/tasks/matrix-fields/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matrix-fields/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matrix-fields/environment/pack_submission.py b/tasks/matrix-fields/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matrix-fields/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matrix-fields/instruction.md b/tasks/matrix-fields/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..df6d409a0add3663c9b491fa85f3d5f3bca52377 --- /dev/null +++ b/tasks/matrix-fields/instruction.md @@ -0,0 +1,167 @@ +# openai/math challenge `MatrixFields` (family 107) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 107 of the release, *Matrix multiplication with exponent at most $9/4$* +(Theoretical computer science). The family as a whole: Proves $\omega\le9/4$ over $\mathbb C$, giving $O_\varepsilon(n^{9/4+\varepsilon})$ arithmetic operations for square matrix multiplication. In characteristic zero, some inner dimension $n^a$ with $a>0.465$ permits $n^{2+o(1)}$ rectangular multiplication. Further square bounds give $\omega<2.258$ outside finitely many positive characteristics and $\omega<2.371054886006746$ over every fixed field. + +The challenge is `MatrixFields`, also at `/opt/openai-math/challenges/MatrixFields.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators Topology Polynomial + +namespace MatrixAllFields + +noncomputable section + +open scoped BigOperators + +namespace MatrixMultiplication.Arithmetic + +inductive Gate (F Input Register : Type*) where + | constant : F → Gate F Input Register + | input : Input → Gate F Input Register + | add : Register → Register → Gate F Input Register + | sub : Register → Register → Gate F Input Register + | mul : Register → Register → Gate F Input Register + +namespace Gate + +variable {F Input Register : Type*} + +def eval [Field F] (inputs : Input → F) (registers : Register → F) : + Gate F Input Register → F + | .constant z => z + | .input i => inputs i + | .add i j => registers i + registers j + | .sub i j => registers i - registers j + | .mul i j => registers i * registers j + +def cost : Gate F Input Register → ℕ + | .constant _ => 0 + | .input _ => 0 + | .add _ _ => 1 + | .sub _ _ => 1 + | .mul _ _ => 1 + +end Gate + +inductive Program (F Input : Type*) : ℕ → Type _ where + | nil : Program F Input 0 + | step {r : ℕ} : Program F Input r → Gate F Input (Fin r) → Program F Input (r + 1) + +namespace Program + +variable {F Input : Type*} + +def eval [Field F] : {r : ℕ} → Program F Input r → (Input → F) → Fin r → F + | 0, .nil, _ => Fin.elim0 + | _ + 1, .step p g, inputs => + Fin.cases (g.eval inputs (p.eval inputs)) (p.eval inputs) + +def cost : {r : ℕ} → Program F Input r → ℕ + | 0, .nil => 0 + | _ + 1, .step p g => p.cost + g.cost + +end Program + +abbrev MatrixInput (a b c : ℕ) := (Fin a × Fin b) ⊕ (Fin b × Fin c) + +def matrixInputs {F : Type*} {a b c : ℕ} + (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F) : + MatrixInput a b c → F + | .inl (i, j) => A i j + | .inr (j, k) => B j k + +structure MatrixAlgorithm (F : Type*) (a b c : ℕ) where + registers : ℕ + program : Program F (MatrixInput a b c) registers + output : Fin a → Fin c → Fin registers + +namespace MatrixAlgorithm + +variable {F : Type*} [Field F] {a b c : ℕ} + +def eval (P : MatrixAlgorithm F a b c) + (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F) : + Matrix (Fin a) (Fin c) F := + fun i k => P.program.eval (matrixInputs A B) (P.output i k) + +def Correct (P : MatrixAlgorithm F a b c) : Prop := + ∀ (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F), P.eval A B = A * B + +def cost (P : MatrixAlgorithm F a b c) : ℕ := P.program.cost + +end MatrixAlgorithm + +/-- Positive slack, one uniform constant, and a correct program at every size. -/ +def AdmissibleExponent (F : Type*) [Field F] (τ : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ + ∀ n : ℕ, 1 ≤ n → ∃ P : MatrixAlgorithm F n n n, + P.Correct ∧ (P.cost : ℝ) ≤ C * (n : ℝ) ^ (τ + ε) + +def omega (F : Type*) [Field F] : ℝ := sInf {τ : ℝ | AdmissibleExponent F τ} + +end MatrixMultiplication.Arithmetic + +end + +end MatrixAllFields + +namespace MatrixAllFields.MatrixMultiplication.AllFieldMain + +universe u + +theorem omega_lt_source_constant (F : Type u) [Field F] : + Arithmetic.omega F < (2371054886006746 : ℝ) / 10 ^ 15 ∧ + (2371054886006746 : ℝ) / 10 ^ 15 < (2371056 : ℝ) / 10 ^ 6 := by + sorry + +end MatrixAllFields.MatrixMultiplication.AllFieldMain + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatrixFields.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MatrixAllFields.MatrixMultiplication.AllFieldMain.omega_lt_source_constant` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matrix-fields/solution/closure.txt b/tasks/matrix-fields/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f6fd2ffed4ef967b0af08685a1dfee7e9a6f196b --- /dev/null +++ b/tasks/matrix-fields/solution/closure.txt @@ -0,0 +1,354 @@ +OAI.LinearAlgebra.MatrixFields.Arithmetic.ArithmeticComplexity +OAI.LinearAlgebra.MatrixFields.Arithmetic.ArithmeticExponent +OAI.LinearAlgebra.MatrixFields.Arithmetic.ArithmeticPrograms +OAI.LinearAlgebra.MatrixFields.Arithmetic.CommonDimensions +OAI.LinearAlgebra.MatrixFields.Arithmetic.ComplexArithmeticExponent +OAI.LinearAlgebra.MatrixFields.Arithmetic.ComplexArithmeticGrowth +OAI.LinearAlgebra.MatrixFields.Arithmetic.ComplexArithmeticLowerBound +OAI.LinearAlgebra.MatrixFields.Arithmetic.MatrixMapDecidable +OAI.LinearAlgebra.MatrixFields.Arithmetic.RecursiveBlockPrograms +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_1_14I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_1_14I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_1_14I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_2_13I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_2_13I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_2_13I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_3_12I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_3_12I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_3_12I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_4_11I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_4_11I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_4_11I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_5_10I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_5_10I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_5_10I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_5_10I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_6_9I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_6_9I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_6_9I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_6_9I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_6_9I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_7_8I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_7_8I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_7_8I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_7_8I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA1_7_8I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_2_12I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_2_12I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_2_12I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_3_11I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_3_11I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_3_11I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_4_10I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_4_10I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_4_10I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_4_10I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_5_9I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_5_9I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_5_9I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_5_9I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_6_8I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_6_8I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_6_8I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_6_8I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_6_8I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_7_7I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_7_7I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_7_7I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_7_7I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA2_7_7I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_3_10I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_3_10I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_3_10I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_3_10I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_4_9I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_4_9I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_4_9I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_4_9I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_5_8I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_5_8I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_5_8I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_5_8I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_6_7I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_6_7I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_6_7I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_6_7I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA3_6_7I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_4_8I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_4_8I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_4_8I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_4_8I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_5_7I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_5_7I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_5_7I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_5_7I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_6_6I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_6_6I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_6_6I1Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_6_6I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA4_6_6I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA5_5_6I0 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA5_5_6I1 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA5_5_6I2 +OAI.LinearAlgebra.MatrixFields.CapacityA.CapA5_5_6I2Pair +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_1_6I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_1_6I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_1_6I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_2_5I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_2_5I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_2_5I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_3_4I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_3_4I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_3_4I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_4_3I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_4_3I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_4_3I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_5_2I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_5_2I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_5_2I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_6_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_6_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB1_6_1I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_1_5I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_1_5I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_1_5I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_2_4I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_2_4I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_2_4I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_3_3I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_3_3I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_3_3I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_4_2I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_4_2I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_4_2I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_5_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_5_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB2_5_1I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_1_4I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_1_4I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_1_4I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_2_3I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_2_3I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_2_3I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_3_2I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_3_2I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_3_2I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_4_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_4_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB3_4_1I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_1_3I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_1_3I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_1_3I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_2_2I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_2_2I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_2_2I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_3_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_3_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB4_3_1I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_1_2I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_1_2I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_1_2I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_2_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_2_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB5_2_1I2 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB6_1_1I0 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB6_1_1I1 +OAI.LinearAlgebra.MatrixFields.CapacityB.CapB6_1_1I2 +OAI.LinearAlgebra.MatrixFields.Certificates.CertificatesReplay +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_1_7 +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_3_5 +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_4_4 +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_5_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_7_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Four0_8_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four1_0_7 +OAI.LinearAlgebra.MatrixFields.Certificates.Four1_7_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four2_0_6 +OAI.LinearAlgebra.MatrixFields.Certificates.Four2_6_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four3_0_5 +OAI.LinearAlgebra.MatrixFields.Certificates.Four3_5_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four4_0_4 +OAI.LinearAlgebra.MatrixFields.Certificates.Four4_4_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four5_0_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Four5_3_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four6_0_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Four6_2_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four7_0_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Four7_1_0 +OAI.LinearAlgebra.MatrixFields.Certificates.Four8_0_0 +OAI.LinearAlgebra.MatrixFields.Certificates.InitialProbabilities +OAI.LinearAlgebra.MatrixFields.Certificates.LittleB1_3_4 +OAI.LinearAlgebra.MatrixFields.Certificates.LittleB1_4_3 +OAI.LinearAlgebra.MatrixFields.Certificates.LittleB1_5_2 +OAI.LinearAlgebra.MatrixFields.Certificates.LittleB2_3_3 +OAI.LinearAlgebra.MatrixFields.Certificates.LittleB2_5_1 +OAI.LinearAlgebra.MatrixFields.Certificates.NativeInterior +OAI.LinearAlgebra.MatrixFields.Certificates.NativeSharp +OAI.LinearAlgebra.MatrixFields.Certificates.SparseContraction +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA1_1_14 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA1_3_12 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA1_4_11 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA1_7_8 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_2_12 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_3_11 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_4_10 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_5_9 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_6_8 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA2_7_7 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA3_3_10 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA3_4_9 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA3_5_8 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA3_6_7 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA4_5_7 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitA4_6_6 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitB1_1_6 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitB1_3_4 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitB2_3_3 +OAI.LinearAlgebra.MatrixFields.Certificates.SplitB5_1_2 +OAI.LinearAlgebra.MatrixFields.Certificates.SupportedContraction +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_1_6 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_2_5 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_3_4 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_4_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_5_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal1_6_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal2_1_5 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal2_2_4 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal2_3_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal2_4_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal2_5_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal3_1_4 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal3_2_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal3_3_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal3_4_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal4_1_3 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal4_2_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal4_3_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal5_1_2 +OAI.LinearAlgebra.MatrixFields.Certificates.Terminal5_2_1 +OAI.LinearAlgebra.MatrixFields.Certificates.Weights2 +OAI.LinearAlgebra.MatrixFields.Certificates.Zero0_1_7 +OAI.LinearAlgebra.MatrixFields.Conclusions.AllFieldsBound +OAI.LinearAlgebra.MatrixFields.Construction.ActiveSums +OAI.LinearAlgebra.MatrixFields.Construction.CompleteWordPair +OAI.LinearAlgebra.MatrixFields.Construction.ComplexExpressionFamily +OAI.LinearAlgebra.MatrixFields.Construction.ComplexLocalMaps +OAI.LinearAlgebra.MatrixFields.Construction.ComplexPolynomialWitnessProduct +OAI.LinearAlgebra.MatrixFields.Construction.ComplexRectangularASI +OAI.LinearAlgebra.MatrixFields.Construction.ComplexSharedAuxiliaryBank +OAI.LinearAlgebra.MatrixFields.Construction.ExactStatisticWords +OAI.LinearAlgebra.MatrixFields.Construction.ExpressionFamily +OAI.LinearAlgebra.MatrixFields.Construction.FinalState +OAI.LinearAlgebra.MatrixFields.Construction.FiniteCover +OAI.LinearAlgebra.MatrixFields.Construction.GroupAmbientDegree +OAI.LinearAlgebra.MatrixFields.Construction.GroupAssignmentRetention +OAI.LinearAlgebra.MatrixFields.Construction.GroupAssignments +OAI.LinearAlgebra.MatrixFields.Construction.GroupBranchDesignation +OAI.LinearAlgebra.MatrixFields.Construction.GroupDegreeEnvelope +OAI.LinearAlgebra.MatrixFields.Construction.GroupNativeDegreeBound +OAI.LinearAlgebra.MatrixFields.Construction.InitialFamily +OAI.LinearAlgebra.MatrixFields.Construction.InitialHistories +OAI.LinearAlgebra.MatrixFields.Construction.InitialState +OAI.LinearAlgebra.MatrixFields.Construction.JointAPFree +OAI.LinearAlgebra.MatrixFields.Construction.JointCanonicalMixed +OAI.LinearAlgebra.MatrixFields.Construction.JointCanonicalSymmetry +OAI.LinearAlgebra.MatrixFields.Construction.JointCoarseReorder +OAI.LinearAlgebra.MatrixFields.Construction.JointCompatibilityCountProducer +OAI.LinearAlgebra.MatrixFields.Construction.JointCompatibilityIncidence +OAI.LinearAlgebra.MatrixFields.Construction.JointCompatibilityScaling +OAI.LinearAlgebra.MatrixFields.Construction.JointGibbsApproximation +OAI.LinearAlgebra.MatrixFields.Construction.JointLossCounts +OAI.LinearAlgebra.MatrixFields.Construction.JointMarginalSupport +OAI.LinearAlgebra.MatrixFields.Construction.JointMaskedAssignment +OAI.LinearAlgebra.MatrixFields.Construction.OrderedLimits +OAI.LinearAlgebra.MatrixFields.Construction.PairMarginals +OAI.LinearAlgebra.MatrixFields.Construction.ShapeEncoding +OAI.LinearAlgebra.MatrixFields.Construction.Subdivision +OAI.LinearAlgebra.MatrixFields.Construction.ZeroFinish +OAI.LinearAlgebra.MatrixFields.Entropy.ComplexAsymptoticRecurrence +OAI.LinearAlgebra.MatrixFields.Entropy.ComplexPolynomialPowerGrowth +OAI.LinearAlgebra.MatrixFields.Entropy.ConditionalContinuity +OAI.LinearAlgebra.MatrixFields.Entropy.ConditionalRateBridge +OAI.LinearAlgebra.MatrixFields.Entropy.ConstructionRates +OAI.LinearAlgebra.MatrixFields.Entropy.FiniteAverage +OAI.LinearAlgebra.MatrixFields.Entropy.FloorExponentialRates +OAI.LinearAlgebra.MatrixFields.Entropy.GroupBranchLaws +OAI.LinearAlgebra.MatrixFields.Entropy.GroupCountRate +OAI.LinearAlgebra.MatrixFields.Entropy.GroupPairEntropy +OAI.LinearAlgebra.MatrixFields.Entropy.GroupProjectedEntropy +OAI.LinearAlgebra.MatrixFields.Entropy.InitialEntropy +OAI.LinearAlgebra.MatrixFields.Entropy.InitialLeafRates +OAI.LinearAlgebra.MatrixFields.Entropy.JointAmbientEntropy +OAI.LinearAlgebra.MatrixFields.Entropy.JointAmbientRateLimit +OAI.LinearAlgebra.MatrixFields.Entropy.JointCompatibilityEntropyBound +OAI.LinearAlgebra.MatrixFields.Entropy.JointCompatibilityRateLimit +OAI.LinearAlgebra.MatrixFields.Entropy.JointExtractionRates +OAI.LinearAlgebra.MatrixFields.Entropy.JointMaskedRates +OAI.LinearAlgebra.MatrixFields.Entropy.NativeLaws +OAI.LinearAlgebra.MatrixFields.Entropy.ParametersHalfLaws +OAI.LinearAlgebra.MatrixFields.Entropy.RateLimit +OAI.LinearAlgebra.MatrixFields.Entropy.RectangularGrowth +OAI.LinearAlgebra.MatrixFields.Entropy.StageCLaw +OAI.LinearAlgebra.MatrixFields.Entropy.StageCTerminalRates +OAI.LinearAlgebra.MatrixFields.Entropy.TerminalRates +OAI.LinearAlgebra.MatrixFields.Entropy.TerminalStatisticLaws +OAI.LinearAlgebra.MatrixFields.Entropy.ZeroLeafRateFormula +OAI.LinearAlgebra.MatrixFields.Entropy.ZeroLeafRates +OAI.LinearAlgebra.MatrixFields.Extraction.AuxiliarySeparation +OAI.LinearAlgebra.MatrixFields.Extraction.ComplexFiniteSeparation +OAI.LinearAlgebra.MatrixFields.Extraction.ComplexLabelHierarchySeparation +OAI.LinearAlgebra.MatrixFields.Extraction.ComplexRationalTypes +OAI.LinearAlgebra.MatrixFields.Extraction.ConditionalLabels +OAI.LinearAlgebra.MatrixFields.Extraction.ConstructionLabels +OAI.LinearAlgebra.MatrixFields.Extraction.GroupPairWindows +OAI.LinearAlgebra.MatrixFields.Extraction.GroupSelection +OAI.LinearAlgebra.MatrixFields.Extraction.InitialHash +OAI.LinearAlgebra.MatrixFields.Extraction.JointExtraction +OAI.LinearAlgebra.MatrixFields.Extraction.JointMaskedGoodSelection +OAI.LinearAlgebra.MatrixFields.Extraction.JointMaskedSelection +OAI.LinearAlgebra.MatrixFields.Extraction.JointPairClassWindows +OAI.LinearAlgebra.MatrixFields.Extraction.JointTypeCounts +OAI.LinearAlgebra.MatrixFields.Histories.CWShapePhysicalPermutation +OAI.LinearAlgebra.MatrixFields.Histories.GroupOrbitCount +OAI.LinearAlgebra.MatrixFields.Histories.GroupOrbitTransport +OAI.LinearAlgebra.MatrixFields.Histories.HistoryChildLaws +OAI.LinearAlgebra.MatrixFields.Histories.HistoryGroupCore +OAI.LinearAlgebra.MatrixFields.Histories.HistoryIteration +OAI.LinearAlgebra.MatrixFields.Histories.HistoryPositions +OAI.LinearAlgebra.MatrixFields.Histories.HistoryRecovery +OAI.LinearAlgebra.MatrixFields.Histories.HistoryRecoveryBudget +OAI.LinearAlgebra.MatrixFields.Histories.HistorySourceAssignment +OAI.LinearAlgebra.MatrixFields.Histories.HistorySums +OAI.LinearAlgebra.MatrixFields.Histories.InheritedMaskMargins +OAI.LinearAlgebra.MatrixFields.Histories.InitialOrbit +OAI.LinearAlgebra.MatrixFields.Histories.InverseLinearRecovery +OAI.LinearAlgebra.MatrixFields.Histories.JointScalarOrbitAdmissibility +OAI.LinearAlgebra.MatrixFields.Histories.ScheduledPositivity +OAI.LinearAlgebra.MatrixFields.Histories.ZeroHistorySums +OAI.LinearAlgebra.MatrixFields.Main +OAI.LinearAlgebra.MatrixFields.Model +OAI.LinearAlgebra.MatrixFields.Parameters.ComplementSums +OAI.LinearAlgebra.MatrixFields.Parameters.GroupSelectionParameters +OAI.LinearAlgebra.MatrixFields.Parameters.GroupStatisticComplement +OAI.LinearAlgebra.MatrixFields.Parameters.JointOrdinaryPopulationSelection +OAI.LinearAlgebra.MatrixFields.Parameters.JointPopulation +OAI.LinearAlgebra.MatrixFields.Parameters.JointPopulationMixedCompatibility +OAI.LinearAlgebra.MatrixFields.Parameters.NativeCapacity +OAI.LinearAlgebra.MatrixFields.Parameters.ParametersCompatibility +OAI.LinearAlgebra.MatrixFields.Parameters.ParametersContractions +OAI.LinearAlgebra.MatrixFields.Parameters.ParametersHalfComplement +OAI.LinearAlgebra.MatrixFields.Parameters.ParametersStageC +OAI.LinearAlgebra.MatrixFields.Parameters.ParametersWeights +OAI.LinearAlgebra.MatrixFields.Parameters.PopulationCounts +OAI.LinearAlgebra.MatrixFields.Parameters.StageCCapacity +OAI.LinearAlgebra.MatrixFields.Parameters.TerminalPopulations +OAI.LinearAlgebra.MatrixFields.Tensors.CWCompleteStatistics +OAI.LinearAlgebra.MatrixFields.Tensors.CWStageCPlacements +OAI.LinearAlgebra.MatrixFields.Tensors.CWStageCStatistics +OAI.LinearAlgebra.MatrixFields.Tensors.CWStrandCompatibility +OAI.LinearAlgebra.MatrixFields.Tensors.CWWordDimensionParameters +OAI.LinearAlgebra.MatrixFields.Tensors.CWZeroGeometry +OAI.LinearAlgebra.MatrixFields.Tensors.ComplexDotPairing +OAI.LinearAlgebra.MatrixFields.Tensors.ComplexSeparatedTensorDecomposition +OAI.LinearAlgebra.MatrixFields.Tensors.JointPopulationCWNonzero +OAI.LinearAlgebra.MatrixFields.Tensors.TerminalRelabel diff --git a/tasks/matrix-fields/solution/reference.py b/tasks/matrix-fields/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matrix-fields/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matrix-fields/solution/solve.sh b/tasks/matrix-fields/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba48cb1b2290295641a2e20ccda1cf4acbeb3681 --- /dev/null +++ b/tasks/matrix-fields/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatrixFields, i.e. module OAI.LinearAlgebra.MatrixFields.Main and the +# 354 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.LinearAlgebra.MatrixFields.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatrixFields" diff --git a/tasks/matrix-fields/task.toml b/tasks/matrix-fields/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..796c23a8b64a12683fccb41e7369de0ab257c0b2 --- /dev/null +++ b/tasks/matrix-fields/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matrix-fields" +version = "1.0.0" +description = "Prove MatrixFields (openai/math family 107: Matrix multiplication with exponent at most $9/4$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatrixFields.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatrixFields" +family = "107" +family_title = "Matrix multiplication with exponent at most $9/4$" +subject = "Theoretical computer science" +theorems = ["OAI.MatrixAllFields.MatrixMultiplication.AllFieldMain.omega_lt_source_constant"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.LinearAlgebra.MatrixFields.Main" +reference_modules = 354 +reference_lean_bytes = 12952806 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 4564 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 22500 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matrix-fields/tests/Challenge.lean b/tasks/matrix-fields/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e11c17d138ef17d88bda99570ca2cc2d5825d551 --- /dev/null +++ b/tasks/matrix-fields/tests/Challenge.lean @@ -0,0 +1,116 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators Topology Polynomial + +namespace MatrixAllFields + +noncomputable section + +open scoped BigOperators + +namespace MatrixMultiplication.Arithmetic + +inductive Gate (F Input Register : Type*) where + | constant : F → Gate F Input Register + | input : Input → Gate F Input Register + | add : Register → Register → Gate F Input Register + | sub : Register → Register → Gate F Input Register + | mul : Register → Register → Gate F Input Register + +namespace Gate + +variable {F Input Register : Type*} + +def eval [Field F] (inputs : Input → F) (registers : Register → F) : + Gate F Input Register → F + | .constant z => z + | .input i => inputs i + | .add i j => registers i + registers j + | .sub i j => registers i - registers j + | .mul i j => registers i * registers j + +def cost : Gate F Input Register → ℕ + | .constant _ => 0 + | .input _ => 0 + | .add _ _ => 1 + | .sub _ _ => 1 + | .mul _ _ => 1 + +end Gate + +inductive Program (F Input : Type*) : ℕ → Type _ where + | nil : Program F Input 0 + | step {r : ℕ} : Program F Input r → Gate F Input (Fin r) → Program F Input (r + 1) + +namespace Program + +variable {F Input : Type*} + +def eval [Field F] : {r : ℕ} → Program F Input r → (Input → F) → Fin r → F + | 0, .nil, _ => Fin.elim0 + | _ + 1, .step p g, inputs => + Fin.cases (g.eval inputs (p.eval inputs)) (p.eval inputs) + +def cost : {r : ℕ} → Program F Input r → ℕ + | 0, .nil => 0 + | _ + 1, .step p g => p.cost + g.cost + +end Program + +abbrev MatrixInput (a b c : ℕ) := (Fin a × Fin b) ⊕ (Fin b × Fin c) + +def matrixInputs {F : Type*} {a b c : ℕ} + (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F) : + MatrixInput a b c → F + | .inl (i, j) => A i j + | .inr (j, k) => B j k + +structure MatrixAlgorithm (F : Type*) (a b c : ℕ) where + registers : ℕ + program : Program F (MatrixInput a b c) registers + output : Fin a → Fin c → Fin registers + +namespace MatrixAlgorithm + +variable {F : Type*} [Field F] {a b c : ℕ} + +def eval (P : MatrixAlgorithm F a b c) + (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F) : + Matrix (Fin a) (Fin c) F := + fun i k => P.program.eval (matrixInputs A B) (P.output i k) + +def Correct (P : MatrixAlgorithm F a b c) : Prop := + ∀ (A : Matrix (Fin a) (Fin b) F) (B : Matrix (Fin b) (Fin c) F), P.eval A B = A * B + +def cost (P : MatrixAlgorithm F a b c) : ℕ := P.program.cost + +end MatrixAlgorithm + +/-- Positive slack, one uniform constant, and a correct program at every size. -/ +def AdmissibleExponent (F : Type*) [Field F] (τ : ℝ) : Prop := + ∀ ε : ℝ, 0 < ε → ∃ C : ℝ, 0 < C ∧ + ∀ n : ℕ, 1 ≤ n → ∃ P : MatrixAlgorithm F n n n, + P.Correct ∧ (P.cost : ℝ) ≤ C * (n : ℝ) ^ (τ + ε) + +def omega (F : Type*) [Field F] : ℝ := sInf {τ : ℝ | AdmissibleExponent F τ} + +end MatrixMultiplication.Arithmetic + +end + +end MatrixAllFields + +namespace MatrixAllFields.MatrixMultiplication.AllFieldMain + +universe u + +theorem omega_lt_source_constant (F : Type u) [Field F] : + Arithmetic.omega F < (2371054886006746 : ℝ) / 10 ^ 15 ∧ + (2371054886006746 : ℝ) / 10 ^ 15 < (2371056 : ℝ) / 10 ^ 6 := by + sorry + +end MatrixAllFields.MatrixMultiplication.AllFieldMain + +end OAI diff --git a/tasks/matrix-fields/tests/grade.py b/tasks/matrix-fields/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matrix-fields/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matrix-fields/tests/task.json b/tasks/matrix-fields/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..bd0d0086d1dbc5852da463f810d12c1ba1bc94c8 --- /dev/null +++ b/tasks/matrix-fields/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatrixFields", + "comparator": { + "theorem_names": [ + "OAI.MatrixAllFields.MatrixMultiplication.AllFieldMain.omega_lt_source_constant" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 21600 +} \ No newline at end of file diff --git a/tasks/matrix-fields/tests/test.sh b/tasks/matrix-fields/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matrix-fields/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matrix-removal/environment/Dockerfile b/tasks/matrix-removal/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matrix-removal/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matrix-removal/environment/fetch_mathlib.sh b/tasks/matrix-removal/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matrix-removal/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matrix-removal/environment/lake-manifest.json b/tasks/matrix-removal/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matrix-removal/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matrix-removal/environment/lakefile.lean b/tasks/matrix-removal/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matrix-removal/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matrix-removal/environment/lean_setup.sh b/tasks/matrix-removal/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matrix-removal/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matrix-removal/environment/pack_submission.py b/tasks/matrix-removal/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matrix-removal/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matrix-removal/instruction.md b/tasks/matrix-removal/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..676f95e3558cd6f0b3b2a74eb13645dbdcb96c4b --- /dev/null +++ b/tasks/matrix-removal/instruction.md @@ -0,0 +1,128 @@ +# openai/math challenge `MatrixRemoval` (family 190) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 190 of the release, *Polynomial removal fails for ordered binary matrices* +(Combinatorics). The family as a whole: Disproves polynomial ordered binary matrix removal with one fixed $66\times66$ zero–one pattern. Matrices can require many binary-entry changes to become pattern-free while their copy density is smaller than every proposed polynomial bound in that distance. Copies preserve row and column orders and match both zeros and ones. + +The challenge is `MatrixRemoval`, also at `/opt/openai-math/challenges/MatrixRemoval.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem348 + +abbrev BinaryMatrix (n : ℕ) := Fin n → Fin n → Bool + +abbrev IncreasingMap (k n : ℕ) := {f : Fin k → Fin n // StrictMono f} + +def orderedCopies {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : + Finset (IncreasingMap k n × IncreasingMap k n) := by + classical + exact Finset.univ.filter (fun rc => + ∀ i j, A ((rc.1).val i) ((rc.2).val j) = H i j) + +def copyCount {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : ℕ := + (orderedCopies H A).card + +def HFree {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : Prop := + copyCount H A = 0 + +def hammingDistance {n : ℕ} (A B : BinaryMatrix n) : ℕ := by + classical + exact (Finset.univ.filter (fun rc : Fin n × Fin n => + A rc.1 rc.2 ≠ B rc.1 rc.2)).card + +def etaBit (a b : ℕ) : Bool := + decide (((a / (2 ^ (5 - b))) % 2) = 1) + +def anchor64 (u v : Fin 64) : Bool := + if 32 ≤ u.val ∧ 59 ≤ v.val then + etaBit (u.val - 32) (v.val - 58) + else + decide (u.val ≠ v.val) + +def fixedH : BinaryMatrix 66 := fun u v => + if hu : u.val < 64 then + if hv : v.val < 64 then + anchor64 ⟨u.val, hu⟩ ⟨v.val, hv⟩ + else + decide ((v.val = 64 ∧ u.val = 0) ∨ + (v.val = 65 ∧ u.val = 1)) + else + if v.val < 64 then + decide ((u.val = 64 ∧ v.val = 0) ∨ + (u.val = 65 ∧ v.val = 1)) + else + decide (u.val = 65 ∨ v.val = 64) + +def fixedMinEdits {n : ℕ} (A : BinaryMatrix n) : ℕ := by + classical + exact + (Finset.univ.image (fun B : BinaryMatrix n => + if HFree fixedH B then hammingDistance A B else n * n + 1)).min' + (by simp) + +def fixedDistance {n : ℕ} (A : BinaryMatrix n) : ℝ := + (fixedMinEdits A : ℝ) / ((n : ℝ) ^ 2) + +theorem no_polynomial_removal_bound : + ∀ c C : ℝ, 0 < c → 0 < C → + ∃ n : ℕ, 1 ≤ n ∧ + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + ∃ A : BinaryMatrix n, + fixedDistance A ≥ ε ∧ + (copyCount fixedH A : ℝ) < + c * Real.rpow ε C * ((n : ℝ) ^ 132) := by + sorry + +end Problem348 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatrixRemoval.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem348.no_polynomial_removal_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matrix-removal/solution/closure.txt b/tasks/matrix-removal/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4068473bf697b5c7a5e85214d4e9b3b128bb687c --- /dev/null +++ b/tasks/matrix-removal/solution/closure.txt @@ -0,0 +1,61 @@ +OAI.Combinatorics.MatrixRemoval.AnchorFrames +OAI.Combinatorics.MatrixRemoval.AnchorGroups +OAI.Combinatorics.MatrixRemoval.AnchorPatternBridge +OAI.Combinatorics.MatrixRemoval.AnchorPatternFixed +OAI.Combinatorics.MatrixRemoval.AnchorProperties +OAI.Combinatorics.MatrixRemoval.AnchorRigidity +OAI.Combinatorics.MatrixRemoval.AnchorRigidityFixed +OAI.Combinatorics.MatrixRemoval.Asymptotics +OAI.Combinatorics.MatrixRemoval.BodyExtension +OAI.Combinatorics.MatrixRemoval.BodyRoles +OAI.Combinatorics.MatrixRemoval.CanonicalCopyBound +OAI.Combinatorics.MatrixRemoval.CanonicalHorizontal +OAI.Combinatorics.MatrixRemoval.CanonicalModeEntries +OAI.Combinatorics.MatrixRemoval.Consequence +OAI.Combinatorics.MatrixRemoval.CopyBound +OAI.Combinatorics.MatrixRemoval.CopyBoundFixed +OAI.Combinatorics.MatrixRemoval.DirectNonshattering +OAI.Combinatorics.MatrixRemoval.GuardContainment +OAI.Combinatorics.MatrixRemoval.GuardedFrame +OAI.Combinatorics.MatrixRemoval.GuardedPath +OAI.Combinatorics.MatrixRemoval.Host +OAI.Combinatorics.MatrixRemoval.HostAnchorFrames +OAI.Combinatorics.MatrixRemoval.HostAnchorGroups +OAI.Combinatorics.MatrixRemoval.HostAnchorPinning +OAI.Combinatorics.MatrixRemoval.HostAnchorRigidity +OAI.Combinatorics.MatrixRemoval.HostBodyModes +OAI.Combinatorics.MatrixRemoval.HostBodyOrder +OAI.Combinatorics.MatrixRemoval.HostCopyBound +OAI.Combinatorics.MatrixRemoval.HostModeIncidence +OAI.Combinatorics.MatrixRemoval.HostNonshattering +OAI.Combinatorics.MatrixRemoval.HostRepairDistance +OAI.Combinatorics.MatrixRemoval.HostRoleExtraction +OAI.Combinatorics.MatrixRemoval.HostRootLeaf +OAI.Combinatorics.MatrixRemoval.HostSampledPath +OAI.Combinatorics.MatrixRemoval.HostSampledSelection +OAI.Combinatorics.MatrixRemoval.HostSampling +OAI.Combinatorics.MatrixRemoval.HostSamplingCompatibility +OAI.Combinatorics.MatrixRemoval.HostTreeOrder +OAI.Combinatorics.MatrixRemoval.HostTwins +OAI.Combinatorics.MatrixRemoval.HostVerticalLocalization +OAI.Combinatorics.MatrixRemoval.Main +OAI.Combinatorics.MatrixRemoval.ModeIncidence +OAI.Combinatorics.MatrixRemoval.ModeLocalization +OAI.Combinatorics.MatrixRemoval.Model +OAI.Combinatorics.MatrixRemoval.OrderedAnchorGroups +OAI.Combinatorics.MatrixRemoval.OrderedAnchorRigidity +OAI.Combinatorics.MatrixRemoval.OrderedBodyLocalization +OAI.Combinatorics.MatrixRemoval.OrderedHost +OAI.Combinatorics.MatrixRemoval.OrderedHostCopy +OAI.Combinatorics.MatrixRemoval.OrderedRepairDistance +OAI.Combinatorics.MatrixRemoval.OrderedSampledSelection +OAI.Combinatorics.MatrixRemoval.PathPropagation +OAI.Combinatorics.MatrixRemoval.PinnedHostCopy +OAI.Combinatorics.MatrixRemoval.SampledPath +OAI.Combinatorics.MatrixRemoval.SampledPathOrder +OAI.Combinatorics.MatrixRemoval.SamplingAvoidance +OAI.Combinatorics.MatrixRemoval.SamplingDistance +OAI.Combinatorics.MatrixRemoval.SelectedAnchorSparsity +OAI.Combinatorics.MatrixRemoval.SequenceAssembly +OAI.Combinatorics.MatrixRemoval.ThreeSeedSampling +OAI.Combinatorics.MatrixRemoval.TreePositions diff --git a/tasks/matrix-removal/solution/reference.py b/tasks/matrix-removal/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matrix-removal/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matrix-removal/solution/solve.sh b/tasks/matrix-removal/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..36f87e40fb120427c77f97641a797e5b5ddba9cd --- /dev/null +++ b/tasks/matrix-removal/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatrixRemoval, i.e. module OAI.Combinatorics.MatrixRemoval.Main and the +# 61 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.MatrixRemoval.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatrixRemoval" diff --git a/tasks/matrix-removal/task.toml b/tasks/matrix-removal/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..780ad96fe6f9901cbf1f977408e4e696c35fafc6 --- /dev/null +++ b/tasks/matrix-removal/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matrix-removal" +version = "1.0.0" +description = "Prove MatrixRemoval (openai/math family 190: Polynomial removal fails for ordered binary matrices) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatrixRemoval.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatrixRemoval" +family = "190" +family_title = "Polynomial removal fails for ordered binary matrices" +subject = "Combinatorics" +theorems = ["OAI.Problem348.no_polynomial_removal_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.MatrixRemoval.Main" +reference_modules = 61 +reference_lean_bytes = 322573 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 710 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11990 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matrix-removal/tests/Challenge.lean b/tasks/matrix-removal/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..74a1ea5e9ffa8f194d1b4dc16b95569db25dcf62 --- /dev/null +++ b/tasks/matrix-removal/tests/Challenge.lean @@ -0,0 +1,77 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem348 + +abbrev BinaryMatrix (n : ℕ) := Fin n → Fin n → Bool + +abbrev IncreasingMap (k n : ℕ) := {f : Fin k → Fin n // StrictMono f} + +def orderedCopies {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : + Finset (IncreasingMap k n × IncreasingMap k n) := by + classical + exact Finset.univ.filter (fun rc => + ∀ i j, A ((rc.1).val i) ((rc.2).val j) = H i j) + +def copyCount {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : ℕ := + (orderedCopies H A).card + +def HFree {k n : ℕ} (H : BinaryMatrix k) (A : BinaryMatrix n) : Prop := + copyCount H A = 0 + +def hammingDistance {n : ℕ} (A B : BinaryMatrix n) : ℕ := by + classical + exact (Finset.univ.filter (fun rc : Fin n × Fin n => + A rc.1 rc.2 ≠ B rc.1 rc.2)).card + +def etaBit (a b : ℕ) : Bool := + decide (((a / (2 ^ (5 - b))) % 2) = 1) + +def anchor64 (u v : Fin 64) : Bool := + if 32 ≤ u.val ∧ 59 ≤ v.val then + etaBit (u.val - 32) (v.val - 58) + else + decide (u.val ≠ v.val) + +def fixedH : BinaryMatrix 66 := fun u v => + if hu : u.val < 64 then + if hv : v.val < 64 then + anchor64 ⟨u.val, hu⟩ ⟨v.val, hv⟩ + else + decide ((v.val = 64 ∧ u.val = 0) ∨ + (v.val = 65 ∧ u.val = 1)) + else + if v.val < 64 then + decide ((u.val = 64 ∧ v.val = 0) ∨ + (u.val = 65 ∧ v.val = 1)) + else + decide (u.val = 65 ∨ v.val = 64) + +def fixedMinEdits {n : ℕ} (A : BinaryMatrix n) : ℕ := by + classical + exact + (Finset.univ.image (fun B : BinaryMatrix n => + if HFree fixedH B then hammingDistance A B else n * n + 1)).min' + (by simp) + +def fixedDistance {n : ℕ} (A : BinaryMatrix n) : ℝ := + (fixedMinEdits A : ℝ) / ((n : ℝ) ^ 2) + +theorem no_polynomial_removal_bound : + ∀ c C : ℝ, 0 < c → 0 < C → + ∃ n : ℕ, 1 ≤ n ∧ + ∃ ε : ℝ, 0 < ε ∧ ε < 1 ∧ + ∃ A : BinaryMatrix n, + fixedDistance A ≥ ε ∧ + (copyCount fixedH A : ℝ) < + c * Real.rpow ε C * ((n : ℝ) ^ 132) := by + sorry + +end Problem348 + +end + +end OAI diff --git a/tasks/matrix-removal/tests/grade.py b/tasks/matrix-removal/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matrix-removal/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matrix-removal/tests/task.json b/tasks/matrix-removal/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ed99d0d24a04cea9b176f312eb4b0693c18f476c --- /dev/null +++ b/tasks/matrix-removal/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatrixRemoval", + "comparator": { + "theorem_names": [ + "OAI.Problem348.no_polynomial_removal_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11090 +} \ No newline at end of file diff --git a/tasks/matrix-removal/tests/test.sh b/tasks/matrix-removal/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matrix-removal/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matroid-prophet/environment/Dockerfile b/tasks/matroid-prophet/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matroid-prophet/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matroid-prophet/environment/fetch_mathlib.sh b/tasks/matroid-prophet/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matroid-prophet/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matroid-prophet/environment/lake-manifest.json b/tasks/matroid-prophet/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matroid-prophet/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matroid-prophet/environment/lakefile.lean b/tasks/matroid-prophet/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matroid-prophet/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matroid-prophet/environment/lean_setup.sh b/tasks/matroid-prophet/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matroid-prophet/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matroid-prophet/environment/pack_submission.py b/tasks/matroid-prophet/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matroid-prophet/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matroid-prophet/instruction.md b/tasks/matroid-prophet/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..39ee785d28298bb38973918dcd626b6f68deae56 --- /dev/null +++ b/tasks/matroid-prophet/instruction.md @@ -0,0 +1,145 @@ +# openai/math challenge `MatroidProphet` (family 111) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 111 of the release, *One-sample matroid prophet inequalities against an almighty adversary* +(Theoretical computer science). The family as a whole: For every finite matroid known in advance, gives a distribution-independent online rule using one independent sample per element and earning a universal constant fraction of the expected offline optimum. Values are independent and nonnegative, with finite expected optimum. The guarantee holds even when the arrival-order adversary sees all samples, values, and the rule's entire random seed; no polynomial-time implementation is asserted. + +The challenge is `MatroidProphet`, also at `/opt/openai-math/challenges/MatroidProphet.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# One-sample matroid selection + +The rule and its finite seed law depend only on the known labeled matroid. +A decision sees the initial sample vector, the entire seed, and the arriving +label/value prefix. Every prefix is feasible, and decisions are irrevocable. +The arrival permutation may depend on all samples, values, and seed bits. +Only the actual offline optimum is required to be integrable. +-/ + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +namespace MatroidProphet + +abbrev Weights (n : ℕ) := Fin n → ℝ +abbrev Seed (bits : ℕ) := Fin bits → Bool +abbrev ArrivalOrder (n : ℕ) := Equiv.Perm (Fin n) +instance arrivalOrderMeasurableSpace (n : ℕ) : MeasurableSpace (ArrivalOrder n) := ⊤ + +abbrev History (n : ℕ) (k : Fin n) := Fin (k.val + 1) → Fin n × ℝ + +structure OnlineRule (n bits : ℕ) where + decide : (k : Fin n) → Seed bits → Weights n → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Seed bits × (Weights n × History n k) => decide k x.1 x.2.1 x.2.2) + +def prefixIndex {n : ℕ} (k : Fin n) (j : Fin (k.val + 1)) : Fin n := + ⟨j.val, Nat.lt_of_lt_of_le j.isLt (Nat.succ_le_of_lt k.isLt)⟩ + +def history {n : ℕ} (v : Weights n) (π : ArrivalOrder n) (k : Fin n) : History n k := + fun j => let e := π (prefixIndex k j); (e, v e) + +def decisionAt {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (k : Fin n) : Bool := + A.decide k r s (history v π k) + +noncomputable def acceptedThrough {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ decisionAt A r s v π (π.symm e) = true + +noncomputable def accepted {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : Finset (Fin n) := + acceptedThrough A r s v π n + +noncomputable def reward {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ accepted A r s v π, v e + +noncomputable def optimum {n : ℕ} (M : Matroid (Fin n)) (v : Weights n) : ℝ := by + classical + exact Finset.univ.sup' Finset.univ_nonempty + (fun I : Finset (Fin n) => if M.Indep (I : Set (Fin n)) then ∑ e ∈ I, v e else 0) + +def Feasible {n bits : ℕ} (M : Matroid (Fin n)) (A : OnlineRule n bits) : Prop := + ∀ (r : Seed bits) (s v : Weights n) (π : ArrivalOrder n) (t : ℕ), + (∀ e, 0 ≤ s e) → (∀ e, 0 ≤ v e) → + M.Indep (acceptedThrough A r s v π t : Set (Fin n)) + +def pairedCoordinates.{u} {n : ℕ} {Ω : Type u} (S V : Ω → Weights n) + (i : Fin n × Bool) : Ω → ℝ := + if i.2 then fun ω => S ω i.1 else fun ω => V ω i.1 + +def OneSampleChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : OnlineRule n bits), Feasible M A ∧ + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (S V : Ω → Weights n) (R : Ω → Seed bits), + Measurable S → Measurable V → Measurable R → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ S ω e) → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ V ω e) → + iIndepFun (pairedCoordinates S V) μ → + (∀ e, Measure.map (fun ω => S ω e) μ = Measure.map (fun ω => V ω e) μ) → + IndepFun (fun ω => (S ω, V ω)) R μ → + Measure.map R μ = ν → + Integrable (fun ω => optimum M (V ω)) μ → + ∀ (π : Ω → ArrivalOrder n), Measurable π → + Integrable (fun ω => reward A (R ω) (S ω) (V ω) (π ω)) μ ∧ + ((2 : ℝ) ^ 310)⁻¹ * (∫ ω, optimum M (V ω) ∂μ) ≤ + ∫ ω, reward A (R ω) (S ω) (V ω) (π ω) ∂μ + +theorem one_sample.{u} : OneSampleChallenge.{u} := by + sorry + +end MatroidProphet + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatroidProphet.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MatroidProphet.one_sample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matroid-prophet/solution/closure.txt b/tasks/matroid-prophet/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d938db0d621c557c9862b30dadada861d9b7e6b7 --- /dev/null +++ b/tasks/matroid-prophet/solution/closure.txt @@ -0,0 +1,125 @@ +OAI.Probability.MatroidProphet.AdaptiveResampling +OAI.Probability.MatroidProphet.Algorithm.Cost +OAI.Probability.MatroidProphet.Algorithm.Expectation +OAI.Probability.MatroidProphet.Algorithm.Feasible +OAI.Probability.MatroidProphet.Algorithm.LayerRank +OAI.Probability.MatroidProphet.Algorithm.Mean +OAI.Probability.MatroidProphet.Algorithm.Observed +OAI.Probability.MatroidProphet.Algorithm.Rule +OAI.Probability.MatroidProphet.Algorithm.SeedLaw +OAI.Probability.MatroidProphet.Algorithm.Selection +OAI.Probability.MatroidProphet.Algorithm.Statistics +OAI.Probability.MatroidProphet.Algorithm.WeightedPayoff +OAI.Probability.MatroidProphet.Algorithm.Worst +OAI.Probability.MatroidProphet.AnalyzedMass +OAI.Probability.MatroidProphet.Baseline +OAI.Probability.MatroidProphet.BatchReveal +OAI.Probability.MatroidProphet.BranchMix +OAI.Probability.MatroidProphet.CandidateFilter +OAI.Probability.MatroidProphet.Candidates +OAI.Probability.MatroidProphet.Certificates.Budget +OAI.Probability.MatroidProphet.Certificates.Execution +OAI.Probability.MatroidProphet.CommonBudget +OAI.Probability.MatroidProphet.CompletePayoff +OAI.Probability.MatroidProphet.ConditionalThinning +OAI.Probability.MatroidProphet.Constants +OAI.Probability.MatroidProphet.Density.Basic +OAI.Probability.MatroidProphet.Density.Birth +OAI.Probability.MatroidProphet.Density.Guarded +OAI.Probability.MatroidProphet.Density.Path +OAI.Probability.MatroidProphet.ExitNumerics +OAI.Probability.MatroidProphet.FiniteBits +OAI.Probability.MatroidProphet.FocalTransfer +OAI.Probability.MatroidProphet.Gluing +OAI.Probability.MatroidProphet.GreedyOptimal +OAI.Probability.MatroidProphet.GroupConditioning +OAI.Probability.MatroidProphet.GroupPayoff +OAI.Probability.MatroidProphet.GroupSafety +OAI.Probability.MatroidProphet.GroupTransfer +OAI.Probability.MatroidProphet.Groups +OAI.Probability.MatroidProphet.HazardCover +OAI.Probability.MatroidProphet.Information +OAI.Probability.MatroidProphet.LayerGreedy +OAI.Probability.MatroidProphet.LayerOnline +OAI.Probability.MatroidProphet.LayerRank +OAI.Probability.MatroidProphet.Main +OAI.Probability.MatroidProphet.Maximum.Basic +OAI.Probability.MatroidProphet.Maximum.Guarantee +OAI.Probability.MatroidProphet.Maximum.Mask +OAI.Probability.MatroidProphet.Maximum.Probability +OAI.Probability.MatroidProphet.Maximum.Score +OAI.Probability.MatroidProphet.Model +OAI.Probability.MatroidProphet.PathRankCost +OAI.Probability.MatroidProphet.PathStatistics +OAI.Probability.MatroidProphet.Pivots.Arbitrary +OAI.Probability.MatroidProphet.Pivots.Basic +OAI.Probability.MatroidProphet.Pivots.BlockPatterns +OAI.Probability.MatroidProphet.Pivots.Blocks +OAI.Probability.MatroidProphet.Pivots.Completeness +OAI.Probability.MatroidProphet.Pivots.Count +OAI.Probability.MatroidProphet.Pivots.Encoding +OAI.Probability.MatroidProphet.Pivots.Entropy +OAI.Probability.MatroidProphet.Pivots.Existence +OAI.Probability.MatroidProphet.Pivots.Greedy +OAI.Probability.MatroidProphet.Pivots.GreedyScan +OAI.Probability.MatroidProphet.Pivots.Guarantee +OAI.Probability.MatroidProphet.Pivots.Interleavings +OAI.Probability.MatroidProphet.Pivots.OccurrenceSupport +OAI.Probability.MatroidProphet.Pivots.Patterns +OAI.Probability.MatroidProphet.Pivots.PhasePattern +OAI.Probability.MatroidProphet.Pivots.Phases +OAI.Probability.MatroidProphet.Pivots.Reindex +OAI.Probability.MatroidProphet.Pivots.ResidualFamily +OAI.Probability.MatroidProphet.Pivots.Scores +OAI.Probability.MatroidProphet.Pivots.Sign +OAI.Probability.MatroidProphet.Priority +OAI.Probability.MatroidProphet.ProductRestriction +OAI.Probability.MatroidProphet.ProductSplit +OAI.Probability.MatroidProphet.RankAccounting +OAI.Probability.MatroidProphet.RankCost +OAI.Probability.MatroidProphet.Reduction +OAI.Probability.MatroidProphet.Residual.Comparison +OAI.Probability.MatroidProphet.Residual.Constants +OAI.Probability.MatroidProphet.Residual.Deterministic +OAI.Probability.MatroidProphet.Residual.Encoding +OAI.Probability.MatroidProphet.Residual.Gap +OAI.Probability.MatroidProphet.Residual.Generators +OAI.Probability.MatroidProphet.Residual.Global +OAI.Probability.MatroidProphet.Residual.LabeledFamily +OAI.Probability.MatroidProphet.Residual.MaskUnion +OAI.Probability.MatroidProphet.Residual.Nominal +OAI.Probability.MatroidProphet.Residual.Probability +OAI.Probability.MatroidProphet.Residual.Statistics +OAI.Probability.MatroidProphet.Residual.Tail +OAI.Probability.MatroidProphet.Residual.Timeline +OAI.Probability.MatroidProphet.Residual.Transfer +OAI.Probability.MatroidProphet.Residual.Witnesses +OAI.Probability.MatroidProphet.RevealComposition +OAI.Probability.MatroidProphet.RevealContinuation +OAI.Probability.MatroidProphet.Reverse.Bands +OAI.Probability.MatroidProphet.Reverse.BirthLoss +OAI.Probability.MatroidProphet.Reverse.BirthSafety +OAI.Probability.MatroidProphet.Reverse.Certificates +OAI.Probability.MatroidProphet.Reverse.Cost +OAI.Probability.MatroidProphet.Reverse.Exposure +OAI.Probability.MatroidProphet.Reverse.Hazard +OAI.Probability.MatroidProphet.Reverse.Hybrid +OAI.Probability.MatroidProphet.Reverse.Iteration +OAI.Probability.MatroidProphet.Reverse.LowHazard +OAI.Probability.MatroidProphet.Reverse.Paths +OAI.Probability.MatroidProphet.Reverse.PrefixTree +OAI.Probability.MatroidProphet.Reverse.SquareSum +OAI.Probability.MatroidProphet.Reverse.Squared +OAI.Probability.MatroidProphet.Reverse.Trace +OAI.Probability.MatroidProphet.Rounding +OAI.Probability.MatroidProphet.SafeParity +OAI.Probability.MatroidProphet.SafeSamples +OAI.Probability.MatroidProphet.SafeStatistics +OAI.Probability.MatroidProphet.Seed +OAI.Probability.MatroidProphet.SeedLaw +OAI.Probability.MatroidProphet.Simulation +OAI.Probability.MatroidProphet.Statements +OAI.Probability.MatroidProphet.Thinning +OAI.Probability.MatroidProphet.WeightGroups +OAI.Probability.MatroidProphet.WeightedAccounting +OAI.Probability.MatroidProphet.WeightedPayoff diff --git a/tasks/matroid-prophet/solution/reference.py b/tasks/matroid-prophet/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matroid-prophet/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matroid-prophet/solution/solve.sh b/tasks/matroid-prophet/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ae392287fe709ce7f9dd4cb9040d1c659fca0d35 --- /dev/null +++ b/tasks/matroid-prophet/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatroidProphet, i.e. module OAI.Probability.MatroidProphet.Main and the +# 125 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.MatroidProphet.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatroidProphet" diff --git a/tasks/matroid-prophet/task.toml b/tasks/matroid-prophet/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e2a6a153c4e06a964e6f385e43393503525bd32 --- /dev/null +++ b/tasks/matroid-prophet/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matroid-prophet" +version = "1.0.0" +description = "Prove MatroidProphet (openai/math family 111: One-sample matroid prophet inequalities against an almighty adversary) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatroidProphet.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatroidProphet" +family = "111" +family_title = "One-sample matroid prophet inequalities against an almighty adversary" +subject = "Theoretical computer science" +theorems = ["OAI.MatroidProphet.one_sample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.MatroidProphet.Main" +reference_modules = 125 +reference_lean_bytes = 666444 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 745 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12299 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matroid-prophet/tests/Challenge.lean b/tasks/matroid-prophet/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..412ad5b86840403f95d28ee4643fb2556aaa4deb --- /dev/null +++ b/tasks/matroid-prophet/tests/Challenge.lean @@ -0,0 +1,94 @@ +import Mathlib + +namespace OAI + +/-! +# One-sample matroid selection + +The rule and its finite seed law depend only on the known labeled matroid. +A decision sees the initial sample vector, the entire seed, and the arriving +label/value prefix. Every prefix is feasible, and decisions are irrevocable. +The arrival permutation may depend on all samples, values, and seed bits. +Only the actual offline optimum is required to be integrable. +-/ + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +namespace MatroidProphet + +abbrev Weights (n : ℕ) := Fin n → ℝ +abbrev Seed (bits : ℕ) := Fin bits → Bool +abbrev ArrivalOrder (n : ℕ) := Equiv.Perm (Fin n) +instance arrivalOrderMeasurableSpace (n : ℕ) : MeasurableSpace (ArrivalOrder n) := ⊤ + +abbrev History (n : ℕ) (k : Fin n) := Fin (k.val + 1) → Fin n × ℝ + +structure OnlineRule (n bits : ℕ) where + decide : (k : Fin n) → Seed bits → Weights n → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Seed bits × (Weights n × History n k) => decide k x.1 x.2.1 x.2.2) + +def prefixIndex {n : ℕ} (k : Fin n) (j : Fin (k.val + 1)) : Fin n := + ⟨j.val, Nat.lt_of_lt_of_le j.isLt (Nat.succ_le_of_lt k.isLt)⟩ + +def history {n : ℕ} (v : Weights n) (π : ArrivalOrder n) (k : Fin n) : History n k := + fun j => let e := π (prefixIndex k j); (e, v e) + +def decisionAt {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (k : Fin n) : Bool := + A.decide k r s (history v π k) + +noncomputable def acceptedThrough {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ decisionAt A r s v π (π.symm e) = true + +noncomputable def accepted {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : Finset (Fin n) := + acceptedThrough A r s v π n + +noncomputable def reward {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ accepted A r s v π, v e + +noncomputable def optimum {n : ℕ} (M : Matroid (Fin n)) (v : Weights n) : ℝ := by + classical + exact Finset.univ.sup' Finset.univ_nonempty + (fun I : Finset (Fin n) => if M.Indep (I : Set (Fin n)) then ∑ e ∈ I, v e else 0) + +def Feasible {n bits : ℕ} (M : Matroid (Fin n)) (A : OnlineRule n bits) : Prop := + ∀ (r : Seed bits) (s v : Weights n) (π : ArrivalOrder n) (t : ℕ), + (∀ e, 0 ≤ s e) → (∀ e, 0 ≤ v e) → + M.Indep (acceptedThrough A r s v π t : Set (Fin n)) + +def pairedCoordinates.{u} {n : ℕ} {Ω : Type u} (S V : Ω → Weights n) + (i : Fin n × Bool) : Ω → ℝ := + if i.2 then fun ω => S ω i.1 else fun ω => V ω i.1 + +def OneSampleChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : OnlineRule n bits), Feasible M A ∧ + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (S V : Ω → Weights n) (R : Ω → Seed bits), + Measurable S → Measurable V → Measurable R → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ S ω e) → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ V ω e) → + iIndepFun (pairedCoordinates S V) μ → + (∀ e, Measure.map (fun ω => S ω e) μ = Measure.map (fun ω => V ω e) μ) → + IndepFun (fun ω => (S ω, V ω)) R μ → + Measure.map R μ = ν → + Integrable (fun ω => optimum M (V ω)) μ → + ∀ (π : Ω → ArrivalOrder n), Measurable π → + Integrable (fun ω => reward A (R ω) (S ω) (V ω) (π ω)) μ ∧ + ((2 : ℝ) ^ 310)⁻¹ * (∫ ω, optimum M (V ω) ∂μ) ≤ + ∫ ω, reward A (R ω) (S ω) (V ω) (π ω) ∂μ + +theorem one_sample.{u} : OneSampleChallenge.{u} := by + sorry + +end MatroidProphet + +end OAI diff --git a/tasks/matroid-prophet/tests/grade.py b/tasks/matroid-prophet/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matroid-prophet/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matroid-prophet/tests/task.json b/tasks/matroid-prophet/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a8bf9a80d3ca2729cc8b4193b1d8190b1ee2afda --- /dev/null +++ b/tasks/matroid-prophet/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MatroidProphet", + "comparator": { + "theorem_names": [ + "OAI.MatroidProphet.one_sample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11399 +} \ No newline at end of file diff --git a/tasks/matroid-prophet/tests/test.sh b/tasks/matroid-prophet/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matroid-prophet/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/matroid-secretary/environment/Dockerfile b/tasks/matroid-secretary/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/matroid-secretary/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/matroid-secretary/environment/fetch_mathlib.sh b/tasks/matroid-secretary/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/matroid-secretary/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/matroid-secretary/environment/lake-manifest.json b/tasks/matroid-secretary/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/matroid-secretary/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/matroid-secretary/environment/lakefile.lean b/tasks/matroid-secretary/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/matroid-secretary/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/matroid-secretary/environment/lean_setup.sh b/tasks/matroid-secretary/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/matroid-secretary/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/matroid-secretary/environment/pack_submission.py b/tasks/matroid-secretary/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/matroid-secretary/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/matroid-secretary/instruction.md b/tasks/matroid-secretary/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5efef284693bba6adc3180e290bb8334bab92601 --- /dev/null +++ b/tasks/matroid-secretary/instruction.md @@ -0,0 +1,297 @@ +# openai/math challenge `MatroidSecretary` (family 111) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 111 of the release, *One-sample matroid prophet inequalities against an almighty adversary* +(Theoretical computer science). The family as a whole: For every finite matroid known in advance, gives a distribution-independent online rule using one independent sample per element and earning a universal constant fraction of the expected offline optimum. Values are independent and nonnegative, with finite expected optimum. The guarantee holds even when the arrival-order adversary sees all samples, values, and the rule's entire random seed; no polynomial-time implementation is asserted. + +The challenge is `MatroidSecretary`, also at `/opt/openai-math/challenges/MatroidSecretary.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +# Matroid selection against an almighty adversary + +The three guarantees concern one independent sample per label, a hidden fixed +weight vector, and a uniformly sampled observation prefix. The rule and its +finite seed law are fixed before the input weights or value distributions. +-/ + +open scoped BigOperators + +section + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +namespace MatroidProphet + +abbrev Weights (n : ℕ) := Fin n → ℝ +abbrev Seed (bits : ℕ) := Fin bits → Bool +abbrev ArrivalOrder (n : ℕ) := Equiv.Perm (Fin n) +instance arrivalOrderMeasurableSpace (n : ℕ) : MeasurableSpace (ArrivalOrder n) := ⊤ + +abbrev History (n : ℕ) (k : Fin n) := Fin (k.val + 1) → Fin n × ℝ + +structure OnlineRule (n bits : ℕ) where + decide : (k : Fin n) → Seed bits → Weights n → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Seed bits × (Weights n × History n k) => decide k x.1 x.2.1 x.2.2) + +def prefixIndex {n : ℕ} (k : Fin n) (j : Fin (k.val + 1)) : Fin n := + ⟨j.val, Nat.lt_of_lt_of_le j.isLt (Nat.succ_le_of_lt k.isLt)⟩ + +def history {n : ℕ} (v : Weights n) (π : ArrivalOrder n) (k : Fin n) : History n k := + fun j => let e := π (prefixIndex k j); (e, v e) + +def decisionAt {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (k : Fin n) : Bool := + A.decide k r s (history v π k) + +noncomputable def acceptedThrough {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ decisionAt A r s v π (π.symm e) = true + +noncomputable def accepted {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : Finset (Fin n) := + acceptedThrough A r s v π n + +noncomputable def reward {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ accepted A r s v π, v e + +noncomputable def optimum {n : ℕ} (M : Matroid (Fin n)) (v : Weights n) : ℝ := by + classical + exact Finset.univ.sup' Finset.univ_nonempty + (fun I : Finset (Fin n) => if M.Indep (I : Set (Fin n)) then ∑ e ∈ I, v e else 0) + +def Feasible {n bits : ℕ} (M : Matroid (Fin n)) (A : OnlineRule n bits) : Prop := + ∀ (r : Seed bits) (s v : Weights n) (π : ArrivalOrder n) (t : ℕ), + (∀ e, 0 ≤ s e) → (∀ e, 0 ≤ v e) → + M.Indep (acceptedThrough A r s v π t : Set (Fin n)) + +def pairedCoordinates.{u} {n : ℕ} {Ω : Type u} (S V : Ω → Weights n) + (i : Fin n × Bool) : Ω → ℝ := + if i.2 then fun ω => S ω i.1 else fun ω => V ω i.1 + +def OneSampleChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : OnlineRule n bits), Feasible M A ∧ + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (S V : Ω → Weights n) (R : Ω → Seed bits), + Measurable S → Measurable V → Measurable R → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ S ω e) → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ V ω e) → + iIndepFun (pairedCoordinates S V) μ → + (∀ e, Measure.map (fun ω => S ω e) μ = Measure.map (fun ω => V ω e) μ) → + IndepFun (fun ω => (S ω, V ω)) R μ → + Measure.map R μ = ν → + Integrable (fun ω => optimum M (V ω)) μ → + ∀ (π : Ω → ArrivalOrder n), Measurable π → + Integrable (fun ω => reward A (R ω) (S ω) (V ω) (π ω)) μ ∧ + ((2 : ℝ) ^ 310)⁻¹ * (∫ ω, optimum M (V ω) ∂μ) ≤ + ∫ ω, reward A (R ω) (S ω) (V ω) (π ω) ∂μ + +end MatroidProphet + +end + +section + +open MeasureTheory +open scoped BigOperators + +namespace MatroidProphet + +instance arrivalOrderMeasurableSingletonClass (n : ℕ) : + MeasurableSingletonClass (ArrivalOrder n) := ⟨fun _ => trivial⟩ + +structure HiddenRule (n bits : ℕ) where + mask : Seed bits → Finset (Fin n) + core : OnlineRule n bits + +noncomputable def observed {n bits : ℕ} (A : HiddenRule n bits) (r : Seed bits) + (w : Weights n) : Weights n := by + classical + exact fun e => if e ∈ A.mask r then w e else 0 + +noncomputable def hiddenAcceptedThrough {n bits : ℕ} (A : HiddenRule n bits) + (r : Seed bits) (w : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := + acceptedThrough A.core r (observed A r w) w π t \ A.mask r + +noncomputable def hiddenReward {n bits : ℕ} (A : HiddenRule n bits) + (r : Seed bits) (w : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ hiddenAcceptedThrough A r w π n, w e + +noncomputable def hiddenWorstReward {n bits : ℕ} (A : HiddenRule n bits) + (w : Weights n) (r : Seed bits) : ℝ := by + classical + exact Finset.univ.inf' Finset.univ_nonempty (hiddenReward A r w) + +end MatroidProphet + +end + +section + +open MeasureTheory ProbabilityTheory + +namespace MatroidProphet + +def HiddenVectorChallenge : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : HiddenRule n bits), + (∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ (r : Seed bits) (π : ArrivalOrder n) (t : ℕ), + M.Indep (hiddenAcceptedThrough A r w π t : Set (Fin n))) ∧ + ∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ((2 : ℝ) ^ 293)⁻¹ * optimum M w ≤ + ∫ r, hiddenWorstReward A w r ∂ν + +end MatroidProphet + +end + +section + +open MeasureTheory + +namespace MatroidProphet + +structure SecretaryRule (n : ℕ) (Q : Type*) [MeasurableSpace Q] where + prefixLength : Q → Fin (n + 1) + measurable_prefixLength : Measurable prefixLength + decide : (k : Fin n) → Q → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Q × History n k => decide k x.1 x.2) + +def SamePrefix {n : ℕ} (K : ℕ) (σ π : ArrivalOrder n) : Prop := + ∀ k : Fin n, k.val < K → σ k = π k + +def secretaryDecisionAt {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) + (k : Fin n) : Bool := + if k.val < (A.prefixLength q).val then false else A.decide k q (history w π k) + +noncomputable def secretaryAcceptedThrough {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) + (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ secretaryDecisionAt A q w π (π.symm e) = true + +noncomputable def secretaryReward {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ secretaryAcceptedThrough A q w π n, w e + +def SecretaryFeasible {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (M : Matroid (Fin n)) (A : SecretaryRule n Q) : Prop := + ∀ (q : Q) (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ (π : ArrivalOrder n) (t : ℕ), + M.Indep (secretaryAcceptedThrough A q w π t : Set (Fin n)) + +end MatroidProphet + +end + +section + +namespace MatroidProphet.Secretary + +open MeasureTheory + +noncomputable def uniformArrivalLaw (n : ℕ) : Measure (ArrivalOrder n) := + (PMF.uniformOfFintype (ArrivalOrder n)).toMeasure + +end MatroidProphet.Secretary + +end + +section + +open MeasureTheory ProbabilityTheory + +namespace MatroidProphet + +def SecretaryChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (q : ℕ) (ν : Measure (Fin q)), IsProbabilityMeasure ν ∧ + ∃ (A : SecretaryRule n (Fin q)), SecretaryFeasible M A ∧ + ∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (Q : Ω → Fin q) (σ π : Ω → ArrivalOrder n), + Measurable Q → Measurable σ → Measurable π → + Measure.map Q μ = ν → + Measure.map σ μ = Secretary.uniformArrivalLaw n → + IndepFun Q σ μ → + (∀ᵐ ω ∂μ, SamePrefix (A.prefixLength (Q ω)).val (σ ω) (π ω)) → + Integrable (fun ω => secretaryReward A (Q ω) w (π ω)) μ ∧ + ((2 : ℝ) ^ 293)⁻¹ * optimum M w ≤ + ∫ ω, secretaryReward A (Q ω) w (π ω) ∂μ + +end MatroidProphet + +end + +namespace MatroidProphet.Assigned + +theorem one_sample.{u} : MatroidProphet.OneSampleChallenge.{u} := by + sorry + +theorem hidden_vector : MatroidProphet.HiddenVectorChallenge := by + sorry + +theorem secretary.{u} : MatroidProphet.SecretaryChallenge.{u} := by + sorry + +end MatroidProphet.Assigned + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MatroidSecretary.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.MatroidProphet.Assigned.one_sample`, `OAI.MatroidProphet.Assigned.hidden_vector`, `OAI.MatroidProphet.Assigned.secretary` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/matroid-secretary/solution/closure.txt b/tasks/matroid-secretary/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c04cf3a565f97c771509a02c483e688e071fcaa2 --- /dev/null +++ b/tasks/matroid-secretary/solution/closure.txt @@ -0,0 +1,243 @@ +OAI.Probability.MatroidProphet.AdaptiveResampling +OAI.Probability.MatroidProphet.Algorithm.Cost +OAI.Probability.MatroidProphet.Algorithm.Expectation +OAI.Probability.MatroidProphet.Algorithm.Feasible +OAI.Probability.MatroidProphet.Algorithm.LayerRank +OAI.Probability.MatroidProphet.Algorithm.Mean +OAI.Probability.MatroidProphet.Algorithm.Observed +OAI.Probability.MatroidProphet.Algorithm.Rule +OAI.Probability.MatroidProphet.Algorithm.SeedLaw +OAI.Probability.MatroidProphet.Algorithm.Selection +OAI.Probability.MatroidProphet.Algorithm.Statistics +OAI.Probability.MatroidProphet.Algorithm.WeightedPayoff +OAI.Probability.MatroidProphet.Algorithm.Worst +OAI.Probability.MatroidProphet.AnalyzedMass +OAI.Probability.MatroidProphet.Baseline +OAI.Probability.MatroidProphet.BatchReveal +OAI.Probability.MatroidProphet.BranchMix +OAI.Probability.MatroidProphet.CandidateFilter +OAI.Probability.MatroidProphet.Candidates +OAI.Probability.MatroidProphet.Certificates.Budget +OAI.Probability.MatroidProphet.Certificates.Execution +OAI.Probability.MatroidProphet.CommonBudget +OAI.Probability.MatroidProphet.CompletePayoff +OAI.Probability.MatroidProphet.ConditionalThinning +OAI.Probability.MatroidProphet.Constants +OAI.Probability.MatroidProphet.Density.Basic +OAI.Probability.MatroidProphet.Density.Birth +OAI.Probability.MatroidProphet.Density.Guarded +OAI.Probability.MatroidProphet.Density.Path +OAI.Probability.MatroidProphet.ExitNumerics +OAI.Probability.MatroidProphet.FiniteBits +OAI.Probability.MatroidProphet.FocalTransfer +OAI.Probability.MatroidProphet.Gluing +OAI.Probability.MatroidProphet.GreedyOptimal +OAI.Probability.MatroidProphet.GroupConditioning +OAI.Probability.MatroidProphet.GroupPayoff +OAI.Probability.MatroidProphet.GroupSafety +OAI.Probability.MatroidProphet.GroupTransfer +OAI.Probability.MatroidProphet.Groups +OAI.Probability.MatroidProphet.HazardCover +OAI.Probability.MatroidProphet.Information +OAI.Probability.MatroidProphet.LayerGreedy +OAI.Probability.MatroidProphet.LayerOnline +OAI.Probability.MatroidProphet.LayerRank +OAI.Probability.MatroidProphet.Main +OAI.Probability.MatroidProphet.Maximum.Basic +OAI.Probability.MatroidProphet.Maximum.Guarantee +OAI.Probability.MatroidProphet.Maximum.Mask +OAI.Probability.MatroidProphet.Maximum.Probability +OAI.Probability.MatroidProphet.Maximum.Score +OAI.Probability.MatroidProphet.Model +OAI.Probability.MatroidProphet.PathRankCost +OAI.Probability.MatroidProphet.PathStatistics +OAI.Probability.MatroidProphet.Pivots.Arbitrary +OAI.Probability.MatroidProphet.Pivots.Basic +OAI.Probability.MatroidProphet.Pivots.BlockPatterns +OAI.Probability.MatroidProphet.Pivots.Blocks +OAI.Probability.MatroidProphet.Pivots.Completeness +OAI.Probability.MatroidProphet.Pivots.Count +OAI.Probability.MatroidProphet.Pivots.Encoding +OAI.Probability.MatroidProphet.Pivots.Entropy +OAI.Probability.MatroidProphet.Pivots.Existence +OAI.Probability.MatroidProphet.Pivots.Greedy +OAI.Probability.MatroidProphet.Pivots.GreedyScan +OAI.Probability.MatroidProphet.Pivots.Guarantee +OAI.Probability.MatroidProphet.Pivots.Interleavings +OAI.Probability.MatroidProphet.Pivots.OccurrenceSupport +OAI.Probability.MatroidProphet.Pivots.Patterns +OAI.Probability.MatroidProphet.Pivots.PhasePattern +OAI.Probability.MatroidProphet.Pivots.Phases +OAI.Probability.MatroidProphet.Pivots.Reindex +OAI.Probability.MatroidProphet.Pivots.ResidualFamily +OAI.Probability.MatroidProphet.Pivots.Scores +OAI.Probability.MatroidProphet.Pivots.Sign +OAI.Probability.MatroidProphet.Priority +OAI.Probability.MatroidProphet.ProductRestriction +OAI.Probability.MatroidProphet.ProductSplit +OAI.Probability.MatroidProphet.RankAccounting +OAI.Probability.MatroidProphet.RankCost +OAI.Probability.MatroidProphet.Reduction +OAI.Probability.MatroidProphet.Residual.Comparison +OAI.Probability.MatroidProphet.Residual.Constants +OAI.Probability.MatroidProphet.Residual.Deterministic +OAI.Probability.MatroidProphet.Residual.Encoding +OAI.Probability.MatroidProphet.Residual.Gap +OAI.Probability.MatroidProphet.Residual.Generators +OAI.Probability.MatroidProphet.Residual.Global +OAI.Probability.MatroidProphet.Residual.LabeledFamily +OAI.Probability.MatroidProphet.Residual.MaskUnion +OAI.Probability.MatroidProphet.Residual.Nominal +OAI.Probability.MatroidProphet.Residual.Probability +OAI.Probability.MatroidProphet.Residual.Statistics +OAI.Probability.MatroidProphet.Residual.Tail +OAI.Probability.MatroidProphet.Residual.Timeline +OAI.Probability.MatroidProphet.Residual.Transfer +OAI.Probability.MatroidProphet.Residual.Witnesses +OAI.Probability.MatroidProphet.RevealComposition +OAI.Probability.MatroidProphet.RevealContinuation +OAI.Probability.MatroidProphet.Reverse.Bands +OAI.Probability.MatroidProphet.Reverse.BirthLoss +OAI.Probability.MatroidProphet.Reverse.BirthSafety +OAI.Probability.MatroidProphet.Reverse.Certificates +OAI.Probability.MatroidProphet.Reverse.Cost +OAI.Probability.MatroidProphet.Reverse.Exposure +OAI.Probability.MatroidProphet.Reverse.Hazard +OAI.Probability.MatroidProphet.Reverse.Hybrid +OAI.Probability.MatroidProphet.Reverse.Iteration +OAI.Probability.MatroidProphet.Reverse.LowHazard +OAI.Probability.MatroidProphet.Reverse.Paths +OAI.Probability.MatroidProphet.Reverse.PrefixTree +OAI.Probability.MatroidProphet.Reverse.SquareSum +OAI.Probability.MatroidProphet.Reverse.Squared +OAI.Probability.MatroidProphet.Reverse.Trace +OAI.Probability.MatroidProphet.Rounding +OAI.Probability.MatroidProphet.SafeParity +OAI.Probability.MatroidProphet.SafeSamples +OAI.Probability.MatroidProphet.SafeStatistics +OAI.Probability.MatroidProphet.Seed +OAI.Probability.MatroidProphet.SeedLaw +OAI.Probability.MatroidProphet.Simulation +OAI.Probability.MatroidProphet.Statements +OAI.Probability.MatroidProphet.Thinning +OAI.Probability.MatroidProphet.WeightGroups +OAI.Probability.MatroidProphet.WeightedAccounting +OAI.Probability.MatroidProphet.WeightedPayoff +OAI.Probability.MatroidSecretary.Accounting.ConditionalExpectation +OAI.Probability.MatroidSecretary.Accounting.Contracts +OAI.Probability.MatroidSecretary.Accounting.ExpectedCost +OAI.Probability.MatroidSecretary.Accounting.Independent +OAI.Probability.MatroidSecretary.Accounting.MainFeasibilityContract +OAI.Probability.MatroidSecretary.Accounting.MaximumWeighted +OAI.Probability.MatroidSecretary.Accounting.Observation +OAI.Probability.MatroidSecretary.Accounting.SharpCost +OAI.Probability.MatroidSecretary.Accounting.StrictSmallGroups +OAI.Probability.MatroidSecretary.Accounting.Threshold +OAI.Probability.MatroidSecretary.Accounting.WeightedRewardModel +OAI.Probability.MatroidSecretary.Contracts +OAI.Probability.MatroidSecretary.Density.Comparison +OAI.Probability.MatroidSecretary.Density.DensityContractsModel +OAI.Probability.MatroidSecretary.Density.DensityContractsTheorems +OAI.Probability.MatroidSecretary.FixedOutsideThinning +OAI.Probability.MatroidSecretary.Labels.FiniteLabelAgreement +OAI.Probability.MatroidSecretary.Labels.FiniteLabelTransport +OAI.Probability.MatroidSecretary.Labels.FiniteLabelingModel +OAI.Probability.MatroidSecretary.Labels.LabeledHiddenModel +OAI.Probability.MatroidSecretary.Labels.LabeledHiddenVector +OAI.Probability.MatroidSecretary.Labels.LabeledOneSample +OAI.Probability.MatroidSecretary.Labels.LabeledTransport +OAI.Probability.MatroidSecretary.Labels.LabeledTransportOneSample +OAI.Probability.MatroidSecretary.Labels.RelabelingCompatibility +OAI.Probability.MatroidSecretary.Labels.RelabelingModel +OAI.Probability.MatroidSecretary.Labels.RelabelingProbability +OAI.Probability.MatroidSecretary.Labels.RelabelingProphet +OAI.Probability.MatroidSecretary.Labels.RelabelingTheorems +OAI.Probability.MatroidSecretary.Main +OAI.Probability.MatroidSecretary.Pivots.CertificateAuxSeed +OAI.Probability.MatroidSecretary.Pivots.MarkedAuxiliaryAE +OAI.Probability.MatroidSecretary.Pivots.MarkedPivotContract +OAI.Probability.MatroidSecretary.Pivots.MarkedPivotEdgeCases +OAI.Probability.MatroidSecretary.Pivots.MarkedPivotFiniteOrder +OAI.Probability.MatroidSecretary.Pivots.MarkedPivotSpecification +OAI.Probability.MatroidSecretary.Pivots.MarkedQueryProgramModel +OAI.Probability.MatroidSecretary.Pivots.MarkedTransactions +OAI.Probability.MatroidSecretary.Pivots.PatternFamilySpecificationProof +OAI.Probability.MatroidSecretary.Pivots.PivotOrderInvariance +OAI.Probability.MatroidSecretary.Pivots.RandomizedMarkedTransactions +OAI.Probability.MatroidSecretary.Pivots.RawPatternCount +OAI.Probability.MatroidSecretary.Pivots.SupportedQueryModel +OAI.Probability.MatroidSecretary.Pivots.SupportedTransactions +OAI.Probability.MatroidSecretary.Pivots.TransactionLogResource +OAI.Probability.MatroidSecretary.Residual.ExitContract +OAI.Probability.MatroidSecretary.Residual.ExitSeries +OAI.Probability.MatroidSecretary.Residual.FocalFamilyInvariance +OAI.Probability.MatroidSecretary.Residual.ResidualFamilyContract +OAI.Probability.MatroidSecretary.Residual.ResidualFamilySpecification +OAI.Probability.MatroidSecretary.Residual.ResidualTailEvent +OAI.Probability.MatroidSecretary.Residual.ResidualTailExact +OAI.Probability.MatroidSecretary.Sampling.BernoulliConditionalFiber +OAI.Probability.MatroidSecretary.Sampling.FiniteSeedModel +OAI.Probability.MatroidSecretary.Sampling.FiniteSeedTheorems +OAI.Probability.MatroidSecretary.Sampling.PrecommittedKernel +OAI.Probability.MatroidSecretary.Sampling.SourceRankMask +OAI.Probability.MatroidSecretary.Sampling.SourceSeedConditionalSupport +OAI.Probability.MatroidSecretary.Sampling.SourceSeedSupport +OAI.Probability.MatroidSecretary.Sampling.UniformPermutationImage +OAI.Probability.MatroidSecretary.Secretary.Assembly +OAI.Probability.MatroidSecretary.Secretary.BinomialMixture +OAI.Probability.MatroidSecretary.Secretary.ConditionalLaw +OAI.Probability.MatroidSecretary.Secretary.Coupling +OAI.Probability.MatroidSecretary.Secretary.CutoffLaw +OAI.Probability.MatroidSecretary.Secretary.DegenerateCases +OAI.Probability.MatroidSecretary.Secretary.Execution +OAI.Probability.MatroidSecretary.Secretary.Final +OAI.Probability.MatroidSecretary.Secretary.KernelModel +OAI.Probability.MatroidSecretary.Secretary.LawTransfer +OAI.Probability.MatroidSecretary.Secretary.MaskLaw +OAI.Probability.MatroidSecretary.Secretary.MaskLawAbe +OAI.Probability.MatroidSecretary.Secretary.MaskModel +OAI.Probability.MatroidSecretary.Secretary.Model +OAI.Probability.MatroidSecretary.Secretary.Observation +OAI.Probability.MatroidSecretary.Secretary.Precommit +OAI.Probability.MatroidSecretary.Secretary.Prefix +OAI.Probability.MatroidSecretary.Secretary.PrefixObservationModel +OAI.Probability.MatroidSecretary.Secretary.ProbabilityModel +OAI.Probability.MatroidSecretary.Secretary.Relabeling +OAI.Probability.MatroidSecretary.Secretary.Replay +OAI.Probability.MatroidSecretary.Secretary.ReplayFacts +OAI.Probability.MatroidSecretary.Secretary.ReplayRule +OAI.Probability.MatroidSecretary.Secretary.ReplayTransport +OAI.Probability.MatroidSecretary.Secretary.Seed +OAI.Probability.MatroidSecretary.Secretary.SeedModel +OAI.Probability.MatroidSecretary.Secretary.SourceAssembly +OAI.Probability.MatroidSecretary.Secretary.SourceMask +OAI.Probability.MatroidSecretary.Secretary.SourcePrefixLaw +OAI.Probability.MatroidSecretary.Secretary.Specification +OAI.Probability.MatroidSecretary.Secretary.TableLaw +OAI.Probability.MatroidSecretary.Secretary.TripleKernel +OAI.Probability.MatroidSecretary.Secretary.TripleKernelModel +OAI.Probability.MatroidSecretary.Selection.AssignedSafe +OAI.Probability.MatroidSecretary.Selection.AveragedSafeExact +OAI.Probability.MatroidSecretary.Selection.CandidateContract +OAI.Probability.MatroidSecretary.Selection.CandidateContracts +OAI.Probability.MatroidSecretary.Selection.CandidateSpecification +OAI.Probability.MatroidSecretary.Selection.CandidateSpecificationTheorems +OAI.Probability.MatroidSecretary.Selection.FeasibilityContract +OAI.Probability.MatroidSecretary.Selection.FeasibilitySpec +OAI.Probability.MatroidSecretary.Selection.GreedyExecution +OAI.Probability.MatroidSecretary.Selection.LayerImplementation +OAI.Probability.MatroidSecretary.Selection.SafeSpecification +OAI.Probability.MatroidSecretary.Transport.AdversarialMinimum +OAI.Probability.MatroidSecretary.Transport.GeneralSimulation +OAI.Probability.MatroidSecretary.Transport.GeneralSimulationModel +OAI.Probability.MatroidSecretary.Transport.InformationRestriction +OAI.Probability.MatroidSecretary.Transport.SimulationInformation +OAI.Probability.MatroidSecretary.Transport.StrongOneSample +OAI.Probability.MatroidSecretary.Transport.TransferContract +OAI.Probability.MatroidSecretary.Transport.TransferContracts +OAI.Probability.MatroidSecretary.Transport.TransferSpecification +OAI.Probability.MatroidSecretary.Weights.DegenerateCases +OAI.Probability.MatroidSecretary.Weights.FiniteWeightLawModel +OAI.Probability.MatroidSecretary.Weights.FiniteWeightLawTheorems +OAI.Probability.MatroidSecretary.Weights.OptimumIntegrability +OAI.Probability.MatroidSecretary.Weights.ZeroBenchmark diff --git a/tasks/matroid-secretary/solution/reference.py b/tasks/matroid-secretary/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/matroid-secretary/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/matroid-secretary/solution/solve.sh b/tasks/matroid-secretary/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2087efee140f0a7336ef94185b1db1b7bde15f46 --- /dev/null +++ b/tasks/matroid-secretary/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MatroidSecretary, i.e. module OAI.Probability.MatroidSecretary.Main and the +# 243 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.MatroidSecretary.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MatroidSecretary" diff --git a/tasks/matroid-secretary/task.toml b/tasks/matroid-secretary/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cb9f64b0a70eb51558f4984f1d95ad31a92cbc4f --- /dev/null +++ b/tasks/matroid-secretary/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/matroid-secretary" +version = "1.0.0" +description = "Prove MatroidSecretary (openai/math family 111: One-sample matroid prophet inequalities against an almighty adversary) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MatroidSecretary.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MatroidSecretary" +family = "111" +family_title = "One-sample matroid prophet inequalities against an almighty adversary" +subject = "Theoretical computer science" +theorems = ["OAI.MatroidProphet.Assigned.one_sample", "OAI.MatroidProphet.Assigned.hidden_vector", "OAI.MatroidProphet.Assigned.secretary"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.MatroidSecretary.Main" +reference_modules = 243 +reference_lean_bytes = 1175443 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 973 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12757 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/matroid-secretary/tests/Challenge.lean b/tasks/matroid-secretary/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..eeab143368162042ac9405e437cca64f18b24a89 --- /dev/null +++ b/tasks/matroid-secretary/tests/Challenge.lean @@ -0,0 +1,246 @@ +import Mathlib + +namespace OAI + +/-! +# Matroid selection against an almighty adversary + +The three guarantees concern one independent sample per label, a hidden fixed +weight vector, and a uniformly sampled observation prefix. The rule and its +finite seed law are fixed before the input weights or value distributions. +-/ + +open scoped BigOperators + +section + +open MeasureTheory ProbabilityTheory +open scoped BigOperators + +namespace MatroidProphet + +abbrev Weights (n : ℕ) := Fin n → ℝ +abbrev Seed (bits : ℕ) := Fin bits → Bool +abbrev ArrivalOrder (n : ℕ) := Equiv.Perm (Fin n) +instance arrivalOrderMeasurableSpace (n : ℕ) : MeasurableSpace (ArrivalOrder n) := ⊤ + +abbrev History (n : ℕ) (k : Fin n) := Fin (k.val + 1) → Fin n × ℝ + +structure OnlineRule (n bits : ℕ) where + decide : (k : Fin n) → Seed bits → Weights n → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Seed bits × (Weights n × History n k) => decide k x.1 x.2.1 x.2.2) + +def prefixIndex {n : ℕ} (k : Fin n) (j : Fin (k.val + 1)) : Fin n := + ⟨j.val, Nat.lt_of_lt_of_le j.isLt (Nat.succ_le_of_lt k.isLt)⟩ + +def history {n : ℕ} (v : Weights n) (π : ArrivalOrder n) (k : Fin n) : History n k := + fun j => let e := π (prefixIndex k j); (e, v e) + +def decisionAt {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (k : Fin n) : Bool := + A.decide k r s (history v π k) + +noncomputable def acceptedThrough {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ decisionAt A r s v π (π.symm e) = true + +noncomputable def accepted {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : Finset (Fin n) := + acceptedThrough A r s v π n + +noncomputable def reward {n bits : ℕ} (A : OnlineRule n bits) (r : Seed bits) + (s v : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ accepted A r s v π, v e + +noncomputable def optimum {n : ℕ} (M : Matroid (Fin n)) (v : Weights n) : ℝ := by + classical + exact Finset.univ.sup' Finset.univ_nonempty + (fun I : Finset (Fin n) => if M.Indep (I : Set (Fin n)) then ∑ e ∈ I, v e else 0) + +def Feasible {n bits : ℕ} (M : Matroid (Fin n)) (A : OnlineRule n bits) : Prop := + ∀ (r : Seed bits) (s v : Weights n) (π : ArrivalOrder n) (t : ℕ), + (∀ e, 0 ≤ s e) → (∀ e, 0 ≤ v e) → + M.Indep (acceptedThrough A r s v π t : Set (Fin n)) + +def pairedCoordinates.{u} {n : ℕ} {Ω : Type u} (S V : Ω → Weights n) + (i : Fin n × Bool) : Ω → ℝ := + if i.2 then fun ω => S ω i.1 else fun ω => V ω i.1 + +def OneSampleChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : OnlineRule n bits), Feasible M A ∧ + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (S V : Ω → Weights n) (R : Ω → Seed bits), + Measurable S → Measurable V → Measurable R → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ S ω e) → + (∀ᵐ ω ∂μ, ∀ e, 0 ≤ V ω e) → + iIndepFun (pairedCoordinates S V) μ → + (∀ e, Measure.map (fun ω => S ω e) μ = Measure.map (fun ω => V ω e) μ) → + IndepFun (fun ω => (S ω, V ω)) R μ → + Measure.map R μ = ν → + Integrable (fun ω => optimum M (V ω)) μ → + ∀ (π : Ω → ArrivalOrder n), Measurable π → + Integrable (fun ω => reward A (R ω) (S ω) (V ω) (π ω)) μ ∧ + ((2 : ℝ) ^ 310)⁻¹ * (∫ ω, optimum M (V ω) ∂μ) ≤ + ∫ ω, reward A (R ω) (S ω) (V ω) (π ω) ∂μ + +end MatroidProphet + +end + +section + +open MeasureTheory +open scoped BigOperators + +namespace MatroidProphet + +instance arrivalOrderMeasurableSingletonClass (n : ℕ) : + MeasurableSingletonClass (ArrivalOrder n) := ⟨fun _ => trivial⟩ + +structure HiddenRule (n bits : ℕ) where + mask : Seed bits → Finset (Fin n) + core : OnlineRule n bits + +noncomputable def observed {n bits : ℕ} (A : HiddenRule n bits) (r : Seed bits) + (w : Weights n) : Weights n := by + classical + exact fun e => if e ∈ A.mask r then w e else 0 + +noncomputable def hiddenAcceptedThrough {n bits : ℕ} (A : HiddenRule n bits) + (r : Seed bits) (w : Weights n) (π : ArrivalOrder n) (t : ℕ) : Finset (Fin n) := + acceptedThrough A.core r (observed A r w) w π t \ A.mask r + +noncomputable def hiddenReward {n bits : ℕ} (A : HiddenRule n bits) + (r : Seed bits) (w : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ hiddenAcceptedThrough A r w π n, w e + +noncomputable def hiddenWorstReward {n bits : ℕ} (A : HiddenRule n bits) + (w : Weights n) (r : Seed bits) : ℝ := by + classical + exact Finset.univ.inf' Finset.univ_nonempty (hiddenReward A r w) + +end MatroidProphet + +end + +section + +open MeasureTheory ProbabilityTheory + +namespace MatroidProphet + +def HiddenVectorChallenge : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (bits : ℕ) (ν : Measure (Seed bits)), IsProbabilityMeasure ν ∧ + ∃ (A : HiddenRule n bits), + (∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ (r : Seed bits) (π : ArrivalOrder n) (t : ℕ), + M.Indep (hiddenAcceptedThrough A r w π t : Set (Fin n))) ∧ + ∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ((2 : ℝ) ^ 293)⁻¹ * optimum M w ≤ + ∫ r, hiddenWorstReward A w r ∂ν + +end MatroidProphet + +end + +section + +open MeasureTheory + +namespace MatroidProphet + +structure SecretaryRule (n : ℕ) (Q : Type*) [MeasurableSpace Q] where + prefixLength : Q → Fin (n + 1) + measurable_prefixLength : Measurable prefixLength + decide : (k : Fin n) → Q → History n k → Bool + measurable_decide : ∀ k, Measurable + (fun x : Q × History n k => decide k x.1 x.2) + +def SamePrefix {n : ℕ} (K : ℕ) (σ π : ArrivalOrder n) : Prop := + ∀ k : Fin n, k.val < K → σ k = π k + +def secretaryDecisionAt {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) + (k : Fin n) : Bool := + if k.val < (A.prefixLength q).val then false else A.decide k q (history w π k) + +noncomputable def secretaryAcceptedThrough {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) + (t : ℕ) : Finset (Fin n) := by + classical + exact Finset.univ.filter fun e => + (π.symm e).val < t ∧ secretaryDecisionAt A q w π (π.symm e) = true + +noncomputable def secretaryReward {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (A : SecretaryRule n Q) (q : Q) (w : Weights n) (π : ArrivalOrder n) : ℝ := + ∑ e ∈ secretaryAcceptedThrough A q w π n, w e + +def SecretaryFeasible {n : ℕ} {Q : Type*} [MeasurableSpace Q] + (M : Matroid (Fin n)) (A : SecretaryRule n Q) : Prop := + ∀ (q : Q) (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ (π : ArrivalOrder n) (t : ℕ), + M.Indep (secretaryAcceptedThrough A q w π t : Set (Fin n)) + +end MatroidProphet + +end + +section + +namespace MatroidProphet.Secretary + +open MeasureTheory + +noncomputable def uniformArrivalLaw (n : ℕ) : Measure (ArrivalOrder n) := + (PMF.uniformOfFintype (ArrivalOrder n)).toMeasure + +end MatroidProphet.Secretary + +end + +section + +open MeasureTheory ProbabilityTheory + +namespace MatroidProphet + +def SecretaryChallenge.{u} : Prop := + ∀ (n : ℕ) (M : Matroid (Fin n)), M.E = Set.univ → + ∃ (q : ℕ) (ν : Measure (Fin q)), IsProbabilityMeasure ν ∧ + ∃ (A : SecretaryRule n (Fin q)), SecretaryFeasible M A ∧ + ∀ (w : Weights n), (∀ e, 0 ≤ w e) → + ∀ {Ω : Type u} [MeasurableSpace Ω] (μ : Measure Ω) [IsProbabilityMeasure μ] + (Q : Ω → Fin q) (σ π : Ω → ArrivalOrder n), + Measurable Q → Measurable σ → Measurable π → + Measure.map Q μ = ν → + Measure.map σ μ = Secretary.uniformArrivalLaw n → + IndepFun Q σ μ → + (∀ᵐ ω ∂μ, SamePrefix (A.prefixLength (Q ω)).val (σ ω) (π ω)) → + Integrable (fun ω => secretaryReward A (Q ω) w (π ω)) μ ∧ + ((2 : ℝ) ^ 293)⁻¹ * optimum M w ≤ + ∫ ω, secretaryReward A (Q ω) w (π ω) ∂μ + +end MatroidProphet + +end + +namespace MatroidProphet.Assigned + +theorem one_sample.{u} : MatroidProphet.OneSampleChallenge.{u} := by + sorry + +theorem hidden_vector : MatroidProphet.HiddenVectorChallenge := by + sorry + +theorem secretary.{u} : MatroidProphet.SecretaryChallenge.{u} := by + sorry + +end MatroidProphet.Assigned + +end OAI diff --git a/tasks/matroid-secretary/tests/grade.py b/tasks/matroid-secretary/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/matroid-secretary/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/matroid-secretary/tests/task.json b/tasks/matroid-secretary/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7be20045b8d12a6cb1aed3702bfaa4bccbe4d65f --- /dev/null +++ b/tasks/matroid-secretary/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "MatroidSecretary", + "comparator": { + "theorem_names": [ + "OAI.MatroidProphet.Assigned.one_sample", + "OAI.MatroidProphet.Assigned.hidden_vector", + "OAI.MatroidProphet.Assigned.secretary" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11857 +} \ No newline at end of file diff --git a/tasks/matroid-secretary/tests/test.sh b/tasks/matroid-secretary/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/matroid-secretary/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/maximal-seshadri-constants/environment/Dockerfile b/tasks/maximal-seshadri-constants/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/maximal-seshadri-constants/environment/fetch_mathlib.sh b/tasks/maximal-seshadri-constants/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/maximal-seshadri-constants/environment/lake-manifest.json b/tasks/maximal-seshadri-constants/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/maximal-seshadri-constants/environment/lakefile.lean b/tasks/maximal-seshadri-constants/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/maximal-seshadri-constants/environment/lean_setup.sh b/tasks/maximal-seshadri-constants/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/maximal-seshadri-constants/environment/pack_submission.py b/tasks/maximal-seshadri-constants/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/maximal-seshadri-constants/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/maximal-seshadri-constants/instruction.md b/tasks/maximal-seshadri-constants/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b1e0955cffce4cffe266afe4cb8c4e2a9c3a3b0 --- /dev/null +++ b/tasks/maximal-seshadri-constants/instruction.md @@ -0,0 +1,465 @@ +# openai/math challenge `MaximalSeshadriConstants` (family 039) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 039 of the release, *Nagata's conjecture and maximal Seshadri constants* +(Algebraic and complex geometry). The family as a whole: Proves Nagata's strict inequality $\sum_i m_i ⟨MvPolynomial.C c, MvPolynomial.isHomogeneous_C _ c⟩ + map_one' := Subtype.ext MvPolynomial.C_1 + map_mul' := fun a b => Subtype.ext (MvPolynomial.C_mul (a := a) (a' := b)) + map_zero' := Subtype.ext MvPolynomial.C_0 + map_add' := fun a b => Subtype.ext (MvPolynomial.C_add (a := a) (a' := b)) } + + +def projectiveSpaceToSpec (N : ℕ) : + complexProjectiveSpace N ⟶ Spec (CommRingCat.of ℂ) := + Proj.toSpecZero _ ≫ Spec.map (CommRingCat.ofHom (constantsInDegreeZero N)) + + + + +structure Surface where + scheme : Scheme + structureMap : scheme ⟶ Spec (CommRingCat.of ℂ) + integral : IsIntegral scheme + smooth : SmoothOfRelativeDimension 2 structureMap + embeddingDimension : ℕ + embedding : scheme ⟶ complexProjectiveSpace embeddingDimension + closedImmersion : IsClosedImmersion embedding + overComplex : embedding ≫ projectiveSpaceToSpec embeddingDimension = structureMap + +attribute [instance] Surface.integral Surface.smooth Surface.closedImmersion + +variable (X : Scheme) + + +structure LineBundle where + sheaf : X.Modules + locallyRankOne : ∀ x : X, ∃ U : X.Opens, x ∈ U ∧ + Nonempty (sheaf.restrict U.ι ≅ SheafOfModules.unit U.toScheme.ringCatSheaf) + + + +def moduleTensor (M N : X.Modules) : X.Modules := + (PresheafOfModules.sheafification (𝟙 X.ringCatSheaf.obj)).obj + (PresheafOfModulesOfCommRing.Monoidal.tensorObj (R := X.presheaf) M.val N.val) + + +def modulePow (M : X.Modules) : ℕ → X.Modules + | 0 => SheafOfModules.unit X.ringCatSheaf + | n + 1 => moduleTensor X M (modulePow M n) + + +def structureSheaf : X.Modules := SheafOfModules.unit X.ringCatSheaf + + +abbrev GlobalSections (M : X.Modules) := structureSheaf X ⟶ M + + + +def sectionOpen {M : X.Modules} (s : GlobalSections X M) : X.Opens := + ⨆ (U : X.Opens) (_ : IsIso ((Scheme.Modules.restrictFunctor U.ι).map s)), U + + +def LineBundle.IsAmple (L : LineBundle X) : Prop := + ∀ (x : X) (V : X.Opens), x ∈ V → ∃ n : ℕ, 0 < n ∧ + ∃ s : GlobalSections X (modulePow X L.sheaf n), + x ∈ sectionOpen X s ∧ sectionOpen X s ≤ V ∧ IsAffineOpen (sectionOpen X s) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + +variable (X : Scheme) + + +def restrictScalar (U : X.Opens) : Γ(X, ⊤) →+* Γ(X, U) := + (X.presheaf.map (homOfLE le_top).op).hom + +lemma restrictScalar_naturality {U V : X.Opens} (i : U ⟶ V) (r : Γ(X, ⊤)) : + X.presheaf.map i.op (restrictScalar X V r) = restrictScalar X U r := by + change (X.presheaf.map (homOfLE le_top).op ≫ X.presheaf.map i.op) r = _ + rw [← X.presheaf.map_comp] + rfl + + +def sheafHomSMul {M N : X.Modules} (r : Γ(X, ⊤)) (f : M ⟶ N) : M ⟶ N where + val := { + app U := by + letI : Module Γ(X, U.unop) (M.val.obj U) := (M.val.obj U).isModule + letI : Module Γ(X, U.unop) (N.val.obj U) := (N.val.obj U).isModule + let g : M.val.obj U →ₗ[Γ(X, U.unop)] N.val.obj U := (f.val.app U).hom + exact ModuleCat.ofHom ((restrictScalar X U.unop r) • g) + naturality {U V} g := by + let : Module (X.presheaf.obj V) (N.presheaf.obj V) := (N.val.obj V).isModule + ext m + change restrictScalar X V.unop r • f.app V.unop (M.presheaf.map g m) = + N.presheaf.map g (restrictScalar X U.unop r • f.app U.unop m) + have hn := CategoryTheory.congr_fun (f.mapPresheaf.naturality g) m + change f.app V.unop (M.presheaf.map g m) = + N.presheaf.map g (f.app U.unop m) at hn + rw [hn] + calc + _ = X.presheaf.map g (restrictScalar X U.unop r) • + N.presheaf.map g (f.app U.unop m) := by + exact congrArg (fun a : X.presheaf.obj V => + a • N.presheaf.map g (f.app U.unop m)) + (restrictScalar_naturality X g.unop r).symm + _ = _ := (N.map_smul g.unop (restrictScalar X U.unop r) (f.app U.unop m)).symm } + + +instance sheafHomModule (M N : X.Modules) : Module Γ(X, ⊤) (M ⟶ N) where + smul := sheafHomSMul X + one_smul f := by + ext U m + change restrictScalar X U 1 • f.app U m = f.app U m + simp + mul_smul r s f := by + ext U m + change restrictScalar X U (r * s) • f.app U m = + restrictScalar X U r • (restrictScalar X U s • f.app U m) + simp [mul_smul] + smul_zero r := by + ext U m + change restrictScalar X U r • (0 : Γ(N, U)) = 0 + exact smul_zero _ + smul_add r f g := by + ext U m + change restrictScalar X U r • (f.app U m + g.app U m) = + restrictScalar X U r • f.app U m + restrictScalar X U r • g.app U m + exact smul_add _ _ _ + zero_smul f := by + ext U m + change restrictScalar X U 0 • f.app U m = 0 + simp + add_smul r s f := by + ext U m + change restrictScalar X U (r + s) • f.app U m = + restrictScalar X U r • f.app U m + restrictScalar X U s • f.app U m + simp [add_smul] + +instance sheafLinear : Linear Γ(X, ⊤) X.Modules where + smul_comp M N P r f g := by + ext U m + change g.app U (restrictScalar X U r • f.app U m) = + restrictScalar X U r • g.app U (f.app U m) + exact g.app_smul _ _ + comp_smul M N P f r g := by + ext U m + rfl + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + +variable {X : Scheme.{0}} + +instance schemeHasExt : HasExt.{1} X.Modules := HasExt.standard X.Modules + + + +def baseScalars (f : X ⟶ Spec (CommRingCat.of ℂ)) : ℂ →+* Γ(X, ⊤) := + f.appTop.hom.comp (Scheme.ΓSpecIso (CommRingCat.of ℂ)).inv.hom + + + + + + + +abbrev cohomology (M : X.Modules) (n : ℕ) : Type 1 := + Abelian.Ext.{1} (C := X.Modules) (structureSheaf X) M n + + + + +def cohomologyDimension (f : X ⟶ Spec (CommRingCat.of ℂ)) + (M : X.Modules) (n : ℕ) : ℕ := + letI : Module ℂ (cohomology M n) := + Module.compHom (cohomology M n) (baseScalars f) + Module.finrank ℂ (cohomology M n) + + + +def eulerCharacteristic (f : X ⟶ Spec (CommRingCat.of ℂ)) (d : ℕ) + (M : X.Modules) : ℤ := + ∑ n ∈ Finset.range (d + 1), (-1 : ℤ) ^ n * (cohomologyDimension f M n : ℤ) + + + +def selfIntersection (S : Surface) (L : LineBundle S.scheme) : ℤ := + eulerCharacteristic S.structureMap 2 (modulePow S.scheme L.sheaf 2) - + 2 * eulerCharacteristic S.structureMap 2 L.sheaf + + eulerCharacteristic S.structureMap 2 (SheafOfModules.unit S.scheme.ringCatSheaf) + + + +structure IntegralCurve (S : Surface) where + scheme : Scheme + embedding : scheme ⟶ S.scheme + closedImmersion : IsClosedImmersion embedding + integral : IsIntegral scheme + dimension : topologicalKrullDim scheme = 1 + +attribute [instance] IntegralCurve.closedImmersion IntegralCurve.integral + + + +def curveDegree (S : Surface) (L : LineBundle S.scheme) (C : IntegralCurve S) : ℤ := + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + ((Scheme.Modules.pullback C.embedding).obj L.sheaf) - + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + (SheafOfModules.unit C.scheme.ringCatSheaf) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory CategoryTheory.Limits AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + + +abbrev complexBase : Scheme := Spec (CommRingCat.of ℂ) + + +abbrev ComplexPoint (S : Surface) := + Over.mk (𝟙 complexBase) ⟶ Over.mk S.structureMap + + +def ComplexPoint.image {S : Surface} (p : ComplexPoint S) : S.scheme := + p.left (⟨⊥, Ideal.isPrime_bot⟩ : PrimeSpectrum ℂ) + + +def surfacePower (S : Surface) (r : ℕ) : Over complexBase := + ∏ᶜ (fun _ : Fin r => Over.mk S.structureMap) + + +def tupleImage (S : Surface) (r : ℕ) (p : Fin r → ComplexPoint S) : + (surfacePower S r).left := + (Limits.Pi.lift p).left (⟨⊥, Ideal.isPrime_bot⟩ : PrimeSpectrum ℂ) + + + +@[instance_reducible] def tupleZariskiTopology (S : Surface) (r : ℕ) : + TopologicalSpace (Fin r → ComplexPoint S) := + TopologicalSpace.induced (tupleImage S r) inferInstance + + +def Configuration (S : Surface) (r : ℕ) := + {p : Fin r → ComplexPoint S // Function.Injective (fun i => (p i).image)} + +instance configurationTopology (S : Surface) (r : ℕ) : + TopologicalSpace (Configuration S r) := + letI := tupleZariskiTopology S r + inferInstanceAs (TopologicalSpace {p : Fin r → ComplexPoint S // + Function.Injective (fun i => (p i).image)}) + + + + + +def idealOrder {R : Type} [CommRing R] [IsLocalRing R] (I : Ideal R) : ℕ := + sInf {n : ℕ | ¬ I ≤ IsLocalRing.maximalIdeal R ^ (n + 1)} + + + + +def curveMultiplicity (S : Surface) (C : IntegralCurve S) (p : ComplexPoint S) : ℕ := by + classical + exact if h : ∃ q : C.scheme, C.embedding q = p.image then + idealOrder (RingHom.ker (C.embedding.stalkMap h.choose).hom) + else 0 + + +def totalMultiplicity (S : Surface) (r : ℕ) (C : IntegralCurve S) + (p : Configuration S r) : ℕ := + ∑ i : Fin r, curveMultiplicity S C (p.val i) + + +def seshadriConstant (S : Surface) (L : LineBundle S.scheme) (r : ℕ) + (p : Configuration S r) : ℝ := + sInf {a : ℝ | ∃ C : IntegralCurve S, 0 < totalMultiplicity S r C p ∧ + a = (curveDegree S L C : ℝ) / (totalMultiplicity S r C p : ℝ)} + + + + + + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory CategoryTheory.Limits AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + + + + +def moduleCurveDegree (S : Surface) (M : S.scheme.Modules) (C : IntegralCurve S) : ℤ := + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + ((Scheme.Modules.pullback C.embedding).obj M) - + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + (structureSheaf C.scheme) + + + +def sectionImageIdeal {X : Scheme} (J : LineBundle X) + (ι : J.sheaf ⟶ structureSheaf X) (U : X.Opens) : Ideal Γ(X, U) := by + letI : Module Γ(X, U) (J.sheaf.val.obj (Opposite.op U)) := + (J.sheaf.val.obj (Opposite.op U)).isModule + let φ : J.sheaf.val.obj (Opposite.op U) →ₗ[Γ(X, U)] Γ(X, U) := + (ι.val.app (Opposite.op U)).hom + exact φ.range + + + + +def PresentsPullbackIdeal {X Y : Scheme} (I : X.IdealSheafData) (f : Y ⟶ X) + (J : LineBundle Y) (ι : J.sheaf ⟶ structureSheaf Y) : Prop := + Mono ι ∧ ∀ (U : Y.affineOpens) (V : X.affineOpens) + (e : U.1 ≤ f ⁻¹ᵁ V.1), + sectionImageIdeal J ι U.1 = (I.ideal V).map (f.appLE V.1 U.1 e).hom + + +def InvertiblePullbackIdeal {X Y : Scheme} (I : X.IdealSheafData) (f : Y ⟶ X) : Prop := + ∃ (J : LineBundle Y) (ι : J.sheaf ⟶ structureSheaf Y), PresentsPullbackIdeal I f J ι + + + + +def centreIdeal (S : Surface) (r : ℕ) (p : Configuration S r) : S.scheme.IdealSheafData := + ∏ i : Fin r, (p.val i).left.ker + + + + +def IsBlowup {X B : Scheme} (I : X.IdealSheafData) (π : B ⟶ X) : Prop := + InvertiblePullbackIdeal I π ∧ ∀ (Y : Scheme) (f : Y ⟶ X), + InvertiblePullbackIdeal I f → ∃! h : Y ⟶ B, h ≫ π = f + + + + +structure PointBlowup (S : Surface) (r : ℕ) (p : Configuration S r) where + surface : Surface + projection : surface.scheme ⟶ S.scheme + overComplex : projection ≫ S.structureMap = surface.structureMap + isBlowup : IsBlowup (centreIdeal S r p) projection + exceptionalIdeal : Fin r → LineBundle surface.scheme + exceptionalInclusion : ∀ i, (exceptionalIdeal i).sheaf ⟶ structureSheaf surface.scheme + exceptionalPullback : ∀ i, PresentsPullbackIdeal (p.val i).left.ker projection + (exceptionalIdeal i) (exceptionalInclusion i) + + + + +def PointBlowup.BoundaryNef {S : Surface} {r : ℕ} {p : Configuration S r} + (B : PointBlowup S r p) (L : LineBundle S.scheme) : Prop := + ∀ C : IntegralCurve B.surface, + 0 ≤ (moduleCurveDegree B.surface + ((Scheme.Modules.pullback B.projection).obj L.sheaf) C : ℝ) + + Real.sqrt ((selfIntersection S L : ℝ) / r) * + ∑ i : Fin r, (curveDegree B.surface (B.exceptionalIdeal i) C : ℝ) + + + +def EventualMaximalSeshadri (S : Surface) (L : LineBundle S.scheme) : Prop := + ∃ r₀ : ℕ, 0 < r₀ ∧ ∀ r : ℕ, r₀ ≤ r → + ∃ Z : ℕ → Set (Configuration S r), + (∀ n, IsClosed (Z n) ∧ Z n ≠ Set.univ) ∧ + (∃ p : Configuration S r, ∀ n, p ∉ Z n) ∧ + ∀ p : Configuration S r, (∀ n, p ∉ Z n) → + (∃ B : PointBlowup S r p, B.BoundaryNef L) ∧ + seshadriConstant S L r p = Real.sqrt ((selfIntersection S L : ℝ) / r) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry + +theorem maximalSeshadriConstants (S : Surface) (L : LineBundle S.scheme) + (hL : LineBundle.IsAmple S.scheme L) : EventualMaximalSeshadri S L := by + sorry + +end MaximalSeshadri.Geometry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MaximalSeshadriConstants.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MaximalSeshadri.Geometry.maximalSeshadriConstants` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/maximal-seshadri-constants/solution/closure.txt b/tasks/maximal-seshadri-constants/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..df666dcae7c49a1d9eb230f7497155799036f3ec --- /dev/null +++ b/tasks/maximal-seshadri-constants/solution/closure.txt @@ -0,0 +1,421 @@ +OAI.AlgebraicGeometry.Seshadri.Analytic.ConvergentSeries +OAI.AlgebraicGeometry.Seshadri.Analytic.CoordinateJets +OAI.AlgebraicGeometry.Seshadri.Analytic.EtaleJetCharts +OAI.AlgebraicGeometry.Seshadri.Analytic.FormalSeries +OAI.AlgebraicGeometry.Seshadri.Analytic.PointCharts +OAI.AlgebraicGeometry.Seshadri.Analytic.PolynomialCharts +OAI.AlgebraicGeometry.Seshadri.Analytic.TaylorCoefficients +OAI.AlgebraicGeometry.Seshadri.Bertini.CountableSpecialization +OAI.AlgebraicGeometry.Seshadri.Bertini.CriticalLocus +OAI.AlgebraicGeometry.Seshadri.Bertini.Derivations +OAI.AlgebraicGeometry.Seshadri.Bertini.Descent +OAI.AlgebraicGeometry.Seshadri.Bertini.DifferentialFrames +OAI.AlgebraicGeometry.Seshadri.Bertini.EtaleCoordinates +OAI.AlgebraicGeometry.Seshadri.Bertini.GenericHyperplanes +OAI.AlgebraicGeometry.Seshadri.Bertini.GenericSmoothness +OAI.AlgebraicGeometry.Seshadri.Bertini.GeometricDomains +OAI.AlgebraicGeometry.Seshadri.Bertini.HyperplaneFamilies +OAI.AlgebraicGeometry.Seshadri.Bertini.IntegralSubschemes +OAI.AlgebraicGeometry.Seshadri.Bertini.LinearFamilies +OAI.AlgebraicGeometry.Seshadri.Bertini.LinearForms +OAI.AlgebraicGeometry.Seshadri.Bertini.SimultaneousHyperplanes +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupAffineSections +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupEffectiveBound +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupForbiddenSection +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupHartogsCharts +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupIntegral +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupIntersection +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupIntersectionGrowth +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupLineDescent +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupProper +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupSectionDescent +OAI.AlgebraicGeometry.Seshadri.Blowup.BlowupSectionDimensions +OAI.AlgebraicGeometry.Seshadri.Blowup.BoundaryNef +OAI.AlgebraicGeometry.Seshadri.Blowup.EventualExceptionalAmple +OAI.AlgebraicGeometry.Seshadri.Blowup.ExceptionalIdeal +OAI.AlgebraicGeometry.Seshadri.Blowup.FiniteCenters +OAI.AlgebraicGeometry.Seshadri.Blowup.Gluing +OAI.AlgebraicGeometry.Seshadri.Blowup.HartogsPrincipal +OAI.AlgebraicGeometry.Seshadri.Blowup.HartogsScheme +OAI.AlgebraicGeometry.Seshadri.Blowup.LocalEquations +OAI.AlgebraicGeometry.Seshadri.Blowup.LocalUniversal +OAI.AlgebraicGeometry.Seshadri.Blowup.NefPerturbation +OAI.AlgebraicGeometry.Seshadri.Blowup.OrderContraction +OAI.AlgebraicGeometry.Seshadri.Blowup.PlaneCharts +OAI.AlgebraicGeometry.Seshadri.Blowup.PointBlowupExistence +OAI.AlgebraicGeometry.Seshadri.Blowup.PointSmoothness +OAI.AlgebraicGeometry.Seshadri.Blowup.PowerContraction +OAI.AlgebraicGeometry.Seshadri.Blowup.PrincipalCharts +OAI.AlgebraicGeometry.Seshadri.Blowup.ReesAlgebra +OAI.AlgebraicGeometry.Seshadri.Blowup.ReesCharts +OAI.AlgebraicGeometry.Seshadri.Blowup.ReesSections +OAI.AlgebraicGeometry.Seshadri.Blowup.RelativeReesSections +OAI.AlgebraicGeometry.Seshadri.Blowup.SchemeHartogs +OAI.AlgebraicGeometry.Seshadri.Blowup.UnequalNefNumerics +OAI.AlgebraicGeometry.Seshadri.Blowup.Uniqueness +OAI.AlgebraicGeometry.Seshadri.Cohomology.AffineDenominators +OAI.AlgebraicGeometry.Seshadri.Cohomology.AffineVanishing +OAI.AlgebraicGeometry.Seshadri.Cohomology.BaseCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.CartierExtraction +OAI.AlgebraicGeometry.Seshadri.Cohomology.CechH0 +OAI.AlgebraicGeometry.Seshadri.Cohomology.CechPresentation +OAI.AlgebraicGeometry.Seshadri.Cohomology.ClosedPushforwardCohomology +OAI.AlgebraicGeometry.Seshadri.Cohomology.CohomologyIso +OAI.AlgebraicGeometry.Seshadri.Cohomology.CurveCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.CurveCohomology +OAI.AlgebraicGeometry.Seshadri.Cohomology.CurveH0Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.CurveH1Bound +OAI.AlgebraicGeometry.Seshadri.Cohomology.CurveH1Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.CycleStructures +OAI.AlgebraicGeometry.Seshadri.Cohomology.ExtCokernel +OAI.AlgebraicGeometry.Seshadri.Cohomology.FiniteCover +OAI.AlgebraicGeometry.Seshadri.Cohomology.FiniteSupportCohomology +OAI.AlgebraicGeometry.Seshadri.Cohomology.FreeVertices +OAI.AlgebraicGeometry.Seshadri.Cohomology.GeneralSurfaceH2 +OAI.AlgebraicGeometry.Seshadri.Cohomology.Injectives +OAI.AlgebraicGeometry.Seshadri.Cohomology.IntegralExtension +OAI.AlgebraicGeometry.Seshadri.Cohomology.IntegralIdealExtension +OAI.AlgebraicGeometry.Seshadri.Cohomology.KernelH1 +OAI.AlgebraicGeometry.Seshadri.Cohomology.KernelVertices +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentH0 +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentIntersection +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentLattices +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentPlane +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentSupport +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentTails +OAI.AlgebraicGeometry.Seshadri.Cohomology.LaurentTorsion +OAI.AlgebraicGeometry.Seshadri.Cohomology.MixedDivisibleExtension +OAI.AlgebraicGeometry.Seshadri.Cohomology.MixedGlobalExtension +OAI.AlgebraicGeometry.Seshadri.Cohomology.MixedLocalExtension +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneCechFinite +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneCechLinear +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneFreeCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneH0Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneH1Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlanePairToric +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlanePairs +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneRelationCycles +OAI.AlgebraicGeometry.Seshadri.Cohomology.PlaneVertex +OAI.AlgebraicGeometry.Seshadri.Cohomology.ProjectiveCurveCohomology +OAI.AlgebraicGeometry.Seshadri.Cohomology.RestrictionComparison +OAI.AlgebraicGeometry.Seshadri.Cohomology.SectionIdealExt +OAI.AlgebraicGeometry.Seshadri.Cohomology.SheafExactness +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceBaseCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceCech +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceCohomology +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceH0Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceH1Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceH1Growth +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceH2Finite +OAI.AlgebraicGeometry.Seshadri.Cohomology.SurfaceH2Untwist +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricCoordinates +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricFreeMap +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricH0 +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricH1 +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricPolynomial +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricPresentation +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricSpan +OAI.AlgebraicGeometry.Seshadri.Cohomology.ToricVertexPresentation +OAI.AlgebraicGeometry.Seshadri.Cohomology.TripleComplex +OAI.AlgebraicGeometry.Seshadri.Cohomology.TripleEvaluation +OAI.AlgebraicGeometry.Seshadri.Cohomology.TripleExt +OAI.AlgebraicGeometry.Seshadri.Cohomology.TripleFree +OAI.AlgebraicGeometry.Seshadri.Cohomology.TripleTopExt +OAI.AlgebraicGeometry.Seshadri.Configurations.AffineCenter +OAI.AlgebraicGeometry.Seshadri.Configurations.AffinePointParameters +OAI.AlgebraicGeometry.Seshadri.Configurations.CenterPrime +OAI.AlgebraicGeometry.Seshadri.Configurations.Configurations +OAI.AlgebraicGeometry.Seshadri.Configurations.GlobalCenter +OAI.AlgebraicGeometry.Seshadri.Configurations.RationalPoint +OAI.AlgebraicGeometry.Seshadri.Configurations.SmoothRationalPoints +OAI.AlgebraicGeometry.Seshadri.Definitions +OAI.AlgebraicGeometry.Seshadri.Divisors.AffineSectionQuotient +OAI.AlgebraicGeometry.Seshadri.Divisors.BaseSections +OAI.AlgebraicGeometry.Seshadri.Divisors.CartierResidual +OAI.AlgebraicGeometry.Seshadri.Divisors.CartierSection +OAI.AlgebraicGeometry.Seshadri.Divisors.CartierSequence +OAI.AlgebraicGeometry.Seshadri.Divisors.CenteredSections +OAI.AlgebraicGeometry.Seshadri.Divisors.CoprimeDivisor +OAI.AlgebraicGeometry.Seshadri.Divisors.IdealSectionLifting +OAI.AlgebraicGeometry.Seshadri.Divisors.IntegralCurveCartier +OAI.AlgebraicGeometry.Seshadri.Divisors.IntegralSectionIdeal +OAI.AlgebraicGeometry.Seshadri.Divisors.LinearSections +OAI.AlgebraicGeometry.Seshadri.Divisors.MaximalCartier +OAI.AlgebraicGeometry.Seshadri.Divisors.MaximalCartierIso +OAI.AlgebraicGeometry.Seshadri.Divisors.MixedSectionOpen +OAI.AlgebraicGeometry.Seshadri.Divisors.MixedSections +OAI.AlgebraicGeometry.Seshadri.Divisors.OpenSectionsLinear +OAI.AlgebraicGeometry.Seshadri.Divisors.PolynomialSections +OAI.AlgebraicGeometry.Seshadri.Divisors.PrincipalSectionIdeal +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionChart +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionCoefficientOrder +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionCokernel +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionComponent +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionCurveBound +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionGermSystem +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionIdeal +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionMono +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionNaturality +OAI.AlgebraicGeometry.Seshadri.Divisors.SectionTransport +OAI.AlgebraicGeometry.Seshadri.Geometry.AffineBundleFinite +OAI.AlgebraicGeometry.Seshadri.Geometry.AffineLineFinite +OAI.AlgebraicGeometry.Seshadri.Geometry.AmpleFromCover +OAI.AlgebraicGeometry.Seshadri.Geometry.AmplePowers +OAI.AlgebraicGeometry.Seshadri.Geometry.ChartCoherence +OAI.AlgebraicGeometry.Seshadri.Geometry.ChartPolynomial +OAI.AlgebraicGeometry.Seshadri.Geometry.CurveFinite +OAI.AlgebraicGeometry.Seshadri.Geometry.CurveFiniteMap +OAI.AlgebraicGeometry.Seshadri.Geometry.CurveMultiplicity +OAI.AlgebraicGeometry.Seshadri.Geometry.CurvePencil +OAI.AlgebraicGeometry.Seshadri.Geometry.CurveProjection +OAI.AlgebraicGeometry.Seshadri.Geometry.EtaleAffineTest +OAI.AlgebraicGeometry.Seshadri.Geometry.EtaleDimension +OAI.AlgebraicGeometry.Seshadri.Geometry.EtaleLowerDimension +OAI.AlgebraicGeometry.Seshadri.Geometry.EtalePointChart +OAI.AlgebraicGeometry.Seshadri.Geometry.EtaleRealization +OAI.AlgebraicGeometry.Seshadri.Geometry.EtaleRegularPair +OAI.AlgebraicGeometry.Seshadri.Geometry.FiniteScheme +OAI.AlgebraicGeometry.Seshadri.Geometry.FiniteSupportTwist +OAI.AlgebraicGeometry.Seshadri.Geometry.FreePresentation +OAI.AlgebraicGeometry.Seshadri.Geometry.FreeVertexClearing +OAI.AlgebraicGeometry.Seshadri.Geometry.GeneralQuadraticNumerics +OAI.AlgebraicGeometry.Seshadri.Geometry.GeneratedEtaleCoordinates +OAI.AlgebraicGeometry.Seshadri.Geometry.GeometricDivision +OAI.AlgebraicGeometry.Seshadri.Geometry.IntegralImage +OAI.AlgebraicGeometry.Seshadri.Geometry.LineClosedUnit +OAI.AlgebraicGeometry.Seshadri.Geometry.LocalCoordinateAtlas +OAI.AlgebraicGeometry.Seshadri.Geometry.LocalQuadratic +OAI.AlgebraicGeometry.Seshadri.Geometry.NestedChart +OAI.AlgebraicGeometry.Seshadri.Geometry.NormalizedMixed +OAI.AlgebraicGeometry.Seshadri.Geometry.PencilCharts +OAI.AlgebraicGeometry.Seshadri.Geometry.PencilCokernel +OAI.AlgebraicGeometry.Seshadri.Geometry.PencilOverlap +OAI.AlgebraicGeometry.Seshadri.Geometry.PlaneBoundaries +OAI.AlgebraicGeometry.Seshadri.Geometry.PlaneChartAlgebra +OAI.AlgebraicGeometry.Seshadri.Geometry.PlaneCoordinates +OAI.AlgebraicGeometry.Seshadri.Geometry.PolynomialLattices +OAI.AlgebraicGeometry.Seshadri.Geometry.PrincipalSequence +OAI.AlgebraicGeometry.Seshadri.Geometry.ProperGlobalField +OAI.AlgebraicGeometry.Seshadri.Geometry.RelativeProjectivity +OAI.AlgebraicGeometry.Seshadri.Geometry.ResidualZero +OAI.AlgebraicGeometry.Seshadri.Geometry.SmoothAffineRefinement +OAI.AlgebraicGeometry.Seshadri.Geometry.SmoothSurfaceDimension +OAI.AlgebraicGeometry.Seshadri.Geometry.SubsystemCoordinates +OAI.AlgebraicGeometry.Seshadri.Geometry.SurfaceAffineCover +OAI.AlgebraicGeometry.Seshadri.Geometry.SurfaceDenseProjection +OAI.AlgebraicGeometry.Seshadri.Geometry.SurfaceProjection +OAI.AlgebraicGeometry.Seshadri.Geometry.SurfaceTopGrowth +OAI.AlgebraicGeometry.Seshadri.Geometry.TwoChartFinite +OAI.AlgebraicGeometry.Seshadri.Interpolation.ActualInterpolation +OAI.AlgebraicGeometry.Seshadri.Interpolation.AllCurveLowerBound +OAI.AlgebraicGeometry.Seshadri.Interpolation.AllSectionQuadrilateral +OAI.AlgebraicGeometry.Seshadri.Interpolation.CompressionRanks +OAI.AlgebraicGeometry.Seshadri.Interpolation.ConvergentSeries +OAI.AlgebraicGeometry.Seshadri.Interpolation.CyclicLattices +OAI.AlgebraicGeometry.Seshadri.Interpolation.EtaleQuadrilateral +OAI.AlgebraicGeometry.Seshadri.Interpolation.GermInterpolation +OAI.AlgebraicGeometry.Seshadri.Interpolation.InitialBasis +OAI.AlgebraicGeometry.Seshadri.Interpolation.LaurentJets +OAI.AlgebraicGeometry.Seshadri.Interpolation.LaurentMoments +OAI.AlgebraicGeometry.Seshadri.Interpolation.Moments +OAI.AlgebraicGeometry.Seshadri.Interpolation.PolynomialBounds +OAI.AlgebraicGeometry.Seshadri.Interpolation.PrimitiveDirections +OAI.AlgebraicGeometry.Seshadri.Interpolation.QuadrilateralRows +OAI.AlgebraicGeometry.Seshadri.Interpolation.RowCompression +OAI.AlgebraicGeometry.Seshadri.Interpolation.SeshadriUpper +OAI.AlgebraicGeometry.Seshadri.Interpolation.SeshadriUpperNumerics +OAI.AlgebraicGeometry.Seshadri.Interpolation.SurfaceQuadrilateral +OAI.AlgebraicGeometry.Seshadri.Interpolation.TorusJets +OAI.AlgebraicGeometry.Seshadri.Interpolation.TriangleJets +OAI.AlgebraicGeometry.Seshadri.Interpolation.VeryGeneralInterpolation +OAI.AlgebraicGeometry.Seshadri.Interpolation.WeightedRescaling +OAI.AlgebraicGeometry.Seshadri.Intersection.AllCurveDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.AmbientCurveDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.AmpleCurveDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.ArbitraryCartierEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.BivariateSurfaceEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.CartierEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.CurveCartierEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.CurveDegreeAdditivity +OAI.AlgebraicGeometry.Seshadri.Intersection.CurveDegreePositive +OAI.AlgebraicGeometry.Seshadri.Intersection.CurveIdealDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.CurvePowerDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.CurveSectionDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.EffectiveDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.EulerExact +OAI.AlgebraicGeometry.Seshadri.Intersection.ExactDimensionBound +OAI.AlgebraicGeometry.Seshadri.Intersection.FiniteEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.FiniteIntersection +OAI.AlgebraicGeometry.Seshadri.Intersection.FiniteLineEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.GeneralSurfaceEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.GlobalIntersectionLength +OAI.AlgebraicGeometry.Seshadri.Intersection.IdealProductDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.IntegralCurveEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.IntegralSectionDimension +OAI.AlgebraicGeometry.Seshadri.Intersection.IntersectionBilinear +OAI.AlgebraicGeometry.Seshadri.Intersection.IntersectionCurveIso +OAI.AlgebraicGeometry.Seshadri.Intersection.IntersectionEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.LocalSectionDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.MixedIntersection +OAI.AlgebraicGeometry.Seshadri.Intersection.OpenChartDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.PencilIntersection +OAI.AlgebraicGeometry.Seshadri.Intersection.PositiveSquareEffectivity +OAI.AlgebraicGeometry.Seshadri.Intersection.QuadraticSequence +OAI.AlgebraicGeometry.Seshadri.Intersection.QuotientIntersection +OAI.AlgebraicGeometry.Seshadri.Intersection.SchematicIntersection +OAI.AlgebraicGeometry.Seshadri.Intersection.SectionDimension +OAI.AlgebraicGeometry.Seshadri.Intersection.SectionEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.SurfaceCurveDegree +OAI.AlgebraicGeometry.Seshadri.Intersection.SurfaceEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.SurfacePositiveSquare +OAI.AlgebraicGeometry.Seshadri.Intersection.SurfaceQuadraticEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.SurfaceTwistEuler +OAI.AlgebraicGeometry.Seshadri.Intersection.TwistNumerics +OAI.AlgebraicGeometry.Seshadri.Intersection.TwoChartIntersection +OAI.AlgebraicGeometry.Seshadri.Jets.AnalyticFullRank +OAI.AlgebraicGeometry.Seshadri.Jets.AnalyticNode +OAI.AlgebraicGeometry.Seshadri.Jets.BinaryJetDimension +OAI.AlgebraicGeometry.Seshadri.Jets.CenteredJetChart +OAI.AlgebraicGeometry.Seshadri.Jets.CenteredRationalJet +OAI.AlgebraicGeometry.Seshadri.Jets.CoordinateEquivalences +OAI.AlgebraicGeometry.Seshadri.Jets.EffectiveJetFrames +OAI.AlgebraicGeometry.Seshadri.Jets.EffectiveJets +OAI.AlgebraicGeometry.Seshadri.Jets.EtaleAnalytic +OAI.AlgebraicGeometry.Seshadri.Jets.FormalAdic +OAI.AlgebraicGeometry.Seshadri.Jets.FormalEtale +OAI.AlgebraicGeometry.Seshadri.Jets.JetOpenConfigurations +OAI.AlgebraicGeometry.Seshadri.Jets.JetOpenness +OAI.AlgebraicGeometry.Seshadri.Jets.JetVanishing +OAI.AlgebraicGeometry.Seshadri.Jets.LocalQuotients +OAI.AlgebraicGeometry.Seshadri.Jets.NodalTaylor +OAI.AlgebraicGeometry.Seshadri.Jets.PolynomialJets +OAI.AlgebraicGeometry.Seshadri.Jets.QuadraticJets +OAI.AlgebraicGeometry.Seshadri.Jets.SectionJetDimensions +OAI.AlgebraicGeometry.Seshadri.Jets.UniformAnalyticAlgebra +OAI.AlgebraicGeometry.Seshadri.Lattice.InitialWeights +OAI.AlgebraicGeometry.Seshadri.Lattice.NodePolygon +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.ArtinianLength +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.ClosedColength +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.ClosedStalk +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.CurveOrderExact +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.ExactPointOrder +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.FiniteStalkSum +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.IdealContractionMembership +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.IdealEquation +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.IntegralCurveIdeal +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.LinearRadical +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.LocalBinaryPrime +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.LocalContainment +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.LocalCurvePrincipal +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.LocalDimension +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.PointIdealGenerators +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.PointIdealMembership +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.PowerIdeal +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.SmoothCurvePrincipal +OAI.AlgebraicGeometry.Seshadri.LocalAlgebra.TwistedIdealPower +OAI.AlgebraicGeometry.Seshadri.Main +OAI.AlgebraicGeometry.Seshadri.Model +OAI.AlgebraicGeometry.Seshadri.Nodal.BranchDimension +OAI.AlgebraicGeometry.Seshadri.Nodal.BranchFaithfulness +OAI.AlgebraicGeometry.Seshadri.Nodal.EtaleNodalDivisor +OAI.AlgebraicGeometry.Seshadri.Nodal.EtaleNode +OAI.AlgebraicGeometry.Seshadri.Nodal.FramedNodalChart +OAI.AlgebraicGeometry.Seshadri.Nodal.FramedNodalDivisor +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalAssociated +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalBranch +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalCurveDegree +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalDegree +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalDivisor +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalDivisorDegree +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalGlobalBound +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalGlobalLength +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalIdealDegree +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalIdealEuler +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalIntersection +OAI.AlgebraicGeometry.Seshadri.Nodal.NodalNumericalDegree +OAI.AlgebraicGeometry.Seshadri.Nodal.QuadraticDiscriminant +OAI.AlgebraicGeometry.Seshadri.Nodal.SchemeNodalIntersection +OAI.AlgebraicGeometry.Seshadri.Projective.AmpleBertini +OAI.AlgebraicGeometry.Seshadri.Projective.AmpleEmbedding +OAI.AlgebraicGeometry.Seshadri.Projective.BertiniEquations +OAI.AlgebraicGeometry.Seshadri.Projective.BertiniSection +OAI.AlgebraicGeometry.Seshadri.Projective.CenteredEmbedding +OAI.AlgebraicGeometry.Seshadri.Projective.ClosedEmbedding +OAI.AlgebraicGeometry.Seshadri.Projective.CoprimeEmbedding +OAI.AlgebraicGeometry.Seshadri.Projective.FiniteAtlas +OAI.AlgebraicGeometry.Seshadri.Projective.FramedMaps +OAI.AlgebraicGeometry.Seshadri.Projective.GlobalIntegralQuartic +OAI.AlgebraicGeometry.Seshadri.Projective.GlobalQuartic +OAI.AlgebraicGeometry.Seshadri.Projective.HyperplaneAvoidance +OAI.AlgebraicGeometry.Seshadri.Projective.HyperplaneIdeal +OAI.AlgebraicGeometry.Seshadri.Projective.HyperplanePullback +OAI.AlgebraicGeometry.Seshadri.Projective.HyperplaneSection +OAI.AlgebraicGeometry.Seshadri.Projective.LocalBertiniSection +OAI.AlgebraicGeometry.Seshadri.Projective.MixedEmbedding +OAI.AlgebraicGeometry.Seshadri.Projective.OrdinaryQuadraticQuartic +OAI.AlgebraicGeometry.Seshadri.Projective.PolynomialCharts +OAI.AlgebraicGeometry.Seshadri.Projective.ProjectiveCartier +OAI.AlgebraicGeometry.Seshadri.Projective.ProjectiveCoordinates +OAI.AlgebraicGeometry.Seshadri.Projective.ProjectiveMapEvaluation +OAI.AlgebraicGeometry.Seshadri.Projective.ProjectiveRefinement +OAI.AlgebraicGeometry.Seshadri.Projective.ProjectiveTranslate +OAI.AlgebraicGeometry.Seshadri.Projective.PullbackProjective +OAI.AlgebraicGeometry.Seshadri.Projective.QuarticBertini +OAI.AlgebraicGeometry.Seshadri.Projective.QuarticDivision +OAI.AlgebraicGeometry.Seshadri.Projective.QuarticIdealBertini +OAI.AlgebraicGeometry.Seshadri.Projective.QuarticReindex +OAI.AlgebraicGeometry.Seshadri.Projective.QuarticSubsystem +OAI.AlgebraicGeometry.Seshadri.Projective.SectionMaps +OAI.AlgebraicGeometry.Seshadri.Projective.SurfaceQuartic +OAI.AlgebraicGeometry.Seshadri.Sheaves.AffineLocalizing +OAI.AlgebraicGeometry.Seshadri.Sheaves.AffineOrderRestriction +OAI.AlgebraicGeometry.Seshadri.Sheaves.AmpleFramedCover +OAI.AlgebraicGeometry.Seshadri.Sheaves.BaseChangeNatural +OAI.AlgebraicGeometry.Seshadri.Sheaves.CartierModule +OAI.AlgebraicGeometry.Seshadri.Sheaves.CartierRestriction +OAI.AlgebraicGeometry.Seshadri.Sheaves.CartierTensor +OAI.AlgebraicGeometry.Seshadri.Sheaves.ChartModuleMap +OAI.AlgebraicGeometry.Seshadri.Sheaves.ClosedModuleExact +OAI.AlgebraicGeometry.Seshadri.Sheaves.ClosedPushforwardEuler +OAI.AlgebraicGeometry.Seshadri.Sheaves.ClosedPushforwardExact +OAI.AlgebraicGeometry.Seshadri.Sheaves.DiscreteLineBundle +OAI.AlgebraicGeometry.Seshadri.Sheaves.EtaleLineFrame +OAI.AlgebraicGeometry.Seshadri.Sheaves.FramedPullback +OAI.AlgebraicGeometry.Seshadri.Sheaves.Frames +OAI.AlgebraicGeometry.Seshadri.Sheaves.LineBundleCoherent +OAI.AlgebraicGeometry.Seshadri.Sheaves.LinePullback +OAI.AlgebraicGeometry.Seshadri.Sheaves.LinePullbackTensor +OAI.AlgebraicGeometry.Seshadri.Sheaves.ModuleLocal +OAI.AlgebraicGeometry.Seshadri.Sheaves.OpenBaseChange +OAI.AlgebraicGeometry.Seshadri.Sheaves.OpenPullbackUnit +OAI.AlgebraicGeometry.Seshadri.Sheaves.PlaneModules +OAI.AlgebraicGeometry.Seshadri.Sheaves.PlaneProjectionModule +OAI.AlgebraicGeometry.Seshadri.Sheaves.PowerExtension +OAI.AlgebraicGeometry.Seshadri.Sheaves.PullbackSectionLinear +OAI.AlgebraicGeometry.Seshadri.Sheaves.PullbackSectionOpenExact +OAI.AlgebraicGeometry.Seshadri.Sheaves.PullbackTensorRestrict +OAI.AlgebraicGeometry.Seshadri.Sheaves.PushforwardTensor +OAI.AlgebraicGeometry.Seshadri.Sheaves.RestrictTensorMap +OAI.AlgebraicGeometry.Seshadri.Sheaves.RestrictedGenerators +OAI.AlgebraicGeometry.Seshadri.Sheaves.RestrictedSections +OAI.AlgebraicGeometry.Seshadri.Sheaves.Restriction +OAI.AlgebraicGeometry.Seshadri.Sheaves.RestrictionLocalization +OAI.AlgebraicGeometry.Seshadri.Sheaves.SectionOpens +OAI.AlgebraicGeometry.Seshadri.Sheaves.SectionPullback +OAI.AlgebraicGeometry.Seshadri.Sheaves.Sections +OAI.AlgebraicGeometry.Seshadri.Sheaves.SupportedSheaf +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorAssocPure +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorCurveEuler +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorDivision +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorFramePure +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorFrames +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorInclusion +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorOpenSection +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorOpenSquare +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorPowerDistribution +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorPowerPure +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorPure +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorRestrictPure +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorSectionOpen +OAI.AlgebraicGeometry.Seshadri.Sheaves.TensorUnitPure diff --git a/tasks/maximal-seshadri-constants/solution/reference.py b/tasks/maximal-seshadri-constants/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/maximal-seshadri-constants/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/maximal-seshadri-constants/solution/solve.sh b/tasks/maximal-seshadri-constants/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a05d9815d85156070160b8f1a43469efa642269a --- /dev/null +++ b/tasks/maximal-seshadri-constants/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MaximalSeshadriConstants, i.e. module OAI.AlgebraicGeometry.Seshadri.Main and the +# 421 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.AlgebraicGeometry.Seshadri.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MaximalSeshadriConstants" diff --git a/tasks/maximal-seshadri-constants/task.toml b/tasks/maximal-seshadri-constants/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..79242e26f81d4b67761533042d9826346c368952 --- /dev/null +++ b/tasks/maximal-seshadri-constants/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/maximal-seshadri-constants" +version = "1.0.0" +description = "Prove MaximalSeshadriConstants (openai/math family 039: Nagata's conjecture and maximal Seshadri constants) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MaximalSeshadriConstants.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MaximalSeshadriConstants" +family = "039" +family_title = "Nagata's conjecture and maximal Seshadri constants" +subject = "Algebraic and complex geometry" +theorems = ["OAI.MaximalSeshadri.Geometry.maximalSeshadriConstants"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.AlgebraicGeometry.Seshadri.Main" +reference_modules = 421 +reference_lean_bytes = 2494022 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2446 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13944 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/maximal-seshadri-constants/tests/Challenge.lean b/tasks/maximal-seshadri-constants/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6e7879e23dd19a40bcdd5b488c3c4a23f3afaa4c --- /dev/null +++ b/tasks/maximal-seshadri-constants/tests/Challenge.lean @@ -0,0 +1,414 @@ +import Mathlib + +namespace OAI + + + + + + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + +attribute [local instance] MvPolynomial.gradedAlgebra + + +def complexProjectiveSpace (N : ℕ) : Scheme := + Proj (MvPolynomial.homogeneousSubmodule (Fin (N + 1)) ℂ) + + +def constantsInDegreeZero (N : ℕ) : + ℂ →+* (MvPolynomial.homogeneousSubmodule (Fin (N + 1)) ℂ 0) := + { toFun := fun c => ⟨MvPolynomial.C c, MvPolynomial.isHomogeneous_C _ c⟩ + map_one' := Subtype.ext MvPolynomial.C_1 + map_mul' := fun a b => Subtype.ext (MvPolynomial.C_mul (a := a) (a' := b)) + map_zero' := Subtype.ext MvPolynomial.C_0 + map_add' := fun a b => Subtype.ext (MvPolynomial.C_add (a := a) (a' := b)) } + + +def projectiveSpaceToSpec (N : ℕ) : + complexProjectiveSpace N ⟶ Spec (CommRingCat.of ℂ) := + Proj.toSpecZero _ ≫ Spec.map (CommRingCat.ofHom (constantsInDegreeZero N)) + + + + +structure Surface where + scheme : Scheme + structureMap : scheme ⟶ Spec (CommRingCat.of ℂ) + integral : IsIntegral scheme + smooth : SmoothOfRelativeDimension 2 structureMap + embeddingDimension : ℕ + embedding : scheme ⟶ complexProjectiveSpace embeddingDimension + closedImmersion : IsClosedImmersion embedding + overComplex : embedding ≫ projectiveSpaceToSpec embeddingDimension = structureMap + +attribute [instance] Surface.integral Surface.smooth Surface.closedImmersion + +variable (X : Scheme) + + +structure LineBundle where + sheaf : X.Modules + locallyRankOne : ∀ x : X, ∃ U : X.Opens, x ∈ U ∧ + Nonempty (sheaf.restrict U.ι ≅ SheafOfModules.unit U.toScheme.ringCatSheaf) + + + +def moduleTensor (M N : X.Modules) : X.Modules := + (PresheafOfModules.sheafification (𝟙 X.ringCatSheaf.obj)).obj + (PresheafOfModulesOfCommRing.Monoidal.tensorObj (R := X.presheaf) M.val N.val) + + +def modulePow (M : X.Modules) : ℕ → X.Modules + | 0 => SheafOfModules.unit X.ringCatSheaf + | n + 1 => moduleTensor X M (modulePow M n) + + +def structureSheaf : X.Modules := SheafOfModules.unit X.ringCatSheaf + + +abbrev GlobalSections (M : X.Modules) := structureSheaf X ⟶ M + + + +def sectionOpen {M : X.Modules} (s : GlobalSections X M) : X.Opens := + ⨆ (U : X.Opens) (_ : IsIso ((Scheme.Modules.restrictFunctor U.ι).map s)), U + + +def LineBundle.IsAmple (L : LineBundle X) : Prop := + ∀ (x : X) (V : X.Opens), x ∈ V → ∃ n : ℕ, 0 < n ∧ + ∃ s : GlobalSections X (modulePow X L.sheaf n), + x ∈ sectionOpen X s ∧ sectionOpen X s ≤ V ∧ IsAffineOpen (sectionOpen X s) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + +variable (X : Scheme) + + +def restrictScalar (U : X.Opens) : Γ(X, ⊤) →+* Γ(X, U) := + (X.presheaf.map (homOfLE le_top).op).hom + +lemma restrictScalar_naturality {U V : X.Opens} (i : U ⟶ V) (r : Γ(X, ⊤)) : + X.presheaf.map i.op (restrictScalar X V r) = restrictScalar X U r := by + change (X.presheaf.map (homOfLE le_top).op ≫ X.presheaf.map i.op) r = _ + rw [← X.presheaf.map_comp] + rfl + + +def sheafHomSMul {M N : X.Modules} (r : Γ(X, ⊤)) (f : M ⟶ N) : M ⟶ N where + val := { + app U := by + letI : Module Γ(X, U.unop) (M.val.obj U) := (M.val.obj U).isModule + letI : Module Γ(X, U.unop) (N.val.obj U) := (N.val.obj U).isModule + let g : M.val.obj U →ₗ[Γ(X, U.unop)] N.val.obj U := (f.val.app U).hom + exact ModuleCat.ofHom ((restrictScalar X U.unop r) • g) + naturality {U V} g := by + let : Module (X.presheaf.obj V) (N.presheaf.obj V) := (N.val.obj V).isModule + ext m + change restrictScalar X V.unop r • f.app V.unop (M.presheaf.map g m) = + N.presheaf.map g (restrictScalar X U.unop r • f.app U.unop m) + have hn := CategoryTheory.congr_fun (f.mapPresheaf.naturality g) m + change f.app V.unop (M.presheaf.map g m) = + N.presheaf.map g (f.app U.unop m) at hn + rw [hn] + calc + _ = X.presheaf.map g (restrictScalar X U.unop r) • + N.presheaf.map g (f.app U.unop m) := by + exact congrArg (fun a : X.presheaf.obj V => + a • N.presheaf.map g (f.app U.unop m)) + (restrictScalar_naturality X g.unop r).symm + _ = _ := (N.map_smul g.unop (restrictScalar X U.unop r) (f.app U.unop m)).symm } + + +instance sheafHomModule (M N : X.Modules) : Module Γ(X, ⊤) (M ⟶ N) where + smul := sheafHomSMul X + one_smul f := by + ext U m + change restrictScalar X U 1 • f.app U m = f.app U m + simp + mul_smul r s f := by + ext U m + change restrictScalar X U (r * s) • f.app U m = + restrictScalar X U r • (restrictScalar X U s • f.app U m) + simp [mul_smul] + smul_zero r := by + ext U m + change restrictScalar X U r • (0 : Γ(N, U)) = 0 + exact smul_zero _ + smul_add r f g := by + ext U m + change restrictScalar X U r • (f.app U m + g.app U m) = + restrictScalar X U r • f.app U m + restrictScalar X U r • g.app U m + exact smul_add _ _ _ + zero_smul f := by + ext U m + change restrictScalar X U 0 • f.app U m = 0 + simp + add_smul r s f := by + ext U m + change restrictScalar X U (r + s) • f.app U m = + restrictScalar X U r • f.app U m + restrictScalar X U s • f.app U m + simp [add_smul] + +instance sheafLinear : Linear Γ(X, ⊤) X.Modules where + smul_comp M N P r f g := by + ext U m + change g.app U (restrictScalar X U r • f.app U m) = + restrictScalar X U r • g.app U (f.app U m) + exact g.app_smul _ _ + comp_smul M N P f r g := by + ext U m + rfl + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + +variable {X : Scheme.{0}} + +instance schemeHasExt : HasExt.{1} X.Modules := HasExt.standard X.Modules + + + +def baseScalars (f : X ⟶ Spec (CommRingCat.of ℂ)) : ℂ →+* Γ(X, ⊤) := + f.appTop.hom.comp (Scheme.ΓSpecIso (CommRingCat.of ℂ)).inv.hom + + + + + + + +abbrev cohomology (M : X.Modules) (n : ℕ) : Type 1 := + Abelian.Ext.{1} (C := X.Modules) (structureSheaf X) M n + + + + +def cohomologyDimension (f : X ⟶ Spec (CommRingCat.of ℂ)) + (M : X.Modules) (n : ℕ) : ℕ := + letI : Module ℂ (cohomology M n) := + Module.compHom (cohomology M n) (baseScalars f) + Module.finrank ℂ (cohomology M n) + + + +def eulerCharacteristic (f : X ⟶ Spec (CommRingCat.of ℂ)) (d : ℕ) + (M : X.Modules) : ℤ := + ∑ n ∈ Finset.range (d + 1), (-1 : ℤ) ^ n * (cohomologyDimension f M n : ℤ) + + + +def selfIntersection (S : Surface) (L : LineBundle S.scheme) : ℤ := + eulerCharacteristic S.structureMap 2 (modulePow S.scheme L.sheaf 2) - + 2 * eulerCharacteristic S.structureMap 2 L.sheaf + + eulerCharacteristic S.structureMap 2 (SheafOfModules.unit S.scheme.ringCatSheaf) + + + +structure IntegralCurve (S : Surface) where + scheme : Scheme + embedding : scheme ⟶ S.scheme + closedImmersion : IsClosedImmersion embedding + integral : IsIntegral scheme + dimension : topologicalKrullDim scheme = 1 + +attribute [instance] IntegralCurve.closedImmersion IntegralCurve.integral + + + +def curveDegree (S : Surface) (L : LineBundle S.scheme) (C : IntegralCurve S) : ℤ := + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + ((Scheme.Modules.pullback C.embedding).obj L.sheaf) - + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + (SheafOfModules.unit C.scheme.ringCatSheaf) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory CategoryTheory.Limits AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + + +abbrev complexBase : Scheme := Spec (CommRingCat.of ℂ) + + +abbrev ComplexPoint (S : Surface) := + Over.mk (𝟙 complexBase) ⟶ Over.mk S.structureMap + + +def ComplexPoint.image {S : Surface} (p : ComplexPoint S) : S.scheme := + p.left (⟨⊥, Ideal.isPrime_bot⟩ : PrimeSpectrum ℂ) + + +def surfacePower (S : Surface) (r : ℕ) : Over complexBase := + ∏ᶜ (fun _ : Fin r => Over.mk S.structureMap) + + +def tupleImage (S : Surface) (r : ℕ) (p : Fin r → ComplexPoint S) : + (surfacePower S r).left := + (Limits.Pi.lift p).left (⟨⊥, Ideal.isPrime_bot⟩ : PrimeSpectrum ℂ) + + + +@[instance_reducible] def tupleZariskiTopology (S : Surface) (r : ℕ) : + TopologicalSpace (Fin r → ComplexPoint S) := + TopologicalSpace.induced (tupleImage S r) inferInstance + + +def Configuration (S : Surface) (r : ℕ) := + {p : Fin r → ComplexPoint S // Function.Injective (fun i => (p i).image)} + +instance configurationTopology (S : Surface) (r : ℕ) : + TopologicalSpace (Configuration S r) := + letI := tupleZariskiTopology S r + inferInstanceAs (TopologicalSpace {p : Fin r → ComplexPoint S // + Function.Injective (fun i => (p i).image)}) + + + + + +def idealOrder {R : Type} [CommRing R] [IsLocalRing R] (I : Ideal R) : ℕ := + sInf {n : ℕ | ¬ I ≤ IsLocalRing.maximalIdeal R ^ (n + 1)} + + + + +def curveMultiplicity (S : Surface) (C : IntegralCurve S) (p : ComplexPoint S) : ℕ := by + classical + exact if h : ∃ q : C.scheme, C.embedding q = p.image then + idealOrder (RingHom.ker (C.embedding.stalkMap h.choose).hom) + else 0 + + +def totalMultiplicity (S : Surface) (r : ℕ) (C : IntegralCurve S) + (p : Configuration S r) : ℕ := + ∑ i : Fin r, curveMultiplicity S C (p.val i) + + +def seshadriConstant (S : Surface) (L : LineBundle S.scheme) (r : ℕ) + (p : Configuration S r) : ℝ := + sInf {a : ℝ | ∃ C : IntegralCurve S, 0 < totalMultiplicity S r C p ∧ + a = (curveDegree S L C : ℝ) / (totalMultiplicity S r C p : ℝ)} + + + + + + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry +noncomputable section +open CategoryTheory CategoryTheory.Limits AlgebraicGeometry TopologicalSpace +open scoped AlgebraicGeometry + + + + +def moduleCurveDegree (S : Surface) (M : S.scheme.Modules) (C : IntegralCurve S) : ℤ := + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + ((Scheme.Modules.pullback C.embedding).obj M) - + eulerCharacteristic (C.embedding ≫ S.structureMap) 1 + (structureSheaf C.scheme) + + + +def sectionImageIdeal {X : Scheme} (J : LineBundle X) + (ι : J.sheaf ⟶ structureSheaf X) (U : X.Opens) : Ideal Γ(X, U) := by + letI : Module Γ(X, U) (J.sheaf.val.obj (Opposite.op U)) := + (J.sheaf.val.obj (Opposite.op U)).isModule + let φ : J.sheaf.val.obj (Opposite.op U) →ₗ[Γ(X, U)] Γ(X, U) := + (ι.val.app (Opposite.op U)).hom + exact φ.range + + + + +def PresentsPullbackIdeal {X Y : Scheme} (I : X.IdealSheafData) (f : Y ⟶ X) + (J : LineBundle Y) (ι : J.sheaf ⟶ structureSheaf Y) : Prop := + Mono ι ∧ ∀ (U : Y.affineOpens) (V : X.affineOpens) + (e : U.1 ≤ f ⁻¹ᵁ V.1), + sectionImageIdeal J ι U.1 = (I.ideal V).map (f.appLE V.1 U.1 e).hom + + +def InvertiblePullbackIdeal {X Y : Scheme} (I : X.IdealSheafData) (f : Y ⟶ X) : Prop := + ∃ (J : LineBundle Y) (ι : J.sheaf ⟶ structureSheaf Y), PresentsPullbackIdeal I f J ι + + + + +def centreIdeal (S : Surface) (r : ℕ) (p : Configuration S r) : S.scheme.IdealSheafData := + ∏ i : Fin r, (p.val i).left.ker + + + + +def IsBlowup {X B : Scheme} (I : X.IdealSheafData) (π : B ⟶ X) : Prop := + InvertiblePullbackIdeal I π ∧ ∀ (Y : Scheme) (f : Y ⟶ X), + InvertiblePullbackIdeal I f → ∃! h : Y ⟶ B, h ≫ π = f + + + + +structure PointBlowup (S : Surface) (r : ℕ) (p : Configuration S r) where + surface : Surface + projection : surface.scheme ⟶ S.scheme + overComplex : projection ≫ S.structureMap = surface.structureMap + isBlowup : IsBlowup (centreIdeal S r p) projection + exceptionalIdeal : Fin r → LineBundle surface.scheme + exceptionalInclusion : ∀ i, (exceptionalIdeal i).sheaf ⟶ structureSheaf surface.scheme + exceptionalPullback : ∀ i, PresentsPullbackIdeal (p.val i).left.ker projection + (exceptionalIdeal i) (exceptionalInclusion i) + + + + +def PointBlowup.BoundaryNef {S : Surface} {r : ℕ} {p : Configuration S r} + (B : PointBlowup S r p) (L : LineBundle S.scheme) : Prop := + ∀ C : IntegralCurve B.surface, + 0 ≤ (moduleCurveDegree B.surface + ((Scheme.Modules.pullback B.projection).obj L.sheaf) C : ℝ) + + Real.sqrt ((selfIntersection S L : ℝ) / r) * + ∑ i : Fin r, (curveDegree B.surface (B.exceptionalIdeal i) C : ℝ) + + + +def EventualMaximalSeshadri (S : Surface) (L : LineBundle S.scheme) : Prop := + ∃ r₀ : ℕ, 0 < r₀ ∧ ∀ r : ℕ, r₀ ≤ r → + ∃ Z : ℕ → Set (Configuration S r), + (∀ n, IsClosed (Z n) ∧ Z n ≠ Set.univ) ∧ + (∃ p : Configuration S r, ∀ n, p ∉ Z n) ∧ + ∀ p : Configuration S r, (∀ n, p ∉ Z n) → + (∃ B : PointBlowup S r p, B.BoundaryNef L) ∧ + seshadriConstant S L r p = Real.sqrt ((selfIntersection S L : ℝ) / r) + +end +end MaximalSeshadri.Geometry + +namespace MaximalSeshadri.Geometry + +theorem maximalSeshadriConstants (S : Surface) (L : LineBundle S.scheme) + (hL : LineBundle.IsAmple S.scheme L) : EventualMaximalSeshadri S L := by + sorry + +end MaximalSeshadri.Geometry + +end OAI diff --git a/tasks/maximal-seshadri-constants/tests/grade.py b/tasks/maximal-seshadri-constants/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/maximal-seshadri-constants/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/maximal-seshadri-constants/tests/task.json b/tasks/maximal-seshadri-constants/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7a44fbbb7d859a1615d55e895662317654b42d95 --- /dev/null +++ b/tasks/maximal-seshadri-constants/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MaximalSeshadriConstants", + "comparator": { + "theorem_names": [ + "OAI.MaximalSeshadri.Geometry.maximalSeshadriConstants" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13044 +} \ No newline at end of file diff --git a/tasks/maximal-seshadri-constants/tests/test.sh b/tasks/maximal-seshadri-constants/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/maximal-seshadri-constants/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/memory-precision/environment/Dockerfile b/tasks/memory-precision/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/memory-precision/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/memory-precision/environment/fetch_mathlib.sh b/tasks/memory-precision/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/memory-precision/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/memory-precision/environment/lake-manifest.json b/tasks/memory-precision/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/memory-precision/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/memory-precision/environment/lakefile.lean b/tasks/memory-precision/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/memory-precision/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/memory-precision/environment/lean_setup.sh b/tasks/memory-precision/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/memory-precision/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/memory-precision/environment/pack_submission.py b/tasks/memory-precision/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/memory-precision/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/memory-precision/instruction.md b/tasks/memory-precision/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c7041c4401db756cde297d94733a6f5a5771f9fe --- /dev/null +++ b/tasks/memory-precision/instruction.md @@ -0,0 +1,863 @@ +# openai/math challenge `MemoryPrecision` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `MemoryPrecision`, also at `/opt/openai-math/challenges/MemoryPrecision.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter EuclideanGeometry +open scoped ENNReal NNReal RealInnerProductSpace Topology Pointwise + +noncomputable section +universe u v + +namespace MemoryPrecision.Kernel + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev State (M : ℕ) := Fin (2^M) + +abbrev Action (M : ℕ) := Bool × State M + +abbrev Observations (d k : ℕ) := Fin k → (Vector d × ℝ) + +abbrev Rows (d k : ℕ) := Fin k → Vector d + +def UniformSphere (d : ℕ) : Measure (Sphere d) := + let euclideanGroup : NormedAddCommGroup (Vector d) := + PiLp.normedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ) + let euclideanInner := PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ) + let σ := @Measure.toSphere (Vector d) euclideanGroup + (@InnerProductSpace.toNormedSpace ℝ (Vector d) _ + euclideanGroup.toSeminormedAddCommGroup euclideanInner) inferInstance + (@volume (Vector d) (@measureSpaceOfInnerProductSpace (Vector d) + euclideanGroup euclideanInner inferInstance inferInstance inferInstance)) + (σ Set.univ)⁻¹ • σ + +def RowLaw (d k : ℕ) : @Measure (Rows d k) + (@MeasurableSpace.pi (Fin k) (fun _ => Vector d) + (fun _ => @WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (Fin d → ℝ) inferInstance)) := + let euclideanMeasurable := @WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (Fin d → ℝ) inferInstance + @Measure.pi (Fin k) (fun _ => Vector d) inferInstance (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Vector d) + (PiLp.normedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) inferInstance euclideanMeasurable) + +def ObservationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Policy (d M T : ℕ) where + initial : Action M → ℝ≥0∞ + initial_sum : ∑ a, initial a = 1 + transition : ℕ → State M → (Vector d × ℝ) → Action M → ℝ≥0∞ + transition_sum : ∀ t j obs, ∑ a, transition t j obs a = 1 + output : ℕ → State M → Measure (Sphere d) + output_probability : ∀ t j, IsProbabilityMeasure (output t j) + +namespace Policy + +def Completed {d M T : ℕ} (K : Policy d M T) : Prop := + ∀ t j a, AEMeasurable (fun obs => K.transition t j obs a) (ObservationReference d) + +def eval {d M T : ℕ} {X : Type*} (K : Policy d M T) + (w : ℕ → State M → X → ℝ≥0∞) (n : ℕ) : + (k : ℕ) → State M → X → Observations d k → ℝ≥0∞ + | 0, j, s, _ => w n j s + | k+1, j, s, obs => ∑ a : Action M, K.transition (n+1) j (obs 0) a * + if a.1 then w (n+1) a.2 s else K.eval w (n+1) k a.2 s (Fin.tail obs) + +def pathValue {d M T : ℕ} {X : Type*} (K : Policy d M T) + (w : ℕ → State M → X → ℝ≥0∞) (s : X) (obs : Observations d T) : ℝ≥0∞ := + ∑ a : Action M, K.initial a * if a.1 then w 0 a.2 s else K.eval w 0 T a.2 s obs + +def records {d T : ℕ} (s : Sphere d) (A : Rows d T) : Observations d T := + fun index => (A index, @inner ℝ (EuclideanSpace ℝ (Fin d)) + (@InnerProductSpace.toInner ℝ (EuclideanSpace ℝ (Fin d)) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) s.val (A index)) + +def outputTest {d M T : ℕ} (K : Policy d M T) (f : Sphere d × Sphere d → ℝ≥0∞) + (t : ℕ) (j : State M) (s : Sphere d) : ℝ≥0∞ := + ∫⁻ v, f (s,v) ∂K.output t j + +def angleTest {d : ℕ} (ε : ℝ) + (point : MemoryPrecision.Kernel.Sphere d × MemoryPrecision.Kernel.Sphere d) : ℝ≥0∞ := + @ite ℝ≥0∞ (Real.arccos (@inner ℝ (EuclideanSpace ℝ (Fin d)) + (@InnerProductSpace.toInner ℝ (EuclideanSpace ℝ (Fin d)) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + point.2.val point.1.val) ≤ ε) (Classical.propDecidable _) 1 0 + +def chordTest {d : ℕ} (ε : ℝ) (x : Sphere d × Sphere d) : ℝ≥0∞ := + {x : Sphere d × Sphere d | dist x.2.val x.1.val ≤ ε}.indicator (fun _ => 1) x + +def experiment {d M T : ℕ} {Ω : Type u} (K : Ω → Policy d M T) + (f : Sphere d × Sphere d → ℝ≥0∞) (z : Sphere d × (Ω × Rows d T)) : ℝ≥0∞ := + (K z.2.1).pathValue ((K z.2.1).outputTest f) z.1 (records z.1 z.2.2) + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) : Prop where + completed : ∀ᵐ ω ∂ρ, (K ω).Completed + experiment : ∀ f : Sphere d × Sphere d → ℝ≥0∞, Measurable f → + (∀ x, f x ≤ 1) → AEMeasurable (experiment K f) (π.prod (ρ.prod (RowLaw d T))) + +def Success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z, experiment K (angleTest ε) z ∂π.prod (ρ.prod (RowLaw d T)) + +def ChordSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z, experiment K (chordTest ε) z ∂π.prod (ρ.prod (RowLaw d T)) + +end Policy +end MemoryPrecision.Kernel + +namespace NoiselessRegression +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +end NoiselessRegression + +namespace MemoryPrecision +open NoiselessRegression + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def J (β : ℝ) (m j : ℕ) : ℝ := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let three : ℝ := @OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1))) + 1 + three^j * two^β * (m : ℝ) / (β - (j : ℝ) - (m : ℝ)) + +def AmbientBallBound {d : ℕ} (μ : Measure (Space d)) (H β : ℝ) : Prop := + ∀ x : Space d, ∀ r : ℝ, 0 < r → + μ (Metric.closedBall x r) ≤ ENNReal.ofReal (H * r^β) + +def InverseGram {d p : ℕ} (m : ℕ) (v : Space d × (Fin (p-1) → Space d)) : ℝ≥0∞ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + letI : AddCommGroup (Space d) := WithLp.instAddCommGroup exponent (Fin d → ℝ) + letI : Inner ℝ (Space d) := @InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + ENNReal.ofReal ((Real.sqrt (Matrix.gram ℝ (fun i => v.2 i - v.1)).det)⁻¹ ^ m) + +def MatrixLabelReference (d m : ℕ) : @Measure ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod (Fin m → Space d) (Fin m → ℝ) + (@MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + inferInstance) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := WithLp.measurableSpace exponent (Fin d → ℝ) + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + let rowLaw := @Measure.pi (Fin m) (fun _ => Space d) inferInstance + (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + inferInstance euclideanMeasurable) + @Measure.prod _ _ rowMeasurable inferInstance rowLaw volume + +def ProjectionLaw {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) : @Measure ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod (Fin m → Space d) (Fin m → ℝ) + (@MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + inferInstance) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := WithLp.measurableSpace exponent (Fin d → ℝ) + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + let rowLaw := @Measure.pi (Fin m) (fun _ => Space d) inferInstance + (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + inferInstance euclideanMeasurable) + @Measure.map ((Fin m → Space d) × Space d) ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod _ _ rowMeasurable euclideanMeasurable) + (@MeasurableSpace.prod _ _ rowMeasurable inferInstance) + (fun pair => (pair.1, fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + pair.2 (pair.1 index))) + (@Measure.prod _ _ rowMeasurable euclideanMeasurable rowLaw μ) + +def ProjectedEllipsoid {d m : ℕ} (z : Space d) (R : ℝ) : + Set ((Fin m → Space d) × (Fin m → ℝ)) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanInner := @InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + {pair | ∃ displacement ∈ @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.toLp exponent (fun _ => (0 : ℝ))) R, + pair.2 = fun index => @inner ℝ (Space d) euclideanInner z (pair.1 index) + + @inner ℝ (Space d) euclideanInner displacement (pair.1 index)} + +def ProjectionNormScale (m p : ℕ) (H β R : ℝ) : ℝ := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + (two * Real.pi) ^ (-(m : ℝ) * ((p : ℝ)-1) / (two*(p : ℝ))) * H * + R ^ (β - (m : ℝ)*(1-1/(p : ℝ))) * + (∏ j ∈ Finset.range (p-1), J β m j) ^ (1/(p : ℝ)) + +def UniformSphere (d : ℕ) : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ)) := + let euclideanMeasurable := WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ) + @Measure.map (Kernel.Sphere d) (Space d) + (MeasurableSpace.comap Subtype.val euclideanMeasurable) euclideanMeasurable + Subtype.val (Kernel.UniformSphere d) + +def GaussianRegularization {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) (δ : ℝ) + (Ay : (Fin m → Space d) × (Fin m → ℝ)) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + ∫ signal, ∏ index, gaussianPDFReal 0 ⟨δ^2, sq_nonneg δ⟩ + (Ay.2 index - @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + signal (Ay.1 index)) ∂μ + +def PointwiseDensity {d : ℕ} (μ : Measure (Space d)) (m : ℕ) + (x : (Fin m → Space d) × (Fin m → ℝ)) : ℝ := by + classical + exact if h : ∃ l : ℝ, Tendsto (fun i : ℕ => GaussianRegularization μ m (1/(i:ℝ)) x) + atTop (𝓝 l) then Classical.choose h else 0 + +lemma space_finiteDimensional (d : ℕ) : FiniteDimensional ℝ (Space d) := by + infer_instance + +def UnitBallVolume (m : ℕ) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanGroup := PiLp.normedAddCommGroup exponent (fun _ : Fin m => ℝ) + letI : MeasurableSpace (Space m) := WithLp.measurableSpace exponent (Fin m → ℝ) + let euclideanVolume := @volume (Space m) (@measureSpaceOfInnerProductSpace (Space m) + euclideanGroup (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin m => ℝ)) + (space_finiteDimensional m) inferInstance inferInstance) + (euclideanVolume (@Metric.ball (Space m) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin m => ℝ)) + (WithLp.toLp exponent (fun _ : Fin m => (0 : ℝ))) 1)).toReal + +def CoordinateUnit (m : ℕ) : Space m := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + WithLp.toLp exponent (fun j : Fin m => if (j:ℕ) = 0 then (1:ℝ) else 0) + +lemma gaussianVariance_nonneg (δ : ℝ) : 0 ≤ δ^2 := sq_nonneg δ + +def GaussianKernel (m : ℕ) (δ : ℝ) (y : Space m) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∏ index, gaussianPDFReal 0 ⟨δ^2, gaussianVariance_nonneg δ⟩ + (@WithLp.ofLp exponent (Fin m → ℝ) y index) + +def RadialMixture (m : ℕ) (δ r : ℝ) : ℝ := + UnitBallVolume m * r^m * (r / δ^2) * GaussianKernel m δ (r • CoordinateUnit m) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Space d) 1 + +def SpherePrior (d : ℕ) : Measure (Sphere d) := + MemoryPrecision.Kernel.UniformSphere d + +def SphereBallBound {d : ℕ} (h : Sphere d → ℝ≥0∞) (H α : ℝ) : Prop := + ∀ z : Space d, ∀ r : ℝ, 0 < r → + (∫⁻ s in {s : Sphere d | dist s.val z ≤ r}, h s ∂SpherePrior d) ≤ + ENNReal.ofReal (H * r^α) + +section WeightedImage +variable {X : Type*} [MeasurableSpace X] {d m N : ℕ} + +def WeightedBlock (ι : X → Space d) (h : Fin N → X → ℝ≥0∞) + (g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞) (x : X) : ℝ≥0∞ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := @WithLp.measurableSpace exponent (Fin d → ℝ) inferInstance + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + @MeasureTheory.lintegral (Fin m → Space d) rowMeasurable + (@Measure.pi (Fin m) (fun _ => Space d) inferInstance (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + (space_finiteDimensional d) euclideanMeasurable)) + (fun rows => ∑ state, g state (rows, fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + (ι x) (rows index)) * h state x) + +end WeightedImage + +def SphereBlock {d m N : ℕ} (h : Fin N → Sphere d → ℝ≥0∞) + (g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞) + (s : Sphere d) : ℝ≥0∞ := + WeightedBlock Subtype.val h g s + +abbrev CubeSet (n : ℕ) : Set (EuclideanSpace ℝ (Fin n)) := + fun (point : EuclideanSpace ℝ (Fin n)) => ∀ index : Fin n, + @LE.le ℝ Real.instLE + (@abs ℝ Real.lattice Real.instAddGroup + (@WithLp.ofLp + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (Fin n → ℝ) point index)) + (@HDiv.hDiv ℝ ℝ ℝ (@instHDiv ℝ Real.instDivInvMonoid.toDiv) + (@OfNat.ofNat ℝ 1 (@One.toOfNat1 ℝ Real.instOne)) + (@OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))))) + +abbrev Cube (d : ℕ) := CubeSet (d/2) + +def CubeLaw (d : ℕ) : Measure (Cube d) := + (volume : Measure (Space (d/2))).comap Subtype.val + +lemma cube_second_coordinate_lt (d : ℕ) (index : Fin d) + (lower : ¬index.val < d/2) (upper : index.val < 2*(d/2)) : + index.val - d/2 < d/2 := by omega + +def cubeRaw (d : ℕ) (u : Space (d/2)) : Space d := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + @HSMul.hSMul ℝ (Space d) (Space d) + (@instHSMul ℝ (Space d) (WithLp.instSMul exponent ℝ (Fin d → ℝ))) + (Real.sqrt (d/2:ℕ))⁻¹ (WithLp.toLp exponent (fun index : Fin d => + if lower : index.val < d/2 then + @WithLp.ofLp exponent (Fin (d/2) → ℝ) u ⟨index.val, lower⟩ + else if upper : index.val < 2*(d/2) then + Real.sqrt (1-(@WithLp.ofLp exponent (Fin (d/2) → ℝ) u + ⟨index.val-d/2, cube_second_coordinate_lt d index lower upper⟩)^2) + else 0)) + +def CubeEmbedding (d : ℕ) (u : Cube d) : Space d := cubeRaw d u.val + +def CubeBall (d : ℕ) (z : Space (d/2)) (r : ℝ) : Set (Cube d) := + {u | dist u.val z ≤ Real.sqrt (d/2:ℕ) * r} + +def CubeLocal {d : ℕ} (f : Cube d → ℝ≥0∞) (L : ℝ) : Prop := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let cubeMeasurable := @Subtype.instMeasurableSpace (Space (d/2)) (CubeSet (d/2)) + (@WithLp.measurableSpace exponent (Fin (d/2) → ℝ) inferInstance) + ∀ z : Space (d/2), ∀ r : ℝ, 0 < r → + @MeasureTheory.lintegral (Cube d) cubeMeasurable + (@Measure.restrict (Cube d) cubeMeasurable (CubeLaw d) (CubeBall d z r)) f ≤ + ENNReal.ofReal (L * r^( + (@OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1)))) * (d/2:ℕ) / + (@OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2)))) : ℝ)) + +/-- Every coordinate of the paired cube has square at most one quarter. -/ + +lemma cube_coordinate_square_le {d : ℕ} (u : Cube d) (i : Fin (d/2)) : u.val i^2 ≤ 1/4 := by + have hu : -(1/2 : ℝ) ≤ u.val i ∧ u.val i ≤ 1/2 := abs_le.mp (u.property i) + nlinarith [sq_nonneg (u.val i-1/2), sq_nonneg (u.val i+1/2)] + +lemma sum_fin_split {n d : ℕ} (hn : n ≤ d) (f : Fin d → ℝ) : + (∑ i, f i) = (∑ i : Fin n, f ⟨i.val,by omega⟩) + + ∑ i : Fin (d-n), f ⟨n+i.val,by omega⟩ := by + let e : Fin (n+(d-n)) ≃ Fin d := finCongr (Nat.add_sub_of_le hn) + calc + _ = ∑ i : Fin (n+(d-n)), f (e i) := (Equiv.sum_comp e f).symm + _ = _ := by rw [Fin.sum_univ_add]; rfl + +def cubeCoords (d : ℕ) (u : Space (d/2)) : Space d := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + WithLp.toLp exponent (fun index : Fin d => + if lower : index.val < d/2 then + @WithLp.ofLp exponent (Fin (d/2) → ℝ) u ⟨index.val, lower⟩ + else if upper : index.val < 2*(d/2) then + Real.sqrt (1-(@WithLp.ofLp exponent (Fin (d/2) → ℝ) u + ⟨index.val-d/2, cube_second_coordinate_lt d index lower upper⟩)^2) + else 0) + +lemma cubeCoords_first (d : ℕ) (u : Space (d/2)) (i : Fin (d/2)) : + cubeCoords d u ⟨i.val,by omega⟩ = u i := by + simp [cubeCoords, i.isLt] + +lemma cubeCoords_second (d : ℕ) (u : Space (d/2)) (i : Fin (d/2)) : + cubeCoords d u ⟨d/2+i.val,by omega⟩ = Real.sqrt (1-u i^2) := by + simp [cubeCoords, show ¬d/2+i.val < d/2 by omega, show d/2+i.val < 2*(d/2) by omega] + +lemma cubeCoords_tail (d : ℕ) (u : Space (d/2)) (i : Fin d) (hi : 2*(d/2) ≤ i.val) : + cubeCoords d u i = 0 := by + simp [cubeCoords, show ¬i.val < d/2 by omega, show ¬i.val < 2*(d/2) by omega] + +lemma cubeCoords_sum (d : ℕ) (u : Space (d/2)) (f : ℝ → ℝ) (hf : f 0 = 0) : + (∑ i : Fin d, f (cubeCoords d u i)) = + (∑ i : Fin (d/2), f (u i)) + ∑ i : Fin (d/2), f (Real.sqrt (1-u i^2)) := by + rw [sum_fin_split (show d/2 ≤ d by omega)] + simp_rw [cubeCoords_first] + rw [sum_fin_split (show d/2 ≤ d-d/2 by omega)] + congr 1 + have h1 : (∑ i : Fin (d/2), f (cubeCoords d u ⟨d/2+i.val,by omega⟩)) = + ∑ i : Fin (d/2), f (Real.sqrt (1-u i^2)) := by simp_rw [cubeCoords_second] + rw [h1] + have h0 : (∑ i : Fin (d-d/2-d/2), f (cubeCoords d u ⟨d/2+(d/2+i.val),by omega⟩)) = 0 := by + apply Finset.sum_eq_zero + intro i _ + rw [cubeCoords_tail d u _ (show 2*(d/2) ≤ d/2+(d/2+i.val) by omega), hf] + rw [h0, add_zero] + +lemma cubeEmbedding_norm {d : ℕ} (hd : 2 ≤ d) (u : Cube d) : + @Norm.norm (Space d) (PiLp.instNorm + (p := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (β := fun _ : Fin d => ℝ)) + (CubeEmbedding d u) = (1 : ℝ) := by + have hs : ‖cubeCoords d u.val‖^2 = (d/2:ℕ) := by + rw [EuclideanSpace.real_norm_sq_eq, cubeCoords_sum d u.val (fun x => x^2) (by norm_num)] + have he (i : Fin (d/2)) : Real.sqrt (1-u.val i^2)^2 = 1-u.val i^2 := + Real.sq_sqrt (by have := cube_coordinate_square_le u i; linarith) + simp_rw [he] + rw [← Finset.sum_add_distrib] + simp + have hn : 0 < (d/2:ℕ) := by omega + have hr : 0 < Real.sqrt (d/2:ℕ) := Real.sqrt_pos.2 (by exact_mod_cast hn) + have hnorm : ‖cubeCoords d u.val‖ = Real.sqrt (d/2:ℕ) := by + rw [← Real.sqrt_sq (norm_nonneg _), hs] + change ‖(Real.sqrt (d/2:ℕ))⁻¹ • cubeCoords d u.val‖ = 1 + rw [norm_smul, Real.norm_eq_abs, abs_inv, abs_of_pos hr, hnorm, inv_mul_cancel₀ hr.ne'] + +def CubeSphere {d : ℕ} (hd : 2 ≤ d) (u : Cube d) : UnitSphere d := + ⟨CubeEmbedding d u, by simpa [Metric.mem_sphere, dist_zero_right] using cubeEmbedding_norm hd u⟩ + +def AmbientGramStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let three : ℝ := @OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1))) + let four : ℝ := @OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + (∀ (d m p : ℕ), + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + letI : PseudoMetricSpace (Space d) := + PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ) + letI : AddCommGroup (Space d) := WithLp.instAddCommGroup exponent (Fin d → ℝ) + letI : Module ℝ (Space d) := WithLp.instModule (p := exponent) (K := ℝ) (V := Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β R H : ℝ, (m : ℝ) + (p : ℝ) - two < β → 0 < R → 0 < H → + ∀ (μ : Measure (Space d)), IsFiniteMeasure μ → + ∀ z : Space d, μ.support ⊆ Metric.closedBall z R → + AmbientBallBound μ H β → + (∀ (j : ℕ), j ≤ p-2 → ∀ L : AffineSubspace ℝ (Space d), + Nonempty L → Module.finrank ℝ L.direction = j → + (∀ t : ℝ, 0 < t → t ≤ R → + μ {s | Metric.infDist s L ≤ t} ≤ + ENNReal.ofReal (three^j * two^β * H * R^j * t^(β-(j:ℝ)))) ∧ + (∫⁻ s, (ENNReal.ofReal (Metric.infDist s L)) ^ (-(m:ℝ)) ∂μ) ≤ + ENNReal.ofReal (J β m j * H * R^(β-(m:ℝ)))) ∧ + (∀ᵐ v : Space d × (Fin (p-1) → Space d) + ∂μ.prod (Measure.pi (fun _ : Fin (p-1) => μ)), + LinearIndependent ℝ (fun i => v.2 i - v.1)) ∧ + (∫⁻ v : Space d × (Fin (p-1) → Space d), InverseGram m v + ∂μ.prod (Measure.pi (fun _ : Fin (p-1) => μ))) ≤ + ENNReal.ofReal (H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)) * + ∏ j : Fin (p-1), J β m j)) ∧ + (∃ C : ℝ, 1 ≤ C ∧ ∀ (d m p : ℕ), 16 ≤ d → p = d/8 → + 1 ≤ m → m ≤ p → ∀ β : ℝ, ((d:ℝ)-1)/two ≤ β → β ≤ (d:ℝ)/two → + (∀ j : ℕ, j ≤ p-2 → + ((d:ℝ)-1)/two - two*(p:ℝ) + two ≤ β-(j:ℝ)-(m:ℝ) ∧ + (d:ℝ)/four + three/two ≤ ((d:ℝ)-1)/two - two*(p:ℝ) + two ∧ + J β m j ≤ C^d) ∧ + (∀ H R : ℝ, 0 < H → 0 < R → + H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)) * (∏ j : Fin (p-1), J β m j) ≤ + C^(d*(p-1)) * H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)))) + +def FiniteDensityStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + ∃ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F ∧ (∀ x, 0 ≤ F x) ∧ + (MatrixLabelReference d m).withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m ∧ + (∀ᵐ x ∂MatrixLabelReference d m, x ∉ ProjectedEllipsoid z R → F x = 0) ∧ + eLpNorm F (p : ℝ≥0∞) (MatrixLabelReference d m) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R) + +def MeasurableTestStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + let ν := MatrixLabelReference d m + let η := ProjectionLaw μ m + let B := ENNReal.ofReal (ProjectionNormScale m p H β R) + let α := 1-1/(p:ℝ) + (∀ E, MeasurableSet E → ν E ≠ ∞ → η E ≤ B * (ν E)^α) ∧ + η ≪ ν ∧ + ∃ ηc : Measure (NullMeasurableSpace ((Fin m → Space d) × (Fin m → ℝ)) ν), + (∀ E, NullMeasurableSet E ν → ηc E = η E) ∧ + (∀ E, NullMeasurableSet E ν → ν.completion E ≠ ∞ → + ηc E ≤ B * (ν.completion E)^α) ∧ + (∀ φ : NullMeasurableSpace ((Fin m → Space d) × (Fin m → ℝ)) ν → ℝ≥0∞, + Measurable φ → (∀ x, φ x ≤ 1) → + (∫⁻ x, φ x ∂ηc) ≤ B * (∫⁻ x in ProjectedEllipsoid z R, φ x ∂ν.completion)^α) + +def JointL1Statement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 2 ≤ d → 1 ≤ m → m < d → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + μ ≪ UniformSphere d → + ∀ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F → (∀ x, 0 ≤ F x) → + (MatrixLabelReference d m).withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m → + Tendsto (fun δ => eLpNorm (fun Ay => GaussianRegularization μ m δ Ay - F Ay) + 1 (MatrixLabelReference d m)) (𝓝[Set.Ioi 0] 0) (𝓝 0) ∧ + eLpNorm F (p : ℝ≥0∞) (MatrixLabelReference d m) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R) + +def RadialMixtureRepresentation (m : ℕ) : Prop := + ∀ δ : ℝ, 0 < δ → + (∀ r : ℝ, 0 < r → 0 ≤ RadialMixture m δ r) ∧ + Measurable (RadialMixture m δ) ∧ + (∫ r in Set.Ioi 0, RadialMixture m δ r) = 1 ∧ + (∀ y : Space m, GaussianKernel m δ y = + ∫ r in Set.Ioi ‖y‖, RadialMixture m δ r / (UnitBallVolume m * r^m)) + +def FullRankDensityFormula {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) : Prop := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ A : Fin m → Space d, + @LinearIndependent (Fin m) ℝ (Space d) A Real.commRing.toSemiring + (WithLp.instAddCommGroup exponent (Fin d → ℝ)).toAddCommMonoid + (WithLp.instModule (p := exponent) (K := ℝ) (V := Fin d → ℝ)) → + (volume : Measure (Fin m → ℝ)).withDensity + (fun y => ENNReal.ofReal (PointwiseDensity μ m (A,y))) = + @Measure.map (Space d) (Fin m → ℝ) + (WithLp.measurableSpace exponent (Fin d → ℝ)) inferInstance + (fun signal => fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + signal (A index)) μ + +def PointwiseDensityProperties {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m p : ℕ) (H β R : ℝ) : Prop := + letI : MeasurableSpace (Space d) := WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ) + let reference : Measure ((Fin m → Space d) × (Fin m → ℝ)) := MatrixLabelReference d m + RadialMixtureRepresentation m ∧ + (∀ x, 0 ≤ PointwiseDensity μ m x) ∧ + Measurable (PointwiseDensity μ m) ∧ + FullRankDensityFormula μ m ∧ + reference.withDensity (fun x => ENNReal.ofReal (PointwiseDensity μ m x)) = + ProjectionLaw μ m ∧ + (∀ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F → (∀ x, 0 ≤ F x) → + reference.withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m → PointwiseDensity μ m =ᵐ[reference] F) ∧ + (∫⁻ x, ENNReal.ofReal (PointwiseDensity μ m x)^p ∂reference) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R)^p + +def PointwiseDensityStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, 2 ≤ d → 1 ≤ m → m < d → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, + ∀ μ : @Measure (Space d) (WithLp.measurableSpace exponent (Fin d → ℝ)), + IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + μ ≪ UniformSphere d → PointwiseDensityProperties μ m p H β R + +def CoefficientStepStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∃ C : ℝ, 1 ≤ C ∧ ∀ d m N : ℕ, 16 ≤ d → + 1 ≤ m → m ≤ d/8 → 1 ≤ N → + ∀ α H : ℝ, ((d:ℝ)-1)/two ≤ α → α ≤ (d:ℝ)/two → 0 < H → + ∀ h : Fin N → Sphere d → ℝ≥0∞, + (∀ w, Measurable (h w)) → (∀ w s, h w s ≤ 1) → + (∀ w, SphereBallBound (h w) H α) → + ∀ g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞, + (∀ w, Measurable (g w)) → (∀ x, ∑ w, g w x ≤ 1) → + SphereBallBound (SphereBlock h g) (C^d * (N:ℝ)^(1/((d/8:ℕ):ℝ)) * H) α + +def CubeBlockStatement : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d k N : ℕ, 16 ≤ d → 1 ≤ k → k ≤ (d/2)/4 → 1 ≤ N → + ∀ L : ℝ, 0 ≤ L → ∀ f : Fin N → Cube d → ℝ≥0∞, + (∀ v, Measurable (f v)) → (∀ v u, f v u ≤ 1) → (∀ v, CubeLocal (f v) L) → + ∀ g : Fin N → ((Fin k → Space d) × (Fin k → ℝ)) → ℝ≥0∞, + (∀ v, Measurable (g v)) → (∀ x, ∑ v, g v x ≤ 1) → + CubeLocal (WeightedBlock (CubeEmbedding d) f g) + (C^(d/2) * (N:ℝ)^(1/(((d/2)/4:ℕ):ℝ)) * L) + +end MemoryPrecision + +namespace MemoryPrecision.Kernel +namespace Policy + +def ModelAdmissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) : Prop := + ∀ π : Measure (Sphere d), IsProbabilityMeasure π → Admissible K ρ π + +end Policy + +open MemoryPrecision NoiselessRegression Policy + +def CubePrior {d : ℕ} (hd : 2 ≤ d) : Measure (MemoryPrecision.Kernel.Sphere d) := + (CubeLaw d).map (CubeSphere hd) + +def BlockCount (T p : ℕ) : ℕ := ⌈(T:ℝ)/(p:ℝ)⌉₊ + +def SourceEllipsoidStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let four : ℝ := @OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2))) + let ten : ℝ := @OfNat.ofNat ℝ 10 (@instOfNatAtLeastTwo ℝ 10 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 8))) + ∃ C C₀ : ℝ, 1 ≤ C ∧ 1 ≤ C₀ ∧ + ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, 0 < ε → ε ≤ 1/ten → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ K : Ω → Policy d M T, Policy.Admissible K ρ (UniformSphere d) → + Policy.Success K ρ (UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + (four^d * ε^(((d:ℝ)-1)/two) * + (C^d * (((d/8+2)*2^M : ℕ):ℝ)^(1/((d/8:ℕ):ℝ)))^(BlockCount T (d/8)))) ∧ + Policy.ChordSuccess K ρ (UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + (C₀^d * ε^((d:ℝ)/two-1) * + (C^d * (((2*(d/8)+4)*2^M : ℕ):ℝ)^(1/((d/8:ℕ):ℝ)))^(BlockCount T (d/8)))) ∧ + {x : Sphere d × Sphere d | Real.arccos (@inner ℝ (Vector d) + (@InnerProductSpace.toInner ℝ (Vector d) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + x.2.val x.1.val) ≤ ε} ⊆ + {x | @Dist.dist (Vector d) + (PiLp.instDist (p := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (α := fun _ : Fin d => ℝ)) x.2.val x.1.val ≤ ε} + +lemma cubePrior_dimension {d₀ d : ℕ} (hd₀ : 16 ≤ d₀) (hd : d₀ ≤ d) : 2 ≤ d := + Nat.le_trans (by decide : 2 ≤ 16) (Nat.le_trans hd₀ hd) + +end MemoryPrecision.Kernel + +namespace MemoryPrecision + +theorem main : + AmbientGramStatement ∧ + FiniteDensityStatement ∧ + MeasurableTestStatement ∧ + JointL1Statement ∧ + PointwiseDensityStatement ∧ + CoefficientStepStatement ∧ + Kernel.SourceEllipsoidStatement.{u} ∧ + CubeBlockStatement ∧ + (∃ D : ℝ, Real.exp 1 ≤ D ∧ ∃ d₀ : ℕ, ∃ hd₀ : 16 ≤ d₀, ∃ c : ℝ, 0 < c ∧ + ∀ d M T : ℕ, ∀ hd : d₀ ≤ d, M ≤ d^2 → ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ K : Ω → MemoryPrecision.Kernel.Policy d M T, + MemoryPrecision.Kernel.Policy.ModelAdmissible.{u} K ρ → + MemoryPrecision.Kernel.Policy.Success K ρ + (MemoryPrecision.Kernel.CubePrior (MemoryPrecision.Kernel.cubePrior_dimension hd₀ hd)) ε ≤ + min 1 (ENNReal.ofReal + (D^((d/2)*(MemoryPrecision.Kernel.BlockCount T ((d/2)/4)+1)) * ε^((d/2:ℕ)/4:ℝ))) ∧ + ((∀ signal : MemoryPrecision.Kernel.Sphere d, + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) / + (@OfNat.ofNat ℝ≥0∞ 3 + (@instOfNatAtLeastTwo ℝ≥0∞ 3 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) ≤ + (∫⁻ observation, + MemoryPrecision.Kernel.Policy.experiment K + (MemoryPrecision.Kernel.Policy.angleTest ε) (signal, observation) + ∂ρ.prod (MemoryPrecision.Kernel.RowLaw d T))) → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ))) ∧ + (∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, 0 < d₀ ∧ + ∀ d M T : ℕ, d₀ ≤ d → ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → MemoryPrecision.Kernel.Policy d M T, + MemoryPrecision.Kernel.Policy.Admissible L ρ (MemoryPrecision.Kernel.UniformSphere d) → + MemoryPrecision.Kernel.Policy.Success L ρ (MemoryPrecision.Kernel.UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + ((2*ε*Real.exp (C*(1+(M:ℝ)/(d:ℝ)^2)*(MemoryPrecision.Kernel.BlockCount T ((d-1)/8):ℝ)))^(((d:ℝ)-1)/2)))) := by + sorry + +end MemoryPrecision + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MemoryPrecision.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MemoryPrecision.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/memory-precision/solution/closure.txt b/tasks/memory-precision/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1e10ecfe31f8ad9bf6cc39a64508b7eba5318540 --- /dev/null +++ b/tasks/memory-precision/solution/closure.txt @@ -0,0 +1,88 @@ +OAI.Probability.GaussianRegression.AffineTubes +OAI.Probability.GaussianRegression.Blocks +OAI.Probability.GaussianRegression.Caps +OAI.Probability.GaussianRegression.Execution +OAI.Probability.GaussianRegression.GaussianKernel +OAI.Probability.GaussianRegression.Gram +OAI.Probability.GaussianRegression.InverseMoments +OAI.Probability.GaussianRegression.Main +OAI.Probability.GaussianRegression.Model +OAI.Probability.GaussianRegression.Nets +OAI.Probability.GaussianRegression.Observation +OAI.Probability.GaussianRegression.Precision +OAI.Probability.GaussianRegression.Projection +OAI.Probability.GaussianRegression.ReplicaMoments +OAI.Probability.GaussianRegression.Rotational +OAI.Probability.GaussianRegression.Smoothing +OAI.Probability.GaussianRegression.Sphere +OAI.Probability.GaussianRegression.Stream +OAI.Probability.GaussianRegression.Success +OAI.Probability.GaussianRegression.Support +OAI.Probability.GaussianRegression.Transfer +OAI.Probability.MemoryPrecision.AmbientGram +OAI.Probability.MemoryPrecision.BallAverages +OAI.Probability.MemoryPrecision.CoefficientStep +OAI.Probability.MemoryPrecision.CubeArithmetic +OAI.Probability.MemoryPrecision.CubeBlock +OAI.Probability.MemoryPrecision.CubeCaps +OAI.Probability.MemoryPrecision.CubeContinuation +OAI.Probability.MemoryPrecision.CubeExperiment +OAI.Probability.MemoryPrecision.CubeGeometry +OAI.Probability.MemoryPrecision.CubeSuccess +OAI.Probability.MemoryPrecision.DensityPassage +OAI.Probability.MemoryPrecision.DensityUniqueness +OAI.Probability.MemoryPrecision.EllipsoidSuccess +OAI.Probability.MemoryPrecision.FiberDensity +OAI.Probability.MemoryPrecision.FiniteDensity +OAI.Probability.MemoryPrecision.GaussianConvolution +OAI.Probability.MemoryPrecision.JointL1 +OAI.Probability.MemoryPrecision.KernelAdmissibility +OAI.Probability.MemoryPrecision.KernelCaps +OAI.Probability.MemoryPrecision.KernelCube +OAI.Probability.MemoryPrecision.KernelEllipsoid +OAI.Probability.MemoryPrecision.KernelEvaluation +OAI.Probability.MemoryPrecision.KernelIntegral +OAI.Probability.MemoryPrecision.KernelModel +OAI.Probability.MemoryPrecision.KernelSphere +OAI.Probability.MemoryPrecision.KernelStream +OAI.Probability.MemoryPrecision.KernelVersion +OAI.Probability.MemoryPrecision.LabelTranslations +OAI.Probability.MemoryPrecision.Main +OAI.Probability.MemoryPrecision.MeasurableTests +OAI.Probability.MemoryPrecision.PointwiseDensity +OAI.Probability.MemoryPrecision.PointwiseMain +OAI.Probability.MemoryPrecision.Precision +OAI.Probability.MemoryPrecision.PriorMeasurability +OAI.Probability.MemoryPrecision.RadialMixture +OAI.Probability.MemoryPrecision.RealContinuation +OAI.Probability.MemoryPrecision.RealStream +OAI.Probability.MemoryPrecision.Reflection +OAI.Probability.MemoryPrecision.SeedAverage +OAI.Probability.MemoryPrecision.SharpGaussian +OAI.Probability.MemoryPrecision.SphereCaps +OAI.Probability.MemoryPrecision.SphericalProjection +OAI.Probability.MemoryPrecision.StochasticContinuation +OAI.Probability.MemoryPrecision.StochasticMass +OAI.Probability.MemoryPrecision.StreamArithmetic +OAI.Probability.MemoryPrecision.StreamZero +OAI.Probability.MemoryPrecision.SuccessArithmetic +OAI.Probability.MemoryPrecision.WeightedImage +OAI.Probability.MemoryPrecision.WeightedSelection +OAI.Probability.MemoryPrecision.ZeroHorizon +OAI.Probability.ProjectionMoments.AllRadii +OAI.Probability.ProjectionMoments.BallMoments +OAI.Probability.ProjectionMoments.BorelRules +OAI.Probability.ProjectionMoments.CapDomination +OAI.Probability.ProjectionMoments.CapDuality +OAI.Probability.ProjectionMoments.CapTests +OAI.Probability.ProjectionMoments.Caps +OAI.Probability.ProjectionMoments.FrameMoments +OAI.Probability.ProjectionMoments.Frames +OAI.Probability.ProjectionMoments.GaussianDensity +OAI.Probability.ProjectionMoments.Graph +OAI.Probability.ProjectionMoments.Model +OAI.Probability.ProjectionMoments.Polar +OAI.Probability.ProjectionMoments.RieszPotential +OAI.Probability.ProjectionMoments.SphereDensity +OAI.Probability.ProjectionMoments.Stopping +OAI.Probability.ProjectionMoments.WeightedCover diff --git a/tasks/memory-precision/solution/reference.py b/tasks/memory-precision/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/memory-precision/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/memory-precision/solution/solve.sh b/tasks/memory-precision/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6479703b4644c0e47ac592ddbc2c35bfe5fa0247 --- /dev/null +++ b/tasks/memory-precision/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MemoryPrecision, i.e. module OAI.Probability.MemoryPrecision.Main and the +# 88 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.MemoryPrecision.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MemoryPrecision" diff --git a/tasks/memory-precision/task.toml b/tasks/memory-precision/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f696ae639dc54b9699a92644d7c3b870ee92fd06 --- /dev/null +++ b/tasks/memory-precision/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/memory-precision" +version = "1.0.0" +description = "Prove MemoryPrecision (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MemoryPrecision.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MemoryPrecision" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.MemoryPrecision.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.MemoryPrecision.Main" +reference_modules = 88 +reference_lean_bytes = 780345 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 957 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12402 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/memory-precision/tests/Challenge.lean b/tasks/memory-precision/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9cc787bf862637dcc784ce66cb1efd68f5a85ceb --- /dev/null +++ b/tasks/memory-precision/tests/Challenge.lean @@ -0,0 +1,812 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter EuclideanGeometry +open scoped ENNReal NNReal RealInnerProductSpace Topology Pointwise + +noncomputable section +universe u v + +namespace MemoryPrecision.Kernel + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev State (M : ℕ) := Fin (2^M) + +abbrev Action (M : ℕ) := Bool × State M + +abbrev Observations (d k : ℕ) := Fin k → (Vector d × ℝ) + +abbrev Rows (d k : ℕ) := Fin k → Vector d + +def UniformSphere (d : ℕ) : Measure (Sphere d) := + let euclideanGroup : NormedAddCommGroup (Vector d) := + PiLp.normedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ) + let euclideanInner := PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ) + let σ := @Measure.toSphere (Vector d) euclideanGroup + (@InnerProductSpace.toNormedSpace ℝ (Vector d) _ + euclideanGroup.toSeminormedAddCommGroup euclideanInner) inferInstance + (@volume (Vector d) (@measureSpaceOfInnerProductSpace (Vector d) + euclideanGroup euclideanInner inferInstance inferInstance inferInstance)) + (σ Set.univ)⁻¹ • σ + +def RowLaw (d k : ℕ) : @Measure (Rows d k) + (@MeasurableSpace.pi (Fin k) (fun _ => Vector d) + (fun _ => @WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (Fin d → ℝ) inferInstance)) := + let euclideanMeasurable := @WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (Fin d → ℝ) inferInstance + @Measure.pi (Fin k) (fun _ => Vector d) inferInstance (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Vector d) + (PiLp.normedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) inferInstance euclideanMeasurable) + +def ObservationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Policy (d M T : ℕ) where + initial : Action M → ℝ≥0∞ + initial_sum : ∑ a, initial a = 1 + transition : ℕ → State M → (Vector d × ℝ) → Action M → ℝ≥0∞ + transition_sum : ∀ t j obs, ∑ a, transition t j obs a = 1 + output : ℕ → State M → Measure (Sphere d) + output_probability : ∀ t j, IsProbabilityMeasure (output t j) + +namespace Policy + +def Completed {d M T : ℕ} (K : Policy d M T) : Prop := + ∀ t j a, AEMeasurable (fun obs => K.transition t j obs a) (ObservationReference d) + +def eval {d M T : ℕ} {X : Type*} (K : Policy d M T) + (w : ℕ → State M → X → ℝ≥0∞) (n : ℕ) : + (k : ℕ) → State M → X → Observations d k → ℝ≥0∞ + | 0, j, s, _ => w n j s + | k+1, j, s, obs => ∑ a : Action M, K.transition (n+1) j (obs 0) a * + if a.1 then w (n+1) a.2 s else K.eval w (n+1) k a.2 s (Fin.tail obs) + +def pathValue {d M T : ℕ} {X : Type*} (K : Policy d M T) + (w : ℕ → State M → X → ℝ≥0∞) (s : X) (obs : Observations d T) : ℝ≥0∞ := + ∑ a : Action M, K.initial a * if a.1 then w 0 a.2 s else K.eval w 0 T a.2 s obs + +def records {d T : ℕ} (s : Sphere d) (A : Rows d T) : Observations d T := + fun index => (A index, @inner ℝ (EuclideanSpace ℝ (Fin d)) + (@InnerProductSpace.toInner ℝ (EuclideanSpace ℝ (Fin d)) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) s.val (A index)) + +def outputTest {d M T : ℕ} (K : Policy d M T) (f : Sphere d × Sphere d → ℝ≥0∞) + (t : ℕ) (j : State M) (s : Sphere d) : ℝ≥0∞ := + ∫⁻ v, f (s,v) ∂K.output t j + +def angleTest {d : ℕ} (ε : ℝ) + (point : MemoryPrecision.Kernel.Sphere d × MemoryPrecision.Kernel.Sphere d) : ℝ≥0∞ := + @ite ℝ≥0∞ (Real.arccos (@inner ℝ (EuclideanSpace ℝ (Fin d)) + (@InnerProductSpace.toInner ℝ (EuclideanSpace ℝ (Fin d)) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + point.2.val point.1.val) ≤ ε) (Classical.propDecidable _) 1 0 + +def chordTest {d : ℕ} (ε : ℝ) (x : Sphere d × Sphere d) : ℝ≥0∞ := + {x : Sphere d × Sphere d | dist x.2.val x.1.val ≤ ε}.indicator (fun _ => 1) x + +def experiment {d M T : ℕ} {Ω : Type u} (K : Ω → Policy d M T) + (f : Sphere d × Sphere d → ℝ≥0∞) (z : Sphere d × (Ω × Rows d T)) : ℝ≥0∞ := + (K z.2.1).pathValue ((K z.2.1).outputTest f) z.1 (records z.1 z.2.2) + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) : Prop where + completed : ∀ᵐ ω ∂ρ, (K ω).Completed + experiment : ∀ f : Sphere d × Sphere d → ℝ≥0∞, Measurable f → + (∀ x, f x ≤ 1) → AEMeasurable (experiment K f) (π.prod (ρ.prod (RowLaw d T))) + +def Success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z, experiment K (angleTest ε) z ∂π.prod (ρ.prod (RowLaw d T)) + +def ChordSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) (π : Measure (Sphere d)) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z, experiment K (chordTest ε) z ∂π.prod (ρ.prod (RowLaw d T)) + +end Policy +end MemoryPrecision.Kernel + +namespace NoiselessRegression +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +end NoiselessRegression + +namespace MemoryPrecision +open NoiselessRegression + +abbrev Space (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def J (β : ℝ) (m j : ℕ) : ℝ := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let three : ℝ := @OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1))) + 1 + three^j * two^β * (m : ℝ) / (β - (j : ℝ) - (m : ℝ)) + +def AmbientBallBound {d : ℕ} (μ : Measure (Space d)) (H β : ℝ) : Prop := + ∀ x : Space d, ∀ r : ℝ, 0 < r → + μ (Metric.closedBall x r) ≤ ENNReal.ofReal (H * r^β) + +def InverseGram {d p : ℕ} (m : ℕ) (v : Space d × (Fin (p-1) → Space d)) : ℝ≥0∞ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + letI : AddCommGroup (Space d) := WithLp.instAddCommGroup exponent (Fin d → ℝ) + letI : Inner ℝ (Space d) := @InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + ENNReal.ofReal ((Real.sqrt (Matrix.gram ℝ (fun i => v.2 i - v.1)).det)⁻¹ ^ m) + +def MatrixLabelReference (d m : ℕ) : @Measure ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod (Fin m → Space d) (Fin m → ℝ) + (@MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + inferInstance) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := WithLp.measurableSpace exponent (Fin d → ℝ) + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + let rowLaw := @Measure.pi (Fin m) (fun _ => Space d) inferInstance + (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + inferInstance euclideanMeasurable) + @Measure.prod _ _ rowMeasurable inferInstance rowLaw volume + +def ProjectionLaw {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) : @Measure ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod (Fin m → Space d) (Fin m → ℝ) + (@MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + inferInstance) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := WithLp.measurableSpace exponent (Fin d → ℝ) + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + let rowLaw := @Measure.pi (Fin m) (fun _ => Space d) inferInstance + (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + inferInstance euclideanMeasurable) + @Measure.map ((Fin m → Space d) × Space d) ((Fin m → Space d) × (Fin m → ℝ)) + (@MeasurableSpace.prod _ _ rowMeasurable euclideanMeasurable) + (@MeasurableSpace.prod _ _ rowMeasurable inferInstance) + (fun pair => (pair.1, fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + pair.2 (pair.1 index))) + (@Measure.prod _ _ rowMeasurable euclideanMeasurable rowLaw μ) + +def ProjectedEllipsoid {d m : ℕ} (z : Space d) (R : ℝ) : + Set ((Fin m → Space d) × (Fin m → ℝ)) := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanInner := @InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + {pair | ∃ displacement ∈ @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.toLp exponent (fun _ => (0 : ℝ))) R, + pair.2 = fun index => @inner ℝ (Space d) euclideanInner z (pair.1 index) + + @inner ℝ (Space d) euclideanInner displacement (pair.1 index)} + +def ProjectionNormScale (m p : ℕ) (H β R : ℝ) : ℝ := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + (two * Real.pi) ^ (-(m : ℝ) * ((p : ℝ)-1) / (two*(p : ℝ))) * H * + R ^ (β - (m : ℝ)*(1-1/(p : ℝ))) * + (∏ j ∈ Finset.range (p-1), J β m j) ^ (1/(p : ℝ)) + +def UniformSphere (d : ℕ) : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ)) := + let euclideanMeasurable := WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ) + @Measure.map (Kernel.Sphere d) (Space d) + (MeasurableSpace.comap Subtype.val euclideanMeasurable) euclideanMeasurable + Subtype.val (Kernel.UniformSphere d) + +def GaussianRegularization {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) (δ : ℝ) + (Ay : (Fin m → Space d) × (Fin m → ℝ)) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + ∫ signal, ∏ index, gaussianPDFReal 0 ⟨δ^2, sq_nonneg δ⟩ + (Ay.2 index - @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + signal (Ay.1 index)) ∂μ + +def PointwiseDensity {d : ℕ} (μ : Measure (Space d)) (m : ℕ) + (x : (Fin m → Space d) × (Fin m → ℝ)) : ℝ := by + classical + exact if h : ∃ l : ℝ, Tendsto (fun i : ℕ => GaussianRegularization μ m (1/(i:ℝ)) x) + atTop (𝓝 l) then Classical.choose h else 0 + +lemma space_finiteDimensional (d : ℕ) : FiniteDimensional ℝ (Space d) := by + infer_instance + +def UnitBallVolume (m : ℕ) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanGroup := PiLp.normedAddCommGroup exponent (fun _ : Fin m => ℝ) + letI : MeasurableSpace (Space m) := WithLp.measurableSpace exponent (Fin m → ℝ) + let euclideanVolume := @volume (Space m) (@measureSpaceOfInnerProductSpace (Space m) + euclideanGroup (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin m => ℝ)) + (space_finiteDimensional m) inferInstance inferInstance) + (euclideanVolume (@Metric.ball (Space m) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin m => ℝ)) + (WithLp.toLp exponent (fun _ : Fin m => (0 : ℝ))) 1)).toReal + +def CoordinateUnit (m : ℕ) : Space m := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + WithLp.toLp exponent (fun j : Fin m => if (j:ℕ) = 0 then (1:ℝ) else 0) + +lemma gaussianVariance_nonneg (δ : ℝ) : 0 ≤ δ^2 := sq_nonneg δ + +def GaussianKernel (m : ℕ) (δ : ℝ) (y : Space m) : ℝ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∏ index, gaussianPDFReal 0 ⟨δ^2, gaussianVariance_nonneg δ⟩ + (@WithLp.ofLp exponent (Fin m → ℝ) y index) + +def RadialMixture (m : ℕ) (δ r : ℝ) : ℝ := + UnitBallVolume m * r^m * (r / δ^2) * GaussianKernel m δ (r • CoordinateUnit m) + +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Space d) 1 + +def SpherePrior (d : ℕ) : Measure (Sphere d) := + MemoryPrecision.Kernel.UniformSphere d + +def SphereBallBound {d : ℕ} (h : Sphere d → ℝ≥0∞) (H α : ℝ) : Prop := + ∀ z : Space d, ∀ r : ℝ, 0 < r → + (∫⁻ s in {s : Sphere d | dist s.val z ≤ r}, h s ∂SpherePrior d) ≤ + ENNReal.ofReal (H * r^α) + +section WeightedImage +variable {X : Type*} [MeasurableSpace X] {d m N : ℕ} + +def WeightedBlock (ι : X → Space d) (h : Fin N → X → ℝ≥0∞) + (g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞) (x : X) : ℝ≥0∞ := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let euclideanMeasurable := @WithLp.measurableSpace exponent (Fin d → ℝ) inferInstance + let rowMeasurable := @MeasurableSpace.pi (Fin m) (fun _ => Space d) + (fun _ => euclideanMeasurable) + @MeasureTheory.lintegral (Fin m → Space d) rowMeasurable + (@Measure.pi (Fin m) (fun _ => Space d) inferInstance (fun _ => euclideanMeasurable) + (fun _ => @stdGaussian (Space d) + (PiLp.normedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ)) + (space_finiteDimensional d) euclideanMeasurable)) + (fun rows => ∑ state, g state (rows, fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + (ι x) (rows index)) * h state x) + +end WeightedImage + +def SphereBlock {d m N : ℕ} (h : Fin N → Sphere d → ℝ≥0∞) + (g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞) + (s : Sphere d) : ℝ≥0∞ := + WeightedBlock Subtype.val h g s + +abbrev CubeSet (n : ℕ) : Set (EuclideanSpace ℝ (Fin n)) := + fun (point : EuclideanSpace ℝ (Fin n)) => ∀ index : Fin n, + @LE.le ℝ Real.instLE + (@abs ℝ Real.lattice Real.instAddGroup + (@WithLp.ofLp + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (Fin n → ℝ) point index)) + (@HDiv.hDiv ℝ ℝ ℝ (@instHDiv ℝ Real.instDivInvMonoid.toDiv) + (@OfNat.ofNat ℝ 1 (@One.toOfNat1 ℝ Real.instOne)) + (@OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))))) + +abbrev Cube (d : ℕ) := CubeSet (d/2) + +def CubeLaw (d : ℕ) : Measure (Cube d) := + (volume : Measure (Space (d/2))).comap Subtype.val + +lemma cube_second_coordinate_lt (d : ℕ) (index : Fin d) + (lower : ¬index.val < d/2) (upper : index.val < 2*(d/2)) : + index.val - d/2 < d/2 := by omega + +def cubeRaw (d : ℕ) (u : Space (d/2)) : Space d := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + @HSMul.hSMul ℝ (Space d) (Space d) + (@instHSMul ℝ (Space d) (WithLp.instSMul exponent ℝ (Fin d → ℝ))) + (Real.sqrt (d/2:ℕ))⁻¹ (WithLp.toLp exponent (fun index : Fin d => + if lower : index.val < d/2 then + @WithLp.ofLp exponent (Fin (d/2) → ℝ) u ⟨index.val, lower⟩ + else if upper : index.val < 2*(d/2) then + Real.sqrt (1-(@WithLp.ofLp exponent (Fin (d/2) → ℝ) u + ⟨index.val-d/2, cube_second_coordinate_lt d index lower upper⟩)^2) + else 0)) + +def CubeEmbedding (d : ℕ) (u : Cube d) : Space d := cubeRaw d u.val + +def CubeBall (d : ℕ) (z : Space (d/2)) (r : ℝ) : Set (Cube d) := + {u | dist u.val z ≤ Real.sqrt (d/2:ℕ) * r} + +def CubeLocal {d : ℕ} (f : Cube d → ℝ≥0∞) (L : ℝ) : Prop := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let cubeMeasurable := @Subtype.instMeasurableSpace (Space (d/2)) (CubeSet (d/2)) + (@WithLp.measurableSpace exponent (Fin (d/2) → ℝ) inferInstance) + ∀ z : Space (d/2), ∀ r : ℝ, 0 < r → + @MeasureTheory.lintegral (Cube d) cubeMeasurable + (@Measure.restrict (Cube d) cubeMeasurable (CubeLaw d) (CubeBall d z r)) f ≤ + ENNReal.ofReal (L * r^( + (@OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1)))) * (d/2:ℕ) / + (@OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2)))) : ℝ)) + +/-- Every coordinate of the paired cube has square at most one quarter. -/ + +lemma cube_coordinate_square_le {d : ℕ} (u : Cube d) (i : Fin (d/2)) : u.val i^2 ≤ 1/4 := by + have hu : -(1/2 : ℝ) ≤ u.val i ∧ u.val i ≤ 1/2 := abs_le.mp (u.property i) + nlinarith [sq_nonneg (u.val i-1/2), sq_nonneg (u.val i+1/2)] + +lemma sum_fin_split {n d : ℕ} (hn : n ≤ d) (f : Fin d → ℝ) : + (∑ i, f i) = (∑ i : Fin n, f ⟨i.val,by omega⟩) + + ∑ i : Fin (d-n), f ⟨n+i.val,by omega⟩ := by + let e : Fin (n+(d-n)) ≃ Fin d := finCongr (Nat.add_sub_of_le hn) + calc + _ = ∑ i : Fin (n+(d-n)), f (e i) := (Equiv.sum_comp e f).symm + _ = _ := by rw [Fin.sum_univ_add]; rfl + +def cubeCoords (d : ℕ) (u : Space (d/2)) : Space d := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + WithLp.toLp exponent (fun index : Fin d => + if lower : index.val < d/2 then + @WithLp.ofLp exponent (Fin (d/2) → ℝ) u ⟨index.val, lower⟩ + else if upper : index.val < 2*(d/2) then + Real.sqrt (1-(@WithLp.ofLp exponent (Fin (d/2) → ℝ) u + ⟨index.val-d/2, cube_second_coordinate_lt d index lower upper⟩)^2) + else 0) + +lemma cubeCoords_first (d : ℕ) (u : Space (d/2)) (i : Fin (d/2)) : + cubeCoords d u ⟨i.val,by omega⟩ = u i := by + simp [cubeCoords, i.isLt] + +lemma cubeCoords_second (d : ℕ) (u : Space (d/2)) (i : Fin (d/2)) : + cubeCoords d u ⟨d/2+i.val,by omega⟩ = Real.sqrt (1-u i^2) := by + simp [cubeCoords, show ¬d/2+i.val < d/2 by omega, show d/2+i.val < 2*(d/2) by omega] + +lemma cubeCoords_tail (d : ℕ) (u : Space (d/2)) (i : Fin d) (hi : 2*(d/2) ≤ i.val) : + cubeCoords d u i = 0 := by + simp [cubeCoords, show ¬i.val < d/2 by omega, show ¬i.val < 2*(d/2) by omega] + +lemma cubeCoords_sum (d : ℕ) (u : Space (d/2)) (f : ℝ → ℝ) (hf : f 0 = 0) : + (∑ i : Fin d, f (cubeCoords d u i)) = + (∑ i : Fin (d/2), f (u i)) + ∑ i : Fin (d/2), f (Real.sqrt (1-u i^2)) := by + rw [sum_fin_split (show d/2 ≤ d by omega)] + simp_rw [cubeCoords_first] + rw [sum_fin_split (show d/2 ≤ d-d/2 by omega)] + congr 1 + have h1 : (∑ i : Fin (d/2), f (cubeCoords d u ⟨d/2+i.val,by omega⟩)) = + ∑ i : Fin (d/2), f (Real.sqrt (1-u i^2)) := by simp_rw [cubeCoords_second] + rw [h1] + have h0 : (∑ i : Fin (d-d/2-d/2), f (cubeCoords d u ⟨d/2+(d/2+i.val),by omega⟩)) = 0 := by + apply Finset.sum_eq_zero + intro i _ + rw [cubeCoords_tail d u _ (show 2*(d/2) ≤ d/2+(d/2+i.val) by omega), hf] + rw [h0, add_zero] + +lemma cubeEmbedding_norm {d : ℕ} (hd : 2 ≤ d) (u : Cube d) : + @Norm.norm (Space d) (PiLp.instNorm + (p := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (β := fun _ : Fin d => ℝ)) + (CubeEmbedding d u) = (1 : ℝ) := by + have hs : ‖cubeCoords d u.val‖^2 = (d/2:ℕ) := by + rw [EuclideanSpace.real_norm_sq_eq, cubeCoords_sum d u.val (fun x => x^2) (by norm_num)] + have he (i : Fin (d/2)) : Real.sqrt (1-u.val i^2)^2 = 1-u.val i^2 := + Real.sq_sqrt (by have := cube_coordinate_square_le u i; linarith) + simp_rw [he] + rw [← Finset.sum_add_distrib] + simp + have hn : 0 < (d/2:ℕ) := by omega + have hr : 0 < Real.sqrt (d/2:ℕ) := Real.sqrt_pos.2 (by exact_mod_cast hn) + have hnorm : ‖cubeCoords d u.val‖ = Real.sqrt (d/2:ℕ) := by + rw [← Real.sqrt_sq (norm_nonneg _), hs] + change ‖(Real.sqrt (d/2:ℕ))⁻¹ • cubeCoords d u.val‖ = 1 + rw [norm_smul, Real.norm_eq_abs, abs_inv, abs_of_pos hr, hnorm, inv_mul_cancel₀ hr.ne'] + +def CubeSphere {d : ℕ} (hd : 2 ≤ d) (u : Cube d) : UnitSphere d := + ⟨CubeEmbedding d u, by simpa [Metric.mem_sphere, dist_zero_right] using cubeEmbedding_norm hd u⟩ + +def AmbientGramStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let three : ℝ := @OfNat.ofNat ℝ 3 (@instOfNatAtLeastTwo ℝ 3 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 1))) + let four : ℝ := @OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + (∀ (d m p : ℕ), + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + letI : PseudoMetricSpace (Space d) := + PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ) + letI : AddCommGroup (Space d) := WithLp.instAddCommGroup exponent (Fin d → ℝ) + letI : Module ℝ (Space d) := WithLp.instModule (p := exponent) (K := ℝ) (V := Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β R H : ℝ, (m : ℝ) + (p : ℝ) - two < β → 0 < R → 0 < H → + ∀ (μ : Measure (Space d)), IsFiniteMeasure μ → + ∀ z : Space d, μ.support ⊆ Metric.closedBall z R → + AmbientBallBound μ H β → + (∀ (j : ℕ), j ≤ p-2 → ∀ L : AffineSubspace ℝ (Space d), + Nonempty L → Module.finrank ℝ L.direction = j → + (∀ t : ℝ, 0 < t → t ≤ R → + μ {s | Metric.infDist s L ≤ t} ≤ + ENNReal.ofReal (three^j * two^β * H * R^j * t^(β-(j:ℝ)))) ∧ + (∫⁻ s, (ENNReal.ofReal (Metric.infDist s L)) ^ (-(m:ℝ)) ∂μ) ≤ + ENNReal.ofReal (J β m j * H * R^(β-(m:ℝ)))) ∧ + (∀ᵐ v : Space d × (Fin (p-1) → Space d) + ∂μ.prod (Measure.pi (fun _ : Fin (p-1) => μ)), + LinearIndependent ℝ (fun i => v.2 i - v.1)) ∧ + (∫⁻ v : Space d × (Fin (p-1) → Space d), InverseGram m v + ∂μ.prod (Measure.pi (fun _ : Fin (p-1) => μ))) ≤ + ENNReal.ofReal (H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)) * + ∏ j : Fin (p-1), J β m j)) ∧ + (∃ C : ℝ, 1 ≤ C ∧ ∀ (d m p : ℕ), 16 ≤ d → p = d/8 → + 1 ≤ m → m ≤ p → ∀ β : ℝ, ((d:ℝ)-1)/two ≤ β → β ≤ (d:ℝ)/two → + (∀ j : ℕ, j ≤ p-2 → + ((d:ℝ)-1)/two - two*(p:ℝ) + two ≤ β-(j:ℝ)-(m:ℝ) ∧ + (d:ℝ)/four + three/two ≤ ((d:ℝ)-1)/two - two*(p:ℝ) + two ∧ + J β m j ≤ C^d) ∧ + (∀ H R : ℝ, 0 < H → 0 < R → + H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)) * (∏ j : Fin (p-1), J β m j) ≤ + C^(d*(p-1)) * H^p * R^(β*(p:ℝ)-(m:ℝ)*(p-1:ℕ)))) + +def FiniteDensityStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + ∃ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F ∧ (∀ x, 0 ≤ F x) ∧ + (MatrixLabelReference d m).withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m ∧ + (∀ᵐ x ∂MatrixLabelReference d m, x ∉ ProjectedEllipsoid z R → F x = 0) ∧ + eLpNorm F (p : ℝ≥0∞) (MatrixLabelReference d m) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R) + +def MeasurableTestStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 1 ≤ d → 1 ≤ m → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + let ν := MatrixLabelReference d m + let η := ProjectionLaw μ m + let B := ENNReal.ofReal (ProjectionNormScale m p H β R) + let α := 1-1/(p:ℝ) + (∀ E, MeasurableSet E → ν E ≠ ∞ → η E ≤ B * (ν E)^α) ∧ + η ≪ ν ∧ + ∃ ηc : Measure (NullMeasurableSpace ((Fin m → Space d) × (Fin m → ℝ)) ν), + (∀ E, NullMeasurableSet E ν → ηc E = η E) ∧ + (∀ E, NullMeasurableSet E ν → ν.completion E ≠ ∞ → + ηc E ≤ B * (ν.completion E)^α) ∧ + (∀ φ : NullMeasurableSpace ((Fin m → Space d) × (Fin m → ℝ)) ν → ℝ≥0∞, + Measurable φ → (∀ x, φ x ≤ 1) → + (∫⁻ x, φ x ∂ηc) ≤ B * (∫⁻ x in ProjectedEllipsoid z R, φ x ∂ν.completion)^α) + +def JointL1Statement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, + letI : MeasurableSpace (Space d) := WithLp.measurableSpace exponent (Fin d → ℝ) + 2 ≤ d → 1 ≤ m → m < d → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, ∀ μ : Measure (Space d), IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + μ ≪ UniformSphere d → + ∀ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F → (∀ x, 0 ≤ F x) → + (MatrixLabelReference d m).withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m → + Tendsto (fun δ => eLpNorm (fun Ay => GaussianRegularization μ m δ Ay - F Ay) + 1 (MatrixLabelReference d m)) (𝓝[Set.Ioi 0] 0) (𝓝 0) ∧ + eLpNorm F (p : ℝ≥0∞) (MatrixLabelReference d m) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R) + +def RadialMixtureRepresentation (m : ℕ) : Prop := + ∀ δ : ℝ, 0 < δ → + (∀ r : ℝ, 0 < r → 0 ≤ RadialMixture m δ r) ∧ + Measurable (RadialMixture m δ) ∧ + (∫ r in Set.Ioi 0, RadialMixture m δ r) = 1 ∧ + (∀ y : Space m, GaussianKernel m δ y = + ∫ r in Set.Ioi ‖y‖, RadialMixture m δ r / (UnitBallVolume m * r^m)) + +def FullRankDensityFormula {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m : ℕ) : Prop := + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ A : Fin m → Space d, + @LinearIndependent (Fin m) ℝ (Space d) A Real.commRing.toSemiring + (WithLp.instAddCommGroup exponent (Fin d → ℝ)).toAddCommMonoid + (WithLp.instModule (p := exponent) (K := ℝ) (V := Fin d → ℝ)) → + (volume : Measure (Fin m → ℝ)).withDensity + (fun y => ENNReal.ofReal (PointwiseDensity μ m (A,y))) = + @Measure.map (Space d) (Fin m → ℝ) + (WithLp.measurableSpace exponent (Fin d → ℝ)) inferInstance + (fun signal => fun index => @inner ℝ (Space d) + (@InnerProductSpace.toInner ℝ (Space d) _ + (PiLp.seminormedAddCommGroup exponent (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + signal (A index)) μ + +def PointwiseDensityProperties {d : ℕ} + (μ : @Measure (Space d) + (WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ))) + (m p : ℕ) (H β R : ℝ) : Prop := + letI : MeasurableSpace (Space d) := WithLp.measurableSpace + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) (Fin d → ℝ) + let reference : Measure ((Fin m → Space d) × (Fin m → ℝ)) := MatrixLabelReference d m + RadialMixtureRepresentation m ∧ + (∀ x, 0 ≤ PointwiseDensity μ m x) ∧ + Measurable (PointwiseDensity μ m) ∧ + FullRankDensityFormula μ m ∧ + reference.withDensity (fun x => ENNReal.ofReal (PointwiseDensity μ m x)) = + ProjectionLaw μ m ∧ + (∀ F : ((Fin m → Space d) × (Fin m → ℝ)) → ℝ, + Measurable F → (∀ x, 0 ≤ F x) → + reference.withDensity (fun x => ENNReal.ofReal (F x)) = + ProjectionLaw μ m → PointwiseDensity μ m =ᵐ[reference] F) ∧ + (∫⁻ x, ENNReal.ofReal (PointwiseDensity μ m x)^p ∂reference) ≤ + ENNReal.ofReal (ProjectionNormScale m p H β R)^p + +def PointwiseDensityStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let exponent : ℝ≥0∞ := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∀ d m p : ℕ, 2 ≤ d → 1 ≤ m → m < d → 2 ≤ p → + ∀ β H R : ℝ, (m : ℝ)+(p : ℝ)-two < β → 0 < H → 0 < R → + ∀ z : Space d, + ∀ μ : @Measure (Space d) (WithLp.measurableSpace exponent (Fin d → ℝ)), + IsFiniteMeasure μ → + @Measure.support (Space d) + (PiLp.topologicalSpace (p := exponent) (β := fun _ : Fin d => ℝ)) + (WithLp.measurableSpace exponent (Fin d → ℝ)) μ ⊆ + @Metric.closedBall (Space d) + (PiLp.instPseudoMetricSpace (p := exponent) (β := fun _ : Fin d => ℝ)) z R → + AmbientBallBound μ H β → + μ ≪ UniformSphere d → PointwiseDensityProperties μ m p H β R + +def CoefficientStepStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + ∃ C : ℝ, 1 ≤ C ∧ ∀ d m N : ℕ, 16 ≤ d → + 1 ≤ m → m ≤ d/8 → 1 ≤ N → + ∀ α H : ℝ, ((d:ℝ)-1)/two ≤ α → α ≤ (d:ℝ)/two → 0 < H → + ∀ h : Fin N → Sphere d → ℝ≥0∞, + (∀ w, Measurable (h w)) → (∀ w s, h w s ≤ 1) → + (∀ w, SphereBallBound (h w) H α) → + ∀ g : Fin N → ((Fin m → Space d) × (Fin m → ℝ)) → ℝ≥0∞, + (∀ w, Measurable (g w)) → (∀ x, ∑ w, g w x ≤ 1) → + SphereBallBound (SphereBlock h g) (C^d * (N:ℝ)^(1/((d/8:ℕ):ℝ)) * H) α + +def CubeBlockStatement : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d k N : ℕ, 16 ≤ d → 1 ≤ k → k ≤ (d/2)/4 → 1 ≤ N → + ∀ L : ℝ, 0 ≤ L → ∀ f : Fin N → Cube d → ℝ≥0∞, + (∀ v, Measurable (f v)) → (∀ v u, f v u ≤ 1) → (∀ v, CubeLocal (f v) L) → + ∀ g : Fin N → ((Fin k → Space d) × (Fin k → ℝ)) → ℝ≥0∞, + (∀ v, Measurable (g v)) → (∀ x, ∑ v, g v x ≤ 1) → + CubeLocal (WeightedBlock (CubeEmbedding d) f g) + (C^(d/2) * (N:ℝ)^(1/(((d/2)/4:ℕ):ℝ)) * L) + +end MemoryPrecision + +namespace MemoryPrecision.Kernel +namespace Policy + +def ModelAdmissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (K : Ω → Policy d M T) (ρ : Measure Ω) : Prop := + ∀ π : Measure (Sphere d), IsProbabilityMeasure π → Admissible K ρ π + +end Policy + +open MemoryPrecision NoiselessRegression Policy + +def CubePrior {d : ℕ} (hd : 2 ≤ d) : Measure (MemoryPrecision.Kernel.Sphere d) := + (CubeLaw d).map (CubeSphere hd) + +def BlockCount (T p : ℕ) : ℕ := ⌈(T:ℝ)/(p:ℝ)⌉₊ + +def SourceEllipsoidStatement : Prop := + let two : ℝ := @OfNat.ofNat ℝ 2 (@instOfNatAtLeastTwo ℝ 2 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0))) + let four : ℝ := @OfNat.ofNat ℝ 4 (@instOfNatAtLeastTwo ℝ 4 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 2))) + let ten : ℝ := @OfNat.ofNat ℝ 10 (@instOfNatAtLeastTwo ℝ 10 Real.commRing.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 8))) + ∃ C C₀ : ℝ, 1 ≤ C ∧ 1 ≤ C₀ ∧ + ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, 0 < ε → ε ≤ 1/ten → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ K : Ω → Policy d M T, Policy.Admissible K ρ (UniformSphere d) → + Policy.Success K ρ (UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + (four^d * ε^(((d:ℝ)-1)/two) * + (C^d * (((d/8+2)*2^M : ℕ):ℝ)^(1/((d/8:ℕ):ℝ)))^(BlockCount T (d/8)))) ∧ + Policy.ChordSuccess K ρ (UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + (C₀^d * ε^((d:ℝ)/two-1) * + (C^d * (((2*(d/8)+4)*2^M : ℕ):ℝ)^(1/((d/8:ℕ):ℝ)))^(BlockCount T (d/8)))) ∧ + {x : Sphere d × Sphere d | Real.arccos (@inner ℝ (Vector d) + (@InnerProductSpace.toInner ℝ (Vector d) _ + (PiLp.seminormedAddCommGroup + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (fun _ : Fin d => ℝ)) + (PiLp.innerProductSpace (𝕜 := ℝ) (fun _ : Fin d => ℝ))) + x.2.val x.1.val) ≤ ε} ⊆ + {x | @Dist.dist (Vector d) + (PiLp.instDist (p := @OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast + (Mathlib.Meta.NormNum.instAtLeastTwo (nat_lit 0)))) + (α := fun _ : Fin d => ℝ)) x.2.val x.1.val ≤ ε} + +lemma cubePrior_dimension {d₀ d : ℕ} (hd₀ : 16 ≤ d₀) (hd : d₀ ≤ d) : 2 ≤ d := + Nat.le_trans (by decide : 2 ≤ 16) (Nat.le_trans hd₀ hd) + +end MemoryPrecision.Kernel + +namespace MemoryPrecision + +theorem main : + AmbientGramStatement ∧ + FiniteDensityStatement ∧ + MeasurableTestStatement ∧ + JointL1Statement ∧ + PointwiseDensityStatement ∧ + CoefficientStepStatement ∧ + Kernel.SourceEllipsoidStatement.{u} ∧ + CubeBlockStatement ∧ + (∃ D : ℝ, Real.exp 1 ≤ D ∧ ∃ d₀ : ℕ, ∃ hd₀ : 16 ≤ d₀, ∃ c : ℝ, 0 < c ∧ + ∀ d M T : ℕ, ∀ hd : d₀ ≤ d, M ≤ d^2 → ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ K : Ω → MemoryPrecision.Kernel.Policy d M T, + MemoryPrecision.Kernel.Policy.ModelAdmissible.{u} K ρ → + MemoryPrecision.Kernel.Policy.Success K ρ + (MemoryPrecision.Kernel.CubePrior (MemoryPrecision.Kernel.cubePrior_dimension hd₀ hd)) ε ≤ + min 1 (ENNReal.ofReal + (D^((d/2)*(MemoryPrecision.Kernel.BlockCount T ((d/2)/4)+1)) * ε^((d/2:ℕ)/4:ℝ))) ∧ + ((∀ signal : MemoryPrecision.Kernel.Sphere d, + (@OfNat.ofNat ℝ≥0∞ 2 + (@instOfNatAtLeastTwo ℝ≥0∞ 2 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) / + (@OfNat.ofNat ℝ≥0∞ 3 + (@instOfNatAtLeastTwo ℝ≥0∞ 3 ENNReal.instAddCommMonoidWithOne.toNatCast inferInstance)) ≤ + (∫⁻ observation, + MemoryPrecision.Kernel.Policy.experiment K + (MemoryPrecision.Kernel.Policy.angleTest ε) (signal, observation) + ∂ρ.prod (MemoryPrecision.Kernel.RowLaw d T))) → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ))) ∧ + (∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, 0 < d₀ ∧ + ∀ d M T : ℕ, d₀ ≤ d → ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → MemoryPrecision.Kernel.Policy d M T, + MemoryPrecision.Kernel.Policy.Admissible L ρ (MemoryPrecision.Kernel.UniformSphere d) → + MemoryPrecision.Kernel.Policy.Success L ρ (MemoryPrecision.Kernel.UniformSphere d) ε ≤ min 1 (ENNReal.ofReal + ((2*ε*Real.exp (C*(1+(M:ℝ)/(d:ℝ)^2)*(MemoryPrecision.Kernel.BlockCount T ((d-1)/8):ℝ)))^(((d:ℝ)-1)/2)))) := by + sorry + +end MemoryPrecision + +end + +end OAI diff --git a/tasks/memory-precision/tests/grade.py b/tasks/memory-precision/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/memory-precision/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/memory-precision/tests/task.json b/tasks/memory-precision/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5989c7ed8c30069703fbcc935f8fc07fe9bea556 --- /dev/null +++ b/tasks/memory-precision/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MemoryPrecision", + "comparator": { + "theorem_names": [ + "OAI.MemoryPrecision.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11502 +} \ No newline at end of file diff --git a/tasks/memory-precision/tests/test.sh b/tasks/memory-precision/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/memory-precision/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/metric-entropy-duality/environment/Dockerfile b/tasks/metric-entropy-duality/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/metric-entropy-duality/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/metric-entropy-duality/environment/fetch_mathlib.sh b/tasks/metric-entropy-duality/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/metric-entropy-duality/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/metric-entropy-duality/environment/lake-manifest.json b/tasks/metric-entropy-duality/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/metric-entropy-duality/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/metric-entropy-duality/environment/lakefile.lean b/tasks/metric-entropy-duality/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/metric-entropy-duality/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/metric-entropy-duality/environment/lean_setup.sh b/tasks/metric-entropy-duality/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/metric-entropy-duality/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/metric-entropy-duality/environment/pack_submission.py b/tasks/metric-entropy-duality/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/metric-entropy-duality/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/metric-entropy-duality/instruction.md b/tasks/metric-entropy-duality/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d91008e719b95eb3d93319866493899fbbbaa6f8 --- /dev/null +++ b/tasks/metric-entropy-duality/instruction.md @@ -0,0 +1,110 @@ +# openai/math challenge `MetricEntropyDuality` (family 329) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 329 of the release, *A counterexample to Pietsch's metric-entropy duality conjecture* +(Functional analysis). The family as a whole: Disproves Pietsch's dimension-free duality conjecture for metric entropy. Origin-symmetric convex bodies violate every proposed choice of universal constants in the conjectured comparison between covering numbers and those of the polar bodies, even when the covering body is a cube. + +The challenge is `MetricEntropyDuality`, also at `/opt/openai-math/challenges/MetricEntropyDuality.lean`: + +```lean +import Mathlib.Analysis.Convex.Topology +import Mathlib.Analysis.Normed.Group.Constructions +import Mathlib.Order.Lattice.Nat +import Mathlib.Analysis.SpecialFunctions.Log.Basic + +namespace OAI + +universe u + +noncomputable section + +namespace MetricEntropyDuality + +open Filter Topology +open scoped BigOperators Pointwise + +abbrev RealSpace (ι : Type u) := ι → ℝ + +def pairing {ι : Type u} [Fintype ι] (x y : RealSpace ι) : ℝ := + ∑ i, x i * y i + +def cube (ι : Type u) : Set (RealSpace ι) := + {x | ∀ i, |x i| ≤ 1} + +def polar {ι : Type u} [Fintype ι] (K : Set (RealSpace ι)) : Set (RealSpace ι) := + {y | ∀ x ∈ K, pairing x y ≤ 1} + +def Covers {ι : Type u} {M : ℕ} (A B : Set (RealSpace ι)) + (centers : Fin M → RealSpace ι) : Prop := + ∀ x ∈ A, ∃ j, x - centers j ∈ B + +def Coverable {ι : Type u} (A B : Set (RealSpace ι)) : Prop := + ∃ M : ℕ, ∃ centers : Fin M → RealSpace ι, Covers A B centers + +def coveringNumber {ι : Type u} (A B : Set (RealSpace ι)) : ℕ := + sInf {M : ℕ | ∃ centers : Fin M → RealSpace ι, Covers A B centers} + +structure IsSymmetricConvexBody {ι : Type u} [Fintype ι] + (K : Set (RealSpace ι)) : Prop where + isCompact : IsCompact K + convex : Convex ℝ K + symmetric : ∀ x, x ∈ K ↔ -x ∈ K + interior_nonempty : (interior K).Nonempty + +theorem exists_entropy_duality_counterexample_with_covers + (a b : ℝ) (ha : 1 ≤ a) (hb : 1 ≤ b) : + ∃ n : ℕ, 0 < n ∧ ∃ K : Set (RealSpace (Fin n)), + IsSymmetricConvexBody K ∧ + Coverable K (cube (Fin n)) ∧ + Coverable (polar (cube (Fin n))) (a⁻¹ • polar K) ∧ + b * Real.log (coveringNumber (polar (cube (Fin n))) (a⁻¹ • polar K) : ℝ) < + Real.log (coveringNumber K (cube (Fin n)) : ℝ) := by + sorry + +end MetricEntropyDuality + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MetricEntropyDuality.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MetricEntropyDuality.exists_entropy_duality_counterexample_with_covers` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/metric-entropy-duality/solution/closure.txt b/tasks/metric-entropy-duality/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..29bd07567142b3620baddac920c0f7272db70e5f --- /dev/null +++ b/tasks/metric-entropy-duality/solution/closure.txt @@ -0,0 +1,52 @@ +OAI.Analysis.MetricEntropy.Asymptotics +OAI.Analysis.MetricEntropy.Basic +OAI.Analysis.MetricEntropy.CommonIndex +OAI.Analysis.MetricEntropy.Compression +OAI.Analysis.MetricEntropy.CompressionCode +OAI.Analysis.MetricEntropy.CompressionDecoder +OAI.Analysis.MetricEntropy.CompressionLevels +OAI.Analysis.MetricEntropy.Construction +OAI.Analysis.MetricEntropy.ConvexBody +OAI.Analysis.MetricEntropy.CoordinateTransport +OAI.Analysis.MetricEntropy.CoveringNumber +OAI.Analysis.MetricEntropy.DimensionRatio +OAI.Analysis.MetricEntropy.DirectionBudget +OAI.Analysis.MetricEntropy.DirectionDeletion +OAI.Analysis.MetricEntropy.DirectionSampling +OAI.Analysis.MetricEntropy.DirectionTuples +OAI.Analysis.MetricEntropy.EntropyBounds +OAI.Analysis.MetricEntropy.EntropyComparison +OAI.Analysis.MetricEntropy.EntropyFinal +OAI.Analysis.MetricEntropy.EntropyPair +OAI.Analysis.MetricEntropy.EntropyPairLimits +OAI.Analysis.MetricEntropy.FieldGraphSeparation +OAI.Analysis.MetricEntropy.FiniteFieldRows +OAI.Analysis.MetricEntropy.FiniteProductCounting +OAI.Analysis.MetricEntropy.FormCardinality +OAI.Analysis.MetricEntropy.FormContraction +OAI.Analysis.MetricEntropy.FormDimension +OAI.Analysis.MetricEntropy.FormPolynomials +OAI.Analysis.MetricEntropy.FormZeroCount +OAI.Analysis.MetricEntropy.GraphProfile +OAI.Analysis.MetricEntropy.GreedyPivots +OAI.Analysis.MetricEntropy.GroupedWeights +OAI.Analysis.MetricEntropy.LabelEncoding +OAI.Analysis.MetricEntropy.LogProfile +OAI.Analysis.MetricEntropy.Main +OAI.Analysis.MetricEntropy.MatrixEntropy +OAI.Analysis.MetricEntropy.MatrixToBody +OAI.Analysis.MetricEntropy.Model +OAI.Analysis.MetricEntropy.Parameters +OAI.Analysis.MetricEntropy.PartitionGraph +OAI.Analysis.MetricEntropy.PolarCover +OAI.Analysis.MetricEntropy.PolynomialZeroBound +OAI.Analysis.MetricEntropy.PrimeChoice +OAI.Analysis.MetricEntropy.ProfileMixtures +OAI.Analysis.MetricEntropy.ProfilePivots +OAI.Analysis.MetricEntropy.RobustDirections +OAI.Analysis.MetricEntropy.SignedCompression +OAI.Analysis.MetricEntropy.SupportPolar +OAI.Analysis.MetricEntropy.SymmetricForms +OAI.Analysis.MetricEntropy.SymmetricIndex +OAI.Analysis.MetricEntropy.SymmetricMultiplicity +OAI.Analysis.MetricEntropy.WeightRounding diff --git a/tasks/metric-entropy-duality/solution/reference.py b/tasks/metric-entropy-duality/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/metric-entropy-duality/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/metric-entropy-duality/solution/solve.sh b/tasks/metric-entropy-duality/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..61e6b355d62bd18b8a12d760314c2ba2b458f8b0 --- /dev/null +++ b/tasks/metric-entropy-duality/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MetricEntropyDuality, i.e. module OAI.Analysis.MetricEntropy.Main and the +# 52 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.MetricEntropy.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MetricEntropyDuality" diff --git a/tasks/metric-entropy-duality/task.toml b/tasks/metric-entropy-duality/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d7b6fadc46bf2082c1e4c777791f8a7a7c37dbe --- /dev/null +++ b/tasks/metric-entropy-duality/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/metric-entropy-duality" +version = "1.0.0" +description = "Prove MetricEntropyDuality (openai/math family 329: A counterexample to Pietsch's metric-entropy duality conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MetricEntropyDuality.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MetricEntropyDuality" +family = "329" +family_title = "A counterexample to Pietsch's metric-entropy duality conjecture" +subject = "Functional analysis" +theorems = ["OAI.MetricEntropyDuality.exists_entropy_duality_counterexample_with_covers"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.MetricEntropy.Main" +reference_modules = 52 +reference_lean_bytes = 267910 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 557 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11941 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/metric-entropy-duality/tests/Challenge.lean b/tasks/metric-entropy-duality/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f05676fe1c06c40e0be9197d054f4d646f463b96 --- /dev/null +++ b/tasks/metric-entropy-duality/tests/Challenge.lean @@ -0,0 +1,59 @@ +import Mathlib.Analysis.Convex.Topology +import Mathlib.Analysis.Normed.Group.Constructions +import Mathlib.Order.Lattice.Nat +import Mathlib.Analysis.SpecialFunctions.Log.Basic + +namespace OAI + +universe u + +noncomputable section + +namespace MetricEntropyDuality + +open Filter Topology +open scoped BigOperators Pointwise + +abbrev RealSpace (ι : Type u) := ι → ℝ + +def pairing {ι : Type u} [Fintype ι] (x y : RealSpace ι) : ℝ := + ∑ i, x i * y i + +def cube (ι : Type u) : Set (RealSpace ι) := + {x | ∀ i, |x i| ≤ 1} + +def polar {ι : Type u} [Fintype ι] (K : Set (RealSpace ι)) : Set (RealSpace ι) := + {y | ∀ x ∈ K, pairing x y ≤ 1} + +def Covers {ι : Type u} {M : ℕ} (A B : Set (RealSpace ι)) + (centers : Fin M → RealSpace ι) : Prop := + ∀ x ∈ A, ∃ j, x - centers j ∈ B + +def Coverable {ι : Type u} (A B : Set (RealSpace ι)) : Prop := + ∃ M : ℕ, ∃ centers : Fin M → RealSpace ι, Covers A B centers + +def coveringNumber {ι : Type u} (A B : Set (RealSpace ι)) : ℕ := + sInf {M : ℕ | ∃ centers : Fin M → RealSpace ι, Covers A B centers} + +structure IsSymmetricConvexBody {ι : Type u} [Fintype ι] + (K : Set (RealSpace ι)) : Prop where + isCompact : IsCompact K + convex : Convex ℝ K + symmetric : ∀ x, x ∈ K ↔ -x ∈ K + interior_nonempty : (interior K).Nonempty + +theorem exists_entropy_duality_counterexample_with_covers + (a b : ℝ) (ha : 1 ≤ a) (hb : 1 ≤ b) : + ∃ n : ℕ, 0 < n ∧ ∃ K : Set (RealSpace (Fin n)), + IsSymmetricConvexBody K ∧ + Coverable K (cube (Fin n)) ∧ + Coverable (polar (cube (Fin n))) (a⁻¹ • polar K) ∧ + b * Real.log (coveringNumber (polar (cube (Fin n))) (a⁻¹ • polar K) : ℝ) < + Real.log (coveringNumber K (cube (Fin n)) : ℝ) := by + sorry + +end MetricEntropyDuality + +end + +end OAI diff --git a/tasks/metric-entropy-duality/tests/grade.py b/tasks/metric-entropy-duality/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/metric-entropy-duality/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/metric-entropy-duality/tests/task.json b/tasks/metric-entropy-duality/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a459219410ea5b93da86684de7445716548cc0d3 --- /dev/null +++ b/tasks/metric-entropy-duality/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MetricEntropyDuality", + "comparator": { + "theorem_names": [ + "OAI.MetricEntropyDuality.exists_entropy_duality_counterexample_with_covers" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11041 +} \ No newline at end of file diff --git a/tasks/metric-entropy-duality/tests/test.sh b/tasks/metric-entropy-duality/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/metric-entropy-duality/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/metric-k-median/environment/Dockerfile b/tasks/metric-k-median/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/metric-k-median/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/metric-k-median/environment/fetch_mathlib.sh b/tasks/metric-k-median/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/metric-k-median/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/metric-k-median/environment/lake-manifest.json b/tasks/metric-k-median/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/metric-k-median/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/metric-k-median/environment/lakefile.lean b/tasks/metric-k-median/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/metric-k-median/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/metric-k-median/environment/lean_setup.sh b/tasks/metric-k-median/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/metric-k-median/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/metric-k-median/environment/pack_submission.py b/tasks/metric-k-median/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/metric-k-median/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/metric-k-median/instruction.md b/tasks/metric-k-median/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e592c2ae1a428634e7892d0942e7db4576a2ef6a --- /dev/null +++ b/tasks/metric-k-median/instruction.md @@ -0,0 +1,119 @@ +# openai/math challenge `MetricKMedian` (family 125) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 125 of the release, *The approximation threshold for metric $k$-median* +(Theoretical computer science). The family as a whole: Gives a deterministic polynomial-time $(1+2/e+\varepsilon)$-approximation for finite rational metric $k$-median with specified candidate facilities, for every fixed $\varepsilon>0$. Assuming $P\ne NP$, the optimal infimum approximation factor is $1+2/e$. + +The challenge is `MetricKMedian`, also at `/opt/openai-math/challenges/MetricKMedian.lean`: + +```lean +import Mathlib + +namespace OAI + + + + +section +section +namespace MetricKMedian + +structure Instance where + n : ℕ + distance : Fin n → Fin n → ℚ + clients : Finset (Fin n) + facilities : Finset (Fin n) + k : ℕ + distance_nonneg : ∀ i j, 0 ≤ distance i j + distance_eq_zero : ∀ i j, distance i j = 0 ↔ i = j + distance_symm : ∀ i j, distance i j = distance j i + distance_triangle : ∀ i j h, distance i h ≤ distance i j + distance j h + k_pos : 1 ≤ k + k_le : k ≤ facilities.card + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length true ++ [false] ++ n.bits + +def encodeRat (q : ℚ) : List Bool := + [decide (q.num < 0)] ++ encodeNat q.num.natAbs ++ encodeNat q.den + +def encodeInstance (I : Instance) : List Bool := + encodeNat I.n ++ encodeNat I.k ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.n => + (List.ofFn (fun j : Fin I.n => encodeRat (I.distance i j))).flatten)).flatten + +noncomputable def nearest (I : Instance) (j : Fin I.n) (S : Finset (Fin I.n)) : ℝ := + if h : S.Nonempty then + (S.image (fun i => (I.distance j i : ℝ))).min' (h.image _) + else 0 + +noncomputable def cost (I : Instance) (S : Finset (Fin I.n)) : ℝ := + ∑ j ∈ I.clients, nearest I j S + +def feasibleSets (I : Instance) : Finset (Finset (Fin I.n)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.k) + +noncomputable def optimum (I : Instance) : ℝ := + if h : (feasibleSets I).Nonempty then + ((feasibleSets I).image (cost I)).min' (h.image _) + else 0 + +def Correct (epsilon : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ (1 + 2 / Real.exp 1 + epsilon) * optimum I + +theorem main_finite_work : ∀ ε : ℝ, 0 < ε → + ∃ (algorithm : Instance → List Bool) (P : Turing.TM2ComputableInPolyTime encodeInstance id algorithm), + (∀ k : P.tm.K, Finite (P.tm.Γ k)) ∧ ∀ I, Correct ε I (algorithm I) := by + sorry + +end MetricKMedian +end +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MetricKMedian.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MetricKMedian.main_finite_work` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/metric-k-median/solution/closure.txt b/tasks/metric-k-median/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..af7e76abab4cfb87d35b3edd696a1e38d6b7157e --- /dev/null +++ b/tasks/metric-k-median/solution/closure.txt @@ -0,0 +1,569 @@ +OAI.Combinatorics.KMedian.Analysis.AnalyticEnvelopes +OAI.Combinatorics.KMedian.Analysis.BernsteinFalse +OAI.Combinatorics.KMedian.Analysis.BernsteinTrue +OAI.Combinatorics.KMedian.Analysis.CertificatePolynomials +OAI.Combinatorics.KMedian.Analysis.ChargeTransfer +OAI.Combinatorics.KMedian.Analysis.Coefficients +OAI.Combinatorics.KMedian.Analysis.ComparisonCertificates +OAI.Combinatorics.KMedian.Analysis.FiniteAverages +OAI.Combinatorics.KMedian.Analysis.FiniteComparison +OAI.Combinatorics.KMedian.Analysis.NormalizedTransfer +OAI.Combinatorics.KMedian.Analysis.PolynomialBounds +OAI.Combinatorics.KMedian.Analysis.QuadraticEnvelopes +OAI.Combinatorics.KMedian.Analysis.RowComparison +OAI.Combinatorics.KMedian.Analysis.ScalarCertificates +OAI.Combinatorics.KMedian.Analysis.ScalarTransfer +OAI.Combinatorics.KMedian.Analysis.TaylorBounds +OAI.Combinatorics.KMedian.Analysis.TaylorExpansion +OAI.Combinatorics.KMedian.Binary.BinaryAddition +OAI.Combinatorics.KMedian.Binary.BinaryAutoExtras +OAI.Combinatorics.KMedian.Binary.BinaryAutoFiniteLists +OAI.Combinatorics.KMedian.Binary.BinaryAutomatic +OAI.Combinatorics.KMedian.Binary.BinaryBooleanLists +OAI.Combinatorics.KMedian.Binary.BinaryDivision +OAI.Combinatorics.KMedian.Binary.BinaryDyadicPowers +OAI.Combinatorics.KMedian.Binary.BinaryFloor +OAI.Combinatorics.KMedian.Binary.BinaryGCD +OAI.Combinatorics.KMedian.Binary.BinaryGuard +OAI.Combinatorics.KMedian.Binary.BinaryGuardTotal +OAI.Combinatorics.KMedian.Binary.BinaryInteger +OAI.Combinatorics.KMedian.Binary.BinaryIntegerHeight +OAI.Combinatorics.KMedian.Binary.BinaryIterations +OAI.Combinatorics.KMedian.Binary.BinaryListContext +OAI.Combinatorics.KMedian.Binary.BinaryListExtras +OAI.Combinatorics.KMedian.Binary.BinaryListFold +OAI.Combinatorics.KMedian.Binary.BinaryListIndex +OAI.Combinatorics.KMedian.Binary.BinaryListIndices +OAI.Combinatorics.KMedian.Binary.BinaryListMap +OAI.Combinatorics.KMedian.Binary.BinaryListMapTotal +OAI.Combinatorics.KMedian.Binary.BinaryListSelection +OAI.Combinatorics.KMedian.Binary.BinaryListZip +OAI.Combinatorics.KMedian.Binary.BinaryLists +OAI.Combinatorics.KMedian.Binary.BinaryMatrix +OAI.Combinatorics.KMedian.Binary.BinaryMultiplication +OAI.Combinatorics.KMedian.Binary.BinaryNatSum +OAI.Combinatorics.KMedian.Binary.BinaryNatural +OAI.Combinatorics.KMedian.Binary.BinaryPredicates +OAI.Combinatorics.KMedian.Binary.BinaryRational +OAI.Combinatorics.KMedian.Binary.BinaryRationalFold +OAI.Combinatorics.KMedian.Binary.BinaryRationalHeight +OAI.Combinatorics.KMedian.Binary.BinaryRepeat +OAI.Combinatorics.KMedian.Binary.BinarySubtraction +OAI.Combinatorics.KMedian.Binary.BinaryWords +OAI.Combinatorics.KMedian.Binary.BooleanComposition +OAI.Combinatorics.KMedian.Binary.BooleanEmbedding +OAI.Combinatorics.KMedian.Binary.BooleanEncoding +OAI.Combinatorics.KMedian.Binary.BooleanFinite +OAI.Combinatorics.KMedian.Binary.BooleanListPrimitives +OAI.Combinatorics.KMedian.Binary.BooleanLoop +OAI.Combinatorics.KMedian.Binary.BooleanLoopFrom +OAI.Combinatorics.KMedian.Binary.BooleanMachine +OAI.Combinatorics.KMedian.Binary.BooleanMonomials +OAI.Combinatorics.KMedian.Binary.BooleanParallelTransducer +OAI.Combinatorics.KMedian.Binary.BooleanPolynomial +OAI.Combinatorics.KMedian.Binary.BooleanProducts +OAI.Combinatorics.KMedian.Binary.BooleanRecode +OAI.Combinatorics.KMedian.Binary.BooleanReverse +OAI.Combinatorics.KMedian.Binary.BooleanSum +OAI.Combinatorics.KMedian.Binary.BooleanThread +OAI.Combinatorics.KMedian.Binary.BooleanTransducer +OAI.Combinatorics.KMedian.Binary.InstanceParserProgram +OAI.Combinatorics.KMedian.Binary.NumericParserProgram +OAI.Combinatorics.KMedian.Binary.SequentialParserProgram +OAI.Combinatorics.KMedian.Compression.AffineElimination +OAI.Combinatorics.KMedian.Compression.AffineKernel +OAI.Combinatorics.KMedian.Compression.AffineListCompiler +OAI.Combinatorics.KMedian.Compression.AffineListOperations +OAI.Combinatorics.KMedian.Compression.BoundedDependence +OAI.Combinatorics.KMedian.Compression.CircuitBitBound +OAI.Combinatorics.KMedian.Compression.CompressionBinaryProgram +OAI.Combinatorics.KMedian.Compression.CompressionBounds +OAI.Combinatorics.KMedian.Compression.CompressionListStep +OAI.Combinatorics.KMedian.Compression.ComputedAffineKernel +OAI.Combinatorics.KMedian.Compression.ComputedCompression +OAI.Combinatorics.KMedian.Compression.ComputedCompressionStep +OAI.Combinatorics.KMedian.Compression.ComputedElimination +OAI.Combinatorics.KMedian.Compression.ComputedIntegerKernel +OAI.Combinatorics.KMedian.Compression.ComputedPivot +OAI.Combinatorics.KMedian.Compression.DependentIntegerKernel +OAI.Combinatorics.KMedian.Compression.FinsetVectorExtension +OAI.Combinatorics.KMedian.Compression.FullIntegerKernel +OAI.Combinatorics.KMedian.Compression.GaussianBinaryProgram +OAI.Combinatorics.KMedian.Compression.GaussianCircuit +OAI.Combinatorics.KMedian.Compression.GaussianInputBounds +OAI.Combinatorics.KMedian.Compression.GaussianKernel +OAI.Combinatorics.KMedian.Compression.GaussianListCompiler +OAI.Combinatorics.KMedian.Compression.GaussianListMachine +OAI.Combinatorics.KMedian.Compression.GaussianListOperations +OAI.Combinatorics.KMedian.Compression.GaussianListPivot +OAI.Combinatorics.KMedian.Compression.GaussianListRun +OAI.Combinatorics.KMedian.Compression.GaussianListSemantics +OAI.Combinatorics.KMedian.Compression.GaussianListSize +OAI.Combinatorics.KMedian.Compression.GaussianResidualCertificate +OAI.Combinatorics.KMedian.Compression.GaussianResidualHeight +OAI.Combinatorics.KMedian.Compression.GaussianStates +OAI.Combinatorics.KMedian.Compression.GaussianTabulated +OAI.Combinatorics.KMedian.Compression.GramBounds +OAI.Combinatorics.KMedian.Compression.GramDependence +OAI.Combinatorics.KMedian.Compression.IntegerCoefficientBounds +OAI.Combinatorics.KMedian.Compression.IntegerKernelProgram +OAI.Combinatorics.KMedian.Compression.IntegerListProgram +OAI.Combinatorics.KMedian.Compression.IntegerRationalCompression +OAI.Combinatorics.KMedian.Compression.RationalCompression +OAI.Combinatorics.KMedian.Compression.RationalIntegerLaw +OAI.Combinatorics.KMedian.Compression.RationalKernelHeightSupport +OAI.Combinatorics.KMedian.Compression.RationalOperationHeight +OAI.Combinatorics.KMedian.Compression.RationalScaling +OAI.Combinatorics.KMedian.Geometry.BoundFreeCompression +OAI.Combinatorics.KMedian.Geometry.BundleRounding +OAI.Combinatorics.KMedian.Geometry.ChunkCharges +OAI.Combinatorics.KMedian.Geometry.ComputedInstanceAlgorithm +OAI.Combinatorics.KMedian.Geometry.ComputedRationalCompression +OAI.Combinatorics.KMedian.Geometry.FilteredMoments +OAI.Combinatorics.KMedian.Geometry.FixedBatchTransition +OAI.Combinatorics.KMedian.Geometry.GraphComparison +OAI.Combinatorics.KMedian.Geometry.GraphLaw +OAI.Combinatorics.KMedian.Geometry.GraphListOperations +OAI.Combinatorics.KMedian.Geometry.GraphMoments +OAI.Combinatorics.KMedian.Geometry.GraphRunHeight +OAI.Combinatorics.KMedian.Geometry.GreedyCompletion +OAI.Combinatorics.KMedian.Geometry.GreedyPacking +OAI.Combinatorics.KMedian.Geometry.IntegerBranching +OAI.Combinatorics.KMedian.Geometry.ListSigma +OAI.Combinatorics.KMedian.Geometry.MomentAnalysis +OAI.Combinatorics.KMedian.Geometry.NearestFillingFormula +OAI.Combinatorics.KMedian.Geometry.NearestFractional +OAI.Combinatorics.KMedian.Geometry.NearestReindex +OAI.Combinatorics.KMedian.Geometry.PotentialBounds +OAI.Combinatorics.KMedian.Geometry.RationalAllParameters +OAI.Combinatorics.KMedian.Geometry.RationalBrackets +OAI.Combinatorics.KMedian.Geometry.RationalBundleGeometry +OAI.Combinatorics.KMedian.Geometry.RationalCompletedCost +OAI.Combinatorics.KMedian.Geometry.RationalFractionalInput +OAI.Combinatorics.KMedian.Geometry.RationalFractionalScan +OAI.Combinatorics.KMedian.Geometry.RationalGeometryScan +OAI.Combinatorics.KMedian.Geometry.RationalGridRound +OAI.Combinatorics.KMedian.Geometry.RationalHistoryCompletion +OAI.Combinatorics.KMedian.Geometry.RationalHistorySelection +OAI.Combinatorics.KMedian.Geometry.RationalHistoryValid +OAI.Combinatorics.KMedian.Geometry.RationalImageCost +OAI.Combinatorics.KMedian.Geometry.RationalIndexedCost +OAI.Combinatorics.KMedian.Geometry.RationalInstanceCost +OAI.Combinatorics.KMedian.Geometry.RationalIntervals +OAI.Combinatorics.KMedian.Geometry.RationalNearestCopies +OAI.Combinatorics.KMedian.Geometry.RationalParameterizedHistory +OAI.Combinatorics.KMedian.Geometry.RationalSparseTaper +OAI.Combinatorics.KMedian.Geometry.RationalSplitEnumeration +OAI.Combinatorics.KMedian.Geometry.RationalSplitInput +OAI.Combinatorics.KMedian.Geometry.RationalSplitting +OAI.Combinatorics.KMedian.Geometry.RationalUnitInput +OAI.Combinatorics.KMedian.Geometry.RationalUnitScan +OAI.Combinatorics.KMedian.Geometry.SortedListEncoding +OAI.Combinatorics.KMedian.Geometry.TimeAdvance +OAI.Combinatorics.KMedian.Geometry.TrimIntegerLaw +OAI.Combinatorics.KMedian.Geometry.UniformDrift +OAI.Combinatorics.KMedian.Instance +OAI.Combinatorics.KMedian.Main +OAI.Combinatorics.KMedian.Model +OAI.Combinatorics.KMedian.Optimization.ApproximateFractional +OAI.Combinatorics.KMedian.Optimization.ApproximateLPSelection +OAI.Combinatorics.KMedian.Optimization.ApproximationListProgram +OAI.Combinatorics.KMedian.Optimization.ApproximationSlack +OAI.Combinatorics.KMedian.Optimization.ComputedNearest +OAI.Combinatorics.KMedian.Optimization.DualListCompiler +OAI.Combinatorics.KMedian.Optimization.DualListOperations +OAI.Combinatorics.KMedian.Optimization.FractionalDual +OAI.Combinatorics.KMedian.Optimization.FractionalInputProgram +OAI.Combinatorics.KMedian.Optimization.FractionalListChecks +OAI.Combinatorics.KMedian.Optimization.FractionalScanProgram +OAI.Combinatorics.KMedian.Optimization.FractionalSelectProgram +OAI.Combinatorics.KMedian.Optimization.GradientDenominator +OAI.Combinatorics.KMedian.Optimization.IndexedInstanceLP +OAI.Combinatorics.KMedian.Optimization.IntegralFractionalComparison +OAI.Combinatorics.KMedian.Optimization.LPBinaryInput +OAI.Combinatorics.KMedian.Optimization.LPBinaryStart +OAI.Combinatorics.KMedian.Optimization.LPBinaryTrajectory +OAI.Combinatorics.KMedian.Optimization.LPListFacts +OAI.Combinatorics.KMedian.Optimization.LPMinimumSelection +OAI.Combinatorics.KMedian.Optimization.MatrixNormalization +OAI.Combinatorics.KMedian.Optimization.OptimizationBitBound +OAI.Combinatorics.KMedian.Optimization.ProjectedSubgradient +OAI.Combinatorics.KMedian.Optimization.RationalArgmin +OAI.Combinatorics.KMedian.Optimization.SimplexDiameter +OAI.Combinatorics.KMedian.Optimization.SimplexListProgram +OAI.Combinatorics.KMedian.Optimization.SimplexProjection +OAI.Combinatorics.KMedian.Optimization.SubgradientDenominator +OAI.Combinatorics.KMedian.Optimization.SubgradientTrajectoryHeight +OAI.Combinatorics.KMedian.Optimization.TruncatedListCompiler +OAI.Combinatorics.KMedian.Optimization.TruncatedListOperations +OAI.Combinatorics.KMedian.Optimization.TruncatedObjective +OAI.Combinatorics.KMedian.Optimization.TruncatedOptimization +OAI.Combinatorics.KMedian.Optimization.TruncatedRepair +OAI.Combinatorics.KMedian.Optimization.ZeroCostBranch +OAI.Combinatorics.KMedian.Preparation.AssignmentCopies +OAI.Combinatorics.KMedian.Preparation.AssignmentRepair +OAI.Combinatorics.KMedian.Preparation.CoupledGeometry +OAI.Combinatorics.KMedian.Preparation.CoupledNoise +OAI.Combinatorics.KMedian.Preparation.CoupledPreparation +OAI.Combinatorics.KMedian.Preparation.CoupledReindex +OAI.Combinatorics.KMedian.Preparation.CoupledWeights +OAI.Combinatorics.KMedian.Preparation.DistantAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyAssignments +OAI.Combinatorics.KMedian.Preparation.NearbyBall +OAI.Combinatorics.KMedian.Preparation.NearestAssignmentGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationClientAssignments +OAI.Combinatorics.KMedian.Preparation.PreparationCostGeometry +OAI.Combinatorics.KMedian.Preparation.PreparationDeficits +OAI.Combinatorics.KMedian.Preparation.PreparationGrid +OAI.Combinatorics.KMedian.Preparation.PreparationInner +OAI.Combinatorics.KMedian.Preparation.PreparationMoments +OAI.Combinatorics.KMedian.Preparation.PreparationNoise +OAI.Combinatorics.KMedian.Preparation.PreparationOldCost +OAI.Combinatorics.KMedian.Preparation.PreparationOutcome +OAI.Combinatorics.KMedian.Preparation.PreparationOuter +OAI.Combinatorics.KMedian.Preparation.PreparationParameters +OAI.Combinatorics.KMedian.Preparation.PreparationRescaling +OAI.Combinatorics.KMedian.Preparation.PreparationStars +OAI.Combinatorics.KMedian.Preparation.PreparationSubsetNoise +OAI.Combinatorics.KMedian.Preparation.PreparedDataOperations +OAI.Combinatorics.KMedian.Preparation.PreparedKernelProgram +OAI.Combinatorics.KMedian.Preparation.PreparedLawProgram +OAI.Combinatorics.KMedian.Preparation.PreparedScanProgram +OAI.Combinatorics.KMedian.Preparation.RationalPreparedScan +OAI.Combinatorics.KMedian.Preparation.RationalRepresentatives +OAI.Combinatorics.KMedian.Preparation.RationalSupplierPreparation +OAI.Combinatorics.KMedian.Preparation.RationalSupplierScan +OAI.Combinatorics.KMedian.Preparation.RepresentativeBundles +OAI.Combinatorics.KMedian.Preparation.RepresentativeGeometry +OAI.Combinatorics.KMedian.Preparation.RepresentativeProgram +OAI.Combinatorics.KMedian.Preparation.RetainedActivations +OAI.Combinatorics.KMedian.Preparation.SelectedPreparationOutcome +OAI.Combinatorics.KMedian.Preparation.ShortfallByDeviation +OAI.Combinatorics.KMedian.Preparation.SupplierAllocation +OAI.Combinatorics.KMedian.Preparation.SupplierCharges +OAI.Combinatorics.KMedian.Preparation.SupplierGeometry +OAI.Combinatorics.KMedian.Preparation.SupplierListOperations +OAI.Combinatorics.KMedian.Preparation.SupplierMap +OAI.Combinatorics.KMedian.Preparation.SupplierPreparationProgram +OAI.Combinatorics.KMedian.Preparation.SupplierScanProgram +OAI.Combinatorics.KMedian.Preparation.SupportRepair +OAI.Combinatorics.KMedian.Probability.BernoulliBatches +OAI.Combinatorics.KMedian.Probability.BernoulliListOperations +OAI.Combinatorics.KMedian.Probability.BernoulliPolynomial +OAI.Combinatorics.KMedian.Probability.BernoulliRealTransfer +OAI.Combinatorics.KMedian.Probability.BernoulliReindex +OAI.Combinatorics.KMedian.Probability.BernoulliRunHeight +OAI.Combinatorics.KMedian.Probability.BernoulliRunProgram +OAI.Combinatorics.KMedian.Probability.BernoulliSquare +OAI.Combinatorics.KMedian.Probability.BernoulliStepProgram +OAI.Combinatorics.KMedian.Probability.BernoulliVariance +OAI.Combinatorics.KMedian.Probability.Conditioning +OAI.Combinatorics.KMedian.Probability.FiniteClipping +OAI.Combinatorics.KMedian.Probability.FiniteJoint +OAI.Combinatorics.KMedian.Probability.FiniteKernels +OAI.Combinatorics.KMedian.Probability.FiniteLawConstructions +OAI.Combinatorics.KMedian.Probability.FiniteLaws +OAI.Combinatorics.KMedian.Probability.FiniteProcess +OAI.Combinatorics.KMedian.Probability.FiniteVariance +OAI.Combinatorics.KMedian.Probability.NegativeStars +OAI.Combinatorics.KMedian.Probability.NonnegativeRounding +OAI.Combinatorics.KMedian.Probability.ProbabilitySupport +OAI.Combinatorics.KMedian.Probability.PushforwardLaw +OAI.Combinatorics.KMedian.Probability.SignedPartial +OAI.Combinatorics.KMedian.Probability.SignedStars +OAI.Combinatorics.KMedian.Probability.SumLaws +OAI.Combinatorics.KMedian.Probability.SupportedLaw +OAI.Combinatorics.KMedian.Process.ActionDegrees +OAI.Combinatorics.KMedian.Process.ActionTransitionList +OAI.Combinatorics.KMedian.Process.ActualActions +OAI.Combinatorics.KMedian.Process.AdaptiveCount +OAI.Combinatorics.KMedian.Process.AveragedCount +OAI.Combinatorics.KMedian.Process.AveragedDrift +OAI.Combinatorics.KMedian.Process.AveragedGenerator +OAI.Combinatorics.KMedian.Process.BackupGeometry +OAI.Combinatorics.KMedian.Process.BackupInvariant +OAI.Combinatorics.KMedian.Process.BatchActionArrays +OAI.Combinatorics.KMedian.Process.BatchActionCodes +OAI.Combinatorics.KMedian.Process.BatchActionList +OAI.Combinatorics.KMedian.Process.BatchEstimate +OAI.Combinatorics.KMedian.Process.BatchGraphData +OAI.Combinatorics.KMedian.Process.BatchOrdinalArrays +OAI.Combinatorics.KMedian.Process.BatchOrdinalCodes +OAI.Combinatorics.KMedian.Process.BatchProposalProgram +OAI.Combinatorics.KMedian.Process.BatchUniform +OAI.Combinatorics.KMedian.Process.ConditionalRoundDrift +OAI.Combinatorics.KMedian.Process.CopyGraphProgram +OAI.Combinatorics.KMedian.Process.CopyListEncoding +OAI.Combinatorics.KMedian.Process.CopyNearestProgram +OAI.Combinatorics.KMedian.Process.CopyNextProgram +OAI.Combinatorics.KMedian.Process.CopyRound +OAI.Combinatorics.KMedian.Process.CopyState +OAI.Combinatorics.KMedian.Process.CopyTransport +OAI.Combinatorics.KMedian.Process.CountGeometry +OAI.Combinatorics.KMedian.Process.CountInstantiation +OAI.Combinatorics.KMedian.Process.CountListOperations +OAI.Combinatorics.KMedian.Process.CountRunHeight +OAI.Combinatorics.KMedian.Process.CountRunProgram +OAI.Combinatorics.KMedian.Process.CountSize +OAI.Combinatorics.KMedian.Process.CountSource +OAI.Combinatorics.KMedian.Process.CountStepProgram +OAI.Combinatorics.KMedian.Process.CountTail +OAI.Combinatorics.KMedian.Process.CountVariance +OAI.Combinatorics.KMedian.Process.CountsMaskProgram +OAI.Combinatorics.KMedian.Process.ErasureDecay +OAI.Combinatorics.KMedian.Process.FiniteGraph +OAI.Combinatorics.KMedian.Process.ForceBatchBound +OAI.Combinatorics.KMedian.Process.ForcedLocal +OAI.Combinatorics.KMedian.Process.ForcedTransition +OAI.Combinatorics.KMedian.Process.FrozenBatchBound +OAI.Combinatorics.KMedian.Process.FullBatchBound +OAI.Combinatorics.KMedian.Process.GeneratorAverage +OAI.Combinatorics.KMedian.Process.GeneratorBound +OAI.Combinatorics.KMedian.Process.GroupCap +OAI.Combinatorics.KMedian.Process.HeavyActions +OAI.Combinatorics.KMedian.Process.LocalBatchUniform +OAI.Combinatorics.KMedian.Process.LocalForceScale +OAI.Combinatorics.KMedian.Process.PhaseBatchBound +OAI.Combinatorics.KMedian.Process.PhysicalBatchLaw +OAI.Combinatorics.KMedian.Process.PhysicalBatchList +OAI.Combinatorics.KMedian.Process.PhysicalBatchProgram +OAI.Combinatorics.KMedian.Process.PhysicalBatchUpdateProgram +OAI.Combinatorics.KMedian.Process.PhysicalCountGeometry +OAI.Combinatorics.KMedian.Process.PhysicalCountLaw +OAI.Combinatorics.KMedian.Process.PhysicalHistoriesProgram +OAI.Combinatorics.KMedian.Process.PhysicalOldMass +OAI.Combinatorics.KMedian.Process.PhysicalPotential +OAI.Combinatorics.KMedian.Process.PhysicalProcess +OAI.Combinatorics.KMedian.Process.PhysicalRound +OAI.Combinatorics.KMedian.Process.PhysicalRoundProgram +OAI.Combinatorics.KMedian.Process.PhysicalState +OAI.Combinatorics.KMedian.Process.ProcessCompletion +OAI.Combinatorics.KMedian.Process.QuadraticCount +OAI.Combinatorics.KMedian.Process.RoundCountsProgram +OAI.Combinatorics.KMedian.Process.RoundParameters +OAI.Combinatorics.KMedian.Process.RoundWithCount +OAI.Combinatorics.KMedian.Process.RoundingCoordinateHeight +OAI.Combinatorics.KMedian.Process.RoundingListOperations +OAI.Combinatorics.KMedian.Process.RoundingRunHeight +OAI.Combinatorics.KMedian.Process.RoundingRunProgram +OAI.Combinatorics.KMedian.Process.RoundingStateCompiler +OAI.Combinatorics.KMedian.Process.RoundingUniformStep +OAI.Combinatorics.KMedian.Process.SourceAverage +OAI.Combinatorics.KMedian.Process.SourceBalance +OAI.Combinatorics.KMedian.Process.SourceDriftLaw +OAI.Combinatorics.KMedian.Process.SourceGenerator +OAI.Combinatorics.KMedian.Process.StateInvariants +OAI.Combinatorics.KMedian.Process.SurvivalProbability +OAI.Combinatorics.KMedian.Process.Taper +OAI.Combinatorics.KMedian.Process.TaperAllProgram +OAI.Combinatorics.KMedian.Process.TaperData +OAI.Combinatorics.KMedian.Process.TaperGraph +OAI.Combinatorics.KMedian.Process.TaperGraphProgram +OAI.Combinatorics.KMedian.Process.TaperListProgram +OAI.Combinatorics.KMedian.Process.TaperReindex +OAI.Combinatorics.KMedian.Process.UnbalancedActions +OAI.Combinatorics.KMedian.Programs.BoundedEnumerationProgram +OAI.Combinatorics.KMedian.Programs.BranchProgram +OAI.Combinatorics.KMedian.Programs.BundleGeometryProgram +OAI.Combinatorics.KMedian.Programs.BundlesProgram +OAI.Combinatorics.KMedian.Programs.CardinalRoundProgram +OAI.Combinatorics.KMedian.Programs.DependentSparseProgram +OAI.Combinatorics.KMedian.Programs.FinalSelectionProgram +OAI.Combinatorics.KMedian.Programs.FinsetMaskProgram +OAI.Combinatorics.KMedian.Programs.GraphLawProgram +OAI.Combinatorics.KMedian.Programs.GraphRunProgram +OAI.Combinatorics.KMedian.Programs.GraphStepProgram +OAI.Combinatorics.KMedian.Programs.GreedyPackingProgram +OAI.Combinatorics.KMedian.Programs.HistorySelectionProgram +OAI.Combinatorics.KMedian.Programs.InstanceComputedPseudo +OAI.Combinatorics.KMedian.Programs.InstanceDataProgram +OAI.Combinatorics.KMedian.Programs.InstanceFractionalRound +OAI.Combinatorics.KMedian.Programs.InstanceRoundProgram +OAI.Combinatorics.KMedian.Programs.InstanceRounding +OAI.Combinatorics.KMedian.Programs.InstanceZeroProgram +OAI.Combinatorics.KMedian.Programs.LastFractionProgram +OAI.Combinatorics.KMedian.Programs.MaskBestProgram +OAI.Combinatorics.KMedian.Programs.MaximumProgram +OAI.Combinatorics.KMedian.Programs.NearestListProgram +OAI.Combinatorics.KMedian.Programs.NearestMaskProgram +OAI.Combinatorics.KMedian.Programs.OriginalMaskProgram +OAI.Combinatorics.KMedian.Programs.OuterLawProgram +OAI.Combinatorics.KMedian.Programs.PivotListProgram +OAI.Combinatorics.KMedian.Programs.RationalFeatureProgram +OAI.Combinatorics.KMedian.Programs.RationalSortProgram +OAI.Combinatorics.KMedian.Programs.RestrictionProgram +OAI.Combinatorics.KMedian.Programs.ScaleListProgram +OAI.Combinatorics.KMedian.Programs.ScoreProgram +OAI.Combinatorics.KMedian.Programs.SplitListProgram +OAI.Combinatorics.KMedian.Programs.StarActivationProgram +OAI.Combinatorics.KMedian.Programs.TaggedBestProgram +OAI.Combinatorics.KMedian.Programs.UnitGeometryProgram +OAI.Combinatorics.KMedian.Programs.UnitRepresentativeProgram +OAI.Combinatorics.KMedian.Programs.UnitScanProgram +OAI.Combinatorics.KMedian.Reduction.BadCenterBound +OAI.Combinatorics.KMedian.Reduction.BudgetReduction +OAI.Combinatorics.KMedian.Reduction.CloseFromServing +OAI.Combinatorics.KMedian.Reduction.CompletionEndpoint +OAI.Combinatorics.KMedian.Reduction.CompletionEnumeration +OAI.Combinatorics.KMedian.Reduction.CompletionGeometry +OAI.Combinatorics.KMedian.Reduction.CompletionMaskProgram +OAI.Combinatorics.KMedian.Reduction.CompletionProgram +OAI.Combinatorics.KMedian.Reduction.CompletionSelection +OAI.Combinatorics.KMedian.Reduction.DeletionEndpoint +OAI.Combinatorics.KMedian.Reduction.DeletionGeometry +OAI.Combinatorics.KMedian.Reduction.DeletionHistory +OAI.Combinatorics.KMedian.Reduction.DeletionProgram +OAI.Combinatorics.KMedian.Reduction.LocalCompletion +OAI.Combinatorics.KMedian.Reduction.LocalCompletionProgram +OAI.Combinatorics.KMedian.Reduction.NormalizationGuesses +OAI.Combinatorics.KMedian.Reduction.OrdinaryListProgram +OAI.Combinatorics.KMedian.Reduction.RadiusPacking +OAI.Combinatorics.KMedian.Reduction.RationalCompletion +OAI.Combinatorics.KMedian.Reduction.RationalDeletion +OAI.Combinatorics.KMedian.Reduction.RationalGreedyCompletion +OAI.Combinatorics.KMedian.Reduction.RationalLocalChoice +OAI.Combinatorics.KMedian.Reduction.RationalThreshold +OAI.Combinatorics.KMedian.Reduction.ReductionClosure +OAI.Combinatorics.KMedian.Reduction.ReductionCostProgram +OAI.Combinatorics.KMedian.Reduction.ReductionOutcomesProgram +OAI.Combinatorics.KMedian.Reduction.Sparsification +OAI.Combinatorics.KMedian.Reduction.SparsifyEnumeration +OAI.Combinatorics.KMedian.Rounding.ExactRounding +OAI.Combinatorics.KMedian.Rounding.ExceptionalStar +OAI.Combinatorics.KMedian.Rounding.GridClipping +OAI.Combinatorics.KMedian.Rounding.GridDataProgram +OAI.Combinatorics.KMedian.Rounding.GridEndpoint +OAI.Combinatorics.KMedian.Rounding.GridRounding +OAI.Combinatorics.KMedian.Rounding.GridRoundingProgram +OAI.Combinatorics.KMedian.Rounding.IntegerSimplexProjection +OAI.Combinatorics.KMedian.Rounding.MarginalRounding +OAI.Combinatorics.KMedian.Rounding.RationalBatchData +OAI.Combinatorics.KMedian.Rounding.RationalBatchEnumeration +OAI.Combinatorics.KMedian.Rounding.RationalBatchFacts +OAI.Combinatorics.KMedian.Rounding.RationalCopyTransition +OAI.Combinatorics.KMedian.Rounding.RationalLastFraction +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraph +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalGraphInstance +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryCount +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistoryDrift +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalHistorySurvival +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalInvariant +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalKernel +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalReplay +OAI.Combinatorics.KMedian.Rounding.RationalPhysicalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalProposalBound +OAI.Combinatorics.KMedian.Rounding.RationalProposalCount +OAI.Combinatorics.KMedian.Rounding.RationalProposalSurvival +OAI.Combinatorics.KMedian.Rounding.RationalRetain +OAI.Combinatorics.KMedian.Rounding.RationalRoundEvents +OAI.Combinatorics.KMedian.Rounding.RationalRoundParameters +OAI.Combinatorics.KMedian.Rounding.RationalRounding +OAI.Combinatorics.KMedian.Rounding.RationalSignedStep +OAI.Combinatorics.KMedian.Rounding.RationalSignedTerminal +OAI.Combinatorics.KMedian.Rounding.RationalTaper +OAI.Combinatorics.KMedian.Rounding.RationalTaperAffine +OAI.Combinatorics.KMedian.Rounding.RationalTaperCandidates +OAI.Combinatorics.KMedian.Rounding.RationalTaperData +OAI.Combinatorics.KMedian.Rounding.RationalTaperZero +OAI.Combinatorics.KMedian.Rounding.RationalWeightedInvariants +OAI.Combinatorics.KMedian.Rounding.RationalWeightedStep +OAI.Combinatorics.KMedian.Rounding.SignedGridInvariant +OAI.Combinatorics.KMedian.Rounding.SignedListOperations +OAI.Combinatorics.KMedian.Rounding.SignedPreparationProgram +OAI.Combinatorics.KMedian.Rounding.SignedRoundProgram +OAI.Combinatorics.KMedian.Rounding.SignedTerminalProgram +OAI.Combinatorics.KMedian.Rounding.TargetSubset +OAI.Combinatorics.KMedian.Rounding.TargetSubsetProgram +OAI.Combinatorics.KMedian.Rounding.UniformSplitRounding +OAI.Combinatorics.KMedian.Rounding.WeightedGridInvariant +OAI.Combinatorics.KMedian.Rounding.WeightedPartial +OAI.Combinatorics.KMedian.Rounding.WeightedRounding +OAI.Combinatorics.KMedian.Sparse.SparseAffineMoments +OAI.Combinatorics.KMedian.Sparse.SparseAlgorithm +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliFeatures +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliRun +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSubsets +OAI.Combinatorics.KMedian.Sparse.SparseBernoulliSupport +OAI.Combinatorics.KMedian.Sparse.SparseBind +OAI.Combinatorics.KMedian.Sparse.SparseBindProgram +OAI.Combinatorics.KMedian.Sparse.SparseBoundedCount +OAI.Combinatorics.KMedian.Sparse.SparseBoundedDrift +OAI.Combinatorics.KMedian.Sparse.SparseBoundedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseBranchProgram +OAI.Combinatorics.KMedian.Sparse.SparseBundleEncoding +OAI.Combinatorics.KMedian.Sparse.SparseBundleLaw +OAI.Combinatorics.KMedian.Sparse.SparseCardinalFixed +OAI.Combinatorics.KMedian.Sparse.SparseCardinalRounding +OAI.Combinatorics.KMedian.Sparse.SparseCompressProgram +OAI.Combinatorics.KMedian.Sparse.SparseConditionalCount +OAI.Combinatorics.KMedian.Sparse.SparseConditionalRoundDrift +OAI.Combinatorics.KMedian.Sparse.SparseCountFeatures +OAI.Combinatorics.KMedian.Sparse.SparseCountInstantiation +OAI.Combinatorics.KMedian.Sparse.SparseCountRun +OAI.Combinatorics.KMedian.Sparse.SparseCountStatistic +OAI.Combinatorics.KMedian.Sparse.SparseCoupledPreparation +OAI.Combinatorics.KMedian.Sparse.SparseDeletion +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedBatch +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedCount +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedEstimate +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFrozen +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedFull +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraph +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedMixture +OAI.Combinatorics.KMedian.Sparse.SparseEnumeratedSurvival +OAI.Combinatorics.KMedian.Sparse.SparseFiltered +OAI.Combinatorics.KMedian.Sparse.SparseGraphFeatures +OAI.Combinatorics.KMedian.Sparse.SparseGraphLaw +OAI.Combinatorics.KMedian.Sparse.SparseGraphReal +OAI.Combinatorics.KMedian.Sparse.SparseGraphRun +OAI.Combinatorics.KMedian.Sparse.SparseGridRounding +OAI.Combinatorics.KMedian.Sparse.SparseGridZero +OAI.Combinatorics.KMedian.Sparse.SparseHistories +OAI.Combinatorics.KMedian.Sparse.SparseHistoryBounds +OAI.Combinatorics.KMedian.Sparse.SparseIntegerLaw +OAI.Combinatorics.KMedian.Sparse.SparseIterationHeight +OAI.Combinatorics.KMedian.Sparse.SparseListTrim +OAI.Combinatorics.KMedian.Sparse.SparseLocalBatch +OAI.Combinatorics.KMedian.Sparse.SparseMap +OAI.Combinatorics.KMedian.Sparse.SparseMapBind +OAI.Combinatorics.KMedian.Sparse.SparseMarginal +OAI.Combinatorics.KMedian.Sparse.SparseMarginalTools +OAI.Combinatorics.KMedian.Sparse.SparseMixProgram +OAI.Combinatorics.KMedian.Sparse.SparseMixture +OAI.Combinatorics.KMedian.Sparse.SparseMomentAlgebra +OAI.Combinatorics.KMedian.Sparse.SparseNonnegativeSupport +OAI.Combinatorics.KMedian.Sparse.SparseOuterCounts +OAI.Combinatorics.KMedian.Sparse.SparseOuterLaw +OAI.Combinatorics.KMedian.Sparse.SparseOuterMoments +OAI.Combinatorics.KMedian.Sparse.SparseOuterReal +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalBatch +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalCount +OAI.Combinatorics.KMedian.Sparse.SparsePhysicalSurvival +OAI.Combinatorics.KMedian.Sparse.SparsePreparedBudget +OAI.Combinatorics.KMedian.Sparse.SparsePreparedLaw +OAI.Combinatorics.KMedian.Sparse.SparsePreparedMoments +OAI.Combinatorics.KMedian.Sparse.SparsePreparedProbability +OAI.Combinatorics.KMedian.Sparse.SparseProduct +OAI.Combinatorics.KMedian.Sparse.SparseProductProgram +OAI.Combinatorics.KMedian.Sparse.SparseRealExpectation +OAI.Combinatorics.KMedian.Sparse.SparseRealLaw +OAI.Combinatorics.KMedian.Sparse.SparseReduction +OAI.Combinatorics.KMedian.Sparse.SparseRescaledInner +OAI.Combinatorics.KMedian.Sparse.SparseSelect +OAI.Combinatorics.KMedian.Sparse.SparseSignedBudget +OAI.Combinatorics.KMedian.Sparse.SparseSignedFixed +OAI.Combinatorics.KMedian.Sparse.SparseSignedPartial +OAI.Combinatorics.KMedian.Sparse.SparseSignedPreparation +OAI.Combinatorics.KMedian.Sparse.SparseSignedRounding +OAI.Combinatorics.KMedian.Sparse.SparseStarActivation +OAI.Combinatorics.KMedian.Sparse.SparseSupplierSupport +OAI.Combinatorics.KMedian.Sparse.SparseSupport +OAI.Combinatorics.KMedian.Sparse.SparseSurvival +OAI.Combinatorics.KMedian.Sparse.SparseTable +OAI.Combinatorics.KMedian.Sparse.SparseTargetSubset +OAI.Combinatorics.KMedian.Sparse.SparseWeightedPartial +OAI.Combinatorics.KMedian.Sparse.SparseWeightedRounding diff --git a/tasks/metric-k-median/solution/reference.py b/tasks/metric-k-median/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/metric-k-median/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/metric-k-median/solution/solve.sh b/tasks/metric-k-median/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..906e826d6ff1aa01fa75e594583e53b2cae2b63e --- /dev/null +++ b/tasks/metric-k-median/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MetricKMedian, i.e. module OAI.Combinatorics.KMedian.Main and the +# 569 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.KMedian.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MetricKMedian" diff --git a/tasks/metric-k-median/task.toml b/tasks/metric-k-median/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4a162afff5bb7900820a80e0137c95fa6bea8e6f --- /dev/null +++ b/tasks/metric-k-median/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/metric-k-median" +version = "1.0.0" +description = "Prove MetricKMedian (openai/math family 125: The approximation threshold for metric $k$-median) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MetricKMedian.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MetricKMedian" +family = "125" +family_title = "The approximation threshold for metric $k$-median" +subject = "Theoretical computer science" +theorems = ["OAI.MetricKMedian.main_finite_work"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.KMedian.Main" +reference_modules = 569 +reference_lean_bytes = 2480461 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1451 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13932 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/metric-k-median/tests/Challenge.lean b/tasks/metric-k-median/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a85012c9074cf8b86c1250c43db398e6812d798 --- /dev/null +++ b/tasks/metric-k-median/tests/Challenge.lean @@ -0,0 +1,68 @@ +import Mathlib + +namespace OAI + + + + +section +section +namespace MetricKMedian + +structure Instance where + n : ℕ + distance : Fin n → Fin n → ℚ + clients : Finset (Fin n) + facilities : Finset (Fin n) + k : ℕ + distance_nonneg : ∀ i j, 0 ≤ distance i j + distance_eq_zero : ∀ i j, distance i j = 0 ↔ i = j + distance_symm : ∀ i j, distance i j = distance j i + distance_triangle : ∀ i j h, distance i h ≤ distance i j + distance j h + k_pos : 1 ≤ k + k_le : k ≤ facilities.card + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length true ++ [false] ++ n.bits + +def encodeRat (q : ℚ) : List Bool := + [decide (q.num < 0)] ++ encodeNat q.num.natAbs ++ encodeNat q.den + +def encodeInstance (I : Instance) : List Bool := + encodeNat I.n ++ encodeNat I.k ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.clients)) ++ + List.ofFn (fun i : Fin I.n => decide (i ∈ I.facilities)) ++ + (List.ofFn (fun i : Fin I.n => + (List.ofFn (fun j : Fin I.n => encodeRat (I.distance i j))).flatten)).flatten + +noncomputable def nearest (I : Instance) (j : Fin I.n) (S : Finset (Fin I.n)) : ℝ := + if h : S.Nonempty then + (S.image (fun i => (I.distance j i : ℝ))).min' (h.image _) + else 0 + +noncomputable def cost (I : Instance) (S : Finset (Fin I.n)) : ℝ := + ∑ j ∈ I.clients, nearest I j S + +def feasibleSets (I : Instance) : Finset (Finset (Fin I.n)) := + I.facilities.powerset.filter (fun S => S.Nonempty ∧ S.card ≤ I.k) + +noncomputable def optimum (I : Instance) : ℝ := + if h : (feasibleSets I).Nonempty then + ((feasibleSets I).image (cost I)).min' (h.image _) + else 0 + +def Correct (epsilon : ℝ) (I : Instance) (output : List Bool) : Prop := + ∃ S : Finset (Fin I.n), S ⊆ I.facilities ∧ S.Nonempty ∧ S.card ≤ I.k ∧ + output = List.ofFn (fun i : Fin I.n => decide (i ∈ S)) ∧ + cost I S ≤ (1 + 2 / Real.exp 1 + epsilon) * optimum I + +theorem main_finite_work : ∀ ε : ℝ, 0 < ε → + ∃ (algorithm : Instance → List Bool) (P : Turing.TM2ComputableInPolyTime encodeInstance id algorithm), + (∀ k : P.tm.K, Finite (P.tm.Γ k)) ∧ ∀ I, Correct ε I (algorithm I) := by + sorry + +end MetricKMedian +end +end + +end OAI diff --git a/tasks/metric-k-median/tests/grade.py b/tasks/metric-k-median/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/metric-k-median/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/metric-k-median/tests/task.json b/tasks/metric-k-median/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fecddf8e9343f5efdb5168500cf2346ba2e53e78 --- /dev/null +++ b/tasks/metric-k-median/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MetricKMedian", + "comparator": { + "theorem_names": [ + "OAI.MetricKMedian.main_finite_work" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13032 +} \ No newline at end of file diff --git a/tasks/metric-k-median/tests/test.sh b/tasks/metric-k-median/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/metric-k-median/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/midpoint-lenses/environment/Dockerfile b/tasks/midpoint-lenses/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/midpoint-lenses/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/midpoint-lenses/environment/fetch_mathlib.sh b/tasks/midpoint-lenses/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/midpoint-lenses/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/midpoint-lenses/environment/lake-manifest.json b/tasks/midpoint-lenses/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/midpoint-lenses/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/midpoint-lenses/environment/lakefile.lean b/tasks/midpoint-lenses/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/midpoint-lenses/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/midpoint-lenses/environment/lean_setup.sh b/tasks/midpoint-lenses/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/midpoint-lenses/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/midpoint-lenses/environment/pack_submission.py b/tasks/midpoint-lenses/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/midpoint-lenses/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/midpoint-lenses/instruction.md b/tasks/midpoint-lenses/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d64ca51328ab65429d6b9d98c2c1ecd13e708e75 --- /dev/null +++ b/tasks/midpoint-lenses/instruction.md @@ -0,0 +1,394 @@ +# openai/math challenge `MidpointLenses` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `MidpointLenses`, also at `/opt/openai-math/challenges/MidpointLenses.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +/-! +# Segment tests, their completion, and coordinate functionals +-/ + + + +open scoped BigOperators +open Finset + +namespace SegmentLenses + +abbrev InfiniteVertex := List ℕ + +def ForestVertex := {p : ℕ × List ℕ // 1 ≤ p.1 ∧ p.2.length ≤ p.1} + +def ForestAncestor (a b : ForestVertex) : Prop := + a.val.1 = b.val.1 ∧ a.val.2.IsPrefix b.val.2 + +def IsInterval {V : Type*} (ancestor : V → V → Prop) (S : Finset V) : Prop := + ∃ a b, ancestor a b ∧ ∀ v, v ∈ S ↔ ancestor a v ∧ ancestor v b + +def Ancestral {V : Type*} (ancestor : V → V → Prop) (H : Finset V) : Prop := + ∀ ⦃a b⦄, b ∈ H → ancestor a b → a ∈ H + +class SegmentSystem (V : Type*) where + isSegment : Finset V → Prop + singleton : ∀ v, isSegment {v} + +structure SegmentFamily (V : Type*) [SegmentSystem V] where + sets : Finset (Finset V) + segment : ∀ S ∈ sets, SegmentSystem.isSegment S + disjoint : (sets : Set (Finset V)).PairwiseDisjoint id + +namespace SegmentFamily + +variable {V : Type*} [SegmentSystem V] + +def column (F : SegmentFamily V) (v : V) : EuclideanSpace ℝ F.sets := + by classical exact WithLp.toLp 2 (fun S => if v ∈ S.val then 1 else 0) + +def test (F : SegmentFamily V) : (V →₀ ℝ) →ₗ[ℝ] EuclideanSpace ℝ F.sets := + Finsupp.linearCombination ℝ F.column + +def seminorm (F : SegmentFamily V) : Seminorm ℝ (V →₀ ℝ) := + (normSeminorm ℝ (EuclideanSpace ℝ F.sets)).comp F.test + +def singleton (v : V) : SegmentFamily V where + sets := {{v}} + segment := by + intro S h + have he : S = {v} := Finset.mem_singleton.mp h + rw [he] + exact SegmentSystem.singleton v + disjoint := by + intro S hS T hT hne + simp only [Finset.mem_coe, Finset.mem_singleton] at hS hT + exact False.elim (hne (hS.trans hT.symm)) + +end SegmentFamily + +def segmentSeminorm (V : Type*) [SegmentSystem V] : Seminorm ℝ (V →₀ ℝ) := + ⨆ F : SegmentFamily V, F.seminorm + +def Test (V : Type*) := V →₀ ℝ + +namespace Test + +variable {V : Type*} +instance : AddCommGroup (Test V) := inferInstanceAs (AddCommGroup (V →₀ ℝ)) +instance : Module ℝ (Test V) := inferInstanceAs (Module ℝ (V →₀ ℝ)) + +def coeff (u : Test V) : V →₀ ℝ := u + +def ofFinsupp (u : V →₀ ℝ) : Test V := u + +variable [SegmentSystem V] +instance : Norm (Test V) where norm u := segmentSeminorm V u.coeff + +instance : NormedAddCommGroup (Test V) := by + have norm_column_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (v : V) : ‖F.column v‖ ≤ 1 := by + classical + by_cases hv : ∃ S ∈ F.sets, v ∈ S + · obtain ⟨S, hS, hvS⟩ := hv + have he : F.column v = PiLp.single 2 (⟨S, hS⟩ : F.sets) (1 : ℝ) := by + ext T + change (if v ∈ T.val then (1 : ℝ) else 0) = _ + by_cases hTS : T = ⟨S, hS⟩ + · subst T + simp [hvS] + · have hn : v ∉ T.val := by + intro hvT + have hne : T.val ≠ S := fun h => hTS (Subtype.ext h) + exact Finset.disjoint_left.mp (F.disjoint T.property hS hne) hvT hvS + simp [hTS, hn] + rw [he, PiLp.norm_single] + norm_num + · have he : F.column v = 0 := by + ext S + have hn : v ∉ S.val := fun h => hv ⟨S.val, S.property, h⟩ + simp [SegmentFamily.column, hn] + rw [he, norm_zero] + norm_num + have test_apply {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) (S : F.sets) : + F.test u S = ∑ v ∈ S.val, u v := by + classical + simp only [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum, + WithLp.ofLp_sum, Finset.sum_apply, PiLp.smul_apply, SegmentFamily.column, + smul_eq_mul] + simp only [mul_ite, mul_one, mul_zero] + rw [← Finset.sum_filter] + apply Finset.sum_subset + · intro v hv + exact (Finset.mem_filter.mp hv).2 + · intro v hv hnv + have hnot : v ∉ u.support := by + intro hvs + exact hnv (Finset.mem_filter.mpr ⟨hvs, hv⟩) + exact Finsupp.notMem_support_iff.mp hnot + have norm_test_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + ‖F.test u‖ ≤ ∑ v ∈ u.support, |u v| := by + classical + rw [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum] + calc + ‖∑ v ∈ u.support, u v • F.column v‖ ≤ + ∑ v ∈ u.support, ‖u v • F.column v‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := by + apply Finset.sum_le_sum + intro v hv + rw [norm_smul, Real.norm_eq_abs] + exact mul_le_of_le_one_right (abs_nonneg _) (norm_column_le F v) + have seminorm_sq {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + F.seminorm u ^ 2 = ∑ S : F.sets, (∑ v ∈ S.val, u v) ^ 2 := by + change ‖F.test u‖ ^ 2 = _ + rw [EuclideanSpace.real_norm_sq_eq] + apply Finset.sum_congr rfl + intro S _ + rw [test_apply] + have singleton_seminorm {V : Type _} [SegmentSystem V] (v : V) (u : V →₀ ℝ) : + (SegmentFamily.singleton v).seminorm u = |u v| := by + have h := seminorm_sq (SegmentFamily.singleton v) u + have hh : (∑ S : (SegmentFamily.singleton v).sets, (∑ w ∈ S.val, u w) ^ 2) = u v ^ 2 := by + exact (Finset.sum_coe_sort (SegmentFamily.singleton v).sets + (fun S : Finset V => (∑ w ∈ S, u w) ^ 2)).trans (by simp [SegmentFamily.singleton]) + rw [hh] at h + have hn := apply_nonneg (SegmentFamily.singleton v).seminorm u + nlinarith [sq_abs (u v), abs_nonneg (u v)] + have segmentTests_bdd (V : Type _) [SegmentSystem V] : + BddAbove (Set.range (SegmentFamily.seminorm (V := V))) := by + rw [Seminorm.bddAbove_iff] + refine ⟨fun u => ∑ v ∈ u.support, |u v|, ?_⟩ + rintro _ ⟨p, ⟨F, rfl⟩, rfl⟩ u + exact norm_test_le F u + have le_segmentSeminorm {V : Type _} [SegmentSystem V] + (F : SegmentFamily V) (u : V →₀ ℝ) : F.seminorm u ≤ segmentSeminorm V u := by + have h := le_ciSup (f := fun G : SegmentFamily V => G.seminorm) (segmentTests_bdd V) F + exact Seminorm.le_def.mp h u + have abs_coord_le {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) (v : V) : + |u v| ≤ segmentSeminorm V u := by + rw [← singleton_seminorm v u] + exact le_segmentSeminorm _ _ + have segmentSeminorm_eq_zero {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) : + segmentSeminorm V u = 0 ↔ u = 0 := by + constructor + · intro h + ext v + have hh := abs_coord_le u v + rw [h] at hh + simpa using hh + · rintro rfl + exact map_zero _ + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg u := apply_nonneg (segmentSeminorm V) u.coeff + norm_smul c u := map_smul_eq_mul (segmentSeminorm V) c u.coeff + norm_triangle u v := map_add_le_add (segmentSeminorm V) u.coeff v.coeff + norm_eq_zero_iff u := segmentSeminorm_eq_zero u.coeff } +instance : NormedSpace ℝ (Test V) where + norm_smul_le c u := le_of_eq (map_smul_eq_mul (segmentSeminorm V) c u.coeff) + +def evaluation (v : V) : Test V →L[ℝ] ℝ := by + have norm_column_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (v : V) : ‖F.column v‖ ≤ 1 := by + classical + by_cases hv : ∃ S ∈ F.sets, v ∈ S + · obtain ⟨S, hS, hvS⟩ := hv + have he : F.column v = PiLp.single 2 (⟨S, hS⟩ : F.sets) (1 : ℝ) := by + ext T + change (if v ∈ T.val then (1 : ℝ) else 0) = _ + by_cases hTS : T = ⟨S, hS⟩ + · subst T + simp [hvS] + · have hn : v ∉ T.val := by + intro hvT + have hne : T.val ≠ S := fun h => hTS (Subtype.ext h) + exact Finset.disjoint_left.mp (F.disjoint T.property hS hne) hvT hvS + simp [hTS, hn] + rw [he, PiLp.norm_single] + norm_num + · have he : F.column v = 0 := by + ext S + have hn : v ∉ S.val := fun h => hv ⟨S.val, S.property, h⟩ + simp [SegmentFamily.column, hn] + rw [he, norm_zero] + norm_num + have test_apply {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) (S : F.sets) : + F.test u S = ∑ v ∈ S.val, u v := by + classical + simp only [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum, + WithLp.ofLp_sum, Finset.sum_apply, PiLp.smul_apply, SegmentFamily.column, + smul_eq_mul] + simp only [mul_ite, mul_one, mul_zero] + rw [← Finset.sum_filter] + apply Finset.sum_subset + · intro v hv + exact (Finset.mem_filter.mp hv).2 + · intro v hv hnv + have hnot : v ∉ u.support := by + intro hvs + exact hnv (Finset.mem_filter.mpr ⟨hvs, hv⟩) + exact Finsupp.notMem_support_iff.mp hnot + have norm_test_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + ‖F.test u‖ ≤ ∑ v ∈ u.support, |u v| := by + classical + rw [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum] + calc + ‖∑ v ∈ u.support, u v • F.column v‖ ≤ + ∑ v ∈ u.support, ‖u v • F.column v‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := by + apply Finset.sum_le_sum + intro v hv + rw [norm_smul, Real.norm_eq_abs] + exact mul_le_of_le_one_right (abs_nonneg _) (norm_column_le F v) + have seminorm_sq {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + F.seminorm u ^ 2 = ∑ S : F.sets, (∑ v ∈ S.val, u v) ^ 2 := by + change ‖F.test u‖ ^ 2 = _ + rw [EuclideanSpace.real_norm_sq_eq] + apply Finset.sum_congr rfl + intro S _ + rw [test_apply] + have singleton_seminorm {V : Type _} [SegmentSystem V] (v : V) (u : V →₀ ℝ) : + (SegmentFamily.singleton v).seminorm u = |u v| := by + have h := seminorm_sq (SegmentFamily.singleton v) u + have hh : (∑ S : (SegmentFamily.singleton v).sets, (∑ w ∈ S.val, u w) ^ 2) = u v ^ 2 := by + exact (Finset.sum_coe_sort (SegmentFamily.singleton v).sets + (fun S : Finset V => (∑ w ∈ S, u w) ^ 2)).trans (by simp [SegmentFamily.singleton]) + rw [hh] at h + have hn := apply_nonneg (SegmentFamily.singleton v).seminorm u + nlinarith [sq_abs (u v), abs_nonneg (u v)] + have segmentTests_bdd (V : Type _) [SegmentSystem V] : + BddAbove (Set.range (SegmentFamily.seminorm (V := V))) := by + rw [Seminorm.bddAbove_iff] + refine ⟨fun u => ∑ v ∈ u.support, |u v|, ?_⟩ + rintro _ ⟨p, ⟨F, rfl⟩, rfl⟩ u + exact norm_test_le F u + have le_segmentSeminorm {V : Type _} [SegmentSystem V] + (F : SegmentFamily V) (u : V →₀ ℝ) : F.seminorm u ≤ segmentSeminorm V u := by + have h := le_ciSup (f := fun G : SegmentFamily V => G.seminorm) (segmentTests_bdd V) F + exact Seminorm.le_def.mp h u + have abs_coord_le {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) (v : V) : + |u v| ≤ segmentSeminorm V u := by + rw [← singleton_seminorm v u] + exact le_segmentSeminorm _ _ + exact let f : Test V →ₗ[ℝ] ℝ := + { toFun := fun u => u.coeff v + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + f.mkContinuous 1 (fun u => by + change |u.coeff v| ≤ 1 * segmentSeminorm V u.coeff + simpa only [one_mul] using abs_coord_le u.coeff v) + +end Test + +abbrev Primal (V : Type*) [SegmentSystem V] := UniformSpace.Completion (Test V) + +abbrev FullDual (V : Type*) [SegmentSystem V] := StrongDual ℝ (Primal V) + +def unitVector {V : Type*} [SegmentSystem V] (v : V) : Primal V := + (Test.ofFinsupp (Finsupp.single v 1) : Test V) + +def coordinate {V : Type*} [SegmentSystem V] (v : V) : FullDual V := + (Test.evaluation v).extend UniformSpace.Completion.toComplL + +def coordinateSpan (V : Type*) [SegmentSystem V] : Submodule ℝ (FullDual V) := + (Submodule.span ℝ (Set.range (coordinate (V := V)))).topologicalClosure + +abbrev CoordinatePredual (V : Type*) [SegmentSystem V] : Type _ := ↥(coordinateSpan V) + +def head {V : Type*} [SegmentSystem V] (H : Finset V) (x : FullDual V) : FullDual V := + ∑ v ∈ H, x (unitVector v) • coordinate v + +def tail {V : Type*} [SegmentSystem V] (H : Finset V) (x : FullDual V) : FullDual V := + x - head H x + +instance infiniteSegments : SegmentSystem InfiniteVertex where + isSegment := IsInterval List.IsPrefix + singleton v := by + refine ⟨v, v, List.prefix_rfl, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl; exact ⟨List.prefix_rfl, List.prefix_rfl⟩ + · rintro ⟨hvw, hwv⟩ + exact hwv.eq_of_length (Nat.le_antisymm hwv.length_le hvw.length_le) + +instance forestSegments : SegmentSystem ForestVertex where + isSegment := IsInterval ForestAncestor + singleton v := by + refine ⟨v, v, ⟨rfl, List.prefix_rfl⟩, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl; exact ⟨⟨rfl, List.prefix_rfl⟩, ⟨rfl, List.prefix_rfl⟩⟩ + · rintro ⟨hvw, hwv⟩ + exact Subtype.ext (Prod.ext hwv.1 (hwv.2.eq_of_length (Nat.le_antisymm hwv.2.length_le hvw.2.length_le))) + +abbrev J := Primal ForestVertex + +abbrev X := FullDual ForestVertex + +abbrev JInfinite := Primal InfiniteVertex + +abbrev BInfinite := CoordinatePredual InfiniteVertex + +theorem midpoint_lens_main : + (∀ (H : Finset ForestVertex) (_ : Ancestral ForestAncestor H) + (x y : X) (_ : x = head H x) (R : ℝ) (_ : 0 ≤ R) + (_ : ‖x + y‖ ≤ R) (_ : ‖x - y‖ ≤ R), + ‖tail H y‖ ≤ 2 * Real.sqrt (R ^ 2 - ‖x‖ ^ 2)) ∧ + (∀ (H : Finset InfiniteVertex) (_ : Ancestral List.IsPrefix H) + (x y : BInfinite) (_ : x.val = head H x.val) (R : ℝ) (_ : 0 ≤ R) + (_ : ‖x + y‖ ≤ R) (_ : ‖x - y‖ ≤ R), + ‖tail H y.val‖ ≤ 2 * Real.sqrt (R ^ 2 - ‖x‖ ^ 2)) := + sorry + +end SegmentLenses + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MidpointLenses.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SegmentLenses.midpoint_lens_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/midpoint-lenses/solution/closure.txt b/tasks/midpoint-lenses/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..20336e020682def1dd88977b9761980a3afb20b1 --- /dev/null +++ b/tasks/midpoint-lenses/solution/closure.txt @@ -0,0 +1,11 @@ +OAI.Analysis.SegmentLenses.AtomicBalls +OAI.Analysis.SegmentLenses.Basic +OAI.Analysis.SegmentLenses.Completed +OAI.Analysis.SegmentLenses.FiniteLaws +OAI.Analysis.SegmentLenses.GateRecovery +OAI.Analysis.SegmentLenses.HeadTests +OAI.Analysis.SegmentLenses.LawRecovery +OAI.Analysis.SegmentLenses.Main +OAI.Analysis.SegmentLenses.Pairing +OAI.Analysis.SegmentLenses.TailBudget +OAI.Analysis.SegmentLenses.TreeGeometry diff --git a/tasks/midpoint-lenses/solution/reference.py b/tasks/midpoint-lenses/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/midpoint-lenses/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/midpoint-lenses/solution/solve.sh b/tasks/midpoint-lenses/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7fd872bdaffcc6f8888736e7f4d6579b00c2cd41 --- /dev/null +++ b/tasks/midpoint-lenses/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MidpointLenses, i.e. module OAI.Analysis.SegmentLenses.Main and the +# 11 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.SegmentLenses.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MidpointLenses" diff --git a/tasks/midpoint-lenses/task.toml b/tasks/midpoint-lenses/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a43492260ed20e05b272941b03d2eaede3144c3d --- /dev/null +++ b/tasks/midpoint-lenses/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/midpoint-lenses" +version = "1.0.0" +description = "Prove MidpointLenses (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MidpointLenses.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MidpointLenses" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.SegmentLenses.midpoint_lens_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.SegmentLenses.Main" +reference_modules = 11 +reference_lean_bytes = 129714 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 634 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11816 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/midpoint-lenses/tests/Challenge.lean b/tasks/midpoint-lenses/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bca57d7af8242f487c540dc429477e629bd464f1 --- /dev/null +++ b/tasks/midpoint-lenses/tests/Challenge.lean @@ -0,0 +1,343 @@ +import Mathlib + +namespace OAI + +noncomputable section + +/-! +# Segment tests, their completion, and coordinate functionals +-/ + + + +open scoped BigOperators +open Finset + +namespace SegmentLenses + +abbrev InfiniteVertex := List ℕ + +def ForestVertex := {p : ℕ × List ℕ // 1 ≤ p.1 ∧ p.2.length ≤ p.1} + +def ForestAncestor (a b : ForestVertex) : Prop := + a.val.1 = b.val.1 ∧ a.val.2.IsPrefix b.val.2 + +def IsInterval {V : Type*} (ancestor : V → V → Prop) (S : Finset V) : Prop := + ∃ a b, ancestor a b ∧ ∀ v, v ∈ S ↔ ancestor a v ∧ ancestor v b + +def Ancestral {V : Type*} (ancestor : V → V → Prop) (H : Finset V) : Prop := + ∀ ⦃a b⦄, b ∈ H → ancestor a b → a ∈ H + +class SegmentSystem (V : Type*) where + isSegment : Finset V → Prop + singleton : ∀ v, isSegment {v} + +structure SegmentFamily (V : Type*) [SegmentSystem V] where + sets : Finset (Finset V) + segment : ∀ S ∈ sets, SegmentSystem.isSegment S + disjoint : (sets : Set (Finset V)).PairwiseDisjoint id + +namespace SegmentFamily + +variable {V : Type*} [SegmentSystem V] + +def column (F : SegmentFamily V) (v : V) : EuclideanSpace ℝ F.sets := + by classical exact WithLp.toLp 2 (fun S => if v ∈ S.val then 1 else 0) + +def test (F : SegmentFamily V) : (V →₀ ℝ) →ₗ[ℝ] EuclideanSpace ℝ F.sets := + Finsupp.linearCombination ℝ F.column + +def seminorm (F : SegmentFamily V) : Seminorm ℝ (V →₀ ℝ) := + (normSeminorm ℝ (EuclideanSpace ℝ F.sets)).comp F.test + +def singleton (v : V) : SegmentFamily V where + sets := {{v}} + segment := by + intro S h + have he : S = {v} := Finset.mem_singleton.mp h + rw [he] + exact SegmentSystem.singleton v + disjoint := by + intro S hS T hT hne + simp only [Finset.mem_coe, Finset.mem_singleton] at hS hT + exact False.elim (hne (hS.trans hT.symm)) + +end SegmentFamily + +def segmentSeminorm (V : Type*) [SegmentSystem V] : Seminorm ℝ (V →₀ ℝ) := + ⨆ F : SegmentFamily V, F.seminorm + +def Test (V : Type*) := V →₀ ℝ + +namespace Test + +variable {V : Type*} +instance : AddCommGroup (Test V) := inferInstanceAs (AddCommGroup (V →₀ ℝ)) +instance : Module ℝ (Test V) := inferInstanceAs (Module ℝ (V →₀ ℝ)) + +def coeff (u : Test V) : V →₀ ℝ := u + +def ofFinsupp (u : V →₀ ℝ) : Test V := u + +variable [SegmentSystem V] +instance : Norm (Test V) where norm u := segmentSeminorm V u.coeff + +instance : NormedAddCommGroup (Test V) := by + have norm_column_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (v : V) : ‖F.column v‖ ≤ 1 := by + classical + by_cases hv : ∃ S ∈ F.sets, v ∈ S + · obtain ⟨S, hS, hvS⟩ := hv + have he : F.column v = PiLp.single 2 (⟨S, hS⟩ : F.sets) (1 : ℝ) := by + ext T + change (if v ∈ T.val then (1 : ℝ) else 0) = _ + by_cases hTS : T = ⟨S, hS⟩ + · subst T + simp [hvS] + · have hn : v ∉ T.val := by + intro hvT + have hne : T.val ≠ S := fun h => hTS (Subtype.ext h) + exact Finset.disjoint_left.mp (F.disjoint T.property hS hne) hvT hvS + simp [hTS, hn] + rw [he, PiLp.norm_single] + norm_num + · have he : F.column v = 0 := by + ext S + have hn : v ∉ S.val := fun h => hv ⟨S.val, S.property, h⟩ + simp [SegmentFamily.column, hn] + rw [he, norm_zero] + norm_num + have test_apply {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) (S : F.sets) : + F.test u S = ∑ v ∈ S.val, u v := by + classical + simp only [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum, + WithLp.ofLp_sum, Finset.sum_apply, PiLp.smul_apply, SegmentFamily.column, + smul_eq_mul] + simp only [mul_ite, mul_one, mul_zero] + rw [← Finset.sum_filter] + apply Finset.sum_subset + · intro v hv + exact (Finset.mem_filter.mp hv).2 + · intro v hv hnv + have hnot : v ∉ u.support := by + intro hvs + exact hnv (Finset.mem_filter.mpr ⟨hvs, hv⟩) + exact Finsupp.notMem_support_iff.mp hnot + have norm_test_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + ‖F.test u‖ ≤ ∑ v ∈ u.support, |u v| := by + classical + rw [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum] + calc + ‖∑ v ∈ u.support, u v • F.column v‖ ≤ + ∑ v ∈ u.support, ‖u v • F.column v‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := by + apply Finset.sum_le_sum + intro v hv + rw [norm_smul, Real.norm_eq_abs] + exact mul_le_of_le_one_right (abs_nonneg _) (norm_column_le F v) + have seminorm_sq {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + F.seminorm u ^ 2 = ∑ S : F.sets, (∑ v ∈ S.val, u v) ^ 2 := by + change ‖F.test u‖ ^ 2 = _ + rw [EuclideanSpace.real_norm_sq_eq] + apply Finset.sum_congr rfl + intro S _ + rw [test_apply] + have singleton_seminorm {V : Type _} [SegmentSystem V] (v : V) (u : V →₀ ℝ) : + (SegmentFamily.singleton v).seminorm u = |u v| := by + have h := seminorm_sq (SegmentFamily.singleton v) u + have hh : (∑ S : (SegmentFamily.singleton v).sets, (∑ w ∈ S.val, u w) ^ 2) = u v ^ 2 := by + exact (Finset.sum_coe_sort (SegmentFamily.singleton v).sets + (fun S : Finset V => (∑ w ∈ S, u w) ^ 2)).trans (by simp [SegmentFamily.singleton]) + rw [hh] at h + have hn := apply_nonneg (SegmentFamily.singleton v).seminorm u + nlinarith [sq_abs (u v), abs_nonneg (u v)] + have segmentTests_bdd (V : Type _) [SegmentSystem V] : + BddAbove (Set.range (SegmentFamily.seminorm (V := V))) := by + rw [Seminorm.bddAbove_iff] + refine ⟨fun u => ∑ v ∈ u.support, |u v|, ?_⟩ + rintro _ ⟨p, ⟨F, rfl⟩, rfl⟩ u + exact norm_test_le F u + have le_segmentSeminorm {V : Type _} [SegmentSystem V] + (F : SegmentFamily V) (u : V →₀ ℝ) : F.seminorm u ≤ segmentSeminorm V u := by + have h := le_ciSup (f := fun G : SegmentFamily V => G.seminorm) (segmentTests_bdd V) F + exact Seminorm.le_def.mp h u + have abs_coord_le {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) (v : V) : + |u v| ≤ segmentSeminorm V u := by + rw [← singleton_seminorm v u] + exact le_segmentSeminorm _ _ + have segmentSeminorm_eq_zero {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) : + segmentSeminorm V u = 0 ↔ u = 0 := by + constructor + · intro h + ext v + have hh := abs_coord_le u v + rw [h] at hh + simpa using hh + · rintro rfl + exact map_zero _ + exact NormedAddCommGroup.ofCore (𝕜 := ℝ) { + norm_nonneg u := apply_nonneg (segmentSeminorm V) u.coeff + norm_smul c u := map_smul_eq_mul (segmentSeminorm V) c u.coeff + norm_triangle u v := map_add_le_add (segmentSeminorm V) u.coeff v.coeff + norm_eq_zero_iff u := segmentSeminorm_eq_zero u.coeff } +instance : NormedSpace ℝ (Test V) where + norm_smul_le c u := le_of_eq (map_smul_eq_mul (segmentSeminorm V) c u.coeff) + +def evaluation (v : V) : Test V →L[ℝ] ℝ := by + have norm_column_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (v : V) : ‖F.column v‖ ≤ 1 := by + classical + by_cases hv : ∃ S ∈ F.sets, v ∈ S + · obtain ⟨S, hS, hvS⟩ := hv + have he : F.column v = PiLp.single 2 (⟨S, hS⟩ : F.sets) (1 : ℝ) := by + ext T + change (if v ∈ T.val then (1 : ℝ) else 0) = _ + by_cases hTS : T = ⟨S, hS⟩ + · subst T + simp [hvS] + · have hn : v ∉ T.val := by + intro hvT + have hne : T.val ≠ S := fun h => hTS (Subtype.ext h) + exact Finset.disjoint_left.mp (F.disjoint T.property hS hne) hvT hvS + simp [hTS, hn] + rw [he, PiLp.norm_single] + norm_num + · have he : F.column v = 0 := by + ext S + have hn : v ∉ S.val := fun h => hv ⟨S.val, S.property, h⟩ + simp [SegmentFamily.column, hn] + rw [he, norm_zero] + norm_num + have test_apply {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) (S : F.sets) : + F.test u S = ∑ v ∈ S.val, u v := by + classical + simp only [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum, + WithLp.ofLp_sum, Finset.sum_apply, PiLp.smul_apply, SegmentFamily.column, + smul_eq_mul] + simp only [mul_ite, mul_one, mul_zero] + rw [← Finset.sum_filter] + apply Finset.sum_subset + · intro v hv + exact (Finset.mem_filter.mp hv).2 + · intro v hv hnv + have hnot : v ∉ u.support := by + intro hvs + exact hnv (Finset.mem_filter.mpr ⟨hvs, hv⟩) + exact Finsupp.notMem_support_iff.mp hnot + have norm_test_le {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + ‖F.test u‖ ≤ ∑ v ∈ u.support, |u v| := by + classical + rw [SegmentFamily.test, Finsupp.linearCombination_apply, Finsupp.sum] + calc + ‖∑ v ∈ u.support, u v • F.column v‖ ≤ + ∑ v ∈ u.support, ‖u v • F.column v‖ := norm_sum_le _ _ + _ ≤ ∑ v ∈ u.support, |u v| := by + apply Finset.sum_le_sum + intro v hv + rw [norm_smul, Real.norm_eq_abs] + exact mul_le_of_le_one_right (abs_nonneg _) (norm_column_le F v) + have seminorm_sq {V : Type _} [SegmentSystem V] (F : SegmentFamily V) (u : V →₀ ℝ) : + F.seminorm u ^ 2 = ∑ S : F.sets, (∑ v ∈ S.val, u v) ^ 2 := by + change ‖F.test u‖ ^ 2 = _ + rw [EuclideanSpace.real_norm_sq_eq] + apply Finset.sum_congr rfl + intro S _ + rw [test_apply] + have singleton_seminorm {V : Type _} [SegmentSystem V] (v : V) (u : V →₀ ℝ) : + (SegmentFamily.singleton v).seminorm u = |u v| := by + have h := seminorm_sq (SegmentFamily.singleton v) u + have hh : (∑ S : (SegmentFamily.singleton v).sets, (∑ w ∈ S.val, u w) ^ 2) = u v ^ 2 := by + exact (Finset.sum_coe_sort (SegmentFamily.singleton v).sets + (fun S : Finset V => (∑ w ∈ S, u w) ^ 2)).trans (by simp [SegmentFamily.singleton]) + rw [hh] at h + have hn := apply_nonneg (SegmentFamily.singleton v).seminorm u + nlinarith [sq_abs (u v), abs_nonneg (u v)] + have segmentTests_bdd (V : Type _) [SegmentSystem V] : + BddAbove (Set.range (SegmentFamily.seminorm (V := V))) := by + rw [Seminorm.bddAbove_iff] + refine ⟨fun u => ∑ v ∈ u.support, |u v|, ?_⟩ + rintro _ ⟨p, ⟨F, rfl⟩, rfl⟩ u + exact norm_test_le F u + have le_segmentSeminorm {V : Type _} [SegmentSystem V] + (F : SegmentFamily V) (u : V →₀ ℝ) : F.seminorm u ≤ segmentSeminorm V u := by + have h := le_ciSup (f := fun G : SegmentFamily V => G.seminorm) (segmentTests_bdd V) F + exact Seminorm.le_def.mp h u + have abs_coord_le {V : Type _} [SegmentSystem V] (u : V →₀ ℝ) (v : V) : + |u v| ≤ segmentSeminorm V u := by + rw [← singleton_seminorm v u] + exact le_segmentSeminorm _ _ + exact let f : Test V →ₗ[ℝ] ℝ := + { toFun := fun u => u.coeff v + map_add' := fun _ _ => rfl + map_smul' := fun _ _ => rfl } + f.mkContinuous 1 (fun u => by + change |u.coeff v| ≤ 1 * segmentSeminorm V u.coeff + simpa only [one_mul] using abs_coord_le u.coeff v) + +end Test + +abbrev Primal (V : Type*) [SegmentSystem V] := UniformSpace.Completion (Test V) + +abbrev FullDual (V : Type*) [SegmentSystem V] := StrongDual ℝ (Primal V) + +def unitVector {V : Type*} [SegmentSystem V] (v : V) : Primal V := + (Test.ofFinsupp (Finsupp.single v 1) : Test V) + +def coordinate {V : Type*} [SegmentSystem V] (v : V) : FullDual V := + (Test.evaluation v).extend UniformSpace.Completion.toComplL + +def coordinateSpan (V : Type*) [SegmentSystem V] : Submodule ℝ (FullDual V) := + (Submodule.span ℝ (Set.range (coordinate (V := V)))).topologicalClosure + +abbrev CoordinatePredual (V : Type*) [SegmentSystem V] : Type _ := ↥(coordinateSpan V) + +def head {V : Type*} [SegmentSystem V] (H : Finset V) (x : FullDual V) : FullDual V := + ∑ v ∈ H, x (unitVector v) • coordinate v + +def tail {V : Type*} [SegmentSystem V] (H : Finset V) (x : FullDual V) : FullDual V := + x - head H x + +instance infiniteSegments : SegmentSystem InfiniteVertex where + isSegment := IsInterval List.IsPrefix + singleton v := by + refine ⟨v, v, List.prefix_rfl, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl; exact ⟨List.prefix_rfl, List.prefix_rfl⟩ + · rintro ⟨hvw, hwv⟩ + exact hwv.eq_of_length (Nat.le_antisymm hwv.length_le hvw.length_le) + +instance forestSegments : SegmentSystem ForestVertex where + isSegment := IsInterval ForestAncestor + singleton v := by + refine ⟨v, v, ⟨rfl, List.prefix_rfl⟩, ?_⟩ + intro w + simp only [Finset.mem_singleton] + constructor + · rintro rfl; exact ⟨⟨rfl, List.prefix_rfl⟩, ⟨rfl, List.prefix_rfl⟩⟩ + · rintro ⟨hvw, hwv⟩ + exact Subtype.ext (Prod.ext hwv.1 (hwv.2.eq_of_length (Nat.le_antisymm hwv.2.length_le hvw.2.length_le))) + +abbrev J := Primal ForestVertex + +abbrev X := FullDual ForestVertex + +abbrev JInfinite := Primal InfiniteVertex + +abbrev BInfinite := CoordinatePredual InfiniteVertex + +theorem midpoint_lens_main : + (∀ (H : Finset ForestVertex) (_ : Ancestral ForestAncestor H) + (x y : X) (_ : x = head H x) (R : ℝ) (_ : 0 ≤ R) + (_ : ‖x + y‖ ≤ R) (_ : ‖x - y‖ ≤ R), + ‖tail H y‖ ≤ 2 * Real.sqrt (R ^ 2 - ‖x‖ ^ 2)) ∧ + (∀ (H : Finset InfiniteVertex) (_ : Ancestral List.IsPrefix H) + (x y : BInfinite) (_ : x.val = head H x.val) (R : ℝ) (_ : 0 ≤ R) + (_ : ‖x + y‖ ≤ R) (_ : ‖x - y‖ ≤ R), + ‖tail H y.val‖ ≤ 2 * Real.sqrt (R ^ 2 - ‖x‖ ^ 2)) := + sorry + +end SegmentLenses + +end + +end OAI diff --git a/tasks/midpoint-lenses/tests/grade.py b/tasks/midpoint-lenses/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/midpoint-lenses/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/midpoint-lenses/tests/task.json b/tasks/midpoint-lenses/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f5cf2ee485c8feb752ae1a5a549a0060fafb0dec --- /dev/null +++ b/tasks/midpoint-lenses/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MidpointLenses", + "comparator": { + "theorem_names": [ + "OAI.SegmentLenses.midpoint_lens_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10916 +} \ No newline at end of file diff --git a/tasks/midpoint-lenses/tests/test.sh b/tasks/midpoint-lenses/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/midpoint-lenses/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/min-uncut/environment/Dockerfile b/tasks/min-uncut/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/min-uncut/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/min-uncut/environment/fetch_mathlib.sh b/tasks/min-uncut/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/min-uncut/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/min-uncut/environment/lake-manifest.json b/tasks/min-uncut/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/min-uncut/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/min-uncut/environment/lakefile.lean b/tasks/min-uncut/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/min-uncut/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/min-uncut/environment/lean_setup.sh b/tasks/min-uncut/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/min-uncut/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/min-uncut/environment/pack_submission.py b/tasks/min-uncut/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/min-uncut/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/min-uncut/instruction.md b/tasks/min-uncut/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ba9145073fe81e6371c16891aaf216d01b49cf84 --- /dev/null +++ b/tasks/min-uncut/instruction.md @@ -0,0 +1,181 @@ +# openai/math challenge `MinUncut` (family 102) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 102 of the release, *The Unique Games Conjecture and optimal approximation thresholds* +(Theoretical computer science). The family as a whole: Proves Khot's Unique Games Conjecture. Independent direct reductions also establish NP-hardness, on unweighted graphs, of approximation beyond the Goemans–Williamson ratio for Max-Cut, below factor two for Vertex Cover, and within any fixed constant factor for Min-UnCut and directed feedback vertex set. These direct proofs use established PCP and Label Cover hardness results. + +The challenge is `MinUncut`, also at `/opt/openai-math/challenges/MinUncut.lean`: + +```lean +import Mathlib + +namespace OAI + + + + + + + + + + +namespace MinUncutGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end MinUncutGames.BinaryFormula + +namespace MinUncutGames.BinaryEncoding +open BinaryFormula + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def nameBits (name : Nat) : List Bool := frame name.bits + +def literalBits (literal : Literal) : List Bool := + literal.positive :: nameBits literal.name + +def clauseBits (clause : Clause) : List Bool := + literalBits clause[0] ++ literalBits clause[1] ++ literalBits clause[2] + +def clausesBits : List Clause → List Bool + | [] => [false] + | clause :: clauses => true :: (clauseBits clause ++ clausesBits clauses) + +def formulaBits (formula : Formula) : List Bool := clausesBits formula.clauses + +end MinUncutGames.BinaryEncoding + +namespace MinUncut +open MinUncutGames.BinaryFormula MinUncutGames.BinaryEncoding + + + +structure Output where + vertices : ℕ + adjacent : Fin vertices → Fin vertices → Bool + symmetric : ∀ u v, adjacent u v = adjacent v u + loopless : ∀ u, adjacent u u = false + threshold : ℕ + threshold_pos : 1 ≤ threshold + + + +def Output.uncut (G : Output) (cut : Fin G.vertices → Bool) : ℕ := + (Finset.univ.filter fun uv : Fin G.vertices × Fin G.vertices => + uv.1 < uv.2 ∧ G.adjacent uv.1 uv.2 = true ∧ cut uv.1 = cut uv.2).card + + + +noncomputable def Output.opt (G : Output) : ℕ := + (Finset.univ.image G.uncut).min' (by + exact Finset.image_nonempty.mpr Finset.univ_nonempty) + + + +def Output.bits (G : Output) : List Bool := + nameBits G.vertices ++ + ((List.finRange G.vertices).flatMap fun u => + (List.finRange G.vertices).map fun v => G.adjacent u v) ++ + nameBits G.threshold + + + +def inputBits (input : ℕ × Formula) : List Bool := + nameBits input.1 ++ formulaBits input.2 + + + + + +structure Reduction where + reduce : ℕ → Formula → Output + machine : Turing.TM2Computable inputBits Output.bits (fun p => reduce p.1 p.2) + finiteAlphabet : ∀ k : machine.tm.K, Finite (machine.tm.Γ k) + time : ℕ → Polynomial ℕ + runtime : ∀ K φ, + Turing.TM2OutputsInTime machine.tm + ((inputBits (K, φ)).map machine.inputAlphabet.symm) + (some (((reduce K φ).bits).map machine.outputAlphabet.symm)) + ((time K).eval (formulaBits φ).length) + size : ℕ → Polynomial ℕ + output_size : ∀ K φ, + (reduce K φ).vertices + (reduce K φ).bits.length ≤ + (size K).eval (formulaBits φ).length + yes : ∀ K, 2 ≤ K → ∀ φ, φ.Satisfiable → + (reduce K φ).opt ≤ (reduce K φ).threshold + no : ∀ K, 2 ≤ K → ∀ φ, ¬ φ.Satisfiable → + K * (reduce K φ).threshold < (reduce K φ).opt + +end MinUncut + +namespace MinUncut + +theorem main : Nonempty Reduction := by + sorry + +end MinUncut + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/MinUncut.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MinUncut.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/min-uncut/solution/closure.txt b/tasks/min-uncut/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9969714a13d77c0738d8565e6a946c2aa6fa1496 --- /dev/null +++ b/tasks/min-uncut/solution/closure.txt @@ -0,0 +1,375 @@ +OAI.Computability.MinUncut.Analysis.CenteredPointCorrelationPower +OAI.Computability.MinUncut.Analysis.FaceCorrelation +OAI.Computability.MinUncut.Analysis.FiniteGaussianLaw +OAI.Computability.MinUncut.Analysis.FreshCorrelation +OAI.Computability.MinUncut.Analysis.GaussNegPreserving +OAI.Computability.MinUncut.Analysis.GaussianAssembly +OAI.Computability.MinUncut.Analysis.GaussianDensityError +OAI.Computability.MinUncut.Analysis.GaussianDistance +OAI.Computability.MinUncut.Analysis.GaussianPacking +OAI.Computability.MinUncut.Analysis.GaussianQuadrature +OAI.Computability.MinUncut.Analysis.GaussianRounding +OAI.Computability.MinUncut.Analysis.GaussianRows +OAI.Computability.MinUncut.Analysis.GaussianSliceContinuous +OAI.Computability.MinUncut.Analysis.GaussianSmallBall +OAI.Computability.MinUncut.Analysis.Gradient +OAI.Computability.MinUncut.Analysis.GradientEnergyFirstTables +OAI.Computability.MinUncut.Analysis.Hermite +OAI.Computability.MinUncut.Analysis.HermiteComponent +OAI.Computability.MinUncut.Analysis.LiteralGaussian +OAI.Computability.MinUncut.Analysis.LowGradient +OAI.Computability.MinUncut.Analysis.LowGradientEnergyLowerWeighted +OAI.Computability.MinUncut.Analysis.MaskHermite +OAI.Computability.MinUncut.Analysis.OddAtom +OAI.Computability.MinUncut.Analysis.OddMaxTranslate +OAI.Computability.MinUncut.Analysis.RationalRowNoise +OAI.Computability.MinUncut.Analysis.RowProjectedGradient +OAI.Computability.MinUncut.Analysis.SelectedProjectGaussianLocal +OAI.Computability.MinUncut.Analysis.SmoothingRho +OAI.Computability.MinUncut.Analysis.UniformCube +OAI.Computability.MinUncut.Encoding.ArbitraryProductWeights +OAI.Computability.MinUncut.Encoding.Binary +OAI.Computability.MinUncut.Encoding.BinaryCoordinates +OAI.Computability.MinUncut.Encoding.BinaryLinear +OAI.Computability.MinUncut.Encoding.BitOutputBound +OAI.Computability.MinUncut.Encoding.DecodedGraphCore +OAI.Computability.MinUncut.Encoding.Decoder +OAI.Computability.MinUncut.Encoding.DerivedResolver +OAI.Computability.MinUncut.Encoding.FormulaEncoding +OAI.Computability.MinUncut.Encoding.GameDecoder +OAI.Computability.MinUncut.Encoding.GameEncoding +OAI.Computability.MinUncut.Encoding.LocalDecoder +OAI.Computability.MinUncut.Encoding.PortTableEncoding +OAI.Computability.MinUncut.Encoding.QuestionEncoding +OAI.Computability.MinUncut.Encoding.RawGraphEncoding +OAI.Computability.MinUncut.Encoding.Serialization +OAI.Computability.MinUncut.Encoding.SignatureEncoding +OAI.Computability.MinUncut.Encoding.ThreeBitTest +OAI.Computability.MinUncut.Encoding.UniformEncoding +OAI.Computability.MinUncut.Estimates.ActualBoxBound +OAI.Computability.MinUncut.Estimates.AlgebraicSigns +OAI.Computability.MinUncut.Estimates.AnalyticOuter +OAI.Computability.MinUncut.Estimates.ArraySum +OAI.Computability.MinUncut.Estimates.Assembly +OAI.Computability.MinUncut.Estimates.Away +OAI.Computability.MinUncut.Estimates.Basic +OAI.Computability.MinUncut.Estimates.Basic2 +OAI.Computability.MinUncut.Estimates.BlocksEffectivity +OAI.Computability.MinUncut.Estimates.Bridge +OAI.Computability.MinUncut.Estimates.CodeComputability +OAI.Computability.MinUncut.Estimates.CodeContinuations +OAI.Computability.MinUncut.Estimates.CodeIteration +OAI.Computability.MinUncut.Estimates.CoefficientMoments +OAI.Computability.MinUncut.Estimates.CollisionIndicator +OAI.Computability.MinUncut.Estimates.ComparisonSoundness +OAI.Computability.MinUncut.Estimates.ConditionalRounding +OAI.Computability.MinUncut.Estimates.Convolution +OAI.Computability.MinUncut.Estimates.CountedWordParser +OAI.Computability.MinUncut.Estimates.CoupledAnswer +OAI.Computability.MinUncut.Estimates.Density +OAI.Computability.MinUncut.Estimates.EraseAway +OAI.Computability.MinUncut.Estimates.EuclideanInvariantScore +OAI.Computability.MinUncut.Estimates.ExpectResampleRow +OAI.Computability.MinUncut.Estimates.ExpressionEffectivity +OAI.Computability.MinUncut.Estimates.ExpressionOutput +OAI.Computability.MinUncut.Estimates.F2 +OAI.Computability.MinUncut.Estimates.FaceUpdateSelf +OAI.Computability.MinUncut.Estimates.FiberPrefix +OAI.Computability.MinUncut.Estimates.FirstError +OAI.Computability.MinUncut.Estimates.FourthTest +OAI.Computability.MinUncut.Estimates.HeapInitializationMath +OAI.Computability.MinUncut.Estimates.IndexedLists +OAI.Computability.MinUncut.Estimates.InnerAssembly +OAI.Computability.MinUncut.Estimates.InnerUniform +OAI.Computability.MinUncut.Estimates.InputData +OAI.Computability.MinUncut.Estimates.IntegralExpect +OAI.Computability.MinUncut.Estimates.IterationMagnitude +OAI.Computability.MinUncut.Estimates.LiftedVectors +OAI.Computability.MinUncut.Estimates.ListDecoding +OAI.Computability.MinUncut.Estimates.LiteralLocalTemplates +OAI.Computability.MinUncut.Estimates.LiteralTestQueries +OAI.Computability.MinUncut.Estimates.LocalBodyEffectivity +OAI.Computability.MinUncut.Estimates.MemLpMaskProject +OAI.Computability.MinUncut.Estimates.NormalizedWeights +OAI.Computability.MinUncut.Estimates.OuterRemainder +OAI.Computability.MinUncut.Estimates.OuterSampling +OAI.Computability.MinUncut.Estimates.OutputSize +OAI.Computability.MinUncut.Estimates.PatchDensity +OAI.Computability.MinUncut.Estimates.PatchExpectation +OAI.Computability.MinUncut.Estimates.PointField +OAI.Computability.MinUncut.Estimates.PolynomialRecursor +OAI.Computability.MinUncut.Estimates.Rest +OAI.Computability.MinUncut.Estimates.ReversePrefixProgram +OAI.Computability.MinUncut.Estimates.RowListBridge +OAI.Computability.MinUncut.Estimates.SamplerAssembly +OAI.Computability.MinUncut.Estimates.SamplerCost +OAI.Computability.MinUncut.Estimates.SecondFailureIndicator +OAI.Computability.MinUncut.Estimates.SelectedProject +OAI.Computability.MinUncut.Estimates.SelectedProjectSliceContinuous +OAI.Computability.MinUncut.Estimates.SelectedSyntax +OAI.Computability.MinUncut.Estimates.SingleRow +OAI.Computability.MinUncut.Estimates.TM2Costed +OAI.Computability.MinUncut.Estimates.TableLawPacking +OAI.Computability.MinUncut.Estimates.TableTestFunctions +OAI.Computability.MinUncut.Estimates.TemplateExpressions +OAI.Computability.MinUncut.Estimates.UniformAlgebra +OAI.Computability.MinUncut.Estimates.UniformBoolean +OAI.Computability.MinUncut.Estimates.UniformEquation +OAI.Computability.MinUncut.Estimates.UniformEquationOutput +OAI.Computability.MinUncut.Estimates.UniformFaceArray +OAI.Computability.MinUncut.Estimates.UniformGrid +OAI.Computability.MinUncut.Estimates.UniformOutput +OAI.Computability.MinUncut.Estimates.UniformProduct +OAI.Computability.MinUncut.Estimates.UniformRestrict +OAI.Computability.MinUncut.Estimates.UniformSets +OAI.Computability.MinUncut.Estimates.UniformTransport +OAI.Computability.MinUncut.Estimates.WeightedTestLaw +OAI.Computability.MinUncut.Games.Actual +OAI.Computability.MinUncut.Games.AdaptiveKernel +OAI.Computability.MinUncut.Games.AffineLabels +OAI.Computability.MinUncut.Games.Basic +OAI.Computability.MinUncut.Games.FinalCNFHeader +OAI.Computability.MinUncut.Games.FinalCNFOutput +OAI.Computability.MinUncut.Games.FinalCNFPattern +OAI.Computability.MinUncut.Games.FinalCNFStream +OAI.Computability.MinUncut.Games.FiniteNoise +OAI.Computability.MinUncut.Games.GraphCounterModel +OAI.Computability.MinUncut.Games.GraphIterationBounds +OAI.Computability.MinUncut.Games.HintSections +OAI.Computability.MinUncut.Games.HintSimulation +OAI.Computability.MinUncut.Games.HintSoundness +OAI.Computability.MinUncut.Games.IncidenceProbability +OAI.Computability.MinUncut.Games.JointCoefficient +OAI.Computability.MinUncut.Games.JointHintBound +OAI.Computability.MinUncut.Games.JointHintSampling +OAI.Computability.MinUncut.Games.JointInner +OAI.Computability.MinUncut.Games.KernelSampling +OAI.Computability.MinUncut.Games.LabelBound +OAI.Computability.MinUncut.Games.MaskRowKernel +OAI.Computability.MinUncut.Games.OuterQuestions +OAI.Computability.MinUncut.Games.Parameters +OAI.Computability.MinUncut.Games.Pinsker +OAI.Computability.MinUncut.Games.PoweringGlobalEnumeration +OAI.Computability.MinUncut.Games.PoweringInitializeFrame +OAI.Computability.MinUncut.Games.PoweringMasterState +OAI.Computability.MinUncut.Games.PoweringPlanBudget +OAI.Computability.MinUncut.Games.PoweringPolynomialBudget +OAI.Computability.MinUncut.Games.QuestionArithmetic +OAI.Computability.MinUncut.Games.QuestionExpressions +OAI.Computability.MinUncut.Games.Reindexing +OAI.Computability.MinUncut.Games.Sampling +OAI.Computability.MinUncut.Games.Target +OAI.Computability.MinUncut.Games.TotalVariation +OAI.Computability.MinUncut.Games.TripleKernel +OAI.Computability.MinUncut.Graphs.CanonicalPathGraph +OAI.Computability.MinUncut.Graphs.CanonicalSamplerGraph +OAI.Computability.MinUncut.Graphs.CompleteGraphProgram +OAI.Computability.MinUncut.Graphs.DemandExpressions +OAI.Computability.MinUncut.Graphs.DemandOrder +OAI.Computability.MinUncut.Graphs.DemandQueryEffectivity +OAI.Computability.MinUncut.Graphs.DemandStageEffectivity +OAI.Computability.MinUncut.Graphs.EdgeMean +OAI.Computability.MinUncut.Graphs.GeneratedGraph +OAI.Computability.MinUncut.Graphs.Graph +OAI.Computability.MinUncut.Graphs.GraphOutput +OAI.Computability.MinUncut.Graphs.GraphSize +OAI.Computability.MinUncut.Graphs.GraphWordCodec +OAI.Computability.MinUncut.Graphs.HonestBudgets +OAI.Computability.MinUncut.Graphs.HonestComparisons +OAI.Computability.MinUncut.Graphs.HonestRows +OAI.Computability.MinUncut.Graphs.SelectedGraphEndpoint +OAI.Computability.MinUncut.Graphs.SignedGraph +OAI.Computability.MinUncut.Graphs.UnboundedGraphBase +OAI.Computability.MinUncut.Graphs.Vertex +OAI.Computability.MinUncut.Graphs.VertexInjective +OAI.Computability.MinUncut.Machines.Addresses +OAI.Computability.MinUncut.Machines.Alphabet +OAI.Computability.MinUncut.Machines.AlphabetBudget +OAI.Computability.MinUncut.Machines.AlphabetGraph +OAI.Computability.MinUncut.Machines.AlphabetReduction +OAI.Computability.MinUncut.Machines.AlphabetRetraction +OAI.Computability.MinUncut.Machines.AlphabetSize +OAI.Computability.MinUncut.Machines.ArenaMachineProgram +OAI.Computability.MinUncut.Machines.CodeFiniteMachine +OAI.Computability.MinUncut.Machines.Driver +OAI.Computability.MinUncut.Machines.FiberGraphMachine +OAI.Computability.MinUncut.Machines.FiniteAlphabetBounds +OAI.Computability.MinUncut.Machines.FramedWordDecoder +OAI.Computability.MinUncut.Machines.GraphCoreMachine +OAI.Computability.MinUncut.Machines.GraphRenderMachine +OAI.Computability.MinUncut.Machines.Input +OAI.Computability.MinUncut.Machines.LoopInitialization +OAI.Computability.MinUncut.Machines.Machine +OAI.Computability.MinUncut.Machines.MachineBinaryFormula +OAI.Computability.MinUncut.Machines.MachineBinaryLiteralMachine +OAI.Computability.MinUncut.Machines.MachineBinaryNameMachine +OAI.Computability.MinUncut.Machines.MachineBinaryOccurrenceRename +OAI.Computability.MinUncut.Machines.MachineBinaryParsing +OAI.Computability.MinUncut.Machines.MachineBinaryRenameMachine +OAI.Computability.MinUncut.Machines.MachineCanonicalOutput +OAI.Computability.MinUncut.Machines.MachineCloudCount +OAI.Computability.MinUncut.Machines.MachineCloudPadding +OAI.Computability.MinUncut.Machines.MachineCloudPrefix +OAI.Computability.MinUncut.Machines.MachineCloudSelect +OAI.Computability.MinUncut.Machines.MachineCompare +OAI.Computability.MinUncut.Machines.MachineDrain +OAI.Computability.MinUncut.Machines.MachineDummyRows +OAI.Computability.MinUncut.Machines.MachineExpanderFamilyAffine +OAI.Computability.MinUncut.Machines.MachineExpanderFamilyCycle +OAI.Computability.MinUncut.Machines.MachineExpanderRowFrames +OAI.Computability.MinUncut.Machines.MachineExpanderTableProgram +OAI.Computability.MinUncut.Machines.MachineExpanderTableRows +OAI.Computability.MinUncut.Machines.MachineFiniteAlphabet +OAI.Computability.MinUncut.Machines.MachineFiniteSequence +OAI.Computability.MinUncut.Machines.MachineFiniteTable +OAI.Computability.MinUncut.Machines.MachineFixedDivMod +OAI.Computability.MinUncut.Machines.MachineInitialHeaders +OAI.Computability.MinUncut.Machines.MachineLazyRows +OAI.Computability.MinUncut.Machines.MachineLazyTable +OAI.Computability.MinUncut.Machines.MachineLazyTableRuntime +OAI.Computability.MinUncut.Machines.MachineLookup +OAI.Computability.MinUncut.Machines.MachineOverlayRows +OAI.Computability.MinUncut.Machines.MachineOverlayTable +OAI.Computability.MinUncut.Machines.MachinePaddedExpanderFamilyBounds +OAI.Computability.MinUncut.Machines.MachinePaddedOverlay +OAI.Computability.MinUncut.Machines.MachinePortReindex +OAI.Computability.MinUncut.Machines.MachinePreservingLookup +OAI.Computability.MinUncut.Machines.MachineRegisterEmit +OAI.Computability.MinUncut.Machines.MachineRegularLift +OAI.Computability.MinUncut.Machines.MachineRegularMetadata +OAI.Computability.MinUncut.Machines.MachineRegularOriginalBody +OAI.Computability.MinUncut.Machines.MachineRegularOwnerProgram +OAI.Computability.MinUncut.Machines.MachineRegularTableRuntime +OAI.Computability.MinUncut.Machines.MachineRegularTableTrace +OAI.Computability.MinUncut.Machines.MachineRegularVertexBlock +OAI.Computability.MinUncut.Machines.MachineSubroutine +OAI.Computability.MinUncut.Machines.MachineSubstitution +OAI.Computability.MinUncut.Machines.MachineTableIteration +OAI.Computability.MinUncut.Machines.MachineTransducer +OAI.Computability.MinUncut.Machines.MachineTupleOdometer +OAI.Computability.MinUncut.Machines.MachineUnaryAdd +OAI.Computability.MinUncut.Machines.MachineUnaryCounter +OAI.Computability.MinUncut.Machines.OuterAlphabets +OAI.Computability.MinUncut.Machines.PCPIterationMachine +OAI.Computability.MinUncut.Machines.PoweringMachineField +OAI.Computability.MinUncut.Machines.PoweringMachineGlobal +OAI.Computability.MinUncut.Machines.PoweringMachineRelation +OAI.Computability.MinUncut.Machines.PoweringMachineRotor +OAI.Computability.MinUncut.Machines.PoweringMachineRow +OAI.Computability.MinUncut.Machines.PoweringMachineRowHeaders +OAI.Computability.MinUncut.Machines.PoweringMachineRuntime +OAI.Computability.MinUncut.Machines.PoweringMachineVertex +OAI.Computability.MinUncut.Machines.PoweringRuntimeBudget +OAI.Computability.MinUncut.Machines.PreprocessingMachineBounds +OAI.Computability.MinUncut.Machines.RawInitialMachineBudget +OAI.Computability.MinUncut.Machines.RawInitialMachineFinish +OAI.Computability.MinUncut.Machines.RawInitialMachinePhases +OAI.Computability.MinUncut.Machines.Relations +OAI.Computability.MinUncut.Machines.Runtime +OAI.Computability.MinUncut.Machines.RuntimeFinish +OAI.Computability.MinUncut.Machines.RuntimeModel +OAI.Computability.MinUncut.Machines.RuntimeModel2 +OAI.Computability.MinUncut.Machines.RuntimeSpace +OAI.Computability.MinUncut.Machines.SelectorMachine +OAI.Computability.MinUncut.Machines.UnboundedGraphMachine +OAI.Computability.MinUncut.Machines.UniformAlphabet +OAI.Computability.MinUncut.Machines.UniformDemandAlphabet +OAI.Computability.MinUncut.Main +OAI.Computability.MinUncut.Model +OAI.Computability.MinUncut.PCP.AddressArithmetic +OAI.Computability.MinUncut.PCP.Bounds +OAI.Computability.MinUncut.PCP.CayleySampling +OAI.Computability.MinUncut.PCP.CayleySpectral +OAI.Computability.MinUncut.PCP.ClauseLookup +OAI.Computability.MinUncut.PCP.ClauseVerifier +OAI.Computability.MinUncut.PCP.CompletedSampling +OAI.Computability.MinUncut.PCP.Completion +OAI.Computability.MinUncut.PCP.ContextClear +OAI.Computability.MinUncut.PCP.ContextLoad +OAI.Computability.MinUncut.PCP.ContextPrepare +OAI.Computability.MinUncut.PCP.DegreeReplacement +OAI.Computability.MinUncut.PCP.DescriptorEmission +OAI.Computability.MinUncut.PCP.DistributionMaps +OAI.Computability.MinUncut.PCP.EquationEmit +OAI.Computability.MinUncut.PCP.ExpanderFamily +OAI.Computability.MinUncut.PCP.ExpanderRowControl +OAI.Computability.MinUncut.PCP.ExpanderTableEnumeration +OAI.Computability.MinUncut.PCP.FieldArray +OAI.Computability.MinUncut.PCP.FinalBooleanVerifier +OAI.Computability.MinUncut.PCP.Folding +OAI.Computability.MinUncut.PCP.FourierResponse +OAI.Computability.MinUncut.PCP.Game +OAI.Computability.MinUncut.PCP.Gap +OAI.Computability.MinUncut.PCP.Generator +OAI.Computability.MinUncut.PCP.GraphGap +OAI.Computability.MinUncut.PCP.GraphTableComplexity +OAI.Computability.MinUncut.PCP.GraphTables +OAI.Computability.MinUncut.PCP.Hastad +OAI.Computability.MinUncut.PCP.HeaderAccumulate +OAI.Computability.MinUncut.PCP.HeaderCounts +OAI.Computability.MinUncut.PCP.HonestTest +OAI.Computability.MinUncut.PCP.InitialGraph +OAI.Computability.MinUncut.PCP.LoopOrder +OAI.Computability.MinUncut.PCP.Occurrences +OAI.Computability.MinUncut.PCP.Overlap +OAI.Computability.MinUncut.PCP.Overlay +OAI.Computability.MinUncut.PCP.Parity +OAI.Computability.MinUncut.PCP.PortTableLookup +OAI.Computability.MinUncut.PCP.PoweringFinalConstants +OAI.Computability.MinUncut.PCP.PoweringOpinionTables +OAI.Computability.MinUncut.PCP.PoweringReturn +OAI.Computability.MinUncut.PCP.PoweringRowData +OAI.Computability.MinUncut.PCP.PoweringRowHeaderSemantics +OAI.Computability.MinUncut.PCP.PoweringTableLayout +OAI.Computability.MinUncut.PCP.PoweringTableSemantics +OAI.Computability.MinUncut.PCP.PreprocessingFamilyBridge +OAI.Computability.MinUncut.PCP.PreprocessingInternalRows +OAI.Computability.MinUncut.PCP.PreprocessingLazyWords +OAI.Computability.MinUncut.PCP.PreprocessingOverlayWords +OAI.Computability.MinUncut.PCP.PreprocessingPaddingOffsets +OAI.Computability.MinUncut.PCP.PreprocessingPaddingWords +OAI.Computability.MinUncut.PCP.PreprocessingRegularBounds +OAI.Computability.MinUncut.PCP.PreprocessingRegularLoopWords +OAI.Computability.MinUncut.PCP.PreprocessingRegularTables +OAI.Computability.MinUncut.PCP.PreprocessingStageMaps +OAI.Computability.MinUncut.PCP.PreprocessingTableSpectral +OAI.Computability.MinUncut.PCP.ProfileBridge +OAI.Computability.MinUncut.PCP.ProfileCorrection +OAI.Computability.MinUncut.PCP.RawInitialPredicate +OAI.Computability.MinUncut.PCP.RawInitialTables +OAI.Computability.MinUncut.PCP.RoundComputation +OAI.Computability.MinUncut.PCP.SelectedInformation +OAI.Computability.MinUncut.PCP.SelectedLikelihood +OAI.Computability.MinUncut.PCP.SelectedMarginal +OAI.Computability.MinUncut.PCP.SelectionSequence +OAI.Computability.MinUncut.PCP.SpectralCut +OAI.Computability.MinUncut.PCP.TableIteration +OAI.Computability.MinUncut.PCP.TupleBody +OAI.Computability.MinUncut.PCP.TupleBound +OAI.Computability.MinUncut.PCP.UniformRestriction +OAI.Computability.MinUncut.PCP.Walsh +OAI.Computability.MinUncut.Search.ArithmeticExpression +OAI.Computability.MinUncut.Search.ArithmeticTactic +OAI.Computability.MinUncut.Search.BlockEnumeration +OAI.Computability.MinUncut.Search.CodeArithmetic +OAI.Computability.MinUncut.Search.CodeFoldComputable +OAI.Computability.MinUncut.Search.CodeLayoutComputable +OAI.Computability.MinUncut.Search.EnumerationPlain +OAI.Computability.MinUncut.Search.FiniteAverageBounds +OAI.Computability.MinUncut.Search.FiniteEnumeration +OAI.Computability.MinUncut.Search.FiniteQueryFamily +OAI.Computability.MinUncut.Search.InnerParameters +OAI.Computability.MinUncut.Search.OuterParameters +OAI.Computability.MinUncut.Search.ParameterFields +OAI.Computability.MinUncut.Search.Parameters +OAI.Computability.MinUncut.Search.PolynomialArithmetic +OAI.Computability.MinUncut.Search.RationalBasics +OAI.Computability.MinUncut.Search.RationalDenominatorArithmetic +OAI.Computability.MinUncut.Search.RationalInner +OAI.Computability.MinUncut.Search.RawRationalArithmetic +OAI.Computability.MinUncut.Search.SampleEnumeration +OAI.Computability.MinUncut.Search.TemplateArithmetic +OAI.Computability.MinUncut.Search.UniformFind +OAI.Computability.MinUncut.Search.UniformFiniteSum +OAI.Computability.MinUncut.Search.UniformQuantifier +OAI.Computability.MinUncut.Search.UniformRational diff --git a/tasks/min-uncut/solution/reference.py b/tasks/min-uncut/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/min-uncut/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/min-uncut/solution/solve.sh b/tasks/min-uncut/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c58cff37f20f4d265ffca3044a1bf97f574749e3 --- /dev/null +++ b/tasks/min-uncut/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of MinUncut, i.e. module OAI.Computability.MinUncut.Main and the +# 375 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.MinUncut.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of MinUncut" diff --git a/tasks/min-uncut/task.toml b/tasks/min-uncut/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e3b06e63ecfeb356ac38fd5e4ebac819b19c0bc0 --- /dev/null +++ b/tasks/min-uncut/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/min-uncut" +version = "1.0.0" +description = "Prove MinUncut (openai/math family 102: The Unique Games Conjecture and optimal approximation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/MinUncut.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "MinUncut" +family = "102" +family_title = "The Unique Games Conjecture and optimal approximation thresholds" +subject = "Theoretical computer science" +theorems = ["OAI.MinUncut.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.MinUncut.Main" +reference_modules = 375 +reference_lean_bytes = 5995678 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1335 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17096 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/min-uncut/tests/Challenge.lean b/tasks/min-uncut/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f4631616d289df94cdec11e3f010fb5b8669623c --- /dev/null +++ b/tasks/min-uncut/tests/Challenge.lean @@ -0,0 +1,130 @@ +import Mathlib + +namespace OAI + + + + + + + + + + +namespace MinUncutGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end MinUncutGames.BinaryFormula + +namespace MinUncutGames.BinaryEncoding +open BinaryFormula + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def nameBits (name : Nat) : List Bool := frame name.bits + +def literalBits (literal : Literal) : List Bool := + literal.positive :: nameBits literal.name + +def clauseBits (clause : Clause) : List Bool := + literalBits clause[0] ++ literalBits clause[1] ++ literalBits clause[2] + +def clausesBits : List Clause → List Bool + | [] => [false] + | clause :: clauses => true :: (clauseBits clause ++ clausesBits clauses) + +def formulaBits (formula : Formula) : List Bool := clausesBits formula.clauses + +end MinUncutGames.BinaryEncoding + +namespace MinUncut +open MinUncutGames.BinaryFormula MinUncutGames.BinaryEncoding + + + +structure Output where + vertices : ℕ + adjacent : Fin vertices → Fin vertices → Bool + symmetric : ∀ u v, adjacent u v = adjacent v u + loopless : ∀ u, adjacent u u = false + threshold : ℕ + threshold_pos : 1 ≤ threshold + + + +def Output.uncut (G : Output) (cut : Fin G.vertices → Bool) : ℕ := + (Finset.univ.filter fun uv : Fin G.vertices × Fin G.vertices => + uv.1 < uv.2 ∧ G.adjacent uv.1 uv.2 = true ∧ cut uv.1 = cut uv.2).card + + + +noncomputable def Output.opt (G : Output) : ℕ := + (Finset.univ.image G.uncut).min' (by + exact Finset.image_nonempty.mpr Finset.univ_nonempty) + + + +def Output.bits (G : Output) : List Bool := + nameBits G.vertices ++ + ((List.finRange G.vertices).flatMap fun u => + (List.finRange G.vertices).map fun v => G.adjacent u v) ++ + nameBits G.threshold + + + +def inputBits (input : ℕ × Formula) : List Bool := + nameBits input.1 ++ formulaBits input.2 + + + + + +structure Reduction where + reduce : ℕ → Formula → Output + machine : Turing.TM2Computable inputBits Output.bits (fun p => reduce p.1 p.2) + finiteAlphabet : ∀ k : machine.tm.K, Finite (machine.tm.Γ k) + time : ℕ → Polynomial ℕ + runtime : ∀ K φ, + Turing.TM2OutputsInTime machine.tm + ((inputBits (K, φ)).map machine.inputAlphabet.symm) + (some (((reduce K φ).bits).map machine.outputAlphabet.symm)) + ((time K).eval (formulaBits φ).length) + size : ℕ → Polynomial ℕ + output_size : ∀ K φ, + (reduce K φ).vertices + (reduce K φ).bits.length ≤ + (size K).eval (formulaBits φ).length + yes : ∀ K, 2 ≤ K → ∀ φ, φ.Satisfiable → + (reduce K φ).opt ≤ (reduce K φ).threshold + no : ∀ K, 2 ≤ K → ∀ φ, ¬ φ.Satisfiable → + K * (reduce K φ).threshold < (reduce K φ).opt + +end MinUncut + +namespace MinUncut + +theorem main : Nonempty Reduction := by + sorry + +end MinUncut + +end OAI diff --git a/tasks/min-uncut/tests/grade.py b/tasks/min-uncut/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/min-uncut/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/min-uncut/tests/task.json b/tasks/min-uncut/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9c5eedef58952190ecc341e6e47a12f824de3b88 --- /dev/null +++ b/tasks/min-uncut/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "MinUncut", + "comparator": { + "theorem_names": [ + "OAI.MinUncut.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16196 +} \ No newline at end of file diff --git a/tasks/min-uncut/tests/test.sh b/tasks/min-uncut/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/min-uncut/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/nagata/environment/Dockerfile b/tasks/nagata/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/nagata/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/nagata/environment/fetch_mathlib.sh b/tasks/nagata/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/nagata/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/nagata/environment/lake-manifest.json b/tasks/nagata/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/nagata/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/nagata/environment/lakefile.lean b/tasks/nagata/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/nagata/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/nagata/environment/lean_setup.sh b/tasks/nagata/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/nagata/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/nagata/environment/pack_submission.py b/tasks/nagata/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/nagata/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/nagata/instruction.md b/tasks/nagata/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d098755a86e655c0c39aed706b27c91af27acab2 --- /dev/null +++ b/tasks/nagata/instruction.md @@ -0,0 +1,423 @@ +# openai/math challenge `Nagata` (family 039) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 039 of the release, *Nagata's conjecture and maximal Seshadri constants* +(Algebraic and complex geometry). The family as a whole: Proves Nagata's strict inequality $\sum_i m_i MvPolynomial.X index + MvPolynomial.C (point index)) + +@[simp] theorem translateHom_C (point : σ → K) (coefficient : K) : + translateHom point (MvPolynomial.C coefficient) = MvPolynomial.C coefficient := by + simp [translateHom] + +@[simp] theorem translateHom_X (point : σ → K) (index : σ) : + translateHom point (MvPolynomial.X index) = MvPolynomial.X index + MvPolynomial.C (point index) := by + simp [translateHom] + +theorem translateHom_neg_comp (point : σ → K) : + (translateHom (-point)).comp (translateHom point) = RingHom.id _ := by + apply MvPolynomial.ringHom_ext + · intro coefficient; simp + · intro index; simp [add_assoc] + +theorem translateHom_comp_neg (point : σ → K) : + (translateHom point).comp (translateHom (-point)) = RingHom.id _ := by + simpa only [neg_neg] using translateHom_neg_comp (-point) + +def translateEquiv (point : σ → K) : MvPolynomial σ K ≃+* MvPolynomial σ K := + { translateHom point with + invFun := translateHom (-point) + left_inv := fun polynomial => RingHom.congr_fun (translateHom_neg_comp point) polynomial + right_inv := fun polynomial => RingHom.congr_fun (translateHom_comp_neg point) polynomial } + +@[simp] theorem translateEquiv_apply (point : σ → K) (polynomial : MvPolynomial σ K) : + translateEquiv point polynomial = translateHom point polynomial := rfl + +theorem translate_ne_zero (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : translateHom point polynomial ≠ 0 := by + intro translated_zero + apply nonzero + apply (translateEquiv point).injective + simpa only [translateEquiv_apply, map_zero] using translated_zero + +theorem translated_support_nonempty (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : (translateHom point polynomial).support.Nonempty := + MvPolynomial.support_nonempty.mpr (translate_ne_zero point polynomial nonzero) + +/-- The least total degree of a nonzero Taylor coefficient. -/ +def ordinaryMultiplicity (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : ℕ := + (translateHom point polynomial).support.inf' + (translated_support_nonempty point polynomial nonzero) Finsupp.degree + +end Nagata.AffineMultiplicity + +namespace Nagata.ProjectiveGeometry + +abbrev PlanePoint := Projectivization ℂ (Fin 3 → ℂ) + +abbrev OrderedDistinctPoints (count : ℕ) := + {points : Fin count → PlanePoint // Function.Injective points} + +structure MultihomogeneousEquation (count : ℕ) where + polynomial : MvPolynomial (Fin count × Fin 3) ℂ + multidegree : Fin count → ℕ + homogeneous : ∀ exponent ∈ polynomial.support, ∀ index, + (∑ coordinate : Fin 3, exponent (index, coordinate)) = multidegree index + +def equationVanishes {count : ℕ} (equation : MultihomogeneousEquation count) + (points : Fin count → PlanePoint) : Prop := + ∀ (vectors : Fin count → Fin 3 → ℂ) (nonzero : ∀ index, vectors index ≠ 0), + (∀ index, Projectivization.mk ℂ (vectors index) (nonzero index) = points index) → + MvPolynomial.eval (fun index => vectors index.1 index.2) equation.polynomial = 0 + +def IsProductZariskiClosed {count : ℕ} (locus : Set (Fin count → PlanePoint)) : Prop := + ∃ equations : Set (MultihomogeneousEquation count), + ∀ points, points ∈ locus ↔ ∀ equation ∈ equations, equationVanishes equation points + +def IsConfigurationZariskiClosed {count : ℕ} + (locus : Set (OrderedDistinctPoints count)) : Prop := + ∃ ambient : Set (Fin count → PlanePoint), IsProductZariskiClosed ambient ∧ + ∀ points, points ∈ locus ↔ points.val ∈ ambient + +abbrev ChartVariables (chart : Fin 3) := {coordinate : Fin 3 // coordinate ≠ chart} + +def dehomogenize (chart : Fin 3) (polynomial : MvPolynomial (Fin 3) ℂ) : + MvPolynomial (ChartVariables chart) ℂ := + MvPolynomial.eval₂ MvPolynomial.C + (fun coordinate => if equal : coordinate = chart then 1 + else MvPolynomial.X ⟨coordinate, equal⟩) polynomial + +def chartCoordinates (chart : Fin 3) (point : PlanePoint) : ChartVariables chart → ℂ := + fun coordinate => point.rep coordinate.val / point.rep chart + +/-- Local multiplicity lower bounds are membership in powers of the point ideal. -/ +def multiplicityAtLeast (polynomial : MvPolynomial (Fin 3) ℂ) + (point : PlanePoint) (multiplicity : ℕ) : Prop := + ∀ chart : Fin 3, point.rep chart ≠ 0 → + AffineMultiplicity.orderAtLeast (chartCoordinates chart point) multiplicity + (dehomogenize chart polynomial) + +theorem chart_exists (point : PlanePoint) : ∃ chart : Fin 3, point.rep chart ≠ 0 := by + by_contra absent + apply point.rep_nonzero + funext chart + exact Classical.not_not.mp (fun nonzero => absent ⟨chart, nonzero⟩) + +end Nagata.ProjectiveGeometry + +namespace Nagata.Workers.W30 + +open UniqueFactorizationMonoid + +abbrev TernaryPolynomial := MvPolynomial (Fin 3) ℂ + +local instance : DecidableEq (Associates TernaryPolynomial) := Classical.decEq _ + +def equationMultiplicity (polynomial : TernaryPolynomial) : + Associates TernaryPolynomial →₀ ℕ := + factorization (Associates.mk polynomial) + +def associatePrincipalIdeal (associate : Associates TernaryPolynomial) : + Ideal TernaryPolynomial := + (Ideal.associatesEquivIsPrincipal TernaryPolynomial associate).val + +def equationIdealCycle (polynomial : TernaryPolynomial) : Ideal TernaryPolynomial →₀ ℕ := + (equationMultiplicity polynomial).mapDomain associatePrincipalIdeal + +attribute [local instance] MvPolynomial.gradedAlgebra + +theorem exists_positive_degree_equation_of_homogeneous_cycle + (cycle : Ideal TernaryPolynomial →₀ ℕ) (nonzero : cycle ≠ 0) + (homogeneous : ∀ ideal ∈ cycle.support, + ideal.IsPrime ∧ ideal ≠ ⊥ ∧ ideal.IsPrincipal ∧ + ideal.IsHomogeneous (MvPolynomial.homogeneousSubmodule (Fin 3) ℂ)) : + ∃ polynomial : TernaryPolynomial, + polynomial ≠ 0 ∧ polynomial.IsHomogeneous polynomial.totalDegree ∧ + 0 < polynomial.totalDegree ∧ equationIdealCycle polynomial = cycle := by + sorry + +end Nagata.Workers.W30 + +namespace Nagata.W16 + +abbrev PlanePolynomial := MvPolynomial (Fin 3) ℂ + +structure NonzeroHomogeneousForm (degree : ℕ) where + polynomial : PlanePolynomial + homogeneous : polynomial.IsHomogeneous degree + nonzero : polynomial ≠ 0 + +theorem homogeneous_eval_scale {Variables Coefficient : Type*} [CommSemiring Coefficient] + {polynomial : MvPolynomial Variables Coefficient} {degree : ℕ} + (homogeneous : polynomial.IsHomogeneous degree) + (coordinates : Variables → Coefficient) (scalar : Coefficient) : + MvPolynomial.eval (fun index => scalar * coordinates index) polynomial = + scalar ^ degree * MvPolynomial.eval coordinates polynomial := by + classical + simp only [MvPolynomial.eval_eq, Finset.mul_sum] + apply Finset.sum_congr rfl + intro exponent supported + simp only [mul_pow, Finset.prod_mul_distrib, Finset.prod_pow_eq_pow_sum] + rw [← homogeneous.degree_eq_sum_deg_support supported] + ac_rfl + +open Nagata.ProjectiveGeometry + +theorem eval_dehomogenize (chart : Fin 3) (polynomial : PlanePolynomial) + (coordinates : ChartVariables chart → ℂ) : + MvPolynomial.eval coordinates (dehomogenize chart polynomial) = + MvPolynomial.eval + (fun index => if equal : index = chart then 1 else coordinates ⟨index, equal⟩) + polynomial := by + classical + unfold dehomogenize + rw [← MvPolynomial.eval_assoc] + apply congrArg (fun values : Fin 3 → ℂ => MvPolynomial.eval values polynomial) + funext index + by_cases equal : index = chart <;> simp [equal, Function.comp_apply] + +theorem eval_dehomogenize_normalized {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (coordinates : Fin 3 → ℂ) (chart_nonzero : coordinates chart ≠ 0) : + MvPolynomial.eval (fun index : ChartVariables chart => coordinates index.val / coordinates chart) + (dehomogenize chart polynomial) = + (coordinates chart)⁻¹ ^ degree * MvPolynomial.eval coordinates polynomial := by + classical + rw [eval_dehomogenize] + have normalized : + (fun index : Fin 3 => if equal : index = chart then (1 : ℂ) + else coordinates index / coordinates chart) = + fun index => (coordinates chart)⁻¹ * coordinates index := by + funext index + by_cases equal : index = chart + · subst index + simp [chart_nonzero] + · simp [equal, div_eq_mul_inv, mul_comm] + rw [normalized] + exact homogeneous_eval_scale homogeneous coordinates (coordinates chart)⁻¹ + +theorem eval_eq_zero_of_dehomogenize_eq_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (chart_zero : dehomogenize chart polynomial = 0) + (coordinates : Fin 3 → ℂ) (chart_nonzero : coordinates chart ≠ 0) : + MvPolynomial.eval coordinates polynomial = 0 := by + have evaluated := congrArg + (MvPolynomial.eval (fun index : ChartVariables chart => coordinates index.val / coordinates chart)) + chart_zero + rw [eval_dehomogenize_normalized homogeneous chart coordinates chart_nonzero, map_zero] at evaluated + exact (mul_eq_zero.mp evaluated).resolve_left (pow_ne_zero degree (inv_ne_zero chart_nonzero)) + +theorem eq_zero_of_dehomogenize_eq_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (chart_zero : dehomogenize chart polynomial = 0) : polynomial = 0 := by + have multiplied : MvPolynomial.X chart * polynomial = 0 := by + apply ((MvPolynomial.isHomogeneous_X ℂ chart).mul homogeneous).eq_zero_of_forall_eval_eq_zero + intro coordinates + rw [MvPolynomial.eval_mul, MvPolynomial.eval_X] + by_cases chart_nonzero : coordinates chart = 0 + · simp [chart_nonzero] + · rw [eval_eq_zero_of_dehomogenize_eq_zero homogeneous chart chart_zero coordinates chart_nonzero, + mul_zero] + exact (mul_eq_zero.mp multiplied).resolve_left (MvPolynomial.X_ne_zero chart) + +theorem dehomogenize_ne_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (nonzero : polynomial ≠ 0) + (chart : Fin 3) : ProjectiveGeometry.dehomogenize chart polynomial ≠ 0 := by + intro chart_zero + exact nonzero (eq_zero_of_dehomogenize_eq_zero homogeneous chart chart_zero) + +end Nagata.W16 + +namespace Nagata.Workers.W10 + +open Nagata.Workers.W30 Nagata.W16 + +attribute [local instance] MvPolynomial.gradedAlgebra + +/-- Nonzero finite cycles of homogeneous prime plane ideals, with natural weights. -/ +def EffectivePlaneCurve := {cycle : Ideal TernaryPolynomial →₀ ℕ // + cycle ≠ 0 ∧ ∀ ideal ∈ cycle.support, + ideal.IsPrime ∧ ideal ≠ ⊥ ∧ ideal.IsPrincipal ∧ + ideal.IsHomogeneous (MvPolynomial.homogeneousSubmodule (Fin 3) ℂ)} + +/-- An equation realizing the entire cycle, including repeated components. -/ +def curveEquation (curve : EffectivePlaneCurve) : TernaryPolynomial := + Classical.choose (exists_positive_degree_equation_of_homogeneous_cycle + curve.val curve.property.1 curve.property.2) + +theorem curveEquation_spec (curve : EffectivePlaneCurve) : + curveEquation curve ≠ 0 ∧ + (curveEquation curve).IsHomogeneous (curveEquation curve).totalDegree ∧ + 0 < (curveEquation curve).totalDegree ∧ equationIdealCycle (curveEquation curve) = curve.val := + Classical.choose_spec (exists_positive_degree_equation_of_homogeneous_cycle + curve.val curve.property.1 curve.property.2) + +theorem curveEquation_nonzero (curve : EffectivePlaneCurve) : curveEquation curve ≠ 0 := + (curveEquation_spec curve).1 + +def curveDegree (curve : EffectivePlaneCurve) : ℕ := (curveEquation curve).totalDegree + +theorem curveEquation_homogeneous (curve : EffectivePlaneCurve) : + (curveEquation curve).IsHomogeneous (curveDegree curve) := + (curveEquation_spec curve).2.1 + +def curveForm (curve : EffectivePlaneCurve) : NonzeroHomogeneousForm (curveDegree curve) := + ⟨curveEquation curve, curveEquation_homogeneous curve, curveEquation_nonzero curve⟩ + +end Nagata.Workers.W10 + +namespace Nagata.ProjectiveGeometry + +def formOrdinaryMultiplicity {degree : ℕ} (form : W16.NonzeroHomogeneousForm degree) + (point : PlanePoint) : ℕ := + let chart := Classical.choose (chart_exists point) + AffineMultiplicity.ordinaryMultiplicity (chartCoordinates chart point) + (dehomogenize chart form.polynomial) + (W16.dehomogenize_ne_zero form.homogeneous form.nonzero chart) + +end Nagata.ProjectiveGeometry + +namespace Nagata.W15 + +open Nagata.Workers.W10 Nagata.ProjectiveGeometry + +def curveOrdinaryMultiplicity (curve : EffectivePlaneCurve) (point : PlanePoint) : ℕ := + formOrdinaryMultiplicity (curveForm curve) point + +end Nagata.W15 + +namespace Nagata + +open ProjectiveGeometry + +def FullNagata : Prop := + ∀ count : ℕ, 10 ≤ count → + ∃ exceptional : ℕ → Set (OrderedDistinctPoints count), + (∀ index, IsConfigurationZariskiClosed (exceptional index) ∧ + exceptional index ≠ Set.univ) ∧ + (∃ points : OrderedDistinctPoints count, ∀ index, points ∉ exceptional index) ∧ + ∀ points : OrderedDistinctPoints count, (∀ index, points ∉ exceptional index) → + ∀ degree : ℕ, 1 ≤ degree → + ∀ polynomial : MvPolynomial (Fin 3) ℂ, + polynomial ≠ 0 → polynomial.IsHomogeneous degree → + ∀ multiplicities : Fin count → ℕ, + (∀ index, multiplicityAtLeast polynomial (points.val index) (multiplicities index)) → + (∑ index, (multiplicities index : ℝ)) < (degree : ℝ) * Real.sqrt (count : ℝ) + +theorem nagata_conjecture : + ∀ count : ℕ, 10 ≤ count → + ∃ exceptional : ℕ → Set (OrderedDistinctPoints count), + (∀ index, IsConfigurationZariskiClosed (exceptional index) ∧ + exceptional index ≠ Set.univ) ∧ + (∃ points : OrderedDistinctPoints count, ∀ index, points ∉ exceptional index) ∧ + ∀ points : OrderedDistinctPoints count, (∀ index, points ∉ exceptional index) → + ∀ curve : Workers.W10.EffectivePlaneCurve, ∀ multiplicities : Fin count → ℕ, + (∀ index, multiplicities index ≤ W15.curveOrdinaryMultiplicity curve (points.val index)) → + (∑ index, (multiplicities index : ℝ)) < + (Workers.W10.curveDegree curve : ℝ) * Real.sqrt (count : ℝ) := by + sorry + +theorem nagata_conjecture_coordinates : FullNagata := by + sorry + +end Nagata + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Nagata.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Nagata.Workers.W30.exists_positive_degree_equation_of_homogeneous_cycle`, `OAI.Nagata.nagata_conjecture`, `OAI.Nagata.nagata_conjecture_coordinates` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/nagata/solution/closure.txt b/tasks/nagata/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..34484680538a07ddf711815b28aed00954137aa5 --- /dev/null +++ b/tasks/nagata/solution/closure.txt @@ -0,0 +1,117 @@ +OAI.AlgebraicGeometry.PlaneCurves.AffineMultiplicity +OAI.AlgebraicGeometry.PlaneCurves.AnalyticFactorization +OAI.AlgebraicGeometry.PlaneCurves.AnalyticJets +OAI.AlgebraicGeometry.PlaneCurves.AnalyticOrder +OAI.AlgebraicGeometry.PlaneCurves.AnalyticScaling +OAI.AlgebraicGeometry.PlaneCurves.AnalyticTaylor +OAI.AlgebraicGeometry.PlaneCurves.ArithmeticReduction +OAI.AlgebraicGeometry.PlaneCurves.AssociatedBundles +OAI.AlgebraicGeometry.PlaneCurves.Automorphic +OAI.AlgebraicGeometry.PlaneCurves.Avoidance +OAI.AlgebraicGeometry.PlaneCurves.BasisNoncancellation +OAI.AlgebraicGeometry.PlaneCurves.BinaryForms +OAI.AlgebraicGeometry.PlaneCurves.ChartGradients +OAI.AlgebraicGeometry.PlaneCurves.ChartJets +OAI.AlgebraicGeometry.PlaneCurves.ChartMultiplicityBridge +OAI.AlgebraicGeometry.PlaneCurves.CoefficientBlocks +OAI.AlgebraicGeometry.PlaneCurves.CoefficientIdeals +OAI.AlgebraicGeometry.PlaneCurves.CoefficientSpaces +OAI.AlgebraicGeometry.PlaneCurves.CoefficientTransforms +OAI.AlgebraicGeometry.PlaneCurves.Collision +OAI.AlgebraicGeometry.PlaneCurves.CollisionBounds +OAI.AlgebraicGeometry.PlaneCurves.Configuration +OAI.AlgebraicGeometry.PlaneCurves.ConstantSections +OAI.AlgebraicGeometry.PlaneCurves.CoverNormal +OAI.AlgebraicGeometry.PlaneCurves.CubicEquations +OAI.AlgebraicGeometry.PlaneCurves.CubicEvaluation +OAI.AlgebraicGeometry.PlaneCurves.CubicGeometry +OAI.AlgebraicGeometry.PlaneCurves.CubicMap +OAI.AlgebraicGeometry.PlaneCurves.CubicRelations +OAI.AlgebraicGeometry.PlaneCurves.CycleMultiplicity +OAI.AlgebraicGeometry.PlaneCurves.DividedFamilies +OAI.AlgebraicGeometry.PlaneCurves.EffectiveCurves +OAI.AlgebraicGeometry.PlaneCurves.Enclosure +OAI.AlgebraicGeometry.PlaneCurves.ExponentMatrices +OAI.AlgebraicGeometry.PlaneCurves.ExponentSets +OAI.AlgebraicGeometry.PlaneCurves.Factorization +OAI.AlgebraicGeometry.PlaneCurves.FixedCurveSections +OAI.AlgebraicGeometry.PlaneCurves.Forms +OAI.AlgebraicGeometry.PlaneCurves.Fourier +OAI.AlgebraicGeometry.PlaneCurves.FrechetMultiplicity +OAI.AlgebraicGeometry.PlaneCurves.FullTarget +OAI.AlgebraicGeometry.PlaneCurves.GaussianBounds +OAI.AlgebraicGeometry.PlaneCurves.GeometricCollision +OAI.AlgebraicGeometry.PlaneCurves.Gluing +OAI.AlgebraicGeometry.PlaneCurves.GraphOrder +OAI.AlgebraicGeometry.PlaneCurves.HomogeneousFamilies +OAI.AlgebraicGeometry.PlaneCurves.HomogeneousIdeals +OAI.AlgebraicGeometry.PlaneCurves.HomogeneousOrder +OAI.AlgebraicGeometry.PlaneCurves.Homogenization +OAI.AlgebraicGeometry.PlaneCurves.IdealCycles +OAI.AlgebraicGeometry.PlaneCurves.Incidence +OAI.AlgebraicGeometry.PlaneCurves.InfiniteProducts +OAI.AlgebraicGeometry.PlaneCurves.Interpolation +OAI.AlgebraicGeometry.PlaneCurves.Intervals +OAI.AlgebraicGeometry.PlaneCurves.JetGerms +OAI.AlgebraicGeometry.PlaneCurves.KernelBridges +OAI.AlgebraicGeometry.PlaneCurves.LaurentCoefficients +OAI.AlgebraicGeometry.PlaneCurves.LineBases +OAI.AlgebraicGeometry.PlaneCurves.LineConfigurations +OAI.AlgebraicGeometry.PlaneCurves.LineGeometry +OAI.AlgebraicGeometry.PlaneCurves.LineIntersections +OAI.AlgebraicGeometry.PlaneCurves.LineNormalData +OAI.AlgebraicGeometry.PlaneCurves.LineObstructions +OAI.AlgebraicGeometry.PlaneCurves.LineRestriction +OAI.AlgebraicGeometry.PlaneCurves.LineSmoothness +OAI.AlgebraicGeometry.PlaneCurves.LowDegree +OAI.AlgebraicGeometry.PlaneCurves.MarkedCubic +OAI.AlgebraicGeometry.PlaneCurves.MarkedDisplacements +OAI.AlgebraicGeometry.PlaneCurves.MarkedPoints +OAI.AlgebraicGeometry.PlaneCurves.MatrixLimits +OAI.AlgebraicGeometry.PlaneCurves.MixedDerivatives +OAI.AlgebraicGeometry.PlaneCurves.MovingConfigurations +OAI.AlgebraicGeometry.PlaneCurves.MovingLines +OAI.AlgebraicGeometry.PlaneCurves.MultiplierBundles +OAI.AlgebraicGeometry.PlaneCurves.Multipliers +OAI.AlgebraicGeometry.PlaneCurves.Nagata +OAI.AlgebraicGeometry.PlaneCurves.NecessarySections +OAI.AlgebraicGeometry.PlaneCurves.NormalCharts +OAI.AlgebraicGeometry.PlaneCurves.NormalCoefficients +OAI.AlgebraicGeometry.PlaneCurves.NormalPolynomials +OAI.AlgebraicGeometry.PlaneCurves.NormalSpecialization +OAI.AlgebraicGeometry.PlaneCurves.NormalizedExponents +OAI.AlgebraicGeometry.PlaneCurves.Parameters +OAI.AlgebraicGeometry.PlaneCurves.PolynomialAvoidance +OAI.AlgebraicGeometry.PlaneCurves.PolynomialBases +OAI.AlgebraicGeometry.PlaneCurves.PolynomialBlocks +OAI.AlgebraicGeometry.PlaneCurves.PolynomialJets +OAI.AlgebraicGeometry.PlaneCurves.ProjectiveMultiplicity +OAI.AlgebraicGeometry.PlaneCurves.ProjectiveTopology +OAI.AlgebraicGeometry.PlaneCurves.QuotientSections +OAI.AlgebraicGeometry.PlaneCurves.RationalKernels +OAI.AlgebraicGeometry.PlaneCurves.RelationIdeals +OAI.AlgebraicGeometry.PlaneCurves.RowData +OAI.AlgebraicGeometry.PlaneCurves.Rows +OAI.AlgebraicGeometry.PlaneCurves.ScaledMatrices +OAI.AlgebraicGeometry.PlaneCurves.SectionBases +OAI.AlgebraicGeometry.PlaneCurves.SectionDimensions +OAI.AlgebraicGeometry.PlaneCurves.SectionKernels +OAI.AlgebraicGeometry.PlaneCurves.SectionOrder +OAI.AlgebraicGeometry.PlaneCurves.SquareLinear +OAI.AlgebraicGeometry.PlaneCurves.SquareNormal +OAI.AlgebraicGeometry.PlaneCurves.SquareReduction +OAI.AlgebraicGeometry.PlaneCurves.TaylorMultiplicity +OAI.AlgebraicGeometry.PlaneCurves.ThetaCoefficients +OAI.AlgebraicGeometry.PlaneCurves.ThetaEvaluation +OAI.AlgebraicGeometry.PlaneCurves.ThetaExponents +OAI.AlgebraicGeometry.PlaneCurves.ThetaLimits +OAI.AlgebraicGeometry.PlaneCurves.ThetaMatrices +OAI.AlgebraicGeometry.PlaneCurves.ThetaPolynomialBases +OAI.AlgebraicGeometry.PlaneCurves.ThetaProducts +OAI.AlgebraicGeometry.PlaneCurves.ThetaSections +OAI.AlgebraicGeometry.PlaneCurves.ThetaSeries +OAI.AlgebraicGeometry.PlaneCurves.TorusCharts +OAI.AlgebraicGeometry.PlaneCurves.TorusConfigurations +OAI.AlgebraicGeometry.PlaneCurves.UniversalFamilies +OAI.AlgebraicGeometry.PlaneCurves.UniversalReduction +OAI.AlgebraicGeometry.PlaneCurves.UniversalSections diff --git a/tasks/nagata/solution/reference.py b/tasks/nagata/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/nagata/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/nagata/solution/solve.sh b/tasks/nagata/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba93f2a760431af6a246dd112a4f1ff27dbb4889 --- /dev/null +++ b/tasks/nagata/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Nagata, i.e. module OAI.AlgebraicGeometry.PlaneCurves.Nagata and the +# 117 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.AlgebraicGeometry.PlaneCurves.Nagata /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Nagata" diff --git a/tasks/nagata/task.toml b/tasks/nagata/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..241b6e6a290cca18ab684fe00cda8961c1c05a64 --- /dev/null +++ b/tasks/nagata/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/nagata" +version = "1.0.0" +description = "Prove Nagata (openai/math family 039: Nagata's conjecture and maximal Seshadri constants) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Nagata.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Nagata" +family = "039" +family_title = "Nagata's conjecture and maximal Seshadri constants" +subject = "Algebraic and complex geometry" +theorems = ["OAI.Nagata.Workers.W30.exists_positive_degree_equation_of_homogeneous_cycle", "OAI.Nagata.nagata_conjecture", "OAI.Nagata.nagata_conjecture_coordinates"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.AlgebraicGeometry.PlaneCurves.Nagata" +reference_modules = 117 +reference_lean_bytes = 1609242 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 505 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13148 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/nagata/tests/Challenge.lean b/tasks/nagata/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2b453fbdef76a33643c0cf77ee62f4a39bd6f24 --- /dev/null +++ b/tasks/nagata/tests/Challenge.lean @@ -0,0 +1,372 @@ +import Mathlib.Algebra.CharZero.Infinite +import Mathlib.Algebra.Group.Irreducible.Defs +import Mathlib.Algebra.MvPolynomial.Eval +import Mathlib.Algebra.MvPolynomial.NoZeroDivisors +import Mathlib.Algebra.MvPolynomial.Rename +import Mathlib.Analysis.Real.Sqrt +import Mathlib.Basic.Complex.Basic +import Mathlib.Data.Fin.SuccPred +import Mathlib.Data.Fin.Tuple.Basic +import Mathlib.Data.Fintype.BigOperators +import Mathlib.LinearAlgebra.Projectivization.Basic +import Mathlib.RingTheory.GradedAlgebra.Homogeneous.Ideal +import Mathlib.RingTheory.Ideal.Height +import Mathlib.RingTheory.Ideal.IsPrincipal +import Mathlib.RingTheory.Ideal.Maps +import Mathlib.RingTheory.Ideal.Maximal +import Mathlib.RingTheory.Localization.AtPrime.Basic +import Mathlib.RingTheory.MvPolynomial.Homogeneous +import Mathlib.RingTheory.MvPolynomial.Ideal +import Mathlib.RingTheory.Polynomial.UniqueFactorization +import Mathlib.RingTheory.UniqueFactorizationDomain.Basic +import Mathlib.RingTheory.UniqueFactorizationDomain.Finsupp + +namespace OAI + +/-! +# Nagata's strict inequality for very general complex plane configurations + +The exceptional family is chosen before every curve and multiplicity vector. +Closedness means common multihomogeneous zero loci on the product of projective +planes, restricted to the open set of ordered distinct configurations. +-/ + +noncomputable section + +open scoped BigOperators + +namespace Nagata.AffineMultiplicity + +variable {σ K : Type*} [CommRing K] + +def pointIdeal (point : σ → K) : Ideal (MvPolynomial σ K) := + RingHom.ker (MvPolynomial.eval point) + +def orderAtLeast (point : σ → K) (multiplicity : ℕ) + (polynomial : MvPolynomial σ K) : Prop := + polynomial ∈ pointIdeal point ^ multiplicity + +def translateHom (point : σ → K) : MvPolynomial σ K →+* MvPolynomial σ K := + MvPolynomial.eval₂Hom MvPolynomial.C + (fun index => MvPolynomial.X index + MvPolynomial.C (point index)) + +@[simp] theorem translateHom_C (point : σ → K) (coefficient : K) : + translateHom point (MvPolynomial.C coefficient) = MvPolynomial.C coefficient := by + simp [translateHom] + +@[simp] theorem translateHom_X (point : σ → K) (index : σ) : + translateHom point (MvPolynomial.X index) = MvPolynomial.X index + MvPolynomial.C (point index) := by + simp [translateHom] + +theorem translateHom_neg_comp (point : σ → K) : + (translateHom (-point)).comp (translateHom point) = RingHom.id _ := by + apply MvPolynomial.ringHom_ext + · intro coefficient; simp + · intro index; simp [add_assoc] + +theorem translateHom_comp_neg (point : σ → K) : + (translateHom point).comp (translateHom (-point)) = RingHom.id _ := by + simpa only [neg_neg] using translateHom_neg_comp (-point) + +def translateEquiv (point : σ → K) : MvPolynomial σ K ≃+* MvPolynomial σ K := + { translateHom point with + invFun := translateHom (-point) + left_inv := fun polynomial => RingHom.congr_fun (translateHom_neg_comp point) polynomial + right_inv := fun polynomial => RingHom.congr_fun (translateHom_comp_neg point) polynomial } + +@[simp] theorem translateEquiv_apply (point : σ → K) (polynomial : MvPolynomial σ K) : + translateEquiv point polynomial = translateHom point polynomial := rfl + +theorem translate_ne_zero (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : translateHom point polynomial ≠ 0 := by + intro translated_zero + apply nonzero + apply (translateEquiv point).injective + simpa only [translateEquiv_apply, map_zero] using translated_zero + +theorem translated_support_nonempty (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : (translateHom point polynomial).support.Nonempty := + MvPolynomial.support_nonempty.mpr (translate_ne_zero point polynomial nonzero) + +/-- The least total degree of a nonzero Taylor coefficient. -/ +def ordinaryMultiplicity (point : σ → K) (polynomial : MvPolynomial σ K) + (nonzero : polynomial ≠ 0) : ℕ := + (translateHom point polynomial).support.inf' + (translated_support_nonempty point polynomial nonzero) Finsupp.degree + +end Nagata.AffineMultiplicity + +namespace Nagata.ProjectiveGeometry + +abbrev PlanePoint := Projectivization ℂ (Fin 3 → ℂ) + +abbrev OrderedDistinctPoints (count : ℕ) := + {points : Fin count → PlanePoint // Function.Injective points} + +structure MultihomogeneousEquation (count : ℕ) where + polynomial : MvPolynomial (Fin count × Fin 3) ℂ + multidegree : Fin count → ℕ + homogeneous : ∀ exponent ∈ polynomial.support, ∀ index, + (∑ coordinate : Fin 3, exponent (index, coordinate)) = multidegree index + +def equationVanishes {count : ℕ} (equation : MultihomogeneousEquation count) + (points : Fin count → PlanePoint) : Prop := + ∀ (vectors : Fin count → Fin 3 → ℂ) (nonzero : ∀ index, vectors index ≠ 0), + (∀ index, Projectivization.mk ℂ (vectors index) (nonzero index) = points index) → + MvPolynomial.eval (fun index => vectors index.1 index.2) equation.polynomial = 0 + +def IsProductZariskiClosed {count : ℕ} (locus : Set (Fin count → PlanePoint)) : Prop := + ∃ equations : Set (MultihomogeneousEquation count), + ∀ points, points ∈ locus ↔ ∀ equation ∈ equations, equationVanishes equation points + +def IsConfigurationZariskiClosed {count : ℕ} + (locus : Set (OrderedDistinctPoints count)) : Prop := + ∃ ambient : Set (Fin count → PlanePoint), IsProductZariskiClosed ambient ∧ + ∀ points, points ∈ locus ↔ points.val ∈ ambient + +abbrev ChartVariables (chart : Fin 3) := {coordinate : Fin 3 // coordinate ≠ chart} + +def dehomogenize (chart : Fin 3) (polynomial : MvPolynomial (Fin 3) ℂ) : + MvPolynomial (ChartVariables chart) ℂ := + MvPolynomial.eval₂ MvPolynomial.C + (fun coordinate => if equal : coordinate = chart then 1 + else MvPolynomial.X ⟨coordinate, equal⟩) polynomial + +def chartCoordinates (chart : Fin 3) (point : PlanePoint) : ChartVariables chart → ℂ := + fun coordinate => point.rep coordinate.val / point.rep chart + +/-- Local multiplicity lower bounds are membership in powers of the point ideal. -/ +def multiplicityAtLeast (polynomial : MvPolynomial (Fin 3) ℂ) + (point : PlanePoint) (multiplicity : ℕ) : Prop := + ∀ chart : Fin 3, point.rep chart ≠ 0 → + AffineMultiplicity.orderAtLeast (chartCoordinates chart point) multiplicity + (dehomogenize chart polynomial) + +theorem chart_exists (point : PlanePoint) : ∃ chart : Fin 3, point.rep chart ≠ 0 := by + by_contra absent + apply point.rep_nonzero + funext chart + exact Classical.not_not.mp (fun nonzero => absent ⟨chart, nonzero⟩) + +end Nagata.ProjectiveGeometry + +namespace Nagata.Workers.W30 + +open UniqueFactorizationMonoid + +abbrev TernaryPolynomial := MvPolynomial (Fin 3) ℂ + +local instance : DecidableEq (Associates TernaryPolynomial) := Classical.decEq _ + +def equationMultiplicity (polynomial : TernaryPolynomial) : + Associates TernaryPolynomial →₀ ℕ := + factorization (Associates.mk polynomial) + +def associatePrincipalIdeal (associate : Associates TernaryPolynomial) : + Ideal TernaryPolynomial := + (Ideal.associatesEquivIsPrincipal TernaryPolynomial associate).val + +def equationIdealCycle (polynomial : TernaryPolynomial) : Ideal TernaryPolynomial →₀ ℕ := + (equationMultiplicity polynomial).mapDomain associatePrincipalIdeal + +attribute [local instance] MvPolynomial.gradedAlgebra + +theorem exists_positive_degree_equation_of_homogeneous_cycle + (cycle : Ideal TernaryPolynomial →₀ ℕ) (nonzero : cycle ≠ 0) + (homogeneous : ∀ ideal ∈ cycle.support, + ideal.IsPrime ∧ ideal ≠ ⊥ ∧ ideal.IsPrincipal ∧ + ideal.IsHomogeneous (MvPolynomial.homogeneousSubmodule (Fin 3) ℂ)) : + ∃ polynomial : TernaryPolynomial, + polynomial ≠ 0 ∧ polynomial.IsHomogeneous polynomial.totalDegree ∧ + 0 < polynomial.totalDegree ∧ equationIdealCycle polynomial = cycle := by + sorry + +end Nagata.Workers.W30 + +namespace Nagata.W16 + +abbrev PlanePolynomial := MvPolynomial (Fin 3) ℂ + +structure NonzeroHomogeneousForm (degree : ℕ) where + polynomial : PlanePolynomial + homogeneous : polynomial.IsHomogeneous degree + nonzero : polynomial ≠ 0 + +theorem homogeneous_eval_scale {Variables Coefficient : Type*} [CommSemiring Coefficient] + {polynomial : MvPolynomial Variables Coefficient} {degree : ℕ} + (homogeneous : polynomial.IsHomogeneous degree) + (coordinates : Variables → Coefficient) (scalar : Coefficient) : + MvPolynomial.eval (fun index => scalar * coordinates index) polynomial = + scalar ^ degree * MvPolynomial.eval coordinates polynomial := by + classical + simp only [MvPolynomial.eval_eq, Finset.mul_sum] + apply Finset.sum_congr rfl + intro exponent supported + simp only [mul_pow, Finset.prod_mul_distrib, Finset.prod_pow_eq_pow_sum] + rw [← homogeneous.degree_eq_sum_deg_support supported] + ac_rfl + +open Nagata.ProjectiveGeometry + +theorem eval_dehomogenize (chart : Fin 3) (polynomial : PlanePolynomial) + (coordinates : ChartVariables chart → ℂ) : + MvPolynomial.eval coordinates (dehomogenize chart polynomial) = + MvPolynomial.eval + (fun index => if equal : index = chart then 1 else coordinates ⟨index, equal⟩) + polynomial := by + classical + unfold dehomogenize + rw [← MvPolynomial.eval_assoc] + apply congrArg (fun values : Fin 3 → ℂ => MvPolynomial.eval values polynomial) + funext index + by_cases equal : index = chart <;> simp [equal, Function.comp_apply] + +theorem eval_dehomogenize_normalized {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (coordinates : Fin 3 → ℂ) (chart_nonzero : coordinates chart ≠ 0) : + MvPolynomial.eval (fun index : ChartVariables chart => coordinates index.val / coordinates chart) + (dehomogenize chart polynomial) = + (coordinates chart)⁻¹ ^ degree * MvPolynomial.eval coordinates polynomial := by + classical + rw [eval_dehomogenize] + have normalized : + (fun index : Fin 3 => if equal : index = chart then (1 : ℂ) + else coordinates index / coordinates chart) = + fun index => (coordinates chart)⁻¹ * coordinates index := by + funext index + by_cases equal : index = chart + · subst index + simp [chart_nonzero] + · simp [equal, div_eq_mul_inv, mul_comm] + rw [normalized] + exact homogeneous_eval_scale homogeneous coordinates (coordinates chart)⁻¹ + +theorem eval_eq_zero_of_dehomogenize_eq_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (chart_zero : dehomogenize chart polynomial = 0) + (coordinates : Fin 3 → ℂ) (chart_nonzero : coordinates chart ≠ 0) : + MvPolynomial.eval coordinates polynomial = 0 := by + have evaluated := congrArg + (MvPolynomial.eval (fun index : ChartVariables chart => coordinates index.val / coordinates chart)) + chart_zero + rw [eval_dehomogenize_normalized homogeneous chart coordinates chart_nonzero, map_zero] at evaluated + exact (mul_eq_zero.mp evaluated).resolve_left (pow_ne_zero degree (inv_ne_zero chart_nonzero)) + +theorem eq_zero_of_dehomogenize_eq_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (chart : Fin 3) + (chart_zero : dehomogenize chart polynomial = 0) : polynomial = 0 := by + have multiplied : MvPolynomial.X chart * polynomial = 0 := by + apply ((MvPolynomial.isHomogeneous_X ℂ chart).mul homogeneous).eq_zero_of_forall_eval_eq_zero + intro coordinates + rw [MvPolynomial.eval_mul, MvPolynomial.eval_X] + by_cases chart_nonzero : coordinates chart = 0 + · simp [chart_nonzero] + · rw [eval_eq_zero_of_dehomogenize_eq_zero homogeneous chart chart_zero coordinates chart_nonzero, + mul_zero] + exact (mul_eq_zero.mp multiplied).resolve_left (MvPolynomial.X_ne_zero chart) + +theorem dehomogenize_ne_zero {degree : ℕ} {polynomial : PlanePolynomial} + (homogeneous : polynomial.IsHomogeneous degree) (nonzero : polynomial ≠ 0) + (chart : Fin 3) : ProjectiveGeometry.dehomogenize chart polynomial ≠ 0 := by + intro chart_zero + exact nonzero (eq_zero_of_dehomogenize_eq_zero homogeneous chart chart_zero) + +end Nagata.W16 + +namespace Nagata.Workers.W10 + +open Nagata.Workers.W30 Nagata.W16 + +attribute [local instance] MvPolynomial.gradedAlgebra + +/-- Nonzero finite cycles of homogeneous prime plane ideals, with natural weights. -/ +def EffectivePlaneCurve := {cycle : Ideal TernaryPolynomial →₀ ℕ // + cycle ≠ 0 ∧ ∀ ideal ∈ cycle.support, + ideal.IsPrime ∧ ideal ≠ ⊥ ∧ ideal.IsPrincipal ∧ + ideal.IsHomogeneous (MvPolynomial.homogeneousSubmodule (Fin 3) ℂ)} + +/-- An equation realizing the entire cycle, including repeated components. -/ +def curveEquation (curve : EffectivePlaneCurve) : TernaryPolynomial := + Classical.choose (exists_positive_degree_equation_of_homogeneous_cycle + curve.val curve.property.1 curve.property.2) + +theorem curveEquation_spec (curve : EffectivePlaneCurve) : + curveEquation curve ≠ 0 ∧ + (curveEquation curve).IsHomogeneous (curveEquation curve).totalDegree ∧ + 0 < (curveEquation curve).totalDegree ∧ equationIdealCycle (curveEquation curve) = curve.val := + Classical.choose_spec (exists_positive_degree_equation_of_homogeneous_cycle + curve.val curve.property.1 curve.property.2) + +theorem curveEquation_nonzero (curve : EffectivePlaneCurve) : curveEquation curve ≠ 0 := + (curveEquation_spec curve).1 + +def curveDegree (curve : EffectivePlaneCurve) : ℕ := (curveEquation curve).totalDegree + +theorem curveEquation_homogeneous (curve : EffectivePlaneCurve) : + (curveEquation curve).IsHomogeneous (curveDegree curve) := + (curveEquation_spec curve).2.1 + +def curveForm (curve : EffectivePlaneCurve) : NonzeroHomogeneousForm (curveDegree curve) := + ⟨curveEquation curve, curveEquation_homogeneous curve, curveEquation_nonzero curve⟩ + +end Nagata.Workers.W10 + +namespace Nagata.ProjectiveGeometry + +def formOrdinaryMultiplicity {degree : ℕ} (form : W16.NonzeroHomogeneousForm degree) + (point : PlanePoint) : ℕ := + let chart := Classical.choose (chart_exists point) + AffineMultiplicity.ordinaryMultiplicity (chartCoordinates chart point) + (dehomogenize chart form.polynomial) + (W16.dehomogenize_ne_zero form.homogeneous form.nonzero chart) + +end Nagata.ProjectiveGeometry + +namespace Nagata.W15 + +open Nagata.Workers.W10 Nagata.ProjectiveGeometry + +def curveOrdinaryMultiplicity (curve : EffectivePlaneCurve) (point : PlanePoint) : ℕ := + formOrdinaryMultiplicity (curveForm curve) point + +end Nagata.W15 + +namespace Nagata + +open ProjectiveGeometry + +def FullNagata : Prop := + ∀ count : ℕ, 10 ≤ count → + ∃ exceptional : ℕ → Set (OrderedDistinctPoints count), + (∀ index, IsConfigurationZariskiClosed (exceptional index) ∧ + exceptional index ≠ Set.univ) ∧ + (∃ points : OrderedDistinctPoints count, ∀ index, points ∉ exceptional index) ∧ + ∀ points : OrderedDistinctPoints count, (∀ index, points ∉ exceptional index) → + ∀ degree : ℕ, 1 ≤ degree → + ∀ polynomial : MvPolynomial (Fin 3) ℂ, + polynomial ≠ 0 → polynomial.IsHomogeneous degree → + ∀ multiplicities : Fin count → ℕ, + (∀ index, multiplicityAtLeast polynomial (points.val index) (multiplicities index)) → + (∑ index, (multiplicities index : ℝ)) < (degree : ℝ) * Real.sqrt (count : ℝ) + +theorem nagata_conjecture : + ∀ count : ℕ, 10 ≤ count → + ∃ exceptional : ℕ → Set (OrderedDistinctPoints count), + (∀ index, IsConfigurationZariskiClosed (exceptional index) ∧ + exceptional index ≠ Set.univ) ∧ + (∃ points : OrderedDistinctPoints count, ∀ index, points ∉ exceptional index) ∧ + ∀ points : OrderedDistinctPoints count, (∀ index, points ∉ exceptional index) → + ∀ curve : Workers.W10.EffectivePlaneCurve, ∀ multiplicities : Fin count → ℕ, + (∀ index, multiplicities index ≤ W15.curveOrdinaryMultiplicity curve (points.val index)) → + (∑ index, (multiplicities index : ℝ)) < + (Workers.W10.curveDegree curve : ℝ) * Real.sqrt (count : ℝ) := by + sorry + +theorem nagata_conjecture_coordinates : FullNagata := by + sorry + +end Nagata + +end + +end OAI diff --git a/tasks/nagata/tests/grade.py b/tasks/nagata/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/nagata/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/nagata/tests/task.json b/tasks/nagata/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a789cf1e02f3a247426978a7b987e6719424df79 --- /dev/null +++ b/tasks/nagata/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "Nagata", + "comparator": { + "theorem_names": [ + "OAI.Nagata.Workers.W30.exists_positive_degree_equation_of_homogeneous_cycle", + "OAI.Nagata.nagata_conjecture", + "OAI.Nagata.nagata_conjecture_coordinates" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12248 +} \ No newline at end of file diff --git a/tasks/nagata/tests/test.sh b/tasks/nagata/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/nagata/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/naimark/environment/Dockerfile b/tasks/naimark/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/naimark/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/naimark/environment/fetch_mathlib.sh b/tasks/naimark/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/naimark/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/naimark/environment/lake-manifest.json b/tasks/naimark/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/naimark/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/naimark/environment/lakefile.lean b/tasks/naimark/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/naimark/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/naimark/environment/lean_setup.sh b/tasks/naimark/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/naimark/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/naimark/environment/pack_submission.py b/tasks/naimark/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/naimark/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/naimark/instruction.md b/tasks/naimark/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f6b1fa2339c1291f0842a7dae315f8e1ffaab6dc --- /dev/null +++ b/tasks/naimark/instruction.md @@ -0,0 +1,108 @@ +# openai/math challenge `Naimark` (family 297) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 297 of the release, *A ZFC counterexample to Naimark's problem* +(Operator algebras). The family as a whole: Gives an alternative to \href{https://arxiv.org/abs/2609.26930v1}{Tanaka's ZFC construction} of a unital infinite-dimensional simple complex $C^*$-algebra with a faithful tracial state and exactly one nonzero irreducible representation up to unitary equivalence. Thus the unrestricted compact-operator characterization fails without additional set-theoretic assumptions; the counterexample is nonseparable. + +The challenge is `Naimark`, also at `/opt/openai-math/challenges/Naimark.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u v w + +namespace NaimarkZFC + +def IsSimpleCStar (A : Type u) [CStarAlgebra A] : Prop := + Nontrivial A ∧ ∀ I : TwoSidedIdeal A, IsClosed (I : Set A) → I = ⊥ ∨ I = ⊤ + +def IsState {A : Type u} [CStarAlgebra A] (f : A →L[ℂ] ℂ) : Prop := + ‖f‖ = 1 ∧ ∀ a : A, (f (star a * a)).im = 0 ∧ 0 ≤ (f (star a * a)).re + +def IsFaithfulTracialState {A : Type u} [CStarAlgebra A] (f : A →L[ℂ] ℂ) : Prop := + IsState f ∧ (∀ a b : A, f (a * b) = f (b * a)) ∧ + ∀ a : A, a ≠ 0 → 0 < (f (star a * a)).re + +def IsIrreducible {A : Type u} [CStarAlgebra A] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) : Prop := + π ≠ 0 ∧ ∀ M : Submodule ℂ H, IsClosed (M : Set H) → + (∀ a : A, ∀ x ∈ M, π a x ∈ M) → M = ⊥ ∨ M = ⊤ + +def UnitarilyEquivalent {A : Type u} [CStarAlgebra A] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + {K : Type w} [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) (ρ : A →⋆ₙₐ[ℂ] (K →L[ℂ] K)) : Prop := + ∃ U : H ≃ₗᵢ[ℂ] K, ∀ a : A, ∀ x : H, U (π a x) = ρ a (U x) + +def HasUniqueIrreducibleRepresentation (A : Type u) [CStarAlgebra A] : Prop := + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (K : Type w) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) (ρ : A →⋆ₙₐ[ℂ] (K →L[ℂ] K)), + IsIrreducible π → IsIrreducible ρ → UnitarilyEquivalent π ρ + +def IsIsomorphicToCompacts (A : Type u) [CStarAlgebra A] + (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] : Prop := + ∃ φ : A →⋆ₙₐ[ℂ] (H →L[ℂ] H), Function.Injective φ ∧ + ∀ T : H →L[ℂ] H, (∃ a : A, φ a = T) ↔ IsCompactOperator T + +theorem main : + ∃ (A : Type u) (_ : CStarAlgebra A), + IsSimpleCStar A ∧ ¬ FiniteDimensional ℂ A ∧ + (∃ τ : A →L[ℂ] ℂ, IsFaithfulTracialState τ) ∧ + HasUniqueIrreducibleRepresentation.{u, v, w} A ∧ + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H], + ¬ IsIsomorphicToCompacts A H := by + sorry + +end NaimarkZFC + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Naimark.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.NaimarkZFC.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/naimark/solution/closure.txt b/tasks/naimark/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3eb62be15dad6b90d6e0bdd50fd0fc4c8c5af20d --- /dev/null +++ b/tasks/naimark/solution/closure.txt @@ -0,0 +1,16 @@ +OAI.Analysis.Naimark.Amalgamation +OAI.Analysis.Naimark.Basic +OAI.Analysis.Naimark.CAR +OAI.Analysis.Naimark.Dependencies +OAI.Analysis.Naimark.DirectLimit +OAI.Analysis.Naimark.Extension +OAI.Analysis.Naimark.HNN +OAI.Analysis.Naimark.Homogeneity +OAI.Analysis.Naimark.Omission +OAI.Analysis.Naimark.Operators +OAI.Analysis.Naimark.Peaking +OAI.Analysis.Naimark.Recursion +OAI.Analysis.Naimark.Representations +OAI.Analysis.Naimark.Stages +OAI.Analysis.Naimark.States +OAI.Analysis.Naimark.Tracial diff --git a/tasks/naimark/solution/reference.py b/tasks/naimark/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/naimark/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/naimark/solution/solve.sh b/tasks/naimark/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b0c80c51f02887e54993c5ebd5d7b65335d34577 --- /dev/null +++ b/tasks/naimark/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Naimark, i.e. module OAI.Analysis.Naimark.Tracial and the +# 16 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Naimark.Tracial /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Naimark" diff --git a/tasks/naimark/task.toml b/tasks/naimark/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f8502ec2b444a12e94550d455341dbc856d816e9 --- /dev/null +++ b/tasks/naimark/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/naimark" +version = "1.0.0" +description = "Prove Naimark (openai/math family 297: A ZFC counterexample to Naimark's problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Naimark.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Naimark" +family = "297" +family_title = "A ZFC counterexample to Naimark's problem" +subject = "Operator algebras" +theorems = ["OAI.NaimarkZFC.main"] +definition_holes = [] +fixed_definitions = ["OAI.NaimarkZFC.IsSimpleCStar", "OAI.NaimarkZFC.IsState", "OAI.NaimarkZFC.IsFaithfulTracialState", "OAI.NaimarkZFC.IsIrreducible", "OAI.NaimarkZFC.UnitarilyEquivalent", "OAI.NaimarkZFC.HasUniqueIrreducibleRepresentation", "OAI.NaimarkZFC.IsIsomorphicToCompacts"] +reference_module = "OAI.Analysis.Naimark.Tracial" +reference_modules = 16 +reference_lean_bytes = 1208784 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2857 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12787 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/naimark/tests/Challenge.lean b/tasks/naimark/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..702192c1f36cc75b8ca889b3d93c4a3b26a30f86 --- /dev/null +++ b/tasks/naimark/tests/Challenge.lean @@ -0,0 +1,57 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u v w + +namespace NaimarkZFC + +def IsSimpleCStar (A : Type u) [CStarAlgebra A] : Prop := + Nontrivial A ∧ ∀ I : TwoSidedIdeal A, IsClosed (I : Set A) → I = ⊥ ∨ I = ⊤ + +def IsState {A : Type u} [CStarAlgebra A] (f : A →L[ℂ] ℂ) : Prop := + ‖f‖ = 1 ∧ ∀ a : A, (f (star a * a)).im = 0 ∧ 0 ≤ (f (star a * a)).re + +def IsFaithfulTracialState {A : Type u} [CStarAlgebra A] (f : A →L[ℂ] ℂ) : Prop := + IsState f ∧ (∀ a b : A, f (a * b) = f (b * a)) ∧ + ∀ a : A, a ≠ 0 → 0 < (f (star a * a)).re + +def IsIrreducible {A : Type u} [CStarAlgebra A] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) : Prop := + π ≠ 0 ∧ ∀ M : Submodule ℂ H, IsClosed (M : Set H) → + (∀ a : A, ∀ x ∈ M, π a x ∈ M) → M = ⊥ ∨ M = ⊤ + +def UnitarilyEquivalent {A : Type u} [CStarAlgebra A] + {H : Type v} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + {K : Type w} [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) (ρ : A →⋆ₙₐ[ℂ] (K →L[ℂ] K)) : Prop := + ∃ U : H ≃ₗᵢ[ℂ] K, ∀ a : A, ∀ x : H, U (π a x) = ρ a (U x) + +def HasUniqueIrreducibleRepresentation (A : Type u) [CStarAlgebra A] : Prop := + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (K : Type w) [NormedAddCommGroup K] [InnerProductSpace ℂ K] [CompleteSpace K] + (π : A →⋆ₙₐ[ℂ] (H →L[ℂ] H)) (ρ : A →⋆ₙₐ[ℂ] (K →L[ℂ] K)), + IsIrreducible π → IsIrreducible ρ → UnitarilyEquivalent π ρ + +def IsIsomorphicToCompacts (A : Type u) [CStarAlgebra A] + (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] : Prop := + ∃ φ : A →⋆ₙₐ[ℂ] (H →L[ℂ] H), Function.Injective φ ∧ + ∀ T : H →L[ℂ] H, (∃ a : A, φ a = T) ↔ IsCompactOperator T + +theorem main : + ∃ (A : Type u) (_ : CStarAlgebra A), + IsSimpleCStar A ∧ ¬ FiniteDimensional ℂ A ∧ + (∃ τ : A →L[ℂ] ℂ, IsFaithfulTracialState τ) ∧ + HasUniqueIrreducibleRepresentation.{u, v, w} A ∧ + ∀ (H : Type v) [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H], + ¬ IsIsomorphicToCompacts A H := by + sorry + +end NaimarkZFC + +end + +end OAI diff --git a/tasks/naimark/tests/grade.py b/tasks/naimark/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/naimark/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/naimark/tests/task.json b/tasks/naimark/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1aad857f72fd5c296fff4afd5bea9cd926653d7b --- /dev/null +++ b/tasks/naimark/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Naimark", + "comparator": { + "theorem_names": [ + "OAI.NaimarkZFC.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11887 +} \ No newline at end of file diff --git a/tasks/naimark/tests/test.sh b/tasks/naimark/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/naimark/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/navier-stokes-alternating/environment/Dockerfile b/tasks/navier-stokes-alternating/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/navier-stokes-alternating/environment/fetch_mathlib.sh b/tasks/navier-stokes-alternating/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/navier-stokes-alternating/environment/lake-manifest.json b/tasks/navier-stokes-alternating/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/navier-stokes-alternating/environment/lakefile.lean b/tasks/navier-stokes-alternating/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/navier-stokes-alternating/environment/lean_setup.sh b/tasks/navier-stokes-alternating/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/navier-stokes-alternating/environment/pack_submission.py b/tasks/navier-stokes-alternating/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/navier-stokes-alternating/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/navier-stokes-alternating/instruction.md b/tasks/navier-stokes-alternating/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fd78659302b274536def791b178188cfd72c49a9 --- /dev/null +++ b/tasks/navier-stokes-alternating/instruction.md @@ -0,0 +1,296 @@ +# openai/math challenge `NavierStokesAlternating` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `NavierStokesAlternating`, also at `/opt/openai-math/challenges/NavierStokesAlternating.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped BigOperators ENNReal Topology ContDiff +open MeasureTheory + +namespace AlternatingNS + +abbrev Rule := ℕ × ℕ × Fin 3 + +abbrev Machine := ℕ × ℕ × ℕ × List ℕ × List (Option Rule) + +namespace Machine + +def states (M : Machine) : ℕ := M.1 + 1 + +def alphabet (M : Machine) : ℕ := M.2.1 + 1 + +def initialState (M : Machine) : ℕ := M.2.2.1 + +def haltingStates (M : Machine) : List ℕ := M.2.2.2.1 + +def table (M : Machine) : List (Option Rule) := M.2.2.2.2 + +def instruction (M : Machine) (q a : ℕ) : Option Rule := + (M.table[q * M.alphabet + a]?).join + +def WellFormed (M : Machine) : Prop := + M.initialState < M.states ∧ + (∀ q ∈ M.haltingStates, q < M.states) ∧ + ∀ q a r, q < M.states → a < M.alphabet → M.instruction q a = some r → + r.1 < M.states ∧ r.2.1 < M.alphabet + +def ValidInput (M : Machine) (w : List ℕ) : Prop := + ∀ a ∈ w, a < M.alphabet + +structure Configuration where + state : ℕ + head : ℤ + tape : ℤ → ℕ + +def isHalting (M : Machine) (c : Configuration) : Bool := + decide (c.state = M.states ∨ c.state ∈ M.haltingStates) + +def initial (M : Machine) (w : List ℕ) : Configuration where + state := M.initialState + head := 0 + tape := fun i => if 0 ≤ i then w[i.toNat]?.getD 0 else 0 + +def step (M : Machine) (c : Configuration) : Configuration := + if M.isHalting c then c else + match M.instruction c.state (c.tape c.head) with + | none => { c with state := M.states } + | some r => + { state := r.1 + head := c.head + ((r.2.2.val : ℤ) - 1) + tape := Function.update c.tape c.head r.2.1 } + +def run (M : Machine) (w : List ℕ) (n : ℕ) : Configuration := + (M.step)^[n] (M.initial w) + +def Halts (M : Machine) (w : List ℕ) : Prop := + ∃ n : ℕ, M.isHalting (M.run w n) = true + +end Machine + +abbrev Space := EuclideanSpace ℝ (Fin 3) +abbrev Field (E : Type*) := ℝ → Space → E +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev MultiIndex := Fin 3 → ℕ + +noncomputable section + +def e (i : Fin 3) : Space := EuclideanSpace.single i 1 + +def dx {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (i : Fin 3) (F : Field E) : Field E := + fun t x => fderiv ℝ (F t) x (e i) + +def dt {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (F : Field E) : Field E := + fun t x => fderivWithin ℝ (fun s => F s x) (Set.Ici 0) t 1 + +def spatial {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (α : MultiIndex) (F : Field E) : Field E := + (dx 0)^[α 0] ((dx 1)^[α 1] ((dx 2)^[α 2] F)) + +def mixed {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (l : ℕ) (α : MultiIndex) (F : Field E) : Field E := + dt^[l] (spatial α F) + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i : Fin 3, dx i u t x i + +def grad (p : Pressure) (t : ℝ) (x : Space) : Space := + (EuclideanSpace.equiv (Fin 3) ℝ).symm (fun i => dx i p t x) + +def laplacian (u : Velocity) (t : ℝ) (x : Space) : Space := + ∑ i : Fin 3, dx i (dx i u) t x + +def advection (u : Velocity) (t : ℝ) (x : Space) : Space := + fderiv ℝ (u t) x (u t x) + +def residual (ν : ℝ) (u : Velocity) : Velocity := + fun t x => dt u t x + advection u t x - ν • laplacian u t x + +def timeCylinder (T : ℝ) : Set (ℝ × Space) := Set.Icc 0 T ×ˢ Set.univ + +def Smooth {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (F : Field E) : Prop := + ContDiffOn ℝ (∞) (Function.uncurry F) (Set.Ici 0 ×ˢ Set.univ) + +def ClassicalRegularity (u : Velocity) (p : Pressure) : Prop := + (∀ x, DifferentiableOn ℝ (fun t => u t x) (Set.Ici 0)) ∧ + (∀ t, 0 ≤ t → Differentiable ℝ (u t)) ∧ + (∀ t, 0 ≤ t → ∀ i, Differentiable ℝ (dx i u t)) ∧ + (∀ t, 0 ≤ t → Differentiable ℝ (p t)) ∧ + ∀ T, 0 ≤ T → + ContinuousOn (Function.uncurry u) (timeCylinder T) ∧ + ContinuousOn (Function.uncurry (dt u)) (timeCylinder T) ∧ + (∀ i, ContinuousOn (Function.uncurry (dx i u)) (timeCylinder T)) ∧ + (∀ i j, ContinuousOn (Function.uncurry (dx i (dx j u))) (timeCylinder T)) ∧ + ContinuousOn (Function.uncurry p) (timeCylinder T) ∧ + (∀ i, ContinuousOn (Function.uncurry (dx i p)) (timeCylinder T)) + +def ContinuousInH {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (k : ℕ) (F : Field E) (T : ℝ) : Prop := + ∀ α : MultiIndex, (∑ i, α i) ≤ k → + ∃ g : ℝ → Lp E 2 (volume : Measure Space), + ContinuousOn g (Set.Icc 0 T) ∧ + ∀ t ∈ Set.Icc 0 T, + ∀ᵐ x ∂(volume : Measure Space), (g t) x = spatial α F t x + +def C1InL2 (u : Velocity) (T : ℝ) : Prop := + ∃ g g' : ℝ → Lp Space 2 (volume : Measure Space), + ContinuousOn g (Set.Icc 0 T) ∧ + ContinuousOn g' (Set.Icc 0 T) ∧ + (∀ t ∈ Set.Icc 0 T, HasDerivWithinAt g (g' t) (Set.Icc 0 T) t) ∧ + (∀ t ∈ Set.Icc 0 T, ∀ᵐ x ∂(volume : Measure Space), (g t) x = u t x) ∧ + (∀ t ∈ Set.Icc 0 T, ∀ᵐ x ∂(volume : Measure Space), (g' t) x = dt u t x) + +def CompetitorEnergyClass (u : Velocity) (p : Pressure) : Prop := + ∀ T, 0 ≤ T → + ContinuousInH 2 u T ∧ C1InL2 u T ∧ ContinuousInH 1 p T ∧ + ∃ C : ℝ, ∀ t ∈ Set.Icc 0 T, ∀ x, ‖u t x‖ ≤ C + +def EnergyClass (u : Velocity) (p : Pressure) : Prop := + CompetitorEnergyClass u p ∧ + ∀ T, 0 ≤ T → ∃ C : ℝ, ∀ t ∈ Set.Icc 0 T, ∀ x, + ‖u t x‖ + ‖fderiv ℝ (u t) x‖ ≤ C + +def NavierStokes (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + ClassicalRegularity u p ∧ + (∀ x, u 0 x = 0) ∧ + ∀ t, 0 ≤ t → ∀ x, + div u t x = 0 ∧ + dt u t x + advection u t x = -grad p t x + ν • laplacian u t x + f t x + +def Rapid (F : Velocity) : Prop := + ∀ J l : ℕ, ∀ α : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ + ∀ t, 0 ≤ t → ∀ x, + (1 + t + ‖x‖) ^ J * ‖mixed l α F t x‖ ≤ C + +def SupportedIn (F : Velocity) (K : Set Space) : Prop := + ∀ t, 0 ≤ t → Function.support (F t) ⊆ K + +def IsTrajectory (u : Velocity) (a : Space) (γ : ℝ → Space) : Prop := + γ 0 = a ∧ ∀ t, 0 ≤ t → HasDerivWithinAt γ (u t (γ t)) (Set.Ici 0) t + +def observedParticle : Space := (EuclideanSpace.equiv (Fin 3) ℝ).symm ![-1, 0, 0] + +abbrev RationalPoint := ℚ × ℚ × ℚ × ℚ +abbrev RationalVector := ℚ × ℚ × ℚ +abbrev IndexCode := ℕ × ℕ × ℕ +abbrev Program := Nat.Partrec.Code +abbrev FieldProgram := Program × Program × Program + +def Returns {A B : Type*} [Encodable A] [Encodable B] + (c : Program) (a : A) (b : B) : Prop := + Encodable.encode b ∈ c.eval (Encodable.encode a) + +def index (α : IndexCode) : MultiIndex := ![α.1, α.2.1, α.2.2] + +def rationalVector (q : RationalVector) : Space := + (EuclideanSpace.equiv (Fin 3) ℝ).symm ![(q.1 : ℝ), (q.2.1 : ℝ), (q.2.2 : ℝ)] + +def rationalPoint (q : RationalPoint) : ℝ × Space := + ((q.1 : ℝ), rationalVector q.2) + +def dyadicError (n : ℕ) : ℝ := (1 / 2 : ℝ) ^ n + +def ComputableReal (r : ℝ) : Prop := + ∃ a : ℕ → ℚ, Computable (fun n => ((a n).num, (a n).den)) ∧ + ∀ n, |r - (a n : ℝ)| ≤ dyadicError n + +def ProgramFor (c : FieldProgram) (F : Velocity) : Prop := + (∀ (l : ℕ) (α : IndexCode) (q : RationalPoint) (k : ℕ), + ∃ v : RationalVector, Returns c.1 (l, α, q, k) v ∧ + (0 ≤ q.1 → + ‖rationalVector v - mixed l (index α) F (rationalPoint q).1 (rationalPoint q).2‖ + ≤ dyadicError k)) ∧ + (∀ (l : ℕ) (α : IndexCode) (R k : ℕ), + ∃ m : ℕ, Returns c.2.1 (l, α, R, k) m ∧ + ∀ z z' : ℝ × Space, + 0 ≤ z.1 → 0 ≤ z'.1 → ‖z‖ ≤ R → ‖z'‖ ≤ R → + ‖z - z'‖ ≤ dyadicError m → + ‖mixed l (index α) F z.1 z.2 - mixed l (index α) F z'.1 z'.2‖ ≤ dyadicError k) ∧ + (∀ (J l : ℕ) (α : IndexCode), + ∃ B : ℕ, Returns c.2.2 (J, l, α) B ∧ + ∀ t, 0 ≤ t → ∀ x, + (1 + t + ‖x‖) ^ J * ‖mixed l (index α) F t x‖ ≤ B) + +def AlternatingConclusion (ν : ℝ) : Prop := + ∃ (compileForce compileVelocity : Machine × List ℕ → FieldProgram), + Computable compileForce ∧ Computable compileVelocity ∧ + ∃ K : Set Space, IsCompact K ∧ + ∀ (M : Machine) (w : List ℕ), M.WellFormed → M.ValidInput w → + ∃ (f U : Velocity) (X : Space → ℝ → Space), + ProgramFor (compileForce (M, w)) f ∧ + ProgramFor (compileVelocity (M, w)) U ∧ + Smooth f ∧ Smooth U ∧ + SupportedIn f K ∧ SupportedIn U K ∧ Rapid f ∧ Rapid U ∧ + f = residual ν U ∧ + NavierStokes ν f U (fun _ _ => 0) ∧ EnergyClass U (fun _ _ => 0) ∧ + (∀ (v : Velocity) (p : Pressure), + NavierStokes ν f v p → CompetitorEnergyClass v p → + ∀ t, 0 ≤ t → ∀ x, v t x = U t x ∧ p t x = 0) ∧ + (∀ a, IsTrajectory U a (X a)) ∧ + (∀ a γ, IsTrajectory U a γ → ∀ t, 0 ≤ t → γ t = X a t) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ 0 < X observedParticle t 0) ↔ M.Halts w) + +end +end AlternatingNS + +namespace AlternatingNS + +theorem alternating (ν : ℝ) (hν : 0 < ν) (hc : ComputableReal ν) : + AlternatingConclusion ν := by + sorry + +end AlternatingNS + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/NavierStokesAlternating.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AlternatingNS.alternating` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/navier-stokes-alternating/solution/closure.txt b/tasks/navier-stokes-alternating/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc924cffcba3c06117ccc503c72c33b66c534a4e --- /dev/null +++ b/tasks/navier-stokes-alternating/solution/closure.txt @@ -0,0 +1,41 @@ +OAI.MathematicalPhysics.AlternatingFlow.Analytic +OAI.MathematicalPhysics.AlternatingFlow.AnalyticResult +OAI.MathematicalPhysics.AlternatingFlow.Arithmetic +OAI.MathematicalPhysics.AlternatingFlow.BaseNames +OAI.MathematicalPhysics.AlternatingFlow.CertifiedBounds +OAI.MathematicalPhysics.AlternatingFlow.Compilers +OAI.MathematicalPhysics.AlternatingFlow.Construction +OAI.MathematicalPhysics.AlternatingFlow.ConstructiveBounds +OAI.MathematicalPhysics.AlternatingFlow.DecayBounds +OAI.MathematicalPhysics.AlternatingFlow.DecoderBounds +OAI.MathematicalPhysics.AlternatingFlow.DecoderNames +OAI.MathematicalPhysics.AlternatingFlow.DerivativeBounds +OAI.MathematicalPhysics.AlternatingFlow.Detector +OAI.MathematicalPhysics.AlternatingFlow.Development +OAI.MathematicalPhysics.AlternatingFlow.Effective +OAI.MathematicalPhysics.AlternatingFlow.EffectiveProfiles +OAI.MathematicalPhysics.AlternatingFlow.Encoding +OAI.MathematicalPhysics.AlternatingFlow.EnergyUniqueness +OAI.MathematicalPhysics.AlternatingFlow.ExpNames +OAI.MathematicalPhysics.AlternatingFlow.FieldPrograms +OAI.MathematicalPhysics.AlternatingFlow.ForceNames +OAI.MathematicalPhysics.AlternatingFlow.InitialNames +OAI.MathematicalPhysics.AlternatingFlow.JetNames +OAI.MathematicalPhysics.AlternatingFlow.JetPrograms +OAI.MathematicalPhysics.AlternatingFlow.LocalNames +OAI.MathematicalPhysics.AlternatingFlow.LocalRules +OAI.MathematicalPhysics.AlternatingFlow.MachineProfiles +OAI.MathematicalPhysics.AlternatingFlow.Machines +OAI.MathematicalPhysics.AlternatingFlow.Main +OAI.MathematicalPhysics.AlternatingFlow.MixedPrograms +OAI.MathematicalPhysics.AlternatingFlow.Model +OAI.MathematicalPhysics.AlternatingFlow.Names +OAI.MathematicalPhysics.AlternatingFlow.ProfileNames +OAI.MathematicalPhysics.AlternatingFlow.Profiles +OAI.MathematicalPhysics.AlternatingFlow.Quantitative +OAI.MathematicalPhysics.AlternatingFlow.RecursiveBounds +OAI.MathematicalPhysics.AlternatingFlow.Scales +OAI.MathematicalPhysics.AlternatingFlow.SpatialCurls +OAI.MathematicalPhysics.AlternatingFlow.TimeGlue +OAI.MathematicalPhysics.AlternatingFlow.TypedPrograms +OAI.MathematicalPhysics.AlternatingFlow.VelocityNames diff --git a/tasks/navier-stokes-alternating/solution/reference.py b/tasks/navier-stokes-alternating/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/navier-stokes-alternating/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/navier-stokes-alternating/solution/solve.sh b/tasks/navier-stokes-alternating/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f1c4fc765714f1b0966291035878cc23bea02c91 --- /dev/null +++ b/tasks/navier-stokes-alternating/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of NavierStokesAlternating, i.e. module OAI.MathematicalPhysics.AlternatingFlow.Development and the +# 41 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.AlternatingFlow.Development /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of NavierStokesAlternating" diff --git a/tasks/navier-stokes-alternating/task.toml b/tasks/navier-stokes-alternating/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f25f4dcfe0e0b29c15cb5cd004f52b0ef217c95 --- /dev/null +++ b/tasks/navier-stokes-alternating/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/navier-stokes-alternating" +version = "1.0.0" +description = "Prove NavierStokesAlternating (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/NavierStokesAlternating.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "NavierStokesAlternating" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.AlternatingNS.alternating"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.AlternatingFlow.Development" +reference_modules = 41 +reference_lean_bytes = 385862 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 874 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12047 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/navier-stokes-alternating/tests/Challenge.lean b/tasks/navier-stokes-alternating/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0260ba9ba848f8a8b9869a46cf99242b4e9f7232 --- /dev/null +++ b/tasks/navier-stokes-alternating/tests/Challenge.lean @@ -0,0 +1,245 @@ +import Mathlib + +namespace OAI + +open scoped BigOperators ENNReal Topology ContDiff +open MeasureTheory + +namespace AlternatingNS + +abbrev Rule := ℕ × ℕ × Fin 3 + +abbrev Machine := ℕ × ℕ × ℕ × List ℕ × List (Option Rule) + +namespace Machine + +def states (M : Machine) : ℕ := M.1 + 1 + +def alphabet (M : Machine) : ℕ := M.2.1 + 1 + +def initialState (M : Machine) : ℕ := M.2.2.1 + +def haltingStates (M : Machine) : List ℕ := M.2.2.2.1 + +def table (M : Machine) : List (Option Rule) := M.2.2.2.2 + +def instruction (M : Machine) (q a : ℕ) : Option Rule := + (M.table[q * M.alphabet + a]?).join + +def WellFormed (M : Machine) : Prop := + M.initialState < M.states ∧ + (∀ q ∈ M.haltingStates, q < M.states) ∧ + ∀ q a r, q < M.states → a < M.alphabet → M.instruction q a = some r → + r.1 < M.states ∧ r.2.1 < M.alphabet + +def ValidInput (M : Machine) (w : List ℕ) : Prop := + ∀ a ∈ w, a < M.alphabet + +structure Configuration where + state : ℕ + head : ℤ + tape : ℤ → ℕ + +def isHalting (M : Machine) (c : Configuration) : Bool := + decide (c.state = M.states ∨ c.state ∈ M.haltingStates) + +def initial (M : Machine) (w : List ℕ) : Configuration where + state := M.initialState + head := 0 + tape := fun i => if 0 ≤ i then w[i.toNat]?.getD 0 else 0 + +def step (M : Machine) (c : Configuration) : Configuration := + if M.isHalting c then c else + match M.instruction c.state (c.tape c.head) with + | none => { c with state := M.states } + | some r => + { state := r.1 + head := c.head + ((r.2.2.val : ℤ) - 1) + tape := Function.update c.tape c.head r.2.1 } + +def run (M : Machine) (w : List ℕ) (n : ℕ) : Configuration := + (M.step)^[n] (M.initial w) + +def Halts (M : Machine) (w : List ℕ) : Prop := + ∃ n : ℕ, M.isHalting (M.run w n) = true + +end Machine + +abbrev Space := EuclideanSpace ℝ (Fin 3) +abbrev Field (E : Type*) := ℝ → Space → E +abbrev Velocity := Field Space +abbrev Pressure := Field ℝ +abbrev MultiIndex := Fin 3 → ℕ + +noncomputable section + +def e (i : Fin 3) : Space := EuclideanSpace.single i 1 + +def dx {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (i : Fin 3) (F : Field E) : Field E := + fun t x => fderiv ℝ (F t) x (e i) + +def dt {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (F : Field E) : Field E := + fun t x => fderivWithin ℝ (fun s => F s x) (Set.Ici 0) t 1 + +def spatial {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (α : MultiIndex) (F : Field E) : Field E := + (dx 0)^[α 0] ((dx 1)^[α 1] ((dx 2)^[α 2] F)) + +def mixed {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (l : ℕ) (α : MultiIndex) (F : Field E) : Field E := + dt^[l] (spatial α F) + +def div (u : Velocity) (t : ℝ) (x : Space) : ℝ := + ∑ i : Fin 3, dx i u t x i + +def grad (p : Pressure) (t : ℝ) (x : Space) : Space := + (EuclideanSpace.equiv (Fin 3) ℝ).symm (fun i => dx i p t x) + +def laplacian (u : Velocity) (t : ℝ) (x : Space) : Space := + ∑ i : Fin 3, dx i (dx i u) t x + +def advection (u : Velocity) (t : ℝ) (x : Space) : Space := + fderiv ℝ (u t) x (u t x) + +def residual (ν : ℝ) (u : Velocity) : Velocity := + fun t x => dt u t x + advection u t x - ν • laplacian u t x + +def timeCylinder (T : ℝ) : Set (ℝ × Space) := Set.Icc 0 T ×ˢ Set.univ + +def Smooth {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (F : Field E) : Prop := + ContDiffOn ℝ (∞) (Function.uncurry F) (Set.Ici 0 ×ˢ Set.univ) + +def ClassicalRegularity (u : Velocity) (p : Pressure) : Prop := + (∀ x, DifferentiableOn ℝ (fun t => u t x) (Set.Ici 0)) ∧ + (∀ t, 0 ≤ t → Differentiable ℝ (u t)) ∧ + (∀ t, 0 ≤ t → ∀ i, Differentiable ℝ (dx i u t)) ∧ + (∀ t, 0 ≤ t → Differentiable ℝ (p t)) ∧ + ∀ T, 0 ≤ T → + ContinuousOn (Function.uncurry u) (timeCylinder T) ∧ + ContinuousOn (Function.uncurry (dt u)) (timeCylinder T) ∧ + (∀ i, ContinuousOn (Function.uncurry (dx i u)) (timeCylinder T)) ∧ + (∀ i j, ContinuousOn (Function.uncurry (dx i (dx j u))) (timeCylinder T)) ∧ + ContinuousOn (Function.uncurry p) (timeCylinder T) ∧ + (∀ i, ContinuousOn (Function.uncurry (dx i p)) (timeCylinder T)) + +def ContinuousInH {E : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + (k : ℕ) (F : Field E) (T : ℝ) : Prop := + ∀ α : MultiIndex, (∑ i, α i) ≤ k → + ∃ g : ℝ → Lp E 2 (volume : Measure Space), + ContinuousOn g (Set.Icc 0 T) ∧ + ∀ t ∈ Set.Icc 0 T, + ∀ᵐ x ∂(volume : Measure Space), (g t) x = spatial α F t x + +def C1InL2 (u : Velocity) (T : ℝ) : Prop := + ∃ g g' : ℝ → Lp Space 2 (volume : Measure Space), + ContinuousOn g (Set.Icc 0 T) ∧ + ContinuousOn g' (Set.Icc 0 T) ∧ + (∀ t ∈ Set.Icc 0 T, HasDerivWithinAt g (g' t) (Set.Icc 0 T) t) ∧ + (∀ t ∈ Set.Icc 0 T, ∀ᵐ x ∂(volume : Measure Space), (g t) x = u t x) ∧ + (∀ t ∈ Set.Icc 0 T, ∀ᵐ x ∂(volume : Measure Space), (g' t) x = dt u t x) + +def CompetitorEnergyClass (u : Velocity) (p : Pressure) : Prop := + ∀ T, 0 ≤ T → + ContinuousInH 2 u T ∧ C1InL2 u T ∧ ContinuousInH 1 p T ∧ + ∃ C : ℝ, ∀ t ∈ Set.Icc 0 T, ∀ x, ‖u t x‖ ≤ C + +def EnergyClass (u : Velocity) (p : Pressure) : Prop := + CompetitorEnergyClass u p ∧ + ∀ T, 0 ≤ T → ∃ C : ℝ, ∀ t ∈ Set.Icc 0 T, ∀ x, + ‖u t x‖ + ‖fderiv ℝ (u t) x‖ ≤ C + +def NavierStokes (ν : ℝ) (f u : Velocity) (p : Pressure) : Prop := + ClassicalRegularity u p ∧ + (∀ x, u 0 x = 0) ∧ + ∀ t, 0 ≤ t → ∀ x, + div u t x = 0 ∧ + dt u t x + advection u t x = -grad p t x + ν • laplacian u t x + f t x + +def Rapid (F : Velocity) : Prop := + ∀ J l : ℕ, ∀ α : MultiIndex, ∃ C : ℝ, 0 ≤ C ∧ + ∀ t, 0 ≤ t → ∀ x, + (1 + t + ‖x‖) ^ J * ‖mixed l α F t x‖ ≤ C + +def SupportedIn (F : Velocity) (K : Set Space) : Prop := + ∀ t, 0 ≤ t → Function.support (F t) ⊆ K + +def IsTrajectory (u : Velocity) (a : Space) (γ : ℝ → Space) : Prop := + γ 0 = a ∧ ∀ t, 0 ≤ t → HasDerivWithinAt γ (u t (γ t)) (Set.Ici 0) t + +def observedParticle : Space := (EuclideanSpace.equiv (Fin 3) ℝ).symm ![-1, 0, 0] + +abbrev RationalPoint := ℚ × ℚ × ℚ × ℚ +abbrev RationalVector := ℚ × ℚ × ℚ +abbrev IndexCode := ℕ × ℕ × ℕ +abbrev Program := Nat.Partrec.Code +abbrev FieldProgram := Program × Program × Program + +def Returns {A B : Type*} [Encodable A] [Encodable B] + (c : Program) (a : A) (b : B) : Prop := + Encodable.encode b ∈ c.eval (Encodable.encode a) + +def index (α : IndexCode) : MultiIndex := ![α.1, α.2.1, α.2.2] + +def rationalVector (q : RationalVector) : Space := + (EuclideanSpace.equiv (Fin 3) ℝ).symm ![(q.1 : ℝ), (q.2.1 : ℝ), (q.2.2 : ℝ)] + +def rationalPoint (q : RationalPoint) : ℝ × Space := + ((q.1 : ℝ), rationalVector q.2) + +def dyadicError (n : ℕ) : ℝ := (1 / 2 : ℝ) ^ n + +def ComputableReal (r : ℝ) : Prop := + ∃ a : ℕ → ℚ, Computable (fun n => ((a n).num, (a n).den)) ∧ + ∀ n, |r - (a n : ℝ)| ≤ dyadicError n + +def ProgramFor (c : FieldProgram) (F : Velocity) : Prop := + (∀ (l : ℕ) (α : IndexCode) (q : RationalPoint) (k : ℕ), + ∃ v : RationalVector, Returns c.1 (l, α, q, k) v ∧ + (0 ≤ q.1 → + ‖rationalVector v - mixed l (index α) F (rationalPoint q).1 (rationalPoint q).2‖ + ≤ dyadicError k)) ∧ + (∀ (l : ℕ) (α : IndexCode) (R k : ℕ), + ∃ m : ℕ, Returns c.2.1 (l, α, R, k) m ∧ + ∀ z z' : ℝ × Space, + 0 ≤ z.1 → 0 ≤ z'.1 → ‖z‖ ≤ R → ‖z'‖ ≤ R → + ‖z - z'‖ ≤ dyadicError m → + ‖mixed l (index α) F z.1 z.2 - mixed l (index α) F z'.1 z'.2‖ ≤ dyadicError k) ∧ + (∀ (J l : ℕ) (α : IndexCode), + ∃ B : ℕ, Returns c.2.2 (J, l, α) B ∧ + ∀ t, 0 ≤ t → ∀ x, + (1 + t + ‖x‖) ^ J * ‖mixed l (index α) F t x‖ ≤ B) + +def AlternatingConclusion (ν : ℝ) : Prop := + ∃ (compileForce compileVelocity : Machine × List ℕ → FieldProgram), + Computable compileForce ∧ Computable compileVelocity ∧ + ∃ K : Set Space, IsCompact K ∧ + ∀ (M : Machine) (w : List ℕ), M.WellFormed → M.ValidInput w → + ∃ (f U : Velocity) (X : Space → ℝ → Space), + ProgramFor (compileForce (M, w)) f ∧ + ProgramFor (compileVelocity (M, w)) U ∧ + Smooth f ∧ Smooth U ∧ + SupportedIn f K ∧ SupportedIn U K ∧ Rapid f ∧ Rapid U ∧ + f = residual ν U ∧ + NavierStokes ν f U (fun _ _ => 0) ∧ EnergyClass U (fun _ _ => 0) ∧ + (∀ (v : Velocity) (p : Pressure), + NavierStokes ν f v p → CompetitorEnergyClass v p → + ∀ t, 0 ≤ t → ∀ x, v t x = U t x ∧ p t x = 0) ∧ + (∀ a, IsTrajectory U a (X a)) ∧ + (∀ a γ, IsTrajectory U a γ → ∀ t, 0 ≤ t → γ t = X a t) ∧ + ((∃ t : ℝ, 0 ≤ t ∧ 0 < X observedParticle t 0) ↔ M.Halts w) + +end +end AlternatingNS + +namespace AlternatingNS + +theorem alternating (ν : ℝ) (hν : 0 < ν) (hc : ComputableReal ν) : + AlternatingConclusion ν := by + sorry + +end AlternatingNS + +end OAI diff --git a/tasks/navier-stokes-alternating/tests/grade.py b/tasks/navier-stokes-alternating/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/navier-stokes-alternating/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/navier-stokes-alternating/tests/task.json b/tasks/navier-stokes-alternating/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c7539160cff558d30b2833f72db52300ab9b921e --- /dev/null +++ b/tasks/navier-stokes-alternating/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "NavierStokesAlternating", + "comparator": { + "theorem_names": [ + "OAI.AlternatingNS.alternating" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11147 +} \ No newline at end of file diff --git a/tasks/navier-stokes-alternating/tests/test.sh b/tasks/navier-stokes-alternating/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/navier-stokes-alternating/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/navier-stokes-velocity/environment/Dockerfile b/tasks/navier-stokes-velocity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/navier-stokes-velocity/environment/fetch_mathlib.sh b/tasks/navier-stokes-velocity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/navier-stokes-velocity/environment/lake-manifest.json b/tasks/navier-stokes-velocity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/navier-stokes-velocity/environment/lakefile.lean b/tasks/navier-stokes-velocity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/navier-stokes-velocity/environment/lean_setup.sh b/tasks/navier-stokes-velocity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/navier-stokes-velocity/environment/pack_submission.py b/tasks/navier-stokes-velocity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/navier-stokes-velocity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/navier-stokes-velocity/instruction.md b/tasks/navier-stokes-velocity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..26fa454a446df2d3d0bf789f604ff15b5d47e37c --- /dev/null +++ b/tasks/navier-stokes-velocity/instruction.md @@ -0,0 +1,1326 @@ +# openai/math challenge `NavierStokesVelocity` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `NavierStokesVelocity`, also at `/opt/openai-math/challenges/NavierStokesVelocity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace VelocityDetection +open scoped BigOperators Topology ContDiff +open Set Function Filter + +abbrev Coord (n : ℕ) := Fin n → ℝ + +abbrev ScalarField (n : ℕ) := ℝ → Coord n → ℝ + +abbrev VectorField (n : ℕ) := ℝ → Coord n → Coord n + +theorem neZeroTwo : NeZero 2 := ⟨Nat.succ_ne_zero 1⟩ + +theorem neZeroThree : NeZero 3 := ⟨Nat.succ_ne_zero 2⟩ + +theorem neZeroFive : NeZero 5 := ⟨Nat.succ_ne_zero 4⟩ + +def spatialD {n : ℕ} (i : Fin n) (q : ScalarField n) : ScalarField n := + fun t x => deriv (fun s => q t (Function.update x i s)) (x i) + +def timeD {n : ℕ} (q : ScalarField n) : ScalarField n := + fun t x => derivWithin (fun s => q s x) (Ici 0) t + +def laplacian {n : ℕ} (q : ScalarField n) : ScalarField n := + fun t x => ∑ i : Fin n, spatialD i (spatialD i q) t x + +def advection {n : ℕ} (a : VectorField n) (q : ScalarField n) : ScalarField n := + fun t x => ∑ i : Fin n, a t x i * spatialD i q t x + +def divergence {n : ℕ} (a : VectorField n) : ScalarField n := + fun t x => ∑ i : Fin n, spatialD i (fun s y => a s y i) t x + +def NavierStokes (ν : ℝ) (u : VectorField 3) (p : ScalarField 3) + (f : VectorField 3) : Prop := + (∀ (t : ℝ), 0 ≤ t → ∀ x : Coord 3, ∀ i : Fin 3, + timeD (fun s y => u s y i) t x + advection u (fun s y => u s y i) t x = + -spatialD i p t x + ν * laplacian (fun s y => u s y i) t x + f t x i) ∧ + (∀ (t : ℝ), 0 ≤ t → ∀ x, divergence u t x = 0) ∧ + (∀ x, u 0 x = 0) + +def horizontal (x : Coord 3) : Coord 2 := ![x 0, x 1] + +end VelocityDetection +end + +noncomputable section +namespace VelocityDetection.Stacks +open scoped BigOperators Topology ContDiff +open Set Function Filter + +inductive Move + | right + | stay + | left + deriving DecidableEq, Repr + +def update (b : ℕ) (m : Move) (β x y : ℕ) : ℕ × ℕ := + match m with + | .right => (b * x + β, y / b) + | .stay => (x, y - y % b + β) + | .left => (x / b, x % b + b * β + b ^ 2 * (y / b)) + +structure Rule (σ : Type*) (b : ℕ) where + target : σ + written : Fin b + move : Move + +structure Configuration (σ : Type*) where + state : σ + leftStack : ℕ + rightStack : ℕ + deriving DecidableEq + +def applyRule {σ : Type*} {b : ℕ} (r : Rule σ b) (c : Configuration σ) : Configuration σ := + let st := update b r.move r.written c.leftStack c.rightStack + ⟨r.target, st.1, st.2⟩ + +def address (B i x y : ℕ) : ℕ := 1 + x + B * y + B ^ 2 * i + +def capacity (b m n : ℕ) : ℕ := b ^ (m + n) + +end VelocityDetection.Stacks +end + +noncomputable section +namespace VelocityDetection.Expanding +open scoped BigOperators Topology ContDiff +open Set Function Filter + +def lambda (D : ℝ) : ℝ := 4 * D + +def initialRadius (ν K D : ℝ) : ℝ := + 1024 * 3000 * (1 + ν) * lambda D * (K * D + 2) + +def radius (ν K D : ℝ) (n : ℕ) : ℝ := initialRadius ν K D * lambda D ^ n + +end VelocityDetection.Expanding +end + +noncomputable section +namespace VelocityDetection.Observation +open scoped BigOperators Topology ContDiff +open Set Function Filter +open MeasureTheory + +def join (X : Coord 2) (z : ℝ) : Coord 3 := ![X 0, X 1, z] + +def torusEvent (u : VectorField 3) : Prop := + letI := neZeroThree + ∃ t : ℝ, 0 ≤ t ∧ ∃ x : Coord 3, + 1 / ((32 : ℕ) : ℝ) < x 1 ∧ x 1 < 1 / ((8 : ℕ) : ℝ) ∧ (1 / ((2 : ℕ) : ℝ) : ℝ) < u t x 2 + +def upperHalfPlane : Set (Coord 2) := {X | 0 < X 1} + +def planeMass (u : VectorField 3) (t : ℝ) : ℝ := + letI := neZeroThree + ∫ q in upperHalfPlane ×ˢ Ioc (0 : ℝ) 1, + u t (join q.1 q.2) 2 ∂(volume.prod volume) + +def planeEvent (u : VectorField 3) : Prop := + ∃ t : ℝ, 0 ≤ t ∧ (1 / ((2 : ℕ) : ℝ) : ℝ) < planeMass u t + +end VelocityDetection.Observation +end + +noncomputable section +namespace VelocityDetection.SmoothProfiles +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff + +abbrev step := Real.smoothTransition + +end VelocityDetection.SmoothProfiles +end + +noncomputable section +namespace VelocityDetection.TranslationGates +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open SmoothProfiles + +def window (s : ℝ) : ℝ := step (s + 3) * step (3 - s) + +end VelocityDetection.TranslationGates +end + +noncomputable section +namespace VelocityDetection.CenterPaths +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open SmoothProfiles + +def ramp (r : ℝ) : ℝ := step (2 * r - 1 / 2) + +def theta (a T : ℝ) (j : ℕ) (t : ℝ) : ℝ := ramp (3 * (t - a) / T - j) + +def privateRow (S : ℝ) (k : ℕ) : ℝ := -((k : ℝ) + 2) * S + +def center (a T S S' σ : ℝ) (k l : ℕ) (t : ℝ) : Coord 2 := + ![(1 - theta a T 1 t) * S * k + theta a T 1 t * S' * l, + -(1 - theta a T 0 t) * S + + (theta a T 0 t - theta a T 2 t) * privateRow S k + theta a T 2 t * σ * S'] + +end VelocityDetection.CenterPaths +end + +noncomputable section +namespace VelocityDetection.UniformDerivatives +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +variable {I E F G : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup G] [NormedSpace ℝ G] + +def Bounded (f : I → E → F) : Prop := + ∀ n : ℕ, ∃ C : ℝ, 0 ≤ C ∧ ∀ a x, ‖iteratedFDeriv ℝ n (f a) x‖ ≤ C + +end VelocityDetection.UniformDerivatives +end + +noncomputable section +namespace VelocityDetection.Stacks +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +variable {N b : ℕ} (hb : 0 < b) (table : Fin N → Fin b → Option (Rule (Fin N) b)) + +def lookup (c : Configuration (Fin N)) : Option (Rule (Fin N) b) := + table c.state ⟨c.rightStack % b, Nat.mod_lt _ hb⟩ + +end VelocityDetection.Stacks +end + +noncomputable section +namespace VelocityDetection.TailSpace +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +def compatible (n : ℕ) : Submodule ℝ + (C₀(Coord n, ℝ) × Lp ℝ 1 (volume : Measure (Coord n))) where + carrier := {v | (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X)} + zero_mem' := by exact Lp.coeFn_zero .. + add_mem' := by + intro v w hv hw + change (fun X => (v.2 + w.2) X) =ᵐ[volume] (fun X => v.1 X + w.1 X) + change (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X) at hv + change (fun X => w.2 X) =ᵐ[volume] (fun X => w.1 X) at hw + filter_upwards [Lp.coeFn_add v.2 w.2, hv, hw] with X hadd hvx hwx + simpa [hvx, hwx] using hadd + smul_mem' := by + intro c v hv + change (fun X => (c • v.2) X) =ᵐ[volume] (fun X => c * v.1 X) + change (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X) at hv + filter_upwards [Lp.coeFn_smul c v.2, hv] with X hsmul hvx + simpa [hvx] using hsmul + +end VelocityDetection.TailSpace +end + +noncomputable section +namespace VelocityDetection.Cylinder +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +abbrev Space := Coord 2 × ℝ + +abbrev Vect := Fin 3 → ℝ + +def measure : Measure Space := volume.prod (volume.restrict (Ioc (0 : ℝ) 1)) + +def periodic (f : Space → ℝ) : Prop := ∀ X z, f (X, z + 1) = f (X, z) + +def frame (i : Fin 3) : Space := ![(![1, 0], 0), (![0, 1], 0), (0, 1)] i + +def D (i : Fin 3) (f : Space → ℝ) (x : Space) : ℝ := fderiv ℝ f x (frame i) + +structure SliceH2 (v : Space → Vect) : Prop where + smooth : ∀ i, ContDiff ℝ 2 (fun x => v x i) + per : ∀ i, periodic (fun x => v x i) + square_integrable : ∀ i, MemLp (fun x => v x i) 2 measure + derivative_square_integrable : ∀ i k, MemLp (D k (fun x => v x i)) 2 measure + second_square_integrable : ∀ i k l, MemLp (D l (D k (fun x => v x i))) 2 measure + +structure PressureH1 (q : Space → ℝ) : Prop where + smooth : ContDiff ℝ 1 q + per : periodic q + square_integrable : MemLp q 2 measure + derivative_square_integrable : ∀ k, MemLp (D k q) 2 measure + +theorem twoAtLeastTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev LpSpace {α : Type*} [MeasurableSpace α] (E : Type*) [NormedAddCommGroup E] + (p : ENNReal) (μ : Measure α) : Type _ := Lp E p μ + +abbrev L2Space : Type := + letI := twoAtLeastTwo + LpSpace ℝ 2 measure + +def dt (u : ℝ → Space → Vect) (t : ℝ) (x : Space) (i : Fin 3) : ℝ := + derivWithin (fun s => u s x i) (Ici 0) t + +theorem spaceOuterMeasureClass : OuterMeasureClass (Measure Space) Space := + Measure.instOuterMeasureClass + +def continuousL2On (g : ℝ → Space → ℝ) (T : ℝ) : Prop := + letI : IsTopologicalAddGroup ℝ := instIsTopologicalAddGroupReal + letI := spaceOuterMeasureClass + ∃ G : ℝ → L2Space, ContinuousOn G (Icc 0 T) ∧ + ∀ t ∈ Icc 0 T, (fun x => G t x) =ᵐ[measure] g t + +def continuousH2On (u : ℝ → Space → Vect) (T : ℝ) : Prop := + (∀ t ∈ Icc 0 T, SliceH2 (u t)) ∧ + (∀ i, continuousL2On (fun t x => u t x i) T) ∧ + (∀ i k, continuousL2On (fun t => D k (fun x => u t x i)) T) ∧ + (∀ i k l, continuousL2On (fun t => D l (D k (fun x => u t x i))) T) + +def continuousH1On (p : ℝ → Space → ℝ) (T : ℝ) : Prop := + (∀ t ∈ Icc 0 T, PressureH1 (p t)) ∧ continuousL2On p T ∧ + (∀ i, continuousL2On (fun t => D i (p t)) T) + +def C1L2On (u : ℝ → Space → Vect) (T : ℝ) : Prop := + letI : IsTopologicalAddGroup ℝ := instIsTopologicalAddGroupReal + letI := spaceOuterMeasureClass + ∃ U dU : ℝ → Fin 3 → L2Space, + (∀ i, ContinuousOn (fun t => U t i) (Icc 0 T)) ∧ + (∀ i, ContinuousOn (fun t => dU t i) (Icc 0 T)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, (fun x => U t i x) =ᵐ[measure] (fun x => u t x i)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, (fun x => dU t i x) =ᵐ[measure] (fun x => dt u t x i)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, + HasDerivWithinAt (fun s => U s i) (dU t i) (Icc 0 T) t) + +structure ComparisonClass (u : ℝ → Space → Vect) (p : ℝ → Space → ℝ) : Prop where + velocity_H2 : ∀ T > 0, continuousH2On u T + velocity_C1L2 : ∀ T > 0, C1L2On u T + pressure_H1 : ∀ T > 0, continuousH1On p T + time_derivative : ∀ t ≥ 0, ∀ x i, + HasDerivWithinAt (fun s => u s x i) (dt u t x i) (Ici 0) t + velocity_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => u y.1 y.2 i) (Icc 0 T ×ˢ univ) + time_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => dt u y.1 y.2 i) (Icc 0 T ×ˢ univ) + gradient_continuous : ∀ T > 0, ∀ i k, + ContinuousOn (fun y : ℝ × Space => D k (fun x => u y.1 x i) y.2) (Icc 0 T ×ˢ univ) + second_continuous : ∀ T > 0, ∀ i k l, + ContinuousOn (fun y : ℝ × Space => D l (D k (fun x => u y.1 x i)) y.2) (Icc 0 T ×ˢ univ) + pressure_continuous : ∀ T > 0, + ContinuousOn (fun y : ℝ × Space => p y.1 y.2) (Icc 0 T ×ˢ univ) + pressure_gradient_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => D i (p y.1) y.2) (Icc 0 T ×ˢ univ) + bounds : ∀ T > 0, ∃ B : ℝ, 0 ≤ B ∧ + (∀ t ∈ Icc 0 T, ∀ x i, |u t x i| ≤ B) ∧ + (∀ t ∈ Icc 0 T, ∀ x i k, |D k (fun y => u t y i) x| ≤ B) + +def join (x : Space) : Coord 3 := + letI := neZeroTwo + ![x.1 0, x.1 1, x.2] + +end VelocityDetection.Cylinder +end + +noncomputable section +namespace VelocityDetection.TailSpace +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +def evalLinear (X : Coord 2) : compatible 2 →ₗ[ℝ] ℝ where + toFun f := f.val.1 X + map_add' _ _ := rfl + map_smul' _ _ := rfl + +def eval (X : Coord 2) : compatible 2 →L[ℝ] ℝ where + toLinearMap := evalLinear X + cont := AddMonoidHomClass.continuous_of_bound (evalLinear X) 1 (fun f => by + change ‖f.val.1 X‖ ≤ 1 * ‖f.val‖ + rw [one_mul] + exact (BoundedContinuousFunction.norm_coe_le_norm f.val.1.toBCF X).trans (norm_fst_le f.val)) + +end VelocityDetection.TailSpace +end + +noncomputable section +namespace VelocityDetection.History +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks + +structure Configuration (N : ℕ) where + tape : Stacks.Configuration (Fin N) + history : ℕ + deriving DecidableEq + +end VelocityDetection.History +end + +noncomputable section +namespace VelocityDetection.History +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks +variable {N b : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) + +def radix (N b : ℕ) : ℕ := N * b + +def tag (c : Stacks.Configuration (Fin N)) : ℕ := b * c.state.val + c.rightStack % b + +include hb in + +def applyRule (r : Rule (Fin N) b) (c : Configuration N) : Configuration N := + ⟨Stacks.applyRule r c.tape, radix N b * c.history + tag (b := b) c.tape⟩ + +include hb in + +def packedState (c : Configuration N) : ℕ := N * c.history + c.tape.state.val + +def address (B : ℕ) (c : Configuration N) : ℕ := + Stacks.address B (packedState c) c.tape.leftStack c.tape.rightStack + +abbrev Box (N B H : ℕ) := Fin N × Fin B × Fin B × Fin H + +def config {B H : ℕ} (c : Box N B H) : Configuration N := + ⟨⟨c.1, c.2.1, c.2.2.1⟩, c.2.2.2⟩ + +def Active (B H : ℕ) := {c : Box N B H // (Stacks.lookup hb table (config c).tape).isSome} + +def rule {B H : ℕ} (c : Active hb table B H) : Rule (Fin N) b := + (Stacks.lookup hb table (config c.val).tape).get c.property + +def target {B H : ℕ} (c : Active hb table B H) : Configuration N := + applyRule (rule hb table c) (config c.val) + +def sourceAddress {B H : ℕ} (c : Active hb table B H) : ℕ := address B (config c.val) + +def targetAddress {B H : ℕ} (c : Active hb table B H) : ℕ := address (b * B) (target hb table c) + +end VelocityDetection.History +end + +noncomputable section +namespace VelocityDetection.TapeCodes +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def word (w : List (Fin b)) : ℕ := Nat.ofDigits b (w.map Fin.val) + +def half (w : ListBlank (Fin b)) : ℕ := + w.liftOn word (by sorry) + +def tape (q : Fin N) (T : Tape (Fin b)) : Stacks.Configuration (Fin N) := + ⟨q, half T.left, half T.right₀⟩ + +def rule (a : Fin b) (q : Fin N) : TM0.Stmt (Fin b) → Rule (Fin N) b + | .move .left => ⟨q, a, .left⟩ + | .move .right => ⟨q, a, .right⟩ + | .write β => ⟨q, β, .stay⟩ + +def table (M : TM0.Machine (Fin b) (Fin N)) : Fin N → Fin b → Option (Rule (Fin N) b) := + fun q a => (M q a).map (fun p => rule a p.1 p.2) + +end VelocityDetection.TapeCodes +end + +noncomputable section +namespace VelocityDetection.Prelude +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks +variable {N b : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) (q₀ : Fin N) + +def rule (r : Rule (Fin N) b) : Rule (Fin (N + 1)) b := + ⟨r.target.castSucc, r.written, r.move⟩ + +def table' : Fin (N + 1) → Fin b → Option (Rule (Fin (N + 1)) b) := + Fin.lastCases (fun a => some ⟨q₀.castSucc, a, .stay⟩) + (fun q a => (table q a).map rule) + +def initial (x y : ℕ) : Configuration (Fin (N + 1)) := ⟨Fin.last N, x, y⟩ + +end VelocityDetection.Prelude +end + +noncomputable section +namespace VelocityDetection.MachineHistory +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def table (M : TM0.Machine (Fin b) (Fin N)) : + Fin (N + 1) → Fin b → Option (Rule (Fin (N + 1)) b) := + Prelude.table' (TapeCodes.table M) 0 + +def initial (w : List (Fin b)) : Stacks.Configuration (Fin (N + 1)) := + Prelude.initial 0 (TapeCodes.word w) + +end VelocityDetection.MachineHistory +end + +noncomputable section +namespace VelocityDetection.Effective +open Polynomial Set Function Filter +open scoped BigOperators Topology ContDiff + +abbrev Poly := List (ℕ × ℚ) + +noncomputable def poly : Poly → Polynomial ℝ + | [] => 0 + | (k,q)::ps => Polynomial.C (q:ℝ)*Polynomial.X^k + poly ps + +def nextPoly : Poly → Poly + | [] => [] + | (k,q)::ps => (k+2,q)::(k+1,-q*k)::nextPoly ps + +noncomputable def flat (p : Poly) (x : ℝ) : ℝ := + (poly p).eval x⁻¹ * expNegInvGlue x + +def polyBound : Poly → ℚ + | [] => 0 + | (k,q)::ps => |q| *k.factorial + polyBound ps + +inductive Expr (n : ℕ) where + | rat : ℚ → Expr n + | var : Fin n → Expr n + | add : Expr n → Expr n → Expr n + | neg : Expr n → Expr n + | mul : Expr n → Expr n → Expr n + | inv : Expr n → Expr n + | flat : Poly → Expr n → Expr n + deriving Inhabited + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Polynomial Set Function Filter +open scoped BigOperators Topology ContDiff +variable {n : ℕ} + +noncomputable def eval (x : Fin n → ℝ) : Expr n → ℝ + | .rat q => q + | .var i => x i + | .add a b => a.eval x + b.eval x + | .neg a => -a.eval x + | .mul a b => a.eval x * b.eval x + | .inv a => (a.eval x)⁻¹ + | .flat p a => Effective.flat p (a.eval x) + +def diff (i : Fin n) : Expr n → Expr n + | .rat _ => .rat 0 + | .var j => .rat (if i=j then 1 else 0) + | .add a b => .add (a.diff i) (b.diff i) + | .neg a => .neg (a.diff i) + | .mul a b => .add (.mul (a.diff i) b) (.mul a (b.diff i)) + | .inv a => .neg (.mul (a.diff i) (.mul (.inv a) (.inv a))) + | .flat p a => .mul (.flat (nextPoly p) a) (a.diff i) + +def jet : List (Fin n) → Expr n → Expr n + | [], e => e + | i::is, e => jet is (e.diff i) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped BigOperators Topology + +structure Ball where + center : ℚ + radius : ℚ + deriving Inhabited + +def polyEval : Poly → ℚ → ℚ + | [], _ => 0 + | (k,q)::ps, x => q*x^k+polyEval ps x + +def expSum (q : ℚ) (n : ℕ) : ℚ := ∑ k ∈ Finset.range n, q^k / k.factorial + +def expError (q : ℚ) (n : ℕ) : ℚ := |q|^n / n.factorial * 2 + +def flatRound (p : Poly) (q : ℚ) (n : ℕ) : Ball := + if q ≤ 0 then ⟨0,0⟩ else + if |q⁻¹|/(n+1) ≤ (1/2:ℚ) ∧ + |polyEval p q⁻¹| *expError (-q⁻¹) n ≤ polyBound (nextPoly p)*|q| then + ⟨polyEval p q⁻¹*expSum (-q⁻¹) n,|polyEval p q⁻¹| *expError (-q⁻¹) n⟩ + else ⟨0,polyBound (nextPoly p)*|q|⟩ + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.Ball +open Set Filter Function +open scoped Topology + +def atom (q : ℚ) : Ball := ⟨q,0⟩ + +def add (a b : Ball) : Ball := ⟨a.center+b.center,a.radius+b.radius⟩ + +def neg (a : Ball) : Ball := ⟨-a.center,a.radius⟩ + +def mul (a b : Ball) : Ball := + ⟨a.center*b.center,|a.center| *b.radius+|b.center| *a.radius+a.radius*b.radius⟩ + +def inv (a : Ball) : Ball := + ⟨a.center⁻¹,a.radius/(|a.center| *(|a.center|-a.radius))⟩ + +def invSafe (a : Ball) : Bool := decide (a.radius < |a.center|) + +def flat (p : Poly) (a : Ball) (k : ℕ) : Ball := + let b := flatRound p a.center k + ⟨b.center,b.radius+polyBound (nextPoly p)*a.radius⟩ + +end VelocityDetection.Effective.Ball +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Filter Function +open scoped Topology +variable {n : ℕ} + +def round (a : Fin n → Ball) (k : ℕ) : Expr n → Ball := + Expr.rec (motive := fun _ => Ball) + Ball.atom a + (fun _ _ e f => e.add f) + (fun _ e => e.neg) + (fun _ _ e f => e.mul f) + (fun _ e => e.inv) + (fun p _ e => e.flat p k) + +def safe (a : Fin n → Ball) (k : ℕ) : Expr n → Bool := + Expr.rec (motive := fun _ => Bool) + (fun _ => true) (fun _ => true) + (fun _ _ e f => e && f) + (fun _ e => e) + (fun _ _ e f => e && f) + (fun e safe_e => safe_e && (e.round a k).invSafe) + (fun _ _ e => e) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology + +noncomputable def coordinateD {n : ℕ} (i : Fin n) (f : (Fin n → ℝ) → ℝ) (x : Fin n → ℝ) : ℝ := + deriv (fun s => f (update x i s)) (x i) + +noncomputable def mixedD {n : ℕ} : List (Fin n) → ((Fin n → ℝ) → ℝ) → (Fin n → ℝ) → ℝ + | [], f => f + | i::is, f => mixedD is (coordinateD i f) + +def accuracy (k : ℕ) : ℚ := (1/2)^k + +def Names {n : ℕ} (q : Fin n → ℕ → ℚ) (x : Fin n → ℝ) : Prop := + ∀ i k, |x i-(q i k:ℝ)| ≤ (accuracy k:ℝ) + +def inputBall {n : ℕ} (q : Fin n → ℕ → ℚ) (k : ℕ) (i : Fin n) : Ball := + ⟨q i k,accuracy k⟩ + +def trial {n : ℕ} (e : Expr n) (is : List (Fin n)) (q : Fin n → ℕ → ℚ) + (ε : ℚ) (k : ℕ) : Option ℚ := + let d := e.jet is + let a := inputBall q k + if d.safe a k && decide ((d.round a k).radius ≤ ε) then some (d.round a k).center else none + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.PeriodicSpace +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators BoundedContinuousFunction + +abbrev Torus (n : ℕ) := Fin n → AddCircle (1 : ℝ) + +def cover {n : ℕ} (X : Coord n) : Torus n := fun i => (X i : AddCircle (1 : ℝ)) + +end VelocityDetection.PeriodicSpace +end + +noncomputable section +namespace VelocityDetection.SmoothBump +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators +open TranslationGates + +def profile (s : ℝ) : ℝ := window (((3 : ℕ) : ℝ)*s) + +end VelocityDetection.SmoothBump +end + +noncomputable section +namespace VelocityDetection.TorusClass +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators + +abbrev Space := Coord 3 + +def measure : Measure Space := volume.restrict (Icc (0 : Space) 1) + +def periodic (f : Space → ℝ) : Prop := FactorsThrough f PeriodicSpace.cover + +def frame (i : Fin 3) : Space := Pi.single i 1 + +def D (i : Fin 3) (f : Space → ℝ) (x : Space) : ℝ := fderiv ℝ f x (frame i) + +def dt (u : VectorField 3) (t : ℝ) (x : Space) (i : Fin 3) : ℝ := + derivWithin (fun s => u s x i) (Ici 0) t + +structure ComparisonClass (u : VectorField 3) (p : ScalarField 3) : Prop where + velocity_slices : ∀ t ≥ 0, ∀ i, ContDiff ℝ 2 (fun x => u t x i) + pressure_slices : ∀ t ≥ 0, ContDiff ℝ 1 (p t) + velocity_periodic : ∀ t ≥ 0, FactorsThrough (u t) PeriodicSpace.cover + pressure_periodic : ∀ t ≥ 0, periodic (p t) + pressure_mean : ∀ t ≥ 0, (∫ x, p t x ∂measure) = 0 + time_derivative : ∀ t ≥ 0, ∀ x i, + HasDerivWithinAt (fun s => u s x i) (dt u t x i) (Ici 0) t + velocity_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => u y.1 y.2 i) (Icc 0 T ×ˢ univ) + time_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => dt u y.1 y.2 i) (Icc 0 T ×ˢ univ) + gradient_continuous : ∀ T > 0, ∀ i k, + ContinuousOn (fun y : ℝ × Space => D k (fun x => u y.1 x i) y.2) (Icc 0 T ×ˢ univ) + second_continuous : ∀ T > 0, ∀ i k l, + ContinuousOn (fun y : ℝ × Space => D l (D k (fun x => u y.1 x i)) y.2) (Icc 0 T ×ˢ univ) + pressure_continuous : ∀ T > 0, + ContinuousOn (fun y : ℝ × Space => p y.1 y.2) (Icc 0 T ×ˢ univ) + pressure_gradient_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => D i (p y.1) y.2) (Icc 0 T ×ˢ univ) + +end VelocityDetection.TorusClass +end + +noncomputable section +namespace VelocityDetection.MachineTorus +open Set Function MeasureTheory +open scoped Topology ContDiff BigOperators +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def initialAddress (w : List (Fin b)) : ℕ := + History.address (capacity b (w.length+1) 0) ⟨MachineHistory.initial (N := N) w,0⟩ + +end VelocityDetection.MachineTorus +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Function Filter +open scoped Topology BigOperators +variable {n m : ℕ} + +instance : Add (Expr n) := ⟨Expr.add⟩ + +instance : Neg (Expr n) := ⟨Expr.neg⟩ + +instance : Sub (Expr n) := ⟨fun a b => .add a (.neg b)⟩ + +instance : Mul (Expr n) := ⟨Expr.mul⟩ + +instance : Inv (Expr n) := ⟨Expr.inv⟩ + +instance : Div (Expr n) := ⟨fun a b => .mul a (.inv b)⟩ + +instance (k : ℕ) : OfNat (Expr n) k := ⟨.rat k⟩ + +def subst (v : Fin m → Expr n) : Expr m → Expr n := + Expr.rec (motive := fun _ => Expr n) + Expr.rat v + (fun _ _ a b => .add a b) + (fun _ a => .neg a) + (fun _ _ a b => .mul a b) + (fun _ a => .inv a) + (fun p _ a => .flat p a) + +def sumList : List (Expr n) → Expr n + | [] => 0 + | e::es => e + sumList es + +def sumFin (k : ℕ) (f : Fin k → Expr n) : Expr n := sumList (List.ofFn f) + +def unaryD (e : Expr 1) (a : Expr n) : Expr n := (e.diff 0).subst (fun _ => a) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective.Recipe +open Set Function Filter +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr +variable {n : ℕ} + +def glue (a : Expr n) : Expr n := .flat [(0,1)] a + +def step (a : Expr n) : Expr n := glue a/(glue a+glue (1-a)) + +def pulse (a : Expr n) : Expr n := (step (.var 0 : Expr 1)).unaryD a + +def window (a : Expr n) : Expr n := step (a+3)*step (3-a) + +def windowD (a : Expr n) : Expr n := pulse (a+3)*step (3-a)-step (a+3)*pulse (3-a) + +def theta (a T : Expr n) (j : ℕ) (t : Expr n) : Expr n := + step (2*(3*(t-a)/T-.rat j)-.rat (1/2)) + +def center (a T S S' σ : Expr n) (k l : ℕ) (t : Expr n) : Fin 2 → Expr n := + ![(1-theta a T 1 t)*S*.rat k+theta a T 1 t*S'*.rat l, + -(1-theta a T 0 t)*S+(theta a T 0 t-theta a T 2 t)*(-(.rat k+2)*S)+ + theta a T 2 t*σ*S'] + +def gate (R : Expr n) (c G X : Fin 2 → Expr n) : Fin 2 → Expr n := + letI := neZeroTwo + ![window ((X 0-c 0)/R)*(windowD ((X 1-c 1)/R)/R)* + (G 0*(X 1-c 1)-G 1*(X 0-c 0))+ + window ((X 0-c 0)/R)*window ((X 1-c 1)/R)*G 0, + window ((X 0-c 0)/R)*window ((X 1-c 1)/R)*G 1- + (windowD ((X 0-c 0)/R)/R*window ((X 1-c 1)/R))* + (G 0*(X 1-c 1)-G 1*(X 0-c 0))] + +def impulse (t : Expr n) (p X : Fin 2 → Expr n) : Expr n := + letI := neZeroTwo + pulse t*pulse (X 0-p 0+.rat (1/2))*pulse (X 1-p 1+.rat (1/2)) + +def packet (R : Expr n) (X : Fin 2 → Expr n) : Expr n := + letI := neZeroTwo + window (3*(X 0/R))*window (3*(X 1/R)) + +end VelocityDetection.Effective.Recipe +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Function +open scoped BigOperators Topology +variable {n : ℕ} + +def activeSum {N b B H : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) + (f : History.Active hb table B H → Expr n) : Expr n := + sumFin N (fun s => sumFin B (fun l => sumFin B (fun r => sumFin H (fun h => + if hp : (Stacks.lookup hb table (History.config (s,l,r,h)).tape).isSome then + f ⟨(s,l,r,h),hp⟩ else 0)))) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective.ArrayRecipe +open Set Function +open scoped BigOperators Topology +open _root_.OAI.VelocityDetection.Effective.Expr Stacks +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) (m : ℕ) + +abbrev Code := Expr 5 + +def K (N b m : ℕ) : ℕ := N * capacity b (m+1) 0 ^ 2 + +def D (N b : ℕ) : ℕ := b^2 * History.radix N b + +def radius (N b m n : ℕ) : Code := + .rat (1024*3000*(4*(D N b))*(K N b m*D N b+2)*(4*D N b)^n) * (1+.var 0) + +def spacing (N b m n : ℕ) : Code := 16*radius N b m n + +def duration (N b m n : ℕ) : Code := + spacing N b m (n+1) * .rat (K N b m*D N b^(n+1)+2) + +def start (N b m : ℕ) : ℕ → Code + | 0 => 1 + | n+1 => start N b m n+duration N b m n + +def sign (c : History.Configuration N) : ℚ := + if (lookup hb table c.tape).isNone then 1 else -1 + +abbrev Instruction (n : ℕ) := History.Active hb table (capacity b (m+1) n) (History.radix N b^n) + +def path (n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + Recipe.center (start N b m n) (duration N b m n) (spacing N b m n) + (spacing N b m (n+1)) (.rat (sign hb table (History.target hb table c))) + (History.sourceAddress hb table c) (History.targetAddress hb table c) (.var 1) + +def gate (n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + Recipe.gate (radius N b m n) (path hb table m n c) + (fun i => (path hb table m n c i).diff 1) ![.var 2,.var 3] + +def stage (n : ℕ) (i : Fin 2) : Code := + activeSum hb table (fun c : Instruction hb table m n => gate hb table m n c i) + +def field (L : ℕ) (i : Fin 2) : Code := sumFin L (fun n => stage hb table m n i) + +end VelocityDetection.Effective.ArrayRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.ChartRecipe +open Set Function ArrayRecipe +open scoped BigOperators Topology +open VelocityDetection.Effective.Expr +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) (m : ℕ) + +def scale (N b m P : ℕ) : ℚ := (1024*((K N b m:ℚ)*(D N b:ℚ)^(P+1)+4))⁻¹ + +def radius (N b m P : ℕ) : ℚ := scale N b m P/16 + +def targetHeight (P n : ℕ) (c : Instruction hb table m n) : ℚ := + if ArrayRecipe.sign hb table (History.target hb table c) = 1 then -(7/16) else -scale N b m P + +def path (P n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + letI := neZeroFive + fun i => + .rat (![1/4,1/2] i) + Recipe.center (.rat n) 1 (.rat (scale N b m P)) (.rat (scale N b m P)) + (.rat (targetHeight hb table m P n c/scale N b m P)) + (History.sourceAddress hb table c) (History.targetAddress hb table c) (.var 1) i + +def gate (P n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + letI := neZeroFive + Recipe.gate (.rat (radius N b m P)) (path hb table m P n c) + (fun i => (path hb table m P n c i).diff 1) ![.var 2,.var 3] + +def stage (P n : ℕ) (i : Fin 2) : Code := + activeSum hb table (fun c : Instruction hb table m n => gate hb table m P n c i) + +def prefixCode (P : ℕ) (i : Fin 2) : Code := sumFin P (fun n => stage hb table m P n i) + +def duration (N b m B k : ℕ) : Code := + letI := neZeroFive + .rat ((1/16)*(1/2:ℚ)^k) / + (3*(1+.var 0*.rat (2*(B:ℚ)/(radius N b m (k+1))^2))) + +def localTime (N b m B k : ℕ) : Code := + letI := neZeroFive + (.var 1-.rat (k+1))/duration N b m B k + +def weight (N b m B k : ℕ) : Code := + Recipe.step (8*localTime N b m B k)-Recipe.step (8*localTime N b m B k-.rat 7) + +def clock (N b m B k : ℕ) : Code := .rat (k+1)* + (Recipe.step (8*localTime N b m B k-1)-Recipe.step (8*localTime N b m B k-.rat 5)) + +def rawField (B k : ℕ) (i : Fin 2) : Code := + letI := neZeroFive + (clock N b m B k).diff 1 * (prefixCode hb table m (k+1) i).subst + ![.var 0,clock N b m B k,.var 2,.var 3,.var 4] + +def initial (N b m P q : ℕ) : Fin 2 → Code := + ![.rat (1/4+scale N b m P*q),.rat (1/2-scale N b m P)] + +def rawSource (B q k : ℕ) : Code := + letI := neZeroFive + (weight N b m B k).diff 1 * + Recipe.packet (.rat (radius N b m (k+1))) + (fun i => (![.var 2,.var 3] i)-initial N b m (k+1) q i) + +end VelocityDetection.Effective.ChartRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Function +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr ArrayRecipe + +def periodize (R : ℕ) (e : Code) : Code := + letI := neZeroFive + sumFin (2*R+1) (fun i => sumFin (2*R+1) (fun j => + e.subst ![.var 0,.var 1,.var 2-.rat ((i:ℚ)-R),.var 3-.rat ((j:ℚ)-R),.var 4])) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.ChartRecipe +open Set Function +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr ArrayRecipe +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) (m : ℕ) + +def fieldBlock (B R k : ℕ) (i : Fin 2) : Code := periodize R (rawField hb table m B k i) + +def sourceBlock (N b m B q R k : ℕ) : Code := periodize R (rawSource (N:=N) (b:=b) m B q k) + +def field (B R L : ℕ) (i : Fin 2) : Code := sumFin L (fun k => fieldBlock hb table m B R k i) + +def source (N b m B q R L : ℕ) : Code := sumFin L (fun k => sourceBlock N b m B q R k) + +end VelocityDetection.Effective.ChartRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +def residualCode (a : Fin 2 → Code) (i : Fin 2) : Code := + letI := neZeroTwo + letI := neZeroFive + (a i).diff 1 + a 0*(a i).diff 2 + a 1*(a i).diff 3 - + .var 0*((((a i).diff 2).diff 2)+(((a i).diff 3).diff 3)) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.ArrayRecipe +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +def initialCode (N b m q : ℕ) : Fin 2 → Code := + ![spacing N b m 0 * .rat q,-spacing N b m 0] + +def source (N b m q : ℕ) : Code := + letI := neZeroFive + Recipe.impulse (.var 1) (initialCode N b m q) ![.var 2,.var 3] + +end VelocityDetection.Effective.ArrayRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +noncomputable def forceFunction (f : ℝ → VectorField 3) (i : Fin 3) (x : Fin 5 → ℝ) : ℝ := + letI := neZeroFive + f (x 0) (x 1) ![x 2,x 3,x 4] i + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe +variable {b N : ℕ} [NeZero b] [NeZero N] + +inductive Domain where | torus | cylinder + deriving DecidableEq, Repr + +def field (d : Domain) (B R L : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 2) : Code := match d with + | .torus => ChartRecipe.field (NeZero.pos b) (MachineHistory.table M) w.length B R L i + | .cylinder => ArrayRecipe.field (NeZero.pos b) (MachineHistory.table M) w.length L i + +def source (d : Domain) (B R L : ℕ) (w : List (Fin b)) : Code := match d with + | .torus => ChartRecipe.source (N+1) b w.length B (MachineTorus.initialAddress (N:=N) w) R L + | .cylinder => ArrayRecipe.source (N+1) b w.length (MachineTorus.initialAddress (N:=N) w) + +def force (d : Domain) (B R L : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) : Code := + letI := neZeroTwo + ![residualCode (field d B R L M w) 0,residualCode (field d B R L M w) 1, + source (N:=N) d B R L w] i + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Filter Function Turing +open scoped Topology ContDiff BigOperators +variable {b N : ℕ} [NeZero b] [NeZero N] + +def timeCutoff (q : Fin 5 → ℕ → ℚ) : ℕ := + letI := neZeroFive + ⌈q 1 0+2⌉₊ + +def spaceCutoff (q : Fin 5 → ℕ → ℚ) : ℕ := + letI := neZeroFive + ⌈|q 2 0|+|q 3 0|+3⌉₊ + +def runTrial (d : Domain) (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) (is : List (Fin 5)) (q : Fin 5 → ℕ → ℚ) + (ε : ℚ) (k : ℕ) : Option ℚ := + trial (force d B (spaceCutoff q) (timeCutoff q) M w i) is q ε k + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology BigOperators + +structure RationalBox (n : ℕ) where + lower : Fin n → ℚ + upper : Fin n → ℚ + ordered : ∀ i, lower i ≤ upper i + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.RationalBox +open Set Filter Function +open scoped Topology BigOperators +variable {n : ℕ} (Q : RationalBox n) + +def carrier : Set (Fin n → ℝ) := Icc (fun i => (Q.lower i:ℝ)) (fun i => (Q.upper i:ℝ)) + +def cell (k : ℕ) (j : Fin n → Fin (k+2)) (i : Fin n) : Ball := + ⟨Q.lower i+(Q.upper i-Q.lower i)*((j i:ℕ):ℚ)/(k+1), + (Q.upper i-Q.lower i)/(k+1)⟩ + +def boundTrial (e : Expr n) (is : List (Fin n)) (k : ℕ) : Option ℚ := + if ∀ j : Fin n → Fin (k+2), (e.jet is).safe (Q.cell k j) k = true then + some (∑ j : Fin n → Fin (k+2), + (|((e.jet is).round (Q.cell k j) k).center| + |((e.jet is).round (Q.cell k j) k).radius|)) + else none + +end VelocityDetection.Effective.RationalBox +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Function Turing +variable {b N : ℕ} [NeZero b] [NeZero N] + +def boxTimeCutoff (Q : RationalBox 5) : ℕ := + letI := neZeroFive + ⌈Q.upper 1+1⌉₊ + +def boxSpaceCutoff (Q : RationalBox 5) : ℕ := + letI := neZeroFive + ⌈|Q.lower 2|+|Q.upper 2|+|Q.lower 3|+|Q.upper 3|+2⌉₊ + +def runBoundTrial (d : Domain) (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) (is : List (Fin 5)) (Q : RationalBox 5) (k : ℕ) : Option ℚ := + Q.boundTrial (force d B (boxSpaceCutoff Q) (boxTimeCutoff Q) M w i) is k + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Turing + +structure Program (b N : ℕ) [NeZero b] [NeZero N] where + derivativeBound : ℕ + table : TM0.Machine (Fin b) (Fin N) + input : List (Fin b) + +def compile {b N : ℕ} [NeZero b] [NeZero N] (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) (w : List (Fin b)) : + Program b N := ⟨B,M,w⟩ + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe.Program +open Turing +variable {b N : ℕ} [NeZero b] [NeZero N] + +def valueTrial (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (q : Fin 5 → ℕ → ℚ) (ε : ℚ) (k : ℕ) : Option ℚ := + runTrial d P.derivativeBound P.table P.input i is q ε k + +def boundTrial (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (Q : RationalBox 5) (k : ℕ) : Option ℚ := + runBoundTrial d P.derivativeBound P.table P.input i is Q k + +noncomputable def evaluate (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (q : Fin 5 → ℕ → ℚ) (ε : ℚ) : Part ℚ := Nat.rfindOpt (P.valueTrial d i is q ε) + +noncomputable def derivativeBounds (P : Program b N) (d : Domain) (i : Fin 3) + (is : List (Fin 5)) (Q : RationalBox 5) : Part ℚ := Nat.rfindOpt (P.boundTrial d i is Q) + +def Represents (P : Program b N) (d : Domain) (F : ℝ → VectorField 3) : Prop := + letI := neZeroFive + (∀ (i : Fin 3) (is : List (Fin 5)) (q : Fin 5 → ℕ → ℚ) (x : Fin 5 → ℝ), + Names q x → 0 < x 0 → ∀ ε : ℚ, 0 < ε → + (P.evaluate d i is q ε).Dom ∧ + ∀ r ∈ P.evaluate d i is q ε, + |mixedD is (forceFunction F i) x-(r:ℝ)| ≤ (ε:ℝ)) ∧ + (∀ (i : Fin 3) (is : List (Fin 5)) (Q : RationalBox 5), 0 < Q.lower 0 → + (P.derivativeBounds d i is Q).Dom ∧ + ∀ C ∈ P.derivativeBounds d i is Q, 0 ≤ C ∧ + ∀ x ∈ Q.carrier, |mixedD is (forceFunction F i) x| ≤ (C:ℝ)) + +end VelocityDetection.Effective.MachineRecipe.Program +end + +noncomputable section +namespace VelocityDetection.Effective +open Turing + +def ComputableReal (x : ℝ) : Prop := + ∃ q : ℕ → ℚ, Computable q ∧ ∀ k, |x-(q k:ℝ)| ≤ (accuracy k:ℝ) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection +open Set Function MeasureTheory Turing +open scoped ContDiff +open Effective Effective.MachineRecipe + +theorem main_result : + ∃ B : ℕ, 0 < B ∧ + (∀ s : ℝ, |deriv (deriv SmoothBump.profile) s| ≤ (B:ℝ)) ∧ + ∀ (ν : ℝ), 0 < ν → ComputableReal ν → + ∀ (b N : ℕ) [NeZero b] [NeZero N] + (M : TM0.Machine (Fin b) (Fin N)) (w : List (Fin b)), + ∃ (Ftor Fcyl : ℝ → VectorField 3), + (compile B M w).Represents .torus Ftor ∧ + (compile B M w).Represents .cylinder Fcyl ∧ + (ContDiff ℝ ∞ (uncurry (Ftor ν)) ∧ + (∀ t, FactorsThrough (Ftor ν t) PeriodicSpace.cover) ∧ + (∃ K : Set (Coord 2), IsCompact K ∧ (∀ X ∈ K, ∀ i, X i ∈ Ioo (0:ℝ) 1) ∧ + ∀ t X, PeriodicSpace.cover (horizontal X) ∉ PeriodicSpace.cover '' K → Ftor ν t X = 0) ∧ + (∀ T d, ∃ C : ℝ, 0 ≤ C ∧ ∀ t ∈ Icc (0:ℝ) T, ∀ X, + ‖iteratedFDeriv ℝ d (uncurry (Ftor ν)) (t,X)‖ ≤ C) ∧ + ∃ u : VectorField 3, + ContDiff ℝ ∞ (uncurry u) ∧ TorusClass.ComparisonClass u (fun _ _ => 0) ∧ + NavierStokes ν u (fun _ _ => 0) (Ftor ν) ∧ + (Observation.torusEvent u ↔ (TM0.eval M w).Dom) ∧ + ∀ (v : VectorField 3) (p : ScalarField 3), TorusClass.ComparisonClass v p → + NavierStokes ν v p (Ftor ν) → + ∀ t ≥ 0, (∀ X, v t X = u t X) ∧ (∀ X, p t X = 0)) ∧ + (ContDiff ℝ ∞ (uncurry (Fcyl ν)) ∧ + UniformDerivatives.Bounded (fun _ : Unit => uncurry (Fcyl ν)) ∧ + (∀ t X z, Fcyl ν t (update X 2 z) = Fcyl ν t X) ∧ + (∀ T : ℝ, ∃ K : Set (Coord 2), IsCompact K ∧ ∀ t ∈ Icc (0:ℝ) T, + ∀ X : Coord 3, horizontal X ∉ K → Fcyl ν t X = 0) ∧ + ∃ u : VectorField 3, + ContDiff ℝ ∞ (uncurry u) ∧ + Cylinder.ComparisonClass (fun t x => u t (Cylinder.join x)) (fun _ _ => 0) ∧ + NavierStokes ν u (fun _ _ => 0) (Fcyl ν) ∧ + (∀ t ≥ 0, (∀ x, 0 ≤ u t (Cylinder.join x) 2) ∧ + Integrable (fun x => u t (Cylinder.join x) 2) Cylinder.measure) ∧ + (Observation.planeEvent u ↔ (TM0.eval M w).Dom) ∧ + ∀ (v : VectorField 3) (p : ScalarField 3), + Cylinder.ComparisonClass (fun t x => v t (Cylinder.join x)) + (fun t x => p t (Cylinder.join x)) → + NavierStokes ν v p (Fcyl ν) → + ∀ t ≥ 0, (∀ X, v t X = u t X) ∧ (∀ X, p t X = 0)) := by sorry + +end VelocityDetection +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/NavierStokesVelocity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.VelocityDetection.main_result` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/navier-stokes-velocity/solution/closure.txt b/tasks/navier-stokes-velocity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c3b0fc380b259d236fc1bfdebd9c0c7a5222378 --- /dev/null +++ b/tasks/navier-stokes-velocity/solution/closure.txt @@ -0,0 +1,152 @@ +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ArrayBounds +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ArrayMass +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ArrayScalars +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ArrayTrajectories +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstBlock +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstBlockRawReferenceLaplacian +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstCalculus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstSchedule +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstTotal +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstTotalComparisonClass +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstTotalForce +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.BurstTotalReferenceSum +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CenterPaths +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CenterPathsSignedCenter +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ChartExpressions +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ChartRouting +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ChartRoutingPeriodicPrefixDivergence +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ChartTrace +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ChartTraceRouteIsInstalled +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ClmDerivWithin +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CompactIntegral +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CompactTails +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Cutoff +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CutoffCutoffZeroOnUpper +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CutoffDecay +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CutoffObservation +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CutoffRetention +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Cylinder +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CylinderDLift +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CylinderEnergy +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CylinderMeasure +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.CylinderUniqueness +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.EffectivePrescriptions +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Expanding +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArray +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArrayDriftData +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArrayForce +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArrayGate +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArrayLocalSupportField +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpandingArrayLoss +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ExpressionAlgebra +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.FiniteAddresses +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ForceExpressions +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.GateBounds +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HeatKernels +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HeatKernelsContDiffKernel +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HeatKernelsIntegrableOnInvSqrt +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HeatKernelsNormalEqKernel +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HeatKernelsNormalTwoNeg +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.History +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HistoryRouting +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HistoryRoutingTrace +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.HistoryToBox +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.IntegrableSumNormed +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.JointCalculus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.JointCalculusHorizontalLinear +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.JointCalculusTimeDEqDeriv +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MachineCylinder +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MachineHistory +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MachineTorus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Main +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MainResult +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalar +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalarContDiffScalar +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalarGlobalJetsClamp +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalarMild +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalarSupportedData +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MildScalarTimeDerivative +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Model +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.MovingCutoff +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Observation +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ObservationMeasurableUpperHalfPlane +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ParabolicComparison +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ParabolicTails +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PathBounds +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicCalculus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicComparison +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicEvaluation +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicHeat +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicIntegrableSumNormed +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicJets +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicJetsCalculus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicLifts +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMild +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMildContDiffScalar +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMildGlobalJetsClamp +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMildMild +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMildPeriodicData +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicMildTimeDerivative +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicSpace +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicSpaceContinuousProduct +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicSpaceOfPeriodicCurve +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicSpaceRestrictLApply +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicSpaceRestrictRestrict +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodicTime +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Periodization +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodizationExtendAdd +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodizationExtendEventuallyEqFinite +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodizationSupportDAlong +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PeriodizationSupportSpatialD +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Prelude +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.PulseBounds +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.RationalEvaluation +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.RoutingArray +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.RoutingArrayTrace +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.RoutingData +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.RoutingSupport +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.ScalarMass +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SmoothBump +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SmoothExpressions +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SmoothProfiles +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SmoothProfilesIntegrableImpulse +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SmoothProfilesLocalSupportImpulse +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialCalculus +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialCalculusPartialDComm +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialCalculusPartialDSub +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialDTranslate +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialIntegration +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.SpatialSlices +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Stacks +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.StacksLookup +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.StacksOptionStep +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.StageCounts +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailCompleteness +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailConvolution +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailDifferentiability +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailEvaluation +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailJets +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpace +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceContDiffPartialDInfty +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceContinuousAverageJoint +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceContinuousProduct +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceConvolveRescale +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceHeatDerivative +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceHeatExtension +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceIntegrableCompatible +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceIntegrableKernelValue +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceNormValueLe +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceRestrictRestrict +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TailSpaceToC0 +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TapeCodes +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TimeBlocks +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TimeIntegral +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TorusClass +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TorusClassContinuousOnEnergy +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TorusClassSmoothSlice +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.TranslationGates +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.UniformDerivatives +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.UniformDerivativesFderiv +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.UniformDerivativesNormSumLeSparse +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.WeakVolterra +OAI.MathematicalPhysics.NavierStokes.VelocityDetection.WeakVolterraIntegrableCausal diff --git a/tasks/navier-stokes-velocity/solution/reference.py b/tasks/navier-stokes-velocity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/navier-stokes-velocity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/navier-stokes-velocity/solution/solve.sh b/tasks/navier-stokes-velocity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0a8705867ab1d31d407860219d8ae6299e7f867a --- /dev/null +++ b/tasks/navier-stokes-velocity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of NavierStokesVelocity, i.e. module OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Main and the +# 152 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of NavierStokesVelocity" diff --git a/tasks/navier-stokes-velocity/task.toml b/tasks/navier-stokes-velocity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba6710eb2f3f33801306a0058433372702095b66 --- /dev/null +++ b/tasks/navier-stokes-velocity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/navier-stokes-velocity" +version = "1.0.0" +description = "Prove NavierStokesVelocity (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/NavierStokesVelocity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "NavierStokesVelocity" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.VelocityDetection.main_result"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.NavierStokes.VelocityDetection.Main" +reference_modules = 152 +reference_lean_bytes = 1031916 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1274 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12628 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/navier-stokes-velocity/tests/Challenge.lean b/tasks/navier-stokes-velocity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..72e7fd1e6d366ce7c4bc36014127cafc184c3a9b --- /dev/null +++ b/tasks/navier-stokes-velocity/tests/Challenge.lean @@ -0,0 +1,1275 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace VelocityDetection +open scoped BigOperators Topology ContDiff +open Set Function Filter + +abbrev Coord (n : ℕ) := Fin n → ℝ + +abbrev ScalarField (n : ℕ) := ℝ → Coord n → ℝ + +abbrev VectorField (n : ℕ) := ℝ → Coord n → Coord n + +theorem neZeroTwo : NeZero 2 := ⟨Nat.succ_ne_zero 1⟩ + +theorem neZeroThree : NeZero 3 := ⟨Nat.succ_ne_zero 2⟩ + +theorem neZeroFive : NeZero 5 := ⟨Nat.succ_ne_zero 4⟩ + +def spatialD {n : ℕ} (i : Fin n) (q : ScalarField n) : ScalarField n := + fun t x => deriv (fun s => q t (Function.update x i s)) (x i) + +def timeD {n : ℕ} (q : ScalarField n) : ScalarField n := + fun t x => derivWithin (fun s => q s x) (Ici 0) t + +def laplacian {n : ℕ} (q : ScalarField n) : ScalarField n := + fun t x => ∑ i : Fin n, spatialD i (spatialD i q) t x + +def advection {n : ℕ} (a : VectorField n) (q : ScalarField n) : ScalarField n := + fun t x => ∑ i : Fin n, a t x i * spatialD i q t x + +def divergence {n : ℕ} (a : VectorField n) : ScalarField n := + fun t x => ∑ i : Fin n, spatialD i (fun s y => a s y i) t x + +def NavierStokes (ν : ℝ) (u : VectorField 3) (p : ScalarField 3) + (f : VectorField 3) : Prop := + (∀ (t : ℝ), 0 ≤ t → ∀ x : Coord 3, ∀ i : Fin 3, + timeD (fun s y => u s y i) t x + advection u (fun s y => u s y i) t x = + -spatialD i p t x + ν * laplacian (fun s y => u s y i) t x + f t x i) ∧ + (∀ (t : ℝ), 0 ≤ t → ∀ x, divergence u t x = 0) ∧ + (∀ x, u 0 x = 0) + +def horizontal (x : Coord 3) : Coord 2 := ![x 0, x 1] + +end VelocityDetection +end + +noncomputable section +namespace VelocityDetection.Stacks +open scoped BigOperators Topology ContDiff +open Set Function Filter + +inductive Move + | right + | stay + | left + deriving DecidableEq, Repr + +def update (b : ℕ) (m : Move) (β x y : ℕ) : ℕ × ℕ := + match m with + | .right => (b * x + β, y / b) + | .stay => (x, y - y % b + β) + | .left => (x / b, x % b + b * β + b ^ 2 * (y / b)) + +structure Rule (σ : Type*) (b : ℕ) where + target : σ + written : Fin b + move : Move + +structure Configuration (σ : Type*) where + state : σ + leftStack : ℕ + rightStack : ℕ + deriving DecidableEq + +def applyRule {σ : Type*} {b : ℕ} (r : Rule σ b) (c : Configuration σ) : Configuration σ := + let st := update b r.move r.written c.leftStack c.rightStack + ⟨r.target, st.1, st.2⟩ + +def address (B i x y : ℕ) : ℕ := 1 + x + B * y + B ^ 2 * i + +def capacity (b m n : ℕ) : ℕ := b ^ (m + n) + +end VelocityDetection.Stacks +end + +noncomputable section +namespace VelocityDetection.Expanding +open scoped BigOperators Topology ContDiff +open Set Function Filter + +def lambda (D : ℝ) : ℝ := 4 * D + +def initialRadius (ν K D : ℝ) : ℝ := + 1024 * 3000 * (1 + ν) * lambda D * (K * D + 2) + +def radius (ν K D : ℝ) (n : ℕ) : ℝ := initialRadius ν K D * lambda D ^ n + +end VelocityDetection.Expanding +end + +noncomputable section +namespace VelocityDetection.Observation +open scoped BigOperators Topology ContDiff +open Set Function Filter +open MeasureTheory + +def join (X : Coord 2) (z : ℝ) : Coord 3 := ![X 0, X 1, z] + +def torusEvent (u : VectorField 3) : Prop := + letI := neZeroThree + ∃ t : ℝ, 0 ≤ t ∧ ∃ x : Coord 3, + 1 / ((32 : ℕ) : ℝ) < x 1 ∧ x 1 < 1 / ((8 : ℕ) : ℝ) ∧ (1 / ((2 : ℕ) : ℝ) : ℝ) < u t x 2 + +def upperHalfPlane : Set (Coord 2) := {X | 0 < X 1} + +def planeMass (u : VectorField 3) (t : ℝ) : ℝ := + letI := neZeroThree + ∫ q in upperHalfPlane ×ˢ Ioc (0 : ℝ) 1, + u t (join q.1 q.2) 2 ∂(volume.prod volume) + +def planeEvent (u : VectorField 3) : Prop := + ∃ t : ℝ, 0 ≤ t ∧ (1 / ((2 : ℕ) : ℝ) : ℝ) < planeMass u t + +end VelocityDetection.Observation +end + +noncomputable section +namespace VelocityDetection.SmoothProfiles +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff + +abbrev step := Real.smoothTransition + +end VelocityDetection.SmoothProfiles +end + +noncomputable section +namespace VelocityDetection.TranslationGates +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open SmoothProfiles + +def window (s : ℝ) : ℝ := step (s + 3) * step (3 - s) + +end VelocityDetection.TranslationGates +end + +noncomputable section +namespace VelocityDetection.CenterPaths +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open SmoothProfiles + +def ramp (r : ℝ) : ℝ := step (2 * r - 1 / 2) + +def theta (a T : ℝ) (j : ℕ) (t : ℝ) : ℝ := ramp (3 * (t - a) / T - j) + +def privateRow (S : ℝ) (k : ℕ) : ℝ := -((k : ℝ) + 2) * S + +def center (a T S S' σ : ℝ) (k l : ℕ) (t : ℝ) : Coord 2 := + ![(1 - theta a T 1 t) * S * k + theta a T 1 t * S' * l, + -(1 - theta a T 0 t) * S + + (theta a T 0 t - theta a T 2 t) * privateRow S k + theta a T 2 t * σ * S'] + +end VelocityDetection.CenterPaths +end + +noncomputable section +namespace VelocityDetection.UniformDerivatives +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +variable {I E F G : Type*} [NormedAddCommGroup E] [NormedSpace ℝ E] + [NormedAddCommGroup F] [NormedSpace ℝ F] [NormedAddCommGroup G] [NormedSpace ℝ G] + +def Bounded (f : I → E → F) : Prop := + ∀ n : ℕ, ∃ C : ℝ, 0 ≤ C ∧ ∀ a x, ‖iteratedFDeriv ℝ n (f a) x‖ ≤ C + +end VelocityDetection.UniformDerivatives +end + +noncomputable section +namespace VelocityDetection.Stacks +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +variable {N b : ℕ} (hb : 0 < b) (table : Fin N → Fin b → Option (Rule (Fin N) b)) + +def lookup (c : Configuration (Fin N)) : Option (Rule (Fin N) b) := + table c.state ⟨c.rightStack % b, Nat.mod_lt _ hb⟩ + +end VelocityDetection.Stacks +end + +noncomputable section +namespace VelocityDetection.TailSpace +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +def compatible (n : ℕ) : Submodule ℝ + (C₀(Coord n, ℝ) × Lp ℝ 1 (volume : Measure (Coord n))) where + carrier := {v | (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X)} + zero_mem' := by exact Lp.coeFn_zero .. + add_mem' := by + intro v w hv hw + change (fun X => (v.2 + w.2) X) =ᵐ[volume] (fun X => v.1 X + w.1 X) + change (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X) at hv + change (fun X => w.2 X) =ᵐ[volume] (fun X => w.1 X) at hw + filter_upwards [Lp.coeFn_add v.2 w.2, hv, hw] with X hadd hvx hwx + simpa [hvx, hwx] using hadd + smul_mem' := by + intro c v hv + change (fun X => (c • v.2) X) =ᵐ[volume] (fun X => c * v.1 X) + change (fun X => v.2 X) =ᵐ[volume] (fun X => v.1 X) at hv + filter_upwards [Lp.coeFn_smul c v.2, hv] with X hsmul hvx + simpa [hvx] using hsmul + +end VelocityDetection.TailSpace +end + +noncomputable section +namespace VelocityDetection.Cylinder +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +abbrev Space := Coord 2 × ℝ + +abbrev Vect := Fin 3 → ℝ + +def measure : Measure Space := volume.prod (volume.restrict (Ioc (0 : ℝ) 1)) + +def periodic (f : Space → ℝ) : Prop := ∀ X z, f (X, z + 1) = f (X, z) + +def frame (i : Fin 3) : Space := ![(![1, 0], 0), (![0, 1], 0), (0, 1)] i + +def D (i : Fin 3) (f : Space → ℝ) (x : Space) : ℝ := fderiv ℝ f x (frame i) + +structure SliceH2 (v : Space → Vect) : Prop where + smooth : ∀ i, ContDiff ℝ 2 (fun x => v x i) + per : ∀ i, periodic (fun x => v x i) + square_integrable : ∀ i, MemLp (fun x => v x i) 2 measure + derivative_square_integrable : ∀ i k, MemLp (D k (fun x => v x i)) 2 measure + second_square_integrable : ∀ i k l, MemLp (D l (D k (fun x => v x i))) 2 measure + +structure PressureH1 (q : Space → ℝ) : Prop where + smooth : ContDiff ℝ 1 q + per : periodic q + square_integrable : MemLp q 2 measure + derivative_square_integrable : ∀ k, MemLp (D k q) 2 measure + +theorem twoAtLeastTwo : Nat.AtLeastTwo 2 := ⟨Nat.le_refl 2⟩ + +abbrev LpSpace {α : Type*} [MeasurableSpace α] (E : Type*) [NormedAddCommGroup E] + (p : ENNReal) (μ : Measure α) : Type _ := Lp E p μ + +abbrev L2Space : Type := + letI := twoAtLeastTwo + LpSpace ℝ 2 measure + +def dt (u : ℝ → Space → Vect) (t : ℝ) (x : Space) (i : Fin 3) : ℝ := + derivWithin (fun s => u s x i) (Ici 0) t + +theorem spaceOuterMeasureClass : OuterMeasureClass (Measure Space) Space := + Measure.instOuterMeasureClass + +def continuousL2On (g : ℝ → Space → ℝ) (T : ℝ) : Prop := + letI : IsTopologicalAddGroup ℝ := instIsTopologicalAddGroupReal + letI := spaceOuterMeasureClass + ∃ G : ℝ → L2Space, ContinuousOn G (Icc 0 T) ∧ + ∀ t ∈ Icc 0 T, (fun x => G t x) =ᵐ[measure] g t + +def continuousH2On (u : ℝ → Space → Vect) (T : ℝ) : Prop := + (∀ t ∈ Icc 0 T, SliceH2 (u t)) ∧ + (∀ i, continuousL2On (fun t x => u t x i) T) ∧ + (∀ i k, continuousL2On (fun t => D k (fun x => u t x i)) T) ∧ + (∀ i k l, continuousL2On (fun t => D l (D k (fun x => u t x i))) T) + +def continuousH1On (p : ℝ → Space → ℝ) (T : ℝ) : Prop := + (∀ t ∈ Icc 0 T, PressureH1 (p t)) ∧ continuousL2On p T ∧ + (∀ i, continuousL2On (fun t => D i (p t)) T) + +def C1L2On (u : ℝ → Space → Vect) (T : ℝ) : Prop := + letI : IsTopologicalAddGroup ℝ := instIsTopologicalAddGroupReal + letI := spaceOuterMeasureClass + ∃ U dU : ℝ → Fin 3 → L2Space, + (∀ i, ContinuousOn (fun t => U t i) (Icc 0 T)) ∧ + (∀ i, ContinuousOn (fun t => dU t i) (Icc 0 T)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, (fun x => U t i x) =ᵐ[measure] (fun x => u t x i)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, (fun x => dU t i x) =ᵐ[measure] (fun x => dt u t x i)) ∧ + (∀ t ∈ Icc 0 T, ∀ i, + HasDerivWithinAt (fun s => U s i) (dU t i) (Icc 0 T) t) + +structure ComparisonClass (u : ℝ → Space → Vect) (p : ℝ → Space → ℝ) : Prop where + velocity_H2 : ∀ T > 0, continuousH2On u T + velocity_C1L2 : ∀ T > 0, C1L2On u T + pressure_H1 : ∀ T > 0, continuousH1On p T + time_derivative : ∀ t ≥ 0, ∀ x i, + HasDerivWithinAt (fun s => u s x i) (dt u t x i) (Ici 0) t + velocity_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => u y.1 y.2 i) (Icc 0 T ×ˢ univ) + time_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => dt u y.1 y.2 i) (Icc 0 T ×ˢ univ) + gradient_continuous : ∀ T > 0, ∀ i k, + ContinuousOn (fun y : ℝ × Space => D k (fun x => u y.1 x i) y.2) (Icc 0 T ×ˢ univ) + second_continuous : ∀ T > 0, ∀ i k l, + ContinuousOn (fun y : ℝ × Space => D l (D k (fun x => u y.1 x i)) y.2) (Icc 0 T ×ˢ univ) + pressure_continuous : ∀ T > 0, + ContinuousOn (fun y : ℝ × Space => p y.1 y.2) (Icc 0 T ×ˢ univ) + pressure_gradient_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => D i (p y.1) y.2) (Icc 0 T ×ˢ univ) + bounds : ∀ T > 0, ∃ B : ℝ, 0 ≤ B ∧ + (∀ t ∈ Icc 0 T, ∀ x i, |u t x i| ≤ B) ∧ + (∀ t ∈ Icc 0 T, ∀ x i k, |D k (fun y => u t y i) x| ≤ B) + +def join (x : Space) : Coord 3 := + letI := neZeroTwo + ![x.1 0, x.1 1, x.2] + +end VelocityDetection.Cylinder +end + +noncomputable section +namespace VelocityDetection.TailSpace +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty + +def evalLinear (X : Coord 2) : compatible 2 →ₗ[ℝ] ℝ where + toFun f := f.val.1 X + map_add' _ _ := rfl + map_smul' _ _ := rfl + +def eval (X : Coord 2) : compatible 2 →L[ℝ] ℝ where + toLinearMap := evalLinear X + cont := AddMonoidHomClass.continuous_of_bound (evalLinear X) 1 (fun f => by + change ‖f.val.1 X‖ ≤ 1 * ‖f.val‖ + rw [one_mul] + exact (BoundedContinuousFunction.norm_coe_le_norm f.val.1.toBCF X).trans (norm_fst_le f.val)) + +end VelocityDetection.TailSpace +end + +noncomputable section +namespace VelocityDetection.History +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks + +structure Configuration (N : ℕ) where + tape : Stacks.Configuration (Fin N) + history : ℕ + deriving DecidableEq + +end VelocityDetection.History +end + +noncomputable section +namespace VelocityDetection.History +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks +variable {N b : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) + +def radix (N b : ℕ) : ℕ := N * b + +def tag (c : Stacks.Configuration (Fin N)) : ℕ := b * c.state.val + c.rightStack % b + +include hb in + +def applyRule (r : Rule (Fin N) b) (c : Configuration N) : Configuration N := + ⟨Stacks.applyRule r c.tape, radix N b * c.history + tag (b := b) c.tape⟩ + +include hb in + +def packedState (c : Configuration N) : ℕ := N * c.history + c.tape.state.val + +def address (B : ℕ) (c : Configuration N) : ℕ := + Stacks.address B (packedState c) c.tape.leftStack c.tape.rightStack + +abbrev Box (N B H : ℕ) := Fin N × Fin B × Fin B × Fin H + +def config {B H : ℕ} (c : Box N B H) : Configuration N := + ⟨⟨c.1, c.2.1, c.2.2.1⟩, c.2.2.2⟩ + +def Active (B H : ℕ) := {c : Box N B H // (Stacks.lookup hb table (config c).tape).isSome} + +def rule {B H : ℕ} (c : Active hb table B H) : Rule (Fin N) b := + (Stacks.lookup hb table (config c.val).tape).get c.property + +def target {B H : ℕ} (c : Active hb table B H) : Configuration N := + applyRule (rule hb table c) (config c.val) + +def sourceAddress {B H : ℕ} (c : Active hb table B H) : ℕ := address B (config c.val) + +def targetAddress {B H : ℕ} (c : Active hb table B H) : ℕ := address (b * B) (target hb table c) + +end VelocityDetection.History +end + +noncomputable section +namespace VelocityDetection.TapeCodes +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def word (w : List (Fin b)) : ℕ := Nat.ofDigits b (w.map Fin.val) + +def half (w : ListBlank (Fin b)) : ℕ := + w.liftOn word (by sorry) + +def tape (q : Fin N) (T : Tape (Fin b)) : Stacks.Configuration (Fin N) := + ⟨q, half T.left, half T.right₀⟩ + +def rule (a : Fin b) (q : Fin N) : TM0.Stmt (Fin b) → Rule (Fin N) b + | .move .left => ⟨q, a, .left⟩ + | .move .right => ⟨q, a, .right⟩ + | .write β => ⟨q, β, .stay⟩ + +def table (M : TM0.Machine (Fin b) (Fin N)) : Fin N → Fin b → Option (Rule (Fin N) b) := + fun q a => (M q a).map (fun p => rule a p.1 p.2) + +end VelocityDetection.TapeCodes +end + +noncomputable section +namespace VelocityDetection.Prelude +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Stacks +variable {N b : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) (q₀ : Fin N) + +def rule (r : Rule (Fin N) b) : Rule (Fin (N + 1)) b := + ⟨r.target.castSucc, r.written, r.move⟩ + +def table' : Fin (N + 1) → Fin b → Option (Rule (Fin (N + 1)) b) := + Fin.lastCases (fun a => some ⟨q₀.castSucc, a, .stay⟩) + (fun q a => (table q a).map rule) + +def initial (x y : ℕ) : Configuration (Fin (N + 1)) := ⟨Fin.last N, x, y⟩ + +end VelocityDetection.Prelude +end + +noncomputable section +namespace VelocityDetection.MachineHistory +open scoped BigOperators Topology ContDiff +open Set Function Filter +open Set Function Filter MeasureTheory +open scoped Topology BigOperators ContDiff +open scoped Topology ContDiff BigOperators +open scoped Topology ContDiff ZeroAtInfty +open scoped Topology ContDiff ZeroAtInfty BigOperators +open scoped Topology +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def table (M : TM0.Machine (Fin b) (Fin N)) : + Fin (N + 1) → Fin b → Option (Rule (Fin (N + 1)) b) := + Prelude.table' (TapeCodes.table M) 0 + +def initial (w : List (Fin b)) : Stacks.Configuration (Fin (N + 1)) := + Prelude.initial 0 (TapeCodes.word w) + +end VelocityDetection.MachineHistory +end + +noncomputable section +namespace VelocityDetection.Effective +open Polynomial Set Function Filter +open scoped BigOperators Topology ContDiff + +abbrev Poly := List (ℕ × ℚ) + +noncomputable def poly : Poly → Polynomial ℝ + | [] => 0 + | (k,q)::ps => Polynomial.C (q:ℝ)*Polynomial.X^k + poly ps + +def nextPoly : Poly → Poly + | [] => [] + | (k,q)::ps => (k+2,q)::(k+1,-q*k)::nextPoly ps + +noncomputable def flat (p : Poly) (x : ℝ) : ℝ := + (poly p).eval x⁻¹ * expNegInvGlue x + +def polyBound : Poly → ℚ + | [] => 0 + | (k,q)::ps => |q| *k.factorial + polyBound ps + +inductive Expr (n : ℕ) where + | rat : ℚ → Expr n + | var : Fin n → Expr n + | add : Expr n → Expr n → Expr n + | neg : Expr n → Expr n + | mul : Expr n → Expr n → Expr n + | inv : Expr n → Expr n + | flat : Poly → Expr n → Expr n + deriving Inhabited + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Polynomial Set Function Filter +open scoped BigOperators Topology ContDiff +variable {n : ℕ} + +noncomputable def eval (x : Fin n → ℝ) : Expr n → ℝ + | .rat q => q + | .var i => x i + | .add a b => a.eval x + b.eval x + | .neg a => -a.eval x + | .mul a b => a.eval x * b.eval x + | .inv a => (a.eval x)⁻¹ + | .flat p a => Effective.flat p (a.eval x) + +def diff (i : Fin n) : Expr n → Expr n + | .rat _ => .rat 0 + | .var j => .rat (if i=j then 1 else 0) + | .add a b => .add (a.diff i) (b.diff i) + | .neg a => .neg (a.diff i) + | .mul a b => .add (.mul (a.diff i) b) (.mul a (b.diff i)) + | .inv a => .neg (.mul (a.diff i) (.mul (.inv a) (.inv a))) + | .flat p a => .mul (.flat (nextPoly p) a) (a.diff i) + +def jet : List (Fin n) → Expr n → Expr n + | [], e => e + | i::is, e => jet is (e.diff i) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped BigOperators Topology + +structure Ball where + center : ℚ + radius : ℚ + deriving Inhabited + +def polyEval : Poly → ℚ → ℚ + | [], _ => 0 + | (k,q)::ps, x => q*x^k+polyEval ps x + +def expSum (q : ℚ) (n : ℕ) : ℚ := ∑ k ∈ Finset.range n, q^k / k.factorial + +def expError (q : ℚ) (n : ℕ) : ℚ := |q|^n / n.factorial * 2 + +def flatRound (p : Poly) (q : ℚ) (n : ℕ) : Ball := + if q ≤ 0 then ⟨0,0⟩ else + if |q⁻¹|/(n+1) ≤ (1/2:ℚ) ∧ + |polyEval p q⁻¹| *expError (-q⁻¹) n ≤ polyBound (nextPoly p)*|q| then + ⟨polyEval p q⁻¹*expSum (-q⁻¹) n,|polyEval p q⁻¹| *expError (-q⁻¹) n⟩ + else ⟨0,polyBound (nextPoly p)*|q|⟩ + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.Ball +open Set Filter Function +open scoped Topology + +def atom (q : ℚ) : Ball := ⟨q,0⟩ + +def add (a b : Ball) : Ball := ⟨a.center+b.center,a.radius+b.radius⟩ + +def neg (a : Ball) : Ball := ⟨-a.center,a.radius⟩ + +def mul (a b : Ball) : Ball := + ⟨a.center*b.center,|a.center| *b.radius+|b.center| *a.radius+a.radius*b.radius⟩ + +def inv (a : Ball) : Ball := + ⟨a.center⁻¹,a.radius/(|a.center| *(|a.center|-a.radius))⟩ + +def invSafe (a : Ball) : Bool := decide (a.radius < |a.center|) + +def flat (p : Poly) (a : Ball) (k : ℕ) : Ball := + let b := flatRound p a.center k + ⟨b.center,b.radius+polyBound (nextPoly p)*a.radius⟩ + +end VelocityDetection.Effective.Ball +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Filter Function +open scoped Topology +variable {n : ℕ} + +def round (a : Fin n → Ball) (k : ℕ) : Expr n → Ball := + Expr.rec (motive := fun _ => Ball) + Ball.atom a + (fun _ _ e f => e.add f) + (fun _ e => e.neg) + (fun _ _ e f => e.mul f) + (fun _ e => e.inv) + (fun p _ e => e.flat p k) + +def safe (a : Fin n → Ball) (k : ℕ) : Expr n → Bool := + Expr.rec (motive := fun _ => Bool) + (fun _ => true) (fun _ => true) + (fun _ _ e f => e && f) + (fun _ e => e) + (fun _ _ e f => e && f) + (fun e safe_e => safe_e && (e.round a k).invSafe) + (fun _ _ e => e) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology + +noncomputable def coordinateD {n : ℕ} (i : Fin n) (f : (Fin n → ℝ) → ℝ) (x : Fin n → ℝ) : ℝ := + deriv (fun s => f (update x i s)) (x i) + +noncomputable def mixedD {n : ℕ} : List (Fin n) → ((Fin n → ℝ) → ℝ) → (Fin n → ℝ) → ℝ + | [], f => f + | i::is, f => mixedD is (coordinateD i f) + +def accuracy (k : ℕ) : ℚ := (1/2)^k + +def Names {n : ℕ} (q : Fin n → ℕ → ℚ) (x : Fin n → ℝ) : Prop := + ∀ i k, |x i-(q i k:ℝ)| ≤ (accuracy k:ℝ) + +def inputBall {n : ℕ} (q : Fin n → ℕ → ℚ) (k : ℕ) (i : Fin n) : Ball := + ⟨q i k,accuracy k⟩ + +def trial {n : ℕ} (e : Expr n) (is : List (Fin n)) (q : Fin n → ℕ → ℚ) + (ε : ℚ) (k : ℕ) : Option ℚ := + let d := e.jet is + let a := inputBall q k + if d.safe a k && decide ((d.round a k).radius ≤ ε) then some (d.round a k).center else none + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.PeriodicSpace +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators BoundedContinuousFunction + +abbrev Torus (n : ℕ) := Fin n → AddCircle (1 : ℝ) + +def cover {n : ℕ} (X : Coord n) : Torus n := fun i => (X i : AddCircle (1 : ℝ)) + +end VelocityDetection.PeriodicSpace +end + +noncomputable section +namespace VelocityDetection.SmoothBump +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators +open TranslationGates + +def profile (s : ℝ) : ℝ := window (((3 : ℕ) : ℝ)*s) + +end VelocityDetection.SmoothBump +end + +noncomputable section +namespace VelocityDetection.TorusClass +open Set Function Filter MeasureTheory +open scoped Topology ContDiff BigOperators + +abbrev Space := Coord 3 + +def measure : Measure Space := volume.restrict (Icc (0 : Space) 1) + +def periodic (f : Space → ℝ) : Prop := FactorsThrough f PeriodicSpace.cover + +def frame (i : Fin 3) : Space := Pi.single i 1 + +def D (i : Fin 3) (f : Space → ℝ) (x : Space) : ℝ := fderiv ℝ f x (frame i) + +def dt (u : VectorField 3) (t : ℝ) (x : Space) (i : Fin 3) : ℝ := + derivWithin (fun s => u s x i) (Ici 0) t + +structure ComparisonClass (u : VectorField 3) (p : ScalarField 3) : Prop where + velocity_slices : ∀ t ≥ 0, ∀ i, ContDiff ℝ 2 (fun x => u t x i) + pressure_slices : ∀ t ≥ 0, ContDiff ℝ 1 (p t) + velocity_periodic : ∀ t ≥ 0, FactorsThrough (u t) PeriodicSpace.cover + pressure_periodic : ∀ t ≥ 0, periodic (p t) + pressure_mean : ∀ t ≥ 0, (∫ x, p t x ∂measure) = 0 + time_derivative : ∀ t ≥ 0, ∀ x i, + HasDerivWithinAt (fun s => u s x i) (dt u t x i) (Ici 0) t + velocity_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => u y.1 y.2 i) (Icc 0 T ×ˢ univ) + time_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => dt u y.1 y.2 i) (Icc 0 T ×ˢ univ) + gradient_continuous : ∀ T > 0, ∀ i k, + ContinuousOn (fun y : ℝ × Space => D k (fun x => u y.1 x i) y.2) (Icc 0 T ×ˢ univ) + second_continuous : ∀ T > 0, ∀ i k l, + ContinuousOn (fun y : ℝ × Space => D l (D k (fun x => u y.1 x i)) y.2) (Icc 0 T ×ˢ univ) + pressure_continuous : ∀ T > 0, + ContinuousOn (fun y : ℝ × Space => p y.1 y.2) (Icc 0 T ×ˢ univ) + pressure_gradient_continuous : ∀ T > 0, ∀ i, + ContinuousOn (fun y : ℝ × Space => D i (p y.1) y.2) (Icc 0 T ×ˢ univ) + +end VelocityDetection.TorusClass +end + +noncomputable section +namespace VelocityDetection.MachineTorus +open Set Function MeasureTheory +open scoped Topology ContDiff BigOperators +open Turing Stacks +variable {b N : ℕ} [NeZero b] [NeZero N] + +def initialAddress (w : List (Fin b)) : ℕ := + History.address (capacity b (w.length+1) 0) ⟨MachineHistory.initial (N := N) w,0⟩ + +end VelocityDetection.MachineTorus +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Function Filter +open scoped Topology BigOperators +variable {n m : ℕ} + +instance : Add (Expr n) := ⟨Expr.add⟩ + +instance : Neg (Expr n) := ⟨Expr.neg⟩ + +instance : Sub (Expr n) := ⟨fun a b => .add a (.neg b)⟩ + +instance : Mul (Expr n) := ⟨Expr.mul⟩ + +instance : Inv (Expr n) := ⟨Expr.inv⟩ + +instance : Div (Expr n) := ⟨fun a b => .mul a (.inv b)⟩ + +instance (k : ℕ) : OfNat (Expr n) k := ⟨.rat k⟩ + +def subst (v : Fin m → Expr n) : Expr m → Expr n := + Expr.rec (motive := fun _ => Expr n) + Expr.rat v + (fun _ _ a b => .add a b) + (fun _ a => .neg a) + (fun _ _ a b => .mul a b) + (fun _ a => .inv a) + (fun p _ a => .flat p a) + +def sumList : List (Expr n) → Expr n + | [] => 0 + | e::es => e + sumList es + +def sumFin (k : ℕ) (f : Fin k → Expr n) : Expr n := sumList (List.ofFn f) + +def unaryD (e : Expr 1) (a : Expr n) : Expr n := (e.diff 0).subst (fun _ => a) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective.Recipe +open Set Function Filter +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr +variable {n : ℕ} + +def glue (a : Expr n) : Expr n := .flat [(0,1)] a + +def step (a : Expr n) : Expr n := glue a/(glue a+glue (1-a)) + +def pulse (a : Expr n) : Expr n := (step (.var 0 : Expr 1)).unaryD a + +def window (a : Expr n) : Expr n := step (a+3)*step (3-a) + +def windowD (a : Expr n) : Expr n := pulse (a+3)*step (3-a)-step (a+3)*pulse (3-a) + +def theta (a T : Expr n) (j : ℕ) (t : Expr n) : Expr n := + step (2*(3*(t-a)/T-.rat j)-.rat (1/2)) + +def center (a T S S' σ : Expr n) (k l : ℕ) (t : Expr n) : Fin 2 → Expr n := + ![(1-theta a T 1 t)*S*.rat k+theta a T 1 t*S'*.rat l, + -(1-theta a T 0 t)*S+(theta a T 0 t-theta a T 2 t)*(-(.rat k+2)*S)+ + theta a T 2 t*σ*S'] + +def gate (R : Expr n) (c G X : Fin 2 → Expr n) : Fin 2 → Expr n := + letI := neZeroTwo + ![window ((X 0-c 0)/R)*(windowD ((X 1-c 1)/R)/R)* + (G 0*(X 1-c 1)-G 1*(X 0-c 0))+ + window ((X 0-c 0)/R)*window ((X 1-c 1)/R)*G 0, + window ((X 0-c 0)/R)*window ((X 1-c 1)/R)*G 1- + (windowD ((X 0-c 0)/R)/R*window ((X 1-c 1)/R))* + (G 0*(X 1-c 1)-G 1*(X 0-c 0))] + +def impulse (t : Expr n) (p X : Fin 2 → Expr n) : Expr n := + letI := neZeroTwo + pulse t*pulse (X 0-p 0+.rat (1/2))*pulse (X 1-p 1+.rat (1/2)) + +def packet (R : Expr n) (X : Fin 2 → Expr n) : Expr n := + letI := neZeroTwo + window (3*(X 0/R))*window (3*(X 1/R)) + +end VelocityDetection.Effective.Recipe +end + +noncomputable section +namespace VelocityDetection.Effective.Expr +open Set Function +open scoped BigOperators Topology +variable {n : ℕ} + +def activeSum {N b B H : ℕ} (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) + (f : History.Active hb table B H → Expr n) : Expr n := + sumFin N (fun s => sumFin B (fun l => sumFin B (fun r => sumFin H (fun h => + if hp : (Stacks.lookup hb table (History.config (s,l,r,h)).tape).isSome then + f ⟨(s,l,r,h),hp⟩ else 0)))) + +end VelocityDetection.Effective.Expr +end + +noncomputable section +namespace VelocityDetection.Effective.ArrayRecipe +open Set Function +open scoped BigOperators Topology +open _root_.OAI.VelocityDetection.Effective.Expr Stacks +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Rule (Fin N) b)) (m : ℕ) + +abbrev Code := Expr 5 + +def K (N b m : ℕ) : ℕ := N * capacity b (m+1) 0 ^ 2 + +def D (N b : ℕ) : ℕ := b^2 * History.radix N b + +def radius (N b m n : ℕ) : Code := + .rat (1024*3000*(4*(D N b))*(K N b m*D N b+2)*(4*D N b)^n) * (1+.var 0) + +def spacing (N b m n : ℕ) : Code := 16*radius N b m n + +def duration (N b m n : ℕ) : Code := + spacing N b m (n+1) * .rat (K N b m*D N b^(n+1)+2) + +def start (N b m : ℕ) : ℕ → Code + | 0 => 1 + | n+1 => start N b m n+duration N b m n + +def sign (c : History.Configuration N) : ℚ := + if (lookup hb table c.tape).isNone then 1 else -1 + +abbrev Instruction (n : ℕ) := History.Active hb table (capacity b (m+1) n) (History.radix N b^n) + +def path (n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + Recipe.center (start N b m n) (duration N b m n) (spacing N b m n) + (spacing N b m (n+1)) (.rat (sign hb table (History.target hb table c))) + (History.sourceAddress hb table c) (History.targetAddress hb table c) (.var 1) + +def gate (n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + Recipe.gate (radius N b m n) (path hb table m n c) + (fun i => (path hb table m n c i).diff 1) ![.var 2,.var 3] + +def stage (n : ℕ) (i : Fin 2) : Code := + activeSum hb table (fun c : Instruction hb table m n => gate hb table m n c i) + +def field (L : ℕ) (i : Fin 2) : Code := sumFin L (fun n => stage hb table m n i) + +end VelocityDetection.Effective.ArrayRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.ChartRecipe +open Set Function ArrayRecipe +open scoped BigOperators Topology +open VelocityDetection.Effective.Expr +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) (m : ℕ) + +def scale (N b m P : ℕ) : ℚ := (1024*((K N b m:ℚ)*(D N b:ℚ)^(P+1)+4))⁻¹ + +def radius (N b m P : ℕ) : ℚ := scale N b m P/16 + +def targetHeight (P n : ℕ) (c : Instruction hb table m n) : ℚ := + if ArrayRecipe.sign hb table (History.target hb table c) = 1 then -(7/16) else -scale N b m P + +def path (P n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + letI := neZeroFive + fun i => + .rat (![1/4,1/2] i) + Recipe.center (.rat n) 1 (.rat (scale N b m P)) (.rat (scale N b m P)) + (.rat (targetHeight hb table m P n c/scale N b m P)) + (History.sourceAddress hb table c) (History.targetAddress hb table c) (.var 1) i + +def gate (P n : ℕ) (c : Instruction hb table m n) : Fin 2 → Code := + letI := neZeroFive + Recipe.gate (.rat (radius N b m P)) (path hb table m P n c) + (fun i => (path hb table m P n c i).diff 1) ![.var 2,.var 3] + +def stage (P n : ℕ) (i : Fin 2) : Code := + activeSum hb table (fun c : Instruction hb table m n => gate hb table m P n c i) + +def prefixCode (P : ℕ) (i : Fin 2) : Code := sumFin P (fun n => stage hb table m P n i) + +def duration (N b m B k : ℕ) : Code := + letI := neZeroFive + .rat ((1/16)*(1/2:ℚ)^k) / + (3*(1+.var 0*.rat (2*(B:ℚ)/(radius N b m (k+1))^2))) + +def localTime (N b m B k : ℕ) : Code := + letI := neZeroFive + (.var 1-.rat (k+1))/duration N b m B k + +def weight (N b m B k : ℕ) : Code := + Recipe.step (8*localTime N b m B k)-Recipe.step (8*localTime N b m B k-.rat 7) + +def clock (N b m B k : ℕ) : Code := .rat (k+1)* + (Recipe.step (8*localTime N b m B k-1)-Recipe.step (8*localTime N b m B k-.rat 5)) + +def rawField (B k : ℕ) (i : Fin 2) : Code := + letI := neZeroFive + (clock N b m B k).diff 1 * (prefixCode hb table m (k+1) i).subst + ![.var 0,clock N b m B k,.var 2,.var 3,.var 4] + +def initial (N b m P q : ℕ) : Fin 2 → Code := + ![.rat (1/4+scale N b m P*q),.rat (1/2-scale N b m P)] + +def rawSource (B q k : ℕ) : Code := + letI := neZeroFive + (weight N b m B k).diff 1 * + Recipe.packet (.rat (radius N b m (k+1))) + (fun i => (![.var 2,.var 3] i)-initial N b m (k+1) q i) + +end VelocityDetection.Effective.ChartRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Function +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr ArrayRecipe + +def periodize (R : ℕ) (e : Code) : Code := + letI := neZeroFive + sumFin (2*R+1) (fun i => sumFin (2*R+1) (fun j => + e.subst ![.var 0,.var 1,.var 2-.rat ((i:ℚ)-R),.var 3-.rat ((j:ℚ)-R),.var 4])) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.ChartRecipe +open Set Function +open scoped Topology BigOperators +open _root_.OAI.VelocityDetection.Effective.Expr ArrayRecipe +variable {N b : ℕ} (hN : 0 < N) (hb : 0 < b) + (table : Fin N → Fin b → Option (Stacks.Rule (Fin N) b)) (m : ℕ) + +def fieldBlock (B R k : ℕ) (i : Fin 2) : Code := periodize R (rawField hb table m B k i) + +def sourceBlock (N b m B q R k : ℕ) : Code := periodize R (rawSource (N:=N) (b:=b) m B q k) + +def field (B R L : ℕ) (i : Fin 2) : Code := sumFin L (fun k => fieldBlock hb table m B R k i) + +def source (N b m B q R L : ℕ) : Code := sumFin L (fun k => sourceBlock N b m B q R k) + +end VelocityDetection.Effective.ChartRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +def residualCode (a : Fin 2 → Code) (i : Fin 2) : Code := + letI := neZeroTwo + letI := neZeroFive + (a i).diff 1 + a 0*(a i).diff 2 + a 1*(a i).diff 3 - + .var 0*((((a i).diff 2).diff 2)+(((a i).diff 3).diff 3)) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.ArrayRecipe +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +def initialCode (N b m q : ℕ) : Fin 2 → Code := + ![spacing N b m 0 * .rat q,-spacing N b m 0] + +def source (N b m q : ℕ) : Code := + letI := neZeroFive + Recipe.impulse (.var 1) (initialCode N b m q) ![.var 2,.var 3] + +end VelocityDetection.Effective.ArrayRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe + +noncomputable def forceFunction (f : ℝ → VectorField 3) (i : Fin 3) (x : Fin 5 → ℝ) : ℝ := + letI := neZeroFive + f (x 0) (x 1) ![x 2,x 3,x 4] i + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Filter Function Turing +open scoped Topology BigOperators ContDiff +open VelocityDetection.Effective.Expr ArrayRecipe +variable {b N : ℕ} [NeZero b] [NeZero N] + +inductive Domain where | torus | cylinder + deriving DecidableEq, Repr + +def field (d : Domain) (B R L : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 2) : Code := match d with + | .torus => ChartRecipe.field (NeZero.pos b) (MachineHistory.table M) w.length B R L i + | .cylinder => ArrayRecipe.field (NeZero.pos b) (MachineHistory.table M) w.length L i + +def source (d : Domain) (B R L : ℕ) (w : List (Fin b)) : Code := match d with + | .torus => ChartRecipe.source (N+1) b w.length B (MachineTorus.initialAddress (N:=N) w) R L + | .cylinder => ArrayRecipe.source (N+1) b w.length (MachineTorus.initialAddress (N:=N) w) + +def force (d : Domain) (B R L : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) : Code := + letI := neZeroTwo + ![residualCode (field d B R L M w) 0,residualCode (field d B R L M w) 1, + source (N:=N) d B R L w] i + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Filter Function Turing +open scoped Topology ContDiff BigOperators +variable {b N : ℕ} [NeZero b] [NeZero N] + +def timeCutoff (q : Fin 5 → ℕ → ℚ) : ℕ := + letI := neZeroFive + ⌈q 1 0+2⌉₊ + +def spaceCutoff (q : Fin 5 → ℕ → ℚ) : ℕ := + letI := neZeroFive + ⌈|q 2 0|+|q 3 0|+3⌉₊ + +def runTrial (d : Domain) (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) (is : List (Fin 5)) (q : Fin 5 → ℕ → ℚ) + (ε : ℚ) (k : ℕ) : Option ℚ := + trial (force d B (spaceCutoff q) (timeCutoff q) M w i) is q ε k + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective +open Set Filter Function +open scoped Topology BigOperators + +structure RationalBox (n : ℕ) where + lower : Fin n → ℚ + upper : Fin n → ℚ + ordered : ∀ i, lower i ≤ upper i + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection.Effective.RationalBox +open Set Filter Function +open scoped Topology BigOperators +variable {n : ℕ} (Q : RationalBox n) + +def carrier : Set (Fin n → ℝ) := Icc (fun i => (Q.lower i:ℝ)) (fun i => (Q.upper i:ℝ)) + +def cell (k : ℕ) (j : Fin n → Fin (k+2)) (i : Fin n) : Ball := + ⟨Q.lower i+(Q.upper i-Q.lower i)*((j i:ℕ):ℚ)/(k+1), + (Q.upper i-Q.lower i)/(k+1)⟩ + +def boundTrial (e : Expr n) (is : List (Fin n)) (k : ℕ) : Option ℚ := + if ∀ j : Fin n → Fin (k+2), (e.jet is).safe (Q.cell k j) k = true then + some (∑ j : Fin n → Fin (k+2), + (|((e.jet is).round (Q.cell k j) k).center| + |((e.jet is).round (Q.cell k j) k).radius|)) + else none + +end VelocityDetection.Effective.RationalBox +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Set Function Turing +variable {b N : ℕ} [NeZero b] [NeZero N] + +def boxTimeCutoff (Q : RationalBox 5) : ℕ := + letI := neZeroFive + ⌈Q.upper 1+1⌉₊ + +def boxSpaceCutoff (Q : RationalBox 5) : ℕ := + letI := neZeroFive + ⌈|Q.lower 2|+|Q.upper 2|+|Q.lower 3|+|Q.upper 3|+2⌉₊ + +def runBoundTrial (d : Domain) (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) + (w : List (Fin b)) (i : Fin 3) (is : List (Fin 5)) (Q : RationalBox 5) (k : ℕ) : Option ℚ := + Q.boundTrial (force d B (boxSpaceCutoff Q) (boxTimeCutoff Q) M w i) is k + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe +open Turing + +structure Program (b N : ℕ) [NeZero b] [NeZero N] where + derivativeBound : ℕ + table : TM0.Machine (Fin b) (Fin N) + input : List (Fin b) + +def compile {b N : ℕ} [NeZero b] [NeZero N] (B : ℕ) (M : TM0.Machine (Fin b) (Fin N)) (w : List (Fin b)) : + Program b N := ⟨B,M,w⟩ + +end VelocityDetection.Effective.MachineRecipe +end + +noncomputable section +namespace VelocityDetection.Effective.MachineRecipe.Program +open Turing +variable {b N : ℕ} [NeZero b] [NeZero N] + +def valueTrial (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (q : Fin 5 → ℕ → ℚ) (ε : ℚ) (k : ℕ) : Option ℚ := + runTrial d P.derivativeBound P.table P.input i is q ε k + +def boundTrial (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (Q : RationalBox 5) (k : ℕ) : Option ℚ := + runBoundTrial d P.derivativeBound P.table P.input i is Q k + +noncomputable def evaluate (P : Program b N) (d : Domain) (i : Fin 3) (is : List (Fin 5)) + (q : Fin 5 → ℕ → ℚ) (ε : ℚ) : Part ℚ := Nat.rfindOpt (P.valueTrial d i is q ε) + +noncomputable def derivativeBounds (P : Program b N) (d : Domain) (i : Fin 3) + (is : List (Fin 5)) (Q : RationalBox 5) : Part ℚ := Nat.rfindOpt (P.boundTrial d i is Q) + +def Represents (P : Program b N) (d : Domain) (F : ℝ → VectorField 3) : Prop := + letI := neZeroFive + (∀ (i : Fin 3) (is : List (Fin 5)) (q : Fin 5 → ℕ → ℚ) (x : Fin 5 → ℝ), + Names q x → 0 < x 0 → ∀ ε : ℚ, 0 < ε → + (P.evaluate d i is q ε).Dom ∧ + ∀ r ∈ P.evaluate d i is q ε, + |mixedD is (forceFunction F i) x-(r:ℝ)| ≤ (ε:ℝ)) ∧ + (∀ (i : Fin 3) (is : List (Fin 5)) (Q : RationalBox 5), 0 < Q.lower 0 → + (P.derivativeBounds d i is Q).Dom ∧ + ∀ C ∈ P.derivativeBounds d i is Q, 0 ≤ C ∧ + ∀ x ∈ Q.carrier, |mixedD is (forceFunction F i) x| ≤ (C:ℝ)) + +end VelocityDetection.Effective.MachineRecipe.Program +end + +noncomputable section +namespace VelocityDetection.Effective +open Turing + +def ComputableReal (x : ℝ) : Prop := + ∃ q : ℕ → ℚ, Computable q ∧ ∀ k, |x-(q k:ℝ)| ≤ (accuracy k:ℝ) + +end VelocityDetection.Effective +end + +noncomputable section +namespace VelocityDetection +open Set Function MeasureTheory Turing +open scoped ContDiff +open Effective Effective.MachineRecipe + +theorem main_result : + ∃ B : ℕ, 0 < B ∧ + (∀ s : ℝ, |deriv (deriv SmoothBump.profile) s| ≤ (B:ℝ)) ∧ + ∀ (ν : ℝ), 0 < ν → ComputableReal ν → + ∀ (b N : ℕ) [NeZero b] [NeZero N] + (M : TM0.Machine (Fin b) (Fin N)) (w : List (Fin b)), + ∃ (Ftor Fcyl : ℝ → VectorField 3), + (compile B M w).Represents .torus Ftor ∧ + (compile B M w).Represents .cylinder Fcyl ∧ + (ContDiff ℝ ∞ (uncurry (Ftor ν)) ∧ + (∀ t, FactorsThrough (Ftor ν t) PeriodicSpace.cover) ∧ + (∃ K : Set (Coord 2), IsCompact K ∧ (∀ X ∈ K, ∀ i, X i ∈ Ioo (0:ℝ) 1) ∧ + ∀ t X, PeriodicSpace.cover (horizontal X) ∉ PeriodicSpace.cover '' K → Ftor ν t X = 0) ∧ + (∀ T d, ∃ C : ℝ, 0 ≤ C ∧ ∀ t ∈ Icc (0:ℝ) T, ∀ X, + ‖iteratedFDeriv ℝ d (uncurry (Ftor ν)) (t,X)‖ ≤ C) ∧ + ∃ u : VectorField 3, + ContDiff ℝ ∞ (uncurry u) ∧ TorusClass.ComparisonClass u (fun _ _ => 0) ∧ + NavierStokes ν u (fun _ _ => 0) (Ftor ν) ∧ + (Observation.torusEvent u ↔ (TM0.eval M w).Dom) ∧ + ∀ (v : VectorField 3) (p : ScalarField 3), TorusClass.ComparisonClass v p → + NavierStokes ν v p (Ftor ν) → + ∀ t ≥ 0, (∀ X, v t X = u t X) ∧ (∀ X, p t X = 0)) ∧ + (ContDiff ℝ ∞ (uncurry (Fcyl ν)) ∧ + UniformDerivatives.Bounded (fun _ : Unit => uncurry (Fcyl ν)) ∧ + (∀ t X z, Fcyl ν t (update X 2 z) = Fcyl ν t X) ∧ + (∀ T : ℝ, ∃ K : Set (Coord 2), IsCompact K ∧ ∀ t ∈ Icc (0:ℝ) T, + ∀ X : Coord 3, horizontal X ∉ K → Fcyl ν t X = 0) ∧ + ∃ u : VectorField 3, + ContDiff ℝ ∞ (uncurry u) ∧ + Cylinder.ComparisonClass (fun t x => u t (Cylinder.join x)) (fun _ _ => 0) ∧ + NavierStokes ν u (fun _ _ => 0) (Fcyl ν) ∧ + (∀ t ≥ 0, (∀ x, 0 ≤ u t (Cylinder.join x) 2) ∧ + Integrable (fun x => u t (Cylinder.join x) 2) Cylinder.measure) ∧ + (Observation.planeEvent u ↔ (TM0.eval M w).Dom) ∧ + ∀ (v : VectorField 3) (p : ScalarField 3), + Cylinder.ComparisonClass (fun t x => v t (Cylinder.join x)) + (fun t x => p t (Cylinder.join x)) → + NavierStokes ν v p (Fcyl ν) → + ∀ t ≥ 0, (∀ X, v t X = u t X) ∧ (∀ X, p t X = 0)) := by sorry + +end VelocityDetection +end + +end OAI diff --git a/tasks/navier-stokes-velocity/tests/grade.py b/tasks/navier-stokes-velocity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/navier-stokes-velocity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/navier-stokes-velocity/tests/task.json b/tasks/navier-stokes-velocity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..91cf2500515e0d79bd15a4d4beac1af000b4fd9e --- /dev/null +++ b/tasks/navier-stokes-velocity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "NavierStokesVelocity", + "comparator": { + "theorem_names": [ + "OAI.VelocityDetection.main_result" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11728 +} \ No newline at end of file diff --git a/tasks/navier-stokes-velocity/tests/test.sh b/tasks/navier-stokes-velocity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/navier-stokes-velocity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/nodal-length/environment/Dockerfile b/tasks/nodal-length/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/nodal-length/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/nodal-length/environment/fetch_mathlib.sh b/tasks/nodal-length/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/nodal-length/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/nodal-length/environment/lake-manifest.json b/tasks/nodal-length/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/nodal-length/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/nodal-length/environment/lakefile.lean b/tasks/nodal-length/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/nodal-length/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/nodal-length/environment/lean_setup.sh b/tasks/nodal-length/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/nodal-length/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/nodal-length/environment/pack_submission.py b/tasks/nodal-length/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/nodal-length/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/nodal-length/instruction.md b/tasks/nodal-length/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fabbab853184e37f6a9268b6029db6286f3161b7 --- /dev/null +++ b/tasks/nodal-length/instruction.md @@ -0,0 +1,113 @@ +# openai/math challenge `NodalLength` (family 350) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 350 of the release, *Yau's nodal conjecture: surfaces and counterexamples* +(Differential geometry). The family as a whole: Proves the sharp $C\sqrt\lambda$ upper bound for nodal length on every fixed smooth closed surface, completing Yau's conjecture there. The upper bound fails for fixed smooth metrics in dimensions three and four, including metrics on $S^3$ arbitrarily close to round. In dimension five, nodal measure can grow faster than $\lambda^{1/2+\varepsilon_0}$ for some fixed $\varepsilon_0>0$, ruling out even arbitrarily small power losses. + +The challenge is `NodalLength`, also at `/opt/openai-math/challenges/NodalLength.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped ContDiff Bundle ENNReal +open Bundle Manifold MeasureTheory + +namespace SharpNodal + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +variable {M : Type*} [MetricSpace M] [ChartedSpace Plane M] + [IsManifold 𝓘(ℝ, Plane) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Plane) x)] + +def coordinateMetric (x : M) (y : Plane) : Matrix (Fin 2) (Fin 2) ℝ := + fun i j => inner ℝ + (mfderiv 𝓘(ℝ, Plane) 𝓘(ℝ, Plane) (chartAt Plane x).symm y + (EuclideanSpace.single i 1)) + (mfderiv 𝓘(ℝ, Plane) 𝓘(ℝ, Plane) (chartAt Plane x).symm y + (EuclideanSpace.single j 1)) + +def coordinateDensity (x : M) (y : Plane) : ℝ := + Real.sqrt (coordinateMetric x y).det + +def coordPartial (f : Plane → ℝ) (i : Fin 2) (y : Plane) : ℝ := + fderiv ℝ f y (EuclideanSpace.single i 1) + +def laplaceBeltrami (u : M → ℝ) (x : M) : ℝ := + (coordinateDensity x (chartAt Plane x x))⁻¹ * + ∑ i : Fin 2, coordPartial (fun y => coordinateDensity x y * + ∑ j : Fin 2, ((coordinateMetric x y)⁻¹ i j) * + coordPartial (u ∘ (chartAt Plane x).symm) j y) i (chartAt Plane x x) + +def nodalSet (u : M → ℝ) : Set M := {x | u x = 0} + +def nodalLength (u : M → ℝ) : ℝ≥0∞ := + letI : MeasurableSpace M := borel M + letI : BorelSpace M := ⟨rfl⟩ + Measure.hausdorffMeasure 1 (nodalSet u) + +def MainStatement (M : Type*) [MetricSpace M] [ChartedSpace Plane M] + [IsManifold 𝓘(ℝ, Plane) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Plane) x)] : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ (lam : ℝ), 0 < lam → ∀ (u : M → ℝ), + ContMDiff 𝓘(ℝ, Plane) 𝓘(ℝ) ∞ u → u ≠ 0 → + (∀ x, -laplaceBeltrami u x = lam * u x) → + nodalLength u ≤ ENNReal.ofReal (C * Real.sqrt lam) + +theorem Main [CompactSpace M] [ConnectedSpace M] + [IsContMDiffRiemannianBundle 𝓘(ℝ,Plane) ∞ Plane + (fun x:M=>TangentSpace 𝓘(ℝ,Plane) x)] + [IsRiemannianManifold 𝓘(ℝ,Plane) M] : MainStatement M := by + sorry + +end SharpNodal + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/NodalLength.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SharpNodal.Main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/nodal-length/solution/closure.txt b/tasks/nodal-length/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..26cd278f8c2881f21c52bf5c96a72a1d0c343ba6 --- /dev/null +++ b/tasks/nodal-length/solution/closure.txt @@ -0,0 +1,59 @@ +OAI.Analysis.NodalLength.AffineError +OAI.Analysis.NodalLength.Carleman +OAI.Analysis.NodalLength.Cells +OAI.Analysis.NodalLength.ChartTransfer +OAI.Analysis.NodalLength.Commutator +OAI.Analysis.NodalLength.CompactCover +OAI.Analysis.NodalLength.ComplexDerivatives +OAI.Analysis.NodalLength.Conductivity +OAI.Analysis.NodalLength.ConformalLength +OAI.Analysis.NodalLength.Cutoffs +OAI.Analysis.NodalLength.Decomposition +OAI.Analysis.NodalLength.Descent +OAI.Analysis.NodalLength.Distributional +OAI.Analysis.NodalLength.Divisors +OAI.Analysis.NodalLength.Eigenfunctions +OAI.Analysis.NodalLength.Elliptic +OAI.Analysis.NodalLength.Energy +OAI.Analysis.NodalLength.Excursions +OAI.Analysis.NodalLength.FrequencyGap +OAI.Analysis.NodalLength.GlobalProfiles +OAI.Analysis.NodalLength.GradientAnchors +OAI.Analysis.NodalLength.GradientCones +OAI.Analysis.NodalLength.GridImprovement +OAI.Analysis.NodalLength.GridPaths +OAI.Analysis.NodalLength.HolomorphicGradient +OAI.Analysis.NodalLength.HolomorphicLength +OAI.Analysis.NodalLength.Integration +OAI.Analysis.NodalLength.InteriorMass +OAI.Analysis.NodalLength.Isothermal +OAI.Analysis.NodalLength.Lattice +OAI.Analysis.NodalLength.LocalLength +OAI.Analysis.NodalLength.LogGradients +OAI.Analysis.NodalLength.Main +OAI.Analysis.NodalLength.MassComparison +OAI.Analysis.NodalLength.MetricFamilies +OAI.Analysis.NodalLength.MetricFlux +OAI.Analysis.NodalLength.Model +OAI.Analysis.NodalLength.Multipliers +OAI.Analysis.NodalLength.NodalGraphs +OAI.Analysis.NodalLength.Normalization +OAI.Analysis.NodalLength.NormalizedCharts +OAI.Analysis.NodalLength.Parametrix +OAI.Analysis.NodalLength.Persistence +OAI.Analysis.NodalLength.PlaneLength +OAI.Analysis.NodalLength.Potential +OAI.Analysis.NodalLength.ProfileExtraction +OAI.Analysis.NodalLength.ProfileTests +OAI.Analysis.NodalLength.RegularWeights +OAI.Analysis.NodalLength.Regularization +OAI.Analysis.NodalLength.RieszMeasure +OAI.Analysis.NodalLength.ScaledWaves +OAI.Analysis.NodalLength.Similarity +OAI.Analysis.NodalLength.StoppedTrees +OAI.Analysis.NodalLength.Subdivision +OAI.Analysis.NodalLength.Subharmonic +OAI.Analysis.NodalLength.SupportLimits +OAI.Analysis.NodalLength.TerminalGrid +OAI.Analysis.NodalLength.Vitali +OAI.Analysis.NodalLength.WitnessPacking diff --git a/tasks/nodal-length/solution/reference.py b/tasks/nodal-length/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/nodal-length/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/nodal-length/solution/solve.sh b/tasks/nodal-length/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..949706b42e46da3f86fbf84ce5ab125a93df79a3 --- /dev/null +++ b/tasks/nodal-length/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of NodalLength, i.e. module OAI.Analysis.NodalLength.Main and the +# 59 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.NodalLength.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of NodalLength" diff --git a/tasks/nodal-length/task.toml b/tasks/nodal-length/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d821fb9b2ea6cbe2b85662d2aa04f8dcfe8fedf5 --- /dev/null +++ b/tasks/nodal-length/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/nodal-length" +version = "1.0.0" +description = "Prove NodalLength (openai/math family 350: Yau's nodal conjecture: surfaces and counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/NodalLength.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "NodalLength" +family = "350" +family_title = "Yau's nodal conjecture: surfaces and counterexamples" +subject = "Differential geometry" +theorems = ["OAI.SharpNodal.Main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.NodalLength.Main" +reference_modules = 59 +reference_lean_bytes = 1484359 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1261 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13035 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/nodal-length/tests/Challenge.lean b/tasks/nodal-length/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..03ace4ffdc61e09751adb681344ec766029b2f06 --- /dev/null +++ b/tasks/nodal-length/tests/Challenge.lean @@ -0,0 +1,62 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped ContDiff Bundle ENNReal +open Bundle Manifold MeasureTheory + +namespace SharpNodal + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +variable {M : Type*} [MetricSpace M] [ChartedSpace Plane M] + [IsManifold 𝓘(ℝ, Plane) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Plane) x)] + +def coordinateMetric (x : M) (y : Plane) : Matrix (Fin 2) (Fin 2) ℝ := + fun i j => inner ℝ + (mfderiv 𝓘(ℝ, Plane) 𝓘(ℝ, Plane) (chartAt Plane x).symm y + (EuclideanSpace.single i 1)) + (mfderiv 𝓘(ℝ, Plane) 𝓘(ℝ, Plane) (chartAt Plane x).symm y + (EuclideanSpace.single j 1)) + +def coordinateDensity (x : M) (y : Plane) : ℝ := + Real.sqrt (coordinateMetric x y).det + +def coordPartial (f : Plane → ℝ) (i : Fin 2) (y : Plane) : ℝ := + fderiv ℝ f y (EuclideanSpace.single i 1) + +def laplaceBeltrami (u : M → ℝ) (x : M) : ℝ := + (coordinateDensity x (chartAt Plane x x))⁻¹ * + ∑ i : Fin 2, coordPartial (fun y => coordinateDensity x y * + ∑ j : Fin 2, ((coordinateMetric x y)⁻¹ i j) * + coordPartial (u ∘ (chartAt Plane x).symm) j y) i (chartAt Plane x x) + +def nodalSet (u : M → ℝ) : Set M := {x | u x = 0} + +def nodalLength (u : M → ℝ) : ℝ≥0∞ := + letI : MeasurableSpace M := borel M + letI : BorelSpace M := ⟨rfl⟩ + Measure.hausdorffMeasure 1 (nodalSet u) + +def MainStatement (M : Type*) [MetricSpace M] [ChartedSpace Plane M] + [IsManifold 𝓘(ℝ, Plane) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace 𝓘(ℝ, Plane) x)] : Prop := + ∃ C : ℝ, 0 ≤ C ∧ ∀ (lam : ℝ), 0 < lam → ∀ (u : M → ℝ), + ContMDiff 𝓘(ℝ, Plane) 𝓘(ℝ) ∞ u → u ≠ 0 → + (∀ x, -laplaceBeltrami u x = lam * u x) → + nodalLength u ≤ ENNReal.ofReal (C * Real.sqrt lam) + +theorem Main [CompactSpace M] [ConnectedSpace M] + [IsContMDiffRiemannianBundle 𝓘(ℝ,Plane) ∞ Plane + (fun x:M=>TangentSpace 𝓘(ℝ,Plane) x)] + [IsRiemannianManifold 𝓘(ℝ,Plane) M] : MainStatement M := by + sorry + +end SharpNodal + +end + +end OAI diff --git a/tasks/nodal-length/tests/grade.py b/tasks/nodal-length/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/nodal-length/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/nodal-length/tests/task.json b/tasks/nodal-length/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1c0dfd954b3efcb36b61a778d02cf66a6234cdce --- /dev/null +++ b/tasks/nodal-length/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "NodalLength", + "comparator": { + "theorem_names": [ + "OAI.SharpNodal.Main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12135 +} \ No newline at end of file diff --git a/tasks/nodal-length/tests/test.sh b/tasks/nodal-length/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/nodal-length/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/noiseless-regression/environment/Dockerfile b/tasks/noiseless-regression/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/noiseless-regression/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/noiseless-regression/environment/fetch_mathlib.sh b/tasks/noiseless-regression/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/noiseless-regression/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/noiseless-regression/environment/lake-manifest.json b/tasks/noiseless-regression/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/noiseless-regression/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/noiseless-regression/environment/lakefile.lean b/tasks/noiseless-regression/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/noiseless-regression/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/noiseless-regression/environment/lean_setup.sh b/tasks/noiseless-regression/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/noiseless-regression/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/noiseless-regression/environment/pack_submission.py b/tasks/noiseless-regression/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/noiseless-regression/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/noiseless-regression/instruction.md b/tasks/noiseless-regression/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b4320785b67648e823808215201f98343e1b2164 --- /dev/null +++ b/tasks/noiseless-regression/instruction.md @@ -0,0 +1,176 @@ +# openai/math challenge `NoiselessRegression` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `NoiselessRegression`, also at `/opt/openai-math/challenges/NoiselessRegression.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Finite-state Gaussian regression with noiseless labels and angular accuracy. +-/ + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace + +noncomputable section + +universe u + +namespace NoiselessRegression + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Learner (d M T : ℕ) (Ω : Type u) where + initialChoice : Ω → Bool × State M + transition : ℕ → Ω → State M → (Vector d × ℝ) → Bool × State M + output : ℕ → Ω → State M → UnitSphere d + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def start {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) (ω : Ω) : + RunStatus M := + let a := L.initialChoice ω + if a.1 then .inr (0, a.2) else .inl a.2 + +def run {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ → RunStatus M + | 0 => L.start ω + | n + 1 => + match L.run s ω x n with + | .inr done => .inr done + | .inl state => + if hn : n < T then + let row := x ⟨n, hn⟩ + let a := L.transition (n + 1) ω state (row, ⟪row, s.val⟫) + if a.1 then .inr (n + 1, a.2) else .inl a.2 + else .inl state + +def terminal {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ × State M := + match L.run s ω x T with + | .inl state => (T, state) + | .inr done => done + +def estimate {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : UnitSphere d := + let a := L.terminal s ω x + L.output a.1 ω a.2 + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) : Prop where + initialChoice : AEMeasurable L.initialChoice ρ + transition : ∀ t a, AEMeasurable (fun z : Ω × (Vector d × ℝ) => + L.transition t z.1 a z.2) (ρ.prod (observationReference d)) + output : ∀ t a, AEMeasurable (fun ω => L.output t ω a) ρ + fixed_experiment : ∀ s, AEMeasurable (fun z : Ω × Samples d T => + L.estimate s z.1 z.2) (ρ.prod (sampleLaw d T)) + uniform_experiment : AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => L.estimate z.1 z.2.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +def success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + (ρ.prod (sampleLaw d T)) + {z | angularError s (L.estimate s z.1 z.2) ≤ ε} + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end Learner + +def SubquadraticMemory : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ) ^ 2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Learner d (M d) T Ω, L.Admissible ρ → + (((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.uniformSuccess ρ ε ∨ + ∀ s, ((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.success ρ ε s) → + c * (d : ℝ) * Real.log (1 / ε) ≤ (T : ℝ) + +def FixedQuadraticMemory : Prop := + ∀ A₀ : ℝ, 0 < A₀ → ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, + ∀ d : ℕ, d₀ ≤ d → ∀ M T : ℕ, (M : ℝ) ≤ A₀ * (d : ℝ) ^ 2 → + ∀ ε : ℝ, 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Learner d M T Ω, L.Admissible ρ → + ((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.uniformSuccess ρ ε → + c * (d : ℝ) * Real.log (1 / ε) ≤ (T : ℝ) + +theorem main : SubquadraticMemory.{u} ∧ FixedQuadraticMemory.{u} := by + sorry + +end NoiselessRegression + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/NoiselessRegression.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.NoiselessRegression.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/noiseless-regression/solution/closure.txt b/tasks/noiseless-regression/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fae18d7030b8aac3c1256f19ee4b700fc62c941 --- /dev/null +++ b/tasks/noiseless-regression/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.Probability.GaussianRegression.AffineTubes +OAI.Probability.GaussianRegression.Blocks +OAI.Probability.GaussianRegression.Caps +OAI.Probability.GaussianRegression.Execution +OAI.Probability.GaussianRegression.GaussianKernel +OAI.Probability.GaussianRegression.Gram +OAI.Probability.GaussianRegression.InverseMoments +OAI.Probability.GaussianRegression.Main +OAI.Probability.GaussianRegression.Model +OAI.Probability.GaussianRegression.Nets +OAI.Probability.GaussianRegression.Observation +OAI.Probability.GaussianRegression.Precision +OAI.Probability.GaussianRegression.Projection +OAI.Probability.GaussianRegression.ReplicaMoments +OAI.Probability.GaussianRegression.Rotational +OAI.Probability.GaussianRegression.Smoothing +OAI.Probability.GaussianRegression.Sphere +OAI.Probability.GaussianRegression.Stream +OAI.Probability.GaussianRegression.Success +OAI.Probability.GaussianRegression.Support +OAI.Probability.GaussianRegression.Transfer +OAI.Probability.ProjectionMoments.Model diff --git a/tasks/noiseless-regression/solution/reference.py b/tasks/noiseless-regression/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/noiseless-regression/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/noiseless-regression/solution/solve.sh b/tasks/noiseless-regression/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..38d334d4701dc0b13f1b56c2cb948ad2e9d0dc02 --- /dev/null +++ b/tasks/noiseless-regression/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of NoiselessRegression, i.e. module OAI.Probability.GaussianRegression.Main and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.GaussianRegression.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of NoiselessRegression" diff --git a/tasks/noiseless-regression/task.toml b/tasks/noiseless-regression/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..44af47c460aea3641c5e6eda9e70209355cd1609 --- /dev/null +++ b/tasks/noiseless-regression/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/noiseless-regression" +version = "1.0.0" +description = "Prove NoiselessRegression (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/NoiselessRegression.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "NoiselessRegression" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.NoiselessRegression.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.GaussianRegression.Main" +reference_modules = 22 +reference_lean_bytes = 200854 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 758 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11880 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/noiseless-regression/tests/Challenge.lean b/tasks/noiseless-regression/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9643741f0fee5bf2cb1c2caffc63a9a4d36a6ef --- /dev/null +++ b/tasks/noiseless-regression/tests/Challenge.lean @@ -0,0 +1,125 @@ +import Mathlib + +namespace OAI + +/-! +Finite-state Gaussian regression with noiseless labels and angular accuracy. +-/ + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace + +noncomputable section + +universe u + +namespace NoiselessRegression + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Learner (d M T : ℕ) (Ω : Type u) where + initialChoice : Ω → Bool × State M + transition : ℕ → Ω → State M → (Vector d × ℝ) → Bool × State M + output : ℕ → Ω → State M → UnitSphere d + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def start {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) (ω : Ω) : + RunStatus M := + let a := L.initialChoice ω + if a.1 then .inr (0, a.2) else .inl a.2 + +def run {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ → RunStatus M + | 0 => L.start ω + | n + 1 => + match L.run s ω x n with + | .inr done => .inr done + | .inl state => + if hn : n < T then + let row := x ⟨n, hn⟩ + let a := L.transition (n + 1) ω state (row, ⟪row, s.val⟫) + if a.1 then .inr (n + 1, a.2) else .inl a.2 + else .inl state + +def terminal {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ × State M := + match L.run s ω x T with + | .inl state => (T, state) + | .inr done => done + +def estimate {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : UnitSphere d := + let a := L.terminal s ω x + L.output a.1 ω a.2 + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) : Prop where + initialChoice : AEMeasurable L.initialChoice ρ + transition : ∀ t a, AEMeasurable (fun z : Ω × (Vector d × ℝ) => + L.transition t z.1 a z.2) (ρ.prod (observationReference d)) + output : ∀ t a, AEMeasurable (fun ω => L.output t ω a) ρ + fixed_experiment : ∀ s, AEMeasurable (fun z : Ω × Samples d T => + L.estimate s z.1 z.2) (ρ.prod (sampleLaw d T)) + uniform_experiment : AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => L.estimate z.1 z.2.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +def success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + (ρ.prod (sampleLaw d T)) + {z | angularError s (L.estimate s z.1 z.2) ≤ ε} + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end Learner + +def SubquadraticMemory : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ) ^ 2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Learner d (M d) T Ω, L.Admissible ρ → + (((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.uniformSuccess ρ ε ∨ + ∀ s, ((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.success ρ ε s) → + c * (d : ℝ) * Real.log (1 / ε) ≤ (T : ℝ) + +def FixedQuadraticMemory : Prop := + ∀ A₀ : ℝ, 0 < A₀ → ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, + ∀ d : ℕ, d₀ ≤ d → ∀ M T : ℕ, (M : ℝ) ≤ A₀ * (d : ℝ) ^ 2 → + ∀ ε : ℝ, 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Learner d M T Ω, L.Admissible ρ → + ((2 : ℕ) / (3 : ℕ) : ℝ≥0∞) ≤ L.uniformSuccess ρ ε → + c * (d : ℝ) * Real.log (1 / ε) ≤ (T : ℝ) + +theorem main : SubquadraticMemory.{u} ∧ FixedQuadraticMemory.{u} := by + sorry + +end NoiselessRegression + +end + +end OAI diff --git a/tasks/noiseless-regression/tests/grade.py b/tasks/noiseless-regression/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/noiseless-regression/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/noiseless-regression/tests/task.json b/tasks/noiseless-regression/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6c42694716ef4aaf08e8df2a10d30b7fc51a9e10 --- /dev/null +++ b/tasks/noiseless-regression/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "NoiselessRegression", + "comparator": { + "theorem_names": [ + "OAI.NoiselessRegression.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10980 +} \ No newline at end of file diff --git a/tasks/noiseless-regression/tests/test.sh b/tasks/noiseless-regression/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/noiseless-regression/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/odd-kaplansky/environment/Dockerfile b/tasks/odd-kaplansky/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/odd-kaplansky/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/odd-kaplansky/environment/fetch_mathlib.sh b/tasks/odd-kaplansky/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/odd-kaplansky/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/odd-kaplansky/environment/lake-manifest.json b/tasks/odd-kaplansky/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/odd-kaplansky/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/odd-kaplansky/environment/lakefile.lean b/tasks/odd-kaplansky/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/odd-kaplansky/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/odd-kaplansky/environment/lean_setup.sh b/tasks/odd-kaplansky/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/odd-kaplansky/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/odd-kaplansky/environment/pack_submission.py b/tasks/odd-kaplansky/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/odd-kaplansky/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/odd-kaplansky/instruction.md b/tasks/odd-kaplansky/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9535b9b570f1c659140d17bbf6e5ab48b5a18334 --- /dev/null +++ b/tasks/odd-kaplansky/instruction.md @@ -0,0 +1,84 @@ +# openai/math challenge `OddKaplansky` (family 197) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 197 of the release, *Nonsofic groups and group-ring counterexamples* +(Algebra). The family as a whole: Constructs a finitely presented torsion-free nonsofic group whose group algebra over $\mathbb F_2$ is not directly finite, disproving Kaplansky's conjecture even without torsion. Companion examples give injective nonsurjective cellular automata on all configurations, refuting Gottschalk's surjunctivity conjecture. Another counterexample is an integral group-ring matrix, invertible over the rational group ring, with Fuglede–Kadison determinant strictly between zero and one, disproving the unrestricted Determinant Conjecture. + +The challenge is `OddKaplansky`, also at `/opt/openai-math/challenges/OddKaplansky.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace OddKaplansky + +@[irreducible] def sourceM : ℕ := Nat.choose 1200 600 +@[irreducible] def sourcePrime : ℕ := Nat.minFac ((Nat.factorial sourceM)^2 + 1) + +noncomputable section + +def cellular {K G : Type} [Field K] [Group G] + (d : MonoidAlgebra K G) (x : G → K) (g : G) : K := + d.coeff.sum fun u c => c * x (g * u) + +def MainClaim : Prop := + sourcePrime.Prime ∧ Odd sourcePrime ∧ + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K sourcePrime), + Fintype.card K = sourcePrime^4 ∧ + ∃ (G : Type) (_ : Group G) (_ : Group.FG G), + (∃ g : G, g ≠ 1 ∧ IsOfFinOrder g) ∧ + ∃ a b : MonoidAlgebra K G, + a * b = 1 ∧ b * a ≠ 1 ∧ + Function.Injective (cellular b) ∧ ¬ Function.Surjective (cellular b) + +theorem main_theorem : MainClaim := by + sorry + +end + +end OddKaplansky + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/OddKaplansky.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.OddKaplansky.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/odd-kaplansky/solution/closure.txt b/tasks/odd-kaplansky/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b769de7b6ece6ca8597900f8666fb28deddcce4 --- /dev/null +++ b/tasks/odd-kaplansky/solution/closure.txt @@ -0,0 +1,138 @@ +OAI.Algebra.OddKaplansky.AdmissibleCount +OAI.Algebra.OddKaplansky.Amalgam +OAI.Algebra.OddKaplansky.AmalgamExtras +OAI.Algebra.OddKaplansky.AugmentBound +OAI.Algebra.OddKaplansky.AugmentInverse +OAI.Algebra.OddKaplansky.Augmentation +OAI.Algebra.OddKaplansky.AugmentationMatrices +OAI.Algebra.OddKaplansky.BooleanPolynomial +OAI.Algebra.OddKaplansky.Cellular +OAI.Algebra.OddKaplansky.CoefficientOrder +OAI.Algebra.OddKaplansky.Compression +OAI.Algebra.OddKaplansky.Construction +OAI.Algebra.OddKaplansky.CosetCoordinates +OAI.Algebra.OddKaplansky.CosetGreedy +OAI.Algebra.OddKaplansky.CosetMatrix +OAI.Algebra.OddKaplansky.CosetRectangles +OAI.Algebra.OddKaplansky.CyclicCoset +OAI.Algebra.OddKaplansky.Diagrams +OAI.Algebra.OddKaplansky.FiniteChoice +OAI.Algebra.OddKaplansky.FiniteInverse +OAI.Algebra.OddKaplansky.Fourier +OAI.Algebra.OddKaplansky.FreeBlocks +OAI.Algebra.OddKaplansky.FreeShiftCount +OAI.Algebra.OddKaplansky.Gluing +OAI.Algebra.OddKaplansky.GraphEdges +OAI.Algebra.OddKaplansky.GraphNumerics +OAI.Algebra.OddKaplansky.GreedyColumns +OAI.Algebra.OddKaplansky.GreedyFormula +OAI.Algebra.OddKaplansky.GreedyInverse +OAI.Algebra.OddKaplansky.GreedyLift +OAI.Algebra.OddKaplansky.GreedyRectangle +OAI.Algebra.OddKaplansky.GreedyRing +OAI.Algebra.OddKaplansky.Heisenberg +OAI.Algebra.OddKaplansky.HeisenbergRepresentation +OAI.Algebra.OddKaplansky.HeisenbergSector +OAI.Algebra.OddKaplansky.HighCount +OAI.Algebra.OddKaplansky.IdempotentFree +OAI.Algebra.OddKaplansky.IncidenceCycles +OAI.Algebra.OddKaplansky.IndexCut +OAI.Algebra.OddKaplansky.LocalAlgebra +OAI.Algebra.OddKaplansky.LocalGroup +OAI.Algebra.OddKaplansky.Main +OAI.Algebra.OddKaplansky.MatrixActions +OAI.Algebra.OddKaplansky.MatrixUnits +OAI.Algebra.OddKaplansky.ModularGeneric +OAI.Algebra.OddKaplansky.ModularSource +OAI.Algebra.OddKaplansky.NilpotentBasis +OAI.Algebra.OddKaplansky.OrbitBlock +OAI.Algebra.OddKaplansky.OrbitSelection +OAI.Algebra.OddKaplansky.OrderedBlocks +OAI.Algebra.OddKaplansky.OrderedCoordinates +OAI.Algebra.OddKaplansky.OrderedGroup +OAI.Algebra.OddKaplansky.OrderedMatrices +OAI.Algebra.OddKaplansky.OrderedModular +OAI.Algebra.OddKaplansky.OrderedOrbits +OAI.Algebra.OddKaplansky.OrderedRectangles +OAI.Algebra.OddKaplansky.OrderedZero +OAI.Algebra.OddKaplansky.Parameters +OAI.Algebra.OddKaplansky.PolynomialGrid +OAI.Algebra.OddKaplansky.PrescribedGreedy +OAI.Algebra.OddKaplansky.PrescribedInverse +OAI.Algebra.OddKaplansky.PrescribedSector +OAI.Algebra.OddKaplansky.QuadraticTower +OAI.Algebra.OddKaplansky.ScalarAlgebra +OAI.Algebra.OddKaplansky.SectorConstruction +OAI.Algebra.OddKaplansky.SectorFourier +OAI.Algebra.OddKaplansky.SectorGreedy +OAI.Algebra.OddKaplansky.SectorGroup +OAI.Algebra.OddKaplansky.SectorOrbit +OAI.Algebra.OddKaplansky.SectorRectangles +OAI.Algebra.OddKaplansky.SectorStabilizer +OAI.Algebra.OddKaplansky.SimplexCount +OAI.Algebra.OddKaplansky.SourceFit +OAI.Algebra.OddKaplansky.SourceGluing +OAI.Algebra.OddKaplansky.SourceSector +OAI.Algebra.OddKaplansky.SquareCertificate +OAI.Algebra.OddKaplansky.SquareConstruction +OAI.Algebra.OddKaplansky.Transfer +OAI.Algebra.OddKaplansky.WeightedGram +OAI.Algebra.OddKaplansky.WeightedProjection +OAI.Algebra.OddKaplansky.WreathActions +OAI.Algebra.OddKaplansky.WreathBasis +OAI.Algebra.OddKaplansky.WreathFourier +OAI.Algebra.OddKaplansky.WreathLinear +OAI.Algebra.OddKaplansky.WreathMultiply +OAI.Algebra.OddKaplansky.WreathRepresentation +OAI.RingTheory.DirectFiniteness.AffineLines +OAI.RingTheory.DirectFiniteness.Alteration +OAI.RingTheory.DirectFiniteness.CandidateBounds +OAI.RingTheory.DirectFiniteness.CandidateClassification +OAI.RingTheory.DirectFiniteness.CandidateCounting +OAI.RingTheory.DirectFiniteness.CandidateDependencies +OAI.RingTheory.DirectFiniteness.CandidateGeometry +OAI.RingTheory.DirectFiniteness.CandidateModel +OAI.RingTheory.DirectFiniteness.CandidateRelations +OAI.RingTheory.DirectFiniteness.CyclicLabels +OAI.RingTheory.DirectFiniteness.DirectionFrame +OAI.RingTheory.DirectFiniteness.DirectionSpaces +OAI.RingTheory.DirectFiniteness.EventLoad +OAI.RingTheory.DirectFiniteness.FieldExtensions +OAI.RingTheory.DirectFiniteness.FiniteAffine +OAI.RingTheory.DirectFiniteness.FiniteParameters +OAI.RingTheory.DirectFiniteness.FrameExistence +OAI.RingTheory.DirectFiniteness.FrameTransport +OAI.RingTheory.DirectFiniteness.HoleEvents +OAI.RingTheory.DirectFiniteness.HoleExistence +OAI.RingTheory.DirectFiniteness.HoleNumerics +OAI.RingTheory.DirectFiniteness.HoleSelection +OAI.RingTheory.DirectFiniteness.LabelSupport +OAI.RingTheory.DirectFiniteness.LexicographicOrder +OAI.RingTheory.DirectFiniteness.Model +OAI.RingTheory.DirectFiniteness.ModelPartition +OAI.RingTheory.DirectFiniteness.OneCandidateCounting +OAI.RingTheory.DirectFiniteness.ParameterBounds +OAI.RingTheory.DirectFiniteness.PartialPartition +OAI.RingTheory.DirectFiniteness.PlaneOperators +OAI.RingTheory.DirectFiniteness.PrescribedFields +OAI.RingTheory.DirectFiniteness.PrescribedParameters +OAI.RingTheory.DirectFiniteness.PrescribedSubfield +OAI.RingTheory.DirectFiniteness.PrimeCertificate +OAI.RingTheory.DirectFiniteness.QuotientField +OAI.RingTheory.DirectFiniteness.ReducedWalks +OAI.RingTheory.DirectFiniteness.ReplacementGeometry +OAI.RingTheory.DirectFiniteness.ReplacementPolygon +OAI.RingTheory.DirectFiniteness.ShortIndependence +OAI.RingTheory.DirectFiniteness.SlabAssembly +OAI.RingTheory.DirectFiniteness.SlabAvoidance +OAI.RingTheory.DirectFiniteness.SlabEvents +OAI.RingTheory.DirectFiniteness.SlabHoleEvents +OAI.RingTheory.DirectFiniteness.SlabKeys +OAI.RingTheory.DirectFiniteness.SlabLoad +OAI.RingTheory.DirectFiniteness.SlabNumerics +OAI.RingTheory.DirectFiniteness.SlabPartition +OAI.RingTheory.DirectFiniteness.SlabPatch +OAI.RingTheory.DirectFiniteness.TradeDegree +OAI.RingTheory.DirectFiniteness.TradeFamily +OAI.RingTheory.DirectFiniteness.TradeLines +OAI.RingTheory.DirectFiniteness.TradePolygon diff --git a/tasks/odd-kaplansky/solution/reference.py b/tasks/odd-kaplansky/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/odd-kaplansky/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/odd-kaplansky/solution/solve.sh b/tasks/odd-kaplansky/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6ee746e18ecdea14e8822ac91a1ec4f76def5315 --- /dev/null +++ b/tasks/odd-kaplansky/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of OddKaplansky, i.e. module OAI.Algebra.OddKaplansky.Main and the +# 138 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.OddKaplansky.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of OddKaplansky" diff --git a/tasks/odd-kaplansky/task.toml b/tasks/odd-kaplansky/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9212da314b915b247886357c8f4ec768bdffb131 --- /dev/null +++ b/tasks/odd-kaplansky/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/odd-kaplansky" +version = "1.0.0" +description = "Prove OddKaplansky (openai/math family 197: Nonsofic groups and group-ring counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/OddKaplansky.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "OddKaplansky" +family = "197" +family_title = "Nonsofic groups and group-ring counterexamples" +subject = "Algebra" +theorems = ["OAI.OddKaplansky.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.OddKaplansky.Main" +reference_modules = 138 +reference_lean_bytes = 832311 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1336 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12449 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/odd-kaplansky/tests/Challenge.lean b/tasks/odd-kaplansky/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6599090468963d820e62f8313fb66233f6d55bfa --- /dev/null +++ b/tasks/odd-kaplansky/tests/Challenge.lean @@ -0,0 +1,33 @@ +import Mathlib + +namespace OAI + +namespace OddKaplansky + +@[irreducible] def sourceM : ℕ := Nat.choose 1200 600 +@[irreducible] def sourcePrime : ℕ := Nat.minFac ((Nat.factorial sourceM)^2 + 1) + +noncomputable section + +def cellular {K G : Type} [Field K] [Group G] + (d : MonoidAlgebra K G) (x : G → K) (g : G) : K := + d.coeff.sum fun u c => c * x (g * u) + +def MainClaim : Prop := + sourcePrime.Prime ∧ Odd sourcePrime ∧ + ∃ (K : Type) (_ : Field K) (_ : Fintype K) (_ : CharP K sourcePrime), + Fintype.card K = sourcePrime^4 ∧ + ∃ (G : Type) (_ : Group G) (_ : Group.FG G), + (∃ g : G, g ≠ 1 ∧ IsOfFinOrder g) ∧ + ∃ a b : MonoidAlgebra K G, + a * b = 1 ∧ b * a ≠ 1 ∧ + Function.Injective (cellular b) ∧ ¬ Function.Surjective (cellular b) + +theorem main_theorem : MainClaim := by + sorry + +end + +end OddKaplansky + +end OAI diff --git a/tasks/odd-kaplansky/tests/grade.py b/tasks/odd-kaplansky/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/odd-kaplansky/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/odd-kaplansky/tests/task.json b/tasks/odd-kaplansky/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9ed490b96788296567fedfc3963d4c392e449272 --- /dev/null +++ b/tasks/odd-kaplansky/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "OddKaplansky", + "comparator": { + "theorem_names": [ + "OAI.OddKaplansky.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11549 +} \ No newline at end of file diff --git a/tasks/odd-kaplansky/tests/test.sh b/tasks/odd-kaplansky/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/odd-kaplansky/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/one-way-liveness/environment/Dockerfile b/tasks/one-way-liveness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/one-way-liveness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/one-way-liveness/environment/fetch_mathlib.sh b/tasks/one-way-liveness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/one-way-liveness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/one-way-liveness/environment/lake-manifest.json b/tasks/one-way-liveness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/one-way-liveness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/one-way-liveness/environment/lakefile.lean b/tasks/one-way-liveness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/one-way-liveness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/one-way-liveness/environment/lean_setup.sh b/tasks/one-way-liveness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/one-way-liveness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/one-way-liveness/environment/pack_submission.py b/tasks/one-way-liveness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/one-way-liveness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/one-way-liveness/instruction.md b/tasks/one-way-liveness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d5368a2478c01027389737a447002ce673f40114 --- /dev/null +++ b/tasks/one-way-liveness/instruction.md @@ -0,0 +1,156 @@ +# openai/math challenge `OneWayLiveness` (family 129) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 129 of the release, *Exponential state costs for two-way automata* +(Theoretical computer science). The family as a whole: Proves exponential lower bounds both for complementing two-way nondeterministic finite automata and for simulating one-way nondeterministic automata by two-way deterministic ones. The latter resolves the Sakoda–Sipser state-succinctness conjecture over growing finite alphabets; both results rule out polynomial state bounds independent of alphabet size. + +The challenge is `OneWayLiveness`, also at `/opt/openai-math/challenges/OneWayLiveness.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace OneWayLiveness + +@[ext] structure BRel (H : Type*) where + holds : H → H → Prop + +namespace BRel +variable {H : Type*} +instance : One (BRel H) := ⟨⟨Eq⟩⟩ +instance : Mul (BRel H) := ⟨fun a b => ⟨fun x z => ∃ y, a.holds x y ∧ b.holds y z⟩⟩ +instance : Monoid (BRel H) where + mul_assoc a b c := by + ext x z + change (∃ y, (∃ w, a.holds x w ∧ b.holds w y) ∧ c.holds y z) ↔ + ∃ w, a.holds x w ∧ ∃ y, b.holds w y ∧ c.holds y z + aesop + one_mul a := by ext x z; change (∃ y, x = y ∧ a.holds y z) ↔ a.holds x z; simp + mul_one a := by ext x z; change (∃ y, a.holds x y ∧ y = z) ↔ a.holds x z; simp + +/-- Nonemptiness is the existence of a path through the word's ordered product. -/ +def live (w : List (BRel H)) : Prop := ∃ x y, w.prod.holds x y +end BRel + +abbrev Alphabet (h : ℕ) := BRel (Fin h) +def OWL (h : ℕ) : Set (List (Alphabet h)) := {w | BRel.live w} + +inductive Symbol (Alpha : Type*) where + | left : Symbol Alpha + | letter : Alpha → Symbol Alpha + | right : Symbol Alpha + +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.Rel : Move → ℕ → ℕ → Prop + | .left, i, j => j + 1 = i + | .stay, i, j => j = i + | .right, i, j => j = i + 1 + +/-- The finite word including both endmarkers. -/ +def scanned {Alpha : Type*} (w : List Alpha) (i : Fin (w.length + 2)) : Symbol Alpha := + if h0 : i.val = 0 then .left + else if hi : i.val < w.length + 1 then .letter (w[i.val - 1]'(by omega)) + else .right + +abbrev Configuration {Alpha : Type*} (w : List Alpha) (n : ℕ) := Fin (w.length + 2) × Fin n + +structure DMachine (Alpha : Type*) (s : ℕ) where + initial : Fin s + accepting : Set (Fin s) + transition : Fin s → Symbol Alpha → Option (Fin s × Move) + left_boundary : ∀ q q', transition q .left ≠ some (q', .left) + right_boundary : ∀ q q', transition q .right ≠ some (q', .right) + +structure NMachine (Alpha : Type*) (n : ℕ) where + initial : Fin n + accepting : Set (Fin n) + transition : Fin n → Symbol Alpha → Set (Fin n × Move) + left_boundary : ∀ q q', (q', .left) ∉ transition q .left + right_boundary : ∀ q q', (q', .right) ∉ transition q .right + +def DMachine.Step {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) (w : List Alpha) + (c c' : Configuration w s) : Prop := + ∃ d, M.transition c.2 (scanned w c.1) = some (c'.2, d) ∧ d.Rel c.1.val c'.1.val + +def NMachine.Step {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) (w : List Alpha) + (c c' : Configuration w n) : Prop := + ∃ d, (c'.2, d) ∈ M.transition c.2 (scanned w c.1) ∧ d.Rel c.1.val c'.1.val + +/-- The positive convention explicitly excludes a length-zero computation. -/ +def FiniteRun {C : Type*} (positive : Bool) (step : C → C → Prop) (c c' : C) : Prop := + if positive then Relation.TransGen step c c' else Relation.ReflTransGen step c c' + +def DMachine.Accepts {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) + (positive : Bool) (w : List Alpha) : Prop := + ∃ c, FiniteRun positive (M.Step w) (⟨0, by omega⟩, M.initial) c ∧ c.2 ∈ M.accepting + +def NMachine.Accepts {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) + (positive : Bool) (w : List Alpha) : Prop := + ∃ c, FiniteRun positive (M.Step w) (⟨0, by omega⟩, M.initial) c ∧ c.2 ∈ M.accepting + +def NMachine.NoLeft {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) : Prop := + ∀ q a q', (q', Move.left) ∉ M.transition q a + +def NMachine.Recognizes {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) + (positive : Bool) (L : Set (List Alpha)) : Prop := ∀ w, M.Accepts positive w ↔ w ∈ L + +def DMachine.Recognizes {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) + (positive : Bool) (L : Set (List Alpha)) : Prop := ∀ w, M.Accepts positive w ↔ w ∈ L + +theorem main_theorem (h : ℕ) (hh : 2 ≤ h) : + (∃ N : NMachine (Alphabet h) (h + 3), N.NoLeft ∧ + ∀ positive : Bool, N.Recognizes positive (OWL h)) ∧ + (∀ (positive : Bool) (s : ℕ) (D : DMachine (Alphabet h) s), + D.Recognizes positive (OWL h) → + 2 ^ ((h - 2) / 31) ≤ 4 * (s + if positive then 2 else 1) ^ 2) := by + sorry + +end OneWayLiveness + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/OneWayLiveness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.OneWayLiveness.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/one-way-liveness/solution/closure.txt b/tasks/one-way-liveness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2bf5fe1253f857e11b0ab8214d3a8072cac1132 --- /dev/null +++ b/tasks/one-way-liveness/solution/closure.txt @@ -0,0 +1,16 @@ +OAI.Combinatorics.Automata.Cells +OAI.Combinatorics.Automata.Corners +OAI.Combinatorics.Automata.Diagram +OAI.Combinatorics.Automata.Diagrams +OAI.Combinatorics.Automata.Main +OAI.Combinatorics.Automata.Model +OAI.Combinatorics.Automata.Network +OAI.Combinatorics.Automata.Normalization +OAI.Combinatorics.Automata.PathNFA +OAI.Combinatorics.Automata.Rank +OAI.Combinatorics.Automata.RankLoss +OAI.Combinatorics.Automata.Recognition +OAI.Combinatorics.Automata.Relations +OAI.Combinatorics.Automata.Syntactic +OAI.Combinatorics.Automata.Tours +OAI.Combinatorics.Automata.Wiring diff --git a/tasks/one-way-liveness/solution/reference.py b/tasks/one-way-liveness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/one-way-liveness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/one-way-liveness/solution/solve.sh b/tasks/one-way-liveness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f45c46cc4dc47f2c6caaac84016123c1eba43023 --- /dev/null +++ b/tasks/one-way-liveness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of OneWayLiveness, i.e. module OAI.Combinatorics.Automata.Main and the +# 16 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Automata.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of OneWayLiveness" diff --git a/tasks/one-way-liveness/task.toml b/tasks/one-way-liveness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd7c04ce2451b48e10f74518f3a43d4e6fe7b6b3 --- /dev/null +++ b/tasks/one-way-liveness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/one-way-liveness" +version = "1.0.0" +description = "Prove OneWayLiveness (openai/math family 129: Exponential state costs for two-way automata) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/OneWayLiveness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "OneWayLiveness" +family = "129" +family_title = "Exponential state costs for two-way automata" +subject = "Theoretical computer science" +theorems = ["OAI.OneWayLiveness.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Automata.Main" +reference_modules = 16 +reference_lean_bytes = 172519 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 624 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11855 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/one-way-liveness/tests/Challenge.lean b/tasks/one-way-liveness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b1895c1f64b7284fe7f920d9967bd236bd49ea67 --- /dev/null +++ b/tasks/one-way-liveness/tests/Challenge.lean @@ -0,0 +1,105 @@ +import Mathlib + +namespace OAI + +namespace OneWayLiveness + +@[ext] structure BRel (H : Type*) where + holds : H → H → Prop + +namespace BRel +variable {H : Type*} +instance : One (BRel H) := ⟨⟨Eq⟩⟩ +instance : Mul (BRel H) := ⟨fun a b => ⟨fun x z => ∃ y, a.holds x y ∧ b.holds y z⟩⟩ +instance : Monoid (BRel H) where + mul_assoc a b c := by + ext x z + change (∃ y, (∃ w, a.holds x w ∧ b.holds w y) ∧ c.holds y z) ↔ + ∃ w, a.holds x w ∧ ∃ y, b.holds w y ∧ c.holds y z + aesop + one_mul a := by ext x z; change (∃ y, x = y ∧ a.holds y z) ↔ a.holds x z; simp + mul_one a := by ext x z; change (∃ y, a.holds x y ∧ y = z) ↔ a.holds x z; simp + +/-- Nonemptiness is the existence of a path through the word's ordered product. -/ +def live (w : List (BRel H)) : Prop := ∃ x y, w.prod.holds x y +end BRel + +abbrev Alphabet (h : ℕ) := BRel (Fin h) +def OWL (h : ℕ) : Set (List (Alphabet h)) := {w | BRel.live w} + +inductive Symbol (Alpha : Type*) where + | left : Symbol Alpha + | letter : Alpha → Symbol Alpha + | right : Symbol Alpha + +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.Rel : Move → ℕ → ℕ → Prop + | .left, i, j => j + 1 = i + | .stay, i, j => j = i + | .right, i, j => j = i + 1 + +/-- The finite word including both endmarkers. -/ +def scanned {Alpha : Type*} (w : List Alpha) (i : Fin (w.length + 2)) : Symbol Alpha := + if h0 : i.val = 0 then .left + else if hi : i.val < w.length + 1 then .letter (w[i.val - 1]'(by omega)) + else .right + +abbrev Configuration {Alpha : Type*} (w : List Alpha) (n : ℕ) := Fin (w.length + 2) × Fin n + +structure DMachine (Alpha : Type*) (s : ℕ) where + initial : Fin s + accepting : Set (Fin s) + transition : Fin s → Symbol Alpha → Option (Fin s × Move) + left_boundary : ∀ q q', transition q .left ≠ some (q', .left) + right_boundary : ∀ q q', transition q .right ≠ some (q', .right) + +structure NMachine (Alpha : Type*) (n : ℕ) where + initial : Fin n + accepting : Set (Fin n) + transition : Fin n → Symbol Alpha → Set (Fin n × Move) + left_boundary : ∀ q q', (q', .left) ∉ transition q .left + right_boundary : ∀ q q', (q', .right) ∉ transition q .right + +def DMachine.Step {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) (w : List Alpha) + (c c' : Configuration w s) : Prop := + ∃ d, M.transition c.2 (scanned w c.1) = some (c'.2, d) ∧ d.Rel c.1.val c'.1.val + +def NMachine.Step {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) (w : List Alpha) + (c c' : Configuration w n) : Prop := + ∃ d, (c'.2, d) ∈ M.transition c.2 (scanned w c.1) ∧ d.Rel c.1.val c'.1.val + +/-- The positive convention explicitly excludes a length-zero computation. -/ +def FiniteRun {C : Type*} (positive : Bool) (step : C → C → Prop) (c c' : C) : Prop := + if positive then Relation.TransGen step c c' else Relation.ReflTransGen step c c' + +def DMachine.Accepts {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) + (positive : Bool) (w : List Alpha) : Prop := + ∃ c, FiniteRun positive (M.Step w) (⟨0, by omega⟩, M.initial) c ∧ c.2 ∈ M.accepting + +def NMachine.Accepts {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) + (positive : Bool) (w : List Alpha) : Prop := + ∃ c, FiniteRun positive (M.Step w) (⟨0, by omega⟩, M.initial) c ∧ c.2 ∈ M.accepting + +def NMachine.NoLeft {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) : Prop := + ∀ q a q', (q', Move.left) ∉ M.transition q a + +def NMachine.Recognizes {Alpha : Type*} {n : ℕ} (M : NMachine Alpha n) + (positive : Bool) (L : Set (List Alpha)) : Prop := ∀ w, M.Accepts positive w ↔ w ∈ L + +def DMachine.Recognizes {Alpha : Type*} {s : ℕ} (M : DMachine Alpha s) + (positive : Bool) (L : Set (List Alpha)) : Prop := ∀ w, M.Accepts positive w ↔ w ∈ L + +theorem main_theorem (h : ℕ) (hh : 2 ≤ h) : + (∃ N : NMachine (Alphabet h) (h + 3), N.NoLeft ∧ + ∀ positive : Bool, N.Recognizes positive (OWL h)) ∧ + (∀ (positive : Bool) (s : ℕ) (D : DMachine (Alphabet h) s), + D.Recognizes positive (OWL h) → + 2 ^ ((h - 2) / 31) ≤ 4 * (s + if positive then 2 else 1) ^ 2) := by + sorry + +end OneWayLiveness + +end OAI diff --git a/tasks/one-way-liveness/tests/grade.py b/tasks/one-way-liveness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/one-way-liveness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/one-way-liveness/tests/task.json b/tasks/one-way-liveness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8f576b02289bcd97c4d9438f62557a30830441b6 --- /dev/null +++ b/tasks/one-way-liveness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "OneWayLiveness", + "comparator": { + "theorem_names": [ + "OAI.OneWayLiveness.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10955 +} \ No newline at end of file diff --git a/tasks/one-way-liveness/tests/test.sh b/tasks/one-way-liveness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/one-way-liveness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/optimal-max-cut/environment/Dockerfile b/tasks/optimal-max-cut/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/optimal-max-cut/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/optimal-max-cut/environment/fetch_mathlib.sh b/tasks/optimal-max-cut/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/optimal-max-cut/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/optimal-max-cut/environment/lake-manifest.json b/tasks/optimal-max-cut/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/optimal-max-cut/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/optimal-max-cut/environment/lakefile.lean b/tasks/optimal-max-cut/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/optimal-max-cut/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/optimal-max-cut/environment/lean_setup.sh b/tasks/optimal-max-cut/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/optimal-max-cut/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/optimal-max-cut/environment/pack_submission.py b/tasks/optimal-max-cut/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/optimal-max-cut/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/optimal-max-cut/instruction.md b/tasks/optimal-max-cut/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5cd86b65b0d0b25b4897cb700ba7f47a4006f647 --- /dev/null +++ b/tasks/optimal-max-cut/instruction.md @@ -0,0 +1,207 @@ +# openai/math challenge `OptimalMaxCut` (family 102) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 102 of the release, *The Unique Games Conjecture and optimal approximation thresholds* +(Theoretical computer science). The family as a whole: Proves Khot's Unique Games Conjecture. Independent direct reductions also establish NP-hardness, on unweighted graphs, of approximation beyond the Goemans–Williamson ratio for Max-Cut, below factor two for Vertex Cover, and within any fixed constant factor for Min-UnCut and directed feedback vertex set. These direct proofs use established PCP and Label Cover hardness results. + +The challenge is `OptimalMaxCut`, also at `/opt/openai-math/challenges/OptimalMaxCut.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MaxCutGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +/-- An ordinary conjunction of three-slot clauses with sparse variable names. +Repeated names and repeated literals are permitted in every clause. -/ +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end MaxCutGames.BinaryFormula + +namespace MaxCutGames.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +/-- Prefix-free framing on the two-symbol input alphabet. -/ +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +/-- Equality with the canonical digits rejects alternate padded encodings. -/ +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +/-- Fuel bounds the number of clause iterations, not the size of any name. -/ +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end MaxCutGames.BinaryEncoding + +namespace OptimalMaxCut + +open scoped BigOperators + +/-- The exact Goemans–Williamson ratio, as an infimum over -1 ≤ ρ < 1. -/ +noncomputable def alphaGW : ℝ := + sInf ((fun ρ : ℝ => 2 * Real.arccos ρ / (Real.pi * (1 - ρ))) '' + Set.Ico (-1 : ℝ) 1) + +/-- The ordinary binary 3SAT language, including rejection of malformed words. -/ +def binary3SAT (input : List Bool) : Prop := + ∃ formula, MaxCutGames.BinaryEncoding.decodeFormula input = some formula ∧ + formula.Satisfiable + +/-- A finite simple unweighted graph with its full Boolean adjacency table. -/ +structure Graph where + vertices : ℕ + adj : Fin vertices → Fin vertices → Bool + symmetric : ∀ u v, adj u v = adj v u + loopless : ∀ u, adj u u = false + +/-- Each unordered distinct edge crossing the cut is counted exactly once. -/ +def Graph.cutSize (G : Graph) (cut : Fin G.vertices → Bool) : ℕ := + ∑ u : Fin G.vertices, ∑ v : Fin G.vertices, + if u < v ∧ G.adj u v = true ∧ cut u ≠ cut v then 1 else 0 + +/-- The maximum over all Boolean cuts of the finite vertex set. -/ +def Graph.maxCut (G : Graph) : ℕ := + (Finset.univ.image G.cutSize).sup id + +/-- The positive integer scale Q is part of the output. It need not equal the +number of graph edges. -/ +structure ScaledGraph where + graph : Graph + scale : ℕ + scale_pos : 0 < scale + +/-- Canonical delimited binary vertex count and scale, followed by the full +adjacency table in lexicographic order. -/ +def ScaledGraph.bits (G : ScaledGraph) : List Bool := + MaxCutGames.BinaryEncoding.nameBits G.graph.vertices ++ + MaxCutGames.BinaryEncoding.nameBits G.scale ++ + (List.finRange G.graph.vertices).flatMap (fun u => + (List.finRange G.graph.vertices).map (fun v => G.graph.adj u v)) + +/-- The rational gap bounds and the finite machine are fixed before the input. +The bounds compare the maximum cut divided by the positive output scale. -/ +structure GapReduction (α : ℝ) where + yesBound : ℚ + noBound : ℚ + yes_pos : 0 < yesBound + no_nonneg : 0 ≤ noBound + gap : (noBound : ℝ) < α * (yesBound : ℝ) + construct : List Bool → ScaledGraph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + ScaledGraph.bits construct + finiteAlphabet : ∀ k, Finite (computation.tm.Γ k) + completeness : ∀ input, binary3SAT input → + (yesBound : ℝ) ≤ ((construct input).graph.maxCut : ℝ) / (construct input).scale + soundness : ∀ input, ¬ binary3SAT input → + ((construct input).graph.maxCut : ℝ) / (construct input).scale ≤ (noBound : ℝ) + +def MainStatement : Prop := + ∀ α : ℝ, alphaGW < α → α ≤ 1 → Nonempty (GapReduction α) + +end OptimalMaxCut + +theorem OptimalMaxCut.main : OptimalMaxCut.MainStatement := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/OptimalMaxCut.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.OptimalMaxCut.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/optimal-max-cut/solution/closure.txt b/tasks/optimal-max-cut/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c41066d7004069fe643c039763377b5c94c0c5a --- /dev/null +++ b/tasks/optimal-max-cut/solution/closure.txt @@ -0,0 +1,372 @@ +OAI.Computability.MaxCut.Analysis.CubeEquiv +OAI.Computability.MaxCut.Analysis.CubePerm +OAI.Computability.MaxCut.Arithmetic.GridComputer +OAI.Computability.MaxCut.Arithmetic.GridWeight +OAI.Computability.MaxCut.Arithmetic.Prime +OAI.Computability.MaxCut.Encoding.ActualAdviceSampling +OAI.Computability.MaxCut.Encoding.ActualAdviceUpper +OAI.Computability.MaxCut.Encoding.ActualEvents +OAI.Computability.MaxCut.Encoding.ActualGoodRows +OAI.Computability.MaxCut.Encoding.ActualInputRows +OAI.Computability.MaxCut.Encoding.AdjacencyBits +OAI.Computability.MaxCut.Encoding.AdviceFibers +OAI.Computability.MaxCut.Encoding.AdviceLaw +OAI.Computability.MaxCut.Encoding.AffineWitnessFirstBit +OAI.Computability.MaxCut.Encoding.BinaryCoordinates +OAI.Computability.MaxCut.Encoding.BinaryParityReduction +OAI.Computability.MaxCut.Encoding.BinaryRowTransport +OAI.Computability.MaxCut.Encoding.Bit +OAI.Computability.MaxCut.Encoding.BitCube +OAI.Computability.MaxCut.Encoding.BitPairWeightQ +OAI.Computability.MaxCut.Encoding.BitValue +OAI.Computability.MaxCut.Encoding.Decoder +OAI.Computability.MaxCut.Encoding.DimensionSelection +OAI.Computability.MaxCut.Encoding.Encoding +OAI.Computability.MaxCut.Encoding.Encoding2 +OAI.Computability.MaxCut.Encoding.FormulaEncoding +OAI.Computability.MaxCut.Encoding.GameDecoder +OAI.Computability.MaxCut.Encoding.GameEncodingSize +OAI.Computability.MaxCut.Encoding.InputData +OAI.Computability.MaxCut.Encoding.InputEncoding +OAI.Computability.MaxCut.Encoding.KMSKernelOrbits +OAI.Computability.MaxCut.Encoding.KMSKernelOrbitsFourier +OAI.Computability.MaxCut.Encoding.MatrixCoordinates +OAI.Computability.MaxCut.Encoding.MatrixGap +OAI.Computability.MaxCut.Encoding.MatrixGapInverse +OAI.Computability.MaxCut.Encoding.NameCompaction +OAI.Computability.MaxCut.Encoding.PaddedLaw +OAI.Computability.MaxCut.Encoding.PortTableEncoding +OAI.Computability.MaxCut.Encoding.PositiveMultiplier +OAI.Computability.MaxCut.Encoding.PrivateFourier +OAI.Computability.MaxCut.Encoding.SelectedPolicies +OAI.Computability.MaxCut.Encoding.Serialization +OAI.Computability.MaxCut.Encoding.SparseLaw +OAI.Computability.MaxCut.Encoding.SubdivisionEncoding +OAI.Computability.MaxCut.Encoding.SurrogateFibers +OAI.Computability.MaxCut.Encoding.TableKeys +OAI.Computability.MaxCut.Encoding.TableKeysAddressGame +OAI.Computability.MaxCut.Encoding.TableKeysCompleteness +OAI.Computability.MaxCut.Encoding.TableKeysGame +OAI.Computability.MaxCut.Encoding.ThreeBitTest +OAI.Computability.MaxCut.Encoding.TransferredDecoding +OAI.Computability.MaxCut.Encoding.VerticesBits +OAI.Computability.MaxCut.Encoding.VisibleTransfer +OAI.Computability.MaxCut.Estimates.Anchor +OAI.Computability.MaxCut.Estimates.Basic +OAI.Computability.MaxCut.Estimates.Clip +OAI.Computability.MaxCut.Estimates.CorrectSum +OAI.Computability.MaxCut.Estimates.Degree +OAI.Computability.MaxCut.Estimates.Density +OAI.Computability.MaxCut.Estimates.Dictator +OAI.Computability.MaxCut.Estimates.Divides +OAI.Computability.MaxCut.Estimates.ListSum +OAI.Computability.MaxCut.Estimates.Param +OAI.Computability.MaxCut.Estimates.Put +OAI.Computability.MaxCut.Estimates.Rename +OAI.Computability.MaxCut.Estimates.Sample +OAI.Computability.MaxCut.Estimates.Vec +OAI.Computability.MaxCut.Estimates.VecEquivSymmVal +OAI.Computability.MaxCut.Gadgets.Polynomial +OAI.Computability.MaxCut.Gadgets.ValuePolynomial +OAI.Computability.MaxCut.Games.A1Reduction +OAI.Computability.MaxCut.Games.A4IndexCount +OAI.Computability.MaxCut.Games.A5Induction +OAI.Computability.MaxCut.Games.A5ReverseIndex +OAI.Computability.MaxCut.Games.A5Scalar +OAI.Computability.MaxCut.Games.ActualAdviceStochasticBridge +OAI.Computability.MaxCut.Games.ActualCompleteness +OAI.Computability.MaxCut.Games.AddressGame +OAI.Computability.MaxCut.Games.AddressOdometerSchedule +OAI.Computability.MaxCut.Games.AddressTupleLoaded +OAI.Computability.MaxCut.Games.AdviceImageLaw +OAI.Computability.MaxCut.Games.AffineWitness +OAI.Computability.MaxCut.Games.AffineWitnessFiniteDensity +OAI.Computability.MaxCut.Games.AnswerBridge +OAI.Computability.MaxCut.Games.BaseDetection +OAI.Computability.MaxCut.Games.Basic +OAI.Computability.MaxCut.Games.Basic2 +OAI.Computability.MaxCut.Games.BlockRestriction +OAI.Computability.MaxCut.Games.CanonicalAddress +OAI.Computability.MaxCut.Games.CanonicalWordTemplate +OAI.Computability.MaxCut.Games.Clone100Counting +OAI.Computability.MaxCut.Games.CloneTable +OAI.Computability.MaxCut.Games.Concatenation +OAI.Computability.MaxCut.Games.CoordinateTransport +OAI.Computability.MaxCut.Games.Deletion +OAI.Computability.MaxCut.Games.Derivatives +OAI.Computability.MaxCut.Games.DyadicErrors +OAI.Computability.MaxCut.Games.EquationLookup +OAI.Computability.MaxCut.Games.FinalCNFHeader +OAI.Computability.MaxCut.Games.FinalCNFOutput +OAI.Computability.MaxCut.Games.FinalCNFPattern +OAI.Computability.MaxCut.Games.FinalCNFStream +OAI.Computability.MaxCut.Games.FinalParameters +OAI.Computability.MaxCut.Games.FinishBounds +OAI.Computability.MaxCut.Games.FiniteFieldChoice +OAI.Computability.MaxCut.Games.FiniteNoise +OAI.Computability.MaxCut.Games.GamesAdapter +OAI.Computability.MaxCut.Games.GapSemantics +OAI.Computability.MaxCut.Games.GenericPolynomial +OAI.Computability.MaxCut.Games.GraphIterationBounds +OAI.Computability.MaxCut.Games.HarmonicLoss +OAI.Computability.MaxCut.Games.Identities +OAI.Computability.MaxCut.Games.Incidence +OAI.Computability.MaxCut.Games.IncidenceExtraction +OAI.Computability.MaxCut.Games.IncidenceGap +OAI.Computability.MaxCut.Games.Information +OAI.Computability.MaxCut.Games.KMSAnalyticFrequencyShift +OAI.Computability.MaxCut.Games.KMSAnalyticHybridEnergyImageSplit +OAI.Computability.MaxCut.Games.KMSAnalyticHybridEnergyImageTransportCore +OAI.Computability.MaxCut.Games.KMSAnalyticRestrictionTransport +OAI.Computability.MaxCut.Games.KMSAnalyticSmallInvariant +OAI.Computability.MaxCut.Games.KMSBasisComparisonNeighborsFiberFunctional +OAI.Computability.MaxCut.Games.KMSBasisComparisonPseudorandomTupleMap +OAI.Computability.MaxCut.Games.KMSBasisInvariant +OAI.Computability.MaxCut.Games.KMSFourthMomentMixedRestriction +OAI.Computability.MaxCut.Games.KMSFourthMomentPointShuffle +OAI.Computability.MaxCut.Games.KMSFourthMomentZoomInvariant +OAI.Computability.MaxCut.Games.KMSInjectionCountBounds +OAI.Computability.MaxCut.Games.KMSMomentConstants +OAI.Computability.MaxCut.Games.KMSMomentTheorem +OAI.Computability.MaxCut.Games.Kernels +OAI.Computability.MaxCut.Games.LabelBound +OAI.Computability.MaxCut.Games.LevelInequality +OAI.Computability.MaxCut.Games.MaskMoment +OAI.Computability.MaxCut.Games.MatrixCharacters +OAI.Computability.MaxCut.Games.MatrixChartDegreeNeighbors +OAI.Computability.MaxCut.Games.MatrixChartKMSNeighbors +OAI.Computability.MaxCut.Games.MatrixChartShortcode +OAI.Computability.MaxCut.Games.MatrixFourier +OAI.Computability.MaxCut.Games.MatrixGap +OAI.Computability.MaxCut.Games.MatrixNoise +OAI.Computability.MaxCut.Games.NP +OAI.Computability.MaxCut.Games.NoiseEnumeration +OAI.Computability.MaxCut.Games.OccurrenceTupleOrder +OAI.Computability.MaxCut.Games.OperatorNorm +OAI.Computability.MaxCut.Games.OrientationVectors +OAI.Computability.MaxCut.Games.OrientedBlockKernel +OAI.Computability.MaxCut.Games.Parameters +OAI.Computability.MaxCut.Games.PartnerFullSampling +OAI.Computability.MaxCut.Games.PartnerProjection +OAI.Computability.MaxCut.Games.Pinsker +OAI.Computability.MaxCut.Games.PoweringGlobalEnumeration +OAI.Computability.MaxCut.Games.PoweringInitializeFrame +OAI.Computability.MaxCut.Games.PoweringMasterState +OAI.Computability.MaxCut.Games.PoweringPlanBudget +OAI.Computability.MaxCut.Games.PoweringPolynomialBudget +OAI.Computability.MaxCut.Games.Probability +OAI.Computability.MaxCut.Games.Product +OAI.Computability.MaxCut.Games.ProductSoundness +OAI.Computability.MaxCut.Games.ProductTarget +OAI.Computability.MaxCut.Games.RankAdditivity +OAI.Computability.MaxCut.Games.RawMapLaw +OAI.Computability.MaxCut.Games.RawPartnerTarget +OAI.Computability.MaxCut.Games.RawPrivateTable +OAI.Computability.MaxCut.Games.RealTarget +OAI.Computability.MaxCut.Games.Reindexing +OAI.Computability.MaxCut.Games.Restriction +OAI.Computability.MaxCut.Games.RowErasure +OAI.Computability.MaxCut.Games.RowErasureConcentration +OAI.Computability.MaxCut.Games.RowErasureSelection +OAI.Computability.MaxCut.Games.RowErasureSelectionNormalization +OAI.Computability.MaxCut.Games.RowErasureSliceQuotient +OAI.Computability.MaxCut.Games.SeparationCertificate +OAI.Computability.MaxCut.Games.ShortcodeFiberSampling +OAI.Computability.MaxCut.Games.SplitMaps +OAI.Computability.MaxCut.Games.StageData +OAI.Computability.MaxCut.Games.StageNoiseRecurrence +OAI.Computability.MaxCut.Games.Subdivision +OAI.Computability.MaxCut.Games.SubmoduleInterval +OAI.Computability.MaxCut.Games.Target +OAI.Computability.MaxCut.Games.Theorem +OAI.Computability.MaxCut.Games.TranslationTarget +OAI.Computability.MaxCut.Games.UniformPartition +OAI.Computability.MaxCut.Games.UpperBound +OAI.Computability.MaxCut.Games.UpperMobius +OAI.Computability.MaxCut.Games.WeightRounding +OAI.Computability.MaxCut.Games.Weighted +OAI.Computability.MaxCut.Graphs.TestCut +OAI.Computability.MaxCut.Machines.AddressMachineInitial +OAI.Computability.MaxCut.Machines.AddressMachineLoop +OAI.Computability.MaxCut.Machines.AddressMachineProgram +OAI.Computability.MaxCut.Machines.Alphabet +OAI.Computability.MaxCut.Machines.AlphabetBudget +OAI.Computability.MaxCut.Machines.AlphabetGraph +OAI.Computability.MaxCut.Machines.AlphabetReduction +OAI.Computability.MaxCut.Machines.AlphabetRetraction +OAI.Computability.MaxCut.Machines.Body +OAI.Computability.MaxCut.Machines.CanonicalBodyMachine +OAI.Computability.MaxCut.Machines.CloneMachineModel +OAI.Computability.MaxCut.Machines.CompareLoop +OAI.Computability.MaxCut.Machines.EmitRows +OAI.Computability.MaxCut.Machines.FramedLen +OAI.Computability.MaxCut.Machines.GraphCounterFinish +OAI.Computability.MaxCut.Machines.Input +OAI.Computability.MaxCut.Machines.Lookup +OAI.Computability.MaxCut.Machines.Machine +OAI.Computability.MaxCut.Machines.Machine2 +OAI.Computability.MaxCut.Machines.MachineBinaryFormula +OAI.Computability.MaxCut.Machines.MachineBinaryInputReduction +OAI.Computability.MaxCut.Machines.MachineBinaryNameCompare +OAI.Computability.MaxCut.Machines.MachineBinaryParsing +OAI.Computability.MaxCut.Machines.MachineBinaryRenameLoop +OAI.Computability.MaxCut.Machines.MachineBinaryRenameWords +OAI.Computability.MaxCut.Machines.MachineCanonicalOutput +OAI.Computability.MaxCut.Machines.MachineClone100 +OAI.Computability.MaxCut.Machines.MachineClone100Table +OAI.Computability.MaxCut.Machines.MachineClone100Triples +OAI.Computability.MaxCut.Machines.MachineCloudCount +OAI.Computability.MaxCut.Machines.MachineCloudPadding +OAI.Computability.MaxCut.Machines.MachineCloudPrefix +OAI.Computability.MaxCut.Machines.MachineCloudSelect +OAI.Computability.MaxCut.Machines.MachineCopy +OAI.Computability.MaxCut.Machines.MachineDummyRows +OAI.Computability.MaxCut.Machines.MachineExpanderFamilyAffine +OAI.Computability.MaxCut.Machines.MachineExpanderFamilyCycle +OAI.Computability.MaxCut.Machines.MachineExpanderRowFrames +OAI.Computability.MaxCut.Machines.MachineExpanderTableProgram +OAI.Computability.MaxCut.Machines.MachineExpanderTableRows +OAI.Computability.MaxCut.Machines.MachineFieldProfile +OAI.Computability.MaxCut.Machines.MachineFieldTemplate +OAI.Computability.MaxCut.Machines.MachineFiniteTable +OAI.Computability.MaxCut.Machines.MachineFixedDivMod +OAI.Computability.MaxCut.Machines.MachineHorner +OAI.Computability.MaxCut.Machines.MachineInitialHeaders +OAI.Computability.MaxCut.Machines.MachineLazyRows +OAI.Computability.MaxCut.Machines.MachineLazyTable +OAI.Computability.MaxCut.Machines.MachineLazyTableRuntime +OAI.Computability.MaxCut.Machines.MachineLookupCore +OAI.Computability.MaxCut.Machines.MachineOverlayRows +OAI.Computability.MaxCut.Machines.MachineOverlayTable +OAI.Computability.MaxCut.Machines.MachinePaddedExpanderFamilyBounds +OAI.Computability.MaxCut.Machines.MachinePaddedOverlay +OAI.Computability.MaxCut.Machines.MachinePortReindex +OAI.Computability.MaxCut.Machines.MachineProductGatherBounds +OAI.Computability.MaxCut.Machines.MachineProductLoop +OAI.Computability.MaxCut.Machines.MachineProductProgram +OAI.Computability.MaxCut.Machines.MachineRegisterEmit +OAI.Computability.MaxCut.Machines.MachineRegularLift +OAI.Computability.MaxCut.Machines.MachineRegularMetadata +OAI.Computability.MaxCut.Machines.MachineRegularOriginalBody +OAI.Computability.MaxCut.Machines.MachineRegularOwnerProgram +OAI.Computability.MaxCut.Machines.MachineRegularTableRuntime +OAI.Computability.MaxCut.Machines.MachineRegularTableTrace +OAI.Computability.MaxCut.Machines.MachineRegularVertexBlock +OAI.Computability.MaxCut.Machines.MachineRhsLoad +OAI.Computability.MaxCut.Machines.MachineSequential +OAI.Computability.MaxCut.Machines.MachineSingleOrbitProgram +OAI.Computability.MaxCut.Machines.MachineStateFrame +OAI.Computability.MaxCut.Machines.MachineSubdivisionCorrespondence +OAI.Computability.MaxCut.Machines.MachineSubdivisionDynamicRows +OAI.Computability.MaxCut.Machines.MachineSubdivisionEmission +OAI.Computability.MaxCut.Machines.MachineSubdivisionRows +OAI.Computability.MaxCut.Machines.MachineSubdivisionTableRead +OAI.Computability.MaxCut.Machines.MachineSubroutine +OAI.Computability.MaxCut.Machines.MachineTableIteration +OAI.Computability.MaxCut.Machines.MachineTemplateAddress +OAI.Computability.MaxCut.Machines.MachineTuple +OAI.Computability.MaxCut.Machines.MachineTupleOdometer +OAI.Computability.MaxCut.Machines.MachineUnaryAffine +OAI.Computability.MaxCut.Machines.MachineUnaryMultiply +OAI.Computability.MaxCut.Machines.MachineUniformCopyOrder +OAI.Computability.MaxCut.Machines.MachineUniformRounding +OAI.Computability.MaxCut.Machines.PoweringMachineField +OAI.Computability.MaxCut.Machines.PoweringMachineGlobal +OAI.Computability.MaxCut.Machines.PoweringMachineLoop +OAI.Computability.MaxCut.Machines.PoweringMachineRelation +OAI.Computability.MaxCut.Machines.PoweringMachineRotor +OAI.Computability.MaxCut.Machines.PoweringMachineRowHeaders +OAI.Computability.MaxCut.Machines.PoweringMachineRuntime +OAI.Computability.MaxCut.Machines.PoweringMachineVertex +OAI.Computability.MaxCut.Machines.PoweringRuntimeBudget +OAI.Computability.MaxCut.Machines.Printer +OAI.Computability.MaxCut.Machines.RawInitialMachineBudget +OAI.Computability.MaxCut.Machines.RawInitialMachineCleanup +OAI.Computability.MaxCut.Machines.RawInitialMachineModel +OAI.Computability.MaxCut.Machines.Relations +OAI.Computability.MaxCut.Machines.Runtime +OAI.Computability.MaxCut.Machines.Runtime2 +OAI.Computability.MaxCut.Machines.RuntimeModel +OAI.Computability.MaxCut.Machines.RuntimeSpace +OAI.Computability.MaxCut.Machines.SelectorMachine +OAI.Computability.MaxCut.Main +OAI.Computability.MaxCut.Model +OAI.Computability.MaxCut.Model2 +OAI.Computability.MaxCut.PCP.AnalyticCheeger +OAI.Computability.MaxCut.PCP.Bounds +OAI.Computability.MaxCut.PCP.CayleySampling +OAI.Computability.MaxCut.PCP.CayleySpectral +OAI.Computability.MaxCut.PCP.ClauseVerifier +OAI.Computability.MaxCut.PCP.CompletedSampling +OAI.Computability.MaxCut.PCP.ContextClear +OAI.Computability.MaxCut.PCP.ContextLoad +OAI.Computability.MaxCut.PCP.ContextPrepare +OAI.Computability.MaxCut.PCP.DescriptorEmission +OAI.Computability.MaxCut.PCP.DistributionMaps +OAI.Computability.MaxCut.PCP.EquationEmit +OAI.Computability.MaxCut.PCP.ExpanderFamily +OAI.Computability.MaxCut.PCP.ExpanderRowControl +OAI.Computability.MaxCut.PCP.ExpanderTableEnumeration +OAI.Computability.MaxCut.PCP.FieldArray +OAI.Computability.MaxCut.PCP.FinalBooleanVerifier +OAI.Computability.MaxCut.PCP.Folding +OAI.Computability.MaxCut.PCP.FourierResponse +OAI.Computability.MaxCut.PCP.Game +OAI.Computability.MaxCut.PCP.Gap +OAI.Computability.MaxCut.PCP.Generator +OAI.Computability.MaxCut.PCP.GraphGap +OAI.Computability.MaxCut.PCP.GraphTableComplexity +OAI.Computability.MaxCut.PCP.Hastad +OAI.Computability.MaxCut.PCP.HeaderAccumulate +OAI.Computability.MaxCut.PCP.HeaderCounts +OAI.Computability.MaxCut.PCP.HonestTest +OAI.Computability.MaxCut.PCP.InitialGraph +OAI.Computability.MaxCut.PCP.KernelIteration +OAI.Computability.MaxCut.PCP.LocalEquation +OAI.Computability.MaxCut.PCP.LoopOrder +OAI.Computability.MaxCut.PCP.MatrixParity +OAI.Computability.MaxCut.PCP.MatrixParityRow +OAI.Computability.MaxCut.PCP.Occurrences +OAI.Computability.MaxCut.PCP.Overlap +OAI.Computability.MaxCut.PCP.Overlay +OAI.Computability.MaxCut.PCP.Parameters +OAI.Computability.MaxCut.PCP.Parity +OAI.Computability.MaxCut.PCP.ParityIndependence +OAI.Computability.MaxCut.PCP.PortTableLookup +OAI.Computability.MaxCut.PCP.PortTables +OAI.Computability.MaxCut.PCP.PoweringDecoding +OAI.Computability.MaxCut.PCP.PoweringOpinionTables +OAI.Computability.MaxCut.PCP.PoweringRowData +OAI.Computability.MaxCut.PCP.PoweringRowHeaderSemantics +OAI.Computability.MaxCut.PCP.PoweringTableLayout +OAI.Computability.MaxCut.PCP.PoweringTableSemantics +OAI.Computability.MaxCut.PCP.PreprocessingFamilyBridge +OAI.Computability.MaxCut.PCP.PreprocessingInternalRows +OAI.Computability.MaxCut.PCP.PreprocessingLazyWords +OAI.Computability.MaxCut.PCP.PreprocessingOverlayWords +OAI.Computability.MaxCut.PCP.PreprocessingPaddingOffsets +OAI.Computability.MaxCut.PCP.PreprocessingPaddingWords +OAI.Computability.MaxCut.PCP.PreprocessingRegularBounds +OAI.Computability.MaxCut.PCP.PreprocessingRegularLoopWords +OAI.Computability.MaxCut.PCP.PreprocessingRegularSoundness +OAI.Computability.MaxCut.PCP.PreprocessingRegularTables +OAI.Computability.MaxCut.PCP.PreprocessingStageMaps +OAI.Computability.MaxCut.PCP.Product +OAI.Computability.MaxCut.PCP.ProductCollisionBounds +OAI.Computability.MaxCut.PCP.ProfileBridge +OAI.Computability.MaxCut.PCP.ProfileCorrection +OAI.Computability.MaxCut.PCP.RawInitialPredicate +OAI.Computability.MaxCut.PCP.RawInitialTables +OAI.Computability.MaxCut.PCP.RepetitionUpper +OAI.Computability.MaxCut.PCP.RoundComputation +OAI.Computability.MaxCut.PCP.RoundGap +OAI.Computability.MaxCut.PCP.Rounding +OAI.Computability.MaxCut.PCP.SelectedInformation +OAI.Computability.MaxCut.PCP.SelectedJointGame +OAI.Computability.MaxCut.PCP.SelectedProfileBudget +OAI.Computability.MaxCut.PCP.SelectionSequence +OAI.Computability.MaxCut.PCP.SpectralCut +OAI.Computability.MaxCut.PCP.TableIteration +OAI.Computability.MaxCut.PCP.TupleBody +OAI.Computability.MaxCut.PCP.UniformRestriction +OAI.Computability.MaxCut.PCP.Variation diff --git a/tasks/optimal-max-cut/solution/reference.py b/tasks/optimal-max-cut/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/optimal-max-cut/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/optimal-max-cut/solution/solve.sh b/tasks/optimal-max-cut/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f0822fdafb33e97f8fee9812621f3113f254b135 --- /dev/null +++ b/tasks/optimal-max-cut/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of OptimalMaxCut, i.e. module OAI.Computability.MaxCut.Main and the +# 372 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.MaxCut.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of OptimalMaxCut" diff --git a/tasks/optimal-max-cut/task.toml b/tasks/optimal-max-cut/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..42469484423e00c409cf671ad39cbd27b0e82076 --- /dev/null +++ b/tasks/optimal-max-cut/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/optimal-max-cut" +version = "1.0.0" +description = "Prove OptimalMaxCut (openai/math family 102: The Unique Games Conjecture and optimal approximation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/OptimalMaxCut.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "OptimalMaxCut" +family = "102" +family_title = "The Unique Games Conjecture and optimal approximation thresholds" +subject = "Theoretical computer science" +theorems = ["OAI.OptimalMaxCut.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.MaxCut.Main" +reference_modules = 372 +reference_lean_bytes = 8863088 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1488 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19676 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/optimal-max-cut/tests/Challenge.lean b/tasks/optimal-max-cut/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e200abdca45813740899ec408377a275e9141e5 --- /dev/null +++ b/tasks/optimal-max-cut/tests/Challenge.lean @@ -0,0 +1,156 @@ +import Mathlib + +namespace OAI + +namespace MaxCutGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +/-- An ordinary conjunction of three-slot clauses with sparse variable names. +Repeated names and repeated literals are permitted in every clause. -/ +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end MaxCutGames.BinaryFormula + +namespace MaxCutGames.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +/-- Prefix-free framing on the two-symbol input alphabet. -/ +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +/-- Equality with the canonical digits rejects alternate padded encodings. -/ +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +/-- Fuel bounds the number of clause iterations, not the size of any name. -/ +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end MaxCutGames.BinaryEncoding + +namespace OptimalMaxCut + +open scoped BigOperators + +/-- The exact Goemans–Williamson ratio, as an infimum over -1 ≤ ρ < 1. -/ +noncomputable def alphaGW : ℝ := + sInf ((fun ρ : ℝ => 2 * Real.arccos ρ / (Real.pi * (1 - ρ))) '' + Set.Ico (-1 : ℝ) 1) + +/-- The ordinary binary 3SAT language, including rejection of malformed words. -/ +def binary3SAT (input : List Bool) : Prop := + ∃ formula, MaxCutGames.BinaryEncoding.decodeFormula input = some formula ∧ + formula.Satisfiable + +/-- A finite simple unweighted graph with its full Boolean adjacency table. -/ +structure Graph where + vertices : ℕ + adj : Fin vertices → Fin vertices → Bool + symmetric : ∀ u v, adj u v = adj v u + loopless : ∀ u, adj u u = false + +/-- Each unordered distinct edge crossing the cut is counted exactly once. -/ +def Graph.cutSize (G : Graph) (cut : Fin G.vertices → Bool) : ℕ := + ∑ u : Fin G.vertices, ∑ v : Fin G.vertices, + if u < v ∧ G.adj u v = true ∧ cut u ≠ cut v then 1 else 0 + +/-- The maximum over all Boolean cuts of the finite vertex set. -/ +def Graph.maxCut (G : Graph) : ℕ := + (Finset.univ.image G.cutSize).sup id + +/-- The positive integer scale Q is part of the output. It need not equal the +number of graph edges. -/ +structure ScaledGraph where + graph : Graph + scale : ℕ + scale_pos : 0 < scale + +/-- Canonical delimited binary vertex count and scale, followed by the full +adjacency table in lexicographic order. -/ +def ScaledGraph.bits (G : ScaledGraph) : List Bool := + MaxCutGames.BinaryEncoding.nameBits G.graph.vertices ++ + MaxCutGames.BinaryEncoding.nameBits G.scale ++ + (List.finRange G.graph.vertices).flatMap (fun u => + (List.finRange G.graph.vertices).map (fun v => G.graph.adj u v)) + +/-- The rational gap bounds and the finite machine are fixed before the input. +The bounds compare the maximum cut divided by the positive output scale. -/ +structure GapReduction (α : ℝ) where + yesBound : ℚ + noBound : ℚ + yes_pos : 0 < yesBound + no_nonneg : 0 ≤ noBound + gap : (noBound : ℝ) < α * (yesBound : ℝ) + construct : List Bool → ScaledGraph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + ScaledGraph.bits construct + finiteAlphabet : ∀ k, Finite (computation.tm.Γ k) + completeness : ∀ input, binary3SAT input → + (yesBound : ℝ) ≤ ((construct input).graph.maxCut : ℝ) / (construct input).scale + soundness : ∀ input, ¬ binary3SAT input → + ((construct input).graph.maxCut : ℝ) / (construct input).scale ≤ (noBound : ℝ) + +def MainStatement : Prop := + ∀ α : ℝ, alphaGW < α → α ≤ 1 → Nonempty (GapReduction α) + +end OptimalMaxCut + +theorem OptimalMaxCut.main : OptimalMaxCut.MainStatement := by + sorry + +end OAI diff --git a/tasks/optimal-max-cut/tests/grade.py b/tasks/optimal-max-cut/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/optimal-max-cut/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/optimal-max-cut/tests/task.json b/tasks/optimal-max-cut/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e31cc5d452b79c028d4d208527195548fe68d2f3 --- /dev/null +++ b/tasks/optimal-max-cut/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "OptimalMaxCut", + "comparator": { + "theorem_names": [ + "OAI.OptimalMaxCut.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18776 +} \ No newline at end of file diff --git a/tasks/optimal-max-cut/tests/test.sh b/tasks/optimal-max-cut/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/optimal-max-cut/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ordinary-elliott/environment/Dockerfile b/tasks/ordinary-elliott/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ordinary-elliott/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ordinary-elliott/environment/fetch_mathlib.sh b/tasks/ordinary-elliott/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ordinary-elliott/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ordinary-elliott/environment/lake-manifest.json b/tasks/ordinary-elliott/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ordinary-elliott/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ordinary-elliott/environment/lakefile.lean b/tasks/ordinary-elliott/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ordinary-elliott/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ordinary-elliott/environment/lean_setup.sh b/tasks/ordinary-elliott/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ordinary-elliott/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ordinary-elliott/environment/pack_submission.py b/tasks/ordinary-elliott/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ordinary-elliott/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ordinary-elliott/instruction.md b/tasks/ordinary-elliott/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e64bc3d401ba13c93f84b729b06d87a295005b91 --- /dev/null +++ b/tasks/ordinary-elliott/instruction.md @@ -0,0 +1,95 @@ +# openai/math challenge `OrdinaryElliott` (family 007) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 007 of the release, *Two-point Chowla and the corrected binary Elliott conjecture* +(Number theory). The family as a whole: Proves the ordinary two-point Chowla conjecture, with a bound $O(X/(\log X)^c)$ for Liouville correlation sums along fixed nonproportional affine forms, where $c>0$ is absolute. More generally, proves the binary corrected Elliott conjecture for complex multiplicative functions bounded by one when one factor is uniformly nonpretentious against each fixed Dirichlet character times $n^{it}$ for $|t|\le X$. + +The challenge is `OrdinaryElliott`, also at `/opt/openai-math/challenges/OrdinaryElliott.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators +open Filter + +namespace OrdinaryCorrelations + +def OneBounded (f : ℕ → ℂ) : Prop := ∀ n, ‖f n‖ ≤ 1 + +def Multiplicative (f : ℕ → ℂ) : Prop := + ∀ m n : ℕ, 0 < m → 0 < n → m.Coprime n → f (m * n) = f m * f n + +def distanceSq (f : ℕ → ℂ) {q : ℕ} (χ : DirichletCharacter ℂ q) + (t X : ℝ) : ℝ := + ∑ p ∈ (Finset.Icc 2 ⌊X⌋₊).filter Nat.Prime, + (1 - (f p * star (χ (p : ZMod q) * + Complex.exp ((t * Real.log (p : ℝ) : ℝ) * Complex.I))).re) / (p : ℝ) + +def distance (f : ℕ → ℂ) {q : ℕ} (χ : DirichletCharacter ℂ q) + (t X : ℝ) : ℝ := Real.sqrt (distanceSq f χ t X) + +def UniformlyNonpretentious (f : ℕ → ℂ) : Prop := + ∀ (q : ℕ), 0 < q → ∀ χ : DirichletCharacter ℂ q, + Tendsto (fun N : ℕ => sInf ((fun t : ℝ => distance f χ t (N : ℝ)) '' + Set.Icc (-(N : ℝ)) (N : ℝ))) atTop atTop + +def shiftAverage (f₁ f₂ : ℕ → ℂ) (h₁ h₂ N : ℕ) : ℂ := + (N : ℂ)⁻¹ * ∑ n ∈ Finset.Icc 1 N, f₁ (n + h₁) * f₂ (n + h₂) + +theorem binary_corrected_elliott + (f₁ f₂ : ℕ → ℂ) (hf₁ : OneBounded f₁) (hf₂ : OneBounded f₂) + (hm₁ : Multiplicative f₁) (hm₂ : Multiplicative f₂) + (hNP : UniformlyNonpretentious f₁ ∨ UniformlyNonpretentious f₂) + (h₁ h₂ : ℕ) (hne : h₁ ≠ h₂) : + Tendsto (shiftAverage f₁ f₂ h₁ h₂) atTop (nhds 0) := by + sorry + +end OrdinaryCorrelations +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/OrdinaryElliott.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.OrdinaryCorrelations.binary_corrected_elliott` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ordinary-elliott/solution/closure.txt b/tasks/ordinary-elliott/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b81fc03e316cc72f9522f2184f7c7f55c1ca4cac --- /dev/null +++ b/tasks/ordinary-elliott/solution/closure.txt @@ -0,0 +1,628 @@ +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AccuracyCancel +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ActualMassOne +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ActualTerminalEnergyExplicit +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ActualWindowMass +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AdjacentCutoff +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AdmissibleFacts +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AeNotNatTranslate +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AllFrequencyPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AllPrimeInterval +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Alpha +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AmplitudeSecondSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AnalyticCentering +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AnalyticCenteringLimsup +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AnalyticTransition +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ArithmeticGeneratingUpper +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ArithmeticPositiveGenerating +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ArithmeticTwist +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.AssignedLength +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Avoids +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BadFrequencies +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BandPowerLower +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BernoulliWeight +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BilinearPart +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinErrorWidth +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinQ +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinSumByMultiples +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinnedRamareError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinnedRamareErrorIdentity +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BinnedStage +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BlockDiagonalBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BoundaryBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BoundedLogSeriesCauchyDerivative +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Box +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BoxAddWidth +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BoxMono +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BoxNonneg +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Bump +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.BumpMass +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CapUpper +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CappedRectangle +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CardFourLeEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CardFourLeIntervalEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CellSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CellSumFull +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CharBounded +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CharacterModulation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Coefficient +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CoefficientHom +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CofactorEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CofactorNormLeOne +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Collect +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CompactDerivativeSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CompactUnweightedDerivativeSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Complete +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CompleteInverseOne +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CompleteIsComplete +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CompressEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ContinuousDerivativeVertical +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ContinuousOnShiftRpow +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CoprimePacketMinorArc +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Core +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CorePrime +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Count +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CrossTransitionEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CutRectangle +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Cutoff +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CutoffSeriesEqSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.CutoffSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DeletedWeightMean +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DerivativeConstant +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DerivativeVerticalBounded +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DivisorPrimeFactor +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DivisorTriangleHighAtScale +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DivisorsEqFilterIoc +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DualSmoothZeroLeft +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicCoefficientEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicCoefficientSquareSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicCoefficientSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicCofactorMellin +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicCofactorMellinEqPolynomial +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicGaussianL1Power +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicGaussianPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicGaussianSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicL1LeDiscrete +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicLogWindowPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicLogWindowSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicMellinExplicitParameters +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicMellinPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicPhaseMass +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicPhysicalPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicSharpLogPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicSubintervalSharpSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.DyadicWeightRemoval +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.E +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EnergyComplexLe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EnergyLeGram +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ErrorSampleConstant +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Euler +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EvenLengthLower +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Event +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EventualGate +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EventualRoughBox +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EventualShortTwists +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.EventualSourceLarge +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ExistsScaledGeometricLt +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ExpBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ExplicitDensityCost +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ExponentBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Factor +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FactorialExp +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FinEquivApply +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FinitePhaseGrid +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FinitePrimeTwistsPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FiniteSchur +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FirstSampleConstant +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FirstThresholdGain +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FixedBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FloorIntersectionError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ForwardIntegrableOn +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ForwardOnUnit +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ForwardSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FourierMass +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FourierSeries +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FourthLeRealEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FrozenBandBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.FrozenWidthError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.GaussianL1Numeric +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.GeometricProduct +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.GlobalPacket +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.GoodBox +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Grid +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.GridMinLower +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.HalfGeometricIdentity +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.HalfLeLogTwo +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.HarmonicBlockBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.HasDerivAtLogPrimitive +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.HorizontalProductBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.IntegerGridSeparated +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.IntegralInverseFiveQuarters +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.IntervalDivisorCard +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.IntervalWidthSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.InverseBandBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.InverseBinGeometric +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.InverseCubeSummable +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Kernel +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelBinBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelConstant +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelL1Concentration +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelWeight +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelWeightFactor +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.KernelWindow +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Line +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LocalSampling +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogBin +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogBorderCard +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogCoef +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogCorrelation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogPhaseMulConj +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogSeriesCauchyDerivative +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogSmoothPart +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogarithmicDeltaTendsto +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.LogweightError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MajorArcsEvenPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MajorWidth +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MangoldtAbscissa +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MassNonneg +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MassPowerBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MeanC +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MeanR +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MinorDyadicWidth +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MixedWeight +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MobiusInverse +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ModOneCharacter +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ModulationNormLeOne +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MomentCoefficient +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingCompactUnweightedSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingCompletePartialSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingParameters +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingPowerCompactWeightedSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingSquareCompactUnweightedSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingSquareCompactWeightedSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.MovingSquareCompletePartialSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NatDivRealError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NatKernelSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NormCauchy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NormOneAddLeExp +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NormPhase +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NormPowLeGramTrace +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.NormalizedPrimeBlockBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OneBounded +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OneOrZero +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryArchimedeanTwistBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryCofactorDyadicBoundBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryCofactorWeightBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryCofactorWeightBasic3 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryCorrelationsBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryDirichletFiberMomentsBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryDirichletMeanSquareBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryDirichletMixedMomentsBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryFrequencyChainBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryMellinSamplingBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryNarrowGridBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryNarrowGridBasic2 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryNarrowGridBasic3 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryPrimeDirichletMomentsBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryPrimeDirichletMomentsBasic2 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryRestrictedCofactorBasic2 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinarySelbergWeightsBasic3 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinarySelbergWeightsBasic4 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryShortPowerLogarithmic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinarySum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryTwistWidthBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryTwoScaleCofactorBasic3 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.OrdinaryTwoScaleCofactorBasic4 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PartialSmallOfTriangleSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PeriodicEvenBoundFromNP +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Phase +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PhaseAdd +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PhaseEqOneIffInteger +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PhaseMulStar +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PhaseNatMul +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PhaseSubInt +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Poly +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PowerSumLe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PowersetFirstMoment +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrefixEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrefixSet +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeBlockPacket +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeCount +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeCountLe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeCountRoughZero +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeCountZeroIff +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeFactorsCardLeDyadic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeHarmonicPowerBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeLogReciprocalBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeParameters +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeProductSquarefree +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeStart +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeWeight +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimeWindow +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Primes +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrimitiveTwoLower +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.PrincipalDivergence +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Product +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ProductNeZero +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ProductSupportBand +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ProductWeightMulHom +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.QuadraticGeometricLimit +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RationalApproximation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RationalPhaseOfModEq +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RationalPrimeBlockBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RealPowerHom +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Reciprocal +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ReciprocalHom +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ReciprocalRangeMass +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ResidueFiberCard +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RetainedChoice +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Riesz +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RieszCoeffNorm +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RoughHarmonicEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RoughMellinEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RoughPolynomial +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.RoughSupportGlobal +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SampledBudget +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ScaledWindow +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SelbergPrimeSubset +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SharpLogGate +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SharpSmoothingNumeric +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SharpWeightTermError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SharpWindowIocAdd +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SharpWindowZeroHigh +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ShellGridScales +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ShiftedDual +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ShiftedMultiplesCard +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.ShiftedPowerLeExponential +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SieveTriangleKernel +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SieveTriangleKernelErrorAt +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmallSmoothCountFinite +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Smooth +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothBlock +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothCofactorHarmonic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothCofactorSumEq +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothDamped +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothPart +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothRoughCorrelation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SmoothedPrimeEnergy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourceBlockMatrix +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourceBlockMatrixTraceExpansion +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourceLocalSum +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourcePrimeFactorBasic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourcePrimeFactorBasic2 +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SourceProductSmall +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SparseCardOfMoment +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SquareBoundedLogSeriesCauchy +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SquareDivGe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SquarefreeHarmonic +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumDvdDilateComplex +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumFinFunSucc +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumIntegralError +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumIntegralErrorLipschitz +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumMultiples +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumMultiplesIoc +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumRangeCut +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.SumRangeSuccEqIcc +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Support +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Surviving +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Tent +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TentPhaseIntegral +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TermMangoldtEq +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TerminalBinnedSparseExplicit +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TerminalPrimeExceptionalProduct +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Threshold +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TransitionConstant +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TriangleEqCutoff +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TriangleMain +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TruncatedWeightedPacket +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Truncation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TruncationComparison +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TupleEntryDvdLocation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TupleProduct +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Twist +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TwistNormLe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.TwoPowerRatioLimit +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.UniformPowerQuotientBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.UniformQuotientBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.UniformSmoothHarmonicBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.UnitDual +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.UnnormalizedProductNormLe +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.Vertical +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.VerticalSeries +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightMean +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightedFunctionNonpretentious +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightedMatrixBilinear +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightedPartialSumBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightedRoughTwistCorrelation +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WeightedSquare +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WindowBound +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WindowMulBounded +OAI.NumberTheory.OrdinaryCorrelations.AbsoluteDefect.WindowSmall +OAI.NumberTheory.OrdinaryCorrelations.Elliott.Adj +OAI.NumberTheory.OrdinaryCorrelations.Elliott.BiasedSequenceOfFailure +OAI.NumberTheory.OrdinaryCorrelations.Elliott.BinIndex +OAI.NumberTheory.OrdinaryCorrelations.Elliott.BinaryCorrectedElliott +OAI.NumberTheory.OrdinaryCorrelations.Elliott.Cesaro +OAI.NumberTheory.OrdinaryCorrelations.Elliott.CesaroNormFunctionEq +OAI.NumberTheory.OrdinaryCorrelations.Elliott.ConstantsA +OAI.NumberTheory.OrdinaryCorrelations.Elliott.DeletedOut +OAI.NumberTheory.OrdinaryCorrelations.Elliott.DirMatrix +OAI.NumberTheory.OrdinaryCorrelations.Elliott.DivisorForm +OAI.NumberTheory.OrdinaryCorrelations.Elliott.Main +OAI.NumberTheory.OrdinaryCorrelations.Elliott.MeanZeroOfNonpretentious +OAI.NumberTheory.OrdinaryCorrelations.Elliott.NormThreshold +OAI.NumberTheory.OrdinaryCorrelations.Elliott.OneAddSumLeProduct +OAI.NumberTheory.OrdinaryCorrelations.Elliott.PrimeDefect +OAI.NumberTheory.OrdinaryCorrelations.Elliott.ProductOneBounded +OAI.NumberTheory.OrdinaryCorrelations.Elliott.RelativeErrorTendsto +OAI.NumberTheory.OrdinaryCorrelations.Elliott.SmoothCutoffExists +OAI.NumberTheory.OrdinaryCorrelations.Elliott.SubsetCost +OAI.NumberTheory.OrdinaryCorrelations.Elliott.TraceMean +OAI.NumberTheory.OrdinaryCorrelations.Elliott.WeightMeanOneLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AbsPrimeMeanLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ActiveComponents +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ActiveReachable +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ActivityGapIndices +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ActivityResidue +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AffineResidueEquiv +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AllCoreLit +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AllForward +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AllSlotMasses +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AmplitudeGeOne +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Append +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ArithmeticClause +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ArithmeticSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AttachedMetadata +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Avg +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AvgAdd +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AvgFintypeChange +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.AvoidEdgeSuffix +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BelowChain +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BetaZ +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BinWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BitWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Block +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BlockActiveCapacity +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BlockEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BlockGateExists +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BoundedLists +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.BoundedMultiplicity +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CardPrimesLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CardTreeVerticesLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CenterMassTendsto +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ChargeKappaPos +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ChargePivotAbsorption +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ChargedCorrectionSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ClosedLine +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CodeEntropyMass +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CoefficientEqSingle +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CoefficientZeroOfNotSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ComponentBoundAfterGap +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ConnectedLitComponent +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ConnectedSet +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ConnectedSetPath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Constant +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CoordinateEquiv +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CoreTupleBins +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CorruptWitness +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Cylinder +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.CylinderBudget +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DataInjective +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DensitySizeLeTestSize +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Directed +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DisconnectedCertificate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DisconnectedErrorSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DisconnectedWitness +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DisjointIntervals +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DivisorFamily +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DivisorPath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DivisorPathFilling +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.DivisorPathTemplate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EarlierTuple +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EdgeAt +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EdgeGraph +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EdgeGraphMono +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EdgeInjective +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Edges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Enum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Epsilon +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.EventuallyConstPowLeExp +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ExceptionalBudget +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ExceptionalCodeSlot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ExistsNewPrime +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ExistsTreePathWithSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Expression +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ExtFields +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FactorialTotal +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FactorsAppendSubset +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FarBlockPair +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FarCorrupted +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FarFilling +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FarTemplate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FarTestSizePolynomial +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Fiber +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FiniteSumInstanceTransfer +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FirstEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FirstSlot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FixedCharges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FixedDisconnected +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FixedIsTagged +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FlatCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FlatSlot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ForestCuts +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ForwardSegment +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FreePieceWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FreeResidues +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FreeSplit +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.FullArithmeticTrace +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GapEmpty +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GapFilling +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GapPathCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GapShapes +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GapTemplate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GateAncestor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GateSelection +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GeometryGoodEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GeometryRetained +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GlobalRecord +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GoodGapTemplate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.GrowsSingleton +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.HarmonicCongruenceBound +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IndependentTests +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Index +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IndexedWitnessFilling +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IntegerResidues +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IntegerResiduesAdd +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IntersectionEqBotOfSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.IntervalOverlap +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.KappaPos +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LabelPrimeSet +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LabelPrimeSetEraseProduct +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LastEdge +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LineList +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LinePrimeCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LinePrimeMemFullUsed +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LinearCoeffZeroOfNot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ListLocalLeOne +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ListSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LitEdgesEmptyOfNo +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LitEdgesSubsetTree +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LocalIndicator +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LocalToken +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LocalUnlitCount +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.LocalWithList +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.MemSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.MemTakeIndex +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ModifiedWeightSameBand +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.NoFixedQualifyingPath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Nonempty +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.NormalizedFiberWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.NumericalLine +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.OfRelabel +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.OffsetAbsLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Ordered +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.OrderedSelection +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.OrientedSubpathRefl +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PackedGapPrefactor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PackedGapPrefactorMonoPath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PackedGapSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PaddedGroupWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PaddedWeightIdentity +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PathTop +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PivotEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PostGapErrorSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Precedes +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrefixCoefficientNondvd +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrimeChargeProduct +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrimeFactorsCardLeLog +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrimeIndex +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrimeOccurrenceInterval +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrimeSystem +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrivateFamily +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.PrivateMono +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ProductCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RankBot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Realizable +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RecordPacket +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RecordUntaggedSingleton +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RecordedTopOutgoing +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RecordedTops +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RelabelAppend +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RepeatedCenterUnlitCount +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RepeatedUnlitTotalEqFixed +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ResidualRankPrivateFamily +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Restrict +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RetainedKernel +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ReturnCountLe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ReverseSegment +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RootCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RootNotDestination +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.RowFactors +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SegmentEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SelectedUsed +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Shape +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ShapeFromGrows +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ShapePivotBins +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SignedAssignedSum +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SingleEdgeWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SizedSet +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SlotEdgeProduct +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SlotWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceCoreEquiv +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceCylinderTruncation +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceDisconnectedCertificatesSmall +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceFullTraceRaw +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceLengthGe +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceListSlotBudget +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceManyWitnessTests +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourcePivotAbsorb +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourcePivotFactor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourcePolyDivTendsto +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourcePrimeUpper +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourcePrimitiveCoefficientInputs +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceReturnFactor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceSystem +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceWitnessBasicScales +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceWitnessDelta +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceWitnessError +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceWitnessErrorBelowTrace +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SourceWitnessMajorant +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Spec +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SpecPrimeSlot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SpecSegment +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SpecificationPrefactor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SpecificationSlotCount +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SpecificationTemplate +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Splice +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SquarefreeExpression +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.StepFactor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Subpath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SubtreeUnionWeightNonneg +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SumEquiv +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SumPeriodBlocks +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Support +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SupportEqUsed +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.SupportIffExtraOrLabel +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Symbolic +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TaggedEdgeProduct +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TaggedShape +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TaggedShapeMap +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Test +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TestVacuous +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TiltedListLocalMean +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TokenSlot +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Topology +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TopologyTreeSteps +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TotalCodeMass +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TotalUnlitCountEqSubtype +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeBlocksWithEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeDestinationInjective +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeEdge +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeEdgeInjective +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeOccurrences +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeOccurrencesEmptyOfFree +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreePrimeSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TreeVertices +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TwoBlockRerooting +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.TwoTermBinomial +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UncutTreeEdges +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UnlitPolynomialBound +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Unselected +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UnselectedCard +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UntaggedEdgeCode +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UntaggedReferenceWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.UsedPrimeReciprocal +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.VertexAt +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.VertexIndex +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.VertexWeight +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.VerticesInBlock +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WalkBetweenSupport +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WalkSupportConnected +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WalkVertices +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.Witness +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessBaseDoublePath +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessConfiguration +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessEntropyBase +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessSlotCount +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessTestDescriptor +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.WitnessTestShape +OAI.NumberTheory.OrdinaryCorrelations.HighTrace.ZeroExpression diff --git a/tasks/ordinary-elliott/solution/reference.py b/tasks/ordinary-elliott/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ordinary-elliott/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ordinary-elliott/solution/solve.sh b/tasks/ordinary-elliott/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..25af2fbe1d90eda2fcc4fc819a5d3e6cf3485bdc --- /dev/null +++ b/tasks/ordinary-elliott/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of OrdinaryElliott, i.e. module OAI.NumberTheory.OrdinaryCorrelations.Elliott.Main and the +# 628 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.OrdinaryCorrelations.Elliott.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of OrdinaryElliott" diff --git a/tasks/ordinary-elliott/task.toml b/tasks/ordinary-elliott/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0af8735e7f1717e11a4a77b15c44ad420a01ddee --- /dev/null +++ b/tasks/ordinary-elliott/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ordinary-elliott" +version = "1.0.0" +description = "Prove OrdinaryElliott (openai/math family 007: Two-point Chowla and the corrected binary Elliott conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/OrdinaryElliott.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "OrdinaryElliott" +family = "007" +family_title = "Two-point Chowla and the corrected binary Elliott conjecture" +subject = "Number theory" +theorems = ["OAI.OrdinaryCorrelations.binary_corrected_elliott"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.OrdinaryCorrelations.Elliott.Main" +reference_modules = 628 +reference_lean_bytes = 3068303 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1590 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14461 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ordinary-elliott/tests/Challenge.lean b/tasks/ordinary-elliott/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..914f601065031ff59b509058cb3d9d709fd0b23e --- /dev/null +++ b/tasks/ordinary-elliott/tests/Challenge.lean @@ -0,0 +1,44 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators +open Filter + +namespace OrdinaryCorrelations + +def OneBounded (f : ℕ → ℂ) : Prop := ∀ n, ‖f n‖ ≤ 1 + +def Multiplicative (f : ℕ → ℂ) : Prop := + ∀ m n : ℕ, 0 < m → 0 < n → m.Coprime n → f (m * n) = f m * f n + +def distanceSq (f : ℕ → ℂ) {q : ℕ} (χ : DirichletCharacter ℂ q) + (t X : ℝ) : ℝ := + ∑ p ∈ (Finset.Icc 2 ⌊X⌋₊).filter Nat.Prime, + (1 - (f p * star (χ (p : ZMod q) * + Complex.exp ((t * Real.log (p : ℝ) : ℝ) * Complex.I))).re) / (p : ℝ) + +def distance (f : ℕ → ℂ) {q : ℕ} (χ : DirichletCharacter ℂ q) + (t X : ℝ) : ℝ := Real.sqrt (distanceSq f χ t X) + +def UniformlyNonpretentious (f : ℕ → ℂ) : Prop := + ∀ (q : ℕ), 0 < q → ∀ χ : DirichletCharacter ℂ q, + Tendsto (fun N : ℕ => sInf ((fun t : ℝ => distance f χ t (N : ℝ)) '' + Set.Icc (-(N : ℝ)) (N : ℝ))) atTop atTop + +def shiftAverage (f₁ f₂ : ℕ → ℂ) (h₁ h₂ N : ℕ) : ℂ := + (N : ℂ)⁻¹ * ∑ n ∈ Finset.Icc 1 N, f₁ (n + h₁) * f₂ (n + h₂) + +theorem binary_corrected_elliott + (f₁ f₂ : ℕ → ℂ) (hf₁ : OneBounded f₁) (hf₂ : OneBounded f₂) + (hm₁ : Multiplicative f₁) (hm₂ : Multiplicative f₂) + (hNP : UniformlyNonpretentious f₁ ∨ UniformlyNonpretentious f₂) + (h₁ h₂ : ℕ) (hne : h₁ ≠ h₂) : + Tendsto (shiftAverage f₁ f₂ h₁ h₂) atTop (nhds 0) := by + sorry + +end OrdinaryCorrelations +end + +end OAI diff --git a/tasks/ordinary-elliott/tests/grade.py b/tasks/ordinary-elliott/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ordinary-elliott/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ordinary-elliott/tests/task.json b/tasks/ordinary-elliott/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a5e789f4d94d6ac5c1f8cc073c09869d83c9dc21 --- /dev/null +++ b/tasks/ordinary-elliott/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "OrdinaryElliott", + "comparator": { + "theorem_names": [ + "OAI.OrdinaryCorrelations.binary_corrected_elliott" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13561 +} \ No newline at end of file diff --git a/tasks/ordinary-elliott/tests/test.sh b/tasks/ordinary-elliott/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ordinary-elliott/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/parity-lifts/environment/Dockerfile b/tasks/parity-lifts/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/parity-lifts/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/parity-lifts/environment/fetch_mathlib.sh b/tasks/parity-lifts/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/parity-lifts/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/parity-lifts/environment/lake-manifest.json b/tasks/parity-lifts/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/parity-lifts/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/parity-lifts/environment/lakefile.lean b/tasks/parity-lifts/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/parity-lifts/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/parity-lifts/environment/lean_setup.sh b/tasks/parity-lifts/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/parity-lifts/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/parity-lifts/environment/pack_submission.py b/tasks/parity-lifts/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/parity-lifts/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/parity-lifts/instruction.md b/tasks/parity-lifts/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9b47bff7aed95190336e300c92e0db84295f5ee --- /dev/null +++ b/tasks/parity-lifts/instruction.md @@ -0,0 +1,260 @@ +# openai/math challenge `ParityLifts` (family 133) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 133 of the release, *The complexity of Weisfeiler–Leman refinement* +(Theoretical computer science). The family as a whole: Proves unconditional $n^{\Omega(k)}$ deterministic time lower bounds for joint and separate $k$-dimensional Weisfeiler–Leman equivalence, for sufficiently large fixed $k$ in the specified sequential adjacency-matrix models. With dimension as input, joint equivalence is EXPTIME-complete even on subcubic graphs; deciding whether refinement identifies a graph is also EXPTIME-complete. + +The challenge is `ParityLifts`, also at `/opt/openai-math/challenges/ParityLifts.lean`: + +```lean +import Mathlib + +namespace OAI + + + +namespace ParityWL + +open scoped BigOperators + +abbrev Bit := ZMod 2 +abbrev MainPair (t : ℕ) := {p : Fin t × Fin t // p.1 < p.2} +abbrev Helper (t : ℕ) := + {q : MainPair t × Fin t // q.2 ≠ q.1.1.1 ∧ q.2 ≠ q.1.1.2} +abbrev TemplateVertex (t : ℕ) := Fin t ⊕ Helper t + +structure ChoiceSystem (t : ℕ) where + Domain : Fin t → Type + domainFintype : ∀ i, Fintype (Domain i) + Label : MainPair t → Type + labelFintype : ∀ p, Fintype (Label p) + leftLabel : (p : MainPair t) → Domain p.1.1 → Label p + rightLabel : (p : MainPair t) → Domain p.1.2 → Label p + +attribute [instance] ChoiceSystem.domainFintype ChoiceSystem.labelFintype + +def ChoiceSystem.Successful {t : ℕ} (C : ChoiceSystem t) : Prop := + ∃ d : (i : Fin t) → C.Domain i, + ∀ p : MainPair t, C.leftLabel p (d p.1.1) = C.rightLabel p (d p.1.2) + +def ChoiceSystem.SizeAtMost {t : ℕ} (C : ChoiceSystem t) (A : ℕ) : Prop := + (∀ i, Fintype.card (C.Domain i) ≤ A) ∧ (∀ p, Fintype.card (C.Label p) ≤ A) + +def helperIncident {t : ℕ} (h : Helper t) (i : Fin t) : Prop := + i = h.1.1.1.1 ∨ i = h.1.1.1.2 ∨ i = h.1.2 + +def templateAdj {t : ℕ} : TemplateVertex t → TemplateVertex t → Prop + | .inl i, .inl j => i ≠ j + | .inl i, .inr h => helperIncident h i + | .inr h, .inl i => helperIncident h i + | .inr _, .inr _ => False + +def template (t : ℕ) : SimpleGraph (TemplateVertex t) where + Adj := templateAdj + symm := ⟨by + intro x y h + cases x <;> cases y <;> simp_all [templateAdj, ne_comm]⟩ + loopless := ⟨by + intro x + cases x <;> simp [templateAdj]⟩ + +abbrev BaseVertex {t : ℕ} (C : ChoiceSystem t) := + ((i : Fin t) × C.Domain i) ⊕ ((h : Helper t) × C.Label h.1.1) + +def baseType {t : ℕ} {C : ChoiceSystem t} : BaseVertex C → TemplateVertex t + | .inl x => .inl x.1 + | .inr x => .inr x.1 + +inductive BaseArc {t : ℕ} (C : ChoiceSystem t) : BaseVertex C → BaseVertex C → Prop + | main (p : MainPair t) (d : C.Domain p.1.1) (e : C.Domain p.1.2) + (h : C.leftLabel p d = C.rightLabel p e) : + BaseArc C (.inl ⟨p.1.1, d⟩) (.inl ⟨p.1.2, e⟩) + | left (h : Helper t) (d : C.Domain h.1.1.1.1) : + BaseArc C (.inr ⟨h, C.leftLabel h.1.1 d⟩) (.inl ⟨h.1.1.1.1, d⟩) + | right (h : Helper t) (e : C.Domain h.1.1.1.2) : + BaseArc C (.inr ⟨h, C.rightLabel h.1.1 e⟩) (.inl ⟨h.1.1.1.2, e⟩) + | third (h : Helper t) (q : C.Label h.1.1) (f : C.Domain h.1.2) : + BaseArc C (.inr ⟨h, q⟩) (.inl ⟨h.1.2, f⟩) + +def baseGraph {t : ℕ} (C : ChoiceSystem t) : SimpleGraph (BaseVertex C) := + SimpleGraph.fromRel (BaseArc C) + +def baseProjection {t : ℕ} (C : ChoiceSystem t) : baseGraph C →g template t where + toFun := baseType + map_rel' := by + intro x y h + have arc : ∀ u v, BaseArc C u v → (template t).Adj (baseType u) (baseType v) := by + intro u v huv + cases huv with + | main p d e he => exact ne_of_lt p.property + | left h d => exact Or.inl rfl + | right h e => exact Or.inr (Or.inl rfl) + | third h q f => exact Or.inr (Or.inr rfl) + rcases h.2 with hxy | hyx + · exact arc x y hxy + · exact (arc y x hyx).symm + +section Lifts + +variable {A V : Type} [Fintype A] (T : SimpleGraph A) (G : SimpleGraph V) + +noncomputable def Tag (b : A → Bit) (a : A) := by + classical + exact {z : T.neighborSet a → Bit // ∑ v, z v = b a} + +noncomputable instance tagFintype (b : A → Bit) (a : A) : Fintype (Tag T b a) := by + classical + unfold Tag + infer_instance + +abbrev LiftVertex (τ : G →g T) (b : A → Bit) := (u : V) × Tag T b (τ u) + +noncomputable def liftGraph (τ : G →g T) (b : A → Bit) : + SimpleGraph (LiftVertex T G τ b) where + Adj u v := ∃ h : G.Adj u.1 v.1, + u.2.1 ⟨τ v.1, τ.map_adj h⟩ = v.2.1 ⟨τ u.1, τ.map_adj h.symm⟩ + symm := ⟨by + intro u v h + rcases h with ⟨h, e⟩ + exact ⟨h.symm, e.symm⟩⟩ + loopless := ⟨by + intro u h + exact G.irrefl h.1⟩ + +end Lifts + +noncomputable def starParity (t : ℕ) : TemplateVertex t → Bit := + fun a => if ∃ i : Fin t, i.val = 0 ∧ a = .inl i then 1 else 0 + +noncomputable def zeroLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (fun _ => 0) + +noncomputable def starLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (starParity t) + +inductive Convention | joint | separate + deriving DecidableEq + +def bagParameter (c : Convention) (k : ℕ) : ℕ := + match c with | .joint => k + 1 | .separate => k + +def detectionRound : Convention → ℕ | .joint => 2 | .separate => 1 + +def orderFactor (t : ℕ) : ℕ := + t * 2 ^ (t - 2 + 3 * (t - 1).choose 2) + 12 * t.choose 3 + +abbrev AtomicType (k : ℕ) := Fin k → Fin k → Bool × Bool + +def JointColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => JointColor k r × Multiset (Fin k → JointColor k r) + +def SeparateColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => SeparateColor k r × (Fin k → Multiset (SeparateColor k r)) + +noncomputable def atomicType {V : Type} (G : SimpleGraph V) {k : ℕ} + (x : Fin k → V) : AtomicType k := by + classical + exact fun i j => (decide (x i = x j), decide (G.Adj (x i) (x j))) + +noncomputable def jointColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → JointColor k r + | 0, x => atomicType G x + | r + 1, x => (jointColor G k r x, + Finset.univ.val.map (fun y => fun i => jointColor G k r (Function.update x i y))) + +noncomputable def separateColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → SeparateColor k r + | 0, x => atomicType G x + | r + 1, x => (separateColor G k r x, + fun i => Finset.univ.val.map (fun y => separateColor G k r (Function.update x i y))) + +noncomputable def sameHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => Finset.univ.val.map (jointColor G k r) = + Finset.univ.val.map (jointColor H k r) + | .separate => Finset.univ.val.map (separateColor G k r) = + Finset.univ.val.map (separateColor H k r) + +noncomputable def samePureHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => + Finset.univ.val.map (fun x : Fin k → V => jointColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => jointColor (G.sum H) k r (Sum.inr ∘ x)) + | .separate => + Finset.univ.val.map (fun x : Fin k → V => separateColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => separateColor (G.sum H) k r (Sum.inr ∘ x)) + +noncomputable def WLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, sameHistogram G H c k r + +noncomputable def PureWLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, samePureHistogram G H c k r + +noncomputable def ParityReductionStatement : Prop := + ∀ (k : ℕ), 4 ≤ k → ∀ c : Convention, ∀ C : ChoiceSystem (bagParameter c k), + let T := template (bagParameter c k) + let G := baseGraph C + let τ := baseProjection C + let V₀ := LiftVertex T G τ (fun _ => 0) + let V₁ := LiftVertex T G τ (starParity (bagParameter c k)) + Fintype.card V₀ = Fintype.card V₁ ∧ + (∀ A : ℕ, 1 ≤ A → C.SizeAtMost A → Fintype.card V₀ ≤ A * orderFactor (bagParameter c k)) ∧ + (WLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (PureWLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (C.Successful → ¬ sameHistogram (zeroLift C) (starLift C) c k (detectionRound c) ∧ + ¬ samePureHistogram (zeroLift C) (starLift C) c k (detectionRound c)) + +theorem parity_reduction : ParityReductionStatement := by + sorry + +end ParityWL + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ParityLifts.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ParityWL.parity_reduction` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/parity-lifts/solution/closure.txt b/tasks/parity-lifts/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d2eec69634a6032251c52e092307e6077232701f --- /dev/null +++ b/tasks/parity-lifts/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.Combinatorics.ParityLifts.BagTrees +OAI.Combinatorics.ParityLifts.BalancedBags +OAI.Combinatorics.ParityLifts.BaseLabels +OAI.Combinatorics.ParityLifts.ChoiceExtraction +OAI.Combinatorics.ParityLifts.ColorSpan +OAI.Combinatorics.ParityLifts.DecompositionCuts +OAI.Combinatorics.ParityLifts.Detection +OAI.Combinatorics.ParityLifts.GlueTrees +OAI.Combinatorics.ParityLifts.GlueVertices +OAI.Combinatorics.ParityLifts.Interpolation +OAI.Combinatorics.ParityLifts.LiftCounts +OAI.Combinatorics.ParityLifts.Main +OAI.Combinatorics.ParityLifts.Masses +OAI.Combinatorics.ParityLifts.Model +OAI.Combinatorics.ParityLifts.PureComponents +OAI.Combinatorics.ParityLifts.RankedTrees +OAI.Combinatorics.ParityLifts.Rerooting +OAI.Combinatorics.ParityLifts.RootedTests +OAI.Combinatorics.ParityLifts.TagSizes +OAI.Combinatorics.ParityLifts.TestAlgebra +OAI.Combinatorics.ParityLifts.WeightedDual +OAI.Combinatorics.ParityLifts.Witnesses diff --git a/tasks/parity-lifts/solution/reference.py b/tasks/parity-lifts/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/parity-lifts/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/parity-lifts/solution/solve.sh b/tasks/parity-lifts/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c30a78a88f09002a5da025cba349b33cee45877d --- /dev/null +++ b/tasks/parity-lifts/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ParityLifts, i.e. module OAI.Combinatorics.ParityLifts.Main and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ParityLifts.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ParityLifts" diff --git a/tasks/parity-lifts/task.toml b/tasks/parity-lifts/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca7037b2f5ba6196ec46930e53cab407377549e8 --- /dev/null +++ b/tasks/parity-lifts/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/parity-lifts" +version = "1.0.0" +description = "Prove ParityLifts (openai/math family 133: The complexity of Weisfeiler–Leman refinement) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ParityLifts.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ParityLifts" +family = "133" +family_title = "The complexity of Weisfeiler–Leman refinement" +subject = "Theoretical computer science" +theorems = ["OAI.ParityWL.parity_reduction"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ParityLifts.Main" +reference_modules = 22 +reference_lean_bytes = 181099 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 839 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11862 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/parity-lifts/tests/Challenge.lean b/tasks/parity-lifts/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2ddf367a6965bf8e7bf4de999b50531ecf83545c --- /dev/null +++ b/tasks/parity-lifts/tests/Challenge.lean @@ -0,0 +1,209 @@ +import Mathlib + +namespace OAI + + + +namespace ParityWL + +open scoped BigOperators + +abbrev Bit := ZMod 2 +abbrev MainPair (t : ℕ) := {p : Fin t × Fin t // p.1 < p.2} +abbrev Helper (t : ℕ) := + {q : MainPair t × Fin t // q.2 ≠ q.1.1.1 ∧ q.2 ≠ q.1.1.2} +abbrev TemplateVertex (t : ℕ) := Fin t ⊕ Helper t + +structure ChoiceSystem (t : ℕ) where + Domain : Fin t → Type + domainFintype : ∀ i, Fintype (Domain i) + Label : MainPair t → Type + labelFintype : ∀ p, Fintype (Label p) + leftLabel : (p : MainPair t) → Domain p.1.1 → Label p + rightLabel : (p : MainPair t) → Domain p.1.2 → Label p + +attribute [instance] ChoiceSystem.domainFintype ChoiceSystem.labelFintype + +def ChoiceSystem.Successful {t : ℕ} (C : ChoiceSystem t) : Prop := + ∃ d : (i : Fin t) → C.Domain i, + ∀ p : MainPair t, C.leftLabel p (d p.1.1) = C.rightLabel p (d p.1.2) + +def ChoiceSystem.SizeAtMost {t : ℕ} (C : ChoiceSystem t) (A : ℕ) : Prop := + (∀ i, Fintype.card (C.Domain i) ≤ A) ∧ (∀ p, Fintype.card (C.Label p) ≤ A) + +def helperIncident {t : ℕ} (h : Helper t) (i : Fin t) : Prop := + i = h.1.1.1.1 ∨ i = h.1.1.1.2 ∨ i = h.1.2 + +def templateAdj {t : ℕ} : TemplateVertex t → TemplateVertex t → Prop + | .inl i, .inl j => i ≠ j + | .inl i, .inr h => helperIncident h i + | .inr h, .inl i => helperIncident h i + | .inr _, .inr _ => False + +def template (t : ℕ) : SimpleGraph (TemplateVertex t) where + Adj := templateAdj + symm := ⟨by + intro x y h + cases x <;> cases y <;> simp_all [templateAdj, ne_comm]⟩ + loopless := ⟨by + intro x + cases x <;> simp [templateAdj]⟩ + +abbrev BaseVertex {t : ℕ} (C : ChoiceSystem t) := + ((i : Fin t) × C.Domain i) ⊕ ((h : Helper t) × C.Label h.1.1) + +def baseType {t : ℕ} {C : ChoiceSystem t} : BaseVertex C → TemplateVertex t + | .inl x => .inl x.1 + | .inr x => .inr x.1 + +inductive BaseArc {t : ℕ} (C : ChoiceSystem t) : BaseVertex C → BaseVertex C → Prop + | main (p : MainPair t) (d : C.Domain p.1.1) (e : C.Domain p.1.2) + (h : C.leftLabel p d = C.rightLabel p e) : + BaseArc C (.inl ⟨p.1.1, d⟩) (.inl ⟨p.1.2, e⟩) + | left (h : Helper t) (d : C.Domain h.1.1.1.1) : + BaseArc C (.inr ⟨h, C.leftLabel h.1.1 d⟩) (.inl ⟨h.1.1.1.1, d⟩) + | right (h : Helper t) (e : C.Domain h.1.1.1.2) : + BaseArc C (.inr ⟨h, C.rightLabel h.1.1 e⟩) (.inl ⟨h.1.1.1.2, e⟩) + | third (h : Helper t) (q : C.Label h.1.1) (f : C.Domain h.1.2) : + BaseArc C (.inr ⟨h, q⟩) (.inl ⟨h.1.2, f⟩) + +def baseGraph {t : ℕ} (C : ChoiceSystem t) : SimpleGraph (BaseVertex C) := + SimpleGraph.fromRel (BaseArc C) + +def baseProjection {t : ℕ} (C : ChoiceSystem t) : baseGraph C →g template t where + toFun := baseType + map_rel' := by + intro x y h + have arc : ∀ u v, BaseArc C u v → (template t).Adj (baseType u) (baseType v) := by + intro u v huv + cases huv with + | main p d e he => exact ne_of_lt p.property + | left h d => exact Or.inl rfl + | right h e => exact Or.inr (Or.inl rfl) + | third h q f => exact Or.inr (Or.inr rfl) + rcases h.2 with hxy | hyx + · exact arc x y hxy + · exact (arc y x hyx).symm + +section Lifts + +variable {A V : Type} [Fintype A] (T : SimpleGraph A) (G : SimpleGraph V) + +noncomputable def Tag (b : A → Bit) (a : A) := by + classical + exact {z : T.neighborSet a → Bit // ∑ v, z v = b a} + +noncomputable instance tagFintype (b : A → Bit) (a : A) : Fintype (Tag T b a) := by + classical + unfold Tag + infer_instance + +abbrev LiftVertex (τ : G →g T) (b : A → Bit) := (u : V) × Tag T b (τ u) + +noncomputable def liftGraph (τ : G →g T) (b : A → Bit) : + SimpleGraph (LiftVertex T G τ b) where + Adj u v := ∃ h : G.Adj u.1 v.1, + u.2.1 ⟨τ v.1, τ.map_adj h⟩ = v.2.1 ⟨τ u.1, τ.map_adj h.symm⟩ + symm := ⟨by + intro u v h + rcases h with ⟨h, e⟩ + exact ⟨h.symm, e.symm⟩⟩ + loopless := ⟨by + intro u h + exact G.irrefl h.1⟩ + +end Lifts + +noncomputable def starParity (t : ℕ) : TemplateVertex t → Bit := + fun a => if ∃ i : Fin t, i.val = 0 ∧ a = .inl i then 1 else 0 + +noncomputable def zeroLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (fun _ => 0) + +noncomputable def starLift {t : ℕ} (C : ChoiceSystem t) := + liftGraph (template t) (baseGraph C) (baseProjection C) (starParity t) + +inductive Convention | joint | separate + deriving DecidableEq + +def bagParameter (c : Convention) (k : ℕ) : ℕ := + match c with | .joint => k + 1 | .separate => k + +def detectionRound : Convention → ℕ | .joint => 2 | .separate => 1 + +def orderFactor (t : ℕ) : ℕ := + t * 2 ^ (t - 2 + 3 * (t - 1).choose 2) + 12 * t.choose 3 + +abbrev AtomicType (k : ℕ) := Fin k → Fin k → Bool × Bool + +def JointColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => JointColor k r × Multiset (Fin k → JointColor k r) + +def SeparateColor (k : ℕ) : ℕ → Type + | 0 => AtomicType k + | r + 1 => SeparateColor k r × (Fin k → Multiset (SeparateColor k r)) + +noncomputable def atomicType {V : Type} (G : SimpleGraph V) {k : ℕ} + (x : Fin k → V) : AtomicType k := by + classical + exact fun i j => (decide (x i = x j), decide (G.Adj (x i) (x j))) + +noncomputable def jointColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → JointColor k r + | 0, x => atomicType G x + | r + 1, x => (jointColor G k r x, + Finset.univ.val.map (fun y => fun i => jointColor G k r (Function.update x i y))) + +noncomputable def separateColor {V : Type} [Fintype V] (G : SimpleGraph V) (k : ℕ) : + (r : ℕ) → (Fin k → V) → SeparateColor k r + | 0, x => atomicType G x + | r + 1, x => (separateColor G k r x, + fun i => Finset.univ.val.map (fun y => separateColor G k r (Function.update x i y))) + +noncomputable def sameHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => Finset.univ.val.map (jointColor G k r) = + Finset.univ.val.map (jointColor H k r) + | .separate => Finset.univ.val.map (separateColor G k r) = + Finset.univ.val.map (separateColor H k r) + +noncomputable def samePureHistogram {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k r : ℕ) : Prop := + match c with + | .joint => + Finset.univ.val.map (fun x : Fin k → V => jointColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => jointColor (G.sum H) k r (Sum.inr ∘ x)) + | .separate => + Finset.univ.val.map (fun x : Fin k → V => separateColor (G.sum H) k r (Sum.inl ∘ x)) = + Finset.univ.val.map (fun x : Fin k → W => separateColor (G.sum H) k r (Sum.inr ∘ x)) + +noncomputable def WLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, sameHistogram G H c k r + +noncomputable def PureWLEquivalent {V W : Type} [Fintype V] [Fintype W] + (G : SimpleGraph V) (H : SimpleGraph W) (c : Convention) (k : ℕ) : Prop := + ∀ r, samePureHistogram G H c k r + +noncomputable def ParityReductionStatement : Prop := + ∀ (k : ℕ), 4 ≤ k → ∀ c : Convention, ∀ C : ChoiceSystem (bagParameter c k), + let T := template (bagParameter c k) + let G := baseGraph C + let τ := baseProjection C + let V₀ := LiftVertex T G τ (fun _ => 0) + let V₁ := LiftVertex T G τ (starParity (bagParameter c k)) + Fintype.card V₀ = Fintype.card V₁ ∧ + (∀ A : ℕ, 1 ≤ A → C.SizeAtMost A → Fintype.card V₀ ≤ A * orderFactor (bagParameter c k)) ∧ + (WLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (PureWLEquivalent (zeroLift C) (starLift C) c k ↔ ¬ C.Successful) ∧ + (C.Successful → ¬ sameHistogram (zeroLift C) (starLift C) c k (detectionRound c) ∧ + ¬ samePureHistogram (zeroLift C) (starLift C) c k (detectionRound c)) + +theorem parity_reduction : ParityReductionStatement := by + sorry + +end ParityWL + +end OAI diff --git a/tasks/parity-lifts/tests/grade.py b/tasks/parity-lifts/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/parity-lifts/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/parity-lifts/tests/task.json b/tasks/parity-lifts/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3484ac5e46e2ed0aabd15a200b27fae5c6b9bf59 --- /dev/null +++ b/tasks/parity-lifts/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ParityLifts", + "comparator": { + "theorem_names": [ + "OAI.ParityWL.parity_reduction" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10962 +} \ No newline at end of file diff --git a/tasks/parity-lifts/tests/test.sh b/tasks/parity-lifts/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/parity-lifts/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/partial-permutation/environment/Dockerfile b/tasks/partial-permutation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/partial-permutation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/partial-permutation/environment/fetch_mathlib.sh b/tasks/partial-permutation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/partial-permutation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/partial-permutation/environment/lake-manifest.json b/tasks/partial-permutation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/partial-permutation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/partial-permutation/environment/lakefile.lean b/tasks/partial-permutation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/partial-permutation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/partial-permutation/environment/lean_setup.sh b/tasks/partial-permutation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/partial-permutation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/partial-permutation/environment/pack_submission.py b/tasks/partial-permutation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/partial-permutation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/partial-permutation/instruction.md b/tasks/partial-permutation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ab4253864349c0d6f939309ae2e658e468cd608f --- /dev/null +++ b/tasks/partial-permutation/instruction.md @@ -0,0 +1,167 @@ +# openai/math challenge `PartialPermutation` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `PartialPermutation`, also at `/opt/openai-math/challenges/PartialPermutation.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped Classical BigOperators ComplexConjugate MonoidAlgebra +namespace PartialPermutation +noncomputable section + +def IsUnitary {G V : Type*} [Group G] [NormedAddCommGroup V] + [InnerProductSpace ℂ V] (ρ : Representation ℂ G V) : Prop := + ∀ g x y, inner ℂ (ρ g x) (ρ g y) = inner ℂ x y + +section +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] +def hsNormSq (A : Module.End ℂ V) : ℝ := + (LinearMap.trace ℂ V (LinearMap.adjoint A * A)).re + +end + +def complexFourier {G V : Type*} [Group G] [Fintype G] [AddCommGroup V] [Module ℂ V] + (ρ : Representation ℂ G V) (f : G → ℂ) : Module.End ℂ V := ∑ g, f g • ρ g + +section +variable {G V : Type*} [Group G] [Fintype G] [AddCommGroup V] [Module ℂ V] + [FiniteDimensional ℂ V] (ρ : Representation ℂ G V) +noncomputable def componentSimple (c : isotypicComponents ℂ[G] ρ.asModule) : + Submodule ℂ[G] ρ.asModule := c.property.choose + +instance components_finite : Finite (isotypicComponents ℂ[G] ρ.asModule) := by + let : IsNoetherian ℂ[G] ρ.asModule := isNoetherian_of_tower ℂ inferInstance + infer_instance + +end + +section +variable (G : Type*) [Group G] [Fintype G] +def regularRep : Representation ℂ G (EuclideanSpace ℂ G) where + toFun g := + { toFun := fun f => WithLp.toLp 2 (fun h => f (g⁻¹ * h)) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext f h; simp + map_mul' := by + intro x y + ext f h + change f ((x * y)⁻¹ * h) = f (y⁻¹ * (x⁻¹ * h)) + simp [mul_assoc] + +end + +section +variable {G : Type*} [Group G] [Fintype G] +abbrev IrreducibleIndex (G : Type*) [Group G] [Fintype G] := + isotypicComponents ℂ[G] (regularRep G).asModule + +noncomputable instance irreducibleIndex_fintype : Fintype (IrreducibleIndex G) := + Fintype.ofFinite _ + +abbrev irreducibleSpace (c : IrreducibleIndex G) := + (Subrepresentation.ofSubmodule' (componentSimple (regularRep G) c)).toSubmodule + +abbrev irreducibleDegree (c : IrreducibleIndex G) := Module.finrank ℂ (irreducibleSpace c) + +end + +def mass {G : Type*} [Fintype G] (f : G → ℝ) : ℝ := ∑ g, f g + +def LeftCosetCap {G : Type*} [Group G] [Fintype G] + (f : G → ℝ) (H : Subgroup G) (B : ℝ) : Prop := + by classical exact ∀ g, ∑ h : H, f (g * h) ≤ B / H.index + +def blockSubgroup {X : Type*} (M : Set X) : Subgroup (Equiv.Perm X) where + carrier := {g | ∀ x, x ∉ M → g x = x} + one_mem' := by simp + mul_mem' := by + intro g h hg hh x hx + simp only [Set.mem_ofPred_eq] at hg hh ⊢ + simp [Equiv.Perm.mul_apply, hh x hx, hg x hx] + inv_mem' := by + intro g hg x hx + exact ((Equiv.eq_symm_apply g).mpr (hg x hx)).symm + +def inverseDegreeSum (G : Type*) [Group G] [Fintype G] (u : ℝ) : ℝ := + ∑ c : IrreducibleIndex G, (irreducibleDegree c : ℝ)^(-u) + +def symmetricInverseDegreeSum (n : ℕ) (u : ℝ) : ℝ := + inverseDegreeSum (Equiv.Perm (Fin n)) u + +def symmetricDegreeConstant (u : ℝ) : ℝ := + sSup {x : ℝ | ∃ n : ℕ, 1 ≤ n ∧ x = symmetricInverseDegreeSum n u} + +def ComplementaryCosetsFiniteStatement : Prop := + ∀ (X : Type*) [Fintype X] [DecidableEq X] (b : ℕ) (_ : 0 < b) (M : Fin b → Set X), + (∀ i, (M i).Nonempty) → + Pairwise (fun i j => Disjoint (M i) (M j)) → (⋃ i, M i) = Set.univ → + ∀ (V : Type) [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (ρ : Representation ℂ (Equiv.Perm X) V), + Representation.IsIrreducible ρ → IsUnitary ρ → + ∀ (f : Equiv.Perm X → ℝ) (B u : ℝ), + (∀ g, 0 ≤ f g) → mass f ≤ 1 → 0 < u → + (∀ i, LeftCosetCap f (blockSubgroup (M i)) B) → + (hsNormSq (complexFourier ρ (fun g => f g)) ≤ + b * B * symmetricDegreeConstant u * + (Module.finrank ℂ V : ℝ)^(-1+(u+2)/(b : ℝ))) ∧ + (‖LinearMap.toContinuousLinearMap (complexFourier ρ (fun g => f g))‖^2 ≤ + b * B * symmetricDegreeConstant u * + (Module.finrank ℂ V : ℝ)^(-1+(u+2)/(b : ℝ))) + +theorem complementaryCosets_finite : ComplementaryCosetsFiniteStatement := by + sorry + +end +end PartialPermutation + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PartialPermutation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PartialPermutation.complementaryCosets_finite` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/partial-permutation/solution/closure.txt b/tasks/partial-permutation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4810e8fff66c7381c6f7ab334c9291562989b3f3 --- /dev/null +++ b/tasks/partial-permutation/solution/closure.txt @@ -0,0 +1,62 @@ +OAI.RepresentationTheory.PartialPermutation.AlternatingTabloids +OAI.RepresentationTheory.PartialPermutation.BlockSubgroups +OAI.RepresentationTheory.PartialPermutation.CentralKernels +OAI.RepresentationTheory.PartialPermutation.Characters +OAI.RepresentationTheory.PartialPermutation.ClassCharacters +OAI.RepresentationTheory.PartialPermutation.ColumnRearrangement +OAI.RepresentationTheory.PartialPermutation.ColumnSorting +OAI.RepresentationTheory.PartialPermutation.CompleteKernels +OAI.RepresentationTheory.PartialPermutation.ComponentGeometry +OAI.RepresentationTheory.PartialPermutation.Components +OAI.RepresentationTheory.PartialPermutation.ConjugacyCounts +OAI.RepresentationTheory.PartialPermutation.ConvolutionKernels +OAI.RepresentationTheory.PartialPermutation.CosetCaps +OAI.RepresentationTheory.PartialPermutation.CrossTableaux +OAI.RepresentationTheory.PartialPermutation.DeficitCounts +OAI.RepresentationTheory.PartialPermutation.DeficitPlancherel +OAI.RepresentationTheory.PartialPermutation.DegreeEstimates +OAI.RepresentationTheory.PartialPermutation.DegreeTransfer +OAI.RepresentationTheory.PartialPermutation.DiagonalBounds +OAI.RepresentationTheory.PartialPermutation.DiagramCounts +OAI.RepresentationTheory.PartialPermutation.Equivalences +OAI.RepresentationTheory.PartialPermutation.FillingExtensions +OAI.RepresentationTheory.PartialPermutation.FourierBessel +OAI.RepresentationTheory.PartialPermutation.HilbertSchmidt +OAI.RepresentationTheory.PartialPermutation.Interleavings +OAI.RepresentationTheory.PartialPermutation.IsotypicKernels +OAI.RepresentationTheory.PartialPermutation.IsotypicMatrices +OAI.RepresentationTheory.PartialPermutation.IsotypicProjections +OAI.RepresentationTheory.PartialPermutation.JointKernels +OAI.RepresentationTheory.PartialPermutation.Main +OAI.RepresentationTheory.PartialPermutation.MatrixCoefficients +OAI.RepresentationTheory.PartialPermutation.MatrixDegrees +OAI.RepresentationTheory.PartialPermutation.Model +OAI.RepresentationTheory.PartialPermutation.ModuleTransport +OAI.RepresentationTheory.PartialPermutation.NormBounds +OAI.RepresentationTheory.PartialPermutation.OperatorNorm +OAI.RepresentationTheory.PartialPermutation.PartitionAsymptotics +OAI.RepresentationTheory.PartialPermutation.Plancherel +OAI.RepresentationTheory.PartialPermutation.Polytabloids +OAI.RepresentationTheory.PartialPermutation.ProjectionCovers +OAI.RepresentationTheory.PartialPermutation.ProjectionEnergy +OAI.RepresentationTheory.PartialPermutation.RankFillings +OAI.RepresentationTheory.PartialPermutation.ReciprocalBounds +OAI.RepresentationTheory.PartialPermutation.ReciprocalTransfer +OAI.RepresentationTheory.PartialPermutation.RegularRepresentation +OAI.RepresentationTheory.PartialPermutation.Restriction +OAI.RepresentationTheory.PartialPermutation.RowBounds +OAI.RepresentationTheory.PartialPermutation.SchurAverage +OAI.RepresentationTheory.PartialPermutation.SmallKernels +OAI.RepresentationTheory.PartialPermutation.SpechtClassification +OAI.RepresentationTheory.PartialPermutation.SpechtDimension +OAI.RepresentationTheory.PartialPermutation.SpechtModules +OAI.RepresentationTheory.PartialPermutation.SpechtShapes +OAI.RepresentationTheory.PartialPermutation.StandardTableaux +OAI.RepresentationTheory.PartialPermutation.SymmetricTransfer +OAI.RepresentationTheory.PartialPermutation.TableauLimits +OAI.RepresentationTheory.PartialPermutation.TableauVectors +OAI.RepresentationTheory.PartialPermutation.TableauWeights +OAI.RepresentationTheory.PartialPermutation.Tabloids +OAI.RepresentationTheory.PartialPermutation.TailBounds +OAI.RepresentationTheory.PartialPermutation.TrivialRepresentation +OAI.RepresentationTheory.PartialPermutation.Truncation diff --git a/tasks/partial-permutation/solution/reference.py b/tasks/partial-permutation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/partial-permutation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/partial-permutation/solution/solve.sh b/tasks/partial-permutation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d323148bf26310d87c498f9c37bd98fcc49622db --- /dev/null +++ b/tasks/partial-permutation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PartialPermutation, i.e. module OAI.RepresentationTheory.PartialPermutation.Main and the +# 62 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RepresentationTheory.PartialPermutation.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PartialPermutation" diff --git a/tasks/partial-permutation/task.toml b/tasks/partial-permutation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3231987f8d8a7d76b17de0de69848edf65a68e7 --- /dev/null +++ b/tasks/partial-permutation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/partial-permutation" +version = "1.0.0" +description = "Prove PartialPermutation (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PartialPermutation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PartialPermutation" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.PartialPermutation.complementaryCosets_finite"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RepresentationTheory.PartialPermutation.Main" +reference_modules = 62 +reference_lean_bytes = 245598 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 802 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11921 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/partial-permutation/tests/Challenge.lean b/tasks/partial-permutation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f52ccf0e636961d1d322176bab620b0a1170dd2e --- /dev/null +++ b/tasks/partial-permutation/tests/Challenge.lean @@ -0,0 +1,116 @@ +import Mathlib + +namespace OAI + +open scoped Classical BigOperators ComplexConjugate MonoidAlgebra +namespace PartialPermutation +noncomputable section + +def IsUnitary {G V : Type*} [Group G] [NormedAddCommGroup V] + [InnerProductSpace ℂ V] (ρ : Representation ℂ G V) : Prop := + ∀ g x y, inner ℂ (ρ g x) (ρ g y) = inner ℂ x y + +section +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] +def hsNormSq (A : Module.End ℂ V) : ℝ := + (LinearMap.trace ℂ V (LinearMap.adjoint A * A)).re + +end + +def complexFourier {G V : Type*} [Group G] [Fintype G] [AddCommGroup V] [Module ℂ V] + (ρ : Representation ℂ G V) (f : G → ℂ) : Module.End ℂ V := ∑ g, f g • ρ g + +section +variable {G V : Type*} [Group G] [Fintype G] [AddCommGroup V] [Module ℂ V] + [FiniteDimensional ℂ V] (ρ : Representation ℂ G V) +noncomputable def componentSimple (c : isotypicComponents ℂ[G] ρ.asModule) : + Submodule ℂ[G] ρ.asModule := c.property.choose + +instance components_finite : Finite (isotypicComponents ℂ[G] ρ.asModule) := by + let : IsNoetherian ℂ[G] ρ.asModule := isNoetherian_of_tower ℂ inferInstance + infer_instance + +end + +section +variable (G : Type*) [Group G] [Fintype G] +def regularRep : Representation ℂ G (EuclideanSpace ℂ G) where + toFun g := + { toFun := fun f => WithLp.toLp 2 (fun h => f (g⁻¹ * h)) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext f h; simp + map_mul' := by + intro x y + ext f h + change f ((x * y)⁻¹ * h) = f (y⁻¹ * (x⁻¹ * h)) + simp [mul_assoc] + +end + +section +variable {G : Type*} [Group G] [Fintype G] +abbrev IrreducibleIndex (G : Type*) [Group G] [Fintype G] := + isotypicComponents ℂ[G] (regularRep G).asModule + +noncomputable instance irreducibleIndex_fintype : Fintype (IrreducibleIndex G) := + Fintype.ofFinite _ + +abbrev irreducibleSpace (c : IrreducibleIndex G) := + (Subrepresentation.ofSubmodule' (componentSimple (regularRep G) c)).toSubmodule + +abbrev irreducibleDegree (c : IrreducibleIndex G) := Module.finrank ℂ (irreducibleSpace c) + +end + +def mass {G : Type*} [Fintype G] (f : G → ℝ) : ℝ := ∑ g, f g + +def LeftCosetCap {G : Type*} [Group G] [Fintype G] + (f : G → ℝ) (H : Subgroup G) (B : ℝ) : Prop := + by classical exact ∀ g, ∑ h : H, f (g * h) ≤ B / H.index + +def blockSubgroup {X : Type*} (M : Set X) : Subgroup (Equiv.Perm X) where + carrier := {g | ∀ x, x ∉ M → g x = x} + one_mem' := by simp + mul_mem' := by + intro g h hg hh x hx + simp only [Set.mem_ofPred_eq] at hg hh ⊢ + simp [Equiv.Perm.mul_apply, hh x hx, hg x hx] + inv_mem' := by + intro g hg x hx + exact ((Equiv.eq_symm_apply g).mpr (hg x hx)).symm + +def inverseDegreeSum (G : Type*) [Group G] [Fintype G] (u : ℝ) : ℝ := + ∑ c : IrreducibleIndex G, (irreducibleDegree c : ℝ)^(-u) + +def symmetricInverseDegreeSum (n : ℕ) (u : ℝ) : ℝ := + inverseDegreeSum (Equiv.Perm (Fin n)) u + +def symmetricDegreeConstant (u : ℝ) : ℝ := + sSup {x : ℝ | ∃ n : ℕ, 1 ≤ n ∧ x = symmetricInverseDegreeSum n u} + +def ComplementaryCosetsFiniteStatement : Prop := + ∀ (X : Type*) [Fintype X] [DecidableEq X] (b : ℕ) (_ : 0 < b) (M : Fin b → Set X), + (∀ i, (M i).Nonempty) → + Pairwise (fun i j => Disjoint (M i) (M j)) → (⋃ i, M i) = Set.univ → + ∀ (V : Type) [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (ρ : Representation ℂ (Equiv.Perm X) V), + Representation.IsIrreducible ρ → IsUnitary ρ → + ∀ (f : Equiv.Perm X → ℝ) (B u : ℝ), + (∀ g, 0 ≤ f g) → mass f ≤ 1 → 0 < u → + (∀ i, LeftCosetCap f (blockSubgroup (M i)) B) → + (hsNormSq (complexFourier ρ (fun g => f g)) ≤ + b * B * symmetricDegreeConstant u * + (Module.finrank ℂ V : ℝ)^(-1+(u+2)/(b : ℝ))) ∧ + (‖LinearMap.toContinuousLinearMap (complexFourier ρ (fun g => f g))‖^2 ≤ + b * B * symmetricDegreeConstant u * + (Module.finrank ℂ V : ℝ)^(-1+(u+2)/(b : ℝ))) + +theorem complementaryCosets_finite : ComplementaryCosetsFiniteStatement := by + sorry + +end +end PartialPermutation + +end OAI diff --git a/tasks/partial-permutation/tests/grade.py b/tasks/partial-permutation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/partial-permutation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/partial-permutation/tests/task.json b/tasks/partial-permutation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..744a1bc6ca599371e4345b53b3888483ce2a3648 --- /dev/null +++ b/tasks/partial-permutation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PartialPermutation", + "comparator": { + "theorem_names": [ + "OAI.PartialPermutation.complementaryCosets_finite" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11021 +} \ No newline at end of file diff --git a/tasks/partial-permutation/tests/test.sh b/tasks/partial-permutation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/partial-permutation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/partition-consistency/environment/Dockerfile b/tasks/partition-consistency/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/partition-consistency/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/partition-consistency/environment/fetch_mathlib.sh b/tasks/partition-consistency/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/partition-consistency/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/partition-consistency/environment/lake-manifest.json b/tasks/partition-consistency/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/partition-consistency/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/partition-consistency/environment/lakefile.lean b/tasks/partition-consistency/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/partition-consistency/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/partition-consistency/environment/lean_setup.sh b/tasks/partition-consistency/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/partition-consistency/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/partition-consistency/environment/pack_submission.py b/tasks/partition-consistency/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/partition-consistency/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/partition-consistency/instruction.md b/tasks/partition-consistency/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..eea3153dbeb83f3c819214a0f84d5131cf7f7072 --- /dev/null +++ b/tasks/partition-consistency/instruction.md @@ -0,0 +1,375 @@ +# openai/math challenge `PartitionConsistency` (family 244) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 244 of the release, *The partition principle does not imply choice* +(Mathematical logic). The family as a whole: Assuming ZF is consistent, constructs a model in which every surjective image of a set injects into that set, yet the axiom of choice fails. Choice for ordinal-indexed families still holds. From any countable transitive model of ZFC, a separate construction gives a transitive symmetric extension with these properties and no new countable sequences of ground-model elements. + +The challenge is `PartitionConsistency`, also at `/opt/openai-math/challenges/PartitionConsistency.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PartitionConsistency + +/-- Pure first-order membership syntax with equality. `n` variables are in scope. +A quantifier binds the last variable in its body. There are no atoms/urelements, +function symbols, constants, semantic predicates, or mathematical assumptions +in this syntax. -/ +inductive Formula : ℕ → Type where + | bot {n} : Formula n + | mem {n} (x y : Fin n) : Formula n + | equal {n} (x y : Fin n) : Formula n + | imp {n} (p q : Formula n) : Formula n + | conj {n} (p q : Formula n) : Formula n + | disj {n} (p q : Formula n) : Formula n + | all {n} (p : Formula (n + 1)) : Formula n + | ex {n} (p : Formula (n + 1)) : Formula n + +namespace Formula + +abbrev neg {n} (p : Formula n) : Formula n := p.imp .bot +abbrev iff {n} (p q : Formula n) : Formula n := (p.imp q).conj (q.imp p) + +/-- Under a binder, a renaming leaves the newly bound variable bound. -/ +def liftRen {n m} (r : Fin n → Fin m) : Fin (n + 1) → Fin (m + 1) := + Fin.lastCases (Fin.last m) (fun i => (r i).castSucc) + +/-- Capture-avoiding renaming; in this relational language all terms are variables. -/ +def rename {n m} (r : Fin n → Fin m) : Formula n → Formula m + | .bot => .bot + | .mem x y => .mem (r x) (r y) + | .equal x y => .equal (r x) (r y) + | .imp p q => .imp (rename r p) (rename r q) + | .conj p q => .conj (rename r p) (rename r q) + | .disj p q => .disj (rename r p) (rename r q) + | .all p => .all (rename (liftRen r) p) + | .ex p => .ex (rename (liftRen r) p) + +abbrev raise {n} (p : Formula n) : Formula (n + 1) := rename Fin.castSucc p + +/-- Substitution of a variable term for the variable just quantified. -/ +def instantiate {n} (p : Formula (n + 1)) (x : Fin n) : Formula n := + rename (Fin.lastCases x id) p + +/-- Universal closure of all the free variables. -/ +def close : {n : ℕ} → Formula n → Formula 0 + | 0, p => p + | _ + 1, p => close (.all p) + +end Formula + +abbrev Sentence := Formula 0 +abbrev Theory := Set Sentence + +/-- Classical first-order natural deduction with equality. Hypotheses may be an +infinite theory, but a derivation is a finite inductive proof. The `allI` and +`exE` rules use a fresh last variable, and shift all assumptions to avoid +capture. We allow finitely many free variables in proofs of closed sentences. -/ +inductive Derives : {n : ℕ} → Set (Formula n) → Formula n → Prop where + | hyp {n} {Γ : Set (Formula n)} {p} : p ∈ Γ → Derives Γ p + | weaken {n} {Γ Δ : Set (Formula n)} {p} : + Γ ⊆ Δ → Derives Γ p → Derives Δ p + | impI {n} {Γ : Set (Formula n)} {p q} : + Derives (insert p Γ) q → Derives Γ (.imp p q) + | impE {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.imp p q) → Derives Γ p → Derives Γ q + | botE {n} {Γ : Set (Formula n)} {p} : Derives Γ .bot → Derives Γ p + | classical {n} {Γ : Set (Formula n)} {p} : + Derives (insert p.neg Γ) .bot → Derives Γ p + | conjI {n} {Γ : Set (Formula n)} {p q} : + Derives Γ p → Derives Γ q → Derives Γ (.conj p q) + | conjL {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.conj p q) → Derives Γ p + | conjR {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.conj p q) → Derives Γ q + | disjL {n} {Γ : Set (Formula n)} {p q} : + Derives Γ p → Derives Γ (.disj p q) + | disjR {n} {Γ : Set (Formula n)} {p q} : + Derives Γ q → Derives Γ (.disj p q) + | disjE {n} {Γ : Set (Formula n)} {p q r} : + Derives Γ (.disj p q) → Derives (insert p Γ) r → + Derives (insert q Γ) r → Derives Γ r + | allI {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} : + Derives (Formula.raise '' Γ) p → Derives Γ (.all p) + | allE {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} (t : Fin n) : + Derives Γ (.all p) → Derives Γ (p.instantiate t) + | exI {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} (t : Fin n) : + Derives Γ (p.instantiate t) → Derives Γ (.ex p) + | exE {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} {q : Formula n} : + Derives Γ (.ex p) → Derives (insert p (Formula.raise '' Γ)) q.raise → + Derives Γ q + | eqRefl {n} {Γ : Set (Formula n)} (t : Fin n) : Derives Γ (.equal t t) + | eqSubst {n} {Γ : Set (Formula n)} {s t : Fin n} (p : Formula (n + 1)) : + Derives Γ (.equal s t) → Derives Γ (p.instantiate s) → + Derives Γ (p.instantiate t) + | rename {n m} {Γ : Set (Formula n)} {p : Formula n} (r : Fin n → Fin m) : + Derives Γ p → Derives (Formula.rename r '' Γ) (Formula.rename r p) + +/-- Sentences are usable as open hypotheses with any finite supply of variables. -/ +def Theory.at (T : Theory) (n : ℕ) : Set (Formula n) := + Formula.rename Fin.elim0 '' T + +/-- Ordinary syntactic consistency: there is no finite natural-deduction proof +of falsity from the theory, with any finite supply of free variables. -/ +def Consistent (T : Theory) : Prop := ∀ n, ¬ Derives (T.at n) .bot + +namespace SetLanguage +open Formula + +/-! All abbreviations in this namespace expand to formulas of the pure language +of equality and membership. Functions are sets of Kuratowski pairs *inside the +structure*. In particular, no quantification over external Lean functions is +used in PP, Choice, or ordinal-indexed Choice. -/ + +/-- `a ⊆ b`. -/ +def subset {n} (a b : Fin n) : Formula n := + rename ![a, b] (Formula.all ((Formula.mem 2 0).imp (Formula.mem 2 1)) : Formula 2) + +/-- `a = ∅`. -/ +def empty {n} (a : Fin n) : Formula n := + rename ![a] (Formula.all (Formula.mem 1 0).neg : Formula 1) + +/-- `a ≠ ∅`, stated as existence of a member. -/ +def nonempty {n} (a : Fin n) : Formula n := + rename ![a] (Formula.ex (Formula.mem 1 0) : Formula 1) + +/-- `p = {x,y}`. -/ +def unorderedPair {n} (p x y : Fin n) : Formula n := + rename ![p, x, y] + (Formula.all ((Formula.mem 3 0).iff ((Formula.equal 3 1).disj (Formula.equal 3 2))) : Formula 3) + +/-- `b = a ∪ {a}`. -/ +def successor {n} (b a : Fin n) : Formula n := + rename ![b, a] + (Formula.all ((Formula.mem 2 0).iff ((Formula.mem 2 1).disj (Formula.equal 2 1))) : Formula 2) + +/-- Kuratowski ordered pair: `p = {{x},{x,y}}`. -/ +def orderedPair {n} (p x y : Fin n) : Formula n := + rename ![p, x, y] + (Formula.ex (Formula.ex ((unorderedPair 3 1 1).conj + ((unorderedPair 4 1 2).conj (unorderedPair 0 3 4)))) : Formula 3) + +/-- The internal graph relation `⟨x,y⟩ ∈ f`. -/ +def edge {n} (f x y : Fin n) : Formula n := + rename ![f, x, y] + (Formula.ex ((Formula.mem 3 0).conj (orderedPair 3 1 2)) : Formula 3) + +/-- `f` is a set graph of a function whose domain is exactly `d`. +The first conjunct excludes non-pairs and graph entries outside the domain; +the second conjunct asserts totality and single-valuedness. -/ +def functionOn {n} (f d : Fin n) : Formula n := + rename ![f, d] + ((Formula.all ((Formula.mem 2 0).imp + (Formula.ex (Formula.ex ((Formula.mem 3 1).conj (orderedPair 2 3 4)))))).conj + (Formula.all ((Formula.mem 2 1).imp + (Formula.ex ((edge 0 2 3).conj (Formula.all ((edge 0 2 4).imp (Formula.equal 4 3))))))) : Formula 2) + +/-- Internal set function `f : d → r`. -/ +def mapsTo {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 3 1).imp ((edge 0 3 4).imp (Formula.mem 4 2))))) : Formula 3) + +/-- Internal set surjection `f : d ↠ r`. -/ +def surjection {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((mapsTo 0 1 2).conj + (Formula.all ((Formula.mem 3 2).imp (Formula.ex ((Formula.mem 4 1).conj (edge 0 4 3))))) : Formula 3) + +/-- Internal set injection `f : d ↪ r`. -/ +def injection {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((mapsTo 0 1 2).conj + (Formula.all (Formula.all (.all + ((Formula.mem 3 1).imp ((Formula.mem 4 1).imp + (((edge 0 3 5).conj (edge 0 4 5)).imp (Formula.equal 3 4))))))) : Formula 3) + +/-- Transitivity of a set (not transitivity of the external structure). -/ +def transitiveSet {n} (a : Fin n) : Formula n := + rename ![a] + (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 1).imp (Formula.mem 2 0)))) : Formula 1) + +/-- Membership is an internal strict linear order on `a`. -/ +def membershipLinear {n} (a : Fin n) : Formula n := + rename ![a] + ((Formula.all ((Formula.mem 1 0).imp (Formula.mem 1 1).neg)).conj + ((Formula.all (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 0).imp ((Formula.mem 3 0).imp + (((Formula.mem 1 2).conj (Formula.mem 2 3)).imp (Formula.mem 1 3)))))))).conj + (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 0).imp + ((Formula.equal 1 2).disj ((Formula.mem 1 2).disj (Formula.mem 2 1)))))))) : Formula 1) + +/-- Every nonempty internal subset of `a` has a membership-minimal element. +This does NOT assert external well-foundedness of the relation. -/ +def membershipWellFounded {n} (a : Fin n) : Formula n := + rename ![a] + (Formula.all (((subset 1 0).conj (nonempty 1)).imp + (Formula.ex ((Formula.mem 2 1).conj (Formula.all ((Formula.mem 3 1).imp (Formula.mem 3 2).neg))))) : Formula 1) + +/-- A von Neumann ordinal: a transitive set internally wellordered by membership. -/ +def ordinal {n} (a : Fin n) : Formula n := + (transitiveSet a).conj ((membershipLinear a).conj (membershipWellFounded a)) + +/-- A choice function on the set `A` of nonempty sets. -/ +def choiceOn {n} (c A : Fin n) : Formula n := + rename ![c, A] + ((functionOn 0 1).conj + (Formula.all ((Formula.mem 2 1).imp (Formula.ex ((edge 0 2 3).conj (Formula.mem 3 2))))) : Formula 2) + +/-- A graph `F` coding a family of nonempty sets indexed by ordinal `η`. -/ +def nonemptyFamily {n} (F η : Fin n) : Formula n := + rename ![F, η] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 2 1).imp ((edge 0 2 3).imp (nonempty 3))))) : Formula 2) + +/-- `c(ξ) ∈ F(ξ)` for every `ξ ∈ η`, with `c` an internal function. -/ +def choiceForFamily {n} (c η F : Fin n) : Formula n := + rename ![c, η, F] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 3 1).imp ((edge 2 3 4).imp + (Formula.ex ((edge 0 3 5).conj (Formula.mem 5 4))))))) : Formula 3) + +/-- The Partition Principle. The reverse injection is not required to be a +section of the original surjection. Both `X` and `Y` range over all sets. -/ +def PP : Sentence := + Formula.all (Formula.all ((Formula.ex (surjection 2 0 1)).imp (Formula.ex (injection 2 1 0)))) + +/-- Ordinary Choice for every set of nonempty sets. -/ +def AC : Sentence := + Formula.all ((Formula.all ((Formula.mem 1 0).imp (nonempty 1))).imp (Formula.ex (choiceOn 1 0))) + +/-- Choice for every ordinal-indexed family of nonempty sets, including ordinals +which may fail to be well founded from outside a model. -/ +def ACwo : Sentence := + Formula.all ((ordinal 0).imp + (Formula.all ((nonemptyFamily 1 0).imp (Formula.ex (choiceForFamily 2 0 1))))) + +/-! Full pure-set ZF, not a finite fragment and not ZFA. -/ + +def extensionality : Sentence := + Formula.all (Formula.all ((Formula.all ((Formula.mem 2 0).iff (Formula.mem 2 1))).imp (Formula.equal 0 1))) + +def emptySet : Sentence := Formula.ex (empty 0) + +def pairing : Sentence := Formula.all (Formula.all (Formula.ex (unorderedPair 2 0 1))) + +def union : Sentence := + Formula.all (Formula.ex (Formula.all ((Formula.mem 2 1).iff (Formula.ex ((Formula.mem 3 0).conj (Formula.mem 2 3)))))) + +def powerSet : Sentence := Formula.all (Formula.ex (Formula.all ((Formula.mem 2 1).iff (subset 2 0)))) + +def infinity : Sentence := + Formula.ex ((Formula.ex ((Formula.mem 1 0).conj (empty 1))).conj + (Formula.all ((Formula.mem 1 0).imp (Formula.ex ((Formula.mem 2 0).conj (successor 2 1)))))) + +def foundation : Sentence := + Formula.all ((nonempty 0).imp + (Formula.ex ((Formula.mem 1 0).conj (Formula.all ((Formula.mem 2 1).imp (Formula.mem 2 0).neg))))) + +/-- The instance of Separation for an entirely arbitrary formula `p(params,x)`. +All parameters are universally closed. Neither the quantifier complexity of +`p` nor the number of parameters is bounded. -/ +def separation {n} (p : Formula (n + 1)) : Sentence := + let A : Fin (n + 3) := (Fin.last n).castSucc.castSucc + let B : Fin (n + 3) := (Fin.last (n + 1)).castSucc + let x : Fin (n + 3) := Fin.last (n + 2) + let r : Fin (n + 1) → Fin (n + 3) := + Fin.lastCases x (fun i => i.castSucc.castSucc.castSucc) + close (Formula.all (Formula.ex (Formula.all ((Formula.mem x B).iff ((Formula.mem x A).conj (rename r p)))))) + +/-- Substitution into a binary formula with `n` additional parameters. -/ +def relation {n m} (p : Formula (n + 2)) (params : Fin n → Fin m) (x y : Fin m) : + Formula m := + rename (Fin.lastCases y (Fin.lastCases x params)) p + +/-- The instance of Replacement for an entirely arbitrary formula +`p(params,x,y)`: if it is single-valued and total on `A`, its image is a set. +As with Separation, the parameters are all universally closed. -/ +def replacement {n} (p : Formula (n + 2)) : Sentence := + let unique : Formula (n + 3) := + Formula.all ((relation p (fun i => i.castSucc.castSucc.castSucc.castSucc) + (Fin.last (n + 1)).castSucc.castSucc (Fin.last (n + 3))).imp + (Formula.equal (Fin.last (n + 3)) (Fin.last (n + 2)).castSucc)) + let totalFunctional : Formula (n + 1) := + Formula.all ((Formula.mem (Fin.last (n + 1)) (Fin.last n).castSucc).imp + (Formula.ex ((relation p (fun i => i.castSucc.castSucc.castSucc) + (Fin.last (n + 1)).castSucc (Fin.last (n + 2))).conj unique))) + let image : Formula (n + 1) := + Formula.ex (Formula.all ((Formula.mem (Fin.last (n + 2)) (Fin.last (n + 1)).castSucc).iff + (Formula.ex ((Formula.mem (Fin.last (n + 3)) (Fin.last n).castSucc.castSucc.castSucc).conj + (relation p (fun i => i.castSucc.castSucc.castSucc.castSucc) + (Fin.last (n + 3)) (Fin.last (n + 2)).castSucc))))) + close (Formula.all (totalFunctional.imp image)) + +/-- Exactly the axioms and all schema instances of pure first-order ZF. -/ +inductive IsZFAxiom : Sentence → Prop where + | extensionality : IsZFAxiom extensionality + | emptySet : IsZFAxiom emptySet + | pairing : IsZFAxiom pairing + | union : IsZFAxiom union + | powerSet : IsZFAxiom powerSet + | infinity : IsZFAxiom infinity + | foundation : IsZFAxiom foundation + | separation {n} (p : Formula (n + 1)) : IsZFAxiom (separation p) + | replacement {n} (p : Formula (n + 2)) : IsZFAxiom (replacement p) + +/-- Zermelo–Fraenkel set theory, without Choice. -/ +def ZF : Theory := {p | IsZFAxiom p} + +/-- ZF with the Partition Principle, ordinal-indexed Choice and failure of Choice. -/ +def targetTheory : Theory := ZF ∪ {PP, ACwo, AC.neg} + +end SetLanguage + +/-- Relative consistency of ZF with the Partition Principle, ordinal-indexed +Choice and failure of Choice. -/ +theorem main_consistency : + Consistent SetLanguage.ZF → Consistent SetLanguage.targetTheory := by + sorry + +end PartitionConsistency + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PartitionConsistency.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PartitionConsistency.main_consistency` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/partition-consistency/solution/closure.txt b/tasks/partition-consistency/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f0762efc942bd07555c939ef11d33df1b338b726 --- /dev/null +++ b/tasks/partition-consistency/solution/closure.txt @@ -0,0 +1,75 @@ +OAI.SetTheory.PartitionConsistency.Algebra.ConservativeExtensions +OAI.SetTheory.PartitionConsistency.Algebra.DiagramOrder +OAI.SetTheory.PartitionConsistency.Algebra.DirectLimits +OAI.SetTheory.PartitionConsistency.Algebra.GateTowers +OAI.SetTheory.PartitionConsistency.Algebra.MergerCones +OAI.SetTheory.PartitionConsistency.Algebra.MergerWords +OAI.SetTheory.PartitionConsistency.Algebra.PersistentProfiles +OAI.SetTheory.PartitionConsistency.Algebra.PlacementExtensions +OAI.SetTheory.PartitionConsistency.Algebra.Placements +OAI.SetTheory.PartitionConsistency.Algebra.ProbeGates +OAI.SetTheory.PartitionConsistency.Algebra.ProbeMargins +OAI.SetTheory.PartitionConsistency.Algebra.ProbePresentations +OAI.SetTheory.PartitionConsistency.Algebra.ProbeWords +OAI.SetTheory.PartitionConsistency.Construction.BlockTowers +OAI.SetTheory.PartitionConsistency.Construction.CellCuts +OAI.SetTheory.PartitionConsistency.Construction.CellReorder +OAI.SetTheory.PartitionConsistency.Construction.CellTowers +OAI.SetTheory.PartitionConsistency.Construction.CompleteRounds +OAI.SetTheory.PartitionConsistency.Construction.ConservativeCells +OAI.SetTheory.PartitionConsistency.Construction.ConservativeHulls +OAI.SetTheory.PartitionConsistency.Construction.DiagramPlacements +OAI.SetTheory.PartitionConsistency.Construction.MergerPushouts +OAI.SetTheory.PartitionConsistency.Construction.MonoidBase +OAI.SetTheory.PartitionConsistency.Construction.MonoidRounds +OAI.SetTheory.PartitionConsistency.Construction.MonoidTowers +OAI.SetTheory.PartitionConsistency.Construction.SaturatedMonoids +OAI.SetTheory.PartitionConsistency.Forcing.AtomicForcing +OAI.SetTheory.PartitionConsistency.Forcing.ChoiceFailure +OAI.SetTheory.PartitionConsistency.Forcing.CohenForcing +OAI.SetTheory.PartitionConsistency.Forcing.Diagrams +OAI.SetTheory.PartitionConsistency.Forcing.EquivariantMixing +OAI.SetTheory.PartitionConsistency.Forcing.ForcingNames +OAI.SetTheory.PartitionConsistency.Forcing.ForcingQuotient +OAI.SetTheory.PartitionConsistency.Forcing.ForcingTruth +OAI.SetTheory.PartitionConsistency.Forcing.NameActions +OAI.SetTheory.PartitionConsistency.Forcing.ProductForcing +OAI.SetTheory.PartitionConsistency.Forcing.ProductNames +OAI.SetTheory.PartitionConsistency.Forcing.RelationCalculus +OAI.SetTheory.PartitionConsistency.Forcing.SupportFilter +OAI.SetTheory.PartitionConsistency.Forcing.SymmetricChoice +OAI.SetTheory.PartitionConsistency.Forcing.SymmetricNames +OAI.SetTheory.PartitionConsistency.Forcing.SymmetricSets +OAI.SetTheory.PartitionConsistency.Logic.Completeness +OAI.SetTheory.PartitionConsistency.Logic.CountableModels +OAI.SetTheory.PartitionConsistency.Logic.GroundModels +OAI.SetTheory.PartitionConsistency.Logic.Proofs +OAI.SetTheory.PartitionConsistency.Logic.SetLanguage +OAI.SetTheory.PartitionConsistency.Main +OAI.SetTheory.PartitionConsistency.Models.AssignedGraphs +OAI.SetTheory.PartitionConsistency.Models.AvailableRecords +OAI.SetTheory.PartitionConsistency.Models.ClassFibers +OAI.SetTheory.PartitionConsistency.Models.CodeCardinals +OAI.SetTheory.PartitionConsistency.Models.CodeLinks +OAI.SetTheory.PartitionConsistency.Models.ComponentGluing +OAI.SetTheory.PartitionConsistency.Models.ConcreteQuotients +OAI.SetTheory.PartitionConsistency.Models.ConcreteSystem +OAI.SetTheory.PartitionConsistency.Models.GermSelectors +OAI.SetTheory.PartitionConsistency.Models.GraphFusion +OAI.SetTheory.PartitionConsistency.Models.LocalQuotients +OAI.SetTheory.PartitionConsistency.Models.LocalRecords +OAI.SetTheory.PartitionConsistency.Models.OrbitAssignments +OAI.SetTheory.PartitionConsistency.Models.OrbitNames +OAI.SetTheory.PartitionConsistency.Models.OrderedSections +OAI.SetTheory.PartitionConsistency.Models.OrdinalChoice +OAI.SetTheory.PartitionConsistency.Models.OrdinalCodes +OAI.SetTheory.PartitionConsistency.Models.OrdinalPresentation +OAI.SetTheory.PartitionConsistency.Models.PersistentCodes +OAI.SetTheory.PartitionConsistency.Models.QuotientActions +OAI.SetTheory.PartitionConsistency.Models.QuotientTransport +OAI.SetTheory.PartitionConsistency.Models.SliceAssembly +OAI.SetTheory.PartitionConsistency.Models.SliceGeometry +OAI.SetTheory.PartitionConsistency.Models.StableSelectors +OAI.SetTheory.PartitionConsistency.Models.TailGraphs +OAI.SetTheory.PartitionConsistency.Models.UniformImages +OAI.SetTheory.PartitionConsistency.Models.UniformNames diff --git a/tasks/partition-consistency/solution/reference.py b/tasks/partition-consistency/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/partition-consistency/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/partition-consistency/solution/solve.sh b/tasks/partition-consistency/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9bd06b24b1dc34d87d183413401ab262876c6e6 --- /dev/null +++ b/tasks/partition-consistency/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PartitionConsistency, i.e. module OAI.SetTheory.PartitionConsistency.Main and the +# 75 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.SetTheory.PartitionConsistency.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PartitionConsistency" diff --git a/tasks/partition-consistency/task.toml b/tasks/partition-consistency/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b5e080927dad8dbcdda334e9095d31e1c11f9086 --- /dev/null +++ b/tasks/partition-consistency/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/partition-consistency" +version = "1.0.0" +description = "Prove PartitionConsistency (openai/math family 244: The partition principle does not imply choice) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PartitionConsistency.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PartitionConsistency" +family = "244" +family_title = "The partition principle does not imply choice" +subject = "Mathematical logic" +theorems = ["OAI.PartitionConsistency.main_consistency"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.SetTheory.PartitionConsistency.Main" +reference_modules = 75 +reference_lean_bytes = 1501215 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 823 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13051 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/partition-consistency/tests/Challenge.lean b/tasks/partition-consistency/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b0164000be29492237dbac6486670f7f33d09f21 --- /dev/null +++ b/tasks/partition-consistency/tests/Challenge.lean @@ -0,0 +1,324 @@ +import Mathlib + +namespace OAI + +namespace PartitionConsistency + +/-- Pure first-order membership syntax with equality. `n` variables are in scope. +A quantifier binds the last variable in its body. There are no atoms/urelements, +function symbols, constants, semantic predicates, or mathematical assumptions +in this syntax. -/ +inductive Formula : ℕ → Type where + | bot {n} : Formula n + | mem {n} (x y : Fin n) : Formula n + | equal {n} (x y : Fin n) : Formula n + | imp {n} (p q : Formula n) : Formula n + | conj {n} (p q : Formula n) : Formula n + | disj {n} (p q : Formula n) : Formula n + | all {n} (p : Formula (n + 1)) : Formula n + | ex {n} (p : Formula (n + 1)) : Formula n + +namespace Formula + +abbrev neg {n} (p : Formula n) : Formula n := p.imp .bot +abbrev iff {n} (p q : Formula n) : Formula n := (p.imp q).conj (q.imp p) + +/-- Under a binder, a renaming leaves the newly bound variable bound. -/ +def liftRen {n m} (r : Fin n → Fin m) : Fin (n + 1) → Fin (m + 1) := + Fin.lastCases (Fin.last m) (fun i => (r i).castSucc) + +/-- Capture-avoiding renaming; in this relational language all terms are variables. -/ +def rename {n m} (r : Fin n → Fin m) : Formula n → Formula m + | .bot => .bot + | .mem x y => .mem (r x) (r y) + | .equal x y => .equal (r x) (r y) + | .imp p q => .imp (rename r p) (rename r q) + | .conj p q => .conj (rename r p) (rename r q) + | .disj p q => .disj (rename r p) (rename r q) + | .all p => .all (rename (liftRen r) p) + | .ex p => .ex (rename (liftRen r) p) + +abbrev raise {n} (p : Formula n) : Formula (n + 1) := rename Fin.castSucc p + +/-- Substitution of a variable term for the variable just quantified. -/ +def instantiate {n} (p : Formula (n + 1)) (x : Fin n) : Formula n := + rename (Fin.lastCases x id) p + +/-- Universal closure of all the free variables. -/ +def close : {n : ℕ} → Formula n → Formula 0 + | 0, p => p + | _ + 1, p => close (.all p) + +end Formula + +abbrev Sentence := Formula 0 +abbrev Theory := Set Sentence + +/-- Classical first-order natural deduction with equality. Hypotheses may be an +infinite theory, but a derivation is a finite inductive proof. The `allI` and +`exE` rules use a fresh last variable, and shift all assumptions to avoid +capture. We allow finitely many free variables in proofs of closed sentences. -/ +inductive Derives : {n : ℕ} → Set (Formula n) → Formula n → Prop where + | hyp {n} {Γ : Set (Formula n)} {p} : p ∈ Γ → Derives Γ p + | weaken {n} {Γ Δ : Set (Formula n)} {p} : + Γ ⊆ Δ → Derives Γ p → Derives Δ p + | impI {n} {Γ : Set (Formula n)} {p q} : + Derives (insert p Γ) q → Derives Γ (.imp p q) + | impE {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.imp p q) → Derives Γ p → Derives Γ q + | botE {n} {Γ : Set (Formula n)} {p} : Derives Γ .bot → Derives Γ p + | classical {n} {Γ : Set (Formula n)} {p} : + Derives (insert p.neg Γ) .bot → Derives Γ p + | conjI {n} {Γ : Set (Formula n)} {p q} : + Derives Γ p → Derives Γ q → Derives Γ (.conj p q) + | conjL {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.conj p q) → Derives Γ p + | conjR {n} {Γ : Set (Formula n)} {p q} : + Derives Γ (.conj p q) → Derives Γ q + | disjL {n} {Γ : Set (Formula n)} {p q} : + Derives Γ p → Derives Γ (.disj p q) + | disjR {n} {Γ : Set (Formula n)} {p q} : + Derives Γ q → Derives Γ (.disj p q) + | disjE {n} {Γ : Set (Formula n)} {p q r} : + Derives Γ (.disj p q) → Derives (insert p Γ) r → + Derives (insert q Γ) r → Derives Γ r + | allI {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} : + Derives (Formula.raise '' Γ) p → Derives Γ (.all p) + | allE {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} (t : Fin n) : + Derives Γ (.all p) → Derives Γ (p.instantiate t) + | exI {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} (t : Fin n) : + Derives Γ (p.instantiate t) → Derives Γ (.ex p) + | exE {n} {Γ : Set (Formula n)} {p : Formula (n + 1)} {q : Formula n} : + Derives Γ (.ex p) → Derives (insert p (Formula.raise '' Γ)) q.raise → + Derives Γ q + | eqRefl {n} {Γ : Set (Formula n)} (t : Fin n) : Derives Γ (.equal t t) + | eqSubst {n} {Γ : Set (Formula n)} {s t : Fin n} (p : Formula (n + 1)) : + Derives Γ (.equal s t) → Derives Γ (p.instantiate s) → + Derives Γ (p.instantiate t) + | rename {n m} {Γ : Set (Formula n)} {p : Formula n} (r : Fin n → Fin m) : + Derives Γ p → Derives (Formula.rename r '' Γ) (Formula.rename r p) + +/-- Sentences are usable as open hypotheses with any finite supply of variables. -/ +def Theory.at (T : Theory) (n : ℕ) : Set (Formula n) := + Formula.rename Fin.elim0 '' T + +/-- Ordinary syntactic consistency: there is no finite natural-deduction proof +of falsity from the theory, with any finite supply of free variables. -/ +def Consistent (T : Theory) : Prop := ∀ n, ¬ Derives (T.at n) .bot + +namespace SetLanguage +open Formula + +/-! All abbreviations in this namespace expand to formulas of the pure language +of equality and membership. Functions are sets of Kuratowski pairs *inside the +structure*. In particular, no quantification over external Lean functions is +used in PP, Choice, or ordinal-indexed Choice. -/ + +/-- `a ⊆ b`. -/ +def subset {n} (a b : Fin n) : Formula n := + rename ![a, b] (Formula.all ((Formula.mem 2 0).imp (Formula.mem 2 1)) : Formula 2) + +/-- `a = ∅`. -/ +def empty {n} (a : Fin n) : Formula n := + rename ![a] (Formula.all (Formula.mem 1 0).neg : Formula 1) + +/-- `a ≠ ∅`, stated as existence of a member. -/ +def nonempty {n} (a : Fin n) : Formula n := + rename ![a] (Formula.ex (Formula.mem 1 0) : Formula 1) + +/-- `p = {x,y}`. -/ +def unorderedPair {n} (p x y : Fin n) : Formula n := + rename ![p, x, y] + (Formula.all ((Formula.mem 3 0).iff ((Formula.equal 3 1).disj (Formula.equal 3 2))) : Formula 3) + +/-- `b = a ∪ {a}`. -/ +def successor {n} (b a : Fin n) : Formula n := + rename ![b, a] + (Formula.all ((Formula.mem 2 0).iff ((Formula.mem 2 1).disj (Formula.equal 2 1))) : Formula 2) + +/-- Kuratowski ordered pair: `p = {{x},{x,y}}`. -/ +def orderedPair {n} (p x y : Fin n) : Formula n := + rename ![p, x, y] + (Formula.ex (Formula.ex ((unorderedPair 3 1 1).conj + ((unorderedPair 4 1 2).conj (unorderedPair 0 3 4)))) : Formula 3) + +/-- The internal graph relation `⟨x,y⟩ ∈ f`. -/ +def edge {n} (f x y : Fin n) : Formula n := + rename ![f, x, y] + (Formula.ex ((Formula.mem 3 0).conj (orderedPair 3 1 2)) : Formula 3) + +/-- `f` is a set graph of a function whose domain is exactly `d`. +The first conjunct excludes non-pairs and graph entries outside the domain; +the second conjunct asserts totality and single-valuedness. -/ +def functionOn {n} (f d : Fin n) : Formula n := + rename ![f, d] + ((Formula.all ((Formula.mem 2 0).imp + (Formula.ex (Formula.ex ((Formula.mem 3 1).conj (orderedPair 2 3 4)))))).conj + (Formula.all ((Formula.mem 2 1).imp + (Formula.ex ((edge 0 2 3).conj (Formula.all ((edge 0 2 4).imp (Formula.equal 4 3))))))) : Formula 2) + +/-- Internal set function `f : d → r`. -/ +def mapsTo {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 3 1).imp ((edge 0 3 4).imp (Formula.mem 4 2))))) : Formula 3) + +/-- Internal set surjection `f : d ↠ r`. -/ +def surjection {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((mapsTo 0 1 2).conj + (Formula.all ((Formula.mem 3 2).imp (Formula.ex ((Formula.mem 4 1).conj (edge 0 4 3))))) : Formula 3) + +/-- Internal set injection `f : d ↪ r`. -/ +def injection {n} (f d r : Fin n) : Formula n := + rename ![f, d, r] + ((mapsTo 0 1 2).conj + (Formula.all (Formula.all (.all + ((Formula.mem 3 1).imp ((Formula.mem 4 1).imp + (((edge 0 3 5).conj (edge 0 4 5)).imp (Formula.equal 3 4))))))) : Formula 3) + +/-- Transitivity of a set (not transitivity of the external structure). -/ +def transitiveSet {n} (a : Fin n) : Formula n := + rename ![a] + (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 1).imp (Formula.mem 2 0)))) : Formula 1) + +/-- Membership is an internal strict linear order on `a`. -/ +def membershipLinear {n} (a : Fin n) : Formula n := + rename ![a] + ((Formula.all ((Formula.mem 1 0).imp (Formula.mem 1 1).neg)).conj + ((Formula.all (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 0).imp ((Formula.mem 3 0).imp + (((Formula.mem 1 2).conj (Formula.mem 2 3)).imp (Formula.mem 1 3)))))))).conj + (Formula.all (Formula.all ((Formula.mem 1 0).imp ((Formula.mem 2 0).imp + ((Formula.equal 1 2).disj ((Formula.mem 1 2).disj (Formula.mem 2 1)))))))) : Formula 1) + +/-- Every nonempty internal subset of `a` has a membership-minimal element. +This does NOT assert external well-foundedness of the relation. -/ +def membershipWellFounded {n} (a : Fin n) : Formula n := + rename ![a] + (Formula.all (((subset 1 0).conj (nonempty 1)).imp + (Formula.ex ((Formula.mem 2 1).conj (Formula.all ((Formula.mem 3 1).imp (Formula.mem 3 2).neg))))) : Formula 1) + +/-- A von Neumann ordinal: a transitive set internally wellordered by membership. -/ +def ordinal {n} (a : Fin n) : Formula n := + (transitiveSet a).conj ((membershipLinear a).conj (membershipWellFounded a)) + +/-- A choice function on the set `A` of nonempty sets. -/ +def choiceOn {n} (c A : Fin n) : Formula n := + rename ![c, A] + ((functionOn 0 1).conj + (Formula.all ((Formula.mem 2 1).imp (Formula.ex ((edge 0 2 3).conj (Formula.mem 3 2))))) : Formula 2) + +/-- A graph `F` coding a family of nonempty sets indexed by ordinal `η`. -/ +def nonemptyFamily {n} (F η : Fin n) : Formula n := + rename ![F, η] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 2 1).imp ((edge 0 2 3).imp (nonempty 3))))) : Formula 2) + +/-- `c(ξ) ∈ F(ξ)` for every `ξ ∈ η`, with `c` an internal function. -/ +def choiceForFamily {n} (c η F : Fin n) : Formula n := + rename ![c, η, F] + ((functionOn 0 1).conj + (Formula.all (Formula.all ((Formula.mem 3 1).imp ((edge 2 3 4).imp + (Formula.ex ((edge 0 3 5).conj (Formula.mem 5 4))))))) : Formula 3) + +/-- The Partition Principle. The reverse injection is not required to be a +section of the original surjection. Both `X` and `Y` range over all sets. -/ +def PP : Sentence := + Formula.all (Formula.all ((Formula.ex (surjection 2 0 1)).imp (Formula.ex (injection 2 1 0)))) + +/-- Ordinary Choice for every set of nonempty sets. -/ +def AC : Sentence := + Formula.all ((Formula.all ((Formula.mem 1 0).imp (nonempty 1))).imp (Formula.ex (choiceOn 1 0))) + +/-- Choice for every ordinal-indexed family of nonempty sets, including ordinals +which may fail to be well founded from outside a model. -/ +def ACwo : Sentence := + Formula.all ((ordinal 0).imp + (Formula.all ((nonemptyFamily 1 0).imp (Formula.ex (choiceForFamily 2 0 1))))) + +/-! Full pure-set ZF, not a finite fragment and not ZFA. -/ + +def extensionality : Sentence := + Formula.all (Formula.all ((Formula.all ((Formula.mem 2 0).iff (Formula.mem 2 1))).imp (Formula.equal 0 1))) + +def emptySet : Sentence := Formula.ex (empty 0) + +def pairing : Sentence := Formula.all (Formula.all (Formula.ex (unorderedPair 2 0 1))) + +def union : Sentence := + Formula.all (Formula.ex (Formula.all ((Formula.mem 2 1).iff (Formula.ex ((Formula.mem 3 0).conj (Formula.mem 2 3)))))) + +def powerSet : Sentence := Formula.all (Formula.ex (Formula.all ((Formula.mem 2 1).iff (subset 2 0)))) + +def infinity : Sentence := + Formula.ex ((Formula.ex ((Formula.mem 1 0).conj (empty 1))).conj + (Formula.all ((Formula.mem 1 0).imp (Formula.ex ((Formula.mem 2 0).conj (successor 2 1)))))) + +def foundation : Sentence := + Formula.all ((nonempty 0).imp + (Formula.ex ((Formula.mem 1 0).conj (Formula.all ((Formula.mem 2 1).imp (Formula.mem 2 0).neg))))) + +/-- The instance of Separation for an entirely arbitrary formula `p(params,x)`. +All parameters are universally closed. Neither the quantifier complexity of +`p` nor the number of parameters is bounded. -/ +def separation {n} (p : Formula (n + 1)) : Sentence := + let A : Fin (n + 3) := (Fin.last n).castSucc.castSucc + let B : Fin (n + 3) := (Fin.last (n + 1)).castSucc + let x : Fin (n + 3) := Fin.last (n + 2) + let r : Fin (n + 1) → Fin (n + 3) := + Fin.lastCases x (fun i => i.castSucc.castSucc.castSucc) + close (Formula.all (Formula.ex (Formula.all ((Formula.mem x B).iff ((Formula.mem x A).conj (rename r p)))))) + +/-- Substitution into a binary formula with `n` additional parameters. -/ +def relation {n m} (p : Formula (n + 2)) (params : Fin n → Fin m) (x y : Fin m) : + Formula m := + rename (Fin.lastCases y (Fin.lastCases x params)) p + +/-- The instance of Replacement for an entirely arbitrary formula +`p(params,x,y)`: if it is single-valued and total on `A`, its image is a set. +As with Separation, the parameters are all universally closed. -/ +def replacement {n} (p : Formula (n + 2)) : Sentence := + let unique : Formula (n + 3) := + Formula.all ((relation p (fun i => i.castSucc.castSucc.castSucc.castSucc) + (Fin.last (n + 1)).castSucc.castSucc (Fin.last (n + 3))).imp + (Formula.equal (Fin.last (n + 3)) (Fin.last (n + 2)).castSucc)) + let totalFunctional : Formula (n + 1) := + Formula.all ((Formula.mem (Fin.last (n + 1)) (Fin.last n).castSucc).imp + (Formula.ex ((relation p (fun i => i.castSucc.castSucc.castSucc) + (Fin.last (n + 1)).castSucc (Fin.last (n + 2))).conj unique))) + let image : Formula (n + 1) := + Formula.ex (Formula.all ((Formula.mem (Fin.last (n + 2)) (Fin.last (n + 1)).castSucc).iff + (Formula.ex ((Formula.mem (Fin.last (n + 3)) (Fin.last n).castSucc.castSucc.castSucc).conj + (relation p (fun i => i.castSucc.castSucc.castSucc.castSucc) + (Fin.last (n + 3)) (Fin.last (n + 2)).castSucc))))) + close (Formula.all (totalFunctional.imp image)) + +/-- Exactly the axioms and all schema instances of pure first-order ZF. -/ +inductive IsZFAxiom : Sentence → Prop where + | extensionality : IsZFAxiom extensionality + | emptySet : IsZFAxiom emptySet + | pairing : IsZFAxiom pairing + | union : IsZFAxiom union + | powerSet : IsZFAxiom powerSet + | infinity : IsZFAxiom infinity + | foundation : IsZFAxiom foundation + | separation {n} (p : Formula (n + 1)) : IsZFAxiom (separation p) + | replacement {n} (p : Formula (n + 2)) : IsZFAxiom (replacement p) + +/-- Zermelo–Fraenkel set theory, without Choice. -/ +def ZF : Theory := {p | IsZFAxiom p} + +/-- ZF with the Partition Principle, ordinal-indexed Choice and failure of Choice. -/ +def targetTheory : Theory := ZF ∪ {PP, ACwo, AC.neg} + +end SetLanguage + +/-- Relative consistency of ZF with the Partition Principle, ordinal-indexed +Choice and failure of Choice. -/ +theorem main_consistency : + Consistent SetLanguage.ZF → Consistent SetLanguage.targetTheory := by + sorry + +end PartitionConsistency + +end OAI diff --git a/tasks/partition-consistency/tests/grade.py b/tasks/partition-consistency/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/partition-consistency/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/partition-consistency/tests/task.json b/tasks/partition-consistency/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9ac5abf0286107fdcd2dcf99157373d7f3e43d6b --- /dev/null +++ b/tasks/partition-consistency/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PartitionConsistency", + "comparator": { + "theorem_names": [ + "OAI.PartitionConsistency.main_consistency" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12151 +} \ No newline at end of file diff --git a/tasks/partition-consistency/tests/test.sh b/tasks/partition-consistency/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/partition-consistency/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/partition-principle/environment/Dockerfile b/tasks/partition-principle/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/partition-principle/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/partition-principle/environment/fetch_mathlib.sh b/tasks/partition-principle/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/partition-principle/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/partition-principle/environment/lake-manifest.json b/tasks/partition-principle/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/partition-principle/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/partition-principle/environment/lakefile.lean b/tasks/partition-principle/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/partition-principle/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/partition-principle/environment/lean_setup.sh b/tasks/partition-principle/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/partition-principle/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/partition-principle/environment/pack_submission.py b/tasks/partition-principle/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/partition-principle/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/partition-principle/instruction.md b/tasks/partition-principle/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3ad0293caf8b35a620642b572343d4b605440635 --- /dev/null +++ b/tasks/partition-principle/instruction.md @@ -0,0 +1,328 @@ +# openai/math challenge `PartitionPrinciple` (family 244) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 244 of the release, *The partition principle does not imply choice* +(Mathematical logic). The family as a whole: Assuming ZF is consistent, constructs a model in which every surjective image of a set injects into that set, yet the axiom of choice fails. Choice for ordinal-indexed families still holds. From any countable transitive model of ZFC, a separate construction gives a transitive symmetric extension with these properties and no new countable sequences of ground-model elements. + +The challenge is `PartitionPrinciple`, also at `/opt/openai-math/challenges/PartitionPrinciple.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PartitionPilot.Forcing + +universe u + +inductive SetFormula : Nat → Type + | equal {n} : Fin n → Fin n → SetFormula n + | mem {n} : Fin n → Fin n → SetFormula n + | neg {n} : SetFormula n → SetFormula n + | conj {n} : SetFormula n → SetFormula n → SetFormula n + | all {n} : SetFormula (n + 1) → SetFormula n + +namespace SetFormula + +def extend {A : Type u} {n : Nat} (x : A) (env : Fin n → A) : Fin (n + 1) → A := + Fin.cases x env + +def Realize (U : Set ZFSet.{u}) : {n : Nat} → SetFormula n → (Fin n → ZFSet.{u}) → Prop + | _, .equal i j, env => env i = env j + | _, .mem i j, env => env i ∈ env j + | _, .neg φ, env => ¬ Realize U φ env + | _, .conj φ ψ, env => Realize U φ env ∧ Realize U ψ env + | _, .all φ, env => ∀ x ∈ U, Realize U φ (extend x env) + +def ex {n : Nat} (φ : SetFormula (n + 1)) : SetFormula n := .neg (.all (.neg φ)) + +def disj {n : Nat} (φ ψ : SetFormula n) : SetFormula n := .neg (.conj (.neg φ) (.neg ψ)) + +def imp {n : Nat} (φ ψ : SetFormula n) : SetFormula n := .neg (.conj φ (.neg ψ)) + +end SetFormula + +inductive BoundedFormula : Nat → Type + | equal {n} : Fin n → Fin n → BoundedFormula n + | mem {n} : Fin n → Fin n → BoundedFormula n + | neg {n} : BoundedFormula n → BoundedFormula n + | conj {n} : BoundedFormula n → BoundedFormula n → BoundedFormula n + | allMem {n} : Fin n → BoundedFormula (n + 1) → BoundedFormula n + +namespace BoundedFormula + +open SetFormula + +def imp {n} (φ ψ : BoundedFormula n) : BoundedFormula n := .neg (.conj φ (.neg ψ)) + +def disj {n} (φ ψ : BoundedFormula n) : BoundedFormula n := .neg (.conj (.neg φ) (.neg ψ)) + +def exMem {n} (b : Fin n) (φ : BoundedFormula (n + 1)) : BoundedFormula n := + .neg (.allMem b (.neg φ)) + +def toFormula : {n : Nat} → BoundedFormula n → SetFormula n + | _, .equal i j => .equal i j + | _, .mem i j => .mem i j + | _, .neg φ => .neg φ.toFormula + | _, .conj φ ψ => .conj φ.toFormula ψ.toFormula + | _, .allMem b φ => .all (SetFormula.imp (.mem 0 b.succ) φ.toFormula) + +def singletonFormula {n} (z x : Fin n) : BoundedFormula n := + .conj (.mem x z) (.allMem z (.equal 0 x.succ)) + +def unorderedPairFormula {n} (z x y : Fin n) : BoundedFormula n := + .conj (.mem x z) (.conj (.mem y z) (.allMem z (disj (.equal 0 x.succ) (.equal 0 y.succ)))) + +def orderedPairFormula {n} (z x y : Fin n) : BoundedFormula n := + exMem z (.conj (singletonFormula 0 x.succ) + (exMem z.succ (.conj (unorderedPairFormula 0 x.succ.succ y.succ.succ) + (unorderedPairFormula z.succ.succ 1 0)))) + +def pairMembershipFormula {n} (x y r : Fin n) : BoundedFormula n := + exMem r (orderedPairFormula 0 x.succ y.succ) + +def relationBetweenFormula {n} (a b f : Fin n) : BoundedFormula n := + .allMem f (exMem a.succ (exMem b.succ.succ (orderedPairFormula 2 1 0))) + +def functionFormula {n} (a b f : Fin n) : BoundedFormula n := + .conj (relationBetweenFormula a b f) + (.allMem a (exMem b.succ (.conj (pairMembershipFormula 1 0 f.succ.succ) + (.allMem b.succ.succ (imp (pairMembershipFormula 2 0 f.succ.succ.succ) (.equal 0 1)))))) + +def nonemptyFormula {n} (x : Fin n) : BoundedFormula n := exMem x (.equal 0 0) + +def choiceFunctionFormula {n} (a f : Fin n) : BoundedFormula n := + .conj (.allMem f (exMem a.succ (exMem 0 (orderedPairFormula 2 1 0)))) + (.allMem a (exMem 0 (.conj (pairMembershipFormula 1 0 f.succ.succ) + (.allMem 1 (imp (pairMembershipFormula 2 0 f.succ.succ.succ) (.equal 0 1)))))) + +end BoundedFormula + +structure TransitiveGround where + sets : Set ZFSet.{u} + transitive : ∀ {x y}, x ∈ sets → y ∈ x → y ∈ sets + +structure InjectionCode (D N f : ZFSet.{u}) : Prop where + function : ZFSet.IsFunc D N f + injective : ∀ x y z, ZFSet.pair x z ∈ f → ZFSet.pair y z ∈ f → x = y + +namespace TransitiveGround + +open SetFormula + +variable (M : TransitiveGround.{u}) + +def groundEmbeddable (D N : ZFSet.{u}) : Prop := ∃ f ∈ M.sets, InjectionCode D N f + +end TransitiveGround + +def setTransitive (x : ZFSet.{u}) : Prop := ∀ y ∈ x, ∀ z ∈ y, z ∈ x + +def ordinalSetProperty (x : ZFSet.{u}) : Prop := + setTransitive x ∧ ∀ y ∈ x, setTransitive y + +namespace TransitiveGround + +open SetFormula + +variable (M : TransitiveGround.{u}) + +noncomputable def groundPower (B : ZFSet.{u}) : ZFSet.{u} := + ZFSet.sep (fun p => p ∈ M.sets) (ZFSet.powerset B) + +end TransitiveGround + +def GroundBelow (M : TransitiveGround.{u}) (A K : ZFSet.{u}) : Prop := + ∃ β ∈ K, M.groundEmbeddable A β + +def GroundCardinal (M : TransitiveGround.{u}) (κ : ZFSet.{u}) : Prop := + ordinalSetProperty κ ∧ ∀ β ∈ κ, ¬ M.groundEmbeddable κ β + +def CofinalFunctionCode (α K f : ZFSet.{u}) : Prop := + ZFSet.IsFunc α K f ∧ ∀ β ∈ K, ∃ x ∈ α, ∃ y ∈ K, + ZFSet.pair x y ∈ f ∧ (β = y ∨ β ∈ y) + +def GroundCofinalRegular (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + ∀ α ∈ K, ∀ f ∈ M.sets, ¬ CofinalFunctionCode α K f + +def GroundCardinalStrongLimit (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + ∀ κ ∈ K, GroundCardinal M κ → GroundBelow M (M.groundPower κ) K + +def GroundStandardInaccessible (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + GroundCardinal M K ∧ ¬ M.groundEmbeddable K ZFSet.omega ∧ + GroundCofinalRegular M K ∧ GroundCardinalStrongLimit M K + +namespace SetFormula + +def extensionality : SetFormula 0 := + .all (.all (imp + (.all (.conj (imp (.mem 0 2) (.mem 0 1)) (imp (.mem 0 1) (.mem 0 2)))) + (.equal 1 0))) + +def foundation : SetFormula 0 := + .all (imp (ex (.mem 0 1)) + (ex (.conj (.mem 0 1) (.all (.neg (.conj (.mem 0 2) (.mem 0 1))))))) + +def emptySet : SetFormula 0 := ex (.all (.neg (.mem 0 1))) + +def pairing : SetFormula 0 := + .all (.all (ex (.all (.conj + (imp (.mem 0 1) (disj (.equal 0 3) (.equal 0 2))) + (imp (disj (.equal 0 3) (.equal 0 2)) (.mem 0 1)))))) + +def union : SetFormula 0 := + .all (ex (.all (.conj + (imp (.mem 0 1) (ex (.conj (.mem 0 3) (.mem 1 0)))) + (imp (ex (.conj (.mem 0 3) (.mem 1 0))) (.mem 0 1))))) + +def powerSet : SetFormula 0 := + .all (ex (.all (.conj + (imp (.mem 0 1) (.all (imp (.mem 0 1) (.mem 0 3)))) + (imp (.all (imp (.mem 0 1) (.mem 0 3))) (.mem 0 1))))) + +def SeparationSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 1)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ x ∈ U, ∃ y ∈ U, + ∀ z ∈ U, z ∈ y ↔ z ∈ x ∧ Realize U φ (extend z params) + +def CollectionSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 2)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ a ∈ U, + (∀ x ∈ U, x ∈ a → ∃ y ∈ U, Realize U φ (extend x (extend y params))) → + ∃ b ∈ U, ∀ x ∈ U, x ∈ a → + ∃ y ∈ U, y ∈ b ∧ Realize U φ (extend x (extend y params)) + +def emptySetFormula {n : Nat} (x : Fin n) : SetFormula n := .all (.neg (.mem 0 x.succ)) + +def successorFormula {n : Nat} (y x : Fin n) : SetFormula n := + .all (.conj (imp (.mem 0 y.succ) (disj (.equal 0 x.succ) (.mem 0 x.succ))) + (imp (disj (.equal 0 x.succ) (.mem 0 x.succ)) (.mem 0 y.succ))) + +def infinity : SetFormula 0 := + ex (.conj (ex (.conj (.mem 0 1) (emptySetFormula 0))) + (.all (imp (.mem 0 1) (ex (.conj (.mem 0 2) (successorFormula 0 1)))))) + +def choice : SetFormula 0 := + .all (imp (BoundedFormula.allMem 0 (BoundedFormula.nonemptyFormula 0)).toFormula + (ex (BoundedFormula.choiceFunctionFormula 1 0).toFormula)) + +def ReplacementSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 2)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ A ∈ U, + (∀ x ∈ U, x ∈ A → ∃ y ∈ U, Realize U φ (extend x (extend y params)) ∧ + ∀ z ∈ U, Realize U φ (extend x (extend z params)) → z = y) → + ∃ B ∈ U, ∀ y ∈ U, y ∈ B ↔ ∃ x ∈ U, x ∈ A ∧ Realize U φ (extend x (extend y params)) + +def finiteZFAxioms : SetFormula 0 := + .conj extensionality (.conj foundation (.conj emptySet + (.conj pairing (.conj SetFormula.union (.conj powerSet infinity))))) + +def ZFRealization (U : Set ZFSet.{u}) : Prop := + Realize U finiteZFAxioms Fin.elim0 ∧ SeparationSchema U ∧ ReplacementSchema U + +end SetFormula + +namespace BoundedFormula + +open SetFormula + +def injectionFormula {n} (d c f : Fin n) : BoundedFormula n := + .conj (functionFormula d c f) (.allMem d (.allMem d.succ (.allMem c.succ.succ + (imp (.conj (pairMembershipFormula 2 0 f.succ.succ.succ) + (pairMembershipFormula 1 0 f.succ.succ.succ)) (.equal 2 1))))) + +end BoundedFormula + +namespace SetFormula + +def hasInjectionFormula {n} (d c : Fin n) : SetFormula n := + ex (BoundedFormula.injectionFormula d.succ c.succ 0).toFormula + +end SetFormula + +namespace BoundedFormula + +open SetFormula + +def surjectionFormula {n : Nat} (a b f : Fin n) : BoundedFormula n := + .conj (functionFormula a b f) + (.allMem b (exMem a.succ (pairMembershipFormula 0 1 f.succ.succ))) + +end BoundedFormula + +namespace SetFormula + +def partitionPrinciple : SetFormula 0 := + .all (.all (.all (imp (BoundedFormula.surjectionFormula (n := 3) 2 1 0).toFormula + (hasInjectionFormula (n := 3) 1 2)))) + +end SetFormula + +end PartitionPilot.Forcing + +namespace PartitionPilot.Forcing.TransitiveGround + +open SetFormula + +universe u + +variable (M : TransitiveGround.{u}) + +theorem exists_model_partitionPrinciple_without_choice + (pairing : Realize M.sets SetFormula.pairing Fin.elim0) + (unions : Realize M.sets SetFormula.union Fin.elim0) + (powers : Realize M.sets powerSet Fin.elim0) (separation : SeparationSchema M.sets) + (collection : CollectionSchema M.sets) (infinite : Realize M.sets infinity Fin.elim0) + (choice : Realize M.sets SetFormula.choice Fin.elim0) + (small : M.sets.Countable) + {K : ZFSet.{u}} (hK : K ∈ M.sets) (standard : GroundStandardInaccessible M K) : + ∃ N : TransitiveGround.{u}, M.sets ⊆ N.sets ∧ ZFRealization N.sets ∧ + Realize N.sets partitionPrinciple Fin.elim0 ∧ + ¬ Realize N.sets SetFormula.choice Fin.elim0 := by + sorry + +end PartitionPilot.Forcing.TransitiveGround + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PartitionPrinciple.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PartitionPilot.Forcing.TransitiveGround.exists_model_partitionPrinciple_without_choice` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/partition-principle/solution/closure.txt b/tasks/partition-principle/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..30ed690a5f0daecf49b91d309aa87a3386a21093 --- /dev/null +++ b/tasks/partition-principle/solution/closure.txt @@ -0,0 +1,943 @@ +OAI.SetTheory.PartitionPrinciple.Definability.AssignmentQueryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.AttachmentOldCodeLaws +OAI.SetTheory.PartitionPrinciple.Definability.BatchAttachmentRealization +OAI.SetTheory.PartitionPrinciple.Definability.BatchGraphSetFormulas +OAI.SetTheory.PartitionPrinciple.Definability.BoundedAtomicEquality +OAI.SetTheory.PartitionPrinciple.Definability.BoundedChronologyCodes +OAI.SetTheory.PartitionPrinciple.Definability.BoundedDirectedOrders +OAI.SetTheory.PartitionPrinciple.Definability.BoundedMeetOrderCodes +OAI.SetTheory.PartitionPrinciple.Definability.BoundedRelationImageEquality +OAI.SetTheory.PartitionPrinciple.Definability.CodedBatchDecoding +OAI.SetTheory.PartitionPrinciple.Definability.CodedEqualityRelations +OAI.SetTheory.PartitionPrinciple.Definability.CodedFilterImages +OAI.SetTheory.PartitionPrinciple.Definability.CodedInjectiveCones +OAI.SetTheory.PartitionPrinciple.Definability.CodedLayerRestrictions +OAI.SetTheory.PartitionPrinciple.Definability.CodedLayerSourceCongruence +OAI.SetTheory.PartitionPrinciple.Definability.CodedProfileImageTests +OAI.SetTheory.PartitionPrinciple.Definability.CodedRangeCompletion +OAI.SetTheory.PartitionPrinciple.Definability.CodedTemplateShadowLaws +OAI.SetTheory.PartitionPrinciple.Definability.CompressionExternalStepRealization +OAI.SetTheory.PartitionPrinciple.Definability.CompressionRequestRealization +OAI.SetTheory.PartitionPrinciple.Definability.CountableFormulaFamilies +OAI.SetTheory.PartitionPrinciple.Definability.CountableSetFormulas +OAI.SetTheory.PartitionPrinciple.Definability.CrossStageMembershipFormulas +OAI.SetTheory.PartitionPrinciple.Definability.DecodedFunctionGraphs +OAI.SetTheory.PartitionPrinciple.Definability.DepthSlotCodes +OAI.SetTheory.PartitionPrinciple.Definability.EqualityStepSyntax +OAI.SetTheory.PartitionPrinciple.Definability.EquivalenceClassCodes +OAI.SetTheory.PartitionPrinciple.Definability.ExternalColumnCodes +OAI.SetTheory.PartitionPrinciple.Definability.ExternalCopyRelations +OAI.SetTheory.PartitionPrinciple.Definability.ExternalFamilySlotCodes +OAI.SetTheory.PartitionPrinciple.Definability.ExternalGroupOperationGraphs +OAI.SetTheory.PartitionPrinciple.Definability.ExternalRealization +OAI.SetTheory.PartitionPrinciple.Definability.ExternalRequestGraphCoordinates +OAI.SetTheory.PartitionPrinciple.Definability.ExternalSlotCopyGraphs +OAI.SetTheory.PartitionPrinciple.Definability.ExternalStarCarrierRanks +OAI.SetTheory.PartitionPrinciple.Definability.ExternalStarOverlapRealization +OAI.SetTheory.PartitionPrinciple.Definability.ExternalTileCoordinateRealization +OAI.SetTheory.PartitionPrinciple.Definability.ExternalTileSlotSupportRealization +OAI.SetTheory.PartitionPrinciple.Definability.ExternalWordRewriteFormulas +OAI.SetTheory.PartitionPrinciple.Definability.ExternalWordRewriteRealization +OAI.SetTheory.PartitionPrinciple.Definability.ExternalWordRewriteRelations +OAI.SetTheory.PartitionPrinciple.Definability.FinalRankRealization +OAI.SetTheory.PartitionPrinciple.Definability.FiniteWordMapCodes +OAI.SetTheory.PartitionPrinciple.Definability.FiniteWordOperationFormulas +OAI.SetTheory.PartitionPrinciple.Definability.FixedTopCodes +OAI.SetTheory.PartitionPrinciple.Definability.FlatCopyGraphRealization +OAI.SetTheory.PartitionPrinciple.Definability.FlatLimitConditionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.ForcingHistoryConditionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.ForcingHistoryOutputFormulas +OAI.SetTheory.PartitionPrinciple.Definability.ForcingWitnessFormulas +OAI.SetTheory.PartitionPrinciple.Definability.FormulaSymmetry +OAI.SetTheory.PartitionPrinciple.Definability.GraphValueMembershipFormula +OAI.SetTheory.PartitionPrinciple.Definability.GreedyAntichainStepFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundActedRepresentativeGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundAllSupportCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundAssignmentClassGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundBatchAttachmentGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundBelowFunctionGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundBelowIndexedCarriers +OAI.SetTheory.PartitionPrinciple.Definability.GroundBelowMainGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundBelowRelationSpaces +OAI.SetTheory.PartitionPrinciple.Definability.GroundBinaryRowSets +OAI.SetTheory.PartitionPrinciple.Definability.GroundBoundedCompressionHeights +OAI.SetTheory.PartitionPrinciple.Definability.GroundBoundedExternalBirths +OAI.SetTheory.PartitionPrinciple.Definability.GroundCompletedCompressionCertificateFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundCompositionFamilyFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundCompressionHistoryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundDefinableRelationProducts +OAI.SetTheory.PartitionPrinciple.Definability.GroundDepthSlotCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundEligibleTaskSetRecognition +OAI.SetTheory.PartitionPrinciple.Definability.GroundExternalCutoffFieldGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundExternalRequestSetRecognition +OAI.SetTheory.PartitionPrinciple.Definability.GroundFlatCarrierSequences +OAI.SetTheory.PartitionPrinciple.Definability.GroundFlatCopyGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundFlatCopyPresentation +OAI.SetTheory.PartitionPrinciple.Definability.GroundFlatRestrictionGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundFunctionCoordinateDensity +OAI.SetTheory.PartitionPrinciple.Definability.GroundFunctionRangeFamilies +OAI.SetTheory.PartitionPrinciple.Definability.GroundInternalRowSetZF +OAI.SetTheory.PartitionPrinciple.Definability.GroundLiftedCompressionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundLiftedRowTupleProvenance +OAI.SetTheory.PartitionPrinciple.Definability.GroundLiftedRowTupleSupports +OAI.SetTheory.PartitionPrinciple.Definability.GroundLowRankFunctionGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundMainCodeRanks +OAI.SetTheory.PartitionPrinciple.Definability.GroundMainFinalGraphValueCandidateAvailability +OAI.SetTheory.PartitionPrinciple.Definability.GroundMainFinalSemanticStructuralZF +OAI.SetTheory.PartitionPrinciple.Definability.GroundMainTransitionCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundNiceVisibilityGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundOutsideRowCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundPackedRefinementFormulaData +OAI.SetTheory.PartitionPrinciple.Definability.GroundPairCompositions +OAI.SetTheory.PartitionPrinciple.Definability.GroundPairEmptyRefinementSystem +OAI.SetTheory.PartitionPrinciple.Definability.GroundPairedCompositionRows +OAI.SetTheory.PartitionPrinciple.Definability.GroundPartialFunctionSpaces +OAI.SetTheory.PartitionPrinciple.Definability.GroundPowerImageGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundPreparationEventSupportGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundPrincipalNiceSupportCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundPushFilterFamilyFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundQuantifiedGraphFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundRankedBoundedSerialization +OAI.SetTheory.PartitionPrinciple.Definability.GroundRationalCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundRecursiveActionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundRefinementLevelSingleCodes +OAI.SetTheory.PartitionPrinciple.Definability.GroundRefinementLiftedClassGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundRefinementPairClassGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundRegularFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundRelationProductFamilies +OAI.SetTheory.PartitionPrinciple.Definability.GroundRowGraphDescent +OAI.SetTheory.PartitionPrinciple.Definability.GroundSelectedSupportTupleFamilies +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAbsentLiftActors +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAlignedCopyCollisions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAlignedCopyUnions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAlignedLargerCutTests +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAlignedRectangleUnions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAssignmentLabelCanonicalSuccessors +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAssignmentLabelDomainTotality +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAssignmentLabelInjectionPackages +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticAugmentedClassRequests +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticFairPreparationLimits +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticFairPreparationRecordedLimits +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticFairPreparationSupportedLimits +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticOrdinalRowOrbitCovers +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticPreparedProfileSelections +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticPreparedWitnessSelections +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticRepresentedDomainAbsentLift +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticRepresentedDomainEasyCases +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticRepresentedDomainLiftDecisions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticRepresentedDomainPersistence +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralCutActions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralDataSupport +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralFamilyEvaluation +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralFilterLifts +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralFinalRefinements +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralOrderCoordinates +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralPrefixPreparationInputs +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralRefinementNormalization +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralRefinementObjectSupports +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralRequestActions +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralRequestBatches +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralSupportIncidence +OAI.SetTheory.PartitionPrinciple.Definability.GroundSemanticStructuralSymmetricRefinementOutputs +OAI.SetTheory.PartitionPrinciple.Definability.GroundSeparatorFamilyFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundSerializedCodeRanks +OAI.SetTheory.PartitionPrinciple.Definability.GroundStageOneFormulaData +OAI.SetTheory.PartitionPrinciple.Definability.GroundStandardInaccessibleFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundStrongLimitFormulas +OAI.SetTheory.PartitionPrinciple.Definability.GroundTaggedComponentGraphs +OAI.SetTheory.PartitionPrinciple.Definability.GroundVaryingPreparationRelations +OAI.SetTheory.PartitionPrinciple.Definability.HistoryFieldFormulas +OAI.SetTheory.PartitionPrinciple.Definability.IndexedAttachmentCodes +OAI.SetTheory.PartitionPrinciple.Definability.IndexedMixedOperationLiftCodes +OAI.SetTheory.PartitionPrinciple.Definability.IndexedOperationLiftCodes +OAI.SetTheory.PartitionPrinciple.Definability.IndexedSubstructureCodes +OAI.SetTheory.PartitionPrinciple.Definability.IndexedValueLiftCodes +OAI.SetTheory.PartitionPrinciple.Definability.InitialMainAlgebraCodes +OAI.SetTheory.PartitionPrinciple.Definability.IntervalEmbeddingFormulas +OAI.SetTheory.PartitionPrinciple.Definability.IntervalHeightFormulas +OAI.SetTheory.PartitionPrinciple.Definability.IntervalSequenceFormulas +OAI.SetTheory.PartitionPrinciple.Definability.LeastSlotOwnerCodes +OAI.SetTheory.PartitionPrinciple.Definability.LiftedCompressionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.LinkedMainInvariantCodes +OAI.SetTheory.PartitionPrinciple.Definability.LinkedMainTransitionRawCodes +OAI.SetTheory.PartitionPrinciple.Definability.LinkedProfileTransitionRawCodes +OAI.SetTheory.PartitionPrinciple.Definability.MainLimitCoverageFormulas +OAI.SetTheory.PartitionPrinciple.Definability.MainPrefixTraceStepFormulas +OAI.SetTheory.PartitionPrinciple.Definability.MainPrefixValidityFormulas +OAI.SetTheory.PartitionPrinciple.Definability.MainTransitionValidityCodes +OAI.SetTheory.PartitionPrinciple.Definability.MapFamilyApplicationGraphs +OAI.SetTheory.PartitionPrinciple.Definability.NameSupportFormulas +OAI.SetTheory.PartitionPrinciple.Definability.NatUnionCodes +OAI.SetTheory.PartitionPrinciple.Definability.NaturalSetCodes +OAI.SetTheory.PartitionPrinciple.Definability.NaturalStepFormulas +OAI.SetTheory.PartitionPrinciple.Definability.NonemptyTupleFields +OAI.SetTheory.PartitionPrinciple.Definability.OrbitImageFormulas +OAI.SetTheory.PartitionPrinciple.Definability.PairPushFilterFamilies +OAI.SetTheory.PartitionPrinciple.Definability.ParentSupportCodes +OAI.SetTheory.PartitionPrinciple.Definability.PartitionPrincipleFormula +OAI.SetTheory.PartitionPrinciple.Definability.PreparedCertificateCodes +OAI.SetTheory.PartitionPrinciple.Definability.PresentedGroupCodes +OAI.SetTheory.PartitionPrinciple.Definability.PresentedRowAssignmentGraphs +OAI.SetTheory.PartitionPrinciple.Definability.PreservedMainPrefixHistoryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.PrincipalSupportFormulas +OAI.SetTheory.PartitionPrinciple.Definability.PrincipalTileRealization +OAI.SetTheory.PartitionPrinciple.Definability.RationalCodeLaws +OAI.SetTheory.PartitionPrinciple.Definability.RawCheckFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RawRenameFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RecursiveActionRealization +OAI.SetTheory.PartitionPrinciple.Definability.RecursivePrimitiveFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RefinementDataHistoryEntryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RefinementHistoryOrderOutputFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RefinementIndexActionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RefinementValidityCodes +OAI.SetTheory.PartitionPrinciple.Definability.RenamedEntryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.RepresentativeProductAgreement +OAI.SetTheory.PartitionPrinciple.Definability.RootedSupportOwnerFunction +OAI.SetTheory.PartitionPrinciple.Definability.RowAssignmentCutGraphLaws +OAI.SetTheory.PartitionPrinciple.Definability.RowAssignmentTransitionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.SeparationEntryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.SeparationFulfillmentCodes +OAI.SetTheory.PartitionPrinciple.Definability.SerializedChronologyFormulas +OAI.SetTheory.PartitionPrinciple.Definability.SetPresentations +OAI.SetTheory.PartitionPrinciple.Definability.SmallFunctionActionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.StrictLexHeightFormulas +OAI.SetTheory.PartitionPrinciple.Definability.StructuralAssignmentActionFormulas +OAI.SetTheory.PartitionPrinciple.Definability.StructuralRefinementHistoryFormulas +OAI.SetTheory.PartitionPrinciple.Definability.SupportedCertificateFamilyFormulas +OAI.SetTheory.PartitionPrinciple.Definability.SupportedCertificateRelations +OAI.SetTheory.PartitionPrinciple.Definability.TaggedExtensionCodes +OAI.SetTheory.PartitionPrinciple.Definability.TaggedGrowthLayerFormulas +OAI.SetTheory.PartitionPrinciple.Definability.TaggedSumPresentations +OAI.SetTheory.PartitionPrinciple.Definability.TaskCapFamilyCodes +OAI.SetTheory.PartitionPrinciple.Definability.TaskRepresentativeCodes +OAI.SetTheory.PartitionPrinciple.Definability.TaskTransportFormulas +OAI.SetTheory.PartitionPrinciple.Definability.TileStarIncidenceRealization +OAI.SetTheory.PartitionPrinciple.Definability.TupleRelationProducts +OAI.SetTheory.PartitionPrinciple.Definability.UnionEntryFormula +OAI.SetTheory.PartitionPrinciple.Definability.VisibilityProfileFormulas +OAI.SetTheory.PartitionPrinciple.Forcing.ActionPostcompositionCodes +OAI.SetTheory.PartitionPrinciple.Forcing.ActiveNameImageSymmetry +OAI.SetTheory.PartitionPrinciple.Forcing.AllSupportFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.AtomicTruth +OAI.SetTheory.PartitionPrinciple.Forcing.ChronologicalTransport +OAI.SetTheory.PartitionPrinciple.Forcing.CodedDenseOrders +OAI.SetTheory.PartitionPrinciple.Forcing.CodedRecursiveTaskActions +OAI.SetTheory.PartitionPrinciple.Forcing.CompleteProjectionFilterLifts +OAI.SetTheory.PartitionPrinciple.Forcing.ConditionQuantifiers +OAI.SetTheory.PartitionPrinciple.Forcing.CrossStageMembershipNameActions +OAI.SetTheory.PartitionPrinciple.Forcing.DenseInterpolation +OAI.SetTheory.PartitionPrinciple.Forcing.EligibleBatchEquivariance +OAI.SetTheory.PartitionPrinciple.Forcing.EvaluatedDomains +OAI.SetTheory.PartitionPrinciple.Forcing.ExternalAction +OAI.SetTheory.PartitionPrinciple.Forcing.ExternalFilterBases +OAI.SetTheory.PartitionPrinciple.Forcing.ExternalWordInverseEvaluation +OAI.SetTheory.PartitionPrinciple.Forcing.FinalFilterLocalization +OAI.SetTheory.PartitionPrinciple.Forcing.FinitePrincipalNameSupports +OAI.SetTheory.PartitionPrinciple.Forcing.FixedTop +OAI.SetTheory.PartitionPrinciple.Forcing.FixedTopProfilePreservation +OAI.SetTheory.PartitionPrinciple.Forcing.FlatConditionSystems +OAI.SetTheory.PartitionPrinciple.Forcing.FlatLimitConditionCodes +OAI.SetTheory.PartitionPrinciple.Forcing.FlatSuccessorConditionUnions +OAI.SetTheory.PartitionPrinciple.Forcing.FlatSuccessorConditions +OAI.SetTheory.PartitionPrinciple.Forcing.ForcingHistoryTestDecomposition +OAI.SetTheory.PartitionPrinciple.Forcing.GeneratedMeetFilters +OAI.SetTheory.PartitionPrinciple.Forcing.GenericPartialFunctions +OAI.SetTheory.PartitionPrinciple.Forcing.GreedyAntichainTraces +OAI.SetTheory.PartitionPrinciple.Forcing.GroundAbsentLiftClassTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundActionFilterImages +OAI.SetTheory.PartitionPrinciple.Forcing.GroundActionPostcomposition +OAI.SetTheory.PartitionPrinciple.Forcing.GroundBatchEarlierLayerWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundBinaryRowNameCodes +OAI.SetTheory.PartitionPrinciple.Forcing.GroundBinaryRowNameSupportBounds +OAI.SetTheory.PartitionPrinciple.Forcing.GroundBinaryRowNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundBinaryRowStructuralDataBoundActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundChronologicalTransitionTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundChronologyWitnessSelection +OAI.SetTheory.PartitionPrinciple.Forcing.GroundCompleteProjectionAtomicTruth +OAI.SetTheory.PartitionPrinciple.Forcing.GroundCompleteProjectionGenericity +OAI.SetTheory.PartitionPrinciple.Forcing.GroundCompressionIncomingWitnessRanks +OAI.SetTheory.PartitionPrinciple.Forcing.GroundCompressionSerializationTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundCountableFunctionForcing +OAI.SetTheory.PartitionPrinciple.Forcing.GroundDefinableRefinementNameGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundEligibleActionStep +OAI.SetTheory.PartitionPrinciple.Forcing.GroundEligibleBatchActionRecognition +OAI.SetTheory.PartitionPrinciple.Forcing.GroundExternalLayerWitnessRanks +OAI.SetTheory.PartitionPrinciple.Forcing.GroundExternalOldAction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundExternalStarSupports +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFairPreparationConditionSequences +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFilterCopies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFilterPullbackRecovery +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFixedIndexAssignmentSlices +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFixedPoints +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFixedTopStep +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFixedTopTerminal +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFlatLimitConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFlatSuccessorFullActionGraph +OAI.SetTheory.PartitionPrinciple.Forcing.GroundFlatSuccessorNameGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundForcingHistoryLimitConnection +OAI.SetTheory.PartitionPrinciple.Forcing.GroundForcingHistoryOrders +OAI.SetTheory.PartitionPrinciple.Forcing.GroundForcingHistorySuccessors +OAI.SetTheory.PartitionPrinciple.Forcing.GroundGraphValueDescendantWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundIdealProjections +OAI.SetTheory.PartitionPrinciple.Forcing.GroundInaccessibleConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundIndexedGraphNameFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundInvariantNamePowers +OAI.SetTheory.PartitionPrinciple.Forcing.GroundLayerWitnessPushforward +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainConditionalTotality +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalCompressedNameForcing +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalRectangleActionData +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalRowNiceNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalRowSupport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalSameFilterPreparationBatch +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageOneForcing +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageOneGroundAction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageThreeAction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageThreeNameLifting +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageTwoAction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageTwoConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStageTwoNameLifting +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStructuralCommonSupportInduction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStructuralDecidingAntichains +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStructuralPositionSupport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStructuralRefinementNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalStructuralSupportPreparation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalSupportConstruction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalSupportedCertificateFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainFinalSymmetricRefinementOutputs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainPrefixInsertionFamilyTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainPrefixLimitActionLaws +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainPrefixLimitLayerWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainPrefixPriorLayerWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMainPrefixRectangleBoundTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundMixtureNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNameSequenceForcingWitness +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNameSequenceValues +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNiceNameGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNiceNameNormalization +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNicePreparationWitnessBounds +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNiceRefinementClassSupports +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNiceRefinementIndexActionLaws +OAI.SetTheory.PartitionPrinciple.Forcing.GroundNiceSupportEvaluation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundOrdinaryEqualityDecisionFusion +OAI.SetTheory.PartitionPrinciple.Forcing.GroundOrdinaryMembershipAntichainFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundOutsideRowNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPairNameFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPreparationForcing +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPreparedCertificateActionPackages +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPreparedWitnessSelections +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPrincipalSupportZF +OAI.SetTheory.PartitionPrinciple.Forcing.GroundProductActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundProductSizeWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundProjectedRowChooserWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundPushFilters +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRankedCompressionFieldsTransport +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRankedFixedTopSerialization +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRawNiceNameGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRawPreparedFamilyConditionPersistence +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRawRefinementStageWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRawRowAssignmentActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRawStageRefinementTestActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRecordedPreparationSupportInclusions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRecursiveActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRecursiveRowNameActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRefinementAssignmentActionFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRefinementAssignmentLabelNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRefinementCollisionSymmetry +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRefinementDiagonalConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRefinementValidityForcing +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRenamedNameFamilyBounds +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRepresentativeAntichainBounds +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRepresentedDomainConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRestrictedActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRowAssignmentActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRowGenerics +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRowTermSetNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundRowTupleEvaluation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSelectedOrbitNameFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSeparatedRowConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSharedConditionalNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSizeWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSmallFunctionPermutations +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneDataBoundFixation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneDataBoundSmallFixation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneFlatConditions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneGenericProjection +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneGroundAction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneNameLiftFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneNameLifting +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageOneRawNames +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageThreeActionInputs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageThreeDataBoundFixation +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageTwoActionInputs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageTwoConditionTop +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageTwoNameGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageTwoNameLiftFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStageTwoNamePositionSupports +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStoredPreparedFamilyActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStoredStructuralRequestActions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStructuralForcingActionGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.GroundStructuralForcingHistoryConstruction +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSupportedCertificateFamilyDecisions +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSupportedCertificateProfiles +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSymmetricCollection +OAI.SetTheory.PartitionPrinciple.Forcing.GroundSymmetricPowerSet +OAI.SetTheory.PartitionPrinciple.Forcing.GroundTaskBearingSuccessorWitness +OAI.SetTheory.PartitionPrinciple.Forcing.GroundTestedMeetFilters +OAI.SetTheory.PartitionPrinciple.Forcing.GroundUnionSizeWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.GroundVaryingFamilyEvaluation +OAI.SetTheory.PartitionPrinciple.Forcing.GrowthLayerWitnessRestrictions +OAI.SetTheory.PartitionPrinciple.Forcing.IdealChain +OAI.SetTheory.PartitionPrinciple.Forcing.IdealInsertionProfileTransport +OAI.SetTheory.PartitionPrinciple.Forcing.IndexedTupleNames +OAI.SetTheory.PartitionPrinciple.Forcing.InitialAction +OAI.SetTheory.PartitionPrinciple.Forcing.InitialRecursiveActionAgreement +OAI.SetTheory.PartitionPrinciple.Forcing.InitialRowForcing +OAI.SetTheory.PartitionPrinciple.Forcing.LimitAction +OAI.SetTheory.PartitionPrinciple.Forcing.MainPrefixConditionalStepCodes +OAI.SetTheory.PartitionPrinciple.Forcing.MainPrefixConditionalTraceLaws +OAI.SetTheory.PartitionPrinciple.Forcing.MeetOrderPosetActions +OAI.SetTheory.PartitionPrinciple.Forcing.NameFamilySetTransport +OAI.SetTheory.PartitionPrinciple.Forcing.NameMixingRanks +OAI.SetTheory.PartitionPrinciple.Forcing.NameOrbitBounds +OAI.SetTheory.PartitionPrinciple.Forcing.NamePresentationEquivalences +OAI.SetTheory.PartitionPrinciple.Forcing.NameRenameSteps +OAI.SetTheory.PartitionPrinciple.Forcing.NatActionUnions +OAI.SetTheory.PartitionPrinciple.Forcing.OrbitPairGraphNames +OAI.SetTheory.PartitionPrinciple.Forcing.OwnerBirthLayerTransport +OAI.SetTheory.PartitionPrinciple.Forcing.PairFamilyEvaluation +OAI.SetTheory.PartitionPrinciple.Forcing.PreparedWitnessCertificateGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.PresentedMeetActionCodes +OAI.SetTheory.PartitionPrinciple.Forcing.ProfileTransport +OAI.SetTheory.PartitionPrinciple.Forcing.RecursiveAction +OAI.SetTheory.PartitionPrinciple.Forcing.RecursiveNextTaskActions +OAI.SetTheory.PartitionPrinciple.Forcing.RecursiveRefinementUnionConditions +OAI.SetTheory.PartitionPrinciple.Forcing.RefinementAssignmentActionLaws +OAI.SetTheory.PartitionPrinciple.Forcing.RefinementAssignmentLabelActions +OAI.SetTheory.PartitionPrinciple.Forcing.RefinementAssignmentLabelNames +OAI.SetTheory.PartitionPrinciple.Forcing.RefinementCoarseImageNames +OAI.SetTheory.PartitionPrinciple.Forcing.RefinementDataBoundActions +OAI.SetTheory.PartitionPrinciple.Forcing.RelationActionFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.RenamedPairNameFamilies +OAI.SetTheory.PartitionPrinciple.Forcing.RequestedSupportOwners +OAI.SetTheory.PartitionPrinciple.Forcing.RootedSupportOwners +OAI.SetTheory.PartitionPrinciple.Forcing.RowNames +OAI.SetTheory.PartitionPrinciple.Forcing.RowSupportDescent +OAI.SetTheory.PartitionPrinciple.Forcing.SmallCodedMeetActions +OAI.SetTheory.PartitionPrinciple.Forcing.StageOneEvaluatedAssignments +OAI.SetTheory.PartitionPrinciple.Forcing.StageThreeAssignmentTestActions +OAI.SetTheory.PartitionPrinciple.Forcing.StageTwoAssignmentTestActions +OAI.SetTheory.PartitionPrinciple.Forcing.StageTwoConditionUnions +OAI.SetTheory.PartitionPrinciple.Forcing.StructuralAssignmentActionGraphs +OAI.SetTheory.PartitionPrinciple.Forcing.StructuralAssignmentActionLaws +OAI.SetTheory.PartitionPrinciple.Forcing.StructuralForcingStageWitnessStep +OAI.SetTheory.PartitionPrinciple.Forcing.SymmetricGroundForcing +OAI.SetTheory.PartitionPrinciple.Forcing.TaskTransportCodes +OAI.SetTheory.PartitionPrinciple.Forcing.UniformGroundNames +OAI.SetTheory.PartitionPrinciple.Forcing.UniformGroundSizeWitnesses +OAI.SetTheory.PartitionPrinciple.Forcing.UniqueFiberForcing +OAI.SetTheory.PartitionPrinciple.Geometry.AssignmentIndexLevels +OAI.SetTheory.PartitionPrinciple.Geometry.AssignmentNestedSplices +OAI.SetTheory.PartitionPrinciple.Geometry.AtomicEqualitySteps +OAI.SetTheory.PartitionPrinciple.Geometry.AtomicSoundness +OAI.SetTheory.PartitionPrinciple.Geometry.BinaryTiles +OAI.SetTheory.PartitionPrinciple.Geometry.CheckCertificates +OAI.SetTheory.PartitionPrinciple.Geometry.CompatibleCopies +OAI.SetTheory.PartitionPrinciple.Geometry.CompleteProjectionPredensity +OAI.SetTheory.PartitionPrinciple.Geometry.Compression +OAI.SetTheory.PartitionPrinciple.Geometry.CompressionExternalTileOverlaps +OAI.SetTheory.PartitionPrinciple.Geometry.CompressionTheorem +OAI.SetTheory.PartitionPrinciple.Geometry.CompressionUnionBaseFilling +OAI.SetTheory.PartitionPrinciple.Geometry.DecodedGroundGroups +OAI.SetTheory.PartitionPrinciple.Geometry.DecodedMeetMaps +OAI.SetTheory.PartitionPrinciple.Geometry.DepthLayerHeights +OAI.SetTheory.PartitionPrinciple.Geometry.DirectSystem +OAI.SetTheory.PartitionPrinciple.Geometry.EligibleBatchAgreement +OAI.SetTheory.PartitionPrinciple.Geometry.EligibleTaskCovariance +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalColumnOrders +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalCopyDescent +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalHeights +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalOwnerCoordinateLaws +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalTileVertexPresentation +OAI.SetTheory.PartitionPrinciple.Geometry.ExternalTranslation +OAI.SetTheory.PartitionPrinciple.Geometry.FinalProfilePersistence +OAI.SetTheory.PartitionPrinciple.Geometry.FinalRectangles +OAI.SetTheory.PartitionPrinciple.Geometry.FiniteIntervalExtension +OAI.SetTheory.PartitionPrinciple.Geometry.FiniteIterationTraces +OAI.SetTheory.PartitionPrinciple.Geometry.FiniteWordOperations +OAI.SetTheory.PartitionPrinciple.Geometry.FixedCompressionSeeds +OAI.SetTheory.PartitionPrinciple.Geometry.GluingHeights +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAbsentLiftRangeCollisions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAssignmentIndexLevels +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAssignmentLabelDomainTotality +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAssignmentRepresentativeClosure +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAssignmentRequestBatches +OAI.SetTheory.PartitionPrinciple.Geometry.GroundAttachmentEmbeddings +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBatchAttachment +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBatchEmbeddingRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBatchHeightGraphs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBelowExternalPoints +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBelowFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBelowInitialCompression +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBinaryRowRecordedPreparationBounds +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBinaryRows +OAI.SetTheory.PartitionPrinciple.Geometry.GroundBinaryUnionFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCantorDiagonal +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCertificateBasisUnions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCertificateProfileImageFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCodedBinaryHeights +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCoherentHeightUnion +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompleteProjectionRefinementTests +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompletedCompressionCertificateRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompletedMapRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionFiniteFieldGraphs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionHeightSteps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionMarkingRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionOrigins +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionStampBounds +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCompressionStarIncidence +OAI.SetTheory.PartitionPrinciple.Geometry.GroundConstantBatchLayers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundContainmentOrders +OAI.SetTheory.PartitionPrinciple.Geometry.GroundCumulativeHierarchyLevels +OAI.SetTheory.PartitionPrinciple.Geometry.GroundDefinableIndexBounds +OAI.SetTheory.PartitionPrinciple.Geometry.GroundDefinableRowAssignmentOrders +OAI.SetTheory.PartitionPrinciple.Geometry.GroundDefinableSelections +OAI.SetTheory.PartitionPrinciple.Geometry.GroundEligibleCaps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundEqualityStep +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalAlphabetInversion +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalCompressionFieldRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalCutoffCoherence +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalCutoffLayers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalGenerators +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalGroupEmbeddings +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalLocalHeightFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalLocalHeightSelection +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalMainTransition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalProfilePreservation +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalRawPriorLayers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalRectangleFulfillment +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalRequestFieldRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalRequestOverlaps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalRewriteSteps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalSerializedCore +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalSlotCopies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalStarOverlaps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundExternalTileSlotSupports +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFairPreparationEventOrigins +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFairPreparationMonotonicity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFairRefinementAssignmentVisits +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFamilyValueUnions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFinalInsertionExceptions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFiniteAccounting +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFiniteSeedBounds +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFiniteWordLaws +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFiniteWordLength +OAI.SetTheory.PartitionPrinciple.Geometry.GroundFixedTopOrders +OAI.SetTheory.PartitionPrinciple.Geometry.GroundForcedSequenceReadings +OAI.SetTheory.PartitionPrinciple.Geometry.GroundGeometry +OAI.SetTheory.PartitionPrinciple.Geometry.GroundGrowthLayerRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundHartogs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundHeightPushforward +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIdentityInsertionTasks +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedClassInclusions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedImageCovers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedMixedOperationLifts +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedOperationLifts +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedSubstructures +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIndexedValueLifts +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialCompletedCompressionCertificates +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialCompressionCompletion +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialCompressionIterates +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialCompressionOrigin +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialExternalGroup +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialExternalHeights +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialLiftEmbeddings +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialMainAlgebra +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialSeedMatchedSerialization +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInitialSeedSerializationRanks +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInternalNoChooserConsequences +OAI.SetTheory.PartitionPrinciple.Geometry.GroundInternalRowsInZF +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIntervalEmbeddingRelation +OAI.SetTheory.PartitionPrinciple.Geometry.GroundIntervalSelection +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLayerSourceCongruence +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLiftedCompressionGraphs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLinkedProfilePreservation +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLinkedProfileTransitionRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLinkedTransitionRetarget +OAI.SetTheory.PartitionPrinciple.Geometry.GroundLiteralTaskFieldRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainBoundTaskOutput +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainCompressionActorCode +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainDiagramAppend +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalDecidedVisibility +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalEnumeratedCertificateFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalExtensionBases +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalFairPreparationOrbits +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalFulfillmentConstruction +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalOrdinaryInsertion +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalPersistentAssignmentLabels +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalPreparedInsertionProfiles +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRefinementSystem +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRowModelDescent +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRowOrdinaryZF +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRowOrdinaryZFC +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRowRectangles +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalRowTerms +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalSeparatedActors +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStoredPreparedDensity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralCompression +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralLateProfileExclusions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralRectangleRefinements +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralRefinementOutputs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralRowNoChooser +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainFinalStructuralSeparationRefinements +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainTaskCapFulfillment +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainTransitionLaws +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMainTransitionValidity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMeetGeneratorSteps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMixtureDensityRecovery +OAI.SetTheory.PartitionPrinciple.Geometry.GroundMixtureTermBounds +OAI.SetTheory.PartitionPrinciple.Geometry.GroundNaturalFamilyShift +OAI.SetTheory.PartitionPrinciple.Geometry.GroundNaturalNumbers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundNiceAssignmentClassFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundNiceRefinementVisibility +OAI.SetTheory.PartitionPrinciple.Geometry.GroundNormalizedRefinementOutputs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundOmegaOneRowModel +OAI.SetTheory.PartitionPrinciple.Geometry.GroundOrdinarySubmodelReflection +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPartialCoverPartitions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPredenseMeet +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparationFamilyImages +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparedAlignedReferenceCollisions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparedMixedCollisions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparedPositionCollisions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparedSelectionProfiles +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPreparedStructuralInsertionCollisions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundPresentedPreimages +OAI.SetTheory.PartitionPrinciple.Geometry.GroundProfiledExternalRequests +OAI.SetTheory.PartitionPrinciple.Geometry.GroundProjectedRowUniqueFibers +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRankedCompressionSerialization +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRankedExternalSerialization +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRankedLayerSelection +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRawCandidateDensity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRawLayerPushforward +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRawRefinementDataIdentification +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRecognizedInitialOrigin +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementAbsentLiftInsertions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementAssignmentImages +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementAssignmentLabelEntries +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementCoarseVisibility +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementDataOutputs +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementFinitePowerSystems +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementRawTestMonotonicity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRefinementVisibleLiftInsertions +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRepresentativeIndexSteps +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRequestedCompressionTiles +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRequestedRectangleHeights +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRetainedPreparationSelections +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRowAssignmentCuts +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRowAssignmentProjections +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRowAssignmentTransitionFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundRowDistinguishing +OAI.SetTheory.PartitionPrinciple.Geometry.GroundSerialOrbits +OAI.SetTheory.PartitionPrinciple.Geometry.GroundSerializedBoundNormalization +OAI.SetTheory.PartitionPrinciple.Geometry.GroundSerializedCandidateLevels +OAI.SetTheory.PartitionPrinciple.Geometry.GroundSharedRefinementValidity +OAI.SetTheory.PartitionPrinciple.Geometry.GroundSingleAttachment +OAI.SetTheory.PartitionPrinciple.Geometry.GroundStoredPreparationFamilyPersistence +OAI.SetTheory.PartitionPrinciple.Geometry.GroundStoredVisitCertificates +OAI.SetTheory.PartitionPrinciple.Geometry.GroundStructuralCompleteProjections +OAI.SetTheory.PartitionPrinciple.Geometry.GroundStructuralFinitePowerTerms +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTaskBearingInsertionFulfillment +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTaskBearingRectangles +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTaskBearingSeparation +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTaskBearingStrictTop +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTaskRepresentativeRecognition +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTemplateHeightRanges +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTemplateIntervalFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTileStarIncidence +OAI.SetTheory.PartitionPrinciple.Geometry.GroundTwoPointHeights +OAI.SetTheory.PartitionPrinciple.Geometry.GroundUnionInterpretation +OAI.SetTheory.PartitionPrinciple.Geometry.GroundVisibilitySupportIncidence +OAI.SetTheory.PartitionPrinciple.Geometry.GrowthLayerSourceCongruence +OAI.SetTheory.PartitionPrinciple.Geometry.HeightAttachment +OAI.SetTheory.PartitionPrinciple.Geometry.HeightColumnBoundLaws +OAI.SetTheory.PartitionPrinciple.Geometry.InitialCompressionAccounting +OAI.SetTheory.PartitionPrinciple.Geometry.InitialCompressionUnionProfiles +OAI.SetTheory.PartitionPrinciple.Geometry.InitialRepresentativeAgreement +OAI.SetTheory.PartitionPrinciple.Geometry.IntervalEmbeddingFamilyCodes +OAI.SetTheory.PartitionPrinciple.Geometry.IntervalTraceValidity +OAI.SetTheory.PartitionPrinciple.Geometry.LiftedCompressionEmbeddings +OAI.SetTheory.PartitionPrinciple.Geometry.LiftedCompressionFunctions +OAI.SetTheory.PartitionPrinciple.Geometry.MainDiagramGluing +OAI.SetTheory.PartitionPrinciple.Geometry.MainDiagrams +OAI.SetTheory.PartitionPrinciple.Geometry.MainEndpoints +OAI.SetTheory.PartitionPrinciple.Geometry.MainInitial +OAI.SetTheory.PartitionPrinciple.Geometry.MainInsertion +OAI.SetTheory.PartitionPrinciple.Geometry.MainProfilePersistence +OAI.SetTheory.PartitionPrinciple.Geometry.MainRectangleMeets +OAI.SetTheory.PartitionPrinciple.Geometry.MainRectangles +OAI.SetTheory.PartitionPrinciple.Geometry.NodeCoding +OAI.SetTheory.PartitionPrinciple.Geometry.OldProfilePreservationComposition +OAI.SetTheory.PartitionPrinciple.Geometry.OutwardSchedule +OAI.SetTheory.PartitionPrinciple.Geometry.PartialBatchStep +OAI.SetTheory.PartitionPrinciple.Geometry.PresentedRowAssignmentDecoding +OAI.SetTheory.PartitionPrinciple.Geometry.PresentedRowAssignmentTotality +OAI.SetTheory.PartitionPrinciple.Geometry.PrincipalBatch +OAI.SetTheory.PartitionPrinciple.Geometry.RationalHeightDescent +OAI.SetTheory.PartitionPrinciple.Geometry.RationalOrderBounds +OAI.SetTheory.PartitionPrinciple.Geometry.RawEqualitySteps +OAI.SetTheory.PartitionPrinciple.Geometry.RectangleFulfillmentAtBound +OAI.SetTheory.PartitionPrinciple.Geometry.RectangleTile +OAI.SetTheory.PartitionPrinciple.Geometry.RefinementIndexThreeLevels +OAI.SetTheory.PartitionPrinciple.Geometry.RefinementLevelThreeTestGuards +OAI.SetTheory.PartitionPrinciple.Geometry.RefinementLevelThreeUnionGuards +OAI.SetTheory.PartitionPrinciple.Geometry.RefinementValidityReindex +OAI.SetTheory.PartitionPrinciple.Geometry.RepresentativeIndexSteps +OAI.SetTheory.PartitionPrinciple.Geometry.RequestedOwnerSlotLaws +OAI.SetTheory.PartitionPrinciple.Geometry.RootedSupportOrder +OAI.SetTheory.PartitionPrinciple.Geometry.RowAssignmentOrderLaws +OAI.SetTheory.PartitionPrinciple.Geometry.RowAssignmentTransitionFamilies +OAI.SetTheory.PartitionPrinciple.Geometry.RowAtomicDescent +OAI.SetTheory.PartitionPrinciple.Geometry.RowCopyRefinements +OAI.SetTheory.PartitionPrinciple.Geometry.RowPositionBounds +OAI.SetTheory.PartitionPrinciple.Geometry.SeparationTileCodes +OAI.SetTheory.PartitionPrinciple.Geometry.StructuralPreparationSourceImages +OAI.SetTheory.PartitionPrinciple.Geometry.TaggedGrowthLayerRanks +OAI.SetTheory.PartitionPrinciple.Geometry.TaskSystem +OAI.SetTheory.PartitionPrinciple.Geometry.TemplateHeightRangeCodes +OAI.SetTheory.PartitionPrinciple.Geometry.TileStarIncomingCodes +OAI.SetTheory.PartitionPrinciple.Geometry.TileTreeGluing +OAI.SetTheory.PartitionPrinciple.Geometry.UniformAtomicEquality +OAI.SetTheory.PartitionPrinciple.Main +OAI.SetTheory.PartitionPrinciple.Model +OAI.SetTheory.PartitionPrinciple.Models.CopyQuotient +OAI.SetTheory.PartitionPrinciple.Models.ExternalCopyQuotient +OAI.SetTheory.PartitionPrinciple.Models.GroundChoiceEnumerationSteps +OAI.SetTheory.PartitionPrinciple.Models.GroundChoiceEnumerationTraces +OAI.SetTheory.PartitionPrinciple.Models.GroundCoherentHeightChoices +OAI.SetTheory.PartitionPrinciple.Models.GroundCountableQuotients +OAI.SetTheory.PartitionPrinciple.Models.GroundExternalWordQuotient +OAI.SetTheory.PartitionPrinciple.Models.GroundFiniteWordInjections +OAI.SetTheory.PartitionPrinciple.Models.GroundInjectionRestrictions +OAI.SetTheory.PartitionPrinciple.Models.GroundInternalRowChoice +OAI.SetTheory.PartitionPrinciple.Models.GroundMainFinalAssignmentLabelInjections +OAI.SetTheory.PartitionPrinciple.Models.GroundMainFinalPartitionModel +OAI.SetTheory.PartitionPrinciple.Models.GroundMainFinalStructuralRowNonchoice +OAI.SetTheory.PartitionPrinciple.Models.GroundNameSupportEnumerationChoices +OAI.SetTheory.PartitionPrinciple.Models.GroundOrdinalPartitionInjectionAssembly +OAI.SetTheory.PartitionPrinciple.Models.GroundQuotientBinaryOperations +OAI.SetTheory.PartitionPrinciple.Models.GroundQuotientUnaryOperations +OAI.SetTheory.PartitionPrinciple.Models.GroundRefinementQuotientNames +OAI.SetTheory.PartitionPrinciple.Models.GroundRowCoverPartitionPrinciple +OAI.SetTheory.PartitionPrinciple.Models.GroundSuccessorInjections +OAI.SetTheory.PartitionPrinciple.Models.GroundSupportedEqualityChoices +OAI.SetTheory.PartitionPrinciple.Models.IncidenceQuotient +OAI.SetTheory.PartitionPrinciple.Models.LiteralQuotientRankBounds +OAI.SetTheory.PartitionPrinciple.Models.RootedGluingQuotient +OAI.SetTheory.PartitionPrinciple.Models.Separation +OAI.SetTheory.PartitionPrinciple.Transfinite.AgreementLimits +OAI.SetTheory.PartitionPrinciple.Transfinite.AmalgamationCoinitiality +OAI.SetTheory.PartitionPrinciple.Transfinite.AttachmentCoinitiality +OAI.SetTheory.PartitionPrinciple.Transfinite.ChronologicalTheorem +OAI.SetTheory.PartitionPrinciple.Transfinite.CodedMainPrefixSystems +OAI.SetTheory.PartitionPrinciple.Transfinite.CoherentTower +OAI.SetTheory.PartitionPrinciple.Transfinite.CoinitialityPreservation +OAI.SetTheory.PartitionPrinciple.Transfinite.CompressionPrefixCoinitiality +OAI.SetTheory.PartitionPrinciple.Transfinite.CountableCoding +OAI.SetTheory.PartitionPrinciple.Transfinite.CrossStageParameterSupports +OAI.SetTheory.PartitionPrinciple.Transfinite.ExternalBirthLayerSeparation +OAI.SetTheory.PartitionPrinciple.Transfinite.ExternalChronologyStageLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.ExternalRequestRankBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.FairPreparationBirthPersistence +OAI.SetTheory.PartitionPrinciple.Transfinite.FinalCardinality +OAI.SetTheory.PartitionPrinciple.Transfinite.FinalInsertionStages +OAI.SetTheory.PartitionPrinciple.Transfinite.FinalRectangleStages +OAI.SetTheory.PartitionPrinciple.Transfinite.FinalStageBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.FiniteFamilyRankBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.FiniteFlatHistoryCoherence +OAI.SetTheory.PartitionPrinciple.Transfinite.GluingBirthRanges +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundBatchBirths +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundBinaryRowStageOneRefinement +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCanonicalCompressionHistory +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologicalBasis +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologicalCompressionCoinitiality +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologicalExternalCoinitiality +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologyFieldAppend +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologyLayerRelation +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologyPairRanks +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundChronologyPairs +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCoinitialOperations +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCompressionBirthData +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCompressionBirths +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCompressionCarrierRankBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCompressionPrefixGraphs +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableFunctionClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableFunctionEnumerations +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableFunctionOrdinaryZFC +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableFunctionSequences +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableFunctionZF +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableLayerCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableProducts +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableRelationSelections +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableRowExactUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundCountableRowSequenceReflection +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundDefinableRefinementHistories +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundExtensionOrdinals +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundExternalBirthLayers +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundExternalSerializedChronology +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFairPreparationLimitCertificates +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFiniteBirthHistories +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFixedFairPreparationLimitCertificates +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFlatLimitAdequacy +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFlatSuccessorAssignmentGraphs +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFlatSuccessorAtomicTransfer +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFlatSuccessorProjectedFilters +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundFourFlatStageHistories +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundHistoryFields +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundHistoryUnionBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInaccessibleOrdinalClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialCompressionHistory +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialCompressionPrefix +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialExternalBirths +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialExternalChronology +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialMainSeedSuccessorSerialization +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialMainStage +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialPreservedMainPrefix +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInitialRecursiveSuccessor +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundIntervalRecursion +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundInvariantSuccessors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundLayerBirthFibers +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundLinkedMainStageCodeLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundLinkedMainStageLevels +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalChronology +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalPersistentSuccessorLabels +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalPrefixCompatibleCaps +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalPrefixPreparationBatches +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalPreparedPrefixBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageOneClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageThreeClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageThreeHistory +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageThreeSupport +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageTwoClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageTwoIndices +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStageTwoSupport +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStructuralPrefixDescent +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalStructuralSizeFamilies +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainFinalSuccessorPreparedProfiles +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainOrdinalConstructionData +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixConePreservation +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixConeValues +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixCoveredLimitAppend +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixDecoding +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixExtensionRelations +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixFieldFamilies +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixFinalDirectedness +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixFinalInsertion +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixFinalStrictGrowth +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixInsertionSuccessors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitBottom +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitChronologyCore +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitCoverageConstruction +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitCoverageGraph +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitGroupLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixLimitSizes +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixOmegaOneAppend +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixPreservedSeeds +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixPriorFields +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixRawCoveredAppend +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixRectangleLocalization +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixSelectedStepTotality +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixSelectedSuccessors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixSuccessor +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainPrefixTopColumns +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainStageCandidates +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainStageFromCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainStageInvariant +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainSuccessorCompressionActors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainSuccessorProfilePreservation +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundMainSuccessorSeparation +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundNaturalRecursion +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOmegaOneTaskBearingSuccessorFunction +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOrdinalEnumerationFamilies +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOrdinalImagePartitions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOrdinalOrderCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOrdinalPartialMapCovers +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundOrdinaryCountableFunctions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRankedSerializedChronology +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRawFinitePowerStageSystems +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRawRefinementStageZF +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRecursiveOriginalRowFamilies +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRecursiveRefinementBinaryUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRecursiveRefinementInternalClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRecursiveRefinementMixedUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRecursiveRowCompleteProjection +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRefinementFullIndexSize +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundRefinementHistorySpliceSteps +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSelectedMainLimitCoverage +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSerializedChronologyRestrictions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSerializedChronologyTimeEquality +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSerializedCompressionChronology +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSmallAssignmentCuts +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSmallFamilyRangeRanks +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundSmallFunctionSpaces +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneAssignmentImages +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneAssignmentUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneOrder +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneProjectedFilters +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneSequenceProjections +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageOneTestEquivalence +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageThreeAssignmentFamilies +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageThreeClosureData +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageThreeInternalClosure +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageThreeSuccessorLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageTwoAtomicLifting +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageTwoIndexAnchors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageTwoProjectedFilters +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStageTwoRefinementObjects +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStandardInaccessible +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStrongLimitPowers +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStructuralBirthLevelSelectors +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStructuralFullIndexSize +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStructuralFullIndexWeakSize +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStructuralHistoryTestUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundStructuralRefinementHistories +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundTaskBearingSuccessorDecoding +OAI.SetTheory.PartitionPrinciple.Transfinite.GroundTwoStageMainDiagram +OAI.SetTheory.PartitionPrinciple.Transfinite.HeightTower +OAI.SetTheory.PartitionPrinciple.Transfinite.InaccessibleBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.InitialRecursiveTaskLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.LimitGroup +OAI.SetTheory.PartitionPrinciple.Transfinite.LimitProfilePersistence +OAI.SetTheory.PartitionPrinciple.Transfinite.LinkedSuccessorOutputFieldEquality +OAI.SetTheory.PartitionPrinciple.Transfinite.MainBirthExtensions +OAI.SetTheory.PartitionPrinciple.Transfinite.MainBirthOrigins +OAI.SetTheory.PartitionPrinciple.Transfinite.MainOrdinalSteps +OAI.SetTheory.PartitionPrinciple.Transfinite.MainPrefixHistoryUnionRecognition +OAI.SetTheory.PartitionPrinciple.Transfinite.MainPrefixSelectedTraceLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.MainStageFilterBases +OAI.SetTheory.PartitionPrinciple.Transfinite.MainStageTaskCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.NaturalRecursionTraceValues +OAI.SetTheory.PartitionPrinciple.Transfinite.NonzeroLimitOrdinalCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.OrdinalExternalHeights +OAI.SetTheory.PartitionPrinciple.Transfinite.OrdinalRecursionTraces +OAI.SetTheory.PartitionPrinciple.Transfinite.OrdinalSetCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.OwnerBirthLayers +OAI.SetTheory.PartitionPrinciple.Transfinite.PartialBatchLimits +OAI.SetTheory.PartitionPrinciple.Transfinite.PreservedMainPrefixHistoryValues +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveLiftAgreement +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveMaps +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveNextMapInputs +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveRefinementInclusionCoherence +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveRefinementMapCoherence +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveStateFieldEnvironments +OAI.SetTheory.PartitionPrinciple.Transfinite.RecursiveStructuralRefinementHistories +OAI.SetTheory.PartitionPrinciple.Transfinite.RefinementBirthEnumerationFairness +OAI.SetTheory.PartitionPrinciple.Transfinite.RefinementBirthSchedules +OAI.SetTheory.PartitionPrinciple.Transfinite.RefinementFlatSuccessorUnions +OAI.SetTheory.PartitionPrinciple.Transfinite.RefinementHistoryPrefixLevels +OAI.SetTheory.PartitionPrinciple.Transfinite.SerializedChronologyCodes +OAI.SetTheory.PartitionPrinciple.Transfinite.SetRankBounds +OAI.SetTheory.PartitionPrinciple.Transfinite.SmallTileHeightInputs +OAI.SetTheory.PartitionPrinciple.Transfinite.StageOneDataBoundLaws +OAI.SetTheory.PartitionPrinciple.Transfinite.StageTwoAssignmentSplices +OAI.SetTheory.PartitionPrinciple.Transfinite.StageTwoClosureData +OAI.SetTheory.PartitionPrinciple.Transfinite.StageTwoSupportData +OAI.SetTheory.PartitionPrinciple.Transfinite.SuccessorBirths diff --git a/tasks/partition-principle/solution/reference.py b/tasks/partition-principle/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/partition-principle/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/partition-principle/solution/solve.sh b/tasks/partition-principle/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d30e61989217e8e7158b90af959cf0e01ffbcc06 --- /dev/null +++ b/tasks/partition-principle/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PartitionPrinciple, i.e. module OAI.SetTheory.PartitionPrinciple.Main and the +# 943 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.SetTheory.PartitionPrinciple.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PartitionPrinciple" diff --git a/tasks/partition-principle/task.toml b/tasks/partition-principle/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd60bdd9d947b171814f967a417da24643435c9f --- /dev/null +++ b/tasks/partition-principle/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/partition-principle" +version = "1.0.0" +description = "Prove PartitionPrinciple (openai/math family 244: The partition principle does not imply choice) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PartitionPrinciple.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PartitionPrinciple" +family = "244" +family_title = "The partition principle does not imply choice" +subject = "Mathematical logic" +theorems = ["OAI.PartitionPilot.Forcing.TransitiveGround.exists_model_partitionPrinciple_without_choice"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.SetTheory.PartitionPrinciple.Main" +reference_modules = 943 +reference_lean_bytes = 12843154 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2843 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 22500 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/partition-principle/tests/Challenge.lean b/tasks/partition-principle/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e551315f882d35ba66f9f24bd67f27ce30cfd2f5 --- /dev/null +++ b/tasks/partition-principle/tests/Challenge.lean @@ -0,0 +1,277 @@ +import Mathlib + +namespace OAI + +namespace PartitionPilot.Forcing + +universe u + +inductive SetFormula : Nat → Type + | equal {n} : Fin n → Fin n → SetFormula n + | mem {n} : Fin n → Fin n → SetFormula n + | neg {n} : SetFormula n → SetFormula n + | conj {n} : SetFormula n → SetFormula n → SetFormula n + | all {n} : SetFormula (n + 1) → SetFormula n + +namespace SetFormula + +def extend {A : Type u} {n : Nat} (x : A) (env : Fin n → A) : Fin (n + 1) → A := + Fin.cases x env + +def Realize (U : Set ZFSet.{u}) : {n : Nat} → SetFormula n → (Fin n → ZFSet.{u}) → Prop + | _, .equal i j, env => env i = env j + | _, .mem i j, env => env i ∈ env j + | _, .neg φ, env => ¬ Realize U φ env + | _, .conj φ ψ, env => Realize U φ env ∧ Realize U ψ env + | _, .all φ, env => ∀ x ∈ U, Realize U φ (extend x env) + +def ex {n : Nat} (φ : SetFormula (n + 1)) : SetFormula n := .neg (.all (.neg φ)) + +def disj {n : Nat} (φ ψ : SetFormula n) : SetFormula n := .neg (.conj (.neg φ) (.neg ψ)) + +def imp {n : Nat} (φ ψ : SetFormula n) : SetFormula n := .neg (.conj φ (.neg ψ)) + +end SetFormula + +inductive BoundedFormula : Nat → Type + | equal {n} : Fin n → Fin n → BoundedFormula n + | mem {n} : Fin n → Fin n → BoundedFormula n + | neg {n} : BoundedFormula n → BoundedFormula n + | conj {n} : BoundedFormula n → BoundedFormula n → BoundedFormula n + | allMem {n} : Fin n → BoundedFormula (n + 1) → BoundedFormula n + +namespace BoundedFormula + +open SetFormula + +def imp {n} (φ ψ : BoundedFormula n) : BoundedFormula n := .neg (.conj φ (.neg ψ)) + +def disj {n} (φ ψ : BoundedFormula n) : BoundedFormula n := .neg (.conj (.neg φ) (.neg ψ)) + +def exMem {n} (b : Fin n) (φ : BoundedFormula (n + 1)) : BoundedFormula n := + .neg (.allMem b (.neg φ)) + +def toFormula : {n : Nat} → BoundedFormula n → SetFormula n + | _, .equal i j => .equal i j + | _, .mem i j => .mem i j + | _, .neg φ => .neg φ.toFormula + | _, .conj φ ψ => .conj φ.toFormula ψ.toFormula + | _, .allMem b φ => .all (SetFormula.imp (.mem 0 b.succ) φ.toFormula) + +def singletonFormula {n} (z x : Fin n) : BoundedFormula n := + .conj (.mem x z) (.allMem z (.equal 0 x.succ)) + +def unorderedPairFormula {n} (z x y : Fin n) : BoundedFormula n := + .conj (.mem x z) (.conj (.mem y z) (.allMem z (disj (.equal 0 x.succ) (.equal 0 y.succ)))) + +def orderedPairFormula {n} (z x y : Fin n) : BoundedFormula n := + exMem z (.conj (singletonFormula 0 x.succ) + (exMem z.succ (.conj (unorderedPairFormula 0 x.succ.succ y.succ.succ) + (unorderedPairFormula z.succ.succ 1 0)))) + +def pairMembershipFormula {n} (x y r : Fin n) : BoundedFormula n := + exMem r (orderedPairFormula 0 x.succ y.succ) + +def relationBetweenFormula {n} (a b f : Fin n) : BoundedFormula n := + .allMem f (exMem a.succ (exMem b.succ.succ (orderedPairFormula 2 1 0))) + +def functionFormula {n} (a b f : Fin n) : BoundedFormula n := + .conj (relationBetweenFormula a b f) + (.allMem a (exMem b.succ (.conj (pairMembershipFormula 1 0 f.succ.succ) + (.allMem b.succ.succ (imp (pairMembershipFormula 2 0 f.succ.succ.succ) (.equal 0 1)))))) + +def nonemptyFormula {n} (x : Fin n) : BoundedFormula n := exMem x (.equal 0 0) + +def choiceFunctionFormula {n} (a f : Fin n) : BoundedFormula n := + .conj (.allMem f (exMem a.succ (exMem 0 (orderedPairFormula 2 1 0)))) + (.allMem a (exMem 0 (.conj (pairMembershipFormula 1 0 f.succ.succ) + (.allMem 1 (imp (pairMembershipFormula 2 0 f.succ.succ.succ) (.equal 0 1)))))) + +end BoundedFormula + +structure TransitiveGround where + sets : Set ZFSet.{u} + transitive : ∀ {x y}, x ∈ sets → y ∈ x → y ∈ sets + +structure InjectionCode (D N f : ZFSet.{u}) : Prop where + function : ZFSet.IsFunc D N f + injective : ∀ x y z, ZFSet.pair x z ∈ f → ZFSet.pair y z ∈ f → x = y + +namespace TransitiveGround + +open SetFormula + +variable (M : TransitiveGround.{u}) + +def groundEmbeddable (D N : ZFSet.{u}) : Prop := ∃ f ∈ M.sets, InjectionCode D N f + +end TransitiveGround + +def setTransitive (x : ZFSet.{u}) : Prop := ∀ y ∈ x, ∀ z ∈ y, z ∈ x + +def ordinalSetProperty (x : ZFSet.{u}) : Prop := + setTransitive x ∧ ∀ y ∈ x, setTransitive y + +namespace TransitiveGround + +open SetFormula + +variable (M : TransitiveGround.{u}) + +noncomputable def groundPower (B : ZFSet.{u}) : ZFSet.{u} := + ZFSet.sep (fun p => p ∈ M.sets) (ZFSet.powerset B) + +end TransitiveGround + +def GroundBelow (M : TransitiveGround.{u}) (A K : ZFSet.{u}) : Prop := + ∃ β ∈ K, M.groundEmbeddable A β + +def GroundCardinal (M : TransitiveGround.{u}) (κ : ZFSet.{u}) : Prop := + ordinalSetProperty κ ∧ ∀ β ∈ κ, ¬ M.groundEmbeddable κ β + +def CofinalFunctionCode (α K f : ZFSet.{u}) : Prop := + ZFSet.IsFunc α K f ∧ ∀ β ∈ K, ∃ x ∈ α, ∃ y ∈ K, + ZFSet.pair x y ∈ f ∧ (β = y ∨ β ∈ y) + +def GroundCofinalRegular (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + ∀ α ∈ K, ∀ f ∈ M.sets, ¬ CofinalFunctionCode α K f + +def GroundCardinalStrongLimit (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + ∀ κ ∈ K, GroundCardinal M κ → GroundBelow M (M.groundPower κ) K + +def GroundStandardInaccessible (M : TransitiveGround.{u}) (K : ZFSet.{u}) : Prop := + GroundCardinal M K ∧ ¬ M.groundEmbeddable K ZFSet.omega ∧ + GroundCofinalRegular M K ∧ GroundCardinalStrongLimit M K + +namespace SetFormula + +def extensionality : SetFormula 0 := + .all (.all (imp + (.all (.conj (imp (.mem 0 2) (.mem 0 1)) (imp (.mem 0 1) (.mem 0 2)))) + (.equal 1 0))) + +def foundation : SetFormula 0 := + .all (imp (ex (.mem 0 1)) + (ex (.conj (.mem 0 1) (.all (.neg (.conj (.mem 0 2) (.mem 0 1))))))) + +def emptySet : SetFormula 0 := ex (.all (.neg (.mem 0 1))) + +def pairing : SetFormula 0 := + .all (.all (ex (.all (.conj + (imp (.mem 0 1) (disj (.equal 0 3) (.equal 0 2))) + (imp (disj (.equal 0 3) (.equal 0 2)) (.mem 0 1)))))) + +def union : SetFormula 0 := + .all (ex (.all (.conj + (imp (.mem 0 1) (ex (.conj (.mem 0 3) (.mem 1 0)))) + (imp (ex (.conj (.mem 0 3) (.mem 1 0))) (.mem 0 1))))) + +def powerSet : SetFormula 0 := + .all (ex (.all (.conj + (imp (.mem 0 1) (.all (imp (.mem 0 1) (.mem 0 3)))) + (imp (.all (imp (.mem 0 1) (.mem 0 3))) (.mem 0 1))))) + +def SeparationSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 1)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ x ∈ U, ∃ y ∈ U, + ∀ z ∈ U, z ∈ y ↔ z ∈ x ∧ Realize U φ (extend z params) + +def CollectionSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 2)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ a ∈ U, + (∀ x ∈ U, x ∈ a → ∃ y ∈ U, Realize U φ (extend x (extend y params))) → + ∃ b ∈ U, ∀ x ∈ U, x ∈ a → + ∃ y ∈ U, y ∈ b ∧ Realize U φ (extend x (extend y params)) + +def emptySetFormula {n : Nat} (x : Fin n) : SetFormula n := .all (.neg (.mem 0 x.succ)) + +def successorFormula {n : Nat} (y x : Fin n) : SetFormula n := + .all (.conj (imp (.mem 0 y.succ) (disj (.equal 0 x.succ) (.mem 0 x.succ))) + (imp (disj (.equal 0 x.succ) (.mem 0 x.succ)) (.mem 0 y.succ))) + +def infinity : SetFormula 0 := + ex (.conj (ex (.conj (.mem 0 1) (emptySetFormula 0))) + (.all (imp (.mem 0 1) (ex (.conj (.mem 0 2) (successorFormula 0 1)))))) + +def choice : SetFormula 0 := + .all (imp (BoundedFormula.allMem 0 (BoundedFormula.nonemptyFormula 0)).toFormula + (ex (BoundedFormula.choiceFunctionFormula 1 0).toFormula)) + +def ReplacementSchema (U : Set ZFSet.{u}) : Prop := + ∀ {n} (φ : SetFormula (n + 2)) (params : Fin n → ZFSet.{u}), + (∀ i, params i ∈ U) → ∀ A ∈ U, + (∀ x ∈ U, x ∈ A → ∃ y ∈ U, Realize U φ (extend x (extend y params)) ∧ + ∀ z ∈ U, Realize U φ (extend x (extend z params)) → z = y) → + ∃ B ∈ U, ∀ y ∈ U, y ∈ B ↔ ∃ x ∈ U, x ∈ A ∧ Realize U φ (extend x (extend y params)) + +def finiteZFAxioms : SetFormula 0 := + .conj extensionality (.conj foundation (.conj emptySet + (.conj pairing (.conj SetFormula.union (.conj powerSet infinity))))) + +def ZFRealization (U : Set ZFSet.{u}) : Prop := + Realize U finiteZFAxioms Fin.elim0 ∧ SeparationSchema U ∧ ReplacementSchema U + +end SetFormula + +namespace BoundedFormula + +open SetFormula + +def injectionFormula {n} (d c f : Fin n) : BoundedFormula n := + .conj (functionFormula d c f) (.allMem d (.allMem d.succ (.allMem c.succ.succ + (imp (.conj (pairMembershipFormula 2 0 f.succ.succ.succ) + (pairMembershipFormula 1 0 f.succ.succ.succ)) (.equal 2 1))))) + +end BoundedFormula + +namespace SetFormula + +def hasInjectionFormula {n} (d c : Fin n) : SetFormula n := + ex (BoundedFormula.injectionFormula d.succ c.succ 0).toFormula + +end SetFormula + +namespace BoundedFormula + +open SetFormula + +def surjectionFormula {n : Nat} (a b f : Fin n) : BoundedFormula n := + .conj (functionFormula a b f) + (.allMem b (exMem a.succ (pairMembershipFormula 0 1 f.succ.succ))) + +end BoundedFormula + +namespace SetFormula + +def partitionPrinciple : SetFormula 0 := + .all (.all (.all (imp (BoundedFormula.surjectionFormula (n := 3) 2 1 0).toFormula + (hasInjectionFormula (n := 3) 1 2)))) + +end SetFormula + +end PartitionPilot.Forcing + +namespace PartitionPilot.Forcing.TransitiveGround + +open SetFormula + +universe u + +variable (M : TransitiveGround.{u}) + +theorem exists_model_partitionPrinciple_without_choice + (pairing : Realize M.sets SetFormula.pairing Fin.elim0) + (unions : Realize M.sets SetFormula.union Fin.elim0) + (powers : Realize M.sets powerSet Fin.elim0) (separation : SeparationSchema M.sets) + (collection : CollectionSchema M.sets) (infinite : Realize M.sets infinity Fin.elim0) + (choice : Realize M.sets SetFormula.choice Fin.elim0) + (small : M.sets.Countable) + {K : ZFSet.{u}} (hK : K ∈ M.sets) (standard : GroundStandardInaccessible M K) : + ∃ N : TransitiveGround.{u}, M.sets ⊆ N.sets ∧ ZFRealization N.sets ∧ + Realize N.sets partitionPrinciple Fin.elim0 ∧ + ¬ Realize N.sets SetFormula.choice Fin.elim0 := by + sorry + +end PartitionPilot.Forcing.TransitiveGround + +end OAI diff --git a/tasks/partition-principle/tests/grade.py b/tasks/partition-principle/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/partition-principle/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/partition-principle/tests/task.json b/tasks/partition-principle/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9af4f33e032e4a21102c04044472d4ce6cdc4d0f --- /dev/null +++ b/tasks/partition-principle/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PartitionPrinciple", + "comparator": { + "theorem_names": [ + "OAI.PartitionPilot.Forcing.TransitiveGround.exists_model_partitionPrinciple_without_choice" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 21600 +} \ No newline at end of file diff --git a/tasks/partition-principle/tests/test.sh b/tasks/partition-principle/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/partition-principle/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/perceptron-free-energy/environment/Dockerfile b/tasks/perceptron-free-energy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/perceptron-free-energy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/perceptron-free-energy/environment/fetch_mathlib.sh b/tasks/perceptron-free-energy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/perceptron-free-energy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/perceptron-free-energy/environment/lake-manifest.json b/tasks/perceptron-free-energy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/perceptron-free-energy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/perceptron-free-energy/environment/lakefile.lean b/tasks/perceptron-free-energy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/perceptron-free-energy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/perceptron-free-energy/environment/lean_setup.sh b/tasks/perceptron-free-energy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/perceptron-free-energy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/perceptron-free-energy/environment/pack_submission.py b/tasks/perceptron-free-energy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/perceptron-free-energy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/perceptron-free-energy/instruction.md b/tasks/perceptron-free-energy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de5360c48946f601a6a59e61ffcadfce85e8693d --- /dev/null +++ b/tasks/perceptron-free-energy/instruction.md @@ -0,0 +1,162 @@ +# openai/math challenge `PerceptronFreeEnergy` (family 222) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 222 of the release, *Perceptron free energies and microscopic jamming* +(Probability and statistical mechanics). The family as a whole: Determines finite-temperature variational free energies for Gaussian Ising perceptrons with bounded Borel log-potentials and Gaussian spherical perceptrons with bounded continuous potentials, at every positive pattern density. A spherical extension treats bi-orthogonally invariant disorder with compact limiting singular-value distributions and no outliers. At margin $-1$, the quadratic-penalty spherical model has a sharp feasibility threshold and limiting gap and force laws, with system size, zero temperature, and critical density taken in that order. + +The challenge is `PerceptronFreeEnergy`, also at `/opt/openai-math/challenges/PerceptronFreeEnergy.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory ProbabilityTheory Filter Set +open scoped ENNReal NNReal Topology BigOperators BoundedContinuousFunction + +namespace SphericalPerceptronFreeEnergy + +abbrev Time := unitInterval +abbrev BrownianPath := C(ℝ≥0, ℝ) + +instance : MeasurableSpace BrownianPath := borel BrownianPath +instance : BorelSpace BrownianPath := ⟨rfl⟩ + +abbrev Spin (N : ℕ) := EuclideanSpace ℝ (Fin N) + +def patternCount (α : ℝ) (N : ℕ) : ℕ := ⌊α * (N : ℝ)⌋₊ +abbrev Patterns (α : ℝ) (N : ℕ) := Fin (patternCount α N) → Fin N → ℝ + +def patternLaw (α : ℝ) (N : ℕ) : Measure (Patterns α N) := + Measure.pi fun _ => Measure.pi fun _ => gaussianReal 0 1 + +def unitSphereLaw (N : ℕ) : Measure (Metric.sphere (0 : Spin N) 1) := + let s := (volume : Measure (Spin N)).toSphere + (s Set.univ)⁻¹ • s + +def sphereLaw (N : ℕ) : Measure (Spin N) := + (unitSphereLaw N).map fun x => Real.sqrt (N : ℝ) • x.val + +def patternField {α : ℝ} {N : ℕ} (g : Patterns α N) + (a : Fin (patternCount α N)) (x : Spin N) : ℝ := + (∑ i : Fin N, g a i * x i) / Real.sqrt (N : ℝ) + +def hamiltonian (α : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) (g : Patterns α N) + (x : Spin N) : ℝ := + ∑ a : Fin (patternCount α N), φ (patternField g a x) + +def pressure (α β : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) (g : Patterns α N) : ℝ := + Real.log (∫ x, Real.exp (β * hamiltonian α φ N g x) ∂sphereLaw N) / (N : ℝ) + +def expectedPressure (α β : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) : ℝ := + ∫ g, pressure α β φ N g ∂patternLaw α N + +structure Trial where + toFun : Time → ℝ + monotone : Monotone toFun + measurable : Measurable toFun + nonneg : ∀ t, 0 ≤ toFun t + le_one : ∀ t, toFun t ≤ 1 + +instance : CoeFun Trial (fun _ => Time → ℝ) := ⟨Trial.toFun⟩ + +def timeLaw : Measure Time := Measure.comap Subtype.val volume + +def tailIntegral (m : Trial) (t : Time) : ℝ := + ∫ s in Set.Ici t, m s ∂timeLaw + +def entropy (m : Trial) : ℝ≥0∞ := + (∫⁻ t, (ENNReal.ofReal (tailIntegral m t))⁻¹ - + (ENNReal.ofReal (1 - (t : ℝ)))⁻¹ ∂timeLaw) / 2 + +def brownianEval (t : ℝ≥0) (ω : BrownianPath) : ℝ := ω t + +@[instance_reducible] def nullSigma (P : Measure BrownianPath) : MeasurableSpace BrownianPath := + MeasurableSpace.generateFrom {s | P s = 0} + +@[instance_reducible] def usualBrownianSigma (P : Measure BrownianPath) (t : Time) : + MeasurableSpace BrownianPath := + ⨅ s : {s : ℝ≥0 // (t : ℝ) < s}, + (⨆ r : {r : ℝ≥0 // r ≤ s.val}, + MeasurableSpace.comap (brownianEval r.val) (borel ℝ)) ⊔ nullSigma P + +def Progressive (P : Measure BrownianPath) (v : Time → BrownianPath → ℝ) : Prop := + ∀ t : Time, + @Measurable (Set.Iic t × BrownianPath) ℝ + (MeasurableSpace.prod inferInstance (usualBrownianSigma P t)) (borel ℝ) + (fun p => v p.1.val p.2) + +def controlCost (P : Measure BrownianPath) (m : Trial) + (v : Time → BrownianPath → ℝ) : ℝ≥0∞ := + ∫⁻ ω, ∫⁻ t, ENNReal.ofReal (m t * v t ω ^ 2) ∂timeLaw ∂P + +def controlPayoff (P : Measure BrownianPath) (f : ℝ →ᵇ ℝ) (m : Trial) + (v : Time → BrownianPath → ℝ) : ℝ := + (∫ ω, f (brownianEval 1 ω + ∫ t, m t * v t ω ∂timeLaw) ∂P) - + (controlCost P m v).toReal / 2 + +def controlValue (P : Measure BrownianPath) (f : ℝ →ᵇ ℝ) (m : Trial) : ℝ := + sSup {a | ∃ v : Time → BrownianPath → ℝ, + Progressive P v ∧ controlCost P m v < ∞ ∧ a = controlPayoff P f m v} + +def variationalValue (P : Measure BrownianPath) (α β : ℝ) (φ : ℝ →ᵇ ℝ) : EReal := + ⨅ m : Trial, ((α * controlValue P (β • φ) m : ℝ) : EReal) + (entropy m).toEReal + +theorem main (P : Measure BrownianPath) [IsProbabilityMeasure P] + (hB : IsBrownianReal brownianEval P) + (α β : ℝ) (hα : 0 < α) (hβ : 0 < β) (φ : ℝ →ᵇ ℝ) : + ∃ p : ℝ, variationalValue P α β φ = (p : EReal) ∧ + Tendsto (fun N : ℕ => expectedPressure α β φ (N + 1)) atTop (𝓝 p) ∧ + ∀ ε : ℝ, 0 < ε → + Tendsto (fun N : ℕ => patternLaw α (N + 1) + {g | ε < |pressure α β φ (N + 1) g - p|}) atTop (𝓝 0) := by + sorry + +end SphericalPerceptronFreeEnergy + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PerceptronFreeEnergy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SphericalPerceptronFreeEnergy.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/perceptron-free-energy/solution/closure.txt b/tasks/perceptron-free-energy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4fdf10d42de0bb9232ab4cfe7877bed0674fdb15 --- /dev/null +++ b/tasks/perceptron-free-energy/solution/closure.txt @@ -0,0 +1,411 @@ +OAI.Probability.Perceptron.Brownian.CavityGaussianFields +OAI.Probability.Perceptron.Brownian.CountableGaussianField +OAI.Probability.Perceptron.Brownian.GaussianField +OAI.Probability.Perceptron.Brownian.GaussianFieldAlgebra +OAI.Probability.Perceptron.Cascade.BulkRPCCoupling +OAI.Probability.Perceptron.Cascade.CascadeConstant +OAI.Probability.Perceptron.Cascade.CascadeHeat +OAI.Probability.Perceptron.Cascade.CascadeIndependentTilt +OAI.Probability.Perceptron.Cascade.CascadeParameters +OAI.Probability.Perceptron.Cascade.CascadeTransport +OAI.Probability.Perceptron.Cascade.CavityCappedRPC +OAI.Probability.Perceptron.Cascade.CavityFiniteRPC +OAI.Probability.Perceptron.Cascade.CavityRPCControl +OAI.Probability.Perceptron.Cascade.DecoratedWeightedTotal +OAI.Probability.Perceptron.Cascade.DepthWeights +OAI.Probability.Perceptron.Cascade.EnrichedPoissonVariance +OAI.Probability.Perceptron.Cascade.IndexedCascadeRegular +OAI.Probability.Perceptron.Cascade.IndexedMarkedPoisson +OAI.Probability.Perceptron.Cascade.IndexedPoisson +OAI.Probability.Perceptron.Cascade.IndexedReplicaWeights +OAI.Probability.Perceptron.Cascade.IndexedTiltedLeaves +OAI.Probability.Perceptron.Cascade.IndexedTiltedWeights +OAI.Probability.Perceptron.Cascade.IndexedVertices +OAI.Probability.Perceptron.Cascade.PoissonCountMoments +OAI.Probability.Perceptron.Cascade.PoissonDensityDerivative +OAI.Probability.Perceptron.Cascade.PoissonLaplace +OAI.Probability.Perceptron.Cascade.PoissonWeightedTotal +OAI.Probability.Perceptron.Cascade.Poissonization +OAI.Probability.Perceptron.Cascade.ReweightedMomentComparison +OAI.Probability.Perceptron.Cascade.ReweightedMomentLimit +OAI.Probability.Perceptron.Cascade.StableCascade +OAI.Probability.Perceptron.Cascade.StablePoissonTotalLogMemLpTwo +OAI.Probability.Perceptron.Cascade.TwoVisitWeights +OAI.Probability.Perceptron.Cascade.WeightedCDF +OAI.Probability.Perceptron.Cascade.WeightedTotalBiasedLaw +OAI.Probability.Perceptron.Cascade.WeightedTrialLaw +OAI.Probability.Perceptron.Cavity.AmbientBulkFeature +OAI.Probability.Perceptron.Cavity.BulkAnnealedTangent +OAI.Probability.Perceptron.Cavity.BulkCavityData +OAI.Probability.Perceptron.Cavity.BulkCavityRecursion +OAI.Probability.Perceptron.Cavity.BulkCompactGG +OAI.Probability.Perceptron.Cavity.BulkConcentration +OAI.Probability.Perceptron.Cavity.BulkCoupling +OAI.Probability.Perceptron.Cavity.BulkDeviation +OAI.Probability.Perceptron.Cavity.BulkDiagonalLimit +OAI.Probability.Perceptron.Cavity.BulkEmpiricalLimit +OAI.Probability.Perceptron.Cavity.BulkEnergyDeviation +OAI.Probability.Perceptron.Cavity.BulkFreshRestore +OAI.Probability.Perceptron.Cavity.BulkGoodParameters +OAI.Probability.Perceptron.Cavity.BulkLimitGeometry +OAI.Probability.Perceptron.Cavity.BulkMarkedArray +OAI.Probability.Perceptron.Cavity.BulkMarkedMoments +OAI.Probability.Perceptron.Cavity.BulkMarkedPairLimit +OAI.Probability.Perceptron.Cavity.BulkMarkedSelfConsistency +OAI.Probability.Perceptron.Cavity.BulkMarkedTangentLimit +OAI.Probability.Perceptron.Cavity.BulkModel +OAI.Probability.Perceptron.Cavity.BulkPairLaw +OAI.Probability.Perceptron.Cavity.BulkParameterDeviation +OAI.Probability.Perceptron.Cavity.BulkRadialIBP +OAI.Probability.Perceptron.Cavity.BulkRadialIdentity +OAI.Probability.Perceptron.Cavity.BulkRadialLimit +OAI.Probability.Perceptron.Cavity.BulkReplicaDominated +OAI.Probability.Perceptron.Cavity.BulkReplicaStein +OAI.Probability.Perceptron.Cavity.BulkRestorationLimit +OAI.Probability.Perceptron.Cavity.BulkRestoredObservables +OAI.Probability.Perceptron.Cavity.BulkSingleEmpiricalLimit +OAI.Probability.Perceptron.Cavity.BulkSingleLimit +OAI.Probability.Perceptron.Cavity.BulkStein +OAI.Probability.Perceptron.Cavity.BulkTangentError +OAI.Probability.Perceptron.Cavity.BulkThermal +OAI.Probability.Perceptron.Cavity.BulkTimeLaw +OAI.Probability.Perceptron.Cavity.CavityAnnealedUncap +OAI.Probability.Perceptron.Cavity.CavityApproxStationary +OAI.Probability.Perceptron.Cavity.CavityBlockProduct +OAI.Probability.Perceptron.Cavity.CavityBoundedContinuous +OAI.Probability.Perceptron.Cavity.CavityBulkCoefficients +OAI.Probability.Perceptron.Cavity.CavityBulkLog +OAI.Probability.Perceptron.Cavity.CavityBulkUncappedLog +OAI.Probability.Perceptron.Cavity.CavityCompensator +OAI.Probability.Perceptron.Cavity.CavityConditionalIncrement +OAI.Probability.Perceptron.Cavity.CavityCountableIsotropic +OAI.Probability.Perceptron.Cavity.CavityCounts +OAI.Probability.Perceptron.Cavity.CavityCovarianceComparison +OAI.Probability.Perceptron.Cavity.CavityDiagonalKernel +OAI.Probability.Perceptron.Cavity.CavityDisintegration +OAI.Probability.Perceptron.Cavity.CavityExpectedCompensator +OAI.Probability.Perceptron.Cavity.CavityExpectedQDrop +OAI.Probability.Perceptron.Cavity.CavityFiniteEvaluation +OAI.Probability.Perceptron.Cavity.CavityFiniteIncrement +OAI.Probability.Perceptron.Cavity.CavityFreshReplacement +OAI.Probability.Perceptron.Cavity.CavityFullEvaluation +OAI.Probability.Perceptron.Cavity.CavityFullLog +OAI.Probability.Perceptron.Cavity.CavityGaussianQuadratic +OAI.Probability.Perceptron.Cavity.CavityGaussianReplica +OAI.Probability.Perceptron.Cavity.CavityGaussianTransport +OAI.Probability.Perceptron.Cavity.CavityGeometry +OAI.Probability.Perceptron.Cavity.CavityGoodFreshLower +OAI.Probability.Perceptron.Cavity.CavityIncrementLaw +OAI.Probability.Perceptron.Cavity.CavityIndexedLog +OAI.Probability.Perceptron.Cavity.CavityLabelAnnealed +OAI.Probability.Perceptron.Cavity.CavityLabelArray +OAI.Probability.Perceptron.Cavity.CavityLabelLimit +OAI.Probability.Perceptron.Cavity.CavityLabelMoment +OAI.Probability.Perceptron.Cavity.CavityLabelPartition +OAI.Probability.Perceptron.Cavity.CavityMeanCap +OAI.Probability.Perceptron.Cavity.CavityNormalizedIncrement +OAI.Probability.Perceptron.Cavity.CavityOldExpectation +OAI.Probability.Perceptron.Cavity.CavityPerturbationCovariance +OAI.Probability.Perceptron.Cavity.CavityProductLaw +OAI.Probability.Perceptron.Cavity.CavityQuadraticDrop +OAI.Probability.Perceptron.Cavity.CavityResidualFormula +OAI.Probability.Perceptron.Cavity.CavityResidualUncap +OAI.Probability.Perceptron.Cavity.CavityRoundedLower +OAI.Probability.Perceptron.Cavity.CavityShellExpansion +OAI.Probability.Perceptron.Cavity.CavityShellLimit +OAI.Probability.Perceptron.Cavity.CavityShellPerturbation +OAI.Probability.Perceptron.Cavity.CavityShellPolar +OAI.Probability.Perceptron.Cavity.CavityShellRestriction +OAI.Probability.Perceptron.Cavity.CavityShellSubexp +OAI.Probability.Perceptron.Cavity.CavitySmoothLimit +OAI.Probability.Perceptron.Cavity.CavitySphericalGrid +OAI.Probability.Perceptron.Cavity.CavitySphericalMoments +OAI.Probability.Perceptron.Cavity.CavityTaylorFinite +OAI.Probability.Perceptron.Cavity.CavityTelescoping +OAI.Probability.Perceptron.Cavity.CavityTrueShellLower +OAI.Probability.Perceptron.Cavity.CavityTrueShellQ +OAI.Probability.Perceptron.Cavity.CavityUncappedLimit +OAI.Probability.Perceptron.Cavity.CavityUniformRemainder +OAI.Probability.Perceptron.Cavity.ContinuousCavityProfile +OAI.Probability.Perceptron.Cavity.CountableFreshMoment +OAI.Probability.Perceptron.Cavity.FreshDensity +OAI.Probability.Perceptron.Cavity.FreshDiagonalNoise +OAI.Probability.Perceptron.Cavity.FreshGGLogUniqueness +OAI.Probability.Perceptron.Cavity.FreshGGUniqueness +OAI.Probability.Perceptron.Cavity.FreshGeometry +OAI.Probability.Perceptron.Cavity.FreshLogRatio +OAI.Probability.Perceptron.Cavity.FreshMarkedKernel +OAI.Probability.Perceptron.Cavity.FreshMomentLimit +OAI.Probability.Perceptron.Cavity.FreshReference +OAI.Probability.Perceptron.Cavity.FreshReplicaKernel +OAI.Probability.Perceptron.Cavity.FreshThermalLaw +OAI.Probability.Perceptron.Cavity.IndexedFreshTilt +OAI.Probability.Perceptron.Cavity.LabelFreshKernel +OAI.Probability.Perceptron.Cavity.LabelFreshLog +OAI.Probability.Perceptron.Cavity.LeafFreshLog +OAI.Probability.Perceptron.Control.ContactControl +OAI.Probability.Perceptron.Control.ControlDrift +OAI.Probability.Perceptron.Control.ControlledPrefix +OAI.Probability.Perceptron.Control.FreshControl +OAI.Probability.Perceptron.Control.LabelProfileControl +OAI.Probability.Perceptron.Control.QuantileControlContinuity +OAI.Probability.Perceptron.Control.QuantileControlTail +OAI.Probability.Perceptron.Control.StepControl +OAI.Probability.Perceptron.Control.StepControlTail +OAI.Probability.Perceptron.Interpolation.AnnealedMarkedReplica +OAI.Probability.Perceptron.Interpolation.AnnealedReplicaConvergence +OAI.Probability.Perceptron.Interpolation.ArrayGeometry +OAI.Probability.Perceptron.Interpolation.ArrayLawExt +OAI.Probability.Perceptron.Interpolation.ArrayLimitGeometry +OAI.Probability.Perceptron.Interpolation.ArrayTangentConsistency +OAI.Probability.Perceptron.Interpolation.CompactArrayMap +OAI.Probability.Perceptron.Interpolation.CountableGaussianReplicaIBP +OAI.Probability.Perceptron.Interpolation.FieldArray +OAI.Probability.Perceptron.Interpolation.FiniteOverlap +OAI.Probability.Perceptron.Interpolation.FiniteVectorReplica +OAI.Probability.Perceptron.Interpolation.GaussianReplicaFubini +OAI.Probability.Perceptron.Interpolation.GibbsArrayGeometry +OAI.Probability.Perceptron.Interpolation.GibbsOverlapArray +OAI.Probability.Perceptron.Interpolation.GibbsReplicaMean +OAI.Probability.Perceptron.Interpolation.IntegrableReplicaGibbs +OAI.Probability.Perceptron.Interpolation.KernelInfiniteReplica +OAI.Probability.Perceptron.Interpolation.KernelReplicaGibbs +OAI.Probability.Perceptron.Interpolation.NonlinearReplicaIBP +OAI.Probability.Perceptron.Interpolation.OverlapArray +OAI.Probability.Perceptron.Interpolation.OverlapBlock +OAI.Probability.Perceptron.Interpolation.PerturbationComparison +OAI.Probability.Perceptron.Interpolation.PerturbationContact +OAI.Probability.Perceptron.Interpolation.ReplicaIBP +OAI.Probability.Perceptron.Interpolation.ReplicaMeanConst +OAI.Probability.Perceptron.Interpolation.RestorationReplicaBlocks +OAI.Probability.Perceptron.Interpolation.TerminalReplicaRestoration +OAI.Probability.Perceptron.Interpolation.TiltReplicaCoordinate +OAI.Probability.Perceptron.Interpolation.TripleGaussianReplica +OAI.Probability.Perceptron.Interpolation.VectorReplicaDirectionBound +OAI.Probability.Perceptron.Main +OAI.Probability.Perceptron.Model +OAI.Probability.Perceptron.Pressure.CountableTerminalRestoration +OAI.Probability.Perceptron.Pressure.EnrichedConcentration +OAI.Probability.Perceptron.Pressure.EnrichedPatternMean +OAI.Probability.Perceptron.Pressure.EnrichedPatternVariance +OAI.Probability.Perceptron.Pressure.FiniteTerminal +OAI.Probability.Perceptron.Pressure.GaussianHamiltonianCoordinates +OAI.Probability.Perceptron.Pressure.GaussianPressureDerivative +OAI.Probability.Perceptron.Pressure.HeightPartition +OAI.Probability.Perceptron.Pressure.IndexedGibbsPartition +OAI.Probability.Perceptron.Pressure.IndexedTerminalGibbs +OAI.Probability.Perceptron.Pressure.IndexedTerminalProduct +OAI.Probability.Perceptron.Pressure.IndexedTerminalRoots +OAI.Probability.Perceptron.Pressure.KernelEnergyConcentration +OAI.Probability.Perceptron.Pressure.PatternFree +OAI.Probability.Perceptron.Pressure.PatternMatrices +OAI.Probability.Perceptron.Pressure.PressureMonotone +OAI.Probability.Perceptron.Pressure.PressureTransport +OAI.Probability.Perceptron.Pressure.RootPartition +OAI.Probability.Perceptron.Pressure.SphericalPatternDirection +OAI.Probability.Perceptron.Pressure.SphericalPatternRadial +OAI.Probability.Perceptron.Pressure.TerminalRestorationCoefficients +OAI.Probability.Perceptron.Pressure.TerminalRestorationLaw +OAI.Probability.Perceptron.Pressure.TerminalVariational +OAI.Probability.Perceptron.Pressure.VectorPartition +OAI.Probability.Perceptron.Sphere.CoordinateBoxBound +OAI.Probability.Perceptron.Sphere.CoordinateContact +OAI.Probability.Perceptron.Sphere.GaussianAffineCoordinate +OAI.Probability.Perceptron.Sphere.GaussianCoordinateProjection +OAI.Probability.Perceptron.Sphere.GaussianPolar +OAI.Probability.Perceptron.Sphere.GaussianRotation +OAI.Probability.Perceptron.Sphere.SphereBridge +OAI.Probability.Perceptron.Sphere.SphereHeat +OAI.Probability.Perceptron.Sphere.SphereIsometryMap +OAI.Probability.Perceptron.Sphere.SphereKernel +OAI.Probability.Perceptron.Sphere.SphereLimit +OAI.Probability.Perceptron.Sphere.UnitSphereTangent +OAI.Probability.Perceptron.Variational.AmplitudeConvex +OAI.Probability.Perceptron.Variational.AnnealedIBP +OAI.Probability.Perceptron.Variational.AtomicBranches +OAI.Probability.Perceptron.Variational.AtomicPairVisitLaw +OAI.Probability.Perceptron.Variational.BackwardScore +OAI.Probability.Perceptron.Variational.BcfEvalRingHom +OAI.Probability.Perceptron.Variational.BlockFocus +OAI.Probability.Perceptron.Variational.BoundaryEstimate +OAI.Probability.Perceptron.Variational.BoundedC1 +OAI.Probability.Perceptron.Variational.BoundedGibbsDerivative +OAI.Probability.Perceptron.Variational.BoundedLeafRestoration +OAI.Probability.Perceptron.Variational.CappedAContinuity +OAI.Probability.Perceptron.Variational.CompactEnvelope +OAI.Probability.Perceptron.Variational.CompactGGDensity +OAI.Probability.Perceptron.Variational.CompactGGEvents +OAI.Probability.Perceptron.Variational.CompactGGFiniteCode +OAI.Probability.Perceptron.Variational.CompactJointMonomials +OAI.Probability.Perceptron.Variational.CompactRestorationWitness +OAI.Probability.Perceptron.Variational.CompactScalarGG +OAI.Probability.Perceptron.Variational.CompactTripleGG +OAI.Probability.Perceptron.Variational.Contact +OAI.Probability.Perceptron.Variational.ContactDensity +OAI.Probability.Perceptron.Variational.ContactFatou +OAI.Probability.Perceptron.Variational.ContactGGRate +OAI.Probability.Perceptron.Variational.ContactTail +OAI.Probability.Perceptron.Variational.ConvexUniform +OAI.Probability.Perceptron.Variational.CountMixtureVariance +OAI.Probability.Perceptron.Variational.CountableGaussianFullIBP +OAI.Probability.Perceptron.Variational.CountableGaussianIBP +OAI.Probability.Perceptron.Variational.CountableGaussianResampling +OAI.Probability.Perceptron.Variational.CountableMarkedDiagonal +OAI.Probability.Perceptron.Variational.CountableSingleRestoration +OAI.Probability.Perceptron.Variational.CoupledDual +OAI.Probability.Perceptron.Variational.CouplingAffine +OAI.Probability.Perceptron.Variational.CouplingDerivative +OAI.Probability.Perceptron.Variational.CouplingKernel +OAI.Probability.Perceptron.Variational.CovarianceMatrix +OAI.Probability.Perceptron.Variational.DecoratedFocus +OAI.Probability.Perceptron.Variational.DecoratedShapeLaw +OAI.Probability.Perceptron.Variational.DecoratedTiltTotal +OAI.Probability.Perceptron.Variational.DensityDerivative +OAI.Probability.Perceptron.Variational.DensityLipschitz +OAI.Probability.Perceptron.Variational.DepthBlock +OAI.Probability.Perceptron.Variational.DepthGG +OAI.Probability.Perceptron.Variational.DepthLaw +OAI.Probability.Perceptron.Variational.DiagonalDeviation +OAI.Probability.Perceptron.Variational.DilationExpansion +OAI.Probability.Perceptron.Variational.EnergyMean +OAI.Probability.Perceptron.Variational.EnrichedMoments +OAI.Probability.Perceptron.Variational.EnrichedUniformBounds +OAI.Probability.Perceptron.Variational.EnrichedVarianceBound +OAI.Probability.Perceptron.Variational.EntropicHeat +OAI.Probability.Perceptron.Variational.EntropicParameter +OAI.Probability.Perceptron.Variational.Entropy +OAI.Probability.Perceptron.Variational.Field +OAI.Probability.Perceptron.Variational.FieldContinuity +OAI.Probability.Perceptron.Variational.FieldDerivative +OAI.Probability.Perceptron.Variational.FieldRounding +OAI.Probability.Perceptron.Variational.FieldWord +OAI.Probability.Perceptron.Variational.FiniteFieldModel +OAI.Probability.Perceptron.Variational.FiniteGaussianRow +OAI.Probability.Perceptron.Variational.FixedCount +OAI.Probability.Perceptron.Variational.FocusedRootProbability +OAI.Probability.Perceptron.Variational.FocusedSampleLaw +OAI.Probability.Perceptron.Variational.FocusedShapeProbability +OAI.Probability.Perceptron.Variational.FocusedVisit +OAI.Probability.Perceptron.Variational.GaussianAbsoluteEnergyBound +OAI.Probability.Perceptron.Variational.GaussianAverage +OAI.Probability.Perceptron.Variational.GaussianBackward +OAI.Probability.Perceptron.Variational.GaussianBlock +OAI.Probability.Perceptron.Variational.GaussianBoltzmann +OAI.Probability.Perceptron.Variational.GaussianComparison +OAI.Probability.Perceptron.Variational.GaussianCoupling +OAI.Probability.Perceptron.Variational.GaussianCovarianceDerivative +OAI.Probability.Perceptron.Variational.GaussianEnergyMoments +OAI.Probability.Perceptron.Variational.GaussianGibbsContinuity +OAI.Probability.Perceptron.Variational.GaussianGibbsEnergy +OAI.Probability.Perceptron.Variational.GaussianLinearStability +OAI.Probability.Perceptron.Variational.GaussianLinearVariance +OAI.Probability.Perceptron.Variational.GaussianMarkRecursion +OAI.Probability.Perceptron.Variational.GaussianWordStability +OAI.Probability.Perceptron.Variational.GibbsRestoration +OAI.Probability.Perceptron.Variational.GlobalContact +OAI.Probability.Perceptron.Variational.GlobalContactLimit +OAI.Probability.Perceptron.Variational.GridGap +OAI.Probability.Perceptron.Variational.HeatGrid +OAI.Probability.Perceptron.Variational.HeatLogBCF +OAI.Probability.Perceptron.Variational.HeatTilt +OAI.Probability.Perceptron.Variational.HeightWord +OAI.Probability.Perceptron.Variational.IndexedAncestry +OAI.Probability.Perceptron.Variational.IndexedChildLaw +OAI.Probability.Perceptron.Variational.IndexedDiagonalField +OAI.Probability.Perceptron.Variational.IndexedFractionalLog +OAI.Probability.Perceptron.Variational.IndexedGaussianCovariance +OAI.Probability.Perceptron.Variational.IndexedGaussianCovarianceLaw +OAI.Probability.Perceptron.Variational.IndexedGaussianMarks +OAI.Probability.Perceptron.Variational.IndexedLeafTotal +OAI.Probability.Perceptron.Variational.IndexedMarkProduct +OAI.Probability.Perceptron.Variational.IndexedObservableTransport +OAI.Probability.Perceptron.Variational.IndexedPathCorrelation +OAI.Probability.Perceptron.Variational.IndexedTiltedRegular +OAI.Probability.Perceptron.Variational.IndexedTwoShape +OAI.Probability.Perceptron.Variational.IndexedVisit +OAI.Probability.Perceptron.Variational.InfinitePiSplit +OAI.Probability.Perceptron.Variational.IntegrableGibbs +OAI.Probability.Perceptron.Variational.IntegrableProdConditionalSquare +OAI.Probability.Perceptron.Variational.IntegratedConvex +OAI.Probability.Perceptron.Variational.IntegratedThermal +OAI.Probability.Perceptron.Variational.KernelProductIntegral +OAI.Probability.Perceptron.Variational.LabelPairTestValue +OAI.Probability.Perceptron.Variational.LabelProfilePairReference +OAI.Probability.Perceptron.Variational.LabelProfileReference +OAI.Probability.Perceptron.Variational.LabelProfileReferenceFull +OAI.Probability.Perceptron.Variational.LabelProfileSingleReference +OAI.Probability.Perceptron.Variational.LabelReference +OAI.Probability.Perceptron.Variational.LabelReferenceValue +OAI.Probability.Perceptron.Variational.LabelResponse +OAI.Probability.Perceptron.Variational.LabelRestorationKernel +OAI.Probability.Perceptron.Variational.LabelRestorationMoments +OAI.Probability.Perceptron.Variational.LabelRestorationMoments2 +OAI.Probability.Perceptron.Variational.LabelRestorationPair +OAI.Probability.Perceptron.Variational.LabelRestorationSingle +OAI.Probability.Perceptron.Variational.LabelRestoredValue +OAI.Probability.Perceptron.Variational.LabelSingleRestoredValue +OAI.Probability.Perceptron.Variational.LabelThermalLaw +OAI.Probability.Perceptron.Variational.LabelValue +OAI.Probability.Perceptron.Variational.LeafGibbsMarginal +OAI.Probability.Perceptron.Variational.LeafMarginalLaw +OAI.Probability.Perceptron.Variational.LevelTrialApprox +OAI.Probability.Perceptron.Variational.LocalMaxSecondDerivNonpos +OAI.Probability.Perceptron.Variational.MarkTiltKernel +OAI.Probability.Perceptron.Variational.MarkedBlockParameter +OAI.Probability.Perceptron.Variational.MarkedGraphLaw +OAI.Probability.Perceptron.Variational.MarkedTangentCanonical +OAI.Probability.Perceptron.Variational.MarkedTotalBiasedLaw +OAI.Probability.Perceptron.Variational.MarkedVariance +OAI.Probability.Perceptron.Variational.MeasurableVariance +OAI.Probability.Perceptron.Variational.NonlinearDirectionIBP +OAI.Probability.Perceptron.Variational.NormSquareBand +OAI.Probability.Perceptron.Variational.OrderedCode +OAI.Probability.Perceptron.Variational.ParameterResampling +OAI.Probability.Perceptron.Variational.PiMarkLaw +OAI.Probability.Perceptron.Variational.PointedShape +OAI.Probability.Perceptron.Variational.ProbabilityMaps +OAI.Probability.Perceptron.Variational.ProductMarkLaw +OAI.Probability.Perceptron.Variational.PureLabel +OAI.Probability.Perceptron.Variational.QuadraticContactRemainders +OAI.Probability.Perceptron.Variational.QuantileLimit +OAI.Probability.Perceptron.Variational.QuantileReference +OAI.Probability.Perceptron.Variational.QuantileSingleReference +OAI.Probability.Perceptron.Variational.QuantileUpperTail +OAI.Probability.Perceptron.Variational.QuantitativeGG +OAI.Probability.Perceptron.Variational.RestorationMoments +OAI.Probability.Perceptron.Variational.RightDerivativeIntegral +OAI.Probability.Perceptron.Variational.RoundedCoupling +OAI.Probability.Perceptron.Variational.RoundedLaw +OAI.Probability.Perceptron.Variational.RoundedMarkedReference +OAI.Probability.Perceptron.Variational.RoundedMarkedSelection +OAI.Probability.Perceptron.Variational.RoundedPairCoefficients +OAI.Probability.Perceptron.Variational.Shape +OAI.Probability.Perceptron.Variational.ShapeProbability +OAI.Probability.Perceptron.Variational.ShapeSampleLaw +OAI.Probability.Perceptron.Variational.ShellBridge +OAI.Probability.Perceptron.Variational.SingleRestorationLaw +OAI.Probability.Perceptron.Variational.StableLaplaceConstant +OAI.Probability.Perceptron.Variational.StableLogIntensity +OAI.Probability.Perceptron.Variational.StableMassKernel +OAI.Probability.Perceptron.Variational.StableTotalBiasedLaw +OAI.Probability.Perceptron.Variational.StationaryExistence +OAI.Probability.Perceptron.Variational.StepDual +OAI.Probability.Perceptron.Variational.StepEntropy +OAI.Probability.Perceptron.Variational.StepStationary +OAI.Probability.Perceptron.Variational.SynchronizedLimit +OAI.Probability.Perceptron.Variational.TangentConsistency +OAI.Probability.Perceptron.Variational.TensorFeatures +OAI.Probability.Perceptron.Variational.TiltMeanCenteredAbsSq +OAI.Probability.Perceptron.Variational.TiltedPathDiagonal +OAI.Probability.Perceptron.Variational.TiltedPathProduct +OAI.Probability.Perceptron.Variational.TiltedVisitKernel +OAI.Probability.Perceptron.Variational.TiltedVisitKernelLaw +OAI.Probability.Perceptron.Variational.Trial +OAI.Probability.Perceptron.Variational.TripleIndex +OAI.Probability.Perceptron.Variational.TripleRootRegroup +OAI.Probability.Perceptron.Variational.UnboundedContact +OAI.Probability.Perceptron.Variational.UniformGrid +OAI.Probability.Perceptron.Variational.UniformQuantileCells +OAI.Probability.Perceptron.Variational.UniformUncapLimit +OAI.Probability.Perceptron.Variational.UpperContact +OAI.Probability.Perceptron.Variational.VarianceProdMemLp diff --git a/tasks/perceptron-free-energy/solution/reference.py b/tasks/perceptron-free-energy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/perceptron-free-energy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/perceptron-free-energy/solution/solve.sh b/tasks/perceptron-free-energy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6602155f9ea584337df76e4912469bae05ddffe7 --- /dev/null +++ b/tasks/perceptron-free-energy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PerceptronFreeEnergy, i.e. module OAI.Probability.Perceptron.Main and the +# 411 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Perceptron.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PerceptronFreeEnergy" diff --git a/tasks/perceptron-free-energy/task.toml b/tasks/perceptron-free-energy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c8fd0cbb38e3351765c2cce441ab93ba176943a --- /dev/null +++ b/tasks/perceptron-free-energy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/perceptron-free-energy" +version = "1.0.0" +description = "Prove PerceptronFreeEnergy (openai/math family 222: Perceptron free energies and microscopic jamming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PerceptronFreeEnergy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PerceptronFreeEnergy" +family = "222" +family_title = "Perceptron free energies and microscopic jamming" +subject = "Probability and statistical mechanics" +theorems = ["OAI.SphericalPerceptronFreeEnergy.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Perceptron.Main" +reference_modules = 411 +reference_lean_bytes = 3856745 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1268 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15171 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/perceptron-free-energy/tests/Challenge.lean b/tasks/perceptron-free-energy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..408c1b65ee5ce32896101e6892cfae34b0e50596 --- /dev/null +++ b/tasks/perceptron-free-energy/tests/Challenge.lean @@ -0,0 +1,111 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory ProbabilityTheory Filter Set +open scoped ENNReal NNReal Topology BigOperators BoundedContinuousFunction + +namespace SphericalPerceptronFreeEnergy + +abbrev Time := unitInterval +abbrev BrownianPath := C(ℝ≥0, ℝ) + +instance : MeasurableSpace BrownianPath := borel BrownianPath +instance : BorelSpace BrownianPath := ⟨rfl⟩ + +abbrev Spin (N : ℕ) := EuclideanSpace ℝ (Fin N) + +def patternCount (α : ℝ) (N : ℕ) : ℕ := ⌊α * (N : ℝ)⌋₊ +abbrev Patterns (α : ℝ) (N : ℕ) := Fin (patternCount α N) → Fin N → ℝ + +def patternLaw (α : ℝ) (N : ℕ) : Measure (Patterns α N) := + Measure.pi fun _ => Measure.pi fun _ => gaussianReal 0 1 + +def unitSphereLaw (N : ℕ) : Measure (Metric.sphere (0 : Spin N) 1) := + let s := (volume : Measure (Spin N)).toSphere + (s Set.univ)⁻¹ • s + +def sphereLaw (N : ℕ) : Measure (Spin N) := + (unitSphereLaw N).map fun x => Real.sqrt (N : ℝ) • x.val + +def patternField {α : ℝ} {N : ℕ} (g : Patterns α N) + (a : Fin (patternCount α N)) (x : Spin N) : ℝ := + (∑ i : Fin N, g a i * x i) / Real.sqrt (N : ℝ) + +def hamiltonian (α : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) (g : Patterns α N) + (x : Spin N) : ℝ := + ∑ a : Fin (patternCount α N), φ (patternField g a x) + +def pressure (α β : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) (g : Patterns α N) : ℝ := + Real.log (∫ x, Real.exp (β * hamiltonian α φ N g x) ∂sphereLaw N) / (N : ℝ) + +def expectedPressure (α β : ℝ) (φ : ℝ →ᵇ ℝ) (N : ℕ) : ℝ := + ∫ g, pressure α β φ N g ∂patternLaw α N + +structure Trial where + toFun : Time → ℝ + monotone : Monotone toFun + measurable : Measurable toFun + nonneg : ∀ t, 0 ≤ toFun t + le_one : ∀ t, toFun t ≤ 1 + +instance : CoeFun Trial (fun _ => Time → ℝ) := ⟨Trial.toFun⟩ + +def timeLaw : Measure Time := Measure.comap Subtype.val volume + +def tailIntegral (m : Trial) (t : Time) : ℝ := + ∫ s in Set.Ici t, m s ∂timeLaw + +def entropy (m : Trial) : ℝ≥0∞ := + (∫⁻ t, (ENNReal.ofReal (tailIntegral m t))⁻¹ - + (ENNReal.ofReal (1 - (t : ℝ)))⁻¹ ∂timeLaw) / 2 + +def brownianEval (t : ℝ≥0) (ω : BrownianPath) : ℝ := ω t + +@[instance_reducible] def nullSigma (P : Measure BrownianPath) : MeasurableSpace BrownianPath := + MeasurableSpace.generateFrom {s | P s = 0} + +@[instance_reducible] def usualBrownianSigma (P : Measure BrownianPath) (t : Time) : + MeasurableSpace BrownianPath := + ⨅ s : {s : ℝ≥0 // (t : ℝ) < s}, + (⨆ r : {r : ℝ≥0 // r ≤ s.val}, + MeasurableSpace.comap (brownianEval r.val) (borel ℝ)) ⊔ nullSigma P + +def Progressive (P : Measure BrownianPath) (v : Time → BrownianPath → ℝ) : Prop := + ∀ t : Time, + @Measurable (Set.Iic t × BrownianPath) ℝ + (MeasurableSpace.prod inferInstance (usualBrownianSigma P t)) (borel ℝ) + (fun p => v p.1.val p.2) + +def controlCost (P : Measure BrownianPath) (m : Trial) + (v : Time → BrownianPath → ℝ) : ℝ≥0∞ := + ∫⁻ ω, ∫⁻ t, ENNReal.ofReal (m t * v t ω ^ 2) ∂timeLaw ∂P + +def controlPayoff (P : Measure BrownianPath) (f : ℝ →ᵇ ℝ) (m : Trial) + (v : Time → BrownianPath → ℝ) : ℝ := + (∫ ω, f (brownianEval 1 ω + ∫ t, m t * v t ω ∂timeLaw) ∂P) - + (controlCost P m v).toReal / 2 + +def controlValue (P : Measure BrownianPath) (f : ℝ →ᵇ ℝ) (m : Trial) : ℝ := + sSup {a | ∃ v : Time → BrownianPath → ℝ, + Progressive P v ∧ controlCost P m v < ∞ ∧ a = controlPayoff P f m v} + +def variationalValue (P : Measure BrownianPath) (α β : ℝ) (φ : ℝ →ᵇ ℝ) : EReal := + ⨅ m : Trial, ((α * controlValue P (β • φ) m : ℝ) : EReal) + (entropy m).toEReal + +theorem main (P : Measure BrownianPath) [IsProbabilityMeasure P] + (hB : IsBrownianReal brownianEval P) + (α β : ℝ) (hα : 0 < α) (hβ : 0 < β) (φ : ℝ →ᵇ ℝ) : + ∃ p : ℝ, variationalValue P α β φ = (p : EReal) ∧ + Tendsto (fun N : ℕ => expectedPressure α β φ (N + 1)) atTop (𝓝 p) ∧ + ∀ ε : ℝ, 0 < ε → + Tendsto (fun N : ℕ => patternLaw α (N + 1) + {g | ε < |pressure α β φ (N + 1) g - p|}) atTop (𝓝 0) := by + sorry + +end SphericalPerceptronFreeEnergy + +end + +end OAI diff --git a/tasks/perceptron-free-energy/tests/grade.py b/tasks/perceptron-free-energy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/perceptron-free-energy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/perceptron-free-energy/tests/task.json b/tasks/perceptron-free-energy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..83370e6a9f8ea3a335ffc4dea7f0935d70e2f088 --- /dev/null +++ b/tasks/perceptron-free-energy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PerceptronFreeEnergy", + "comparator": { + "theorem_names": [ + "OAI.SphericalPerceptronFreeEnergy.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14271 +} \ No newline at end of file diff --git a/tasks/perceptron-free-energy/tests/test.sh b/tasks/perceptron-free-energy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/perceptron-free-energy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/perfect-completeness/environment/Dockerfile b/tasks/perfect-completeness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/perfect-completeness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/perfect-completeness/environment/fetch_mathlib.sh b/tasks/perfect-completeness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/perfect-completeness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/perfect-completeness/environment/lake-manifest.json b/tasks/perfect-completeness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/perfect-completeness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/perfect-completeness/environment/lakefile.lean b/tasks/perfect-completeness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/perfect-completeness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/perfect-completeness/environment/lean_setup.sh b/tasks/perfect-completeness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/perfect-completeness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/perfect-completeness/environment/pack_submission.py b/tasks/perfect-completeness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/perfect-completeness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/perfect-completeness/instruction.md b/tasks/perfect-completeness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9003a56026eccea05f375b3f4a986614755d7ee0 --- /dev/null +++ b/tasks/perfect-completeness/instruction.md @@ -0,0 +1,236 @@ +# openai/math challenge `PerfectCompleteness` (family 105) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 105 of the release, *The 2-to-1 Games Conjecture with perfect completeness* +(Theoretical computer science). The family as a whole: Proves Khot's 2-to-1 Games Conjecture with perfect completeness: for every fixed rational $\delta\in(0,1)$, it is NP-hard to distinguish satisfiable games from games whose optimum is at most $\delta$, on explicit unweighted instances. The alphabet depends only on $\delta$, and every right-hand label has exactly two preimages under each constraint map. + +The challenge is `PerfectCompleteness`, also at `/opt/openai-math/challenges/PerfectCompleteness.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace UniqueGamesTheorem.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +def encodeWords : List Nat → List Bool + | [] => [] + | n :: ns => encodeWord n ++ encodeWords ns + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +namespace PerfectCompleteness.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end PerfectCompleteness.BinaryFormula + +namespace PerfectCompleteness.BinaryEncoding + +open PerfectCompleteness.BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end PerfectCompleteness.BinaryEncoding + +namespace PerfectCompleteness.BinaryLanguage + +def language (input : List Bool) : Prop := + ∃ formula, BinaryEncoding.decodeFormula input = some formula ∧ formula.Satisfiable + +end PerfectCompleteness.BinaryLanguage + +namespace PerfectCompleteness + +structure ProjectionTable (q : Nat) where + images : Vector (Fin q) (2 * q) + exactlyTwo : ∀ b : Fin q, + ((List.finRange (2 * q)).filter (fun a => decide (images[a] = b))).length = 2 + +structure Edge (leftVertices rightVertices q : Nat) where + left : Fin leftVertices + right : Fin rightVertices + projection : ProjectionTable q + +structure Instance (q : Nat) where + leftVertices : Nat + rightVertices : Nat + edges : List (Edge leftVertices rightVertices q) + nonempty : edges ≠ [] + +abbrev Labeling {q : Nat} (G : Instance q) := + (Fin G.leftVertices → Fin (2 * q)) × (Fin G.rightVertices → Fin q) + +def Edge.satisfied {l r q : Nat} (e : Edge l r q) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : Bool := + decide (e.projection.images[a e.left] = b e.right) + +def countSatisfied {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) : List (Edge l r q) → Nat + | [] => 0 + | e :: es => (if e.satisfied a b then 1 else 0) + countSatisfied a b es + +end PerfectCompleteness + +namespace PerfectCompleteness.Instance + +def maxSatisfied {q : Nat} (G : Instance q) : Nat := + Finset.univ.sup (fun s : Labeling G => countSatisfied s.1 s.2 G.edges) + +noncomputable def value {q : Nat} (G : Instance q) : ℝ := + (G.maxSatisfied : ℝ) / G.edges.length + +end PerfectCompleteness.Instance + +namespace PerfectCompleteness.Encoding + +open UniqueGamesTheorem.Foundations.Complexity + +def tableWords {q : Nat} (table : ProjectionTable q) : List Nat := + table.images.toList.map Fin.val + +def edgeWords {l r q : Nat} (edge : Edge l r q) : List Nat := + [edge.left.val, edge.right.val] ++ tableWords edge.projection + +def gameWords {q : Nat} (game : Instance q) : List Nat := + [game.leftVertices, game.rightVertices, q, game.edges.length] ++ + game.edges.flatMap edgeWords + +def gameBits {q : Nat} (game : Instance q) : List Bool := + encodeWords (gameWords game) + +end PerfectCompleteness.Encoding + +namespace PerfectCompleteness + +open Turing UniqueGamesTheorem.Foundations.Complexity + +structure BinaryGapReduction (δ : ℚ) where + alphabet : Nat + alphabet_ge_two : 2 ≤ alphabet + construct : List Bool → Instance alphabet + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + Encoding.gameBits construct + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + completeness : ∀ input, BinaryLanguage.language input → (construct input).value = 1 + soundness : ∀ input, ¬BinaryLanguage.language input → (construct input).value ≤ (δ : ℝ) + +end PerfectCompleteness + +namespace PerfectCompleteness.Theorem11 + +theorem exists_reduction (δ : ℚ) (positive : 0 < δ) (less_than_one : δ < 1) : + Nonempty (PerfectCompleteness.BinaryGapReduction δ) := by + sorry + +end PerfectCompleteness.Theorem11 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PerfectCompleteness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PerfectCompleteness.Theorem11.exists_reduction` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/perfect-completeness/solution/closure.txt b/tasks/perfect-completeness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b04deda17331c5854a8f28ae0c916487d50243e --- /dev/null +++ b/tasks/perfect-completeness/solution/closure.txt @@ -0,0 +1,863 @@ +OAI.Computability.PerfectCompleteness.Algebra.AffineDecoderMeeting +OAI.Computability.PerfectCompleteness.Algebra.AffineFunctionalDependence +OAI.Computability.PerfectCompleteness.Algebra.AffineLinearHeavyWitness +OAI.Computability.PerfectCompleteness.Algebra.BilinearGramCompressionLemmas +OAI.Computability.PerfectCompleteness.Algebra.BilinearWitnessLemmas +OAI.Computability.PerfectCompleteness.Algebra.BucketMatrixResampling +OAI.Computability.PerfectCompleteness.Algebra.CanonicalMatrixTable +OAI.Computability.PerfectCompleteness.Algebra.ChildBilinearCollisionTransfer +OAI.Computability.PerfectCompleteness.Algebra.DecoderRankSplit +OAI.Computability.PerfectCompleteness.Algebra.EvaluationMatrix +OAI.Computability.PerfectCompleteness.Algebra.FixedRankContradiction +OAI.Computability.PerfectCompleteness.Algebra.FunctionSpaceLowerRank +OAI.Computability.PerfectCompleteness.Algebra.HierarchicalMatrixTable +OAI.Computability.PerfectCompleteness.Algebra.LowerAffineSliceRank +OAI.Computability.PerfectCompleteness.Algebra.LowerCrossRank +OAI.Computability.PerfectCompleteness.Algebra.LowerCutNodeMatrix +OAI.Computability.PerfectCompleteness.Algebra.MatrixErasure +OAI.Computability.PerfectCompleteness.Algebra.MatrixInverse +OAI.Computability.PerfectCompleteness.Algebra.MatrixInverseConstantsLemmas +OAI.Computability.PerfectCompleteness.Algebra.MatrixRowQuotientLaw +OAI.Computability.PerfectCompleteness.Algebra.MatrixTriangularFoldingLemmas +OAI.Computability.PerfectCompleteness.Algebra.OutputCharacters +OAI.Computability.PerfectCompleteness.Algebra.PrefixMatrixAcceptance +OAI.Computability.PerfectCompleteness.Algebra.PreliminaryMatrixAcceptance +OAI.Computability.PerfectCompleteness.Algebra.ProductEvaluationRank +OAI.Computability.PerfectCompleteness.Algebra.RightDecoderAffineSuccess +OAI.Computability.PerfectCompleteness.Algebra.TensorAffineHeavyWitness +OAI.Computability.PerfectCompleteness.Algebra.TensorBucketEvaluationLemmas +OAI.Computability.PerfectCompleteness.Algebra.TensorRowAdviceLemmas +OAI.Computability.PerfectCompleteness.Algebra.TensorSliceDimension +OAI.Computability.PerfectCompleteness.Algebra.UniformLinearImage +OAI.Computability.PerfectCompleteness.Construction.AscendingBranchingLemmas +OAI.Computability.PerfectCompleteness.Construction.BucketFullAgreement +OAI.Computability.PerfectCompleteness.Construction.BucketQuotientAgreement +OAI.Computability.PerfectCompleteness.Construction.CanonicalLocalCompletion +OAI.Computability.PerfectCompleteness.Construction.ChildCallNumbering +OAI.Computability.PerfectCompleteness.Construction.ChildUnmarkedSpace +OAI.Computability.PerfectCompleteness.Construction.CutBucketTransportLemmas +OAI.Computability.PerfectCompleteness.Construction.CutChildGrouping +OAI.Computability.PerfectCompleteness.Construction.CutNodeRows +OAI.Computability.PerfectCompleteness.Construction.DescendantSpacesLemmas +OAI.Computability.PerfectCompleteness.Construction.FactoredFunctionsLemmas +OAI.Computability.PerfectCompleteness.Construction.FlexibleLocalCompletionLemmas +OAI.Computability.PerfectCompleteness.Construction.HiddenBucketBias +OAI.Computability.PerfectCompleteness.Construction.HiddenChildMixture +OAI.Computability.PerfectCompleteness.Construction.HierarchicalAdviceFromBuckets +OAI.Computability.PerfectCompleteness.Construction.HierarchicalBucketFamily +OAI.Computability.PerfectCompleteness.Construction.LocalCompletionFamily +OAI.Computability.PerfectCompleteness.Construction.LocalCompletionOutput +OAI.Computability.PerfectCompleteness.Construction.LocalCompletionSerializedOutput +OAI.Computability.PerfectCompleteness.Construction.LocalReconstruction +OAI.Computability.PerfectCompleteness.Construction.MixedSourceLocalOddLists +OAI.Computability.PerfectCompleteness.Construction.NativeLeafAlphabet +OAI.Computability.PerfectCompleteness.Construction.NodeEmbedding +OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlockProducts +OAI.Computability.PerfectCompleteness.Construction.OriginalChildBlocks +OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalarAssemblyLemmas +OAI.Computability.PerfectCompleteness.Construction.OriginalChildScalars +OAI.Computability.PerfectCompleteness.Construction.OriginalCutBucketReplacement +OAI.Computability.PerfectCompleteness.Construction.OriginalHiddenChild +OAI.Computability.PerfectCompleteness.Construction.OriginalOwnBucketSplit +OAI.Computability.PerfectCompleteness.Construction.OwnBucketBias +OAI.Computability.PerfectCompleteness.Construction.ProjectedNodeEmbedding +OAI.Computability.PerfectCompleteness.Construction.RelativeDescendantProductsLemmas +OAI.Computability.PerfectCompleteness.Construction.SourceChildKernelLemmas +OAI.Computability.PerfectCompleteness.Construction.SourceLocalOddLists +OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalChildExpectation +OAI.Computability.PerfectCompleteness.Construction.SourcePhysicalTaggedChildren +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionCutSplit +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionKernelJoint +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionOrderLemmas +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPairPullback +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPhysicalHigh +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionPositionSplit +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionRawSwap +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionReconstruction +OAI.Computability.PerfectCompleteness.Construction.SourceQuestionUnmarkedRange +OAI.Computability.PerfectCompleteness.Construction.StoppedBucketRows +OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBucketIndex +OAI.Computability.PerfectCompleteness.Construction.StoppedProjectedBuckets +OAI.Computability.PerfectCompleteness.Construction.TreeCanonical +OAI.Computability.PerfectCompleteness.Construction.TreeSourceSpaces +OAI.Computability.PerfectCompleteness.Construction.WholeCutLocalityLemmas +OAI.Computability.PerfectCompleteness.Decoding.BucketUsefulCollision +OAI.Computability.PerfectCompleteness.Decoding.CanonicalBucketCollision +OAI.Computability.PerfectCompleteness.Decoding.CanonicalUpperDirectionSplit +OAI.Computability.PerfectCompleteness.Decoding.ChildAssemblyProjection +OAI.Computability.PerfectCompleteness.Decoding.ChildBlockProjection +OAI.Computability.PerfectCompleteness.Decoding.ChildFiniteCallCollisionTransfer +OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderOddLists +OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderRateLemmas +OAI.Computability.PerfectCompleteness.Decoding.CleanDecoderSeedLawLemmas +OAI.Computability.PerfectCompleteness.Decoding.CleanEndpointProjection +OAI.Computability.PerfectCompleteness.Decoding.CleanLeftDecoderLemmas +OAI.Computability.PerfectCompleteness.Decoding.CleanPhysicalDecoderLaw +OAI.Computability.PerfectCompleteness.Decoding.CleanRecordProjection +OAI.Computability.PerfectCompleteness.Decoding.CollisionAveragingLemmas +OAI.Computability.PerfectCompleteness.Decoding.CutGroupedProjectionLemmas +OAI.Computability.PerfectCompleteness.Decoding.CutProjectionAssembly +OAI.Computability.PerfectCompleteness.Decoding.CutProjectionGeometry +OAI.Computability.PerfectCompleteness.Decoding.DecoderContraction +OAI.Computability.PerfectCompleteness.Decoding.DecoderFamilyLawLemmas +OAI.Computability.PerfectCompleteness.Decoding.DecoderSourcePullback +OAI.Computability.PerfectCompleteness.Decoding.DecoderTableCoupling +OAI.Computability.PerfectCompleteness.Decoding.DependentDecoderSampling +OAI.Computability.PerfectCompleteness.Decoding.FixedDecoderCleanRateLemmas +OAI.Computability.PerfectCompleteness.Decoding.FixedLowerUniformCollision +OAI.Computability.PerfectCompleteness.Decoding.FixedProjectionErrorLemmas +OAI.Computability.PerfectCompleteness.Decoding.FixedSourceChildCollision +OAI.Computability.PerfectCompleteness.Decoding.FixedSourceLowerCollision +OAI.Computability.PerfectCompleteness.Decoding.FixedSourceProjectionComparison +OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderContext +OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedDecoderLaw +OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedNativeProjection +OAI.Computability.PerfectCompleteness.Decoding.FixedStoppedUpperProbability +OAI.Computability.PerfectCompleteness.Decoding.FixedUpperPairErrorLemmas +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalAllDecoderTables +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderMeetingLemmas +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalDecoderTables +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLeftDecoder +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalLowerInverseLemmas +OAI.Computability.PerfectCompleteness.Decoding.HierarchicalUsefulCollision +OAI.Computability.PerfectCompleteness.Decoding.LeftDecoder +OAI.Computability.PerfectCompleteness.Decoding.LeftDecoderKnownRows +OAI.Computability.PerfectCompleteness.Decoding.LowerCutBucketLocality +OAI.Computability.PerfectCompleteness.Decoding.LowerCutFiberDisintegrationLemmas +OAI.Computability.PerfectCompleteness.Decoding.LowerCutFormCollision +OAI.Computability.PerfectCompleteness.Decoding.LowerCutNodeCoordinates +OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairBackground +OAI.Computability.PerfectCompleteness.Decoding.LowerCutPairLemmas +OAI.Computability.PerfectCompleteness.Decoding.LowerCutRowsLemmas +OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalar +OAI.Computability.PerfectCompleteness.Decoding.LowerCutScalarProjectionLemmas +OAI.Computability.PerfectCompleteness.Decoding.LowerCutUniformCoordinatesLemmas +OAI.Computability.PerfectCompleteness.Decoding.LowerDirectionFiber +OAI.Computability.PerfectCompleteness.Decoding.LowerProjectedFiberAverage +OAI.Computability.PerfectCompleteness.Decoding.LowerProjectedOriginalSuccessLemmas +OAI.Computability.PerfectCompleteness.Decoding.OriginalCutCollision +OAI.Computability.PerfectCompleteness.Decoding.OriginalWholeCutProjection +OAI.Computability.PerfectCompleteness.Decoding.ProjectedFiberUpperSeed +OAI.Computability.PerfectCompleteness.Decoding.ProjectedLowerFiber +OAI.Computability.PerfectCompleteness.Decoding.ProjectedNativeCollision +OAI.Computability.PerfectCompleteness.Decoding.ProjectedRawDecoderLaw +OAI.Computability.PerfectCompleteness.Decoding.ProjectedUpperPair +OAI.Computability.PerfectCompleteness.Decoding.Projection +OAI.Computability.PerfectCompleteness.Decoding.RepresentativeBucketCollisionLemmas +OAI.Computability.PerfectCompleteness.Decoding.RightDecoderLemmas +OAI.Computability.PerfectCompleteness.Decoding.RightDecoderWitness +OAI.Computability.PerfectCompleteness.Decoding.SelectedArrayProjection +OAI.Computability.PerfectCompleteness.Decoding.SourceChildProjectionComparison +OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionCollisionTransportLemmas +OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionPhysicalCollision +OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionProjectionWitness +OAI.Computability.PerfectCompleteness.Decoding.SourceQuestionTaggedProjection +OAI.Computability.PerfectCompleteness.Decoding.TwoResponseCollisionLemmas +OAI.Computability.PerfectCompleteness.Decoding.UpperCutOldRecord +OAI.Computability.PerfectCompleteness.Decoding.UpperCutTriangle +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutCalls +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutComparison +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutErasure +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutLaw +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutProjection +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReconstructionLemmas +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarCutReference +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarFreshProjectionLemmas +OAI.Computability.PerfectCompleteness.Decoding.UpperScalarPairAveraging +OAI.Computability.PerfectCompleteness.Decoding.WholeCutGroupedProjection +OAI.Computability.PerfectCompleteness.Foundations.CanonicalCoarseningErasure +OAI.Computability.PerfectCompleteness.Foundations.CanonicalDictionaryNames +OAI.Computability.PerfectCompleteness.Foundations.CanonicalDirections +OAI.Computability.PerfectCompleteness.Foundations.CanonicalEdgesLemmas +OAI.Computability.PerfectCompleteness.Foundations.CanonicalKeys +OAI.Computability.PerfectCompleteness.Foundations.CanonicalPartialTable +OAI.Computability.PerfectCompleteness.Foundations.CanonicalVertexNames +OAI.Computability.PerfectCompleteness.Foundations.ClauseSupportLemmas +OAI.Computability.PerfectCompleteness.Foundations.CommonAccuracy +OAI.Computability.PerfectCompleteness.Foundations.CoordinateReplacementLemmas +OAI.Computability.PerfectCompleteness.Foundations.CutCallExtension +OAI.Computability.PerfectCompleteness.Foundations.CutContinuationAveraging +OAI.Computability.PerfectCompleteness.Foundations.CutNativeForms +OAI.Computability.PerfectCompleteness.Foundations.CutSlotAssembly +OAI.Computability.PerfectCompleteness.Foundations.CutSlotOutside +OAI.Computability.PerfectCompleteness.Foundations.CutTerminalSplit +OAI.Computability.PerfectCompleteness.Foundations.CutTerminalZero +OAI.Computability.PerfectCompleteness.Foundations.DependentPredictionDifferenceLemmas +OAI.Computability.PerfectCompleteness.Foundations.DescriptorKeyTemplate +OAI.Computability.PerfectCompleteness.Foundations.DesignatedLeavesLemmas +OAI.Computability.PerfectCompleteness.Foundations.DualQuotientRowsLemmas +OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationLemmas +OAI.Computability.PerfectCompleteness.Foundations.DummyEliminationWeighted +OAI.Computability.PerfectCompleteness.Foundations.ExactConditionalOutput +OAI.Computability.PerfectCompleteness.Foundations.ExtraCutCall +OAI.Computability.PerfectCompleteness.Foundations.FiniteProduct +OAI.Computability.PerfectCompleteness.Foundations.FiniteRangeInverse +OAI.Computability.PerfectCompleteness.Foundations.GeometricPathLemmas +OAI.Computability.PerfectCompleteness.Foundations.GeometricPrefixSplit +OAI.Computability.PerfectCompleteness.Foundations.GlobalityLemmas +OAI.Computability.PerfectCompleteness.Foundations.GoodAdviceEventsLemmas +OAI.Computability.PerfectCompleteness.Foundations.HeterogeneousAdviceFamily +OAI.Computability.PerfectCompleteness.Foundations.HeterogeneousPairAdvice +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAdviceExperimentLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalAgreementMean +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalArrays +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalFrozenTablesLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPairCoarse +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalPrediction +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedExperimentLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedPredictionLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedRawAverage +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedRawMeeting +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalProjectedSliceLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalRawAverage +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalRawPredictionLemmas +OAI.Computability.PerfectCompleteness.Foundations.HierarchicalUsefulBackground +OAI.Computability.PerfectCompleteness.Foundations.KeyFiniteness +OAI.Computability.PerfectCompleteness.Foundations.LegalOutputLemmas +OAI.Computability.PerfectCompleteness.Foundations.LegalRationalOutputLemmas +OAI.Computability.PerfectCompleteness.Foundations.LinearEvaluationLemmas +OAI.Computability.PerfectCompleteness.Foundations.ManyGoodRowsLemmas +OAI.Computability.PerfectCompleteness.Foundations.MultiplicationFormInjectiveLemmas +OAI.Computability.PerfectCompleteness.Foundations.NormalizationLemmas +OAI.Computability.PerfectCompleteness.Foundations.OccurrenceStochasticLemmas +OAI.Computability.PerfectCompleteness.Foundations.OddListAlphabetTransport +OAI.Computability.PerfectCompleteness.Foundations.OddListExtraction +OAI.Computability.PerfectCompleteness.Foundations.OddLists +OAI.Computability.PerfectCompleteness.Foundations.OriginalBelowCut +OAI.Computability.PerfectCompleteness.Foundations.OriginalExtraCutComparison +OAI.Computability.PerfectCompleteness.Foundations.OriginalHiddenConditional +OAI.Computability.PerfectCompleteness.Foundations.OriginalPrefixContinuation +OAI.Computability.PerfectCompleteness.Foundations.OriginalTerminalSplitLemmas +OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCut +OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutBridge +OAI.Computability.PerfectCompleteness.Foundations.OriginalWholeCutComparison +OAI.Computability.PerfectCompleteness.Foundations.OutputAnnihilator +OAI.Computability.PerfectCompleteness.Foundations.PCPSource +OAI.Computability.PerfectCompleteness.Foundations.PCPSourceHardness +OAI.Computability.PerfectCompleteness.Foundations.PartialTableInverse +OAI.Computability.PerfectCompleteness.Foundations.PartitionsLemmas +OAI.Computability.PerfectCompleteness.Foundations.PrefixTests +OAI.Computability.PerfectCompleteness.Foundations.ProjectedCallRestriction +OAI.Computability.PerfectCompleteness.Foundations.ProjectedCardinality +OAI.Computability.PerfectCompleteness.Foundations.ProjectedCutChoices +OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberBackground +OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberRawPair +OAI.Computability.PerfectCompleteness.Foundations.ProjectedFiberSquare +OAI.Computability.PerfectCompleteness.Foundations.ProjectedMeetingTransport +OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixComparison +OAI.Computability.PerfectCompleteness.Foundations.ProjectedPrefixConditional +OAI.Computability.PerfectCompleteness.Foundations.ProjectedWholeCut +OAI.Computability.PerfectCompleteness.Foundations.QuarterBalanceLemmas +OAI.Computability.PerfectCompleteness.Foundations.QuotientTableAgreementLemmas +OAI.Computability.PerfectCompleteness.Foundations.RawOccurrenceOrderLemmas +OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaceEquivLemmas +OAI.Computability.PerfectCompleteness.Foundations.RecursiveSpaces +OAI.Computability.PerfectCompleteness.Foundations.ReducedDomains +OAI.Computability.PerfectCompleteness.Foundations.RetainedKeyTransport +OAI.Computability.PerfectCompleteness.Foundations.SignedCostEnvelope +OAI.Computability.PerfectCompleteness.Foundations.SignedScheduleIndex +OAI.Computability.PerfectCompleteness.Foundations.SignedTupleLayout +OAI.Computability.PerfectCompleteness.Foundations.SignedTupleSemantics +OAI.Computability.PerfectCompleteness.Foundations.SlotProjectedExperiment +OAI.Computability.PerfectCompleteness.Foundations.SourceClause +OAI.Computability.PerfectCompleteness.Foundations.SourceKeyBoundsLemmas +OAI.Computability.PerfectCompleteness.Foundations.SourceOddListsLemmas +OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalCallExtension +OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalExteriorReplay +OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalExteriorSwap +OAI.Computability.PerfectCompleteness.Foundations.SourcePhysicalSourceSwapLemmas +OAI.Computability.PerfectCompleteness.Foundations.SourcePrefixComparison +OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedChoices +OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedTag +OAI.Computability.PerfectCompleteness.Foundations.SourceProjectedWholeChoices +OAI.Computability.PerfectCompleteness.Foundations.SourceStrategy +OAI.Computability.PerfectCompleteness.Foundations.SourceTupleData +OAI.Computability.PerfectCompleteness.Foundations.SourceTuplePlacement +OAI.Computability.PerfectCompleteness.Foundations.SourceTupleResetPlacementLemmas +OAI.Computability.PerfectCompleteness.Foundations.SourceVisitOrder +OAI.Computability.PerfectCompleteness.Foundations.StoppedPathHead +OAI.Computability.PerfectCompleteness.Foundations.StoppedPhysicalPrefixSwap +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedArrays +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedCoarseLemmas +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedContext +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedExperiment +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedOldRecord +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedPhysicalAdvice +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedUsefulAverage +OAI.Computability.PerfectCompleteness.Foundations.StoppedProjectedUsefulEvent +OAI.Computability.PerfectCompleteness.Foundations.StoppedSharedComparison +OAI.Computability.PerfectCompleteness.Foundations.StoppedSharedEvents +OAI.Computability.PerfectCompleteness.Foundations.TerminalCalls +OAI.Computability.PerfectCompleteness.Foundations.TriangularFolding +OAI.Computability.PerfectCompleteness.Foundations.TupleIndexEmitterLemmas +OAI.Computability.PerfectCompleteness.Foundations.WholeArrayComposition +OAI.Computability.PerfectCompleteness.Foundations.WholeArrayInteriorExteriorLemmas +OAI.Computability.PerfectCompleteness.Foundations.WholeArrayPositiveSplit +OAI.Computability.PerfectCompleteness.Foundations.WholeArrayRawAssembly +OAI.Computability.PerfectCompleteness.Foundations.WholeArraySubtreeSplit +OAI.Computability.PerfectCompleteness.Foundations.WholeCutCallsLemmas +OAI.Computability.PerfectCompleteness.Foundations.WholeCutExteriorTransportLemmas +OAI.Computability.PerfectCompleteness.Foundations.WholeCutGrouping +OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayGroupingTransport +OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayKeys +OAI.Computability.PerfectCompleteness.Foundations.WholeCutReplayLemmas +OAI.Computability.PerfectCompleteness.Foundations.WholeReplaySubtreeLemmas +OAI.Computability.PerfectCompleteness.Machines.AcceptanceMachine +OAI.Computability.PerfectCompleteness.Machines.AcceptanceStage +OAI.Computability.PerfectCompleteness.Machines.BinaryDualCoordinates +OAI.Computability.PerfectCompleteness.Machines.BinaryFormulaLemmas +OAI.Computability.PerfectCompleteness.Machines.BinaryGapReduction +OAI.Computability.PerfectCompleteness.Machines.BinaryHeaderMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryInputReduction +OAI.Computability.PerfectCompleteness.Machines.BinaryLiteralMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryNameCompare +OAI.Computability.PerfectCompleteness.Machines.BinaryNameMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryNameSearch +OAI.Computability.PerfectCompleteness.Machines.BinaryOccurrenceRename +OAI.Computability.PerfectCompleteness.Machines.BinaryPairMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryParsingLemmas +OAI.Computability.PerfectCompleteness.Machines.BinaryRankOneCount +OAI.Computability.PerfectCompleteness.Machines.BinaryRenameLoop +OAI.Computability.PerfectCompleteness.Machines.BinaryRenameMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryRenameWords +OAI.Computability.PerfectCompleteness.Machines.BinaryTokenMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryTotalInputMachine +OAI.Computability.PerfectCompleteness.Machines.BinaryValidatorMachine +OAI.Computability.PerfectCompleteness.Machines.BoundedExecution +OAI.Computability.PerfectCompleteness.Machines.CanonicalCoarseningEncoding +OAI.Computability.PerfectCompleteness.Machines.CanonicalDictionaryAppendMachine +OAI.Computability.PerfectCompleteness.Machines.CanonicalDictionaryMachine +OAI.Computability.PerfectCompleteness.Machines.CanonicalEndpointMachine +OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyMachine +OAI.Computability.PerfectCompleteness.Machines.CanonicalKeyShapeMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.CanonicalLabelEncoding +OAI.Computability.PerfectCompleteness.Machines.CellsMachine +OAI.Computability.PerfectCompleteness.Machines.CellsTokensAlignmentLemmas +OAI.Computability.PerfectCompleteness.Machines.CircuitBatchLemmas +OAI.Computability.PerfectCompleteness.Machines.CircuitEmission +OAI.Computability.PerfectCompleteness.Machines.CircuitEncodingLemmas +OAI.Computability.PerfectCompleteness.Machines.CircuitFinish +OAI.Computability.PerfectCompleteness.Machines.CircuitLemmas +OAI.Computability.PerfectCompleteness.Machines.CircuitProducerStagesLemmas +OAI.Computability.PerfectCompleteness.Machines.ClashMachine +OAI.Computability.PerfectCompleteness.Machines.ClashMachineFull +OAI.Computability.PerfectCompleteness.Machines.CleanRecordDecoderInput +OAI.Computability.PerfectCompleteness.Machines.ClockPreparation +OAI.Computability.PerfectCompleteness.Machines.CompletedEdgeMachine +OAI.Computability.PerfectCompleteness.Machines.Completeness +OAI.Computability.PerfectCompleteness.Machines.DescriptorKeyMachine +OAI.Computability.PerfectCompleteness.Machines.DescriptorProjectionMachine +OAI.Computability.PerfectCompleteness.Machines.DomainEncoding +OAI.Computability.PerfectCompleteness.Machines.EncodingLemmas +OAI.Computability.PerfectCompleteness.Machines.ExactTargetOdometer +OAI.Computability.PerfectCompleteness.Machines.ExactTargetOnlineEncoding +OAI.Computability.PerfectCompleteness.Machines.FiniteBlockMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.FiniteConstraintMachine +OAI.Computability.PerfectCompleteness.Machines.FixedBinaryGapReduction +OAI.Computability.PerfectCompleteness.Machines.FixedStoppedNativeTape +OAI.Computability.PerfectCompleteness.Machines.FixedUnaryRepresentationMachine +OAI.Computability.PerfectCompleteness.Machines.ForestStage +OAI.Computability.PerfectCompleteness.Machines.HierarchicalLowerMatrixInput +OAI.Computability.PerfectCompleteness.Machines.InitializationControl +OAI.Computability.PerfectCompleteness.Machines.InitializationMachine +OAI.Computability.PerfectCompleteness.Machines.InitializationMachineAt +OAI.Computability.PerfectCompleteness.Machines.InitializationStageLemmas +OAI.Computability.PerfectCompleteness.Machines.InitializationTemplateLemmas +OAI.Computability.PerfectCompleteness.Machines.InputCellsMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.InputFrame +OAI.Computability.PerfectCompleteness.Machines.KeyMetadataMachine +OAI.Computability.PerfectCompleteness.Machines.LocalCompletionMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.LowerCutDecoderInput +OAI.Computability.PerfectCompleteness.Machines.LowerCutInstalledInput +OAI.Computability.PerfectCompleteness.Machines.LowerCutOwnInput +OAI.Computability.PerfectCompleteness.Machines.MachineCircuit +OAI.Computability.PerfectCompleteness.Machines.MetadataFreeTapeLemmas +OAI.Computability.PerfectCompleteness.Machines.NormalizationEmitMachine +OAI.Computability.PerfectCompleteness.Machines.NormalizationLoopMachine +OAI.Computability.PerfectCompleteness.Machines.NormalizationMachine +OAI.Computability.PerfectCompleteness.Machines.NormalizationReadMachine +OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetMachine +OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetProducer +OAI.Computability.PerfectCompleteness.Machines.NormalizedTargetTapeBound +OAI.Computability.PerfectCompleteness.Machines.OrClosure +OAI.Computability.PerfectCompleteness.Machines.OriginalWholeCutTape +OAI.Computability.PerfectCompleteness.Machines.OutputOrder +OAI.Computability.PerfectCompleteness.Machines.OwnInputAffineSliceLemmas +OAI.Computability.PerfectCompleteness.Machines.OwnInputHeavyBounds +OAI.Computability.PerfectCompleteness.Machines.OwnInputReferenceLemmas +OAI.Computability.PerfectCompleteness.Machines.PaddingCellsMachine +OAI.Computability.PerfectCompleteness.Machines.PayloadCellsAlignment +OAI.Computability.PerfectCompleteness.Machines.PayloadCellsMachine +OAI.Computability.PerfectCompleteness.Machines.PayloadPresenceMachine +OAI.Computability.PerfectCompleteness.Machines.PayloadRowsLoop +OAI.Computability.PerfectCompleteness.Machines.PositionLemmas +OAI.Computability.PerfectCompleteness.Machines.PostfixAlignment +OAI.Computability.PerfectCompleteness.Machines.PostfixBounds +OAI.Computability.PerfectCompleteness.Machines.PostfixMachine +OAI.Computability.PerfectCompleteness.Machines.PreprocessingMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.ProducerArenaLemmas +OAI.Computability.PerfectCompleteness.Machines.ProducerBootstrapLemmas +OAI.Computability.PerfectCompleteness.Machines.ProducerInvariant +OAI.Computability.PerfectCompleteness.Machines.ProducerTimeLemmas +OAI.Computability.PerfectCompleteness.Machines.ScalarTapeCardinality +OAI.Computability.PerfectCompleteness.Machines.SignedDescriptorStageMachine +OAI.Computability.PerfectCompleteness.Machines.SignedRuntimeBounds +OAI.Computability.PerfectCompleteness.Machines.SignedTupleBodyMachine +OAI.Computability.PerfectCompleteness.Machines.SignedTupleCleanupMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.SourceClauseCountMachine +OAI.Computability.PerfectCompleteness.Machines.SourceClauseLookupMachine +OAI.Computability.PerfectCompleteness.Machines.SourceClauseReaderMachineLemmas +OAI.Computability.PerfectCompleteness.Machines.SourceClauseSelectMachine +OAI.Computability.PerfectCompleteness.Machines.SourceCoordinateMachine +OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceIndexMachine +OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceLoopMachine +OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceMachine +OAI.Computability.PerfectCompleteness.Machines.SourceOccurrenceProducerLemmas +OAI.Computability.PerfectCompleteness.Machines.SourcePhysicalTapeFiber +OAI.Computability.PerfectCompleteness.Machines.SourcePhysicalTapeLaw +OAI.Computability.PerfectCompleteness.Machines.SourceTupleMachine +OAI.Computability.PerfectCompleteness.Machines.SourceTupleResetMachine +OAI.Computability.PerfectCompleteness.Machines.StatementCircuit +OAI.Computability.PerfectCompleteness.Machines.StoppedCleanOwnInputGeometry +OAI.Computability.PerfectCompleteness.Machines.StoppedOwnInputGeometry +OAI.Computability.PerfectCompleteness.Machines.TargetFinalizeMachine +OAI.Computability.PerfectCompleteness.Machines.TargetHeaderMachine +OAI.Computability.PerfectCompleteness.Machines.TargetTapeEnvelope +OAI.Computability.PerfectCompleteness.Machines.TermMachine +OAI.Computability.PerfectCompleteness.Machines.TransitionIteration +OAI.Computability.PerfectCompleteness.Machines.TransitionMachine +OAI.Computability.PerfectCompleteness.Machines.TransitionTemplate +OAI.Computability.PerfectCompleteness.Machines.TupleEnumerationMachine +OAI.Computability.PerfectCompleteness.Machines.TupleIndexMachine +OAI.Computability.PerfectCompleteness.Machines.TupleInitializationMachine +OAI.Computability.PerfectCompleteness.Machines.UnaryBlockCopyMachine +OAI.Computability.PerfectCompleteness.Machines.UnaryBlockSkipMachine +OAI.Computability.PerfectCompleteness.Machines.UnaryRepresentationMachine +OAI.Computability.PerfectCompleteness.Machines.ValidityComposition +OAI.Computability.PerfectCompleteness.Machines.ValidityMachine +OAI.Computability.PerfectCompleteness.Machines.VerifierCircuit +OAI.Computability.PerfectCompleteness.Machines.VerifierFront +OAI.Computability.PerfectCompleteness.Machines.WholeArrayInteriorOwnInputLaw +OAI.Computability.PerfectCompleteness.Machines.WholeArrayOwnInputLaw +OAI.Computability.PerfectCompleteness.Machines.WitnessCircuit +OAI.Computability.PerfectCompleteness.Machines.WitnessEncodingLemmas +OAI.Computability.PerfectCompleteness.Main +OAI.Computability.PerfectCompleteness.Model +OAI.Computability.PerfectCompleteness.Reduction.CanonicalGameLemmas +OAI.Computability.PerfectCompleteness.Reduction.CanonicalNamedGame +OAI.Computability.PerfectCompleteness.Reduction.CompletedOccurrenceOrder +OAI.Computability.PerfectCompleteness.Reduction.CompletedVisitOrder +OAI.Computability.PerfectCompleteness.Reduction.CompletionAlphabetLemmas +OAI.Computability.PerfectCompleteness.Reduction.CompletionLemmas +OAI.Computability.PerfectCompleteness.Reduction.CompletionOutputLemmas +OAI.Computability.PerfectCompleteness.Reduction.CompletionSoundness +OAI.Computability.PerfectCompleteness.Reduction.ExactPreliminaryTarget +OAI.Computability.PerfectCompleteness.Reduction.FinitePreliminaryCompletion +OAI.Computability.PerfectCompleteness.Reduction.FixedCallBudgetLemmas +OAI.Computability.PerfectCompleteness.Reduction.FixedComparisonErrorsLemmas +OAI.Computability.PerfectCompleteness.Reduction.FixedNativeHigh +OAI.Computability.PerfectCompleteness.Reduction.FixedPhysicalStoppedComparison +OAI.Computability.PerfectCompleteness.Reduction.FixedPreliminarySoundness +OAI.Computability.PerfectCompleteness.Reduction.FixedQueryCodec +OAI.Computability.PerfectCompleteness.Reduction.FixedRows +OAI.Computability.PerfectCompleteness.Reduction.FixedSourcePhysicalHighLemmas +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedActualBounds +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedContradiction +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedDirections +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedError +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedHighBound +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedInverseBound +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedMeetingEquality +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedPair +OAI.Computability.PerfectCompleteness.Reduction.FixedStoppedUsefulMass +OAI.Computability.PerfectCompleteness.Reduction.FixedTarget +OAI.Computability.PerfectCompleteness.Reduction.FixedTargetValue +OAI.Computability.PerfectCompleteness.Reduction.HierarchicalFixedAdviceFamilyLemmas +OAI.Computability.PerfectCompleteness.Reduction.NormalizedTarget +OAI.Computability.PerfectCompleteness.Reduction.NormalizedTargetInitialization +OAI.Computability.PerfectCompleteness.Reduction.OccurrenceGame +OAI.Computability.PerfectCompleteness.Reduction.OddListGame +OAI.Computability.PerfectCompleteness.Reduction.PreliminaryAveraging +OAI.Computability.PerfectCompleteness.Reduction.PreliminaryLevelPair +OAI.Computability.PerfectCompleteness.Reduction.PreliminaryOutputLemmas +OAI.Computability.PerfectCompleteness.Reduction.SignedCompletionSchedule +OAI.Computability.PerfectCompleteness.Reduction.SourceCompleteness +OAI.Computability.PerfectCompleteness.Reduction.SourceGame +OAI.Computability.PerfectCompleteness.Reduction.Target +OAI.Computability.PerfectCompleteness.Reduction.TargetFinalizeBound +OAI.Computability.PerfectCompleteness.Reduction.TargetGameLemmas +OAI.Computability.PerfectCompleteness.Reduction.Value +OAI.Computability.PerfectCompleteness.Repetition.AmplifiedCleanRateLemmas +OAI.Computability.PerfectCompleteness.Repetition.CleanConditioning +OAI.Computability.PerfectCompleteness.Repetition.CleanCountingLemmas +OAI.Computability.PerfectCompleteness.Repetition.CleanEndpointSlots +OAI.Computability.PerfectCompleteness.Repetition.CleanNativeReplay +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalCanonicalQuery +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalHighAverage +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalHighEvent +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalProjectedMeeting +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalRawChildren +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplay +OAI.Computability.PerfectCompleteness.Repetition.CleanPhysicalReplayLaw +OAI.Computability.PerfectCompleteness.Repetition.CleanRecordChildBlocks +OAI.Computability.PerfectCompleteness.Repetition.CleanRecordObservation +OAI.Computability.PerfectCompleteness.Repetition.CleanTreeFactors +OAI.Computability.PerfectCompleteness.Repetition.CutChildCleanLawLemmas +OAI.Computability.PerfectCompleteness.Repetition.FixedCleanRate +OAI.Computability.PerfectCompleteness.Repetition.RepetitionRateLemmas +OAI.Computability.PerfectCompleteness.Repetition.SourceAmplification +OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanCutEquality +OAI.Computability.PerfectCompleteness.Repetition.StoppedCleanGeometry +OAI.Computability.PerfectCompleteness.Sampling.BoundedListSamplingLemmas +OAI.Computability.PerfectCompleteness.Sampling.BucketDescriptorLaw +OAI.Computability.PerfectCompleteness.Sampling.BucketResamplingLaw +OAI.Computability.PerfectCompleteness.Sampling.BucketSampler +OAI.Computability.PerfectCompleteness.Sampling.BucketUniformLemmas +OAI.Computability.PerfectCompleteness.Sampling.CandidateCoupling +OAI.Computability.PerfectCompleteness.Sampling.ChildCallNumberingLaws +OAI.Computability.PerfectCompleteness.Sampling.CommonProductVariationLemmas +OAI.Computability.PerfectCompleteness.Sampling.CompletedSignedLaw +OAI.Computability.PerfectCompleteness.Sampling.CompletionProbability +OAI.Computability.PerfectCompleteness.Sampling.CutCallOriginalLaw +OAI.Computability.PerfectCompleteness.Sampling.CutSamplerKeyLocalityLemmas +OAI.Computability.PerfectCompleteness.Sampling.CutSamplerLocality +OAI.Computability.PerfectCompleteness.Sampling.CutSamplerRefinement +OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayGroupingTransport +OAI.Computability.PerfectCompleteness.Sampling.CutSamplerReplayTransportLemmas +OAI.Computability.PerfectCompleteness.Sampling.DensityVariation +OAI.Computability.PerfectCompleteness.Sampling.FilledUniformSampler +OAI.Computability.PerfectCompleteness.Sampling.FiniteListSampling +OAI.Computability.PerfectCompleteness.Sampling.FixedSourcePairVariation +OAI.Computability.PerfectCompleteness.Sampling.FixedStoppedPhysicalLawLemmas +OAI.Computability.PerfectCompleteness.Sampling.GoodRowSampling +OAI.Computability.PerfectCompleteness.Sampling.HierarchicalArrayLaw +OAI.Computability.PerfectCompleteness.Sampling.HierarchicalBackgroundVariation +OAI.Computability.PerfectCompleteness.Sampling.MetadataFreeLaw +OAI.Computability.PerfectCompleteness.Sampling.MetadataFreeSampler +OAI.Computability.PerfectCompleteness.Sampling.NumberedUniformCut +OAI.Computability.PerfectCompleteness.Sampling.OriginalCutBucketLaw +OAI.Computability.PerfectCompleteness.Sampling.OriginalCutPairLaw +OAI.Computability.PerfectCompleteness.Sampling.OriginalUniformCut +OAI.Computability.PerfectCompleteness.Sampling.OriginalUniformCutBase +OAI.Computability.PerfectCompleteness.Sampling.OriginalUsefulPairLaw +OAI.Computability.PerfectCompleteness.Sampling.OriginalWholeCutLaw +OAI.Computability.PerfectCompleteness.Sampling.OwnLawHeavyList +OAI.Computability.PerfectCompleteness.Sampling.PreliminarySampler +OAI.Computability.PerfectCompleteness.Sampling.RationalFiniteLawLemmas +OAI.Computability.PerfectCompleteness.Sampling.RecordSeedSamplingLemmas +OAI.Computability.PerfectCompleteness.Sampling.RecursiveSamplerLaws +OAI.Computability.PerfectCompleteness.Sampling.RestrictionCrossLaw +OAI.Computability.PerfectCompleteness.Sampling.RestrictionRowsLaw +OAI.Computability.PerfectCompleteness.Sampling.SamplerCardinalityLemmas +OAI.Computability.PerfectCompleteness.Sampling.SamplerComposition +OAI.Computability.PerfectCompleteness.Sampling.SamplerCompositionLaws +OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelLaw +OAI.Computability.PerfectCompleteness.Sampling.SourceChildKernelMarginalLemmas +OAI.Computability.PerfectCompleteness.Sampling.SourceChildMarkedLaw +OAI.Computability.PerfectCompleteness.Sampling.SourceChildQuestionLaw +OAI.Computability.PerfectCompleteness.Sampling.SourcePhysicalAssemblyLaw +OAI.Computability.PerfectCompleteness.Sampling.SourcePhysicalWholeLaw +OAI.Computability.PerfectCompleteness.Sampling.StoppedBucketUsefulProbability +OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedGlobalLawLemmas +OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedMeetingLaw +OAI.Computability.PerfectCompleteness.Sampling.StoppedProjectedUsefulProbability +OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedLaw +OAI.Computability.PerfectCompleteness.Sampling.StoppedSharedSampler +OAI.Computability.PerfectCompleteness.Sampling.StoppedSourcePairLaw +OAI.Computability.PerfectCompleteness.Sampling.StoppedUsefulPairLaw +OAI.Computability.PerfectCompleteness.Sampling.TaggedKernelRebuildLaw +OAI.Computability.PerfectCompleteness.Sampling.UniformChildSum +OAI.Computability.PerfectCompleteness.Sampling.UniformDensity +OAI.Computability.PerfectCompleteness.Sampling.UniformDifference +OAI.Computability.PerfectCompleteness.Sampling.UniformLatent +OAI.Computability.PerfectCompleteness.Sampling.UniformLatentSupportLemmas +OAI.Computability.PerfectCompleteness.Sampling.WholeArrayBucketsLaw +OAI.Computability.PerfectCompleteness.Sampling.WholeArrayExteriorLaw +OAI.Computability.PerfectCompleteness.Sampling.WholeArrayHiddenLaw +OAI.Computability.PerfectCompleteness.Sampling.WholeArrayInteriorHiddenLaw +OAI.Computability.PerfectCompleteness.Sampling.WholeArrayProductLaw +OAI.Computability.PerfectCompleteness.Sampling.WholeArraySampler +OAI.Computability.PerfectCompleteness.Sampling.WholeCutSampler +OAI.Computability.PerfectCompleteness.Theorem11 +OAI.Computability.UniqueGames.Analysis.A13IndexLemmas +OAI.Computability.UniqueGames.Analysis.A5FrequencyTransportLemmas +OAI.Computability.UniqueGames.Analysis.A5IndexCount +OAI.Computability.UniqueGames.Analysis.A5ReverseIndex +OAI.Computability.UniqueGames.Analysis.AntecedentCountLemmas +OAI.Computability.UniqueGames.Analysis.BadConvolution +OAI.Computability.UniqueGames.Analysis.CompressionCountLemmas +OAI.Computability.UniqueGames.Analysis.DegreeCover +OAI.Computability.UniqueGames.Analysis.DerivativeInduction +OAI.Computability.UniqueGames.Analysis.DyadicError +OAI.Computability.UniqueGames.Analysis.FiberEnergyLemmas +OAI.Computability.UniqueGames.Analysis.HybridCompositionLemmas +OAI.Computability.UniqueGames.Analysis.HybridCounting +OAI.Computability.UniqueGames.Analysis.Identities +OAI.Computability.UniqueGames.Analysis.MatrixCharactersLemmas +OAI.Computability.UniqueGames.Analysis.MatrixNoiseLemmas +OAI.Computability.UniqueGames.Analysis.MatrixRestrictions +OAI.Computability.UniqueGames.Analysis.MatrixSubspaceCount +OAI.Computability.UniqueGames.Analysis.OperatorPartitions +OAI.Computability.UniqueGames.Analysis.ParityLemmas +OAI.Computability.UniqueGames.Analysis.RestrictionLemmas +OAI.Computability.UniqueGames.Analysis.RestrictionTransport +OAI.Computability.UniqueGames.Analysis.SubspaceCountingLemmas +OAI.Computability.UniqueGames.Analysis.WeightedFourthMoment +OAI.Computability.UniqueGames.Foundations.Basic +OAI.Computability.UniqueGames.Foundations.Conditioning +OAI.Computability.UniqueGames.Foundations.FiniteTrialsLemmas +OAI.Computability.UniqueGames.Foundations.KernelSampling +OAI.Computability.UniqueGames.Foundations.LabelBound +OAI.Computability.UniqueGames.Foundations.MixtureLemmas +OAI.Computability.UniqueGames.Foundations.PinskerLemmas +OAI.Computability.UniqueGames.Foundations.Rectangle +OAI.Computability.UniqueGames.Foundations.SamplingLemmas +OAI.Computability.UniqueGames.Foundations.SharedProfiles +OAI.Computability.UniqueGames.Foundations.ValueLemmas +OAI.Computability.UniqueGames.Gadgets.ActualGadgetLemmas +OAI.Computability.UniqueGames.Gadgets.AdaptivePathsLemmas +OAI.Computability.UniqueGames.Gadgets.ConcatenationLemmas +OAI.Computability.UniqueGames.Gadgets.NonlinearRecurrenceLemmas +OAI.Computability.UniqueGames.Gadgets.QuotientLemmas +OAI.Computability.UniqueGames.Games.CompletedSamplingLemmas +OAI.Computability.UniqueGames.Games.FactorizationLemmas +OAI.Computability.UniqueGames.Games.FinishBoundsLemmas +OAI.Computability.UniqueGames.Games.MaskedVariation +OAI.Computability.UniqueGames.Games.Overlap +OAI.Computability.UniqueGames.Games.PartialRevealLemmas +OAI.Computability.UniqueGames.Games.SelectedCommonMarginalLemmas +OAI.Computability.UniqueGames.Games.SelectedInformationLemmas +OAI.Computability.UniqueGames.Games.SelectionSequence +OAI.Computability.UniqueGames.Games.Variation +OAI.Computability.UniqueGames.Machines.FinalCNFLoopLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFMachineLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFOutputLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFPattern +OAI.Computability.UniqueGames.Machines.FinalCNFRowPlanLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFStream +OAI.Computability.UniqueGames.Machines.FinalCNFTableAdapter +OAI.Computability.UniqueGames.Machines.FinalCNFTemplate +OAI.Computability.UniqueGames.Machines.GraphCounterFinish +OAI.Computability.UniqueGames.Machines.GraphCounterModel +OAI.Computability.UniqueGames.Machines.GraphCounterStartLemmas +OAI.Computability.UniqueGames.Machines.GraphIterationBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineAppendAt +OAI.Computability.UniqueGames.Machines.MachineCanonicalOutputLemmas +OAI.Computability.UniqueGames.Machines.MachineCeilingPower +OAI.Computability.UniqueGames.Machines.MachineCloudCount +OAI.Computability.UniqueGames.Machines.MachineCloudPadding +OAI.Computability.UniqueGames.Machines.MachineCloudPrefix +OAI.Computability.UniqueGames.Machines.MachineCloudRankLemmas +OAI.Computability.UniqueGames.Machines.MachineCompare +OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +OAI.Computability.UniqueGames.Machines.MachineControlLemmas +OAI.Computability.UniqueGames.Machines.MachineCopy +OAI.Computability.UniqueGames.Machines.MachineDrain +OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderFamily +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyLoop +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyTapes +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyTransferLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderRow +OAI.Computability.UniqueGames.Machines.MachineExpanderRowCleanup +OAI.Computability.UniqueGames.Machines.MachineExpanderRowDivision +OAI.Computability.UniqueGames.Machines.MachineExpanderRowEmitLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderRowFrames +OAI.Computability.UniqueGames.Machines.MachineExpanderTable +OAI.Computability.UniqueGames.Machines.MachineExpanderTableLoop +OAI.Computability.UniqueGames.Machines.MachineExpanderTableProgramLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderTableReverse +OAI.Computability.UniqueGames.Machines.MachineExpanderTableRows +OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet +OAI.Computability.UniqueGames.Machines.MachineFiniteTable +OAI.Computability.UniqueGames.Machines.MachineFixedDivMod +OAI.Computability.UniqueGames.Machines.MachineInitialHeaders +OAI.Computability.UniqueGames.Machines.MachineLazyCodec +OAI.Computability.UniqueGames.Machines.MachineLazyRows +OAI.Computability.UniqueGames.Machines.MachineLazyTable +OAI.Computability.UniqueGames.Machines.MachineLazyTableRuntime +OAI.Computability.UniqueGames.Machines.MachineLemmas +OAI.Computability.UniqueGames.Machines.MachineLogCounter +OAI.Computability.UniqueGames.Machines.MachineLookupCore +OAI.Computability.UniqueGames.Machines.MachineLookupDiscard +OAI.Computability.UniqueGames.Machines.MachineLookupLemmas +OAI.Computability.UniqueGames.Machines.MachineOverlayRows +OAI.Computability.UniqueGames.Machines.MachineOverlayTable +OAI.Computability.UniqueGames.Machines.MachinePaddedExpanderFamilyBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddedOverlay +OAI.Computability.UniqueGames.Machines.MachinePaddedOverlayRuntimeLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddingRowsLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddingTable +OAI.Computability.UniqueGames.Machines.MachinePortReindex +OAI.Computability.UniqueGames.Machines.MachineProductFieldLemmas +OAI.Computability.UniqueGames.Machines.MachineProductGatherBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineRadixStepLemmas +OAI.Computability.UniqueGames.Machines.MachineRegularDummyRow +OAI.Computability.UniqueGames.Machines.MachineRegularFamily +OAI.Computability.UniqueGames.Machines.MachineRegularInternalRow +OAI.Computability.UniqueGames.Machines.MachineRegularLift +OAI.Computability.UniqueGames.Machines.MachineRegularMetadata +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalBody +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalBodyBounds +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalClean +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalRow +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerBody +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerBodyBounds +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerCleanup +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerProgram +OAI.Computability.UniqueGames.Machines.MachineRegularTable +OAI.Computability.UniqueGames.Machines.MachineRegularTableBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineRegularTableTrace +OAI.Computability.UniqueGames.Machines.MachineRegularVertexBlock +OAI.Computability.UniqueGames.Machines.MachineRepeat +OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +OAI.Computability.UniqueGames.Machines.MachineTableSplit +OAI.Computability.UniqueGames.Machines.MachineTransducerCopy +OAI.Computability.UniqueGames.Machines.MachineTupleOdometer +OAI.Computability.UniqueGames.Machines.MachineUnaryAddAt +OAI.Computability.UniqueGames.Machines.MachineUnaryAffineAt +OAI.Computability.UniqueGames.Machines.MachineUnaryEqualityBit +OAI.Computability.UniqueGames.Machines.MachineUnaryLessAtLemmas +OAI.Computability.UniqueGames.Machines.MachineUnaryMultiply +OAI.Computability.UniqueGames.Machines.MachineVertexPadding +OAI.Computability.UniqueGames.Machines.PoweringGlobalEnumerationLemmas +OAI.Computability.UniqueGames.Machines.PoweringInitializeFrame +OAI.Computability.UniqueGames.Machines.PoweringMachineEqualityField +OAI.Computability.UniqueGames.Machines.PoweringMachineFinish +OAI.Computability.UniqueGames.Machines.PoweringMachineInitialize +OAI.Computability.UniqueGames.Machines.PoweringMachineLoop +OAI.Computability.UniqueGames.Machines.PoweringMachineOuterLoopLemmas +OAI.Computability.UniqueGames.Machines.PoweringMachineRelationLemmas +OAI.Computability.UniqueGames.Machines.PoweringMachineRow +OAI.Computability.UniqueGames.Machines.PoweringMachineRowBody +OAI.Computability.UniqueGames.Machines.PoweringMachineVertex +OAI.Computability.UniqueGames.Machines.PoweringMasterState +OAI.Computability.UniqueGames.Machines.PoweringPlanBudget +OAI.Computability.UniqueGames.Machines.PoweringPolynomialBudgetLemmas +OAI.Computability.UniqueGames.Machines.Runtime +OAI.Computability.UniqueGames.Model +OAI.Computability.UniqueGames.PCP.Addresses +OAI.Computability.UniqueGames.PCP.AlphabetGraphLemmas +OAI.Computability.UniqueGames.PCP.AlphabetReductionLemmas +OAI.Computability.UniqueGames.PCP.AlphabetRetractionLemmas +OAI.Computability.UniqueGames.PCP.AlphabetTableBoundsLemmas +OAI.Computability.UniqueGames.PCP.AmplificationIteration +OAI.Computability.UniqueGames.PCP.AssignmentTester +OAI.Computability.UniqueGames.PCP.Body +OAI.Computability.UniqueGames.PCP.CayleySampling +OAI.Computability.UniqueGames.PCP.CayleyTailCount +OAI.Computability.UniqueGames.PCP.ClauseVerifierLemmas +OAI.Computability.UniqueGames.PCP.CleanupLemmas +OAI.Computability.UniqueGames.PCP.CloudRoundingLemmas +OAI.Computability.UniqueGames.PCP.CodeComposition +OAI.Computability.UniqueGames.PCP.CompareLoop +OAI.Computability.UniqueGames.PCP.DriverLemmas +OAI.Computability.UniqueGames.PCP.EmitRows +OAI.Computability.UniqueGames.PCP.Emitter +OAI.Computability.UniqueGames.PCP.ExpanderRowControlLemmas +OAI.Computability.UniqueGames.PCP.ExpanderTableEnumeration +OAI.Computability.UniqueGames.PCP.ExpanderTables +OAI.Computability.UniqueGames.PCP.ExpandersLemmas +OAI.Computability.UniqueGames.PCP.FinalBooleanVerifier +OAI.Computability.UniqueGames.PCP.FinalConstantsLemmas +OAI.Computability.UniqueGames.PCP.FinalTableFormula +OAI.Computability.UniqueGames.PCP.FoldedEquationLemmas +OAI.Computability.UniqueGames.PCP.FourierResponseLemmas +OAI.Computability.UniqueGames.PCP.GenericGraphTables +OAI.Computability.UniqueGames.PCP.GraphTables +OAI.Computability.UniqueGames.PCP.HonestTestLemmas +OAI.Computability.UniqueGames.PCP.InitialGraphLemmas +OAI.Computability.UniqueGames.PCP.Initialization +OAI.Computability.UniqueGames.PCP.InputLemmas +OAI.Computability.UniqueGames.PCP.LoopInitializationLemmas +OAI.Computability.UniqueGames.PCP.LoopState +OAI.Computability.UniqueGames.PCP.MachineRawInitialTable +OAI.Computability.UniqueGames.PCP.NameCompaction +OAI.Computability.UniqueGames.PCP.OverlayLemmas +OAI.Computability.UniqueGames.PCP.PortTableEncoding +OAI.Computability.UniqueGames.PCP.PortTableLookup +OAI.Computability.UniqueGames.PCP.PoweringLabelsLemmas +OAI.Computability.UniqueGames.PCP.PoweringOpinionTables +OAI.Computability.UniqueGames.PCP.PoweringOpinionsLemmas +OAI.Computability.UniqueGames.PCP.PoweringPortReindexLemmas +OAI.Computability.UniqueGames.PCP.PoweringTableLayout +OAI.Computability.UniqueGames.PCP.PoweringTableSemanticsLemmas +OAI.Computability.UniqueGames.PCP.PoweringTablesLemmas +OAI.Computability.UniqueGames.PCP.Preprocessing +OAI.Computability.UniqueGames.PCP.PreprocessingInternalRows +OAI.Computability.UniqueGames.PCP.PreprocessingLazyWords +OAI.Computability.UniqueGames.PCP.PreprocessingOverlayTables +OAI.Computability.UniqueGames.PCP.PreprocessingOverlayWords +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingOffsets +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingTables +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingWords +OAI.Computability.UniqueGames.PCP.PreprocessingRegularLoopWordsLemmas +OAI.Computability.UniqueGames.PCP.PreprocessingRegularSoundness +OAI.Computability.UniqueGames.PCP.PreprocessingRegularTablesLemmas +OAI.Computability.UniqueGames.PCP.PreprocessingRegularWords +OAI.Computability.UniqueGames.PCP.PreprocessingTableSpectral +OAI.Computability.UniqueGames.PCP.PreprocessingTablesLemmas +OAI.Computability.UniqueGames.PCP.QueriesLemmas +OAI.Computability.UniqueGames.PCP.RawInitialMachineBody +OAI.Computability.UniqueGames.PCP.RawInitialMachineCleanup +OAI.Computability.UniqueGames.PCP.RawInitialMachineFinish +OAI.Computability.UniqueGames.PCP.RawInitialMachineLoop +OAI.Computability.UniqueGames.PCP.RawInitialMachineLoopData +OAI.Computability.UniqueGames.PCP.RawInitialMachinePhases +OAI.Computability.UniqueGames.PCP.RawInitialMachineReadClause +OAI.Computability.UniqueGames.PCP.RawInitialMachineRows +OAI.Computability.UniqueGames.PCP.RawInitialMachineStart +OAI.Computability.UniqueGames.PCP.RawInitialTablesLemmas +OAI.Computability.UniqueGames.PCP.RoundSize +OAI.Computability.UniqueGames.PCP.RuntimeModel +OAI.Computability.UniqueGames.PCP.Setup +OAI.Computability.UniqueGames.PCP.SourceAddressArithmeticLemmas +OAI.Computability.UniqueGames.PCP.SourceContextClear +OAI.Computability.UniqueGames.PCP.SourceContextLoad +OAI.Computability.UniqueGames.PCP.SourceDescriptorEmissionLemmas +OAI.Computability.UniqueGames.PCP.SourceFieldArrayLemmas +OAI.Computability.UniqueGames.PCP.SourceGapLemmas +OAI.Computability.UniqueGames.PCP.SourceHeaderAccumulate +OAI.Computability.UniqueGames.PCP.SourceHeaderCounts +OAI.Computability.UniqueGames.PCP.SourceHonestLemmas +OAI.Computability.UniqueGames.PCP.SourceLoopInitLemmas +OAI.Computability.UniqueGames.PCP.SourceMachine +OAI.Computability.UniqueGames.PCP.SourceNoiseParameterLemmas +OAI.Computability.UniqueGames.PCP.SourceOccurrences +OAI.Computability.UniqueGames.PCP.SourceQueryLoopLemmas +OAI.Computability.UniqueGames.PCP.SourceQueryOrderLemmas +OAI.Computability.UniqueGames.PCP.SourceRuntimeSpace +OAI.Computability.UniqueGames.PCP.SourceSignaturePrepareLemmas +OAI.Computability.UniqueGames.PCP.SourceTupleBody +OAI.Computability.UniqueGames.PCP.SourceTupleBound +OAI.Computability.UniqueGames.PCP.Table +OAI.Computability.UniqueGames.PCP.TableGapReductionLemmas +OAI.Computability.UniqueGames.PCP.TableIteration +OAI.Computability.UniqueGames.PCP.VertexPadding +OAI.Computability.UniqueGames.PCP.ZigzagGraphsLemmas +OAI.Computability.UniqueGames.Reduction.ActualCanonicalLemmas +OAI.Computability.UniqueGames.Reduction.ActualGame +OAI.Computability.UniqueGames.Reduction.ActualSourceLemmas +OAI.Computability.UniqueGames.Reduction.BinaryCoordinates +OAI.Computability.UniqueGames.Reduction.BinaryLinear +OAI.Computability.UniqueGames.Reduction.CanonicalBodyTemplateLemmas +OAI.Computability.UniqueGames.Reduction.EncodingLemmas +OAI.Computability.UniqueGames.Reduction.ExplicitLemmas +OAI.Computability.UniqueGames.Reduction.FinalParametersLemmas +OAI.Computability.UniqueGames.Reduction.GameEncodingSizeLemmas +OAI.Computability.UniqueGames.Reduction.GapSemanticsLemmas +OAI.Computability.UniqueGames.Reduction.IncidenceProbabilityLemmas +OAI.Computability.UniqueGames.Reduction.MachineFieldTemplate +OAI.Computability.UniqueGames.Reduction.MachineReverse +OAI.Computability.UniqueGames.Reduction.MachineSubstitution +OAI.Computability.UniqueGames.Reduction.MachineTransducer +OAI.Computability.UniqueGames.Reduction.MachineTransfer +OAI.Computability.UniqueGames.Reduction.NoiseEnumerationLemmas +OAI.Computability.UniqueGames.Reduction.RealTargetLemmas +OAI.Computability.UniqueGames.Reduction.SourceIncidenceLemmas +OAI.Computability.UniqueGames.Reduction.WeightRounding +OAI.Computability.UniqueGames.Reduction.WeightedSource +OAI.Computability.UniqueGames.Soundness.ExpectationComparisonLemmas +OAI.Computability.UniqueGames.Soundness.LinearMapDensityLemmas +OAI.Computability.UniqueGames.Soundness.PartnerLinearLemmas diff --git a/tasks/perfect-completeness/solution/reference.py b/tasks/perfect-completeness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/perfect-completeness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/perfect-completeness/solution/solve.sh b/tasks/perfect-completeness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f63ddfa7912be2f1501d2f26f198b704856e1a3f --- /dev/null +++ b/tasks/perfect-completeness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PerfectCompleteness, i.e. module OAI.Computability.PerfectCompleteness.Main and the +# 863 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.PerfectCompleteness.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PerfectCompleteness" diff --git a/tasks/perfect-completeness/task.toml b/tasks/perfect-completeness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3d79edfd979a621162d09bfabf6d7dc07d0d224a --- /dev/null +++ b/tasks/perfect-completeness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/perfect-completeness" +version = "1.0.0" +description = "Prove PerfectCompleteness (openai/math family 105: The 2-to-1 Games Conjecture with perfect completeness) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PerfectCompleteness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PerfectCompleteness" +family = "105" +family_title = "The 2-to-1 Games Conjecture with perfect completeness" +subject = "Theoretical computer science" +theorems = ["OAI.PerfectCompleteness.Theorem11.exists_reduction"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.PerfectCompleteness.Main" +reference_modules = 863 +reference_lean_bytes = 12353482 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2380 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 22500 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/perfect-completeness/tests/Challenge.lean b/tasks/perfect-completeness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6ce53557019808040aaee908d802fbeeb63b166 --- /dev/null +++ b/tasks/perfect-completeness/tests/Challenge.lean @@ -0,0 +1,185 @@ +import Mathlib + +namespace OAI + +namespace UniqueGamesTheorem.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +def encodeWords : List Nat → List Bool + | [] => [] + | n :: ns => encodeWord n ++ encodeWords ns + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +namespace PerfectCompleteness.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end PerfectCompleteness.BinaryFormula + +namespace PerfectCompleteness.BinaryEncoding + +open PerfectCompleteness.BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end PerfectCompleteness.BinaryEncoding + +namespace PerfectCompleteness.BinaryLanguage + +def language (input : List Bool) : Prop := + ∃ formula, BinaryEncoding.decodeFormula input = some formula ∧ formula.Satisfiable + +end PerfectCompleteness.BinaryLanguage + +namespace PerfectCompleteness + +structure ProjectionTable (q : Nat) where + images : Vector (Fin q) (2 * q) + exactlyTwo : ∀ b : Fin q, + ((List.finRange (2 * q)).filter (fun a => decide (images[a] = b))).length = 2 + +structure Edge (leftVertices rightVertices q : Nat) where + left : Fin leftVertices + right : Fin rightVertices + projection : ProjectionTable q + +structure Instance (q : Nat) where + leftVertices : Nat + rightVertices : Nat + edges : List (Edge leftVertices rightVertices q) + nonempty : edges ≠ [] + +abbrev Labeling {q : Nat} (G : Instance q) := + (Fin G.leftVertices → Fin (2 * q)) × (Fin G.rightVertices → Fin q) + +def Edge.satisfied {l r q : Nat} (e : Edge l r q) + (a : Fin l → Fin (2 * q)) (b : Fin r → Fin q) : Bool := + decide (e.projection.images[a e.left] = b e.right) + +def countSatisfied {l r q : Nat} (a : Fin l → Fin (2 * q)) + (b : Fin r → Fin q) : List (Edge l r q) → Nat + | [] => 0 + | e :: es => (if e.satisfied a b then 1 else 0) + countSatisfied a b es + +end PerfectCompleteness + +namespace PerfectCompleteness.Instance + +def maxSatisfied {q : Nat} (G : Instance q) : Nat := + Finset.univ.sup (fun s : Labeling G => countSatisfied s.1 s.2 G.edges) + +noncomputable def value {q : Nat} (G : Instance q) : ℝ := + (G.maxSatisfied : ℝ) / G.edges.length + +end PerfectCompleteness.Instance + +namespace PerfectCompleteness.Encoding + +open UniqueGamesTheorem.Foundations.Complexity + +def tableWords {q : Nat} (table : ProjectionTable q) : List Nat := + table.images.toList.map Fin.val + +def edgeWords {l r q : Nat} (edge : Edge l r q) : List Nat := + [edge.left.val, edge.right.val] ++ tableWords edge.projection + +def gameWords {q : Nat} (game : Instance q) : List Nat := + [game.leftVertices, game.rightVertices, q, game.edges.length] ++ + game.edges.flatMap edgeWords + +def gameBits {q : Nat} (game : Instance q) : List Bool := + encodeWords (gameWords game) + +end PerfectCompleteness.Encoding + +namespace PerfectCompleteness + +open Turing UniqueGamesTheorem.Foundations.Complexity + +structure BinaryGapReduction (δ : ℚ) where + alphabet : Nat + alphabet_ge_two : 2 ≤ alphabet + construct : List Bool → Instance alphabet + computation : TM2ComputableInPolyTime (id : List Bool → List Bool) + Encoding.gameBits construct + finiteAlphabet : MachineFiniteAlphabet.FiniteAlphabet computation.tm + completeness : ∀ input, BinaryLanguage.language input → (construct input).value = 1 + soundness : ∀ input, ¬BinaryLanguage.language input → (construct input).value ≤ (δ : ℝ) + +end PerfectCompleteness + +namespace PerfectCompleteness.Theorem11 + +theorem exists_reduction (δ : ℚ) (positive : 0 < δ) (less_than_one : δ < 1) : + Nonempty (PerfectCompleteness.BinaryGapReduction δ) := by + sorry + +end PerfectCompleteness.Theorem11 + +end OAI diff --git a/tasks/perfect-completeness/tests/grade.py b/tasks/perfect-completeness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/perfect-completeness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/perfect-completeness/tests/task.json b/tasks/perfect-completeness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3ec2ad9a5547ba5df350de63bd194605f0840a5b --- /dev/null +++ b/tasks/perfect-completeness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PerfectCompleteness", + "comparator": { + "theorem_names": [ + "OAI.PerfectCompleteness.Theorem11.exists_reduction" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 21600 +} \ No newline at end of file diff --git a/tasks/perfect-completeness/tests/test.sh b/tasks/perfect-completeness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/perfect-completeness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/periodic-group/environment/Dockerfile b/tasks/periodic-group/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/periodic-group/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/periodic-group/environment/fetch_mathlib.sh b/tasks/periodic-group/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/periodic-group/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/periodic-group/environment/lake-manifest.json b/tasks/periodic-group/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/periodic-group/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/periodic-group/environment/lakefile.lean b/tasks/periodic-group/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/periodic-group/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/periodic-group/environment/lean_setup.sh b/tasks/periodic-group/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/periodic-group/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/periodic-group/environment/pack_submission.py b/tasks/periodic-group/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/periodic-group/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/periodic-group/instruction.md b/tasks/periodic-group/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2f6428cbde7ac5ea0c633838a8b134a1293c1637 --- /dev/null +++ b/tasks/periodic-group/instruction.md @@ -0,0 +1,107 @@ +# openai/math challenge `PeriodicGroup` (family 247) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 247 of the release, *An infinite finitely presented residually finite $2$-group* +(Group theory). The family as a whole: Constructs an infinite finitely presented residually finite group whose elements all have finite $2$-power order, answering the finitely presented Burnside problem negatively even in this class. The construction also yields an infinite-dimensional finitely presented nil associative $\mathbb F_2$-algebra and a finitely presented infinite-dimensional algebraic unitization, giving negative answers to the corresponding nilpotence and Kurosh finiteness questions. + +The challenge is `PeriodicGroup`, also at `/opt/openai-math/challenges/PeriodicGroup.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u + +namespace SourceBurnside + +structure Root (n : ℕ) where + row : Fin n + col : Fin n + ne : row ≠ col + deriving DecidableEq + +abbrev Generator (n : ℕ) (R : Type u) := Root n × R + +def bracket {G : Type u} [Group G] (x y : G) : G := x * y * x⁻¹ * y⁻¹ + +def letter {n : ℕ} {R : Type u} (p : Root n) (a : R) : + FreeGroup (Generator n R) := FreeGroup.of (p, a) + +inductive SteinbergRel (n : ℕ) (R : Type u) [Ring R] : + FreeGroup (Generator n R) → Prop + | add (p : Root n) (a b : R) : + SteinbergRel n R (letter p (a + b) * (letter p a * letter p b)⁻¹) + | commute (p q : Root n) (h₁ : p.col ≠ q.row) (h₂ : p.row ≠ q.col) (a b : R) : + SteinbergRel n R (bracket (letter p a) (letter q b)) + | mul (i j k : Fin n) (hij : i ≠ j) (hjk : j ≠ k) (hik : i ≠ k) (a b : R) : + SteinbergRel n R + (bracket (letter ⟨i, j, hij⟩ a) (letter ⟨j, k, hjk⟩ b) * + (letter ⟨i, k, hik⟩ (a * b))⁻¹) + +def Steinberg (n : ℕ) (R : Type u) [Ring R] := + PresentedGroup {r | SteinbergRel n R r} + deriving Group + +def Periodic (G : Type u) [Group G] : Prop := ∀ g : G, ∃ m : ℕ, 0 < m ∧ g ^ m = 1 + +def MainStatement : Prop := + ∃ (R : Type) (_ : Ring R) (_ : Algebra (ZMod 2) R), + Infinite (Steinberg 12 R) ∧ Group.IsFinitelyPresented (Steinberg 12 R) ∧ + Periodic (Steinberg 12 R) + +def BurnsideStatement : Prop := + ∃ (G : Type) (_ : Group G), Infinite G ∧ Group.IsFinitelyPresented G ∧ Periodic G + +end SourceBurnside + +namespace SourceBurnside + +theorem thm_main : MainStatement ∧ BurnsideStatement := by + sorry + +end SourceBurnside + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PeriodicGroup.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SourceBurnside.thm_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/periodic-group/solution/closure.txt b/tasks/periodic-group/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8dbfaf47378e1c56d953426d7521b3540feddafb --- /dev/null +++ b/tasks/periodic-group/solution/closure.txt @@ -0,0 +1,63 @@ +OAI.GroupTheory.PeriodicGroups.Algebra.DirectCancellation +OAI.GroupTheory.PeriodicGroups.Algebra.HierarchyGrowth +OAI.GroupTheory.PeriodicGroups.Algebra.MatrixTests +OAI.GroupTheory.PeriodicGroups.Algebra.PacketIntervals +OAI.GroupTheory.PeriodicGroups.Algebra.WordAlgebra +OAI.GroupTheory.PeriodicGroups.Formulas.Addressable +OAI.GroupTheory.PeriodicGroups.Formulas.BooleanCircuits +OAI.GroupTheory.PeriodicGroups.Formulas.ClauseEncoding +OAI.GroupTheory.PeriodicGroups.Formulas.LocalPredicates +OAI.GroupTheory.PeriodicGroups.Formulas.PredicateCompilation +OAI.GroupTheory.PeriodicGroups.Formulas.Tableaux +OAI.GroupTheory.PeriodicGroups.Frames.AcyclicFrameEdge +OAI.GroupTheory.PeriodicGroups.Frames.ElementaryFrames +OAI.GroupTheory.PeriodicGroups.Frames.ExteriorComplex +OAI.GroupTheory.PeriodicGroups.Homology.FiniteExtensions +OAI.GroupTheory.PeriodicGroups.Homology.FiniteNormalHomology +OAI.GroupTheory.PeriodicGroups.Homology.KernelStability +OAI.GroupTheory.PeriodicGroups.Homology.LocallyFiniteActions +OAI.GroupTheory.PeriodicGroups.Homology.RelativeHomology +OAI.GroupTheory.PeriodicGroups.Machines.ArithmeticDevices +OAI.GroupTheory.PeriodicGroups.Machines.BinaryRegisters +OAI.GroupTheory.PeriodicGroups.Machines.Compilation +OAI.GroupTheory.PeriodicGroups.Machines.InputEncoding +OAI.GroupTheory.PeriodicGroups.Machines.ProgramAssembly +OAI.GroupTheory.PeriodicGroups.Machines.ProgramFixedPoint +OAI.GroupTheory.PeriodicGroups.Machines.RegisterLoops +OAI.GroupTheory.PeriodicGroups.Machines.RegisterOperators +OAI.GroupTheory.PeriodicGroups.Machines.StackCompression +OAI.GroupTheory.PeriodicGroups.Machines.TapePrograms +OAI.GroupTheory.PeriodicGroups.Machines.TimedExecution +OAI.GroupTheory.PeriodicGroups.Machines.UniversalInput +OAI.GroupTheory.PeriodicGroups.Machines.UniversalStack +OAI.GroupTheory.PeriodicGroups.Main +OAI.GroupTheory.PeriodicGroups.Matrices.ElementaryGenerators +OAI.GroupTheory.PeriodicGroups.Periodicity.KernelTorsion +OAI.GroupTheory.PeriodicGroups.Presentation.FinitePresentation +OAI.GroupTheory.PeriodicGroups.Presentation.MatrixStabilizers +OAI.GroupTheory.PeriodicGroups.Presentation.SmallFaithful +OAI.GroupTheory.PeriodicGroups.Presentation.SmallSwapActions +OAI.GroupTheory.PeriodicGroups.Rules.BoundaryCell +OAI.GroupTheory.PeriodicGroups.Rules.CommittedWords +OAI.GroupTheory.PeriodicGroups.Rules.ConnectedWords +OAI.GroupTheory.PeriodicGroups.Rules.DataWords +OAI.GroupTheory.PeriodicGroups.Rules.GeometricRelations +OAI.GroupTheory.PeriodicGroups.Rules.HeadTour +OAI.GroupTheory.PeriodicGroups.Rules.LocalSyntax +OAI.GroupTheory.PeriodicGroups.Rules.Palette +OAI.GroupTheory.PeriodicGroups.Rules.PrefixRewriting +OAI.GroupTheory.PeriodicGroups.Rules.Recognizer +OAI.GroupTheory.PeriodicGroups.Rules.TableEncoding +OAI.GroupTheory.PeriodicGroups.Rules.TemplateHierarchy +OAI.GroupTheory.PeriodicGroups.Rules.Transactions +OAI.GroupTheory.PeriodicGroups.Rules.WordComponents +OAI.GroupTheory.PeriodicGroups.Rules.WordRewriting +OAI.GroupTheory.PeriodicGroups.Steinberg.BandFactorization +OAI.GroupTheory.PeriodicGroups.Steinberg.BlockEmbeddings +OAI.GroupTheory.PeriodicGroups.Steinberg.CoefficientQuotients +OAI.GroupTheory.PeriodicGroups.Steinberg.DiagonalActions +OAI.GroupTheory.PeriodicGroups.Steinberg.KernelRelations +OAI.GroupTheory.PeriodicGroups.Steinberg.MatrixUnits +OAI.GroupTheory.PeriodicGroups.Steinberg.MonomialPresentation +OAI.GroupTheory.PeriodicGroups.Steinberg.PresentationModel +OAI.GroupTheory.PeriodicGroups.Steinberg.RankActions diff --git a/tasks/periodic-group/solution/reference.py b/tasks/periodic-group/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/periodic-group/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/periodic-group/solution/solve.sh b/tasks/periodic-group/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e376a3c64639b1196367cfdf85240f57bbb8391 --- /dev/null +++ b/tasks/periodic-group/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PeriodicGroup, i.e. module OAI.GroupTheory.PeriodicGroups.Main and the +# 63 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.PeriodicGroups.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PeriodicGroup" diff --git a/tasks/periodic-group/task.toml b/tasks/periodic-group/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d882513adfb98dc1567340350622e20322ba5ca --- /dev/null +++ b/tasks/periodic-group/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/periodic-group" +version = "1.0.0" +description = "Prove PeriodicGroup (openai/math family 247: An infinite finitely presented residually finite $2$-group) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PeriodicGroup.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PeriodicGroup" +family = "247" +family_title = "An infinite finitely presented residually finite $2$-group" +subject = "Group theory" +theorems = ["OAI.SourceBurnside.thm_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.PeriodicGroups.Main" +reference_modules = 63 +reference_lean_bytes = 1797133 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1008 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13317 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/periodic-group/tests/Challenge.lean b/tasks/periodic-group/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7656ab1dcbfc8aefbd95c1c68a2d9a97f8f58fd9 --- /dev/null +++ b/tasks/periodic-group/tests/Challenge.lean @@ -0,0 +1,56 @@ +import Mathlib + +namespace OAI + +universe u + +namespace SourceBurnside + +structure Root (n : ℕ) where + row : Fin n + col : Fin n + ne : row ≠ col + deriving DecidableEq + +abbrev Generator (n : ℕ) (R : Type u) := Root n × R + +def bracket {G : Type u} [Group G] (x y : G) : G := x * y * x⁻¹ * y⁻¹ + +def letter {n : ℕ} {R : Type u} (p : Root n) (a : R) : + FreeGroup (Generator n R) := FreeGroup.of (p, a) + +inductive SteinbergRel (n : ℕ) (R : Type u) [Ring R] : + FreeGroup (Generator n R) → Prop + | add (p : Root n) (a b : R) : + SteinbergRel n R (letter p (a + b) * (letter p a * letter p b)⁻¹) + | commute (p q : Root n) (h₁ : p.col ≠ q.row) (h₂ : p.row ≠ q.col) (a b : R) : + SteinbergRel n R (bracket (letter p a) (letter q b)) + | mul (i j k : Fin n) (hij : i ≠ j) (hjk : j ≠ k) (hik : i ≠ k) (a b : R) : + SteinbergRel n R + (bracket (letter ⟨i, j, hij⟩ a) (letter ⟨j, k, hjk⟩ b) * + (letter ⟨i, k, hik⟩ (a * b))⁻¹) + +def Steinberg (n : ℕ) (R : Type u) [Ring R] := + PresentedGroup {r | SteinbergRel n R r} + deriving Group + +def Periodic (G : Type u) [Group G] : Prop := ∀ g : G, ∃ m : ℕ, 0 < m ∧ g ^ m = 1 + +def MainStatement : Prop := + ∃ (R : Type) (_ : Ring R) (_ : Algebra (ZMod 2) R), + Infinite (Steinberg 12 R) ∧ Group.IsFinitelyPresented (Steinberg 12 R) ∧ + Periodic (Steinberg 12 R) + +def BurnsideStatement : Prop := + ∃ (G : Type) (_ : Group G), Infinite G ∧ Group.IsFinitelyPresented G ∧ Periodic G + +end SourceBurnside + +namespace SourceBurnside + +theorem thm_main : MainStatement ∧ BurnsideStatement := by + sorry + +end SourceBurnside + +end OAI diff --git a/tasks/periodic-group/tests/grade.py b/tasks/periodic-group/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/periodic-group/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/periodic-group/tests/task.json b/tasks/periodic-group/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2b3eeddb188490a8bb10e3d8212e49d1d6b0c303 --- /dev/null +++ b/tasks/periodic-group/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PeriodicGroup", + "comparator": { + "theorem_names": [ + "OAI.SourceBurnside.thm_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12417 +} \ No newline at end of file diff --git a/tasks/periodic-group/tests/test.sh b/tasks/periodic-group/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/periodic-group/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/periodic-tiling-three/environment/Dockerfile b/tasks/periodic-tiling-three/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/periodic-tiling-three/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/periodic-tiling-three/environment/fetch_mathlib.sh b/tasks/periodic-tiling-three/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/periodic-tiling-three/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/periodic-tiling-three/environment/lake-manifest.json b/tasks/periodic-tiling-three/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/periodic-tiling-three/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/periodic-tiling-three/environment/lakefile.lean b/tasks/periodic-tiling-three/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/periodic-tiling-three/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/periodic-tiling-three/environment/lean_setup.sh b/tasks/periodic-tiling-three/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/periodic-tiling-three/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/periodic-tiling-three/environment/pack_submission.py b/tasks/periodic-tiling-three/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/periodic-tiling-three/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/periodic-tiling-three/instruction.md b/tasks/periodic-tiling-three/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..07a1160c75fc18c3cac638f3f7b426674bb325f9 --- /dev/null +++ b/tasks/periodic-tiling-three/instruction.md @@ -0,0 +1,117 @@ +# openai/math challenge `PeriodicTilingThree` (family 155) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 155 of the release, *A counterexample to periodic tiling in dimension three* +(Combinatorics). The family as a whole: Constructs a finite translational tile in $\mathbb Z^3$ that tiles space but admits no fully periodic tiling, disproving the periodic tiling conjecture in the smallest possible lattice dimension. Its unit-cube thickening gives the same counterexample in $\mathbb R^3$, even with arbitrary real translation vectors. + +The challenge is `PeriodicTilingThree`, also at `/opt/openai-math/challenges/PeriodicTilingThree.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u + +namespace PeriodicTilingThree + +abbrev Lattice (d : ℕ) := Fin d → ℤ + +variable {G : Type u} [AddCommGroup G] + +def Tiles (F : Finset G) (A : Set G) : Prop := + Function.Bijective (fun p : ↥F × A => (p.1 : G) + (p.2 : G)) + +def Period (A : Set G) (v : G) : Prop := + ∀ x : G, x + v ∈ A ↔ x ∈ A + +def FullyPeriodic (A : Set G) : Prop := + ∃ P : AddSubgroup G, P.FiniteIndex ∧ ∀ v ∈ P, Period A v + +open MeasureTheory + +abbrev Space (d : ℕ) := Fin d → ℝ + +def castLattice {d : ℕ} : Lattice d →+ Space d where + toFun z i := (z i : ℝ) + map_zero' := by ext i; simp + map_add' z w := by ext i; simp + +def unitCube (d : ℕ) : Set (Space d) := Set.Icc 0 1 + +def Thickening {d : ℕ} (F : Finset (Lattice d)) : Set (Space d) := + {x | ∃ z ∈ F, x - castLattice z ∈ unitCube d} + +def AETiles {d : ℕ} (Ω A : Set (Space d)) : Prop := + ∀ᵐ x ∂volume, ∃! a : A, x - (a : Space d) ∈ Ω + +def latticeOfBasis {d : ℕ} (b : Module.Basis (Fin d) ℝ (Space d)) : + AddSubgroup (Space d) := (Submodule.span ℤ (Set.range b)).toAddSubgroup + +def EuclideanFullyPeriodic {d : ℕ} (A : Set (Space d)) : Prop := + ∃ b : Module.Basis (Fin d) ℝ (Space d), ∀ v ∈ latticeOfBasis b, Period A v + +def HasTileWithoutPeriodicComplement (d : ℕ) : Prop := + ∃ T : Finset (Lattice d), T.Nonempty ∧ + (∃ A : Set (Lattice d), Tiles T A) ∧ + ∀ A : Set (Lattice d), Tiles T A → ¬ FullyPeriodic A + +theorem periodic_tiling_counterexample_and_minimality : + (∃ T : Finset (Lattice 3), T.Nonempty ∧ + (∃ A : Set (Lattice 3), Tiles T A) ∧ + (∀ A : Set (Lattice 3), Tiles T A → ¬ FullyPeriodic A) ∧ + (∃ A : Set (Space 3), AETiles (Thickening T) A) ∧ + (∀ A : Set (Space 3), + AETiles (Thickening T) A → ¬ EuclideanFullyPeriodic A)) ∧ + IsLeast {d : ℕ | HasTileWithoutPeriodicComplement d} 3 := by + sorry + +end PeriodicTilingThree + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PeriodicTilingThree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PeriodicTilingThree.periodic_tiling_counterexample_and_minimality` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/periodic-tiling-three/solution/closure.txt b/tasks/periodic-tiling-three/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6c209e0b118fd39b1598791eb5d2ae28938334e2 --- /dev/null +++ b/tasks/periodic-tiling-three/solution/closure.txt @@ -0,0 +1,122 @@ +OAI.Geometry.PeriodicTiling.AETilingCountable +OAI.Geometry.PeriodicTiling.Activation +OAI.Geometry.PeriodicTiling.ActivationOffsets +OAI.Geometry.PeriodicTiling.ActivationTiles +OAI.Geometry.PeriodicTiling.ActivityWord +OAI.Geometry.PeriodicTiling.AuxiliaryCubes +OAI.Geometry.PeriodicTiling.BlockActivationInverse +OAI.Geometry.PeriodicTiling.BoundedDifferences +OAI.Geometry.PeriodicTiling.CenterFiniteness +OAI.Geometry.PeriodicTiling.ChannelDigitBlocks +OAI.Geometry.PeriodicTiling.CircleWeylCriterion +OAI.Geometry.PeriodicTiling.ClosedBoxRounding +OAI.Geometry.PeriodicTiling.ClosedCoverChains +OAI.Geometry.PeriodicTiling.CommonModel +OAI.Geometry.PeriodicTiling.CommonSeedOutputs +OAI.Geometry.PeriodicTiling.CommonSolution +OAI.Geometry.PeriodicTiling.ComponentTargets +OAI.Geometry.PeriodicTiling.ConfigurationDifferenceReduction +OAI.Geometry.PeriodicTiling.ConfigurationDifferences +OAI.Geometry.PeriodicTiling.ConstituentAssembly +OAI.Geometry.PeriodicTiling.ConstituentGeometry +OAI.Geometry.PeriodicTiling.ConstraintCycles +OAI.Geometry.PeriodicTiling.CosetParts +OAI.Geometry.PeriodicTiling.CosetPeriodicity +OAI.Geometry.PeriodicTiling.Counterexample +OAI.Geometry.PeriodicTiling.CycleTests +OAI.Geometry.PeriodicTiling.CyclicCRT +OAI.Geometry.PeriodicTiling.CyclicCoordinates +OAI.Geometry.PeriodicTiling.CyclicCounterexample +OAI.Geometry.PeriodicTiling.CyclicFactorCRT +OAI.Geometry.PeriodicTiling.CyclicQuotient +OAI.Geometry.PeriodicTiling.CyclicShear +OAI.Geometry.PeriodicTiling.CyclicStack +OAI.Geometry.PeriodicTiling.CyclicSystemStacking +OAI.Geometry.PeriodicTiling.CyclicTypes +OAI.Geometry.PeriodicTiling.Dependence +OAI.Geometry.PeriodicTiling.DirectionalLimits +OAI.Geometry.PeriodicTiling.DirectionalSlices +OAI.Geometry.PeriodicTiling.DisjointSuccessorPairs +OAI.Geometry.PeriodicTiling.EncodedSystem +OAI.Geometry.PeriodicTiling.EncodedSystemObstruction +OAI.Geometry.PeriodicTiling.EncodingParameters +OAI.Geometry.PeriodicTiling.EncodingPrimeSelection +OAI.Geometry.PeriodicTiling.EuclideanBasic +OAI.Geometry.PeriodicTiling.FiniteCylinder +OAI.Geometry.PeriodicTiling.FiniteDifferencePolynomial +OAI.Geometry.PeriodicTiling.FiniteEventUnion +OAI.Geometry.PeriodicTiling.FiniteMasks +OAI.Geometry.PeriodicTiling.FinitePairCounting +OAI.Geometry.PeriodicTiling.FinitePairRatio +OAI.Geometry.PeriodicTiling.ForwardDifference +OAI.Geometry.PeriodicTiling.FullDifferenceBound +OAI.Geometry.PeriodicTiling.FullDifferencePartition +OAI.Geometry.PeriodicTiling.GraphTests +OAI.Geometry.PeriodicTiling.GridRigidity +OAI.Geometry.PeriodicTiling.IntegerMatrixIndex +OAI.Geometry.PeriodicTiling.LabeledDigitBlocks +OAI.Geometry.PeriodicTiling.LastDigit +OAI.Geometry.PeriodicTiling.LatticeDescent +OAI.Geometry.PeriodicTiling.LatticeDimensions +OAI.Geometry.PeriodicTiling.LatticePeriodicity +OAI.Geometry.PeriodicTiling.LatticeThickening +OAI.Geometry.PeriodicTiling.LowerDimensions +OAI.Geometry.PeriodicTiling.Main +OAI.Geometry.PeriodicTiling.MarkedCell +OAI.Geometry.PeriodicTiling.MarkedTile +OAI.Geometry.PeriodicTiling.MarkedTileDescent +OAI.Geometry.PeriodicTiling.MarkedTileExistence +OAI.Geometry.PeriodicTiling.Model +OAI.Geometry.PeriodicTiling.OneDimensional +OAI.Geometry.PeriodicTiling.OneDimensionalLattice +OAI.Geometry.PeriodicTiling.OrdinaryActivation +OAI.Geometry.PeriodicTiling.OrdinaryModel +OAI.Geometry.PeriodicTiling.PeriodicPartGrouping +OAI.Geometry.PeriodicTiling.PeriodicRegion +OAI.Geometry.PeriodicTiling.PeriodicVolume +OAI.Geometry.PeriodicTiling.PeriodicVolumeMass +OAI.Geometry.PeriodicTiling.PeriodicVolumeOrbits +OAI.Geometry.PeriodicTiling.PlanarPeriodicity +OAI.Geometry.PeriodicTiling.PlaneLattices +OAI.Geometry.PeriodicTiling.PolynomialShiftDifference +OAI.Geometry.PeriodicTiling.PolynomialWeyl +OAI.Geometry.PeriodicTiling.PrimeDifferencePairs +OAI.Geometry.PeriodicTiling.QuotientTiling +OAI.Geometry.PeriodicTiling.RationalPolynomialPeriod +OAI.Geometry.PeriodicTiling.ResidueCoordinates +OAI.Geometry.PeriodicTiling.ResidueCountBound +OAI.Geometry.PeriodicTiling.ResidueLiftPairs +OAI.Geometry.PeriodicTiling.ResidueTransversal +OAI.Geometry.PeriodicTiling.RigidSectionGeometry +OAI.Geometry.PeriodicTiling.ScalarAverage +OAI.Geometry.PeriodicTiling.ScalarPolynomialPeriodicity +OAI.Geometry.PeriodicTiling.ScalarVanDerCorput +OAI.Geometry.PeriodicTiling.SeedSymbols +OAI.Geometry.PeriodicTiling.SeparatedCenters +OAI.Geometry.PeriodicTiling.SharedSeedInactive +OAI.Geometry.PeriodicTiling.SharedSeedInverse +OAI.Geometry.PeriodicTiling.SharedSeedLabelEquiv +OAI.Geometry.PeriodicTiling.SharedSeedLabels +OAI.Geometry.PeriodicTiling.SharedSeedRegions +OAI.Geometry.PeriodicTiling.SharedSeedSizeTransport +OAI.Geometry.PeriodicTiling.ShiftMultiplicity +OAI.Geometry.PeriodicTiling.Stacking +OAI.Geometry.PeriodicTiling.StackingContributions +OAI.Geometry.PeriodicTiling.SystemObstruction +OAI.Geometry.PeriodicTiling.ThreeDimensionalTransfer +OAI.Geometry.PeriodicTiling.ThreeDimensions +OAI.Geometry.PeriodicTiling.TileDilation +OAI.Geometry.PeriodicTiling.TilesRegion +OAI.Geometry.PeriodicTiling.TilingBasic +OAI.Geometry.PeriodicTiling.TilingTranslation +OAI.Geometry.PeriodicTiling.TilingTransport +OAI.Geometry.PeriodicTiling.VoxelCubeMeasure +OAI.Geometry.PeriodicTiling.VoxelGeometry +OAI.Geometry.PeriodicTiling.VoxelMeasure +OAI.Geometry.PeriodicTiling.WeakPeriodicity +OAI.Geometry.PeriodicTiling.WordAffine +OAI.Geometry.PeriodicTiling.WordAffineAlgebra +OAI.Geometry.PeriodicTiling.WordAffineCount +OAI.Geometry.PeriodicTiling.WordAffineGeometry +OAI.Geometry.PeriodicTiling.WordObstruction +OAI.Geometry.PeriodicTiling.WordRule diff --git a/tasks/periodic-tiling-three/solution/reference.py b/tasks/periodic-tiling-three/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/periodic-tiling-three/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/periodic-tiling-three/solution/solve.sh b/tasks/periodic-tiling-three/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8adeb07a86bc3ac93c8b84d48bed22dd9b385bce --- /dev/null +++ b/tasks/periodic-tiling-three/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PeriodicTilingThree, i.e. module OAI.Geometry.PeriodicTiling.Main and the +# 122 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.PeriodicTiling.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PeriodicTilingThree" diff --git a/tasks/periodic-tiling-three/task.toml b/tasks/periodic-tiling-three/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..381a763953db41863cc607173568ae0b8f822021 --- /dev/null +++ b/tasks/periodic-tiling-three/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/periodic-tiling-three" +version = "1.0.0" +description = "Prove PeriodicTilingThree (openai/math family 155: A counterexample to periodic tiling in dimension three) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PeriodicTilingThree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PeriodicTilingThree" +family = "155" +family_title = "A counterexample to periodic tiling in dimension three" +subject = "Combinatorics" +theorems = ["OAI.PeriodicTilingThree.periodic_tiling_counterexample_and_minimality"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.PeriodicTiling.Main" +reference_modules = 122 +reference_lean_bytes = 661551 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 928 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12295 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/periodic-tiling-three/tests/Challenge.lean b/tasks/periodic-tiling-three/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9eb75b99b57afe0f7a9e24035095d9c9015acb52 --- /dev/null +++ b/tasks/periodic-tiling-three/tests/Challenge.lean @@ -0,0 +1,66 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u + +namespace PeriodicTilingThree + +abbrev Lattice (d : ℕ) := Fin d → ℤ + +variable {G : Type u} [AddCommGroup G] + +def Tiles (F : Finset G) (A : Set G) : Prop := + Function.Bijective (fun p : ↥F × A => (p.1 : G) + (p.2 : G)) + +def Period (A : Set G) (v : G) : Prop := + ∀ x : G, x + v ∈ A ↔ x ∈ A + +def FullyPeriodic (A : Set G) : Prop := + ∃ P : AddSubgroup G, P.FiniteIndex ∧ ∀ v ∈ P, Period A v + +open MeasureTheory + +abbrev Space (d : ℕ) := Fin d → ℝ + +def castLattice {d : ℕ} : Lattice d →+ Space d where + toFun z i := (z i : ℝ) + map_zero' := by ext i; simp + map_add' z w := by ext i; simp + +def unitCube (d : ℕ) : Set (Space d) := Set.Icc 0 1 + +def Thickening {d : ℕ} (F : Finset (Lattice d)) : Set (Space d) := + {x | ∃ z ∈ F, x - castLattice z ∈ unitCube d} + +def AETiles {d : ℕ} (Ω A : Set (Space d)) : Prop := + ∀ᵐ x ∂volume, ∃! a : A, x - (a : Space d) ∈ Ω + +def latticeOfBasis {d : ℕ} (b : Module.Basis (Fin d) ℝ (Space d)) : + AddSubgroup (Space d) := (Submodule.span ℤ (Set.range b)).toAddSubgroup + +def EuclideanFullyPeriodic {d : ℕ} (A : Set (Space d)) : Prop := + ∃ b : Module.Basis (Fin d) ℝ (Space d), ∀ v ∈ latticeOfBasis b, Period A v + +def HasTileWithoutPeriodicComplement (d : ℕ) : Prop := + ∃ T : Finset (Lattice d), T.Nonempty ∧ + (∃ A : Set (Lattice d), Tiles T A) ∧ + ∀ A : Set (Lattice d), Tiles T A → ¬ FullyPeriodic A + +theorem periodic_tiling_counterexample_and_minimality : + (∃ T : Finset (Lattice 3), T.Nonempty ∧ + (∃ A : Set (Lattice 3), Tiles T A) ∧ + (∀ A : Set (Lattice 3), Tiles T A → ¬ FullyPeriodic A) ∧ + (∃ A : Set (Space 3), AETiles (Thickening T) A) ∧ + (∀ A : Set (Space 3), + AETiles (Thickening T) A → ¬ EuclideanFullyPeriodic A)) ∧ + IsLeast {d : ℕ | HasTileWithoutPeriodicComplement d} 3 := by + sorry + +end PeriodicTilingThree + +end + +end OAI diff --git a/tasks/periodic-tiling-three/tests/grade.py b/tasks/periodic-tiling-three/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/periodic-tiling-three/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/periodic-tiling-three/tests/task.json b/tasks/periodic-tiling-three/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..932cf025aca499460aed8ad33f7a1340d46e79c4 --- /dev/null +++ b/tasks/periodic-tiling-three/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PeriodicTilingThree", + "comparator": { + "theorem_names": [ + "OAI.PeriodicTilingThree.periodic_tiling_counterexample_and_minimality" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11395 +} \ No newline at end of file diff --git a/tasks/periodic-tiling-three/tests/test.sh b/tasks/periodic-tiling-three/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/periodic-tiling-three/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/permanent-cubic/environment/Dockerfile b/tasks/permanent-cubic/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/permanent-cubic/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/permanent-cubic/environment/fetch_mathlib.sh b/tasks/permanent-cubic/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/permanent-cubic/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/permanent-cubic/environment/lake-manifest.json b/tasks/permanent-cubic/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/permanent-cubic/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/permanent-cubic/environment/lakefile.lean b/tasks/permanent-cubic/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/permanent-cubic/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/permanent-cubic/environment/lean_setup.sh b/tasks/permanent-cubic/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/permanent-cubic/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/permanent-cubic/environment/pack_submission.py b/tasks/permanent-cubic/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/permanent-cubic/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/permanent-cubic/instruction.md b/tasks/permanent-cubic/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..156a0274940db11ed761abbfe9903287279b9dc3 --- /dev/null +++ b/tasks/permanent-cubic/instruction.md @@ -0,0 +1,93 @@ +# openai/math challenge `PermanentCubic` (family 108) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 108 of the release, *A cubic permanent–determinant lower bound* +(Theoretical computer science). The family as a whole: Proves an $\Omega(n^3)$ lower bound for the border determinantal complexity of the $n\times n$ permanent over $\mathbb C$. Even coefficientwise limits of determinants of affine-linear matrices require matrix size at least $cn^3$, for an absolute $c>0$ and all sufficiently large $n$; the same bound therefore holds for exact representations. + +The challenge is `PermanentCubic`, also at `/opt/openai-math/challenges/PermanentCubic.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PermanentBorder + +open Filter +open scoped Topology + +abbrev Variables (m : ℕ) := Fin m × Fin m +abbrev Poly (σ : Type*) := MvPolynomial σ ℂ + +noncomputable def permanentPolynomial (m : ℕ) : Poly (Variables m) := + ∑ τ : Equiv.Perm (Fin m), ∏ i : Fin m, MvPolynomial.X (i, τ i) + +noncomputable def affineMatrixPolynomial {σ : Type*} [Fintype σ] (n : ℕ) + (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ) : Poly σ := + Matrix.det (fun i j => MvPolynomial.C (A₀ i j) + + ∑ v : σ, MvPolynomial.C (A v i j) * MvPolynomial.X v) + +def HasBorderDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : ℕ → Matrix (Fin n) (Fin n) ℂ) + (A : ℕ → σ → Matrix (Fin n) (Fin n) ℂ), + ∀ d : σ →₀ ℕ, Tendsto + (fun j => (affineMatrixPolynomial n (A₀ j) (A j)).coeff d) + atTop (𝓝 (p.coeff d)) + +def HasExactDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ), affineMatrixPolynomial n A₀ A = p + +theorem permanent_cubic_lower_bounds : + (∀ (m n : ℕ), 1408 ≤ m → HasBorderDeterminant n (permanentPolynomial m) → + (m : ℝ)^3 / (5529600 * Real.exp 1) ≤ (n : ℝ)) ∧ + (∀ (m n : ℕ), 1408 ≤ m → HasExactDeterminant n (permanentPolynomial m) → + (m : ℝ)^3 / (5529600 * Real.exp 1) ≤ (n : ℝ)) := by + sorry + +end PermanentBorder + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PermanentCubic.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PermanentBorder.permanent_cubic_lower_bounds` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/permanent-cubic/solution/closure.txt b/tasks/permanent-cubic/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e684e86be01720df9a6d27f5c7e3c4c1ebb4400b --- /dev/null +++ b/tasks/permanent-cubic/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Algebra.Determinantal.AdjugateNormalForm +OAI.Algebra.Determinantal.AffineSelectors +OAI.Algebra.Determinantal.BilinearCounts +OAI.Algebra.Determinantal.BorderClosure +OAI.Algebra.Determinantal.BorderPolars +OAI.Algebra.Determinantal.BranchConductor +OAI.Algebra.Determinantal.Centralizers +OAI.Algebra.Determinantal.ConditionalBound +OAI.Algebra.Determinantal.ConductorBounds +OAI.Algebra.Determinantal.ConductorDimension +OAI.Algebra.Determinantal.ConductorDuality +OAI.Algebra.Determinantal.ConductorLocalization +OAI.Algebra.Determinantal.CoordinateFields +OAI.Algebra.Determinantal.CurveParameters +OAI.Algebra.Determinantal.DegreeBounds +OAI.Algebra.Determinantal.DeterminantFields +OAI.Algebra.Determinantal.FiberDimension +OAI.Algebra.Determinantal.FilteredPlane +OAI.Algebra.Determinantal.GateCoefficients +OAI.Algebra.Determinantal.Gates +OAI.Algebra.Determinantal.GenericPolars +OAI.Algebra.Determinantal.Gradients +OAI.Algebra.Determinantal.HalfPolynomials +OAI.Algebra.Determinantal.HomogeneousPadding +OAI.Algebra.Determinantal.InitialForm +OAI.Algebra.Determinantal.KernelCharts +OAI.Algebra.Determinantal.LinearForms +OAI.Algebra.Determinantal.LocalDerivations +OAI.Algebra.Determinantal.Main +OAI.Algebra.Determinantal.Model +OAI.Algebra.Determinantal.Monogenic +OAI.Algebra.Determinantal.Multigraded +OAI.Algebra.Determinantal.Nilpotents +OAI.Algebra.Determinantal.Normalization +OAI.Algebra.Determinantal.PencilSeparability +OAI.Algebra.Determinantal.PlaneHilbert +OAI.Algebra.Determinantal.PointBounds +OAI.Algebra.Determinantal.ProjectiveCounts +OAI.Algebra.Determinantal.PunctualCharts +OAI.Algebra.Determinantal.QuotientFields +OAI.Algebra.Determinantal.RankTransfer +OAI.Algebra.Determinantal.RegularSections +OAI.Algebra.Determinantal.RowIdeals +OAI.Algebra.Determinantal.SchurDifferentials +OAI.Algebra.Determinantal.SchurLifts +OAI.Algebra.Determinantal.Selector +OAI.Algebra.Determinantal.SingularValues +OAI.Algebra.Determinantal.SliceCertificates +OAI.Algebra.Determinantal.SmoothSlices +OAI.Algebra.Determinantal.Transcendence +OAI.Algebra.Determinantal.WildParameters diff --git a/tasks/permanent-cubic/solution/reference.py b/tasks/permanent-cubic/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/permanent-cubic/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/permanent-cubic/solution/solve.sh b/tasks/permanent-cubic/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..305b964b843c09bee3d844e2445a6be85e089963 --- /dev/null +++ b/tasks/permanent-cubic/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PermanentCubic, i.e. module OAI.Algebra.Determinantal.Main and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.Determinantal.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PermanentCubic" diff --git a/tasks/permanent-cubic/task.toml b/tasks/permanent-cubic/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6836d2041fc2b0c194ac93ed7ea744f83a4d718c --- /dev/null +++ b/tasks/permanent-cubic/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/permanent-cubic" +version = "1.0.0" +description = "Prove PermanentCubic (openai/math family 108: A cubic permanent–determinant lower bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PermanentCubic.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PermanentCubic" +family = "108" +family_title = "A cubic permanent–determinant lower bound" +subject = "Theoretical computer science" +theorems = ["OAI.PermanentBorder.permanent_cubic_lower_bounds"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.Determinantal.Main" +reference_modules = 51 +reference_lean_bytes = 915904 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1031 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12524 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/permanent-cubic/tests/Challenge.lean b/tasks/permanent-cubic/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e5b566f18fe7a7789ffc42f1eb00fcc1735d2f87 --- /dev/null +++ b/tasks/permanent-cubic/tests/Challenge.lean @@ -0,0 +1,42 @@ +import Mathlib + +namespace OAI + +namespace PermanentBorder + +open Filter +open scoped Topology + +abbrev Variables (m : ℕ) := Fin m × Fin m +abbrev Poly (σ : Type*) := MvPolynomial σ ℂ + +noncomputable def permanentPolynomial (m : ℕ) : Poly (Variables m) := + ∑ τ : Equiv.Perm (Fin m), ∏ i : Fin m, MvPolynomial.X (i, τ i) + +noncomputable def affineMatrixPolynomial {σ : Type*} [Fintype σ] (n : ℕ) + (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ) : Poly σ := + Matrix.det (fun i j => MvPolynomial.C (A₀ i j) + + ∑ v : σ, MvPolynomial.C (A v i j) * MvPolynomial.X v) + +def HasBorderDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : ℕ → Matrix (Fin n) (Fin n) ℂ) + (A : ℕ → σ → Matrix (Fin n) (Fin n) ℂ), + ∀ d : σ →₀ ℕ, Tendsto + (fun j => (affineMatrixPolynomial n (A₀ j) (A j)).coeff d) + atTop (𝓝 (p.coeff d)) + +def HasExactDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ), affineMatrixPolynomial n A₀ A = p + +theorem permanent_cubic_lower_bounds : + (∀ (m n : ℕ), 1408 ≤ m → HasBorderDeterminant n (permanentPolynomial m) → + (m : ℝ)^3 / (5529600 * Real.exp 1) ≤ (n : ℝ)) ∧ + (∀ (m n : ℕ), 1408 ≤ m → HasExactDeterminant n (permanentPolynomial m) → + (m : ℝ)^3 / (5529600 * Real.exp 1) ≤ (n : ℝ)) := by + sorry + +end PermanentBorder + +end OAI diff --git a/tasks/permanent-cubic/tests/grade.py b/tasks/permanent-cubic/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/permanent-cubic/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/permanent-cubic/tests/task.json b/tasks/permanent-cubic/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2bc2829640ac778a151563d45c3cc04546a778af --- /dev/null +++ b/tasks/permanent-cubic/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PermanentCubic", + "comparator": { + "theorem_names": [ + "OAI.PermanentBorder.permanent_cubic_lower_bounds" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11624 +} \ No newline at end of file diff --git a/tasks/permanent-cubic/tests/test.sh b/tasks/permanent-cubic/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/permanent-cubic/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/petty-projection-volume/environment/Dockerfile b/tasks/petty-projection-volume/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/petty-projection-volume/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/petty-projection-volume/environment/fetch_mathlib.sh b/tasks/petty-projection-volume/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/petty-projection-volume/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/petty-projection-volume/environment/lake-manifest.json b/tasks/petty-projection-volume/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/petty-projection-volume/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/petty-projection-volume/environment/lakefile.lean b/tasks/petty-projection-volume/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/petty-projection-volume/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/petty-projection-volume/environment/lean_setup.sh b/tasks/petty-projection-volume/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/petty-projection-volume/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/petty-projection-volume/environment/pack_submission.py b/tasks/petty-projection-volume/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/petty-projection-volume/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/petty-projection-volume/instruction.md b/tasks/petty-projection-volume/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..14c9540fc29da1618b94abbf367a0f664b963f85 --- /dev/null +++ b/tasks/petty-projection-volume/instruction.md @@ -0,0 +1,105 @@ +# openai/math challenge `PettyProjectionVolume` (family 088) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 088 of the release, *Petty's projection-volume conjecture and simplex counterexamples* +(Convex and metric geometry). The family as a whole: Proves Petty's projection-volume conjecture in the remaining dimensions $n\ge4$: ellipsoids uniquely minimize projection-body volume at fixed body volume. Also establishes the full Lutwak–Petty projection inequalities. In contrast, products of simplices exceed Brannen's proposed simplex maximum for normalized projection-body volume by an exponential factor in every sufficiently large dimension. + +The challenge is `PettyProjectionVolume`, also at `/opt/openai-math/challenges/PettyProjectionVolume.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace PettyProjection + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def IsConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def unitBall (n : ℕ) : Set (Space n) := Metric.closedBall 0 1 + +def kappa (n : ℕ) : ℝ := volume.real (unitBall n) + +def perpendicular {n : ℕ} (u : Space n) : Submodule ℝ (Space n) := + (Submodule.span ℝ {u})ᗮ + +/-- Volume in the induced Euclidean structure on the orthogonal hyperplane. -/ +def shadowVolume {n : ℕ} (K : Set (Space n)) (u : Space n) : ℝ := + (volume : Measure (perpendicular u)).real + ((perpendicular u).orthogonalProjectionOnto '' K) + +/-- The body with support function equal to the volumes of orthogonal shadows, +expressed as its defining intersection of supporting half-spaces. -/ +def projectionBody {n : ℕ} (K : Set (Space n)) : Set (Space n) := + {x | ∀ u : Space n, ‖u‖ = 1 → ⟪u, x⟫ ≤ shadowVolume K u} + +def projectionRatio {n : ℕ} (K : Set (Space n)) : ℝ := + volume.real (projectionBody K) / volume.real K ^ (n - 1) + +def pettyConstant (n : ℕ) : ℝ := + kappa (n - 1) ^ n * kappa n ^ (2 - (n : ℤ)) + +def IsEllipsoid {n : ℕ} (K : Set (Space n)) : Prop := + ∃ (a : Space n) (T : Space n ≃ₗ[ℝ] Space n), + K = (fun x => a + T x) '' unitBall n + +/-- The exact unrestricted inequality and its global equality characterization. +-/ +theorem petty_projection_volume (n : ℕ) (hn : 4 ≤ n) + (K : Set (Space n)) (hK : IsConvexBody K) : + pettyConstant n ≤ projectionRatio K ∧ + (projectionRatio K = pettyConstant n ↔ IsEllipsoid K) := by + sorry + +end PettyProjection +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PettyProjectionVolume.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PettyProjection.petty_projection_volume` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/petty-projection-volume/solution/closure.txt b/tasks/petty-projection-volume/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e02c6df9f62fd61c4365433cbf9eda028fe969dd --- /dev/null +++ b/tasks/petty-projection-volume/solution/closure.txt @@ -0,0 +1,33 @@ +OAI.Geometry.ProjectionBodies.AffineCovariance +OAI.Geometry.ProjectionBodies.AffinePosition +OAI.Geometry.ProjectionBodies.BilinearEquality +OAI.Geometry.ProjectionBodies.Brouwer +OAI.Geometry.ProjectionBodies.BrunnMinkowski +OAI.Geometry.ProjectionBodies.CosineCalculus +OAI.Geometry.ProjectionBodies.CosineSpectrum +OAI.Geometry.ProjectionBodies.FixedPointCalculus +OAI.Geometry.ProjectionBodies.GaussianMeasures +OAI.Geometry.ProjectionBodies.Homothety +OAI.Geometry.ProjectionBodies.Main +OAI.Geometry.ProjectionBodies.Model +OAI.Geometry.ProjectionBodies.NormCurvature +OAI.Geometry.ProjectionBodies.NormEstimates +OAI.Geometry.ProjectionBodies.NormRigidity +OAI.Geometry.ProjectionBodies.Normalization +OAI.Geometry.ProjectionBodies.PositionMatrices +OAI.Geometry.ProjectionBodies.RankContinuity +OAI.Geometry.ProjectionBodies.RelativeGauges +OAI.Geometry.ProjectionBodies.ScalarBounds +OAI.Geometry.ProjectionBodies.ScalarCalculus +OAI.Geometry.ProjectionBodies.SeminormBounds +OAI.Geometry.ProjectionBodies.ShadowSlices +OAI.Geometry.ProjectionBodies.SignCalculus +OAI.Geometry.ProjectionBodies.SignSpectrum +OAI.Geometry.ProjectionBodies.SliceTransport +OAI.Geometry.ProjectionBodies.SphericalCore +OAI.Geometry.ProjectionBodies.SphericalGap +OAI.Geometry.ProjectionBodies.Support +OAI.Geometry.ProjectionBodies.SupportMeasures +OAI.Geometry.ProjectionBodies.VariationalMinimizers +OAI.Geometry.ProjectionBodies.VariationalRepresentation +OAI.Geometry.ProjectionBodies.WulffVariation diff --git a/tasks/petty-projection-volume/solution/reference.py b/tasks/petty-projection-volume/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/petty-projection-volume/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/petty-projection-volume/solution/solve.sh b/tasks/petty-projection-volume/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ce209c39f3fc59926cd08699f194b5a0a86a1d6f --- /dev/null +++ b/tasks/petty-projection-volume/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PettyProjectionVolume, i.e. module OAI.Geometry.ProjectionBodies.Main and the +# 33 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.ProjectionBodies.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PettyProjectionVolume" diff --git a/tasks/petty-projection-volume/task.toml b/tasks/petty-projection-volume/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b3ce940f79fc8d6f861f07a26905d9a7dc2afb8e --- /dev/null +++ b/tasks/petty-projection-volume/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/petty-projection-volume" +version = "1.0.0" +description = "Prove PettyProjectionVolume (openai/math family 088: Petty's projection-volume conjecture and simplex counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PettyProjectionVolume.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PettyProjectionVolume" +family = "088" +family_title = "Petty's projection-volume conjecture and simplex counterexamples" +subject = "Convex and metric geometry" +theorems = ["OAI.PettyProjection.petty_projection_volume"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.ProjectionBodies.Main" +reference_modules = 33 +reference_lean_bytes = 662308 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 979 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12296 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/petty-projection-volume/tests/Challenge.lean b/tasks/petty-projection-volume/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..680a631459c84863752d24ea9ad899e069de69f8 --- /dev/null +++ b/tasks/petty-projection-volume/tests/Challenge.lean @@ -0,0 +1,54 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace PettyProjection + +abbrev Space (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def IsConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def unitBall (n : ℕ) : Set (Space n) := Metric.closedBall 0 1 + +def kappa (n : ℕ) : ℝ := volume.real (unitBall n) + +def perpendicular {n : ℕ} (u : Space n) : Submodule ℝ (Space n) := + (Submodule.span ℝ {u})ᗮ + +/-- Volume in the induced Euclidean structure on the orthogonal hyperplane. -/ +def shadowVolume {n : ℕ} (K : Set (Space n)) (u : Space n) : ℝ := + (volume : Measure (perpendicular u)).real + ((perpendicular u).orthogonalProjectionOnto '' K) + +/-- The body with support function equal to the volumes of orthogonal shadows, +expressed as its defining intersection of supporting half-spaces. -/ +def projectionBody {n : ℕ} (K : Set (Space n)) : Set (Space n) := + {x | ∀ u : Space n, ‖u‖ = 1 → ⟪u, x⟫ ≤ shadowVolume K u} + +def projectionRatio {n : ℕ} (K : Set (Space n)) : ℝ := + volume.real (projectionBody K) / volume.real K ^ (n - 1) + +def pettyConstant (n : ℕ) : ℝ := + kappa (n - 1) ^ n * kappa n ^ (2 - (n : ℤ)) + +def IsEllipsoid {n : ℕ} (K : Set (Space n)) : Prop := + ∃ (a : Space n) (T : Space n ≃ₗ[ℝ] Space n), + K = (fun x => a + T x) '' unitBall n + +/-- The exact unrestricted inequality and its global equality characterization. +-/ +theorem petty_projection_volume (n : ℕ) (hn : 4 ≤ n) + (K : Set (Space n)) (hK : IsConvexBody K) : + pettyConstant n ≤ projectionRatio K ∧ + (projectionRatio K = pettyConstant n ↔ IsEllipsoid K) := by + sorry + +end PettyProjection +end + +end OAI diff --git a/tasks/petty-projection-volume/tests/grade.py b/tasks/petty-projection-volume/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/petty-projection-volume/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/petty-projection-volume/tests/task.json b/tasks/petty-projection-volume/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6586724c7d70d1c751174c16e6b8697b612279af --- /dev/null +++ b/tasks/petty-projection-volume/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PettyProjectionVolume", + "comparator": { + "theorem_names": [ + "OAI.PettyProjection.petty_projection_volume" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11396 +} \ No newline at end of file diff --git a/tasks/petty-projection-volume/tests/test.sh b/tasks/petty-projection-volume/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/petty-projection-volume/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/pi-exponent/environment/Dockerfile b/tasks/pi-exponent/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/pi-exponent/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/pi-exponent/environment/fetch_mathlib.sh b/tasks/pi-exponent/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/pi-exponent/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/pi-exponent/environment/lake-manifest.json b/tasks/pi-exponent/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/pi-exponent/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/pi-exponent/environment/lakefile.lean b/tasks/pi-exponent/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/pi-exponent/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/pi-exponent/environment/lean_setup.sh b/tasks/pi-exponent/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/pi-exponent/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/pi-exponent/environment/pack_submission.py b/tasks/pi-exponent/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/pi-exponent/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/pi-exponent/instruction.md b/tasks/pi-exponent/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8e36250cbd02e14f9bd3ec9e4dc34e2d3ffa2f5 --- /dev/null +++ b/tasks/pi-exponent/instruction.md @@ -0,0 +1,70 @@ +# openai/math challenge `PiExponent` (family 017) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 017 of the release, *The irrationality exponent of $\pi$ is $2$* +(Number theory). The family as a whole: Proves that the irrationality exponent of $\pi$ is exactly $2$: for every $\varepsilon>0$ and all sufficiently large denominators $q$, every rational $p/q$ satisfies $|\pi-p/q|\ge q^{-2-\varepsilon}$. This also proves convergence of the Flint–Hills series $\sum_{n\ge1}1/(n^3\sin^2 n)$, with angles in radians. + +The challenge is `PiExponent`, also at `/opt/openai-math/challenges/PiExponent.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PiExponent + +theorem main : + (∀ ν : ℝ, 2 < ν → ∃ Q : ℤ, 2 ≤ Q ∧ + ∀ p q : ℤ, Q ≤ q → + (q : ℝ) ^ (-ν) ≤ |Real.pi - (p : ℝ) / (q : ℝ)|) ∧ + sSup {ν : ℝ | 0 < ν ∧ + Set.Infinite {r : ℚ | 2 ≤ r.den ∧ + 0 < |Real.pi - (r : ℝ)| ∧ + |Real.pi - (r : ℝ)| < (r.den : ℝ) ^ (-ν)}} = 2 := by + sorry + +end PiExponent + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PiExponent.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PiExponent.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/pi-exponent/solution/closure.txt b/tasks/pi-exponent/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7a389e187909d100a43b4e63fa1fe15641a86024 --- /dev/null +++ b/tasks/pi-exponent/solution/closure.txt @@ -0,0 +1,869 @@ +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleBlowupAmple +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleBlowupGeometry +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleBlowupMargin +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleBlowupPolarization +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleCurveModelDegrees +OAI.NumberTheory.PiExponent.Ampleness.AdmissibleJetAmpleness +OAI.NumberTheory.PiExponent.Ampleness.AffineBlowupUniversal +OAI.NumberTheory.PiExponent.Ampleness.AffineFunctionFieldCompatibility +OAI.NumberTheory.PiExponent.Ampleness.AffineReesCanonicalRecovery +OAI.NumberTheory.PiExponent.Ampleness.AmpleAllPowersGeneration +OAI.NumberTheory.PiExponent.Ampleness.AmpleCommonDegree +OAI.NumberTheory.PiExponent.Ampleness.AmpleCurveDegreePositive +OAI.NumberTheory.PiExponent.Ampleness.AmpleDivisorDimension +OAI.NumberTheory.PiExponent.Ampleness.AmpleDivisorDimensionBase +OAI.NumberTheory.PiExponent.Ampleness.AmpleFiniteProjectiveEmbedding +OAI.NumberTheory.PiExponent.Ampleness.AmpleFromCover +OAI.NumberTheory.PiExponent.Ampleness.AmpleGeneratedTensor +OAI.NumberTheory.PiExponent.Ampleness.AmpleGlobalGeneration +OAI.NumberTheory.PiExponent.Ampleness.AmpleIso +OAI.NumberTheory.PiExponent.Ampleness.AmplePositiveTwist +OAI.NumberTheory.PiExponent.Ampleness.AmpleProjectiveSections +OAI.NumberTheory.PiExponent.Ampleness.AmpleSlopeAlgebra +OAI.NumberTheory.PiExponent.Ampleness.AmpleSlopeTopology +OAI.NumberTheory.PiExponent.Ampleness.AmpleThresholdPolynomial +OAI.NumberTheory.PiExponent.Ampleness.BlowupAffineSections +OAI.NumberTheory.PiExponent.Ampleness.BlowupAmpleTwist +OAI.NumberTheory.PiExponent.Ampleness.BlowupComplement +OAI.NumberTheory.PiExponent.Ampleness.BlowupCurveMargin +OAI.NumberTheory.PiExponent.Ampleness.BlowupIdeal +OAI.NumberTheory.PiExponent.Ampleness.BlowupJetReesReduction +OAI.NumberTheory.PiExponent.Ampleness.BlowupJetSurjectivity +OAI.NumberTheory.PiExponent.Ampleness.BlowupJetSurjectivityComplete +OAI.NumberTheory.PiExponent.Ampleness.BlowupPresentationRestriction +OAI.NumberTheory.PiExponent.Ampleness.BlowupProperIntegral +OAI.NumberTheory.PiExponent.Ampleness.BlowupSchemeExt +OAI.NumberTheory.PiExponent.Ampleness.BlowupUniversalBaseChange +OAI.NumberTheory.PiExponent.Ampleness.ClosedAmpleBaseChange +OAI.NumberTheory.PiExponent.Ampleness.ClosedAmpleRestriction +OAI.NumberTheory.PiExponent.Ampleness.CoherentAffineFinite +OAI.NumberTheory.PiExponent.Ampleness.ComponentAmpleDescent +OAI.NumberTheory.PiExponent.Ampleness.ComponentAmpleDescentCover +OAI.NumberTheory.PiExponent.Ampleness.ComponentAmpleDescentIdeal +OAI.NumberTheory.PiExponent.Ampleness.ComponentAmpleDescentLocal +OAI.NumberTheory.PiExponent.Ampleness.ComponentAmpleDescentSupported +OAI.NumberTheory.PiExponent.Ampleness.CurveBlowupImage +OAI.NumberTheory.PiExponent.Ampleness.CurveBlowupImageBase +OAI.NumberTheory.PiExponent.Ampleness.CurveNormalizationPolarization +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalAffineChart +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalAffineChartRestriction +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalChartPullbackValue +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalCurveDegree +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalPowerPresentation +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalPowerSections +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalRecoveryMap +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalRecoveryTwist +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalRepresentedOpaque +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalRepresentedTypes +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalRepresentedValue +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalTypedRestriction +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalTypedTransport +OAI.NumberTheory.PiExponent.Ampleness.ExceptionalTypedTransportNaturality +OAI.NumberTheory.PiExponent.Ampleness.FiniteAffineFrames +OAI.NumberTheory.PiExponent.Ampleness.FinitePullbackAmple +OAI.NumberTheory.PiExponent.Ampleness.FiniteReesComparison +OAI.NumberTheory.PiExponent.Ampleness.GlobalBlowupAffineSquare +OAI.NumberTheory.PiExponent.Ampleness.GlobalBlowupGluing +OAI.NumberTheory.PiExponent.Ampleness.GlobalBlowupJetSurjectivity +OAI.NumberTheory.PiExponent.Ampleness.GlobalBlowupRestriction +OAI.NumberTheory.PiExponent.Ampleness.GlobalExceptionalComparison +OAI.NumberTheory.PiExponent.Ampleness.GlobalReesCanonicalRecovery +OAI.NumberTheory.PiExponent.Ampleness.GlobalReesRecoveryComparison +OAI.NumberTheory.PiExponent.Ampleness.IntegralComponentAmple +OAI.NumberTheory.PiExponent.Ampleness.LineAmpleOperations +OAI.NumberTheory.PiExponent.Ampleness.LocalHomogeneousDegrees +OAI.NumberTheory.PiExponent.Ampleness.NakaiAmpleFromSections +OAI.NumberTheory.PiExponent.Ampleness.NakaiBasepointFree +OAI.NumberTheory.PiExponent.Ampleness.NakaiCartier +OAI.NumberTheory.PiExponent.Ampleness.NakaiDivisorAmple +OAI.NumberTheory.PiExponent.Ampleness.NakaiEffectivity +OAI.NumberTheory.PiExponent.Ampleness.NakaiInductionStep +OAI.NumberTheory.PiExponent.Ampleness.NakaiSectionLifting +OAI.NumberTheory.PiExponent.Ampleness.NakaiStationarity +OAI.NumberTheory.PiExponent.Ampleness.NefAmple +OAI.NumberTheory.PiExponent.Ampleness.NilpotentAmpleDescent +OAI.NumberTheory.PiExponent.Ampleness.NoetherianAmpleProjectiveSections +OAI.NumberTheory.PiExponent.Ampleness.NumericalAmpleness +OAI.NumberTheory.PiExponent.Ampleness.NumericalAmplenessTheorem +OAI.NumberTheory.PiExponent.Ampleness.ProjectiveO1Ample +OAI.NumberTheory.PiExponent.Ampleness.ProperAmpleFiniteDimension +OAI.NumberTheory.PiExponent.Ampleness.ReducedComponentAmple +OAI.NumberTheory.PiExponent.Ampleness.ReesExceptional +OAI.NumberTheory.PiExponent.Ampleness.ReesExceptionalSheaf +OAI.NumberTheory.PiExponent.Ampleness.ReesFiniteCover +OAI.NumberTheory.PiExponent.Ampleness.ReesFixedChart +OAI.NumberTheory.PiExponent.Ampleness.ReesFixedFrames +OAI.NumberTheory.PiExponent.Ampleness.ReesFixedPower +OAI.NumberTheory.PiExponent.Ampleness.ReesFixedPowerRestriction +OAI.NumberTheory.PiExponent.Ampleness.ReesFixedRestriction +OAI.NumberTheory.PiExponent.Ampleness.ReesGradedModule +OAI.NumberTheory.PiExponent.Ampleness.ReesLocalizedChart +OAI.NumberTheory.PiExponent.Ampleness.ReesLocalizedIntersections +OAI.NumberTheory.PiExponent.Ampleness.ReesPolynomialPresentation +OAI.NumberTheory.PiExponent.Ampleness.ReesPrincipalLift +OAI.NumberTheory.PiExponent.Ampleness.ReesProductAugmentation +OAI.NumberTheory.PiExponent.Ampleness.ReesProductChart +OAI.NumberTheory.PiExponent.Ampleness.ReesProductFrames +OAI.NumberTheory.PiExponent.Ampleness.ReesProductPower +OAI.NumberTheory.PiExponent.Ampleness.ReesProductRestriction +OAI.NumberTheory.PiExponent.Ampleness.ReesProductSchemeChart +OAI.NumberTheory.PiExponent.Ampleness.ReesProductSchemeRestriction +OAI.NumberTheory.PiExponent.Ampleness.ReesPushdown +OAI.NumberTheory.PiExponent.Ampleness.ReesRelativeSections +OAI.NumberTheory.PiExponent.Ampleness.ReesSectionInclusion +OAI.NumberTheory.PiExponent.Ampleness.ReesSheafCanonicalValue +OAI.NumberTheory.PiExponent.Ampleness.ReesUniversalUniqueness +OAI.NumberTheory.PiExponent.Ampleness.RelativeAffineSectionAmple +OAI.NumberTheory.PiExponent.Ampleness.WeightedAffineFrame +OAI.NumberTheory.PiExponent.Ampleness.WeightedProjectiveAmple +OAI.NumberTheory.PiExponent.Ampleness.ZeroDimensionalAmple +OAI.NumberTheory.PiExponent.Analysis.AlgebraicLogarithmicObstruction +OAI.NumberTheory.PiExponent.Analysis.AnalyticAggregate +OAI.NumberTheory.PiExponent.Analysis.AnalyticCollision +OAI.NumberTheory.PiExponent.Analysis.AnalyticDeterminantCollision +OAI.NumberTheory.PiExponent.Analysis.AnalyticRowSeries +OAI.NumberTheory.PiExponent.Analysis.Collision +OAI.NumberTheory.PiExponent.Analysis.CollisionCombinatorics +OAI.NumberTheory.PiExponent.Analysis.CollisionExponential +OAI.NumberTheory.PiExponent.Analysis.CollisionGeometricSum +OAI.NumberTheory.PiExponent.Analysis.CollisionLimit +OAI.NumberTheory.PiExponent.Analysis.CollisionOccupancy +OAI.NumberTheory.PiExponent.Analysis.ColonSeriesTelescope +OAI.NumberTheory.PiExponent.Analysis.DeterminantAnalyticBound +OAI.NumberTheory.PiExponent.Analysis.DimensionLimits +OAI.NumberTheory.PiExponent.Analysis.DyadicPowers +OAI.NumberTheory.PiExponent.Analysis.DyadicSpacing +OAI.NumberTheory.PiExponent.Analysis.DyadicSummation +OAI.NumberTheory.PiExponent.Analysis.FiniteDeterminantCollision +OAI.NumberTheory.PiExponent.Analysis.FiniteSpacing +OAI.NumberTheory.PiExponent.Analysis.FlintConsequence +OAI.NumberTheory.PiExponent.Analysis.FlintHills +OAI.NumberTheory.PiExponent.Analysis.FlintSine +OAI.NumberTheory.PiExponent.Analysis.FormalLogTailOrder +OAI.NumberTheory.PiExponent.Analysis.FormalLogTruncation +OAI.NumberTheory.PiExponent.Analysis.HilbertSeries +OAI.NumberTheory.PiExponent.Analysis.LiteralAnalyticSummand +OAI.NumberTheory.PiExponent.Analysis.LogTailAnalytic +OAI.NumberTheory.PiExponent.Analysis.LogarithmicContactIdeal +OAI.NumberTheory.PiExponent.Analysis.LogarithmicObstruction +OAI.NumberTheory.PiExponent.Analysis.PeriodAnalytic +OAI.NumberTheory.PiExponent.Analysis.RegularSequenceSeries +OAI.NumberTheory.PiExponent.Analysis.TranslationCountLimit +OAI.NumberTheory.PiExponent.Approximation.AddEquivSignedSum +OAI.NumberTheory.PiExponent.Approximation.AdditiveKernelTransport +OAI.NumberTheory.PiExponent.Approximation.AdmissibleMatrixFrame +OAI.NumberTheory.PiExponent.Approximation.AdmissibleMatrixGeometry +OAI.NumberTheory.PiExponent.Approximation.AdmissibleMatrixInterpolation +OAI.NumberTheory.PiExponent.Approximation.AdmissibleParameters +OAI.NumberTheory.PiExponent.Approximation.AffineClosedAnnihilatedDescent +OAI.NumberTheory.PiExponent.Approximation.AffineThickeningCriterion +OAI.NumberTheory.PiExponent.Approximation.ApproximationCenters +OAI.NumberTheory.PiExponent.Approximation.ApproximationSelection +OAI.NumberTheory.PiExponent.Approximation.Arithmetic +OAI.NumberTheory.PiExponent.Approximation.CanonicalAffineRecovery +OAI.NumberTheory.PiExponent.Approximation.ClosedAnnihilatedDescent +OAI.NumberTheory.PiExponent.Approximation.ClosedImmersionModules +OAI.NumberTheory.PiExponent.Approximation.ClosedImmersionSerreTransfer +OAI.NumberTheory.PiExponent.Approximation.ClosedPowerSectionLifting +OAI.NumberTheory.PiExponent.Approximation.ClosedPullbackUnit +OAI.NumberTheory.PiExponent.Approximation.ClosedPullbackUnitRestriction +OAI.NumberTheory.PiExponent.Approximation.ClosedPushforwardAffine +OAI.NumberTheory.PiExponent.Approximation.ClosedPushforwardCoherent +OAI.NumberTheory.PiExponent.Approximation.ClosedPushforwardLinear +OAI.NumberTheory.PiExponent.Approximation.ClosedRestrictionTensor +OAI.NumberTheory.PiExponent.Approximation.ClosedSectionLifting +OAI.NumberTheory.PiExponent.Approximation.ClosedSupportedSerre +OAI.NumberTheory.PiExponent.Approximation.ClosedThickeningSections +OAI.NumberTheory.PiExponent.Approximation.ClosedUnitKernel +OAI.NumberTheory.PiExponent.Approximation.CocycleTensor +OAI.NumberTheory.PiExponent.Approximation.CocycleTensorIso +OAI.NumberTheory.PiExponent.Approximation.CoherentCokernels +OAI.NumberTheory.PiExponent.Approximation.CoherentTwistPresentation +OAI.NumberTheory.PiExponent.Approximation.Comparison +OAI.NumberTheory.PiExponent.Approximation.CompositePullbackFrame +OAI.NumberTheory.PiExponent.Approximation.ConstantPullbackDegree +OAI.NumberTheory.PiExponent.Approximation.CoordinateFrameIdentification +OAI.NumberTheory.PiExponent.Approximation.CoordinateSliceComparison +OAI.NumberTheory.PiExponent.Approximation.DeterminantContradiction +OAI.NumberTheory.PiExponent.Approximation.Exponent +OAI.NumberTheory.PiExponent.Approximation.FibreNormalRigidity +OAI.NumberTheory.PiExponent.Approximation.FibreWeightSeparation +OAI.NumberTheory.PiExponent.Approximation.FormalMatrixBridge +OAI.NumberTheory.PiExponent.Approximation.FormalMatrixSurjectivity +OAI.NumberTheory.PiExponent.Approximation.FrameEquationFamily +OAI.NumberTheory.PiExponent.Approximation.FrameResidueDirections +OAI.NumberTheory.PiExponent.Approximation.FrameSections +OAI.NumberTheory.PiExponent.Approximation.FrameSubopens +OAI.NumberTheory.PiExponent.Approximation.FrameSubopensCoherence +OAI.NumberTheory.PiExponent.Approximation.FrameTensorPowers +OAI.NumberTheory.PiExponent.Approximation.FramedPullback +OAI.NumberTheory.PiExponent.Approximation.FullSupportNilpotence +OAI.NumberTheory.PiExponent.Approximation.GeneratorsSectionCover +OAI.NumberTheory.PiExponent.Approximation.GenericFibreRigidity +OAI.NumberTheory.PiExponent.Approximation.GenericNormalRigidity +OAI.NumberTheory.PiExponent.Approximation.GlobalClosedAnnihilatedDescent +OAI.NumberTheory.PiExponent.Approximation.GlobalSectionClearing +OAI.NumberTheory.PiExponent.Approximation.GlueGlobalGenerators +OAI.NumberTheory.PiExponent.Approximation.IntegralLineSections +OAI.NumberTheory.PiExponent.Approximation.InterpolationConsequence +OAI.NumberTheory.PiExponent.Approximation.InterpolationMatrix +OAI.NumberTheory.PiExponent.Approximation.InverseDualRestriction +OAI.NumberTheory.PiExponent.Approximation.InverseFrameRestriction +OAI.NumberTheory.PiExponent.Approximation.InverseFrames +OAI.NumberTheory.PiExponent.Approximation.LineClosedUnit +OAI.NumberTheory.PiExponent.Approximation.LinePowerLaws +OAI.NumberTheory.PiExponent.Approximation.LinePullback +OAI.NumberTheory.PiExponent.Approximation.LinePullbackPowers +OAI.NumberTheory.PiExponent.Approximation.MatrixArithmetic +OAI.NumberTheory.PiExponent.Approximation.MatrixCounting +OAI.NumberTheory.PiExponent.Approximation.MatrixTranslation +OAI.NumberTheory.PiExponent.Approximation.MatrixTranslationBounds +OAI.NumberTheory.PiExponent.Approximation.MixedFrameExtension +OAI.NumberTheory.PiExponent.Approximation.MixedSectionExtension +OAI.NumberTheory.PiExponent.Approximation.MixedSectionOpenExtension +OAI.NumberTheory.PiExponent.Approximation.ModuleLinePowerLaws +OAI.NumberTheory.PiExponent.Approximation.ModulePullbackCoherent +OAI.NumberTheory.PiExponent.Approximation.NegativeTwistPresentations +OAI.NumberTheory.PiExponent.Approximation.NoetherianPowerExtension +OAI.NumberTheory.PiExponent.Approximation.NumericalMarginRestriction +OAI.NumberTheory.PiExponent.Approximation.NumericalSlopeInduction +OAI.NumberTheory.PiExponent.Approximation.NumericalThresholdStep +OAI.NumberTheory.PiExponent.Approximation.OpenBaseChange +OAI.NumberTheory.PiExponent.Approximation.OpenPullbackUnit +OAI.NumberTheory.PiExponent.Approximation.OrdinaryComponentRigidity +OAI.NumberTheory.PiExponent.Approximation.OrdinarySliceComparison +OAI.NumberTheory.PiExponent.Approximation.Parameters +OAI.NumberTheory.PiExponent.Approximation.PersistentComponents +OAI.NumberTheory.PiExponent.Approximation.PersistentWeightComparison +OAI.NumberTheory.PiExponent.Approximation.PowerSectionExtension +OAI.NumberTheory.PiExponent.Approximation.ProjectionFormula +OAI.NumberTheory.PiExponent.Approximation.PushforwardOpenSections +OAI.NumberTheory.PiExponent.Approximation.PushforwardSectionComparison +OAI.NumberTheory.PiExponent.Approximation.PushforwardTensor +OAI.NumberTheory.PiExponent.Approximation.RectangularVolume +OAI.NumberTheory.PiExponent.Approximation.RegularComponentSection +OAI.NumberTheory.PiExponent.Approximation.RegularSectionChoice +OAI.NumberTheory.PiExponent.Approximation.RegularSectionMono +OAI.NumberTheory.PiExponent.Approximation.RowTranslation +OAI.NumberTheory.PiExponent.Approximation.SectionDivision +OAI.NumberTheory.PiExponent.Approximation.SectionImageSupport +OAI.NumberTheory.PiExponent.Approximation.SectionOpens +OAI.NumberTheory.PiExponent.Approximation.SectionPowerFrames +OAI.NumberTheory.PiExponent.Approximation.SectionPowerOpens +OAI.NumberTheory.PiExponent.Approximation.SectionPullback +OAI.NumberTheory.PiExponent.Approximation.SectionZeroSupport +OAI.NumberTheory.PiExponent.Approximation.SerreAssembly +OAI.NumberTheory.PiExponent.Approximation.SerrePowerDescent +OAI.NumberTheory.PiExponent.Approximation.SerreSectionLifting +OAI.NumberTheory.PiExponent.Approximation.Sigma +OAI.NumberTheory.PiExponent.Approximation.SuccessiveApproximations +OAI.NumberTheory.PiExponent.Approximation.TensorMixedSection +OAI.NumberTheory.PiExponent.Approximation.TensorOpenBaseChange +OAI.NumberTheory.PiExponent.Approximation.TensorPowerRestriction +OAI.NumberTheory.PiExponent.Approximation.TensorPure +OAI.NumberTheory.PiExponent.Approximation.TensorSectionOpen +OAI.NumberTheory.PiExponent.Approximation.TwistGlobalExtension +OAI.NumberTheory.PiExponent.Approximation.TwistPowerSection +OAI.NumberTheory.PiExponent.Approximation.TwistPresentations +OAI.NumberTheory.PiExponent.Approximation.TwistSectionClearing +OAI.NumberTheory.PiExponent.Approximation.TwistSectionScalars +OAI.NumberTheory.PiExponent.Approximation.TwistSections +OAI.NumberTheory.PiExponent.Approximation.WeightErrorMargin +OAI.NumberTheory.PiExponent.Approximation.WeightSeparation +OAI.NumberTheory.PiExponent.Approximation.WeightSeparationConstant +OAI.NumberTheory.PiExponent.Approximation.WeightSeparationProducts +OAI.NumberTheory.PiExponent.Approximation.WeightedAffineParametrization +OAI.NumberTheory.PiExponent.Approximation.WeightedCompactification +OAI.NumberTheory.PiExponent.Approximation.WeightedCompactificationGeometry +OAI.NumberTheory.PiExponent.Approximation.WeightedCompactificationImmersion +OAI.NumberTheory.PiExponent.Approximation.WeightedFrameDegree +OAI.NumberTheory.PiExponent.Approximation.WeightedGeometryScale +OAI.NumberTheory.PiExponent.Approximation.WeightedGlobalSectionBound +OAI.NumberTheory.PiExponent.Approximation.WeightedPullbackDegree +OAI.NumberTheory.PiExponent.Approximation.WeightedSectionOrder +OAI.NumberTheory.PiExponent.Approximation.WeightedSliceDegree +OAI.NumberTheory.PiExponent.Cohomology.AmpleCohomologyFinite +OAI.NumberTheory.PiExponent.Cohomology.AmpleLineCohomology +OAI.NumberTheory.PiExponent.Cohomology.CartierEulerDifference +OAI.NumberTheory.PiExponent.Cohomology.CartierEulerPair +OAI.NumberTheory.PiExponent.Cohomology.CartierMixedEuler +OAI.NumberTheory.PiExponent.Cohomology.CechExtFinite +OAI.NumberTheory.PiExponent.Cohomology.CechH1Transfer +OAI.NumberTheory.PiExponent.Cohomology.CechHigher +OAI.NumberTheory.PiExponent.Cohomology.CechLinear +OAI.NumberTheory.PiExponent.Cohomology.CechOne +OAI.NumberTheory.PiExponent.Cohomology.CechOneConverse +OAI.NumberTheory.PiExponent.Cohomology.CechZero +OAI.NumberTheory.PiExponent.Cohomology.CechZeroAdditive +OAI.NumberTheory.PiExponent.Cohomology.CohomologyFinite +OAI.NumberTheory.PiExponent.Cohomology.CohomologyIso +OAI.NumberTheory.PiExponent.Cohomology.CurveCycleEuler +OAI.NumberTheory.PiExponent.Cohomology.CurveDerivativeVanishing +OAI.NumberTheory.PiExponent.Cohomology.CurveEuler +OAI.NumberTheory.PiExponent.Cohomology.CurveFinitePushforwardCohomology +OAI.NumberTheory.PiExponent.Cohomology.CurveNormalizationCohomology +OAI.NumberTheory.PiExponent.Cohomology.CurveNormalizationEuler +OAI.NumberTheory.PiExponent.Cohomology.CurveRegularEuler +OAI.NumberTheory.PiExponent.Cohomology.CurveTensorEuler +OAI.NumberTheory.PiExponent.Cohomology.CurveTwoAffineVanishing +OAI.NumberTheory.PiExponent.Cohomology.CurveZeroEuler +OAI.NumberTheory.PiExponent.Cohomology.EndomorphismEulerAdditivity +OAI.NumberTheory.PiExponent.Cohomology.EulerCutoff +OAI.NumberTheory.PiExponent.Cohomology.EulerDifferencePolynomial +OAI.NumberTheory.PiExponent.Cohomology.EulerExact +OAI.NumberTheory.PiExponent.Cohomology.EulerPolynomialDegree +OAI.NumberTheory.PiExponent.Cohomology.EulerPolynomialInterpolation +OAI.NumberTheory.PiExponent.Cohomology.EulerRegularSections +OAI.NumberTheory.PiExponent.Cohomology.EulerRegularTwists +OAI.NumberTheory.PiExponent.Cohomology.EulerSupportDimension +OAI.NumberTheory.PiExponent.Cohomology.EulerTwistTransport +OAI.NumberTheory.PiExponent.Cohomology.EulerZeroDimensional +OAI.NumberTheory.PiExponent.Cohomology.FiniteCoverCohomology +OAI.NumberTheory.PiExponent.Cohomology.FiniteLineEuler +OAI.NumberTheory.PiExponent.Cohomology.FiniteSupportCohomology +OAI.NumberTheory.PiExponent.Cohomology.FiniteZeroEuler +OAI.NumberTheory.PiExponent.Cohomology.FreeCechResolution +OAI.NumberTheory.PiExponent.Cohomology.FreeCechSections +OAI.NumberTheory.PiExponent.Cohomology.GradedCech +OAI.NumberTheory.PiExponent.Cohomology.GradedCechBound +OAI.NumberTheory.PiExponent.Cohomology.GradedCechExactness +OAI.NumberTheory.PiExponent.Cohomology.GradedCechRecovery +OAI.NumberTheory.PiExponent.Cohomology.GradedFreeCech +OAI.NumberTheory.PiExponent.Cohomology.GradedH0 +OAI.NumberTheory.PiExponent.Cohomology.GradedPolynomialCech +OAI.NumberTheory.PiExponent.Cohomology.GradedPolynomialLaurent +OAI.NumberTheory.PiExponent.Cohomology.GradedSerreVanishing +OAI.NumberTheory.PiExponent.Cohomology.IdealPowerCohomology +OAI.NumberTheory.PiExponent.Cohomology.LaurentCechFinite +OAI.NumberTheory.PiExponent.Cohomology.LaurentExtFinite +OAI.NumberTheory.PiExponent.Cohomology.LineCohomologyDimension +OAI.NumberTheory.PiExponent.Cohomology.LocalIntersectionEulerFiltration +OAI.NumberTheory.PiExponent.Cohomology.LocalIntersectionRegularEuler +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerAlgebra +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerAmpleDimension +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerCartier +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerCartierAmple +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerCurveMargin +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerDimension +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerPolarization +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerPositivity +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerRestriction +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerSlope +OAI.NumberTheory.PiExponent.Cohomology.MixedEulerTop +OAI.NumberTheory.PiExponent.Cohomology.NakaiCohomology +OAI.NumberTheory.PiExponent.Cohomology.NakaiEulerGrowth +OAI.NumberTheory.PiExponent.Cohomology.NilpotentIdealVanishing +OAI.NumberTheory.PiExponent.Cohomology.NoetherianAmpleSerreVanishing +OAI.NumberTheory.PiExponent.Cohomology.NumericalEulerSlopeInputs +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomology +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologyCech +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologyCharts +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologyFiniteCharts +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologyLaurent +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologyPencil +OAI.NumberTheory.PiExponent.Cohomology.PencilCohomologySections +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveCoordinateAcyclicity +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveEmbeddingCohomologyBound +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveFramedCech +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveLaurentTransitions +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveLaurentVertex +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveLineLaurent +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveMonomialCech +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveMonomialCechHigher +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveMonomialCohomology +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveTwistAcyclicity +OAI.NumberTheory.PiExponent.Cohomology.ProjectiveTwistCech +OAI.NumberTheory.PiExponent.Cohomology.ReesCechInjectivity +OAI.NumberTheory.PiExponent.Cohomology.ReesCechRecovery +OAI.NumberTheory.PiExponent.Cohomology.ReesCohomologySetup +OAI.NumberTheory.PiExponent.Cohomology.ReesSheafCechBase +OAI.NumberTheory.PiExponent.Cohomology.ReesSheafCechNaturality +OAI.NumberTheory.PiExponent.Cohomology.ReesSheafCechRecovery +OAI.NumberTheory.PiExponent.Cohomology.SerreVanishing +OAI.NumberTheory.PiExponent.Cohomology.TupleCechBound +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveCoordinates +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveDegreeData +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveImage +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveInequality +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveModel +OAI.NumberTheory.PiExponent.Geometry.AdmissibleCurveWeights +OAI.NumberTheory.PiExponent.Geometry.BirationalOpenIso +OAI.NumberTheory.PiExponent.Geometry.BirationalValuationStalk +OAI.NumberTheory.PiExponent.Geometry.CanonicalRecoveryProperties +OAI.NumberTheory.PiExponent.Geometry.CartierDegreeLength +OAI.NumberTheory.PiExponent.Geometry.CartierPowerFrames +OAI.NumberTheory.PiExponent.Geometry.CartierSequence +OAI.NumberTheory.PiExponent.Geometry.CoherentProjectiveFinite +OAI.NumberTheory.PiExponent.Geometry.ConePrimeProperties +OAI.NumberTheory.PiExponent.Geometry.CurveCenters +OAI.NumberTheory.PiExponent.Geometry.CurveChartFunctionField +OAI.NumberTheory.PiExponent.Geometry.CurveComponentCutLengths +OAI.NumberTheory.PiExponent.Geometry.CurveComponentIncidence +OAI.NumberTheory.PiExponent.Geometry.CurveComponentLocalLengths +OAI.NumberTheory.PiExponent.Geometry.CurveComponentMultiplicity +OAI.NumberTheory.PiExponent.Geometry.CurveComponentRigidity +OAI.NumberTheory.PiExponent.Geometry.CurveComponentStalks +OAI.NumberTheory.PiExponent.Geometry.CurveComponentZeroPoints +OAI.NumberTheory.PiExponent.Geometry.CurveComponentsDimension +OAI.NumberTheory.PiExponent.Geometry.CurveContact +OAI.NumberTheory.PiExponent.Geometry.CurveContactFamily +OAI.NumberTheory.PiExponent.Geometry.CurveContactSum +OAI.NumberTheory.PiExponent.Geometry.CurveCutQuotient +OAI.NumberTheory.PiExponent.Geometry.CurveCycleLengths +OAI.NumberTheory.PiExponent.Geometry.CurveCycleNumerical +OAI.NumberTheory.PiExponent.Geometry.CurveDegreeAdditivity +OAI.NumberTheory.PiExponent.Geometry.CurveDegreeLaws +OAI.NumberTheory.PiExponent.Geometry.CurveEffectiveTwist +OAI.NumberTheory.PiExponent.Geometry.CurveFieldRigidity +OAI.NumberTheory.PiExponent.Geometry.CurveFinitePushforwardCoherent +OAI.NumberTheory.PiExponent.Geometry.CurveFunctionFieldCompatibility +OAI.NumberTheory.PiExponent.Geometry.CurveGeometricFunctionField +OAI.NumberTheory.PiExponent.Geometry.CurveGlobalCoordinateOrder +OAI.NumberTheory.PiExponent.Geometry.CurveGlobalMonomial +OAI.NumberTheory.PiExponent.Geometry.CurveGlobalMonomialLocal +OAI.NumberTheory.PiExponent.Geometry.CurveImageAffineChart +OAI.NumberTheory.PiExponent.Geometry.CurveImageAffineCoordinates +OAI.NumberTheory.PiExponent.Geometry.CurveImageOpenLocus +OAI.NumberTheory.PiExponent.Geometry.CurveInequality +OAI.NumberTheory.PiExponent.Geometry.CurveInequalityIntrinsic +OAI.NumberTheory.PiExponent.Geometry.CurveLocalAssociativity +OAI.NumberTheory.PiExponent.Geometry.CurveLocalMultiplicity +OAI.NumberTheory.PiExponent.Geometry.CurveLocalOrder +OAI.NumberTheory.PiExponent.Geometry.CurveModelFieldEmbedding +OAI.NumberTheory.PiExponent.Geometry.CurveModelGenericPoint +OAI.NumberTheory.PiExponent.Geometry.CurveModelInfinityGenericPoint +OAI.NumberTheory.PiExponent.Geometry.CurveModelLocalOrder +OAI.NumberTheory.PiExponent.Geometry.CurveModelPlaces +OAI.NumberTheory.PiExponent.Geometry.CurveMonomialMap +OAI.NumberTheory.PiExponent.Geometry.CurveMorphismFinite +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationDegree +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationDimension +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationInvariance +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationLocalRing +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationModel +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationMorphism +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationNonaffine +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationOverlap +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationProjective +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationProper +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizationUnit +OAI.NumberTheory.PiExponent.Geometry.CurveNormalizedDegreeTransfer +OAI.NumberTheory.PiExponent.Geometry.CurveParameterFinite +OAI.NumberTheory.PiExponent.Geometry.CurvePlaceCenter +OAI.NumberTheory.PiExponent.Geometry.CurvePlaceCenterStalk +OAI.NumberTheory.PiExponent.Geometry.CurvePlaceSectionDivisor +OAI.NumberTheory.PiExponent.Geometry.CurvePlaceSectionOrder +OAI.NumberTheory.PiExponent.Geometry.CurvePrimeHeight +OAI.NumberTheory.PiExponent.Geometry.CurveProductFormula +OAI.NumberTheory.PiExponent.Geometry.CurveProperExtension +OAI.NumberTheory.PiExponent.Geometry.CurveProperImageDimension +OAI.NumberTheory.PiExponent.Geometry.CurveSectionDegree +OAI.NumberTheory.PiExponent.Geometry.CurveStalkGluing +OAI.NumberTheory.PiExponent.Geometry.CurveValuationCenter +OAI.NumberTheory.PiExponent.Geometry.CurveZeroPole +OAI.NumberTheory.PiExponent.Geometry.FiniteCurveZeros +OAI.NumberTheory.PiExponent.Geometry.FiniteNormalizationGrowth +OAI.NumberTheory.PiExponent.Geometry.FiniteOfNoContractedCurves +OAI.NumberTheory.PiExponent.Geometry.FromSpecStalkLocalIso +OAI.NumberTheory.PiExponent.Geometry.GeneralCartierDegreeLength +OAI.NumberTheory.PiExponent.Geometry.IdealSheafPowers +OAI.NumberTheory.PiExponent.Geometry.IntegralCurveExistence +OAI.NumberTheory.PiExponent.Geometry.LineBundleCoherent +OAI.NumberTheory.PiExponent.Geometry.LineBundleFrameCocycle +OAI.NumberTheory.PiExponent.Geometry.LineBundleGluing +OAI.NumberTheory.PiExponent.Geometry.LineBundleGluingSections +OAI.NumberTheory.PiExponent.Geometry.LineBundleGluingTransitions +OAI.NumberTheory.PiExponent.Geometry.LineBundleInverse +OAI.NumberTheory.PiExponent.Geometry.LineBundleProduct +OAI.NumberTheory.PiExponent.Geometry.LineBundleTensor +OAI.NumberTheory.PiExponent.Geometry.NormalizationGrowth +OAI.NumberTheory.PiExponent.Geometry.PlaceCenteredBranch +OAI.NumberTheory.PiExponent.Geometry.PlaceLocalRing +OAI.NumberTheory.PiExponent.Geometry.PlaceParameterModel +OAI.NumberTheory.PiExponent.Geometry.PlaceValuationRing +OAI.NumberTheory.PiExponent.Geometry.PolynomialProjectiveStructure +OAI.NumberTheory.PiExponent.Geometry.PrincipalCartierSequence +OAI.NumberTheory.PiExponent.Geometry.ProjectiveChartOverlaps +OAI.NumberTheory.PiExponent.Geometry.ProjectiveChartRingNaturality +OAI.NumberTheory.PiExponent.Geometry.ProjectiveChartRingNaturalityCore +OAI.NumberTheory.PiExponent.Geometry.ProjectiveChartSections +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCharts +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoefficientBound +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateChartMap +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateConstants +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateFinite +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateFiniteSections +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateFiniteValues +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateOverlapNaturality +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinatePullback +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateRatios +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateRingNaturality +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateScalars +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateSections +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateTransitions +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinateValues +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCoordinates +OAI.NumberTheory.PiExponent.Geometry.ProjectiveCurveTwoAffine +OAI.NumberTheory.PiExponent.Geometry.ProjectiveDenseChart +OAI.NumberTheory.PiExponent.Geometry.ProjectiveEmbeddingCharts +OAI.NumberTheory.PiExponent.Geometry.ProjectiveFiniteCoordinates +OAI.NumberTheory.PiExponent.Geometry.ProjectiveFinitePencil +OAI.NumberTheory.PiExponent.Geometry.ProjectiveFrameNaturality +OAI.NumberTheory.PiExponent.Geometry.ProjectiveFramedAtlas +OAI.NumberTheory.PiExponent.Geometry.ProjectiveFramedSections +OAI.NumberTheory.PiExponent.Geometry.ProjectiveGlobalPolynomialAlgebra +OAI.NumberTheory.PiExponent.Geometry.ProjectiveGlobalPolynomials +OAI.NumberTheory.PiExponent.Geometry.ProjectiveIntrinsicCoefficientLaw +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLatticeOrder +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLatticePullback +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLineCharts +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLineProper +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLineReciprocal +OAI.NumberTheory.PiExponent.Geometry.ProjectiveLocalCoefficients +OAI.NumberTheory.PiExponent.Geometry.ProjectiveMonomialFinite +OAI.NumberTheory.PiExponent.Geometry.ProjectiveNegativeCoordinates +OAI.NumberTheory.PiExponent.Geometry.ProjectiveNegativeFrames +OAI.NumberTheory.PiExponent.Geometry.ProjectiveNegativeScalars +OAI.NumberTheory.PiExponent.Geometry.ProjectiveNegativeTransitions +OAI.NumberTheory.PiExponent.Geometry.ProjectiveO1ChartMap +OAI.NumberTheory.PiExponent.Geometry.ProjectiveO1Identity +OAI.NumberTheory.PiExponent.Geometry.ProjectiveO1LocalIdentity +OAI.NumberTheory.PiExponent.Geometry.ProjectiveO1Morphism +OAI.NumberTheory.PiExponent.Geometry.ProjectiveO1Sections +OAI.NumberTheory.PiExponent.Geometry.ProjectivePencilScalars +OAI.NumberTheory.PiExponent.Geometry.ProjectivePullbackFrames +OAI.NumberTheory.PiExponent.Geometry.ProjectiveRatioCocycle +OAI.NumberTheory.PiExponent.Geometry.ProjectiveRepresentedCoefficient +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSectionExtension +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSectionInterface +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSectionPullback +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSectionReindex +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSectionsPullback +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSerreTransfer +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSpaceBasics +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSpaceFinite +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSpaceIntegral +OAI.NumberTheory.PiExponent.Geometry.ProjectiveSpaceSerre +OAI.NumberTheory.PiExponent.Geometry.ProjectiveTupleCharts +OAI.NumberTheory.PiExponent.Geometry.ProjectiveVertexCompatibility +OAI.NumberTheory.PiExponent.Geometry.ProperHypersurfaceHilbert +OAI.NumberTheory.PiExponent.Geometry.ReducedComponentStalk +OAI.NumberTheory.PiExponent.Geometry.SectionCartierPower +OAI.NumberTheory.PiExponent.Geometry.SectionCartierRegular +OAI.NumberTheory.PiExponent.Geometry.SectionOrderDivisor +OAI.NumberTheory.PiExponent.Geometry.SectionZeroStalk +OAI.NumberTheory.PiExponent.Geometry.SheafSectionGluing +OAI.NumberTheory.PiExponent.Geometry.SheafificationUnitIso +OAI.NumberTheory.PiExponent.Geometry.SupportedSheaf +OAI.NumberTheory.PiExponent.Geometry.WeightedCurveDegree +OAI.NumberTheory.PiExponent.Geometry.WeightedCurveRigidity +OAI.NumberTheory.PiExponent.Geometry.WeightedLocalSheaf +OAI.NumberTheory.PiExponent.Geometry.WeightedProjectiveCurveDegree +OAI.NumberTheory.PiExponent.Geometry.WeightedProjectiveEmbedding +OAI.NumberTheory.PiExponent.Geometry.WeightedProjectiveLineBundle +OAI.NumberTheory.PiExponent.Geometry.WeightedProjectiveStructure +OAI.NumberTheory.PiExponent.Jets.AdmissibleJetPackets +OAI.NumberTheory.PiExponent.Jets.AdmissibleJetSurjectivity +OAI.NumberTheory.PiExponent.Jets.AffineJetCoefficientFrame +OAI.NumberTheory.PiExponent.Jets.AffineJetCoefficientInterface +OAI.NumberTheory.PiExponent.Jets.AffineJetFramedPackets +OAI.NumberTheory.PiExponent.Jets.AffineJetPackets +OAI.NumberTheory.PiExponent.Jets.AffineJetPolynomial +OAI.NumberTheory.PiExponent.Jets.AffineJetQuotient +OAI.NumberTheory.PiExponent.Jets.AffineJetSupport +OAI.NumberTheory.PiExponent.Jets.AlgebraicJetPackets +OAI.NumberTheory.PiExponent.Jets.AuxiliaryJetMap +OAI.NumberTheory.PiExponent.Jets.BranchContact +OAI.NumberTheory.PiExponent.Jets.BranchContactIdeal +OAI.NumberTheory.PiExponent.Jets.CommutingTaylor +OAI.NumberTheory.PiExponent.Jets.CompactJetIdeal +OAI.NumberTheory.PiExponent.Jets.CompactJetIdealCoherent +OAI.NumberTheory.PiExponent.Jets.CompactJetPolynomial +OAI.NumberTheory.PiExponent.Jets.CompactLogJetIdeal +OAI.NumberTheory.PiExponent.Jets.ConormalPairing +OAI.NumberTheory.PiExponent.Jets.CotangentGeneration +OAI.NumberTheory.PiExponent.Jets.DVRBranch +OAI.NumberTheory.PiExponent.Jets.DVRBranchExpansion +OAI.NumberTheory.PiExponent.Jets.DVRBranchJet +OAI.NumberTheory.PiExponent.Jets.DVRBranchOrder +OAI.NumberTheory.PiExponent.Jets.DerivativeIdeals +OAI.NumberTheory.PiExponent.Jets.DifferentialConstant +OAI.NumberTheory.PiExponent.Jets.FilteredLength +OAI.NumberTheory.PiExponent.Jets.FormalAuxiliaryJet +OAI.NumberTheory.PiExponent.Jets.FormalBranchContact +OAI.NumberTheory.PiExponent.Jets.FormalBranchCoordinates +OAI.NumberTheory.PiExponent.Jets.FormalBranchEvaluation +OAI.NumberTheory.PiExponent.Jets.FormalBranchOrder +OAI.NumberTheory.PiExponent.Jets.FormalBranchOrderRational +OAI.NumberTheory.PiExponent.Jets.FormalJetDerivatives +OAI.NumberTheory.PiExponent.Jets.FormalJetIndices +OAI.NumberTheory.PiExponent.Jets.FormalLogJet +OAI.NumberTheory.PiExponent.Jets.FrameTransverseMultiplicity +OAI.NumberTheory.PiExponent.Jets.GradedGeneration +OAI.NumberTheory.PiExponent.Jets.IntrinsicLength +OAI.NumberTheory.PiExponent.Jets.JetCenterIdentification +OAI.NumberTheory.PiExponent.Jets.JetGeometry +OAI.NumberTheory.PiExponent.Jets.JetPowerIdealCoprime +OAI.NumberTheory.PiExponent.Jets.JetProductLocalization +OAI.NumberTheory.PiExponent.Jets.KoszulTopDifferential +OAI.NumberTheory.PiExponent.Jets.NormalBasisProducts +OAI.NumberTheory.PiExponent.Jets.NormalBasisRigidity +OAI.NumberTheory.PiExponent.Jets.NormalFrameBasis +OAI.NumberTheory.PiExponent.Jets.OrdinaryAuxiliaryJet +OAI.NumberTheory.PiExponent.Jets.OrdinaryBranchEvaluation +OAI.NumberTheory.PiExponent.Jets.OrdinaryDVRBranchJet +OAI.NumberTheory.PiExponent.Jets.OrdinaryDerivativeIdeals +OAI.NumberTheory.PiExponent.Jets.OrdinaryJetDerivatives +OAI.NumberTheory.PiExponent.Jets.OrdinaryTaylor +OAI.NumberTheory.PiExponent.Jets.PolynomialJetPackets +OAI.NumberTheory.PiExponent.Jets.PolynomialTangentDifferential +OAI.NumberTheory.PiExponent.Jets.PrimeNormalCotangent +OAI.NumberTheory.PiExponent.Jets.PrimeTaylorCotangent +OAI.NumberTheory.PiExponent.Jets.RectangularCotangent +OAI.NumberTheory.PiExponent.Jets.ResidueConormalPairing +OAI.NumberTheory.PiExponent.Jets.TaylorRectangular +OAI.NumberTheory.PiExponent.Jets.TransverseMultiplicity +OAI.NumberTheory.PiExponent.Jets.TransverseSliceComparison +OAI.NumberTheory.PiExponent.Jets.TransverseWeightedMultiplicity +OAI.NumberTheory.PiExponent.LocalAlgebra.AffineClosedPointLocalization +OAI.NumberTheory.PiExponent.LocalAlgebra.AffineIdealSections +OAI.NumberTheory.PiExponent.LocalAlgebra.AffineLocalRegularBezout +OAI.NumberTheory.PiExponent.LocalAlgebra.AffinePrimeDimensionBridge +OAI.NumberTheory.PiExponent.LocalAlgebra.AffineResidueTranscendence +OAI.NumberTheory.PiExponent.LocalAlgebra.AffineTranscendenceDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.AssociatedPrimeAvoidance +OAI.NumberTheory.PiExponent.LocalAlgebra.ClosedPointLocalDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.CoherentExtFiniteness +OAI.NumberTheory.PiExponent.LocalAlgebra.CoherentInverseFinite +OAI.NumberTheory.PiExponent.LocalAlgebra.ColonHilbertStep +OAI.NumberTheory.PiExponent.LocalAlgebra.CompleteIntersectionComponentBound +OAI.NumberTheory.PiExponent.LocalAlgebra.CompleteIntersectionHilbert +OAI.NumberTheory.PiExponent.LocalAlgebra.ComponentMultiplicityBound +OAI.NumberTheory.PiExponent.LocalAlgebra.ComponentMultiplicitySum +OAI.NumberTheory.PiExponent.LocalAlgebra.ConeComplex +OAI.NumberTheory.PiExponent.LocalAlgebra.ConeEquationLength +OAI.NumberTheory.PiExponent.LocalAlgebra.ConeLocalLength +OAI.NumberTheory.PiExponent.LocalAlgebra.ConePrimeLocalization +OAI.NumberTheory.PiExponent.LocalAlgebra.ConeQuotientAugmentation +OAI.NumberTheory.PiExponent.LocalAlgebra.ConeRegularSequence +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateBasisSplitting +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateContactBound +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateFiniteSlice +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateSliceLength +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateTranscendenceBasis +OAI.NumberTheory.PiExponent.LocalAlgebra.CoordinateTranscendenceLocalization +OAI.NumberTheory.PiExponent.LocalAlgebra.CumulativeHilbertSections +OAI.NumberTheory.PiExponent.LocalAlgebra.CyclicPrimeFactor +OAI.NumberTheory.PiExponent.LocalAlgebra.DVRValuationUnique +OAI.NumberTheory.PiExponent.LocalAlgebra.Dimension +OAI.NumberTheory.PiExponent.LocalAlgebra.EquidimensionalRetainedCut +OAI.NumberTheory.PiExponent.LocalAlgebra.FibreContact +OAI.NumberTheory.PiExponent.LocalAlgebra.FiltrationLength +OAI.NumberTheory.PiExponent.LocalAlgebra.FiniteFreeExtTransfer +OAI.NumberTheory.PiExponent.LocalAlgebra.FiniteFreeResolutionExt +OAI.NumberTheory.PiExponent.LocalAlgebra.FiniteFromClosedFibers +OAI.NumberTheory.PiExponent.LocalAlgebra.FiniteGlobalPresentation +OAI.NumberTheory.PiExponent.LocalAlgebra.FiniteSupportLocalIso +OAI.NumberTheory.PiExponent.LocalAlgebra.FinsuppCandidates +OAI.NumberTheory.PiExponent.LocalAlgebra.FlatLocalLength +OAI.NumberTheory.PiExponent.LocalAlgebra.FreeResolutionAssociatedHeight +OAI.NumberTheory.PiExponent.LocalAlgebra.GenericCombination +OAI.NumberTheory.PiExponent.LocalAlgebra.GlobalInvertibleIdeal +OAI.NumberTheory.PiExponent.LocalAlgebra.HilbertDenominatorReduction +OAI.NumberTheory.PiExponent.LocalAlgebra.HilbertDifferenceDegree +OAI.NumberTheory.PiExponent.LocalAlgebra.HilbertGrowthComparison +OAI.NumberTheory.PiExponent.LocalAlgebra.HilbertMultiplicityFiltration +OAI.NumberTheory.PiExponent.LocalAlgebra.HilbertZeroVariables +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealFiniteGenerators +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealModule +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealModuleRestriction +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPowerAnnihilator +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPowerDescent +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPowerFiltration +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPowerRestriction +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPullbackMap +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealPullbackOpenSquare +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealSectionRestriction +OAI.NumberTheory.PiExponent.LocalAlgebra.IdealTensorPowers +OAI.NumberTheory.PiExponent.LocalAlgebra.IntegralAffineOpenDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.InvertibleIdealAway +OAI.NumberTheory.PiExponent.LocalAlgebra.InvertibleIdealLocal +OAI.NumberTheory.PiExponent.LocalAlgebra.IsolatedIntersectionSteps +OAI.NumberTheory.PiExponent.LocalAlgebra.IteratedKoszulExactness +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulBounded +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualBottom +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualCone +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualEndpoint +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualInitial +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualStep +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulDualTransport +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulFiniteFree +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulTopAugmentation +OAI.NumberTheory.PiExponent.LocalAlgebra.KoszulTopTerm +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalBezout +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalComponentDegree +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionDimensionOne +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionExactStep +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionFormula +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionLength +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionMinimalSum +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionPrimeFactors +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionPrimeFiltration +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionQuotientTransport +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalIntersectionTransport +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalLength +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalLengthTransport +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalPrefixCutDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalPrimeTower +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalPullbackSectionOrder +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalSectionOrder +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizationQuotientParameters +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedAlgebraEvaluation +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedComponent +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedCyclicFactor +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedFiltrationLength +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedLengthEquivalence +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedMinimalPrimeFamily +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedOneCutPropagation +OAI.NumberTheory.PiExponent.LocalAlgebra.LocalizedRadical +OAI.NumberTheory.PiExponent.LocalAlgebra.MultiplicityCycles +OAI.NumberTheory.PiExponent.LocalAlgebra.NaturalMultiplicityPropagation +OAI.NumberTheory.PiExponent.LocalAlgebra.OpenIsoFunctionField +OAI.NumberTheory.PiExponent.LocalAlgebra.OrdinaryMultiplicity +OAI.NumberTheory.PiExponent.LocalAlgebra.PairResolutionShortComplex +OAI.NumberTheory.PiExponent.LocalAlgebra.ParameterCombinations +OAI.NumberTheory.PiExponent.LocalAlgebra.ParameterKilledFiniteLength +OAI.NumberTheory.PiExponent.LocalAlgebra.ParameterResidueField +OAI.NumberTheory.PiExponent.LocalAlgebra.PointLengthEquiv +OAI.NumberTheory.PiExponent.LocalAlgebra.PositiveCoherentExtFiniteness +OAI.NumberTheory.PiExponent.LocalAlgebra.PositiveDimensionalHilbert +OAI.NumberTheory.PiExponent.LocalAlgebra.PresentedIdealIso +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeCutBudget +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeDegreeExistence +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeFrameMultiplicity +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeHilbertComparison +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeHilbertDegree +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeHilbertDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeHypersurfaceDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeHypersurfaceEquidimension +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeNormalKernel +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeNormalRigidity +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeResidueAlgebraEquiv +OAI.NumberTheory.PiExponent.LocalAlgebra.PrimeWeightedBezout +OAI.NumberTheory.PiExponent.LocalAlgebra.PrincipalQuotientDimension +OAI.NumberTheory.PiExponent.LocalAlgebra.QuotientLengthEquivalence +OAI.NumberTheory.PiExponent.LocalAlgebra.QuotientLocalizedLength +OAI.NumberTheory.PiExponent.LocalAlgebra.QuotientPrimeResidueBasis +OAI.NumberTheory.PiExponent.LocalAlgebra.QuotientSections +OAI.NumberTheory.PiExponent.LocalAlgebra.RamifiedLocalLength +OAI.NumberTheory.PiExponent.LocalAlgebra.RamifiedLocalization +OAI.NumberTheory.PiExponent.LocalAlgebra.RamifiedPointMap +OAI.NumberTheory.PiExponent.LocalAlgebra.RamifiedPowerLength +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularCutHistory +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularDegreePositivity +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularHilbertStep +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularPairExtObstruction +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularParameterAvoidance +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularParameterSelection +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularParameterSelection2 +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularPrefixLocalization +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularPrefixes +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceAugmentation +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceDualExactness +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceExt +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceExtObstruction +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceHomZero +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceLowExt +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceQuotientTail +OAI.NumberTheory.PiExponent.LocalAlgebra.RegularSequenceResolution +OAI.NumberTheory.PiExponent.LocalAlgebra.RetainedIntersectionCycles +OAI.NumberTheory.PiExponent.LocalAlgebra.RetainedMinimalPrimeFamily +OAI.NumberTheory.PiExponent.LocalAlgebra.SectionImageIdeal +OAI.NumberTheory.PiExponent.LocalAlgebra.SectionZeroIdeal +OAI.NumberTheory.PiExponent.LocalAlgebra.SeparablePointLength +OAI.NumberTheory.PiExponent.LocalAlgebra.SerreDimensionShift +OAI.NumberTheory.PiExponent.LocalAlgebra.SplitClosedPointCompatibility +OAI.NumberTheory.PiExponent.LocalAlgebra.SplitCoordinateClosedPoint +OAI.NumberTheory.PiExponent.LocalAlgebra.StabilizedColonPowers +OAI.NumberTheory.PiExponent.LocalAlgebra.SubquotientLength +OAI.NumberTheory.PiExponent.LocalAlgebra.TensorIdealInclusion +OAI.NumberTheory.PiExponent.LocalAlgebra.TranscendenceBasisReduction +OAI.NumberTheory.PiExponent.LocalAlgebra.TriangularLocalParameters +OAI.NumberTheory.PiExponent.LocalAlgebra.TriangularLocalParametersAssembly +OAI.NumberTheory.PiExponent.LocalAlgebra.TriangularLocalParametersTransport +OAI.NumberTheory.PiExponent.LocalAlgebra.TwistLocalExtension +OAI.NumberTheory.PiExponent.LocalAlgebra.TwistLocalSections +OAI.NumberTheory.PiExponent.LocalAlgebra.WeightedBezout +OAI.NumberTheory.PiExponent.LocalAlgebra.WeightedBezoutBound +OAI.NumberTheory.PiExponent.LocalAlgebra.WeightedChartRingEvaluation +OAI.NumberTheory.PiExponent.LocalAlgebra.WeightedLocalLattice +OAI.NumberTheory.PiExponent.Main +OAI.NumberTheory.PiExponent.Polynomials.AuxiliaryPolynomial +OAI.NumberTheory.PiExponent.Polynomials.CoefficientLocalizationMaximal +OAI.NumberTheory.PiExponent.Polynomials.ColonHilbertPolynomial +OAI.NumberTheory.PiExponent.Polynomials.CompositePullbackCoefficient +OAI.NumberTheory.PiExponent.Polynomials.ConeHomogeneousEquations +OAI.NumberTheory.PiExponent.Polynomials.CoordinateQuotientGrading +OAI.NumberTheory.PiExponent.Polynomials.FrameCoefficientLaws +OAI.NumberTheory.PiExponent.Polynomials.FrameCoefficients +OAI.NumberTheory.PiExponent.Polynomials.GlobalPolynomialCoefficientLaw +OAI.NumberTheory.PiExponent.Polynomials.GlobalPolynomialWeightedBound +OAI.NumberTheory.PiExponent.Polynomials.GradedLocalizationExact +OAI.NumberTheory.PiExponent.Polynomials.GradedLocalizationFree +OAI.NumberTheory.PiExponent.Polynomials.GradedSerre +OAI.NumberTheory.PiExponent.Polynomials.GradedSerreStep +OAI.NumberTheory.PiExponent.Polynomials.GradedSubring +OAI.NumberTheory.PiExponent.Polynomials.HilbertPolynomial +OAI.NumberTheory.PiExponent.Polynomials.HilbertPolynomialBase +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousComponentLength +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousHilbertExistence +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousHilbertPolynomial +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousIdealStep +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousListHistory +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousPrimeFactor +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousPrimeFiltration +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousQuotientDimension +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousSections +OAI.NumberTheory.PiExponent.Polynomials.HomogeneousSubmoduleGrading +OAI.NumberTheory.PiExponent.Polynomials.Homogenization +OAI.NumberTheory.PiExponent.Polynomials.MixedSlopePolynomial +OAI.NumberTheory.PiExponent.Polynomials.NatToIntGrading +OAI.NumberTheory.PiExponent.Polynomials.NestedPolynomialSwap +OAI.NumberTheory.PiExponent.Polynomials.PolynomialAssociatedLocalization +OAI.NumberTheory.PiExponent.Polynomials.PolynomialCoefficientLocalization +OAI.NumberTheory.PiExponent.Polynomials.PolynomialCoordinateMinpolyQuotient +OAI.NumberTheory.PiExponent.Polynomials.PolynomialCumulative +OAI.NumberTheory.PiExponent.Polynomials.PolynomialFrame +OAI.NumberTheory.PiExponent.Polynomials.PolynomialFrameDegree +OAI.NumberTheory.PiExponent.Polynomials.PolynomialGrowthRanks +OAI.NumberTheory.PiExponent.Polynomials.PolynomialLocalLowExt +OAI.NumberTheory.PiExponent.Polynomials.PolynomialLocalRegularParameters +OAI.NumberTheory.PiExponent.Polynomials.PolynomialLocalResidueResolution +OAI.NumberTheory.PiExponent.Polynomials.PolynomialLocalUnmixedness +OAI.NumberTheory.PiExponent.Polynomials.PolynomialMaximalHeight +OAI.NumberTheory.PiExponent.Polynomials.PolynomialNormalNonzero +OAI.NumberTheory.PiExponent.Polynomials.PolynomialPoleBound +OAI.NumberTheory.PiExponent.Polynomials.PolynomialPrimeClosedPointEquiv +OAI.NumberTheory.PiExponent.Polynomials.PolynomialPrimeDimension +OAI.NumberTheory.PiExponent.Polynomials.PowerCoverBasis +OAI.NumberTheory.PiExponent.Polynomials.PowerCoverExponents +OAI.NumberTheory.PiExponent.Polynomials.PowerCoverSubstitution +OAI.NumberTheory.PiExponent.Polynomials.PullbackFrameCoefficient +OAI.NumberTheory.PiExponent.Polynomials.RationalResidueCoefficientField +OAI.NumberTheory.PiExponent.Polynomials.ShiftedFreeGrading +OAI.NumberTheory.PiExponent.Polynomials.SimplexCounting +OAI.NumberTheory.PiExponent.Polynomials.SimplexFloor +OAI.NumberTheory.PiExponent.Polynomials.SimplexLog +OAI.NumberTheory.PiExponent.Polynomials.SimplexRational +OAI.NumberTheory.PiExponent.Polynomials.SimplexRationalWeights +OAI.NumberTheory.PiExponent.Polynomials.SimplexUnweighted +OAI.NumberTheory.PiExponent.Polynomials.SurjectiveGradedMap +OAI.NumberTheory.PiExponent.Polynomials.TranslatedPowerCover +OAI.NumberTheory.PiExponent.Polynomials.WeightedHomogeneousSubstitution +OAI.NumberTheory.PiExponent.Polynomials.WeightedMonomialFamilyLattice +OAI.NumberTheory.PiExponent.Polynomials.WeightedMonomialImage +OAI.NumberTheory.PiExponent.Polynomials.WeightedMonomialLattice +OAI.NumberTheory.PiExponent.Polynomials.WeightedMonomialMap +OAI.NumberTheory.PiExponent.Polynomials.WeightedMonomialPole +OAI.NumberTheory.PiExponent.Polynomials.WeightedPolynomialPole +OAI.NumberTheory.PiExponent.Statement diff --git a/tasks/pi-exponent/solution/reference.py b/tasks/pi-exponent/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/pi-exponent/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/pi-exponent/solution/solve.sh b/tasks/pi-exponent/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c0be80cdb60f42a341d2c100851d52e5ac0c160 --- /dev/null +++ b/tasks/pi-exponent/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PiExponent, i.e. module OAI.NumberTheory.PiExponent.Main and the +# 869 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.PiExponent.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PiExponent" diff --git a/tasks/pi-exponent/task.toml b/tasks/pi-exponent/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..02596fc80259d6d27e0386d2bc3b72718d7f92dc --- /dev/null +++ b/tasks/pi-exponent/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/pi-exponent" +version = "1.0.0" +description = "Prove PiExponent (openai/math family 017: The irrationality exponent of $\\pi$ is $2$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PiExponent.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PiExponent" +family = "017" +family_title = "The irrationality exponent of $\\pi$ is $2$" +subject = "Number theory" +theorems = ["OAI.PiExponent.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.PiExponent.Main" +reference_modules = 869 +reference_lean_bytes = 4321464 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2882 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 15589 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/pi-exponent/tests/Challenge.lean b/tasks/pi-exponent/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bf78c83492e3f7aa3ab922b13d0b4151e7f601c3 --- /dev/null +++ b/tasks/pi-exponent/tests/Challenge.lean @@ -0,0 +1,19 @@ +import Mathlib + +namespace OAI + +namespace PiExponent + +theorem main : + (∀ ν : ℝ, 2 < ν → ∃ Q : ℤ, 2 ≤ Q ∧ + ∀ p q : ℤ, Q ≤ q → + (q : ℝ) ^ (-ν) ≤ |Real.pi - (p : ℝ) / (q : ℝ)|) ∧ + sSup {ν : ℝ | 0 < ν ∧ + Set.Infinite {r : ℚ | 2 ≤ r.den ∧ + 0 < |Real.pi - (r : ℝ)| ∧ + |Real.pi - (r : ℝ)| < (r.den : ℝ) ^ (-ν)}} = 2 := by + sorry + +end PiExponent + +end OAI diff --git a/tasks/pi-exponent/tests/grade.py b/tasks/pi-exponent/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/pi-exponent/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/pi-exponent/tests/task.json b/tasks/pi-exponent/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1473966056fd6b9ea8bda3a7a2ded14138033f50 --- /dev/null +++ b/tasks/pi-exponent/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PiExponent", + "comparator": { + "theorem_names": [ + "OAI.PiExponent.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14689 +} \ No newline at end of file diff --git a/tasks/pi-exponent/tests/test.sh b/tasks/pi-exponent/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/pi-exponent/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/pinched-kahler/environment/Dockerfile b/tasks/pinched-kahler/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/pinched-kahler/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/pinched-kahler/environment/fetch_mathlib.sh b/tasks/pinched-kahler/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/pinched-kahler/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/pinched-kahler/environment/lake-manifest.json b/tasks/pinched-kahler/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/pinched-kahler/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/pinched-kahler/environment/lakefile.lean b/tasks/pinched-kahler/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/pinched-kahler/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/pinched-kahler/environment/lean_setup.sh b/tasks/pinched-kahler/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/pinched-kahler/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/pinched-kahler/environment/pack_submission.py b/tasks/pinched-kahler/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/pinched-kahler/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/pinched-kahler/instruction.md b/tasks/pinched-kahler/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b5b7a8024fab3001bd77d2a28d3e1788e3b25863 --- /dev/null +++ b/tasks/pinched-kahler/instruction.md @@ -0,0 +1,210 @@ +# openai/math challenge `PinchedKahler` (family 359) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 359 of the release, *Negative Kahler curvature without bounded holomorphic coordinates* +(Differential geometry). The family as a whole: Constructs a contractible domain in $\mathbb C^3$ with a complete negatively pinched Kahler metric but no bounded holomorphic coordinates, disproving bounded-domain uniformization in this setting. A higher-dimensional example has sectional curvature at most $-1$ and only constant bounded holomorphic functions; its curvature is not bounded below. + +The challenge is `PinchedKahler`, also at `/opt/openai-math/challenges/PinchedKahler.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set Filter Topology +open scoped ContDiff + +namespace PinchedHartogs + +abbrev Base := EuclideanSpace ℂ (Fin 2) +abbrev Ambient := Base × ℂ +abbrev Target := Fin 3 → ℂ + +def ball : Set Base := {z | ‖z‖ < 1} + +def hartogs (φ : Base → ℝ) : Set Ambient := + {p | p.1 ∈ ball ∧ Real.exp (φ p.1) * ‖p.2‖ ^ 2 < 1} + +def noMinorant (φ : Base → ℝ) : Prop := + ¬ ∃ (H : Base → ℂ) (C : ℝ), AnalyticOnNhd ℂ H ball ∧ + ∀ z ∈ ball, (H z).re ≤ C + 4 * Real.log (1 / (1 - ‖z‖)) + φ z + +def coordVector (j : Fin 3) : Ambient := + ![(EuclideanSpace.single 0 1, 0), (EuclideanSpace.single 1 1, 0), (0, 1)] j + +def jacobian (F : Ambient → Target) (p : Ambient) : Matrix (Fin 3) (Fin 3) ℂ := + fun i j ↦ (fderiv ℂ F p (coordVector j)) i + +open scoped Matrix.Norms.Elementwise + +abbrev CMatrix := Matrix (Fin 3) (Fin 3) ℂ +abbrev CurvatureTensor := Fin 3 → Fin 3 → Fin 3 → Fin 3 → ℂ + +def coordinates (u : Ambient) : Fin 3 → ℂ := ![u.1 0, u.1 1, u.2] + +def dz (f : Ambient → ℂ) (p : Ambient) (j : Fin 3) : ℂ := + (fderiv ℝ f p (coordVector j) - Complex.I * fderiv ℝ f p (Complex.I • coordVector j)) / 2 + +def dbar (f : Ambient → ℂ) (p : Ambient) (j : Fin 3) : ℂ := + (fderiv ℝ f p (coordVector j) + Complex.I * fderiv ℝ f p (Complex.I • coordVector j)) / 2 + +def hermitianValue (h : CMatrix) (u v : Ambient) : ℂ := + ∑ i, ∑ j, h i j * coordinates u i * star (coordinates v j) + +def realArea (h : CMatrix) (u v : Ambient) : ℝ := + (hermitianValue h u u).re * (hermitianValue h v v).re - (hermitianValue h u v).re ^ 2 + +def tensorValue (R : CurvatureTensor) (u v w y : Ambient) : ℂ := + ∑ a, ∑ b, ∑ c, ∑ d, + R a b c d * coordinates u a * star (coordinates v b) * coordinates w c * star (coordinates y d) + +def curvature (g : Ambient → CMatrix) (p : Ambient) : CurvatureTensor := fun a b c d ↦ + -dbar (fun q ↦ dz (fun r ↦ g r c d) q a) p b + + ∑ e, ∑ k, (g p)⁻¹ e k * dz (fun q ↦ g q c e) p a * dbar (fun q ↦ g q k d) p b + +def sectional (g : Ambient → CMatrix) (p u v : Ambient) : ℝ := + ((tensorValue (curvature g p) u u v v).re - (tensorValue (curvature g p) u v u v).re) / + (2 * realArea (g p) u v) + +def IsKahlerMetric (M : Set Ambient) (g : Ambient → CMatrix) : Prop := + ContDiffOn ℝ ∞ g M ∧ + (∀ p ∈ M, ∀ i j, g p i j = star (g p j i)) ∧ + (∀ p ∈ M, ∀ u : Ambient, u ≠ 0 → 0 < (hermitianValue (g p) u u).re) ∧ + (∀ p ∈ M, ∀ i j k, dz (fun q ↦ g q k j) p i = dz (fun q ↦ g q i j) p k) + +def christoffel (g : Ambient → CMatrix) (p : Ambient) (k a c : Fin 3) : ℂ := + ∑ e, (g p)⁻¹ e k * dz (fun q ↦ g q c e) p a + +def GeodesicallyComplete (M : Set Ambient) (g : Ambient → CMatrix) : Prop := + ∀ p ∈ M, ∀ v : Ambient, ∃ γ : ℝ → Ambient, + ContDiff ℝ ∞ γ ∧ (∀ t, γ t ∈ M) ∧ γ 0 = p ∧ deriv γ 0 = v ∧ + ∀ t k, coordinates (deriv (deriv γ) t) k + + ∑ a, ∑ c, christoffel g (γ t) k a c * coordinates (deriv γ t) a * + coordinates (deriv γ t) c = 0 + +def IsNegativelyPinched (M : Set Ambient) (g : Ambient → CMatrix) (A B : ℝ) : Prop := + 0 < A ∧ A ≤ B ∧ ∀ p ∈ M, ∀ u v : Ambient, LinearIndependent ℝ ![u, v] → + -B ≤ sectional g p u v ∧ sectional g p u v ≤ -A + +def NoBoundedCoordinates (M : Set Ambient) : Prop := + ∀ F : Ambient → Target, AnalyticOnNhd ℂ F M → + (∃ B : ℝ, ∀ p ∈ M, ∀ i, ‖F p i‖ ≤ B) → + ¬ ∀ p ∈ M, (jacobian F p).det ≠ 0 + +def BiholomorphicToBoundedDomain (M : Set Ambient) : Prop := + ∃ N : Set Ambient, IsOpen N ∧ Bornology.IsBounded N ∧ + ∃ F G : Ambient → Ambient, AnalyticOnNhd ℂ F M ∧ AnalyticOnNhd ℂ G N ∧ + MapsTo F M N ∧ MapsTo G N M ∧ (∀ p ∈ M, G (F p) = p) ∧ (∀ q ∈ N, F (G q) = q) + +def MainTheorem : Prop := + ∃ (M : Set Ambient) (g : Ambient → CMatrix) (A B : ℝ), + IsOpen M ∧ M.Nonempty ∧ ContractibleSpace M ∧ IsKahlerMetric M g ∧ + GeodesicallyComplete M g ∧ IsNegativelyPinched M g A B ∧ + NoBoundedCoordinates M ∧ ¬ BiholomorphicToBoundedDomain M + +def psi (z : Base) : ℝ := -Real.log (1 - ‖z‖ ^ 2) +def metricPotential (φ : Base → ℝ) (lam : ℝ) (p : Ambient) : ℝ := + lam * psi p.1 - Real.log (1 - Real.exp (φ p.1) * ‖p.2‖ ^ 2) + +def complexHessian (f : Ambient → ℝ) (p : Ambient) : CMatrix := + fun i j ↦ dz (fun q ↦ dbar (fun r ↦ (f r : ℂ)) q j) p i + +def hartogsMetric (φ : Base → ℝ) (lam : ℝ) : Ambient → CMatrix := + complexHessian (metricPotential φ lam) + +def dzBase (f : Base → ℂ) (z : Base) (i : Fin 2) : ℂ := + (fderiv ℝ f z (EuclideanSpace.single i 1) - + Complex.I * fderiv ℝ f z (Complex.I • EuclideanSpace.single i 1)) / 2 + +def dbarBase (f : Base → ℂ) (z : Base) (i : Fin 2) : ℂ := + (fderiv ℝ f z (EuclideanSpace.single i 1) + + Complex.I * fderiv ℝ f z (Complex.I • EuclideanSpace.single i 1)) / 2 + +def baseHessian (φ : Base → ℝ) (z : Base) : Matrix (Fin 2) (Fin 2) ℂ := + fun i j ↦ dzBase (fun q ↦ dbarBase (fun r ↦ (φ r : ℂ)) q j) z i + +def centeredChart (r : ℝ) (U : Base ≃ₗᵢ[ℂ] Base) (ζ : Base) : Base := + U (WithLp.toLp 2 ![((r : ℂ) + ζ 0) / (1 + (r : ℂ) * ζ 0), + ((Real.sqrt (1 - r ^ 2) : ℝ) : ℂ) * ζ 1 / (1 + (r : ℂ) * ζ 0)]) + +def ChartControl (φ : Base → ℝ) (c C : ℝ) : Prop := + ∀ r : ℝ, 0 ≤ r → r < 1 → ∀ U : Base ≃ₗᵢ[ℂ] Base, ∀ v : Base, + c * ‖v‖ ^ 2 ≤ (∑ i, ∑ j, baseHessian (φ ∘ centeredChart r U) 0 i j * v i * star (v j)).re ∧ + (∑ i, ∑ j, baseHessian (φ ∘ centeredChart r U) 0 i j * v i * star (v j)).re ≤ C * ‖v‖ ^ 2 + +def ChartJets (φ : Base → ℝ) (C : ℝ) : Prop := + ∀ r : ℝ, 0 ≤ r → r < 1 → ∀ U : Base ≃ₗᵢ[ℂ] Base, ∀ i j k l : Fin 2, + ‖dzBase (fun z ↦ baseHessian (φ ∘ centeredChart r U) z i j) 0 k‖ + + ‖dbarBase (fun z ↦ baseHessian (φ ∘ centeredChart r U) z i j) 0 l‖ + + ‖dzBase (fun z ↦ dbarBase (fun q ↦ baseHessian (φ ∘ centeredChart r U) q i j) z l) 0 k‖ ≤ C + +def ControlledPotential : Prop := + ∃ φ : Base → ℝ, ∃ C : ℝ, ContDiffOn ℝ ∞ φ ball ∧ + ChartControl φ 1 C ∧ ChartJets φ C ∧ noMinorant φ + +def MetricTransfer : Prop := + ∀ c C : ℝ, 0 < c → c ≤ C → ∃ lam0 : ℝ, 0 < lam0 ∧ + ∀ φ : Base → ℝ, ContDiffOn ℝ ∞ φ ball → ChartControl φ c C → ChartJets φ C → + ∀ lam : ℝ, lam0 ≤ lam → ContractibleSpace (hartogs φ) ∧ + IsKahlerMetric (hartogs φ) (hartogsMetric φ lam) ∧ + GeodesicallyComplete (hartogs φ) (hartogsMetric φ lam) ∧ + ∃ A B : ℝ, IsNegativelyPinched (hartogs φ) (hartogsMetric φ lam) A B + +theorem main_theorem : MainTheorem := by + sorry + +theorem controlled_potential : ControlledPotential := by + sorry + +theorem metric_transfer : MetricTransfer := by + sorry + +end PinchedHartogs + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PinchedKahler.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.PinchedHartogs.main_theorem`, `OAI.PinchedHartogs.controlled_potential`, `OAI.PinchedHartogs.metric_transfer` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/pinched-kahler/solution/closure.txt b/tasks/pinched-kahler/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f06b50df85a1de6e3439c153a4bcef15df872250 --- /dev/null +++ b/tasks/pinched-kahler/solution/closure.txt @@ -0,0 +1,119 @@ +OAI.Geometry.Kahler.BaseAdaptedHopf +OAI.Geometry.Kahler.BaseAnisotropic +OAI.Geometry.Kahler.BaseCauchyJets +OAI.Geometry.Kahler.BaseCentralComparison +OAI.Geometry.Kahler.BaseCentralSecond +OAI.Geometry.Kahler.BaseChartJets +OAI.Geometry.Kahler.BaseChartLow +OAI.Geometry.Kahler.BaseChartNormalization +OAI.Geometry.Kahler.BaseChartScale +OAI.Geometry.Kahler.BaseChartSeries +OAI.Geometry.Kahler.BaseChartUniform +OAI.Geometry.Kahler.BaseCircleLog +OAI.Geometry.Kahler.BaseCirclePowerLog +OAI.Geometry.Kahler.BaseCompositionJets +OAI.Geometry.Kahler.BaseCorrectionDifferential +OAI.Geometry.Kahler.BaseCorrectionEstimate +OAI.Geometry.Kahler.BaseCorrectionMoments +OAI.Geometry.Kahler.BaseDensityBandwidth +OAI.Geometry.Kahler.BaseDensityDefinitions +OAI.Geometry.Kahler.BaseDensityFourier +OAI.Geometry.Kahler.BaseDensityInduction +OAI.Geometry.Kahler.BaseDensityLowMoments +OAI.Geometry.Kahler.BaseDensityMeasure +OAI.Geometry.Kahler.BaseDensityMoments +OAI.Geometry.Kahler.BaseDensityPatchEstimates +OAI.Geometry.Kahler.BaseDensityScales +OAI.Geometry.Kahler.BaseDensityStep +OAI.Geometry.Kahler.BaseDensityStepSupport +OAI.Geometry.Kahler.BaseDensityTheorem +OAI.Geometry.Kahler.BaseDensityThreshold +OAI.Geometry.Kahler.BaseDensityUpdate +OAI.Geometry.Kahler.BaseGaussian +OAI.Geometry.Kahler.BaseHessianJet +OAI.Geometry.Kahler.BaseHopf +OAI.Geometry.Kahler.BaseHorizontalArc +OAI.Geometry.Kahler.BaseHorizontalGeometry +OAI.Geometry.Kahler.BaseJetNorms +OAI.Geometry.Kahler.BaseLaterComparison +OAI.Geometry.Kahler.BaseLaterMoments +OAI.Geometry.Kahler.BaseLaterNegative +OAI.Geometry.Kahler.BaseLocalSmoothSeries +OAI.Geometry.Kahler.BaseLocalSmoothSeriesOn +OAI.Geometry.Kahler.BaseLogApproximation +OAI.Geometry.Kahler.BaseLogBounds +OAI.Geometry.Kahler.BaseLogFactor +OAI.Geometry.Kahler.BaseLogJetBounds +OAI.Geometry.Kahler.BaseLogPhase +OAI.Geometry.Kahler.BaseLogTests +OAI.Geometry.Kahler.BaseMeans +OAI.Geometry.Kahler.BaseMinorant +OAI.Geometry.Kahler.BaseModelParameters +OAI.Geometry.Kahler.BaseModelSign +OAI.Geometry.Kahler.BaseNegativeScaleBound +OAI.Geometry.Kahler.BaseNegativeThreshold +OAI.Geometry.Kahler.BaseOffPatchMean +OAI.Geometry.Kahler.BaseOrbitGrowth +OAI.Geometry.Kahler.BasePacking +OAI.Geometry.Kahler.BasePatchComparison +OAI.Geometry.Kahler.BasePatchDecomposition +OAI.Geometry.Kahler.BasePatchModel +OAI.Geometry.Kahler.BasePatchPhase +OAI.Geometry.Kahler.BasePatches +OAI.Geometry.Kahler.BasePeakBounds +OAI.Geometry.Kahler.BasePhaseAveraging +OAI.Geometry.Kahler.BasePhaseDerivatives +OAI.Geometry.Kahler.BasePhaseDifferential +OAI.Geometry.Kahler.BasePhaseFourier +OAI.Geometry.Kahler.BasePhaseMoments +OAI.Geometry.Kahler.BasePhaseReal +OAI.Geometry.Kahler.BasePhaseSupport +OAI.Geometry.Kahler.BasePolynomialChange +OAI.Geometry.Kahler.BasePotentialControl +OAI.Geometry.Kahler.BasePotentialSmooth +OAI.Geometry.Kahler.BaseProfileBounds +OAI.Geometry.Kahler.BaseProfiles +OAI.Geometry.Kahler.BaseProjective +OAI.Geometry.Kahler.BaseRadialCancellation +OAI.Geometry.Kahler.BaseRadialLaw +OAI.Geometry.Kahler.BaseRadialMeasure +OAI.Geometry.Kahler.BaseRadialModelError +OAI.Geometry.Kahler.BaseRadialMoments +OAI.Geometry.Kahler.BaseRadialPatch +OAI.Geometry.Kahler.BaseRadialSubstitution +OAI.Geometry.Kahler.BaseRadii +OAI.Geometry.Kahler.BaseRootAveraging +OAI.Geometry.Kahler.BaseScaleSum +OAI.Geometry.Kahler.BaseSeriesBounds +OAI.Geometry.Kahler.BaseShiftAveraging +OAI.Geometry.Kahler.BaseSphere +OAI.Geometry.Kahler.BaseTestAveraging +OAI.Geometry.Kahler.BaseTestSystem +OAI.Geometry.Kahler.BaseWeightedDerivative +OAI.Geometry.Kahler.Definitions +OAI.Geometry.Kahler.HartogsCharts +OAI.Geometry.Kahler.HartogsCompletenessSupport +OAI.Geometry.Kahler.HartogsCurvature +OAI.Geometry.Kahler.HartogsCurvatureContinuity +OAI.Geometry.Kahler.HartogsErrorBounds +OAI.Geometry.Kahler.HartogsFrame +OAI.Geometry.Kahler.HartogsGauge +OAI.Geometry.Kahler.HartogsGaugeTransfer +OAI.Geometry.Kahler.HartogsJetLinearity +OAI.Geometry.Kahler.HartogsJets +OAI.Geometry.Kahler.HartogsLiftedJets +OAI.Geometry.Kahler.HartogsMatrixBounds +OAI.Geometry.Kahler.HartogsModelBridge +OAI.Geometry.Kahler.HartogsNormalBlocks +OAI.Geometry.Kahler.HartogsNormalCurvature +OAI.Geometry.Kahler.HartogsNormalJets +OAI.Geometry.Kahler.HartogsNormalTables +OAI.Geometry.Kahler.HartogsPinching +OAI.Geometry.Kahler.HartogsTensorSymmetry +OAI.Geometry.Kahler.HartogsTopologySupport +OAI.Geometry.Kahler.HartogsTransfer +OAI.Geometry.Kahler.HartogsTransferTools +OAI.Geometry.Kahler.Main +OAI.Geometry.Kahler.MetricCalculus +OAI.Geometry.Kahler.Obstruction +OAI.Geometry.Kahler.PinchingCompact diff --git a/tasks/pinched-kahler/solution/reference.py b/tasks/pinched-kahler/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/pinched-kahler/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/pinched-kahler/solution/solve.sh b/tasks/pinched-kahler/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ebac6c376a8c76ec1f103bb45b032952a1018522 --- /dev/null +++ b/tasks/pinched-kahler/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PinchedKahler, i.e. module OAI.Geometry.Kahler.Main and the +# 119 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.Kahler.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PinchedKahler" diff --git a/tasks/pinched-kahler/task.toml b/tasks/pinched-kahler/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7cd214c8aca413614bb8f477f63c3744e349306e --- /dev/null +++ b/tasks/pinched-kahler/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/pinched-kahler" +version = "1.0.0" +description = "Prove PinchedKahler (openai/math family 359: Negative Kahler curvature without bounded holomorphic coordinates) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PinchedKahler.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PinchedKahler" +family = "359" +family_title = "Negative Kahler curvature without bounded holomorphic coordinates" +subject = "Differential geometry" +theorems = ["OAI.PinchedHartogs.main_theorem", "OAI.PinchedHartogs.controlled_potential", "OAI.PinchedHartogs.metric_transfer"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.Kahler.Main" +reference_modules = 119 +reference_lean_bytes = 921746 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1351 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12529 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/pinched-kahler/tests/Challenge.lean b/tasks/pinched-kahler/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8f55474744633082b995669e1fa7669ea1e7d49e --- /dev/null +++ b/tasks/pinched-kahler/tests/Challenge.lean @@ -0,0 +1,159 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set Filter Topology +open scoped ContDiff + +namespace PinchedHartogs + +abbrev Base := EuclideanSpace ℂ (Fin 2) +abbrev Ambient := Base × ℂ +abbrev Target := Fin 3 → ℂ + +def ball : Set Base := {z | ‖z‖ < 1} + +def hartogs (φ : Base → ℝ) : Set Ambient := + {p | p.1 ∈ ball ∧ Real.exp (φ p.1) * ‖p.2‖ ^ 2 < 1} + +def noMinorant (φ : Base → ℝ) : Prop := + ¬ ∃ (H : Base → ℂ) (C : ℝ), AnalyticOnNhd ℂ H ball ∧ + ∀ z ∈ ball, (H z).re ≤ C + 4 * Real.log (1 / (1 - ‖z‖)) + φ z + +def coordVector (j : Fin 3) : Ambient := + ![(EuclideanSpace.single 0 1, 0), (EuclideanSpace.single 1 1, 0), (0, 1)] j + +def jacobian (F : Ambient → Target) (p : Ambient) : Matrix (Fin 3) (Fin 3) ℂ := + fun i j ↦ (fderiv ℂ F p (coordVector j)) i + +open scoped Matrix.Norms.Elementwise + +abbrev CMatrix := Matrix (Fin 3) (Fin 3) ℂ +abbrev CurvatureTensor := Fin 3 → Fin 3 → Fin 3 → Fin 3 → ℂ + +def coordinates (u : Ambient) : Fin 3 → ℂ := ![u.1 0, u.1 1, u.2] + +def dz (f : Ambient → ℂ) (p : Ambient) (j : Fin 3) : ℂ := + (fderiv ℝ f p (coordVector j) - Complex.I * fderiv ℝ f p (Complex.I • coordVector j)) / 2 + +def dbar (f : Ambient → ℂ) (p : Ambient) (j : Fin 3) : ℂ := + (fderiv ℝ f p (coordVector j) + Complex.I * fderiv ℝ f p (Complex.I • coordVector j)) / 2 + +def hermitianValue (h : CMatrix) (u v : Ambient) : ℂ := + ∑ i, ∑ j, h i j * coordinates u i * star (coordinates v j) + +def realArea (h : CMatrix) (u v : Ambient) : ℝ := + (hermitianValue h u u).re * (hermitianValue h v v).re - (hermitianValue h u v).re ^ 2 + +def tensorValue (R : CurvatureTensor) (u v w y : Ambient) : ℂ := + ∑ a, ∑ b, ∑ c, ∑ d, + R a b c d * coordinates u a * star (coordinates v b) * coordinates w c * star (coordinates y d) + +def curvature (g : Ambient → CMatrix) (p : Ambient) : CurvatureTensor := fun a b c d ↦ + -dbar (fun q ↦ dz (fun r ↦ g r c d) q a) p b + + ∑ e, ∑ k, (g p)⁻¹ e k * dz (fun q ↦ g q c e) p a * dbar (fun q ↦ g q k d) p b + +def sectional (g : Ambient → CMatrix) (p u v : Ambient) : ℝ := + ((tensorValue (curvature g p) u u v v).re - (tensorValue (curvature g p) u v u v).re) / + (2 * realArea (g p) u v) + +def IsKahlerMetric (M : Set Ambient) (g : Ambient → CMatrix) : Prop := + ContDiffOn ℝ ∞ g M ∧ + (∀ p ∈ M, ∀ i j, g p i j = star (g p j i)) ∧ + (∀ p ∈ M, ∀ u : Ambient, u ≠ 0 → 0 < (hermitianValue (g p) u u).re) ∧ + (∀ p ∈ M, ∀ i j k, dz (fun q ↦ g q k j) p i = dz (fun q ↦ g q i j) p k) + +def christoffel (g : Ambient → CMatrix) (p : Ambient) (k a c : Fin 3) : ℂ := + ∑ e, (g p)⁻¹ e k * dz (fun q ↦ g q c e) p a + +def GeodesicallyComplete (M : Set Ambient) (g : Ambient → CMatrix) : Prop := + ∀ p ∈ M, ∀ v : Ambient, ∃ γ : ℝ → Ambient, + ContDiff ℝ ∞ γ ∧ (∀ t, γ t ∈ M) ∧ γ 0 = p ∧ deriv γ 0 = v ∧ + ∀ t k, coordinates (deriv (deriv γ) t) k + + ∑ a, ∑ c, christoffel g (γ t) k a c * coordinates (deriv γ t) a * + coordinates (deriv γ t) c = 0 + +def IsNegativelyPinched (M : Set Ambient) (g : Ambient → CMatrix) (A B : ℝ) : Prop := + 0 < A ∧ A ≤ B ∧ ∀ p ∈ M, ∀ u v : Ambient, LinearIndependent ℝ ![u, v] → + -B ≤ sectional g p u v ∧ sectional g p u v ≤ -A + +def NoBoundedCoordinates (M : Set Ambient) : Prop := + ∀ F : Ambient → Target, AnalyticOnNhd ℂ F M → + (∃ B : ℝ, ∀ p ∈ M, ∀ i, ‖F p i‖ ≤ B) → + ¬ ∀ p ∈ M, (jacobian F p).det ≠ 0 + +def BiholomorphicToBoundedDomain (M : Set Ambient) : Prop := + ∃ N : Set Ambient, IsOpen N ∧ Bornology.IsBounded N ∧ + ∃ F G : Ambient → Ambient, AnalyticOnNhd ℂ F M ∧ AnalyticOnNhd ℂ G N ∧ + MapsTo F M N ∧ MapsTo G N M ∧ (∀ p ∈ M, G (F p) = p) ∧ (∀ q ∈ N, F (G q) = q) + +def MainTheorem : Prop := + ∃ (M : Set Ambient) (g : Ambient → CMatrix) (A B : ℝ), + IsOpen M ∧ M.Nonempty ∧ ContractibleSpace M ∧ IsKahlerMetric M g ∧ + GeodesicallyComplete M g ∧ IsNegativelyPinched M g A B ∧ + NoBoundedCoordinates M ∧ ¬ BiholomorphicToBoundedDomain M + +def psi (z : Base) : ℝ := -Real.log (1 - ‖z‖ ^ 2) +def metricPotential (φ : Base → ℝ) (lam : ℝ) (p : Ambient) : ℝ := + lam * psi p.1 - Real.log (1 - Real.exp (φ p.1) * ‖p.2‖ ^ 2) + +def complexHessian (f : Ambient → ℝ) (p : Ambient) : CMatrix := + fun i j ↦ dz (fun q ↦ dbar (fun r ↦ (f r : ℂ)) q j) p i + +def hartogsMetric (φ : Base → ℝ) (lam : ℝ) : Ambient → CMatrix := + complexHessian (metricPotential φ lam) + +def dzBase (f : Base → ℂ) (z : Base) (i : Fin 2) : ℂ := + (fderiv ℝ f z (EuclideanSpace.single i 1) - + Complex.I * fderiv ℝ f z (Complex.I • EuclideanSpace.single i 1)) / 2 + +def dbarBase (f : Base → ℂ) (z : Base) (i : Fin 2) : ℂ := + (fderiv ℝ f z (EuclideanSpace.single i 1) + + Complex.I * fderiv ℝ f z (Complex.I • EuclideanSpace.single i 1)) / 2 + +def baseHessian (φ : Base → ℝ) (z : Base) : Matrix (Fin 2) (Fin 2) ℂ := + fun i j ↦ dzBase (fun q ↦ dbarBase (fun r ↦ (φ r : ℂ)) q j) z i + +def centeredChart (r : ℝ) (U : Base ≃ₗᵢ[ℂ] Base) (ζ : Base) : Base := + U (WithLp.toLp 2 ![((r : ℂ) + ζ 0) / (1 + (r : ℂ) * ζ 0), + ((Real.sqrt (1 - r ^ 2) : ℝ) : ℂ) * ζ 1 / (1 + (r : ℂ) * ζ 0)]) + +def ChartControl (φ : Base → ℝ) (c C : ℝ) : Prop := + ∀ r : ℝ, 0 ≤ r → r < 1 → ∀ U : Base ≃ₗᵢ[ℂ] Base, ∀ v : Base, + c * ‖v‖ ^ 2 ≤ (∑ i, ∑ j, baseHessian (φ ∘ centeredChart r U) 0 i j * v i * star (v j)).re ∧ + (∑ i, ∑ j, baseHessian (φ ∘ centeredChart r U) 0 i j * v i * star (v j)).re ≤ C * ‖v‖ ^ 2 + +def ChartJets (φ : Base → ℝ) (C : ℝ) : Prop := + ∀ r : ℝ, 0 ≤ r → r < 1 → ∀ U : Base ≃ₗᵢ[ℂ] Base, ∀ i j k l : Fin 2, + ‖dzBase (fun z ↦ baseHessian (φ ∘ centeredChart r U) z i j) 0 k‖ + + ‖dbarBase (fun z ↦ baseHessian (φ ∘ centeredChart r U) z i j) 0 l‖ + + ‖dzBase (fun z ↦ dbarBase (fun q ↦ baseHessian (φ ∘ centeredChart r U) q i j) z l) 0 k‖ ≤ C + +def ControlledPotential : Prop := + ∃ φ : Base → ℝ, ∃ C : ℝ, ContDiffOn ℝ ∞ φ ball ∧ + ChartControl φ 1 C ∧ ChartJets φ C ∧ noMinorant φ + +def MetricTransfer : Prop := + ∀ c C : ℝ, 0 < c → c ≤ C → ∃ lam0 : ℝ, 0 < lam0 ∧ + ∀ φ : Base → ℝ, ContDiffOn ℝ ∞ φ ball → ChartControl φ c C → ChartJets φ C → + ∀ lam : ℝ, lam0 ≤ lam → ContractibleSpace (hartogs φ) ∧ + IsKahlerMetric (hartogs φ) (hartogsMetric φ lam) ∧ + GeodesicallyComplete (hartogs φ) (hartogsMetric φ lam) ∧ + ∃ A B : ℝ, IsNegativelyPinched (hartogs φ) (hartogsMetric φ lam) A B + +theorem main_theorem : MainTheorem := by + sorry + +theorem controlled_potential : ControlledPotential := by + sorry + +theorem metric_transfer : MetricTransfer := by + sorry + +end PinchedHartogs + +end + +end OAI diff --git a/tasks/pinched-kahler/tests/grade.py b/tasks/pinched-kahler/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/pinched-kahler/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/pinched-kahler/tests/task.json b/tasks/pinched-kahler/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..558186f114a953ac56bfac7699e6aa8b4bd8c3b9 --- /dev/null +++ b/tasks/pinched-kahler/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "PinchedKahler", + "comparator": { + "theorem_names": [ + "OAI.PinchedHartogs.main_theorem", + "OAI.PinchedHartogs.controlled_potential", + "OAI.PinchedHartogs.metric_transfer" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11629 +} \ No newline at end of file diff --git a/tasks/pinched-kahler/tests/test.sh b/tasks/pinched-kahler/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/pinched-kahler/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/pinned-distances/environment/Dockerfile b/tasks/pinned-distances/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/pinned-distances/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/pinned-distances/environment/fetch_mathlib.sh b/tasks/pinned-distances/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/pinned-distances/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/pinned-distances/environment/lake-manifest.json b/tasks/pinned-distances/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/pinned-distances/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/pinned-distances/environment/lakefile.lean b/tasks/pinned-distances/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/pinned-distances/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/pinned-distances/environment/lean_setup.sh b/tasks/pinned-distances/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/pinned-distances/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/pinned-distances/environment/pack_submission.py b/tasks/pinned-distances/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/pinned-distances/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/pinned-distances/instruction.md b/tasks/pinned-distances/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..bfa40011aa38ed78137dfad2224fa8bb4c10d5f0 --- /dev/null +++ b/tasks/pinned-distances/instruction.md @@ -0,0 +1,87 @@ +# openai/math challenge `PinnedDistances` (family 167) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 167 of the release, *Pinned distances and a power saving for planar unit distances* +(Combinatorics). The family as a whole: Proves the weak pinned Erd\H{o}s distance conjecture: for every fixed $\varepsilon>0$, all but $o(n)$ points of any $n$-point planar set determine at least $n^{1-\varepsilon}$ distinct nonzero distances. A complementary theorem bounds the number of unit-distance pairs by $O(n^{4/3-\delta})$ for an absolute $\delta>0$. + +The challenge is `PinnedDistances`, also at `/opt/openai-math/challenges/PinnedDistances.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Filter +open scoped Topology + +namespace WeakPinned +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def distanceFiber (P : Finset Plane) (x y : Plane) : Finset Plane := + (P.erase x).filter (fun z => dist z x = dist y x) + +def k (P : Finset Plane) (x y : Plane) : ℕ := + (distanceFiber P x y).card + +def richPairs (P : Finset Plane) (s : ℝ) : Finset (Plane × Plane) := + (P ×ˢ P).filter (fun xy => xy.1 ≠ xy.2 ∧ + (P.card : ℝ) ^ s ≤ (k P xy.1 xy.2 : ℝ)) + +def pairFraction (P : Finset Plane) (s : ℝ) : ℝ := + (richPairs P s).card / ((P.card : ℝ) * ((P.card : ℝ) - 1)) + +def F (n : ℕ) (s : ℝ) : ℝ := + if 2 ≤ n then sSup {a : ℝ | ∃ P : Finset Plane, P.card = n ∧ a = pairFraction P s} + else 0 + +theorem main (s : ℝ) (hs : 0 F n s) atTop (𝓝 0) := by + sorry + +end WeakPinned + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PinnedDistances.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WeakPinned.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/pinned-distances/solution/closure.txt b/tasks/pinned-distances/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c1b7229713d31592322ac2f758a83671450fe4ec --- /dev/null +++ b/tasks/pinned-distances/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Geometry.PinnedDistances.ArithmeticContradiction +OAI.Geometry.PinnedDistances.ArithmeticGraphs +OAI.Geometry.PinnedDistances.ArithmeticHierarchy +OAI.Geometry.PinnedDistances.ArithmeticSequence +OAI.Geometry.PinnedDistances.ArithmeticVariance +OAI.Geometry.PinnedDistances.BoundedContradiction +OAI.Geometry.PinnedDistances.BoundedRates +OAI.Geometry.PinnedDistances.ChartLimits +OAI.Geometry.PinnedDistances.ConditionalIntegral +OAI.Geometry.PinnedDistances.CutApproximation +OAI.Geometry.PinnedDistances.CutGeometry +OAI.Geometry.PinnedDistances.EmpiricalCompactness +OAI.Geometry.PinnedDistances.EnergyLaw +OAI.Geometry.PinnedDistances.ExtremalCore +OAI.Geometry.PinnedDistances.ExtremalFractions +OAI.Geometry.PinnedDistances.FiberOverlap +OAI.Geometry.PinnedDistances.FiberTransport +OAI.Geometry.PinnedDistances.FiniteLaw +OAI.Geometry.PinnedDistances.FiniteMixtures +OAI.Geometry.PinnedDistances.FiniteObstruction +OAI.Geometry.PinnedDistances.GlobalOverlap +OAI.Geometry.PinnedDistances.GlobalPotentials +OAI.Geometry.PinnedDistances.GridBounds +OAI.Geometry.PinnedDistances.Hierarchy +OAI.Geometry.PinnedDistances.IncomingFibers +OAI.Geometry.PinnedDistances.LimitObstruction +OAI.Geometry.PinnedDistances.LogBounds +OAI.Geometry.PinnedDistances.Main +OAI.Geometry.PinnedDistances.MeasureLimits +OAI.Geometry.PinnedDistances.MinPotentials +OAI.Geometry.PinnedDistances.MixtureLaw +OAI.Geometry.PinnedDistances.MobiusObstruction +OAI.Geometry.PinnedDistances.Model +OAI.Geometry.PinnedDistances.NormalizedGraphs +OAI.Geometry.PinnedDistances.OverlapRates +OAI.Geometry.PinnedDistances.PartitionIntegrals +OAI.Geometry.PinnedDistances.ProductFormula +OAI.Geometry.PinnedDistances.ProductLimits +OAI.Geometry.PinnedDistances.RandomGrids +OAI.Geometry.PinnedDistances.SmallCells +OAI.Geometry.PinnedDistances.TreeContradiction +OAI.Geometry.PinnedDistances.TreeTransport +OAI.Geometry.PinnedDistances.UnboundedContradiction +OAI.Geometry.PinnedDistances.UniformCore +OAI.Geometry.PinnedDistances.Variance +OAI.Geometry.PinnedDistances.VarianceRates +OAI.Geometry.PinnedDistances.WeightedSelection diff --git a/tasks/pinned-distances/solution/reference.py b/tasks/pinned-distances/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/pinned-distances/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/pinned-distances/solution/solve.sh b/tasks/pinned-distances/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..688294368b8fc61753ab9a8ee2cec807ca00bc63 --- /dev/null +++ b/tasks/pinned-distances/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PinnedDistances, i.e. module OAI.Geometry.PinnedDistances.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.PinnedDistances.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PinnedDistances" diff --git a/tasks/pinned-distances/task.toml b/tasks/pinned-distances/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..80890049432c899743b322a61bff3c8cb8495e16 --- /dev/null +++ b/tasks/pinned-distances/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/pinned-distances" +version = "1.0.0" +description = "Prove PinnedDistances (openai/math family 167: Pinned distances and a power saving for planar unit distances) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PinnedDistances.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PinnedDistances" +family = "167" +family_title = "Pinned distances and a power saving for planar unit distances" +subject = "Combinatorics" +theorems = ["OAI.WeakPinned.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.PinnedDistances.Main" +reference_modules = 47 +reference_lean_bytes = 739601 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 926 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12365 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/pinned-distances/tests/Challenge.lean b/tasks/pinned-distances/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b21ebbe370ea1424d956a10613471e9ff4c5a8fd --- /dev/null +++ b/tasks/pinned-distances/tests/Challenge.lean @@ -0,0 +1,36 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Filter +open scoped Topology + +namespace WeakPinned +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def distanceFiber (P : Finset Plane) (x y : Plane) : Finset Plane := + (P.erase x).filter (fun z => dist z x = dist y x) + +def k (P : Finset Plane) (x y : Plane) : ℕ := + (distanceFiber P x y).card + +def richPairs (P : Finset Plane) (s : ℝ) : Finset (Plane × Plane) := + (P ×ˢ P).filter (fun xy => xy.1 ≠ xy.2 ∧ + (P.card : ℝ) ^ s ≤ (k P xy.1 xy.2 : ℝ)) + +def pairFraction (P : Finset Plane) (s : ℝ) : ℝ := + (richPairs P s).card / ((P.card : ℝ) * ((P.card : ℝ) - 1)) + +def F (n : ℕ) (s : ℝ) : ℝ := + if 2 ≤ n then sSup {a : ℝ | ∃ P : Finset Plane, P.card = n ∧ a = pairFraction P s} + else 0 + +theorem main (s : ℝ) (hs : 0 F n s) atTop (𝓝 0) := by + sorry + +end WeakPinned + +end + +end OAI diff --git a/tasks/pinned-distances/tests/grade.py b/tasks/pinned-distances/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/pinned-distances/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/pinned-distances/tests/task.json b/tasks/pinned-distances/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..76f6e1e1a607eb4cb1715cd26d9a4d970625204f --- /dev/null +++ b/tasks/pinned-distances/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PinnedDistances", + "comparator": { + "theorem_names": [ + "OAI.WeakPinned.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11465 +} \ No newline at end of file diff --git a/tasks/pinned-distances/tests/test.sh b/tasks/pinned-distances/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/pinned-distances/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/planar-anderson-spectrum/environment/Dockerfile b/tasks/planar-anderson-spectrum/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/planar-anderson-spectrum/environment/fetch_mathlib.sh b/tasks/planar-anderson-spectrum/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/planar-anderson-spectrum/environment/lake-manifest.json b/tasks/planar-anderson-spectrum/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/planar-anderson-spectrum/environment/lakefile.lean b/tasks/planar-anderson-spectrum/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/planar-anderson-spectrum/environment/lean_setup.sh b/tasks/planar-anderson-spectrum/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/planar-anderson-spectrum/environment/pack_submission.py b/tasks/planar-anderson-spectrum/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/planar-anderson-spectrum/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/planar-anderson-spectrum/instruction.md b/tasks/planar-anderson-spectrum/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5991a961f4e746352465ee911e0aa2a603e5ba36 --- /dev/null +++ b/tasks/planar-anderson-spectrum/instruction.md @@ -0,0 +1,86 @@ +# openai/math challenge `PlanarAndersonSpectrum` (family 261) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 261 of the release, *Localization and delocalization in the Anderson model* +(Mathematical physics). The family as a whole: Resolves the predicted spectral contrast for the lattice Anderson model with independent uniform site potentials. In dimension two, every positive disorder strength gives almost surely pure-point spectrum. In every fixed dimension $d\ge3$, sufficiently weak positive disorder gives purely absolutely continuous spectrum on a fixed open interval with nonzero spectral weight. + +The challenge is `PlanarAndersonSpectrum`, also at `/opt/openai-math/challenges/PlanarAndersonSpectrum.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace PlanarAnderson + +abbrev Site := ℤ × ℤ +abbrev Configuration := Site → ℝ +abbrev Hilbert := lp (fun _ : Site => ℂ) 2 + +def disorderLaw (h : ℝ) : Measure Configuration := + Measure.infinitePi (fun _ : Site => ProbabilityTheory.cond volume (Set.Icc (-h) h)) + +def IsAndersonOperator (v : Configuration) (H : Hilbert →L[ℂ] Hilbert) : Prop := + ∀ (u : Hilbert) (x : Site), + (H u) x = u (x.1 + 1, x.2) + u (x.1 - 1, x.2) + + u (x.1, x.2 + 1) + u (x.1, x.2 - 1) + (v x : ℂ) * u x + +def spectralInterval (h : ℝ) : Set ℂ := + {z | z.im = 0 ∧ -4 - h ≤ z.re ∧ z.re ≤ 4 + h} + +theorem anderson_spectrum_ae {h : ℝ} (hh : 0 < h) : + ∀ᵐ v ∂disorderLaw h, ∃ H : Hilbert →L[ℂ] Hilbert, + IsAndersonOperator v H ∧ IsSelfAdjoint H ∧ spectrum ℂ H = spectralInterval h := by + sorry + +end PlanarAnderson + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlanarAndersonSpectrum.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarAnderson.anderson_spectrum_ae` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/planar-anderson-spectrum/solution/closure.txt b/tasks/planar-anderson-spectrum/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ded66c5bc9e6122c4f62ebe354542411fbb1a180 --- /dev/null +++ b/tasks/planar-anderson-spectrum/solution/closure.txt @@ -0,0 +1 @@ +OAI.MathematicalPhysics.PlanarAnderson.Spectrum diff --git a/tasks/planar-anderson-spectrum/solution/reference.py b/tasks/planar-anderson-spectrum/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/planar-anderson-spectrum/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/planar-anderson-spectrum/solution/solve.sh b/tasks/planar-anderson-spectrum/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..62a2d512339ce04818859134a8ad8d16a2ecbeb9 --- /dev/null +++ b/tasks/planar-anderson-spectrum/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlanarAndersonSpectrum, i.e. module OAI.MathematicalPhysics.PlanarAnderson.Spectrum and the +# 1 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.PlanarAnderson.Spectrum /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlanarAndersonSpectrum" diff --git a/tasks/planar-anderson-spectrum/task.toml b/tasks/planar-anderson-spectrum/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ec778533c661aa96e42724493d31f05a739e3301 --- /dev/null +++ b/tasks/planar-anderson-spectrum/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/planar-anderson-spectrum" +version = "1.0.0" +description = "Prove PlanarAndersonSpectrum (openai/math family 261: Localization and delocalization in the Anderson model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlanarAndersonSpectrum.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlanarAndersonSpectrum" +family = "261" +family_title = "Localization and delocalization in the Anderson model" +subject = "Mathematical physics" +theorems = ["OAI.PlanarAnderson.anderson_spectrum_ae"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.PlanarAnderson.Spectrum" +reference_modules = 1 +reference_lean_bytes = 35165 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 582 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11731 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/planar-anderson-spectrum/tests/Challenge.lean b/tasks/planar-anderson-spectrum/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..aac6e079c38b70768c57c325ea97467682e19697 --- /dev/null +++ b/tasks/planar-anderson-spectrum/tests/Challenge.lean @@ -0,0 +1,35 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory +open scoped ENNReal + +namespace PlanarAnderson + +abbrev Site := ℤ × ℤ +abbrev Configuration := Site → ℝ +abbrev Hilbert := lp (fun _ : Site => ℂ) 2 + +def disorderLaw (h : ℝ) : Measure Configuration := + Measure.infinitePi (fun _ : Site => ProbabilityTheory.cond volume (Set.Icc (-h) h)) + +def IsAndersonOperator (v : Configuration) (H : Hilbert →L[ℂ] Hilbert) : Prop := + ∀ (u : Hilbert) (x : Site), + (H u) x = u (x.1 + 1, x.2) + u (x.1 - 1, x.2) + + u (x.1, x.2 + 1) + u (x.1, x.2 - 1) + (v x : ℂ) * u x + +def spectralInterval (h : ℝ) : Set ℂ := + {z | z.im = 0 ∧ -4 - h ≤ z.re ∧ z.re ≤ 4 + h} + +theorem anderson_spectrum_ae {h : ℝ} (hh : 0 < h) : + ∀ᵐ v ∂disorderLaw h, ∃ H : Hilbert →L[ℂ] Hilbert, + IsAndersonOperator v H ∧ IsSelfAdjoint H ∧ spectrum ℂ H = spectralInterval h := by + sorry + +end PlanarAnderson + +end + +end OAI diff --git a/tasks/planar-anderson-spectrum/tests/grade.py b/tasks/planar-anderson-spectrum/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/planar-anderson-spectrum/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/planar-anderson-spectrum/tests/task.json b/tasks/planar-anderson-spectrum/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2d4f7d8efb094fedffa920ad0542d8de72ed036f --- /dev/null +++ b/tasks/planar-anderson-spectrum/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlanarAndersonSpectrum", + "comparator": { + "theorem_names": [ + "OAI.PlanarAnderson.anderson_spectrum_ae" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10831 +} \ No newline at end of file diff --git a/tasks/planar-anderson-spectrum/tests/test.sh b/tasks/planar-anderson-spectrum/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/planar-anderson-spectrum/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/planar-falconer/environment/Dockerfile b/tasks/planar-falconer/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/planar-falconer/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/planar-falconer/environment/fetch_mathlib.sh b/tasks/planar-falconer/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/planar-falconer/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/planar-falconer/environment/lake-manifest.json b/tasks/planar-falconer/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/planar-falconer/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/planar-falconer/environment/lakefile.lean b/tasks/planar-falconer/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/planar-falconer/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/planar-falconer/environment/lean_setup.sh b/tasks/planar-falconer/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/planar-falconer/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/planar-falconer/environment/pack_submission.py b/tasks/planar-falconer/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/planar-falconer/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/planar-falconer/instruction.md b/tasks/planar-falconer/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8eadffd79f1579fca2f623ab9c75b880ec7afe4d --- /dev/null +++ b/tasks/planar-falconer/instruction.md @@ -0,0 +1,76 @@ +# openai/math challenge `PlanarFalconer` (family 073) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 073 of the release, *The Falconer distance conjecture* +(Real and complex analysis). The family as a whole: Resolves the Falconer distance conjecture in every dimension $d\ge2$: every compact set $E\subset\mathbb R^d$ with Hausdorff dimension greater than $d/2$ determines a set of Euclidean distances of positive Lebesgue measure. + +The challenge is `PlanarFalconer`, also at `/opt/openai-math/challenges/PlanarFalconer.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PlanarFalconer +open MeasureTheory Set + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def distanceSet (E : Set Plane) : Set ℝ := + {r | ∃ x ∈ E, ∃ y ∈ E, dist x y = r} + +def MainTarget : Prop := + ∀ E : Set Plane, IsCompact E → 1 < dimH E → 0 < volume (distanceSet E) + +end PlanarFalconer + +namespace PlanarFalconer + +theorem mainTarget_proved : MainTarget := by + sorry + +end PlanarFalconer + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlanarFalconer.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarFalconer.mainTarget_proved` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/planar-falconer/solution/closure.txt b/tasks/planar-falconer/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3bba074ced66f9e8886c124ab454d535afc4d23 --- /dev/null +++ b/tasks/planar-falconer/solution/closure.txt @@ -0,0 +1,719 @@ +OAI.MeasureTheory.Falconer.Angular.ActualAngleMasks +OAI.MeasureTheory.Falconer.Angular.ActualAngularDropping +OAI.MeasureTheory.Falconer.Angular.ActualAngularEquation23 +OAI.MeasureTheory.Falconer.Angular.ActualAngularNear +OAI.MeasureTheory.Falconer.Angular.ActualAngularNearDropping +OAI.MeasureTheory.Falconer.Angular.ActualAngularRecursionBound +OAI.MeasureTheory.Falconer.Angular.ActualAngularRegularization +OAI.MeasureTheory.Falconer.Angular.ActualAngularTerminal +OAI.MeasureTheory.Falconer.Angular.ActualAngularTests +OAI.MeasureTheory.Falconer.Angular.ActualFarCircleExpansion +OAI.MeasureTheory.Falconer.Angular.ActualFarStationaryReduction +OAI.MeasureTheory.Falconer.Angular.ActualFourStationarySupport +OAI.MeasureTheory.Falconer.Angular.ActualFullCircleStationary +OAI.MeasureTheory.Falconer.Angular.ActualInactiveCircle +OAI.MeasureTheory.Falconer.Angular.ActualSingleStationaryKernel +OAI.MeasureTheory.Falconer.Angular.ActualStationaryAmplitude +OAI.MeasureTheory.Falconer.Angular.ActualStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.ActualStationaryProductKernel +OAI.MeasureTheory.Falconer.Angular.ActualStationarySpatialIntegrability +OAI.MeasureTheory.Falconer.Angular.ActualTwoPointStationary +OAI.MeasureTheory.Falconer.Angular.AngleBumpScaling +OAI.MeasureTheory.Falconer.Angular.AngleCoordinateTests +OAI.MeasureTheory.Falconer.Angular.AngleMaskDerivatives +OAI.MeasureTheory.Falconer.Angular.AngleMaskPeriodicity +OAI.MeasureTheory.Falconer.Angular.AngularBinKernel +OAI.MeasureTheory.Falconer.Angular.AngularBinSelection +OAI.MeasureTheory.Falconer.Angular.AngularCellKernels +OAI.MeasureTheory.Falconer.Angular.AngularCellSpatialIntegral +OAI.MeasureTheory.Falconer.Angular.AngularComparableCarrier +OAI.MeasureTheory.Falconer.Angular.AngularCountMean +OAI.MeasureTheory.Falconer.Angular.AngularDifferentialBounds +OAI.MeasureTheory.Falconer.Angular.AngularDifferentialExpr +OAI.MeasureTheory.Falconer.Angular.AngularDroppedMaximum +OAI.MeasureTheory.Falconer.Angular.AngularDyadicSum +OAI.MeasureTheory.Falconer.Angular.AngularEnergyDropping +OAI.MeasureTheory.Falconer.Angular.AngularFarDepth +OAI.MeasureTheory.Falconer.Angular.AngularFarGeometry +OAI.MeasureTheory.Falconer.Angular.AngularFarSeparation +OAI.MeasureTheory.Falconer.Angular.AngularFarSpatialSum +OAI.MeasureTheory.Falconer.Angular.AngularFarStationaryScale +OAI.MeasureTheory.Falconer.Angular.AngularFourCellMass +OAI.MeasureTheory.Falconer.Angular.AngularFourSpatialIntegral +OAI.MeasureTheory.Falconer.Angular.AngularIntegrability +OAI.MeasureTheory.Falconer.Angular.AngularIntegrationByParts +OAI.MeasureTheory.Falconer.Angular.AngularKernelIntegral +OAI.MeasureTheory.Falconer.Angular.AngularLabelEligibility +OAI.MeasureTheory.Falconer.Angular.AngularLengthIntegralPartition +OAI.MeasureTheory.Falconer.Angular.AngularLengthPartition +OAI.MeasureTheory.Falconer.Angular.AngularMeanAssembly +OAI.MeasureTheory.Falconer.Angular.AngularNearIntegral +OAI.MeasureTheory.Falconer.Angular.AngularNearNeighbors +OAI.MeasureTheory.Falconer.Angular.AngularNearProfile +OAI.MeasureTheory.Falconer.Angular.AngularNearProgress +OAI.MeasureTheory.Falconer.Angular.AngularNearSum +OAI.MeasureTheory.Falconer.Angular.AngularNoncomparableCarrier +OAI.MeasureTheory.Falconer.Angular.AngularNonstationary +OAI.MeasureTheory.Falconer.Angular.AngularNonstationaryPower +OAI.MeasureTheory.Falconer.Angular.AngularOccupiedFarPartition +OAI.MeasureTheory.Falconer.Angular.AngularOccupiedPartition +OAI.MeasureTheory.Falconer.Angular.AngularOperatorTerms +OAI.MeasureTheory.Falconer.Angular.AngularOriginalFarPartition +OAI.MeasureTheory.Falconer.Angular.AngularOriginalIntegrability +OAI.MeasureTheory.Falconer.Angular.AngularPairCircleIntegral +OAI.MeasureTheory.Falconer.Angular.AngularParentNearFar +OAI.MeasureTheory.Falconer.Angular.AngularProductEnergyIntegral +OAI.MeasureTheory.Falconer.Angular.AngularProfileSum +OAI.MeasureTheory.Falconer.Angular.AngularRadialKernel +OAI.MeasureTheory.Falconer.Angular.AngularRestrictedIntegralSum +OAI.MeasureTheory.Falconer.Angular.AngularRestrictedKernel +OAI.MeasureTheory.Falconer.Angular.AngularStateContributions +OAI.MeasureTheory.Falconer.Angular.AngularStateData +OAI.MeasureTheory.Falconer.Angular.AngularStateDropping +OAI.MeasureTheory.Falconer.Angular.AngularStateNearFar +OAI.MeasureTheory.Falconer.Angular.AngularStateSuccessor +OAI.MeasureTheory.Falconer.Angular.AngularStationaryRadialError +OAI.MeasureTheory.Falconer.Angular.AngularStationarySpatial +OAI.MeasureTheory.Falconer.Angular.AngularStripIntervals +OAI.MeasureTheory.Falconer.Angular.AngularStripMeasure +OAI.MeasureTheory.Falconer.Angular.AngularTerminalBound +OAI.MeasureTheory.Falconer.Angular.AngularTransform +OAI.MeasureTheory.Falconer.Angular.AngularTransformSplitting +OAI.MeasureTheory.Falconer.Angular.AngularTransportBounds +OAI.MeasureTheory.Falconer.Angular.AngularUniformAbsorption +OAI.MeasureTheory.Falconer.Angular.AngularWidths +OAI.MeasureTheory.Falconer.Angular.CircleAngularBins +OAI.MeasureTheory.Falconer.Angular.CircleDirectCoefficients +OAI.MeasureTheory.Falconer.Angular.CircleLocalIntegral +OAI.MeasureTheory.Falconer.Angular.CircleMaskCoordinates +OAI.MeasureTheory.Falconer.Angular.CircleMaskSupport +OAI.MeasureTheory.Falconer.Angular.CircleResidualDecay +OAI.MeasureTheory.Falconer.Angular.CircleRotation +OAI.MeasureTheory.Falconer.Angular.CircleStationaryPartition +OAI.MeasureTheory.Falconer.Angular.CircleTests +OAI.MeasureTheory.Falconer.Angular.CommonProfileAngularNear +OAI.MeasureTheory.Falconer.Angular.CompactCircleResidual +OAI.MeasureTheory.Falconer.Angular.CompactStationaryAmplitude +OAI.MeasureTheory.Falconer.Angular.FiniteAngularSquare +OAI.MeasureTheory.Falconer.Angular.FourStationarySupport +OAI.MeasureTheory.Falconer.Angular.FullCircleDecomposition +OAI.MeasureTheory.Falconer.Angular.FullCircleStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.FullCircleStationaryPower +OAI.MeasureTheory.Falconer.Angular.GraphAngleCharts +OAI.MeasureTheory.Falconer.Angular.GraphAngularCoordinates +OAI.MeasureTheory.Falconer.Angular.GraphRotatedWeights +OAI.MeasureTheory.Falconer.Angular.GraphTorusAngles +OAI.MeasureTheory.Falconer.Angular.InheritedAngularSymbols +OAI.MeasureTheory.Falconer.Angular.InheritedCircleRegularity +OAI.MeasureTheory.Falconer.Angular.InverseCircleArcLength +OAI.MeasureTheory.Falconer.Angular.InverseCircleAssembly +OAI.MeasureTheory.Falconer.Angular.InverseCirclePower +OAI.MeasureTheory.Falconer.Angular.InverseStationaryCancellation +OAI.MeasureTheory.Falconer.Angular.InverseStationaryCutoff +OAI.MeasureTheory.Falconer.Angular.InverseStationaryOperators +OAI.MeasureTheory.Falconer.Angular.InverseStationaryRemainder +OAI.MeasureTheory.Falconer.Angular.InverseStationaryScales +OAI.MeasureTheory.Falconer.Angular.InverseStationaryTriangle +OAI.MeasureTheory.Falconer.Angular.InverseStationaryWeighted +OAI.MeasureTheory.Falconer.Angular.LocalizedStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.MeasurableAngularJets +OAI.MeasureTheory.Falconer.Angular.NormalizedStationaryJet +OAI.MeasureTheory.Falconer.Angular.PeriodicAngularBins +OAI.MeasureTheory.Falconer.Angular.ProjectionAngularGeometry +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryIdentity +OAI.MeasureTheory.Falconer.Angular.QuadraticStationaryL1 +OAI.MeasureTheory.Falconer.Angular.RadialStationaryProfile +OAI.MeasureTheory.Falconer.Angular.ReciprocalSineBounds +OAI.MeasureTheory.Falconer.Angular.RegularizedAngularNear +OAI.MeasureTheory.Falconer.Angular.RetainedAngularFailure +OAI.MeasureTheory.Falconer.Angular.RootStationaryScale +OAI.MeasureTheory.Falconer.Angular.RotatedActualInactive +OAI.MeasureTheory.Falconer.Angular.RotatedBinPartition +OAI.MeasureTheory.Falconer.Angular.RotatedCircleIntegral +OAI.MeasureTheory.Falconer.Angular.RotatedConeKernel +OAI.MeasureTheory.Falconer.Angular.RotatedGraphEligibility +OAI.MeasureTheory.Falconer.Angular.RotatedInverseCircle +OAI.MeasureTheory.Falconer.Angular.RotatedParallelCandidates +OAI.MeasureTheory.Falconer.Angular.RotatedScaleNonstationary +OAI.MeasureTheory.Falconer.Angular.ScaledAngularTransport +OAI.MeasureTheory.Falconer.Angular.SelectedAngularBins +OAI.MeasureTheory.Falconer.Angular.SignedStationaryExpansion +OAI.MeasureTheory.Falconer.Angular.SignedStationaryJet +OAI.MeasureTheory.Falconer.Angular.SignedStationaryRadial +OAI.MeasureTheory.Falconer.Angular.SingleStationaryAngular +OAI.MeasureTheory.Falconer.Angular.SingleStationaryIntegral +OAI.MeasureTheory.Falconer.Angular.SingleStationaryRadial +OAI.MeasureTheory.Falconer.Angular.SmoothAngleMask +OAI.MeasureTheory.Falconer.Angular.SmoothInverseSine +OAI.MeasureTheory.Falconer.Angular.SmoothRotatedCone +OAI.MeasureTheory.Falconer.Angular.SourceAngularDirect +OAI.MeasureTheory.Falconer.Angular.SourceAngularReduction +OAI.MeasureTheory.Falconer.Angular.StationaryApproximantSupport +OAI.MeasureTheory.Falconer.Angular.StationaryArcLength +OAI.MeasureTheory.Falconer.Angular.StationaryChartAmplitude +OAI.MeasureTheory.Falconer.Angular.StationaryChartCutoffs +OAI.MeasureTheory.Falconer.Angular.StationaryChartIntegral +OAI.MeasureTheory.Falconer.Angular.StationaryDifferentialExpr +OAI.MeasureTheory.Falconer.Angular.StationaryJetLocality +OAI.MeasureTheory.Falconer.Angular.StationaryJetOperators +OAI.MeasureTheory.Falconer.Angular.StationaryOppositePhase +OAI.MeasureTheory.Falconer.Angular.StationaryPairGain +OAI.MeasureTheory.Falconer.Angular.StationaryPairSupport +OAI.MeasureTheory.Falconer.Angular.StationaryPowerRate +OAI.MeasureTheory.Falconer.Angular.StationaryProductIntegral +OAI.MeasureTheory.Falconer.Angular.StationaryProductKernel +OAI.MeasureTheory.Falconer.Angular.StationaryRadialCoefficient +OAI.MeasureTheory.Falconer.Angular.StationaryRadialScaling +OAI.MeasureTheory.Falconer.Angular.StationaryRemainderScale +OAI.MeasureTheory.Falconer.Angular.StationarySineChart +OAI.MeasureTheory.Falconer.Angular.SuffixAngularRadius +OAI.MeasureTheory.Falconer.DistanceSet +OAI.MeasureTheory.Falconer.Estimates.ActualClassFamilies +OAI.MeasureTheory.Falconer.Estimates.ActualClassMass +OAI.MeasureTheory.Falconer.Estimates.ActualComparableDepthSum +OAI.MeasureTheory.Falconer.Estimates.ActualComparableFarError +OAI.MeasureTheory.Falconer.Estimates.ActualDirectBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEquation12 +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEquation20 +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceEstimate +OAI.MeasureTheory.Falconer.Estimates.ActualDistanceTerminal +OAI.MeasureTheory.Falconer.Estimates.ActualFarBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualFarEquation24 +OAI.MeasureTheory.Falconer.Estimates.ActualFarPower +OAI.MeasureTheory.Falconer.Estimates.ActualFarSourceBuffer +OAI.MeasureTheory.Falconer.Estimates.ActualFarSourceEquation24 +OAI.MeasureTheory.Falconer.Estimates.ActualFarSpatialError +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableFar +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableMain +OAI.MeasureTheory.Falconer.Estimates.ActualNoncomparableSpatial +OAI.MeasureTheory.Falconer.Estimates.ActualOuterMasks +OAI.MeasureTheory.Falconer.Estimates.ActualProductEquation13 +OAI.MeasureTheory.Falconer.Estimates.ActualProductEstimate +OAI.MeasureTheory.Falconer.Estimates.ActualRegularizedClasses +OAI.MeasureTheory.Falconer.Estimates.ActualRootEquation21 +OAI.MeasureTheory.Falconer.Estimates.ActualSuccessorUpperBounds +OAI.MeasureTheory.Falconer.Estimates.ActualTransformSplitting +OAI.MeasureTheory.Falconer.Estimates.ActualTwoPointDerivatives +OAI.MeasureTheory.Falconer.Estimates.Assembly +OAI.MeasureTheory.Falconer.Estimates.ClassPairCandidate +OAI.MeasureTheory.Falconer.Estimates.ClassPruning +OAI.MeasureTheory.Falconer.Estimates.ComparableComplexRebin +OAI.MeasureTheory.Falconer.Estimates.ComparableContributionPartition +OAI.MeasureTheory.Falconer.Estimates.ComparablePositiveRebin +OAI.MeasureTheory.Falconer.Estimates.ComparableProfileFactor +OAI.MeasureTheory.Falconer.Estimates.DistanceActivityStrip +OAI.MeasureTheory.Falconer.Estimates.DistanceCandidateWidth +OAI.MeasureTheory.Falconer.Estimates.DistanceEligibleIndices +OAI.MeasureTheory.Falconer.Estimates.DistanceForm +OAI.MeasureTheory.Falconer.Estimates.DistanceFormFubini +OAI.MeasureTheory.Falconer.Estimates.DistanceFormRemoval +OAI.MeasureTheory.Falconer.Estimates.DistanceMatrixData +OAI.MeasureTheory.Falconer.Estimates.DistanceOccupiedSum +OAI.MeasureTheory.Falconer.Estimates.DistanceProfileFactor +OAI.MeasureTheory.Falconer.Estimates.DistanceWeightSum +OAI.MeasureTheory.Falconer.Estimates.FarComparableSplit +OAI.MeasureTheory.Falconer.Estimates.FiniteSquareIntegrable +OAI.MeasureTheory.Falconer.Estimates.FrechetCompositionScale +OAI.MeasureTheory.Falconer.Estimates.FrechetProductScale +OAI.MeasureTheory.Falconer.Estimates.InactivePairMass +OAI.MeasureTheory.Falconer.Estimates.IndependentClassEquation27 +OAI.MeasureTheory.Falconer.Estimates.IntermediateProfiles +OAI.MeasureTheory.Falconer.Estimates.InverseLeibniz +OAI.MeasureTheory.Falconer.Estimates.LinearNonstationary +OAI.MeasureTheory.Falconer.Estimates.ListBoundedFunctions +OAI.MeasureTheory.Falconer.Estimates.MaskLoss +OAI.MeasureTheory.Falconer.Estimates.NoncomparablePower +OAI.MeasureTheory.Falconer.Estimates.OccupiedClasses +OAI.MeasureTheory.Falconer.Estimates.OccupiedPacking +OAI.MeasureTheory.Falconer.Estimates.OrderedLeibniz +OAI.MeasureTheory.Falconer.Estimates.OuterChildProfileBound +OAI.MeasureTheory.Falconer.Estimates.OuterEntryProfile +OAI.MeasureTheory.Falconer.Estimates.OuterMaskFailure +OAI.MeasureTheory.Falconer.Estimates.OuterRootEquation21 +OAI.MeasureTheory.Falconer.Estimates.ParallelCandidateCount +OAI.MeasureTheory.Falconer.Estimates.ParallelExceptional +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceGoodSet +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceJetSupport +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceMasks +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceOriginalSpatial +OAI.MeasureTheory.Falconer.Estimates.PositiveDistancePushforward +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceRebinBound +OAI.MeasureTheory.Falconer.Estimates.PositiveDistanceWeight +OAI.MeasureTheory.Falconer.Estimates.ProductCandidateWidth +OAI.MeasureTheory.Falconer.Estimates.ProductMatrix +OAI.MeasureTheory.Falconer.Estimates.ProductMatrixIntegrand +OAI.MeasureTheory.Falconer.Estimates.ProductMatrixReindex +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedCount +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedIntegrand +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedSum +OAI.MeasureTheory.Falconer.Estimates.ProductOccupiedVertices +OAI.MeasureTheory.Falconer.Estimates.ProductTransformPartition +OAI.MeasureTheory.Falconer.Estimates.ProductWeightSum +OAI.MeasureTheory.Falconer.Estimates.ProfileAffine +OAI.MeasureTheory.Falconer.Estimates.ProfileEnvelopes +OAI.MeasureTheory.Falconer.Estimates.ProfileInterpolation +OAI.MeasureTheory.Falconer.Estimates.ProfileMassError +OAI.MeasureTheory.Falconer.Estimates.ProfilePacking +OAI.MeasureTheory.Falconer.Estimates.QuadraticDampingLimit +OAI.MeasureTheory.Falconer.Estimates.QuadraticTaylorRemainder +OAI.MeasureTheory.Falconer.Estimates.RegularizationCardinality +OAI.MeasureTheory.Falconer.Estimates.RegularizationLabels +OAI.MeasureTheory.Falconer.Estimates.RegularizationQuantifiers +OAI.MeasureTheory.Falconer.Estimates.RegularizationScales +OAI.MeasureTheory.Falconer.Estimates.RegularizationSubpower +OAI.MeasureTheory.Falconer.Estimates.RegularizedMass +OAI.MeasureTheory.Falconer.Estimates.RootCoefficientSubpower +OAI.MeasureTheory.Falconer.Estimates.RootEquation21 +OAI.MeasureTheory.Falconer.Estimates.RootFiniteSeparation +OAI.MeasureTheory.Falconer.Estimates.RootLeibniz +OAI.MeasureTheory.Falconer.Estimates.RootLeibnizBounds +OAI.MeasureTheory.Falconer.Estimates.RootPairDerivatives +OAI.MeasureTheory.Falconer.Estimates.RootSpatialTerms +OAI.MeasureTheory.Falconer.Estimates.RootSupremum +OAI.MeasureTheory.Falconer.Estimates.RootWeightedDistance +OAI.MeasureTheory.Falconer.Estimates.RootWeightedInverse +OAI.MeasureTheory.Falconer.Estimates.ScaleUniformNonstationary +OAI.MeasureTheory.Falconer.Estimates.SelectedDistanceAssembly +OAI.MeasureTheory.Falconer.Estimates.SignedConvolution +OAI.MeasureTheory.Falconer.Estimates.SliceAverage +OAI.MeasureTheory.Falconer.Estimates.SmoothCompositionScale +OAI.MeasureTheory.Falconer.Estimates.SmoothConvolution +OAI.MeasureTheory.Falconer.Estimates.SourceAssemblyParameters +OAI.MeasureTheory.Falconer.Estimates.SourceProfileEquation25 +OAI.MeasureTheory.Falconer.Estimates.SourceStateTerminal +OAI.MeasureTheory.Falconer.Estimates.SourceStrongSeparation +OAI.MeasureTheory.Falconer.Estimates.SpatialAnchorMasks +OAI.MeasureTheory.Falconer.Estimates.SpatialDistanceFormSeparation +OAI.MeasureTheory.Falconer.Estimates.SpatialLeibnizSubpower +OAI.MeasureTheory.Falconer.Estimates.SpatialPhasedDistanceForm +OAI.MeasureTheory.Falconer.Estimates.SpatialPlancherel +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceNestedDomination +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceNestedSupport +OAI.MeasureTheory.Falconer.Estimates.WeightedDistancePushforward +OAI.MeasureTheory.Falconer.Estimates.WeightedDistanceSourceMapping +OAI.MeasureTheory.Falconer.Fourier.ActualDistanceLowBand +OAI.MeasureTheory.Falconer.Fourier.ActualSymbolEstimates +OAI.MeasureTheory.Falconer.Fourier.AnchorSymbolDropping +OAI.MeasureTheory.Falconer.Fourier.BinKernel +OAI.MeasureTheory.Falconer.Fourier.DistanceBandKernelBound +OAI.MeasureTheory.Falconer.Fourier.DistanceFourierDifference +OAI.MeasureTheory.Falconer.Fourier.DistanceFrequencyBox +OAI.MeasureTheory.Falconer.Fourier.DistanceFrequencyMajorant +OAI.MeasureTheory.Falconer.Fourier.DistanceKernelSplitting +OAI.MeasureTheory.Falconer.Fourier.DistanceSincCollision +OAI.MeasureTheory.Falconer.Fourier.DistanceSincKernel +OAI.MeasureTheory.Falconer.Fourier.DistanceSincSpectralIdentity +OAI.MeasureTheory.Falconer.Fourier.FiberSchwartz +OAI.MeasureTheory.Falconer.Fourier.FourierBandBound +OAI.MeasureTheory.Falconer.Fourier.FourierBandDecomposition +OAI.MeasureTheory.Falconer.Fourier.FourierConvolution +OAI.MeasureTheory.Falconer.Fourier.FourierEnergy +OAI.MeasureTheory.Falconer.Fourier.FourierLebesgue +OAI.MeasureTheory.Falconer.Fourier.FourierPairing +OAI.MeasureTheory.Falconer.Fourier.FourierSlice +OAI.MeasureTheory.Falconer.Fourier.GaussianRepresentation +OAI.MeasureTheory.Falconer.Fourier.GoodSupportedKernelMajorant +OAI.MeasureTheory.Falconer.Fourier.GraphActualFrequencySupport +OAI.MeasureTheory.Falconer.Fourier.GraphFourPointKernel +OAI.MeasureTheory.Falconer.Fourier.GraphFourSymbolDerivatives +OAI.MeasureTheory.Falconer.Fourier.GraphKernelBounds +OAI.MeasureTheory.Falconer.Fourier.InheritedSymbolMeasurability +OAI.MeasureTheory.Falconer.Fourier.InheritedSymbolSupport +OAI.MeasureTheory.Falconer.Fourier.KernelFourierIdentity +OAI.MeasureTheory.Falconer.Fourier.LowFrequencyKernel +OAI.MeasureTheory.Falconer.Fourier.MeasureKernelConvolution +OAI.MeasureTheory.Falconer.Fourier.MellinGaussian +OAI.MeasureTheory.Falconer.Fourier.MinimalPairSymbol +OAI.MeasureTheory.Falconer.Fourier.NormalizedSymbolFactors +OAI.MeasureTheory.Falconer.Fourier.OscillatoryTaylor +OAI.MeasureTheory.Falconer.Fourier.ParentInactiveKernel +OAI.MeasureTheory.Falconer.Fourier.PlaneFourierNonstationary +OAI.MeasureTheory.Falconer.Fourier.PositiveDistanceSpatialKernel +OAI.MeasureTheory.Falconer.Fourier.QuadraticGaussianPairing +OAI.MeasureTheory.Falconer.Fourier.QuadraticKernelBounds +OAI.MeasureTheory.Falconer.Fourier.RootFourierError +OAI.MeasureTheory.Falconer.Fourier.RootKernelTerms +OAI.MeasureTheory.Falconer.Fourier.RootNormalizedKernel +OAI.MeasureTheory.Falconer.Fourier.RootPairSymbols +OAI.MeasureTheory.Falconer.Fourier.RootUniformFourier +OAI.MeasureTheory.Falconer.Fourier.SchwartzFourierMomentBounds +OAI.MeasureTheory.Falconer.Fourier.SchwartzFourierMoments +OAI.MeasureTheory.Falconer.Fourier.SchwartzLpTests +OAI.MeasureTheory.Falconer.Fourier.SmoothKernel +OAI.MeasureTheory.Falconer.Fourier.SpatialAnnulusKernel +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierIntegration +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierSeparation +OAI.MeasureTheory.Falconer.Fourier.SpatialFourierTests +OAI.MeasureTheory.Falconer.Fourier.SpatialPhasedSymbols +OAI.MeasureTheory.Falconer.Fourier.SymbolProductBounds +OAI.MeasureTheory.Falconer.Fourier.UniformSymbolScale +OAI.MeasureTheory.Falconer.Fourier.WeightedDistanceFourier +OAI.MeasureTheory.Falconer.Fourier.WeightedDistanceLowFrequency +OAI.MeasureTheory.Falconer.Fourier.WeightedDistancePositiveKernel +OAI.MeasureTheory.Falconer.Frostman.AtomlessRadialContinuity +OAI.MeasureTheory.Falconer.Frostman.Capacity +OAI.MeasureTheory.Falconer.Frostman.Content +OAI.MeasureTheory.Falconer.Frostman.ContentBound +OAI.MeasureTheory.Falconer.Frostman.Frostman +OAI.MeasureTheory.Falconer.Frostman.FrostmanProfileCells +OAI.MeasureTheory.Falconer.Frostman.GeometricCapacity +OAI.MeasureTheory.Falconer.Frostman.NormalizedRootSetup +OAI.MeasureTheory.Falconer.Geometry.BinBands +OAI.MeasureTheory.Falconer.Geometry.BinEstimates +OAI.MeasureTheory.Falconer.Geometry.BinOffsets +OAI.MeasureTheory.Falconer.Geometry.Bins +OAI.MeasureTheory.Falconer.Geometry.CellwiseDistanceForm +OAI.MeasureTheory.Falconer.Geometry.CompactMultiplierScale +OAI.MeasureTheory.Falconer.Geometry.CompactQuadraticExpansion +OAI.MeasureTheory.Falconer.Geometry.CompactSublevel +OAI.MeasureTheory.Falconer.Geometry.ComparableCellCounting +OAI.MeasureTheory.Falconer.Geometry.DyadicCenterSeparation +OAI.MeasureTheory.Falconer.Geometry.DyadicClasses +OAI.MeasureTheory.Falconer.Geometry.DyadicGeometry +OAI.MeasureTheory.Falconer.Geometry.DyadicInverseDistance +OAI.MeasureTheory.Falconer.Geometry.DyadicPacking +OAI.MeasureTheory.Falconer.Geometry.FiniteBinComparison +OAI.MeasureTheory.Falconer.Geometry.InactiveBinDecay +OAI.MeasureTheory.Falconer.Geometry.InactiveBinGeometry +OAI.MeasureTheory.Falconer.Geometry.InactiveBinScales +OAI.MeasureTheory.Falconer.Geometry.PositiveDistanceBins +OAI.MeasureTheory.Falconer.Geometry.ProfileGrid +OAI.MeasureTheory.Falconer.Geometry.RootPatchGeometry +OAI.MeasureTheory.Falconer.Geometry.RootSimilarityGeometry +OAI.MeasureTheory.Falconer.Geometry.ScaledDyadicPacking +OAI.MeasureTheory.Falconer.Geometry.SelectedBinAmplitude +OAI.MeasureTheory.Falconer.Geometry.SeparatedDistanceMaximum +OAI.MeasureTheory.Falconer.Geometry.SeparatedSpatialDistanceForm +OAI.MeasureTheory.Falconer.Graphs.ActualDirectGraph +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceChildEnergy +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceDegrees +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ActualDistanceHFGraph +OAI.MeasureTheory.Falconer.Graphs.ActualProductChildEnergy +OAI.MeasureTheory.Falconer.Graphs.ActualProductDegrees +OAI.MeasureTheory.Falconer.Graphs.ActualProductEnergyFinite +OAI.MeasureTheory.Falconer.Graphs.ActualProductGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphCross +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphIntegral +OAI.MeasureTheory.Falconer.Graphs.DistanceGraphPointwise +OAI.MeasureTheory.Falconer.Graphs.DistancePairDegree +OAI.MeasureTheory.Falconer.Graphs.DistanceSupportedGraph +OAI.MeasureTheory.Falconer.Graphs.EligibleDistanceGraphSum +OAI.MeasureTheory.Falconer.Graphs.EligibleProductGraphSum +OAI.MeasureTheory.Falconer.Graphs.Energy +OAI.MeasureTheory.Falconer.Graphs.FiberEnergy +OAI.MeasureTheory.Falconer.Graphs.FiberPairing +OAI.MeasureTheory.Falconer.Graphs.FiberSlice +OAI.MeasureTheory.Falconer.Graphs.FiberTrace +OAI.MeasureTheory.Falconer.Graphs.FinsetSchur +OAI.MeasureTheory.Falconer.Graphs.GraphActualMixedDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphActualNonedgeGeometry +OAI.MeasureTheory.Falconer.Graphs.GraphActualNonedgeSum +OAI.MeasureTheory.Falconer.Graphs.GraphActualQuadCells +OAI.MeasureTheory.Falconer.Graphs.GraphActualTransport +OAI.MeasureTheory.Falconer.Graphs.GraphAlgebraicDirections +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeRepresentative +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeScale +OAI.MeasureTheory.Falconer.Graphs.GraphAmplitudeSupport +OAI.MeasureTheory.Falconer.Graphs.GraphBinDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphCartesianSubstitution +OAI.MeasureTheory.Falconer.Graphs.GraphChartIntegral +OAI.MeasureTheory.Falconer.Graphs.GraphChartRegularity +OAI.MeasureTheory.Falconer.Graphs.GraphChartVariation +OAI.MeasureTheory.Falconer.Graphs.GraphCompleteWeightSupport +OAI.MeasureTheory.Falconer.Graphs.GraphConeCutoff +OAI.MeasureTheory.Falconer.Graphs.GraphCoordinateInverse +OAI.MeasureTheory.Falconer.Graphs.GraphDerivativeBounds +OAI.MeasureTheory.Falconer.Graphs.GraphDirectionStability +OAI.MeasureTheory.Falconer.Graphs.GraphEndpointContinuity +OAI.MeasureTheory.Falconer.Graphs.GraphEtaIntegratedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphEtaNonstationary +OAI.MeasureTheory.Falconer.Graphs.GraphFiberPacking +OAI.MeasureTheory.Falconer.Graphs.GraphFixedCutoffs +OAI.MeasureTheory.Falconer.Graphs.GraphFourMassBound +OAI.MeasureTheory.Falconer.Graphs.GraphFourTransformExpansion +OAI.MeasureTheory.Falconer.Graphs.GraphFourTransformPointIntegral +OAI.MeasureTheory.Falconer.Graphs.GraphGeometry +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalBump +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalChart +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalDomain +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalPhase +OAI.MeasureTheory.Falconer.Graphs.GraphGlobalSupports +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedNonedgePower +OAI.MeasureTheory.Falconer.Graphs.GraphInheritedTransformChart +OAI.MeasureTheory.Falconer.Graphs.GraphLiftInverse +OAI.MeasureTheory.Falconer.Graphs.GraphLiftJacobian +OAI.MeasureTheory.Falconer.Graphs.GraphMixedComposition +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeAmplitude +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeErrorScale +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeFiniteSum +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeGradient +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeIndexCount +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgeIntegralErrors +OAI.MeasureTheory.Falconer.Graphs.GraphNonedgePerturbation +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalFubini +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalGraphRemoval +OAI.MeasureTheory.Falconer.Graphs.GraphOriginalNonedgePower +OAI.MeasureTheory.Falconer.Graphs.GraphParentDiameter +OAI.MeasureTheory.Falconer.Graphs.GraphPointIntegralChart +OAI.MeasureTheory.Falconer.Graphs.GraphPolarAnnulus +OAI.MeasureTheory.Falconer.Graphs.GraphPolarJacobian +OAI.MeasureTheory.Falconer.Graphs.GraphProductMeasure +OAI.MeasureTheory.Falconer.Graphs.GraphProfileCoefficient +OAI.MeasureTheory.Falconer.Graphs.GraphRetainedEdges +OAI.MeasureTheory.Falconer.Graphs.GraphScaleDirection +OAI.MeasureTheory.Falconer.Graphs.GraphSignChart +OAI.MeasureTheory.Falconer.Graphs.GraphSignPartition +OAI.MeasureTheory.Falconer.Graphs.GraphSignSupports +OAI.MeasureTheory.Falconer.Graphs.GraphSliceDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphSpatialFubini +OAI.MeasureTheory.Falconer.Graphs.GraphTorusArcLength +OAI.MeasureTheory.Falconer.Graphs.GraphTransformChart +OAI.MeasureTheory.Falconer.Graphs.GraphTransportIntegrability +OAI.MeasureTheory.Falconer.Graphs.GraphWeightDerivatives +OAI.MeasureTheory.Falconer.Graphs.GraphZIntegratedNonedge +OAI.MeasureTheory.Falconer.Graphs.GraphZNonedgeScale +OAI.MeasureTheory.Falconer.Graphs.GraphZNonstationary +OAI.MeasureTheory.Falconer.Graphs.LocalDistanceCollision +OAI.MeasureTheory.Falconer.Graphs.OuterRootGraphBound +OAI.MeasureTheory.Falconer.Graphs.PairCollisionTonelli +OAI.MeasureTheory.Falconer.Graphs.ParentAbsoluteGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ParentGraphEnergy +OAI.MeasureTheory.Falconer.Graphs.ParentGraphIndices +OAI.MeasureTheory.Falconer.Graphs.ParentRetainedEnergy +OAI.MeasureTheory.Falconer.Graphs.PrefixGraphSpecialization +OAI.MeasureTheory.Falconer.Graphs.PrefixSuccessorEnergy +OAI.MeasureTheory.Falconer.Graphs.ProductAbsoluteGraphAssembly +OAI.MeasureTheory.Falconer.Graphs.ProductEnergyMaximum +OAI.MeasureTheory.Falconer.Graphs.ProductEnergyTransfer +OAI.MeasureTheory.Falconer.Graphs.ProductGraphEnergy +OAI.MeasureTheory.Falconer.Graphs.ProductGraphIndices +OAI.MeasureTheory.Falconer.Graphs.ProductGraphIntegral +OAI.MeasureTheory.Falconer.Graphs.ProductGraphPointwise +OAI.MeasureTheory.Falconer.Graphs.ProductPairDegree +OAI.MeasureTheory.Falconer.Graphs.RecursiveEnergyFamily +OAI.MeasureTheory.Falconer.Graphs.RootParentEnergy +OAI.MeasureTheory.Falconer.Graphs.SmoothFiberEstimate +OAI.MeasureTheory.Falconer.Graphs.SourceSpatialEnergy +OAI.MeasureTheory.Falconer.Graphs.UniformDistancePairDegree +OAI.MeasureTheory.Falconer.Graphs.WeightedDistanceCoincidence +OAI.MeasureTheory.Falconer.Main +OAI.MeasureTheory.Falconer.Measures.BoundedDualDensity +OAI.MeasureTheory.Falconer.Measures.ComparableIntegralPartition +OAI.MeasureTheory.Falconer.Measures.ComparableNormalization +OAI.MeasureTheory.Falconer.Measures.DistanceMatrixSchur +OAI.MeasureTheory.Falconer.Measures.DistanceMeasure +OAI.MeasureTheory.Falconer.Measures.DistanceSchurIntegral +OAI.MeasureTheory.Falconer.Measures.DistributionAbsoluteContinuity +OAI.MeasureTheory.Falconer.Measures.DyadicIntegralSplitting +OAI.MeasureTheory.Falconer.Measures.DyadicMeasure +OAI.MeasureTheory.Falconer.Measures.DyadicMeasureSplitting +OAI.MeasureTheory.Falconer.Measures.ExtendedDensityNorm +OAI.MeasureTheory.Falconer.Measures.FiniteLpIntegral +OAI.MeasureTheory.Falconer.Measures.FiniteMeasureProducts +OAI.MeasureTheory.Falconer.Measures.FiniteProductIntegral +OAI.MeasureTheory.Falconer.Measures.FourCellMeasureSplitting +OAI.MeasureTheory.Falconer.Measures.FourSpatialPairMeasure +OAI.MeasureTheory.Falconer.Measures.InactiveBinIntegral +OAI.MeasureTheory.Falconer.Measures.NormAffineRemainder +OAI.MeasureTheory.Falconer.Measures.NormalizedLeibnizAssignment +OAI.MeasureTheory.Falconer.Measures.ProductMatrixSchur +OAI.MeasureTheory.Falconer.Measures.ProductSchurIntegral +OAI.MeasureTheory.Falconer.Measures.RootNormalizedCoefficients +OAI.MeasureTheory.Falconer.Measures.RootNormalizedError +OAI.MeasureTheory.Falconer.Measures.RootSimilarityMeasures +OAI.MeasureTheory.Falconer.Measures.Schur +OAI.MeasureTheory.Falconer.Measures.TestNormDensity +OAI.MeasureTheory.Falconer.Measures.TestNormMeasurable +OAI.MeasureTheory.Falconer.Measures.TestNormRepresentation +OAI.MeasureTheory.Falconer.Measures.TotalVariation +OAI.MeasureTheory.Falconer.Measures.WeakApproximation +OAI.MeasureTheory.Falconer.Measures.WeakLimit +OAI.MeasureTheory.Falconer.Measures.WeightedIntegralSquare +OAI.MeasureTheory.Falconer.Model +OAI.MeasureTheory.Falconer.Radial.ActualFarRadialError +OAI.MeasureTheory.Falconer.Radial.ActualNoncomparableRadial +OAI.MeasureTheory.Falconer.Radial.ActualSingleRadialError +OAI.MeasureTheory.Falconer.Radial.ActualSuffixProjection +OAI.MeasureTheory.Falconer.Radial.FiniteRadialContinuity +OAI.MeasureTheory.Falconer.Radial.FiniteRadialTestEnergy +OAI.MeasureTheory.Falconer.Radial.GraphRadialNormalization +OAI.MeasureTheory.Falconer.Radial.GraphTorusRadial +OAI.MeasureTheory.Falconer.Radial.LinearRadialDecay +OAI.MeasureTheory.Falconer.Radial.MollifiedRadialBound +OAI.MeasureTheory.Falconer.Radial.NoncomparableRadialSymmetry +OAI.MeasureTheory.Falconer.Radial.ProfileProjectionCollision +OAI.MeasureTheory.Falconer.Radial.ProjectedDiameter +OAI.MeasureTheory.Falconer.Radial.ProjectionCellPartition +OAI.MeasureTheory.Falconer.Radial.ProjectionCollisionCount +OAI.MeasureTheory.Falconer.Radial.ProjectionDensity +OAI.MeasureTheory.Falconer.Radial.ProjectionEnergy +OAI.MeasureTheory.Falconer.Radial.ProjectionExceptional +OAI.MeasureTheory.Falconer.Radial.ProjectionMoment +OAI.MeasureTheory.Falconer.Radial.ProjectionShiftedBand +OAI.MeasureTheory.Falconer.Radial.RadialCapMass +OAI.MeasureTheory.Falconer.Radial.RadialContinuity +OAI.MeasureTheory.Falconer.Radial.RadialDensity +OAI.MeasureTheory.Falconer.Radial.RadialDistanceError +OAI.MeasureTheory.Falconer.Radial.RadialFailureMass +OAI.MeasureTheory.Falconer.Radial.RadialFatou +OAI.MeasureTheory.Falconer.Radial.RadialLpEnergy +OAI.MeasureTheory.Falconer.Radial.RadialMixedEnergy +OAI.MeasureTheory.Falconer.Radial.RadialPreparation +OAI.MeasureTheory.Falconer.Radial.RadialShellMeasure +OAI.MeasureTheory.Falconer.Radial.RadialTestBound +OAI.MeasureTheory.Falconer.Radial.RadialTestEnergy +OAI.MeasureTheory.Falconer.Radial.RadialTestNorm +OAI.MeasureTheory.Falconer.Radial.RadialTonelli +OAI.MeasureTheory.Falconer.Radial.RadonLpDensity +OAI.MeasureTheory.Falconer.Radial.SmoothRadialEstimate +OAI.MeasureTheory.Falconer.Radial.SourceRadialSetup +OAI.MeasureTheory.Falconer.Radial.SuffixProjectionWidths +OAI.MeasureTheory.Falconer.Radial.UniformProjectionCollision +OAI.MeasureTheory.Falconer.Radial.UniformRadialRestrictions +OAI.MeasureTheory.Falconer.Recursion.ActualDistanceRecursionBound +OAI.MeasureTheory.Falconer.Recursion.ActualPolicyPayments +OAI.MeasureTheory.Falconer.Recursion.ActualRecursiveProfile +OAI.MeasureTheory.Falconer.Recursion.ActualSuffixLocalBins +OAI.MeasureTheory.Falconer.Recursion.ActualSuffixReduction +OAI.MeasureTheory.Falconer.Recursion.BlockLeafCounts +OAI.MeasureTheory.Falconer.Recursion.BlockRegularization +OAI.MeasureTheory.Falconer.Recursion.BranchAnalyticSuccessors +OAI.MeasureTheory.Falconer.Recursion.BranchCounts +OAI.MeasureTheory.Falconer.Recursion.BranchErrorBounds +OAI.MeasureTheory.Falconer.Recursion.BranchExponent +OAI.MeasureTheory.Falconer.Recursion.BranchExponentAlgebra +OAI.MeasureTheory.Falconer.Recursion.BranchPotential +OAI.MeasureTheory.Falconer.Recursion.BranchRecursionOrder +OAI.MeasureTheory.Falconer.Recursion.BranchRepresentativeCharges +OAI.MeasureTheory.Falconer.Recursion.BranchTransitions +OAI.MeasureTheory.Falconer.Recursion.BranchValidity +OAI.MeasureTheory.Falconer.Recursion.DescriptorGoodTransfer +OAI.MeasureTheory.Falconer.Recursion.DescriptorMaskFailure +OAI.MeasureTheory.Falconer.Recursion.DescriptorMaskSymmetry +OAI.MeasureTheory.Falconer.Recursion.DescriptorMasks +OAI.MeasureTheory.Falconer.Recursion.DirectPolicyWitness +OAI.MeasureTheory.Falconer.Recursion.DisplacementDepth +OAI.MeasureTheory.Falconer.Recursion.InheritedEligibleWitness +OAI.MeasureTheory.Falconer.Recursion.InheritedPolicyState +OAI.MeasureTheory.Falconer.Recursion.InteriorPolicy +OAI.MeasureTheory.Falconer.Recursion.LeafMassBins +OAI.MeasureTheory.Falconer.Recursion.Ledger +OAI.MeasureTheory.Falconer.Recursion.MinimalDescriptorLength +OAI.MeasureTheory.Falconer.Recursion.OuterRecursiveTransport +OAI.MeasureTheory.Falconer.Recursion.ParentBinFamily +OAI.MeasureTheory.Falconer.Recursion.ParentBinSelection +OAI.MeasureTheory.Falconer.Recursion.ParentCellGeometry +OAI.MeasureTheory.Falconer.Recursion.ParentConeGeometry +OAI.MeasureTheory.Falconer.Recursion.ParentConeSource +OAI.MeasureTheory.Falconer.Recursion.ParentDiscardedForm +OAI.MeasureTheory.Falconer.Recursion.ParentHFBridge +OAI.MeasureTheory.Falconer.Recursion.ParentInactiveRemoval +OAI.MeasureTheory.Falconer.Recursion.PolicyDescriptors +OAI.MeasureTheory.Falconer.Recursion.PolicyInteriorInterval +OAI.MeasureTheory.Falconer.Recursion.Potential +OAI.MeasureTheory.Falconer.Recursion.PrefixBandAssembly +OAI.MeasureTheory.Falconer.Recursion.PrefixChildDropping +OAI.MeasureTheory.Falconer.Recursion.PrefixCounting +OAI.MeasureTheory.Falconer.Recursion.PrefixInverseSupremum +OAI.MeasureTheory.Falconer.Recursion.PrefixLowMaximum +OAI.MeasureTheory.Falconer.Recursion.PrefixMass +OAI.MeasureTheory.Falconer.Recursion.PrefixPolicyGeometry +OAI.MeasureTheory.Falconer.Recursion.ProductPrefixCount +OAI.MeasureTheory.Falconer.Recursion.ProductRetainedStrip +OAI.MeasureTheory.Falconer.Recursion.ProfileBlockRefinement +OAI.MeasureTheory.Falconer.Recursion.ReachedBranchWeights +OAI.MeasureTheory.Falconer.Recursion.ReachedStateRecursion +OAI.MeasureTheory.Falconer.Recursion.RecursiveCellInvariants +OAI.MeasureTheory.Falconer.Recursion.RetainedPairMasks +OAI.MeasureTheory.Falconer.Recursion.SourceBranchDepth +OAI.MeasureTheory.Falconer.Recursion.SourcePrefixReduction +OAI.MeasureTheory.Falconer.Recursion.SourceSuffixReduction +OAI.MeasureTheory.Falconer.Recursion.SuffixBinAssembly +OAI.MeasureTheory.Falconer.Recursion.SuffixBinGeometry +OAI.MeasureTheory.Falconer.Recursion.SuffixCoarseDomination +OAI.MeasureTheory.Falconer.Recursion.SuffixDescriptors +OAI.MeasureTheory.Falconer.Recursion.SuffixDirectionGeometry +OAI.MeasureTheory.Falconer.Recursion.SuffixDistanceTaylor +OAI.MeasureTheory.Falconer.Recursion.SuffixGoodTransport +OAI.MeasureTheory.Falconer.Recursion.SuffixLocalBins +OAI.MeasureTheory.Falconer.Recursion.SuffixNormalization +OAI.MeasureTheory.Falconer.Recursion.SuffixPowerLoss +OAI.MeasureTheory.Falconer.Recursion.SuffixRetainedPairs +OAI.MeasureTheory.Falconer.Recursion.TwoProfileRecursion +OAI.MeasureTheory.Falconer.Recursion.WeightedBranchInduction +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellDistance +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellNormalized +OAI.MeasureTheory.Falconer.Shells.ActualComparableShellRebin +OAI.MeasureTheory.Falconer.Shells.ActualHighShellEquation21 +OAI.MeasureTheory.Falconer.Shells.ActualHighShellInverse +OAI.MeasureTheory.Falconer.Shells.ActualRestorationBound +OAI.MeasureTheory.Falconer.Shells.AngularLengthShellCover +OAI.MeasureTheory.Falconer.Shells.AngularShellEnergy +OAI.MeasureTheory.Falconer.Shells.ContinuousCoefficientShell +OAI.MeasureTheory.Falconer.Shells.FiniteWeightedShell +OAI.MeasureTheory.Falconer.Shells.HighShellCoefficientBounds +OAI.MeasureTheory.Falconer.Shells.HighShellCone +OAI.MeasureTheory.Falconer.Shells.HighShellEndpointTerms +OAI.MeasureTheory.Falconer.Shells.HighShellEquation21 +OAI.MeasureTheory.Falconer.Shells.HighShellErrorPower +OAI.MeasureTheory.Falconer.Shells.HighShellFiniteSeparation +OAI.MeasureTheory.Falconer.Shells.HighShellFourierError +OAI.MeasureTheory.Falconer.Shells.HighShellKernelTerms +OAI.MeasureTheory.Falconer.Shells.HighShellLeibnizSymbols +OAI.MeasureTheory.Falconer.Shells.HighShellMainEnergy +OAI.MeasureTheory.Falconer.Shells.HighShellMeasurable +OAI.MeasureTheory.Falconer.Shells.HighShellMixture +OAI.MeasureTheory.Falconer.Shells.HighShellNormalization +OAI.MeasureTheory.Falconer.Shells.HighShellOrderForm +OAI.MeasureTheory.Falconer.Shells.HighShellParentEnergy +OAI.MeasureTheory.Falconer.Shells.HighShellProfileMass +OAI.MeasureTheory.Falconer.Shells.HighShellRadialBounds +OAI.MeasureTheory.Falconer.Shells.HighShellSeparatedTerms +OAI.MeasureTheory.Falconer.Shells.HighShellStationaryScale +OAI.MeasureTheory.Falconer.Shells.HighShellSubpower +OAI.MeasureTheory.Falconer.Shells.HighShellSupremum +OAI.MeasureTheory.Falconer.Shells.ListWeightedShell +OAI.MeasureTheory.Falconer.Shells.NormalizedHighShellError +OAI.MeasureTheory.Falconer.Shells.NormalizedHighShellKernel +OAI.MeasureTheory.Falconer.Shells.NormalizedOuterShell +OAI.MeasureTheory.Falconer.Shells.OriginalShellIntegral +OAI.MeasureTheory.Falconer.Shells.PrefixHighShell +OAI.MeasureTheory.Falconer.Shells.RadialShellMass +OAI.MeasureTheory.Falconer.Shells.RestorationPowerRate +OAI.MeasureTheory.Falconer.Shells.RestorationSubpower +OAI.MeasureTheory.Falconer.Shells.RestoredMaskCoverage +OAI.MeasureTheory.Falconer.Shells.RestoredShellCandidates +OAI.MeasureTheory.Falconer.Shells.RootEndpointData +OAI.MeasureTheory.Falconer.Shells.RootEndpointTerms +OAI.MeasureTheory.Falconer.Shells.RootHighShellInverse +OAI.MeasureTheory.Falconer.Shells.RootShellData +OAI.MeasureTheory.Falconer.Shells.RootShellMain +OAI.MeasureTheory.Falconer.Shells.RootShellMixture +OAI.MeasureTheory.Falconer.Shells.RootShellOrder +OAI.MeasureTheory.Falconer.Shells.ShellApproximationError +OAI.MeasureTheory.Falconer.Shells.ShellErrorSummability +OAI.MeasureTheory.Falconer.Shells.ShellFrequencyEnergy +OAI.MeasureTheory.Falconer.Shells.ShellFrequencyTests +OAI.MeasureTheory.Falconer.Shells.ShellKernels +OAI.MeasureTheory.Falconer.Shells.ShellMixtures +OAI.MeasureTheory.Falconer.Shells.ShellMultipliers +OAI.MeasureTheory.Falconer.Shells.ShellReconstruction +OAI.MeasureTheory.Falconer.Shells.ShellSummability +OAI.MeasureTheory.Falconer.Shells.ShellTestConvergence +OAI.MeasureTheory.Falconer.Shells.Shells +OAI.MeasureTheory.Falconer.Shells.SmoothShellDomination +OAI.MeasureTheory.Falconer.Shells.SmoothShellPartition +OAI.MeasureTheory.Falconer.Shells.TwoRootApproximations +OAI.MeasureTheory.Falconer.Shells.TwoRootCandidates +OAI.MeasureTheory.Falconer.Shells.TwoRootClassMixture +OAI.MeasureTheory.Falconer.Shells.TwoRootMaskCoverage +OAI.MeasureTheory.Falconer.Shells.TwoRootMasks +OAI.MeasureTheory.Falconer.Shells.TwoRootMixtureFinite +OAI.MeasureTheory.Falconer.Shells.TwoRootRestoration +OAI.MeasureTheory.Falconer.Shells.TwoRootShellDecay +OAI.MeasureTheory.Falconer.Shells.TwoSidedShell +OAI.MeasureTheory.Falconer.Shells.WeightedHighShellInverse diff --git a/tasks/planar-falconer/solution/reference.py b/tasks/planar-falconer/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/planar-falconer/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/planar-falconer/solution/solve.sh b/tasks/planar-falconer/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ae30da53e6e31ed95a6571b9a1726d37b1e613c --- /dev/null +++ b/tasks/planar-falconer/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlanarFalconer, i.e. module OAI.MeasureTheory.Falconer.Main and the +# 719 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MeasureTheory.Falconer.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlanarFalconer" diff --git a/tasks/planar-falconer/task.toml b/tasks/planar-falconer/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f95f9c505a00f42b96fbb0bacb7179858cff1e9 --- /dev/null +++ b/tasks/planar-falconer/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/planar-falconer" +version = "1.0.0" +description = "Prove PlanarFalconer (openai/math family 073: The Falconer distance conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlanarFalconer.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlanarFalconer" +family = "073" +family_title = "The Falconer distance conjecture" +subject = "Real and complex analysis" +theorems = ["OAI.PlanarFalconer.mainTarget_proved"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MeasureTheory.Falconer.Main" +reference_modules = 719 +reference_lean_bytes = 2640523 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1803 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14076 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/planar-falconer/tests/Challenge.lean b/tasks/planar-falconer/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..56a7d65c687b851e93055b9776d6623a6e266aac --- /dev/null +++ b/tasks/planar-falconer/tests/Challenge.lean @@ -0,0 +1,25 @@ +import Mathlib + +namespace OAI + +namespace PlanarFalconer +open MeasureTheory Set + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def distanceSet (E : Set Plane) : Set ℝ := + {r | ∃ x ∈ E, ∃ y ∈ E, dist x y = r} + +def MainTarget : Prop := + ∀ E : Set Plane, IsCompact E → 1 < dimH E → 0 < volume (distanceSet E) + +end PlanarFalconer + +namespace PlanarFalconer + +theorem mainTarget_proved : MainTarget := by + sorry + +end PlanarFalconer + +end OAI diff --git a/tasks/planar-falconer/tests/grade.py b/tasks/planar-falconer/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/planar-falconer/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/planar-falconer/tests/task.json b/tasks/planar-falconer/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1b170fcbe1d5438b9e55d440e99b9fd679ea76fb --- /dev/null +++ b/tasks/planar-falconer/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlanarFalconer", + "comparator": { + "theorem_names": [ + "OAI.PlanarFalconer.mainTarget_proved" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 13176 +} \ No newline at end of file diff --git a/tasks/planar-falconer/tests/test.sh b/tasks/planar-falconer/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/planar-falconer/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/planar-first-passage/environment/Dockerfile b/tasks/planar-first-passage/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/planar-first-passage/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/planar-first-passage/environment/fetch_mathlib.sh b/tasks/planar-first-passage/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/planar-first-passage/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/planar-first-passage/environment/lake-manifest.json b/tasks/planar-first-passage/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/planar-first-passage/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/planar-first-passage/environment/lakefile.lean b/tasks/planar-first-passage/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/planar-first-passage/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/planar-first-passage/environment/lean_setup.sh b/tasks/planar-first-passage/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/planar-first-passage/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/planar-first-passage/environment/pack_submission.py b/tasks/planar-first-passage/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/planar-first-passage/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/planar-first-passage/instruction.md b/tasks/planar-first-passage/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f2af2fbc9cdd083801965b8eef8ee385aa464a6c --- /dev/null +++ b/tasks/planar-first-passage/instruction.md @@ -0,0 +1,153 @@ +# openai/math challenge `PlanarFirstPassage` (family 212) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 212 of the release, *No bigeodesics and smooth limit shapes in planar first-passage percolation* +(Probability and statistical mechanics). The family as a whole: Proves that planar first-passage percolation has no doubly infinite geodesic for iid nonnegative nonatomic edge weights when the minimum of four weights has finite second moment. For exponential weights, the limit shape is strictly convex with $C^1$ boundary. Differentiability also holds for every Gamma law with positive shape and rate. + +The challenge is `PlanarFirstPassage`, also at `/opt/openai-math/challenges/PlanarFirstPassage.lean`: + +```lean +import Mathlib.Algebra.BigOperators.Group.List.Basic +import Mathlib.Algebra.Group.Prod +import Mathlib.Analysis.Calculus.ContDiff.Defs +import Mathlib.Analysis.Calculus.Deriv.Basic +import Mathlib.Analysis.Calculus.FDeriv.Basic +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Analysis.LocallyConvex.WithSeminorms +import Mathlib.Probability.Distributions.Exponential +import Mathlib.Probability.Independence.Basic + +namespace OAI + +namespace PlanarFPP + +open Set MeasureTheory ProbabilityTheory Filter +open scoped Topology + +abbrev Vertex := ℤ × ℤ + +abbrev Edge := Vertex × Bool + +inductive Step where + | east | west | north | south + deriving DecidableEq + +def Step.delta : Step → Vertex + | .east => (1, 0) + | .west => (-1, 0) + | .north => (0, 1) + | .south => (0, -1) + +def Step.edge (p : Vertex) : Step → Edge + | .east => (p, false) + | .west => (p + (-1, 0), false) + | .north => (p, true) + | .south => (p + (0, -1), true) + +def displacement (ds : List Step) : Vertex := (ds.map Step.delta).sum + +def pathCost (τ : Edge → ℝ) (p : Vertex) : List Step → ℝ + | [] => 0 + | d :: ds => τ (d.edge p) + pathCost τ (p + d.delta) ds + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +noncomputable def latticeFloor (v : Plane) : Vertex := (⌊v 0⌋, ⌊v 1⌋) + +noncomputable def passageTime (τ : Edge → ℝ) (p q : Vertex) : ℝ := + sInf {t | ∃ ds : List Step, p + displacement ds = q ∧ pathCost τ p ds = t} + +structure TimeConstantNorm (μ : Plane → ℝ) : Prop where + nonneg : ∀ v, 0 ≤ μ v + zero_iff : ∀ v, μ v = 0 ↔ v = 0 + triangle : ∀ v w, μ (v + w) ≤ μ v + μ w + homogeneous : ∀ (a : ℝ) v, μ (a • v) = |a| * μ v + +structure ExponentialEnvironment {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) : Prop where + probability : IsProbabilityMeasure P + measurable : ∀ e, Measurable (τ e) + independent : iIndepFun τ P + marginal : ∀ e, Measure.map (τ e) P = expMeasure 1 + +def IsTimeConstant {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) (μ : Plane → ℝ) : Prop := + ∀ v : Plane, ∀ᵐ ω ∂P, + Tendsto (fun t : ℝ => passageTime (fun e => τ e ω) (0, 0) + (latticeFloor (t • v)) / t) atTop (𝓝 (μ v)) + +def DifferentiableAwayFromOrigin (μ : Plane → ℝ) : Prop := + ∀ v : Plane, v ≠ 0 → ∃ ℓ : Plane →L[ℝ] ℝ, HasFDerivAt μ ℓ v + +def UniqueNormalizedSupports (μ : Plane → ℝ) : Prop := + ∀ v : Plane, μ v = 1 → ∃! ℓ : Plane →L[ℝ] ℝ, + ℓ v = 1 ∧ ∀ w, ℓ w ≤ μ w + +def C1UnitSphere (μ : Plane → ℝ) : Prop := + ∀ v : Plane, μ v = 1 → ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ + ∃ g : Plane → ℝ, ContDiffOn ℝ 1 g U ∧ + (∀ w ∈ U, μ w = 1 ↔ g w = 0) ∧ + ∀ w ∈ U, g w = 0 → ∃ ℓ : Plane →L[ℝ] ℝ, + HasFDerivAt g ℓ w ∧ ℓ ≠ 0 + +def HasC1CurveChart (S : Set Plane) (v : Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ v ∈ S ∧ ∃ γ : ℝ → Plane, ∃ θ : Plane → ℝ, + ContDiff ℝ 1 γ ∧ ContinuousOn θ U ∧ + (∀ t, γ t ∈ S ∩ U) ∧ (∀ t, θ (γ t)=t) ∧ + (∀ z ∈ S ∩ U, γ (θ z)=z) ∧ + (∀ t, ∃ d : Plane, HasDerivAt γ d t ∧ d ≠ 0) + +theorem manuscriptMain (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) (τ : Edge → Ω → ℝ) + (henv : ExponentialEnvironment P τ) : + ∃ μ : Plane → ℝ, TimeConstantNorm μ ∧ IsTimeConstant P τ μ ∧ + DifferentiableAwayFromOrigin μ ∧ UniqueNormalizedSupports μ ∧ C1UnitSphere μ ∧ + (∀ v ∈ frontier {z | μ z ≤ 1}, ∃! L : Set Plane, + ∃ g : Plane →L[ℝ] ℝ, g ≠ 0 ∧ (∀ z, μ z ≤ 1 → g z ≤ g v) ∧ L={z | g z=g v}) ∧ + (∀ v ∈ frontier {z | μ z ≤ 1}, HasC1CurveChart (frontier {z | μ z ≤ 1}) v) := by + sorry + +end PlanarFPP + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlanarFirstPassage.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarFPP.manuscriptMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/planar-first-passage/solution/closure.txt b/tasks/planar-first-passage/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0b0e9322c1cc66d7f6627b1c49287130513f0af9 --- /dev/null +++ b/tasks/planar-first-passage/solution/closure.txt @@ -0,0 +1,195 @@ +OAI.Probability.FirstPassage.ActualNoCorner +OAI.Probability.FirstPassage.ActualTimeConstant +OAI.Probability.FirstPassage.ActualWitnessScale +OAI.Probability.FirstPassage.AttachmentGeometry +OAI.Probability.FirstPassage.BKBinaryRanks +OAI.Probability.FirstPassage.BKBitLaw +OAI.Probability.FirstPassage.BKContinuous +OAI.Probability.FirstPassage.BKDyadicPaths +OAI.Probability.FirstPassage.BKExponentialQuantiles +OAI.Probability.FirstPassage.BKFamilies +OAI.Probability.FirstPassage.BKForcing +OAI.Probability.FirstPassage.BKLimit +OAI.Probability.FirstPassage.BKPathMeasurability +OAI.Probability.FirstPassage.BKQuantization +OAI.Probability.FirstPassage.BKRepeated +OAI.Probability.FirstPassage.BallTravel +OAI.Probability.FirstPassage.BoundaryCurve +OAI.Probability.FirstPassage.BoundaryCycles +OAI.Probability.FirstPassage.BoundaryGeometry +OAI.Probability.FirstPassage.BoundaryWinding +OAI.Probability.FirstPassage.CharacteristicLengths +OAI.Probability.FirstPassage.CompanionModel +OAI.Probability.FirstPassage.ConnectorEvents +OAI.Probability.FirstPassage.ConnectorGeometry +OAI.Probability.FirstPassage.ConnectorProbability +OAI.Probability.FirstPassage.ContiguousWitnesses +OAI.Probability.FirstPassage.ContourCounts +OAI.Probability.FirstPassage.ContourEnumeration +OAI.Probability.FirstPassage.ContourLocalization +OAI.Probability.FirstPassage.ConvexC1 +OAI.Probability.FirstPassage.CoordinateTails +OAI.Probability.FirstPassage.CrossingChain +OAI.Probability.FirstPassage.CrossingEndpointBounds +OAI.Probability.FirstPassage.CrossingTilt +OAI.Probability.FirstPassage.CrossingTrialGeometry +OAI.Probability.FirstPassage.EnclosingContour +OAI.Probability.FirstPassage.EndpointAsymptotics +OAI.Probability.FirstPassage.EndpointBlocks +OAI.Probability.FirstPassage.EndpointBounds +OAI.Probability.FirstPassage.EndpointCoarse +OAI.Probability.FirstPassage.EndpointCoarseGeometry +OAI.Probability.FirstPassage.EndpointConnection +OAI.Probability.FirstPassage.EndpointEntrance +OAI.Probability.FirstPassage.EndpointEvents +OAI.Probability.FirstPassage.EndpointExit +OAI.Probability.FirstPassage.EndpointExtensions +OAI.Probability.FirstPassage.EndpointGeometry +OAI.Probability.FirstPassage.EndpointLimit +OAI.Probability.FirstPassage.EndpointMesh +OAI.Probability.FirstPassage.EndpointNet +OAI.Probability.FirstPassage.EndpointProbability +OAI.Probability.FirstPassage.EndpointRecords +OAI.Probability.FirstPassage.EndpointTail +OAI.Probability.FirstPassage.EndpointTranslation +OAI.Probability.FirstPassage.ExponentialTilt +OAI.Probability.FirstPassage.ExponentialTiltLaw +OAI.Probability.FirstPassage.ExtremeSlopes +OAI.Probability.FirstPassage.FiniteEdgeEvents +OAI.Probability.FirstPassage.FiniteEdgeTilt +OAI.Probability.FirstPassage.FiniteNet +OAI.Probability.FirstPassage.FiniteTiltLaw +OAI.Probability.FirstPassage.GlobalDifferentiability +OAI.Probability.FirstPassage.GoodSiteEvents +OAI.Probability.FirstPassage.GoodSitePaths +OAI.Probability.FirstPassage.GoodSiteProbability +OAI.Probability.FirstPassage.GridConnectionGeometry +OAI.Probability.FirstPassage.GridConnections +OAI.Probability.FirstPassage.GridCounting +OAI.Probability.FirstPassage.GridMeshes +OAI.Probability.FirstPassage.GridProbability +OAI.Probability.FirstPassage.GridTail +OAI.Probability.FirstPassage.GridTrials +OAI.Probability.FirstPassage.HighDensityOriented +OAI.Probability.FirstPassage.IntervalTravel +OAI.Probability.FirstPassage.LatticeGeometry +OAI.Probability.FirstPassage.LatticeLimitExtension +OAI.Probability.FirstPassage.LatticeSwap +OAI.Probability.FirstPassage.LocalDifferentiability +OAI.Probability.FirstPassage.LocalTravel +OAI.Probability.FirstPassage.Localization +OAI.Probability.FirstPassage.LocalizedEvents +OAI.Probability.FirstPassage.MainTheorem +OAI.Probability.FirstPassage.NoCornerContradiction +OAI.Probability.FirstPassage.NormBoundary +OAI.Probability.FirstPassage.OrientedCompactness +OAI.Probability.FirstPassage.OrientedProbability +OAI.Probability.FirstPassage.PassageTime +OAI.Probability.FirstPassage.PathColumnCrossing +OAI.Probability.FirstPassage.PathConcatenation +OAI.Probability.FirstPassage.PathSubpaths +OAI.Probability.FirstPassage.PathWitnesses +OAI.Probability.FirstPassage.Paths +OAI.Probability.FirstPassage.PlaneGeometry +OAI.Probability.FirstPassage.PositiveMoment +OAI.Probability.FirstPassage.ProbabilityFoundations +OAI.Probability.FirstPassage.RareFast +OAI.Probability.FirstPassage.RareFastEvents +OAI.Probability.FirstPassage.RareFastGeometry +OAI.Probability.FirstPassage.RealScaleConnections +OAI.Probability.FirstPassage.RecordScales +OAI.Probability.FirstPassage.Reversal +OAI.Probability.FirstPassage.SeparatedSelection +OAI.Probability.FirstPassage.ShapeDeficit +OAI.Probability.FirstPassage.ShapeProbability +OAI.Probability.FirstPassage.ShortCrossingGeometry +OAI.Probability.FirstPassage.ShortCrossingProbability +OAI.Probability.FirstPassage.SimplePathApproximation +OAI.Probability.FirstPassage.SourceTilt +OAI.Probability.FirstPassage.SpatialBadPathCover +OAI.Probability.FirstPassage.SpatialChunkGeometry +OAI.Probability.FirstPassage.SpatialChunkWitness +OAI.Probability.FirstPassage.SpatialChunks +OAI.Probability.FirstPassage.SpatialCrossingGeometry +OAI.Probability.FirstPassage.SpatialEntropyProbability +OAI.Probability.FirstPassage.SpatialFirstExit +OAI.Probability.FirstPassage.SpatialModulus +OAI.Probability.FirstPassage.SpatialPositiveChunk +OAI.Probability.FirstPassage.SpatialRareEvents +OAI.Probability.FirstPassage.SpatialWitnessCounts +OAI.Probability.FirstPassage.SpatialWitnesses +OAI.Probability.FirstPassage.SphereCharts +OAI.Probability.FirstPassage.SquareLoops +OAI.Probability.FirstPassage.SupportContactEstimate +OAI.Probability.FirstPassage.Supports +OAI.Probability.FirstPassage.Target +OAI.Probability.FirstPassage.TiltComparison +OAI.Probability.FirstPassage.TiltPath +OAI.Probability.FirstPassage.TiltRegionCount +OAI.Probability.FirstPassage.TiltedRegions +OAI.Probability.FirstPassage.TimeConstantObligation +OAI.Probability.FirstPassage.Translation +OAI.Probability.FirstPassage.UniformShape +OAI.Probability.FirstPassage.UniqueSupports +OAI.Probability.FirstPassage.UnitSphereC1 +OAI.Probability.FirstPassage.VerticalIntervals +OAI.Probability.FirstPassage.Waypoints +OAI.Probability.FirstPassage.WitnessBorelCantelli +OAI.Probability.FirstPassage.WitnessDecomposition +OAI.Probability.FirstPassage.WitnessEntropy +OAI.Probability.FirstPassage.WitnessSelection +OAI.Probability.LatticePassage.BoundedCost +OAI.Probability.LatticePassage.BoundedEfronStein +OAI.Probability.LatticePassage.CalibrationL2 +OAI.Probability.LatticePassage.CalibrationMean +OAI.Probability.LatticePassage.CalibrationShift +OAI.Probability.LatticePassage.CenteredConcentration +OAI.Probability.LatticePassage.CenteredLocalization +OAI.Probability.LatticePassage.CheapPath +OAI.Probability.LatticePassage.CoordinatePath +OAI.Probability.LatticePassage.DirectionalConvergence +OAI.Probability.LatticePassage.DyadicMGF +OAI.Probability.LatticePassage.EdgeInfluence +OAI.Probability.LatticePassage.EfronStein +OAI.Probability.LatticePassage.Environment +OAI.Probability.LatticePassage.ExponentialEnergy +OAI.Probability.LatticePassage.ExponentialIncrement +OAI.Probability.LatticePassage.ExponentialMoment +OAI.Probability.LatticePassage.FiniteProduct +OAI.Probability.LatticePassage.FiniteResampling +OAI.Probability.LatticePassage.FiniteVariance +OAI.Probability.LatticePassage.Geodesic +OAI.Probability.LatticePassage.GeodesicSimple +OAI.Probability.LatticePassage.GeodesicTail +OAI.Probability.LatticePassage.HilbertWeakCompactness +OAI.Probability.LatticePassage.Lattice +OAI.Probability.LatticePassage.LatticeMetric +OAI.Probability.LatticePassage.LocalCovariance +OAI.Probability.LatticePassage.LocalPassage +OAI.Probability.LatticePassage.LocalSelection +OAI.Probability.LatticePassage.LocalizationMean +OAI.Probability.LatticePassage.MeanPositivity +OAI.Probability.LatticePassage.MeanTimeConstant +OAI.Probability.LatticePassage.MetricCalibration +OAI.Probability.LatticePassage.MetricConcentration +OAI.Probability.LatticePassage.Model +OAI.Probability.LatticePassage.NaturalMoment +OAI.Probability.LatticePassage.OffsetCalibration +OAI.Probability.LatticePassage.PassageMGF +OAI.Probability.LatticePassage.PassageRegularity +OAI.Probability.LatticePassage.PassageVariance +OAI.Probability.LatticePassage.PathCounting +OAI.Probability.LatticePassage.Paths +OAI.Probability.LatticePassage.PlanarCalibration +OAI.Probability.LatticePassage.PositiveMoment +OAI.Probability.LatticePassage.ProductVariance +OAI.Probability.LatticePassage.RectangleCalibration +OAI.Probability.LatticePassage.ResamplingMoment +OAI.Probability.LatticePassage.ResamplingSymmetry +OAI.Probability.LatticePassage.ResamplingTransform +OAI.Probability.LatticePassage.SecondMoment +OAI.Probability.LatticePassage.Stationarity +OAI.Probability.LatticePassage.StationaryCalibration +OAI.Probability.LatticePassage.TimeConstantNorm +OAI.Probability.LatticePassage.UniformCheapPaths +OAI.Probability.LatticePassage.WeakCalibration diff --git a/tasks/planar-first-passage/solution/reference.py b/tasks/planar-first-passage/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/planar-first-passage/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/planar-first-passage/solution/solve.sh b/tasks/planar-first-passage/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..584d61139ccce663cf8c7d88c53b0cfafdf107ba --- /dev/null +++ b/tasks/planar-first-passage/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlanarFirstPassage, i.e. module OAI.Probability.FirstPassage.BoundaryCurve and the +# 195 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.FirstPassage.BoundaryCurve /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlanarFirstPassage" diff --git a/tasks/planar-first-passage/task.toml b/tasks/planar-first-passage/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7713551866825ebfbf0e7cad5e37725380984866 --- /dev/null +++ b/tasks/planar-first-passage/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/planar-first-passage" +version = "1.0.0" +description = "Prove PlanarFirstPassage (openai/math family 212: No bigeodesics and smooth limit shapes in planar first-passage percolation) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlanarFirstPassage.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlanarFirstPassage" +family = "212" +family_title = "No bigeodesics and smooth limit shapes in planar first-passage percolation" +subject = "Probability and statistical mechanics" +theorems = ["OAI.PlanarFPP.manuscriptMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.FirstPassage.BoundaryCurve" +reference_modules = 195 +reference_lean_bytes = 854325 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 768 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12468 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/planar-first-passage/tests/Challenge.lean b/tasks/planar-first-passage/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..747a40dc3b5058a23c5f0a1eafe6fe25bd6c4def --- /dev/null +++ b/tasks/planar-first-passage/tests/Challenge.lean @@ -0,0 +1,102 @@ +import Mathlib.Algebra.BigOperators.Group.List.Basic +import Mathlib.Algebra.Group.Prod +import Mathlib.Analysis.Calculus.ContDiff.Defs +import Mathlib.Analysis.Calculus.Deriv.Basic +import Mathlib.Analysis.Calculus.FDeriv.Basic +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Analysis.LocallyConvex.WithSeminorms +import Mathlib.Probability.Distributions.Exponential +import Mathlib.Probability.Independence.Basic + +namespace OAI + +namespace PlanarFPP + +open Set MeasureTheory ProbabilityTheory Filter +open scoped Topology + +abbrev Vertex := ℤ × ℤ + +abbrev Edge := Vertex × Bool + +inductive Step where + | east | west | north | south + deriving DecidableEq + +def Step.delta : Step → Vertex + | .east => (1, 0) + | .west => (-1, 0) + | .north => (0, 1) + | .south => (0, -1) + +def Step.edge (p : Vertex) : Step → Edge + | .east => (p, false) + | .west => (p + (-1, 0), false) + | .north => (p, true) + | .south => (p + (0, -1), true) + +def displacement (ds : List Step) : Vertex := (ds.map Step.delta).sum + +def pathCost (τ : Edge → ℝ) (p : Vertex) : List Step → ℝ + | [] => 0 + | d :: ds => τ (d.edge p) + pathCost τ (p + d.delta) ds + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +noncomputable def latticeFloor (v : Plane) : Vertex := (⌊v 0⌋, ⌊v 1⌋) + +noncomputable def passageTime (τ : Edge → ℝ) (p q : Vertex) : ℝ := + sInf {t | ∃ ds : List Step, p + displacement ds = q ∧ pathCost τ p ds = t} + +structure TimeConstantNorm (μ : Plane → ℝ) : Prop where + nonneg : ∀ v, 0 ≤ μ v + zero_iff : ∀ v, μ v = 0 ↔ v = 0 + triangle : ∀ v w, μ (v + w) ≤ μ v + μ w + homogeneous : ∀ (a : ℝ) v, μ (a • v) = |a| * μ v + +structure ExponentialEnvironment {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) : Prop where + probability : IsProbabilityMeasure P + measurable : ∀ e, Measurable (τ e) + independent : iIndepFun τ P + marginal : ∀ e, Measure.map (τ e) P = expMeasure 1 + +def IsTimeConstant {Ω : Type*} [MeasurableSpace Ω] + (P : Measure Ω) (τ : Edge → Ω → ℝ) (μ : Plane → ℝ) : Prop := + ∀ v : Plane, ∀ᵐ ω ∂P, + Tendsto (fun t : ℝ => passageTime (fun e => τ e ω) (0, 0) + (latticeFloor (t • v)) / t) atTop (𝓝 (μ v)) + +def DifferentiableAwayFromOrigin (μ : Plane → ℝ) : Prop := + ∀ v : Plane, v ≠ 0 → ∃ ℓ : Plane →L[ℝ] ℝ, HasFDerivAt μ ℓ v + +def UniqueNormalizedSupports (μ : Plane → ℝ) : Prop := + ∀ v : Plane, μ v = 1 → ∃! ℓ : Plane →L[ℝ] ℝ, + ℓ v = 1 ∧ ∀ w, ℓ w ≤ μ w + +def C1UnitSphere (μ : Plane → ℝ) : Prop := + ∀ v : Plane, μ v = 1 → ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ + ∃ g : Plane → ℝ, ContDiffOn ℝ 1 g U ∧ + (∀ w ∈ U, μ w = 1 ↔ g w = 0) ∧ + ∀ w ∈ U, g w = 0 → ∃ ℓ : Plane →L[ℝ] ℝ, + HasFDerivAt g ℓ w ∧ ℓ ≠ 0 + +def HasC1CurveChart (S : Set Plane) (v : Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ v ∈ U ∧ v ∈ S ∧ ∃ γ : ℝ → Plane, ∃ θ : Plane → ℝ, + ContDiff ℝ 1 γ ∧ ContinuousOn θ U ∧ + (∀ t, γ t ∈ S ∩ U) ∧ (∀ t, θ (γ t)=t) ∧ + (∀ z ∈ S ∩ U, γ (θ z)=z) ∧ + (∀ t, ∃ d : Plane, HasDerivAt γ d t ∧ d ≠ 0) + +theorem manuscriptMain (Ω : Type) [MeasurableSpace Ω] (P : Measure Ω) (τ : Edge → Ω → ℝ) + (henv : ExponentialEnvironment P τ) : + ∃ μ : Plane → ℝ, TimeConstantNorm μ ∧ IsTimeConstant P τ μ ∧ + DifferentiableAwayFromOrigin μ ∧ UniqueNormalizedSupports μ ∧ C1UnitSphere μ ∧ + (∀ v ∈ frontier {z | μ z ≤ 1}, ∃! L : Set Plane, + ∃ g : Plane →L[ℝ] ℝ, g ≠ 0 ∧ (∀ z, μ z ≤ 1 → g z ≤ g v) ∧ L={z | g z=g v}) ∧ + (∀ v ∈ frontier {z | μ z ≤ 1}, HasC1CurveChart (frontier {z | μ z ≤ 1}) v) := by + sorry + +end PlanarFPP + +end OAI diff --git a/tasks/planar-first-passage/tests/grade.py b/tasks/planar-first-passage/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/planar-first-passage/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/planar-first-passage/tests/task.json b/tasks/planar-first-passage/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..b0fb786b9d962599093232ff5c42c4a5eb58529d --- /dev/null +++ b/tasks/planar-first-passage/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlanarFirstPassage", + "comparator": { + "theorem_names": [ + "OAI.PlanarFPP.manuscriptMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11568 +} \ No newline at end of file diff --git a/tasks/planar-first-passage/tests/test.sh b/tasks/planar-first-passage/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/planar-first-passage/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/planar-l1/environment/Dockerfile b/tasks/planar-l1/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/planar-l1/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/planar-l1/environment/fetch_mathlib.sh b/tasks/planar-l1/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/planar-l1/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/planar-l1/environment/lake-manifest.json b/tasks/planar-l1/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/planar-l1/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/planar-l1/environment/lakefile.lean b/tasks/planar-l1/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/planar-l1/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/planar-l1/environment/lean_setup.sh b/tasks/planar-l1/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/planar-l1/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/planar-l1/environment/pack_submission.py b/tasks/planar-l1/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/planar-l1/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/planar-l1/instruction.md b/tasks/planar-l1/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8534f495c68794d471bb0f30a1a1805dc2dcc687 --- /dev/null +++ b/tasks/planar-l1/instruction.md @@ -0,0 +1,102 @@ +# openai/math challenge `PlanarL1` (family 089) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 089 of the release, *Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs* +(Convex and metric geometry). The family as a whole: Resolves the planar and bounded-treewidth cases of the Gupta–Newman–Rabinovich–Sinclair conjecture. Shortest-path metrics of finite connected graphs with arbitrary positive edge lengths embed into real $L_1$ with universal distortion for planar graphs, and distortion depending only on treewidth for bounded-treewidth graphs. The corresponding multicommodity flow–cut gaps are uniformly bounded. + +The challenge is `PlanarL1`, also at `/opt/openai-math/challenges/PlanarL1.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PlanarL1 + +/-- A topological drawing by simple plane arcs, with injective vertex placement, +no vertex in an edge interior, and disjoint interiors for distinct unoriented edges. -/ +def IsPlanar {V : Type} (G : SimpleGraph V) : Prop := + ∃ (point : V → ℝ × ℝ) (arc : ∀ u v : V, G.Adj u v → C(unitInterval, ℝ × ℝ)), + Function.Injective point ∧ + (∀ u v h, (arc u v h) 0 = point u ∧ (arc u v h) 1 = point v) ∧ + (∀ u v h, Function.Injective (arc u v h)) ∧ + (∀ u v h (t : unitInterval) w, 0 < (t : ℝ) → (t : ℝ) < 1 → + (arc u v h) t ≠ point w) ∧ + (∀ u v h x y k (s t : unitInterval), + 0 < (s : ℝ) → (s : ℝ) < 1 → 0 < (t : ℝ) → (t : ℝ) < 1 → + (arc u v h) s = (arc x y k) t → + (u = x ∧ v = y) ∨ (u = y ∧ v = x)) + +/-- The sum of edge lengths along a finite graph walk. -/ +def walkLength {V : Type} {G : SimpleGraph V} (length : V → V → ℝ) + {u v : V} : G.Walk u v → ℝ + | .nil => 0 + | @SimpleGraph.Walk.cons _ _ u w _ _ p => length u w + walkLength length p + +/-- The infimum of lengths of actual walks between the two vertices. -/ +noncomputable def graphDistance {V : Type} (G : SimpleGraph V) + (length : V → V → ℝ) (u v : V) : ℝ := + sInf (Set.range (fun p : G.Walk u v => walkLength length p)) + +/-- One universal distortion bound for finite connected planar graphs with +arbitrary symmetric positive edge lengths, realized in a real `L¹` space. -/ +def MainStatement : Prop := + ∃ C : ℝ, 1 ≤ C ∧ + ∀ (n : ℕ) (G : SimpleGraph (Fin n)) (length : Fin n → Fin n → ℝ), + G.Connected → IsPlanar G → + (∀ u v, length u v = length v u) → + (∀ u v, G.Adj u v → 0 < length u v) → + ∃ (Ω : Type) (measurable : MeasurableSpace Ω) + (μ : @MeasureTheory.Measure Ω measurable) + (f : Fin n → @MeasureTheory.Lp Ω ℝ measurable _ 1 μ), + ∀ x y, graphDistance G length x y ≤ ‖f x - f y‖ ∧ + ‖f x - f y‖ ≤ C * graphDistance G length x y + +theorem planar_graph_metrics_embed_L1 : MainStatement := by + sorry + +end PlanarL1 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlanarL1.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarL1.planar_graph_metrics_embed_L1` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/planar-l1/solution/closure.txt b/tasks/planar-l1/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e451c3a63bf5bc644759bb428c49709d5af9ee0 --- /dev/null +++ b/tasks/planar-l1/solution/closure.txt @@ -0,0 +1,63 @@ +OAI.Combinatorics.PlanarL1.Ambient +OAI.Combinatorics.PlanarL1.BandTrees +OAI.Combinatorics.PlanarL1.Bands +OAI.Combinatorics.PlanarL1.Clipping +OAI.Combinatorics.PlanarL1.Columns +OAI.Combinatorics.PlanarL1.CoupledState +OAI.Combinatorics.PlanarL1.Crossings +OAI.Combinatorics.PlanarL1.CutExtraction +OAI.Combinatorics.PlanarL1.Cuts +OAI.Combinatorics.PlanarL1.Dilation +OAI.Combinatorics.PlanarL1.DiskCrossing +OAI.Combinatorics.PlanarL1.Distance +OAI.Combinatorics.PlanarL1.Drawing +OAI.Combinatorics.PlanarL1.Embedding +OAI.Combinatorics.PlanarL1.Execution +OAI.Combinatorics.PlanarL1.FamilyPersistence +OAI.Combinatorics.PlanarL1.Fields +OAI.Combinatorics.PlanarL1.FiniteL1 +OAI.Combinatorics.PlanarL1.Gluing +OAI.Combinatorics.PlanarL1.Growth +OAI.Combinatorics.PlanarL1.HeightTree +OAI.Combinatorics.PlanarL1.Increments +OAI.Combinatorics.PlanarL1.Interpolation +OAI.Combinatorics.PlanarL1.Layout +OAI.Combinatorics.PlanarL1.LocalPersistence +OAI.Combinatorics.PlanarL1.MainCells +OAI.Combinatorics.PlanarL1.MainFamily +OAI.Combinatorics.PlanarL1.MainGain +OAI.Combinatorics.PlanarL1.MainPersistence +OAI.Combinatorics.PlanarL1.MainStep +OAI.Combinatorics.PlanarL1.Movement +OAI.Combinatorics.PlanarL1.Noncrossing +OAI.Combinatorics.PlanarL1.Order +OAI.Combinatorics.PlanarL1.OrderedState +OAI.Combinatorics.PlanarL1.OrdinaryState +OAI.Combinatorics.PlanarL1.PairGeometry +OAI.Combinatorics.PlanarL1.PairSelection +OAI.Combinatorics.PlanarL1.Parameters +OAI.Combinatorics.PlanarL1.Persistence +OAI.Combinatorics.PlanarL1.PlanarMetric +OAI.Combinatorics.PlanarL1.Polygonal +OAI.Combinatorics.PlanarL1.Probability +OAI.Combinatorics.PlanarL1.RadialTree +OAI.Combinatorics.PlanarL1.Retubing +OAI.Combinatorics.PlanarL1.ScaleHistory +OAI.Combinatorics.PlanarL1.Schedule +OAI.Combinatorics.PlanarL1.SecondaryBatch +OAI.Combinatorics.PlanarL1.SecondaryCells +OAI.Combinatorics.PlanarL1.SecondaryFamily +OAI.Combinatorics.PlanarL1.SecondaryGain +OAI.Combinatorics.PlanarL1.SecondaryStep +OAI.Combinatorics.PlanarL1.SeedPacking +OAI.Combinatorics.PlanarL1.SelectedGain +OAI.Combinatorics.PlanarL1.Separation +OAI.Combinatorics.PlanarL1.Statement +OAI.Combinatorics.PlanarL1.Stem +OAI.Combinatorics.PlanarL1.StepSuccess +OAI.Combinatorics.PlanarL1.Surgery +OAI.Combinatorics.PlanarL1.SurvivingSeeds +OAI.Combinatorics.PlanarL1.Threshold +OAI.Combinatorics.PlanarL1.Tiling +OAI.Combinatorics.PlanarL1.TreeDisk +OAI.Combinatorics.PlanarL1.WeightedMetric diff --git a/tasks/planar-l1/solution/reference.py b/tasks/planar-l1/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/planar-l1/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/planar-l1/solution/solve.sh b/tasks/planar-l1/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..480e5ad7ca92b4f1d05dd5b766d09381d49a0dd1 --- /dev/null +++ b/tasks/planar-l1/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlanarL1, i.e. module OAI.Combinatorics.PlanarL1.Embedding and the +# 63 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.PlanarL1.Embedding /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlanarL1" diff --git a/tasks/planar-l1/task.toml b/tasks/planar-l1/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..572de97c655d799873ad8dd4aa5ed27e006bb7df --- /dev/null +++ b/tasks/planar-l1/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/planar-l1" +version = "1.0.0" +description = "Prove PlanarL1 (openai/math family 089: Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlanarL1.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlanarL1" +family = "089" +family_title = "Bounded-distortion $L_1$ embeddings of planar and bounded-treewidth graphs" +subject = "Convex and metric geometry" +theorems = ["OAI.PlanarL1.planar_graph_metrics_embed_L1"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.PlanarL1.Embedding" +reference_modules = 63 +reference_lean_bytes = 1567179 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 713 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13110 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/planar-l1/tests/Challenge.lean b/tasks/planar-l1/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0b93c85ebad6b2f9efbeb62cfe1dfc5f61cc8bd9 --- /dev/null +++ b/tasks/planar-l1/tests/Challenge.lean @@ -0,0 +1,51 @@ +import Mathlib + +namespace OAI + +namespace PlanarL1 + +/-- A topological drawing by simple plane arcs, with injective vertex placement, +no vertex in an edge interior, and disjoint interiors for distinct unoriented edges. -/ +def IsPlanar {V : Type} (G : SimpleGraph V) : Prop := + ∃ (point : V → ℝ × ℝ) (arc : ∀ u v : V, G.Adj u v → C(unitInterval, ℝ × ℝ)), + Function.Injective point ∧ + (∀ u v h, (arc u v h) 0 = point u ∧ (arc u v h) 1 = point v) ∧ + (∀ u v h, Function.Injective (arc u v h)) ∧ + (∀ u v h (t : unitInterval) w, 0 < (t : ℝ) → (t : ℝ) < 1 → + (arc u v h) t ≠ point w) ∧ + (∀ u v h x y k (s t : unitInterval), + 0 < (s : ℝ) → (s : ℝ) < 1 → 0 < (t : ℝ) → (t : ℝ) < 1 → + (arc u v h) s = (arc x y k) t → + (u = x ∧ v = y) ∨ (u = y ∧ v = x)) + +/-- The sum of edge lengths along a finite graph walk. -/ +def walkLength {V : Type} {G : SimpleGraph V} (length : V → V → ℝ) + {u v : V} : G.Walk u v → ℝ + | .nil => 0 + | @SimpleGraph.Walk.cons _ _ u w _ _ p => length u w + walkLength length p + +/-- The infimum of lengths of actual walks between the two vertices. -/ +noncomputable def graphDistance {V : Type} (G : SimpleGraph V) + (length : V → V → ℝ) (u v : V) : ℝ := + sInf (Set.range (fun p : G.Walk u v => walkLength length p)) + +/-- One universal distortion bound for finite connected planar graphs with +arbitrary symmetric positive edge lengths, realized in a real `L¹` space. -/ +def MainStatement : Prop := + ∃ C : ℝ, 1 ≤ C ∧ + ∀ (n : ℕ) (G : SimpleGraph (Fin n)) (length : Fin n → Fin n → ℝ), + G.Connected → IsPlanar G → + (∀ u v, length u v = length v u) → + (∀ u v, G.Adj u v → 0 < length u v) → + ∃ (Ω : Type) (measurable : MeasurableSpace Ω) + (μ : @MeasureTheory.Measure Ω measurable) + (f : Fin n → @MeasureTheory.Lp Ω ℝ measurable _ 1 μ), + ∀ x y, graphDistance G length x y ≤ ‖f x - f y‖ ∧ + ‖f x - f y‖ ≤ C * graphDistance G length x y + +theorem planar_graph_metrics_embed_L1 : MainStatement := by + sorry + +end PlanarL1 + +end OAI diff --git a/tasks/planar-l1/tests/grade.py b/tasks/planar-l1/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/planar-l1/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/planar-l1/tests/task.json b/tasks/planar-l1/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6d1b35bc6cd0ae3c21f7e71fb030c957f7ffb65e --- /dev/null +++ b/tasks/planar-l1/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlanarL1", + "comparator": { + "theorem_names": [ + "OAI.PlanarL1.planar_graph_metrics_embed_L1" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12210 +} \ No newline at end of file diff --git a/tasks/planar-l1/tests/test.sh b/tasks/planar-l1/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/planar-l1/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/planar-unit-distances/environment/Dockerfile b/tasks/planar-unit-distances/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/planar-unit-distances/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/planar-unit-distances/environment/fetch_mathlib.sh b/tasks/planar-unit-distances/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/planar-unit-distances/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/planar-unit-distances/environment/lake-manifest.json b/tasks/planar-unit-distances/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/planar-unit-distances/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/planar-unit-distances/environment/lakefile.lean b/tasks/planar-unit-distances/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/planar-unit-distances/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/planar-unit-distances/environment/lean_setup.sh b/tasks/planar-unit-distances/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/planar-unit-distances/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/planar-unit-distances/environment/pack_submission.py b/tasks/planar-unit-distances/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/planar-unit-distances/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/planar-unit-distances/instruction.md b/tasks/planar-unit-distances/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..86e1842d2ab6017ccd7db85f7181793ff8a946fb --- /dev/null +++ b/tasks/planar-unit-distances/instruction.md @@ -0,0 +1,76 @@ +# openai/math challenge `PlanarUnitDistances` (family 167) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 167 of the release, *Pinned distances and a power saving for planar unit distances* +(Combinatorics). The family as a whole: Proves the weak pinned Erd\H{o}s distance conjecture: for every fixed $\varepsilon>0$, all but $o(n)$ points of any $n$-point planar set determine at least $n^{1-\varepsilon}$ distinct nonzero distances. A complementary theorem bounds the number of unit-distance pairs by $O(n^{4/3-\delta})$ for an absolute $\delta>0$. + +The challenge is `PlanarUnitDistances`, also at `/opt/openai-math/challenges/PlanarUnitDistances.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace PlanarUnitDistances + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def IsUnitPair : Sym2 Plane → Prop := + Sym2.lift ⟨fun x y => dist x y = 1, fun x y => by dsimp; rw [dist_comm]⟩ + +noncomputable def unitPairCount (X : Finset Plane) : ℕ := by + classical + exact (X.sym2.filter IsUnitPair).card + +noncomputable def u (n : ℕ) : ℕ := + sSup {m : ℕ | ∃ X : Finset Plane, X.card = n ∧ unitPairCount X = m} + +theorem main : ∃ C β : ℝ, 0 < C ∧ 1 ≤ β ∧ β < (4 : ℝ) / 3 ∧ + ∀ n : ℕ, (u n : ℝ) ≤ C * (n : ℝ) ^ β := by + sorry + +end PlanarUnitDistances + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlanarUnitDistances.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PlanarUnitDistances.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/planar-unit-distances/solution/closure.txt b/tasks/planar-unit-distances/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d26fdbcb274ce1400c5c8b6fbd6d371a6853a729 --- /dev/null +++ b/tasks/planar-unit-distances/solution/closure.txt @@ -0,0 +1,40 @@ +OAI.Geometry.UnitDistances.AbsoluteValues +OAI.Geometry.UnitDistances.Basic +OAI.Geometry.UnitDistances.Blocks +OAI.Geometry.UnitDistances.Circles +OAI.Geometry.UnitDistances.Cross +OAI.Geometry.UnitDistances.Cutting +OAI.Geometry.UnitDistances.Derivations +OAI.Geometry.UnitDistances.Entropy +OAI.Geometry.UnitDistances.Extraction +OAI.Geometry.UnitDistances.GenericCurves +OAI.Geometry.UnitDistances.Grid +OAI.Geometry.UnitDistances.HeightTransfer +OAI.Geometry.UnitDistances.Information +OAI.Geometry.UnitDistances.Integration +OAI.Geometry.UnitDistances.Levels +OAI.Geometry.UnitDistances.Loci +OAI.Geometry.UnitDistances.Main +OAI.Geometry.UnitDistances.Obstruction +OAI.Geometry.UnitDistances.Powers +OAI.Geometry.UnitDistances.PredictionBudget +OAI.Geometry.UnitDistances.Predictions +OAI.Geometry.UnitDistances.Preparation +OAI.Geometry.UnitDistances.Profiles +OAI.Geometry.UnitDistances.Quantization +OAI.Geometry.UnitDistances.Radicals +OAI.Geometry.UnitDistances.RareBudget +OAI.Geometry.UnitDistances.RareEvents +OAI.Geometry.UnitDistances.Regularization +OAI.Geometry.UnitDistances.Sampling +OAI.Geometry.UnitDistances.Scale +OAI.Geometry.UnitDistances.Scores +OAI.Geometry.UnitDistances.Sequence +OAI.Geometry.UnitDistances.Slots +OAI.Geometry.UnitDistances.SmallHeight +OAI.Geometry.UnitDistances.States +OAI.Geometry.UnitDistances.Sweep +OAI.Geometry.UnitDistances.Tails +OAI.Geometry.UnitDistances.Transfer +OAI.Geometry.UnitDistances.Valuations +OAI.Geometry.UnitDistances.Wedges diff --git a/tasks/planar-unit-distances/solution/reference.py b/tasks/planar-unit-distances/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/planar-unit-distances/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/planar-unit-distances/solution/solve.sh b/tasks/planar-unit-distances/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..60cc9824cb55a26b4701856b589ba63ab093bbab --- /dev/null +++ b/tasks/planar-unit-distances/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlanarUnitDistances, i.e. module OAI.Geometry.UnitDistances.Main and the +# 40 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.UnitDistances.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlanarUnitDistances" diff --git a/tasks/planar-unit-distances/task.toml b/tasks/planar-unit-distances/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6fc12b7eedae6ef874bc2172091e8aaf3a76548c --- /dev/null +++ b/tasks/planar-unit-distances/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/planar-unit-distances" +version = "1.0.0" +description = "Prove PlanarUnitDistances (openai/math family 167: Pinned distances and a power saving for planar unit distances) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlanarUnitDistances.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlanarUnitDistances" +family = "167" +family_title = "Pinned distances and a power saving for planar unit distances" +subject = "Combinatorics" +theorems = ["OAI.PlanarUnitDistances.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.UnitDistances.Main" +reference_modules = 40 +reference_lean_bytes = 1344796 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1123 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12910 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/planar-unit-distances/tests/Challenge.lean b/tasks/planar-unit-distances/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..92866ae695092215b79a72c636d9687bfe958304 --- /dev/null +++ b/tasks/planar-unit-distances/tests/Challenge.lean @@ -0,0 +1,25 @@ +import Mathlib + +namespace OAI + +namespace PlanarUnitDistances + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def IsUnitPair : Sym2 Plane → Prop := + Sym2.lift ⟨fun x y => dist x y = 1, fun x y => by dsimp; rw [dist_comm]⟩ + +noncomputable def unitPairCount (X : Finset Plane) : ℕ := by + classical + exact (X.sym2.filter IsUnitPair).card + +noncomputable def u (n : ℕ) : ℕ := + sSup {m : ℕ | ∃ X : Finset Plane, X.card = n ∧ unitPairCount X = m} + +theorem main : ∃ C β : ℝ, 0 < C ∧ 1 ≤ β ∧ β < (4 : ℝ) / 3 ∧ + ∀ n : ℕ, (u n : ℝ) ≤ C * (n : ℝ) ^ β := by + sorry + +end PlanarUnitDistances + +end OAI diff --git a/tasks/planar-unit-distances/tests/grade.py b/tasks/planar-unit-distances/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/planar-unit-distances/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/planar-unit-distances/tests/task.json b/tasks/planar-unit-distances/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..556d99bb6498cc2e832cfe779a0e6d35e6d4e6d4 --- /dev/null +++ b/tasks/planar-unit-distances/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlanarUnitDistances", + "comparator": { + "theorem_names": [ + "OAI.PlanarUnitDistances.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12010 +} \ No newline at end of file diff --git a/tasks/planar-unit-distances/tests/test.sh b/tasks/planar-unit-distances/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/planar-unit-distances/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/plane-coloring/environment/Dockerfile b/tasks/plane-coloring/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/plane-coloring/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/plane-coloring/environment/fetch_mathlib.sh b/tasks/plane-coloring/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/plane-coloring/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/plane-coloring/environment/lake-manifest.json b/tasks/plane-coloring/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/plane-coloring/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/plane-coloring/environment/lakefile.lean b/tasks/plane-coloring/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/plane-coloring/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/plane-coloring/environment/lean_setup.sh b/tasks/plane-coloring/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/plane-coloring/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/plane-coloring/environment/pack_submission.py b/tasks/plane-coloring/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/plane-coloring/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/plane-coloring/instruction.md b/tasks/plane-coloring/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b3e3d3e99b7f38c44a1e79d7c95e35429af17dbc --- /dev/null +++ b/tasks/plane-coloring/instruction.md @@ -0,0 +1,72 @@ +# openai/math challenge `PlaneColoring` (family 158) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 158 of the release, *The Euclidean plane cannot be colored with five colors* +(Combinatorics). The family as a whole: Proves that every five-coloring of the Euclidean plane has a monochromatic pair at distance one, with no restriction on the color classes. This advances the Hadwiger–Nelson problem: together with the classical seven-coloring, only six and seven remain possible chromatic numbers of the plane. + +The challenge is `PlaneColoring`, also at `/opt/openai-math/challenges/PlaneColoring.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem160 + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def ProperColoring (k : ℕ) : Prop := + ∃ c : Plane → Fin k, + ∀ x y : Plane, dist x y = 1 → c x ≠ c y + +theorem properColoring_seven : ProperColoring 7 := by sorry + +end Problem160 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PlaneColoring.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem160.properColoring_seven` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/plane-coloring/solution/closure.txt b/tasks/plane-coloring/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..de5cddbed000b730210e79914a1371afb344f863 --- /dev/null +++ b/tasks/plane-coloring/solution/closure.txt @@ -0,0 +1,9 @@ +OAI.Geometry.PlaneColoring.Assembly +OAI.Geometry.PlaneColoring.Basic +OAI.Geometry.PlaneColoring.Covering +OAI.Geometry.PlaneColoring.Lattice +OAI.Geometry.PlaneColoring.Main +OAI.Geometry.PlaneColoring.MeasurableAssembly +OAI.Geometry.PlaneColoring.MeasurableProper +OAI.Geometry.PlaneColoring.Metric +OAI.Geometry.PlaneColoring.Seven diff --git a/tasks/plane-coloring/solution/reference.py b/tasks/plane-coloring/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/plane-coloring/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/plane-coloring/solution/solve.sh b/tasks/plane-coloring/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4c6fad8b6fb30aa9ff387610711e59093a8ebe95 --- /dev/null +++ b/tasks/plane-coloring/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PlaneColoring, i.e. module OAI.Geometry.PlaneColoring.Main and the +# 9 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.PlaneColoring.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PlaneColoring" diff --git a/tasks/plane-coloring/task.toml b/tasks/plane-coloring/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3c47c1c981e31b42604cbae05abe98d02868848f --- /dev/null +++ b/tasks/plane-coloring/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/plane-coloring" +version = "1.0.0" +description = "Prove PlaneColoring (openai/math family 158: The Euclidean plane cannot be colored with five colors) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PlaneColoring.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PlaneColoring" +family = "158" +family_title = "The Euclidean plane cannot be colored with five colors" +subject = "Combinatorics" +theorems = ["OAI.Problem160.properColoring_seven"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.PlaneColoring.Main" +reference_modules = 9 +reference_lean_bytes = 17840 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 677 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11716 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/plane-coloring/tests/Challenge.lean b/tasks/plane-coloring/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7c836214b1fbdef0ed72ccd619f20bbeb0b66e80 --- /dev/null +++ b/tasks/plane-coloring/tests/Challenge.lean @@ -0,0 +1,21 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem160 + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def ProperColoring (k : ℕ) : Prop := + ∃ c : Plane → Fin k, + ∀ x y : Plane, dist x y = 1 → c x ≠ c y + +theorem properColoring_seven : ProperColoring 7 := by sorry + +end Problem160 + +end + +end OAI diff --git a/tasks/plane-coloring/tests/grade.py b/tasks/plane-coloring/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/plane-coloring/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/plane-coloring/tests/task.json b/tasks/plane-coloring/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..286c6bc54b2b3f6f5f41fa43bc536fe130e21140 --- /dev/null +++ b/tasks/plane-coloring/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PlaneColoring", + "comparator": { + "theorem_names": [ + "OAI.Problem160.properColoring_seven" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10816 +} \ No newline at end of file diff --git a/tasks/plane-coloring/tests/test.sh b/tasks/plane-coloring/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/plane-coloring/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/posterior-replicas/environment/Dockerfile b/tasks/posterior-replicas/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/posterior-replicas/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/posterior-replicas/environment/fetch_mathlib.sh b/tasks/posterior-replicas/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/posterior-replicas/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/posterior-replicas/environment/lake-manifest.json b/tasks/posterior-replicas/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/posterior-replicas/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/posterior-replicas/environment/lakefile.lean b/tasks/posterior-replicas/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/posterior-replicas/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/posterior-replicas/environment/lean_setup.sh b/tasks/posterior-replicas/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/posterior-replicas/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/posterior-replicas/environment/pack_submission.py b/tasks/posterior-replicas/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/posterior-replicas/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/posterior-replicas/instruction.md b/tasks/posterior-replicas/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ffb5f1231f7b0dae7b0e58fc9eb2751699e20aaf --- /dev/null +++ b/tasks/posterior-replicas/instruction.md @@ -0,0 +1,506 @@ +# openai/math challenge `PosteriorReplicas` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `PosteriorReplicas`, also at `/opt/openai-math/challenges/PosteriorReplicas.lean`: + +```lean +import Mathlib + +namespace OAI + +section + +open MeasureTheory ProbabilityTheory InformationTheory Set Matrix +open scoped ENNReal NNReal RealInnerProductSpace Classical + +noncomputable section + +namespace PosteriorReplicas + +abbrev Vec (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Rows (d k : ℕ) := Fin k → Vec d +abbrev Labels (k : ℕ) := Fin k → ℝ +abbrev Data (d k : ℕ) := Rows d k × Labels k +abbrev Tuple (d m : ℕ) := Fin (m + 1) → Vec d + +def sphereLaw (d : ℕ) : Measure (Vec d) := + let σ := (volume : Measure (Vec d)).toSphere + ((σ univ)⁻¹ • σ).map Subtype.val + +def gaussianRows (d k : ℕ) : Measure (Rows d k) := + Measure.pi fun _ => stdGaussian (Vec d) + +instance (d k : ℕ) : IsProbabilityMeasure (gaussianRows d k) := by + unfold gaussianRows + infer_instance + +def labels {d k : ℕ} (A : Rows d k) (s : Vec d) : Labels k := + fun i => ⟪A i, s⟫ + +lemma measurable_labels {d k : ℕ} : + Measurable (fun z : Rows d k × Vec d => labels z.1 z.2) := by + unfold labels + fun_prop + +def messageKernel {d k N : ℕ} (κ : Kernel (Data d k) (Fin N)) : + Kernel (Vec d × Rows d k) (Fin N) := + κ.comap (fun z => (z.2, labels z.2 z.1)) (by + unfold labels + fun_prop) + +instance {d k N : ℕ} (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ] : + IsMarkovKernel (messageKernel κ) := by + unfold messageKernel + infer_instance + +def signalMessageLaw {d k N : ℕ} (p : Measure (Vec d)) + (κ : Kernel (Data d k) (Fin N)) : Measure (Vec d × Fin N) := + ((p.prod (gaussianRows d k)) ⊗ₘ messageKernel κ).map + (fun z => (z.1.1, z.2)) + +instance {d k N : ℕ} (p : Measure (Vec d)) [IsProbabilityMeasure p] + (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ] : + IsProbabilityMeasure (signalMessageLaw p κ) := by + unfold signalMessageLaw + infer_instance + +def sideLaw {d N : ℕ} (ℓ : ℕ) (q : Measure (Vec d × Fin N)) : + Measure (Data d ℓ × (Vec d × Fin N)) := + ((gaussianRows d ℓ).prod q).map + (fun z => ((z.1, labels z.1 z.2.1), z.2)) + +instance {d N : ℕ} (ℓ : ℕ) (q : Measure (Vec d × Fin N)) [IsProbabilityMeasure q] : + IsProbabilityMeasure (sideLaw ℓ q) := by + unfold sideLaw + infer_instance + +def messageEntropy {d N : ℕ} (q : Measure (Vec d × Fin N)) : ℝ := + ∑ w : Fin N, -(q.snd.real {w}) * Real.log (q.snd.real {w}) + +def conditionalInformation {d ℓ N : ℕ} [NeZero N] + (μ : Measure (Data d ℓ × (Vec d × Fin N))) [IsFiniteMeasure μ] : ℝ≥0∞ := + klDiv μ (μ.fst ⊗ₘ (μ.condKernel.fst ×ₖ μ.condKernel.snd)) + +def GaussianReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + let k := 2 * (d / 16) + let t := k + 1 + let ℓ := 4 * k + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (L : ℝ), + Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ L) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw ℓ (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (messageEntropy (signalMessageLaw p κ) / (t : ℝ) + + C * (d : ℝ) + C * Real.log (2 + Real.log L)) + +inductive BaseLaw where + | spherical + | gaussian + deriving DecidableEq + +def BaseLaw.measure (base : BaseLaw) (d : ℕ) : Measure (Vec d) := + match base with + | .spherical => sphereLaw d + | .gaussian => stdGaussian (Vec d) + +def rowGram {d k : ℕ} (A : Rows d k) : Matrix (Fin k) (Fin k) ℝ := + fun i j => ⟪A i, A j⟫ + +def liftLabel {d k : ℕ} (A : Rows d k) (y : Labels k) : Vec d := + ∑ i, ((rowGram A)⁻¹ *ᵥ y) i • A i + +def kernelComponent {d k : ℕ} (A : Rows d k) (x : Vec d) : Vec d := + x - liftLabel A (labels A x) + +def baseFiber {d k : ℕ} (base : BaseLaw) (A : Rows d k) (y : Labels k) : + Measure (Vec d) := + match base with + | .gaussian => (stdGaussian (Vec d)).map + (fun x => liftLabel A y + kernelComponent A x) + | .spherical => (stdGaussian (Vec d)).map + (fun x => liftLabel A y + + (Real.sqrt (1 - ‖liftLabel A y‖ ^ 2) / ‖kernelComponent A x‖) • + kernelComponent A x) + +def baseDensity {d k : ℕ} (base : BaseLaw) (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + if LinearIndependent ℝ A then + match base with + | .gaussian => ENNReal.ofReal + ((2 * Real.pi) ^ (-(k : ℝ) / 2) * + Real.exp (-‖liftLabel A y‖ ^ 2 / 2) / Real.sqrt (rowGram A).det) + | .spherical => if ‖liftLabel A y‖ < 1 then ENNReal.ofReal + (Real.Gamma ((d : ℝ) / 2) / + (Real.pi ^ ((k : ℝ) / 2) * Real.Gamma (((d : ℝ) - k) / 2)) * + (1 - ‖liftLabel A y‖ ^ 2) ^ (((d : ℝ) - k - 2) / 2) / + Real.sqrt (rowGram A).det) else 0 + else 0 + +def tiltMass {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + ∫⁻ x, f x ∂baseFiber base A y + +def projectedDensity {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + baseDensity base A y * tiltMass base f A y + +def tiltedFiber {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : Measure (Vec d) := + if tiltMass base f A y = 0 then Measure.dirac 0 + else (tiltMass base f A y)⁻¹ • (baseFiber base A y).withDensity f + +def differences {d m : ℕ} (u : Tuple d m) : Fin m → Vec d := + fun i => u i.succ - u 0 + +def differenceSpan {d m : ℕ} (u : Tuple d m) : Submodule ℝ (Vec d) := + Submodule.span ℝ (Set.range (differences u)) + +def affineVolume {d m : ℕ} (u : Tuple d m) : ℝ := + Real.sqrt (Matrix.gram ℝ (differences u)).det + +def constrainedRows {d m : ℕ} (k : ℕ) (u : Tuple d m) : Measure (Rows d k) := + (gaussianRows d k).map + (fun A i => (differenceSpan u)ᗮ.starProjection (A i)) + +def equalLabelLeft {d k m : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (H : Rows d k × Labels k × Tuple d m → ℝ≥0∞) : ℝ≥0∞ := + ∫⁻ A, ∫⁻ y, (projectedDensity base f A y) ^ (m + 1) * + ∫⁻ u, H (A, y, u) ∂Measure.pi (fun _ : Fin (m + 1) => tiltedFiber base f A y) + ∂volume ∂gaussianRows d k + +def equalLabelRight {d k m : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (H : Rows d k × Labels k × Tuple d m → ℝ≥0∞) : ℝ≥0∞ := + ENNReal.ofReal ((2 * Real.pi) ^ (-(k * m : ℝ) / 2)) * + ∫⁻ u, (ENNReal.ofReal (affineVolume u))⁻¹ ^ k * + ∫⁻ A, H (A, labels A (u 0), u) ∂constrainedRows k u + ∂Measure.pi (fun _ : Fin (m + 1) => (base.measure d).withDensity f) + +def EqualLabelMeasureIdentity : Prop := + ∀ (d k m : ℕ), 1 ≤ k → 1 ≤ m → k + m ≤ d - 2 → + ∀ (base : BaseLaw) (f : Vec d → ℝ≥0∞), Measurable f → + (∃ L : ℝ≥0∞, L ≠ ∞ ∧ ∀ x, f x ≤ L) → + equalLabelLeft (k := k) (m := m) base f (fun _ => 1) < ∞ ∧ + ∀ H : Rows d k × Labels k × Tuple d m → ℝ≥0∞, + Measurable H → equalLabelLeft base f H = equalLabelRight base f H + +def DistanceReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (b : ℝ), + 0 ≤ b → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ Real.exp b) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d (d / 16)) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw (d / 2) (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (messageEntropy (signalMessageLaw p κ) / ((d / 8 : ℕ) : ℝ) + + C * ((d : ℝ) + b / (d : ℝ))) + +def SyntheticReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 16 ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (L : ℝ), + 1 ≤ L → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ L) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (z : Data d (d / 8) → Fin N) (hz : Measurable z), + conditionalInformation + (sideLaw (d / 2) (signalMessageLaw p (Kernel.deterministic z hz))) ≤ + ENNReal.ofReal (Real.log (N : ℝ) / ((d / 8 : ℕ) : ℝ) + + C * ((d : ℝ) + Real.log (1 + Real.log L))) + +def IncidenceReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (F : ℝ), + 1 ≤ F → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ F) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d (d / 16)) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw (d / 4) (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (Real.log (N : ℝ) / ((d / 16 : ℕ) : ℝ) + + C * (d : ℝ) + C * Real.log (1 + Real.log F)) + +def labelNorm {k : ℕ} (y : Labels k) : ℝ := ‖WithLp.toLp 2 y‖ + +def ballDensityVersion {d k : ℕ} (ν : Measure (Vec d)) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + Filter.liminf (fun n : ℕ => + ((volume : Measure (Labels k)) {v | labelNorm v < (n + 1 : ℝ)⁻¹})⁻¹ * + ν {x | labelNorm (labels A x - y) < (n + 1 : ℝ)⁻¹}) Filter.atTop + +def gaussianDensityVersion {d k : ℕ} (ν : Measure (Vec d)) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + Filter.liminf (fun n : ℕ => ∫⁻ x, + ENNReal.ofReal ((2 * Real.pi * ((n + 1 : ℝ)⁻¹)^2) ^ (-(k : ℝ) / 2) * + Real.exp (-(labelNorm (labels A x - y))^2 / (2 * ((n + 1 : ℝ)⁻¹)^2))) ∂ν) + Filter.atTop + +def EqualLabelVersions : Prop := + ∀ (d k m : ℕ), 1 ≤ k → 1 ≤ m → k + m ≤ d - 2 → + ∀ (base : BaseLaw) (f : Vec d → ℝ≥0∞), Measurable f → + (∃ L : ℝ≥0∞, L ≠ ∞ ∧ ∀ x, f x ≤ L) → + let ν := (base.measure d).withDensity f + (Measurable (fun z : Rows d k × Labels k => projectedDensity base f z.1 z.2)) ∧ + (Measurable (fun z : Rows d k × Labels k => ballDensityVersion ν z.1 z.2)) ∧ + (Measurable (fun z : Rows d k × Labels k => gaussianDensityVersion ν z.1 z.2)) ∧ + (∀ A : Rows d k, LinearIndependent ℝ A → + ν.map (labels A) = volume.withDensity (projectedDensity base f A) ∧ + projectedDensity base f A =ᵐ[volume] ballDensityVersion ν A ∧ + projectedDensity base f A =ᵐ[volume] gaussianDensityVersion ν A) ∧ + (∀ᵐ u ∂Measure.pi (fun _ : Fin (m + 1) => ν), + LinearIndependent ℝ (differences u) ∧ + ∀ᵐ A ∂constrainedRows k u, + LinearIndependent ℝ A ∧ + (∀ i, labels A (u i) = labels A (u 0)) ∧ + (base = .spherical → ‖liftLabel A (labels A (u 0))‖ < 1) ∧ + 0 < projectedDensity base f A (labels A (u 0)) ∧ + projectedDensity base f A (labels A (u 0)) ≠ ∞ ∧ + projectedDensity base f A (labels A (u 0)) = + ballDensityVersion ν A (labels A (u 0)) ∧ + projectedDensity base f A (labels A (u 0)) = + gaussianDensityVersion ν A (labels A (u 0))) + +def haarRows (d ℓ : ℕ) : Measure (Rows d ℓ) := + (gaussianRows d ℓ).map (InnerProductSpace.gramSchmidtNormed ℝ) + +def cmi {Z X Y : Type*} [MeasurableSpace Z] [MeasurableSpace X] [MeasurableSpace Y] + [StandardBorelSpace X] [StandardBorelSpace Y] [Nonempty X] [Nonempty Y] + (μ : Measure (Z × (X × Y))) [IsFiniteMeasure μ] : ℝ≥0∞ := + klDiv μ (μ.fst ⊗ₘ (μ.condKernel.fst ×ₖ μ.condKernel.snd)) + +def finiteEntropy {J : Type*} [Fintype J] [MeasurableSpace J] (μ : Measure J) : ℝ := + ∑ j, - μ.real {j} * Real.log (μ.real {j}) + +def stateMessageKernel {d k V W : ℕ} (κ : Kernel (Fin V × Data d k) (Fin W)) : + Kernel ((Vec d × Fin V) × Rows d k) (Fin W) := + κ.comap (fun z => (z.1.2, (z.2, labels z.2 z.1.1))) (by unfold labels; fun_prop) + +instance {d k V W : ℕ} (κ : Kernel (Fin V × Data d k) (Fin W)) [IsMarkovKernel κ] : + IsMarkovKernel (stateMessageKernel κ) := by + unfold stateMessageKernel + infer_instance + +def stateMessageLaw {d k V W : ℕ} (q : Measure (Vec d × Fin V)) + (κ : Kernel (Fin V × Data d k) (Fin W)) : Measure ((Vec d × Fin V) × Fin W) := + (((q.prod (gaussianRows d k)) ⊗ₘ stateMessageKernel κ).map + (fun z => (z.1.1, z.2))) + +instance {d k V W : ℕ} (q : Measure (Vec d × Fin V)) [IsProbabilityMeasure q] + (κ : Kernel (Fin V × Data d k) (Fin W)) [IsMarkovKernel κ] : + IsProbabilityMeasure (stateMessageLaw q κ) := by + unfold stateMessageLaw + infer_instance + +def stateHaarSideLaw {d V W : ℕ} (ℓ : ℕ) + (q : Measure ((Vec d × Fin V) × Fin W)) : + Measure ((Fin V × Data d ℓ) × (Vec d × Fin W)) := + ((haarRows d ℓ).prod q).map + (fun z => ((z.2.1.2, (z.1, labels z.1 z.2.1.1)), (z.2.1.1, z.2.2))) + +instance {d V W : ℕ} (ℓ : ℕ) + (q : Measure ((Vec d × Fin V) × Fin W)) [IsFiniteMeasure q] : + IsFiniteMeasure (stateHaarSideLaw ℓ q) := by + unfold stateHaarSideLaw haarRows + infer_instance + +def terminalConditionalEntropy {d V W : ℕ} + (q : Measure ((Vec d × Fin V) × Fin W)) : ℝ := + finiteEntropy (q.map (fun z => (z.1.2, z.2))) - finiteEntropy (q.map (fun z => z.1.2)) + +def HaarReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 64 ≤ d → + ∀ (V W : ℕ) [NeZero V] [NeZero W] + (q : Measure (Vec d × Fin V)) [IsProbabilityMeasure q], + q.fst = sphereLaw d → + ∀ (κ : Kernel (Fin V × Data d (d / 16)) (Fin W)) [IsMarkovKernel κ], + cmi (stateHaarSideLaw (d / 4) (stateMessageLaw q κ)) ≤ + ENNReal.ofReal (terminalConditionalEntropy (stateMessageLaw q κ) / + ((d / 16 + 1 : ℕ) : ℝ) + C * (d : ℝ) + + Real.log (1 + C * (d : ℝ) + finiteEntropy q.snd) + + C * (finiteEntropy q.snd + Real.log (d : ℝ)) / (d : ℝ)^2) + +end PosteriorReplicas +end +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace + +noncomputable section + +universe u + +namespace PosteriorRegression + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +end Learner + +end PosteriorRegression + +open MeasureTheory ProbabilityTheory InformationTheory Set Matrix +open scoped ENNReal NNReal RealInnerProductSpace Classical + +noncomputable section + +namespace PosteriorRegression +abbrev CompletedObservation (d : ℕ) := NullMeasurableSpace (Vector d × ℝ) (observationReference d) +abbrev Destination (M : ℕ) := Bool × State M + +structure CompletedKernelLearner (d M : ℕ) where + initial : Measure (Destination M) + initial_probability : IsProbabilityMeasure initial + transition : ℕ → State M → Kernel (CompletedObservation d) (Destination M) + transition_markov : ∀ t a, IsMarkovKernel (transition t a) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t a, IsProbabilityMeasure (output t a) + +attribute [instance] CompletedKernelLearner.initial_probability + CompletedKernelLearner.transition_markov CompletedKernelLearner.output_probability + +namespace CompletedKernelLearner +open Learner +def destStatus {M : ℕ} (n : ℕ) (v : Destination M) : RunStatus M := + if v.1 then Sum.inr (n,v.2) else Sum.inl v.2 + +def finishState {M : ℕ} (T : ℕ) : RunStatus M → ℕ × State M + | .inl a => (T,a) + | .inr done => done + +def stepMeasure {d M T : ℕ} (K : CompletedKernelLearner d M) + (s : UnitSphere d) (x : Samples d T) (i : Fin T) : RunStatus M → Measure (RunStatus M) + | .inr done => Measure.dirac (.inr done) + | .inl a => (K.transition (i.val+1) a (x i,⟪x i,s.val⟫)).map (destStatus (i.val+1)) + +def runMeasure {d M T : ℕ} (K : CompletedKernelLearner d M) + (s : UnitSphere d) (x : Samples d T) : ℕ → Measure (RunStatus M) + | 0 => K.initial.map (destStatus 0) + | n+1 => if hn : n K.output a.1 a.2) + +end CompletedKernelLearner + +structure JointKernelExperiment (d M T : ℕ) (Ω : Type u) [MeasurableSpace Ω] + (ρ : Measure Ω) where + rules : Ω → CompletedKernelLearner d M + outputKernel : Kernel (Ω × (UnitSphere d × Samples d T)) (UnitSphere d) + output_markov : IsMarkovKernel outputKernel + conditional_output : ∀ᵐ ω ∂ρ, ∀ᵐ z ∂((uniformSphere d).prod (sampleLaw d T)), + outputKernel (ω,z) = (rules ω).estimateLaw z.1 z.2 + +attribute [instance] JointKernelExperiment.output_markov + +namespace JointKernelExperiment +open Learner +def law {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] {ρ : Measure Ω} + (E : JointKernelExperiment d M T Ω ρ) : Measure ((Ω × (UnitSphere d × Samples d T)) × UnitSphere d) := + (ρ.prod ((uniformSphere d).prod (sampleLaw d T))) ⊗ₘ E.outputKernel + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] {ρ : Measure Ω} + (E : JointKernelExperiment d M T Ω ρ) (ε : ℝ) : ℝ≥0∞ := + E.law {z | angularError z.1.2.1 z.2 ≤ ε} + +end JointKernelExperiment + +def KernelSubquadraticMemory : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0<ε → ε≤1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ E : JointKernelExperiment d (M d) T Ω ρ, + (2/3 : ℝ≥0∞) ≤ E.uniformSuccess ε → + c * (d : ℝ) * Real.log (1/ε) ≤ (T : ℝ) + +end PosteriorRegression + +namespace PosteriorReplicas + +end PosteriorReplicas +end +end + +namespace PosteriorReplicas + +universe u + +theorem source_main : EqualLabelMeasureIdentity ∧ EqualLabelVersions ∧ + GaussianReplicaBlock ∧ DistanceReplicaBlock ∧ HaarReplicaBlock ∧ + SyntheticReplicaBlock ∧ IncidenceReplicaBlock ∧ + PosteriorRegression.KernelSubquadraticMemory.{u} := by + sorry + +end PosteriorReplicas + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PosteriorReplicas.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PosteriorReplicas.source_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/posterior-replicas/solution/closure.txt b/tasks/posterior-replicas/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..91e04862ad329a4d5824fc27a0a8738350b80d6b --- /dev/null +++ b/tasks/posterior-replicas/solution/closure.txt @@ -0,0 +1,136 @@ +OAI.Probability.PosteriorReplicas.Gaussian.ConstrainedGaussian +OAI.Probability.PosteriorReplicas.Gaussian.ConstrainedNoise +OAI.Probability.PosteriorReplicas.Gaussian.GaussianDensity +OAI.Probability.PosteriorReplicas.Gaussian.GaussianFiber +OAI.Probability.PosteriorReplicas.Gaussian.GaussianGramMoment +OAI.Probability.PosteriorReplicas.Gaussian.GaussianLogMoment +OAI.Probability.PosteriorReplicas.Gaussian.GaussianPolar +OAI.Probability.PosteriorReplicas.Gaussian.GaussianRowMix +OAI.Probability.PosteriorReplicas.Gaussian.GaussianSmallBall +OAI.Probability.PosteriorReplicas.Gaussian.GaussianWishart +OAI.Probability.PosteriorReplicas.Gaussian.GramTransform +OAI.Probability.PosteriorReplicas.Gaussian.MatrixNoise +OAI.Probability.PosteriorReplicas.Gaussian.ObservableGaussian +OAI.Probability.PosteriorReplicas.Gaussian.RadialIntegrals +OAI.Probability.PosteriorReplicas.Gaussian.RandomComplement +OAI.Probability.PosteriorReplicas.Geometry.AffineMoments +OAI.Probability.PosteriorReplicas.Geometry.BallJacobian +OAI.Probability.PosteriorReplicas.Geometry.BaseContinuity +OAI.Probability.PosteriorReplicas.Geometry.BaseFunProp +OAI.Probability.PosteriorReplicas.Geometry.BaseGeometry +OAI.Probability.PosteriorReplicas.Geometry.DensityBinEnvelope +OAI.Probability.PosteriorReplicas.Geometry.DensityBinsGeometry +OAI.Probability.PosteriorReplicas.Geometry.FrameTubes +OAI.Probability.PosteriorReplicas.Geometry.InverseMomentBins +OAI.Probability.PosteriorReplicas.Geometry.LabelConvolution +OAI.Probability.PosteriorReplicas.Geometry.LabelEllipsoids +OAI.Probability.PosteriorReplicas.Geometry.SphereDensity +OAI.Probability.PosteriorReplicas.Geometry.SphereSubspace +OAI.Probability.PosteriorReplicas.Geometry.SphereTubeQuantitative +OAI.Probability.PosteriorReplicas.Geometry.TupleMoments +OAI.Probability.PosteriorReplicas.Information.BinCutoff +OAI.Probability.PosteriorReplicas.Information.CmiKernel +OAI.Probability.PosteriorReplicas.Information.ConditionalKL +OAI.Probability.PosteriorReplicas.Information.ConditionalPiKL +OAI.Probability.PosteriorReplicas.Information.EntropyLossTest +OAI.Probability.PosteriorReplicas.Information.EntropyTest +OAI.Probability.PosteriorReplicas.Information.FiniteConditionalEntropy +OAI.Probability.PosteriorReplicas.Information.FiniteEntropyBounds +OAI.Probability.PosteriorReplicas.Information.FiniteKL +OAI.Probability.PosteriorReplicas.Information.FiniteStateDensity +OAI.Probability.PosteriorReplicas.Information.GenericInformationBound +OAI.Probability.PosteriorReplicas.Information.GraphKL +OAI.Probability.PosteriorReplicas.Information.HaarInformationEq +OAI.Probability.PosteriorReplicas.Information.HaarStateBound +OAI.Probability.PosteriorReplicas.Information.HeadlineInformation +OAI.Probability.PosteriorReplicas.Information.KLTools +OAI.Probability.PosteriorReplicas.Information.LikelihoodIntegrability +OAI.Probability.PosteriorReplicas.Information.LogComparison +OAI.Probability.PosteriorReplicas.Information.NormalizedLikelihood +OAI.Probability.PosteriorReplicas.Information.ObservableLikelihood +OAI.Probability.PosteriorReplicas.Information.ObservationCorrelation +OAI.Probability.PosteriorReplicas.Information.ParametricKernel +OAI.Probability.PosteriorReplicas.Information.PiKL +OAI.Probability.PosteriorReplicas.Information.RandomCorrelation +OAI.Probability.PosteriorReplicas.Information.RandomProjectionInformation +OAI.Probability.PosteriorReplicas.Information.ReplicaCost +OAI.Probability.PosteriorReplicas.Information.ReplicaFiniteKL +OAI.Probability.PosteriorReplicas.Information.ReplicaInformation +OAI.Probability.PosteriorReplicas.Information.ReplicaInformationBound +OAI.Probability.PosteriorReplicas.Information.ReplicaLoss +OAI.Probability.PosteriorReplicas.Information.ReplicaMeasureInformation +OAI.Probability.PosteriorReplicas.Information.StateExperiment +OAI.Probability.PosteriorReplicas.Information.StateSide +OAI.Probability.PosteriorReplicas.Kernels.DensityRatio +OAI.Probability.PosteriorReplicas.Kernels.KernelPi +OAI.Probability.PosteriorReplicas.Kernels.LiftedReplica +OAI.Probability.PosteriorReplicas.Kernels.PosteriorExperiment +OAI.Probability.PosteriorReplicas.Kernels.PosteriorKernel +OAI.Probability.PosteriorReplicas.Kernels.ReplicaGaussianMarginals +OAI.Probability.PosteriorReplicas.Kernels.ReplicaMeasure +OAI.Probability.PosteriorReplicas.Kernels.ReplicaTupleMarginals +OAI.Probability.PosteriorReplicas.Learners.CompletedKernelLaw +OAI.Probability.PosteriorReplicas.Learners.CompletedKernelLearner +OAI.Probability.PosteriorReplicas.Learners.HaarLawIdentification +OAI.Probability.PosteriorReplicas.Learners.JointKernelExperiment +OAI.Probability.PosteriorReplicas.Learners.JointLawBridge +OAI.Probability.PosteriorReplicas.Learners.KernelLearnerBridge +OAI.Probability.PosteriorReplicas.Learners.KernelSuccess +OAI.Probability.PosteriorReplicas.Learners.LearnerModelBridge +OAI.Probability.PosteriorReplicas.Main +OAI.Probability.PosteriorReplicas.Measures.BaseDisintegration +OAI.Probability.PosteriorReplicas.Measures.ConstrainedDensityExpectation +OAI.Probability.PosteriorReplicas.Measures.DensityDifferentiation +OAI.Probability.PosteriorReplicas.Measures.DensityTools +OAI.Probability.PosteriorReplicas.Measures.EqualApproximation +OAI.Probability.PosteriorReplicas.Measures.EqualBaseMeasures +OAI.Probability.PosteriorReplicas.Measures.EqualLabelIdentity +OAI.Probability.PosteriorReplicas.Measures.EqualLabelTransfer +OAI.Probability.PosteriorReplicas.Measures.EqualLabelVersions +OAI.Probability.PosteriorReplicas.Measures.EqualRightMeasure +OAI.Probability.PosteriorReplicas.Measures.EuclideanLabels +OAI.Probability.PosteriorReplicas.Measures.GaussianConstant +OAI.Probability.PosteriorReplicas.Measures.GaussianDifferentiation +OAI.Probability.PosteriorReplicas.Measures.PiTools +OAI.Probability.PosteriorReplicas.Measures.ProductFibers +OAI.Probability.PosteriorReplicas.Measures.ReferenceMoments +OAI.Probability.PosteriorReplicas.Measures.TiltNormalization +OAI.Probability.PosteriorReplicas.Model +OAI.Probability.PosteriorReplicas.Regression.AePiLast +OAI.Probability.PosteriorReplicas.Regression.AffineTubes +OAI.Probability.PosteriorReplicas.Regression.Conclusions +OAI.Probability.PosteriorReplicas.Regression.EuclideanNets +OAI.Probability.PosteriorReplicas.Regression.FiniteNets +OAI.Probability.PosteriorReplicas.Regression.FrostmanGeometry +OAI.Probability.PosteriorReplicas.Regression.Fubini +OAI.Probability.PosteriorReplicas.Regression.GaussianDomination +OAI.Probability.PosteriorReplicas.Regression.GaussianKernel +OAI.Probability.PosteriorReplicas.Regression.GaussianNoise +OAI.Probability.PosteriorReplicas.Regression.GramDistances +OAI.Probability.PosteriorReplicas.Regression.GramFactorization +OAI.Probability.PosteriorReplicas.Regression.HolderSet +OAI.Probability.PosteriorReplicas.Regression.InverseMoments +OAI.Probability.PosteriorReplicas.Regression.LabelDependence +OAI.Probability.PosteriorReplicas.Regression.LearnerBasics +OAI.Probability.PosteriorReplicas.Regression.LimitSet +OAI.Probability.PosteriorReplicas.Regression.LowerFubini +OAI.Probability.PosteriorReplicas.Regression.MemoryBounds +OAI.Probability.PosteriorReplicas.Regression.MemoryPrecision +OAI.Probability.PosteriorReplicas.Regression.ObservationContinuity +OAI.Probability.PosteriorReplicas.Regression.OuterBound +OAI.Probability.PosteriorReplicas.Regression.PiLast +OAI.Probability.PosteriorReplicas.Regression.ProductDensity +OAI.Probability.PosteriorReplicas.Regression.ProjectionBlocks +OAI.Probability.PosteriorReplicas.Regression.ProjectionCoupling +OAI.Probability.PosteriorReplicas.Regression.ReplicaKernel +OAI.Probability.PosteriorReplicas.Regression.ReplicaMoments +OAI.Probability.PosteriorReplicas.Regression.ReplicaNondegenerate +OAI.Probability.PosteriorReplicas.Regression.SmoothingMoments +OAI.Probability.PosteriorReplicas.Regression.SphereBounds +OAI.Probability.PosteriorReplicas.Regression.SphereGeometry +OAI.Probability.PosteriorReplicas.Regression.StreamCaps +OAI.Probability.PosteriorReplicas.Regression.StreamEstimates +OAI.Probability.PosteriorReplicas.Regression.StreamIntegrals +OAI.Probability.PosteriorReplicas.Regression.StreamSlices +OAI.Probability.PosteriorReplicas.Regression.StreamTransfer +OAI.Probability.PosteriorReplicas.Regression.SupportVolume diff --git a/tasks/posterior-replicas/solution/reference.py b/tasks/posterior-replicas/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/posterior-replicas/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/posterior-replicas/solution/solve.sh b/tasks/posterior-replicas/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b9092793c0ff845f4d6cde87fe28a195079e8f9e --- /dev/null +++ b/tasks/posterior-replicas/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PosteriorReplicas, i.e. module OAI.Probability.PosteriorReplicas.Main and the +# 136 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.PosteriorReplicas.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PosteriorReplicas" diff --git a/tasks/posterior-replicas/task.toml b/tasks/posterior-replicas/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..cfa214ca85d367cf63e22942d51e1074048e7ca4 --- /dev/null +++ b/tasks/posterior-replicas/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/posterior-replicas" +version = "1.0.0" +description = "Prove PosteriorReplicas (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PosteriorReplicas.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PosteriorReplicas" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.PosteriorReplicas.source_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.PosteriorReplicas.Main" +reference_modules = 136 +reference_lean_bytes = 716462 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1090 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12344 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/posterior-replicas/tests/Challenge.lean b/tasks/posterior-replicas/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..be840922beb1feff22f51fa3d0c5b1d21f2f2211 --- /dev/null +++ b/tasks/posterior-replicas/tests/Challenge.lean @@ -0,0 +1,455 @@ +import Mathlib + +namespace OAI + +section + +open MeasureTheory ProbabilityTheory InformationTheory Set Matrix +open scoped ENNReal NNReal RealInnerProductSpace Classical + +noncomputable section + +namespace PosteriorReplicas + +abbrev Vec (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Rows (d k : ℕ) := Fin k → Vec d +abbrev Labels (k : ℕ) := Fin k → ℝ +abbrev Data (d k : ℕ) := Rows d k × Labels k +abbrev Tuple (d m : ℕ) := Fin (m + 1) → Vec d + +def sphereLaw (d : ℕ) : Measure (Vec d) := + let σ := (volume : Measure (Vec d)).toSphere + ((σ univ)⁻¹ • σ).map Subtype.val + +def gaussianRows (d k : ℕ) : Measure (Rows d k) := + Measure.pi fun _ => stdGaussian (Vec d) + +instance (d k : ℕ) : IsProbabilityMeasure (gaussianRows d k) := by + unfold gaussianRows + infer_instance + +def labels {d k : ℕ} (A : Rows d k) (s : Vec d) : Labels k := + fun i => ⟪A i, s⟫ + +lemma measurable_labels {d k : ℕ} : + Measurable (fun z : Rows d k × Vec d => labels z.1 z.2) := by + unfold labels + fun_prop + +def messageKernel {d k N : ℕ} (κ : Kernel (Data d k) (Fin N)) : + Kernel (Vec d × Rows d k) (Fin N) := + κ.comap (fun z => (z.2, labels z.2 z.1)) (by + unfold labels + fun_prop) + +instance {d k N : ℕ} (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ] : + IsMarkovKernel (messageKernel κ) := by + unfold messageKernel + infer_instance + +def signalMessageLaw {d k N : ℕ} (p : Measure (Vec d)) + (κ : Kernel (Data d k) (Fin N)) : Measure (Vec d × Fin N) := + ((p.prod (gaussianRows d k)) ⊗ₘ messageKernel κ).map + (fun z => (z.1.1, z.2)) + +instance {d k N : ℕ} (p : Measure (Vec d)) [IsProbabilityMeasure p] + (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ] : + IsProbabilityMeasure (signalMessageLaw p κ) := by + unfold signalMessageLaw + infer_instance + +def sideLaw {d N : ℕ} (ℓ : ℕ) (q : Measure (Vec d × Fin N)) : + Measure (Data d ℓ × (Vec d × Fin N)) := + ((gaussianRows d ℓ).prod q).map + (fun z => ((z.1, labels z.1 z.2.1), z.2)) + +instance {d N : ℕ} (ℓ : ℕ) (q : Measure (Vec d × Fin N)) [IsProbabilityMeasure q] : + IsProbabilityMeasure (sideLaw ℓ q) := by + unfold sideLaw + infer_instance + +def messageEntropy {d N : ℕ} (q : Measure (Vec d × Fin N)) : ℝ := + ∑ w : Fin N, -(q.snd.real {w}) * Real.log (q.snd.real {w}) + +def conditionalInformation {d ℓ N : ℕ} [NeZero N] + (μ : Measure (Data d ℓ × (Vec d × Fin N))) [IsFiniteMeasure μ] : ℝ≥0∞ := + klDiv μ (μ.fst ⊗ₘ (μ.condKernel.fst ×ₖ μ.condKernel.snd)) + +def GaussianReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + let k := 2 * (d / 16) + let t := k + 1 + let ℓ := 4 * k + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (L : ℝ), + Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ L) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d k) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw ℓ (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (messageEntropy (signalMessageLaw p κ) / (t : ℝ) + + C * (d : ℝ) + C * Real.log (2 + Real.log L)) + +inductive BaseLaw where + | spherical + | gaussian + deriving DecidableEq + +def BaseLaw.measure (base : BaseLaw) (d : ℕ) : Measure (Vec d) := + match base with + | .spherical => sphereLaw d + | .gaussian => stdGaussian (Vec d) + +def rowGram {d k : ℕ} (A : Rows d k) : Matrix (Fin k) (Fin k) ℝ := + fun i j => ⟪A i, A j⟫ + +def liftLabel {d k : ℕ} (A : Rows d k) (y : Labels k) : Vec d := + ∑ i, ((rowGram A)⁻¹ *ᵥ y) i • A i + +def kernelComponent {d k : ℕ} (A : Rows d k) (x : Vec d) : Vec d := + x - liftLabel A (labels A x) + +def baseFiber {d k : ℕ} (base : BaseLaw) (A : Rows d k) (y : Labels k) : + Measure (Vec d) := + match base with + | .gaussian => (stdGaussian (Vec d)).map + (fun x => liftLabel A y + kernelComponent A x) + | .spherical => (stdGaussian (Vec d)).map + (fun x => liftLabel A y + + (Real.sqrt (1 - ‖liftLabel A y‖ ^ 2) / ‖kernelComponent A x‖) • + kernelComponent A x) + +def baseDensity {d k : ℕ} (base : BaseLaw) (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + if LinearIndependent ℝ A then + match base with + | .gaussian => ENNReal.ofReal + ((2 * Real.pi) ^ (-(k : ℝ) / 2) * + Real.exp (-‖liftLabel A y‖ ^ 2 / 2) / Real.sqrt (rowGram A).det) + | .spherical => if ‖liftLabel A y‖ < 1 then ENNReal.ofReal + (Real.Gamma ((d : ℝ) / 2) / + (Real.pi ^ ((k : ℝ) / 2) * Real.Gamma (((d : ℝ) - k) / 2)) * + (1 - ‖liftLabel A y‖ ^ 2) ^ (((d : ℝ) - k - 2) / 2) / + Real.sqrt (rowGram A).det) else 0 + else 0 + +def tiltMass {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + ∫⁻ x, f x ∂baseFiber base A y + +def projectedDensity {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + baseDensity base A y * tiltMass base f A y + +def tiltedFiber {d k : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (A : Rows d k) (y : Labels k) : Measure (Vec d) := + if tiltMass base f A y = 0 then Measure.dirac 0 + else (tiltMass base f A y)⁻¹ • (baseFiber base A y).withDensity f + +def differences {d m : ℕ} (u : Tuple d m) : Fin m → Vec d := + fun i => u i.succ - u 0 + +def differenceSpan {d m : ℕ} (u : Tuple d m) : Submodule ℝ (Vec d) := + Submodule.span ℝ (Set.range (differences u)) + +def affineVolume {d m : ℕ} (u : Tuple d m) : ℝ := + Real.sqrt (Matrix.gram ℝ (differences u)).det + +def constrainedRows {d m : ℕ} (k : ℕ) (u : Tuple d m) : Measure (Rows d k) := + (gaussianRows d k).map + (fun A i => (differenceSpan u)ᗮ.starProjection (A i)) + +def equalLabelLeft {d k m : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (H : Rows d k × Labels k × Tuple d m → ℝ≥0∞) : ℝ≥0∞ := + ∫⁻ A, ∫⁻ y, (projectedDensity base f A y) ^ (m + 1) * + ∫⁻ u, H (A, y, u) ∂Measure.pi (fun _ : Fin (m + 1) => tiltedFiber base f A y) + ∂volume ∂gaussianRows d k + +def equalLabelRight {d k m : ℕ} (base : BaseLaw) (f : Vec d → ℝ≥0∞) + (H : Rows d k × Labels k × Tuple d m → ℝ≥0∞) : ℝ≥0∞ := + ENNReal.ofReal ((2 * Real.pi) ^ (-(k * m : ℝ) / 2)) * + ∫⁻ u, (ENNReal.ofReal (affineVolume u))⁻¹ ^ k * + ∫⁻ A, H (A, labels A (u 0), u) ∂constrainedRows k u + ∂Measure.pi (fun _ : Fin (m + 1) => (base.measure d).withDensity f) + +def EqualLabelMeasureIdentity : Prop := + ∀ (d k m : ℕ), 1 ≤ k → 1 ≤ m → k + m ≤ d - 2 → + ∀ (base : BaseLaw) (f : Vec d → ℝ≥0∞), Measurable f → + (∃ L : ℝ≥0∞, L ≠ ∞ ∧ ∀ x, f x ≤ L) → + equalLabelLeft (k := k) (m := m) base f (fun _ => 1) < ∞ ∧ + ∀ H : Rows d k × Labels k × Tuple d m → ℝ≥0∞, + Measurable H → equalLabelLeft base f H = equalLabelRight base f H + +def DistanceReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (b : ℝ), + 0 ≤ b → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ Real.exp b) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d (d / 16)) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw (d / 2) (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (messageEntropy (signalMessageLaw p κ) / ((d / 8 : ℕ) : ℝ) + + C * ((d : ℝ) + b / (d : ℝ))) + +def SyntheticReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 16 ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (L : ℝ), + 1 ≤ L → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ L) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (z : Data d (d / 8) → Fin N) (hz : Measurable z), + conditionalInformation + (sideLaw (d / 2) (signalMessageLaw p (Kernel.deterministic z hz))) ≤ + ENNReal.ofReal (Real.log (N : ℝ) / ((d / 8 : ℕ) : ℝ) + + C * ((d : ℝ) + Real.log (1 + Real.log L))) + +def IncidenceReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∀ (p : Measure (Vec d)) [IsProbabilityMeasure p] + (f : Vec d → ℝ) (F : ℝ), + 1 ≤ F → Measurable f → (∀ x, 0 ≤ f x ∧ f x ≤ F) → + p = (sphereLaw d).withDensity (fun x => ENNReal.ofReal (f x)) → + ∀ (N : ℕ) [NeZero N] (κ : Kernel (Data d (d / 16)) (Fin N)) [IsMarkovKernel κ], + conditionalInformation (sideLaw (d / 4) (signalMessageLaw p κ)) ≤ + ENNReal.ofReal (Real.log (N : ℝ) / ((d / 16 : ℕ) : ℝ) + + C * (d : ℝ) + C * Real.log (1 + Real.log F)) + +def labelNorm {k : ℕ} (y : Labels k) : ℝ := ‖WithLp.toLp 2 y‖ + +def ballDensityVersion {d k : ℕ} (ν : Measure (Vec d)) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + Filter.liminf (fun n : ℕ => + ((volume : Measure (Labels k)) {v | labelNorm v < (n + 1 : ℝ)⁻¹})⁻¹ * + ν {x | labelNorm (labels A x - y) < (n + 1 : ℝ)⁻¹}) Filter.atTop + +def gaussianDensityVersion {d k : ℕ} (ν : Measure (Vec d)) + (A : Rows d k) (y : Labels k) : ℝ≥0∞ := + Filter.liminf (fun n : ℕ => ∫⁻ x, + ENNReal.ofReal ((2 * Real.pi * ((n + 1 : ℝ)⁻¹)^2) ^ (-(k : ℝ) / 2) * + Real.exp (-(labelNorm (labels A x - y))^2 / (2 * ((n + 1 : ℝ)⁻¹)^2))) ∂ν) + Filter.atTop + +def EqualLabelVersions : Prop := + ∀ (d k m : ℕ), 1 ≤ k → 1 ≤ m → k + m ≤ d - 2 → + ∀ (base : BaseLaw) (f : Vec d → ℝ≥0∞), Measurable f → + (∃ L : ℝ≥0∞, L ≠ ∞ ∧ ∀ x, f x ≤ L) → + let ν := (base.measure d).withDensity f + (Measurable (fun z : Rows d k × Labels k => projectedDensity base f z.1 z.2)) ∧ + (Measurable (fun z : Rows d k × Labels k => ballDensityVersion ν z.1 z.2)) ∧ + (Measurable (fun z : Rows d k × Labels k => gaussianDensityVersion ν z.1 z.2)) ∧ + (∀ A : Rows d k, LinearIndependent ℝ A → + ν.map (labels A) = volume.withDensity (projectedDensity base f A) ∧ + projectedDensity base f A =ᵐ[volume] ballDensityVersion ν A ∧ + projectedDensity base f A =ᵐ[volume] gaussianDensityVersion ν A) ∧ + (∀ᵐ u ∂Measure.pi (fun _ : Fin (m + 1) => ν), + LinearIndependent ℝ (differences u) ∧ + ∀ᵐ A ∂constrainedRows k u, + LinearIndependent ℝ A ∧ + (∀ i, labels A (u i) = labels A (u 0)) ∧ + (base = .spherical → ‖liftLabel A (labels A (u 0))‖ < 1) ∧ + 0 < projectedDensity base f A (labels A (u 0)) ∧ + projectedDensity base f A (labels A (u 0)) ≠ ∞ ∧ + projectedDensity base f A (labels A (u 0)) = + ballDensityVersion ν A (labels A (u 0)) ∧ + projectedDensity base f A (labels A (u 0)) = + gaussianDensityVersion ν A (labels A (u 0))) + +def haarRows (d ℓ : ℕ) : Measure (Rows d ℓ) := + (gaussianRows d ℓ).map (InnerProductSpace.gramSchmidtNormed ℝ) + +def cmi {Z X Y : Type*} [MeasurableSpace Z] [MeasurableSpace X] [MeasurableSpace Y] + [StandardBorelSpace X] [StandardBorelSpace Y] [Nonempty X] [Nonempty Y] + (μ : Measure (Z × (X × Y))) [IsFiniteMeasure μ] : ℝ≥0∞ := + klDiv μ (μ.fst ⊗ₘ (μ.condKernel.fst ×ₖ μ.condKernel.snd)) + +def finiteEntropy {J : Type*} [Fintype J] [MeasurableSpace J] (μ : Measure J) : ℝ := + ∑ j, - μ.real {j} * Real.log (μ.real {j}) + +def stateMessageKernel {d k V W : ℕ} (κ : Kernel (Fin V × Data d k) (Fin W)) : + Kernel ((Vec d × Fin V) × Rows d k) (Fin W) := + κ.comap (fun z => (z.1.2, (z.2, labels z.2 z.1.1))) (by unfold labels; fun_prop) + +instance {d k V W : ℕ} (κ : Kernel (Fin V × Data d k) (Fin W)) [IsMarkovKernel κ] : + IsMarkovKernel (stateMessageKernel κ) := by + unfold stateMessageKernel + infer_instance + +def stateMessageLaw {d k V W : ℕ} (q : Measure (Vec d × Fin V)) + (κ : Kernel (Fin V × Data d k) (Fin W)) : Measure ((Vec d × Fin V) × Fin W) := + (((q.prod (gaussianRows d k)) ⊗ₘ stateMessageKernel κ).map + (fun z => (z.1.1, z.2))) + +instance {d k V W : ℕ} (q : Measure (Vec d × Fin V)) [IsProbabilityMeasure q] + (κ : Kernel (Fin V × Data d k) (Fin W)) [IsMarkovKernel κ] : + IsProbabilityMeasure (stateMessageLaw q κ) := by + unfold stateMessageLaw + infer_instance + +def stateHaarSideLaw {d V W : ℕ} (ℓ : ℕ) + (q : Measure ((Vec d × Fin V) × Fin W)) : + Measure ((Fin V × Data d ℓ) × (Vec d × Fin W)) := + ((haarRows d ℓ).prod q).map + (fun z => ((z.2.1.2, (z.1, labels z.1 z.2.1.1)), (z.2.1.1, z.2.2))) + +instance {d V W : ℕ} (ℓ : ℕ) + (q : Measure ((Vec d × Fin V) × Fin W)) [IsFiniteMeasure q] : + IsFiniteMeasure (stateHaarSideLaw ℓ q) := by + unfold stateHaarSideLaw haarRows + infer_instance + +def terminalConditionalEntropy {d V W : ℕ} + (q : Measure ((Vec d × Fin V) × Fin W)) : ℝ := + finiteEntropy (q.map (fun z => (z.1.2, z.2))) - finiteEntropy (q.map (fun z => z.1.2)) + +def HaarReplicaBlock : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 64 ≤ d → + ∀ (V W : ℕ) [NeZero V] [NeZero W] + (q : Measure (Vec d × Fin V)) [IsProbabilityMeasure q], + q.fst = sphereLaw d → + ∀ (κ : Kernel (Fin V × Data d (d / 16)) (Fin W)) [IsMarkovKernel κ], + cmi (stateHaarSideLaw (d / 4) (stateMessageLaw q κ)) ≤ + ENNReal.ofReal (terminalConditionalEntropy (stateMessageLaw q κ) / + ((d / 16 + 1 : ℕ) : ℝ) + C * (d : ℝ) + + Real.log (1 + C * (d : ℝ) + finiteEntropy q.snd) + + C * (finiteEntropy q.snd + Real.log (d : ℝ)) / (d : ℝ)^2) + +end PosteriorReplicas +end +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace + +noncomputable section + +universe u + +namespace PosteriorRegression + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +end Learner + +end PosteriorRegression + +open MeasureTheory ProbabilityTheory InformationTheory Set Matrix +open scoped ENNReal NNReal RealInnerProductSpace Classical + +noncomputable section + +namespace PosteriorRegression +abbrev CompletedObservation (d : ℕ) := NullMeasurableSpace (Vector d × ℝ) (observationReference d) +abbrev Destination (M : ℕ) := Bool × State M + +structure CompletedKernelLearner (d M : ℕ) where + initial : Measure (Destination M) + initial_probability : IsProbabilityMeasure initial + transition : ℕ → State M → Kernel (CompletedObservation d) (Destination M) + transition_markov : ∀ t a, IsMarkovKernel (transition t a) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t a, IsProbabilityMeasure (output t a) + +attribute [instance] CompletedKernelLearner.initial_probability + CompletedKernelLearner.transition_markov CompletedKernelLearner.output_probability + +namespace CompletedKernelLearner +open Learner +def destStatus {M : ℕ} (n : ℕ) (v : Destination M) : RunStatus M := + if v.1 then Sum.inr (n,v.2) else Sum.inl v.2 + +def finishState {M : ℕ} (T : ℕ) : RunStatus M → ℕ × State M + | .inl a => (T,a) + | .inr done => done + +def stepMeasure {d M T : ℕ} (K : CompletedKernelLearner d M) + (s : UnitSphere d) (x : Samples d T) (i : Fin T) : RunStatus M → Measure (RunStatus M) + | .inr done => Measure.dirac (.inr done) + | .inl a => (K.transition (i.val+1) a (x i,⟪x i,s.val⟫)).map (destStatus (i.val+1)) + +def runMeasure {d M T : ℕ} (K : CompletedKernelLearner d M) + (s : UnitSphere d) (x : Samples d T) : ℕ → Measure (RunStatus M) + | 0 => K.initial.map (destStatus 0) + | n+1 => if hn : n K.output a.1 a.2) + +end CompletedKernelLearner + +structure JointKernelExperiment (d M T : ℕ) (Ω : Type u) [MeasurableSpace Ω] + (ρ : Measure Ω) where + rules : Ω → CompletedKernelLearner d M + outputKernel : Kernel (Ω × (UnitSphere d × Samples d T)) (UnitSphere d) + output_markov : IsMarkovKernel outputKernel + conditional_output : ∀ᵐ ω ∂ρ, ∀ᵐ z ∂((uniformSphere d).prod (sampleLaw d T)), + outputKernel (ω,z) = (rules ω).estimateLaw z.1 z.2 + +attribute [instance] JointKernelExperiment.output_markov + +namespace JointKernelExperiment +open Learner +def law {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] {ρ : Measure Ω} + (E : JointKernelExperiment d M T Ω ρ) : Measure ((Ω × (UnitSphere d × Samples d T)) × UnitSphere d) := + (ρ.prod ((uniformSphere d).prod (sampleLaw d T))) ⊗ₘ E.outputKernel + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] {ρ : Measure Ω} + (E : JointKernelExperiment d M T Ω ρ) (ε : ℝ) : ℝ≥0∞ := + E.law {z | angularError z.1.2.1 z.2 ≤ ε} + +end JointKernelExperiment + +def KernelSubquadraticMemory : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0<ε → ε≤1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ E : JointKernelExperiment d (M d) T Ω ρ, + (2/3 : ℝ≥0∞) ≤ E.uniformSuccess ε → + c * (d : ℝ) * Real.log (1/ε) ≤ (T : ℝ) + +end PosteriorRegression + +namespace PosteriorReplicas + +end PosteriorReplicas +end +end + +namespace PosteriorReplicas + +universe u + +theorem source_main : EqualLabelMeasureIdentity ∧ EqualLabelVersions ∧ + GaussianReplicaBlock ∧ DistanceReplicaBlock ∧ HaarReplicaBlock ∧ + SyntheticReplicaBlock ∧ IncidenceReplicaBlock ∧ + PosteriorRegression.KernelSubquadraticMemory.{u} := by + sorry + +end PosteriorReplicas + +end OAI diff --git a/tasks/posterior-replicas/tests/grade.py b/tasks/posterior-replicas/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/posterior-replicas/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/posterior-replicas/tests/task.json b/tasks/posterior-replicas/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2f84fa802f21edb5eaf6f73145dbd877548f3be2 --- /dev/null +++ b/tasks/posterior-replicas/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PosteriorReplicas", + "comparator": { + "theorem_names": [ + "OAI.PosteriorReplicas.source_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11444 +} \ No newline at end of file diff --git a/tasks/posterior-replicas/tests/test.sh b/tasks/posterior-replicas/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/posterior-replicas/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/power-free-values/environment/Dockerfile b/tasks/power-free-values/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/power-free-values/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/power-free-values/environment/fetch_mathlib.sh b/tasks/power-free-values/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/power-free-values/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/power-free-values/environment/lake-manifest.json b/tasks/power-free-values/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/power-free-values/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/power-free-values/environment/lakefile.lean b/tasks/power-free-values/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/power-free-values/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/power-free-values/environment/lean_setup.sh b/tasks/power-free-values/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/power-free-values/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/power-free-values/environment/pack_submission.py b/tasks/power-free-values/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/power-free-values/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/power-free-values/instruction.md b/tasks/power-free-values/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..55e1ff34db2860cbf9318e43d0582d640d1ea111 --- /dev/null +++ b/tasks/power-free-values/instruction.md @@ -0,0 +1,97 @@ +# openai/math challenge `PowerFreeValues` (family 020) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 020 of the release, *Squarefree quartics and power-free polynomial values* +(Number theory). The family as a whole: Proves the squarefree-values conjecture for irreducible integer quartics with no fixed prime-square divisor: squarefree values on positive integers have the predicted positive Euler-product density. More generally, establishes the $(d-2)$-power-free density for irreducible integer polynomials of degrees four through eight under the necessary local condition; together with Browning's higher-degree theorem, this covers every $d\ge4$. + +The challenge is `PowerFreeValues`, also at `/opt/openai-math/challenges/PowerFreeValues.lean`: + +```lean +import Mathlib + +namespace OAI + + + +open Filter Asymptotics +open scoped Topology + +namespace QuarticPowerFree + +def PowerFree (k : ℕ) (a : ℤ) : Prop := + ∀ p : ℕ, p.Prime → ¬ (p : ℤ) ^ k ∣ a + +def rho (f : Polynomial ℤ) (q : ℕ) : ℕ := + ((Finset.range q).filter fun a : ℕ => (q : ℤ) ∣ f.eval (a : ℤ)).card + +noncomputable def count (f : Polynomial ℤ) (k : ℕ) (X : ℝ) : ℕ := by + classical + exact ((Finset.Icc 1 ⌊X⌋₊).filter fun n : ℕ => PowerFree k (f.eval (n : ℤ))).card + +def LocallyAdmissible (f : Polynomial ℤ) (k : ℕ) : Prop := + ∀ p : ℕ, p.Prime → rho f (p ^ k) < p ^ k + +noncomputable def localFactor (f : Polynomial ℤ) (k : ℕ) (p : Nat.Primes) : ℝ := + 1 - (rho f (p.val ^ k) : ℝ) / (p.val : ℝ) ^ k + +noncomputable def densityConstant (f : Polynomial ℤ) (k : ℕ) : ℝ := + ∏' p : Nat.Primes, localFactor f k p + +def DensityStatement (f : Polynomial ℤ) (k : ℕ) : Prop := + Multipliable (localFactor f k) ∧ + 0 < densityConstant f k ∧ + (fun X : ℝ => (count f k X : ℝ) - densityConstant f k * X) =o[atTop] + (fun X : ℝ => X) + +theorem allDegrees (f : Polynomial ℤ) + (hirr : Irreducible (f.map (Int.castRingHom ℚ))) + (hdeglo : 4 ≤ f.natDegree) + (hlocal : LocallyAdmissible f (f.natDegree - 2)) : + DensityStatement f (f.natDegree - 2) := by + sorry + +end QuarticPowerFree + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PowerFreeValues.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QuarticPowerFree.allDegrees` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/power-free-values/solution/closure.txt b/tasks/power-free-values/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b321294a3566d6965e7a3bba2097e9f245d631b7 --- /dev/null +++ b/tasks/power-free-values/solution/closure.txt @@ -0,0 +1,63 @@ +OAI.NumberTheory.PowerFree.AdaptiveFibres +OAI.NumberTheory.PowerFree.AdaptiveRanks +OAI.NumberTheory.PowerFree.AffineCounting +OAI.NumberTheory.PowerFree.AffineHilbert +OAI.NumberTheory.PowerFree.BoundedLifts +OAI.NumberTheory.PowerFree.ComplexValues +OAI.NumberTheory.PowerFree.CurveAlternatives +OAI.NumberTheory.PowerFree.CurveThresholds +OAI.NumberTheory.PowerFree.DeformedRoots +OAI.NumberTheory.PowerFree.DegreeBudgets +OAI.NumberTheory.PowerFree.DegreeSchedules +OAI.NumberTheory.PowerFree.EmbeddingCharts +OAI.NumberTheory.PowerFree.GenericCuts +OAI.NumberTheory.PowerFree.HighDegree +OAI.NumberTheory.PowerFree.HilbertGrowth +OAI.NumberTheory.PowerFree.HilbertSimplex +OAI.NumberTheory.PowerFree.HomogeneousLifts +OAI.NumberTheory.PowerFree.IntegerPatches +OAI.NumberTheory.PowerFree.IntegralKernels +OAI.NumberTheory.PowerFree.Jacobians +OAI.NumberTheory.PowerFree.LaurentCoordinates +OAI.NumberTheory.PowerFree.Main +OAI.NumberTheory.PowerFree.MediumDegree +OAI.NumberTheory.PowerFree.Model +OAI.NumberTheory.PowerFree.NormBoxes +OAI.NumberTheory.PowerFree.NormComponents +OAI.NumberTheory.PowerFree.NormHilbert +OAI.NumberTheory.PowerFree.NormalMonomials +OAI.NumberTheory.PowerFree.PairAlgebras +OAI.NumberTheory.PowerFree.PairBoundaries +OAI.NumberTheory.PowerFree.PairCuts +OAI.NumberTheory.PowerFree.PairHilbert +OAI.NumberTheory.PowerFree.PairProjections +OAI.NumberTheory.PowerFree.PatchBounds +OAI.NumberTheory.PowerFree.PointInterpolation +OAI.NumberTheory.PowerFree.PoleCoefficients +OAI.NumberTheory.PowerFree.PositiveCoordinates +OAI.NumberTheory.PowerFree.PrimeBlocks +OAI.NumberTheory.PowerFree.PrimePools +OAI.NumberTheory.PowerFree.PrincipalLifts +OAI.NumberTheory.PowerFree.ProjectionDegrees +OAI.NumberTheory.PowerFree.PureCuts +OAI.NumberTheory.PowerFree.QuarticBoxes +OAI.NumberTheory.PowerFree.QuarticComponents +OAI.NumberTheory.PowerFree.QuarticPairs +OAI.NumberTheory.PowerFree.QuarticSurfaces +OAI.NumberTheory.PowerFree.RadialFibres +OAI.NumberTheory.PowerFree.RationalCoordinates +OAI.NumberTheory.PowerFree.RegularBlocks +OAI.NumberTheory.PowerFree.ResidueBounds +OAI.NumberTheory.PowerFree.ResidueRelations +OAI.NumberTheory.PowerFree.RootPairHilbert +OAI.NumberTheory.PowerFree.SelectedPrimes +OAI.NumberTheory.PowerFree.Sieve +OAI.NumberTheory.PowerFree.StoppingTrees +OAI.NumberTheory.PowerFree.SurfaceCounting +OAI.NumberTheory.PowerFree.ThreePoles +OAI.NumberTheory.PowerFree.TwoPoles +OAI.NumberTheory.PowerFree.UnitBalancing +OAI.NumberTheory.PowerFree.WeightedFunctions +OAI.NumberTheory.PowerFree.WeightedHypersurfaces +OAI.NumberTheory.PowerFree.WeightedRelations +OAI.NumberTheory.PowerFree.WeightedSlabs diff --git a/tasks/power-free-values/solution/reference.py b/tasks/power-free-values/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/power-free-values/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/power-free-values/solution/solve.sh b/tasks/power-free-values/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6eba67f5d9e9fd8ac60a4c0bce6592a550ff78a8 --- /dev/null +++ b/tasks/power-free-values/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PowerFreeValues, i.e. module OAI.NumberTheory.PowerFree.Main and the +# 63 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.PowerFree.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PowerFreeValues" diff --git a/tasks/power-free-values/task.toml b/tasks/power-free-values/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c29f4995587d417bd9ad99941037e33a5a0dd065 --- /dev/null +++ b/tasks/power-free-values/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/power-free-values" +version = "1.0.0" +description = "Prove PowerFreeValues (openai/math family 020: Squarefree quartics and power-free polynomial values) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PowerFreeValues.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PowerFreeValues" +family = "020" +family_title = "Squarefree quartics and power-free polynomial values" +subject = "Number theory" +theorems = ["OAI.QuarticPowerFree.allDegrees"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.PowerFree.Main" +reference_modules = 63 +reference_lean_bytes = 1138297 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1054 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12724 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/power-free-values/tests/Challenge.lean b/tasks/power-free-values/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..515e91fe8f60e8b63c74de87a313b34b12054061 --- /dev/null +++ b/tasks/power-free-values/tests/Challenge.lean @@ -0,0 +1,46 @@ +import Mathlib + +namespace OAI + + + +open Filter Asymptotics +open scoped Topology + +namespace QuarticPowerFree + +def PowerFree (k : ℕ) (a : ℤ) : Prop := + ∀ p : ℕ, p.Prime → ¬ (p : ℤ) ^ k ∣ a + +def rho (f : Polynomial ℤ) (q : ℕ) : ℕ := + ((Finset.range q).filter fun a : ℕ => (q : ℤ) ∣ f.eval (a : ℤ)).card + +noncomputable def count (f : Polynomial ℤ) (k : ℕ) (X : ℝ) : ℕ := by + classical + exact ((Finset.Icc 1 ⌊X⌋₊).filter fun n : ℕ => PowerFree k (f.eval (n : ℤ))).card + +def LocallyAdmissible (f : Polynomial ℤ) (k : ℕ) : Prop := + ∀ p : ℕ, p.Prime → rho f (p ^ k) < p ^ k + +noncomputable def localFactor (f : Polynomial ℤ) (k : ℕ) (p : Nat.Primes) : ℝ := + 1 - (rho f (p.val ^ k) : ℝ) / (p.val : ℝ) ^ k + +noncomputable def densityConstant (f : Polynomial ℤ) (k : ℕ) : ℝ := + ∏' p : Nat.Primes, localFactor f k p + +def DensityStatement (f : Polynomial ℤ) (k : ℕ) : Prop := + Multipliable (localFactor f k) ∧ + 0 < densityConstant f k ∧ + (fun X : ℝ => (count f k X : ℝ) - densityConstant f k * X) =o[atTop] + (fun X : ℝ => X) + +theorem allDegrees (f : Polynomial ℤ) + (hirr : Irreducible (f.map (Int.castRingHom ℚ))) + (hdeglo : 4 ≤ f.natDegree) + (hlocal : LocallyAdmissible f (f.natDegree - 2)) : + DensityStatement f (f.natDegree - 2) := by + sorry + +end QuarticPowerFree + +end OAI diff --git a/tasks/power-free-values/tests/grade.py b/tasks/power-free-values/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/power-free-values/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/power-free-values/tests/task.json b/tasks/power-free-values/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4e2882052413a261bd2933e1266b143df8a91e39 --- /dev/null +++ b/tasks/power-free-values/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PowerFreeValues", + "comparator": { + "theorem_names": [ + "OAI.QuarticPowerFree.allDegrees" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11824 +} \ No newline at end of file diff --git a/tasks/power-free-values/tests/test.sh b/tasks/power-free-values/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/power-free-values/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/prime-gaps/environment/Dockerfile b/tasks/prime-gaps/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/prime-gaps/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/prime-gaps/environment/fetch_mathlib.sh b/tasks/prime-gaps/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/prime-gaps/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/prime-gaps/environment/lake-manifest.json b/tasks/prime-gaps/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/prime-gaps/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/prime-gaps/environment/lakefile.lean b/tasks/prime-gaps/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/prime-gaps/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/prime-gaps/environment/lean_setup.sh b/tasks/prime-gaps/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/prime-gaps/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/prime-gaps/environment/pack_submission.py b/tasks/prime-gaps/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/prime-gaps/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/prime-gaps/instruction.md b/tasks/prime-gaps/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ced7f307c75261979e5574dbef7646af14781277 --- /dev/null +++ b/tasks/prime-gaps/instruction.md @@ -0,0 +1,98 @@ +# openai/math challenge `PrimeGaps` (family 026) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 026 of the release, *Positive lower density of large prime gaps* +(Number theory). The family as a whole: For every fixed $C>0$, a positive proportion of consecutive prime gaps exceed $C\log p_n$, throughout every sufficiently large initial segment of the primes. The proportion may depend on $C$. Consequently, the indices where $p_n/n$ increases have positive lower density, answering Erd\H{o}s and Prachar. + +The challenge is `PrimeGaps`, also at `/opt/openai-math/challenges/PrimeGaps.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace LargePrimeGaps + +noncomputable def prime (n : ℕ) : ℕ := Nat.nth Nat.Prime (n - 1) + +noncomputable def largeGapIndices (C : ℝ) (N : ℕ) : Finset ℕ := by + classical + exact (Finset.Icc 1 N).filter fun n => + C * Real.log (prime n : ℝ) < (prime (n + 1) : ℝ) - (prime n : ℝ) + +end LargePrimeGaps + +noncomputable section + +namespace Problem344 + +def primeAt (n : ℕ) : ℕ := + Nat.nth Nat.Prime (n - 1) + +def initialCount (A : Set ℕ) (N : ℕ) : ℕ := by + classical + exact ((Finset.Icc 1 N).filter (fun n => n ∈ A)).card + +def lowerAsymptoticDensity (A : Set ℕ) : ℝ := + sSup {d : ℝ | ∃ N0 : ℕ, ∀ N : ℕ, N0 ≤ N → + d ≤ (initialCount A N : ℝ) / (N : ℝ)} + +def ratioIncreaseIndices : Set ℕ := + {n | 1 ≤ n ∧ + (primeAt n : ℝ) / (n : ℝ) < + (primeAt (n + 1) : ℝ) / ((n + 1 : ℕ) : ℝ)} + +theorem large_gaps_and_ratio_density : + (∀ C : ℝ, 0 < C → + ∃ c : ℝ, 0 < c ∧ ∃ N₀ : ℕ, ∀ N : ℕ, N₀ ≤ N → + c * (N : ℝ) ≤ ((LargePrimeGaps.largeGapIndices C N).card : ℝ)) ∧ + 0 < lowerAsymptoticDensity ratioIncreaseIndices := by + sorry + +end Problem344 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/PrimeGaps.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem344.large_gaps_and_ratio_density` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/prime-gaps/solution/closure.txt b/tasks/prime-gaps/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8289cb2911d6feb2c99d585298442b122f784b04 --- /dev/null +++ b/tasks/prime-gaps/solution/closure.txt @@ -0,0 +1,56 @@ +OAI.NumberTheory.PrimeGaps.AdditiveSieve +OAI.NumberTheory.PrimeGaps.BoxMeans +OAI.NumberTheory.PrimeGaps.CharacterErrors +OAI.NumberTheory.PrimeGaps.ConductorBounds +OAI.NumberTheory.PrimeGaps.ContourIntegrals +OAI.NumberTheory.PrimeGaps.ContourSums +OAI.NumberTheory.PrimeGaps.CumulativeProfiles +OAI.NumberTheory.PrimeGaps.Density +OAI.NumberTheory.PrimeGaps.DensityBounds +OAI.NumberTheory.PrimeGaps.DensityTransport +OAI.NumberTheory.PrimeGaps.DetectorMoments +OAI.NumberTheory.PrimeGaps.Detectors +OAI.NumberTheory.PrimeGaps.DirichletGrowth +OAI.NumberTheory.PrimeGaps.DivisorBounds +OAI.NumberTheory.PrimeGaps.DivisorSums +OAI.NumberTheory.PrimeGaps.DyadicMeans +OAI.NumberTheory.PrimeGaps.EqualityPatterns +OAI.NumberTheory.PrimeGaps.EulerChoices +OAI.NumberTheory.PrimeGaps.EulerFactors +OAI.NumberTheory.PrimeGaps.EulerProducts +OAI.NumberTheory.PrimeGaps.FourierDerivatives +OAI.NumberTheory.PrimeGaps.FourierNormalization +OAI.NumberTheory.PrimeGaps.Indices +OAI.NumberTheory.PrimeGaps.LaplaceTransform +OAI.NumberTheory.PrimeGaps.LevelMoments +OAI.NumberTheory.PrimeGaps.LogParameters +OAI.NumberTheory.PrimeGaps.Main +OAI.NumberTheory.PrimeGaps.MangoldtBounds +OAI.NumberTheory.PrimeGaps.MarkedMoments +OAI.NumberTheory.PrimeGaps.MellinSmoothing +OAI.NumberTheory.PrimeGaps.MultiplicativeSieve +OAI.NumberTheory.PrimeGaps.OrthantIntegrals +OAI.NumberTheory.PrimeGaps.PairedDetectors +OAI.NumberTheory.PrimeGaps.PatternMoments +OAI.NumberTheory.PrimeGaps.PrimeGrowth +OAI.NumberTheory.PrimeGaps.PrincipalGrowth +OAI.NumberTheory.PrimeGaps.ProfileSymmetry +OAI.NumberTheory.PrimeGaps.ProfileVariance +OAI.NumberTheory.PrimeGaps.Profiles +OAI.NumberTheory.PrimeGaps.RatioAlgebra +OAI.NumberTheory.PrimeGaps.RatioCorollary +OAI.NumberTheory.PrimeGaps.RatioDensity +OAI.NumberTheory.PrimeGaps.RatioReduction +OAI.NumberTheory.PrimeGaps.RestrictedWeights +OAI.NumberTheory.PrimeGaps.RieszBounds +OAI.NumberTheory.PrimeGaps.RieszDecay +OAI.NumberTheory.PrimeGaps.SiegelBounds +OAI.NumberTheory.PrimeGaps.SingularSeries +OAI.NumberTheory.PrimeGaps.SingularTails +OAI.NumberTheory.PrimeGaps.TaylorBounds +OAI.NumberTheory.PrimeGaps.TensorProfiles +OAI.NumberTheory.PrimeGaps.VaughanBounds +OAI.NumberTheory.PrimeGaps.VaughanIdentity +OAI.NumberTheory.PrimeGaps.WeightMoments +OAI.NumberTheory.PrimeGaps.ZeroFreeBounds +OAI.NumberTheory.PrimeGaps.ZetaKernel diff --git a/tasks/prime-gaps/solution/reference.py b/tasks/prime-gaps/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/prime-gaps/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/prime-gaps/solution/solve.sh b/tasks/prime-gaps/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..93237928bbac9ac9bd9ff3d4263431abb82dc6c7 --- /dev/null +++ b/tasks/prime-gaps/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of PrimeGaps, i.e. module OAI.NumberTheory.PrimeGaps.RatioCorollary and the +# 56 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.PrimeGaps.RatioCorollary /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of PrimeGaps" diff --git a/tasks/prime-gaps/task.toml b/tasks/prime-gaps/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c5202b801d7e625a24b69be1693c6e08d06b13a9 --- /dev/null +++ b/tasks/prime-gaps/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/prime-gaps" +version = "1.0.0" +description = "Prove PrimeGaps (openai/math family 026: Positive lower density of large prime gaps) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/PrimeGaps.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "PrimeGaps" +family = "026" +family_title = "Positive lower density of large prime gaps" +subject = "Number theory" +theorems = ["OAI.Problem344.large_gaps_and_ratio_density"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.PrimeGaps.RatioCorollary" +reference_modules = 56 +reference_lean_bytes = 1086346 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 727 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12677 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/prime-gaps/tests/Challenge.lean b/tasks/prime-gaps/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..30450675a284489ec37f1f82004f3980717551c2 --- /dev/null +++ b/tasks/prime-gaps/tests/Challenge.lean @@ -0,0 +1,47 @@ +import Mathlib + +namespace OAI + +namespace LargePrimeGaps + +noncomputable def prime (n : ℕ) : ℕ := Nat.nth Nat.Prime (n - 1) + +noncomputable def largeGapIndices (C : ℝ) (N : ℕ) : Finset ℕ := by + classical + exact (Finset.Icc 1 N).filter fun n => + C * Real.log (prime n : ℝ) < (prime (n + 1) : ℝ) - (prime n : ℝ) + +end LargePrimeGaps + +noncomputable section + +namespace Problem344 + +def primeAt (n : ℕ) : ℕ := + Nat.nth Nat.Prime (n - 1) + +def initialCount (A : Set ℕ) (N : ℕ) : ℕ := by + classical + exact ((Finset.Icc 1 N).filter (fun n => n ∈ A)).card + +def lowerAsymptoticDensity (A : Set ℕ) : ℝ := + sSup {d : ℝ | ∃ N0 : ℕ, ∀ N : ℕ, N0 ≤ N → + d ≤ (initialCount A N : ℝ) / (N : ℝ)} + +def ratioIncreaseIndices : Set ℕ := + {n | 1 ≤ n ∧ + (primeAt n : ℝ) / (n : ℝ) < + (primeAt (n + 1) : ℝ) / ((n + 1 : ℕ) : ℝ)} + +theorem large_gaps_and_ratio_density : + (∀ C : ℝ, 0 < C → + ∃ c : ℝ, 0 < c ∧ ∃ N₀ : ℕ, ∀ N : ℕ, N₀ ≤ N → + c * (N : ℝ) ≤ ((LargePrimeGaps.largeGapIndices C N).card : ℝ)) ∧ + 0 < lowerAsymptoticDensity ratioIncreaseIndices := by + sorry + +end Problem344 + +end + +end OAI diff --git a/tasks/prime-gaps/tests/grade.py b/tasks/prime-gaps/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/prime-gaps/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/prime-gaps/tests/task.json b/tasks/prime-gaps/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fc288e411c9c7eb5eab7086606f9d5defa222433 --- /dev/null +++ b/tasks/prime-gaps/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "PrimeGaps", + "comparator": { + "theorem_names": [ + "OAI.Problem344.large_gaps_and_ratio_density" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11777 +} \ No newline at end of file diff --git a/tasks/prime-gaps/tests/test.sh b/tasks/prime-gaps/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/prime-gaps/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/product-brown/environment/Dockerfile b/tasks/product-brown/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/product-brown/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/product-brown/environment/fetch_mathlib.sh b/tasks/product-brown/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/product-brown/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/product-brown/environment/lake-manifest.json b/tasks/product-brown/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/product-brown/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/product-brown/environment/lakefile.lean b/tasks/product-brown/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/product-brown/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/product-brown/environment/lean_setup.sh b/tasks/product-brown/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/product-brown/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/product-brown/environment/pack_submission.py b/tasks/product-brown/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/product-brown/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/product-brown/instruction.md b/tasks/product-brown/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f19c73559f4693a60903d56a6243f2769c5da53e --- /dev/null +++ b/tasks/product-brown/instruction.md @@ -0,0 +1,808 @@ +# openai/math challenge `ProductBrown` (family 293) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 293 of the release, *A counterexample to the hyperinvariant-subspace problem* +(Operator algebras). The family as a whole: Constructs a nonzero norm-quasinilpotent operator on every infinite-dimensional separable complex Hilbert space with no nonzero proper closed subspace invariant under every commuting operator. The construction also gives operators with no nontrivial invariant projection in the hyperfinite type $\mathrm{II}_1$ factor. + +The challenge is `ProductBrown`, also at `/opt/openai-math/challenges/ProductBrown.lean`: + +```lean +import Mathlib + +namespace OAI + +section +noncomputable section +open Polynomial +namespace FiniteFactor + +theorem product_has_low_nonzero_coeff (K : ℕ) (p q : ℂ[X]) + (hp : p.coeff K ≠ 0) (hq : q.coeff K ≠ 0) : + ∃ n ≤ 2 * K, (p * q).coeff n ≠ 0 := by + have hp0 : p ≠ 0 := by intro h; simp [h] at hp + have hq0 : q ≠ 0 := by intro h; simp [h] at hq + refine ⟨(p * q).natTrailingDegree, ?_, + Polynomial.coeff_natTrailingDegree_ne_zero.mpr (mul_ne_zero hp0 hq0)⟩ + rw [Polynomial.natTrailingDegree_mul hp0 hq0] + have ha := Polynomial.natTrailingDegree_le_of_ne_zero hp + have hb := Polynomial.natTrailingDegree_le_of_ne_zero hq + omega + +abbrev Coefficients (K : ℕ) := Fin (2 * K + 1) → ℂ + +noncomputable def coefficientPolynomial {K : ℕ} (a : Coefficients K) : ℂ[X] := + ∑ i : Fin (2 * K + 1), Polynomial.monomial i.val (a i) + +theorem coefficientPolynomial_coeff {K : ℕ} (a : Coefficients K) + (i : Fin (2 * K + 1)) : (coefficientPolynomial a).coeff i.val = a i := by + classical + simp [coefficientPolynomial, Polynomial.finsetSum_coeff, Polynomial.coeff_monomial, + Fin.val_inj] + +noncomputable def productCoefficient {K : ℕ} (a b : Coefficients K) (n : ℕ) : ℂ := + ∑ i : Fin (2 * K + 1), ∑ j : Fin (2 * K + 1), + if i.val + j.val = n then a i * b j else 0 + +theorem productCoefficient_eq {K : ℕ} (a b : Coefficients K) (n : ℕ) : + productCoefficient a b n = + (coefficientPolynomial a * coefficientPolynomial b).coeff n := by + classical + simp only [productCoefficient, coefficientPolynomial, Finset.sum_mul, Finset.mul_sum, + Polynomial.monomial_mul_monomial, Polynomial.finsetSum_coeff, Polynomial.coeff_monomial] + exact Finset.sum_comm + +theorem continuous_productCoefficient (K n : ℕ) : + Continuous (fun ab : Coefficients K × Coefficients K => + productCoefficient ab.1 ab.2 n) := by + classical + unfold productCoefficient + apply continuous_finsetSum + intro i _ + apply continuous_finsetSum + intro j _ + split_ifs <;> fun_prop + +noncomputable def lowCoefficients {K : ℕ} (ab : Coefficients K × Coefficients K) : + Coefficients K := fun n => productCoefficient ab.1 ab.2 n.val + +theorem continuous_lowCoefficients (K : ℕ) : Continuous (@lowCoefficients K) := + continuous_pi fun n => continuous_productCoefficient K n.val + +theorem lowCoefficients_ne_zero {K : ℕ} (ab : Coefficients K × Coefficients K) + (ha : ab.1 ⟨K, by omega⟩ ≠ 0) (hb : ab.2 ⟨K, by omega⟩ ≠ 0) : + lowCoefficients ab ≠ 0 := by + have ha' : (coefficientPolynomial ab.1).coeff K ≠ 0 := by + simpa using (coefficientPolynomial_coeff ab.1 ⟨K, by omega⟩).trans_ne ha + have hb' : (coefficientPolynomial ab.2).coeff K ≠ 0 := by + simpa using (coefficientPolynomial_coeff ab.2 ⟨K, by omega⟩).trans_ne hb + obtain ⟨n, hn, hne⟩ := product_has_low_nonzero_coeff K _ _ ha' hb' + intro h + have hz := congrFun h ⟨n, by omega⟩ + exact hne (by simpa [lowCoefficients, productCoefficient_eq] using hz) + +def admissibleCoefficients (K : ℕ) (D δ : ℝ) : Set (Coefficients K) := + {a | ∀ i, ‖a i‖ ≤ D} ∩ {a | δ ≤ ‖a ⟨K, by omega⟩‖} + +theorem isCompact_admissibleCoefficients (K : ℕ) (D δ : ℝ) : + IsCompact (admissibleCoefficients K D δ) := by + have hc : IsCompact {a : Coefficients K | ∀ i, ‖a i‖ ≤ D} := by + simpa [Set.pi, Metric.mem_closedBall, dist_zero_right] using + (isCompact_pi_infinite fun _ : Fin (2 * K + 1) => + isCompact_closedBall (0 : ℂ) D) + exact hc.inter_right (isClosed_le continuous_const (continuous_apply (⟨K, by omega⟩ : Fin (2 * K + 1))).norm) + +theorem uniform_product_coefficient_bound (K : ℕ) (D δ : ℝ) (hδ : 0 < δ) : + ∃ ε : ℝ, 0 < ε ∧ ∀ a b : Coefficients K, + (∀ i, ‖a i‖ ≤ D) → (∀ i, ‖b i‖ ≤ D) → + δ ≤ ‖a ⟨K, by omega⟩‖ → δ ≤ ‖b ⟨K, by omega⟩‖ → + ∃ n : Fin (2 * K + 1), ε ≤ ‖productCoefficient a b n.val‖ := by + classical + let S := (admissibleCoefficients K D δ).prod (admissibleCoefficients K D δ) + have hc : IsCompact S := (isCompact_admissibleCoefficients K D δ).prod + (isCompact_admissibleCoefficients K D δ) + by_cases hs : S.Nonempty + · obtain ⟨ab, hab, hmin⟩ := hc.exists_isMinOn hs + (continuous_lowCoefficients K).norm.continuousOn + have hpos : 0 < ‖lowCoefficients ab‖ := by + apply norm_pos_iff.mpr + apply lowCoefficients_ne_zero + · exact norm_pos_iff.mp (hδ.trans_le hab.1.2) + · exact norm_pos_iff.mp (hδ.trans_le hab.2.2) + refine ⟨‖lowCoefficients ab‖, hpos, ?_⟩ + intro a b ha hb ha0 hb0 + have hm : ‖lowCoefficients ab‖ ≤ ‖lowCoefficients (a, b)‖ := + hmin ⟨⟨ha, ha0⟩, ⟨hb, hb0⟩⟩ + by_contra hn + push Not at hn + have hlt : ‖lowCoefficients (a, b)‖ < ‖lowCoefficients ab‖ := + (pi_norm_lt_iff hpos).mpr hn + exact (not_lt_of_ge hm) hlt + · refine ⟨1, zero_lt_one, ?_⟩ + intro a b ha hb ha0 hb0 + exact False.elim (hs ⟨(a, b), ⟨⟨ha, ha0⟩, ⟨hb, hb0⟩⟩⟩) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace FiniteFactor + +def unitIntervalMeasure : Measure ℝ := volume.restrict (Set.Ico 0 1) + +instance : IsProbabilityMeasure unitIntervalMeasure := by + constructor + simp [unitIntervalMeasure, Real.volume_Ico] + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace FiniteFactor + +def sourceKappa (s : ℕ) : ℝ := 1 / (100*((s : ℝ)+1)) + +end FiniteFactor +end +end + +section +noncomputable section +open Filter Finset +open scoped Topology +namespace FiniteFactor + +def sourceNextCutoff (m : ℕ) : ℕ := Nat.ceil ((m : ℝ)^((3/4 : ℝ)*(m : ℝ))) + +theorem sourceNextCutoff_large (m : ℕ) (hm : 100 ≤ m) : 2*m < sourceNextCutoff m := by + have hmR : (100 : ℝ) ≤ m := by exact_mod_cast hm + have hp : (m : ℝ)^2 ≤ (m : ℝ)^((3/4 : ℝ)*(m : ℝ)) := by + rw [← Real.rpow_natCast] + exact Real.rpow_le_rpow_of_exponent_le (by linarith) (by norm_num; linarith) + have hh := hp.trans (Nat.le_ceil _) + have hh2 : (2 : ℝ)*m < (sourceNextCutoff m : ℝ) := by + change (m : ℝ)^2 ≤ (sourceNextCutoff m : ℝ) at hh + nlinarith + exact_mod_cast hh2 + +theorem exists_source_block_length (R κ L G : ℝ) (hκ : 0 < κ) (hG : 0 < G) : + ∃ m : ℕ, R ≤ (m : ℝ) ∧ 100 ≤ m ∧ κ*(m : ℝ)^(1/40 : ℝ) ≥ L ∧ + G*(sourceNextCutoff m : ℝ) < (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) := by + have ht : Tendsto (fun m : ℕ => (m : ℝ)^(1/40 : ℝ)) atTop atTop := + (tendsto_rpow_atTop (by norm_num)).comp tendsto_natCast_atTop_atTop + obtain ⟨m, hmR, hm100, hmG, hmκ⟩ := + ((tendsto_natCast_atTop_atTop.eventually (eventually_ge_atTop R)).and + ((eventually_ge_atTop (100 : ℕ)).and + ((tendsto_natCast_atTop_atTop.eventually (eventually_gt_atTop (2*G))).and + (ht.eventually (eventually_ge_atTop (L/κ)))))).exists + refine ⟨m, hmR, hm100, (div_le_iff₀ hκ).mp hmκ |>.trans_eq (mul_comm _ _), ?_⟩ + have hm1 : (1 : ℝ) ≤ m := by exact_mod_cast (show 1 ≤ m by omega) + have hm0 : (0 : ℝ) < m := lt_of_lt_of_le zero_lt_one hm1 + let A : ℝ := (m : ℝ)^((3/4 : ℝ)*(m : ℝ)) + have hApos : 0 < A := Real.rpow_pos_of_pos hm0 _ + have hA1 : 1 ≤ A := Real.one_le_rpow hm1 (by positivity) + have hceil : (sourceNextCutoff m : ℝ) ≤ 2*A := by + have hh := Nat.ceil_lt_add_one hApos.le + change (Nat.ceil A : ℝ) ≤ 2*A + linarith + calc + G*(sourceNextCutoff m : ℝ) ≤ G*(2*A) := mul_le_mul_of_nonneg_left hceil hG.le + _ < (m : ℝ)*A := by nlinarith + _ = (m : ℝ)^((3/4 : ℝ)*(m : ℝ)+1) := by rw [Real.rpow_add hm0, Real.rpow_one]; ring + _ ≤ (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) := + Real.rpow_le_rpow_of_exponent_le hm1 (by + have hh : (100 : ℝ) ≤ m := by exact_mod_cast hm100 + linarith) + +structure SourceStageState where + K : ℕ + G : ℝ + d : ℕ + B : ℝ + previousL : ℝ + K_ge : 1 ≤ K + G_ge : 1 ≤ G + B_nonneg : 0 ≤ B + previousL_ge : 1 ≤ previousL + +def SourceStageState.D (a : SourceStageState) : ℝ := Real.exp (((a.K : ℝ)+1)*a.B) + +structure SourceStageChoice (s : ℕ) (a : SourceStageState) where + ε : ℝ + L : ℝ + Gnext : ℝ + m : ℕ + ε_pos : 0 < ε + polynomial : ∀ u v : Coefficients a.K, + (∀ i, ‖u i‖ ≤ a.D) → (∀ i, ‖v i‖ ≤ a.D) → + 1/((s : ℝ)+1) ≤ ‖u ⟨a.K, by omega⟩‖ → 1/((s : ℝ)+1) ≤ ‖v ⟨a.K, by omega⟩‖ → + ∃ n : Fin (2*a.K+1), ε ≤ ‖productCoefficient u v n.val‖ + L_ge : a.previousL ≤ L + decay : ((2*a.K : ℕ)+1 : ℝ)*3*Real.exp (-L/10000) ≤ ε/((s : ℝ)+1) + Gnext_ge : 1 ≤ Gnext + next_budget : sourceKappa (s+1) * Real.sqrt Gnext ≥ L + m_ge_K : a.K ≤ m + m_ge_pow : 2^(s+1) ≤ m + m_ge_G : 4*a.G ≤ (m : ℝ) + m_ge_100 : 100 ≤ m + previous_size : (a.d : ℝ) ≤ (m : ℝ)/100 + current_budget : sourceKappa s * (m : ℝ)^(1/40 : ℝ) ≥ L + next_gap : Gnext*(sourceNextCutoff m : ℝ) < (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) + +theorem exists_sourceStageChoice (s : ℕ) (a : SourceStageState) : + Nonempty (SourceStageChoice s a) := by + have hs : 0 < (s : ℝ)+1 := by positivity + have hk (j : ℕ) : 0 < sourceKappa j := by unfold sourceKappa; positivity + obtain ⟨ε, hε, hp⟩ := uniform_product_coefficient_bound a.K a.D (1/((s : ℝ)+1)) (by positivity) + let target : ℝ := (ε/((s : ℝ)+1))/(((2*a.K : ℕ)+1 : ℝ)*3) + have ht : 0 < target := by dsimp [target]; positivity + obtain ⟨t, htL, htt⟩ := ((eventually_ge_atTop (a.previousL/10000)).and + (Real.tendsto_exp_neg_atTop_nhds_zero.eventually (gt_mem_nhds ht))).exists + let L : ℝ := 10000*t + have hL : a.previousL ≤ L := by dsimp [L]; linarith + have hLpos : 0 < L := lt_of_lt_of_le (by linarith [a.previousL_ge]) hL + let G : ℝ := (1+L/sourceKappa (s+1))^2 + have hG : 1 ≤ G := by dsimp [G]; nlinarith [div_pos hLpos (hk (s+1))] + have hbudget : L ≤ sourceKappa (s+1)*Real.sqrt G := by + rw [show Real.sqrt G = 1+L/sourceKappa (s+1) by + dsimp [G]; rw [Real.sqrt_sq (by linarith [div_pos hLpos (hk (s+1))])]] + rw [mul_add, mul_one, mul_div_cancel₀ _ (hk (s+1)).ne'] + linarith [hk (s+1)] + let R : ℝ := max (a.K : ℝ) (max ((2^(s+1) : ℕ) : ℝ) (max (4*a.G) (100*(a.d : ℝ)))) + obtain ⟨m, hmR, hm100, hmκ, hmgap⟩ := exists_source_block_length R (sourceKappa s) L G (hk s) (by linarith) + have hmK : (a.K : ℝ) ≤ m := (le_max_left _ _).trans hmR + have hm2 : (((2^(s+1) : ℕ)) : ℝ) ≤ m := (le_max_left _ _).trans ((le_max_right _ _).trans hmR) + have hmG : 4*a.G ≤ (m : ℝ) := (le_max_left _ _).trans + ((le_max_right _ _).trans ((le_max_right _ _).trans hmR)) + have hmd : 100*(a.d : ℝ) ≤ m := (le_max_right _ _).trans + ((le_max_right _ _).trans ((le_max_right _ _).trans hmR)) + refine ⟨⟨ε, L, G, m, hε, hp, hL, ?_, hG, hbudget, + by exact_mod_cast hmK, by exact_mod_cast hm2, hmG, hm100, by linarith, hmκ, hmgap⟩⟩ + have hden : 0 < (((2*a.K : ℕ)+1 : ℝ)*3) := by positivity + have htt' := (lt_div_iff₀ hden).mp htt + have he : -L/10000 = -t := by dsimp [L]; ring + rw [he] + nlinarith + +def selectedSourceStage (s : ℕ) (a : SourceStageState) : SourceStageChoice s a := + Classical.choice (exists_sourceStageChoice s a) + +def SourceStageChoice.C {s : ℕ} {a : SourceStageState} (b : SourceStageChoice s a) : ℝ := + max b.L ((a.K : ℝ)^2) + +def SourceStageChoice.next {s : ℕ} {a : SourceStageState} (b : SourceStageChoice s a) : SourceStageState where + K := sourceNextCutoff b.m + G := b.Gnext + d := a.d+b.m + B := a.B+b.C*(b.m : ℝ) + previousL := b.L + K_ge := by have := sourceNextCutoff_large b.m b.m_ge_100; omega + G_ge := b.Gnext_ge + B_nonneg := add_nonneg a.B_nonneg (mul_nonneg (le_max_of_le_right (sq_nonneg _)) (Nat.cast_nonneg _)) + previousL_ge := a.previousL_ge.trans b.L_ge + +def sourceStageState : ℕ → SourceStageState + | 0 => ⟨100, 1, 0, 0, 1, by norm_num, le_rfl, le_rfl, le_rfl⟩ + | s+1 => (selectedSourceStage s (sourceStageState s)).next + +def sourceStage (s : ℕ) : SourceStageChoice s (sourceStageState s) := + selectedSourceStage s (sourceStageState s) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def coordinateFloor {ι : Type*} (θ : ι → ℝ) (k : ℤ) (x : ι → ℝ) (i : ι) : ℤ := + Int.floor (x i + (k : ℝ)*θ i) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def coordinateRotate {ι : Type*} (θ : ι → ℝ) (k : ℤ) (x : ι → ℝ) (i : ι) : ℝ := + Int.fract (x i + (k : ℝ)*θ i) + +def sourceLog {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : ℝ := + ∑' i, c i * (coordinateFloor θ k x i : ℝ) + +def sourceCocycle {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : ℝ := + Real.exp (-sourceLog θ c k x) + +theorem sourceCocycle_pos {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : + 0 < sourceCocycle θ c k x := Real.exp_pos _ + +theorem sourceCocycle_measurable {ι : Type*} [Countable ι] + (θ c : ι → ℝ) (k : ℤ) : + @Measurable (ι → ℝ) ℝ + (@MeasurableSpace.pi ι (fun _ => ℝ) (fun _ => Real.measurableSpace)) + Real.measurableSpace (sourceCocycle θ c k) := by + apply Real.continuous_exp.measurable.comp + apply Measurable.neg + apply Measurable.tsum + intro i + have hm0 : Measurable (fun x : ι → ℝ => x i + (k : ℝ)*θ i) := + (measurable_pi_apply i).add measurable_const + have hm := Int.measurable_floor.comp hm0 + exact measurable_const.mul ((measurable_of_countable (fun z : ℤ => (z : ℝ))).comp hm) + +theorem sourceWeight_le_one {ι : Type*} (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) {x : ι → ℝ} + (hx : ∀ i, x i ∈ Set.Ico 0 1) : sourceCocycle θ c 1 x ≤ 1 := by + apply Real.exp_le_one_iff.mpr + apply neg_nonpos.mpr + apply tsum_nonneg + intro i + apply mul_nonneg (hc i) + unfold coordinateFloor + exact_mod_cast Int.floor_nonneg.mpr (show 0 ≤ x i + (1 : ℤ)*θ i by simpa using add_nonneg (hx i).1 (hθ i)) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +abbrev sourceMeasure (ι : Type*) : Measure ((ι → ℝ) × ℤ) := + (Measure.infinitePi (fun _ : ι => unitIntervalMeasure)).prod Measure.count + +abbrev SourceHilbert (ι : Type*) : Type _ := Lp ℂ 2 (sourceMeasure ι) + +def sourceDiagonal {ι : Type*} (θ c : ι → ℝ) (z : (ι → ℝ) × ℤ) : ℂ := + sourceCocycle θ c 1 (coordinateRotate θ z.2 z.1) + +theorem sourceDiagonal_measurable {ι : Type*} [Countable ι] (θ c : ι → ℝ) : + Measurable (sourceDiagonal θ c) := by + apply Complex.measurable_ofReal.comp + apply (sourceCocycle_measurable θ c 1).comp + apply Measurable.of_eval + intro i + unfold coordinateRotate + fun_prop + +theorem sourceDiagonal_norm_le {ι : Type*} (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) (z : (ι → ℝ) × ℤ) : + ‖sourceDiagonal θ c z‖ ≤ 1 := by + rw [sourceDiagonal, Complex.norm_real, Real.norm_of_nonneg (sourceCocycle_pos _ _ _ _).le] + apply sourceWeight_le_one θ c hθ hc + intro i + exact ⟨Int.fract_nonneg _, Int.fract_lt_one _⟩ + +theorem sourceDiagonal_memLp {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : + MemLp (sourceDiagonal θ c) ∞ (sourceMeasure ι) := + memLp_top_of_bound (sourceDiagonal_measurable θ c).aestronglyMeasurable 1 + (Eventually.of_forall (sourceDiagonal_norm_le θ c hθ hc)) + +def sourceMultiplication {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (ContinuousLinearMap.mul ℂ ℂ).holderL (sourceMeasure ι) ∞ 2 2 + ((sourceDiagonal_memLp θ c hθ hc).toLp (sourceDiagonal θ c)) + +def sourceShiftIndex {ι : Type*} (z : (ι → ℝ) × ℤ) : (ι → ℝ) × ℤ := (z.1, z.2-1) + +theorem sourceShiftIndex_preserving (ι : Type*) : + MeasurePreserving (sourceShiftIndex (ι := ι)) (sourceMeasure ι) (sourceMeasure ι) := by + have hm : Measurable (fun k : ℤ => k-1) := measurable_of_countable _ + have hi : Function.Injective (fun k : ℤ => k-1) := by intro a b h; dsimp at h; omega + have hs : Function.Surjective (fun k : ℤ => k-1) := by intro k; exact ⟨k+1, by dsimp; omega⟩ + have hp : MeasurePreserving (fun k : ℤ => k-1) Measure.count Measure.count := by + refine ⟨hm, ?_⟩ + ext S hS + rw [Measure.map_apply hm hS, Measure.count_apply (hS.preimage hm), Measure.count_apply hS, + ← hi.encard_image, Set.image_preimage_eq S hs] + exact (MeasurePreserving.id _).prod hp + +def sourceShift (ι : Type*) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (Lp.compMeasurePreservingₗᵢ ℂ sourceShiftIndex (sourceShiftIndex_preserving ι)).toContinuousLinearMap + +def sourceOperator {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (sourceShift ι).comp (sourceMultiplication θ c hθ hc) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter Finset +open scoped Topology ENNReal +namespace FiniteFactor +namespace CouplingParameters + +abbrev BlockCoordinate (m : ℕ → ℕ) := Σ s : ℕ, Fin (m s) + +end CouplingParameters +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter Finset +open scoped Topology ENNReal +namespace FiniteFactor + +def sourceBlockSize (s : ℕ) : ℕ := (sourceStage s).m +abbrev SourceCoordinate := CouplingParameters.BlockCoordinate sourceBlockSize + +def sourceLogWeight (i : SourceCoordinate) : ℝ := (sourceStage i.1).C + +def SourceAngles (θ : SourceCoordinate → ℝ) : Prop := + let realGroup : GroupWithZero ℝ := + (@DivisionRing.toDivisionSemiring ℝ Real.instField.toDivisionRing).toGroupWithZero + let realOrder : LE ℝ := @Preorder.toLE ℝ Real.partialOrder.toPreorder + ∀ i : SourceCoordinate, + let block : ℝ := @Nat.cast ℝ Real.instNatCast (sourceBlockSize i.1) + let cutoff : ℝ := @Nat.cast ℝ Real.instNatCast (sourceStageState i.1).K + let denominator : ℝ := @Mul.mul ℝ Real.instMul block cutoff + let lower : ℝ := + @Div.div ℝ realGroup.toDiv (@One.one ℝ Real.instOne) denominator + let upper : ℝ := + @Div.div ℝ realGroup.toDiv (@Nat.cast ℝ Real.instNatCast 2) denominator + @LE.le ℝ realOrder lower (θ i) ∧ @LE.le ℝ realOrder (θ i) upper + +theorem sourceBlockSize_pos (s : ℕ) : (0 : ℝ) < sourceBlockSize s := by + exact_mod_cast (show 0 < (sourceStage s).m by have := (sourceStage s).m_ge_100; omega) + +theorem sourceCutoff_pos (s : ℕ) : (0 : ℝ) < (sourceStageState s).K := by + exact_mod_cast (show 0 < (sourceStageState s).K by have := (sourceStageState s).K_ge; omega) + +theorem SourceAngles.nonneg {θ : SourceCoordinate → ℝ} (hθ : SourceAngles θ) + (i : SourceCoordinate) : + @LE.le ℝ (@Preorder.toLE ℝ Real.partialOrder.toPreorder) + (@Zero.zero ℝ Real.instZero) (θ i) := + let realGroup : GroupWithZero ℝ := + (@DivisionRing.toDivisionSemiring ℝ Real.instField.toDivisionRing).toGroupWithZero + let realOrder : Preorder ℝ := Real.partialOrder.toPreorder + let realStrict : @PosMulStrictMono ℝ Real.instMul Real.instZero realOrder := + @IsStrictOrderedRing.toPosMulStrictMono ℝ Real.semiring Real.partialOrder + Real.instIsStrictOrderedRing + let realReflect : @PosMulReflectLT ℝ Real.instMul Real.instZero realOrder := + @PosMulMono.toPosMulReflectLT ℝ Real.instMul Real.instZero Real.linearOrder + (@IsOrderedRing.toPosMulMono ℝ Real.semiring Real.partialOrder + Real.instIsOrderedRing) + let block : ℝ := @Nat.cast ℝ Real.instNatCast (sourceBlockSize i.1) + let cutoff : ℝ := @Nat.cast ℝ Real.instNatCast (sourceStageState i.1).K + let denominator : ℝ := @Mul.mul ℝ Real.instMul block cutoff + let lower : ℝ := + @Div.div ℝ realGroup.toDiv (@One.one ℝ Real.instOne) denominator + let upper : ℝ := + @Div.div ℝ realGroup.toDiv (@Nat.cast ℝ Real.instNatCast 2) denominator + let zeroReal : ℝ := @Zero.zero ℝ Real.instZero + @le_trans ℝ realOrder zeroReal lower (θ i) + (@le_of_lt ℝ realOrder zeroReal lower + ((@one_div_pos ℝ realGroup Real.partialOrder realReflect denominator).mpr + (@mul_pos ℝ realGroup.toMulZeroClass (a := block) (b := cutoff) + realOrder realStrict (sourceBlockSize_pos i.1) (sourceCutoff_pos i.1)))) + (@And.left + (@LE.le ℝ realOrder.toLE lower (θ i)) + (@LE.le ℝ realOrder.toLE (θ i) upper) + (hθ i)) + +theorem sourceLogWeight_nonneg (i : SourceCoordinate) : 0 ≤ sourceLogWeight i := + le_max_of_le_right (sq_nonneg _) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def sourceVacuum : SourceHilbert SourceCoordinate := + @indicatorConstLp ((SourceCoordinate → ℝ) × ℤ) ℂ + (@Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace) + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + (Set.univ ×ˢ {(0 : ℤ)}) + (@Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero))) + (MeasurableSet.univ.prod (measurableSet_singleton (0 : ℤ))) + (letI : IsProbabilityMeasure unitIntervalMeasure := + ⟨(Measure.restrict_apply_univ + (μ := (volume : Measure ℝ)) (Set.Ico (0 : ℝ) 1)).trans + ((Real.volume_Ico (a := 0) (b := 1)).trans + ((congrArg ENNReal.ofReal (sub_zero (1 : ℝ))).trans + ENNReal.ofReal_one))⟩ + let base : Measure (SourceCoordinate → ℝ) := + Measure.infinitePi (fun _ : SourceCoordinate => unitIntervalMeasure) + let mass_one := + (Measure.prod_prod (μ := base) (ν := (Measure.count : Measure ℤ)) + Set.univ {(0 : ℤ)}).trans + ((congrArg₂ (fun left right : ℝ≥0∞ => left * right) + (measure_univ (μ := base)) + (Measure.count_singleton (0 : ℤ))).trans (one_mul (1 : ℝ≥0∞))) + fun mass_top => ENNReal.one_ne_top (mass_one.symm.trans mass_top)) (1 : ℂ) + +theorem sourceVacuum_norm : ‖sourceVacuum‖ = 1 := by + rw [sourceVacuum,norm_indicatorConstLp (by norm_num) (by norm_num)] + simp [measureReal_def,sourceMeasure,Measure.prod_prod] + +section + +local notation "vacuumMeasurable" => + @Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace +local notation "vacuumSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring +local notation "vacuumIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ vacuumSemiring) +local notation "vacuumHilbertGroup" => + @MeasureTheory.Lp.instNormedAddCommGroup + ((SourceCoordinate → ℝ) × ℤ) ℂ vacuumMeasurable + (@Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero))) + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + fact_one_le_two_ennreal +local notation "vacuumHilbertInner" => + @MeasureTheory.L2.innerProductSpace + ((SourceCoordinate → ℝ) × ℤ) ℂ ℂ Complex.instRCLike + vacuumMeasurable (sourceMeasure SourceCoordinate) + Complex.instNormedAddCommGroup (@RCLike.innerProductSpace ℂ Complex.instRCLike) +local notation "vacuumHilbertTopology" => + @UniformSpace.toTopologicalSpace (SourceHilbert SourceCoordinate) + (@PseudoMetricSpace.toUniformSpace (SourceHilbert SourceCoordinate) + (@MetricSpace.toPseudoMetricSpace (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toMetricSpace (SourceHilbert SourceCoordinate) vacuumHilbertGroup))) +local notation "vacuumHilbertAddition" => + @AddCommGroup.toAddCommMonoid (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toAddCommGroup (SourceHilbert SourceCoordinate) vacuumHilbertGroup) +local notation "vacuumHilbertModule" => + @NormedSpace.toModule ℂ (SourceHilbert SourceCoordinate) + (@DenselyNormedField.toNormedField ℂ + (@RCLike.toDenselyNormedField ℂ Complex.instRCLike)) + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + vacuumHilbertInner) + +abbrev sourceVacuumFunctional + (operator : @ContinuousLinearMap ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + vacuumHilbertModule vacuumHilbertModule) : ℂ := + @inner ℂ (SourceHilbert SourceCoordinate) + (@InnerProductSpace.toInner ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + vacuumHilbertInner) sourceVacuum + (@AddHom.toFun (SourceHilbert SourceCoordinate) (SourceHilbert SourceCoordinate) + (vacuumHilbertAddition).toAdd (vacuumHilbertAddition).toAdd + (@LinearMap.toAddHom ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) (SourceHilbert SourceCoordinate) + vacuumHilbertAddition vacuumHilbertAddition vacuumHilbertModule vacuumHilbertModule + (@ContinuousLinearMap.toLinearMap ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + vacuumHilbertModule vacuumHilbertModule operator)) sourceVacuum) + +end + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology ENNReal CStarAlgebra +namespace FiniteFactor + +local instance : IsometricContinuousFunctionalCalculus ℝ + (SourceHilbert SourceCoordinate →L[ℂ] SourceHilbert SourceCoordinate) IsSelfAdjoint := + IsSelfAdjoint.instIsometricContinuousFunctionalCalculus +instance productHilbertNontrivial : Nontrivial (SourceHilbert SourceCoordinate) := by + have hv : sourceVacuum≠0 := by + intro hz + have h := sourceVacuum_norm + rw [hz,norm_zero] at h + norm_num at h + exact ⟨⟨sourceVacuum,0,hv⟩⟩ + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology +namespace FiniteFactor + +local notation "productMeasurable" => + @Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace +local notation "productSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring +local notation "productIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ productSemiring) +local notation "productExponent" => + @Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero)) +local notation "productHilbertGroup" => + @MeasureTheory.Lp.instNormedAddCommGroup + ((SourceCoordinate → ℝ) × ℤ) ℂ productMeasurable + productExponent + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + fact_one_le_two_ennreal +local notation "productHilbertInner" => + @MeasureTheory.L2.innerProductSpace + ((SourceCoordinate → ℝ) × ℤ) ℂ ℂ Complex.instRCLike + productMeasurable (sourceMeasure SourceCoordinate) + Complex.instNormedAddCommGroup (@RCLike.innerProductSpace ℂ Complex.instRCLike) +local notation "productHilbertTopology" => + @UniformSpace.toTopologicalSpace (SourceHilbert SourceCoordinate) + (@PseudoMetricSpace.toUniformSpace (SourceHilbert SourceCoordinate) + (@MetricSpace.toPseudoMetricSpace (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toMetricSpace (SourceHilbert SourceCoordinate) productHilbertGroup))) +local notation "productHilbertAddition" => + @AddCommGroup.toAddCommMonoid (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toAddCommGroup (SourceHilbert SourceCoordinate) productHilbertGroup) +local notation "productHilbertModule" => + @NormedSpace.toModule ℂ (SourceHilbert SourceCoordinate) + (@DenselyNormedField.toNormedField ℂ + (@RCLike.toDenselyNormedField ℂ Complex.instRCLike)) + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + productHilbertInner) + +abbrev ProductOp := + @ContinuousLinearMap ℂ ℂ productSemiring productSemiring productIdentity + (SourceHilbert SourceCoordinate) productHilbertTopology productHilbertAddition + (SourceHilbert SourceCoordinate) productHilbertTopology productHilbertAddition + productHilbertModule productHilbertModule + +section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology ENNReal + +local instance : Module ℝ ProductOp := Module.complexToReal ProductOp +local instance : IsometricContinuousFunctionalCalculus ℝ ProductOp IsSelfAdjoint := + IsSelfAdjoint.instIsometricContinuousFunctionalCalculus + +def logarithmCutoff (n : ℕ) : C(ℝ,ℝ) where + toFun t := Real.log (max (Real.exp (-(n:ℝ))) t) + continuous_toFun := (continuous_const.max continuous_id).log + (fun _=>ne_of_gt ((Real.exp_pos _).trans_le (le_max_left _ _))) + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def FugledeKadisonDeterminant (τ : ProductOp → ℂ) (T : ProductOp) : ℝ≥0∞ := + let determinant := fun (Hilbert : Type) [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] [Nontrivial Hilbert] + (trace : (Hilbert →L[ℂ] Hilbert) → ℂ) (operator : Hilbert →L[ℂ] Hilbert) => + letI : Module ℝ (Hilbert →L[ℂ] Hilbert) := Module.complexToReal _ + letI : IsometricContinuousFunctionalCalculus ℝ (Hilbert →L[ℂ] Hilbert) + IsSelfAdjoint := IsSelfAdjoint.instIsometricContinuousFunctionalCalculus + ⨅ n : ℕ, ENNReal.ofReal + (Real.exp ((trace (cfc (logarithmCutoff n) (CFC.abs operator))).re)) + let domain := (SourceCoordinate → ℝ) × ℤ + let measurable : MeasurableSpace domain := productMeasurable + let exponent : ℝ≥0∞ := productExponent + let measure : @Measure domain measurable := sourceMeasure SourceCoordinate + let complete := @MeasureTheory.Lp.instCompleteSpace domain measurable exponent measure ℂ + Complex.instNormedAddCommGroup Complex.instCompleteSpace fact_one_le_two_ennreal + @determinant (SourceHilbert SourceCoordinate) productHilbertGroup productHilbertInner + complete productHilbertNontrivial τ T + +end + +section +open MeasureTheory Filter +open scoped ENNReal Topology + +def expLogPotential (μ : Measure ℂ) (z : ℂ) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (Real.exp (∫ w,logarithmCutoff n ‖z-w‖ ∂μ)) + +def IsBrownMeasure (τ : ProductOp → ℂ) (T : ProductOp) (μ : Measure ℂ) : Prop := + let translate := fun (Hilbert : Type) [NormedAddCommGroup Hilbert] + [NormedSpace ℂ Hilbert] (operator : Hilbert →L[ℂ] Hilbert) (scalar : ℂ) => + operator - algebraMap ℂ (Hilbert →L[ℂ] Hilbert) scalar + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ + ∀ z : ℂ, FugledeKadisonDeterminant τ + (@translate (SourceHilbert SourceCoordinate) productHilbertGroup + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + productHilbertInner) T z) = expLogPotential μ z + +def ProductBrownClaim : Prop := + ∀ (θ : SourceCoordinate → ℝ) (hθ : SourceAngles θ), + IsBrownMeasure sourceVacuumFunctional + (sourceOperator θ sourceLogWeight hθ.nonneg sourceLogWeight_nonneg) (Measure.dirac 0) + +end + +end FiniteFactor +end +end + +namespace FiniteFactor + +/-- The Brown measure of the product weighted shift is the point mass at zero. -/ +theorem productBrown : ProductBrownClaim := by + sorry + +end FiniteFactor + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ProductBrown.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.FiniteFactor.productBrown` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/product-brown/solution/closure.txt b/tasks/product-brown/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b9792b2f9f3646ca3ac1a600465aaf5d9d960f38 --- /dev/null +++ b/tasks/product-brown/solution/closure.txt @@ -0,0 +1,292 @@ +OAI.Analysis.BrownMeasure.Atomic +OAI.Analysis.BrownMeasure.ConcreteTrace +OAI.Analysis.BrownMeasure.Determinant +OAI.Analysis.BrownMeasure.Dirac +OAI.Analysis.BrownMeasure.FunctionalCalculus +OAI.Analysis.BrownMeasure.LogDerivative +OAI.Analysis.BrownMeasure.Main +OAI.Analysis.BrownMeasure.Mercator +OAI.Analysis.BrownMeasure.MercatorCalculus +OAI.Analysis.BrownMeasure.Model +OAI.Analysis.BrownMeasure.Modulus +OAI.Analysis.BrownMeasure.Orbit +OAI.Analysis.BrownMeasure.Polar +OAI.Analysis.BrownMeasure.PurePoint +OAI.Analysis.BrownMeasure.Quasinilpotent +OAI.Analysis.BrownMeasure.Resolvent +OAI.Analysis.BrownMeasure.RootSeries +OAI.Analysis.BrownMeasure.Spectrum +OAI.Analysis.BrownMeasure.TraceDerivative +OAI.Analysis.BrownMeasure.UnitDeterminant +OAI.Analysis.BrownMeasure.Weight +OAI.Analysis.FiniteFactor.BiasedPairs.CommonConull +OAI.Analysis.FiniteFactor.BiasedPairs.Conull +OAI.Analysis.FiniteFactor.BiasedPairs.Measures +OAI.Analysis.FiniteFactor.BiasedPairs.PairIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixDomination +OAI.Analysis.FiniteFactor.BiasedPairs.PrefixLimit +OAI.Analysis.FiniteFactor.BiasedPairs.RealIdentity +OAI.Analysis.FiniteFactor.BiasedPairs.ReferenceDomination +OAI.Analysis.FiniteFactor.BoundedMatrixOperator +OAI.Analysis.FiniteFactor.CompactGraphLusin +OAI.Analysis.FiniteFactor.CompactZeroTransfer +OAI.Analysis.FiniteFactor.Contradiction +OAI.Analysis.FiniteFactor.Convolution +OAI.Analysis.FiniteFactor.CountableMaskedError +OAI.Analysis.FiniteFactor.Coupling.BadEvents +OAI.Analysis.FiniteFactor.Coupling.Bayes +OAI.Analysis.FiniteFactor.Coupling.BlockLimit +OAI.Analysis.FiniteFactor.Coupling.Bounds +OAI.Analysis.FiniteFactor.Coupling.Conditioning +OAI.Analysis.FiniteFactor.Coupling.CoordinateMass +OAI.Analysis.FiniteFactor.Coupling.Crossing +OAI.Analysis.FiniteFactor.Coupling.Density +OAI.Analysis.FiniteFactor.Coupling.FiniteDisintegration +OAI.Analysis.FiniteFactor.Coupling.FiniteLaw +OAI.Analysis.FiniteFactor.Coupling.FinitePosteriorAC +OAI.Analysis.FiniteFactor.Coupling.Infinite +OAI.Analysis.FiniteFactor.Coupling.Law +OAI.Analysis.FiniteFactor.Coupling.Limit +OAI.Analysis.FiniteFactor.Coupling.Marginals +OAI.Analysis.FiniteFactor.Coupling.Mixture +OAI.Analysis.FiniteFactor.Coupling.Noncrossing +OAI.Analysis.FiniteFactor.Coupling.Order +OAI.Analysis.FiniteFactor.Coupling.Parameters +OAI.Analysis.FiniteFactor.Coupling.Prefix +OAI.Analysis.FiniteFactor.Coupling.Products +OAI.Analysis.FiniteFactor.Coupling.TaggedAdmissibility +OAI.Analysis.FiniteFactor.Coupling.VectorBayes +OAI.Analysis.FiniteFactor.CrossedProduct.AngleLaw +OAI.Analysis.FiniteFactor.CrossedProduct.AngleRelations +OAI.Analysis.FiniteFactor.CrossedProduct.AssignedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.Attenuation +OAI.Analysis.FiniteFactor.CrossedProduct.BoundaryEvent +OAI.Analysis.FiniteFactor.CrossedProduct.CappedPair +OAI.Analysis.FiniteFactor.CrossedProduct.CappedTransfer +OAI.Analysis.FiniteFactor.CrossedProduct.CentralDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.CentralScalarField +OAI.Analysis.FiniteFactor.CrossedProduct.Cocycle +OAI.Analysis.FiniteFactor.CrossedProduct.ColumnSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.ConjugationVacuum +OAI.Analysis.FiniteFactor.CrossedProduct.ConvolutionCocycle +OAI.Analysis.FiniteFactor.CrossedProduct.CouplingBudget +OAI.Analysis.FiniteFactor.CrossedProduct.CurrentTaggedEvent +OAI.Analysis.FiniteFactor.CrossedProduct.DiagonalLoss +OAI.Analysis.FiniteFactor.CrossedProduct.EventExpectation +OAI.Analysis.FiniteFactor.CrossedProduct.EventLossAssembly +OAI.Analysis.FiniteFactor.CrossedProduct.EventMassUpper +OAI.Analysis.FiniteFactor.CrossedProduct.EventPositive +OAI.Analysis.FiniteFactor.CrossedProduct.FiberEnergy +OAI.Analysis.FiniteFactor.CrossedProduct.FiberIndicators +OAI.Analysis.FiniteFactor.CrossedProduct.FiberSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.FiberTotal +OAI.Analysis.FiniteFactor.CrossedProduct.FieldAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FieldRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCocycleBounds +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteCoefficients +OAI.Analysis.FiniteFactor.CrossedProduct.FiniteVectors +OAI.Analysis.FiniteFactor.CrossedProduct.FloorSupport +OAI.Analysis.FiniteFactor.CrossedProduct.FreeRotation +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundary +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBoundaryLoss +OAI.Analysis.FiniteFactor.CrossedProduct.FutureBudget +OAI.Analysis.FiniteFactor.CrossedProduct.GeneratedAlgebra +OAI.Analysis.FiniteFactor.CrossedProduct.HilbertSeparable +OAI.Analysis.FiniteFactor.CrossedProduct.IndicatorProjection +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantConull +OAI.Analysis.FiniteFactor.CrossedProduct.InvariantProjection +OAI.Analysis.FiniteFactor.CrossedProduct.LusinCompact +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedError +OAI.Analysis.FiniteFactor.CrossedProduct.MaskedSquareMass +OAI.Analysis.FiniteFactor.CrossedProduct.MultiplicationAdjoint +OAI.Analysis.FiniteFactor.CrossedProduct.NoMinimalProjection +OAI.Analysis.FiniteFactor.CrossedProduct.NormalFunctionalSpace +OAI.Analysis.FiniteFactor.CrossedProduct.NormalRiesz +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedBadEvents +OAI.Analysis.FiniteFactor.CrossedProduct.OmittedRatio +OAI.Analysis.FiniteFactor.CrossedProduct.Operator +OAI.Analysis.FiniteFactor.CrossedProduct.OperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.OrbitNormalization +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedSampling +OAI.Analysis.FiniteFactor.CrossedProduct.OrderedTorusSampling +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCount +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseCoverage +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseDecay +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseFirst +OAI.Analysis.FiniteFactor.CrossedProduct.PhaseMarginal +OAI.Analysis.FiniteFactor.CrossedProduct.Phases +OAI.Analysis.FiniteFactor.CrossedProduct.Powers +OAI.Analysis.FiniteFactor.CrossedProduct.PredualIdentification +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedBase +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFactor +OAI.Analysis.FiniteFactor.CrossedProduct.PreparedFinite +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionColumns +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionConvolution +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionDiagonal +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionErrors +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionEvent +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.ProjectionPositiveConull +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceMixture +OAI.Analysis.FiniteFactor.CrossedProduct.ReferenceOrdered +OAI.Analysis.FiniteFactor.CrossedProduct.Reflection +OAI.Analysis.FiniteFactor.CrossedProduct.ResamplingLaw +OAI.Analysis.FiniteFactor.CrossedProduct.Rotation +OAI.Analysis.FiniteFactor.CrossedProduct.RotationCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.RotationErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCenter +OAI.Analysis.FiniteFactor.CrossedProduct.ScalarCommutant +OAI.Analysis.FiniteFactor.CrossedProduct.SmallPartitionSets +OAI.Analysis.FiniteFactor.CrossedProduct.StageCoupling +OAI.Analysis.FiniteFactor.CrossedProduct.StageOperator +OAI.Analysis.FiniteFactor.CrossedProduct.StagePolynomial +OAI.Analysis.FiniteFactor.CrossedProduct.Stages +OAI.Analysis.FiniteFactor.CrossedProduct.TagGeometry +OAI.Analysis.FiniteFactor.CrossedProduct.TagLaw +OAI.Analysis.FiniteFactor.CrossedProduct.TailTrimming +OAI.Analysis.FiniteFactor.CrossedProduct.TorusCharacters +OAI.Analysis.FiniteFactor.CrossedProduct.TorusErgodic +OAI.Analysis.FiniteFactor.CrossedProduct.TorusModel +OAI.Analysis.FiniteFactor.CrossedProduct.TorusOperatorField +OAI.Analysis.FiniteFactor.CrossedProduct.TorusRotation +OAI.Analysis.FiniteFactor.CrossedProduct.Trace +OAI.Analysis.FiniteFactor.CrossedProduct.TracialRepresentation +OAI.Analysis.FiniteFactor.CrossedProduct.Transport +OAI.Analysis.FiniteFactor.CrossedProduct.TruncatedBound +OAI.Analysis.FiniteFactor.CrossedProduct.UncappedPairIdentity +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumFunctional +OAI.Analysis.FiniteFactor.CrossedProduct.VacuumSeparating +OAI.Analysis.FiniteFactor.CrossedProduct.VectorFunctionalRelations +OAI.Analysis.FiniteFactor.CrossedProduct.WeightedShiftField +OAI.Analysis.FiniteFactor.Diffuse.OperatorCesaro +OAI.Analysis.FiniteFactor.Diffuse.OperatorMeanErgodic +OAI.Analysis.FiniteFactor.Diffuse.OperatorSupport +OAI.Analysis.FiniteFactor.Diffuse.ProjectionTrace +OAI.Analysis.FiniteFactor.Diffuse.SmallPartitions +OAI.Analysis.FiniteFactor.Diffuse.SupportLimit +OAI.Analysis.FiniteFactor.Diffuse.SupportTrace +OAI.Analysis.FiniteFactor.Diffuse.TracePowers +OAI.Analysis.FiniteFactor.Fiber.Diagonal +OAI.Analysis.FiniteFactor.Fiber.PairZeroSet +OAI.Analysis.FiniteFactor.Fiber.ProjectionDiagonal +OAI.Analysis.FiniteFactor.Fiber.Shift +OAI.Analysis.FiniteFactor.Fiber.StrongContinuity +OAI.Analysis.FiniteFactor.Fiber.TransportConvolution +OAI.Analysis.FiniteFactor.FiniteMeasureCylinderCriterion +OAI.Analysis.FiniteFactor.FiniteMixtureAlgebra +OAI.Analysis.FiniteFactor.FiniteProductAbsoluteContinuity +OAI.Analysis.FiniteFactor.FiniteProductMixture +OAI.Analysis.FiniteFactor.FiniteSingleTag +OAI.Analysis.FiniteFactor.IndependentCount +OAI.Analysis.FiniteFactor.L2UniformAbsoluteContinuity +OAI.Analysis.FiniteFactor.Main +OAI.Analysis.FiniteFactor.Matrix.Action +OAI.Analysis.FiniteFactor.Matrix.Bounds +OAI.Analysis.FiniteFactor.Matrix.Covariance +OAI.Analysis.FiniteFactor.Matrix.Entries +OAI.Analysis.FiniteFactor.Matrix.Integrals +OAI.Analysis.FiniteFactor.Model +OAI.Analysis.FiniteFactor.OperatorTracialRepresentation +OAI.Analysis.FiniteFactor.OperatorUltraweak +OAI.Analysis.FiniteFactor.OrbitSampling.CompactTorus +OAI.Analysis.FiniteFactor.OrbitSampling.CrossProducts +OAI.Analysis.FiniteFactor.OrbitSampling.Cube +OAI.Analysis.FiniteFactor.OrbitSampling.CutoffMass +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderBasis +OAI.Analysis.FiniteFactor.OrbitSampling.CylinderSystem +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalContribution +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalEvent +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalIntegral +OAI.Analysis.FiniteFactor.OrbitSampling.DiagonalLimit +OAI.Analysis.FiniteFactor.OrbitSampling.Discrepancy +OAI.Analysis.FiniteFactor.OrbitSampling.EmpiricalL2 +OAI.Analysis.FiniteFactor.OrbitSampling.Error +OAI.Analysis.FiniteFactor.OrbitSampling.ErrorEvent +OAI.Analysis.FiniteFactor.OrbitSampling.FirstCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.FirstMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.Fourier +OAI.Analysis.FiniteFactor.OrbitSampling.IdealProduct +OAI.Analysis.FiniteFactor.OrbitSampling.IdealRectangleLimit +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaMass +OAI.Analysis.FiniteFactor.OrbitSampling.LambdaRectangles +OAI.Analysis.FiniteFactor.OrbitSampling.LimitMeasure +OAI.Analysis.FiniteFactor.OrbitSampling.Measures +OAI.Analysis.FiniteFactor.OrbitSampling.Moments +OAI.Analysis.FiniteFactor.OrbitSampling.OrbitSupport +OAI.Analysis.FiniteFactor.OrbitSampling.OrderedRestriction +OAI.Analysis.FiniteFactor.OrbitSampling.PairMoments +OAI.Analysis.FiniteFactor.OrbitSampling.PhaseSelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.Powers +OAI.Analysis.FiniteFactor.OrbitSampling.ProductError +OAI.Analysis.FiniteFactor.OrbitSampling.ProductMoments +OAI.Analysis.FiniteFactor.OrbitSampling.RationalTests +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleApproximation +OAI.Analysis.FiniteFactor.OrbitSampling.RectangleError +OAI.Analysis.FiniteFactor.OrbitSampling.RotationTransport +OAI.Analysis.FiniteFactor.OrbitSampling.SecondCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.SecondMarginal +OAI.Analysis.FiniteFactor.OrbitSampling.SelfMoment +OAI.Analysis.FiniteFactor.OrbitSampling.SelfSummability +OAI.Analysis.FiniteFactor.OrbitSampling.SingleCorrelation +OAI.Analysis.FiniteFactor.OrbitSampling.Tail +OAI.Analysis.FiniteFactor.OrbitSampling.TestedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TestedTransport +OAI.Analysis.FiniteFactor.OrbitSampling.TorusLimitMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TorusSupport +OAI.Analysis.FiniteFactor.OrbitSampling.TriangleLaw +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedMarginals +OAI.Analysis.FiniteFactor.OrbitSampling.TrimmedWeak +OAI.Analysis.FiniteFactor.OrbitSampling.UniformEvent +OAI.Analysis.FiniteFactor.OrbitSampling.WeakLimit +OAI.Analysis.FiniteFactor.OrbitSampling.WeightedTail +OAI.Analysis.FiniteFactor.OrbitSampling.Weights +OAI.Analysis.FiniteFactor.PeriodizedUniform +OAI.Analysis.FiniteFactor.Polynomial +OAI.Analysis.FiniteFactor.ProductDensityLimit +OAI.Analysis.FiniteFactor.ProductKernel +OAI.Analysis.FiniteFactor.Quasinilpotence +OAI.Analysis.FiniteFactor.Sampling.AveragedTransport +OAI.Analysis.FiniteFactor.Sampling.Cancellation +OAI.Analysis.FiniteFactor.Sampling.FirstDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.FirstInterval +OAI.Analysis.FiniteFactor.Sampling.Fourier +OAI.Analysis.FiniteFactor.Sampling.FourierSum +OAI.Analysis.FiniteFactor.Sampling.IntegratedCorrelation +OAI.Analysis.FiniteFactor.Sampling.IntervalError +OAI.Analysis.FiniteFactor.Sampling.IntervalSums +OAI.Analysis.FiniteFactor.Sampling.Kernel +OAI.Analysis.FiniteFactor.Sampling.KernelTail +OAI.Analysis.FiniteFactor.Sampling.LayerCake +OAI.Analysis.FiniteFactor.Sampling.LayerDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.MixedCorrelation +OAI.Analysis.FiniteFactor.Sampling.OrientedMoments +OAI.Analysis.FiniteFactor.Sampling.Periodization +OAI.Analysis.FiniteFactor.Sampling.ProductError +OAI.Analysis.FiniteFactor.Sampling.Rectangle +OAI.Analysis.FiniteFactor.Sampling.SecondDensity +OAI.Analysis.FiniteFactor.Sampling.SecondDiscrepancy +OAI.Analysis.FiniteFactor.Sampling.SecondInterval +OAI.Analysis.FiniteFactor.Sampling.SecondLevelAE +OAI.Analysis.FiniteFactor.Sampling.SecondLevels +OAI.Analysis.FiniteFactor.Sampling.SecondMoment +OAI.Analysis.FiniteFactor.Sampling.SecondTriangular +OAI.Analysis.FiniteFactor.Sampling.Selection +OAI.Analysis.FiniteFactor.Sampling.SelfMoment +OAI.Analysis.FiniteFactor.Sampling.SmoothedPair +OAI.Analysis.FiniteFactor.Sampling.Smoothing +OAI.Analysis.FiniteFactor.Sampling.SmoothingLaw +OAI.Analysis.FiniteFactor.Sampling.TestedFirstMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSecondMoment +OAI.Analysis.FiniteFactor.Sampling.TestedSelfMoment +OAI.Analysis.FiniteFactor.Sampling.Transport +OAI.Analysis.FiniteFactor.Sampling.WeightTransport +OAI.Analysis.FiniteFactor.Sampling.WeightedCoordinate +OAI.Analysis.FiniteFactor.Sampling.Weights +OAI.Analysis.FiniteFactor.SubmeasureL2Density +OAI.Analysis.FiniteFactor.TagExponentialLower +OAI.Analysis.FiniteFactor.TailEstimate +OAI.Analysis.FiniteFactor.Truncation diff --git a/tasks/product-brown/solution/reference.py b/tasks/product-brown/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/product-brown/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/product-brown/solution/solve.sh b/tasks/product-brown/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5c331a6dd314e0bb7ed3dd86fd6c5d46bb98e8cd --- /dev/null +++ b/tasks/product-brown/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ProductBrown, i.e. module OAI.Analysis.BrownMeasure.Main and the +# 292 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.BrownMeasure.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ProductBrown" diff --git a/tasks/product-brown/task.toml b/tasks/product-brown/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bcc0152d32c17500d631d56f7713c11756343c39 --- /dev/null +++ b/tasks/product-brown/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/product-brown" +version = "1.0.0" +description = "Prove ProductBrown (openai/math family 293: A counterexample to the hyperinvariant-subspace problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ProductBrown.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ProductBrown" +family = "293" +family_title = "A counterexample to the hyperinvariant-subspace problem" +subject = "Operator algebras" +theorems = ["OAI.FiniteFactor.productBrown"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.BrownMeasure.Main" +reference_modules = 292 +reference_lean_bytes = 1198654 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 853 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12778 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/product-brown/tests/Challenge.lean b/tasks/product-brown/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a2bbbe9672222d5b4a7db18864d1f8497aec588d --- /dev/null +++ b/tasks/product-brown/tests/Challenge.lean @@ -0,0 +1,757 @@ +import Mathlib + +namespace OAI + +section +noncomputable section +open Polynomial +namespace FiniteFactor + +theorem product_has_low_nonzero_coeff (K : ℕ) (p q : ℂ[X]) + (hp : p.coeff K ≠ 0) (hq : q.coeff K ≠ 0) : + ∃ n ≤ 2 * K, (p * q).coeff n ≠ 0 := by + have hp0 : p ≠ 0 := by intro h; simp [h] at hp + have hq0 : q ≠ 0 := by intro h; simp [h] at hq + refine ⟨(p * q).natTrailingDegree, ?_, + Polynomial.coeff_natTrailingDegree_ne_zero.mpr (mul_ne_zero hp0 hq0)⟩ + rw [Polynomial.natTrailingDegree_mul hp0 hq0] + have ha := Polynomial.natTrailingDegree_le_of_ne_zero hp + have hb := Polynomial.natTrailingDegree_le_of_ne_zero hq + omega + +abbrev Coefficients (K : ℕ) := Fin (2 * K + 1) → ℂ + +noncomputable def coefficientPolynomial {K : ℕ} (a : Coefficients K) : ℂ[X] := + ∑ i : Fin (2 * K + 1), Polynomial.monomial i.val (a i) + +theorem coefficientPolynomial_coeff {K : ℕ} (a : Coefficients K) + (i : Fin (2 * K + 1)) : (coefficientPolynomial a).coeff i.val = a i := by + classical + simp [coefficientPolynomial, Polynomial.finsetSum_coeff, Polynomial.coeff_monomial, + Fin.val_inj] + +noncomputable def productCoefficient {K : ℕ} (a b : Coefficients K) (n : ℕ) : ℂ := + ∑ i : Fin (2 * K + 1), ∑ j : Fin (2 * K + 1), + if i.val + j.val = n then a i * b j else 0 + +theorem productCoefficient_eq {K : ℕ} (a b : Coefficients K) (n : ℕ) : + productCoefficient a b n = + (coefficientPolynomial a * coefficientPolynomial b).coeff n := by + classical + simp only [productCoefficient, coefficientPolynomial, Finset.sum_mul, Finset.mul_sum, + Polynomial.monomial_mul_monomial, Polynomial.finsetSum_coeff, Polynomial.coeff_monomial] + exact Finset.sum_comm + +theorem continuous_productCoefficient (K n : ℕ) : + Continuous (fun ab : Coefficients K × Coefficients K => + productCoefficient ab.1 ab.2 n) := by + classical + unfold productCoefficient + apply continuous_finsetSum + intro i _ + apply continuous_finsetSum + intro j _ + split_ifs <;> fun_prop + +noncomputable def lowCoefficients {K : ℕ} (ab : Coefficients K × Coefficients K) : + Coefficients K := fun n => productCoefficient ab.1 ab.2 n.val + +theorem continuous_lowCoefficients (K : ℕ) : Continuous (@lowCoefficients K) := + continuous_pi fun n => continuous_productCoefficient K n.val + +theorem lowCoefficients_ne_zero {K : ℕ} (ab : Coefficients K × Coefficients K) + (ha : ab.1 ⟨K, by omega⟩ ≠ 0) (hb : ab.2 ⟨K, by omega⟩ ≠ 0) : + lowCoefficients ab ≠ 0 := by + have ha' : (coefficientPolynomial ab.1).coeff K ≠ 0 := by + simpa using (coefficientPolynomial_coeff ab.1 ⟨K, by omega⟩).trans_ne ha + have hb' : (coefficientPolynomial ab.2).coeff K ≠ 0 := by + simpa using (coefficientPolynomial_coeff ab.2 ⟨K, by omega⟩).trans_ne hb + obtain ⟨n, hn, hne⟩ := product_has_low_nonzero_coeff K _ _ ha' hb' + intro h + have hz := congrFun h ⟨n, by omega⟩ + exact hne (by simpa [lowCoefficients, productCoefficient_eq] using hz) + +def admissibleCoefficients (K : ℕ) (D δ : ℝ) : Set (Coefficients K) := + {a | ∀ i, ‖a i‖ ≤ D} ∩ {a | δ ≤ ‖a ⟨K, by omega⟩‖} + +theorem isCompact_admissibleCoefficients (K : ℕ) (D δ : ℝ) : + IsCompact (admissibleCoefficients K D δ) := by + have hc : IsCompact {a : Coefficients K | ∀ i, ‖a i‖ ≤ D} := by + simpa [Set.pi, Metric.mem_closedBall, dist_zero_right] using + (isCompact_pi_infinite fun _ : Fin (2 * K + 1) => + isCompact_closedBall (0 : ℂ) D) + exact hc.inter_right (isClosed_le continuous_const (continuous_apply (⟨K, by omega⟩ : Fin (2 * K + 1))).norm) + +theorem uniform_product_coefficient_bound (K : ℕ) (D δ : ℝ) (hδ : 0 < δ) : + ∃ ε : ℝ, 0 < ε ∧ ∀ a b : Coefficients K, + (∀ i, ‖a i‖ ≤ D) → (∀ i, ‖b i‖ ≤ D) → + δ ≤ ‖a ⟨K, by omega⟩‖ → δ ≤ ‖b ⟨K, by omega⟩‖ → + ∃ n : Fin (2 * K + 1), ε ≤ ‖productCoefficient a b n.val‖ := by + classical + let S := (admissibleCoefficients K D δ).prod (admissibleCoefficients K D δ) + have hc : IsCompact S := (isCompact_admissibleCoefficients K D δ).prod + (isCompact_admissibleCoefficients K D δ) + by_cases hs : S.Nonempty + · obtain ⟨ab, hab, hmin⟩ := hc.exists_isMinOn hs + (continuous_lowCoefficients K).norm.continuousOn + have hpos : 0 < ‖lowCoefficients ab‖ := by + apply norm_pos_iff.mpr + apply lowCoefficients_ne_zero + · exact norm_pos_iff.mp (hδ.trans_le hab.1.2) + · exact norm_pos_iff.mp (hδ.trans_le hab.2.2) + refine ⟨‖lowCoefficients ab‖, hpos, ?_⟩ + intro a b ha hb ha0 hb0 + have hm : ‖lowCoefficients ab‖ ≤ ‖lowCoefficients (a, b)‖ := + hmin ⟨⟨ha, ha0⟩, ⟨hb, hb0⟩⟩ + by_contra hn + push Not at hn + have hlt : ‖lowCoefficients (a, b)‖ < ‖lowCoefficients ab‖ := + (pi_norm_lt_iff hpos).mpr hn + exact (not_lt_of_ge hm) hlt + · refine ⟨1, zero_lt_one, ?_⟩ + intro a b ha hb ha0 hb0 + exact False.elim (hs ⟨(a, b), ⟨⟨ha, ha0⟩, ⟨hb, hb0⟩⟩⟩) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace FiniteFactor + +def unitIntervalMeasure : Measure ℝ := volume.restrict (Set.Ico 0 1) + +instance : IsProbabilityMeasure unitIntervalMeasure := by + constructor + simp [unitIntervalMeasure, Real.volume_Ico] + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory +open scoped ENNReal +namespace FiniteFactor + +def sourceKappa (s : ℕ) : ℝ := 1 / (100*((s : ℝ)+1)) + +end FiniteFactor +end +end + +section +noncomputable section +open Filter Finset +open scoped Topology +namespace FiniteFactor + +def sourceNextCutoff (m : ℕ) : ℕ := Nat.ceil ((m : ℝ)^((3/4 : ℝ)*(m : ℝ))) + +theorem sourceNextCutoff_large (m : ℕ) (hm : 100 ≤ m) : 2*m < sourceNextCutoff m := by + have hmR : (100 : ℝ) ≤ m := by exact_mod_cast hm + have hp : (m : ℝ)^2 ≤ (m : ℝ)^((3/4 : ℝ)*(m : ℝ)) := by + rw [← Real.rpow_natCast] + exact Real.rpow_le_rpow_of_exponent_le (by linarith) (by norm_num; linarith) + have hh := hp.trans (Nat.le_ceil _) + have hh2 : (2 : ℝ)*m < (sourceNextCutoff m : ℝ) := by + change (m : ℝ)^2 ≤ (sourceNextCutoff m : ℝ) at hh + nlinarith + exact_mod_cast hh2 + +theorem exists_source_block_length (R κ L G : ℝ) (hκ : 0 < κ) (hG : 0 < G) : + ∃ m : ℕ, R ≤ (m : ℝ) ∧ 100 ≤ m ∧ κ*(m : ℝ)^(1/40 : ℝ) ≥ L ∧ + G*(sourceNextCutoff m : ℝ) < (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) := by + have ht : Tendsto (fun m : ℕ => (m : ℝ)^(1/40 : ℝ)) atTop atTop := + (tendsto_rpow_atTop (by norm_num)).comp tendsto_natCast_atTop_atTop + obtain ⟨m, hmR, hm100, hmG, hmκ⟩ := + ((tendsto_natCast_atTop_atTop.eventually (eventually_ge_atTop R)).and + ((eventually_ge_atTop (100 : ℕ)).and + ((tendsto_natCast_atTop_atTop.eventually (eventually_gt_atTop (2*G))).and + (ht.eventually (eventually_ge_atTop (L/κ)))))).exists + refine ⟨m, hmR, hm100, (div_le_iff₀ hκ).mp hmκ |>.trans_eq (mul_comm _ _), ?_⟩ + have hm1 : (1 : ℝ) ≤ m := by exact_mod_cast (show 1 ≤ m by omega) + have hm0 : (0 : ℝ) < m := lt_of_lt_of_le zero_lt_one hm1 + let A : ℝ := (m : ℝ)^((3/4 : ℝ)*(m : ℝ)) + have hApos : 0 < A := Real.rpow_pos_of_pos hm0 _ + have hA1 : 1 ≤ A := Real.one_le_rpow hm1 (by positivity) + have hceil : (sourceNextCutoff m : ℝ) ≤ 2*A := by + have hh := Nat.ceil_lt_add_one hApos.le + change (Nat.ceil A : ℝ) ≤ 2*A + linarith + calc + G*(sourceNextCutoff m : ℝ) ≤ G*(2*A) := mul_le_mul_of_nonneg_left hceil hG.le + _ < (m : ℝ)*A := by nlinarith + _ = (m : ℝ)^((3/4 : ℝ)*(m : ℝ)+1) := by rw [Real.rpow_add hm0, Real.rpow_one]; ring + _ ≤ (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) := + Real.rpow_le_rpow_of_exponent_le hm1 (by + have hh : (100 : ℝ) ≤ m := by exact_mod_cast hm100 + linarith) + +structure SourceStageState where + K : ℕ + G : ℝ + d : ℕ + B : ℝ + previousL : ℝ + K_ge : 1 ≤ K + G_ge : 1 ≤ G + B_nonneg : 0 ≤ B + previousL_ge : 1 ≤ previousL + +def SourceStageState.D (a : SourceStageState) : ℝ := Real.exp (((a.K : ℝ)+1)*a.B) + +structure SourceStageChoice (s : ℕ) (a : SourceStageState) where + ε : ℝ + L : ℝ + Gnext : ℝ + m : ℕ + ε_pos : 0 < ε + polynomial : ∀ u v : Coefficients a.K, + (∀ i, ‖u i‖ ≤ a.D) → (∀ i, ‖v i‖ ≤ a.D) → + 1/((s : ℝ)+1) ≤ ‖u ⟨a.K, by omega⟩‖ → 1/((s : ℝ)+1) ≤ ‖v ⟨a.K, by omega⟩‖ → + ∃ n : Fin (2*a.K+1), ε ≤ ‖productCoefficient u v n.val‖ + L_ge : a.previousL ≤ L + decay : ((2*a.K : ℕ)+1 : ℝ)*3*Real.exp (-L/10000) ≤ ε/((s : ℝ)+1) + Gnext_ge : 1 ≤ Gnext + next_budget : sourceKappa (s+1) * Real.sqrt Gnext ≥ L + m_ge_K : a.K ≤ m + m_ge_pow : 2^(s+1) ≤ m + m_ge_G : 4*a.G ≤ (m : ℝ) + m_ge_100 : 100 ≤ m + previous_size : (a.d : ℝ) ≤ (m : ℝ)/100 + current_budget : sourceKappa s * (m : ℝ)^(1/40 : ℝ) ≥ L + next_gap : Gnext*(sourceNextCutoff m : ℝ) < (m : ℝ)^((4/5 : ℝ)*(m : ℝ)) + +theorem exists_sourceStageChoice (s : ℕ) (a : SourceStageState) : + Nonempty (SourceStageChoice s a) := by + have hs : 0 < (s : ℝ)+1 := by positivity + have hk (j : ℕ) : 0 < sourceKappa j := by unfold sourceKappa; positivity + obtain ⟨ε, hε, hp⟩ := uniform_product_coefficient_bound a.K a.D (1/((s : ℝ)+1)) (by positivity) + let target : ℝ := (ε/((s : ℝ)+1))/(((2*a.K : ℕ)+1 : ℝ)*3) + have ht : 0 < target := by dsimp [target]; positivity + obtain ⟨t, htL, htt⟩ := ((eventually_ge_atTop (a.previousL/10000)).and + (Real.tendsto_exp_neg_atTop_nhds_zero.eventually (gt_mem_nhds ht))).exists + let L : ℝ := 10000*t + have hL : a.previousL ≤ L := by dsimp [L]; linarith + have hLpos : 0 < L := lt_of_lt_of_le (by linarith [a.previousL_ge]) hL + let G : ℝ := (1+L/sourceKappa (s+1))^2 + have hG : 1 ≤ G := by dsimp [G]; nlinarith [div_pos hLpos (hk (s+1))] + have hbudget : L ≤ sourceKappa (s+1)*Real.sqrt G := by + rw [show Real.sqrt G = 1+L/sourceKappa (s+1) by + dsimp [G]; rw [Real.sqrt_sq (by linarith [div_pos hLpos (hk (s+1))])]] + rw [mul_add, mul_one, mul_div_cancel₀ _ (hk (s+1)).ne'] + linarith [hk (s+1)] + let R : ℝ := max (a.K : ℝ) (max ((2^(s+1) : ℕ) : ℝ) (max (4*a.G) (100*(a.d : ℝ)))) + obtain ⟨m, hmR, hm100, hmκ, hmgap⟩ := exists_source_block_length R (sourceKappa s) L G (hk s) (by linarith) + have hmK : (a.K : ℝ) ≤ m := (le_max_left _ _).trans hmR + have hm2 : (((2^(s+1) : ℕ)) : ℝ) ≤ m := (le_max_left _ _).trans ((le_max_right _ _).trans hmR) + have hmG : 4*a.G ≤ (m : ℝ) := (le_max_left _ _).trans + ((le_max_right _ _).trans ((le_max_right _ _).trans hmR)) + have hmd : 100*(a.d : ℝ) ≤ m := (le_max_right _ _).trans + ((le_max_right _ _).trans ((le_max_right _ _).trans hmR)) + refine ⟨⟨ε, L, G, m, hε, hp, hL, ?_, hG, hbudget, + by exact_mod_cast hmK, by exact_mod_cast hm2, hmG, hm100, by linarith, hmκ, hmgap⟩⟩ + have hden : 0 < (((2*a.K : ℕ)+1 : ℝ)*3) := by positivity + have htt' := (lt_div_iff₀ hden).mp htt + have he : -L/10000 = -t := by dsimp [L]; ring + rw [he] + nlinarith + +def selectedSourceStage (s : ℕ) (a : SourceStageState) : SourceStageChoice s a := + Classical.choice (exists_sourceStageChoice s a) + +def SourceStageChoice.C {s : ℕ} {a : SourceStageState} (b : SourceStageChoice s a) : ℝ := + max b.L ((a.K : ℝ)^2) + +def SourceStageChoice.next {s : ℕ} {a : SourceStageState} (b : SourceStageChoice s a) : SourceStageState where + K := sourceNextCutoff b.m + G := b.Gnext + d := a.d+b.m + B := a.B+b.C*(b.m : ℝ) + previousL := b.L + K_ge := by have := sourceNextCutoff_large b.m b.m_ge_100; omega + G_ge := b.Gnext_ge + B_nonneg := add_nonneg a.B_nonneg (mul_nonneg (le_max_of_le_right (sq_nonneg _)) (Nat.cast_nonneg _)) + previousL_ge := a.previousL_ge.trans b.L_ge + +def sourceStageState : ℕ → SourceStageState + | 0 => ⟨100, 1, 0, 0, 1, by norm_num, le_rfl, le_rfl, le_rfl⟩ + | s+1 => (selectedSourceStage s (sourceStageState s)).next + +def sourceStage (s : ℕ) : SourceStageChoice s (sourceStageState s) := + selectedSourceStage s (sourceStageState s) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def coordinateFloor {ι : Type*} (θ : ι → ℝ) (k : ℤ) (x : ι → ℝ) (i : ι) : ℤ := + Int.floor (x i + (k : ℝ)*θ i) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def coordinateRotate {ι : Type*} (θ : ι → ℝ) (k : ℤ) (x : ι → ℝ) (i : ι) : ℝ := + Int.fract (x i + (k : ℝ)*θ i) + +def sourceLog {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : ℝ := + ∑' i, c i * (coordinateFloor θ k x i : ℝ) + +def sourceCocycle {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : ℝ := + Real.exp (-sourceLog θ c k x) + +theorem sourceCocycle_pos {ι : Type*} (θ c : ι → ℝ) (k : ℤ) (x : ι → ℝ) : + 0 < sourceCocycle θ c k x := Real.exp_pos _ + +theorem sourceCocycle_measurable {ι : Type*} [Countable ι] + (θ c : ι → ℝ) (k : ℤ) : + @Measurable (ι → ℝ) ℝ + (@MeasurableSpace.pi ι (fun _ => ℝ) (fun _ => Real.measurableSpace)) + Real.measurableSpace (sourceCocycle θ c k) := by + apply Real.continuous_exp.measurable.comp + apply Measurable.neg + apply Measurable.tsum + intro i + have hm0 : Measurable (fun x : ι → ℝ => x i + (k : ℝ)*θ i) := + (measurable_pi_apply i).add measurable_const + have hm := Int.measurable_floor.comp hm0 + exact measurable_const.mul ((measurable_of_countable (fun z : ℤ => (z : ℝ))).comp hm) + +theorem sourceWeight_le_one {ι : Type*} (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) {x : ι → ℝ} + (hx : ∀ i, x i ∈ Set.Ico 0 1) : sourceCocycle θ c 1 x ≤ 1 := by + apply Real.exp_le_one_iff.mpr + apply neg_nonpos.mpr + apply tsum_nonneg + intro i + apply mul_nonneg (hc i) + unfold coordinateFloor + exact_mod_cast Int.floor_nonneg.mpr (show 0 ≤ x i + (1 : ℤ)*θ i by simpa using add_nonneg (hx i).1 (hθ i)) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +abbrev sourceMeasure (ι : Type*) : Measure ((ι → ℝ) × ℤ) := + (Measure.infinitePi (fun _ : ι => unitIntervalMeasure)).prod Measure.count + +abbrev SourceHilbert (ι : Type*) : Type _ := Lp ℂ 2 (sourceMeasure ι) + +def sourceDiagonal {ι : Type*} (θ c : ι → ℝ) (z : (ι → ℝ) × ℤ) : ℂ := + sourceCocycle θ c 1 (coordinateRotate θ z.2 z.1) + +theorem sourceDiagonal_measurable {ι : Type*} [Countable ι] (θ c : ι → ℝ) : + Measurable (sourceDiagonal θ c) := by + apply Complex.measurable_ofReal.comp + apply (sourceCocycle_measurable θ c 1).comp + apply Measurable.of_eval + intro i + unfold coordinateRotate + fun_prop + +theorem sourceDiagonal_norm_le {ι : Type*} (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) (z : (ι → ℝ) × ℤ) : + ‖sourceDiagonal θ c z‖ ≤ 1 := by + rw [sourceDiagonal, Complex.norm_real, Real.norm_of_nonneg (sourceCocycle_pos _ _ _ _).le] + apply sourceWeight_le_one θ c hθ hc + intro i + exact ⟨Int.fract_nonneg _, Int.fract_lt_one _⟩ + +theorem sourceDiagonal_memLp {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : + MemLp (sourceDiagonal θ c) ∞ (sourceMeasure ι) := + memLp_top_of_bound (sourceDiagonal_measurable θ c).aestronglyMeasurable 1 + (Eventually.of_forall (sourceDiagonal_norm_le θ c hθ hc)) + +def sourceMultiplication {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (ContinuousLinearMap.mul ℂ ℂ).holderL (sourceMeasure ι) ∞ 2 2 + ((sourceDiagonal_memLp θ c hθ hc).toLp (sourceDiagonal θ c)) + +def sourceShiftIndex {ι : Type*} (z : (ι → ℝ) × ℤ) : (ι → ℝ) × ℤ := (z.1, z.2-1) + +theorem sourceShiftIndex_preserving (ι : Type*) : + MeasurePreserving (sourceShiftIndex (ι := ι)) (sourceMeasure ι) (sourceMeasure ι) := by + have hm : Measurable (fun k : ℤ => k-1) := measurable_of_countable _ + have hi : Function.Injective (fun k : ℤ => k-1) := by intro a b h; dsimp at h; omega + have hs : Function.Surjective (fun k : ℤ => k-1) := by intro k; exact ⟨k+1, by dsimp; omega⟩ + have hp : MeasurePreserving (fun k : ℤ => k-1) Measure.count Measure.count := by + refine ⟨hm, ?_⟩ + ext S hS + rw [Measure.map_apply hm hS, Measure.count_apply (hS.preimage hm), Measure.count_apply hS, + ← hi.encard_image, Set.image_preimage_eq S hs] + exact (MeasurePreserving.id _).prod hp + +def sourceShift (ι : Type*) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (Lp.compMeasurePreservingₗᵢ ℂ sourceShiftIndex (sourceShiftIndex_preserving ι)).toContinuousLinearMap + +def sourceOperator {ι : Type*} [Countable ι] (θ c : ι → ℝ) + (hθ : ∀ i, 0 ≤ θ i) (hc : ∀ i, 0 ≤ c i) : SourceHilbert ι →L[ℂ] SourceHilbert ι := + (sourceShift ι).comp (sourceMultiplication θ c hθ hc) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter Finset +open scoped Topology ENNReal +namespace FiniteFactor +namespace CouplingParameters + +abbrev BlockCoordinate (m : ℕ → ℕ) := Σ s : ℕ, Fin (m s) + +end CouplingParameters +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter Finset +open scoped Topology ENNReal +namespace FiniteFactor + +def sourceBlockSize (s : ℕ) : ℕ := (sourceStage s).m +abbrev SourceCoordinate := CouplingParameters.BlockCoordinate sourceBlockSize + +def sourceLogWeight (i : SourceCoordinate) : ℝ := (sourceStage i.1).C + +def SourceAngles (θ : SourceCoordinate → ℝ) : Prop := + let realGroup : GroupWithZero ℝ := + (@DivisionRing.toDivisionSemiring ℝ Real.instField.toDivisionRing).toGroupWithZero + let realOrder : LE ℝ := @Preorder.toLE ℝ Real.partialOrder.toPreorder + ∀ i : SourceCoordinate, + let block : ℝ := @Nat.cast ℝ Real.instNatCast (sourceBlockSize i.1) + let cutoff : ℝ := @Nat.cast ℝ Real.instNatCast (sourceStageState i.1).K + let denominator : ℝ := @Mul.mul ℝ Real.instMul block cutoff + let lower : ℝ := + @Div.div ℝ realGroup.toDiv (@One.one ℝ Real.instOne) denominator + let upper : ℝ := + @Div.div ℝ realGroup.toDiv (@Nat.cast ℝ Real.instNatCast 2) denominator + @LE.le ℝ realOrder lower (θ i) ∧ @LE.le ℝ realOrder (θ i) upper + +theorem sourceBlockSize_pos (s : ℕ) : (0 : ℝ) < sourceBlockSize s := by + exact_mod_cast (show 0 < (sourceStage s).m by have := (sourceStage s).m_ge_100; omega) + +theorem sourceCutoff_pos (s : ℕ) : (0 : ℝ) < (sourceStageState s).K := by + exact_mod_cast (show 0 < (sourceStageState s).K by have := (sourceStageState s).K_ge; omega) + +theorem SourceAngles.nonneg {θ : SourceCoordinate → ℝ} (hθ : SourceAngles θ) + (i : SourceCoordinate) : + @LE.le ℝ (@Preorder.toLE ℝ Real.partialOrder.toPreorder) + (@Zero.zero ℝ Real.instZero) (θ i) := + let realGroup : GroupWithZero ℝ := + (@DivisionRing.toDivisionSemiring ℝ Real.instField.toDivisionRing).toGroupWithZero + let realOrder : Preorder ℝ := Real.partialOrder.toPreorder + let realStrict : @PosMulStrictMono ℝ Real.instMul Real.instZero realOrder := + @IsStrictOrderedRing.toPosMulStrictMono ℝ Real.semiring Real.partialOrder + Real.instIsStrictOrderedRing + let realReflect : @PosMulReflectLT ℝ Real.instMul Real.instZero realOrder := + @PosMulMono.toPosMulReflectLT ℝ Real.instMul Real.instZero Real.linearOrder + (@IsOrderedRing.toPosMulMono ℝ Real.semiring Real.partialOrder + Real.instIsOrderedRing) + let block : ℝ := @Nat.cast ℝ Real.instNatCast (sourceBlockSize i.1) + let cutoff : ℝ := @Nat.cast ℝ Real.instNatCast (sourceStageState i.1).K + let denominator : ℝ := @Mul.mul ℝ Real.instMul block cutoff + let lower : ℝ := + @Div.div ℝ realGroup.toDiv (@One.one ℝ Real.instOne) denominator + let upper : ℝ := + @Div.div ℝ realGroup.toDiv (@Nat.cast ℝ Real.instNatCast 2) denominator + let zeroReal : ℝ := @Zero.zero ℝ Real.instZero + @le_trans ℝ realOrder zeroReal lower (θ i) + (@le_of_lt ℝ realOrder zeroReal lower + ((@one_div_pos ℝ realGroup Real.partialOrder realReflect denominator).mpr + (@mul_pos ℝ realGroup.toMulZeroClass (a := block) (b := cutoff) + realOrder realStrict (sourceBlockSize_pos i.1) (sourceCutoff_pos i.1)))) + (@And.left + (@LE.le ℝ realOrder.toLE lower (θ i)) + (@LE.le ℝ realOrder.toLE (θ i) upper) + (hθ i)) + +theorem sourceLogWeight_nonneg (i : SourceCoordinate) : 0 ≤ sourceLogWeight i := + le_max_of_le_right (sq_nonneg _) + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter +open scoped ENNReal +namespace FiniteFactor + +def sourceVacuum : SourceHilbert SourceCoordinate := + @indicatorConstLp ((SourceCoordinate → ℝ) × ℤ) ℂ + (@Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace) + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + (Set.univ ×ˢ {(0 : ℤ)}) + (@Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero))) + (MeasurableSet.univ.prod (measurableSet_singleton (0 : ℤ))) + (letI : IsProbabilityMeasure unitIntervalMeasure := + ⟨(Measure.restrict_apply_univ + (μ := (volume : Measure ℝ)) (Set.Ico (0 : ℝ) 1)).trans + ((Real.volume_Ico (a := 0) (b := 1)).trans + ((congrArg ENNReal.ofReal (sub_zero (1 : ℝ))).trans + ENNReal.ofReal_one))⟩ + let base : Measure (SourceCoordinate → ℝ) := + Measure.infinitePi (fun _ : SourceCoordinate => unitIntervalMeasure) + let mass_one := + (Measure.prod_prod (μ := base) (ν := (Measure.count : Measure ℤ)) + Set.univ {(0 : ℤ)}).trans + ((congrArg₂ (fun left right : ℝ≥0∞ => left * right) + (measure_univ (μ := base)) + (Measure.count_singleton (0 : ℤ))).trans (one_mul (1 : ℝ≥0∞))) + fun mass_top => ENNReal.one_ne_top (mass_one.symm.trans mass_top)) (1 : ℂ) + +theorem sourceVacuum_norm : ‖sourceVacuum‖ = 1 := by + rw [sourceVacuum,norm_indicatorConstLp (by norm_num) (by norm_num)] + simp [measureReal_def,sourceMeasure,Measure.prod_prod] + +section + +local notation "vacuumMeasurable" => + @Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace +local notation "vacuumSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring +local notation "vacuumIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ vacuumSemiring) +local notation "vacuumHilbertGroup" => + @MeasureTheory.Lp.instNormedAddCommGroup + ((SourceCoordinate → ℝ) × ℤ) ℂ vacuumMeasurable + (@Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero))) + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + fact_one_le_two_ennreal +local notation "vacuumHilbertInner" => + @MeasureTheory.L2.innerProductSpace + ((SourceCoordinate → ℝ) × ℤ) ℂ ℂ Complex.instRCLike + vacuumMeasurable (sourceMeasure SourceCoordinate) + Complex.instNormedAddCommGroup (@RCLike.innerProductSpace ℂ Complex.instRCLike) +local notation "vacuumHilbertTopology" => + @UniformSpace.toTopologicalSpace (SourceHilbert SourceCoordinate) + (@PseudoMetricSpace.toUniformSpace (SourceHilbert SourceCoordinate) + (@MetricSpace.toPseudoMetricSpace (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toMetricSpace (SourceHilbert SourceCoordinate) vacuumHilbertGroup))) +local notation "vacuumHilbertAddition" => + @AddCommGroup.toAddCommMonoid (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toAddCommGroup (SourceHilbert SourceCoordinate) vacuumHilbertGroup) +local notation "vacuumHilbertModule" => + @NormedSpace.toModule ℂ (SourceHilbert SourceCoordinate) + (@DenselyNormedField.toNormedField ℂ + (@RCLike.toDenselyNormedField ℂ Complex.instRCLike)) + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + vacuumHilbertInner) + +abbrev sourceVacuumFunctional + (operator : @ContinuousLinearMap ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + vacuumHilbertModule vacuumHilbertModule) : ℂ := + @inner ℂ (SourceHilbert SourceCoordinate) + (@InnerProductSpace.toInner ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) vacuumHilbertGroup) + vacuumHilbertInner) sourceVacuum + (@AddHom.toFun (SourceHilbert SourceCoordinate) (SourceHilbert SourceCoordinate) + (vacuumHilbertAddition).toAdd (vacuumHilbertAddition).toAdd + (@LinearMap.toAddHom ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) (SourceHilbert SourceCoordinate) + vacuumHilbertAddition vacuumHilbertAddition vacuumHilbertModule vacuumHilbertModule + (@ContinuousLinearMap.toLinearMap ℂ ℂ vacuumSemiring vacuumSemiring vacuumIdentity + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + (SourceHilbert SourceCoordinate) vacuumHilbertTopology vacuumHilbertAddition + vacuumHilbertModule vacuumHilbertModule operator)) sourceVacuum) + +end + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology ENNReal CStarAlgebra +namespace FiniteFactor + +local instance : IsometricContinuousFunctionalCalculus ℝ + (SourceHilbert SourceCoordinate →L[ℂ] SourceHilbert SourceCoordinate) IsSelfAdjoint := + IsSelfAdjoint.instIsometricContinuousFunctionalCalculus +instance productHilbertNontrivial : Nontrivial (SourceHilbert SourceCoordinate) := by + have hv : sourceVacuum≠0 := by + intro hz + have h := sourceVacuum_norm + rw [hz,norm_zero] at h + norm_num at h + exact ⟨⟨sourceVacuum,0,hv⟩⟩ + +end FiniteFactor +end +end + +section +noncomputable section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology +namespace FiniteFactor + +local notation "productMeasurable" => + @Prod.instMeasurableSpace (SourceCoordinate → ℝ) ℤ + (@MeasurableSpace.pi SourceCoordinate (fun _ => ℝ) + (fun _ => Real.measurableSpace)) Int.instMeasurableSpace +local notation "productSemiring" => + Complex.instNormedField.toField.toCommRing.toRing.toSemiring +local notation "productIdentity" => + @RingHom.id ℂ (@Semiring.toNonAssocSemiring ℂ productSemiring) +local notation "productExponent" => + @Nat.cast ENNReal + (ENNReal.instAddCommMonoidWithOne.toAddMonoidWithOne.toNatCast) + (Nat.succ (Nat.succ Nat.zero)) +local notation "productHilbertGroup" => + @MeasureTheory.Lp.instNormedAddCommGroup + ((SourceCoordinate → ℝ) × ℤ) ℂ productMeasurable + productExponent + (sourceMeasure SourceCoordinate) Complex.instNormedAddCommGroup + fact_one_le_two_ennreal +local notation "productHilbertInner" => + @MeasureTheory.L2.innerProductSpace + ((SourceCoordinate → ℝ) × ℤ) ℂ ℂ Complex.instRCLike + productMeasurable (sourceMeasure SourceCoordinate) + Complex.instNormedAddCommGroup (@RCLike.innerProductSpace ℂ Complex.instRCLike) +local notation "productHilbertTopology" => + @UniformSpace.toTopologicalSpace (SourceHilbert SourceCoordinate) + (@PseudoMetricSpace.toUniformSpace (SourceHilbert SourceCoordinate) + (@MetricSpace.toPseudoMetricSpace (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toMetricSpace (SourceHilbert SourceCoordinate) productHilbertGroup))) +local notation "productHilbertAddition" => + @AddCommGroup.toAddCommMonoid (SourceHilbert SourceCoordinate) + (@NormedAddCommGroup.toAddCommGroup (SourceHilbert SourceCoordinate) productHilbertGroup) +local notation "productHilbertModule" => + @NormedSpace.toModule ℂ (SourceHilbert SourceCoordinate) + (@DenselyNormedField.toNormedField ℂ + (@RCLike.toDenselyNormedField ℂ Complex.instRCLike)) + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + productHilbertInner) + +abbrev ProductOp := + @ContinuousLinearMap ℂ ℂ productSemiring productSemiring productIdentity + (SourceHilbert SourceCoordinate) productHilbertTopology productHilbertAddition + (SourceHilbert SourceCoordinate) productHilbertTopology productHilbertAddition + productHilbertModule productHilbertModule + +section +open MeasureTheory Filter InnerProductSpace +open scoped ComplexInnerProductSpace Topology ENNReal + +local instance : Module ℝ ProductOp := Module.complexToReal ProductOp +local instance : IsometricContinuousFunctionalCalculus ℝ ProductOp IsSelfAdjoint := + IsSelfAdjoint.instIsometricContinuousFunctionalCalculus + +def logarithmCutoff (n : ℕ) : C(ℝ,ℝ) where + toFun t := Real.log (max (Real.exp (-(n:ℝ))) t) + continuous_toFun := (continuous_const.max continuous_id).log + (fun _=>ne_of_gt ((Real.exp_pos _).trans_le (le_max_left _ _))) + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def FugledeKadisonDeterminant (τ : ProductOp → ℂ) (T : ProductOp) : ℝ≥0∞ := + let determinant := fun (Hilbert : Type) [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] [Nontrivial Hilbert] + (trace : (Hilbert →L[ℂ] Hilbert) → ℂ) (operator : Hilbert →L[ℂ] Hilbert) => + letI : Module ℝ (Hilbert →L[ℂ] Hilbert) := Module.complexToReal _ + letI : IsometricContinuousFunctionalCalculus ℝ (Hilbert →L[ℂ] Hilbert) + IsSelfAdjoint := IsSelfAdjoint.instIsometricContinuousFunctionalCalculus + ⨅ n : ℕ, ENNReal.ofReal + (Real.exp ((trace (cfc (logarithmCutoff n) (CFC.abs operator))).re)) + let domain := (SourceCoordinate → ℝ) × ℤ + let measurable : MeasurableSpace domain := productMeasurable + let exponent : ℝ≥0∞ := productExponent + let measure : @Measure domain measurable := sourceMeasure SourceCoordinate + let complete := @MeasureTheory.Lp.instCompleteSpace domain measurable exponent measure ℂ + Complex.instNormedAddCommGroup Complex.instCompleteSpace fact_one_le_two_ennreal + @determinant (SourceHilbert SourceCoordinate) productHilbertGroup productHilbertInner + complete productHilbertNontrivial τ T + +end + +section +open MeasureTheory Filter +open scoped ENNReal Topology + +def expLogPotential (μ : Measure ℂ) (z : ℂ) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (Real.exp (∫ w,logarithmCutoff n ‖z-w‖ ∂μ)) + +def IsBrownMeasure (τ : ProductOp → ℂ) (T : ProductOp) (μ : Measure ℂ) : Prop := + let translate := fun (Hilbert : Type) [NormedAddCommGroup Hilbert] + [NormedSpace ℂ Hilbert] (operator : Hilbert →L[ℂ] Hilbert) (scalar : ℂ) => + operator - algebraMap ℂ (Hilbert →L[ℂ] Hilbert) scalar + IsProbabilityMeasure μ ∧ IsCompact μ.support ∧ + ∀ z : ℂ, FugledeKadisonDeterminant τ + (@translate (SourceHilbert SourceCoordinate) productHilbertGroup + (@InnerProductSpace.toNormedSpace ℂ (SourceHilbert SourceCoordinate) Complex.instRCLike + (@NormedAddCommGroup.toSeminormedAddCommGroup + (SourceHilbert SourceCoordinate) productHilbertGroup) + productHilbertInner) T z) = expLogPotential μ z + +def ProductBrownClaim : Prop := + ∀ (θ : SourceCoordinate → ℝ) (hθ : SourceAngles θ), + IsBrownMeasure sourceVacuumFunctional + (sourceOperator θ sourceLogWeight hθ.nonneg sourceLogWeight_nonneg) (Measure.dirac 0) + +end + +end FiniteFactor +end +end + +namespace FiniteFactor + +/-- The Brown measure of the product weighted shift is the point mass at zero. -/ +theorem productBrown : ProductBrownClaim := by + sorry + +end FiniteFactor + +end OAI diff --git a/tasks/product-brown/tests/grade.py b/tasks/product-brown/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/product-brown/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/product-brown/tests/task.json b/tasks/product-brown/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ad6f981a91a05d975ca19f80da9a223b8889ec75 --- /dev/null +++ b/tasks/product-brown/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ProductBrown", + "comparator": { + "theorem_names": [ + "OAI.FiniteFactor.productBrown" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11878 +} \ No newline at end of file diff --git a/tasks/product-brown/tests/test.sh b/tasks/product-brown/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/product-brown/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/projection-counterexample/environment/Dockerfile b/tasks/projection-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/projection-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/projection-counterexample/environment/fetch_mathlib.sh b/tasks/projection-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/projection-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/projection-counterexample/environment/lake-manifest.json b/tasks/projection-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/projection-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/projection-counterexample/environment/lakefile.lean b/tasks/projection-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/projection-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/projection-counterexample/environment/lean_setup.sh b/tasks/projection-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/projection-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/projection-counterexample/environment/pack_submission.py b/tasks/projection-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/projection-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/projection-counterexample/instruction.md b/tasks/projection-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b6514df987fceead8285786df39054d11e848b6 --- /dev/null +++ b/tasks/projection-counterexample/instruction.md @@ -0,0 +1,96 @@ +# openai/math challenge `ProjectionCounterexample` (family 088) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 088 of the release, *Petty's projection-volume conjecture and simplex counterexamples* +(Convex and metric geometry). The family as a whole: Proves Petty's projection-volume conjecture in the remaining dimensions $n\ge4$: ellipsoids uniquely minimize projection-body volume at fixed body volume. Also establishes the full Lutwak–Petty projection inequalities. In contrast, products of simplices exceed Brannen's proposed simplex maximum for normalized projection-body volume by an exponential factor in every sufficiently large dimension. + +The challenge is `ProjectionCounterexample`, also at `/opt/openai-math/challenges/ProjectionCounterexample.lean`: + +```lean +import Mathlib.Analysis.Convex.Hull +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Analysis.InnerProductSpace.Projection.Basic +import Mathlib.Geometry.Euclidean.Volume.Measure + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace ProjectionCounterexample + +abbrev E (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def simplex (d : ℕ) : Set (E d) := + convexHull ℝ (insert 0 (range fun i : Fin d => EuclideanSpace.single i (1 : ℝ))) + +def IsConvexBody {d : ℕ} (P : Set (E d)) : Prop := + IsCompact P ∧ Convex ℝ P ∧ (interior P).Nonempty + +def project {d : ℕ} (u : E d) : E d →L[ℝ] E d := + (ℝ ∙ u)ᗮ.starProjection + +def projectionVolume {d : ℕ} (P : Set (E d)) (u : E d) : ℝ := + (Measure.euclideanHausdorffMeasure (d - 1) (project u '' P)).toReal + +def projectionBody {d : ℕ} (P : Set (E d)) : Set (E d) := + {x | ∀ u : E d, ‖u‖ = 1 → ⟪u, x⟫ ≤ projectionVolume P u} + +def bodyVolume {d : ℕ} (P : Set (E d)) : ℝ := (volume P).toReal + +def ratio {d : ℕ} (P : Set (E d)) : ℝ := + bodyVolume (projectionBody P) / bodyVolume P ^ (d - 1) + +theorem universal_simplex_upper_bound_false : + ¬ (∀ P : Set (E 20), IsConvexBody P → ratio P ≤ ratio (simplex 20)) := by + sorry + +end ProjectionCounterexample + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ProjectionCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ProjectionCounterexample.universal_simplex_upper_bound_false` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/projection-counterexample/solution/closure.txt b/tasks/projection-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5e6ae9c8d7f17296baaf7a5f2809e2ff3ebdc72c --- /dev/null +++ b/tasks/projection-counterexample/solution/closure.txt @@ -0,0 +1,41 @@ +OAI.Geometry.ProjectionBody.AffineChartMeasure +OAI.Geometry.ProjectionBody.Arithmetic +OAI.Geometry.ProjectionBody.BrightnessSum +OAI.Geometry.ProjectionBody.ConvexGeometry +OAI.Geometry.ProjectionBody.Counterexample +OAI.Geometry.ProjectionBody.Definitions +OAI.Geometry.ProjectionBody.FacetCoordinates +OAI.Geometry.ProjectionBody.FacetCover +OAI.Geometry.ProjectionBody.FacetMeasure +OAI.Geometry.ProjectionBody.GeometryDefinitions +OAI.Geometry.ProjectionBody.GraphChart +OAI.Geometry.ProjectionBody.GraphJacobian +OAI.Geometry.ProjectionBody.GraphProjection +OAI.Geometry.ProjectionBody.HyperplaneJacobian +OAI.Geometry.ProjectionBody.NullHyperplane +OAI.Geometry.ProjectionBody.ProductBrightness +OAI.Geometry.ProjectionBody.ProductFacetCharts +OAI.Geometry.ProjectionBody.ProductFacetGraphs +OAI.Geometry.ProjectionBody.ProductFacetIndices +OAI.Geometry.ProjectionBody.ProductFacetProjection +OAI.Geometry.ProjectionBody.ProductFacets +OAI.Geometry.ProjectionBody.ProductVolumes +OAI.Geometry.ProjectionBody.ProductZonotopeBridge +OAI.Geometry.ProjectionBody.ProjectionKernel +OAI.Geometry.ProjectionBody.SimplexBrightness +OAI.Geometry.ProjectionBody.SimplexFacetCharts +OAI.Geometry.ProjectionBody.SimplexFacets +OAI.Geometry.ProjectionBody.SimplexVolume +OAI.Geometry.ProjectionBody.UnitSupport +OAI.Geometry.ProjectionBody.ZonotopeBridge +OAI.Geometry.Zonotope.Body +OAI.Geometry.Zonotope.Decomposition +OAI.Geometry.Zonotope.Determinant +OAI.Geometry.Zonotope.Euclidean +OAI.Geometry.Zonotope.EuclideanVolume +OAI.Geometry.Zonotope.Halfspaces +OAI.Geometry.Zonotope.Product +OAI.Geometry.Zonotope.Scaling +OAI.Geometry.Zonotope.Shear +OAI.Geometry.Zonotope.Support +OAI.Geometry.Zonotope.Volume diff --git a/tasks/projection-counterexample/solution/reference.py b/tasks/projection-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/projection-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/projection-counterexample/solution/solve.sh b/tasks/projection-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..16dd5c889c96898108a7b1867eb771c7f566181e --- /dev/null +++ b/tasks/projection-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ProjectionCounterexample, i.e. module OAI.Geometry.ProjectionBody.Counterexample and the +# 41 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.ProjectionBody.Counterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ProjectionCounterexample" diff --git a/tasks/projection-counterexample/task.toml b/tasks/projection-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1f7c6698a86d2b8dd7d2fca79826a56e9e939101 --- /dev/null +++ b/tasks/projection-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/projection-counterexample" +version = "1.0.0" +description = "Prove ProjectionCounterexample (openai/math family 088: Petty's projection-volume conjecture and simplex counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ProjectionCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ProjectionCounterexample" +family = "088" +family_title = "Petty's projection-volume conjecture and simplex counterexamples" +subject = "Convex and metric geometry" +theorems = ["OAI.ProjectionCounterexample.universal_simplex_upper_bound_false"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.ProjectionBody.Counterexample" +reference_modules = 41 +reference_lean_bytes = 131947 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 576 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11818 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/projection-counterexample/tests/Challenge.lean b/tasks/projection-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5c8504059ca289b96e9f3a5ec84de35c58d0967a --- /dev/null +++ b/tasks/projection-counterexample/tests/Challenge.lean @@ -0,0 +1,45 @@ +import Mathlib.Analysis.Convex.Hull +import Mathlib.Analysis.InnerProductSpace.PiL2 +import Mathlib.Analysis.InnerProductSpace.Projection.Basic +import Mathlib.Geometry.Euclidean.Volume.Measure + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace + +namespace ProjectionCounterexample + +abbrev E (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def simplex (d : ℕ) : Set (E d) := + convexHull ℝ (insert 0 (range fun i : Fin d => EuclideanSpace.single i (1 : ℝ))) + +def IsConvexBody {d : ℕ} (P : Set (E d)) : Prop := + IsCompact P ∧ Convex ℝ P ∧ (interior P).Nonempty + +def project {d : ℕ} (u : E d) : E d →L[ℝ] E d := + (ℝ ∙ u)ᗮ.starProjection + +def projectionVolume {d : ℕ} (P : Set (E d)) (u : E d) : ℝ := + (Measure.euclideanHausdorffMeasure (d - 1) (project u '' P)).toReal + +def projectionBody {d : ℕ} (P : Set (E d)) : Set (E d) := + {x | ∀ u : E d, ‖u‖ = 1 → ⟪u, x⟫ ≤ projectionVolume P u} + +def bodyVolume {d : ℕ} (P : Set (E d)) : ℝ := (volume P).toReal + +def ratio {d : ℕ} (P : Set (E d)) : ℝ := + bodyVolume (projectionBody P) / bodyVolume P ^ (d - 1) + +theorem universal_simplex_upper_bound_false : + ¬ (∀ P : Set (E 20), IsConvexBody P → ratio P ≤ ratio (simplex 20)) := by + sorry + +end ProjectionCounterexample + +end + +end OAI diff --git a/tasks/projection-counterexample/tests/grade.py b/tasks/projection-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/projection-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/projection-counterexample/tests/task.json b/tasks/projection-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..abf166c83cf8efaddaf792d812c1f06d25675ff9 --- /dev/null +++ b/tasks/projection-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ProjectionCounterexample", + "comparator": { + "theorem_names": [ + "OAI.ProjectionCounterexample.universal_simplex_upper_bound_false" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10918 +} \ No newline at end of file diff --git a/tasks/projection-counterexample/tests/test.sh b/tasks/projection-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/projection-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/projection-moments/environment/Dockerfile b/tasks/projection-moments/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/projection-moments/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/projection-moments/environment/fetch_mathlib.sh b/tasks/projection-moments/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/projection-moments/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/projection-moments/environment/lake-manifest.json b/tasks/projection-moments/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/projection-moments/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/projection-moments/environment/lakefile.lean b/tasks/projection-moments/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/projection-moments/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/projection-moments/environment/lean_setup.sh b/tasks/projection-moments/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/projection-moments/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/projection-moments/environment/pack_submission.py b/tasks/projection-moments/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/projection-moments/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/projection-moments/instruction.md b/tasks/projection-moments/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3015cfbf7cbb44fa6fd4df95a4086e548cfb6717 --- /dev/null +++ b/tasks/projection-moments/instruction.md @@ -0,0 +1,765 @@ +# openai/math challenge `ProjectionMoments` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `ProjectionMoments`, also at `/opt/openai-math/challenges/ProjectionMoments.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +universe u + +namespace NoiselessRegression + +section + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev State (M : ℕ) := Fin (2 ^ M) + +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Learner (d M T : ℕ) (Ω : Type u) where + initialChoice : Ω → Bool × State M + transition : ℕ → Ω → State M → (Vector d × ℝ) → Bool × State M + output : ℕ → Ω → State M → UnitSphere d + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def start {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) (ω : Ω) : + RunStatus M := + let a := L.initialChoice ω + if a.1 then .inr (0, a.2) else .inl a.2 + +def run {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ → RunStatus M + | 0 => L.start ω + | n + 1 => + match L.run s ω x n with + | .inr done => .inr done + | .inl state => + if hn : n < T then + let row := x ⟨n, hn⟩ + let a := L.transition (n + 1) ω state (row, ⟪row, s.val⟫) + if a.1 then .inr (n + 1, a.2) else .inl a.2 + else .inl state + +def terminal {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ × State M := + match L.run s ω x T with + | .inl state => (T, state) + | .inr done => done + +def estimate {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : UnitSphere d := + let a := L.terminal s ω x + L.output a.1 ω a.2 + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) : Prop where + initialChoice : AEMeasurable L.initialChoice ρ + transition : ∀ t a, AEMeasurable (fun z : Ω × (Vector d × ℝ) => + L.transition t z.1 a z.2) (ρ.prod (observationReference d)) + output : ∀ t a, AEMeasurable (fun ω => L.output t ω a) ρ + fixed_experiment : ∀ s, AEMeasurable (fun z : Ω × Samples d T => + L.estimate s z.1 z.2) (ρ.prod (sampleLaw d T)) + uniform_experiment : AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => L.estimate z.1 z.2.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end Learner + +open scoped Topology + +open InnerProductSpace + +section SphereBounds + +open scoped Pointwise + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def sphereLaw : Measure (Metric.sphere (0 : E) 1) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +end SphereBounds + +open scoped Pointwise + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def ambientSphereLaw : Measure E := (sphereLaw (E := E)).map Subtype.val + +end + +section + +section + +variable {d M T : ℕ} {Ω : Type u} + +abbrev Learner.TaggedState (M T : ℕ) := Sum (State M) (Fin (T+1) × State M) + +instance Learner.taggedMeasurableSpace : MeasurableSpace (TaggedState M T) := ⊤ + +def Learner.taggedStart (a : Bool × State M) : TaggedState M T := + if a.1 then .inr (⟨0,by omega⟩,a.2) else .inl a.2 + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + +structure Learner.MeasurableRules (L : Learner d M T Ω) : Prop where + initial : Measurable L.initialChoice + transition : ∀ t j, Measurable (fun z : Ω × (Vector d × ℝ) => L.transition t z.1 j z.2) + output : ∀ t j, Measurable (fun ω => L.output t ω j) + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +structure FiniteKernelLearner (d M T : ℕ) where + initial : Measure (Bool × State M) + initial_probability : IsProbabilityMeasure initial + transition : ℕ → State M → (Vector d × ℝ) → Measure (Bool × State M) + transition_probability : ∀ t j obs, IsProbabilityMeasure (transition t j obs) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t j, IsProbabilityMeasure (output t j) + +namespace FiniteKernelLearner + +variable {d M T : ℕ} + +structure CompletedRules (K : FiniteKernelLearner d M T) : Prop where + transition : ∀ t j a, AEMeasurable (fun obs => K.transition t j obs {a}) (observationReference d) + +end FiniteKernelLearner + +open MeasureTheory ProbabilityTheory Set Filter unitInterval + +section CoinRun + +variable {J O : Type*} [Fintype J] [MeasurableSpace J] [MeasurableSingletonClass J] + [MeasurableSpace O] + +def kernelRun (P : ℕ → J → O → Measure J) : (n : ℕ) → J → (Fin n → O) → Measure J + | 0, j, _ => Measure.dirac j + | n+1, j, obs => (kernelRun P n j (Fin.init obs)).bind (fun a => P (n+1) a (obs (Fin.last n))) + +end CoinRun + +section + +section + +open Learner + +variable {d M T : ℕ} + +abbrev FiniteKernelLearner.Tape (M T : ℕ) := (Bool × State M) × ((Fin T → I) × I) + +def FiniteKernelLearner.destination (t : ℕ) (h : t ≤ T) (a : Bool × State M) : TaggedState M T := + if a.1 then .inr (⟨t,by omega⟩,a.2) else .inl a.2 + +def FiniteKernelLearner.taggedKernel (K : FiniteKernelLearner d M T) (t : ℕ) : + TaggedState M T → (Vector d × ℝ) → Measure (TaggedState M T) + | .inr a, _ => Measure.dirac (.inr a) + | .inl j, obs => if ht : t ≤ T then (K.transition t j obs).map (destination t ht) + else Measure.dirac (.inl j) + +def FiniteKernelLearner.terminalOutput (K : FiniteKernelLearner d M T) : TaggedState M T → Measure (UnitSphere d) + | .inl j => K.output T j + | .inr (t,j) => K.output t j + +end + +open MeasureTheory ProbabilityTheory Set Filter unitInterval + +open scoped ENNReal NNReal RealInnerProductSpace + +open Learner + +variable {d M T : ℕ} + +abbrev FiniteKernelLearner.Result (d M : ℕ) := (ℕ × State M) × UnitSphere d + +def FiniteKernelLearner.terminalTag : TaggedState M T → ℕ × State M + | .inl j => (T,j) + | .inr (t,j) => (t,j) + +def FiniteKernelLearner.terminalJointOutput (K : FiniteKernelLearner d M T) (j : TaggedState M T) : Measure (Result d M) := + (K.terminalOutput j).map (fun y => (terminalTag j,y)) + +def FiniteKernelLearner.jointExperimentLaw (K : FiniteKernelLearner d M T) (obs : Fin T → (Vector d × ℝ)) : Measure (Result d M) := + K.initial.bind (fun a => (kernelRun K.taggedKernel T (taggedStart a) obs).bind K.terminalJointOutput) + +def FiniteKernelLearner.uniformSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × Samples d T, + K.jointExperimentLaw (fun i => (z.2 i,⟪z.1.val,z.2 i⟫)) + {r | angularError z.1 r.2 ≤ ε} ∂((uniformSphere d).prod (sampleLaw d T)) + +def FiniteKernelLearner.uniformFixedSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × Samples d T, + K.jointExperimentLaw (fun i => (z.2 i,⟪z.1.val,z.2 i⟫)) + {r | r.1.1 = t ∧ angularError z.1 r.2 ≤ ε} ∂((uniformSphere d).prod (sampleLaw d T)) + +end + +section + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] [Nontrivial E] + +variable {d M T : ℕ} {Ω : Type u} + +def Learner.uniformFixedSuccess [MeasurableSpace Ω] (L : Learner d M T Ω) (ρ : Measure Ω) + (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | (L.terminal z.1 z.2.1 z.2.2).1 = t ∧ angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end + +section + +variable {d M T : ℕ} + +def FiniteKernelLearner.seededSuccess {Ξ : Type u} [MeasurableSpace Ξ] + (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ ξ, (K ξ).uniformSuccess ε ∂ρ + +def FiniteKernelLearner.seededFixedSuccess {Ξ : Type u} [MeasurableSpace Ξ] + (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ∫⁻ ξ, (K ξ).uniformFixedSuccess ε t ∂ρ + +def FiniteKernelLearner.FixedQuadraticMemory : Prop := + ∀ A₀ : ℝ, 0 < A₀ → ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, + ∀ d : ℕ, d₀ ≤ d → ∀ M T : ℕ, (M : ℝ) ≤ A₀ * (d : ℝ)^2 → + ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + (2/3 : ℝ≥0∞) ≤ seededSuccess K ρ ε → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ) + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {d M T : ℕ} {Ξ : Type u} [MeasurableSpace Ξ] + +def FiniteKernelLearner.conditionalSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) + (s : UnitSphere d) (x : Samples d T) : ℝ≥0∞ := + K.jointExperimentLaw (fun i => (x i,⟪s.val,x i⟫)) {r | Learner.angularError s r.2 ≤ ε} + +def FiniteKernelLearner.seededPointwiseSuccess (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) + (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + ∫⁻ z : Ξ × Samples d T, (K z.1).conditionalSuccess ε s z.2 ∂ρ.prod (sampleLaw d T) + +def FiniteKernelLearner.JointSuccessMeasurable (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) : Prop := + AEMeasurable (fun z : UnitSphere d × (Ξ × Samples d T) => + (K z.2.1).conditionalSuccess ε z.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def FiniteKernelLearner.SubquadraticMemoryWithPointwise : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ((2/3 : ℝ≥0∞) ≤ seededSuccess K ρ ε ∨ + (JointSuccessMeasurable K ρ ε ∧ ∀ s, (2/3 : ℝ≥0∞) ≤ seededPointwiseSuccess K ρ ε s)) → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ) + +end NoiselessRegression + +namespace ProjectionMoments + +open NoiselessRegression NoiselessRegression.FiniteKernelLearner + +section + +section GaussianGraph + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def vectorSmoothing (ν : Measure E) (m : ℕ) (φ : (Fin m → ℝ) → ℝ≥0∞) + (z : (Fin m → E) × (Fin m → ℝ)) : ℝ≥0∞ := + ∫⁻ t, φ (fun j => z.2 j - ⟪t, z.1 j⟫) ∂ν + +abbrev Label (m : ℕ) := EuclideanSpace ℝ (Fin m) + +def ballKernel (m : ℕ) (η : ℝ) (y : Fin m → ℝ) : ℝ≥0∞ := + (Metric.closedBall (0 : Label m) η).indicator + (fun _ => (volume (Metric.closedBall (0 : Label m) η))⁻¹) (WithLp.toLp 2 y) + +def rowMap {m : ℕ} (A : Fin m → E) : E →L[ℝ] Label m := + (PiLp.continuousLinearEquiv 2 ℝ (fun _ : Fin m => ℝ)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun j => innerSL ℝ (A j))) + +def ballAverage (ν : Measure E) (m : ℕ) (η : ℝ) + (z : (Fin m → E) × Label m) : ℝ≥0∞ := + vectorSmoothing ν m (ballKernel m η) (z.1, WithLp.ofLp z.2) + +def lowerDensity (ν : Measure E) (m : ℕ) (z : (Fin m → E) × Label m) : ℝ≥0∞ := + liminf (fun n : ℕ => ballAverage ν m ((n : ℝ) + 1)⁻¹ z) atTop + +def AllBallMass (ν : Measure E) (K a : ℝ) : Prop := + ∀ b : E, ∀ t : ℝ, 0 < t → ν (Metric.closedBall b t) ≤ ENNReal.ofReal (K * t ^ a) + +end GaussianGraph + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +section Rotations + +variable (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +abbrev Rotation := unitary (E →L[ℝ] E) + +instance rotationMeasurableSpace : MeasurableSpace (Rotation E) := borel (Rotation E) + +instance rotationBorelSpace : BorelSpace (Rotation E) := ⟨rfl⟩ + +instance rotationCompact : CompactSpace (Rotation E) := by + apply isCompact_iff_compactSpace.mp + apply Metric.isCompact_of_isClosed_isBounded isClosed_unitary + apply (Metric.isBounded_closedBall (x := (0 : E →L[ℝ] E)) (r := 1)).subset (s := (unitary (E →L[ℝ] E) : Set (E →L[ℝ] E))) + intro U hU + rw [Metric.mem_closedBall, dist_zero_right] + by_cases h : Subsingleton E + · have := h + simp + · have : Nontrivial E := not_subsingleton_iff_nontrivial.mp h + exact (CStarRing.norm_of_mem_unitary hU).le + +def rotationLaw : Measure (Rotation E) := + ((Measure.haar : Measure (Rotation E)) Set.univ)⁻¹ • Measure.haar + +variable {E} + +variable [MeasurableSpace E] [BorelSpace E] + +def rotateRows {ι : Type*} (O : Rotation E) (v : ι → E) : ι → E := + fun i => (O : E →L[ℝ] E) (v i) + +end Rotations + +section Triangular + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + [MeasurableSpace E] [BorelSpace E] + +def coordinateMap {m : ℕ} (A : Fin m → E) : E →ₗ[ℝ] (Fin m → ℝ) := + (WithLp.linearEquiv 2 ℝ (Fin m → ℝ)) ∘ₗ (rowMap A).toLinearMap + +def coordinateDensity (ν : Measure E) (m : ℕ) (z : (Fin m → E) × (Fin m → ℝ)) : ℝ≥0∞ := + lowerDensity ν m (z.1, WithLp.toLp 2 z.2) + +def frameLaw {m : ℕ} (u : Fin m → E) : Measure (Fin m → E) := + (rotationLaw E).map (fun O => rotateRows O u) + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def rieszKernel (α : ℝ) (z s : E) : ℝ≥0∞ := (ENNReal.ofReal ‖s-z‖)^(-α) + +def rieszPotential (α : ℝ) (h : E → ℝ≥0∞) : ℝ≥0∞ := + ⨆ z : E, ∫⁻ s, h s*rieszKernel α z s ∂NoiselessRegression.ambientSphereLaw + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace Matrix + +open scoped ENNReal NNReal RealInnerProductSpace Topology MatrixOrder Matrix.Norms.L2Operator + +def mixRows {k : ℕ} (M : Matrix (Fin k) (Fin k) ℝ) (X : Fin k → E) : Fin k → E := + fun i => ∑ j, M i j • X j + +def polarRadial {k : ℕ} (X : Fin k → E) : Matrix (Fin k) (Fin k) ℝ := + CFC.sqrt (Matrix.gram ℝ X) + +def rawPolarRows {k : ℕ} (X : Fin k → E) : Fin k → E := + mixRows (polarRadial X)⁻¹ X + +def polarRows {k : ℕ} (u X : Fin k → E) : Fin k → E := by + classical + exact if LinearIndependent ℝ X then rawPolarRows X else u + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def unitBallVolume (k : ℕ) : ℝ≥0∞ := (volume : Measure (Label k)) (Metric.closedBall 0 1) + +def unitBallLaw (k : ℕ) : Measure (Label k) := + (unitBallVolume k)⁻¹ • volume.restrict (Metric.closedBall 0 1) + +def normalizedDensity (ν : Measure E) (k : ℕ) (u : Fin k → E) + (z : (Fin k → E) × Label k) : ℝ≥0∞ := + unitBallVolume k * lowerDensity ν k (polarRows u z.1,z.2) + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def sphereWeightedRestriction (h : E → ℝ≥0∞) (H : Set E) : Measure E := + (NoiselessRegression.ambientSphereLaw.withDensity h).restrict H + +end Triangular + +section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +variable {E : Type u} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def capMeasure (c : E) (r : ℝ) : Measure E := + (NoiselessRegression.ambientSphereLaw (Metric.closedBall c r))⁻¹ • + NoiselessRegression.ambientSphereLaw.restrict (Metric.closedBall c r) + +structure CapDictionary (c : E) (r α : ℝ) where + I : Type u + countable : Countable I + center : I → E + radius : I → ℝ + center_norm : ∀ i, ‖center i‖ = 1 + radius_pos : ∀ i, 0 < radius i + radius_le : ∀ i, radius i ≤ r + parent : I + parent_center : center parent = c + parent_radius : radius parent = r + proper : ∀ R : ℝ, {i | (r/radius i)^α ≤ R}.Finite + cover : ∀ (s : E), ‖s‖ = 1 → ∀ t : ℝ, 0 < t → t ≤ 1/4 → + ∃ i, 4*r*t ≤ radius i ∧ radius i < 8*r*t ∧ dist s (center i) ≤ radius i/2 + +end + +section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace Matrix + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def radialLabel {k : ℕ} (X : Fin k → E) (y : Label k) : Label k := + WithLp.toLp 2 (polarRadial X *ᵥ y.ofLp) + +def capKernelValue {k : ℕ} (K : (Fin k → E) × Label k → ℝ≥0∞) (s : E) : ℝ≥0∞ := + ∫⁻ X, K (X,rowMap X s) ∂Measure.pi (fun _ => stdGaussian E) + +def capReferenceLabel {k : ℕ} (c : E) (r : ℝ) (X : Fin k → E) (z : Label k) : Label k := + rowMap X c + r • radialLabel X z + +def capReference {k : ℕ} (K : (Fin k → E) × Label k → ℝ≥0∞) (c : E) (r : ℝ) : ℝ≥0∞ := + ∫⁻ X, ∫⁻ z, K (X,capReferenceLabel c r X z) ∂unitBallLaw k ∂Measure.pi (fun _ => stdGaussian E) + +end + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def fractionalBlock {J : Type*} [Fintype J] {k : ℕ} + (Q : J → (Fin k → E) × Label k → ℝ≥0∞) (f : J → E → ℝ≥0∞) (s : E) : ℝ≥0∞ := + ∫⁻ X, ∑ j, Q j (X,rowMap X s)*f j s ∂Measure.pi (fun _ => stdGaussian E) + +end + +def IntegratedFrameMoment : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ (d k q : ℕ) (β K R : ℝ) + (ν : Measure (EuclideanSpace ℝ (Fin d))) [IsFiniteMeasure ν] + (z : EuclideanSpace ℝ (Fin d)) (u : Fin k → EuclideanSpace ℝ (Fin d)), + 1 ≤ k → 2 ≤ q → k+q ≤ d → 0 < β → β ≤ d → + 1 ≤ β-k-((q:ℝ)-2) → 0 ≤ K → 0 < R → + ν.support ⊆ Metric.closedBall z R → AllBallMass ν K β → + Orthonormal ℝ u → + (∀ᵐ A ∂frameLaw u, ν.map (coordinateMap A) ≪ (volume : Measure (Fin k → ℝ))) → + Measurable (coordinateDensity ν k) ∧ + (∀ᵐ A ∂frameLaw u, + (volume : Measure (Fin k → ℝ)).withDensity (fun y => coordinateDensity ν k (A,y)) = + ν.map (coordinateMap A)) ∧ + (∀ (A : Fin k → EuclideanSpace ℝ (Fin d)), Orthonormal ℝ A → + ∀ y : Fin k → ℝ, + R < ‖WithLp.toLp 2 (y-coordinateMap A z)‖ → coordinateDensity ν k (A,y) = 0) ∧ + (∫⁻ A, ∫⁻ y : Fin k → ℝ, coordinateDensity ν k (A,y)^q ∂volume ∂frameLaw u) ^ (1/(q:ℝ)) ≤ + ENNReal.ofReal (C^d * (C*Real.sqrt d)^((k:ℝ)*(1-1/(q:ℝ))) * + K * R^(β-(k:ℝ)*(1-1/(q:ℝ)))) + +def NormalizedUnitBallMoment : Prop := + ∀ D : ℝ, 0 < D → + ∃ C_D : ℝ, 0 < C_D ∧ ∀ d : ℕ, 32 ≤ d → + let k := d/16 + let lam : ℝ := ((d:ℝ)-1)/2 + ∀ (ν : Measure (EuclideanSpace ℝ (Fin d))) [IsFiniteMeasure ν] + (u : Fin k → EuclideanSpace ℝ (Fin d)), + ν Set.univ ≤ 1 → ν.support ⊆ Metric.closedBall 0 1 → + AllBallMass ν (D^d) lam → Orthonormal ℝ u → + (∀ᵐ X ∂Measure.pi (fun _ : Fin k => stdGaussian (EuclideanSpace ℝ (Fin d))), + ν.map (rowMap (polarRows u X)) ≪ (volume : Measure (Label k))) → + Measurable (normalizedDensity ν k u) ∧ + (∀ᵐ X ∂Measure.pi (fun _ : Fin k => stdGaussian (EuclideanSpace ℝ (Fin d))), + ((unitBallVolume k)⁻¹ • (volume : Measure (Label k))).withDensity + (fun y => normalizedDensity ν k u (X,y)) = ν.map (rowMap (polarRows u X))) ∧ + (∀ X y, 1 < ‖y‖ → normalizedDensity ν k u (X,y) = 0) ∧ + (∫⁻ X, ∫⁻ y, normalizedDensity ν k u (X,y)^k ∂unitBallLaw k + ∂Measure.pi (fun _ => stdGaussian (EuclideanSpace ℝ (Fin d)))) ≤ + ENNReal.ofReal (Real.exp (C_D*d*k)) + +def AllRadiiSphereMoment : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/4 + let β : ℝ := (d:ℝ)-1-k + ∀ f : EuclideanSpace ℝ (Fin d) → ℝ≥0∞, + Measurable f → (∀ s, f s ≤ 1) → + ∀ K : ℝ, 0 ≤ K → + AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity f) K β → + ∀ z : EuclideanSpace ℝ (Fin d), ∀ R : ℝ, 0 < R → + ∀ u : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ u → + let μ := sphereWeightedRestriction f (Metric.closedBall z R) + Measurable (coordinateDensity μ k) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ A → + (volume : Measure (Fin k → ℝ)).withDensity (fun y => coordinateDensity μ k (A,y)) = + μ.map (coordinateMap A)) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ A → + ∀ y : Fin k → ℝ, R < ‖WithLp.toLp 2 (y-coordinateMap A z)‖ → + coordinateDensity μ k (A,y) = 0) ∧ + (∫⁻ A, ∫⁻ y : Fin k → ℝ, coordinateDensity μ k (A,y)^k ∂volume ∂frameLaw u) ^ (1/(k:ℝ)) ≤ + ENNReal.ofReal (C^d*(C*Real.sqrt d)^((k:ℝ)*(1-1/(k:ℝ)))* + K*R^(β-(k:ℝ)*(1-1/(k:ℝ)))) + +def PositiveCapDomination : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 32 ≤ d → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + ∀ (c : EuclideanSpace ℝ (Fin d)), ‖c‖ = 1 → + ∀ r : ℝ, 0 < r → r ≤ 2 → ∀ N : ℕ, + ∀ K : Fin N → (Fin k → EuclideanSpace ℝ (Fin d)) × Label k → ℝ≥0∞, + (∀ j, Measurable (K j)) → (∀ z, ∑ j, K j z ≤ 1) → + (∑ j, capReference (K j) c r) ≤ 1 ∧ + ∀ j, ∃ D : CapDictionary c r α, ∃ a : D.I → ℝ, + (∀ i, 0 ≤ a i) ∧ Summable (fun i => a i*(r/D.radius i)^α) ∧ + (∑' i, a i*(r/D.radius i)^α) ≤ Real.exp (C*d)*(capReference (K j) c r).toReal^(1-1/(k:ℝ)) ∧ + (capMeasure c r).withDensity (capKernelValue (K j)) ≤ + Measure.sum (fun i => ENNReal.ofReal (a i) • capMeasure (D.center i) (D.radius i)) ∧ + (Measure.sum (fun i => ENNReal.ofReal (a i) • capMeasure (D.center i) (D.radius i))) Set.univ < ∞ + +def DeterministicOffsetDensity : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/8 + let α : ℝ := (d:ℝ)/2 + ∀ h : EuclideanSpace ℝ (Fin d) → ℝ≥0∞, Measurable h → (∀ s, h s ≤ 1) → + ∀ z : EuclideanSpace ℝ (Fin d), ∀ ρ : ℝ, 0 < ρ → + ∀ H : Set (EuclideanSpace ℝ (Fin d)), MeasurableSet H → H ⊆ Metric.closedBall z ρ → + rieszPotential α h < ∞ ∧ + Measurable (lowerDensity (sphereWeightedRestriction h H) k) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), LinearIndependent ℝ A → + volume.withDensity (fun y => lowerDensity (sphereWeightedRestriction h H) k (A,y)) = + (sphereWeightedRestriction h H).map (rowMap A)) ∧ + (∀ b : Label k, (∫⁻ A, (lowerDensity (sphereWeightedRestriction h H) k (A,rowMap A z+b))^k + ∂Measure.pi (fun _ => stdGaussian (EuclideanSpace ℝ (Fin d))))^(1/(k:ℝ)) ≤ + ENNReal.ofReal (C^d) * rieszPotential α h * ENNReal.ofReal (ρ^(α-k))) ∧ + (∀ A y, ‖rowMap A‖*ρ < ‖y-rowMap A z‖ → + lowerDensity (sphereWeightedRestriction h H) k (A,y) = 0) + +def AllRadiiBlockBound : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/4 + let β : ℝ := (d:ℝ)-1-k + ∀ N : ℕ, ∀ f : Fin N → EuclideanSpace ℝ (Fin d) → ℝ≥0∞, + (∀ j, Measurable (f j)) → (∀ j s, f j s ≤ 1) → + ∀ K : ℝ, 0 ≤ K → + (∀ j, AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity (f j)) K β) → + ∀ Q : Fin N → (Fin k → EuclideanSpace ℝ (Fin d)) × Label k → ℝ≥0∞, + (∀ j, Measurable (Q j)) → (∀ z, ∑ j, Q j z ≤ 1) → + AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity (fractionalBlock Q f)) + (C^d*(N:ℝ)^(1/(k:ℝ))*K) β + +def HaarStreamingCost : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let k := d/4 + let Nstar : ℝ := ((k:ℝ)+2)*2^M + seededSuccess K ρ ε ≤ ENNReal.ofReal + (C^d*ε^k*(C^d*Nstar^(1/(k:ℝ)))^((T+k-1)/k)) + +def RieszStreamingCost : Prop := + ∃ C₀ : ℝ, 1 ≤ C₀ ∧ ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let q := d/8 + let W : ℝ := ((T:ℝ)+2)*2^M + seededSuccess K ρ ε ≤ ENNReal.ofReal + (C₀^d*ε^((d:ℝ)/2-1)*(1+C₀^d*(1+Real.log (1/ε))*W^(1/(q:ℝ)))^((T+q-1)/q)) + +def CapFixedStoppingCost : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d M T : ℕ, 32 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ∀ t : ℕ, t ≤ T → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededFixedSuccess K ρ ε t ≤ ENNReal.ofReal + (Real.exp (C*d)*(ε/2)^α*(Real.exp (C*d)*(2:ℝ)^((M:ℝ)/k))^((t+k-1)/k)) + +def CapTotalStoppingCost : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d M T : ℕ, 32 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededSuccess K ρ ε ≤ ENNReal.ofReal + (((T:ℝ)+1)*Real.exp (C*d)*(ε/2)^α* + (Real.exp (C*d)*(2:ℝ)^((M:ℝ)/k))^((T+k-1)/k)) + +def CapFixedStoppingAsymptotic : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d:ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ∀ t : ℕ, t ≤ T → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededFixedSuccess K ρ ε t ≤ ENNReal.ofReal + (Real.exp (C*d*(1+((t+k-1)/k:ℕ)))*(ε/2)^α) + +def CapTotalStoppingAsymptotic : Prop := + ∃ C₁ C₂ : ℝ, 0 < C₁ ∧ 0 < C₂ ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d:ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + seededSuccess K ρ ε ≤ ENNReal.ofReal + (((T:ℝ)+1)*Real.exp (C₁*d+C₂*T-(d:ℝ)*Real.log (1/ε)/3)) + +def KernelModelBridge : Prop := + ∀ d M T : ℕ, 3 ≤ d → ∀ K : FiniteKernelLearner d M T, K.CompletedRules → + ∃ (ρ : Measure (Tape M T)) (L : Learner d M T (Tape M T)), + IsProbabilityMeasure ρ ∧ L.MeasurableRules ∧ L.Admissible ρ ∧ + (∀ ε, L.uniformSuccess ρ ε = K.uniformSuccess ε) ∧ + (∀ ε t, L.uniformFixedSuccess ρ ε t = K.uniformFixedSuccess ε t) + +def MainStatement : Prop := + IntegratedFrameMoment ∧ NormalizedUnitBallMoment ∧ AllRadiiSphereMoment ∧ + PositiveCapDomination ∧ DeterministicOffsetDensity ∧ AllRadiiBlockBound ∧ + HaarStreamingCost.{u} ∧ RieszStreamingCost.{u} ∧ CapFixedStoppingCost.{u} ∧ + CapTotalStoppingCost.{u} ∧ CapFixedStoppingAsymptotic.{u} ∧ + CapTotalStoppingAsymptotic.{u} ∧ KernelModelBridge ∧ + NoiselessRegression.FiniteKernelLearner.SubquadraticMemoryWithPointwise.{u} ∧ + NoiselessRegression.FiniteKernelLearner.FixedQuadraticMemory.{u} + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace +open scoped ENNReal NNReal RealInnerProductSpace Topology + +theorem main : MainStatement.{u} := by + sorry + +end ProjectionMoments + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ProjectionMoments.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ProjectionMoments.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/projection-moments/solution/closure.txt b/tasks/projection-moments/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0d1743358bc7003c98a7159deb4791b0d059d50b --- /dev/null +++ b/tasks/projection-moments/solution/closure.txt @@ -0,0 +1,46 @@ +OAI.Probability.GaussianRegression.AffineTubes +OAI.Probability.GaussianRegression.Blocks +OAI.Probability.GaussianRegression.Caps +OAI.Probability.GaussianRegression.Execution +OAI.Probability.GaussianRegression.GaussianKernel +OAI.Probability.GaussianRegression.Gram +OAI.Probability.GaussianRegression.InverseMoments +OAI.Probability.GaussianRegression.Main +OAI.Probability.GaussianRegression.Model +OAI.Probability.GaussianRegression.Nets +OAI.Probability.GaussianRegression.Observation +OAI.Probability.GaussianRegression.Precision +OAI.Probability.GaussianRegression.Projection +OAI.Probability.GaussianRegression.ReplicaMoments +OAI.Probability.GaussianRegression.Rotational +OAI.Probability.GaussianRegression.Smoothing +OAI.Probability.GaussianRegression.Sphere +OAI.Probability.GaussianRegression.Stream +OAI.Probability.GaussianRegression.Success +OAI.Probability.GaussianRegression.Support +OAI.Probability.GaussianRegression.Transfer +OAI.Probability.ProjectionMoments.AllRadii +OAI.Probability.ProjectionMoments.Asymptotics +OAI.Probability.ProjectionMoments.BallMoments +OAI.Probability.ProjectionMoments.BorelRules +OAI.Probability.ProjectionMoments.CapDomination +OAI.Probability.ProjectionMoments.CapDuality +OAI.Probability.ProjectionMoments.CapTests +OAI.Probability.ProjectionMoments.Caps +OAI.Probability.ProjectionMoments.FrameMoments +OAI.Probability.ProjectionMoments.Frames +OAI.Probability.ProjectionMoments.GaussianDensity +OAI.Probability.ProjectionMoments.Graph +OAI.Probability.ProjectionMoments.Kernels +OAI.Probability.ProjectionMoments.Main +OAI.Probability.ProjectionMoments.Model +OAI.Probability.ProjectionMoments.Polar +OAI.Probability.ProjectionMoments.Realization +OAI.Probability.ProjectionMoments.RieszPotential +OAI.Probability.ProjectionMoments.Seeded +OAI.Probability.ProjectionMoments.SphereDensity +OAI.Probability.ProjectionMoments.SphereWeights +OAI.Probability.ProjectionMoments.Stopping +OAI.Probability.ProjectionMoments.StoppingKernel +OAI.Probability.ProjectionMoments.Streaming +OAI.Probability.ProjectionMoments.WeightedCover diff --git a/tasks/projection-moments/solution/reference.py b/tasks/projection-moments/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/projection-moments/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/projection-moments/solution/solve.sh b/tasks/projection-moments/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e4df244e777409d03c38966172c8dfa17e9ad3f6 --- /dev/null +++ b/tasks/projection-moments/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ProjectionMoments, i.e. module OAI.Probability.ProjectionMoments.Main and the +# 46 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ProjectionMoments.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ProjectionMoments" diff --git a/tasks/projection-moments/task.toml b/tasks/projection-moments/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..35583330a2a80972777791100c9e45d0fb8d2660 --- /dev/null +++ b/tasks/projection-moments/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/projection-moments" +version = "1.0.0" +description = "Prove ProjectionMoments (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ProjectionMoments.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ProjectionMoments" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.ProjectionMoments.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ProjectionMoments.Main" +reference_modules = 46 +reference_lean_bytes = 515196 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 919 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12163 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/projection-moments/tests/Challenge.lean b/tasks/projection-moments/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3409d69fb128e6ace78dc4e603df8063b984384d --- /dev/null +++ b/tasks/projection-moments/tests/Challenge.lean @@ -0,0 +1,714 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +universe u + +namespace NoiselessRegression + +section + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 + +abbrev State (M : ℕ) := Fin (2 ^ M) + +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure Learner (d M T : ℕ) (Ω : Type u) where + initialChoice : Ω → Bool × State M + transition : ℕ → Ω → State M → (Vector d × ℝ) → Bool × State M + output : ℕ → Ω → State M → UnitSphere d + +namespace Learner + +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def start {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) (ω : Ω) : + RunStatus M := + let a := L.initialChoice ω + if a.1 then .inr (0, a.2) else .inl a.2 + +def run {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ → RunStatus M + | 0 => L.start ω + | n + 1 => + match L.run s ω x n with + | .inr done => .inr done + | .inl state => + if hn : n < T then + let row := x ⟨n, hn⟩ + let a := L.transition (n + 1) ω state (row, ⟪row, s.val⟫) + if a.1 then .inr (n + 1, a.2) else .inl a.2 + else .inl state + +def terminal {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : ℕ × State M := + match L.run s ω x T with + | .inl state => (T, state) + | .inr done => done + +def estimate {d M T : ℕ} {Ω : Type u} (L : Learner d M T Ω) + (s : UnitSphere d) (ω : Ω) (x : Samples d T) : UnitSphere d := + let a := L.terminal s ω x + L.output a.1 ω a.2 + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) : Prop where + initialChoice : AEMeasurable L.initialChoice ρ + transition : ∀ t a, AEMeasurable (fun z : Ω × (Vector d × ℝ) => + L.transition t z.1 a z.2) (ρ.prod (observationReference d)) + output : ∀ t a, AEMeasurable (fun ω => L.output t ω a) ρ + fixed_experiment : ∀ s, AEMeasurable (fun z : Ω × Samples d T => + L.estimate s z.1 z.2) (ρ.prod (sampleLaw d T)) + uniform_experiment : AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => L.estimate z.1 z.2.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def angularError {d : ℕ} (s ŝ : UnitSphere d) : ℝ := + Real.arccos ⟪ŝ.val, s.val⟫ + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : Learner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end Learner + +open scoped Topology + +open InnerProductSpace + +section SphereBounds + +open scoped Pointwise + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def sphereLaw : Measure (Metric.sphere (0 : E) 1) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +end SphereBounds + +open scoped Pointwise + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def ambientSphereLaw : Measure E := (sphereLaw (E := E)).map Subtype.val + +end + +section + +section + +variable {d M T : ℕ} {Ω : Type u} + +abbrev Learner.TaggedState (M T : ℕ) := Sum (State M) (Fin (T+1) × State M) + +instance Learner.taggedMeasurableSpace : MeasurableSpace (TaggedState M T) := ⊤ + +def Learner.taggedStart (a : Bool × State M) : TaggedState M T := + if a.1 then .inr (⟨0,by omega⟩,a.2) else .inl a.2 + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + +structure Learner.MeasurableRules (L : Learner d M T Ω) : Prop where + initial : Measurable L.initialChoice + transition : ∀ t j, Measurable (fun z : Ω × (Vector d × ℝ) => L.transition t z.1 j z.2) + output : ∀ t j, Measurable (fun ω => L.output t ω j) + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +structure FiniteKernelLearner (d M T : ℕ) where + initial : Measure (Bool × State M) + initial_probability : IsProbabilityMeasure initial + transition : ℕ → State M → (Vector d × ℝ) → Measure (Bool × State M) + transition_probability : ∀ t j obs, IsProbabilityMeasure (transition t j obs) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t j, IsProbabilityMeasure (output t j) + +namespace FiniteKernelLearner + +variable {d M T : ℕ} + +structure CompletedRules (K : FiniteKernelLearner d M T) : Prop where + transition : ∀ t j a, AEMeasurable (fun obs => K.transition t j obs {a}) (observationReference d) + +end FiniteKernelLearner + +open MeasureTheory ProbabilityTheory Set Filter unitInterval + +section CoinRun + +variable {J O : Type*} [Fintype J] [MeasurableSpace J] [MeasurableSingletonClass J] + [MeasurableSpace O] + +def kernelRun (P : ℕ → J → O → Measure J) : (n : ℕ) → J → (Fin n → O) → Measure J + | 0, j, _ => Measure.dirac j + | n+1, j, obs => (kernelRun P n j (Fin.init obs)).bind (fun a => P (n+1) a (obs (Fin.last n))) + +end CoinRun + +section + +section + +open Learner + +variable {d M T : ℕ} + +abbrev FiniteKernelLearner.Tape (M T : ℕ) := (Bool × State M) × ((Fin T → I) × I) + +def FiniteKernelLearner.destination (t : ℕ) (h : t ≤ T) (a : Bool × State M) : TaggedState M T := + if a.1 then .inr (⟨t,by omega⟩,a.2) else .inl a.2 + +def FiniteKernelLearner.taggedKernel (K : FiniteKernelLearner d M T) (t : ℕ) : + TaggedState M T → (Vector d × ℝ) → Measure (TaggedState M T) + | .inr a, _ => Measure.dirac (.inr a) + | .inl j, obs => if ht : t ≤ T then (K.transition t j obs).map (destination t ht) + else Measure.dirac (.inl j) + +def FiniteKernelLearner.terminalOutput (K : FiniteKernelLearner d M T) : TaggedState M T → Measure (UnitSphere d) + | .inl j => K.output T j + | .inr (t,j) => K.output t j + +end + +open MeasureTheory ProbabilityTheory Set Filter unitInterval + +open scoped ENNReal NNReal RealInnerProductSpace + +open Learner + +variable {d M T : ℕ} + +abbrev FiniteKernelLearner.Result (d M : ℕ) := (ℕ × State M) × UnitSphere d + +def FiniteKernelLearner.terminalTag : TaggedState M T → ℕ × State M + | .inl j => (T,j) + | .inr (t,j) => (t,j) + +def FiniteKernelLearner.terminalJointOutput (K : FiniteKernelLearner d M T) (j : TaggedState M T) : Measure (Result d M) := + (K.terminalOutput j).map (fun y => (terminalTag j,y)) + +def FiniteKernelLearner.jointExperimentLaw (K : FiniteKernelLearner d M T) (obs : Fin T → (Vector d × ℝ)) : Measure (Result d M) := + K.initial.bind (fun a => (kernelRun K.taggedKernel T (taggedStart a) obs).bind K.terminalJointOutput) + +def FiniteKernelLearner.uniformSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × Samples d T, + K.jointExperimentLaw (fun i => (z.2 i,⟪z.1.val,z.2 i⟫)) + {r | angularError z.1 r.2 ≤ ε} ∂((uniformSphere d).prod (sampleLaw d T)) + +def FiniteKernelLearner.uniformFixedSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × Samples d T, + K.jointExperimentLaw (fun i => (z.2 i,⟪z.1.val,z.2 i⟫)) + {r | r.1.1 = t ∧ angularError z.1 r.2 ≤ ε} ∂((uniformSphere d).prod (sampleLaw d T)) + +end + +section + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] [Nontrivial E] + +variable {d M T : ℕ} {Ω : Type u} + +def Learner.uniformFixedSuccess [MeasurableSpace Ω] (L : Learner d M T Ω) (ρ : Measure Ω) + (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + {z | (L.terminal z.1 z.2.1 z.2.2).1 = t ∧ angularError z.1 (L.estimate z.1 z.2.1 z.2.2) ≤ ε} + +end + +section + +variable {d M T : ℕ} + +def FiniteKernelLearner.seededSuccess {Ξ : Type u} [MeasurableSpace Ξ] + (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ ξ, (K ξ).uniformSuccess ε ∂ρ + +def FiniteKernelLearner.seededFixedSuccess {Ξ : Type u} [MeasurableSpace Ξ] + (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) (t : ℕ) : ℝ≥0∞ := + ∫⁻ ξ, (K ξ).uniformFixedSuccess ε t ∂ρ + +def FiniteKernelLearner.FixedQuadraticMemory : Prop := + ∀ A₀ : ℝ, 0 < A₀ → ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, + ∀ d : ℕ, d₀ ≤ d → ∀ M T : ℕ, (M : ℝ) ≤ A₀ * (d : ℝ)^2 → + ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + (2/3 : ℝ≥0∞) ≤ seededSuccess K ρ ε → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ) + +end + +open MeasureTheory ProbabilityTheory Set Filter + +open scoped ENNReal NNReal RealInnerProductSpace + +variable {d M T : ℕ} {Ξ : Type u} [MeasurableSpace Ξ] + +def FiniteKernelLearner.conditionalSuccess (K : FiniteKernelLearner d M T) (ε : ℝ) + (s : UnitSphere d) (x : Samples d T) : ℝ≥0∞ := + K.jointExperimentLaw (fun i => (x i,⟪s.val,x i⟫)) {r | Learner.angularError s r.2 ≤ ε} + +def FiniteKernelLearner.seededPointwiseSuccess (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) + (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + ∫⁻ z : Ξ × Samples d T, (K z.1).conditionalSuccess ε s z.2 ∂ρ.prod (sampleLaw d T) + +def FiniteKernelLearner.JointSuccessMeasurable (K : Ξ → FiniteKernelLearner d M T) (ρ : Measure Ξ) (ε : ℝ) : Prop := + AEMeasurable (fun z : UnitSphere d × (Ξ × Samples d T) => + (K z.2.1).conditionalSuccess ε z.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def FiniteKernelLearner.SubquadraticMemoryWithPointwise : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ((2/3 : ℝ≥0∞) ≤ seededSuccess K ρ ε ∨ + (JointSuccessMeasurable K ρ ε ∧ ∀ s, (2/3 : ℝ≥0∞) ≤ seededPointwiseSuccess K ρ ε s)) → + c*(d:ℝ)*Real.log (1/ε) ≤ (T:ℝ) + +end NoiselessRegression + +namespace ProjectionMoments + +open NoiselessRegression NoiselessRegression.FiniteKernelLearner + +section + +section GaussianGraph + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def vectorSmoothing (ν : Measure E) (m : ℕ) (φ : (Fin m → ℝ) → ℝ≥0∞) + (z : (Fin m → E) × (Fin m → ℝ)) : ℝ≥0∞ := + ∫⁻ t, φ (fun j => z.2 j - ⟪t, z.1 j⟫) ∂ν + +abbrev Label (m : ℕ) := EuclideanSpace ℝ (Fin m) + +def ballKernel (m : ℕ) (η : ℝ) (y : Fin m → ℝ) : ℝ≥0∞ := + (Metric.closedBall (0 : Label m) η).indicator + (fun _ => (volume (Metric.closedBall (0 : Label m) η))⁻¹) (WithLp.toLp 2 y) + +def rowMap {m : ℕ} (A : Fin m → E) : E →L[ℝ] Label m := + (PiLp.continuousLinearEquiv 2 ℝ (fun _ : Fin m => ℝ)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun j => innerSL ℝ (A j))) + +def ballAverage (ν : Measure E) (m : ℕ) (η : ℝ) + (z : (Fin m → E) × Label m) : ℝ≥0∞ := + vectorSmoothing ν m (ballKernel m η) (z.1, WithLp.ofLp z.2) + +def lowerDensity (ν : Measure E) (m : ℕ) (z : (Fin m → E) × Label m) : ℝ≥0∞ := + liminf (fun n : ℕ => ballAverage ν m ((n : ℝ) + 1)⁻¹ z) atTop + +def AllBallMass (ν : Measure E) (K a : ℝ) : Prop := + ∀ b : E, ∀ t : ℝ, 0 < t → ν (Metric.closedBall b t) ≤ ENNReal.ofReal (K * t ^ a) + +end GaussianGraph + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +section Rotations + +variable (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + +abbrev Rotation := unitary (E →L[ℝ] E) + +instance rotationMeasurableSpace : MeasurableSpace (Rotation E) := borel (Rotation E) + +instance rotationBorelSpace : BorelSpace (Rotation E) := ⟨rfl⟩ + +instance rotationCompact : CompactSpace (Rotation E) := by + apply isCompact_iff_compactSpace.mp + apply Metric.isCompact_of_isClosed_isBounded isClosed_unitary + apply (Metric.isBounded_closedBall (x := (0 : E →L[ℝ] E)) (r := 1)).subset (s := (unitary (E →L[ℝ] E) : Set (E →L[ℝ] E))) + intro U hU + rw [Metric.mem_closedBall, dist_zero_right] + by_cases h : Subsingleton E + · have := h + simp + · have : Nontrivial E := not_subsingleton_iff_nontrivial.mp h + exact (CStarRing.norm_of_mem_unitary hU).le + +def rotationLaw : Measure (Rotation E) := + ((Measure.haar : Measure (Rotation E)) Set.univ)⁻¹ • Measure.haar + +variable {E} + +variable [MeasurableSpace E] [BorelSpace E] + +def rotateRows {ι : Type*} (O : Rotation E) (v : ι → E) : ι → E := + fun i => (O : E →L[ℝ] E) (v i) + +end Rotations + +section Triangular + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] + [MeasurableSpace E] [BorelSpace E] + +def coordinateMap {m : ℕ} (A : Fin m → E) : E →ₗ[ℝ] (Fin m → ℝ) := + (WithLp.linearEquiv 2 ℝ (Fin m → ℝ)) ∘ₗ (rowMap A).toLinearMap + +def coordinateDensity (ν : Measure E) (m : ℕ) (z : (Fin m → E) × (Fin m → ℝ)) : ℝ≥0∞ := + lowerDensity ν m (z.1, WithLp.toLp 2 z.2) + +def frameLaw {m : ℕ} (u : Fin m → E) : Measure (Fin m → E) := + (rotationLaw E).map (fun O => rotateRows O u) + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def rieszKernel (α : ℝ) (z s : E) : ℝ≥0∞ := (ENNReal.ofReal ‖s-z‖)^(-α) + +def rieszPotential (α : ℝ) (h : E → ℝ≥0∞) : ℝ≥0∞ := + ⨆ z : E, ∫⁻ s, h s*rieszKernel α z s ∂NoiselessRegression.ambientSphereLaw + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace Matrix + +open scoped ENNReal NNReal RealInnerProductSpace Topology MatrixOrder Matrix.Norms.L2Operator + +def mixRows {k : ℕ} (M : Matrix (Fin k) (Fin k) ℝ) (X : Fin k → E) : Fin k → E := + fun i => ∑ j, M i j • X j + +def polarRadial {k : ℕ} (X : Fin k → E) : Matrix (Fin k) (Fin k) ℝ := + CFC.sqrt (Matrix.gram ℝ X) + +def rawPolarRows {k : ℕ} (X : Fin k → E) : Fin k → E := + mixRows (polarRadial X)⁻¹ X + +def polarRows {k : ℕ} (u X : Fin k → E) : Fin k → E := by + classical + exact if LinearIndependent ℝ X then rawPolarRows X else u + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def unitBallVolume (k : ℕ) : ℝ≥0∞ := (volume : Measure (Label k)) (Metric.closedBall 0 1) + +def unitBallLaw (k : ℕ) : Measure (Label k) := + (unitBallVolume k)⁻¹ • volume.restrict (Metric.closedBall 0 1) + +def normalizedDensity (ν : Measure E) (k : ℕ) (u : Fin k → E) + (z : (Fin k → E) × Label k) : ℝ≥0∞ := + unitBallVolume k * lowerDensity ν k (polarRows u z.1,z.2) + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +def sphereWeightedRestriction (h : E → ℝ≥0∞) (H : Set E) : Measure E := + (NoiselessRegression.ambientSphereLaw.withDensity h).restrict H + +end Triangular + +section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +variable {E : Type u} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def capMeasure (c : E) (r : ℝ) : Measure E := + (NoiselessRegression.ambientSphereLaw (Metric.closedBall c r))⁻¹ • + NoiselessRegression.ambientSphereLaw.restrict (Metric.closedBall c r) + +structure CapDictionary (c : E) (r α : ℝ) where + I : Type u + countable : Countable I + center : I → E + radius : I → ℝ + center_norm : ∀ i, ‖center i‖ = 1 + radius_pos : ∀ i, 0 < radius i + radius_le : ∀ i, radius i ≤ r + parent : I + parent_center : center parent = c + parent_radius : radius parent = r + proper : ∀ R : ℝ, {i | (r/radius i)^α ≤ R}.Finite + cover : ∀ (s : E), ‖s‖ = 1 → ∀ t : ℝ, 0 < t → t ≤ 1/4 → + ∃ i, 4*r*t ≤ radius i ∧ radius i < 8*r*t ∧ dist s (center i) ≤ radius i/2 + +end + +section + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace Matrix + +open scoped ENNReal NNReal RealInnerProductSpace Topology + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def radialLabel {k : ℕ} (X : Fin k → E) (y : Label k) : Label k := + WithLp.toLp 2 (polarRadial X *ᵥ y.ofLp) + +def capKernelValue {k : ℕ} (K : (Fin k → E) × Label k → ℝ≥0∞) (s : E) : ℝ≥0∞ := + ∫⁻ X, K (X,rowMap X s) ∂Measure.pi (fun _ => stdGaussian E) + +def capReferenceLabel {k : ℕ} (c : E) (r : ℝ) (X : Fin k → E) (z : Label k) : Label k := + rowMap X c + r • radialLabel X z + +def capReference {k : ℕ} (K : (Fin k → E) × Label k → ℝ≥0∞) (c : E) (r : ℝ) : ℝ≥0∞ := + ∫⁻ X, ∫⁻ z, K (X,capReferenceLabel c r X z) ∂unitBallLaw k ∂Measure.pi (fun _ => stdGaussian E) + +end + +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def fractionalBlock {J : Type*} [Fintype J] {k : ℕ} + (Q : J → (Fin k → E) × Label k → ℝ≥0∞) (f : J → E → ℝ≥0∞) (s : E) : ℝ≥0∞ := + ∫⁻ X, ∑ j, Q j (X,rowMap X s)*f j s ∂Measure.pi (fun _ => stdGaussian E) + +end + +def IntegratedFrameMoment : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ (d k q : ℕ) (β K R : ℝ) + (ν : Measure (EuclideanSpace ℝ (Fin d))) [IsFiniteMeasure ν] + (z : EuclideanSpace ℝ (Fin d)) (u : Fin k → EuclideanSpace ℝ (Fin d)), + 1 ≤ k → 2 ≤ q → k+q ≤ d → 0 < β → β ≤ d → + 1 ≤ β-k-((q:ℝ)-2) → 0 ≤ K → 0 < R → + ν.support ⊆ Metric.closedBall z R → AllBallMass ν K β → + Orthonormal ℝ u → + (∀ᵐ A ∂frameLaw u, ν.map (coordinateMap A) ≪ (volume : Measure (Fin k → ℝ))) → + Measurable (coordinateDensity ν k) ∧ + (∀ᵐ A ∂frameLaw u, + (volume : Measure (Fin k → ℝ)).withDensity (fun y => coordinateDensity ν k (A,y)) = + ν.map (coordinateMap A)) ∧ + (∀ (A : Fin k → EuclideanSpace ℝ (Fin d)), Orthonormal ℝ A → + ∀ y : Fin k → ℝ, + R < ‖WithLp.toLp 2 (y-coordinateMap A z)‖ → coordinateDensity ν k (A,y) = 0) ∧ + (∫⁻ A, ∫⁻ y : Fin k → ℝ, coordinateDensity ν k (A,y)^q ∂volume ∂frameLaw u) ^ (1/(q:ℝ)) ≤ + ENNReal.ofReal (C^d * (C*Real.sqrt d)^((k:ℝ)*(1-1/(q:ℝ))) * + K * R^(β-(k:ℝ)*(1-1/(q:ℝ)))) + +def NormalizedUnitBallMoment : Prop := + ∀ D : ℝ, 0 < D → + ∃ C_D : ℝ, 0 < C_D ∧ ∀ d : ℕ, 32 ≤ d → + let k := d/16 + let lam : ℝ := ((d:ℝ)-1)/2 + ∀ (ν : Measure (EuclideanSpace ℝ (Fin d))) [IsFiniteMeasure ν] + (u : Fin k → EuclideanSpace ℝ (Fin d)), + ν Set.univ ≤ 1 → ν.support ⊆ Metric.closedBall 0 1 → + AllBallMass ν (D^d) lam → Orthonormal ℝ u → + (∀ᵐ X ∂Measure.pi (fun _ : Fin k => stdGaussian (EuclideanSpace ℝ (Fin d))), + ν.map (rowMap (polarRows u X)) ≪ (volume : Measure (Label k))) → + Measurable (normalizedDensity ν k u) ∧ + (∀ᵐ X ∂Measure.pi (fun _ : Fin k => stdGaussian (EuclideanSpace ℝ (Fin d))), + ((unitBallVolume k)⁻¹ • (volume : Measure (Label k))).withDensity + (fun y => normalizedDensity ν k u (X,y)) = ν.map (rowMap (polarRows u X))) ∧ + (∀ X y, 1 < ‖y‖ → normalizedDensity ν k u (X,y) = 0) ∧ + (∫⁻ X, ∫⁻ y, normalizedDensity ν k u (X,y)^k ∂unitBallLaw k + ∂Measure.pi (fun _ => stdGaussian (EuclideanSpace ℝ (Fin d)))) ≤ + ENNReal.ofReal (Real.exp (C_D*d*k)) + +def AllRadiiSphereMoment : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/4 + let β : ℝ := (d:ℝ)-1-k + ∀ f : EuclideanSpace ℝ (Fin d) → ℝ≥0∞, + Measurable f → (∀ s, f s ≤ 1) → + ∀ K : ℝ, 0 ≤ K → + AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity f) K β → + ∀ z : EuclideanSpace ℝ (Fin d), ∀ R : ℝ, 0 < R → + ∀ u : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ u → + let μ := sphereWeightedRestriction f (Metric.closedBall z R) + Measurable (coordinateDensity μ k) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ A → + (volume : Measure (Fin k → ℝ)).withDensity (fun y => coordinateDensity μ k (A,y)) = + μ.map (coordinateMap A)) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), Orthonormal ℝ A → + ∀ y : Fin k → ℝ, R < ‖WithLp.toLp 2 (y-coordinateMap A z)‖ → + coordinateDensity μ k (A,y) = 0) ∧ + (∫⁻ A, ∫⁻ y : Fin k → ℝ, coordinateDensity μ k (A,y)^k ∂volume ∂frameLaw u) ^ (1/(k:ℝ)) ≤ + ENNReal.ofReal (C^d*(C*Real.sqrt d)^((k:ℝ)*(1-1/(k:ℝ)))* + K*R^(β-(k:ℝ)*(1-1/(k:ℝ)))) + +def PositiveCapDomination : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d : ℕ, 32 ≤ d → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + ∀ (c : EuclideanSpace ℝ (Fin d)), ‖c‖ = 1 → + ∀ r : ℝ, 0 < r → r ≤ 2 → ∀ N : ℕ, + ∀ K : Fin N → (Fin k → EuclideanSpace ℝ (Fin d)) × Label k → ℝ≥0∞, + (∀ j, Measurable (K j)) → (∀ z, ∑ j, K j z ≤ 1) → + (∑ j, capReference (K j) c r) ≤ 1 ∧ + ∀ j, ∃ D : CapDictionary c r α, ∃ a : D.I → ℝ, + (∀ i, 0 ≤ a i) ∧ Summable (fun i => a i*(r/D.radius i)^α) ∧ + (∑' i, a i*(r/D.radius i)^α) ≤ Real.exp (C*d)*(capReference (K j) c r).toReal^(1-1/(k:ℝ)) ∧ + (capMeasure c r).withDensity (capKernelValue (K j)) ≤ + Measure.sum (fun i => ENNReal.ofReal (a i) • capMeasure (D.center i) (D.radius i)) ∧ + (Measure.sum (fun i => ENNReal.ofReal (a i) • capMeasure (D.center i) (D.radius i))) Set.univ < ∞ + +def DeterministicOffsetDensity : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/8 + let α : ℝ := (d:ℝ)/2 + ∀ h : EuclideanSpace ℝ (Fin d) → ℝ≥0∞, Measurable h → (∀ s, h s ≤ 1) → + ∀ z : EuclideanSpace ℝ (Fin d), ∀ ρ : ℝ, 0 < ρ → + ∀ H : Set (EuclideanSpace ℝ (Fin d)), MeasurableSet H → H ⊆ Metric.closedBall z ρ → + rieszPotential α h < ∞ ∧ + Measurable (lowerDensity (sphereWeightedRestriction h H) k) ∧ + (∀ A : Fin k → EuclideanSpace ℝ (Fin d), LinearIndependent ℝ A → + volume.withDensity (fun y => lowerDensity (sphereWeightedRestriction h H) k (A,y)) = + (sphereWeightedRestriction h H).map (rowMap A)) ∧ + (∀ b : Label k, (∫⁻ A, (lowerDensity (sphereWeightedRestriction h H) k (A,rowMap A z+b))^k + ∂Measure.pi (fun _ => stdGaussian (EuclideanSpace ℝ (Fin d))))^(1/(k:ℝ)) ≤ + ENNReal.ofReal (C^d) * rieszPotential α h * ENNReal.ofReal (ρ^(α-k))) ∧ + (∀ A y, ‖rowMap A‖*ρ < ‖y-rowMap A z‖ → + lowerDensity (sphereWeightedRestriction h H) k (A,y) = 0) + +def AllRadiiBlockBound : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d : ℕ, 16 ≤ d → + let k := d/4 + let β : ℝ := (d:ℝ)-1-k + ∀ N : ℕ, ∀ f : Fin N → EuclideanSpace ℝ (Fin d) → ℝ≥0∞, + (∀ j, Measurable (f j)) → (∀ j s, f j s ≤ 1) → + ∀ K : ℝ, 0 ≤ K → + (∀ j, AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity (f j)) K β) → + ∀ Q : Fin N → (Fin k → EuclideanSpace ℝ (Fin d)) × Label k → ℝ≥0∞, + (∀ j, Measurable (Q j)) → (∀ z, ∑ j, Q j z ≤ 1) → + AllBallMass (NoiselessRegression.ambientSphereLaw.withDensity (fractionalBlock Q f)) + (C^d*(N:ℝ)^(1/(k:ℝ))*K) β + +def HaarStreamingCost : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let k := d/4 + let Nstar : ℝ := ((k:ℝ)+2)*2^M + seededSuccess K ρ ε ≤ ENNReal.ofReal + (C^d*ε^k*(C^d*Nstar^(1/(k:ℝ)))^((T+k-1)/k)) + +def RieszStreamingCost : Prop := + ∃ C₀ : ℝ, 1 ≤ C₀ ∧ ∀ d M T : ℕ, 16 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let q := d/8 + let W : ℝ := ((T:ℝ)+2)*2^M + seededSuccess K ρ ε ≤ ENNReal.ofReal + (C₀^d*ε^((d:ℝ)/2-1)*(1+C₀^d*(1+Real.log (1/ε))*W^(1/(q:ℝ)))^((T+q-1)/q)) + +def CapFixedStoppingCost : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d M T : ℕ, 32 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ∀ t : ℕ, t ≤ T → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededFixedSuccess K ρ ε t ≤ ENNReal.ofReal + (Real.exp (C*d)*(ε/2)^α*(Real.exp (C*d)*(2:ℝ)^((M:ℝ)/k))^((t+k-1)/k)) + +def CapTotalStoppingCost : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ d M T : ℕ, 32 ≤ d → ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d M T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededSuccess K ρ ε ≤ ENNReal.ofReal + (((T:ℝ)+1)*Real.exp (C*d)*(ε/2)^α* + (Real.exp (C*d)*(2:ℝ)^((M:ℝ)/k))^((T+k-1)/k)) + +def CapFixedStoppingAsymptotic : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d:ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + ∀ t : ℕ, t ≤ T → + let k := d/16 + let α : ℝ := ((d:ℝ)-1)/2 + seededFixedSuccess K ρ ε t ≤ ENNReal.ofReal + (Real.exp (C*d*(1+((t+k-1)/k:ℕ)))*(ε/2)^α) + +def CapTotalStoppingAsymptotic : Prop := + ∃ C₁ C₂ : ℝ, 0 < C₁ ∧ 0 < C₂ ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d:ℝ)) (fun d => (d:ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ξ : Type u) [MeasurableSpace Ξ] (ρ : Measure Ξ), IsProbabilityMeasure ρ → + ∀ K : Ξ → FiniteKernelLearner d (M d) T, (∀ᵐ ξ ∂ρ, (K ξ).CompletedRules) → + seededSuccess K ρ ε ≤ ENNReal.ofReal + (((T:ℝ)+1)*Real.exp (C₁*d+C₂*T-(d:ℝ)*Real.log (1/ε)/3)) + +def KernelModelBridge : Prop := + ∀ d M T : ℕ, 3 ≤ d → ∀ K : FiniteKernelLearner d M T, K.CompletedRules → + ∃ (ρ : Measure (Tape M T)) (L : Learner d M T (Tape M T)), + IsProbabilityMeasure ρ ∧ L.MeasurableRules ∧ L.Admissible ρ ∧ + (∀ ε, L.uniformSuccess ρ ε = K.uniformSuccess ε) ∧ + (∀ ε t, L.uniformFixedSuccess ρ ε t = K.uniformFixedSuccess ε t) + +def MainStatement : Prop := + IntegratedFrameMoment ∧ NormalizedUnitBallMoment ∧ AllRadiiSphereMoment ∧ + PositiveCapDomination ∧ DeterministicOffsetDensity ∧ AllRadiiBlockBound ∧ + HaarStreamingCost.{u} ∧ RieszStreamingCost.{u} ∧ CapFixedStoppingCost.{u} ∧ + CapTotalStoppingCost.{u} ∧ CapFixedStoppingAsymptotic.{u} ∧ + CapTotalStoppingAsymptotic.{u} ∧ KernelModelBridge ∧ + NoiselessRegression.FiniteKernelLearner.SubquadraticMemoryWithPointwise.{u} ∧ + NoiselessRegression.FiniteKernelLearner.FixedQuadraticMemory.{u} + +open MeasureTheory ProbabilityTheory Set Filter InnerProductSpace +open scoped ENNReal NNReal RealInnerProductSpace Topology + +theorem main : MainStatement.{u} := by + sorry + +end ProjectionMoments + +end + +end OAI diff --git a/tasks/projection-moments/tests/grade.py b/tasks/projection-moments/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/projection-moments/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/projection-moments/tests/task.json b/tasks/projection-moments/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8f4154a7546b9e2d84812c83f8fc6a475ace4d95 --- /dev/null +++ b/tasks/projection-moments/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ProjectionMoments", + "comparator": { + "theorem_names": [ + "OAI.ProjectionMoments.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11263 +} \ No newline at end of file diff --git a/tasks/projection-moments/tests/test.sh b/tasks/projection-moments/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/projection-moments/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/projection-volume/environment/Dockerfile b/tasks/projection-volume/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/projection-volume/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/projection-volume/environment/fetch_mathlib.sh b/tasks/projection-volume/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/projection-volume/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/projection-volume/environment/lake-manifest.json b/tasks/projection-volume/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/projection-volume/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/projection-volume/environment/lakefile.lean b/tasks/projection-volume/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/projection-volume/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/projection-volume/environment/lean_setup.sh b/tasks/projection-volume/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/projection-volume/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/projection-volume/environment/pack_submission.py b/tasks/projection-volume/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/projection-volume/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/projection-volume/instruction.md b/tasks/projection-volume/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..0385ce73cd644afbce051a6b5b20708688649daa --- /dev/null +++ b/tasks/projection-volume/instruction.md @@ -0,0 +1,112 @@ +# openai/math challenge `ProjectionVolume` (family 088) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 088 of the release, *Petty's projection-volume conjecture and simplex counterexamples* +(Convex and metric geometry). The family as a whole: Proves Petty's projection-volume conjecture in the remaining dimensions $n\ge4$: ellipsoids uniquely minimize projection-body volume at fixed body volume. Also establishes the full Lutwak–Petty projection inequalities. In contrast, products of simplices exceed Brannen's proposed simplex maximum for normalized projection-body volume by an exponential factor in every sufficiently large dimension. + +The challenge is `ProjectionVolume`, also at `/opt/openai-math/challenges/ProjectionVolume.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace Pointwise + +namespace Paper092 + +noncomputable def simplexConstant (d : ℕ) : ℝ := + (d + 1) * (d : ℝ) ^ d / d.factorial + +abbrev Euclidean (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def normalHyperplane {n : ℕ} (u : Euclidean n) : Submodule ℝ (Euclidean n) := + (Submodule.span ℝ ({u} : Set (Euclidean n)))ᗮ + +def projectionVolume {n : ℕ} (K : Set (Euclidean n)) (u : Euclidean n) : ENNReal := + (volume : Measure (normalHyperplane u)) + ((normalHyperplane u).orthogonalProjectionOnto '' K) + +def brightness {n : ℕ} (K : Set (Euclidean n)) (u : Euclidean n) : ℝ := + ‖u‖ * (projectionVolume K u).toReal + +def projectionBody {n : ℕ} (K : Set (Euclidean n)) : Set (Euclidean n) := + {y | ∀ u, ⟪u, y⟫ ≤ brightness K u} + +def normalizedProjectionVolume {n : ℕ} (K : Set (Euclidean n)) : ℝ := + (volume (projectionBody K)).toReal / (volume K).toReal ^ (n - 1) + +def standardSimplex (n : ℕ) : Set (Euclidean n) := + convexHull ℝ (insert 0 (Set.range fun i : Fin n => EuclideanSpace.single i (1 : ℝ))) + +def firstBlock (x : Euclidean 20) : Euclidean 10 := + WithLp.toLp 2 (fun i : Fin 10 => x (Fin.castAdd 10 i)) + +def secondBlock (x : Euclidean 20) : Euclidean 10 := + WithLp.toLp 2 (fun i : Fin 10 => x (Fin.natAdd 10 i)) + +def productWitness : Set (Euclidean 20) := + {x | firstBlock x ∈ standardSimplex 10 ∧ secondBlock x ∈ standardSimplex 10} + +theorem product_counterexample : + (IsCompact productWitness ∧ Convex ℝ productWitness ∧ + (interior productWitness).Nonempty) ∧ + normalizedProjectionVolume productWitness / simplexConstant 20 = + (121 * (Nat.choose 20 10 : ℝ)) / (21 * (2 : ℝ) ^ 20) ∧ + normalizedProjectionVolume productWitness / simplexConstant 20 = + (22355476 : ℝ) / 22020096 ∧ + 1 < normalizedProjectionVolume productWitness / simplexConstant 20 ∧ + (volume (projectionBody productWitness)).toReal > + simplexConstant 20 * (volume productWitness).toReal ^ 19 := by + sorry + +end Paper092 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ProjectionVolume.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Paper092.product_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/projection-volume/solution/closure.txt b/tasks/projection-volume/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..46fdd75f7ebf2f28fb5ee2cbb507ae1d11489c67 --- /dev/null +++ b/tasks/projection-volume/solution/closure.txt @@ -0,0 +1,29 @@ +OAI.Geometry.ProjectionVolume.Arithmetic +OAI.Geometry.ProjectionVolume.Basic +OAI.Geometry.ProjectionVolume.Brightness +OAI.Geometry.ProjectionVolume.EuclideanVolume +OAI.Geometry.ProjectionVolume.Extrusion +OAI.Geometry.ProjectionVolume.FacetAreas +OAI.Geometry.ProjectionVolume.Model +OAI.Geometry.ProjectionVolume.ProductBrightness +OAI.Geometry.ProjectionVolume.ProductCoefficients +OAI.Geometry.ProjectionVolume.ProductCounterexample +OAI.Geometry.ProjectionVolume.ProductFacetAreaValues +OAI.Geometry.ProjectionVolume.ProductFacetAreas +OAI.Geometry.ProjectionVolume.ProductFacetGeometry +OAI.Geometry.ProjectionVolume.ProductNormals +OAI.Geometry.ProjectionVolume.ProductProjection +OAI.Geometry.ProjectionVolume.ProductVolume +OAI.Geometry.ProjectionVolume.ProductVolumeGeneral +OAI.Geometry.ProjectionVolume.ProductZonotope +OAI.Geometry.ProjectionVolume.ProjectionCoefficients +OAI.Geometry.ProjectionVolume.ProjectionJacobian +OAI.Geometry.ProjectionVolume.ProjectionReconstruction +OAI.Geometry.ProjectionVolume.SimplexCoordinates +OAI.Geometry.ProjectionVolume.SimplexGeometry +OAI.Geometry.ProjectionVolume.SimplexNormals +OAI.Geometry.ProjectionVolume.SimplexProjection +OAI.Geometry.ProjectionVolume.SimplexVolume +OAI.Geometry.ProjectionVolume.SimplexZonotope +OAI.Geometry.ProjectionVolume.SupportGeometry +OAI.Geometry.ProjectionVolume.Translation diff --git a/tasks/projection-volume/solution/reference.py b/tasks/projection-volume/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/projection-volume/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/projection-volume/solution/solve.sh b/tasks/projection-volume/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..961d3c35c12324dc81c2bf4dd5c06f691e9ea041 --- /dev/null +++ b/tasks/projection-volume/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ProjectionVolume, i.e. module OAI.Geometry.ProjectionVolume.ProductCounterexample and the +# 29 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.ProjectionVolume.ProductCounterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ProjectionVolume" diff --git a/tasks/projection-volume/task.toml b/tasks/projection-volume/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9ef942931c88920cc6e99acc22bc5f485a5382ea --- /dev/null +++ b/tasks/projection-volume/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/projection-volume" +version = "1.0.0" +description = "Prove ProjectionVolume (openai/math family 088: Petty's projection-volume conjecture and simplex counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ProjectionVolume.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ProjectionVolume" +family = "088" +family_title = "Petty's projection-volume conjecture and simplex counterexamples" +subject = "Convex and metric geometry" +theorems = ["OAI.Paper092.product_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.ProjectionVolume.ProductCounterexample" +reference_modules = 29 +reference_lean_bytes = 128826 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 601 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11815 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/projection-volume/tests/Challenge.lean b/tasks/projection-volume/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ceba0e72f227c9ce3ca10d617f034794bc8d5f34 --- /dev/null +++ b/tasks/projection-volume/tests/Challenge.lean @@ -0,0 +1,61 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped RealInnerProductSpace Pointwise + +namespace Paper092 + +noncomputable def simplexConstant (d : ℕ) : ℝ := + (d + 1) * (d : ℝ) ^ d / d.factorial + +abbrev Euclidean (n : ℕ) := EuclideanSpace ℝ (Fin n) + +def normalHyperplane {n : ℕ} (u : Euclidean n) : Submodule ℝ (Euclidean n) := + (Submodule.span ℝ ({u} : Set (Euclidean n)))ᗮ + +def projectionVolume {n : ℕ} (K : Set (Euclidean n)) (u : Euclidean n) : ENNReal := + (volume : Measure (normalHyperplane u)) + ((normalHyperplane u).orthogonalProjectionOnto '' K) + +def brightness {n : ℕ} (K : Set (Euclidean n)) (u : Euclidean n) : ℝ := + ‖u‖ * (projectionVolume K u).toReal + +def projectionBody {n : ℕ} (K : Set (Euclidean n)) : Set (Euclidean n) := + {y | ∀ u, ⟪u, y⟫ ≤ brightness K u} + +def normalizedProjectionVolume {n : ℕ} (K : Set (Euclidean n)) : ℝ := + (volume (projectionBody K)).toReal / (volume K).toReal ^ (n - 1) + +def standardSimplex (n : ℕ) : Set (Euclidean n) := + convexHull ℝ (insert 0 (Set.range fun i : Fin n => EuclideanSpace.single i (1 : ℝ))) + +def firstBlock (x : Euclidean 20) : Euclidean 10 := + WithLp.toLp 2 (fun i : Fin 10 => x (Fin.castAdd 10 i)) + +def secondBlock (x : Euclidean 20) : Euclidean 10 := + WithLp.toLp 2 (fun i : Fin 10 => x (Fin.natAdd 10 i)) + +def productWitness : Set (Euclidean 20) := + {x | firstBlock x ∈ standardSimplex 10 ∧ secondBlock x ∈ standardSimplex 10} + +theorem product_counterexample : + (IsCompact productWitness ∧ Convex ℝ productWitness ∧ + (interior productWitness).Nonempty) ∧ + normalizedProjectionVolume productWitness / simplexConstant 20 = + (121 * (Nat.choose 20 10 : ℝ)) / (21 * (2 : ℝ) ^ 20) ∧ + normalizedProjectionVolume productWitness / simplexConstant 20 = + (22355476 : ℝ) / 22020096 ∧ + 1 < normalizedProjectionVolume productWitness / simplexConstant 20 ∧ + (volume (projectionBody productWitness)).toReal > + simplexConstant 20 * (volume productWitness).toReal ^ 19 := by + sorry + +end Paper092 + +end + +end OAI diff --git a/tasks/projection-volume/tests/grade.py b/tasks/projection-volume/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/projection-volume/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/projection-volume/tests/task.json b/tasks/projection-volume/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5200e7ef3d00182c846f82e2c4692f01a8c3e8d0 --- /dev/null +++ b/tasks/projection-volume/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ProjectionVolume", + "comparator": { + "theorem_names": [ + "OAI.Paper092.product_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10915 +} \ No newline at end of file diff --git a/tasks/projection-volume/tests/test.sh b/tasks/projection-volume/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/projection-volume/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/qac-parity/environment/Dockerfile b/tasks/qac-parity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/qac-parity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/qac-parity/environment/fetch_mathlib.sh b/tasks/qac-parity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/qac-parity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/qac-parity/environment/lake-manifest.json b/tasks/qac-parity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/qac-parity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/qac-parity/environment/lakefile.lean b/tasks/qac-parity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/qac-parity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/qac-parity/environment/lean_setup.sh b/tasks/qac-parity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/qac-parity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/qac-parity/environment/pack_submission.py b/tasks/qac-parity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/qac-parity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/qac-parity/instruction.md b/tasks/qac-parity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ff440d05b5105f81279dedb97bb593e16bcc5faf --- /dev/null +++ b/tasks/qac-parity/instruction.md @@ -0,0 +1,127 @@ +# openai/math challenge `QACParity` (family 274) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 274 of the release, *Moore's parity conjecture for $\mathrm{QAC}^0$* +(Mathematical physics). The family as a whole: Resolves Moore's parity conjecture in the measured-output model: constant-depth quantum circuits with arbitrary one-qubit gates, unbounded-arity Toffoli gates and polynomially many total qubits cannot compute parity with any fixed positive worst-case advantage. Ancillas start in zero, one output qubit is measured, and all other registers may be discarded. Xu–Li's reductions give the same bounded-error obstruction for strict majority. + +The challenge is `QACParity`, also at `/opt/openai-math/challenges/QACParity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator + +namespace QAC + +abbrev Bit := Fin 2 +abbrev Word (N : ℕ) := Fin N → Bit +abbrev Operator (N : ℕ) := Matrix (Word N) (Word N) ℂ +abbrev QubitOperator := Matrix Bit Bit ℂ + +/-- Tensor product in the computational basis. -/ +def tensorMatrix {N : ℕ} (a : Fin N → QubitOperator) : Operator N := + fun x y => ∏ i, a i (x i) (y i) + +/-- A one-qubit unitary or an unbounded-arity Toffoli gate. -/ +inductive Gate (N : ℕ) where + | local (q : Fin N) (u : Matrix.unitaryGroup Bit ℂ) + | toffoli (controls : Finset (Fin N)) (target : Fin N) (hne : target ∉ controls) + +namespace Gate + +def support {N : ℕ} : Gate N → Finset (Fin N) + | .local q _ => {q} + | .toffoli c t _ => insert t c + +/-- A Toffoli flips its target iff all controls are one. -/ +def toffoliWord {N : ℕ} (c : Finset (Fin N)) (t : Fin N) (x : Word N) : Word N := + if ∀ i ∈ c, x i = 1 then Function.update x t (1 - x t) else x + +def matrix {N : ℕ} : Gate N → Operator N + | .local q u => tensorMatrix fun i => if i = q then (u : QubitOperator) else 1 + | .toffoli c t _ => fun x y => if x = toffoliWord c t y then 1 else 0 + +end Gate + +structure PhysicalLayer (N : ℕ) where + gates : List (Gate N) + disjoint : gates.Pairwise (fun A B => Disjoint A.support B.support) + +def physicalLayerMatrix {N : ℕ} (L : PhysicalLayer N) : Operator N := + (L.gates.map Gate.matrix).prod + +/-- Chronological order: the rightmost matrix acts first. -/ +def physicalCircuitMatrix {N : ℕ} (layers : List (PhysicalLayer N)) : Operator N := + ((layers.map physicalLayerMatrix).reverse).prod + +/-- The computational-basis input with the remaining qubits initialized to zero. -/ +def inputWord {n N : ℕ} (x : Word n) : Word N := + fun i => if h : i.val < n then x ⟨i.val, h⟩ else 0 + +def parity {n : ℕ} (x : Word n) : Bit := ∑ i, x i + +/-- Born probability, summing all final garbage with no cleanliness assumption. -/ +def successProbability {n N : ℕ} (W : Operator N) (out : Fin N) (x : Word n) : ℝ := + ∑ y : Word N, if y out = parity x then Complex.normSq (W y (inputWord x)) else 0 + +/-- The literal measured-output, polynomial-total-qubit parity lower bound. -/ +def ParityStatement : Prop := + ∀ (d : ℕ) (c ε : ℝ), 1 ≤ c → 0 < ε → ε ≤ 1 / 2 → + ∃ n₀ : ℕ, ∀ n ≥ n₀, ∀ N : ℕ, n ≤ N → (N : ℝ) ≤ (n : ℝ) ^ c → + ∀ layers : List (PhysicalLayer N), layers.length ≤ d → + ∀ out : Fin N, ¬ (∀ x : Word n, + 1 / 2 + ε ≤ successProbability (physicalCircuitMatrix layers) out x) + +end QAC + +theorem QAC.parity_lower_bound : QAC.ParityStatement := by + sorry + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/QACParity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QAC.parity_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/qac-parity/solution/closure.txt b/tasks/qac-parity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b93a3be005e7a2b2c083ef634538e3bbb2e2f2b --- /dev/null +++ b/tasks/qac-parity/solution/closure.txt @@ -0,0 +1,21 @@ +OAI.InformationTheory.QuantumCircuit.Ancilla +OAI.InformationTheory.QuantumCircuit.Asymptotics +OAI.InformationTheory.QuantumCircuit.Backward +OAI.InformationTheory.QuantumCircuit.Basic +OAI.InformationTheory.QuantumCircuit.Circuit +OAI.InformationTheory.QuantumCircuit.Computational +OAI.InformationTheory.QuantumCircuit.Count +OAI.InformationTheory.QuantumCircuit.DepthZero +OAI.InformationTheory.QuantumCircuit.Localization +OAI.InformationTheory.QuantumCircuit.Measurement +OAI.InformationTheory.QuantumCircuit.Model +OAI.InformationTheory.QuantumCircuit.Parity +OAI.InformationTheory.QuantumCircuit.ParityTrace +OAI.InformationTheory.QuantumCircuit.Physical +OAI.InformationTheory.QuantumCircuit.Polynomial +OAI.InformationTheory.QuantumCircuit.ProductProjection +OAI.InformationTheory.QuantumCircuit.Reflection +OAI.InformationTheory.QuantumCircuit.ScaleInduction +OAI.InformationTheory.QuantumCircuit.Spectral +OAI.InformationTheory.QuantumCircuit.Toffoli +OAI.InformationTheory.QuantumCircuit.Transition diff --git a/tasks/qac-parity/solution/reference.py b/tasks/qac-parity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/qac-parity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/qac-parity/solution/solve.sh b/tasks/qac-parity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c925ea1f88ecbe5f9f10287d0827a26fb306466f --- /dev/null +++ b/tasks/qac-parity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of QACParity, i.e. module OAI.InformationTheory.QuantumCircuit.Parity and the +# 21 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.QuantumCircuit.Parity /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of QACParity" diff --git a/tasks/qac-parity/task.toml b/tasks/qac-parity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3bd6b6fa29ceb71e0c07d40199e210f54bd13ade --- /dev/null +++ b/tasks/qac-parity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/qac-parity" +version = "1.0.0" +description = "Prove QACParity (openai/math family 274: Moore's parity conjecture for $\\mathrm{QAC}^0$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/QACParity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "QACParity" +family = "274" +family_title = "Moore's parity conjecture for $\\mathrm{QAC}^0$" +subject = "Mathematical physics" +theorems = ["OAI.QAC.parity_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.QuantumCircuit.Parity" +reference_modules = 21 +reference_lean_bytes = 152586 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 693 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11837 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/qac-parity/tests/Challenge.lean b/tasks/qac-parity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8befca08a4e620cdc873f06efa0780f6955e1778 --- /dev/null +++ b/tasks/qac-parity/tests/Challenge.lean @@ -0,0 +1,76 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator + +namespace QAC + +abbrev Bit := Fin 2 +abbrev Word (N : ℕ) := Fin N → Bit +abbrev Operator (N : ℕ) := Matrix (Word N) (Word N) ℂ +abbrev QubitOperator := Matrix Bit Bit ℂ + +/-- Tensor product in the computational basis. -/ +def tensorMatrix {N : ℕ} (a : Fin N → QubitOperator) : Operator N := + fun x y => ∏ i, a i (x i) (y i) + +/-- A one-qubit unitary or an unbounded-arity Toffoli gate. -/ +inductive Gate (N : ℕ) where + | local (q : Fin N) (u : Matrix.unitaryGroup Bit ℂ) + | toffoli (controls : Finset (Fin N)) (target : Fin N) (hne : target ∉ controls) + +namespace Gate + +def support {N : ℕ} : Gate N → Finset (Fin N) + | .local q _ => {q} + | .toffoli c t _ => insert t c + +/-- A Toffoli flips its target iff all controls are one. -/ +def toffoliWord {N : ℕ} (c : Finset (Fin N)) (t : Fin N) (x : Word N) : Word N := + if ∀ i ∈ c, x i = 1 then Function.update x t (1 - x t) else x + +def matrix {N : ℕ} : Gate N → Operator N + | .local q u => tensorMatrix fun i => if i = q then (u : QubitOperator) else 1 + | .toffoli c t _ => fun x y => if x = toffoliWord c t y then 1 else 0 + +end Gate + +structure PhysicalLayer (N : ℕ) where + gates : List (Gate N) + disjoint : gates.Pairwise (fun A B => Disjoint A.support B.support) + +def physicalLayerMatrix {N : ℕ} (L : PhysicalLayer N) : Operator N := + (L.gates.map Gate.matrix).prod + +/-- Chronological order: the rightmost matrix acts first. -/ +def physicalCircuitMatrix {N : ℕ} (layers : List (PhysicalLayer N)) : Operator N := + ((layers.map physicalLayerMatrix).reverse).prod + +/-- The computational-basis input with the remaining qubits initialized to zero. -/ +def inputWord {n N : ℕ} (x : Word n) : Word N := + fun i => if h : i.val < n then x ⟨i.val, h⟩ else 0 + +def parity {n : ℕ} (x : Word n) : Bit := ∑ i, x i + +/-- Born probability, summing all final garbage with no cleanliness assumption. -/ +def successProbability {n N : ℕ} (W : Operator N) (out : Fin N) (x : Word n) : ℝ := + ∑ y : Word N, if y out = parity x then Complex.normSq (W y (inputWord x)) else 0 + +/-- The literal measured-output, polynomial-total-qubit parity lower bound. -/ +def ParityStatement : Prop := + ∀ (d : ℕ) (c ε : ℝ), 1 ≤ c → 0 < ε → ε ≤ 1 / 2 → + ∃ n₀ : ℕ, ∀ n ≥ n₀, ∀ N : ℕ, n ≤ N → (N : ℝ) ≤ (n : ℝ) ^ c → + ∀ layers : List (PhysicalLayer N), layers.length ≤ d → + ∀ out : Fin N, ¬ (∀ x : Word n, + 1 / 2 + ε ≤ successProbability (physicalCircuitMatrix layers) out x) + +end QAC + +theorem QAC.parity_lower_bound : QAC.ParityStatement := by + sorry + +end + +end OAI diff --git a/tasks/qac-parity/tests/grade.py b/tasks/qac-parity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/qac-parity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/qac-parity/tests/task.json b/tasks/qac-parity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8509237613aaae0a2e39849c8902784648b623c9 --- /dev/null +++ b/tasks/qac-parity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "QACParity", + "comparator": { + "theorem_names": [ + "OAI.QAC.parity_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10937 +} \ No newline at end of file diff --git a/tasks/qac-parity/tests/test.sh b/tasks/qac-parity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/qac-parity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/quadric-bundles/environment/Dockerfile b/tasks/quadric-bundles/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/quadric-bundles/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/quadric-bundles/environment/fetch_mathlib.sh b/tasks/quadric-bundles/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/quadric-bundles/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/quadric-bundles/environment/lake-manifest.json b/tasks/quadric-bundles/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/quadric-bundles/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/quadric-bundles/environment/lakefile.lean b/tasks/quadric-bundles/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/quadric-bundles/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/quadric-bundles/environment/lean_setup.sh b/tasks/quadric-bundles/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/quadric-bundles/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/quadric-bundles/environment/pack_submission.py b/tasks/quadric-bundles/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/quadric-bundles/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/quadric-bundles/instruction.md b/tasks/quadric-bundles/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..48dab160f5b3f2ada8ea4d13834e094a83bec110 --- /dev/null +++ b/tasks/quadric-bundles/instruction.md @@ -0,0 +1,232 @@ +# openai/math challenge `QuadricBundles` (family 050) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 050 of the release, *A counterexample to Griffiths' positivity conjecture* +(Algebraic and complex geometry). The family as a whole: Constructs ample rank-two bundles on $\mathbb P^1\times\mathbb P^1$ with no smooth Hermitian metric of strictly Griffiths-positive curvature, disproving Griffiths' positivity conjecture already on the quadric surface. + +The challenge is `QuadricBundles`, also at `/opt/openai-math/challenges/QuadricBundles.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace QuadricCounterexample + +open Set Filter Topology Metric OnePoint + +open scoped Matrix.Norms.Elementwise ComplexOrder + +abbrev ProjectiveLine := OnePoint ℂ +abbrev QuadricSurface := ProjectiveLine × ProjectiveLine + +def reciprocalP1 (x : ProjectiveLine) : ProjectiveLine := + x.elim (0 : ℂ) (fun z ↦ if z = 0 then ∞ else (z⁻¹ : ℂ)) + +def affineP1 (i : Fin 2) (z : ℂ) : ProjectiveLine := + if i = 0 then reciprocalP1 z else (z : ProjectiveLine) + +def affineQuadric (i : Fin 2 × Fin 2) (z : ℂ × ℂ) : QuadricSurface := + (affineP1 i.1 z.1, affineP1 i.2 z.2) + +def coordP1 (i : Fin 2) (x : ProjectiveLine) : ℂ := + (if i=0 then reciprocalP1 x else x).elim 0 id +def coordQuadric (i : Fin 2 × Fin 2) (x : QuadricSurface) : ℂ × ℂ := + (coordP1 i.1 x.1,coordP1 i.2 x.2) + +def powerP1 (m : ℕ) (x : ProjectiveLine) : ProjectiveLine := + x.elim ∞ (fun z ↦ ((z^m : ℂ) : ProjectiveLine)) +def powerQuadric (m : ℕ) (x : QuadricSurface) : QuadricSurface := + (powerP1 m x.1,powerP1 m x.2) + +abbrev BaseCoordinates := ℂ × ℂ +abbrev FiberCoordinates := Fin 2 → ℂ +abbrev TwoMatrix := Matrix (Fin 2) (Fin 2) ℂ +abbrev BasePolynomial := MvPolynomial (Fin 2) ℂ +def baseEval (p : BasePolynomial) (z : BaseCoordinates) : ℂ := + MvPolynomial.eval ![z.1,z.2] p + +def AlgebraicallyRegularOn (U : Set BaseCoordinates) (f : BaseCoordinates → ℂ) : Prop := + ∀ z ∈ U, ∃ p q : BasePolynomial, baseEval q z ≠ 0 ∧ + ∀ w ∈ U, baseEval q w ≠ 0 → f w=baseEval p w/baseEval q w + +def principalChart (i : Fin 2 × Fin 2) (p : BasePolynomial) : Set QuadricSurface := + {x | x ∈ range (affineQuadric i) ∧ baseEval p (coordQuadric i x) ≠ 0} + +structure AlgebraicRankTwoBundle where + numberOfCharts : ℕ + chart : ℕ → Fin 2 × Fin 2 + equation : ℕ → BasePolynomial + finiteCover : ∀ i, numberOfCharts ≤ i → equation i=0 + covers : ∀ x : QuadricSurface, ∃ i, x ∈ principalChart (chart i) (equation i) + transition : ℕ → ℕ → QuadricSurface → TwoMatrix + transition_self : ∀ i x, x ∈ principalChart (chart i) (equation i) → + transition i i x=1 + transition_mul : ∀ i j k x, + x ∈ principalChart (chart i) (equation i) → + x ∈ principalChart (chart j) (equation j) → + x ∈ principalChart (chart k) (equation k) → + transition i j x * transition j k x=transition i k x + transition_regular : ∀ i j a b, AlgebraicallyRegularOn + {z | baseEval (equation i) z ≠ 0 ∧ + affineQuadric (chart i) z ∈ principalChart (chart j) (equation j)} + (fun z ↦ transition i j (affineQuadric (chart i) z) a b) + +namespace AlgebraicRankTwoBundle + +def domain (V : AlgebraicRankTwoBundle) (i : ℕ) : Set QuadricSurface := + principalChart (V.chart i) (V.equation i) +def coordinateDomain (V : AlgebraicRankTwoBundle) (i : ℕ) : Set BaseCoordinates := + {z | baseEval (V.equation i) z ≠ 0} + +def dualTransition (V : AlgebraicRankTwoBundle) (i j : ℕ) (x : QuadricSurface) : TwoMatrix := + (V.transition j i x).transpose + +end AlgebraicRankTwoBundle + +def hyperplaneTransition (i j : Fin 2) (x : ProjectiveLine) : ℂ := + if i=j then 1 else coordP1 i x +def polarizationTransition (i j : Fin 2 × Fin 2) (x : QuadricSurface) : ℂ := + hyperplaneTransition i.1 j.1 x.1 * hyperplaneTransition i.2 j.2 x.2 + +def IsPowerPullbackTwist (G : AlgebraicRankTwoBundle) (m : ℕ) + (E : AlgebraicRankTwoBundle) : Prop := + E.numberOfCharts=G.numberOfCharts ∧ E.chart=G.chart ∧ + (∀ i, E.equation i = (MvPolynomial.bind₁ fun j ↦ MvPolynomial.X j ^ m) (G.equation i)) ∧ + ∀ i j x, x ∈ E.domain i → x ∈ E.domain j → + E.transition i j x = polarizationTransition (G.chart i) (G.chart j) x • + G.transition i j (powerQuadric m x) + +structure SymmetricSection (V : AlgebraicRankTwoBundle) (n : ℕ) where + coefficient : ℕ → Fin (n+1) → BaseCoordinates → ℂ + regular : ∀ i k, AlgebraicallyRegularOn (V.coordinateDomain i) (coefficient i k) + compatible : ∀ i j x, x ∈ V.domain i → x ∈ V.domain j → ∀ v : FiberCoordinates, + (∑ k : Fin (n+1), coefficient i k (coordQuadric (V.chart i) x) * + ((V.dualTransition i j x).mulVec v 0)^k.val * + ((V.dualTransition i j x).mulVec v 1)^(n-k.val)) = + ∑ k : Fin (n+1), coefficient j k (coordQuadric (V.chart j) x) * v 0^k.val * v 1^(n-k.val) + +def SymmetricSection.value {V : AlgebraicRankTwoBundle} {n : ℕ} + (s : SymmetricSection V n) (i : ℕ) (x : QuadricSurface) (v : FiberCoordinates) : ℂ := + ∑ k : Fin (n+1), s.coefficient i k (coordQuadric (V.chart i) x) * v 0^k.val * v 1^(n-k.val) + +def ProjectiveAlgebraicCone {N : ℕ} (C : Set (Fin N → ℂ)) : Prop := + ∃ equations : Set (MvPolynomial (Fin N) ℂ), + (∀ p ∈ equations, ∃ d : ℕ, p.IsHomogeneous d) ∧ + C = {y | ∀ p ∈ equations, MvPolynomial.eval y p=0} + +def sectionVector {V : AlgebraicRankTwoBundle} {n N : ℕ} + (s : Fin N → SymmetricSection V n) (i : ℕ) (x : QuadricSurface) + (v : FiberCoordinates) : Fin N → ℂ := fun j ↦ (s j).value i x v + +def GivesClosedProjectiveEmbedding {V : AlgebraicRankTwoBundle} {n N : ℕ} + (s : Fin N → SymmetricSection V n) : Prop := + (∀ i x, x ∈ V.domain i → ∀ v : FiberCoordinates, v ≠ 0 → sectionVector s i x v ≠ 0) ∧ + (∀ i j x y, x ∈ V.domain i → y ∈ V.domain j → ∀ v w : FiberCoordinates, + v ≠ 0 → w ≠ 0 → (∃ c : ℂ, c ≠ 0 ∧ sectionVector s i x v = c • sectionVector s j y w) → + x=y ∧ ∃ c : ℂ, c ≠ 0 ∧ v=c • ((V.dualTransition i j x).mulVec w)) ∧ + ProjectiveAlgebraicCone ({0} ∪ {a | ∃ i x, x ∈ V.domain i ∧ + ∃ v : FiberCoordinates, v ≠ 0 ∧ ∃ c : ℂ, c ≠ 0 ∧ a=c • sectionVector s i x v}) ∧ + ∀ i x, x ∈ V.domain i → ∀ v : FiberCoordinates, v ≠ 0 → + ∃ j : Fin N, ∃ b : Fin 2, v b ≠ 0 ∧ sectionVector s i x v j ≠ 0 ∧ + ∃ p q : Fin 3 → MvPolynomial (Fin N) ℂ, + (∀ k, MvPolynomial.eval (fun l ↦ sectionVector s i x v l / sectionVector s i x v j) (q k) ≠ 0) ∧ + ∀ i' x', x' ∈ V.domain i' → ∀ v' : FiberCoordinates, v' ≠ 0 → + sectionVector s i' x' v' j ≠ 0 → + (∀ k, MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (q k) ≠ 0) → + x' ∈ V.domain i ∧ ((V.dualTransition i i' x').mulVec v') b ≠ 0 ∧ + (∀ k : Fin 3, + (![ (coordQuadric (V.chart i) x').1, (coordQuadric (V.chart i) x').2, + ((V.dualTransition i i' x').mulVec v') (1-b) / + ((V.dualTransition i i' x').mulVec v') b ] : Fin 3 → ℂ) k = + MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (p k) / + MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (q k)) + +def IsAmple (V : AlgebraicRankTwoBundle) : Prop := + ∃ n : ℕ, 0 < n ∧ ∃ N : ℕ, ∃ s : Fin N → SymmetricSection V n, + GivesClosedProjectiveEmbedding s + +def holomorphicMetricDerivative (H : BaseCoordinates → TwoMatrix) + (z u : BaseCoordinates) : TwoMatrix := + (1/2 : ℂ) • (fderiv ℝ H z u - Complex.I • fderiv ℝ H z (Complex.I • u)) + +def metricMixedHessian (H : BaseCoordinates → TwoMatrix) + (z u : BaseCoordinates) : TwoMatrix := + (1/4 : ℂ) • ((fderiv ℝ (fun y ↦ fderiv ℝ H y) z u) u + + (fderiv ℝ (fun y ↦ fderiv ℝ H y) z (Complex.I • u)) (Complex.I • u)) + +structure SmoothHermitianMetric (V : AlgebraicRankTwoBundle) where + dualMatrix : ℕ → BaseCoordinates → TwoMatrix + smooth : ∀ i, ContDiffOn ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) (dualMatrix i) (V.coordinateDomain i) + positive : ∀ i z, z ∈ V.coordinateDomain i → (dualMatrix i z).PosDef + compatible : ∀ i j x, x ∈ V.domain i → x ∈ V.domain j → + dualMatrix j (coordQuadric (V.chart j) x) = + (V.dualTransition i j x).conjTranspose * dualMatrix i (coordQuadric (V.chart i) x) * + V.dualTransition i j x + +def SmoothHermitianMetric.StrictlyGriffithsPositive {V : AlgebraicRankTwoBundle} + (h : SmoothHermitianMetric V) : Prop := + ∀ i z, z ∈ V.coordinateDomain i → ∀ u : BaseCoordinates, u ≠ 0 → + (metricMixedHessian (h.dualMatrix i) z u - + (holomorphicMetricDerivative (h.dualMatrix i) z u).conjTranspose * + (h.dualMatrix i z)⁻¹ * holomorphicMetricDerivative (h.dualMatrix i) z u).PosDef + +def SourceMainTheorem : Prop := + ∃ G : AlgebraicRankTwoBundle, ∃ E : ℕ → AlgebraicRankTwoBundle, + (∀ m, 0 < m → IsPowerPullbackTwist G m (E m)) ∧ + (∀ m, 0 < m → IsAmple (E m)) ∧ + ∃ m₀ : ℕ, 0 < m₀ ∧ ∀ m, m₀ ≤ m → + ¬ ∃ h : SmoothHermitianMetric (E m), h.StrictlyGriffithsPositive + +theorem main_theorem : SourceMainTheorem := by + sorry + +end QuadricCounterexample + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/QuadricBundles.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QuadricCounterexample.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/quadric-bundles/solution/closure.txt b/tasks/quadric-bundles/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..86f1aef782b290df236b40aae2ab0b91bc975a9b --- /dev/null +++ b/tasks/quadric-bundles/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Geometry.QuadricBundles.Ampleness +OAI.Geometry.QuadricBundles.BallAverage +OAI.Geometry.QuadricBundles.BinaryForms +OAI.Geometry.QuadricBundles.Charts +OAI.Geometry.QuadricBundles.Compactness +OAI.Geometry.QuadricBundles.Curvature +OAI.Geometry.QuadricBundles.DiskHessian +OAI.Geometry.QuadricBundles.DualForms +OAI.Geometry.QuadricBundles.Embedding +OAI.Geometry.QuadricBundles.Equalizer +OAI.Geometry.QuadricBundles.Gluing +OAI.Geometry.QuadricBundles.Graphs +OAI.Geometry.QuadricBundles.HomogeneousClassification +OAI.Geometry.QuadricBundles.LaurentCech +OAI.Geometry.QuadricBundles.LineFactors +OAI.Geometry.QuadricBundles.Main +OAI.Geometry.QuadricBundles.MatrixDynamics +OAI.Geometry.QuadricBundles.MatrixRepresentative +OAI.Geometry.QuadricBundles.Model +OAI.Geometry.QuadricBundles.Noncollapse +OAI.Geometry.QuadricBundles.Plurisubharmonic +OAI.Geometry.QuadricBundles.PointwiseRepresentative +OAI.Geometry.QuadricBundles.PolynomialGeneration +OAI.Geometry.QuadricBundles.ProjectiveEquations +OAI.Geometry.QuadricBundles.RegularMatrices +OAI.Geometry.QuadricBundles.Regularity +OAI.Geometry.QuadricBundles.Removability +OAI.Geometry.QuadricBundles.RootTrace +OAI.Geometry.QuadricBundles.SymmetricFlags +OAI.Geometry.QuadricBundles.TraceExtraction +OAI.Geometry.QuadricBundles.TraceMetrics +OAI.Geometry.QuadricBundles.TriangularSections +OAI.Geometry.QuadricBundles.WeakBaseChange +OAI.Geometry.QuadricBundles.WeakLimits diff --git a/tasks/quadric-bundles/solution/reference.py b/tasks/quadric-bundles/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/quadric-bundles/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/quadric-bundles/solution/solve.sh b/tasks/quadric-bundles/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..30f13982ef7551f68c331942df1b3bbeaa53988a --- /dev/null +++ b/tasks/quadric-bundles/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of QuadricBundles, i.e. module OAI.Geometry.QuadricBundles.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.QuadricBundles.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of QuadricBundles" diff --git a/tasks/quadric-bundles/task.toml b/tasks/quadric-bundles/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5c60fb170104834683bf09841130ce2fd8db507f --- /dev/null +++ b/tasks/quadric-bundles/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/quadric-bundles" +version = "1.0.0" +description = "Prove QuadricBundles (openai/math family 050: A counterexample to Griffiths' positivity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/QuadricBundles.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "QuadricBundles" +family = "050" +family_title = "A counterexample to Griffiths' positivity conjecture" +subject = "Algebraic and complex geometry" +theorems = ["OAI.QuadricCounterexample.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.QuadricBundles.Main" +reference_modules = 34 +reference_lean_bytes = 604021 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 886 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12243 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/quadric-bundles/tests/Challenge.lean b/tasks/quadric-bundles/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e56aea69f438c79cb66100f8d02deb4508e95f8 --- /dev/null +++ b/tasks/quadric-bundles/tests/Challenge.lean @@ -0,0 +1,181 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace QuadricCounterexample + +open Set Filter Topology Metric OnePoint + +open scoped Matrix.Norms.Elementwise ComplexOrder + +abbrev ProjectiveLine := OnePoint ℂ +abbrev QuadricSurface := ProjectiveLine × ProjectiveLine + +def reciprocalP1 (x : ProjectiveLine) : ProjectiveLine := + x.elim (0 : ℂ) (fun z ↦ if z = 0 then ∞ else (z⁻¹ : ℂ)) + +def affineP1 (i : Fin 2) (z : ℂ) : ProjectiveLine := + if i = 0 then reciprocalP1 z else (z : ProjectiveLine) + +def affineQuadric (i : Fin 2 × Fin 2) (z : ℂ × ℂ) : QuadricSurface := + (affineP1 i.1 z.1, affineP1 i.2 z.2) + +def coordP1 (i : Fin 2) (x : ProjectiveLine) : ℂ := + (if i=0 then reciprocalP1 x else x).elim 0 id +def coordQuadric (i : Fin 2 × Fin 2) (x : QuadricSurface) : ℂ × ℂ := + (coordP1 i.1 x.1,coordP1 i.2 x.2) + +def powerP1 (m : ℕ) (x : ProjectiveLine) : ProjectiveLine := + x.elim ∞ (fun z ↦ ((z^m : ℂ) : ProjectiveLine)) +def powerQuadric (m : ℕ) (x : QuadricSurface) : QuadricSurface := + (powerP1 m x.1,powerP1 m x.2) + +abbrev BaseCoordinates := ℂ × ℂ +abbrev FiberCoordinates := Fin 2 → ℂ +abbrev TwoMatrix := Matrix (Fin 2) (Fin 2) ℂ +abbrev BasePolynomial := MvPolynomial (Fin 2) ℂ +def baseEval (p : BasePolynomial) (z : BaseCoordinates) : ℂ := + MvPolynomial.eval ![z.1,z.2] p + +def AlgebraicallyRegularOn (U : Set BaseCoordinates) (f : BaseCoordinates → ℂ) : Prop := + ∀ z ∈ U, ∃ p q : BasePolynomial, baseEval q z ≠ 0 ∧ + ∀ w ∈ U, baseEval q w ≠ 0 → f w=baseEval p w/baseEval q w + +def principalChart (i : Fin 2 × Fin 2) (p : BasePolynomial) : Set QuadricSurface := + {x | x ∈ range (affineQuadric i) ∧ baseEval p (coordQuadric i x) ≠ 0} + +structure AlgebraicRankTwoBundle where + numberOfCharts : ℕ + chart : ℕ → Fin 2 × Fin 2 + equation : ℕ → BasePolynomial + finiteCover : ∀ i, numberOfCharts ≤ i → equation i=0 + covers : ∀ x : QuadricSurface, ∃ i, x ∈ principalChart (chart i) (equation i) + transition : ℕ → ℕ → QuadricSurface → TwoMatrix + transition_self : ∀ i x, x ∈ principalChart (chart i) (equation i) → + transition i i x=1 + transition_mul : ∀ i j k x, + x ∈ principalChart (chart i) (equation i) → + x ∈ principalChart (chart j) (equation j) → + x ∈ principalChart (chart k) (equation k) → + transition i j x * transition j k x=transition i k x + transition_regular : ∀ i j a b, AlgebraicallyRegularOn + {z | baseEval (equation i) z ≠ 0 ∧ + affineQuadric (chart i) z ∈ principalChart (chart j) (equation j)} + (fun z ↦ transition i j (affineQuadric (chart i) z) a b) + +namespace AlgebraicRankTwoBundle + +def domain (V : AlgebraicRankTwoBundle) (i : ℕ) : Set QuadricSurface := + principalChart (V.chart i) (V.equation i) +def coordinateDomain (V : AlgebraicRankTwoBundle) (i : ℕ) : Set BaseCoordinates := + {z | baseEval (V.equation i) z ≠ 0} + +def dualTransition (V : AlgebraicRankTwoBundle) (i j : ℕ) (x : QuadricSurface) : TwoMatrix := + (V.transition j i x).transpose + +end AlgebraicRankTwoBundle + +def hyperplaneTransition (i j : Fin 2) (x : ProjectiveLine) : ℂ := + if i=j then 1 else coordP1 i x +def polarizationTransition (i j : Fin 2 × Fin 2) (x : QuadricSurface) : ℂ := + hyperplaneTransition i.1 j.1 x.1 * hyperplaneTransition i.2 j.2 x.2 + +def IsPowerPullbackTwist (G : AlgebraicRankTwoBundle) (m : ℕ) + (E : AlgebraicRankTwoBundle) : Prop := + E.numberOfCharts=G.numberOfCharts ∧ E.chart=G.chart ∧ + (∀ i, E.equation i = (MvPolynomial.bind₁ fun j ↦ MvPolynomial.X j ^ m) (G.equation i)) ∧ + ∀ i j x, x ∈ E.domain i → x ∈ E.domain j → + E.transition i j x = polarizationTransition (G.chart i) (G.chart j) x • + G.transition i j (powerQuadric m x) + +structure SymmetricSection (V : AlgebraicRankTwoBundle) (n : ℕ) where + coefficient : ℕ → Fin (n+1) → BaseCoordinates → ℂ + regular : ∀ i k, AlgebraicallyRegularOn (V.coordinateDomain i) (coefficient i k) + compatible : ∀ i j x, x ∈ V.domain i → x ∈ V.domain j → ∀ v : FiberCoordinates, + (∑ k : Fin (n+1), coefficient i k (coordQuadric (V.chart i) x) * + ((V.dualTransition i j x).mulVec v 0)^k.val * + ((V.dualTransition i j x).mulVec v 1)^(n-k.val)) = + ∑ k : Fin (n+1), coefficient j k (coordQuadric (V.chart j) x) * v 0^k.val * v 1^(n-k.val) + +def SymmetricSection.value {V : AlgebraicRankTwoBundle} {n : ℕ} + (s : SymmetricSection V n) (i : ℕ) (x : QuadricSurface) (v : FiberCoordinates) : ℂ := + ∑ k : Fin (n+1), s.coefficient i k (coordQuadric (V.chart i) x) * v 0^k.val * v 1^(n-k.val) + +def ProjectiveAlgebraicCone {N : ℕ} (C : Set (Fin N → ℂ)) : Prop := + ∃ equations : Set (MvPolynomial (Fin N) ℂ), + (∀ p ∈ equations, ∃ d : ℕ, p.IsHomogeneous d) ∧ + C = {y | ∀ p ∈ equations, MvPolynomial.eval y p=0} + +def sectionVector {V : AlgebraicRankTwoBundle} {n N : ℕ} + (s : Fin N → SymmetricSection V n) (i : ℕ) (x : QuadricSurface) + (v : FiberCoordinates) : Fin N → ℂ := fun j ↦ (s j).value i x v + +def GivesClosedProjectiveEmbedding {V : AlgebraicRankTwoBundle} {n N : ℕ} + (s : Fin N → SymmetricSection V n) : Prop := + (∀ i x, x ∈ V.domain i → ∀ v : FiberCoordinates, v ≠ 0 → sectionVector s i x v ≠ 0) ∧ + (∀ i j x y, x ∈ V.domain i → y ∈ V.domain j → ∀ v w : FiberCoordinates, + v ≠ 0 → w ≠ 0 → (∃ c : ℂ, c ≠ 0 ∧ sectionVector s i x v = c • sectionVector s j y w) → + x=y ∧ ∃ c : ℂ, c ≠ 0 ∧ v=c • ((V.dualTransition i j x).mulVec w)) ∧ + ProjectiveAlgebraicCone ({0} ∪ {a | ∃ i x, x ∈ V.domain i ∧ + ∃ v : FiberCoordinates, v ≠ 0 ∧ ∃ c : ℂ, c ≠ 0 ∧ a=c • sectionVector s i x v}) ∧ + ∀ i x, x ∈ V.domain i → ∀ v : FiberCoordinates, v ≠ 0 → + ∃ j : Fin N, ∃ b : Fin 2, v b ≠ 0 ∧ sectionVector s i x v j ≠ 0 ∧ + ∃ p q : Fin 3 → MvPolynomial (Fin N) ℂ, + (∀ k, MvPolynomial.eval (fun l ↦ sectionVector s i x v l / sectionVector s i x v j) (q k) ≠ 0) ∧ + ∀ i' x', x' ∈ V.domain i' → ∀ v' : FiberCoordinates, v' ≠ 0 → + sectionVector s i' x' v' j ≠ 0 → + (∀ k, MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (q k) ≠ 0) → + x' ∈ V.domain i ∧ ((V.dualTransition i i' x').mulVec v') b ≠ 0 ∧ + (∀ k : Fin 3, + (![ (coordQuadric (V.chart i) x').1, (coordQuadric (V.chart i) x').2, + ((V.dualTransition i i' x').mulVec v') (1-b) / + ((V.dualTransition i i' x').mulVec v') b ] : Fin 3 → ℂ) k = + MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (p k) / + MvPolynomial.eval (fun l ↦ sectionVector s i' x' v' l / sectionVector s i' x' v' j) (q k)) + +def IsAmple (V : AlgebraicRankTwoBundle) : Prop := + ∃ n : ℕ, 0 < n ∧ ∃ N : ℕ, ∃ s : Fin N → SymmetricSection V n, + GivesClosedProjectiveEmbedding s + +def holomorphicMetricDerivative (H : BaseCoordinates → TwoMatrix) + (z u : BaseCoordinates) : TwoMatrix := + (1/2 : ℂ) • (fderiv ℝ H z u - Complex.I • fderiv ℝ H z (Complex.I • u)) + +def metricMixedHessian (H : BaseCoordinates → TwoMatrix) + (z u : BaseCoordinates) : TwoMatrix := + (1/4 : ℂ) • ((fderiv ℝ (fun y ↦ fderiv ℝ H y) z u) u + + (fderiv ℝ (fun y ↦ fderiv ℝ H y) z (Complex.I • u)) (Complex.I • u)) + +structure SmoothHermitianMetric (V : AlgebraicRankTwoBundle) where + dualMatrix : ℕ → BaseCoordinates → TwoMatrix + smooth : ∀ i, ContDiffOn ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) (dualMatrix i) (V.coordinateDomain i) + positive : ∀ i z, z ∈ V.coordinateDomain i → (dualMatrix i z).PosDef + compatible : ∀ i j x, x ∈ V.domain i → x ∈ V.domain j → + dualMatrix j (coordQuadric (V.chart j) x) = + (V.dualTransition i j x).conjTranspose * dualMatrix i (coordQuadric (V.chart i) x) * + V.dualTransition i j x + +def SmoothHermitianMetric.StrictlyGriffithsPositive {V : AlgebraicRankTwoBundle} + (h : SmoothHermitianMetric V) : Prop := + ∀ i z, z ∈ V.coordinateDomain i → ∀ u : BaseCoordinates, u ≠ 0 → + (metricMixedHessian (h.dualMatrix i) z u - + (holomorphicMetricDerivative (h.dualMatrix i) z u).conjTranspose * + (h.dualMatrix i z)⁻¹ * holomorphicMetricDerivative (h.dualMatrix i) z u).PosDef + +def SourceMainTheorem : Prop := + ∃ G : AlgebraicRankTwoBundle, ∃ E : ℕ → AlgebraicRankTwoBundle, + (∀ m, 0 < m → IsPowerPullbackTwist G m (E m)) ∧ + (∀ m, 0 < m → IsAmple (E m)) ∧ + ∃ m₀ : ℕ, 0 < m₀ ∧ ∀ m, m₀ ≤ m → + ¬ ∃ h : SmoothHermitianMetric (E m), h.StrictlyGriffithsPositive + +theorem main_theorem : SourceMainTheorem := by + sorry + +end QuadricCounterexample + +end + +end OAI diff --git a/tasks/quadric-bundles/tests/grade.py b/tasks/quadric-bundles/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/quadric-bundles/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/quadric-bundles/tests/task.json b/tasks/quadric-bundles/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..55920c60ad7cb1ef76be9c3f1a750ddb6c2a803e --- /dev/null +++ b/tasks/quadric-bundles/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "QuadricBundles", + "comparator": { + "theorem_names": [ + "OAI.QuadricCounterexample.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11343 +} \ No newline at end of file diff --git a/tasks/quadric-bundles/tests/test.sh b/tasks/quadric-bundles/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/quadric-bundles/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/quantitative-van-der-waerden/environment/Dockerfile b/tasks/quantitative-van-der-waerden/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/quantitative-van-der-waerden/environment/fetch_mathlib.sh b/tasks/quantitative-van-der-waerden/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/quantitative-van-der-waerden/environment/lake-manifest.json b/tasks/quantitative-van-der-waerden/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/quantitative-van-der-waerden/environment/lakefile.lean b/tasks/quantitative-van-der-waerden/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/quantitative-van-der-waerden/environment/lean_setup.sh b/tasks/quantitative-van-der-waerden/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/quantitative-van-der-waerden/environment/pack_submission.py b/tasks/quantitative-van-der-waerden/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/quantitative-van-der-waerden/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/quantitative-van-der-waerden/instruction.md b/tasks/quantitative-van-der-waerden/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6d63c398cd2139ecf5d1338e861b6f8d345fe434 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/instruction.md @@ -0,0 +1,84 @@ +# openai/math challenge `QuantitativeVanDerWaerden` (family 160) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 160 of the release, *Superexponential van der Waerden numbers* +(Combinatorics). The family as a whole: Resolves Erd\H{o}s's superexponential-growth question for van der Waerden numbers. If $W_r(k)$ is the least interval length forcing a monochromatic $k$-term progression in every $r$-coloring, then $W_r(k)>k^{ck\lfloor\log_2 r\rfloor}$ for an absolute $c>0$, all $r\ge2$ and sufficiently large $k$, uniformly in $r$. In particular, $W_r(k)^{1/k}\to\infty$ for each fixed $r$. + +The challenge is `QuantitativeVanDerWaerden`, also at `/opt/openai-math/challenges/QuantitativeVanDerWaerden.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u + +namespace QuantitativeVanDerWaerden + +def MonoAP {α : Type u} (c : ℕ → α) (k a d : ℕ) : Prop := + ∀ j < k, c (a + j * d) = c a + +def HasMonoAP {α : Type u} (c : ℕ → α) (k N : ℕ) : Prop := + ∃ a d, 0 < d ∧ a + (k - 1) * d < N ∧ MonoAP c k a d + +def IsRamsey (α : Type u) (k N : ℕ) : Prop := + ∀ c : ℕ → α, HasMonoAP c k N + +/-- The least positive Ramsey interval size. Statements about its Ramsey +property require a finiteness proof; no such proof is built into this definition. -/ +noncomputable def W (r k : ℕ) : ℕ := + sInf {N : ℕ | 0 < N ∧ IsRamsey (Fin r) k N} + +open Filter + +/-- An absolute quantitative lower bound, uniform over all color counts. -/ +theorem uniform_lower_bound : + ∃ K : ℕ, ∀ k ≥ K, ∀ r ≥ 2, + (k : ℝ) ^ ((1 / 100000 : ℝ) * k * (Nat.log 2 r : ℝ)) < (W r k : ℝ) := by + sorry + +end QuantitativeVanDerWaerden + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/QuantitativeVanDerWaerden.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QuantitativeVanDerWaerden.uniform_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/quantitative-van-der-waerden/solution/closure.txt b/tasks/quantitative-van-der-waerden/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d942c77600090abb87caa2a6a6c810b254c64116 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/solution/closure.txt @@ -0,0 +1,115 @@ +OAI.Combinatorics.ProgressionColoring.AdaptiveMesh +OAI.Combinatorics.ProgressionColoring.AdaptiveMeshBreakpoints +OAI.Combinatorics.ProgressionColoring.AdaptiveMeshCounting +OAI.Combinatorics.ProgressionColoring.AffineEntropy +OAI.Combinatorics.ProgressionColoring.AffineEntropyNat +OAI.Combinatorics.ProgressionColoring.AnchoredPatternDefinitions +OAI.Combinatorics.ProgressionColoring.AnchoredPatterns +OAI.Combinatorics.ProgressionColoring.Arrangement +OAI.Combinatorics.ProgressionColoring.Asymptotics +OAI.Combinatorics.ProgressionColoring.Basic +OAI.Combinatorics.ProgressionColoring.BlockCoverage +OAI.Combinatorics.ProgressionColoring.ClosestReturn +OAI.Combinatorics.ProgressionColoring.ClosestReturnEstimates +OAI.Combinatorics.ProgressionColoring.ComparisonOutputs +OAI.Combinatorics.ProgressionColoring.ConstructionArithmetic +OAI.Combinatorics.ProgressionColoring.ConstructionDichotomyDenominator +OAI.Combinatorics.ProgressionColoring.ConstructionDichotomyScales +OAI.Combinatorics.ProgressionColoring.ConstructionHeavyLabelReturn +OAI.Combinatorics.ProgressionColoring.ConstructionHeavyLight +OAI.Combinatorics.ProgressionColoring.ConstructionModel +OAI.Combinatorics.ProgressionColoring.ConstructionModelBounds +OAI.Combinatorics.ProgressionColoring.ConstructionSignatureBudget +OAI.Combinatorics.ProgressionColoring.ConstructionWordFamily +OAI.Combinatorics.ProgressionColoring.CoshBound +OAI.Combinatorics.ProgressionColoring.CyclicBasic +OAI.Combinatorics.ProgressionColoring.CyclicBlockLabels +OAI.Combinatorics.ProgressionColoring.CyclicColoring +OAI.Combinatorics.ProgressionColoring.CyclicHeavyIntervalWidth +OAI.Combinatorics.ProgressionColoring.CyclicModel +OAI.Combinatorics.ProgressionColoring.CyclicRationalReturn +OAI.Combinatorics.ProgressionColoring.CyclicSignatures +OAI.Combinatorics.ProgressionColoring.CyclicWitness +OAI.Combinatorics.ProgressionColoring.Dichotomy +OAI.Combinatorics.ProgressionColoring.DigitProduct +OAI.Combinatorics.ProgressionColoring.DigitProductBounds +OAI.Combinatorics.ProgressionColoring.Dilation +OAI.Combinatorics.ProgressionColoring.EligibleOuterColoring +OAI.Combinatorics.ProgressionColoring.EligiblePatternTests +OAI.Combinatorics.ProgressionColoring.EligibleRecordedSupport +OAI.Combinatorics.ProgressionColoring.FairBitProbability +OAI.Combinatorics.ProgressionColoring.FairBitTail +OAI.Combinatorics.ProgressionColoring.FairOuterColoring +OAI.Combinatorics.ProgressionColoring.FiniteGaps +OAI.Combinatorics.ProgressionColoring.FiniteLocalLemma +OAI.Combinatorics.ProgressionColoring.FiniteLocalLemmaMeasure +OAI.Combinatorics.ProgressionColoring.FiniteProbability +OAI.Combinatorics.ProgressionColoring.GenericAsymptotics +OAI.Combinatorics.ProgressionColoring.GlobalLabelWords +OAI.Combinatorics.ProgressionColoring.Growth +OAI.Combinatorics.ProgressionColoring.GrowthConsequences +OAI.Combinatorics.ProgressionColoring.GrowthRates +OAI.Combinatorics.ProgressionColoring.HeavyIntervalWidth +OAI.Combinatorics.ProgressionColoring.HeavyLabelReturn +OAI.Combinatorics.ProgressionColoring.HeavyReturnFinPath +OAI.Combinatorics.ProgressionColoring.HeavyReturnSeparation +OAI.Combinatorics.ProgressionColoring.HeavyReturnWidth +OAI.Combinatorics.ProgressionColoring.KeyMultiplicity +OAI.Combinatorics.ProgressionColoring.LabelCounts +OAI.Combinatorics.ProgressionColoring.LabelFiber +OAI.Combinatorics.ProgressionColoring.LabelIncidences +OAI.Combinatorics.ProgressionColoring.LargeColor +OAI.Combinatorics.ProgressionColoring.LargeColorConsequences +OAI.Combinatorics.ProgressionColoring.LargeColorGrowth +OAI.Combinatorics.ProgressionColoring.LiteralLabelRectangles +OAI.Combinatorics.ProgressionColoring.LocalTail +OAI.Combinatorics.ProgressionColoring.LongPeriodBlocks +OAI.Combinatorics.ProgressionColoring.LongPeriodColoring +OAI.Combinatorics.ProgressionColoring.LongPeriodEligibility +OAI.Combinatorics.ProgressionColoring.LongPeriodRegularGrid +OAI.Combinatorics.ProgressionColoring.LongPeriodRegularity +OAI.Combinatorics.ProgressionColoring.Main +OAI.Combinatorics.ProgressionColoring.MeshPartitions +OAI.Combinatorics.ProgressionColoring.Model +OAI.Combinatorics.ProgressionColoring.ModelGeometry +OAI.Combinatorics.ProgressionColoring.NormBands +OAI.Combinatorics.ProgressionColoring.OuterBalanced +OAI.Combinatorics.ProgressionColoring.OuterBudget +OAI.Combinatorics.ProgressionColoring.OuterChoiceDefinitions +OAI.Combinatorics.ProgressionColoring.OuterColoring +OAI.Combinatorics.ProgressionColoring.OuterDichotomy +OAI.Combinatorics.ProgressionColoring.OuterFamilies +OAI.Combinatorics.ProgressionColoring.OuterIncidence +OAI.Combinatorics.ProgressionColoring.OuterModelChoice +OAI.Combinatorics.ProgressionColoring.OuterPatternColoring +OAI.Combinatorics.ProgressionColoring.OuterRowRealBound +OAI.Combinatorics.ProgressionColoring.OuterRows +OAI.Combinatorics.ProgressionColoring.OuterRowsMod +OAI.Combinatorics.ProgressionColoring.OuterTestColoring +OAI.Combinatorics.ProgressionColoring.OuterWordTests +OAI.Combinatorics.ProgressionColoring.Parameters +OAI.Combinatorics.ProgressionColoring.Perturbation +OAI.Combinatorics.ProgressionColoring.PerturbationScales +OAI.Combinatorics.ProgressionColoring.PrimeScale +OAI.Combinatorics.ProgressionColoring.PrimitiveVector +OAI.Combinatorics.ProgressionColoring.ProbabilityScales +OAI.Combinatorics.ProgressionColoring.RationalGridCount +OAI.Combinatorics.ProgressionColoring.RationalGridMultiplicity +OAI.Combinatorics.ProgressionColoring.RationalReturn +OAI.Combinatorics.ProgressionColoring.RationalSeparation +OAI.Combinatorics.ProgressionColoring.RecordedSupport +OAI.Combinatorics.ProgressionColoring.ResidueFiber +OAI.Combinatorics.ProgressionColoring.ScalarAdaptiveMesh +OAI.Combinatorics.ProgressionColoring.ScalarEntropy +OAI.Combinatorics.ProgressionColoring.ScalarMesh +OAI.Combinatorics.ProgressionColoring.ShortPeriodCut +OAI.Combinatorics.ProgressionColoring.ShortPeriodLift +OAI.Combinatorics.ProgressionColoring.ShortPeriodPath +OAI.Combinatorics.ProgressionColoring.SignatureCounting +OAI.Combinatorics.ProgressionColoring.SmallBoxAffinity +OAI.Combinatorics.ProgressionColoring.TernarySign +OAI.Combinatorics.ProgressionColoring.UniformBudget +OAI.Combinatorics.ProgressionColoring.UniformMesh +OAI.Combinatorics.ProgressionColoring.UniformTransfer +OAI.Combinatorics.ProgressionColoring.UpperBound +OAI.Combinatorics.ProgressionColoring.WordDichotomy diff --git a/tasks/quantitative-van-der-waerden/solution/reference.py b/tasks/quantitative-van-der-waerden/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/quantitative-van-der-waerden/solution/solve.sh b/tasks/quantitative-van-der-waerden/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fd8719156d29985c3f81b4ca45585449cb8442fc --- /dev/null +++ b/tasks/quantitative-van-der-waerden/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of QuantitativeVanDerWaerden, i.e. module OAI.Combinatorics.ProgressionColoring.Main and the +# 115 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ProgressionColoring.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of QuantitativeVanDerWaerden" diff --git a/tasks/quantitative-van-der-waerden/task.toml b/tasks/quantitative-van-der-waerden/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..31aacbcf40c90c1d286791c06c069a98cdb8ae75 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/quantitative-van-der-waerden" +version = "1.0.0" +description = "Prove QuantitativeVanDerWaerden (openai/math family 160: Superexponential van der Waerden numbers) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/QuantitativeVanDerWaerden.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "QuantitativeVanDerWaerden" +family = "160" +family_title = "Superexponential van der Waerden numbers" +subject = "Combinatorics" +theorems = ["OAI.QuantitativeVanDerWaerden.uniform_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ProgressionColoring.Main" +reference_modules = 115 +reference_lean_bytes = 643306 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 811 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12278 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/quantitative-van-der-waerden/tests/Challenge.lean b/tasks/quantitative-van-der-waerden/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bee3f5a820455ead2a00f8fdc08d4ae5276cba2a --- /dev/null +++ b/tasks/quantitative-van-der-waerden/tests/Challenge.lean @@ -0,0 +1,33 @@ +import Mathlib + +namespace OAI + +universe u + +namespace QuantitativeVanDerWaerden + +def MonoAP {α : Type u} (c : ℕ → α) (k a d : ℕ) : Prop := + ∀ j < k, c (a + j * d) = c a + +def HasMonoAP {α : Type u} (c : ℕ → α) (k N : ℕ) : Prop := + ∃ a d, 0 < d ∧ a + (k - 1) * d < N ∧ MonoAP c k a d + +def IsRamsey (α : Type u) (k N : ℕ) : Prop := + ∀ c : ℕ → α, HasMonoAP c k N + +/-- The least positive Ramsey interval size. Statements about its Ramsey +property require a finiteness proof; no such proof is built into this definition. -/ +noncomputable def W (r k : ℕ) : ℕ := + sInf {N : ℕ | 0 < N ∧ IsRamsey (Fin r) k N} + +open Filter + +/-- An absolute quantitative lower bound, uniform over all color counts. -/ +theorem uniform_lower_bound : + ∃ K : ℕ, ∀ k ≥ K, ∀ r ≥ 2, + (k : ℝ) ^ ((1 / 100000 : ℝ) * k * (Nat.log 2 r : ℝ)) < (W r k : ℝ) := by + sorry + +end QuantitativeVanDerWaerden + +end OAI diff --git a/tasks/quantitative-van-der-waerden/tests/grade.py b/tasks/quantitative-van-der-waerden/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/quantitative-van-der-waerden/tests/task.json b/tasks/quantitative-van-der-waerden/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ae137f1d1fe253ec080aaf62ae4b9e951a2575f6 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "QuantitativeVanDerWaerden", + "comparator": { + "theorem_names": [ + "OAI.QuantitativeVanDerWaerden.uniform_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11378 +} \ No newline at end of file diff --git a/tasks/quantitative-van-der-waerden/tests/test.sh b/tasks/quantitative-van-der-waerden/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/quantitative-van-der-waerden/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/quintic-lienard/environment/Dockerfile b/tasks/quintic-lienard/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/quintic-lienard/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/quintic-lienard/environment/fetch_mathlib.sh b/tasks/quintic-lienard/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/quintic-lienard/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/quintic-lienard/environment/lake-manifest.json b/tasks/quintic-lienard/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/quintic-lienard/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/quintic-lienard/environment/lakefile.lean b/tasks/quintic-lienard/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/quintic-lienard/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/quintic-lienard/environment/lean_setup.sh b/tasks/quintic-lienard/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/quintic-lienard/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/quintic-lienard/environment/pack_submission.py b/tasks/quintic-lienard/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/quintic-lienard/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/quintic-lienard/instruction.md b/tasks/quintic-lienard/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..700694c67ca20e75ee6bda0d17b0409d92bb323b --- /dev/null +++ b/tasks/quintic-lienard/instruction.md @@ -0,0 +1,97 @@ +# openai/math challenge `QuinticLienard` (family 143) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 143 of the release, *Uniform limit-cycle bounds in Hilbert's sixteenth problem* +(Dynamical systems and ergodic theory). The family as a whole: Resolves the uniform boundedness assertion in Hilbert's sixteenth problem: the number of isolated periodic orbits of a real planar polynomial vector field is bounded by a finite constant depending only on its degree. For classical quintic Lienard systems, the exact maximum is two limit cycles. + +The challenge is `QuinticLienard`, also at `/opt/openai-math/challenges/QuinticLienard.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace QuinticLienard + +abbrev Plane := ℝ × ℝ + +def vectorField (F : Polynomial ℝ) (z : Plane) : Plane := + (z.2 - F.eval z.1, -z.1) + +def IsSolution (F : Polynomial ℝ) (z : ℝ → Plane) : Prop := + ∀ t : ℝ, HasDerivAt z (vectorField F (z t)) t + +def IsPeriodicOrbit (F : Polynomial ℝ) (C : Set Plane) : Prop := + ∃ (z : ℝ → Plane) (T : ℝ), + IsSolution F z ∧ 0 < T ∧ Function.Periodic z T ∧ + (∃ s t : ℝ, z s ≠ z t) ∧ C = Set.range z + +def IsLimitCycle (F : Polynomial ℝ) (C : Set Plane) : Prop := + IsPeriodicOrbit F C ∧ + ∃ U : Set Plane, IsOpen U ∧ C ⊆ U ∧ + ∀ C' : Set Plane, IsPeriodicOrbit F C' → C' ⊆ U → C' = C + +open scoped Topology NNReal ContDiff Manifold +open Filter Set +open Set Filter Metric MeasureTheory +open scoped Topology NNReal ContDiff +open scoped Topology ENNReal +open Set Filter MeasureTheory +open Set Filter Asymptotics +open Set Filter Metric +open scoped Topology NNReal +open scoped Topology +open scoped Topology ContDiff +open Set Filter +open scoped Topology ContDiff NNReal + +theorem main : + (∀ F : Polynomial ℝ, F.degree ≤ 5 → {C : Set Plane | IsLimitCycle F C}.encard ≤ 2) ∧ + (∃ F : Polynomial ℝ, F.degree ≤ 5 ∧ {C : Set Plane | IsLimitCycle F C}.encard = 2) := by + sorry + +end QuinticLienard + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/QuinticLienard.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QuinticLienard.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/quintic-lienard/solution/closure.txt b/tasks/quintic-lienard/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b03c867a99d53333e2f3e2332ef28182b0f7430 --- /dev/null +++ b/tasks/quintic-lienard/solution/closure.txt @@ -0,0 +1,146 @@ +OAI.Analysis.LienardCycles.ActualCharacteristic +OAI.Analysis.LienardCycles.ActualError +OAI.Analysis.LienardCycles.ActualFitLimits +OAI.Analysis.LienardCycles.ActualFitTransport +OAI.Analysis.LienardCycles.ActualReflection +OAI.Analysis.LienardCycles.ActualSlopeComparison +OAI.Analysis.LienardCycles.ActualSmallWidth +OAI.Analysis.LienardCycles.AlgebraicFlow +OAI.Analysis.LienardCycles.AlgebraicNotation +OAI.Analysis.LienardCycles.AngleBounds +OAI.Analysis.LienardCycles.ArcEndpoints +OAI.Analysis.LienardCycles.ArcFamilies +OAI.Analysis.LienardCycles.ArchSymmetries +OAI.Analysis.LienardCycles.ArchVariation +OAI.Analysis.LienardCycles.AxisBranches +OAI.Analysis.LienardCycles.AxisCases +OAI.Analysis.LienardCycles.AxisComparison +OAI.Analysis.LienardCycles.AxisFit +OAI.Analysis.LienardCycles.AxisIntercept +OAI.Analysis.LienardCycles.AxisLimits +OAI.Analysis.LienardCycles.AxisReflection +OAI.Analysis.LienardCycles.AxisRegularity +OAI.Analysis.LienardCycles.AxisSecants +OAI.Analysis.LienardCycles.AxisWidthGerm +OAI.Analysis.LienardCycles.AxisWidthRegularity +OAI.Analysis.LienardCycles.AxisZeroCount +OAI.Analysis.LienardCycles.AxisZeros +OAI.Analysis.LienardCycles.BaseLimits +OAI.Analysis.LienardCycles.BaseSymmetry +OAI.Analysis.LienardCycles.BaseTransport +OAI.Analysis.LienardCycles.BoundaryFlow +OAI.Analysis.LienardCycles.BoundaryGerm +OAI.Analysis.LienardCycles.CanonicalAnalytic +OAI.Analysis.LienardCycles.CanonicalVariation +OAI.Analysis.LienardCycles.CaseOne +OAI.Analysis.LienardCycles.Characteristic +OAI.Analysis.LienardCycles.CharacteristicJets +OAI.Analysis.LienardCycles.CharacteristicLimit +OAI.Analysis.LienardCycles.CharacteristicPositive +OAI.Analysis.LienardCycles.CharacteristicScaling +OAI.Analysis.LienardCycles.CharacteristicSigns +OAI.Analysis.LienardCycles.ClosedCutoff +OAI.Analysis.LienardCycles.CoefficientCases +OAI.Analysis.LienardCycles.ConditionalFit +OAI.Analysis.LienardCycles.CubicVariation +OAI.Analysis.LienardCycles.CurvatureComparison +OAI.Analysis.LienardCycles.CurvatureJets +OAI.Analysis.LienardCycles.CurvaturePositive +OAI.Analysis.LienardCycles.CurvatureRange +OAI.Analysis.LienardCycles.CurvatureTransport +OAI.Analysis.LienardCycles.CycleIsolation +OAI.Analysis.LienardCycles.CycleSection +OAI.Analysis.LienardCycles.CycleTransform +OAI.Analysis.LienardCycles.EndpointAlgebra +OAI.Analysis.LienardCycles.EndpointComparison +OAI.Analysis.LienardCycles.EndpointJets +OAI.Analysis.LienardCycles.EndpointScaling +OAI.Analysis.LienardCycles.EndpointSigns +OAI.Analysis.LienardCycles.ExcursionAxis +OAI.Analysis.LienardCycles.ExcursionGraph +OAI.Analysis.LienardCycles.ExcursionSigns +OAI.Analysis.LienardCycles.FiberQuotient +OAI.Analysis.LienardCycles.FiniteFlow +OAI.Analysis.LienardCycles.FitAngles +OAI.Analysis.LienardCycles.FitProperness +OAI.Analysis.LienardCycles.FitSmall +OAI.Analysis.LienardCycles.FixedSlopeLimit +OAI.Analysis.LienardCycles.FixedWidthFamilies +OAI.Analysis.LienardCycles.GlobalFit +OAI.Analysis.LienardCycles.GlobalODE +OAI.Analysis.LienardCycles.HeightLimits +OAI.Analysis.LienardCycles.HeightSigns +OAI.Analysis.LienardCycles.HyperbolicCoordinate +OAI.Analysis.LienardCycles.Intercept +OAI.Analysis.LienardCycles.IntervalInverse +OAI.Analysis.LienardCycles.LocalExcursion +OAI.Analysis.LienardCycles.Main +OAI.Analysis.LienardCycles.MixedDerivatives +OAI.Analysis.LienardCycles.Model +OAI.Analysis.LienardCycles.ModelAlgebra +OAI.Analysis.LienardCycles.ModelEndpoint +OAI.Analysis.LienardCycles.ModelScaling +OAI.Analysis.LienardCycles.MonotoneIntegral +OAI.Analysis.LienardCycles.OpenArch +OAI.Analysis.LienardCycles.OpenArchAxis +OAI.Analysis.LienardCycles.OriginalProfile +OAI.Analysis.LienardCycles.OvalMatching +OAI.Analysis.LienardCycles.ParameterVariation +OAI.Analysis.LienardCycles.PartialCalculus +OAI.Analysis.LienardCycles.PeriodicBasics +OAI.Analysis.LienardCycles.PeriodicMatching +OAI.Analysis.LienardCycles.PeriodicOval +OAI.Analysis.LienardCycles.PeriodicSymmetry +OAI.Analysis.LienardCycles.PhysicalFlow +OAI.Analysis.LienardCycles.PolynomialModel +OAI.Analysis.LienardCycles.PositiveArcs +OAI.Analysis.LienardCycles.PositiveBase +OAI.Analysis.LienardCycles.PositiveCanonical +OAI.Analysis.LienardCycles.PositiveEndpoints +OAI.Analysis.LienardCycles.PositiveFit +OAI.Analysis.LienardCycles.PositiveParabolic +OAI.Analysis.LienardCycles.PositiveScaling +OAI.Analysis.LienardCycles.PositiveSymmetries +OAI.Analysis.LienardCycles.PositiveTransport +OAI.Analysis.LienardCycles.PositiveVariation +OAI.Analysis.LienardCycles.PositiveWidth +OAI.Analysis.LienardCycles.PositiveZero +OAI.Analysis.LienardCycles.ProfileComparison +OAI.Analysis.LienardCycles.ProfileDerivatives +OAI.Analysis.LienardCycles.QuadraticCoordinates +OAI.Analysis.LienardCycles.QuadraticDerivatives +OAI.Analysis.LienardCycles.QuadraticFit +OAI.Analysis.LienardCycles.QuadraticSlices +OAI.Analysis.LienardCycles.QuadraticVariation +OAI.Analysis.LienardCycles.QuadraticZero +OAI.Analysis.LienardCycles.RadiusLimits +OAI.Analysis.LienardCycles.RadiusSigns +OAI.Analysis.LienardCycles.RealAnalysis +OAI.Analysis.LienardCycles.RegionBarrier +OAI.Analysis.LienardCycles.ReturnMatching +OAI.Analysis.LienardCycles.ReturnNeighborhood +OAI.Analysis.LienardCycles.Riccati +OAI.Analysis.LienardCycles.RiccatiComparison +OAI.Analysis.LienardCycles.RiccatiDerivatives +OAI.Analysis.LienardCycles.RiccatiJets +OAI.Analysis.LienardCycles.ScalarArcs +OAI.Analysis.LienardCycles.ScalarComparison +OAI.Analysis.LienardCycles.ScaledActual +OAI.Analysis.LienardCycles.ScaledAlgebraic +OAI.Analysis.LienardCycles.ScaledCoefficients +OAI.Analysis.LienardCycles.ScaledDerivative +OAI.Analysis.LienardCycles.ScaledExpansion +OAI.Analysis.LienardCycles.Schwarzian +OAI.Analysis.LienardCycles.SchwarzianScaling +OAI.Analysis.LienardCycles.SecantIntegral +OAI.Analysis.LienardCycles.SharpCycles +OAI.Analysis.LienardCycles.SharpFlow +OAI.Analysis.LienardCycles.SharpPhysical +OAI.Analysis.LienardCycles.SharpReturn +OAI.Analysis.LienardCycles.SmoothFlow +OAI.Analysis.LienardCycles.SqrtPaths +OAI.Analysis.LienardCycles.StableExcursion +OAI.Analysis.LienardCycles.UpperAssembly +OAI.Analysis.LienardCycles.WidthCoordinates +OAI.Analysis.LienardCycles.WidthTransport +OAI.Analysis.LienardCycles.ZeroVariation diff --git a/tasks/quintic-lienard/solution/reference.py b/tasks/quintic-lienard/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/quintic-lienard/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/quintic-lienard/solution/solve.sh b/tasks/quintic-lienard/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..362b20a7af4fe623e6900ba8ce64fd82113057f0 --- /dev/null +++ b/tasks/quintic-lienard/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of QuinticLienard, i.e. module OAI.Analysis.LienardCycles.Main and the +# 146 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LienardCycles.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of QuinticLienard" diff --git a/tasks/quintic-lienard/task.toml b/tasks/quintic-lienard/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a90b482f4cf5de3dfbdb386f44b68987fb4b4686 --- /dev/null +++ b/tasks/quintic-lienard/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/quintic-lienard" +version = "1.0.0" +description = "Prove QuinticLienard (openai/math family 143: Uniform limit-cycle bounds in Hilbert's sixteenth problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/QuinticLienard.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "QuinticLienard" +family = "143" +family_title = "Uniform limit-cycle bounds in Hilbert's sixteenth problem" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.QuinticLienard.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LienardCycles.Main" +reference_modules = 146 +reference_lean_bytes = 816084 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1484 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12434 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/quintic-lienard/tests/Challenge.lean b/tasks/quintic-lienard/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..aaa3712a73aa86b4c6a7a0e0a6007eb62feb135a --- /dev/null +++ b/tasks/quintic-lienard/tests/Challenge.lean @@ -0,0 +1,46 @@ +import Mathlib + +namespace OAI + +namespace QuinticLienard + +abbrev Plane := ℝ × ℝ + +def vectorField (F : Polynomial ℝ) (z : Plane) : Plane := + (z.2 - F.eval z.1, -z.1) + +def IsSolution (F : Polynomial ℝ) (z : ℝ → Plane) : Prop := + ∀ t : ℝ, HasDerivAt z (vectorField F (z t)) t + +def IsPeriodicOrbit (F : Polynomial ℝ) (C : Set Plane) : Prop := + ∃ (z : ℝ → Plane) (T : ℝ), + IsSolution F z ∧ 0 < T ∧ Function.Periodic z T ∧ + (∃ s t : ℝ, z s ≠ z t) ∧ C = Set.range z + +def IsLimitCycle (F : Polynomial ℝ) (C : Set Plane) : Prop := + IsPeriodicOrbit F C ∧ + ∃ U : Set Plane, IsOpen U ∧ C ⊆ U ∧ + ∀ C' : Set Plane, IsPeriodicOrbit F C' → C' ⊆ U → C' = C + +open scoped Topology NNReal ContDiff Manifold +open Filter Set +open Set Filter Metric MeasureTheory +open scoped Topology NNReal ContDiff +open scoped Topology ENNReal +open Set Filter MeasureTheory +open Set Filter Asymptotics +open Set Filter Metric +open scoped Topology NNReal +open scoped Topology +open scoped Topology ContDiff +open Set Filter +open scoped Topology ContDiff NNReal + +theorem main : + (∀ F : Polynomial ℝ, F.degree ≤ 5 → {C : Set Plane | IsLimitCycle F C}.encard ≤ 2) ∧ + (∃ F : Polynomial ℝ, F.degree ≤ 5 ∧ {C : Set Plane | IsLimitCycle F C}.encard = 2) := by + sorry + +end QuinticLienard + +end OAI diff --git a/tasks/quintic-lienard/tests/grade.py b/tasks/quintic-lienard/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/quintic-lienard/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/quintic-lienard/tests/task.json b/tasks/quintic-lienard/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..32e48c1a375a625ca18916e4dd0b326b656577aa --- /dev/null +++ b/tasks/quintic-lienard/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "QuinticLienard", + "comparator": { + "theorem_names": [ + "OAI.QuinticLienard.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11534 +} \ No newline at end of file diff --git a/tasks/quintic-lienard/tests/test.sh b/tasks/quintic-lienard/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/quintic-lienard/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/radial-density-interval/environment/Dockerfile b/tasks/radial-density-interval/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/radial-density-interval/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/radial-density-interval/environment/fetch_mathlib.sh b/tasks/radial-density-interval/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/radial-density-interval/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/radial-density-interval/environment/lake-manifest.json b/tasks/radial-density-interval/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/radial-density-interval/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/radial-density-interval/environment/lakefile.lean b/tasks/radial-density-interval/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/radial-density-interval/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/radial-density-interval/environment/lean_setup.sh b/tasks/radial-density-interval/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/radial-density-interval/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/radial-density-interval/environment/pack_submission.py b/tasks/radial-density-interval/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/radial-density-interval/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/radial-density-interval/instruction.md b/tasks/radial-density-interval/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..78a9bcf5d7f2822b02f2009b2918ba19588d2bd7 --- /dev/null +++ b/tasks/radial-density-interval/instruction.md @@ -0,0 +1,123 @@ +# openai/math challenge `RadialDensityInterval` (family 228) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 228 of the release, *Continuum phase transitions for radial pair potentials* +(Probability and statistical mechanics). The family as a whole: Constructs stable distance-dependent pair interactions for three-dimensional classical particles with a first-order phase transition: the canonical free energy has a derivative jump at one inverse temperature throughout an open density interval. One potential has a divergent repulsive core; another is bounded and continuous with an integrable power-law tail, realizing the type of transition sought in Simon's continuum problem. + +The challenge is `RadialDensityInterval`, also at `/opt/openai-math/challenges/RadialDensityInterval.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators NNReal ContDiff ENNReal +open Filter MeasureTheory Set + +namespace RadialTransition + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Potential := ℝ≥0 → ℝ + +def cube (L : ℝ) : Set Position := + {x | ∀ k : Fin 3, 0 ≤ x k ∧ x k ≤ L} + +def configurationCube (L : ℝ) (N : ℕ) : Set (Fin N → Position) := + {x | ∀ i : Fin N, x i ∈ cube L} + +def energy (φ : Potential) {N : ℕ} (x : Fin N → Position) : ℝ := + ∑ i : Fin N, ∑ j : Fin N with i < j, φ (nndist (x i) (x j)) + +def partition (φ : Potential) (L : ℝ) (N : ℕ) (β : ℝ) : ℝ := + (N.factorial : ℝ)⁻¹ * + ∫ x in configurationCube L N, Real.exp (-β * energy φ x) + +def packingNumber (L : ℝ) : ℕ := + sSup {n : ℕ | ∃ X : Finset Position, X.card = n ∧ + (∀ x ∈ X, x ∈ cube L) ∧ + (∀ x ∈ X, ∀ y ∈ X, x ≠ y → 1 ≤ dist x y)} + +def IsPackingDensity (p : ℝ) : Prop := + Tendsto (fun L : ℝ => (packingNumber L : ℝ) / L ^ 3) atTop (nhds p) + +def IsBoundedPotential (φ : Potential) : Prop := + ∃ M : ℝ, 0 ≤ M ∧ ∀ r : ℝ≥0, |φ r| ≤ M + +def StableWith (φ : Potential) (B : ℝ) : Prop := + ∀ (N : ℕ) (x : Fin N → Position), -(B * N) ≤ energy φ x + +def AlgebraicDecayWith (φ : Potential) (C : ℝ) : Prop := + ∀ r : ℝ≥0, 1 ≤ r → |φ r| ≤ C * (r : ℝ) ^ (-(3 : ℝ) - 1 / 32) + +def IsCanonicalFreeEnergy (φ : Potential) (ρ : ℝ) (f : ℝ → ℝ) : Prop := + ∀ β : ℝ, 0 < β → + Tendsto (fun L : ℝ => + -(Real.log (partition φ L ⌊ρ * L ^ 3⌋₊ β) / (β * L ^ 3))) + atTop (nhds (f β)) + +def StrictTemperatureCorner (f : ℝ → ℝ) (βc : ℝ) : Prop := + ∃ dLeft dRight : ℝ, + HasDerivWithinAt f dLeft (Iic βc) βc ∧ + HasDerivWithinAt f dRight (Ici βc) βc ∧ + dRight < dLeft ∧ ¬DifferentiableAt ℝ f βc + +theorem densityInterval : + ∃ (p : ℝ) (φ : Potential) (B C η βc : ℝ) (f : ℝ → ℝ → ℝ), + 0 < p ∧ IsPackingDensity p ∧ + IsBoundedPotential φ ∧ Continuous φ ∧ + 0 < B ∧ 0 < C ∧ StableWith φ B ∧ AlgebraicDecayWith φ C ∧ + 0 < η ∧ Ioo (5*p/3 - η) (5*p/3 + η) ⊆ Ioi 0 ∧ + βc ∈ Icc (7/8:ℝ) (9/8) ∧ + ∀ ρ ∈ Ioo (5*p/3 - η) (5*p/3 + η), + IsCanonicalFreeEnergy φ ρ (fun β => f β ρ) ∧ + StrictTemperatureCorner (fun β => f β ρ) βc := by + sorry + +end RadialTransition +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RadialDensityInterval.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RadialTransition.densityInterval` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/radial-density-interval/solution/closure.txt b/tasks/radial-density-interval/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..085053318575e8b0b2ea504be51764bb09ef9e99 --- /dev/null +++ b/tasks/radial-density-interval/solution/closure.txt @@ -0,0 +1,104 @@ +OAI.Probability.RadialTransition.BadRemoval +OAI.Probability.RadialTransition.BoltzmannMeasure +OAI.Probability.RadialTransition.BoundedCore +OAI.Probability.RadialTransition.BoxEnsembles +OAI.Probability.RadialTransition.BoxPressure +OAI.Probability.RadialTransition.CanonicalCorner +OAI.Probability.RadialTransition.CanonicalCosts +OAI.Probability.RadialTransition.CanonicalDuality +OAI.Probability.RadialTransition.CanonicalLimit +OAI.Probability.RadialTransition.CellDifferences +OAI.Probability.RadialTransition.CellIntegral +OAI.Probability.RadialTransition.CellInteractions +OAI.Probability.RadialTransition.CellMoments +OAI.Probability.RadialTransition.CellStability +OAI.Probability.RadialTransition.ClusterConvolution +OAI.Probability.RadialTransition.ClusterEmbedding +OAI.Probability.RadialTransition.ClusterWeights +OAI.Probability.RadialTransition.ConfigurationMaps +OAI.Probability.RadialTransition.ConvolutionFock +OAI.Probability.RadialTransition.ConvolutionIntegral +OAI.Probability.RadialTransition.CoreConvergence +OAI.Probability.RadialTransition.CoreLocalLower +OAI.Probability.RadialTransition.CorePressureLower +OAI.Probability.RadialTransition.CorePressureUpper +OAI.Probability.RadialTransition.CoreUpper +OAI.Probability.RadialTransition.CountWeights +OAI.Probability.RadialTransition.CroppedCells +OAI.Probability.RadialTransition.DeletedInteractions +OAI.Probability.RadialTransition.DensityInterval +OAI.Probability.RadialTransition.DensityMixtures +OAI.Probability.RadialTransition.EnvelopeSupport +OAI.Probability.RadialTransition.FamilyControls +OAI.Probability.RadialTransition.FamilyIdeal +OAI.Probability.RadialTransition.FamilyStep +OAI.Probability.RadialTransition.FinitePartition +OAI.Probability.RadialTransition.FockIntegral +OAI.Probability.RadialTransition.FreeClusterCover +OAI.Probability.RadialTransition.FreeGeometry +OAI.Probability.RadialTransition.GrandBounds +OAI.Probability.RadialTransition.GrandPartition +OAI.Probability.RadialTransition.GridPressure +OAI.Probability.RadialTransition.IdealAttainment +OAI.Probability.RadialTransition.IdealAttraction +OAI.Probability.RadialTransition.IdealLimit +OAI.Probability.RadialTransition.IdealSupports +OAI.Probability.RadialTransition.IdealUniform +OAI.Probability.RadialTransition.InfiniteBall +OAI.Probability.RadialTransition.InitialSeparation +OAI.Probability.RadialTransition.InitialSlopes +OAI.Probability.RadialTransition.InteriorGrid +OAI.Probability.RadialTransition.KacComparison +OAI.Probability.RadialTransition.KacDeletion +OAI.Probability.RadialTransition.KacPressure +OAI.Probability.RadialTransition.KacVariational +OAI.Probability.RadialTransition.KernelError +OAI.Probability.RadialTransition.LatticeStability +OAI.Probability.RadialTransition.LinearInteractions +OAI.Probability.RadialTransition.MacroLower +OAI.Probability.RadialTransition.MacroRegions +OAI.Probability.RadialTransition.MacroUpper +OAI.Probability.RadialTransition.Main +OAI.Probability.RadialTransition.MeasurableEnergy +OAI.Probability.RadialTransition.MeasurableFock +OAI.Probability.RadialTransition.MeasurableProducts +OAI.Probability.RadialTransition.MixtureBounds +OAI.Probability.RadialTransition.Model +OAI.Probability.RadialTransition.MultiConvolution +OAI.Probability.RadialTransition.MultiScale +OAI.Probability.RadialTransition.MultisetEnergy +OAI.Probability.RadialTransition.OccupationMoments +OAI.Probability.RadialTransition.PackingBlob +OAI.Probability.RadialTransition.PackingLimit +OAI.Probability.RadialTransition.PairEnsembles +OAI.Probability.RadialTransition.ParameterPressure +OAI.Probability.RadialTransition.ParameterTools +OAI.Probability.RadialTransition.ParticleMeasure +OAI.Probability.RadialTransition.PartitionReplication +OAI.Probability.RadialTransition.PerturbationMoments +OAI.Probability.RadialTransition.PhaseGeometry +OAI.Probability.RadialTransition.PhysicalIteration +OAI.Probability.RadialTransition.PressureBall +OAI.Probability.RadialTransition.PressureContinuity +OAI.Probability.RadialTransition.ProductConfigurations +OAI.Probability.RadialTransition.ProductFock +OAI.Probability.RadialTransition.Propagation +OAI.Probability.RadialTransition.RadialKernel +OAI.Probability.RadialTransition.RangeBounds +OAI.Probability.RadialTransition.ScaleBudgets +OAI.Probability.RadialTransition.ScaleSequence +OAI.Probability.RadialTransition.ScaledKernels +OAI.Probability.RadialTransition.ShellGeometry +OAI.Probability.RadialTransition.SpatialProducts +OAI.Probability.RadialTransition.SpatialReplication +OAI.Probability.RadialTransition.SqrtGrid +OAI.Probability.RadialTransition.StarIntegral +OAI.Probability.RadialTransition.SupportControl +OAI.Probability.RadialTransition.SupportGeometry +OAI.Probability.RadialTransition.TetraGeometry +OAI.Probability.RadialTransition.TetraIntegral +OAI.Probability.RadialTransition.ThermodynamicLimit +OAI.Probability.RadialTransition.TruncatedFamily +OAI.Probability.RadialTransition.UniformConstants +OAI.Probability.RadialTransition.UniformKac +OAI.Probability.RadialTransition.WindowLipschitz diff --git a/tasks/radial-density-interval/solution/reference.py b/tasks/radial-density-interval/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/radial-density-interval/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/radial-density-interval/solution/solve.sh b/tasks/radial-density-interval/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fcc5a4e465785792b06a841088800c1573a361f9 --- /dev/null +++ b/tasks/radial-density-interval/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RadialDensityInterval, i.e. module OAI.Probability.RadialTransition.DensityInterval and the +# 104 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.RadialTransition.DensityInterval /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RadialDensityInterval" diff --git a/tasks/radial-density-interval/task.toml b/tasks/radial-density-interval/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0413418b0ef7c86e9a6d6786158440df854b4539 --- /dev/null +++ b/tasks/radial-density-interval/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/radial-density-interval" +version = "1.0.0" +description = "Prove RadialDensityInterval (openai/math family 228: Continuum phase transitions for radial pair potentials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RadialDensityInterval.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RadialDensityInterval" +family = "228" +family_title = "Continuum phase transitions for radial pair potentials" +subject = "Probability and statistical mechanics" +theorems = ["OAI.RadialTransition.densityInterval"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.RadialTransition.DensityInterval" +reference_modules = 104 +reference_lean_bytes = 698440 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1163 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12328 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/radial-density-interval/tests/Challenge.lean b/tasks/radial-density-interval/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a97c1f21da4d92225d2bb3edf54061d318447786 --- /dev/null +++ b/tasks/radial-density-interval/tests/Challenge.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators NNReal ContDiff ENNReal +open Filter MeasureTheory Set + +namespace RadialTransition + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Potential := ℝ≥0 → ℝ + +def cube (L : ℝ) : Set Position := + {x | ∀ k : Fin 3, 0 ≤ x k ∧ x k ≤ L} + +def configurationCube (L : ℝ) (N : ℕ) : Set (Fin N → Position) := + {x | ∀ i : Fin N, x i ∈ cube L} + +def energy (φ : Potential) {N : ℕ} (x : Fin N → Position) : ℝ := + ∑ i : Fin N, ∑ j : Fin N with i < j, φ (nndist (x i) (x j)) + +def partition (φ : Potential) (L : ℝ) (N : ℕ) (β : ℝ) : ℝ := + (N.factorial : ℝ)⁻¹ * + ∫ x in configurationCube L N, Real.exp (-β * energy φ x) + +def packingNumber (L : ℝ) : ℕ := + sSup {n : ℕ | ∃ X : Finset Position, X.card = n ∧ + (∀ x ∈ X, x ∈ cube L) ∧ + (∀ x ∈ X, ∀ y ∈ X, x ≠ y → 1 ≤ dist x y)} + +def IsPackingDensity (p : ℝ) : Prop := + Tendsto (fun L : ℝ => (packingNumber L : ℝ) / L ^ 3) atTop (nhds p) + +def IsBoundedPotential (φ : Potential) : Prop := + ∃ M : ℝ, 0 ≤ M ∧ ∀ r : ℝ≥0, |φ r| ≤ M + +def StableWith (φ : Potential) (B : ℝ) : Prop := + ∀ (N : ℕ) (x : Fin N → Position), -(B * N) ≤ energy φ x + +def AlgebraicDecayWith (φ : Potential) (C : ℝ) : Prop := + ∀ r : ℝ≥0, 1 ≤ r → |φ r| ≤ C * (r : ℝ) ^ (-(3 : ℝ) - 1 / 32) + +def IsCanonicalFreeEnergy (φ : Potential) (ρ : ℝ) (f : ℝ → ℝ) : Prop := + ∀ β : ℝ, 0 < β → + Tendsto (fun L : ℝ => + -(Real.log (partition φ L ⌊ρ * L ^ 3⌋₊ β) / (β * L ^ 3))) + atTop (nhds (f β)) + +def StrictTemperatureCorner (f : ℝ → ℝ) (βc : ℝ) : Prop := + ∃ dLeft dRight : ℝ, + HasDerivWithinAt f dLeft (Iic βc) βc ∧ + HasDerivWithinAt f dRight (Ici βc) βc ∧ + dRight < dLeft ∧ ¬DifferentiableAt ℝ f βc + +theorem densityInterval : + ∃ (p : ℝ) (φ : Potential) (B C η βc : ℝ) (f : ℝ → ℝ → ℝ), + 0 < p ∧ IsPackingDensity p ∧ + IsBoundedPotential φ ∧ Continuous φ ∧ + 0 < B ∧ 0 < C ∧ StableWith φ B ∧ AlgebraicDecayWith φ C ∧ + 0 < η ∧ Ioo (5*p/3 - η) (5*p/3 + η) ⊆ Ioi 0 ∧ + βc ∈ Icc (7/8:ℝ) (9/8) ∧ + ∀ ρ ∈ Ioo (5*p/3 - η) (5*p/3 + η), + IsCanonicalFreeEnergy φ ρ (fun β => f β ρ) ∧ + StrictTemperatureCorner (fun β => f β ρ) βc := by + sorry + +end RadialTransition +end + +end OAI diff --git a/tasks/radial-density-interval/tests/grade.py b/tasks/radial-density-interval/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/radial-density-interval/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/radial-density-interval/tests/task.json b/tasks/radial-density-interval/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6f46ec1d38ee442652f5304440f698cae409f0f7 --- /dev/null +++ b/tasks/radial-density-interval/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RadialDensityInterval", + "comparator": { + "theorem_names": [ + "OAI.RadialTransition.densityInterval" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11428 +} \ No newline at end of file diff --git a/tasks/radial-density-interval/tests/test.sh b/tasks/radial-density-interval/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/radial-density-interval/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/radial-transition/environment/Dockerfile b/tasks/radial-transition/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/radial-transition/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/radial-transition/environment/fetch_mathlib.sh b/tasks/radial-transition/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/radial-transition/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/radial-transition/environment/lake-manifest.json b/tasks/radial-transition/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/radial-transition/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/radial-transition/environment/lakefile.lean b/tasks/radial-transition/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/radial-transition/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/radial-transition/environment/lean_setup.sh b/tasks/radial-transition/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/radial-transition/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/radial-transition/environment/pack_submission.py b/tasks/radial-transition/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/radial-transition/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/radial-transition/instruction.md b/tasks/radial-transition/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a5adaf4689527fa37d235bd4e06dbaf80b7406a5 --- /dev/null +++ b/tasks/radial-transition/instruction.md @@ -0,0 +1,121 @@ +# openai/math challenge `RadialTransition` (family 228) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 228 of the release, *Continuum phase transitions for radial pair potentials* +(Probability and statistical mechanics). The family as a whole: Constructs stable distance-dependent pair interactions for three-dimensional classical particles with a first-order phase transition: the canonical free energy has a derivative jump at one inverse temperature throughout an open density interval. One potential has a divergent repulsive core; another is bounded and continuous with an integrable power-law tail, realizing the type of transition sought in Simon's continuum problem. + +The challenge is `RadialTransition`, also at `/opt/openai-math/challenges/RadialTransition.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators NNReal +open Filter MeasureTheory Set + +namespace RadialTransition + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Potential := ℝ≥0 → ℝ + +def cube (L : ℝ) : Set Position := + {x | ∀ k : Fin 3, 0 ≤ x k ∧ x k ≤ L} + +def configurationCube (L : ℝ) (N : ℕ) : Set (Fin N → Position) := + {x | ∀ i : Fin N, x i ∈ cube L} + +def energy (φ : Potential) {N : ℕ} (x : Fin N → Position) : ℝ := + ∑ i : Fin N, ∑ j : Fin N with i < j, φ (nndist (x i) (x j)) + +def partition (φ : Potential) (L : ℝ) (N : ℕ) (β : ℝ) : ℝ := + (N.factorial : ℝ)⁻¹ * + ∫ x in configurationCube L N, Real.exp (-β * energy φ x) + +def packingNumber (L : ℝ) : ℕ := + sSup {n : ℕ | ∃ X : Finset Position, X.card = n ∧ + (∀ x ∈ X, x ∈ cube L) ∧ + (∀ x ∈ X, ∀ y ∈ X, x ≠ y → 1 ≤ dist x y)} + +def IsPackingDensity (p : ℝ) : Prop := + Tendsto (fun L : ℝ => (packingNumber L : ℝ) / L ^ 3) atTop (nhds p) + +def IsBoundedPotential (φ : Potential) : Prop := + ∃ M : ℝ, 0 ≤ M ∧ ∀ r : ℝ≥0, |φ r| ≤ M + +def StableWith (φ : Potential) (B : ℝ) : Prop := + ∀ (N : ℕ) (x : Fin N → Position), -(B * N) ≤ energy φ x + +def AlgebraicDecayWith (φ : Potential) (C : ℝ) : Prop := + ∀ r : ℝ≥0, 1 ≤ r → |φ r| ≤ C * (r : ℝ) ^ (-(3 : ℝ) - 1 / 32) + +def IsCanonicalFreeEnergy (φ : Potential) (ρ : ℝ) (f : ℝ → ℝ) : Prop := + ∀ β : ℝ, 0 < β → + Tendsto (fun L : ℝ => + -(Real.log (partition φ L ⌊ρ * L ^ 3⌋₊ β) / (β * L ^ 3))) + atTop (nhds (f β)) + +def StrictTemperatureCorner (f : ℝ → ℝ) (βc : ℝ) : Prop := + ∃ dLeft dRight : ℝ, + HasDerivWithinAt f dLeft (Iic βc) βc ∧ + HasDerivWithinAt f dRight (Ici βc) βc ∧ + dRight < dLeft ∧ ¬DifferentiableAt ℝ f βc + +theorem main : + ∃ (p : ℝ) (φ : Potential) (B C : ℝ) (f : ℝ → ℝ) (βc : ℝ), + 0 < p ∧ IsPackingDensity p ∧ + IsBoundedPotential φ ∧ Continuous φ ∧ + 0 < B ∧ 0 < C ∧ StableWith φ B ∧ AlgebraicDecayWith φ C ∧ + IsCanonicalFreeEnergy φ (5*p/3) f ∧ + βc ∈ Icc (7/8:ℝ) (9/8) ∧ StrictTemperatureCorner f βc := by + sorry + +end RadialTransition + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RadialTransition.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RadialTransition.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/radial-transition/solution/closure.txt b/tasks/radial-transition/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..46adb68bb39bbf06feb4028ae1319474e8223324 --- /dev/null +++ b/tasks/radial-transition/solution/closure.txt @@ -0,0 +1,103 @@ +OAI.Probability.RadialTransition.BadRemoval +OAI.Probability.RadialTransition.BoltzmannMeasure +OAI.Probability.RadialTransition.BoundedCore +OAI.Probability.RadialTransition.BoxEnsembles +OAI.Probability.RadialTransition.BoxPressure +OAI.Probability.RadialTransition.CanonicalCorner +OAI.Probability.RadialTransition.CanonicalCosts +OAI.Probability.RadialTransition.CanonicalDuality +OAI.Probability.RadialTransition.CanonicalLimit +OAI.Probability.RadialTransition.CellDifferences +OAI.Probability.RadialTransition.CellIntegral +OAI.Probability.RadialTransition.CellInteractions +OAI.Probability.RadialTransition.CellMoments +OAI.Probability.RadialTransition.CellStability +OAI.Probability.RadialTransition.ClusterConvolution +OAI.Probability.RadialTransition.ClusterEmbedding +OAI.Probability.RadialTransition.ClusterWeights +OAI.Probability.RadialTransition.ConfigurationMaps +OAI.Probability.RadialTransition.ConvolutionFock +OAI.Probability.RadialTransition.ConvolutionIntegral +OAI.Probability.RadialTransition.CoreConvergence +OAI.Probability.RadialTransition.CoreLocalLower +OAI.Probability.RadialTransition.CorePressureLower +OAI.Probability.RadialTransition.CorePressureUpper +OAI.Probability.RadialTransition.CoreUpper +OAI.Probability.RadialTransition.CountWeights +OAI.Probability.RadialTransition.CroppedCells +OAI.Probability.RadialTransition.DeletedInteractions +OAI.Probability.RadialTransition.DensityMixtures +OAI.Probability.RadialTransition.EnvelopeSupport +OAI.Probability.RadialTransition.FamilyControls +OAI.Probability.RadialTransition.FamilyIdeal +OAI.Probability.RadialTransition.FamilyStep +OAI.Probability.RadialTransition.FinitePartition +OAI.Probability.RadialTransition.FockIntegral +OAI.Probability.RadialTransition.FreeClusterCover +OAI.Probability.RadialTransition.FreeGeometry +OAI.Probability.RadialTransition.GrandBounds +OAI.Probability.RadialTransition.GrandPartition +OAI.Probability.RadialTransition.GridPressure +OAI.Probability.RadialTransition.IdealAttainment +OAI.Probability.RadialTransition.IdealAttraction +OAI.Probability.RadialTransition.IdealLimit +OAI.Probability.RadialTransition.IdealSupports +OAI.Probability.RadialTransition.IdealUniform +OAI.Probability.RadialTransition.InfiniteBall +OAI.Probability.RadialTransition.InitialSeparation +OAI.Probability.RadialTransition.InitialSlopes +OAI.Probability.RadialTransition.InteriorGrid +OAI.Probability.RadialTransition.KacComparison +OAI.Probability.RadialTransition.KacDeletion +OAI.Probability.RadialTransition.KacPressure +OAI.Probability.RadialTransition.KacVariational +OAI.Probability.RadialTransition.KernelError +OAI.Probability.RadialTransition.LatticeStability +OAI.Probability.RadialTransition.LinearInteractions +OAI.Probability.RadialTransition.MacroLower +OAI.Probability.RadialTransition.MacroRegions +OAI.Probability.RadialTransition.MacroUpper +OAI.Probability.RadialTransition.Main +OAI.Probability.RadialTransition.MeasurableEnergy +OAI.Probability.RadialTransition.MeasurableFock +OAI.Probability.RadialTransition.MeasurableProducts +OAI.Probability.RadialTransition.MixtureBounds +OAI.Probability.RadialTransition.Model +OAI.Probability.RadialTransition.MultiConvolution +OAI.Probability.RadialTransition.MultiScale +OAI.Probability.RadialTransition.MultisetEnergy +OAI.Probability.RadialTransition.OccupationMoments +OAI.Probability.RadialTransition.PackingBlob +OAI.Probability.RadialTransition.PackingLimit +OAI.Probability.RadialTransition.PairEnsembles +OAI.Probability.RadialTransition.ParameterPressure +OAI.Probability.RadialTransition.ParameterTools +OAI.Probability.RadialTransition.ParticleMeasure +OAI.Probability.RadialTransition.PartitionReplication +OAI.Probability.RadialTransition.PerturbationMoments +OAI.Probability.RadialTransition.PhaseGeometry +OAI.Probability.RadialTransition.PhysicalIteration +OAI.Probability.RadialTransition.PressureBall +OAI.Probability.RadialTransition.PressureContinuity +OAI.Probability.RadialTransition.ProductConfigurations +OAI.Probability.RadialTransition.ProductFock +OAI.Probability.RadialTransition.Propagation +OAI.Probability.RadialTransition.RadialKernel +OAI.Probability.RadialTransition.RangeBounds +OAI.Probability.RadialTransition.ScaleBudgets +OAI.Probability.RadialTransition.ScaleSequence +OAI.Probability.RadialTransition.ScaledKernels +OAI.Probability.RadialTransition.ShellGeometry +OAI.Probability.RadialTransition.SpatialProducts +OAI.Probability.RadialTransition.SpatialReplication +OAI.Probability.RadialTransition.SqrtGrid +OAI.Probability.RadialTransition.StarIntegral +OAI.Probability.RadialTransition.SupportControl +OAI.Probability.RadialTransition.SupportGeometry +OAI.Probability.RadialTransition.TetraGeometry +OAI.Probability.RadialTransition.TetraIntegral +OAI.Probability.RadialTransition.ThermodynamicLimit +OAI.Probability.RadialTransition.TruncatedFamily +OAI.Probability.RadialTransition.UniformConstants +OAI.Probability.RadialTransition.UniformKac +OAI.Probability.RadialTransition.WindowLipschitz diff --git a/tasks/radial-transition/solution/reference.py b/tasks/radial-transition/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/radial-transition/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/radial-transition/solution/solve.sh b/tasks/radial-transition/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6b928f55ea99f5e675c68e3d28abdaed5bae2b9d --- /dev/null +++ b/tasks/radial-transition/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RadialTransition, i.e. module OAI.Probability.RadialTransition.Main and the +# 103 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.RadialTransition.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RadialTransition" diff --git a/tasks/radial-transition/task.toml b/tasks/radial-transition/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..64f0a8a0c787cf0143504a91a36e2291c606c8d6 --- /dev/null +++ b/tasks/radial-transition/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/radial-transition" +version = "1.0.0" +description = "Prove RadialTransition (openai/math family 228: Continuum phase transitions for radial pair potentials) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RadialTransition.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RadialTransition" +family = "228" +family_title = "Continuum phase transitions for radial pair potentials" +subject = "Probability and statistical mechanics" +theorems = ["OAI.RadialTransition.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.RadialTransition.Main" +reference_modules = 103 +reference_lean_bytes = 693070 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1222 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12323 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/radial-transition/tests/Challenge.lean b/tasks/radial-transition/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..09f994133923301f8ed387a7238a877ebeeeca58 --- /dev/null +++ b/tasks/radial-transition/tests/Challenge.lean @@ -0,0 +1,70 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators NNReal +open Filter MeasureTheory Set + +namespace RadialTransition + +abbrev Position := EuclideanSpace ℝ (Fin 3) +abbrev Potential := ℝ≥0 → ℝ + +def cube (L : ℝ) : Set Position := + {x | ∀ k : Fin 3, 0 ≤ x k ∧ x k ≤ L} + +def configurationCube (L : ℝ) (N : ℕ) : Set (Fin N → Position) := + {x | ∀ i : Fin N, x i ∈ cube L} + +def energy (φ : Potential) {N : ℕ} (x : Fin N → Position) : ℝ := + ∑ i : Fin N, ∑ j : Fin N with i < j, φ (nndist (x i) (x j)) + +def partition (φ : Potential) (L : ℝ) (N : ℕ) (β : ℝ) : ℝ := + (N.factorial : ℝ)⁻¹ * + ∫ x in configurationCube L N, Real.exp (-β * energy φ x) + +def packingNumber (L : ℝ) : ℕ := + sSup {n : ℕ | ∃ X : Finset Position, X.card = n ∧ + (∀ x ∈ X, x ∈ cube L) ∧ + (∀ x ∈ X, ∀ y ∈ X, x ≠ y → 1 ≤ dist x y)} + +def IsPackingDensity (p : ℝ) : Prop := + Tendsto (fun L : ℝ => (packingNumber L : ℝ) / L ^ 3) atTop (nhds p) + +def IsBoundedPotential (φ : Potential) : Prop := + ∃ M : ℝ, 0 ≤ M ∧ ∀ r : ℝ≥0, |φ r| ≤ M + +def StableWith (φ : Potential) (B : ℝ) : Prop := + ∀ (N : ℕ) (x : Fin N → Position), -(B * N) ≤ energy φ x + +def AlgebraicDecayWith (φ : Potential) (C : ℝ) : Prop := + ∀ r : ℝ≥0, 1 ≤ r → |φ r| ≤ C * (r : ℝ) ^ (-(3 : ℝ) - 1 / 32) + +def IsCanonicalFreeEnergy (φ : Potential) (ρ : ℝ) (f : ℝ → ℝ) : Prop := + ∀ β : ℝ, 0 < β → + Tendsto (fun L : ℝ => + -(Real.log (partition φ L ⌊ρ * L ^ 3⌋₊ β) / (β * L ^ 3))) + atTop (nhds (f β)) + +def StrictTemperatureCorner (f : ℝ → ℝ) (βc : ℝ) : Prop := + ∃ dLeft dRight : ℝ, + HasDerivWithinAt f dLeft (Iic βc) βc ∧ + HasDerivWithinAt f dRight (Ici βc) βc ∧ + dRight < dLeft ∧ ¬DifferentiableAt ℝ f βc + +theorem main : + ∃ (p : ℝ) (φ : Potential) (B C : ℝ) (f : ℝ → ℝ) (βc : ℝ), + 0 < p ∧ IsPackingDensity p ∧ + IsBoundedPotential φ ∧ Continuous φ ∧ + 0 < B ∧ 0 < C ∧ StableWith φ B ∧ AlgebraicDecayWith φ C ∧ + IsCanonicalFreeEnergy φ (5*p/3) f ∧ + βc ∈ Icc (7/8:ℝ) (9/8) ∧ StrictTemperatureCorner f βc := by + sorry + +end RadialTransition + +end + +end OAI diff --git a/tasks/radial-transition/tests/grade.py b/tasks/radial-transition/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/radial-transition/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/radial-transition/tests/task.json b/tasks/radial-transition/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d959a39e230bfeeb6a0272c4c8468a2b4b653125 --- /dev/null +++ b/tasks/radial-transition/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RadialTransition", + "comparator": { + "theorem_names": [ + "OAI.RadialTransition.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11423 +} \ No newline at end of file diff --git a/tasks/radial-transition/tests/test.sh b/tasks/radial-transition/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/radial-transition/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/randomized-mean-payoff/environment/Dockerfile b/tasks/randomized-mean-payoff/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/randomized-mean-payoff/environment/fetch_mathlib.sh b/tasks/randomized-mean-payoff/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/randomized-mean-payoff/environment/lake-manifest.json b/tasks/randomized-mean-payoff/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/randomized-mean-payoff/environment/lakefile.lean b/tasks/randomized-mean-payoff/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/randomized-mean-payoff/environment/lean_setup.sh b/tasks/randomized-mean-payoff/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/randomized-mean-payoff/environment/pack_submission.py b/tasks/randomized-mean-payoff/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/randomized-mean-payoff/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/randomized-mean-payoff/instruction.md b/tasks/randomized-mean-payoff/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e8e83887b2cda3a40ca1f5577133ff6571b5c3b6 --- /dev/null +++ b/tasks/randomized-mean-payoff/instruction.md @@ -0,0 +1,177 @@ +# openai/math challenge `RandomizedMeanPayoff` (family 104) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 104 of the release, *Quasipolynomial algorithms for mean-payoff, stochastic and parity games* +(Theoretical computer science). The family as a whole: Gives deterministic algorithms using $2^{O((\log(L+2))^2)}$ bit operations, for complete binary input length $L$, for ordinary mean-payoff games and two separate extensions. They compute exact values and optimal positional strategies in ordinary games, the nonnegative expectation-of-liminf value set in turn-based stochastic games, and the winning set for nonnegative liminf mean payoff conjoined with parity. Signed rewards, rational chance probabilities, and parity priorities are unrestricted and binary-encoded. + +The challenge is `RandomizedMeanPayoff`, also at `/opt/openai-math/challenges/RandomizedMeanPayoff.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace MeanPayoff +structure Game where + n : ℕ + positive : 0 < n + m : ℕ + tail : Fin m → Fin n + head : Fin m → Fin n + maxOwner : Fin n → Bool + weight : Fin m → ℤ + total : ∀ v : Fin n, ∃ e : Fin m, tail e = v + +def Strategy (G : Game) := + List (Fin G.m) → (v : Fin G.n) → {e : Fin G.m // G.tail e = v} + +def move (G : Game) (σ τ : Strategy G) (v : Fin G.n) + (history : List (Fin G.m)) : Fin G.m := + if G.maxOwner v then (σ history v).val else (τ history v).val + +def position (G : Game) (σ τ : Strategy G) (start : Fin G.n) : + ℕ → Fin G.n × List (Fin G.m) + | 0 => (start, []) + | t + 1 => + let p := position G σ τ start t + let e := move G σ τ p.1 p.2 + (G.head e, p.2 ++ [e]) + +def play (G : Game) (σ τ : Strategy G) (start : Fin G.n) (t : ℕ) : Fin G.m := + let p := position G σ τ start t + move G σ τ p.1 p.2 + +noncomputable def meanPayoff (G : Game) (π : ℕ → Fin G.m) : ℝ := + Filter.liminf (fun T : ℕ => + (∑ j ∈ Finset.range T, (G.weight (π j) : ℝ)) / (T : ℝ)) Filter.atTop + +def Winning (G : Game) (v : Fin G.n) : Prop := + ∃ σ : Strategy G, ∀ τ : Strategy G, 0 ≤ meanPayoff G (play G σ τ v) + +def encodeNat (n : ℕ) : List Bool := + let bits := Nat.bits (n + 1) + List.replicate bits.length true ++ [false] ++ bits + +def encodeInt (z : ℤ) : List Bool := + decide (z < 0) :: encodeNat z.natAbs + +def input (G : Game) : List Bool := + encodeNat G.n ++ encodeNat G.m ++ List.ofFn G.maxOwner ++ + (List.ofFn (fun e : Fin G.m => + encodeNat ((G.tail e).val + 1) ++ encodeNat ((G.head e).val + 1) ++ + encodeInt (G.weight e))).flatten + +abbrev Symbol := Option Bool + +inductive Direction where + | left | stay | right + deriving DecidableEq + +def Direction.offset : Direction → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Action (q : ℕ) where + next : Fin q + write : Fin 3 → Symbol + shift : Fin 3 → Direction + +structure Machine where + states : ℕ + start : Fin states + transition : Fin states → (Fin 3 → Symbol) → Bool → Option (Action states) + +structure Configuration (M : Machine) where + control : Option (Fin M.states) + head : Fin 3 → ℤ + tape : Fin 3 → ℤ → Symbol + +def initial (M : Machine) (code : List Bool) : Configuration M where + control := some M.start + head := fun _ => 0 + tape := fun k j => if k = 0 ∧ 0 ≤ j then code[j.toNat]? else none + +def step (M : Machine) (c : Configuration M) (bit : Bool) : Configuration M := + match c.control with + | none => c + | some s => + match M.transition s (fun k => c.tape k (c.head k)) bit with + | none => { c with control := none } + | some a => + { control := some a.next + head := fun k => c.head k + (a.shift k).offset + tape := fun k => Function.update (c.tape k) (c.head k) (a.write k) } + +def run (M : Machine) (code : List Bool) (random : ℕ → Bool) : ℕ → Configuration M + | 0 => initial M code + | t + 1 => step M (run M code random t) (random t) + +def padBits {T : ℕ} (bits : Fin T → Bool) (j : ℕ) : Bool := + if h : j < T then bits ⟨j, h⟩ else false + +def result (M : Machine) (G : Game) (T : ℕ) (bits : Fin T → Bool) : Configuration M := + run M (input G) (padBits bits) T + +def CorrectOutput (G : Game) {M : Machine} (c : Configuration M) : Prop := + c.control = none ∧ + (∀ v : Fin G.n, c.tape 2 (v.val : ℤ) = some true ↔ Winning G v) ∧ + (∀ v : Fin G.n, c.tape 2 (v.val : ℤ) = some false ↔ ¬ Winning G v) ∧ + ∀ j : ℤ, (j < 0 ∨ (G.n : ℤ) ≤ j) → c.tape 2 j = none + +noncomputable def MainClaim : Prop := by + classical + exact ∃ M : Machine, ∃ C : ℝ, 0 < C ∧ ∀ G : Game, ∃ T : ℕ, + (T : ℝ) ≤ (2 : ℝ) ^ (C * (Real.logb 2 ((input G).length + 2)) ^ 2) ∧ + (∀ bits : Fin T → Bool, (result M G T bits).control = none) ∧ + 7 * 2 ^ T ≤ 8 * (Finset.univ.filter + (fun bits : Fin T → Bool => CorrectOutput G (result M G T bits))).card + +end MeanPayoff + +theorem randomized_quasipolynomial_mean_payoff : MeanPayoff.MainClaim := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RandomizedMeanPayoff.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.randomized_quasipolynomial_mean_payoff` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/randomized-mean-payoff/solution/closure.txt b/tasks/randomized-mean-payoff/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2a23260ed169673382f088358cf5aa3f267289bb --- /dev/null +++ b/tasks/randomized-mean-payoff/solution/closure.txt @@ -0,0 +1,89 @@ +OAI.Computability.MeanPayoff.Allocation +OAI.Computability.MeanPayoff.Alternatives +OAI.Computability.MeanPayoff.ArenaParsing +OAI.Computability.MeanPayoff.Arithmetic +OAI.Computability.MeanPayoff.ArithmeticBounds +OAI.Computability.MeanPayoff.ArithmeticDevices +OAI.Computability.MeanPayoff.BatchDevices +OAI.Computability.MeanPayoff.BinaryData +OAI.Computability.MeanPayoff.BitDepth +OAI.Computability.MeanPayoff.BitProgram +OAI.Computability.MeanPayoff.Budgets +OAI.Computability.MeanPayoff.CallBounds +OAI.Computability.MeanPayoff.Comparison +OAI.Computability.MeanPayoff.CountedRecursion +OAI.Computability.MeanPayoff.CountedTraversal +OAI.Computability.MeanPayoff.Counters +OAI.Computability.MeanPayoff.Decoding +OAI.Computability.MeanPayoff.Deviation +OAI.Computability.MeanPayoff.Drift +OAI.Computability.MeanPayoff.Driver +OAI.Computability.MeanPayoff.DriverExecution +OAI.Computability.MeanPayoff.EncodedArithmetic +OAI.Computability.MeanPayoff.EncodedPrograms +OAI.Computability.MeanPayoff.ErrorBounds +OAI.Computability.MeanPayoff.FiniteBox +OAI.Computability.MeanPayoff.FiniteIteration +OAI.Computability.MeanPayoff.FiniteSuccess +OAI.Computability.MeanPayoff.FiniteTrees +OAI.Computability.MeanPayoff.GridLabels +OAI.Computability.MeanPayoff.InputCode +OAI.Computability.MeanPayoff.InputSize +OAI.Computability.MeanPayoff.Instructions +OAI.Computability.MeanPayoff.Labeller +OAI.Computability.MeanPayoff.LoopDevices +OAI.Computability.MeanPayoff.Main +OAI.Computability.MeanPayoff.Model +OAI.Computability.MeanPayoff.Normalization +OAI.Computability.MeanPayoff.Online +OAI.Computability.MeanPayoff.OperatorCosts +OAI.Computability.MeanPayoff.OperatorDevices +OAI.Computability.MeanPayoff.Orientation +OAI.Computability.MeanPayoff.Packets +OAI.Computability.MeanPayoff.ParserCosts +OAI.Computability.MeanPayoff.Pivots +OAI.Computability.MeanPayoff.PolynomialCosts +OAI.Computability.MeanPayoff.Potential +OAI.Computability.MeanPayoff.Preparation +OAI.Computability.MeanPayoff.Probability +OAI.Computability.MeanPayoff.RawLabels +OAI.Computability.MeanPayoff.RawMass +OAI.Computability.MeanPayoff.RawSolutions +OAI.Computability.MeanPayoff.Realizer +OAI.Computability.MeanPayoff.Recursion +OAI.Computability.MeanPayoff.RecursiveExecution +OAI.Computability.MeanPayoff.Registers +OAI.Computability.MeanPayoff.RootBox +OAI.Computability.MeanPayoff.Sampling +OAI.Computability.MeanPayoff.SignedBits +OAI.Computability.MeanPayoff.Simulation +OAI.Computability.MeanPayoff.SizeBounds +OAI.Computability.MeanPayoff.Sorting +OAI.Computability.MeanPayoff.Stack +OAI.Computability.MeanPayoff.StackMacros +OAI.Computability.MeanPayoff.StackSimulation +OAI.Computability.MeanPayoff.Tightening +OAI.Computability.MeanPayoff.Traversal +OAI.Computability.MeanPayoff.TreeCopy +OAI.Computability.MeanPayoff.TreeDevices +OAI.Computability.MeanPayoff.VectorDevices +OAI.Computability.MeanPayoff.Volume +OAI.Computability.MeanPayoff.WinnerCorrespondence +OAI.Computability.MeanPayoff.WordDecoding +OAI.Computability.RandomMean.Allocation +OAI.Computability.RandomMean.Chunks +OAI.Computability.RandomMean.Complexity +OAI.Computability.RandomMean.Control +OAI.Computability.RandomMean.ControlCorrectness +OAI.Computability.RandomMean.DispatchBounds +OAI.Computability.RandomMean.Growth +OAI.Computability.RandomMean.InputBounds +OAI.Computability.RandomMean.Loop +OAI.Computability.RandomMean.Main +OAI.Computability.RandomMean.Orientation +OAI.Computability.RandomMean.Preparation +OAI.Computability.RandomMean.RandomTables +OAI.Computability.RandomMean.Realizer +OAI.Computability.RandomMean.SizeBounds +OAI.Computability.RandomMean.StateGrowth +OAI.Computability.RandomMean.Traces diff --git a/tasks/randomized-mean-payoff/solution/reference.py b/tasks/randomized-mean-payoff/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/randomized-mean-payoff/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/randomized-mean-payoff/solution/solve.sh b/tasks/randomized-mean-payoff/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b25fef2567047b6d10e857f7daf82c6a2e312ab0 --- /dev/null +++ b/tasks/randomized-mean-payoff/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RandomizedMeanPayoff, i.e. module OAI.Computability.RandomMean.Main and the +# 89 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.RandomMean.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RandomizedMeanPayoff" diff --git a/tasks/randomized-mean-payoff/task.toml b/tasks/randomized-mean-payoff/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c6f2543973bdc204c232d6d5b10305faa495ff32 --- /dev/null +++ b/tasks/randomized-mean-payoff/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/randomized-mean-payoff" +version = "1.0.0" +description = "Prove RandomizedMeanPayoff (openai/math family 104: Quasipolynomial algorithms for mean-payoff, stochastic and parity games) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RandomizedMeanPayoff.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RandomizedMeanPayoff" +family = "104" +family_title = "Quasipolynomial algorithms for mean-payoff, stochastic and parity games" +subject = "Theoretical computer science" +theorems = ["OAI.randomized_quasipolynomial_mean_payoff"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.RandomMean.Main" +reference_modules = 89 +reference_lean_bytes = 1301045 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1082 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12870 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/randomized-mean-payoff/tests/Challenge.lean b/tasks/randomized-mean-payoff/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..cc70577163b98c4489466ec919a6985ee03397f1 --- /dev/null +++ b/tasks/randomized-mean-payoff/tests/Challenge.lean @@ -0,0 +1,126 @@ +import Mathlib + +namespace OAI + +namespace MeanPayoff +structure Game where + n : ℕ + positive : 0 < n + m : ℕ + tail : Fin m → Fin n + head : Fin m → Fin n + maxOwner : Fin n → Bool + weight : Fin m → ℤ + total : ∀ v : Fin n, ∃ e : Fin m, tail e = v + +def Strategy (G : Game) := + List (Fin G.m) → (v : Fin G.n) → {e : Fin G.m // G.tail e = v} + +def move (G : Game) (σ τ : Strategy G) (v : Fin G.n) + (history : List (Fin G.m)) : Fin G.m := + if G.maxOwner v then (σ history v).val else (τ history v).val + +def position (G : Game) (σ τ : Strategy G) (start : Fin G.n) : + ℕ → Fin G.n × List (Fin G.m) + | 0 => (start, []) + | t + 1 => + let p := position G σ τ start t + let e := move G σ τ p.1 p.2 + (G.head e, p.2 ++ [e]) + +def play (G : Game) (σ τ : Strategy G) (start : Fin G.n) (t : ℕ) : Fin G.m := + let p := position G σ τ start t + move G σ τ p.1 p.2 + +noncomputable def meanPayoff (G : Game) (π : ℕ → Fin G.m) : ℝ := + Filter.liminf (fun T : ℕ => + (∑ j ∈ Finset.range T, (G.weight (π j) : ℝ)) / (T : ℝ)) Filter.atTop + +def Winning (G : Game) (v : Fin G.n) : Prop := + ∃ σ : Strategy G, ∀ τ : Strategy G, 0 ≤ meanPayoff G (play G σ τ v) + +def encodeNat (n : ℕ) : List Bool := + let bits := Nat.bits (n + 1) + List.replicate bits.length true ++ [false] ++ bits + +def encodeInt (z : ℤ) : List Bool := + decide (z < 0) :: encodeNat z.natAbs + +def input (G : Game) : List Bool := + encodeNat G.n ++ encodeNat G.m ++ List.ofFn G.maxOwner ++ + (List.ofFn (fun e : Fin G.m => + encodeNat ((G.tail e).val + 1) ++ encodeNat ((G.head e).val + 1) ++ + encodeInt (G.weight e))).flatten + +abbrev Symbol := Option Bool + +inductive Direction where + | left | stay | right + deriving DecidableEq + +def Direction.offset : Direction → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Action (q : ℕ) where + next : Fin q + write : Fin 3 → Symbol + shift : Fin 3 → Direction + +structure Machine where + states : ℕ + start : Fin states + transition : Fin states → (Fin 3 → Symbol) → Bool → Option (Action states) + +structure Configuration (M : Machine) where + control : Option (Fin M.states) + head : Fin 3 → ℤ + tape : Fin 3 → ℤ → Symbol + +def initial (M : Machine) (code : List Bool) : Configuration M where + control := some M.start + head := fun _ => 0 + tape := fun k j => if k = 0 ∧ 0 ≤ j then code[j.toNat]? else none + +def step (M : Machine) (c : Configuration M) (bit : Bool) : Configuration M := + match c.control with + | none => c + | some s => + match M.transition s (fun k => c.tape k (c.head k)) bit with + | none => { c with control := none } + | some a => + { control := some a.next + head := fun k => c.head k + (a.shift k).offset + tape := fun k => Function.update (c.tape k) (c.head k) (a.write k) } + +def run (M : Machine) (code : List Bool) (random : ℕ → Bool) : ℕ → Configuration M + | 0 => initial M code + | t + 1 => step M (run M code random t) (random t) + +def padBits {T : ℕ} (bits : Fin T → Bool) (j : ℕ) : Bool := + if h : j < T then bits ⟨j, h⟩ else false + +def result (M : Machine) (G : Game) (T : ℕ) (bits : Fin T → Bool) : Configuration M := + run M (input G) (padBits bits) T + +def CorrectOutput (G : Game) {M : Machine} (c : Configuration M) : Prop := + c.control = none ∧ + (∀ v : Fin G.n, c.tape 2 (v.val : ℤ) = some true ↔ Winning G v) ∧ + (∀ v : Fin G.n, c.tape 2 (v.val : ℤ) = some false ↔ ¬ Winning G v) ∧ + ∀ j : ℤ, (j < 0 ∨ (G.n : ℤ) ≤ j) → c.tape 2 j = none + +noncomputable def MainClaim : Prop := by + classical + exact ∃ M : Machine, ∃ C : ℝ, 0 < C ∧ ∀ G : Game, ∃ T : ℕ, + (T : ℝ) ≤ (2 : ℝ) ^ (C * (Real.logb 2 ((input G).length + 2)) ^ 2) ∧ + (∀ bits : Fin T → Bool, (result M G T bits).control = none) ∧ + 7 * 2 ^ T ≤ 8 * (Finset.univ.filter + (fun bits : Fin T → Bool => CorrectOutput G (result M G T bits))).card + +end MeanPayoff + +theorem randomized_quasipolynomial_mean_payoff : MeanPayoff.MainClaim := by + sorry + +end OAI diff --git a/tasks/randomized-mean-payoff/tests/grade.py b/tasks/randomized-mean-payoff/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/randomized-mean-payoff/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/randomized-mean-payoff/tests/task.json b/tasks/randomized-mean-payoff/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5c3ebeff15b76cd2ae272019844abef5c5983c2c --- /dev/null +++ b/tasks/randomized-mean-payoff/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RandomizedMeanPayoff", + "comparator": { + "theorem_names": [ + "OAI.randomized_quasipolynomial_mean_payoff" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11970 +} \ No newline at end of file diff --git a/tasks/randomized-mean-payoff/tests/test.sh b/tasks/randomized-mean-payoff/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/randomized-mean-payoff/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/rational-hitting/environment/Dockerfile b/tasks/rational-hitting/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/rational-hitting/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/rational-hitting/environment/fetch_mathlib.sh b/tasks/rational-hitting/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/rational-hitting/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/rational-hitting/environment/lake-manifest.json b/tasks/rational-hitting/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/rational-hitting/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/rational-hitting/environment/lakefile.lean b/tasks/rational-hitting/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/rational-hitting/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/rational-hitting/environment/lean_setup.sh b/tasks/rational-hitting/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/rational-hitting/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/rational-hitting/environment/pack_submission.py b/tasks/rational-hitting/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/rational-hitting/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/rational-hitting/instruction.md b/tasks/rational-hitting/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..da88ae4c2bb0eb509f4de7cd777f71d796437190 --- /dev/null +++ b/tasks/rational-hitting/instruction.md @@ -0,0 +1,164 @@ +# openai/math challenge `RationalHitting` (family 116) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 116 of the release, *Uniform identity testing for noncommutative formulas* +(Theoretical computer science). The family as a whole: For each characteristic, constructs in deterministic polynomial bit time a polynomial-dimensional matrix tuple detecting every nonzero division-free noncommutative formula of bounded size over any field of that characteristic. Rational formulas over $\mathbb Q$ also admit polynomial-size hitting lists whenever they have a defined rational-matrix evaluation. + +The challenge is `RationalHitting`, also at `/opt/openai-math/challenges/RationalHitting.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace RationalHitting + +universe u + +inductive Formula (n : ℕ) where + | var : Fin n → Formula n + | const : ℚ → Formula n + | add : Formula n → Formula n → Formula n + | mul : Formula n → Formula n → Formula n + | inv : Formula n → Formula n + deriving DecidableEq + +namespace Formula + +def size {n : ℕ} : Formula n → ℕ + | .var _ | .const _ => 1 + | .add f g | .mul f g => f.size + g.size + 1 + | .inv f => f.size + 1 + +/-- Evaluation in any rational algebra; a unary inverse requires an actual + two-sided inverse of the evaluated operand, not a totalized inverse. -/ +inductive Eval {n : ℕ} {R : Type u} [Ring R] + (c : ℚ →+* R) (X : Fin n → R) : Formula n → R → Prop where + | var (i) : Eval c X (.var i) (X i) + | const (a) : Eval c X (.const a) (c a) + | add {f g a b} : Eval c X f a → Eval c X g b → Eval c X (.add f g) (a + b) + | mul {f g a b} : Eval c X f a → Eval c X g b → Eval c X (.mul f g) (a * b) + | inv {f a b} : Eval c X f a → a * b = 1 → b * a = 1 → Eval c X (.inv f) b + +end Formula + +abbrev Mat (d : ℕ) := Matrix (Fin d) (Fin d) ℚ +abbrev Tuple (n d : ℕ) := Fin n → Mat d + +def Evaluates {n d : ℕ} (f : Formula n) (X : Tuple n d) (v : Mat d) : Prop := + f.Eval (algebraMap ℚ (Mat d)) X v + +def Admissible {n : ℕ} (f : Formula n) : Prop := + ∃ d, 0 < d ∧ ∃ (X : Tuple n d), ∃ v, Evaluates f X v + +def Nonzero {n : ℕ} (f : Formula n) : Prop := + ∃ d, 0 < d ∧ ∃ (X : Tuple n d), ∃ v, Evaluates f X v ∧ v ≠ 0 + +/-- All output tuples have one common positive dimension. -/ +structure Output (n : ℕ) where + dimension : ℕ + dimension_pos : 0 < dimension + tuples : List (Tuple n dimension) + +/-- Little-endian unsigned binary, prefixed by a unary bit-length and a zero + terminator. This is a self-delimiting binary encoding, including zero. -/ +def encodeNat (a : ℕ) : List Bool := + let ds := (Nat.digits 2 a).map (fun b => b != 0) + List.replicate ds.length true ++ [false] ++ ds + +/-- Sign bit, binary numerator magnitude, and positive binary denominator. + Rat.num and Rat.den are the canonical reduced numerator and denominator. -/ +def encodeRat (a : ℚ) : List Bool := + [decide (a.num < 0)] ++ encodeNat a.num.natAbs ++ encodeNat a.den + +def encodeTuple {n d : ℕ} (X : Tuple n d) : List Bool := + (List.finRange n).flatMap fun i => + (List.finRange d).flatMap fun j => + (List.finRange d).flatMap fun k => encodeRat (X i j k) + +def encodeOutput {n : ℕ} (H : Output n) : List Bool := + encodeNat H.dimension ++ encodeNat H.tuples.length ++ H.tuples.flatMap encodeTuple + +/-- 0 is blank, 1 and 2 are the two literal binary digits, 3 is work space. + Fixed finite tape alphabet and finite state space; no advice or oracle. -/ +abbrev Alphabet := Fin 4 +abbrev Machine (m : ℕ) := Turing.TM0.Machine Alphabet (Fin (m + 1)) +abbrev Config (m : ℕ) := Turing.TM0.Cfg Alphabet (Fin (m + 1)) + +def tapeBit (b : Bool) : Alphabet := if b then 2 else 1 + +def unaryInput (n s : ℕ) : List Alphabet := + List.replicate n 2 ++ [1] ++ List.replicate s 2 + +/-- Exactly t ordinary deterministic TM0 transitions. -/ +def run {m : ℕ} (G : Machine m) : ℕ → Config m → Option (Config m) + | 0, a => some a + | t + 1, a => (Turing.TM0.step G a).bind (run G t) + +def OutputsWithin {m n : ℕ} (G : Machine m) (s bound : ℕ) (H : Output n) : Prop := + ∃ t ≤ bound, ∃ a : Config m, + run G t (Turing.TM0.init (unaryInput n s)) = some a ∧ + Turing.TM0.step G a = none ∧ + a.Tape.right₀ = Turing.ListBlank.mk ((encodeOutput H).map tapeBit) + +def Hits {n : ℕ} (s : ℕ) (H : Output n) : Prop := + ∀ f : Formula n, f.size ≤ s → Admissible f → Nonzero f → + ∃ X ∈ H.tuples, ∃ v, Evaluates f X v ∧ IsUnit v + +/-- A fixed polynomial bound on bit time, full binary output length, +and common positive dimension. -/ +def MainStatement : Prop := + ∃ (m : ℕ) (G : Machine m) (C k : ℕ), 0 < C ∧ 0 < k ∧ + ∀ n s : ℕ, 1 ≤ n → 1 ≤ s → ∃ H : Output n, + H.dimension ≤ C * (n + s + 1) ^ k ∧ + (encodeOutput H).length ≤ C * (n + s + 1) ^ k ∧ + OutputsWithin G s (C * (n + s + 1) ^ k) H ∧ Hits s H + +theorem main : MainStatement := by + sorry + +end RationalHitting + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RationalHitting.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RationalHitting.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/rational-hitting/solution/closure.txt b/tasks/rational-hitting/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0ea0885430bd462dd585d24656ee2a93ba32d461 --- /dev/null +++ b/tasks/rational-hitting/solution/closure.txt @@ -0,0 +1,53 @@ +OAI.Computability.RationalHitting.Affine +OAI.Computability.RationalHitting.BinaryAddition +OAI.Computability.RationalHitting.BinaryBinomial +OAI.Computability.RationalHitting.BinaryDivision +OAI.Computability.RationalHitting.BinaryFactorial +OAI.Computability.RationalHitting.BinaryGcd +OAI.Computability.RationalHitting.BinaryMultiply +OAI.Computability.RationalHitting.BinarySubtract +OAI.Computability.RationalHitting.BinomialBounds +OAI.Computability.RationalHitting.BlockDivision +OAI.Computability.RationalHitting.Certificates +OAI.Computability.RationalHitting.Compiler +OAI.Computability.RationalHitting.CyclotomicGrid +OAI.Computability.RationalHitting.Deformation +OAI.Computability.RationalHitting.DenseDeterminant +OAI.Computability.RationalHitting.DenseRecords +OAI.Computability.RationalHitting.Determinant +OAI.Computability.RationalHitting.EncodingBounds +OAI.Computability.RationalHitting.Evaluation +OAI.Computability.RationalHitting.Executable +OAI.Computability.RationalHitting.Feasibility +OAI.Computability.RationalHitting.FiniteCompiler +OAI.Computability.RationalHitting.Generator +OAI.Computability.RationalHitting.GridComputation +OAI.Computability.RationalHitting.InputAdapter +OAI.Computability.RationalHitting.IntegralLift +OAI.Computability.RationalHitting.LaurentReduction +OAI.Computability.RationalHitting.LiftComputation +OAI.Computability.RationalHitting.ListProcedures +OAI.Computability.RationalHitting.Main +OAI.Computability.RationalHitting.MatrixComputation +OAI.Computability.RationalHitting.Model +OAI.Computability.RationalHitting.OutputAdapter +OAI.Computability.RationalHitting.OutputComputation +OAI.Computability.RationalHitting.PaddedRank +OAI.Computability.RationalHitting.ProcedureControl +OAI.Computability.RationalHitting.ProcedurePairs +OAI.Computability.RationalHitting.Procedures +OAI.Computability.RationalHitting.QuantumMatrices +OAI.Computability.RationalHitting.QuantumSeries +OAI.Computability.RationalHitting.RationalArithmetic +OAI.Computability.RationalHitting.RationalBinary +OAI.Computability.RationalHitting.Rectangular +OAI.Computability.RationalHitting.SignedArithmetic +OAI.Computability.RationalHitting.SignedBinary +OAI.Computability.RationalHitting.SmallExpansion +OAI.Computability.RationalHitting.StackLanguage +OAI.Computability.RationalHitting.StackSimulation +OAI.Computability.RationalHitting.StackWords +OAI.Computability.RationalHitting.Tabulation +OAI.Computability.RationalHitting.TaylorComputation +OAI.Computability.RationalHitting.UnaryArithmetic +OAI.Computability.RationalHitting.Wronskian diff --git a/tasks/rational-hitting/solution/reference.py b/tasks/rational-hitting/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/rational-hitting/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/rational-hitting/solution/solve.sh b/tasks/rational-hitting/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1041fd92feba8f5b675870fbdb7d2f6c533e8332 --- /dev/null +++ b/tasks/rational-hitting/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RationalHitting, i.e. module OAI.Computability.RationalHitting.Main and the +# 53 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.RationalHitting.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RationalHitting" diff --git a/tasks/rational-hitting/task.toml b/tasks/rational-hitting/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c66c7325fb9bc34e860a18efdc076d01d39c38d0 --- /dev/null +++ b/tasks/rational-hitting/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/rational-hitting" +version = "1.0.0" +description = "Prove RationalHitting (openai/math family 116: Uniform identity testing for noncommutative formulas) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RationalHitting.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RationalHitting" +family = "116" +family_title = "Uniform identity testing for noncommutative formulas" +subject = "Theoretical computer science" +theorems = ["OAI.RationalHitting.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.RationalHitting.Main" +reference_modules = 53 +reference_lean_bytes = 700555 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 666 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12330 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/rational-hitting/tests/Challenge.lean b/tasks/rational-hitting/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7693842d66f4f3660251b4571903e2f8ec6980a8 --- /dev/null +++ b/tasks/rational-hitting/tests/Challenge.lean @@ -0,0 +1,113 @@ +import Mathlib + +namespace OAI + +namespace RationalHitting + +universe u + +inductive Formula (n : ℕ) where + | var : Fin n → Formula n + | const : ℚ → Formula n + | add : Formula n → Formula n → Formula n + | mul : Formula n → Formula n → Formula n + | inv : Formula n → Formula n + deriving DecidableEq + +namespace Formula + +def size {n : ℕ} : Formula n → ℕ + | .var _ | .const _ => 1 + | .add f g | .mul f g => f.size + g.size + 1 + | .inv f => f.size + 1 + +/-- Evaluation in any rational algebra; a unary inverse requires an actual + two-sided inverse of the evaluated operand, not a totalized inverse. -/ +inductive Eval {n : ℕ} {R : Type u} [Ring R] + (c : ℚ →+* R) (X : Fin n → R) : Formula n → R → Prop where + | var (i) : Eval c X (.var i) (X i) + | const (a) : Eval c X (.const a) (c a) + | add {f g a b} : Eval c X f a → Eval c X g b → Eval c X (.add f g) (a + b) + | mul {f g a b} : Eval c X f a → Eval c X g b → Eval c X (.mul f g) (a * b) + | inv {f a b} : Eval c X f a → a * b = 1 → b * a = 1 → Eval c X (.inv f) b + +end Formula + +abbrev Mat (d : ℕ) := Matrix (Fin d) (Fin d) ℚ +abbrev Tuple (n d : ℕ) := Fin n → Mat d + +def Evaluates {n d : ℕ} (f : Formula n) (X : Tuple n d) (v : Mat d) : Prop := + f.Eval (algebraMap ℚ (Mat d)) X v + +def Admissible {n : ℕ} (f : Formula n) : Prop := + ∃ d, 0 < d ∧ ∃ (X : Tuple n d), ∃ v, Evaluates f X v + +def Nonzero {n : ℕ} (f : Formula n) : Prop := + ∃ d, 0 < d ∧ ∃ (X : Tuple n d), ∃ v, Evaluates f X v ∧ v ≠ 0 + +/-- All output tuples have one common positive dimension. -/ +structure Output (n : ℕ) where + dimension : ℕ + dimension_pos : 0 < dimension + tuples : List (Tuple n dimension) + +/-- Little-endian unsigned binary, prefixed by a unary bit-length and a zero + terminator. This is a self-delimiting binary encoding, including zero. -/ +def encodeNat (a : ℕ) : List Bool := + let ds := (Nat.digits 2 a).map (fun b => b != 0) + List.replicate ds.length true ++ [false] ++ ds + +/-- Sign bit, binary numerator magnitude, and positive binary denominator. + Rat.num and Rat.den are the canonical reduced numerator and denominator. -/ +def encodeRat (a : ℚ) : List Bool := + [decide (a.num < 0)] ++ encodeNat a.num.natAbs ++ encodeNat a.den + +def encodeTuple {n d : ℕ} (X : Tuple n d) : List Bool := + (List.finRange n).flatMap fun i => + (List.finRange d).flatMap fun j => + (List.finRange d).flatMap fun k => encodeRat (X i j k) + +def encodeOutput {n : ℕ} (H : Output n) : List Bool := + encodeNat H.dimension ++ encodeNat H.tuples.length ++ H.tuples.flatMap encodeTuple + +/-- 0 is blank, 1 and 2 are the two literal binary digits, 3 is work space. + Fixed finite tape alphabet and finite state space; no advice or oracle. -/ +abbrev Alphabet := Fin 4 +abbrev Machine (m : ℕ) := Turing.TM0.Machine Alphabet (Fin (m + 1)) +abbrev Config (m : ℕ) := Turing.TM0.Cfg Alphabet (Fin (m + 1)) + +def tapeBit (b : Bool) : Alphabet := if b then 2 else 1 + +def unaryInput (n s : ℕ) : List Alphabet := + List.replicate n 2 ++ [1] ++ List.replicate s 2 + +/-- Exactly t ordinary deterministic TM0 transitions. -/ +def run {m : ℕ} (G : Machine m) : ℕ → Config m → Option (Config m) + | 0, a => some a + | t + 1, a => (Turing.TM0.step G a).bind (run G t) + +def OutputsWithin {m n : ℕ} (G : Machine m) (s bound : ℕ) (H : Output n) : Prop := + ∃ t ≤ bound, ∃ a : Config m, + run G t (Turing.TM0.init (unaryInput n s)) = some a ∧ + Turing.TM0.step G a = none ∧ + a.Tape.right₀ = Turing.ListBlank.mk ((encodeOutput H).map tapeBit) + +def Hits {n : ℕ} (s : ℕ) (H : Output n) : Prop := + ∀ f : Formula n, f.size ≤ s → Admissible f → Nonzero f → + ∃ X ∈ H.tuples, ∃ v, Evaluates f X v ∧ IsUnit v + +/-- A fixed polynomial bound on bit time, full binary output length, +and common positive dimension. -/ +def MainStatement : Prop := + ∃ (m : ℕ) (G : Machine m) (C k : ℕ), 0 < C ∧ 0 < k ∧ + ∀ n s : ℕ, 1 ≤ n → 1 ≤ s → ∃ H : Output n, + H.dimension ≤ C * (n + s + 1) ^ k ∧ + (encodeOutput H).length ≤ C * (n + s + 1) ^ k ∧ + OutputsWithin G s (C * (n + s + 1) ^ k) H ∧ Hits s H + +theorem main : MainStatement := by + sorry + +end RationalHitting + +end OAI diff --git a/tasks/rational-hitting/tests/grade.py b/tasks/rational-hitting/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/rational-hitting/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/rational-hitting/tests/task.json b/tasks/rational-hitting/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e042074ca9bdab344191ff56bf288488315eba07 --- /dev/null +++ b/tasks/rational-hitting/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RationalHitting", + "comparator": { + "theorem_names": [ + "OAI.RationalHitting.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11430 +} \ No newline at end of file diff --git a/tasks/rational-hitting/tests/test.sh b/tasks/rational-hitting/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/rational-hitting/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/real-l1-renorming/environment/Dockerfile b/tasks/real-l1-renorming/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/real-l1-renorming/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/real-l1-renorming/environment/fetch_mathlib.sh b/tasks/real-l1-renorming/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/real-l1-renorming/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/real-l1-renorming/environment/lake-manifest.json b/tasks/real-l1-renorming/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/real-l1-renorming/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/real-l1-renorming/environment/lakefile.lean b/tasks/real-l1-renorming/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/real-l1-renorming/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/real-l1-renorming/environment/lean_setup.sh b/tasks/real-l1-renorming/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/real-l1-renorming/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/real-l1-renorming/environment/pack_submission.py b/tasks/real-l1-renorming/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/real-l1-renorming/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/real-l1-renorming/instruction.md b/tasks/real-l1-renorming/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..89868103f9d3b267de29bab7bf07c16cf812d537 --- /dev/null +++ b/tasks/real-l1-renorming/instruction.md @@ -0,0 +1,106 @@ +# openai/math challenge `RealL1Renorming` (family 330) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 330 of the release, *A negative answer to Kalton's Lipschitz-free approximation question* +(Functional analysis). The family as a whole: Constructs a countable uniformly discrete metric space whose real Lipschitz-free Banach space has the approximation property but not the bounded approximation property, answering Kalton's question negatively. Finite-rank operators approximate the identity on every compact set, but their norms cannot share a finite bound. + +The challenge is `RealL1Renorming`, also at `/opt/openai-math/challenges/RealL1Renorming.lean`: + +```lean +import Mathlib.Analysis.Normed.Lp.lpSpace +import Mathlib.Analysis.Normed.Operator.Basic +import Mathlib.RingTheory.Finiteness.Defs + +namespace OAI + +noncomputable section + +/-! +# Quantitative renorming of real ℓ¹ with fixed vector-space operations +-/ + +open scoped BigOperators ENNReal + +namespace DiscreteFree + +variable {M : Type*} [MetricSpace M] + +def HasBAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] (Λ : ℝ) : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ‖T‖ ≤ Λ ∧ ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def blockBound (p : ℕ) : ℝ := 300 * (p : ℝ)^2 + 150 * (p : ℝ) + 5 + +open scoped BigOperators ENNReal + +def RealL1 : Type := lp (fun _ : ℕ => ℝ) (1 : ENNReal) + +noncomputable instance : NormedAddCommGroup RealL1 := + inferInstanceAs (NormedAddCommGroup (lp (fun _ : ℕ => ℝ) (1 : ENNReal))) + +noncomputable instance : NormedSpace ℝ RealL1 := + inferInstanceAs (NormedSpace ℝ (lp (fun _ : ℕ => ℝ) (1 : ENNReal))) + +def RealL1RenormingStatement : Prop := + ∀ p : ℕ, 1 ≤ p → ∃ N : AddGroupNorm RealL1, + (∀ (r : ℝ) (c : RealL1), N (r • c) = |r| * N c) ∧ + (∀ c : RealL1, (1 / 2 : ℝ) * ‖c‖ ≤ N c ∧ N c ≤ blockBound p * ‖c‖) ∧ + (let m : Module ℝ RealL1 := inferInstance + letI : NormedAddCommGroup RealL1 := N.toNormedAddCommGroup + ∃ s : NormedSpace ℝ RealL1, s.toModule = m ∧ + letI := s + CompleteSpace RealL1 ∧ + HasBAP RealL1 (2 * blockBound p) ∧ ¬ HasBAP RealL1 (p : ℝ) ∧ + (p = 1 → ¬ HasBAP RealL1 1)) + +theorem real_l1_quantitative_renorming : RealL1RenormingStatement := by + sorry + +end DiscreteFree + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RealL1Renorming.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DiscreteFree.real_l1_quantitative_renorming` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/real-l1-renorming/solution/closure.txt b/tasks/real-l1-renorming/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..69b92208aa473fe161cc5e33241e1d18e0d119b9 --- /dev/null +++ b/tasks/real-l1-renorming/solution/closure.txt @@ -0,0 +1,33 @@ +OAI.Analysis.LipschitzFree.AffineWeights +OAI.Analysis.LipschitzFree.Attachment +OAI.Analysis.LipschitzFree.BlockBAP +OAI.Analysis.LipschitzFree.BlockObstruction +OAI.Analysis.LipschitzFree.BlockPaths +OAI.Analysis.LipschitzFree.BoxLabels +OAI.Analysis.LipschitzFree.Coefficients +OAI.Analysis.LipschitzFree.ColorCounting +OAI.Analysis.LipschitzFree.CompactApproximation +OAI.Analysis.LipschitzFree.Coordinates +OAI.Analysis.LipschitzFree.Evaluation +OAI.Analysis.LipschitzFree.FiniteQuotients +OAI.Analysis.LipschitzFree.Functor +OAI.Analysis.LipschitzFree.GraphColoring +OAI.Analysis.LipschitzFree.GraphGirth +OAI.Analysis.LipschitzFree.GraphSequence +OAI.Analysis.LipschitzFree.GraphWalks +OAI.Analysis.LipschitzFree.LabelBumps +OAI.Analysis.LipschitzFree.MetricBlock +OAI.Analysis.LipschitzFree.MetricClosure +OAI.Analysis.LipschitzFree.Model +OAI.Analysis.LipschitzFree.Parameters +OAI.Analysis.LipschitzFree.PortGraphs +OAI.Analysis.LipschitzFree.Renorming +OAI.Analysis.LipschitzFree.RenormingModel +OAI.Analysis.LipschitzFree.RetainedWedge +OAI.Analysis.LipschitzFree.ScalarTests +OAI.Analysis.LipschitzFree.SignedTests +OAI.Analysis.LipschitzFree.StatePaths +OAI.Analysis.LipschitzFree.SupportReduction +OAI.Analysis.LipschitzFree.Wedge +OAI.Analysis.LipschitzFree.WedgeApproximation +OAI.Analysis.LipschitzFree.Words diff --git a/tasks/real-l1-renorming/solution/reference.py b/tasks/real-l1-renorming/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/real-l1-renorming/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/real-l1-renorming/solution/solve.sh b/tasks/real-l1-renorming/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b5283ae3724d8607f07fb75d7a95c1bb246cbefc --- /dev/null +++ b/tasks/real-l1-renorming/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RealL1Renorming, i.e. module OAI.Analysis.LipschitzFree.Renorming and the +# 33 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LipschitzFree.Renorming /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RealL1Renorming" diff --git a/tasks/real-l1-renorming/task.toml b/tasks/real-l1-renorming/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a3ea6457e3c76ab120b4b5a2bf41e1c284f22bc --- /dev/null +++ b/tasks/real-l1-renorming/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/real-l1-renorming" +version = "1.0.0" +description = "Prove RealL1Renorming (openai/math family 330: A negative answer to Kalton's Lipschitz-free approximation question) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RealL1Renorming.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RealL1Renorming" +family = "330" +family_title = "A negative answer to Kalton's Lipschitz-free approximation question" +subject = "Functional analysis" +theorems = ["OAI.DiscreteFree.real_l1_quantitative_renorming"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LipschitzFree.Renorming" +reference_modules = 33 +reference_lean_bytes = 179835 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 304 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11861 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/real-l1-renorming/tests/Challenge.lean b/tasks/real-l1-renorming/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ec37135e0c8c463a944115a1e167a17ce9860dc8 --- /dev/null +++ b/tasks/real-l1-renorming/tests/Challenge.lean @@ -0,0 +1,55 @@ +import Mathlib.Analysis.Normed.Lp.lpSpace +import Mathlib.Analysis.Normed.Operator.Basic +import Mathlib.RingTheory.Finiteness.Defs + +namespace OAI + +noncomputable section + +/-! +# Quantitative renorming of real ℓ¹ with fixed vector-space operations +-/ + +open scoped BigOperators ENNReal + +namespace DiscreteFree + +variable {M : Type*} [MetricSpace M] + +def HasBAP (X : Type*) [NormedAddCommGroup X] [NormedSpace ℝ X] (Λ : ℝ) : Prop := + ∀ C : Set X, IsCompact C → ∀ ε : ℝ, 0 < ε → + ∃ T : X →L[ℝ] X, Module.Finite ℝ (LinearMap.range T.toLinearMap) ∧ + ‖T‖ ≤ Λ ∧ ∃ η : ℝ, η < ε ∧ ∀ u ∈ C, ‖T u - u‖ ≤ η + +def blockBound (p : ℕ) : ℝ := 300 * (p : ℝ)^2 + 150 * (p : ℝ) + 5 + +open scoped BigOperators ENNReal + +def RealL1 : Type := lp (fun _ : ℕ => ℝ) (1 : ENNReal) + +noncomputable instance : NormedAddCommGroup RealL1 := + inferInstanceAs (NormedAddCommGroup (lp (fun _ : ℕ => ℝ) (1 : ENNReal))) + +noncomputable instance : NormedSpace ℝ RealL1 := + inferInstanceAs (NormedSpace ℝ (lp (fun _ : ℕ => ℝ) (1 : ENNReal))) + +def RealL1RenormingStatement : Prop := + ∀ p : ℕ, 1 ≤ p → ∃ N : AddGroupNorm RealL1, + (∀ (r : ℝ) (c : RealL1), N (r • c) = |r| * N c) ∧ + (∀ c : RealL1, (1 / 2 : ℝ) * ‖c‖ ≤ N c ∧ N c ≤ blockBound p * ‖c‖) ∧ + (let m : Module ℝ RealL1 := inferInstance + letI : NormedAddCommGroup RealL1 := N.toNormedAddCommGroup + ∃ s : NormedSpace ℝ RealL1, s.toModule = m ∧ + letI := s + CompleteSpace RealL1 ∧ + HasBAP RealL1 (2 * blockBound p) ∧ ¬ HasBAP RealL1 (p : ℝ) ∧ + (p = 1 → ¬ HasBAP RealL1 1)) + +theorem real_l1_quantitative_renorming : RealL1RenormingStatement := by + sorry + +end DiscreteFree + +end + +end OAI diff --git a/tasks/real-l1-renorming/tests/grade.py b/tasks/real-l1-renorming/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/real-l1-renorming/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/real-l1-renorming/tests/task.json b/tasks/real-l1-renorming/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..df6fa8f2d0c39338afe2b7d06f0994eafc7b3a3e --- /dev/null +++ b/tasks/real-l1-renorming/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RealL1Renorming", + "comparator": { + "theorem_names": [ + "OAI.DiscreteFree.real_l1_quantitative_renorming" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10961 +} \ No newline at end of file diff --git a/tasks/real-l1-renorming/tests/test.sh b/tasks/real-l1-renorming/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/real-l1-renorming/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/recursive-potentials/environment/Dockerfile b/tasks/recursive-potentials/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/recursive-potentials/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/recursive-potentials/environment/fetch_mathlib.sh b/tasks/recursive-potentials/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/recursive-potentials/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/recursive-potentials/environment/lake-manifest.json b/tasks/recursive-potentials/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/recursive-potentials/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/recursive-potentials/environment/lakefile.lean b/tasks/recursive-potentials/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/recursive-potentials/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/recursive-potentials/environment/lean_setup.sh b/tasks/recursive-potentials/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/recursive-potentials/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/recursive-potentials/environment/pack_submission.py b/tasks/recursive-potentials/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/recursive-potentials/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/recursive-potentials/instruction.md b/tasks/recursive-potentials/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ac4470a49d06c4f7e1ea5ef059324a141a9f097f --- /dev/null +++ b/tasks/recursive-potentials/instruction.md @@ -0,0 +1,1015 @@ +# openai/math challenge `RecursivePotentials` (family 331) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 331 of the release, *Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming* +(Functional analysis). The family as a whole: Constructs a real reflexive Banach space with an asymptotically midpoint uniformly convex norm but no equivalent asymptotically uniformly convex norm, extending Baudier's separation to reflexive spaces. In the same space, depth-$k$ countably branching diamonds require distortion at least $\sqrt{1+k/12}$, so midpoint uniform convexity does not force uniformly bounded diamond distortion even under reflexivity. + +The challenge is `RecursivePotentials`, also at `/opt/openai-math/challenges/RecursivePotentials.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +/-! +The final claim constructs the spaces and states all eleven original results. +`Analysis.RecursivePotentials.Challenge.main_iff_original` verifies statement preservation. +-/ + +universe uIndex uSpace uOther uDomain uTarget uFiber + +open scoped BigOperators + +namespace RecursivePotentials + +def leastPair (x a b : ℝ) : ℝ × ℝ := (max a (x + b), max b (-x + a)) + +structure FiniteRootedTree (ι : Type uIndex) where + root : ι + parent : ι → ι + depth : ι → ℕ + parent_root : parent root = root + depth_root : depth root = 0 + parent_depth : ∀ i, i ≠ root → depth (parent i) < depth i + +namespace FiniteRootedTree + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) + +def children (s : ι) : Finset ι := + Finset.univ.filter fun c => c ≠ T.root ∧ T.parent c = s + +def maxDepth : ℕ := Finset.univ.sup T.depth + +noncomputable def fields (v : ι → ℝ) (s : ι) : ℝ × ℝ := + leastPair (v s) + (Real.sqrt (∑ c : {c // c ∈ T.children s}, (fields v c.1).1 ^ 2)) + (Real.sqrt (∑ c : {c // c ∈ T.children s}, (fields v c.1).2 ^ 2)) +termination_by T.maxDepth - T.depth s +decreasing_by + all_goals + have hc := (Finset.mem_filter.mp c.2).2 + have hd := T.parent_depth c.1 hc.1 + rw [hc.2] at hd + have hm : T.depth c.1 ≤ T.maxDepth := Finset.le_sup (Finset.mem_univ c.1) + omega + +def Initial (H : Finset ι) : Prop := T.root ∈ H ∧ ∀ s ∈ H, T.parent s ∈ H + +end + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def ancestors (s : ι) : Finset ι := + if _hs : s = T.root then {s} else insert s (ancestors (T.parent s)) +termination_by T.depth s +decreasing_by exact T.parent_depth s _hs + +def ancestorClosure (S : Finset ι) : Finset ι := + insert T.root (S.biUnion T.ancestors) + +def restrict (H : Finset ι) (hH : T.Initial H) : FiniteRootedTree H where + root := ⟨T.root, hH.1⟩ + parent s := ⟨T.parent s, hH.2 s.1 s.2⟩ + depth s := T.depth s + parent_root := Subtype.ext T.parent_root + depth_root := T.depth_root + parent_depth s hs := T.parent_depth s (fun h => hs (Subtype.ext h)) + +noncomputable def extend (H : Finset ι) (f : H → ℝ) : ι →₀ ℝ := + Finsupp.onFinset H (fun s => if hs : s ∈ H then f ⟨s, hs⟩ else 0) + (fun s hs => by by_contra hh; simp [hh] at hs) + +def head (v : ι →₀ ℝ) : Finset ι := T.ancestorClosure v.support + +def projectHead (_T : FiniteRootedTree ι) (H : Finset ι) (v : ι →₀ ℝ) : ι →₀ ℝ := v.filter (· ∈ H) + +end FiniteRootedTree + +structure CofiniteSubspace (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] where + space : Submodule ℝ E + closed : IsClosed (space : Set E) + finiteQuotient : Module.Finite ℝ (E ⧸ space) + +section Moduli + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] + +noncomputable def averagedGain (x : E) (t : ℝ) (y : E) : ℝ := (‖x + t • y‖ + ‖x - t • y‖) / 2 - 1 + +noncomputable def averagedInner (x : E) (t : ℝ) (F : CofiniteSubspace E) : ℝ := + sInf {r : ℝ | ∃ y ∈ F.space, 1 ≤ ‖y‖ ∧ r = averagedGain x t y} + +noncomputable def averagedModulus (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] + (t : ℝ) : ℝ := + sInf {r : ℝ | ∃ x : E, ‖x‖ = 1 ∧ r = sSup (Set.range (averagedInner x t))} + +end Moduli + +def sequenceTree : FiniteRootedTree (List ℕ) where + root := [] + parent := List.dropLast + depth := List.length + parent_root := rfl + depth_root := rfl + parent_depth s hs := by + rw [List.length_dropLast] + have h := List.length_pos_iff_ne_nil.mpr hs + omega + +abbrev ComponentNode (h : ℕ+) := {s : List ℕ // s.length ≤ h.val} + +abbrev JoinedNode := Option (Σ h : ℕ+, ComponentNode h) + +def joinedTree : FiniteRootedTree JoinedNode where + root := none + parent + | none => none + | some ⟨h, s⟩ => if s.1 = [] then none else + some ⟨h, ⟨s.1.dropLast, by rw [List.length_dropLast]; have := s.2; omega⟩⟩ + depth + | none => 0 + | some ⟨_, s⟩ => s.1.length + 1 + parent_root := rfl + depth_root := rfl + parent_depth s hs := by + cases s with + | none => exact (hs rfl).elim + | some s => + obtain ⟨h, s⟩ := s + dsimp + by_cases he : s.1 = [] + · simp [he] + · rw [ite_eq_right he] + dsimp + rw [List.length_dropLast] + have hpos := List.length_pos_iff_ne_nil.mpr he + omega + +open Filter Topology + +def WeaklyNull {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (d : ℕ → E) : Prop := + ∀ f : E →L[ℝ] ℝ, Tendsto (fun k => f (d k)) atTop (𝓝 0) + +structure EquivalentNorm (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] where + N : Seminorm ℝ E + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + lower_le_upper : lower ≤ upper + lower_bound : ∀ x, lower * ‖x‖ ≤ N x + upper_bound : ∀ x, N x ≤ upper * ‖x‖ + +namespace EquivalentNorm + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (A : EquivalentNorm E) + +noncomputable def inner (x : E) (t : ℝ) (F : CofiniteSubspace E) : ℝ := + sInf {r : ℝ | ∃ y ∈ F.space, A.N y = 1 ∧ r = A.N (x + t • y) - 1} + +noncomputable def modulus (t : ℝ) : ℝ := + sInf {r : ℝ | ∃ x : E, A.N x = 1 ∧ r = sSup (Set.range (A.inner x t))} + +def AUC : Prop := ∀ t : ℝ, 0 < t → 0 < A.modulus t + +end EquivalentNorm + +open scoped ENNReal + +def IsReflexive (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ E) + +namespace SquareSum + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (E : ι → Type uFiber) + [∀ i, NormedAddCommGroup (E i)] [fiberNormedSpace : ∀ i, NormedSpace ℝ (E i)] + +abbrev Space : Type _ := ↥(lp E 2) + +end SquareSum + +open UniformSpace + +def completionEquivOfDense {E : Type uSpace} {F : Type uOther} [NormedAddCommGroup E] + [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [CompleteSpace F] (f : E →L[ℝ] F) + (K : NNReal) (hK : ∀ x, ‖x‖ ≤ K * ‖f x‖) (hdense : DenseRange f) : Completion E ≃L[ℝ] F := by + let g := f.fromCompletion + have hbound : ∀ x : Completion E, ‖x‖ ≤ K * ‖g x‖ := by + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_le continuous_norm (continuous_const.mul (g.continuous.norm)) + | ih x => simpa only [g, ContinuousLinearMap.fromCompletion_apply_coe, Completion.norm_coe] using hK x + have hanti := g.antilipschitz_of_bound hbound + have hclosed := hanti.isClosed_range g.uniformContinuous + have hsurj : Function.Surjective g := by + intro y + have hh : y ∈ closure (Set.range f) := hdense y + have hsub : Set.range f ⊆ Set.range g := by + rintro _ ⟨x, rfl⟩ + exact ⟨(x : Completion E), ContinuousLinearMap.fromCompletion_apply_coe f x⟩ + have hm := closure_mono hsub hh + rw [hclosed.closure_eq] at hm + exact hm + exact ContinuousLinearEquiv.ofBijective g (LinearMap.ker_eq_bot.mpr hanti.injective) + (LinearMap.range_eq_top.mpr hsurj) + +def componentTree (h : ℕ+) : FiniteRootedTree (ComponentNode h) where + root := ⟨[], by simp⟩ + parent s := ⟨s.1.dropLast, by rw [List.length_dropLast]; have := s.2; omega⟩ + depth s := s.1.length + parent_root := Subtype.ext rfl + depth_root := rfl + parent_depth s hs := by + rw [List.length_dropLast] + have hne : s.1 ≠ [] := fun h => hs (Subtype.ext h) + have hp := List.length_pos_iff_ne_nil.mpr hne + omega + +def logarithmicGamma (M β : ℝ) : ℝ := + let h := β ^ 2 / (2 * M ^ 2) + let c := β * Real.sqrt h / 8 + let H := 1 + Real.log (M / c) + let K := 4 * (2 + Real.sqrt 6) * H / h + β * h / 8 * Real.exp (-K) + +open Filter + +open scoped Topology + +structure ChildExponent where + val : ℝ + one_le : 1 ≤ val + +namespace ChildExponent + +variable (p : ChildExponent) + +def agg {ι : Type uIndex} (s : Finset ι) (f : ι → ℝ) : ℝ := + (∑ i ∈ s, |f i| ^ p.val) ^ (1 / p.val) + +end ChildExponent + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) (p : ChildExponent) + +def FiniteRootedTree.pfields (v : ι → ℝ) (s : ι) : ℝ × ℝ := + leastPair (v s) + (p.agg Finset.univ (fun c : {c // c ∈ T.children s} => (pfields v c.1).1)) + (p.agg Finset.univ (fun c : {c // c ∈ T.children s} => (pfields v c.1).2)) +termination_by T.maxDepth - T.depth s +decreasing_by + all_goals + have hc := (Finset.mem_filter.mp c.2).2 + have hd := T.parent_depth c.1 hc.1 + rw [hc.2] at hd + have hm : T.depth c.1 ≤ T.maxDepth := Finset.le_sup (Finset.mem_univ c.1) + omega + +end + +namespace VariableExponent + +def heightExponent (h : ℕ+) : ℝ := 1 + 1 / (h.val : ℝ) + +def cubicConstant : ℝ := (6 * Real.exp 1)⁻¹ ^ 3 + +def sixthConstant : ℝ := 2 * Real.exp (-(Real.exp 1 - 1)) * (4 : ℝ)⁻¹ ^ 6 + +end VariableExponent + +open Filter Topology TopologicalSpace + +end RecursivePotentials + +namespace ComparatorModel + +open scoped BigOperators + +namespace RecursivePotentials + +section + +noncomputable abbrev leastPair := @_root_.OAI.RecursivePotentials.leastPair + +noncomputable abbrev FiniteRootedTree := @_root_.OAI.RecursivePotentials.FiniteRootedTree + +namespace FiniteRootedTree + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) + +noncomputable abbrev Initial (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.Initial T + +end + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +noncomputable abbrev restrict (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.restrict T + +noncomputable abbrev extend (H : Finset ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.extend H + +noncomputable abbrev head (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.head T + +class Heads : Prop where + initial : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) (v : ι →₀ ℝ), + T.Initial (T.head v) + +variable [ComparatorModel.RecursivePotentials.FiniteRootedTree.Heads] + +noncomputable def P (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).fields + (fun s => v s.1) s).1) + +noncomputable def Q (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).fields + (fun s => v s.1) s).2) + +noncomputable def normSum (v : ι →₀ ℝ) : ℝ := T.P v T.root + T.Q v T.root + +noncomputable abbrev projectHead (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead T + +end FiniteRootedTree + +variable [ComparatorModel.RecursivePotentials.FiniteRootedTree.Heads] + +def TreeVector {ι : Type uIndex} (_T : FiniteRootedTree ι) := ι →₀ ℝ + +namespace TreeVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +instance : AddCommGroup (TreeVector T) := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) + +instance : Module ℝ (TreeVector T) := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : CoeFun (TreeVector T) (fun _ => ι → ℝ) := ⟨fun v => (show ι →₀ ℝ from v)⟩ + +noncomputable instance : Norm (TreeVector T) := ⟨fun v => T.normSum v⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι), + NormedSpace.Core ℝ (TreeVector T) + coordinate_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (v : ι →₀ ℝ) (s : ι), |v s| ≤ T.normSum v + projection_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (H : Finset ι), T.Initial H → ∀ v, T.normSum (T.projectHead H v) ≤ T.normSum v + +variable [ComparatorModel.RecursivePotentials.TreeVector.Construction] + +noncomputable instance : NormedAddCommGroup (TreeVector T) := + NormedAddCommGroup.ofCore (TreeVector.Construction.core T) + +noncomputable instance : NormedSpace ℝ (TreeVector T) := NormedSpace.ofCore (TreeVector.Construction.core T) + +def coordinateLinear (s : ι) : TreeVector T →ₗ[ℝ] ℝ where + toFun v := v s + map_add' _v _w := rfl + map_smul' _a _v := rfl + +noncomputable def coordinate (s : ι) : TreeVector T →L[ℝ] ℝ := + (coordinateLinear T s).mkContinuous 1 (fun v => by + change ‖v s‖ ≤ 1 * T.normSum v + rw [Real.norm_eq_abs, one_mul] + exact TreeVector.Construction.coordinate_bound T v s) + +def projectionLinear (H : Finset ι) : TreeVector T →ₗ[ℝ] TreeVector T where + toFun := T.projectHead H + map_add' v w := by + change ι →₀ ℝ at v w + apply Finsupp.ext + intro s + change T.projectHead H (v + w) s = (T.projectHead H v + T.projectHead H w) s + by_cases hs : s ∈ H <;> simp [FiniteRootedTree.projectHead, _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead, hs] + map_smul' a v := by + change ι →₀ ℝ at v + apply Finsupp.ext + intro s + change T.projectHead H (a • v) s = (a • T.projectHead H v) s + by_cases hs : s ∈ H <;> simp [FiniteRootedTree.projectHead, _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead, hs] + +noncomputable def projection (H : Finset ι) (hH : T.Initial H) : + TreeVector T →L[ℝ] TreeVector T := + (projectionLinear T H).mkContinuous 1 (fun v => by + change T.normSum (T.projectHead H v) ≤ 1 * T.normSum v + rw [one_mul] + exact TreeVector.Construction.projection_bound T H hH v) + +end TreeVector + +variable [ComparatorModel.RecursivePotentials.TreeVector.Construction] + +abbrev TreeSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) := + UniformSpace.Completion (TreeVector T) + +namespace TreeSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def coordinate (s : ι) : TreeSpace T →L[ℝ] ℝ := (TreeVector.coordinate T s).fromCompletion + +def P (s : ι) : TreeSpace T → ℝ := + Completion.extension (fun v : TreeVector T => T.P v s) + +def Q (s : ι) : TreeSpace T → ℝ := + Completion.extension (fun v : TreeVector T => T.Q v s) + +def projection (H : Finset ι) (hH : T.Initial H) : TreeSpace T →L[ℝ] TreeSpace T := + (TreeVector.projection T H hH).completion + +def tail (H : Finset ι) (hH : T.Initial H) : Submodule ℝ (TreeSpace T) := + (projection T H hH).ker + +end TreeSpace + +section Moduli + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] + +noncomputable abbrev averagedModulus := @_root_.OAI.RecursivePotentials.averagedModulus + +end Moduli + +noncomputable abbrev sequenceTree := @_root_.OAI.RecursivePotentials.sequenceTree + +noncomputable abbrev ComponentNode := @_root_.OAI.RecursivePotentials.ComponentNode + +noncomputable abbrev JoinedNode := @_root_.OAI.RecursivePotentials.JoinedNode + +noncomputable abbrev joinedTree := @_root_.OAI.RecursivePotentials.joinedTree + +abbrev XSigma := TreeSpace sequenceTree + +abbrev XJoined := TreeSpace joinedTree + +def ZeroTreeVector {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) : Type _ := + ↥((TreeVector.coordinate T T.root).ker) + +namespace ZeroTreeVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +instance : AddCommGroup (ZeroTreeVector T) := + inferInstanceAs (AddCommGroup (TreeVector.coordinate T T.root).ker) + +instance : Module ℝ (ZeroTreeVector T) := + inferInstanceAs (Module ℝ (TreeVector.coordinate T T.root).ker) + +def toTree : ZeroTreeVector T →ₗ[ℝ] TreeVector T := + (TreeVector.coordinate T T.root).ker.subtype + +instance : Norm (ZeroTreeVector T) := ⟨fun v => T.P (toTree T v) T.root⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι), + NormedSpace.Core ℝ (ZeroTreeVector T) + half : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (v : ZeroTreeVector T), ‖v‖ = ‖toTree T v‖ / 2 + +variable [ComparatorModel.RecursivePotentials.ZeroTreeVector.Construction] + +instance : NormedAddCommGroup (ZeroTreeVector T) := NormedAddCommGroup.ofCore (ZeroTreeVector.Construction.core T) + +instance : NormedSpace ℝ (ZeroTreeVector T) := NormedSpace.ofCore (ZeroTreeVector.Construction.core T) + +def inclusion : ZeroTreeVector T →L[ℝ] TreeVector T := + (toTree T).mkContinuous 2 (fun v => by rw [ZeroTreeVector.Construction.half]; exact le_of_eq (by ring)) + +def projectionLinear (H : Finset ι) (hH : T.Initial H) : ZeroTreeVector T →ₗ[ℝ] ZeroTreeVector T := + (((TreeVector.projection T H hH).toLinearMap).comp (toTree T)).codRestrict + (TreeVector.coordinate T T.root).ker (fun v => by + change TreeVector.coordinate T T.root (TreeVector.projection T H hH (toTree T v)) = 0 + change T.projectHead H (toTree T v) T.root = 0 + change (if T.root ∈ H then toTree T v T.root else 0) = 0 + rw [ite_eq_left hH.1] + exact v.2) + +def projection (H : Finset ι) (hH : T.Initial H) : ZeroTreeVector T →L[ℝ] ZeroTreeVector T := + (projectionLinear T H hH).mkContinuous 1 (fun v => by + rw [one_mul, ZeroTreeVector.Construction.half, ZeroTreeVector.Construction.half] + exact (div_le_div_iff_of_pos_right (by norm_num : (0 : ℝ) < 2)).mpr + (TreeVector.Construction.projection_bound T H hH (toTree T v))) + +end ZeroTreeVector + +variable [ComparatorModel.RecursivePotentials.ZeroTreeVector.Construction] + +abbrev ZeroTreeSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) := + UniformSpace.Completion (ZeroTreeVector T) + +namespace ZeroTreeSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def inclusion : ZeroTreeSpace T →L[ℝ] TreeSpace T := (ZeroTreeVector.inclusion T).completion + +def projection (H : Finset ι) (hH : T.Initial H) : ZeroTreeSpace T →L[ℝ] ZeroTreeSpace T := + (ZeroTreeVector.projection T H hH).completion + +def tail (H : Finset ι) (hH : T.Initial H) : Submodule ℝ (ZeroTreeSpace T) := + (projection T H hH).ker + +end ZeroTreeSpace + +abbrev XZero := ZeroTreeSpace joinedTree + +section + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def ZeroTreeSpace.coordinate (s : ι) : ZeroTreeSpace T →L[ℝ] ℝ := + (TreeSpace.coordinate T s).comp (inclusion T) + +def ZeroTreeSpace.P (s : ι) (x : ZeroTreeSpace T) : ℝ := TreeSpace.P T s (inclusion T x) + +def ZeroTreeSpace.Q (s : ι) (x : ZeroTreeSpace T) : ℝ := TreeSpace.Q T s (inclusion T x) + +end + +open Filter Topology + +noncomputable abbrev WeaklyNull := @_root_.OAI.RecursivePotentials.WeaklyNull + +noncomputable abbrev EquivalentNorm := @_root_.OAI.RecursivePotentials.EquivalentNorm + +namespace EquivalentNorm + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (A : EquivalentNorm E) + +noncomputable abbrev modulus (A : EquivalentNorm E) := _root_.OAI.RecursivePotentials.EquivalentNorm.modulus A + +noncomputable abbrev AUC (A : EquivalentNorm E) := _root_.OAI.RecursivePotentials.EquivalentNorm.AUC A + +end EquivalentNorm + +open scoped ENNReal + +noncomputable abbrev IsReflexive := @_root_.OAI.RecursivePotentials.IsReflexive + +namespace SquareSum + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (E : ι → Type uFiber) + [∀ i, NormedAddCommGroup (E i)] [fiberNormedSpace : ∀ i, NormedSpace ℝ (E i)] + +noncomputable abbrev Space := @_root_.OAI.RecursivePotentials.SquareSum.Space + +end SquareSum + +open UniformSpace + +noncomputable abbrev completionEquivOfDense := @_root_.OAI.RecursivePotentials.completionEquivOfDense + +noncomputable abbrev componentTree := @_root_.OAI.RecursivePotentials.componentTree + +noncomputable abbrev logarithmicGamma := @_root_.OAI.RecursivePotentials.logarithmicGamma + +open Filter + +open scoped Topology + +def XJoined_separated_familiesStatement : Prop := ∀ {ε : ℝ} (_hε : 0 < ε), + ∃ η : ℝ, 0 < η ∧ η < 1 ∧ + (ε ≤ 2 → η = min (1/2) (logarithmicGamma 2 (ε/16))) ∧ + ∀ (x : XJoined) (z : ℕ → XJoined), + (∀ n, ‖x+z n‖ ≤ 1) → (∀ n, ‖x-z n‖ ≤ 1) → + (∀ i j, i ≠ j → ε ≤ ‖z i-z j‖) → ‖x‖ ≤ 1-η + +noncomputable abbrev ChildExponent := @_root_.OAI.RecursivePotentials.ChildExponent + +namespace VariableExponent + +noncomputable abbrev heightExponent := @_root_.OAI.RecursivePotentials.VariableExponent.heightExponent + +noncomputable abbrev cubicConstant := @_root_.OAI.RecursivePotentials.VariableExponent.cubicConstant + +noncomputable abbrev sixthConstant := @_root_.OAI.RecursivePotentials.VariableExponent.sixthConstant + +end VariableExponent + +namespace VariableTree + +open FiniteRootedTree + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +noncomputable def P (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).pfields e + (fun s => v s.1) s).1) + +noncomputable def Q (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).pfields e + (fun s => v s.1) s).2) + +noncomputable def normSum (v : ι →₀ ℝ) : ℝ := P T e v T.root + Q T e v T.root + +end VariableTree + +def AggregationVector {ι : Type uIndex} (_T : FiniteRootedTree ι) (_e : ChildExponent) := ι →₀ ℝ + +namespace AggregationVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +instance : AddCommGroup (AggregationVector T e) := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) + +instance : Module ℝ (AggregationVector T e) := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : CoeFun (AggregationVector T e) (fun _ => ι → ℝ) := ⟨fun v => (show ι →₀ ℝ from v)⟩ + +noncomputable instance : Norm (AggregationVector T e) := ⟨fun v => VariableTree.normSum T e v⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) (e : ChildExponent), + NormedSpace.Core ℝ (AggregationVector T e) + coordinate_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) (v : ι →₀ ℝ) (s : ι), |v s| ≤ VariableTree.normSum T e v + +variable [ComparatorModel.RecursivePotentials.AggregationVector.Construction] + +noncomputable instance : NormedAddCommGroup (AggregationVector T e) := + NormedAddCommGroup.ofCore (AggregationVector.Construction.core T e) + +noncomputable instance : NormedSpace ℝ (AggregationVector T e) := NormedSpace.ofCore (AggregationVector.Construction.core T e) + +def coordinateLinear (s : ι) : AggregationVector T e →ₗ[ℝ] ℝ where + toFun v := v s + map_add' _v _w := rfl + map_smul' _a _v := rfl + +noncomputable def coordinate (s : ι) : AggregationVector T e →L[ℝ] ℝ := + (coordinateLinear T e s).mkContinuous 1 (fun v => by + change ‖v s‖ ≤ 1 * VariableTree.normSum T e v + rw [Real.norm_eq_abs, one_mul] + exact AggregationVector.Construction.coordinate_bound T e v s) + +end AggregationVector + +variable [ComparatorModel.RecursivePotentials.AggregationVector.Construction] + +abbrev AggregationSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) := + UniformSpace.Completion (AggregationVector T e) + +namespace AggregationSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +def coordinate (s : ι) : + AggregationSpace T e →L[ℝ] ℝ := (AggregationVector.coordinate T e s).fromCompletion + +def P (s : ι) : AggregationSpace T e → ℝ := + Completion.extension (fun v : AggregationVector T e => VariableTree.P T e v s) + +def Q (s : ι) : AggregationSpace T e → ℝ := + Completion.extension (fun v : AggregationVector T e => VariableTree.Q T e v s) + +end AggregationSpace + +section + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +def AggregationVector.basisVector (s : ι) : AggregationVector T e := Finsupp.single s 1 + +end + +open Filter Topology TopologicalSpace + +namespace ChildExponent + +instance (e : ChildExponent) : Fact (1 ≤ ENNReal.ofReal e.val) := + ⟨by simpa using ENNReal.ofReal_le_ofReal e.one_le⟩ + +end ChildExponent + +section + +open scoped ENNReal + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +abbrev AggregationVector.CoordinateLp (ι : Type uIndex) (e : ChildExponent) := ↥(lp (fun _ : ι => ℝ) (ENNReal.ofReal e.val)) + +def AggregationVector.toLpLinear : AggregationVector T e →ₗ[ℝ] CoordinateLp ι e := + Finsupp.lsum ℝ (fun s => lp.lsingle (𝕜 := ℝ) (E := fun _ : ι => ℝ) (ENNReal.ofReal e.val) s) + +class AggregationVector.LpConstruction : Prop where + bounds : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent), 1 < e.val → + (∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) → + ∀ h : ℕ, (∀ s, T.depth s ≤ h) → ∀ v : AggregationVector T e, + ‖v‖ ≤ (2*(h+1:ℝ)^(1-1/e.val))*‖toLpLinear T e v‖ ∧ + ‖toLpLinear T e v‖ ≤ (h+1:ℝ)^(1/e.val)*‖v‖ + dense : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent), DenseRange (toLpLinear T e) + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def AggregationVector.toLp (hp : 1 < e.val) + (hstep : ∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) + (h : ℕ) (hh : ∀ s, T.depth s ≤ h) : AggregationVector T e →L[ℝ] CoordinateLp ι e := + (toLpLinear T e).mkContinuous ((h+1:ℝ)^(1/e.val)) + (fun v => (LpConstruction.bounds T e hp hstep h hh v).2) + +end + +section + +open AggregationVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def AggregationSpace.lpEquiv (hp : 1 < e.val) + (hstep : ∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) + (h : ℕ) (hh : ∀ s, T.depth s ≤ h) : AggregationSpace T e ≃L[ℝ] CoordinateLp ι e := + completionEquivOfDense (AggregationVector.toLp T e hp hstep h hh) + ⟨2*(h+1:ℝ)^(1-1/e.val),by positivity⟩ + (fun v => (AggregationVector.LpConstruction.bounds T e hp hstep h hh v).1) + (AggregationVector.LpConstruction.dense T e) + +end + +namespace Variable + +section + +open UniformSpace VariableExponent Filter Topology TopologicalSpace + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def exponent (h : ℕ+) : ChildExponent := ⟨heightExponent h,(by + dsimp [heightExponent] + have hh : (0 : ℝ) < h.val := by exact_mod_cast h.pos + exact le_add_of_nonneg_right (le_of_lt (one_div_pos.mpr hh)))⟩ + +abbrev Component (h : ℕ+) := AggregationSpace (componentTree h) (exponent h) + +abbrev Xv := SquareSum.Space Component + +abbrev Node := Σ h : ℕ+, ComponentNode h + +def componentEquiv (h : ℕ+) : + Component h ≃L[ℝ] AggregationVector.CoordinateLp (ComponentNode h) (exponent h) := + AggregationSpace.lpEquiv (componentTree h) (exponent h) (by + dsimp [exponent, heightExponent] + have hh : (0 : ℝ) < h.val := by exact_mod_cast h.pos + exact lt_add_of_pos_right _ (one_div_pos.mpr hh)) + (by + intro c hc + change c.1.length = c.1.dropLast.length + 1 + rw [List.length_dropLast] + have hp := List.length_pos_iff_ne_nil.mpr (show c.1 ≠ [] from fun he => hc (Subtype.ext he)) + omega) h.val (fun c => c.2) + +def componentCoordinate (h : ℕ+) (s : ComponentNode h) : Component h →L[ℝ] ℝ := + AggregationSpace.coordinate (componentTree h) (exponent h) s + +def coordinate (s : Node) : Xv →L[ℝ] ℝ := + (componentCoordinate s.1 s.2).comp (lp.evalCLM ℝ Component 2 s.1) + +def basis (s : Node) : Xv := lp.single 2 s.1 + ((AggregationVector.basisVector (componentTree s.1) (exponent s.1) s.2 : AggregationVector (componentTree s.1) (exponent s.1)) : Component s.1) + +def FiniteTotalSupport (x : Xv) : Prop := ∃ S : Finset Node, ∀ s ∉ S, coordinate s x = 0 + +def projection (S : Finset Node) : Xv →L[ℝ] Xv := ∑ s ∈ S, (coordinate s).smulRight (basis s) + +def AdmissibleHeads (x y : Xv) (A : ∀ h, Finset (ComponentNode h)) : Prop := + ∀ h, x h ≠ 0 → (componentTree h).Initial (A h) ∧ + (∀ s ∉ A h, componentCoordinate h s (x h) = 0) ∧ + (∀ s ∈ A h, componentCoordinate h s (y h) = 0) + +def cubic_stabilityStatement : Prop := ∀ (x y : Xv) (_hx : FiniteTotalSupport x) (A : ∀ h, Finset (ComponentNode h)) + (_hA : AdmissibleHeads x y A) {R : ℝ} (_hR : 0 < R) (_hp : ‖x+y‖ ≤ R) (_hm : ‖x-y‖ ≤ R), + ‖x‖^2+cubicConstant/(2*Real.sqrt 2*R)*‖y‖^3 ≤ R^2 + +def sixth_stabilityStatement : Prop := ∀ (x y : Xv) (_hx : FiniteTotalSupport x) (A : ∀ h, Finset (ComponentNode h)) + (_hA : AdmissibleHeads x y A), + sixthConstant*‖y‖^6/(‖x+y‖^2+‖x-y‖^2)^2 ≤ ‖x+y‖^2+‖x-y‖^2-2*‖x‖^2 + +open UniformSpace VariableExponent Filter Topology TopologicalSpace + +def weakTailConstant : ℝ := cubicConstant/(2*Real.sqrt 2) + +def theta (ε : ℝ) : ℝ := Real.sqrt (1-weakTailConstant*ε^3) + +def weak_tailStatement : Prop := ∀ (x : Xv) {ε : ℝ} (_hε : 0 < ε) (_hε1 : ε ≤ 1) + (y : ℕ → Xv) (_hy : WeaklyNull y) (_hyε : ∀ j, ε ≤ ‖y j‖) + (_hp : ∀ j, ‖x+y j‖ ≤ 1) (_hm : ∀ j, ‖x-y j‖ ≤ 1), + ‖x‖ ≤ theta ε ∧ theta ε < 1 + +end + +open UniformSpace VariableExponent Filter Topology + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def one_sided_modulus_zeroStatement : Prop := ∀ (A : EquivalentNorm Xv), + A.modulus (A.lower/A.upper) = 0 + +def no_equivalent_AUCStatement : Prop := ∀ (A : EquivalentNorm Xv), + ¬A.AUC + +end Variable + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +structure RootSumCompletionStatement {ι : Type uIndex} [DecidableEq ι] + (T : FiniteRootedTree ι) : Prop where + complete : CompleteSpace (TreeSpace T) + infinite_dimensional : ¬Module.Finite ℝ (TreeSpace T) + coordinate_continuous : ∀ s, Continuous (TreeSpace.coordinate T s) + coordinate_extends : ∀ s (v : TreeVector T), TreeSpace.coordinate T s (v : TreeSpace T) = v s + fields_continuous : ∀ s, Continuous (TreeSpace.P T s) ∧ Continuous (TreeSpace.Q T s) + fields_extend : ∀ s (v : TreeVector T), + TreeSpace.P T s (v : TreeSpace T) = T.P v s ∧ TreeSpace.Q T s (v : TreeSpace T) = T.Q v s + root_formula : ∀ x : TreeSpace T, ‖x‖ = TreeSpace.P T T.root x + TreeSpace.Q T T.root x + projections : ∀ (H : Finset ι) (hH : T.Initial H), + (∀ x : TreeSpace T, ‖TreeSpace.projection T H hH x‖ ≤ ‖x‖) ∧ + (∀ x : TreeSpace T, TreeSpace.projection T H hH (TreeSpace.projection T H hH x) = TreeSpace.projection T H hH x) ∧ + (∀ (s : ι) (x : TreeSpace T), TreeSpace.coordinate T s (TreeSpace.projection T H hH x) = + if s ∈ H then TreeSpace.coordinate T s x else 0) ∧ + FiniteDimensional ℝ (TreeSpace.projection T H hH).range ∧ + IsClosed (TreeSpace.tail T H hH : Set (TreeSpace T)) ∧ + Module.Finite ℝ (TreeSpace T ⧸ TreeSpace.tail T H hH) ∧ + ∀ x ∈ TreeSpace.tail T H hH, ∀ ε : ℝ, 0 < ε → + ∃ v : TreeVector T, TreeVector.projection T H hH v = 0 ∧ ‖(v : TreeSpace T)-x‖ < ε + +structure ZeroRootCompletionStatement {ι : Type uIndex} [DecidableEq ι] + (T : FiniteRootedTree ι) : Prop where + complete : CompleteSpace (ZeroTreeSpace T) + infinite_dimensional : ¬Module.Finite ℝ (ZeroTreeSpace T) + coordinate_continuous : ∀ s, Continuous (ZeroTreeSpace.coordinate T s) + coordinate_extends : ∀ s (v : ZeroTreeVector T), + ZeroTreeSpace.coordinate T s (v : ZeroTreeSpace T) = ZeroTreeVector.toTree T v s + fields_continuous : ∀ s, Continuous (ZeroTreeSpace.P T s) ∧ Continuous (ZeroTreeSpace.Q T s) + fields_extend : ∀ s (v : ZeroTreeVector T), + ZeroTreeSpace.P T s (v : ZeroTreeSpace T) = T.P (ZeroTreeVector.toTree T v) s ∧ + ZeroTreeSpace.Q T s (v : ZeroTreeSpace T) = T.Q (ZeroTreeVector.toTree T v) s + root_fixed : ∀ x : ZeroTreeSpace T, ZeroTreeSpace.coordinate T T.root x = 0 + root_formula : ∀ x : ZeroTreeSpace T, ‖x‖ = ZeroTreeSpace.P T T.root x ∧ ‖x‖ = ZeroTreeSpace.Q T T.root x + projections : ∀ (H : Finset ι) (hH : T.Initial H), + (∀ x : ZeroTreeSpace T, ‖ZeroTreeSpace.projection T H hH x‖ ≤ ‖x‖) ∧ + (∀ x : ZeroTreeSpace T, ZeroTreeSpace.projection T H hH (ZeroTreeSpace.projection T H hH x) = ZeroTreeSpace.projection T H hH x) ∧ + (∀ (s : ι) (x : ZeroTreeSpace T), ZeroTreeSpace.coordinate T s (ZeroTreeSpace.projection T H hH x) = + if s ∈ H then ZeroTreeSpace.coordinate T s x else 0) ∧ + FiniteDimensional ℝ (ZeroTreeSpace.projection T H hH).range ∧ + IsClosed (ZeroTreeSpace.tail T H hH : Set (ZeroTreeSpace T)) ∧ + Module.Finite ℝ (ZeroTreeSpace T ⧸ ZeroTreeSpace.tail T H hH) ∧ + ∀ x ∈ ZeroTreeSpace.tail T H hH, ∀ ε : ℝ, 0 < ε → + ∃ v : ZeroTreeVector T, ZeroTreeVector.projection T H hH v = 0 ∧ ‖(v : ZeroTreeSpace T)-x‖ < ε + +def rec_completionStatement : Prop := RootSumCompletionStatement sequenceTree ∧ + ZeroRootCompletionStatement joinedTree ∧ RootSumCompletionStatement joinedTree ∧ + IsReflexive XZero ∧ IsReflexive XJoined + +def rec_mainStatement : Prop := (∀ t : ℝ, 0 < t → t < 1 → t^3/128 ≤ averagedModulus XSigma t ∧ t^3/128 ≤ averagedModulus XJoined t) ∧ + (∀ (H : Finset JoinedNode), joinedTree.Initial H → ∀ x : XZero, + (∀ s ∉ H, ZeroTreeSpace.coordinate joinedTree s x = 0) → ∀ z : XZero, + (∀ s ∈ H, ZeroTreeSpace.coordinate joinedTree s z = 0) → z ≠ 0 → + (‖x+z‖+‖x-z‖)/2 ≥ ‖x‖+‖z‖^3/(8*(2*‖x‖+‖z‖)^2)) ∧ + (∀ A : EquivalentNorm XSigma, ¬A.AUC) ∧ + (∀ A : EquivalentNorm XZero, ¬A.AUC) ∧ + (∀ A : EquivalentNorm XJoined, ¬A.AUC) + +def stop_all_radiiStatement : Prop := ∀ {t : ℝ} (_ht : 0 < t), + 0 < averagedModulus XSigma t + +open VariableExponent + +def Variable.nu (h : ℕ+) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) : ℝ := + AggregationSpace.P (componentTree h) (exponent h) (componentTree h).root ((componentEquiv h).symm v) + + AggregationSpace.Q (componentTree h) (exponent h) (componentTree h).root ((componentEquiv h).symm v) + +structure Variable.SourceNormStatement (h : ℕ+) : Prop where + nonneg : ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), 0 ≤ nu h v + definite : ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), nu h v = 0 ↔ v = 0 + triangle : ∀ v w : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), + nu h (v+w) ≤ nu h v + nu h w + homogeneous : ∀ (a : ℝ) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)), + nu h (a • v) = |a| * nu h v + +def Variable.spaceStatement : Prop := (∀ h : ℕ+, CompleteSpace (Component h) ∧ IsReflexive (Component h) ∧ + SeparableSpace (Component h →L[ℝ] ℝ) ∧ SourceNormStatement h ∧ + ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), + (h.val+1:ℝ)^(-1/heightExponent h)*‖v‖ ≤ nu h v ∧ + nu h v ≤ 2*(h.val+1:ℝ)^(1-1/heightExponent h)*‖v‖) ∧ + CompleteSpace Xv ∧ IsReflexive Xv ∧ SeparableSpace (Xv →L[ℝ] ℝ) ∧ + Dense {x : Xv | FiniteTotalSupport x} ∧ + ∀ S : Finset Node, Continuous (projection S) ∧ FiniteDimensional ℝ (projection S).range ∧ + (∀ x : Xv, projection S (projection S x) = projection S x) ∧ + ∀ (s : Node) (x : Xv), coordinate s (projection S x) = if s ∈ S then coordinate s x else 0 + +def Variable.aggregateChildren (h : ℕ+) (s : ComponentNode h) (f : ComponentNode h → ℝ) : ℝ := + (∑' c, if c ≠ (componentTree h).root ∧ (componentTree h).parent c = s then + f c ^ heightExponent h else 0) ^ (1/heightExponent h) + +def Variable.lpPotentials (h : ℕ+) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) + (s : ComponentNode h) : ℝ × ℝ := + (AggregationSpace.P (componentTree h) (exponent h) s ((componentEquiv h).symm v), + AggregationSpace.Q (componentTree h) (exponent h) s ((componentEquiv h).symm v)) + +def Variable.lp_model_exactStatement : Prop := ∀ (h : ℕ+) + (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) + (f : ComponentNode h → ℝ × ℝ) + (_hf : ∀ s, f s = leastPair (v s) + (aggregateChildren h s (fun c => (f c).1)) + (aggregateChildren h s (fun c => (f c).2))), + f = lpPotentials h v ∧ nu h v = (f (componentTree h).root).1+(f (componentTree h).root).2 + +end + +def MainClaim : Prop := + ∃ h0 : FiniteRootedTree.Heads.{0}, letI := h0; + ∃ h1 : TreeVector.Construction.{0}, letI := h1; + ∃ h2 : ZeroTreeVector.Construction.{0}, letI := h2; + ∃ h3 : AggregationVector.Construction.{0}, letI := h3; + ∃ h4 : AggregationVector.LpConstruction.{0}, letI := h4; + rec_mainStatement ∧ + rec_completionStatement ∧ + stop_all_radiiStatement ∧ + XJoined_separated_familiesStatement ∧ + Variable.spaceStatement ∧ + Variable.lp_model_exactStatement ∧ + Variable.one_sided_modulus_zeroStatement ∧ + Variable.no_equivalent_AUCStatement ∧ + Variable.sixth_stabilityStatement ∧ + Variable.cubic_stabilityStatement ∧ + Variable.weak_tailStatement + +theorem main : MainClaim := by + sorry + +end RecursivePotentials + +end ComparatorModel + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RecursivePotentials.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ComparatorModel.RecursivePotentials.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/recursive-potentials/solution/closure.txt b/tasks/recursive-potentials/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..00407e8b396552d4d2ad17c73b7c490765717274 --- /dev/null +++ b/tasks/recursive-potentials/solution/closure.txt @@ -0,0 +1,12 @@ +OAI.Analysis.RecursivePotentials.Challenge +OAI.Analysis.RecursivePotentials.ChallengeDefinitions +OAI.Analysis.RecursivePotentials.EquivalentNorms +OAI.Analysis.RecursivePotentials.JoinedGeometry +OAI.Analysis.RecursivePotentials.Main +OAI.Analysis.RecursivePotentials.Model +OAI.Analysis.RecursivePotentials.TreeGeometry +OAI.Analysis.RecursivePotentials.VariableCompletion +OAI.Analysis.RecursivePotentials.VariableEstimates +OAI.Analysis.RecursivePotentials.VariableLp +OAI.Analysis.RecursivePotentials.VariableStability +OAI.Analysis.RecursivePotentials.ZeroRootGeometry diff --git a/tasks/recursive-potentials/solution/reference.py b/tasks/recursive-potentials/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/recursive-potentials/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/recursive-potentials/solution/solve.sh b/tasks/recursive-potentials/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6578c2cbdb4ce8dee4ed25b28dbb85f4d40b23c6 --- /dev/null +++ b/tasks/recursive-potentials/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RecursivePotentials, i.e. module OAI.Analysis.RecursivePotentials.Challenge and the +# 12 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.RecursivePotentials.Challenge /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RecursivePotentials" diff --git a/tasks/recursive-potentials/task.toml b/tasks/recursive-potentials/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3fceb910c1df73f08bab798fa46de898b5478f69 --- /dev/null +++ b/tasks/recursive-potentials/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/recursive-potentials" +version = "1.0.0" +description = "Prove RecursivePotentials (openai/math family 331: Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RecursivePotentials.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RecursivePotentials" +family = "331" +family_title = "Asymptotic midpoint uniform convexity without asymptotically uniformly convex renorming" +subject = "Functional analysis" +theorems = ["OAI.ComparatorModel.RecursivePotentials.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.RecursivePotentials.Challenge" +reference_modules = 12 +reference_lean_bytes = 445768 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 617 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12101 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/recursive-potentials/tests/Challenge.lean b/tasks/recursive-potentials/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..4a6258dc2253ba0a22adf82e1450432c64a2bd8a --- /dev/null +++ b/tasks/recursive-potentials/tests/Challenge.lean @@ -0,0 +1,964 @@ +import Mathlib + +namespace OAI + +noncomputable section + +/-! +The final claim constructs the spaces and states all eleven original results. +`Analysis.RecursivePotentials.Challenge.main_iff_original` verifies statement preservation. +-/ + +universe uIndex uSpace uOther uDomain uTarget uFiber + +open scoped BigOperators + +namespace RecursivePotentials + +def leastPair (x a b : ℝ) : ℝ × ℝ := (max a (x + b), max b (-x + a)) + +structure FiniteRootedTree (ι : Type uIndex) where + root : ι + parent : ι → ι + depth : ι → ℕ + parent_root : parent root = root + depth_root : depth root = 0 + parent_depth : ∀ i, i ≠ root → depth (parent i) < depth i + +namespace FiniteRootedTree + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) + +def children (s : ι) : Finset ι := + Finset.univ.filter fun c => c ≠ T.root ∧ T.parent c = s + +def maxDepth : ℕ := Finset.univ.sup T.depth + +noncomputable def fields (v : ι → ℝ) (s : ι) : ℝ × ℝ := + leastPair (v s) + (Real.sqrt (∑ c : {c // c ∈ T.children s}, (fields v c.1).1 ^ 2)) + (Real.sqrt (∑ c : {c // c ∈ T.children s}, (fields v c.1).2 ^ 2)) +termination_by T.maxDepth - T.depth s +decreasing_by + all_goals + have hc := (Finset.mem_filter.mp c.2).2 + have hd := T.parent_depth c.1 hc.1 + rw [hc.2] at hd + have hm : T.depth c.1 ≤ T.maxDepth := Finset.le_sup (Finset.mem_univ c.1) + omega + +def Initial (H : Finset ι) : Prop := T.root ∈ H ∧ ∀ s ∈ H, T.parent s ∈ H + +end + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def ancestors (s : ι) : Finset ι := + if _hs : s = T.root then {s} else insert s (ancestors (T.parent s)) +termination_by T.depth s +decreasing_by exact T.parent_depth s _hs + +def ancestorClosure (S : Finset ι) : Finset ι := + insert T.root (S.biUnion T.ancestors) + +def restrict (H : Finset ι) (hH : T.Initial H) : FiniteRootedTree H where + root := ⟨T.root, hH.1⟩ + parent s := ⟨T.parent s, hH.2 s.1 s.2⟩ + depth s := T.depth s + parent_root := Subtype.ext T.parent_root + depth_root := T.depth_root + parent_depth s hs := T.parent_depth s (fun h => hs (Subtype.ext h)) + +noncomputable def extend (H : Finset ι) (f : H → ℝ) : ι →₀ ℝ := + Finsupp.onFinset H (fun s => if hs : s ∈ H then f ⟨s, hs⟩ else 0) + (fun s hs => by by_contra hh; simp [hh] at hs) + +def head (v : ι →₀ ℝ) : Finset ι := T.ancestorClosure v.support + +def projectHead (_T : FiniteRootedTree ι) (H : Finset ι) (v : ι →₀ ℝ) : ι →₀ ℝ := v.filter (· ∈ H) + +end FiniteRootedTree + +structure CofiniteSubspace (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] where + space : Submodule ℝ E + closed : IsClosed (space : Set E) + finiteQuotient : Module.Finite ℝ (E ⧸ space) + +section Moduli + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] + +noncomputable def averagedGain (x : E) (t : ℝ) (y : E) : ℝ := (‖x + t • y‖ + ‖x - t • y‖) / 2 - 1 + +noncomputable def averagedInner (x : E) (t : ℝ) (F : CofiniteSubspace E) : ℝ := + sInf {r : ℝ | ∃ y ∈ F.space, 1 ≤ ‖y‖ ∧ r = averagedGain x t y} + +noncomputable def averagedModulus (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] + (t : ℝ) : ℝ := + sInf {r : ℝ | ∃ x : E, ‖x‖ = 1 ∧ r = sSup (Set.range (averagedInner x t))} + +end Moduli + +def sequenceTree : FiniteRootedTree (List ℕ) where + root := [] + parent := List.dropLast + depth := List.length + parent_root := rfl + depth_root := rfl + parent_depth s hs := by + rw [List.length_dropLast] + have h := List.length_pos_iff_ne_nil.mpr hs + omega + +abbrev ComponentNode (h : ℕ+) := {s : List ℕ // s.length ≤ h.val} + +abbrev JoinedNode := Option (Σ h : ℕ+, ComponentNode h) + +def joinedTree : FiniteRootedTree JoinedNode where + root := none + parent + | none => none + | some ⟨h, s⟩ => if s.1 = [] then none else + some ⟨h, ⟨s.1.dropLast, by rw [List.length_dropLast]; have := s.2; omega⟩⟩ + depth + | none => 0 + | some ⟨_, s⟩ => s.1.length + 1 + parent_root := rfl + depth_root := rfl + parent_depth s hs := by + cases s with + | none => exact (hs rfl).elim + | some s => + obtain ⟨h, s⟩ := s + dsimp + by_cases he : s.1 = [] + · simp [he] + · rw [ite_eq_right he] + dsimp + rw [List.length_dropLast] + have hpos := List.length_pos_iff_ne_nil.mpr he + omega + +open Filter Topology + +def WeaklyNull {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (d : ℕ → E) : Prop := + ∀ f : E →L[ℝ] ℝ, Tendsto (fun k => f (d k)) atTop (𝓝 0) + +structure EquivalentNorm (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] where + N : Seminorm ℝ E + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + lower_le_upper : lower ≤ upper + lower_bound : ∀ x, lower * ‖x‖ ≤ N x + upper_bound : ∀ x, N x ≤ upper * ‖x‖ + +namespace EquivalentNorm + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (A : EquivalentNorm E) + +noncomputable def inner (x : E) (t : ℝ) (F : CofiniteSubspace E) : ℝ := + sInf {r : ℝ | ∃ y ∈ F.space, A.N y = 1 ∧ r = A.N (x + t • y) - 1} + +noncomputable def modulus (t : ℝ) : ℝ := + sInf {r : ℝ | ∃ x : E, A.N x = 1 ∧ r = sSup (Set.range (A.inner x t))} + +def AUC : Prop := ∀ t : ℝ, 0 < t → 0 < A.modulus t + +end EquivalentNorm + +open scoped ENNReal + +def IsReflexive (E : Type uSpace) [NormedAddCommGroup E] [NormedSpace ℝ E] : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ E) + +namespace SquareSum + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (E : ι → Type uFiber) + [∀ i, NormedAddCommGroup (E i)] [fiberNormedSpace : ∀ i, NormedSpace ℝ (E i)] + +abbrev Space : Type _ := ↥(lp E 2) + +end SquareSum + +open UniformSpace + +def completionEquivOfDense {E : Type uSpace} {F : Type uOther} [NormedAddCommGroup E] + [NormedSpace ℝ E] [NormedAddCommGroup F] [NormedSpace ℝ F] [CompleteSpace F] (f : E →L[ℝ] F) + (K : NNReal) (hK : ∀ x, ‖x‖ ≤ K * ‖f x‖) (hdense : DenseRange f) : Completion E ≃L[ℝ] F := by + let g := f.fromCompletion + have hbound : ∀ x : Completion E, ‖x‖ ≤ K * ‖g x‖ := by + intro x + induction x using Completion.induction_on with + | hp => exact isClosed_le continuous_norm (continuous_const.mul (g.continuous.norm)) + | ih x => simpa only [g, ContinuousLinearMap.fromCompletion_apply_coe, Completion.norm_coe] using hK x + have hanti := g.antilipschitz_of_bound hbound + have hclosed := hanti.isClosed_range g.uniformContinuous + have hsurj : Function.Surjective g := by + intro y + have hh : y ∈ closure (Set.range f) := hdense y + have hsub : Set.range f ⊆ Set.range g := by + rintro _ ⟨x, rfl⟩ + exact ⟨(x : Completion E), ContinuousLinearMap.fromCompletion_apply_coe f x⟩ + have hm := closure_mono hsub hh + rw [hclosed.closure_eq] at hm + exact hm + exact ContinuousLinearEquiv.ofBijective g (LinearMap.ker_eq_bot.mpr hanti.injective) + (LinearMap.range_eq_top.mpr hsurj) + +def componentTree (h : ℕ+) : FiniteRootedTree (ComponentNode h) where + root := ⟨[], by simp⟩ + parent s := ⟨s.1.dropLast, by rw [List.length_dropLast]; have := s.2; omega⟩ + depth s := s.1.length + parent_root := Subtype.ext rfl + depth_root := rfl + parent_depth s hs := by + rw [List.length_dropLast] + have hne : s.1 ≠ [] := fun h => hs (Subtype.ext h) + have hp := List.length_pos_iff_ne_nil.mpr hne + omega + +def logarithmicGamma (M β : ℝ) : ℝ := + let h := β ^ 2 / (2 * M ^ 2) + let c := β * Real.sqrt h / 8 + let H := 1 + Real.log (M / c) + let K := 4 * (2 + Real.sqrt 6) * H / h + β * h / 8 * Real.exp (-K) + +open Filter + +open scoped Topology + +structure ChildExponent where + val : ℝ + one_le : 1 ≤ val + +namespace ChildExponent + +variable (p : ChildExponent) + +def agg {ι : Type uIndex} (s : Finset ι) (f : ι → ℝ) : ℝ := + (∑ i ∈ s, |f i| ^ p.val) ^ (1 / p.val) + +end ChildExponent + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) (p : ChildExponent) + +def FiniteRootedTree.pfields (v : ι → ℝ) (s : ι) : ℝ × ℝ := + leastPair (v s) + (p.agg Finset.univ (fun c : {c // c ∈ T.children s} => (pfields v c.1).1)) + (p.agg Finset.univ (fun c : {c // c ∈ T.children s} => (pfields v c.1).2)) +termination_by T.maxDepth - T.depth s +decreasing_by + all_goals + have hc := (Finset.mem_filter.mp c.2).2 + have hd := T.parent_depth c.1 hc.1 + rw [hc.2] at hd + have hm : T.depth c.1 ≤ T.maxDepth := Finset.le_sup (Finset.mem_univ c.1) + omega + +end + +namespace VariableExponent + +def heightExponent (h : ℕ+) : ℝ := 1 + 1 / (h.val : ℝ) + +def cubicConstant : ℝ := (6 * Real.exp 1)⁻¹ ^ 3 + +def sixthConstant : ℝ := 2 * Real.exp (-(Real.exp 1 - 1)) * (4 : ℝ)⁻¹ ^ 6 + +end VariableExponent + +open Filter Topology TopologicalSpace + +end RecursivePotentials + +namespace ComparatorModel + +open scoped BigOperators + +namespace RecursivePotentials + +section + +noncomputable abbrev leastPair := @_root_.OAI.RecursivePotentials.leastPair + +noncomputable abbrev FiniteRootedTree := @_root_.OAI.RecursivePotentials.FiniteRootedTree + +namespace FiniteRootedTree + +section + +variable {ι : Type uIndex} [indexFinite : Fintype ι] [indexDecidable : DecidableEq ι] + (T : FiniteRootedTree ι) + +noncomputable abbrev Initial (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.Initial T + +end + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +noncomputable abbrev restrict (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.restrict T + +noncomputable abbrev extend (H : Finset ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.extend H + +noncomputable abbrev head (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.head T + +class Heads : Prop where + initial : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) (v : ι →₀ ℝ), + T.Initial (T.head v) + +variable [ComparatorModel.RecursivePotentials.FiniteRootedTree.Heads] + +noncomputable def P (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).fields + (fun s => v s.1) s).1) + +noncomputable def Q (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).fields + (fun s => v s.1) s).2) + +noncomputable def normSum (v : ι →₀ ℝ) : ℝ := T.P v T.root + T.Q v T.root + +noncomputable abbrev projectHead (T : FiniteRootedTree ι) := _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead T + +end FiniteRootedTree + +variable [ComparatorModel.RecursivePotentials.FiniteRootedTree.Heads] + +def TreeVector {ι : Type uIndex} (_T : FiniteRootedTree ι) := ι →₀ ℝ + +namespace TreeVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +instance : AddCommGroup (TreeVector T) := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) + +instance : Module ℝ (TreeVector T) := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : CoeFun (TreeVector T) (fun _ => ι → ℝ) := ⟨fun v => (show ι →₀ ℝ from v)⟩ + +noncomputable instance : Norm (TreeVector T) := ⟨fun v => T.normSum v⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι), + NormedSpace.Core ℝ (TreeVector T) + coordinate_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (v : ι →₀ ℝ) (s : ι), |v s| ≤ T.normSum v + projection_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (H : Finset ι), T.Initial H → ∀ v, T.normSum (T.projectHead H v) ≤ T.normSum v + +variable [ComparatorModel.RecursivePotentials.TreeVector.Construction] + +noncomputable instance : NormedAddCommGroup (TreeVector T) := + NormedAddCommGroup.ofCore (TreeVector.Construction.core T) + +noncomputable instance : NormedSpace ℝ (TreeVector T) := NormedSpace.ofCore (TreeVector.Construction.core T) + +def coordinateLinear (s : ι) : TreeVector T →ₗ[ℝ] ℝ where + toFun v := v s + map_add' _v _w := rfl + map_smul' _a _v := rfl + +noncomputable def coordinate (s : ι) : TreeVector T →L[ℝ] ℝ := + (coordinateLinear T s).mkContinuous 1 (fun v => by + change ‖v s‖ ≤ 1 * T.normSum v + rw [Real.norm_eq_abs, one_mul] + exact TreeVector.Construction.coordinate_bound T v s) + +def projectionLinear (H : Finset ι) : TreeVector T →ₗ[ℝ] TreeVector T where + toFun := T.projectHead H + map_add' v w := by + change ι →₀ ℝ at v w + apply Finsupp.ext + intro s + change T.projectHead H (v + w) s = (T.projectHead H v + T.projectHead H w) s + by_cases hs : s ∈ H <;> simp [FiniteRootedTree.projectHead, _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead, hs] + map_smul' a v := by + change ι →₀ ℝ at v + apply Finsupp.ext + intro s + change T.projectHead H (a • v) s = (a • T.projectHead H v) s + by_cases hs : s ∈ H <;> simp [FiniteRootedTree.projectHead, _root_.OAI.RecursivePotentials.FiniteRootedTree.projectHead, hs] + +noncomputable def projection (H : Finset ι) (hH : T.Initial H) : + TreeVector T →L[ℝ] TreeVector T := + (projectionLinear T H).mkContinuous 1 (fun v => by + change T.normSum (T.projectHead H v) ≤ 1 * T.normSum v + rw [one_mul] + exact TreeVector.Construction.projection_bound T H hH v) + +end TreeVector + +variable [ComparatorModel.RecursivePotentials.TreeVector.Construction] + +abbrev TreeSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) := + UniformSpace.Completion (TreeVector T) + +namespace TreeSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def coordinate (s : ι) : TreeSpace T →L[ℝ] ℝ := (TreeVector.coordinate T s).fromCompletion + +def P (s : ι) : TreeSpace T → ℝ := + Completion.extension (fun v : TreeVector T => T.P v s) + +def Q (s : ι) : TreeSpace T → ℝ := + Completion.extension (fun v : TreeVector T => T.Q v s) + +def projection (H : Finset ι) (hH : T.Initial H) : TreeSpace T →L[ℝ] TreeSpace T := + (TreeVector.projection T H hH).completion + +def tail (H : Finset ι) (hH : T.Initial H) : Submodule ℝ (TreeSpace T) := + (projection T H hH).ker + +end TreeSpace + +section Moduli + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] + +noncomputable abbrev averagedModulus := @_root_.OAI.RecursivePotentials.averagedModulus + +end Moduli + +noncomputable abbrev sequenceTree := @_root_.OAI.RecursivePotentials.sequenceTree + +noncomputable abbrev ComponentNode := @_root_.OAI.RecursivePotentials.ComponentNode + +noncomputable abbrev JoinedNode := @_root_.OAI.RecursivePotentials.JoinedNode + +noncomputable abbrev joinedTree := @_root_.OAI.RecursivePotentials.joinedTree + +abbrev XSigma := TreeSpace sequenceTree + +abbrev XJoined := TreeSpace joinedTree + +def ZeroTreeVector {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) : Type _ := + ↥((TreeVector.coordinate T T.root).ker) + +namespace ZeroTreeVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +instance : AddCommGroup (ZeroTreeVector T) := + inferInstanceAs (AddCommGroup (TreeVector.coordinate T T.root).ker) + +instance : Module ℝ (ZeroTreeVector T) := + inferInstanceAs (Module ℝ (TreeVector.coordinate T T.root).ker) + +def toTree : ZeroTreeVector T →ₗ[ℝ] TreeVector T := + (TreeVector.coordinate T T.root).ker.subtype + +instance : Norm (ZeroTreeVector T) := ⟨fun v => T.P (toTree T v) T.root⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι), + NormedSpace.Core ℝ (ZeroTreeVector T) + half : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (v : ZeroTreeVector T), ‖v‖ = ‖toTree T v‖ / 2 + +variable [ComparatorModel.RecursivePotentials.ZeroTreeVector.Construction] + +instance : NormedAddCommGroup (ZeroTreeVector T) := NormedAddCommGroup.ofCore (ZeroTreeVector.Construction.core T) + +instance : NormedSpace ℝ (ZeroTreeVector T) := NormedSpace.ofCore (ZeroTreeVector.Construction.core T) + +def inclusion : ZeroTreeVector T →L[ℝ] TreeVector T := + (toTree T).mkContinuous 2 (fun v => by rw [ZeroTreeVector.Construction.half]; exact le_of_eq (by ring)) + +def projectionLinear (H : Finset ι) (hH : T.Initial H) : ZeroTreeVector T →ₗ[ℝ] ZeroTreeVector T := + (((TreeVector.projection T H hH).toLinearMap).comp (toTree T)).codRestrict + (TreeVector.coordinate T T.root).ker (fun v => by + change TreeVector.coordinate T T.root (TreeVector.projection T H hH (toTree T v)) = 0 + change T.projectHead H (toTree T v) T.root = 0 + change (if T.root ∈ H then toTree T v T.root else 0) = 0 + rw [ite_eq_left hH.1] + exact v.2) + +def projection (H : Finset ι) (hH : T.Initial H) : ZeroTreeVector T →L[ℝ] ZeroTreeVector T := + (projectionLinear T H hH).mkContinuous 1 (fun v => by + rw [one_mul, ZeroTreeVector.Construction.half, ZeroTreeVector.Construction.half] + exact (div_le_div_iff_of_pos_right (by norm_num : (0 : ℝ) < 2)).mpr + (TreeVector.Construction.projection_bound T H hH (toTree T v))) + +end ZeroTreeVector + +variable [ComparatorModel.RecursivePotentials.ZeroTreeVector.Construction] + +abbrev ZeroTreeSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) := + UniformSpace.Completion (ZeroTreeVector T) + +namespace ZeroTreeSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def inclusion : ZeroTreeSpace T →L[ℝ] TreeSpace T := (ZeroTreeVector.inclusion T).completion + +def projection (H : Finset ι) (hH : T.Initial H) : ZeroTreeSpace T →L[ℝ] ZeroTreeSpace T := + (ZeroTreeVector.projection T H hH).completion + +def tail (H : Finset ι) (hH : T.Initial H) : Submodule ℝ (ZeroTreeSpace T) := + (projection T H hH).ker + +end ZeroTreeSpace + +abbrev XZero := ZeroTreeSpace joinedTree + +section + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + +def ZeroTreeSpace.coordinate (s : ι) : ZeroTreeSpace T →L[ℝ] ℝ := + (TreeSpace.coordinate T s).comp (inclusion T) + +def ZeroTreeSpace.P (s : ι) (x : ZeroTreeSpace T) : ℝ := TreeSpace.P T s (inclusion T x) + +def ZeroTreeSpace.Q (s : ι) (x : ZeroTreeSpace T) : ℝ := TreeSpace.Q T s (inclusion T x) + +end + +open Filter Topology + +noncomputable abbrev WeaklyNull := @_root_.OAI.RecursivePotentials.WeaklyNull + +noncomputable abbrev EquivalentNorm := @_root_.OAI.RecursivePotentials.EquivalentNorm + +namespace EquivalentNorm + +variable {E : Type uSpace} [NormedAddCommGroup E] [NormedSpace ℝ E] (A : EquivalentNorm E) + +noncomputable abbrev modulus (A : EquivalentNorm E) := _root_.OAI.RecursivePotentials.EquivalentNorm.modulus A + +noncomputable abbrev AUC (A : EquivalentNorm E) := _root_.OAI.RecursivePotentials.EquivalentNorm.AUC A + +end EquivalentNorm + +open scoped ENNReal + +noncomputable abbrev IsReflexive := @_root_.OAI.RecursivePotentials.IsReflexive + +namespace SquareSum + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (E : ι → Type uFiber) + [∀ i, NormedAddCommGroup (E i)] [fiberNormedSpace : ∀ i, NormedSpace ℝ (E i)] + +noncomputable abbrev Space := @_root_.OAI.RecursivePotentials.SquareSum.Space + +end SquareSum + +open UniformSpace + +noncomputable abbrev completionEquivOfDense := @_root_.OAI.RecursivePotentials.completionEquivOfDense + +noncomputable abbrev componentTree := @_root_.OAI.RecursivePotentials.componentTree + +noncomputable abbrev logarithmicGamma := @_root_.OAI.RecursivePotentials.logarithmicGamma + +open Filter + +open scoped Topology + +def XJoined_separated_familiesStatement : Prop := ∀ {ε : ℝ} (_hε : 0 < ε), + ∃ η : ℝ, 0 < η ∧ η < 1 ∧ + (ε ≤ 2 → η = min (1/2) (logarithmicGamma 2 (ε/16))) ∧ + ∀ (x : XJoined) (z : ℕ → XJoined), + (∀ n, ‖x+z n‖ ≤ 1) → (∀ n, ‖x-z n‖ ≤ 1) → + (∀ i j, i ≠ j → ε ≤ ‖z i-z j‖) → ‖x‖ ≤ 1-η + +noncomputable abbrev ChildExponent := @_root_.OAI.RecursivePotentials.ChildExponent + +namespace VariableExponent + +noncomputable abbrev heightExponent := @_root_.OAI.RecursivePotentials.VariableExponent.heightExponent + +noncomputable abbrev cubicConstant := @_root_.OAI.RecursivePotentials.VariableExponent.cubicConstant + +noncomputable abbrev sixthConstant := @_root_.OAI.RecursivePotentials.VariableExponent.sixthConstant + +end VariableExponent + +namespace VariableTree + +open FiniteRootedTree + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +noncomputable def P (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).pfields e + (fun s => v s.1) s).1) + +noncomputable def Q (v : ι →₀ ℝ) : ι →₀ ℝ := + extend (T.head v) (fun s => ((T.restrict (T.head v) (FiniteRootedTree.Heads.initial T v)).pfields e + (fun s => v s.1) s).2) + +noncomputable def normSum (v : ι →₀ ℝ) : ℝ := P T e v T.root + Q T e v T.root + +end VariableTree + +def AggregationVector {ι : Type uIndex} (_T : FiniteRootedTree ι) (_e : ChildExponent) := ι →₀ ℝ + +namespace AggregationVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +instance : AddCommGroup (AggregationVector T e) := inferInstanceAs (AddCommGroup (ι →₀ ℝ)) + +instance : Module ℝ (AggregationVector T e) := inferInstanceAs (Module ℝ (ι →₀ ℝ)) + +instance : CoeFun (AggregationVector T e) (fun _ => ι → ℝ) := ⟨fun v => (show ι →₀ ℝ from v)⟩ + +noncomputable instance : Norm (AggregationVector T e) := ⟨fun v => VariableTree.normSum T e v⟩ + +class Construction : Prop where + core : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) (e : ChildExponent), + NormedSpace.Core ℝ (AggregationVector T e) + coordinate_bound : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) (v : ι →₀ ℝ) (s : ι), |v s| ≤ VariableTree.normSum T e v + +variable [ComparatorModel.RecursivePotentials.AggregationVector.Construction] + +noncomputable instance : NormedAddCommGroup (AggregationVector T e) := + NormedAddCommGroup.ofCore (AggregationVector.Construction.core T e) + +noncomputable instance : NormedSpace ℝ (AggregationVector T e) := NormedSpace.ofCore (AggregationVector.Construction.core T e) + +def coordinateLinear (s : ι) : AggregationVector T e →ₗ[ℝ] ℝ where + toFun v := v s + map_add' _v _w := rfl + map_smul' _a _v := rfl + +noncomputable def coordinate (s : ι) : AggregationVector T e →L[ℝ] ℝ := + (coordinateLinear T e s).mkContinuous 1 (fun v => by + change ‖v s‖ ≤ 1 * VariableTree.normSum T e v + rw [Real.norm_eq_abs, one_mul] + exact AggregationVector.Construction.coordinate_bound T e v s) + +end AggregationVector + +variable [ComparatorModel.RecursivePotentials.AggregationVector.Construction] + +abbrev AggregationSpace {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) := + UniformSpace.Completion (AggregationVector T e) + +namespace AggregationSpace + +open UniformSpace + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +def coordinate (s : ι) : + AggregationSpace T e →L[ℝ] ℝ := (AggregationVector.coordinate T e s).fromCompletion + +def P (s : ι) : AggregationSpace T e → ℝ := + Completion.extension (fun v : AggregationVector T e => VariableTree.P T e v s) + +def Q (s : ι) : AggregationSpace T e → ℝ := + Completion.extension (fun v : AggregationVector T e => VariableTree.Q T e v s) + +end AggregationSpace + +section + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +def AggregationVector.basisVector (s : ι) : AggregationVector T e := Finsupp.single s 1 + +end + +open Filter Topology TopologicalSpace + +namespace ChildExponent + +instance (e : ChildExponent) : Fact (1 ≤ ENNReal.ofReal e.val) := + ⟨by simpa using ENNReal.ofReal_le_ofReal e.one_le⟩ + +end ChildExponent + +section + +open scoped ENNReal + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +abbrev AggregationVector.CoordinateLp (ι : Type uIndex) (e : ChildExponent) := ↥(lp (fun _ : ι => ℝ) (ENNReal.ofReal e.val)) + +def AggregationVector.toLpLinear : AggregationVector T e →ₗ[ℝ] CoordinateLp ι e := + Finsupp.lsum ℝ (fun s => lp.lsingle (𝕜 := ℝ) (E := fun _ : ι => ℝ) (ENNReal.ofReal e.val) s) + +class AggregationVector.LpConstruction : Prop where + bounds : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent), 1 < e.val → + (∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) → + ∀ h : ℕ, (∀ s, T.depth s ≤ h) → ∀ v : AggregationVector T e, + ‖v‖ ≤ (2*(h+1:ℝ)^(1-1/e.val))*‖toLpLinear T e v‖ ∧ + ‖toLpLinear T e v‖ ≤ (h+1:ℝ)^(1/e.val)*‖v‖ + dense : ∀ {ι : Type uIndex} [DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent), DenseRange (toLpLinear T e) + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def AggregationVector.toLp (hp : 1 < e.val) + (hstep : ∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) + (h : ℕ) (hh : ∀ s, T.depth s ≤ h) : AggregationVector T e →L[ℝ] CoordinateLp ι e := + (toLpLinear T e).mkContinuous ((h+1:ℝ)^(1/e.val)) + (fun v => (LpConstruction.bounds T e hp hstep h hh v).2) + +end + +section + +open AggregationVector + +variable {ι : Type uIndex} [indexDecidable : DecidableEq ι] (T : FiniteRootedTree ι) + (e : ChildExponent) + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def AggregationSpace.lpEquiv (hp : 1 < e.val) + (hstep : ∀ c, c ≠ T.root → T.depth c = T.depth (T.parent c) + 1) + (h : ℕ) (hh : ∀ s, T.depth s ≤ h) : AggregationSpace T e ≃L[ℝ] CoordinateLp ι e := + completionEquivOfDense (AggregationVector.toLp T e hp hstep h hh) + ⟨2*(h+1:ℝ)^(1-1/e.val),by positivity⟩ + (fun v => (AggregationVector.LpConstruction.bounds T e hp hstep h hh v).1) + (AggregationVector.LpConstruction.dense T e) + +end + +namespace Variable + +section + +open UniformSpace VariableExponent Filter Topology TopologicalSpace + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def exponent (h : ℕ+) : ChildExponent := ⟨heightExponent h,(by + dsimp [heightExponent] + have hh : (0 : ℝ) < h.val := by exact_mod_cast h.pos + exact le_add_of_nonneg_right (le_of_lt (one_div_pos.mpr hh)))⟩ + +abbrev Component (h : ℕ+) := AggregationSpace (componentTree h) (exponent h) + +abbrev Xv := SquareSum.Space Component + +abbrev Node := Σ h : ℕ+, ComponentNode h + +def componentEquiv (h : ℕ+) : + Component h ≃L[ℝ] AggregationVector.CoordinateLp (ComponentNode h) (exponent h) := + AggregationSpace.lpEquiv (componentTree h) (exponent h) (by + dsimp [exponent, heightExponent] + have hh : (0 : ℝ) < h.val := by exact_mod_cast h.pos + exact lt_add_of_pos_right _ (one_div_pos.mpr hh)) + (by + intro c hc + change c.1.length = c.1.dropLast.length + 1 + rw [List.length_dropLast] + have hp := List.length_pos_iff_ne_nil.mpr (show c.1 ≠ [] from fun he => hc (Subtype.ext he)) + omega) h.val (fun c => c.2) + +def componentCoordinate (h : ℕ+) (s : ComponentNode h) : Component h →L[ℝ] ℝ := + AggregationSpace.coordinate (componentTree h) (exponent h) s + +def coordinate (s : Node) : Xv →L[ℝ] ℝ := + (componentCoordinate s.1 s.2).comp (lp.evalCLM ℝ Component 2 s.1) + +def basis (s : Node) : Xv := lp.single 2 s.1 + ((AggregationVector.basisVector (componentTree s.1) (exponent s.1) s.2 : AggregationVector (componentTree s.1) (exponent s.1)) : Component s.1) + +def FiniteTotalSupport (x : Xv) : Prop := ∃ S : Finset Node, ∀ s ∉ S, coordinate s x = 0 + +def projection (S : Finset Node) : Xv →L[ℝ] Xv := ∑ s ∈ S, (coordinate s).smulRight (basis s) + +def AdmissibleHeads (x y : Xv) (A : ∀ h, Finset (ComponentNode h)) : Prop := + ∀ h, x h ≠ 0 → (componentTree h).Initial (A h) ∧ + (∀ s ∉ A h, componentCoordinate h s (x h) = 0) ∧ + (∀ s ∈ A h, componentCoordinate h s (y h) = 0) + +def cubic_stabilityStatement : Prop := ∀ (x y : Xv) (_hx : FiniteTotalSupport x) (A : ∀ h, Finset (ComponentNode h)) + (_hA : AdmissibleHeads x y A) {R : ℝ} (_hR : 0 < R) (_hp : ‖x+y‖ ≤ R) (_hm : ‖x-y‖ ≤ R), + ‖x‖^2+cubicConstant/(2*Real.sqrt 2*R)*‖y‖^3 ≤ R^2 + +def sixth_stabilityStatement : Prop := ∀ (x y : Xv) (_hx : FiniteTotalSupport x) (A : ∀ h, Finset (ComponentNode h)) + (_hA : AdmissibleHeads x y A), + sixthConstant*‖y‖^6/(‖x+y‖^2+‖x-y‖^2)^2 ≤ ‖x+y‖^2+‖x-y‖^2-2*‖x‖^2 + +open UniformSpace VariableExponent Filter Topology TopologicalSpace + +def weakTailConstant : ℝ := cubicConstant/(2*Real.sqrt 2) + +def theta (ε : ℝ) : ℝ := Real.sqrt (1-weakTailConstant*ε^3) + +def weak_tailStatement : Prop := ∀ (x : Xv) {ε : ℝ} (_hε : 0 < ε) (_hε1 : ε ≤ 1) + (y : ℕ → Xv) (_hy : WeaklyNull y) (_hyε : ∀ j, ε ≤ ‖y j‖) + (_hp : ∀ j, ‖x+y j‖ ≤ 1) (_hm : ∀ j, ‖x-y j‖ ≤ 1), + ‖x‖ ≤ theta ε ∧ theta ε < 1 + +end + +open UniformSpace VariableExponent Filter Topology + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +def one_sided_modulus_zeroStatement : Prop := ∀ (A : EquivalentNorm Xv), + A.modulus (A.lower/A.upper) = 0 + +def no_equivalent_AUCStatement : Prop := ∀ (A : EquivalentNorm Xv), + ¬A.AUC + +end Variable + +variable [ComparatorModel.RecursivePotentials.AggregationVector.LpConstruction] + +structure RootSumCompletionStatement {ι : Type uIndex} [DecidableEq ι] + (T : FiniteRootedTree ι) : Prop where + complete : CompleteSpace (TreeSpace T) + infinite_dimensional : ¬Module.Finite ℝ (TreeSpace T) + coordinate_continuous : ∀ s, Continuous (TreeSpace.coordinate T s) + coordinate_extends : ∀ s (v : TreeVector T), TreeSpace.coordinate T s (v : TreeSpace T) = v s + fields_continuous : ∀ s, Continuous (TreeSpace.P T s) ∧ Continuous (TreeSpace.Q T s) + fields_extend : ∀ s (v : TreeVector T), + TreeSpace.P T s (v : TreeSpace T) = T.P v s ∧ TreeSpace.Q T s (v : TreeSpace T) = T.Q v s + root_formula : ∀ x : TreeSpace T, ‖x‖ = TreeSpace.P T T.root x + TreeSpace.Q T T.root x + projections : ∀ (H : Finset ι) (hH : T.Initial H), + (∀ x : TreeSpace T, ‖TreeSpace.projection T H hH x‖ ≤ ‖x‖) ∧ + (∀ x : TreeSpace T, TreeSpace.projection T H hH (TreeSpace.projection T H hH x) = TreeSpace.projection T H hH x) ∧ + (∀ (s : ι) (x : TreeSpace T), TreeSpace.coordinate T s (TreeSpace.projection T H hH x) = + if s ∈ H then TreeSpace.coordinate T s x else 0) ∧ + FiniteDimensional ℝ (TreeSpace.projection T H hH).range ∧ + IsClosed (TreeSpace.tail T H hH : Set (TreeSpace T)) ∧ + Module.Finite ℝ (TreeSpace T ⧸ TreeSpace.tail T H hH) ∧ + ∀ x ∈ TreeSpace.tail T H hH, ∀ ε : ℝ, 0 < ε → + ∃ v : TreeVector T, TreeVector.projection T H hH v = 0 ∧ ‖(v : TreeSpace T)-x‖ < ε + +structure ZeroRootCompletionStatement {ι : Type uIndex} [DecidableEq ι] + (T : FiniteRootedTree ι) : Prop where + complete : CompleteSpace (ZeroTreeSpace T) + infinite_dimensional : ¬Module.Finite ℝ (ZeroTreeSpace T) + coordinate_continuous : ∀ s, Continuous (ZeroTreeSpace.coordinate T s) + coordinate_extends : ∀ s (v : ZeroTreeVector T), + ZeroTreeSpace.coordinate T s (v : ZeroTreeSpace T) = ZeroTreeVector.toTree T v s + fields_continuous : ∀ s, Continuous (ZeroTreeSpace.P T s) ∧ Continuous (ZeroTreeSpace.Q T s) + fields_extend : ∀ s (v : ZeroTreeVector T), + ZeroTreeSpace.P T s (v : ZeroTreeSpace T) = T.P (ZeroTreeVector.toTree T v) s ∧ + ZeroTreeSpace.Q T s (v : ZeroTreeSpace T) = T.Q (ZeroTreeVector.toTree T v) s + root_fixed : ∀ x : ZeroTreeSpace T, ZeroTreeSpace.coordinate T T.root x = 0 + root_formula : ∀ x : ZeroTreeSpace T, ‖x‖ = ZeroTreeSpace.P T T.root x ∧ ‖x‖ = ZeroTreeSpace.Q T T.root x + projections : ∀ (H : Finset ι) (hH : T.Initial H), + (∀ x : ZeroTreeSpace T, ‖ZeroTreeSpace.projection T H hH x‖ ≤ ‖x‖) ∧ + (∀ x : ZeroTreeSpace T, ZeroTreeSpace.projection T H hH (ZeroTreeSpace.projection T H hH x) = ZeroTreeSpace.projection T H hH x) ∧ + (∀ (s : ι) (x : ZeroTreeSpace T), ZeroTreeSpace.coordinate T s (ZeroTreeSpace.projection T H hH x) = + if s ∈ H then ZeroTreeSpace.coordinate T s x else 0) ∧ + FiniteDimensional ℝ (ZeroTreeSpace.projection T H hH).range ∧ + IsClosed (ZeroTreeSpace.tail T H hH : Set (ZeroTreeSpace T)) ∧ + Module.Finite ℝ (ZeroTreeSpace T ⧸ ZeroTreeSpace.tail T H hH) ∧ + ∀ x ∈ ZeroTreeSpace.tail T H hH, ∀ ε : ℝ, 0 < ε → + ∃ v : ZeroTreeVector T, ZeroTreeVector.projection T H hH v = 0 ∧ ‖(v : ZeroTreeSpace T)-x‖ < ε + +def rec_completionStatement : Prop := RootSumCompletionStatement sequenceTree ∧ + ZeroRootCompletionStatement joinedTree ∧ RootSumCompletionStatement joinedTree ∧ + IsReflexive XZero ∧ IsReflexive XJoined + +def rec_mainStatement : Prop := (∀ t : ℝ, 0 < t → t < 1 → t^3/128 ≤ averagedModulus XSigma t ∧ t^3/128 ≤ averagedModulus XJoined t) ∧ + (∀ (H : Finset JoinedNode), joinedTree.Initial H → ∀ x : XZero, + (∀ s ∉ H, ZeroTreeSpace.coordinate joinedTree s x = 0) → ∀ z : XZero, + (∀ s ∈ H, ZeroTreeSpace.coordinate joinedTree s z = 0) → z ≠ 0 → + (‖x+z‖+‖x-z‖)/2 ≥ ‖x‖+‖z‖^3/(8*(2*‖x‖+‖z‖)^2)) ∧ + (∀ A : EquivalentNorm XSigma, ¬A.AUC) ∧ + (∀ A : EquivalentNorm XZero, ¬A.AUC) ∧ + (∀ A : EquivalentNorm XJoined, ¬A.AUC) + +def stop_all_radiiStatement : Prop := ∀ {t : ℝ} (_ht : 0 < t), + 0 < averagedModulus XSigma t + +open VariableExponent + +def Variable.nu (h : ℕ+) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) : ℝ := + AggregationSpace.P (componentTree h) (exponent h) (componentTree h).root ((componentEquiv h).symm v) + + AggregationSpace.Q (componentTree h) (exponent h) (componentTree h).root ((componentEquiv h).symm v) + +structure Variable.SourceNormStatement (h : ℕ+) : Prop where + nonneg : ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), 0 ≤ nu h v + definite : ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), nu h v = 0 ↔ v = 0 + triangle : ∀ v w : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), + nu h (v+w) ≤ nu h v + nu h w + homogeneous : ∀ (a : ℝ) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)), + nu h (a • v) = |a| * nu h v + +def Variable.spaceStatement : Prop := (∀ h : ℕ+, CompleteSpace (Component h) ∧ IsReflexive (Component h) ∧ + SeparableSpace (Component h →L[ℝ] ℝ) ∧ SourceNormStatement h ∧ + ∀ v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h), + (h.val+1:ℝ)^(-1/heightExponent h)*‖v‖ ≤ nu h v ∧ + nu h v ≤ 2*(h.val+1:ℝ)^(1-1/heightExponent h)*‖v‖) ∧ + CompleteSpace Xv ∧ IsReflexive Xv ∧ SeparableSpace (Xv →L[ℝ] ℝ) ∧ + Dense {x : Xv | FiniteTotalSupport x} ∧ + ∀ S : Finset Node, Continuous (projection S) ∧ FiniteDimensional ℝ (projection S).range ∧ + (∀ x : Xv, projection S (projection S x) = projection S x) ∧ + ∀ (s : Node) (x : Xv), coordinate s (projection S x) = if s ∈ S then coordinate s x else 0 + +def Variable.aggregateChildren (h : ℕ+) (s : ComponentNode h) (f : ComponentNode h → ℝ) : ℝ := + (∑' c, if c ≠ (componentTree h).root ∧ (componentTree h).parent c = s then + f c ^ heightExponent h else 0) ^ (1/heightExponent h) + +def Variable.lpPotentials (h : ℕ+) (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) + (s : ComponentNode h) : ℝ × ℝ := + (AggregationSpace.P (componentTree h) (exponent h) s ((componentEquiv h).symm v), + AggregationSpace.Q (componentTree h) (exponent h) s ((componentEquiv h).symm v)) + +def Variable.lp_model_exactStatement : Prop := ∀ (h : ℕ+) + (v : AggregationVector.CoordinateLp (ComponentNode h) (exponent h)) + (f : ComponentNode h → ℝ × ℝ) + (_hf : ∀ s, f s = leastPair (v s) + (aggregateChildren h s (fun c => (f c).1)) + (aggregateChildren h s (fun c => (f c).2))), + f = lpPotentials h v ∧ nu h v = (f (componentTree h).root).1+(f (componentTree h).root).2 + +end + +def MainClaim : Prop := + ∃ h0 : FiniteRootedTree.Heads.{0}, letI := h0; + ∃ h1 : TreeVector.Construction.{0}, letI := h1; + ∃ h2 : ZeroTreeVector.Construction.{0}, letI := h2; + ∃ h3 : AggregationVector.Construction.{0}, letI := h3; + ∃ h4 : AggregationVector.LpConstruction.{0}, letI := h4; + rec_mainStatement ∧ + rec_completionStatement ∧ + stop_all_radiiStatement ∧ + XJoined_separated_familiesStatement ∧ + Variable.spaceStatement ∧ + Variable.lp_model_exactStatement ∧ + Variable.one_sided_modulus_zeroStatement ∧ + Variable.no_equivalent_AUCStatement ∧ + Variable.sixth_stabilityStatement ∧ + Variable.cubic_stabilityStatement ∧ + Variable.weak_tailStatement + +theorem main : MainClaim := by + sorry + +end RecursivePotentials + +end ComparatorModel + +end + +end OAI diff --git a/tasks/recursive-potentials/tests/grade.py b/tasks/recursive-potentials/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/recursive-potentials/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/recursive-potentials/tests/task.json b/tasks/recursive-potentials/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2e74b0fa1a97be55fd923b80be7a2c86798037a5 --- /dev/null +++ b/tasks/recursive-potentials/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RecursivePotentials", + "comparator": { + "theorem_names": [ + "OAI.ComparatorModel.RecursivePotentials.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11201 +} \ No newline at end of file diff --git a/tasks/recursive-potentials/tests/test.sh b/tasks/recursive-potentials/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/recursive-potentials/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/reflexive-fixed-points/environment/Dockerfile b/tasks/reflexive-fixed-points/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/reflexive-fixed-points/environment/fetch_mathlib.sh b/tasks/reflexive-fixed-points/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/reflexive-fixed-points/environment/lake-manifest.json b/tasks/reflexive-fixed-points/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/reflexive-fixed-points/environment/lakefile.lean b/tasks/reflexive-fixed-points/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/reflexive-fixed-points/environment/lean_setup.sh b/tasks/reflexive-fixed-points/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/reflexive-fixed-points/environment/pack_submission.py b/tasks/reflexive-fixed-points/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/reflexive-fixed-points/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/reflexive-fixed-points/instruction.md b/tasks/reflexive-fixed-points/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8676bda78a5674640587467f6f2d23416c8119d7 --- /dev/null +++ b/tasks/reflexive-fixed-points/instruction.md @@ -0,0 +1,86 @@ +# openai/math challenge `ReflexiveFixedPoints` (family 328) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 328 of the release, *Fixed points of nonexpansive maps in reflexive Banach spaces* +(Functional analysis). The family as a whole: Resolves Kirk's reflexive-space fixed-point problem: every nonexpansive selfmap of a nonempty closed bounded convex subset of a real reflexive Banach space has a fixed point. The result uses the original norm, without assuming uniform convexity. + +The challenge is `ReflexiveFixedPoints`, also at `/opt/openai-math/challenges/ReflexiveFixedPoints.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace ReflexiveFixedPoints + +universe u + +variable (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Surjectivity of the canonical map into the continuous bidual. -/ +def CanonicallyReflexive : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ X) + +variable {X} + +/-- Every nonexpansive selfmap of a nonempty closed bounded convex set has +an actual fixed point, with nonexpansiveness stated in the original norm. -/ +theorem exists_fixedPoint_of_canonicallyReflexive + {X : Type u} [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + (hX : CanonicallyReflexive X) (C : Set X) + (hne : C.Nonempty) (hclosed : IsClosed C) + (hbounded : Bornology.IsBounded C) (hconvex : Convex ℝ C) + (F : C → C) + (hF : ∀ a b : C, ‖(F a : X) - (F b : X)‖ ≤ ‖(a : X) - (b : X)‖) : + ∃ a : C, F a = a := by + sorry + +end ReflexiveFixedPoints + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ReflexiveFixedPoints.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ReflexiveFixedPoints.exists_fixedPoint_of_canonicallyReflexive` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/reflexive-fixed-points/solution/closure.txt b/tasks/reflexive-fixed-points/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..71d6eabb6a23da44803551ce8d44c6528ba05232 --- /dev/null +++ b/tasks/reflexive-fixed-points/solution/closure.txt @@ -0,0 +1,86 @@ +OAI.Analysis.Nonexpansive.AdaptiveConvexPrefix +OAI.Analysis.Nonexpansive.AdaptiveParentReturn +OAI.Analysis.Nonexpansive.AdaptiveRun +OAI.Analysis.Nonexpansive.AdaptiveSelection +OAI.Analysis.Nonexpansive.Anchor +OAI.Analysis.Nonexpansive.AnchorAdaptiveSelection +OAI.Analysis.Nonexpansive.Basic +OAI.Analysis.Nonexpansive.BlockBefore +OAI.Analysis.Nonexpansive.BlockEstimates +OAI.Analysis.Nonexpansive.BranchContradiction +OAI.Analysis.Nonexpansive.CandidateAncestors +OAI.Analysis.Nonexpansive.CandidateDetectors +OAI.Analysis.Nonexpansive.CandidateLabels +OAI.Analysis.Nonexpansive.CandidateLedger +OAI.Analysis.Nonexpansive.CandidateLedgerJoin +OAI.Analysis.Nonexpansive.CandidateLevel +OAI.Analysis.Nonexpansive.CandidateLevelHistory +OAI.Analysis.Nonexpansive.CandidatePredictions +OAI.Analysis.Nonexpansive.CandidatePreparation +OAI.Analysis.Nonexpansive.CandidateRecords +OAI.Analysis.Nonexpansive.CandidateSelection +OAI.Analysis.Nonexpansive.CandidateStages +OAI.Analysis.Nonexpansive.CandidateThreshold +OAI.Analysis.Nonexpansive.CandidateTolerance +OAI.Analysis.Nonexpansive.CandidateTreeTolerance +OAI.Analysis.Nonexpansive.CommonTerminal +OAI.Analysis.Nonexpansive.CompactDetector +OAI.Analysis.Nonexpansive.CompactMapSemigroup +OAI.Analysis.Nonexpansive.DenseDifferences +OAI.Analysis.Nonexpansive.Diametral +OAI.Analysis.Nonexpansive.FeasibleBranch +OAI.Analysis.Nonexpansive.FinitePrefixEmbedding +OAI.Analysis.Nonexpansive.FiniteWitness +OAI.Analysis.Nonexpansive.FrontierFromGroups +OAI.Analysis.Nonexpansive.FrontierTower +OAI.Analysis.Nonexpansive.FunctionalVanishing +OAI.Analysis.Nonexpansive.GeneratedMaps +OAI.Analysis.Nonexpansive.GlobalCandidateOrdinals +OAI.Analysis.Nonexpansive.LedgerPredictionLimits +OAI.Analysis.Nonexpansive.ListRunPrefix +OAI.Analysis.Nonexpansive.Main +OAI.Analysis.Nonexpansive.MinimalInvariant +OAI.Analysis.Nonexpansive.Model +OAI.Analysis.Nonexpansive.NormalizedContradiction +OAI.Analysis.Nonexpansive.OrderedGroupConcat +OAI.Analysis.Nonexpansive.OrderedTree +OAI.Analysis.Nonexpansive.OrderedTreeIntervals +OAI.Analysis.Nonexpansive.OriginalNorm +OAI.Analysis.Nonexpansive.ParentReturnHistory +OAI.Analysis.Nonexpansive.PointwiseWeakApproximation +OAI.Analysis.Nonexpansive.PredictionCompact +OAI.Analysis.Nonexpansive.PredictionCutoff +OAI.Analysis.Nonexpansive.PredictionOutputs +OAI.Analysis.Nonexpansive.PrefixPredictionOutputs +OAI.Analysis.Nonexpansive.PrefixPredictionReindex +OAI.Analysis.Nonexpansive.Reduction +OAI.Analysis.Nonexpansive.Resolvents +OAI.Analysis.Nonexpansive.ScalarNormalization +OAI.Analysis.Nonexpansive.SeparableInvariant +OAI.Analysis.Nonexpansive.SequentialHistory +OAI.Analysis.Nonexpansive.SubtreeErrors +OAI.Analysis.Nonexpansive.SubtreeEvaluation +OAI.Analysis.Nonexpansive.SwitchingBlocks +OAI.Analysis.Nonexpansive.SwitchingNorm +OAI.Analysis.Nonexpansive.SwitchingScalar +OAI.Analysis.Nonexpansive.SwitchingStates +OAI.Analysis.Nonexpansive.SwitchingTreeData +OAI.Analysis.Nonexpansive.TailMapSemigroup +OAI.Analysis.Nonexpansive.TailMaps +OAI.Analysis.Nonexpansive.TerminalSequence +OAI.Analysis.Nonexpansive.TransmittedSubtreeErrors +OAI.Analysis.Nonexpansive.TreeBudget +OAI.Analysis.Nonexpansive.TreeEvaluation +OAI.Analysis.Nonexpansive.TreeFiniteWitness +OAI.Analysis.Nonexpansive.TreeFrontier +OAI.Analysis.Nonexpansive.TreeProducer +OAI.Analysis.Nonexpansive.TreeTerminal +OAI.Analysis.Nonexpansive.TreeTolerance +OAI.Analysis.Nonexpansive.WeakBranchIntersection +OAI.Analysis.Nonexpansive.WeakCommonTerminal +OAI.Analysis.Nonexpansive.WeakCompactness +OAI.Analysis.Nonexpansive.WeakMetric +OAI.Analysis.Nonexpansive.WeakNestedConvexHull +OAI.Analysis.Nonexpansive.WeakSelfMap +OAI.Analysis.Nonexpansive.WeightedDeficit +OAI.Analysis.Nonexpansive.WeightedTree diff --git a/tasks/reflexive-fixed-points/solution/reference.py b/tasks/reflexive-fixed-points/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/reflexive-fixed-points/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/reflexive-fixed-points/solution/solve.sh b/tasks/reflexive-fixed-points/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3636c279c19f834b77e1c41853834ecb55fba98 --- /dev/null +++ b/tasks/reflexive-fixed-points/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ReflexiveFixedPoints, i.e. module OAI.Analysis.Nonexpansive.Main and the +# 86 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Nonexpansive.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ReflexiveFixedPoints" diff --git a/tasks/reflexive-fixed-points/task.toml b/tasks/reflexive-fixed-points/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f0a0ca295e17f5eee1c217717b454284863f1bc5 --- /dev/null +++ b/tasks/reflexive-fixed-points/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/reflexive-fixed-points" +version = "1.0.0" +description = "Prove ReflexiveFixedPoints (openai/math family 328: Fixed points of nonexpansive maps in reflexive Banach spaces) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ReflexiveFixedPoints.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ReflexiveFixedPoints" +family = "328" +family_title = "Fixed points of nonexpansive maps in reflexive Banach spaces" +subject = "Functional analysis" +theorems = ["OAI.ReflexiveFixedPoints.exists_fixedPoint_of_canonicallyReflexive"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Nonexpansive.Main" +reference_modules = 86 +reference_lean_bytes = 480875 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 664 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12132 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/reflexive-fixed-points/tests/Challenge.lean b/tasks/reflexive-fixed-points/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1c99bec5eeebf53ed44a6a91e627a5b6c98d06a6 --- /dev/null +++ b/tasks/reflexive-fixed-points/tests/Challenge.lean @@ -0,0 +1,35 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace ReflexiveFixedPoints + +universe u + +variable (X : Type u) [NormedAddCommGroup X] [NormedSpace ℝ X] + +/-- Surjectivity of the canonical map into the continuous bidual. -/ +def CanonicallyReflexive : Prop := + Function.Surjective (NormedSpace.inclusionInDoubleDual ℝ X) + +variable {X} + +/-- Every nonexpansive selfmap of a nonempty closed bounded convex set has +an actual fixed point, with nonexpansiveness stated in the original norm. -/ +theorem exists_fixedPoint_of_canonicallyReflexive + {X : Type u} [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + (hX : CanonicallyReflexive X) (C : Set X) + (hne : C.Nonempty) (hclosed : IsClosed C) + (hbounded : Bornology.IsBounded C) (hconvex : Convex ℝ C) + (F : C → C) + (hF : ∀ a b : C, ‖(F a : X) - (F b : X)‖ ≤ ‖(a : X) - (b : X)‖) : + ∃ a : C, F a = a := by + sorry + +end ReflexiveFixedPoints + +end + +end OAI diff --git a/tasks/reflexive-fixed-points/tests/grade.py b/tasks/reflexive-fixed-points/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/reflexive-fixed-points/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/reflexive-fixed-points/tests/task.json b/tasks/reflexive-fixed-points/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4b42dd3e9c0cea871a77cda0353310d1ed24b362 --- /dev/null +++ b/tasks/reflexive-fixed-points/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ReflexiveFixedPoints", + "comparator": { + "theorem_names": [ + "OAI.ReflexiveFixedPoints.exists_fixedPoint_of_canonicallyReflexive" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11232 +} \ No newline at end of file diff --git a/tasks/reflexive-fixed-points/tests/test.sh b/tasks/reflexive-fixed-points/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/reflexive-fixed-points/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/regular-parity/environment/Dockerfile b/tasks/regular-parity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/regular-parity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/regular-parity/environment/fetch_mathlib.sh b/tasks/regular-parity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/regular-parity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/regular-parity/environment/lake-manifest.json b/tasks/regular-parity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/regular-parity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/regular-parity/environment/lakefile.lean b/tasks/regular-parity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/regular-parity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/regular-parity/environment/lean_setup.sh b/tasks/regular-parity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/regular-parity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/regular-parity/environment/pack_submission.py b/tasks/regular-parity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/regular-parity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/regular-parity/instruction.md b/tasks/regular-parity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4a9cf37ad171c702deb78f5dedc5aa2738b074be --- /dev/null +++ b/tasks/regular-parity/instruction.md @@ -0,0 +1,126 @@ +# openai/math challenge `RegularParity` (family 274) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 274 of the release, *Moore's parity conjecture for $\mathrm{QAC}^0$* +(Mathematical physics). The family as a whole: Resolves Moore's parity conjecture in the measured-output model: constant-depth quantum circuits with arbitrary one-qubit gates, unbounded-arity Toffoli gates and polynomially many total qubits cannot compute parity with any fixed positive worst-case advantage. Ancillas start in zero, one output qubit is measured, and all other registers may be discarded. Xu–Li's reductions give the same bounded-error obstruction for strict majority. + +The challenge is `RegularParity`, also at `/opt/openai-math/challenges/RegularParity.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator + +namespace QAC + +abbrev Bit := Fin 2 +abbrev Word (N : ℕ) := Fin N → Bit +abbrev Operator (N : ℕ) := Matrix (Word N) (Word N) ℂ +abbrev QubitOperator := Matrix Bit Bit ℂ + +/-- Tensor product in the computational basis. -/ +def tensorMatrix {N : ℕ} (a : Fin N → QubitOperator) : Operator N := + fun x y => ∏ i, a i (x i) (y i) + +/-- A one-qubit unitary or an unbounded-arity Toffoli gate. -/ +inductive Gate (N : ℕ) where + | local (q : Fin N) (u : Matrix.unitaryGroup Bit ℂ) + | toffoli (controls : Finset (Fin N)) (target : Fin N) (hne : target ∉ controls) + +namespace Gate + +def support {N : ℕ} : Gate N → Finset (Fin N) + | .local q _ => {q} + | .toffoli c t _ => insert t c + +/-- A Toffoli flips its target iff all controls are one. -/ +def toffoliWord {N : ℕ} (c : Finset (Fin N)) (t : Fin N) (x : Word N) : Word N := + if ∀ i ∈ c, x i = 1 then Function.update x t (1 - x t) else x + +def matrix {N : ℕ} : Gate N → Operator N + | .local q u => tensorMatrix fun i => if i = q then (u : QubitOperator) else 1 + | .toffoli c t _ => fun x y => if x = toffoliWord c t y then 1 else 0 + +end Gate + +structure PhysicalLayer (N : ℕ) where + gates : List (Gate N) + disjoint : gates.Pairwise (fun A B => Disjoint A.support B.support) + +def physicalLayerMatrix {N : ℕ} (L : PhysicalLayer N) : Operator N := + (L.gates.map Gate.matrix).prod + +/-- Chronological order: the rightmost matrix acts first. -/ +def physicalCircuitMatrix {N : ℕ} (layers : List (PhysicalLayer N)) : Operator N := + ((layers.map physicalLayerMatrix).reverse).prod + +/-- The computational-basis input with the remaining qubits initialized to zero. -/ +def inputWord {n N : ℕ} (x : Word n) : Word N := + fun i => if h : i.val < n then x ⟨i.val, h⟩ else 0 + +def parity {n : ℕ} (x : Word n) : Bit := ∑ i, x i + +/-- Born probability, summing all final garbage with no cleanliness assumption. -/ +def successProbability {n N : ℕ} (W : Operator N) (out : Fin N) (x : Word n) : ℝ := + ∑ y : Word N, if y out = parity x then Complex.normSq (W y (inputWord x)) else 0 + +/-- Fixed-depth circuits with polynomially many total qubits cannot compute parity +with worst-case success at least two thirds. -/ +theorem parity_lower_bound_polynomial_size (d k C : ℕ) + (_hd : 0 < d) (_hk : 0 < k) (_hC : 0 < C) : + ∃ n₀ : ℕ, ∀ n ≥ n₀, ∀ N : ℕ, n ≤ N → N ≤ C * (n + 1) ^ k → + ∀ layers : List (PhysicalLayer N), layers.length ≤ d → + ∀ out : Fin N, ∃ x : Word n, + successProbability (physicalCircuitMatrix layers) out x < (2 : ℝ) / 3 := by + sorry + +end QAC + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RegularParity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.QAC.parity_lower_bound_polynomial_size` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/regular-parity/solution/closure.txt b/tasks/regular-parity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3b2fe50c1b42014277540708b352d660b5f6941b --- /dev/null +++ b/tasks/regular-parity/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.InformationTheory.QuantumCircuit.Ancilla +OAI.InformationTheory.QuantumCircuit.Asymptotics +OAI.InformationTheory.QuantumCircuit.Backward +OAI.InformationTheory.QuantumCircuit.Basic +OAI.InformationTheory.QuantumCircuit.Circuit +OAI.InformationTheory.QuantumCircuit.Computational +OAI.InformationTheory.QuantumCircuit.Count +OAI.InformationTheory.QuantumCircuit.DepthZero +OAI.InformationTheory.QuantumCircuit.Localization +OAI.InformationTheory.QuantumCircuit.Main +OAI.InformationTheory.QuantumCircuit.Measurement +OAI.InformationTheory.QuantumCircuit.Model +OAI.InformationTheory.QuantumCircuit.Parity +OAI.InformationTheory.QuantumCircuit.ParityTrace +OAI.InformationTheory.QuantumCircuit.Physical +OAI.InformationTheory.QuantumCircuit.Polynomial +OAI.InformationTheory.QuantumCircuit.ProductProjection +OAI.InformationTheory.QuantumCircuit.Reflection +OAI.InformationTheory.QuantumCircuit.ScaleInduction +OAI.InformationTheory.QuantumCircuit.Spectral +OAI.InformationTheory.QuantumCircuit.Toffoli +OAI.InformationTheory.QuantumCircuit.Transition diff --git a/tasks/regular-parity/solution/reference.py b/tasks/regular-parity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/regular-parity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/regular-parity/solution/solve.sh b/tasks/regular-parity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3f0c742676e35fc46b00914970de6172fdf2ccc --- /dev/null +++ b/tasks/regular-parity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RegularParity, i.e. module OAI.InformationTheory.QuantumCircuit.Main and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.QuantumCircuit.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RegularParity" diff --git a/tasks/regular-parity/task.toml b/tasks/regular-parity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2532f0a4d5a208ee0975764843f8f09d623a0dc9 --- /dev/null +++ b/tasks/regular-parity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/regular-parity" +version = "1.0.0" +description = "Prove RegularParity (openai/math family 274: Moore's parity conjecture for $\\mathrm{QAC}^0$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RegularParity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RegularParity" +family = "274" +family_title = "Moore's parity conjecture for $\\mathrm{QAC}^0$" +subject = "Mathematical physics" +theorems = ["OAI.QAC.parity_lower_bound_polynomial_size"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.QuantumCircuit.Main" +reference_modules = 22 +reference_lean_bytes = 154244 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 623 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11838 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/regular-parity/tests/Challenge.lean b/tasks/regular-parity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..af6aa2abfaefc5766ad5676c02087278ecbc03e2 --- /dev/null +++ b/tasks/regular-parity/tests/Challenge.lean @@ -0,0 +1,75 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator + +namespace QAC + +abbrev Bit := Fin 2 +abbrev Word (N : ℕ) := Fin N → Bit +abbrev Operator (N : ℕ) := Matrix (Word N) (Word N) ℂ +abbrev QubitOperator := Matrix Bit Bit ℂ + +/-- Tensor product in the computational basis. -/ +def tensorMatrix {N : ℕ} (a : Fin N → QubitOperator) : Operator N := + fun x y => ∏ i, a i (x i) (y i) + +/-- A one-qubit unitary or an unbounded-arity Toffoli gate. -/ +inductive Gate (N : ℕ) where + | local (q : Fin N) (u : Matrix.unitaryGroup Bit ℂ) + | toffoli (controls : Finset (Fin N)) (target : Fin N) (hne : target ∉ controls) + +namespace Gate + +def support {N : ℕ} : Gate N → Finset (Fin N) + | .local q _ => {q} + | .toffoli c t _ => insert t c + +/-- A Toffoli flips its target iff all controls are one. -/ +def toffoliWord {N : ℕ} (c : Finset (Fin N)) (t : Fin N) (x : Word N) : Word N := + if ∀ i ∈ c, x i = 1 then Function.update x t (1 - x t) else x + +def matrix {N : ℕ} : Gate N → Operator N + | .local q u => tensorMatrix fun i => if i = q then (u : QubitOperator) else 1 + | .toffoli c t _ => fun x y => if x = toffoliWord c t y then 1 else 0 + +end Gate + +structure PhysicalLayer (N : ℕ) where + gates : List (Gate N) + disjoint : gates.Pairwise (fun A B => Disjoint A.support B.support) + +def physicalLayerMatrix {N : ℕ} (L : PhysicalLayer N) : Operator N := + (L.gates.map Gate.matrix).prod + +/-- Chronological order: the rightmost matrix acts first. -/ +def physicalCircuitMatrix {N : ℕ} (layers : List (PhysicalLayer N)) : Operator N := + ((layers.map physicalLayerMatrix).reverse).prod + +/-- The computational-basis input with the remaining qubits initialized to zero. -/ +def inputWord {n N : ℕ} (x : Word n) : Word N := + fun i => if h : i.val < n then x ⟨i.val, h⟩ else 0 + +def parity {n : ℕ} (x : Word n) : Bit := ∑ i, x i + +/-- Born probability, summing all final garbage with no cleanliness assumption. -/ +def successProbability {n N : ℕ} (W : Operator N) (out : Fin N) (x : Word n) : ℝ := + ∑ y : Word N, if y out = parity x then Complex.normSq (W y (inputWord x)) else 0 + +/-- Fixed-depth circuits with polynomially many total qubits cannot compute parity +with worst-case success at least two thirds. -/ +theorem parity_lower_bound_polynomial_size (d k C : ℕ) + (_hd : 0 < d) (_hk : 0 < k) (_hC : 0 < C) : + ∃ n₀ : ℕ, ∀ n ≥ n₀, ∀ N : ℕ, n ≤ N → N ≤ C * (n + 1) ^ k → + ∀ layers : List (PhysicalLayer N), layers.length ≤ d → + ∀ out : Fin N, ∃ x : Word n, + successProbability (physicalCircuitMatrix layers) out x < (2 : ℝ) / 3 := by + sorry + +end QAC + +end + +end OAI diff --git a/tasks/regular-parity/tests/grade.py b/tasks/regular-parity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/regular-parity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/regular-parity/tests/task.json b/tasks/regular-parity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6d57e1536192e48eceed3582d58b7fb5dfa3edae --- /dev/null +++ b/tasks/regular-parity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RegularParity", + "comparator": { + "theorem_names": [ + "OAI.QAC.parity_lower_bound_polynomial_size" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10938 +} \ No newline at end of file diff --git a/tasks/regular-parity/tests/test.sh b/tasks/regular-parity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/regular-parity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/relative-generation/environment/Dockerfile b/tasks/relative-generation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/relative-generation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/relative-generation/environment/fetch_mathlib.sh b/tasks/relative-generation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/relative-generation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/relative-generation/environment/lake-manifest.json b/tasks/relative-generation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/relative-generation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/relative-generation/environment/lakefile.lean b/tasks/relative-generation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/relative-generation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/relative-generation/environment/lean_setup.sh b/tasks/relative-generation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/relative-generation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/relative-generation/environment/pack_submission.py b/tasks/relative-generation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/relative-generation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/relative-generation/instruction.md b/tasks/relative-generation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b95524b33132681e00e091e424f90ce540e39c45 --- /dev/null +++ b/tasks/relative-generation/instruction.md @@ -0,0 +1,161 @@ +# openai/math challenge `RelativeGeneration` (family 296) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 296 of the release, *The generator problem for finite factors* +(Operator algebras). The family as a whole: Proves that every type $\mathrm{II}_1$ factor with separable predual is generated by a single operator, equivalently by two self-adjoint operators, resolving the generator problem. More strongly, for every irreducible inclusion $P\subset M$ of such factors, the unitaries $u$ with $M=W^*(P,u)$ form a dense $G_\delta$ subset in the trace $2$-norm topology. + +The challenge is `RelativeGeneration`, also at `/opt/openai-math/challenges/RelativeGeneration.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe level + +namespace RelativeGeneration + +variable {Hilbert : Type level} [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] + +/-- Weak operator closedness of a concrete unital star subalgebra. -/ +def WOTClosed (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop := + IsClosed {operator : Hilbert →WOT[ℂ] Hilbert | operator.toCLM ∈ algebra} + +/-- The weakly closed unital star algebra generated by a set of operators. -/ +def wstar (operators : Set (Hilbert →L[ℂ] Hilbert)) : + StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert) := + sInf {algebra | WOTClosed algebra ∧ operators ⊆ algebra} + +/-- A nonzero, weakly closed, finite diffuse algebra with scalar center. -/ +structure IsII1Factor (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop where + nonzero : (0 : Hilbert →L[ℂ] Hilbert) ≠ 1 + weaklyClosed : WOTClosed algebra + factor : ∀ element : algebra, (∀ other : algebra, other * element = element * other) → + ∃ scalar : ℂ, element = algebraMap ℂ algebra scalar + finite : ∀ isometry : algebra, star isometry * isometry = 1 → isometry * star isometry = 1 + diffuse : ∀ projection : algebra, IsStarProjection projection → projection ≠ 0 → + ∃ subprojection : algebra, IsStarProjection subprojection ∧ subprojection ≠ 0 ∧ + subprojection ≠ projection ∧ projection * subprojection = subprojection ∧ + subprojection * projection = subprojection + +/-- A same-universe separable Banach predual, with the conjugate-linear dual convention. +This imposes no separability on the Hilbert representation or the operator norm topology. -/ +def HasSeparablePredual (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop := + ∃ (Banach : Type level) (_ : NormedAddCommGroup Banach) (_ : NormedSpace ℂ Banach) + (_ : CompleteSpace Banach) (_ : TopologicalSpace.SeparableSpace Banach), + Nonempty (StrongDual ℂ Banach ≃ₗᵢ⋆[ℂ] algebra) + +/-- The ultraweak topology is generated by absolutely summable vector functionals. -/ +abbrev ultraweakTopology (Hilbert : Type level) [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] : + TopologicalSpace (Hilbert →L[ℂ] Hilbert) := + ⨅ (left : ℕ → Hilbert) (right : ℕ → Hilbert) + (_ : Summable (fun index => ‖left index‖ * ‖right index‖)), + TopologicalSpace.induced + (fun operator : Hilbert →L[ℂ] Hilbert => + ∑' index, inner ℂ (left index) (operator (right index))) inferInstance + +/-- The concrete algebra carries the induced ultraweak topology. -/ +abbrev algebraUltraweakTopology (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : + TopologicalSpace algebra := + TopologicalSpace.induced (fun operator : algebra => (operator : Hilbert →L[ℂ] Hilbert)) + (ultraweakTopology Hilbert) + +/-- A faithful normal normalized trace, not an additional hypothesis on the inclusion. -/ +structure IsNormalizedTrace (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) : Prop where + normalized : trace 1 = 1 + positive : ∀ element : algebra, 0 ≤ (trace (star element * element)).re + star_preserving : ∀ element : algebra, trace (star element) = star (trace element) + tracial : ∀ left right : algebra, trace (left * right) = trace (right * left) + faithful : ∀ element : algebra, trace (star element * element) = 0 → element = 0 + normal : @Continuous algebra ℂ (algebraUltraweakTopology algebra) inferInstance trace + +/-- The normalized trace two-distance between genuine unitaries of the original algebra. -/ +def traceDistance (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) (left right : unitary algebra) : ℝ := + Real.sqrt (trace (star ((left : algebra) - (right : algebra)) * + ((left : algebra) - (right : algebra)))).re + +/-- The topology generated by trace two-distance balls, not the inherited operator norm topology. -/ +abbrev traceTopology (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) : TopologicalSpace (unitary algebra) := + TopologicalSpace.generateFrom {ball | ∃ center : unitary algebra, ∃ radius : ℝ, + 0 < radius ∧ ball = {point | traceDistance algebra trace center point < radius}} + +/-- The entire relative-generator locus in the original unitary group. -/ +def relativeGeneratorLocus (small large : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : + Set (unitary large) := + {element | wstar ((small : Set (Hilbert →L[ℂ] Hilbert)) ∪ + {((element : large) : Hilbert →L[ℂ] Hilbert)}) = large} + +/-- Every irreducible inclusion of concrete type II₁ factors with separable predual +of the larger factor has a dense Gδ full relative-generator locus in the normalized +trace two-topology. The normalized faithful normal trace is asserted to exist; +no representation, transport, cyclicity, or perturbation premise is imposed. -/ +def MainTarget : Prop := + ∀ (Hilbert : Type level) [NormedAddCommGroup Hilbert] [InnerProductSpace ℂ Hilbert] + [CompleteSpace Hilbert] (small large : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)), + IsII1Factor small → IsII1Factor large → ∀ inclusion : small ≤ large, + (∀ element : large, + (∀ member : small, StarSubalgebra.inclusion inclusion member * element = + element * StarSubalgebra.inclusion inclusion member) → + ∃ scalar : ℂ, element = algebraMap ℂ large scalar) → + HasSeparablePredual large → + ∃ trace : large →L[ℂ] ℂ, IsNormalizedTrace large trace ∧ + @IsGδ (unitary large) (traceTopology large trace) (relativeGeneratorLocus small large) ∧ + @Dense (unitary large) (traceTopology large trace) (relativeGeneratorLocus small large) + +theorem main_theorem : MainTarget.{level} := by + sorry + +end RelativeGeneration + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RelativeGeneration.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RelativeGeneration.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/relative-generation/solution/closure.txt b/tasks/relative-generation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6e90ed4026a72c99491d76c390597a90ea86b2e4 --- /dev/null +++ b/tasks/relative-generation/solution/closure.txt @@ -0,0 +1,102 @@ +OAI.Analysis.FactorGeneration.AmplificationEncoding +OAI.Analysis.FactorGeneration.Bicommutant +OAI.Analysis.FactorGeneration.Coefficients +OAI.Analysis.FactorGeneration.Convolution +OAI.Analysis.FactorGeneration.CoordinatePerturbation +OAI.Analysis.FactorGeneration.CoordinateUnitaries +OAI.Analysis.FactorGeneration.CornerIndependence +OAI.Analysis.FactorGeneration.CornerTrace +OAI.Analysis.FactorGeneration.Correlation +OAI.Analysis.FactorGeneration.CyclicPredual +OAI.Analysis.FactorGeneration.Dimension +OAI.Analysis.FactorGeneration.DyadicComparison +OAI.Analysis.FactorGeneration.EnergyDescent +OAI.Analysis.FactorGeneration.Expectations +OAI.Analysis.FactorGeneration.Exponential +OAI.Analysis.FactorGeneration.FiniteComparison +OAI.Analysis.FactorGeneration.FreeGroupMoments +OAI.Analysis.FactorGeneration.FreeWords +OAI.Analysis.FactorGeneration.FunctionalLimits +OAI.Analysis.FactorGeneration.Generation +OAI.Analysis.FactorGeneration.GroupTrace +OAI.Analysis.FactorGeneration.HaarIndependence +OAI.Analysis.FactorGeneration.HaarPatches +OAI.Analysis.FactorGeneration.HaarSequences +OAI.Analysis.FactorGeneration.HilbertLimits +OAI.Analysis.FactorGeneration.HilbertProjections +OAI.Analysis.FactorGeneration.LaurentAlgebra +OAI.Analysis.FactorGeneration.LaurentMoments +OAI.Analysis.FactorGeneration.LocalPatches +OAI.Analysis.FactorGeneration.LocalQuantization +OAI.Analysis.FactorGeneration.LocalizedStates +OAI.Analysis.FactorGeneration.LongWords +OAI.Analysis.FactorGeneration.Main +OAI.Analysis.FactorGeneration.MatrixAlgebras +OAI.Analysis.FactorGeneration.MatrixEncoding +OAI.Analysis.FactorGeneration.MatrixExpectation +OAI.Analysis.FactorGeneration.MatrixGenerators +OAI.Analysis.FactorGeneration.MatrixRefinement +OAI.Analysis.FactorGeneration.MatrixSequence +OAI.Analysis.FactorGeneration.MatrixUnits +OAI.Analysis.FactorGeneration.MonotoneTrace +OAI.Analysis.FactorGeneration.NormalDimension +OAI.Analysis.FactorGeneration.NormalTrace +OAI.Analysis.FactorGeneration.OperatorLimits +OAI.Analysis.FactorGeneration.OrbitMinima +OAI.Analysis.FactorGeneration.PartialIsometries +OAI.Analysis.FactorGeneration.PartialUnitaries +OAI.Analysis.FactorGeneration.PatchingBounds +OAI.Analysis.FactorGeneration.PatchingWords +OAI.Analysis.FactorGeneration.PerturbationBounds +OAI.Analysis.FactorGeneration.Pinching +OAI.Analysis.FactorGeneration.PredualContinuity +OAI.Analysis.FactorGeneration.PredualOrder +OAI.Analysis.FactorGeneration.PredualRange +OAI.Analysis.FactorGeneration.ProductWords +OAI.Analysis.FactorGeneration.ProjectionComparison +OAI.Analysis.FactorGeneration.ProjectionEncoding +OAI.Analysis.FactorGeneration.ProjectionLimits +OAI.Analysis.FactorGeneration.QuotientCorners +OAI.Analysis.FactorGeneration.QuotientHilbert +OAI.Analysis.FactorGeneration.QuotientRepresentation +OAI.Analysis.FactorGeneration.RelativeGeneration +OAI.Analysis.FactorGeneration.RepresentedCorners +OAI.Analysis.FactorGeneration.RepresentedFreeness +OAI.Analysis.FactorGeneration.ResidualCompletion +OAI.Analysis.FactorGeneration.ResidualEstimates +OAI.Analysis.FactorGeneration.ResidualMoments +OAI.Analysis.FactorGeneration.SpectralApproximation +OAI.Analysis.FactorGeneration.SpectralDimension +OAI.Analysis.FactorGeneration.SpectralPinching +OAI.Analysis.FactorGeneration.SpectralStates +OAI.Analysis.FactorGeneration.SpectralTruncation +OAI.Analysis.FactorGeneration.Subfactors +OAI.Analysis.FactorGeneration.Supports +OAI.Analysis.FactorGeneration.Target +OAI.Analysis.FactorGeneration.TensorRefinement +OAI.Analysis.FactorGeneration.TraceHilbert +OAI.Analysis.FactorGeneration.TraceTopology +OAI.Analysis.FactorGeneration.TraceTransport +OAI.Analysis.FactorGeneration.TracialInclusion +OAI.Analysis.FactorGeneration.Ultrapower +OAI.Analysis.FactorGeneration.UniformPartitions +OAI.Analysis.FactorGeneration.UnitaryMetric +OAI.Analysis.FactorGeneration.WordCorrelation +OAI.Analysis.FactorGeneration.Words +OAI.Analysis.FreeGroupFactor.GlobalODE +OAI.Analysis.FreeGroupFactor.Model +OAI.Analysis.FreeGroupFactor.NCPolynomial +OAI.Analysis.FreeGroupFactor.Operators +OAI.Analysis.FreeGroupFactor.PolynomialFlow +OAI.Analysis.FreeGroupFactor.Taylor +OAI.Analysis.FreeGroupFactor.TraceCocycle +OAI.Analysis.FreeGroupFactor.UnitaryEvaluation +OAI.Analysis.RelativeGeneration.ConditionalMembership +OAI.Analysis.RelativeGeneration.DistanceSections +OAI.Analysis.RelativeGeneration.InclusionTransport +OAI.Analysis.RelativeGeneration.LocusTopology +OAI.Analysis.RelativeGeneration.Main +OAI.Analysis.RelativeGeneration.OriginalTransport +OAI.Analysis.RelativeGeneration.OriginalUnitary +OAI.Analysis.RelativeGeneration.RepresentedLocus +OAI.Analysis.RelativeGeneration.Topology diff --git a/tasks/relative-generation/solution/reference.py b/tasks/relative-generation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/relative-generation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/relative-generation/solution/solve.sh b/tasks/relative-generation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..65f6727664cd3d47c6c6f143319b8cba7a06b937 --- /dev/null +++ b/tasks/relative-generation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RelativeGeneration, i.e. module OAI.Analysis.RelativeGeneration.Main and the +# 102 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.RelativeGeneration.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RelativeGeneration" diff --git a/tasks/relative-generation/task.toml b/tasks/relative-generation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..440b5e3ca14ad767e3686c92507bb7442a068f58 --- /dev/null +++ b/tasks/relative-generation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/relative-generation" +version = "1.0.0" +description = "Prove RelativeGeneration (openai/math family 296: The generator problem for finite factors) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RelativeGeneration.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RelativeGeneration" +family = "296" +family_title = "The generator problem for finite factors" +subject = "Operator algebras" +theorems = ["OAI.RelativeGeneration.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.RelativeGeneration.Main" +reference_modules = 102 +reference_lean_bytes = 1722505 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 3956 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13250 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/relative-generation/tests/Challenge.lean b/tasks/relative-generation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..dfb87a4dfbb7e584b0f44d7657aff8084650f4a7 --- /dev/null +++ b/tasks/relative-generation/tests/Challenge.lean @@ -0,0 +1,110 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe level + +namespace RelativeGeneration + +variable {Hilbert : Type level} [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] + +/-- Weak operator closedness of a concrete unital star subalgebra. -/ +def WOTClosed (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop := + IsClosed {operator : Hilbert →WOT[ℂ] Hilbert | operator.toCLM ∈ algebra} + +/-- The weakly closed unital star algebra generated by a set of operators. -/ +def wstar (operators : Set (Hilbert →L[ℂ] Hilbert)) : + StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert) := + sInf {algebra | WOTClosed algebra ∧ operators ⊆ algebra} + +/-- A nonzero, weakly closed, finite diffuse algebra with scalar center. -/ +structure IsII1Factor (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop where + nonzero : (0 : Hilbert →L[ℂ] Hilbert) ≠ 1 + weaklyClosed : WOTClosed algebra + factor : ∀ element : algebra, (∀ other : algebra, other * element = element * other) → + ∃ scalar : ℂ, element = algebraMap ℂ algebra scalar + finite : ∀ isometry : algebra, star isometry * isometry = 1 → isometry * star isometry = 1 + diffuse : ∀ projection : algebra, IsStarProjection projection → projection ≠ 0 → + ∃ subprojection : algebra, IsStarProjection subprojection ∧ subprojection ≠ 0 ∧ + subprojection ≠ projection ∧ projection * subprojection = subprojection ∧ + subprojection * projection = subprojection + +/-- A same-universe separable Banach predual, with the conjugate-linear dual convention. +This imposes no separability on the Hilbert representation or the operator norm topology. -/ +def HasSeparablePredual (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : Prop := + ∃ (Banach : Type level) (_ : NormedAddCommGroup Banach) (_ : NormedSpace ℂ Banach) + (_ : CompleteSpace Banach) (_ : TopologicalSpace.SeparableSpace Banach), + Nonempty (StrongDual ℂ Banach ≃ₗᵢ⋆[ℂ] algebra) + +/-- The ultraweak topology is generated by absolutely summable vector functionals. -/ +abbrev ultraweakTopology (Hilbert : Type level) [NormedAddCommGroup Hilbert] + [InnerProductSpace ℂ Hilbert] [CompleteSpace Hilbert] : + TopologicalSpace (Hilbert →L[ℂ] Hilbert) := + ⨅ (left : ℕ → Hilbert) (right : ℕ → Hilbert) + (_ : Summable (fun index => ‖left index‖ * ‖right index‖)), + TopologicalSpace.induced + (fun operator : Hilbert →L[ℂ] Hilbert => + ∑' index, inner ℂ (left index) (operator (right index))) inferInstance + +/-- The concrete algebra carries the induced ultraweak topology. -/ +abbrev algebraUltraweakTopology (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : + TopologicalSpace algebra := + TopologicalSpace.induced (fun operator : algebra => (operator : Hilbert →L[ℂ] Hilbert)) + (ultraweakTopology Hilbert) + +/-- A faithful normal normalized trace, not an additional hypothesis on the inclusion. -/ +structure IsNormalizedTrace (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) : Prop where + normalized : trace 1 = 1 + positive : ∀ element : algebra, 0 ≤ (trace (star element * element)).re + star_preserving : ∀ element : algebra, trace (star element) = star (trace element) + tracial : ∀ left right : algebra, trace (left * right) = trace (right * left) + faithful : ∀ element : algebra, trace (star element * element) = 0 → element = 0 + normal : @Continuous algebra ℂ (algebraUltraweakTopology algebra) inferInstance trace + +/-- The normalized trace two-distance between genuine unitaries of the original algebra. -/ +def traceDistance (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) (left right : unitary algebra) : ℝ := + Real.sqrt (trace (star ((left : algebra) - (right : algebra)) * + ((left : algebra) - (right : algebra)))).re + +/-- The topology generated by trace two-distance balls, not the inherited operator norm topology. -/ +abbrev traceTopology (algebra : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) + (trace : algebra →L[ℂ] ℂ) : TopologicalSpace (unitary algebra) := + TopologicalSpace.generateFrom {ball | ∃ center : unitary algebra, ∃ radius : ℝ, + 0 < radius ∧ ball = {point | traceDistance algebra trace center point < radius}} + +/-- The entire relative-generator locus in the original unitary group. -/ +def relativeGeneratorLocus (small large : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)) : + Set (unitary large) := + {element | wstar ((small : Set (Hilbert →L[ℂ] Hilbert)) ∪ + {((element : large) : Hilbert →L[ℂ] Hilbert)}) = large} + +/-- Every irreducible inclusion of concrete type II₁ factors with separable predual +of the larger factor has a dense Gδ full relative-generator locus in the normalized +trace two-topology. The normalized faithful normal trace is asserted to exist; +no representation, transport, cyclicity, or perturbation premise is imposed. -/ +def MainTarget : Prop := + ∀ (Hilbert : Type level) [NormedAddCommGroup Hilbert] [InnerProductSpace ℂ Hilbert] + [CompleteSpace Hilbert] (small large : StarSubalgebra ℂ (Hilbert →L[ℂ] Hilbert)), + IsII1Factor small → IsII1Factor large → ∀ inclusion : small ≤ large, + (∀ element : large, + (∀ member : small, StarSubalgebra.inclusion inclusion member * element = + element * StarSubalgebra.inclusion inclusion member) → + ∃ scalar : ℂ, element = algebraMap ℂ large scalar) → + HasSeparablePredual large → + ∃ trace : large →L[ℂ] ℂ, IsNormalizedTrace large trace ∧ + @IsGδ (unitary large) (traceTopology large trace) (relativeGeneratorLocus small large) ∧ + @Dense (unitary large) (traceTopology large trace) (relativeGeneratorLocus small large) + +theorem main_theorem : MainTarget.{level} := by + sorry + +end RelativeGeneration + +end + +end OAI diff --git a/tasks/relative-generation/tests/grade.py b/tasks/relative-generation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/relative-generation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/relative-generation/tests/task.json b/tasks/relative-generation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dcf7f9729de6f442dd8cf283535c1814db4c4ca4 --- /dev/null +++ b/tasks/relative-generation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RelativeGeneration", + "comparator": { + "theorem_names": [ + "OAI.RelativeGeneration.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12350 +} \ No newline at end of file diff --git a/tasks/relative-generation/tests/test.sh b/tasks/relative-generation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/relative-generation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/rokhlin/environment/Dockerfile b/tasks/rokhlin/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/rokhlin/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/rokhlin/environment/fetch_mathlib.sh b/tasks/rokhlin/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/rokhlin/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/rokhlin/environment/lake-manifest.json b/tasks/rokhlin/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/rokhlin/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/rokhlin/environment/lakefile.lean b/tasks/rokhlin/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/rokhlin/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/rokhlin/environment/lean_setup.sh b/tasks/rokhlin/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/rokhlin/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/rokhlin/environment/pack_submission.py b/tasks/rokhlin/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/rokhlin/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/rokhlin/instruction.md b/tasks/rokhlin/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fbe3b889c67bbea9d7b403e0a5fb81e6e8122c59 --- /dev/null +++ b/tasks/rokhlin/instruction.md @@ -0,0 +1,88 @@ +# openai/math challenge `Rokhlin` (family 145) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 145 of the release, *Rokhlin's multiple-mixing problem* +(Dynamical systems and ergodic theory). The family as a whole: Proves that every invertible mixing probability-preserving transformation is mixing of all finite orders, resolving Rokhlin's multiple-mixing problem for a single transformation. Correlations among any finite collection of measurable sets converge to the product of their measures whenever all pairwise time separations diverge. + +The challenge is `Rokhlin`, also at `/opt/openai-math/challenges/Rokhlin.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory Filter +open scoped BigOperators Topology + +namespace Rokhlin + +variable {Ω : Type*} [MeasurableSpace Ω] + +def timeMap (T : Ω ≃ᵐ Ω) (n : ℤ) : Ω → Ω := + ⇑((T.toEquiv : Equiv.Perm Ω) ^ n) + +def IsMixing (μ : Measure Ω) (T : Ω ≃ᵐ Ω) : Prop := + ∀ A B : Set Ω, MeasurableSet A → MeasurableSet B → + Tendsto (fun n : ℤ => μ (A ∩ timeMap T n ⁻¹' B)) + (comap Int.natAbs atTop) (𝓝 (μ A * μ B)) + +def layoutTime {k : ℕ} (gaps : Fin (k - 1) → ℕ+) (i : Fin k) : ℕ := + ∑ j : Fin (k - 1), if j.val < i.val then (gaps j : ℕ) else 0 + +def MixingOfOrder (μ : Measure Ω) (T : Ω ≃ᵐ Ω) (k : ℕ) : Prop := + ∀ A : Fin k → Set Ω, (∀ i, MeasurableSet (A i)) → + Tendsto + (fun gaps : Fin (k - 1) → ℕ+ => + μ (⋂ i : Fin k, timeMap T (layoutTime gaps i : ℤ) ⁻¹' A i)) + atTop (𝓝 (∏ i : Fin k, μ (A i))) + +theorem mixing_all_finite_orders (μ : Measure Ω) [IsProbabilityMeasure μ] + (T : Ω ≃ᵐ Ω) (h_pres : MeasurePreserving T μ μ) (h_mix : IsMixing μ T) : + ∀ k : ℕ, 3 ≤ k → MixingOfOrder μ T k := by + sorry + +end Rokhlin + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Rokhlin.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Rokhlin.mixing_all_finite_orders` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/rokhlin/solution/closure.txt b/tasks/rokhlin/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..435ea037ba695521c19ddd0efcec475b283ebb1a --- /dev/null +++ b/tasks/rokhlin/solution/closure.txt @@ -0,0 +1,13 @@ +OAI.Dynamics.MultipleMixing.Arrays +OAI.Dynamics.MultipleMixing.Entropy +OAI.Dynamics.MultipleMixing.ExactLines +OAI.Dynamics.MultipleMixing.FibreMeasures +OAI.Dynamics.MultipleMixing.Foundations +OAI.Dynamics.MultipleMixing.HilbertCodes +OAI.Dynamics.MultipleMixing.Joinings +OAI.Dynamics.MultipleMixing.Main +OAI.Dynamics.MultipleMixing.OrbitCancellation +OAI.Dynamics.MultipleMixing.Saturation +OAI.Dynamics.MultipleMixing.Tail +OAI.Dynamics.MultipleMixing.Tensors +OAI.Dynamics.MultipleMixing.WeakLimits diff --git a/tasks/rokhlin/solution/reference.py b/tasks/rokhlin/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/rokhlin/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/rokhlin/solution/solve.sh b/tasks/rokhlin/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..e314c29b3925f81d9fe6d3cc81e27a6d2c501e12 --- /dev/null +++ b/tasks/rokhlin/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Rokhlin, i.e. module OAI.Dynamics.MultipleMixing.Main and the +# 13 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.MultipleMixing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Rokhlin" diff --git a/tasks/rokhlin/task.toml b/tasks/rokhlin/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..387a14aef15187307d897e95d6b05784c5263a10 --- /dev/null +++ b/tasks/rokhlin/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/rokhlin" +version = "1.0.0" +description = "Prove Rokhlin (openai/math family 145: Rokhlin's multiple-mixing problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Rokhlin.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Rokhlin" +family = "145" +family_title = "Rokhlin's multiple-mixing problem" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.Rokhlin.mixing_all_finite_orders"] +definition_holes = [] +fixed_definitions = ["OAI.Rokhlin.timeMap", "OAI.Rokhlin.IsMixing", "OAI.Rokhlin.layoutTime", "OAI.Rokhlin.MixingOfOrder"] +reference_module = "OAI.Dynamics.MultipleMixing.Main" +reference_modules = 13 +reference_lean_bytes = 1407449 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1397 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12966 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/rokhlin/tests/Challenge.lean b/tasks/rokhlin/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..39cd6de52ff29c3dc4b799925f43d9d6005e565a --- /dev/null +++ b/tasks/rokhlin/tests/Challenge.lean @@ -0,0 +1,37 @@ +import Mathlib + +namespace OAI + +open MeasureTheory Filter +open scoped BigOperators Topology + +namespace Rokhlin + +variable {Ω : Type*} [MeasurableSpace Ω] + +def timeMap (T : Ω ≃ᵐ Ω) (n : ℤ) : Ω → Ω := + ⇑((T.toEquiv : Equiv.Perm Ω) ^ n) + +def IsMixing (μ : Measure Ω) (T : Ω ≃ᵐ Ω) : Prop := + ∀ A B : Set Ω, MeasurableSet A → MeasurableSet B → + Tendsto (fun n : ℤ => μ (A ∩ timeMap T n ⁻¹' B)) + (comap Int.natAbs atTop) (𝓝 (μ A * μ B)) + +def layoutTime {k : ℕ} (gaps : Fin (k - 1) → ℕ+) (i : Fin k) : ℕ := + ∑ j : Fin (k - 1), if j.val < i.val then (gaps j : ℕ) else 0 + +def MixingOfOrder (μ : Measure Ω) (T : Ω ≃ᵐ Ω) (k : ℕ) : Prop := + ∀ A : Fin k → Set Ω, (∀ i, MeasurableSet (A i)) → + Tendsto + (fun gaps : Fin (k - 1) → ℕ+ => + μ (⋂ i : Fin k, timeMap T (layoutTime gaps i : ℤ) ⁻¹' A i)) + atTop (𝓝 (∏ i : Fin k, μ (A i))) + +theorem mixing_all_finite_orders (μ : Measure Ω) [IsProbabilityMeasure μ] + (T : Ω ≃ᵐ Ω) (h_pres : MeasurePreserving T μ μ) (h_mix : IsMixing μ T) : + ∀ k : ℕ, 3 ≤ k → MixingOfOrder μ T k := by + sorry + +end Rokhlin + +end OAI diff --git a/tasks/rokhlin/tests/grade.py b/tasks/rokhlin/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/rokhlin/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/rokhlin/tests/task.json b/tasks/rokhlin/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1f348bf3c425dedabbc46f37cb1f62676f377a33 --- /dev/null +++ b/tasks/rokhlin/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Rokhlin", + "comparator": { + "theorem_names": [ + "OAI.Rokhlin.mixing_all_finite_orders" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12066 +} \ No newline at end of file diff --git a/tasks/rokhlin/tests/test.sh b/tasks/rokhlin/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/rokhlin/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ruled-covering/environment/Dockerfile b/tasks/ruled-covering/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ruled-covering/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ruled-covering/environment/fetch_mathlib.sh b/tasks/ruled-covering/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ruled-covering/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ruled-covering/environment/lake-manifest.json b/tasks/ruled-covering/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ruled-covering/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ruled-covering/environment/lakefile.lean b/tasks/ruled-covering/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ruled-covering/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ruled-covering/environment/lean_setup.sh b/tasks/ruled-covering/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ruled-covering/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ruled-covering/environment/pack_submission.py b/tasks/ruled-covering/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ruled-covering/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ruled-covering/instruction.md b/tasks/ruled-covering/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1d5f43a5650ac1578e4e2c774428b12ad18fdde1 --- /dev/null +++ b/tasks/ruled-covering/instruction.md @@ -0,0 +1,273 @@ +# openai/math challenge `RuledCovering` (family 100) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 100 of the release, *A counterexample to Bang's cylinder-covering bound* +(Convex and metric geometry). The family as a whole: Covers the entire closed regular tetrahedron by finitely many cylinders with compact triangular perpendicular bases whose total area is less than half its smallest orthogonal projection area. This disproves Bang's half-area cylinder-covering bound and the stronger directionwise normalized conjecture in dimension three. + +The challenge is `RuledCovering`, also at `/opt/openai-math/challenges/RuledCovering.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory Filter +open scoped Topology ContDiff +namespace RuledApproximation + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def vec2 (x y : ℝ) : Plane := WithLp.toLp 2 ![x, y] +def vec3 (x y z : ℝ) : Space := WithLp.toLp 2 ![x, y, z] +def axial (s : ℝ) (p : Plane) : Space := vec3 s (p 0) (p 1) + +def IsParallelogram {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s ∈ Icc (0 : ℝ) 1, ∃ t ∈ Icc (0 : ℝ) 1, + x = c + s • u + t • v} + +def IsTriangle {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s : ℝ, ∃ t : ℝ, 0 ≤ s ∧ 0 ≤ t ∧ s + t ≤ 1 ∧ + x = c + s • u + t • v} + +structure Cylinder where + axis : Space + unit_axis : ‖axis‖ = 1 + base : Set ((Submodule.span ℝ ({axis} : Set Space))ᗮ) + +namespace Cylinder + +def carrier (C : Cylinder) : Set Space := + {x | ∃ b ∈ C.base, ∃ t : ℝ, x = (b : Space) + t • C.axis} + +def area (C : Cylinder) : ℝ := volume.real C.base + +def parallelogram (C : Cylinder) : Prop := IsParallelogram C.base + +def triangle (C : Cylinder) : Prop := IsTriangle C.base + +def openBounded (C : Cylinder) : Prop := + IsOpen C.base ∧ Bornology.IsBounded C.base ∧ MeasurableSet C.base +end Cylinder + +def familySet {n : ℕ} (C : Fin n → Cylinder) : Set Space := ⋃ i, (C i).carrier +def familyArea {n : ℕ} (C : Fin n → Cylinder) : ℝ := ∑ i, (C i).area + +def HasFiniteCover (shape : Cylinder → Prop) (S : Set Space) (A : ℝ) : Prop := + ∃ n : ℕ, ∃ C : Fin n → Cylinder, + (∀ i, shape (C i)) ∧ S ⊆ familySet C ∧ familyArea C ≤ A + +/-- No boundary hypothesis is included in this neighborhood regularity predicate. -/ +def SmoothNear (n : WithTop ℕ∞) (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ D ⊆ U ∧ ContDiffOn ℝ n v U + +/-- In dimension two these two distinct nonzero eigenvalues are all the eigenvalues. -/ +def HyperbolicAt (L : ℝ) (v : Plane → Plane) (p : Plane) : Prop := + ∃ lam : ℝ, 0 < L * lam ∧ L * lam < 1 ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap lam ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap (-lam) + +def weight (v : Plane) : ℝ := 1 / Real.sqrt (1 + ‖v‖ ^ 2) +def physicalWeight (h : ℝ) (w : Plane) : ℝ := + 1 / Real.sqrt (1 + w 0 ^ 2 + h ^ 2 * w 1 ^ 2) + +def ruled (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ r : ℝ, |r| ≤ L ∧ + z = vec3 (p 0 + r * v p 0) (p 1 + r * v p 1) r} + +def physicalRuled (h : ℝ) (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ s : ℝ, |s| ≤ L ∧ + z = vec3 s (p 0 + s * v p 0) (h * (p 1 + s * v p 1))} + +def HyperbolicStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (L : ℝ), + IsCompact D → SmoothNear 1 D v → 0 < L → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram (ruled D v L) + ((∫ p in D, weight (v p)) + e) + +def PhysicalHyperbolicStatement : Prop := + ∀ (h L : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < h → 0 < L → IsCompact D → SmoothNear 1 D v → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ (e : ℝ), 0 < e → ∀ F : Space ≃ᵢ Space, + HasFiniteCover Cylinder.parallelogram (F '' physicalRuled h D v L) + (h * (∫ p in D, physicalWeight h (v p)) + e) + +def OpenRectangleC2 (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ a b : Plane, (∀ i, a i < b i) ∧ + D ⊆ {p | ∀ i, p i ∈ Ioo (a i) (b i)} ∧ + ContDiffOn ℝ 2 v {p | ∀ i, p i ∈ Ioo (a i) (b i)} + +def LogarithmicStatement : Prop := + ∀ (X k : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < X → 0 < k → IsCompact D → volume (frontier D) = 0 → + OpenRectangleC2 D v → + (∀ p ∈ D, LinearMap.trace ℝ Plane (fderiv ℝ v p).toLinearMap = 0 ∧ + LinearMap.det (fderiv ℝ v p).toLinearMap < 0 ∧ + k * X * Real.sqrt (-LinearMap.det (fderiv ℝ v p).toLinearMap) < 1) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.openBounded + (physicalRuled 1 D (fun p => k • v p) X) + ((∫ p in D, 1 / Real.sqrt (1 + k ^ 2 * ‖v p‖ ^ 2)) + e) + +def ProductCellStatement : Prop := + ∀ (h M : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < h → 0 < M → IsCompact D → volume (frontier D) = 0 → + SmoothNear 1 D v → (∀ p ∈ D, HyperbolicAt M v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.openBounded (physicalRuled h D v M) + (h * (∫ p in D, physicalWeight h (v p)) + e) + +def OrthogonalGridStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (kappa : ℝ), + IsCompact D → volume (frontier D) = 0 → SmoothNear 1 D v → kappa < 1 → + (∀ p ∈ D, LinearMap.trace ℝ Plane (fderiv ℝ v p).toLinearMap = 0 ∧ + LinearMap.det (fderiv ℝ v p).toLinearMap < 0 ∧ ‖fderiv ℝ v p‖ ≤ kappa) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram + (physicalRuled (Real.sqrt 2) D v 1) + (Real.sqrt 2 * (∫ p in D, + 1 / Real.sqrt (1 + v p 0 ^ 2 + 2 * v p 1 ^ 2)) + e) + +def unitSquare : Set Plane := {x | ∀ i, |x i| ≤ (1 : ℝ) / 2} + +def IsSquareTile (T : Set Plane) : Prop := + ∃ c : Plane, ∃ R : Plane ≃ₗᵢ[ℝ] Plane, ∃ a : ℝ, 0 < a ∧ + T = (fun x => c + a • R x) '' unitSquare + +def auxiliaryCylinder (T : Set Plane) (g : Plane) : Set Space := + {z | ∃ s : ℝ, ∃ b ∈ T, z = axial s (b + s • g)} + +def firstPhysicalMap (h : ℝ) (z : Space) : Space := vec3 (z 0) (z 1) (h * z 2) +def secondPhysicalMap (h a : ℝ) (z : Space) : Space := + vec3 (z 1) (z 0) (h * (a - z 2)) + +def NilpotentStatement : Prop := + ∀ (D : Set Plane) (G : Plane → Plane), IsCompact D → SmoothNear ∞ D G → + (∀ b ∈ D, (fderiv ℝ G b).comp (fderiv ℝ G b) = 0) → + ∀ h eps : ℝ, 0 < h → 0 < eps → + ∃ n : ℕ, ∃ T : Fin n → Set Plane, ∃ g : Fin n → Plane, + (∀ i, IsSquareTile (T i)) ∧ + physicalRuled 1 D G 1 ⊆ ⋃ i, auxiliaryCylinder (T i) (g i) ∧ + (∑ i, volume.real (T i) * physicalWeight h (g i)) ≤ + (∫ b in D, physicalWeight h (G b)) + eps ∧ + ∀ a : ℝ, ∃ C₁ C₂ : Fin n → Cylinder, + (∀ i, (C₁ i).parallelogram ∧ (C₂ i).parallelogram ∧ + (C₁ i).carrier = firstPhysicalMap h '' auxiliaryCylinder (T i) (g i) ∧ + (C₂ i).carrier = secondPhysicalMap h a '' auxiliaryCylinder (T i) (g i) ∧ + (C₁ i).area = h * volume.real (T i) * physicalWeight h (g i) ∧ + (C₂ i).area = h * volume.real (T i) * physicalWeight h (g i)) + +/-- The regular edge-2 tetrahedron in physical coordinates. -/ +def tetrahedron : Set Space := + {z | ∃ t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |z 0| ≤ 1 - t ∧ |z 1| ≤ t ∧ + z 2 = Real.sqrt 2 * t} + +def singularField (p : ℝ) (b : Plane) : Plane := + vec2 (((1 / 2 : ℝ) / 2) * (b 1 / (1 / 2)) ^ (p - 1) * + (p + (2 - p) * (b 0 / b 1) ^ 2)) + ((b 1 / (1 / 2)) ^ (p - 2) * b 0) + +def ceilingPolynomial (p b : ℝ) : ℝ := + b ^ 2 * ((1 / 2 : ℝ) * p / 2 + (2 - p) / (2 * (1 / 2)) * b ^ 2) + +def singularDomain (p gamma c : ℝ) : Set Plane := + {b | c ^ gamma ≤ b 1 ∧ b 1 ≤ 2 ∧ |b 0| ≤ b 1 ∧ + b 1 ≤ (1 / 2 : ℝ) + c ^ 2 * ceilingPolynomial p (b 0) + c ^ (5 / 2 : ℝ)} + +def singularLower (p gamma c : ℝ) : Set Space := + physicalRuled (Real.sqrt 2) (singularDomain p gamma c) + (fun b => c • singularField p b) 1 + +def singularUpper (p gamma c : ℝ) : Set Space := + {z | ∃ b ∈ singularDomain p gamma c, ∃ y : ℝ, |y| ≤ 1 ∧ + z = vec3 (b 0 - c * y * singularField p b 0) y + (Real.sqrt 2 * (1 - (b 1 - c * y * singularField p b 1)))} + +def lowerTip (d : ℝ) : Set Space := + {z | ∃ t : ℝ, 0 ≤ t ∧ t ≤ 2 * d ∧ |z 1| ≤ t ∧ z 2 = Real.sqrt 2 * t} + +def upperTip (d : ℝ) : Set Space := + {z | ∃ s : ℝ, 0 ≤ s ∧ s ≤ 2 * d ∧ |z 0| ≤ s ∧ z 2 = Real.sqrt 2 * (1 - s)} + +def singularCost (p gamma c : ℝ) : ℝ := + Real.sqrt 2 * ∫ b in singularDomain p gamma c, + physicalWeight (Real.sqrt 2) (c • singularField p b) + +def singularCoefficient (p : ℝ) : ℝ := + (1 / 2 : ℝ) ^ 4 * (2 * p ^ 2 + 10 * p - 13) / (30 * p) + +def SingularStatement : Prop := + ∀ p gamma : ℝ, 1 < p → p < (Real.sqrt 51 - 5) / 2 → + 1 < gamma → gamma < 1 / (2 - p) → + singularCoefficient p < 0 ∧ + Asymptotics.IsLittleO (𝓝[>] (0 : ℝ)) + (fun c => 2 * singularCost p gamma c + 8 * Real.sqrt 2 * (c ^ gamma) ^ 2 - + (Real.sqrt 2 / 2 + 2 * Real.sqrt 2 * singularCoefficient p * c ^ 2)) + (fun c => c ^ 2) ∧ + ∀ᶠ c : ℝ in 𝓝[>] (0 : ℝ), + ∃ n m : ℕ, ∃ C : Fin n → Cylinder, ∃ D : Fin m → Cylinder, + ∃ B₁ B₂ : Cylinder, + (∀ i, (C i).parallelogram) ∧ (∀ j, (D j).parallelogram) ∧ + B₁.triangle ∧ B₂.triangle ∧ + singularLower p gamma c ⊆ familySet C ∧ + singularUpper p gamma c ⊆ familySet D ∧ + B₁.carrier = lowerTip (c ^ gamma) ∧ B₂.carrier = upperTip (c ^ gamma) ∧ + tetrahedron ⊆ familySet C ∪ familySet D ∪ B₁.carrier ∪ B₂.carrier ∧ + familyArea C + familyArea D + B₁.area + B₂.area < Real.sqrt 2 / 2 + +def FullMain : Prop := + HyperbolicStatement ∧ PhysicalHyperbolicStatement ∧ LogarithmicStatement ∧ + ProductCellStatement ∧ OrthogonalGridStatement ∧ NilpotentStatement ∧ SingularStatement + +theorem fullMain : FullMain := by + sorry + +end RuledApproximation + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RuledCovering.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RuledApproximation.fullMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ruled-covering/solution/closure.txt b/tasks/ruled-covering/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bccb53119e42406b51c3811d9eae6dd75b595cdc --- /dev/null +++ b/tasks/ruled-covering/solution/closure.txt @@ -0,0 +1,30 @@ +OAI.Geometry.RuledCovering.CapAsymptotics +OAI.Geometry.RuledCovering.ConeVolume +OAI.Geometry.RuledCovering.ConvexBases +OAI.Geometry.RuledCovering.EnergyIntegral +OAI.Geometry.RuledCovering.Frames +OAI.Geometry.RuledCovering.Hyperbolic +OAI.Geometry.RuledCovering.HyperbolicCover +OAI.Geometry.RuledCovering.HyperbolicLattice +OAI.Geometry.RuledCovering.Isometries +OAI.Geometry.RuledCovering.Lattice +OAI.Geometry.RuledCovering.LocalApproximation +OAI.Geometry.RuledCovering.LocalCover +OAI.Geometry.RuledCovering.Main +OAI.Geometry.RuledCovering.Model +OAI.Geometry.RuledCovering.Nilpotent +OAI.Geometry.RuledCovering.NilpotentLattice +OAI.Geometry.RuledCovering.OuterApproximation +OAI.Geometry.RuledCovering.PlanarIntegration +OAI.Geometry.RuledCovering.Projection +OAI.Geometry.RuledCovering.Singular +OAI.Geometry.RuledCovering.SingularAsymptotics +OAI.Geometry.RuledCovering.SingularBounds +OAI.Geometry.RuledCovering.SingularEnergy +OAI.Geometry.RuledCovering.SingularField +OAI.Geometry.RuledCovering.SingularGeometry +OAI.Geometry.RuledCovering.SingularInverse +OAI.Geometry.RuledCovering.SingularOverlap +OAI.Geometry.RuledCovering.SpecializedCover +OAI.Geometry.RuledCovering.SquareCover +OAI.Geometry.RuledCovering.TipCylinders diff --git a/tasks/ruled-covering/solution/reference.py b/tasks/ruled-covering/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ruled-covering/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ruled-covering/solution/solve.sh b/tasks/ruled-covering/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2914b33ea0301a8a3b7cbca081f4f089627a037e --- /dev/null +++ b/tasks/ruled-covering/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RuledCovering, i.e. module OAI.Geometry.RuledCovering.Main and the +# 30 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.RuledCovering.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RuledCovering" diff --git a/tasks/ruled-covering/task.toml b/tasks/ruled-covering/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..766ea2ea03f51e4440dcc10a0b863ec8996bbf84 --- /dev/null +++ b/tasks/ruled-covering/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ruled-covering" +version = "1.0.0" +description = "Prove RuledCovering (openai/math family 100: A counterexample to Bang's cylinder-covering bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RuledCovering.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RuledCovering" +family = "100" +family_title = "A counterexample to Bang's cylinder-covering bound" +subject = "Convex and metric geometry" +theorems = ["OAI.RuledApproximation.fullMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.RuledCovering.Main" +reference_modules = 30 +reference_lean_bytes = 195883 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 963 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11876 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ruled-covering/tests/Challenge.lean b/tasks/ruled-covering/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..453e3cbc43dc28e8075c98cee588311da98cfde0 --- /dev/null +++ b/tasks/ruled-covering/tests/Challenge.lean @@ -0,0 +1,222 @@ +import Mathlib + +namespace OAI + +noncomputable section +open Set MeasureTheory Filter +open scoped Topology ContDiff +namespace RuledApproximation + +abbrev Plane := EuclideanSpace ℝ (Fin 2) +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def vec2 (x y : ℝ) : Plane := WithLp.toLp 2 ![x, y] +def vec3 (x y z : ℝ) : Space := WithLp.toLp 2 ![x, y, z] +def axial (s : ℝ) (p : Plane) : Space := vec3 s (p 0) (p 1) + +def IsParallelogram {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s ∈ Icc (0 : ℝ) 1, ∃ t ∈ Icc (0 : ℝ) 1, + x = c + s • u + t • v} + +def IsTriangle {E : Type*} [AddCommGroup E] [Module ℝ E] (P : Set E) : Prop := + ∃ c u v : E, LinearIndependent ℝ ![u, v] ∧ + P = {x | ∃ s : ℝ, ∃ t : ℝ, 0 ≤ s ∧ 0 ≤ t ∧ s + t ≤ 1 ∧ + x = c + s • u + t • v} + +structure Cylinder where + axis : Space + unit_axis : ‖axis‖ = 1 + base : Set ((Submodule.span ℝ ({axis} : Set Space))ᗮ) + +namespace Cylinder + +def carrier (C : Cylinder) : Set Space := + {x | ∃ b ∈ C.base, ∃ t : ℝ, x = (b : Space) + t • C.axis} + +def area (C : Cylinder) : ℝ := volume.real C.base + +def parallelogram (C : Cylinder) : Prop := IsParallelogram C.base + +def triangle (C : Cylinder) : Prop := IsTriangle C.base + +def openBounded (C : Cylinder) : Prop := + IsOpen C.base ∧ Bornology.IsBounded C.base ∧ MeasurableSet C.base +end Cylinder + +def familySet {n : ℕ} (C : Fin n → Cylinder) : Set Space := ⋃ i, (C i).carrier +def familyArea {n : ℕ} (C : Fin n → Cylinder) : ℝ := ∑ i, (C i).area + +def HasFiniteCover (shape : Cylinder → Prop) (S : Set Space) (A : ℝ) : Prop := + ∃ n : ℕ, ∃ C : Fin n → Cylinder, + (∀ i, shape (C i)) ∧ S ⊆ familySet C ∧ familyArea C ≤ A + +/-- No boundary hypothesis is included in this neighborhood regularity predicate. -/ +def SmoothNear (n : WithTop ℕ∞) (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ U : Set Plane, IsOpen U ∧ D ⊆ U ∧ ContDiffOn ℝ n v U + +/-- In dimension two these two distinct nonzero eigenvalues are all the eigenvalues. -/ +def HyperbolicAt (L : ℝ) (v : Plane → Plane) (p : Plane) : Prop := + ∃ lam : ℝ, 0 < L * lam ∧ L * lam < 1 ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap lam ∧ + Module.End.HasEigenvalue (fderiv ℝ v p).toLinearMap (-lam) + +def weight (v : Plane) : ℝ := 1 / Real.sqrt (1 + ‖v‖ ^ 2) +def physicalWeight (h : ℝ) (w : Plane) : ℝ := + 1 / Real.sqrt (1 + w 0 ^ 2 + h ^ 2 * w 1 ^ 2) + +def ruled (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ r : ℝ, |r| ≤ L ∧ + z = vec3 (p 0 + r * v p 0) (p 1 + r * v p 1) r} + +def physicalRuled (h : ℝ) (D : Set Plane) (v : Plane → Plane) (L : ℝ) : Set Space := + {z | ∃ p ∈ D, ∃ s : ℝ, |s| ≤ L ∧ + z = vec3 s (p 0 + s * v p 0) (h * (p 1 + s * v p 1))} + +def HyperbolicStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (L : ℝ), + IsCompact D → SmoothNear 1 D v → 0 < L → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram (ruled D v L) + ((∫ p in D, weight (v p)) + e) + +def PhysicalHyperbolicStatement : Prop := + ∀ (h L : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < h → 0 < L → IsCompact D → SmoothNear 1 D v → + (∀ p ∈ D, HyperbolicAt L v p) → + ∀ (e : ℝ), 0 < e → ∀ F : Space ≃ᵢ Space, + HasFiniteCover Cylinder.parallelogram (F '' physicalRuled h D v L) + (h * (∫ p in D, physicalWeight h (v p)) + e) + +def OpenRectangleC2 (D : Set Plane) (v : Plane → Plane) : Prop := + ∃ a b : Plane, (∀ i, a i < b i) ∧ + D ⊆ {p | ∀ i, p i ∈ Ioo (a i) (b i)} ∧ + ContDiffOn ℝ 2 v {p | ∀ i, p i ∈ Ioo (a i) (b i)} + +def LogarithmicStatement : Prop := + ∀ (X k : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < X → 0 < k → IsCompact D → volume (frontier D) = 0 → + OpenRectangleC2 D v → + (∀ p ∈ D, LinearMap.trace ℝ Plane (fderiv ℝ v p).toLinearMap = 0 ∧ + LinearMap.det (fderiv ℝ v p).toLinearMap < 0 ∧ + k * X * Real.sqrt (-LinearMap.det (fderiv ℝ v p).toLinearMap) < 1) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.openBounded + (physicalRuled 1 D (fun p => k • v p) X) + ((∫ p in D, 1 / Real.sqrt (1 + k ^ 2 * ‖v p‖ ^ 2)) + e) + +def ProductCellStatement : Prop := + ∀ (h M : ℝ) (D : Set Plane) (v : Plane → Plane), + 0 < h → 0 < M → IsCompact D → volume (frontier D) = 0 → + SmoothNear 1 D v → (∀ p ∈ D, HyperbolicAt M v p) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.openBounded (physicalRuled h D v M) + (h * (∫ p in D, physicalWeight h (v p)) + e) + +def OrthogonalGridStatement : Prop := + ∀ (D : Set Plane) (v : Plane → Plane) (kappa : ℝ), + IsCompact D → volume (frontier D) = 0 → SmoothNear 1 D v → kappa < 1 → + (∀ p ∈ D, LinearMap.trace ℝ Plane (fderiv ℝ v p).toLinearMap = 0 ∧ + LinearMap.det (fderiv ℝ v p).toLinearMap < 0 ∧ ‖fderiv ℝ v p‖ ≤ kappa) → + ∀ e : ℝ, 0 < e → HasFiniteCover Cylinder.parallelogram + (physicalRuled (Real.sqrt 2) D v 1) + (Real.sqrt 2 * (∫ p in D, + 1 / Real.sqrt (1 + v p 0 ^ 2 + 2 * v p 1 ^ 2)) + e) + +def unitSquare : Set Plane := {x | ∀ i, |x i| ≤ (1 : ℝ) / 2} + +def IsSquareTile (T : Set Plane) : Prop := + ∃ c : Plane, ∃ R : Plane ≃ₗᵢ[ℝ] Plane, ∃ a : ℝ, 0 < a ∧ + T = (fun x => c + a • R x) '' unitSquare + +def auxiliaryCylinder (T : Set Plane) (g : Plane) : Set Space := + {z | ∃ s : ℝ, ∃ b ∈ T, z = axial s (b + s • g)} + +def firstPhysicalMap (h : ℝ) (z : Space) : Space := vec3 (z 0) (z 1) (h * z 2) +def secondPhysicalMap (h a : ℝ) (z : Space) : Space := + vec3 (z 1) (z 0) (h * (a - z 2)) + +def NilpotentStatement : Prop := + ∀ (D : Set Plane) (G : Plane → Plane), IsCompact D → SmoothNear ∞ D G → + (∀ b ∈ D, (fderiv ℝ G b).comp (fderiv ℝ G b) = 0) → + ∀ h eps : ℝ, 0 < h → 0 < eps → + ∃ n : ℕ, ∃ T : Fin n → Set Plane, ∃ g : Fin n → Plane, + (∀ i, IsSquareTile (T i)) ∧ + physicalRuled 1 D G 1 ⊆ ⋃ i, auxiliaryCylinder (T i) (g i) ∧ + (∑ i, volume.real (T i) * physicalWeight h (g i)) ≤ + (∫ b in D, physicalWeight h (G b)) + eps ∧ + ∀ a : ℝ, ∃ C₁ C₂ : Fin n → Cylinder, + (∀ i, (C₁ i).parallelogram ∧ (C₂ i).parallelogram ∧ + (C₁ i).carrier = firstPhysicalMap h '' auxiliaryCylinder (T i) (g i) ∧ + (C₂ i).carrier = secondPhysicalMap h a '' auxiliaryCylinder (T i) (g i) ∧ + (C₁ i).area = h * volume.real (T i) * physicalWeight h (g i) ∧ + (C₂ i).area = h * volume.real (T i) * physicalWeight h (g i)) + +/-- The regular edge-2 tetrahedron in physical coordinates. -/ +def tetrahedron : Set Space := + {z | ∃ t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |z 0| ≤ 1 - t ∧ |z 1| ≤ t ∧ + z 2 = Real.sqrt 2 * t} + +def singularField (p : ℝ) (b : Plane) : Plane := + vec2 (((1 / 2 : ℝ) / 2) * (b 1 / (1 / 2)) ^ (p - 1) * + (p + (2 - p) * (b 0 / b 1) ^ 2)) + ((b 1 / (1 / 2)) ^ (p - 2) * b 0) + +def ceilingPolynomial (p b : ℝ) : ℝ := + b ^ 2 * ((1 / 2 : ℝ) * p / 2 + (2 - p) / (2 * (1 / 2)) * b ^ 2) + +def singularDomain (p gamma c : ℝ) : Set Plane := + {b | c ^ gamma ≤ b 1 ∧ b 1 ≤ 2 ∧ |b 0| ≤ b 1 ∧ + b 1 ≤ (1 / 2 : ℝ) + c ^ 2 * ceilingPolynomial p (b 0) + c ^ (5 / 2 : ℝ)} + +def singularLower (p gamma c : ℝ) : Set Space := + physicalRuled (Real.sqrt 2) (singularDomain p gamma c) + (fun b => c • singularField p b) 1 + +def singularUpper (p gamma c : ℝ) : Set Space := + {z | ∃ b ∈ singularDomain p gamma c, ∃ y : ℝ, |y| ≤ 1 ∧ + z = vec3 (b 0 - c * y * singularField p b 0) y + (Real.sqrt 2 * (1 - (b 1 - c * y * singularField p b 1)))} + +def lowerTip (d : ℝ) : Set Space := + {z | ∃ t : ℝ, 0 ≤ t ∧ t ≤ 2 * d ∧ |z 1| ≤ t ∧ z 2 = Real.sqrt 2 * t} + +def upperTip (d : ℝ) : Set Space := + {z | ∃ s : ℝ, 0 ≤ s ∧ s ≤ 2 * d ∧ |z 0| ≤ s ∧ z 2 = Real.sqrt 2 * (1 - s)} + +def singularCost (p gamma c : ℝ) : ℝ := + Real.sqrt 2 * ∫ b in singularDomain p gamma c, + physicalWeight (Real.sqrt 2) (c • singularField p b) + +def singularCoefficient (p : ℝ) : ℝ := + (1 / 2 : ℝ) ^ 4 * (2 * p ^ 2 + 10 * p - 13) / (30 * p) + +def SingularStatement : Prop := + ∀ p gamma : ℝ, 1 < p → p < (Real.sqrt 51 - 5) / 2 → + 1 < gamma → gamma < 1 / (2 - p) → + singularCoefficient p < 0 ∧ + Asymptotics.IsLittleO (𝓝[>] (0 : ℝ)) + (fun c => 2 * singularCost p gamma c + 8 * Real.sqrt 2 * (c ^ gamma) ^ 2 - + (Real.sqrt 2 / 2 + 2 * Real.sqrt 2 * singularCoefficient p * c ^ 2)) + (fun c => c ^ 2) ∧ + ∀ᶠ c : ℝ in 𝓝[>] (0 : ℝ), + ∃ n m : ℕ, ∃ C : Fin n → Cylinder, ∃ D : Fin m → Cylinder, + ∃ B₁ B₂ : Cylinder, + (∀ i, (C i).parallelogram) ∧ (∀ j, (D j).parallelogram) ∧ + B₁.triangle ∧ B₂.triangle ∧ + singularLower p gamma c ⊆ familySet C ∧ + singularUpper p gamma c ⊆ familySet D ∧ + B₁.carrier = lowerTip (c ^ gamma) ∧ B₂.carrier = upperTip (c ^ gamma) ∧ + tetrahedron ⊆ familySet C ∪ familySet D ∪ B₁.carrier ∪ B₂.carrier ∧ + familyArea C + familyArea D + B₁.area + B₂.area < Real.sqrt 2 / 2 + +def FullMain : Prop := + HyperbolicStatement ∧ PhysicalHyperbolicStatement ∧ LogarithmicStatement ∧ + ProductCellStatement ∧ OrthogonalGridStatement ∧ NilpotentStatement ∧ SingularStatement + +theorem fullMain : FullMain := by + sorry + +end RuledApproximation + +end + +end OAI diff --git a/tasks/ruled-covering/tests/grade.py b/tasks/ruled-covering/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ruled-covering/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ruled-covering/tests/task.json b/tasks/ruled-covering/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..45e66aa1c7a39e43ad67ac810fe514cb189a23c1 --- /dev/null +++ b/tasks/ruled-covering/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RuledCovering", + "comparator": { + "theorem_names": [ + "OAI.RuledApproximation.fullMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10976 +} \ No newline at end of file diff --git a/tasks/ruled-covering/tests/test.sh b/tasks/ruled-covering/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ruled-covering/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ryser-covering/environment/Dockerfile b/tasks/ryser-covering/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ryser-covering/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ryser-covering/environment/fetch_mathlib.sh b/tasks/ryser-covering/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ryser-covering/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ryser-covering/environment/lake-manifest.json b/tasks/ryser-covering/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ryser-covering/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ryser-covering/environment/lakefile.lean b/tasks/ryser-covering/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ryser-covering/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ryser-covering/environment/lean_setup.sh b/tasks/ryser-covering/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ryser-covering/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ryser-covering/environment/pack_submission.py b/tasks/ryser-covering/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ryser-covering/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ryser-covering/instruction.md b/tasks/ryser-covering/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d052f3bad6fd035c6f36c13b1bea2f1026c2c1cc --- /dev/null +++ b/tasks/ryser-covering/instruction.md @@ -0,0 +1,110 @@ +# openai/math challenge `RyserCovering` (family 162) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 162 of the release, *Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures* +(Combinatorics). The family as a whole: Disproves Ryser's covering conjecture by constructing intersecting $(q+1)$-partite, $(q+1)$-uniform hypergraphs with covering number $q+1$, rather than the predicted bound $q$, for every sufficiently large prime $q$. A separate construction over extension fields also disproves Gyarfas's monochromatic tree-cover conjecture. + +The challenge is `RyserCovering`, also at `/opt/openai-math/challenges/RyserCovering.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace RyserCoveringCounterexample + +abbrev Hypergraph (V : Type*) := Finset (Finset V) + +section + +variable {V : Type*} [DecidableEq V] + +def IsCover (H : Hypergraph V) (C : Finset V) : Prop := + ∀ e ∈ H, ∃ v ∈ C, v ∈ e + +def Intersecting (H : Hypergraph V) : Prop := + ∀ e ∈ H, ∀ f ∈ H, e ≠ f → (e ∩ f).Nonempty + +attribute [-instance] instDecidablePairwiseCoeFinsetOfDecidableEqOfDecidableRel in +def matchings (H : Hypergraph V) : Finset (Hypergraph V) := by + classical + exact H.powerset.filter fun M => (M : Set (Finset V)).Pairwise Disjoint + +def matchingNumber (H : Hypergraph V) : ℕ := (matchings H).sup Finset.card + +def coverCardinalities (H : Hypergraph V) : Set ℕ := + {n | ∃ C : Finset V, IsCover H C ∧ C.card = n} + +def coverNumber (H : Hypergraph V) : ℕ := sInf (coverCardinalities H) + +def PartiteUniform {I : Type*} (part : V → I) (H : Hypergraph V) : Prop := + ∀ e ∈ H, ∀ i : I, ∃! v : V, v ∈ e ∧ part v = i + +def RPartiteUniform (r : ℕ) (H : Hypergraph V) : Prop := + ∃ part : V → Fin r, PartiteUniform part H + +end + +def CounterexampleRank (r : ℕ) : Prop := + ∃ (V : Type) (fin : Fintype V) (dec : DecidableEq V), + letI : Fintype V := fin + letI : DecidableEq V := dec + ∃ H : Hypergraph V, + 0 < r ∧ H.Nonempty ∧ RPartiteUniform r H ∧ Intersecting H ∧ + (∃ C : Finset V, IsCover H C) ∧ matchingNumber H = 1 ∧ coverNumber H = r + +theorem exists_prime_eventually_counterexampleRank : + ∃ p : ℕ, p.Prime ∧ 5 < p ∧ p % 3 = 2 ∧ + ∃ N : ℕ, ∀ n : ℕ, N ≤ n → n.Prime → 2 < n → + CounterexampleRank (p ^ n + 1) := by + sorry + +end RyserCoveringCounterexample + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RyserCovering.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RyserCoveringCounterexample.exists_prime_eventually_counterexampleRank` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ryser-covering/solution/closure.txt b/tasks/ryser-covering/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..502b1b34f241fbda52b75d704d2a88288000eccf --- /dev/null +++ b/tasks/ryser-covering/solution/closure.txt @@ -0,0 +1,217 @@ +OAI.Combinatorics.Ryser.Construction.ActualHypergraph +OAI.Combinatorics.Ryser.Construction.AmbientDeletionGeometry +OAI.Combinatorics.Ryser.Construction.AmbientDeletionNumerics +OAI.Combinatorics.Ryser.Construction.AmbientDeletionPoolLaw +OAI.Combinatorics.Ryser.Construction.AmbientDeletionProcess +OAI.Combinatorics.Ryser.Construction.AmbientDeletionShapes +OAI.Combinatorics.Ryser.Construction.AmbientDeletionSurvivors +OAI.Combinatorics.Ryser.Construction.AmbientDeletionTrials +OAI.Combinatorics.Ryser.Construction.AmbientPoolExistence +OAI.Combinatorics.Ryser.Construction.CoordinateCompatibility +OAI.Combinatorics.Ryser.Construction.CosetDirections +OAI.Combinatorics.Ryser.Construction.CosetIndex +OAI.Combinatorics.Ryser.Construction.CoverBudget +OAI.Combinatorics.Ryser.Construction.CoverCounting +OAI.Combinatorics.Ryser.Construction.CoverPencil +OAI.Combinatorics.Ryser.Construction.DeletionIntersection +OAI.Combinatorics.Ryser.Construction.DeletionLines +OAI.Combinatorics.Ryser.Construction.DeletionParallel +OAI.Combinatorics.Ryser.Construction.DeletionUnionBasic +OAI.Combinatorics.Ryser.Construction.DeletionUnionInside +OAI.Combinatorics.Ryser.Construction.DeletionUnionOutside +OAI.Combinatorics.Ryser.Construction.DeterministicCover +OAI.Combinatorics.Ryser.Construction.DirectionPlacement +OAI.Combinatorics.Ryser.Construction.DirectionSets +OAI.Combinatorics.Ryser.Construction.ExceptionalBudget +OAI.Combinatorics.Ryser.Construction.ExceptionalCover +OAI.Combinatorics.Ryser.Construction.ExtraDirections +OAI.Combinatorics.Ryser.Construction.FiniteInsideCover +OAI.Combinatorics.Ryser.Construction.FiniteOutsideAction +OAI.Combinatorics.Ryser.Construction.FiniteOutsideCover +OAI.Combinatorics.Ryser.Construction.FiniteSelectionCounting +OAI.Combinatorics.Ryser.Construction.GadgetAlgebra +OAI.Combinatorics.Ryser.Construction.GadgetConcentration +OAI.Combinatorics.Ryser.Construction.GadgetConsequences +OAI.Combinatorics.Ryser.Construction.GadgetCover +OAI.Combinatorics.Ryser.Construction.GadgetDefinitions +OAI.Combinatorics.Ryser.Construction.GadgetExistence +OAI.Combinatorics.Ryser.Construction.GadgetGood +OAI.Combinatorics.Ryser.Construction.GadgetOriginalCounts +OAI.Combinatorics.Ryser.Construction.GadgetOriginalDensity +OAI.Combinatorics.Ryser.Construction.GadgetOriginalExpectation +OAI.Combinatorics.Ryser.Construction.GadgetProcess +OAI.Combinatorics.Ryser.Construction.GadgetShapes +OAI.Combinatorics.Ryser.Construction.GroupBounds +OAI.Combinatorics.Ryser.Construction.GroupPlacement +OAI.Combinatorics.Ryser.Construction.GroupSelection +OAI.Combinatorics.Ryser.Construction.Hypergraph +OAI.Combinatorics.Ryser.Construction.InfiniteCover +OAI.Combinatorics.Ryser.Construction.Intersection +OAI.Combinatorics.Ryser.Construction.LabelAction +OAI.Combinatorics.Ryser.Construction.LinearPlacement +OAI.Combinatorics.Ryser.Construction.Main +OAI.Combinatorics.Ryser.Construction.OrdinaryCover +OAI.Combinatorics.Ryser.Construction.PlacedLines +OAI.Combinatorics.Ryser.Construction.PlacementIntersection +OAI.Combinatorics.Ryser.Construction.PoolThinAsymptotic +OAI.Combinatorics.Ryser.Construction.PoolThinGeometry +OAI.Combinatorics.Ryser.Construction.PoolThinProbability +OAI.Combinatorics.Ryser.Construction.PoolThinSelection +OAI.Combinatorics.Ryser.Construction.SelectedHypergraph +OAI.Combinatorics.Ryser.Construction.SmallPrimes +OAI.Combinatorics.Ryser.Domination.Append +OAI.Combinatorics.Ryser.Domination.Basic +OAI.Combinatorics.Ryser.Domination.Counting +OAI.Combinatorics.Ryser.Domination.Exchange +OAI.Combinatorics.Ryser.Domination.Extension +OAI.Combinatorics.Ryser.Domination.Main +OAI.Combinatorics.Ryser.Domination.Nonempty +OAI.Combinatorics.Ryser.Domination.Seed +OAI.Combinatorics.Ryser.Domination.TraceDefinitions +OAI.Combinatorics.Ryser.Field.Extension +OAI.Combinatorics.Ryser.Field.ExtensionSubfields +OAI.Combinatorics.Ryser.Field.SubfieldBound +OAI.Combinatorics.Ryser.Geometry.AffineJoins +OAI.Combinatorics.Ryser.Geometry.Basic +OAI.Combinatorics.Ryser.Geometry.Cardinality +OAI.Combinatorics.Ryser.Geometry.Normalization +OAI.Combinatorics.Ryser.Geometry.ProjectionMoments +OAI.Combinatorics.Ryser.Geometry.ProjectionPair +OAI.Combinatorics.Ryser.Geometry.ProjectiveJoins +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformAffine +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformBasic +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformXY +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformXZ +OAI.Combinatorics.Ryser.Geometry.SliceEnergy +OAI.Combinatorics.Ryser.Hypergraph.Cover +OAI.Combinatorics.Ryser.Hypergraph.Definitions +OAI.Combinatorics.Ryser.Hypergraph.Infinitude +OAI.Combinatorics.Ryser.Hypergraph.Matching +OAI.Combinatorics.Ryser.Hypergraph.Partite +OAI.Combinatorics.Ryser.Incidence.AllLineCap +OAI.Combinatorics.Ryser.Incidence.CoordinateTransfer +OAI.Combinatorics.Ryser.Incidence.CoordinateTransferSet +OAI.Combinatorics.Ryser.Incidence.DegreeSquares +OAI.Combinatorics.Ryser.Incidence.DenseNeighborhood +OAI.Combinatorics.Ryser.Incidence.ExtractedContradiction +OAI.Combinatorics.Ryser.Incidence.FiniteSetCovering +OAI.Combinatorics.Ryser.Incidence.FiniteSetEstimates +OAI.Combinatorics.Ryser.Incidence.FiniteSets +OAI.Combinatorics.Ryser.Incidence.FourAnchors +OAI.Combinatorics.Ryser.Incidence.FourAnchorsCounting +OAI.Combinatorics.Ryser.Incidence.FourAnchorsGeometry +OAI.Combinatorics.Ryser.Incidence.FourAnchorsLocal +OAI.Combinatorics.Ryser.Incidence.FourAnchorsNumerics +OAI.Combinatorics.Ryser.Incidence.GraphParameters +OAI.Combinatorics.Ryser.Incidence.NoApproximateSubfield +OAI.Combinatorics.Ryser.Incidence.NoApproximateSubfieldNumerics +OAI.Combinatorics.Ryser.Incidence.Parameters +OAI.Combinatorics.Ryser.Incidence.Pencils +OAI.Combinatorics.Ryser.Incidence.PopularOverlap +OAI.Combinatorics.Ryser.Incidence.PopularScalars +OAI.Combinatorics.Ryser.Incidence.PrunedContradiction +OAI.Combinatorics.Ryser.Incidence.Pruning +OAI.Combinatorics.Ryser.Incidence.PruningCore +OAI.Combinatorics.Ryser.Incidence.PruningHigh +OAI.Combinatorics.Ryser.Incidence.PruningNumerics +OAI.Combinatorics.Ryser.Incidence.RatioSet +OAI.Combinatorics.Ryser.Incidence.ScalarCollisionCount +OAI.Combinatorics.Ryser.Incidence.ScalarCollisions +OAI.Combinatorics.Ryser.Incidence.ScalarCover +OAI.Combinatorics.Ryser.Incidence.ScalarCoverExpressions +OAI.Combinatorics.Ryser.Incidence.ScalarCoverGeometry +OAI.Combinatorics.Ryser.Incidence.Uniform +OAI.Combinatorics.Ryser.Incidence.WalkCounts +OAI.Combinatorics.Ryser.Incidence.WalkExpansion +OAI.Combinatorics.Ryser.Incidence.WalkExtraction +OAI.Combinatorics.Ryser.Incidence.WalkQuotients +OAI.Combinatorics.Ryser.Incidence.WalkTrimming +OAI.Combinatorics.Ryser.LineCover.CleanCover +OAI.Combinatorics.Ryser.LineCover.CountConcentration +OAI.Combinatorics.Ryser.LineCover.CountEvents +OAI.Combinatorics.Ryser.LineCover.CountTailNumerics +OAI.Combinatorics.Ryser.LineCover.CoverEstimates +OAI.Combinatorics.Ryser.LineCover.Definitions +OAI.Combinatorics.Ryser.LineCover.Deletion +OAI.Combinatorics.Ryser.LineCover.DeletionDefinitions +OAI.Combinatorics.Ryser.LineCover.DisjointPairs +OAI.Combinatorics.Ryser.LineCover.FailureNumerics +OAI.Combinatorics.Ryser.LineCover.FiniteFailureNumerics +OAI.Combinatorics.Ryser.LineCover.GoodCounts +OAI.Combinatorics.Ryser.LineCover.GoodTuples +OAI.Combinatorics.Ryser.LineCover.HeavyIncidence +OAI.Combinatorics.Ryser.LineCover.HighConcurrency +OAI.Combinatorics.Ryser.LineCover.HighDegeneracy +OAI.Combinatorics.Ryser.LineCover.HighIncidence +OAI.Combinatorics.Ryser.LineCover.HighOccupancy +OAI.Combinatorics.Ryser.LineCover.HighProbability +OAI.Combinatorics.Ryser.LineCover.HighSamples +OAI.Combinatorics.Ryser.LineCover.InjectionSampling +OAI.Combinatorics.Ryser.LineCover.LowConcurrency +OAI.Combinatorics.Ryser.LineCover.LowDegeneracy +OAI.Combinatorics.Ryser.LineCover.LowOccupancy +OAI.Combinatorics.Ryser.LineCover.Main +OAI.Combinatorics.Ryser.LineCover.MaxConcurrency +OAI.Combinatorics.Ryser.LineCover.MeanCounts +OAI.Combinatorics.Ryser.LineCover.Overlap +OAI.Combinatorics.Ryser.LineCover.PairCounting +OAI.Combinatorics.Ryser.LineCover.PairSampling +OAI.Combinatorics.Ryser.LineCover.Process +OAI.Combinatorics.Ryser.LineCover.ProjectiveLift +OAI.Combinatorics.Ryser.LineCover.Rigidity +OAI.Combinatorics.Ryser.LineCover.RigidityNumerics +OAI.Combinatorics.Ryser.LineCover.RigidityParameters +OAI.Combinatorics.Ryser.LineCover.RigiditySampling +OAI.Combinatorics.Ryser.LineCover.SamplingDefinitions +OAI.Combinatorics.Ryser.LineCover.SamplingNumerics +OAI.Combinatorics.Ryser.LineCover.SurvivalNumerics +OAI.Combinatorics.Ryser.LineCover.SurvivorSampling +OAI.Combinatorics.Ryser.LineCover.TailNumerics +OAI.Combinatorics.Ryser.LineCover.TupleConcentration +OAI.Combinatorics.Ryser.LineCover.TupleGeometry +OAI.Combinatorics.Ryser.LineCover.TwoPopulationMoments +OAI.Combinatorics.Ryser.LineCover.TwoPopulationSampling +OAI.Combinatorics.Ryser.Probability.Concentration +OAI.Combinatorics.Ryser.Probability.Exponential +OAI.Combinatorics.Ryser.Probability.Exposure +OAI.Combinatorics.Ryser.Probability.Finite +OAI.Combinatorics.Ryser.Probability.Product +OAI.Combinatorics.Ryser.Probability.ProductMap +OAI.Combinatorics.Ryser.Probability.RareAnchor +OAI.Combinatorics.Ryser.Probability.Variance +OAI.Combinatorics.Ryser.Selection.AnalyticalLimits +OAI.Combinatorics.Ryser.Selection.CertificateBounds +OAI.Combinatorics.Ryser.Selection.CertificateCount +OAI.Combinatorics.Ryser.Selection.CertificateUnion +OAI.Combinatorics.Ryser.Selection.Chunk +OAI.Combinatorics.Ryser.Selection.ChunkConditioning +OAI.Combinatorics.Ryser.Selection.ChunkDensity +OAI.Combinatorics.Ryser.Selection.ChunkEnergy +OAI.Combinatorics.Ryser.Selection.ChunkLoss +OAI.Combinatorics.Ryser.Selection.ChunkPartition +OAI.Combinatorics.Ryser.Selection.ChunkPartitionBounds +OAI.Combinatorics.Ryser.Selection.ChunkTail +OAI.Combinatorics.Ryser.Selection.ChunkTailAsymptotics +OAI.Combinatorics.Ryser.Selection.Definitions +OAI.Combinatorics.Ryser.Selection.DensityConstants +OAI.Combinatorics.Ryser.Selection.Estimates +OAI.Combinatorics.Ryser.Selection.FeasibleDensity +OAI.Combinatorics.Ryser.Selection.Forbidden +OAI.Combinatorics.Ryser.Selection.IndependentTail +OAI.Combinatorics.Ryser.Selection.KChoice +OAI.Combinatorics.Ryser.Selection.LargeCertificates +OAI.Combinatorics.Ryser.Selection.LayerBounds +OAI.Combinatorics.Ryser.Selection.LayerNormalization +OAI.Combinatorics.Ryser.Selection.Main +OAI.Combinatorics.Ryser.Selection.NumericLimits +OAI.Combinatorics.Ryser.Selection.Parameters +OAI.Combinatorics.Ryser.Selection.PoolCounts +OAI.Combinatorics.Ryser.Selection.PoolGraph +OAI.Combinatorics.Ryser.Selection.PoolLaw +OAI.Combinatorics.Ryser.Selection.Quantitative +OAI.Combinatorics.Ryser.Selection.RegularTail +OAI.Combinatorics.Ryser.Selection.SmallCertificates +OAI.Combinatorics.Ryser.Selection.SmallRange +OAI.Combinatorics.Ryser.Selection.SmallSum +OAI.Combinatorics.Ryser.Selection.UniformDensity +OAI.Combinatorics.Ryser.Selection.UnusedProduct diff --git a/tasks/ryser-covering/solution/reference.py b/tasks/ryser-covering/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ryser-covering/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ryser-covering/solution/solve.sh b/tasks/ryser-covering/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ad40db3b0345c8f91068638e0d142aef0f182352 --- /dev/null +++ b/tasks/ryser-covering/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RyserCovering, i.e. module OAI.Combinatorics.Ryser.Construction.Main and the +# 217 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Ryser.Construction.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RyserCovering" diff --git a/tasks/ryser-covering/task.toml b/tasks/ryser-covering/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..bd4ccd4725995918ba7ec8bef8a57f36ea1e0527 --- /dev/null +++ b/tasks/ryser-covering/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ryser-covering" +version = "1.0.0" +description = "Prove RyserCovering (openai/math family 162: Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RyserCovering.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RyserCovering" +family = "162" +family_title = "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures" +subject = "Combinatorics" +theorems = ["OAI.RyserCoveringCounterexample.exists_prime_eventually_counterexampleRank"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Ryser.Construction.Main" +reference_modules = 217 +reference_lean_bytes = 1129016 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 702 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12716 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ryser-covering/tests/Challenge.lean b/tasks/ryser-covering/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d57361e616da5348374a59ef77ac695a6a166fb4 --- /dev/null +++ b/tasks/ryser-covering/tests/Challenge.lean @@ -0,0 +1,59 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace RyserCoveringCounterexample + +abbrev Hypergraph (V : Type*) := Finset (Finset V) + +section + +variable {V : Type*} [DecidableEq V] + +def IsCover (H : Hypergraph V) (C : Finset V) : Prop := + ∀ e ∈ H, ∃ v ∈ C, v ∈ e + +def Intersecting (H : Hypergraph V) : Prop := + ∀ e ∈ H, ∀ f ∈ H, e ≠ f → (e ∩ f).Nonempty + +attribute [-instance] instDecidablePairwiseCoeFinsetOfDecidableEqOfDecidableRel in +def matchings (H : Hypergraph V) : Finset (Hypergraph V) := by + classical + exact H.powerset.filter fun M => (M : Set (Finset V)).Pairwise Disjoint + +def matchingNumber (H : Hypergraph V) : ℕ := (matchings H).sup Finset.card + +def coverCardinalities (H : Hypergraph V) : Set ℕ := + {n | ∃ C : Finset V, IsCover H C ∧ C.card = n} + +def coverNumber (H : Hypergraph V) : ℕ := sInf (coverCardinalities H) + +def PartiteUniform {I : Type*} (part : V → I) (H : Hypergraph V) : Prop := + ∀ e ∈ H, ∀ i : I, ∃! v : V, v ∈ e ∧ part v = i + +def RPartiteUniform (r : ℕ) (H : Hypergraph V) : Prop := + ∃ part : V → Fin r, PartiteUniform part H + +end + +def CounterexampleRank (r : ℕ) : Prop := + ∃ (V : Type) (fin : Fintype V) (dec : DecidableEq V), + letI : Fintype V := fin + letI : DecidableEq V := dec + ∃ H : Hypergraph V, + 0 < r ∧ H.Nonempty ∧ RPartiteUniform r H ∧ Intersecting H ∧ + (∃ C : Finset V, IsCover H C) ∧ matchingNumber H = 1 ∧ coverNumber H = r + +theorem exists_prime_eventually_counterexampleRank : + ∃ p : ℕ, p.Prime ∧ 5 < p ∧ p % 3 = 2 ∧ + ∃ N : ℕ, ∀ n : ℕ, N ≤ n → n.Prime → 2 < n → + CounterexampleRank (p ^ n + 1) := by + sorry + +end RyserCoveringCounterexample + +end + +end OAI diff --git a/tasks/ryser-covering/tests/grade.py b/tasks/ryser-covering/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ryser-covering/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ryser-covering/tests/task.json b/tasks/ryser-covering/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a7d8a740bd9085a3e72f1dfda2fed7558c694613 --- /dev/null +++ b/tasks/ryser-covering/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RyserCovering", + "comparator": { + "theorem_names": [ + "OAI.RyserCoveringCounterexample.exists_prime_eventually_counterexampleRank" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11816 +} \ No newline at end of file diff --git a/tasks/ryser-covering/tests/test.sh b/tasks/ryser-covering/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ryser-covering/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/ryser-odd-extensions/environment/Dockerfile b/tasks/ryser-odd-extensions/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/ryser-odd-extensions/environment/fetch_mathlib.sh b/tasks/ryser-odd-extensions/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/ryser-odd-extensions/environment/lake-manifest.json b/tasks/ryser-odd-extensions/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/ryser-odd-extensions/environment/lakefile.lean b/tasks/ryser-odd-extensions/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/ryser-odd-extensions/environment/lean_setup.sh b/tasks/ryser-odd-extensions/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/ryser-odd-extensions/environment/pack_submission.py b/tasks/ryser-odd-extensions/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/ryser-odd-extensions/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/ryser-odd-extensions/instruction.md b/tasks/ryser-odd-extensions/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3cc4918659517e1a03bbf7f95f7a36e9bb823be2 --- /dev/null +++ b/tasks/ryser-odd-extensions/instruction.md @@ -0,0 +1,125 @@ +# openai/math challenge `RyserOddExtensions` (family 162) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 162 of the release, *Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures* +(Combinatorics). The family as a whole: Disproves Ryser's covering conjecture by constructing intersecting $(q+1)$-partite, $(q+1)$-uniform hypergraphs with covering number $q+1$, rather than the predicted bound $q$, for every sufficiently large prime $q$. A separate construction over extension fields also disproves Gyarfas's monochromatic tree-cover conjecture. + +The challenge is `RyserOddExtensions`, also at `/opt/openai-math/challenges/RyserOddExtensions.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace RyserCoveringCounterexample + +abbrev Hypergraph (Vertex : Type*) := Finset (Finset Vertex) + +variable {Vertex : Type*} [DecidableEq Vertex] + +def IsCover (hypergraph : Hypergraph Vertex) (cover : Finset Vertex) : Prop := + ∀ edge ∈ hypergraph, ∃ vertex ∈ cover, vertex ∈ edge + +def Intersecting (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, ∀ other ∈ hypergraph, edge ≠ other → (edge ∩ other).Nonempty + +attribute [-instance] instDecidablePairwiseCoeFinsetOfDecidableEqOfDecidableRel in +def matchings (hypergraph : Hypergraph Vertex) : Finset (Hypergraph Vertex) := by + classical + exact hypergraph.powerset.filter fun matching => + (matching : Set (Finset Vertex)).Pairwise Disjoint + +def matchingNumber (hypergraph : Hypergraph Vertex) : ℕ := + (matchings hypergraph).sup Finset.card + +def coverCardinalities (hypergraph : Hypergraph Vertex) : Set ℕ := + {size | ∃ cover : Finset Vertex, IsCover hypergraph cover ∧ cover.card = size} + +def coverNumber (hypergraph : Hypergraph Vertex) : ℕ := sInf (coverCardinalities hypergraph) + +def Uniform (rank : ℕ) (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, edge.card = rank + +def PartiteUniform {Index : Type*} (part : Vertex → Index) + (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, ∀ index : Index, + ∃! vertex : Vertex, vertex ∈ edge ∧ part vertex = index + +def RPartiteUniform (rank : ℕ) (hypergraph : Hypergraph Vertex) : Prop := + ∃ part : Vertex → Fin rank, PartiteUniform part hypergraph + +end RyserCoveringCounterexample + +namespace RyserOdd + +open RyserCoveringCounterexample + +def Specification.ExplicitFailureAt (rank : ℕ) : Prop := + ∃ (Vertex : Type) (finiteVertices : Fintype Vertex) (decidableVertices : DecidableEq Vertex), + letI : Fintype Vertex := finiteVertices + letI : DecidableEq Vertex := decidableVertices + ∃ hypergraph : RyserCoveringCounterexample.Hypergraph Vertex, + 0 < rank ∧ hypergraph.Nonempty ∧ RPartiteUniform rank hypergraph ∧ + Uniform rank hypergraph ∧ Intersecting hypergraph ∧ + (∃ cover : Finset Vertex, IsCover hypergraph cover) ∧ + matchingNumber hypergraph = 1 ∧ coverNumber hypergraph = rank ∧ + (rank - 1) * matchingNumber hypergraph < coverNumber hypergraph + +theorem eventualOddFailures_and_infinite : + (∃ primeThreshold : ℕ, ∀ prime : ℕ, primeThreshold ≤ prime → + prime.Prime → prime % 3 = 2 → + ∃ degreeThreshold : ℕ, 3 ≤ degreeThreshold ∧ + ∀ degree : ℕ, degreeThreshold ≤ degree → Odd degree → + Specification.ExplicitFailureAt (prime ^ degree + 1)) ∧ + Set.Infinite {rank : ℕ | Specification.ExplicitFailureAt rank} := by + sorry + +end RyserOdd + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/RyserOddExtensions.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RyserOdd.eventualOddFailures_and_infinite` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/ryser-odd-extensions/solution/closure.txt b/tasks/ryser-odd-extensions/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7a9fb743d66d028f6bcf989d194204fee949e90b --- /dev/null +++ b/tasks/ryser-odd-extensions/solution/closure.txt @@ -0,0 +1,219 @@ +OAI.Combinatorics.Ryser.Construction.ActualHypergraph +OAI.Combinatorics.Ryser.Construction.AmbientDeletionGeometry +OAI.Combinatorics.Ryser.Construction.AmbientDeletionNumerics +OAI.Combinatorics.Ryser.Construction.AmbientDeletionPoolLaw +OAI.Combinatorics.Ryser.Construction.AmbientDeletionProcess +OAI.Combinatorics.Ryser.Construction.AmbientDeletionShapes +OAI.Combinatorics.Ryser.Construction.AmbientDeletionSurvivors +OAI.Combinatorics.Ryser.Construction.AmbientDeletionTrials +OAI.Combinatorics.Ryser.Construction.AmbientPoolExistence +OAI.Combinatorics.Ryser.Construction.CoordinateCompatibility +OAI.Combinatorics.Ryser.Construction.CosetDirections +OAI.Combinatorics.Ryser.Construction.CosetIndex +OAI.Combinatorics.Ryser.Construction.CoverBudget +OAI.Combinatorics.Ryser.Construction.CoverCounting +OAI.Combinatorics.Ryser.Construction.CoverPencil +OAI.Combinatorics.Ryser.Construction.DeletionIntersection +OAI.Combinatorics.Ryser.Construction.DeletionLines +OAI.Combinatorics.Ryser.Construction.DeletionParallel +OAI.Combinatorics.Ryser.Construction.DeletionUnionBasic +OAI.Combinatorics.Ryser.Construction.DeletionUnionInside +OAI.Combinatorics.Ryser.Construction.DeletionUnionOutside +OAI.Combinatorics.Ryser.Construction.DeterministicCover +OAI.Combinatorics.Ryser.Construction.DirectionPlacement +OAI.Combinatorics.Ryser.Construction.DirectionSets +OAI.Combinatorics.Ryser.Construction.ExceptionalBudget +OAI.Combinatorics.Ryser.Construction.ExceptionalCover +OAI.Combinatorics.Ryser.Construction.ExtraDirections +OAI.Combinatorics.Ryser.Construction.FiniteInsideCover +OAI.Combinatorics.Ryser.Construction.FiniteOutsideAction +OAI.Combinatorics.Ryser.Construction.FiniteOutsideCover +OAI.Combinatorics.Ryser.Construction.FiniteSelectionCounting +OAI.Combinatorics.Ryser.Construction.GadgetAlgebra +OAI.Combinatorics.Ryser.Construction.GadgetConcentration +OAI.Combinatorics.Ryser.Construction.GadgetConsequences +OAI.Combinatorics.Ryser.Construction.GadgetCover +OAI.Combinatorics.Ryser.Construction.GadgetDefinitions +OAI.Combinatorics.Ryser.Construction.GadgetExistence +OAI.Combinatorics.Ryser.Construction.GadgetGood +OAI.Combinatorics.Ryser.Construction.GadgetOriginalCounts +OAI.Combinatorics.Ryser.Construction.GadgetOriginalDensity +OAI.Combinatorics.Ryser.Construction.GadgetOriginalExpectation +OAI.Combinatorics.Ryser.Construction.GadgetProcess +OAI.Combinatorics.Ryser.Construction.GadgetShapes +OAI.Combinatorics.Ryser.Construction.GroupBounds +OAI.Combinatorics.Ryser.Construction.GroupPlacement +OAI.Combinatorics.Ryser.Construction.GroupSelection +OAI.Combinatorics.Ryser.Construction.Hypergraph +OAI.Combinatorics.Ryser.Construction.InfiniteCover +OAI.Combinatorics.Ryser.Construction.Intersection +OAI.Combinatorics.Ryser.Construction.LabelAction +OAI.Combinatorics.Ryser.Construction.LinearPlacement +OAI.Combinatorics.Ryser.Construction.OddGadgets +OAI.Combinatorics.Ryser.Construction.OrdinaryCover +OAI.Combinatorics.Ryser.Construction.PlacedLines +OAI.Combinatorics.Ryser.Construction.PlacementIntersection +OAI.Combinatorics.Ryser.Construction.PoolThinAsymptotic +OAI.Combinatorics.Ryser.Construction.PoolThinGeometry +OAI.Combinatorics.Ryser.Construction.PoolThinProbability +OAI.Combinatorics.Ryser.Construction.PoolThinSelection +OAI.Combinatorics.Ryser.Construction.SelectedHypergraph +OAI.Combinatorics.Ryser.Construction.SmallPrimes +OAI.Combinatorics.Ryser.Domination.Append +OAI.Combinatorics.Ryser.Domination.Basic +OAI.Combinatorics.Ryser.Domination.Counting +OAI.Combinatorics.Ryser.Domination.Exchange +OAI.Combinatorics.Ryser.Domination.Extension +OAI.Combinatorics.Ryser.Domination.Main +OAI.Combinatorics.Ryser.Domination.Nonempty +OAI.Combinatorics.Ryser.Domination.Seed +OAI.Combinatorics.Ryser.Domination.TraceDefinitions +OAI.Combinatorics.Ryser.Field.Extension +OAI.Combinatorics.Ryser.Field.ExtensionSubfields +OAI.Combinatorics.Ryser.Field.OddSubfields +OAI.Combinatorics.Ryser.Field.SubfieldBound +OAI.Combinatorics.Ryser.Geometry.AffineJoins +OAI.Combinatorics.Ryser.Geometry.Basic +OAI.Combinatorics.Ryser.Geometry.Cardinality +OAI.Combinatorics.Ryser.Geometry.Normalization +OAI.Combinatorics.Ryser.Geometry.ProjectionMoments +OAI.Combinatorics.Ryser.Geometry.ProjectionPair +OAI.Combinatorics.Ryser.Geometry.ProjectiveJoins +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformAffine +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformBasic +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformXY +OAI.Combinatorics.Ryser.Geometry.ProjectiveTransformXZ +OAI.Combinatorics.Ryser.Geometry.SliceEnergy +OAI.Combinatorics.Ryser.Hypergraph.Cover +OAI.Combinatorics.Ryser.Hypergraph.Definitions +OAI.Combinatorics.Ryser.Hypergraph.Infinitude +OAI.Combinatorics.Ryser.Hypergraph.Matching +OAI.Combinatorics.Ryser.Hypergraph.Partite +OAI.Combinatorics.Ryser.Incidence.AllLineCap +OAI.Combinatorics.Ryser.Incidence.CoordinateTransfer +OAI.Combinatorics.Ryser.Incidence.CoordinateTransferSet +OAI.Combinatorics.Ryser.Incidence.DegreeSquares +OAI.Combinatorics.Ryser.Incidence.DenseNeighborhood +OAI.Combinatorics.Ryser.Incidence.ExtractedContradiction +OAI.Combinatorics.Ryser.Incidence.FiniteSetCovering +OAI.Combinatorics.Ryser.Incidence.FiniteSetEstimates +OAI.Combinatorics.Ryser.Incidence.FiniteSets +OAI.Combinatorics.Ryser.Incidence.FourAnchors +OAI.Combinatorics.Ryser.Incidence.FourAnchorsCounting +OAI.Combinatorics.Ryser.Incidence.FourAnchorsGeometry +OAI.Combinatorics.Ryser.Incidence.FourAnchorsLocal +OAI.Combinatorics.Ryser.Incidence.FourAnchorsNumerics +OAI.Combinatorics.Ryser.Incidence.GraphParameters +OAI.Combinatorics.Ryser.Incidence.NoApproximateSubfield +OAI.Combinatorics.Ryser.Incidence.NoApproximateSubfieldNumerics +OAI.Combinatorics.Ryser.Incidence.Parameters +OAI.Combinatorics.Ryser.Incidence.Pencils +OAI.Combinatorics.Ryser.Incidence.PopularOverlap +OAI.Combinatorics.Ryser.Incidence.PopularScalars +OAI.Combinatorics.Ryser.Incidence.PrunedContradiction +OAI.Combinatorics.Ryser.Incidence.Pruning +OAI.Combinatorics.Ryser.Incidence.PruningCore +OAI.Combinatorics.Ryser.Incidence.PruningHigh +OAI.Combinatorics.Ryser.Incidence.PruningNumerics +OAI.Combinatorics.Ryser.Incidence.RatioSet +OAI.Combinatorics.Ryser.Incidence.ScalarCollisionCount +OAI.Combinatorics.Ryser.Incidence.ScalarCollisions +OAI.Combinatorics.Ryser.Incidence.ScalarCover +OAI.Combinatorics.Ryser.Incidence.ScalarCoverExpressions +OAI.Combinatorics.Ryser.Incidence.ScalarCoverGeometry +OAI.Combinatorics.Ryser.Incidence.Uniform +OAI.Combinatorics.Ryser.Incidence.WalkCounts +OAI.Combinatorics.Ryser.Incidence.WalkExpansion +OAI.Combinatorics.Ryser.Incidence.WalkExtraction +OAI.Combinatorics.Ryser.Incidence.WalkQuotients +OAI.Combinatorics.Ryser.Incidence.WalkTrimming +OAI.Combinatorics.Ryser.LineCover.CleanCover +OAI.Combinatorics.Ryser.LineCover.CountConcentration +OAI.Combinatorics.Ryser.LineCover.CountEvents +OAI.Combinatorics.Ryser.LineCover.CountTailNumerics +OAI.Combinatorics.Ryser.LineCover.CoverEstimates +OAI.Combinatorics.Ryser.LineCover.Definitions +OAI.Combinatorics.Ryser.LineCover.Deletion +OAI.Combinatorics.Ryser.LineCover.DeletionDefinitions +OAI.Combinatorics.Ryser.LineCover.DisjointPairs +OAI.Combinatorics.Ryser.LineCover.FailureNumerics +OAI.Combinatorics.Ryser.LineCover.FiniteFailureNumerics +OAI.Combinatorics.Ryser.LineCover.GoodCounts +OAI.Combinatorics.Ryser.LineCover.GoodTuples +OAI.Combinatorics.Ryser.LineCover.HeavyIncidence +OAI.Combinatorics.Ryser.LineCover.HighConcurrency +OAI.Combinatorics.Ryser.LineCover.HighDegeneracy +OAI.Combinatorics.Ryser.LineCover.HighIncidence +OAI.Combinatorics.Ryser.LineCover.HighOccupancy +OAI.Combinatorics.Ryser.LineCover.HighProbability +OAI.Combinatorics.Ryser.LineCover.HighSamples +OAI.Combinatorics.Ryser.LineCover.InjectionSampling +OAI.Combinatorics.Ryser.LineCover.LowConcurrency +OAI.Combinatorics.Ryser.LineCover.LowDegeneracy +OAI.Combinatorics.Ryser.LineCover.LowOccupancy +OAI.Combinatorics.Ryser.LineCover.Main +OAI.Combinatorics.Ryser.LineCover.MaxConcurrency +OAI.Combinatorics.Ryser.LineCover.MeanCounts +OAI.Combinatorics.Ryser.LineCover.Overlap +OAI.Combinatorics.Ryser.LineCover.PairCounting +OAI.Combinatorics.Ryser.LineCover.PairSampling +OAI.Combinatorics.Ryser.LineCover.Process +OAI.Combinatorics.Ryser.LineCover.ProjectiveLift +OAI.Combinatorics.Ryser.LineCover.Rigidity +OAI.Combinatorics.Ryser.LineCover.RigidityNumerics +OAI.Combinatorics.Ryser.LineCover.RigidityParameters +OAI.Combinatorics.Ryser.LineCover.RigiditySampling +OAI.Combinatorics.Ryser.LineCover.SamplingDefinitions +OAI.Combinatorics.Ryser.LineCover.SamplingNumerics +OAI.Combinatorics.Ryser.LineCover.SurvivalNumerics +OAI.Combinatorics.Ryser.LineCover.SurvivorSampling +OAI.Combinatorics.Ryser.LineCover.TailNumerics +OAI.Combinatorics.Ryser.LineCover.TupleConcentration +OAI.Combinatorics.Ryser.LineCover.TupleGeometry +OAI.Combinatorics.Ryser.LineCover.TwoPopulationMoments +OAI.Combinatorics.Ryser.LineCover.TwoPopulationSampling +OAI.Combinatorics.Ryser.OddExtensions +OAI.Combinatorics.Ryser.Probability.Concentration +OAI.Combinatorics.Ryser.Probability.Exponential +OAI.Combinatorics.Ryser.Probability.Exposure +OAI.Combinatorics.Ryser.Probability.Finite +OAI.Combinatorics.Ryser.Probability.Product +OAI.Combinatorics.Ryser.Probability.ProductMap +OAI.Combinatorics.Ryser.Probability.RareAnchor +OAI.Combinatorics.Ryser.Probability.Variance +OAI.Combinatorics.Ryser.Selection.AnalyticalLimits +OAI.Combinatorics.Ryser.Selection.CertificateBounds +OAI.Combinatorics.Ryser.Selection.CertificateCount +OAI.Combinatorics.Ryser.Selection.CertificateUnion +OAI.Combinatorics.Ryser.Selection.Chunk +OAI.Combinatorics.Ryser.Selection.ChunkConditioning +OAI.Combinatorics.Ryser.Selection.ChunkDensity +OAI.Combinatorics.Ryser.Selection.ChunkEnergy +OAI.Combinatorics.Ryser.Selection.ChunkLoss +OAI.Combinatorics.Ryser.Selection.ChunkPartition +OAI.Combinatorics.Ryser.Selection.ChunkPartitionBounds +OAI.Combinatorics.Ryser.Selection.ChunkTail +OAI.Combinatorics.Ryser.Selection.ChunkTailAsymptotics +OAI.Combinatorics.Ryser.Selection.Definitions +OAI.Combinatorics.Ryser.Selection.DensityConstants +OAI.Combinatorics.Ryser.Selection.Estimates +OAI.Combinatorics.Ryser.Selection.FeasibleDensity +OAI.Combinatorics.Ryser.Selection.Forbidden +OAI.Combinatorics.Ryser.Selection.IndependentTail +OAI.Combinatorics.Ryser.Selection.KChoice +OAI.Combinatorics.Ryser.Selection.LargeCertificates +OAI.Combinatorics.Ryser.Selection.LayerBounds +OAI.Combinatorics.Ryser.Selection.LayerNormalization +OAI.Combinatorics.Ryser.Selection.Main +OAI.Combinatorics.Ryser.Selection.NumericLimits +OAI.Combinatorics.Ryser.Selection.Parameters +OAI.Combinatorics.Ryser.Selection.PoolCounts +OAI.Combinatorics.Ryser.Selection.PoolGraph +OAI.Combinatorics.Ryser.Selection.PoolLaw +OAI.Combinatorics.Ryser.Selection.Quantitative +OAI.Combinatorics.Ryser.Selection.RegularTail +OAI.Combinatorics.Ryser.Selection.SmallCertificates +OAI.Combinatorics.Ryser.Selection.SmallRange +OAI.Combinatorics.Ryser.Selection.SmallSum +OAI.Combinatorics.Ryser.Selection.UniformDensity +OAI.Combinatorics.Ryser.Selection.UnusedProduct diff --git a/tasks/ryser-odd-extensions/solution/reference.py b/tasks/ryser-odd-extensions/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/ryser-odd-extensions/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/ryser-odd-extensions/solution/solve.sh b/tasks/ryser-odd-extensions/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fb7407886c3a55c67440c30b6f6e9c830c3e0bea --- /dev/null +++ b/tasks/ryser-odd-extensions/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of RyserOddExtensions, i.e. module OAI.Combinatorics.Ryser.OddExtensions and the +# 219 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Ryser.OddExtensions /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of RyserOddExtensions" diff --git a/tasks/ryser-odd-extensions/task.toml b/tasks/ryser-odd-extensions/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..60d95c8c1ef6e083d1e07a2898224fbe75d06054 --- /dev/null +++ b/tasks/ryser-odd-extensions/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/ryser-odd-extensions" +version = "1.0.0" +description = "Prove RyserOddExtensions (openai/math family 162: Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/RyserOddExtensions.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "RyserOddExtensions" +family = "162" +family_title = "Counterexamples to Ryser's covering and Gyarfas's tree-cover conjectures" +subject = "Combinatorics" +theorems = ["OAI.RyserOdd.eventualOddFailures_and_infinite"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Ryser.OddExtensions" +reference_modules = 219 +reference_lean_bytes = 1140439 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 649 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12726 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/ryser-odd-extensions/tests/Challenge.lean b/tasks/ryser-odd-extensions/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e41426a80f37da6ba537f7d9090a6ac467c99b97 --- /dev/null +++ b/tasks/ryser-odd-extensions/tests/Challenge.lean @@ -0,0 +1,74 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace RyserCoveringCounterexample + +abbrev Hypergraph (Vertex : Type*) := Finset (Finset Vertex) + +variable {Vertex : Type*} [DecidableEq Vertex] + +def IsCover (hypergraph : Hypergraph Vertex) (cover : Finset Vertex) : Prop := + ∀ edge ∈ hypergraph, ∃ vertex ∈ cover, vertex ∈ edge + +def Intersecting (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, ∀ other ∈ hypergraph, edge ≠ other → (edge ∩ other).Nonempty + +attribute [-instance] instDecidablePairwiseCoeFinsetOfDecidableEqOfDecidableRel in +def matchings (hypergraph : Hypergraph Vertex) : Finset (Hypergraph Vertex) := by + classical + exact hypergraph.powerset.filter fun matching => + (matching : Set (Finset Vertex)).Pairwise Disjoint + +def matchingNumber (hypergraph : Hypergraph Vertex) : ℕ := + (matchings hypergraph).sup Finset.card + +def coverCardinalities (hypergraph : Hypergraph Vertex) : Set ℕ := + {size | ∃ cover : Finset Vertex, IsCover hypergraph cover ∧ cover.card = size} + +def coverNumber (hypergraph : Hypergraph Vertex) : ℕ := sInf (coverCardinalities hypergraph) + +def Uniform (rank : ℕ) (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, edge.card = rank + +def PartiteUniform {Index : Type*} (part : Vertex → Index) + (hypergraph : Hypergraph Vertex) : Prop := + ∀ edge ∈ hypergraph, ∀ index : Index, + ∃! vertex : Vertex, vertex ∈ edge ∧ part vertex = index + +def RPartiteUniform (rank : ℕ) (hypergraph : Hypergraph Vertex) : Prop := + ∃ part : Vertex → Fin rank, PartiteUniform part hypergraph + +end RyserCoveringCounterexample + +namespace RyserOdd + +open RyserCoveringCounterexample + +def Specification.ExplicitFailureAt (rank : ℕ) : Prop := + ∃ (Vertex : Type) (finiteVertices : Fintype Vertex) (decidableVertices : DecidableEq Vertex), + letI : Fintype Vertex := finiteVertices + letI : DecidableEq Vertex := decidableVertices + ∃ hypergraph : RyserCoveringCounterexample.Hypergraph Vertex, + 0 < rank ∧ hypergraph.Nonempty ∧ RPartiteUniform rank hypergraph ∧ + Uniform rank hypergraph ∧ Intersecting hypergraph ∧ + (∃ cover : Finset Vertex, IsCover hypergraph cover) ∧ + matchingNumber hypergraph = 1 ∧ coverNumber hypergraph = rank ∧ + (rank - 1) * matchingNumber hypergraph < coverNumber hypergraph + +theorem eventualOddFailures_and_infinite : + (∃ primeThreshold : ℕ, ∀ prime : ℕ, primeThreshold ≤ prime → + prime.Prime → prime % 3 = 2 → + ∃ degreeThreshold : ℕ, 3 ≤ degreeThreshold ∧ + ∀ degree : ℕ, degreeThreshold ≤ degree → Odd degree → + Specification.ExplicitFailureAt (prime ^ degree + 1)) ∧ + Set.Infinite {rank : ℕ | Specification.ExplicitFailureAt rank} := by + sorry + +end RyserOdd + +end + +end OAI diff --git a/tasks/ryser-odd-extensions/tests/grade.py b/tasks/ryser-odd-extensions/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/ryser-odd-extensions/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/ryser-odd-extensions/tests/task.json b/tasks/ryser-odd-extensions/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6b26f442ae63401a965f943f002441c12f6a2134 --- /dev/null +++ b/tasks/ryser-odd-extensions/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "RyserOddExtensions", + "comparator": { + "theorem_names": [ + "OAI.RyserOdd.eventualOddFailures_and_infinite" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11826 +} \ No newline at end of file diff --git a/tasks/ryser-odd-extensions/tests/test.sh b/tasks/ryser-odd-extensions/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/ryser-odd-extensions/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sat-sharpness/environment/Dockerfile b/tasks/sat-sharpness/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sat-sharpness/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sat-sharpness/environment/fetch_mathlib.sh b/tasks/sat-sharpness/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sat-sharpness/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sat-sharpness/environment/lake-manifest.json b/tasks/sat-sharpness/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sat-sharpness/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sat-sharpness/environment/lakefile.lean b/tasks/sat-sharpness/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sat-sharpness/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sat-sharpness/environment/lean_setup.sh b/tasks/sat-sharpness/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sat-sharpness/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sat-sharpness/environment/pack_submission.py b/tasks/sat-sharpness/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sat-sharpness/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sat-sharpness/instruction.md b/tasks/sat-sharpness/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cd7af7648e64b8b38c2ec9e0302e0047e6bbf2b8 --- /dev/null +++ b/tasks/sat-sharpness/instruction.md @@ -0,0 +1,129 @@ +# openai/math challenge `SATSharpness` (family 235) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 235 of the release, *Random-SAT thresholds, sharp variance and computability* +(Probability and statistical mechanics). The family as a whole: For random $k$-SAT with independent uniformly signed proper clauses sampled with replacement, proves finite positive limiting thresholds and hitting-time variance $\Theta_k(n)$ for every fixed $k\ge3$, and computability of the 3-SAT threshold. We credit Gaia Carenini with priority for resolving the threshold-existence conjecture in her concurrent \href{https://eccc.weizmann.ac.il/report/2026/229/}{ECCC TR26-229}, made public October 5, 2026; this family supplies another proof and the sharper variance and computability results. + +The challenge is `SATSharpness`, also at `/opt/openai-math/challenges/SATSharpness.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory + +namespace RandomKSAT + +open scoped Classical ENNReal + +abbrev Assignment (n : ℕ) := Fin n → Bool + +def Clause (n k : ℕ) := + (s : {s : Finset (Fin n) // s.card = k}) × (s.1 → Bool) + +instance clauseFintype (n k : ℕ) : Fintype (Clause n k) := by + classical + unfold Clause + infer_instance + +instance clauseMeasurableSpace (n k : ℕ) : MeasurableSpace (Clause n k) := ⊤ + +instance clauseMeasurableSingletonClass (n k : ℕ) : + MeasurableSingletonClass (Clause n k) := ⟨fun _ => trivial⟩ + +def Satisfies {n k : ℕ} (c : Clause n k) (a : Assignment n) : Prop := + ∃ v : c.1.1, a v = c.2 v + +abbrev Stream (n k : ℕ) := ℕ → Clause n k + +def clauseLaw (n k : ℕ) : Measure (Clause n k) := uniformOn Set.univ + +def streamLaw (n k : ℕ) : Measure (Stream n k) := + Measure.infinitePi (fun _ : ℕ => clauseLaw n k) + +def SetSAT {u s : ℕ} (S : Finset (Assignment u)) (ω : Stream u s) (g : ℕ) : Prop := + ∃ a ∈ S, ∀ i < g, Satisfies (ω i) a + +def blockKill (u s : ℕ) (S : Finset (Assignment u)) (g : ℕ) : ℝ := + (streamLaw u s {ω | ¬ SetSAT S ω g}).toReal + +def favg.{u_1} {α : Type u_1} [Fintype α] (f : α → ℝ) : ℝ := + (∑ a, f a) / Fintype.card α + +def clauseStep (u s : ℕ) (f : Finset (Assignment u) → ℝ) + (S : Finset (Assignment u)) : ℝ := + favg fun c : Clause u s => f (S.filter (Satisfies c)) + +def alive (u : ℕ) (S : Finset (Assignment u)) : ℝ := if S.Nonempty then 1 else 0 + +def survival (u s : ℕ) (S : Finset (Assignment u)) (m : ℕ) : ℝ := + (clauseStep u s)^[m] (alive u) S + +def lifetime (u s : ℕ) (S : Finset (Assignment u)) : ℝ := ∑' m, survival u s S m + +theorem sharpness (k : ℕ) (hk : 3 ≤ k) : + (∀ γ D A : ℝ, γ < (k : ℝ) / ((k-1 : ℕ) : ℝ) → 0 < D → 0 < A → + ∀ N : ℕ, ∃ u : ℕ, N ≤ u ∧ k ≤ u ∧ ∃ S : Finset (Assignment u), + S.Nonempty ∧ A * (u : ℝ) ^ (-((k-1 : ℕ) : ℝ)) ≤ blockKill u (k-1) S 1 ∧ + D * (blockKill u (k-1) S 1) ^ (-γ) < lifetime u k S) ∧ + (∃ u : ℕ → ℕ, ∃ S : ∀ g, Finset (Assignment (u g)), + (∀ g, 2 ≤ g → k ≤ u g ∧ (S g).Nonempty) ∧ + Asymptotics.IsEquivalent Filter.atTop + (fun g => blockKill (u g) (k-1) (S g) 1 - blockKill (u g) k (S g) g) + (fun g => ((2 : ℝ)^k)⁻¹ * (g : ℝ)^(-((k-1 : ℕ) : ℝ)))) ∧ + (¬ ∃ e : ℕ → ℝ, + Asymptotics.IsLittleO Filter.atTop e (fun g => (g : ℝ)^(-((k-1 : ℕ) : ℝ))) ∧ + ∀ u, k ≤ u → ∀ S : Finset (Assignment u), S.Nonempty → ∀ g, 2 ≤ g → + blockKill u (k-1) S 1 - e g ≤ blockKill u k S g) := by + sorry + +end RandomKSAT + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SATSharpness.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RandomKSAT.sharpness` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sat-sharpness/solution/closure.txt b/tasks/sat-sharpness/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0816cea1160085b0078946ebb6ff5a6e27578090 --- /dev/null +++ b/tasks/sat-sharpness/solution/closure.txt @@ -0,0 +1,26 @@ +OAI.Probability.SATVariance.BlockKilling +OAI.Probability.SATVariance.CapBridge +OAI.Probability.SATVariance.CappedUpper +OAI.Probability.SATVariance.ClauseCombinatorics +OAI.Probability.SATVariance.CountMoments +OAI.Probability.SATVariance.FiberRefresh +OAI.Probability.SATVariance.FiniteVariance +OAI.Probability.SATVariance.FirstFailure +OAI.Probability.SATVariance.FrozenReplacement +OAI.Probability.SATVariance.HallSatisfiability +OAI.Probability.SATVariance.HiddenTests +OAI.Probability.SATVariance.LifetimePotential +OAI.Probability.SATVariance.LifetimeSharpness +OAI.Probability.SATVariance.MarkovReplacement +OAI.Probability.SATVariance.Model +OAI.Probability.SATVariance.Moments +OAI.Probability.SATVariance.OccupationBounds +OAI.Probability.SATVariance.OmissionCompression +OAI.Probability.SATVariance.PairEvolution +OAI.Probability.SATVariance.ReplacementSharpness +OAI.Probability.SATVariance.RootDisintegration +OAI.Probability.SATVariance.Sharpness +OAI.Probability.SATVariance.SharpnessEstimates +OAI.Probability.SATVariance.Subcube +OAI.Probability.SATVariance.SupportProbabilities +OAI.Probability.SATVariance.WeightedRewards diff --git a/tasks/sat-sharpness/solution/reference.py b/tasks/sat-sharpness/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sat-sharpness/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sat-sharpness/solution/solve.sh b/tasks/sat-sharpness/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..34cef6e0f5370ab4c29c1de6cacf364a13b29a88 --- /dev/null +++ b/tasks/sat-sharpness/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SATSharpness, i.e. module OAI.Probability.SATVariance.Sharpness and the +# 26 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SATVariance.Sharpness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SATSharpness" diff --git a/tasks/sat-sharpness/task.toml b/tasks/sat-sharpness/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5032dd2678a84e050d1276ce32cc8db1fb924a11 --- /dev/null +++ b/tasks/sat-sharpness/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sat-sharpness" +version = "1.0.0" +description = "Prove SATSharpness (openai/math family 235: Random-SAT thresholds, sharp variance and computability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SATSharpness.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SATSharpness" +family = "235" +family_title = "Random-SAT thresholds, sharp variance and computability" +subject = "Probability and statistical mechanics" +theorems = ["OAI.RandomKSAT.sharpness"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SATVariance.Sharpness" +reference_modules = 26 +reference_lean_bytes = 237426 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 561 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11913 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sat-sharpness/tests/Challenge.lean b/tasks/sat-sharpness/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..31c865b89d5fee2f3b1e8efcbd4f4c95f8162304 --- /dev/null +++ b/tasks/sat-sharpness/tests/Challenge.lean @@ -0,0 +1,78 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory + +namespace RandomKSAT + +open scoped Classical ENNReal + +abbrev Assignment (n : ℕ) := Fin n → Bool + +def Clause (n k : ℕ) := + (s : {s : Finset (Fin n) // s.card = k}) × (s.1 → Bool) + +instance clauseFintype (n k : ℕ) : Fintype (Clause n k) := by + classical + unfold Clause + infer_instance + +instance clauseMeasurableSpace (n k : ℕ) : MeasurableSpace (Clause n k) := ⊤ + +instance clauseMeasurableSingletonClass (n k : ℕ) : + MeasurableSingletonClass (Clause n k) := ⟨fun _ => trivial⟩ + +def Satisfies {n k : ℕ} (c : Clause n k) (a : Assignment n) : Prop := + ∃ v : c.1.1, a v = c.2 v + +abbrev Stream (n k : ℕ) := ℕ → Clause n k + +def clauseLaw (n k : ℕ) : Measure (Clause n k) := uniformOn Set.univ + +def streamLaw (n k : ℕ) : Measure (Stream n k) := + Measure.infinitePi (fun _ : ℕ => clauseLaw n k) + +def SetSAT {u s : ℕ} (S : Finset (Assignment u)) (ω : Stream u s) (g : ℕ) : Prop := + ∃ a ∈ S, ∀ i < g, Satisfies (ω i) a + +def blockKill (u s : ℕ) (S : Finset (Assignment u)) (g : ℕ) : ℝ := + (streamLaw u s {ω | ¬ SetSAT S ω g}).toReal + +def favg.{u_1} {α : Type u_1} [Fintype α] (f : α → ℝ) : ℝ := + (∑ a, f a) / Fintype.card α + +def clauseStep (u s : ℕ) (f : Finset (Assignment u) → ℝ) + (S : Finset (Assignment u)) : ℝ := + favg fun c : Clause u s => f (S.filter (Satisfies c)) + +def alive (u : ℕ) (S : Finset (Assignment u)) : ℝ := if S.Nonempty then 1 else 0 + +def survival (u s : ℕ) (S : Finset (Assignment u)) (m : ℕ) : ℝ := + (clauseStep u s)^[m] (alive u) S + +def lifetime (u s : ℕ) (S : Finset (Assignment u)) : ℝ := ∑' m, survival u s S m + +theorem sharpness (k : ℕ) (hk : 3 ≤ k) : + (∀ γ D A : ℝ, γ < (k : ℝ) / ((k-1 : ℕ) : ℝ) → 0 < D → 0 < A → + ∀ N : ℕ, ∃ u : ℕ, N ≤ u ∧ k ≤ u ∧ ∃ S : Finset (Assignment u), + S.Nonempty ∧ A * (u : ℝ) ^ (-((k-1 : ℕ) : ℝ)) ≤ blockKill u (k-1) S 1 ∧ + D * (blockKill u (k-1) S 1) ^ (-γ) < lifetime u k S) ∧ + (∃ u : ℕ → ℕ, ∃ S : ∀ g, Finset (Assignment (u g)), + (∀ g, 2 ≤ g → k ≤ u g ∧ (S g).Nonempty) ∧ + Asymptotics.IsEquivalent Filter.atTop + (fun g => blockKill (u g) (k-1) (S g) 1 - blockKill (u g) k (S g) g) + (fun g => ((2 : ℝ)^k)⁻¹ * (g : ℝ)^(-((k-1 : ℕ) : ℝ)))) ∧ + (¬ ∃ e : ℕ → ℝ, + Asymptotics.IsLittleO Filter.atTop e (fun g => (g : ℝ)^(-((k-1 : ℕ) : ℝ))) ∧ + ∀ u, k ≤ u → ∀ S : Finset (Assignment u), S.Nonempty → ∀ g, 2 ≤ g → + blockKill u (k-1) S 1 - e g ≤ blockKill u k S g) := by + sorry + +end RandomKSAT + +end + +end OAI diff --git a/tasks/sat-sharpness/tests/grade.py b/tasks/sat-sharpness/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sat-sharpness/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sat-sharpness/tests/task.json b/tasks/sat-sharpness/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e66c9ba1452c60fca2292063715f8bfdf9b0ad0f --- /dev/null +++ b/tasks/sat-sharpness/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SATSharpness", + "comparator": { + "theorem_names": [ + "OAI.RandomKSAT.sharpness" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11013 +} \ No newline at end of file diff --git a/tasks/sat-sharpness/tests/test.sh b/tasks/sat-sharpness/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sat-sharpness/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sat-variance/environment/Dockerfile b/tasks/sat-variance/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sat-variance/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sat-variance/environment/fetch_mathlib.sh b/tasks/sat-variance/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sat-variance/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sat-variance/environment/lake-manifest.json b/tasks/sat-variance/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sat-variance/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sat-variance/environment/lakefile.lean b/tasks/sat-variance/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sat-variance/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sat-variance/environment/lean_setup.sh b/tasks/sat-variance/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sat-variance/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sat-variance/environment/pack_submission.py b/tasks/sat-variance/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sat-variance/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sat-variance/instruction.md b/tasks/sat-variance/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..93dbeaa3e97511e055fb2d23257361f68fdf7854 --- /dev/null +++ b/tasks/sat-variance/instruction.md @@ -0,0 +1,121 @@ +# openai/math challenge `SATVariance` (family 235) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 235 of the release, *Random-SAT thresholds, sharp variance and computability* +(Probability and statistical mechanics). The family as a whole: For random $k$-SAT with independent uniformly signed proper clauses sampled with replacement, proves finite positive limiting thresholds and hitting-time variance $\Theta_k(n)$ for every fixed $k\ge3$, and computability of the 3-SAT threshold. We credit Gaia Carenini with priority for resolving the threshold-existence conjecture in her concurrent \href{https://eccc.weizmann.ac.il/report/2026/229/}{ECCC TR26-229}, made public October 5, 2026; this family supplies another proof and the sharper variance and computability results. + +The challenge is `SATVariance`, also at `/opt/openai-math/challenges/SATVariance.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory + +namespace RandomKSAT + +abbrev Assignment (n : ℕ) := Fin n → Bool + +def Clause (n k : ℕ) := + (s : {s : Finset (Fin n) // s.card = k}) × (s.1 → Bool) + +instance clauseFintype (n k : ℕ) : Fintype (Clause n k) := by + classical + unfold Clause + infer_instance + +instance clauseMeasurableSpace (n k : ℕ) : MeasurableSpace (Clause n k) := ⊤ + +instance clauseMeasurableSingletonClass (n k : ℕ) : + MeasurableSingletonClass (Clause n k) := ⟨fun _ => trivial⟩ + +def Satisfies {n k : ℕ} (c : Clause n k) (a : Assignment n) : Prop := + ∃ v : c.1.1, a v = c.2 v + +abbrev Stream (n k : ℕ) := ℕ → Clause n k + +def clauseLaw (n k : ℕ) : Measure (Clause n k) := uniformOn Set.univ + +def streamLaw (n k : ℕ) : Measure (Stream n k) := + Measure.infinitePi (fun _ : ℕ => clauseLaw n k) + +def PrefixSAT {n k : ℕ} (ω : Stream n k) (m : ℕ) : Prop := + ∃ a : Assignment n, ∀ i < m, Satisfies (ω i) a + +def firstFailure {n k : ℕ} (ω : Stream n k) : ℕ∞ := + sInf ((fun m : ℕ => (m : ℕ∞)) '' {m | ¬ PrefixSAT ω m}) + +def H {n k : ℕ} (ω : Stream n k) : ℝ := (firstFailure ω).toNat + +def cap (n : ℕ) (B : ℝ) : ℕ := ⌊B * n⌋₊ + +def T {n k : ℕ} (B : ℝ) (ω : Stream n k) : ℝ := + (min (firstFailure ω) (cap n B : ℕ∞)).toNat + +def ell (k n : ℕ) : ℝ := + if k = 3 then Real.log (Real.exp 1 * n) else 1 + +def U (k : ℕ) : ℝ := Real.log 2 / (-Real.log (1 - ((2 : ℝ) ^ k)⁻¹)) + +theorem variance_main (k : ℕ) (hk : 3 ≤ k) : + (∃ C : ℝ, 0 ≤ C ∧ ∀ n : ℕ, k ≤ n → + variance (H : Stream n k → ℝ) (streamLaw n k) ≤ C * n * ell k n) ∧ + (∀ B : ℝ, 0 < B → ∃ C : ℝ, 0 ≤ C ∧ ∀ n : ℕ, k ≤ n → + variance (T B : Stream n k → ℝ) (streamLaw n k) ≤ C * n * ell k n) ∧ + (∃ c : ℝ, 0 < c ∧ + (∃ N : ℕ, ∀ n : ℕ, N ≤ n → k ≤ n → + c * n ≤ variance (H : Stream n k → ℝ) (streamLaw n k)) ∧ + (∀ B : ℝ, U k < B → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → k ≤ n → + c * n ≤ variance (T B : Stream n k → ℝ) (streamLaw n k))) := by + sorry + +end RandomKSAT + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SATVariance.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RandomKSAT.variance_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sat-variance/solution/closure.txt b/tasks/sat-variance/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d11869a3c7c16afb36e55438634f9dce1f182863 --- /dev/null +++ b/tasks/sat-variance/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.Probability.SATVariance.BlockKilling +OAI.Probability.SATVariance.BystanderStops +OAI.Probability.SATVariance.BystanderVariance +OAI.Probability.SATVariance.CapBridge +OAI.Probability.SATVariance.CappedUpper +OAI.Probability.SATVariance.ClauseCombinatorics +OAI.Probability.SATVariance.CountMoments +OAI.Probability.SATVariance.FailureWindows +OAI.Probability.SATVariance.FiberRefresh +OAI.Probability.SATVariance.FiniteVariance +OAI.Probability.SATVariance.FirstFailure +OAI.Probability.SATVariance.FrozenReplacement +OAI.Probability.SATVariance.HallSatisfiability +OAI.Probability.SATVariance.HiddenTests +OAI.Probability.SATVariance.InsertionVariance +OAI.Probability.SATVariance.IsolatedSupports +OAI.Probability.SATVariance.LifetimePotential +OAI.Probability.SATVariance.LifetimeSharpness +OAI.Probability.SATVariance.LinearLower +OAI.Probability.SATVariance.Main +OAI.Probability.SATVariance.MarkovReplacement +OAI.Probability.SATVariance.Model +OAI.Probability.SATVariance.Moments +OAI.Probability.SATVariance.OccupationBounds +OAI.Probability.SATVariance.OmissionCompression +OAI.Probability.SATVariance.PairEvolution +OAI.Probability.SATVariance.ReplacementSharpness +OAI.Probability.SATVariance.RootDisintegration +OAI.Probability.SATVariance.SentinelBridge +OAI.Probability.SATVariance.Sharpness +OAI.Probability.SATVariance.SharpnessEstimates +OAI.Probability.SATVariance.ShuffleAverages +OAI.Probability.SATVariance.Subcube +OAI.Probability.SATVariance.SupportProbabilities +OAI.Probability.SATVariance.WeightedRewards diff --git a/tasks/sat-variance/solution/reference.py b/tasks/sat-variance/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sat-variance/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sat-variance/solution/solve.sh b/tasks/sat-variance/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8902617b57ab9bbdc9964cada89a582fd8553fac --- /dev/null +++ b/tasks/sat-variance/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SATVariance, i.e. module OAI.Probability.SATVariance.Main and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SATVariance.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SATVariance" diff --git a/tasks/sat-variance/task.toml b/tasks/sat-variance/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7e93c16d19da5937857710bff98099fb298abe04 --- /dev/null +++ b/tasks/sat-variance/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sat-variance" +version = "1.0.0" +description = "Prove SATVariance (openai/math family 235: Random-SAT thresholds, sharp variance and computability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SATVariance.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SATVariance" +family = "235" +family_title = "Random-SAT thresholds, sharp variance and computability" +subject = "Probability and statistical mechanics" +theorems = ["OAI.RandomKSAT.variance_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SATVariance.Main" +reference_modules = 35 +reference_lean_bytes = 299818 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 700 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11969 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sat-variance/tests/Challenge.lean b/tasks/sat-variance/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5ecf51d98833741230b4421bf7e7ffa47ba45d44 --- /dev/null +++ b/tasks/sat-variance/tests/Challenge.lean @@ -0,0 +1,70 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory ProbabilityTheory + +namespace RandomKSAT + +abbrev Assignment (n : ℕ) := Fin n → Bool + +def Clause (n k : ℕ) := + (s : {s : Finset (Fin n) // s.card = k}) × (s.1 → Bool) + +instance clauseFintype (n k : ℕ) : Fintype (Clause n k) := by + classical + unfold Clause + infer_instance + +instance clauseMeasurableSpace (n k : ℕ) : MeasurableSpace (Clause n k) := ⊤ + +instance clauseMeasurableSingletonClass (n k : ℕ) : + MeasurableSingletonClass (Clause n k) := ⟨fun _ => trivial⟩ + +def Satisfies {n k : ℕ} (c : Clause n k) (a : Assignment n) : Prop := + ∃ v : c.1.1, a v = c.2 v + +abbrev Stream (n k : ℕ) := ℕ → Clause n k + +def clauseLaw (n k : ℕ) : Measure (Clause n k) := uniformOn Set.univ + +def streamLaw (n k : ℕ) : Measure (Stream n k) := + Measure.infinitePi (fun _ : ℕ => clauseLaw n k) + +def PrefixSAT {n k : ℕ} (ω : Stream n k) (m : ℕ) : Prop := + ∃ a : Assignment n, ∀ i < m, Satisfies (ω i) a + +def firstFailure {n k : ℕ} (ω : Stream n k) : ℕ∞ := + sInf ((fun m : ℕ => (m : ℕ∞)) '' {m | ¬ PrefixSAT ω m}) + +def H {n k : ℕ} (ω : Stream n k) : ℝ := (firstFailure ω).toNat + +def cap (n : ℕ) (B : ℝ) : ℕ := ⌊B * n⌋₊ + +def T {n k : ℕ} (B : ℝ) (ω : Stream n k) : ℝ := + (min (firstFailure ω) (cap n B : ℕ∞)).toNat + +def ell (k n : ℕ) : ℝ := + if k = 3 then Real.log (Real.exp 1 * n) else 1 + +def U (k : ℕ) : ℝ := Real.log 2 / (-Real.log (1 - ((2 : ℝ) ^ k)⁻¹)) + +theorem variance_main (k : ℕ) (hk : 3 ≤ k) : + (∃ C : ℝ, 0 ≤ C ∧ ∀ n : ℕ, k ≤ n → + variance (H : Stream n k → ℝ) (streamLaw n k) ≤ C * n * ell k n) ∧ + (∀ B : ℝ, 0 < B → ∃ C : ℝ, 0 ≤ C ∧ ∀ n : ℕ, k ≤ n → + variance (T B : Stream n k → ℝ) (streamLaw n k) ≤ C * n * ell k n) ∧ + (∃ c : ℝ, 0 < c ∧ + (∃ N : ℕ, ∀ n : ℕ, N ≤ n → k ≤ n → + c * n ≤ variance (H : Stream n k → ℝ) (streamLaw n k)) ∧ + (∀ B : ℝ, U k < B → ∃ N : ℕ, ∀ n : ℕ, N ≤ n → k ≤ n → + c * n ≤ variance (T B : Stream n k → ℝ) (streamLaw n k))) := by + sorry + +end RandomKSAT + +end + +end OAI diff --git a/tasks/sat-variance/tests/grade.py b/tasks/sat-variance/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sat-variance/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sat-variance/tests/task.json b/tasks/sat-variance/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..17c9ddc0f8d7f5f269b1a00295523c176f7abee6 --- /dev/null +++ b/tasks/sat-variance/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SATVariance", + "comparator": { + "theorem_names": [ + "OAI.RandomKSAT.variance_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11069 +} \ No newline at end of file diff --git a/tasks/sat-variance/tests/test.sh b/tasks/sat-variance/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sat-variance/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/saxl/environment/Dockerfile b/tasks/saxl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/saxl/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/saxl/environment/fetch_mathlib.sh b/tasks/saxl/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/saxl/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/saxl/environment/lake-manifest.json b/tasks/saxl/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/saxl/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/saxl/environment/lakefile.lean b/tasks/saxl/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/saxl/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/saxl/environment/lean_setup.sh b/tasks/saxl/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/saxl/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/saxl/environment/pack_submission.py b/tasks/saxl/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/saxl/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/saxl/instruction.md b/tasks/saxl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fe4853e531c60f8c620f7b1f66dfbddd8e08a954 --- /dev/null +++ b/tasks/saxl/instruction.md @@ -0,0 +1,170 @@ +# openai/math challenge `Saxl` (family 205) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 205 of the release, *Saxl's conjecture and universal tensor squares* +(Algebra). The family as a whole: Proves Saxl's conjecture: the tensor square of every staircase representation contains every irreducible complex representation of the corresponding symmetric group. More generally, every $S_n$ with $n\notin\{2,4,9\}$ has an irreducible representation whose tensor square contains all irreducibles. + +The challenge is `Saxl`, also at `/opt/openai-math/challenges/Saxl.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped TensorProduct + +universe uG uV + +namespace Saxl + +/- Coefficients of position tensors on an alphabet of size `d`. -/ +abbrev WordSpace (n d : ℕ) := (Fin n → Fin d) → ℂ + +/- The position action satisfies `g e_a = e_(a ∘ g⁻¹)`. -/ +def wordRep (n d : ℕ) : Representation ℂ (Equiv.Perm (Fin n)) (WordSpace n d) where + toFun g := + { toFun := fun f a => f (a ∘ g) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext f a; rfl + map_mul' g h := by ext f a; rfl + +/- The cyclic subrepresentation generated by an actual vector. -/ +def cyclic {G : Type uG} {V : Type uV} [Group G] [AddCommGroup V] [Module ℂ V] + (ρ : Representation ℂ G V) (v : V) : Subrepresentation ρ where + toSubmodule := Submodule.span ℂ (Set.range fun g : G => ρ g v) + apply_mem_toSubmodule g := by + intro x hx + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨h, rfl⟩ := hx + apply Submodule.subset_span + exact ⟨g * h, by simp only [map_mul, Module.End.mul_apply]⟩ + | zero => simp + | add x y hx hy ihx ihy => + simpa only [map_add] using Submodule.add_mem _ ihx ihy + | smul a x hx ih => + simpa only [map_smul] using Submodule.smul_mem _ a ih + +/- A tableau is an enumeration of all cells by the position set. -/ +abbrev Tableau (n : ℕ) (μ : YoungDiagram) := Fin n ≃ μ.cells + +/- One fixed tableau; changing its enumeration gives an isomorphic Specht module. -/ +def canonicalTableau {n : ℕ} (μ : YoungDiagram) (hn : μ.card = n) : Tableau n μ := + (Fintype.equivFinOfCardEq (by simpa using hn)).symm + +/- The row word corresponding to the tabloid of a tableau. -/ +def rowWord {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : Fin n → Fin (μ.colLen 0) := + fun i => ⟨(t i).val.1, YoungDiagram.mem_iff_lt_colLen.mp + (μ.up_left_mem le_rfl (Nat.zero_le _) (t i).property)⟩ + +/- The column permutations of a tableau. -/ +def columnGroup {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + Subgroup (Equiv.Perm (Fin n)) where + carrier := {g | ∀ i, (t (g i)).val.2 = (t i).val.2} + one_mem' := by intro i; rfl + mul_mem' := by + intro g h hg hh i + exact (hg (h i)).trans (hh i) + inv_mem' := by + intro g hg i + have h := hg (g⁻¹ i) + simpa using h.symm + +/- The standard column-antisymmetrized row tabloid, with complex coefficients. -/ +def polytabloid {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + WordSpace n (μ.colLen 0) := by + classical + letI := Fintype.ofFinite (columnGroup t) + exact ∑ g : columnGroup t, + (((Equiv.Perm.sign (g : Equiv.Perm (Fin n))) : ℤ) : ℂ) • + wordRep n (μ.colLen 0) (g : Equiv.Perm (Fin n)) (Pi.single (rowWord t) 1) + +/- The Specht module, defined as the orbit span of a polytabloid in the +row-tabloid permutation module, realized inside the word space. -/ +def spechtSub {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) := + cyclic (wordRep n (μ.colLen 0)) (polytabloid t) + +abbrev Specht {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) := + (spechtSub t).toSubmodule + +/- The genuine symmetric-group representation on the complex Specht module. -/ +def spechtRep {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + Representation ℂ (Equiv.Perm (Fin n)) (Specht t) := + (spechtSub t).toRepresentation + +/- Kronecker multiplicity is the complex dimension of Hom, with the +diagonal symmetric-group action on the tensor product. -/ +def kronecker {n : ℕ} {α β μ : YoungDiagram} + (a : Tableau n α) (b : Tableau n β) (t : Tableau n μ) : ℕ := + Module.finrank ℂ (Representation.IntertwiningMap (spechtRep t) + ((spechtRep a).tprod (spechtRep b))) + + +def staircase (m : ℕ) : YoungDiagram where + cells := ((Finset.range m) ×ˢ (Finset.range m)).filter (fun x => x.1 + x.2 < m) + isLowerSet := by + intro x y hxy hy + simp only [Finset.mem_coe, Finset.mem_filter, Finset.mem_product, + Finset.mem_range] at hy ⊢ + exact ⟨⟨lt_of_le_of_lt hxy.1 hy.1.1, lt_of_le_of_lt hxy.2 hy.1.2⟩, + lt_of_le_of_lt (Nat.add_le_add hxy.1 hxy.2) hy.2⟩ + + +def SaxlConjecture : Prop := + ∀ (m : ℕ), 1 ≤ m → ∀ (μ : YoungDiagram) (hμ : μ.card = (staircase m).card), + 0 < kronecker (canonicalTableau (staircase m) rfl) + (canonicalTableau (staircase m) rfl) (canonicalTableau μ hμ) + +theorem saxl_conjecture : SaxlConjecture := by + sorry + +end Saxl + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Saxl.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Saxl.saxl_conjecture` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/saxl/solution/closure.txt b/tasks/saxl/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4ebf695a8334084adcbb958aa8ddcf8fad17f8dd --- /dev/null +++ b/tasks/saxl/solution/closure.txt @@ -0,0 +1,38 @@ +OAI.RepresentationTheory.Saxl.BandFactorization +OAI.RepresentationTheory.Saxl.BandGlue +OAI.RepresentationTheory.Saxl.BandMatrices +OAI.RepresentationTheory.Saxl.BandOrbit +OAI.RepresentationTheory.Saxl.BandPairing +OAI.RepresentationTheory.Saxl.BandSupport +OAI.RepresentationTheory.Saxl.Basic +OAI.RepresentationTheory.Saxl.ColumnContraction +OAI.RepresentationTheory.Saxl.CoordinateSector +OAI.RepresentationTheory.Saxl.CyclicSector +OAI.RepresentationTheory.Saxl.CyclicTensor +OAI.RepresentationTheory.Saxl.DominatedQuotient +OAI.RepresentationTheory.Saxl.DominatedSupport +OAI.RepresentationTheory.Saxl.HighProjection +OAI.RepresentationTheory.Saxl.HorizontalRemoval +OAI.RepresentationTheory.Saxl.Main +OAI.RepresentationTheory.Saxl.Model +OAI.RepresentationTheory.Saxl.PathAlternation +OAI.RepresentationTheory.Saxl.PathContraction +OAI.RepresentationTheory.Saxl.PieriRestriction +OAI.RepresentationTheory.Saxl.Polytabloid +OAI.RepresentationTheory.Saxl.PositionSplit +OAI.RepresentationTheory.Saxl.PositionTensor +OAI.RepresentationTheory.Saxl.RepeatedProjection +OAI.RepresentationTheory.Saxl.ShapeRigidity +OAI.RepresentationTheory.Saxl.SignEquivalence +OAI.RepresentationTheory.Saxl.SizedStrips +OAI.RepresentationTheory.Saxl.SpechtClassification +OAI.RepresentationTheory.Saxl.SpechtDuality +OAI.RepresentationTheory.Saxl.SpechtSubmodule +OAI.RepresentationTheory.Saxl.StaircaseSign +OAI.RepresentationTheory.Saxl.StaircaseTensor +OAI.RepresentationTheory.Saxl.StripExtension +OAI.RepresentationTheory.Saxl.StripReduction +OAI.RepresentationTheory.Saxl.StripSupport +OAI.RepresentationTheory.Saxl.SupportSeparation +OAI.RepresentationTheory.Saxl.TableauTransport +OAI.RepresentationTheory.Saxl.YoungRule diff --git a/tasks/saxl/solution/reference.py b/tasks/saxl/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/saxl/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/saxl/solution/solve.sh b/tasks/saxl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7f211e4cb3b61bc6f3e07c1ddd30be20bbe3d964 --- /dev/null +++ b/tasks/saxl/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Saxl, i.e. module OAI.RepresentationTheory.Saxl.Main and the +# 38 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RepresentationTheory.Saxl.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Saxl" diff --git a/tasks/saxl/task.toml b/tasks/saxl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e1a0d994a4dfe192f81fc47244dd46db3d4423f --- /dev/null +++ b/tasks/saxl/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/saxl" +version = "1.0.0" +description = "Prove Saxl (openai/math family 205: Saxl's conjecture and universal tensor squares) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Saxl.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Saxl" +family = "205" +family_title = "Saxl's conjecture and universal tensor squares" +subject = "Algebra" +theorems = ["OAI.Saxl.saxl_conjecture"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RepresentationTheory.Saxl.Main" +reference_modules = 38 +reference_lean_bytes = 321190 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 943 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11989 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/saxl/tests/Challenge.lean b/tasks/saxl/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a38a2913147886cabd314918ecc596e32d5f976 --- /dev/null +++ b/tasks/saxl/tests/Challenge.lean @@ -0,0 +1,119 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped TensorProduct + +universe uG uV + +namespace Saxl + +/- Coefficients of position tensors on an alphabet of size `d`. -/ +abbrev WordSpace (n d : ℕ) := (Fin n → Fin d) → ℂ + +/- The position action satisfies `g e_a = e_(a ∘ g⁻¹)`. -/ +def wordRep (n d : ℕ) : Representation ℂ (Equiv.Perm (Fin n)) (WordSpace n d) where + toFun g := + { toFun := fun f a => f (a ∘ g) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext f a; rfl + map_mul' g h := by ext f a; rfl + +/- The cyclic subrepresentation generated by an actual vector. -/ +def cyclic {G : Type uG} {V : Type uV} [Group G] [AddCommGroup V] [Module ℂ V] + (ρ : Representation ℂ G V) (v : V) : Subrepresentation ρ where + toSubmodule := Submodule.span ℂ (Set.range fun g : G => ρ g v) + apply_mem_toSubmodule g := by + intro x hx + induction hx using Submodule.span_induction with + | mem x hx => + obtain ⟨h, rfl⟩ := hx + apply Submodule.subset_span + exact ⟨g * h, by simp only [map_mul, Module.End.mul_apply]⟩ + | zero => simp + | add x y hx hy ihx ihy => + simpa only [map_add] using Submodule.add_mem _ ihx ihy + | smul a x hx ih => + simpa only [map_smul] using Submodule.smul_mem _ a ih + +/- A tableau is an enumeration of all cells by the position set. -/ +abbrev Tableau (n : ℕ) (μ : YoungDiagram) := Fin n ≃ μ.cells + +/- One fixed tableau; changing its enumeration gives an isomorphic Specht module. -/ +def canonicalTableau {n : ℕ} (μ : YoungDiagram) (hn : μ.card = n) : Tableau n μ := + (Fintype.equivFinOfCardEq (by simpa using hn)).symm + +/- The row word corresponding to the tabloid of a tableau. -/ +def rowWord {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : Fin n → Fin (μ.colLen 0) := + fun i => ⟨(t i).val.1, YoungDiagram.mem_iff_lt_colLen.mp + (μ.up_left_mem le_rfl (Nat.zero_le _) (t i).property)⟩ + +/- The column permutations of a tableau. -/ +def columnGroup {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + Subgroup (Equiv.Perm (Fin n)) where + carrier := {g | ∀ i, (t (g i)).val.2 = (t i).val.2} + one_mem' := by intro i; rfl + mul_mem' := by + intro g h hg hh i + exact (hg (h i)).trans (hh i) + inv_mem' := by + intro g hg i + have h := hg (g⁻¹ i) + simpa using h.symm + +/- The standard column-antisymmetrized row tabloid, with complex coefficients. -/ +def polytabloid {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + WordSpace n (μ.colLen 0) := by + classical + letI := Fintype.ofFinite (columnGroup t) + exact ∑ g : columnGroup t, + (((Equiv.Perm.sign (g : Equiv.Perm (Fin n))) : ℤ) : ℂ) • + wordRep n (μ.colLen 0) (g : Equiv.Perm (Fin n)) (Pi.single (rowWord t) 1) + +/- The Specht module, defined as the orbit span of a polytabloid in the +row-tabloid permutation module, realized inside the word space. -/ +def spechtSub {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) := + cyclic (wordRep n (μ.colLen 0)) (polytabloid t) + +abbrev Specht {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) := + (spechtSub t).toSubmodule + +/- The genuine symmetric-group representation on the complex Specht module. -/ +def spechtRep {n : ℕ} {μ : YoungDiagram} (t : Tableau n μ) : + Representation ℂ (Equiv.Perm (Fin n)) (Specht t) := + (spechtSub t).toRepresentation + +/- Kronecker multiplicity is the complex dimension of Hom, with the +diagonal symmetric-group action on the tensor product. -/ +def kronecker {n : ℕ} {α β μ : YoungDiagram} + (a : Tableau n α) (b : Tableau n β) (t : Tableau n μ) : ℕ := + Module.finrank ℂ (Representation.IntertwiningMap (spechtRep t) + ((spechtRep a).tprod (spechtRep b))) + + +def staircase (m : ℕ) : YoungDiagram where + cells := ((Finset.range m) ×ˢ (Finset.range m)).filter (fun x => x.1 + x.2 < m) + isLowerSet := by + intro x y hxy hy + simp only [Finset.mem_coe, Finset.mem_filter, Finset.mem_product, + Finset.mem_range] at hy ⊢ + exact ⟨⟨lt_of_le_of_lt hxy.1 hy.1.1, lt_of_le_of_lt hxy.2 hy.1.2⟩, + lt_of_le_of_lt (Nat.add_le_add hxy.1 hxy.2) hy.2⟩ + + +def SaxlConjecture : Prop := + ∀ (m : ℕ), 1 ≤ m → ∀ (μ : YoungDiagram) (hμ : μ.card = (staircase m).card), + 0 < kronecker (canonicalTableau (staircase m) rfl) + (canonicalTableau (staircase m) rfl) (canonicalTableau μ hμ) + +theorem saxl_conjecture : SaxlConjecture := by + sorry + +end Saxl + +end + +end OAI diff --git a/tasks/saxl/tests/grade.py b/tasks/saxl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/saxl/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/saxl/tests/task.json b/tasks/saxl/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4e3485604f8c1baf49d01b1b04a869b9ec075024 --- /dev/null +++ b/tasks/saxl/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Saxl", + "comparator": { + "theorem_names": [ + "OAI.Saxl.saxl_conjecture" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11089 +} \ No newline at end of file diff --git a/tasks/saxl/tests/test.sh b/tasks/saxl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/saxl/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/second-kahn-kalai/environment/Dockerfile b/tasks/second-kahn-kalai/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/second-kahn-kalai/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/second-kahn-kalai/environment/fetch_mathlib.sh b/tasks/second-kahn-kalai/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/second-kahn-kalai/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/second-kahn-kalai/environment/lake-manifest.json b/tasks/second-kahn-kalai/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/second-kahn-kalai/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/second-kahn-kalai/environment/lakefile.lean b/tasks/second-kahn-kalai/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/second-kahn-kalai/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/second-kahn-kalai/environment/lean_setup.sh b/tasks/second-kahn-kalai/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/second-kahn-kalai/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/second-kahn-kalai/environment/pack_submission.py b/tasks/second-kahn-kalai/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/second-kahn-kalai/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/second-kahn-kalai/instruction.md b/tasks/second-kahn-kalai/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9e713c11b994ef9e6cf30b1af2c5b4f6ae48f087 --- /dev/null +++ b/tasks/second-kahn-kalai/instruction.md @@ -0,0 +1,125 @@ +# openai/math challenge `SecondKahnKalai` (family 176) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 176 of the release, *The second Kahn–Kalai conjecture* +(Combinatorics). The family as a whole: Proves the second Kahn–Kalai conjecture: for every finite simple graph $H$ with $h\ge1$ edges and at most $n$ vertices, its appearance threshold in $G(n,p)$ is at most $C p_{\mathrm E}(n,H)(1+\log_2 h)$, with universal $C$. Here $p_{\mathrm E}$ is the least density at which every subgraph of $H$ has expected copy count at least $1/2$. + +The challenge is `SecondKahnKalai`, also at `/opt/openai-math/challenges/SecondKahnKalai.lean`: + +```lean +import Mathlib.Data.Fintype.Powerset +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Combinatorics.SimpleGraph.Copy +import Mathlib.Analysis.SpecialFunctions.Log.Basic + +namespace OAI + +noncomputable section + +universe u + +namespace LeanBlast.SecondKahnKalai + +def bernoulliWeight {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (W : Finset X) : ℝ := + ∏ x, if x ∈ W then p else 1 - p + +def bernoulliExpectation {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (f : Finset X → ℝ) : ℝ := + ∑ W, bernoulliWeight p W * f W + +def bernoulliProbability {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (P : Finset X → Prop) : ℝ := by + classical + exact ∑ W, if P W then bernoulliWeight p W else 0 + +/-- The unordered non-loop edges of the complete graph on `n` vertices. -/ +abbrev Edge (n : ℕ) := {e : Sym2 (Fin n) // ¬e.IsDiag} + +/-- A set of edges, interpreted as an ordinary graph on all `n` vertices. -/ +def graphOfEdges {n : ℕ} (W : Finset (Edge n)) : SimpleGraph (Fin n) := + SimpleGraph.fromEdgeSet (Subtype.val '' (W : Set (Edge n))) + +/-- The number of unordered edges, each counted once. -/ +def edgeCount {V : Type u} (H : SimpleGraph V) : ℕ := Nat.card H.edgeSet + +/-- Expected number of actual unlabelled non-induced copies in `G(n,p)`. -/ +def expectedCopies {V : Type u} (n : ℕ) (p : ℝ) (H : SimpleGraph V) : ℝ := + bernoulliExpectation p (fun W : Finset (Edge n) => + ((graphOfEdges W).copyCount H : ℝ)) + +/-- Probability that `G(n,p)` contains at least one non-induced copy. -/ +def containmentProbability {V : Type u} (n : ℕ) (p : ℝ) + (H : SimpleGraph V) : ℝ := + bernoulliProbability p (fun W : Finset (Edge n) => + 0 < (graphOfEdges W).copyCount H) + +def criticalThreshold {V : Type u} (n : ℕ) (H : SimpleGraph V) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc 0 1 ∧ (1 / 2 : ℝ) ≤ containmentProbability n p H} + +def expectationThreshold {V : Type u} (n : ℕ) (H : SimpleGraph V) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc 0 1 ∧ + ∀ F : H.Subgraph, (1 / 2 : ℝ) ≤ expectedCopies n p F.coe} + +def logTwo (x : ℝ) : ℝ := Real.log x / Real.log 2 + +def SecondKahnKalaiBounds {V : Type u} (n : ℕ) (H : SimpleGraph V) : Prop := + criticalThreshold n H ≤ + min 1 (2048 * Real.exp 50 * expectationThreshold n H * + (1 + logTwo (edgeCount H : ℝ))) ∧ + criticalThreshold n H ≤ + 6144 * Real.exp 50 * expectationThreshold n H * logTwo (n : ℝ) + +theorem secondKahnKalaiBounds (n : ℕ) (V : Type u) [Fintype V] + (H : SimpleGraph V) (hn : 2 ≤ n) (hcard : Fintype.card V ≤ n) + (hedge : 1 ≤ edgeCount H) : SecondKahnKalaiBounds n H := by + sorry + +end LeanBlast.SecondKahnKalai + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SecondKahnKalai.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LeanBlast.SecondKahnKalai.secondKahnKalaiBounds` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/second-kahn-kalai/solution/closure.txt b/tasks/second-kahn-kalai/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..294189bd0168766b6bbf5088122f7cb68774f79d --- /dev/null +++ b/tasks/second-kahn-kalai/solution/closure.txt @@ -0,0 +1,37 @@ +OAI.Combinatorics.GraphThreshold.AdaptiveTrials +OAI.Combinatorics.GraphThreshold.Basic +OAI.Combinatorics.GraphThreshold.BernoulliCoupling +OAI.Combinatorics.GraphThreshold.BernoulliMonotonicity +OAI.Combinatorics.GraphThreshold.BernoulliUnion +OAI.Combinatorics.GraphThreshold.CapacityIteration +OAI.Combinatorics.GraphThreshold.CopyOrbits +OAI.Combinatorics.GraphThreshold.EmbeddingExtension +OAI.Combinatorics.GraphThreshold.FiniteProbability +OAI.Combinatorics.GraphThreshold.GraphContainment +OAI.Combinatorics.GraphThreshold.GraphCopies +OAI.Combinatorics.GraphThreshold.GraphEncoding +OAI.Combinatorics.GraphThreshold.GraphExpectedCopies +OAI.Combinatorics.GraphThreshold.GraphHierarchy +OAI.Combinatorics.GraphThreshold.GraphProbability +OAI.Combinatorics.GraphThreshold.GraphSupport +OAI.Combinatorics.GraphThreshold.LocalFailure +OAI.Combinatorics.GraphThreshold.LocalFailureNumerics +OAI.Combinatorics.GraphThreshold.Main +OAI.Combinatorics.GraphThreshold.Model +OAI.Combinatorics.GraphThreshold.OutsideChangeOfMeasure +OAI.Combinatorics.GraphThreshold.Predecessor +OAI.Combinatorics.GraphThreshold.ProbabilityTree +OAI.Combinatorics.GraphThreshold.ProbabilityTreeFacts +OAI.Combinatorics.GraphThreshold.ProbabilityTreePaths +OAI.Combinatorics.GraphThreshold.ProbabilityTreeTrim +OAI.Combinatorics.GraphThreshold.Resampling +OAI.Combinatorics.GraphThreshold.ResamplingDensity +OAI.Combinatorics.GraphThreshold.ResamplingEvents +OAI.Combinatorics.GraphThreshold.SpreadCounting +OAI.Combinatorics.GraphThreshold.Statement +OAI.Combinatorics.GraphThreshold.ThresholdBounds +OAI.Combinatorics.GraphThreshold.Thresholds +OAI.Combinatorics.GraphThreshold.TreeCovering +OAI.Combinatorics.GraphThreshold.TreePotential +OAI.Combinatorics.GraphThreshold.TreeReduction +OAI.Combinatorics.GraphThreshold.TreeReductionData diff --git a/tasks/second-kahn-kalai/solution/reference.py b/tasks/second-kahn-kalai/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/second-kahn-kalai/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/second-kahn-kalai/solution/solve.sh b/tasks/second-kahn-kalai/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ef70b6f6f4dea7d9f3a64214304874aefecf5759 --- /dev/null +++ b/tasks/second-kahn-kalai/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SecondKahnKalai, i.e. module OAI.Combinatorics.GraphThreshold.Main and the +# 37 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.GraphThreshold.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SecondKahnKalai" diff --git a/tasks/second-kahn-kalai/task.toml b/tasks/second-kahn-kalai/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..e69ccae547dbe22c1a33519f63538fde45b528c7 --- /dev/null +++ b/tasks/second-kahn-kalai/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/second-kahn-kalai" +version = "1.0.0" +description = "Prove SecondKahnKalai (openai/math family 176: The second Kahn–Kalai conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SecondKahnKalai.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SecondKahnKalai" +family = "176" +family_title = "The second Kahn–Kalai conjecture" +subject = "Combinatorics" +theorems = ["OAI.LeanBlast.SecondKahnKalai.secondKahnKalaiBounds"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.GraphThreshold.Main" +reference_modules = 37 +reference_lean_bytes = 288343 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 573 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11959 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/second-kahn-kalai/tests/Challenge.lean b/tasks/second-kahn-kalai/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a9cf65511e3bf58877869ac3d16f3a47b88c70ad --- /dev/null +++ b/tasks/second-kahn-kalai/tests/Challenge.lean @@ -0,0 +1,74 @@ +import Mathlib.Data.Fintype.Powerset +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.BigOperators.Ring.Finset +import Mathlib.Combinatorics.SimpleGraph.Copy +import Mathlib.Analysis.SpecialFunctions.Log.Basic + +namespace OAI + +noncomputable section + +universe u + +namespace LeanBlast.SecondKahnKalai + +def bernoulliWeight {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (W : Finset X) : ℝ := + ∏ x, if x ∈ W then p else 1 - p + +def bernoulliExpectation {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (f : Finset X → ℝ) : ℝ := + ∑ W, bernoulliWeight p W * f W + +def bernoulliProbability {X : Type u} [Fintype X] [DecidableEq X] + (p : ℝ) (P : Finset X → Prop) : ℝ := by + classical + exact ∑ W, if P W then bernoulliWeight p W else 0 + +/-- The unordered non-loop edges of the complete graph on `n` vertices. -/ +abbrev Edge (n : ℕ) := {e : Sym2 (Fin n) // ¬e.IsDiag} + +/-- A set of edges, interpreted as an ordinary graph on all `n` vertices. -/ +def graphOfEdges {n : ℕ} (W : Finset (Edge n)) : SimpleGraph (Fin n) := + SimpleGraph.fromEdgeSet (Subtype.val '' (W : Set (Edge n))) + +/-- The number of unordered edges, each counted once. -/ +def edgeCount {V : Type u} (H : SimpleGraph V) : ℕ := Nat.card H.edgeSet + +/-- Expected number of actual unlabelled non-induced copies in `G(n,p)`. -/ +def expectedCopies {V : Type u} (n : ℕ) (p : ℝ) (H : SimpleGraph V) : ℝ := + bernoulliExpectation p (fun W : Finset (Edge n) => + ((graphOfEdges W).copyCount H : ℝ)) + +/-- Probability that `G(n,p)` contains at least one non-induced copy. -/ +def containmentProbability {V : Type u} (n : ℕ) (p : ℝ) + (H : SimpleGraph V) : ℝ := + bernoulliProbability p (fun W : Finset (Edge n) => + 0 < (graphOfEdges W).copyCount H) + +def criticalThreshold {V : Type u} (n : ℕ) (H : SimpleGraph V) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc 0 1 ∧ (1 / 2 : ℝ) ≤ containmentProbability n p H} + +def expectationThreshold {V : Type u} (n : ℕ) (H : SimpleGraph V) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc 0 1 ∧ + ∀ F : H.Subgraph, (1 / 2 : ℝ) ≤ expectedCopies n p F.coe} + +def logTwo (x : ℝ) : ℝ := Real.log x / Real.log 2 + +def SecondKahnKalaiBounds {V : Type u} (n : ℕ) (H : SimpleGraph V) : Prop := + criticalThreshold n H ≤ + min 1 (2048 * Real.exp 50 * expectationThreshold n H * + (1 + logTwo (edgeCount H : ℝ))) ∧ + criticalThreshold n H ≤ + 6144 * Real.exp 50 * expectationThreshold n H * logTwo (n : ℝ) + +theorem secondKahnKalaiBounds (n : ℕ) (V : Type u) [Fintype V] + (H : SimpleGraph V) (hn : 2 ≤ n) (hcard : Fintype.card V ≤ n) + (hedge : 1 ≤ edgeCount H) : SecondKahnKalaiBounds n H := by + sorry + +end LeanBlast.SecondKahnKalai + +end + +end OAI diff --git a/tasks/second-kahn-kalai/tests/grade.py b/tasks/second-kahn-kalai/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/second-kahn-kalai/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/second-kahn-kalai/tests/task.json b/tasks/second-kahn-kalai/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e07554ba10bb3ecfad4624f790fc68d593178e98 --- /dev/null +++ b/tasks/second-kahn-kalai/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SecondKahnKalai", + "comparator": { + "theorem_names": [ + "OAI.LeanBlast.SecondKahnKalai.secondKahnKalaiBounds" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11059 +} \ No newline at end of file diff --git a/tasks/second-kahn-kalai/tests/test.sh b/tasks/second-kahn-kalai/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/second-kahn-kalai/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/self-similar-corollaries/environment/Dockerfile b/tasks/self-similar-corollaries/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/self-similar-corollaries/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/self-similar-corollaries/environment/fetch_mathlib.sh b/tasks/self-similar-corollaries/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/self-similar-corollaries/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/self-similar-corollaries/environment/lake-manifest.json b/tasks/self-similar-corollaries/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/self-similar-corollaries/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/self-similar-corollaries/environment/lakefile.lean b/tasks/self-similar-corollaries/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/self-similar-corollaries/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/self-similar-corollaries/environment/lean_setup.sh b/tasks/self-similar-corollaries/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/self-similar-corollaries/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/self-similar-corollaries/environment/pack_submission.py b/tasks/self-similar-corollaries/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/self-similar-corollaries/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/self-similar-corollaries/instruction.md b/tasks/self-similar-corollaries/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..73b71d81727f44e48d2e5bd52213ddcb6fac0811 --- /dev/null +++ b/tasks/self-similar-corollaries/instruction.md @@ -0,0 +1,141 @@ +# openai/math challenge `SelfSimilarCorollaries` (family 148) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 148 of the release, *The dimension formula for self-similar measures on the line* +(Dynamical systems and ergodic theory). The family as a whole: For every self-similar measure on the line generated by finitely many contracting similarities, proves $\dim_{\mathrm H}\mu=\min\{1,h_{\mathrm{RW}}/\chi\}$, where $h_{\mathrm{RW}}$ is the entropy rate of random composed maps and $\chi$ the average logarithmic contraction. This resolves the entropy-rate dimension conjecture without a separation assumption, allowing exact overlaps and unequal contraction ratios. + +The challenge is `SelfSimilarCorollaries`, also at `/opt/openai-math/challenges/SelfSimilarCorollaries.lean`: + +```lean +import Mathlib + +namespace OAI + +universe uι + +section + +open scoped BigOperators ENNReal +open MeasureTheory + +namespace EntropyRateDimension + +structure System (ι : Type uι) [Fintype ι] where + ratio : ι → ℝ + offset : ι → ℝ + weight : ι → ℝ + ratio_pos : ∀ i, 0 < |ratio i| + ratio_lt_one : ∀ i, |ratio i| < 1 + weight_pos : ∀ i, 0 < weight i + weight_sum : ∑ i, weight i = 1 + +namespace System +variable {ι : Type uι} [Fintype ι] + +def affine (S : System ι) (i : ι) (x : ℝ) : ℝ := S.ratio i * x + S.offset i + +def wordAffine (S : System ι) : List ι → ℝ × ℝ + | [] => (1, 0) + | i :: w => (S.ratio i * (S.wordAffine w).1, + S.ratio i * (S.wordAffine w).2 + S.offset i) + +def SelfSimilar (S : System ι) (μ : Measure ℝ) : Prop := + μ = ∑ i, ENNReal.ofReal (S.weight i) • μ.map (S.affine i) + +end System + +noncomputable def lowerHausdorffDimension (μ : Measure ℝ) : ℝ≥0∞ := + ⨅ (E : Set ℝ) (_ : MeasurableSet E) (_ : 0 < μ E), dimH E + +namespace Extensions +variable {ι : Type uι} [Fintype ι] + +def NoExactOverlaps (S : System ι) : Prop := Function.Injective S.wordAffine + +noncomputable def symbolEntropy (S : System ι) : ℝ := + ∑ i, Real.negMulLog (S.weight i) + +theorem homogeneous_dimension_direct {ι : Type uι} [Fintype ι] [Nonempty ι] (S : System ι) + {lam : ℝ} (hlam : 0 < lam) (hr : ∀ i, S.ratio i = lam) + (μ : Measure ℝ) [IsProbabilityMeasure μ] (hμ : S.SelfSimilar μ) + (h : NoExactOverlaps S) : + lowerHausdorffDimension μ = + ENNReal.ofReal (min 1 (symbolEntropy S / Real.log (1/lam))) := by + sorry + +end Extensions +end EntropyRateDimension +end + +open scoped BigOperators ENNReal + +namespace CorSetReference +variable {ι : Type uι} [Fintype ι] [Nonempty ι] + +noncomputable def codingPoint (r t : ι → ℝ) (ω : ℕ → ι) : ℝ := + ∑' n, (∏ j ∈ Finset.range n, r (ω j)) * t (ω n) + + +noncomputable def attractor (r t : ι → ℝ) : Set ℝ := + Set.range (codingPoint r t) + + +def word (r t : ι → ℝ) : List ι → ℝ × ℝ := + List.foldr (fun symbol coefficients => + (r symbol * coefficients.1, r symbol * coefficients.2 + t symbol)) (1, 0) + +theorem cor_set {ι : Type uι} [Fintype ι] [Nonempty ι] + (r t : ι → ℝ) (hr0 : ∀ i, 0 < |r i|) (hr1 : ∀ i, |r i| < 1) + (hno : ∀ u v : List ι, u ≠ [] → v ≠ [] → + word r t u = word r t v → u = v) : + IsCompact (attractor r t) ∧ (attractor r t).Nonempty ∧ + (∃! s : ℝ, 0 ≤ s ∧ ∑ i, |r i| ^ s = 1) ∧ + (∀ s : ℝ, 0 ≤ s → (∑ i, |r i| ^ s = 1) → + dimH (attractor r t) = ENNReal.ofReal (min 1 s)) := by + sorry + +end CorSetReference + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SelfSimilarCorollaries.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.EntropyRateDimension.Extensions.homogeneous_dimension_direct`, `OAI.CorSetReference.cor_set` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/self-similar-corollaries/solution/closure.txt b/tasks/self-similar-corollaries/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f2a18d77fcf5c13b958c22840a733b8ab16cb2b1 --- /dev/null +++ b/tasks/self-similar-corollaries/solution/closure.txt @@ -0,0 +1,64 @@ +OAI.MeasureTheory.SelfSimilar.Attractor +OAI.MeasureTheory.SelfSimilar.AttractorDimension +OAI.MeasureTheory.SelfSimilar.AttractorFormula +OAI.MeasureTheory.SelfSimilar.BallIntegrability +OAI.MeasureTheory.SelfSimilar.BallLimits +OAI.MeasureTheory.SelfSimilar.BallRatios +OAI.MeasureTheory.SelfSimilar.BandSelection +OAI.MeasureTheory.SelfSimilar.Basic +OAI.MeasureTheory.SelfSimilar.Bernoulli +OAI.MeasureTheory.SelfSimilar.BlockWords +OAI.MeasureTheory.SelfSimilar.Boundary +OAI.MeasureTheory.SelfSimilar.Clipping +OAI.MeasureTheory.SelfSimilar.Coding +OAI.MeasureTheory.SelfSimilar.CodingIntegrals +OAI.MeasureTheory.SelfSimilar.Conditioning +OAI.MeasureTheory.SelfSimilar.DigitSumset +OAI.MeasureTheory.SelfSimilar.DimensionCorollaries +OAI.MeasureTheory.SelfSimilar.EntropyBounds +OAI.MeasureTheory.SelfSimilar.EntropyBudget +OAI.MeasureTheory.SelfSimilar.EntropyDimension +OAI.MeasureTheory.SelfSimilar.EntropyGap +OAI.MeasureTheory.SelfSimilar.ErgodicAverages +OAI.MeasureTheory.SelfSimilar.ExactDimension +OAI.MeasureTheory.SelfSimilar.FairPairs +OAI.MeasureTheory.SelfSimilar.FiniteDistribution +OAI.MeasureTheory.SelfSimilar.FiniteEntropy +OAI.MeasureTheory.SelfSimilar.FiniteRefinement +OAI.MeasureTheory.SelfSimilar.FiniteVariance +OAI.MeasureTheory.SelfSimilar.GlobalCount +OAI.MeasureTheory.SelfSimilar.GridCoupling +OAI.MeasureTheory.SelfSimilar.HomogeneousDimension +OAI.MeasureTheory.SelfSimilar.Interpolation +OAI.MeasureTheory.SelfSimilar.InvariantLaw +OAI.MeasureTheory.SelfSimilar.KernelEntropy +OAI.MeasureTheory.SelfSimilar.LocalEntropy +OAI.MeasureTheory.SelfSimilar.LocalMass +OAI.MeasureTheory.SelfSimilar.Main +OAI.MeasureTheory.SelfSimilar.MassDimension +OAI.MeasureTheory.SelfSimilar.MeasureEntropy +OAI.MeasureTheory.SelfSimilar.Model +OAI.MeasureTheory.SelfSimilar.NoOverlaps +OAI.MeasureTheory.SelfSimilar.PairBands +OAI.MeasureTheory.SelfSimilar.PairGain +OAI.MeasureTheory.SelfSimilar.ProductLaw +OAI.MeasureTheory.SelfSimilar.RadialLimit +OAI.MeasureTheory.SelfSimilar.RadiusGrowth +OAI.MeasureTheory.SelfSimilar.RandomGrid +OAI.MeasureTheory.SelfSimilar.RetainedLoss +OAI.MeasureTheory.SelfSimilar.ScaleGain +OAI.MeasureTheory.SelfSimilar.SuffixLaw +OAI.MeasureTheory.SelfSimilar.SumsetBound +OAI.MeasureTheory.SelfSimilar.TailConvolution +OAI.MeasureTheory.SelfSimilar.TranslationGain +OAI.MeasureTheory.SelfSimilar.TriangularAverages +OAI.MeasureTheory.SelfSimilar.TypedEntropy +OAI.MeasureTheory.SelfSimilar.TypedLaw +OAI.MeasureTheory.SelfSimilar.TypedSumset +OAI.MeasureTheory.SelfSimilar.UnweightedAttractor +OAI.MeasureTheory.SelfSimilar.UpperBound +OAI.MeasureTheory.SelfSimilar.WindowCount +OAI.MeasureTheory.SelfSimilar.WindowGain +OAI.MeasureTheory.SelfSimilar.Windows +OAI.MeasureTheory.SelfSimilar.WordAverage +OAI.MeasureTheory.SelfSimilar.WordTypes diff --git a/tasks/self-similar-corollaries/solution/reference.py b/tasks/self-similar-corollaries/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/self-similar-corollaries/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/self-similar-corollaries/solution/solve.sh b/tasks/self-similar-corollaries/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4202ea714b771a60a13d05889718558f553cfde5 --- /dev/null +++ b/tasks/self-similar-corollaries/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SelfSimilarCorollaries, i.e. module OAI.MeasureTheory.SelfSimilar.DimensionCorollaries and the +# 64 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MeasureTheory.SelfSimilar.DimensionCorollaries /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SelfSimilarCorollaries" diff --git a/tasks/self-similar-corollaries/task.toml b/tasks/self-similar-corollaries/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d844893a3e1e5ef02f825a9b17435b0342055eed --- /dev/null +++ b/tasks/self-similar-corollaries/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/self-similar-corollaries" +version = "1.0.0" +description = "Prove SelfSimilarCorollaries (openai/math family 148: The dimension formula for self-similar measures on the line) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SelfSimilarCorollaries.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SelfSimilarCorollaries" +family = "148" +family_title = "The dimension formula for self-similar measures on the line" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.EntropyRateDimension.Extensions.homogeneous_dimension_direct", "OAI.CorSetReference.cor_set"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MeasureTheory.SelfSimilar.DimensionCorollaries" +reference_modules = 64 +reference_lean_bytes = 559526 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1090 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12203 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/self-similar-corollaries/tests/Challenge.lean b/tasks/self-similar-corollaries/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d2430524a79e106ad056e71402c31a616dff26a2 --- /dev/null +++ b/tasks/self-similar-corollaries/tests/Challenge.lean @@ -0,0 +1,90 @@ +import Mathlib + +namespace OAI + +universe uι + +section + +open scoped BigOperators ENNReal +open MeasureTheory + +namespace EntropyRateDimension + +structure System (ι : Type uι) [Fintype ι] where + ratio : ι → ℝ + offset : ι → ℝ + weight : ι → ℝ + ratio_pos : ∀ i, 0 < |ratio i| + ratio_lt_one : ∀ i, |ratio i| < 1 + weight_pos : ∀ i, 0 < weight i + weight_sum : ∑ i, weight i = 1 + +namespace System +variable {ι : Type uι} [Fintype ι] + +def affine (S : System ι) (i : ι) (x : ℝ) : ℝ := S.ratio i * x + S.offset i + +def wordAffine (S : System ι) : List ι → ℝ × ℝ + | [] => (1, 0) + | i :: w => (S.ratio i * (S.wordAffine w).1, + S.ratio i * (S.wordAffine w).2 + S.offset i) + +def SelfSimilar (S : System ι) (μ : Measure ℝ) : Prop := + μ = ∑ i, ENNReal.ofReal (S.weight i) • μ.map (S.affine i) + +end System + +noncomputable def lowerHausdorffDimension (μ : Measure ℝ) : ℝ≥0∞ := + ⨅ (E : Set ℝ) (_ : MeasurableSet E) (_ : 0 < μ E), dimH E + +namespace Extensions +variable {ι : Type uι} [Fintype ι] + +def NoExactOverlaps (S : System ι) : Prop := Function.Injective S.wordAffine + +noncomputable def symbolEntropy (S : System ι) : ℝ := + ∑ i, Real.negMulLog (S.weight i) + +theorem homogeneous_dimension_direct {ι : Type uι} [Fintype ι] [Nonempty ι] (S : System ι) + {lam : ℝ} (hlam : 0 < lam) (hr : ∀ i, S.ratio i = lam) + (μ : Measure ℝ) [IsProbabilityMeasure μ] (hμ : S.SelfSimilar μ) + (h : NoExactOverlaps S) : + lowerHausdorffDimension μ = + ENNReal.ofReal (min 1 (symbolEntropy S / Real.log (1/lam))) := by + sorry + +end Extensions +end EntropyRateDimension +end + +open scoped BigOperators ENNReal + +namespace CorSetReference +variable {ι : Type uι} [Fintype ι] [Nonempty ι] + +noncomputable def codingPoint (r t : ι → ℝ) (ω : ℕ → ι) : ℝ := + ∑' n, (∏ j ∈ Finset.range n, r (ω j)) * t (ω n) + + +noncomputable def attractor (r t : ι → ℝ) : Set ℝ := + Set.range (codingPoint r t) + + +def word (r t : ι → ℝ) : List ι → ℝ × ℝ := + List.foldr (fun symbol coefficients => + (r symbol * coefficients.1, r symbol * coefficients.2 + t symbol)) (1, 0) + +theorem cor_set {ι : Type uι} [Fintype ι] [Nonempty ι] + (r t : ι → ℝ) (hr0 : ∀ i, 0 < |r i|) (hr1 : ∀ i, |r i| < 1) + (hno : ∀ u v : List ι, u ≠ [] → v ≠ [] → + word r t u = word r t v → u = v) : + IsCompact (attractor r t) ∧ (attractor r t).Nonempty ∧ + (∃! s : ℝ, 0 ≤ s ∧ ∑ i, |r i| ^ s = 1) ∧ + (∀ s : ℝ, 0 ≤ s → (∑ i, |r i| ^ s = 1) → + dimH (attractor r t) = ENNReal.ofReal (min 1 s)) := by + sorry + +end CorSetReference + +end OAI diff --git a/tasks/self-similar-corollaries/tests/grade.py b/tasks/self-similar-corollaries/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/self-similar-corollaries/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/self-similar-corollaries/tests/task.json b/tasks/self-similar-corollaries/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7964a2eab13abc19d1cecda9b9aa31145102da29 --- /dev/null +++ b/tasks/self-similar-corollaries/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "SelfSimilarCorollaries", + "comparator": { + "theorem_names": [ + "OAI.EntropyRateDimension.Extensions.homogeneous_dimension_direct", + "OAI.CorSetReference.cor_set" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11303 +} \ No newline at end of file diff --git a/tasks/self-similar-corollaries/tests/test.sh b/tasks/self-similar-corollaries/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/self-similar-corollaries/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/self-similar/environment/Dockerfile b/tasks/self-similar/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/self-similar/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/self-similar/environment/fetch_mathlib.sh b/tasks/self-similar/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/self-similar/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/self-similar/environment/lake-manifest.json b/tasks/self-similar/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/self-similar/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/self-similar/environment/lakefile.lean b/tasks/self-similar/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/self-similar/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/self-similar/environment/lean_setup.sh b/tasks/self-similar/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/self-similar/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/self-similar/environment/pack_submission.py b/tasks/self-similar/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/self-similar/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/self-similar/instruction.md b/tasks/self-similar/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f1f0fb317083ba40ef0a795e547b88ded095be91 --- /dev/null +++ b/tasks/self-similar/instruction.md @@ -0,0 +1,124 @@ +# openai/math challenge `SelfSimilar` (family 148) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 148 of the release, *The dimension formula for self-similar measures on the line* +(Dynamical systems and ergodic theory). The family as a whole: For every self-similar measure on the line generated by finitely many contracting similarities, proves $\dim_{\mathrm H}\mu=\min\{1,h_{\mathrm{RW}}/\chi\}$, where $h_{\mathrm{RW}}$ is the entropy rate of random composed maps and $\chi$ the average logarithmic contraction. This resolves the entropy-rate dimension conjecture without a separation assumption, allowing exact overlaps and unequal contraction ratios. + +The challenge is `SelfSimilar`, also at `/opt/openai-math/challenges/SelfSimilar.lean`: + +```lean +import Mathlib + +namespace OAI + +universe uι + +open scoped BigOperators ENNReal +open MeasureTheory + +namespace EntropyRateDimension + +structure System (ι : Type uι) [Fintype ι] where + ratio : ι → ℝ + offset : ι → ℝ + weight : ι → ℝ + ratio_pos : ∀ i, 0 < |ratio i| + ratio_lt_one : ∀ i, |ratio i| < 1 + weight_pos : ∀ i, 0 < weight i + weight_sum : ∑ i, weight i = 1 + +namespace System + +variable {ι : Type uι} [Fintype ι] + +def affine (S : System ι) (i : ι) (x : ℝ) : ℝ := S.ratio i * x + S.offset i + +def wordAffine (S : System ι) : List ι → ℝ × ℝ + | [] => (1, 0) + | i :: w => (S.ratio i * (S.wordAffine w).1, + S.ratio i * (S.wordAffine w).2 + S.offset i) + +def completeMap (S : System ι) {n : ℕ} (w : Fin n → ι) : ℝ × ℝ := + S.wordAffine (List.ofFn w) + +noncomputable def wordWeight (S : System ι) {n : ℕ} (w : Fin n → ι) : ℝ := + ∏ j, S.weight (w j) + +noncomputable def mapSupport (S : System ι) (n : ℕ) : Finset (ℝ × ℝ) := by + classical + exact Finset.univ.image (S.completeMap (n := n)) + +noncomputable def mapMass (S : System ι) (n : ℕ) (g : ℝ × ℝ) : ℝ := by + classical + exact ∑ w ∈ (Finset.univ : Finset (Fin n → ι)).filter (S.completeMap · = g), + S.wordWeight w + +noncomputable def walkEntropy (S : System ι) (n : ℕ) : ℝ := + (∑ g ∈ S.mapSupport n, Real.negMulLog (S.mapMass n g)) / Real.log 2 + +noncomputable def entropyRate (S : System ι) : ℝ := + sInf (Set.range fun n : ℕ => S.walkEntropy (n + 1) / (n + 1 : ℕ)) + +noncomputable def lyapunov (S : System ι) : ℝ := + -(∑ i, S.weight i * (Real.log |S.ratio i| / Real.log 2)) + +def SelfSimilar (S : System ι) (μ : Measure ℝ) : Prop := + μ = ∑ i, ENNReal.ofReal (S.weight i) • μ.map (S.affine i) + +end System + +noncomputable def lowerHausdorffDimension (μ : Measure ℝ) : ℝ≥0∞ := + ⨅ (E : Set ℝ) (_ : MeasurableSet E) (_ : 0 < μ E), dimH E +open MeasureTheory + +theorem entropy_rate_dimension {ι : Type uι} [Fintype ι] [Nonempty ι] + (S : System ι) (μ : Measure ℝ) [IsProbabilityMeasure μ] + (hμ : S.SelfSimilar μ) : + lowerHausdorffDimension μ = ENNReal.ofReal (min 1 (S.entropyRate / S.lyapunov)) := by + sorry + +end EntropyRateDimension + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SelfSimilar.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EntropyRateDimension.entropy_rate_dimension` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/self-similar/solution/closure.txt b/tasks/self-similar/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b47f3341e5cf8c101dc698d6f9bfc5747cbfeb35 --- /dev/null +++ b/tasks/self-similar/solution/closure.txt @@ -0,0 +1,57 @@ +OAI.MeasureTheory.SelfSimilar.BallIntegrability +OAI.MeasureTheory.SelfSimilar.BallLimits +OAI.MeasureTheory.SelfSimilar.BallRatios +OAI.MeasureTheory.SelfSimilar.BandSelection +OAI.MeasureTheory.SelfSimilar.Basic +OAI.MeasureTheory.SelfSimilar.Bernoulli +OAI.MeasureTheory.SelfSimilar.BlockWords +OAI.MeasureTheory.SelfSimilar.Boundary +OAI.MeasureTheory.SelfSimilar.Clipping +OAI.MeasureTheory.SelfSimilar.Coding +OAI.MeasureTheory.SelfSimilar.CodingIntegrals +OAI.MeasureTheory.SelfSimilar.Conditioning +OAI.MeasureTheory.SelfSimilar.DigitSumset +OAI.MeasureTheory.SelfSimilar.EntropyBounds +OAI.MeasureTheory.SelfSimilar.EntropyBudget +OAI.MeasureTheory.SelfSimilar.EntropyDimension +OAI.MeasureTheory.SelfSimilar.EntropyGap +OAI.MeasureTheory.SelfSimilar.ErgodicAverages +OAI.MeasureTheory.SelfSimilar.ExactDimension +OAI.MeasureTheory.SelfSimilar.FairPairs +OAI.MeasureTheory.SelfSimilar.FiniteDistribution +OAI.MeasureTheory.SelfSimilar.FiniteEntropy +OAI.MeasureTheory.SelfSimilar.FiniteRefinement +OAI.MeasureTheory.SelfSimilar.FiniteVariance +OAI.MeasureTheory.SelfSimilar.GlobalCount +OAI.MeasureTheory.SelfSimilar.GridCoupling +OAI.MeasureTheory.SelfSimilar.Interpolation +OAI.MeasureTheory.SelfSimilar.InvariantLaw +OAI.MeasureTheory.SelfSimilar.KernelEntropy +OAI.MeasureTheory.SelfSimilar.LocalEntropy +OAI.MeasureTheory.SelfSimilar.LocalMass +OAI.MeasureTheory.SelfSimilar.Main +OAI.MeasureTheory.SelfSimilar.MassDimension +OAI.MeasureTheory.SelfSimilar.MeasureEntropy +OAI.MeasureTheory.SelfSimilar.Model +OAI.MeasureTheory.SelfSimilar.PairBands +OAI.MeasureTheory.SelfSimilar.PairGain +OAI.MeasureTheory.SelfSimilar.ProductLaw +OAI.MeasureTheory.SelfSimilar.RadialLimit +OAI.MeasureTheory.SelfSimilar.RadiusGrowth +OAI.MeasureTheory.SelfSimilar.RandomGrid +OAI.MeasureTheory.SelfSimilar.RetainedLoss +OAI.MeasureTheory.SelfSimilar.ScaleGain +OAI.MeasureTheory.SelfSimilar.SuffixLaw +OAI.MeasureTheory.SelfSimilar.SumsetBound +OAI.MeasureTheory.SelfSimilar.TailConvolution +OAI.MeasureTheory.SelfSimilar.TranslationGain +OAI.MeasureTheory.SelfSimilar.TriangularAverages +OAI.MeasureTheory.SelfSimilar.TypedEntropy +OAI.MeasureTheory.SelfSimilar.TypedLaw +OAI.MeasureTheory.SelfSimilar.TypedSumset +OAI.MeasureTheory.SelfSimilar.UpperBound +OAI.MeasureTheory.SelfSimilar.WindowCount +OAI.MeasureTheory.SelfSimilar.WindowGain +OAI.MeasureTheory.SelfSimilar.Windows +OAI.MeasureTheory.SelfSimilar.WordAverage +OAI.MeasureTheory.SelfSimilar.WordTypes diff --git a/tasks/self-similar/solution/reference.py b/tasks/self-similar/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/self-similar/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/self-similar/solution/solve.sh b/tasks/self-similar/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c915b5f258a87d345ec653f84eb00fd2e32c7a88 --- /dev/null +++ b/tasks/self-similar/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SelfSimilar, i.e. module OAI.MeasureTheory.SelfSimilar.Main and the +# 57 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MeasureTheory.SelfSimilar.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SelfSimilar" diff --git a/tasks/self-similar/task.toml b/tasks/self-similar/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8dec16b3675e6ede0bfedaaadb72e944c64e7874 --- /dev/null +++ b/tasks/self-similar/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/self-similar" +version = "1.0.0" +description = "Prove SelfSimilar (openai/math family 148: The dimension formula for self-similar measures on the line) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SelfSimilar.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SelfSimilar" +family = "148" +family_title = "The dimension formula for self-similar measures on the line" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.EntropyRateDimension.entropy_rate_dimension"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MeasureTheory.SelfSimilar.Main" +reference_modules = 57 +reference_lean_bytes = 523984 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 832 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12171 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/self-similar/tests/Challenge.lean b/tasks/self-similar/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..36631fae29445952b191f98801e772aab83dcc64 --- /dev/null +++ b/tasks/self-similar/tests/Challenge.lean @@ -0,0 +1,73 @@ +import Mathlib + +namespace OAI + +universe uι + +open scoped BigOperators ENNReal +open MeasureTheory + +namespace EntropyRateDimension + +structure System (ι : Type uι) [Fintype ι] where + ratio : ι → ℝ + offset : ι → ℝ + weight : ι → ℝ + ratio_pos : ∀ i, 0 < |ratio i| + ratio_lt_one : ∀ i, |ratio i| < 1 + weight_pos : ∀ i, 0 < weight i + weight_sum : ∑ i, weight i = 1 + +namespace System + +variable {ι : Type uι} [Fintype ι] + +def affine (S : System ι) (i : ι) (x : ℝ) : ℝ := S.ratio i * x + S.offset i + +def wordAffine (S : System ι) : List ι → ℝ × ℝ + | [] => (1, 0) + | i :: w => (S.ratio i * (S.wordAffine w).1, + S.ratio i * (S.wordAffine w).2 + S.offset i) + +def completeMap (S : System ι) {n : ℕ} (w : Fin n → ι) : ℝ × ℝ := + S.wordAffine (List.ofFn w) + +noncomputable def wordWeight (S : System ι) {n : ℕ} (w : Fin n → ι) : ℝ := + ∏ j, S.weight (w j) + +noncomputable def mapSupport (S : System ι) (n : ℕ) : Finset (ℝ × ℝ) := by + classical + exact Finset.univ.image (S.completeMap (n := n)) + +noncomputable def mapMass (S : System ι) (n : ℕ) (g : ℝ × ℝ) : ℝ := by + classical + exact ∑ w ∈ (Finset.univ : Finset (Fin n → ι)).filter (S.completeMap · = g), + S.wordWeight w + +noncomputable def walkEntropy (S : System ι) (n : ℕ) : ℝ := + (∑ g ∈ S.mapSupport n, Real.negMulLog (S.mapMass n g)) / Real.log 2 + +noncomputable def entropyRate (S : System ι) : ℝ := + sInf (Set.range fun n : ℕ => S.walkEntropy (n + 1) / (n + 1 : ℕ)) + +noncomputable def lyapunov (S : System ι) : ℝ := + -(∑ i, S.weight i * (Real.log |S.ratio i| / Real.log 2)) + +def SelfSimilar (S : System ι) (μ : Measure ℝ) : Prop := + μ = ∑ i, ENNReal.ofReal (S.weight i) • μ.map (S.affine i) + +end System + +noncomputable def lowerHausdorffDimension (μ : Measure ℝ) : ℝ≥0∞ := + ⨅ (E : Set ℝ) (_ : MeasurableSet E) (_ : 0 < μ E), dimH E +open MeasureTheory + +theorem entropy_rate_dimension {ι : Type uι} [Fintype ι] [Nonempty ι] + (S : System ι) (μ : Measure ℝ) [IsProbabilityMeasure μ] + (hμ : S.SelfSimilar μ) : + lowerHausdorffDimension μ = ENNReal.ofReal (min 1 (S.entropyRate / S.lyapunov)) := by + sorry + +end EntropyRateDimension + +end OAI diff --git a/tasks/self-similar/tests/grade.py b/tasks/self-similar/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/self-similar/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/self-similar/tests/task.json b/tasks/self-similar/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..03332c378ddaa5b279d1649d0b93f7e3185222f8 --- /dev/null +++ b/tasks/self-similar/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SelfSimilar", + "comparator": { + "theorem_names": [ + "OAI.EntropyRateDimension.entropy_rate_dimension" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11271 +} \ No newline at end of file diff --git a/tasks/self-similar/tests/test.sh b/tasks/self-similar/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/self-similar/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sensitivity-separation/environment/Dockerfile b/tasks/sensitivity-separation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sensitivity-separation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sensitivity-separation/environment/fetch_mathlib.sh b/tasks/sensitivity-separation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sensitivity-separation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sensitivity-separation/environment/lake-manifest.json b/tasks/sensitivity-separation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sensitivity-separation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sensitivity-separation/environment/lakefile.lean b/tasks/sensitivity-separation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sensitivity-separation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sensitivity-separation/environment/lean_setup.sh b/tasks/sensitivity-separation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sensitivity-separation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sensitivity-separation/environment/pack_submission.py b/tasks/sensitivity-separation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sensitivity-separation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sensitivity-separation/instruction.md b/tasks/sensitivity-separation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9abe1fb4882a984b1b96feb28aba425a90b9ca6e --- /dev/null +++ b/tasks/sensitivity-separation/instruction.md @@ -0,0 +1,93 @@ +# openai/math challenge `SensitivitySeparation` (family 132) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 132 of the release, *A counterexample to the quadratic sensitivity conjecture* +(Theoretical computer science). The family as a whole: Constructs total Boolean functions with block sensitivity $\operatorname{bs}(f)\ge s(f)^\alpha$ for a fixed $\alpha>2$, disproving the quadratic strengthening of the Sensitivity Conjecture. Here $s(f)$ counts influential individual-bit flips, while block sensitivity allows disjoint groups of bits to change together. + +The challenge is `SensitivitySeparation`, also at `/opt/openai-math/challenges/SensitivitySeparation.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped Classical + +namespace Paper320 + +def flip {I : Type} (x : I → Bool) (B : Finset I) : I → Bool := + fun i => if i ∈ B then !(x i) else x i + +def sensitivityAt {I : Type} [Fintype I] + (f : (I → Bool) → Bool) (x : I → Bool) : ℕ := + (Finset.univ.filter fun i => f (flip x {i}) ≠ f x).card + +def sensitivity {I : Type} [Fintype I] (f : (I → Bool) → Bool) : ℕ := + Finset.univ.sup (sensitivityAt f) + +def blockSensitivityAt {I : Type} [Fintype I] + (f : (I → Bool) → Bool) (x : I → Bool) : ℕ := + Finset.univ.sup fun blocks : Finset (Finset I) => + if (∀ A ∈ blocks, ∀ B ∈ blocks, A ≠ B → Disjoint A B) ∧ + (∀ B ∈ blocks, B.Nonempty ∧ f (flip x B) ≠ f x) + then blocks.card else 0 + +def blockSensitivity {I : Type} [Fintype I] (f : (I → Bool) → Bool) : ℕ := + Finset.univ.sup (blockSensitivityAt f) + +theorem quantitative_separation (d : ℕ) (hd : 1 ≤ d) : + ∃ (n : ℕ) (f : (Fin n → Bool) → Bool), + 0 < n ∧ f (fun _ => false) = false ∧ + (∃ x y : Fin n → Bool, f x ≠ f y) ∧ + (2 : ℝ) ^ d / (4 * ((d : ℝ) + 2) ^ 2) ≤ + (blockSensitivity f : ℝ) / (sensitivity f : ℝ) ^ 2 := by + sorry + +end Paper320 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SensitivitySeparation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Paper320.quantitative_separation` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sensitivity-separation/solution/closure.txt b/tasks/sensitivity-separation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0550034a430c361afc6c7d50cb882de1441bb7bd --- /dev/null +++ b/tasks/sensitivity-separation/solution/closure.txt @@ -0,0 +1,42 @@ +OAI.Combinatorics.Sensitivity.Basic +OAI.Combinatorics.Sensitivity.Composition +OAI.Combinatorics.Sensitivity.ConstructedSeed +OAI.Combinatorics.Sensitivity.Construction +OAI.Combinatorics.Sensitivity.FixedCoordinates +OAI.Combinatorics.Sensitivity.HammingBase +OAI.Combinatorics.Sensitivity.InitialPredicates +OAI.Combinatorics.Sensitivity.Iterates +OAI.Combinatorics.Sensitivity.Labeling +OAI.Combinatorics.Sensitivity.LabelingBounds +OAI.Combinatorics.Sensitivity.LabelingConstraints +OAI.Combinatorics.Sensitivity.LabelingEstimate +OAI.Combinatorics.Sensitivity.LabelingEvents +OAI.Combinatorics.Sensitivity.Model +OAI.Combinatorics.Sensitivity.Or +OAI.Combinatorics.Sensitivity.ParameterBounds +OAI.Combinatorics.Sensitivity.PowerAmplification +OAI.Combinatorics.Sensitivity.ProfileArithmetic +OAI.Combinatorics.Sensitivity.QuantitativeProfiles +OAI.Combinatorics.Sensitivity.Recursive +OAI.Combinatorics.Sensitivity.RecursiveBlocks +OAI.Combinatorics.Sensitivity.RecursiveCandidates +OAI.Combinatorics.Sensitivity.RecursiveChildren +OAI.Combinatorics.Sensitivity.RecursiveDefinitions +OAI.Combinatorics.Sensitivity.RecursiveFailures +OAI.Combinatorics.Sensitivity.RecursiveFlips +OAI.Combinatorics.Sensitivity.RecursiveJointZero +OAI.Combinatorics.Sensitivity.RecursiveOne +OAI.Combinatorics.Sensitivity.RecursiveProfiles +OAI.Combinatorics.Sensitivity.RecursiveRepair +OAI.Combinatorics.Sensitivity.RecursiveSets +OAI.Combinatorics.Sensitivity.RecursiveZero +OAI.Combinatorics.Sensitivity.Reindex +OAI.Combinatorics.Sensitivity.ScalarBounds +OAI.Combinatorics.Sensitivity.SeedAmplification +OAI.Combinatorics.Sensitivity.Separation +OAI.Combinatorics.Sensitivity.SeparationArithmetic +OAI.Combinatorics.Sensitivity.Tournament +OAI.Combinatorics.Sensitivity.TournamentCounts +OAI.Combinatorics.Sensitivity.TournamentCyclic +OAI.Combinatorics.Sensitivity.Tower +OAI.Combinatorics.Sensitivity.TowerProfiles diff --git a/tasks/sensitivity-separation/solution/reference.py b/tasks/sensitivity-separation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sensitivity-separation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sensitivity-separation/solution/solve.sh b/tasks/sensitivity-separation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..faec8e072c1830517e9d50e645d7bce043794b52 --- /dev/null +++ b/tasks/sensitivity-separation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SensitivitySeparation, i.e. module OAI.Combinatorics.Sensitivity.Separation and the +# 42 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Sensitivity.Separation /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SensitivitySeparation" diff --git a/tasks/sensitivity-separation/task.toml b/tasks/sensitivity-separation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..34b8315bad8b144e5b5a3bcdd755bf2b785585e6 --- /dev/null +++ b/tasks/sensitivity-separation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sensitivity-separation" +version = "1.0.0" +description = "Prove SensitivitySeparation (openai/math family 132: A counterexample to the quadratic sensitivity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SensitivitySeparation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SensitivitySeparation" +family = "132" +family_title = "A counterexample to the quadratic sensitivity conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.Paper320.quantitative_separation"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Sensitivity.Separation" +reference_modules = 42 +reference_lean_bytes = 159617 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 787 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11843 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sensitivity-separation/tests/Challenge.lean b/tasks/sensitivity-separation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b2cf871bc3bb38194fc1b742666210f11498918b --- /dev/null +++ b/tasks/sensitivity-separation/tests/Challenge.lean @@ -0,0 +1,42 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped Classical + +namespace Paper320 + +def flip {I : Type} (x : I → Bool) (B : Finset I) : I → Bool := + fun i => if i ∈ B then !(x i) else x i + +def sensitivityAt {I : Type} [Fintype I] + (f : (I → Bool) → Bool) (x : I → Bool) : ℕ := + (Finset.univ.filter fun i => f (flip x {i}) ≠ f x).card + +def sensitivity {I : Type} [Fintype I] (f : (I → Bool) → Bool) : ℕ := + Finset.univ.sup (sensitivityAt f) + +def blockSensitivityAt {I : Type} [Fintype I] + (f : (I → Bool) → Bool) (x : I → Bool) : ℕ := + Finset.univ.sup fun blocks : Finset (Finset I) => + if (∀ A ∈ blocks, ∀ B ∈ blocks, A ≠ B → Disjoint A B) ∧ + (∀ B ∈ blocks, B.Nonempty ∧ f (flip x B) ≠ f x) + then blocks.card else 0 + +def blockSensitivity {I : Type} [Fintype I] (f : (I → Bool) → Bool) : ℕ := + Finset.univ.sup (blockSensitivityAt f) + +theorem quantitative_separation (d : ℕ) (hd : 1 ≤ d) : + ∃ (n : ℕ) (f : (Fin n → Bool) → Bool), + 0 < n ∧ f (fun _ => false) = false ∧ + (∃ x y : Fin n → Bool, f x ≠ f y) ∧ + (2 : ℝ) ^ d / (4 * ((d : ℝ) + 2) ^ 2) ≤ + (blockSensitivity f : ℝ) / (sensitivity f : ℝ) ^ 2 := by + sorry + +end Paper320 + +end + +end OAI diff --git a/tasks/sensitivity-separation/tests/grade.py b/tasks/sensitivity-separation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sensitivity-separation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sensitivity-separation/tests/task.json b/tasks/sensitivity-separation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ad60a9aebd0337cb4a6c7d70df0bfeb3783057b0 --- /dev/null +++ b/tasks/sensitivity-separation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SensitivitySeparation", + "comparator": { + "theorem_names": [ + "OAI.Paper320.quantitative_separation" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10943 +} \ No newline at end of file diff --git a/tasks/sensitivity-separation/tests/test.sh b/tasks/sensitivity-separation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sensitivity-separation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/separable-quotient-negative/environment/Dockerfile b/tasks/separable-quotient-negative/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/separable-quotient-negative/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/separable-quotient-negative/environment/fetch_mathlib.sh b/tasks/separable-quotient-negative/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/separable-quotient-negative/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/separable-quotient-negative/environment/lake-manifest.json b/tasks/separable-quotient-negative/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/separable-quotient-negative/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/separable-quotient-negative/environment/lakefile.lean b/tasks/separable-quotient-negative/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/separable-quotient-negative/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/separable-quotient-negative/environment/lean_setup.sh b/tasks/separable-quotient-negative/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/separable-quotient-negative/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/separable-quotient-negative/environment/pack_submission.py b/tasks/separable-quotient-negative/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/separable-quotient-negative/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/separable-quotient-negative/instruction.md b/tasks/separable-quotient-negative/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb5beb592891e7416d0f5aa13c3ef69615ef333d --- /dev/null +++ b/tasks/separable-quotient-negative/instruction.md @@ -0,0 +1,82 @@ +# openai/math challenge `SeparableQuotientNegative` (family 323) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 323 of the release, *Relative independence of the separable quotient problem* +(Functional analysis). The family as a whole: Establishes, relative to the consistency of a measurable cardinal, that the separable quotient problem is independent of ZFC. The assertion that every infinite-dimensional Banach space has a separable infinite-dimensional quotient can hold for all real and complex Banach spaces, whereas the continuum hypothesis yields counterexamples over both fields. + +The challenge is `SeparableQuotientNegative`, also at `/opt/openai-math/challenges/SeparableQuotientNegative.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace SeparableQuotient + +open MeasureTheory Cardinal + +universe u + +/-- The continuum hypothesis. -/ +def CH : Prop := Cardinal.mk ℝ = Cardinal.aleph 1 + +/-- A bounded linear surjection onto an infinite-dimensional separable Banach space. -/ +def HasSeparableQuotient (𝕜 : Type) [RCLike 𝕜] + (X : Type u) [NormedAddCommGroup X] [NormedSpace 𝕜 X] : Prop := + ∃ (Y : Type u) (_ : NormedAddCommGroup Y) (_ : NormedSpace 𝕜 Y), + CompleteSpace Y ∧ TopologicalSpace.SeparableSpace Y ∧ + (¬ FiniteDimensional 𝕜 Y) ∧ ∃ T : X →L[𝕜] Y, Function.Surjective T + +/-- The separable quotient assertion at an arbitrary ambient universe. -/ +def SQ (𝕜 : Type) [RCLike 𝕜] : Prop := + ∀ (X : Type u) [NormedAddCommGroup X] [NormedSpace 𝕜 X] [CompleteSpace X], + (¬ FiniteDimensional 𝕜 X) → HasSeparableQuotient 𝕜 X + +theorem negative_main (hCH : CH) : ¬ SQ.{u} ℝ ∧ ¬ SQ.{u} ℂ := by + sorry + +end SeparableQuotient + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SeparableQuotientNegative.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SeparableQuotient.negative_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/separable-quotient-negative/solution/closure.txt b/tasks/separable-quotient-negative/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0948e7622264ba228b31d139ded62791239dc095 --- /dev/null +++ b/tasks/separable-quotient-negative/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Analysis.SeparableQuotients.AdjointSurjectivity +OAI.Analysis.SeparableQuotients.BlockApproximation +OAI.Analysis.SeparableQuotients.BlockEstimates +OAI.Analysis.SeparableQuotients.BoundedCompleteness +OAI.Analysis.SeparableQuotients.BranchPaths +OAI.Analysis.SeparableQuotients.BranchReduction +OAI.Analysis.SeparableQuotients.BranchSeparation +OAI.Analysis.SeparableQuotients.ChangedPredual +OAI.Analysis.SeparableQuotients.CoherentClosures +OAI.Analysis.SeparableQuotients.ColorDecomposition +OAI.Analysis.SeparableQuotients.Complexification +OAI.Analysis.SeparableQuotients.CoordinateDual +OAI.Analysis.SeparableQuotients.CoordinatePredual +OAI.Analysis.SeparableQuotients.EvaluationCriterion +OAI.Analysis.SeparableQuotients.ExactPairs +OAI.Analysis.SeparableQuotients.FiniteLp +OAI.Analysis.SeparableQuotients.FiniteNormers +OAI.Analysis.SeparableQuotients.LpDuality +OAI.Analysis.SeparableQuotients.Main +OAI.Analysis.SeparableQuotients.MarkedEstimates +OAI.Analysis.SeparableQuotients.Model +OAI.Analysis.SeparableQuotients.NegativeComplex +OAI.Analysis.SeparableQuotients.NegativeReal +OAI.Analysis.SeparableQuotients.NormCompletion +OAI.Analysis.SeparableQuotients.NormingBounds +OAI.Analysis.SeparableQuotients.NormingFamilies +OAI.Analysis.SeparableQuotients.NormingOperations +OAI.Analysis.SeparableQuotients.NormingTrees +OAI.Analysis.SeparableQuotients.Parameters +OAI.Analysis.SeparableQuotients.PartitionBlocks +OAI.Analysis.SeparableQuotients.PathCoding +OAI.Analysis.SeparableQuotients.PathConvergence +OAI.Analysis.SeparableQuotients.PathLimits +OAI.Analysis.SeparableQuotients.PathOperators +OAI.Analysis.SeparableQuotients.PathRigidity +OAI.Analysis.SeparableQuotients.PathStabilization +OAI.Analysis.SeparableQuotients.PerturbationOperator +OAI.Analysis.SeparableQuotients.PrefixNormers +OAI.Analysis.SeparableQuotients.ProductQuotients +OAI.Analysis.SeparableQuotients.QuotientPerturbation +OAI.Analysis.SeparableQuotients.RamseyThinning +OAI.Analysis.SeparableQuotients.RealCoefficients +OAI.Analysis.SeparableQuotients.SeparableSubspaces +OAI.Analysis.SeparableQuotients.StoppedCharges +OAI.Analysis.SeparableQuotients.StrictSingularity +OAI.Analysis.SeparableQuotients.TailBlocks +OAI.Analysis.SeparableQuotients.TreeBounds +OAI.Analysis.SeparableQuotients.TreeCharges +OAI.Analysis.SeparableQuotients.WindowCharges +OAI.Analysis.SeparableQuotients.WindowEstimates +OAI.Analysis.SeparableQuotients.WindowThinning diff --git a/tasks/separable-quotient-negative/solution/reference.py b/tasks/separable-quotient-negative/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/separable-quotient-negative/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/separable-quotient-negative/solution/solve.sh b/tasks/separable-quotient-negative/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5f875c4783bad618f5a88785f93ebba456f8f3c8 --- /dev/null +++ b/tasks/separable-quotient-negative/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SeparableQuotientNegative, i.e. module OAI.Analysis.SeparableQuotients.Main and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.SeparableQuotients.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SeparableQuotientNegative" diff --git a/tasks/separable-quotient-negative/task.toml b/tasks/separable-quotient-negative/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a01ae823b72a930174bc6a4a15950b461a0ce5c4 --- /dev/null +++ b/tasks/separable-quotient-negative/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/separable-quotient-negative" +version = "1.0.0" +description = "Prove SeparableQuotientNegative (openai/math family 323: Relative independence of the separable quotient problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SeparableQuotientNegative.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SeparableQuotientNegative" +family = "323" +family_title = "Relative independence of the separable quotient problem" +subject = "Functional analysis" +theorems = ["OAI.SeparableQuotient.negative_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.SeparableQuotients.Main" +reference_modules = 51 +reference_lean_bytes = 669194 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 974 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12302 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/separable-quotient-negative/tests/Challenge.lean b/tasks/separable-quotient-negative/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b489a0ad4b757ae0ed725db356d8a5c80c66f59a --- /dev/null +++ b/tasks/separable-quotient-negative/tests/Challenge.lean @@ -0,0 +1,31 @@ +import Mathlib + +namespace OAI + +namespace SeparableQuotient + +open MeasureTheory Cardinal + +universe u + +/-- The continuum hypothesis. -/ +def CH : Prop := Cardinal.mk ℝ = Cardinal.aleph 1 + +/-- A bounded linear surjection onto an infinite-dimensional separable Banach space. -/ +def HasSeparableQuotient (𝕜 : Type) [RCLike 𝕜] + (X : Type u) [NormedAddCommGroup X] [NormedSpace 𝕜 X] : Prop := + ∃ (Y : Type u) (_ : NormedAddCommGroup Y) (_ : NormedSpace 𝕜 Y), + CompleteSpace Y ∧ TopologicalSpace.SeparableSpace Y ∧ + (¬ FiniteDimensional 𝕜 Y) ∧ ∃ T : X →L[𝕜] Y, Function.Surjective T + +/-- The separable quotient assertion at an arbitrary ambient universe. -/ +def SQ (𝕜 : Type) [RCLike 𝕜] : Prop := + ∀ (X : Type u) [NormedAddCommGroup X] [NormedSpace 𝕜 X] [CompleteSpace X], + (¬ FiniteDimensional 𝕜 X) → HasSeparableQuotient 𝕜 X + +theorem negative_main (hCH : CH) : ¬ SQ.{u} ℝ ∧ ¬ SQ.{u} ℂ := by + sorry + +end SeparableQuotient + +end OAI diff --git a/tasks/separable-quotient-negative/tests/grade.py b/tasks/separable-quotient-negative/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/separable-quotient-negative/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/separable-quotient-negative/tests/task.json b/tasks/separable-quotient-negative/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a773c1afebc6fab54d61a4fd864fd63771d6f21f --- /dev/null +++ b/tasks/separable-quotient-negative/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SeparableQuotientNegative", + "comparator": { + "theorem_names": [ + "OAI.SeparableQuotient.negative_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11402 +} \ No newline at end of file diff --git a/tasks/separable-quotient-negative/tests/test.sh b/tasks/separable-quotient-negative/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/separable-quotient-negative/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/seymour-second-neighborhood/environment/Dockerfile b/tasks/seymour-second-neighborhood/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/seymour-second-neighborhood/environment/fetch_mathlib.sh b/tasks/seymour-second-neighborhood/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/seymour-second-neighborhood/environment/lake-manifest.json b/tasks/seymour-second-neighborhood/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/seymour-second-neighborhood/environment/lakefile.lean b/tasks/seymour-second-neighborhood/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/seymour-second-neighborhood/environment/lean_setup.sh b/tasks/seymour-second-neighborhood/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/seymour-second-neighborhood/environment/pack_submission.py b/tasks/seymour-second-neighborhood/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/seymour-second-neighborhood/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/seymour-second-neighborhood/instruction.md b/tasks/seymour-second-neighborhood/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..61acedf605c415c45293f939f95f52cb9b761c1d --- /dev/null +++ b/tasks/seymour-second-neighborhood/instruction.md @@ -0,0 +1,91 @@ +# openai/math challenge `SeymourSecondNeighborhood` (family 173) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 173 of the release, *Seymour's second-neighborhood conjecture* +(Combinatorics). The family as a whole: Proves Seymour's second-neighborhood conjecture: every nonempty finite oriented graph has a vertex with at least as many vertices at directed distance exactly two as at directed distance one. Oriented graphs may be arbitrary apart from the exclusion of loops and oppositely directed edge pairs. + +The challenge is `SeymourSecondNeighborhood`, also at `/opt/openai-math/challenges/SeymourSecondNeighborhood.lean`: + +```lean +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Finset.Union + +namespace OAI + +namespace SeymourSecondNeighborhood + +variable {V : Type*} + +structure IsOriented (r : V → V → Prop) : Prop where + loopless : ∀ v, ¬ r v v + asymmetric : ∀ {u v}, r u v → ¬ r v u + +variable [Fintype V] [DecidableEq V] + +noncomputable section + +def firstNeighbors (r : V → V → Prop) (v : V) : Finset V := by + classical + exact Finset.univ.filter (r v) + +def secondNeighbors (r : V → V → Prop) (v : V) : Finset V := by + classical + exact Finset.univ.filter (fun w => + w ≠ v ∧ ¬ r v w ∧ ∃ u, r v u ∧ r u w) + +def GoodVertex (r : V → V → Prop) (v : V) : Prop := + (firstNeighbors r v).card ≤ (secondNeighbors r v).card + +end + +variable [Nonempty V] + +theorem exists_goodVertex (r : V → V → Prop) (hr : IsOriented r) : + ∃ v, GoodVertex r v := by + sorry + +end SeymourSecondNeighborhood + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SeymourSecondNeighborhood.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SeymourSecondNeighborhood.exists_goodVertex` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/seymour-second-neighborhood/solution/closure.txt b/tasks/seymour-second-neighborhood/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..44dfbab5269aa6adf6e4fce43cf0b4b9d6b306c3 --- /dev/null +++ b/tasks/seymour-second-neighborhood/solution/closure.txt @@ -0,0 +1,43 @@ +OAI.Combinatorics.SecondNeighborhood.AugmentedGraph +OAI.Combinatorics.SecondNeighborhood.AugmentedMatching +OAI.Combinatorics.SecondNeighborhood.AugmentedRankBound +OAI.Combinatorics.SecondNeighborhood.Basic +OAI.Combinatorics.SecondNeighborhood.CompositeRankBound +OAI.Combinatorics.SecondNeighborhood.CoverPruning +OAI.Combinatorics.SecondNeighborhood.Deletion +OAI.Combinatorics.SecondNeighborhood.ExtremalCompatibility +OAI.Combinatorics.SecondNeighborhood.ExtremalContradiction +OAI.Combinatorics.SecondNeighborhood.ExtremalCounting +OAI.Combinatorics.SecondNeighborhood.ExtremalImages +OAI.Combinatorics.SecondNeighborhood.GenericRank +OAI.Combinatorics.SecondNeighborhood.GenericRankCoefficients +OAI.Combinatorics.SecondNeighborhood.GenericRankColumns +OAI.Combinatorics.SecondNeighborhood.GenericRankFamily +OAI.Combinatorics.SecondNeighborhood.GenericRankGlobalMinors +OAI.Combinatorics.SecondNeighborhood.GenericRankMatching +OAI.Combinatorics.SecondNeighborhood.GenericRankSelection +OAI.Combinatorics.SecondNeighborhood.GenericRankSupport +OAI.Combinatorics.SecondNeighborhood.KernelBasisLifts +OAI.Combinatorics.SecondNeighborhood.KernelConflict +OAI.Combinatorics.SecondNeighborhood.KernelIndependence +OAI.Combinatorics.SecondNeighborhood.KernelRestriction +OAI.Combinatorics.SecondNeighborhood.Main +OAI.Combinatorics.SecondNeighborhood.Matching +OAI.Combinatorics.SecondNeighborhood.MatchingAugmented +OAI.Combinatorics.SecondNeighborhood.MatchingCover +OAI.Combinatorics.SecondNeighborhood.MatchingExchange +OAI.Combinatorics.SecondNeighborhood.MatrixMaps +OAI.Combinatorics.SecondNeighborhood.MatrixMapsCommute +OAI.Combinatorics.SecondNeighborhood.MatrixMapsPolynomial +OAI.Combinatorics.SecondNeighborhood.MaxSupportKernel +OAI.Combinatorics.SecondNeighborhood.MinimalCounterexample +OAI.Combinatorics.SecondNeighborhood.Model +OAI.Combinatorics.SecondNeighborhood.Pruning +OAI.Combinatorics.SecondNeighborhood.PruningDefinitions +OAI.Combinatorics.SecondNeighborhood.RankBoundFromMinors +OAI.Combinatorics.SecondNeighborhood.Reduction +OAI.Combinatorics.SecondNeighborhood.ReductionCore +OAI.Combinatorics.SecondNeighborhood.Reindex +OAI.Combinatorics.SecondNeighborhood.SubsetAugmentation +OAI.Combinatorics.SecondNeighborhood.SubsetDeficit +OAI.Combinatorics.SecondNeighborhood.TransitiveBlowup diff --git a/tasks/seymour-second-neighborhood/solution/reference.py b/tasks/seymour-second-neighborhood/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/seymour-second-neighborhood/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/seymour-second-neighborhood/solution/solve.sh b/tasks/seymour-second-neighborhood/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..977fa323c19a33e56c09cc13945e4a40edfdccc7 --- /dev/null +++ b/tasks/seymour-second-neighborhood/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SeymourSecondNeighborhood, i.e. module OAI.Combinatorics.SecondNeighborhood.Main and the +# 43 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.SecondNeighborhood.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SeymourSecondNeighborhood" diff --git a/tasks/seymour-second-neighborhood/task.toml b/tasks/seymour-second-neighborhood/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..edda89f35ad2c180b81f41d0a38ce641605918a2 --- /dev/null +++ b/tasks/seymour-second-neighborhood/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/seymour-second-neighborhood" +version = "1.0.0" +description = "Prove SeymourSecondNeighborhood (openai/math family 173: Seymour's second-neighborhood conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SeymourSecondNeighborhood.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SeymourSecondNeighborhood" +family = "173" +family_title = "Seymour's second-neighborhood conjecture" +subject = "Combinatorics" +theorems = ["OAI.SeymourSecondNeighborhood.exists_goodVertex"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.SecondNeighborhood.Main" +reference_modules = 43 +reference_lean_bytes = 190801 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 649 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11871 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/seymour-second-neighborhood/tests/Challenge.lean b/tasks/seymour-second-neighborhood/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..70d287c3f831d0698352b144d39cdf29cac6c24b --- /dev/null +++ b/tasks/seymour-second-neighborhood/tests/Challenge.lean @@ -0,0 +1,40 @@ +import Mathlib.Data.Fintype.Card +import Mathlib.Data.Finset.Union + +namespace OAI + +namespace SeymourSecondNeighborhood + +variable {V : Type*} + +structure IsOriented (r : V → V → Prop) : Prop where + loopless : ∀ v, ¬ r v v + asymmetric : ∀ {u v}, r u v → ¬ r v u + +variable [Fintype V] [DecidableEq V] + +noncomputable section + +def firstNeighbors (r : V → V → Prop) (v : V) : Finset V := by + classical + exact Finset.univ.filter (r v) + +def secondNeighbors (r : V → V → Prop) (v : V) : Finset V := by + classical + exact Finset.univ.filter (fun w => + w ≠ v ∧ ¬ r v w ∧ ∃ u, r v u ∧ r u w) + +def GoodVertex (r : V → V → Prop) (v : V) : Prop := + (firstNeighbors r v).card ≤ (secondNeighbors r v).card + +end + +variable [Nonempty V] + +theorem exists_goodVertex (r : V → V → Prop) (hr : IsOriented r) : + ∃ v, GoodVertex r v := by + sorry + +end SeymourSecondNeighborhood + +end OAI diff --git a/tasks/seymour-second-neighborhood/tests/grade.py b/tasks/seymour-second-neighborhood/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/seymour-second-neighborhood/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/seymour-second-neighborhood/tests/task.json b/tasks/seymour-second-neighborhood/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..84c4e48df7a145b09cc71fabb0d09145ff1d870d --- /dev/null +++ b/tasks/seymour-second-neighborhood/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SeymourSecondNeighborhood", + "comparator": { + "theorem_names": [ + "OAI.SeymourSecondNeighborhood.exists_goodVertex" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10971 +} \ No newline at end of file diff --git a/tasks/seymour-second-neighborhood/tests/test.sh b/tasks/seymour-second-neighborhood/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/seymour-second-neighborhood/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sharp-cat0-filling/environment/Dockerfile b/tasks/sharp-cat0-filling/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sharp-cat0-filling/environment/fetch_mathlib.sh b/tasks/sharp-cat0-filling/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sharp-cat0-filling/environment/lake-manifest.json b/tasks/sharp-cat0-filling/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sharp-cat0-filling/environment/lakefile.lean b/tasks/sharp-cat0-filling/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sharp-cat0-filling/environment/lean_setup.sh b/tasks/sharp-cat0-filling/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sharp-cat0-filling/environment/pack_submission.py b/tasks/sharp-cat0-filling/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sharp-cat0-filling/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sharp-cat0-filling/instruction.md b/tasks/sharp-cat0-filling/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a2bde53f07fb21cf1ca01688019155de19bcbad1 --- /dev/null +++ b/tasks/sharp-cat0-filling/instruction.md @@ -0,0 +1,197 @@ +# openai/math challenge `SharpCAT0Filling` (family 337) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 337 of the release, *Cartan–Hadamard isoperimetry and CAT$(0)$ fillings* +(Differential geometry). The family as a whole: Proves generalized Cartan–Hadamard isoperimetry in every dimension: in a complete simply connected manifold with sectional curvature at most $\kappa\le0$, every finite-volume finite-perimeter set satisfies the sharp comparison with the equal-volume model ball. Bounded positive-volume equality regions for $\kappa=0$ are Euclidean balls. Also proves sharp Euclidean filling bounds for compactly supported integral $n$-cycles, $n\ge2$, in arbitrary proper CAT$(0)$ spaces. + +The challenge is `SharpCAT0Filling`, also at `/opt/openai-math/challenges/SharpCAT0Filling.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped Topology ENNReal NNReal + +namespace CAT0Fillings + +attribute [local instance] Classical.propDecidable + +universe u + +abbrev Euc (k : ℕ) := EuclideanSpace ℝ (Fin k) +abbrev Functional (X : Type u) (k : ℕ) := (X → ℝ) → (Fin k → X → ℝ) → ℝ + +section MetricCurrents + +variable {X : Type u} [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + +def BoundedLip (b : X → ℝ) : Prop := + (∃ K : ℝ≥0, LipschitzWith K b) ∧ ∃ M : ℝ, ∀ x, |b x| ≤ M + +def Admissible {k : ℕ} (b : X → ℝ) (π : Fin k → X → ℝ) : Prop := + BoundedLip b ∧ ∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i) + +def Controls {k : ℕ} (T : Functional X k) (μ : Measure X) : Prop := + ∀ (b : X → ℝ) (π : Fin k → X → ℝ), BoundedLip b → + (∀ i, LipschitzWith 1 (π i)) → + |T b π| ≤ ∫ x, |b x| ∂μ + +noncomputable def mass {k : ℕ} (T : Functional X k) : ℝ := + sInf {r : ℝ | ∃ μ : Measure X, + IsFiniteMeasure μ ∧ Controls T μ ∧ r = μ.real univ} + +structure IsMetricCurrent {k : ℕ} (T : Functional X k) : Prop where + offDomain : ∀ b π, ¬Admissible b π → T b π = 0 + linearFirst : ∀ b₁ b₂ π (a c : ℝ), BoundedLip b₁ → BoundedLip b₂ → + (∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i)) → + T (fun x => a * b₁ x + c * b₂ x) π = a * T b₁ π + c * T b₂ π + linearCoord : ∀ b π i f (a c : ℝ), Admissible b π → + (∃ K : ℝ≥0, LipschitzWith K f) → + T b (Function.update π i (fun x => a * π i x + c * f x)) = + a * T b π + c * T b (Function.update π i f) + sequentialContinuity : ∀ b π (πs : ℕ → Fin k → X → ℝ), BoundedLip b → + (∀ i, ∃ K : ℝ≥0, ∀ j, LipschitzWith K (πs j i)) → + (∀ i x, Tendsto (fun j => πs j i x) atTop (𝓝 (π i x))) → + Tendsto (fun j => T b (πs j)) atTop (𝓝 (T b π)) + locality : ∀ b π, Admissible b π → + (∃ (i : Fin k) (U : Set X) (c : ℝ), IsOpen U ∧ Function.support b ⊆ U ∧ + ∀ x ∈ U, π i x = c) → T b π = 0 + finiteMass : ∃ μ : Measure X, IsFiniteMeasure μ ∧ Controls T μ + +noncomputable def boundarySucc {k : ℕ} (T : Functional X (k + 1)) : Functional X k := + fun b π => if Admissible b π then T (fun _ => 1) (Matrix.vecCons b π) else 0 + +noncomputable def boundary : {k : ℕ} → Functional X k → Functional X (k - 1) + | 0, _ => fun _ _ => 0 + | _ + 1, T => boundarySucc T + +structure IntegerChart (X : Type u) [MetricSpace X] (k : ℕ) where + domain : Set (Euc k) + borel : MeasurableSet domain + bounded : Bornology.IsBounded domain + param : domain → X + bilipschitz : ∃ L U : ℝ≥0, LipschitzWith L param ∧ AntilipschitzWith U param + multiplicity : Euc k → ℤ + integrable : Integrable (fun z => (multiplicity z : ℝ)) (volume.restrict domain) + +namespace IntegerChart + +variable {k : ℕ} (C : IntegerChart X k) + +noncomputable def scalar (f : X → ℝ) (z : Euc k) : ℝ := + if hz : z ∈ C.domain then f (C.param ⟨z, hz⟩) else 0 + +noncomputable def jacobian (π : Fin k → X → ℝ) (z : Euc k) : ℝ := + Matrix.det (fun i j => + (fderivWithin ℝ (C.scalar (π i)) C.domain z) (EuclideanSpace.single j 1)) + +noncomputable def action : Functional X k := + fun b π => if Admissible b π then + ∫ z in C.domain, (C.multiplicity z : ℝ) * C.scalar b z * C.jacobian π z + else 0 + +def image : Set X := Set.range C.param + +end IntegerChart + +def IntegerRectifiable {k : ℕ} (T : Functional X k) : Prop := + ∃ C : ℕ → IntegerChart X k, + Pairwise (fun i j => Disjoint (C i).image (C j).image) ∧ + (∀ i, IsMetricCurrent (C i).action) ∧ + Summable (fun i => mass (C i).action) ∧ + ∀ b π, T b π = ∑' i, (C i).action b π + +def IsIntegral : (k : ℕ) → Functional X k → Prop + | 0, T => IsMetricCurrent T ∧ IntegerRectifiable T + | _ + 1, T => IsMetricCurrent T ∧ IntegerRectifiable T ∧ + IsMetricCurrent (boundarySucc T) ∧ IntegerRectifiable (boundarySucc T) + +abbrev IntegralCurrent (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + (k : ℕ) := { T : Functional X k // IsIntegral k T } + +def CompactlySupported {k : ℕ} (T : Functional X k) : Prop := + ∃ K : Set X, IsCompact K ∧ + ∀ b π, Admissible b π → (∀ x ∈ K, b x = 0) → T b π = 0 + +def IsCycle {k : ℕ} (T : Functional X k) : Prop := boundary T = fun _ _ => 0 + +end MetricCurrents + +section Geometry +variable (X : Type u) [MetricSpace X] + +def IsCAT0 : Prop := + ∃ segment : X → X → ℝ → X, + (∀ x y, segment x y 0 = x ∧ segment x y 1 = y) ∧ + (∀ x y s t, s ∈ Icc (0 : ℝ) 1 → t ∈ Icc (0 : ℝ) 1 → + dist (segment x y s) (segment x y t) = |s - t| * dist x y) ∧ + (∀ o x y s t, s ∈ Icc (0 : ℝ) 1 → t ∈ Icc (0 : ℝ) 1 → + dist (segment o x s) (segment o y t) ^ 2 ≤ + (s * dist o x - t * dist o y) ^ 2 + + s * t * ((dist x y) ^ 2 - (dist o x - dist o y) ^ 2)) + +end Geometry + +noncomputable def omega (k : ℕ) : ℝ := + (volume (Metric.ball (0 : Euc k) 1)).toReal +noncomputable def sphereArea (n : ℕ) : ℝ := (n + 1 : ℝ) * omega (n + 1) +noncomputable def fillingCoefficient (n : ℕ) : ℝ := + 1 / ((n + 1 : ℝ) * (sphereArea n) ^ (1 / (n : ℝ))) +noncomputable def fillingPower (n : ℕ) : ℝ := (n + 1 : ℝ) / (n : ℝ) + +theorem sharp_integral_filling + (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] [ProperSpace X] + (hX : IsCAT0 X) (n : ℕ) (hn : 2 ≤ n) (T : IntegralCurrent X n) + (hTc : CompactlySupported T.val) (hTz : IsCycle T.val) : + ∃ S : IntegralCurrent X (n + 1), CompactlySupported S.val ∧ + boundarySucc S.val = T.val ∧ + mass S.val ≤ fillingCoefficient n * (mass T.val) ^ fillingPower n := by + sorry + +end CAT0Fillings + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SharpCAT0Filling.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CAT0Fillings.sharp_integral_filling` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sharp-cat0-filling/solution/closure.txt b/tasks/sharp-cat0-filling/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d440daaf21b8fbc1c7e1801cb3c590b2275733f2 --- /dev/null +++ b/tasks/sharp-cat0-filling/solution/closure.txt @@ -0,0 +1,330 @@ +OAI.Geometry.CAT0Fillings.BV.JointPoincare +OAI.Geometry.CAT0Fillings.BV.Oscillation +OAI.Geometry.CAT0Fillings.BV.Poincare +OAI.Geometry.CAT0Fillings.BV.WeakCalculus +OAI.Geometry.CAT0Fillings.Bubble.Beta +OAI.Geometry.CAT0Fillings.Bubble.Euclidean +OAI.Geometry.CAT0Fillings.Bubble.Moments +OAI.Geometry.CAT0Fillings.Calculus.AbsoluteValue +OAI.Geometry.CAT0Fillings.Calculus.Atlas +OAI.Geometry.CAT0Fillings.Calculus.Bivariate +OAI.Geometry.CAT0Fillings.Calculus.ChainSet +OAI.Geometry.CAT0Fillings.Calculus.ClosedBivariate +OAI.Geometry.CAT0Fillings.Calculus.ClosedChain +OAI.Geometry.CAT0Fillings.Calculus.ClosedLevel +OAI.Geometry.CAT0Fillings.Calculus.LipschitzFTC +OAI.Geometry.CAT0Fillings.Calculus.Piecewise +OAI.Geometry.CAT0Fillings.Calculus.Polynomial +OAI.Geometry.CAT0Fillings.Calculus.PositiveBivariate +OAI.Geometry.CAT0Fillings.Calculus.PositiveExtension +OAI.Geometry.CAT0Fillings.Calculus.Smoothing +OAI.Geometry.CAT0Fillings.Calculus.Truncation +OAI.Geometry.CAT0Fillings.Calculus.VectorLimit +OAI.Geometry.CAT0Fillings.Charts.Atoms +OAI.Geometry.CAT0Fillings.Charts.ChainRule +OAI.Geometry.CAT0Fillings.Charts.ChangeVariables +OAI.Geometry.CAT0Fillings.Charts.ContainingCharts +OAI.Geometry.CAT0Fillings.Charts.Control +OAI.Geometry.CAT0Fillings.Charts.CurrentAxioms +OAI.Geometry.CAT0Fillings.Charts.CurrentContinuity +OAI.Geometry.CAT0Fillings.Charts.DensityPush +OAI.Geometry.CAT0Fillings.Charts.Differentiability +OAI.Geometry.CAT0Fillings.Charts.DomainRestriction +OAI.Geometry.CAT0Fillings.Charts.ExactMass +OAI.Geometry.CAT0Fillings.Charts.Extensions +OAI.Geometry.CAT0Fillings.Charts.ExtensionsLimit +OAI.Geometry.CAT0Fillings.Charts.HilbertMass +OAI.Geometry.CAT0Fillings.Charts.ImageRestriction +OAI.Geometry.CAT0Fillings.Charts.IntegerSeries +OAI.Geometry.CAT0Fillings.Charts.Jacobian +OAI.Geometry.CAT0Fillings.Charts.JacobianBound +OAI.Geometry.CAT0Fillings.Charts.LinearMass +OAI.Geometry.CAT0Fillings.Charts.MeasurePartition +OAI.Geometry.CAT0Fillings.Charts.MultiplicityMass +OAI.Geometry.CAT0Fillings.Charts.MultiplicityRestriction +OAI.Geometry.CAT0Fillings.Charts.Orientation +OAI.Geometry.CAT0Fillings.Charts.OverlapSum +OAI.Geometry.CAT0Fillings.Charts.Postcompose +OAI.Geometry.CAT0Fillings.Charts.Quadratic +OAI.Geometry.CAT0Fillings.Charts.RectifiableMass +OAI.Geometry.CAT0Fillings.Charts.Reparametrization +OAI.Geometry.CAT0Fillings.Charts.Scalar +OAI.Geometry.CAT0Fillings.Charts.ScalarPieces +OAI.Geometry.CAT0Fillings.Charts.StraightPieces +OAI.Geometry.CAT0Fillings.Charts.Straightening +OAI.Geometry.CAT0Fillings.Charts.Transitions +OAI.Geometry.CAT0Fillings.Chord.AverageProfile +OAI.Geometry.CAT0Fillings.Chord.Barycenter +OAI.Geometry.CAT0Fillings.Chord.Bubble +OAI.Geometry.CAT0Fillings.Chord.Combined +OAI.Geometry.CAT0Fillings.Chord.DensityContradiction +OAI.Geometry.CAT0Fillings.Chord.Distribution +OAI.Geometry.CAT0Fillings.Chord.DoubleAverage +OAI.Geometry.CAT0Fillings.Chord.Fubini +OAI.Geometry.CAT0Fillings.Chord.GroundProducts +OAI.Geometry.CAT0Fillings.Chord.GroundState +OAI.Geometry.CAT0Fillings.Chord.Identity +OAI.Geometry.CAT0Fillings.Chord.Moments +OAI.Geometry.CAT0Fillings.Chord.NonnegativeMeasure +OAI.Geometry.CAT0Fillings.Chord.Profile +OAI.Geometry.CAT0Fillings.Chord.ProfileBound +OAI.Geometry.CAT0Fillings.Chord.RadialIntegral +OAI.Geometry.CAT0Fillings.Chord.TestIdentity +OAI.Geometry.CAT0Fillings.Compactness.Ascoli +OAI.Geometry.CAT0Fillings.Compactness.Atlas +OAI.Geometry.CAT0Fillings.Compactness.BV +OAI.Geometry.CAT0Fillings.Compactness.Borel +OAI.Geometry.CAT0Fillings.Compactness.ChartDensity +OAI.Geometry.CAT0Fillings.Compactness.Convolution +OAI.Geometry.CAT0Fillings.Compactness.Coordinates +OAI.Geometry.CAT0Fillings.Compactness.Interpolation +OAI.Geometry.CAT0Fillings.Compactness.IntrinsicBV +OAI.Geometry.CAT0Fillings.Compactness.Projected +OAI.Geometry.CAT0Fillings.Compactness.Tails +OAI.Geometry.CAT0Fillings.Compactness.Translation +OAI.Geometry.CAT0Fillings.Conformal.Closed +OAI.Geometry.CAT0Fillings.Conformal.Growth +OAI.Geometry.CAT0Fillings.Constants +OAI.Geometry.CAT0Fillings.Currents.ActionLimits +OAI.Geometry.CAT0Fillings.Currents.ActionSeries +OAI.Geometry.CAT0Fillings.Currents.Addition +OAI.Geometry.CAT0Fillings.Currents.AffineCalculus +OAI.Geometry.CAT0Fillings.Currents.AtomCompactness +OAI.Geometry.CAT0Fillings.Currents.Atoms +OAI.Geometry.CAT0Fillings.Currents.Basic +OAI.Geometry.CAT0Fillings.Currents.BorelAction +OAI.Geometry.CAT0Fillings.Currents.BoundaryMass +OAI.Geometry.CAT0Fillings.Currents.CanonicalMass +OAI.Geometry.CAT0Fillings.Currents.ChartSums +OAI.Geometry.CAT0Fillings.Currents.ComponentMass +OAI.Geometry.CAT0Fillings.Currents.Composition +OAI.Geometry.CAT0Fillings.Currents.Contraction +OAI.Geometry.CAT0Fillings.Currents.ControlledSum +OAI.Geometry.CAT0Fillings.Currents.CountableTests +OAI.Geometry.CAT0Fillings.Currents.CycleCalculus +OAI.Geometry.CAT0Fillings.Currents.CycleDerivative +OAI.Geometry.CAT0Fillings.Currents.CycleDifference +OAI.Geometry.CAT0Fillings.Currents.CycleFTC +OAI.Geometry.CAT0Fillings.Currents.DenseTests +OAI.Geometry.CAT0Fillings.Currents.DisjointUnions +OAI.Geometry.CAT0Fillings.Currents.FiniteAtoms +OAI.Geometry.CAT0Fillings.Currents.GeneralPush +OAI.Geometry.CAT0Fillings.Currents.IntegralPush +OAI.Geometry.CAT0Fillings.Currents.LevelLocality +OAI.Geometry.CAT0Fillings.Currents.MassBounds +OAI.Geometry.CAT0Fillings.Currents.MassTests +OAI.Geometry.CAT0Fillings.Currents.MovingAction +OAI.Geometry.CAT0Fillings.Currents.Multilinear +OAI.Geometry.CAT0Fillings.Currents.MultilinearPair +OAI.Geometry.CAT0Fillings.Currents.Negation +OAI.Geometry.CAT0Fillings.Currents.ProductRule +OAI.Geometry.CAT0Fillings.Currents.PushBoundary +OAI.Geometry.CAT0Fillings.Currents.PushMajorant +OAI.Geometry.CAT0Fillings.Currents.Pushforward +OAI.Geometry.CAT0Fillings.Currents.Restriction +OAI.Geometry.CAT0Fillings.Currents.SumControls +OAI.Geometry.CAT0Fillings.Currents.Summation +OAI.Geometry.CAT0Fillings.Currents.TestBounds +OAI.Geometry.CAT0Fillings.Currents.WeakClosure +OAI.Geometry.CAT0Fillings.Currents.WeakCompactness +OAI.Geometry.CAT0Fillings.Currents.WeakMass +OAI.Geometry.CAT0Fillings.Currents.WeakMeasures +OAI.Geometry.CAT0Fillings.Currents.WeightedAction +OAI.Geometry.CAT0Fillings.Density.Chart +OAI.Geometry.CAT0Fillings.Density.InverseCutoff +OAI.Geometry.CAT0Fillings.Density.NearEuclidean +OAI.Geometry.CAT0Fillings.Density.Normalized +OAI.Geometry.CAT0Fillings.Density.RadialBound +OAI.Geometry.CAT0Fillings.Density.RadialEstimate +OAI.Geometry.CAT0Fillings.Differentiation.Centered +OAI.Geometry.CAT0Fillings.Differentiation.CurveSpeed +OAI.Geometry.CAT0Fillings.Differentiation.Degenerate +OAI.Geometry.CAT0Fillings.Differentiation.Density +OAI.Geometry.CAT0Fillings.Differentiation.Directional +OAI.Geometry.CAT0Fillings.Differentiation.ErrorModulus +OAI.Geometry.CAT0Fillings.Differentiation.FullRank +OAI.Geometry.CAT0Fillings.Differentiation.HilbertCharts +OAI.Geometry.CAT0Fillings.Differentiation.HilbertPartition +OAI.Geometry.CAT0Fillings.Differentiation.LargePieces +OAI.Geometry.CAT0Fillings.Differentiation.LocalBounds +OAI.Geometry.CAT0Fillings.Differentiation.Parallelogram +OAI.Geometry.CAT0Fillings.Differentiation.Partitions +OAI.Geometry.CAT0Fillings.Differentiation.ScalarBound +OAI.Geometry.CAT0Fillings.Differentiation.Seminorm +OAI.Geometry.CAT0Fillings.Differentiation.TwoPoint +OAI.Geometry.CAT0Fillings.Euler.Contradiction +OAI.Geometry.CAT0Fillings.Euler.Moments +OAI.Geometry.CAT0Fillings.Euler.NormalizedContradiction +OAI.Geometry.CAT0Fillings.Euler.OppositeIntegral +OAI.Geometry.CAT0Fillings.Euler.OppositePointwise +OAI.Geometry.CAT0Fillings.Fillings.Attainment +OAI.Geometry.CAT0Fillings.Fillings.Compact +OAI.Geometry.CAT0Fillings.Fillings.ConeBound +OAI.Geometry.CAT0Fillings.Fillings.Existence +OAI.Geometry.CAT0Fillings.Fillings.WeightedCone +OAI.Geometry.CAT0Fillings.Geometry.Ball +OAI.Geometry.CAT0Fillings.Geometry.Comparison +OAI.Geometry.CAT0Fillings.Geometry.Determinant +OAI.Geometry.CAT0Fillings.Geometry.DeterminantBound +OAI.Geometry.CAT0Fillings.Geometry.HilbertDifferential +OAI.Geometry.CAT0Fillings.Geometry.MatrixRows +OAI.Geometry.CAT0Fillings.Geometry.Polarization +OAI.Geometry.CAT0Fillings.Gradient.Chart +OAI.Geometry.CAT0Fillings.Gradient.ClosedLinear +OAI.Geometry.CAT0Fillings.Gradient.CyclePairing +OAI.Geometry.CAT0Fillings.Gradient.Determinant +OAI.Geometry.CAT0Fillings.Gradient.HilbertAtlas +OAI.Geometry.CAT0Fillings.Gradient.Multiplier +OAI.Geometry.CAT0Fillings.Gradient.Pairing +OAI.Geometry.CAT0Fillings.Isoperimetry.SmallCells +OAI.Geometry.CAT0Fillings.Isoperimetry.SmallSets +OAI.Geometry.CAT0Fillings.Jacobian.ClosedForms +OAI.Geometry.CAT0Fillings.Jacobian.Coordinates +OAI.Geometry.CAT0Fillings.Jacobian.HeadEstimates +OAI.Geometry.CAT0Fillings.Jacobian.Lipschitz +OAI.Geometry.CAT0Fillings.Jacobian.Mixed +OAI.Geometry.CAT0Fillings.Jacobian.Smoothing +OAI.Geometry.CAT0Fillings.Jacobian.WeakLimits +OAI.Geometry.CAT0Fillings.Main +OAI.Geometry.CAT0Fillings.Mass.Approximation +OAI.Geometry.CAT0Fillings.Mass.Convolution +OAI.Geometry.CAT0Fillings.Mass.Duality +OAI.Geometry.CAT0Fillings.Mass.Gradient +OAI.Geometry.CAT0Fillings.Mass.IntrinsicCoarea +OAI.Geometry.CAT0Fillings.Mass.TestDensity +OAI.Geometry.CAT0Fillings.Minimizers.CriticalEnergy +OAI.Geometry.CAT0Fillings.Minimizers.Euler +OAI.Geometry.CAT0Fillings.Minimizers.Geometric +OAI.Geometry.CAT0Fillings.Minimizers.Minimum +OAI.Geometry.CAT0Fillings.Minimizers.NoLoss +OAI.Geometry.CAT0Fillings.Minimizers.Nonnegative +OAI.Geometry.CAT0Fillings.Minimizers.Normalization +OAI.Geometry.CAT0Fillings.Minimizers.SpatialVariation +OAI.Geometry.CAT0Fillings.Minimizers.WeakSequence +OAI.Geometry.CAT0Fillings.Model +OAI.Geometry.CAT0Fillings.Powers.Absorption +OAI.Geometry.CAT0Fillings.Powers.ClosedLimit +OAI.Geometry.CAT0Fillings.Powers.EulerMoments +OAI.Geometry.CAT0Fillings.Powers.PolynomialBound +OAI.Geometry.CAT0Fillings.Powers.Potential +OAI.Geometry.CAT0Fillings.Powers.Slope +OAI.Geometry.CAT0Fillings.Powers.Truncated +OAI.Geometry.CAT0Fillings.Prism.Action +OAI.Geometry.CAT0Fillings.Prism.Boundary +OAI.Geometry.CAT0Fillings.Prism.Chart +OAI.Geometry.CAT0Fillings.Prism.ClosedCylinder +OAI.Geometry.CAT0Fillings.Prism.ClosedFamily +OAI.Geometry.CAT0Fillings.Prism.ConeMass +OAI.Geometry.CAT0Fillings.Prism.Differential +OAI.Geometry.CAT0Fillings.Prism.Family +OAI.Geometry.CAT0Fillings.Prism.IntegralAction +OAI.Geometry.CAT0Fillings.Prism.Mass +OAI.Geometry.CAT0Fillings.Prism.MixedMass +OAI.Geometry.CAT0Fillings.Prism.TimeAction +OAI.Geometry.CAT0Fillings.Prism.TimeCoordinate +OAI.Geometry.CAT0Fillings.Radial.ChartMass +OAI.Geometry.CAT0Fillings.Radial.ClosedInequality +OAI.Geometry.CAT0Fillings.Radial.Extension +OAI.Geometry.CAT0Fillings.Radial.FirstVariation +OAI.Geometry.CAT0Fillings.Radial.Integrability +OAI.Geometry.CAT0Fillings.Radial.IntegralDerivative +OAI.Geometry.CAT0Fillings.Radial.IntrinsicSlope +OAI.Geometry.CAT0Fillings.Radial.MassComparison +OAI.Geometry.CAT0Fillings.Radial.MeasurableBound +OAI.Geometry.CAT0Fillings.Radial.MetricBound +OAI.Geometry.CAT0Fillings.Radial.MetricDerivative +OAI.Geometry.CAT0Fillings.Radial.MetricSlope +OAI.Geometry.CAT0Fillings.Radial.NormalizedDerivative +OAI.Geometry.CAT0Fillings.Radial.ScalarDerivative +OAI.Geometry.CAT0Fillings.Radial.SeriesDerivative +OAI.Geometry.CAT0Fillings.Radial.SpatialBound +OAI.Geometry.CAT0Fillings.Radial.SpatialForm +OAI.Geometry.CAT0Fillings.Radial.TestBound +OAI.Geometry.CAT0Fillings.Radial.TotalBound +OAI.Geometry.CAT0Fillings.Radial.TotalDeterminant +OAI.Geometry.CAT0Fillings.Radial.TotalForm +OAI.Geometry.CAT0Fillings.Radial.UniformSlope +OAI.Geometry.CAT0Fillings.Radial.WholeMass +OAI.Geometry.CAT0Fillings.Rearrangement.Distribution +OAI.Geometry.CAT0Fillings.Rearrangement.Energy +OAI.Geometry.CAT0Fillings.Rearrangement.Euclidean +OAI.Geometry.CAT0Fillings.Rearrangement.Gradient +OAI.Geometry.CAT0Fillings.Rearrangement.Inverse +OAI.Geometry.CAT0Fillings.Rearrangement.Sobolev +OAI.Geometry.CAT0Fillings.Rearrangement.Substitution +OAI.Geometry.CAT0Fillings.Reconstruction.AtomCarrier +OAI.Geometry.CAT0Fillings.Reconstruction.AtomGraphs +OAI.Geometry.CAT0Fillings.Reconstruction.BorelAtoms +OAI.Geometry.CAT0Fillings.Reconstruction.GraphAssembly +OAI.Geometry.CAT0Fillings.Reconstruction.GraphCharts +OAI.Geometry.CAT0Fillings.Reconstruction.Identification +OAI.Geometry.CAT0Fillings.Reconstruction.JointCharts +OAI.Geometry.CAT0Fillings.Reconstruction.LipschitzPieces +OAI.Geometry.CAT0Fillings.Reconstruction.Localization +OAI.Geometry.CAT0Fillings.Reconstruction.ScalarCharts +OAI.Geometry.CAT0Fillings.Reconstruction.ScalarKernel +OAI.Geometry.CAT0Fillings.Reconstruction.Slices +OAI.Geometry.CAT0Fillings.Reconstruction.Uniqueness +OAI.Geometry.CAT0Fillings.Scaling.Extremal +OAI.Geometry.CAT0Fillings.Scaling.HighCoefficient +OAI.Geometry.CAT0Fillings.Scaling.Metric +OAI.Geometry.CAT0Fillings.Slices.Approximation +OAI.Geometry.CAT0Fillings.Slices.BorelAction +OAI.Geometry.CAT0Fillings.Slices.Carriers +OAI.Geometry.CAT0Fillings.Slices.FullCarrier +OAI.Geometry.CAT0Fillings.Slices.FullSlices +OAI.Geometry.CAT0Fillings.Slices.JointKernel +OAI.Geometry.CAT0Fillings.Slices.Limits +OAI.Geometry.CAT0Fillings.Slices.NormalBudget +OAI.Geometry.CAT0Fillings.Slices.WeakApproximation +OAI.Geometry.CAT0Fillings.Slicing.BoundaryTests +OAI.Geometry.CAT0Fillings.Slicing.CoordinateChart +OAI.Geometry.CAT0Fillings.Slicing.CoordinateCoarea +OAI.Geometry.CAT0Fillings.Slicing.CoordinateDerivative +OAI.Geometry.CAT0Fillings.Slicing.CoordinateIntegral +OAI.Geometry.CAT0Fillings.Slicing.CycleCoarea +OAI.Geometry.CAT0Fillings.Slicing.EuclideanSplit +OAI.Geometry.CAT0Fillings.Slicing.GeneralCoarea +OAI.Geometry.CAT0Fillings.Slicing.IntegralBoundary +OAI.Geometry.CAT0Fillings.Slicing.Iterated +OAI.Geometry.CAT0Fillings.Slicing.NormalRestriction +OAI.Geometry.CAT0Fillings.Slicing.ProfileIntegral +OAI.Geometry.CAT0Fillings.Slicing.Profiles +OAI.Geometry.CAT0Fillings.Slicing.RectifiableCoarea +OAI.Geometry.CAT0Fillings.Slicing.ScalarCoarea +OAI.Geometry.CAT0Fillings.Slicing.SmoothCutoff +OAI.Geometry.CAT0Fillings.Slicing.StripMass +OAI.Geometry.CAT0Fillings.Slicing.Superlevels +OAI.Geometry.CAT0Fillings.Slicing.WeakRestriction +OAI.Geometry.CAT0Fillings.Slicing.WeakSlices +OAI.Geometry.CAT0Fillings.Sobolev.AlmostSharp +OAI.Geometry.CAT0Fillings.Sobolev.BrezisLieb +OAI.Geometry.CAT0Fillings.Sobolev.Compact +OAI.Geometry.CAT0Fillings.Sobolev.Completion +OAI.Geometry.CAT0Fillings.Sobolev.Constant +OAI.Geometry.CAT0Fillings.Sobolev.CriticalNorm +OAI.Geometry.CAT0Fillings.Sobolev.SmallSupport +OAI.Geometry.CAT0Fillings.Sobolev.Truncation +OAI.Geometry.CAT0Fillings.Swept.Current +OAI.Geometry.CAT0Fillings.Swept.Measure +OAI.Geometry.CAT0Fillings.Swept.RadialChart +OAI.Geometry.CAT0Fillings.Swept.WholeMass +OAI.Geometry.CAT0Fillings.Tangent.Blowup +OAI.Geometry.CAT0Fillings.Tangent.Coordinates +OAI.Geometry.CAT0Fillings.Tangent.CurrentDensity +OAI.Geometry.CAT0Fillings.Tangent.Kernel +OAI.Geometry.CAT0Fillings.Tangent.LocalChart +OAI.Geometry.CAT0Fillings.Tangent.Quadratic +OAI.Geometry.CAT0Fillings.Tangent.Transfer +OAI.Geometry.CAT0Fillings.Transport.AbsoluteContinuity +OAI.Geometry.CAT0Fillings.Transport.Cauchy +OAI.Geometry.CAT0Fillings.Transport.Integrals +OAI.Geometry.CAT0Fillings.Transport.Normalization +OAI.Geometry.CAT0Fillings.Transport.Proper +OAI.Geometry.CAT0Fillings.Transport.RadialCDF +OAI.Geometry.CAT0Fillings.Transport.RadialMoments +OAI.Geometry.CAT0Fillings.Transport.Sharp +OAI.Geometry.CAT0Fillings.Transport.Support +OAI.Geometry.CAT0Fillings.Variational.Ekeland +OAI.Geometry.CAT0Fillings.Variational.Extremizer +OAI.Geometry.CAT0Fillings.Variational.LowerContinuity diff --git a/tasks/sharp-cat0-filling/solution/reference.py b/tasks/sharp-cat0-filling/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sharp-cat0-filling/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sharp-cat0-filling/solution/solve.sh b/tasks/sharp-cat0-filling/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..31ebf5584024a70f3a2c85150ccab9047b6eef3c --- /dev/null +++ b/tasks/sharp-cat0-filling/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SharpCAT0Filling, i.e. module OAI.Geometry.CAT0Fillings.Main and the +# 330 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.CAT0Fillings.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SharpCAT0Filling" diff --git a/tasks/sharp-cat0-filling/task.toml b/tasks/sharp-cat0-filling/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0266bb4d7d3de173fb7e5079590d7e0f4f2bf233 --- /dev/null +++ b/tasks/sharp-cat0-filling/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sharp-cat0-filling" +version = "1.0.0" +description = "Prove SharpCAT0Filling (openai/math family 337: Cartan–Hadamard isoperimetry and CAT$(0)$ fillings) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SharpCAT0Filling.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SharpCAT0Filling" +family = "337" +family_title = "Cartan–Hadamard isoperimetry and CAT$(0)$ fillings" +subject = "Differential geometry" +theorems = ["OAI.CAT0Fillings.sharp_integral_filling"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.CAT0Fillings.Main" +reference_modules = 330 +reference_lean_bytes = 2329103 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1201 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13796 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sharp-cat0-filling/tests/Challenge.lean b/tasks/sharp-cat0-filling/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..65e1f6264588c62968a509ef296f1d2822bcc823 --- /dev/null +++ b/tasks/sharp-cat0-filling/tests/Challenge.lean @@ -0,0 +1,146 @@ +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped Topology ENNReal NNReal + +namespace CAT0Fillings + +attribute [local instance] Classical.propDecidable + +universe u + +abbrev Euc (k : ℕ) := EuclideanSpace ℝ (Fin k) +abbrev Functional (X : Type u) (k : ℕ) := (X → ℝ) → (Fin k → X → ℝ) → ℝ + +section MetricCurrents + +variable {X : Type u} [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + +def BoundedLip (b : X → ℝ) : Prop := + (∃ K : ℝ≥0, LipschitzWith K b) ∧ ∃ M : ℝ, ∀ x, |b x| ≤ M + +def Admissible {k : ℕ} (b : X → ℝ) (π : Fin k → X → ℝ) : Prop := + BoundedLip b ∧ ∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i) + +def Controls {k : ℕ} (T : Functional X k) (μ : Measure X) : Prop := + ∀ (b : X → ℝ) (π : Fin k → X → ℝ), BoundedLip b → + (∀ i, LipschitzWith 1 (π i)) → + |T b π| ≤ ∫ x, |b x| ∂μ + +noncomputable def mass {k : ℕ} (T : Functional X k) : ℝ := + sInf {r : ℝ | ∃ μ : Measure X, + IsFiniteMeasure μ ∧ Controls T μ ∧ r = μ.real univ} + +structure IsMetricCurrent {k : ℕ} (T : Functional X k) : Prop where + offDomain : ∀ b π, ¬Admissible b π → T b π = 0 + linearFirst : ∀ b₁ b₂ π (a c : ℝ), BoundedLip b₁ → BoundedLip b₂ → + (∀ i, ∃ K : ℝ≥0, LipschitzWith K (π i)) → + T (fun x => a * b₁ x + c * b₂ x) π = a * T b₁ π + c * T b₂ π + linearCoord : ∀ b π i f (a c : ℝ), Admissible b π → + (∃ K : ℝ≥0, LipschitzWith K f) → + T b (Function.update π i (fun x => a * π i x + c * f x)) = + a * T b π + c * T b (Function.update π i f) + sequentialContinuity : ∀ b π (πs : ℕ → Fin k → X → ℝ), BoundedLip b → + (∀ i, ∃ K : ℝ≥0, ∀ j, LipschitzWith K (πs j i)) → + (∀ i x, Tendsto (fun j => πs j i x) atTop (𝓝 (π i x))) → + Tendsto (fun j => T b (πs j)) atTop (𝓝 (T b π)) + locality : ∀ b π, Admissible b π → + (∃ (i : Fin k) (U : Set X) (c : ℝ), IsOpen U ∧ Function.support b ⊆ U ∧ + ∀ x ∈ U, π i x = c) → T b π = 0 + finiteMass : ∃ μ : Measure X, IsFiniteMeasure μ ∧ Controls T μ + +noncomputable def boundarySucc {k : ℕ} (T : Functional X (k + 1)) : Functional X k := + fun b π => if Admissible b π then T (fun _ => 1) (Matrix.vecCons b π) else 0 + +noncomputable def boundary : {k : ℕ} → Functional X k → Functional X (k - 1) + | 0, _ => fun _ _ => 0 + | _ + 1, T => boundarySucc T + +structure IntegerChart (X : Type u) [MetricSpace X] (k : ℕ) where + domain : Set (Euc k) + borel : MeasurableSet domain + bounded : Bornology.IsBounded domain + param : domain → X + bilipschitz : ∃ L U : ℝ≥0, LipschitzWith L param ∧ AntilipschitzWith U param + multiplicity : Euc k → ℤ + integrable : Integrable (fun z => (multiplicity z : ℝ)) (volume.restrict domain) + +namespace IntegerChart + +variable {k : ℕ} (C : IntegerChart X k) + +noncomputable def scalar (f : X → ℝ) (z : Euc k) : ℝ := + if hz : z ∈ C.domain then f (C.param ⟨z, hz⟩) else 0 + +noncomputable def jacobian (π : Fin k → X → ℝ) (z : Euc k) : ℝ := + Matrix.det (fun i j => + (fderivWithin ℝ (C.scalar (π i)) C.domain z) (EuclideanSpace.single j 1)) + +noncomputable def action : Functional X k := + fun b π => if Admissible b π then + ∫ z in C.domain, (C.multiplicity z : ℝ) * C.scalar b z * C.jacobian π z + else 0 + +def image : Set X := Set.range C.param + +end IntegerChart + +def IntegerRectifiable {k : ℕ} (T : Functional X k) : Prop := + ∃ C : ℕ → IntegerChart X k, + Pairwise (fun i j => Disjoint (C i).image (C j).image) ∧ + (∀ i, IsMetricCurrent (C i).action) ∧ + Summable (fun i => mass (C i).action) ∧ + ∀ b π, T b π = ∑' i, (C i).action b π + +def IsIntegral : (k : ℕ) → Functional X k → Prop + | 0, T => IsMetricCurrent T ∧ IntegerRectifiable T + | _ + 1, T => IsMetricCurrent T ∧ IntegerRectifiable T ∧ + IsMetricCurrent (boundarySucc T) ∧ IntegerRectifiable (boundarySucc T) + +abbrev IntegralCurrent (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] + (k : ℕ) := { T : Functional X k // IsIntegral k T } + +def CompactlySupported {k : ℕ} (T : Functional X k) : Prop := + ∃ K : Set X, IsCompact K ∧ + ∀ b π, Admissible b π → (∀ x ∈ K, b x = 0) → T b π = 0 + +def IsCycle {k : ℕ} (T : Functional X k) : Prop := boundary T = fun _ _ => 0 + +end MetricCurrents + +section Geometry +variable (X : Type u) [MetricSpace X] + +def IsCAT0 : Prop := + ∃ segment : X → X → ℝ → X, + (∀ x y, segment x y 0 = x ∧ segment x y 1 = y) ∧ + (∀ x y s t, s ∈ Icc (0 : ℝ) 1 → t ∈ Icc (0 : ℝ) 1 → + dist (segment x y s) (segment x y t) = |s - t| * dist x y) ∧ + (∀ o x y s t, s ∈ Icc (0 : ℝ) 1 → t ∈ Icc (0 : ℝ) 1 → + dist (segment o x s) (segment o y t) ^ 2 ≤ + (s * dist o x - t * dist o y) ^ 2 + + s * t * ((dist x y) ^ 2 - (dist o x - dist o y) ^ 2)) + +end Geometry + +noncomputable def omega (k : ℕ) : ℝ := + (volume (Metric.ball (0 : Euc k) 1)).toReal +noncomputable def sphereArea (n : ℕ) : ℝ := (n + 1 : ℝ) * omega (n + 1) +noncomputable def fillingCoefficient (n : ℕ) : ℝ := + 1 / ((n + 1 : ℝ) * (sphereArea n) ^ (1 / (n : ℝ))) +noncomputable def fillingPower (n : ℕ) : ℝ := (n + 1 : ℝ) / (n : ℝ) + +theorem sharp_integral_filling + (X : Type u) [MetricSpace X] [MeasurableSpace X] [BorelSpace X] [ProperSpace X] + (hX : IsCAT0 X) (n : ℕ) (hn : 2 ≤ n) (T : IntegralCurrent X n) + (hTc : CompactlySupported T.val) (hTz : IsCycle T.val) : + ∃ S : IntegralCurrent X (n + 1), CompactlySupported S.val ∧ + boundarySucc S.val = T.val ∧ + mass S.val ≤ fillingCoefficient n * (mass T.val) ^ fillingPower n := by + sorry + +end CAT0Fillings + +end OAI diff --git a/tasks/sharp-cat0-filling/tests/grade.py b/tasks/sharp-cat0-filling/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sharp-cat0-filling/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sharp-cat0-filling/tests/task.json b/tasks/sharp-cat0-filling/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4bedc97d116b3f55c45e3306a8007acd1c28a969 --- /dev/null +++ b/tasks/sharp-cat0-filling/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SharpCAT0Filling", + "comparator": { + "theorem_names": [ + "OAI.CAT0Fillings.sharp_integral_filling" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 12896 +} \ No newline at end of file diff --git a/tasks/sharp-cat0-filling/tests/test.sh b/tasks/sharp-cat0-filling/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sharp-cat0-filling/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sharp-threshold/environment/Dockerfile b/tasks/sharp-threshold/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sharp-threshold/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sharp-threshold/environment/fetch_mathlib.sh b/tasks/sharp-threshold/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sharp-threshold/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sharp-threshold/environment/lake-manifest.json b/tasks/sharp-threshold/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sharp-threshold/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sharp-threshold/environment/lakefile.lean b/tasks/sharp-threshold/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sharp-threshold/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sharp-threshold/environment/lean_setup.sh b/tasks/sharp-threshold/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sharp-threshold/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sharp-threshold/environment/pack_submission.py b/tasks/sharp-threshold/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sharp-threshold/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sharp-threshold/instruction.md b/tasks/sharp-threshold/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f80d15e351d18d151daa026e15ca67b8de0da4b6 --- /dev/null +++ b/tasks/sharp-threshold/instruction.md @@ -0,0 +1,114 @@ +# openai/math challenge `SharpThreshold` (family 186) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 186 of the release, *The Friedgut–Kalai graph and hypergraph threshold conjectures* +(Combinatorics). The family as a whole: Proves the Friedgut–Kalai threshold-width conjectures for graphs and fixed-uniformity hypergraphs. For fixed $0<\varepsilon<1/2$, every nontrivial increasing relabeling-invariant property crosses from probability $\varepsilon$ to $1-\varepsilon$ within width $O((\log n)^{-2})$ for graphs and $O_r((\log n)^{-r/(r-1)})$ for $r$-uniform hypergraphs, $r\ge3$. The hypergraph influence bound also applies to nonmonotone properties. + +The challenge is `SharpThreshold`, also at `/opt/openai-math/challenges/SharpThreshold.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem313 + +abbrev GraphEdge (n : ℕ) := {e : Finset (Fin n) // e.card = 2} + +abbrev GraphConfig (n : ℕ) := GraphEdge n → Bool + +def permEdge {n : ℕ} (π : Equiv.Perm (Fin n)) (e : GraphEdge n) : GraphEdge n := + ⟨e.1.map π.toEmbedding, by simpa using e.2⟩ + +def permuteConfig {n : ℕ} (π : Equiv.Perm (Fin n)) + (x : GraphConfig n) : GraphConfig n := + fun e => x (permEdge π.symm e) + +def VertexInvariant {n : ℕ} (f : GraphConfig n → Bool) : Prop := + ∀ (π : Equiv.Perm (Fin n)) (x : GraphConfig n), + f (permuteConfig π x) = f x + +def ConfigLE {n : ℕ} (x y : GraphConfig n) : Prop := + ∀ e, x e = true → y e = true + +def IncreasingGraphProperty {n : ℕ} (f : GraphConfig n → Bool) : Prop := + ∀ x y, ConfigLE x y → f x = true → f y = true + +def NontrivialGraphProperty {n : ℕ} (f : GraphConfig n → Bool) : Prop := + (∃ x, f x = true) ∧ (∃ x, f x = false) + +def boolReal (b : Bool) : ℝ := + match b with + | false => 0 + | true => 1 + +def graphWeight {n : ℕ} (p : ℝ) (x : GraphConfig n) : ℝ := by + classical + exact Finset.univ.prod (fun e : GraphEdge n => + if x e = true then p else 1 - p) + +def graphMean {n : ℕ} (p : ℝ) (f : GraphConfig n → Bool) : ℝ := by + classical + exact Finset.univ.sum (fun x : GraphConfig n => + graphWeight p x * boolReal (f x)) + +def graphQuantile {n : ℕ} (a : ℝ) (f : GraphConfig n → Bool) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ graphMean p f ≥ a} + +theorem sharp_threshold_width : + ∀ (n : ℕ) (f : GraphConfig n → Bool) (ε : ℝ), + 2 ≤ n → VertexInvariant f → IncreasingGraphProperty f → + NontrivialGraphProperty f → 0 < ε → ε < (1 / 2 : ℝ) → + graphQuantile (1 - ε) f - graphQuantile ε f ≤ + ((2 : ℝ) ^ 19 / (Real.log (n : ℝ)) ^ 2) * Real.log (1 / (2 * ε)) := by + sorry + +end Problem313 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SharpThreshold.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Problem313.sharp_threshold_width` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sharp-threshold/solution/closure.txt b/tasks/sharp-threshold/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..2890b02958aaad67e2015e41f41692515e278e7a --- /dev/null +++ b/tasks/sharp-threshold/solution/closure.txt @@ -0,0 +1,78 @@ +OAI.Combinatorics.SharpThreshold.BlockAverage +OAI.Combinatorics.SharpThreshold.BlockCapture +OAI.Combinatorics.SharpThreshold.BlockCounting +OAI.Combinatorics.SharpThreshold.BlockIncidence +OAI.Combinatorics.SharpThreshold.BlockInfluence +OAI.Combinatorics.SharpThreshold.BlockLowDegree +OAI.Combinatorics.SharpThreshold.BlockOrbit +OAI.Combinatorics.SharpThreshold.BlockOrbitSubtype +OAI.Combinatorics.SharpThreshold.BlockOrbits +OAI.Combinatorics.SharpThreshold.BlockParameters +OAI.Combinatorics.SharpThreshold.BlockRestrictionSymmetry +OAI.Combinatorics.SharpThreshold.BlockSize +OAI.Combinatorics.SharpThreshold.BlockSymmetry +OAI.Combinatorics.SharpThreshold.BooleanDerivative +OAI.Combinatorics.SharpThreshold.BooleanProjection +OAI.Combinatorics.SharpThreshold.DirichletEnergy +OAI.Combinatorics.SharpThreshold.ExpQuadratic +OAI.Combinatorics.SharpThreshold.FiniteParseval +OAI.Combinatorics.SharpThreshold.FourierAnalysis +OAI.Combinatorics.SharpThreshold.FourierBasis +OAI.Combinatorics.SharpThreshold.FourierDerivative +OAI.Combinatorics.SharpThreshold.FourierDirichlet +OAI.Combinatorics.SharpThreshold.FourierHypercontractive +OAI.Combinatorics.SharpThreshold.FourierNoise +OAI.Combinatorics.SharpThreshold.FourierOption +OAI.Combinatorics.SharpThreshold.FourierOptionExpectation +OAI.Combinatorics.SharpThreshold.FourierOrthogonality +OAI.Combinatorics.SharpThreshold.FourierProjection +OAI.Combinatorics.SharpThreshold.FourierReindex +OAI.Combinatorics.SharpThreshold.FourierRestriction +OAI.Combinatorics.SharpThreshold.FourierRestrictionMass +OAI.Combinatorics.SharpThreshold.FourierSupportSplit +OAI.Combinatorics.SharpThreshold.FourierVariance +OAI.Combinatorics.SharpThreshold.GraphBlockAverage +OAI.Combinatorics.SharpThreshold.GraphBlockCapture +OAI.Combinatorics.SharpThreshold.GraphQuantile +OAI.Combinatorics.SharpThreshold.GraphRestrictionInfluence +OAI.Combinatorics.SharpThreshold.GraphSupport +OAI.Combinatorics.SharpThreshold.GraphSymmetry +OAI.Combinatorics.SharpThreshold.GraphVarianceBound +OAI.Combinatorics.SharpThreshold.HypercontractiveTensor +OAI.Combinatorics.SharpThreshold.InfluenceReindex +OAI.Combinatorics.SharpThreshold.LowDegree +OAI.Combinatorics.SharpThreshold.LowDegreeBounds +OAI.Combinatorics.SharpThreshold.LowDegreeConstants +OAI.Combinatorics.SharpThreshold.LowDegreeCounting +OAI.Combinatorics.SharpThreshold.LowDegreeInfluence +OAI.Combinatorics.SharpThreshold.LowDegreeL4 +OAI.Combinatorics.SharpThreshold.LowDegreeNumerical +OAI.Combinatorics.SharpThreshold.LowDegreeSupport +OAI.Combinatorics.SharpThreshold.Main +OAI.Combinatorics.SharpThreshold.MeanEndpoints +OAI.Combinatorics.SharpThreshold.Model +OAI.Combinatorics.SharpThreshold.NoiseKernel +OAI.Combinatorics.SharpThreshold.OrbitInfluence +OAI.Combinatorics.SharpThreshold.Permutation +OAI.Combinatorics.SharpThreshold.Probability +OAI.Combinatorics.SharpThreshold.ProductReindex +OAI.Combinatorics.SharpThreshold.ProductRestriction +OAI.Combinatorics.SharpThreshold.ProjectionIdentities +OAI.Combinatorics.SharpThreshold.ProjectionNorm +OAI.Combinatorics.SharpThreshold.Quantile +OAI.Combinatorics.SharpThreshold.QuantileAnalysis +OAI.Combinatorics.SharpThreshold.RestrictionInfluence +OAI.Combinatorics.SharpThreshold.RestrictionMass +OAI.Combinatorics.SharpThreshold.RestrictionMassSubtype +OAI.Combinatorics.SharpThreshold.Russo +OAI.Combinatorics.SharpThreshold.RussoReindex +OAI.Combinatorics.SharpThreshold.SharpThreshold +OAI.Combinatorics.SharpThreshold.SpectralBounds +OAI.Combinatorics.SharpThreshold.SupportDegree +OAI.Combinatorics.SharpThreshold.SupportDegreeGraph +OAI.Combinatorics.SharpThreshold.SupportIncidence +OAI.Combinatorics.SharpThreshold.ThresholdConstants +OAI.Combinatorics.SharpThreshold.ThresholdODE +OAI.Combinatorics.SharpThreshold.TwoPoint +OAI.Combinatorics.SharpThreshold.VarianceConstants +OAI.Combinatorics.SharpThreshold.VarianceReduction diff --git a/tasks/sharp-threshold/solution/reference.py b/tasks/sharp-threshold/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sharp-threshold/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sharp-threshold/solution/solve.sh b/tasks/sharp-threshold/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ba0558e1cd848a4d6156c41adbe16153ab590467 --- /dev/null +++ b/tasks/sharp-threshold/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SharpThreshold, i.e. module OAI.Combinatorics.SharpThreshold.Main and the +# 78 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.SharpThreshold.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SharpThreshold" diff --git a/tasks/sharp-threshold/task.toml b/tasks/sharp-threshold/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..caf6765e3a4dc23cb7439751363002c3ab363cf9 --- /dev/null +++ b/tasks/sharp-threshold/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sharp-threshold" +version = "1.0.0" +description = "Prove SharpThreshold (openai/math family 186: The Friedgut–Kalai graph and hypergraph threshold conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SharpThreshold.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SharpThreshold" +family = "186" +family_title = "The Friedgut–Kalai graph and hypergraph threshold conjectures" +subject = "Combinatorics" +theorems = ["OAI.Problem313.sharp_threshold_width"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.SharpThreshold.Main" +reference_modules = 78 +reference_lean_bytes = 313943 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 662 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11982 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sharp-threshold/tests/Challenge.lean b/tasks/sharp-threshold/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ef4ccc6106955d4c332dc3d8e6893a1fbe3248d0 --- /dev/null +++ b/tasks/sharp-threshold/tests/Challenge.lean @@ -0,0 +1,63 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace Problem313 + +abbrev GraphEdge (n : ℕ) := {e : Finset (Fin n) // e.card = 2} + +abbrev GraphConfig (n : ℕ) := GraphEdge n → Bool + +def permEdge {n : ℕ} (π : Equiv.Perm (Fin n)) (e : GraphEdge n) : GraphEdge n := + ⟨e.1.map π.toEmbedding, by simpa using e.2⟩ + +def permuteConfig {n : ℕ} (π : Equiv.Perm (Fin n)) + (x : GraphConfig n) : GraphConfig n := + fun e => x (permEdge π.symm e) + +def VertexInvariant {n : ℕ} (f : GraphConfig n → Bool) : Prop := + ∀ (π : Equiv.Perm (Fin n)) (x : GraphConfig n), + f (permuteConfig π x) = f x + +def ConfigLE {n : ℕ} (x y : GraphConfig n) : Prop := + ∀ e, x e = true → y e = true + +def IncreasingGraphProperty {n : ℕ} (f : GraphConfig n → Bool) : Prop := + ∀ x y, ConfigLE x y → f x = true → f y = true + +def NontrivialGraphProperty {n : ℕ} (f : GraphConfig n → Bool) : Prop := + (∃ x, f x = true) ∧ (∃ x, f x = false) + +def boolReal (b : Bool) : ℝ := + match b with + | false => 0 + | true => 1 + +def graphWeight {n : ℕ} (p : ℝ) (x : GraphConfig n) : ℝ := by + classical + exact Finset.univ.prod (fun e : GraphEdge n => + if x e = true then p else 1 - p) + +def graphMean {n : ℕ} (p : ℝ) (f : GraphConfig n → Bool) : ℝ := by + classical + exact Finset.univ.sum (fun x : GraphConfig n => + graphWeight p x * boolReal (f x)) + +def graphQuantile {n : ℕ} (a : ℝ) (f : GraphConfig n → Bool) : ℝ := + sInf {p : ℝ | p ∈ Set.Icc (0 : ℝ) 1 ∧ graphMean p f ≥ a} + +theorem sharp_threshold_width : + ∀ (n : ℕ) (f : GraphConfig n → Bool) (ε : ℝ), + 2 ≤ n → VertexInvariant f → IncreasingGraphProperty f → + NontrivialGraphProperty f → 0 < ε → ε < (1 / 2 : ℝ) → + graphQuantile (1 - ε) f - graphQuantile ε f ≤ + ((2 : ℝ) ^ 19 / (Real.log (n : ℝ)) ^ 2) * Real.log (1 / (2 * ε)) := by + sorry + +end Problem313 + +end + +end OAI diff --git a/tasks/sharp-threshold/tests/grade.py b/tasks/sharp-threshold/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sharp-threshold/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sharp-threshold/tests/task.json b/tasks/sharp-threshold/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fd421d2150c91b8f71eeec68c3d1fee668f43084 --- /dev/null +++ b/tasks/sharp-threshold/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SharpThreshold", + "comparator": { + "theorem_names": [ + "OAI.Problem313.sharp_threshold_width" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11082 +} \ No newline at end of file diff --git a/tasks/sharp-threshold/tests/test.sh b/tasks/sharp-threshold/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sharp-threshold/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/short-egyptian-fractions/environment/Dockerfile b/tasks/short-egyptian-fractions/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/short-egyptian-fractions/environment/fetch_mathlib.sh b/tasks/short-egyptian-fractions/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/short-egyptian-fractions/environment/lake-manifest.json b/tasks/short-egyptian-fractions/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/short-egyptian-fractions/environment/lakefile.lean b/tasks/short-egyptian-fractions/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/short-egyptian-fractions/environment/lean_setup.sh b/tasks/short-egyptian-fractions/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/short-egyptian-fractions/environment/pack_submission.py b/tasks/short-egyptian-fractions/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/short-egyptian-fractions/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/short-egyptian-fractions/instruction.md b/tasks/short-egyptian-fractions/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ea85dc8fe5461b140fa12ab9b67e5d72421030b1 --- /dev/null +++ b/tasks/short-egyptian-fractions/instruction.md @@ -0,0 +1,78 @@ +# openai/math challenge `ShortEgyptianFractions` (family 025) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 025 of the release, *Erd\H{o}s’s short Egyptian-fraction conjecture* +(Number theory). The family as a whole: Every rational $a/b$ with $1\le a (1 : ℚ) / (n : ℚ))).sum = (a : ℚ) / (b : ℚ) + +noncomputable def minLength (a b : ℕ) : ℕ := + sInf {k : ℕ | ∃ ns : List ℕ, IsExpansion a b ns ∧ ns.length = k} + +noncomputable def maxMinLength (b : ℕ) : ℕ := + (Finset.Ico 1 b).sup (fun a => minLength a b) + +theorem main : + (∀ a b : ℕ, 1 ≤ a → a < b → ∃ ns : List ℕ, IsExpansion a b ns) ∧ + ∃ c₁ c₂ : ℝ, 0 < c₁ ∧ 0 < c₂ ∧ ∃ b₀ : ℕ, 2 ≤ b₀ ∧ + ∀ b : ℕ, b₀ ≤ b → + c₁ * Real.log (Real.log (b : ℝ)) ≤ (maxMinLength b : ℝ) ∧ + (maxMinLength b : ℝ) ≤ c₂ * Real.log (Real.log (b : ℝ)) := by + sorry + +end ShortEgyptian + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ShortEgyptianFractions.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ShortEgyptian.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/short-egyptian-fractions/solution/closure.txt b/tasks/short-egyptian-fractions/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee912bfb4200b83a48977bf1d68250ed818a1723 --- /dev/null +++ b/tasks/short-egyptian-fractions/solution/closure.txt @@ -0,0 +1,58 @@ +OAI.NumberTheory.ShortEgyptian.Basic +OAI.NumberTheory.ShortEgyptian.BilinearProducts +OAI.NumberTheory.ShortEgyptian.DenseSplit +OAI.NumberTheory.ShortEgyptian.Density +OAI.NumberTheory.ShortEgyptian.DensityBounds +OAI.NumberTheory.ShortEgyptian.DescentSets +OAI.NumberTheory.ShortEgyptian.DeterministicLists +OAI.NumberTheory.ShortEgyptian.DeterministicMean +OAI.NumberTheory.ShortEgyptian.Distinctness +OAI.NumberTheory.ShortEgyptian.DivisorCover +OAI.NumberTheory.ShortEgyptian.DivisorMoments +OAI.NumberTheory.ShortEgyptian.DivisorWeights +OAI.NumberTheory.ShortEgyptian.DoubleCount +OAI.NumberTheory.ShortEgyptian.EmpiricalDiscrepancy +OAI.NumberTheory.ShortEgyptian.FiniteFourier +OAI.NumberTheory.ShortEgyptian.FirstDerivative +OAI.NumberTheory.ShortEgyptian.FourierDiscrepancy +OAI.NumberTheory.ShortEgyptian.GreedyExistence +OAI.NumberTheory.ShortEgyptian.GreedyPreparation +OAI.NumberTheory.ShortEgyptian.HammingDistance +OAI.NumberTheory.ShortEgyptian.Holder +OAI.NumberTheory.ShortEgyptian.IntervalDifferencing +OAI.NumberTheory.ShortEgyptian.IteratedDifferencing +OAI.NumberTheory.ShortEgyptian.LevelSelection +OAI.NumberTheory.ShortEgyptian.ListConstruction +OAI.NumberTheory.ShortEgyptian.ListSelection +OAI.NumberTheory.ShortEgyptian.LowerBound +OAI.NumberTheory.ShortEgyptian.Main +OAI.NumberTheory.ShortEgyptian.Model +OAI.NumberTheory.ShortEgyptian.MomentAsymptotics +OAI.NumberTheory.ShortEgyptian.MomentDecay +OAI.NumberTheory.ShortEgyptian.MomentRecurrence +OAI.NumberTheory.ShortEgyptian.ParameterBounds +OAI.NumberTheory.ShortEgyptian.PrimeLists +OAI.NumberTheory.ShortEgyptian.PrimeProducts +OAI.NumberTheory.ShortEgyptian.PrimeReciprocals +OAI.NumberTheory.ShortEgyptian.PrimeSplitting +OAI.NumberTheory.ShortEgyptian.ProductCorrelations +OAI.NumberTheory.ShortEgyptian.RandomBounds +OAI.NumberTheory.ShortEgyptian.RandomMoments +OAI.NumberTheory.ShortEgyptian.ReciprocalDifferences +OAI.NumberTheory.ShortEgyptian.ReciprocalEstimates +OAI.NumberTheory.ShortEgyptian.RecurrenceUnrolling +OAI.NumberTheory.ShortEgyptian.ResidueAssembly +OAI.NumberTheory.ShortEgyptian.ResidueDiscrepancy +OAI.NumberTheory.ShortEgyptian.ResidueSystem +OAI.NumberTheory.ShortEgyptian.SamplePartitions +OAI.NumberTheory.ShortEgyptian.ScaleBounds +OAI.NumberTheory.ShortEgyptian.ScaleGeometry +OAI.NumberTheory.ShortEgyptian.SecondDerivative +OAI.NumberTheory.ShortEgyptian.SelectionBounds +OAI.NumberTheory.ShortEgyptian.SmoothBounds +OAI.NumberTheory.ShortEgyptian.TerminalExpansion +OAI.NumberTheory.ShortEgyptian.TerminalScale +OAI.NumberTheory.ShortEgyptian.TruncatedDivisors +OAI.NumberTheory.ShortEgyptian.UpperAssembly +OAI.NumberTheory.ShortEgyptian.WindowDiscrepancy +OAI.NumberTheory.ShortEgyptian.WindowSpectrum diff --git a/tasks/short-egyptian-fractions/solution/reference.py b/tasks/short-egyptian-fractions/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/short-egyptian-fractions/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/short-egyptian-fractions/solution/solve.sh b/tasks/short-egyptian-fractions/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d4b446c79e81ed8da5c151b0dc979cdb6eb6e19 --- /dev/null +++ b/tasks/short-egyptian-fractions/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ShortEgyptianFractions, i.e. module OAI.NumberTheory.ShortEgyptian.Main and the +# 58 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.ShortEgyptian.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ShortEgyptianFractions" diff --git a/tasks/short-egyptian-fractions/task.toml b/tasks/short-egyptian-fractions/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ee86598d4936217cf8e33f225065a6f701c27098 --- /dev/null +++ b/tasks/short-egyptian-fractions/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/short-egyptian-fractions" +version = "1.0.0" +description = "Prove ShortEgyptianFractions (openai/math family 025: Erd\\H{o}s’s short Egyptian-fraction conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "number-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ShortEgyptianFractions.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ShortEgyptianFractions" +family = "025" +family_title = "Erd\\H{o}s’s short Egyptian-fraction conjecture" +subject = "Number theory" +theorems = ["OAI.ShortEgyptian.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.ShortEgyptian.Main" +reference_modules = 58 +reference_lean_bytes = 383383 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 818 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12045 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/short-egyptian-fractions/tests/Challenge.lean b/tasks/short-egyptian-fractions/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..da06f4ee1a07f69e099965b785ee6d0430d7b4ad --- /dev/null +++ b/tasks/short-egyptian-fractions/tests/Challenge.lean @@ -0,0 +1,27 @@ +import Mathlib + +namespace OAI + +namespace ShortEgyptian + +def IsExpansion (a b : ℕ) (ns : List ℕ) : Prop := + ns.Pairwise (· < ·) ∧ (∀ n ∈ ns, 2 ≤ n) ∧ + (ns.map (fun n => (1 : ℚ) / (n : ℚ))).sum = (a : ℚ) / (b : ℚ) + +noncomputable def minLength (a b : ℕ) : ℕ := + sInf {k : ℕ | ∃ ns : List ℕ, IsExpansion a b ns ∧ ns.length = k} + +noncomputable def maxMinLength (b : ℕ) : ℕ := + (Finset.Ico 1 b).sup (fun a => minLength a b) + +theorem main : + (∀ a b : ℕ, 1 ≤ a → a < b → ∃ ns : List ℕ, IsExpansion a b ns) ∧ + ∃ c₁ c₂ : ℝ, 0 < c₁ ∧ 0 < c₂ ∧ ∃ b₀ : ℕ, 2 ≤ b₀ ∧ + ∀ b : ℕ, b₀ ≤ b → + c₁ * Real.log (Real.log (b : ℝ)) ≤ (maxMinLength b : ℝ) ∧ + (maxMinLength b : ℝ) ≤ c₂ * Real.log (Real.log (b : ℝ)) := by + sorry + +end ShortEgyptian + +end OAI diff --git a/tasks/short-egyptian-fractions/tests/grade.py b/tasks/short-egyptian-fractions/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/short-egyptian-fractions/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/short-egyptian-fractions/tests/task.json b/tasks/short-egyptian-fractions/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f44d9b765fcad1d7361ce25762ce13f3cd9a5de7 --- /dev/null +++ b/tasks/short-egyptian-fractions/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ShortEgyptianFractions", + "comparator": { + "theorem_names": [ + "OAI.ShortEgyptian.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11145 +} \ No newline at end of file diff --git a/tasks/short-egyptian-fractions/tests/test.sh b/tasks/short-egyptian-fractions/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/short-egyptian-fractions/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sidorenko-counterexample/environment/Dockerfile b/tasks/sidorenko-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sidorenko-counterexample/environment/fetch_mathlib.sh b/tasks/sidorenko-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sidorenko-counterexample/environment/lake-manifest.json b/tasks/sidorenko-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sidorenko-counterexample/environment/lakefile.lean b/tasks/sidorenko-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sidorenko-counterexample/environment/lean_setup.sh b/tasks/sidorenko-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sidorenko-counterexample/environment/pack_submission.py b/tasks/sidorenko-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sidorenko-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sidorenko-counterexample/instruction.md b/tasks/sidorenko-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3a4e18ce04cf39b7b88391fe469a93a884104a3f --- /dev/null +++ b/tasks/sidorenko-counterexample/instruction.md @@ -0,0 +1,98 @@ +# openai/math challenge `SidorenkoCounterexample` (family 161) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 161 of the release, *Counterexamples to Sidorenko's conjecture and the forcing conjecture* +(Combinatorics). The family as a whole: Disproves Sidorenko's conjecture with a connected bipartite pattern on $35$ vertices and $66$ edges that occurs less frequently than in a random graph of the same edge density. The same pattern disproves the forcing conjecture of Skokan and Thoma: matching its density and the edge density of a constant graphon need not force quasirandomness. + +The challenge is `SidorenkoCounterexample`, also at `/opt/openai-math/challenges/SidorenkoCounterexample.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! # A finite counterexample to Sidorenko's conjecture + +The pattern is the incidence graph of the 22 triples in Table 1 of the source. +Homomorphism density counts all edge-preserving maps, including noninjective maps. +-/ + +namespace SidorenkoCounterexample + +def faces : Fin 22 → Finset (Fin 13) := ![ + {0,1,3}, {0,1,9}, {0,2,3}, {0,2,9}, {1,3,10}, {1,7,10}, + {1,7,12}, {1,9,12}, {2,3,4}, {2,4,9}, {3,4,11}, {3,10,11}, + {4,8,9}, {4,8,11}, {5,6,7}, {5,6,11}, {5,7,10}, {5,10,11}, + {6,7,12}, {6,8,11}, {6,8,12}, {8,9,12}] + +abbrev PatternVertex := Fin 13 ⊕ Fin 22 + +def incidence : PatternVertex → PatternVertex → Prop + | .inl point, .inr face => point ∈ faces face + | .inr face, .inl point => point ∈ faces face + | _, _ => False + +def H : SimpleGraph PatternVertex where + Adj := incidence + symm.symm := by intro left right; cases left <;> cases right <;> simp [incidence] + loopless.irrefl := by intro vertex; cases vertex <;> simp [incidence] + +noncomputable def homCount {V W : Type*} (F : SimpleGraph V) (G : SimpleGraph W) : ℕ := + Nat.card {hom : V → W // ∀ left right, F.Adj left right → G.Adj (hom left) (hom right)} + +noncomputable def homDensity {V W : Type*} (F : SimpleGraph V) (G : SimpleGraph W) : ℝ := + (homCount F G : ℝ) / (Nat.card W : ℝ) ^ Nat.card V + +noncomputable def edgeDensity {W : Type*} (G : SimpleGraph W) : ℝ := + 2 * (Nat.card G.edgeSet : ℝ) / (Nat.card W : ℝ) ^ 2 + +/-- A finite simple host with at least one edge violates Sidorenko's inequality. -/ +theorem main : ∃ size : ℕ, 0 < size ∧ ∃ host : SimpleGraph (Fin size), + (∃ left right, host.Adj left right) ∧ homDensity H host < (edgeDensity host) ^ 66 := by + sorry + +end SidorenkoCounterexample + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SidorenkoCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SidorenkoCounterexample.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sidorenko-counterexample/solution/closure.txt b/tasks/sidorenko-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b795ed9e9ff78bb71e96331f4eda543c12347170 --- /dev/null +++ b/tasks/sidorenko-counterexample/solution/closure.txt @@ -0,0 +1,35 @@ +OAI.Combinatorics.Sidorenko.Activation +OAI.Combinatorics.Sidorenko.Basic +OAI.Combinatorics.Sidorenko.Charts +OAI.Combinatorics.Sidorenko.Coefficients +OAI.Combinatorics.Sidorenko.Coercivity +OAI.Combinatorics.Sidorenko.Configurations +OAI.Combinatorics.Sidorenko.Dilution +OAI.Combinatorics.Sidorenko.Discriminant +OAI.Combinatorics.Sidorenko.Exposure +OAI.Combinatorics.Sidorenko.FormGluing +OAI.Combinatorics.Sidorenko.GlobalMoments +OAI.Combinatorics.Sidorenko.Grassmann +OAI.Combinatorics.Sidorenko.Lagrangian +OAI.Combinatorics.Sidorenko.LocalMoments +OAI.Combinatorics.Sidorenko.Monomials +OAI.Combinatorics.Sidorenko.Normalization +OAI.Combinatorics.Sidorenko.Nullity +OAI.Combinatorics.Sidorenko.OrbitBounds +OAI.Combinatorics.Sidorenko.Orbits +OAI.Combinatorics.Sidorenko.PairBounds +OAI.Combinatorics.Sidorenko.Pinning +OAI.Combinatorics.Sidorenko.Planted +OAI.Combinatorics.Sidorenko.Projections +OAI.Combinatorics.Sidorenko.RandomHost +OAI.Combinatorics.Sidorenko.Reduction +OAI.Combinatorics.Sidorenko.Refinement +OAI.Combinatorics.Sidorenko.Restrictions +OAI.Combinatorics.Sidorenko.SignMoments +OAI.Combinatorics.Sidorenko.Signs +OAI.Combinatorics.Sidorenko.Spans +OAI.Combinatorics.Sidorenko.SubspaceCounts +OAI.Combinatorics.Sidorenko.Symmetrization +OAI.Combinatorics.Sidorenko.Tail +OAI.Combinatorics.Sidorenko.TripleRanks +OAI.Combinatorics.Sidorenko.Types diff --git a/tasks/sidorenko-counterexample/solution/reference.py b/tasks/sidorenko-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sidorenko-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sidorenko-counterexample/solution/solve.sh b/tasks/sidorenko-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..64500ea6b7a143cfe41f45e36c95063748afcbe0 --- /dev/null +++ b/tasks/sidorenko-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SidorenkoCounterexample, i.e. module OAI.Combinatorics.Sidorenko.RandomHost and the +# 35 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.Sidorenko.RandomHost /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SidorenkoCounterexample" diff --git a/tasks/sidorenko-counterexample/task.toml b/tasks/sidorenko-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b1d35bdd99cc5a7b0d75a00dcea823a157f80ae3 --- /dev/null +++ b/tasks/sidorenko-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sidorenko-counterexample" +version = "1.0.0" +description = "Prove SidorenkoCounterexample (openai/math family 161: Counterexamples to Sidorenko's conjecture and the forcing conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SidorenkoCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SidorenkoCounterexample" +family = "161" +family_title = "Counterexamples to Sidorenko's conjecture and the forcing conjecture" +subject = "Combinatorics" +theorems = ["OAI.SidorenkoCounterexample.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.Sidorenko.RandomHost" +reference_modules = 35 +reference_lean_bytes = 1216768 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1285 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12795 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sidorenko-counterexample/tests/Challenge.lean b/tasks/sidorenko-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3f4fa1074f812e2e823350ea50ff1a786e4a1927 --- /dev/null +++ b/tasks/sidorenko-counterexample/tests/Challenge.lean @@ -0,0 +1,47 @@ +import Mathlib + +namespace OAI + +/-! # A finite counterexample to Sidorenko's conjecture + +The pattern is the incidence graph of the 22 triples in Table 1 of the source. +Homomorphism density counts all edge-preserving maps, including noninjective maps. +-/ + +namespace SidorenkoCounterexample + +def faces : Fin 22 → Finset (Fin 13) := ![ + {0,1,3}, {0,1,9}, {0,2,3}, {0,2,9}, {1,3,10}, {1,7,10}, + {1,7,12}, {1,9,12}, {2,3,4}, {2,4,9}, {3,4,11}, {3,10,11}, + {4,8,9}, {4,8,11}, {5,6,7}, {5,6,11}, {5,7,10}, {5,10,11}, + {6,7,12}, {6,8,11}, {6,8,12}, {8,9,12}] + +abbrev PatternVertex := Fin 13 ⊕ Fin 22 + +def incidence : PatternVertex → PatternVertex → Prop + | .inl point, .inr face => point ∈ faces face + | .inr face, .inl point => point ∈ faces face + | _, _ => False + +def H : SimpleGraph PatternVertex where + Adj := incidence + symm.symm := by intro left right; cases left <;> cases right <;> simp [incidence] + loopless.irrefl := by intro vertex; cases vertex <;> simp [incidence] + +noncomputable def homCount {V W : Type*} (F : SimpleGraph V) (G : SimpleGraph W) : ℕ := + Nat.card {hom : V → W // ∀ left right, F.Adj left right → G.Adj (hom left) (hom right)} + +noncomputable def homDensity {V W : Type*} (F : SimpleGraph V) (G : SimpleGraph W) : ℝ := + (homCount F G : ℝ) / (Nat.card W : ℝ) ^ Nat.card V + +noncomputable def edgeDensity {W : Type*} (G : SimpleGraph W) : ℝ := + 2 * (Nat.card G.edgeSet : ℝ) / (Nat.card W : ℝ) ^ 2 + +/-- A finite simple host with at least one edge violates Sidorenko's inequality. -/ +theorem main : ∃ size : ℕ, 0 < size ∧ ∃ host : SimpleGraph (Fin size), + (∃ left right, host.Adj left right) ∧ homDensity H host < (edgeDensity host) ^ 66 := by + sorry + +end SidorenkoCounterexample + +end OAI diff --git a/tasks/sidorenko-counterexample/tests/grade.py b/tasks/sidorenko-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sidorenko-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sidorenko-counterexample/tests/task.json b/tasks/sidorenko-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9c4d6975a25ff869ed43cd59d4fba998a399df55 --- /dev/null +++ b/tasks/sidorenko-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SidorenkoCounterexample", + "comparator": { + "theorem_names": [ + "OAI.SidorenkoCounterexample.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11895 +} \ No newline at end of file diff --git a/tasks/sidorenko-counterexample/tests/test.sh b/tasks/sidorenko-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sidorenko-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/signed-finite-band/environment/Dockerfile b/tasks/signed-finite-band/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/signed-finite-band/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/signed-finite-band/environment/fetch_mathlib.sh b/tasks/signed-finite-band/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/signed-finite-band/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/signed-finite-band/environment/lake-manifest.json b/tasks/signed-finite-band/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/signed-finite-band/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/signed-finite-band/environment/lakefile.lean b/tasks/signed-finite-band/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/signed-finite-band/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/signed-finite-band/environment/lean_setup.sh b/tasks/signed-finite-band/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/signed-finite-band/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/signed-finite-band/environment/pack_submission.py b/tasks/signed-finite-band/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/signed-finite-band/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/signed-finite-band/instruction.md b/tasks/signed-finite-band/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9432a5cc64da212a45038fa94befc59b1d59c17d --- /dev/null +++ b/tasks/signed-finite-band/instruction.md @@ -0,0 +1,105 @@ +# openai/math challenge `SignedFiniteBand` (family 085) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 085 of the release, *Endpoint regularity of the planar centered maximal function* +(Real and complex analysis). The family as a whole: Resolves the planar centered-disk case of the Haj{\l}asz–Onninen maximal-function regularity problem. For every real $f\in W^{1,1}(\mathbb R^2)$, the centered disk maximal function satisfies $\|\nabla Mf\|_1\le C\|\nabla f\|_1$ with an absolute constant. It belongs locally to $W^{1,1}$ and has a globally integrable weak gradient. + +The challenge is `SignedFiniteBand`, also at `/opt/openai-math/challenges/SignedFiniteBand.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +namespace SignedDisk + +open MeasureTheory Set +open scoped ENNReal NNReal Topology ContDiff + +namespace CenteredDiskEndpoint + +/-- The Euclidean plane, with its Euclidean norm. -/ +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def diskAverage (f : Plane → ℝ) (x : Plane) (r : ℝ) : ℝ := + (∫ y in Metric.ball x r, f y) / (Real.pi * r ^ 2) + +/-- The i-th coordinate derivative of a smooth test function. -/ +def testPartial (φ : Plane → ℝ) (i : Fin 2) (x : Plane) : ℝ := + fderiv ℝ φ x (EuclideanSpace.single i 1) + +/-- Distributional first derivatives represented by a vector-valued function. -/ +def HasWeakGradient (f : Plane → ℝ) (g : Plane → Plane) : Prop := + ∀ (φ : Plane → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + ∀ i : Fin 2, (∫ x, f x * testPartial φ i x) = -∫ x, g x i * φ x + +/-- The gradient L1 norm in Euclidean norm. -/ +def gradientNorm (g : Plane → Plane) : ℝ := ∫ x, ‖g x‖ + +/-- Signed envelope over all real radii in the closed band, including its endpoints. -/ +def signedBand (f : Plane → ℝ) (a b : ℝ) (x : Plane) : ℝ := + sSup ((fun r => diskAverage f x r) '' Icc a b) + +def SignedFiniteBandStatement : Prop := + ∃ C : ℝ, 0 ≤ C ∧ + ∀ (f : Plane → ℝ), ContDiff ℝ ∞ f → HasCompactSupport f → + ∀ (a : ℝ), 0 < a → ∀ m : ℕ, + LocallyIntegrable (signedBand f a ((2 : ℝ)^m * a)) ∧ + ∃ G : Plane → Plane, Integrable G ∧ + HasWeakGradient (signedBand f a ((2 : ℝ)^m * a)) G ∧ + gradientNorm G ≤ C * gradientNorm (gradient f) + +theorem main_signed_finite_band : SignedFiniteBandStatement := by + sorry + +end CenteredDiskEndpoint + +end SignedDisk + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SignedFiniteBand.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SignedDisk.CenteredDiskEndpoint.main_signed_finite_band` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/signed-finite-band/solution/closure.txt b/tasks/signed-finite-band/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fadeb0e51bfa70a1771e75eb6fcbafa56205d126 --- /dev/null +++ b/tasks/signed-finite-band/solution/closure.txt @@ -0,0 +1,39 @@ +OAI.Analysis.SignedDisk.ActualLabels1 +OAI.Analysis.SignedDisk.ActualMarkTrees1 +OAI.Analysis.SignedDisk.ActualMarkTrees2 +OAI.Analysis.SignedDisk.AffineDensities1 +OAI.Analysis.SignedDisk.CommonPrices1 +OAI.Analysis.SignedDisk.CommonPrices2 +OAI.Analysis.SignedDisk.CommonPrices3 +OAI.Analysis.SignedDisk.CommonPrices4 +OAI.Analysis.SignedDisk.DirectionNeighbors1 +OAI.Analysis.SignedDisk.DiskGeometry1 +OAI.Analysis.SignedDisk.DiskGeometry2 +OAI.Analysis.SignedDisk.DiskKernels1 +OAI.Analysis.SignedDisk.DiskMaximalTools1 +OAI.Analysis.SignedDisk.DiskMaximalTools2 +OAI.Analysis.SignedDisk.DiskMoments1 +OAI.Analysis.SignedDisk.DiskScales1 +OAI.Analysis.SignedDisk.DiskScales2 +OAI.Analysis.SignedDisk.DiskScales3 +OAI.Analysis.SignedDisk.DyadicHats1 +OAI.Analysis.SignedDisk.DyadicHats2 +OAI.Analysis.SignedDisk.DyadicHats3 +OAI.Analysis.SignedDisk.FiniteLabels1 +OAI.Analysis.SignedDisk.FiniteLabels2 +OAI.Analysis.SignedDisk.IntrinsicMarks1 +OAI.Analysis.SignedDisk.LabelSwitches1 +OAI.Analysis.SignedDisk.LocalCancellation1 +OAI.Analysis.SignedDisk.LocalCancellation2 +OAI.Analysis.SignedDisk.LocalCancellation3 +OAI.Analysis.SignedDisk.LocalCancellation4 +OAI.Analysis.SignedDisk.LocalCancellation5 +OAI.Analysis.SignedDisk.Main +OAI.Analysis.SignedDisk.Model +OAI.Analysis.SignedDisk.PhysicalCells1 +OAI.Analysis.SignedDisk.PlanePotential1 +OAI.Analysis.SignedDisk.PlanePotential2 +OAI.Analysis.SignedDisk.ScalarCancellation1 +OAI.Analysis.SignedDisk.SignedRuns1 +OAI.Analysis.SignedDisk.SignedRuns2 +OAI.Analysis.SignedDisk.VectorRefinement1 diff --git a/tasks/signed-finite-band/solution/reference.py b/tasks/signed-finite-band/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/signed-finite-band/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/signed-finite-band/solution/solve.sh b/tasks/signed-finite-band/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0ec7a64dd467bc63550888419dd14998dfdd6dd5 --- /dev/null +++ b/tasks/signed-finite-band/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SignedFiniteBand, i.e. module OAI.Analysis.SignedDisk.Main and the +# 39 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.SignedDisk.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SignedFiniteBand" diff --git a/tasks/signed-finite-band/task.toml b/tasks/signed-finite-band/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..af3df6d8f954e574c17763e0af55450c37c03fcd --- /dev/null +++ b/tasks/signed-finite-band/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/signed-finite-band" +version = "1.0.0" +description = "Prove SignedFiniteBand (openai/math family 085: Endpoint regularity of the planar centered maximal function) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SignedFiniteBand.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SignedFiniteBand" +family = "085" +family_title = "Endpoint regularity of the planar centered maximal function" +subject = "Real and complex analysis" +theorems = ["OAI.SignedDisk.CenteredDiskEndpoint.main_signed_finite_band"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.SignedDisk.Main" +reference_modules = 39 +reference_lean_bytes = 841812 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 785 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12457 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/signed-finite-band/tests/Challenge.lean b/tasks/signed-finite-band/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f481bcf3dbf2549670eede7ef02d423dc84147a3 --- /dev/null +++ b/tasks/signed-finite-band/tests/Challenge.lean @@ -0,0 +1,54 @@ +import Mathlib + +namespace OAI + +noncomputable section + +namespace SignedDisk + +open MeasureTheory Set +open scoped ENNReal NNReal Topology ContDiff + +namespace CenteredDiskEndpoint + +/-- The Euclidean plane, with its Euclidean norm. -/ +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def diskAverage (f : Plane → ℝ) (x : Plane) (r : ℝ) : ℝ := + (∫ y in Metric.ball x r, f y) / (Real.pi * r ^ 2) + +/-- The i-th coordinate derivative of a smooth test function. -/ +def testPartial (φ : Plane → ℝ) (i : Fin 2) (x : Plane) : ℝ := + fderiv ℝ φ x (EuclideanSpace.single i 1) + +/-- Distributional first derivatives represented by a vector-valued function. -/ +def HasWeakGradient (f : Plane → ℝ) (g : Plane → Plane) : Prop := + ∀ (φ : Plane → ℝ), ContDiff ℝ ∞ φ → HasCompactSupport φ → + ∀ i : Fin 2, (∫ x, f x * testPartial φ i x) = -∫ x, g x i * φ x + +/-- The gradient L1 norm in Euclidean norm. -/ +def gradientNorm (g : Plane → Plane) : ℝ := ∫ x, ‖g x‖ + +/-- Signed envelope over all real radii in the closed band, including its endpoints. -/ +def signedBand (f : Plane → ℝ) (a b : ℝ) (x : Plane) : ℝ := + sSup ((fun r => diskAverage f x r) '' Icc a b) + +def SignedFiniteBandStatement : Prop := + ∃ C : ℝ, 0 ≤ C ∧ + ∀ (f : Plane → ℝ), ContDiff ℝ ∞ f → HasCompactSupport f → + ∀ (a : ℝ), 0 < a → ∀ m : ℕ, + LocallyIntegrable (signedBand f a ((2 : ℝ)^m * a)) ∧ + ∃ G : Plane → Plane, Integrable G ∧ + HasWeakGradient (signedBand f a ((2 : ℝ)^m * a)) G ∧ + gradientNorm G ≤ C * gradientNorm (gradient f) + +theorem main_signed_finite_band : SignedFiniteBandStatement := by + sorry + +end CenteredDiskEndpoint + +end SignedDisk + +end + +end OAI diff --git a/tasks/signed-finite-band/tests/grade.py b/tasks/signed-finite-band/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/signed-finite-band/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/signed-finite-band/tests/task.json b/tasks/signed-finite-band/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2d607b11e715f2dc38d3e51a91900646a4432396 --- /dev/null +++ b/tasks/signed-finite-band/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SignedFiniteBand", + "comparator": { + "theorem_names": [ + "OAI.SignedDisk.CenteredDiskEndpoint.main_signed_finite_band" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11557 +} \ No newline at end of file diff --git a/tasks/signed-finite-band/tests/test.sh b/tasks/signed-finite-band/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/signed-finite-band/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/signed-sweep-moment/environment/Dockerfile b/tasks/signed-sweep-moment/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/signed-sweep-moment/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/signed-sweep-moment/environment/fetch_mathlib.sh b/tasks/signed-sweep-moment/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/signed-sweep-moment/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/signed-sweep-moment/environment/lake-manifest.json b/tasks/signed-sweep-moment/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/signed-sweep-moment/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/signed-sweep-moment/environment/lakefile.lean b/tasks/signed-sweep-moment/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/signed-sweep-moment/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/signed-sweep-moment/environment/lean_setup.sh b/tasks/signed-sweep-moment/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/signed-sweep-moment/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/signed-sweep-moment/environment/pack_submission.py b/tasks/signed-sweep-moment/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/signed-sweep-moment/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/signed-sweep-moment/instruction.md b/tasks/signed-sweep-moment/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4d847d5ff437e6d5a8dfadd77d753169c7e42d04 --- /dev/null +++ b/tasks/signed-sweep-moment/instruction.md @@ -0,0 +1,240 @@ +# openai/math challenge `SignedSweepMoment` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `SignedSweepMoment`, also at `/opt/openai-math/challenges/SignedSweepMoment.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators TensorProduct +open Module + +namespace SignedSweeps + +abbrev Partition (n : ℕ) := {lam : YoungDiagram // lam.card = n} + +abbrev SymmetricGroup (n : ℕ) := Equiv.Perm (Fin n) + +namespace Partition + +def transpose {n : ℕ} (lam : Partition n) : Partition n := + ⟨lam.1.transpose, by simpa [YoungDiagram.card, YoungDiagram.transpose] using lam.2⟩ + +def tableau {n : ℕ} (lam : Partition n) : {c // c ∈ lam.1.cells} ≃ Fin n := + Fintype.equivFinOfCardEq (by simpa using lam.2) + +def rowOf {n : ℕ} (lam : Partition n) (x : Fin n) : ℕ := + ((tableau lam).symm x).1.1 + +def colOf {n : ℕ} (lam : Partition n) (x : Fin n) : ℕ := + ((tableau lam).symm x).1.2 + +end Partition + +def fiberSubgroup {A C : Type*} (f : A → C) : Subgroup (Equiv.Perm A) where + carrier := {g | ∀ x, f (g x) = f x} + one_mem' := by intro x; rfl + mul_mem' := by + intro g h hg hh x + exact (hg (h x)).trans (hh x) + inv_mem' := by + intro g hg x + simpa using (hg (g⁻¹ x)).symm + +def rowSubgroup {n : ℕ} (lam : Partition n) : Subgroup (SymmetricGroup n) := + fiberSubgroup lam.rowOf + +def colSubgroup {n : ℕ} (lam : Partition n) : Subgroup (SymmetricGroup n) := + fiberSubgroup lam.colOf + +abbrev RegularSpace (n : ℕ) := EuclideanSpace ℂ (SymmetricGroup n) + +def regularIsometry {n : ℕ} (g : SymmetricGroup n) : + RegularSpace n ≃ₗᵢ[ℂ] RegularSpace n := + LinearIsometryEquiv.piLpCongrLeft 2 ℂ ℂ (Equiv.mulLeft g) + +@[simp] +lemma regularIsometry_apply {n : ℕ} (g : SymmetricGroup n) + (f : RegularSpace n) (h : SymmetricGroup n) : + regularIsometry g f h = f (g⁻¹ * h) := rfl + +def regularRepresentation (n : ℕ) : Representation ℂ (SymmetricGroup n) (RegularSpace n) where + toFun g := (regularIsometry g).toLinearEquiv.toLinearMap + map_one' := by ext f h; simp + map_mul' := by + intro g h + ext f k + simp [mul_assoc] + +@[simp] +lemma regularRepresentation_apply {n : ℕ} (g : SymmetricGroup n) + (f : RegularSpace n) (h : SymmetricGroup n) : + regularRepresentation n g f h = f (g⁻¹ * h) := rfl + +def polytabloid {n : ℕ} (lam : Partition n) : RegularSpace n := by + classical + exact ∑ c : colSubgroup lam, ∑ a : rowSubgroup lam, + (((Equiv.Perm.sign (c : SymmetricGroup n) : ℤˣ) : ℤ) : ℂ) • + EuclideanSpace.single ((c : SymmetricGroup n) * (a : SymmetricGroup n)) 1 + +def spechtSubrepresentation {n : ℕ} (lam : Partition n) : + Subrepresentation (regularRepresentation n) where + toSubmodule := Submodule.span ℂ (Set.range (fun g => regularRepresentation n g (polytabloid lam))) + apply_mem_toSubmodule := by + intro g f hf + induction hf using Submodule.span_induction with + | mem v hv => + obtain ⟨h, rfl⟩ := hv + apply Submodule.subset_span + refine ⟨g * h, ?_⟩ + simp [map_mul, Module.End.mul_apply] + | zero => simp + | add x y hx hy ihx ihy => + simpa only [map_add] using Submodule.add_mem _ ihx ihy + | smul a x hx ih => + simpa only [map_smul] using Submodule.smul_mem _ a ih + +def Specht {n : ℕ} (lam : Partition n) : Type := (spechtSubrepresentation lam).toSubmodule + +instance spechtNormedAddCommGroup {n : ℕ} (lam : Partition n) : NormedAddCommGroup (Specht lam) := + inferInstanceAs (NormedAddCommGroup (spechtSubrepresentation lam).toSubmodule) + +instance spechtInnerProductSpace {n : ℕ} (lam : Partition n) : InnerProductSpace ℂ (Specht lam) := + inferInstanceAs (InnerProductSpace ℂ (spechtSubrepresentation lam).toSubmodule) + +instance spechtFiniteDimensional {n : ℕ} (lam : Partition n) : FiniteDimensional ℂ (Specht lam) := + inferInstanceAs (FiniteDimensional ℂ (spechtSubrepresentation lam).toSubmodule) + +def spechtRepresentation {n : ℕ} (lam : Partition n) : + Representation ℂ (SymmetricGroup n) (Specht lam) := + (spechtSubrepresentation lam).toRepresentation + +def spechtDimension {n : ℕ} (lam : Partition n) : ℕ := finrank ℂ (Specht lam) + +def blockEmbedding {u v l n : ℕ} (h : u + v + l = n) + (a : SymmetricGroup u) (b : SymmetricGroup v) (c : SymmetricGroup l) : + SymmetricGroup n := + let e : (Fin u ⊕ Fin v) ⊕ Fin l ≃ Fin n := + ((Equiv.sumCongr finSumFinEquiv (Equiv.refl (Fin l))).trans finSumFinEquiv).trans + (finCongr h) + e.permCongr ((a.sumCongr b).sumCongr c) + +def SignedOccurrence {u v l n : ℕ} (h : u + v + l = n) + (α : Partition u) (β : Partition v) (γ : Partition l) (lam : Partition n) : Prop := + ∃ f : ((Specht α ⊗[ℂ] Specht β.transpose) ⊗[ℂ] Specht γ) →ₗ[ℂ] Specht lam, + Function.Injective f ∧ + ∀ (a : SymmetricGroup u) (b : SymmetricGroup v) (c : SymmetricGroup l) x, + f (TensorProduct.map + (TensorProduct.map (spechtRepresentation α a) (spechtRepresentation β.transpose b)) + (spechtRepresentation γ c) x) = + spechtRepresentation lam (blockEmbedding h a b c) (f x) + +abbrev BinaryPositions (d : ℕ) := Fin d → Fin 2 + +def positionsEquiv (d : ℕ) : BinaryPositions d ≃ Fin (2 ^ d) := + Fintype.equivFinOfCardEq (by simp [BinaryPositions]) + +def coordinateSubgroup (d : ℕ) (i : Fin d) : Subgroup (SymmetricGroup (2 ^ d)) := + fiberSubgroup (fun x : Fin (2 ^ d) => + fun j : {j : Fin d // j ≠ i} => (positionsEquiv d).symm x j.1) + +def layerOperator {d : ℕ} (lam : Partition (2 ^ d)) (i : Fin d) : + Specht lam →ₗ[ℂ] Specht lam := by + classical + exact (Fintype.card (coordinateSubgroup d i) : ℂ)⁻¹ • + ∑ g : coordinateSubgroup d i, spechtRepresentation lam g.1 + +def sweepOperator {d : ℕ} (lam : Partition (2 ^ d)) : Specht lam →ₗ[ℂ] Specht lam := + ((List.ofFn (layerOperator lam)).reverse).prod + +def positiveSquare {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + [FiniteDimensional ℂ E] (T : E →ₗ[ℂ] E) : E →ₗ[ℂ] E := T.adjoint * T + +def sweepSquare {d : ℕ} (lam : Partition (2 ^ d)) : Specht lam →ₗ[ℂ] Specht lam := + positiveSquare (E := Specht lam) (sweepOperator lam) + +def weightedMoment {d : ℕ} (lam : Partition (2 ^ d)) (r : ℕ) : ℝ := + (spechtDimension lam : ℝ) * (LinearMap.trace ℂ (Specht lam) (sweepSquare lam ^ r)).re + +def logMoment (x : ℝ) : EReal := if x = 0 then ⊥ else (Real.log x : EReal) + +def signedEntropy {u v : ℕ} (α : Partition u) (β : Partition v) : ℝ := + ((α.1.rowLens ++ β.1.rowLens).map + (fun a : ℕ => (a : ℝ) * Real.log (((u : ℝ) + v) / a))).sum + +def coefficient (a : ℝ) (d : ℕ) : ℝ := a * (1 - 1 / (2 * Real.sqrt d)) + +def remainderBudget (κ : ℝ) (d l : ℕ) : ℝ := + if l = 0 then 0 else + max 0 (coefficient κ d * l * Real.log (2 ^ d : ℕ) - + (l : ℝ) * Real.log ((2 ^ d : ℕ) / (l : ℝ))) + +theorem signed_occurrence_moment_bound : + ∃ η₀ : ℝ, 0 < η₀ ∧ + ∀ η : ℝ, 0 < η → η < η₀ → + ∃ κ₀ : ℝ, 0 < κ₀ ∧ κ₀ < η / 256 ∧ + ∀ κ : ℝ, 0 < κ → κ < κ₀ → + ∃ r : ℕ, 1 ≤ r ∧ + ∀ d : ℕ, 1 ≤ d → + ∀ lam : Partition (2 ^ d), + ∀ (u v l : ℕ) (h : u + v + l = 2 ^ d) + (α : Partition u) (β : Partition v) (γ : Partition l), + SignedOccurrence h α β γ lam → + logMoment (weightedMoment lam r) ≤ + ((coefficient η d * signedEntropy α β + + remainderBudget κ d l : ℝ) : EReal) := by + sorry + +end SignedSweeps + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SignedSweepMoment.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SignedSweeps.signed_occurrence_moment_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/signed-sweep-moment/solution/closure.txt b/tasks/signed-sweep-moment/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5cce23f2233528dcde203709dc5fa6e00babccb7 --- /dev/null +++ b/tasks/signed-sweep-moment/solution/closure.txt @@ -0,0 +1,174 @@ +OAI.Probability.SignedSweeps.AllocationSigns +OAI.Probability.SignedSweeps.BalancedErrors +OAI.Probability.SignedSweeps.BaseCases +OAI.Probability.SignedSweeps.BetaNumbers +OAI.Probability.SignedSweeps.BinaryNetworks +OAI.Probability.SignedSweeps.BlockAngle +OAI.Probability.SignedSweeps.BlockPermutations +OAI.Probability.SignedSweeps.BlockRestriction +OAI.Probability.SignedSweeps.BlockTraceBudget +OAI.Probability.SignedSweeps.BranchingDimensions +OAI.Probability.SignedSweeps.BudgetAbsorption +OAI.Probability.SignedSweeps.BudgetBounds +OAI.Probability.SignedSweeps.CoefficientAlgebra +OAI.Probability.SignedSweeps.CoefficientPositivity +OAI.Probability.SignedSweeps.CoefficientPush +OAI.Probability.SignedSweeps.CoefficientUniform +OAI.Probability.SignedSweeps.ColorEntropy +OAI.Probability.SignedSweeps.ColumnAnnihilation +OAI.Probability.SignedSweeps.ColumnSubgroup +OAI.Probability.SignedSweeps.ConvexTwirl +OAI.Probability.SignedSweeps.DensityComparison +OAI.Probability.SignedSweeps.DimensionUpperEntropy +OAI.Probability.SignedSweeps.EmbeddedImprimitivity +OAI.Probability.SignedSweeps.EncounterGraph +OAI.Probability.SignedSweeps.EndpointKernels +OAI.Probability.SignedSweeps.EquivSign +OAI.Probability.SignedSweeps.EvenBoard +OAI.Probability.SignedSweeps.EvenDensity +OAI.Probability.SignedSweeps.EvenMean +OAI.Probability.SignedSweeps.EvenWordCommutant +OAI.Probability.SignedSweeps.ExactRowDimension +OAI.Probability.SignedSweeps.FallingFactorials +OAI.Probability.SignedSweeps.FiniteProbability +OAI.Probability.SignedSweeps.FiniteSampling +OAI.Probability.SignedSweeps.GroupAverage +OAI.Probability.SignedSweeps.GroupedCommute +OAI.Probability.SignedSweeps.GroupedDensity +OAI.Probability.SignedSweeps.GroupedTypes +OAI.Probability.SignedSweeps.HilbertBlockLower +OAI.Probability.SignedSweeps.HilbertBlockNorm +OAI.Probability.SignedSweeps.HilbertBlocks +OAI.Probability.SignedSweeps.HilbertFibers +OAI.Probability.SignedSweeps.HoleCount +OAI.Probability.SignedSweeps.HoleEntropy +OAI.Probability.SignedSweeps.HookArms +OAI.Probability.SignedSweeps.HookCarrierDimension +OAI.Probability.SignedSweeps.HookDimension +OAI.Probability.SignedSweeps.HullDensityComparison +OAI.Probability.SignedSweeps.HullLift +OAI.Probability.SignedSweeps.Imprimitivity +OAI.Probability.SignedSweeps.IndependentNetworks +OAI.Probability.SignedSweeps.InducedCarrier +OAI.Probability.SignedSweeps.InjectionRestriction +OAI.Probability.SignedSweeps.InvariantObstruction +OAI.Probability.SignedSweeps.Invariants +OAI.Probability.SignedSweeps.Irreducibility +OAI.Probability.SignedSweeps.IrreducibleClassification +OAI.Probability.SignedSweeps.IsometricFibers +OAI.Probability.SignedSweeps.Isotypic +OAI.Probability.SignedSweeps.IsotypicDecomposition +OAI.Probability.SignedSweeps.KernelBounds +OAI.Probability.SignedSweeps.KernelTransition +OAI.Probability.SignedSweeps.KroneckerHull +OAI.Probability.SignedSweeps.LocalStabilizerTrace +OAI.Probability.SignedSweeps.LocalTraceBudget +OAI.Probability.SignedSweeps.Main +OAI.Probability.SignedSweeps.MajorizationFactorial +OAI.Probability.SignedSweeps.MarginalKernels +OAI.Probability.SignedSweeps.MarkedCompression +OAI.Probability.SignedSweeps.MarkedMultiplicity +OAI.Probability.SignedSweeps.MarkedPairFibers +OAI.Probability.SignedSweeps.MarkedSector +OAI.Probability.SignedSweeps.MarkedSites +OAI.Probability.SignedSweeps.MarkedTrace +OAI.Probability.SignedSweeps.MarkedWords +OAI.Probability.SignedSweeps.MaskedKernels +OAI.Probability.SignedSweeps.MatrixHullLift +OAI.Probability.SignedSweeps.MatrixTwirl +OAI.Probability.SignedSweeps.MixedNetworks +OAI.Probability.SignedSweeps.Model +OAI.Probability.SignedSweeps.MomentMonotonicity +OAI.Probability.SignedSweeps.NetworkSampling +OAI.Probability.SignedSweeps.NormalizedColors +OAI.Probability.SignedSweeps.OccupiedCounts +OAI.Probability.SignedSweeps.OccupiedGeometry +OAI.Probability.SignedSweeps.OccupiedSweep +OAI.Probability.SignedSweeps.OccupiedTrace +OAI.Probability.SignedSweeps.OccurrenceDimension +OAI.Probability.SignedSweeps.OccurrenceDominance +OAI.Probability.SignedSweeps.OrbitDimension +OAI.Probability.SignedSweeps.PairCentral +OAI.Probability.SignedSweeps.PairConstituents +OAI.Probability.SignedSweeps.PairCovariance +OAI.Probability.SignedSweeps.PairDecomposition +OAI.Probability.SignedSweeps.PairDensityLower +OAI.Probability.SignedSweeps.PairDensityUpper +OAI.Probability.SignedSweeps.PairDominance +OAI.Probability.SignedSweeps.PairEntropyDensity +OAI.Probability.SignedSweeps.PairExtension +OAI.Probability.SignedSweeps.PairTwirlLift +OAI.Probability.SignedSweeps.PairWordTypes +OAI.Probability.SignedSweeps.PartitionCount +OAI.Probability.SignedSweeps.PartitionGeometry +OAI.Probability.SignedSweeps.PermutationRows +OAI.Probability.SignedSweeps.PiTensorHull +OAI.Probability.SignedSweeps.PiTensorMatrix +OAI.Probability.SignedSweeps.PolarDecomposition +OAI.Probability.SignedSweeps.PolytabloidNonzero +OAI.Probability.SignedSweeps.PositiveRootTensor +OAI.Probability.SignedSweeps.ProjectionTrace +OAI.Probability.SignedSweeps.ProvedRanges +OAI.Probability.SignedSweeps.ProvedRanges2 +OAI.Probability.SignedSweeps.ProvedRanges3 +OAI.Probability.SignedSweeps.ProvedRanges4 +OAI.Probability.SignedSweeps.RestrictionSum +OAI.Probability.SignedSweeps.RestrictionSum2 +OAI.Probability.SignedSweeps.ReverseEncounters +OAI.Probability.SignedSweeps.RowDimensionFormula +OAI.Probability.SignedSweeps.RowSymmetry +OAI.Probability.SignedSweeps.ShiftedRows +OAI.Probability.SignedSweeps.SignedArmDominance +OAI.Probability.SignedSweeps.SignedBlockCoefficients +OAI.Probability.SignedSweeps.SignedBlockTrace +OAI.Probability.SignedSweeps.SignedPair +OAI.Probability.SignedSweeps.SignedPairDimension +OAI.Probability.SignedSweeps.SignedTypeAngle +OAI.Probability.SignedSweeps.SignedWords +OAI.Probability.SignedSweeps.SparseBridge +OAI.Probability.SignedSweeps.SparseUniform +OAI.Probability.SignedSweeps.SpectralAngle +OAI.Probability.SignedSweeps.SpectralCommute +OAI.Probability.SignedSweeps.SpectralConj +OAI.Probability.SignedSweeps.SpectralGap +OAI.Probability.SignedSweeps.SubsetInclusion +OAI.Probability.SignedSweeps.SubsetLaw +OAI.Probability.SignedSweeps.SubsetSweep +OAI.Probability.SignedSweeps.SupportInverse +OAI.Probability.SignedSweeps.SweepBlockLayers +OAI.Probability.SignedSweeps.SweepCoefficients +OAI.Probability.SignedSweeps.SweepRecurrence +OAI.Probability.SignedSweeps.SwitchAverages +OAI.Probability.SignedSweeps.SwitchGeneration +OAI.Probability.SignedSweeps.TensorAngle +OAI.Probability.SignedSweeps.TensorCommutant +OAI.Probability.SignedSweeps.TensorDensity +OAI.Probability.SignedSweeps.TensorMultiplicity +OAI.Probability.SignedSweeps.TensorSupport +OAI.Probability.SignedSweeps.TraceDecomposition +OAI.Probability.SignedSweeps.TransposeSpecht +OAI.Probability.SignedSweeps.TupleNorm +OAI.Probability.SignedSweeps.TupleRealization +OAI.Probability.SignedSweeps.TypeTrace +OAI.Probability.SignedSweeps.UniformMoment +OAI.Probability.SignedSweeps.UniquePaths +OAI.Probability.SignedSweeps.UnitaryTensorSpan +OAI.Probability.SignedSweeps.VandermondeBranch +OAI.Probability.SignedSweeps.WeightedGraph +OAI.Probability.SignedSweeps.WeightedNoIsolates +OAI.Probability.SignedSweeps.WordAllocations +OAI.Probability.SignedSweeps.WordBlocks +OAI.Probability.SignedSweeps.WordDensity +OAI.Probability.SignedSweeps.WordEmbedding +OAI.Probability.SignedSweeps.WordEntropy +OAI.Probability.SignedSweeps.WordGrouping +OAI.Probability.SignedSweeps.WordIsotypic +OAI.Probability.SignedSweeps.WordMonomial +OAI.Probability.SignedSweeps.WordSpecht +OAI.Probability.SignedSweeps.WordSpectral +OAI.Probability.SignedSweeps.WordTensorBasis +OAI.Probability.SignedSweeps.WordTwirl +OAI.Probability.SignedSweeps.WordUpper +OAI.Probability.SignedSweeps.YoungCorners +OAI.Probability.SignedSweeps.YoungLemma +OAI.Probability.SignedSweeps.YoungRecurrence diff --git a/tasks/signed-sweep-moment/solution/reference.py b/tasks/signed-sweep-moment/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/signed-sweep-moment/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/signed-sweep-moment/solution/solve.sh b/tasks/signed-sweep-moment/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bbb36279be134309402bd8ffb82246b36e54f4a1 --- /dev/null +++ b/tasks/signed-sweep-moment/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SignedSweepMoment, i.e. module OAI.Probability.SignedSweeps.Main and the +# 174 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SignedSweeps.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SignedSweepMoment" diff --git a/tasks/signed-sweep-moment/task.toml b/tasks/signed-sweep-moment/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..117dfbb77e00c7636b70e6a4ff170acb7725e5e4 --- /dev/null +++ b/tasks/signed-sweep-moment/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/signed-sweep-moment" +version = "1.0.0" +description = "Prove SignedSweepMoment (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SignedSweepMoment.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SignedSweepMoment" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.SignedSweeps.signed_occurrence_moment_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SignedSweeps.Main" +reference_modules = 174 +reference_lean_bytes = 1198418 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1266 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12778 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/signed-sweep-moment/tests/Challenge.lean b/tasks/signed-sweep-moment/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..aca61acfccd6a63c296607787c600ffefcdad00b --- /dev/null +++ b/tasks/signed-sweep-moment/tests/Challenge.lean @@ -0,0 +1,189 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators TensorProduct +open Module + +namespace SignedSweeps + +abbrev Partition (n : ℕ) := {lam : YoungDiagram // lam.card = n} + +abbrev SymmetricGroup (n : ℕ) := Equiv.Perm (Fin n) + +namespace Partition + +def transpose {n : ℕ} (lam : Partition n) : Partition n := + ⟨lam.1.transpose, by simpa [YoungDiagram.card, YoungDiagram.transpose] using lam.2⟩ + +def tableau {n : ℕ} (lam : Partition n) : {c // c ∈ lam.1.cells} ≃ Fin n := + Fintype.equivFinOfCardEq (by simpa using lam.2) + +def rowOf {n : ℕ} (lam : Partition n) (x : Fin n) : ℕ := + ((tableau lam).symm x).1.1 + +def colOf {n : ℕ} (lam : Partition n) (x : Fin n) : ℕ := + ((tableau lam).symm x).1.2 + +end Partition + +def fiberSubgroup {A C : Type*} (f : A → C) : Subgroup (Equiv.Perm A) where + carrier := {g | ∀ x, f (g x) = f x} + one_mem' := by intro x; rfl + mul_mem' := by + intro g h hg hh x + exact (hg (h x)).trans (hh x) + inv_mem' := by + intro g hg x + simpa using (hg (g⁻¹ x)).symm + +def rowSubgroup {n : ℕ} (lam : Partition n) : Subgroup (SymmetricGroup n) := + fiberSubgroup lam.rowOf + +def colSubgroup {n : ℕ} (lam : Partition n) : Subgroup (SymmetricGroup n) := + fiberSubgroup lam.colOf + +abbrev RegularSpace (n : ℕ) := EuclideanSpace ℂ (SymmetricGroup n) + +def regularIsometry {n : ℕ} (g : SymmetricGroup n) : + RegularSpace n ≃ₗᵢ[ℂ] RegularSpace n := + LinearIsometryEquiv.piLpCongrLeft 2 ℂ ℂ (Equiv.mulLeft g) + +@[simp] +lemma regularIsometry_apply {n : ℕ} (g : SymmetricGroup n) + (f : RegularSpace n) (h : SymmetricGroup n) : + regularIsometry g f h = f (g⁻¹ * h) := rfl + +def regularRepresentation (n : ℕ) : Representation ℂ (SymmetricGroup n) (RegularSpace n) where + toFun g := (regularIsometry g).toLinearEquiv.toLinearMap + map_one' := by ext f h; simp + map_mul' := by + intro g h + ext f k + simp [mul_assoc] + +@[simp] +lemma regularRepresentation_apply {n : ℕ} (g : SymmetricGroup n) + (f : RegularSpace n) (h : SymmetricGroup n) : + regularRepresentation n g f h = f (g⁻¹ * h) := rfl + +def polytabloid {n : ℕ} (lam : Partition n) : RegularSpace n := by + classical + exact ∑ c : colSubgroup lam, ∑ a : rowSubgroup lam, + (((Equiv.Perm.sign (c : SymmetricGroup n) : ℤˣ) : ℤ) : ℂ) • + EuclideanSpace.single ((c : SymmetricGroup n) * (a : SymmetricGroup n)) 1 + +def spechtSubrepresentation {n : ℕ} (lam : Partition n) : + Subrepresentation (regularRepresentation n) where + toSubmodule := Submodule.span ℂ (Set.range (fun g => regularRepresentation n g (polytabloid lam))) + apply_mem_toSubmodule := by + intro g f hf + induction hf using Submodule.span_induction with + | mem v hv => + obtain ⟨h, rfl⟩ := hv + apply Submodule.subset_span + refine ⟨g * h, ?_⟩ + simp [map_mul, Module.End.mul_apply] + | zero => simp + | add x y hx hy ihx ihy => + simpa only [map_add] using Submodule.add_mem _ ihx ihy + | smul a x hx ih => + simpa only [map_smul] using Submodule.smul_mem _ a ih + +def Specht {n : ℕ} (lam : Partition n) : Type := (spechtSubrepresentation lam).toSubmodule + +instance spechtNormedAddCommGroup {n : ℕ} (lam : Partition n) : NormedAddCommGroup (Specht lam) := + inferInstanceAs (NormedAddCommGroup (spechtSubrepresentation lam).toSubmodule) + +instance spechtInnerProductSpace {n : ℕ} (lam : Partition n) : InnerProductSpace ℂ (Specht lam) := + inferInstanceAs (InnerProductSpace ℂ (spechtSubrepresentation lam).toSubmodule) + +instance spechtFiniteDimensional {n : ℕ} (lam : Partition n) : FiniteDimensional ℂ (Specht lam) := + inferInstanceAs (FiniteDimensional ℂ (spechtSubrepresentation lam).toSubmodule) + +def spechtRepresentation {n : ℕ} (lam : Partition n) : + Representation ℂ (SymmetricGroup n) (Specht lam) := + (spechtSubrepresentation lam).toRepresentation + +def spechtDimension {n : ℕ} (lam : Partition n) : ℕ := finrank ℂ (Specht lam) + +def blockEmbedding {u v l n : ℕ} (h : u + v + l = n) + (a : SymmetricGroup u) (b : SymmetricGroup v) (c : SymmetricGroup l) : + SymmetricGroup n := + let e : (Fin u ⊕ Fin v) ⊕ Fin l ≃ Fin n := + ((Equiv.sumCongr finSumFinEquiv (Equiv.refl (Fin l))).trans finSumFinEquiv).trans + (finCongr h) + e.permCongr ((a.sumCongr b).sumCongr c) + +def SignedOccurrence {u v l n : ℕ} (h : u + v + l = n) + (α : Partition u) (β : Partition v) (γ : Partition l) (lam : Partition n) : Prop := + ∃ f : ((Specht α ⊗[ℂ] Specht β.transpose) ⊗[ℂ] Specht γ) →ₗ[ℂ] Specht lam, + Function.Injective f ∧ + ∀ (a : SymmetricGroup u) (b : SymmetricGroup v) (c : SymmetricGroup l) x, + f (TensorProduct.map + (TensorProduct.map (spechtRepresentation α a) (spechtRepresentation β.transpose b)) + (spechtRepresentation γ c) x) = + spechtRepresentation lam (blockEmbedding h a b c) (f x) + +abbrev BinaryPositions (d : ℕ) := Fin d → Fin 2 + +def positionsEquiv (d : ℕ) : BinaryPositions d ≃ Fin (2 ^ d) := + Fintype.equivFinOfCardEq (by simp [BinaryPositions]) + +def coordinateSubgroup (d : ℕ) (i : Fin d) : Subgroup (SymmetricGroup (2 ^ d)) := + fiberSubgroup (fun x : Fin (2 ^ d) => + fun j : {j : Fin d // j ≠ i} => (positionsEquiv d).symm x j.1) + +def layerOperator {d : ℕ} (lam : Partition (2 ^ d)) (i : Fin d) : + Specht lam →ₗ[ℂ] Specht lam := by + classical + exact (Fintype.card (coordinateSubgroup d i) : ℂ)⁻¹ • + ∑ g : coordinateSubgroup d i, spechtRepresentation lam g.1 + +def sweepOperator {d : ℕ} (lam : Partition (2 ^ d)) : Specht lam →ₗ[ℂ] Specht lam := + ((List.ofFn (layerOperator lam)).reverse).prod + +def positiveSquare {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + [FiniteDimensional ℂ E] (T : E →ₗ[ℂ] E) : E →ₗ[ℂ] E := T.adjoint * T + +def sweepSquare {d : ℕ} (lam : Partition (2 ^ d)) : Specht lam →ₗ[ℂ] Specht lam := + positiveSquare (E := Specht lam) (sweepOperator lam) + +def weightedMoment {d : ℕ} (lam : Partition (2 ^ d)) (r : ℕ) : ℝ := + (spechtDimension lam : ℝ) * (LinearMap.trace ℂ (Specht lam) (sweepSquare lam ^ r)).re + +def logMoment (x : ℝ) : EReal := if x = 0 then ⊥ else (Real.log x : EReal) + +def signedEntropy {u v : ℕ} (α : Partition u) (β : Partition v) : ℝ := + ((α.1.rowLens ++ β.1.rowLens).map + (fun a : ℕ => (a : ℝ) * Real.log (((u : ℝ) + v) / a))).sum + +def coefficient (a : ℝ) (d : ℕ) : ℝ := a * (1 - 1 / (2 * Real.sqrt d)) + +def remainderBudget (κ : ℝ) (d l : ℕ) : ℝ := + if l = 0 then 0 else + max 0 (coefficient κ d * l * Real.log (2 ^ d : ℕ) - + (l : ℝ) * Real.log ((2 ^ d : ℕ) / (l : ℝ))) + +theorem signed_occurrence_moment_bound : + ∃ η₀ : ℝ, 0 < η₀ ∧ + ∀ η : ℝ, 0 < η → η < η₀ → + ∃ κ₀ : ℝ, 0 < κ₀ ∧ κ₀ < η / 256 ∧ + ∀ κ : ℝ, 0 < κ → κ < κ₀ → + ∃ r : ℕ, 1 ≤ r ∧ + ∀ d : ℕ, 1 ≤ d → + ∀ lam : Partition (2 ^ d), + ∀ (u v l : ℕ) (h : u + v + l = 2 ^ d) + (α : Partition u) (β : Partition v) (γ : Partition l), + SignedOccurrence h α β γ lam → + logMoment (weightedMoment lam r) ≤ + ((coefficient η d * signedEntropy α β + + remainderBudget κ d l : ℝ) : EReal) := by + sorry + +end SignedSweeps + +end + +end OAI diff --git a/tasks/signed-sweep-moment/tests/grade.py b/tasks/signed-sweep-moment/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/signed-sweep-moment/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/signed-sweep-moment/tests/task.json b/tasks/signed-sweep-moment/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5ff27b084aecbdaa264f8b2e7a0a2e0f7ab61ae1 --- /dev/null +++ b/tasks/signed-sweep-moment/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SignedSweepMoment", + "comparator": { + "theorem_names": [ + "OAI.SignedSweeps.signed_occurrence_moment_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11878 +} \ No newline at end of file diff --git a/tasks/signed-sweep-moment/tests/test.sh b/tasks/signed-sweep-moment/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/signed-sweep-moment/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/single-fold/environment/Dockerfile b/tasks/single-fold/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/single-fold/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/single-fold/environment/fetch_mathlib.sh b/tasks/single-fold/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/single-fold/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/single-fold/environment/lake-manifest.json b/tasks/single-fold/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/single-fold/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/single-fold/environment/lakefile.lean b/tasks/single-fold/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/single-fold/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/single-fold/environment/lean_setup.sh b/tasks/single-fold/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/single-fold/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/single-fold/environment/pack_submission.py b/tasks/single-fold/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/single-fold/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/single-fold/instruction.md b/tasks/single-fold/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e31aca397b71c0bc1c364343233e67026100eb53 --- /dev/null +++ b/tasks/single-fold/instruction.md @@ -0,0 +1,80 @@ +# openai/math challenge `SingleFold` (family 242) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 242 of the release, *Single-fold Diophantine representations* +(Mathematical logic). The family as a whole: Every recursively enumerable set of tuples of natural numbers has a Diophantine representation with exactly one auxiliary solution for each member and none for nonmembers. This proves the single-fold conjecture and hence the finite-fold conjecture. Diophantine solvability over the nonnegative integers remains undecidable even with an at-most-one-solution promise. + +The challenge is `SingleFold`, also at `/opt/openai-math/challenges/SingleFold.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace SingleFold + +/-- Evaluation over the integers of an integer polynomial at natural inputs. -/ +noncomputable def evalNat {n m : ℕ} (P : MvPolynomial (Fin n ⊕ Fin m) ℤ) + (a : Fin n → ℕ) (w : Fin m → ℕ) : ℤ := + MvPolynomial.eval (Sum.elim (fun i => (a i : ℤ)) (fun j => (w j : ℤ))) P + +/-- Exact existence on members, no witness on nonmembers, and uniqueness of the +whole witness on every input. No coordinates are hidden outside `w`. -/ +def Represents {n m : ℕ} (P : MvPolynomial (Fin n ⊕ Fin m) ℤ) + (S : Set (Fin n → ℕ)) : Prop := + ∀ a, (a ∈ S ↔ ∃ w, evalNat P a w = 0) ∧ + ∀ w v, evalNat P a w = 0 → evalNat P a v = 0 → w = v + +/-- Single-fold representation with positive input and witness lengths. -/ +def MainStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → ∀ (S : Set (Fin n → ℕ)), REPred (fun a => a ∈ S) → + ∃ (m : ℕ), 1 ≤ m ∧ ∃ P : MvPolynomial (Fin n ⊕ Fin m) ℤ, Represents P S + +theorem main : MainStatement := by + sorry + +end SingleFold + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SingleFold.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SingleFold.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/single-fold/solution/closure.txt b/tasks/single-fold/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7b4cacd612826b84f06eeb9000b3e4835730ee79 --- /dev/null +++ b/tasks/single-fold/solution/closure.txt @@ -0,0 +1,28 @@ +OAI.NumberTheory.SingleFold.Binary +OAI.NumberTheory.SingleFold.CounterBounds +OAI.NumberTheory.SingleFold.CounterCompilation +OAI.NumberTheory.SingleFold.CounterMachine +OAI.NumberTheory.SingleFold.CounterRecords +OAI.NumberTheory.SingleFold.DescentMap +OAI.NumberTheory.SingleFold.Duplication +OAI.NumberTheory.SingleFold.EllipticCoordinates +OAI.NumberTheory.SingleFold.EllipticGrowth +OAI.NumberTheory.SingleFold.EllipticHeight +OAI.NumberTheory.SingleFold.FiniteGeneration +OAI.NumberTheory.SingleFold.FunctionalCompiler +OAI.NumberTheory.SingleFold.HeightGrowth +OAI.NumberTheory.SingleFold.LocalDescent +OAI.NumberTheory.SingleFold.MacroMachine +OAI.NumberTheory.SingleFold.Main +OAI.NumberTheory.SingleFold.Model +OAI.NumberTheory.SingleFold.Packed +OAI.NumberTheory.SingleFold.Pell +OAI.NumberTheory.SingleFold.PolynomialCompiler +OAI.NumberTheory.SingleFold.Power +OAI.NumberTheory.SingleFold.QuadraticHeight +OAI.NumberTheory.SingleFold.Rank +OAI.NumberTheory.SingleFold.RationalCodes +OAI.NumberTheory.SingleFold.RecursiveEnumeration +OAI.NumberTheory.SingleFold.SquareSupport +OAI.NumberTheory.SingleFold.Torsion +OAI.NumberTheory.SingleFold.TuringSimulation diff --git a/tasks/single-fold/solution/reference.py b/tasks/single-fold/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/single-fold/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/single-fold/solution/solve.sh b/tasks/single-fold/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a955994fd7bb2cca72f5efdaac470339bb9903d7 --- /dev/null +++ b/tasks/single-fold/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SingleFold, i.e. module OAI.NumberTheory.SingleFold.Main and the +# 28 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.NumberTheory.SingleFold.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SingleFold" diff --git a/tasks/single-fold/task.toml b/tasks/single-fold/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..fb692c353e6dfc7e9b360419e639fbfc87054990 --- /dev/null +++ b/tasks/single-fold/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/single-fold" +version = "1.0.0" +description = "Prove SingleFold (openai/math family 242: Single-fold Diophantine representations) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SingleFold.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SingleFold" +family = "242" +family_title = "Single-fold Diophantine representations" +subject = "Mathematical logic" +theorems = ["OAI.SingleFold.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.NumberTheory.SingleFold.Main" +reference_modules = 28 +reference_lean_bytes = 336998 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 851 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12003 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/single-fold/tests/Challenge.lean b/tasks/single-fold/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1ca4b4e2c4aabdc4a3a8d45d661502273f4bf919 --- /dev/null +++ b/tasks/single-fold/tests/Challenge.lean @@ -0,0 +1,29 @@ +import Mathlib + +namespace OAI + +namespace SingleFold + +/-- Evaluation over the integers of an integer polynomial at natural inputs. -/ +noncomputable def evalNat {n m : ℕ} (P : MvPolynomial (Fin n ⊕ Fin m) ℤ) + (a : Fin n → ℕ) (w : Fin m → ℕ) : ℤ := + MvPolynomial.eval (Sum.elim (fun i => (a i : ℤ)) (fun j => (w j : ℤ))) P + +/-- Exact existence on members, no witness on nonmembers, and uniqueness of the +whole witness on every input. No coordinates are hidden outside `w`. -/ +def Represents {n m : ℕ} (P : MvPolynomial (Fin n ⊕ Fin m) ℤ) + (S : Set (Fin n → ℕ)) : Prop := + ∀ a, (a ∈ S ↔ ∃ w, evalNat P a w = 0) ∧ + ∀ w v, evalNat P a w = 0 → evalNat P a v = 0 → w = v + +/-- Single-fold representation with positive input and witness lengths. -/ +def MainStatement : Prop := + ∀ (n : ℕ), 1 ≤ n → ∀ (S : Set (Fin n → ℕ)), REPred (fun a => a ∈ S) → + ∃ (m : ℕ), 1 ≤ m ∧ ∃ P : MvPolynomial (Fin n ⊕ Fin m) ℤ, Represents P S + +theorem main : MainStatement := by + sorry + +end SingleFold + +end OAI diff --git a/tasks/single-fold/tests/grade.py b/tasks/single-fold/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/single-fold/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/single-fold/tests/task.json b/tasks/single-fold/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..00152be40ae22770661a912a8439b7be09c6ddf3 --- /dev/null +++ b/tasks/single-fold/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SingleFold", + "comparator": { + "theorem_names": [ + "OAI.SingleFold.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11103 +} \ No newline at end of file diff --git a/tasks/single-fold/tests/test.sh b/tasks/single-fold/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/single-fold/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/single-lattice-covering/environment/Dockerfile b/tasks/single-lattice-covering/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/single-lattice-covering/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/single-lattice-covering/environment/fetch_mathlib.sh b/tasks/single-lattice-covering/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/single-lattice-covering/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/single-lattice-covering/environment/lake-manifest.json b/tasks/single-lattice-covering/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/single-lattice-covering/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/single-lattice-covering/environment/lakefile.lean b/tasks/single-lattice-covering/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/single-lattice-covering/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/single-lattice-covering/environment/lean_setup.sh b/tasks/single-lattice-covering/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/single-lattice-covering/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/single-lattice-covering/environment/pack_submission.py b/tasks/single-lattice-covering/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/single-lattice-covering/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/single-lattice-covering/instruction.md b/tasks/single-lattice-covering/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c22ca66cd6f2ac8164985230c483229b0c8afc8d --- /dev/null +++ b/tasks/single-lattice-covering/instruction.md @@ -0,0 +1,80 @@ +# openai/math challenge `SingleLatticeCovering` (family 092) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 092 of the release, *The optimal order of convex-body covering density* +(Convex and metric geometry). The family as a whole: Determines the optimal worst-case covering density as $\Theta(n\log n)$, for both lattice and unrestricted translative coverings. Every convex body in $\mathbb R^n$, $n\ge2$, admits a lattice covering of density at most $Cn\log n$; centrally symmetric examples in every sufficiently large dimension require at least $cn\log n$ even without the lattice restriction, for absolute $c,C>0$. + +The challenge is `SingleLatticeCovering`, also at `/opt/openai-math/challenges/SingleLatticeCovering.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! Convex bodies and exact coverings by a single lattice in real coordinate space. -/ + +namespace SingleLatticeCovering + +open MeasureTheory +open scoped Pointwise + +abbrev Space (n : ℕ) := Fin n → ℝ + +def IsConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def LatticeCovers {n : ℕ} (K : Set (Space n)) (L : Submodule ℤ (Space n)) : Prop := + K + (L : Set (Space n)) = Set.univ + +theorem single_lattice_covering : + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ), 2 ≤ n → + ∀ (K : Set (Space n)), IsConvexBody K → + ∃ (L : Submodule ℤ (Space n)) (_ : DiscreteTopology L), + IsZLattice ℝ L ∧ LatticeCovers K L ∧ + (volume K).toReal / ZLattice.covolume L ≤ C * (n : ℝ) * Real.log (n : ℝ) := by sorry + +end SingleLatticeCovering + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SingleLatticeCovering.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SingleLatticeCovering.single_lattice_covering` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/single-lattice-covering/solution/closure.txt b/tasks/single-lattice-covering/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..49e48ebd23b3f7ab1e45d8ded9ef3342c428fa10 --- /dev/null +++ b/tasks/single-lattice-covering/solution/closure.txt @@ -0,0 +1,41 @@ +OAI.Geometry.LatticeCovering.Assembly +OAI.Geometry.LatticeCovering.Bits +OAI.Geometry.LatticeCovering.BrokenCircuits +OAI.Geometry.LatticeCovering.Chains +OAI.Geometry.LatticeCovering.CircuitErrors +OAI.Geometry.LatticeCovering.CircuitLattices +OAI.Geometry.LatticeCovering.CircuitSums +OAI.Geometry.LatticeCovering.CircuitVolumes +OAI.Geometry.LatticeCovering.Completion +OAI.Geometry.LatticeCovering.Concentration +OAI.Geometry.LatticeCovering.Covering +OAI.Geometry.LatticeCovering.Desmoothing +OAI.Geometry.LatticeCovering.Folded +OAI.Geometry.LatticeCovering.GaussianMoments +OAI.Geometry.LatticeCovering.GaussianPositions +OAI.Geometry.LatticeCovering.GaussianRates +OAI.Geometry.LatticeCovering.GaussianSections +OAI.Geometry.LatticeCovering.GaussianSmoothing +OAI.Geometry.LatticeCovering.GridCounts +OAI.Geometry.LatticeCovering.Horizontal +OAI.Geometry.LatticeCovering.Isotropy +OAI.Geometry.LatticeCovering.Lines +OAI.Geometry.LatticeCovering.LogConcavity +OAI.Geometry.LatticeCovering.Main +OAI.Geometry.LatticeCovering.Marginals +OAI.Geometry.LatticeCovering.MeanHoles +OAI.Geometry.LatticeCovering.Model +OAI.Geometry.LatticeCovering.Patterns +OAI.Geometry.LatticeCovering.PrimeGrids +OAI.Geometry.LatticeCovering.PrimeKernels +OAI.Geometry.LatticeCovering.Products +OAI.Geometry.LatticeCovering.ProjectionBounds +OAI.Geometry.LatticeCovering.RadialBounds +OAI.Geometry.LatticeCovering.Rates +OAI.Geometry.LatticeCovering.Residuals +OAI.Geometry.LatticeCovering.Rounding +OAI.Geometry.LatticeCovering.Sampling +OAI.Geometry.LatticeCovering.SamplingBounds +OAI.Geometry.LatticeCovering.Sections +OAI.Geometry.LatticeCovering.Shears +OAI.Geometry.LatticeCovering.Transport diff --git a/tasks/single-lattice-covering/solution/reference.py b/tasks/single-lattice-covering/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/single-lattice-covering/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/single-lattice-covering/solution/solve.sh b/tasks/single-lattice-covering/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bfa09f793dcbcad590e8b58d3c02fe73b336d013 --- /dev/null +++ b/tasks/single-lattice-covering/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SingleLatticeCovering, i.e. module OAI.Geometry.LatticeCovering.Main and the +# 41 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.LatticeCovering.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SingleLatticeCovering" diff --git a/tasks/single-lattice-covering/task.toml b/tasks/single-lattice-covering/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6d59315a7f95ce1c0061333e3f5911c2aaaabce7 --- /dev/null +++ b/tasks/single-lattice-covering/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/single-lattice-covering" +version = "1.0.0" +description = "Prove SingleLatticeCovering (openai/math family 092: The optimal order of convex-body covering density) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SingleLatticeCovering.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SingleLatticeCovering" +family = "092" +family_title = "The optimal order of convex-body covering density" +subject = "Convex and metric geometry" +theorems = ["OAI.SingleLatticeCovering.single_lattice_covering"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.LatticeCovering.Main" +reference_modules = 41 +reference_lean_bytes = 1145959 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1015 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12731 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/single-lattice-covering/tests/Challenge.lean b/tasks/single-lattice-covering/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..bc1206bfaa5e0914fb820077a3c289e35ee6db2a --- /dev/null +++ b/tasks/single-lattice-covering/tests/Challenge.lean @@ -0,0 +1,29 @@ +import Mathlib + +namespace OAI + +/-! Convex bodies and exact coverings by a single lattice in real coordinate space. -/ + +namespace SingleLatticeCovering + +open MeasureTheory +open scoped Pointwise + +abbrev Space (n : ℕ) := Fin n → ℝ + +def IsConvexBody {n : ℕ} (K : Set (Space n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty + +def LatticeCovers {n : ℕ} (K : Set (Space n)) (L : Submodule ℤ (Space n)) : Prop := + K + (L : Set (Space n)) = Set.univ + +theorem single_lattice_covering : + ∃ C : ℝ, 0 < C ∧ ∀ (n : ℕ), 2 ≤ n → + ∀ (K : Set (Space n)), IsConvexBody K → + ∃ (L : Submodule ℤ (Space n)) (_ : DiscreteTopology L), + IsZLattice ℝ L ∧ LatticeCovers K L ∧ + (volume K).toReal / ZLattice.covolume L ≤ C * (n : ℝ) * Real.log (n : ℝ) := by sorry + +end SingleLatticeCovering + +end OAI diff --git a/tasks/single-lattice-covering/tests/grade.py b/tasks/single-lattice-covering/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/single-lattice-covering/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/single-lattice-covering/tests/task.json b/tasks/single-lattice-covering/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d547ab590f480e0005df82c8cc54deffe6edfeac --- /dev/null +++ b/tasks/single-lattice-covering/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SingleLatticeCovering", + "comparator": { + "theorem_names": [ + "OAI.SingleLatticeCovering.single_lattice_covering" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11831 +} \ No newline at end of file diff --git a/tasks/single-lattice-covering/tests/test.sh b/tasks/single-lattice-covering/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/single-lattice-covering/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/singleton-loop-matching/environment/Dockerfile b/tasks/singleton-loop-matching/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/singleton-loop-matching/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/singleton-loop-matching/environment/fetch_mathlib.sh b/tasks/singleton-loop-matching/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/singleton-loop-matching/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/singleton-loop-matching/environment/lake-manifest.json b/tasks/singleton-loop-matching/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/singleton-loop-matching/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/singleton-loop-matching/environment/lakefile.lean b/tasks/singleton-loop-matching/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/singleton-loop-matching/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/singleton-loop-matching/environment/lean_setup.sh b/tasks/singleton-loop-matching/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/singleton-loop-matching/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/singleton-loop-matching/environment/pack_submission.py b/tasks/singleton-loop-matching/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/singleton-loop-matching/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/singleton-loop-matching/instruction.md b/tasks/singleton-loop-matching/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..463888f71e1ec784d8d0b4c4b33ddfb0d5099768 --- /dev/null +++ b/tasks/singleton-loop-matching/instruction.md @@ -0,0 +1,183 @@ +# openai/math challenge `SingletonLoopMatching` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `SingletonLoopMatching`, also at `/opt/openai-math/challenges/SingletonLoopMatching.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u_1 u_2 + +namespace MatchingEntropy +structure LooplessGraph (V : Type u_1) (E : Type u_2) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e=v ∨ G.right e=v +end LooplessGraph +end MatchingEntropy + +namespace BinaryMatching +abbrev Pair (n : ℕ) := {ij : Fin n × Fin n // ij.1 < ij.2} +def completeGraph (n : ℕ) : MatchingEntropy.LooplessGraph (Fin n) (Pair n) where + left e := e.val.1 + right e := e.val.2 + loopless e := ne_of_lt e.property + +structure Record where + left : ℕ + right : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + n : ℕ + records : List Record + valid : ∀ e∈records, e.left < e.right ∧ e.right < n + unique : (records.map (fun e => (e.left,e.right))).Nodup + +def multiplicity (G : Input) (e : Pair G.n) : ℕ := + match G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => 0 + | some r => r.multiplicity + + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length false ++ true :: n.bits + +def encodeRecord (r : Record) : List Bool := + encodeNat r.left ++ encodeNat r.right ++ encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + encodeNat G.n ++ encodeNat G.records.length ++ G.records.flatMap encodeRecord + +end BinaryMatching + +open scoped BigOperators + +namespace LoopMatching + +structure LoopRecord where + vertex : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + ordinary : BinaryMatching.Input + loops : List LoopRecord + valid : ∀ e ∈ loops, e.vertex < ordinary.n + unique : (loops.map LoopRecord.vertex).Nodup + +abbrev Input.n (G : Input) : ℕ := G.ordinary.n + +def loopMultiplicity (G : Input) (v : Fin G.n) : ℕ := + match G.loops.find? (fun r => r.vertex == v.val) with + | none => 0 + | some r => r.multiplicity + +def IsPartialMatching (n : ℕ) (M : Finset (BinaryMatching.Pair n)) : Prop := + ∀ v : Fin n, ∀ e ∈ M, ∀ f ∈ M, + (BinaryMatching.completeGraph n).Incident v e → + (BinaryMatching.completeGraph n).Incident v f → e = f + +abbrev PartialMatching (n : ℕ) := + { M : Finset (BinaryMatching.Pair n) // IsPartialMatching n M } + +noncomputable instance partialMatchingFintype (n : ℕ) : Fintype (PartialMatching n) := + Fintype.ofFinite _ + +noncomputable def loopVertices {n : ℕ} (M : PartialMatching n) : Finset (Fin n) := by + classical + exact Finset.univ.filter (fun v => + ∀ e ∈ M.val, ¬ (BinaryMatching.completeGraph n).Incident v e) + +noncomputable def weight (G : Input) (M : PartialMatching G.n) : ℕ := + (∏ e ∈ M.val, BinaryMatching.multiplicity G.ordinary e) * + ∏ v ∈ loopVertices M, loopMultiplicity G v + +noncomputable def count (G : Input) : ℕ := ∑ M : PartialMatching G.n, weight G M + + +def encodeLoopRecord (r : LoopRecord) : List Bool := + BinaryMatching.encodeNat r.vertex ++ BinaryMatching.encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + BinaryMatching.encodeInput G.ordinary ++ + BinaryMatching.encodeNat G.loops.length ++ G.loops.flatMap encodeLoopRecord + +def encodeOutput (a : ℕ × ℕ) : List Bool := + BinaryMatching.encodeNat a.1 ++ BinaryMatching.encodeNat a.2 + + +def FullEndpoint : Prop := + ∃ A : Input → ℕ × ℕ, + ∃ machine : Turing.TM2ComputableInPolyTime encodeInput encodeOutput A, + (∀ k, Finite (machine.tm.Γ k)) ∧ + (∃ P : Polynomial ℕ, ∀ G, + (encodeOutput (A G)).length ≤ P.eval (encodeInput G).length) ∧ + ∀ G, 0 < (A G).2 ∧ + (A G).1 ≤ (A G).2 * count G ∧ + (A G).2 * count G ≤ 2 ^ (18 * G.n) * (A G).1 ∧ + ((A G).1 = 0 ↔ count G = 0) + +end LoopMatching + +namespace LoopMatching + +/-- A finite-alphabet polynomial-time rational approximation for singleton-loop matchings. -/ +theorem fullEndpoint : FullEndpoint := by + sorry + +end LoopMatching + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SingletonLoopMatching.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.LoopMatching.fullEndpoint` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/singleton-loop-matching/solution/closure.txt b/tasks/singleton-loop-matching/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..306c256b4915d42b49470eaf5dffe35275606573 --- /dev/null +++ b/tasks/singleton-loop-matching/solution/closure.txt @@ -0,0 +1,136 @@ +OAI.Combinatorics.PerfectMatching.AlgorithmPartition +OAI.Combinatorics.PerfectMatching.Ascent +OAI.Combinatorics.PerfectMatching.Basic +OAI.Combinatorics.PerfectMatching.Calculus +OAI.Combinatorics.PerfectMatching.CompletePairs +OAI.Combinatorics.PerfectMatching.Completion +OAI.Combinatorics.PerfectMatching.Continuity +OAI.Combinatorics.PerfectMatching.Contraction +OAI.Combinatorics.PerfectMatching.CountCorrect +OAI.Combinatorics.PerfectMatching.Coupling +OAI.Combinatorics.PerfectMatching.Covariance +OAI.Combinatorics.PerfectMatching.Duality +OAI.Combinatorics.PerfectMatching.DyadicEntropy +OAI.Combinatorics.PerfectMatching.DyadicEnvelope +OAI.Combinatorics.PerfectMatching.ElementaryCount +OAI.Combinatorics.PerfectMatching.Entropy +OAI.Combinatorics.PerfectMatching.EntropyUpper +OAI.Combinatorics.PerfectMatching.Face +OAI.Combinatorics.PerfectMatching.FeasibilityRepair +OAI.Combinatorics.PerfectMatching.ForcedReduction +OAI.Combinatorics.PerfectMatching.Main +OAI.Combinatorics.PerfectMatching.MatchingCovariance +OAI.Combinatorics.PerfectMatching.Model +OAI.Combinatorics.PerfectMatching.ObjectivePenalty +OAI.Combinatorics.PerfectMatching.OddCuts +OAI.Combinatorics.PerfectMatching.Optimizer +OAI.Combinatorics.PerfectMatching.ParameterBounds +OAI.Combinatorics.PerfectMatching.Partition +OAI.Combinatorics.PerfectMatching.Polyhedron +OAI.Combinatorics.PerfectMatching.Polytope +OAI.Combinatorics.PerfectMatching.SecondVariation +OAI.Combinatorics.PerfectMatching.Separable +OAI.Combinatorics.PerfectMatching.SeparableCovariance +OAI.Combinatorics.PerfectMatching.SeparableLower +OAI.Combinatorics.PerfectMatching.Simplex +OAI.Combinatorics.PerfectMatching.SizeBounds +OAI.Combinatorics.PerfectMatching.Violation +OAI.Combinatorics.PerfectMatching.WeightedSpectrum +OAI.Computability.LoopMatching.Accumulator +OAI.Computability.LoopMatching.Approximation +OAI.Computability.LoopMatching.BinaryMultiply +OAI.Computability.LoopMatching.BitAdd +OAI.Computability.LoopMatching.BitAddRoutine +OAI.Computability.LoopMatching.BitLength +OAI.Computability.LoopMatching.BitNormalize +OAI.Computability.LoopMatching.ChoiceCounts +OAI.Computability.LoopMatching.CountDecomposition +OAI.Computability.LoopMatching.CountedParser +OAI.Computability.LoopMatching.Endpoint +OAI.Computability.LoopMatching.ExpandBijection +OAI.Computability.LoopMatching.ExpandCount +OAI.Computability.LoopMatching.ExpandInput +OAI.Computability.LoopMatching.InputDecode +OAI.Computability.LoopMatching.InputMachine +OAI.Computability.LoopMatching.LiteralChoices +OAI.Computability.LoopMatching.LoopParser +OAI.Computability.LoopMatching.MachineMain +OAI.Computability.LoopMatching.Main +OAI.Computability.LoopMatching.Model +OAI.Computability.LoopMatching.RawAccumulator +OAI.Computability.LoopMatching.SmallBoundary +OAI.Computability.LoopMatching.SparseBoundary +OAI.Computability.MatchingCount.ArgRoutine +OAI.Computability.MatchingCount.BinaryAlgorithm +OAI.Computability.MatchingCount.BinaryParser +OAI.Computability.MatchingCount.BinarySolve +OAI.Computability.MatchingCount.CappedPower +OAI.Computability.MatchingCount.CutAlgebra +OAI.Computability.MatchingCount.DenseOracle +OAI.Computability.MatchingCount.DivisionRoutine +OAI.Computability.MatchingCount.FiniteStack +OAI.Computability.MatchingCount.FoldRoutine +OAI.Computability.MatchingCount.GuardRoutine +OAI.Computability.MatchingCount.IntegerRoutine +OAI.Computability.MatchingCount.IterateRoutine +OAI.Computability.MatchingCount.LengthRoutine +OAI.Computability.MatchingCount.ListNumeric +OAI.Computability.MatchingCount.ListRoutine +OAI.Computability.MatchingCount.MapRoutine +OAI.Computability.MatchingCount.OddCutParity +OAI.Computability.MatchingCount.OddCutUncross +OAI.Computability.MatchingCount.OddMincut +OAI.Computability.MatchingCount.OptionCases +OAI.Computability.MatchingCount.OracleBounds +OAI.Computability.MatchingCount.OrbitRoutine +OAI.Computability.MatchingCount.PairRoutine +OAI.Computability.MatchingCount.ParamRoutine +OAI.Computability.MatchingCount.ParserSupport +OAI.Computability.MatchingCount.PolyCoding +OAI.Computability.MatchingCount.ProjectionRoutine +OAI.Computability.MatchingCount.RawBitsBridge +OAI.Computability.MatchingCount.RawContraction +OAI.Computability.MatchingCount.RawContractionCompiler +OAI.Computability.MatchingCount.RawData +OAI.Computability.MatchingCount.RawFlow +OAI.Computability.MatchingCount.RawFlowCompiler +OAI.Computability.MatchingCount.RawFlowSize +OAI.Computability.MatchingCount.RawInput +OAI.Computability.MatchingCount.RawOddBounds +OAI.Computability.MatchingCount.RawOddCompiler +OAI.Computability.MatchingCount.RawOddCut +OAI.Computability.MatchingCount.RawOptimizer +OAI.Computability.MatchingCount.RawOptimizerCompiler +OAI.Computability.MatchingCount.RawOptimizerData +OAI.Computability.MatchingCount.RawOptimizerDataCompiler +OAI.Computability.MatchingCount.RawOptimizerRows +OAI.Computability.MatchingCount.RawOptimizerRowsCompiler +OAI.Computability.MatchingCount.RawPrimitives +OAI.Computability.MatchingCount.RawRoutine +OAI.Computability.MatchingCount.RawSearch +OAI.Computability.MatchingCount.RawSearchCompiler +OAI.Computability.MatchingCount.RawSearchSize +OAI.Computability.MatchingCount.RawSize +OAI.Computability.MatchingCount.RecursiveBounds +OAI.Computability.MatchingCount.RecursiveCoding +OAI.Computability.MatchingCount.RecursiveCompiler +OAI.Computability.MatchingCount.RecursiveEval +OAI.Computability.MatchingCount.ResidualSearch +OAI.Computability.MatchingCount.ScaledAlgorithm +OAI.Computability.MatchingCount.ScaledBounds +OAI.Computability.MatchingCount.ScaledState +OAI.Computability.MatchingCount.SelectRoutine +OAI.Computability.MatchingCount.SequenceRoutine +OAI.Computability.MatchingCount.StackCopy +OAI.Computability.MatchingCount.StackEmbed +OAI.Computability.MatchingCount.StackFrame +OAI.Computability.MatchingCount.StackMacros +OAI.Computability.MatchingCount.StackPair +OAI.Computability.MatchingCount.StackRoutine +OAI.Computability.MatchingCount.SumRoutine +OAI.Computability.MatchingCount.TerminalMincut +OAI.Computability.MatchingCount.UnaryArithmetic +OAI.Computability.MatchingCount.UnaryClog +OAI.Computability.MatchingCount.UnaryDivision +OAI.Computability.MatchingCount.UnitFlow +OAI.Computability.MatchingCount.UnitMincut diff --git a/tasks/singleton-loop-matching/solution/reference.py b/tasks/singleton-loop-matching/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/singleton-loop-matching/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/singleton-loop-matching/solution/solve.sh b/tasks/singleton-loop-matching/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b06699c48cda9b7a6129876b1b77ec0e4fd6981c --- /dev/null +++ b/tasks/singleton-loop-matching/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SingletonLoopMatching, i.e. module OAI.Computability.LoopMatching.Endpoint and the +# 136 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.LoopMatching.Endpoint /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SingletonLoopMatching" diff --git a/tasks/singleton-loop-matching/task.toml b/tasks/singleton-loop-matching/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..90b25a774726214f0575e26fc729e7a17ef08bd2 --- /dev/null +++ b/tasks/singleton-loop-matching/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/singleton-loop-matching" +version = "1.0.0" +description = "Prove SingletonLoopMatching (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SingletonLoopMatching.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SingletonLoopMatching" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.LoopMatching.fullEndpoint"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.LoopMatching.Endpoint" +reference_modules = 136 +reference_lean_bytes = 719294 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1239 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12347 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/singleton-loop-matching/tests/Challenge.lean b/tasks/singleton-loop-matching/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0e51d3717c63d11ff7a4b6f920ccbfd8a71f447a --- /dev/null +++ b/tasks/singleton-loop-matching/tests/Challenge.lean @@ -0,0 +1,132 @@ +import Mathlib + +namespace OAI + +universe u_1 u_2 + +namespace MatchingEntropy +structure LooplessGraph (V : Type u_1) (E : Type u_2) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e +namespace LooplessGraph +variable {V : Type u_1} {E : Type u_2} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e=v ∨ G.right e=v +end LooplessGraph +end MatchingEntropy + +namespace BinaryMatching +abbrev Pair (n : ℕ) := {ij : Fin n × Fin n // ij.1 < ij.2} +def completeGraph (n : ℕ) : MatchingEntropy.LooplessGraph (Fin n) (Pair n) where + left e := e.val.1 + right e := e.val.2 + loopless e := ne_of_lt e.property + +structure Record where + left : ℕ + right : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + n : ℕ + records : List Record + valid : ∀ e∈records, e.left < e.right ∧ e.right < n + unique : (records.map (fun e => (e.left,e.right))).Nodup + +def multiplicity (G : Input) (e : Pair G.n) : ℕ := + match G.records.find? (fun r => r.left=e.val.1.val && r.right=e.val.2.val) with + | none => 0 + | some r => r.multiplicity + + +def encodeNat (n : ℕ) : List Bool := + List.replicate n.bits.length false ++ true :: n.bits + +def encodeRecord (r : Record) : List Bool := + encodeNat r.left ++ encodeNat r.right ++ encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + encodeNat G.n ++ encodeNat G.records.length ++ G.records.flatMap encodeRecord + +end BinaryMatching + +open scoped BigOperators + +namespace LoopMatching + +structure LoopRecord where + vertex : ℕ + multiplicity : ℕ + deriving DecidableEq + +structure Input where + ordinary : BinaryMatching.Input + loops : List LoopRecord + valid : ∀ e ∈ loops, e.vertex < ordinary.n + unique : (loops.map LoopRecord.vertex).Nodup + +abbrev Input.n (G : Input) : ℕ := G.ordinary.n + +def loopMultiplicity (G : Input) (v : Fin G.n) : ℕ := + match G.loops.find? (fun r => r.vertex == v.val) with + | none => 0 + | some r => r.multiplicity + +def IsPartialMatching (n : ℕ) (M : Finset (BinaryMatching.Pair n)) : Prop := + ∀ v : Fin n, ∀ e ∈ M, ∀ f ∈ M, + (BinaryMatching.completeGraph n).Incident v e → + (BinaryMatching.completeGraph n).Incident v f → e = f + +abbrev PartialMatching (n : ℕ) := + { M : Finset (BinaryMatching.Pair n) // IsPartialMatching n M } + +noncomputable instance partialMatchingFintype (n : ℕ) : Fintype (PartialMatching n) := + Fintype.ofFinite _ + +noncomputable def loopVertices {n : ℕ} (M : PartialMatching n) : Finset (Fin n) := by + classical + exact Finset.univ.filter (fun v => + ∀ e ∈ M.val, ¬ (BinaryMatching.completeGraph n).Incident v e) + +noncomputable def weight (G : Input) (M : PartialMatching G.n) : ℕ := + (∏ e ∈ M.val, BinaryMatching.multiplicity G.ordinary e) * + ∏ v ∈ loopVertices M, loopMultiplicity G v + +noncomputable def count (G : Input) : ℕ := ∑ M : PartialMatching G.n, weight G M + + +def encodeLoopRecord (r : LoopRecord) : List Bool := + BinaryMatching.encodeNat r.vertex ++ BinaryMatching.encodeNat r.multiplicity + +def encodeInput (G : Input) : List Bool := + BinaryMatching.encodeInput G.ordinary ++ + BinaryMatching.encodeNat G.loops.length ++ G.loops.flatMap encodeLoopRecord + +def encodeOutput (a : ℕ × ℕ) : List Bool := + BinaryMatching.encodeNat a.1 ++ BinaryMatching.encodeNat a.2 + + +def FullEndpoint : Prop := + ∃ A : Input → ℕ × ℕ, + ∃ machine : Turing.TM2ComputableInPolyTime encodeInput encodeOutput A, + (∀ k, Finite (machine.tm.Γ k)) ∧ + (∃ P : Polynomial ℕ, ∀ G, + (encodeOutput (A G)).length ≤ P.eval (encodeInput G).length) ∧ + ∀ G, 0 < (A G).2 ∧ + (A G).1 ≤ (A G).2 * count G ∧ + (A G).2 * count G ≤ 2 ^ (18 * G.n) * (A G).1 ∧ + ((A G).1 = 0 ↔ count G = 0) + +end LoopMatching + +namespace LoopMatching + +/-- A finite-alphabet polynomial-time rational approximation for singleton-loop matchings. -/ +theorem fullEndpoint : FullEndpoint := by + sorry + +end LoopMatching + +end OAI diff --git a/tasks/singleton-loop-matching/tests/grade.py b/tasks/singleton-loop-matching/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/singleton-loop-matching/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/singleton-loop-matching/tests/task.json b/tasks/singleton-loop-matching/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9ae5a6b931208a6410d8ca3518a040678c40d2d5 --- /dev/null +++ b/tasks/singleton-loop-matching/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SingletonLoopMatching", + "comparator": { + "theorem_names": [ + "OAI.LoopMatching.fullEndpoint" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11447 +} \ No newline at end of file diff --git a/tasks/singleton-loop-matching/tests/test.sh b/tasks/singleton-loop-matching/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/singleton-loop-matching/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sk-full-support/environment/Dockerfile b/tasks/sk-full-support/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sk-full-support/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sk-full-support/environment/fetch_mathlib.sh b/tasks/sk-full-support/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sk-full-support/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sk-full-support/environment/lake-manifest.json b/tasks/sk-full-support/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sk-full-support/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sk-full-support/environment/lakefile.lean b/tasks/sk-full-support/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sk-full-support/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sk-full-support/environment/lean_setup.sh b/tasks/sk-full-support/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sk-full-support/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sk-full-support/environment/pack_submission.py b/tasks/sk-full-support/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sk-full-support/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sk-full-support/instruction.md b/tasks/sk-full-support/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fb73fecdacce9d3a73b937588bf9df2520e64352 --- /dev/null +++ b/tasks/sk-full-support/instruction.md @@ -0,0 +1,149 @@ +# openai/math challenge `SKFullSupport` (family 281) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 281 of the release, *QAOA optimality for the SK model* +(Mathematical physics). The family as a whole: Proves that QAOA approaches the ground-state energy of the Gaussian zero-field Sherrington–Kirkpatrick model when system size tends to infinity before circuit depth. For every accuracy, finite depth and deterministic angles independent of size and disorder achieve the required limiting expected energy per spin. This also yields leading-order optimal expected MaxCut values on large-degree random regular graphs, with size tending to infinity before degree. + +The challenge is `SKFullSupport`, also at `/opt/openai-math/challenges/SKFullSupport.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal Topology + +noncomputable section + +namespace ZeroTemperatureSK + +abbrev Time := Set.Ico (0 : ℝ) 1 + +def extend (γ : Time → ℝ) (t : ℝ) : ℝ := + if ht : t ∈ Set.Ico (0 : ℝ) 1 then γ ⟨t, ht⟩ else 0 + +structure OrderParameter where + val : Time → ℝ + nonneg : ∀ t, 0 ≤ val t + monotone : Monotone val + right_continuous : ∀ t, ContinuousWithinAt val (Set.Ici t) t + integrable : Integrable (extend val) + +structure BrownianSystem (Ω : Type*) [MeasurableSpace Ω] where + law : Measure Ω + isProbability : IsProbabilityMeasure law + B : ℝ≥0 → Ω → ℝ + measurable : ∀ t, Measurable (B t) + brownian : IsBrownianReal B law + +variable {Ω : Type*} [MeasurableSpace Ω] + +def incrementFiltration (W : BrownianSystem Ω) (t : ℝ≥0) : + Filtration ℝ≥0 ‹MeasurableSpace Ω› := + Filtration.natural (fun s ω => W.B (t + s) ω - W.B t ω) + (fun s => ((W.measurable (t + s)).sub (W.measurable t)).stronglyMeasurable) + +structure Control (W : BrownianSystem Ω) (t : ℝ≥0) where + val : ℝ≥0 → Ω → ℝ + progressive : IsProgressive (incrementFiltration W t) val + bound : ∀ s ω, |val s ω| ≤ 1 + +def controlPayoff (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) + (α : Control W (Real.toNNReal t)) (ω : Ω) : ℝ := + |x + W.B 1 ω - W.B (Real.toNNReal t) ω + + ∫ s in t..1, extend γ.val s * α.val (Real.toNNReal (s - t)) ω| - + (1 / 2 : ℝ) * ∫ s in t..1, extend γ.val s * (α.val (Real.toNNReal (s - t)) ω)^2 + +def value (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + sSup (Set.range (fun α : Control W (Real.toNNReal t) => + ∫ ω, controlPayoff W γ t x α ω ∂W.law)) + +def gradient (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (value W γ t) x + +def curvature (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (gradient W γ t) x + +def parisi (W : BrownianSystem Ω) (γ : OrderParameter) : ℝ := + value W γ 0 0 - (1 / 2 : ℝ) * ∫ t in (0 : ℝ)..1, t * extend γ.val t + +def IsMinimizer (W : BrownianSystem Ω) (γ : OrderParameter) : Prop := + ∀ η : OrderParameter, parisi W γ ≤ parisi W η + +def IsStieltjesMeasure (γ : OrderParameter) (μ : Measure Time) : Prop := + ∀ t : Time, μ (Set.Iic t) = ENNReal.ofReal (γ.val t) + +def IsDiffusion (W : BrownianSystem Ω) (γ : OrderParameter) + (X : ℝ≥0 → Ω → ℝ) : Prop := + IsProgressive (Filtration.natural W.B (fun t => (W.measurable t).stronglyMeasurable)) X ∧ + (∀ᵐ ω ∂W.law, ContinuousOn (fun t : ℝ => X (Real.toNNReal t) ω) (Set.Icc 0 1) ∧ + X 0 ω = 0 ∧ ∀ t ∈ Set.Icc (0 : ℝ) 1, + X (Real.toNNReal t) ω = W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..t, extend γ.val s * + gradient W γ s (X (Real.toNNReal s) ω)) + +def squareMoment (W : BrownianSystem Ω) (γ : OrderParameter) + (X : ℝ≥0 → Ω → ℝ) (t : ℝ) : ℝ := + ∫ ω, (gradient W γ t (X (Real.toNNReal t) ω))^2 ∂W.law + +def FullSupportConclusion (W : BrownianSystem Ω) (γ : OrderParameter) : Prop := + (∃ μ : Measure Time, IsStieltjesMeasure γ μ) ∧ + (∃ X : ℝ≥0 → Ω → ℝ, IsDiffusion W γ X) ∧ + (∀ μ : Measure Time, IsStieltjesMeasure γ μ → μ.support = Set.univ) ∧ + (∀ a b : Time, a < b → γ.val a < γ.val b) ∧ + ∀ X : ℝ≥0 → Ω → ℝ, IsDiffusion W γ X → ∀ t : Time, + squareMoment W γ X t = (t : ℝ) ∧ + (∫ ω, (curvature W γ t (X (Real.toNNReal t) ω))^2 ∂W.law) = 1 + +theorem full_support (W : BrownianSystem Ω) (γ : OrderParameter) + (hmin : IsMinimizer W γ) : FullSupportConclusion W γ := by + sorry + +end ZeroTemperatureSK + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SKFullSupport.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ZeroTemperatureSK.full_support` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sk-full-support/solution/closure.txt b/tasks/sk-full-support/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c4adc3a23e5c83053201c54144cbf62f36137b1 --- /dev/null +++ b/tasks/sk-full-support/solution/closure.txt @@ -0,0 +1,135 @@ +OAI.Probability.SKSupport.Backward.Backward +OAI.Probability.SKSupport.Backward.BackwardComparison +OAI.Probability.SKSupport.Backward.BackwardGradientMild +OAI.Probability.SKSupport.Backward.BackwardGradientSqJointBound +OAI.Probability.SKSupport.Backward.BackwardJointBound +OAI.Probability.SKSupport.Backward.BackwardRescale +OAI.Probability.SKSupport.Backward.GaussianBackwardShapes +OAI.Probability.SKSupport.Backward.TerminalTailValue +OAI.Probability.SKSupport.Backward.TerminalTransition +OAI.Probability.SKSupport.Backward.TiltedBackward +OAI.Probability.SKSupport.Control.CoefficientApprox +OAI.Probability.SKSupport.Control.ControlPayoffConvex +OAI.Probability.SKSupport.Control.ControlledGrid +OAI.Probability.SKSupport.Control.ExpectedControlPayoff +OAI.Probability.SKSupport.Control.FiniteContinuity +OAI.Probability.SKSupport.Control.GridApprox +OAI.Probability.SKSupport.Control.GridBridge +OAI.Probability.SKSupport.Control.ValueDifference +OAI.Probability.SKSupport.Control.VariableGrid +OAI.Probability.SKSupport.Density.Certificate +OAI.Probability.SKSupport.Density.CoerciveMoments +OAI.Probability.SKSupport.Density.DensityFubini +OAI.Probability.SKSupport.Density.DensityHeat +OAI.Probability.SKSupport.Density.FiniteDensity +OAI.Probability.SKSupport.Density.FiniteForwardRatio +OAI.Probability.SKSupport.Density.GaussianDecay +OAI.Probability.SKSupport.Density.GaussianLogDensity +OAI.Probability.SKSupport.Density.GaussianTails +OAI.Probability.SKSupport.Density.RatioComparison +OAI.Probability.SKSupport.Density.RatioJets +OAI.Probability.SKSupport.Density.SampleJets +OAI.Probability.SKSupport.Diffusion.AbsIncrement +OAI.Probability.SKSupport.Diffusion.AffineComparison +OAI.Probability.SKSupport.Diffusion.BoundedDiffusionProperties +OAI.Probability.SKSupport.Diffusion.CompactDrift +OAI.Probability.SKSupport.Diffusion.Diffusion +OAI.Probability.SKSupport.Diffusion.DiffusionStability +OAI.Probability.SKSupport.Diffusion.ExpectedBrownianStep +OAI.Probability.SKSupport.Diffusion.ExpectedFeedbackStep +OAI.Probability.SKSupport.Diffusion.FeedbackVerification +OAI.Probability.SKSupport.Diffusion.FiniteFeedback +OAI.Probability.SKSupport.Diffusion.FiniteTransition +OAI.Probability.SKSupport.Diffusion.MixedDrift +OAI.Probability.SKSupport.Diffusion.MixedPathStability +OAI.Probability.SKSupport.Diffusion.PicardDiffusion +OAI.Probability.SKSupport.Diffusion.PicardUniqueness +OAI.Probability.SKSupport.Diffusion.ProgressiveBrownian +OAI.Probability.SKSupport.Diffusion.ProgressiveIntegralMeasurable +OAI.Probability.SKSupport.Diffusion.StepDrift +OAI.Probability.SKSupport.Diffusion.TerminalShapes +OAI.Probability.SKSupport.Diffusion.Uniqueness +OAI.Probability.SKSupport.Diffusion.VariableFeedbackEuler +OAI.Probability.SKSupport.Foundations.AdaptedIndepIncrement +OAI.Probability.SKSupport.Foundations.BoundedSmooth +OAI.Probability.SKSupport.Foundations.Cascade +OAI.Probability.SKSupport.Foundations.Const +OAI.Probability.SKSupport.Foundations.Control +OAI.Probability.SKSupport.Foundations.ControlledState +OAI.Probability.SKSupport.Foundations.DerivVarianceHeatCurve +OAI.Probability.SKSupport.Foundations.DerivWithinVarianceHeatWeightExp +OAI.Probability.SKSupport.Foundations.ElementaryControl +OAI.Probability.SKSupport.Foundations.Equation +OAI.Probability.SKSupport.Foundations.ExpTranslateLocalBound +OAI.Probability.SKSupport.Foundations.ExpectedVerificationStep +OAI.Probability.SKSupport.Foundations.ExponentialBoundLipschitz +OAI.Probability.SKSupport.Foundations.Finite +OAI.Probability.SKSupport.Foundations.FiniteValue +OAI.Probability.SKSupport.Foundations.GradientAbs +OAI.Probability.SKSupport.Foundations.IntegrableCompBoundedDeriv +OAI.Probability.SKSupport.Foundations.IntegralIoiMulExpSq +OAI.Probability.SKSupport.Foundations.InvSqrtNegHalf +OAI.Probability.SKSupport.Foundations.MeasurableSpatialDeriv +OAI.Probability.SKSupport.Foundations.RightCoeffApprox +OAI.Probability.SKSupport.Foundations.RightGenerator +OAI.Probability.SKSupport.Foundations.Semigroup +OAI.Probability.SKSupport.Foundations.SmoothingStep +OAI.Probability.SKSupport.Foundations.SoftAbs +OAI.Probability.SKSupport.Foundations.StepData +OAI.Probability.SKSupport.Foundations.SumRangeBlocks +OAI.Probability.SKSupport.Foundations.Taylor1Bound +OAI.Probability.SKSupport.Foundations.VarianceHeat +OAI.Probability.SKSupport.Foundations.VarianceHeatGradientBound +OAI.Probability.SKSupport.Main +OAI.Probability.SKSupport.Model +OAI.Probability.SKSupport.Moments.BurgersJets +OAI.Probability.SKSupport.Moments.Curvature +OAI.Probability.SKSupport.Moments.FamilyReparam +OAI.Probability.SKSupport.Moments.FiniteStrictConvex +OAI.Probability.SKSupport.Moments.IntegratedCompletionSquare +OAI.Probability.SKSupport.Moments.JetFields +OAI.Probability.SKSupport.Moments.NormalFirstMoment +OAI.Probability.SKSupport.Moments.NormalThirdMoment +OAI.Probability.SKSupport.Moments.PerturbationLimits +OAI.Probability.SKSupport.Moments.PositiveGradientError +OAI.Probability.SKSupport.Moments.SquareEquation +OAI.Probability.SKSupport.Moments.StrictMoments +OAI.Probability.SKSupport.Moments.StripSquareMoment +OAI.Probability.SKSupport.Moments.ThirdFields +OAI.Probability.SKSupport.Parabolic.AffineEvolution +OAI.Probability.SKSupport.Parabolic.BurgersConstruction +OAI.Probability.SKSupport.Parabolic.ForwardConstruction +OAI.Probability.SKSupport.Parabolic.ForwardGeometry +OAI.Probability.SKSupport.Parabolic.ForwardRegularity +OAI.Probability.SKSupport.Parabolic.ForwardSigns +OAI.Probability.SKSupport.Parabolic.FullLineComparison +OAI.Probability.SKSupport.Parabolic.GradientStability +OAI.Probability.SKSupport.Parabolic.ReverseBurgers +OAI.Probability.SKSupport.Parabolic.TiltedEvolution +OAI.Probability.SKSupport.Parabolic.TiltedMean +OAI.Probability.SKSupport.Parabolic.TiltedTransition +OAI.Probability.SKSupport.Parabolic.UniformTiltedMeanBounds +OAI.Probability.SKSupport.Parabolic.VarianceTilted +OAI.Probability.SKSupport.Regularity.AbsExtend +OAI.Probability.SKSupport.Regularity.BoundedSmoothFamily +OAI.Probability.SKSupport.Regularity.ClosedTime +OAI.Probability.SKSupport.Regularity.FamilyDifferentiation +OAI.Probability.SKSupport.Regularity.GaussianFlowRegularity +OAI.Probability.SKSupport.Regularity.GaussianValueContinuity +OAI.Probability.SKSupport.Regularity.IntegralTimeStep +OAI.Probability.SKSupport.Regularity.JointRegularity +OAI.Probability.SKSupport.Regularity.MixedIdentity +OAI.Probability.SKSupport.Regularity.ParameterChords +OAI.Probability.SKSupport.Regularity.PositiveRegularity +OAI.Probability.SKSupport.Regularity.Regularity +OAI.Probability.SKSupport.Regularity.RightRegularity +OAI.Probability.SKSupport.Regularity.TimeFields +OAI.Probability.SKSupport.Regularity.TimeStepBound +OAI.Probability.SKSupport.Support.CDFParameters +OAI.Probability.SKSupport.Support.Closure +OAI.Probability.SKSupport.Support.ContactPotential +OAI.Probability.SKSupport.Support.FiniteCDF +OAI.Probability.SKSupport.Support.GapCurvature +OAI.Probability.SKSupport.Support.NoTerminalPlateau +OAI.Probability.SKSupport.Support.TerminalCurvature +OAI.Probability.SKSupport.Support.VariationIntegrals diff --git a/tasks/sk-full-support/solution/reference.py b/tasks/sk-full-support/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sk-full-support/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sk-full-support/solution/solve.sh b/tasks/sk-full-support/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac7711a034fa2f077fe7bf69b0224b50f416f093 --- /dev/null +++ b/tasks/sk-full-support/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SKFullSupport, i.e. module OAI.Probability.SKSupport.Main and the +# 135 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SKSupport.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SKFullSupport" diff --git a/tasks/sk-full-support/task.toml b/tasks/sk-full-support/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d0099ba3e1dda84aece93a3b9c60b5f409290eb7 --- /dev/null +++ b/tasks/sk-full-support/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sk-full-support" +version = "1.0.0" +description = "Prove SKFullSupport (openai/math family 281: QAOA optimality for the SK model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SKFullSupport.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SKFullSupport" +family = "281" +family_title = "QAOA optimality for the SK model" +subject = "Mathematical physics" +theorems = ["OAI.ZeroTemperatureSK.full_support"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SKSupport.Main" +reference_modules = 135 +reference_lean_bytes = 989995 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 964 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12590 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sk-full-support/tests/Challenge.lean b/tasks/sk-full-support/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2a4bdf1cabdbf723ea9ea2bd1705a6ee038e4f71 --- /dev/null +++ b/tasks/sk-full-support/tests/Challenge.lean @@ -0,0 +1,98 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal Topology + +noncomputable section + +namespace ZeroTemperatureSK + +abbrev Time := Set.Ico (0 : ℝ) 1 + +def extend (γ : Time → ℝ) (t : ℝ) : ℝ := + if ht : t ∈ Set.Ico (0 : ℝ) 1 then γ ⟨t, ht⟩ else 0 + +structure OrderParameter where + val : Time → ℝ + nonneg : ∀ t, 0 ≤ val t + monotone : Monotone val + right_continuous : ∀ t, ContinuousWithinAt val (Set.Ici t) t + integrable : Integrable (extend val) + +structure BrownianSystem (Ω : Type*) [MeasurableSpace Ω] where + law : Measure Ω + isProbability : IsProbabilityMeasure law + B : ℝ≥0 → Ω → ℝ + measurable : ∀ t, Measurable (B t) + brownian : IsBrownianReal B law + +variable {Ω : Type*} [MeasurableSpace Ω] + +def incrementFiltration (W : BrownianSystem Ω) (t : ℝ≥0) : + Filtration ℝ≥0 ‹MeasurableSpace Ω› := + Filtration.natural (fun s ω => W.B (t + s) ω - W.B t ω) + (fun s => ((W.measurable (t + s)).sub (W.measurable t)).stronglyMeasurable) + +structure Control (W : BrownianSystem Ω) (t : ℝ≥0) where + val : ℝ≥0 → Ω → ℝ + progressive : IsProgressive (incrementFiltration W t) val + bound : ∀ s ω, |val s ω| ≤ 1 + +def controlPayoff (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) + (α : Control W (Real.toNNReal t)) (ω : Ω) : ℝ := + |x + W.B 1 ω - W.B (Real.toNNReal t) ω + + ∫ s in t..1, extend γ.val s * α.val (Real.toNNReal (s - t)) ω| - + (1 / 2 : ℝ) * ∫ s in t..1, extend γ.val s * (α.val (Real.toNNReal (s - t)) ω)^2 + +def value (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + sSup (Set.range (fun α : Control W (Real.toNNReal t) => + ∫ ω, controlPayoff W γ t x α ω ∂W.law)) + +def gradient (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (value W γ t) x + +def curvature (W : BrownianSystem Ω) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (gradient W γ t) x + +def parisi (W : BrownianSystem Ω) (γ : OrderParameter) : ℝ := + value W γ 0 0 - (1 / 2 : ℝ) * ∫ t in (0 : ℝ)..1, t * extend γ.val t + +def IsMinimizer (W : BrownianSystem Ω) (γ : OrderParameter) : Prop := + ∀ η : OrderParameter, parisi W γ ≤ parisi W η + +def IsStieltjesMeasure (γ : OrderParameter) (μ : Measure Time) : Prop := + ∀ t : Time, μ (Set.Iic t) = ENNReal.ofReal (γ.val t) + +def IsDiffusion (W : BrownianSystem Ω) (γ : OrderParameter) + (X : ℝ≥0 → Ω → ℝ) : Prop := + IsProgressive (Filtration.natural W.B (fun t => (W.measurable t).stronglyMeasurable)) X ∧ + (∀ᵐ ω ∂W.law, ContinuousOn (fun t : ℝ => X (Real.toNNReal t) ω) (Set.Icc 0 1) ∧ + X 0 ω = 0 ∧ ∀ t ∈ Set.Icc (0 : ℝ) 1, + X (Real.toNNReal t) ω = W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..t, extend γ.val s * + gradient W γ s (X (Real.toNNReal s) ω)) + +def squareMoment (W : BrownianSystem Ω) (γ : OrderParameter) + (X : ℝ≥0 → Ω → ℝ) (t : ℝ) : ℝ := + ∫ ω, (gradient W γ t (X (Real.toNNReal t) ω))^2 ∂W.law + +def FullSupportConclusion (W : BrownianSystem Ω) (γ : OrderParameter) : Prop := + (∃ μ : Measure Time, IsStieltjesMeasure γ μ) ∧ + (∃ X : ℝ≥0 → Ω → ℝ, IsDiffusion W γ X) ∧ + (∀ μ : Measure Time, IsStieltjesMeasure γ μ → μ.support = Set.univ) ∧ + (∀ a b : Time, a < b → γ.val a < γ.val b) ∧ + ∀ X : ℝ≥0 → Ω → ℝ, IsDiffusion W γ X → ∀ t : Time, + squareMoment W γ X t = (t : ℝ) ∧ + (∫ ω, (curvature W γ t (X (Real.toNNReal t) ω))^2 ∂W.law) = 1 + +theorem full_support (W : BrownianSystem Ω) (γ : OrderParameter) + (hmin : IsMinimizer W γ) : FullSupportConclusion W γ := by + sorry + +end ZeroTemperatureSK + +end + +end OAI diff --git a/tasks/sk-full-support/tests/grade.py b/tasks/sk-full-support/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sk-full-support/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sk-full-support/tests/task.json b/tasks/sk-full-support/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2fd36fa8d4a81455f17828af15c021d286dd1624 --- /dev/null +++ b/tasks/sk-full-support/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SKFullSupport", + "comparator": { + "theorem_names": [ + "OAI.ZeroTemperatureSK.full_support" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11690 +} \ No newline at end of file diff --git a/tasks/sk-full-support/tests/test.sh b/tasks/sk-full-support/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sk-full-support/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sk-value/environment/Dockerfile b/tasks/sk-value/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sk-value/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sk-value/environment/fetch_mathlib.sh b/tasks/sk-value/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sk-value/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sk-value/environment/lake-manifest.json b/tasks/sk-value/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sk-value/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sk-value/environment/lakefile.lean b/tasks/sk-value/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sk-value/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sk-value/environment/lean_setup.sh b/tasks/sk-value/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sk-value/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sk-value/environment/pack_submission.py b/tasks/sk-value/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sk-value/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sk-value/instruction.md b/tasks/sk-value/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b019e8835bc1a128d60c64e0dee46e981ea10e21 --- /dev/null +++ b/tasks/sk-value/instruction.md @@ -0,0 +1,226 @@ +# openai/math challenge `SKValue` (family 281) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 281 of the release, *QAOA optimality for the SK model* +(Mathematical physics). The family as a whole: Proves that QAOA approaches the ground-state energy of the Gaussian zero-field Sherrington–Kirkpatrick model when system size tends to infinity before circuit depth. For every accuracy, finite depth and deterministic angles independent of size and disorder achieve the required limiting expected energy per spin. This also yields leading-order optimal expected MaxCut values on large-degree random regular graphs, with size tending to infinity before degree. + +The challenge is `SKValue`, also at `/opt/openai-math/challenges/SKValue.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter Set +open scoped Topology ENNReal NNReal BigOperators + +namespace SKValue + +noncomputable def standardGaussian : Measure ℝ := gaussianReal 0 1 + +instance : IsProbabilityMeasure standardGaussian := by unfold standardGaussian; infer_instance + +noncomputable def gaussianProduct (ι : Type) [Fintype ι] : Measure (ι → ℝ) := + Measure.pi (fun _ : ι ↦ standardGaussian) +instance gaussianProduct_probability (ι : Type) [Fintype ι] : + IsProbabilityMeasure (gaussianProduct ι) := by + unfold gaussianProduct + infer_instance + +def coordinate (N : ℕ) (j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + z ⟨j % (N+1), Nat.mod_lt _ (Nat.succ_pos _)⟩ + +noncomputable def stepSize (T : ℝ) (N : ℕ) : ℝ := T / N +noncomputable def meshTime (T : ℝ) (N j : ℕ) : ℝ := j * stepSize T N + +noncomputable def euler (T : ℝ) (N : ℕ) (γ : ℝ → ℝ) (u : ℝ → ℝ → ℝ) + (z : Fin (N+1) → ℝ) : ℕ → ℝ + | 0 => 0 + | j+1 => euler T N γ u z j + Real.sqrt (stepSize T N) * coordinate N j z + + stepSize T N * γ (meshTime T N j) * u (meshTime T N j) (euler T N γ u z j) + +structure OrderParameter where + coeff : ℝ → ℝ + nonneg : ∀ t ∈ Ico (0 : ℝ) 1, 0 ≤ coeff t + monotone : MonotoneOn coeff (Ico (0 : ℝ) 1) + rightContinuous : ∀ t ∈ Ico (0 : ℝ) 1, ContinuousWithinAt coeff (Ici t) t + integrable : IntegrableOn coeff (Ioc (0 : ℝ) 1) + +structure BrownianSpace where + Ω : Type + measurableSpace : MeasurableSpace Ω + μ : @Measure Ω measurableSpace + probability : @IsProbabilityMeasure Ω measurableSpace μ + B : ℝ≥0 → Ω → ℝ + measurable : ∀ t, @StronglyMeasurable Ω ℝ _ measurableSpace (B t) + brownian : @IsBrownianReal Ω measurableSpace B μ + +attribute [instance] BrownianSpace.measurableSpace BrownianSpace.probability + +noncomputable def BrownianSpace.filtration (W : BrownianSpace) : + Filtration ℝ≥0 W.measurableSpace := Filtration.natural W.B W.measurable + +noncomputable def shiftedFiltration (W : BrownianSpace) (t : ℝ) : + Filtration ℝ≥0 W.measurableSpace := + Filtration.natural (fun s ω ↦ W.B (Real.toNNReal t + s) ω - W.B (Real.toNNReal t) ω) + (fun _ ↦ (W.measurable _).sub (W.measurable _)) + +def Admissible (W : BrownianSpace) (t : ℝ) (α : ℝ≥0 → W.Ω → ℝ) : Prop := + IsProgressive (shiftedFiltration W t) α ∧ ∀ s ω, |α s ω| ≤ 1 + +noncomputable def controlPayoff (W : BrownianSpace) (γ : OrderParameter) + (t x : ℝ) (α : ℝ≥0 → W.Ω → ℝ) : ℝ := + ∫ ω, (|x + W.B 1 ω - W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..(1-t), γ.coeff (t+s) * α (Real.toNNReal s) ω| - + (1/2 : ℝ) * ∫ s in (0 : ℝ)..(1-t), γ.coeff (t+s) * α (Real.toNNReal s) ω ^ 2) ∂W.μ + +noncomputable def phi (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + sSup {r | ∃ α, Admissible W t α ∧ r = controlPayoff W γ t x α} + +noncomputable def gradient (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (phi W γ t) x + +noncomputable def curvature (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (gradient W γ t) x + +noncomputable def parisi (W : BrownianSpace) (γ : OrderParameter) : ℝ := + phi W γ 0 0 - (1/2 : ℝ) * ∫ t in (0 : ℝ)..1, t * γ.coeff t + +def IsMinimizer (W : BrownianSpace) (γ : OrderParameter) : Prop := + ∀ η : OrderParameter, parisi W γ ≤ parisi W η + +def IsDiffusion (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ) : Prop := + Adapted W.filtration (fun t ω ↦ X (min (t : ℝ) 1) ω) ∧ + (∀ᵐ ω ∂W.μ, ContinuousOn (fun t ↦ X t ω) (Icc (0 : ℝ) 1) ∧ + ∀ t ∈ Icc (0 : ℝ) 1, + X t ω = W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..t, γ.coeff s * gradient W γ s (X s ω)) + +noncomputable def spin (b : Bool) : ℝ := if b then 1 else -1 + +noncomputable def hamiltonian (n : ℕ) (J : (Fin n × Fin n) → ℝ) + (σ : Fin n → Bool) : ℝ := + (Real.sqrt (n : ℝ))⁻¹ * + ∑ i : Fin n, ∑ j : Fin n, if i < j then J (i,j) * spin (σ i) * spin (σ j) else 0 + +noncomputable def groundStateSequence (n : ℕ) : ℝ := + (n : ℝ)⁻¹ * ∫ J, sSup (range (hamiltonian n J)) ∂gaussianProduct (Fin n × Fin n) + +noncomputable def groundStateValue : ℝ := limUnder atTop groundStateSequence + +noncomputable def gradientStopped (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) (U : W.Ω → ℝ) (t : ℝ≥0) (ω : W.Ω) : ℝ := + if (t : ℝ) < 1 then gradient W γ t (X t ω) else U ω + +def ScalarValueConclusion (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) : Prop := + Tendsto groundStateSequence atTop (𝓝 groundStateValue) ∧ + ∃ U : W.Ω → ℝ, + Martingale (gradientStopped W γ X U) W.filtration W.μ ∧ + (∀ᵐ ω ∂W.μ, |U ω| ≤ 1 ∧ (U ω)^2 = 1 ∧ + Tendsto (fun t ↦ gradient W γ t (X t ω)) (𝓝[<] (1 : ℝ)) (𝓝 (U ω))) ∧ + Tendsto (fun t ↦ ∫ ω, (gradient W γ t (X t ω) - U ω)^2 ∂W.μ) + (𝓝[<] (1 : ℝ)) (𝓝 (0 : ℝ)) ∧ + groundStateValue = (∫ ω, |X 1 ω| ∂W.μ) - ∫ t in (0 : ℝ)..1, t * γ.coeff t ∧ + groundStateValue = ∫ ω, U ω * W.B 1 ω ∂W.μ ∧ + groundStateValue = ∫ t in (0 : ℝ)..1, ∫ ω, curvature W γ t (X t ω) ∂W.μ ∧ + IntervalIntegrable (fun t ↦ ∫ ω, curvature W γ t (X t ω) ∂W.μ) volume 0 1 + +noncomputable def eulerPath (W : BrownianSpace) (γ : OrderParameter) (T : ℝ) (N : ℕ) + (z : Fin (N+1) → ℝ) (j : ℕ) : ℝ := + euler T N γ.coeff (gradient W γ) z j + +noncomputable def rawCoefficient (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + curvature W γ (meshTime T N j) (eulerPath W γ T N z j) + +noncomputable def normalizer (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) : ℝ := + (Real.sqrt (∫ z, (rawCoefficient W γ T N j z)^2 ∂gaussianProduct (Fin (N+1))))⁻¹ + +noncomputable def gaussianIncrement (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + normalizer W γ T N j * rawCoefficient W γ T N j z * coordinate N j z + +noncomputable def roundedSign (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + Real.sign (gradient W γ T (eulerPath W γ T N z N) + + 2 * cdf standardGaussian (coordinate N N z) - 1) + +noncomputable def coefficientA (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) : ℝ := + if j = 0 then 0 else + ∫ z, roundedSign W γ T N z * gaussianIncrement W γ T N (j-1) z + ∂gaussianProduct (Fin (N+1)) + +noncomputable def coefficientB (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N i : ℕ) : ℝ := + ∫ z, roundedSign W γ T N z * coordinate N (i-1) z ∂gaussianProduct (Fin (N+1)) + +noncomputable def shiftedCoefficientSum (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N : ℕ) : ℝ := + ∑ j ∈ Finset.range (N+1), coefficientA W γ T N j * coefficientB W γ T N (j+1) + +def FiniteGaussianConclusion (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) (T : ℝ) : Prop := + (∀ᶠ N in atTop, ∀ j < N, 0 < normalizer W γ T N j) ∧ + Tendsto (shiftedCoefficientSum W γ T) atTop + (𝓝 (∫ t in (0 : ℝ)..T, ∫ ω, curvature W γ t (X t ω) ∂W.μ)) ∧ + Tendsto (fun S ↦ ∫ t in (0 : ℝ)..S, ∫ ω, curvature W γ t (X t ω) ∂W.μ) + (𝓝[<] (1 : ℝ)) (𝓝 groundStateValue) + +theorem value_consequences : + (∀ (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ), + IsMinimizer W γ → IsDiffusion W γ X → ScalarValueConclusion W γ X) ∧ + (∀ (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ) (T : ℝ), + 0 < T → T < 1 → IsMinimizer W γ → IsDiffusion W γ X → + FiniteGaussianConclusion W γ X T) ∧ + (∀ (W : BrownianSpace) (γ : OrderParameter), + IsMinimizer W γ → groundStateValue = parisi W γ) := by + sorry + +end SKValue + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SKValue.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SKValue.value_consequences` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sk-value/solution/closure.txt b/tasks/sk-value/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..6fe4c117c922234c56cf35f8f28da921eb9d5e6b --- /dev/null +++ b/tasks/sk-value/solution/closure.txt @@ -0,0 +1,212 @@ +OAI.Probability.SKValue.Coercivity.Coercivity +OAI.Probability.SKValue.Coercivity.CurvatureMoment +OAI.Probability.SKValue.Coercivity.FiniteCoercivity +OAI.Probability.SKValue.Coercivity.GapBoundary +OAI.Probability.SKValue.Coercivity.IntegratedCoercivity +OAI.Probability.SKValue.Coercivity.LiteralCoercivity +OAI.Probability.SKValue.Coercivity.ZeroFlux +OAI.Probability.SKValue.Coercivity.ZeroGapHump +OAI.Probability.SKValue.Control.ControlIntegral +OAI.Probability.SKValue.Control.ControlPayoffConvex +OAI.Probability.SKValue.Control.ControlStability +OAI.Probability.SKValue.Control.ControlValue +OAI.Probability.SKValue.Control.ControlVerification +OAI.Probability.SKValue.Control.Controls +OAI.Probability.SKValue.Control.FiniteStepControl +OAI.Probability.SKValue.Control.Forced +OAI.Probability.SKValue.Control.PhiRegularity +OAI.Probability.SKValue.Control.PolynomialGenerator +OAI.Probability.SKValue.Control.Regularity +OAI.Probability.SKValue.Control.StripRegularity +OAI.Probability.SKValue.Control.SupStability +OAI.Probability.SKValue.Control.Verification +OAI.Probability.SKValue.Equations.AdmissibleZero +OAI.Probability.SKValue.Equations.AestronglyMeasurableInitialMax +OAI.Probability.SKValue.Equations.BackwardComparison +OAI.Probability.SKValue.Equations.BackwardPolynomials +OAI.Probability.SKValue.Equations.BetaBound +OAI.Probability.SKValue.Equations.BrownianIncrementIndepPast +OAI.Probability.SKValue.Equations.BurgersMild +OAI.Probability.SKValue.Equations.CoupledComparison +OAI.Probability.SKValue.Equations.CoupledDensity +OAI.Probability.SKValue.Equations.CubicEnvelopeMean +OAI.Probability.SKValue.Equations.Cutoff +OAI.Probability.SKValue.Equations.DriftDefectUniformBound +OAI.Probability.SKValue.Equations.DuhamelJets +OAI.Probability.SKValue.Equations.FiniteRounded +OAI.Probability.SKValue.Equations.FirstMomentPerturbation +OAI.Probability.SKValue.Equations.ForcedGenerator +OAI.Probability.SKValue.Equations.ForwardComparison +OAI.Probability.SKValue.Equations.ForwardDensity +OAI.Probability.SKValue.Equations.GeneralProfileShape +OAI.Probability.SKValue.Equations.GradientErrorConstant +OAI.Probability.SKValue.Equations.GradientStrip +OAI.Probability.SKValue.Equations.GradientStripCore +OAI.Probability.SKValue.Equations.HalflineComparison +OAI.Probability.SKValue.Equations.InitialMax +OAI.Probability.SKValue.Equations.IntegralAbsSqrtSecond +OAI.Probability.SKValue.Equations.JetAlgebra +OAI.Probability.SKValue.Equations.LineComparison +OAI.Probability.SKValue.Equations.LipschitzCompMemLpFinite +OAI.Probability.SKValue.Equations.LiteralNormalizer +OAI.Probability.SKValue.Equations.MemLpLinearCombination +OAI.Probability.SKValue.Equations.ParabolicComparison +OAI.Probability.SKValue.Equations.ParametricChain +OAI.Probability.SKValue.Equations.PolynomialForced +OAI.Probability.SKValue.Equations.PolynomialMoment +OAI.Probability.SKValue.Equations.PolynomialObservable +OAI.Probability.SKValue.Equations.ProfileShape +OAI.Probability.SKValue.Equations.RawIncrement +OAI.Probability.SKValue.Equations.RealFiltration +OAI.Probability.SKValue.Equations.ResponseContraction +OAI.Probability.SKValue.Equations.ResponseJets +OAI.Probability.SKValue.Equations.Shift +OAI.Probability.SKValue.Equations.ShiftedPairing +OAI.Probability.SKValue.Equations.ShortStripClose +OAI.Probability.SKValue.Equations.StrictProfile +OAI.Probability.SKValue.Equations.StripIntegralLimit +OAI.Probability.SKValue.Equations.SumStepsSub +OAI.Probability.SKValue.Equations.TestGenerator +OAI.Probability.SKValue.Equations.TestPatch +OAI.Probability.SKValue.Equations.ThirdOrderRemainderBound +OAI.Probability.SKValue.Equations.TruncatedStieltjes +OAI.Probability.SKValue.Equations.UniformPolynomial +OAI.Probability.SKValue.Equations.ValueStrip +OAI.Probability.SKValue.Equations.WeightedCap +OAI.Probability.SKValue.Evolution.BoundedSmooth +OAI.Probability.SKValue.Evolution.BurgersDerivative +OAI.Probability.SKValue.Evolution.BurgersJets +OAI.Probability.SKValue.Evolution.ColeHopf +OAI.Probability.SKValue.Evolution.ColeHopfPDE +OAI.Probability.SKValue.Evolution.DensityPairing +OAI.Probability.SKValue.Evolution.DerivativeLimit +OAI.Probability.SKValue.Evolution.EvolutionDifferentiation +OAI.Probability.SKValue.Evolution.EvolutionPatch +OAI.Probability.SKValue.Evolution.EvolutionShift +OAI.Probability.SKValue.Evolution.EvolveStrips +OAI.Probability.SKValue.Evolution.FiniteStepEvolution +OAI.Probability.SKValue.Evolution.GridConvergence +OAI.Probability.SKValue.Evolution.GridProfile +OAI.Probability.SKValue.Evolution.HeatBounds +OAI.Probability.SKValue.Evolution.HeatContinuity +OAI.Probability.SKValue.Evolution.HeatConvexity +OAI.Probability.SKValue.Evolution.HeatDuality +OAI.Probability.SKValue.Evolution.HeatKernelBound +OAI.Probability.SKValue.Evolution.HeatRegularity +OAI.Probability.SKValue.Evolution.HeatTimeBound +OAI.Probability.SKValue.Evolution.HeatTransform +OAI.Probability.SKValue.Evolution.HigherPDE +OAI.Probability.SKValue.Evolution.IntegralPrimitiveTerminal +OAI.Probability.SKValue.Evolution.JetParity +OAI.Probability.SKValue.Evolution.L1Terminal +OAI.Probability.SKValue.Evolution.LogCoshTerminal +OAI.Probability.SKValue.Evolution.LogHeatJets +OAI.Probability.SKValue.Evolution.MeanDerivativeContinuous +OAI.Probability.SKValue.Evolution.MildBurgersJets +OAI.Probability.SKValue.Evolution.MonotoneWeightedGridBound +OAI.Probability.SKValue.Evolution.ShortStrip +OAI.Probability.SKValue.Evolution.SmoothApproxBounds +OAI.Probability.SKValue.Evolution.SmoothEvolution +OAI.Probability.SKValue.Evolution.SmoothFamily +OAI.Probability.SKValue.Evolution.TerminalAlgebra +OAI.Probability.SKValue.Evolution.TerminalError +OAI.Probability.SKValue.Evolution.TestEvolution +OAI.Probability.SKValue.Evolution.TestHeat +OAI.Probability.SKValue.Evolution.TestStrip +OAI.Probability.SKValue.Evolution.TimePatch +OAI.Probability.SKValue.Evolution.TimeWeightedIntervalIntegrable +OAI.Probability.SKValue.Evolution.UniformGridRiemannBound +OAI.Probability.SKValue.Gaussian.BrownianCoordinates +OAI.Probability.SKValue.Gaussian.CoordinateDependsBefore +OAI.Probability.SKValue.Gaussian.CoupledCoordinates +OAI.Probability.SKValue.Gaussian.DensityDerivative +OAI.Probability.SKValue.Gaussian.DensityJump +OAI.Probability.SKValue.Gaussian.EvenEvolution +OAI.Probability.SKValue.Gaussian.GaussianFactor +OAI.Probability.SKValue.Gaussian.GaussianSquareVariance +OAI.Probability.SKValue.Gaussian.IntegralPositiveMulGaussian +OAI.Probability.SKValue.Gaussian.ProfileLawStability +OAI.Probability.SKValue.Gaussian.ProfileSplit +OAI.Probability.SKValue.Gaussian.ShiftedBrownianCoordinates +OAI.Probability.SKValue.Gaussian.SplitConvergence +OAI.Probability.SKValue.Gaussian.SplitJets +OAI.Probability.SKValue.Gaussian.SplitShape +OAI.Probability.SKValue.Gaussian.UniformError +OAI.Probability.SKValue.GroundState.AdaptiveColumns +OAI.Probability.SKValue.GroundState.AffineComparison +OAI.Probability.SKValue.GroundState.BlockCoeff +OAI.Probability.SKValue.GroundState.BranchLaw +OAI.Probability.SKValue.GroundState.BranchMeanUpper +OAI.Probability.SKValue.GroundState.CascadeMoments +OAI.Probability.SKValue.GroundState.CascadePassage +OAI.Probability.SKValue.GroundState.ColumnBounds +OAI.Probability.SKValue.GroundState.ConstantFatou +OAI.Probability.SKValue.GroundState.CrossExpectation +OAI.Probability.SKValue.GroundState.EmpiricalCalculus +OAI.Probability.SKValue.GroundState.EmpiricalEnergyLimit +OAI.Probability.SKValue.GroundState.EmpiricalLog +OAI.Probability.SKValue.GroundState.EmpiricalPower +OAI.Probability.SKValue.GroundState.EmpiricalVectors +OAI.Probability.SKValue.GroundState.ExponentialMoments +OAI.Probability.SKValue.GroundState.FieldTreeLaw +OAI.Probability.SKValue.GroundState.FiniteBranching +OAI.Probability.SKValue.GroundState.GaussianColumn +OAI.Probability.SKValue.GroundState.GaussianTranspose +OAI.Probability.SKValue.GroundState.GaussianTree +OAI.Probability.SKValue.GroundState.GramSchmidtLimit +OAI.Probability.SKValue.GroundState.GumbelMax +OAI.Probability.SKValue.GroundState.GumbelReplacement +OAI.Probability.SKValue.GroundState.LiteralLower +OAI.Probability.SKValue.GroundState.LogComparison +OAI.Probability.SKValue.GroundState.MainConclusions +OAI.Probability.SKValue.GroundState.PredictableNormalizer +OAI.Probability.SKValue.GroundState.QuadraticSK +OAI.Probability.SKValue.GroundState.RandomColumn +OAI.Probability.SKValue.GroundState.RandomGuerra +OAI.Probability.SKValue.GroundState.RotatedCoefficients +OAI.Probability.SKValue.GroundState.RoundingSpin +OAI.Probability.SKValue.GroundState.StandardGaussian +OAI.Probability.SKValue.GroundState.TreeGuerra +OAI.Probability.SKValue.GroundState.TreeProductLaw +OAI.Probability.SKValue.GroundState.TreeWidths +OAI.Probability.SKValue.GroundState.WeakGuerra +OAI.Probability.SKValue.Main +OAI.Probability.SKValue.Model +OAI.Probability.SKValue.Processes.CrossMesh +OAI.Probability.SKValue.Processes.CrossMeshComparison +OAI.Probability.SKValue.Processes.CrossValueBound +OAI.Probability.SKValue.Processes.CurvatureNonneg +OAI.Probability.SKValue.Processes.DiffusionExistence +OAI.Probability.SKValue.Processes.DiffusionGradientCondExp +OAI.Probability.SKValue.Processes.DiffusionGradientWeakMartingaleLocal +OAI.Probability.SKValue.Processes.EulerL1 +OAI.Probability.SKValue.Processes.EulerLimitProcess +OAI.Probability.SKValue.Processes.EulerMemLp +OAI.Probability.SKValue.Processes.Feedback +OAI.Probability.SKValue.Processes.FiniteGaussianFixedStrip +OAI.Probability.SKValue.Processes.FiniteProfileLaw +OAI.Probability.SKValue.Processes.ForcedDiffusion +OAI.Probability.SKValue.Processes.ForcedExpectation +OAI.Probability.SKValue.Processes.GradientSquareIntegral +OAI.Probability.SKValue.Processes.Measurable +OAI.Probability.SKValue.Processes.MeshBrownian +OAI.Probability.SKValue.Processes.MeshMaxError +OAI.Probability.SKValue.Processes.MeshMeanBound +OAI.Probability.SKValue.Processes.MeshRaw +OAI.Probability.SKValue.Processes.StripPaths +OAI.Probability.SKValue.Processes.TerminalCondExp +OAI.Probability.SKValue.Processes.TestDiffusion +OAI.Probability.SKValue.Processes.TestExpectation +OAI.Probability.SKValue.Processes.UnitMomentMartingale +OAI.Probability.SKValue.Processes.ValueEulerOneStep +OAI.Probability.SKValue.Processes.VariableTestLaw +OAI.Probability.SKValue.Processes.Volterra +OAI.Probability.SKValue.Processes.WeightedTerminalExpectation +OAI.Probability.SKValue.Variation.ContactAssembly +OAI.Probability.SKValue.Variation.ContactIntegral +OAI.Probability.SKValue.Variation.ContactOrigin +OAI.Probability.SKValue.Variation.ContactVariations +OAI.Probability.SKValue.Variation.FirstVariationCompact +OAI.Probability.SKValue.Variation.MinimizerContact +OAI.Probability.SKValue.Variation.OrderVariations +OAI.Probability.SKValue.Variation.WeightedMoments diff --git a/tasks/sk-value/solution/reference.py b/tasks/sk-value/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sk-value/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sk-value/solution/solve.sh b/tasks/sk-value/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f6e7f6c100c8c9dc6cb85b3538cbc82bcc02ec8a --- /dev/null +++ b/tasks/sk-value/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SKValue, i.e. module OAI.Probability.SKValue.Main and the +# 212 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SKValue.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SKValue" diff --git a/tasks/sk-value/task.toml b/tasks/sk-value/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..85f646cc2dc4fb59862e859ecd4483611262d8ba --- /dev/null +++ b/tasks/sk-value/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sk-value" +version = "1.0.0" +description = "Prove SKValue (openai/math family 281: QAOA optimality for the SK model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SKValue.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SKValue" +family = "281" +family_title = "QAOA optimality for the SK model" +subject = "Mathematical physics" +theorems = ["OAI.SKValue.value_consequences"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SKValue.Main" +reference_modules = 212 +reference_lean_bytes = 1487979 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1378 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13039 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sk-value/tests/Challenge.lean b/tasks/sk-value/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a510a0fc583650d790619484068e330a2b4b2b7 --- /dev/null +++ b/tasks/sk-value/tests/Challenge.lean @@ -0,0 +1,175 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter Set +open scoped Topology ENNReal NNReal BigOperators + +namespace SKValue + +noncomputable def standardGaussian : Measure ℝ := gaussianReal 0 1 + +instance : IsProbabilityMeasure standardGaussian := by unfold standardGaussian; infer_instance + +noncomputable def gaussianProduct (ι : Type) [Fintype ι] : Measure (ι → ℝ) := + Measure.pi (fun _ : ι ↦ standardGaussian) +instance gaussianProduct_probability (ι : Type) [Fintype ι] : + IsProbabilityMeasure (gaussianProduct ι) := by + unfold gaussianProduct + infer_instance + +def coordinate (N : ℕ) (j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + z ⟨j % (N+1), Nat.mod_lt _ (Nat.succ_pos _)⟩ + +noncomputable def stepSize (T : ℝ) (N : ℕ) : ℝ := T / N +noncomputable def meshTime (T : ℝ) (N j : ℕ) : ℝ := j * stepSize T N + +noncomputable def euler (T : ℝ) (N : ℕ) (γ : ℝ → ℝ) (u : ℝ → ℝ → ℝ) + (z : Fin (N+1) → ℝ) : ℕ → ℝ + | 0 => 0 + | j+1 => euler T N γ u z j + Real.sqrt (stepSize T N) * coordinate N j z + + stepSize T N * γ (meshTime T N j) * u (meshTime T N j) (euler T N γ u z j) + +structure OrderParameter where + coeff : ℝ → ℝ + nonneg : ∀ t ∈ Ico (0 : ℝ) 1, 0 ≤ coeff t + monotone : MonotoneOn coeff (Ico (0 : ℝ) 1) + rightContinuous : ∀ t ∈ Ico (0 : ℝ) 1, ContinuousWithinAt coeff (Ici t) t + integrable : IntegrableOn coeff (Ioc (0 : ℝ) 1) + +structure BrownianSpace where + Ω : Type + measurableSpace : MeasurableSpace Ω + μ : @Measure Ω measurableSpace + probability : @IsProbabilityMeasure Ω measurableSpace μ + B : ℝ≥0 → Ω → ℝ + measurable : ∀ t, @StronglyMeasurable Ω ℝ _ measurableSpace (B t) + brownian : @IsBrownianReal Ω measurableSpace B μ + +attribute [instance] BrownianSpace.measurableSpace BrownianSpace.probability + +noncomputable def BrownianSpace.filtration (W : BrownianSpace) : + Filtration ℝ≥0 W.measurableSpace := Filtration.natural W.B W.measurable + +noncomputable def shiftedFiltration (W : BrownianSpace) (t : ℝ) : + Filtration ℝ≥0 W.measurableSpace := + Filtration.natural (fun s ω ↦ W.B (Real.toNNReal t + s) ω - W.B (Real.toNNReal t) ω) + (fun _ ↦ (W.measurable _).sub (W.measurable _)) + +def Admissible (W : BrownianSpace) (t : ℝ) (α : ℝ≥0 → W.Ω → ℝ) : Prop := + IsProgressive (shiftedFiltration W t) α ∧ ∀ s ω, |α s ω| ≤ 1 + +noncomputable def controlPayoff (W : BrownianSpace) (γ : OrderParameter) + (t x : ℝ) (α : ℝ≥0 → W.Ω → ℝ) : ℝ := + ∫ ω, (|x + W.B 1 ω - W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..(1-t), γ.coeff (t+s) * α (Real.toNNReal s) ω| - + (1/2 : ℝ) * ∫ s in (0 : ℝ)..(1-t), γ.coeff (t+s) * α (Real.toNNReal s) ω ^ 2) ∂W.μ + +noncomputable def phi (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + sSup {r | ∃ α, Admissible W t α ∧ r = controlPayoff W γ t x α} + +noncomputable def gradient (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (phi W γ t) x + +noncomputable def curvature (W : BrownianSpace) (γ : OrderParameter) (t x : ℝ) : ℝ := + deriv (gradient W γ t) x + +noncomputable def parisi (W : BrownianSpace) (γ : OrderParameter) : ℝ := + phi W γ 0 0 - (1/2 : ℝ) * ∫ t in (0 : ℝ)..1, t * γ.coeff t + +def IsMinimizer (W : BrownianSpace) (γ : OrderParameter) : Prop := + ∀ η : OrderParameter, parisi W γ ≤ parisi W η + +def IsDiffusion (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ) : Prop := + Adapted W.filtration (fun t ω ↦ X (min (t : ℝ) 1) ω) ∧ + (∀ᵐ ω ∂W.μ, ContinuousOn (fun t ↦ X t ω) (Icc (0 : ℝ) 1) ∧ + ∀ t ∈ Icc (0 : ℝ) 1, + X t ω = W.B (Real.toNNReal t) ω + + ∫ s in (0 : ℝ)..t, γ.coeff s * gradient W γ s (X s ω)) + +noncomputable def spin (b : Bool) : ℝ := if b then 1 else -1 + +noncomputable def hamiltonian (n : ℕ) (J : (Fin n × Fin n) → ℝ) + (σ : Fin n → Bool) : ℝ := + (Real.sqrt (n : ℝ))⁻¹ * + ∑ i : Fin n, ∑ j : Fin n, if i < j then J (i,j) * spin (σ i) * spin (σ j) else 0 + +noncomputable def groundStateSequence (n : ℕ) : ℝ := + (n : ℝ)⁻¹ * ∫ J, sSup (range (hamiltonian n J)) ∂gaussianProduct (Fin n × Fin n) + +noncomputable def groundStateValue : ℝ := limUnder atTop groundStateSequence + +noncomputable def gradientStopped (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) (U : W.Ω → ℝ) (t : ℝ≥0) (ω : W.Ω) : ℝ := + if (t : ℝ) < 1 then gradient W γ t (X t ω) else U ω + +def ScalarValueConclusion (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) : Prop := + Tendsto groundStateSequence atTop (𝓝 groundStateValue) ∧ + ∃ U : W.Ω → ℝ, + Martingale (gradientStopped W γ X U) W.filtration W.μ ∧ + (∀ᵐ ω ∂W.μ, |U ω| ≤ 1 ∧ (U ω)^2 = 1 ∧ + Tendsto (fun t ↦ gradient W γ t (X t ω)) (𝓝[<] (1 : ℝ)) (𝓝 (U ω))) ∧ + Tendsto (fun t ↦ ∫ ω, (gradient W γ t (X t ω) - U ω)^2 ∂W.μ) + (𝓝[<] (1 : ℝ)) (𝓝 (0 : ℝ)) ∧ + groundStateValue = (∫ ω, |X 1 ω| ∂W.μ) - ∫ t in (0 : ℝ)..1, t * γ.coeff t ∧ + groundStateValue = ∫ ω, U ω * W.B 1 ω ∂W.μ ∧ + groundStateValue = ∫ t in (0 : ℝ)..1, ∫ ω, curvature W γ t (X t ω) ∂W.μ ∧ + IntervalIntegrable (fun t ↦ ∫ ω, curvature W γ t (X t ω) ∂W.μ) volume 0 1 + +noncomputable def eulerPath (W : BrownianSpace) (γ : OrderParameter) (T : ℝ) (N : ℕ) + (z : Fin (N+1) → ℝ) (j : ℕ) : ℝ := + euler T N γ.coeff (gradient W γ) z j + +noncomputable def rawCoefficient (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + curvature W γ (meshTime T N j) (eulerPath W γ T N z j) + +noncomputable def normalizer (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) : ℝ := + (Real.sqrt (∫ z, (rawCoefficient W γ T N j z)^2 ∂gaussianProduct (Fin (N+1))))⁻¹ + +noncomputable def gaussianIncrement (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + normalizer W γ T N j * rawCoefficient W γ T N j z * coordinate N j z + +noncomputable def roundedSign (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N : ℕ) (z : Fin (N+1) → ℝ) : ℝ := + Real.sign (gradient W γ T (eulerPath W γ T N z N) + + 2 * cdf standardGaussian (coordinate N N z) - 1) + +noncomputable def coefficientA (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N j : ℕ) : ℝ := + if j = 0 then 0 else + ∫ z, roundedSign W γ T N z * gaussianIncrement W γ T N (j-1) z + ∂gaussianProduct (Fin (N+1)) + +noncomputable def coefficientB (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N i : ℕ) : ℝ := + ∫ z, roundedSign W γ T N z * coordinate N (i-1) z ∂gaussianProduct (Fin (N+1)) + +noncomputable def shiftedCoefficientSum (W : BrownianSpace) (γ : OrderParameter) + (T : ℝ) (N : ℕ) : ℝ := + ∑ j ∈ Finset.range (N+1), coefficientA W γ T N j * coefficientB W γ T N (j+1) + +def FiniteGaussianConclusion (W : BrownianSpace) (γ : OrderParameter) + (X : ℝ → W.Ω → ℝ) (T : ℝ) : Prop := + (∀ᶠ N in atTop, ∀ j < N, 0 < normalizer W γ T N j) ∧ + Tendsto (shiftedCoefficientSum W γ T) atTop + (𝓝 (∫ t in (0 : ℝ)..T, ∫ ω, curvature W γ t (X t ω) ∂W.μ)) ∧ + Tendsto (fun S ↦ ∫ t in (0 : ℝ)..S, ∫ ω, curvature W γ t (X t ω) ∂W.μ) + (𝓝[<] (1 : ℝ)) (𝓝 groundStateValue) + +theorem value_consequences : + (∀ (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ), + IsMinimizer W γ → IsDiffusion W γ X → ScalarValueConclusion W γ X) ∧ + (∀ (W : BrownianSpace) (γ : OrderParameter) (X : ℝ → W.Ω → ℝ) (T : ℝ), + 0 < T → T < 1 → IsMinimizer W γ → IsDiffusion W γ X → + FiniteGaussianConclusion W γ X T) ∧ + (∀ (W : BrownianSpace) (γ : OrderParameter), + IsMinimizer W γ → groundStateValue = parisi W γ) := by + sorry + +end SKValue + +end OAI diff --git a/tasks/sk-value/tests/grade.py b/tasks/sk-value/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sk-value/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sk-value/tests/task.json b/tasks/sk-value/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f190eaec6ad977062ad13e2873495c84b5ec32d7 --- /dev/null +++ b/tasks/sk-value/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SKValue", + "comparator": { + "theorem_names": [ + "OAI.SKValue.value_consequences" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12139 +} \ No newline at end of file diff --git a/tasks/sk-value/tests/test.sh b/tasks/sk-value/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sk-value/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/sle-lower-positivity/environment/Dockerfile b/tasks/sle-lower-positivity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/sle-lower-positivity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/sle-lower-positivity/environment/fetch_mathlib.sh b/tasks/sle-lower-positivity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/sle-lower-positivity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/sle-lower-positivity/environment/lake-manifest.json b/tasks/sle-lower-positivity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/sle-lower-positivity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/sle-lower-positivity/environment/lakefile.lean b/tasks/sle-lower-positivity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/sle-lower-positivity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/sle-lower-positivity/environment/lean_setup.sh b/tasks/sle-lower-positivity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/sle-lower-positivity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/sle-lower-positivity/environment/pack_submission.py b/tasks/sle-lower-positivity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/sle-lower-positivity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/sle-lower-positivity/instruction.md b/tasks/sle-lower-positivity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2edaba227fed9508e85f585eb007c10d616d1454 --- /dev/null +++ b/tasks/sle-lower-positivity/instruction.md @@ -0,0 +1,136 @@ +# openai/math challenge `SLELowerPositivity` (family 230) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 230 of the release, *Exact Hausdorff measure for SLE* +(Probability and statistical mechanics). The family as a whole: Resolves Schramm’s Hausdorff-measure question for chordal $\mathrm{SLE}_\kappa$, $0<\kappa<8$. The explicit gauge $r^d(\log\log(1/r))^{(2-d)/2}$, $d=1+\kappa/8$, gives almost surely positive finite measure to every trace segment $\gamma([s,t])$ with $0 G (Real.toNNReal u) z) + (2 / (G t z - (U t : ℂ))) (Ici 0) (t : ℝ)) ∧ + (∀ t, Tendsto (fun z : ℂ => z * (G t z - z)) + (cocompact ℂ ⊓ 𝓟 (survivingDomain γ t)) (𝓝 (2 * (t : ℂ)))) ∧ + (∀ t, Tendsto (fun y : ℝ => F t ((U t : ℂ) + (y : ℂ) * Complex.I)) + (𝓝[>] 0) (𝓝 (γ t))) + +def IsCapacityTwoTrace (U : ℝ≥0 → ℝ) (γ : ℝ≥0 → ℂ) : Prop := + ∃ G F : ℝ≥0 → ℂ → ℂ, IsCapacityTwoWitness U γ G F + +def IsOrdinaryChordalSLE {Ω : Type*} [MeasurableSpace Ω] + (κ : ℝ) (γ : Ω → ℝ≥0 → ℂ) (P : Measure Ω) : Prop := + (∀ t, Measurable (fun ω => γ ω t)) ∧ + ∃ B : ℝ≥0 → Ω → ℝ, ProbabilityTheory.IsBrownianReal B P ∧ + ∀ᵐ ω ∂P, IsCapacityTwoTrace (fun t => Real.sqrt κ * B t ω) (γ ω) + +structure IsGauge (h : ℝ → ℝ) : Prop where + continuousOn : ContinuousOn h (Ici 0) + monotoneOn : MonotoneOn h (Ici 0) + zero : h 0 = 0 + positive : ∀ r, 0 < r → 0 < h r + +noncomputable def hFormula (κ r : ℝ) : ℝ := + r ^ dimension κ * (Real.log (Real.log (1 / r))) ^ (codimension κ / ((2 : ℕ) : ℝ)) + +def HasSmallRadiusFormula (h f : ℝ → ℝ) : Prop := + h =ᶠ[𝓝[>] 0] f + +noncomputable def extendedGauge (h : ℝ → ℝ) (r : ℝ≥0∞) : ℝ≥0∞ := + ENNReal.ofReal (h r.toReal) + +noncomputable def hausdorffGauge (h : ℝ → ℝ) : Measure ℂ := + Measure.mkMetric (extendedGauge h) + +def segment (γ : ℝ≥0 → ℂ) (s t : ℝ≥0) : Set ℂ := γ '' Icc s t + +def SourceLowerMainTarget : Prop := + ∀ (Ω : Type v_lower) (_ : MeasurableSpace Ω) (P : Measure Ω), IsProbabilityMeasure P → + ∀ κ : ℝ, 0 < κ → κ < ((8 : ℕ) : ℝ) → + ∀ (γ : Ω → ℝ≥0 → ℂ), IsOrdinaryChordalSLE κ γ P → + ∀ h : ℝ → ℝ, IsGauge h → HasSmallRadiusFormula h (hFormula κ) → + ∀ᵐ ω ∂P, ∀ s t : ℝ≥0, 0 < s → s < t → + 0 < hausdorffGauge h (segment (γ ω) s t) + +theorem sourceLowerMain_proved : SourceLowerMainTarget := by + sorry + +end SLEExactGauge + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SLELowerPositivity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SLEExactGauge.sourceLowerMain_proved` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/sle-lower-positivity/solution/closure.txt b/tasks/sle-lower-positivity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd90fc64905e2a86fcb14a352533546e20211a4e --- /dev/null +++ b/tasks/sle-lower-positivity/solution/closure.txt @@ -0,0 +1,65 @@ +OAI.Probability.SLE.ActualRetainedKernel +OAI.Probability.SLE.AngularLaws +OAI.Probability.SLE.AngularMoments +OAI.Probability.SLE.AngularPowerDynkin +OAI.Probability.SLE.BoundaryDensity +OAI.Probability.SLE.BrownianGenerators +OAI.Probability.SLE.BrownianStrongMarkov +OAI.Probability.SLE.ChartMeasurability +OAI.Probability.SLE.ClippedCoordinates +OAI.Probability.SLE.DiskHalfPlane +OAI.Probability.SLE.DyadicStrips +OAI.Probability.SLE.ExponentialMartingales +OAI.Probability.SLE.FiniteMass +OAI.Probability.SLE.FiniteRadiusStop +OAI.Probability.SLE.FiniteStoppedLaw +OAI.Probability.SLE.GreenCovariance +OAI.Probability.SLE.HausdorffLimits +OAI.Probability.SLE.IntegralLimits +OAI.Probability.SLE.InteriorDiskProof +OAI.Probability.SLE.InteriorEntrance +OAI.Probability.SLE.IntervalDensity +OAI.Probability.SLE.InverseMoments +OAI.Probability.SLE.ItoIsometry +OAI.Probability.SLE.KernelConsistency +OAI.Probability.SLE.KernelExpectation +OAI.Probability.SLE.LoewnerCharts +OAI.Probability.SLE.LoewnerReflection +OAI.Probability.SLE.LowerPositivity +OAI.Probability.SLE.LowerRestartConditionalAllKappa +OAI.Probability.SLE.MeasureSupport +OAI.Probability.SLE.NearRealContraction +OAI.Probability.SLE.NestedMeans +OAI.Probability.SLE.OccupationBound +OAI.Probability.SLE.OptionalStopping +OAI.Probability.SLE.PhysicalKernelUtilities +OAI.Probability.SLE.PhysicalMeshPast +OAI.Probability.SLE.PhysicalMeshWindowCore +OAI.Probability.SLE.PhysicalTransport +OAI.Probability.SLE.RadiusClocks +OAI.Probability.SLE.RectangleMeans +OAI.Probability.SLE.RetainedDyadicGeometry +OAI.Probability.SLE.RetainedSeedMoments +OAI.Probability.SLE.SausagePointBound +OAI.Probability.SLE.SimpleFields +OAI.Probability.SLE.SimplePastMesh +OAI.Probability.SLE.SimpleTails +OAI.Probability.SLE.SmallKappaSausageMoments +OAI.Probability.SLE.SpatialMeans +OAI.Probability.SLE.StochasticFubini +OAI.Probability.SLE.StochasticIntegrals +OAI.Probability.SLE.StoppedFields +OAI.Probability.SLE.StoppedKernels +OAI.Probability.SLE.StoppedMeasures +OAI.Probability.SLE.StoppedPower +OAI.Probability.SLE.StripKernels +OAI.Probability.SLE.StripProbabilities +OAI.Probability.SLE.SwallowExit +OAI.Probability.SLE.SwallowLyapunov +OAI.Probability.SLE.TracePosCombined +OAI.Probability.SLE.WindowAssembly +OAI.Probability.SLE.WindowBGeometry +OAI.Probability.SLE.WindowBounds +OAI.Probability.SLE.WindowGeometry +OAI.Probability.SLE.WindowPropagation +OAI.Probability.SLE.WindowTails diff --git a/tasks/sle-lower-positivity/solution/reference.py b/tasks/sle-lower-positivity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/sle-lower-positivity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/sle-lower-positivity/solution/solve.sh b/tasks/sle-lower-positivity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..67ee29bdb6afee006921e4437b5cfe467065732e --- /dev/null +++ b/tasks/sle-lower-positivity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SLELowerPositivity, i.e. module OAI.Probability.SLE.LowerPositivity and the +# 65 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SLE.LowerPositivity /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SLELowerPositivity" diff --git a/tasks/sle-lower-positivity/task.toml b/tasks/sle-lower-positivity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..00e6c13d410730b9bfb7bb9f3e1bc602ea190ac2 --- /dev/null +++ b/tasks/sle-lower-positivity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/sle-lower-positivity" +version = "1.0.0" +description = "Prove SLELowerPositivity (openai/math family 230: Exact Hausdorff measure for SLE) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SLELowerPositivity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SLELowerPositivity" +family = "230" +family_title = "Exact Hausdorff measure for SLE" +subject = "Probability and statistical mechanics" +theorems = ["OAI.SLEExactGauge.sourceLowerMain_proved"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SLE.LowerPositivity" +reference_modules = 65 +reference_lean_bytes = 2264389 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1070 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13737 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/sle-lower-positivity/tests/Challenge.lean b/tasks/sle-lower-positivity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..263176269e19986fc030c344da18d511b9a635b2 --- /dev/null +++ b/tasks/sle-lower-positivity/tests/Challenge.lean @@ -0,0 +1,85 @@ +import Mathlib + +namespace OAI + +/-! Positivity of the explicit Hausdorff gauge on all positive-time SLE segments. -/ + +noncomputable section +open Set Filter MeasureTheory +open scoped Topology ENNReal NNReal +namespace SLEExactGauge +universe v_lower + +noncomputable def dimension (κ : ℝ) : ℝ := 1 + κ / 8 + +noncomputable def codimension (κ : ℝ) : ℝ := ((2 : ℕ) : ℝ) - dimension κ + +def upperHalfPlane : Set ℂ := {z | 0 < z.im} + +def survivingDomain (γ : ℝ≥0 → ℂ) (t : ℝ≥0) : Set ℂ := + {z | z ∈ upperHalfPlane \ (γ '' Icc 0 t) ∧ + ¬ Bornology.IsBounded (connectedComponentIn (upperHalfPlane \ (γ '' Icc 0 t)) z)} + +def IsCapacityTwoWitness (U : ℝ≥0 → ℝ) (γ : ℝ≥0 → ℂ) + (G F : ℝ≥0 → ℂ → ℂ) : Prop := + Continuous γ ∧ γ 0 = 0 ∧ (∀ t, 0 ≤ (γ t).im) ∧ + (∀ t, DifferentiableOn ℂ (G t) (survivingDomain γ t)) ∧ + (∀ t, DifferentiableOn ℂ (F t) upperHalfPlane) ∧ + (∀ t, MapsTo (G t) (survivingDomain γ t) upperHalfPlane) ∧ + (∀ t, MapsTo (F t) upperHalfPlane (survivingDomain γ t)) ∧ + (∀ t z, z ∈ survivingDomain γ t → F t (G t z) = z) ∧ + (∀ t z, z ∈ upperHalfPlane → G t (F t z) = z) ∧ + (∀ z ∈ upperHalfPlane, G 0 z = z) ∧ + (∀ t z, z ∈ survivingDomain γ t → + HasDerivWithinAt (fun u : ℝ => G (Real.toNNReal u) z) + (2 / (G t z - (U t : ℂ))) (Ici 0) (t : ℝ)) ∧ + (∀ t, Tendsto (fun z : ℂ => z * (G t z - z)) + (cocompact ℂ ⊓ 𝓟 (survivingDomain γ t)) (𝓝 (2 * (t : ℂ)))) ∧ + (∀ t, Tendsto (fun y : ℝ => F t ((U t : ℂ) + (y : ℂ) * Complex.I)) + (𝓝[>] 0) (𝓝 (γ t))) + +def IsCapacityTwoTrace (U : ℝ≥0 → ℝ) (γ : ℝ≥0 → ℂ) : Prop := + ∃ G F : ℝ≥0 → ℂ → ℂ, IsCapacityTwoWitness U γ G F + +def IsOrdinaryChordalSLE {Ω : Type*} [MeasurableSpace Ω] + (κ : ℝ) (γ : Ω → ℝ≥0 → ℂ) (P : Measure Ω) : Prop := + (∀ t, Measurable (fun ω => γ ω t)) ∧ + ∃ B : ℝ≥0 → Ω → ℝ, ProbabilityTheory.IsBrownianReal B P ∧ + ∀ᵐ ω ∂P, IsCapacityTwoTrace (fun t => Real.sqrt κ * B t ω) (γ ω) + +structure IsGauge (h : ℝ → ℝ) : Prop where + continuousOn : ContinuousOn h (Ici 0) + monotoneOn : MonotoneOn h (Ici 0) + zero : h 0 = 0 + positive : ∀ r, 0 < r → 0 < h r + +noncomputable def hFormula (κ r : ℝ) : ℝ := + r ^ dimension κ * (Real.log (Real.log (1 / r))) ^ (codimension κ / ((2 : ℕ) : ℝ)) + +def HasSmallRadiusFormula (h f : ℝ → ℝ) : Prop := + h =ᶠ[𝓝[>] 0] f + +noncomputable def extendedGauge (h : ℝ → ℝ) (r : ℝ≥0∞) : ℝ≥0∞ := + ENNReal.ofReal (h r.toReal) + +noncomputable def hausdorffGauge (h : ℝ → ℝ) : Measure ℂ := + Measure.mkMetric (extendedGauge h) + +def segment (γ : ℝ≥0 → ℂ) (s t : ℝ≥0) : Set ℂ := γ '' Icc s t + +def SourceLowerMainTarget : Prop := + ∀ (Ω : Type v_lower) (_ : MeasurableSpace Ω) (P : Measure Ω), IsProbabilityMeasure P → + ∀ κ : ℝ, 0 < κ → κ < ((8 : ℕ) : ℝ) → + ∀ (γ : Ω → ℝ≥0 → ℂ), IsOrdinaryChordalSLE κ γ P → + ∀ h : ℝ → ℝ, IsGauge h → HasSmallRadiusFormula h (hFormula κ) → + ∀ᵐ ω ∂P, ∀ s t : ℝ≥0, 0 < s → s < t → + 0 < hausdorffGauge h (segment (γ ω) s t) + +theorem sourceLowerMain_proved : SourceLowerMainTarget := by + sorry + +end SLEExactGauge + +end + +end OAI diff --git a/tasks/sle-lower-positivity/tests/grade.py b/tasks/sle-lower-positivity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/sle-lower-positivity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/sle-lower-positivity/tests/task.json b/tasks/sle-lower-positivity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ae7f6be5201c7cc0582802cdbca63a0088f1a289 --- /dev/null +++ b/tasks/sle-lower-positivity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SLELowerPositivity", + "comparator": { + "theorem_names": [ + "OAI.SLEExactGauge.sourceLowerMain_proved" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12837 +} \ No newline at end of file diff --git a/tasks/sle-lower-positivity/tests/test.sh b/tasks/sle-lower-positivity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/sle-lower-positivity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/smooth-initial-form/environment/Dockerfile b/tasks/smooth-initial-form/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/smooth-initial-form/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/smooth-initial-form/environment/fetch_mathlib.sh b/tasks/smooth-initial-form/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/smooth-initial-form/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/smooth-initial-form/environment/lake-manifest.json b/tasks/smooth-initial-form/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/smooth-initial-form/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/smooth-initial-form/environment/lakefile.lean b/tasks/smooth-initial-form/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/smooth-initial-form/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/smooth-initial-form/environment/lean_setup.sh b/tasks/smooth-initial-form/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/smooth-initial-form/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/smooth-initial-form/environment/pack_submission.py b/tasks/smooth-initial-form/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/smooth-initial-form/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/smooth-initial-form/instruction.md b/tasks/smooth-initial-form/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..9ace7b1e604a22cb050573aff6b7e23ad2564fe3 --- /dev/null +++ b/tasks/smooth-initial-form/instruction.md @@ -0,0 +1,107 @@ +# openai/math challenge `SmoothInitialForm` (family 108) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 108 of the release, *A cubic permanent–determinant lower bound* +(Theoretical computer science). The family as a whole: Proves an $\Omega(n^3)$ lower bound for the border determinantal complexity of the $n\times n$ permanent over $\mathbb C$. Even coefficientwise limits of determinants of affine-linear matrices require matrix size at least $cn^3$, for an absolute $c>0$ and all sufficiently large $n$; the same bound therefore holds for exact representations. + +The challenge is `SmoothInitialForm`, also at `/opt/openai-math/challenges/SmoothInitialForm.lean`: + +```lean +import Mathlib + +namespace OAI + +open MvPolynomial +namespace PermanentBorder + +open Filter +open scoped Topology + +abbrev Poly (σ : Type*) := MvPolynomial σ ℂ + +noncomputable def affineMatrixPolynomial {σ : Type*} [Fintype σ] (n : ℕ) + (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ) : Poly σ := + Matrix.det (fun i j => MvPolynomial.C (A₀ i j) + + ∑ v : σ, MvPolynomial.C (A v i j) * MvPolynomial.X v) + +def HasBorderDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : ℕ → Matrix (Fin n) (Fin n) ℂ) + (A : ℕ → σ → Matrix (Fin n) (Fin n) ℂ), + ∀ d : σ →₀ ℕ, Tendsto + (fun j => (affineMatrixPolynomial n (A₀ j) (A j)).coeff d) + atTop (𝓝 (p.coeff d)) + +def HasExactDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ), affineMatrixPolynomial n A₀ A = p + +noncomputable def affineSubstitution {σ τ : Type*} [Fintype τ] + (b : σ → ℂ) (B : σ → τ → ℂ) : Poly σ →ₐ[ℂ] Poly τ := + MvPolynomial.aeval (fun v => MvPolynomial.C (b v) + + ∑ w : τ, MvPolynomial.C (B v w) * MvPolynomial.X w) + +theorem smooth_initial_form_lower_bound (d r : ℕ) (g : Poly (Fin d)) + (a : Fin d → ℂ) (hd : 2 ≤ d) (hr : 2 ≤ r) + (hG : homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g) ≠ 0) + (hlow : ∀ j < r, homogeneousComponent j + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g) = 0) + (hs : ∀ y : Fin d → ℂ, + eval y (homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g)) = 0 → + (∀ i, eval y (pderiv i (homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g))) = 0) → + y = 0) : + ∀ n : ℕ, + (HasBorderDeterminant n g → + ((r - 1 : ℕ) : ℝ) * ((d - 1 : ℕ) : ℝ) / (4 * Real.exp 1) ≤ (n : ℝ)) ∧ + (HasExactDeterminant n g → + ((r - 1 : ℕ) : ℝ) * ((d - 1 : ℕ) : ℝ) / (4 * Real.exp 1) ≤ (n : ℝ)) := by + sorry + +end PermanentBorder + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SmoothInitialForm.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PermanentBorder.smooth_initial_form_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/smooth-initial-form/solution/closure.txt b/tasks/smooth-initial-form/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a1e97f90d57d0359f7c62f66c87fc2f960a4104e --- /dev/null +++ b/tasks/smooth-initial-form/solution/closure.txt @@ -0,0 +1,17 @@ +OAI.Algebra.Determinantal.BilinearCounts +OAI.Algebra.Determinantal.BorderClosure +OAI.Algebra.Determinantal.BorderPolars +OAI.Algebra.Determinantal.GenericPolars +OAI.Algebra.Determinantal.InitialForm +OAI.Algebra.Determinantal.KernelCharts +OAI.Algebra.Determinantal.LinearForms +OAI.Algebra.Determinantal.Model +OAI.Algebra.Determinantal.Multigraded +OAI.Algebra.Determinantal.PointBounds +OAI.Algebra.Determinantal.ProjectiveCounts +OAI.Algebra.Determinantal.RankTransfer +OAI.Algebra.Determinantal.RegularSections +OAI.Algebra.Determinantal.SchurDifferentials +OAI.Algebra.Determinantal.SchurLifts +OAI.Algebra.Determinantal.SliceCertificates +OAI.Algebra.Determinantal.SmoothSlices diff --git a/tasks/smooth-initial-form/solution/reference.py b/tasks/smooth-initial-form/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/smooth-initial-form/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/smooth-initial-form/solution/solve.sh b/tasks/smooth-initial-form/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a78d63990df5724dfc2afc8fefe3227f3d1e6d94 --- /dev/null +++ b/tasks/smooth-initial-form/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SmoothInitialForm, i.e. module OAI.Algebra.Determinantal.InitialForm and the +# 17 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.Determinantal.InitialForm /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SmoothInitialForm" diff --git a/tasks/smooth-initial-form/task.toml b/tasks/smooth-initial-form/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ca6169af8de82229b6817baac65b812889df1007 --- /dev/null +++ b/tasks/smooth-initial-form/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/smooth-initial-form" +version = "1.0.0" +description = "Prove SmoothInitialForm (openai/math family 108: A cubic permanent–determinant lower bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SmoothInitialForm.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SmoothInitialForm" +family = "108" +family_title = "A cubic permanent–determinant lower bound" +subject = "Theoretical computer science" +theorems = ["OAI.PermanentBorder.smooth_initial_form_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.Determinantal.InitialForm" +reference_modules = 17 +reference_lean_bytes = 290725 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 852 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11961 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/smooth-initial-form/tests/Challenge.lean b/tasks/smooth-initial-form/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..63b54a0eebcfc908a4f143eb1a8dcfbf54acff18 --- /dev/null +++ b/tasks/smooth-initial-form/tests/Challenge.lean @@ -0,0 +1,56 @@ +import Mathlib + +namespace OAI + +open MvPolynomial +namespace PermanentBorder + +open Filter +open scoped Topology + +abbrev Poly (σ : Type*) := MvPolynomial σ ℂ + +noncomputable def affineMatrixPolynomial {σ : Type*} [Fintype σ] (n : ℕ) + (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ) : Poly σ := + Matrix.det (fun i j => MvPolynomial.C (A₀ i j) + + ∑ v : σ, MvPolynomial.C (A v i j) * MvPolynomial.X v) + +def HasBorderDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : ℕ → Matrix (Fin n) (Fin n) ℂ) + (A : ℕ → σ → Matrix (Fin n) (Fin n) ℂ), + ∀ d : σ →₀ ℕ, Tendsto + (fun j => (affineMatrixPolynomial n (A₀ j) (A j)).coeff d) + atTop (𝓝 (p.coeff d)) + +def HasExactDeterminant {σ : Type*} [Fintype σ] (n : ℕ) (p : Poly σ) : Prop := + 0 < n ∧ ∃ (A₀ : Matrix (Fin n) (Fin n) ℂ) + (A : σ → Matrix (Fin n) (Fin n) ℂ), affineMatrixPolynomial n A₀ A = p + +noncomputable def affineSubstitution {σ τ : Type*} [Fintype τ] + (b : σ → ℂ) (B : σ → τ → ℂ) : Poly σ →ₐ[ℂ] Poly τ := + MvPolynomial.aeval (fun v => MvPolynomial.C (b v) + + ∑ w : τ, MvPolynomial.C (B v w) * MvPolynomial.X w) + +theorem smooth_initial_form_lower_bound (d r : ℕ) (g : Poly (Fin d)) + (a : Fin d → ℂ) (hd : 2 ≤ d) (hr : 2 ≤ r) + (hG : homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g) ≠ 0) + (hlow : ∀ j < r, homogeneousComponent j + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g) = 0) + (hs : ∀ y : Fin d → ℂ, + eval y (homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g)) = 0 → + (∀ i, eval y (pderiv i (homogeneousComponent r + (affineSubstitution a (fun i j : Fin d => if i = j then 1 else 0) g))) = 0) → + y = 0) : + ∀ n : ℕ, + (HasBorderDeterminant n g → + ((r - 1 : ℕ) : ℝ) * ((d - 1 : ℕ) : ℝ) / (4 * Real.exp 1) ≤ (n : ℝ)) ∧ + (HasExactDeterminant n g → + ((r - 1 : ℕ) : ℝ) * ((d - 1 : ℕ) : ℝ) / (4 * Real.exp 1) ≤ (n : ℝ)) := by + sorry + +end PermanentBorder + +end OAI diff --git a/tasks/smooth-initial-form/tests/grade.py b/tasks/smooth-initial-form/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/smooth-initial-form/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/smooth-initial-form/tests/task.json b/tasks/smooth-initial-form/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6778779a835cd5da6b7c38002cf3776c8dddd1c3 --- /dev/null +++ b/tasks/smooth-initial-form/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SmoothInitialForm", + "comparator": { + "theorem_names": [ + "OAI.PermanentBorder.smooth_initial_form_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11061 +} \ No newline at end of file diff --git a/tasks/smooth-initial-form/tests/test.sh b/tasks/smooth-initial-form/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/smooth-initial-form/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/smooth-obstruction/environment/Dockerfile b/tasks/smooth-obstruction/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/smooth-obstruction/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/smooth-obstruction/environment/fetch_mathlib.sh b/tasks/smooth-obstruction/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/smooth-obstruction/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/smooth-obstruction/environment/lake-manifest.json b/tasks/smooth-obstruction/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/smooth-obstruction/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/smooth-obstruction/environment/lakefile.lean b/tasks/smooth-obstruction/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/smooth-obstruction/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/smooth-obstruction/environment/lean_setup.sh b/tasks/smooth-obstruction/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/smooth-obstruction/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/smooth-obstruction/environment/pack_submission.py b/tasks/smooth-obstruction/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/smooth-obstruction/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/smooth-obstruction/instruction.md b/tasks/smooth-obstruction/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a6b14fcf7ed79c108ab6c7ef9cee4c06b5bf839c --- /dev/null +++ b/tasks/smooth-obstruction/instruction.md @@ -0,0 +1,150 @@ +# openai/math challenge `SmoothObstruction` (family 152) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 152 of the release, *Zero entropy does not guarantee a smooth positive-volume model* +(Dynamical systems and ergodic theory). The family as a whole: Constructs a zero-entropy ergodic invertible transformation of a standard nonatomic probability space that is not measurably conjugate to any $C^\infty$ diffeomorphism preserving a strictly positive smooth probability density on a compact finite-dimensional manifold. One example rules out every finite dimension. + +The challenge is `SmoothObstruction`, also at `/opt/openai-math/challenges/SmoothObstruction.lean`: + +```lean +import Mathlib + +namespace OAI + + +open MeasureTheory Set Filter +open scoped ENNReal Topology Manifold ContDiff + +namespace SmoothObstruction + +/-- Shannon entropy in bits; the value at mass zero is zero. -/ +noncomputable def entropyTerm (p : ℝ) : ℝ := -(p * Real.log p) / Real.log 2 + +/-- The entropy of the length-`n` join of the partition with labels in `Fin q`. -/ +noncomputable def blockEntropy {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) {q : ℕ} (P : X → Fin q) (n : ℕ) : ℝ := + ∑ w : Fin n → Fin q, + entropyTerm ((μ {x | ∀ j : Fin n, P ((T^[j.val]) x) = w j}).toReal) + +/-- All finite-partition entropy rates exist and have one finite real upper +bound. This spells out `sup_P lim_n H(join_{j blockEntropy μ T P n / (n : ℝ)) atTop (𝓝 h) + +/-- Measure-space isomorphism after removing measurable null sets. -/ +def ConullIsomorphic {X Y : Type*} [MeasurableSpace X] [MeasurableSpace Y] + (μ : Measure X) (ν : Measure Y) : Prop := + ∃ (A : Set X) (B : Set Y), MeasurableSet A ∧ MeasurableSet B ∧ + μ Aᶜ = 0 ∧ ν Bᶜ = 0 ∧ + ∃ e : A ≃ᵐ B, + MeasurePreserving e (μ.comap (Subtype.val : A → X)) + (ν.comap (Subtype.val : B → Y)) + +/-- Standard nonatomic in the source's explicit modulo-null-set sense. -/ +def StandardNonatomic {X : Type*} [MeasurableSpace X] (μ : Measure X) : Prop := + ConullIsomorphic μ + (volume.comap (Subtype.val : Set.Icc (0 : ℝ) 1 → ℝ)) + +/-- Measurable conjugacy on invariant conull measurable subsets, not a +continuous conjugacy and not merely a factor map. -/ +def ConullConjugate {X Y : Type*} [MeasurableSpace X] [MeasurableSpace Y] + (μ : Measure X) (T : X → X) (ν : Measure Y) (S : Y → Y) : Prop := + ∃ (A : Set X) (B : Set Y), MeasurableSet A ∧ MeasurableSet B ∧ + μ Aᶜ = 0 ∧ ν Bᶜ = 0 ∧ T ⁻¹' A = A ∧ S ⁻¹' B = B ∧ + ∃ e : A ≃ᵐ B, + MeasurePreserving e (μ.comap (Subtype.val : A → X)) + (ν.comap (Subtype.val : B → Y)) ∧ + ∀ (x y : A), T x = y → (e y : Y) = S (e x) + +/-- Positive smooth local coordinate densities. In a half-space chart, +`ContDiffOn` includes smoothness up to the boundary. Absolute Lebesgue density +is used; no orientation or volume form is part of the data. -/ +def SmoothPositiveDensity {d : ℕ} {H : Type*} [TopologicalSpace H] + (I : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin d)) H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [MeasurableSpace M] + (ν : Measure M) : Prop := + ∀ x : M, ∃ f : EuclideanSpace ℝ (Fin d) → ℝ, + ContDiffOn ℝ ∞ f (extChartAt I x).target ∧ + (∀ y ∈ (extChartAt I x).target, 0 < f y) ∧ + Measure.map (extChartAt I x) (ν.restrict (extChartAt I x).source) = + (volume.withDensity (fun y => ENNReal.ofReal (f y))).restrict + (extChartAt I x).target + +/-- A smooth positive-volume model with a specified Euclidean or half-space +manifold model. All model dimensions will be quantified below. -/ +def HasModelWith {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) {d : ℕ} {H : Type} [TopologicalSpace H] + (I : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin d)) H) : Prop := + ∃ (M : Type) (_ : TopologicalSpace M) (_ : MeasurableSpace M) + (_ : BorelSpace M) (_ : T2Space M) (_ : SecondCountableTopology M) + (_ : CompactSpace M) (_ : ChartedSpace H M) (_ : IsManifold I ∞ M) + (ν : Measure M) (_ : IsProbabilityMeasure ν) + (S : Diffeomorph I I M M ∞), + SmoothPositiveDensity I ν ∧ MeasurePreserving S ν ν ∧ + ConullConjugate μ T ν S + +/-- Closed manifolds of all dimensions (including zero), and smooth manifolds +with boundary of every positive finite dimension. Nonorientable manifolds +are included: no orientability hypothesis occurs. -/ +def HasSmoothPositiveVolumeModel {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) : Prop := + (∃ d : ℕ, HasModelWith μ T (𝓡 d)) ∨ + (∃ d : ℕ, ∃ _ : NeZero d, HasModelWith μ T (𝓡∂ d)) + +/-- A finite-entropy standard nonatomic ergodic system with no smooth positive-volume model. -/ +theorem main : + ∃ (X : Type) (_ : MeasurableSpace X) (μ : Measure X) + (_ : IsProbabilityMeasure μ) (T : X ≃ᵐ X), + StandardNonatomic μ ∧ Ergodic T μ ∧ FiniteKSEntropy μ T ∧ + ¬ HasSmoothPositiveVolumeModel μ T := by + sorry + +end SmoothObstruction + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SmoothObstruction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SmoothObstruction.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/smooth-obstruction/solution/closure.txt b/tasks/smooth-obstruction/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2ce7d2c9456402bbbabeb8b5aed8fb7801783d2 --- /dev/null +++ b/tasks/smooth-obstruction/solution/closure.txt @@ -0,0 +1,53 @@ +OAI.Dynamics.SmoothObstruction.AsymptoticSplitting +OAI.Dynamics.SmoothObstruction.BoundaryDensity +OAI.Dynamics.SmoothObstruction.BoundaryMatching +OAI.Dynamics.SmoothObstruction.Charts +OAI.Dynamics.SmoothObstruction.CoordinateTubes +OAI.Dynamics.SmoothObstruction.Coordinates +OAI.Dynamics.SmoothObstruction.Counting +OAI.Dynamics.SmoothObstruction.DensityBounds +OAI.Dynamics.SmoothObstruction.DensityLocalization +OAI.Dynamics.SmoothObstruction.DyadicChord +OAI.Dynamics.SmoothObstruction.EndpointFrames +OAI.Dynamics.SmoothObstruction.EndpointMass +OAI.Dynamics.SmoothObstruction.ExteriorPowers +OAI.Dynamics.SmoothObstruction.FiniteEntropy +OAI.Dynamics.SmoothObstruction.FiniteLaw +OAI.Dynamics.SmoothObstruction.GlobalSwitching +OAI.Dynamics.SmoothObstruction.GreenOperator +OAI.Dynamics.SmoothObstruction.GridCells +OAI.Dynamics.SmoothObstruction.InvariantMeasure +OAI.Dynamics.SmoothObstruction.Main +OAI.Dynamics.SmoothObstruction.ManifoldMatching +OAI.Dynamics.SmoothObstruction.MinorTransfer +OAI.Dynamics.SmoothObstruction.Models +OAI.Dynamics.SmoothObstruction.NonlinearMatching +OAI.Dynamics.SmoothObstruction.Obstruction +OAI.Dynamics.SmoothObstruction.OrthogonalCocycle +OAI.Dynamics.SmoothObstruction.PairBounds +OAI.Dynamics.SmoothObstruction.PairLaw +OAI.Dynamics.SmoothObstruction.PartitionEntropy +OAI.Dynamics.SmoothObstruction.PhaseDynamics +OAI.Dynamics.SmoothObstruction.PhaseEntropy +OAI.Dynamics.SmoothObstruction.ProductCoordinates +OAI.Dynamics.SmoothObstruction.Recognition +OAI.Dynamics.SmoothObstruction.Sampling +OAI.Dynamics.SmoothObstruction.Selection +OAI.Dynamics.SmoothObstruction.ShearGauge +OAI.Dynamics.SmoothObstruction.ShortDerivative +OAI.Dynamics.SmoothObstruction.ShortScales +OAI.Dynamics.SmoothObstruction.SmoothScales +OAI.Dynamics.SmoothObstruction.SpectralBins +OAI.Dynamics.SmoothObstruction.Splitting +OAI.Dynamics.SmoothObstruction.SplittingStability +OAI.Dynamics.SmoothObstruction.StandardProbability +OAI.Dynamics.SmoothObstruction.StationaryGauge +OAI.Dynamics.SmoothObstruction.SwitchRecovery +OAI.Dynamics.SmoothObstruction.SwitchScales +OAI.Dynamics.SmoothObstruction.SymbolCores +OAI.Dynamics.SmoothObstruction.TubeProjection +OAI.Dynamics.SmoothObstruction.WordEntropy +OAI.Dynamics.SmoothObstruction.WordHierarchy +OAI.Dynamics.SmoothObstruction.WordLaw +OAI.Dynamics.SmoothObstruction.WordParameters +OAI.Dynamics.SmoothObstruction.WordStep diff --git a/tasks/smooth-obstruction/solution/reference.py b/tasks/smooth-obstruction/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/smooth-obstruction/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/smooth-obstruction/solution/solve.sh b/tasks/smooth-obstruction/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2fad7990db4aef6271507ac703270d3f335b3fa6 --- /dev/null +++ b/tasks/smooth-obstruction/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SmoothObstruction, i.e. module OAI.Dynamics.SmoothObstruction.Main and the +# 53 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.SmoothObstruction.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SmoothObstruction" diff --git a/tasks/smooth-obstruction/task.toml b/tasks/smooth-obstruction/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f07c8f6c065827aa1f26a61b610ed6e51ae06e1e --- /dev/null +++ b/tasks/smooth-obstruction/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/smooth-obstruction" +version = "1.0.0" +description = "Prove SmoothObstruction (openai/math family 152: Zero entropy does not guarantee a smooth positive-volume model) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SmoothObstruction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SmoothObstruction" +family = "152" +family_title = "Zero entropy does not guarantee a smooth positive-volume model" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.SmoothObstruction.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.SmoothObstruction.Main" +reference_modules = 53 +reference_lean_bytes = 1540084 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1158 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13086 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/smooth-obstruction/tests/Challenge.lean b/tasks/smooth-obstruction/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f666502eeb7056809e186a347733f960de0bfa9c --- /dev/null +++ b/tasks/smooth-obstruction/tests/Challenge.lean @@ -0,0 +1,99 @@ +import Mathlib + +namespace OAI + + +open MeasureTheory Set Filter +open scoped ENNReal Topology Manifold ContDiff + +namespace SmoothObstruction + +/-- Shannon entropy in bits; the value at mass zero is zero. -/ +noncomputable def entropyTerm (p : ℝ) : ℝ := -(p * Real.log p) / Real.log 2 + +/-- The entropy of the length-`n` join of the partition with labels in `Fin q`. -/ +noncomputable def blockEntropy {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) {q : ℕ} (P : X → Fin q) (n : ℕ) : ℝ := + ∑ w : Fin n → Fin q, + entropyTerm ((μ {x | ∀ j : Fin n, P ((T^[j.val]) x) = w j}).toReal) + +/-- All finite-partition entropy rates exist and have one finite real upper +bound. This spells out `sup_P lim_n H(join_{j blockEntropy μ T P n / (n : ℝ)) atTop (𝓝 h) + +/-- Measure-space isomorphism after removing measurable null sets. -/ +def ConullIsomorphic {X Y : Type*} [MeasurableSpace X] [MeasurableSpace Y] + (μ : Measure X) (ν : Measure Y) : Prop := + ∃ (A : Set X) (B : Set Y), MeasurableSet A ∧ MeasurableSet B ∧ + μ Aᶜ = 0 ∧ ν Bᶜ = 0 ∧ + ∃ e : A ≃ᵐ B, + MeasurePreserving e (μ.comap (Subtype.val : A → X)) + (ν.comap (Subtype.val : B → Y)) + +/-- Standard nonatomic in the source's explicit modulo-null-set sense. -/ +def StandardNonatomic {X : Type*} [MeasurableSpace X] (μ : Measure X) : Prop := + ConullIsomorphic μ + (volume.comap (Subtype.val : Set.Icc (0 : ℝ) 1 → ℝ)) + +/-- Measurable conjugacy on invariant conull measurable subsets, not a +continuous conjugacy and not merely a factor map. -/ +def ConullConjugate {X Y : Type*} [MeasurableSpace X] [MeasurableSpace Y] + (μ : Measure X) (T : X → X) (ν : Measure Y) (S : Y → Y) : Prop := + ∃ (A : Set X) (B : Set Y), MeasurableSet A ∧ MeasurableSet B ∧ + μ Aᶜ = 0 ∧ ν Bᶜ = 0 ∧ T ⁻¹' A = A ∧ S ⁻¹' B = B ∧ + ∃ e : A ≃ᵐ B, + MeasurePreserving e (μ.comap (Subtype.val : A → X)) + (ν.comap (Subtype.val : B → Y)) ∧ + ∀ (x y : A), T x = y → (e y : Y) = S (e x) + +/-- Positive smooth local coordinate densities. In a half-space chart, +`ContDiffOn` includes smoothness up to the boundary. Absolute Lebesgue density +is used; no orientation or volume form is part of the data. -/ +def SmoothPositiveDensity {d : ℕ} {H : Type*} [TopologicalSpace H] + (I : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin d)) H) + {M : Type*} [TopologicalSpace M] [ChartedSpace H M] [MeasurableSpace M] + (ν : Measure M) : Prop := + ∀ x : M, ∃ f : EuclideanSpace ℝ (Fin d) → ℝ, + ContDiffOn ℝ ∞ f (extChartAt I x).target ∧ + (∀ y ∈ (extChartAt I x).target, 0 < f y) ∧ + Measure.map (extChartAt I x) (ν.restrict (extChartAt I x).source) = + (volume.withDensity (fun y => ENNReal.ofReal (f y))).restrict + (extChartAt I x).target + +/-- A smooth positive-volume model with a specified Euclidean or half-space +manifold model. All model dimensions will be quantified below. -/ +def HasModelWith {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) {d : ℕ} {H : Type} [TopologicalSpace H] + (I : ModelWithCorners ℝ (EuclideanSpace ℝ (Fin d)) H) : Prop := + ∃ (M : Type) (_ : TopologicalSpace M) (_ : MeasurableSpace M) + (_ : BorelSpace M) (_ : T2Space M) (_ : SecondCountableTopology M) + (_ : CompactSpace M) (_ : ChartedSpace H M) (_ : IsManifold I ∞ M) + (ν : Measure M) (_ : IsProbabilityMeasure ν) + (S : Diffeomorph I I M M ∞), + SmoothPositiveDensity I ν ∧ MeasurePreserving S ν ν ∧ + ConullConjugate μ T ν S + +/-- Closed manifolds of all dimensions (including zero), and smooth manifolds +with boundary of every positive finite dimension. Nonorientable manifolds +are included: no orientability hypothesis occurs. -/ +def HasSmoothPositiveVolumeModel {X : Type*} [MeasurableSpace X] + (μ : Measure X) (T : X → X) : Prop := + (∃ d : ℕ, HasModelWith μ T (𝓡 d)) ∨ + (∃ d : ℕ, ∃ _ : NeZero d, HasModelWith μ T (𝓡∂ d)) + +/-- A finite-entropy standard nonatomic ergodic system with no smooth positive-volume model. -/ +theorem main : + ∃ (X : Type) (_ : MeasurableSpace X) (μ : Measure X) + (_ : IsProbabilityMeasure μ) (T : X ≃ᵐ X), + StandardNonatomic μ ∧ Ergodic T μ ∧ FiniteKSEntropy μ T ∧ + ¬ HasSmoothPositiveVolumeModel μ T := by + sorry + +end SmoothObstruction + +end OAI diff --git a/tasks/smooth-obstruction/tests/grade.py b/tasks/smooth-obstruction/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/smooth-obstruction/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/smooth-obstruction/tests/task.json b/tasks/smooth-obstruction/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..bbca377c0dc81d3eefcad1ad97bbe0a7c55c1379 --- /dev/null +++ b/tasks/smooth-obstruction/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SmoothObstruction", + "comparator": { + "theorem_names": [ + "OAI.SmoothObstruction.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12186 +} \ No newline at end of file diff --git a/tasks/smooth-obstruction/tests/test.sh b/tasks/smooth-obstruction/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/smooth-obstruction/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/soft-channel204/environment/Dockerfile b/tasks/soft-channel204/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/soft-channel204/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/soft-channel204/environment/fetch_mathlib.sh b/tasks/soft-channel204/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/soft-channel204/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/soft-channel204/environment/lake-manifest.json b/tasks/soft-channel204/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/soft-channel204/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/soft-channel204/environment/lakefile.lean b/tasks/soft-channel204/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/soft-channel204/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/soft-channel204/environment/lean_setup.sh b/tasks/soft-channel204/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/soft-channel204/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/soft-channel204/environment/pack_submission.py b/tasks/soft-channel204/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/soft-channel204/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/soft-channel204/instruction.md b/tasks/soft-channel204/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..96a061b6d054e9560c33cb723a77fae9b9dfedb1 --- /dev/null +++ b/tasks/soft-channel204/instruction.md @@ -0,0 +1,172 @@ +# openai/math challenge `SoftChannel204` (family 119) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 119 of the release, *The Courtade–Kumar and Hellinger conjectures* +(Theoretical computer science). The family as a whole: Proves the Courtade–Kumar conjecture: among Boolean functions of independent uniform bits, a single coordinate retains the most mutual information after independent bit-flip noise. A stronger theorem treats randomized binary summaries at fixed initial information. The Hellinger conjecture is also proved for every Boolean output bias and noise correlation. + +The challenge is `SoftChannel204`, also at `/opt/openai-math/challenges/SoftChannel204.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace SoftChannel204 + +abbrev Cube (n : ℕ) := Fin n → Bool + +def sign (b : Bool) : ℝ := if b then 1 else -1 + +def avg {n : ℕ} (g : Cube n → ℝ) : ℝ := (∑ x, g x) / (2 : ℝ) ^ n + +def L : ℝ := Real.log 2 + +def psi (r : ℝ) : ℝ := + (1 + r) / 2 * Real.log (1 + r) + (1 - r) / 2 * Real.log (1 - r) + +def H (r : ℝ) : ℝ := L - psi r + +def info {n : ℕ} (u : Cube n → ℝ) : ℝ := H (avg u) - avg (H ∘ u) + +def psiInv (s : ℝ) : ℝ := Function.invFunOn psi (Set.Icc 0 1) s + +def kernel {n : ℕ} (ρ : ℝ) (x y : Cube n) : ℝ := + ∏ i, if x i = y i then (1 + ρ) / 2 else (1 - ρ) / 2 + +def noise {n : ℕ} (ρ : ℝ) (u : Cube n → ℝ) (y : Cube n) : ℝ := + ∑ x, kernel ρ y x * u x + +def Closed {n : ℕ} (u : Cube n → ℝ) : Prop := ∀ x, u x ∈ Set.Icc (-1) 1 + +def Interior {n : ℕ} (g : Cube n → ℝ) : Prop := ∀ x, g x ∈ Set.Ioo (-1) 1 + +def softCoordinate {n : ℕ} (i : Fin n) (a : ℝ) (x : Cube n) : ℝ := a * sign (x i) + +def flip {n : ℕ} (i : Fin n) (x : Cube n) : Cube n := Function.update x i (!(x i)) + +def numberOperator {n : ℕ} (g : Cube n → ℝ) (x : Cube n) : ℝ := + (1 / 2 : ℝ) * ∑ i, (g x - g (flip i x)) + +def production {n : ℕ} (g : Cube n → ℝ) : ℝ := + avg (fun x => Real.artanh (g x) * numberOperator g x) + +/-- Defined by this formula on `[0, L)`; no finite endpoint value at `L` is asserted. -/ +def F (s : ℝ) : ℝ := psiInv s * Real.artanh (psiInv s) + +/-- The excess `F s - 2 * s`, used for `s < L`, is extended by zero to negative arguments. -/ +def S (s : ℝ) : ℝ := if s < 0 then 0 else F s - 2 * s + +/-- The reserve is used for `|m| < 1` and `0 ≤ I < H m`. -/ +def reserve (m I : ℝ) : ℝ := + 2 * I + (1 - m ^ 2) * S (L - (H m - I) / (1 - m ^ 2)) + +def hybrid (m I : ℝ) : ℝ := max (reserve m I) (F I) + +def softJoint {n : ℕ} (ρ : ℝ) (u : Cube n → ℝ) (b : Bool) (y : Cube n) : ℝ := + avg (fun x => (1 + sign b * u x) / 2 * kernel ρ x y) + +def boolJoint {n : ℕ} (ρ : ℝ) (f : Cube n → Bool) (b : Bool) (y : Cube n) : ℝ := + avg (fun x => if f x = b then kernel ρ x y else 0) + +def leftMarginal {n : ℕ} (p : Bool → Cube n → ℝ) (b : Bool) : ℝ := ∑ y, p b y + +def rightMarginal {n : ℕ} (p : Bool → Cube n → ℝ) (y : Cube n) : ℝ := ∑ b, p b y + +def mutualInformation {n : ℕ} (p : Bool → Cube n → ℝ) : ℝ := + ∑ b, ∑ y, if 0 < p b y then + p b y * Real.log (p b y / (leftMarginal p b * rightMarginal p y)) else 0 + +def binaryEntropyBits (ε : ℝ) : ℝ := + -(ε * Real.log ε + (1 - ε) * Real.log (1 - ε)) / L + +def SoftContraction : Prop := ∀ (n : ℕ) (u : Cube n → ℝ), Closed u → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + info (noise ρ u) ≤ psi (|ρ| * psiInv (info u)) + +def SoftAttainment : Prop := ∀ (n : ℕ) (i : Fin n) (a : ℝ), |a| ≤ 1 → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + info (noise ρ (softCoordinate i a)) = + psi (|ρ| * psiInv (info (softCoordinate i a))) + +def SoftInformationIdentity : Prop := ∀ (n : ℕ) (u : Cube n → ℝ), Closed u → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + mutualInformation (softJoint ρ u) = info (noise ρ u) + +def RefinedBoolean : Prop := ∀ (n : ℕ) (f : Cube n → Bool) + (ρ : ℝ), ρ ∈ Set.Icc (-1 : ℝ) 1 → + let m := avg (sign ∘ f) + let bound := psi (|ρ| * psiInv (H m)) + mutualInformation (boolJoint ρ f) = info (noise ρ (sign ∘ f)) ∧ + mutualInformation (boolJoint ρ f) ≤ bound ∧ bound ≤ psi |ρ| ∧ + (0 < |m| → |m| < 1 → 0 < |ρ| → bound < psi |ρ|) + +def BooleanAttainment : Prop := ∀ (n : ℕ) (i : Fin n) + (ρ : ℝ), ρ ∈ Set.Icc (-1 : ℝ) 1 → + mutualInformation (boolJoint ρ (fun x => x i)) = psi |ρ| ∧ + mutualInformation (boolJoint ρ (fun x => !(x i))) = psi |ρ| + +def BitsConversion : Prop := ∀ (n : ℕ) (f : Cube n → Bool) + (ε : ℝ), ε ∈ Set.Icc (0 : ℝ) (1/2) → + psi (1 - 2 * ε) / L = 1 - binaryEntropyBits ε ∧ + mutualInformation (boolJoint (1 - 2 * ε) f) / L ≤ 1 - binaryEntropyBits ε + +def SharpProduction : Prop := ∀ (n : ℕ) (g : Cube n → ℝ), Interior g → + hybrid (avg g) (info g) ≤ production g ∧ F (info g) ≤ hybrid (avg g) (info g) + +def FullMain : Prop := SoftContraction ∧ SoftAttainment ∧ SoftInformationIdentity ∧ + RefinedBoolean ∧ BooleanAttainment ∧ BitsConversion ∧ SharpProduction + +theorem fullMain : FullMain := by + sorry + +end SoftChannel204 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SoftChannel204.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SoftChannel204.fullMain` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/soft-channel204/solution/closure.txt b/tasks/soft-channel204/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..305bad1c7b711912f70df9c9197a8085850d7e5c --- /dev/null +++ b/tasks/soft-channel204/solution/closure.txt @@ -0,0 +1,70 @@ +OAI.Combinatorics.GotsmanLinial.Model +OAI.Combinatorics.GotsmanLinial.Statement +OAI.InformationTheory.BooleanNoise.ArtanhBounds +OAI.InformationTheory.BooleanNoise.Attainment +OAI.InformationTheory.BooleanNoise.Basic +OAI.InformationTheory.BooleanNoise.Comparison +OAI.InformationTheory.BooleanNoise.ComparisonEstimates +OAI.InformationTheory.BooleanNoise.ConcavityAcrossJoin +OAI.InformationTheory.BooleanNoise.CubeSplits +OAI.InformationTheory.BooleanNoise.CubeVariance +OAI.InformationTheory.BooleanNoise.CurvatureBounds +OAI.InformationTheory.BooleanNoise.CurvatureCertificates +OAI.InformationTheory.BooleanNoise.EndpointLimits +OAI.InformationTheory.BooleanNoise.EntropyBounds +OAI.InformationTheory.BooleanNoise.EntropyScalars +OAI.InformationTheory.BooleanNoise.EntropySeries +OAI.InformationTheory.BooleanNoise.FiniteDistribution +OAI.InformationTheory.BooleanNoise.FiniteInformation +OAI.InformationTheory.BooleanNoise.FiniteNoise +OAI.InformationTheory.BooleanNoise.GeneralDissipation +OAI.InformationTheory.BooleanNoise.InformationIdentity +OAI.InformationTheory.BooleanNoise.InverseRegularity +OAI.InformationTheory.BooleanNoise.InverseScalars +OAI.InformationTheory.BooleanNoise.JensenGaps +OAI.InformationTheory.BooleanNoise.KRegularity +OAI.InformationTheory.BooleanNoise.LRegularity +OAI.InformationTheory.BooleanNoise.LShape +OAI.InformationTheory.BooleanNoise.LambdaScalars +OAI.InformationTheory.BooleanNoise.LargeCurvature +OAI.InformationTheory.BooleanNoise.MediumCurvature +OAI.InformationTheory.BooleanNoise.Model +OAI.InformationTheory.BooleanNoise.MonotoneDissipation +OAI.InformationTheory.BooleanNoise.NormalizedPair +OAI.InformationTheory.BooleanNoise.PairEntropy +OAI.InformationTheory.BooleanNoise.PerspectiveCalculus +OAI.InformationTheory.BooleanNoise.PerspectiveInequality +OAI.InformationTheory.BooleanNoise.PerspectiveJensen +OAI.InformationTheory.BooleanNoise.PerspectiveLogTrapezoid +OAI.InformationTheory.BooleanNoise.Rearrangement +OAI.InformationTheory.BooleanNoise.SemigroupFlow +OAI.InformationTheory.BooleanNoise.SmallCurvatureAux +OAI.InformationTheory.BooleanNoise.Statement +OAI.InformationTheory.SoftChannel.Canonical +OAI.InformationTheory.SoftChannel.Comparison +OAI.InformationTheory.SoftChannel.Contraction +OAI.InformationTheory.SoftChannel.CurvatureBounds +OAI.InformationTheory.SoftChannel.CurvatureCertificates +OAI.InformationTheory.SoftChannel.EndpointLimits +OAI.InformationTheory.SoftChannel.HighReserve +OAI.InformationTheory.SoftChannel.JensenGaps +OAI.InformationTheory.SoftChannel.Joining +OAI.InformationTheory.SoftChannel.LRegularity +OAI.InformationTheory.SoftChannel.Main +OAI.InformationTheory.SoftChannel.Model +OAI.InformationTheory.SoftChannel.NormalizedPair +OAI.InformationTheory.SoftChannel.PairEntropy +OAI.InformationTheory.SoftChannel.Payment +OAI.InformationTheory.SoftChannel.PerspectiveCalculus +OAI.InformationTheory.SoftChannel.PerspectiveInequality +OAI.InformationTheory.SoftChannel.PerspectiveLogTrapezoid +OAI.InformationTheory.SoftChannel.Production +OAI.InformationTheory.SoftChannel.RateSlope +OAI.InformationTheory.SoftChannel.RateWindow +OAI.InformationTheory.SoftChannel.Rearrangement +OAI.InformationTheory.SoftChannel.SemigroupFlow +OAI.InformationTheory.SoftChannel.SoftInformation +OAI.InformationTheory.SoftChannel.SoftReserve +OAI.InformationTheory.SoftChannel.Thinning +OAI.InformationTheory.SoftChannel.Wall +OAI.InformationTheory.SoftChannel.Window diff --git a/tasks/soft-channel204/solution/reference.py b/tasks/soft-channel204/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/soft-channel204/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/soft-channel204/solution/solve.sh b/tasks/soft-channel204/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..859ce5dcc245197f56f0ba72c4c34c4dccdb84b9 --- /dev/null +++ b/tasks/soft-channel204/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SoftChannel204, i.e. module OAI.InformationTheory.SoftChannel.Main and the +# 70 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.InformationTheory.SoftChannel.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SoftChannel204" diff --git a/tasks/soft-channel204/task.toml b/tasks/soft-channel204/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4e489ad27ebec4d2408f1c86317358ac64fe0046 --- /dev/null +++ b/tasks/soft-channel204/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/soft-channel204" +version = "1.0.0" +description = "Prove SoftChannel204 (openai/math family 119: The Courtade–Kumar and Hellinger conjectures) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SoftChannel204.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SoftChannel204" +family = "119" +family_title = "The Courtade–Kumar and Hellinger conjectures" +subject = "Theoretical computer science" +theorems = ["OAI.SoftChannel204.fullMain"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.InformationTheory.SoftChannel.Main" +reference_modules = 70 +reference_lean_bytes = 495679 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 775 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12146 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/soft-channel204/tests/Challenge.lean b/tasks/soft-channel204/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..77ee2c34f2fd6372846bbd03fff438cea7e6cfdd --- /dev/null +++ b/tasks/soft-channel204/tests/Challenge.lean @@ -0,0 +1,121 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace SoftChannel204 + +abbrev Cube (n : ℕ) := Fin n → Bool + +def sign (b : Bool) : ℝ := if b then 1 else -1 + +def avg {n : ℕ} (g : Cube n → ℝ) : ℝ := (∑ x, g x) / (2 : ℝ) ^ n + +def L : ℝ := Real.log 2 + +def psi (r : ℝ) : ℝ := + (1 + r) / 2 * Real.log (1 + r) + (1 - r) / 2 * Real.log (1 - r) + +def H (r : ℝ) : ℝ := L - psi r + +def info {n : ℕ} (u : Cube n → ℝ) : ℝ := H (avg u) - avg (H ∘ u) + +def psiInv (s : ℝ) : ℝ := Function.invFunOn psi (Set.Icc 0 1) s + +def kernel {n : ℕ} (ρ : ℝ) (x y : Cube n) : ℝ := + ∏ i, if x i = y i then (1 + ρ) / 2 else (1 - ρ) / 2 + +def noise {n : ℕ} (ρ : ℝ) (u : Cube n → ℝ) (y : Cube n) : ℝ := + ∑ x, kernel ρ y x * u x + +def Closed {n : ℕ} (u : Cube n → ℝ) : Prop := ∀ x, u x ∈ Set.Icc (-1) 1 + +def Interior {n : ℕ} (g : Cube n → ℝ) : Prop := ∀ x, g x ∈ Set.Ioo (-1) 1 + +def softCoordinate {n : ℕ} (i : Fin n) (a : ℝ) (x : Cube n) : ℝ := a * sign (x i) + +def flip {n : ℕ} (i : Fin n) (x : Cube n) : Cube n := Function.update x i (!(x i)) + +def numberOperator {n : ℕ} (g : Cube n → ℝ) (x : Cube n) : ℝ := + (1 / 2 : ℝ) * ∑ i, (g x - g (flip i x)) + +def production {n : ℕ} (g : Cube n → ℝ) : ℝ := + avg (fun x => Real.artanh (g x) * numberOperator g x) + +/-- Defined by this formula on `[0, L)`; no finite endpoint value at `L` is asserted. -/ +def F (s : ℝ) : ℝ := psiInv s * Real.artanh (psiInv s) + +/-- The excess `F s - 2 * s`, used for `s < L`, is extended by zero to negative arguments. -/ +def S (s : ℝ) : ℝ := if s < 0 then 0 else F s - 2 * s + +/-- The reserve is used for `|m| < 1` and `0 ≤ I < H m`. -/ +def reserve (m I : ℝ) : ℝ := + 2 * I + (1 - m ^ 2) * S (L - (H m - I) / (1 - m ^ 2)) + +def hybrid (m I : ℝ) : ℝ := max (reserve m I) (F I) + +def softJoint {n : ℕ} (ρ : ℝ) (u : Cube n → ℝ) (b : Bool) (y : Cube n) : ℝ := + avg (fun x => (1 + sign b * u x) / 2 * kernel ρ x y) + +def boolJoint {n : ℕ} (ρ : ℝ) (f : Cube n → Bool) (b : Bool) (y : Cube n) : ℝ := + avg (fun x => if f x = b then kernel ρ x y else 0) + +def leftMarginal {n : ℕ} (p : Bool → Cube n → ℝ) (b : Bool) : ℝ := ∑ y, p b y + +def rightMarginal {n : ℕ} (p : Bool → Cube n → ℝ) (y : Cube n) : ℝ := ∑ b, p b y + +def mutualInformation {n : ℕ} (p : Bool → Cube n → ℝ) : ℝ := + ∑ b, ∑ y, if 0 < p b y then + p b y * Real.log (p b y / (leftMarginal p b * rightMarginal p y)) else 0 + +def binaryEntropyBits (ε : ℝ) : ℝ := + -(ε * Real.log ε + (1 - ε) * Real.log (1 - ε)) / L + +def SoftContraction : Prop := ∀ (n : ℕ) (u : Cube n → ℝ), Closed u → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + info (noise ρ u) ≤ psi (|ρ| * psiInv (info u)) + +def SoftAttainment : Prop := ∀ (n : ℕ) (i : Fin n) (a : ℝ), |a| ≤ 1 → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + info (noise ρ (softCoordinate i a)) = + psi (|ρ| * psiInv (info (softCoordinate i a))) + +def SoftInformationIdentity : Prop := ∀ (n : ℕ) (u : Cube n → ℝ), Closed u → + ∀ ρ ∈ Set.Icc (-1 : ℝ) 1, + mutualInformation (softJoint ρ u) = info (noise ρ u) + +def RefinedBoolean : Prop := ∀ (n : ℕ) (f : Cube n → Bool) + (ρ : ℝ), ρ ∈ Set.Icc (-1 : ℝ) 1 → + let m := avg (sign ∘ f) + let bound := psi (|ρ| * psiInv (H m)) + mutualInformation (boolJoint ρ f) = info (noise ρ (sign ∘ f)) ∧ + mutualInformation (boolJoint ρ f) ≤ bound ∧ bound ≤ psi |ρ| ∧ + (0 < |m| → |m| < 1 → 0 < |ρ| → bound < psi |ρ|) + +def BooleanAttainment : Prop := ∀ (n : ℕ) (i : Fin n) + (ρ : ℝ), ρ ∈ Set.Icc (-1 : ℝ) 1 → + mutualInformation (boolJoint ρ (fun x => x i)) = psi |ρ| ∧ + mutualInformation (boolJoint ρ (fun x => !(x i))) = psi |ρ| + +def BitsConversion : Prop := ∀ (n : ℕ) (f : Cube n → Bool) + (ε : ℝ), ε ∈ Set.Icc (0 : ℝ) (1/2) → + psi (1 - 2 * ε) / L = 1 - binaryEntropyBits ε ∧ + mutualInformation (boolJoint (1 - 2 * ε) f) / L ≤ 1 - binaryEntropyBits ε + +def SharpProduction : Prop := ∀ (n : ℕ) (g : Cube n → ℝ), Interior g → + hybrid (avg g) (info g) ≤ production g ∧ F (info g) ≤ hybrid (avg g) (info g) + +def FullMain : Prop := SoftContraction ∧ SoftAttainment ∧ SoftInformationIdentity ∧ + RefinedBoolean ∧ BooleanAttainment ∧ BitsConversion ∧ SharpProduction + +theorem fullMain : FullMain := by + sorry + +end SoftChannel204 + +end + +end OAI diff --git a/tasks/soft-channel204/tests/grade.py b/tasks/soft-channel204/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/soft-channel204/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/soft-channel204/tests/task.json b/tasks/soft-channel204/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..28b0d7c7e7490a26a05256c73b023b0aaee6931e --- /dev/null +++ b/tasks/soft-channel204/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SoftChannel204", + "comparator": { + "theorem_names": [ + "OAI.SoftChannel204.fullMain" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11246 +} \ No newline at end of file diff --git a/tasks/soft-channel204/tests/test.sh b/tasks/soft-channel204/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/soft-channel204/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/solenoidal-sheet-programs/environment/Dockerfile b/tasks/solenoidal-sheet-programs/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/solenoidal-sheet-programs/environment/fetch_mathlib.sh b/tasks/solenoidal-sheet-programs/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/solenoidal-sheet-programs/environment/lake-manifest.json b/tasks/solenoidal-sheet-programs/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/solenoidal-sheet-programs/environment/lakefile.lean b/tasks/solenoidal-sheet-programs/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/solenoidal-sheet-programs/environment/lean_setup.sh b/tasks/solenoidal-sheet-programs/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/solenoidal-sheet-programs/environment/pack_submission.py b/tasks/solenoidal-sheet-programs/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/solenoidal-sheet-programs/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/solenoidal-sheet-programs/instruction.md b/tasks/solenoidal-sheet-programs/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e2493f83858fe1d027381133309388d33bf754da --- /dev/null +++ b/tasks/solenoidal-sheet-programs/instruction.md @@ -0,0 +1,248 @@ +# openai/math challenge `SolenoidalSheetPrograms` (family 376) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 376 of the release, *Universal computation in forced Navier–Stokes flows* +(Partial differential equations). The family as a whole: Constructs viscous incompressible flows starting from rest on a fixed flat three-dimensional domain that perform universal computation under smooth external forcing. A terminating compiler turns a Turing machine and input into a finite program for the force, so a designated particle reaches a fixed region exactly when the machine halts. The viscosity is fixed, positive and computable. + +The challenge is `SolenoidalSheetPrograms`, also at `/opt/openai-math/challenges/SolenoidalSheetPrograms.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped BigOperators + +namespace Solenoidal + +abbrev Plane := Fin 2 → ℝ +abbrev Space := Fin 3 → ℝ +abbrev SpaceTime := ℝ × Space +abbrev Field := ℝ → Space → Space +abbrev Pressure := ℝ → Space → ℝ +abbrev Torus := Fin 3 → AddCircle (10 : ℝ) + +def toTorus (x : Space) : Torus := fun i => (x i : AddCircle (10 : ℝ)) + +def sheet (y : Plane) : Space := ![y 0, y 1, 2] + +structure Rectangle where + lower : Fin 2 → ℚ + upper : Fin 2 → ℚ + positive : ∀ j, lower j < upper j + +namespace Rectangle + +def carrier (R : Rectangle) : Set Plane := + {y | ∀ j, (R.lower j : ℝ) ≤ y j ∧ y j ≤ (R.upper j : ℝ)} + +def center (R : Rectangle) : Plane := + fun j => ((R.lower j : ℝ) + (R.upper j : ℝ)) / 2 + +def halfWidth (R : Rectangle) : Plane := + fun j => ((R.upper j : ℝ) - (R.lower j : ℝ)) / 2 + +def inCodingSquare (R : Rectangle) : Prop := + ∀ j, 2 ≤ R.lower j ∧ R.upper j ≤ 3 + +end Rectangle + +def SeparatelySeparated {N : ℕ} (R : Fin N → Rectangle) : Prop := + ∀ i j, i ≠ j → ∃ δ : ℝ, 0 < δ ∧ + ∀ x ∈ (R i).carrier, ∀ y ∈ (R j).carrier, δ ≤ ‖x - y‖ + +def diagonalMap (P Q : Rectangle) (r : Fin 2 → ℚ) (y : Plane) : Plane := + fun j => Q.center j + (r j : ℝ) * (y j - P.center j) + +structure SheetData (N : ℕ) where + source : Fin N → Rectangle + target : Fin N → Rectangle + source_inside : ∀ i, (source i).inCodingSquare + target_inside : ∀ i, (target i).inCodingSquare + source_separated : SeparatelySeparated source + target_separated : SeparatelySeparated target + ratio : Fin N → Fin 2 → ℚ + ratio_positive : ∀ i j, 0 < ratio i j + image_eq : ∀ i, + diagonalMap (source i) (target i) (ratio i) '' (source i).carrier = + (target i).carrier + +def deck (k : Fin 3 → ℤ) : Space := fun j => 10 * (k j : ℝ) + +def SpatiallyPeriodic {E : Type*} (g : ℝ → Space → E) : Prop := + ∀ t x k, g t (x + deck k) = g t x + +def fundamentalCell : Set Space := + Set.pi Set.univ (fun _ => Set.Ico (0 : ℝ) 10) + +def basis (j : Fin 3) : Space := Pi.single j 1 + +def spatialPartial (u : Field) (j : Fin 3) : Field := + fun t x => fderiv ℝ (u t) x (basis j) + +def timePartial (u : Field) : Field := + fun t x => derivWithin (fun s => u s x) (Set.Ici 0) t + +def divergence (u : Field) (t : ℝ) (x : Space) : ℝ := + ∑ j : Fin 3, spatialPartial u j t x j + +def laplacian (u : Field) : Field := + fun t x => ∑ j : Fin 3, spatialPartial (spatialPartial u j) j t x + +def advection (u : Field) : Field := + fun t x => fderiv ℝ (u t) x (u t x) + +def gradient (p : Pressure) : Field := + fun t x j => fderiv ℝ (p t) x (basis j) + +def DivergenceFree (u : Field) : Prop := ∀ t x, divergence u t x = 0 + +def MeanZero (u : Field) : Prop := + ∀ t, (∫ x in fundamentalCell, u t x) = 0 + +def Smooth (u : Field) : Prop := + ContDiff ℝ (⊤ : ℕ∞) (fun z : SpaceTime => u z.1 z.2) + +def OnePeriodic (u : Field) : Prop := ∀ t x, u (t + 1) x = u t x + +def IntegerCollars (u : Field) : Prop := + ∃ ε : ℝ, 0 < ε ∧ ∀ n : ℤ, ∀ t x, |t - (n : ℝ)| < ε → u t x = 0 + +def cylinder (T : ℝ) : Set SpaceTime := Set.Icc 0 T ×ˢ Set.univ + +structure ClassicalSolution (ν : ℝ) (f u : Field) (p : Pressure) : Prop where + spatial_periodic_u : SpatiallyPeriodic u + spatial_periodic_p : SpatiallyPeriodic p + continuous_u : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => u z.1 z.2) (cylinder T) + differentiable_t : ∀ t, 0 ≤ t → ∀ x, + DifferentiableWithinAt ℝ (fun s => u s x) (Set.Ici 0) t + continuous_t : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => timePartial u z.1 z.2) (cylinder T) + differentiable_x : ∀ t, 0 ≤ t → Differentiable ℝ (u t) + continuous_x : ∀ T, 0 ≤ T → ∀ j, + ContinuousOn (fun z : SpaceTime => spatialPartial u j z.1 z.2) (cylinder T) + differentiable_xx : ∀ t, 0 ≤ t → ∀ j, + Differentiable ℝ (spatialPartial u j t) + continuous_xx : ∀ T, 0 ≤ T → ∀ i j, + ContinuousOn (fun z : SpaceTime => spatialPartial (spatialPartial u i) j z.1 z.2) + (cylinder T) + continuous_p : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => p z.1 z.2) (cylinder T) + differentiable_p : ∀ t, 0 ≤ t → Differentiable ℝ (p t) + continuous_px : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => gradient p z.1 z.2) (cylinder T) + pressure_mean_zero : ∀ t, 0 ≤ t → (∫ x in fundamentalCell, p t x) = 0 + incompressible : ∀ t, 0 ≤ t → ∀ x, divergence u t x = 0 + initial : ∀ x, u 0 x = 0 + equation : ∀ t, 0 ≤ t → ∀ x, + timePartial u t x + advection u t x = + -gradient p t x + ν • laplacian u t x + f t x + +def MaterialFlow (u : Field) (X : ℝ → Space → Space) : Prop := + (∀ a, X 0 a = a) ∧ + (∀ a, ContinuousOn (fun t => X t a) (Set.Ici 0)) ∧ + (∀ a t, 0 ≤ t → + HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t) + +def spacetimeBasis : Fin 4 → SpaceTime := + ![(1, 0), (0, basis 0), (0, basis 1), (0, basis 2)] + +def mixedDerivative (u : Field) : List (Fin 4) → SpaceTime → Space + | [] => fun z => u z.1 z.2 + | j :: α => fun z => fderiv ℝ (mixedDerivative u α) z (spacetimeBasis j) + +def flatten (z : SpaceTime) : Fin 4 → ℝ := ![z.1, z.2 0, z.2 1, z.2 2] + +def NamesReal (c : Nat.Partrec.Code) (r : ℝ) : Prop := + ∀ n : ℕ, ∃ q : ℚ, Encodable.encode q ∈ c.eval n ∧ + |(q : ℝ) - r| ≤ (1 / 2 : ℝ) ^ n + +def ComputableReal (r : ℝ) : Prop := ∃ c, NamesReal c r + +def NamesPoint (c : Nat.Partrec.Code) (z : SpaceTime) : Prop := + ∀ n : ℕ, ∃ q : Fin 4 → ℚ, + @Encodable.encode (Fin 4 → ℚ) Encodable.finArrow q ∈ c.eval n ∧ + ‖(fun j => (q j : ℝ)) - flatten z‖ ≤ (1 / 2 : ℝ) ^ n + +def Effective (u : Field) : Prop := + ∃ e : Nat.Partrec.Code, ∀ α : List (Fin 4), ∀ c : Nat.Partrec.Code, + ∀ z : SpaceTime, NamesPoint c z → ∀ ε : ℚ, 0 < ε → + ∃ q : Fin 3 → ℚ, + @Encodable.encode (Fin 3 → ℚ) Encodable.finArrow q ∈ + e.eval (Encodable.encode (α, c, ε)) ∧ + ‖(fun j => (q j : ℝ)) - mixedDerivative u α z‖ < (ε : ℝ) + +def EffectiveBounds (u : Field) : Prop := + ∃ e : Nat.Partrec.Code, ∀ α : List (Fin 4), ∃ B : ℚ, + Encodable.encode B ∈ e.eval (Encodable.encode α) ∧ 0 ≤ B ∧ + ∀ z : SpaceTime, ‖mixedDerivative u α z‖ ≤ (B : ℝ) + +theorem sheet_theorem {N : ℕ} (D : SheetData N) (ν : ℝ) + (hν : 0 < ν) (hνcomp : ComputableReal ν) : + ∃ f u : Field, ∃ X : ℝ → Space → Space, + SpatiallyPeriodic f ∧ SpatiallyPeriodic u ∧ + Smooth f ∧ Smooth u ∧ Effective f ∧ + MeanZero f ∧ DivergenceFree f ∧ OnePeriodic f ∧ + ClassicalSolution ν f u (fun _ _ => 0) ∧ + (∀ v : Field, ∀ p : Pressure, ClassicalSolution ν f v p → + ∀ t, 0 ≤ t → ∀ x, v t x = u t x ∧ p t x = 0) ∧ + MaterialFlow u X ∧ + (∀ i : Fin N, ∀ y ∈ (D.source i).carrier, + toTorus (X 1 (sheet y)) = + toTorus (sheet (diagonalMap (D.source i) (D.target i) (D.ratio i) y))) ∧ + IntegerCollars u ∧ (∀ t x, advection u t x = 0) ∧ + EffectiveBounds f ∧ EffectiveBounds u ∧ + (N = 0 → f = 0 ∧ u = 0) := by + sorry + +end Solenoidal + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SolenoidalSheetPrograms.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Solenoidal.sheet_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/solenoidal-sheet-programs/solution/closure.txt b/tasks/solenoidal-sheet-programs/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9c4b94fdfad47eda2b4e54c1ad5f95847c589368 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/solution/closure.txt @@ -0,0 +1,26 @@ +OAI.MathematicalPhysics.SheetFlows.BoxJets +OAI.MathematicalPhysics.SheetFlows.CircuitPrograms +OAI.MathematicalPhysics.SheetFlows.Circuits +OAI.MathematicalPhysics.SheetFlows.ClassicalRegularity +OAI.MathematicalPhysics.SheetFlows.Clocks +OAI.MathematicalPhysics.SheetFlows.Computing +OAI.MathematicalPhysics.SheetFlows.Differential +OAI.MathematicalPhysics.SheetFlows.DirectForce +OAI.MathematicalPhysics.SheetFlows.EffectiveForcing +OAI.MathematicalPhysics.SheetFlows.EnergyIdentities +OAI.MathematicalPhysics.SheetFlows.FormulaProfiles +OAI.MathematicalPhysics.SheetFlows.JetCalculus +OAI.MathematicalPhysics.SheetFlows.JetProfiles +OAI.MathematicalPhysics.SheetFlows.Localization +OAI.MathematicalPhysics.SheetFlows.Model +OAI.MathematicalPhysics.SheetFlows.Profiles +OAI.MathematicalPhysics.SheetFlows.Pulses +OAI.MathematicalPhysics.SheetFlows.RationalBalls +OAI.MathematicalPhysics.SheetFlows.RationalFormula +OAI.MathematicalPhysics.SheetFlows.RectangleGeometry +OAI.MathematicalPhysics.SheetFlows.Routing +OAI.MathematicalPhysics.SheetFlows.ScheduledForce +OAI.MathematicalPhysics.SheetFlows.ShearCore +OAI.MathematicalPhysics.SheetFlows.SheetProgram +OAI.MathematicalPhysics.SheetFlows.Trajectories +OAI.MathematicalPhysics.SheetFlows.Uniqueness diff --git a/tasks/solenoidal-sheet-programs/solution/reference.py b/tasks/solenoidal-sheet-programs/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/solenoidal-sheet-programs/solution/solve.sh b/tasks/solenoidal-sheet-programs/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..20f5b81cd2376b93845390fb9cecf3ebe712eb91 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SolenoidalSheetPrograms, i.e. module OAI.MathematicalPhysics.SheetFlows.SheetProgram and the +# 26 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.MathematicalPhysics.SheetFlows.SheetProgram /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SolenoidalSheetPrograms" diff --git a/tasks/solenoidal-sheet-programs/task.toml b/tasks/solenoidal-sheet-programs/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dd1f8a7591faf32ff609c78a1c429b72d92e0985 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/solenoidal-sheet-programs" +version = "1.0.0" +description = "Prove SolenoidalSheetPrograms (openai/math family 376: Universal computation in forced Navier–Stokes flows) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SolenoidalSheetPrograms.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SolenoidalSheetPrograms" +family = "376" +family_title = "Universal computation in forced Navier–Stokes flows" +subject = "Partial differential equations" +theorems = ["OAI.Solenoidal.sheet_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.MathematicalPhysics.SheetFlows.SheetProgram" +reference_modules = 26 +reference_lean_bytes = 295192 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 690 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11965 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/solenoidal-sheet-programs/tests/Challenge.lean b/tasks/solenoidal-sheet-programs/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d066e7b2b954137731f96abb9e66efd24fe47b5e --- /dev/null +++ b/tasks/solenoidal-sheet-programs/tests/Challenge.lean @@ -0,0 +1,197 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open Set MeasureTheory +open scoped BigOperators + +namespace Solenoidal + +abbrev Plane := Fin 2 → ℝ +abbrev Space := Fin 3 → ℝ +abbrev SpaceTime := ℝ × Space +abbrev Field := ℝ → Space → Space +abbrev Pressure := ℝ → Space → ℝ +abbrev Torus := Fin 3 → AddCircle (10 : ℝ) + +def toTorus (x : Space) : Torus := fun i => (x i : AddCircle (10 : ℝ)) + +def sheet (y : Plane) : Space := ![y 0, y 1, 2] + +structure Rectangle where + lower : Fin 2 → ℚ + upper : Fin 2 → ℚ + positive : ∀ j, lower j < upper j + +namespace Rectangle + +def carrier (R : Rectangle) : Set Plane := + {y | ∀ j, (R.lower j : ℝ) ≤ y j ∧ y j ≤ (R.upper j : ℝ)} + +def center (R : Rectangle) : Plane := + fun j => ((R.lower j : ℝ) + (R.upper j : ℝ)) / 2 + +def halfWidth (R : Rectangle) : Plane := + fun j => ((R.upper j : ℝ) - (R.lower j : ℝ)) / 2 + +def inCodingSquare (R : Rectangle) : Prop := + ∀ j, 2 ≤ R.lower j ∧ R.upper j ≤ 3 + +end Rectangle + +def SeparatelySeparated {N : ℕ} (R : Fin N → Rectangle) : Prop := + ∀ i j, i ≠ j → ∃ δ : ℝ, 0 < δ ∧ + ∀ x ∈ (R i).carrier, ∀ y ∈ (R j).carrier, δ ≤ ‖x - y‖ + +def diagonalMap (P Q : Rectangle) (r : Fin 2 → ℚ) (y : Plane) : Plane := + fun j => Q.center j + (r j : ℝ) * (y j - P.center j) + +structure SheetData (N : ℕ) where + source : Fin N → Rectangle + target : Fin N → Rectangle + source_inside : ∀ i, (source i).inCodingSquare + target_inside : ∀ i, (target i).inCodingSquare + source_separated : SeparatelySeparated source + target_separated : SeparatelySeparated target + ratio : Fin N → Fin 2 → ℚ + ratio_positive : ∀ i j, 0 < ratio i j + image_eq : ∀ i, + diagonalMap (source i) (target i) (ratio i) '' (source i).carrier = + (target i).carrier + +def deck (k : Fin 3 → ℤ) : Space := fun j => 10 * (k j : ℝ) + +def SpatiallyPeriodic {E : Type*} (g : ℝ → Space → E) : Prop := + ∀ t x k, g t (x + deck k) = g t x + +def fundamentalCell : Set Space := + Set.pi Set.univ (fun _ => Set.Ico (0 : ℝ) 10) + +def basis (j : Fin 3) : Space := Pi.single j 1 + +def spatialPartial (u : Field) (j : Fin 3) : Field := + fun t x => fderiv ℝ (u t) x (basis j) + +def timePartial (u : Field) : Field := + fun t x => derivWithin (fun s => u s x) (Set.Ici 0) t + +def divergence (u : Field) (t : ℝ) (x : Space) : ℝ := + ∑ j : Fin 3, spatialPartial u j t x j + +def laplacian (u : Field) : Field := + fun t x => ∑ j : Fin 3, spatialPartial (spatialPartial u j) j t x + +def advection (u : Field) : Field := + fun t x => fderiv ℝ (u t) x (u t x) + +def gradient (p : Pressure) : Field := + fun t x j => fderiv ℝ (p t) x (basis j) + +def DivergenceFree (u : Field) : Prop := ∀ t x, divergence u t x = 0 + +def MeanZero (u : Field) : Prop := + ∀ t, (∫ x in fundamentalCell, u t x) = 0 + +def Smooth (u : Field) : Prop := + ContDiff ℝ (⊤ : ℕ∞) (fun z : SpaceTime => u z.1 z.2) + +def OnePeriodic (u : Field) : Prop := ∀ t x, u (t + 1) x = u t x + +def IntegerCollars (u : Field) : Prop := + ∃ ε : ℝ, 0 < ε ∧ ∀ n : ℤ, ∀ t x, |t - (n : ℝ)| < ε → u t x = 0 + +def cylinder (T : ℝ) : Set SpaceTime := Set.Icc 0 T ×ˢ Set.univ + +structure ClassicalSolution (ν : ℝ) (f u : Field) (p : Pressure) : Prop where + spatial_periodic_u : SpatiallyPeriodic u + spatial_periodic_p : SpatiallyPeriodic p + continuous_u : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => u z.1 z.2) (cylinder T) + differentiable_t : ∀ t, 0 ≤ t → ∀ x, + DifferentiableWithinAt ℝ (fun s => u s x) (Set.Ici 0) t + continuous_t : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => timePartial u z.1 z.2) (cylinder T) + differentiable_x : ∀ t, 0 ≤ t → Differentiable ℝ (u t) + continuous_x : ∀ T, 0 ≤ T → ∀ j, + ContinuousOn (fun z : SpaceTime => spatialPartial u j z.1 z.2) (cylinder T) + differentiable_xx : ∀ t, 0 ≤ t → ∀ j, + Differentiable ℝ (spatialPartial u j t) + continuous_xx : ∀ T, 0 ≤ T → ∀ i j, + ContinuousOn (fun z : SpaceTime => spatialPartial (spatialPartial u i) j z.1 z.2) + (cylinder T) + continuous_p : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => p z.1 z.2) (cylinder T) + differentiable_p : ∀ t, 0 ≤ t → Differentiable ℝ (p t) + continuous_px : ∀ T, 0 ≤ T → + ContinuousOn (fun z : SpaceTime => gradient p z.1 z.2) (cylinder T) + pressure_mean_zero : ∀ t, 0 ≤ t → (∫ x in fundamentalCell, p t x) = 0 + incompressible : ∀ t, 0 ≤ t → ∀ x, divergence u t x = 0 + initial : ∀ x, u 0 x = 0 + equation : ∀ t, 0 ≤ t → ∀ x, + timePartial u t x + advection u t x = + -gradient p t x + ν • laplacian u t x + f t x + +def MaterialFlow (u : Field) (X : ℝ → Space → Space) : Prop := + (∀ a, X 0 a = a) ∧ + (∀ a, ContinuousOn (fun t => X t a) (Set.Ici 0)) ∧ + (∀ a t, 0 ≤ t → + HasDerivWithinAt (fun s => X s a) (u t (X t a)) (Set.Ici 0) t) + +def spacetimeBasis : Fin 4 → SpaceTime := + ![(1, 0), (0, basis 0), (0, basis 1), (0, basis 2)] + +def mixedDerivative (u : Field) : List (Fin 4) → SpaceTime → Space + | [] => fun z => u z.1 z.2 + | j :: α => fun z => fderiv ℝ (mixedDerivative u α) z (spacetimeBasis j) + +def flatten (z : SpaceTime) : Fin 4 → ℝ := ![z.1, z.2 0, z.2 1, z.2 2] + +def NamesReal (c : Nat.Partrec.Code) (r : ℝ) : Prop := + ∀ n : ℕ, ∃ q : ℚ, Encodable.encode q ∈ c.eval n ∧ + |(q : ℝ) - r| ≤ (1 / 2 : ℝ) ^ n + +def ComputableReal (r : ℝ) : Prop := ∃ c, NamesReal c r + +def NamesPoint (c : Nat.Partrec.Code) (z : SpaceTime) : Prop := + ∀ n : ℕ, ∃ q : Fin 4 → ℚ, + @Encodable.encode (Fin 4 → ℚ) Encodable.finArrow q ∈ c.eval n ∧ + ‖(fun j => (q j : ℝ)) - flatten z‖ ≤ (1 / 2 : ℝ) ^ n + +def Effective (u : Field) : Prop := + ∃ e : Nat.Partrec.Code, ∀ α : List (Fin 4), ∀ c : Nat.Partrec.Code, + ∀ z : SpaceTime, NamesPoint c z → ∀ ε : ℚ, 0 < ε → + ∃ q : Fin 3 → ℚ, + @Encodable.encode (Fin 3 → ℚ) Encodable.finArrow q ∈ + e.eval (Encodable.encode (α, c, ε)) ∧ + ‖(fun j => (q j : ℝ)) - mixedDerivative u α z‖ < (ε : ℝ) + +def EffectiveBounds (u : Field) : Prop := + ∃ e : Nat.Partrec.Code, ∀ α : List (Fin 4), ∃ B : ℚ, + Encodable.encode B ∈ e.eval (Encodable.encode α) ∧ 0 ≤ B ∧ + ∀ z : SpaceTime, ‖mixedDerivative u α z‖ ≤ (B : ℝ) + +theorem sheet_theorem {N : ℕ} (D : SheetData N) (ν : ℝ) + (hν : 0 < ν) (hνcomp : ComputableReal ν) : + ∃ f u : Field, ∃ X : ℝ → Space → Space, + SpatiallyPeriodic f ∧ SpatiallyPeriodic u ∧ + Smooth f ∧ Smooth u ∧ Effective f ∧ + MeanZero f ∧ DivergenceFree f ∧ OnePeriodic f ∧ + ClassicalSolution ν f u (fun _ _ => 0) ∧ + (∀ v : Field, ∀ p : Pressure, ClassicalSolution ν f v p → + ∀ t, 0 ≤ t → ∀ x, v t x = u t x ∧ p t x = 0) ∧ + MaterialFlow u X ∧ + (∀ i : Fin N, ∀ y ∈ (D.source i).carrier, + toTorus (X 1 (sheet y)) = + toTorus (sheet (diagonalMap (D.source i) (D.target i) (D.ratio i) y))) ∧ + IntegerCollars u ∧ (∀ t x, advection u t x = 0) ∧ + EffectiveBounds f ∧ EffectiveBounds u ∧ + (N = 0 → f = 0 ∧ u = 0) := by + sorry + +end Solenoidal + +end + +end OAI diff --git a/tasks/solenoidal-sheet-programs/tests/grade.py b/tasks/solenoidal-sheet-programs/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/solenoidal-sheet-programs/tests/task.json b/tasks/solenoidal-sheet-programs/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e1167c32f6e35aa3a0dabf1f9c15fa68547ddce8 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SolenoidalSheetPrograms", + "comparator": { + "theorem_names": [ + "OAI.Solenoidal.sheet_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11065 +} \ No newline at end of file diff --git a/tasks/solenoidal-sheet-programs/tests/test.sh b/tasks/solenoidal-sheet-programs/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/solenoidal-sheet-programs/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/spherical-field/environment/Dockerfile b/tasks/spherical-field/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/spherical-field/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/spherical-field/environment/fetch_mathlib.sh b/tasks/spherical-field/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/spherical-field/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/spherical-field/environment/lake-manifest.json b/tasks/spherical-field/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/spherical-field/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/spherical-field/environment/lakefile.lean b/tasks/spherical-field/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/spherical-field/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/spherical-field/environment/lean_setup.sh b/tasks/spherical-field/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/spherical-field/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/spherical-field/environment/pack_submission.py b/tasks/spherical-field/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/spherical-field/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/spherical-field/instruction.md b/tasks/spherical-field/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a8e91b1de28b892c874d02209f10aa205505ab0d --- /dev/null +++ b/tasks/spherical-field/instruction.md @@ -0,0 +1,608 @@ +# openai/math challenge `SphericalField` (family 222) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 222 of the release, *Perceptron free energies and microscopic jamming* +(Probability and statistical mechanics). The family as a whole: Determines finite-temperature variational free energies for Gaussian Ising perceptrons with bounded Borel log-potentials and Gaussian spherical perceptrons with bounded continuous potentials, at every positive pattern density. A spherical extension treats bi-orthogonally invariant disorder with compact limiting singular-value distributions and no outliers. At margin $-1$, the quadratic-penalty spherical model has a sharp feasibility threshold and limiting gap and force laws, with system size, zero temperature, and critical density taken in that order. + +The challenge is `SphericalField`, also at `/opt/openai-math/challenges/SphericalField.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory ProbabilityTheory Filter Set +open scoped ENNReal NNReal Topology BigOperators BoundedContinuousFunction + +namespace SphericalPerceptron + +abbrev Time := unitInterval + +abbrev Spin (N : ℕ) := EuclideanSpace ℝ (Fin N) + +def unitSphereLaw (N : ℕ) : Measure (Metric.sphere (0 : Spin N) 1) := + let s := (volume : Measure (Spin N)).toSphere + (s Set.univ)⁻¹ • s + +structure Trial where + toFun : Time → ℝ + monotone : Monotone toFun + measurable : Measurable toFun + nonneg : ∀ t, 0 ≤ toFun t + le_one : ∀ t, toFun t ≤ 1 + +instance : CoeFun Trial (fun _ => Time → ℝ) := ⟨Trial.toFun⟩ + +def timeLaw : Measure Time := Measure.comap Subtype.val volume + +def tailIntegral (m : Trial) (t : Time) : ℝ := + ∫ s in Set.Ici t, m s ∂timeLaw + +def entropy (m : Trial) : ℝ≥0∞ := + (∫⁻ t, (ENNReal.ofReal (tailIntegral m t))⁻¹ - + (ENNReal.ofReal (1 - (t : ℝ)))⁻¹ ∂timeLaw) / 2 + +@[simp] theorem timeLaw_eq_volume : timeLaw = (volume : Measure Time) := rfl + +instance : IsProbabilityMeasure timeLaw := by + rw [timeLaw_eq_volume] + infer_instance + +def finitePointMeasure {S : Type*} [MeasurableSpace S] (n : ℕ) (x : Fin n → S) : Measure S := + ∑ i : Fin n, Measure.dirac (x i) + +@[fun_prop] lemma finitePointMeasure_measurable {S : Type*} [MeasurableSpace S] (n : ℕ) : + Measurable (finitePointMeasure (S := S) n) := by + unfold finitePointMeasure + fun_prop + +def finitePoissonLaw {S : Type*} [MeasurableSpace S] (r : ℝ≥0) (ν : Measure S) : + Measure (Measure S) := + Measure.sum fun n : ℕ => + poissonMeasure r {n} • (Measure.pi fun _ : Fin n => ν).map (finitePointMeasure n) + +instance finitePoissonLaw_probability {S : Type*} [MeasurableSpace S] + (r : ℝ≥0) (ν : Measure S) [IsProbabilityMeasure ν] : + IsProbabilityMeasure (finitePoissonLaw r ν) := by + constructor + rw [finitePoissonLaw,Measure.sum_apply _ MeasurableSet.univ] + have hmass (n : ℕ) : ((Measure.pi fun _ : Fin n => ν).map (finitePointMeasure n)) univ = 1 := by + rw [Measure.map_apply (finitePointMeasure_measurable n) MeasurableSet.univ, + preimage_univ,measure_univ] + simp only [Measure.smul_apply,hmass,smul_eq_mul,mul_one] + have hh := hasSum_one_poissonMeasure r + simp_rw [poissonMeasure_singleton] + rw [← ENNReal.ofReal_tsum_of_nonneg (fun _ => by positivity) hh.summable,hh.tsum_eq] + norm_num + +lemma measureSum_measurable {S : Type*} [MeasurableSpace S] : + Measurable (fun η : ℕ → Measure S => Measure.sum η) := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.sum_apply _ hs] + exact Measurable.tsum fun i => (Measure.measurable_coe hs).comp (measurable_pi_apply i) + +def countablePoissonLaw {S : Type*} [MeasurableSpace S] + (r : ℕ → ℝ≥0) (ν : ℕ → Measure S) : Measure (Measure S) := + (Measure.infinitePi fun i => finitePoissonLaw (r i) (ν i)).map Measure.sum + +instance countablePoissonLaw_probability {S : Type*} [MeasurableSpace S] + (r : ℕ → ℝ≥0) (ν : ℕ → Measure S) [∀ i, IsProbabilityMeasure (ν i)] : + IsProbabilityMeasure (countablePoissonLaw r ν) := by + unfold countablePoissonLaw + infer_instance + +def finiteIntensityMarks {S : Type*} [MeasurableSpace S] [Nonempty S] (κ : Measure S) : Measure S := + if κ univ = 0 then Measure.dirac (Classical.choice ‹Nonempty S›) else (κ univ)⁻¹ • κ + +instance finiteIntensityMarks_probability {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [IsFiniteMeasure κ] : IsProbabilityMeasure (finiteIntensityMarks κ) := by + by_cases hκ : κ univ = 0 + · simp only [finiteIntensityMarks,ite_eq_left hκ] + infer_instance + · constructor + simp [finiteIntensityMarks,hκ,ENNReal.inv_mul_cancel hκ (measure_ne_top _ _)] + +def poissonRandomMeasureLaw {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [SFinite κ] : Measure (Measure S) := + countablePoissonLaw (fun i => ((sfiniteSeq κ i) univ).toNNReal) + (fun i => finiteIntensityMarks (sfiniteSeq κ i)) + +instance poissonRandomMeasureLaw_probability {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [SFinite κ] : IsProbabilityMeasure (poissonRandomMeasureLaw κ) := by + unfold poissonRandomMeasureLaw + infer_instance + +def stableLogIntensity (b : ℝ) : Measure ℝ := + volume.withDensity (fun x => ENNReal.ofReal (b * Real.exp (-b*x))) + +instance stableLogIntensity_sigmaFinite (b : ℝ) : SigmaFinite (stableLogIntensity b) := by + unfold stableLogIntensity + infer_instance + +def normalizedMeasure {S : Type*} [MeasurableSpace S] (μ : Measure S) : Measure S := + (μ univ)⁻¹ • μ + +lemma measurable_measure_withDensity_fixed {S : Type*} [MeasurableSpace S] + {f : S → ℝ≥0∞} (hf : Measurable f) : Measurable (fun μ : Measure S => μ.withDensity f) := by + refine Measure.measurable_of_measurable_coe _ fun s hs => ?_ + simp only [withDensity_apply _ hs,← lintegral_indicator hs] + exact Measure.measurable_lintegral (hf.indicator hs) + +lemma normalizedMeasure_measurable {S : Type*} [MeasurableSpace S] : + Measurable (normalizedMeasure (S := S)) := by + refine Measure.measurable_of_measurable_coe _ fun s hs => ?_ + change Measurable (fun μ : Measure S => (μ univ)⁻¹ * μ s) + exact (Measure.measurable_coe MeasurableSet.univ).inv.mul (Measure.measurable_coe hs) + +section MarkedStable +variable {S : Type*} [MeasurableSpace S] + +def markedStableTotalE (η : Measure (ℝ × S)) : ℝ≥0∞ := + ∫⁻ p, ENNReal.ofReal (Real.exp p.1) ∂η + +@[fun_prop] lemma markedStableTotalE_measurable : Measurable (markedStableTotalE (S := S)) := + Measure.measurable_lintegral (by fun_prop) + +def markedStableTotal (η : Measure (ℝ × S)) : ℝ := (markedStableTotalE η).toReal + +@[fun_prop] lemma markedStableTotal_measurable : Measurable (markedStableTotal (S := S)) := + markedStableTotalE_measurable.ennreal_toReal + +def markedStableMassKernel : Kernel (Measure (ℝ × S)) (ℝ × S) where + toFun η := normalizedMeasure (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1))) + measurable' := normalizedMeasure_measurable.comp (measurable_measure_withDensity_fixed (by fun_prop)) + +instance markedStableMassKernel_finite : IsFiniteKernel (markedStableMassKernel (S := S)) := by + refine ⟨1, by simp, ?_⟩ + intro η + change (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1)) univ)⁻¹ * + (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1)) univ) ≤ 1 + exact ENNReal.inv_mul_le_one _ + +def markedStableCountKernel : Kernel (Measure (ℝ × S)) (ℝ × S) := + markedStableMassKernel.withDensity (fun η p => ENNReal.ofReal (markedStableTotal η*Real.exp (-p.1))) + +end MarkedStable + +@[reducible] def DecoratedCascade (S : Type) [MeasurableSpace S] : ℕ → MeasCat + | 0 => MeasCat.of Unit + | n+1 => MeasCat.of (Measure (ℝ×(S×DecoratedCascade S n))) + +instance decoratedCascadeNonempty (S : Type) [MeasurableSpace S] (n : ℕ) : + Nonempty (DecoratedCascade S n) := by + cases n with + | zero => exact ⟨()⟩ + | succ n => exact ⟨(0 : Measure (ℝ×(S×DecoratedCascade S n)))⟩ + +def decoratedCascadeLaw {S : Type} [MeasurableSpace S] [Nonempty S] + (ν : ProbabilityMeasure S) : (n : ℕ) → (Fin n → ℝ) → ProbabilityMeasure (DecoratedCascade S n) + | 0, _ => ⟨Measure.dirac (),by exact Measure.dirac.isProbabilityMeasure⟩ + | n+1, z => ⟨poissonRandomMeasureLaw ((stableLogIntensity (z 0)).prod + ((ν : Measure S).prod (decoratedCascadeLaw ν n (fun i => z i.succ)))), + by exact poissonRandomMeasureLaw_probability _⟩ + +def decoratedTerminalTotalE {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X×S → X) (H : X → ℝ) : (n : ℕ) → X×DecoratedCascade S n → ℝ≥0∞ + | 0, p => ENNReal.ofReal (Real.exp (H p.1)) + | n+1, p => ∫⁻ q : ℝ×(S×DecoratedCascade S n), ENNReal.ofReal (Real.exp q.1) * + decoratedTerminalTotalE step H n (step (p.1,q.2.1),q.2.2) ∂markedStableCountKernel p.2 + +def decoratedTerminalTotal {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X×S → X) (H : X → ℝ) (n : ℕ) (p : X×DecoratedCascade S n) : ℝ := + (decoratedTerminalTotalE step H n p).toReal + +def gaussianShiftStep (σ : ℕ → ℝ) (p : (ℕ → ℝ) × ℝ) : ℕ → ℝ := + fun i => p.1 (i+1)+σ i*p.2 + +def standardGaussianMark : ProbabilityMeasure ℝ := ⟨gaussianReal 0 1,inferInstance⟩ + +def piMarkLaw {ι S : Type} [Fintype ι] [MeasurableSpace S] + (ν : ι → ProbabilityMeasure S) : ProbabilityMeasure (ι → S) := + ⟨Measure.pi (fun i => (ν i : Measure S)),inferInstance⟩ + +def canonicalCoordinateStep (d : ℕ) (σ : ℕ → ℝ) : + (Fin d → ℕ → ℝ)×(Fin d → ℝ) → (Fin d → ℕ → ℝ) := + fun p i => gaussianShiftStep σ (p.1 i,p.2 i) + +def decoratedLeafIntegral {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X × S → X) (F : X → ℝ≥0∞) : + (n : ℕ) → X × DecoratedCascade S n → ℝ≥0∞ + | 0, p => F p.1 + | n+1, p => ∫⁻ q : ℝ × (S × DecoratedCascade S n), + ENNReal.ofReal (Real.exp q.1) * + decoratedLeafIntegral step F n (step (p.1,q.2.1),q.2.2) + ∂markedStableCountKernel p.2 + +def decoratedFieldFactor {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (d : ℕ) (step : X × S → X) (field : X → Spin d) (k : ℕ) + (p : X × DecoratedCascade S k) (x : Spin d) : ℝ≥0∞ := + decoratedLeafIntegral step (fun y => ENNReal.ofReal (Real.exp (inner ℝ (field y) x))) k p + +def decoratedAngularFactor {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (n : ℕ) (step : X × S → X) (field : X → Spin (n+1)) (k : ℕ) + (p : X × DecoratedCascade S k) (r : ℝ) : ℝ≥0∞ := + ∫⁻ u : Metric.sphere (0:Spin (n+1)) 1, + decoratedFieldFactor (n+1) step field k p (r • (u:Spin (n+1))) ∂unitSphereLaw (n+1) + +def coordinateLeafField (d : ℕ) (x : Fin d → ℕ → ℝ) : Spin d := + WithLp.toLp 2 (fun i => x i 0) + +def coordinateCascadeLaw (d k : ℕ) (z : Fin k → ℝ) (r : ℝ≥0) : + Measure ((Fin d → ℝ) × DecoratedCascade (Fin d → ℝ) k) := + (Measure.pi (fun _ : Fin d => gaussianReal 0 r)).prod + (decoratedCascadeLaw (piMarkLaw (fun _ : Fin d => standardGaussianMark)) k z) + +def coordinateAngularLog (n k : ℕ) (σ : ℕ → ℝ) (R : ℝ) + (p : (Fin (n+1) → ℕ → ℝ) × DecoratedCascade (Fin (n+1) → ℝ) k) : ℝ := + Real.log ((decoratedAngularFactor n (canonicalCoordinateStep (n+1) σ) + (coordinateLeafField (n+1)) k p R).toReal / + decoratedTerminalTotal (canonicalCoordinateStep (n+1) σ) (fun _ => 0) k p) + +def normalizedCoordinateSphereLog (n k : ℕ) (σ : ℕ → ℝ) + (p : (Fin (n+1) → ℝ) × DecoratedCascade (Fin (n+1) → ℝ) k) : ℝ := + coordinateAngularLog n k σ (Real.sqrt (n+1:ℕ)) ((fun i _ => p.1 i),p.2) / ((n+1:ℕ):ℝ) + +def expectedCoordinateSphereLog (n k : ℕ) (σ : ℕ → ℝ) (z : Fin k → ℝ) (r : ℝ≥0) : ℝ := + ∫ p, normalizedCoordinateSphereLog n k σ p ∂coordinateCascadeLaw (n+1) k z r + +def weightedStepTrial {I : Type*} [Fintype I] (w : I → ℝ) (q : I → Time) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i = 1) : Trial where + toFun := fun t => ∑ i, if q i ≤ t then w i else 0 + monotone := by + intro s t hst + apply Finset.sum_le_sum + intro i _ + by_cases hi : q i ≤ s + · simp only [ite_eq_left hi,ite_eq_left (hi.trans hst),le_refl] + · rw [ite_eq_right hi] + split_ifs <;> first | exact hw i | rfl + measurable := by + apply Finset.measurable_sum + intro i _ + exact measurable_const.ite (measurableSet_le measurable_const measurable_id) measurable_const + nonneg := by + intro t + apply Finset.sum_nonneg + intro i _ + split_ifs <;> first | exact hw i | rfl + le_one := by + intro t + rw [← hw1] + apply Finset.sum_le_sum + intro i _ + split_ifs <;> first | rfl | exact hw i + +def stepCumulative {k : ℕ} (w : Fin (k+1) → ℝ) (i : Fin k) : ℝ := + ∑ j : Fin (k+1), if j ≤ i.castSucc then w j else 0 + +def stepFieldIncrement (k : ℕ) (h : Fin (k+1) → ℝ) (j : ℕ) : ℝ := + if hj : j < k then + Real.sqrt (2*(h (Fin.rev ⟨j,hj⟩).succ-h (Fin.rev ⟨j,hj⟩).castSucc)) else 0 + +def finiteSphericalFieldValue (n k : ℕ) (w h : Fin (k+1) → ℝ) : ℝ := + expectedCoordinateSphereLog n k (stepFieldIncrement k h) (stepCumulative w) + (Real.toNNReal (2*h 0))-h (Fin.last k) + +def finiteSphericalDualObjective {k : ℕ} (w h : Fin (k+1) → ℝ) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i=1) (q : Fin (k+1) → Time) : ℝ := + (entropy (weightedStepTrial w q hw hw1)).toReal-∑ i, w i*h i*(q i:ℝ) + +def finiteSphericalDualValues {k : ℕ} (w h : Fin (k+1) → ℝ) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i=1) : Set ℝ := + finiteSphericalDualObjective w h hw hw1 '' + {q : Fin (k+1) → Time | Monotone q ∧ (q (Fin.last k):ℝ) < 1} + +structure FiniteFieldModel (f : Time → ℝ) where + depth : ℕ + value : Fin (depth+1) → ℝ + label : Time → Fin (depth+1) + measurable_label : Measurable label + positive : ∀ i, 0 < timeLaw.real (label ⁻¹' {i}) + monotone_value : Monotone value + agrees : (fun u => value (label u)) =ᵐ[timeLaw] f + +def FiniteFieldModel.weight {f : Time → ℝ} (M : FiniteFieldModel f) (i : Fin (M.depth+1)) : ℝ := + timeLaw.real (M.label ⁻¹' {i}) + +def FiniteFieldModel.pressure {f : Time → ℝ} (M : FiniteFieldModel f) (n : ℕ) : ℝ := + finiteSphericalFieldValue n M.depth M.weight M.value + +theorem exists_finiteFieldModel (f : Time → ℝ) (hf : Measurable f) + (hfin : (Set.range f).Finite) : Nonempty (FiniteFieldModel f) := by + classical + let S := hfin.toFinset + let T := S.filter (fun r => 0 < timeLaw.real (f ⁻¹' {r})) + have hae : ∀ᵐ u ∂timeLaw, f u ∈ T := by + have hnull : ∀ r ∈ S, ∀ᵐ u ∂timeLaw, f u=r → 0 < timeLaw.real (f ⁻¹' {r}) := by + intro r hr + by_cases hp : 0 < timeLaw.real (f ⁻¹' {r}) + · exact ae_of_all _ (fun _ _ => hp) + · have hz : timeLaw (f ⁻¹' {r})=0 := by + have hz : (timeLaw (f ⁻¹' {r})).toReal=0 := le_antisymm (le_of_not_gt hp) ENNReal.toReal_nonneg + have hp := (ENNReal.toReal_eq_zero_iff _).mp hz + rcases hp with hp | hp + · exact hp + · exact (measure_ne_top _ _ hp).elim + have hnot : ∀ᵐ u ∂timeLaw, f u ≠ r := by + apply ae_iff.mpr + simpa only [Set.preimage,Set.mem_singleton_iff,not_not] using hz + filter_upwards [hnot] with u hu + exact fun h => (hu h).elim + have hall := (S.eventually_all).mpr hnull + filter_upwards [hall] with u hu + have hmem : f u ∈ S := hfin.mem_toFinset.mpr (mem_range_self u) + exact Finset.mem_filter.mpr ⟨hmem,hu (f u) hmem rfl⟩ + have hT : T.Nonempty := by + obtain ⟨u,hu⟩ := hae.exists + exact ⟨f u,hu⟩ + obtain ⟨d,hd⟩ := Nat.exists_eq_succ_of_ne_zero (Finset.card_ne_zero.mpr hT) + let e := T.orderIsoOfFin hd + let v : Fin (d+1) → ℝ := fun i => e i + have hv : StrictMono v := fun i j hij => e.strictMono hij + have hve : MeasurableEmbedding v := ⟨hv.injective,measurable_of_finite _,fun _ _ => (Set.toFinite _).measurableSet⟩ + let a : Time → Fin (d+1) := fun u => hve.invFun (f u) + have hag : (fun u => v (a u)) =ᵐ[timeLaw] f := by + filter_upwards [hae] with u hu + have hx : f u=v (e.symm ⟨f u,hu⟩) := congrArg Subtype.val (e.apply_symm_apply ⟨f u,hu⟩) |>.symm + dsimp only [a] + rw [hx,hve.leftInverse_invFun] + refine ⟨⟨d,v,a,hve.measurable_invFun.comp hf,?_,hv.monotone,hag⟩⟩ + intro i + have he : a ⁻¹' {i}=ᵐ[timeLaw] f ⁻¹' {v i} := by + filter_upwards [hag] with u hu + apply propext + change (a u=i) ↔ f u=v i + rw [← hu] + exact hv.injective.eq_iff.symm + change 0 < (timeLaw (a ⁻¹' {i})).toReal + rw [measure_congr he] + exact (Finset.mem_filter.mp (e i).2).2 + +structure BoundedField (H : ℝ) where + toFun : Time → ℝ + monotone : Monotone toFun + nonneg : ∀ u, 0 ≤ toFun u + le_bound : ∀ u, toFun u ≤ H + +instance {H : ℝ} : CoeFun (BoundedField H) (fun _ => Time → ℝ) := ⟨BoundedField.toFun⟩ + +lemma BoundedField.measurable {H : ℝ} (f : BoundedField H) : Measurable f := f.monotone.measurable + +def roundLower (N : ℕ) (x : ℝ) : ℝ := (⌊(N+1:ℕ)*x⌋₊:ℝ)/(N+1:ℕ) + +lemma roundLower_nonneg (N : ℕ) (x : ℝ) : 0 ≤ roundLower N x := by unfold roundLower; positivity + +lemma roundLower_monotone (N : ℕ) : Monotone (roundLower N) := by + intro x y hxy + apply div_le_div_of_nonneg_right _ (by positivity) + exact_mod_cast Nat.floor_mono (mul_le_mul_of_nonneg_left hxy (by positivity)) + +lemma roundLower_le (N : ℕ) {x : ℝ} (hx : 0 ≤ x) : roundLower N x ≤ x := by + unfold roundLower + rw [div_le_iff₀ (by positivity : (0:ℝ)<(N+1:ℕ))] + simpa only [mul_comm] using Nat.floor_le (mul_nonneg (by positivity) hx) + +def BoundedField.round {H : ℝ} (f : BoundedField H) (N : ℕ) : BoundedField H where + toFun := fun u => roundLower N (f u) + monotone := (roundLower_monotone N).comp f.monotone + nonneg := fun u => roundLower_nonneg N (f u) + le_bound := fun u => (roundLower_le N (f.nonneg u)).trans (f.le_bound u) + +lemma BoundedField.round_finite {H : ℝ} (f : BoundedField H) (N : ℕ) : + (Set.range (f.round N)).Finite := by + let T := (Finset.range (⌊(N+1:ℕ)*H⌋₊+1)).image (fun k : ℕ => (k:ℝ)/(N+1:ℕ)) + apply T.finite_toSet.subset + rintro x ⟨u,rfl⟩ + apply Finset.mem_image.mpr + refine ⟨⌊(N+1:ℕ)*f u⌋₊,?_,rfl⟩ + apply Finset.mem_range.mpr + exact Nat.lt_succ_of_le (Nat.floor_mono (mul_le_mul_of_nonneg_left (f.le_bound u) (by positivity))) + +def BoundedField.roundModel {H : ℝ} (f : BoundedField H) (N : ℕ) : FiniteFieldModel (f.round N) := + Classical.choice (exists_finiteFieldModel _ (f.round N).measurable (f.round_finite N)) + +def quantileTrial (q : Time → Time) : Trial where + toFun := fun t => timeLaw.real {u | q u ≤ t} + monotone := by + intro s t hst + exact measureReal_mono (fun u hu => hu.trans hst) + measurable := by + apply Monotone.measurable + intro s t hst + exact measureReal_mono (fun u hu => hu.trans hst) + nonneg := fun _ => measureReal_nonneg + le_one := by + intro t + exact measureReal_le_one + +def quantileTail (q : Time → Time) (t : ℝ) : ℝ := + ∫ u, 1-max (q u:ℝ) t ∂timeLaw + +lemma quantileTail_integrable (q : Time → Time) (hq : Measurable q) (t : ℝ) : + Integrable (fun u => 1-max (q u:ℝ) t) timeLaw := by + have hm : Measurable (fun u => 1-max (q u:ℝ) t) := + measurable_const.sub ((measurable_subtype_coe.comp hq).max measurable_const) + apply Integrable.mono' (integrable_const (2+|t|)) hm.aestronglyMeasurable + exact ae_of_all _ fun u => by + rw [Real.norm_eq_abs] + have hq0 := (q u).2.1 + have hq1 := (q u).2.2 + have ha : |max (q u:ℝ) t| ≤ 1+|t| := by + rcases le_total (q u:ℝ) t with h | h + · rw [max_eq_right h]; linarith + · rw [max_eq_left h,abs_of_nonneg hq0]; nlinarith [abs_nonneg t] + have hb := abs_sub 1 (max (q u:ℝ) t) + norm_num at hb + linarith + +lemma quantileTail_lower (q : Time → Time) (hq : Measurable q) {B t : ℝ} + (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (ht : t ≤ B) : + 1-B ≤ quantileTail q t := by + have h := integral_mono_ae (integrable_const (1-B)) (quantileTail_integrable q hq t) + (hb.mono fun u hu => sub_le_sub_left (max_le hu ht) 1) + simpa [quantileTail] using h + +lemma quantileTail_lipschitz (q : Time → Time) (hq : Measurable q) : + LipschitzWith 1 (quantileTail q) := by + apply LipschitzWith.of_dist_le_mul + intro s t + rw [Real.dist_eq,Real.dist_eq,NNReal.coe_one,one_mul] + unfold quantileTail + rw [← integral_sub (quantileTail_integrable q hq s) (quantileTail_integrable q hq t)] + calc + _ ≤ ∫ u, |(1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)| ∂timeLaw := abs_integral_le_integral_abs + _ ≤ ∫ _ : Time, |s-t| ∂timeLaw := by + apply integral_mono ((quantileTail_integrable q hq s).sub (quantileTail_integrable q hq t)).abs (integrable_const _) + intro u + have h := (LipschitzWith.id.const_max (q u:ℝ)).dist_le_mul s t + simp only [Real.dist_eq,NNReal.coe_one,one_mul] at h + change |(1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)| ≤ _ + rw [show (1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)=max (q u:ℝ) t-max (q u:ℝ) s by ring,abs_sub_comm] + exact h + _ = _ := by simp + +def boundedSphericalFieldValue {H : ℝ} (f : BoundedField H) (n : ℕ) : ℝ := + limUnder atTop (fun N => (f.roundModel N).pressure n) + +def BoundedField.toQuantile {B : ℝ} (q : BoundedField B) (hB : B ≤ 1) : Time → Time := + fun u => ⟨q u,q.nonneg u,(q.le_bound u).trans hB⟩ + +lemma BoundedField.toQuantile_measurable {B : ℝ} (q : BoundedField B) (hB : B ≤ 1) : + Measurable (q.toQuantile hB) := q.measurable.subtype_mk + +def quantileA (q : Time → Time) (r : ℝ) : ℝ := + ∫ t in (0:ℝ)..r, 1/(quantileTail q t)^2 + +lemma quantileA_integrand_continuous {B : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) : + ContinuousOn (fun t => 1/(quantileTail q t)^2) (Icc 0 B) := by + apply continuousOn_const.div ((quantileTail_lipschitz q hq).continuous.continuousOn.pow 2) + intro t ht + exact pow_ne_zero _ (ne_of_gt ((sub_pos.mpr hB).trans_le (quantileTail_lower q hq hb ht.2))) + +lemma quantileA_integrand_bound {B t : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (ht : t ≤ B) : + 1/(quantileTail q t)^2 ≤ 1/(1-B)^2 := by + have hd := quantileTail_lower q hq hb ht + exact one_div_le_one_div_of_le (sq_pos_of_pos (sub_pos.mpr hB)) + (pow_le_pow_left₀ (sub_nonneg.mpr hB.le) hd 2) + +lemma quantileA_nonneg (q : Time → Time) {r : ℝ} (hr : 0 ≤ r) : 0 ≤ quantileA q r := + intervalIntegral.integral_nonneg hr (fun _ _ => by positivity) + +lemma quantileA_mono {B : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) : + MonotoneOn (quantileA q) (Icc 0 B) := by + intro r hr s hs hrs + exact intervalIntegral.integral_mono_interval le_rfl hr.1 hrs + (ae_of_all _ fun _ => by positivity) + (((quantileA_integrand_continuous q hq hB hb).mono (Icc_subset_Icc le_rfl hs.2)).intervalIntegrable_of_Icc hs.1) + +lemma quantileA_bound {B r : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (hr : r ∈ Icc 0 B) : + quantileA q r ≤ B/(1-B)^2 := by + have h := intervalIntegral.integral_mono_on hr.1 + (((quantileA_integrand_continuous q hq hB hb).mono (Icc_subset_Icc le_rfl hr.2)).intervalIntegrable_of_Icc hr.1) + (intervalIntegrable_const (μ := volume) (c := 1/(1-B)^2)) + (fun t ht => quantileA_integrand_bound q hq hB hb (ht.2.trans hr.2)) + have he : (∫ _t in (0:ℝ)..r, 1/(1-B)^2)=r/(1-B)^2 := by simp [div_eq_mul_inv] + rw [he] at h + exact h.trans (div_le_div_of_nonneg_right hr.2 (sq_nonneg _)) + +def BoundedField.stationary {B : ℝ} (q : BoundedField B) (hB : B < 1) : + BoundedField (B/(2*(1-B)^2)) where + toFun := fun u => quantileA (q.toQuantile hB.le) (q u)/2 + monotone := fun u v huv => div_le_div_of_nonneg_right + (quantileA_mono _ (q.toQuantile_measurable hB.le) hB (ae_of_all _ q.le_bound) + ⟨q.nonneg u,q.le_bound u⟩ ⟨q.nonneg v,q.le_bound v⟩ (q.monotone huv)) (by norm_num) + nonneg := fun u => div_nonneg (quantileA_nonneg _ (q.nonneg u)) (by norm_num) + le_bound := by + intro u + have h := (quantileA_bound _ (q.toQuantile_measurable hB.le) hB (ae_of_all _ q.le_bound) + ⟨q.nonneg u,q.le_bound u⟩) + calc + _ ≤ (B/(1-B)^2)/2 := div_le_div_of_nonneg_right h (by norm_num) + _ = _ := by rw [div_div,mul_comm] + +def clippedQuantile (q : Time → Time) (hq : Monotone q) (B : ℝ) (hB0 : 0 ≤ B) : BoundedField B where + toFun := fun u => min (q u:ℝ) B + monotone := fun _ _ huv => min_le_min (hq huv) le_rfl + nonneg := fun u => le_min (q u).2.1 hB0 + le_bound := fun _ => min_le_right _ _ + +def stationaryQuantileField (q : Time → Time) (hq : Monotone q) (B : ℝ) (hB0 : 0 ≤ B) (hB1 : B < 1) : + BoundedField (B/(2*(1-B)^2)) := (clippedQuantile q hq B hB0).stationary hB1 + +def SphericalLinearFieldFormula : Prop := + (∀ (k : ℕ) (w : Fin (k+1) → ℝ) (hw : ∀ i, 0 < w i) (hw1 : ∑ i, w i=1), + (∀ h : Fin (k+1) → ℝ, Monotone h → 0 ≤ h 0 → + ∃ q : Fin (k+1) → Time, Monotone q ∧ (q (Fin.last k):ℝ) < 1 ∧ + IsLeast (finiteSphericalDualValues w h (fun i => (hw i).le) hw1) + (finiteSphericalDualObjective w h (fun i => (hw i).le) hw1 q)) ∧ + (∀ K : Set (Fin (k+1) → ℝ), IsCompact K → + (∀ h ∈ K, Monotone h ∧ 0 ≤ h 0) → + TendstoUniformlyOn (fun n h => finiteSphericalFieldValue n k w h) + (fun h => sInf (finiteSphericalDualValues w h (fun i => (hw i).le) hw1)) atTop K)) ∧ + (∀ (B : ℝ) (hB0 : 0 ≤ B) (hB1 : B < 1) (ε : ℝ), 0 < ε → + ∀ᶠ n : ℕ in atTop, ∀ (q : Time → Time) (hq : Monotone q), + (∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) → + entropy (quantileTrial q) < ∞ ∧ + (∀ᵐ u ∂timeLaw, 2*stationaryQuantileField q hq B hB0 hB1 u=quantileA q (q u)) ∧ + |boundedSphericalFieldValue (stationaryQuantileField q hq B hB0 hB1) n- + ((entropy (quantileTrial q)).toReal- + ∫ u, stationaryQuantileField q hq B hB0 hB1 u*(q u:ℝ) ∂timeLaw)| < ε) + +end SphericalPerceptron + +end + +namespace SphericalPerceptron +theorem spherical_linear_field_formula : SphericalLinearFieldFormula := by + sorry +end SphericalPerceptron + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SphericalField.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SphericalPerceptron.spherical_linear_field_formula` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/spherical-field/solution/closure.txt b/tasks/spherical-field/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..33bc5b5662f4cce114578c335e9c55ef18537094 --- /dev/null +++ b/tasks/spherical-field/solution/closure.txt @@ -0,0 +1,142 @@ +OAI.Probability.SphericalField.Cascade.Bias +OAI.Probability.SphericalField.Cascade.Blocks +OAI.Probability.SphericalField.Cascade.Concentration +OAI.Probability.SphericalField.Cascade.CoordinateBounds +OAI.Probability.SphericalField.Cascade.Coordinates +OAI.Probability.SphericalField.Cascade.Decorated +OAI.Probability.SphericalField.Cascade.Descendants +OAI.Probability.SphericalField.Cascade.FocusedShapes +OAI.Probability.SphericalField.Cascade.HeatWord +OAI.Probability.SphericalField.Cascade.LogFluctuations +OAI.Probability.SphericalField.Cascade.MarkedMass +OAI.Probability.SphericalField.Cascade.MarkedStable +OAI.Probability.SphericalField.Cascade.Recursion +OAI.Probability.SphericalField.Cascade.Shapes +OAI.Probability.SphericalField.Cascade.TotalLaw +OAI.Probability.SphericalField.Control.Backward +OAI.Probability.SphericalField.Control.Continuity +OAI.Probability.SphericalField.Control.Feedback +OAI.Probability.SphericalField.Control.Filtration +OAI.Probability.SphericalField.Control.FiniteValue +OAI.Probability.SphericalField.Control.HeatChain +OAI.Probability.SphericalField.Control.Independence +OAI.Probability.SphericalField.Control.Intervals +OAI.Probability.SphericalField.Control.Payoff +OAI.Probability.SphericalField.Control.SmoothTerminals +OAI.Probability.SphericalField.Control.StepError +OAI.Probability.SphericalField.Control.Truncation +OAI.Probability.SphericalField.Entropy.CappedDensity +OAI.Probability.SphericalField.Entropy.Distribution +OAI.Probability.SphericalField.Entropy.Kernel +OAI.Probability.SphericalField.Entropy.Quantile +OAI.Probability.SphericalField.Entropy.StationaryExistence +OAI.Probability.SphericalField.Entropy.StepDual +OAI.Probability.SphericalField.Entropy.StepIntegral +OAI.Probability.SphericalField.Entropy.StepStationary +OAI.Probability.SphericalField.Entropy.Support +OAI.Probability.SphericalField.Entropy.Trials +OAI.Probability.SphericalField.Fields.BoundedPressure +OAI.Probability.SphericalField.Fields.BoundedUniform +OAI.Probability.SphericalField.Fields.CoupledDual +OAI.Probability.SphericalField.Fields.DepthUniform +OAI.Probability.SphericalField.Fields.FiniteModels +OAI.Probability.SphericalField.Fields.GridGap +OAI.Probability.SphericalField.Fields.HeightCost +OAI.Probability.SphericalField.Fields.HeightPartition +OAI.Probability.SphericalField.Fields.HeightWord +OAI.Probability.SphericalField.Fields.Rounding +OAI.Probability.SphericalField.Fields.Transport +OAI.Probability.SphericalField.Fields.UniformGrid +OAI.Probability.SphericalField.Fields.Words +OAI.Probability.SphericalField.Gaussian.ExponentialNorm +OAI.Probability.SphericalField.Gaussian.Fractional +OAI.Probability.SphericalField.Gaussian.Integration +OAI.Probability.SphericalField.Gaussian.Poincare +OAI.Probability.SphericalField.Gaussian.Quadratic +OAI.Probability.SphericalField.Gaussian.Rotations +OAI.Probability.SphericalField.Gaussian.Taylor +OAI.Probability.SphericalField.Gibbs.Contact +OAI.Probability.SphericalField.Gibbs.Convexity +OAI.Probability.SphericalField.Gibbs.Energy +OAI.Probability.SphericalField.Gibbs.GaussianField +OAI.Probability.SphericalField.Gibbs.GaussianIdentities +OAI.Probability.SphericalField.Gibbs.GaussianRows +OAI.Probability.SphericalField.Gibbs.LimitLaws +OAI.Probability.SphericalField.Gibbs.MixedVariance +OAI.Probability.SphericalField.Gibbs.ReplicaCalculus +OAI.Probability.SphericalField.Gibbs.ReplicaIdentity +OAI.Probability.SphericalField.Gibbs.Replicas +OAI.Probability.SphericalField.Gibbs.RootVariance +OAI.Probability.SphericalField.Gibbs.Thermal +OAI.Probability.SphericalField.Gibbs.Tilting +OAI.Probability.SphericalField.Heat.Average +OAI.Probability.SphericalField.Heat.Backward +OAI.Probability.SphericalField.Heat.Boundary +OAI.Probability.SphericalField.Heat.Continuity +OAI.Probability.SphericalField.Heat.Derivatives +OAI.Probability.SphericalField.Heat.Entropic +OAI.Probability.SphericalField.Heat.GeneratorBounds +OAI.Probability.SphericalField.Heat.Grid +OAI.Probability.SphericalField.Heat.Logarithm +OAI.Probability.SphericalField.Heat.MovingParameters +OAI.Probability.SphericalField.Heat.Semigroup +OAI.Probability.SphericalField.Heat.TerminalDerivative +OAI.Probability.SphericalField.Heat.Tilt +OAI.Probability.SphericalField.Heat.TimeDerivative +OAI.Probability.SphericalField.Heat.Translations +OAI.Probability.SphericalField.Heat.WordStability +OAI.Probability.SphericalField.Main +OAI.Probability.SphericalField.Model +OAI.Probability.SphericalField.Perceptron.Concentration +OAI.Probability.SphericalField.Perceptron.Model +OAI.Probability.SphericalField.Perceptron.Partition +OAI.Probability.SphericalField.Perceptron.TimeLaw +OAI.Probability.SphericalField.Perceptron.Variance +OAI.Probability.SphericalField.Poisson.BiasedLaw +OAI.Probability.SphericalField.Poisson.Campbell +OAI.Probability.SphericalField.Poisson.CountableLaw +OAI.Probability.SphericalField.Poisson.DistinctMoments +OAI.Probability.SphericalField.Poisson.FractionalMoments +OAI.Probability.SphericalField.Poisson.Intensity +OAI.Probability.SphericalField.Poisson.Laplace +OAI.Probability.SphericalField.Poisson.LogMoments +OAI.Probability.SphericalField.Poisson.MarkMeasure +OAI.Probability.SphericalField.Poisson.Mecke +OAI.Probability.SphericalField.Poisson.Palm +OAI.Probability.SphericalField.Poisson.Partitions +OAI.Probability.SphericalField.Poisson.PositiveMass +OAI.Probability.SphericalField.Poisson.RandomMeasure +OAI.Probability.SphericalField.Poisson.StableMoments +OAI.Probability.SphericalField.Poisson.Superposition +OAI.Probability.SphericalField.Poisson.WeightedTotal +OAI.Probability.SphericalField.Positivity.Arrays +OAI.Probability.SphericalField.Positivity.Cliques +OAI.Probability.SphericalField.Positivity.Duplication +OAI.Probability.SphericalField.Positivity.FiniteLaws +OAI.Probability.SphericalField.Positivity.JointLaw +OAI.Probability.SphericalField.Positivity.Nonnegative +OAI.Probability.SphericalField.Positivity.Patterns +OAI.Probability.SphericalField.Positivity.ReplicaMean +OAI.Probability.SphericalField.Positivity.Triangles +OAI.Probability.SphericalField.Quantiles.AlmostEverywhere +OAI.Probability.SphericalField.Quantiles.Convergence +OAI.Probability.SphericalField.Quantiles.Distribution +OAI.Probability.SphericalField.Quantiles.Entropy +OAI.Probability.SphericalField.Quantiles.FiniteStationary +OAI.Probability.SphericalField.Quantiles.RoundGrid +OAI.Probability.SphericalField.Quantiles.Stationary +OAI.Probability.SphericalField.Sphere.AmplitudeConvex +OAI.Probability.SphericalField.Sphere.AmplitudeLimit +OAI.Probability.SphericalField.Sphere.Bridge +OAI.Probability.SphericalField.Sphere.ConvexUniform +OAI.Probability.SphericalField.Sphere.EntropicParameter +OAI.Probability.SphericalField.Sphere.FiniteUniform +OAI.Probability.SphericalField.Sphere.Heat +OAI.Probability.SphericalField.Sphere.Invariance +OAI.Probability.SphericalField.Sphere.Limit +OAI.Probability.SphericalField.Sphere.Polar +OAI.Probability.SphericalField.Sphere.RadialBands +OAI.Probability.SphericalField.Sphere.RadialDensity +OAI.Probability.SphericalField.Sphere.Rotations +OAI.Probability.SphericalField.Sphere.Shell +OAI.Probability.SphericalField.Sphere.WeightedBands diff --git a/tasks/spherical-field/solution/reference.py b/tasks/spherical-field/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/spherical-field/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/spherical-field/solution/solve.sh b/tasks/spherical-field/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..facd91a4eed37d5882177a7963fa5b87ac9ce08d --- /dev/null +++ b/tasks/spherical-field/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SphericalField, i.e. module OAI.Probability.SphericalField.Main and the +# 142 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SphericalField.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SphericalField" diff --git a/tasks/spherical-field/task.toml b/tasks/spherical-field/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9a4f545c1503eee961635bfe4bb49a2e06c07bec --- /dev/null +++ b/tasks/spherical-field/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/spherical-field" +version = "1.0.0" +description = "Prove SphericalField (openai/math family 222: Perceptron free energies and microscopic jamming) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SphericalField.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SphericalField" +family = "222" +family_title = "Perceptron free energies and microscopic jamming" +subject = "Probability and statistical mechanics" +theorems = ["OAI.SphericalPerceptron.spherical_linear_field_formula"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SphericalField.Main" +reference_modules = 142 +reference_lean_bytes = 1253471 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1292 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12828 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/spherical-field/tests/Challenge.lean b/tasks/spherical-field/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c9eb09392ed2f2362329c81f139aa4f13dfaaf9e --- /dev/null +++ b/tasks/spherical-field/tests/Challenge.lean @@ -0,0 +1,557 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory ProbabilityTheory Filter Set +open scoped ENNReal NNReal Topology BigOperators BoundedContinuousFunction + +namespace SphericalPerceptron + +abbrev Time := unitInterval + +abbrev Spin (N : ℕ) := EuclideanSpace ℝ (Fin N) + +def unitSphereLaw (N : ℕ) : Measure (Metric.sphere (0 : Spin N) 1) := + let s := (volume : Measure (Spin N)).toSphere + (s Set.univ)⁻¹ • s + +structure Trial where + toFun : Time → ℝ + monotone : Monotone toFun + measurable : Measurable toFun + nonneg : ∀ t, 0 ≤ toFun t + le_one : ∀ t, toFun t ≤ 1 + +instance : CoeFun Trial (fun _ => Time → ℝ) := ⟨Trial.toFun⟩ + +def timeLaw : Measure Time := Measure.comap Subtype.val volume + +def tailIntegral (m : Trial) (t : Time) : ℝ := + ∫ s in Set.Ici t, m s ∂timeLaw + +def entropy (m : Trial) : ℝ≥0∞ := + (∫⁻ t, (ENNReal.ofReal (tailIntegral m t))⁻¹ - + (ENNReal.ofReal (1 - (t : ℝ)))⁻¹ ∂timeLaw) / 2 + +@[simp] theorem timeLaw_eq_volume : timeLaw = (volume : Measure Time) := rfl + +instance : IsProbabilityMeasure timeLaw := by + rw [timeLaw_eq_volume] + infer_instance + +def finitePointMeasure {S : Type*} [MeasurableSpace S] (n : ℕ) (x : Fin n → S) : Measure S := + ∑ i : Fin n, Measure.dirac (x i) + +@[fun_prop] lemma finitePointMeasure_measurable {S : Type*} [MeasurableSpace S] (n : ℕ) : + Measurable (finitePointMeasure (S := S) n) := by + unfold finitePointMeasure + fun_prop + +def finitePoissonLaw {S : Type*} [MeasurableSpace S] (r : ℝ≥0) (ν : Measure S) : + Measure (Measure S) := + Measure.sum fun n : ℕ => + poissonMeasure r {n} • (Measure.pi fun _ : Fin n => ν).map (finitePointMeasure n) + +instance finitePoissonLaw_probability {S : Type*} [MeasurableSpace S] + (r : ℝ≥0) (ν : Measure S) [IsProbabilityMeasure ν] : + IsProbabilityMeasure (finitePoissonLaw r ν) := by + constructor + rw [finitePoissonLaw,Measure.sum_apply _ MeasurableSet.univ] + have hmass (n : ℕ) : ((Measure.pi fun _ : Fin n => ν).map (finitePointMeasure n)) univ = 1 := by + rw [Measure.map_apply (finitePointMeasure_measurable n) MeasurableSet.univ, + preimage_univ,measure_univ] + simp only [Measure.smul_apply,hmass,smul_eq_mul,mul_one] + have hh := hasSum_one_poissonMeasure r + simp_rw [poissonMeasure_singleton] + rw [← ENNReal.ofReal_tsum_of_nonneg (fun _ => by positivity) hh.summable,hh.tsum_eq] + norm_num + +lemma measureSum_measurable {S : Type*} [MeasurableSpace S] : + Measurable (fun η : ℕ → Measure S => Measure.sum η) := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.sum_apply _ hs] + exact Measurable.tsum fun i => (Measure.measurable_coe hs).comp (measurable_pi_apply i) + +def countablePoissonLaw {S : Type*} [MeasurableSpace S] + (r : ℕ → ℝ≥0) (ν : ℕ → Measure S) : Measure (Measure S) := + (Measure.infinitePi fun i => finitePoissonLaw (r i) (ν i)).map Measure.sum + +instance countablePoissonLaw_probability {S : Type*} [MeasurableSpace S] + (r : ℕ → ℝ≥0) (ν : ℕ → Measure S) [∀ i, IsProbabilityMeasure (ν i)] : + IsProbabilityMeasure (countablePoissonLaw r ν) := by + unfold countablePoissonLaw + infer_instance + +def finiteIntensityMarks {S : Type*} [MeasurableSpace S] [Nonempty S] (κ : Measure S) : Measure S := + if κ univ = 0 then Measure.dirac (Classical.choice ‹Nonempty S›) else (κ univ)⁻¹ • κ + +instance finiteIntensityMarks_probability {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [IsFiniteMeasure κ] : IsProbabilityMeasure (finiteIntensityMarks κ) := by + by_cases hκ : κ univ = 0 + · simp only [finiteIntensityMarks,ite_eq_left hκ] + infer_instance + · constructor + simp [finiteIntensityMarks,hκ,ENNReal.inv_mul_cancel hκ (measure_ne_top _ _)] + +def poissonRandomMeasureLaw {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [SFinite κ] : Measure (Measure S) := + countablePoissonLaw (fun i => ((sfiniteSeq κ i) univ).toNNReal) + (fun i => finiteIntensityMarks (sfiniteSeq κ i)) + +instance poissonRandomMeasureLaw_probability {S : Type*} [MeasurableSpace S] [Nonempty S] + (κ : Measure S) [SFinite κ] : IsProbabilityMeasure (poissonRandomMeasureLaw κ) := by + unfold poissonRandomMeasureLaw + infer_instance + +def stableLogIntensity (b : ℝ) : Measure ℝ := + volume.withDensity (fun x => ENNReal.ofReal (b * Real.exp (-b*x))) + +instance stableLogIntensity_sigmaFinite (b : ℝ) : SigmaFinite (stableLogIntensity b) := by + unfold stableLogIntensity + infer_instance + +def normalizedMeasure {S : Type*} [MeasurableSpace S] (μ : Measure S) : Measure S := + (μ univ)⁻¹ • μ + +lemma measurable_measure_withDensity_fixed {S : Type*} [MeasurableSpace S] + {f : S → ℝ≥0∞} (hf : Measurable f) : Measurable (fun μ : Measure S => μ.withDensity f) := by + refine Measure.measurable_of_measurable_coe _ fun s hs => ?_ + simp only [withDensity_apply _ hs,← lintegral_indicator hs] + exact Measure.measurable_lintegral (hf.indicator hs) + +lemma normalizedMeasure_measurable {S : Type*} [MeasurableSpace S] : + Measurable (normalizedMeasure (S := S)) := by + refine Measure.measurable_of_measurable_coe _ fun s hs => ?_ + change Measurable (fun μ : Measure S => (μ univ)⁻¹ * μ s) + exact (Measure.measurable_coe MeasurableSet.univ).inv.mul (Measure.measurable_coe hs) + +section MarkedStable +variable {S : Type*} [MeasurableSpace S] + +def markedStableTotalE (η : Measure (ℝ × S)) : ℝ≥0∞ := + ∫⁻ p, ENNReal.ofReal (Real.exp p.1) ∂η + +@[fun_prop] lemma markedStableTotalE_measurable : Measurable (markedStableTotalE (S := S)) := + Measure.measurable_lintegral (by fun_prop) + +def markedStableTotal (η : Measure (ℝ × S)) : ℝ := (markedStableTotalE η).toReal + +@[fun_prop] lemma markedStableTotal_measurable : Measurable (markedStableTotal (S := S)) := + markedStableTotalE_measurable.ennreal_toReal + +def markedStableMassKernel : Kernel (Measure (ℝ × S)) (ℝ × S) where + toFun η := normalizedMeasure (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1))) + measurable' := normalizedMeasure_measurable.comp (measurable_measure_withDensity_fixed (by fun_prop)) + +instance markedStableMassKernel_finite : IsFiniteKernel (markedStableMassKernel (S := S)) := by + refine ⟨1, by simp, ?_⟩ + intro η + change (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1)) univ)⁻¹ * + (η.withDensity (fun p => ENNReal.ofReal (Real.exp p.1)) univ) ≤ 1 + exact ENNReal.inv_mul_le_one _ + +def markedStableCountKernel : Kernel (Measure (ℝ × S)) (ℝ × S) := + markedStableMassKernel.withDensity (fun η p => ENNReal.ofReal (markedStableTotal η*Real.exp (-p.1))) + +end MarkedStable + +@[reducible] def DecoratedCascade (S : Type) [MeasurableSpace S] : ℕ → MeasCat + | 0 => MeasCat.of Unit + | n+1 => MeasCat.of (Measure (ℝ×(S×DecoratedCascade S n))) + +instance decoratedCascadeNonempty (S : Type) [MeasurableSpace S] (n : ℕ) : + Nonempty (DecoratedCascade S n) := by + cases n with + | zero => exact ⟨()⟩ + | succ n => exact ⟨(0 : Measure (ℝ×(S×DecoratedCascade S n)))⟩ + +def decoratedCascadeLaw {S : Type} [MeasurableSpace S] [Nonempty S] + (ν : ProbabilityMeasure S) : (n : ℕ) → (Fin n → ℝ) → ProbabilityMeasure (DecoratedCascade S n) + | 0, _ => ⟨Measure.dirac (),by exact Measure.dirac.isProbabilityMeasure⟩ + | n+1, z => ⟨poissonRandomMeasureLaw ((stableLogIntensity (z 0)).prod + ((ν : Measure S).prod (decoratedCascadeLaw ν n (fun i => z i.succ)))), + by exact poissonRandomMeasureLaw_probability _⟩ + +def decoratedTerminalTotalE {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X×S → X) (H : X → ℝ) : (n : ℕ) → X×DecoratedCascade S n → ℝ≥0∞ + | 0, p => ENNReal.ofReal (Real.exp (H p.1)) + | n+1, p => ∫⁻ q : ℝ×(S×DecoratedCascade S n), ENNReal.ofReal (Real.exp q.1) * + decoratedTerminalTotalE step H n (step (p.1,q.2.1),q.2.2) ∂markedStableCountKernel p.2 + +def decoratedTerminalTotal {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X×S → X) (H : X → ℝ) (n : ℕ) (p : X×DecoratedCascade S n) : ℝ := + (decoratedTerminalTotalE step H n p).toReal + +def gaussianShiftStep (σ : ℕ → ℝ) (p : (ℕ → ℝ) × ℝ) : ℕ → ℝ := + fun i => p.1 (i+1)+σ i*p.2 + +def standardGaussianMark : ProbabilityMeasure ℝ := ⟨gaussianReal 0 1,inferInstance⟩ + +def piMarkLaw {ι S : Type} [Fintype ι] [MeasurableSpace S] + (ν : ι → ProbabilityMeasure S) : ProbabilityMeasure (ι → S) := + ⟨Measure.pi (fun i => (ν i : Measure S)),inferInstance⟩ + +def canonicalCoordinateStep (d : ℕ) (σ : ℕ → ℝ) : + (Fin d → ℕ → ℝ)×(Fin d → ℝ) → (Fin d → ℕ → ℝ) := + fun p i => gaussianShiftStep σ (p.1 i,p.2 i) + +def decoratedLeafIntegral {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (step : X × S → X) (F : X → ℝ≥0∞) : + (n : ℕ) → X × DecoratedCascade S n → ℝ≥0∞ + | 0, p => F p.1 + | n+1, p => ∫⁻ q : ℝ × (S × DecoratedCascade S n), + ENNReal.ofReal (Real.exp q.1) * + decoratedLeafIntegral step F n (step (p.1,q.2.1),q.2.2) + ∂markedStableCountKernel p.2 + +def decoratedFieldFactor {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (d : ℕ) (step : X × S → X) (field : X → Spin d) (k : ℕ) + (p : X × DecoratedCascade S k) (x : Spin d) : ℝ≥0∞ := + decoratedLeafIntegral step (fun y => ENNReal.ofReal (Real.exp (inner ℝ (field y) x))) k p + +def decoratedAngularFactor {X S : Type} [MeasurableSpace X] [MeasurableSpace S] + (n : ℕ) (step : X × S → X) (field : X → Spin (n+1)) (k : ℕ) + (p : X × DecoratedCascade S k) (r : ℝ) : ℝ≥0∞ := + ∫⁻ u : Metric.sphere (0:Spin (n+1)) 1, + decoratedFieldFactor (n+1) step field k p (r • (u:Spin (n+1))) ∂unitSphereLaw (n+1) + +def coordinateLeafField (d : ℕ) (x : Fin d → ℕ → ℝ) : Spin d := + WithLp.toLp 2 (fun i => x i 0) + +def coordinateCascadeLaw (d k : ℕ) (z : Fin k → ℝ) (r : ℝ≥0) : + Measure ((Fin d → ℝ) × DecoratedCascade (Fin d → ℝ) k) := + (Measure.pi (fun _ : Fin d => gaussianReal 0 r)).prod + (decoratedCascadeLaw (piMarkLaw (fun _ : Fin d => standardGaussianMark)) k z) + +def coordinateAngularLog (n k : ℕ) (σ : ℕ → ℝ) (R : ℝ) + (p : (Fin (n+1) → ℕ → ℝ) × DecoratedCascade (Fin (n+1) → ℝ) k) : ℝ := + Real.log ((decoratedAngularFactor n (canonicalCoordinateStep (n+1) σ) + (coordinateLeafField (n+1)) k p R).toReal / + decoratedTerminalTotal (canonicalCoordinateStep (n+1) σ) (fun _ => 0) k p) + +def normalizedCoordinateSphereLog (n k : ℕ) (σ : ℕ → ℝ) + (p : (Fin (n+1) → ℝ) × DecoratedCascade (Fin (n+1) → ℝ) k) : ℝ := + coordinateAngularLog n k σ (Real.sqrt (n+1:ℕ)) ((fun i _ => p.1 i),p.2) / ((n+1:ℕ):ℝ) + +def expectedCoordinateSphereLog (n k : ℕ) (σ : ℕ → ℝ) (z : Fin k → ℝ) (r : ℝ≥0) : ℝ := + ∫ p, normalizedCoordinateSphereLog n k σ p ∂coordinateCascadeLaw (n+1) k z r + +def weightedStepTrial {I : Type*} [Fintype I] (w : I → ℝ) (q : I → Time) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i = 1) : Trial where + toFun := fun t => ∑ i, if q i ≤ t then w i else 0 + monotone := by + intro s t hst + apply Finset.sum_le_sum + intro i _ + by_cases hi : q i ≤ s + · simp only [ite_eq_left hi,ite_eq_left (hi.trans hst),le_refl] + · rw [ite_eq_right hi] + split_ifs <;> first | exact hw i | rfl + measurable := by + apply Finset.measurable_sum + intro i _ + exact measurable_const.ite (measurableSet_le measurable_const measurable_id) measurable_const + nonneg := by + intro t + apply Finset.sum_nonneg + intro i _ + split_ifs <;> first | exact hw i | rfl + le_one := by + intro t + rw [← hw1] + apply Finset.sum_le_sum + intro i _ + split_ifs <;> first | rfl | exact hw i + +def stepCumulative {k : ℕ} (w : Fin (k+1) → ℝ) (i : Fin k) : ℝ := + ∑ j : Fin (k+1), if j ≤ i.castSucc then w j else 0 + +def stepFieldIncrement (k : ℕ) (h : Fin (k+1) → ℝ) (j : ℕ) : ℝ := + if hj : j < k then + Real.sqrt (2*(h (Fin.rev ⟨j,hj⟩).succ-h (Fin.rev ⟨j,hj⟩).castSucc)) else 0 + +def finiteSphericalFieldValue (n k : ℕ) (w h : Fin (k+1) → ℝ) : ℝ := + expectedCoordinateSphereLog n k (stepFieldIncrement k h) (stepCumulative w) + (Real.toNNReal (2*h 0))-h (Fin.last k) + +def finiteSphericalDualObjective {k : ℕ} (w h : Fin (k+1) → ℝ) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i=1) (q : Fin (k+1) → Time) : ℝ := + (entropy (weightedStepTrial w q hw hw1)).toReal-∑ i, w i*h i*(q i:ℝ) + +def finiteSphericalDualValues {k : ℕ} (w h : Fin (k+1) → ℝ) + (hw : ∀ i, 0 ≤ w i) (hw1 : ∑ i, w i=1) : Set ℝ := + finiteSphericalDualObjective w h hw hw1 '' + {q : Fin (k+1) → Time | Monotone q ∧ (q (Fin.last k):ℝ) < 1} + +structure FiniteFieldModel (f : Time → ℝ) where + depth : ℕ + value : Fin (depth+1) → ℝ + label : Time → Fin (depth+1) + measurable_label : Measurable label + positive : ∀ i, 0 < timeLaw.real (label ⁻¹' {i}) + monotone_value : Monotone value + agrees : (fun u => value (label u)) =ᵐ[timeLaw] f + +def FiniteFieldModel.weight {f : Time → ℝ} (M : FiniteFieldModel f) (i : Fin (M.depth+1)) : ℝ := + timeLaw.real (M.label ⁻¹' {i}) + +def FiniteFieldModel.pressure {f : Time → ℝ} (M : FiniteFieldModel f) (n : ℕ) : ℝ := + finiteSphericalFieldValue n M.depth M.weight M.value + +theorem exists_finiteFieldModel (f : Time → ℝ) (hf : Measurable f) + (hfin : (Set.range f).Finite) : Nonempty (FiniteFieldModel f) := by + classical + let S := hfin.toFinset + let T := S.filter (fun r => 0 < timeLaw.real (f ⁻¹' {r})) + have hae : ∀ᵐ u ∂timeLaw, f u ∈ T := by + have hnull : ∀ r ∈ S, ∀ᵐ u ∂timeLaw, f u=r → 0 < timeLaw.real (f ⁻¹' {r}) := by + intro r hr + by_cases hp : 0 < timeLaw.real (f ⁻¹' {r}) + · exact ae_of_all _ (fun _ _ => hp) + · have hz : timeLaw (f ⁻¹' {r})=0 := by + have hz : (timeLaw (f ⁻¹' {r})).toReal=0 := le_antisymm (le_of_not_gt hp) ENNReal.toReal_nonneg + have hp := (ENNReal.toReal_eq_zero_iff _).mp hz + rcases hp with hp | hp + · exact hp + · exact (measure_ne_top _ _ hp).elim + have hnot : ∀ᵐ u ∂timeLaw, f u ≠ r := by + apply ae_iff.mpr + simpa only [Set.preimage,Set.mem_singleton_iff,not_not] using hz + filter_upwards [hnot] with u hu + exact fun h => (hu h).elim + have hall := (S.eventually_all).mpr hnull + filter_upwards [hall] with u hu + have hmem : f u ∈ S := hfin.mem_toFinset.mpr (mem_range_self u) + exact Finset.mem_filter.mpr ⟨hmem,hu (f u) hmem rfl⟩ + have hT : T.Nonempty := by + obtain ⟨u,hu⟩ := hae.exists + exact ⟨f u,hu⟩ + obtain ⟨d,hd⟩ := Nat.exists_eq_succ_of_ne_zero (Finset.card_ne_zero.mpr hT) + let e := T.orderIsoOfFin hd + let v : Fin (d+1) → ℝ := fun i => e i + have hv : StrictMono v := fun i j hij => e.strictMono hij + have hve : MeasurableEmbedding v := ⟨hv.injective,measurable_of_finite _,fun _ _ => (Set.toFinite _).measurableSet⟩ + let a : Time → Fin (d+1) := fun u => hve.invFun (f u) + have hag : (fun u => v (a u)) =ᵐ[timeLaw] f := by + filter_upwards [hae] with u hu + have hx : f u=v (e.symm ⟨f u,hu⟩) := congrArg Subtype.val (e.apply_symm_apply ⟨f u,hu⟩) |>.symm + dsimp only [a] + rw [hx,hve.leftInverse_invFun] + refine ⟨⟨d,v,a,hve.measurable_invFun.comp hf,?_,hv.monotone,hag⟩⟩ + intro i + have he : a ⁻¹' {i}=ᵐ[timeLaw] f ⁻¹' {v i} := by + filter_upwards [hag] with u hu + apply propext + change (a u=i) ↔ f u=v i + rw [← hu] + exact hv.injective.eq_iff.symm + change 0 < (timeLaw (a ⁻¹' {i})).toReal + rw [measure_congr he] + exact (Finset.mem_filter.mp (e i).2).2 + +structure BoundedField (H : ℝ) where + toFun : Time → ℝ + monotone : Monotone toFun + nonneg : ∀ u, 0 ≤ toFun u + le_bound : ∀ u, toFun u ≤ H + +instance {H : ℝ} : CoeFun (BoundedField H) (fun _ => Time → ℝ) := ⟨BoundedField.toFun⟩ + +lemma BoundedField.measurable {H : ℝ} (f : BoundedField H) : Measurable f := f.monotone.measurable + +def roundLower (N : ℕ) (x : ℝ) : ℝ := (⌊(N+1:ℕ)*x⌋₊:ℝ)/(N+1:ℕ) + +lemma roundLower_nonneg (N : ℕ) (x : ℝ) : 0 ≤ roundLower N x := by unfold roundLower; positivity + +lemma roundLower_monotone (N : ℕ) : Monotone (roundLower N) := by + intro x y hxy + apply div_le_div_of_nonneg_right _ (by positivity) + exact_mod_cast Nat.floor_mono (mul_le_mul_of_nonneg_left hxy (by positivity)) + +lemma roundLower_le (N : ℕ) {x : ℝ} (hx : 0 ≤ x) : roundLower N x ≤ x := by + unfold roundLower + rw [div_le_iff₀ (by positivity : (0:ℝ)<(N+1:ℕ))] + simpa only [mul_comm] using Nat.floor_le (mul_nonneg (by positivity) hx) + +def BoundedField.round {H : ℝ} (f : BoundedField H) (N : ℕ) : BoundedField H where + toFun := fun u => roundLower N (f u) + monotone := (roundLower_monotone N).comp f.monotone + nonneg := fun u => roundLower_nonneg N (f u) + le_bound := fun u => (roundLower_le N (f.nonneg u)).trans (f.le_bound u) + +lemma BoundedField.round_finite {H : ℝ} (f : BoundedField H) (N : ℕ) : + (Set.range (f.round N)).Finite := by + let T := (Finset.range (⌊(N+1:ℕ)*H⌋₊+1)).image (fun k : ℕ => (k:ℝ)/(N+1:ℕ)) + apply T.finite_toSet.subset + rintro x ⟨u,rfl⟩ + apply Finset.mem_image.mpr + refine ⟨⌊(N+1:ℕ)*f u⌋₊,?_,rfl⟩ + apply Finset.mem_range.mpr + exact Nat.lt_succ_of_le (Nat.floor_mono (mul_le_mul_of_nonneg_left (f.le_bound u) (by positivity))) + +def BoundedField.roundModel {H : ℝ} (f : BoundedField H) (N : ℕ) : FiniteFieldModel (f.round N) := + Classical.choice (exists_finiteFieldModel _ (f.round N).measurable (f.round_finite N)) + +def quantileTrial (q : Time → Time) : Trial where + toFun := fun t => timeLaw.real {u | q u ≤ t} + monotone := by + intro s t hst + exact measureReal_mono (fun u hu => hu.trans hst) + measurable := by + apply Monotone.measurable + intro s t hst + exact measureReal_mono (fun u hu => hu.trans hst) + nonneg := fun _ => measureReal_nonneg + le_one := by + intro t + exact measureReal_le_one + +def quantileTail (q : Time → Time) (t : ℝ) : ℝ := + ∫ u, 1-max (q u:ℝ) t ∂timeLaw + +lemma quantileTail_integrable (q : Time → Time) (hq : Measurable q) (t : ℝ) : + Integrable (fun u => 1-max (q u:ℝ) t) timeLaw := by + have hm : Measurable (fun u => 1-max (q u:ℝ) t) := + measurable_const.sub ((measurable_subtype_coe.comp hq).max measurable_const) + apply Integrable.mono' (integrable_const (2+|t|)) hm.aestronglyMeasurable + exact ae_of_all _ fun u => by + rw [Real.norm_eq_abs] + have hq0 := (q u).2.1 + have hq1 := (q u).2.2 + have ha : |max (q u:ℝ) t| ≤ 1+|t| := by + rcases le_total (q u:ℝ) t with h | h + · rw [max_eq_right h]; linarith + · rw [max_eq_left h,abs_of_nonneg hq0]; nlinarith [abs_nonneg t] + have hb := abs_sub 1 (max (q u:ℝ) t) + norm_num at hb + linarith + +lemma quantileTail_lower (q : Time → Time) (hq : Measurable q) {B t : ℝ} + (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (ht : t ≤ B) : + 1-B ≤ quantileTail q t := by + have h := integral_mono_ae (integrable_const (1-B)) (quantileTail_integrable q hq t) + (hb.mono fun u hu => sub_le_sub_left (max_le hu ht) 1) + simpa [quantileTail] using h + +lemma quantileTail_lipschitz (q : Time → Time) (hq : Measurable q) : + LipschitzWith 1 (quantileTail q) := by + apply LipschitzWith.of_dist_le_mul + intro s t + rw [Real.dist_eq,Real.dist_eq,NNReal.coe_one,one_mul] + unfold quantileTail + rw [← integral_sub (quantileTail_integrable q hq s) (quantileTail_integrable q hq t)] + calc + _ ≤ ∫ u, |(1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)| ∂timeLaw := abs_integral_le_integral_abs + _ ≤ ∫ _ : Time, |s-t| ∂timeLaw := by + apply integral_mono ((quantileTail_integrable q hq s).sub (quantileTail_integrable q hq t)).abs (integrable_const _) + intro u + have h := (LipschitzWith.id.const_max (q u:ℝ)).dist_le_mul s t + simp only [Real.dist_eq,NNReal.coe_one,one_mul] at h + change |(1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)| ≤ _ + rw [show (1-max (q u:ℝ) s)-(1-max (q u:ℝ) t)=max (q u:ℝ) t-max (q u:ℝ) s by ring,abs_sub_comm] + exact h + _ = _ := by simp + +def boundedSphericalFieldValue {H : ℝ} (f : BoundedField H) (n : ℕ) : ℝ := + limUnder atTop (fun N => (f.roundModel N).pressure n) + +def BoundedField.toQuantile {B : ℝ} (q : BoundedField B) (hB : B ≤ 1) : Time → Time := + fun u => ⟨q u,q.nonneg u,(q.le_bound u).trans hB⟩ + +lemma BoundedField.toQuantile_measurable {B : ℝ} (q : BoundedField B) (hB : B ≤ 1) : + Measurable (q.toQuantile hB) := q.measurable.subtype_mk + +def quantileA (q : Time → Time) (r : ℝ) : ℝ := + ∫ t in (0:ℝ)..r, 1/(quantileTail q t)^2 + +lemma quantileA_integrand_continuous {B : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) : + ContinuousOn (fun t => 1/(quantileTail q t)^2) (Icc 0 B) := by + apply continuousOn_const.div ((quantileTail_lipschitz q hq).continuous.continuousOn.pow 2) + intro t ht + exact pow_ne_zero _ (ne_of_gt ((sub_pos.mpr hB).trans_le (quantileTail_lower q hq hb ht.2))) + +lemma quantileA_integrand_bound {B t : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (ht : t ≤ B) : + 1/(quantileTail q t)^2 ≤ 1/(1-B)^2 := by + have hd := quantileTail_lower q hq hb ht + exact one_div_le_one_div_of_le (sq_pos_of_pos (sub_pos.mpr hB)) + (pow_le_pow_left₀ (sub_nonneg.mpr hB.le) hd 2) + +lemma quantileA_nonneg (q : Time → Time) {r : ℝ} (hr : 0 ≤ r) : 0 ≤ quantileA q r := + intervalIntegral.integral_nonneg hr (fun _ _ => by positivity) + +lemma quantileA_mono {B : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) : + MonotoneOn (quantileA q) (Icc 0 B) := by + intro r hr s hs hrs + exact intervalIntegral.integral_mono_interval le_rfl hr.1 hrs + (ae_of_all _ fun _ => by positivity) + (((quantileA_integrand_continuous q hq hB hb).mono (Icc_subset_Icc le_rfl hs.2)).intervalIntegrable_of_Icc hs.1) + +lemma quantileA_bound {B r : ℝ} (q : Time → Time) (hq : Measurable q) + (hB : B < 1) (hb : ∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) (hr : r ∈ Icc 0 B) : + quantileA q r ≤ B/(1-B)^2 := by + have h := intervalIntegral.integral_mono_on hr.1 + (((quantileA_integrand_continuous q hq hB hb).mono (Icc_subset_Icc le_rfl hr.2)).intervalIntegrable_of_Icc hr.1) + (intervalIntegrable_const (μ := volume) (c := 1/(1-B)^2)) + (fun t ht => quantileA_integrand_bound q hq hB hb (ht.2.trans hr.2)) + have he : (∫ _t in (0:ℝ)..r, 1/(1-B)^2)=r/(1-B)^2 := by simp [div_eq_mul_inv] + rw [he] at h + exact h.trans (div_le_div_of_nonneg_right hr.2 (sq_nonneg _)) + +def BoundedField.stationary {B : ℝ} (q : BoundedField B) (hB : B < 1) : + BoundedField (B/(2*(1-B)^2)) where + toFun := fun u => quantileA (q.toQuantile hB.le) (q u)/2 + monotone := fun u v huv => div_le_div_of_nonneg_right + (quantileA_mono _ (q.toQuantile_measurable hB.le) hB (ae_of_all _ q.le_bound) + ⟨q.nonneg u,q.le_bound u⟩ ⟨q.nonneg v,q.le_bound v⟩ (q.monotone huv)) (by norm_num) + nonneg := fun u => div_nonneg (quantileA_nonneg _ (q.nonneg u)) (by norm_num) + le_bound := by + intro u + have h := (quantileA_bound _ (q.toQuantile_measurable hB.le) hB (ae_of_all _ q.le_bound) + ⟨q.nonneg u,q.le_bound u⟩) + calc + _ ≤ (B/(1-B)^2)/2 := div_le_div_of_nonneg_right h (by norm_num) + _ = _ := by rw [div_div,mul_comm] + +def clippedQuantile (q : Time → Time) (hq : Monotone q) (B : ℝ) (hB0 : 0 ≤ B) : BoundedField B where + toFun := fun u => min (q u:ℝ) B + monotone := fun _ _ huv => min_le_min (hq huv) le_rfl + nonneg := fun u => le_min (q u).2.1 hB0 + le_bound := fun _ => min_le_right _ _ + +def stationaryQuantileField (q : Time → Time) (hq : Monotone q) (B : ℝ) (hB0 : 0 ≤ B) (hB1 : B < 1) : + BoundedField (B/(2*(1-B)^2)) := (clippedQuantile q hq B hB0).stationary hB1 + +def SphericalLinearFieldFormula : Prop := + (∀ (k : ℕ) (w : Fin (k+1) → ℝ) (hw : ∀ i, 0 < w i) (hw1 : ∑ i, w i=1), + (∀ h : Fin (k+1) → ℝ, Monotone h → 0 ≤ h 0 → + ∃ q : Fin (k+1) → Time, Monotone q ∧ (q (Fin.last k):ℝ) < 1 ∧ + IsLeast (finiteSphericalDualValues w h (fun i => (hw i).le) hw1) + (finiteSphericalDualObjective w h (fun i => (hw i).le) hw1 q)) ∧ + (∀ K : Set (Fin (k+1) → ℝ), IsCompact K → + (∀ h ∈ K, Monotone h ∧ 0 ≤ h 0) → + TendstoUniformlyOn (fun n h => finiteSphericalFieldValue n k w h) + (fun h => sInf (finiteSphericalDualValues w h (fun i => (hw i).le) hw1)) atTop K)) ∧ + (∀ (B : ℝ) (hB0 : 0 ≤ B) (hB1 : B < 1) (ε : ℝ), 0 < ε → + ∀ᶠ n : ℕ in atTop, ∀ (q : Time → Time) (hq : Monotone q), + (∀ᵐ u ∂timeLaw, (q u:ℝ) ≤ B) → + entropy (quantileTrial q) < ∞ ∧ + (∀ᵐ u ∂timeLaw, 2*stationaryQuantileField q hq B hB0 hB1 u=quantileA q (q u)) ∧ + |boundedSphericalFieldValue (stationaryQuantileField q hq B hB0 hB1) n- + ((entropy (quantileTrial q)).toReal- + ∫ u, stationaryQuantileField q hq B hB0 hB1 u*(q u:ℝ) ∂timeLaw)| < ε) + +end SphericalPerceptron + +end + +namespace SphericalPerceptron +theorem spherical_linear_field_formula : SphericalLinearFieldFormula := by + sorry +end SphericalPerceptron + +end OAI diff --git a/tasks/spherical-field/tests/grade.py b/tasks/spherical-field/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/spherical-field/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/spherical-field/tests/task.json b/tasks/spherical-field/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f74853442199234b2afb6f95365af472308b9a2a --- /dev/null +++ b/tasks/spherical-field/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SphericalField", + "comparator": { + "theorem_names": [ + "OAI.SphericalPerceptron.spherical_linear_field_formula" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11928 +} \ No newline at end of file diff --git a/tasks/spherical-field/tests/test.sh b/tasks/spherical-field/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/spherical-field/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/split-tangent-integrability/environment/Dockerfile b/tasks/split-tangent-integrability/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/split-tangent-integrability/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/split-tangent-integrability/environment/fetch_mathlib.sh b/tasks/split-tangent-integrability/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/split-tangent-integrability/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/split-tangent-integrability/environment/lake-manifest.json b/tasks/split-tangent-integrability/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/split-tangent-integrability/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/split-tangent-integrability/environment/lakefile.lean b/tasks/split-tangent-integrability/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/split-tangent-integrability/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/split-tangent-integrability/environment/lean_setup.sh b/tasks/split-tangent-integrability/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/split-tangent-integrability/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/split-tangent-integrability/environment/pack_submission.py b/tasks/split-tangent-integrability/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/split-tangent-integrability/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/split-tangent-integrability/instruction.md b/tasks/split-tangent-integrability/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a843cc3cb11c088949267897fd7d8d63dfcfd5c --- /dev/null +++ b/tasks/split-tangent-integrability/instruction.md @@ -0,0 +1,193 @@ +# openai/math challenge `SplitTangentIntegrability` (family 052) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 052 of the release, *Tangent-bundle splittings and universal covers* +(Algebraic and complex geometry). The family as a whole: A splitting of the tangent bundle of a compact Kahler manifold into two integrable holomorphic subbundles induces a compatible product decomposition of its universal cover, proving the two-summand form of Beauville's splitting conjecture. On smooth rationally connected projective manifolds, both summands are automatically integrable, establishing Horing's conjecture and the corresponding product decomposition. + +The challenge is `SplitTangentIntegrability`, also at `/opt/openai-math/challenges/SplitTangentIntegrability.lean`: + +```lean +import Mathlib + +namespace OAI + + + +noncomputable section +open scoped Manifold ContDiff LinearAlgebra.Projectivization +open Set Bundle + +universe u +namespace SplitTangent + + +structure ComplexManifold where + dim : ℕ + Carrier : Type u + [topology : TopologicalSpace Carrier] + [charts : ChartedSpace (Fin dim → ℂ) Carrier] + [holomorphicAtlas : IsManifold 𝓘(ℂ, Fin dim → ℂ) ω Carrier] + [hausdorff : T2Space Carrier] + [secondCountable : SecondCountableTopology Carrier] + +attribute [instance] ComplexManifold.topology ComplexManifold.charts + ComplexManifold.holomorphicAtlas ComplexManifold.hausdorff + ComplexManifold.secondCountable + +abbrev Model (X : ComplexManifold.{u}) := Fin X.dim → ℂ +abbrev ModelWithCorners (X : ComplexManifold.{u}) := 𝓘(ℂ, Model X) +abbrev Tangent (X : ComplexManifold.{u}) (x : X.Carrier) := + TangentSpace (ModelWithCorners X) x + +abbrev ProjectiveSpace (N : ℕ) := ℙ ℂ (Fin (N + 1) → ℂ) + + + +def projectiveCoordinates {N : ℕ} (i : Fin (N + 1)) + (p : ProjectiveSpace N) : Fin (N + 1) → ℂ := + fun j => (p.rep i)⁻¹ * p.rep j + + + +structure ProjectiveEmbedding (X : ComplexManifold.{u}) where + N : ℕ + map : X.Carrier → ProjectiveSpace N + injective : Function.Injective map + open_patch : ∀ i, IsOpen {x | (map x).rep i ≠ 0} + holomorphic : ∀ i, ContMDiffOn (ModelWithCorners X) 𝓘(ℂ, Fin (N + 1) → ℂ) ω + (fun x => projectiveCoordinates i (map x)) {x | (map x).rep i ≠ 0} + immersion : ∀ x i, (map x).rep i ≠ 0 → Function.Injective + (mfderiv (ModelWithCorners X) 𝓘(ℂ, Fin (N + 1) → ℂ) + (fun y => projectiveCoordinates i (map y)) x) + + +structure RationalCurve (X : ComplexManifold.{u}) where + finite : ℂ → X.Carrier + infinity : ℂ → X.Carrier + finite_holomorphic : ContMDiff 𝓘(ℂ, ℂ) (ModelWithCorners X) ω finite + infinity_holomorphic : ContMDiff 𝓘(ℂ, ℂ) (ModelWithCorners X) ω infinity + overlap : ∀ z : ℂ, z ≠ 0 → finite z = infinity z⁻¹ + +def RationalCurve.value {X : ComplexManifold.{u}} (g : RationalCurve X) + (z : OnePoint ℂ) : X.Carrier := + z.elim (g.infinity 0) g.finite + +abbrev PairPolynomial (N : ℕ) := MvPolynomial (Fin 2 × Fin (N + 1)) ℂ + + +def Bihomogeneous {N : ℕ} (p : PairPolynomial N) : Prop := + ∃ a b : ℕ, ∀ m ∈ p.support, + (∑ i : Fin (N + 1), m (0, i)) = a ∧ + (∑ i : Fin (N + 1), m (1, i)) = b + +def pairEval {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) + (p : PairPolynomial e.N) (xy : X.Carrier × X.Carrier) : ℂ := + MvPolynomial.eval + (fun k : Fin 2 × Fin (e.N + 1) => + if k.1 = 0 then (e.map xy.1).rep k.2 else (e.map xy.2).rep k.2) p + + + +def IsZariskiOpenPair {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) + (U : Set (X.Carrier × X.Carrier)) : Prop := + ∃ equations : Set (PairPolynomial e.N), + (∀ p ∈ equations, Bihomogeneous p) ∧ + U = {xy | ∃ p ∈ equations, pairEval e p xy ≠ 0} + + + +def RationallyConnected {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) : Prop := + ∃ U : Set (X.Carrier × X.Carrier), IsZariskiOpenPair e U ∧ U.Nonempty ∧ Dense U ∧ + ∀ xy ∈ U, ∃ g : RationalCurve X, ∃ a b : OnePoint ℂ, + g.value a = xy.1 ∧ g.value b = xy.2 + + + +structure TangentSplitting (X : ComplexManifold.{u}) where + projector : ∀ x : X.Carrier, Tangent X x →L[ℂ] Tangent X x + idempotent : ∀ x v, projector x (projector x v) = projector x v + holomorphic : ContMDiff + ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) + ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) ω + (fun v : TangentBundle (ModelWithCorners X) X.Carrier => + (⟨v.proj, projector v.proj v.2⟩ : TangentBundle (ModelWithCorners X) X.Carrier)) + first_positive : ∀ x, 0 < Module.finrank ℂ (LinearMap.range (projector x).toLinearMap) + second_positive : ∀ x, 0 < Module.finrank ℂ (LinearMap.ker (projector x).toLinearMap) + +def TangentSplitting.first {X : ComplexManifold.{u}} (S : TangentSplitting X) (x : X.Carrier) : + Submodule ℂ (Tangent X x) := LinearMap.range (S.projector x).toLinearMap + +def TangentSplitting.second {X : ComplexManifold.{u}} (S : TangentSplitting X) (x : X.Carrier) : + Submodule ℂ (Tangent X x) := LinearMap.ker (S.projector x).toLinearMap + + + +def HolomorphicSectionOn (X : ComplexManifold.{u}) + (V : ∀ x : X.Carrier, Tangent X x) (U : Set X.Carrier) : Prop := + ContMDiffOn (ModelWithCorners X) ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) ω + (fun x => (⟨x, V x⟩ : TangentBundle (ModelWithCorners X) X.Carrier)) U + + +def Integrable (X : ComplexManifold.{u}) (D : ∀ x : X.Carrier, Submodule ℂ (Tangent X x)) : Prop := + ∀ U : Set X.Carrier, IsOpen U → ∀ V W : ∀ x : X.Carrier, Tangent X x, + HolomorphicSectionOn X V U → HolomorphicSectionOn X W U → + (∀ x ∈ U, V x ∈ D x) → (∀ x ∈ U, W x ∈ D x) → + ∀ x ∈ U, VectorField.mlieBracketWithin (ModelWithCorners X) V W U x ∈ D x + + + +def IntegrabilityStatement : Prop := + ∀ (X : ComplexManifold.{u}), ConnectedSpace X.Carrier → CompactSpace X.Carrier → + 2 ≤ X.dim → ∀ e : ProjectiveEmbedding X, RationallyConnected e → + ∀ S : TangentSplitting X, Integrable X S.first ∧ Integrable X S.second + +theorem integrability_main : IntegrabilityStatement.{u} := by + sorry + +end SplitTangent + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SplitTangentIntegrability.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SplitTangent.integrability_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/split-tangent-integrability/solution/closure.txt b/tasks/split-tangent-integrability/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5639d23b73676316f8ff3b69c0aa463ddd7269ea --- /dev/null +++ b/tasks/split-tangent-integrability/solution/closure.txt @@ -0,0 +1,15 @@ +OAI.Geometry.SplitTangent.Basic +OAI.Geometry.SplitTangent.BoxFirstTransport +OAI.Geometry.SplitTangent.BoxTransportBase +OAI.Geometry.SplitTangent.BracketIntegrability +OAI.Geometry.SplitTangent.FamilyPropagationStep +OAI.Geometry.SplitTangent.FormalBoxes +OAI.Geometry.SplitTangent.OpenManifold +OAI.Geometry.SplitTangent.RationalAccepted +OAI.Geometry.SplitTangent.RationalEncoding +OAI.Geometry.SplitTangent.RationalFamilies +OAI.Geometry.SplitTangent.RationalFamilyCover +OAI.Geometry.SplitTangent.RationalReparam +OAI.Geometry.SplitTangent.RationalTrivialization +OAI.Geometry.SplitTangent.RationalVariation +OAI.Geometry.SplitTangent.ZariskiPairOpen diff --git a/tasks/split-tangent-integrability/solution/reference.py b/tasks/split-tangent-integrability/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/split-tangent-integrability/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/split-tangent-integrability/solution/solve.sh b/tasks/split-tangent-integrability/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..03b1765588a4ab8812c23aa9a8feb8a6565b9831 --- /dev/null +++ b/tasks/split-tangent-integrability/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SplitTangentIntegrability, i.e. module OAI.Geometry.SplitTangent.RationalVariation and the +# 15 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.SplitTangent.RationalVariation /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SplitTangentIntegrability" diff --git a/tasks/split-tangent-integrability/task.toml b/tasks/split-tangent-integrability/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..70c0c7830467cd35c7a80a270d2adfc2e6147169 --- /dev/null +++ b/tasks/split-tangent-integrability/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/split-tangent-integrability" +version = "1.0.0" +description = "Prove SplitTangentIntegrability (openai/math family 052: Tangent-bundle splittings and universal covers) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SplitTangentIntegrability.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SplitTangentIntegrability" +family = "052" +family_title = "Tangent-bundle splittings and universal covers" +subject = "Algebraic and complex geometry" +theorems = ["OAI.SplitTangent.integrability_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.SplitTangent.RationalVariation" +reference_modules = 15 +reference_lean_bytes = 804852 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 529 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12424 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/split-tangent-integrability/tests/Challenge.lean b/tasks/split-tangent-integrability/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2814ba164e21d9eea00513eabd2a952c77cbb2cd --- /dev/null +++ b/tasks/split-tangent-integrability/tests/Challenge.lean @@ -0,0 +1,142 @@ +import Mathlib + +namespace OAI + + + +noncomputable section +open scoped Manifold ContDiff LinearAlgebra.Projectivization +open Set Bundle + +universe u +namespace SplitTangent + + +structure ComplexManifold where + dim : ℕ + Carrier : Type u + [topology : TopologicalSpace Carrier] + [charts : ChartedSpace (Fin dim → ℂ) Carrier] + [holomorphicAtlas : IsManifold 𝓘(ℂ, Fin dim → ℂ) ω Carrier] + [hausdorff : T2Space Carrier] + [secondCountable : SecondCountableTopology Carrier] + +attribute [instance] ComplexManifold.topology ComplexManifold.charts + ComplexManifold.holomorphicAtlas ComplexManifold.hausdorff + ComplexManifold.secondCountable + +abbrev Model (X : ComplexManifold.{u}) := Fin X.dim → ℂ +abbrev ModelWithCorners (X : ComplexManifold.{u}) := 𝓘(ℂ, Model X) +abbrev Tangent (X : ComplexManifold.{u}) (x : X.Carrier) := + TangentSpace (ModelWithCorners X) x + +abbrev ProjectiveSpace (N : ℕ) := ℙ ℂ (Fin (N + 1) → ℂ) + + + +def projectiveCoordinates {N : ℕ} (i : Fin (N + 1)) + (p : ProjectiveSpace N) : Fin (N + 1) → ℂ := + fun j => (p.rep i)⁻¹ * p.rep j + + + +structure ProjectiveEmbedding (X : ComplexManifold.{u}) where + N : ℕ + map : X.Carrier → ProjectiveSpace N + injective : Function.Injective map + open_patch : ∀ i, IsOpen {x | (map x).rep i ≠ 0} + holomorphic : ∀ i, ContMDiffOn (ModelWithCorners X) 𝓘(ℂ, Fin (N + 1) → ℂ) ω + (fun x => projectiveCoordinates i (map x)) {x | (map x).rep i ≠ 0} + immersion : ∀ x i, (map x).rep i ≠ 0 → Function.Injective + (mfderiv (ModelWithCorners X) 𝓘(ℂ, Fin (N + 1) → ℂ) + (fun y => projectiveCoordinates i (map y)) x) + + +structure RationalCurve (X : ComplexManifold.{u}) where + finite : ℂ → X.Carrier + infinity : ℂ → X.Carrier + finite_holomorphic : ContMDiff 𝓘(ℂ, ℂ) (ModelWithCorners X) ω finite + infinity_holomorphic : ContMDiff 𝓘(ℂ, ℂ) (ModelWithCorners X) ω infinity + overlap : ∀ z : ℂ, z ≠ 0 → finite z = infinity z⁻¹ + +def RationalCurve.value {X : ComplexManifold.{u}} (g : RationalCurve X) + (z : OnePoint ℂ) : X.Carrier := + z.elim (g.infinity 0) g.finite + +abbrev PairPolynomial (N : ℕ) := MvPolynomial (Fin 2 × Fin (N + 1)) ℂ + + +def Bihomogeneous {N : ℕ} (p : PairPolynomial N) : Prop := + ∃ a b : ℕ, ∀ m ∈ p.support, + (∑ i : Fin (N + 1), m (0, i)) = a ∧ + (∑ i : Fin (N + 1), m (1, i)) = b + +def pairEval {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) + (p : PairPolynomial e.N) (xy : X.Carrier × X.Carrier) : ℂ := + MvPolynomial.eval + (fun k : Fin 2 × Fin (e.N + 1) => + if k.1 = 0 then (e.map xy.1).rep k.2 else (e.map xy.2).rep k.2) p + + + +def IsZariskiOpenPair {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) + (U : Set (X.Carrier × X.Carrier)) : Prop := + ∃ equations : Set (PairPolynomial e.N), + (∀ p ∈ equations, Bihomogeneous p) ∧ + U = {xy | ∃ p ∈ equations, pairEval e p xy ≠ 0} + + + +def RationallyConnected {X : ComplexManifold.{u}} (e : ProjectiveEmbedding X) : Prop := + ∃ U : Set (X.Carrier × X.Carrier), IsZariskiOpenPair e U ∧ U.Nonempty ∧ Dense U ∧ + ∀ xy ∈ U, ∃ g : RationalCurve X, ∃ a b : OnePoint ℂ, + g.value a = xy.1 ∧ g.value b = xy.2 + + + +structure TangentSplitting (X : ComplexManifold.{u}) where + projector : ∀ x : X.Carrier, Tangent X x →L[ℂ] Tangent X x + idempotent : ∀ x v, projector x (projector x v) = projector x v + holomorphic : ContMDiff + ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) + ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) ω + (fun v : TangentBundle (ModelWithCorners X) X.Carrier => + (⟨v.proj, projector v.proj v.2⟩ : TangentBundle (ModelWithCorners X) X.Carrier)) + first_positive : ∀ x, 0 < Module.finrank ℂ (LinearMap.range (projector x).toLinearMap) + second_positive : ∀ x, 0 < Module.finrank ℂ (LinearMap.ker (projector x).toLinearMap) + +def TangentSplitting.first {X : ComplexManifold.{u}} (S : TangentSplitting X) (x : X.Carrier) : + Submodule ℂ (Tangent X x) := LinearMap.range (S.projector x).toLinearMap + +def TangentSplitting.second {X : ComplexManifold.{u}} (S : TangentSplitting X) (x : X.Carrier) : + Submodule ℂ (Tangent X x) := LinearMap.ker (S.projector x).toLinearMap + + + +def HolomorphicSectionOn (X : ComplexManifold.{u}) + (V : ∀ x : X.Carrier, Tangent X x) (U : Set X.Carrier) : Prop := + ContMDiffOn (ModelWithCorners X) ((ModelWithCorners X).prod 𝓘(ℂ, Model X)) ω + (fun x => (⟨x, V x⟩ : TangentBundle (ModelWithCorners X) X.Carrier)) U + + +def Integrable (X : ComplexManifold.{u}) (D : ∀ x : X.Carrier, Submodule ℂ (Tangent X x)) : Prop := + ∀ U : Set X.Carrier, IsOpen U → ∀ V W : ∀ x : X.Carrier, Tangent X x, + HolomorphicSectionOn X V U → HolomorphicSectionOn X W U → + (∀ x ∈ U, V x ∈ D x) → (∀ x ∈ U, W x ∈ D x) → + ∀ x ∈ U, VectorField.mlieBracketWithin (ModelWithCorners X) V W U x ∈ D x + + + +def IntegrabilityStatement : Prop := + ∀ (X : ComplexManifold.{u}), ConnectedSpace X.Carrier → CompactSpace X.Carrier → + 2 ≤ X.dim → ∀ e : ProjectiveEmbedding X, RationallyConnected e → + ∀ S : TangentSplitting X, Integrable X S.first ∧ Integrable X S.second + +theorem integrability_main : IntegrabilityStatement.{u} := by + sorry + +end SplitTangent + +end + +end OAI diff --git a/tasks/split-tangent-integrability/tests/grade.py b/tasks/split-tangent-integrability/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/split-tangent-integrability/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/split-tangent-integrability/tests/task.json b/tasks/split-tangent-integrability/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..2f0e3fab826fb39dadbe7737d7fce60900f2ff8b --- /dev/null +++ b/tasks/split-tangent-integrability/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SplitTangentIntegrability", + "comparator": { + "theorem_names": [ + "OAI.SplitTangent.integrability_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11524 +} \ No newline at end of file diff --git a/tasks/split-tangent-integrability/tests/test.sh b/tasks/split-tangent-integrability/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/split-tangent-integrability/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/square-difference/environment/Dockerfile b/tasks/square-difference/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/square-difference/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/square-difference/environment/fetch_mathlib.sh b/tasks/square-difference/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/square-difference/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/square-difference/environment/lake-manifest.json b/tasks/square-difference/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/square-difference/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/square-difference/environment/lakefile.lean b/tasks/square-difference/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/square-difference/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/square-difference/environment/lean_setup.sh b/tasks/square-difference/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/square-difference/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/square-difference/environment/pack_submission.py b/tasks/square-difference/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/square-difference/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/square-difference/instruction.md b/tasks/square-difference/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d556f40499453b02e2036cf54b7f2903953e7117 --- /dev/null +++ b/tasks/square-difference/instruction.md @@ -0,0 +1,69 @@ +# openai/math challenge `SquareDifference` (family 182) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 182 of the release, *Power savings for polynomial-difference-free sets* +(Combinatorics). The family as a whole: For every fixed intersective integer polynomial $h$ of degree $k\ge2$ with positive leading coefficient, proves that a subset of $\{1,\ldots,N\}$ avoiding nonzero values $h(1),h(2),\ldots$ as differences has size $O_h(N^{1-c_k})$, with $c_k>0$ depending only on degree. Here intersective means having a root modulo every modulus. For prime arguments, a power saving also holds when $h$ has a unit root modulo every modulus, with exponent allowed to depend on $h$. + +The challenge is `SquareDifference`, also at `/opt/openai-math/challenges/SquareDifference.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace SquareDifference + +def IsSquareDifferenceFree (A : Finset ℤ) : Prop := + ∀ a ∈ A, ∀ b ∈ A, ∀ m : ℕ, 1 ≤ m → a - b ≠ (m : ℤ) ^ 2 + +theorem power_saving : + ∃ c C : ℝ, 0 < c ∧ ∀ N : ℕ, 1 ≤ N → ∀ A : Finset ℤ, + A ⊆ Finset.Icc 1 (N : ℤ) → SquareDifference.IsSquareDifferenceFree A → + (A.card : ℝ) ≤ C * (N : ℝ) ^ (1 - c) := by + sorry + +end SquareDifference + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SquareDifference.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SquareDifference.power_saving` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/square-difference/solution/closure.txt b/tasks/square-difference/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b03ce4b6eb9d184325e2674437f546ff57c6233b --- /dev/null +++ b/tasks/square-difference/solution/closure.txt @@ -0,0 +1,81 @@ +OAI.Combinatorics.SquareDifference.ActualIntervalPair +OAI.Combinatorics.SquareDifference.AffineTuples +OAI.Combinatorics.SquareDifference.BlockAverage +OAI.Combinatorics.SquareDifference.BlockParameters +OAI.Combinatorics.SquareDifference.CRTTransfer +OAI.Combinatorics.SquareDifference.CircleDistance +OAI.Combinatorics.SquareDifference.CompleteWeights +OAI.Combinatorics.SquareDifference.ConductorBounds +OAI.Combinatorics.SquareDifference.CrossProducts +OAI.Combinatorics.SquareDifference.CyclicIndicator +OAI.Combinatorics.SquareDifference.DualCoordinates +OAI.Combinatorics.SquareDifference.Endpoint +OAI.Combinatorics.SquareDifference.EulerBudget +OAI.Combinatorics.SquareDifference.ExceptionalBasics +OAI.Combinatorics.SquareDifference.ExceptionalBudget +OAI.Combinatorics.SquareDifference.ExtendedPair +OAI.Combinatorics.SquareDifference.FiniteKernel +OAI.Combinatorics.SquareDifference.FourierLift +OAI.Combinatorics.SquareDifference.FunctionalSplit +OAI.Combinatorics.SquareDifference.GateExpansion +OAI.Combinatorics.SquareDifference.GaussSum +OAI.Combinatorics.SquareDifference.GoodPairSupport +OAI.Combinatorics.SquareDifference.InductionParameters +OAI.Combinatorics.SquareDifference.InductiveBounds +OAI.Combinatorics.SquareDifference.IntervalCoefficient +OAI.Combinatorics.SquareDifference.IntervalContraction +OAI.Combinatorics.SquareDifference.IntervalCounting +OAI.Combinatorics.SquareDifference.IntervalCrude +OAI.Combinatorics.SquareDifference.IntervalLift +OAI.Combinatorics.SquareDifference.IntervalPair +OAI.Combinatorics.SquareDifference.IntervalTransfer +OAI.Combinatorics.SquareDifference.IntervalTruncation +OAI.Combinatorics.SquareDifference.LiftMoments +OAI.Combinatorics.SquareDifference.LocalizedPair +OAI.Combinatorics.SquareDifference.LowProduct +OAI.Combinatorics.SquareDifference.Main +OAI.Combinatorics.SquareDifference.MarkedTuples +OAI.Combinatorics.SquareDifference.MatrixBounds +OAI.Combinatorics.SquareDifference.MixedCrude +OAI.Combinatorics.SquareDifference.MixedEnergy +OAI.Combinatorics.SquareDifference.MixedTransfer +OAI.Combinatorics.SquareDifference.OrderedBlock +OAI.Combinatorics.SquareDifference.OrderedGlobal +OAI.Combinatorics.SquareDifference.OrderedLow +OAI.Combinatorics.SquareDifference.OrderedRates +OAI.Combinatorics.SquareDifference.OutsideFourier +OAI.Combinatorics.SquareDifference.PairBridge +OAI.Combinatorics.SquareDifference.PhaseBounds +OAI.Combinatorics.SquareDifference.PositiveResidue +OAI.Combinatorics.SquareDifference.PowerParameters +OAI.Combinatorics.SquareDifference.PrimaryKernel +OAI.Combinatorics.SquareDifference.PrimeExtension +OAI.Combinatorics.SquareDifference.PrimeGauss +OAI.Combinatorics.SquareDifference.PrimeSetup +OAI.Combinatorics.SquareDifference.ProductBounds +OAI.Combinatorics.SquareDifference.RationalApproximation +OAI.Combinatorics.SquareDifference.RationalLift +OAI.Combinatorics.SquareDifference.ReflectionLaw +OAI.Combinatorics.SquareDifference.ResidueFourier +OAI.Combinatorics.SquareDifference.ResidueLift +OAI.Combinatorics.SquareDifference.ResidueReindex +OAI.Combinatorics.SquareDifference.RootModels +OAI.Combinatorics.SquareDifference.ScaleTransfer +OAI.Combinatorics.SquareDifference.SelectedPair +OAI.Combinatorics.SquareDifference.SelectedRoots +OAI.Combinatorics.SquareDifference.SievedFourier +OAI.Combinatorics.SquareDifference.SmallGood +OAI.Combinatorics.SquareDifference.SmallRoots +OAI.Combinatorics.SquareDifference.TensorLaw +OAI.Combinatorics.SquareDifference.TensorPair +OAI.Combinatorics.SquareDifference.TransferParameters +OAI.Combinatorics.SquareDifference.TransferRates +OAI.Combinatorics.SquareDifference.TupleEnergy +OAI.Combinatorics.SquareDifference.TupleReflection +OAI.Combinatorics.SquareDifference.TupleWeights +OAI.Combinatorics.SquareDifference.UniformBase +OAI.Combinatorics.SquareDifference.UniformInduction +OAI.Combinatorics.SquareDifference.UniformRates +OAI.Combinatorics.SquareDifference.UniformTransfer +OAI.Combinatorics.SquareDifference.WalshMoments +OAI.Combinatorics.SquareDifference.WordReflection diff --git a/tasks/square-difference/solution/reference.py b/tasks/square-difference/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/square-difference/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/square-difference/solution/solve.sh b/tasks/square-difference/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7e73fa77d34aa8123936d108ae96ec2fabdbe919 --- /dev/null +++ b/tasks/square-difference/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SquareDifference, i.e. module OAI.Combinatorics.SquareDifference.Main and the +# 81 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.SquareDifference.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SquareDifference" diff --git a/tasks/square-difference/task.toml b/tasks/square-difference/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f000fe23185d61cc34c1a1dd5b5d326d42c50e4 --- /dev/null +++ b/tasks/square-difference/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/square-difference" +version = "1.0.0" +description = "Prove SquareDifference (openai/math family 182: Power savings for polynomial-difference-free sets) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SquareDifference.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SquareDifference" +family = "182" +family_title = "Power savings for polynomial-difference-free sets" +subject = "Combinatorics" +theorems = ["OAI.SquareDifference.power_saving"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.SquareDifference.Main" +reference_modules = 81 +reference_lean_bytes = 1102925 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 978 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12692 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/square-difference/tests/Challenge.lean b/tasks/square-difference/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6c2ec26a1bd4115e08ca18aaca7a55052b0e7731 --- /dev/null +++ b/tasks/square-difference/tests/Challenge.lean @@ -0,0 +1,18 @@ +import Mathlib + +namespace OAI + +namespace SquareDifference + +def IsSquareDifferenceFree (A : Finset ℤ) : Prop := + ∀ a ∈ A, ∀ b ∈ A, ∀ m : ℕ, 1 ≤ m → a - b ≠ (m : ℤ) ^ 2 + +theorem power_saving : + ∃ c C : ℝ, 0 < c ∧ ∀ N : ℕ, 1 ≤ N → ∀ A : Finset ℤ, + A ⊆ Finset.Icc 1 (N : ℤ) → SquareDifference.IsSquareDifferenceFree A → + (A.card : ℝ) ≤ C * (N : ℝ) ^ (1 - c) := by + sorry + +end SquareDifference + +end OAI diff --git a/tasks/square-difference/tests/grade.py b/tasks/square-difference/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/square-difference/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/square-difference/tests/task.json b/tasks/square-difference/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..c3676563cbd27f7408dcc6a19d1e656a82cf6c41 --- /dev/null +++ b/tasks/square-difference/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SquareDifference", + "comparator": { + "theorem_names": [ + "OAI.SquareDifference.power_saving" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11792 +} \ No newline at end of file diff --git a/tasks/square-difference/tests/test.sh b/tasks/square-difference/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/square-difference/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/square-root-degree/environment/Dockerfile b/tasks/square-root-degree/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/square-root-degree/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/square-root-degree/environment/fetch_mathlib.sh b/tasks/square-root-degree/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/square-root-degree/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/square-root-degree/environment/lake-manifest.json b/tasks/square-root-degree/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/square-root-degree/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/square-root-degree/environment/lakefile.lean b/tasks/square-root-degree/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/square-root-degree/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/square-root-degree/environment/lean_setup.sh b/tasks/square-root-degree/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/square-root-degree/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/square-root-degree/environment/pack_submission.py b/tasks/square-root-degree/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/square-root-degree/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/square-root-degree/instruction.md b/tasks/square-root-degree/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..71b2221f02b7b4e882d933a10eec688d4cbeccc3 --- /dev/null +++ b/tasks/square-root-degree/instruction.md @@ -0,0 +1,115 @@ +# openai/math challenge `SquareRootDegree` (family 192) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 192 of the release, *A counterexample to the Gopalan–Servedio conjecture* +(Combinatorics). The family as a whole: Disproves the proposed square-root bound relating a Boolean function's linear Fourier coefficients to its polynomial degree. For every $C>0$, there is a sign-valued Boolean function $f$ with $\sum_i\widehat f(\{i\})>C\sqrt{\deg(f)}$. Thus its total signed correlation with individual input bits can exceed the proposed bound by an arbitrary factor. + +The challenge is `SquareRootDegree`, also at `/opt/openai-math/challenges/SquareRootDegree.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Bool encodes a sign: false is +1 and true is -1. The average is uniform, +and degree is ordinary real Fourier degree, not F₂ degree or threshold degree. +-/ + +open scoped BigOperators + +noncomputable section + +namespace SquareRootDegree + +abbrev Cube (ι : Type*) := ι → Bool + +def sign (b : Bool) : ℝ := if b then -1 else 1 + +def average {α : Type*} [Fintype α] (f : α → ℝ) : ℝ := + (Fintype.card α : ℝ)⁻¹ * ∑ x, f x + +def character {ι : Type*} (s : Finset ι) (x : Cube ι) : ℝ := + ∏ i ∈ s, sign (x i) + +def fourierCoeff {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) (s : Finset ι) : ℝ := by + classical + exact average (fun x => f x * character s x) + +def fourierDegree {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℕ := by + classical + exact (Finset.univ.filter (fun s : Finset ι => fourierCoeff f s ≠ 0)).sup Finset.card + +def IsBoolean {α : Type*} (f : α → ℝ) : Prop := + ∀ x, f x = -1 ∨ f x = 1 + +def Nonconstant {α : Type*} (f : α → ℝ) : Prop := + ∃ x y, f x ≠ f y + +def singletonSum {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℝ := + ∑ i, fourierCoeff f {i} + +def absoluteSingletonSum {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℝ := + ∑ i, |fourierCoeff f {i}| + +def SignedViolations : Prop := + ∀ C : ℝ, 0 < C → ∃ n : ℕ, 0 < n ∧ ∃ f : Cube (Fin n) → ℝ, + IsBoolean f ∧ Nonconstant f ∧ C * Real.sqrt (fourierDegree f) < singletonSum f + +def AbsoluteRatios : Set ℝ := + {r | ∃ n : ℕ, 0 < n ∧ ∃ f : Cube (Fin n) → ℝ, + IsBoolean f ∧ 0 < fourierDegree f ∧ + r = absoluteSingletonSum f / Real.sqrt (fourierDegree f)} + +/-- The two clauses of the literal main theorem. Unboundedness above is the +real-valued formulation of the displayed supremum being positive infinity. -/ +theorem main : SignedViolations ∧ ¬ BddAbove AbsoluteRatios := by + sorry + +end SquareRootDegree + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SquareRootDegree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SquareRootDegree.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/square-root-degree/solution/closure.txt b/tasks/square-root-degree/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..89af865f53e87e795e2c92140b825ba06b7f60c2 --- /dev/null +++ b/tasks/square-root-degree/solution/closure.txt @@ -0,0 +1,21 @@ +OAI.Combinatorics.BooleanFunctions.Amplification +OAI.Combinatorics.BooleanFunctions.Blocks +OAI.Combinatorics.BooleanFunctions.CellDegree +OAI.Combinatorics.BooleanFunctions.Conditioning +OAI.Combinatorics.BooleanFunctions.FiniteCLT +OAI.Combinatorics.BooleanFunctions.FiniteMoments +OAI.Combinatorics.BooleanFunctions.GaussianGain +OAI.Combinatorics.BooleanFunctions.Grouping +OAI.Combinatorics.BooleanFunctions.Main +OAI.Combinatorics.BooleanFunctions.MomentTransfer +OAI.Combinatorics.BooleanFunctions.Observations +OAI.Combinatorics.BooleanFunctions.Producer +OAI.Combinatorics.BooleanFunctions.Projection +OAI.Combinatorics.BooleanFunctions.Readout +OAI.Combinatorics.BooleanFunctions.ReadoutCLT +OAI.Combinatorics.BooleanFunctions.Rounding +OAI.Combinatorics.BooleanFunctions.SmoothGaussian +OAI.Combinatorics.BooleanFunctions.SmoothSelector +OAI.Combinatorics.BooleanFunctions.SoftEvent +OAI.Combinatorics.BooleanFunctions.Switching +OAI.Combinatorics.BooleanFunctions.Walsh diff --git a/tasks/square-root-degree/solution/reference.py b/tasks/square-root-degree/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/square-root-degree/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/square-root-degree/solution/solve.sh b/tasks/square-root-degree/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4b7041563fb8dc923357f83cdc3ce87236646fe3 --- /dev/null +++ b/tasks/square-root-degree/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SquareRootDegree, i.e. module OAI.Combinatorics.BooleanFunctions.Main and the +# 21 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.BooleanFunctions.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SquareRootDegree" diff --git a/tasks/square-root-degree/task.toml b/tasks/square-root-degree/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..de9da0aa810cb87569c0369b32cb240e5b7da09a --- /dev/null +++ b/tasks/square-root-degree/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/square-root-degree" +version = "1.0.0" +description = "Prove SquareRootDegree (openai/math family 192: A counterexample to the Gopalan–Servedio conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SquareRootDegree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SquareRootDegree" +family = "192" +family_title = "A counterexample to the Gopalan–Servedio conjecture" +subject = "Combinatorics" +theorems = ["OAI.SquareRootDegree.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.BooleanFunctions.Main" +reference_modules = 21 +reference_lean_bytes = 158632 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 316 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11842 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/square-root-degree/tests/Challenge.lean b/tasks/square-root-degree/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ff65933e4d424357a4c233ad4a215049a80f0757 --- /dev/null +++ b/tasks/square-root-degree/tests/Challenge.lean @@ -0,0 +1,64 @@ +import Mathlib + +namespace OAI + +/-! +Bool encodes a sign: false is +1 and true is -1. The average is uniform, +and degree is ordinary real Fourier degree, not F₂ degree or threshold degree. +-/ + +open scoped BigOperators + +noncomputable section + +namespace SquareRootDegree + +abbrev Cube (ι : Type*) := ι → Bool + +def sign (b : Bool) : ℝ := if b then -1 else 1 + +def average {α : Type*} [Fintype α] (f : α → ℝ) : ℝ := + (Fintype.card α : ℝ)⁻¹ * ∑ x, f x + +def character {ι : Type*} (s : Finset ι) (x : Cube ι) : ℝ := + ∏ i ∈ s, sign (x i) + +def fourierCoeff {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) (s : Finset ι) : ℝ := by + classical + exact average (fun x => f x * character s x) + +def fourierDegree {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℕ := by + classical + exact (Finset.univ.filter (fun s : Finset ι => fourierCoeff f s ≠ 0)).sup Finset.card + +def IsBoolean {α : Type*} (f : α → ℝ) : Prop := + ∀ x, f x = -1 ∨ f x = 1 + +def Nonconstant {α : Type*} (f : α → ℝ) : Prop := + ∃ x y, f x ≠ f y + +def singletonSum {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℝ := + ∑ i, fourierCoeff f {i} + +def absoluteSingletonSum {ι : Type*} [Fintype ι] (f : Cube ι → ℝ) : ℝ := + ∑ i, |fourierCoeff f {i}| + +def SignedViolations : Prop := + ∀ C : ℝ, 0 < C → ∃ n : ℕ, 0 < n ∧ ∃ f : Cube (Fin n) → ℝ, + IsBoolean f ∧ Nonconstant f ∧ C * Real.sqrt (fourierDegree f) < singletonSum f + +def AbsoluteRatios : Set ℝ := + {r | ∃ n : ℕ, 0 < n ∧ ∃ f : Cube (Fin n) → ℝ, + IsBoolean f ∧ 0 < fourierDegree f ∧ + r = absoluteSingletonSum f / Real.sqrt (fourierDegree f)} + +/-- The two clauses of the literal main theorem. Unboundedness above is the +real-valued formulation of the displayed supremum being positive infinity. -/ +theorem main : SignedViolations ∧ ¬ BddAbove AbsoluteRatios := by + sorry + +end SquareRootDegree + +end + +end OAI diff --git a/tasks/square-root-degree/tests/grade.py b/tasks/square-root-degree/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/square-root-degree/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/square-root-degree/tests/task.json b/tasks/square-root-degree/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4cf7cd3aa82b28fd4190f88923d2c1bb40775bbe --- /dev/null +++ b/tasks/square-root-degree/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SquareRootDegree", + "comparator": { + "theorem_names": [ + "OAI.SquareRootDegree.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10942 +} \ No newline at end of file diff --git a/tasks/square-root-degree/tests/test.sh b/tasks/square-root-degree/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/square-root-degree/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/standard-map-entropy/environment/Dockerfile b/tasks/standard-map-entropy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/standard-map-entropy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/standard-map-entropy/environment/fetch_mathlib.sh b/tasks/standard-map-entropy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/standard-map-entropy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/standard-map-entropy/environment/lake-manifest.json b/tasks/standard-map-entropy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/standard-map-entropy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/standard-map-entropy/environment/lakefile.lean b/tasks/standard-map-entropy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/standard-map-entropy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/standard-map-entropy/environment/lean_setup.sh b/tasks/standard-map-entropy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/standard-map-entropy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/standard-map-entropy/environment/pack_submission.py b/tasks/standard-map-entropy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/standard-map-entropy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/standard-map-entropy/instruction.md b/tasks/standard-map-entropy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4b7bcc2a333f3b0c572174716204460307420cd1 --- /dev/null +++ b/tasks/standard-map-entropy/instruction.md @@ -0,0 +1,104 @@ +# openai/math challenge `StandardMapEntropy` (family 146) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 146 of the release, *Sinai's positive-entropy conjecture for the standard map* +(Dynamical systems and ergodic theory). The family as a whole: Proves that the standard sine map on the two-dimensional torus has positive metric entropy with respect to area for every sufficiently large positive parameter. This establishes Sinai's positive-parameter-measure conjecture for the original family, with the stronger conclusion of a full parameter tail. + +The challenge is `StandardMapEntropy`, also at `/opt/openai-math/challenges/StandardMapEntropy.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory Set +open scoped ENNReal BigOperators + +namespace StandardMapEntropy + +abbrev Circle := AddCircle (1 : ℝ) +abbrev Torus := Circle × Circle + +lemma sine_periodic : Function.Periodic (fun x : ℝ => Real.sin (2 * Real.pi * x)) 1 := by + intro x + dsimp only + rw [show 2 * Real.pi * (x + 1) = 2 * Real.pi * x + 2 * Real.pi by ring] + exact Real.sin_add_two_pi _ + +noncomputable def sine (x : Circle) : ℝ := sine_periodic.lift x + +noncomputable def standardMap (k : ℝ) (z : Torus) : Torus := + (z.1 + z.2 + (k * sine z.1 : ℝ), z.2 + (k * sine z.1 : ℝ)) + +noncomputable def area : Measure Torus := + (volume : Measure Circle).prod (volume : Measure Circle) + +def FinitePartition (r : ℕ) := { p : Torus → Fin (r + 1) // Measurable p } + +def blockAtom {r : ℕ} (f : Torus → Torus) (p : FinitePartition r) + (n : ℕ) (w : Fin n → Fin (r + 1)) : Set Torus := + { z | ∀ i : Fin n, p.val (f^[i.val] z) = w i } + +noncomputable def blockEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) (n : ℕ) : ℝ := + - ∑ w : Fin n → Fin (r + 1), + (μ (blockAtom f p n w)).toReal * Real.log (μ (blockAtom f p n w)).toReal + +noncomputable def partitionEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (blockEntropy μ f p (n + 1) / (n + 1 : ℝ)) + +noncomputable def metricEntropy (μ : Measure Torus) (f : Torus → Torus) : ℝ≥0∞ := + ⨆ r : ℕ, ⨆ p : FinitePartition r, partitionEntropy μ f p + +def MainObligation : Prop := + ∃ k₀ : ℝ, 0 < k₀ ∧ ∀ k : ℝ, k₀ ≤ k → 0 < metricEntropy area (standardMap k) + +theorem main_entropy : MainObligation := by + sorry + +end StandardMapEntropy + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StandardMapEntropy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StandardMapEntropy.main_entropy` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/standard-map-entropy/solution/closure.txt b/tasks/standard-map-entropy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..de0d9b2c0325f09840da0f78f05baaf87fcbdb64 --- /dev/null +++ b/tasks/standard-map-entropy/solution/closure.txt @@ -0,0 +1,205 @@ +OAI.Dynamics.StandardMap.ActualBackwardCarry +OAI.Dynamics.StandardMap.ArrayActions +OAI.Dynamics.StandardMap.ArrayAffinity +OAI.Dynamics.StandardMap.ArrayGrid +OAI.Dynamics.StandardMap.ArrayHalf +OAI.Dynamics.StandardMap.ArrayLimitSupport +OAI.Dynamics.StandardMap.ArrayMoments +OAI.Dynamics.StandardMap.ArrayTestCover +OAI.Dynamics.StandardMap.ArrayTests +OAI.Dynamics.StandardMap.ArrayTopology +OAI.Dynamics.StandardMap.BackwardSlice +OAI.Dynamics.StandardMap.BandCap +OAI.Dynamics.StandardMap.BandCoboundary +OAI.Dynamics.StandardMap.BandComparison +OAI.Dynamics.StandardMap.BandFlux +OAI.Dynamics.StandardMap.BandGeometry +OAI.Dynamics.StandardMap.BandIntensity +OAI.Dynamics.StandardMap.BandSeries +OAI.Dynamics.StandardMap.BiCocycle +OAI.Dynamics.StandardMap.BridgeAggregate +OAI.Dynamics.StandardMap.BridgeAveraging +OAI.Dynamics.StandardMap.BridgeCritical +OAI.Dynamics.StandardMap.BridgeDecay +OAI.Dynamics.StandardMap.BridgeDirichlet +OAI.Dynamics.StandardMap.BridgeEligibility +OAI.Dynamics.StandardMap.BridgeExclusions +OAI.Dynamics.StandardMap.BridgeExist +OAI.Dynamics.StandardMap.BridgeGrid +OAI.Dynamics.StandardMap.BridgeKernel +OAI.Dynamics.StandardMap.BridgeLinear +OAI.Dynamics.StandardMap.BridgeMean +OAI.Dynamics.StandardMap.BridgeNonlinear +OAI.Dynamics.StandardMap.BridgePattern +OAI.Dynamics.StandardMap.BridgeRealBound +OAI.Dynamics.StandardMap.BridgeSamples +OAI.Dynamics.StandardMap.BridgeScalar +OAI.Dynamics.StandardMap.BridgeScalars +OAI.Dynamics.StandardMap.BridgeVague +OAI.Dynamics.StandardMap.BridgeWeights +OAI.Dynamics.StandardMap.CancellationArea +OAI.Dynamics.StandardMap.CancellationScalar +OAI.Dynamics.StandardMap.CancellationTheorem +OAI.Dynamics.StandardMap.CancellationVector +OAI.Dynamics.StandardMap.CappedPrelimit +OAI.Dynamics.StandardMap.CappedTests +OAI.Dynamics.StandardMap.ChangeVariablesBounds +OAI.Dynamics.StandardMap.ClippedTests +OAI.Dynamics.StandardMap.ClosedEligibility +OAI.Dynamics.StandardMap.CocycleAlgebra +OAI.Dynamics.StandardMap.CompactRelabeling +OAI.Dynamics.StandardMap.ConeGrowth +OAI.Dynamics.StandardMap.ContractingGraphPack +OAI.Dynamics.StandardMap.CosineNull +OAI.Dynamics.StandardMap.CoverContraction +OAI.Dynamics.StandardMap.CriticalLaws +OAI.Dynamics.StandardMap.CriticalLimits +OAI.Dynamics.StandardMap.CriticalScales +OAI.Dynamics.StandardMap.CriticalSequence +OAI.Dynamics.StandardMap.CurveCellIntegral +OAI.Dynamics.StandardMap.CurveCharts +OAI.Dynamics.StandardMap.CurveColumns +OAI.Dynamics.StandardMap.CurveCompose +OAI.Dynamics.StandardMap.CurveCore +OAI.Dynamics.StandardMap.CurveIntegral +OAI.Dynamics.StandardMap.CurveIterate +OAI.Dynamics.StandardMap.CurveLift +OAI.Dynamics.StandardMap.CurveLineIntegral +OAI.Dynamics.StandardMap.CurveOneStep +OAI.Dynamics.StandardMap.CurveSubdivision +OAI.Dynamics.StandardMap.DirichletOrbit +OAI.Dynamics.StandardMap.DoublingPointwise +OAI.Dynamics.StandardMap.DyadicArrays +OAI.Dynamics.StandardMap.EndpointActions +OAI.Dynamics.StandardMap.EndpointClasses +OAI.Dynamics.StandardMap.EndpointCompact +OAI.Dynamics.StandardMap.EndpointCovariance +OAI.Dynamics.StandardMap.EndpointDefinition +OAI.Dynamics.StandardMap.EndpointIntensity +OAI.Dynamics.StandardMap.EndpointMatching +OAI.Dynamics.StandardMap.EndpointObservations +OAI.Dynamics.StandardMap.EndpointShapes +OAI.Dynamics.StandardMap.EndpointTransport +OAI.Dynamics.StandardMap.EntropyConjugacy +OAI.Dynamics.StandardMap.EntropyEndpoint +OAI.Dynamics.StandardMap.EntropyIntegral +OAI.Dynamics.StandardMap.EntropyParameters +OAI.Dynamics.StandardMap.FastBridge +OAI.Dynamics.StandardMap.FineArrays +OAI.Dynamics.StandardMap.FineMoments +OAI.Dynamics.StandardMap.FixedDeficit +OAI.Dynamics.StandardMap.FixedPointContinuity +OAI.Dynamics.StandardMap.FixedPointFamily +OAI.Dynamics.StandardMap.ForwardChart +OAI.Dynamics.StandardMap.FourPoint +OAI.Dynamics.StandardMap.GoodCount +OAI.Dynamics.StandardMap.GraphCalculus +OAI.Dynamics.StandardMap.GraphDerivativeUpgrade +OAI.Dynamics.StandardMap.GraphDistortion +OAI.Dynamics.StandardMap.GraphFamilySmooth +OAI.Dynamics.StandardMap.GraphJacobians +OAI.Dynamics.StandardMap.GraphParameterContinuity +OAI.Dynamics.StandardMap.GraphSubsetCalculus +OAI.Dynamics.StandardMap.GraphUniqueness +OAI.Dynamics.StandardMap.GridAtomBound +OAI.Dynamics.StandardMap.GridBridge +OAI.Dynamics.StandardMap.GridPartition +OAI.Dynamics.StandardMap.GridWordIntegrals +OAI.Dynamics.StandardMap.HalfDecomposition +OAI.Dynamics.StandardMap.IntensityBounds +OAI.Dynamics.StandardMap.JointGraphFamily +OAI.Dynamics.StandardMap.LiftDynamics +OAI.Dynamics.StandardMap.LiftEventMeasure +OAI.Dynamics.StandardMap.LimitActions +OAI.Dynamics.StandardMap.LimitBalance +OAI.Dynamics.StandardMap.LimitBridge +OAI.Dynamics.StandardMap.LimitCancellation +OAI.Dynamics.StandardMap.LimitMoments +OAI.Dynamics.StandardMap.LocalMidpointAffine +OAI.Dynamics.StandardMap.LocalMidpointGrid +OAI.Dynamics.StandardMap.LocalScarcity +OAI.Dynamics.StandardMap.LocalSquareBridge +OAI.Dynamics.StandardMap.LocalTestDetection +OAI.Dynamics.StandardMap.LogDerivativeCore +OAI.Dynamics.StandardMap.ManyGood +OAI.Dynamics.StandardMap.MatchingAssembly +OAI.Dynamics.StandardMap.MatchingCore +OAI.Dynamics.StandardMap.MatchingQuantitative +OAI.Dynamics.StandardMap.MeanCancellation +OAI.Dynamics.StandardMap.MeanDeficit +OAI.Dynamics.StandardMap.MeanGrowth +OAI.Dynamics.StandardMap.MiddleCount +OAI.Dynamics.StandardMap.MiddleObservationBridge +OAI.Dynamics.StandardMap.MiddlePrefixBridge +OAI.Dynamics.StandardMap.NoCriticalSequence +OAI.Dynamics.StandardMap.NonaffineLimits +OAI.Dynamics.StandardMap.NonlinearDirichlet +OAI.Dynamics.StandardMap.ObservationExponential +OAI.Dynamics.StandardMap.ObservationTransport +OAI.Dynamics.StandardMap.OneRayZero +OAI.Dynamics.StandardMap.PatternCount +OAI.Dynamics.StandardMap.PatternDecay +OAI.Dynamics.StandardMap.PlaneGeometry +OAI.Dynamics.StandardMap.PlaneTransfer +OAI.Dynamics.StandardMap.ProductDistances +OAI.Dynamics.StandardMap.ProductSum +OAI.Dynamics.StandardMap.RealArrays +OAI.Dynamics.StandardMap.RealBridge +OAI.Dynamics.StandardMap.RealCancellation +OAI.Dynamics.StandardMap.RealScarcityCover +OAI.Dynamics.StandardMap.RecenteredGraphs +OAI.Dynamics.StandardMap.RemainderCap +OAI.Dynamics.StandardMap.RemainderLaws +OAI.Dynamics.StandardMap.RescaledArrays +OAI.Dynamics.StandardMap.SampleLaws +OAI.Dynamics.StandardMap.ScaleAction +OAI.Dynamics.StandardMap.ScaleCancellation +OAI.Dynamics.StandardMap.ScaleEndpoints +OAI.Dynamics.StandardMap.ScaleEvaluation +OAI.Dynamics.StandardMap.ScaleLaws +OAI.Dynamics.StandardMap.ScaleTelescopes +OAI.Dynamics.StandardMap.ScaleTestBounds +OAI.Dynamics.StandardMap.ScaleTruncation +OAI.Dynamics.StandardMap.ScaledChart +OAI.Dynamics.StandardMap.ScaledContraction +OAI.Dynamics.StandardMap.SegmentObservations +OAI.Dynamics.StandardMap.ShapeClassification +OAI.Dynamics.StandardMap.ShapeComponents +OAI.Dynamics.StandardMap.ShapeCore +OAI.Dynamics.StandardMap.ShapeLimit +OAI.Dynamics.StandardMap.ShapeTopology +OAI.Dynamics.StandardMap.SliceCancellation +OAI.Dynamics.StandardMap.SmoothCap +OAI.Dynamics.StandardMap.SmoothControl +OAI.Dynamics.StandardMap.StablePrefix +OAI.Dynamics.StandardMap.StrictGraphCalculus +OAI.Dynamics.StandardMap.SweepSlice +OAI.Dynamics.StandardMap.TerminalCap +OAI.Dynamics.StandardMap.TerminalShortfall +OAI.Dynamics.StandardMap.TerminalStrict +OAI.Dynamics.StandardMap.TestObservations +OAI.Dynamics.StandardMap.TorusDynamics +OAI.Dynamics.StandardMap.TorusIntegral +OAI.Dynamics.StandardMap.TorusObservations +OAI.Dynamics.StandardMap.TransferCore +OAI.Dynamics.StandardMap.TransportCarry +OAI.Dynamics.StandardMap.TransportGraphs +OAI.Dynamics.StandardMap.TransverseSweep +OAI.Dynamics.StandardMap.TreeAffine +OAI.Dynamics.StandardMap.TreeLine +OAI.Dynamics.StandardMap.TreeLocalAffine +OAI.Dynamics.StandardMap.TruncationArrays +OAI.Dynamics.StandardMap.VagueBounds +OAI.Dynamics.StandardMap.VagueLimits +OAI.Dynamics.StandardMap.VagueSupport +OAI.Dynamics.StandardMap.VariedDirichlet +OAI.Dynamics.StandardMap.VectorGrowth +OAI.Dynamics.StandardMap.WeightBalance +OAI.Dynamics.StandardMap.WeightBridge +OAI.Dynamics.StandardMap.WeightIdentification +OAI.Dynamics.StandardMap.WeightSlow +OAI.Dynamics.StandardMap.WeightTruncation +OAI.Dynamics.StandardMap.WeightUnit +OAI.Dynamics.StandardMap.WeightedChart +OAI.Dynamics.StandardMap.WeightedCompact +OAI.Dynamics.StandardMap.WeightedStability diff --git a/tasks/standard-map-entropy/solution/reference.py b/tasks/standard-map-entropy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/standard-map-entropy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/standard-map-entropy/solution/solve.sh b/tasks/standard-map-entropy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5fd9f9e24a6ae8030e9b812ff2bb9c493d848913 --- /dev/null +++ b/tasks/standard-map-entropy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StandardMapEntropy, i.e. module OAI.Dynamics.StandardMap.EntropyEndpoint and the +# 205 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.StandardMap.EntropyEndpoint /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StandardMapEntropy" diff --git a/tasks/standard-map-entropy/task.toml b/tasks/standard-map-entropy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d50d9574950d303a75d7db7421e204f8573c88f6 --- /dev/null +++ b/tasks/standard-map-entropy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/standard-map-entropy" +version = "1.0.0" +description = "Prove StandardMapEntropy (openai/math family 146: Sinai's positive-entropy conjecture for the standard map) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StandardMapEntropy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StandardMapEntropy" +family = "146" +family_title = "Sinai's positive-entropy conjecture for the standard map" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.StandardMapEntropy.main_entropy"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.StandardMap.EntropyEndpoint" +reference_modules = 205 +reference_lean_bytes = 1320589 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1548 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12888 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/standard-map-entropy/tests/Challenge.lean b/tasks/standard-map-entropy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d87b5c1ace865734db169f7fc97c205eff124e2f --- /dev/null +++ b/tasks/standard-map-entropy/tests/Challenge.lean @@ -0,0 +1,53 @@ +import Mathlib + +namespace OAI + +open MeasureTheory Set +open scoped ENNReal BigOperators + +namespace StandardMapEntropy + +abbrev Circle := AddCircle (1 : ℝ) +abbrev Torus := Circle × Circle + +lemma sine_periodic : Function.Periodic (fun x : ℝ => Real.sin (2 * Real.pi * x)) 1 := by + intro x + dsimp only + rw [show 2 * Real.pi * (x + 1) = 2 * Real.pi * x + 2 * Real.pi by ring] + exact Real.sin_add_two_pi _ + +noncomputable def sine (x : Circle) : ℝ := sine_periodic.lift x + +noncomputable def standardMap (k : ℝ) (z : Torus) : Torus := + (z.1 + z.2 + (k * sine z.1 : ℝ), z.2 + (k * sine z.1 : ℝ)) + +noncomputable def area : Measure Torus := + (volume : Measure Circle).prod (volume : Measure Circle) + +def FinitePartition (r : ℕ) := { p : Torus → Fin (r + 1) // Measurable p } + +def blockAtom {r : ℕ} (f : Torus → Torus) (p : FinitePartition r) + (n : ℕ) (w : Fin n → Fin (r + 1)) : Set Torus := + { z | ∀ i : Fin n, p.val (f^[i.val] z) = w i } + +noncomputable def blockEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) (n : ℕ) : ℝ := + - ∑ w : Fin n → Fin (r + 1), + (μ (blockAtom f p n w)).toReal * Real.log (μ (blockAtom f p n w)).toReal + +noncomputable def partitionEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (blockEntropy μ f p (n + 1) / (n + 1 : ℝ)) + +noncomputable def metricEntropy (μ : Measure Torus) (f : Torus → Torus) : ℝ≥0∞ := + ⨆ r : ℕ, ⨆ p : FinitePartition r, partitionEntropy μ f p + +def MainObligation : Prop := + ∃ k₀ : ℝ, 0 < k₀ ∧ ∀ k : ℝ, k₀ ≤ k → 0 < metricEntropy area (standardMap k) + +theorem main_entropy : MainObligation := by + sorry + +end StandardMapEntropy + +end OAI diff --git a/tasks/standard-map-entropy/tests/grade.py b/tasks/standard-map-entropy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/standard-map-entropy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/standard-map-entropy/tests/task.json b/tasks/standard-map-entropy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..bb87b7f95c39852b06143f81fc7fd5d5e482ef9d --- /dev/null +++ b/tasks/standard-map-entropy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "StandardMapEntropy", + "comparator": { + "theorem_names": [ + "OAI.StandardMapEntropy.main_entropy" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11988 +} \ No newline at end of file diff --git a/tasks/standard-map-entropy/tests/test.sh b/tasks/standard-map-entropy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/standard-map-entropy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/standard-map-lyapunov/environment/Dockerfile b/tasks/standard-map-lyapunov/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/standard-map-lyapunov/environment/fetch_mathlib.sh b/tasks/standard-map-lyapunov/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/standard-map-lyapunov/environment/lake-manifest.json b/tasks/standard-map-lyapunov/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/standard-map-lyapunov/environment/lakefile.lean b/tasks/standard-map-lyapunov/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/standard-map-lyapunov/environment/lean_setup.sh b/tasks/standard-map-lyapunov/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/standard-map-lyapunov/environment/pack_submission.py b/tasks/standard-map-lyapunov/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/standard-map-lyapunov/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/standard-map-lyapunov/instruction.md b/tasks/standard-map-lyapunov/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..6705218a3ec941ff8b9169435cb8a4f4bf1f9746 --- /dev/null +++ b/tasks/standard-map-lyapunov/instruction.md @@ -0,0 +1,161 @@ +# openai/math challenge `StandardMapLyapunov` (family 146) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 146 of the release, *Sinai's positive-entropy conjecture for the standard map* +(Dynamical systems and ergodic theory). The family as a whole: Proves that the standard sine map on the two-dimensional torus has positive metric entropy with respect to area for every sufficiently large positive parameter. This establishes Sinai's positive-parameter-measure conjecture for the original family, with the stronger conclusion of a full parameter tail. + +The challenge is `StandardMapLyapunov`, also at `/opt/openai-math/challenges/StandardMapLyapunov.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory Set Filter +open scoped ENNReal BigOperators Topology + +namespace StandardMapEntropy + +abbrev Circle := AddCircle (1 : ℝ) +abbrev Torus := Circle × Circle + +lemma sine_periodic : Function.Periodic (fun x : ℝ => Real.sin (2 * Real.pi * x)) 1 := by + intro x + dsimp only + rw [show 2 * Real.pi * (x + 1) = 2 * Real.pi * x + 2 * Real.pi by ring] + exact Real.sin_add_two_pi _ + +noncomputable def sine (x : Circle) : ℝ := sine_periodic.lift x + +noncomputable def standardMap (k : ℝ) (z : Torus) : Torus := + (z.1 + z.2 + (k * sine z.1 : ℝ), z.2 + (k * sine z.1 : ℝ)) + +noncomputable def area : Measure Torus := + (volume : Measure Circle).prod (volume : Measure Circle) + +def FinitePartition (r : ℕ) := { p : Torus → Fin (r + 1) // Measurable p } + +def blockAtom {r : ℕ} (f : Torus → Torus) (p : FinitePartition r) + (n : ℕ) (w : Fin n → Fin (r + 1)) : Set Torus := + { z | ∀ i : Fin n, p.val (f^[i.val] z) = w i } + +noncomputable def blockEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) (n : ℕ) : ℝ := + - ∑ w : Fin n → Fin (r + 1), + (μ (blockAtom f p n w)).toReal * Real.log (μ (blockAtom f p n w)).toReal + +noncomputable def partitionEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (blockEntropy μ f p (n + 1) / (n + 1 : ℝ)) + +noncomputable def metricEntropy (μ : Measure Torus) (f : Torus → Torus) : ℝ≥0∞ := + ⨆ r : ℕ, ⨆ p : FinitePartition r, partitionEntropy μ f p + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +lemma cosine_periodic : Function.Periodic (fun x : ℝ => Real.cos (2*Real.pi*x)) 1 := by + intro x + dsimp only + rw [show 2*Real.pi*(x+1)=2*Real.pi*x+2*Real.pi by ring] + exact Real.cos_add_two_pi _ +noncomputable def cosine (x : Circle) : ℝ := cosine_periodic.lift x + +noncomputable def torusPotential (k : ℝ) (x : Circle) : ℝ := 2+(2*Real.pi*k)*cosine x + +noncomputable def transferStep (v : ℝ) : ℂ →L[ℝ] ℂ := + { toLinearMap := + { toFun := fun z => ⟨v*z.re-z.im,z.re⟩ + map_add' := by intro z w; apply Complex.ext <;> simp; ring + map_smul' := by intro t z; apply Complex.ext <;> simp; ring } + cont := by + exact Complex.equivRealProdCLM.symm.continuous.comp + (((continuous_const.mul Complex.continuous_re).sub Complex.continuous_im).prodMk Complex.continuous_re) } + +noncomputable def tangentCoordinates : ℂ →L[ℝ] ℂ := + { toLinearMap := + { toFun := fun z => ⟨z.re, z.re-z.im⟩ + map_add' := by intro z w; apply Complex.ext <;> simp; ring + map_smul' := by intro t z; apply Complex.ext <;> simp; ring } + cont := Complex.equivRealProdCLM.symm.continuous.comp + (Complex.continuous_re.prodMk (Complex.continuous_re.sub Complex.continuous_im)) } + +local instance realTangentCompTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +noncomputable def standardDerivative (k : ℝ) (z : Torus) : ℂ →L[ℝ] ℂ := + tangentCoordinates.comp ((transferStep (torusPotential k z.1)).comp tangentCoordinates) + +noncomputable def standardDerivativeProduct (k : ℝ) (z : Torus) (n : ℕ) : ℂ →L[ℝ] ℂ := + Nat.rec (ContinuousLinearMap.id ℝ ℂ) + (fun i A => (standardDerivative k ((standardMap k)^[i] z)).comp A) n + +noncomputable def wedge (z w : ℂ) : ℝ := z.re * w.im - z.im * w.re + +def VectorGrowth (k : ℝ) (z : Torus) (v : ℂ) (l : ℝ) : Prop := + v ≠ 0 ∧ Tendsto (fun n : ℕ => Real.log ‖standardDerivativeProduct k z n v‖ / (n : ℝ)) + atTop (𝓝 l) + +def LyapunovSpectrumAt (k : ℝ) (z : Torus) (l : ℝ) : Prop := + 0 ≤ l ∧ ((l = 0 ∧ ∀ v : ℂ, v ≠ 0 → VectorGrowth k z v 0) ∨ + (0 < l ∧ ∃ s : ℂ, s ≠ 0 ∧ ∀ v : ℂ, v ≠ 0 → + VectorGrowth k z v (if wedge s v = 0 then -l else l))) + +def PositiveLargestLyapunov (k : ℝ) : Prop := + ∃ E : Set Torus, MeasurableSet E ∧ 0 < area E ∧ + ∀ z ∈ E, ∃ l : ℝ, 0 < l ∧ LyapunovSpectrumAt k z l ∧ + Tendsto + (fun n : ℕ => Real.log ‖standardDerivativeProduct k z n‖ / (n : ℝ)) + atTop (𝓝 l) + +theorem main_entropy_complete : + ∃ k₀ : ℝ, 0 < k₀ ∧ ∀ k : ℝ, k₀ ≤ k → + 0 < metricEntropy area (standardMap k) ∧ + PositiveLargestLyapunov k ∧ + (0 < metricEntropy area (standardMap k) ↔ PositiveLargestLyapunov k) := by + sorry + +end StandardMapEntropy + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StandardMapLyapunov.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StandardMapEntropy.main_entropy_complete` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/standard-map-lyapunov/solution/closure.txt b/tasks/standard-map-lyapunov/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cfc3e586b6d02b1e5f008a37d5d45d922fb5c4a5 --- /dev/null +++ b/tasks/standard-map-lyapunov/solution/closure.txt @@ -0,0 +1,211 @@ +OAI.Dynamics.StandardMap.ActualBackwardCarry +OAI.Dynamics.StandardMap.ArrayActions +OAI.Dynamics.StandardMap.ArrayAffinity +OAI.Dynamics.StandardMap.ArrayGrid +OAI.Dynamics.StandardMap.ArrayHalf +OAI.Dynamics.StandardMap.ArrayLimitSupport +OAI.Dynamics.StandardMap.ArrayMoments +OAI.Dynamics.StandardMap.ArrayTestCover +OAI.Dynamics.StandardMap.ArrayTests +OAI.Dynamics.StandardMap.ArrayTopology +OAI.Dynamics.StandardMap.BackwardSlice +OAI.Dynamics.StandardMap.BandCap +OAI.Dynamics.StandardMap.BandCoboundary +OAI.Dynamics.StandardMap.BandComparison +OAI.Dynamics.StandardMap.BandFlux +OAI.Dynamics.StandardMap.BandGeometry +OAI.Dynamics.StandardMap.BandIntensity +OAI.Dynamics.StandardMap.BandSeries +OAI.Dynamics.StandardMap.BiCocycle +OAI.Dynamics.StandardMap.BridgeAggregate +OAI.Dynamics.StandardMap.BridgeAveraging +OAI.Dynamics.StandardMap.BridgeCritical +OAI.Dynamics.StandardMap.BridgeDecay +OAI.Dynamics.StandardMap.BridgeDirichlet +OAI.Dynamics.StandardMap.BridgeEligibility +OAI.Dynamics.StandardMap.BridgeExclusions +OAI.Dynamics.StandardMap.BridgeExist +OAI.Dynamics.StandardMap.BridgeGrid +OAI.Dynamics.StandardMap.BridgeKernel +OAI.Dynamics.StandardMap.BridgeLinear +OAI.Dynamics.StandardMap.BridgeMean +OAI.Dynamics.StandardMap.BridgeNonlinear +OAI.Dynamics.StandardMap.BridgePattern +OAI.Dynamics.StandardMap.BridgeRealBound +OAI.Dynamics.StandardMap.BridgeSamples +OAI.Dynamics.StandardMap.BridgeScalar +OAI.Dynamics.StandardMap.BridgeScalars +OAI.Dynamics.StandardMap.BridgeVague +OAI.Dynamics.StandardMap.BridgeWeights +OAI.Dynamics.StandardMap.CancellationArea +OAI.Dynamics.StandardMap.CancellationScalar +OAI.Dynamics.StandardMap.CancellationTheorem +OAI.Dynamics.StandardMap.CancellationVector +OAI.Dynamics.StandardMap.CappedPrelimit +OAI.Dynamics.StandardMap.CappedTests +OAI.Dynamics.StandardMap.ChangeVariablesBounds +OAI.Dynamics.StandardMap.ClippedTests +OAI.Dynamics.StandardMap.ClosedEligibility +OAI.Dynamics.StandardMap.CocycleAlgebra +OAI.Dynamics.StandardMap.CompactRelabeling +OAI.Dynamics.StandardMap.ConeGrowth +OAI.Dynamics.StandardMap.ContractingGraphPack +OAI.Dynamics.StandardMap.CosineNull +OAI.Dynamics.StandardMap.CoverContraction +OAI.Dynamics.StandardMap.CriticalLaws +OAI.Dynamics.StandardMap.CriticalLimits +OAI.Dynamics.StandardMap.CriticalScales +OAI.Dynamics.StandardMap.CriticalSequence +OAI.Dynamics.StandardMap.CurveCellIntegral +OAI.Dynamics.StandardMap.CurveCharts +OAI.Dynamics.StandardMap.CurveColumns +OAI.Dynamics.StandardMap.CurveCompose +OAI.Dynamics.StandardMap.CurveCore +OAI.Dynamics.StandardMap.CurveIntegral +OAI.Dynamics.StandardMap.CurveIterate +OAI.Dynamics.StandardMap.CurveLift +OAI.Dynamics.StandardMap.CurveLineIntegral +OAI.Dynamics.StandardMap.CurveOneStep +OAI.Dynamics.StandardMap.CurveSubdivision +OAI.Dynamics.StandardMap.DirichletOrbit +OAI.Dynamics.StandardMap.DoublingPointwise +OAI.Dynamics.StandardMap.DyadicArrays +OAI.Dynamics.StandardMap.EndpointActions +OAI.Dynamics.StandardMap.EndpointClasses +OAI.Dynamics.StandardMap.EndpointCompact +OAI.Dynamics.StandardMap.EndpointCovariance +OAI.Dynamics.StandardMap.EndpointDefinition +OAI.Dynamics.StandardMap.EndpointIntensity +OAI.Dynamics.StandardMap.EndpointMatching +OAI.Dynamics.StandardMap.EndpointObservations +OAI.Dynamics.StandardMap.EndpointShapes +OAI.Dynamics.StandardMap.EndpointTransport +OAI.Dynamics.StandardMap.EntropyConjugacy +OAI.Dynamics.StandardMap.EntropyEndpoint +OAI.Dynamics.StandardMap.EntropyIntegral +OAI.Dynamics.StandardMap.EntropyLyapunov +OAI.Dynamics.StandardMap.EntropyParameters +OAI.Dynamics.StandardMap.FastBridge +OAI.Dynamics.StandardMap.FineArrays +OAI.Dynamics.StandardMap.FineMoments +OAI.Dynamics.StandardMap.FixedDeficit +OAI.Dynamics.StandardMap.FixedPointContinuity +OAI.Dynamics.StandardMap.FixedPointFamily +OAI.Dynamics.StandardMap.ForwardChart +OAI.Dynamics.StandardMap.FourPoint +OAI.Dynamics.StandardMap.GoodCount +OAI.Dynamics.StandardMap.GraphCalculus +OAI.Dynamics.StandardMap.GraphDerivativeUpgrade +OAI.Dynamics.StandardMap.GraphDistortion +OAI.Dynamics.StandardMap.GraphFamilySmooth +OAI.Dynamics.StandardMap.GraphJacobians +OAI.Dynamics.StandardMap.GraphParameterContinuity +OAI.Dynamics.StandardMap.GraphSubsetCalculus +OAI.Dynamics.StandardMap.GraphUniqueness +OAI.Dynamics.StandardMap.GridAtomBound +OAI.Dynamics.StandardMap.GridBridge +OAI.Dynamics.StandardMap.GridPartition +OAI.Dynamics.StandardMap.GridWordIntegrals +OAI.Dynamics.StandardMap.HalfDecomposition +OAI.Dynamics.StandardMap.IntensityBounds +OAI.Dynamics.StandardMap.JointGraphFamily +OAI.Dynamics.StandardMap.LiftDynamics +OAI.Dynamics.StandardMap.LiftEventMeasure +OAI.Dynamics.StandardMap.LimitActions +OAI.Dynamics.StandardMap.LimitBalance +OAI.Dynamics.StandardMap.LimitBridge +OAI.Dynamics.StandardMap.LimitCancellation +OAI.Dynamics.StandardMap.LimitMoments +OAI.Dynamics.StandardMap.LocalMidpointAffine +OAI.Dynamics.StandardMap.LocalMidpointGrid +OAI.Dynamics.StandardMap.LocalScarcity +OAI.Dynamics.StandardMap.LocalSquareBridge +OAI.Dynamics.StandardMap.LocalTestDetection +OAI.Dynamics.StandardMap.LogDerivativeCore +OAI.Dynamics.StandardMap.Lyapunov.ActualLyapunov +OAI.Dynamics.StandardMap.Lyapunov.Definitions +OAI.Dynamics.StandardMap.Lyapunov.DerivativeGrowth +OAI.Dynamics.StandardMap.Lyapunov.PlaneLyapunov +OAI.Dynamics.StandardMap.Lyapunov.Subadditive +OAI.Dynamics.StandardMap.ManyGood +OAI.Dynamics.StandardMap.MatchingAssembly +OAI.Dynamics.StandardMap.MatchingCore +OAI.Dynamics.StandardMap.MatchingQuantitative +OAI.Dynamics.StandardMap.MeanCancellation +OAI.Dynamics.StandardMap.MeanDeficit +OAI.Dynamics.StandardMap.MeanGrowth +OAI.Dynamics.StandardMap.MiddleCount +OAI.Dynamics.StandardMap.MiddleObservationBridge +OAI.Dynamics.StandardMap.MiddlePrefixBridge +OAI.Dynamics.StandardMap.NoCriticalSequence +OAI.Dynamics.StandardMap.NonaffineLimits +OAI.Dynamics.StandardMap.NonlinearDirichlet +OAI.Dynamics.StandardMap.ObservationExponential +OAI.Dynamics.StandardMap.ObservationTransport +OAI.Dynamics.StandardMap.OneRayZero +OAI.Dynamics.StandardMap.PatternCount +OAI.Dynamics.StandardMap.PatternDecay +OAI.Dynamics.StandardMap.PlaneGeometry +OAI.Dynamics.StandardMap.PlaneTransfer +OAI.Dynamics.StandardMap.ProductDistances +OAI.Dynamics.StandardMap.ProductSum +OAI.Dynamics.StandardMap.RealArrays +OAI.Dynamics.StandardMap.RealBridge +OAI.Dynamics.StandardMap.RealCancellation +OAI.Dynamics.StandardMap.RealScarcityCover +OAI.Dynamics.StandardMap.RecenteredGraphs +OAI.Dynamics.StandardMap.RemainderCap +OAI.Dynamics.StandardMap.RemainderLaws +OAI.Dynamics.StandardMap.RescaledArrays +OAI.Dynamics.StandardMap.SampleLaws +OAI.Dynamics.StandardMap.ScaleAction +OAI.Dynamics.StandardMap.ScaleCancellation +OAI.Dynamics.StandardMap.ScaleEndpoints +OAI.Dynamics.StandardMap.ScaleEvaluation +OAI.Dynamics.StandardMap.ScaleLaws +OAI.Dynamics.StandardMap.ScaleTelescopes +OAI.Dynamics.StandardMap.ScaleTestBounds +OAI.Dynamics.StandardMap.ScaleTruncation +OAI.Dynamics.StandardMap.ScaledChart +OAI.Dynamics.StandardMap.ScaledContraction +OAI.Dynamics.StandardMap.SegmentObservations +OAI.Dynamics.StandardMap.ShapeClassification +OAI.Dynamics.StandardMap.ShapeComponents +OAI.Dynamics.StandardMap.ShapeCore +OAI.Dynamics.StandardMap.ShapeLimit +OAI.Dynamics.StandardMap.ShapeTopology +OAI.Dynamics.StandardMap.SliceCancellation +OAI.Dynamics.StandardMap.SmoothCap +OAI.Dynamics.StandardMap.SmoothControl +OAI.Dynamics.StandardMap.StablePrefix +OAI.Dynamics.StandardMap.StrictGraphCalculus +OAI.Dynamics.StandardMap.SweepSlice +OAI.Dynamics.StandardMap.TerminalCap +OAI.Dynamics.StandardMap.TerminalShortfall +OAI.Dynamics.StandardMap.TerminalStrict +OAI.Dynamics.StandardMap.TestObservations +OAI.Dynamics.StandardMap.TorusDynamics +OAI.Dynamics.StandardMap.TorusIntegral +OAI.Dynamics.StandardMap.TorusObservations +OAI.Dynamics.StandardMap.TransferCore +OAI.Dynamics.StandardMap.TransportCarry +OAI.Dynamics.StandardMap.TransportGraphs +OAI.Dynamics.StandardMap.TransverseSweep +OAI.Dynamics.StandardMap.TreeAffine +OAI.Dynamics.StandardMap.TreeLine +OAI.Dynamics.StandardMap.TreeLocalAffine +OAI.Dynamics.StandardMap.TruncationArrays +OAI.Dynamics.StandardMap.VagueBounds +OAI.Dynamics.StandardMap.VagueLimits +OAI.Dynamics.StandardMap.VagueSupport +OAI.Dynamics.StandardMap.VariedDirichlet +OAI.Dynamics.StandardMap.VectorGrowth +OAI.Dynamics.StandardMap.WeightBalance +OAI.Dynamics.StandardMap.WeightBridge +OAI.Dynamics.StandardMap.WeightIdentification +OAI.Dynamics.StandardMap.WeightSlow +OAI.Dynamics.StandardMap.WeightTruncation +OAI.Dynamics.StandardMap.WeightUnit +OAI.Dynamics.StandardMap.WeightedChart +OAI.Dynamics.StandardMap.WeightedCompact +OAI.Dynamics.StandardMap.WeightedStability diff --git a/tasks/standard-map-lyapunov/solution/reference.py b/tasks/standard-map-lyapunov/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/standard-map-lyapunov/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/standard-map-lyapunov/solution/solve.sh b/tasks/standard-map-lyapunov/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..40af1a2809c761b0cbdf46021eeb0857a5c3300e --- /dev/null +++ b/tasks/standard-map-lyapunov/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StandardMapLyapunov, i.e. module OAI.Dynamics.StandardMap.EntropyLyapunov and the +# 211 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.StandardMap.EntropyLyapunov /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StandardMapLyapunov" diff --git a/tasks/standard-map-lyapunov/task.toml b/tasks/standard-map-lyapunov/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9fec313c854b07bdcef23aa605de9ba18e39716d --- /dev/null +++ b/tasks/standard-map-lyapunov/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/standard-map-lyapunov" +version = "1.0.0" +description = "Prove StandardMapLyapunov (openai/math family 146: Sinai's positive-entropy conjecture for the standard map) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StandardMapLyapunov.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StandardMapLyapunov" +family = "146" +family_title = "Sinai's positive-entropy conjecture for the standard map" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.StandardMapEntropy.main_entropy_complete"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.StandardMap.EntropyLyapunov" +reference_modules = 211 +reference_lean_bytes = 1383590 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1561 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12945 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/standard-map-lyapunov/tests/Challenge.lean b/tasks/standard-map-lyapunov/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..655f44a4c04da275def9e219dbb57d7898b824c0 --- /dev/null +++ b/tasks/standard-map-lyapunov/tests/Challenge.lean @@ -0,0 +1,110 @@ +import Mathlib + +namespace OAI + +open MeasureTheory Set Filter +open scoped ENNReal BigOperators Topology + +namespace StandardMapEntropy + +abbrev Circle := AddCircle (1 : ℝ) +abbrev Torus := Circle × Circle + +lemma sine_periodic : Function.Periodic (fun x : ℝ => Real.sin (2 * Real.pi * x)) 1 := by + intro x + dsimp only + rw [show 2 * Real.pi * (x + 1) = 2 * Real.pi * x + 2 * Real.pi by ring] + exact Real.sin_add_two_pi _ + +noncomputable def sine (x : Circle) : ℝ := sine_periodic.lift x + +noncomputable def standardMap (k : ℝ) (z : Torus) : Torus := + (z.1 + z.2 + (k * sine z.1 : ℝ), z.2 + (k * sine z.1 : ℝ)) + +noncomputable def area : Measure Torus := + (volume : Measure Circle).prod (volume : Measure Circle) + +def FinitePartition (r : ℕ) := { p : Torus → Fin (r + 1) // Measurable p } + +def blockAtom {r : ℕ} (f : Torus → Torus) (p : FinitePartition r) + (n : ℕ) (w : Fin n → Fin (r + 1)) : Set Torus := + { z | ∀ i : Fin n, p.val (f^[i.val] z) = w i } + +noncomputable def blockEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) (n : ℕ) : ℝ := + - ∑ w : Fin n → Fin (r + 1), + (μ (blockAtom f p n w)).toReal * Real.log (μ (blockAtom f p n w)).toReal + +noncomputable def partitionEntropy {r : ℕ} (μ : Measure Torus) (f : Torus → Torus) + (p : FinitePartition r) : ℝ≥0∞ := + ⨅ n : ℕ, ENNReal.ofReal (blockEntropy μ f p (n + 1) / (n + 1 : ℝ)) + +noncomputable def metricEntropy (μ : Measure Torus) (f : Torus → Torus) : ℝ≥0∞ := + ⨆ r : ℕ, ⨆ p : FinitePartition r, partitionEntropy μ f p + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +lemma cosine_periodic : Function.Periodic (fun x : ℝ => Real.cos (2*Real.pi*x)) 1 := by + intro x + dsimp only + rw [show 2*Real.pi*(x+1)=2*Real.pi*x+2*Real.pi by ring] + exact Real.cos_add_two_pi _ +noncomputable def cosine (x : Circle) : ℝ := cosine_periodic.lift x + +noncomputable def torusPotential (k : ℝ) (x : Circle) : ℝ := 2+(2*Real.pi*k)*cosine x + +noncomputable def transferStep (v : ℝ) : ℂ →L[ℝ] ℂ := + { toLinearMap := + { toFun := fun z => ⟨v*z.re-z.im,z.re⟩ + map_add' := by intro z w; apply Complex.ext <;> simp; ring + map_smul' := by intro t z; apply Complex.ext <;> simp; ring } + cont := by + exact Complex.equivRealProdCLM.symm.continuous.comp + (((continuous_const.mul Complex.continuous_re).sub Complex.continuous_im).prodMk Complex.continuous_re) } + +noncomputable def tangentCoordinates : ℂ →L[ℝ] ℂ := + { toLinearMap := + { toFun := fun z => ⟨z.re, z.re-z.im⟩ + map_add' := by intro z w; apply Complex.ext <;> simp; ring + map_smul' := by intro t z; apply Complex.ext <;> simp; ring } + cont := Complex.equivRealProdCLM.symm.continuous.comp + (Complex.continuous_re.prodMk (Complex.continuous_re.sub Complex.continuous_im)) } + +local instance realTangentCompTriple : + RingHomCompTriple (RingHom.id ℝ) (RingHom.id ℝ) (RingHom.id ℝ) := inferInstance + +noncomputable def standardDerivative (k : ℝ) (z : Torus) : ℂ →L[ℝ] ℂ := + tangentCoordinates.comp ((transferStep (torusPotential k z.1)).comp tangentCoordinates) + +noncomputable def standardDerivativeProduct (k : ℝ) (z : Torus) (n : ℕ) : ℂ →L[ℝ] ℂ := + Nat.rec (ContinuousLinearMap.id ℝ ℂ) + (fun i A => (standardDerivative k ((standardMap k)^[i] z)).comp A) n + +noncomputable def wedge (z w : ℂ) : ℝ := z.re * w.im - z.im * w.re + +def VectorGrowth (k : ℝ) (z : Torus) (v : ℂ) (l : ℝ) : Prop := + v ≠ 0 ∧ Tendsto (fun n : ℕ => Real.log ‖standardDerivativeProduct k z n v‖ / (n : ℝ)) + atTop (𝓝 l) + +def LyapunovSpectrumAt (k : ℝ) (z : Torus) (l : ℝ) : Prop := + 0 ≤ l ∧ ((l = 0 ∧ ∀ v : ℂ, v ≠ 0 → VectorGrowth k z v 0) ∨ + (0 < l ∧ ∃ s : ℂ, s ≠ 0 ∧ ∀ v : ℂ, v ≠ 0 → + VectorGrowth k z v (if wedge s v = 0 then -l else l))) + +def PositiveLargestLyapunov (k : ℝ) : Prop := + ∃ E : Set Torus, MeasurableSet E ∧ 0 < area E ∧ + ∀ z ∈ E, ∃ l : ℝ, 0 < l ∧ LyapunovSpectrumAt k z l ∧ + Tendsto + (fun n : ℕ => Real.log ‖standardDerivativeProduct k z n‖ / (n : ℝ)) + atTop (𝓝 l) + +theorem main_entropy_complete : + ∃ k₀ : ℝ, 0 < k₀ ∧ ∀ k : ℝ, k₀ ≤ k → + 0 < metricEntropy area (standardMap k) ∧ + PositiveLargestLyapunov k ∧ + (0 < metricEntropy area (standardMap k) ↔ PositiveLargestLyapunov k) := by + sorry + +end StandardMapEntropy + +end OAI diff --git a/tasks/standard-map-lyapunov/tests/grade.py b/tasks/standard-map-lyapunov/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/standard-map-lyapunov/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/standard-map-lyapunov/tests/task.json b/tasks/standard-map-lyapunov/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..bb04abfab8ad8627c37637d46673aa15c1eec793 --- /dev/null +++ b/tasks/standard-map-lyapunov/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "StandardMapLyapunov", + "comparator": { + "theorem_names": [ + "OAI.StandardMapEntropy.main_entropy_complete" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12045 +} \ No newline at end of file diff --git a/tasks/standard-map-lyapunov/tests/test.sh b/tasks/standard-map-lyapunov/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/standard-map-lyapunov/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/steinitz-bergstrom/environment/Dockerfile b/tasks/steinitz-bergstrom/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/steinitz-bergstrom/environment/fetch_mathlib.sh b/tasks/steinitz-bergstrom/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/steinitz-bergstrom/environment/lake-manifest.json b/tasks/steinitz-bergstrom/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/steinitz-bergstrom/environment/lakefile.lean b/tasks/steinitz-bergstrom/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/steinitz-bergstrom/environment/lean_setup.sh b/tasks/steinitz-bergstrom/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/steinitz-bergstrom/environment/pack_submission.py b/tasks/steinitz-bergstrom/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/steinitz-bergstrom/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/steinitz-bergstrom/instruction.md b/tasks/steinitz-bergstrom/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a0251432defb244e2aa3b8b481ef7f8ecef1d1d6 --- /dev/null +++ b/tasks/steinitz-bergstrom/instruction.md @@ -0,0 +1,80 @@ +# openai/math challenge `SteinitzBergstrom` (family 097) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 097 of the release, *The Euclidean Steinitz–Bergstrom conjecture* +(Convex and metric geometry). The family as a whole: Proves that any finite sequence in the Euclidean unit ball of $\mathbb R^d$ admits signs keeping every partial sum within $C\sqrt d$, independently of length. Consequently every zero-sum family can be reordered with the same bound on unsigned partial sums. A matching lower bound gives the optimal order $S_2(d)=\Theta(\sqrt d)$. + +The challenge is `SteinitzBergstrom`, also at `/opt/openai-math/challenges/SteinitzBergstrom.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace EuclideanSteinitzBergstrom + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def SignedPrefixBound (C : ℝ) : Prop := + ∀ (d N : ℕ), 1 ≤ d → 1 ≤ N → + ∀ (v : Fin N → Vector d), (∀ i, ‖v i‖ ≤ 1) → + ∃ ε : Fin N → ℝ, (∀ i, ε i = -1 ∨ ε i = 1) ∧ + ∀ k : ℕ, k ≤ N → + ‖∑ i ∈ Finset.univ.filter (fun i : Fin N => i.val < k), ε i • v i‖ ≤ + C * Real.sqrt d + +def OrderingPrefixBound (C : ℝ) : Prop := + ∀ (d N : ℕ), 1 ≤ d → 1 ≤ N → + ∀ (v : Fin N → Vector d), (∀ i, ‖v i‖ ≤ 1) → (∑ i, v i) = 0 → + ∃ π : Equiv.Perm (Fin N), ∀ k : ℕ, k ≤ N → + ‖∑ i ∈ Finset.univ.filter (fun i : Fin N => i.val < k), v (π i)‖ ≤ + C * Real.sqrt d + +theorem main : ∃ C : ℝ, SignedPrefixBound C ∧ OrderingPrefixBound C := by + sorry + +end EuclideanSteinitzBergstrom + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SteinitzBergstrom.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.EuclideanSteinitzBergstrom.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/steinitz-bergstrom/solution/closure.txt b/tasks/steinitz-bergstrom/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..0731ccf9b4dc0e89d258c842ff72f03161904fc6 --- /dev/null +++ b/tasks/steinitz-bergstrom/solution/closure.txt @@ -0,0 +1,29 @@ +OAI.Analysis.Steinitz.Adaptive +OAI.Analysis.Steinitz.Chaining +OAI.Analysis.Steinitz.Coefficients +OAI.Analysis.Steinitz.Correlation +OAI.Analysis.Steinitz.Energy +OAI.Analysis.Steinitz.Filter +OAI.Analysis.Steinitz.FilterMoments +OAI.Analysis.Steinitz.FilteredBody +OAI.Analysis.Steinitz.Gain +OAI.Analysis.Steinitz.GaussianKernel +OAI.Analysis.Steinitz.GaussianProcess +OAI.Analysis.Steinitz.GaussianTail +OAI.Analysis.Steinitz.HeatEnergy +OAI.Analysis.Steinitz.HeatL2 +OAI.Analysis.Steinitz.KernelConvexity +OAI.Analysis.Steinitz.LiftedRearrangement +OAI.Analysis.Steinitz.Main +OAI.Analysis.Steinitz.MatrixEnergy +OAI.Analysis.Steinitz.Model +OAI.Analysis.Steinitz.PathLaws +OAI.Analysis.Steinitz.Predictor +OAI.Analysis.Steinitz.Prekopa +OAI.Analysis.Steinitz.Rearrangement +OAI.Analysis.Steinitz.Scales +OAI.Analysis.Steinitz.SectionEnergy +OAI.Analysis.Steinitz.SigningData +OAI.Analysis.Steinitz.Spectral +OAI.Analysis.Steinitz.Survival +OAI.Analysis.Steinitz.Transference diff --git a/tasks/steinitz-bergstrom/solution/reference.py b/tasks/steinitz-bergstrom/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/steinitz-bergstrom/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/steinitz-bergstrom/solution/solve.sh b/tasks/steinitz-bergstrom/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..853195fb734534f0901c3511b55b13a2848c018c --- /dev/null +++ b/tasks/steinitz-bergstrom/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SteinitzBergstrom, i.e. module OAI.Analysis.Steinitz.Main and the +# 29 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Steinitz.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SteinitzBergstrom" diff --git a/tasks/steinitz-bergstrom/task.toml b/tasks/steinitz-bergstrom/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c8f8ebc900690f791de7f239a481da14dd17218c --- /dev/null +++ b/tasks/steinitz-bergstrom/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/steinitz-bergstrom" +version = "1.0.0" +description = "Prove SteinitzBergstrom (openai/math family 097: The Euclidean Steinitz–Bergstrom conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SteinitzBergstrom.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SteinitzBergstrom" +family = "097" +family_title = "The Euclidean Steinitz–Bergstrom conjecture" +subject = "Convex and metric geometry" +theorems = ["OAI.EuclideanSteinitzBergstrom.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Steinitz.Main" +reference_modules = 29 +reference_lean_bytes = 716227 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 875 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12344 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/steinitz-bergstrom/tests/Challenge.lean b/tasks/steinitz-bergstrom/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..00107bf2365bb51fb4896ce83faa21dbdc5e2bea --- /dev/null +++ b/tasks/steinitz-bergstrom/tests/Challenge.lean @@ -0,0 +1,29 @@ +import Mathlib + +namespace OAI + +namespace EuclideanSteinitzBergstrom + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) + +def SignedPrefixBound (C : ℝ) : Prop := + ∀ (d N : ℕ), 1 ≤ d → 1 ≤ N → + ∀ (v : Fin N → Vector d), (∀ i, ‖v i‖ ≤ 1) → + ∃ ε : Fin N → ℝ, (∀ i, ε i = -1 ∨ ε i = 1) ∧ + ∀ k : ℕ, k ≤ N → + ‖∑ i ∈ Finset.univ.filter (fun i : Fin N => i.val < k), ε i • v i‖ ≤ + C * Real.sqrt d + +def OrderingPrefixBound (C : ℝ) : Prop := + ∀ (d N : ℕ), 1 ≤ d → 1 ≤ N → + ∀ (v : Fin N → Vector d), (∀ i, ‖v i‖ ≤ 1) → (∑ i, v i) = 0 → + ∃ π : Equiv.Perm (Fin N), ∀ k : ℕ, k ≤ N → + ‖∑ i ∈ Finset.univ.filter (fun i : Fin N => i.val < k), v (π i)‖ ≤ + C * Real.sqrt d + +theorem main : ∃ C : ℝ, SignedPrefixBound C ∧ OrderingPrefixBound C := by + sorry + +end EuclideanSteinitzBergstrom + +end OAI diff --git a/tasks/steinitz-bergstrom/tests/grade.py b/tasks/steinitz-bergstrom/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/steinitz-bergstrom/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/steinitz-bergstrom/tests/task.json b/tasks/steinitz-bergstrom/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8fef3c97e2c1aca7ac2c0dde016c26dcf85b3cba --- /dev/null +++ b/tasks/steinitz-bergstrom/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SteinitzBergstrom", + "comparator": { + "theorem_names": [ + "OAI.EuclideanSteinitzBergstrom.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11444 +} \ No newline at end of file diff --git a/tasks/steinitz-bergstrom/tests/test.sh b/tasks/steinitz-bergstrom/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/steinitz-bergstrom/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/strict-means/environment/Dockerfile b/tasks/strict-means/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/strict-means/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/strict-means/environment/fetch_mathlib.sh b/tasks/strict-means/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/strict-means/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/strict-means/environment/lake-manifest.json b/tasks/strict-means/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/strict-means/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/strict-means/environment/lakefile.lean b/tasks/strict-means/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/strict-means/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/strict-means/environment/lean_setup.sh b/tasks/strict-means/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/strict-means/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/strict-means/environment/pack_submission.py b/tasks/strict-means/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/strict-means/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/strict-means/instruction.md b/tasks/strict-means/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..668e5db7df7c6d4c5c7341fd4928850b7aad39d8 --- /dev/null +++ b/tasks/strict-means/instruction.md @@ -0,0 +1,96 @@ +# openai/math challenge `StrictMeans` (family 072) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 072 of the release, *Brennan's conjecture and a counterexample to Kraetzer's prediction* +(Real and complex analysis). The family as a whole: Proves Brennan's conjecture: for every conformal bijection $\phi$ from a simply connected plane domain onto the disk, $|\phi'|^s$ is area-integrable for $4/3 + ((Real.log (integralMean p f r) / Real.log (1 / (1 - r)) : ℝ) : EReal)) + (𝓝[<] (1 : ℝ)) + +noncomputable def boundedSpectrum (p : ℝ) : EReal := + ⨆ (f : ℂ → ℂ) (_ : BoundedNormalizedUnivalent f), growthExponent p f + +noncomputable def kraetzerPrediction (p : ℝ) : EReal := + if |p| ≤ 2 then ((p ^ (2 : ℕ) / 4 : ℝ) : EReal) + else ((|p| - 1 : ℝ) : EReal) + +theorem main : + (∃ ε C : ℝ, 0 < ε ∧ ε < 1 / 4 ∧ + ∀ (f : ℂ → ℂ), NormalizedUnivalent f → + ∀ r : ℝ, 1 / 2 ≤ r → r < 1 → + integralMean (-1) f r ≤ C * (1 - r) ^ (-(1 / 4 : ℝ) + ε)) ∧ + boundedSpectrum (-1) < (1 / 4 : EReal) ∧ + (¬ ∀ p : ℝ, boundedSpectrum p = kraetzerPrediction p) := by + sorry + +end StrictInverseFirstPower + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StrictMeans.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StrictInverseFirstPower.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/strict-means/solution/closure.txt b/tasks/strict-means/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..48b709b1a240b703905cba7b427dbbd88dede25a --- /dev/null +++ b/tasks/strict-means/solution/closure.txt @@ -0,0 +1,94 @@ +OAI.Analysis.StrictMeans.AffineAveraging +OAI.Analysis.StrictMeans.AreaCoefficients +OAI.Analysis.StrictMeans.AreaTails +OAI.Analysis.StrictMeans.AreaTransport +OAI.Analysis.StrictMeans.BorelRanks +OAI.Analysis.StrictMeans.BoundaryCells +OAI.Analysis.StrictMeans.BoundaryEscape +OAI.Analysis.StrictMeans.BoxExtension +OAI.Analysis.StrictMeans.BoxSlope +OAI.Analysis.StrictMeans.BoxTransport +OAI.Analysis.StrictMeans.CanonicalIndex +OAI.Analysis.StrictMeans.CircleBounds +OAI.Analysis.StrictMeans.CompactFamily +OAI.Analysis.StrictMeans.CompactIndexSum +OAI.Analysis.StrictMeans.CompactMorseEuler +OAI.Analysis.StrictMeans.CompactMorseIndex +OAI.Analysis.StrictMeans.CriticalCounts +OAI.Analysis.StrictMeans.CriticalCovariance +OAI.Analysis.StrictMeans.CriticalPotential +OAI.Analysis.StrictMeans.CriticalRanks +OAI.Analysis.StrictMeans.DerivativeDistortion +OAI.Analysis.StrictMeans.DescendingRanks +OAI.Analysis.StrictMeans.DiagonalIndex +OAI.Analysis.StrictMeans.DiscreteLaplacian +OAI.Analysis.StrictMeans.DiskAutomorphisms +OAI.Analysis.StrictMeans.DyadicBounds +OAI.Analysis.StrictMeans.DyadicGap +OAI.Analysis.StrictMeans.Eigenmeasure +OAI.Analysis.StrictMeans.Endpoints +OAI.Analysis.StrictMeans.EqualityBarrier +OAI.Analysis.StrictMeans.FamilyDerivatives +OAI.Analysis.StrictMeans.FiberSum +OAI.Analysis.StrictMeans.FiniteEuler +OAI.Analysis.StrictMeans.GenericTargets +OAI.Analysis.StrictMeans.GreenIdentity +OAI.Analysis.StrictMeans.GridChains +OAI.Analysis.StrictMeans.GridComplex +OAI.Analysis.StrictMeans.GridEuler +OAI.Analysis.StrictMeans.GridLinear +OAI.Analysis.StrictMeans.GridLink +OAI.Analysis.StrictMeans.GridSupport +OAI.Analysis.StrictMeans.HalfPlane +OAI.Analysis.StrictMeans.HeightIndex +OAI.Analysis.StrictMeans.HessianLocal +OAI.Analysis.StrictMeans.HorizontalAveraging +OAI.Analysis.StrictMeans.HorizontalLength +OAI.Analysis.StrictMeans.ImageBounds +OAI.Analysis.StrictMeans.IndexConservation +OAI.Analysis.StrictMeans.IndexEuler +OAI.Analysis.StrictMeans.IndexGeometry +OAI.Analysis.StrictMeans.IndexHomotopy +OAI.Analysis.StrictMeans.IndexLocality +OAI.Analysis.StrictMeans.InfinityEscape +OAI.Analysis.StrictMeans.JacobianMoments +OAI.Analysis.StrictMeans.LatticeEuler +OAI.Analysis.StrictMeans.LatticeGeometry +OAI.Analysis.StrictMeans.LatticeIndex +OAI.Analysis.StrictMeans.LawDensity +OAI.Analysis.StrictMeans.Main +OAI.Analysis.StrictMeans.MeasurableGeometry +OAI.Analysis.StrictMeans.Model +OAI.Analysis.StrictMeans.MorseGeometry +OAI.Analysis.StrictMeans.NormalizedTargets +OAI.Analysis.StrictMeans.PairingCovariance +OAI.Analysis.StrictMeans.PairingCoverage +OAI.Analysis.StrictMeans.PlaneRectangle +OAI.Analysis.StrictMeans.PositiveFunctionals +OAI.Analysis.StrictMeans.QuadraticHomotopy +OAI.Analysis.StrictMeans.QuadraticIndex +OAI.Analysis.StrictMeans.QuadraticLine +OAI.Analysis.StrictMeans.RankCovariance +OAI.Analysis.StrictMeans.RankPairing +OAI.Analysis.StrictMeans.Rebasing +OAI.Analysis.StrictMeans.ReciprocalMoments +OAI.Analysis.StrictMeans.RectangleLog +OAI.Analysis.StrictMeans.RegularLevels +OAI.Analysis.StrictMeans.RegularTargets +OAI.Analysis.StrictMeans.RootTransform +OAI.Analysis.StrictMeans.SmoothGridRegular +OAI.Analysis.StrictMeans.SmoothIndexHomotopy +OAI.Analysis.StrictMeans.SmoothMorseIndex +OAI.Analysis.StrictMeans.SmoothSublevelEuler +OAI.Analysis.StrictMeans.SpectralGrowth +OAI.Analysis.StrictMeans.Spectrum +OAI.Analysis.StrictMeans.SquaredPotential +OAI.Analysis.StrictMeans.StrictTransport +OAI.Analysis.StrictMeans.TransferOperator +OAI.Analysis.StrictMeans.TransportBasic +OAI.Analysis.StrictMeans.TransportInjection +OAI.Analysis.StrictMeans.TransportLimit +OAI.Analysis.StrictMeans.TransportPairing +OAI.Analysis.StrictMeans.TransportTest +OAI.Analysis.StrictMeans.TriangularIndex +OAI.Analysis.StrictMeans.UniformMeans diff --git a/tasks/strict-means/solution/reference.py b/tasks/strict-means/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/strict-means/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/strict-means/solution/solve.sh b/tasks/strict-means/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fc32b2dde67d947a226c283fe4467a2b2e93699c --- /dev/null +++ b/tasks/strict-means/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StrictMeans, i.e. module OAI.Analysis.StrictMeans.Main and the +# 94 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.StrictMeans.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StrictMeans" diff --git a/tasks/strict-means/task.toml b/tasks/strict-means/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0a2c153d7b188f0efad903b347855714397a0702 --- /dev/null +++ b/tasks/strict-means/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/strict-means" +version = "1.0.0" +description = "Prove StrictMeans (openai/math family 072: Brennan's conjecture and a counterexample to Kraetzer's prediction) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StrictMeans.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StrictMeans" +family = "072" +family_title = "Brennan's conjecture and a counterexample to Kraetzer's prediction" +subject = "Real and complex analysis" +theorems = ["OAI.StrictInverseFirstPower.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.StrictMeans.Main" +reference_modules = 94 +reference_lean_bytes = 718706 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1180 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12346 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/strict-means/tests/Challenge.lean b/tasks/strict-means/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..176d72980ce8aed7aa8a9bd29dec7207ab6f1e0b --- /dev/null +++ b/tasks/strict-means/tests/Challenge.lean @@ -0,0 +1,45 @@ +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped Topology + +namespace StrictInverseFirstPower + +def disk : Set ℂ := Metric.ball 0 1 + +def NormalizedUnivalent (f : ℂ → ℂ) : Prop := + DifferentiableOn ℂ f disk ∧ Set.InjOn f disk ∧ f 0 = 0 ∧ deriv f 0 = 1 + +def BoundedNormalizedUnivalent (f : ℂ → ℂ) : Prop := + NormalizedUnivalent f ∧ ∃ R : ℝ, ∀ z ∈ disk, ‖f z‖ ≤ R + +noncomputable def integralMean (p : ℝ) (f : ℂ → ℂ) (r : ℝ) : ℝ := + (2 * Real.pi)⁻¹ * ∫ θ in -Real.pi..Real.pi, + ‖deriv f ((r : ℂ) * Complex.exp ((θ : ℂ) * Complex.I))‖ ^ p + +noncomputable def growthExponent (p : ℝ) (f : ℂ → ℂ) : EReal := + Filter.limsup (fun r : ℝ => + ((Real.log (integralMean p f r) / Real.log (1 / (1 - r)) : ℝ) : EReal)) + (𝓝[<] (1 : ℝ)) + +noncomputable def boundedSpectrum (p : ℝ) : EReal := + ⨆ (f : ℂ → ℂ) (_ : BoundedNormalizedUnivalent f), growthExponent p f + +noncomputable def kraetzerPrediction (p : ℝ) : EReal := + if |p| ≤ 2 then ((p ^ (2 : ℕ) / 4 : ℝ) : EReal) + else ((|p| - 1 : ℝ) : EReal) + +theorem main : + (∃ ε C : ℝ, 0 < ε ∧ ε < 1 / 4 ∧ + ∀ (f : ℂ → ℂ), NormalizedUnivalent f → + ∀ r : ℝ, 1 / 2 ≤ r → r < 1 → + integralMean (-1) f r ≤ C * (1 - r) ^ (-(1 / 4 : ℝ) + ε)) ∧ + boundedSpectrum (-1) < (1 / 4 : EReal) ∧ + (¬ ∀ p : ℝ, boundedSpectrum p = kraetzerPrediction p) := by + sorry + +end StrictInverseFirstPower + +end OAI diff --git a/tasks/strict-means/tests/grade.py b/tasks/strict-means/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/strict-means/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/strict-means/tests/task.json b/tasks/strict-means/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6e1f2a2a3089f3ddf069f60a1e145274ee953fc0 --- /dev/null +++ b/tasks/strict-means/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "StrictMeans", + "comparator": { + "theorem_names": [ + "OAI.StrictInverseFirstPower.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11446 +} \ No newline at end of file diff --git a/tasks/strict-means/tests/test.sh b/tasks/strict-means/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/strict-means/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/strong-thin-tree/environment/Dockerfile b/tasks/strong-thin-tree/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/strong-thin-tree/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/strong-thin-tree/environment/fetch_mathlib.sh b/tasks/strong-thin-tree/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/strong-thin-tree/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/strong-thin-tree/environment/lake-manifest.json b/tasks/strong-thin-tree/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/strong-thin-tree/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/strong-thin-tree/environment/lakefile.lean b/tasks/strong-thin-tree/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/strong-thin-tree/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/strong-thin-tree/environment/lean_setup.sh b/tasks/strong-thin-tree/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/strong-thin-tree/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/strong-thin-tree/environment/pack_submission.py b/tasks/strong-thin-tree/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/strong-thin-tree/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/strong-thin-tree/instruction.md b/tasks/strong-thin-tree/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e517187189b6da0c35d2f44b878a5e21a31b916b --- /dev/null +++ b/tasks/strong-thin-tree/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `StrongThinTree` (family 174) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 174 of the release, *Deterministic construction of strong thin spanning trees* +(Combinatorics). The family as a whole: Resolves the strong thin-tree conjecture constructively. Every finite loopless $k$-edge-connected multigraph on at least two vertices has a spanning tree containing at most a universal $C/k$ fraction of the edges of every cut. Such a tree can be found deterministically in polynomial time, even with binary-encoded parallel-edge multiplicities. + +The challenge is `StrongThinTree`, also at `/opt/openai-math/challenges/StrongThinTree.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace StrongThinTree + +structure MultiGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + loopless : ∀ e, left e ≠ right e + +namespace MultiGraph + +def cut {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) + (S : Finset (Fin n)) : Finset (Fin m) := + T.filter fun e => (G.left e ∈ S ∧ G.right e ∉ S) ∨ + (G.right e ∈ S ∧ G.left e ∉ S) + +def Connected {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → (G.cut T S).Nonempty + +def SpanningTree {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + G.Connected T ∧ ∀ e ∈ T, ¬ G.Connected (T.erase e) + +def EdgeConnected {n m : ℕ} (G : MultiGraph n m) (k : ℕ) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + k ≤ (G.cut Finset.univ S).card + +end MultiGraph + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (k : ℕ), 1 ≤ k → ∀ (n m : ℕ), 2 ≤ n → + ∀ G : MultiGraph n m, G.EdgeConnected k → + ∃ T : Finset (Fin m), G.SpanningTree T ∧ + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + ((G.cut T S).card : ℝ) ≤ (C / (k : ℝ)) * (G.cut Finset.univ S).card + +theorem strongThinTree : MainStatement := by + sorry + +end StrongThinTree + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StrongThinTree.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StrongThinTree.strongThinTree` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/strong-thin-tree/solution/closure.txt b/tasks/strong-thin-tree/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9cec3d32b5b4512f7fedcf9f5f44cd7fdc847201 --- /dev/null +++ b/tasks/strong-thin-tree/solution/closure.txt @@ -0,0 +1,72 @@ +OAI.Combinatorics.ThinTrees.Affine +OAI.Combinatorics.ThinTrees.AssignedFamilies +OAI.Combinatorics.ThinTrees.Assignment +OAI.Combinatorics.ThinTrees.BagBounds +OAI.Combinatorics.ThinTrees.BagConstruction +OAI.Combinatorics.ThinTrees.BagGeometry +OAI.Combinatorics.ThinTrees.Barrier +OAI.Combinatorics.ThinTrees.BasePacking +OAI.Combinatorics.ThinTrees.Blocks +OAI.Combinatorics.ThinTrees.Capture +OAI.Combinatorics.ThinTrees.ChainEdges +OAI.Combinatorics.ThinTrees.Characteristic +OAI.Combinatorics.ThinTrees.Coarea +OAI.Combinatorics.ThinTrees.CompactPacking +OAI.Combinatorics.ThinTrees.Density +OAI.Combinatorics.ThinTrees.DeterminantCalculus +OAI.Combinatorics.ThinTrees.Duality +OAI.Combinatorics.ThinTrees.DyadicSelection +OAI.Combinatorics.ThinTrees.Expectation +OAI.Combinatorics.ThinTrees.Extraction +OAI.Combinatorics.ThinTrees.ExtractionBounds +OAI.Combinatorics.ThinTrees.ExtractionCriterion +OAI.Combinatorics.ThinTrees.ExtractionLimit +OAI.Combinatorics.ThinTrees.FiniteSelection +OAI.Combinatorics.ThinTrees.FixedPoint +OAI.Combinatorics.ThinTrees.GraphMatrix +OAI.Combinatorics.ThinTrees.Hierarchy +OAI.Combinatorics.ThinTrees.HierarchyBounds +OAI.Combinatorics.ThinTrees.HierarchyBuilder +OAI.Combinatorics.ThinTrees.HierarchyResponse +OAI.Combinatorics.ThinTrees.IndependentVectors +OAI.Combinatorics.ThinTrees.Interlacing +OAI.Combinatorics.ThinTrees.Iteration +OAI.Combinatorics.ThinTrees.IterationBounds +OAI.Combinatorics.ThinTrees.Main +OAI.Combinatorics.ThinTrees.Matrix +OAI.Combinatorics.ThinTrees.MatrixDomain +OAI.Combinatorics.ThinTrees.MatrixMixture +OAI.Combinatorics.ThinTrees.MixedPolynomial +OAI.Combinatorics.ThinTrees.Model +OAI.Combinatorics.ThinTrees.Monicity +OAI.Combinatorics.ThinTrees.Normalization +OAI.Combinatorics.ThinTrees.OptionalDirections +OAI.Combinatorics.ThinTrees.Padding +OAI.Combinatorics.ThinTrees.PartialFractions +OAI.Combinatorics.ThinTrees.PartitionHierarchy +OAI.Combinatorics.ThinTrees.PartitionRank +OAI.Combinatorics.ThinTrees.Partitions +OAI.Combinatorics.ThinTrees.Phases +OAI.Combinatorics.ThinTrees.RankOne +OAI.Combinatorics.ThinTrees.RealRoots +OAI.Combinatorics.ThinTrees.Records +OAI.Combinatorics.ThinTrees.Representation +OAI.Combinatorics.ThinTrees.ResponseBounds +OAI.Combinatorics.ThinTrees.ResponseFixedPoint +OAI.Combinatorics.ThinTrees.Restriction +OAI.Combinatorics.ThinTrees.RootBound +OAI.Combinatorics.ThinTrees.Selection +OAI.Combinatorics.ThinTrees.Shells +OAI.Combinatorics.ThinTrees.ShortcutDuality +OAI.Combinatorics.ThinTrees.SimultaneousResponse +OAI.Combinatorics.ThinTrees.Sparsification +OAI.Combinatorics.ThinTrees.SparsifyGeometry +OAI.Combinatorics.ThinTrees.SpectralPacking +OAI.Combinatorics.ThinTrees.SpectralSplit +OAI.Combinatorics.ThinTrees.Stability +OAI.Combinatorics.ThinTrees.StepBounds +OAI.Combinatorics.ThinTrees.Subisotropic +OAI.Combinatorics.ThinTrees.ThresholdChain +OAI.Combinatorics.ThinTrees.Translation +OAI.Combinatorics.ThinTrees.Truncation +OAI.Combinatorics.ThinTrees.TwoSystems diff --git a/tasks/strong-thin-tree/solution/reference.py b/tasks/strong-thin-tree/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/strong-thin-tree/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/strong-thin-tree/solution/solve.sh b/tasks/strong-thin-tree/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..da44fd3dcda109578d27433eb9d6f1a45c134efc --- /dev/null +++ b/tasks/strong-thin-tree/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StrongThinTree, i.e. module OAI.Combinatorics.ThinTrees.Main and the +# 72 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ThinTrees.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StrongThinTree" diff --git a/tasks/strong-thin-tree/task.toml b/tasks/strong-thin-tree/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3e86ce7765b8006cec1eb070664c200ea02f3e69 --- /dev/null +++ b/tasks/strong-thin-tree/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/strong-thin-tree" +version = "1.0.0" +description = "Prove StrongThinTree (openai/math family 174: Deterministic construction of strong thin spanning trees) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StrongThinTree.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StrongThinTree" +family = "174" +family_title = "Deterministic construction of strong thin spanning trees" +subject = "Combinatorics" +theorems = ["OAI.StrongThinTree.strongThinTree"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ThinTrees.Main" +reference_modules = 72 +reference_lean_bytes = 775264 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 974 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12397 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/strong-thin-tree/tests/Challenge.lean b/tasks/strong-thin-tree/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..966ebe865ea3f61cb1295836cfa532bf26aca2e0 --- /dev/null +++ b/tasks/strong-thin-tree/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +namespace StrongThinTree + +structure MultiGraph (n m : ℕ) where + left : Fin m → Fin n + right : Fin m → Fin n + loopless : ∀ e, left e ≠ right e + +namespace MultiGraph + +def cut {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) + (S : Finset (Fin n)) : Finset (Fin m) := + T.filter fun e => (G.left e ∈ S ∧ G.right e ∉ S) ∨ + (G.right e ∈ S ∧ G.left e ∉ S) + +def Connected {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → (G.cut T S).Nonempty + +def SpanningTree {n m : ℕ} (G : MultiGraph n m) (T : Finset (Fin m)) : Prop := + G.Connected T ∧ ∀ e ∈ T, ¬ G.Connected (T.erase e) + +def EdgeConnected {n m : ℕ} (G : MultiGraph n m) (k : ℕ) : Prop := + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + k ≤ (G.cut Finset.univ S).card + +end MultiGraph + +def MainStatement : Prop := + ∃ C : ℝ, 0 < C ∧ ∀ (k : ℕ), 1 ≤ k → ∀ (n m : ℕ), 2 ≤ n → + ∀ G : MultiGraph n m, G.EdgeConnected k → + ∃ T : Finset (Fin m), G.SpanningTree T ∧ + ∀ S : Finset (Fin n), S.Nonempty → S ≠ Finset.univ → + ((G.cut T S).card : ℝ) ≤ (C / (k : ℝ)) * (G.cut Finset.univ S).card + +theorem strongThinTree : MainStatement := by + sorry + +end StrongThinTree + +end OAI diff --git a/tasks/strong-thin-tree/tests/grade.py b/tasks/strong-thin-tree/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/strong-thin-tree/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/strong-thin-tree/tests/task.json b/tasks/strong-thin-tree/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..461877ed9b6d0716232c96d3d24b5aff2d3232da --- /dev/null +++ b/tasks/strong-thin-tree/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "StrongThinTree", + "comparator": { + "theorem_names": [ + "OAI.StrongThinTree.strongThinTree" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11497 +} \ No newline at end of file diff --git a/tasks/strong-thin-tree/tests/test.sh b/tasks/strong-thin-tree/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/strong-thin-tree/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/strongly-rayleigh-dpp/environment/Dockerfile b/tasks/strongly-rayleigh-dpp/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/strongly-rayleigh-dpp/environment/fetch_mathlib.sh b/tasks/strongly-rayleigh-dpp/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/strongly-rayleigh-dpp/environment/lake-manifest.json b/tasks/strongly-rayleigh-dpp/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/strongly-rayleigh-dpp/environment/lakefile.lean b/tasks/strongly-rayleigh-dpp/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/strongly-rayleigh-dpp/environment/lean_setup.sh b/tasks/strongly-rayleigh-dpp/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/strongly-rayleigh-dpp/environment/pack_submission.py b/tasks/strongly-rayleigh-dpp/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/strongly-rayleigh-dpp/instruction.md b/tasks/strongly-rayleigh-dpp/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..ee3912c26cceb6c2f287f255d67339cf755c23d8 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/instruction.md @@ -0,0 +1,236 @@ +# openai/math challenge `StronglyRayleighDPP` (family 231) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 231 of the release, *The free uniform spanning forest is a factor of IID* +(Probability and statistical mechanics). The family as a whole: On every infinite connected locally finite simple unweighted graph, the free uniform spanning forest is a factor of independent vertex labels, by one isomorphism-equivariant rule using no root. Translation-invariant strongly Rayleigh binary processes on every countable group, including invariant determinantal processes with Hermitian positive-contraction kernels, are also factors of IID. + +The challenge is `StronglyRayleighDPP`, also at `/opt/openai-math/challenges/StronglyRayleighDPP.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11 u_12 +universe u_13 u_14 u_15 u_16 u_17 u_18 u_19 u_20 + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal Topology ComplexConjugate + +namespace Problem336AdditiveD139 + +abbrev UnitLabel := Set.Icc (0 : ℝ) 1 + +def leftTranslate {Γ : Type u_1} {α : Type u_2} [Group Γ] (g : Γ) (a : Γ → α) : Γ → α := + fun h => a (g⁻¹ * h) + +def iidUnitLabels (Γ : Type u_3) [MeasurableSpace Γ] : Measure (Γ → UnitLabel) := + Measure.infinitePi (fun _ : Γ => (volume : Measure UnitLabel)) + +def InvariantBinaryLaw {Γ : Type u_4} [Group Γ] + (μ : ProbabilityMeasure (Γ → Bool)) : Prop := + ∀ g : Γ, + Measure.map (leftTranslate g) (μ : Measure (Γ → Bool)) = + (μ : Measure (Γ → Bool)) + +def HasEquivariantIIDFactor {Γ : Type u_5} [Group Γ] [MeasurableSpace Γ] + (μ : ProbabilityMeasure (Γ → Bool)) : Prop := + ∃ Phi : (Γ → UnitLabel) → (Γ → Bool), + Measurable Phi ∧ + (∀ (g : Γ) (u : Γ → UnitLabel), + Phi (leftTranslate g u) = leftTranslate g (Phi u)) ∧ + Measure.map Phi (iidUnitLabels Γ) = (μ : Measure (Γ → Bool)) + +def finiteGeneratingValue {F : Type u_6} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (z : F → ℂ) : ℂ := by + classical + exact ∑ x : F → Bool, + (((μ : Measure (F → Bool)) {x}).toReal : ℂ) * + ∏ i : F, if x i = true then z i else 1 + +def StronglyRayleighFinite {F : Type u_7} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) : Prop := + ∀ z : F → ℂ, (∀ i : F, 0 < (z i).im) → finiteGeneratingValue μ z ≠ 0 + +def marginalMass {I : Type u_8} (μ : ProbabilityMeasure (I → Bool)) + (S : Finset I) (x : S → Bool) : ℝ := + ((μ : Measure (I → Bool)) {a | ∀ i : S, a i.1 = x i}).toReal + +def marginalGeneratingValue {I : Type u_9} (μ : ProbabilityMeasure (I → Bool)) + (S : Finset I) (z : S → ℂ) : ℂ := by + classical + exact ∑ x : S → Bool, + (marginalMass μ S x : ℂ) * + ∏ i : S, if x i = true then z i else 1 + +def StronglyRayleighCountable {I : Type u_10} + (μ : ProbabilityMeasure (I → Bool)) : Prop := + ∀ S : Finset I, ∀ z : S → ℂ, + (∀ i : S, 0 < (z i).im) → marginalGeneratingValue μ S z ≠ 0 + +def boolReal (b : Bool) : ℝ := if b = true then 1 else 0 + +def tiltPartition {F : Type u_11} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) : ℝ := by + classical + exact ∑ x : F → Bool, + Real.exp (∑ j : F, h j * boolReal (x j)) * + ((μ : Measure (F → Bool)) {x}).toReal + +def tiltMean {F : Type u_12} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i : F) : ℝ := by + classical + exact (∑ x : F → Bool, + Real.exp (∑ j : F, h j * boolReal (x j)) * + ((μ : Measure (F → Bool)) {x}).toReal * boolReal (x i)) / + tiltPartition μ h + +def tiltSecondMoment {F : Type u_13} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i j : F) : ℝ := by + classical + exact (∑ x : F → Bool, + Real.exp (∑ k : F, h k * boolReal (x k)) * + ((μ : Measure (F → Bool)) {x}).toReal * + boolReal (x i) * boolReal (x j)) / + tiltPartition μ h + +def tiltCovariance {F : Type u_14} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i j : F) : ℝ := + tiltSecondMoment μ h i j - tiltMean μ h i * tiltMean μ h j + +def coordinatePerturb {F : Type u_15} (h : F → ℝ) (j : F) (r : ℝ) : F → ℝ := by + classical + exact fun k => h k + if k = j then r else 0 + +def PositiveContractionFinite {F : Type u_16} [Fintype F] + (K : F → F → ℂ) : Prop := + (∀ i j, K i j = conj (K j i)) ∧ + ∀ c : F → ℂ, + 0 ≤ (∑ i : F, ∑ j : F, conj (c i) * K i j * c j).re ∧ + (∑ i : F, ∑ j : F, conj (c i) * K i j * c j).re ≤ + ∑ i : F, Complex.normSq (c i) + +def IsFiniteDeterminantalLaw {F : Type u_17} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (K : F → F → ℂ) : Prop := by + classical + exact ∀ A : Finset F, + (((μ : Measure (F → Bool)) {x | ∀ i ∈ A, x i = true}).toReal : ℂ) = + Matrix.det (fun i j : A => K i.1 j.1) + +def PositiveContractionKernel {I : Type u_18} + (K : I → I → ℂ) : Prop := + (∀ i j, K i j = conj (K j i)) ∧ + ∀ (S : Finset I) (c : S → ℂ), + 0 ≤ (∑ i : S, ∑ j : S, conj (c i) * K i.1 j.1 * c j).re ∧ + (∑ i : S, ∑ j : S, conj (c i) * K i.1 j.1 * c j).re ≤ + ∑ i : S, Complex.normSq (c i) + +def IsDeterminantalLaw {I : Type u_19} + (μ : ProbabilityMeasure (I → Bool)) (K : I → I → ℂ) : Prop := by + classical + exact ∀ A : Finset I, + (((μ : Measure (I → Bool)) {x | ∀ i ∈ A, x i = true}).toReal : ℂ) = + Matrix.det (fun i j : A => K i.1 j.1) + +def TranslationInvariantKernel {Γ : Type u_20} [Group Γ] + (K : Γ → Γ → ℂ) : Prop := + ∀ g h k : Γ, K (g * h) (g * k) = K h k + +theorem finite_strongly_rayleigh_response : + ∀ (F : Type u_1) [Fintype F] [Nonempty F] (μ : ProbabilityMeasure (F → Bool)), + StronglyRayleighFinite μ → + (∀ (i j : F) (h : F → ℝ), + HasDerivAt (fun r : ℝ => tiltMean μ (coordinatePerturb h j r) i) + (tiltCovariance μ h i j) 0) ∧ + (∀ (i : F) (h : F → ℝ), + (∑ j : F, |tiltCovariance μ h i j|) ≤ + 2 * tiltMean μ h i * (1 - tiltMean μ h i) ∧ + 2 * tiltMean μ h i * (1 - tiltMean μ h i) ≤ (1 : ℝ) / 2) ∧ + (∀ (i : F) (h h' : F → ℝ) (D : ℝ), + 0 ≤ D → (∀ j : F, |h j - h' j| ≤ D) → + |tiltMean μ h i - tiltMean μ h' i| ≤ D / 2) := by + sorry + +theorem strongly_rayleigh_group_factor : + ∀ (Γ : Type u_2) [Group Γ] [Countable Γ] [MeasurableSpace Γ], + ∀ μ : ProbabilityMeasure (Γ → Bool), + StronglyRayleighCountable μ → InvariantBinaryLaw μ → HasEquivariantIIDFactor μ := by + sorry + +theorem finite_positive_contraction_dpp_is_strongly_rayleigh : + ∀ (F : Type u_3) [Fintype F] [Nonempty F] (K : F → F → ℂ), + PositiveContractionFinite K → + (∃ μ : ProbabilityMeasure (F → Bool), IsFiniteDeterminantalLaw μ K) ∧ + ∀ μ : ProbabilityMeasure (F → Bool), IsFiniteDeterminantalLaw μ K → + StronglyRayleighFinite μ := by + sorry + +theorem countable_positive_contraction_dpp_exists_unique : + ∀ (I : Type u_4) [Countable I] (K : I → I → ℂ), + PositiveContractionKernel K → + ∃! μ : ProbabilityMeasure (I → Bool), IsDeterminantalLaw μ K := by + sorry + +theorem invariant_positive_contraction_dpp_factor : + ∀ (Γ : Type u_5) [Group Γ] [Countable Γ] [MeasurableSpace Γ] + (K : Γ → Γ → ℂ) (μ : ProbabilityMeasure (Γ → Bool)), + PositiveContractionKernel K → IsDeterminantalLaw μ K → + InvariantBinaryLaw μ → HasEquivariantIIDFactor μ := by + sorry + +theorem translation_invariant_kernel_dpp_factor : + ∀ (Γ : Type u_6) [Group Γ] [Countable Γ] [MeasurableSpace Γ] (K : Γ → Γ → ℂ), + PositiveContractionKernel K → TranslationInvariantKernel K → + ∃ μ : ProbabilityMeasure (Γ → Bool), + IsDeterminantalLaw μ K ∧ InvariantBinaryLaw μ ∧ HasEquivariantIIDFactor μ := by + sorry + +end Problem336AdditiveD139 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StronglyRayleighDPP.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Problem336AdditiveD139.finite_strongly_rayleigh_response`, `OAI.Problem336AdditiveD139.strongly_rayleigh_group_factor`, `OAI.Problem336AdditiveD139.finite_positive_contraction_dpp_is_strongly_rayleigh`, `OAI.Problem336AdditiveD139.countable_positive_contraction_dpp_exists_unique`, `OAI.Problem336AdditiveD139.invariant_positive_contraction_dpp_factor`, `OAI.Problem336AdditiveD139.translation_invariant_kernel_dpp_factor` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/strongly-rayleigh-dpp/solution/closure.txt b/tasks/strongly-rayleigh-dpp/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d27060c3c7aca5adcf1a433a2220f260e1e9337e --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/solution/closure.txt @@ -0,0 +1,107 @@ +OAI.Probability.StrongRayleigh.AffineSlopeStability +OAI.Probability.StrongRayleigh.AsymptoticReadout +OAI.Probability.StrongRayleigh.BinaryProjective +OAI.Probability.StrongRayleigh.BivariateStability +OAI.Probability.StrongRayleigh.BrownianBridge +OAI.Probability.StrongRayleigh.BrownianBridgeSignal +OAI.Probability.StrongRayleigh.BrownianContinuability +OAI.Probability.StrongRayleigh.BrownianExistence +OAI.Probability.StrongRayleigh.BrownianKolmogorov +OAI.Probability.StrongRayleigh.BrownianObservationSufficiency +OAI.Probability.StrongRayleigh.BrownianPathLaw +OAI.Probability.StrongRayleigh.BrownianStochasticContinuity +OAI.Probability.StrongRayleigh.BrownianSublinear +OAI.Probability.StrongRayleigh.CanonicalInnovationSampler +OAI.Probability.StrongRayleigh.CantorProjective +OAI.Probability.StrongRayleigh.CharacteristicLaw +OAI.Probability.StrongRayleigh.CharacteristicTaylor +OAI.Probability.StrongRayleigh.ConditionalTaylor +OAI.Probability.StrongRayleigh.ContinuousModification +OAI.Probability.StrongRayleigh.ContinuousPathLaw +OAI.Probability.StrongRayleigh.CountableAssembly +OAI.Probability.StrongRayleigh.CovarianceRow +OAI.Probability.StrongRayleigh.DPPReindex +OAI.Probability.StrongRayleigh.DecoderUniqueness +OAI.Probability.StrongRayleigh.DensePathExtension +OAI.Probability.StrongRayleigh.DensityBayes +OAI.Probability.StrongRayleigh.DeterminantalUniqueness +OAI.Probability.StrongRayleigh.DyadicTail +OAI.Probability.StrongRayleigh.DyadicTimes +OAI.Probability.StrongRayleigh.ElementaryResponse +OAI.Probability.StrongRayleigh.FiniteDPPExistence +OAI.Probability.StrongRayleigh.FiniteDPPGenerating +OAI.Probability.StrongRayleigh.FiniteDPPStability +OAI.Probability.StrongRayleigh.FiniteDPPWeights +OAI.Probability.StrongRayleigh.FiniteEndpointPosterior +OAI.Probability.StrongRayleigh.FiniteFieldTilt +OAI.Probability.StrongRayleigh.FiniteGaussianCharacteristic +OAI.Probability.StrongRayleigh.FiniteMarginal +OAI.Probability.StrongRayleigh.FiniteMarginalObservation +OAI.Probability.StrongRayleigh.FiniteResponseAssembly +OAI.Probability.StrongRayleigh.GaussianMomentBounds +OAI.Probability.StrongRayleigh.GaussianObservation +OAI.Probability.StrongRayleigh.GaussianPerturbation +OAI.Probability.StrongRayleigh.GeneratingSlice +OAI.Probability.StrongRayleigh.GroupBrownianPosterior +OAI.Probability.StrongRayleigh.GroupDrift +OAI.Probability.StrongRayleigh.GroupDriftPosterior +OAI.Probability.StrongRayleigh.GroupExhaustion +OAI.Probability.StrongRayleigh.GroupFactorProof +OAI.Probability.StrongRayleigh.GroupInnovationInverse +OAI.Probability.StrongRayleigh.GroupSampler +OAI.Probability.StrongRayleigh.IIDAction +OAI.Probability.StrongRayleigh.IIDNoiseIncrements +OAI.Probability.StrongRayleigh.InclusionUniqueness +OAI.Probability.StrongRayleigh.IndependentAtomObservation +OAI.Probability.StrongRayleigh.IndependentConditioning +OAI.Probability.StrongRayleigh.InnovationAdapted +OAI.Probability.StrongRayleigh.InnovationCharacteristic +OAI.Probability.StrongRayleigh.InnovationCharacteristicProcess +OAI.Probability.StrongRayleigh.InnovationContinuity +OAI.Probability.StrongRayleigh.InnovationCorrection +OAI.Probability.StrongRayleigh.InnovationErrorScale +OAI.Probability.StrongRayleigh.InnovationFiniteLaw +OAI.Probability.StrongRayleigh.InnovationInverse +OAI.Probability.StrongRayleigh.InnovationMean +OAI.Probability.StrongRayleigh.InnovationPathCriterion +OAI.Probability.StrongRayleigh.InnovationProcessLaw +OAI.Probability.StrongRayleigh.InnovationSampler +OAI.Probability.StrongRayleigh.LimsupDrift +OAI.Probability.StrongRayleigh.LocalCharacteristicBrownian +OAI.Probability.StrongRayleigh.LocalDyadicContinuity +OAI.Probability.StrongRayleigh.LocalInnovation +OAI.Probability.StrongRayleigh.Main +OAI.Probability.StrongRayleigh.MarginalBase +OAI.Probability.StrongRayleigh.MarginalBridge +OAI.Probability.StrongRayleigh.MatrixStability +OAI.Probability.StrongRayleigh.MixedDeterminant +OAI.Probability.StrongRayleigh.Model +OAI.Probability.StrongRayleigh.NoisePastIndependence +OAI.Probability.StrongRayleigh.ObservationHistory +OAI.Probability.StrongRayleigh.ObservationNoise +OAI.Probability.StrongRayleigh.ObservationNoiseReal +OAI.Probability.StrongRayleigh.PairCoefficients +OAI.Probability.StrongRayleigh.PathRealization +OAI.Probability.StrongRayleigh.PathSamplerTransfer +OAI.Probability.StrongRayleigh.PerturbedMoments +OAI.Probability.StrongRayleigh.PickSquareRoot +OAI.Probability.StrongRayleigh.PolynomialPick +OAI.Probability.StrongRayleigh.PosteriorLimit +OAI.Probability.StrongRayleigh.PreBrownianExistence +OAI.Probability.StrongRayleigh.RayleighOffDiagonal +OAI.Probability.StrongRayleigh.RayleighResponse +OAI.Probability.StrongRayleigh.ReferenceGroupPosterior +OAI.Probability.StrongRayleigh.ReferenceInnovationLaw +OAI.Probability.StrongRayleigh.ReferenceObservation +OAI.Probability.StrongRayleigh.ResponseDerivative +OAI.Probability.StrongRayleigh.ResponseDirectional +OAI.Probability.StrongRayleigh.ResponseLipschitz +OAI.Probability.StrongRayleigh.RightHalfPlaneDerivative +OAI.Probability.StrongRayleigh.StableUnivariate +OAI.Probability.StrongRayleigh.StableWronskian +OAI.Probability.StrongRayleigh.TiltPartition +OAI.Probability.StrongRayleigh.TiltScaling +OAI.Probability.StrongRayleigh.Translation +OAI.Probability.StrongRayleigh.TranslationAssembly +OAI.Probability.StrongRayleigh.TwoCoordinateCoefficients +OAI.Probability.StrongRayleigh.WeightedLocalInnovation diff --git a/tasks/strongly-rayleigh-dpp/solution/reference.py b/tasks/strongly-rayleigh-dpp/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/strongly-rayleigh-dpp/solution/solve.sh b/tasks/strongly-rayleigh-dpp/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3ba31b6a39cf5129425d7ead6ecd3f4aba725579 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StronglyRayleighDPP, i.e. module OAI.Probability.StrongRayleigh.Main and the +# 107 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.StrongRayleigh.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StronglyRayleighDPP" diff --git a/tasks/strongly-rayleigh-dpp/task.toml b/tasks/strongly-rayleigh-dpp/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..49ad744096dc83ddc0fdc70476a79e53329354d7 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/strongly-rayleigh-dpp" +version = "1.0.0" +description = "Prove StronglyRayleighDPP (openai/math family 231: The free uniform spanning forest is a factor of IID) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StronglyRayleighDPP.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StronglyRayleighDPP" +family = "231" +family_title = "The free uniform spanning forest is a factor of IID" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Problem336AdditiveD139.finite_strongly_rayleigh_response", "OAI.Problem336AdditiveD139.strongly_rayleigh_group_factor", "OAI.Problem336AdditiveD139.finite_positive_contraction_dpp_is_strongly_rayleigh", "OAI.Problem336AdditiveD139.countable_positive_contraction_dpp_exists_unique", "OAI.Problem336AdditiveD139.invariant_positive_contraction_dpp_factor", "OAI.Problem336AdditiveD139.translation_invariant_kernel_dpp_factor"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.StrongRayleigh.Main" +reference_modules = 107 +reference_lean_bytes = 512357 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 889 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12161 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/strongly-rayleigh-dpp/tests/Challenge.lean b/tasks/strongly-rayleigh-dpp/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..a5cab657dc116acf07acffa602fa1f1ac1f3f67e --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/tests/Challenge.lean @@ -0,0 +1,185 @@ +import Mathlib + +namespace OAI + +universe u_1 u_2 u_3 u_4 u_5 u_6 u_7 u_8 u_9 u_10 u_11 u_12 +universe u_13 u_14 u_15 u_16 u_17 u_18 u_19 u_20 + +noncomputable section + +open MeasureTheory +open scoped BigOperators ENNReal Topology ComplexConjugate + +namespace Problem336AdditiveD139 + +abbrev UnitLabel := Set.Icc (0 : ℝ) 1 + +def leftTranslate {Γ : Type u_1} {α : Type u_2} [Group Γ] (g : Γ) (a : Γ → α) : Γ → α := + fun h => a (g⁻¹ * h) + +def iidUnitLabels (Γ : Type u_3) [MeasurableSpace Γ] : Measure (Γ → UnitLabel) := + Measure.infinitePi (fun _ : Γ => (volume : Measure UnitLabel)) + +def InvariantBinaryLaw {Γ : Type u_4} [Group Γ] + (μ : ProbabilityMeasure (Γ → Bool)) : Prop := + ∀ g : Γ, + Measure.map (leftTranslate g) (μ : Measure (Γ → Bool)) = + (μ : Measure (Γ → Bool)) + +def HasEquivariantIIDFactor {Γ : Type u_5} [Group Γ] [MeasurableSpace Γ] + (μ : ProbabilityMeasure (Γ → Bool)) : Prop := + ∃ Phi : (Γ → UnitLabel) → (Γ → Bool), + Measurable Phi ∧ + (∀ (g : Γ) (u : Γ → UnitLabel), + Phi (leftTranslate g u) = leftTranslate g (Phi u)) ∧ + Measure.map Phi (iidUnitLabels Γ) = (μ : Measure (Γ → Bool)) + +def finiteGeneratingValue {F : Type u_6} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (z : F → ℂ) : ℂ := by + classical + exact ∑ x : F → Bool, + (((μ : Measure (F → Bool)) {x}).toReal : ℂ) * + ∏ i : F, if x i = true then z i else 1 + +def StronglyRayleighFinite {F : Type u_7} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) : Prop := + ∀ z : F → ℂ, (∀ i : F, 0 < (z i).im) → finiteGeneratingValue μ z ≠ 0 + +def marginalMass {I : Type u_8} (μ : ProbabilityMeasure (I → Bool)) + (S : Finset I) (x : S → Bool) : ℝ := + ((μ : Measure (I → Bool)) {a | ∀ i : S, a i.1 = x i}).toReal + +def marginalGeneratingValue {I : Type u_9} (μ : ProbabilityMeasure (I → Bool)) + (S : Finset I) (z : S → ℂ) : ℂ := by + classical + exact ∑ x : S → Bool, + (marginalMass μ S x : ℂ) * + ∏ i : S, if x i = true then z i else 1 + +def StronglyRayleighCountable {I : Type u_10} + (μ : ProbabilityMeasure (I → Bool)) : Prop := + ∀ S : Finset I, ∀ z : S → ℂ, + (∀ i : S, 0 < (z i).im) → marginalGeneratingValue μ S z ≠ 0 + +def boolReal (b : Bool) : ℝ := if b = true then 1 else 0 + +def tiltPartition {F : Type u_11} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) : ℝ := by + classical + exact ∑ x : F → Bool, + Real.exp (∑ j : F, h j * boolReal (x j)) * + ((μ : Measure (F → Bool)) {x}).toReal + +def tiltMean {F : Type u_12} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i : F) : ℝ := by + classical + exact (∑ x : F → Bool, + Real.exp (∑ j : F, h j * boolReal (x j)) * + ((μ : Measure (F → Bool)) {x}).toReal * boolReal (x i)) / + tiltPartition μ h + +def tiltSecondMoment {F : Type u_13} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i j : F) : ℝ := by + classical + exact (∑ x : F → Bool, + Real.exp (∑ k : F, h k * boolReal (x k)) * + ((μ : Measure (F → Bool)) {x}).toReal * + boolReal (x i) * boolReal (x j)) / + tiltPartition μ h + +def tiltCovariance {F : Type u_14} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (h : F → ℝ) (i j : F) : ℝ := + tiltSecondMoment μ h i j - tiltMean μ h i * tiltMean μ h j + +def coordinatePerturb {F : Type u_15} (h : F → ℝ) (j : F) (r : ℝ) : F → ℝ := by + classical + exact fun k => h k + if k = j then r else 0 + +def PositiveContractionFinite {F : Type u_16} [Fintype F] + (K : F → F → ℂ) : Prop := + (∀ i j, K i j = conj (K j i)) ∧ + ∀ c : F → ℂ, + 0 ≤ (∑ i : F, ∑ j : F, conj (c i) * K i j * c j).re ∧ + (∑ i : F, ∑ j : F, conj (c i) * K i j * c j).re ≤ + ∑ i : F, Complex.normSq (c i) + +def IsFiniteDeterminantalLaw {F : Type u_17} [Fintype F] + (μ : ProbabilityMeasure (F → Bool)) (K : F → F → ℂ) : Prop := by + classical + exact ∀ A : Finset F, + (((μ : Measure (F → Bool)) {x | ∀ i ∈ A, x i = true}).toReal : ℂ) = + Matrix.det (fun i j : A => K i.1 j.1) + +def PositiveContractionKernel {I : Type u_18} + (K : I → I → ℂ) : Prop := + (∀ i j, K i j = conj (K j i)) ∧ + ∀ (S : Finset I) (c : S → ℂ), + 0 ≤ (∑ i : S, ∑ j : S, conj (c i) * K i.1 j.1 * c j).re ∧ + (∑ i : S, ∑ j : S, conj (c i) * K i.1 j.1 * c j).re ≤ + ∑ i : S, Complex.normSq (c i) + +def IsDeterminantalLaw {I : Type u_19} + (μ : ProbabilityMeasure (I → Bool)) (K : I → I → ℂ) : Prop := by + classical + exact ∀ A : Finset I, + (((μ : Measure (I → Bool)) {x | ∀ i ∈ A, x i = true}).toReal : ℂ) = + Matrix.det (fun i j : A => K i.1 j.1) + +def TranslationInvariantKernel {Γ : Type u_20} [Group Γ] + (K : Γ → Γ → ℂ) : Prop := + ∀ g h k : Γ, K (g * h) (g * k) = K h k + +theorem finite_strongly_rayleigh_response : + ∀ (F : Type u_1) [Fintype F] [Nonempty F] (μ : ProbabilityMeasure (F → Bool)), + StronglyRayleighFinite μ → + (∀ (i j : F) (h : F → ℝ), + HasDerivAt (fun r : ℝ => tiltMean μ (coordinatePerturb h j r) i) + (tiltCovariance μ h i j) 0) ∧ + (∀ (i : F) (h : F → ℝ), + (∑ j : F, |tiltCovariance μ h i j|) ≤ + 2 * tiltMean μ h i * (1 - tiltMean μ h i) ∧ + 2 * tiltMean μ h i * (1 - tiltMean μ h i) ≤ (1 : ℝ) / 2) ∧ + (∀ (i : F) (h h' : F → ℝ) (D : ℝ), + 0 ≤ D → (∀ j : F, |h j - h' j| ≤ D) → + |tiltMean μ h i - tiltMean μ h' i| ≤ D / 2) := by + sorry + +theorem strongly_rayleigh_group_factor : + ∀ (Γ : Type u_2) [Group Γ] [Countable Γ] [MeasurableSpace Γ], + ∀ μ : ProbabilityMeasure (Γ → Bool), + StronglyRayleighCountable μ → InvariantBinaryLaw μ → HasEquivariantIIDFactor μ := by + sorry + +theorem finite_positive_contraction_dpp_is_strongly_rayleigh : + ∀ (F : Type u_3) [Fintype F] [Nonempty F] (K : F → F → ℂ), + PositiveContractionFinite K → + (∃ μ : ProbabilityMeasure (F → Bool), IsFiniteDeterminantalLaw μ K) ∧ + ∀ μ : ProbabilityMeasure (F → Bool), IsFiniteDeterminantalLaw μ K → + StronglyRayleighFinite μ := by + sorry + +theorem countable_positive_contraction_dpp_exists_unique : + ∀ (I : Type u_4) [Countable I] (K : I → I → ℂ), + PositiveContractionKernel K → + ∃! μ : ProbabilityMeasure (I → Bool), IsDeterminantalLaw μ K := by + sorry + +theorem invariant_positive_contraction_dpp_factor : + ∀ (Γ : Type u_5) [Group Γ] [Countable Γ] [MeasurableSpace Γ] + (K : Γ → Γ → ℂ) (μ : ProbabilityMeasure (Γ → Bool)), + PositiveContractionKernel K → IsDeterminantalLaw μ K → + InvariantBinaryLaw μ → HasEquivariantIIDFactor μ := by + sorry + +theorem translation_invariant_kernel_dpp_factor : + ∀ (Γ : Type u_6) [Group Γ] [Countable Γ] [MeasurableSpace Γ] (K : Γ → Γ → ℂ), + PositiveContractionKernel K → TranslationInvariantKernel K → + ∃ μ : ProbabilityMeasure (Γ → Bool), + IsDeterminantalLaw μ K ∧ InvariantBinaryLaw μ ∧ HasEquivariantIIDFactor μ := by + sorry + +end Problem336AdditiveD139 + +end + +end OAI diff --git a/tasks/strongly-rayleigh-dpp/tests/grade.py b/tasks/strongly-rayleigh-dpp/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/strongly-rayleigh-dpp/tests/task.json b/tasks/strongly-rayleigh-dpp/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ef65b5ba01b551815996656fd2e41bf06a89b56d --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/tests/task.json @@ -0,0 +1,20 @@ +{ + "challenge": "StronglyRayleighDPP", + "comparator": { + "theorem_names": [ + "OAI.Problem336AdditiveD139.finite_strongly_rayleigh_response", + "OAI.Problem336AdditiveD139.strongly_rayleigh_group_factor", + "OAI.Problem336AdditiveD139.finite_positive_contraction_dpp_is_strongly_rayleigh", + "OAI.Problem336AdditiveD139.countable_positive_contraction_dpp_exists_unique", + "OAI.Problem336AdditiveD139.invariant_positive_contraction_dpp_factor", + "OAI.Problem336AdditiveD139.translation_invariant_kernel_dpp_factor" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11261 +} \ No newline at end of file diff --git a/tasks/strongly-rayleigh-dpp/tests/test.sh b/tasks/strongly-rayleigh-dpp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/strongly-rayleigh-dpp/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/structural-crouzeix/environment/Dockerfile b/tasks/structural-crouzeix/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/structural-crouzeix/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/structural-crouzeix/environment/fetch_mathlib.sh b/tasks/structural-crouzeix/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/structural-crouzeix/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/structural-crouzeix/environment/lake-manifest.json b/tasks/structural-crouzeix/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/structural-crouzeix/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/structural-crouzeix/environment/lakefile.lean b/tasks/structural-crouzeix/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/structural-crouzeix/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/structural-crouzeix/environment/lean_setup.sh b/tasks/structural-crouzeix/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/structural-crouzeix/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/structural-crouzeix/environment/pack_submission.py b/tasks/structural-crouzeix/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/structural-crouzeix/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/structural-crouzeix/instruction.md b/tasks/structural-crouzeix/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8832d886b0bad1506d33c921e327e4bfc8869aa4 --- /dev/null +++ b/tasks/structural-crouzeix/instruction.md @@ -0,0 +1,267 @@ +# openai/math challenge `StructuralCrouzeix` (family 325) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 325 of the release, *The complete Crouzeix conjecture* +(Functional analysis). The family as a whole: Resolves the complete Crouzeix conjecture: for every bounded operator $A$ on a complex Hilbert space and every finite matrix-valued polynomial $P$, one has $\lVert P[A]\rVert\le2\sup_{z\in W(A)}\lVert P(z)\rVert$, where $W(A)$ is the numerical range. The constant $2$ is sharp, independent of the matrix size, and valid in infinite dimensions. + +The challenge is `StructuralCrouzeix`, also at `/opt/openai-math/challenges/StructuralCrouzeix.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u_61 u_63 u_67 u_83 u_84 u_181 + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder + +namespace CompleteCrouzeix + + + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ x : EuclideanSpace ℂ (Fin n), ‖x‖ = 1 ∧ + inner ℂ x (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A x) = z} + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Set Filter Metric Complex +open scoped Topology + + +structure DiskCoordinate (U : Set ℂ) (a : ℂ) where + outer : Set ℂ + outer_open : IsOpen outer + closure_subset : closure U ⊆ outer + toDisk : ℂ → ℂ + fromDisk : ℂ → ℂ + analytic_to : AnalyticOnNhd ℂ toDisk outer + injective_to : InjOn toDisk outer + noncritical_to : ∀ z ∈ outer, deriv toDisk z ≠ 0 + image_open : IsOpen (toDisk '' outer) + analytic_from : AnalyticOnNhd ℂ fromDisk (toDisk '' outer) + inverse_map : MapsTo fromDisk (toDisk '' outer) outer + left_inverse : ∀ z ∈ outer, fromDisk (toDisk z) = z + right_inverse : ∀ w ∈ toDisk '' outer, toDisk (fromDisk w) = w + closedDisk_subset : closedBall 0 1 ⊆ toDisk '' outer + image_domain : toDisk '' U = ball 0 1 + base_zero : toDisk a = 0 + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Set Filter Metric Complex +open scoped Topology + + +def exteriorMap (a b : ℂ) (h : ℂ → ℂ) (t : ℂ) : ℂ := a*t+b+h t⁻¹ + +structure ExteriorCoordinate (U : Set ℂ) where + radius : ℝ + radius_gt : 1 < radius + leading : ℂ + constant : ℂ + regular : ℂ → ℂ + leading_ne : leading ≠ 0 + analytic_regular : AnalyticOnNhd ℂ regular (ball 0 radius) + injective : InjOn (exteriorMap leading constant regular) {t | radius⁻¹ < ‖t‖} + noncritical : ∀ t, radius⁻¹ < ‖t‖ → deriv (exteriorMap leading constant regular) t ≠ 0 + boundary_image : exteriorMap leading constant regular '' sphere 0 1 = frontier U + interior_iff : ∀ t, radius⁻¹ < ‖t‖ → + (exteriorMap leading constant regular t ∈ U ↔ t ∈ ball 0 1) + outside : ∀ t, 1 < ‖t‖ → exteriorMap leading constant regular t ∉ closure U + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Polynomial Finset +variable {A : Type u_61} [Ring A] [Algebra ℂ A] + +def scalarJetEval (β : ℂ) (N : A) (s : ℕ) (f : ℂ → ℂ) : A := + ∑ i ∈ range s, (iteratedDeriv i f β / (i.factorial : ℂ)) • N ^ i + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Module Set +open scoped DirectSum +variable {V : Type u_63} [AddCommGroup V] [Module ℂ V] [instFiniteDimensionalℂV : FiniteDimensional ℂ V] + +noncomputable def primaryEquiv (T : Module.End ℂ V) : + V ≃ₗ[ℂ] ⨁ β : ℂ, T.maxGenEigenspace β := by + classical + exact (LinearEquiv.ofBijective (DirectSum.coeLinearMap T.maxGenEigenspace) + (DirectSum.isInternal_submodule_of_iSupIndep_of_iSup_eq_top + T.independent_maxGenEigenspace T.iSup_maxGenEigenspace_eq_top)).symm + +noncomputable def primaryNilpotent (T : Module.End ℂ V) (β : ℂ) : + Module.End ℂ (T.maxGenEigenspace β) := + (T - algebraMap ℂ (Module.End ℂ V) β).restrict + (fun x hx => T.mapsTo_maxGenEigenspace_of_comm + (Algebra.mul_sub_algebraMap_commutes T β) β (show x ∈ T.maxGenEigenspace β from hx)) + +noncomputable def primaryEval (T : Module.End ℂ V) (f : ℂ → ℂ) : Module.End ℂ V := + (primaryEquiv T).symm.toLinearMap ∘ₗ + (DirectSum.lmap fun β => scalarJetEval β (primaryNilpotent T β) (finrank ℂ V) f) ∘ₗ + (primaryEquiv T).toLinearMap + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Filter Topology Set Module +variable {n : Type u_67} [Fintype n] [DecidableEq n] + +noncomputable def matrixAnalyticEval (A : Matrix n n ℂ) (f : ℂ → ℂ) : Matrix n n ℂ := + Matrix.toLinAlgEquiv'.symm (primaryEval (Matrix.toLinAlgEquiv' A) f) + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open scoped ENNReal NNReal Matrix.Norms.L2Operator MatrixOrder Kronecker +variable {n : Type u_83} {m : Type u_84} [Fintype n] [DecidableEq n] [instFintypeM : Fintype m] [instDecidableEqM : DecidableEq m] + +def completeAnalyticEval (D : Matrix n n ℂ) (F : ℂ → Matrix m m ℂ) : + Matrix (n×m) (n×m) ℂ := + fun i j => matrixAnalyticEval D (fun z => F z i.2 j.2) i.1 j.1 + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open scoped Matrix MatrixOrder +variable {n : Type u_181} [Fintype n] [DecidableEq n] [Nonempty n] + +def MetricFeasible (T : Matrix n n ℂ) (τ : ℝ) (H : Matrix n n ℂ) : Prop := + 1 ≤ H ∧ H ≤ algebraMap ℝ (Matrix n n ℂ) τ ∧ Tᴴ * H * T ≤ H + +end CompleteCrouzeix + +end + +noncomputable section +open Set Filter Metric Complex MeasureTheory +open scoped Matrix Topology ComplexConjugate ComplexOrder MatrixOrder + Matrix.Norms.L2Operator Kronecker + +namespace StructuralCrouzeix +open CompleteCrouzeix + +def RegularAnalyticBoundaryAt (U : Set ℂ) (p : ℂ) : Prop := + ∃ χ : ℂ → ℂ, χ 0 = p ∧ AnalyticAt ℂ χ 0 ∧ deriv χ 0 ≠ 0 ∧ + (∀ᶠ z : ℂ in 𝓝 0, χ z ∈ frontier U ↔ z.im = 0) + +structure IsAdmissible (U : Set ℂ) : Prop where + isOpen : IsOpen U + bounded : Bornology.IsBounded U + convex : Convex ℝ U + nonempty : U.Nonempty + jordan : Nonempty (Circle ≃ₜ ↥(frontier U)) + regular : ∀ p ∈ frontier U, RegularAnalyticBoundaryAt U p + +def IsMinimizing {n : ℕ} (T : Matrix (Fin n) (Fin n) ℂ) + (τ : ℝ) (H : Matrix (Fin n) (Fin n) ℂ) : Prop := + MetricFeasible T τ H ∧ + ∀ (σ : ℝ) (J : Matrix (Fin n) (Fin n) ℂ), + MetricFeasible T σ J → τ ≤ σ + +def StrictlyFeasible {n : ℕ} (T : Matrix (Fin n) (Fin n) ℂ) : Prop := + ∃ (τ : ℝ) (H : Matrix (Fin n) (Fin n) ℂ), H.IsHermitian ∧ + (H - 1).PosDef ∧ + (algebraMap ℝ (Matrix (Fin n) (Fin n) ℂ) τ - H).PosDef ∧ + (H - Tᴴ * H * T).PosDef + +def analyticSupNorm {m : ℕ} (U : Set ℂ) + (v : ℂ → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖v z‖) '' closure U) + +def boundaryPoint {U : Set ℂ} (G : ExteriorCoordinate U) (t : UnitAddCircle) : ℂ := + exteriorMap G.leading G.constant G.regular (t.toCircle : ℂ) + +def FullEndpoint : Prop := + ∀ (U : Set ℂ), IsAdmissible U → + (∀ a ∈ U, Nonempty (DiskCoordinate U a)) ∧ + Nonempty (ExteriorCoordinate U) ∧ + ∀ (a : ℂ), a ∈ U → ∀ (f : DiskCoordinate U a) (G : ExteriorCoordinate U), + ∀ (n : ℕ), 0 < n → ∀ (A : Matrix (Fin n) (Fin n) ℂ), + numericalRange A ⊆ U → + let T := matrixAnalyticEval A f.toDisk + StrictlyFeasible T ∧ + ∃ κ : ℝ, 1 ≤ κ ∧ κ ≤ 2 ∧ + (∃ H : Matrix (Fin n) (Fin n) ℂ, IsMinimizing T (κ ^ 2) H) ∧ + ∀ H : Matrix (Fin n) (Fin n) ℂ, IsMinimizing T (κ ^ 2) H → + let S := CFC.sqrt H + let A' := S * A * S⁻¹ + let D := S * T * S⁻¹ + H.PosDef ∧ IsUnit S ∧ + D = matrixAnalyticEval A' f.toDisk ∧ + Dᴴ * D ≤ 1 ∧ spectralRadius ℂ D < 1 ∧ + ‖S‖ * ‖S⁻¹‖ = κ ∧ + (∀ R : Matrix (Fin n) (Fin n) ℂ, IsUnit R → + (R * T * R⁻¹)ᴴ * (R * T * R⁻¹) ≤ 1 → + κ ≤ ‖R‖ * ‖R⁻¹‖) ∧ + ∃ Λ : C(UnitAddCircle, Matrix (Fin n) (Fin n) ℂ), + (∀ t, (Λ t).PosSemidef) ∧ + (∫ t, Λ t ∂AddCircle.haarAddCircle) = 1 ∧ + ∀ (m : ℕ), 0 < m → + ∀ v : ℂ → Matrix (Fin m) (Fin m) ℂ, + AnalyticOnNhd ℂ v (closure U) → + completeAnalyticEval A' v = + (∫ t, Λ t ⊗ₖ v (boundaryPoint G t) ∂AddCircle.haarAddCircle) ∧ + ‖completeAnalyticEval A v‖ ≤ κ * analyticSupNorm U v + +end StructuralCrouzeix +end + +namespace StructuralCrouzeixReference + +/-- Intrinsic structural representation and admissibility of the unit disk. -/ +theorem challenge : StructuralCrouzeix.FullEndpoint ∧ + StructuralCrouzeix.IsAdmissible (Metric.ball (0 : ℂ) 1) := by + sorry + +end StructuralCrouzeixReference + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/StructuralCrouzeix.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.StructuralCrouzeixReference.challenge` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/structural-crouzeix/solution/closure.txt b/tasks/structural-crouzeix/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bdb365fbc15b34929eca41f59a3a6ecf2b2fe2ab --- /dev/null +++ b/tasks/structural-crouzeix/solution/closure.txt @@ -0,0 +1,60 @@ +OAI.Analysis.NumericalRange.AnalyticCharts +OAI.Analysis.NumericalRange.BoundaryCalculus +OAI.Analysis.NumericalRange.BoundaryNormals +OAI.Analysis.NumericalRange.BoundaryRepresentation +OAI.Analysis.NumericalRange.CauchyEvaluation +OAI.Analysis.NumericalRange.CauchyProjection +OAI.Analysis.NumericalRange.CircleIntegrals +OAI.Analysis.NumericalRange.CompleteResolvent +OAI.Analysis.NumericalRange.ConformalGluing +OAI.Analysis.NumericalRange.ConformalJacobian +OAI.Analysis.NumericalRange.ConformalWinding +OAI.Analysis.NumericalRange.ConvexBarrier +OAI.Analysis.NumericalRange.ConvexExterior +OAI.Analysis.NumericalRange.Convexity +OAI.Analysis.NumericalRange.DensityAdjoints +OAI.Analysis.NumericalRange.DensityComparison +OAI.Analysis.NumericalRange.DensityIdentification +OAI.Analysis.NumericalRange.DensityTransport +OAI.Analysis.NumericalRange.DilationDensity +OAI.Analysis.NumericalRange.DiskCalculus +OAI.Analysis.NumericalRange.DiskMapping +OAI.Analysis.NumericalRange.DomainBound +OAI.Analysis.NumericalRange.DomainCalculus +OAI.Analysis.NumericalRange.DualSeparation +OAI.Analysis.NumericalRange.ExteriorKernel +OAI.Analysis.NumericalRange.ExteriorProjection +OAI.Analysis.NumericalRange.FourierExtension +OAI.Analysis.NumericalRange.FourierResolution +OAI.Analysis.NumericalRange.HerglotzReflection +OAI.Analysis.NumericalRange.HilbertSchmidt +OAI.Analysis.NumericalRange.HolomorphicEvaluation +OAI.Analysis.NumericalRange.Main +OAI.Analysis.NumericalRange.MarkovOperator +OAI.Analysis.NumericalRange.MetricFeasibility +OAI.Analysis.NumericalRange.MetricNorm +OAI.Analysis.NumericalRange.Model +OAI.Analysis.NumericalRange.OptimalExtremal +OAI.Analysis.NumericalRange.OrderedDensities +OAI.Analysis.NumericalRange.OrderedMultiplication +OAI.Analysis.NumericalRange.OuterNeighborhood +OAI.Analysis.NumericalRange.PoissonBoundary +OAI.Analysis.NumericalRange.PolynomialCalculus +OAI.Analysis.NumericalRange.PositiveDensity +OAI.Analysis.NumericalRange.PulledDensity +OAI.Analysis.NumericalRange.ResolventPositivity +OAI.Analysis.NumericalRange.Sharpness +OAI.Analysis.NumericalRange.TestingAlgebra +OAI.Analysis.NumericalRange.UnitaryRealization +OAI.Analysis.StructuralCrouzeix.ClosedSide +OAI.Analysis.StructuralCrouzeix.Endpoint +OAI.Analysis.StructuralCrouzeix.ExteriorSupport +OAI.Analysis.StructuralCrouzeix.GeometryBasics +OAI.Analysis.StructuralCrouzeix.Main +OAI.Analysis.StructuralCrouzeix.Model +OAI.Analysis.StructuralCrouzeix.OptimizerAssembly +OAI.Analysis.StructuralCrouzeix.OrientBoundary +OAI.Analysis.StructuralCrouzeix.SharedDensity +OAI.Analysis.StructuralCrouzeix.SharedMaximum +OAI.Analysis.StructuralCrouzeix.SimilarityMinimum +OAI.Analysis.StructuralCrouzeix.UnitDisk diff --git a/tasks/structural-crouzeix/solution/reference.py b/tasks/structural-crouzeix/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/structural-crouzeix/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/structural-crouzeix/solution/solve.sh b/tasks/structural-crouzeix/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..536ffb3df7f71c14e9fd32eb584a51b59cfba7f6 --- /dev/null +++ b/tasks/structural-crouzeix/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of StructuralCrouzeix, i.e. module OAI.Analysis.StructuralCrouzeix.Endpoint and the +# 60 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.StructuralCrouzeix.Endpoint /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of StructuralCrouzeix" diff --git a/tasks/structural-crouzeix/task.toml b/tasks/structural-crouzeix/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4f0a40919b330bcaa7312d4694bb5a62c9342faf --- /dev/null +++ b/tasks/structural-crouzeix/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/structural-crouzeix" +version = "1.0.0" +description = "Prove StructuralCrouzeix (openai/math family 325: The complete Crouzeix conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/StructuralCrouzeix.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "StructuralCrouzeix" +family = "325" +family_title = "The complete Crouzeix conjecture" +subject = "Functional analysis" +theorems = ["OAI.StructuralCrouzeixReference.challenge"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.StructuralCrouzeix.Endpoint" +reference_modules = 60 +reference_lean_bytes = 698525 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1228 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12328 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/structural-crouzeix/tests/Challenge.lean b/tasks/structural-crouzeix/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..c78218e5b4965049ee2cc9e032ee9784a2340fc8 --- /dev/null +++ b/tasks/structural-crouzeix/tests/Challenge.lean @@ -0,0 +1,216 @@ +import Mathlib + +namespace OAI + +universe u_61 u_63 u_67 u_83 u_84 u_181 + +noncomputable section +open scoped BigOperators Matrix.Norms.L2Operator ComplexOrder + +namespace CompleteCrouzeix + + + +def numericalRange {n : ℕ} (A : Matrix (Fin n) (Fin n) ℂ) : Set ℂ := + {z | ∃ x : EuclideanSpace ℂ (Fin n), ‖x‖ = 1 ∧ + inner ℂ x (Matrix.toEuclideanCLM (n := Fin n) (𝕜 := ℂ) A x) = z} + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Set Filter Metric Complex +open scoped Topology + + +structure DiskCoordinate (U : Set ℂ) (a : ℂ) where + outer : Set ℂ + outer_open : IsOpen outer + closure_subset : closure U ⊆ outer + toDisk : ℂ → ℂ + fromDisk : ℂ → ℂ + analytic_to : AnalyticOnNhd ℂ toDisk outer + injective_to : InjOn toDisk outer + noncritical_to : ∀ z ∈ outer, deriv toDisk z ≠ 0 + image_open : IsOpen (toDisk '' outer) + analytic_from : AnalyticOnNhd ℂ fromDisk (toDisk '' outer) + inverse_map : MapsTo fromDisk (toDisk '' outer) outer + left_inverse : ∀ z ∈ outer, fromDisk (toDisk z) = z + right_inverse : ∀ w ∈ toDisk '' outer, toDisk (fromDisk w) = w + closedDisk_subset : closedBall 0 1 ⊆ toDisk '' outer + image_domain : toDisk '' U = ball 0 1 + base_zero : toDisk a = 0 + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Set Filter Metric Complex +open scoped Topology + + +def exteriorMap (a b : ℂ) (h : ℂ → ℂ) (t : ℂ) : ℂ := a*t+b+h t⁻¹ + +structure ExteriorCoordinate (U : Set ℂ) where + radius : ℝ + radius_gt : 1 < radius + leading : ℂ + constant : ℂ + regular : ℂ → ℂ + leading_ne : leading ≠ 0 + analytic_regular : AnalyticOnNhd ℂ regular (ball 0 radius) + injective : InjOn (exteriorMap leading constant regular) {t | radius⁻¹ < ‖t‖} + noncritical : ∀ t, radius⁻¹ < ‖t‖ → deriv (exteriorMap leading constant regular) t ≠ 0 + boundary_image : exteriorMap leading constant regular '' sphere 0 1 = frontier U + interior_iff : ∀ t, radius⁻¹ < ‖t‖ → + (exteriorMap leading constant regular t ∈ U ↔ t ∈ ball 0 1) + outside : ∀ t, 1 < ‖t‖ → exteriorMap leading constant regular t ∉ closure U + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Polynomial Finset +variable {A : Type u_61} [Ring A] [Algebra ℂ A] + +def scalarJetEval (β : ℂ) (N : A) (s : ℕ) (f : ℂ → ℂ) : A := + ∑ i ∈ range s, (iteratedDeriv i f β / (i.factorial : ℂ)) • N ^ i + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Module Set +open scoped DirectSum +variable {V : Type u_63} [AddCommGroup V] [Module ℂ V] [instFiniteDimensionalℂV : FiniteDimensional ℂ V] + +noncomputable def primaryEquiv (T : Module.End ℂ V) : + V ≃ₗ[ℂ] ⨁ β : ℂ, T.maxGenEigenspace β := by + classical + exact (LinearEquiv.ofBijective (DirectSum.coeLinearMap T.maxGenEigenspace) + (DirectSum.isInternal_submodule_of_iSupIndep_of_iSup_eq_top + T.independent_maxGenEigenspace T.iSup_maxGenEigenspace_eq_top)).symm + +noncomputable def primaryNilpotent (T : Module.End ℂ V) (β : ℂ) : + Module.End ℂ (T.maxGenEigenspace β) := + (T - algebraMap ℂ (Module.End ℂ V) β).restrict + (fun x hx => T.mapsTo_maxGenEigenspace_of_comm + (Algebra.mul_sub_algebraMap_commutes T β) β (show x ∈ T.maxGenEigenspace β from hx)) + +noncomputable def primaryEval (T : Module.End ℂ V) (f : ℂ → ℂ) : Module.End ℂ V := + (primaryEquiv T).symm.toLinearMap ∘ₗ + (DirectSum.lmap fun β => scalarJetEval β (primaryNilpotent T β) (finrank ℂ V) f) ∘ₗ + (primaryEquiv T).toLinearMap + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open Filter Topology Set Module +variable {n : Type u_67} [Fintype n] [DecidableEq n] + +noncomputable def matrixAnalyticEval (A : Matrix n n ℂ) (f : ℂ → ℂ) : Matrix n n ℂ := + Matrix.toLinAlgEquiv'.symm (primaryEval (Matrix.toLinAlgEquiv' A) f) + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open scoped ENNReal NNReal Matrix.Norms.L2Operator MatrixOrder Kronecker +variable {n : Type u_83} {m : Type u_84} [Fintype n] [DecidableEq n] [instFintypeM : Fintype m] [instDecidableEqM : DecidableEq m] + +def completeAnalyticEval (D : Matrix n n ℂ) (F : ℂ → Matrix m m ℂ) : + Matrix (n×m) (n×m) ℂ := + fun i j => matrixAnalyticEval D (fun z => F z i.2 j.2) i.1 j.1 + +end CompleteCrouzeix + +namespace CompleteCrouzeix +open scoped Matrix MatrixOrder +variable {n : Type u_181} [Fintype n] [DecidableEq n] [Nonempty n] + +def MetricFeasible (T : Matrix n n ℂ) (τ : ℝ) (H : Matrix n n ℂ) : Prop := + 1 ≤ H ∧ H ≤ algebraMap ℝ (Matrix n n ℂ) τ ∧ Tᴴ * H * T ≤ H + +end CompleteCrouzeix + +end + +noncomputable section +open Set Filter Metric Complex MeasureTheory +open scoped Matrix Topology ComplexConjugate ComplexOrder MatrixOrder + Matrix.Norms.L2Operator Kronecker + +namespace StructuralCrouzeix +open CompleteCrouzeix + +def RegularAnalyticBoundaryAt (U : Set ℂ) (p : ℂ) : Prop := + ∃ χ : ℂ → ℂ, χ 0 = p ∧ AnalyticAt ℂ χ 0 ∧ deriv χ 0 ≠ 0 ∧ + (∀ᶠ z : ℂ in 𝓝 0, χ z ∈ frontier U ↔ z.im = 0) + +structure IsAdmissible (U : Set ℂ) : Prop where + isOpen : IsOpen U + bounded : Bornology.IsBounded U + convex : Convex ℝ U + nonempty : U.Nonempty + jordan : Nonempty (Circle ≃ₜ ↥(frontier U)) + regular : ∀ p ∈ frontier U, RegularAnalyticBoundaryAt U p + +def IsMinimizing {n : ℕ} (T : Matrix (Fin n) (Fin n) ℂ) + (τ : ℝ) (H : Matrix (Fin n) (Fin n) ℂ) : Prop := + MetricFeasible T τ H ∧ + ∀ (σ : ℝ) (J : Matrix (Fin n) (Fin n) ℂ), + MetricFeasible T σ J → τ ≤ σ + +def StrictlyFeasible {n : ℕ} (T : Matrix (Fin n) (Fin n) ℂ) : Prop := + ∃ (τ : ℝ) (H : Matrix (Fin n) (Fin n) ℂ), H.IsHermitian ∧ + (H - 1).PosDef ∧ + (algebraMap ℝ (Matrix (Fin n) (Fin n) ℂ) τ - H).PosDef ∧ + (H - Tᴴ * H * T).PosDef + +def analyticSupNorm {m : ℕ} (U : Set ℂ) + (v : ℂ → Matrix (Fin m) (Fin m) ℂ) : ℝ := + sSup ((fun z => ‖v z‖) '' closure U) + +def boundaryPoint {U : Set ℂ} (G : ExteriorCoordinate U) (t : UnitAddCircle) : ℂ := + exteriorMap G.leading G.constant G.regular (t.toCircle : ℂ) + +def FullEndpoint : Prop := + ∀ (U : Set ℂ), IsAdmissible U → + (∀ a ∈ U, Nonempty (DiskCoordinate U a)) ∧ + Nonempty (ExteriorCoordinate U) ∧ + ∀ (a : ℂ), a ∈ U → ∀ (f : DiskCoordinate U a) (G : ExteriorCoordinate U), + ∀ (n : ℕ), 0 < n → ∀ (A : Matrix (Fin n) (Fin n) ℂ), + numericalRange A ⊆ U → + let T := matrixAnalyticEval A f.toDisk + StrictlyFeasible T ∧ + ∃ κ : ℝ, 1 ≤ κ ∧ κ ≤ 2 ∧ + (∃ H : Matrix (Fin n) (Fin n) ℂ, IsMinimizing T (κ ^ 2) H) ∧ + ∀ H : Matrix (Fin n) (Fin n) ℂ, IsMinimizing T (κ ^ 2) H → + let S := CFC.sqrt H + let A' := S * A * S⁻¹ + let D := S * T * S⁻¹ + H.PosDef ∧ IsUnit S ∧ + D = matrixAnalyticEval A' f.toDisk ∧ + Dᴴ * D ≤ 1 ∧ spectralRadius ℂ D < 1 ∧ + ‖S‖ * ‖S⁻¹‖ = κ ∧ + (∀ R : Matrix (Fin n) (Fin n) ℂ, IsUnit R → + (R * T * R⁻¹)ᴴ * (R * T * R⁻¹) ≤ 1 → + κ ≤ ‖R‖ * ‖R⁻¹‖) ∧ + ∃ Λ : C(UnitAddCircle, Matrix (Fin n) (Fin n) ℂ), + (∀ t, (Λ t).PosSemidef) ∧ + (∫ t, Λ t ∂AddCircle.haarAddCircle) = 1 ∧ + ∀ (m : ℕ), 0 < m → + ∀ v : ℂ → Matrix (Fin m) (Fin m) ℂ, + AnalyticOnNhd ℂ v (closure U) → + completeAnalyticEval A' v = + (∫ t, Λ t ⊗ₖ v (boundaryPoint G t) ∂AddCircle.haarAddCircle) ∧ + ‖completeAnalyticEval A v‖ ≤ κ * analyticSupNorm U v + +end StructuralCrouzeix +end + +namespace StructuralCrouzeixReference + +/-- Intrinsic structural representation and admissibility of the unit disk. -/ +theorem challenge : StructuralCrouzeix.FullEndpoint ∧ + StructuralCrouzeix.IsAdmissible (Metric.ball (0 : ℂ) 1) := by + sorry + +end StructuralCrouzeixReference + +end OAI diff --git a/tasks/structural-crouzeix/tests/grade.py b/tasks/structural-crouzeix/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/structural-crouzeix/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/structural-crouzeix/tests/task.json b/tasks/structural-crouzeix/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..dbe7a0b7161730c70fec41ae36e1744fc0f910b8 --- /dev/null +++ b/tasks/structural-crouzeix/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "StructuralCrouzeix", + "comparator": { + "theorem_names": [ + "OAI.StructuralCrouzeixReference.challenge" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11428 +} \ No newline at end of file diff --git a/tasks/structural-crouzeix/tests/test.sh b/tasks/structural-crouzeix/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/structural-crouzeix/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/subpolynomial-lp/environment/Dockerfile b/tasks/subpolynomial-lp/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/subpolynomial-lp/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/subpolynomial-lp/environment/fetch_mathlib.sh b/tasks/subpolynomial-lp/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/subpolynomial-lp/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/subpolynomial-lp/environment/lake-manifest.json b/tasks/subpolynomial-lp/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/subpolynomial-lp/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/subpolynomial-lp/environment/lakefile.lean b/tasks/subpolynomial-lp/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/subpolynomial-lp/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/subpolynomial-lp/environment/lean_setup.sh b/tasks/subpolynomial-lp/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/subpolynomial-lp/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/subpolynomial-lp/environment/pack_submission.py b/tasks/subpolynomial-lp/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/subpolynomial-lp/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/subpolynomial-lp/instruction.md b/tasks/subpolynomial-lp/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d32a40b43c9827c4a378fcb81b238ef960c215ad --- /dev/null +++ b/tasks/subpolynomial-lp/instruction.md @@ -0,0 +1,101 @@ +# openai/math challenge `SubpolynomialLp` (family 094) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 094 of the release, *Subpolynomial dimension reduction in $L_p$* +(Convex and metric geometry). The family as a whole: For every fixed $11$, every $n$-point subset of real $L_p$ embeds into $\ell_p^d$ with distortion at most $D$ and dimension $d=n^{o(1)}$, answering Naor's sublinear-dimension question for $p\ne2$. In contrast, exact embeddings require worst-case dimension $\Theta(n^2)$ when $p\ne2$. + +The challenge is `SubpolynomialLp`, also at `/opt/openai-math/challenges/SubpolynomialLp.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Filter +open scoped BigOperators Topology +universe u + +namespace SubpolynomialLp + +def coordinateDistance (p : ℝ) {d : ℕ} (x y : Fin d → ℝ) : ℝ := + (∑ a, |x a - y a| ^ p) ^ (1 / p) + +/-- The universal property used in the definition of d_p(n,D). -/ +def GoodDimension (p : ℝ) (n : ℕ) (D : ℝ) (d : ℕ) : Prop := + ∀ (Ω : Type u) (mΩ : MeasurableSpace Ω) (μ : @Measure Ω mΩ) + (x : Fin n → @Lp Ω ℝ mΩ _ (ENNReal.ofReal p) μ), + Function.Injective x → + ∃ (y : Fin n → Fin d → ℝ) (s : ℝ), 0 < s ∧ + ∀ i j, s * ‖x i - x j‖ ≤ coordinateDistance p (y i) (y j) ∧ + coordinateDistance p (y i) (y j) ≤ D * s * ‖x i - x j‖ + +/-- The least universal coordinate dimension. The theorem also asserts that +this least dimension has the defining property, ruling out an empty infimum. -/ +def dimension (p : ℝ) (n : ℕ) (D : ℝ) : ℕ := + sInf {d : ℕ | GoodDimension.{u} p n D d} + +def gamma (p : ℝ) : ℝ := if p < 2 then 2 - p else 1 - 2 / p + +/-- The universal coordinate dimension bounds and their logarithmic limits. -/ +theorem source_main (p : ℝ) (hp : 1 < p) (hp2 : p ≠ 2) : + (∀ D : ℝ, 1 < D → ∃ C : ℝ, ∀ n : ℕ, 2 ≤ n → + GoodDimension.{u} p n D (dimension.{u} p n D) ∧ + Real.log (n : ℝ) / Real.log (1 + 2 * D) ≤ (dimension.{u} p n D : ℝ) ∧ + (dimension.{u} p n D : ℝ) ≤ Real.exp (C * Real.log (n : ℝ) ^ gamma p)) ∧ + (∀ n : ℕ, 9 ≤ n → + GoodDimension.{u} p n 1 (dimension.{u} p n 1) ∧ + ((n - 1) / 4) ^ 2 ≤ dimension.{u} p n 1 ∧ + dimension.{u} p n 1 ≤ n.choose 2) ∧ + (∀ D : ℝ, 1 ≤ D → + Tendsto (fun n : ℕ => Real.log (dimension.{u} p n D : ℝ) / Real.log (n : ℝ)) + atTop (𝓝 (if 1 < D then 0 else 2))) := by + sorry + +end SubpolynomialLp + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SubpolynomialLp.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SubpolynomialLp.source_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/subpolynomial-lp/solution/closure.txt b/tasks/subpolynomial-lp/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..bb72a7df25eab6cace030cbfb7a57bdccfb7958d --- /dev/null +++ b/tasks/subpolynomial-lp/solution/closure.txt @@ -0,0 +1,44 @@ +OAI.Analysis.LpDimension.AboveParameters +OAI.Analysis.LpDimension.AboveTwo +OAI.Analysis.LpDimension.BelowTwo +OAI.Analysis.LpDimension.ClippedMoments +OAI.Analysis.LpDimension.CompoundPoisson +OAI.Analysis.LpDimension.ConvexRepresentation +OAI.Analysis.LpDimension.ConvexSelection +OAI.Analysis.LpDimension.ConvolutionError +OAI.Analysis.LpDimension.CoordinateLaws +OAI.Analysis.LpDimension.CutoffEnvelope +OAI.Analysis.LpDimension.Discretization +OAI.Analysis.LpDimension.DyadicInterpolation +OAI.Analysis.LpDimension.DyadicRamps +OAI.Analysis.LpDimension.ElectricalProjection +OAI.Analysis.LpDimension.Entropy +OAI.Analysis.LpDimension.FourierTails +OAI.Analysis.LpDimension.GlobalCutoff +OAI.Analysis.LpDimension.GradientLaws +OAI.Analysis.LpDimension.GradientSampling +OAI.Analysis.LpDimension.GridObstruction +OAI.Analysis.LpDimension.HeatKernel +OAI.Analysis.LpDimension.HeatLocalization +OAI.Analysis.LpDimension.LogLimits +OAI.Analysis.LpDimension.Main +OAI.Analysis.LpDimension.Model +OAI.Analysis.LpDimension.Packing +OAI.Analysis.LpDimension.Parallelogram +OAI.Analysis.LpDimension.Pareto +OAI.Analysis.LpDimension.PowerEstimates +OAI.Analysis.LpDimension.ProjectedRamps +OAI.Analysis.LpDimension.RampError +OAI.Analysis.LpDimension.RampLaws +OAI.Analysis.LpDimension.RampRetraction +OAI.Analysis.LpDimension.RampSum +OAI.Analysis.LpDimension.RetractionIntegrals +OAI.Analysis.LpDimension.Retractions +OAI.Analysis.LpDimension.Sampling +OAI.Analysis.LpDimension.SamplingBounds +OAI.Analysis.LpDimension.SpectralProjection +OAI.Analysis.LpDimension.StableIntensity +OAI.Analysis.LpDimension.StableLaw +OAI.Analysis.LpDimension.StableRetractions +OAI.Analysis.LpDimension.SymmetricLaws +OAI.Analysis.LpDimension.SymmetricMoments diff --git a/tasks/subpolynomial-lp/solution/reference.py b/tasks/subpolynomial-lp/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/subpolynomial-lp/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/subpolynomial-lp/solution/solve.sh b/tasks/subpolynomial-lp/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7dc6ec6330daf5e53e6cd274437a3d336dcd7d3a --- /dev/null +++ b/tasks/subpolynomial-lp/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SubpolynomialLp, i.e. module OAI.Analysis.LpDimension.Main and the +# 44 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.LpDimension.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SubpolynomialLp" diff --git a/tasks/subpolynomial-lp/task.toml b/tasks/subpolynomial-lp/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..36310fc13ffd94eccfbf393f7a6e7106b5adaac9 --- /dev/null +++ b/tasks/subpolynomial-lp/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/subpolynomial-lp" +version = "1.0.0" +description = "Prove SubpolynomialLp (openai/math family 094: Subpolynomial dimension reduction in $L_p$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SubpolynomialLp.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SubpolynomialLp" +family = "094" +family_title = "Subpolynomial dimension reduction in $L_p$" +subject = "Convex and metric geometry" +theorems = ["OAI.SubpolynomialLp.source_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.LpDimension.Main" +reference_modules = 44 +reference_lean_bytes = 369072 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 893 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12032 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/subpolynomial-lp/tests/Challenge.lean b/tasks/subpolynomial-lp/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..80804d689abf7b2abc02514cc8cce08969ec286b --- /dev/null +++ b/tasks/subpolynomial-lp/tests/Challenge.lean @@ -0,0 +1,50 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Filter +open scoped BigOperators Topology +universe u + +namespace SubpolynomialLp + +def coordinateDistance (p : ℝ) {d : ℕ} (x y : Fin d → ℝ) : ℝ := + (∑ a, |x a - y a| ^ p) ^ (1 / p) + +/-- The universal property used in the definition of d_p(n,D). -/ +def GoodDimension (p : ℝ) (n : ℕ) (D : ℝ) (d : ℕ) : Prop := + ∀ (Ω : Type u) (mΩ : MeasurableSpace Ω) (μ : @Measure Ω mΩ) + (x : Fin n → @Lp Ω ℝ mΩ _ (ENNReal.ofReal p) μ), + Function.Injective x → + ∃ (y : Fin n → Fin d → ℝ) (s : ℝ), 0 < s ∧ + ∀ i j, s * ‖x i - x j‖ ≤ coordinateDistance p (y i) (y j) ∧ + coordinateDistance p (y i) (y j) ≤ D * s * ‖x i - x j‖ + +/-- The least universal coordinate dimension. The theorem also asserts that +this least dimension has the defining property, ruling out an empty infimum. -/ +def dimension (p : ℝ) (n : ℕ) (D : ℝ) : ℕ := + sInf {d : ℕ | GoodDimension.{u} p n D d} + +def gamma (p : ℝ) : ℝ := if p < 2 then 2 - p else 1 - 2 / p + +/-- The universal coordinate dimension bounds and their logarithmic limits. -/ +theorem source_main (p : ℝ) (hp : 1 < p) (hp2 : p ≠ 2) : + (∀ D : ℝ, 1 < D → ∃ C : ℝ, ∀ n : ℕ, 2 ≤ n → + GoodDimension.{u} p n D (dimension.{u} p n D) ∧ + Real.log (n : ℝ) / Real.log (1 + 2 * D) ≤ (dimension.{u} p n D : ℝ) ∧ + (dimension.{u} p n D : ℝ) ≤ Real.exp (C * Real.log (n : ℝ) ^ gamma p)) ∧ + (∀ n : ℕ, 9 ≤ n → + GoodDimension.{u} p n 1 (dimension.{u} p n 1) ∧ + ((n - 1) / 4) ^ 2 ≤ dimension.{u} p n 1 ∧ + dimension.{u} p n 1 ≤ n.choose 2) ∧ + (∀ D : ℝ, 1 ≤ D → + Tendsto (fun n : ℕ => Real.log (dimension.{u} p n D : ℝ) / Real.log (n : ℝ)) + atTop (𝓝 (if 1 < D then 0 else 2))) := by + sorry + +end SubpolynomialLp + +end + +end OAI diff --git a/tasks/subpolynomial-lp/tests/grade.py b/tasks/subpolynomial-lp/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/subpolynomial-lp/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/subpolynomial-lp/tests/task.json b/tasks/subpolynomial-lp/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..168dff99516b441f239d7a9faf24eb01ae65afed --- /dev/null +++ b/tasks/subpolynomial-lp/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SubpolynomialLp", + "comparator": { + "theorem_names": [ + "OAI.SubpolynomialLp.source_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11132 +} \ No newline at end of file diff --git a/tasks/subpolynomial-lp/tests/test.sh b/tasks/subpolynomial-lp/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/subpolynomial-lp/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/subsphere-current/environment/Dockerfile b/tasks/subsphere-current/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/subsphere-current/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/subsphere-current/environment/fetch_mathlib.sh b/tasks/subsphere-current/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/subsphere-current/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/subsphere-current/environment/lake-manifest.json b/tasks/subsphere-current/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/subsphere-current/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/subsphere-current/environment/lakefile.lean b/tasks/subsphere-current/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/subsphere-current/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/subsphere-current/environment/lean_setup.sh b/tasks/subsphere-current/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/subsphere-current/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/subsphere-current/environment/pack_submission.py b/tasks/subsphere-current/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/subsphere-current/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/subsphere-current/instruction.md b/tasks/subsphere-current/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8882c0acb6510c4f9610b84063a66961f1b2b243 --- /dev/null +++ b/tasks/subsphere-current/instruction.md @@ -0,0 +1,499 @@ +# openai/math challenge `SubsphereCurrent` (family 140) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 140 of the release, *Memory–sample lower bounds for noiseless Gaussian regression* +(Theoretical computer science). The family as a whole: For fixed $A>0$, a one-pass learner with $Ad^2$ persistent bits needs $\Omega_A(d\log(1/\epsilon))$ noiseless Gaussian samples to recover a unit vector to angular error $0<\epsilon\le1/10$ with probability $2/3$, uniformly in accuracy for large $d$. Computation and randomized updates are unrestricted, but output uses only the terminal state, stopping index and fresh randomness. + +The challenge is `SubsphereCurrent`, also at `/opt/openai-math/challenges/SubsphereCurrent.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u +namespace SubsphereCurrent +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure KernelLearner (d M T : ℕ) where + initial : PMF (Bool × State M) + transition : ℕ → State M → (Vector d × ℝ) → PMF (Bool × State M) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t q, IsProbabilityMeasure (output t q) + +namespace KernelLearner +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def tagged (M t : ℕ) (a : Bool × State M) : RunStatus M := + if a.1 then .inr (t, a.2) else .inl a.2 + +def run {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : ℕ → PMF (RunStatus M) + | 0 => L.initial.map (tagged M 0) + | n + 1 => (L.run s x n).bind fun status => + match status with + | .inr done => PMF.pure (.inr done) + | .inl q => if hn : n < T then + (L.transition (n + 1) q (x ⟨n, hn⟩, ⟪x ⟨n, hn⟩, s.val⟫)).map (tagged M (n + 1)) + else PMF.pure (.inl q) + +def terminal {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : PMF (ℕ × State M) := + (L.run s x T).map fun status => + match status with + | .inl q => (T, q) + | .inr done => done + +def estimateLaw {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : Measure (UnitSphere d) := + (L.terminal s x).toMeasure.bind fun a => L.output a.1 a.2 + +def angularError {d : ℕ} (s u : UnitSphere d) : ℝ := + Real.arccos ⟪u.val, s.val⟫ + +def conditionalSuccess {d M T : ℕ} (L : KernelLearner d M T) (ε : ℝ) + (s : UnitSphere d) (x : Samples d T) : ℝ≥0∞ := + L.estimateLaw s x {u | angularError s u ≤ ε} + +def CompletedRules {d M T : ℕ} (L : KernelLearner d M T) : Prop := + ∀ t q dest, AEMeasurable (fun obs => L.transition t q obs dest) (observationReference d) + +end KernelLearner + +structure SeededLearner (d M T : ℕ) (Ω : Type u) where + rules : Ω → KernelLearner d M T + +namespace SeededLearner + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) : Prop where + completed_rules : ∀ᵐ ω ∂ρ, (L.rules ω).CompletedRules + fixed_experiment : ∀ s ε, AEMeasurable + (fun z : Ω × Samples d T => (L.rules z.1).conditionalSuccess ε s z.2) + (ρ.prod (sampleLaw d T)) + uniform_experiment : ∀ ε, AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => + (L.rules z.2.1).conditionalSuccess ε z.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + ∫⁻ z : Ω × Samples d T, (L.rules z.1).conditionalSuccess ε s z.2 + ∂(ρ.prod (sampleLaw d T)) + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × (Ω × Samples d T), + (L.rules z.2.1).conditionalSuccess ε z.1 z.2.2 + ∂((uniformSphere d).prod (ρ.prod (sampleLaw d T))) +end SeededLearner + +def ExplicitPrecision : Prop := + ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ) ^ 2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : SeededLearner d (M d) T Ω, L.Admissible ρ → + ((2 / 3 : ℝ≥0∞) ≤ L.uniformSuccess ρ ε ∨ + ∀ s, (2 / 3 : ℝ≥0∞) ≤ L.success ρ ε s) → + (2 : ℝ)⁻¹ ^ 16 * (d : ℝ) * Real.logb 2 (1 / ε) ≤ (T : ℝ) +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent.Affine + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Sphere (E : Type*) [NormedAddCommGroup E] := Metric.sphere (0 : E) 1 + +def sphereLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Measure (Sphere E) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +structure Test (d n : ℕ) where + space : Submodule ℝ (Vector d) + dimension : Module.finrank ℝ space = n + center : Vector d + perpendicular : center ∈ spaceᗮ + radius : ℝ + radius_positive : 0 < radius + unit : ‖center‖^2 + radius^2 = 1 + +def Test.point {d n : ℕ} (A : Test d n) (s : Sphere A.space) : Vector d := + A.center + A.radius • s.val.val + +end SubsphereCurrent.Affine +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe v +namespace SubsphereCurrent.Weighted +abbrev Vector (d : ℕ) := Affine.Vector d +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev Rows (d k : ℕ) := Fin k → Vector d +abbrev Observation (d k : ℕ) := Rows d k × (Fin k → ℝ) + +def onTest {d n : ℕ} (A : Affine.Test d n) (s : Affine.Sphere A.space) : Sphere d := by + refine ⟨A.point s,mem_sphere_zero_iff_norm.mpr ?_⟩ + have hs : ‖(s.val : Vector d)‖ = 1 := by + rw [Submodule.norm_coe] + exact mem_sphere_zero_iff_norm.mp s.property + have ho : ⟪A.center, (s.val : Vector d)⟫ = 0 := + Submodule.inner_left_of_mem_orthogonal s.val.property A.perpendicular + have hz : ‖A.point s‖^2 = 1 := by + rw [Affine.Test.point,norm_add_sq_real,real_inner_smul_right,ho,mul_zero,norm_smul, + Real.norm_eq_abs,abs_of_pos A.radius_positive,hs,mul_one] + nlinarith [A.unit] + nlinarith [norm_nonneg (A.point s)] + +def norm (d n : ℕ) (g : Sphere d → ℝ≥0∞) : ℝ≥0∞ := + ⨆ A : Affine.Test d n, (ENNReal.ofReal A.radius)^((d : ℝ)/16) * + ∫⁻ s : Affine.Sphere A.space, g (onTest A s) ∂Affine.sphereLaw A.space + +def blockInput {d k : ℕ} {V : Type*} [Fintype V] + (κ : V → Observation d k → ℝ≥0∞) (g : V → Sphere d → ℝ≥0∞) + (s : Sphere d) : ℝ≥0∞ := + ∫⁻ X : Rows d k, ∑ v, κ v (X,fun i => ⟪X i,s.val⟫)*g v s + ∂Measure.pi (fun _ => stdGaussian (Vector d)) + +def terminalInput {d : ℕ} (π : Measure (Sphere d)) (ε : ℝ) (s : Sphere d) : ℝ≥0∞ := + π {u | Real.arccos ⟪u.val,s.val⟫ ≤ ε} + +end SubsphereCurrent.Weighted +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe v +namespace SubsphereCurrent.Weighted + +def RadiusWeightedFullEstimate : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ W : ℝ, 1 ≤ W → ∀ (V : Type v) [Fintype V] [Nonempty V], + (Fintype.card V : ℝ) ≤ W → + ∀ κ : V → Observation d (d/16) → ℝ≥0∞, + (∀ v, Measurable (κ v)) → (∀ obs, ∑ v, κ v obs ≤ 1) → + ∀ g : V → Sphere d → ℝ≥0∞, + (∀ v, Measurable (g v)) → (∀ v s, g v s ≤ 1) → + ∀ n : ℕ, (d : ℝ)/2 ≤ n → n ≤ d → + norm d n (blockInput κ g) ≤ + (ENNReal.ofReal W)^(1/((d/16 : ℕ) : ℝ))*ENNReal.ofReal (C^d)*(⨆ v, norm d (n-2) (g v))) ∧ + (∀ n : ℕ, (d : ℝ)/2 ≤ n → n ≤ d → + ∀ π : Measure (Sphere d), IsProbabilityMeasure π → + ∀ ε : ℝ, 0 < ε → + norm d n (terminalInput π ε) ≤ ENNReal.ofReal (C^d)*(ENNReal.ofReal ε)^((d : ℝ)/16)) + +end SubsphereCurrent.Weighted +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u +namespace SubsphereCurrent + +def HalfPrecision : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : SeededLearner d (M d) T Ω, L.Admissible ρ → + (1/2 : ℝ≥0∞) ≤ L.uniformSuccess ρ ε → + c * (d : ℝ) * Real.logb 2 (1/ε) ≤ (T : ℝ) +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent +namespace Fixed + +abbrev Vector (m : ℕ) := EuclideanSpace ℝ (Fin m) +abbrev Sphere (E : Type*) [NormedAddCommGroup E] := Metric.sphere (0 : E) 1 + +def sphereLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Measure (Sphere E) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +def rowsLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] (T : ℕ) : + Measure (Fin T → E) := Measure.pi fun _ => stdGaussian E + +structure Stream (E J : Type*) [MeasurableSpace E] (T : ℕ) where + initial : PMF J + transition : ℕ → J → (E × ℝ) → PMF J + output : J → Measure E + output_probability : ∀ q, IsProbabilityMeasure (output q) + +namespace Stream +variable {E J : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [MeasurableSpace E] [MeasurableSpace J] [Fintype J] [MeasurableSingletonClass J] + {T : ℕ} + +def run (L : Stream E J T) (s : E) (x : Fin T → E) : ℕ → PMF J + | 0 => L.initial + | n+1 => (L.run s x n).bind fun q => if hn : n < T then + L.transition (n+1) q (x ⟨n,hn⟩, ⟪x ⟨n,hn⟩,s⟫) + else PMF.pure q + +def estimateLaw (L : Stream E J T) (s : E) (x : Fin T → E) : Measure E := + (L.run s x T).toMeasure.bind L.output + +def euclideanSuccess (L : Stream E J T) (η : ℝ) (s : E) (x : Fin T → E) : ℝ≥0∞ := + L.estimateLaw s x {y | ‖y-s‖ ≤ η} + +def angularSuccess (L : Stream E J T) (ε : ℝ) (s : E) (x : Fin T → E) : ℝ≥0∞ := + L.estimateLaw s x {y | Real.arccos ⟪y,s⟫ ≤ ε} + +def BorelRules (L : Stream E J T) : Prop := + ∀ n q a, Measurable (fun obs => L.transition n q obs a) + +def suffix (L : Stream E J T) (n k : ℕ) (v : J) : Stream E J k where + initial := PMF.pure v + transition t := L.transition (n+t) + output := L.output + output_probability := L.output_probability + +end Stream + +def DimensionEstimate : Prop := + ∃ C : ℝ, 2 ≤ C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ j m : ℕ, + (d : ℝ)/2 + 2*j ≤ m → m ≤ d → + ∀ η : ℝ, 0 < η → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → Stream (Vector m) (Fin (2^(d^2))) (j*(d/32)), + (∀ᵐ ω ∂ρ, (L ω).BorelRules) → + AEMeasurable (fun z : Sphere (Vector m) × (Ω × (Fin (j*(d/32)) → Vector m)) => + (L z.2.1).euclideanSuccess η z.1.val z.2.2) + ((sphereLaw (Vector m)).prod (ρ.prod (rowsLaw (Vector m) (j*(d/32))))) → + (∫⁻ z : Sphere (Vector m) × (Ω × (Fin (j*(d/32)) → Vector m)), + (L z.2.1).euclideanSuccess η z.1.val z.2.2 + ∂(sphereLaw (Vector m)).prod (ρ.prod (rowsLaw (Vector m) (j*(d/32))))) + ≤ ENNReal.ofReal ((C^(j+1)*η)^((d : ℝ)/32)) + +end Fixed +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent.Affine + +def AllAffineFullEstimate : Prop := + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ k : ℕ, + (d+1)/2 + 2*k ≤ d → ∀ W : ℝ, 1 ≤ W → + ∀ (J : Type v) [Fintype J] [Nonempty J] [MeasurableSpace J] [MeasurableSingletonClass J], + (Fintype.card J : ℝ) ≤ W → W^(1/((d/8 : ℕ) : ℝ)) ≤ (2 : ℝ)^d → + ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → Fixed.Stream (Vector d) J (k*(d/16)), + (∀ᵐ ω ∂ρ, (L ω).BorelRules ∧ ∀ q, ∀ᵐ y ∂(L ω).output q, ‖y‖ = 1) → + ∀ ell : ℕ, ell ≤ k → ∀ v : J, ∀ n : ℕ, (d+1)/2 + 2*ell ≤ n → + ∀ A : Test d n, + (∫⁻ z : Sphere A.space × (Ω × (Fin (ell*(d/16)) → Vector d)), + ((L z.2.1).suffix ((k-ell)*(d/16)) (ell*(d/16)) v).angularSuccess ε (A.point z.1) z.2.2 + ∂(sphereLaw A.space).prod (ρ.prod (Fixed.rowsLaw (Vector d) (ell*(d/16))))) + ≤ ENNReal.ofReal (((16 * ((1000 : ℝ)^32)^ell * ε)/A.radius)^(2*(d/32))) + +end SubsphereCurrent.Affine +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereRegression +section +open scoped Pointwise +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] +def sphereLaw : Measure (Metric.sphere (0 : E) 1) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ +end +section +open scoped Pointwise +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def ambientSphereLaw : Measure E := (sphereLaw (E := E)).map Subtype.val +end +end SubsphereRegression +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] +abbrev Orthogonal (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] := + unitary (E →L[ℝ] E) + +instance orthogonal_compact : CompactSpace (Orthogonal E) := by + apply isCompact_iff_compactSpace.mp + apply (isCompact_closedBall (0 : E →L[ℝ] E) 1).of_isClosed_subset isClosed_unitary + intro u hu + rw [Metric.mem_closedBall,dist_zero_right] + apply u.opNorm_le_bound (by norm_num) + intro x + simp only [u.norm_map_of_mem_unitary hu,one_mul,le_refl] + +noncomputable def orthogonalLaw : Measure (Orthogonal E) := + Measure.haarMeasure ⟨⟨Set.univ,isCompact_univ⟩,by simp⟩ +end SubsphereCurrent.Mixture +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] + +def blockIso (V : Submodule ℝ E) (u : Orthogonal V) (w : Orthogonal Vᗮ) : E ≃ₗᵢ[ℝ] E := + (V.orthogonalDecomposition.trans + ((Unitary.linearIsometryEquiv u).withLpProdCongr 2 (Unitary.linearIsometryEquiv w))).trans + V.orthogonalDecomposition.symm +end SubsphereCurrent.Mixture +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] + [MeasurableSpace E] [BorelSpace E] + +def directionLaw (V N : Submodule ℝ E) : Measure E := + ((orthogonalLaw (E := Vᗮ)).prod (SubsphereRegression.ambientSphereLaw (E := N))).map + (fun z => blockIso V 1 z.1 (z.2 : E)) + +def directionJointLaw (V N : Submodule ℝ E) (t : ℕ) : Measure (Fin t → E) := + ((orthogonalLaw (E := Vᗮ)).prod + (Measure.pi (fun _ : Fin t => SubsphereRegression.ambientSphereLaw (E := N)))).map + (fun z i => blockIso V 1 z.1 (z.2 i : E)) + +def latitudeSpace (V : Submodule ℝ E) (e : Metric.sphere (0 : V) 1) : Submodule ℝ E := + (ℝ ∙ (e.val : E))ᗮ + +def latitudeLaw (V : Submodule ℝ E) (e : Metric.sphere (0 : V) 1) (a delta : ℝ) : Measure E := + ((betaMeasure a delta).prod ((orthogonalLaw (E := V)).prod + (SubsphereRegression.ambientSphereLaw (E := latitudeSpace V e)))).map + (fun z => blockIso V z.2.1 1 + (Real.sqrt (1-z.1) • (e.val : E) + Real.sqrt z.1 • (z.2.2 : E))) + +def MixtureEstimate (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Prop := + (∀ (V N : Submodule ℝ E), V ≤ N → 1 ≤ Module.finrank ℝ V → + Module.finrank ℝ V < Module.finrank ℝ N → Module.finrank ℝ N < Module.finrank ℝ E → + ∀ e : Metric.sphere (0 : V) 1, + directionLaw V N ≤ (2 : ℝ≥0∞) ^ Module.finrank ℝ E • + (SubsphereRegression.ambientSphereLaw + latitudeLaw V e + (((Module.finrank ℝ N : ℝ)-(Module.finrank ℝ V : ℝ))/2) + (((Module.finrank ℝ E : ℝ)-(Module.finrank ℝ N : ℝ))/2))) ∧ + (∀ N : Submodule ℝ E, 1 ≤ Module.finrank ℝ N → + directionLaw ⊥ N = SubsphereRegression.ambientSphereLaw) ∧ + (∀ (V : Submodule ℝ E) (t : ℕ), 1 ≤ Module.finrank ℝ E → + directionJointLaw V ⊤ t = + Measure.pi (fun _ : Fin t => SubsphereRegression.ambientSphereLaw)) + +end SubsphereCurrent.Mixture +end + +noncomputable section +universe u v w +namespace SubsphereCurrent + +def CurrentMainScope : Prop := + ExplicitPrecision.{u} ∧ + Weighted.RadiusWeightedFullEstimate.{v} ∧ + HalfPrecision.{u} ∧ + Affine.AllAffineFullEstimate.{u,v} ∧ + Fixed.DimensionEstimate.{u} ∧ + (∀ (E : Type w) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E], Mixture.MixtureEstimate E) + +end SubsphereCurrent +end + +noncomputable section +universe u v w +namespace SubsphereCurrent + +theorem full_current_main_scope : CurrentMainScope.{u,v,w} := by + sorry + +end SubsphereCurrent +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SubsphereCurrent.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SubsphereCurrent.full_current_main_scope` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/subsphere-current/solution/closure.txt b/tasks/subsphere-current/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..623658731443d80f9842d84b4d22921ff48895ef --- /dev/null +++ b/tasks/subsphere-current/solution/closure.txt @@ -0,0 +1,25 @@ +OAI.Probability.Subsphere.Estimates.AffinePrecision +OAI.Probability.Subsphere.Estimates.FixedPrecision +OAI.Probability.Subsphere.Estimates.HalfPrecision +OAI.Probability.Subsphere.Estimates.Numerics +OAI.Probability.Subsphere.Estimates.Weighted +OAI.Probability.Subsphere.Geometry.Affine +OAI.Probability.Subsphere.Geometry.Integration +OAI.Probability.Subsphere.Geometry.MassBounds +OAI.Probability.Subsphere.Kernels.Precision +OAI.Probability.Subsphere.Main +OAI.Probability.Subsphere.Mixture.BetaTheory +OAI.Probability.Subsphere.Mixture.Domination +OAI.Probability.Subsphere.Mixture.Haar +OAI.Probability.Subsphere.Mixture.Latitude +OAI.Probability.Subsphere.Model +OAI.Probability.Subsphere.Models +OAI.Probability.Subsphere.Regression.Blocks +OAI.Probability.Subsphere.Regression.Gaussian +OAI.Probability.Subsphere.Regression.Geometry +OAI.Probability.Subsphere.Regression.Gram +OAI.Probability.Subsphere.Regression.Model +OAI.Probability.Subsphere.Regression.Precision +OAI.Probability.Subsphere.Regression.Projection +OAI.Probability.Subsphere.Regression.Spheres +OAI.Probability.Subsphere.Regression.Streaming diff --git a/tasks/subsphere-current/solution/reference.py b/tasks/subsphere-current/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/subsphere-current/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/subsphere-current/solution/solve.sh b/tasks/subsphere-current/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..60b012457d9544a6183f17b5111aa9169732171a --- /dev/null +++ b/tasks/subsphere-current/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SubsphereCurrent, i.e. module OAI.Probability.Subsphere.Main and the +# 25 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Subsphere.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SubsphereCurrent" diff --git a/tasks/subsphere-current/task.toml b/tasks/subsphere-current/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3fbc3eed4f7b1cf31f4ab02db78cb7e307649451 --- /dev/null +++ b/tasks/subsphere-current/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/subsphere-current" +version = "1.0.0" +description = "Prove SubsphereCurrent (openai/math family 140: Memory–sample lower bounds for noiseless Gaussian regression) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SubsphereCurrent.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SubsphereCurrent" +family = "140" +family_title = "Memory–sample lower bounds for noiseless Gaussian regression" +subject = "Theoretical computer science" +theorems = ["OAI.SubsphereCurrent.full_current_main_scope"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Subsphere.Main" +reference_modules = 25 +reference_lean_bytes = 477744 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 463 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12129 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/subsphere-current/tests/Challenge.lean b/tasks/subsphere-current/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..07dc7ebfeea2de825724ed30cb6fab0b550db216 --- /dev/null +++ b/tasks/subsphere-current/tests/Challenge.lean @@ -0,0 +1,448 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u +namespace SubsphereCurrent +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev UnitSphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev State (M : ℕ) := Fin (2 ^ M) +abbrev Samples (d T : ℕ) := Fin T → Vector d + +def uniformSphere (d : ℕ) : Measure (UnitSphere d) := + let σ := (volume : Measure (Vector d)).toSphere + (σ Set.univ)⁻¹ • σ + +def sampleLaw (d T : ℕ) : Measure (Samples d T) := + Measure.pi fun _ => stdGaussian (Vector d) + +def observationReference (d : ℕ) : Measure (Vector d × ℝ) := + (stdGaussian (Vector d)).prod volume + +structure KernelLearner (d M T : ℕ) where + initial : PMF (Bool × State M) + transition : ℕ → State M → (Vector d × ℝ) → PMF (Bool × State M) + output : ℕ → State M → Measure (UnitSphere d) + output_probability : ∀ t q, IsProbabilityMeasure (output t q) + +namespace KernelLearner +abbrev RunStatus (M : ℕ) := Sum (State M) (ℕ × State M) + +def tagged (M t : ℕ) (a : Bool × State M) : RunStatus M := + if a.1 then .inr (t, a.2) else .inl a.2 + +def run {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : ℕ → PMF (RunStatus M) + | 0 => L.initial.map (tagged M 0) + | n + 1 => (L.run s x n).bind fun status => + match status with + | .inr done => PMF.pure (.inr done) + | .inl q => if hn : n < T then + (L.transition (n + 1) q (x ⟨n, hn⟩, ⟪x ⟨n, hn⟩, s.val⟫)).map (tagged M (n + 1)) + else PMF.pure (.inl q) + +def terminal {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : PMF (ℕ × State M) := + (L.run s x T).map fun status => + match status with + | .inl q => (T, q) + | .inr done => done + +def estimateLaw {d M T : ℕ} (L : KernelLearner d M T) (s : UnitSphere d) + (x : Samples d T) : Measure (UnitSphere d) := + (L.terminal s x).toMeasure.bind fun a => L.output a.1 a.2 + +def angularError {d : ℕ} (s u : UnitSphere d) : ℝ := + Real.arccos ⟪u.val, s.val⟫ + +def conditionalSuccess {d M T : ℕ} (L : KernelLearner d M T) (ε : ℝ) + (s : UnitSphere d) (x : Samples d T) : ℝ≥0∞ := + L.estimateLaw s x {u | angularError s u ≤ ε} + +def CompletedRules {d M T : ℕ} (L : KernelLearner d M T) : Prop := + ∀ t q dest, AEMeasurable (fun obs => L.transition t q obs dest) (observationReference d) + +end KernelLearner + +structure SeededLearner (d M T : ℕ) (Ω : Type u) where + rules : Ω → KernelLearner d M T + +namespace SeededLearner + +structure Admissible {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) : Prop where + completed_rules : ∀ᵐ ω ∂ρ, (L.rules ω).CompletedRules + fixed_experiment : ∀ s ε, AEMeasurable + (fun z : Ω × Samples d T => (L.rules z.1).conditionalSuccess ε s z.2) + (ρ.prod (sampleLaw d T)) + uniform_experiment : ∀ ε, AEMeasurable + (fun z : UnitSphere d × (Ω × Samples d T) => + (L.rules z.2.1).conditionalSuccess ε z.1 z.2.2) + ((uniformSphere d).prod (ρ.prod (sampleLaw d T))) + +def success {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) (ε : ℝ) (s : UnitSphere d) : ℝ≥0∞ := + ∫⁻ z : Ω × Samples d T, (L.rules z.1).conditionalSuccess ε s z.2 + ∂(ρ.prod (sampleLaw d T)) + +def uniformSuccess {d M T : ℕ} {Ω : Type u} [MeasurableSpace Ω] + (L : SeededLearner d M T Ω) (ρ : Measure Ω) (ε : ℝ) : ℝ≥0∞ := + ∫⁻ z : UnitSphere d × (Ω × Samples d T), + (L.rules z.2.1).conditionalSuccess ε z.1 z.2.2 + ∂((uniformSphere d).prod (ρ.prod (sampleLaw d T))) +end SeededLearner + +def ExplicitPrecision : Prop := + ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ) ^ 2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1 / 10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : SeededLearner d (M d) T Ω, L.Admissible ρ → + ((2 / 3 : ℝ≥0∞) ≤ L.uniformSuccess ρ ε ∨ + ∀ s, (2 / 3 : ℝ≥0∞) ≤ L.success ρ ε s) → + (2 : ℝ)⁻¹ ^ 16 * (d : ℝ) * Real.logb 2 (1 / ε) ≤ (T : ℝ) +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent.Affine + +abbrev Vector (d : ℕ) := EuclideanSpace ℝ (Fin d) +abbrev Sphere (E : Type*) [NormedAddCommGroup E] := Metric.sphere (0 : E) 1 + +def sphereLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Measure (Sphere E) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +structure Test (d n : ℕ) where + space : Submodule ℝ (Vector d) + dimension : Module.finrank ℝ space = n + center : Vector d + perpendicular : center ∈ spaceᗮ + radius : ℝ + radius_positive : 0 < radius + unit : ‖center‖^2 + radius^2 = 1 + +def Test.point {d n : ℕ} (A : Test d n) (s : Sphere A.space) : Vector d := + A.center + A.radius • s.val.val + +end SubsphereCurrent.Affine +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe v +namespace SubsphereCurrent.Weighted +abbrev Vector (d : ℕ) := Affine.Vector d +abbrev Sphere (d : ℕ) := Metric.sphere (0 : Vector d) 1 +abbrev Rows (d k : ℕ) := Fin k → Vector d +abbrev Observation (d k : ℕ) := Rows d k × (Fin k → ℝ) + +def onTest {d n : ℕ} (A : Affine.Test d n) (s : Affine.Sphere A.space) : Sphere d := by + refine ⟨A.point s,mem_sphere_zero_iff_norm.mpr ?_⟩ + have hs : ‖(s.val : Vector d)‖ = 1 := by + rw [Submodule.norm_coe] + exact mem_sphere_zero_iff_norm.mp s.property + have ho : ⟪A.center, (s.val : Vector d)⟫ = 0 := + Submodule.inner_left_of_mem_orthogonal s.val.property A.perpendicular + have hz : ‖A.point s‖^2 = 1 := by + rw [Affine.Test.point,norm_add_sq_real,real_inner_smul_right,ho,mul_zero,norm_smul, + Real.norm_eq_abs,abs_of_pos A.radius_positive,hs,mul_one] + nlinarith [A.unit] + nlinarith [norm_nonneg (A.point s)] + +def norm (d n : ℕ) (g : Sphere d → ℝ≥0∞) : ℝ≥0∞ := + ⨆ A : Affine.Test d n, (ENNReal.ofReal A.radius)^((d : ℝ)/16) * + ∫⁻ s : Affine.Sphere A.space, g (onTest A s) ∂Affine.sphereLaw A.space + +def blockInput {d k : ℕ} {V : Type*} [Fintype V] + (κ : V → Observation d k → ℝ≥0∞) (g : V → Sphere d → ℝ≥0∞) + (s : Sphere d) : ℝ≥0∞ := + ∫⁻ X : Rows d k, ∑ v, κ v (X,fun i => ⟪X i,s.val⟫)*g v s + ∂Measure.pi (fun _ => stdGaussian (Vector d)) + +def terminalInput {d : ℕ} (π : Measure (Sphere d)) (ε : ℝ) (s : Sphere d) : ℝ≥0∞ := + π {u | Real.arccos ⟪u.val,s.val⟫ ≤ ε} + +end SubsphereCurrent.Weighted +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe v +namespace SubsphereCurrent.Weighted + +def RadiusWeightedFullEstimate : Prop := + ∃ C : ℝ, 1 ≤ C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + (∀ W : ℝ, 1 ≤ W → ∀ (V : Type v) [Fintype V] [Nonempty V], + (Fintype.card V : ℝ) ≤ W → + ∀ κ : V → Observation d (d/16) → ℝ≥0∞, + (∀ v, Measurable (κ v)) → (∀ obs, ∑ v, κ v obs ≤ 1) → + ∀ g : V → Sphere d → ℝ≥0∞, + (∀ v, Measurable (g v)) → (∀ v s, g v s ≤ 1) → + ∀ n : ℕ, (d : ℝ)/2 ≤ n → n ≤ d → + norm d n (blockInput κ g) ≤ + (ENNReal.ofReal W)^(1/((d/16 : ℕ) : ℝ))*ENNReal.ofReal (C^d)*(⨆ v, norm d (n-2) (g v))) ∧ + (∀ n : ℕ, (d : ℝ)/2 ≤ n → n ≤ d → + ∀ π : Measure (Sphere d), IsProbabilityMeasure π → + ∀ ε : ℝ, 0 < ε → + norm d n (terminalInput π ε) ≤ ENNReal.ofReal (C^d)*(ENNReal.ofReal ε)^((d : ℝ)/16)) + +end SubsphereCurrent.Weighted +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u +namespace SubsphereCurrent + +def HalfPrecision : Prop := + ∃ c : ℝ, 0 < c ∧ ∀ M : ℕ → ℕ, + Asymptotics.IsLittleO atTop (fun d => (M d : ℝ)) (fun d => (d : ℝ)^2) → + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ T : ℕ, ∀ ε : ℝ, + 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : SeededLearner d (M d) T Ω, L.Admissible ρ → + (1/2 : ℝ≥0∞) ≤ L.uniformSuccess ρ ε → + c * (d : ℝ) * Real.logb 2 (1/ε) ≤ (T : ℝ) +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent +namespace Fixed + +abbrev Vector (m : ℕ) := EuclideanSpace ℝ (Fin m) +abbrev Sphere (E : Type*) [NormedAddCommGroup E] := Metric.sphere (0 : E) 1 + +def sphereLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Measure (Sphere E) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ + +def rowsLaw (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] (T : ℕ) : + Measure (Fin T → E) := Measure.pi fun _ => stdGaussian E + +structure Stream (E J : Type*) [MeasurableSpace E] (T : ℕ) where + initial : PMF J + transition : ℕ → J → (E × ℝ) → PMF J + output : J → Measure E + output_probability : ∀ q, IsProbabilityMeasure (output q) + +namespace Stream +variable {E J : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [MeasurableSpace E] [MeasurableSpace J] [Fintype J] [MeasurableSingletonClass J] + {T : ℕ} + +def run (L : Stream E J T) (s : E) (x : Fin T → E) : ℕ → PMF J + | 0 => L.initial + | n+1 => (L.run s x n).bind fun q => if hn : n < T then + L.transition (n+1) q (x ⟨n,hn⟩, ⟪x ⟨n,hn⟩,s⟫) + else PMF.pure q + +def estimateLaw (L : Stream E J T) (s : E) (x : Fin T → E) : Measure E := + (L.run s x T).toMeasure.bind L.output + +def euclideanSuccess (L : Stream E J T) (η : ℝ) (s : E) (x : Fin T → E) : ℝ≥0∞ := + L.estimateLaw s x {y | ‖y-s‖ ≤ η} + +def angularSuccess (L : Stream E J T) (ε : ℝ) (s : E) (x : Fin T → E) : ℝ≥0∞ := + L.estimateLaw s x {y | Real.arccos ⟪y,s⟫ ≤ ε} + +def BorelRules (L : Stream E J T) : Prop := + ∀ n q a, Measurable (fun obs => L.transition n q obs a) + +def suffix (L : Stream E J T) (n k : ℕ) (v : J) : Stream E J k where + initial := PMF.pure v + transition t := L.transition (n+t) + output := L.output + output_probability := L.output_probability + +end Stream + +def DimensionEstimate : Prop := + ∃ C : ℝ, 2 ≤ C ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ j m : ℕ, + (d : ℝ)/2 + 2*j ≤ m → m ≤ d → + ∀ η : ℝ, 0 < η → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → Stream (Vector m) (Fin (2^(d^2))) (j*(d/32)), + (∀ᵐ ω ∂ρ, (L ω).BorelRules) → + AEMeasurable (fun z : Sphere (Vector m) × (Ω × (Fin (j*(d/32)) → Vector m)) => + (L z.2.1).euclideanSuccess η z.1.val z.2.2) + ((sphereLaw (Vector m)).prod (ρ.prod (rowsLaw (Vector m) (j*(d/32))))) → + (∫⁻ z : Sphere (Vector m) × (Ω × (Fin (j*(d/32)) → Vector m)), + (L z.2.1).euclideanSuccess η z.1.val z.2.2 + ∂(sphereLaw (Vector m)).prod (ρ.prod (rowsLaw (Vector m) (j*(d/32))))) + ≤ ENNReal.ofReal ((C^(j+1)*η)^((d : ℝ)/32)) + +end Fixed +end SubsphereCurrent +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +universe u v +namespace SubsphereCurrent.Affine + +def AllAffineFullEstimate : Prop := + ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → ∀ k : ℕ, + (d+1)/2 + 2*k ≤ d → ∀ W : ℝ, 1 ≤ W → + ∀ (J : Type v) [Fintype J] [Nonempty J] [MeasurableSpace J] [MeasurableSingletonClass J], + (Fintype.card J : ℝ) ≤ W → W^(1/((d/8 : ℕ) : ℝ)) ≤ (2 : ℝ)^d → + ∀ ε : ℝ, 0 < ε → ε ≤ 1/10 → + ∀ (Ω : Type u) [MeasurableSpace Ω] (ρ : Measure Ω), IsProbabilityMeasure ρ → + ∀ L : Ω → Fixed.Stream (Vector d) J (k*(d/16)), + (∀ᵐ ω ∂ρ, (L ω).BorelRules ∧ ∀ q, ∀ᵐ y ∂(L ω).output q, ‖y‖ = 1) → + ∀ ell : ℕ, ell ≤ k → ∀ v : J, ∀ n : ℕ, (d+1)/2 + 2*ell ≤ n → + ∀ A : Test d n, + (∫⁻ z : Sphere A.space × (Ω × (Fin (ell*(d/16)) → Vector d)), + ((L z.2.1).suffix ((k-ell)*(d/16)) (ell*(d/16)) v).angularSuccess ε (A.point z.1) z.2.2 + ∂(sphereLaw A.space).prod (ρ.prod (Fixed.rowsLaw (Vector d) (ell*(d/16))))) + ≤ ENNReal.ofReal (((16 * ((1000 : ℝ)^32)^ell * ε)/A.radius)^(2*(d/32))) + +end SubsphereCurrent.Affine +end + +open MeasureTheory ProbabilityTheory Set Filter +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereRegression +section +open scoped Pointwise +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] +def sphereLaw : Measure (Metric.sphere (0 : E) 1) := + let σ := (volume : Measure E).toSphere + (σ Set.univ)⁻¹ • σ +end +section +open scoped Pointwise +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] + +def ambientSphereLaw : Measure E := (sphereLaw (E := E)).map Subtype.val +end +end SubsphereRegression +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] +abbrev Orthogonal (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] := + unitary (E →L[ℝ] E) + +instance orthogonal_compact : CompactSpace (Orthogonal E) := by + apply isCompact_iff_compactSpace.mp + apply (isCompact_closedBall (0 : E →L[ℝ] E) 1).of_isClosed_subset isClosed_unitary + intro u hu + rw [Metric.mem_closedBall,dist_zero_right] + apply u.opNorm_le_bound (by norm_num) + intro x + simp only [u.norm_map_of_mem_unitary hu,one_mul,le_refl] + +noncomputable def orthogonalLaw : Measure (Orthogonal E) := + Measure.haarMeasure ⟨⟨Set.univ,isCompact_univ⟩,by simp⟩ +end SubsphereCurrent.Mixture +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] + +def blockIso (V : Submodule ℝ E) (u : Orthogonal V) (w : Orthogonal Vᗮ) : E ≃ₗᵢ[ℝ] E := + (V.orthogonalDecomposition.trans + ((Unitary.linearIsometryEquiv u).withLpProdCongr 2 (Unitary.linearIsometryEquiv w))).trans + V.orthogonalDecomposition.symm +end SubsphereCurrent.Mixture +end + +open MeasureTheory ProbabilityTheory Set +open scoped ENNReal NNReal RealInnerProductSpace +noncomputable section +namespace SubsphereCurrent.Mixture +variable {E : Type*} [NormedAddCommGroup E] [InnerProductSpace ℝ E] [FiniteDimensional ℝ E] + [MeasurableSpace E] [BorelSpace E] + +def directionLaw (V N : Submodule ℝ E) : Measure E := + ((orthogonalLaw (E := Vᗮ)).prod (SubsphereRegression.ambientSphereLaw (E := N))).map + (fun z => blockIso V 1 z.1 (z.2 : E)) + +def directionJointLaw (V N : Submodule ℝ E) (t : ℕ) : Measure (Fin t → E) := + ((orthogonalLaw (E := Vᗮ)).prod + (Measure.pi (fun _ : Fin t => SubsphereRegression.ambientSphereLaw (E := N)))).map + (fun z i => blockIso V 1 z.1 (z.2 i : E)) + +def latitudeSpace (V : Submodule ℝ E) (e : Metric.sphere (0 : V) 1) : Submodule ℝ E := + (ℝ ∙ (e.val : E))ᗮ + +def latitudeLaw (V : Submodule ℝ E) (e : Metric.sphere (0 : V) 1) (a delta : ℝ) : Measure E := + ((betaMeasure a delta).prod ((orthogonalLaw (E := V)).prod + (SubsphereRegression.ambientSphereLaw (E := latitudeSpace V e)))).map + (fun z => blockIso V z.2.1 1 + (Real.sqrt (1-z.1) • (e.val : E) + Real.sqrt z.1 • (z.2.2 : E))) + +def MixtureEstimate (E : Type*) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E] : Prop := + (∀ (V N : Submodule ℝ E), V ≤ N → 1 ≤ Module.finrank ℝ V → + Module.finrank ℝ V < Module.finrank ℝ N → Module.finrank ℝ N < Module.finrank ℝ E → + ∀ e : Metric.sphere (0 : V) 1, + directionLaw V N ≤ (2 : ℝ≥0∞) ^ Module.finrank ℝ E • + (SubsphereRegression.ambientSphereLaw + latitudeLaw V e + (((Module.finrank ℝ N : ℝ)-(Module.finrank ℝ V : ℝ))/2) + (((Module.finrank ℝ E : ℝ)-(Module.finrank ℝ N : ℝ))/2))) ∧ + (∀ N : Submodule ℝ E, 1 ≤ Module.finrank ℝ N → + directionLaw ⊥ N = SubsphereRegression.ambientSphereLaw) ∧ + (∀ (V : Submodule ℝ E) (t : ℕ), 1 ≤ Module.finrank ℝ E → + directionJointLaw V ⊤ t = + Measure.pi (fun _ : Fin t => SubsphereRegression.ambientSphereLaw)) + +end SubsphereCurrent.Mixture +end + +noncomputable section +universe u v w +namespace SubsphereCurrent + +def CurrentMainScope : Prop := + ExplicitPrecision.{u} ∧ + Weighted.RadiusWeightedFullEstimate.{v} ∧ + HalfPrecision.{u} ∧ + Affine.AllAffineFullEstimate.{u,v} ∧ + Fixed.DimensionEstimate.{u} ∧ + (∀ (E : Type w) [NormedAddCommGroup E] [InnerProductSpace ℝ E] + [FiniteDimensional ℝ E] [MeasurableSpace E] [BorelSpace E], Mixture.MixtureEstimate E) + +end SubsphereCurrent +end + +noncomputable section +universe u v w +namespace SubsphereCurrent + +theorem full_current_main_scope : CurrentMainScope.{u,v,w} := by + sorry + +end SubsphereCurrent +end + +end OAI diff --git a/tasks/subsphere-current/tests/grade.py b/tasks/subsphere-current/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/subsphere-current/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/subsphere-current/tests/task.json b/tasks/subsphere-current/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4d4a2da7c22546862b3278a3549503040356e310 --- /dev/null +++ b/tasks/subsphere-current/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SubsphereCurrent", + "comparator": { + "theorem_names": [ + "OAI.SubsphereCurrent.full_current_main_scope" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11229 +} \ No newline at end of file diff --git a/tasks/subsphere-current/tests/test.sh b/tasks/subsphere-current/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/subsphere-current/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/superstring/environment/Dockerfile b/tasks/superstring/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/superstring/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/superstring/environment/fetch_mathlib.sh b/tasks/superstring/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/superstring/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/superstring/environment/lake-manifest.json b/tasks/superstring/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/superstring/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/superstring/environment/lakefile.lean b/tasks/superstring/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/superstring/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/superstring/environment/lean_setup.sh b/tasks/superstring/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/superstring/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/superstring/environment/pack_submission.py b/tasks/superstring/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/superstring/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/superstring/instruction.md b/tasks/superstring/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1b42e48ca4441c9015516abfd27e0c203ddafaaf --- /dev/null +++ b/tasks/superstring/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `Superstring` (family 128) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 128 of the release, *A factor-two approximation for shortest common superstring* +(Theoretical computer science). The family as a whole: Gives a deterministic polynomial-time algorithm constructing a common superstring of length at most twice the optimum for every finite family of explicitly represented strings. The running time is polynomial in the full encoded input length, including symbol labels. + +The challenge is `Superstring`, also at `/opt/openai-math/challenges/Superstring.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Superstring + +abbrev Symbol := List Bool +abbrev Word := List Symbol +abbrev Instance := List Word + +/-- Prefix markers encode the list spine, including its final boundary. -/ +def encodeList {α : Type} (enc : α → List Bool) : List α → List Bool + | [] => [true] + | a :: as => false :: (enc a ++ encodeList enc as) + +def encodeSymbol : Symbol → List Bool := encodeList (fun b => [b]) +def encodeWord : Word → List Bool := encodeList encodeSymbol +def encodeInstance : Instance → List Bool := encodeList encodeWord + +/-- Ordinary contiguous substring containment, including the empty word. -/ +def IsCommonSuperstring (S : Instance) (T : Word) : Prop := + ∀ s ∈ S, s <:+: T + +/-- The optimum in symbols, not in bits. -/ +noncomputable def opt (S : Instance) : ℕ := + sInf {n : ℕ | ∃ T : Word, IsCommonSuperstring S T ∧ T.length = n} + +/-- A deterministic finite-stack-machine implementation, with a polynomial bound +on bit-level running time in the explicitly encoded input length. -/ +def HasPolynomialImplementation (f : Instance → Word) : Prop := + ∃ M : Turing.TM2ComputableInPolyTime encodeInstance encodeWord f, + ∀ k : M.tm.K, Finite (M.tm.Γ k) + +/-- The deterministic algorithm with its exact finite-alphabet bit-machine +certificate, contiguous coverage, and factor-two bound in symbols. -/ +theorem main : ∃ f : Instance → Word, + HasPolynomialImplementation f ∧ + ∀ S, IsCommonSuperstring S (f S) ∧ (f S).length ≤ 2 * opt S := by + sorry + +end Superstring + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Superstring.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Superstring.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/superstring/solution/closure.txt b/tasks/superstring/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..92f77e251c303b3ec548158c67f78d9378271c24 --- /dev/null +++ b/tasks/superstring/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Computability.Superstring.Arithmetic +OAI.Computability.Superstring.Attachments +OAI.Computability.Superstring.BlockClose +OAI.Computability.Superstring.Clock +OAI.Computability.Superstring.CollectionCode +OAI.Computability.Superstring.Collections +OAI.Computability.Superstring.Combinators +OAI.Computability.Superstring.Computable +OAI.Computability.Superstring.CountSort +OAI.Computability.Superstring.Counting +OAI.Computability.Superstring.Counts +OAI.Computability.Superstring.DistributeCode +OAI.Computability.Superstring.Distribution +OAI.Computability.Superstring.Encoding +OAI.Computability.Superstring.FactoryPoly +OAI.Computability.Superstring.FibreSelect +OAI.Computability.Superstring.GeoCore +OAI.Computability.Superstring.GroupBridge +OAI.Computability.Superstring.GroupPoly +OAI.Computability.Superstring.GroupSupply +OAI.Computability.Superstring.Groups +OAI.Computability.Superstring.Hierarchical +OAI.Computability.Superstring.HostComplete +OAI.Computability.Superstring.HostNormalization +OAI.Computability.Superstring.HostNormalized +OAI.Computability.Superstring.Input +OAI.Computability.Superstring.Instructions +OAI.Computability.Superstring.Iteration +OAI.Computability.Superstring.LayerBridge +OAI.Computability.Superstring.LayerCode +OAI.Computability.Superstring.LexCode +OAI.Computability.Superstring.LocalCode +OAI.Computability.Superstring.Main +OAI.Computability.Superstring.Model +OAI.Computability.Superstring.Parsing +OAI.Computability.Superstring.Periods +OAI.Computability.Superstring.PolynomialTime +OAI.Computability.Superstring.PrefixMatching +OAI.Computability.Superstring.Programs +OAI.Computability.Superstring.Records +OAI.Computability.Superstring.RequestAttachment +OAI.Computability.Superstring.Schedule +OAI.Computability.Superstring.SchedulerCode +OAI.Computability.Superstring.SchedulerMachine +OAI.Computability.Superstring.Tables +OAI.Computability.Superstring.ThreadSupport +OAI.Computability.Superstring.Threads +OAI.Computability.Superstring.UpperController +OAI.Computability.Superstring.WalkCode +OAI.Computability.Superstring.WalkOutput +OAI.Computability.Superstring.Windows diff --git a/tasks/superstring/solution/reference.py b/tasks/superstring/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/superstring/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/superstring/solution/solve.sh b/tasks/superstring/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c421e502a58596f1ce897034b9d0ec74588113e8 --- /dev/null +++ b/tasks/superstring/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Superstring, i.e. module OAI.Computability.Superstring.Main and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.Superstring.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Superstring" diff --git a/tasks/superstring/task.toml b/tasks/superstring/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..41e51e90a240a43cd48a127b20eb1b52c7d1a0a7 --- /dev/null +++ b/tasks/superstring/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/superstring" +version = "1.0.0" +description = "Prove Superstring (openai/math family 128: A factor-two approximation for shortest common superstring) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Superstring.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Superstring" +family = "128" +family_title = "A factor-two approximation for shortest common superstring" +subject = "Theoretical computer science" +theorems = ["OAI.Superstring.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.Superstring.Main" +reference_modules = 51 +reference_lean_bytes = 940918 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 784 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12546 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/superstring/tests/Challenge.lean b/tasks/superstring/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..48130dac7cd12c22ba5c1382390ecb5eb6783e48 --- /dev/null +++ b/tasks/superstring/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +namespace Superstring + +abbrev Symbol := List Bool +abbrev Word := List Symbol +abbrev Instance := List Word + +/-- Prefix markers encode the list spine, including its final boundary. -/ +def encodeList {α : Type} (enc : α → List Bool) : List α → List Bool + | [] => [true] + | a :: as => false :: (enc a ++ encodeList enc as) + +def encodeSymbol : Symbol → List Bool := encodeList (fun b => [b]) +def encodeWord : Word → List Bool := encodeList encodeSymbol +def encodeInstance : Instance → List Bool := encodeList encodeWord + +/-- Ordinary contiguous substring containment, including the empty word. -/ +def IsCommonSuperstring (S : Instance) (T : Word) : Prop := + ∀ s ∈ S, s <:+: T + +/-- The optimum in symbols, not in bits. -/ +noncomputable def opt (S : Instance) : ℕ := + sInf {n : ℕ | ∃ T : Word, IsCommonSuperstring S T ∧ T.length = n} + +/-- A deterministic finite-stack-machine implementation, with a polynomial bound +on bit-level running time in the explicitly encoded input length. -/ +def HasPolynomialImplementation (f : Instance → Word) : Prop := + ∃ M : Turing.TM2ComputableInPolyTime encodeInstance encodeWord f, + ∀ k : M.tm.K, Finite (M.tm.Γ k) + +/-- The deterministic algorithm with its exact finite-alphabet bit-machine +certificate, contiguous coverage, and factor-two bound in symbols. -/ +theorem main : ∃ f : Instance → Word, + HasPolynomialImplementation f ∧ + ∀ S, IsCommonSuperstring S (f S) ∧ (f S).length ≤ 2 * opt S := by + sorry + +end Superstring + +end OAI diff --git a/tasks/superstring/tests/grade.py b/tasks/superstring/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/superstring/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/superstring/tests/task.json b/tasks/superstring/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..85f5ab293ca0770bea7f0430699a742ee7bb899e --- /dev/null +++ b/tasks/superstring/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Superstring", + "comparator": { + "theorem_names": [ + "OAI.Superstring.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11646 +} \ No newline at end of file diff --git a/tasks/superstring/tests/test.sh b/tasks/superstring/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/superstring/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/switch-chain/environment/Dockerfile b/tasks/switch-chain/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/switch-chain/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/switch-chain/environment/fetch_mathlib.sh b/tasks/switch-chain/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/switch-chain/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/switch-chain/environment/lake-manifest.json b/tasks/switch-chain/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/switch-chain/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/switch-chain/environment/lakefile.lean b/tasks/switch-chain/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/switch-chain/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/switch-chain/environment/lean_setup.sh b/tasks/switch-chain/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/switch-chain/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/switch-chain/environment/pack_submission.py b/tasks/switch-chain/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/switch-chain/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/switch-chain/instruction.md b/tasks/switch-chain/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..fc47c44cd058de593e0ee8fa40d1f5de6874a212 --- /dev/null +++ b/tasks/switch-chain/instruction.md @@ -0,0 +1,222 @@ +# openai/math challenge `SwitchChain` (family 131) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 131 of the release, *Polynomial mixing of graph switches with prescribed degrees* +(Theoretical computer science). The family as a whole: Resolves the simple-undirected Kannan–Tetali–Vempala conjecture: the lazy edge-switch chain mixes in $O(n^8)$ time for every graphical labeled degree sequence. The same degree-constrained graphs can also be sampled exactly uniformly by an almost-surely terminating algorithm with expected polynomial bit running time. + +The challenge is `SwitchChain`, also at `/opt/openai-math/challenges/SwitchChain.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace Problem315 + +def graphDegree {n : Nat} (G : SimpleGraph (Fin n)) (v : Fin n) : Nat := by + classical + exact (Finset.univ.filter (fun w => G.Adj v w)).card + +def Realizes (n : Nat) (d : Fin n → Nat) (G : SimpleGraph (Fin n)) : Prop := + ∀ v, graphDegree G v = d v + +abbrev GraphState (n : Nat) (d : Fin n → Nat) := + {G : SimpleGraph (Fin n) // Realizes n d G} + +def Graphical (n : Nat) (d : Fin n → Nat) : Prop := + Nonempty (GraphState n d) + +abbrev FourSet (n : Nat) := {S : Finset (Fin n) // S.card = 4} + +def IsPerfectMatchingOn {n : Nat} (S : Finset (Fin n)) + (M : SimpleGraph (Fin n)) : Prop := + ∀ v, (v ∈ S → ∃! w, M.Adj v w) ∧ + (v ∉ S → ∀ w, ¬ M.Adj v w) + +abbrev PerfectMatching {n : Nat} (S : FourSet n) := + {M : SimpleGraph (Fin n) // IsPerfectMatchingOn S.1 M} + +abbrev SwitchProposal (n : Nat) := + Σ S : FourSet n, + {p : PerfectMatching S × PerfectMatching S // p.1 ≠ p.2} + +def removedMatching {n : Nat} (p : SwitchProposal n) : SimpleGraph (Fin n) := + p.2.val.1.val + +def addedMatching {n : Nat} (p : SwitchProposal n) : SimpleGraph (Fin n) := + p.2.val.2.val + +def validSwitch {n : Nat} (G : SimpleGraph (Fin n)) + (p : SwitchProposal n) : Prop := + (∀ ⦃u v⦄, (removedMatching p).Adj u v → G.Adj u v) ∧ + (∀ ⦃u v⦄, (addedMatching p).Adj u v → ¬ G.Adj u v) + +def replaceEdges {n : Nat} (G M N : SimpleGraph (Fin n)) : + SimpleGraph (Fin n) where + Adj u v := (G.Adj u v ∧ ¬ M.Adj u v) ∨ N.Adj u v + symm := by + constructor + intro u v h + rcases h with h | h + · left + exact ⟨G.symm.symm u v h.1, fun hm => h.2 (M.symm.symm v u hm)⟩ + · right + exact N.symm.symm u v h + loopless := by + constructor + intro v h + rcases h with h | h + · exact G.loopless.irrefl v h.1 + · exact N.loopless.irrefl v h + +def proposalResult {n : Nat} (G : SimpleGraph (Fin n)) + (p : SwitchProposal n) : SimpleGraph (Fin n) := by + classical + exact + if validSwitch G p then + replaceEdges G (removedMatching p) (addedMatching p) + else G + +def allGraphStates (n : Nat) (d : Fin n → Nat) : + Finset (GraphState n d) := by + classical + exact Finset.univ + +def allProposals (n : Nat) : Finset (SwitchProposal n) := by + classical + exact Finset.univ + +def stateCount (n : Nat) (d : Fin n → Nat) : Nat := + (allGraphStates n d).card + +def switchKernel (n : Nat) (d : Fin n → Nat) + (G H : GraphState n d) : ℝ := by + classical + exact + (if G = H then (1 : ℝ) / 2 else 0) + + (((allProposals n).filter + (fun p => proposalResult G.val p = H.val)).card : ℝ) / + (12 * (Nat.choose n 4 : ℝ)) + +def kernelPow (n : Nat) (d : Fin n → Nat) : + Nat → GraphState n d → GraphState n d → ℝ := by + classical + intro t + induction t with + | zero => + exact fun G H => if G = H then 1 else 0 + | succ t previous => + exact fun G H => + Finset.sum (allGraphStates n d) + (fun K => previous G K * switchKernel n d K H) + +def uniformAverage (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + Finset.sum (allGraphStates n d) (fun G => f G) / + (stateCount n d : ℝ) + +def uniformInner (n : Nat) (d : Fin n → Nat) + (f g : GraphState n d → ℝ) : ℝ := + uniformAverage n d (fun G => f G * g G) + +def uniformVariance (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + uniformAverage n d + (fun G => (f G - uniformAverage n d f) ^ 2) + +def markovApply (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) (G : GraphState n d) : ℝ := + Finset.sum (allGraphStates n d) + (fun H => switchKernel n d G H * f H) + +def dirichletEnergy (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + uniformInner n d f (fun G => f G - markovApply n d f G) + +def hasSpectralGapAtLeast (n : Nat) (d : Fin n → Nat) (γ : ℝ) : Prop := + ∀ f : GraphState n d → ℝ, + γ * uniformVariance n d f ≤ dirichletEnergy n d f + +def tvDistanceFrom (n : Nat) (d : Fin n → Nat) + (t : Nat) (G : GraphState n d) : ℝ := + (1 / 2 : ℝ) * + Finset.sum (allGraphStates n d) + (fun H => + |kernelPow n d t G H - (1 : ℝ) / (stateCount n d : ℝ)|) + +def MixedAt (n : Nat) (d : Fin n → Nat) (t : Nat) : Prop := + ∀ G : GraphState n d, tvDistanceFrom n d t G ≤ (1 : ℝ) / 4 + +def mixingTime (n : Nat) (d : Fin n → Nat) + (h : ∃ t : Nat, MixedAt n d t) : Nat := by + classical + exact Nat.find h + +def SwitchStep (n : Nat) (d : Fin n → Nat) + (G H : GraphState n d) : Prop := + ∃ p : SwitchProposal n, + validSwitch G.val p ∧ proposalResult G.val p = H.val + +theorem switch_chain_main : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → ((∃ h : (∃ t : Nat, MixedAt n d t), mixingTime n d h ≤ 2 * n ^ 8) ∧ (stateCount n d = 1 → (MixedAt n d 0 ∧ ∀ h : (∃ t : Nat, MixedAt n d t), mixingTime n d h = 0)) ∧ (1 < stateCount n d → hasSpectralGapAtLeast n d ((1 : ℝ) / (24 * (n : ℝ) ^ 2 * (Nat.choose n 4 : ℝ))))) := by + sorry + +theorem switch_chain_tv_bound : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → 1 < stateCount n d → ∀ (t : Nat) (G : GraphState n d), tvDistanceFrom n d t G ≤ Real.sqrt (stateCount n d : ℝ) / 2 * Real.exp (- (t : ℝ) / (24 * (n : ℝ) ^ 2 * (Nat.choose n 4 : ℝ))) := by + sorry + +theorem switch_connectivity : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → ∀ G H : GraphState n d, Relation.ReflTransGen (SwitchStep n d) G H := by + sorry + +end Problem315 + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SwitchChain.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Problem315.switch_chain_main`, `OAI.Problem315.switch_chain_tv_bound`, `OAI.Problem315.switch_connectivity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/switch-chain/solution/closure.txt b/tasks/switch-chain/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4d1827df283ee55917ffbe03b8d97d2c0c51e110 --- /dev/null +++ b/tasks/switch-chain/solution/closure.txt @@ -0,0 +1,165 @@ +OAI.Probability.SwitchChain.ActualTripleSquare +OAI.Probability.SwitchChain.BalancedBlockVariance +OAI.Probability.SwitchChain.BinaryAssignments +OAI.Probability.SwitchChain.BinaryColumnPartitions +OAI.Probability.SwitchChain.CellProjectionTransport +OAI.Probability.SwitchChain.CountCoupling +OAI.Probability.SwitchChain.CountCovering +OAI.Probability.SwitchChain.CountEigenEquation +OAI.Probability.SwitchChain.CountEigenvalue +OAI.Probability.SwitchChain.CrossCellAffineComposition +OAI.Probability.SwitchChain.CrossCellConditionalExpectation +OAI.Probability.SwitchChain.CrossCellMoments +OAI.Probability.SwitchChain.CrossCovariance +OAI.Probability.SwitchChain.CrossIndependent +OAI.Probability.SwitchChain.CrossMatrix +OAI.Probability.SwitchChain.CrossToggleCells +OAI.Probability.SwitchChain.CrossToggleGain +OAI.Probability.SwitchChain.CrossTogglePairs +OAI.Probability.SwitchChain.Definitions +OAI.Probability.SwitchChain.DisjointBoundary +OAI.Probability.SwitchChain.DisjointCellCounting +OAI.Probability.SwitchChain.DisjointCellGlobal +OAI.Probability.SwitchChain.DisjointCoordinateFeasibility +OAI.Probability.SwitchChain.DisjointCrossCellEquiv +OAI.Probability.SwitchChain.DisjointEncoding +OAI.Probability.SwitchChain.DisjointEqualityFlags +OAI.Probability.SwitchChain.DisjointFiberCell +OAI.Probability.SwitchChain.DisjointFiberCoordinates +OAI.Probability.SwitchChain.DisjointGraphAffine +OAI.Probability.SwitchChain.DisjointInternal +OAI.Probability.SwitchChain.DisjointProjectionCell +OAI.Probability.SwitchChain.DisjointRealization +OAI.Probability.SwitchChain.DisjointReconstruct +OAI.Probability.SwitchChain.DisjointStateCell +OAI.Probability.SwitchChain.DisjointStateLaw +OAI.Probability.SwitchChain.EnergyTransfer +OAI.Probability.SwitchChain.FiberLabelCounting +OAI.Probability.SwitchChain.FiniteKernelAlgebra +OAI.Probability.SwitchChain.FiniteKernelTV +OAI.Probability.SwitchChain.FiniteVarianceDecomposition +OAI.Probability.SwitchChain.FiniteVarianceEuclidean +OAI.Probability.SwitchChain.FixedBlockCount +OAI.Probability.SwitchChain.FixedBlockMarginal +OAI.Probability.SwitchChain.FixedBlockPartitions +OAI.Probability.SwitchChain.FixedBlockVariance +OAI.Probability.SwitchChain.ForcedColumns +OAI.Probability.SwitchChain.FourVertexSwitch +OAI.Probability.SwitchChain.FrameSynthesis +OAI.Probability.SwitchChain.FrozenRows +OAI.Probability.SwitchChain.GramComparison +OAI.Probability.SwitchChain.HavelConnectivity +OAI.Probability.SwitchChain.HavelInduction +OAI.Probability.SwitchChain.InitialTV +OAI.Probability.SwitchChain.InitialTVGraph +OAI.Probability.SwitchChain.KernelNormalization +OAI.Probability.SwitchChain.LocalGapEndgame +OAI.Probability.SwitchChain.Main +OAI.Probability.SwitchChain.MainFromGap +OAI.Probability.SwitchChain.MatchingCount +OAI.Probability.SwitchChain.MatrixRowVariance +OAI.Probability.SwitchChain.MixingArithmetic +OAI.Probability.SwitchChain.MixingTimeFromTV +OAI.Probability.SwitchChain.NeighborAlignment +OAI.Probability.SwitchChain.OrthogonalPairResampling +OAI.Probability.SwitchChain.PairActualAffine +OAI.Probability.SwitchChain.PairAffineInteraction +OAI.Probability.SwitchChain.PairAggregation +OAI.Probability.SwitchChain.PairAssignmentMoves +OAI.Probability.SwitchChain.PairCrossToggleTransport +OAI.Probability.SwitchChain.PairDisjointAssembly +OAI.Probability.SwitchChain.PairDisjointBudget +OAI.Probability.SwitchChain.PairEqualityBudget +OAI.Probability.SwitchChain.PairEqualityBudgetUnordered +OAI.Probability.SwitchChain.PairEqualityLocalization +OAI.Probability.SwitchChain.PairEqualityOrientation +OAI.Probability.SwitchChain.PairEqualityProjection +OAI.Probability.SwitchChain.PairEqualityRestriction +OAI.Probability.SwitchChain.PairEqualitySlice +OAI.Probability.SwitchChain.PairEqualityUnordered +OAI.Probability.SwitchChain.PairEqualityUnorderedSum +OAI.Probability.SwitchChain.PairFiber +OAI.Probability.SwitchChain.PairFiberBridge +OAI.Probability.SwitchChain.PairFiberConnectivity +OAI.Probability.SwitchChain.PairFiberDegree +OAI.Probability.SwitchChain.PairFiberEnergy +OAI.Probability.SwitchChain.PairFiberEqualityTransport +OAI.Probability.SwitchChain.PairFiberEquiv +OAI.Probability.SwitchChain.PairFiberOrientation +OAI.Probability.SwitchChain.PairFiberRedundancy +OAI.Probability.SwitchChain.PairFiberSliceComparison +OAI.Probability.SwitchChain.PairFiberTransport +OAI.Probability.SwitchChain.PairFibers +OAI.Probability.SwitchChain.PairGeneratorSquare +OAI.Probability.SwitchChain.PairLocalComparison +OAI.Probability.SwitchChain.PairOrbit +OAI.Probability.SwitchChain.PairPoincare +OAI.Probability.SwitchChain.PairProjectionCell +OAI.Probability.SwitchChain.PairRangeInteraction +OAI.Probability.SwitchChain.PairSquaredEnergy +OAI.Probability.SwitchChain.PairSwapFlip +OAI.Probability.SwitchChain.PairSwapFlipProjection +OAI.Probability.SwitchChain.PairSwapInjectivity +OAI.Probability.SwitchChain.PairSwitchComparison +OAI.Probability.SwitchChain.PairTradeSwitch +OAI.Probability.SwitchChain.PairTripleBridge +OAI.Probability.SwitchChain.PermutationFactors +OAI.Probability.SwitchChain.PermutationGenerator +OAI.Probability.SwitchChain.PermutationPathComparison +OAI.Probability.SwitchChain.ProjectionRangeInteraction +OAI.Probability.SwitchChain.ProjectionTools +OAI.Probability.SwitchChain.ProposalLaplacian +OAI.Probability.SwitchChain.ProposalUniqueness +OAI.Probability.SwitchChain.RankOneInteraction +OAI.Probability.SwitchChain.SliceActualSynthesis +OAI.Probability.SwitchChain.SliceBounds +OAI.Probability.SwitchChain.SliceCardEncoding +OAI.Probability.SwitchChain.SliceCoefficientAlgebra +OAI.Probability.SwitchChain.SliceEquality +OAI.Probability.SwitchChain.SliceEuclideanGenerator +OAI.Probability.SwitchChain.SliceFrameProjection +OAI.Probability.SwitchChain.SliceGenerator +OAI.Probability.SwitchChain.SliceGeneratorEquality +OAI.Probability.SwitchChain.SliceGeneratorSampling +OAI.Probability.SwitchChain.SliceGramAction +OAI.Probability.SwitchChain.SliceGramConstant +OAI.Probability.SwitchChain.SliceGramOrbit +OAI.Probability.SwitchChain.SliceGramProfile +OAI.Probability.SwitchChain.SliceGramScalars +OAI.Probability.SwitchChain.SliceImageNorm +OAI.Probability.SwitchChain.SliceMoments +OAI.Probability.SwitchChain.SliceNormalizedFamily +OAI.Probability.SwitchChain.SliceOperatorComparison +OAI.Probability.SwitchChain.SlicePathComparison +OAI.Probability.SwitchChain.SlicePermutationAction +OAI.Probability.SwitchChain.SliceProjectionComparison +OAI.Probability.SwitchChain.SliceReindexedComparison +OAI.Probability.SwitchChain.SliceSynthesis +OAI.Probability.SwitchChain.SliceSynthesisAction +OAI.Probability.SwitchChain.SliceSynthesisBounds +OAI.Probability.SwitchChain.SpectralFromSquare +OAI.Probability.SwitchChain.SwitchFlip +OAI.Probability.SwitchChain.SwitchFoundations +OAI.Probability.SwitchChain.SwitchInFiber +OAI.Probability.SwitchChain.SwitchLaplacian +OAI.Probability.SwitchChain.SwitchMultiplicity +OAI.Probability.SwitchChain.SwitchPairFiber +OAI.Probability.SwitchChain.SwitchTV +OAI.Probability.SwitchChain.SwitchWitness +OAI.Probability.SwitchChain.TransitiveAverage +OAI.Probability.SwitchChain.TripleActualRowBound +OAI.Probability.SwitchChain.TripleCellTransport +OAI.Probability.SwitchChain.TripleCellVarianceGluing +OAI.Probability.SwitchChain.TripleCountEigenvalue +OAI.Probability.SwitchChain.TripleCountGram +OAI.Probability.SwitchChain.TripleCountLaw +OAI.Probability.SwitchChain.TripleGraphEncoding +OAI.Probability.SwitchChain.TripleInternalEncoding +OAI.Probability.SwitchChain.TripleMatrixEncoding +OAI.Probability.SwitchChain.TripleMatrixFinEquiv +OAI.Probability.SwitchChain.TriplePairFiber +OAI.Probability.SwitchChain.TripleProjectionBridge +OAI.Probability.SwitchChain.TripleStateReindex +OAI.Probability.SwitchChain.UnorderedPairSums +OAI.Probability.SwitchChain.VariableBlockVariance +OAI.Probability.SwitchChain.WeightedConditionalVariance diff --git a/tasks/switch-chain/solution/reference.py b/tasks/switch-chain/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/switch-chain/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/switch-chain/solution/solve.sh b/tasks/switch-chain/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f7539f5b45552538f6781e3be03ebf834f23da9d --- /dev/null +++ b/tasks/switch-chain/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SwitchChain, i.e. module OAI.Probability.SwitchChain.Main and the +# 165 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.SwitchChain.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SwitchChain" diff --git a/tasks/switch-chain/task.toml b/tasks/switch-chain/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0ef6d6e367896749b2196a58a26b36018bd1edd5 --- /dev/null +++ b/tasks/switch-chain/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/switch-chain" +version = "1.0.0" +description = "Prove SwitchChain (openai/math family 131: Polynomial mixing of graph switches with prescribed degrees) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SwitchChain.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SwitchChain" +family = "131" +family_title = "Polynomial mixing of graph switches with prescribed degrees" +subject = "Theoretical computer science" +theorems = ["OAI.Problem315.switch_chain_main", "OAI.Problem315.switch_chain_tv_bound", "OAI.Problem315.switch_connectivity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.SwitchChain.Main" +reference_modules = 165 +reference_lean_bytes = 921825 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 924 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12529 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/switch-chain/tests/Challenge.lean b/tasks/switch-chain/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3a275cf5c0cccff2921b091799299cd7795c1d2f --- /dev/null +++ b/tasks/switch-chain/tests/Challenge.lean @@ -0,0 +1,171 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace Problem315 + +def graphDegree {n : Nat} (G : SimpleGraph (Fin n)) (v : Fin n) : Nat := by + classical + exact (Finset.univ.filter (fun w => G.Adj v w)).card + +def Realizes (n : Nat) (d : Fin n → Nat) (G : SimpleGraph (Fin n)) : Prop := + ∀ v, graphDegree G v = d v + +abbrev GraphState (n : Nat) (d : Fin n → Nat) := + {G : SimpleGraph (Fin n) // Realizes n d G} + +def Graphical (n : Nat) (d : Fin n → Nat) : Prop := + Nonempty (GraphState n d) + +abbrev FourSet (n : Nat) := {S : Finset (Fin n) // S.card = 4} + +def IsPerfectMatchingOn {n : Nat} (S : Finset (Fin n)) + (M : SimpleGraph (Fin n)) : Prop := + ∀ v, (v ∈ S → ∃! w, M.Adj v w) ∧ + (v ∉ S → ∀ w, ¬ M.Adj v w) + +abbrev PerfectMatching {n : Nat} (S : FourSet n) := + {M : SimpleGraph (Fin n) // IsPerfectMatchingOn S.1 M} + +abbrev SwitchProposal (n : Nat) := + Σ S : FourSet n, + {p : PerfectMatching S × PerfectMatching S // p.1 ≠ p.2} + +def removedMatching {n : Nat} (p : SwitchProposal n) : SimpleGraph (Fin n) := + p.2.val.1.val + +def addedMatching {n : Nat} (p : SwitchProposal n) : SimpleGraph (Fin n) := + p.2.val.2.val + +def validSwitch {n : Nat} (G : SimpleGraph (Fin n)) + (p : SwitchProposal n) : Prop := + (∀ ⦃u v⦄, (removedMatching p).Adj u v → G.Adj u v) ∧ + (∀ ⦃u v⦄, (addedMatching p).Adj u v → ¬ G.Adj u v) + +def replaceEdges {n : Nat} (G M N : SimpleGraph (Fin n)) : + SimpleGraph (Fin n) where + Adj u v := (G.Adj u v ∧ ¬ M.Adj u v) ∨ N.Adj u v + symm := by + constructor + intro u v h + rcases h with h | h + · left + exact ⟨G.symm.symm u v h.1, fun hm => h.2 (M.symm.symm v u hm)⟩ + · right + exact N.symm.symm u v h + loopless := by + constructor + intro v h + rcases h with h | h + · exact G.loopless.irrefl v h.1 + · exact N.loopless.irrefl v h + +def proposalResult {n : Nat} (G : SimpleGraph (Fin n)) + (p : SwitchProposal n) : SimpleGraph (Fin n) := by + classical + exact + if validSwitch G p then + replaceEdges G (removedMatching p) (addedMatching p) + else G + +def allGraphStates (n : Nat) (d : Fin n → Nat) : + Finset (GraphState n d) := by + classical + exact Finset.univ + +def allProposals (n : Nat) : Finset (SwitchProposal n) := by + classical + exact Finset.univ + +def stateCount (n : Nat) (d : Fin n → Nat) : Nat := + (allGraphStates n d).card + +def switchKernel (n : Nat) (d : Fin n → Nat) + (G H : GraphState n d) : ℝ := by + classical + exact + (if G = H then (1 : ℝ) / 2 else 0) + + (((allProposals n).filter + (fun p => proposalResult G.val p = H.val)).card : ℝ) / + (12 * (Nat.choose n 4 : ℝ)) + +def kernelPow (n : Nat) (d : Fin n → Nat) : + Nat → GraphState n d → GraphState n d → ℝ := by + classical + intro t + induction t with + | zero => + exact fun G H => if G = H then 1 else 0 + | succ t previous => + exact fun G H => + Finset.sum (allGraphStates n d) + (fun K => previous G K * switchKernel n d K H) + +def uniformAverage (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + Finset.sum (allGraphStates n d) (fun G => f G) / + (stateCount n d : ℝ) + +def uniformInner (n : Nat) (d : Fin n → Nat) + (f g : GraphState n d → ℝ) : ℝ := + uniformAverage n d (fun G => f G * g G) + +def uniformVariance (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + uniformAverage n d + (fun G => (f G - uniformAverage n d f) ^ 2) + +def markovApply (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) (G : GraphState n d) : ℝ := + Finset.sum (allGraphStates n d) + (fun H => switchKernel n d G H * f H) + +def dirichletEnergy (n : Nat) (d : Fin n → Nat) + (f : GraphState n d → ℝ) : ℝ := + uniformInner n d f (fun G => f G - markovApply n d f G) + +def hasSpectralGapAtLeast (n : Nat) (d : Fin n → Nat) (γ : ℝ) : Prop := + ∀ f : GraphState n d → ℝ, + γ * uniformVariance n d f ≤ dirichletEnergy n d f + +def tvDistanceFrom (n : Nat) (d : Fin n → Nat) + (t : Nat) (G : GraphState n d) : ℝ := + (1 / 2 : ℝ) * + Finset.sum (allGraphStates n d) + (fun H => + |kernelPow n d t G H - (1 : ℝ) / (stateCount n d : ℝ)|) + +def MixedAt (n : Nat) (d : Fin n → Nat) (t : Nat) : Prop := + ∀ G : GraphState n d, tvDistanceFrom n d t G ≤ (1 : ℝ) / 4 + +def mixingTime (n : Nat) (d : Fin n → Nat) + (h : ∃ t : Nat, MixedAt n d t) : Nat := by + classical + exact Nat.find h + +def SwitchStep (n : Nat) (d : Fin n → Nat) + (G H : GraphState n d) : Prop := + ∃ p : SwitchProposal n, + validSwitch G.val p ∧ proposalResult G.val p = H.val + +theorem switch_chain_main : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → ((∃ h : (∃ t : Nat, MixedAt n d t), mixingTime n d h ≤ 2 * n ^ 8) ∧ (stateCount n d = 1 → (MixedAt n d 0 ∧ ∀ h : (∃ t : Nat, MixedAt n d t), mixingTime n d h = 0)) ∧ (1 < stateCount n d → hasSpectralGapAtLeast n d ((1 : ℝ) / (24 * (n : ℝ) ^ 2 * (Nat.choose n 4 : ℝ))))) := by + sorry + +theorem switch_chain_tv_bound : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → 1 < stateCount n d → ∀ (t : Nat) (G : GraphState n d), tvDistanceFrom n d t G ≤ Real.sqrt (stateCount n d : ℝ) / 2 * Real.exp (- (t : ℝ) / (24 * (n : ℝ) ^ 2 * (Nat.choose n 4 : ℝ))) := by + sorry + +theorem switch_connectivity : + ∀ (n : Nat) (d : Fin n → Nat), 4 ≤ n → (∀ v, d v ≤ n - 1) → Graphical n d → ∀ G H : GraphState n d, Relation.ReflTransGen (SwitchStep n d) G H := by + sorry + +end Problem315 + +end + +end OAI diff --git a/tasks/switch-chain/tests/grade.py b/tasks/switch-chain/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/switch-chain/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/switch-chain/tests/task.json b/tasks/switch-chain/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..43913188d79e54acdc82ab560e4a1b6eabcb6bf7 --- /dev/null +++ b/tasks/switch-chain/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "SwitchChain", + "comparator": { + "theorem_names": [ + "OAI.Problem315.switch_chain_main", + "OAI.Problem315.switch_chain_tv_bound", + "OAI.Problem315.switch_connectivity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11629 +} \ No newline at end of file diff --git a/tasks/switch-chain/tests/test.sh b/tasks/switch-chain/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/switch-chain/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/symmetric-domains/environment/Dockerfile b/tasks/symmetric-domains/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/symmetric-domains/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/symmetric-domains/environment/fetch_mathlib.sh b/tasks/symmetric-domains/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/symmetric-domains/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/symmetric-domains/environment/lake-manifest.json b/tasks/symmetric-domains/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/symmetric-domains/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/symmetric-domains/environment/lakefile.lean b/tasks/symmetric-domains/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/symmetric-domains/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/symmetric-domains/environment/lean_setup.sh b/tasks/symmetric-domains/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/symmetric-domains/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/symmetric-domains/environment/pack_submission.py b/tasks/symmetric-domains/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/symmetric-domains/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/symmetric-domains/instruction.md b/tasks/symmetric-domains/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2057475e45f58a24ff0d9c747b356abdae0d751e --- /dev/null +++ b/tasks/symmetric-domains/instruction.md @@ -0,0 +1,113 @@ +# openai/math challenge `SymmetricDomains` (family 058) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 058 of the release, *The Kollar–Pardon universal-cover conjecture* +(Algebraic and complex geometry). The family as a whole: Proves the Kollar–Pardon conjecture: the semialgebraic universal covers of connected normal projective complex varieties are exactly products $D\times\mathbb C^m\times F$, with $D$ bounded symmetric and $F$ simply connected, normal, and projective. A universal cover is quasi-projective exactly when the bounded symmetric factor is absent. In particular, a smooth projective variety covered by $\mathbb C^n$ has a finite \textnormal{étale} cover by an abelian variety. + +The challenge is `SymmetricDomains`, also at `/opt/openai-math/challenges/SymmetricDomains.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Release061 + +abbrev Affine (n : ℕ) := Fin n → ℂ + +def realCoordinates {n : ℕ} (z : Affine n) : Fin n ⊕ Fin n → ℝ := + Sum.elim (fun j => (z j).re) (fun j => (z j).im) + +def IsAffineAlgebraic {n : ℕ} (V : Set (Affine n)) : Prop := + ∃ P : Set (MvPolynomial (Fin n) ℂ), + V = {z | ∀ p ∈ P, MvPolynomial.eval z p = 0} + +inductive IsSemialgebraic {n : ℕ} : Set (Affine n) → Prop + | zero (p : MvPolynomial (Fin n ⊕ Fin n) ℝ) : + IsSemialgebraic {z | MvPolynomial.eval (realCoordinates z) p = 0} + | positive (p : MvPolynomial (Fin n ⊕ Fin n) ℝ) : + IsSemialgebraic {z | 0 < MvPolynomial.eval (realCoordinates z) p} + | compl {S : Set (Affine n)} : IsSemialgebraic S → IsSemialgebraic Sᶜ + | union {S T : Set (Affine n)} : + IsSemialgebraic S → IsSemialgebraic T → IsSemialgebraic (S ∪ T) + +def HolomorphicOnSubset {n m : ℕ} (S : Set (Affine n)) (f : S → Affine m) : Prop := + ∀ p : S, ∃ W : Set (Affine n), IsOpen W ∧ (p : Affine n) ∈ W ∧ + ∃ F : Affine n → Affine m, AnalyticOnNhd ℂ F W ∧ + ∀ q : S, (q : Affine n) ∈ W → F q = f q + +structure Biholomorph {n m : ℕ} (S : Set (Affine n)) (T : Set (Affine m)) where + toHomeomorph : S ≃ₜ T + holomorphic_toFun : HolomorphicOnSubset S (fun p => (toHomeomorph p : Affine m)) + holomorphic_invFun : HolomorphicOnSubset T (fun q => (toHomeomorph.symm q : Affine n)) + +def IsSmooth {n : ℕ} (S : Set (Affine n)) : Prop := + ∀ p : S, ∃ (m : ℕ) (W : Set (Affine n)), W ⊆ S ∧ + IsOpen ((Subtype.val : S → Affine n) ⁻¹' W) ∧ (p : Affine n) ∈ W ∧ + ∃ D : Set (Affine m), IsOpen D ∧ Nonempty (Biholomorph W D) + +def IsBoundedSymmetricDomain {n : ℕ} (D : Set (Affine n)) : Prop := + IsOpen D ∧ IsConnected D ∧ Bornology.IsBounded D ∧ + ∀ p : D, ∃ σ : Biholomorph D D, + Function.Involutive σ.toHomeomorph ∧ σ.toHomeomorph p = p ∧ + ∃ W : Set D, IsOpen W ∧ p ∈ W ∧ + ∀ q ∈ W, σ.toHomeomorph q = q → q = p + +theorem main {n : ℕ} (V U : Set (Affine n)) + (hV : IsAffineAlgebraic V) (hUV : U ⊆ V) + (hopen : IsOpen ((Subtype.val : V → Affine n) ⁻¹' U)) + (hconn : IsConnected U) (hsa : IsSemialgebraic U) + (hbounded : Bornology.IsBounded U) + (Γ : Type*) [Group Γ] [TopologicalSpace Γ] [DiscreteTopology Γ] + [MulAction Γ U] [ProperSMul Γ U] + [CompactSpace (Quotient (MulAction.orbitRel Γ U))] + (hhol : ∀ γ : Γ, HolomorphicOnSubset U (fun p => (γ • p : U).val)) : + IsSmooth U ∧ ∃ (m : ℕ) (D : Set (Affine m)), + IsBoundedSymmetricDomain D ∧ Nonempty (Biholomorph U D) := by + sorry + +end Release061 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SymmetricDomains.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Release061.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/symmetric-domains/solution/closure.txt b/tasks/symmetric-domains/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f3e99796a9b657219405818055477737309cf66b --- /dev/null +++ b/tasks/symmetric-domains/solution/closure.txt @@ -0,0 +1,335 @@ +OAI.Analysis.SymmetricDomains.ActionAutomorphismHomRange +OAI.Analysis.SymmetricDomains.AdNilpotentPositiveDilations +OAI.Analysis.SymmetricDomains.AffineBand +OAI.Analysis.SymmetricDomains.AffineInverseGermSemialgebraic +OAI.Analysis.SymmetricDomains.AffineProductCoordinates +OAI.Analysis.SymmetricDomains.AlgebraicBranchRamification +OAI.Analysis.SymmetricDomains.AlgebraicGraphPolynomial +OAI.Analysis.SymmetricDomains.AlgebraicIndependentNashPartials +OAI.Analysis.SymmetricDomains.AmbientInverse +OAI.Analysis.SymmetricDomains.AnalyticDirectionalDerivationFun +OAI.Analysis.SymmetricDomains.AnalyticExtensionSemialgebraicAlgebraic +OAI.Analysis.SymmetricDomains.AnalyticFamilyRegraph +OAI.Analysis.SymmetricDomains.AnalyticGermMatrixRank +OAI.Analysis.SymmetricDomains.AnalyticImplicitScalar +OAI.Analysis.SymmetricDomains.AnalyticMulZeroGerm +OAI.Analysis.SymmetricDomains.AnalyticNashRank +OAI.Analysis.SymmetricDomains.AnalyticNashRefinement +OAI.Analysis.SymmetricDomains.AnalyticNhdDifferentiableAffine +OAI.Analysis.SymmetricDomains.AnalyticReparameterization +OAI.Analysis.SymmetricDomains.AnalyticSecondJetCoordinates +OAI.Analysis.SymmetricDomains.AnalyticZeroNull +OAI.Analysis.SymmetricDomains.AnalyticZeroRealPolydisc +OAI.Analysis.SymmetricDomains.AutChartUnimodularJacobian +OAI.Analysis.SymmetricDomains.Basic +OAI.Analysis.SymmetricDomains.BiHaarInvInvariant +OAI.Analysis.SymmetricDomains.BishopAnalyticDiscs +OAI.Analysis.SymmetricDomains.BishopBoundarySolution +OAI.Analysis.SymmetricDomains.BishopBoundarySolutionConstants +OAI.Analysis.SymmetricDomains.BishopDiscRadialExpansion +OAI.Analysis.SymmetricDomains.BishopNormalZeroDeformation +OAI.Analysis.SymmetricDomains.BishopPathInterior +OAI.Analysis.SymmetricDomains.BishopPositiveInterior +OAI.Analysis.SymmetricDomains.BishopTransverseNoncollapse +OAI.Analysis.SymmetricDomains.BoundaryFiberClosureContinuity +OAI.Analysis.SymmetricDomains.BoundaryInjective +OAI.Analysis.SymmetricDomains.BoundaryParameterPeakMaximizer +OAI.Analysis.SymmetricDomains.BoundaryParametricDimensionLt +OAI.Analysis.SymmetricDomains.C1PerturbedFamilyLocal +OAI.Analysis.SymmetricDomains.CartanUniqueness +OAI.Analysis.SymmetricDomains.CayleyTangentBound +OAI.Analysis.SymmetricDomains.Centered +OAI.Analysis.SymmetricDomains.CenteredChartGerms +OAI.Analysis.SymmetricDomains.ChartAbsDetOne +OAI.Analysis.SymmetricDomains.ChartDensityMeasureLeft +OAI.Analysis.SymmetricDomains.ChartDensityPreservedBy +OAI.Analysis.SymmetricDomains.ChartDimensionLeCoordinate +OAI.Analysis.SymmetricDomains.ChartJacobianNeZero +OAI.Analysis.SymmetricDomains.ChartLeftDensityJacobian +OAI.Analysis.SymmetricDomains.ChartLimitMapsAnchor +OAI.Analysis.SymmetricDomains.ChoosePositiveC1Regularization +OAI.Analysis.SymmetricDomains.ClosedMaximizerRelation +OAI.Analysis.SymmetricDomains.CocompactChartDiscContinuity +OAI.Analysis.SymmetricDomains.CocompactScaling +OAI.Analysis.SymmetricDomains.CommutingGeneratorsValueZero +OAI.Analysis.SymmetricDomains.CompactFaithfulIsotropy +OAI.Analysis.SymmetricDomains.CompactPeakRatio +OAI.Analysis.SymmetricDomains.CompactSupportRates +OAI.Analysis.SymmetricDomains.CompleteGeneratorJetProjection +OAI.Analysis.SymmetricDomains.CompleteGeneratorLieAlgebra +OAI.Analysis.SymmetricDomains.CompleteGeneratorTraceAd +OAI.Analysis.SymmetricDomains.ComplexNashNormalGraph +OAI.Analysis.SymmetricDomains.ComplexTangentRankAlternative +OAI.Analysis.SymmetricDomains.ComplexTensorNormalForm +OAI.Analysis.SymmetricDomains.ComplexificationRankLeReal +OAI.Analysis.SymmetricDomains.ComplexifyRealContinuousEquiv +OAI.Analysis.SymmetricDomains.ConjugateMulActionCompact +OAI.Analysis.SymmetricDomains.ConsistentIteratesTendsto +OAI.Analysis.SymmetricDomains.ConsistentVariableStepsTendsto +OAI.Analysis.SymmetricDomains.ContinuityPrinciple +OAI.Analysis.SymmetricDomains.ContinuousAutTransport +OAI.Analysis.SymmetricDomains.ContinuousFderivLocallyUniform +OAI.Analysis.SymmetricDomains.CoordinateDerivativeRank +OAI.Analysis.SymmetricDomains.CoordinateFieldApply +OAI.Analysis.SymmetricDomains.CoordinateFieldLinear +OAI.Analysis.SymmetricDomains.CosineBumpWeightedSummable +OAI.Analysis.SymmetricDomains.CriticalAffineBundleNeighborhood +OAI.Analysis.SymmetricDomains.CriticalCountableCharts +OAI.Analysis.SymmetricDomains.CurvePowerDisplacement +OAI.Analysis.SymmetricDomains.CurveUniformConsistency +OAI.Analysis.SymmetricDomains.Cutoff +OAI.Analysis.SymmetricDomains.DecayWeightDeriv +OAI.Analysis.SymmetricDomains.DifferentiableCauchyTransform +OAI.Analysis.SymmetricDomains.DifferentialMemSpanTranscendence +OAI.Analysis.SymmetricDomains.DiscCompactness +OAI.Analysis.SymmetricDomains.DiscRelationCompactLocal +OAI.Analysis.SymmetricDomains.DivisibleAutomorphismsSubsequence +OAI.Analysis.SymmetricDomains.DivisibleHermitianModel +OAI.Analysis.SymmetricDomains.EntireSupports +OAI.Analysis.SymmetricDomains.EtaleDerivationExtensionUnique +OAI.Analysis.SymmetricDomains.EulerSpectrum +OAI.Analysis.SymmetricDomains.EventualEquicontinuityOpenSubset +OAI.Analysis.SymmetricDomains.EventualOffsetBall +OAI.Analysis.SymmetricDomains.EventuallyImageBallNonzero +OAI.Analysis.SymmetricDomains.ExpandingBiholomorphismsCharts +OAI.Analysis.SymmetricDomains.FiberCardAmbientSheets +OAI.Analysis.SymmetricDomains.FiberPolynomialNatDegree +OAI.Analysis.SymmetricDomains.FieldSecondJet +OAI.Analysis.SymmetricDomains.FiniteAlgebraGenericSheets +OAI.Analysis.SymmetricDomains.FiniteCommonRamification +OAI.Analysis.SymmetricDomains.FiniteCoveringRamifiedSection +OAI.Analysis.SymmetricDomains.FiniteDimensionalCompleteGenerator +OAI.Analysis.SymmetricDomains.FiniteFlowParametrization +OAI.Analysis.SymmetricDomains.FiniteNashCoverAffine +OAI.Analysis.SymmetricDomains.FiniteNashCoverVertical +OAI.Analysis.SymmetricDomains.FiniteProperMapOpen +OAI.Analysis.SymmetricDomains.FiniteUnion +OAI.Analysis.SymmetricDomains.FirstJetConstMul +OAI.Analysis.SymmetricDomains.FirstJetConstMul2 +OAI.Analysis.SymmetricDomains.FirstJetFlowMul +OAI.Analysis.SymmetricDomains.FlatWeightedEuler +OAI.Analysis.SymmetricDomains.FlowWordFirstJet +OAI.Analysis.SymmetricDomains.ForwardBackwardGerm +OAI.Analysis.SymmetricDomains.ForwardLocalDataCompact +OAI.Analysis.SymmetricDomains.GeneratorAdjointContinuous +OAI.Analysis.SymmetricDomains.GeneratorAdjointHom +OAI.Analysis.SymmetricDomains.GeneratorDeterminantDerivZero +OAI.Analysis.SymmetricDomains.GeneratorLieAdjoint +OAI.Analysis.SymmetricDomains.GeneratorPushForwardLinear +OAI.Analysis.SymmetricDomains.GenericAlgebraicBranchRamification +OAI.Analysis.SymmetricDomains.GenericAlgebraicBranchRamification2 +OAI.Analysis.SymmetricDomains.GenericAlgebraicRamificationUniform +OAI.Analysis.SymmetricDomains.GenericFinParameterPolynomial +OAI.Analysis.SymmetricDomains.GenericNashNormalCoordinates +OAI.Analysis.SymmetricDomains.GenericNormalGraphProjection +OAI.Analysis.SymmetricDomains.GenericPolynomialParameterFactor +OAI.Analysis.SymmetricDomains.GenericRealParameterPolynomial +OAI.Analysis.SymmetricDomains.GenericSurjectiveRealNormal +OAI.Analysis.SymmetricDomains.GenericTangentComplexNormal +OAI.Analysis.SymmetricDomains.Geometry +OAI.Analysis.SymmetricDomains.Geometry2 +OAI.Analysis.SymmetricDomains.Geometry3 +OAI.Analysis.SymmetricDomains.GlobalTwoSided +OAI.Analysis.SymmetricDomains.GoodNashBoundary +OAI.Analysis.SymmetricDomains.GraphBoundaryFirstHomotopy +OAI.Analysis.SymmetricDomains.HeisenbergShiftAxis +OAI.Analysis.SymmetricDomains.HermPartUnit +OAI.Analysis.SymmetricDomains.HermiteSignature +OAI.Analysis.SymmetricDomains.HermitianModelSymmetric +OAI.Analysis.SymmetricDomains.HolQuadraticSmul +OAI.Analysis.SymmetricDomains.HolomorphicIdSmallIterates +OAI.Analysis.SymmetricDomains.HolomorphicLocallyUniformLimit +OAI.Analysis.SymmetricDomains.HolomorphicNearIdLower +OAI.Analysis.SymmetricDomains.HolomorphicSupportIndependent +OAI.Analysis.SymmetricDomains.HomeomorphInverse +OAI.Analysis.SymmetricDomains.HorizontalGraphComplexification +OAI.Analysis.SymmetricDomains.HurwitzZeroFreeOr +OAI.Analysis.SymmetricDomains.ImagPartLieReal +OAI.Analysis.SymmetricDomains.IndependentChartConormals +OAI.Analysis.SymmetricDomains.IndependentComplexConormalRows +OAI.Analysis.SymmetricDomains.IndependentConormals +OAI.Analysis.SymmetricDomains.IndependentSupportCoercivity +OAI.Analysis.SymmetricDomains.IndependentSupportRows +OAI.Analysis.SymmetricDomains.InfinitesimalGeneratorEquivariant +OAI.Analysis.SymmetricDomains.InjectiveConormalFinrank +OAI.Analysis.SymmetricDomains.InnerExp +OAI.Analysis.SymmetricDomains.IntegralPrimitive +OAI.Analysis.SymmetricDomains.InteriorBallsAnalyticGraphs +OAI.Analysis.SymmetricDomains.InteriorBallsChangeCoordinates +OAI.Analysis.SymmetricDomains.InteriorBallsSmallSlope +OAI.Analysis.SymmetricDomains.InteriorBallsTotallyReal +OAI.Analysis.SymmetricDomains.InterpolateRealUpper +OAI.Analysis.SymmetricDomains.InverseChartGaussian +OAI.Analysis.SymmetricDomains.InvolutionDerivativeNegId +OAI.Analysis.SymmetricDomains.IsotropyCentralShiftZero +OAI.Analysis.SymmetricDomains.IsotropyCompleteGeneratorsTotally +OAI.Analysis.SymmetricDomains.IsotropyRepresentationUnitsCompact +OAI.Analysis.SymmetricDomains.IterateAverageCoboundary +OAI.Analysis.SymmetricDomains.JointLimitRamification +OAI.Analysis.SymmetricDomains.JointZeroConeProper +OAI.Analysis.SymmetricDomains.LieBracketIndicatorConst +OAI.Analysis.SymmetricDomains.Local +OAI.Analysis.SymmetricDomains.LocalAutomorphismODEGroup +OAI.Analysis.SymmetricDomains.LocalAutomorphismODEGroup2 +OAI.Analysis.SymmetricDomains.LocalBishopData +OAI.Analysis.SymmetricDomains.LocalHaarEqualMass +OAI.Analysis.SymmetricDomains.LocalInverseSupportScaled +OAI.Analysis.SymmetricDomains.LocalMaxGraphParameter +OAI.Analysis.SymmetricDomains.LocalRealHomExtension +OAI.Analysis.SymmetricDomains.LocallyGoodNashBoundary +OAI.Analysis.SymmetricDomains.LocallySmallSlopeGood +OAI.Analysis.SymmetricDomains.LogarithmicPeakBound +OAI.Analysis.SymmetricDomains.Main +OAI.Analysis.SymmetricDomains.MaximizerBundleBorel +OAI.Analysis.SymmetricDomains.MeromorphicGermDetZero +OAI.Analysis.SymmetricDomains.MeromorphicPolynomialRoot +OAI.Analysis.SymmetricDomains.MeromorphicRemovablePositiveRay +OAI.Analysis.SymmetricDomains.Model +OAI.Analysis.SymmetricDomains.ModelAxisNegativeIsotropy +OAI.Analysis.SymmetricDomains.ModelChartOpen +OAI.Analysis.SymmetricDomains.ModelComplexField +OAI.Analysis.SymmetricDomains.ModelIsotropyCentralShift +OAI.Analysis.SymmetricDomains.ModelNormalTranslationAd +OAI.Analysis.SymmetricDomains.ModelRotationWeight +OAI.Analysis.SymmetricDomains.ModelUnaveraged +OAI.Analysis.SymmetricDomains.MontelExpandingDomains +OAI.Analysis.SymmetricDomains.NashCellGeometricRank +OAI.Analysis.SymmetricDomains.NashCellIntrinsicRank +OAI.Analysis.SymmetricDomains.NashCellLowRank +OAI.Analysis.SymmetricDomains.NashNormalGraphBoundary +OAI.Analysis.SymmetricDomains.NashParametrizationExtension +OAI.Analysis.SymmetricDomains.NoncollapseC1Scaling +OAI.Analysis.SymmetricDomains.NoncollapsedSupportedBoundary +OAI.Analysis.SymmetricDomains.NormalOffsetFamilyJoint +OAI.Analysis.SymmetricDomains.NormalOffsetNoncollapse +OAI.Analysis.SymmetricDomains.NormalScaleBound +OAI.Analysis.SymmetricDomains.NormalizedAutomorphismLimitComplete +OAI.Analysis.SymmetricDomains.NormalizedAutomorphismLocalLimit +OAI.Analysis.SymmetricDomains.NormalizedAutomorphismsHaveNonzero +OAI.Analysis.SymmetricDomains.NormalizedDisplacementZeroUniform +OAI.Analysis.SymmetricDomains.NormalizedLocalInverse +OAI.Analysis.SymmetricDomains.OffsetDerivative +OAI.Analysis.SymmetricDomains.OffsetLimitClosedCone +OAI.Analysis.SymmetricDomains.OldOffsetOldPosition +OAI.Analysis.SymmetricDomains.OneKernel +OAI.Analysis.SymmetricDomains.OneParameterDerivativeJoint +OAI.Analysis.SymmetricDomains.OneParameterDifferentiableZero +OAI.Analysis.SymmetricDomains.OneParameterFderivDeriv +OAI.Analysis.SymmetricDomains.OneParameterGeneratorAdd +OAI.Analysis.SymmetricDomains.OneParameterJointStrict +OAI.Analysis.SymmetricDomains.OneParameterLocalODE +OAI.Analysis.SymmetricDomains.OneParameterOneGenerator +OAI.Analysis.SymmetricDomains.OneParameterPositiveLocal +OAI.Analysis.SymmetricDomains.OneParameterPositiveLocal2 +OAI.Analysis.SymmetricDomains.OpenChartLeftTranslate +OAI.Analysis.SymmetricDomains.Pair +OAI.Analysis.SymmetricDomains.ParameterPeakMaximizer +OAI.Analysis.SymmetricDomains.PointSymmetryNegId +OAI.Analysis.SymmetricDomains.PolynomialEmptyInterior +OAI.Analysis.SymmetricDomains.PolynomialIntegralCoordinates +OAI.Analysis.SymmetricDomains.PolynomialRamifiedAnalyticRoot +OAI.Analysis.SymmetricDomains.PolynomialRelationDependentPartials +OAI.Analysis.SymmetricDomains.PolynomialRelationPropagates +OAI.Analysis.SymmetricDomains.PolynomialRemovableLocal +OAI.Analysis.SymmetricDomains.PolynomialRootFiberFinite +OAI.Analysis.SymmetricDomains.PolynomialSignSetChoice +OAI.Analysis.SymmetricDomains.PolynomialSignSetChoice2 +OAI.Analysis.SymmetricDomains.PolynomialSignSetFibre +OAI.Analysis.SymmetricDomains.PolynomialSignSetFinite +OAI.Analysis.SymmetricDomains.PolynomialSignSetFinite2 +OAI.Analysis.SymmetricDomains.PolynomialSignSetInf +OAI.Analysis.SymmetricDomains.PolynomialSignSetOffset +OAI.Analysis.SymmetricDomains.PolynomialSignSetProjection +OAI.Analysis.SymmetricDomains.PolynomialSignSetProjection2 +OAI.Analysis.SymmetricDomains.PolynomialSignSetQuery +OAI.Analysis.SymmetricDomains.PolynomialSignSetRoot +OAI.Analysis.SymmetricDomains.PolynomialSignSetSigns +OAI.Analysis.SymmetricDomains.PolynomialSignSetVector +OAI.Analysis.SymmetricDomains.PositiveMaximizerFiber +OAI.Analysis.SymmetricDomains.PositiveReal +OAI.Analysis.SymmetricDomains.PositiveVertexJets +OAI.Analysis.SymmetricDomains.PowersTendstoOneVanishing +OAI.Analysis.SymmetricDomains.PrimeBoundaryGenericFiber +OAI.Analysis.SymmetricDomains.PrimeZeroLocusFixed +OAI.Analysis.SymmetricDomains.PrimeZeroLocusMaximum +OAI.Analysis.SymmetricDomains.ProductCurveLocalAutomorphism +OAI.Analysis.SymmetricDomains.ProductCurveLocalFlow +OAI.Analysis.SymmetricDomains.ProjectedChartCommonCOne +OAI.Analysis.SymmetricDomains.ProjectedChartConjugationDifferential +OAI.Analysis.SymmetricDomains.ProjectedChartLeftDifferential +OAI.Analysis.SymmetricDomains.ProjectedChartObservableCont +OAI.Analysis.SymmetricDomains.ProjectedChartObservableStrict +OAI.Analysis.SymmetricDomains.ProjectedJetSequencesNot +OAI.Analysis.SymmetricDomains.ProjectionNashChartGerms +OAI.Analysis.SymmetricDomains.ProjectionTangentGeneric +OAI.Analysis.SymmetricDomains.ProperEventuallyFiberSubset +OAI.Analysis.SymmetricDomains.PushForwardGeneratorDeriv +OAI.Analysis.SymmetricDomains.QuadraticDomainConnectedComponent +OAI.Analysis.SymmetricDomains.QuadraticModelDomain +OAI.Analysis.SymmetricDomains.QuadraticModelResidualFiber +OAI.Analysis.SymmetricDomains.RatLieAlgebra +OAI.Analysis.SymmetricDomains.RawQuadraticModelNormalization +OAI.Analysis.SymmetricDomains.RealCriticalMatrix +OAI.Analysis.SymmetricDomains.RealDirectionsTangent +OAI.Analysis.SymmetricDomains.RealMeanPositive +OAI.Analysis.SymmetricDomains.RealParameterPolarRemoval +OAI.Analysis.SymmetricDomains.RealPolynomialAnalyticRoot +OAI.Analysis.SymmetricDomains.RegularSimpleSheet +OAI.Analysis.SymmetricDomains.RootEvaluationSurjective +OAI.Analysis.SymmetricDomains.RootMomentCoefficients +OAI.Analysis.SymmetricDomains.RootSignPattern +OAI.Analysis.SymmetricDomains.SampleAllChambers +OAI.Analysis.SymmetricDomains.ScalarEquicontinuousHolomorphy +OAI.Analysis.SymmetricDomains.ScaledDiscC1Limit +OAI.Analysis.SymmetricDomains.ScaledDiscDeltaC1 +OAI.Analysis.SymmetricDomains.ScaledLocal +OAI.Analysis.SymmetricDomains.ScaledModelC1Limit +OAI.Analysis.SymmetricDomains.ScaledRadialOperatorApply +OAI.Analysis.SymmetricDomains.ScalingEmbeddedCharts +OAI.Analysis.SymmetricDomains.ScalingExpanding +OAI.Analysis.SymmetricDomains.ScalingOpenDomain +OAI.Analysis.SymmetricDomains.SchwarzRadialExpansion +OAI.Analysis.SymmetricDomains.SelectExcludedOffsets +OAI.Analysis.SymmetricDomains.SemialgebraicAnalyticLocalInverse +OAI.Analysis.SymmetricDomains.SemialgebraicBoundaryFiniteNash +OAI.Analysis.SymmetricDomains.SemialgebraicChartBoundaryData +OAI.Analysis.SymmetricDomains.SemialgebraicFiniteAnalyticNash +OAI.Analysis.SymmetricDomains.SemialgebraicOffsetLimits +OAI.Analysis.SymmetricDomains.SemialgebraicOffsetLimitsFamily +OAI.Analysis.SymmetricDomains.SemialgebraicPolynomialNonzero +OAI.Analysis.SymmetricDomains.SemialgebraicRamificationParametersComplex +OAI.Analysis.SymmetricDomains.SemialgebraicSelectionAnalyticPath +OAI.Analysis.SymmetricDomains.SignVariationsPositiveRoots +OAI.Analysis.SymmetricDomains.SignatureRootValues +OAI.Analysis.SymmetricDomains.SliceApproachingGraphs +OAI.Analysis.SymmetricDomains.SliceGraphDerivativeBound +OAI.Analysis.SymmetricDomains.SmallAutomorphismsHaveNonzero +OAI.Analysis.SymmetricDomains.SmallSlopeGoodSupported +OAI.Analysis.SymmetricDomains.SmallSlopeGraphComplexification +OAI.Analysis.SymmetricDomains.SmoothFlatWeightedFourier +OAI.Analysis.SymmetricDomains.SortedFiberSelection +OAI.Analysis.SymmetricDomains.SquarefreeRelationOffDenominator +OAI.Analysis.SymmetricDomains.StrictModelSupports +OAI.Analysis.SymmetricDomains.SupportCayleyOpenImage +OAI.Analysis.SymmetricDomains.SupportDifferentialsChangeChart +OAI.Analysis.SymmetricDomains.SupportedHermitianModel +OAI.Analysis.SymmetricDomains.SupportedHermitianWeightedModel +OAI.Analysis.SymmetricDomains.SupportedPositiveFiberVarying +OAI.Analysis.SymmetricDomains.SupportedWeightedLimit +OAI.Analysis.SymmetricDomains.TarskiQueryCharpoly +OAI.Analysis.SymmetricDomains.TendstoAmbientLocallyUniformly +OAI.Analysis.SymmetricDomains.TransverseCutoffs +OAI.Analysis.SymmetricDomains.UniformCurveTaylor +OAI.Analysis.SymmetricDomains.UniformLatticeHaarRight +OAI.Analysis.SymmetricDomains.UniformSmallOperators +OAI.Analysis.SymmetricDomains.VanishingIdealPrime +OAI.Analysis.SymmetricDomains.VariableEulerAutomorphismFamily +OAI.Analysis.SymmetricDomains.Vector +OAI.Analysis.SymmetricDomains.VectorLift +OAI.Analysis.SymmetricDomains.VerticalPieceBasePolynomial +OAI.Analysis.SymmetricDomains.WeightedChartTwoSided +OAI.Analysis.SymmetricDomains.WeightedSquaredChartLimit +OAI.Analysis.SymmetricDomains.WeightedTaylorUniformlyCompact +OAI.Analysis.SymmetricDomains.WeightedUnscaleC1Error +OAI.Analysis.SymmetricDomains.ZeroISmul +OAI.Analysis.SymmetricDomains.ZeroLocusPolynomialSmooth diff --git a/tasks/symmetric-domains/solution/reference.py b/tasks/symmetric-domains/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/symmetric-domains/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/symmetric-domains/solution/solve.sh b/tasks/symmetric-domains/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a7d3e32d57165b640b30f3266effbf9cc691e1ae --- /dev/null +++ b/tasks/symmetric-domains/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SymmetricDomains, i.e. module OAI.Analysis.SymmetricDomains.Main and the +# 335 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.SymmetricDomains.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SymmetricDomains" diff --git a/tasks/symmetric-domains/task.toml b/tasks/symmetric-domains/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..027a3f4755c65aebc4cb42a20d988b09aba5abf0 --- /dev/null +++ b/tasks/symmetric-domains/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/symmetric-domains" +version = "1.0.0" +description = "Prove SymmetricDomains (openai/math family 058: The Kollar–Pardon universal-cover conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebraic-and-complex-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SymmetricDomains.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SymmetricDomains" +family = "058" +family_title = "The Kollar–Pardon universal-cover conjecture" +subject = "Algebraic and complex geometry" +theorems = ["OAI.Release061.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.SymmetricDomains.Main" +reference_modules = 335 +reference_lean_bytes = 2114940 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1307 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13603 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/symmetric-domains/tests/Challenge.lean b/tasks/symmetric-domains/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..05d033b97fd40b6b643588da4a63194d9685bcf1 --- /dev/null +++ b/tasks/symmetric-domains/tests/Challenge.lean @@ -0,0 +1,62 @@ +import Mathlib + +namespace OAI + +namespace Release061 + +abbrev Affine (n : ℕ) := Fin n → ℂ + +def realCoordinates {n : ℕ} (z : Affine n) : Fin n ⊕ Fin n → ℝ := + Sum.elim (fun j => (z j).re) (fun j => (z j).im) + +def IsAffineAlgebraic {n : ℕ} (V : Set (Affine n)) : Prop := + ∃ P : Set (MvPolynomial (Fin n) ℂ), + V = {z | ∀ p ∈ P, MvPolynomial.eval z p = 0} + +inductive IsSemialgebraic {n : ℕ} : Set (Affine n) → Prop + | zero (p : MvPolynomial (Fin n ⊕ Fin n) ℝ) : + IsSemialgebraic {z | MvPolynomial.eval (realCoordinates z) p = 0} + | positive (p : MvPolynomial (Fin n ⊕ Fin n) ℝ) : + IsSemialgebraic {z | 0 < MvPolynomial.eval (realCoordinates z) p} + | compl {S : Set (Affine n)} : IsSemialgebraic S → IsSemialgebraic Sᶜ + | union {S T : Set (Affine n)} : + IsSemialgebraic S → IsSemialgebraic T → IsSemialgebraic (S ∪ T) + +def HolomorphicOnSubset {n m : ℕ} (S : Set (Affine n)) (f : S → Affine m) : Prop := + ∀ p : S, ∃ W : Set (Affine n), IsOpen W ∧ (p : Affine n) ∈ W ∧ + ∃ F : Affine n → Affine m, AnalyticOnNhd ℂ F W ∧ + ∀ q : S, (q : Affine n) ∈ W → F q = f q + +structure Biholomorph {n m : ℕ} (S : Set (Affine n)) (T : Set (Affine m)) where + toHomeomorph : S ≃ₜ T + holomorphic_toFun : HolomorphicOnSubset S (fun p => (toHomeomorph p : Affine m)) + holomorphic_invFun : HolomorphicOnSubset T (fun q => (toHomeomorph.symm q : Affine n)) + +def IsSmooth {n : ℕ} (S : Set (Affine n)) : Prop := + ∀ p : S, ∃ (m : ℕ) (W : Set (Affine n)), W ⊆ S ∧ + IsOpen ((Subtype.val : S → Affine n) ⁻¹' W) ∧ (p : Affine n) ∈ W ∧ + ∃ D : Set (Affine m), IsOpen D ∧ Nonempty (Biholomorph W D) + +def IsBoundedSymmetricDomain {n : ℕ} (D : Set (Affine n)) : Prop := + IsOpen D ∧ IsConnected D ∧ Bornology.IsBounded D ∧ + ∀ p : D, ∃ σ : Biholomorph D D, + Function.Involutive σ.toHomeomorph ∧ σ.toHomeomorph p = p ∧ + ∃ W : Set D, IsOpen W ∧ p ∈ W ∧ + ∀ q ∈ W, σ.toHomeomorph q = q → q = p + +theorem main {n : ℕ} (V U : Set (Affine n)) + (hV : IsAffineAlgebraic V) (hUV : U ⊆ V) + (hopen : IsOpen ((Subtype.val : V → Affine n) ⁻¹' U)) + (hconn : IsConnected U) (hsa : IsSemialgebraic U) + (hbounded : Bornology.IsBounded U) + (Γ : Type*) [Group Γ] [TopologicalSpace Γ] [DiscreteTopology Γ] + [MulAction Γ U] [ProperSMul Γ U] + [CompactSpace (Quotient (MulAction.orbitRel Γ U))] + (hhol : ∀ γ : Γ, HolomorphicOnSubset U (fun p => (γ • p : U).val)) : + IsSmooth U ∧ ∃ (m : ℕ) (D : Set (Affine m)), + IsBoundedSymmetricDomain D ∧ Nonempty (Biholomorph U D) := by + sorry + +end Release061 + +end OAI diff --git a/tasks/symmetric-domains/tests/grade.py b/tasks/symmetric-domains/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/symmetric-domains/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/symmetric-domains/tests/task.json b/tasks/symmetric-domains/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7a1898b7279adddd562dc6259885a5f5c1782ccd --- /dev/null +++ b/tasks/symmetric-domains/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SymmetricDomains", + "comparator": { + "theorem_names": [ + "OAI.Release061.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12703 +} \ No newline at end of file diff --git a/tasks/symmetric-domains/tests/test.sh b/tasks/symmetric-domains/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/symmetric-domains/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/symmetric-mahler-equality/environment/Dockerfile b/tasks/symmetric-mahler-equality/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/symmetric-mahler-equality/environment/fetch_mathlib.sh b/tasks/symmetric-mahler-equality/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/symmetric-mahler-equality/environment/lake-manifest.json b/tasks/symmetric-mahler-equality/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/symmetric-mahler-equality/environment/lakefile.lean b/tasks/symmetric-mahler-equality/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/symmetric-mahler-equality/environment/lean_setup.sh b/tasks/symmetric-mahler-equality/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/symmetric-mahler-equality/environment/pack_submission.py b/tasks/symmetric-mahler-equality/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/symmetric-mahler-equality/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/symmetric-mahler-equality/instruction.md b/tasks/symmetric-mahler-equality/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c166a6be616d68b4f29214598fa98d10ab8f23fe --- /dev/null +++ b/tasks/symmetric-mahler-equality/instruction.md @@ -0,0 +1,105 @@ +# openai/math challenge `SymmetricMahlerEquality` (family 087) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 087 of the release, *The Mahler conjectures and symplectic width* +(Convex and metric geometry). The family as a whole: Resolves the symmetric and nonsymmetric geometric Mahler conjectures in every dimension, with Hanner polytopes and simplices as the respective volume-product minimizers and all equality cases classified. The corresponding sharp functional Mahler inequalities also hold. For $n\ge2$, every symmetric polar product $K\times K^\circ$ in dimension $2n$ has Gromov width $4$. + +The challenge is `SymmetricMahlerEquality`, also at `/opt/openai-math/challenges/SymmetricMahlerEquality.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace SymmetricMahler + +section + +open Real Complex Set Finset +variable {I : Type*} [Fintype I] + +def coordinatePolar (K : Set (I → ℝ)) : Set (I → ℝ) := + {p | ∀ v ∈ K, (∑ i, p i*v i) ≤ 1} + +end + +noncomputable section + +open Set MeasureTheory Metric + +def hannerProduct {k l : ℕ} (A : Set (Fin k → ℝ)) (B : Set (Fin l → ℝ)) : + Set (Fin (k + l) → ℝ) := + {z | ∃ x ∈ A, ∃ y ∈ B, z = Fin.append x y} + +def hannerJoin {k l : ℕ} (A : Set (Fin k → ℝ)) (B : Set (Fin l → ℝ)) : + Set (Fin (k + l) → ℝ) := + convexHull ℝ + (((fun x : Fin k → ℝ => Fin.append x 0) '' A) ∪ + ((fun y : Fin l → ℝ => Fin.append 0 y) '' B)) + +inductive IsHanner : {n : ℕ} → Set (Fin n → ℝ) → Prop + | interval (a : ℝ) (ha : 0 < a) : + IsHanner (Icc (fun _ : Fin 1 => -a) (fun _ : Fin 1 => a)) + | product {k l : ℕ} {A : Set (Fin k → ℝ)} {B : Set (Fin l → ℝ)} + (hA : IsHanner A) (hB : IsHanner B) : IsHanner (hannerProduct A B) + | join {k l : ℕ} {A : Set (Fin k → ℝ)} {B : Set (Fin l → ℝ)} + (hA : IsHanner A) (hB : IsHanner B) : IsHanner (hannerJoin A B) + +def IsLinearHanner {n : ℕ} (K : Set (Fin n → ℝ)) : Prop := + ∃ H : Set (Fin n → ℝ), IsHanner H ∧ + ∃ T : (Fin n → ℝ) ≃ₗ[ℝ] (Fin n → ℝ), K = T '' H + +theorem symmetric_mahler_equality {n : ℕ} (hn : 1 ≤ n) + {K : Set (Fin n → ℝ)} (hK : IsCompact K) (hconv : Convex ℝ K) + (hsym : ∀ x ∈ K, -x ∈ K) (hint : (interior K).Nonempty) : + ((volume K).toReal * (volume (coordinatePolar K)).toReal = + (4 : ℝ)^n / (Nat.factorial n : ℝ)) ↔ IsLinearHanner K := by + sorry + +end + +end SymmetricMahler + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SymmetricMahlerEquality.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SymmetricMahler.symmetric_mahler_equality` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/symmetric-mahler-equality/solution/closure.txt b/tasks/symmetric-mahler-equality/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..94426caaa9f1f7b5606a9724e0b9094b911246fd --- /dev/null +++ b/tasks/symmetric-mahler-equality/solution/closure.txt @@ -0,0 +1,237 @@ +OAI.Analysis.Mahler.ActualFiniteStrips +OAI.Analysis.Mahler.ActualVerticalPrimitive +OAI.Analysis.Mahler.AngularEndpoint +OAI.Analysis.Mahler.AngularFibers +OAI.Analysis.Mahler.AngularGeometry +OAI.Analysis.Mahler.AngularIntegrals +OAI.Analysis.Mahler.AngularStrip +OAI.Analysis.Mahler.BasisContinuousWedge +OAI.Analysis.Mahler.BoundaryJet +OAI.Analysis.Mahler.ChartExtension +OAI.Analysis.Mahler.ChartStokes +OAI.Analysis.Mahler.Classification +OAI.Analysis.Mahler.ClosedBoundaryStokes +OAI.Analysis.Mahler.ClosedWedgePowers +OAI.Analysis.Mahler.CompactFluxDifferentiation +OAI.Analysis.Mahler.CompactIntegral +OAI.Analysis.Mahler.ComplexCoordinates +OAI.Analysis.Mahler.ComplexStripMap +OAI.Analysis.Mahler.ComplexVolume +OAI.Analysis.Mahler.ConformalInjectivity +OAI.Analysis.Mahler.ConformalInverse +OAI.Analysis.Mahler.ConformalRadialRegularity +OAI.Analysis.Mahler.ConformalSeries +OAI.Analysis.Mahler.ContinuousWedge +OAI.Analysis.Mahler.ContinuousWedgeDerivative +OAI.Analysis.Mahler.ConvexApproximation +OAI.Analysis.Mahler.ConvexCompletion +OAI.Analysis.Mahler.ConvexENNRealTransfer +OAI.Analysis.Mahler.ConvexGeometry +OAI.Analysis.Mahler.ConvexMain +OAI.Analysis.Mahler.ConvexMassReduction +OAI.Analysis.Mahler.ConvexPolarBody +OAI.Analysis.Mahler.ConvexSequence +OAI.Analysis.Mahler.ConvexTransfer +OAI.Analysis.Mahler.CoordinateAnnulus +OAI.Analysis.Mahler.CoordinateBall +OAI.Analysis.Mahler.CoordinateEuclidean +OAI.Analysis.Mahler.CoordinateSphere +OAI.Analysis.Mahler.CovectorVolume +OAI.Analysis.Mahler.DCForms +OAI.Analysis.Mahler.DCRegularity +OAI.Analysis.Mahler.Diamonds +OAI.Analysis.Mahler.DilationTransport +OAI.Analysis.Mahler.EqualityMedians +OAI.Analysis.Mahler.ErrorBound +OAI.Analysis.Mahler.EuclideanMassDensity +OAI.Analysis.Mahler.EuclideanRegularLevels +OAI.Analysis.Mahler.EuclideanSpecialMap +OAI.Analysis.Mahler.ExactFormCoordinates +OAI.Analysis.Mahler.ExactSphereFluxBridge +OAI.Analysis.Mahler.ExactSphereStokes +OAI.Analysis.Mahler.ExteriorAlternatization +OAI.Analysis.Mahler.ExteriorCoefficient +OAI.Analysis.Mahler.ExteriorCoordinates +OAI.Analysis.Mahler.ExteriorDirectional +OAI.Analysis.Mahler.ExteriorFlux +OAI.Analysis.Mahler.ExteriorHessian +OAI.Analysis.Mahler.ExteriorLeibnizTwo +OAI.Analysis.Mahler.ExteriorPower +OAI.Analysis.Mahler.Faces +OAI.Analysis.Mahler.FiberEndpoint +OAI.Analysis.Mahler.FiberHeight +OAI.Analysis.Mahler.FiberPreimageEndpoint +OAI.Analysis.Mahler.FiberPrimitive +OAI.Analysis.Mahler.FiniteStripReduction +OAI.Analysis.Mahler.FiniteStrips +OAI.Analysis.Mahler.FluxVariation +OAI.Analysis.Mahler.FormLocalization +OAI.Analysis.Mahler.FormStokes +OAI.Analysis.Mahler.GlobalFiberParametrization +OAI.Analysis.Mahler.GlobalPlanarBound +OAI.Analysis.Mahler.GlobalPlanarMonotonicity +OAI.Analysis.Mahler.GlobalVerticalGeometry +OAI.Analysis.Mahler.HalfspaceStokes +OAI.Analysis.Mahler.HannerBodies +OAI.Analysis.Mahler.HemisphereArea +OAI.Analysis.Mahler.HemisphereChart +OAI.Analysis.Mahler.HemisphereFlux +OAI.Analysis.Mahler.HemisphereJacobian +OAI.Analysis.Mahler.HemisphereMeasure +OAI.Analysis.Mahler.Hessian +OAI.Analysis.Mahler.HolomorphicLogC2 +OAI.Analysis.Mahler.HolomorphicRegularity +OAI.Analysis.Mahler.HomogeneousCircleIntegral +OAI.Analysis.Mahler.HomogeneousDeformation +OAI.Analysis.Mahler.HomogeneousDensityVariation +OAI.Analysis.Mahler.HomogeneousEndpoint +OAI.Analysis.Mahler.HomogeneousFlux +OAI.Analysis.Mahler.HomogeneousFluxDifferentiation +OAI.Analysis.Mahler.HomogeneousFluxFTC +OAI.Analysis.Mahler.HomogeneousMassAssembly +OAI.Analysis.Mahler.HomogeneousPrimitiveRegularity +OAI.Analysis.Mahler.HomogeneousSmoothForms +OAI.Analysis.Mahler.HomogeneousSphereIntegral +OAI.Analysis.Mahler.HomogeneousTransgression +OAI.Analysis.Mahler.HomogeneousTransgressionFTC +OAI.Analysis.Mahler.HomogeneousVariationCoefficient +OAI.Analysis.Mahler.HorizontalForms +OAI.Analysis.Mahler.ImplicitAngle +OAI.Analysis.Mahler.InteriorStokes +OAI.Analysis.Mahler.InverseRadialRegularity +OAI.Analysis.Mahler.Jacobian +OAI.Analysis.Mahler.Lens +OAI.Analysis.Mahler.LevelFace +OAI.Analysis.Mahler.LevelForms +OAI.Analysis.Mahler.LogDilation +OAI.Analysis.Mahler.LogJet +OAI.Analysis.Mahler.LogNormSquare +OAI.Analysis.Mahler.LogScalarJet +OAI.Analysis.Mahler.LogUniform +OAI.Analysis.Mahler.MainTheorem +OAI.Analysis.Mahler.MassLimit +OAI.Analysis.Mahler.MassTarget +OAI.Analysis.Mahler.MatrixExteriorPower +OAI.Analysis.Mahler.MatrixHessian +OAI.Analysis.Mahler.Medians +OAI.Analysis.Mahler.NormExteriorPower +OAI.Analysis.Mahler.NormSquareForm +OAI.Analysis.Mahler.NormSquareJet +OAI.Analysis.Mahler.OpenExteriorNormalization +OAI.Analysis.Mahler.OpenHessian +OAI.Analysis.Mahler.OrientedChartIntegral +OAI.Analysis.Mahler.OrientedSphereDensity +OAI.Analysis.Mahler.PairExteriorBridge +OAI.Analysis.Mahler.PairTransgression +OAI.Analysis.Mahler.PlanarDensity +OAI.Analysis.Mahler.PlanarErrorRate +OAI.Analysis.Mahler.PlanarEstimates +OAI.Analysis.Mahler.PlanarIntegralRegularity +OAI.Analysis.Mahler.PlanarRegularity +OAI.Analysis.Mahler.PlanarSymmetry +OAI.Analysis.Mahler.Positivity +OAI.Analysis.Mahler.PowerTransgression +OAI.Analysis.Mahler.PrimitiveBound +OAI.Analysis.Mahler.PrimitiveEquality +OAI.Analysis.Mahler.PrimitiveRegularity +OAI.Analysis.Mahler.PullbackRegularity +OAI.Analysis.Mahler.PunctureCutoff +OAI.Analysis.Mahler.PuncturedBallStokes +OAI.Analysis.Mahler.PuncturedSublevelStokes +OAI.Analysis.Mahler.RadialBridge +OAI.Analysis.Mahler.RadialPrimitiveDeriv +OAI.Analysis.Mahler.RawAlternatingCalculus +OAI.Analysis.Mahler.RawAlternationDerivative +OAI.Analysis.Mahler.RawClosedPower +OAI.Analysis.Mahler.RawClosedProduct +OAI.Analysis.Mahler.RawCoefficientDerivative +OAI.Analysis.Mahler.RawExteriorPower +OAI.Analysis.Mahler.RawReindexedDerivative +OAI.Analysis.Mahler.RealLogBridge +OAI.Analysis.Mahler.ReferencePole +OAI.Analysis.Mahler.ReferencePoleFrame +OAI.Analysis.Mahler.ReferenceSphere +OAI.Analysis.Mahler.ReferenceSphereIntegral +OAI.Analysis.Mahler.RegularBoundaryAtlas +OAI.Analysis.Mahler.RegularChartStokes +OAI.Analysis.Mahler.RegularLevelCharts +OAI.Analysis.Mahler.RegularMassReduction +OAI.Analysis.Mahler.RegularPartition +OAI.Analysis.Mahler.RegularStokesAssembly +OAI.Analysis.Mahler.RegularSublevel +OAI.Analysis.Mahler.RescaledHolomorphic +OAI.Analysis.Mahler.RescaledMassMap +OAI.Analysis.Mahler.RescalingEstimates +OAI.Analysis.Mahler.ShellRegularity +OAI.Analysis.Mahler.SineBound +OAI.Analysis.Mahler.SmallSphereLimits +OAI.Analysis.Mahler.SourceBoundaryIntegral +OAI.Analysis.Mahler.SourceCanonicalMeasure +OAI.Analysis.Mahler.SourceCoordinateExterior +OAI.Analysis.Mahler.SourceCoordinateForms +OAI.Analysis.Mahler.SourceCoordinateMeasure +OAI.Analysis.Mahler.SourceExteriorDerivative +OAI.Analysis.Mahler.SourceFluxCoordinates +OAI.Analysis.Mahler.SourceFluxRegularity +OAI.Analysis.Mahler.SourceFullExterior +OAI.Analysis.Mahler.SourceHomogeneous +OAI.Analysis.Mahler.SourceLevelFlux +OAI.Analysis.Mahler.SourceLogC2 +OAI.Analysis.Mahler.SourcePrimitiveStokes +OAI.Analysis.Mahler.SourceRadiusFlux +OAI.Analysis.Mahler.SourceRawCoefficient +OAI.Analysis.Mahler.SourceRawJets +OAI.Analysis.Mahler.SourceRawOrientation +OAI.Analysis.Mahler.SourceRealExterior +OAI.Analysis.Mahler.SourceRegularFlux +OAI.Analysis.Mahler.SourceRegularLimit +OAI.Analysis.Mahler.SourceRegularMass +OAI.Analysis.Mahler.SourceRescaling +OAI.Analysis.Mahler.SourceSphereLimit +OAI.Analysis.Mahler.SourceStokes +OAI.Analysis.Mahler.SourceTopCoordinates +OAI.Analysis.Mahler.SpecialJacobian +OAI.Analysis.Mahler.SpecialLeadingTerm +OAI.Analysis.Mahler.SpecialMassBridge +OAI.Analysis.Mahler.SpecialMassHypotheses +OAI.Analysis.Mahler.SpecialSourceMass +OAI.Analysis.Mahler.SphereAreaTransport +OAI.Analysis.Mahler.SphereCoordinateIntegral +OAI.Analysis.Mahler.SphereDensityBridge +OAI.Analysis.Mahler.SphereDensityRestriction +OAI.Analysis.Mahler.SphereFlux +OAI.Analysis.Mahler.SphereFluxDifferentiation +OAI.Analysis.Mahler.SphereFluxIntegral +OAI.Analysis.Mahler.SphereFluxLimit +OAI.Analysis.Mahler.SphereForms +OAI.Analysis.Mahler.SphereNormalization +OAI.Analysis.Mahler.SphereOrientation +OAI.Analysis.Mahler.SphereRadius +OAI.Analysis.Mahler.SphereTransport +OAI.Analysis.Mahler.SphereVolumeOrientation +OAI.Analysis.Mahler.Splitting +OAI.Analysis.Mahler.StripCompactSublevels +OAI.Analysis.Mahler.StripDifferential +OAI.Analysis.Mahler.StripGeometry +OAI.Analysis.Mahler.StripJacobian +OAI.Analysis.Mahler.StripLevelGeometry +OAI.Analysis.Mahler.StripMassExhaustion +OAI.Analysis.Mahler.StripRankGeometry +OAI.Analysis.Mahler.StripRegularLevels +OAI.Analysis.Mahler.StripRegularValues +OAI.Analysis.Mahler.StripSublevelTopology +OAI.Analysis.Mahler.StripVolume +OAI.Analysis.Mahler.TailIntegral +OAI.Analysis.Mahler.UniformError +OAI.Analysis.Mahler.UniformJet +OAI.Analysis.Mahler.UnitaryReference +OAI.Analysis.Mahler.VerticalRadius +OAI.Analysis.Mahler.VerticalSpeed +OAI.Analysis.Mahler.WedgeAlgebra +OAI.Analysis.Mahler.WedgeAssociativity +OAI.Analysis.Mahler.WedgeCalculus +OAI.Analysis.Mahler.WedgeDecomposition +OAI.Analysis.Mahler.WedgeEven +OAI.Analysis.Mahler.WedgeOne +OAI.Analysis.Mahler.WedgeTwoDifferentialAlgebra +OAI.Analysis.Mahler.WedgeUnit diff --git a/tasks/symmetric-mahler-equality/solution/reference.py b/tasks/symmetric-mahler-equality/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/symmetric-mahler-equality/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/symmetric-mahler-equality/solution/solve.sh b/tasks/symmetric-mahler-equality/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..0b9d89af3fadd6a9bcf31d7158c646adccdcbcd7 --- /dev/null +++ b/tasks/symmetric-mahler-equality/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SymmetricMahlerEquality, i.e. module OAI.Analysis.Mahler.Classification and the +# 237 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Mahler.Classification /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SymmetricMahlerEquality" diff --git a/tasks/symmetric-mahler-equality/task.toml b/tasks/symmetric-mahler-equality/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1d073a9acefe3c577c04787f0405cc82895b961b --- /dev/null +++ b/tasks/symmetric-mahler-equality/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/symmetric-mahler-equality" +version = "1.0.0" +description = "Prove SymmetricMahlerEquality (openai/math family 087: The Mahler conjectures and symplectic width) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SymmetricMahlerEquality.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SymmetricMahlerEquality" +family = "087" +family_title = "The Mahler conjectures and symplectic width" +subject = "Convex and metric geometry" +theorems = ["OAI.SymmetricMahler.symmetric_mahler_equality"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Mahler.Classification" +reference_modules = 237 +reference_lean_bytes = 1330350 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 986 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12897 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/symmetric-mahler-equality/tests/Challenge.lean b/tasks/symmetric-mahler-equality/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..223abd8a20127f566a3e39b33c536f84d36abd86 --- /dev/null +++ b/tasks/symmetric-mahler-equality/tests/Challenge.lean @@ -0,0 +1,54 @@ +import Mathlib + +namespace OAI + +namespace SymmetricMahler + +section + +open Real Complex Set Finset +variable {I : Type*} [Fintype I] + +def coordinatePolar (K : Set (I → ℝ)) : Set (I → ℝ) := + {p | ∀ v ∈ K, (∑ i, p i*v i) ≤ 1} + +end + +noncomputable section + +open Set MeasureTheory Metric + +def hannerProduct {k l : ℕ} (A : Set (Fin k → ℝ)) (B : Set (Fin l → ℝ)) : + Set (Fin (k + l) → ℝ) := + {z | ∃ x ∈ A, ∃ y ∈ B, z = Fin.append x y} + +def hannerJoin {k l : ℕ} (A : Set (Fin k → ℝ)) (B : Set (Fin l → ℝ)) : + Set (Fin (k + l) → ℝ) := + convexHull ℝ + (((fun x : Fin k → ℝ => Fin.append x 0) '' A) ∪ + ((fun y : Fin l → ℝ => Fin.append 0 y) '' B)) + +inductive IsHanner : {n : ℕ} → Set (Fin n → ℝ) → Prop + | interval (a : ℝ) (ha : 0 < a) : + IsHanner (Icc (fun _ : Fin 1 => -a) (fun _ : Fin 1 => a)) + | product {k l : ℕ} {A : Set (Fin k → ℝ)} {B : Set (Fin l → ℝ)} + (hA : IsHanner A) (hB : IsHanner B) : IsHanner (hannerProduct A B) + | join {k l : ℕ} {A : Set (Fin k → ℝ)} {B : Set (Fin l → ℝ)} + (hA : IsHanner A) (hB : IsHanner B) : IsHanner (hannerJoin A B) + +def IsLinearHanner {n : ℕ} (K : Set (Fin n → ℝ)) : Prop := + ∃ H : Set (Fin n → ℝ), IsHanner H ∧ + ∃ T : (Fin n → ℝ) ≃ₗ[ℝ] (Fin n → ℝ), K = T '' H + +theorem symmetric_mahler_equality {n : ℕ} (hn : 1 ≤ n) + {K : Set (Fin n → ℝ)} (hK : IsCompact K) (hconv : Convex ℝ K) + (hsym : ∀ x ∈ K, -x ∈ K) (hint : (interior K).Nonempty) : + ((volume K).toReal * (volume (coordinatePolar K)).toReal = + (4 : ℝ)^n / (Nat.factorial n : ℝ)) ↔ IsLinearHanner K := by + sorry + +end + +end SymmetricMahler + +end OAI diff --git a/tasks/symmetric-mahler-equality/tests/grade.py b/tasks/symmetric-mahler-equality/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/symmetric-mahler-equality/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/symmetric-mahler-equality/tests/task.json b/tasks/symmetric-mahler-equality/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..14f4f0db5bf100f567436e2631171c3fd9a6be88 --- /dev/null +++ b/tasks/symmetric-mahler-equality/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SymmetricMahlerEquality", + "comparator": { + "theorem_names": [ + "OAI.SymmetricMahler.symmetric_mahler_equality" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11997 +} \ No newline at end of file diff --git a/tasks/symmetric-mahler-equality/tests/test.sh b/tasks/symmetric-mahler-equality/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/symmetric-mahler-equality/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/symmetric-polar/environment/Dockerfile b/tasks/symmetric-polar/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/symmetric-polar/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/symmetric-polar/environment/fetch_mathlib.sh b/tasks/symmetric-polar/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/symmetric-polar/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/symmetric-polar/environment/lake-manifest.json b/tasks/symmetric-polar/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/symmetric-polar/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/symmetric-polar/environment/lakefile.lean b/tasks/symmetric-polar/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/symmetric-polar/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/symmetric-polar/environment/lean_setup.sh b/tasks/symmetric-polar/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/symmetric-polar/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/symmetric-polar/environment/pack_submission.py b/tasks/symmetric-polar/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/symmetric-polar/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/symmetric-polar/instruction.md b/tasks/symmetric-polar/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..1902969d2b95d41cad2f8cee45a86c905503f80f --- /dev/null +++ b/tasks/symmetric-polar/instruction.md @@ -0,0 +1,100 @@ +# openai/math challenge `SymmetricPolar` (family 087) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 087 of the release, *The Mahler conjectures and symplectic width* +(Convex and metric geometry). The family as a whole: Resolves the symmetric and nonsymmetric geometric Mahler conjectures in every dimension, with Hanner polytopes and simplices as the respective volume-product minimizers and all equality cases classified. The corresponding sharp functional Mahler inequalities also hold. For $n\ge2$, every symmetric polar product $K\times K^\circ$ in dimension $2n$ has Gromov width $4$. + +The challenge is `SymmetricPolar`, also at `/opt/openai-math/challenges/SymmetricPolar.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set +open scoped ContDiff ENNReal + +namespace SymmetricPolar + +abbrev Position (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev Phase (n : ℕ) := Position n × Position n + +def IsSymmetricConvexBody {n : ℕ} (K : Set (Position n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty ∧ + ∀ x, x ∈ K ↔ -x ∈ K + +def polar {n : ℕ} (K : Set (Position n)) : Set (Position n) := + {p | ∀ q ∈ K, inner (𝕜 := ℝ) q p ≤ 1} + +def polarProduct {n : ℕ} (K : Set (Position n)) : Set (Phase n) := + interior K ×ˢ interior (polar K) + +def capacityBall (n : ℕ) (c : ℝ) : Set (Phase n) := + {z | Real.pi * (‖z.1‖ ^ 2 + ‖z.2‖ ^ 2) < c} + +noncomputable def omega0 {n : ℕ} (v w : Phase n) : ℝ := + inner (𝕜 := ℝ) v.1 w.2 - inner (𝕜 := ℝ) w.1 v.2 + +def HasSymplecticEmbedding {n : ℕ} (U V : Set (Phase n)) : Prop := + ∃ e : Phase n → Phase n, + ContDiffOn ℝ ∞ e U ∧ + Topology.IsEmbedding (fun z : U => e z) ∧ + MapsTo e U V ∧ + ∀ z ∈ U, ∀ v w : Phase n, + omega0 (fderiv ℝ e z v) (fderiv ℝ e z w) = omega0 v w + +noncomputable def gromovWidth {n : ℕ} (U : Set (Phase n)) : ℝ≥0∞ := + sSup (ENNReal.ofReal '' {c : ℝ | 0 < c ∧ HasSymplecticEmbedding (capacityBall n c) U}) + +theorem symmetric_polar_main {n : ℕ} (hn : 2 ≤ n) + (K : Set (Position n)) (hK : IsSymmetricConvexBody K) : + gromovWidth (polarProduct K) = 4 ∧ + ∀ c : ℝ, 0 < c → c < 4 → + HasSymplecticEmbedding (capacityBall n c) (polarProduct K) := by + sorry + +end SymmetricPolar + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/SymmetricPolar.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SymmetricPolar.symmetric_polar_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/symmetric-polar/solution/closure.txt b/tasks/symmetric-polar/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f965d84308cc609c3fef2f6ef1b31fefe8638796 --- /dev/null +++ b/tasks/symmetric-polar/solution/closure.txt @@ -0,0 +1,46 @@ +OAI.Geometry.PolarProducts.CanonicalCoordinates +OAI.Geometry.PolarProducts.CanonicalCylinder +OAI.Geometry.PolarProducts.CompleteFlow +OAI.Geometry.PolarProducts.Contraction +OAI.Geometry.PolarProducts.EmbeddingInverse +OAI.Geometry.PolarProducts.ExteriorHamiltonian +OAI.Geometry.PolarProducts.FiniteDescent +OAI.Geometry.PolarProducts.FourierIntegrals +OAI.Geometry.PolarProducts.FourierPaths +OAI.Geometry.PolarProducts.GalerkinBounds +OAI.Geometry.PolarProducts.GradientLinking +OAI.Geometry.PolarProducts.HamiltonianGrowth +OAI.Geometry.PolarProducts.HamiltonianODE +OAI.Geometry.PolarProducts.HolomorphicBalls +OAI.Geometry.PolarProducts.HorizontalIntegrals +OAI.Geometry.PolarProducts.LensArea +OAI.Geometry.PolarProducts.LensBounds +OAI.Geometry.PolarProducts.LensEstimates +OAI.Geometry.PolarProducts.LensMap +OAI.Geometry.PolarProducts.LocalODE +OAI.Geometry.PolarProducts.LogProfile +OAI.Geometry.PolarProducts.LowerBound +OAI.Geometry.PolarProducts.Main +OAI.Geometry.PolarProducts.Model +OAI.Geometry.PolarProducts.MomentumBounds +OAI.Geometry.PolarProducts.MoserField +OAI.Geometry.PolarProducts.MoserFlow +OAI.Geometry.PolarProducts.Nonsqueezing +OAI.Geometry.PolarProducts.PeriodicFourier +OAI.Geometry.PolarProducts.PeriodicSolutions +OAI.Geometry.PolarProducts.PlanarSquare +OAI.Geometry.PolarProducts.PolarApproximation +OAI.Geometry.PolarProducts.PotentialDeformation +OAI.Geometry.PolarProducts.PotentialForms +OAI.Geometry.PolarProducts.QuadraticAction +OAI.Geometry.PolarProducts.RadialMap +OAI.Geometry.PolarProducts.RegularizedMaximum +OAI.Geometry.PolarProducts.SmoothDegree +OAI.Geometry.PolarProducts.SmoothFlow +OAI.Geometry.PolarProducts.SmoothPaths +OAI.Geometry.PolarProducts.SmoothProfiles +OAI.Geometry.PolarProducts.StripEmbedding +OAI.Geometry.PolarProducts.StripMaps +OAI.Geometry.PolarProducts.TensorCalculus +OAI.Geometry.PolarProducts.TipEstimates +OAI.Geometry.PolarProducts.UpperBound diff --git a/tasks/symmetric-polar/solution/reference.py b/tasks/symmetric-polar/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/symmetric-polar/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/symmetric-polar/solution/solve.sh b/tasks/symmetric-polar/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..abc9e52cdce6fd34e89dff8d5f8db45063bd80f2 --- /dev/null +++ b/tasks/symmetric-polar/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of SymmetricPolar, i.e. module OAI.Geometry.PolarProducts.Main and the +# 46 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.PolarProducts.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of SymmetricPolar" diff --git a/tasks/symmetric-polar/task.toml b/tasks/symmetric-polar/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a1dd4206aa174e6991ced8366f846ced2b414404 --- /dev/null +++ b/tasks/symmetric-polar/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/symmetric-polar" +version = "1.0.0" +description = "Prove SymmetricPolar (openai/math family 087: The Mahler conjectures and symplectic width) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/SymmetricPolar.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "SymmetricPolar" +family = "087" +family_title = "The Mahler conjectures and symplectic width" +subject = "Convex and metric geometry" +theorems = ["OAI.SymmetricPolar.symmetric_polar_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.PolarProducts.Main" +reference_modules = 46 +reference_lean_bytes = 543383 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1068 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12189 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/symmetric-polar/tests/Challenge.lean b/tasks/symmetric-polar/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..56be6f5aed669656141c77a4e505d3d96924d6af --- /dev/null +++ b/tasks/symmetric-polar/tests/Challenge.lean @@ -0,0 +1,49 @@ +import Mathlib + +namespace OAI + +open Set +open scoped ContDiff ENNReal + +namespace SymmetricPolar + +abbrev Position (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev Phase (n : ℕ) := Position n × Position n + +def IsSymmetricConvexBody {n : ℕ} (K : Set (Position n)) : Prop := + IsCompact K ∧ Convex ℝ K ∧ (interior K).Nonempty ∧ + ∀ x, x ∈ K ↔ -x ∈ K + +def polar {n : ℕ} (K : Set (Position n)) : Set (Position n) := + {p | ∀ q ∈ K, inner (𝕜 := ℝ) q p ≤ 1} + +def polarProduct {n : ℕ} (K : Set (Position n)) : Set (Phase n) := + interior K ×ˢ interior (polar K) + +def capacityBall (n : ℕ) (c : ℝ) : Set (Phase n) := + {z | Real.pi * (‖z.1‖ ^ 2 + ‖z.2‖ ^ 2) < c} + +noncomputable def omega0 {n : ℕ} (v w : Phase n) : ℝ := + inner (𝕜 := ℝ) v.1 w.2 - inner (𝕜 := ℝ) w.1 v.2 + +def HasSymplecticEmbedding {n : ℕ} (U V : Set (Phase n)) : Prop := + ∃ e : Phase n → Phase n, + ContDiffOn ℝ ∞ e U ∧ + Topology.IsEmbedding (fun z : U => e z) ∧ + MapsTo e U V ∧ + ∀ z ∈ U, ∀ v w : Phase n, + omega0 (fderiv ℝ e z v) (fderiv ℝ e z w) = omega0 v w + +noncomputable def gromovWidth {n : ℕ} (U : Set (Phase n)) : ℝ≥0∞ := + sSup (ENNReal.ofReal '' {c : ℝ | 0 < c ∧ HasSymplecticEmbedding (capacityBall n c) U}) + +theorem symmetric_polar_main {n : ℕ} (hn : 2 ≤ n) + (K : Set (Position n)) (hK : IsSymmetricConvexBody K) : + gromovWidth (polarProduct K) = 4 ∧ + ∀ c : ℝ, 0 < c → c < 4 → + HasSymplecticEmbedding (capacityBall n c) (polarProduct K) := by + sorry + +end SymmetricPolar + +end OAI diff --git a/tasks/symmetric-polar/tests/grade.py b/tasks/symmetric-polar/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/symmetric-polar/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/symmetric-polar/tests/task.json b/tasks/symmetric-polar/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..720a93c8de7d9f7382697aad63071346fb86ba0b --- /dev/null +++ b/tasks/symmetric-polar/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "SymmetricPolar", + "comparator": { + "theorem_names": [ + "OAI.SymmetricPolar.symmetric_polar_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11289 +} \ No newline at end of file diff --git a/tasks/symmetric-polar/tests/test.sh b/tasks/symmetric-polar/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/symmetric-polar/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/tachikawa/environment/Dockerfile b/tasks/tachikawa/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/tachikawa/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/tachikawa/environment/fetch_mathlib.sh b/tasks/tachikawa/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/tachikawa/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/tachikawa/environment/lake-manifest.json b/tasks/tachikawa/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/tachikawa/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/tachikawa/environment/lakefile.lean b/tasks/tachikawa/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/tachikawa/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/tachikawa/environment/lean_setup.sh b/tasks/tachikawa/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/tachikawa/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/tachikawa/environment/pack_submission.py b/tasks/tachikawa/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/tachikawa/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/tachikawa/instruction.md b/tasks/tachikawa/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7d61acd5488a02c3be02e1b63d31a044fb03518d --- /dev/null +++ b/tasks/tachikawa/instruction.md @@ -0,0 +1,90 @@ +# openai/math challenge `Tachikawa` (family 199) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 199 of the release, *Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama* +(Algebra). The family as a whole: Constructs finite-dimensional algebras over a characteristic-two rational-function field that disprove the Auslander–Reiten and Gorenstein-projective conjectures, and Tachikawa's second conjecture. An associated endomorphism algebra also disproves the classical, generalized and strong Nakayama conjectures, the Auslander–Gorenstein conjecture, and the Wakamatsu tilting conjecture. The counterexamples persist under every extension of the base field. + +The challenge is `Tachikawa`, also at `/opt/openai-math/challenges/Tachikawa.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Tachikawa + +noncomputable section + +abbrev k := FractionRing (MvPolynomial (Fin 3) (ZMod 2)) + +def SymmetricOver (K A : Type) [Field K] [Ring A] [Algebra K A] : Prop := + ∃ e : A ≃ₗ[K] Module.Dual K A, + (∀ a b c : A, e (a * b) c = e b (c * a)) ∧ + (∀ a b c : A, e (a * b) c = e a (b * c)) + +def Counterexample : Prop := + ∃ (A : Type) (rA : Ring A), + letI := rA + ∃ (aA : Algebra k A), + letI := aA + Module.Finite k A ∧ SymmetricOver k A ∧ + ∃ (M : Type) (gM : AddCommGroup M), + letI := gM + ∃ (mA : Module A M) (mk : Module k M), + letI := mA + letI := mk + IsScalarTower k A M ∧ Module.Finite k M ∧ + ¬ Module.Projective A M ∧ + ∀ n : ℕ, 0 < n → + Subsingleton (CategoryTheory.Abelian.Ext (ModuleCat.of A M) (ModuleCat.of A M) n) + +theorem main_theorem : Counterexample := by + sorry + +end + +end Tachikawa + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/Tachikawa.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Tachikawa.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/tachikawa/solution/closure.txt b/tasks/tachikawa/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..20b03c11cec049e34857423e9ea8e6e6cb0e52c6 --- /dev/null +++ b/tasks/tachikawa/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.RingTheory.Tachikawa.Bimodule +OAI.RingTheory.Tachikawa.Coinduction +OAI.RingTheory.Tachikawa.CompleteResolution +OAI.RingTheory.Tachikawa.CompleteTensor +OAI.RingTheory.Tachikawa.Cone +OAI.RingTheory.Tachikawa.Coresolution +OAI.RingTheory.Tachikawa.Corner +OAI.RingTheory.Tachikawa.Counterexample +OAI.RingTheory.Tachikawa.Delta +OAI.RingTheory.Tachikawa.DerivedDescent +OAI.RingTheory.Tachikawa.DerivedInduction +OAI.RingTheory.Tachikawa.DownHom +OAI.RingTheory.Tachikawa.FiniteCoinduction +OAI.RingTheory.Tachikawa.HomProfile +OAI.RingTheory.Tachikawa.Induction +OAI.RingTheory.Tachikawa.Nakayama +OAI.RingTheory.Tachikawa.OuterExt +OAI.RingTheory.Tachikawa.OuterTensor +OAI.RingTheory.Tachikawa.Perfect +OAI.RingTheory.Tachikawa.Period +OAI.RingTheory.Tachikawa.ReverseResolution +OAI.RingTheory.Tachikawa.RightInduction +OAI.RingTheory.Tachikawa.Socle +OAI.RingTheory.Tachikawa.StableDuality +OAI.RingTheory.Tachikawa.StableLift +OAI.RingTheory.Tachikawa.StableShift +OAI.RingTheory.Tachikawa.Symmetry +OAI.RingTheory.Tachikawa.Tensor +OAI.RingTheory.Tachikawa.Triangular +OAI.RingTheory.Tachikawa.TwistHom +OAI.RingTheory.Tachikawa.Twisting diff --git a/tasks/tachikawa/solution/reference.py b/tasks/tachikawa/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/tachikawa/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/tachikawa/solution/solve.sh b/tasks/tachikawa/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c63280b940135c752a63c708b205fd925118c331 --- /dev/null +++ b/tasks/tachikawa/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of Tachikawa, i.e. module OAI.RingTheory.Tachikawa.Counterexample and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RingTheory.Tachikawa.Counterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of Tachikawa" diff --git a/tasks/tachikawa/task.toml b/tasks/tachikawa/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..a5fc97e7b2d4ddce1eb639de2a4414dd4b207586 --- /dev/null +++ b/tasks/tachikawa/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/tachikawa" +version = "1.0.0" +description = "Prove Tachikawa (openai/math family 199: Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/Tachikawa.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "Tachikawa" +family = "199" +family_title = "Counterexamples to conjectures of Auslander–Reiten, Tachikawa, and Nakayama" +subject = "Algebra" +theorems = ["OAI.Tachikawa.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RingTheory.Tachikawa.Counterexample" +reference_modules = 31 +reference_lean_bytes = 1264529 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1382 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12838 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/tachikawa/tests/Challenge.lean b/tasks/tachikawa/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e6966a6372659a10f77b45bd4a594e5c45b2bbef --- /dev/null +++ b/tasks/tachikawa/tests/Challenge.lean @@ -0,0 +1,39 @@ +import Mathlib + +namespace OAI + +namespace Tachikawa + +noncomputable section + +abbrev k := FractionRing (MvPolynomial (Fin 3) (ZMod 2)) + +def SymmetricOver (K A : Type) [Field K] [Ring A] [Algebra K A] : Prop := + ∃ e : A ≃ₗ[K] Module.Dual K A, + (∀ a b c : A, e (a * b) c = e b (c * a)) ∧ + (∀ a b c : A, e (a * b) c = e a (b * c)) + +def Counterexample : Prop := + ∃ (A : Type) (rA : Ring A), + letI := rA + ∃ (aA : Algebra k A), + letI := aA + Module.Finite k A ∧ SymmetricOver k A ∧ + ∃ (M : Type) (gM : AddCommGroup M), + letI := gM + ∃ (mA : Module A M) (mk : Module k M), + letI := mA + letI := mk + IsScalarTower k A M ∧ Module.Finite k M ∧ + ¬ Module.Projective A M ∧ + ∀ n : ℕ, 0 < n → + Subsingleton (CategoryTheory.Abelian.Ext (ModuleCat.of A M) (ModuleCat.of A M) n) + +theorem main_theorem : Counterexample := by + sorry + +end + +end Tachikawa + +end OAI diff --git a/tasks/tachikawa/tests/grade.py b/tasks/tachikawa/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/tachikawa/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/tachikawa/tests/task.json b/tasks/tachikawa/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a588ea395cc93b2462f5bfb8f4dffe671d867ed7 --- /dev/null +++ b/tasks/tachikawa/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "Tachikawa", + "comparator": { + "theorem_names": [ + "OAI.Tachikawa.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11938 +} \ No newline at end of file diff --git a/tasks/tachikawa/tests/test.sh b/tasks/tachikawa/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/tachikawa/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/talagrand-discrete-convexity/environment/Dockerfile b/tasks/talagrand-discrete-convexity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/talagrand-discrete-convexity/environment/fetch_mathlib.sh b/tasks/talagrand-discrete-convexity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/talagrand-discrete-convexity/environment/lake-manifest.json b/tasks/talagrand-discrete-convexity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/talagrand-discrete-convexity/environment/lakefile.lean b/tasks/talagrand-discrete-convexity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/talagrand-discrete-convexity/environment/lean_setup.sh b/tasks/talagrand-discrete-convexity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/talagrand-discrete-convexity/environment/pack_submission.py b/tasks/talagrand-discrete-convexity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/talagrand-discrete-convexity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/talagrand-discrete-convexity/instruction.md b/tasks/talagrand-discrete-convexity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..12f5edc2cc4e486c591a148ca8c872784051cc11 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/instruction.md @@ -0,0 +1,108 @@ +# openai/math challenge `TalagrandDiscreteConvexity` (family 175) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 175 of the release, *Talagrand's conjectures and graph decompositions at expectation thresholds* +(Combinatorics). The family as a whole: Proves that integral and fractional expectation thresholds differ by at most a universal factor, and resolves Talagrand's discrete-convexity conjecture. An application proves the Ascoli–He–Park–Talagrand graph-decomposition conjecture: every graph's edges split into a universally bounded number of fixed pieces, each with containment threshold at most a universal constant times the original graph's integral expectation threshold. The pieces' embeddings need not agree on shared vertices. + +The challenge is `TalagrandDiscreteConvexity`, also at `/opt/openai-math/challenges/TalagrandDiscreteConvexity.lean`: + +```lean +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Group.Finset + +namespace OAI + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +abbrev Family (α : Type*) := Finset (Finset α) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +/-- Independent Bernoulli coordinates, including every absent coordinate. -/ +def bernoulliMass (p : ℝ) (s : Finset α) : ℝ := + p ^ s.card * (1 - p) ^ (Finset.univ \ s).card + +/-- The probability of an arbitrary family, with no monotonicity condition. -/ +def familyMeasure (p : ℝ) (D : Family α) : ℝ := + ∑ s ∈ D, bernoulliMass p s + +/-- Each distinct generator is charged once at the original density. -/ +def cost (p : ℝ) (G : Family α) : ℝ := ∑ I ∈ G, p ^ I.card + +/-- Every covered set contains a generator. -/ +def Covers (G A : Family α) : Prop := ∀ S ∈ A, ∃ I ∈ G, I ⊆ S + +/-- An actual finite containment cover with total cost at most one half. -/ +def Small (p : ℝ) (A : Family α) : Prop := + ∃ G : Family α, Covers G A ∧ cost p G ≤ 1 / 2 + +/-- Exactly `k` entries, with no distinctness or disjointness restriction. -/ +def unionTuple {k : ℕ} (f : Fin k → Finset α) : Finset α := + Finset.univ.biUnion f + +/-- All subsets contained in no union of `k` members of the given family. -/ +def exceptional (k : ℕ) (D : Family α) : Family α := by + classical + exact Finset.univ.filter (fun S => + ∀ f : Fin k → Finset α, (∀ j, f j ∈ D) → ¬ S ⊆ unionTuple f) + +/-- Smallness at the original density for every positive ground-set size. -/ +theorem talagrand_discrete_convexity (N : ℕ) (_hN : 1 ≤ N) + (p : ℝ) (hp0 : 0 < p) (hp1 : p < 1) (D : Family (Fin N)) + (hD : 1 - 1 / (2 : ℝ) ^ 75 ≤ familyMeasure p D) : + Small p (exceptional ((2 : ℕ) ^ 75) D) := by + sorry + +end + +end TalagrandDiscreteConvexity + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TalagrandDiscreteConvexity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TalagrandDiscreteConvexity.talagrand_discrete_convexity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/talagrand-discrete-convexity/solution/closure.txt b/tasks/talagrand-discrete-convexity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e86556f8988b9b1bc1eddf53a24d226aeb20b50f --- /dev/null +++ b/tasks/talagrand-discrete-convexity/solution/closure.txt @@ -0,0 +1,36 @@ +OAI.Combinatorics.DiscreteConvexity.Basic +OAI.Combinatorics.DiscreteConvexity.Bernoulli +OAI.Combinatorics.DiscreteConvexity.BinNumerics +OAI.Combinatorics.DiscreteConvexity.Bins +OAI.Combinatorics.DiscreteConvexity.ColumnExpansion +OAI.Combinatorics.DiscreteConvexity.CoordinateObservations +OAI.Combinatorics.DiscreteConvexity.CoveringBasic +OAI.Combinatorics.DiscreteConvexity.CoveringBinomialBounds +OAI.Combinatorics.DiscreteConvexity.CoveringNumericalBounds +OAI.Combinatorics.DiscreteConvexity.CoveringPairCost +OAI.Combinatorics.DiscreteConvexity.CoveringRegularization +OAI.Combinatorics.DiscreteConvexity.CoveringResidualCost +OAI.Combinatorics.DiscreteConvexity.CoveringResidualProbability +OAI.Combinatorics.DiscreteConvexity.CoveringResidualTuples +OAI.Combinatorics.DiscreteConvexity.CoveringSampledFamilies +OAI.Combinatorics.DiscreteConvexity.DensityConstants +OAI.Combinatorics.DiscreteConvexity.DyadicBins +OAI.Combinatorics.DiscreteConvexity.ElementaryCovering +OAI.Combinatorics.DiscreteConvexity.ExceptionalWeightBound +OAI.Combinatorics.DiscreteConvexity.FiniteFibers +OAI.Combinatorics.DiscreteConvexity.FiniteParseval +OAI.Combinatorics.DiscreteConvexity.FiniteProbability +OAI.Combinatorics.DiscreteConvexity.FourierGlobalBound +OAI.Combinatorics.DiscreteConvexity.FourierProductKernel +OAI.Combinatorics.DiscreteConvexity.FourierWeights +OAI.Combinatorics.DiscreteConvexity.HalfDensity +OAI.Combinatorics.DiscreteConvexity.LabelCoupling +OAI.Combinatorics.DiscreteConvexity.Main +OAI.Combinatorics.DiscreteConvexity.MandatoryCoupling +OAI.Combinatorics.DiscreteConvexity.Model +OAI.Combinatorics.DiscreteConvexity.ProbabilisticExistence +OAI.Combinatorics.DiscreteConvexity.ProductProbability +OAI.Combinatorics.DiscreteConvexity.SignedArrays +OAI.Combinatorics.DiscreteConvexity.UnionBound +OAI.Combinatorics.DiscreteConvexity.UnionTuples +OAI.Combinatorics.DiscreteConvexity.WeightedCover diff --git a/tasks/talagrand-discrete-convexity/solution/reference.py b/tasks/talagrand-discrete-convexity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/talagrand-discrete-convexity/solution/solve.sh b/tasks/talagrand-discrete-convexity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9419c6cb1040fc117cd5a5d6ed3f6944cf3113d9 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TalagrandDiscreteConvexity, i.e. module OAI.Combinatorics.DiscreteConvexity.Main and the +# 36 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.DiscreteConvexity.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TalagrandDiscreteConvexity" diff --git a/tasks/talagrand-discrete-convexity/task.toml b/tasks/talagrand-discrete-convexity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..8f1034434108b8acc53c5c7a7623148363ead314 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/talagrand-discrete-convexity" +version = "1.0.0" +description = "Prove TalagrandDiscreteConvexity (openai/math family 175: Talagrand's conjectures and graph decompositions at expectation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TalagrandDiscreteConvexity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TalagrandDiscreteConvexity" +family = "175" +family_title = "Talagrand's conjectures and graph decompositions at expectation thresholds" +subject = "Combinatorics" +theorems = ["OAI.TalagrandDiscreteConvexity.talagrand_discrete_convexity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.DiscreteConvexity.Main" +reference_modules = 36 +reference_lean_bytes = 174257 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 439 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11856 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/talagrand-discrete-convexity/tests/Challenge.lean b/tasks/talagrand-discrete-convexity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d14e2fa6853931776b1268503eccb6ecbb07154b --- /dev/null +++ b/tasks/talagrand-discrete-convexity/tests/Challenge.lean @@ -0,0 +1,57 @@ +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Group.Finset + +namespace OAI + +namespace TalagrandDiscreteConvexity + +open scoped BigOperators + +abbrev Family (α : Type*) := Finset (Finset α) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +/-- Independent Bernoulli coordinates, including every absent coordinate. -/ +def bernoulliMass (p : ℝ) (s : Finset α) : ℝ := + p ^ s.card * (1 - p) ^ (Finset.univ \ s).card + +/-- The probability of an arbitrary family, with no monotonicity condition. -/ +def familyMeasure (p : ℝ) (D : Family α) : ℝ := + ∑ s ∈ D, bernoulliMass p s + +/-- Each distinct generator is charged once at the original density. -/ +def cost (p : ℝ) (G : Family α) : ℝ := ∑ I ∈ G, p ^ I.card + +/-- Every covered set contains a generator. -/ +def Covers (G A : Family α) : Prop := ∀ S ∈ A, ∃ I ∈ G, I ⊆ S + +/-- An actual finite containment cover with total cost at most one half. -/ +def Small (p : ℝ) (A : Family α) : Prop := + ∃ G : Family α, Covers G A ∧ cost p G ≤ 1 / 2 + +/-- Exactly `k` entries, with no distinctness or disjointness restriction. -/ +def unionTuple {k : ℕ} (f : Fin k → Finset α) : Finset α := + Finset.univ.biUnion f + +/-- All subsets contained in no union of `k` members of the given family. -/ +def exceptional (k : ℕ) (D : Family α) : Family α := by + classical + exact Finset.univ.filter (fun S => + ∀ f : Fin k → Finset α, (∀ j, f j ∈ D) → ¬ S ⊆ unionTuple f) + +/-- Smallness at the original density for every positive ground-set size. -/ +theorem talagrand_discrete_convexity (N : ℕ) (_hN : 1 ≤ N) + (p : ℝ) (hp0 : 0 < p) (hp1 : p < 1) (D : Family (Fin N)) + (hD : 1 - 1 / (2 : ℝ) ^ 75 ≤ familyMeasure p D) : + Small p (exceptional ((2 : ℕ) ^ 75) D) := by + sorry + +end + +end TalagrandDiscreteConvexity + +end OAI diff --git a/tasks/talagrand-discrete-convexity/tests/grade.py b/tasks/talagrand-discrete-convexity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/talagrand-discrete-convexity/tests/task.json b/tasks/talagrand-discrete-convexity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6388e79e01851c5de168be5d8657c5dcca1a2f78 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TalagrandDiscreteConvexity", + "comparator": { + "theorem_names": [ + "OAI.TalagrandDiscreteConvexity.talagrand_discrete_convexity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10956 +} \ No newline at end of file diff --git a/tasks/talagrand-discrete-convexity/tests/test.sh b/tasks/talagrand-discrete-convexity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/talagrand-discrete-convexity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/talagrand-expectation-threshold/environment/Dockerfile b/tasks/talagrand-expectation-threshold/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/talagrand-expectation-threshold/environment/fetch_mathlib.sh b/tasks/talagrand-expectation-threshold/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/talagrand-expectation-threshold/environment/lake-manifest.json b/tasks/talagrand-expectation-threshold/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/talagrand-expectation-threshold/environment/lakefile.lean b/tasks/talagrand-expectation-threshold/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/talagrand-expectation-threshold/environment/lean_setup.sh b/tasks/talagrand-expectation-threshold/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/talagrand-expectation-threshold/environment/pack_submission.py b/tasks/talagrand-expectation-threshold/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/talagrand-expectation-threshold/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/talagrand-expectation-threshold/instruction.md b/tasks/talagrand-expectation-threshold/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..284c3e957aa763e19bde020328929c773616c153 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/instruction.md @@ -0,0 +1,111 @@ +# openai/math challenge `TalagrandExpectationThreshold` (family 175) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 175 of the release, *Talagrand's conjectures and graph decompositions at expectation thresholds* +(Combinatorics). The family as a whole: Proves that integral and fractional expectation thresholds differ by at most a universal factor, and resolves Talagrand's discrete-convexity conjecture. An application proves the Ascoli–He–Park–Talagrand graph-decomposition conjecture: every graph's edges split into a universally bounded number of fixed pieces, each with containment threshold at most a universal constant times the original graph's integral expectation threshold. The pieces' embeddings need not agree on shared vertices. + +The challenge is `TalagrandExpectationThreshold`, also at `/opt/openai-math/challenges/TalagrandExpectationThreshold.lean`: + +```lean +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise + +namespace OAI + +namespace TalagrandThreshold + +open scoped BigOperators + +abbrev Family (α : Type*) := Finset (Finset α) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +def cost (p : ℝ) (G : Family α) : ℝ := ∑ S ∈ G, p ^ S.card + +def Covers (G F : Family α) : Prop := ∀ H ∈ F, ∃ S ∈ G, S ⊆ H + +def Small (p : ℝ) (F : Family α) : Prop := + ∃ G : Family α, Covers G F ∧ cost p G ≤ 1 / 2 + +def fracCost (p : ℝ) (g : Finset α → ℝ) : ℝ := + ∑ S : Finset α, g S * p ^ S.card + +def FractionalCover (F : Family α) (g : Finset α → ℝ) : Prop := + (∀ S, 0 ≤ g S ∧ g S ≤ 1) ∧ + ∀ H ∈ F, 1 ≤ ∑ S ∈ H.powerset, g S + +def FractionalSmall (p : ℝ) (F : Family α) : Prop := + ∃ g : Finset α → ℝ, FractionalCover F g ∧ fracCost p g ≤ 1 / 2 + +def Increasing (F : Family α) : Prop := + ∀ H ∈ F, ∀ K : Finset α, H ⊆ K → K ∈ F + +def integralFeasible (F : Family α) : Set ℝ := + {p | 0 ≤ p ∧ p ≤ 1 ∧ Small p F} + +def fractionalFeasible (F : Family α) : Set ℝ := + {p | 0 ≤ p ∧ p ≤ 1 ∧ FractionalSmall p F} + +def q (F : Family α) : ℝ := sSup (integralFeasible F) + +def qf (F : Family α) : ℝ := sSup (fractionalFeasible F) + +end + +theorem talagrand_expectation_threshold_equivalence [Nonempty α] + (F : Family α) (_hF : F.Nonempty) (hproper : F ≠ Finset.univ) + (hIncreasing : Increasing F) : + qf F ≤ ((25 : ℝ) * (512 : ℝ) ^ 4) * q F := by + sorry + +end TalagrandThreshold + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TalagrandExpectationThreshold.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TalagrandThreshold.talagrand_expectation_threshold_equivalence` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/talagrand-expectation-threshold/solution/closure.txt b/tasks/talagrand-expectation-threshold/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a988bb3b8c49de2ee61a2a905c094ac8fa4c4fb7 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/solution/closure.txt @@ -0,0 +1,47 @@ +OAI.Combinatorics.ExpectationThreshold.Basic +OAI.Combinatorics.ExpectationThreshold.ColorArithmetic +OAI.Combinatorics.ExpectationThreshold.ColorMean +OAI.Combinatorics.ExpectationThreshold.Main +OAI.Combinatorics.ExpectationThreshold.Model +OAI.Combinatorics.ExpectationThreshold.ProbabilityColors +OAI.Combinatorics.ExpectationThreshold.ProbabilityFinite +OAI.Combinatorics.ExpectationThreshold.ProbabilityLikelihood +OAI.Combinatorics.ExpectationThreshold.ProbabilityProduct +OAI.Combinatorics.ExpectationThreshold.ProbabilitySubsetProduct +OAI.Combinatorics.ExpectationThreshold.RoundingColorProducts +OAI.Combinatorics.ExpectationThreshold.RoundingExpectation +OAI.Combinatorics.ExpectationThreshold.RoundingLowerBound +OAI.Combinatorics.ExpectationThreshold.RoundingMain +OAI.Combinatorics.ExpectationThreshold.RoundingMasses +OAI.Combinatorics.ExpectationThreshold.RoundingProbabilityContradiction +OAI.Combinatorics.ExpectationThreshold.ScaleBounds +OAI.Combinatorics.ExpectationThreshold.SelectorAverageColor +OAI.Combinatorics.ExpectationThreshold.SelectorCommonWitness +OAI.Combinatorics.ExpectationThreshold.SelectorCountingEncoding +OAI.Combinatorics.ExpectationThreshold.SelectorCountingEncodingBound +OAI.Combinatorics.ExpectationThreshold.SelectorCountingEncodingRows +OAI.Combinatorics.ExpectationThreshold.SelectorCountingWords +OAI.Combinatorics.ExpectationThreshold.SelectorCountingWordsProducts +OAI.Combinatorics.ExpectationThreshold.SelectorCountingWordsTransport +OAI.Combinatorics.ExpectationThreshold.SelectorDefinitions +OAI.Combinatorics.ExpectationThreshold.SelectorDefinitionsLemmas +OAI.Combinatorics.ExpectationThreshold.SelectorDelay +OAI.Combinatorics.ExpectationThreshold.SelectorDelayFeasibility +OAI.Combinatorics.ExpectationThreshold.SelectorEntropy +OAI.Combinatorics.ExpectationThreshold.SelectorEntropyDyadic +OAI.Combinatorics.ExpectationThreshold.SelectorFeasibility +OAI.Combinatorics.ExpectationThreshold.SelectorGlobalCost +OAI.Combinatorics.ExpectationThreshold.SelectorGlobalCostProfiles +OAI.Combinatorics.ExpectationThreshold.SelectorGroupCost +OAI.Combinatorics.ExpectationThreshold.SelectorMain +OAI.Combinatorics.ExpectationThreshold.SelectorProfile +OAI.Combinatorics.ExpectationThreshold.SelectorReconstruction +OAI.Combinatorics.ExpectationThreshold.SelectorTruncation +OAI.Combinatorics.ExpectationThreshold.SelectorTruncationCompact +OAI.Combinatorics.ExpectationThreshold.SelectorTruncationDefinitions +OAI.Combinatorics.ExpectationThreshold.SelectorTruncationSlope +OAI.Combinatorics.ExpectationThreshold.ThresholdAttainment +OAI.Combinatorics.ExpectationThreshold.ThresholdBounds +OAI.Combinatorics.ExpectationThreshold.ThresholdCompactness +OAI.Combinatorics.ExpectationThreshold.TupleCoefficients +OAI.Combinatorics.ExpectationThreshold.TupleGeometric diff --git a/tasks/talagrand-expectation-threshold/solution/reference.py b/tasks/talagrand-expectation-threshold/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/talagrand-expectation-threshold/solution/solve.sh b/tasks/talagrand-expectation-threshold/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..301202fc3fe461de262b10fbde970a41b16934bf --- /dev/null +++ b/tasks/talagrand-expectation-threshold/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TalagrandExpectationThreshold, i.e. module OAI.Combinatorics.ExpectationThreshold.Main and the +# 47 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.ExpectationThreshold.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TalagrandExpectationThreshold" diff --git a/tasks/talagrand-expectation-threshold/task.toml b/tasks/talagrand-expectation-threshold/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3f3296ba1d2f09a6556fd7a1b440083a12b2e6d2 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/talagrand-expectation-threshold" +version = "1.0.0" +description = "Prove TalagrandExpectationThreshold (openai/math family 175: Talagrand's conjectures and graph decompositions at expectation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TalagrandExpectationThreshold.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TalagrandExpectationThreshold" +family = "175" +family_title = "Talagrand's conjectures and graph decompositions at expectation thresholds" +subject = "Combinatorics" +theorems = ["OAI.TalagrandThreshold.talagrand_expectation_threshold_equivalence"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.ExpectationThreshold.Main" +reference_modules = 47 +reference_lean_bytes = 192418 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 213 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11873 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/talagrand-expectation-threshold/tests/Challenge.lean b/tasks/talagrand-expectation-threshold/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..377c9c9fc595ae20a590bdd54bc78ce8c665fbb2 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/tests/Challenge.lean @@ -0,0 +1,60 @@ +import Mathlib.Data.Fintype.Powerset +import Mathlib.Data.Finset.Union +import Mathlib.Basic.Real.Basic +import Mathlib.Algebra.Order.Archimedean.Real.Basic +import Mathlib.Algebra.Order.BigOperators.Group.Finset +import Mathlib.Algebra.BigOperators.Group.Finset.Piecewise + +namespace OAI + +namespace TalagrandThreshold + +open scoped BigOperators + +abbrev Family (α : Type*) := Finset (Finset α) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable section + +def cost (p : ℝ) (G : Family α) : ℝ := ∑ S ∈ G, p ^ S.card + +def Covers (G F : Family α) : Prop := ∀ H ∈ F, ∃ S ∈ G, S ⊆ H + +def Small (p : ℝ) (F : Family α) : Prop := + ∃ G : Family α, Covers G F ∧ cost p G ≤ 1 / 2 + +def fracCost (p : ℝ) (g : Finset α → ℝ) : ℝ := + ∑ S : Finset α, g S * p ^ S.card + +def FractionalCover (F : Family α) (g : Finset α → ℝ) : Prop := + (∀ S, 0 ≤ g S ∧ g S ≤ 1) ∧ + ∀ H ∈ F, 1 ≤ ∑ S ∈ H.powerset, g S + +def FractionalSmall (p : ℝ) (F : Family α) : Prop := + ∃ g : Finset α → ℝ, FractionalCover F g ∧ fracCost p g ≤ 1 / 2 + +def Increasing (F : Family α) : Prop := + ∀ H ∈ F, ∀ K : Finset α, H ⊆ K → K ∈ F + +def integralFeasible (F : Family α) : Set ℝ := + {p | 0 ≤ p ∧ p ≤ 1 ∧ Small p F} + +def fractionalFeasible (F : Family α) : Set ℝ := + {p | 0 ≤ p ∧ p ≤ 1 ∧ FractionalSmall p F} + +def q (F : Family α) : ℝ := sSup (integralFeasible F) + +def qf (F : Family α) : ℝ := sSup (fractionalFeasible F) + +end + +theorem talagrand_expectation_threshold_equivalence [Nonempty α] + (F : Family α) (_hF : F.Nonempty) (hproper : F ≠ Finset.univ) + (hIncreasing : Increasing F) : + qf F ≤ ((25 : ℝ) * (512 : ℝ) ^ 4) * q F := by + sorry + +end TalagrandThreshold + +end OAI diff --git a/tasks/talagrand-expectation-threshold/tests/grade.py b/tasks/talagrand-expectation-threshold/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/talagrand-expectation-threshold/tests/task.json b/tasks/talagrand-expectation-threshold/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5dea215c94257e30c9ec78cba50503b5db19b547 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TalagrandExpectationThreshold", + "comparator": { + "theorem_names": [ + "OAI.TalagrandThreshold.talagrand_expectation_threshold_equivalence" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10973 +} \ No newline at end of file diff --git a/tasks/talagrand-expectation-threshold/tests/test.sh b/tasks/talagrand-expectation-threshold/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/talagrand-expectation-threshold/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thomason-model-structures/environment/Dockerfile b/tasks/thomason-model-structures/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thomason-model-structures/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thomason-model-structures/environment/fetch_mathlib.sh b/tasks/thomason-model-structures/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thomason-model-structures/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thomason-model-structures/environment/lake-manifest.json b/tasks/thomason-model-structures/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thomason-model-structures/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thomason-model-structures/environment/lakefile.lean b/tasks/thomason-model-structures/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thomason-model-structures/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thomason-model-structures/environment/lean_setup.sh b/tasks/thomason-model-structures/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thomason-model-structures/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thomason-model-structures/environment/pack_submission.py b/tasks/thomason-model-structures/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thomason-model-structures/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thomason-model-structures/instruction.md b/tasks/thomason-model-structures/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2559e743d485cc1cf66f77fc4314b8d4b97fec6e --- /dev/null +++ b/tasks/thomason-model-structures/instruction.md @@ -0,0 +1,2524 @@ +# openai/math challenge `ThomasonModelStructures` (family 317) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 317 of the release, *Thomason model structures in every strict higher dimension* +(Topology). The family as a whole: Resolves the Ara–Maltsiniotis conjecture: for every $n\ge1$ and $n=\omega$, small strict globular $n$-categories admit proper combinatorial Thomason model structures Quillen equivalent to simplicial sets. Thus strict higher categories model the homotopy theory of spaces in every stated dimension. + +The challenge is `ThomasonModelStructures`, also at `/opt/openai-math/challenges/ThomasonModelStructures.lean`: + +```lean +import Mathlib + +/-! Definitions for the Thomason model structures and their Street-nerve detection statement. -/ + +noncomputable section +universe u v w + +section +namespace OAI.Thomason + + +structure OmegaCategory where + Cell : Type u + source : ℕ → Cell → Cell + target : ℕ → Cell → Cell + source_source (i j : ℕ) (x : Cell) : source i (source j x) = source (min i j) x + target_target (i j : ℕ) (x : Cell) : target i (target j x) = target (min i j) x + source_target (i j : ℕ) (x : Cell) : + source i (target j x) = if i < j then source i x else target j x + target_source (i j : ℕ) (x : Cell) : + target i (source j x) = if i < j then target i x else source j x + comp (k : ℕ) (x y : Cell) : target k x = source k y → Cell + source_comp_le (i k : ℕ) (hik : i ≤ k) (x y : Cell) + (h : target k x = source k y) : source i (comp k x y h) = source i x + target_comp_le (i k : ℕ) (hik : i ≤ k) (x y : Cell) + (h : target k x = source k y) : target i (comp k x y h) = target i y + source_comp_gt (i k : ℕ) (hki : k < i) (x y : Cell) + (h : target k x = source k y) + (hs : target k (source i x) = source k (source i y)) : + source i (comp k x y h) = comp k (source i x) (source i y) hs + target_comp_gt (i k : ℕ) (hki : k < i) (x y : Cell) + (h : target k x = source k y) + (ht : target k (target i x) = source k (target i y)) : + target i (comp k x y h) = comp k (target i x) (target i y) ht + unit_left (k : ℕ) (x : Cell) (h : target k (source k x) = source k x) : + comp k (source k x) x h = x + unit_right (k : ℕ) (x : Cell) (h : target k x = source k (target k x)) : + comp k x (target k x) h = x + assoc (k : ℕ) (x y z : Cell) + (hxy : target k x = source k y) (hyz : target k y = source k z) + (hxy_z : target k (comp k x y hxy) = source k z) + (hx_yz : target k x = source k (comp k y z hyz)) : + comp k (comp k x y hxy) z hxy_z = comp k x (comp k y z hyz) hx_yz + interchange (k l : ℕ) (hkl : k < l) (a b c d : Cell) + (hab : target l a = source l b) (hcd : target l c = source l d) + (hac : target k a = source k c) (hbd : target k b = source k d) + (hab_cd : target k (comp l a b hab) = source k (comp l c d hcd)) + (hac_bd : target l (comp k a c hac) = source l (comp k b d hbd)) : + comp k (comp l a b hab) (comp l c d hcd) hab_cd = + comp l (comp k a c hac) (comp k b d hbd) hac_bd + finite_dimension (x : Cell) : ∃ k, source k x = x + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory +variable (C : OmegaCategory.{u}) + +@[ext] +structure Functor (C : OAI.Thomason.OmegaCategory.{u}) (D : OAI.Thomason.OmegaCategory.{v}) where + map : C.Cell → D.Cell + map_source (k : ℕ) (x : C.Cell) : map (C.source k x) = D.source k (map x) + map_target (k : ℕ) (x : C.Cell) : map (C.target k x) = D.target k (map x) + map_comp (k : ℕ) (x y : C.Cell) (h : C.target k x = C.source k y) + (h' : D.target k (map x) = D.source k (map y)) : + map (C.comp k x y h) = D.comp k (map x) (map y) h' + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Functor +variable (C : OmegaCategory.{u}) +variable {C : OmegaCategory.{u}} {D : OmegaCategory.{v}} {B : OmegaCategory.{w}} + +noncomputable def id (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor C C where + map x := x + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + +noncomputable def comp (F : OAI.Thomason.OmegaCategory.Functor C D) (G : OAI.Thomason.OmegaCategory.Functor D B) : OAI.Thomason.OmegaCategory.Functor C B := by + classical + have proof_map_composable_0 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{v}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + exact { + map x := G.map (F.map x) + map_source k x := by rw [F.map_source, G.map_source] + map_target k x := by rw [F.map_target, G.map_target] + map_comp k x y h h' := by + rw [F.map_comp k x y h (proof_map_composable_0 F h), G.map_comp] + } + + +end OAI.Thomason.OmegaCategory.Functor +end + +section +namespace OAI.Thomason.OmegaCategory +variable (C : OmegaCategory.{u}) + +noncomputable instance : CategoryTheory.Category OAI.Thomason.OmegaCategory.{u} where + Hom C D := OAI.Thomason.OmegaCategory.Functor C D + id := OAI.Thomason.OmegaCategory.Functor.id + comp := OAI.Thomason.OmegaCategory.Functor.comp + +noncomputable def IsTruncated (n : ℕ) : Prop := ∀ x : C.Cell, C.source n x = x + +noncomputable def NCategory (n : ℕ) := {C : OAI.Thomason.OmegaCategory.{u} // C.IsTruncated n} + +noncomputable instance (n : ℕ) : CategoryTheory.Category (OAI.Thomason.OmegaCategory.NCategory.{u} n) where + Hom C D := OAI.Thomason.OmegaCategory.Functor C.val D.val + id C := OAI.Thomason.OmegaCategory.Functor.id C.val + comp := OAI.Thomason.OmegaCategory.Functor.comp + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason + + +structure DirectedComplex where + Chain : ℕ → Type u + group : ∀ p, AddCommGroup (Chain p) + d : (p : ℕ) → Chain (p+1) →+ Chain p + d_d (p : ℕ) (x : Chain (p+2)) : d p (d (p+1) x) = 0 + augmentation : Chain 0 →+ ℤ + augmentation_d (x : Chain 1) : augmentation (d 0 x) = 0 + positive : (p : ℕ) → AddSubmonoid (Chain p) + +end OAI.Thomason +end + +attribute [instance] OAI.Thomason.DirectedComplex.group + +section +namespace OAI.Thomason.DirectedComplex + + +@[ext] +structure Hom (K : OAI.Thomason.DirectedComplex.{u}) (L : OAI.Thomason.DirectedComplex.{v}) where + map (p : ℕ) : K.Chain p →+ L.Chain p + map_d (p : ℕ) (x : K.Chain (p+1)) : map p (K.d p x) = L.d p (map (p+1) x) + map_augmentation (x : K.Chain 0) : L.augmentation (map 0 x) = K.augmentation x + map_positive (p : ℕ) (x : K.Chain p) : x ∈ K.positive p → map p x ∈ L.positive p + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Hom +variable {K : DirectedComplex.{u}} {L : DirectedComplex.{v}} {M : DirectedComplex.{w}} + +noncomputable def id (K : OAI.Thomason.DirectedComplex.{u}) : OAI.Thomason.DirectedComplex.Hom K K where + map _ := AddMonoidHom.id _ + map_d _ _ := rfl + map_augmentation _ := rfl + map_positive _ _ h := h + +noncomputable def comp (f : OAI.Thomason.DirectedComplex.Hom K L) (g : OAI.Thomason.DirectedComplex.Hom L M) : OAI.Thomason.DirectedComplex.Hom K M where + map p := (g.map p).comp (f.map p) + map_d p x := by simp only [AddMonoidHom.comp_apply, f.map_d, g.map_d] + map_augmentation x := by simp only [AddMonoidHom.comp_apply, + g.map_augmentation, f.map_augmentation] + map_positive p x hx := g.map_positive p _ (f.map_positive p x hx) + + +end OAI.Thomason.DirectedComplex.Hom +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable instance : CategoryTheory.Category OAI.Thomason.DirectedComplex.{u} where + Hom := OAI.Thomason.DirectedComplex.Hom + id := OAI.Thomason.DirectedComplex.Hom.id + comp := OAI.Thomason.DirectedComplex.Hom.comp + +@[ext] +structure Table (K : OAI.Thomason.DirectedComplex.{u}) where + row : (p : ℕ) → Bool → K.Chain p + positive (p : ℕ) (b : Bool) : row p b ∈ K.positive p + boundary (p : ℕ) (b : Bool) : + K.d p (row (p+1) b) = row p true - row p false + augmentation (b : Bool) : K.augmentation (row 0 b) = 1 + bounded : ∃ k, ∀ p, k < p → ∀ b, row p b = 0 + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Table +variable {K : DirectedComplex.{u}} + +noncomputable def truncate (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : OAI.Thomason.DirectedComplex.Table K where + row p b := if p < k then x.row p b else if p = k then x.row p e else 0 + positive p b := by + split_ifs <;> first | exact x.positive _ _ | exact (K.positive _).zero_mem + boundary p b := by + by_cases hp : p < k + · by_cases hp' : p+1 < k + · simp only [hp, hp', ite_eq_left] + exact x.boundary p b + · have he : p+1 = k := by omega + simp only [ite_eq_left hp, ite_eq_right hp', ite_eq_left he] + exact x.boundary p e + · by_cases he : p = k + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [ite_eq_right hp, ite_eq_right hp', ite_eq_right he', ite_eq_left he, map_zero, sub_self] + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [hp, hp', he', he, ite_false, map_zero, sub_self] + augmentation b := by + by_cases hk : k = 0 + · subst k + simpa using x.augmentation e + · have hk' : 0 < k := Nat.pos_of_ne_zero hk + simpa only [hk', ite_eq_left] using x.augmentation b + bounded := by + refine ⟨k, ?_⟩ + intro p hp b + simp only [show ¬p < k by omega, show ¬p = k by omega, ite_false] + +noncomputable def comp (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : OAI.Thomason.DirectedComplex.Table K := by + classical + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_lower_rows_eq_1 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) {p : ℕ} (hp : p < k) (b : Bool) : + x.row p b = y.row p b := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row p b) h + simpa only [OAI.Thomason.DirectedComplex.Table.truncate, hp, ite_eq_left] using hr + have proof_matching_row_eq_2 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : x.row k true = y.row k false := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row k false) h + simpa [OAI.Thomason.DirectedComplex.Table.truncate] using hr + exact { + row p b := if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b + positive p b := by + split_ifs <;> first + | exact x.positive _ _ + | exact y.positive _ _ + | exact (K.positive _).add_mem (x.positive _ _) (y.positive _ _) + boundary p b := by + by_cases hp : p < k + · by_cases hp' : p+1 < k + · simp only [ite_eq_left hp, ite_eq_left hp'] + exact x.boundary p b + · have he : p+1 = k := by omega + simp only [ite_eq_left hp, ite_eq_right hp', ite_eq_left he] + cases b with + | false => exact x.boundary p false + | true => + change K.d p (y.row (p+1) true) = x.row p true - x.row p false + rw [y.boundary, proof_lower_rows_eq_1 h hp true, proof_lower_rows_eq_1 h hp false] + · by_cases he : p = k + · subst p + have hp' : ¬k+1 < k := by omega + have he' : ¬k+1 = k := by omega + simp only [ite_eq_right (Nat.lt_irrefl k), ite_eq_right hp', ite_eq_right he', + ↓reduceIte, map_add, x.boundary, y.boundary] + rw [proof_matching_row_eq_2 h] + abel_nf + exact add_comm _ _ + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [ite_eq_right hp, ite_eq_right hp', ite_eq_right he', ite_eq_right he, map_add, + x.boundary, y.boundary] + abel + augmentation b := by + by_cases hk : 0 < k + · simp only [ite_eq_left hk] + exact x.augmentation b + · have he : 0 = k := by omega + simp only [ite_eq_right hk, ite_eq_left he] + cases b <;> first | exact x.augmentation _ | exact y.augmentation _ + bounded := by + obtain ⟨nx, hx⟩ := x.bounded + obtain ⟨ny, hy⟩ := y.bounded + refine ⟨max nx ny, ?_⟩ + intro p hp b + have hx' := hx p (lt_of_le_of_lt (le_max_left _ _) hp) + have hy' := hy p (lt_of_le_of_lt (le_max_right _ _) hp) + split_ifs <;> simp only [hx', hy', zero_add] + } + + +end OAI.Thomason.DirectedComplex.Table +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable def nu (K : OAI.Thomason.DirectedComplex.{u}) : OAI.Thomason.OmegaCategory.{u} := by + classical + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_truncate_truncate_5 {K : OAI.Thomason.DirectedComplex.{u}} (i j : ℕ) (e f : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.truncate j f x) = + if i < j then OAI.Thomason.DirectedComplex.Table.truncate i e x else OAI.Thomason.DirectedComplex.Table.truncate j f x := by + ext p b + by_cases hij : i < j + · simp only [hij, ite_eq_left, OAI.Thomason.DirectedComplex.Table.truncate] + by_cases hpi : p < i + · have hpj : p < j := lt_trans hpi hij + simp [hpi, hpj] + · by_cases hpe : p = i + · subst p + simp [hij] + · simp [hpi, hpe] + · simp only [hij, ite_false, OAI.Thomason.DirectedComplex.Table.truncate] + by_cases hpj : p < j + · have hpi : p < i := by omega + simp [hpj, hpi] + · by_cases hpje : p = j + · subst p + by_cases hji : j < i + · simp [hji] + · have hi : i = j := by omega + subst i + simp [] + · by_cases hpi : p < i + · simp [hpi, hpj, hpje] + · by_cases hpie : p = i + · subst p + simp [hij] + · simp [hpi, hpie, hpj, hpje] + have proof_truncate_truncate_same_4 {K : OAI.Thomason.DirectedComplex.{u}} (i j : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.truncate j e x) = OAI.Thomason.DirectedComplex.Table.truncate (min i j) e x := by + rw [proof_truncate_truncate_5] + split_ifs with h + · rw [min_eq_left (le_of_lt h)] + · rw [min_eq_right (le_of_not_gt h)] + have proof_comp_row_14 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.comp k x y h).row p b = if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b := rfl + have proof_source_comp_le_6 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hik : i ≤ k) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : + OAI.Thomason.DirectedComplex.Table.truncate i false (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.truncate i false x := by + ext p b + by_cases hpi : p < i + · have hpk : p < k := lt_of_lt_of_le hpi hik + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpk] + · by_cases hpe : p = i + · subst p + by_cases hik' : i < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik'] + · have he : i = k := by omega + subst i + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpe] + have proof_lower_rows_eq_1 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) {p : ℕ} (hp : p < k) (b : Bool) : + x.row p b = y.row p b := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row p b) h + simpa only [OAI.Thomason.DirectedComplex.Table.truncate, hp, ite_eq_left] using hr + have proof_target_comp_le_7 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hik : i ≤ k) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : + OAI.Thomason.DirectedComplex.Table.truncate i true (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.truncate i true y := by + ext p b + by_cases hpi : p < i + · have hpk : p < k := lt_of_lt_of_le hpi hik + simp only [OAI.Thomason.DirectedComplex.Table.truncate, ite_eq_left hpi, OAI.Thomason.DirectedComplex.Table.comp, ite_eq_left hpk] + exact proof_lower_rows_eq_1 h hpk b + · by_cases hpe : p = i + · subst p + by_cases hik' : i < k + · simpa [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik'] using proof_lower_rows_eq_1 h hik' true + · have he : i = k := by omega + subst i + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpe] + have proof_truncate_comp_gt_8 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hki : k < i) (e : Bool) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (h' : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.truncate i e x) = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.truncate i e y)) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.truncate i e x) (OAI.Thomason.DirectedComplex.Table.truncate i e y) h' := by + ext p b + by_cases hpk : p < k + · have hpi : p < i := lt_trans hpk hki + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpi] + · by_cases hpe : p = k + · subst p + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hki] + · by_cases hpi : p < i + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpi] + · by_cases hpie : p = i + · subst p + have hik : ¬i < k := by omega + have hie : ¬i = k := by omega + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik, hie] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpi, hpie] + have proof_unit_left_9 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.truncate k false x) = OAI.Thomason.DirectedComplex.Table.truncate k false x) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.truncate k false x) x h = x := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp, he] + have proof_unit_right_10 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.truncate k true x)) : + OAI.Thomason.DirectedComplex.Table.comp k x (OAI.Thomason.DirectedComplex.Table.truncate k true x) h = x := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp, he] + have proof_assoc_11 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y z : OAI.Thomason.DirectedComplex.Table K) + (hxy : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (hyz : OAI.Thomason.DirectedComplex.Table.truncate k true y = OAI.Thomason.DirectedComplex.Table.truncate k false z) + (hxy_z : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.comp k x y hxy) = OAI.Thomason.DirectedComplex.Table.truncate k false z) + (hx_yz : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.comp k y z hyz)) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.comp k x y hxy) z hxy_z = OAI.Thomason.DirectedComplex.Table.comp k x (OAI.Thomason.DirectedComplex.Table.comp k y z hyz) hx_yz := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.comp, hp, he, add_assoc] + have proof_interchange_12 {K : OAI.Thomason.DirectedComplex.{u}} (k l : ℕ) (hkl : k < l) (a b c d : OAI.Thomason.DirectedComplex.Table K) + (hab : OAI.Thomason.DirectedComplex.Table.truncate l true a = OAI.Thomason.DirectedComplex.Table.truncate l false b) + (hcd : OAI.Thomason.DirectedComplex.Table.truncate l true c = OAI.Thomason.DirectedComplex.Table.truncate l false d) + (hac : OAI.Thomason.DirectedComplex.Table.truncate k true a = OAI.Thomason.DirectedComplex.Table.truncate k false c) + (hbd : OAI.Thomason.DirectedComplex.Table.truncate k true b = OAI.Thomason.DirectedComplex.Table.truncate k false d) + (hab_cd : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.comp l a b hab) = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.comp l c d hcd)) + (hac_bd : OAI.Thomason.DirectedComplex.Table.truncate l true (OAI.Thomason.DirectedComplex.Table.comp k a c hac) = OAI.Thomason.DirectedComplex.Table.truncate l false (OAI.Thomason.DirectedComplex.Table.comp k b d hbd)) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.comp l a b hab) (OAI.Thomason.DirectedComplex.Table.comp l c d hcd) hab_cd = + OAI.Thomason.DirectedComplex.Table.comp l (OAI.Thomason.DirectedComplex.Table.comp k a c hac) (OAI.Thomason.DirectedComplex.Table.comp k b d hbd) hac_bd := by + ext p e + by_cases hpk : p < k + · have hpl : p < l := lt_trans hpk hkl + simp [OAI.Thomason.DirectedComplex.Table.comp, hpk, hpl] + · by_cases hpe : p = k + · subst p + cases e <;> simp [OAI.Thomason.DirectedComplex.Table.comp, hkl] + · by_cases hpl : p < l + · simp [OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpl] + · by_cases hple : p = l + · subst p + have hlk : ¬l < k := by omega + have hlke : ¬l = k := by omega + cases e <;> simp [OAI.Thomason.DirectedComplex.Table.comp, hlk, hlke] + · simp only [OAI.Thomason.DirectedComplex.Table.comp, ite_eq_right hpk, ite_eq_right hpe, ite_eq_right hpl, ite_eq_right hple] + abel + have proof_finite_dimension_13 {K : OAI.Thomason.DirectedComplex.{u}} (x : OAI.Thomason.DirectedComplex.Table K) : ∃ k, OAI.Thomason.DirectedComplex.Table.truncate k false x = x := by + obtain ⟨k, hk⟩ := x.bounded + have ht : x.row k true = x.row k false := by + have hb := x.boundary k false + rw [hk (k+1) (by omega) false, map_zero] at hb + exact sub_eq_zero.mp hb.symm + refine ⟨k, ?_⟩ + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, ht] + · have hkp : k < p := by omega + simp [OAI.Thomason.DirectedComplex.Table.truncate, hp, he, hk p hkp b] + exact { + Cell := OAI.Thomason.DirectedComplex.Table K + source k := OAI.Thomason.DirectedComplex.Table.truncate k false + target k := OAI.Thomason.DirectedComplex.Table.truncate k true + source_source i j x := proof_truncate_truncate_same_4 i j false x + target_target i j x := proof_truncate_truncate_same_4 i j true x + source_target i j x := proof_truncate_truncate_5 i j false true x + target_source i j x := proof_truncate_truncate_5 i j true false x + comp := OAI.Thomason.DirectedComplex.Table.comp + source_comp_le := proof_source_comp_le_6 + target_comp_le := proof_target_comp_le_7 + source_comp_gt i k hki x y h hs := proof_truncate_comp_gt_8 i k hki false x y h hs + target_comp_gt i k hki x y h ht := proof_truncate_comp_gt_8 i k hki true x y h ht + unit_left := proof_unit_left_9 + unit_right := proof_unit_right_10 + assoc := proof_assoc_11 + interchange := proof_interchange_12 + finite_dimension := proof_finite_dimension_13 + } + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Hom +variable {K : DirectedComplex.{u}} {L : DirectedComplex.{v}} {M : DirectedComplex.{w}} + +noncomputable def table (f : OAI.Thomason.DirectedComplex.Hom K L) (x : OAI.Thomason.DirectedComplex.Table K) : OAI.Thomason.DirectedComplex.Table L where + row p b := f.map p (x.row p b) + positive p b := f.map_positive p _ (x.positive p b) + boundary p b := by rw [← f.map_d, x.boundary, map_sub] + augmentation b := by rw [f.map_augmentation, x.augmentation] + bounded := by + obtain ⟨k, hk⟩ := x.bounded + refine ⟨k, ?_⟩ + intro p hp b + rw [hk p hp b, map_zero] + +noncomputable def nu (f : OAI.Thomason.DirectedComplex.Hom K L) : OAI.Thomason.OmegaCategory.Functor K.nu L.nu := by + classical + have proof_table_row_17 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (f.table x).row p b = f.map p (x.row p b) := rfl + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_table_truncate_15 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (k : ℕ) (b : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + f.table (OAI.Thomason.DirectedComplex.Table.truncate k b x) = OAI.Thomason.DirectedComplex.Table.truncate k b (f.table x) := by + ext p e + simp only [OAI.Thomason.DirectedComplex.Hom.table, OAI.Thomason.DirectedComplex.Table.truncate] + split_ifs <;> simp only [map_zero] + have proof_comp_row_14 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.comp k x y h).row p b = if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b := rfl + have proof_table_comp_16 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (h' : OAI.Thomason.DirectedComplex.Table.truncate k true (f.table x) = OAI.Thomason.DirectedComplex.Table.truncate k false (f.table y)) : + f.table (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.comp k (f.table x) (f.table y) h' := by + ext p e + simp only [OAI.Thomason.DirectedComplex.Hom.table, OAI.Thomason.DirectedComplex.Table.comp] + split_ifs <;> simp only [map_add] + exact { + map := f.table + map_source k x := (proof_table_truncate_15 f k Bool.false x) + map_target k x := (proof_table_truncate_15 f k Bool.true x) + map_comp := (proof_table_comp_16 f) + } + + +end OAI.Thomason.DirectedComplex.Hom +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable def nuFunctor : CategoryTheory.Functor OAI.Thomason.DirectedComplex.{u} OAI.Thomason.OmegaCategory.{u} where + obj := OAI.Thomason.DirectedComplex.nu + map := OAI.Thomason.DirectedComplex.Hom.nu + map_id K := by + change OAI.Thomason.DirectedComplex.Hom.nu (OAI.Thomason.DirectedComplex.Hom.id K) = OAI.Thomason.OmegaCategory.Functor.id K.nu + ext x + rfl + map_comp f g := by + change OAI.Thomason.DirectedComplex.Hom.nu (OAI.Thomason.DirectedComplex.Hom.comp f g) = OAI.Thomason.OmegaCategory.Functor.comp f.nu g.nu + ext x + rfl + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable abbrev Word (E : Type u) [PartialOrder E] := + {l : List E // l.Pairwise (· < ·)} + +noncomputable abbrev Chains (E : Type u) [PartialOrder E] := OAI.Thomason.NormalizedChains.Word E →₀ ℤ + +noncomputable def bracket (l : List E) : OAI.Thomason.NormalizedChains.Chains E := by + classical + exact if h : l.Pairwise (· < ·) then Finsupp.single ⟨l, h⟩ 1 else 0 + +noncomputable def prepend (a : E) : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains E := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + +noncomputable def wordBoundary : List E → OAI.Thomason.NormalizedChains.Chains E + | [] => 0 + | a :: l => OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (wordBoundary l) + +noncomputable def boundary : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains E := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +omit [PartialOrder E] +variable {M : Type v} [AddCommGroup M] + +noncomputable def faces (H : List E → M) : List E → M + | [] => 0 + | a :: l => H l - faces (fun m => H (a :: m)) l + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable def grade (k : ℕ) : Submodule ℤ (OAI.Thomason.NormalizedChains.Chains E) := + Finsupp.supported ℤ ℤ {w : OAI.Thomason.NormalizedChains.Word E | w.val.length = k} + +noncomputable def emptyWord : OAI.Thomason.NormalizedChains.Word E := ⟨[], List.Pairwise.nil⟩ + +noncomputable def emptyCoefficient : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] ℤ := Finsupp.lapply OAI.Thomason.NormalizedChains.emptyWord + +noncomputable def Positive (c : OAI.Thomason.NormalizedChains.Chains E) : Prop := ∀ l, 0 ≤ c l + +noncomputable def positiveGrade (p : ℕ) : AddSubmonoid (OAI.Thomason.NormalizedChains.grade (E := E) (p+1)) where + carrier := {c | Positive c.val} + zero_mem' _ := le_rfl + add_mem' ha hb w := add_nonneg (ha w) (hb w) + +noncomputable def complex (E : Type u) [PartialOrder E] : OAI.Thomason.DirectedComplex.{u} := by + classical + have proof_mem_grade_iff_20 {E : Type u} [instLocal1 : PartialOrder.{u} E] (k : ℕ) (c : OAI.Thomason.NormalizedChains.Chains E) : + c ∈ OAI.Thomason.NormalizedChains.grade k ↔ ∀ w, c w ≠ 0 → w.val.length = k := by + simp only [OAI.Thomason.NormalizedChains.grade, Finsupp.mem_supported, Set.subset_def, Finsupp.mem_support_iff, + Finset.mem_coe, Set.mem_ofPred_eq] + have proof_linearCombination_mem_grade_21 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type u} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (k j : ℕ) + (hH : ∀ w, w.val.length = k → H w ∈ OAI.Thomason.NormalizedChains.grade j) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + Finsupp.linearCombination ℤ H c ∈ OAI.Thomason.NormalizedChains.grade j := by + rw [Finsupp.linearCombination_apply, Finsupp.sum] + apply Submodule.sum_mem + intro w hw + exact Submodule.smul_mem _ _ (hH w ((proof_mem_grade_iff_20 k c).mp hc w + (Finsupp.mem_support_iff.mp hw))) + have proof_bracket_of_pairwise_22 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_23 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_mem_grade_24 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.bracket l ∈ OAI.Thomason.NormalizedChains.grade l.length := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + exact Finsupp.single_mem_supported ℤ 1 rfl + · rw [proof_bracket_of_not_pairwise_23 h] + exact Submodule.zero_mem _ + have proof_wordBoundary_nil_25 {E : Type u} [instLocal1 : PartialOrder.{u} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_26 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_prepend_bracket_27 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_23 h, proof_bracket_of_not_pairwise_23 h'] + have proof_prepend_mem_grade_28 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) {k : ℕ} {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + OAI.Thomason.NormalizedChains.prepend a c ∈ OAI.Thomason.NormalizedChains.grade (k+1) := by + apply proof_linearCombination_mem_grade_21 _ k (k+1) _ hc + intro w hw + simpa only [List.length_cons, hw] using proof_bracket_mem_grade_24 (a :: w.val) + have proof_wordBoundary_mem_grade_29 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.wordBoundary l ∈ OAI.Thomason.NormalizedChains.grade (l.length-1) := by + induction l with + | nil => exact Submodule.zero_mem _ + | cons a l ih => + cases l with + | nil => simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary] using proof_bracket_mem_grade_24 ([] : List E) + | cons b l => + rw [proof_wordBoundary_cons_26] + apply Submodule.sub_mem + · simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27] using proof_bracket_mem_grade_24 (b :: l) + · simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27] using proof_prepend_mem_grade_28 a ih + have proof_boundary_mem_grade_18 {E : Type u} [instLocal1 : PartialOrder.{u} E] {k : ℕ} {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade (k+1)) : + OAI.Thomason.NormalizedChains.boundary c ∈ OAI.Thomason.NormalizedChains.grade k := by + apply proof_linearCombination_mem_grade_21 _ (k+1) k _ hc + intro w hw + simpa only [hw, Nat.add_sub_cancel] using proof_wordBoundary_mem_grade_29 w.val + have proof_prepend_prepend_self_30 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_27] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_23 h] + have proof_wordBoundary_repeated_31 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_30] + have proof_wordBoundary_eq_zero_of_not_pairwise_32 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_31 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_23 hl, ih h.tail hl] + have proof_boundary_bracket_33 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_23 hs, proof_wordBoundary_eq_zero_of_not_pairwise_32 h hs] + have proof_faces_nil_34 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_35 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_hom_36 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type u} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_bracket_37 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_wordBoundary_cons_26] + have h := proof_faces_hom_36 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_27] at h + rw [← h, ih] + have proof_faces_congr_38 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {H K : List E → M} {l : List E} + (h : ∀ m, m.Sublist l → H m = K m) : OAI.Thomason.NormalizedChains.faces H l = OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_faces_cons_35, h l (List.sublist_cons_self a l)] + congr 1 + exact ih (fun m hm => h (a :: m) (List.Sublist.cons_cons a hm)) + have proof_faces_sub_39 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H K : List E → M) (l : List E) : + OAI.Thomason.NormalizedChains.faces (fun m => H m - K m) l = OAI.Thomason.NormalizedChains.faces H l - OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => simp [proof_faces_nil_34] + | cons a l ih => simp only [proof_faces_cons_35, ih]; abel + have proof_faces_faces_40 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (l : List E) : + OAI.Thomason.NormalizedChains.faces (OAI.Thomason.NormalizedChains.faces H) l = 0 := by + induction l generalizing H with + | nil => rfl + | cons a l ih => + simp only [proof_faces_cons_35] + rw [proof_faces_sub_39, ih] + simp [] + have proof_boundary_wordBoundary_41 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.wordBoundary l) = 0 := by + rw [← proof_faces_bracket_37] + change OAI.Thomason.NormalizedChains.boundary.toAddMonoidHom (OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l) = 0 + rw [proof_faces_hom_36] + have hc : OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket m)) l = OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.wordBoundary l := by + apply proof_faces_congr_38 + intro m hm + exact proof_boundary_bracket_33 (h.sublist hm) + change OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket m)) l = 0 + rw [hc] + change OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.wordBoundary m) l = 0 + simp_rw [← proof_faces_bracket_37] + exact proof_faces_faces_40 OAI.Thomason.NormalizedChains.bracket l + have proof_boundary_boundary_19 {E : Type u} [instLocal1 : PartialOrder.{u} E] (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.boundary c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul] + rw [proof_boundary_bracket_33 (l.property.imp fun h => le_of_lt h), + proof_boundary_wordBoundary_41 (l.property.imp fun h => le_of_lt h), smul_zero] + exact { + Chain p := OAI.Thomason.NormalizedChains.grade (E := E) (p+1) + group _ := inferInstance + d p := + { toFun := fun c => ⟨OAI.Thomason.NormalizedChains.boundary c.val, proof_boundary_mem_grade_18 c.property⟩ + map_zero' := Subtype.ext (map_zero _) + map_add' := fun x y => Subtype.ext (map_add _ x.val y.val) } + d_d p x := Subtype.ext (proof_boundary_boundary_19 x.val) + augmentation := + { toFun := fun c => OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary c.val) + map_zero' := by simp [] + map_add' := by intros; simp [] } + augmentation_d x := by + change OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.boundary x.val)) = 0 + rw [proof_boundary_boundary_19, map_zero] + positive := OAI.Thomason.NormalizedChains.positiveGrade + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +variable {D : Type v} [PartialOrder D] {B : Type w} [PartialOrder B] + +noncomputable def map (f : E →o D) : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains D := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable def complexMap {D : Type v} [PartialOrder D] (f : E →o D) : + OAI.Thomason.DirectedComplex.Hom (OAI.Thomason.NormalizedChains.complex E) (OAI.Thomason.NormalizedChains.complex D) := by + classical + have proof_mem_grade_iff_20 {E : Type u} [instLocal1 : PartialOrder.{u} E] (k : ℕ) (c : OAI.Thomason.NormalizedChains.Chains E) : + c ∈ OAI.Thomason.NormalizedChains.grade k ↔ ∀ w, c w ≠ 0 → w.val.length = k := by + simp only [OAI.Thomason.NormalizedChains.grade, Finsupp.mem_supported, Set.subset_def, Finsupp.mem_support_iff, + Finset.mem_coe, Set.mem_ofPred_eq] + have proof_linearCombination_mem_grade_46 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (k j : ℕ) + (hH : ∀ w, w.val.length = k → H w ∈ OAI.Thomason.NormalizedChains.grade j) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + Finsupp.linearCombination ℤ H c ∈ OAI.Thomason.NormalizedChains.grade j := by + rw [Finsupp.linearCombination_apply, Finsupp.sum] + apply Submodule.sum_mem + intro w hw + exact Submodule.smul_mem _ _ (hH w ((proof_mem_grade_iff_20 k c).mp hc w + (Finsupp.mem_support_iff.mp hw))) + have proof_bracket_of_pairwise_47 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_48 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_mem_grade_49 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.bracket l ∈ OAI.Thomason.NormalizedChains.grade l.length := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 h] + exact Finsupp.single_mem_supported ℤ 1 rfl + · rw [proof_bracket_of_not_pairwise_48 h] + exact Submodule.zero_mem _ + have proof_map_mem_grade_42 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) {k : ℕ} + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : OAI.Thomason.NormalizedChains.map f c ∈ OAI.Thomason.NormalizedChains.grade k := by + apply proof_linearCombination_mem_grade_46 _ k k _ hc + intro w hw + simpa only [List.length_map, hw] using proof_bracket_mem_grade_49 (w.val.map f) + have proof_bracket_of_pairwise_22 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_23 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_prepend_bracket_27 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_23 h, proof_bracket_of_not_pairwise_23 h'] + have proof_prepend_prepend_self_30 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_27] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_23 h] + have proof_wordBoundary_nil_25 {E : Type u} [instLocal1 : PartialOrder.{u} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_26 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_wordBoundary_repeated_31 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_30] + have proof_wordBoundary_eq_zero_of_not_pairwise_32 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_31 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_23 hl, ih h.tail hl] + have proof_boundary_bracket_33 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_23 hs, proof_wordBoundary_eq_zero_of_not_pairwise_32 h hs] + have proof_faces_nil_34 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_35 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_hom_36 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type u} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_bracket_37 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_wordBoundary_cons_26] + have h := proof_faces_hom_36 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_27] at h + rw [← h, ih] + have proof_faces_nil_50 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_51 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_wordBoundary_nil_52 {E : Type v} [instLocal1 : PartialOrder.{v} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_53 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_faces_hom_54 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {M' : Type v} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp [proof_faces_nil_50] + | cons a l ih => simp only [proof_faces_cons_51, map_sub, ih] + have proof_prepend_bracket_55 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_48 h, proof_bracket_of_not_pairwise_48 h'] + have proof_faces_bracket_56 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_51, proof_wordBoundary_cons_53] + have h := proof_faces_hom_54 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_55] at h + rw [← h, ih] + have proof_faces_hom_57 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type v} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_map_58 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {D : Type u} (f : D → E) (H : List E → M) (l : List D) : + OAI.Thomason.NormalizedChains.faces H (l.map f) = OAI.Thomason.NormalizedChains.faces (fun m => H (m.map f)) l := by + induction l generalizing H with + | nil => rfl + | cons a l ih => simp only [List.map_cons, OAI.Thomason.NormalizedChains.faces, ih] + have proof_faces_nil_59 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_60 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_congr_61 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {H K : List E → M} {l : List E} + (h : ∀ m, m.Sublist l → H m = K m) : OAI.Thomason.NormalizedChains.faces H l = OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_60, proof_faces_cons_60, h l (List.sublist_cons_self a l)] + congr 1 + exact ih (fun m hm => h (a :: m) (List.Sublist.cons_cons a hm)) + have proof_pairwise_of_map_62 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] {l : List E} (h : l.Pairwise (· ≤ ·)) (f : E → D) + (hf : (l.map f).Pairwise (· < ·)) : l.Pairwise (· < ·) := by + apply (h.and (List.pairwise_map.mp hf)).imp + intro a b hab + exact lt_of_le_of_ne hab.1 (fun he => (ne_of_lt hab.2) (congrArg f he)) + have proof_map_bracket_63 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (l.map f) := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have hf : ¬(l.map f).Pairwise (· < ·) := fun hm => hs (proof_pairwise_of_map_62 h f hm) + simp [proof_bracket_of_not_pairwise_23 hs, proof_bracket_of_not_pairwise_48 hf] + have proof_map_wordBoundary_64 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.wordBoundary l) = OAI.Thomason.NormalizedChains.wordBoundary (l.map f) := by + rw [← proof_faces_bracket_37, ← proof_faces_bracket_56] + change (OAI.Thomason.NormalizedChains.map f).toAddMonoidHom (OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l) = _ + rw [proof_faces_hom_57, proof_faces_map_58] + apply proof_faces_congr_61 + intro m hm + exact proof_map_bracket_63 f (h.sublist hm) + have proof_prepend_prepend_self_65 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_47 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_55] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_48 h] + have proof_wordBoundary_repeated_66 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_55, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_65] + have proof_wordBoundary_eq_zero_of_not_pairwise_67 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_66 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_48 hl, ih h.tail hl] + have proof_boundary_bracket_68 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_48 hs, proof_wordBoundary_eq_zero_of_not_pairwise_67 h hs] + have proof_map_boundary_43 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.boundary c) = OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.map f c) := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + have hl := l.property.imp fun h => le_of_lt h + rw [hz] + simp only [map_smul] + rw [proof_boundary_bracket_33 hl, proof_map_wordBoundary_64 f hl, proof_map_bracket_63 f hl, + proof_boundary_bracket_68 (List.pairwise_map.mpr (hl.imp fun hh => f.monotone hh))] + have proof_emptyCoefficient_bracket_69 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.bracket l) = if l = [] then 1 else 0 := by + classical + by_cases hl : l = [] + · subst l + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_47 List.Pairwise.nil, OAI.Thomason.NormalizedChains.emptyWord] + · by_cases hs : l.Pairwise (· < ·) + · have hw : (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) ≠ OAI.Thomason.NormalizedChains.emptyWord := by + intro he + exact hl (congrArg Subtype.val he) + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_47 hs, hw, hl] + · simp [proof_bracket_of_not_pairwise_48 hs, hl] + have proof_emptyCoefficient_bracket_70 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.bracket l) = if l = [] then 1 else 0 := by + classical + by_cases hl : l = [] + · subst l + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_22 List.Pairwise.nil, OAI.Thomason.NormalizedChains.emptyWord] + · by_cases hs : l.Pairwise (· < ·) + · have hw : (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) ≠ OAI.Thomason.NormalizedChains.emptyWord := by + intro he + exact hl (congrArg Subtype.val he) + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_22 hs, hw, hl] + · simp [proof_bracket_of_not_pairwise_23 hs, hl] + have proof_emptyCoefficient_map_44 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.map f c) = OAI.Thomason.NormalizedChains.emptyCoefficient c := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_map_bracket_63 _ (l.property.imp fun h => le_of_lt h), + proof_emptyCoefficient_bracket_69, proof_emptyCoefficient_bracket_70, List.map_eq_nil_iff] + have proof_linearCombination_positive_71 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (hH : ∀ w, OAI.Thomason.NormalizedChains.Positive (H w)) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : OAI.Thomason.NormalizedChains.Positive c) : + OAI.Thomason.NormalizedChains.Positive (Finsupp.linearCombination ℤ H c) := by + intro w + rw [Finsupp.linearCombination_apply, Finsupp.sum] + simp only [Finset.sum_apply, Finsupp.coe_finsetSum] + apply Finset.sum_nonneg + intro i _ + exact mul_nonneg (hc i) (hH i w) + have proof_bracket_positive_72 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.Positive (OAI.Thomason.NormalizedChains.bracket l) := by + classical + intro w + by_cases h : l.Pairwise (· < ·) + · simp [proof_bracket_of_pairwise_47 h, Finsupp.single_apply] + split <;> omega + · simp [proof_bracket_of_not_pairwise_48 h] + have proof_map_positive_45 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : OAI.Thomason.NormalizedChains.Positive c) : OAI.Thomason.NormalizedChains.Positive (OAI.Thomason.NormalizedChains.map f c) := + proof_linearCombination_positive_71 _ (fun w => proof_bracket_positive_72 (w.val.map f)) hc + exact { + map p := + { toFun := fun c => ⟨OAI.Thomason.NormalizedChains.map f c.val, proof_map_mem_grade_42 f c.property⟩ + map_zero' := Subtype.ext (map_zero _) + map_add' := fun x y => Subtype.ext (map_add _ x.val y.val) } + map_d p x := Subtype.ext (proof_map_boundary_43 f x.val) + map_augmentation x := by + change OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.map f x.val)) = OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary x.val) + rw [← proof_map_boundary_43, proof_emptyCoefficient_map_44] + map_positive p x hx := proof_map_positive_45 f hx + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +open CategoryTheory + +noncomputable def simplexComplexes : SimplexCategory ⥤ OAI.Thomason.DirectedComplex.{0} := by + classical + have proof_bracket_of_pairwise_75 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_pairwise_of_map_76 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] {l : List E} (h : l.Pairwise (· ≤ ·)) (f : E → D) + (hf : (l.map f).Pairwise (· < ·)) : l.Pairwise (· < ·) := by + apply (h.and (List.pairwise_map.mp hf)).imp + intro a b hab + exact lt_of_le_of_ne hab.1 (fun he => (ne_of_lt hab.2) (congrArg f he)) + have proof_bracket_of_not_pairwise_77 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_map_bracket_78 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (l.map f) := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_75 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have hf : ¬(l.map f).Pairwise (· < ·) := fun hm => hs (proof_pairwise_of_map_76 h f hm) + simp [proof_bracket_of_not_pairwise_77 hs, proof_bracket_of_not_pairwise_77 hf] + have proof_map_id_79 {E : Type 0} [instLocal1 : PartialOrder.{0} E] (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.map (OrderHom.id) c = c := by + classical + induction c using Finsupp.induction with + | zero => simp + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_75 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz, map_smul, proof_map_bracket_78 _ (l.property.imp fun h => le_of_lt h)] + simp + have proof_complexMap_id_73 {E : Type 0} [instLocal1 : PartialOrder.{0} E] : OAI.Thomason.NormalizedChains.complexMap (OrderHom.id : E →o E) = + OAI.Thomason.DirectedComplex.Hom.id (OAI.Thomason.NormalizedChains.complex E) := by + ext p x + apply Subtype.ext + exact proof_map_id_79 x.val + have proof_map_comp_80 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] {B : Type 0} [instLocal5 : PartialOrder.{0} B] (f : E →o D) (g : D →o B) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.map (g.comp f) c = OAI.Thomason.NormalizedChains.map g (OAI.Thomason.NormalizedChains.map f c) := by + classical + induction c using Finsupp.induction with + | zero => simp + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_75 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + have hl := l.property.imp fun h => le_of_lt h + rw [hz] + simp only [map_smul] + rw [proof_map_bracket_78 _ hl, proof_map_bracket_78 _ hl, + proof_map_bracket_78 _ (List.pairwise_map.mpr (hl.imp fun hh => f.monotone hh))] + simp [List.map_map] + have proof_complexMap_comp_74 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [PartialOrder D] {B : Type 0} [PartialOrder B] + (f : E →o D) (g : D →o B) : OAI.Thomason.NormalizedChains.complexMap (g.comp f) = + OAI.Thomason.DirectedComplex.Hom.comp (OAI.Thomason.NormalizedChains.complexMap f) (OAI.Thomason.NormalizedChains.complexMap g) := by + ext p x + apply Subtype.ext + exact proof_map_comp_80 f g x.val + exact { + obj m := OAI.Thomason.NormalizedChains.complex (Fin (m.len+1)) + map f := OAI.Thomason.NormalizedChains.complexMap f.toOrderHom + map_id _ := proof_complexMap_id_73 + map_comp f g := proof_complexMap_comp_74 f.toOrderHom g.toOrderHom + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def orientals : SimplexCategory ⥤ OAI.Thomason.OmegaCategory.{0} := + OAI.Thomason.NormalizedChains.simplexComplexes ⋙ OAI.Thomason.DirectedComplex.nuFunctor + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +noncomputable def ulift (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.{max u v} where + Cell := ULift.{v} C.Cell + source k x := ⟨C.source k x.down⟩ + target k x := ⟨C.target k x.down⟩ + source_source i j x := congrArg ULift.up (C.source_source i j x.down) + target_target i j x := congrArg ULift.up (C.target_target i j x.down) + source_target i j x := by + simpa only [apply_ite] using congrArg (ULift.up (α := C.Cell)) (C.source_target i j x.down) + target_source i j x := by + simpa only [apply_ite] using congrArg (ULift.up (α := C.Cell)) (C.target_source i j x.down) + comp k x y h := ⟨C.comp k x.down y.down (congrArg ULift.down h)⟩ + source_comp_le i k hik x y h := + congrArg ULift.up (C.source_comp_le i k hik x.down y.down (congrArg ULift.down h)) + target_comp_le i k hik x y h := + congrArg ULift.up (C.target_comp_le i k hik x.down y.down (congrArg ULift.down h)) + source_comp_gt i k hki x y h hs := + congrArg ULift.up (C.source_comp_gt i k hki x.down y.down + (congrArg ULift.down h) (congrArg ULift.down hs)) + target_comp_gt i k hki x y h ht := + congrArg ULift.up (C.target_comp_gt i k hki x.down y.down + (congrArg ULift.down h) (congrArg ULift.down ht)) + unit_left k x h := congrArg ULift.up (C.unit_left k x.down (congrArg ULift.down h)) + unit_right k x h := congrArg ULift.up (C.unit_right k x.down (congrArg ULift.down h)) + assoc k x y z hxy hyz hxy_z hx_yz := + congrArg ULift.up (C.assoc k x.down y.down z.down + (congrArg ULift.down hxy) (congrArg ULift.down hyz) + (congrArg ULift.down hxy_z) (congrArg ULift.down hx_yz)) + interchange k l hkl a b c d hab hcd hac hbd h₁ h₂ := + congrArg ULift.up (C.interchange k l hkl a.down b.down c.down d.down + (congrArg ULift.down hab) (congrArg ULift.down hcd) + (congrArg ULift.down hac) (congrArg ULift.down hbd) + (congrArg ULift.down h₁) (congrArg ULift.down h₂)) + finite_dimension x := by + obtain ⟨k, hk⟩ := C.finite_dimension x.down + exact ⟨k, congrArg ULift.up hk⟩ + +noncomputable def uliftUp (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor C (OAI.Thomason.OmegaCategory.ulift.{u,v} C) where + map := ULift.up + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + +noncomputable def uliftDown (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.ulift.{u,v} C) C where + map := ULift.down + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def uliftFunctor : OAI.Thomason.OmegaCategory.{u} ⥤ OAI.Thomason.OmegaCategory.{max u v} where + obj := OAI.Thomason.OmegaCategory.ulift + map {C D} F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftDown C) F) (OAI.Thomason.OmegaCategory.uliftUp D) + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def raisedOrientals : SimplexCategory ⥤ OAI.Thomason.OmegaCategory.{u} := + OAI.Thomason.orientals ⋙ OAI.Thomason.OmegaCategory.uliftFunctor.{0,u} + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +structure Presentation where + Generator : Type u + dimension : Generator → ℕ + relations : (C : OAI.Thomason.OmegaCategory.{u}) → (Generator → C.Cell) → Prop + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +structure Interpretation (C : OAI.Thomason.OmegaCategory.{u}) where + map : P.Generator → C.Cell + bounded : ∀ g, C.source (P.dimension g) (map g) = map g + satisfies : P.relations C map + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory + + +inductive CellTerm (G : Type u) where + | gen : G → CellTerm G + | source : ℕ → CellTerm G → CellTerm G + | target : ℕ → CellTerm G → CellTerm G + | comp : ℕ → CellTerm G → CellTerm G → CellTerm G + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.CellTerm + + +noncomputable def composeOrLeft (C : OAI.Thomason.OmegaCategory.{v}) (k : ℕ) (x y : C.Cell) : C.Cell := by + classical + exact if h : C.target k x = C.source k y then C.comp k x y h else x + +noncomputable def eval {G : Type u} (C : OAI.Thomason.OmegaCategory.{v}) (f : G → C.Cell) : OAI.Thomason.OmegaCategory.CellTerm G → C.Cell + | gen g => f g + | source k x => C.source k (eval C f x) + | target k x => C.target k (eval C f x) + | comp k x y => OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft C k (eval C f x) (eval C f y) + + +end OAI.Thomason.OmegaCategory.CellTerm +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def Equiv (x y : OAI.Thomason.OmegaCategory.CellTerm P.Generator) : Prop := + ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), x.eval C I.map = y.eval C I.map + +inductive Valid : OAI.Thomason.OmegaCategory.CellTerm P.Generator → Prop + | gen (g) : Valid (.gen g) + | source (k x) : Valid x → Valid (.source k x) + | target (k x) : Valid x → Valid (.target k x) + | comp (k x y) : Valid x → Valid y → P.Equiv (.target k x) (.source k y) → Valid (.comp k x y) + +noncomputable abbrev ValidTerm := {x : OAI.Thomason.OmegaCategory.CellTerm P.Generator // P.Valid x} + +noncomputable instance termSetoid : Setoid P.ValidTerm := by + classical + have proof_refl_81 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} (x : OAI.Thomason.OmegaCategory.CellTerm P.Generator) : P.Equiv x x := fun _ _ => rfl + have proof_symm_82 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) : P.Equiv y x := fun C I => (h C I).symm + have proof_trans_83 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {z : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) (h' : P.Equiv y z) : P.Equiv x z := + fun C I => (h C I).trans (h' C I) + exact { + r x y := P.Equiv x.val y.val + iseqv := ⟨fun _ => proof_refl_81 _, fun h => (proof_symm_82 h), fun h h' => (proof_trans_83 h h')⟩ + } + +noncomputable abbrev Cells := Quotient P.termSetoid + +noncomputable def evaluate (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : P.Cells → C.Cell := + Quotient.lift (fun x : P.ValidTerm => x.val.eval C I.map) (fun _ _ h => h C I) + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory.CellTerm + + +noncomputable def dimension {G : Type u} (d : G → ℕ) : OAI.Thomason.OmegaCategory.CellTerm G → ℕ + | gen g => d g + | source k _ => k + | target k _ => k + | comp k x y => max (k+1) (max (dimension d x) (dimension d y)) + + +end OAI.Thomason.OmegaCategory.CellTerm +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def sourceTerm (k : ℕ) (x : P.ValidTerm) : P.ValidTerm := ⟨.source k x.val, OAI.Thomason.OmegaCategory.Presentation.Valid.source (P := P) k x.val x.property⟩ + +noncomputable def source (k : ℕ) : P.Cells → P.Cells := by + classical + have proof_source_84 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.source k x) (.source k y) := + fun C I => congrArg (C.source k) (h C I) + exact + Quotient.map (P.sourceTerm k) (fun _ _ h => (proof_source_84 k h)) + +noncomputable def targetTerm (k : ℕ) (x : P.ValidTerm) : P.ValidTerm := ⟨.target k x.val, OAI.Thomason.OmegaCategory.Presentation.Valid.target (P := P) k x.val x.property⟩ + +noncomputable def target (k : ℕ) : P.Cells → P.Cells := by + classical + have proof_target_85 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.target k x) (.target k y) := + fun C I => congrArg (C.target k) (h C I) + exact + Quotient.map (P.targetTerm k) (fun _ _ h => (proof_target_85 k h)) + +noncomputable def compTerm (k : ℕ) (x y : P.ValidTerm) : P.ValidTerm := by + classical + exact if h : P.Equiv (.target k x.val) (.source k y.val) then + ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ else x + +noncomputable def comp (k : ℕ) (x y : P.Cells) (_ : P.target k x = P.source k y) : P.Cells := by + classical + have proof_trans_83 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {z : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) (h' : P.Equiv y z) : P.Equiv x z := + fun C I => (h C I).trans (h' C I) + have proof_symm_82 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) : P.Equiv y x := fun C I => (h C I).symm + have proof_target_85 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.target k x) (.target k y) := + fun C I => congrArg (C.target k) (h C I) + have proof_source_84 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.source k x) (.source k y) := + fun C I => congrArg (C.source k) (h C I) + have proof_composable_congr_87 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {x' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (hx : P.Equiv x x') (hy : P.Equiv y y') : + P.Equiv (.target k x) (.source k y) ↔ P.Equiv (.target k x') (.source k y') := + ⟨fun h => (proof_trans_83 + (proof_symm_82 (proof_target_85 k hx)) + (proof_trans_83 h (proof_source_84 k hy))), + fun h => (proof_trans_83 (proof_target_85 k hx) + (proof_trans_83 h + (proof_symm_82 (proof_source_84 k hy))))⟩ + have proof_comp_88 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {x' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (hx : P.Equiv x x') (hy : P.Equiv y y') : + P.Equiv (.comp k x y) (.comp k x' y') := by + intro C I + exact congrArg₂ (OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft C k) (hx C I) (hy C I) + have proof_compTerm_equiv_86 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) {x y x' y' : P.ValidTerm} + (hx : P.Equiv x.val x'.val) (hy : P.Equiv y.val y'.val) : + P.Equiv (P.compTerm k x y).val (P.compTerm k x' y').val := by + classical + have he := proof_composable_congr_87 k hx hy + by_cases h : P.Equiv (.target k x.val) (.source k y.val) + · simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h, dite_eq_left (he.mp h)] + exact proof_comp_88 k hx hy + · simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_right h, dite_eq_right (mt he.mpr h)] + exact hx + exact + Quotient.map₂ (P.compTerm k) (fun _ _ hx _ _ hy => (proof_compTerm_equiv_86 P k hx hy)) x y + +noncomputable abbrev category : OAI.Thomason.OmegaCategory.{u} := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_source_source_self_95 (C : OAI.Thomason.OmegaCategory.{u}) (k : ℕ) (x : C.Cell) : + C.source k (C.source k x) = C.source k x := by + simp [C.source_source] + have proof_source_target_self_96 (C : OAI.Thomason.OmegaCategory.{u}) (k : ℕ) (x : C.Cell) : + C.source k (C.target k x) = C.target k x := by + simp [C.source_target] + have proof_source_composable_97 (C : OAI.Thomason.OmegaCategory.{u}) {k i : ℕ} (hki : k < i) {x y : C.Cell} + (h : C.target k x = C.source k y) : + C.target k (C.source i x) = C.source k (C.source i y) := by + rw [C.target_source, ite_eq_left hki, C.source_source, min_eq_left (le_of_lt hki)] + exact h + have proof_source_fixed_upwards_98 (C : OAI.Thomason.OmegaCategory.{u}) {i j : ℕ} (hij : i ≤ j) {x : C.Cell} + (h : C.source i x = x) : C.source j x = x := by + rw [← h, C.source_source, min_eq_right hij] + have proof_eval_dimension_93 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x : OAI.Thomason.OmegaCategory.CellTerm P.Generator} (hx : P.Valid x) + (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : + C.source (x.dimension P.dimension) (x.eval C I.map) = x.eval C I.map := by + induction hx with + | gen g => exact I.bounded g + | source k x hx ih => exact (proof_source_source_self_95 C k + (OAI.Thomason.OmegaCategory.CellTerm.eval C (OAI.Thomason.OmegaCategory.Presentation.Interpretation.map I) x)) + | target k x hx ih => exact (proof_source_target_self_96 C k + (OAI.Thomason.OmegaCategory.CellTerm.eval C (OAI.Thomason.OmegaCategory.Presentation.Interpretation.map I) x)) + | comp k x y hx hy h ihx ihy => + have hm := h C I + change C.target k (x.eval C I.map) = C.source k (y.eval C I.map) at hm + simp only [OAI.Thomason.OmegaCategory.CellTerm.dimension, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm] + have hkn : k < max (k+1) (max (x.dimension P.dimension) (y.dimension P.dimension)) := by omega + rw [C.source_comp_gt _ k hkn _ _ hm (proof_source_composable_97 C hkn hm)] + congr 1 + · exact (proof_source_fixed_upwards_98 C (by omega) ihx) + · exact (proof_source_fixed_upwards_98 C (by omega) ihy) + exact { + Cell := P.Cells + source := P.source + target := P.target + comp := P.comp + source_source i j x := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, C.source_source] + target_target i j x := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, C.target_target] + source_target i j x := by + apply (proof_cells_ext_89 P) + intro C I + by_cases hij : i < j <;> simp [proof_evaluate_source_90, proof_evaluate_target_91, hij, C.source_target] + target_source i j x := by + apply (proof_cells_ext_89 P) + intro C I + by_cases hij : i < j <;> simp [proof_evaluate_source_90, proof_evaluate_target_91, hij, C.target_source] + source_comp_le i k hik x y h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.source_comp_le i k hik _ _ _ + target_comp_le i k hik x y h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.target_comp_le i k hik _ _ _ + source_comp_gt i k hki x y h hs := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.source_comp_gt i k hki _ _ _ _ + target_comp_gt i k hki x y h hs := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.target_comp_gt i k hki _ _ _ _ + unit_left k x h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.unit_left k _ _ + unit_right k x h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.unit_right k _ _ + assoc k x y z hxy hyz hxy_z hx_yz := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_comp_92] + exact C.assoc k _ _ _ _ _ _ _ + interchange k l hkl a b c d hab hcd hac hbd hab_cd hac_bd := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_comp_92] + exact C.interchange k l hkl _ _ _ _ _ _ _ _ _ _ + finite_dimension x := by + induction x using Quotient.inductionOn with | h x => + refine ⟨x.val.dimension P.dimension, ?_⟩ + apply (proof_cells_ext_89 P) + intro C I + exact (proof_eval_dimension_93 P (Subtype.property x) C I) + } + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable abbrev colimitPresentation (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Presentation.{u} where + Generator := (j : J) × (F.obj j).Cell + dimension g := Classical.choose ((F.obj g.1).finite_dimension g.2) + relations C f := ∃ ι : ∀ j, OAI.Thomason.OmegaCategory.Functor (F.obj j) C, + (∀ j x, f ⟨j, x⟩ = (ι j).map x) ∧ + (∀ ⦃j j'⦄ (a : j ⟶ j'), OAI.Thomason.OmegaCategory.Functor.comp (F.map a) (ι j') = ι j) + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def generator (g : P.Generator) : P.Cells := Quotient.mk _ ⟨.gen g, .gen g⟩ + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable def colimitInclusion (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) (j : J) : + OAI.Thomason.OmegaCategory.Functor (F.obj j) (OAI.Thomason.OmegaCategory.colimitPresentation F).category := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_evaluate_generator_99 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) + (I : P.Interpretation C) (g : P.Generator) : P.evaluate C I (P.generator g) = I.map g := rfl + exact { + map x := (OAI.Thomason.OmegaCategory.colimitPresentation F).generator ⟨j, x⟩ + map_source k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_source_90, proof_evaluate_generator_99, hi] + exact (ι j).map_source k x + map_target k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_target_91, proof_evaluate_generator_99, hi] + exact (ι j).map_target k x + map_comp k x y h h' := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_comp_92, proof_evaluate_generator_99, hi] + exact (ι j).map_comp k x y h _ + } + +noncomputable def presentedCocone (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : Cocone F := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + exact { + pt := (OAI.Thomason.OmegaCategory.colimitPresentation F).category + ι := { + app := OAI.Thomason.OmegaCategory.colimitInclusion F + naturality := by + intro j j' a + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, hw⟩ + change I.map ⟨j', (F.map a).map x⟩ = I.map ⟨j, x⟩ + rw [hi, hi] + exact congrArg (fun h : OAI.Thomason.OmegaCategory.Functor (F.obj j) C => h.map x) (hw a) } + } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def lift (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : OAI.Thomason.OmegaCategory.Functor P.category C := by + classical + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + exact { + map := P.evaluate C I + map_source := (proof_evaluate_source_90 P C I) + map_target := (proof_evaluate_target_91 P C I) + map_comp k x y h _ := (proof_evaluate_comp_92 P C I k x y h) + } + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable def colimitInterpretation (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) (s : Cocone F) : + (OAI.Thomason.OmegaCategory.colimitPresentation F).Interpretation s.pt where + map g := (s.ι.app g.1).map g.2 + bounded g := by + exact ((s.ι.app g.1).map_source _ g.2).symm.trans + (congrArg (s.ι.app g.1).map (Classical.choose_spec ((F.obj g.1).finite_dimension g.2))) + satisfies := ⟨fun j => s.ι.app j, fun _ _ => rfl, fun {_ _} a => s.w a⟩ + +noncomputable def presentedCoconeIsColimit (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : + IsColimit (OAI.Thomason.OmegaCategory.presentedCocone F) := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + exact { + desc s := (OAI.Thomason.OmegaCategory.colimitPresentation F).lift s.pt (OAI.Thomason.OmegaCategory.colimitInterpretation F s) + fac s j := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + rfl + uniq s m hm := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro ⟨j, x⟩ + exact congrArg (fun f : OAI.Thomason.OmegaCategory.Functor (F.obj j) s.pt => f.map x) (hm j) + } + +noncomputable instance hasColimits : HasColimitsOfSize.{u,u} OAI.Thomason.OmegaCategory.{u} where + has_colimits_of_shape := fun _ _ => { has_colimit := fun F => ⟨⟨OAI.Thomason.OmegaCategory.presentedCocone F, OAI.Thomason.OmegaCategory.presentedCoconeIsColimit F⟩⟩ } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable instance omegaHasSimplicialColimits : + Limits.HasColimitsOfSize.{0,u} OAI.Thomason.OmegaCategory.{u} := + Limits.hasColimitsOfSizeShrink.{0,u} OAI.Thomason.OmegaCategory.{u} + +noncomputable def categorification : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.{u} := + (uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtension OAI.Thomason.raisedOrientals.{u} + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonLeft : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.{u} := + (SSet.sd ⋙ SSet.sd) ⋙ OAI.Thomason.categorification + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetNerve (C : OAI.Thomason.OmegaCategory.{u}) : SSet.{u} where + obj m := OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.orientals.obj m.unop) C + map f := ↾fun x => OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map f.unop) x + map_id m := by + apply ConcreteCategory.hom_ext + intro x + change OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map (𝟙 m.unop)) x = x + rw [OAI.Thomason.orientals.map_id] + rfl + map_comp f g := by + apply ConcreteCategory.hom_ext + intro x + change OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map (g.unop ≫ f.unop)) x = + OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map g.unop) + (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map f.unop) x) + rw [OAI.Thomason.orientals.map_comp] + rfl + +noncomputable def streetNerveMap {C D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) : + OAI.Thomason.streetNerve C ⟶ OAI.Thomason.streetNerve D where + app _ := ↾fun x => OAI.Thomason.OmegaCategory.Functor.comp x F + naturality _ _ _ := rfl + +noncomputable def streetNerveFunctor : OAI.Thomason.OmegaCategory.{u} ⥤ SSet.{u} where + obj := OAI.Thomason.streetNerve + map := OAI.Thomason.streetNerveMap + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonRight : OAI.Thomason.OmegaCategory.{u} ⥤ SSet.{u} := + OAI.Thomason.streetNerveFunctor ⋙ (SSet.ex ⋙ SSet.ex) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetYonedaEquiv (C : OAI.Thomason.OmegaCategory.{u}) (m : SimplexCategoryᵒᵖ) : + ((Presheaf.restrictedULiftYoneda.{0} OAI.Thomason.raisedOrientals).obj C).obj m ≃ + (OAI.Thomason.streetNerve C).obj m where + toFun F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftUp _) F.down + invFun F := ULift.up (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftDown _) F) + left_inv _ := rfl + right_inv _ := rfl + +noncomputable def streetYonedaIso : Presheaf.restrictedULiftYoneda.{0} OAI.Thomason.raisedOrientals.{u} ≅ + OAI.Thomason.streetNerveFunctor.{u} := + NatIso.ofComponents (fun C => + NatIso.ofComponents (fun m => (OAI.Thomason.streetYonedaEquiv C m).toIso) (by intros; rfl)) + (by intros; rfl) + +noncomputable def categorificationAdjunction : OAI.Thomason.categorification.{u} ⊣ OAI.Thomason.streetNerveFunctor.{u} := + (Presheaf.uliftYonedaAdjunction.{0} + ((uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtension OAI.Thomason.raisedOrientals.{u}) + ((uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtensionUnit OAI.Thomason.raisedOrientals.{u})).ofNatIsoRight OAI.Thomason.streetYonedaIso + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonAdjunction : OAI.Thomason.thomasonLeft.{u} ⊣ OAI.Thomason.thomasonRight.{u} := + (SSet.sdExAdjunction.comp SSet.sdExAdjunction).comp OAI.Thomason.categorificationAdjunction + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +noncomputable abbrev truncationPresentation (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Presentation.{u} where + Generator := C.Cell + dimension _ := n + relations D f := D.IsTruncated n ∧ ∃ F : OAI.Thomason.OmegaCategory.Functor C D, f = F.map + +noncomputable def truncationUnit (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : + OAI.Thomason.OmegaCategory.Functor C (OAI.Thomason.OmegaCategory.truncationPresentation n C).category := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_evaluate_generator_99 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) + (I : P.Interpretation C) (g : P.Generator) : P.evaluate C I (P.generator g) = I.map g := rfl + exact { + map := (OAI.Thomason.OmegaCategory.truncationPresentation n C).generator + map_source k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_source_90, proof_evaluate_generator_99, hF] + exact F.map_source k x + map_target k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_target_91, proof_evaluate_generator_99, hF] + exact F.map_target k x + map_comp k x y h h' := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_comp_92, proof_evaluate_generator_99, hF] + exact F.map_comp k x y h _ + } + +noncomputable def truncation (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.NCategory.{u} n := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_truncation_isTruncated_103 (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : + (OAI.Thomason.OmegaCategory.truncationPresentation n C).category.IsTruncated n := by + intro x + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rw [proof_evaluate_source_90] + exact I.satisfies.1 _ + exact + ⟨(OAI.Thomason.OmegaCategory.truncationPresentation n C).category, proof_truncation_isTruncated_103 n C⟩ + +noncomputable def truncationLift {n : ℕ} {C : OAI.Thomason.OmegaCategory.{u}} (D : OAI.Thomason.OmegaCategory.NCategory.{u} n) + (F : OAI.Thomason.OmegaCategory.Functor C D.val) : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D.val := + (OAI.Thomason.OmegaCategory.truncationPresentation n C).lift D.val { + map := F.map + bounded := fun x => D.property (F.map x) + satisfies := ⟨D.property, F, rfl⟩ } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def truncationFunctor (n : ℕ) : OAI.Thomason.OmegaCategory.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact { + obj := OAI.Thomason.OmegaCategory.truncation n + map {C D} F := OAI.Thomason.OmegaCategory.truncationLift (OAI.Thomason.OmegaCategory.truncation n D) (OAI.Thomason.OmegaCategory.Functor.comp F (OAI.Thomason.OmegaCategory.truncationUnit n D)) + map_id C := by + apply proof_truncation_functor_ext_104 + rfl + map_comp F G := by + apply proof_truncation_functor_ext_104 + rfl + } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def categorificationFinite (n : ℕ) : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := + OAI.Thomason.categorification ⋙ OAI.Thomason.OmegaCategory.truncationFunctor n + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonLeftFinite (n : ℕ) : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := + (SSet.sd ⋙ SSet.sd) ⋙ OAI.Thomason.categorificationFinite n + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetNerveFinite (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ SSet.{u} where + obj C := OAI.Thomason.streetNerve C.val + map := OAI.Thomason.streetNerveMap + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonRightFinite (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ SSet.{u} := + OAI.Thomason.streetNerveFinite n ⋙ (SSet.ex ⋙ SSet.ex) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def nCategoryInclusion (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ OAI.Thomason.OmegaCategory.{u} where + obj C := C.val + map F := F + +noncomputable def truncationHomEquiv (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) (D : OAI.Thomason.OmegaCategory.NCategory.{u} n) : + ((OAI.Thomason.OmegaCategory.truncationFunctor n).obj C ⟶ D) ≃ (C ⟶ (OAI.Thomason.OmegaCategory.nCategoryInclusion n).obj D) := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact { + toFun F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F + invFun := OAI.Thomason.OmegaCategory.truncationLift D + left_inv F := by + apply proof_truncation_functor_ext_104 + rfl + right_inv _ := rfl + } + +noncomputable def truncationAdjunction (n : ℕ) : OAI.Thomason.OmegaCategory.truncationFunctor.{u} n ⊣ OAI.Thomason.OmegaCategory.nCategoryInclusion n := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact + Adjunction.mkOfHomEquiv { + homEquiv := OAI.Thomason.OmegaCategory.truncationHomEquiv n + homEquiv_naturality_left_symm := by + intro C' C D F G + apply proof_truncation_functor_ext_104 + rfl + homEquiv_naturality_right := by + intro C D D' F G + rfl } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def categorificationFiniteAdjunction (n : ℕ) : + OAI.Thomason.categorificationFinite.{u} n ⊣ OAI.Thomason.streetNerveFinite.{u} n := + OAI.Thomason.categorificationAdjunction.comp (OAI.Thomason.OmegaCategory.truncationAdjunction n) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonFiniteAdjunction (n : ℕ) : + OAI.Thomason.thomasonLeftFinite.{u} n ⊣ OAI.Thomason.thomasonRightFinite.{u} n := + (SSet.sdExAdjunction.comp SSet.sdExAdjunction).comp (OAI.Thomason.categorificationFiniteAdjunction n) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.WeakHomotopy +open scoped Topology Topology.Homotopy +variable {X : Type u} {Y : Type v} [TopologicalSpace X] [TopologicalSpace Y] + +noncomputable def loopMap (N : Type w) (f : C(X, Y)) (x : X) : GenLoop N X x → GenLoop N Y (f x) := + fun p => ⟨f.comp p.val, fun y hy => congrArg f (p.property y hy)⟩ + +noncomputable def groupMap (N : Type w) (f : C(X, Y)) (x : X) : + HomotopyGroup N X x → HomotopyGroup N Y (f x) := by + classical + have proof_loopMap_homotopic_105 {X : Type u} {Y : Type v} [instLocal2 : TopologicalSpace.{u} X] [instLocal3 : TopologicalSpace.{v} Y] (N : Type w) (f : C(X, Y)) (x : X) + {p q : GenLoop N X x} (h : GenLoop.Homotopic p q) : + GenLoop.Homotopic (OAI.Thomason.WeakHomotopy.loopMap N f x p) (OAI.Thomason.WeakHomotopy.loopMap N f x q) := + h.comp_continuousMap f + exact + Quotient.map (OAI.Thomason.WeakHomotopy.loopMap N f x) (fun _ _ h => proof_loopMap_homotopic_105 N f x h) + +noncomputable def componentsMap (f : C(X, Y)) : ZerothHomotopy X → ZerothHomotopy Y := + ZerothHomotopy.lift (fun x => ZerothHomotopy.mk (f x)) + (fun _ _ p => ZerothHomotopy.sound (p.map f.continuous)) + +noncomputable def Equivalence (f : C(X, Y)) : Prop := + Function.Bijective (OAI.Thomason.WeakHomotopy.componentsMap f) ∧ + ∀ (n : ℕ) (x : X), Function.Bijective (OAI.Thomason.WeakHomotopy.groupMap (Fin (n+1)) f x) + + +end OAI.Thomason.WeakHomotopy +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def simplicialWeakEquivalences : MorphismProperty SSet.{u} := + fun _ _ f => OAI.Thomason.WeakHomotopy.Equivalence (SSet.toTop.map f).hom + +noncomputable def simplicialFibrations : MorphismProperty SSet.{u} := (SSet.modelCategoryQuillen.J).rlp + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Limits HomotopicalAlgebra + +structure KanQuillenModel where + model : ModelCategory SSet.{u} + weak_eq : model.categoryWithWeakEquivalences.weakEquivalences = OAI.Thomason.simplicialWeakEquivalences + fib_eq : model.categoryWithFibrations.fibrations = OAI.Thomason.simplicialFibrations + cof_eq : model.categoryWithCofibrations.cofibrations = MorphismProperty.monomorphisms SSet + +noncomputable def LeftProperFor {C : Type v} [Category.{u} C] + (W Cof : MorphismProperty C) : Prop := + ∀ {A B X Y : C} (i : A ⟶ B) (f : A ⟶ X) (g : B ⟶ Y) (j : X ⟶ Y), + IsPushout i f g j → Cof i → W f → W g + +noncomputable def RightProperFor {C : Type v} [Category.{u} C] + (W Fib : MorphismProperty C) : Prop := + ∀ {A B X Y : C} (f : A ⟶ B) (g : A ⟶ X) (p : B ⟶ Y) (q : X ⟶ Y), + IsPullback f g p q → Fib q → W p → W g + +noncomputable def FibrantFor {C : Type v} [Category.{u} C] (Fib : MorphismProperty C) (Y : C) : Prop := + ∃ (T : C) (_ : IsTerminal T) (p : Y ⟶ T), Fib p + +noncomputable def boundaryImages {C : Type v} [Category.{u} C] (L : SSet.{u} ⥤ C) : MorphismProperty C := + .ofHoms (fun n : ℕ => L.map (SSet.boundary n).ι) + +noncomputable def hornImages {C : Type v} [Category.{u} C] (L : SSet.{u} ⥤ C) : MorphismProperty C := + ⨆ n : ℕ, .ofHoms (fun i : Fin (n+2) => L.map (SSet.horn (n+1) i).ι) + +structure ExactModelEndpoint {C : Type v} [Category.{u} C] + (L : SSet.{u} ⥤ C) (R : C ⥤ SSet.{u}) (adj : L ⊣ R) where + model : ModelCategory C + weak_eq : model.categoryWithWeakEquivalences.weakEquivalences = + OAI.Thomason.simplicialWeakEquivalences.inverseImage R + fib_eq : model.categoryWithFibrations.fibrations = OAI.Thomason.simplicialFibrations.inverseImage R + cof_eq : model.categoryWithCofibrations.cofibrations = + ((OAI.Thomason.simplicialFibrations.inverseImage R) ⊓ (OAI.Thomason.simplicialWeakEquivalences.inverseImage R)).llp + generating_cofibrations : (OAI.Thomason.boundaryImages L).rlp = + model.categoryWithFibrations.fibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences + generating_trivial_cofibrations : (OAI.Thomason.hornImages L).rlp = model.categoryWithFibrations.fibrations + weak_factorization_one : MorphismProperty.IsWeakFactorizationSystem + (model.categoryWithCofibrations.cofibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences) + model.categoryWithFibrations.fibrations + weak_factorization_two : MorphismProperty.IsWeakFactorizationSystem + model.categoryWithCofibrations.cofibrations + (model.categoryWithFibrations.fibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences) + complete : HasLimitsOfSize.{u,u} C + cocomplete : HasColimitsOfSize.{u,u} C + locallyPresentable : IsLocallyPresentable.{u} C + leftProper : OAI.Thomason.LeftProperFor model.categoryWithWeakEquivalences.weakEquivalences + model.categoryWithCofibrations.cofibrations + rightProper : OAI.Thomason.RightProperFor model.categoryWithWeakEquivalences.weakEquivalences + model.categoryWithFibrations.fibrations + leftQuillen : ∀ {K K' : SSet.{u}} (f : K ⟶ K'), Mono f → + model.categoryWithCofibrations.cofibrations (L.map f) ∧ + (OAI.Thomason.simplicialWeakEquivalences f → model.categoryWithWeakEquivalences.weakEquivalences (L.map f)) + quillenEquivalence : ∀ (K : SSet.{u}) (Y : C), + OAI.Thomason.FibrantFor model.categoryWithFibrations.fibrations Y → + ∀ f : L.obj K ⟶ Y, + model.categoryWithWeakEquivalences.weakEquivalences f ↔ + OAI.Thomason.simplicialWeakEquivalences (adj.homEquiv K Y f) + +noncomputable def FullMain : Prop := + Nonempty OAI.Thomason.KanQuillenModel.{u} ∧ + Nonempty (OAI.Thomason.ExactModelEndpoint OAI.Thomason.thomasonLeft.{u} OAI.Thomason.thomasonRight OAI.Thomason.thomasonAdjunction) ∧ + ∀ n : ℕ, 1 ≤ n → + Nonempty (OAI.Thomason.ExactModelEndpoint (OAI.Thomason.thomasonLeftFinite.{u} n) (OAI.Thomason.thomasonRightFinite n) + (OAI.Thomason.thomasonFiniteAdjunction n)) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonWeakEquivalences : MorphismProperty OAI.Thomason.OmegaCategory.{u} := + OAI.Thomason.simplicialWeakEquivalences.inverseImage OAI.Thomason.thomasonRight + +noncomputable def thomasonWeakEquivalencesFinite (n : ℕ) : + MorphismProperty (OAI.Thomason.OmegaCategory.NCategory.{u} n) := + OAI.Thomason.simplicialWeakEquivalences.inverseImage (OAI.Thomason.thomasonRightFinite n) + + +end OAI.Thomason +end + +section +namespace OAI + + +theorem Thomason.main : OAI.Thomason.FullMain.{u} := by + sorry + +theorem Thomason.nerveDetection_allDimensions : + OAI.Thomason.thomasonWeakEquivalences.{u} = + OAI.Thomason.simplicialWeakEquivalences.inverseImage OAI.Thomason.streetNerveFunctor ∧ + ∀ n : ℕ, OAI.Thomason.thomasonWeakEquivalencesFinite.{u} n = + OAI.Thomason.simplicialWeakEquivalences.inverseImage (OAI.Thomason.streetNerveFinite n) := by + sorry + +end OAI +end + +end +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThomasonModelStructures.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.Thomason.main`, `OAI.Thomason.nerveDetection_allDimensions` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thomason-model-structures/solution/closure.txt b/tasks/thomason-model-structures/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c52e44767059da9795a0ab6f7316402c1242ba76 --- /dev/null +++ b/tasks/thomason-model-structures/solution/closure.txt @@ -0,0 +1,85 @@ +OAI.CategoryTheory.Thomason.AlexanderWhitney +OAI.CategoryTheory.Thomason.AtomFibers +OAI.CategoryTheory.Thomason.AttachmentComparison +OAI.CategoryTheory.Thomason.BarycentricMesh +OAI.CategoryTheory.Thomason.BoundaryQuotients +OAI.CategoryTheory.Thomason.BoundedCylinders +OAI.CategoryTheory.Thomason.CoherentGluing +OAI.CategoryTheory.Thomason.Cones +OAI.CategoryTheory.Thomason.CoreCouniversality +OAI.CategoryTheory.Thomason.Couniversality +OAI.CategoryTheory.Thomason.CubicalGeometry +OAI.CategoryTheory.Thomason.CubicalRecognition +OAI.CategoryTheory.Thomason.CylinderAssociativity +OAI.CategoryTheory.Thomason.CylinderFaces +OAI.CategoryTheory.Thomason.CylinderInterchange +OAI.CategoryTheory.Thomason.CylinderProfiles +OAI.CategoryTheory.Thomason.CylinderWeights +OAI.CategoryTheory.Thomason.Definitions +OAI.CategoryTheory.Thomason.DimensionOne +OAI.CategoryTheory.Thomason.DirectedPrisms +OAI.CategoryTheory.Thomason.EdgeComparison +OAI.CategoryTheory.Thomason.ExtensionAnodyne +OAI.CategoryTheory.Thomason.FiberComparisons +OAI.CategoryTheory.Thomason.FiberRecognition +OAI.CategoryTheory.Thomason.FilteredColimits +OAI.CategoryTheory.Thomason.FiniteAttachments +OAI.CategoryTheory.Thomason.FiniteChains +OAI.CategoryTheory.Thomason.FiniteGluing +OAI.CategoryTheory.Thomason.Generators +OAI.CategoryTheory.Thomason.Globes +OAI.CategoryTheory.Thomason.GlobularComplexes +OAI.CategoryTheory.Thomason.GlobularGeneration +OAI.CategoryTheory.Thomason.GrayGenerators +OAI.CategoryTheory.Thomason.GraySquares +OAI.CategoryTheory.Thomason.GreatestAttachments +OAI.CategoryTheory.Thomason.HomotopyExtension +OAI.CategoryTheory.Thomason.HornRealization +OAI.CategoryTheory.Thomason.IntervalCategories +OAI.CategoryTheory.Thomason.IntervalExtension +OAI.CategoryTheory.Thomason.KanQuillen +OAI.CategoryTheory.Thomason.KanTowers +OAI.CategoryTheory.Thomason.LabelledFibers +OAI.CategoryTheory.Thomason.LayeredWhiskers +OAI.CategoryTheory.Thomason.Linearization +OAI.CategoryTheory.Thomason.ModelClasses +OAI.CategoryTheory.Thomason.ModelTransfer +OAI.CategoryTheory.Thomason.NormalizedChains +OAI.CategoryTheory.Thomason.OrientalCounit +OAI.CategoryTheory.Thomason.PartialPrisms +OAI.CategoryTheory.Thomason.PartialTables +OAI.CategoryTheory.Thomason.PastingInterchange +OAI.CategoryTheory.Thomason.Polyhedra +OAI.CategoryTheory.Thomason.PosetComparison +OAI.CategoryTheory.Thomason.PosetalColimits +OAI.CategoryTheory.Thomason.PosetalReduction +OAI.CategoryTheory.Thomason.Presentations +OAI.CategoryTheory.Thomason.PrismBasis +OAI.CategoryTheory.Thomason.ProperTransfer +OAI.CategoryTheory.Thomason.RankedAtoms +OAI.CategoryTheory.Thomason.RankedExchange +OAI.CategoryTheory.Thomason.RankedFaithfulness +OAI.CategoryTheory.Thomason.RectangleComposition +OAI.CategoryTheory.Thomason.RecursiveCylinders +OAI.CategoryTheory.Thomason.RelativeContiguity +OAI.CategoryTheory.Thomason.RelativeRepresentation +OAI.CategoryTheory.Thomason.SieveAttachments +OAI.CategoryTheory.Thomason.SimplexAtoms +OAI.CategoryTheory.Thomason.SimplexBoxes +OAI.CategoryTheory.Thomason.SimplexColimits +OAI.CategoryTheory.Thomason.SimplexRanks +OAI.CategoryTheory.Thomason.SimplicialApproximation +OAI.CategoryTheory.Thomason.SkeletalCategories +OAI.CategoryTheory.Thomason.SquareClassification +OAI.CategoryTheory.Thomason.StandardComparison +OAI.CategoryTheory.Thomason.StationaryCylinders +OAI.CategoryTheory.Thomason.StrictCategories +OAI.CategoryTheory.Thomason.SubdividedUnit +OAI.CategoryTheory.Thomason.SubdivisionFaces +OAI.CategoryTheory.Thomason.SubdivisionMaps +OAI.CategoryTheory.Thomason.SubdivisionNerves +OAI.CategoryTheory.Thomason.SubdivisionPairing +OAI.CategoryTheory.Thomason.SubdivisionWeak +OAI.CategoryTheory.Thomason.TopSequences +OAI.CategoryTheory.Thomason.TwoCellComparison +OAI.CategoryTheory.Thomason.TwoCellExchange diff --git a/tasks/thomason-model-structures/solution/reference.py b/tasks/thomason-model-structures/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thomason-model-structures/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thomason-model-structures/solution/solve.sh b/tasks/thomason-model-structures/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..873ada54fe9f7e5326585f4c07e72626c87b0dc4 --- /dev/null +++ b/tasks/thomason-model-structures/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThomasonModelStructures, i.e. module OAI.CategoryTheory.Thomason.RankedFaithfulness and the +# 85 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.CategoryTheory.Thomason.RankedFaithfulness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThomasonModelStructures" diff --git a/tasks/thomason-model-structures/task.toml b/tasks/thomason-model-structures/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9b0fb30305406359a0340c999b065081bccb7fc4 --- /dev/null +++ b/tasks/thomason-model-structures/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thomason-model-structures" +version = "1.0.0" +description = "Prove ThomasonModelStructures (openai/math family 317: Thomason model structures in every strict higher dimension) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "topology"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThomasonModelStructures.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThomasonModelStructures" +family = "317" +family_title = "Thomason model structures in every strict higher dimension" +subject = "Topology" +theorems = ["OAI.Thomason.main", "OAI.Thomason.nerveDetection_allDimensions"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.CategoryTheory.Thomason.RankedFaithfulness" +reference_modules = 85 +reference_lean_bytes = 2875278 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1608 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14287 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thomason-model-structures/tests/Challenge.lean b/tasks/thomason-model-structures/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a89b56b5d5a4084951baec9e6af544463bb032a --- /dev/null +++ b/tasks/thomason-model-structures/tests/Challenge.lean @@ -0,0 +1,2473 @@ +import Mathlib + +/-! Definitions for the Thomason model structures and their Street-nerve detection statement. -/ + +noncomputable section +universe u v w + +section +namespace OAI.Thomason + + +structure OmegaCategory where + Cell : Type u + source : ℕ → Cell → Cell + target : ℕ → Cell → Cell + source_source (i j : ℕ) (x : Cell) : source i (source j x) = source (min i j) x + target_target (i j : ℕ) (x : Cell) : target i (target j x) = target (min i j) x + source_target (i j : ℕ) (x : Cell) : + source i (target j x) = if i < j then source i x else target j x + target_source (i j : ℕ) (x : Cell) : + target i (source j x) = if i < j then target i x else source j x + comp (k : ℕ) (x y : Cell) : target k x = source k y → Cell + source_comp_le (i k : ℕ) (hik : i ≤ k) (x y : Cell) + (h : target k x = source k y) : source i (comp k x y h) = source i x + target_comp_le (i k : ℕ) (hik : i ≤ k) (x y : Cell) + (h : target k x = source k y) : target i (comp k x y h) = target i y + source_comp_gt (i k : ℕ) (hki : k < i) (x y : Cell) + (h : target k x = source k y) + (hs : target k (source i x) = source k (source i y)) : + source i (comp k x y h) = comp k (source i x) (source i y) hs + target_comp_gt (i k : ℕ) (hki : k < i) (x y : Cell) + (h : target k x = source k y) + (ht : target k (target i x) = source k (target i y)) : + target i (comp k x y h) = comp k (target i x) (target i y) ht + unit_left (k : ℕ) (x : Cell) (h : target k (source k x) = source k x) : + comp k (source k x) x h = x + unit_right (k : ℕ) (x : Cell) (h : target k x = source k (target k x)) : + comp k x (target k x) h = x + assoc (k : ℕ) (x y z : Cell) + (hxy : target k x = source k y) (hyz : target k y = source k z) + (hxy_z : target k (comp k x y hxy) = source k z) + (hx_yz : target k x = source k (comp k y z hyz)) : + comp k (comp k x y hxy) z hxy_z = comp k x (comp k y z hyz) hx_yz + interchange (k l : ℕ) (hkl : k < l) (a b c d : Cell) + (hab : target l a = source l b) (hcd : target l c = source l d) + (hac : target k a = source k c) (hbd : target k b = source k d) + (hab_cd : target k (comp l a b hab) = source k (comp l c d hcd)) + (hac_bd : target l (comp k a c hac) = source l (comp k b d hbd)) : + comp k (comp l a b hab) (comp l c d hcd) hab_cd = + comp l (comp k a c hac) (comp k b d hbd) hac_bd + finite_dimension (x : Cell) : ∃ k, source k x = x + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory +variable (C : OmegaCategory.{u}) + +@[ext] +structure Functor (C : OAI.Thomason.OmegaCategory.{u}) (D : OAI.Thomason.OmegaCategory.{v}) where + map : C.Cell → D.Cell + map_source (k : ℕ) (x : C.Cell) : map (C.source k x) = D.source k (map x) + map_target (k : ℕ) (x : C.Cell) : map (C.target k x) = D.target k (map x) + map_comp (k : ℕ) (x y : C.Cell) (h : C.target k x = C.source k y) + (h' : D.target k (map x) = D.source k (map y)) : + map (C.comp k x y h) = D.comp k (map x) (map y) h' + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Functor +variable (C : OmegaCategory.{u}) +variable {C : OmegaCategory.{u}} {D : OmegaCategory.{v}} {B : OmegaCategory.{w}} + +noncomputable def id (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor C C where + map x := x + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + +noncomputable def comp (F : OAI.Thomason.OmegaCategory.Functor C D) (G : OAI.Thomason.OmegaCategory.Functor D B) : OAI.Thomason.OmegaCategory.Functor C B := by + classical + have proof_map_composable_0 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{v}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + exact { + map x := G.map (F.map x) + map_source k x := by rw [F.map_source, G.map_source] + map_target k x := by rw [F.map_target, G.map_target] + map_comp k x y h h' := by + rw [F.map_comp k x y h (proof_map_composable_0 F h), G.map_comp] + } + + +end OAI.Thomason.OmegaCategory.Functor +end + +section +namespace OAI.Thomason.OmegaCategory +variable (C : OmegaCategory.{u}) + +noncomputable instance : CategoryTheory.Category OAI.Thomason.OmegaCategory.{u} where + Hom C D := OAI.Thomason.OmegaCategory.Functor C D + id := OAI.Thomason.OmegaCategory.Functor.id + comp := OAI.Thomason.OmegaCategory.Functor.comp + +noncomputable def IsTruncated (n : ℕ) : Prop := ∀ x : C.Cell, C.source n x = x + +noncomputable def NCategory (n : ℕ) := {C : OAI.Thomason.OmegaCategory.{u} // C.IsTruncated n} + +noncomputable instance (n : ℕ) : CategoryTheory.Category (OAI.Thomason.OmegaCategory.NCategory.{u} n) where + Hom C D := OAI.Thomason.OmegaCategory.Functor C.val D.val + id C := OAI.Thomason.OmegaCategory.Functor.id C.val + comp := OAI.Thomason.OmegaCategory.Functor.comp + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason + + +structure DirectedComplex where + Chain : ℕ → Type u + group : ∀ p, AddCommGroup (Chain p) + d : (p : ℕ) → Chain (p+1) →+ Chain p + d_d (p : ℕ) (x : Chain (p+2)) : d p (d (p+1) x) = 0 + augmentation : Chain 0 →+ ℤ + augmentation_d (x : Chain 1) : augmentation (d 0 x) = 0 + positive : (p : ℕ) → AddSubmonoid (Chain p) + +end OAI.Thomason +end + +attribute [instance] OAI.Thomason.DirectedComplex.group + +section +namespace OAI.Thomason.DirectedComplex + + +@[ext] +structure Hom (K : OAI.Thomason.DirectedComplex.{u}) (L : OAI.Thomason.DirectedComplex.{v}) where + map (p : ℕ) : K.Chain p →+ L.Chain p + map_d (p : ℕ) (x : K.Chain (p+1)) : map p (K.d p x) = L.d p (map (p+1) x) + map_augmentation (x : K.Chain 0) : L.augmentation (map 0 x) = K.augmentation x + map_positive (p : ℕ) (x : K.Chain p) : x ∈ K.positive p → map p x ∈ L.positive p + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Hom +variable {K : DirectedComplex.{u}} {L : DirectedComplex.{v}} {M : DirectedComplex.{w}} + +noncomputable def id (K : OAI.Thomason.DirectedComplex.{u}) : OAI.Thomason.DirectedComplex.Hom K K where + map _ := AddMonoidHom.id _ + map_d _ _ := rfl + map_augmentation _ := rfl + map_positive _ _ h := h + +noncomputable def comp (f : OAI.Thomason.DirectedComplex.Hom K L) (g : OAI.Thomason.DirectedComplex.Hom L M) : OAI.Thomason.DirectedComplex.Hom K M where + map p := (g.map p).comp (f.map p) + map_d p x := by simp only [AddMonoidHom.comp_apply, f.map_d, g.map_d] + map_augmentation x := by simp only [AddMonoidHom.comp_apply, + g.map_augmentation, f.map_augmentation] + map_positive p x hx := g.map_positive p _ (f.map_positive p x hx) + + +end OAI.Thomason.DirectedComplex.Hom +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable instance : CategoryTheory.Category OAI.Thomason.DirectedComplex.{u} where + Hom := OAI.Thomason.DirectedComplex.Hom + id := OAI.Thomason.DirectedComplex.Hom.id + comp := OAI.Thomason.DirectedComplex.Hom.comp + +@[ext] +structure Table (K : OAI.Thomason.DirectedComplex.{u}) where + row : (p : ℕ) → Bool → K.Chain p + positive (p : ℕ) (b : Bool) : row p b ∈ K.positive p + boundary (p : ℕ) (b : Bool) : + K.d p (row (p+1) b) = row p true - row p false + augmentation (b : Bool) : K.augmentation (row 0 b) = 1 + bounded : ∃ k, ∀ p, k < p → ∀ b, row p b = 0 + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Table +variable {K : DirectedComplex.{u}} + +noncomputable def truncate (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : OAI.Thomason.DirectedComplex.Table K where + row p b := if p < k then x.row p b else if p = k then x.row p e else 0 + positive p b := by + split_ifs <;> first | exact x.positive _ _ | exact (K.positive _).zero_mem + boundary p b := by + by_cases hp : p < k + · by_cases hp' : p+1 < k + · simp only [hp, hp', ite_eq_left] + exact x.boundary p b + · have he : p+1 = k := by omega + simp only [ite_eq_left hp, ite_eq_right hp', ite_eq_left he] + exact x.boundary p e + · by_cases he : p = k + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [ite_eq_right hp, ite_eq_right hp', ite_eq_right he', ite_eq_left he, map_zero, sub_self] + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [hp, hp', he', he, ite_false, map_zero, sub_self] + augmentation b := by + by_cases hk : k = 0 + · subst k + simpa using x.augmentation e + · have hk' : 0 < k := Nat.pos_of_ne_zero hk + simpa only [hk', ite_eq_left] using x.augmentation b + bounded := by + refine ⟨k, ?_⟩ + intro p hp b + simp only [show ¬p < k by omega, show ¬p = k by omega, ite_false] + +noncomputable def comp (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : OAI.Thomason.DirectedComplex.Table K := by + classical + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_lower_rows_eq_1 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) {p : ℕ} (hp : p < k) (b : Bool) : + x.row p b = y.row p b := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row p b) h + simpa only [OAI.Thomason.DirectedComplex.Table.truncate, hp, ite_eq_left] using hr + have proof_matching_row_eq_2 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : x.row k true = y.row k false := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row k false) h + simpa [OAI.Thomason.DirectedComplex.Table.truncate] using hr + exact { + row p b := if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b + positive p b := by + split_ifs <;> first + | exact x.positive _ _ + | exact y.positive _ _ + | exact (K.positive _).add_mem (x.positive _ _) (y.positive _ _) + boundary p b := by + by_cases hp : p < k + · by_cases hp' : p+1 < k + · simp only [ite_eq_left hp, ite_eq_left hp'] + exact x.boundary p b + · have he : p+1 = k := by omega + simp only [ite_eq_left hp, ite_eq_right hp', ite_eq_left he] + cases b with + | false => exact x.boundary p false + | true => + change K.d p (y.row (p+1) true) = x.row p true - x.row p false + rw [y.boundary, proof_lower_rows_eq_1 h hp true, proof_lower_rows_eq_1 h hp false] + · by_cases he : p = k + · subst p + have hp' : ¬k+1 < k := by omega + have he' : ¬k+1 = k := by omega + simp only [ite_eq_right (Nat.lt_irrefl k), ite_eq_right hp', ite_eq_right he', + ↓reduceIte, map_add, x.boundary, y.boundary] + rw [proof_matching_row_eq_2 h] + abel_nf + exact add_comm _ _ + · have hp' : ¬p+1 < k := by omega + have he' : ¬p+1 = k := by omega + simp only [ite_eq_right hp, ite_eq_right hp', ite_eq_right he', ite_eq_right he, map_add, + x.boundary, y.boundary] + abel + augmentation b := by + by_cases hk : 0 < k + · simp only [ite_eq_left hk] + exact x.augmentation b + · have he : 0 = k := by omega + simp only [ite_eq_right hk, ite_eq_left he] + cases b <;> first | exact x.augmentation _ | exact y.augmentation _ + bounded := by + obtain ⟨nx, hx⟩ := x.bounded + obtain ⟨ny, hy⟩ := y.bounded + refine ⟨max nx ny, ?_⟩ + intro p hp b + have hx' := hx p (lt_of_le_of_lt (le_max_left _ _) hp) + have hy' := hy p (lt_of_le_of_lt (le_max_right _ _) hp) + split_ifs <;> simp only [hx', hy', zero_add] + } + + +end OAI.Thomason.DirectedComplex.Table +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable def nu (K : OAI.Thomason.DirectedComplex.{u}) : OAI.Thomason.OmegaCategory.{u} := by + classical + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_truncate_truncate_5 {K : OAI.Thomason.DirectedComplex.{u}} (i j : ℕ) (e f : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.truncate j f x) = + if i < j then OAI.Thomason.DirectedComplex.Table.truncate i e x else OAI.Thomason.DirectedComplex.Table.truncate j f x := by + ext p b + by_cases hij : i < j + · simp only [hij, ite_eq_left, OAI.Thomason.DirectedComplex.Table.truncate] + by_cases hpi : p < i + · have hpj : p < j := lt_trans hpi hij + simp [hpi, hpj] + · by_cases hpe : p = i + · subst p + simp [hij] + · simp [hpi, hpe] + · simp only [hij, ite_false, OAI.Thomason.DirectedComplex.Table.truncate] + by_cases hpj : p < j + · have hpi : p < i := by omega + simp [hpj, hpi] + · by_cases hpje : p = j + · subst p + by_cases hji : j < i + · simp [hji] + · have hi : i = j := by omega + subst i + simp [] + · by_cases hpi : p < i + · simp [hpi, hpj, hpje] + · by_cases hpie : p = i + · subst p + simp [hij] + · simp [hpi, hpie, hpj, hpje] + have proof_truncate_truncate_same_4 {K : OAI.Thomason.DirectedComplex.{u}} (i j : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.truncate j e x) = OAI.Thomason.DirectedComplex.Table.truncate (min i j) e x := by + rw [proof_truncate_truncate_5] + split_ifs with h + · rw [min_eq_left (le_of_lt h)] + · rw [min_eq_right (le_of_not_gt h)] + have proof_comp_row_14 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.comp k x y h).row p b = if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b := rfl + have proof_source_comp_le_6 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hik : i ≤ k) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : + OAI.Thomason.DirectedComplex.Table.truncate i false (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.truncate i false x := by + ext p b + by_cases hpi : p < i + · have hpk : p < k := lt_of_lt_of_le hpi hik + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpk] + · by_cases hpe : p = i + · subst p + by_cases hik' : i < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik'] + · have he : i = k := by omega + subst i + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpe] + have proof_lower_rows_eq_1 {K : OAI.Thomason.DirectedComplex.{u}} {k : ℕ} {x y : OAI.Thomason.DirectedComplex.Table K} + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) {p : ℕ} (hp : p < k) (b : Bool) : + x.row p b = y.row p b := by + have hr := congrArg (fun z : OAI.Thomason.DirectedComplex.Table K => z.row p b) h + simpa only [OAI.Thomason.DirectedComplex.Table.truncate, hp, ite_eq_left] using hr + have proof_target_comp_le_7 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hik : i ≤ k) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) : + OAI.Thomason.DirectedComplex.Table.truncate i true (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.truncate i true y := by + ext p b + by_cases hpi : p < i + · have hpk : p < k := lt_of_lt_of_le hpi hik + simp only [OAI.Thomason.DirectedComplex.Table.truncate, ite_eq_left hpi, OAI.Thomason.DirectedComplex.Table.comp, ite_eq_left hpk] + exact proof_lower_rows_eq_1 h hpk b + · by_cases hpe : p = i + · subst p + by_cases hik' : i < k + · simpa [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik'] using proof_lower_rows_eq_1 h hik' true + · have he : i = k := by omega + subst i + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpi, hpe] + have proof_truncate_comp_gt_8 {K : OAI.Thomason.DirectedComplex.{u}} (i k : ℕ) (hki : k < i) (e : Bool) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (h' : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.truncate i e x) = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.truncate i e y)) : + OAI.Thomason.DirectedComplex.Table.truncate i e (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.truncate i e x) (OAI.Thomason.DirectedComplex.Table.truncate i e y) h' := by + ext p b + by_cases hpk : p < k + · have hpi : p < i := lt_trans hpk hki + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpi] + · by_cases hpe : p = k + · subst p + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hki] + · by_cases hpi : p < i + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpi] + · by_cases hpie : p = i + · subst p + have hik : ¬i < k := by omega + have hie : ¬i = k := by omega + simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hik, hie] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpi, hpie] + have proof_unit_left_9 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.truncate k false x) = OAI.Thomason.DirectedComplex.Table.truncate k false x) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.truncate k false x) x h = x := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp, he] + have proof_unit_right_10 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.truncate k true x)) : + OAI.Thomason.DirectedComplex.Table.comp k x (OAI.Thomason.DirectedComplex.Table.truncate k true x) h = x := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.truncate, OAI.Thomason.DirectedComplex.Table.comp, hp, he] + have proof_assoc_11 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y z : OAI.Thomason.DirectedComplex.Table K) + (hxy : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (hyz : OAI.Thomason.DirectedComplex.Table.truncate k true y = OAI.Thomason.DirectedComplex.Table.truncate k false z) + (hxy_z : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.comp k x y hxy) = OAI.Thomason.DirectedComplex.Table.truncate k false z) + (hx_yz : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.comp k y z hyz)) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.comp k x y hxy) z hxy_z = OAI.Thomason.DirectedComplex.Table.comp k x (OAI.Thomason.DirectedComplex.Table.comp k y z hyz) hx_yz := by + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.comp, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.comp] + · simp [OAI.Thomason.DirectedComplex.Table.comp, hp, he, add_assoc] + have proof_interchange_12 {K : OAI.Thomason.DirectedComplex.{u}} (k l : ℕ) (hkl : k < l) (a b c d : OAI.Thomason.DirectedComplex.Table K) + (hab : OAI.Thomason.DirectedComplex.Table.truncate l true a = OAI.Thomason.DirectedComplex.Table.truncate l false b) + (hcd : OAI.Thomason.DirectedComplex.Table.truncate l true c = OAI.Thomason.DirectedComplex.Table.truncate l false d) + (hac : OAI.Thomason.DirectedComplex.Table.truncate k true a = OAI.Thomason.DirectedComplex.Table.truncate k false c) + (hbd : OAI.Thomason.DirectedComplex.Table.truncate k true b = OAI.Thomason.DirectedComplex.Table.truncate k false d) + (hab_cd : OAI.Thomason.DirectedComplex.Table.truncate k true (OAI.Thomason.DirectedComplex.Table.comp l a b hab) = OAI.Thomason.DirectedComplex.Table.truncate k false (OAI.Thomason.DirectedComplex.Table.comp l c d hcd)) + (hac_bd : OAI.Thomason.DirectedComplex.Table.truncate l true (OAI.Thomason.DirectedComplex.Table.comp k a c hac) = OAI.Thomason.DirectedComplex.Table.truncate l false (OAI.Thomason.DirectedComplex.Table.comp k b d hbd)) : + OAI.Thomason.DirectedComplex.Table.comp k (OAI.Thomason.DirectedComplex.Table.comp l a b hab) (OAI.Thomason.DirectedComplex.Table.comp l c d hcd) hab_cd = + OAI.Thomason.DirectedComplex.Table.comp l (OAI.Thomason.DirectedComplex.Table.comp k a c hac) (OAI.Thomason.DirectedComplex.Table.comp k b d hbd) hac_bd := by + ext p e + by_cases hpk : p < k + · have hpl : p < l := lt_trans hpk hkl + simp [OAI.Thomason.DirectedComplex.Table.comp, hpk, hpl] + · by_cases hpe : p = k + · subst p + cases e <;> simp [OAI.Thomason.DirectedComplex.Table.comp, hkl] + · by_cases hpl : p < l + · simp [OAI.Thomason.DirectedComplex.Table.comp, hpk, hpe, hpl] + · by_cases hple : p = l + · subst p + have hlk : ¬l < k := by omega + have hlke : ¬l = k := by omega + cases e <;> simp [OAI.Thomason.DirectedComplex.Table.comp, hlk, hlke] + · simp only [OAI.Thomason.DirectedComplex.Table.comp, ite_eq_right hpk, ite_eq_right hpe, ite_eq_right hpl, ite_eq_right hple] + abel + have proof_finite_dimension_13 {K : OAI.Thomason.DirectedComplex.{u}} (x : OAI.Thomason.DirectedComplex.Table K) : ∃ k, OAI.Thomason.DirectedComplex.Table.truncate k false x = x := by + obtain ⟨k, hk⟩ := x.bounded + have ht : x.row k true = x.row k false := by + have hb := x.boundary k false + rw [hk (k+1) (by omega) false, map_zero] at hb + exact sub_eq_zero.mp hb.symm + refine ⟨k, ?_⟩ + ext p b + by_cases hp : p < k + · simp [OAI.Thomason.DirectedComplex.Table.truncate, hp] + · by_cases he : p = k + · subst p + cases b <;> simp [OAI.Thomason.DirectedComplex.Table.truncate, ht] + · have hkp : k < p := by omega + simp [OAI.Thomason.DirectedComplex.Table.truncate, hp, he, hk p hkp b] + exact { + Cell := OAI.Thomason.DirectedComplex.Table K + source k := OAI.Thomason.DirectedComplex.Table.truncate k false + target k := OAI.Thomason.DirectedComplex.Table.truncate k true + source_source i j x := proof_truncate_truncate_same_4 i j false x + target_target i j x := proof_truncate_truncate_same_4 i j true x + source_target i j x := proof_truncate_truncate_5 i j false true x + target_source i j x := proof_truncate_truncate_5 i j true false x + comp := OAI.Thomason.DirectedComplex.Table.comp + source_comp_le := proof_source_comp_le_6 + target_comp_le := proof_target_comp_le_7 + source_comp_gt i k hki x y h hs := proof_truncate_comp_gt_8 i k hki false x y h hs + target_comp_gt i k hki x y h ht := proof_truncate_comp_gt_8 i k hki true x y h ht + unit_left := proof_unit_left_9 + unit_right := proof_unit_right_10 + assoc := proof_assoc_11 + interchange := proof_interchange_12 + finite_dimension := proof_finite_dimension_13 + } + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.DirectedComplex.Hom +variable {K : DirectedComplex.{u}} {L : DirectedComplex.{v}} {M : DirectedComplex.{w}} + +noncomputable def table (f : OAI.Thomason.DirectedComplex.Hom K L) (x : OAI.Thomason.DirectedComplex.Table K) : OAI.Thomason.DirectedComplex.Table L where + row p b := f.map p (x.row p b) + positive p b := f.map_positive p _ (x.positive p b) + boundary p b := by rw [← f.map_d, x.boundary, map_sub] + augmentation b := by rw [f.map_augmentation, x.augmentation] + bounded := by + obtain ⟨k, hk⟩ := x.bounded + refine ⟨k, ?_⟩ + intro p hp b + rw [hk p hp b, map_zero] + +noncomputable def nu (f : OAI.Thomason.DirectedComplex.Hom K L) : OAI.Thomason.OmegaCategory.Functor K.nu L.nu := by + classical + have proof_table_row_17 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (f.table x).row p b = f.map p (x.row p b) := rfl + have proof_truncate_row_3 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (e : Bool) (x : OAI.Thomason.DirectedComplex.Table K) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.truncate k e x).row p b = + if p < k then x.row p b else if p = k then x.row p e else 0 := rfl + have proof_table_truncate_15 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (k : ℕ) (b : Bool) (x : OAI.Thomason.DirectedComplex.Table K) : + f.table (OAI.Thomason.DirectedComplex.Table.truncate k b x) = OAI.Thomason.DirectedComplex.Table.truncate k b (f.table x) := by + ext p e + simp only [OAI.Thomason.DirectedComplex.Hom.table, OAI.Thomason.DirectedComplex.Table.truncate] + split_ifs <;> simp only [map_zero] + have proof_comp_row_14 {K : OAI.Thomason.DirectedComplex.{u}} (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) (p : ℕ) (b : Bool) : + (OAI.Thomason.DirectedComplex.Table.comp k x y h).row p b = if p < k then x.row p b else if p = k then + (if b then y.row p true else x.row p false) else x.row p b + y.row p b := rfl + have proof_table_comp_16 {K : OAI.Thomason.DirectedComplex.{u}} {L : OAI.Thomason.DirectedComplex.{v}} (f : OAI.Thomason.DirectedComplex.Hom K L) (k : ℕ) (x y : OAI.Thomason.DirectedComplex.Table K) + (h : OAI.Thomason.DirectedComplex.Table.truncate k true x = OAI.Thomason.DirectedComplex.Table.truncate k false y) + (h' : OAI.Thomason.DirectedComplex.Table.truncate k true (f.table x) = OAI.Thomason.DirectedComplex.Table.truncate k false (f.table y)) : + f.table (OAI.Thomason.DirectedComplex.Table.comp k x y h) = OAI.Thomason.DirectedComplex.Table.comp k (f.table x) (f.table y) h' := by + ext p e + simp only [OAI.Thomason.DirectedComplex.Hom.table, OAI.Thomason.DirectedComplex.Table.comp] + split_ifs <;> simp only [map_add] + exact { + map := f.table + map_source k x := (proof_table_truncate_15 f k Bool.false x) + map_target k x := (proof_table_truncate_15 f k Bool.true x) + map_comp := (proof_table_comp_16 f) + } + + +end OAI.Thomason.DirectedComplex.Hom +end + +section +namespace OAI.Thomason.DirectedComplex + + +noncomputable def nuFunctor : CategoryTheory.Functor OAI.Thomason.DirectedComplex.{u} OAI.Thomason.OmegaCategory.{u} where + obj := OAI.Thomason.DirectedComplex.nu + map := OAI.Thomason.DirectedComplex.Hom.nu + map_id K := by + change OAI.Thomason.DirectedComplex.Hom.nu (OAI.Thomason.DirectedComplex.Hom.id K) = OAI.Thomason.OmegaCategory.Functor.id K.nu + ext x + rfl + map_comp f g := by + change OAI.Thomason.DirectedComplex.Hom.nu (OAI.Thomason.DirectedComplex.Hom.comp f g) = OAI.Thomason.OmegaCategory.Functor.comp f.nu g.nu + ext x + rfl + + +end OAI.Thomason.DirectedComplex +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable abbrev Word (E : Type u) [PartialOrder E] := + {l : List E // l.Pairwise (· < ·)} + +noncomputable abbrev Chains (E : Type u) [PartialOrder E] := OAI.Thomason.NormalizedChains.Word E →₀ ℤ + +noncomputable def bracket (l : List E) : OAI.Thomason.NormalizedChains.Chains E := by + classical + exact if h : l.Pairwise (· < ·) then Finsupp.single ⟨l, h⟩ 1 else 0 + +noncomputable def prepend (a : E) : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains E := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + +noncomputable def wordBoundary : List E → OAI.Thomason.NormalizedChains.Chains E + | [] => 0 + | a :: l => OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (wordBoundary l) + +noncomputable def boundary : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains E := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +omit [PartialOrder E] +variable {M : Type v} [AddCommGroup M] + +noncomputable def faces (H : List E → M) : List E → M + | [] => 0 + | a :: l => H l - faces (fun m => H (a :: m)) l + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable def grade (k : ℕ) : Submodule ℤ (OAI.Thomason.NormalizedChains.Chains E) := + Finsupp.supported ℤ ℤ {w : OAI.Thomason.NormalizedChains.Word E | w.val.length = k} + +noncomputable def emptyWord : OAI.Thomason.NormalizedChains.Word E := ⟨[], List.Pairwise.nil⟩ + +noncomputable def emptyCoefficient : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] ℤ := Finsupp.lapply OAI.Thomason.NormalizedChains.emptyWord + +noncomputable def Positive (c : OAI.Thomason.NormalizedChains.Chains E) : Prop := ∀ l, 0 ≤ c l + +noncomputable def positiveGrade (p : ℕ) : AddSubmonoid (OAI.Thomason.NormalizedChains.grade (E := E) (p+1)) where + carrier := {c | Positive c.val} + zero_mem' _ := le_rfl + add_mem' ha hb w := add_nonneg (ha w) (hb w) + +noncomputable def complex (E : Type u) [PartialOrder E] : OAI.Thomason.DirectedComplex.{u} := by + classical + have proof_mem_grade_iff_20 {E : Type u} [instLocal1 : PartialOrder.{u} E] (k : ℕ) (c : OAI.Thomason.NormalizedChains.Chains E) : + c ∈ OAI.Thomason.NormalizedChains.grade k ↔ ∀ w, c w ≠ 0 → w.val.length = k := by + simp only [OAI.Thomason.NormalizedChains.grade, Finsupp.mem_supported, Set.subset_def, Finsupp.mem_support_iff, + Finset.mem_coe, Set.mem_ofPred_eq] + have proof_linearCombination_mem_grade_21 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type u} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (k j : ℕ) + (hH : ∀ w, w.val.length = k → H w ∈ OAI.Thomason.NormalizedChains.grade j) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + Finsupp.linearCombination ℤ H c ∈ OAI.Thomason.NormalizedChains.grade j := by + rw [Finsupp.linearCombination_apply, Finsupp.sum] + apply Submodule.sum_mem + intro w hw + exact Submodule.smul_mem _ _ (hH w ((proof_mem_grade_iff_20 k c).mp hc w + (Finsupp.mem_support_iff.mp hw))) + have proof_bracket_of_pairwise_22 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_23 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_mem_grade_24 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.bracket l ∈ OAI.Thomason.NormalizedChains.grade l.length := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + exact Finsupp.single_mem_supported ℤ 1 rfl + · rw [proof_bracket_of_not_pairwise_23 h] + exact Submodule.zero_mem _ + have proof_wordBoundary_nil_25 {E : Type u} [instLocal1 : PartialOrder.{u} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_26 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_prepend_bracket_27 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_23 h, proof_bracket_of_not_pairwise_23 h'] + have proof_prepend_mem_grade_28 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) {k : ℕ} {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + OAI.Thomason.NormalizedChains.prepend a c ∈ OAI.Thomason.NormalizedChains.grade (k+1) := by + apply proof_linearCombination_mem_grade_21 _ k (k+1) _ hc + intro w hw + simpa only [List.length_cons, hw] using proof_bracket_mem_grade_24 (a :: w.val) + have proof_wordBoundary_mem_grade_29 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.wordBoundary l ∈ OAI.Thomason.NormalizedChains.grade (l.length-1) := by + induction l with + | nil => exact Submodule.zero_mem _ + | cons a l ih => + cases l with + | nil => simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary] using proof_bracket_mem_grade_24 ([] : List E) + | cons b l => + rw [proof_wordBoundary_cons_26] + apply Submodule.sub_mem + · simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27] using proof_bracket_mem_grade_24 (b :: l) + · simpa [proof_wordBoundary_nil_25, proof_wordBoundary_cons_26, proof_prepend_bracket_27] using proof_prepend_mem_grade_28 a ih + have proof_boundary_mem_grade_18 {E : Type u} [instLocal1 : PartialOrder.{u} E] {k : ℕ} {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade (k+1)) : + OAI.Thomason.NormalizedChains.boundary c ∈ OAI.Thomason.NormalizedChains.grade k := by + apply proof_linearCombination_mem_grade_21 _ (k+1) k _ hc + intro w hw + simpa only [hw, Nat.add_sub_cancel] using proof_wordBoundary_mem_grade_29 w.val + have proof_prepend_prepend_self_30 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_27] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_23 h] + have proof_wordBoundary_repeated_31 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_30] + have proof_wordBoundary_eq_zero_of_not_pairwise_32 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_31 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_23 hl, ih h.tail hl] + have proof_boundary_bracket_33 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_23 hs, proof_wordBoundary_eq_zero_of_not_pairwise_32 h hs] + have proof_faces_nil_34 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_35 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_hom_36 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type u} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_bracket_37 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_wordBoundary_cons_26] + have h := proof_faces_hom_36 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_27] at h + rw [← h, ih] + have proof_faces_congr_38 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {H K : List E → M} {l : List E} + (h : ∀ m, m.Sublist l → H m = K m) : OAI.Thomason.NormalizedChains.faces H l = OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_faces_cons_35, h l (List.sublist_cons_self a l)] + congr 1 + exact ih (fun m hm => h (a :: m) (List.Sublist.cons_cons a hm)) + have proof_faces_sub_39 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H K : List E → M) (l : List E) : + OAI.Thomason.NormalizedChains.faces (fun m => H m - K m) l = OAI.Thomason.NormalizedChains.faces H l - OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => simp [proof_faces_nil_34] + | cons a l ih => simp only [proof_faces_cons_35, ih]; abel + have proof_faces_faces_40 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (l : List E) : + OAI.Thomason.NormalizedChains.faces (OAI.Thomason.NormalizedChains.faces H) l = 0 := by + induction l generalizing H with + | nil => rfl + | cons a l ih => + simp only [proof_faces_cons_35] + rw [proof_faces_sub_39, ih] + simp [] + have proof_boundary_wordBoundary_41 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.wordBoundary l) = 0 := by + rw [← proof_faces_bracket_37] + change OAI.Thomason.NormalizedChains.boundary.toAddMonoidHom (OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l) = 0 + rw [proof_faces_hom_36] + have hc : OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket m)) l = OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.wordBoundary l := by + apply proof_faces_congr_38 + intro m hm + exact proof_boundary_bracket_33 (h.sublist hm) + change OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket m)) l = 0 + rw [hc] + change OAI.Thomason.NormalizedChains.faces (fun m => OAI.Thomason.NormalizedChains.wordBoundary m) l = 0 + simp_rw [← proof_faces_bracket_37] + exact proof_faces_faces_40 OAI.Thomason.NormalizedChains.bracket l + have proof_boundary_boundary_19 {E : Type u} [instLocal1 : PartialOrder.{u} E] (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.boundary c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul] + rw [proof_boundary_bracket_33 (l.property.imp fun h => le_of_lt h), + proof_boundary_wordBoundary_41 (l.property.imp fun h => le_of_lt h), smul_zero] + exact { + Chain p := OAI.Thomason.NormalizedChains.grade (E := E) (p+1) + group _ := inferInstance + d p := + { toFun := fun c => ⟨OAI.Thomason.NormalizedChains.boundary c.val, proof_boundary_mem_grade_18 c.property⟩ + map_zero' := Subtype.ext (map_zero _) + map_add' := fun x y => Subtype.ext (map_add _ x.val y.val) } + d_d p x := Subtype.ext (proof_boundary_boundary_19 x.val) + augmentation := + { toFun := fun c => OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary c.val) + map_zero' := by simp [] + map_add' := by intros; simp [] } + augmentation_d x := by + change OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.boundary x.val)) = 0 + rw [proof_boundary_boundary_19, map_zero] + positive := OAI.Thomason.NormalizedChains.positiveGrade + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +variable {D : Type v} [PartialOrder D] {B : Type w} [PartialOrder B] + +noncomputable def map (f : E →o D) : OAI.Thomason.NormalizedChains.Chains E →ₗ[ℤ] OAI.Thomason.NormalizedChains.Chains D := + Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] + +noncomputable def complexMap {D : Type v} [PartialOrder D] (f : E →o D) : + OAI.Thomason.DirectedComplex.Hom (OAI.Thomason.NormalizedChains.complex E) (OAI.Thomason.NormalizedChains.complex D) := by + classical + have proof_mem_grade_iff_20 {E : Type u} [instLocal1 : PartialOrder.{u} E] (k : ℕ) (c : OAI.Thomason.NormalizedChains.Chains E) : + c ∈ OAI.Thomason.NormalizedChains.grade k ↔ ∀ w, c w ≠ 0 → w.val.length = k := by + simp only [OAI.Thomason.NormalizedChains.grade, Finsupp.mem_supported, Set.subset_def, Finsupp.mem_support_iff, + Finset.mem_coe, Set.mem_ofPred_eq] + have proof_linearCombination_mem_grade_46 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (k j : ℕ) + (hH : ∀ w, w.val.length = k → H w ∈ OAI.Thomason.NormalizedChains.grade j) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : + Finsupp.linearCombination ℤ H c ∈ OAI.Thomason.NormalizedChains.grade j := by + rw [Finsupp.linearCombination_apply, Finsupp.sum] + apply Submodule.sum_mem + intro w hw + exact Submodule.smul_mem _ _ (hH w ((proof_mem_grade_iff_20 k c).mp hc w + (Finsupp.mem_support_iff.mp hw))) + have proof_bracket_of_pairwise_47 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_48 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_mem_grade_49 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.bracket l ∈ OAI.Thomason.NormalizedChains.grade l.length := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 h] + exact Finsupp.single_mem_supported ℤ 1 rfl + · rw [proof_bracket_of_not_pairwise_48 h] + exact Submodule.zero_mem _ + have proof_map_mem_grade_42 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) {k : ℕ} + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : c ∈ OAI.Thomason.NormalizedChains.grade k) : OAI.Thomason.NormalizedChains.map f c ∈ OAI.Thomason.NormalizedChains.grade k := by + apply proof_linearCombination_mem_grade_46 _ k k _ hc + intro w hw + simpa only [List.length_map, hw] using proof_bracket_mem_grade_49 (w.val.map f) + have proof_bracket_of_pairwise_22 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_bracket_of_not_pairwise_23 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_prepend_bracket_27 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_23 h, proof_bracket_of_not_pairwise_23 h'] + have proof_prepend_prepend_self_30 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_27] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_23 h] + have proof_wordBoundary_nil_25 {E : Type u} [instLocal1 : PartialOrder.{u} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_26 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_wordBoundary_repeated_31 {E : Type u} [instLocal1 : PartialOrder.{u} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_27, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_30] + have proof_wordBoundary_eq_zero_of_not_pairwise_32 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_31 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_23 hl, ih h.tail hl] + have proof_boundary_bracket_33 {E : Type u} [instLocal1 : PartialOrder.{u} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_23 hs, proof_wordBoundary_eq_zero_of_not_pairwise_32 h hs] + have proof_faces_nil_34 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_35 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_hom_36 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type u} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_bracket_37 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_35, proof_wordBoundary_cons_26] + have h := proof_faces_hom_36 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_27] at h + rw [← h, ih] + have proof_faces_nil_50 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_51 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_wordBoundary_nil_52 {E : Type v} [instLocal1 : PartialOrder.{v} E] : OAI.Thomason.NormalizedChains.wordBoundary ([] : List E) = 0 := rfl + have proof_wordBoundary_cons_53 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: l) = OAI.Thomason.NormalizedChains.bracket l - OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.wordBoundary l) := rfl + have proof_faces_hom_54 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {M' : Type v} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp [proof_faces_nil_50] + | cons a l ih => simp only [proof_faces_cons_51, map_sub, ih] + have proof_prepend_bracket_55 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (a :: l) := by + classical + by_cases h : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 h] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (a :: l.val)) + (Finsupp.single (⟨l, h⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have h' : ¬(a :: l).Pairwise (· < ·) := fun hw => h hw.tail + simp [proof_bracket_of_not_pairwise_48 h, proof_bracket_of_not_pairwise_48 h'] + have proof_faces_bracket_56 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l = OAI.Thomason.NormalizedChains.wordBoundary l := by + induction l with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_51, proof_wordBoundary_cons_53] + have h := proof_faces_hom_54 (OAI.Thomason.NormalizedChains.prepend a).toAddMonoidHom OAI.Thomason.NormalizedChains.bracket l + simp only [LinearMap.toAddMonoidHom_coe, proof_prepend_bracket_55] at h + rw [← h, ih] + have proof_faces_hom_57 {E : Type u} {M : Type u} [instLocal2 : AddCommGroup.{u} M] {M' : Type v} [AddCommGroup M'] (q : M →+ M') + (H : List E → M) (l : List E) : + q (OAI.Thomason.NormalizedChains.faces H l) = OAI.Thomason.NormalizedChains.faces (fun m => q (H m)) l := by + induction l generalizing H with + | nil => simp only [OAI.Thomason.NormalizedChains.faces, map_zero] + | cons a l ih => simp only [OAI.Thomason.NormalizedChains.faces, map_sub, ih] + have proof_faces_map_58 {E : Type v} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {D : Type u} (f : D → E) (H : List E → M) (l : List D) : + OAI.Thomason.NormalizedChains.faces H (l.map f) = OAI.Thomason.NormalizedChains.faces (fun m => H (m.map f)) l := by + induction l generalizing H with + | nil => rfl + | cons a l ih => simp only [List.map_cons, OAI.Thomason.NormalizedChains.faces, ih] + have proof_faces_nil_59 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) : OAI.Thomason.NormalizedChains.faces H [] = 0 := rfl + have proof_faces_cons_60 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] (H : List E → M) (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.faces H (a :: l) = H l - OAI.Thomason.NormalizedChains.faces (fun m => H (a :: m)) l := rfl + have proof_faces_congr_61 {E : Type u} {M : Type v} [instLocal2 : AddCommGroup.{v} M] {H K : List E → M} {l : List E} + (h : ∀ m, m.Sublist l → H m = K m) : OAI.Thomason.NormalizedChains.faces H l = OAI.Thomason.NormalizedChains.faces K l := by + induction l generalizing H K with + | nil => rfl + | cons a l ih => + rw [proof_faces_cons_60, proof_faces_cons_60, h l (List.sublist_cons_self a l)] + congr 1 + exact ih (fun m hm => h (a :: m) (List.Sublist.cons_cons a hm)) + have proof_pairwise_of_map_62 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] {l : List E} (h : l.Pairwise (· ≤ ·)) (f : E → D) + (hf : (l.map f).Pairwise (· < ·)) : l.Pairwise (· < ·) := by + apply (h.and (List.pairwise_map.mp hf)).imp + intro a b hab + exact lt_of_le_of_ne hab.1 (fun he => (ne_of_lt hab.2) (congrArg f he)) + have proof_map_bracket_63 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (l.map f) := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_22 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have hf : ¬(l.map f).Pairwise (· < ·) := fun hm => hs (proof_pairwise_of_map_62 h f hm) + simp [proof_bracket_of_not_pairwise_23 hs, proof_bracket_of_not_pairwise_48 hf] + have proof_map_wordBoundary_64 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.wordBoundary l) = OAI.Thomason.NormalizedChains.wordBoundary (l.map f) := by + rw [← proof_faces_bracket_37, ← proof_faces_bracket_56] + change (OAI.Thomason.NormalizedChains.map f).toAddMonoidHom (OAI.Thomason.NormalizedChains.faces OAI.Thomason.NormalizedChains.bracket l) = _ + rw [proof_faces_hom_57, proof_faces_map_58] + apply proof_faces_congr_61 + intro m hm + exact proof_map_bracket_63 f (h.sublist hm) + have proof_prepend_prepend_self_65 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.prepend a (OAI.Thomason.NormalizedChains.prepend a c) = 0 := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih, add_zero] + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_47 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_prepend_bracket_55] + have h : ¬(a :: a :: l.val).Pairwise (· < ·) := by simp [] + simp [proof_bracket_of_not_pairwise_48 h] + have proof_wordBoundary_repeated_66 {E : Type v} [instLocal1 : PartialOrder.{v} E] (a : E) (l : List E) : + OAI.Thomason.NormalizedChains.wordBoundary (a :: a :: l) = 0 := by + simp [proof_prepend_bracket_55, OAI.Thomason.NormalizedChains.wordBoundary, map_sub, proof_prepend_prepend_self_65] + have proof_wordBoundary_eq_zero_of_not_pairwise_67 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} + (h : l.Pairwise (· ≤ ·)) (hn : ¬l.Pairwise (· < ·)) : OAI.Thomason.NormalizedChains.wordBoundary l = 0 := by + induction l with + | nil => exact (hn (by simp)).elim + | cons a l ih => + by_cases hl : l.Pairwise (· < ·) + · cases l with + | nil => exact (hn (by simp)).elim + | cons b l => + have hab : a ≤ b := (List.pairwise_cons.mp h).1 b (by simp) + have hab' : ¬a < b := by + intro hab' + exact hn (List.Pairwise.cons_cons_of_trans hab' hl) + have heq : a = b := (lt_or_eq_of_le hab).resolve_left hab' + subst b + exact proof_wordBoundary_repeated_66 a l + · simp [OAI.Thomason.NormalizedChains.wordBoundary, proof_bracket_of_not_pairwise_48 hl, ih h.tail hl] + have proof_boundary_bracket_68 {E : Type v} [instLocal1 : PartialOrder.{v} E] {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.wordBoundary l := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_47 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.wordBoundary l.val) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp [] + · simp [proof_bracket_of_not_pairwise_48 hs, proof_wordBoundary_eq_zero_of_not_pairwise_67 h hs] + have proof_map_boundary_43 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [instLocal3 : PartialOrder.{v} D] (f : E →o D) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.boundary c) = OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.map f c) := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + have hl := l.property.imp fun h => le_of_lt h + rw [hz] + simp only [map_smul] + rw [proof_boundary_bracket_33 hl, proof_map_wordBoundary_64 f hl, proof_map_bracket_63 f hl, + proof_boundary_bracket_68 (List.pairwise_map.mpr (hl.imp fun hh => f.monotone hh))] + have proof_emptyCoefficient_bracket_69 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.bracket l) = if l = [] then 1 else 0 := by + classical + by_cases hl : l = [] + · subst l + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_47 List.Pairwise.nil, OAI.Thomason.NormalizedChains.emptyWord] + · by_cases hs : l.Pairwise (· < ·) + · have hw : (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) ≠ OAI.Thomason.NormalizedChains.emptyWord := by + intro he + exact hl (congrArg Subtype.val he) + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_47 hs, hw, hl] + · simp [proof_bracket_of_not_pairwise_48 hs, hl] + have proof_emptyCoefficient_bracket_70 {E : Type u} [instLocal1 : PartialOrder.{u} E] (l : List E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.bracket l) = if l = [] then 1 else 0 := by + classical + by_cases hl : l = [] + · subst l + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_22 List.Pairwise.nil, OAI.Thomason.NormalizedChains.emptyWord] + · by_cases hs : l.Pairwise (· < ·) + · have hw : (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) ≠ OAI.Thomason.NormalizedChains.emptyWord := by + intro he + exact hl (congrArg Subtype.val he) + simp [OAI.Thomason.NormalizedChains.emptyCoefficient, proof_bracket_of_pairwise_22 hs, hw, hl] + · simp [proof_bracket_of_not_pairwise_23 hs, hl] + have proof_emptyCoefficient_map_44 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.map f c) = OAI.Thomason.NormalizedChains.emptyCoefficient c := by + classical + induction c using Finsupp.induction with + | zero => simp [] + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_22 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz] + simp only [map_smul, proof_map_bracket_63 _ (l.property.imp fun h => le_of_lt h), + proof_emptyCoefficient_bracket_69, proof_emptyCoefficient_bracket_70, List.map_eq_nil_iff] + have proof_linearCombination_positive_71 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] + (H : OAI.Thomason.NormalizedChains.Word E → OAI.Thomason.NormalizedChains.Chains D) (hH : ∀ w, OAI.Thomason.NormalizedChains.Positive (H w)) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : OAI.Thomason.NormalizedChains.Positive c) : + OAI.Thomason.NormalizedChains.Positive (Finsupp.linearCombination ℤ H c) := by + intro w + rw [Finsupp.linearCombination_apply, Finsupp.sum] + simp only [Finset.sum_apply, Finsupp.coe_finsetSum] + apply Finset.sum_nonneg + intro i _ + exact mul_nonneg (hc i) (hH i w) + have proof_bracket_positive_72 {E : Type v} [instLocal1 : PartialOrder.{v} E] (l : List E) : OAI.Thomason.NormalizedChains.Positive (OAI.Thomason.NormalizedChains.bracket l) := by + classical + intro w + by_cases h : l.Pairwise (· < ·) + · simp [proof_bracket_of_pairwise_47 h, Finsupp.single_apply] + split <;> omega + · simp [proof_bracket_of_not_pairwise_48 h] + have proof_map_positive_45 {E : Type u} [instLocal1 : PartialOrder.{u} E] {D : Type v} [PartialOrder D] (f : E →o D) + {c : OAI.Thomason.NormalizedChains.Chains E} (hc : OAI.Thomason.NormalizedChains.Positive c) : OAI.Thomason.NormalizedChains.Positive (OAI.Thomason.NormalizedChains.map f c) := + proof_linearCombination_positive_71 _ (fun w => proof_bracket_positive_72 (w.val.map f)) hc + exact { + map p := + { toFun := fun c => ⟨OAI.Thomason.NormalizedChains.map f c.val, proof_map_mem_grade_42 f c.property⟩ + map_zero' := Subtype.ext (map_zero _) + map_add' := fun x y => Subtype.ext (map_add _ x.val y.val) } + map_d p x := Subtype.ext (proof_map_boundary_43 f x.val) + map_augmentation x := by + change OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary (OAI.Thomason.NormalizedChains.map f x.val)) = OAI.Thomason.NormalizedChains.emptyCoefficient (OAI.Thomason.NormalizedChains.boundary x.val) + rw [← proof_map_boundary_43, proof_emptyCoefficient_map_44] + map_positive p x hx := proof_map_positive_45 f hx + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason.NormalizedChains +variable {E : Type u} [PartialOrder E] +open CategoryTheory + +noncomputable def simplexComplexes : SimplexCategory ⥤ OAI.Thomason.DirectedComplex.{0} := by + classical + have proof_bracket_of_pairwise_75 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {l : List E} (h : l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = Finsupp.single ⟨l, h⟩ 1 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_pairwise_of_map_76 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] {l : List E} (h : l.Pairwise (· ≤ ·)) (f : E → D) + (hf : (l.map f).Pairwise (· < ·)) : l.Pairwise (· < ·) := by + apply (h.and (List.pairwise_map.mp hf)).imp + intro a b hab + exact lt_of_le_of_ne hab.1 (fun he => (ne_of_lt hab.2) (congrArg f he)) + have proof_bracket_of_not_pairwise_77 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {l : List E} (h : ¬l.Pairwise (· < ·)) : + OAI.Thomason.NormalizedChains.bracket l = 0 := by + classical + simp [OAI.Thomason.NormalizedChains.bracket, h] + have proof_map_bracket_78 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] (f : E →o D) {l : List E} (h : l.Pairwise (· ≤ ·)) : + OAI.Thomason.NormalizedChains.map f (OAI.Thomason.NormalizedChains.bracket l) = OAI.Thomason.NormalizedChains.bracket (l.map f) := by + classical + by_cases hs : l.Pairwise (· < ·) + · rw [proof_bracket_of_pairwise_75 hs] + change Finsupp.linearCombination ℤ (fun l : OAI.Thomason.NormalizedChains.Word E => OAI.Thomason.NormalizedChains.bracket (l.val.map f)) + (Finsupp.single (⟨l, hs⟩ : OAI.Thomason.NormalizedChains.Word E) 1) = _ + rw [Finsupp.linearCombination_single] + simp + · have hf : ¬(l.map f).Pairwise (· < ·) := fun hm => hs (proof_pairwise_of_map_76 h f hm) + simp [proof_bracket_of_not_pairwise_77 hs, proof_bracket_of_not_pairwise_77 hf] + have proof_map_id_79 {E : Type 0} [instLocal1 : PartialOrder.{0} E] (c : OAI.Thomason.NormalizedChains.Chains E) : OAI.Thomason.NormalizedChains.map (OrderHom.id) c = c := by + classical + induction c using Finsupp.induction with + | zero => simp + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_75 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + rw [hz, map_smul, proof_map_bracket_78 _ (l.property.imp fun h => le_of_lt h)] + simp + have proof_complexMap_id_73 {E : Type 0} [instLocal1 : PartialOrder.{0} E] : OAI.Thomason.NormalizedChains.complexMap (OrderHom.id : E →o E) = + OAI.Thomason.DirectedComplex.Hom.id (OAI.Thomason.NormalizedChains.complex E) := by + ext p x + apply Subtype.ext + exact proof_map_id_79 x.val + have proof_map_comp_80 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [instLocal3 : PartialOrder.{0} D] {B : Type 0} [instLocal5 : PartialOrder.{0} B] (f : E →o D) (g : D →o B) (c : OAI.Thomason.NormalizedChains.Chains E) : + OAI.Thomason.NormalizedChains.map (g.comp f) c = OAI.Thomason.NormalizedChains.map g (OAI.Thomason.NormalizedChains.map f c) := by + classical + induction c using Finsupp.induction with + | zero => simp + | @single_add l z c _ _ ih => + simp only [map_add, ih] + congr 1 + have hz : Finsupp.single l z = z • OAI.Thomason.NormalizedChains.bracket l.val := by + rw [proof_bracket_of_pairwise_75 l.property] + simp only [Finsupp.smul_single, smul_eq_mul, mul_one] + have hl := l.property.imp fun h => le_of_lt h + rw [hz] + simp only [map_smul] + rw [proof_map_bracket_78 _ hl, proof_map_bracket_78 _ hl, + proof_map_bracket_78 _ (List.pairwise_map.mpr (hl.imp fun hh => f.monotone hh))] + simp [List.map_map] + have proof_complexMap_comp_74 {E : Type 0} [instLocal1 : PartialOrder.{0} E] {D : Type 0} [PartialOrder D] {B : Type 0} [PartialOrder B] + (f : E →o D) (g : D →o B) : OAI.Thomason.NormalizedChains.complexMap (g.comp f) = + OAI.Thomason.DirectedComplex.Hom.comp (OAI.Thomason.NormalizedChains.complexMap f) (OAI.Thomason.NormalizedChains.complexMap g) := by + ext p x + apply Subtype.ext + exact proof_map_comp_80 f g x.val + exact { + obj m := OAI.Thomason.NormalizedChains.complex (Fin (m.len+1)) + map f := OAI.Thomason.NormalizedChains.complexMap f.toOrderHom + map_id _ := proof_complexMap_id_73 + map_comp f g := proof_complexMap_comp_74 f.toOrderHom g.toOrderHom + } + + +end OAI.Thomason.NormalizedChains +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def orientals : SimplexCategory ⥤ OAI.Thomason.OmegaCategory.{0} := + OAI.Thomason.NormalizedChains.simplexComplexes ⋙ OAI.Thomason.DirectedComplex.nuFunctor + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +noncomputable def ulift (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.{max u v} where + Cell := ULift.{v} C.Cell + source k x := ⟨C.source k x.down⟩ + target k x := ⟨C.target k x.down⟩ + source_source i j x := congrArg ULift.up (C.source_source i j x.down) + target_target i j x := congrArg ULift.up (C.target_target i j x.down) + source_target i j x := by + simpa only [apply_ite] using congrArg (ULift.up (α := C.Cell)) (C.source_target i j x.down) + target_source i j x := by + simpa only [apply_ite] using congrArg (ULift.up (α := C.Cell)) (C.target_source i j x.down) + comp k x y h := ⟨C.comp k x.down y.down (congrArg ULift.down h)⟩ + source_comp_le i k hik x y h := + congrArg ULift.up (C.source_comp_le i k hik x.down y.down (congrArg ULift.down h)) + target_comp_le i k hik x y h := + congrArg ULift.up (C.target_comp_le i k hik x.down y.down (congrArg ULift.down h)) + source_comp_gt i k hki x y h hs := + congrArg ULift.up (C.source_comp_gt i k hki x.down y.down + (congrArg ULift.down h) (congrArg ULift.down hs)) + target_comp_gt i k hki x y h ht := + congrArg ULift.up (C.target_comp_gt i k hki x.down y.down + (congrArg ULift.down h) (congrArg ULift.down ht)) + unit_left k x h := congrArg ULift.up (C.unit_left k x.down (congrArg ULift.down h)) + unit_right k x h := congrArg ULift.up (C.unit_right k x.down (congrArg ULift.down h)) + assoc k x y z hxy hyz hxy_z hx_yz := + congrArg ULift.up (C.assoc k x.down y.down z.down + (congrArg ULift.down hxy) (congrArg ULift.down hyz) + (congrArg ULift.down hxy_z) (congrArg ULift.down hx_yz)) + interchange k l hkl a b c d hab hcd hac hbd h₁ h₂ := + congrArg ULift.up (C.interchange k l hkl a.down b.down c.down d.down + (congrArg ULift.down hab) (congrArg ULift.down hcd) + (congrArg ULift.down hac) (congrArg ULift.down hbd) + (congrArg ULift.down h₁) (congrArg ULift.down h₂)) + finite_dimension x := by + obtain ⟨k, hk⟩ := C.finite_dimension x.down + exact ⟨k, congrArg ULift.up hk⟩ + +noncomputable def uliftUp (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor C (OAI.Thomason.OmegaCategory.ulift.{u,v} C) where + map := ULift.up + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + +noncomputable def uliftDown (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.ulift.{u,v} C) C where + map := ULift.down + map_source _ _ := rfl + map_target _ _ := rfl + map_comp _ _ _ _ _ := rfl + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def uliftFunctor : OAI.Thomason.OmegaCategory.{u} ⥤ OAI.Thomason.OmegaCategory.{max u v} where + obj := OAI.Thomason.OmegaCategory.ulift + map {C D} F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftDown C) F) (OAI.Thomason.OmegaCategory.uliftUp D) + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def raisedOrientals : SimplexCategory ⥤ OAI.Thomason.OmegaCategory.{u} := + OAI.Thomason.orientals ⋙ OAI.Thomason.OmegaCategory.uliftFunctor.{0,u} + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +structure Presentation where + Generator : Type u + dimension : Generator → ℕ + relations : (C : OAI.Thomason.OmegaCategory.{u}) → (Generator → C.Cell) → Prop + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +structure Interpretation (C : OAI.Thomason.OmegaCategory.{u}) where + map : P.Generator → C.Cell + bounded : ∀ g, C.source (P.dimension g) (map g) = map g + satisfies : P.relations C map + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory + + +inductive CellTerm (G : Type u) where + | gen : G → CellTerm G + | source : ℕ → CellTerm G → CellTerm G + | target : ℕ → CellTerm G → CellTerm G + | comp : ℕ → CellTerm G → CellTerm G → CellTerm G + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.CellTerm + + +noncomputable def composeOrLeft (C : OAI.Thomason.OmegaCategory.{v}) (k : ℕ) (x y : C.Cell) : C.Cell := by + classical + exact if h : C.target k x = C.source k y then C.comp k x y h else x + +noncomputable def eval {G : Type u} (C : OAI.Thomason.OmegaCategory.{v}) (f : G → C.Cell) : OAI.Thomason.OmegaCategory.CellTerm G → C.Cell + | gen g => f g + | source k x => C.source k (eval C f x) + | target k x => C.target k (eval C f x) + | comp k x y => OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft C k (eval C f x) (eval C f y) + + +end OAI.Thomason.OmegaCategory.CellTerm +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def Equiv (x y : OAI.Thomason.OmegaCategory.CellTerm P.Generator) : Prop := + ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), x.eval C I.map = y.eval C I.map + +inductive Valid : OAI.Thomason.OmegaCategory.CellTerm P.Generator → Prop + | gen (g) : Valid (.gen g) + | source (k x) : Valid x → Valid (.source k x) + | target (k x) : Valid x → Valid (.target k x) + | comp (k x y) : Valid x → Valid y → P.Equiv (.target k x) (.source k y) → Valid (.comp k x y) + +noncomputable abbrev ValidTerm := {x : OAI.Thomason.OmegaCategory.CellTerm P.Generator // P.Valid x} + +noncomputable instance termSetoid : Setoid P.ValidTerm := by + classical + have proof_refl_81 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} (x : OAI.Thomason.OmegaCategory.CellTerm P.Generator) : P.Equiv x x := fun _ _ => rfl + have proof_symm_82 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) : P.Equiv y x := fun C I => (h C I).symm + have proof_trans_83 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {z : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) (h' : P.Equiv y z) : P.Equiv x z := + fun C I => (h C I).trans (h' C I) + exact { + r x y := P.Equiv x.val y.val + iseqv := ⟨fun _ => proof_refl_81 _, fun h => (proof_symm_82 h), fun h h' => (proof_trans_83 h h')⟩ + } + +noncomputable abbrev Cells := Quotient P.termSetoid + +noncomputable def evaluate (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : P.Cells → C.Cell := + Quotient.lift (fun x : P.ValidTerm => x.val.eval C I.map) (fun _ _ h => h C I) + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory.CellTerm + + +noncomputable def dimension {G : Type u} (d : G → ℕ) : OAI.Thomason.OmegaCategory.CellTerm G → ℕ + | gen g => d g + | source k _ => k + | target k _ => k + | comp k x y => max (k+1) (max (dimension d x) (dimension d y)) + + +end OAI.Thomason.OmegaCategory.CellTerm +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def sourceTerm (k : ℕ) (x : P.ValidTerm) : P.ValidTerm := ⟨.source k x.val, OAI.Thomason.OmegaCategory.Presentation.Valid.source (P := P) k x.val x.property⟩ + +noncomputable def source (k : ℕ) : P.Cells → P.Cells := by + classical + have proof_source_84 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.source k x) (.source k y) := + fun C I => congrArg (C.source k) (h C I) + exact + Quotient.map (P.sourceTerm k) (fun _ _ h => (proof_source_84 k h)) + +noncomputable def targetTerm (k : ℕ) (x : P.ValidTerm) : P.ValidTerm := ⟨.target k x.val, OAI.Thomason.OmegaCategory.Presentation.Valid.target (P := P) k x.val x.property⟩ + +noncomputable def target (k : ℕ) : P.Cells → P.Cells := by + classical + have proof_target_85 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.target k x) (.target k y) := + fun C I => congrArg (C.target k) (h C I) + exact + Quotient.map (P.targetTerm k) (fun _ _ h => (proof_target_85 k h)) + +noncomputable def compTerm (k : ℕ) (x y : P.ValidTerm) : P.ValidTerm := by + classical + exact if h : P.Equiv (.target k x.val) (.source k y.val) then + ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ else x + +noncomputable def comp (k : ℕ) (x y : P.Cells) (_ : P.target k x = P.source k y) : P.Cells := by + classical + have proof_trans_83 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {z : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) (h' : P.Equiv y z) : P.Equiv x z := + fun C I => (h C I).trans (h' C I) + have proof_symm_82 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (h : P.Equiv x y) : P.Equiv y x := fun C I => (h C I).symm + have proof_target_85 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.target k x) (.target k y) := + fun C I => congrArg (C.target k) (h C I) + have proof_source_84 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (h : P.Equiv x y) : P.Equiv (.source k x) (.source k y) := + fun C I => congrArg (C.source k) (h C I) + have proof_composable_congr_87 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {x' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (hx : P.Equiv x x') (hy : P.Equiv y y') : + P.Equiv (.target k x) (.source k y) ↔ P.Equiv (.target k x') (.source k y') := + ⟨fun h => (proof_trans_83 + (proof_symm_82 (proof_target_85 k hx)) + (proof_trans_83 h (proof_source_84 k hy))), + fun h => (proof_trans_83 (proof_target_85 k hx) + (proof_trans_83 h + (proof_symm_82 (proof_source_84 k hy))))⟩ + have proof_comp_88 {P : OAI.Thomason.OmegaCategory.Presentation.{u}} {x : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {x' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} {y' : OAI.Thomason.OmegaCategory.CellTerm.{u} (OAI.Thomason.OmegaCategory.Presentation.Generator.{u} P)} (k : ℕ) (hx : P.Equiv x x') (hy : P.Equiv y y') : + P.Equiv (.comp k x y) (.comp k x' y') := by + intro C I + exact congrArg₂ (OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft C k) (hx C I) (hy C I) + have proof_compTerm_equiv_86 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) {x y x' y' : P.ValidTerm} + (hx : P.Equiv x.val x'.val) (hy : P.Equiv y.val y'.val) : + P.Equiv (P.compTerm k x y).val (P.compTerm k x' y').val := by + classical + have he := proof_composable_congr_87 k hx hy + by_cases h : P.Equiv (.target k x.val) (.source k y.val) + · simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h, dite_eq_left (he.mp h)] + exact proof_comp_88 k hx hy + · simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_right h, dite_eq_right (mt he.mpr h)] + exact hx + exact + Quotient.map₂ (P.compTerm k) (fun _ _ hx _ _ hy => (proof_compTerm_equiv_86 P k hx hy)) x y + +noncomputable abbrev category : OAI.Thomason.OmegaCategory.{u} := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_source_source_self_95 (C : OAI.Thomason.OmegaCategory.{u}) (k : ℕ) (x : C.Cell) : + C.source k (C.source k x) = C.source k x := by + simp [C.source_source] + have proof_source_target_self_96 (C : OAI.Thomason.OmegaCategory.{u}) (k : ℕ) (x : C.Cell) : + C.source k (C.target k x) = C.target k x := by + simp [C.source_target] + have proof_source_composable_97 (C : OAI.Thomason.OmegaCategory.{u}) {k i : ℕ} (hki : k < i) {x y : C.Cell} + (h : C.target k x = C.source k y) : + C.target k (C.source i x) = C.source k (C.source i y) := by + rw [C.target_source, ite_eq_left hki, C.source_source, min_eq_left (le_of_lt hki)] + exact h + have proof_source_fixed_upwards_98 (C : OAI.Thomason.OmegaCategory.{u}) {i j : ℕ} (hij : i ≤ j) {x : C.Cell} + (h : C.source i x = x) : C.source j x = x := by + rw [← h, C.source_source, min_eq_right hij] + have proof_eval_dimension_93 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x : OAI.Thomason.OmegaCategory.CellTerm P.Generator} (hx : P.Valid x) + (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : + C.source (x.dimension P.dimension) (x.eval C I.map) = x.eval C I.map := by + induction hx with + | gen g => exact I.bounded g + | source k x hx ih => exact (proof_source_source_self_95 C k + (OAI.Thomason.OmegaCategory.CellTerm.eval C (OAI.Thomason.OmegaCategory.Presentation.Interpretation.map I) x)) + | target k x hx ih => exact (proof_source_target_self_96 C k + (OAI.Thomason.OmegaCategory.CellTerm.eval C (OAI.Thomason.OmegaCategory.Presentation.Interpretation.map I) x)) + | comp k x y hx hy h ihx ihy => + have hm := h C I + change C.target k (x.eval C I.map) = C.source k (y.eval C I.map) at hm + simp only [OAI.Thomason.OmegaCategory.CellTerm.dimension, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm] + have hkn : k < max (k+1) (max (x.dimension P.dimension) (y.dimension P.dimension)) := by omega + rw [C.source_comp_gt _ k hkn _ _ hm (proof_source_composable_97 C hkn hm)] + congr 1 + · exact (proof_source_fixed_upwards_98 C (by omega) ihx) + · exact (proof_source_fixed_upwards_98 C (by omega) ihy) + exact { + Cell := P.Cells + source := P.source + target := P.target + comp := P.comp + source_source i j x := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, C.source_source] + target_target i j x := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, C.target_target] + source_target i j x := by + apply (proof_cells_ext_89 P) + intro C I + by_cases hij : i < j <;> simp [proof_evaluate_source_90, proof_evaluate_target_91, hij, C.source_target] + target_source i j x := by + apply (proof_cells_ext_89 P) + intro C I + by_cases hij : i < j <;> simp [proof_evaluate_source_90, proof_evaluate_target_91, hij, C.target_source] + source_comp_le i k hik x y h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.source_comp_le i k hik _ _ _ + target_comp_le i k hik x y h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.target_comp_le i k hik _ _ _ + source_comp_gt i k hki x y h hs := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.source_comp_gt i k hki _ _ _ _ + target_comp_gt i k hki x y h hs := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.target_comp_gt i k hki _ _ _ _ + unit_left k x h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_source_90, proof_evaluate_comp_92] + exact C.unit_left k _ _ + unit_right k x h := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_target_91, proof_evaluate_comp_92] + exact C.unit_right k _ _ + assoc k x y z hxy hyz hxy_z hx_yz := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_comp_92] + exact C.assoc k _ _ _ _ _ _ _ + interchange k l hkl a b c d hab hcd hac hbd hab_cd hac_bd := by + apply (proof_cells_ext_89 P) + intro C I + simp only [proof_evaluate_comp_92] + exact C.interchange k l hkl _ _ _ _ _ _ _ _ _ _ + finite_dimension x := by + induction x using Quotient.inductionOn with | h x => + refine ⟨x.val.dimension P.dimension, ?_⟩ + apply (proof_cells_ext_89 P) + intro C I + exact (proof_eval_dimension_93 P (Subtype.property x) C I) + } + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable abbrev colimitPresentation (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Presentation.{u} where + Generator := (j : J) × (F.obj j).Cell + dimension g := Classical.choose ((F.obj g.1).finite_dimension g.2) + relations C f := ∃ ι : ∀ j, OAI.Thomason.OmegaCategory.Functor (F.obj j) C, + (∀ j x, f ⟨j, x⟩ = (ι j).map x) ∧ + (∀ ⦃j j'⦄ (a : j ⟶ j'), OAI.Thomason.OmegaCategory.Functor.comp (F.map a) (ι j') = ι j) + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def generator (g : P.Generator) : P.Cells := Quotient.mk _ ⟨.gen g, .gen g⟩ + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable def colimitInclusion (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) (j : J) : + OAI.Thomason.OmegaCategory.Functor (F.obj j) (OAI.Thomason.OmegaCategory.colimitPresentation F).category := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_evaluate_generator_99 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) + (I : P.Interpretation C) (g : P.Generator) : P.evaluate C I (P.generator g) = I.map g := rfl + exact { + map x := (OAI.Thomason.OmegaCategory.colimitPresentation F).generator ⟨j, x⟩ + map_source k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_source_90, proof_evaluate_generator_99, hi] + exact (ι j).map_source k x + map_target k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_target_91, proof_evaluate_generator_99, hi] + exact (ι j).map_target k x + map_comp k x y h h' := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, _⟩ + simp only [proof_evaluate_comp_92, proof_evaluate_generator_99, hi] + exact (ι j).map_comp k x y h _ + } + +noncomputable def presentedCocone (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : Cocone F := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + exact { + pt := (OAI.Thomason.OmegaCategory.colimitPresentation F).category + ι := { + app := OAI.Thomason.OmegaCategory.colimitInclusion F + naturality := by + intro j j' a + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro C I + rcases I.satisfies with ⟨ι, hi, hw⟩ + change I.map ⟨j', (F.map a).map x⟩ = I.map ⟨j, x⟩ + rw [hi, hi] + exact congrArg (fun h : OAI.Thomason.OmegaCategory.Functor (F.obj j) C => h.map x) (hw a) } + } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory.Presentation +variable (P : Presentation.{u}) + +noncomputable def lift (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) : OAI.Thomason.OmegaCategory.Functor P.category C := by + classical + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + exact { + map := P.evaluate C I + map_source := (proof_evaluate_source_90 P C I) + map_target := (proof_evaluate_target_91 P C I) + map_comp k x y h _ := (proof_evaluate_comp_92 P C I k x y h) + } + + +end OAI.Thomason.OmegaCategory.Presentation +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory Limits +variable {J : Type u} [Category.{u} J] + +noncomputable def colimitInterpretation (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) (s : Cocone F) : + (OAI.Thomason.OmegaCategory.colimitPresentation F).Interpretation s.pt where + map g := (s.ι.app g.1).map g.2 + bounded g := by + exact ((s.ι.app g.1).map_source _ g.2).symm.trans + (congrArg (s.ι.app g.1).map (Classical.choose_spec ((F.obj g.1).finite_dimension g.2))) + satisfies := ⟨fun j => s.ι.app j, fun _ _ => rfl, fun {_ _} a => s.w a⟩ + +noncomputable def presentedCoconeIsColimit (F : J ⥤ OAI.Thomason.OmegaCategory.{u}) : + IsColimit (OAI.Thomason.OmegaCategory.presentedCocone F) := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + exact { + desc s := (OAI.Thomason.OmegaCategory.colimitPresentation F).lift s.pt (OAI.Thomason.OmegaCategory.colimitInterpretation F s) + fac s j := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + rfl + uniq s m hm := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.colimitPresentation F)) + intro ⟨j, x⟩ + exact congrArg (fun f : OAI.Thomason.OmegaCategory.Functor (F.obj j) s.pt => f.map x) (hm j) + } + +noncomputable instance hasColimits : HasColimitsOfSize.{u,u} OAI.Thomason.OmegaCategory.{u} where + has_colimits_of_shape := fun _ _ => { has_colimit := fun F => ⟨⟨OAI.Thomason.OmegaCategory.presentedCocone F, OAI.Thomason.OmegaCategory.presentedCoconeIsColimit F⟩⟩ } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable instance omegaHasSimplicialColimits : + Limits.HasColimitsOfSize.{0,u} OAI.Thomason.OmegaCategory.{u} := + Limits.hasColimitsOfSizeShrink.{0,u} OAI.Thomason.OmegaCategory.{u} + +noncomputable def categorification : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.{u} := + (uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtension OAI.Thomason.raisedOrientals.{u} + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonLeft : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.{u} := + (SSet.sd ⋙ SSet.sd) ⋙ OAI.Thomason.categorification + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetNerve (C : OAI.Thomason.OmegaCategory.{u}) : SSet.{u} where + obj m := OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.orientals.obj m.unop) C + map f := ↾fun x => OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map f.unop) x + map_id m := by + apply ConcreteCategory.hom_ext + intro x + change OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map (𝟙 m.unop)) x = x + rw [OAI.Thomason.orientals.map_id] + rfl + map_comp f g := by + apply ConcreteCategory.hom_ext + intro x + change OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map (g.unop ≫ f.unop)) x = + OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map g.unop) + (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.orientals.map f.unop) x) + rw [OAI.Thomason.orientals.map_comp] + rfl + +noncomputable def streetNerveMap {C D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) : + OAI.Thomason.streetNerve C ⟶ OAI.Thomason.streetNerve D where + app _ := ↾fun x => OAI.Thomason.OmegaCategory.Functor.comp x F + naturality _ _ _ := rfl + +noncomputable def streetNerveFunctor : OAI.Thomason.OmegaCategory.{u} ⥤ SSet.{u} where + obj := OAI.Thomason.streetNerve + map := OAI.Thomason.streetNerveMap + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonRight : OAI.Thomason.OmegaCategory.{u} ⥤ SSet.{u} := + OAI.Thomason.streetNerveFunctor ⋙ (SSet.ex ⋙ SSet.ex) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetYonedaEquiv (C : OAI.Thomason.OmegaCategory.{u}) (m : SimplexCategoryᵒᵖ) : + ((Presheaf.restrictedULiftYoneda.{0} OAI.Thomason.raisedOrientals).obj C).obj m ≃ + (OAI.Thomason.streetNerve C).obj m where + toFun F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftUp _) F.down + invFun F := ULift.up (OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.uliftDown _) F) + left_inv _ := rfl + right_inv _ := rfl + +noncomputable def streetYonedaIso : Presheaf.restrictedULiftYoneda.{0} OAI.Thomason.raisedOrientals.{u} ≅ + OAI.Thomason.streetNerveFunctor.{u} := + NatIso.ofComponents (fun C => + NatIso.ofComponents (fun m => (OAI.Thomason.streetYonedaEquiv C m).toIso) (by intros; rfl)) + (by intros; rfl) + +noncomputable def categorificationAdjunction : OAI.Thomason.categorification.{u} ⊣ OAI.Thomason.streetNerveFunctor.{u} := + (Presheaf.uliftYonedaAdjunction.{0} + ((uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtension OAI.Thomason.raisedOrientals.{u}) + ((uliftYoneda.{u} : SimplexCategory ⥤ (SimplexCategoryᵒᵖ ⥤ Type u)).leftKanExtensionUnit OAI.Thomason.raisedOrientals.{u})).ofNatIsoRight OAI.Thomason.streetYonedaIso + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonAdjunction : OAI.Thomason.thomasonLeft.{u} ⊣ OAI.Thomason.thomasonRight.{u} := + (SSet.sdExAdjunction.comp SSet.sdExAdjunction).comp OAI.Thomason.categorificationAdjunction + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory + + +noncomputable abbrev truncationPresentation (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.Presentation.{u} where + Generator := C.Cell + dimension _ := n + relations D f := D.IsTruncated n ∧ ∃ F : OAI.Thomason.OmegaCategory.Functor C D, f = F.map + +noncomputable def truncationUnit (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : + OAI.Thomason.OmegaCategory.Functor C (OAI.Thomason.OmegaCategory.truncationPresentation n C).category := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_target_91 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.target k x) = C.target k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_evaluate_composable_94 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + C.target k (P.evaluate C I x) = C.source k (P.evaluate C I y) := by + rw [← proof_evaluate_target_91, ← proof_evaluate_source_90, h] + have proof_evaluate_comp_92 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) + (x y : P.Cells) (h : P.target k x = P.source k y) : + P.evaluate C I (P.comp k x y h) = + C.comp k (P.evaluate C I x) (P.evaluate C I y) (proof_evaluate_composable_94 P C I k x y h) := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + have hm : P.Equiv (.target k x.val) (.source k y.val) := Quotient.exact h + change (P.compTerm k x y).val.eval C I.map = _ + have hm' : C.target k (x.val.eval C I.map) = C.source k (y.val.eval C I.map) := hm C I + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left hm, OAI.Thomason.OmegaCategory.CellTerm.eval, OAI.Thomason.OmegaCategory.CellTerm.composeOrLeft, dite_eq_left hm'] + rfl + have proof_evaluate_generator_99 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) + (I : P.Interpretation C) (g : P.Generator) : P.evaluate C I (P.generator g) = I.map g := rfl + exact { + map := (OAI.Thomason.OmegaCategory.truncationPresentation n C).generator + map_source k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_source_90, proof_evaluate_generator_99, hF] + exact F.map_source k x + map_target k x := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_target_91, proof_evaluate_generator_99, hF] + exact F.map_target k x + map_comp k x y h h' := by + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rcases I.satisfies with ⟨_, F, hF⟩ + simp only [proof_evaluate_comp_92, proof_evaluate_generator_99, hF] + exact F.map_comp k x y h _ + } + +noncomputable def truncation (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : OAI.Thomason.OmegaCategory.NCategory.{u} n := by + classical + have proof_cells_ext_89 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {x y : P.Cells} + (h : ∀ (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C), P.evaluate C I x = P.evaluate C I y) : x = y := by + induction x using Quotient.inductionOn with | h x => + induction y using Quotient.inductionOn with | h y => + exact Quotient.sound h + have proof_evaluate_source_90 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (C : OAI.Thomason.OmegaCategory.{u}) (I : P.Interpretation C) (k : ℕ) (x : P.Cells) : + P.evaluate C I (P.source k x) = C.source k (P.evaluate C I x) := by + induction x using Quotient.inductionOn + rfl + have proof_truncation_isTruncated_103 (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) : + (OAI.Thomason.OmegaCategory.truncationPresentation n C).category.IsTruncated n := by + intro x + apply (proof_cells_ext_89 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro D I + rw [proof_evaluate_source_90] + exact I.satisfies.1 _ + exact + ⟨(OAI.Thomason.OmegaCategory.truncationPresentation n C).category, proof_truncation_isTruncated_103 n C⟩ + +noncomputable def truncationLift {n : ℕ} {C : OAI.Thomason.OmegaCategory.{u}} (D : OAI.Thomason.OmegaCategory.NCategory.{u} n) + (F : OAI.Thomason.OmegaCategory.Functor C D.val) : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D.val := + (OAI.Thomason.OmegaCategory.truncationPresentation n C).lift D.val { + map := F.map + bounded := fun x => D.property (F.map x) + satisfies := ⟨D.property, F, rfl⟩ } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def truncationFunctor (n : ℕ) : OAI.Thomason.OmegaCategory.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact { + obj := OAI.Thomason.OmegaCategory.truncation n + map {C D} F := OAI.Thomason.OmegaCategory.truncationLift (OAI.Thomason.OmegaCategory.truncation n D) (OAI.Thomason.OmegaCategory.Functor.comp F (OAI.Thomason.OmegaCategory.truncationUnit n D)) + map_id C := by + apply proof_truncation_functor_ext_104 + rfl + map_comp F G := by + apply proof_truncation_functor_ext_104 + rfl + } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def categorificationFinite (n : ℕ) : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := + OAI.Thomason.categorification ⋙ OAI.Thomason.OmegaCategory.truncationFunctor n + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonLeftFinite (n : ℕ) : SSet.{u} ⥤ OAI.Thomason.OmegaCategory.NCategory.{u} n := + (SSet.sd ⋙ SSet.sd) ⋙ OAI.Thomason.categorificationFinite n + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def streetNerveFinite (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ SSet.{u} where + obj C := OAI.Thomason.streetNerve C.val + map := OAI.Thomason.streetNerveMap + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonRightFinite (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ SSet.{u} := + OAI.Thomason.streetNerveFinite n ⋙ (SSet.ex ⋙ SSet.ex) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.OmegaCategory +open CategoryTheory + +noncomputable def nCategoryInclusion (n : ℕ) : OAI.Thomason.OmegaCategory.NCategory.{u} n ⥤ OAI.Thomason.OmegaCategory.{u} where + obj C := C.val + map F := F + +noncomputable def truncationHomEquiv (n : ℕ) (C : OAI.Thomason.OmegaCategory.{u}) (D : OAI.Thomason.OmegaCategory.NCategory.{u} n) : + ((OAI.Thomason.OmegaCategory.truncationFunctor n).obj C ⟶ D) ≃ (C ⟶ (OAI.Thomason.OmegaCategory.nCategoryInclusion n).obj D) := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact { + toFun F := OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F + invFun := OAI.Thomason.OmegaCategory.truncationLift D + left_inv F := by + apply proof_truncation_functor_ext_104 + rfl + right_inv _ := rfl + } + +noncomputable def truncationAdjunction (n : ℕ) : OAI.Thomason.OmegaCategory.truncationFunctor.{u} n ⊣ OAI.Thomason.OmegaCategory.nCategoryInclusion n := by + classical + have proof_mk_comp_101 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) (k : ℕ) (x y : P.ValidTerm) + (h : P.Equiv (.target k x.val) (.source k y.val)) + (h' : P.target k (Quotient.mk _ x) = P.source k (Quotient.mk _ y)) : + P.comp k (Quotient.mk _ x) (Quotient.mk _ y) h' = + Quotient.mk _ ⟨.comp k x.val y.val, OAI.Thomason.OmegaCategory.Presentation.Valid.comp (P := P) k x.val y.val x.property y.property h⟩ := by + change Quotient.mk _ (P.compTerm k x y) = _ + simp only [OAI.Thomason.OmegaCategory.Presentation.compTerm, dite_eq_left h] + have proof_map_composable_102 {C : OAI.Thomason.OmegaCategory.{u}} {D : OAI.Thomason.OmegaCategory.{u}} (F : OAI.Thomason.OmegaCategory.Functor C D) {k : ℕ} {x y : C.Cell} + (h : C.target k x = C.source k y) : + D.target k (F.map x) = D.source k (F.map y) := by + rw [← F.map_target, ← F.map_source, h] + have proof_functor_ext_100 (P : OAI.Thomason.OmegaCategory.Presentation.{u}) {C : OAI.Thomason.OmegaCategory.{u}} {F G : OAI.Thomason.OmegaCategory.Functor P.category C} + (h : ∀ g, F.map (P.generator g) = G.map (P.generator g)) : F = G := by + apply OAI.Thomason.OmegaCategory.Functor.ext + funext x + induction x using Quotient.inductionOn with | h x => + rcases x with ⟨x, hx⟩ + induction hx with + | gen g => exact h g + | source k x hx ih => + change F.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.source k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_source, G.map_source, ih] + | target k x hx ih => + change F.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) = + G.map (P.category.target k (Quotient.mk _ ⟨x, hx⟩)) + rw [F.map_target, G.map_target, ih] + | comp k x y hx hy hm ihx ihy => + have hc : P.category.target k (Quotient.mk _ ⟨x, hx⟩) = + P.category.source k (Quotient.mk _ ⟨y, hy⟩) := Quotient.sound hm + rw [← (proof_mk_comp_101 P k ⟨x, hx⟩ ⟨y, hy⟩ hm hc)] + change F.map (P.category.comp k _ _ hc) = G.map (P.category.comp k _ _ hc) + rw [F.map_comp k _ _ hc (proof_map_composable_102 F hc), G.map_comp k _ _ hc (proof_map_composable_102 G hc)] + congr 1 + have proof_truncation_functor_ext_104 {n : ℕ} {C D : OAI.Thomason.OmegaCategory.{u}} + {F G : OAI.Thomason.OmegaCategory.Functor (OAI.Thomason.OmegaCategory.truncation n C).val D} + (h : OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) F = OAI.Thomason.OmegaCategory.Functor.comp (OAI.Thomason.OmegaCategory.truncationUnit n C) G) : F = G := by + apply (proof_functor_ext_100 (OAI.Thomason.OmegaCategory.truncationPresentation n C)) + intro x + exact congrArg (fun H : OAI.Thomason.OmegaCategory.Functor C D => H.map x) h + exact + Adjunction.mkOfHomEquiv { + homEquiv := OAI.Thomason.OmegaCategory.truncationHomEquiv n + homEquiv_naturality_left_symm := by + intro C' C D F G + apply proof_truncation_functor_ext_104 + rfl + homEquiv_naturality_right := by + intro C D D' F G + rfl } + + +end OAI.Thomason.OmegaCategory +end + +section +namespace OAI.Thomason +open CategoryTheory Opposite + +noncomputable def categorificationFiniteAdjunction (n : ℕ) : + OAI.Thomason.categorificationFinite.{u} n ⊣ OAI.Thomason.streetNerveFinite.{u} n := + OAI.Thomason.categorificationAdjunction.comp (OAI.Thomason.OmegaCategory.truncationAdjunction n) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonFiniteAdjunction (n : ℕ) : + OAI.Thomason.thomasonLeftFinite.{u} n ⊣ OAI.Thomason.thomasonRightFinite.{u} n := + (SSet.sdExAdjunction.comp SSet.sdExAdjunction).comp (OAI.Thomason.categorificationFiniteAdjunction n) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason.WeakHomotopy +open scoped Topology Topology.Homotopy +variable {X : Type u} {Y : Type v} [TopologicalSpace X] [TopologicalSpace Y] + +noncomputable def loopMap (N : Type w) (f : C(X, Y)) (x : X) : GenLoop N X x → GenLoop N Y (f x) := + fun p => ⟨f.comp p.val, fun y hy => congrArg f (p.property y hy)⟩ + +noncomputable def groupMap (N : Type w) (f : C(X, Y)) (x : X) : + HomotopyGroup N X x → HomotopyGroup N Y (f x) := by + classical + have proof_loopMap_homotopic_105 {X : Type u} {Y : Type v} [instLocal2 : TopologicalSpace.{u} X] [instLocal3 : TopologicalSpace.{v} Y] (N : Type w) (f : C(X, Y)) (x : X) + {p q : GenLoop N X x} (h : GenLoop.Homotopic p q) : + GenLoop.Homotopic (OAI.Thomason.WeakHomotopy.loopMap N f x p) (OAI.Thomason.WeakHomotopy.loopMap N f x q) := + h.comp_continuousMap f + exact + Quotient.map (OAI.Thomason.WeakHomotopy.loopMap N f x) (fun _ _ h => proof_loopMap_homotopic_105 N f x h) + +noncomputable def componentsMap (f : C(X, Y)) : ZerothHomotopy X → ZerothHomotopy Y := + ZerothHomotopy.lift (fun x => ZerothHomotopy.mk (f x)) + (fun _ _ p => ZerothHomotopy.sound (p.map f.continuous)) + +noncomputable def Equivalence (f : C(X, Y)) : Prop := + Function.Bijective (OAI.Thomason.WeakHomotopy.componentsMap f) ∧ + ∀ (n : ℕ) (x : X), Function.Bijective (OAI.Thomason.WeakHomotopy.groupMap (Fin (n+1)) f x) + + +end OAI.Thomason.WeakHomotopy +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def simplicialWeakEquivalences : MorphismProperty SSet.{u} := + fun _ _ f => OAI.Thomason.WeakHomotopy.Equivalence (SSet.toTop.map f).hom + +noncomputable def simplicialFibrations : MorphismProperty SSet.{u} := (SSet.modelCategoryQuillen.J).rlp + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory Limits HomotopicalAlgebra + +structure KanQuillenModel where + model : ModelCategory SSet.{u} + weak_eq : model.categoryWithWeakEquivalences.weakEquivalences = OAI.Thomason.simplicialWeakEquivalences + fib_eq : model.categoryWithFibrations.fibrations = OAI.Thomason.simplicialFibrations + cof_eq : model.categoryWithCofibrations.cofibrations = MorphismProperty.monomorphisms SSet + +noncomputable def LeftProperFor {C : Type v} [Category.{u} C] + (W Cof : MorphismProperty C) : Prop := + ∀ {A B X Y : C} (i : A ⟶ B) (f : A ⟶ X) (g : B ⟶ Y) (j : X ⟶ Y), + IsPushout i f g j → Cof i → W f → W g + +noncomputable def RightProperFor {C : Type v} [Category.{u} C] + (W Fib : MorphismProperty C) : Prop := + ∀ {A B X Y : C} (f : A ⟶ B) (g : A ⟶ X) (p : B ⟶ Y) (q : X ⟶ Y), + IsPullback f g p q → Fib q → W p → W g + +noncomputable def FibrantFor {C : Type v} [Category.{u} C] (Fib : MorphismProperty C) (Y : C) : Prop := + ∃ (T : C) (_ : IsTerminal T) (p : Y ⟶ T), Fib p + +noncomputable def boundaryImages {C : Type v} [Category.{u} C] (L : SSet.{u} ⥤ C) : MorphismProperty C := + .ofHoms (fun n : ℕ => L.map (SSet.boundary n).ι) + +noncomputable def hornImages {C : Type v} [Category.{u} C] (L : SSet.{u} ⥤ C) : MorphismProperty C := + ⨆ n : ℕ, .ofHoms (fun i : Fin (n+2) => L.map (SSet.horn (n+1) i).ι) + +structure ExactModelEndpoint {C : Type v} [Category.{u} C] + (L : SSet.{u} ⥤ C) (R : C ⥤ SSet.{u}) (adj : L ⊣ R) where + model : ModelCategory C + weak_eq : model.categoryWithWeakEquivalences.weakEquivalences = + OAI.Thomason.simplicialWeakEquivalences.inverseImage R + fib_eq : model.categoryWithFibrations.fibrations = OAI.Thomason.simplicialFibrations.inverseImage R + cof_eq : model.categoryWithCofibrations.cofibrations = + ((OAI.Thomason.simplicialFibrations.inverseImage R) ⊓ (OAI.Thomason.simplicialWeakEquivalences.inverseImage R)).llp + generating_cofibrations : (OAI.Thomason.boundaryImages L).rlp = + model.categoryWithFibrations.fibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences + generating_trivial_cofibrations : (OAI.Thomason.hornImages L).rlp = model.categoryWithFibrations.fibrations + weak_factorization_one : MorphismProperty.IsWeakFactorizationSystem + (model.categoryWithCofibrations.cofibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences) + model.categoryWithFibrations.fibrations + weak_factorization_two : MorphismProperty.IsWeakFactorizationSystem + model.categoryWithCofibrations.cofibrations + (model.categoryWithFibrations.fibrations ⊓ model.categoryWithWeakEquivalences.weakEquivalences) + complete : HasLimitsOfSize.{u,u} C + cocomplete : HasColimitsOfSize.{u,u} C + locallyPresentable : IsLocallyPresentable.{u} C + leftProper : OAI.Thomason.LeftProperFor model.categoryWithWeakEquivalences.weakEquivalences + model.categoryWithCofibrations.cofibrations + rightProper : OAI.Thomason.RightProperFor model.categoryWithWeakEquivalences.weakEquivalences + model.categoryWithFibrations.fibrations + leftQuillen : ∀ {K K' : SSet.{u}} (f : K ⟶ K'), Mono f → + model.categoryWithCofibrations.cofibrations (L.map f) ∧ + (OAI.Thomason.simplicialWeakEquivalences f → model.categoryWithWeakEquivalences.weakEquivalences (L.map f)) + quillenEquivalence : ∀ (K : SSet.{u}) (Y : C), + OAI.Thomason.FibrantFor model.categoryWithFibrations.fibrations Y → + ∀ f : L.obj K ⟶ Y, + model.categoryWithWeakEquivalences.weakEquivalences f ↔ + OAI.Thomason.simplicialWeakEquivalences (adj.homEquiv K Y f) + +noncomputable def FullMain : Prop := + Nonempty OAI.Thomason.KanQuillenModel.{u} ∧ + Nonempty (OAI.Thomason.ExactModelEndpoint OAI.Thomason.thomasonLeft.{u} OAI.Thomason.thomasonRight OAI.Thomason.thomasonAdjunction) ∧ + ∀ n : ℕ, 1 ≤ n → + Nonempty (OAI.Thomason.ExactModelEndpoint (OAI.Thomason.thomasonLeftFinite.{u} n) (OAI.Thomason.thomasonRightFinite n) + (OAI.Thomason.thomasonFiniteAdjunction n)) + + +end OAI.Thomason +end + +section +namespace OAI.Thomason +open CategoryTheory + +noncomputable def thomasonWeakEquivalences : MorphismProperty OAI.Thomason.OmegaCategory.{u} := + OAI.Thomason.simplicialWeakEquivalences.inverseImage OAI.Thomason.thomasonRight + +noncomputable def thomasonWeakEquivalencesFinite (n : ℕ) : + MorphismProperty (OAI.Thomason.OmegaCategory.NCategory.{u} n) := + OAI.Thomason.simplicialWeakEquivalences.inverseImage (OAI.Thomason.thomasonRightFinite n) + + +end OAI.Thomason +end + +section +namespace OAI + + +theorem Thomason.main : OAI.Thomason.FullMain.{u} := by + sorry + +theorem Thomason.nerveDetection_allDimensions : + OAI.Thomason.thomasonWeakEquivalences.{u} = + OAI.Thomason.simplicialWeakEquivalences.inverseImage OAI.Thomason.streetNerveFunctor ∧ + ∀ n : ℕ, OAI.Thomason.thomasonWeakEquivalencesFinite.{u} n = + OAI.Thomason.simplicialWeakEquivalences.inverseImage (OAI.Thomason.streetNerveFinite n) := by + sorry + +end OAI +end + +end diff --git a/tasks/thomason-model-structures/tests/grade.py b/tasks/thomason-model-structures/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thomason-model-structures/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thomason-model-structures/tests/task.json b/tasks/thomason-model-structures/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..68289caccdcd42cea545c25b6e1913428baffbfa --- /dev/null +++ b/tasks/thomason-model-structures/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "ThomasonModelStructures", + "comparator": { + "theorem_names": [ + "OAI.Thomason.main", + "OAI.Thomason.nerveDetection_allDimensions" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13387 +} \ No newline at end of file diff --git a/tasks/thomason-model-structures/tests/test.sh b/tasks/thomason-model-structures/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thomason-model-structures/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thompson-nonamenability/environment/Dockerfile b/tasks/thompson-nonamenability/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thompson-nonamenability/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thompson-nonamenability/environment/fetch_mathlib.sh b/tasks/thompson-nonamenability/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thompson-nonamenability/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thompson-nonamenability/environment/lake-manifest.json b/tasks/thompson-nonamenability/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thompson-nonamenability/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thompson-nonamenability/environment/lakefile.lean b/tasks/thompson-nonamenability/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thompson-nonamenability/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thompson-nonamenability/environment/lean_setup.sh b/tasks/thompson-nonamenability/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thompson-nonamenability/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thompson-nonamenability/environment/pack_submission.py b/tasks/thompson-nonamenability/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thompson-nonamenability/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thompson-nonamenability/instruction.md b/tasks/thompson-nonamenability/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c6a1c111cf5656e4956b722a2c6bacf9cb93b09f --- /dev/null +++ b/tasks/thompson-nonamenability/instruction.md @@ -0,0 +1,140 @@ +# openai/math challenge `ThompsonNonamenability` (family 248) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 248 of the release, *Thompson's group $F$ is nonamenable* +(Group theory). The family as a whole: Proves that Thompson's group $F$, the group of dyadic piecewise linear homeomorphisms of the interval, is nonamenable, resolving its longstanding amenability problem. + +The challenge is `ThompsonNonamenability`, also at `/opt/openai-math/challenges/ThompsonNonamenability.lean`: + +```lean +import Mathlib.Topology.Homeomorph.Lemmas +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Analysis.Normed.Lp.lpSpace +import Mathlib.Analysis.Normed.Operator.Basic + +namespace OAI + +noncomputable section + +open scoped ENNReal + +universe uG + +namespace ThompsonNonamenability + +abbrev UnitInterval := Set.Icc (0 : ℝ) 1 + +def unitIntervalZero : UnitInterval := ⟨0, le_rfl, zero_le_one⟩ +def unitIntervalOne : UnitInterval := ⟨1, zero_le_one, le_rfl⟩ + +structure IntervalHomeomorph where + toHomeomorph : UnitInterval ≃ₜ UnitInterval + +namespace IntervalHomeomorph + +instance : CoeFun IntervalHomeomorph (fun _ => UnitInterval → UnitInterval) := + ⟨fun f => f.toHomeomorph⟩ + +end IntervalHomeomorph + +def IsDyadic (x : ℝ) : Prop := + ∃ (k : ℤ) (n : ℕ), x = (k : ℝ) / (2 : ℝ) ^ n + +structure DyadicPLWitness (f : IntervalHomeomorph) where + pieceCount : ℕ + positive : 0 < pieceCount + knots : Fin (pieceCount + 1) → UnitInterval + strictMono_knots : StrictMono knots + first : knots 0 = unitIntervalZero + last : knots (Fin.last pieceCount) = unitIntervalOne + dyadic : ∀ i, IsDyadic (knots i : ℝ) + cover : ∀ x : UnitInterval, ∃ i : Fin pieceCount, + knots i.castSucc ≤ x ∧ x ≤ knots i.succ + exponent : Fin pieceCount → ℤ + affine : ∀ (i : Fin pieceCount) (x : UnitInterval), + knots i.castSucc ≤ x → x ≤ knots i.succ → + (f x : ℝ) = (f (knots i.castSucc) : ℝ) + + (2 : ℝ) ^ exponent i * ((x : ℝ) - (knots i.castSucc : ℝ)) + +def HasDyadicPLPieces (f : IntervalHomeomorph) : Prop := Nonempty (DyadicPLWitness f) + +def F := {f : IntervalHomeomorph // StrictMono f ∧ HasDyadicPLPieces f} + +abbrev BoundedReal (G : Type uG) := lp (fun _ : G => ℝ) ∞ + +variable {G : Type uG} [Group G] + +def leftPull (h : G) : BoundedReal G →ₗ[ℝ] BoundedReal G where + toFun f := ⟨fun g => f (h * g), memℓp_infty ⟨‖f‖, by + rintro y ⟨g, rfl⟩ + exact lp.norm_apply_le_norm ENNReal.top_ne_zero f (h * g)⟩⟩ + map_add' f g := by + apply lp.ext + funext x + rfl + map_smul' r f := by + apply lp.ext + funext x + rfl + +structure InvariantMean (G : Type uG) [Group G] where + toLinearMap : BoundedReal G →ₗ[ℝ] ℝ + positive : ∀ f : BoundedReal G, (∀ g, 0 ≤ f g) → 0 ≤ toLinearMap f + normalized : toLinearMap 1 = 1 + left_invariant : ∀ (h : G) (f : BoundedReal G), + toLinearMap (leftPull h f) = toLinearMap f + +theorem thompson_F_nonamenable_composition : + ∃ group : Group F, letI := group; + (∀ (h g : F) (x : UnitInterval), + (h * g).val.toHomeomorph x = h.val.toHomeomorph (g.val.toHomeomorph x)) ∧ + ¬ Nonempty (InvariantMean F) := by + sorry + +end ThompsonNonamenability + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThompsonNonamenability.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThompsonNonamenability.thompson_F_nonamenable_composition` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thompson-nonamenability/solution/closure.txt b/tasks/thompson-nonamenability/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..ae9ad1b2082d11aa16a424f31af4470264619c06 --- /dev/null +++ b/tasks/thompson-nonamenability/solution/closure.txt @@ -0,0 +1,68 @@ +OAI.GroupTheory.Thompson.AffineGridArithmetic +OAI.GroupTheory.Thompson.AffinePiece +OAI.GroupTheory.Thompson.AffineTransport +OAI.GroupTheory.Thompson.AnalyticConstruction +OAI.GroupTheory.Thompson.AnalyticCorrection +OAI.GroupTheory.Thompson.AnalyticCurve +OAI.GroupTheory.Thompson.AnalyticCurveBounds +OAI.GroupTheory.Thompson.AnalyticCurveRotation +OAI.GroupTheory.Thompson.AnalyticCurveSeparation +OAI.GroupTheory.Thompson.AnalyticCutoffs +OAI.GroupTheory.Thompson.AnalyticLpCalculus +OAI.GroupTheory.Thompson.AnalyticModel +OAI.GroupTheory.Thompson.AnalyticNormalization +OAI.GroupTheory.Thompson.AnalyticOscillator +OAI.GroupTheory.Thompson.AnalyticPlaneOscillator +OAI.GroupTheory.Thompson.AnalyticRotation +OAI.GroupTheory.Thompson.AnalyticScalarDerivatives +OAI.GroupTheory.Thompson.AnalyticScalarProfiles +OAI.GroupTheory.Thompson.AnalyticSeparation +OAI.GroupTheory.Thompson.AnalyticSinc +OAI.GroupTheory.Thompson.AnalyticTube +OAI.GroupTheory.Thompson.BasicInterval +OAI.GroupTheory.Thompson.BasicIntervalNesting +OAI.GroupTheory.Thompson.BasicPartition +OAI.GroupTheory.Thompson.BoundaryAlgebra +OAI.GroupTheory.Thompson.CorrectionData +OAI.GroupTheory.Thompson.CorrectionLocal +OAI.GroupTheory.Thompson.CorrectionNonzero +OAI.GroupTheory.Thompson.CorrelationVariance +OAI.GroupTheory.Thompson.DisplacementEstimate +OAI.GroupTheory.Thompson.DyadicArithmetic +OAI.GroupTheory.Thompson.DyadicGapChain +OAI.GroupTheory.Thompson.DyadicGapPartition +OAI.GroupTheory.Thompson.DyadicImages +OAI.GroupTheory.Thompson.FiniteAverage +OAI.GroupTheory.Thompson.FiniteBoundary +OAI.GroupTheory.Thompson.FiniteCoarea +OAI.GroupTheory.Thompson.FiniteCorrelationBoundary +OAI.GroupTheory.Thompson.FiniteLevels +OAI.GroupTheory.Thompson.GlobalColors +OAI.GroupTheory.Thompson.HilbertAverage +OAI.GroupTheory.Thompson.IntervalCharts +OAI.GroupTheory.Thompson.IntervalFamily +OAI.GroupTheory.Thompson.IntervalHomeomorph +OAI.GroupTheory.Thompson.InvariantMean +OAI.GroupTheory.Thompson.Main +OAI.GroupTheory.Thompson.MeanApproximation +OAI.GroupTheory.Thompson.MeanToFolner +OAI.GroupTheory.Thompson.Model +OAI.GroupTheory.Thompson.OrderedChainKnots +OAI.GroupTheory.Thompson.OrderedPLInterpolation +OAI.GroupTheory.Thompson.PLRefinement +OAI.GroupTheory.Thompson.PartitionColorFamily +OAI.GroupTheory.Thompson.ProbabilityDefects +OAI.GroupTheory.Thompson.RecursiveColoring +OAI.GroupTheory.Thompson.RestrictionCovariance +OAI.GroupTheory.Thompson.SortedSubdivision +OAI.GroupTheory.Thompson.StandardCharacterization +OAI.GroupTheory.Thompson.StandardF +OAI.GroupTheory.Thompson.StandardPL +OAI.GroupTheory.Thompson.TransportFamily +OAI.GroupTheory.Thompson.TubeComparison +OAI.GroupTheory.Thompson.TubeNearest +OAI.GroupTheory.Thompson.TubeRegularCurve +OAI.GroupTheory.Thompson.TubeTangent +OAI.GroupTheory.Thompson.UniformPL +OAI.GroupTheory.Thompson.UniformPartition +OAI.GroupTheory.Thompson.UnitBall diff --git a/tasks/thompson-nonamenability/solution/reference.py b/tasks/thompson-nonamenability/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thompson-nonamenability/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thompson-nonamenability/solution/solve.sh b/tasks/thompson-nonamenability/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1898a49217acaec0a5fd06436490c4744dccd641 --- /dev/null +++ b/tasks/thompson-nonamenability/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThompsonNonamenability, i.e. module OAI.GroupTheory.Thompson.Main and the +# 68 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.Thompson.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThompsonNonamenability" diff --git a/tasks/thompson-nonamenability/task.toml b/tasks/thompson-nonamenability/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3efeba56d4368672e7ac64a711459bf816cfe22b --- /dev/null +++ b/tasks/thompson-nonamenability/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thompson-nonamenability" +version = "1.0.0" +description = "Prove ThompsonNonamenability (openai/math family 248: Thompson's group $F$ is nonamenable) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThompsonNonamenability.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThompsonNonamenability" +family = "248" +family_title = "Thompson's group $F$ is nonamenable" +subject = "Group theory" +theorems = ["OAI.ThompsonNonamenability.thompson_F_nonamenable_composition"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.Thompson.Main" +reference_modules = 68 +reference_lean_bytes = 372798 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 146 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12035 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thompson-nonamenability/tests/Challenge.lean b/tasks/thompson-nonamenability/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7a364bdc7a964d0ae8665a0f97517e878c9109f6 --- /dev/null +++ b/tasks/thompson-nonamenability/tests/Challenge.lean @@ -0,0 +1,89 @@ +import Mathlib.Topology.Homeomorph.Lemmas +import Mathlib.Topology.Instances.Real.Lemmas +import Mathlib.Analysis.Normed.Lp.lpSpace +import Mathlib.Analysis.Normed.Operator.Basic + +namespace OAI + +noncomputable section + +open scoped ENNReal + +universe uG + +namespace ThompsonNonamenability + +abbrev UnitInterval := Set.Icc (0 : ℝ) 1 + +def unitIntervalZero : UnitInterval := ⟨0, le_rfl, zero_le_one⟩ +def unitIntervalOne : UnitInterval := ⟨1, zero_le_one, le_rfl⟩ + +structure IntervalHomeomorph where + toHomeomorph : UnitInterval ≃ₜ UnitInterval + +namespace IntervalHomeomorph + +instance : CoeFun IntervalHomeomorph (fun _ => UnitInterval → UnitInterval) := + ⟨fun f => f.toHomeomorph⟩ + +end IntervalHomeomorph + +def IsDyadic (x : ℝ) : Prop := + ∃ (k : ℤ) (n : ℕ), x = (k : ℝ) / (2 : ℝ) ^ n + +structure DyadicPLWitness (f : IntervalHomeomorph) where + pieceCount : ℕ + positive : 0 < pieceCount + knots : Fin (pieceCount + 1) → UnitInterval + strictMono_knots : StrictMono knots + first : knots 0 = unitIntervalZero + last : knots (Fin.last pieceCount) = unitIntervalOne + dyadic : ∀ i, IsDyadic (knots i : ℝ) + cover : ∀ x : UnitInterval, ∃ i : Fin pieceCount, + knots i.castSucc ≤ x ∧ x ≤ knots i.succ + exponent : Fin pieceCount → ℤ + affine : ∀ (i : Fin pieceCount) (x : UnitInterval), + knots i.castSucc ≤ x → x ≤ knots i.succ → + (f x : ℝ) = (f (knots i.castSucc) : ℝ) + + (2 : ℝ) ^ exponent i * ((x : ℝ) - (knots i.castSucc : ℝ)) + +def HasDyadicPLPieces (f : IntervalHomeomorph) : Prop := Nonempty (DyadicPLWitness f) + +def F := {f : IntervalHomeomorph // StrictMono f ∧ HasDyadicPLPieces f} + +abbrev BoundedReal (G : Type uG) := lp (fun _ : G => ℝ) ∞ + +variable {G : Type uG} [Group G] + +def leftPull (h : G) : BoundedReal G →ₗ[ℝ] BoundedReal G where + toFun f := ⟨fun g => f (h * g), memℓp_infty ⟨‖f‖, by + rintro y ⟨g, rfl⟩ + exact lp.norm_apply_le_norm ENNReal.top_ne_zero f (h * g)⟩⟩ + map_add' f g := by + apply lp.ext + funext x + rfl + map_smul' r f := by + apply lp.ext + funext x + rfl + +structure InvariantMean (G : Type uG) [Group G] where + toLinearMap : BoundedReal G →ₗ[ℝ] ℝ + positive : ∀ f : BoundedReal G, (∀ g, 0 ≤ f g) → 0 ≤ toLinearMap f + normalized : toLinearMap 1 = 1 + left_invariant : ∀ (h : G) (f : BoundedReal G), + toLinearMap (leftPull h f) = toLinearMap f + +theorem thompson_F_nonamenable_composition : + ∃ group : Group F, letI := group; + (∀ (h g : F) (x : UnitInterval), + (h * g).val.toHomeomorph x = h.val.toHomeomorph (g.val.toHomeomorph x)) ∧ + ¬ Nonempty (InvariantMean F) := by + sorry + +end ThompsonNonamenability + +end + +end OAI diff --git a/tasks/thompson-nonamenability/tests/grade.py b/tasks/thompson-nonamenability/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thompson-nonamenability/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thompson-nonamenability/tests/task.json b/tasks/thompson-nonamenability/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f5cd22252af5aa025a24b398c67cc21860a91014 --- /dev/null +++ b/tasks/thompson-nonamenability/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThompsonNonamenability", + "comparator": { + "theorem_names": [ + "OAI.ThompsonNonamenability.thompson_F_nonamenable_composition" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11135 +} \ No newline at end of file diff --git a/tasks/thompson-nonamenability/tests/test.sh b/tasks/thompson-nonamenability/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thompson-nonamenability/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thorp-first-reciprocal/environment/Dockerfile b/tasks/thorp-first-reciprocal/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thorp-first-reciprocal/environment/fetch_mathlib.sh b/tasks/thorp-first-reciprocal/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thorp-first-reciprocal/environment/lake-manifest.json b/tasks/thorp-first-reciprocal/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thorp-first-reciprocal/environment/lakefile.lean b/tasks/thorp-first-reciprocal/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thorp-first-reciprocal/environment/lean_setup.sh b/tasks/thorp-first-reciprocal/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thorp-first-reciprocal/environment/pack_submission.py b/tasks/thorp-first-reciprocal/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thorp-first-reciprocal/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thorp-first-reciprocal/instruction.md b/tasks/thorp-first-reciprocal/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4075c5e28fd02b40f6bc24e6aca99138e231e3a0 --- /dev/null +++ b/tasks/thorp-first-reciprocal/instruction.md @@ -0,0 +1,284 @@ +# openai/math challenge `ThorpFirstReciprocal` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `ThorpFirstReciprocal`, also at `/opt/openai-math/challenges/ThorpFirstReciprocal.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe uG uV uE uX uH uI uβ uα + +open scoped BigOperators Classical ComplexConjugate InnerProductSpace +open Filter Topology + +namespace Thorp + +abbrev Position (d : ℕ) := Fin d → Bool + +namespace Block + +variable {I : Type uI} {β : Type uβ} {α : Type uα} + +def perm (p : I → Equiv.Perm β) : Equiv.Perm (I × β) where + toFun x := (x.1, p x.1 x.2) + invFun x := (x.1, (p x.1)⁻¹ x.2) + left_inv x := by simp + right_inv x := by simp + +def hom : (I → Equiv.Perm β) →* Equiv.Perm (I × β) where + toFun := perm + map_one' := by ext ⟨i,b⟩ <;> rfl + map_mul' p q := by ext ⟨i,b⟩ <;> rfl + +def embedding (e : α ≃ I × β) : (I → Equiv.Perm β) →* Equiv.Perm α := + (e.symm.permCongrHom).toMonoidHom.comp hom + +end Block + +namespace Fourier + +variable {G : Type uG} [Group G] [Fintype G] +variable {V : Type uV} [AddCommGroup V] [Module ℂ V] + +def integrated (ρ : Representation ℂ G V) (f : G → ℂ) : Module.End ℂ V := + ∑ g, f g • ρ g + +end Fourier + +namespace Young + +abbrev Cells (D : YoungDiagram) := {p : ℕ × ℕ // p ∈ D.cells} + +def rowCellsEquiv (D : YoungDiagram) : Cells D ≃ (i : Fin (D.colLen 0)) × Fin (D.rowLen i) where + toFun x := ⟨⟨x.val.1, YoungDiagram.mem_iff_lt_colLen.mp (D.up_left_mem le_rfl (Nat.zero_le _) x.property)⟩, + ⟨x.val.2, YoungDiagram.mem_iff_lt_rowLen.mp x.property⟩⟩ + invFun x := ⟨(x.1, x.2), YoungDiagram.mem_iff_lt_rowLen.mpr x.2.isLt⟩ + left_inv x := rfl + right_inv x := by cases x; rfl + +def ofPartition {n : ℕ} (p : Nat.Partition n) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +def longest (D : YoungDiagram) : ℕ := max (D.rowLen 0) (D.colLen 0) + +end Young + +namespace Specht + +variable {G : Type uG} [Group G] +variable {E : Type uE} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + +def cyclic (ρ : Representation ℂ G E) (e : E) : Subrepresentation ρ where + toSubmodule := Submodule.span ℂ (Set.range fun g => ρ g e) + apply_mem_toSubmodule g := by + intro v hv + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨h, rfl⟩ := hv + exact Submodule.subset_span ⟨g * h, by simp⟩ + | zero => simp + | add x y hx hy ihx ihy => + simpa using (Submodule.span ℂ (Set.range fun h => ρ h e)).add_mem ihx ihy + | smul a x hx ih => + simpa using (Submodule.span ℂ (Set.range fun h => ρ h e)).smul_mem a ih + +namespace PermutationSpace + +variable {X : Type uX} [Fintype X] [MulAction G X] + +def rep : Representation ℂ G (EuclideanSpace ℂ X) where + toFun g := { + toFun v := WithLp.toLp 2 (fun x => v (g⁻¹ • x)) + map_add' := by intro v w; rfl + map_smul' := by intro a v; rfl } + map_one' := by ext v x; simp + map_mul' := by + intro g h + ext v x + change v ((g * h)⁻¹ • x) = v (h⁻¹ • g⁻¹ • x) + simp [mul_smul] + +variable {H : Type uH} [Group H] [Fintype H] + +def alternator (ι : H →* G) (χ : H →* ℂ) : Module.End ℂ (EuclideanSpace ℂ X) := + ∑ h, χ h • rep (ι h) + +end PermutationSpace + +variable {α : Type uα} [Fintype α] + +def Tabloid (r : α → ℕ) := {f : α → ℕ // ∃ g : Equiv.Perm α, f = r ∘ g} + +instance tabloidFinite (r : α → ℕ) : Finite (Tabloid r) := by + apply Finite.of_surjective (fun g : Equiv.Perm α => (⟨r ∘ g, g, rfl⟩ : Tabloid r)) + rintro ⟨f, g, rfl⟩ + exact ⟨g, rfl⟩ + +instance tabloidFintype (r : α → ℕ) : Fintype (Tabloid r) := Fintype.ofFinite _ + +instance tabloidAction (r : α → ℕ) : MulAction (Equiv.Perm α) (Tabloid r) where + smul g f := ⟨f.val ∘ ⇑(g⁻¹ : Equiv.Perm α), by + obtain ⟨h, hh⟩ := f.property + refine ⟨h * g⁻¹, ?_⟩ + funext x + simp only [Function.comp_apply, hh, Equiv.Perm.mul_apply]⟩ + one_smul f := by apply Subtype.ext; funext x; rfl + mul_smul g h f := by + apply Subtype.ext + funext x + change f.val ((g * h)⁻¹ x) = f.val (h⁻¹ (g⁻¹ x)) + rw [mul_inv_rev, Equiv.Perm.mul_apply] + +def baseTabloid (r : α → ℕ) : Tabloid r := ⟨r, 1, by funext x; rfl⟩ + +def fiberGroup (c : α → ℕ) : Subgroup (Equiv.Perm α) where + carrier := {g | ∀ x, c (g x) = c x} + one_mem' := by intro x; rfl + mul_mem' := by intro g h hg hh x; exact (hg (h x)).trans (hh x) + inv_mem' := by + intro g hg x + have hh := hg (g⁻¹ x) + change c (g (g.symm x)) = c (g.symm x) at hh + rw [g.apply_symm_apply] at hh + exact hh.symm + +def complexSign : Equiv.Perm α →* ℂ where + toFun g := ((Equiv.Perm.sign g : ℤˣ) : ℤ) + map_one' := by simp + map_mul' := by intro g h; simp + +variable (D : YoungDiagram) (t : α ≃ Thorp.Young.Cells D) + +def tableauRow (x : α) : ℕ := (t x).val.1 + +def tableauCol (x : α) : ℕ := (t x).val.2 + +def tabloidRep : Representation ℂ (Equiv.Perm α) (EuclideanSpace ℂ (Tabloid (tableauRow D t))) := + PermutationSpace.rep + +def columnAlternator : Module.End ℂ (EuclideanSpace ℂ (Tabloid (tableauRow D t))) := + PermutationSpace.alternator (fiberGroup (tableauCol D t)).subtype + (complexSign.comp (fiberGroup (tableauCol D t)).subtype) + +def polytabloid : EuclideanSpace ℂ (Tabloid (tableauRow D t)) := + columnAlternator D t (EuclideanSpace.single (baseTabloid (tableauRow D t)) (1 : ℂ)) + +def module : Subrepresentation (tabloidRep D t) := cyclic (tabloidRep D t) (polytabloid D t) + +abbrev Shape (α : Type uα) [Fintype α] := Nat.Partition (Fintype.card α) + +def canonicalTableau (p : Shape α) : α ≃ Thorp.Young.Cells (Thorp.Young.ofPartition p) := by + have card_cells_eq_sum (D : YoungDiagram) : Fintype.card (Thorp.Young.Cells D) = D.rowLens.sum := by + rw [Fintype.card_congr (Thorp.Young.rowCellsEquiv D), Fintype.card_sigma] + simp only [Fintype.card_fin, YoungDiagram.rowLens] + rw [← List.sum_toFinset _ List.nodup_range, List.toFinset_range, Finset.sum_range] + have rowLens_ofPartition {n : ℕ} (p : Nat.Partition n) : + (Thorp.Young.ofPartition p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + have card_ofPartition {n : ℕ} (p : Nat.Partition n) : Fintype.card (Thorp.Young.Cells (Thorp.Young.ofPartition p)) = n := by + rw [card_cells_eq_sum, rowLens_ofPartition] + simpa only [← Multiset.sum_coe, Multiset.sort_eq] using p.parts_sum + exact Fintype.equivOfCardEq (card_ofPartition p).symm + +abbrev Space (p : Shape α) := (module (Thorp.Young.ofPartition p) (canonicalTableau p)).toSubmodule + +def degree (p : Shape α) : ℕ := Module.finrank ℂ (Space p) + +open Thorp.Young + +abbrev NShape (n : ℕ) := Shape (Fin n) + +def defect {n : ℕ} (p : NShape n) : ℕ := n - longest (ofPartition p) + +end Specht + +namespace Current + +def reciprocalFirst (n : ℕ) : ℝ := + ∑ p : Specht.NShape n, (Specht.degree p : ℝ)⁻¹ + +def exceptionalFirst (n : ℕ) : ℝ := + ∑ p : Specht.NShape n, if 0 < Specht.defect p then (Specht.degree p : ℝ)⁻¹ else 0 + +def C1 : ℝ := sSup (Set.range (fun n : {n : ℕ // 1 ≤ n} => reciprocalFirst n.val)) + +theorem first_reciprocal_main : + (BddAbove (Set.range (fun n : {n : ℕ // 1 ≤ n} => reciprocalFirst n.val)) ∧ + (∀ n : ℕ, 1 ≤ n → reciprocalFirst n ≤ C1) ∧ + Tendsto exceptionalFirst atTop (nhds 0)) ∧ + (∀ (d : ℕ) (_hd : 3 ≤ d) + (e : Position d ≃ Fin 8 × Fin (2 ^ (d - 3))) + {E : Type uE} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + [FiniteDimensional ℂ E] + (ρ : Representation ℂ (Equiv.Perm (Position d)) E) + [Representation.IsIrreducible ρ] + (_ : ∀ g x y, ⟪ρ g x, ρ g y⟫_ℂ = ⟪x, y⟫_ℂ) + (ν : Equiv.Perm (Position d) → ℝ) + (_ : ∀ g, 0 ≤ ν g) (_ : ∑ g, ν g = 1) + (_ : ∀ (i : Fin 8) (g : Equiv.Perm (Position d)), + ∑ h : Equiv.Perm (Fin (2 ^ (d - 3))), + ν (g * Block.embedding e (Pi.mulSingle i h)) ≤ + 4 * (Fintype.card (Equiv.Perm (Fin (2 ^ (d - 3)))) : ℝ) / + Fintype.card (Equiv.Perm (Position d))), + ‖LinearMap.toContinuousLinearMap (Fourier.integrated ρ (fun g => (ν g : ℂ)))‖ ≤ + Real.sqrt (32 * C1) * (Module.finrank ℂ E : ℝ) ^ (-5 / 16 : ℝ)) := by + sorry + +end Current + +end Thorp + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThorpFirstReciprocal.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Thorp.Current.first_reciprocal_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thorp-first-reciprocal/solution/closure.txt b/tasks/thorp-first-reciprocal/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..9342d4a6a0b3e1b5ddb1e63107d7fd91db387588 --- /dev/null +++ b/tasks/thorp-first-reciprocal/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Probability.ThorpShuffle.BlockEmbedding +OAI.Probability.ThorpShuffle.Classification +OAI.Probability.ThorpShuffle.ConditionalFlow +OAI.Probability.ThorpShuffle.ConditionalLaw +OAI.Probability.ThorpShuffle.ConvolutionBounds +OAI.Probability.ThorpShuffle.CosetBounds +OAI.Probability.ThorpShuffle.Cyclic +OAI.Probability.ThorpShuffle.DegreeBounds +OAI.Probability.ThorpShuffle.EnergyDecay +OAI.Probability.ThorpShuffle.ExceptionalShapes +OAI.Probability.ThorpShuffle.ExtensionBounds +OAI.Probability.ThorpShuffle.FiniteExpectation +OAI.Probability.ThorpShuffle.FiniteLaw +OAI.Probability.ThorpShuffle.FirstFourier +OAI.Probability.ThorpShuffle.FirstMain +OAI.Probability.ThorpShuffle.FirstMoment +OAI.Probability.ThorpShuffle.FourierBounds +OAI.Probability.ThorpShuffle.FourierFamilies +OAI.Probability.ThorpShuffle.FourierPerturbation +OAI.Probability.ThorpShuffle.FreshCoins +OAI.Probability.ThorpShuffle.HalfHistories +OAI.Probability.ThorpShuffle.Irreducibility +OAI.Probability.ThorpShuffle.JointProjectors +OAI.Probability.ThorpShuffle.LinearExtensions +OAI.Probability.ThorpShuffle.MarginalBounds +OAI.Probability.ThorpShuffle.MarginalEnergy +OAI.Probability.ThorpShuffle.MaskedResampling +OAI.Probability.ThorpShuffle.MixingBounds +OAI.Probability.ThorpShuffle.Model +OAI.Probability.ThorpShuffle.NoiseEnergy +OAI.Probability.ThorpShuffle.PairAveraging +OAI.Probability.ThorpShuffle.Parity +OAI.Probability.ThorpShuffle.PartitionBounds +OAI.Probability.ThorpShuffle.PermutationCharacters +OAI.Probability.ThorpShuffle.Polytabloids +OAI.Probability.ThorpShuffle.PrefixTests +OAI.Probability.ThorpShuffle.ProductProjectors +OAI.Probability.ThorpShuffle.Reachability +OAI.Probability.ThorpShuffle.ReciprocalDegrees +OAI.Probability.ThorpShuffle.Reynolds +OAI.Probability.ThorpShuffle.Specht +OAI.Probability.ThorpShuffle.SpectralDecay +OAI.Probability.ThorpShuffle.Support +OAI.Probability.ThorpShuffle.SymmetricFamilies +OAI.Probability.ThorpShuffle.Tableaux +OAI.Probability.ThorpShuffle.TaggedCompletion +OAI.Probability.ThorpShuffle.TaggedDeviation +OAI.Probability.ThorpShuffle.Trimming +OAI.Probability.ThorpShuffle.VectorOrbits +OAI.Probability.ThorpShuffle.Walsh +OAI.Probability.ThorpShuffle.WalshFlow diff --git a/tasks/thorp-first-reciprocal/solution/reference.py b/tasks/thorp-first-reciprocal/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thorp-first-reciprocal/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thorp-first-reciprocal/solution/solve.sh b/tasks/thorp-first-reciprocal/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..81abd168458702c064f1731dd7f5fcb9c1ee8b71 --- /dev/null +++ b/tasks/thorp-first-reciprocal/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThorpFirstReciprocal, i.e. module OAI.Probability.ThorpShuffle.FirstMain and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThorpShuffle.FirstMain /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThorpFirstReciprocal" diff --git a/tasks/thorp-first-reciprocal/task.toml b/tasks/thorp-first-reciprocal/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7c682fd31dff5564fa8e40f66733d72eabe58dc6 --- /dev/null +++ b/tasks/thorp-first-reciprocal/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thorp-first-reciprocal" +version = "1.0.0" +description = "Prove ThorpFirstReciprocal (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThorpFirstReciprocal.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThorpFirstReciprocal" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.Thorp.Current.first_reciprocal_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThorpShuffle.FirstMain" +reference_modules = 51 +reference_lean_bytes = 367273 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 637 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12030 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thorp-first-reciprocal/tests/Challenge.lean b/tasks/thorp-first-reciprocal/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b4fa8c4ecf08f945b9eb90ef36207c5b357ab8ff --- /dev/null +++ b/tasks/thorp-first-reciprocal/tests/Challenge.lean @@ -0,0 +1,233 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe uG uV uE uX uH uI uβ uα + +open scoped BigOperators Classical ComplexConjugate InnerProductSpace +open Filter Topology + +namespace Thorp + +abbrev Position (d : ℕ) := Fin d → Bool + +namespace Block + +variable {I : Type uI} {β : Type uβ} {α : Type uα} + +def perm (p : I → Equiv.Perm β) : Equiv.Perm (I × β) where + toFun x := (x.1, p x.1 x.2) + invFun x := (x.1, (p x.1)⁻¹ x.2) + left_inv x := by simp + right_inv x := by simp + +def hom : (I → Equiv.Perm β) →* Equiv.Perm (I × β) where + toFun := perm + map_one' := by ext ⟨i,b⟩ <;> rfl + map_mul' p q := by ext ⟨i,b⟩ <;> rfl + +def embedding (e : α ≃ I × β) : (I → Equiv.Perm β) →* Equiv.Perm α := + (e.symm.permCongrHom).toMonoidHom.comp hom + +end Block + +namespace Fourier + +variable {G : Type uG} [Group G] [Fintype G] +variable {V : Type uV} [AddCommGroup V] [Module ℂ V] + +def integrated (ρ : Representation ℂ G V) (f : G → ℂ) : Module.End ℂ V := + ∑ g, f g • ρ g + +end Fourier + +namespace Young + +abbrev Cells (D : YoungDiagram) := {p : ℕ × ℕ // p ∈ D.cells} + +def rowCellsEquiv (D : YoungDiagram) : Cells D ≃ (i : Fin (D.colLen 0)) × Fin (D.rowLen i) where + toFun x := ⟨⟨x.val.1, YoungDiagram.mem_iff_lt_colLen.mp (D.up_left_mem le_rfl (Nat.zero_le _) x.property)⟩, + ⟨x.val.2, YoungDiagram.mem_iff_lt_rowLen.mp x.property⟩⟩ + invFun x := ⟨(x.1, x.2), YoungDiagram.mem_iff_lt_rowLen.mpr x.2.isLt⟩ + left_inv x := rfl + right_inv x := by cases x; rfl + +def ofPartition {n : ℕ} (p : Nat.Partition n) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +def longest (D : YoungDiagram) : ℕ := max (D.rowLen 0) (D.colLen 0) + +end Young + +namespace Specht + +variable {G : Type uG} [Group G] +variable {E : Type uE} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + +def cyclic (ρ : Representation ℂ G E) (e : E) : Subrepresentation ρ where + toSubmodule := Submodule.span ℂ (Set.range fun g => ρ g e) + apply_mem_toSubmodule g := by + intro v hv + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨h, rfl⟩ := hv + exact Submodule.subset_span ⟨g * h, by simp⟩ + | zero => simp + | add x y hx hy ihx ihy => + simpa using (Submodule.span ℂ (Set.range fun h => ρ h e)).add_mem ihx ihy + | smul a x hx ih => + simpa using (Submodule.span ℂ (Set.range fun h => ρ h e)).smul_mem a ih + +namespace PermutationSpace + +variable {X : Type uX} [Fintype X] [MulAction G X] + +def rep : Representation ℂ G (EuclideanSpace ℂ X) where + toFun g := { + toFun v := WithLp.toLp 2 (fun x => v (g⁻¹ • x)) + map_add' := by intro v w; rfl + map_smul' := by intro a v; rfl } + map_one' := by ext v x; simp + map_mul' := by + intro g h + ext v x + change v ((g * h)⁻¹ • x) = v (h⁻¹ • g⁻¹ • x) + simp [mul_smul] + +variable {H : Type uH} [Group H] [Fintype H] + +def alternator (ι : H →* G) (χ : H →* ℂ) : Module.End ℂ (EuclideanSpace ℂ X) := + ∑ h, χ h • rep (ι h) + +end PermutationSpace + +variable {α : Type uα} [Fintype α] + +def Tabloid (r : α → ℕ) := {f : α → ℕ // ∃ g : Equiv.Perm α, f = r ∘ g} + +instance tabloidFinite (r : α → ℕ) : Finite (Tabloid r) := by + apply Finite.of_surjective (fun g : Equiv.Perm α => (⟨r ∘ g, g, rfl⟩ : Tabloid r)) + rintro ⟨f, g, rfl⟩ + exact ⟨g, rfl⟩ + +instance tabloidFintype (r : α → ℕ) : Fintype (Tabloid r) := Fintype.ofFinite _ + +instance tabloidAction (r : α → ℕ) : MulAction (Equiv.Perm α) (Tabloid r) where + smul g f := ⟨f.val ∘ ⇑(g⁻¹ : Equiv.Perm α), by + obtain ⟨h, hh⟩ := f.property + refine ⟨h * g⁻¹, ?_⟩ + funext x + simp only [Function.comp_apply, hh, Equiv.Perm.mul_apply]⟩ + one_smul f := by apply Subtype.ext; funext x; rfl + mul_smul g h f := by + apply Subtype.ext + funext x + change f.val ((g * h)⁻¹ x) = f.val (h⁻¹ (g⁻¹ x)) + rw [mul_inv_rev, Equiv.Perm.mul_apply] + +def baseTabloid (r : α → ℕ) : Tabloid r := ⟨r, 1, by funext x; rfl⟩ + +def fiberGroup (c : α → ℕ) : Subgroup (Equiv.Perm α) where + carrier := {g | ∀ x, c (g x) = c x} + one_mem' := by intro x; rfl + mul_mem' := by intro g h hg hh x; exact (hg (h x)).trans (hh x) + inv_mem' := by + intro g hg x + have hh := hg (g⁻¹ x) + change c (g (g.symm x)) = c (g.symm x) at hh + rw [g.apply_symm_apply] at hh + exact hh.symm + +def complexSign : Equiv.Perm α →* ℂ where + toFun g := ((Equiv.Perm.sign g : ℤˣ) : ℤ) + map_one' := by simp + map_mul' := by intro g h; simp + +variable (D : YoungDiagram) (t : α ≃ Thorp.Young.Cells D) + +def tableauRow (x : α) : ℕ := (t x).val.1 + +def tableauCol (x : α) : ℕ := (t x).val.2 + +def tabloidRep : Representation ℂ (Equiv.Perm α) (EuclideanSpace ℂ (Tabloid (tableauRow D t))) := + PermutationSpace.rep + +def columnAlternator : Module.End ℂ (EuclideanSpace ℂ (Tabloid (tableauRow D t))) := + PermutationSpace.alternator (fiberGroup (tableauCol D t)).subtype + (complexSign.comp (fiberGroup (tableauCol D t)).subtype) + +def polytabloid : EuclideanSpace ℂ (Tabloid (tableauRow D t)) := + columnAlternator D t (EuclideanSpace.single (baseTabloid (tableauRow D t)) (1 : ℂ)) + +def module : Subrepresentation (tabloidRep D t) := cyclic (tabloidRep D t) (polytabloid D t) + +abbrev Shape (α : Type uα) [Fintype α] := Nat.Partition (Fintype.card α) + +def canonicalTableau (p : Shape α) : α ≃ Thorp.Young.Cells (Thorp.Young.ofPartition p) := by + have card_cells_eq_sum (D : YoungDiagram) : Fintype.card (Thorp.Young.Cells D) = D.rowLens.sum := by + rw [Fintype.card_congr (Thorp.Young.rowCellsEquiv D), Fintype.card_sigma] + simp only [Fintype.card_fin, YoungDiagram.rowLens] + rw [← List.sum_toFinset _ List.nodup_range, List.toFinset_range, Finset.sum_range] + have rowLens_ofPartition {n : ℕ} (p : Nat.Partition n) : + (Thorp.Young.ofPartition p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + have card_ofPartition {n : ℕ} (p : Nat.Partition n) : Fintype.card (Thorp.Young.Cells (Thorp.Young.ofPartition p)) = n := by + rw [card_cells_eq_sum, rowLens_ofPartition] + simpa only [← Multiset.sum_coe, Multiset.sort_eq] using p.parts_sum + exact Fintype.equivOfCardEq (card_ofPartition p).symm + +abbrev Space (p : Shape α) := (module (Thorp.Young.ofPartition p) (canonicalTableau p)).toSubmodule + +def degree (p : Shape α) : ℕ := Module.finrank ℂ (Space p) + +open Thorp.Young + +abbrev NShape (n : ℕ) := Shape (Fin n) + +def defect {n : ℕ} (p : NShape n) : ℕ := n - longest (ofPartition p) + +end Specht + +namespace Current + +def reciprocalFirst (n : ℕ) : ℝ := + ∑ p : Specht.NShape n, (Specht.degree p : ℝ)⁻¹ + +def exceptionalFirst (n : ℕ) : ℝ := + ∑ p : Specht.NShape n, if 0 < Specht.defect p then (Specht.degree p : ℝ)⁻¹ else 0 + +def C1 : ℝ := sSup (Set.range (fun n : {n : ℕ // 1 ≤ n} => reciprocalFirst n.val)) + +theorem first_reciprocal_main : + (BddAbove (Set.range (fun n : {n : ℕ // 1 ≤ n} => reciprocalFirst n.val)) ∧ + (∀ n : ℕ, 1 ≤ n → reciprocalFirst n ≤ C1) ∧ + Tendsto exceptionalFirst atTop (nhds 0)) ∧ + (∀ (d : ℕ) (_hd : 3 ≤ d) + (e : Position d ≃ Fin 8 × Fin (2 ^ (d - 3))) + {E : Type uE} [NormedAddCommGroup E] [InnerProductSpace ℂ E] + [FiniteDimensional ℂ E] + (ρ : Representation ℂ (Equiv.Perm (Position d)) E) + [Representation.IsIrreducible ρ] + (_ : ∀ g x y, ⟪ρ g x, ρ g y⟫_ℂ = ⟪x, y⟫_ℂ) + (ν : Equiv.Perm (Position d) → ℝ) + (_ : ∀ g, 0 ≤ ν g) (_ : ∑ g, ν g = 1) + (_ : ∀ (i : Fin 8) (g : Equiv.Perm (Position d)), + ∑ h : Equiv.Perm (Fin (2 ^ (d - 3))), + ν (g * Block.embedding e (Pi.mulSingle i h)) ≤ + 4 * (Fintype.card (Equiv.Perm (Fin (2 ^ (d - 3)))) : ℝ) / + Fintype.card (Equiv.Perm (Position d))), + ‖LinearMap.toContinuousLinearMap (Fourier.integrated ρ (fun g => (ν g : ℂ)))‖ ≤ + Real.sqrt (32 * C1) * (Module.finrank ℂ E : ℝ) ^ (-5 / 16 : ℝ)) := by + sorry + +end Current + +end Thorp + +end + +end OAI diff --git a/tasks/thorp-first-reciprocal/tests/grade.py b/tasks/thorp-first-reciprocal/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thorp-first-reciprocal/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thorp-first-reciprocal/tests/task.json b/tasks/thorp-first-reciprocal/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cb66a7e6716011c56b274ab9c3cb60947222de56 --- /dev/null +++ b/tasks/thorp-first-reciprocal/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThorpFirstReciprocal", + "comparator": { + "theorem_names": [ + "OAI.Thorp.Current.first_reciprocal_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11130 +} \ No newline at end of file diff --git a/tasks/thorp-first-reciprocal/tests/test.sh b/tasks/thorp-first-reciprocal/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thorp-first-reciprocal/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thorp-remaining/environment/Dockerfile b/tasks/thorp-remaining/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thorp-remaining/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thorp-remaining/environment/fetch_mathlib.sh b/tasks/thorp-remaining/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thorp-remaining/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thorp-remaining/environment/lake-manifest.json b/tasks/thorp-remaining/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thorp-remaining/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thorp-remaining/environment/lakefile.lean b/tasks/thorp-remaining/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thorp-remaining/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thorp-remaining/environment/lean_setup.sh b/tasks/thorp-remaining/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thorp-remaining/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thorp-remaining/environment/pack_submission.py b/tasks/thorp-remaining/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thorp-remaining/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thorp-remaining/instruction.md b/tasks/thorp-remaining/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..65bb9823864d3caebda7f1c5d7067fa099eaa633 --- /dev/null +++ b/tasks/thorp-remaining/instruction.md @@ -0,0 +1,601 @@ +# openai/math challenge `ThorpRemaining` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `ThorpRemaining`, also at `/opt/openai-math/challenges/ThorpRemaining.lean`: + +```lean +import Mathlib + +namespace OAI + +universe u v + +noncomputable section +open scoped BigOperators +open Filter + +namespace Thorp + +abbrev Position (d : ℕ) := Fin d → Bool +abbrev State (d : ℕ) := Equiv.Perm (Position d) + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Position d → Bool + +instance coinsFintype (d : ℕ) : Fintype (Coins d) := by + cases d <;> simp only [Coins] <;> infer_instance + +instance coinsInhabited (d : ℕ) : Inhabited (Coins d) := by + cases d <;> simp only [Coins] <;> infer_instance + +def pairSwitch (d : ℕ) (c : Position d → Bool) : Equiv.Perm (Bool × Position d) where + toFun p := (p.1 ^^ c p.2, p.2) + invFun p := (p.1 ^^ c p.2, p.2) + left_inv p := by + rcases p with ⟨b, s⟩ + cases b <;> cases h : c s <;> simp [h] + right_inv p := by + rcases p with ⟨b, s⟩ + cases b <;> cases h : c s <;> simp [h] + +def rotate (d : ℕ) : State d := + Equiv.piCongrLeft (fun _ : Fin d => Bool) (finRotate d).symm + +def step : (d : ℕ) → Coins d → State d + | 0, _ => Equiv.refl _ + | d + 1, c => + (((Fin.consEquiv (fun _ : Fin (d + 1) => Bool)).symm.trans + (pairSwitch d c)).trans + (Fin.consEquiv (fun _ : Fin (d + 1) => Bool))).trans (rotate (d + 1)) + +abbrev History (d t : ℕ) := Fin t → Coins d + +def run (d t : ℕ) (ω : History d t) : State d := + ((List.ofFn fun i : Fin t => step d (ω i)).reverse).prod + +def fairMass {Ω : Type u} {α : Type v} [Fintype Ω] (f : Ω → α) (a : α) : ℝ := by + classical + exact (∑ ω : Ω, if f ω = a then (1 : ℝ) else 0) / Fintype.card Ω + +def law (d t : ℕ) : State d → ℝ := fairMass (run d t) + +def uniform (d : ℕ) (_ : State d) : ℝ := 1 / Fintype.card (State d) + +def tv {α : Type u} [Fintype α] (μ ν : α → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ a : α, |μ a - ν a| + +def distance (d t : ℕ) : ℝ := tv (law d t) (uniform d) + +def lawFrom (d t : ℕ) (g₀ : State d) : State d → ℝ := + fairMass (fun ω : History d t => run d t ω * g₀) + +abbrev LabelList (d k : ℕ) := Fin k ↪ Position d + +def coordinateRun (d t : ℕ) (ω : History d t) : State d := + (rotate d)⁻¹ ^ t * run d t ω + +def images {d k : ℕ} (t : ℕ) (start : State d) (labels : LabelList d k) + (ω : History d t) : LabelList d k := + labels.trans ((coordinateRun d t ω * start).toEmbedding) + +def listTV {d k : ℕ} (t : ℕ) (start : State d) (labels : LabelList d k) : ℝ := + tv (fairMass (images t start labels)) (fun _ => 1 / Fintype.card (LabelList d k)) + +def mixingTime (d : ℕ) : ℕ := sInf {t : ℕ | distance d t ≤ 1 / 4} + +end Thorp + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +end Thorp + +namespace Thorp +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +open scoped BigOperators Classical +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end Thorp +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +noncomputable def cellRowsEquiv (μ : YoungDiagram) : + Cell μ ≃ (i : Fin (μ.colLen 0)) × Fin (μ.rowLen i) where + toFun x := ⟨rowIndex x,⟨col x,YoungDiagram.mem_iff_lt_rowLen.mp x.2⟩⟩ + invFun p := ⟨(p.1,p.2),YoungDiagram.mem_iff_lt_rowLen.mpr p.2.2⟩ + left_inv x := by apply Subtype.ext; rfl + right_inv p := by rcases p with ⟨⟨i,hi⟩,⟨j,hj⟩⟩; rfl + +lemma card_eq_sum_rowLen (μ : YoungDiagram) : μ.card = ∑ i : Fin (μ.colLen 0), μ.rowLen i := by + rw [←card_cell,Fintype.card_congr (cellRowsEquiv μ),Fintype.card_sigma] + simp only [Fintype.card_fin] + +lemma sum_rowLens (μ : YoungDiagram) : μ.rowLens.sum = μ.card := by + rw [card_eq_sum_rowLen,YoungDiagram.rowLens] + rw [Fin.sum_univ_eq_sum_range] + have hh (n : ℕ) : (List.map μ.rowLen (List.range n)).sum = ∑ i ∈ Finset.range n, μ.rowLen i := by + induction n with + | zero => simp + | succ n ih => simp [List.range_succ,List.map_append,Finset.sum_range_succ,ih] + exact hh _ + +noncomputable def diagramPartition (μ : YoungDiagram) : Nat.Partition μ.card where + parts := μ.rowLens + parts_pos := fun {i} hi => μ.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simp + +noncomputable def partitionDiagram {N : ℕ} (p : Nat.Partition N) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +lemma partitionDiagram_rowLens {N : ℕ} (p : Nat.Partition N) : + (partitionDiagram p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + +lemma partitionDiagram_card {N : ℕ} (p : Nat.Partition N) : (partitionDiagram p).card = N := by + rw [←sum_rowLens,partitionDiagram_rowLens] + change (↑(p.parts.sort (· ≥ ·)) : Multiset ℕ).sum = N + rw [Multiset.sort_eq,p.parts_sum] + +lemma partitionDiagram_diagramPartition (μ : YoungDiagram) : + partitionDiagram (diagramPartition μ) = μ := by + apply YoungDiagram.equivListRowLens.injective + apply Subtype.ext + change (partitionDiagram (diagramPartition μ)).rowLens = μ.rowLens + rw [partitionDiagram_rowLens] + change (↑μ.rowLens : Multiset ℕ).sort (· ≥ ·) = μ.rowLens + rw [Multiset.coe_sort,List.mergeSort_eq_self _ μ.rowLens_sorted.pairwise] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def shapePartitionEquiv (N : ℕ) : Shapes N ≃ Nat.Partition N where + toFun μ := { parts := μ.1.rowLens + parts_pos := fun {i} hi => μ.1.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simpa using (sum_rowLens μ.1).trans μ.2 } + invFun p := ⟨partitionDiagram p,partitionDiagram_card p⟩ + left_inv μ := by + apply Subtype.ext + obtain ⟨μ,rfl⟩ := μ + exact partitionDiagram_diagramPartition μ + right_inv p := by + apply Nat.Partition.ext + change ((partitionDiagram p).rowLens : Multiset ℕ) = p.parts + rw [partitionDiagram_rowLens,Multiset.sort_eq] + +noncomputable instance (N : ℕ) : Fintype (Shapes N) := Fintype.ofEquiv _ (shapePartitionEquiv N).symm + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end Thorp.Specht +namespace Thorp.LowPlanes +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +open scoped BigOperators Classical +open Specht UnitaryFinite + +noncomputable local instance hsNorm (μ : YoungDiagram) : NormedAddCommGroup (hilbertSpace μ) := inferInstance +noncomputable local instance hsInner (μ : YoungDiagram) : InnerProductSpace ℂ (hilbertSpace μ) := inferInstance +noncomputable local instance hsFinite (μ : YoungDiagram) : FiniteDimensional ℂ (hilbertSpace μ) := inferInstance + +noncomputable def Q (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) + +noncomputable def absoluteTrace {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + (A : V →L[ℂ] V) (P : ℝ) : ℝ := + (LinearMap.trace ℂ V (CFC.rpow (CFC.sqrt (star A * A)) P).toLinearMap).re + +noncomputable def regularTrace (d : ℕ) (P : ℝ) : ℝ := + ∑ μ : Shapes (2^d), (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + absoluteTrace (V := hilbertSpace μ.1) (Q d μ) P + +noncomputable def sweepDistance (d v : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d (v*d) (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +end Thorp.LowPlanes +end ThorpNine.Harmonic + +namespace ThorpNine.Harmonic.Thorp.LowPlanes +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +open scoped BigOperators +open Specht UnitaryFinite +attribute [local instance] hsNorm hsInner hsFinite +def weightedMoment (d r : ℕ) (μ : Shapes (2 ^ d)) : ℝ := + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + (LinearMap.trace ℂ (hilbertSpace μ.1) + ((star (Q d μ) * Q d μ) ^ r).toLinearMap).re + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def signedEntropy (α β : YoungDiagram) : ℝ := + (∑ x : Cell α, Real.log ((α.card + β.card : ℕ) / (α.rowLen (row x) : ℝ))) + + (∑ x : Cell β, Real.log ((α.card + β.card : ℕ) / (β.rowLen (row x) : ℝ))) + +def budgetCoefficient (a : ℝ) (d : ℕ) : ℝ := + a * (1 - 1 / (2 * Real.sqrt d)) + +def remainderBudget (κ : ℝ) (d l : ℕ) : ℝ := + if l = 0 then 0 else + max 0 (budgetCoefficient κ d * l * Real.log (2 ^ d : ℝ) - + l * Real.log ((2 ^ d : ℝ) / l)) + +def logWeightedMoment (d r : ℕ) (μ : Shapes (2 ^ d)) : EReal := + (ENNReal.ofReal (weightedMoment d r μ)).log + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def densityL2Squared (d t : ℕ) : ℝ := + (Nat.factorial (2 ^ d) : ℝ) * ∑ g : Equiv.Perm (Card d), + (law d t g - 1 / (Nat.factorial (2 ^ d) : ℝ)) ^ 2 + +def densityL2SquaredFrom (d t : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (Nat.factorial (2 ^ d) : ℝ) * ∑ g : Equiv.Perm (Card d), + (law d t (g * σ⁻¹) - 1 / (Nat.factorial (2 ^ d) : ℝ)) ^ 2 + +end ThorpNine.Harmonic.Thorp.LowPlanes + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace ThorpResults +open ThorpNine.Harmonic.Thorp +open ThorpNine.Harmonic.Thorp.Specht +open ThorpNine.Harmonic.Thorp.LowPlanes + +attribute [local instance] hsNorm hsInner hsFinite + +def FrameMain : Prop := + ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, ∀ start : _root_.OAI.Thorp.State d, + _root_.OAI.Thorp.tv (_root_.OAI.Thorp.lawFrom d (32800 * d) start) (_root_.OAI.Thorp.uniform d) < ε + +def InformationMain : Prop := + (∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ k : ℕ, 8 * k ≤ 7 * 2 ^ d → + ∀ (start : _root_.OAI.Thorp.State d) (labels : _root_.OAI.Thorp.LabelList d k), + _root_.OAI.Thorp.listTV (256 * d) start labels < ε) ∧ + (∀ᶠ d : ℕ in atTop, + ∀ k : ℕ, 16 * k ≤ 15 * 2 ^ d → + ∀ (start : _root_.OAI.Thorp.State d) (labels : _root_.OAI.Thorp.LabelList d k), + _root_.OAI.Thorp.listTV (1024 * d) start labels ≤ + Real.rpow ((2 : ℝ) ^ d) (-(3 : ℝ) / 2)) ∧ + (Tendsto (fun d : ℕ => _root_.OAI.Thorp.distance d (2048 * d)) atTop (nhds 0) ∧ + ∀ (d : ℕ) (start : _root_.OAI.Thorp.State d), + _root_.OAI.Thorp.tv (_root_.OAI.Thorp.lawFrom d (2048 * d) start) (_root_.OAI.Thorp.uniform d) = + _root_.OAI.Thorp.distance d (2048 * d)) + +def SpectrumMain : Prop := + ∃ p : ℝ, 0 < p ∧ ∀ d : ℕ, 1 ≤ d → + regularTrace d (2 * p) ≤ 1 + 1 / 16 ∧ + ∀ M : ℕ, p ≤ M → ∀ σ : Equiv.Perm (Card d), sweepDistance d M σ ≤ 1 / 8 + +def SignedMain : Prop := + ∀ η κ : ℝ, 0 < η → ∃ r : ℕ, 1 ≤ r ∧ ∀ d : ℕ, 1 ≤ d → + ∀ (μ : Shapes (2 ^ d)) (α β γ : YoungDiagram), + α.card + β.card + γ.card = 2 ^ d → + logWeightedMoment d r μ ≤ + ((budgetCoefficient η d * signedEntropy α β + + remainderBudget κ d γ.card : ℝ) : EReal) + +def DegreeSavingMain : Prop := + ∃ r : ℕ, Even r ∧ 2 ≤ r ∧ ∃ η : ℝ, 0 < η ∧ + ∀ d (μ : Shapes (2 ^ d)), + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + (LinearMap.trace ℂ (hilbertSpace μ.1) + ((Q d μ * star (Q d μ)) ^ r).toLinearMap).re ≤ + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) ^ (1 - η) + +def FullDensityMain : Prop := + ∃ v : ℕ, 1 ≤ v ∧ ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ σ : Equiv.Perm (Card d), densityL2SquaredFrom d (v * d) σ < ε + +def ForwardMixingMain : Prop := + ∃ v : ℕ, 1 ≤ v ∧ ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ σ : Equiv.Perm (Card d), sweepDistance d v σ < ε + +def OptimalOrderMain : Prop := + Asymptotics.IsTheta atTop (fun d : ℕ => (_root_.OAI.Thorp.mixingTime d : ℝ)) + (fun d : ℕ => Real.log (2 ^ d : ℝ)) + +end ThorpResults + +namespace ThorpResults +theorem remaining_main : + FrameMain ∧ InformationMain ∧ SpectrumMain ∧ SignedMain ∧ + DegreeSavingMain ∧ FullDensityMain ∧ ForwardMixingMain ∧ OptimalOrderMain := by + sorry +end ThorpResults +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThorpRemaining.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThorpResults.remaining_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thorp-remaining/solution/closure.txt b/tasks/thorp-remaining/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a632a6f4fc2bfc3f6ff5c62e5f78fa6387a1eb12 --- /dev/null +++ b/tasks/thorp-remaining/solution/closure.txt @@ -0,0 +1,92 @@ +OAI.Probability.ThorpResults.FullDensity +OAI.Probability.ThorpResults.FullDevelopment +OAI.Probability.ThorpResults.Main +OAI.Probability.ThorpResults.Mixing +OAI.Probability.ThorpResults.SignedBudget +OAI.Probability.ThorpResults.Statements +OAI.Probability.ThorpResults.UniformMoments +OAI.Probability.ThorpRouting.Harmonic.AlternatingPerm +OAI.Probability.ThorpRouting.Harmonic.AssignmentSlots +OAI.Probability.ThorpRouting.Harmonic.AverageMap +OAI.Probability.ThorpRouting.Harmonic.BlockProduct +OAI.Probability.ThorpRouting.Harmonic.Coins +OAI.Probability.ThorpRouting.Harmonic.CutoffMass +OAI.Probability.ThorpRouting.Harmonic.ExposedCoins +OAI.Probability.ThorpRouting.Harmonic.InputTree +OAI.Probability.ThorpRouting.Harmonic.InsertionPerm +OAI.Probability.ThorpRouting.Harmonic.Main +OAI.Probability.ThorpRouting.Harmonic.Model +OAI.Probability.ThorpRouting.Harmonic.ModifiedReverseCoins +OAI.Probability.ThorpRouting.Harmonic.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Harmonic.PairAssembleEquiv +OAI.Probability.ThorpRouting.Harmonic.PalindromeFamilyCost +OAI.Probability.ThorpRouting.Harmonic.ParallelFollow +OAI.Probability.ThorpRouting.Harmonic.PriorPaths +OAI.Probability.ThorpRouting.Harmonic.RotationMeeting +OAI.Probability.ThorpRouting.Harmonic.SandwichShuffle +OAI.Probability.ThorpRouting.Harmonic.Shapes +OAI.Probability.ThorpRouting.Harmonic.Site +OAI.Probability.ThorpRouting.Harmonic.TailShapes +OAI.Probability.ThorpRouting.Harmonic.TypedSet +OAI.Probability.ThorpRouting.Harmonic.ZeroExtend +OAI.Probability.ThorpRouting.RegularTrace +OAI.Probability.ThorpRouting.TraceBound +OAI.Probability.ThorpRouting.TraceDecay +OAI.Probability.ThorpRouting.TraceModel +OAI.Probability.ThorpShuffle.BlockEmbedding +OAI.Probability.ThorpShuffle.BlockFibers +OAI.Probability.ThorpShuffle.BlockLaws +OAI.Probability.ThorpShuffle.Classification +OAI.Probability.ThorpShuffle.ConditionalFlow +OAI.Probability.ThorpShuffle.ConditionalLaw +OAI.Probability.ThorpShuffle.ConvolutionBounds +OAI.Probability.ThorpShuffle.CosetBounds +OAI.Probability.ThorpShuffle.Cyclic +OAI.Probability.ThorpShuffle.DegreeBounds +OAI.Probability.ThorpShuffle.EightBlocks +OAI.Probability.ThorpShuffle.EnergyDecay +OAI.Probability.ThorpShuffle.ExtensionBounds +OAI.Probability.ThorpShuffle.FiniteExpectation +OAI.Probability.ThorpShuffle.FiniteLaw +OAI.Probability.ThorpShuffle.FixedLists.Asymptotics +OAI.Probability.ThorpShuffle.FixedLists.Energy +OAI.Probability.ThorpShuffle.FixedLists.FullDeck +OAI.Probability.ThorpShuffle.FixedLists.Lists +OAI.Probability.ThorpShuffle.FixedLists.Main +OAI.Probability.ThorpShuffle.FixedLists.Objects +OAI.Probability.ThorpShuffle.FourierBounds +OAI.Probability.ThorpShuffle.FourierFamilies +OAI.Probability.ThorpShuffle.FourierPerturbation +OAI.Probability.ThorpShuffle.FreshCoins +OAI.Probability.ThorpShuffle.HalfHistories +OAI.Probability.ThorpShuffle.Irreducibility +OAI.Probability.ThorpShuffle.JointProjectors +OAI.Probability.ThorpShuffle.LinearExtensions +OAI.Probability.ThorpShuffle.Main +OAI.Probability.ThorpShuffle.MarginalBounds +OAI.Probability.ThorpShuffle.MarginalEnergy +OAI.Probability.ThorpShuffle.MaskedResampling +OAI.Probability.ThorpShuffle.MixingBounds +OAI.Probability.ThorpShuffle.Model +OAI.Probability.ThorpShuffle.NoiseEnergy +OAI.Probability.ThorpShuffle.PairAveraging +OAI.Probability.ThorpShuffle.Parity +OAI.Probability.ThorpShuffle.PartitionBounds +OAI.Probability.ThorpShuffle.PermutationCharacters +OAI.Probability.ThorpShuffle.Polytabloids +OAI.Probability.ThorpShuffle.PrefixTests +OAI.Probability.ThorpShuffle.ProductProjectors +OAI.Probability.ThorpShuffle.Reachability +OAI.Probability.ThorpShuffle.ReciprocalDegrees +OAI.Probability.ThorpShuffle.Reynolds +OAI.Probability.ThorpShuffle.Specht +OAI.Probability.ThorpShuffle.SpectralDecay +OAI.Probability.ThorpShuffle.Support +OAI.Probability.ThorpShuffle.SymmetricFamilies +OAI.Probability.ThorpShuffle.Tableaux +OAI.Probability.ThorpShuffle.TaggedCompletion +OAI.Probability.ThorpShuffle.TaggedDeviation +OAI.Probability.ThorpShuffle.Trimming +OAI.Probability.ThorpShuffle.VectorOrbits +OAI.Probability.ThorpShuffle.Walsh +OAI.Probability.ThorpShuffle.WalshFlow diff --git a/tasks/thorp-remaining/solution/reference.py b/tasks/thorp-remaining/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thorp-remaining/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thorp-remaining/solution/solve.sh b/tasks/thorp-remaining/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b8e274db5924093fba38ba196fdaae10be8a139f --- /dev/null +++ b/tasks/thorp-remaining/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThorpRemaining, i.e. module OAI.Probability.ThorpResults.FullDevelopment and the +# 92 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThorpResults.FullDevelopment /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThorpRemaining" diff --git a/tasks/thorp-remaining/task.toml b/tasks/thorp-remaining/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..182453119052358c68ddfc0f2b419142f3eb19f9 --- /dev/null +++ b/tasks/thorp-remaining/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thorp-remaining" +version = "1.0.0" +description = "Prove ThorpRemaining (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThorpRemaining.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThorpRemaining" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThorpResults.remaining_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThorpResults.FullDevelopment" +reference_modules = 92 +reference_lean_bytes = 1378792 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 730 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12940 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thorp-remaining/tests/Challenge.lean b/tasks/thorp-remaining/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dcc131fab907ff7d2b56a76e7852b54b2247f47 --- /dev/null +++ b/tasks/thorp-remaining/tests/Challenge.lean @@ -0,0 +1,550 @@ +import Mathlib + +namespace OAI + +universe u v + +noncomputable section +open scoped BigOperators +open Filter + +namespace Thorp + +abbrev Position (d : ℕ) := Fin d → Bool +abbrev State (d : ℕ) := Equiv.Perm (Position d) + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Position d → Bool + +instance coinsFintype (d : ℕ) : Fintype (Coins d) := by + cases d <;> simp only [Coins] <;> infer_instance + +instance coinsInhabited (d : ℕ) : Inhabited (Coins d) := by + cases d <;> simp only [Coins] <;> infer_instance + +def pairSwitch (d : ℕ) (c : Position d → Bool) : Equiv.Perm (Bool × Position d) where + toFun p := (p.1 ^^ c p.2, p.2) + invFun p := (p.1 ^^ c p.2, p.2) + left_inv p := by + rcases p with ⟨b, s⟩ + cases b <;> cases h : c s <;> simp [h] + right_inv p := by + rcases p with ⟨b, s⟩ + cases b <;> cases h : c s <;> simp [h] + +def rotate (d : ℕ) : State d := + Equiv.piCongrLeft (fun _ : Fin d => Bool) (finRotate d).symm + +def step : (d : ℕ) → Coins d → State d + | 0, _ => Equiv.refl _ + | d + 1, c => + (((Fin.consEquiv (fun _ : Fin (d + 1) => Bool)).symm.trans + (pairSwitch d c)).trans + (Fin.consEquiv (fun _ : Fin (d + 1) => Bool))).trans (rotate (d + 1)) + +abbrev History (d t : ℕ) := Fin t → Coins d + +def run (d t : ℕ) (ω : History d t) : State d := + ((List.ofFn fun i : Fin t => step d (ω i)).reverse).prod + +def fairMass {Ω : Type u} {α : Type v} [Fintype Ω] (f : Ω → α) (a : α) : ℝ := by + classical + exact (∑ ω : Ω, if f ω = a then (1 : ℝ) else 0) / Fintype.card Ω + +def law (d t : ℕ) : State d → ℝ := fairMass (run d t) + +def uniform (d : ℕ) (_ : State d) : ℝ := 1 / Fintype.card (State d) + +def tv {α : Type u} [Fintype α] (μ ν : α → ℝ) : ℝ := + (1 / 2 : ℝ) * ∑ a : α, |μ a - ν a| + +def distance (d t : ℕ) : ℝ := tv (law d t) (uniform d) + +def lawFrom (d t : ℕ) (g₀ : State d) : State d → ℝ := + fairMass (fun ω : History d t => run d t ω * g₀) + +abbrev LabelList (d k : ℕ) := Fin k ↪ Position d + +def coordinateRun (d t : ℕ) (ω : History d t) : State d := + (rotate d)⁻¹ ^ t * run d t ω + +def images {d k : ℕ} (t : ℕ) (start : State d) (labels : LabelList d k) + (ω : History d t) : LabelList d k := + labels.trans ((coordinateRun d t ω * start).toEmbedding) + +def listTV {d k : ℕ} (t : ℕ) (start : State d) (labels : LabelList d k) : ℝ := + tv (fairMass (images t start labels)) (fun _ => 1 / Fintype.card (LabelList d k)) + +def mixingTime (d : ℕ) : ℕ := sInf {t : ℕ | distance d t ≤ 1 / 4} + +end Thorp + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +end Thorp + +namespace Thorp +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +open scoped BigOperators Classical +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end Thorp +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.Specht +open scoped BigOperators Classical +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +noncomputable def cellRowsEquiv (μ : YoungDiagram) : + Cell μ ≃ (i : Fin (μ.colLen 0)) × Fin (μ.rowLen i) where + toFun x := ⟨rowIndex x,⟨col x,YoungDiagram.mem_iff_lt_rowLen.mp x.2⟩⟩ + invFun p := ⟨(p.1,p.2),YoungDiagram.mem_iff_lt_rowLen.mpr p.2.2⟩ + left_inv x := by apply Subtype.ext; rfl + right_inv p := by rcases p with ⟨⟨i,hi⟩,⟨j,hj⟩⟩; rfl + +lemma card_eq_sum_rowLen (μ : YoungDiagram) : μ.card = ∑ i : Fin (μ.colLen 0), μ.rowLen i := by + rw [←card_cell,Fintype.card_congr (cellRowsEquiv μ),Fintype.card_sigma] + simp only [Fintype.card_fin] + +lemma sum_rowLens (μ : YoungDiagram) : μ.rowLens.sum = μ.card := by + rw [card_eq_sum_rowLen,YoungDiagram.rowLens] + rw [Fin.sum_univ_eq_sum_range] + have hh (n : ℕ) : (List.map μ.rowLen (List.range n)).sum = ∑ i ∈ Finset.range n, μ.rowLen i := by + induction n with + | zero => simp + | succ n ih => simp [List.range_succ,List.map_append,Finset.sum_range_succ,ih] + exact hh _ + +noncomputable def diagramPartition (μ : YoungDiagram) : Nat.Partition μ.card where + parts := μ.rowLens + parts_pos := fun {i} hi => μ.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simp + +noncomputable def partitionDiagram {N : ℕ} (p : Nat.Partition N) : YoungDiagram := + YoungDiagram.ofRowLens (p.parts.sort (· ≥ ·)) (Multiset.pairwise_sort _ _).sortedGE + +lemma partitionDiagram_rowLens {N : ℕ} (p : Nat.Partition N) : + (partitionDiagram p).rowLens = p.parts.sort (· ≥ ·) := by + apply YoungDiagram.rowLens_ofRowLens_eq_self + intro x hx + exact p.parts_pos ((Multiset.mem_sort _).mp hx) + +lemma partitionDiagram_card {N : ℕ} (p : Nat.Partition N) : (partitionDiagram p).card = N := by + rw [←sum_rowLens,partitionDiagram_rowLens] + change (↑(p.parts.sort (· ≥ ·)) : Multiset ℕ).sum = N + rw [Multiset.sort_eq,p.parts_sum] + +lemma partitionDiagram_diagramPartition (μ : YoungDiagram) : + partitionDiagram (diagramPartition μ) = μ := by + apply YoungDiagram.equivListRowLens.injective + apply Subtype.ext + change (partitionDiagram (diagramPartition μ)).rowLens = μ.rowLens + rw [partitionDiagram_rowLens] + change (↑μ.rowLens : Multiset ℕ).sort (· ≥ ·) = μ.rowLens + rw [Multiset.coe_sort,List.mergeSort_eq_self _ μ.rowLens_sorted.pairwise] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def shapePartitionEquiv (N : ℕ) : Shapes N ≃ Nat.Partition N where + toFun μ := { parts := μ.1.rowLens + parts_pos := fun {i} hi => μ.1.pos_of_mem_rowLens i (by simpa using hi) + parts_sum := by simpa using (sum_rowLens μ.1).trans μ.2 } + invFun p := ⟨partitionDiagram p,partitionDiagram_card p⟩ + left_inv μ := by + apply Subtype.ext + obtain ⟨μ,rfl⟩ := μ + exact partitionDiagram_diagramPartition μ + right_inv p := by + apply Nat.Partition.ext + change ((partitionDiagram p).rowLens : Multiset ℕ) = p.parts + rw [partitionDiagram_rowLens,Multiset.sort_eq] + +noncomputable instance (N : ℕ) : Fintype (Shapes N) := Fintype.ofEquiv _ (shapePartitionEquiv N).symm + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end Thorp.Specht +namespace Thorp.LowPlanes +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +open scoped BigOperators Classical +open Specht UnitaryFinite + +noncomputable local instance hsNorm (μ : YoungDiagram) : NormedAddCommGroup (hilbertSpace μ) := inferInstance +noncomputable local instance hsInner (μ : YoungDiagram) : InnerProductSpace ℂ (hilbertSpace μ) := inferInstance +noncomputable local instance hsFinite (μ : YoungDiagram) : FiniteDimensional ℂ (hilbertSpace μ) := inferInstance + +noncomputable def Q (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) + +noncomputable def absoluteTrace {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + (A : V →L[ℂ] V) (P : ℝ) : ℝ := + (LinearMap.trace ℂ V (CFC.rpow (CFC.sqrt (star A * A)) P).toLinearMap).re + +noncomputable def regularTrace (d : ℕ) (P : ℝ) : ℝ := + ∑ μ : Shapes (2^d), (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + absoluteTrace (V := hilbertSpace μ.1) (Q d μ) P + +noncomputable def sweepDistance (d v : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d (v*d) (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +end Thorp.LowPlanes +end ThorpNine.Harmonic + +namespace ThorpNine.Harmonic.Thorp.LowPlanes +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +open scoped BigOperators +open Specht UnitaryFinite +attribute [local instance] hsNorm hsInner hsFinite +def weightedMoment (d r : ℕ) (μ : Shapes (2 ^ d)) : ℝ := + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + (LinearMap.trace ℂ (hilbertSpace μ.1) + ((star (Q d μ) * Q d μ) ^ r).toLinearMap).re + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def signedEntropy (α β : YoungDiagram) : ℝ := + (∑ x : Cell α, Real.log ((α.card + β.card : ℕ) / (α.rowLen (row x) : ℝ))) + + (∑ x : Cell β, Real.log ((α.card + β.card : ℕ) / (β.rowLen (row x) : ℝ))) + +def budgetCoefficient (a : ℝ) (d : ℕ) : ℝ := + a * (1 - 1 / (2 * Real.sqrt d)) + +def remainderBudget (κ : ℝ) (d l : ℕ) : ℝ := + if l = 0 then 0 else + max 0 (budgetCoefficient κ d * l * Real.log (2 ^ d : ℝ) - + l * Real.log ((2 ^ d : ℝ) / l)) + +def logWeightedMoment (d r : ℕ) (μ : Shapes (2 ^ d)) : EReal := + (ENNReal.ofReal (weightedMoment d r μ)).log + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +def densityL2Squared (d t : ℕ) : ℝ := + (Nat.factorial (2 ^ d) : ℝ) * ∑ g : Equiv.Perm (Card d), + (law d t g - 1 / (Nat.factorial (2 ^ d) : ℝ)) ^ 2 + +def densityL2SquaredFrom (d t : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (Nat.factorial (2 ^ d) : ℝ) * ∑ g : Equiv.Perm (Card d), + (law d t (g * σ⁻¹) - 1 / (Nat.factorial (2 ^ d) : ℝ)) ^ 2 + +end ThorpNine.Harmonic.Thorp.LowPlanes + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace ThorpResults +open ThorpNine.Harmonic.Thorp +open ThorpNine.Harmonic.Thorp.Specht +open ThorpNine.Harmonic.Thorp.LowPlanes + +attribute [local instance] hsNorm hsInner hsFinite + +def FrameMain : Prop := + ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, ∀ start : _root_.OAI.Thorp.State d, + _root_.OAI.Thorp.tv (_root_.OAI.Thorp.lawFrom d (32800 * d) start) (_root_.OAI.Thorp.uniform d) < ε + +def InformationMain : Prop := + (∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ k : ℕ, 8 * k ≤ 7 * 2 ^ d → + ∀ (start : _root_.OAI.Thorp.State d) (labels : _root_.OAI.Thorp.LabelList d k), + _root_.OAI.Thorp.listTV (256 * d) start labels < ε) ∧ + (∀ᶠ d : ℕ in atTop, + ∀ k : ℕ, 16 * k ≤ 15 * 2 ^ d → + ∀ (start : _root_.OAI.Thorp.State d) (labels : _root_.OAI.Thorp.LabelList d k), + _root_.OAI.Thorp.listTV (1024 * d) start labels ≤ + Real.rpow ((2 : ℝ) ^ d) (-(3 : ℝ) / 2)) ∧ + (Tendsto (fun d : ℕ => _root_.OAI.Thorp.distance d (2048 * d)) atTop (nhds 0) ∧ + ∀ (d : ℕ) (start : _root_.OAI.Thorp.State d), + _root_.OAI.Thorp.tv (_root_.OAI.Thorp.lawFrom d (2048 * d) start) (_root_.OAI.Thorp.uniform d) = + _root_.OAI.Thorp.distance d (2048 * d)) + +def SpectrumMain : Prop := + ∃ p : ℝ, 0 < p ∧ ∀ d : ℕ, 1 ≤ d → + regularTrace d (2 * p) ≤ 1 + 1 / 16 ∧ + ∀ M : ℕ, p ≤ M → ∀ σ : Equiv.Perm (Card d), sweepDistance d M σ ≤ 1 / 8 + +def SignedMain : Prop := + ∀ η κ : ℝ, 0 < η → ∃ r : ℕ, 1 ≤ r ∧ ∀ d : ℕ, 1 ≤ d → + ∀ (μ : Shapes (2 ^ d)) (α β γ : YoungDiagram), + α.card + β.card + γ.card = 2 ^ d → + logWeightedMoment d r μ ≤ + ((budgetCoefficient η d * signedEntropy α β + + remainderBudget κ d γ.card : ℝ) : EReal) + +def DegreeSavingMain : Prop := + ∃ r : ℕ, Even r ∧ 2 ≤ r ∧ ∃ η : ℝ, 0 < η ∧ + ∀ d (μ : Shapes (2 ^ d)), + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) * + (LinearMap.trace ℂ (hilbertSpace μ.1) + ((Q d μ * star (Q d μ)) ^ r).toLinearMap).re ≤ + (Module.finrank ℂ (hilbertSpace μ.1) : ℝ) ^ (1 - η) + +def FullDensityMain : Prop := + ∃ v : ℕ, 1 ≤ v ∧ ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ σ : Equiv.Perm (Card d), densityL2SquaredFrom d (v * d) σ < ε + +def ForwardMixingMain : Prop := + ∃ v : ℕ, 1 ≤ v ∧ ∀ ε : ℝ, 0 < ε → ∀ᶠ d : ℕ in atTop, + ∀ σ : Equiv.Perm (Card d), sweepDistance d v σ < ε + +def OptimalOrderMain : Prop := + Asymptotics.IsTheta atTop (fun d : ℕ => (_root_.OAI.Thorp.mixingTime d : ℝ)) + (fun d : ℕ => Real.log (2 ^ d : ℝ)) + +end ThorpResults + +namespace ThorpResults +theorem remaining_main : + FrameMain ∧ InformationMain ∧ SpectrumMain ∧ SignedMain ∧ + DegreeSavingMain ∧ FullDensityMain ∧ ForwardMixingMain ∧ OptimalOrderMain := by + sorry +end ThorpResults +end + +end OAI diff --git a/tasks/thorp-remaining/tests/grade.py b/tasks/thorp-remaining/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thorp-remaining/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thorp-remaining/tests/task.json b/tasks/thorp-remaining/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..71cb1058283d98552eff32e0770ac296180a2f38 --- /dev/null +++ b/tasks/thorp-remaining/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThorpRemaining", + "comparator": { + "theorem_names": [ + "OAI.ThorpResults.remaining_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12040 +} \ No newline at end of file diff --git a/tasks/thorp-remaining/tests/test.sh b/tasks/thorp-remaining/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thorp-remaining/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thorp-routing/environment/Dockerfile b/tasks/thorp-routing/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thorp-routing/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thorp-routing/environment/fetch_mathlib.sh b/tasks/thorp-routing/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thorp-routing/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thorp-routing/environment/lake-manifest.json b/tasks/thorp-routing/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thorp-routing/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thorp-routing/environment/lakefile.lean b/tasks/thorp-routing/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thorp-routing/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thorp-routing/environment/lean_setup.sh b/tasks/thorp-routing/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thorp-routing/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thorp-routing/environment/pack_submission.py b/tasks/thorp-routing/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thorp-routing/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thorp-routing/instruction.md b/tasks/thorp-routing/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..5726c4ecfbed70c8d2fca18fa12a1dd4aac1abe0 --- /dev/null +++ b/tasks/thorp-routing/instruction.md @@ -0,0 +1,2630 @@ +# openai/math challenge `ThorpRouting` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `ThorpRouting`, also at `/opt/openai-math/challenges/ThorpRouting.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ThorpNine.Adaptive + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.Casimir +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +end Thorp.Casimir + +namespace Thorp.AdaptiveBounds +open scoped BigOperators Classical +open Casimir + +noncomputable def positiveSquare {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] (T : V →L[ℂ] V) : V →L[ℂ] V := + T * T.adjoint + +noncomputable def F (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) + (rev : Bool) : Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + positiveSquare (V := Specht.hilbertSpace μ) (SparseContact.sweepOperator d μ e rev) + +noncomputable def fourthTrace (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (rev : Bool) : ℝ := + (LinearMap.trace ℂ (Specht.hilbertSpace μ) ((F d μ e rev)^4).toLinearMap).re + +def MainStatement : Prop := + ∃ c c' C c₀ : ℝ, 0 Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Casimir + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +noncomputable def palindromeRowMoment (d : ℕ) {ι : Type*} [Fintype ι] + (e : ι ↪ Card d) (a : ℝ) : ℝ := + finiteMean (fun f : ι ↪ Card d => + ((Fintype.card (ι ↪ Card d):ℝ)*PairRouting.tupleProbability (palindromePerm d) e f)^(1+a)) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.CasimirBounds +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +noncomputable def K (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) + (Specht.relabelledUnitary μ e) (palindromePerm d) + +noncomputable def traceMoment (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (r : ℕ) : ℝ := + (LinearMap.trace ℂ (Specht.hilbertSpace μ) ((K d μ e)^r).toLinearMap).re + +noncomputable def fromDistance (d t : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d t (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +def MainStatement : Prop := + ∃ a C : ℝ, 0 < a ∧ 0 < C ∧ + (∀ d k : ℕ, 1 ≤ k → k ≤ 2^d → ∀ x : Fin k ↪ Card d, + (palindromeRowMoment d x (1/64))^(64/65:ℝ) ≤ + Real.exp (C*levelScale (2^d) k)) ∧ + (∀ (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ), + 0 < μ.card-μ.rowLen 0 → + ‖K d μ e‖ ≤ Real.exp (-a*levelScale (2^d) (μ.card-μ.rowLen 0)) ∧ + (Module.finrank ℂ (Specht.space μ):ℝ) * traceMoment d μ e 65 ≤ + Real.exp (C*levelScale (2^d) (μ.card-μ.rowLen 0))) ∧ + (∃ l : ℕ, 0 < l ∧ ∀ starts : (d : ℕ) → Equiv.Perm (Card d), + Tendsto (fun d => fromDistance d (l*d) (starts d)) atTop (nhds 0)) + +end Thorp.CasimirBounds + +end ThorpNine.Casimir + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Dense + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable def orbitSet (p : Equiv.Perm α) (x : α) : Finset α := + Finset.univ.filter (p.SameCycle x) + +end Thorp + +namespace Thorp.RoutingNetwork +open scoped BigOperators +open Filter +variable {α ι : Type*} [Fintype α] [DecidableEq α] [Fintype ι] [DecidableEq ι] +variable {A : ℕ} + +abbrev SelectedCycle (p : Equiv.Perm (α)) (S : Finset (α)) := + {C : Finset (α) // (∃ x, C = orbitSet p x) ∧ C ⊆ S} + +noncomputable instance (p : Equiv.Perm (α)) (S : Finset (α)) : + Fintype (SelectedCycle p S) := Fintype.ofFinite _ + +end Thorp.RoutingNetwork + +namespace Thorp +open scoped BigOperators +open Filter + +section +variable {β : Type*} [Fintype β] [DecidableEq β] + +def pairLayer (ξ : β → Bool) : Equiv.Perm (Bool × β) where + toFun x := (Bool.xor x.1 (ξ x.2),x.2) + invFun x := (Bool.xor x.1 (ξ x.2),x.2) + left_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + right_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + +end + +def coinStepEquiv (d : ℕ) : (SwitchIndex (d+1) → Bool) ≃ + ((SwitchIndex d → Bool) × (SwitchIndex d → Bool)) × (Card d → Bool) where + toFun ω := ((fun i => ω (Sum.inr (false,i)),fun i => ω (Sum.inr (true,i))), + fun x => ω (Sum.inl x)) + invFun ω := Sum.elim ω.2 (fun bi => if bi.1 then ω.1.2 bi.2 else ω.1.1 bi.2) + left_inv ω := by + funext i + cases i with + | inl x => rfl + | inr bi => cases bi with | mk b i => cases b <;> rfl + right_inv ω := by + rcases ω with ⟨⟨ω₀,ω₁⟩,ξ⟩ + rfl + +def headTailEquiv (d : ℕ) : Card (d+1) ≃ Bool × Card d := + (Fin.consEquiv (fun _ : Fin (d+1) => Bool)).symm + +end Thorp + +namespace Thorp.CycleColoring +open scoped BigOperators +open Filter +variable {α : Type*} [Fintype α] [DecidableEq α] + +def alternatingPerm (p : Equiv.Perm α) : Equiv.Perm (Bool × α) where + toFun x := if x.1 then (false,p x.2) else (true,x.2) + invFun x := if x.1 then (false,x.2) else (true,p.symm x.2) + left_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + right_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + +end Thorp.CycleColoring + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +def required (x : ι → Bool × α) (c : ι → Bool) (i : ι) : Bool := Bool.xor (x i).1 (c i) + +def Compatible (x : ι → Bool × α) (c : ι → Bool) : Prop := + ∀ i j, (x i).2 = (x j).2 → required x c i = required x c j + +def colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : Bool := + Bool.xor (x i).1 (ξ (x i).2) + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma required_colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : + required x (colors x ξ) i = ξ (x i).2 := by + simp only [required,colors] + cases (x i).1 <;> cases ξ (x i).2 <;> rfl + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma colors_compatible (x : ι → Bool × α) (ξ : α → Bool) : Compatible x (colors x ξ) := by + intro i j he + simp only [required_colors,he] + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma Compatible.tail_injective {x : ι ↪ Bool × α} {c : ι → Bool} (hc : Compatible x c) (b : Bool) : + Function.Injective (fun i : {i : ι // c i = b} => (x i.val).2) := by + intro i j he + apply Subtype.ext + apply x.injective + apply Prod.ext + · have hh := hc i j he + simp only [required,i.property,j.property] at hh + cases h₀ : (x i.val).1 <;> cases h₁ : (x j.val).1 <;> cases b <;> simp_all + · exact he + +def childEmbedding (x : ι ↪ Bool × α) (c : ι → Bool) (hc : Compatible x c) (b : Bool) : + {i : ι // c i = b} ↪ α := ⟨fun i => (x i.val).2,hc.tail_injective b⟩ + +noncomputable def labelSet (e : ι ↪ Bool × α) : Finset (Bool × α) := Finset.univ.image e + +def alternatingProjection (p : Bool → Equiv.Perm α) : Equiv.Perm α := (p false).symm * p true + +noncomputable def alternatingCycles (e : ι ↪ Bool × α) (p : Bool → Equiv.Perm α) : ℕ := + Fintype.card (RoutingNetwork.SelectedCycle + (CycleColoring.alternatingPerm (alternatingProjection p)) (labelSet e)) + +def switchedEmbedding (e : ι ↪ Bool × α) (ξ : α → Bool) : ι ↪ Bool × α := + e.trans (pairLayer ξ).toEmbedding + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +def sandwichShuffle {A B C D E F : Type*} : + ((A × B) × C) × ((D × E) × F) ≃ ((A × D) × (B × E)) × (F × C) where + toFun x := (((x.1.1.1,x.2.1.1),(x.1.1.2,x.2.1.2)),(x.2.2,x.1.2)) + invFun x := (((x.1.1.1,x.1.2.1),x.2.2),((x.1.1.2,x.1.2.2),x.2.1)) + left_inv _ := rfl + right_inv _ := rfl + +def benesStepEquiv (d : ℕ) : BenesCoins (d+1) ≃ + (BenesCoins d × BenesCoins d) × ((Card d → Bool) × (Card d → Bool)) := + (Equiv.prodCongr (coinStepEquiv d) (coinStepEquiv d)).trans sandwichShuffle + +noncomputable def palindromeCost : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) + + palindromeCost d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeCost d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end Thorp + +namespace Thorp.DenseTruncation +open scoped BigOperators + +def AdmissibleCycleLaw (j : ℕ) (p : ℕ → ℝ) : Prop := + (∀ l, 0 ≤ p l) ∧ HasSum p 1 ∧ + ∀ l, p l ≤ ((l + 1 : ℕ) : ℝ) / (2 : ℝ) ^ (j - 1) + +noncomputable def h (j : ℕ) : ℝ := + sSup {z : ℝ | ∃ p : ℕ → ℝ, AdmissibleCycleLaw j p ∧ + z = ∑' l : ℕ, p l / ((l + 1 : ℕ) : ℝ)} + +def AdmissibleAllocation (ρ : ℝ) (x : ℕ → ℝ) : Prop := + (∀ j, 0 ≤ x j ∧ x j ≤ 1) ∧ + (∑' j : ℕ, x j / (2 : ℝ) ^ (j + 1)) ≤ ρ + +noncomputable def H (ρ : ℝ) : ℝ := + sSup {z : ℝ | ∃ x : ℕ → ℝ, AdmissibleAllocation ρ x ∧ + z = (1 / 2 : ℝ) * ∑' j : ℕ, h (j + 1) * x j} + +noncomputable def entropyCorrection (ρ : ℝ) : ℝ := + (-ρ - (1 - ρ) * Real.log (1 - ρ)) / (ρ * Real.log 2) + +noncomputable def densityExponent (d r : ℕ) (x : Fin r ↪ Card d) + (ω : BenesCoins d) : ℝ := + palindromeCost d x ω + + Real.log (((2 ^ d).descFactorial r : ℝ) / ((2 : ℝ) ^ d) ^ r) / Real.log 2 + +def MainStatement : Prop := + ∀ ρ : ℝ, 0 < ρ → ∀ ε : ℝ, 0 < ε → + ∃ c : ℝ, 0 < c ∧ ∀ d r : ℕ, 1 ≤ d → 1 ≤ r → + (r : ℝ) / (2 : ℝ) ^ d = ρ → ∀ x : Fin r ↪ Card d, + finiteMean (fun ω : BenesCoins d => + if (r : ℝ) * (H ρ + entropyCorrection ρ + ε) < densityExponent d r x ω + then (1 : ℝ) else 0) ≤ Real.exp (-c * r) + +end Thorp.DenseTruncation + +end ThorpNine.Dense + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Contact + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +def MainStatement : Prop := + ∃ Cstar C : ℝ, 0 < Cstar ∧ 0 < C ∧ + ∀ (d : ℕ), 1 ≤ d → ∀ (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ), + let k := μ.card - μ.rowLen 0 + 1 ≤ k → k < 2^d → ∀ reverse : Bool, + ‖sweepOperator d μ e reverse‖^2 ≤ + min 1 ((Cstar * d * k / (2:ℝ)^d) ^ ((k:ℝ)/2)) ∧ + (k = 1 → sweepOperator d μ e reverse = 0) ∧ + ‖sweepOperator d μ e reverse‖^2 ≤ + C^k * (1+(d:ℝ))^(C*k) * ((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/2) + +end Thorp.SparseContact + +end ThorpNine.Contact + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +end Thorp.StrongSmoothing + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht + +def tailDiagram (μ : YoungDiagram) : YoungDiagram := + YoungDiagram.ofRowLens μ.rowLens.tail μ.rowLens_sorted.pairwise.tail.sortedGE + +end Thorp.StrongTail + +namespace Thorp.Casimir +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +noncomputable def K (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) + (Specht.relabelledUnitary μ e) (palindromePerm d) + +end Thorp.Casimir + +namespace Thorp.HarmonicBounds +open scoped BigOperators Classical +open _root_.OAI.ThorpNine.Harmonic.Thorp.Casimir StrongSmoothing + +abbrev tail (μ : YoungDiagram) := StrongTail.tailDiagram μ + +noncomputable def W (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : ℝ := ‖K d μ e‖ + +noncomputable def tupleTrace (d k : ℕ) (order : Equiv.Perm (Fin d)) (rev : Bool) (p : ℕ) : ℝ := + Matrix.trace ((reflectedKernel d k order rev)^p) + +def MainStatement : Prop := + ∃ c C ζ δ cTail c₁ c₂ : ℝ, ∃ p₀ : ℕ, + 0 ((Fintype.card (Tuples d k):ℝ)* + reflectedKernel d k order rev x y)^(1+δ)) ≤ + Real.exp (C*levelScale (2^d) k)) ∧ + tupleTrace d k order rev p₀ ≤ Real.exp (C*levelScale (2^d) k)) + +end Thorp.HarmonicBounds + +end ThorpNine.Harmonic + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Smoothing + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +noncomputable def regularAbsoluteEvenTrace (d : ℕ) (order : Equiv.Perm (Fin d)) (u : ℕ) : ℝ := + Matrix.trace ((reflectedKernel d (2^d) order false)^u) + +def MainStatement : Prop := + ∃ u : ℕ, 1 ≤ u ∧ ∃ C : ℝ, + (∀ d l : ℕ, l ≤ 2^d → ∀ order : Equiv.Perm (Fin d), ∀ orientation : Bool, + ∀ x y : Tuples d l, + ((reflectedKernel d l order orientation)^u) x y ≤ + Real.exp (C*l)/((2^d).descFactorial l:ℝ)) ∧ + (∀ d : ℕ, ∀ order : Equiv.Perm (Fin d), + regularAbsoluteEvenTrace d order u ≤ Real.exp (C*(2:ℝ)^d)) + +end Thorp.StrongSmoothing + +end ThorpNine.Smoothing + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Tail + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +end Thorp.StrongSmoothing + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht + +def tailDiagram (μ : YoungDiagram) : YoungDiagram := + YoungDiagram.ofRowLens μ.rowLens.tail μ.rowLens_sorted.pairwise.tail.sortedGE + +end Thorp.StrongTail + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open StrongSmoothing + +def DensityAt (p C : ℝ) : Prop := + ∀ (d l : ℕ), l ≤ 2^d → ∀ (order : Equiv.Perm (Fin d)) (rev : Bool) + (x : StrongSmoothing.Tuples d l), + let H := StrongSmoothing.reflectedKernel d l order rev + (Thorp.finiteMean (fun y => ((Fintype.card (StrongSmoothing.Tuples d l):ℝ)*H x y)^p) + ≤ Real.exp (C*l)) ∧ + (Thorp.finiteMean (fun y => ((Fintype.card (StrongSmoothing.Tuples d l):ℝ)*H y x)^p) + ≤ Real.exp (C*l)) ∧ + (((2:ℝ)^d)^l)⁻¹ * (∑ y, ((((2:ℝ)^d)^l)*H x y)^p) ≤ Real.exp (C*l) ∧ + (((2:ℝ)^d)^l)⁻¹ * (∑ y, ((((2:ℝ)^d)^l)*H y x)^p) ≤ Real.exp (C*l) + +end Thorp.StrongTail + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht UnitaryFinite + +def MainStatement : Prop := + ∃ p Cdensity C : ℝ, 1 < p ∧ p ≤ 2 ∧ DensityAt p Cdensity ∧ + ∀ (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) (rev : Bool), + ‖SparseContact.sweepOperator d μ e rev‖^2 ≤ + Real.exp (C*(μ.card-μ.rowLen 0 : ℕ)) * + (Module.finrank ℂ (Specht.space (tailDiagram μ)):ℝ)^(-((p-1)/p)) + +end Thorp.StrongTail + +end ThorpNine.Tail + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.HighTail + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable def orbitSet (p : Equiv.Perm α) (x : α) : Finset α := + Finset.univ.filter (p.SameCycle x) + +end Thorp + +namespace Thorp.RoutingNetwork +open scoped BigOperators +open Filter +variable {α ι : Type*} [Fintype α] [DecidableEq α] [Fintype ι] [DecidableEq ι] +variable {A : ℕ} + +abbrev SelectedCycle (p : Equiv.Perm (α)) (S : Finset (α)) := + {C : Finset (α) // (∃ x, C = orbitSet p x) ∧ C ⊆ S} + +noncomputable instance (p : Equiv.Perm (α)) (S : Finset (α)) : + Fintype (SelectedCycle p S) := Fintype.ofFinite _ + +end Thorp.RoutingNetwork + +namespace Thorp +open scoped BigOperators +open Filter + +def cardSplit : (r s : ℕ) → Card (s+r) ≃ Card r × Card s + | 0, s => + { toFun := fun x => ((fun i => Fin.elim0 i), x) + invFun := fun x => x.2 + left_inv := fun _ => rfl + right_inv := fun x => by + apply Prod.ext + · exact Subsingleton.elim _ _ + · rfl } + | r+1, s => + { toFun := fun x => (Fin.cons (x 0) ((cardSplit r s (Fin.tail x)).1), + (cardSplit r s (Fin.tail x)).2) + invFun := fun x => Fin.cons (x.1 0) ((cardSplit r s).symm (Fin.tail x.1,x.2)) + left_inv := by + intro x + simp only [Fin.cons_zero, Fin.tail_cons, Prod.mk.eta, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv := by + intro x + simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] } + +def assembleBits : (r s : ℕ) → (Card r × SwitchIndex s → Bool) → + (Card s × SwitchIndex r → Bool) → SwitchIndex (s+r) → Bool + | 0, _, lo, _, i => lo ((fun j => Fin.elim0 j), i) + | r+1, s, _, hi, Sum.inl y => hi ((cardSplit r s y).2,Sum.inl (cardSplit r s y).1) + | r+1, s, lo, hi, Sum.inr (b,i) => assembleBits r s + (fun j => lo (Fin.cons b j.1,j.2)) (fun j => hi (j.1,Sum.inr (b,j.2))) i + + +section +variable {β : Type*} [Fintype β] [DecidableEq β] + +def pairLayer (ξ : β → Bool) : Equiv.Perm (Bool × β) where + toFun x := (Bool.xor x.1 (ξ x.2),x.2) + invFun x := (Bool.xor x.1 (ξ x.2),x.2) + left_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + right_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + +end + +def coinStepEquiv (d : ℕ) : (SwitchIndex (d+1) → Bool) ≃ + ((SwitchIndex d → Bool) × (SwitchIndex d → Bool)) × (Card d → Bool) where + toFun ω := ((fun i => ω (Sum.inr (false,i)),fun i => ω (Sum.inr (true,i))), + fun x => ω (Sum.inl x)) + invFun ω := Sum.elim ω.2 (fun bi => if bi.1 then ω.1.2 bi.2 else ω.1.1 bi.2) + left_inv ω := by + funext i + cases i with + | inl x => rfl + | inr bi => cases bi with | mk b i => cases b <;> rfl + right_inv ω := by + rcases ω with ⟨⟨ω₀,ω₁⟩,ξ⟩ + rfl + +def headTailEquiv (d : ℕ) : Card (d+1) ≃ Bool × Card d := + (Fin.consEquiv (fun _ : Fin (d+1) => Bool)).symm + +end Thorp + +namespace Thorp.CycleColoring +open scoped BigOperators +open Filter +variable {α : Type*} [Fintype α] [DecidableEq α] + +def alternatingPerm (p : Equiv.Perm α) : Equiv.Perm (Bool × α) where + toFun x := if x.1 then (false,p x.2) else (true,x.2) + invFun x := if x.1 then (false,x.2) else (true,p.symm x.2) + left_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + right_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + +end Thorp.CycleColoring + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +def required (x : ι → Bool × α) (c : ι → Bool) (i : ι) : Bool := Bool.xor (x i).1 (c i) + +def Compatible (x : ι → Bool × α) (c : ι → Bool) : Prop := + ∀ i j, (x i).2 = (x j).2 → required x c i = required x c j + +def colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : Bool := + Bool.xor (x i).1 (ξ (x i).2) + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma required_colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : + required x (colors x ξ) i = ξ (x i).2 := by + simp only [required,colors] + cases (x i).1 <;> cases ξ (x i).2 <;> rfl + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma colors_compatible (x : ι → Bool × α) (ξ : α → Bool) : Compatible x (colors x ξ) := by + intro i j he + simp only [required_colors,he] + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma Compatible.tail_injective {x : ι ↪ Bool × α} {c : ι → Bool} (hc : Compatible x c) (b : Bool) : + Function.Injective (fun i : {i : ι // c i = b} => (x i.val).2) := by + intro i j he + apply Subtype.ext + apply x.injective + apply Prod.ext + · have hh := hc i j he + simp only [required,i.property,j.property] at hh + cases h₀ : (x i.val).1 <;> cases h₁ : (x j.val).1 <;> cases b <;> simp_all + · exact he + +def childEmbedding (x : ι ↪ Bool × α) (c : ι → Bool) (hc : Compatible x c) (b : Bool) : + {i : ι // c i = b} ↪ α := ⟨fun i => (x i.val).2,hc.tail_injective b⟩ + +noncomputable def labelSet (e : ι ↪ Bool × α) : Finset (Bool × α) := Finset.univ.image e + +def alternatingProjection (p : Bool → Equiv.Perm α) : Equiv.Perm α := (p false).symm * p true + +noncomputable def alternatingCycles (e : ι ↪ Bool × α) (p : Bool → Equiv.Perm α) : ℕ := + Fintype.card (RoutingNetwork.SelectedCycle + (CycleColoring.alternatingPerm (alternatingProjection p)) (labelSet e)) + +def switchedEmbedding (e : ι ↪ Bool × α) (ξ : α → Bool) : ι ↪ Bool × α := + e.trans (pairLayer ξ).toEmbedding + +end Thorp.PairRouting + +namespace Thorp + +section +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +def sandwichShuffle {A B C D E F : Type*} : + ((A × B) × C) × ((D × E) × F) ≃ ((A × D) × (B × E)) × (F × C) where + toFun x := (((x.1.1.1,x.2.1.1),(x.1.1.2,x.2.1.2)),(x.2.2,x.1.2)) + invFun x := (((x.1.1.1,x.1.2.1),x.2.2),((x.1.1.2,x.1.2.2),x.2.1)) + left_inv _ := rfl + right_inv _ := rfl + +def benesStepEquiv (d : ℕ) : BenesCoins (d+1) ≃ + (BenesCoins d × BenesCoins d) × ((Card d → Bool) × (Card d → Bool)) := + (Equiv.prodCongr (coinStepEquiv d) (coinStepEquiv d)).trans sandwichShuffle + +noncomputable def palindromeCost : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) + + palindromeCost d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeCost d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end + +noncomputable def palindromeLowCost (H : ℕ) : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + (if d+1 ≤ H then PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) else 0) + + palindromeLowCost H d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeLowCost H d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end Thorp + +namespace Thorp.HighHeight +open scoped BigOperators Classical + +noncomputable def highCost (J d : ℕ) {ι : Type*} [Fintype ι] + (x : ι ↪ Card d) (ω : BenesCoins d) : ℕ := + palindromeCost d x ω-palindromeLowCost (J-1) d x ω + +def MainStatement : Prop := + ∃ b δ C : ℝ, 0 ((2:ℝ)^b)^(highCost J d x ω)))/Real.log 2 ≤ + C*k*(2:ℝ)^(-b*J)) ∧ + (∀ d k : ℕ, ∀ x : Fin k ↪ Card d, + Real.log (finiteMean (fun ω : BenesCoins d => ((2:ℝ)^b)^(palindromeCost d x ω)))/Real.log 2 ≤ + C*k*((k:ℝ)/(2:ℝ)^d)^δ) ∧ + (∀ r s k : ℕ, ∀ x : Fin k ↪ Card (s+r), ∀ J : ℕ, J₀≤J → 2*s + ((2:ℝ)^b)^(highCost J (s+r) x (assembleBits r s lo hi,X))))/Real.log 2 ≤ + C*k*(2:ℝ)^(-b*J)) + +end Thorp.HighHeight + +end ThorpNine.HighTail + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.SparseSaving + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.SparseRegime + +def MainStatement : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ 0 < d₀ ∧ + ∀ (d : ℕ) (μ : YoungDiagram) (e : Thorp.Card d ≃ Thorp.Specht.Cell μ), + let k := μ.card - μ.rowLen 0 + 1 ≤ k → k < 2^d → (d:ℝ)^((3:ℝ)/4) ≤ Real.log ((2:ℝ)^d/k) → + ∀ rev : Bool, + ‖Thorp.SparseContact.sweepOperator d μ e rev‖^2 ≤ + Real.exp (C*k)*((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/4) ∧ + (d₀ ≤ d → ‖Thorp.SparseContact.sweepOperator d μ e rev‖^2 ≤ + ((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/4)) + +end Thorp.SparseRegime + +end ThorpNine.SparseSaving + +theorem ThorpNine.main : + ThorpNine.Adaptive.Thorp.AdaptiveBounds.MainStatement ∧ + ThorpNine.Casimir.Thorp.CasimirBounds.MainStatement ∧ + ThorpNine.Dense.Thorp.DenseTruncation.MainStatement ∧ + ThorpNine.Contact.Thorp.SparseContact.MainStatement ∧ + ThorpNine.Harmonic.Thorp.HarmonicBounds.MainStatement ∧ + ThorpNine.Smoothing.Thorp.StrongSmoothing.MainStatement ∧ + ThorpNine.Tail.Thorp.StrongTail.MainStatement ∧ + ThorpNine.HighTail.Thorp.HighHeight.MainStatement ∧ + ThorpNine.SparseSaving.Thorp.SparseRegime.MainStatement := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThorpRouting.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThorpNine.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thorp-routing/solution/closure.txt b/tasks/thorp-routing/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b2e8d590740b10f96e13d3ac08d0182065b6e123 --- /dev/null +++ b/tasks/thorp-routing/solution/closure.txt @@ -0,0 +1,170 @@ +OAI.Probability.ThorpRouting.Adaptive.AlternatingPerm +OAI.Probability.ThorpRouting.Adaptive.AssignmentSlots +OAI.Probability.ThorpRouting.Adaptive.BenesCoins +OAI.Probability.ThorpRouting.Adaptive.BlockProduct +OAI.Probability.ThorpRouting.Adaptive.Coins +OAI.Probability.ThorpRouting.Adaptive.ExposedCoins +OAI.Probability.ThorpRouting.Adaptive.HeightDecay +OAI.Probability.ThorpRouting.Adaptive.InputTree +OAI.Probability.ThorpRouting.Adaptive.InsertionPerm +OAI.Probability.ThorpRouting.Adaptive.Main +OAI.Probability.ThorpRouting.Adaptive.MainStatement +OAI.Probability.ThorpRouting.Adaptive.Model +OAI.Probability.ThorpRouting.Adaptive.ModifiedReverseEquiv +OAI.Probability.ThorpRouting.Adaptive.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Adaptive.ModifiedStageEquiv +OAI.Probability.ThorpRouting.Adaptive.ParallelFollow +OAI.Probability.ThorpRouting.Adaptive.ParallelFreshPre +OAI.Probability.ThorpRouting.Adaptive.PriorPaths +OAI.Probability.ThorpRouting.Adaptive.Representative +OAI.Probability.ThorpRouting.Adaptive.RotationMeeting +OAI.Probability.ThorpRouting.Adaptive.ShapePartitionEquiv +OAI.Probability.ThorpRouting.Adaptive.SiteEquiv +OAI.Probability.ThorpRouting.Adaptive.TailShapes +OAI.Probability.ThorpRouting.Adaptive.TupleKernel +OAI.Probability.ThorpRouting.Adaptive.TypedSet +OAI.Probability.ThorpRouting.Casimir.AlternatingPerm +OAI.Probability.ThorpRouting.Casimir.AssignmentSlots +OAI.Probability.ThorpRouting.Casimir.AverageMap +OAI.Probability.ThorpRouting.Casimir.BlockProduct +OAI.Probability.ThorpRouting.Casimir.CutoffMass +OAI.Probability.ThorpRouting.Casimir.Distance +OAI.Probability.ThorpRouting.Casimir.ExposedCoins +OAI.Probability.ThorpRouting.Casimir.InputTree +OAI.Probability.ThorpRouting.Casimir.InsertionPerm +OAI.Probability.ThorpRouting.Casimir.Main +OAI.Probability.ThorpRouting.Casimir.Model +OAI.Probability.ThorpRouting.Casimir.ModifiedReverseCoins +OAI.Probability.ThorpRouting.Casimir.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Casimir.PairAssembleEquiv +OAI.Probability.ThorpRouting.Casimir.PalindromeFamilyCost +OAI.Probability.ThorpRouting.Casimir.ParallelFollow +OAI.Probability.ThorpRouting.Casimir.PriorPaths +OAI.Probability.ThorpRouting.Casimir.RotationMeeting +OAI.Probability.ThorpRouting.Casimir.SandwichShuffle +OAI.Probability.ThorpRouting.Casimir.Shapes +OAI.Probability.ThorpRouting.Casimir.Site +OAI.Probability.ThorpRouting.Casimir.TailShapes +OAI.Probability.ThorpRouting.Casimir.TypedSet +OAI.Probability.ThorpRouting.Casimir.ZeroExtend +OAI.Probability.ThorpRouting.Contact.AlternatingPerm +OAI.Probability.ThorpRouting.Contact.AssignmentSlots +OAI.Probability.ThorpRouting.Contact.BenesCoins +OAI.Probability.ThorpRouting.Contact.BlockProduct +OAI.Probability.ThorpRouting.Contact.Coins +OAI.Probability.ThorpRouting.Contact.ExposedCoins +OAI.Probability.ThorpRouting.Contact.HeightDecay +OAI.Probability.ThorpRouting.Contact.InputTree +OAI.Probability.ThorpRouting.Contact.Main +OAI.Probability.ThorpRouting.Contact.Model +OAI.Probability.ThorpRouting.Contact.ModifiedReverseEquiv +OAI.Probability.ThorpRouting.Contact.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Contact.ModifiedStageEquiv +OAI.Probability.ThorpRouting.Contact.ParallelFollow +OAI.Probability.ThorpRouting.Contact.ParallelFreshPre +OAI.Probability.ThorpRouting.Contact.PriorPaths +OAI.Probability.ThorpRouting.Contact.Representative +OAI.Probability.ThorpRouting.Contact.RotationMeeting +OAI.Probability.ThorpRouting.Contact.ShapePartitionEquiv +OAI.Probability.ThorpRouting.Dense.AssignmentSlots +OAI.Probability.ThorpRouting.Dense.Coins +OAI.Probability.ThorpRouting.Dense.ColoredEmbedding +OAI.Probability.ThorpRouting.Dense.CutoffMass +OAI.Probability.ThorpRouting.Dense.ExposedCoins +OAI.Probability.ThorpRouting.Dense.Main +OAI.Probability.ThorpRouting.Dense.Model +OAI.Probability.ThorpRouting.Dense.PalindromeFamilyCost +OAI.Probability.ThorpRouting.Dense.ParallelFollow +OAI.Probability.ThorpRouting.Dense.PriorPaths +OAI.Probability.ThorpRouting.Dense.ProjectCycle +OAI.Probability.ThorpRouting.Dense.RotationCharge +OAI.Probability.ThorpRouting.Dense.SingleSlotsEquiv +OAI.Probability.ThorpRouting.Harmonic.AlternatingPerm +OAI.Probability.ThorpRouting.Harmonic.AssignmentSlots +OAI.Probability.ThorpRouting.Harmonic.AverageMap +OAI.Probability.ThorpRouting.Harmonic.BlockProduct +OAI.Probability.ThorpRouting.Harmonic.Coins +OAI.Probability.ThorpRouting.Harmonic.CutoffMass +OAI.Probability.ThorpRouting.Harmonic.ExposedCoins +OAI.Probability.ThorpRouting.Harmonic.InputTree +OAI.Probability.ThorpRouting.Harmonic.InsertionPerm +OAI.Probability.ThorpRouting.Harmonic.Main +OAI.Probability.ThorpRouting.Harmonic.Model +OAI.Probability.ThorpRouting.Harmonic.ModifiedReverseCoins +OAI.Probability.ThorpRouting.Harmonic.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Harmonic.PairAssembleEquiv +OAI.Probability.ThorpRouting.Harmonic.PalindromeFamilyCost +OAI.Probability.ThorpRouting.Harmonic.ParallelFollow +OAI.Probability.ThorpRouting.Harmonic.PriorPaths +OAI.Probability.ThorpRouting.Harmonic.RotationMeeting +OAI.Probability.ThorpRouting.Harmonic.SandwichShuffle +OAI.Probability.ThorpRouting.Harmonic.Shapes +OAI.Probability.ThorpRouting.Harmonic.Site +OAI.Probability.ThorpRouting.Harmonic.TailShapes +OAI.Probability.ThorpRouting.Harmonic.TypedSet +OAI.Probability.ThorpRouting.Harmonic.ZeroExtend +OAI.Probability.ThorpRouting.HighTail.AssignmentSlots +OAI.Probability.ThorpRouting.HighTail.Coins +OAI.Probability.ThorpRouting.HighTail.ColoredEmbedding +OAI.Probability.ThorpRouting.HighTail.CutoffMass +OAI.Probability.ThorpRouting.HighTail.ExposedCoins +OAI.Probability.ThorpRouting.HighTail.Main +OAI.Probability.ThorpRouting.HighTail.Model +OAI.Probability.ThorpRouting.HighTail.ParallelFollow +OAI.Probability.ThorpRouting.HighTail.PriorPaths +OAI.Probability.ThorpRouting.HighTail.ProjectCycle +OAI.Probability.ThorpRouting.HighTail.RotationMeeting +OAI.Probability.ThorpRouting.Main +OAI.Probability.ThorpRouting.Smoothing.AlternatingPerm +OAI.Probability.ThorpRouting.Smoothing.AssignmentSlots +OAI.Probability.ThorpRouting.Smoothing.BenesCoins +OAI.Probability.ThorpRouting.Smoothing.Coins +OAI.Probability.ThorpRouting.Smoothing.ExposedCoins +OAI.Probability.ThorpRouting.Smoothing.Main +OAI.Probability.ThorpRouting.Smoothing.Model +OAI.Probability.ThorpRouting.Smoothing.ParallelFollow +OAI.Probability.ThorpRouting.Smoothing.ParallelFreshPre +OAI.Probability.ThorpRouting.Smoothing.PriorPaths +OAI.Probability.ThorpRouting.Smoothing.RotationCharge +OAI.Probability.ThorpRouting.SparseSaving.AlternatingPerm +OAI.Probability.ThorpRouting.SparseSaving.AssignmentSlots +OAI.Probability.ThorpRouting.SparseSaving.BenesCoins +OAI.Probability.ThorpRouting.SparseSaving.BlockProduct +OAI.Probability.ThorpRouting.SparseSaving.Coins +OAI.Probability.ThorpRouting.SparseSaving.ExposedCoins +OAI.Probability.ThorpRouting.SparseSaving.HeightDecay +OAI.Probability.ThorpRouting.SparseSaving.InputTree +OAI.Probability.ThorpRouting.SparseSaving.Main +OAI.Probability.ThorpRouting.SparseSaving.Model +OAI.Probability.ThorpRouting.SparseSaving.ModifiedReverseEquiv +OAI.Probability.ThorpRouting.SparseSaving.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.SparseSaving.ModifiedStageEquiv +OAI.Probability.ThorpRouting.SparseSaving.ParallelFollow +OAI.Probability.ThorpRouting.SparseSaving.ParallelFreshPre +OAI.Probability.ThorpRouting.SparseSaving.PriorPaths +OAI.Probability.ThorpRouting.SparseSaving.Representative +OAI.Probability.ThorpRouting.SparseSaving.RotationMeeting +OAI.Probability.ThorpRouting.SparseSaving.ShapePartitionEquiv +OAI.Probability.ThorpRouting.Tail.AlternatingPerm +OAI.Probability.ThorpRouting.Tail.AssignmentSlots +OAI.Probability.ThorpRouting.Tail.BenesCoins +OAI.Probability.ThorpRouting.Tail.BlockProduct +OAI.Probability.ThorpRouting.Tail.Coins +OAI.Probability.ThorpRouting.Tail.ExposedCoins +OAI.Probability.ThorpRouting.Tail.HeightDecay +OAI.Probability.ThorpRouting.Tail.InputTree +OAI.Probability.ThorpRouting.Tail.InsertionPerm +OAI.Probability.ThorpRouting.Tail.Main +OAI.Probability.ThorpRouting.Tail.MainStatement +OAI.Probability.ThorpRouting.Tail.Model +OAI.Probability.ThorpRouting.Tail.ModifiedReverseEquiv +OAI.Probability.ThorpRouting.Tail.ModifiedRoutingMoment +OAI.Probability.ThorpRouting.Tail.ModifiedStageEquiv +OAI.Probability.ThorpRouting.Tail.ParallelFollow +OAI.Probability.ThorpRouting.Tail.ParallelFreshPre +OAI.Probability.ThorpRouting.Tail.PriorPaths +OAI.Probability.ThorpRouting.Tail.Representative +OAI.Probability.ThorpRouting.Tail.RotationMeeting +OAI.Probability.ThorpRouting.Tail.ShapePartitionEquiv +OAI.Probability.ThorpRouting.Tail.TailShapes +OAI.Probability.ThorpRouting.Tail.TypedMarks diff --git a/tasks/thorp-routing/solution/reference.py b/tasks/thorp-routing/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thorp-routing/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thorp-routing/solution/solve.sh b/tasks/thorp-routing/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6753c253469976f3be6d4863c62f75561accd5c1 --- /dev/null +++ b/tasks/thorp-routing/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThorpRouting, i.e. module OAI.Probability.ThorpRouting.Main and the +# 170 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThorpRouting.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThorpRouting" diff --git a/tasks/thorp-routing/task.toml b/tasks/thorp-routing/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..32cba81b0a8b3fb67bea1c2e50489d6b715efb33 --- /dev/null +++ b/tasks/thorp-routing/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thorp-routing" +version = "1.0.0" +description = "Prove ThorpRouting (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThorpRouting.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThorpRouting" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThorpNine.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThorpRouting.Main" +reference_modules = 170 +reference_lean_bytes = 6581773 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1374 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17623 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thorp-routing/tests/Challenge.lean b/tasks/thorp-routing/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e2f66a0bb06de84438833f901acef28d156f23c5 --- /dev/null +++ b/tasks/thorp-routing/tests/Challenge.lean @@ -0,0 +1,2579 @@ +import Mathlib + +namespace OAI + +namespace ThorpNine.Adaptive + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.Casimir +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +end Thorp.Casimir + +namespace Thorp.AdaptiveBounds +open scoped BigOperators Classical +open Casimir + +noncomputable def positiveSquare {V : Type*} [NormedAddCommGroup V] + [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] (T : V →L[ℂ] V) : V →L[ℂ] V := + T * T.adjoint + +noncomputable def F (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) + (rev : Bool) : Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + positiveSquare (V := Specht.hilbertSpace μ) (SparseContact.sweepOperator d μ e rev) + +noncomputable def fourthTrace (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (rev : Bool) : ℝ := + (LinearMap.trace ℂ (Specht.hilbertSpace μ) ((F d μ e rev)^4).toLinearMap).re + +def MainStatement : Prop := + ∃ c c' C c₀ : ℝ, 0 Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Casimir + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +noncomputable def law (d t : ℕ) (g : Equiv.Perm (Card d)) : ℝ := + (Fintype.card {ω : Fin t → Coins d // run d t ω = g} : ℝ) / + (Fintype.card (Fin t → Coins d) : ℝ) + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +noncomputable def palindromeRowMoment (d : ℕ) {ι : Type*} [Fintype ι] + (e : ι ↪ Card d) (a : ℝ) : ℝ := + finiteMean (fun f : ι ↪ Card d => + ((Fintype.card (ι ↪ Card d):ℝ)*PairRouting.tupleProbability (palindromePerm d) e f)^(1+a)) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.CasimirBounds +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +noncomputable def K (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) + (Specht.relabelledUnitary μ e) (palindromePerm d) + +noncomputable def traceMoment (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (r : ℕ) : ℝ := + (LinearMap.trace ℂ (Specht.hilbertSpace μ) ((K d μ e)^r).toLinearMap).re + +noncomputable def fromDistance (d t : ℕ) (σ : Equiv.Perm (Card d)) : ℝ := + (1/2:ℝ) * ∑ g : Equiv.Perm (Card d), + |law d t (g*σ⁻¹) - 1/(Nat.factorial (2^d):ℝ)| + +def MainStatement : Prop := + ∃ a C : ℝ, 0 < a ∧ 0 < C ∧ + (∀ d k : ℕ, 1 ≤ k → k ≤ 2^d → ∀ x : Fin k ↪ Card d, + (palindromeRowMoment d x (1/64))^(64/65:ℝ) ≤ + Real.exp (C*levelScale (2^d) k)) ∧ + (∀ (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ), + 0 < μ.card-μ.rowLen 0 → + ‖K d μ e‖ ≤ Real.exp (-a*levelScale (2^d) (μ.card-μ.rowLen 0)) ∧ + (Module.finrank ℂ (Specht.space μ):ℝ) * traceMoment d μ e 65 ≤ + Real.exp (C*levelScale (2^d) (μ.card-μ.rowLen 0))) ∧ + (∃ l : ℕ, 0 < l ∧ ∀ starts : (d : ℕ) → Equiv.Perm (Card d), + Tendsto (fun d => fromDistance d (l*d) (starts d)) atTop (nhds 0)) + +end Thorp.CasimirBounds + +end ThorpNine.Casimir + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Dense + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable def orbitSet (p : Equiv.Perm α) (x : α) : Finset α := + Finset.univ.filter (p.SameCycle x) + +end Thorp + +namespace Thorp.RoutingNetwork +open scoped BigOperators +open Filter +variable {α ι : Type*} [Fintype α] [DecidableEq α] [Fintype ι] [DecidableEq ι] +variable {A : ℕ} + +abbrev SelectedCycle (p : Equiv.Perm (α)) (S : Finset (α)) := + {C : Finset (α) // (∃ x, C = orbitSet p x) ∧ C ⊆ S} + +noncomputable instance (p : Equiv.Perm (α)) (S : Finset (α)) : + Fintype (SelectedCycle p S) := Fintype.ofFinite _ + +end Thorp.RoutingNetwork + +namespace Thorp +open scoped BigOperators +open Filter + +section +variable {β : Type*} [Fintype β] [DecidableEq β] + +def pairLayer (ξ : β → Bool) : Equiv.Perm (Bool × β) where + toFun x := (Bool.xor x.1 (ξ x.2),x.2) + invFun x := (Bool.xor x.1 (ξ x.2),x.2) + left_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + right_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + +end + +def coinStepEquiv (d : ℕ) : (SwitchIndex (d+1) → Bool) ≃ + ((SwitchIndex d → Bool) × (SwitchIndex d → Bool)) × (Card d → Bool) where + toFun ω := ((fun i => ω (Sum.inr (false,i)),fun i => ω (Sum.inr (true,i))), + fun x => ω (Sum.inl x)) + invFun ω := Sum.elim ω.2 (fun bi => if bi.1 then ω.1.2 bi.2 else ω.1.1 bi.2) + left_inv ω := by + funext i + cases i with + | inl x => rfl + | inr bi => cases bi with | mk b i => cases b <;> rfl + right_inv ω := by + rcases ω with ⟨⟨ω₀,ω₁⟩,ξ⟩ + rfl + +def headTailEquiv (d : ℕ) : Card (d+1) ≃ Bool × Card d := + (Fin.consEquiv (fun _ : Fin (d+1) => Bool)).symm + +end Thorp + +namespace Thorp.CycleColoring +open scoped BigOperators +open Filter +variable {α : Type*} [Fintype α] [DecidableEq α] + +def alternatingPerm (p : Equiv.Perm α) : Equiv.Perm (Bool × α) where + toFun x := if x.1 then (false,p x.2) else (true,x.2) + invFun x := if x.1 then (false,x.2) else (true,p.symm x.2) + left_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + right_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + +end Thorp.CycleColoring + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +def required (x : ι → Bool × α) (c : ι → Bool) (i : ι) : Bool := Bool.xor (x i).1 (c i) + +def Compatible (x : ι → Bool × α) (c : ι → Bool) : Prop := + ∀ i j, (x i).2 = (x j).2 → required x c i = required x c j + +def colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : Bool := + Bool.xor (x i).1 (ξ (x i).2) + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma required_colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : + required x (colors x ξ) i = ξ (x i).2 := by + simp only [required,colors] + cases (x i).1 <;> cases ξ (x i).2 <;> rfl + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma colors_compatible (x : ι → Bool × α) (ξ : α → Bool) : Compatible x (colors x ξ) := by + intro i j he + simp only [required_colors,he] + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma Compatible.tail_injective {x : ι ↪ Bool × α} {c : ι → Bool} (hc : Compatible x c) (b : Bool) : + Function.Injective (fun i : {i : ι // c i = b} => (x i.val).2) := by + intro i j he + apply Subtype.ext + apply x.injective + apply Prod.ext + · have hh := hc i j he + simp only [required,i.property,j.property] at hh + cases h₀ : (x i.val).1 <;> cases h₁ : (x j.val).1 <;> cases b <;> simp_all + · exact he + +def childEmbedding (x : ι ↪ Bool × α) (c : ι → Bool) (hc : Compatible x c) (b : Bool) : + {i : ι // c i = b} ↪ α := ⟨fun i => (x i.val).2,hc.tail_injective b⟩ + +noncomputable def labelSet (e : ι ↪ Bool × α) : Finset (Bool × α) := Finset.univ.image e + +def alternatingProjection (p : Bool → Equiv.Perm α) : Equiv.Perm α := (p false).symm * p true + +noncomputable def alternatingCycles (e : ι ↪ Bool × α) (p : Bool → Equiv.Perm α) : ℕ := + Fintype.card (RoutingNetwork.SelectedCycle + (CycleColoring.alternatingPerm (alternatingProjection p)) (labelSet e)) + +def switchedEmbedding (e : ι ↪ Bool × α) (ξ : α → Bool) : ι ↪ Bool × α := + e.trans (pairLayer ξ).toEmbedding + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +def sandwichShuffle {A B C D E F : Type*} : + ((A × B) × C) × ((D × E) × F) ≃ ((A × D) × (B × E)) × (F × C) where + toFun x := (((x.1.1.1,x.2.1.1),(x.1.1.2,x.2.1.2)),(x.2.2,x.1.2)) + invFun x := (((x.1.1.1,x.1.2.1),x.2.2),((x.1.1.2,x.1.2.2),x.2.1)) + left_inv _ := rfl + right_inv _ := rfl + +def benesStepEquiv (d : ℕ) : BenesCoins (d+1) ≃ + (BenesCoins d × BenesCoins d) × ((Card d → Bool) × (Card d → Bool)) := + (Equiv.prodCongr (coinStepEquiv d) (coinStepEquiv d)).trans sandwichShuffle + +noncomputable def palindromeCost : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) + + palindromeCost d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeCost d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end Thorp + +namespace Thorp.DenseTruncation +open scoped BigOperators + +def AdmissibleCycleLaw (j : ℕ) (p : ℕ → ℝ) : Prop := + (∀ l, 0 ≤ p l) ∧ HasSum p 1 ∧ + ∀ l, p l ≤ ((l + 1 : ℕ) : ℝ) / (2 : ℝ) ^ (j - 1) + +noncomputable def h (j : ℕ) : ℝ := + sSup {z : ℝ | ∃ p : ℕ → ℝ, AdmissibleCycleLaw j p ∧ + z = ∑' l : ℕ, p l / ((l + 1 : ℕ) : ℝ)} + +def AdmissibleAllocation (ρ : ℝ) (x : ℕ → ℝ) : Prop := + (∀ j, 0 ≤ x j ∧ x j ≤ 1) ∧ + (∑' j : ℕ, x j / (2 : ℝ) ^ (j + 1)) ≤ ρ + +noncomputable def H (ρ : ℝ) : ℝ := + sSup {z : ℝ | ∃ x : ℕ → ℝ, AdmissibleAllocation ρ x ∧ + z = (1 / 2 : ℝ) * ∑' j : ℕ, h (j + 1) * x j} + +noncomputable def entropyCorrection (ρ : ℝ) : ℝ := + (-ρ - (1 - ρ) * Real.log (1 - ρ)) / (ρ * Real.log 2) + +noncomputable def densityExponent (d r : ℕ) (x : Fin r ↪ Card d) + (ω : BenesCoins d) : ℝ := + palindromeCost d x ω + + Real.log (((2 ^ d).descFactorial r : ℝ) / ((2 : ℝ) ^ d) ^ r) / Real.log 2 + +def MainStatement : Prop := + ∀ ρ : ℝ, 0 < ρ → ∀ ε : ℝ, 0 < ε → + ∃ c : ℝ, 0 < c ∧ ∀ d r : ℕ, 1 ≤ d → 1 ≤ r → + (r : ℝ) / (2 : ℝ) ^ d = ρ → ∀ x : Fin r ↪ Card d, + finiteMean (fun ω : BenesCoins d => + if (r : ℝ) * (H ρ + entropyCorrection ρ + ε) < densityExponent d r x ω + then (1 : ℝ) else 0) ≤ Real.exp (-c * r) + +end Thorp.DenseTruncation + +end ThorpNine.Dense + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Contact + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +def MainStatement : Prop := + ∃ Cstar C : ℝ, 0 < Cstar ∧ 0 < C ∧ + ∀ (d : ℕ), 1 ≤ d → ∀ (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ), + let k := μ.card - μ.rowLen 0 + 1 ≤ k → k < 2^d → ∀ reverse : Bool, + ‖sweepOperator d μ e reverse‖^2 ≤ + min 1 ((Cstar * d * k / (2:ℝ)^d) ^ ((k:ℝ)/2)) ∧ + (k = 1 → sweepOperator d μ e reverse = 0) ∧ + ‖sweepOperator d μ e reverse‖^2 ≤ + C^k * (1+(d:ℝ))^(C*k) * ((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/2) + +end Thorp.SparseContact + +end ThorpNine.Contact + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Harmonic + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +end Thorp.StrongSmoothing + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht + +def tailDiagram (μ : YoungDiagram) : YoungDiagram := + YoungDiagram.ofRowLens μ.rowLens.tail μ.rowLens_sorted.pairwise.tail.sortedGE + +end Thorp.StrongTail + +namespace Thorp.Casimir +open scoped BigOperators Classical +open Filter + +noncomputable def levelScale (n k : ℕ) : ℝ := + (k:ℝ) * (1 + Real.log ((n:ℝ)/(k:ℝ))) + +noncomputable def K (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) + (Specht.relabelledUnitary μ e) (palindromePerm d) + +end Thorp.Casimir + +namespace Thorp.HarmonicBounds +open scoped BigOperators Classical +open _root_.OAI.ThorpNine.Harmonic.Thorp.Casimir StrongSmoothing + +abbrev tail (μ : YoungDiagram) := StrongTail.tailDiagram μ + +noncomputable def W (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) : ℝ := ‖K d μ e‖ + +noncomputable def tupleTrace (d k : ℕ) (order : Equiv.Perm (Fin d)) (rev : Bool) (p : ℕ) : ℝ := + Matrix.trace ((reflectedKernel d k order rev)^p) + +def MainStatement : Prop := + ∃ c C ζ δ cTail c₁ c₂ : ℝ, ∃ p₀ : ℕ, + 0 ((Fintype.card (Tuples d k):ℝ)* + reflectedKernel d k order rev x y)^(1+δ)) ≤ + Real.exp (C*levelScale (2^d) k)) ∧ + tupleTrace d k order rev p₀ ≤ Real.exp (C*levelScale (2^d) k)) + +end Thorp.HarmonicBounds + +end ThorpNine.Harmonic + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Smoothing + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +noncomputable def regularAbsoluteEvenTrace (d : ℕ) (order : Equiv.Perm (Fin d)) (u : ℕ) : ℝ := + Matrix.trace ((reflectedKernel d (2^d) order false)^u) + +def MainStatement : Prop := + ∃ u : ℕ, 1 ≤ u ∧ ∃ C : ℝ, + (∀ d l : ℕ, l ≤ 2^d → ∀ order : Equiv.Perm (Fin d), ∀ orientation : Bool, + ∀ x y : Tuples d l, + ((reflectedKernel d l order orientation)^u) x y ≤ + Real.exp (C*l)/((2^d).descFactorial l:ℝ)) ∧ + (∀ d : ℕ, ∀ order : Equiv.Perm (Fin d), + regularAbsoluteEvenTrace d order u ≤ Real.exp (C*(2:ℝ)^d)) + +end Thorp.StrongSmoothing + +end ThorpNine.Smoothing + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.Tail + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +noncomputable def tupleProbability {Ω β : Type*} [Fintype Ω] [DecidableEq β] + (P : Ω → Equiv.Perm β) (x y : ι → β) : ℝ := by + classical + exact finiteMean (fun ω => if ∀ i, P ω (x i) = y i then 1 else 0) + +end Thorp.PairRouting + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.StrongSmoothing + +def coordinateRelabel (d : ℕ) (order : Equiv.Perm (Fin d)) : Equiv.Perm (Card d) where + toFun x := fun i => x (order.symm i) + invFun x := fun i => x (order i) + left_inv x := by funext i; simp + right_inv x := by funext i; simp + +def sweep (d : ℕ) (order : Equiv.Perm (Fin d)) (ω : SwitchIndex d → Bool) : + Equiv.Perm (Card d) := + coordinateRelabel d order * butterflyPerm d (decodeButterfly d ω) * + (coordinateRelabel d order)⁻¹ + +abbrev Tuples (d l : ℕ) := Fin l ↪ Card d + +noncomputable def sweepKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) : + Matrix (Tuples d l) (Tuples d l) ℝ := + fun x y => PairRouting.tupleProbability (sweep d order) x y + +noncomputable def reflectedKernel (d l : ℕ) (order : Equiv.Perm (Fin d)) (orientation : Bool) : + Matrix (Tuples d l) (Tuples d l) ℝ := + let A := sweepKernel d l order + if orientation then A * A.transpose else A.transpose * A + +end Thorp.StrongSmoothing + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht + +def tailDiagram (μ : YoungDiagram) : YoungDiagram := + YoungDiagram.ofRowLens μ.rowLens.tail μ.rowLens_sorted.pairwise.tail.sortedGE + +end Thorp.StrongTail + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open StrongSmoothing + +def DensityAt (p C : ℝ) : Prop := + ∀ (d l : ℕ), l ≤ 2^d → ∀ (order : Equiv.Perm (Fin d)) (rev : Bool) + (x : StrongSmoothing.Tuples d l), + let H := StrongSmoothing.reflectedKernel d l order rev + (Thorp.finiteMean (fun y => ((Fintype.card (StrongSmoothing.Tuples d l):ℝ)*H x y)^p) + ≤ Real.exp (C*l)) ∧ + (Thorp.finiteMean (fun y => ((Fintype.card (StrongSmoothing.Tuples d l):ℝ)*H y x)^p) + ≤ Real.exp (C*l)) ∧ + (((2:ℝ)^d)^l)⁻¹ * (∑ y, ((((2:ℝ)^d)^l)*H x y)^p) ≤ Real.exp (C*l) ∧ + (((2:ℝ)^d)^l)⁻¹ * (∑ y, ((((2:ℝ)^d)^l)*H y x)^p) ≤ Real.exp (C*l) + +end Thorp.StrongTail + +namespace Thorp.StrongTail +open scoped BigOperators Classical +open Specht UnitaryFinite + +def MainStatement : Prop := + ∃ p Cdensity C : ℝ, 1 < p ∧ p ≤ 2 ∧ DensityAt p Cdensity ∧ + ∀ (d : ℕ) (μ : YoungDiagram) (e : Card d ≃ Specht.Cell μ) (rev : Bool), + ‖SparseContact.sweepOperator d μ e rev‖^2 ≤ + Real.exp (C*(μ.card-μ.rowLen 0 : ℕ)) * + (Module.finrank ℂ (Specht.space (tailDiagram μ)):ℝ)^(-((p-1)/p)) + +end Thorp.StrongTail + +end ThorpNine.Tail + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.HighTail + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +noncomputable def finiteMean {Ω : Type*} [Fintype Ω] (f : Ω → ℝ) : ℝ := + (∑ ω, f ω) / Fintype.card Ω + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +variable {α : Type*} [Fintype α] [DecidableEq α] + +noncomputable def orbitSet (p : Equiv.Perm α) (x : α) : Finset α := + Finset.univ.filter (p.SameCycle x) + +end Thorp + +namespace Thorp.RoutingNetwork +open scoped BigOperators +open Filter +variable {α ι : Type*} [Fintype α] [DecidableEq α] [Fintype ι] [DecidableEq ι] +variable {A : ℕ} + +abbrev SelectedCycle (p : Equiv.Perm (α)) (S : Finset (α)) := + {C : Finset (α) // (∃ x, C = orbitSet p x) ∧ C ⊆ S} + +noncomputable instance (p : Equiv.Perm (α)) (S : Finset (α)) : + Fintype (SelectedCycle p S) := Fintype.ofFinite _ + +end Thorp.RoutingNetwork + +namespace Thorp +open scoped BigOperators +open Filter + +def cardSplit : (r s : ℕ) → Card (s+r) ≃ Card r × Card s + | 0, s => + { toFun := fun x => ((fun i => Fin.elim0 i), x) + invFun := fun x => x.2 + left_inv := fun _ => rfl + right_inv := fun x => by + apply Prod.ext + · exact Subsingleton.elim _ _ + · rfl } + | r+1, s => + { toFun := fun x => (Fin.cons (x 0) ((cardSplit r s (Fin.tail x)).1), + (cardSplit r s (Fin.tail x)).2) + invFun := fun x => Fin.cons (x.1 0) ((cardSplit r s).symm (Fin.tail x.1,x.2)) + left_inv := by + intro x + simp only [Fin.cons_zero, Fin.tail_cons, Prod.mk.eta, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv := by + intro x + simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] } + +def assembleBits : (r s : ℕ) → (Card r × SwitchIndex s → Bool) → + (Card s × SwitchIndex r → Bool) → SwitchIndex (s+r) → Bool + | 0, _, lo, _, i => lo ((fun j => Fin.elim0 j), i) + | r+1, s, _, hi, Sum.inl y => hi ((cardSplit r s y).2,Sum.inl (cardSplit r s y).1) + | r+1, s, lo, hi, Sum.inr (b,i) => assembleBits r s + (fun j => lo (Fin.cons b j.1,j.2)) (fun j => hi (j.1,Sum.inr (b,j.2))) i + + +section +variable {β : Type*} [Fintype β] [DecidableEq β] + +def pairLayer (ξ : β → Bool) : Equiv.Perm (Bool × β) where + toFun x := (Bool.xor x.1 (ξ x.2),x.2) + invFun x := (Bool.xor x.1 (ξ x.2),x.2) + left_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + right_inv x := by + rcases x with ⟨b,x⟩ + change (Bool.xor (Bool.xor b (ξ x)) (ξ x),x) = (b,x) + cases b <;> cases ξ x <;> rfl + +end + +def coinStepEquiv (d : ℕ) : (SwitchIndex (d+1) → Bool) ≃ + ((SwitchIndex d → Bool) × (SwitchIndex d → Bool)) × (Card d → Bool) where + toFun ω := ((fun i => ω (Sum.inr (false,i)),fun i => ω (Sum.inr (true,i))), + fun x => ω (Sum.inl x)) + invFun ω := Sum.elim ω.2 (fun bi => if bi.1 then ω.1.2 bi.2 else ω.1.1 bi.2) + left_inv ω := by + funext i + cases i with + | inl x => rfl + | inr bi => cases bi with | mk b i => cases b <;> rfl + right_inv ω := by + rcases ω with ⟨⟨ω₀,ω₁⟩,ξ⟩ + rfl + +def headTailEquiv (d : ℕ) : Card (d+1) ≃ Bool × Card d := + (Fin.consEquiv (fun _ : Fin (d+1) => Bool)).symm + +end Thorp + +namespace Thorp.CycleColoring +open scoped BigOperators +open Filter +variable {α : Type*} [Fintype α] [DecidableEq α] + +def alternatingPerm (p : Equiv.Perm α) : Equiv.Perm (Bool × α) where + toFun x := if x.1 then (false,p x.2) else (true,x.2) + invFun x := if x.1 then (false,x.2) else (true,p.symm x.2) + left_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + right_inv x := by rcases x with ⟨b,x⟩; cases b <;> simp + +end Thorp.CycleColoring + +namespace Thorp.PairRouting +open scoped BigOperators +open Filter +variable {ι α : Type*} [Fintype ι] [Fintype α] [DecidableEq α] + +def required (x : ι → Bool × α) (c : ι → Bool) (i : ι) : Bool := Bool.xor (x i).1 (c i) + +def Compatible (x : ι → Bool × α) (c : ι → Bool) : Prop := + ∀ i j, (x i).2 = (x j).2 → required x c i = required x c j + +def colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : Bool := + Bool.xor (x i).1 (ξ (x i).2) + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma required_colors (x : ι → Bool × α) (ξ : α → Bool) (i : ι) : + required x (colors x ξ) i = ξ (x i).2 := by + simp only [required,colors] + cases (x i).1 <;> cases ξ (x i).2 <;> rfl + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma colors_compatible (x : ι → Bool × α) (ξ : α → Bool) : Compatible x (colors x ξ) := by + intro i j he + simp only [required_colors,he] + +omit [Fintype ι] [Fintype α] [DecidableEq α] in +lemma Compatible.tail_injective {x : ι ↪ Bool × α} {c : ι → Bool} (hc : Compatible x c) (b : Bool) : + Function.Injective (fun i : {i : ι // c i = b} => (x i.val).2) := by + intro i j he + apply Subtype.ext + apply x.injective + apply Prod.ext + · have hh := hc i j he + simp only [required,i.property,j.property] at hh + cases h₀ : (x i.val).1 <;> cases h₁ : (x j.val).1 <;> cases b <;> simp_all + · exact he + +def childEmbedding (x : ι ↪ Bool × α) (c : ι → Bool) (hc : Compatible x c) (b : Bool) : + {i : ι // c i = b} ↪ α := ⟨fun i => (x i.val).2,hc.tail_injective b⟩ + +noncomputable def labelSet (e : ι ↪ Bool × α) : Finset (Bool × α) := Finset.univ.image e + +def alternatingProjection (p : Bool → Equiv.Perm α) : Equiv.Perm α := (p false).symm * p true + +noncomputable def alternatingCycles (e : ι ↪ Bool × α) (p : Bool → Equiv.Perm α) : ℕ := + Fintype.card (RoutingNetwork.SelectedCycle + (CycleColoring.alternatingPerm (alternatingProjection p)) (labelSet e)) + +def switchedEmbedding (e : ι ↪ Bool × α) (ξ : α → Bool) : ι ↪ Bool × α := + e.trans (pairLayer ξ).toEmbedding + +end Thorp.PairRouting + +namespace Thorp + +section +open scoped BigOperators +open Filter + +abbrev BenesCoins (d : ℕ) := (SwitchIndex d → Bool) × (SwitchIndex d → Bool) + +def palindromePerm (d : ℕ) (ω : BenesCoins d) : Equiv.Perm (Card d) := + butterflyPerm d (decodeButterfly d ω.1) * (butterflyPerm d (decodeButterfly d ω.2)).symm + +def sandwichShuffle {A B C D E F : Type*} : + ((A × B) × C) × ((D × E) × F) ≃ ((A × D) × (B × E)) × (F × C) where + toFun x := (((x.1.1.1,x.2.1.1),(x.1.1.2,x.2.1.2)),(x.2.2,x.1.2)) + invFun x := (((x.1.1.1,x.1.2.1),x.2.2),((x.1.1.2,x.1.2.2),x.2.1)) + left_inv _ := rfl + right_inv _ := rfl + +def benesStepEquiv (d : ℕ) : BenesCoins (d+1) ≃ + (BenesCoins d × BenesCoins d) × ((Card d → Bool) × (Card d → Bool)) := + (Equiv.prodCongr (coinStepEquiv d) (coinStepEquiv d)).trans sandwichShuffle + +noncomputable def palindromeCost : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) + + palindromeCost d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeCost d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end + +noncomputable def palindromeLowCost (H : ℕ) : (d : ℕ) → {ι : Type*} → [Fintype ι] → + (ι ↪ Card d) → BenesCoins d → ℕ + | 0, _, _, _, _ => 0 + | d+1, _, _, e, ω => + let σ := benesStepEquiv d ω + let x := e.trans (headTailEquiv d).toEmbedding + let c := PairRouting.colors x σ.2.1 + let hc := PairRouting.colors_compatible x σ.2.1 + (if d+1 ≤ H then PairRouting.alternatingCycles (PairRouting.switchedEmbedding x σ.2.1) + (fun b => palindromePerm d (if b then σ.1.2 else σ.1.1)) else 0) + + palindromeLowCost H d (PairRouting.childEmbedding x c hc false) σ.1.1 + + palindromeLowCost H d (PairRouting.childEmbedding x c hc true) σ.1.2 + +end Thorp + +namespace Thorp.HighHeight +open scoped BigOperators Classical + +noncomputable def highCost (J d : ℕ) {ι : Type*} [Fintype ι] + (x : ι ↪ Card d) (ω : BenesCoins d) : ℕ := + palindromeCost d x ω-palindromeLowCost (J-1) d x ω + +def MainStatement : Prop := + ∃ b δ C : ℝ, 0 ((2:ℝ)^b)^(highCost J d x ω)))/Real.log 2 ≤ + C*k*(2:ℝ)^(-b*J)) ∧ + (∀ d k : ℕ, ∀ x : Fin k ↪ Card d, + Real.log (finiteMean (fun ω : BenesCoins d => ((2:ℝ)^b)^(palindromeCost d x ω)))/Real.log 2 ≤ + C*k*((k:ℝ)/(2:ℝ)^d)^δ) ∧ + (∀ r s k : ℕ, ∀ x : Fin k ↪ Card (s+r), ∀ J : ℕ, J₀≤J → 2*s + ((2:ℝ)^b)^(highCost J (s+r) x (assembleBits r s lo hi,X))))/Real.log 2 ≤ + C*k*(2:ℝ)^(-b*J)) + +end Thorp.HighHeight + +end ThorpNine.HighTail + +run_cmd do + Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + let matcherCache := Lean.mkIdent + (Lean.mkPrivateNameCore `Lean.Meta.Match.Match `Lean.Meta.Match.matcherExt) + Lean.Elab.Command.elabCommand (← `(command| + run_cmd Lean.modifyEnv fun env => Lean.EnvExtension.setState $matcherCache env {})) + +namespace ThorpNine.SparseSaving + +namespace Thorp +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def Butterfly : ℕ → Type + | 0 => Unit + | d + 1 => (Card d → Bool) × (Bool → Butterfly d) + +def childLift {d : ℕ} (p : Bool → Equiv.Perm (Card d)) : Equiv.Perm (Card (d + 1)) where + toFun x := Fin.cons (x 0) (p (x 0) (Fin.tail x)) + invFun x := Fin.cons (x 0) ((p (x 0)).symm (Fin.tail x)) + left_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.symm_apply_apply, Fin.cons_self_tail] + right_inv x := by simp only [Fin.cons_zero, Fin.tail_cons, Equiv.apply_symm_apply, Fin.cons_self_tail] + +def butterflyPerm : (d : ℕ) → Butterfly d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, b => pairSwitch b.1 * childLift (fun ε => butterflyPerm d (b.2 ε)) + +def SwitchIndex : ℕ → Type + | 0 => Empty + | d + 1 => Sum (Card d) (Bool × SwitchIndex d) + +instance (d : ℕ) : Fintype (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (Fintype Empty) + | succ d ih => exact inferInstanceAs (Fintype (Sum (Card d) (Bool × SwitchIndex d))) + +instance (d : ℕ) : DecidableEq (SwitchIndex d) := by + induction d with + | zero => exact inferInstanceAs (DecidableEq Empty) + | succ d ih => exact inferInstanceAs (DecidableEq (Sum (Card d) (Bool × SwitchIndex d))) + +def decodeButterfly : (d : ℕ) → (SwitchIndex d → Bool) → Butterfly d + | 0, _ => () + | d + 1, ω => (fun y => ω (Sum.inl y), fun ε => + decodeButterfly d (fun i => ω (Sum.inr (ε,i)))) + +end Thorp + +namespace Thorp.Specht +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} + +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 + +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 + +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) + + +section +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end Thorp.Specht + +namespace Thorp.PermutationHilbert +open scoped BigOperators ComplexConjugate Classical +open Complex +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end Thorp.PermutationHilbert + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +end Thorp.Specht + +namespace Thorp.UnitaryFinite + +section +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end Thorp.UnitaryFinite + +namespace Thorp.Specht +open scoped BigOperators Classical + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end Thorp.Specht + +namespace Thorp.SparseContact +open scoped BigOperators + +noncomputable def sweepOperator (d : ℕ) (μ : YoungDiagram) + (e : Card d ≃ Specht.Cell μ) (reverse : Bool) : + Specht.hilbertSpace μ →L[ℂ] Specht.hilbertSpace μ := + UnitaryFinite.sampleOperator (V := Specht.hilbertSpace μ) (Specht.relabelledUnitary μ e) + (fun ω : SwitchIndex d → Bool => if reverse then + (butterflyPerm d (decodeButterfly d ω))⁻¹ else butterflyPerm d (decodeButterfly d ω)) + +end Thorp.SparseContact + +namespace Thorp.SparseRegime + +def MainStatement : Prop := + ∃ (C : ℝ) (d₀ : ℕ), 0 < C ∧ 0 < d₀ ∧ + ∀ (d : ℕ) (μ : YoungDiagram) (e : Thorp.Card d ≃ Thorp.Specht.Cell μ), + let k := μ.card - μ.rowLen 0 + 1 ≤ k → k < 2^d → (d:ℝ)^((3:ℝ)/4) ≤ Real.log ((2:ℝ)^d/k) → + ∀ rev : Bool, + ‖Thorp.SparseContact.sweepOperator d μ e rev‖^2 ≤ + Real.exp (C*k)*((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/4) ∧ + (d₀ ≤ d → ‖Thorp.SparseContact.sweepOperator d μ e rev‖^2 ≤ + ((k:ℝ)/(2:ℝ)^d)^((k:ℝ)/4)) + +end Thorp.SparseRegime + +end ThorpNine.SparseSaving + +theorem ThorpNine.main : + ThorpNine.Adaptive.Thorp.AdaptiveBounds.MainStatement ∧ + ThorpNine.Casimir.Thorp.CasimirBounds.MainStatement ∧ + ThorpNine.Dense.Thorp.DenseTruncation.MainStatement ∧ + ThorpNine.Contact.Thorp.SparseContact.MainStatement ∧ + ThorpNine.Harmonic.Thorp.HarmonicBounds.MainStatement ∧ + ThorpNine.Smoothing.Thorp.StrongSmoothing.MainStatement ∧ + ThorpNine.Tail.Thorp.StrongTail.MainStatement ∧ + ThorpNine.HighTail.Thorp.HighHeight.MainStatement ∧ + ThorpNine.SparseSaving.Thorp.SparseRegime.MainStatement := by + sorry + +end OAI diff --git a/tasks/thorp-routing/tests/grade.py b/tasks/thorp-routing/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thorp-routing/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thorp-routing/tests/task.json b/tasks/thorp-routing/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..7561adc0cd1b94cd418877a51e8af92717f3fe4c --- /dev/null +++ b/tasks/thorp-routing/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThorpRouting", + "comparator": { + "theorem_names": [ + "OAI.ThorpNine.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16723 +} \ No newline at end of file diff --git a/tasks/thorp-routing/tests/test.sh b/tasks/thorp-routing/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thorp-routing/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/thorp-weighted-compatibility/environment/Dockerfile b/tasks/thorp-weighted-compatibility/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/thorp-weighted-compatibility/environment/fetch_mathlib.sh b/tasks/thorp-weighted-compatibility/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/thorp-weighted-compatibility/environment/lake-manifest.json b/tasks/thorp-weighted-compatibility/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/thorp-weighted-compatibility/environment/lakefile.lean b/tasks/thorp-weighted-compatibility/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/thorp-weighted-compatibility/environment/lean_setup.sh b/tasks/thorp-weighted-compatibility/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/thorp-weighted-compatibility/environment/pack_submission.py b/tasks/thorp-weighted-compatibility/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/thorp-weighted-compatibility/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/thorp-weighted-compatibility/instruction.md b/tasks/thorp-weighted-compatibility/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2d7c102162a9ec3e01dbc134f81c04a3cc135939 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/instruction.md @@ -0,0 +1,103 @@ +# openai/math challenge `ThorpWeightedCompatibility` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `ThorpWeightedCompatibility`, also at `/opt/openai-math/challenges/ThorpWeightedCompatibility.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped Classical +namespace ThorpCompatibility +open Finset + +abbrev Rows (A D : ℕ) := Fin A → Equiv.Perm (Fin D) +abbrev Cols (A D : ℕ) := Fin D → Equiv.Perm (Fin A) + +def Compatible {A D : ℕ} (r : Rows A D) (c : Cols A D) : Prop := + ∀ j : Fin D, Function.Injective (fun i : Fin A => c (r i j) i) + +noncomputable def uniformMean {α : Type*} [Fintype α] (f : α → ℝ) : ℝ := + (∑ x, f x) / Fintype.card α + +noncomputable def marginalFactor {α : Type*} [Fintype α] + (θ : ℝ) (w : α → ℝ) : ℝ := + (uniformMean (fun x => Real.rpow (w x) (1 / θ))) ^ θ + +noncomputable def weightedCompatibility (A D : ℕ) + (w : Fin A → Equiv.Perm (Fin D) → ℝ) + (v : Fin D → Equiv.Perm (Fin A) → ℝ) : ℝ := by + classical + exact (Nat.factorial (A * D) : ℝ) / + ((Nat.factorial D : ℝ) ^ A * (Nat.factorial A : ℝ) ^ D) * + uniformMean (fun rc : Rows A D × Cols A D => + if Compatible rc.1 rc.2 then (∏ i, w i (rc.1 i)) * (∏ k, v k (rc.2 k)) else 0) + +def WeightedCompatibilityTheorem : Prop := + ∃ L C₀ m₀ : ℝ, 0 < L ∧ 0 < C₀ ∧ 0 < m₀ ∧ + ∀ A D : ℕ, + let n : ℝ := A * D + let m := Real.sqrt n + let θ := 1 - L / Real.log m + m₀ ≤ m → 0 < θ → m / ((2 : ℕ) : ℝ) ≤ A → (A : ℝ) ≤ ((2 : ℕ) : ℝ) * m → + m / ((2 : ℕ) : ℝ) ≤ D → (D : ℝ) ≤ ((2 : ℕ) : ℝ) * m → + ∀ (w : Fin A → Equiv.Perm (Fin D) → ℝ) + (v : Fin D → Equiv.Perm (Fin A) → ℝ), + (∀ i σ, 0 ≤ w i σ) → (∀ k σ, 0 ≤ v k σ) → + weightedCompatibility A D w v ≤ + Real.exp (C₀ * n ^ (((54 : ℕ) : ℝ) / ((100 : ℕ) : ℝ))) * + (∏ i, marginalFactor θ (w i)) * (∏ k, marginalFactor θ (v k)) + + +theorem weightedCompatibility_main : WeightedCompatibilityTheorem := by + sorry + +end ThorpCompatibility + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThorpWeightedCompatibility.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThorpCompatibility.weightedCompatibility_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/thorp-weighted-compatibility/solution/closure.txt b/tasks/thorp-weighted-compatibility/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..cf3c80be63532cde90a2fef167e313d94cc84b55 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/solution/closure.txt @@ -0,0 +1,34 @@ +OAI.Probability.ThorpCompatibility.BinomialBounds +OAI.Probability.ThorpCompatibility.ClumpCost +OAI.Probability.ThorpCompatibility.ClumpMoments +OAI.Probability.ThorpCompatibility.ClumpParameters +OAI.Probability.ThorpCompatibility.ConditionalEntropy +OAI.Probability.ThorpCompatibility.Entropy +OAI.Probability.ThorpCompatibility.EntropyBounds +OAI.Probability.ThorpCompatibility.EntropyChain +OAI.Probability.ThorpCompatibility.EntropyEstimate +OAI.Probability.ThorpCompatibility.ExposureEntropy +OAI.Probability.ThorpCompatibility.FactorialBounds +OAI.Probability.ThorpCompatibility.FiniteLaw +OAI.Probability.ThorpCompatibility.GridDeficits +OAI.Probability.ThorpCompatibility.GridEntropy +OAI.Probability.ThorpCompatibility.GridExposure +OAI.Probability.ThorpCompatibility.HeavyColumns +OAI.Probability.ThorpCompatibility.HeavyEntries +OAI.Probability.ThorpCompatibility.LightRescaling +OAI.Probability.ThorpCompatibility.ListIncidence +OAI.Probability.ThorpCompatibility.LogEstimates +OAI.Probability.ThorpCompatibility.Main +OAI.Probability.ThorpCompatibility.Model +OAI.Probability.ThorpCompatibility.MomentBound +OAI.Probability.ThorpCompatibility.Normalization +OAI.Probability.ThorpCompatibility.PermutationCount +OAI.Probability.ThorpCompatibility.PermutationProbability +OAI.Probability.ThorpCompatibility.Prediction +OAI.Probability.ThorpCompatibility.RandomExclusion +OAI.Probability.ThorpCompatibility.RankAverages +OAI.Probability.ThorpCompatibility.RankLaw +OAI.Probability.ThorpCompatibility.UniformAverages +OAI.Probability.ThorpCompatibility.UniformSupport +OAI.Probability.ThorpCompatibility.VariationalBound +OAI.Probability.ThorpCompatibility.WeightedGibbs diff --git a/tasks/thorp-weighted-compatibility/solution/reference.py b/tasks/thorp-weighted-compatibility/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/thorp-weighted-compatibility/solution/solve.sh b/tasks/thorp-weighted-compatibility/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..8a13eaf2205087d2fea44c1dc988f078b5317a2c --- /dev/null +++ b/tasks/thorp-weighted-compatibility/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThorpWeightedCompatibility, i.e. module OAI.Probability.ThorpCompatibility.Main and the +# 34 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThorpCompatibility.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThorpWeightedCompatibility" diff --git a/tasks/thorp-weighted-compatibility/task.toml b/tasks/thorp-weighted-compatibility/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..3ae7f8b99591db0b9736a8f5d7ed14058d284b8d --- /dev/null +++ b/tasks/thorp-weighted-compatibility/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/thorp-weighted-compatibility" +version = "1.0.0" +description = "Prove ThorpWeightedCompatibility (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThorpWeightedCompatibility.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThorpWeightedCompatibility" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThorpCompatibility.weightedCompatibility_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThorpCompatibility.Main" +reference_modules = 34 +reference_lean_bytes = 135549 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 294 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11821 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/thorp-weighted-compatibility/tests/Challenge.lean b/tasks/thorp-weighted-compatibility/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0ffa8457a98f50f5786f80b70e2dd2733902d5c5 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/tests/Challenge.lean @@ -0,0 +1,52 @@ +import Mathlib + +namespace OAI + +open scoped Classical +namespace ThorpCompatibility +open Finset + +abbrev Rows (A D : ℕ) := Fin A → Equiv.Perm (Fin D) +abbrev Cols (A D : ℕ) := Fin D → Equiv.Perm (Fin A) + +def Compatible {A D : ℕ} (r : Rows A D) (c : Cols A D) : Prop := + ∀ j : Fin D, Function.Injective (fun i : Fin A => c (r i j) i) + +noncomputable def uniformMean {α : Type*} [Fintype α] (f : α → ℝ) : ℝ := + (∑ x, f x) / Fintype.card α + +noncomputable def marginalFactor {α : Type*} [Fintype α] + (θ : ℝ) (w : α → ℝ) : ℝ := + (uniformMean (fun x => Real.rpow (w x) (1 / θ))) ^ θ + +noncomputable def weightedCompatibility (A D : ℕ) + (w : Fin A → Equiv.Perm (Fin D) → ℝ) + (v : Fin D → Equiv.Perm (Fin A) → ℝ) : ℝ := by + classical + exact (Nat.factorial (A * D) : ℝ) / + ((Nat.factorial D : ℝ) ^ A * (Nat.factorial A : ℝ) ^ D) * + uniformMean (fun rc : Rows A D × Cols A D => + if Compatible rc.1 rc.2 then (∏ i, w i (rc.1 i)) * (∏ k, v k (rc.2 k)) else 0) + +def WeightedCompatibilityTheorem : Prop := + ∃ L C₀ m₀ : ℝ, 0 < L ∧ 0 < C₀ ∧ 0 < m₀ ∧ + ∀ A D : ℕ, + let n : ℝ := A * D + let m := Real.sqrt n + let θ := 1 - L / Real.log m + m₀ ≤ m → 0 < θ → m / ((2 : ℕ) : ℝ) ≤ A → (A : ℝ) ≤ ((2 : ℕ) : ℝ) * m → + m / ((2 : ℕ) : ℝ) ≤ D → (D : ℝ) ≤ ((2 : ℕ) : ℝ) * m → + ∀ (w : Fin A → Equiv.Perm (Fin D) → ℝ) + (v : Fin D → Equiv.Perm (Fin A) → ℝ), + (∀ i σ, 0 ≤ w i σ) → (∀ k σ, 0 ≤ v k σ) → + weightedCompatibility A D w v ≤ + Real.exp (C₀ * n ^ (((54 : ℕ) : ℝ) / ((100 : ℕ) : ℝ))) * + (∏ i, marginalFactor θ (w i)) * (∏ k, marginalFactor θ (v k)) + + +theorem weightedCompatibility_main : WeightedCompatibilityTheorem := by + sorry + +end ThorpCompatibility + +end OAI diff --git a/tasks/thorp-weighted-compatibility/tests/grade.py b/tasks/thorp-weighted-compatibility/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/thorp-weighted-compatibility/tests/task.json b/tasks/thorp-weighted-compatibility/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..92ef71a8868ac3043c62d32f246b5d1b2ae70f81 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThorpWeightedCompatibility", + "comparator": { + "theorem_names": [ + "OAI.ThorpCompatibility.weightedCompatibility_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10921 +} \ No newline at end of file diff --git a/tasks/thorp-weighted-compatibility/tests/test.sh b/tasks/thorp-weighted-compatibility/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/thorp-weighted-compatibility/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/three-machine/environment/Dockerfile b/tasks/three-machine/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/three-machine/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/three-machine/environment/fetch_mathlib.sh b/tasks/three-machine/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/three-machine/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/three-machine/environment/lake-manifest.json b/tasks/three-machine/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/three-machine/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/three-machine/environment/lakefile.lean b/tasks/three-machine/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/three-machine/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/three-machine/environment/lean_setup.sh b/tasks/three-machine/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/three-machine/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/three-machine/environment/pack_submission.py b/tasks/three-machine/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/three-machine/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/three-machine/instruction.md b/tasks/three-machine/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..8d191bb80e1349085e53297173c169faaa158e02 --- /dev/null +++ b/tasks/three-machine/instruction.md @@ -0,0 +1,151 @@ +# openai/math challenge `ThreeMachine` (family 124) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 124 of the release, *Polynomial-time scheduling on three identical machines* +(Theoretical computer science). The family as a whole: Resolves the three-processor unit-job scheduling problem of Garey and Johnson: a deterministic polynomial-time algorithm minimizes makespan for nonpreemptive unit-length jobs with arbitrary precedence constraints on three identical parallel machines. For an explicitly given precedence graph, it decides deadline feasibility exactly and constructs a feasible schedule. + +The challenge is `ThreeMachine`, also at `/opt/openai-math/challenges/ThreeMachine.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ThreeMachine + +structure Instance (n : ℕ) where + edges : List (Fin n × Fin n) + +def Instance.edge {n : ℕ} (G : Instance n) (u v : Fin n) : Prop := + (u, v) ∈ G.edges + +def Instance.acyclic {n : ℕ} (G : Instance n) : Prop := + ∀ v, ¬Relation.TransGen G.edge v v + +def Feasible {n : ℕ} (G : Instance n) (T : ℕ) (τ : Fin n → ℕ) : Prop := + (∀ v, 1 ≤ τ v ∧ τ v ≤ T) ∧ + (∀ t, ((Finset.univ : Finset (Fin n)).filter (fun v => τ v = t)).card ≤ 3) ∧ + ∀ u v, G.edge u v → τ u < τ v + +def encodeNat (n : ℕ) : List Bool := + let b := Computability.encodeNat n + List.replicate b.length true ++ false :: b + +def encodeList {α : Type} (f : α → List Bool) (xs : List α) : List Bool := + encodeNat xs.length ++ xs.flatMap f + +def encodeInput {n : ℕ} (G : Instance n) (deadline : Option ℕ) : List Bool := + (match deadline with + | none => [false] + | some T => true :: encodeNat T) ++ + encodeList encodeNat ((List.range n).map (· + 1)) ++ + encodeList (fun (e : Fin n × Fin n) => encodeNat (e.1.val + 1) ++ + encodeNat (e.2.val + 1)) G.edges + +def encodeAnswer : Option (List ℕ) → List Bool + | none => [false] + | some slots => true :: encodeList encodeNat slots + +def slots {n : ℕ} (τ : Fin n → ℕ) : List ℕ := List.ofFn τ + +def CorrectOutput {n : ℕ} (G : Instance n) (deadline : Option ℕ) + (out : List Bool) : Prop := + match deadline with + | none => ∃ T τ, Feasible G T τ ∧ + (∀ T' τ', Feasible G T' τ' → T ≤ T') ∧ + out = encodeAnswer (some (slots τ)) + | some T => + (out = encodeAnswer none ∧ ¬∃ τ, Feasible G T τ) ∨ + ∃ τ, Feasible G T τ ∧ out = encodeAnswer (some (slots τ)) + +structure Machine (k q g : ℕ) where + transition : Fin (q + 1) → (Fin (k + 1) → Fin (g + 3)) → + Option (Fin (q + 1) × (Fin (k + 1) → Fin (g + 3) × Option Turing.Dir)) + +structure Configuration (k q g : ℕ) where + state : Fin (q + 1) + tapes : Fin (k + 1) → Turing.Tape (Fin (g + 3)) + +def bitSymbol {g : ℕ} (b : Bool) : Fin (g + 3) := + if b then ⟨2, by omega⟩ else ⟨1, by omega⟩ + +def Machine.step {k q g : ℕ} (M : Machine k q g) + (c : Configuration k q g) : Option (Configuration k q g) := do + let (state, action) ← M.transition c.state (fun i => (c.tapes i).head) + return { state := state, tapes := fun i => + let tape := (c.tapes i).write (action i).1 + match (action i).2 with + | none => tape + | some d => tape.move d } + +def Machine.initial {k q g : ℕ} (_M : Machine k q g) + (input : List Bool) : Configuration k q g := + { state := 0, tapes := fun i => + Turing.Tape.mk₁ (if i = 0 then input.map bitSymbol else []) } + +def Machine.run {k q g : ℕ} (M : Machine k q g) (input : List Bool) + (t : ℕ) : Configuration k q g := + (fun c => (M.step c).getD c)^[t] (M.initial input) + +def Machine.Produces {k q g : ℕ} (M : Machine k q g) + (input out : List Bool) (timeBound : ℕ) : Prop := + ∃ t ≤ timeBound, M.step (M.run input t) = none ∧ + ((M.run input t).tapes 0).right₀ = Turing.ListBlank.mk (out.map bitSymbol) + +def ReleaseTheorem : Prop := + ∃ (k q g : ℕ) (M : Machine k q g) (C : ℕ), 0 < C ∧ + ∀ n (G : Instance n), 1 ≤ n → G.acyclic → + ∀ deadline : Option ℕ, + (∀ T ∈ deadline, 1 ≤ T ∧ T ≤ n) → + ∃ out, CorrectOutput G deadline out ∧ + M.Produces (encodeInput G deadline) out + (C * ((encodeInput G deadline).length + 2) ^ 150020) + +theorem main_theorem : ReleaseTheorem := by + sorry + +end ThreeMachine + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThreeMachine.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThreeMachine.main_theorem` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/three-machine/solution/closure.txt b/tasks/three-machine/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..af695e564d09b285f7e976bd0530f1a67a08e37a --- /dev/null +++ b/tasks/three-machine/solution/closure.txt @@ -0,0 +1,53 @@ +OAI.Computability.Scheduling.BinaryCosts +OAI.Computability.Scheduling.CostBounds +OAI.Computability.Scheduling.CutoffSimplification +OAI.Computability.Scheduling.DynamicProgram +OAI.Computability.Scheduling.EffectiveFamily +OAI.Computability.Scheduling.EncodingCosts +OAI.Computability.Scheduling.FamilyCosts +OAI.Computability.Scheduling.FamilyRoutines +OAI.Computability.Scheduling.FiniteRoutines +OAI.Computability.Scheduling.FrameInvariants +OAI.Computability.Scheduling.GlobalBoundaries +OAI.Computability.Scheduling.HierarchyCompleteness +OAI.Computability.Scheduling.HierarchySoundness +OAI.Computability.Scheduling.ListParserCosts +OAI.Computability.Scheduling.ListRoutines +OAI.Computability.Scheduling.MachineBridge +OAI.Computability.Scheduling.Main +OAI.Computability.Scheduling.MatrixCosts +OAI.Computability.Scheduling.Model +OAI.Computability.Scheduling.NodeCertificates +OAI.Computability.Scheduling.OptimumCosts +OAI.Computability.Scheduling.OutputCosts +OAI.Computability.Scheduling.Padding +OAI.Computability.Scheduling.Parser +OAI.Computability.Scheduling.Polynomial +OAI.Computability.Scheduling.PolynomialLists +OAI.Computability.Scheduling.PolynomialLoops +OAI.Computability.Scheduling.PolynomialTactic +OAI.Computability.Scheduling.PriorityUpdates +OAI.Computability.Scheduling.ProgramRoutines +OAI.Computability.Scheduling.RankCosts +OAI.Computability.Scheduling.ReaderCosts +OAI.Computability.Scheduling.Realizers +OAI.Computability.Scheduling.RegisterMachine +OAI.Computability.Scheduling.RequestBounds +OAI.Computability.Scheduling.RequestCosts +OAI.Computability.Scheduling.RoutineCompiler +OAI.Computability.Scheduling.RunCertificates +OAI.Computability.Scheduling.ScheduleBounds +OAI.Computability.Scheduling.ScheduleRoutines +OAI.Computability.Scheduling.SchedulingAlgorithm +OAI.Computability.Scheduling.SchedulingCosts +OAI.Computability.Scheduling.SeparatorWalk +OAI.Computability.Scheduling.SolverCosts +OAI.Computability.Scheduling.SplitPaths +OAI.Computability.Scheduling.StackMachine +OAI.Computability.Scheduling.StateBounds +OAI.Computability.Scheduling.StateCosts +OAI.Computability.Scheduling.TableCosts +OAI.Computability.Scheduling.TransitionCosts +OAI.Computability.Scheduling.TreeData +OAI.Computability.Scheduling.UniformRoutines +OAI.Computability.Scheduling.VolumeBounds diff --git a/tasks/three-machine/solution/reference.py b/tasks/three-machine/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/three-machine/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/three-machine/solution/solve.sh b/tasks/three-machine/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..9d801203a7c5b2dd9570b625484c299d8250188b --- /dev/null +++ b/tasks/three-machine/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThreeMachine, i.e. module OAI.Computability.Scheduling.Main and the +# 53 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.Scheduling.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThreeMachine" diff --git a/tasks/three-machine/task.toml b/tasks/three-machine/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..dda5798d015ad27c6b3cf953e9ed00dd6246041c --- /dev/null +++ b/tasks/three-machine/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/three-machine" +version = "1.0.0" +description = "Prove ThreeMachine (openai/math family 124: Polynomial-time scheduling on three identical machines) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThreeMachine.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThreeMachine" +family = "124" +family_title = "Polynomial-time scheduling on three identical machines" +subject = "Theoretical computer science" +theorems = ["OAI.ThreeMachine.main_theorem"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.Scheduling.Main" +reference_modules = 53 +reference_lean_bytes = 851902 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 467 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12466 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/three-machine/tests/Challenge.lean b/tasks/three-machine/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..82e56b4d0dd587adb74a804e2a11249e9e680f0e --- /dev/null +++ b/tasks/three-machine/tests/Challenge.lean @@ -0,0 +1,100 @@ +import Mathlib + +namespace OAI + +namespace ThreeMachine + +structure Instance (n : ℕ) where + edges : List (Fin n × Fin n) + +def Instance.edge {n : ℕ} (G : Instance n) (u v : Fin n) : Prop := + (u, v) ∈ G.edges + +def Instance.acyclic {n : ℕ} (G : Instance n) : Prop := + ∀ v, ¬Relation.TransGen G.edge v v + +def Feasible {n : ℕ} (G : Instance n) (T : ℕ) (τ : Fin n → ℕ) : Prop := + (∀ v, 1 ≤ τ v ∧ τ v ≤ T) ∧ + (∀ t, ((Finset.univ : Finset (Fin n)).filter (fun v => τ v = t)).card ≤ 3) ∧ + ∀ u v, G.edge u v → τ u < τ v + +def encodeNat (n : ℕ) : List Bool := + let b := Computability.encodeNat n + List.replicate b.length true ++ false :: b + +def encodeList {α : Type} (f : α → List Bool) (xs : List α) : List Bool := + encodeNat xs.length ++ xs.flatMap f + +def encodeInput {n : ℕ} (G : Instance n) (deadline : Option ℕ) : List Bool := + (match deadline with + | none => [false] + | some T => true :: encodeNat T) ++ + encodeList encodeNat ((List.range n).map (· + 1)) ++ + encodeList (fun (e : Fin n × Fin n) => encodeNat (e.1.val + 1) ++ + encodeNat (e.2.val + 1)) G.edges + +def encodeAnswer : Option (List ℕ) → List Bool + | none => [false] + | some slots => true :: encodeList encodeNat slots + +def slots {n : ℕ} (τ : Fin n → ℕ) : List ℕ := List.ofFn τ + +def CorrectOutput {n : ℕ} (G : Instance n) (deadline : Option ℕ) + (out : List Bool) : Prop := + match deadline with + | none => ∃ T τ, Feasible G T τ ∧ + (∀ T' τ', Feasible G T' τ' → T ≤ T') ∧ + out = encodeAnswer (some (slots τ)) + | some T => + (out = encodeAnswer none ∧ ¬∃ τ, Feasible G T τ) ∨ + ∃ τ, Feasible G T τ ∧ out = encodeAnswer (some (slots τ)) + +structure Machine (k q g : ℕ) where + transition : Fin (q + 1) → (Fin (k + 1) → Fin (g + 3)) → + Option (Fin (q + 1) × (Fin (k + 1) → Fin (g + 3) × Option Turing.Dir)) + +structure Configuration (k q g : ℕ) where + state : Fin (q + 1) + tapes : Fin (k + 1) → Turing.Tape (Fin (g + 3)) + +def bitSymbol {g : ℕ} (b : Bool) : Fin (g + 3) := + if b then ⟨2, by omega⟩ else ⟨1, by omega⟩ + +def Machine.step {k q g : ℕ} (M : Machine k q g) + (c : Configuration k q g) : Option (Configuration k q g) := do + let (state, action) ← M.transition c.state (fun i => (c.tapes i).head) + return { state := state, tapes := fun i => + let tape := (c.tapes i).write (action i).1 + match (action i).2 with + | none => tape + | some d => tape.move d } + +def Machine.initial {k q g : ℕ} (_M : Machine k q g) + (input : List Bool) : Configuration k q g := + { state := 0, tapes := fun i => + Turing.Tape.mk₁ (if i = 0 then input.map bitSymbol else []) } + +def Machine.run {k q g : ℕ} (M : Machine k q g) (input : List Bool) + (t : ℕ) : Configuration k q g := + (fun c => (M.step c).getD c)^[t] (M.initial input) + +def Machine.Produces {k q g : ℕ} (M : Machine k q g) + (input out : List Bool) (timeBound : ℕ) : Prop := + ∃ t ≤ timeBound, M.step (M.run input t) = none ∧ + ((M.run input t).tapes 0).right₀ = Turing.ListBlank.mk (out.map bitSymbol) + +def ReleaseTheorem : Prop := + ∃ (k q g : ℕ) (M : Machine k q g) (C : ℕ), 0 < C ∧ + ∀ n (G : Instance n), 1 ≤ n → G.acyclic → + ∀ deadline : Option ℕ, + (∀ T ∈ deadline, 1 ≤ T ∧ T ≤ n) → + ∃ out, CorrectOutput G deadline out ∧ + M.Produces (encodeInput G deadline) out + (C * ((encodeInput G deadline).length + 2) ^ 150020) + +theorem main_theorem : ReleaseTheorem := by + sorry + +end ThreeMachine + +end OAI diff --git a/tasks/three-machine/tests/grade.py b/tasks/three-machine/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/three-machine/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/three-machine/tests/task.json b/tasks/three-machine/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9df9bc11f2272473e8aaa1031e085eee8a25e0d2 --- /dev/null +++ b/tasks/three-machine/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThreeMachine", + "comparator": { + "theorem_names": [ + "OAI.ThreeMachine.main_theorem" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11566 +} \ No newline at end of file diff --git a/tasks/three-machine/tests/test.sh b/tasks/three-machine/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/three-machine/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/three-state-supercritical/environment/Dockerfile b/tasks/three-state-supercritical/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/three-state-supercritical/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/three-state-supercritical/environment/fetch_mathlib.sh b/tasks/three-state-supercritical/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/three-state-supercritical/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/three-state-supercritical/environment/lake-manifest.json b/tasks/three-state-supercritical/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/three-state-supercritical/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/three-state-supercritical/environment/lakefile.lean b/tasks/three-state-supercritical/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/three-state-supercritical/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/three-state-supercritical/environment/lean_setup.sh b/tasks/three-state-supercritical/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/three-state-supercritical/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/three-state-supercritical/environment/pack_submission.py b/tasks/three-state-supercritical/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/three-state-supercritical/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/three-state-supercritical/instruction.md b/tasks/three-state-supercritical/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b53c548f0afddcf618eebd0483c713e4b747fc50 --- /dev/null +++ b/tasks/three-state-supercritical/instruction.md @@ -0,0 +1,159 @@ +# openai/math challenge `ThreeStateSupercritical` (family 229) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 229 of the release, *Sharp three- and four-state reconstruction thresholds* +(Probability and statistical mechanics). The family as a whole: Proves the exact reconstruction threshold $d\lambda^2>1$, with nonreconstruction at equality, for three-state symmetric and four-state ferromagnetic broadcasting on regular trees ($d\ge2$) and observed Poisson trees (mean $d>1$ and $d>0$, respectively), with Poisson advantage averaged without conditioning on survival. The three-state theorem allows both signs of $\lambda$ and gives the exact weak-recovery threshold for the symmetric three-community stochastic block model. + +The challenge is `ThreeStateSupercritical`, also at `/opt/openai-math/challenges/ThreeStateSupercritical.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace ThreeState + +abbrev Spin := Fin 3 + + +def Admissible (lam : ℝ) : Prop := -(1 / 2 : ℝ) ≤ lam ∧ lam ≤ 1 + + +noncomputable def channel (lam : ℝ) (i j : Spin) : ℝ := + if i = j then (1 + 2 * lam) / 3 else (1 - lam) / 3 + + + +def Observation : ℕ → Type + | 0 => Spin + | n + 1 => Multiset (Observation n) + +theorem channel_nonneg {lam : ℝ} (h : Admissible lam) (i j : Spin) : + 0 ≤ channel lam i j := by + unfold channel + split_ifs + · dsimp [Admissible] at h + linarith [h.1] + · dsimp [Admissible] at h + linarith [h.2] + +theorem channel_sum (lam : ℝ) (i : Spin) : ∑ j, channel lam i j = 1 := by + fin_cases i <;> simp [channel, Fin.sum_univ_succ] <;> ring + +noncomputable def channelPMF (lam : ℝ) (h : Admissible lam) (i : Spin) : PMF Spin := + PMF.ofFintype (fun j => ENNReal.ofReal (channel lam i j)) (by + rw [← ENNReal.ofReal_sum_of_nonneg (fun j _ => channel_nonneg h i j)] + simp [channel_sum]) + + +noncomputable def iidList {α : Type*} (p : PMF α) : ℕ → PMF (List α) + | 0 => PMF.pure [] + | n + 1 => p.bind fun a => (iidList p n).map (List.cons a) + + + +noncomputable def observedLaw (offspring : PMF ℕ) (lam : ℝ) (h : Admissible lam) : + (n : ℕ) → Spin → PMF (Observation n) + | 0, i => PMF.pure i + | n + 1, i => offspring.bind fun k => + (iidList ((channelPMF lam h i).bind (observedLaw offspring lam h n)) k).map + (fun xs : List (Observation n) => (xs : Multiset (Observation n))) + +noncomputable def uniformSpin : PMF Spin := PMF.ofFintype (fun _ => 1 / 3) (by + simp + exact ENNReal.mul_inv_cancel (by norm_num) (by finiteness)) + + +noncomputable def marginal {α : Type*} (law : Spin → PMF α) : PMF α := + uniformSpin.bind law + + +noncomputable def posterior {α : Type*} (law : Spin → PMF α) (y : α) (i : Spin) : ℝ := + if marginal law y = 0 then 1 / 3 + else (law i y).toReal / (3 * (marginal law y).toReal) + + + +noncomputable def advantage {α : Type*} (law : Spin → PMF α) : ℝ := + ∑' y, (marginal law y).toReal * + ((∑ i : Spin, |posterior law y i - 1 / 3|) / 2) + +noncomputable def regularLaw (b : ℕ) (lam : ℝ) (h : Admissible lam) (n : ℕ) := + observedLaw (PMF.pure b) lam h n + + +noncomputable def poissonOffspring (d : ℝ) (hd : 0 ≤ d) : PMF ℕ := by + refine ⟨fun k => ENNReal.ofReal (Real.exp (-d) * d ^ k / (k.factorial : ℝ)), ?_⟩ + apply ENNReal.hasSum_coe.2 + have hsum : HasSum (fun k : ℕ => Real.exp (-d) * d ^ k / (k.factorial : ℝ)) 1 := + ProbabilityTheory.hasSum_one_poissonMeasure ⟨d, hd⟩ + simpa using hsum.toNNReal (fun k => by positivity) + +noncomputable def poissonLaw (d : ℝ) (hd : 0 ≤ d) (lam : ℝ) + (h : Admissible lam) (n : ℕ) := + observedLaw (poissonOffspring d hd) lam h n + +noncomputable def regularAdvantage (b : ℕ) (lam : ℝ) (h : Admissible lam) (n : ℕ) : ℝ := + advantage (regularLaw b lam h n) + +noncomputable def poissonAdvantage (d : ℝ) (hd : 1 < d) (lam : ℝ) + (h : Admissible lam) (n : ℕ) : ℝ := + advantage (poissonLaw d (le_trans (by norm_num) hd.le) lam h n) + + +def Reconstructs (a : ℕ → ℝ) : Prop := + ∃ L : ℝ, 0 < L ∧ Filter.Tendsto a Filter.atTop (nhds L) + +theorem regular_supercritical (b : ℕ) (hb : 2 ≤ b) (lam : ℝ) (h : Admissible lam) + (hcrit : 1 < (b : ℝ) * lam ^ 2) : Reconstructs (regularAdvantage b lam h) := by + sorry + +theorem poisson_supercritical (d : ℝ) (hd : 1 < d) (lam : ℝ) (h : Admissible lam) + (hcrit : 1 < d * lam ^ 2) : Reconstructs (poissonAdvantage d hd lam h) := by + sorry + +end ThreeState + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThreeStateSupercritical.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.ThreeState.regular_supercritical`, `OAI.ThreeState.poisson_supercritical` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/three-state-supercritical/solution/closure.txt b/tasks/three-state-supercritical/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dee149f3d2b0800f541364ce7cff96edec9f79d7 --- /dev/null +++ b/tasks/three-state-supercritical/solution/closure.txt @@ -0,0 +1,27 @@ +OAI.Probability.ThreeState.Basic +OAI.Probability.ThreeState.Couplings +OAI.Probability.ThreeState.DegreePosterior +OAI.Probability.ThreeState.Entropy +OAI.Probability.ThreeState.EntropyRecursion +OAI.Probability.ThreeState.Expectations +OAI.Probability.ThreeState.FixedPoints +OAI.Probability.ThreeState.Main +OAI.Probability.ThreeState.Messages +OAI.Probability.ThreeState.Negative +OAI.Probability.ThreeState.Noise +OAI.Probability.ThreeState.Observation +OAI.Probability.ThreeState.PairCorrelation +OAI.Probability.ThreeState.PoissonBounds +OAI.Probability.ThreeState.PoissonCalculus +OAI.Probability.ThreeState.PoissonCritical +OAI.Probability.ThreeState.PosteriorMoments +OAI.Probability.ThreeState.Projection +OAI.Probability.ThreeState.RadialDerivatives +OAI.Probability.ThreeState.RadialMoments +OAI.Probability.ThreeState.Region +OAI.Probability.ThreeState.RegularCritical +OAI.Probability.ThreeState.Resolvents +OAI.Probability.ThreeState.ScalarBounds +OAI.Probability.ThreeState.Supercritical +OAI.Probability.ThreeState.Symmetry +OAI.Probability.ThreeState.Update diff --git a/tasks/three-state-supercritical/solution/reference.py b/tasks/three-state-supercritical/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/three-state-supercritical/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/three-state-supercritical/solution/solve.sh b/tasks/three-state-supercritical/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..05b2d1c9d7dd77f9ab4159f55a34c1122f365bdb --- /dev/null +++ b/tasks/three-state-supercritical/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThreeStateSupercritical, i.e. module OAI.Probability.ThreeState.Main and the +# 27 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThreeState.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThreeStateSupercritical" diff --git a/tasks/three-state-supercritical/task.toml b/tasks/three-state-supercritical/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d04bb86f9202d5d60231b0be2158808991d5bac4 --- /dev/null +++ b/tasks/three-state-supercritical/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/three-state-supercritical" +version = "1.0.0" +description = "Prove ThreeStateSupercritical (openai/math family 229: Sharp three- and four-state reconstruction thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThreeStateSupercritical.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThreeStateSupercritical" +family = "229" +family_title = "Sharp three- and four-state reconstruction thresholds" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThreeState.regular_supercritical", "OAI.ThreeState.poisson_supercritical"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThreeState.Main" +reference_modules = 27 +reference_lean_bytes = 382667 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 212 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12044 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/three-state-supercritical/tests/Challenge.lean b/tasks/three-state-supercritical/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..fe5745277c847260e359c23e1cacc8b1e66983ec --- /dev/null +++ b/tasks/three-state-supercritical/tests/Challenge.lean @@ -0,0 +1,108 @@ +import Mathlib + +namespace OAI + +namespace ThreeState + +abbrev Spin := Fin 3 + + +def Admissible (lam : ℝ) : Prop := -(1 / 2 : ℝ) ≤ lam ∧ lam ≤ 1 + + +noncomputable def channel (lam : ℝ) (i j : Spin) : ℝ := + if i = j then (1 + 2 * lam) / 3 else (1 - lam) / 3 + + + +def Observation : ℕ → Type + | 0 => Spin + | n + 1 => Multiset (Observation n) + +theorem channel_nonneg {lam : ℝ} (h : Admissible lam) (i j : Spin) : + 0 ≤ channel lam i j := by + unfold channel + split_ifs + · dsimp [Admissible] at h + linarith [h.1] + · dsimp [Admissible] at h + linarith [h.2] + +theorem channel_sum (lam : ℝ) (i : Spin) : ∑ j, channel lam i j = 1 := by + fin_cases i <;> simp [channel, Fin.sum_univ_succ] <;> ring + +noncomputable def channelPMF (lam : ℝ) (h : Admissible lam) (i : Spin) : PMF Spin := + PMF.ofFintype (fun j => ENNReal.ofReal (channel lam i j)) (by + rw [← ENNReal.ofReal_sum_of_nonneg (fun j _ => channel_nonneg h i j)] + simp [channel_sum]) + + +noncomputable def iidList {α : Type*} (p : PMF α) : ℕ → PMF (List α) + | 0 => PMF.pure [] + | n + 1 => p.bind fun a => (iidList p n).map (List.cons a) + + + +noncomputable def observedLaw (offspring : PMF ℕ) (lam : ℝ) (h : Admissible lam) : + (n : ℕ) → Spin → PMF (Observation n) + | 0, i => PMF.pure i + | n + 1, i => offspring.bind fun k => + (iidList ((channelPMF lam h i).bind (observedLaw offspring lam h n)) k).map + (fun xs : List (Observation n) => (xs : Multiset (Observation n))) + +noncomputable def uniformSpin : PMF Spin := PMF.ofFintype (fun _ => 1 / 3) (by + simp + exact ENNReal.mul_inv_cancel (by norm_num) (by finiteness)) + + +noncomputable def marginal {α : Type*} (law : Spin → PMF α) : PMF α := + uniformSpin.bind law + + +noncomputable def posterior {α : Type*} (law : Spin → PMF α) (y : α) (i : Spin) : ℝ := + if marginal law y = 0 then 1 / 3 + else (law i y).toReal / (3 * (marginal law y).toReal) + + + +noncomputable def advantage {α : Type*} (law : Spin → PMF α) : ℝ := + ∑' y, (marginal law y).toReal * + ((∑ i : Spin, |posterior law y i - 1 / 3|) / 2) + +noncomputable def regularLaw (b : ℕ) (lam : ℝ) (h : Admissible lam) (n : ℕ) := + observedLaw (PMF.pure b) lam h n + + +noncomputable def poissonOffspring (d : ℝ) (hd : 0 ≤ d) : PMF ℕ := by + refine ⟨fun k => ENNReal.ofReal (Real.exp (-d) * d ^ k / (k.factorial : ℝ)), ?_⟩ + apply ENNReal.hasSum_coe.2 + have hsum : HasSum (fun k : ℕ => Real.exp (-d) * d ^ k / (k.factorial : ℝ)) 1 := + ProbabilityTheory.hasSum_one_poissonMeasure ⟨d, hd⟩ + simpa using hsum.toNNReal (fun k => by positivity) + +noncomputable def poissonLaw (d : ℝ) (hd : 0 ≤ d) (lam : ℝ) + (h : Admissible lam) (n : ℕ) := + observedLaw (poissonOffspring d hd) lam h n + +noncomputable def regularAdvantage (b : ℕ) (lam : ℝ) (h : Admissible lam) (n : ℕ) : ℝ := + advantage (regularLaw b lam h n) + +noncomputable def poissonAdvantage (d : ℝ) (hd : 1 < d) (lam : ℝ) + (h : Admissible lam) (n : ℕ) : ℝ := + advantage (poissonLaw d (le_trans (by norm_num) hd.le) lam h n) + + +def Reconstructs (a : ℕ → ℝ) : Prop := + ∃ L : ℝ, 0 < L ∧ Filter.Tendsto a Filter.atTop (nhds L) + +theorem regular_supercritical (b : ℕ) (hb : 2 ≤ b) (lam : ℝ) (h : Admissible lam) + (hcrit : 1 < (b : ℝ) * lam ^ 2) : Reconstructs (regularAdvantage b lam h) := by + sorry + +theorem poisson_supercritical (d : ℝ) (hd : 1 < d) (lam : ℝ) (h : Admissible lam) + (hcrit : 1 < d * lam ^ 2) : Reconstructs (poissonAdvantage d hd lam h) := by + sorry + +end ThreeState + +end OAI diff --git a/tasks/three-state-supercritical/tests/grade.py b/tasks/three-state-supercritical/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/three-state-supercritical/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/three-state-supercritical/tests/task.json b/tasks/three-state-supercritical/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e18bf442f34780e2c2bf2ed4669b1dbab04439eb --- /dev/null +++ b/tasks/three-state-supercritical/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "ThreeStateSupercritical", + "comparator": { + "theorem_names": [ + "OAI.ThreeState.regular_supercritical", + "OAI.ThreeState.poisson_supercritical" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11144 +} \ No newline at end of file diff --git a/tasks/three-state-supercritical/tests/test.sh b/tasks/three-state-supercritical/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/three-state-supercritical/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/three-state-tree-clauses/environment/Dockerfile b/tasks/three-state-tree-clauses/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/three-state-tree-clauses/environment/fetch_mathlib.sh b/tasks/three-state-tree-clauses/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/three-state-tree-clauses/environment/lake-manifest.json b/tasks/three-state-tree-clauses/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/three-state-tree-clauses/environment/lakefile.lean b/tasks/three-state-tree-clauses/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/three-state-tree-clauses/environment/lean_setup.sh b/tasks/three-state-tree-clauses/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/three-state-tree-clauses/environment/pack_submission.py b/tasks/three-state-tree-clauses/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/three-state-tree-clauses/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/three-state-tree-clauses/instruction.md b/tasks/three-state-tree-clauses/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3974b67acea61601af8c81a9e5ef6e3527220087 --- /dev/null +++ b/tasks/three-state-tree-clauses/instruction.md @@ -0,0 +1,155 @@ +# openai/math challenge `ThreeStateTreeClauses` (family 229) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 229 of the release, *Sharp three- and four-state reconstruction thresholds* +(Probability and statistical mechanics). The family as a whole: Proves the exact reconstruction threshold $d\lambda^2>1$, with nonreconstruction at equality, for three-state symmetric and four-state ferromagnetic broadcasting on regular trees ($d\ge2$) and observed Poisson trees (mean $d>1$ and $d>0$, respectively), with Poisson advantage averaged without conditioning on survival. The three-state theorem allows both signs of $\lambda$ and gives the exact weak-recovery threshold for the symmetric three-community stochastic block model. + +The challenge is `ThreeStateTreeClauses`, also at `/opt/openai-math/challenges/ThreeStateTreeClauses.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ENNReal NNReal +open Filter + +namespace ThreeState.TreeClauses + +abbrev Spin := Fin 3 + +def Admissible (lam : ℝ) : Prop := -(1 / 2 : ℝ) ≤ lam ∧ lam ≤ 1 + +def channelWeight (lam : ℝ) (i j : Spin) : ℝ := + if i = j then (1 + 2 * lam) / 3 else (1 - lam) / 3 + +lemma channelWeight_nonneg {lam : ℝ} (hlam : Admissible lam) (i j : Spin) : + 0 ≤ channelWeight lam i j := by + unfold channelWeight + split_ifs <;> dsimp [Admissible] at hlam <;> linarith [hlam.1, hlam.2] + +lemma channelWeight_sum (lam : ℝ) (i : Spin) : ∑ j, channelWeight lam i j = 1 := by + fin_cases i <;> simp [channelWeight, Fin.sum_univ_three] <;> ring + +def channel (lam : ℝ) (hlam : Admissible lam) (i : Spin) : PMF Spin := + PMF.ofFintype (fun j ↦ ENNReal.ofReal (channelWeight lam i j)) (by + rw [← ENNReal.ofReal_sum_of_nonneg (fun j _ ↦ channelWeight_nonneg hlam i j), + channelWeight_sum] + norm_num) + +def Observation : ℕ → Type + | 0 => Spin + | n + 1 => Multiset (Observation n) + +def iidList {α : Type} (p : PMF α) : ℕ → PMF (List α) + | 0 => PMF.pure [] + | n + 1 => p.bind fun x ↦ (iidList p n).map (List.cons x) + +def observationLaw (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) : + (ℓ : ℕ) → Spin → PMF (Observation ℓ) + | 0, i => PMF.pure i + | ℓ + 1, i => offspring.bind fun n ↦ + (iidList ((channel lam hlam i).bind (observationLaw lam hlam offspring ℓ)) n).map + (fun xs ↦ (xs : Multiset (Observation ℓ))) + +def jointWeight (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (i : Spin) (o : Observation ℓ) : ℝ≥0∞ := + (1 / 3 : ℝ≥0∞) * observationLaw lam hlam offspring ℓ i o + +def marginalWeight (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (o : Observation ℓ) : ℝ≥0∞ := + ∑ i, jointWeight lam hlam offspring ℓ i o + +def posterior (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (o : Observation ℓ) (i : Spin) : ℝ := + (jointWeight lam hlam offspring ℓ i o / marginalWeight lam hlam offspring ℓ o).toReal + +def advantage (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) (ℓ : ℕ) : ℝ := + ∑' o : Observation ℓ, (marginalWeight lam hlam offspring ℓ o).toReal * + ((∑ i : Spin, |posterior lam hlam offspring ℓ o i - (1 / 3 : ℝ)|) / 2) + +def Reconstructs (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) : Prop := + ∃ a : ℝ, 0 < a ∧ Tendsto (advantage lam hlam offspring) atTop (nhds a) + +namespace Probability + +def poissonWeight (rate : ℝ) (count : ℕ) : ℝ := + Real.exp (-rate) * rate ^ count / (count.factorial : ℝ) + +lemma poissonWeight_nonneg {rate : ℝ} (hrate : 0 ≤ rate) (count : ℕ) : + 0 ≤ poissonWeight rate count := by + unfold poissonWeight + positivity + +lemma poissonWeight_mass (rate : ℝ≥0) : HasSum (poissonWeight rate) 1 := + ProbabilityTheory.hasSum_one_poissonMeasure rate + +def _root_.OAI.ThreeState.TreeClauses.poissonPMF (rate : ℝ≥0) : PMF ℕ := by + refine ⟨fun count ↦ ENNReal.ofReal (poissonWeight rate count), ?_⟩ + apply ENNReal.hasSum_coe.mpr + rw [← Real.toNNReal_one] + exact (poissonWeight_mass rate).toNNReal (poissonWeight_nonneg rate.coe_nonneg) + +end Probability + +end ThreeState.TreeClauses + +open scoped Topology +namespace ThreeState.TreeClauses.Tree + +theorem regular_reconstructs_above_KS (b : ℕ) (lam : ℝ) (hlam : Admissible lam) + (hKS : 1 < (b:ℝ)*lam^2) : Reconstructs lam hlam (PMF.pure b) := by + sorry + +theorem poisson_reconstructs_above_KS (d : ℝ≥0) (lam : ℝ) (hlam : Admissible lam) + (hKS : 1 < (d:ℝ)*lam^2) : Reconstructs lam hlam (poissonPMF d) := by + sorry + +end ThreeState.TreeClauses.Tree + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThreeStateTreeClauses.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.ThreeState.TreeClauses.Tree.regular_reconstructs_above_KS`, `OAI.ThreeState.TreeClauses.Tree.poisson_reconstructs_above_KS` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/three-state-tree-clauses/solution/closure.txt b/tasks/three-state-tree-clauses/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..95bd2e220d551bc6b15a599c05b82e2a040c3f52 --- /dev/null +++ b/tasks/three-state-tree-clauses/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Probability.ThreeStateClauses.Basic +OAI.Probability.ThreeStateClauses.BranchGrowth +OAI.Probability.ThreeStateClauses.BranchMoments +OAI.Probability.ThreeStateClauses.CompactLimits +OAI.Probability.ThreeStateClauses.Correlation +OAI.Probability.ThreeStateClauses.CountableStatistics +OAI.Probability.ThreeStateClauses.Degradation +OAI.Probability.ThreeStateClauses.DiscreteLaw +OAI.Probability.ThreeStateClauses.FiniteUpdate +OAI.Probability.ThreeStateClauses.InformationLoss +OAI.Probability.ThreeStateClauses.Main +OAI.Probability.ThreeStateClauses.ObservedMixtures +OAI.Probability.ThreeStateClauses.OffspringLaws +OAI.Probability.ThreeStateClauses.PoissonCalculus +OAI.Probability.ThreeStateClauses.PoissonFixed +OAI.Probability.ThreeStateClauses.PoissonLaw +OAI.Probability.ThreeStateClauses.PoissonMoments +OAI.Probability.ThreeStateClauses.PoissonReconstruction +OAI.Probability.ThreeStateClauses.PositiveFixed +OAI.Probability.ThreeStateClauses.PositiveMoments +OAI.Probability.ThreeStateClauses.PosteriorLaw +OAI.Probability.ThreeStateClauses.Products +OAI.Probability.ThreeStateClauses.Projection +OAI.Probability.ThreeStateClauses.RadialAlgebra +OAI.Probability.ThreeStateClauses.RadialBounds +OAI.Probability.ThreeStateClauses.RadialCalculus +OAI.Probability.ThreeStateClauses.RegularCritical +OAI.Probability.ThreeStateClauses.RegularLaw +OAI.Probability.ThreeStateClauses.RegularReconstruction +OAI.Probability.ThreeStateClauses.RegularStatistics +OAI.Probability.ThreeStateClauses.ScalarBounds diff --git a/tasks/three-state-tree-clauses/solution/reference.py b/tasks/three-state-tree-clauses/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/three-state-tree-clauses/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/three-state-tree-clauses/solution/solve.sh b/tasks/three-state-tree-clauses/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..52af0675ed55209cd0abea4fdc41f4baba22a6cd --- /dev/null +++ b/tasks/three-state-tree-clauses/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThreeStateTreeClauses, i.e. module OAI.Probability.ThreeStateClauses.Main and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.ThreeStateClauses.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThreeStateTreeClauses" diff --git a/tasks/three-state-tree-clauses/task.toml b/tasks/three-state-tree-clauses/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2e7af65d084f8fc9fc167da2ad5d350f8125b51d --- /dev/null +++ b/tasks/three-state-tree-clauses/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/three-state-tree-clauses" +version = "1.0.0" +description = "Prove ThreeStateTreeClauses (openai/math family 229: Sharp three- and four-state reconstruction thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThreeStateTreeClauses.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThreeStateTreeClauses" +family = "229" +family_title = "Sharp three- and four-state reconstruction thresholds" +subject = "Probability and statistical mechanics" +theorems = ["OAI.ThreeState.TreeClauses.Tree.regular_reconstructs_above_KS", "OAI.ThreeState.TreeClauses.Tree.poisson_reconstructs_above_KS"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.ThreeStateClauses.Main" +reference_modules = 31 +reference_lean_bytes = 383958 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 204 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12045 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/three-state-tree-clauses/tests/Challenge.lean b/tasks/three-state-tree-clauses/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..d0bdc7f256166c8fa888fe43e21c94427f0e3fd6 --- /dev/null +++ b/tasks/three-state-tree-clauses/tests/Challenge.lean @@ -0,0 +1,104 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators ENNReal NNReal +open Filter + +namespace ThreeState.TreeClauses + +abbrev Spin := Fin 3 + +def Admissible (lam : ℝ) : Prop := -(1 / 2 : ℝ) ≤ lam ∧ lam ≤ 1 + +def channelWeight (lam : ℝ) (i j : Spin) : ℝ := + if i = j then (1 + 2 * lam) / 3 else (1 - lam) / 3 + +lemma channelWeight_nonneg {lam : ℝ} (hlam : Admissible lam) (i j : Spin) : + 0 ≤ channelWeight lam i j := by + unfold channelWeight + split_ifs <;> dsimp [Admissible] at hlam <;> linarith [hlam.1, hlam.2] + +lemma channelWeight_sum (lam : ℝ) (i : Spin) : ∑ j, channelWeight lam i j = 1 := by + fin_cases i <;> simp [channelWeight, Fin.sum_univ_three] <;> ring + +def channel (lam : ℝ) (hlam : Admissible lam) (i : Spin) : PMF Spin := + PMF.ofFintype (fun j ↦ ENNReal.ofReal (channelWeight lam i j)) (by + rw [← ENNReal.ofReal_sum_of_nonneg (fun j _ ↦ channelWeight_nonneg hlam i j), + channelWeight_sum] + norm_num) + +def Observation : ℕ → Type + | 0 => Spin + | n + 1 => Multiset (Observation n) + +def iidList {α : Type} (p : PMF α) : ℕ → PMF (List α) + | 0 => PMF.pure [] + | n + 1 => p.bind fun x ↦ (iidList p n).map (List.cons x) + +def observationLaw (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) : + (ℓ : ℕ) → Spin → PMF (Observation ℓ) + | 0, i => PMF.pure i + | ℓ + 1, i => offspring.bind fun n ↦ + (iidList ((channel lam hlam i).bind (observationLaw lam hlam offspring ℓ)) n).map + (fun xs ↦ (xs : Multiset (Observation ℓ))) + +def jointWeight (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (i : Spin) (o : Observation ℓ) : ℝ≥0∞ := + (1 / 3 : ℝ≥0∞) * observationLaw lam hlam offspring ℓ i o + +def marginalWeight (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (o : Observation ℓ) : ℝ≥0∞ := + ∑ i, jointWeight lam hlam offspring ℓ i o + +def posterior (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) + (ℓ : ℕ) (o : Observation ℓ) (i : Spin) : ℝ := + (jointWeight lam hlam offspring ℓ i o / marginalWeight lam hlam offspring ℓ o).toReal + +def advantage (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) (ℓ : ℕ) : ℝ := + ∑' o : Observation ℓ, (marginalWeight lam hlam offspring ℓ o).toReal * + ((∑ i : Spin, |posterior lam hlam offspring ℓ o i - (1 / 3 : ℝ)|) / 2) + +def Reconstructs (lam : ℝ) (hlam : Admissible lam) (offspring : PMF ℕ) : Prop := + ∃ a : ℝ, 0 < a ∧ Tendsto (advantage lam hlam offspring) atTop (nhds a) + +namespace Probability + +def poissonWeight (rate : ℝ) (count : ℕ) : ℝ := + Real.exp (-rate) * rate ^ count / (count.factorial : ℝ) + +lemma poissonWeight_nonneg {rate : ℝ} (hrate : 0 ≤ rate) (count : ℕ) : + 0 ≤ poissonWeight rate count := by + unfold poissonWeight + positivity + +lemma poissonWeight_mass (rate : ℝ≥0) : HasSum (poissonWeight rate) 1 := + ProbabilityTheory.hasSum_one_poissonMeasure rate + +def _root_.OAI.ThreeState.TreeClauses.poissonPMF (rate : ℝ≥0) : PMF ℕ := by + refine ⟨fun count ↦ ENNReal.ofReal (poissonWeight rate count), ?_⟩ + apply ENNReal.hasSum_coe.mpr + rw [← Real.toNNReal_one] + exact (poissonWeight_mass rate).toNNReal (poissonWeight_nonneg rate.coe_nonneg) + +end Probability + +end ThreeState.TreeClauses + +open scoped Topology +namespace ThreeState.TreeClauses.Tree + +theorem regular_reconstructs_above_KS (b : ℕ) (lam : ℝ) (hlam : Admissible lam) + (hKS : 1 < (b:ℝ)*lam^2) : Reconstructs lam hlam (PMF.pure b) := by + sorry + +theorem poisson_reconstructs_above_KS (d : ℝ≥0) (lam : ℝ) (hlam : Admissible lam) + (hKS : 1 < (d:ℝ)*lam^2) : Reconstructs lam hlam (poissonPMF d) := by + sorry + +end ThreeState.TreeClauses.Tree + +end + +end OAI diff --git a/tasks/three-state-tree-clauses/tests/grade.py b/tasks/three-state-tree-clauses/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/three-state-tree-clauses/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/three-state-tree-clauses/tests/task.json b/tasks/three-state-tree-clauses/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d8987c65789233bac8207854db0d51aa68912ff1 --- /dev/null +++ b/tasks/three-state-tree-clauses/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "ThreeStateTreeClauses", + "comparator": { + "theorem_names": [ + "OAI.ThreeState.TreeClauses.Tree.regular_reconstructs_above_KS", + "OAI.ThreeState.TreeClauses.Tree.poisson_reconstructs_above_KS" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11145 +} \ No newline at end of file diff --git a/tasks/three-state-tree-clauses/tests/test.sh b/tasks/three-state-tree-clauses/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/three-state-tree-clauses/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/three-torus/environment/Dockerfile b/tasks/three-torus/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/three-torus/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/three-torus/environment/fetch_mathlib.sh b/tasks/three-torus/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/three-torus/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/three-torus/environment/lake-manifest.json b/tasks/three-torus/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/three-torus/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/three-torus/environment/lakefile.lean b/tasks/three-torus/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/three-torus/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/three-torus/environment/lean_setup.sh b/tasks/three-torus/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/three-torus/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/three-torus/environment/pack_submission.py b/tasks/three-torus/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/three-torus/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/three-torus/instruction.md b/tasks/three-torus/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..017219c2354c97498bdb29f1b8d3c7dc0a7479f7 --- /dev/null +++ b/tasks/three-torus/instruction.md @@ -0,0 +1,140 @@ +# openai/math challenge `ThreeTorus` (family 144) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 144 of the release, *Banach's simple Lebesgue-spectrum problem* +(Dynamical systems and ergodic theory). The family as a whole: Resolves the probability-preserving form of Banach's simple Lebesgue-spectrum problem within smooth dynamics. A smooth volume-preserving diffeomorphism of the standard-volume three-torus has simple Lebesgue spectrum on its entire complex mean-zero $L^2$ space: the bilateral iterates of one real observable form an orthonormal basis of that space. + +The challenge is `ThreeTorus`, also at `/opt/openai-math/challenges/ThreeTorus.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +The torus is (ℝ/ℤ)³ with normalized product Haar measure. Smoothness means +local smooth lifts on the universal cover, for both the map and its inverse. + +The almost-everywhere graph conditions are independent of representatives of +L² classes. The real generator's bilateral Koopman orbit spans the entire +complex mean-zero L² space. The spectral model is the full circle L² space +with multiplication by the first Fourier character. +-/ + +noncomputable section +open MeasureTheory Set +open scoped ENNReal Topology + +namespace ThreeTorus + +abbrev Torus := Fin 3 → UnitAddCircle +abbrev Cover := Fin 3 → ℝ + +def project (x : Cover) : Torus := fun i => (x i : UnitAddCircle) + +def Smooth (T : Torus → Torus) : Prop := + ∀ x : Cover, ∃ U : Set Cover, IsOpen U ∧ x ∈ U ∧ + ∃ F : Cover → Cover, ContDiffOn ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) F U ∧ + ∀ y ∈ U, T (project y) = project (F y) + +def μ : Measure Torus := Measure.pi (fun _ : Fin 3 => AddCircle.haarAddCircle) + +instance : IsProbabilityMeasure μ := by unfold μ; infer_instance + +abbrev H : Type := Lp ℂ 2 μ + +/-- The full complex subspace defined by zero Lebesgue integral. -/ +def meanZero : Submodule ℂ H where + carrier := {f | ∫ x, f x ∂μ = 0} + zero_mem' := by + change ∫ x, (0 : H) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_zero ℂ 2 μ)] + simp + add_mem' := by + intro f g hf hg + change ∫ x, (f + g) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_add f g)] + change ∫ x, f x + g x ∂μ = 0 + rw [integral_add (MemLp.integrable (by norm_num) (Lp.memLp f)) + (MemLp.integrable (by norm_num) (Lp.memLp g))] + change (∫ x, f x ∂μ) + (∫ x, g x ∂μ) = 0 + rw [show ∫ x, f x ∂μ = 0 from hf, show ∫ x, g x ∂μ = 0 from hg, add_zero] + smul_mem' := by + intro c f hf + change ∫ x, (c • f) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_smul c f)] + change ∫ x, c • f x ∂μ = 0 + rw [integral_smul] + rw [show ∫ x, f x ∂μ = 0 from hf, smul_zero] + +abbrev H₀ := ↥meanZero +abbrev CircleH : Type := Lp ℂ 2 (AddCircle.haarAddCircle (T := (1 : ℝ))) + +def IsReal (f : H₀) : Prop := ∀ᵐ x ∂μ, (f.1 x).im = 0 + +/-- Complete simple Lebesgue spectrum, including the stated consequences. -/ +def MainConclusion : Prop := + ∃ T : Equiv.Perm Torus, + Smooth T ∧ Smooth T.symm ∧ MeasurePreserving T μ μ ∧ + ∃ f : H₀, IsReal f ∧ + ∃ v : ℤ → H₀, + (∀ n : ℤ, ∀ᵐ x ∂μ, (v n).1 x = f.1 ((T ^ n) x)) ∧ + Orthonormal ℂ v ∧ + Dense (Submodule.span ℂ (Set.range v) : Set H₀) ∧ + Ergodic T μ ∧ + ∃ W : H₀ ≃ₗᵢ[ℂ] CircleH, + ∀ g : H₀, ∃ h : H₀, + (∀ᵐ x ∂μ, h.1 x = g.1 (T x)) ∧ + (∀ᵐ z ∂(AddCircle.haarAddCircle (T := (1 : ℝ))), + W h z = fourier 1 z * W g z) + +theorem simple_lebesgue_spectrum : MainConclusion := by + sorry + +end ThreeTorus + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/ThreeTorus.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ThreeTorus.simple_lebesgue_spectrum` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/three-torus/solution/closure.txt b/tasks/three-torus/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1f9506de325f6b82a31685483a70f0b1681d570d --- /dev/null +++ b/tasks/three-torus/solution/closure.txt @@ -0,0 +1,37 @@ +OAI.Dynamics.ThreeTorus.Averaging +OAI.Dynamics.ThreeTorus.Basic +OAI.Dynamics.ThreeTorus.BlockMoments +OAI.Dynamics.ThreeTorus.ColorBlocks +OAI.Dynamics.ThreeTorus.ControlledBlocks +OAI.Dynamics.ThreeTorus.Cutoffs +OAI.Dynamics.ThreeTorus.CyclicPrediction +OAI.Dynamics.ThreeTorus.DynamicsLimit +OAI.Dynamics.ThreeTorus.FiniteBlocks +OAI.Dynamics.ThreeTorus.FlatPackets +OAI.Dynamics.ThreeTorus.Geometry +OAI.Dynamics.ThreeTorus.Jitter +OAI.Dynamics.ThreeTorus.Main +OAI.Dynamics.ThreeTorus.NeutralSupport +OAI.Dynamics.ThreeTorus.PacketAlgebra +OAI.Dynamics.ThreeTorus.PacketCalculus +OAI.Dynamics.ThreeTorus.PacketStates +OAI.Dynamics.ThreeTorus.PassageDensity +OAI.Dynamics.ThreeTorus.PassageFamilies +OAI.Dynamics.ThreeTorus.PassageMass +OAI.Dynamics.ThreeTorus.PhysicalBasis +OAI.Dynamics.ThreeTorus.PhysicalJets +OAI.Dynamics.ThreeTorus.PositiveLaws +OAI.Dynamics.ThreeTorus.Prediction +OAI.Dynamics.ThreeTorus.PredictionModels +OAI.Dynamics.ThreeTorus.Preparation +OAI.Dynamics.ThreeTorus.RetainedPackets +OAI.Dynamics.ThreeTorus.SmoothLimits +OAI.Dynamics.ThreeTorus.SpectralTransport +OAI.Dynamics.ThreeTorus.Stages +OAI.Dynamics.ThreeTorus.StationaryPhase +OAI.Dynamics.ThreeTorus.SymmetricPackets +OAI.Dynamics.ThreeTorus.TensorPackets +OAI.Dynamics.ThreeTorus.TrackedPackets +OAI.Dynamics.ThreeTorus.Transmission +OAI.Dynamics.ThreeTorus.Twists +OAI.Dynamics.ThreeTorus.Whitening diff --git a/tasks/three-torus/solution/reference.py b/tasks/three-torus/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/three-torus/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/three-torus/solution/solve.sh b/tasks/three-torus/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f96f0aa20f19b073ec773ba2009690fdcb4cd3fb --- /dev/null +++ b/tasks/three-torus/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of ThreeTorus, i.e. module OAI.Dynamics.ThreeTorus.Main and the +# 37 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Dynamics.ThreeTorus.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of ThreeTorus" diff --git a/tasks/three-torus/task.toml b/tasks/three-torus/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..6363bcef209bee3f44371aab71a290bc3dfe60df --- /dev/null +++ b/tasks/three-torus/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/three-torus" +version = "1.0.0" +description = "Prove ThreeTorus (openai/math family 144: Banach's simple Lebesgue-spectrum problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "dynamical-systems-and-ergodic-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/ThreeTorus.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "ThreeTorus" +family = "144" +family_title = "Banach's simple Lebesgue-spectrum problem" +subject = "Dynamical systems and ergodic theory" +theorems = ["OAI.ThreeTorus.simple_lebesgue_spectrum"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Dynamics.ThreeTorus.Main" +reference_modules = 37 +reference_lean_bytes = 1720327 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 669 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13248 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/three-torus/tests/Challenge.lean b/tasks/three-torus/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3d7043b2fbc13f291681d8b5e0d924fe70fbe314 --- /dev/null +++ b/tasks/three-torus/tests/Challenge.lean @@ -0,0 +1,89 @@ +import Mathlib + +namespace OAI + +/-! +The torus is (ℝ/ℤ)³ with normalized product Haar measure. Smoothness means +local smooth lifts on the universal cover, for both the map and its inverse. + +The almost-everywhere graph conditions are independent of representatives of +L² classes. The real generator's bilateral Koopman orbit spans the entire +complex mean-zero L² space. The spectral model is the full circle L² space +with multiplication by the first Fourier character. +-/ + +noncomputable section +open MeasureTheory Set +open scoped ENNReal Topology + +namespace ThreeTorus + +abbrev Torus := Fin 3 → UnitAddCircle +abbrev Cover := Fin 3 → ℝ + +def project (x : Cover) : Torus := fun i => (x i : UnitAddCircle) + +def Smooth (T : Torus → Torus) : Prop := + ∀ x : Cover, ∃ U : Set Cover, IsOpen U ∧ x ∈ U ∧ + ∃ F : Cover → Cover, ContDiffOn ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) F U ∧ + ∀ y ∈ U, T (project y) = project (F y) + +def μ : Measure Torus := Measure.pi (fun _ : Fin 3 => AddCircle.haarAddCircle) + +instance : IsProbabilityMeasure μ := by unfold μ; infer_instance + +abbrev H : Type := Lp ℂ 2 μ + +/-- The full complex subspace defined by zero Lebesgue integral. -/ +def meanZero : Submodule ℂ H where + carrier := {f | ∫ x, f x ∂μ = 0} + zero_mem' := by + change ∫ x, (0 : H) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_zero ℂ 2 μ)] + simp + add_mem' := by + intro f g hf hg + change ∫ x, (f + g) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_add f g)] + change ∫ x, f x + g x ∂μ = 0 + rw [integral_add (MemLp.integrable (by norm_num) (Lp.memLp f)) + (MemLp.integrable (by norm_num) (Lp.memLp g))] + change (∫ x, f x ∂μ) + (∫ x, g x ∂μ) = 0 + rw [show ∫ x, f x ∂μ = 0 from hf, show ∫ x, g x ∂μ = 0 from hg, add_zero] + smul_mem' := by + intro c f hf + change ∫ x, (c • f) x ∂μ = 0 + rw [integral_congr_ae (Lp.coeFn_smul c f)] + change ∫ x, c • f x ∂μ = 0 + rw [integral_smul] + rw [show ∫ x, f x ∂μ = 0 from hf, smul_zero] + +abbrev H₀ := ↥meanZero +abbrev CircleH : Type := Lp ℂ 2 (AddCircle.haarAddCircle (T := (1 : ℝ))) + +def IsReal (f : H₀) : Prop := ∀ᵐ x ∂μ, (f.1 x).im = 0 + +/-- Complete simple Lebesgue spectrum, including the stated consequences. -/ +def MainConclusion : Prop := + ∃ T : Equiv.Perm Torus, + Smooth T ∧ Smooth T.symm ∧ MeasurePreserving T μ μ ∧ + ∃ f : H₀, IsReal f ∧ + ∃ v : ℤ → H₀, + (∀ n : ℤ, ∀ᵐ x ∂μ, (v n).1 x = f.1 ((T ^ n) x)) ∧ + Orthonormal ℂ v ∧ + Dense (Submodule.span ℂ (Set.range v) : Set H₀) ∧ + Ergodic T μ ∧ + ∃ W : H₀ ≃ₗᵢ[ℂ] CircleH, + ∀ g : H₀, ∃ h : H₀, + (∀ᵐ x ∂μ, h.1 x = g.1 (T x)) ∧ + (∀ᵐ z ∂(AddCircle.haarAddCircle (T := (1 : ℝ))), + W h z = fourier 1 z * W g z) + +theorem simple_lebesgue_spectrum : MainConclusion := by + sorry + +end ThreeTorus + +end + +end OAI diff --git a/tasks/three-torus/tests/grade.py b/tasks/three-torus/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/three-torus/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/three-torus/tests/task.json b/tasks/three-torus/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0ee7ed865a4112695d04654fea4dda4b2efa311a --- /dev/null +++ b/tasks/three-torus/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "ThreeTorus", + "comparator": { + "theorem_names": [ + "OAI.ThreeTorus.simple_lebesgue_spectrum" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12348 +} \ No newline at end of file diff --git a/tasks/three-torus/tests/test.sh b/tasks/three-torus/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/three-torus/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/tingley-sphere-isometry/environment/Dockerfile b/tasks/tingley-sphere-isometry/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/tingley-sphere-isometry/environment/fetch_mathlib.sh b/tasks/tingley-sphere-isometry/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/tingley-sphere-isometry/environment/lake-manifest.json b/tasks/tingley-sphere-isometry/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/tingley-sphere-isometry/environment/lakefile.lean b/tasks/tingley-sphere-isometry/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/tingley-sphere-isometry/environment/lean_setup.sh b/tasks/tingley-sphere-isometry/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/tingley-sphere-isometry/environment/pack_submission.py b/tasks/tingley-sphere-isometry/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/tingley-sphere-isometry/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/tingley-sphere-isometry/instruction.md b/tasks/tingley-sphere-isometry/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a47761722cd9396e1838094890f56b1e5277fdee --- /dev/null +++ b/tasks/tingley-sphere-isometry/instruction.md @@ -0,0 +1,92 @@ +# openai/math challenge `TingleySphereIsometry` (family 322) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 322 of the release, *Tingley's sphere-isometry problem* +(Functional analysis). The family as a whole: Resolves Tingley's problem: every surjective isometry between the unit spheres of nonzero real Banach spaces extends uniquely to a surjective real-linear isometry of the whole spaces. No dimension restriction is imposed, so the metric geometry of the unit sphere determines the Banach space up to linear isometry. + +The challenge is `TingleySphereIsometry`, also at `/opt/openai-math/challenges/TingleySphereIsometry.lean`: + +```lean +import Mathlib.Analysis.Normed.Module.RCLike.Basic +import Mathlib.Topology.MetricSpace.Isometry + +namespace OAI + +noncomputable section + +namespace Tingley + +universe u v + +abbrev UnitSphere (X : Type u) [NormedAddCommGroup X] := {x : X // ‖x‖ = 1} + +variable {X : Type u} {Y : Type v} +variable [NormedAddCommGroup X] [NormedSpace ℝ X] +variable [NormedAddCommGroup Y] [NormedSpace ℝ Y] + +def normalize (x : X) (hx : x ≠ 0) : UnitSphere X := + ⟨‖x‖⁻¹ • x, norm_smul_inv_norm hx⟩ + +/-- Radial formula, surjectivity, and uniqueness among all real-linear extensions. -/ +theorem tingley_sphere_isometry_full + {X : Type u} {Y : Type v} + [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + [NormedAddCommGroup Y] [NormedSpace ℝ Y] [CompleteSpace Y] + [Nontrivial X] [Nontrivial Y] + (f : UnitSphere X → UnitSphere Y) (hf : Isometry f) (hs : Function.Surjective f) : + ∃ T : X ≃ₗᵢ[ℝ] Y, + (∀ u : UnitSphere X, T (u : X) = (f u : Y)) ∧ + T 0 = 0 ∧ + (∀ x : X, ∀ hx : x ≠ 0, T x = ‖x‖ • (f (normalize x hx) : Y)) ∧ + Function.Surjective T ∧ + (∀ L : X →ₗ[ℝ] Y, (∀ u : UnitSphere X, L (u : X) = (f u : Y)) → + L = T.toLinearEquiv.toLinearMap) := by + sorry + +end Tingley + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TingleySphereIsometry.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Tingley.tingley_sphere_isometry_full` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/tingley-sphere-isometry/solution/closure.txt b/tasks/tingley-sphere-isometry/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..c32bf01f483497e80a704bf8dfd98bf10175d5e3 --- /dev/null +++ b/tasks/tingley-sphere-isometry/solution/closure.txt @@ -0,0 +1,67 @@ +OAI.Analysis.SphereIsometry.AlignedConfiguration +OAI.Analysis.SphereIsometry.Alignment +OAI.Analysis.SphereIsometry.AlignmentSet +OAI.Analysis.SphereIsometry.BarycentricBasic +OAI.Analysis.SphereIsometry.BarycentricFlags +OAI.Analysis.SphereIsometry.BarycentricIncidence +OAI.Analysis.SphereIsometry.BarycentricMesh +OAI.Analysis.SphereIsometry.BarycentricPoints +OAI.Analysis.SphereIsometry.BarycentricPurity +OAI.Analysis.SphereIsometry.BarycentricRestriction +OAI.Analysis.SphereIsometry.BarycentricSupport +OAI.Analysis.SphereIsometry.BarycentricZero +OAI.Analysis.SphereIsometry.Basic +OAI.Analysis.SphereIsometry.ChordContradiction +OAI.Analysis.SphereIsometry.ChordSecant +OAI.Analysis.SphereIsometry.CoefficientBins +OAI.Analysis.SphereIsometry.CompactApproximation +OAI.Analysis.SphereIsometry.CompactConvexFixedPoint +OAI.Analysis.SphereIsometry.CondensingFixedPoint +OAI.Analysis.SphereIsometry.CondensingIteration +OAI.Analysis.SphereIsometry.ConvexCoverRegroup +OAI.Analysis.SphereIsometry.ConvexDiameter +OAI.Analysis.SphereIsometry.DefectAttainment +OAI.Analysis.SphereIsometry.DefectSequence +OAI.Analysis.SphereIsometry.DiameterBounds +OAI.Analysis.SphereIsometry.Extension +OAI.Analysis.SphereIsometry.ExtremalPropagation +OAI.Analysis.SphereIsometry.FiniteComplex +OAI.Analysis.SphereIsometry.InvariantConvexSet +OAI.Analysis.SphereIsometry.IteratedPoints +OAI.Analysis.SphereIsometry.IteratedSubdivision +OAI.Analysis.SphereIsometry.KuratowskiBasic +OAI.Analysis.SphereIsometry.KuratowskiConvexHull +OAI.Analysis.SphereIsometry.KuratowskiNested +OAI.Analysis.SphereIsometry.KuratowskiTotalBounded +OAI.Analysis.SphereIsometry.LargeChord +OAI.Analysis.SphereIsometry.Main +OAI.Analysis.SphereIsometry.Model +OAI.Analysis.SphereIsometry.PositiveConvexFace +OAI.Analysis.SphereIsometry.PositiveScheduling +OAI.Analysis.SphereIsometry.ProbabilitySimplex +OAI.Analysis.SphereIsometry.RadialContact +OAI.Analysis.SphereIsometry.RadialExtension +OAI.Analysis.SphereIsometry.RadialPerturbation +OAI.Analysis.SphereIsometry.ReturnMap +OAI.Analysis.SphereIsometry.ReturnMapBounds +OAI.Analysis.SphereIsometry.ReturnMapEstimate +OAI.Analysis.SphereIsometry.ReturnMapFixedPoint +OAI.Analysis.SphereIsometry.ReturnMapNoncompactness +OAI.Analysis.SphereIsometry.ScalarBins +OAI.Analysis.SphereIsometry.SimplexFixedPoint +OAI.Analysis.SphereIsometry.SimplexLimit +OAI.Analysis.SphereIsometry.SmallChord +OAI.Analysis.SphereIsometry.Sperner +OAI.Analysis.SphereIsometry.SpernerBoundary +OAI.Analysis.SphereIsometry.SpernerFacet +OAI.Analysis.SphereIsometry.SpernerIncidence +OAI.Analysis.SphereIsometry.SphereCompletion +OAI.Analysis.SphereIsometry.SubdivisionData +OAI.Analysis.SphereIsometry.SubdivisionIncidence +OAI.Analysis.SphereIsometry.SubdivisionPointRestriction +OAI.Analysis.SphereIsometry.SubdivisionRestriction +OAI.Analysis.SphereIsometry.Supports +OAI.Analysis.SphereIsometry.UltraNormed +OAI.Analysis.SphereIsometry.UltraRealLimit +OAI.Analysis.SphereIsometry.UltraSphere +OAI.Analysis.SphereIsometry.UnitRepresentatives diff --git a/tasks/tingley-sphere-isometry/solution/reference.py b/tasks/tingley-sphere-isometry/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/tingley-sphere-isometry/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/tingley-sphere-isometry/solution/solve.sh b/tasks/tingley-sphere-isometry/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..24c05355f114241219055ac7f902eceddd087a4c --- /dev/null +++ b/tasks/tingley-sphere-isometry/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TingleySphereIsometry, i.e. module OAI.Analysis.SphereIsometry.Main and the +# 67 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.SphereIsometry.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TingleySphereIsometry" diff --git a/tasks/tingley-sphere-isometry/task.toml b/tasks/tingley-sphere-isometry/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..588c8526a54726696c48c7c2c163bff6e6f0f546 --- /dev/null +++ b/tasks/tingley-sphere-isometry/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/tingley-sphere-isometry" +version = "1.0.0" +description = "Prove TingleySphereIsometry (openai/math family 322: Tingley's sphere-isometry problem) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "functional-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TingleySphereIsometry.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TingleySphereIsometry" +family = "322" +family_title = "Tingley's sphere-isometry problem" +subject = "Functional analysis" +theorems = ["OAI.Tingley.tingley_sphere_isometry_full"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.SphereIsometry.Main" +reference_modules = 67 +reference_lean_bytes = 382424 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 129 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12044 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/tingley-sphere-isometry/tests/Challenge.lean b/tasks/tingley-sphere-isometry/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e8d14b099f558d62cffb37f1e6908d8661873ac2 --- /dev/null +++ b/tasks/tingley-sphere-isometry/tests/Challenge.lean @@ -0,0 +1,41 @@ +import Mathlib.Analysis.Normed.Module.RCLike.Basic +import Mathlib.Topology.MetricSpace.Isometry + +namespace OAI + +noncomputable section + +namespace Tingley + +universe u v + +abbrev UnitSphere (X : Type u) [NormedAddCommGroup X] := {x : X // ‖x‖ = 1} + +variable {X : Type u} {Y : Type v} +variable [NormedAddCommGroup X] [NormedSpace ℝ X] +variable [NormedAddCommGroup Y] [NormedSpace ℝ Y] + +def normalize (x : X) (hx : x ≠ 0) : UnitSphere X := + ⟨‖x‖⁻¹ • x, norm_smul_inv_norm hx⟩ + +/-- Radial formula, surjectivity, and uniqueness among all real-linear extensions. -/ +theorem tingley_sphere_isometry_full + {X : Type u} {Y : Type v} + [NormedAddCommGroup X] [NormedSpace ℝ X] [CompleteSpace X] + [NormedAddCommGroup Y] [NormedSpace ℝ Y] [CompleteSpace Y] + [Nontrivial X] [Nontrivial Y] + (f : UnitSphere X → UnitSphere Y) (hf : Isometry f) (hs : Function.Surjective f) : + ∃ T : X ≃ₗᵢ[ℝ] Y, + (∀ u : UnitSphere X, T (u : X) = (f u : Y)) ∧ + T 0 = 0 ∧ + (∀ x : X, ∀ hx : x ≠ 0, T x = ‖x‖ • (f (normalize x hx) : Y)) ∧ + Function.Surjective T ∧ + (∀ L : X →ₗ[ℝ] Y, (∀ u : UnitSphere X, L (u : X) = (f u : Y)) → + L = T.toLinearEquiv.toLinearMap) := by + sorry + +end Tingley + +end + +end OAI diff --git a/tasks/tingley-sphere-isometry/tests/grade.py b/tasks/tingley-sphere-isometry/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/tingley-sphere-isometry/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/tingley-sphere-isometry/tests/task.json b/tasks/tingley-sphere-isometry/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..4d464eec8cac56b0b62ebbcb75b38da33dfd7b38 --- /dev/null +++ b/tasks/tingley-sphere-isometry/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TingleySphereIsometry", + "comparator": { + "theorem_names": [ + "OAI.Tingley.tingley_sphere_isometry_full" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11144 +} \ No newline at end of file diff --git a/tasks/tingley-sphere-isometry/tests/test.sh b/tasks/tingley-sphere-isometry/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/tingley-sphere-isometry/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/torsion-free-hyperbolic/environment/Dockerfile b/tasks/torsion-free-hyperbolic/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/torsion-free-hyperbolic/environment/fetch_mathlib.sh b/tasks/torsion-free-hyperbolic/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/torsion-free-hyperbolic/environment/lake-manifest.json b/tasks/torsion-free-hyperbolic/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/torsion-free-hyperbolic/environment/lakefile.lean b/tasks/torsion-free-hyperbolic/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/torsion-free-hyperbolic/environment/lean_setup.sh b/tasks/torsion-free-hyperbolic/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/torsion-free-hyperbolic/environment/pack_submission.py b/tasks/torsion-free-hyperbolic/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/torsion-free-hyperbolic/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/torsion-free-hyperbolic/instruction.md b/tasks/torsion-free-hyperbolic/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c899e9beb789ba4c81dc0f753e2b6150e50ea155 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/instruction.md @@ -0,0 +1,94 @@ +# openai/math challenge `TorsionFreeHyperbolic` (family 252) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 252 of the release, *A non-residually-finite torsion-free hyperbolic group* +(Group theory). The family as a whole: Constructs a torsion-free word-hyperbolic group that is not residually finite, answering the residual-finiteness question negatively. One fixed nonidentity element is killed by every finite-dimensional linear representation over every commutative field, so the group is not linear over any such field. + +The challenge is `TorsionFreeHyperbolic`, also at `/opt/openai-math/challenges/TorsionFreeHyperbolic.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Release075 + +universe u v + +/-- No nonidentity element has finite order. This does not assert unique roots. -/ +def TorsionFree (G : Type u) [Group G] : Prop := + ∀ (g : G) (n : ℕ), 0 < n → g ^ n = 1 → g = 1 + +/-- A shortest edge path in the unit-edge graph. -/ +def Geodesic {V : Type u} (X : SimpleGraph V) {x y : V} (p : X.Walk x y) : Prop := + p.length = X.dist x y + +/-- Each vertex of `p` is within `δ` of a vertex of `q` or `r`. -/ +def SideThin {V : Type u} (X : SimpleGraph V) (δ : ℕ) {x y z : V} + (p : X.Walk x y) (q : X.Walk y z) (r : X.Walk z x) : Prop := + ∀ a ∈ p.support, ∃ b, (b ∈ q.support ∨ b ∈ r.support) ∧ X.dist a b ≤ δ + +/-- A finitely generated group with a unit-edge Cayley graph whose geodesic triangles +are uniformly thin. Connectedness of this Cayley graph asserts that `S` generates. -/ +def WordHyperbolic (G : Type u) [Group G] : Prop := + ∃ S : Set G, S.Finite ∧ (SimpleGraph.mulCayley S).Connected ∧ + ∃ δ : ℕ, ∀ (x y z : G) + (p : (SimpleGraph.mulCayley S).Walk x y) + (q : (SimpleGraph.mulCayley S).Walk y z) + (r : (SimpleGraph.mulCayley S).Walk z x), + Geodesic (SimpleGraph.mulCayley S) p → + Geodesic (SimpleGraph.mulCayley S) q → + Geodesic (SimpleGraph.mulCayley S) r → + SideThin (SimpleGraph.mulCayley S) δ p q r ∧ + SideThin (SimpleGraph.mulCayley S) δ q r p ∧ + SideThin (SimpleGraph.mulCayley S) δ r p q + +theorem main : ∃ (G : Type) (_ : Group G), + TorsionFree G ∧ WordHyperbolic G ∧ ¬ Group.ResiduallyFinite G := by + sorry + +end Release075 + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TorsionFreeHyperbolic.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Release075.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/torsion-free-hyperbolic/solution/closure.txt b/tasks/torsion-free-hyperbolic/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..803d8ec44aca3d44fdb85c101751a32c518b19a5 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/solution/closure.txt @@ -0,0 +1,29 @@ +OAI.GroupTheory.Hyperbolic.BasedWords +OAI.GroupTheory.Hyperbolic.CayleyMetric +OAI.GroupTheory.Hyperbolic.CayleyPaths +OAI.GroupTheory.Hyperbolic.Chains +OAI.GroupTheory.Hyperbolic.CyclicAction +OAI.GroupTheory.Hyperbolic.Dipoles +OAI.GroupTheory.Hyperbolic.DiscreteMetric +OAI.GroupTheory.Hyperbolic.FullChains +OAI.GroupTheory.Hyperbolic.FullFilling +OAI.GroupTheory.Hyperbolic.FullGluing +OAI.GroupTheory.Hyperbolic.Hyperbolicity +OAI.GroupTheory.Hyperbolic.Incidence +OAI.GroupTheory.Hyperbolic.LiftedFilling +OAI.GroupTheory.Hyperbolic.Links +OAI.GroupTheory.Hyperbolic.Main +OAI.GroupTheory.Hyperbolic.MatrixRank +OAI.GroupTheory.Hyperbolic.Model +OAI.GroupTheory.Hyperbolic.PermutationCycles +OAI.GroupTheory.Hyperbolic.Planarity +OAI.GroupTheory.Hyperbolic.Presentation +OAI.GroupTheory.Hyperbolic.RePairing +OAI.GroupTheory.Hyperbolic.Rectangles +OAI.GroupTheory.Hyperbolic.Ribbons +OAI.GroupTheory.Hyperbolic.Spheres +OAI.GroupTheory.Hyperbolic.ThinTriangles +OAI.GroupTheory.Hyperbolic.Torsion +OAI.GroupTheory.Hyperbolic.TriangleFilling +OAI.GroupTheory.Hyperbolic.WordPaths +OAI.GroupTheory.Hyperbolic.Words diff --git a/tasks/torsion-free-hyperbolic/solution/reference.py b/tasks/torsion-free-hyperbolic/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/torsion-free-hyperbolic/solution/solve.sh b/tasks/torsion-free-hyperbolic/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..db57d2f0dc54fcf1318dbc88c9730a1a39d05227 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TorsionFreeHyperbolic, i.e. module OAI.GroupTheory.Hyperbolic.Main and the +# 29 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.Hyperbolic.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TorsionFreeHyperbolic" diff --git a/tasks/torsion-free-hyperbolic/task.toml b/tasks/torsion-free-hyperbolic/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ed58e804004680a7f0f43789f3bdd3354273f303 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/torsion-free-hyperbolic" +version = "1.0.0" +description = "Prove TorsionFreeHyperbolic (openai/math family 252: A non-residually-finite torsion-free hyperbolic group) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TorsionFreeHyperbolic.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TorsionFreeHyperbolic" +family = "252" +family_title = "A non-residually-finite torsion-free hyperbolic group" +subject = "Group theory" +theorems = ["OAI.Release075.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.Hyperbolic.Main" +reference_modules = 29 +reference_lean_bytes = 482151 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 289 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12133 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/torsion-free-hyperbolic/tests/Challenge.lean b/tasks/torsion-free-hyperbolic/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..83f9be6b2243d87bdc338c6e4e021a913704af90 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/tests/Challenge.lean @@ -0,0 +1,43 @@ +import Mathlib + +namespace OAI + +namespace Release075 + +universe u v + +/-- No nonidentity element has finite order. This does not assert unique roots. -/ +def TorsionFree (G : Type u) [Group G] : Prop := + ∀ (g : G) (n : ℕ), 0 < n → g ^ n = 1 → g = 1 + +/-- A shortest edge path in the unit-edge graph. -/ +def Geodesic {V : Type u} (X : SimpleGraph V) {x y : V} (p : X.Walk x y) : Prop := + p.length = X.dist x y + +/-- Each vertex of `p` is within `δ` of a vertex of `q` or `r`. -/ +def SideThin {V : Type u} (X : SimpleGraph V) (δ : ℕ) {x y z : V} + (p : X.Walk x y) (q : X.Walk y z) (r : X.Walk z x) : Prop := + ∀ a ∈ p.support, ∃ b, (b ∈ q.support ∨ b ∈ r.support) ∧ X.dist a b ≤ δ + +/-- A finitely generated group with a unit-edge Cayley graph whose geodesic triangles +are uniformly thin. Connectedness of this Cayley graph asserts that `S` generates. -/ +def WordHyperbolic (G : Type u) [Group G] : Prop := + ∃ S : Set G, S.Finite ∧ (SimpleGraph.mulCayley S).Connected ∧ + ∃ δ : ℕ, ∀ (x y z : G) + (p : (SimpleGraph.mulCayley S).Walk x y) + (q : (SimpleGraph.mulCayley S).Walk y z) + (r : (SimpleGraph.mulCayley S).Walk z x), + Geodesic (SimpleGraph.mulCayley S) p → + Geodesic (SimpleGraph.mulCayley S) q → + Geodesic (SimpleGraph.mulCayley S) r → + SideThin (SimpleGraph.mulCayley S) δ p q r ∧ + SideThin (SimpleGraph.mulCayley S) δ q r p ∧ + SideThin (SimpleGraph.mulCayley S) δ r p q + +theorem main : ∃ (G : Type) (_ : Group G), + TorsionFree G ∧ WordHyperbolic G ∧ ¬ Group.ResiduallyFinite G := by + sorry + +end Release075 + +end OAI diff --git a/tasks/torsion-free-hyperbolic/tests/grade.py b/tasks/torsion-free-hyperbolic/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/torsion-free-hyperbolic/tests/task.json b/tasks/torsion-free-hyperbolic/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..616a654002a98cd64848f264f59a7676a0c625f8 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TorsionFreeHyperbolic", + "comparator": { + "theorem_names": [ + "OAI.Release075.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11233 +} \ No newline at end of file diff --git a/tasks/torsion-free-hyperbolic/tests/test.sh b/tasks/torsion-free-hyperbolic/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/torsion-free-hyperbolic/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/torsion-free-zero-divisors/environment/Dockerfile b/tasks/torsion-free-zero-divisors/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/torsion-free-zero-divisors/environment/fetch_mathlib.sh b/tasks/torsion-free-zero-divisors/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/torsion-free-zero-divisors/environment/lake-manifest.json b/tasks/torsion-free-zero-divisors/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/torsion-free-zero-divisors/environment/lakefile.lean b/tasks/torsion-free-zero-divisors/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/torsion-free-zero-divisors/environment/lean_setup.sh b/tasks/torsion-free-zero-divisors/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/torsion-free-zero-divisors/environment/pack_submission.py b/tasks/torsion-free-zero-divisors/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/torsion-free-zero-divisors/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/torsion-free-zero-divisors/instruction.md b/tasks/torsion-free-zero-divisors/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c4c98ce7f7218760f1a1e0f69a1a483c78e9b1 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/instruction.md @@ -0,0 +1,91 @@ +# openai/math challenge `TorsionFreeZeroDivisors` (family 196) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 196 of the release, *A counterexample to Kaplansky's zero-divisor conjecture* +(Algebra). The family as a whole: Constructs a finitely presented torsion-free group $G$ whose group algebra $\mathbb F_2[G]$ has nonzero zero divisors, disproving Kaplansky's zero-divisor conjecture. The group has a finite two-dimensional classifying space. + +The challenge is `TorsionFreeZeroDivisors`, also at `/opt/openai-math/challenges/TorsionFreeZeroDivisors.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TorsionFreeZeroDivisors + +/-- Ordinary group torsion-freeness, without requiring uniqueness of all roots. -/ +def TorsionFree (G : Type) [Group G] : Prop := + ∀ (g : G) (n : ℕ), 0 < n → g ^ n = 1 → g = 1 + +/-- A connected finite Hausdorff 2-dimensional CW K(G,1). -/ +def HasFiniteTwoDimensionalClassifyingSpace (G : Type) [Group G] : Prop := + ∃ (X : Type) (topX : TopologicalSpace X), + letI : TopologicalSpace X := topX + ∃ (_hausdorff : T2Space X) (_connected : PathConnectedSpace X) + (cw : Topology.CWComplex (Set.univ : Set X)), + letI : Topology.CWComplex (Set.univ : Set X) := cw + Topology.CWComplex.Finite (Set.univ : Set X) ∧ + (∀ n : ℕ, 2 < n → IsEmpty (Topology.CWComplex.cell (Set.univ : Set X) n)) ∧ + Nonempty (Topology.CWComplex.cell (Set.univ : Set X) 2) ∧ + ∃ (x : X), Nonempty (G ≃* FundamentalGroup X x) ∧ + ∃ (E : Type) (topE : TopologicalSpace E), + letI : TopologicalSpace E := topE + ContractibleSpace E ∧ + ∃ p : E → X, IsCoveringMap p ∧ Function.Surjective p + +/-- The entire main theorem, including its "Moreover" clause. -/ +def MainTheorem : Prop := + ∃ (G : Type) (inst : Group G), + letI : Group G := inst + Group.IsFinitelyPresented G ∧ TorsionFree G ∧ + HasFiniteTwoDimensionalClassifyingSpace G ∧ + ∃ α β : MonoidAlgebra (ZMod 2) G, α ≠ 0 ∧ β ≠ 0 ∧ α * β = 0 + +theorem main : MainTheorem := by + sorry + +end TorsionFreeZeroDivisors + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TorsionFreeZeroDivisors.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TorsionFreeZeroDivisors.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/torsion-free-zero-divisors/solution/closure.txt b/tasks/torsion-free-zero-divisors/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..19a70b2c4ff26eeb0303dac93dc9798291e05748 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/solution/closure.txt @@ -0,0 +1,123 @@ +OAI.Algebra.GroupRing.AbsorbCells +OAI.Algebra.GroupRing.AbsorbTracks +OAI.Algebra.GroupRing.AffineIntervals +OAI.Algebra.GroupRing.AlgebraicPictures +OAI.Algebra.GroupRing.Attachment +OAI.Algebra.GroupRing.AttachmentFurther +OAI.Algebra.GroupRing.AttachmentHEP +OAI.Algebra.GroupRing.BFSTree +OAI.Algebra.GroupRing.BalancedPieces +OAI.Algebra.GroupRing.BallCount +OAI.Algebra.GroupRing.Basic +OAI.Algebra.GroupRing.BlockGrid +OAI.Algebra.GroupRing.BlockPropagation +OAI.Algebra.GroupRing.BoundedSystem +OAI.Algebra.GroupRing.Cayley +OAI.Algebra.GroupRing.CayleyFurther +OAI.Algebra.GroupRing.CellHEP +OAI.Algebra.GroupRing.CellModule +OAI.Algebra.GroupRing.CellNorm +OAI.Algebra.GroupRing.Cellular +OAI.Algebra.GroupRing.CellularFurther +OAI.Algebra.GroupRing.CellularFurther2 +OAI.Algebra.GroupRing.ChainActiveStages +OAI.Algebra.GroupRing.ChainCoverage +OAI.Algebra.GroupRing.ChainUsage +OAI.Algebra.GroupRing.ChunkComparisons +OAI.Algebra.GroupRing.ClosedWords +OAI.Algebra.GroupRing.ClusterLocalization +OAI.Algebra.GroupRing.ComparisonCoding +OAI.Algebra.GroupRing.ConcreteGroup +OAI.Algebra.GroupRing.ConcreteModel +OAI.Algebra.GroupRing.ConcreteTorsion +OAI.Algebra.GroupRing.ConeArea +OAI.Algebra.GroupRing.ConeBoundaryPaths +OAI.Algebra.GroupRing.ConeCells +OAI.Algebra.GroupRing.ConeChains +OAI.Algebra.GroupRing.ConePicture +OAI.Algebra.GroupRing.ConeSigned +OAI.Algebra.GroupRing.ConeTorsion +OAI.Algebra.GroupRing.ConedMap +OAI.Algebra.GroupRing.ContiguousSplit +OAI.Algebra.GroupRing.CoreStripping +OAI.Algebra.GroupRing.CycleLists +OAI.Algebra.GroupRing.DegreeTwoSuppression +OAI.Algebra.GroupRing.DiskHomotopy +OAI.Algebra.GroupRing.DiskTracks +OAI.Algebra.GroupRing.EntropyStages +OAI.Algebra.GroupRing.ExpansionDiameter +OAI.Algebra.GroupRing.FiniteClusters +OAI.Algebra.GroupRing.FixedGraph +OAI.Algebra.GroupRing.FramedConjugators +OAI.Algebra.GroupRing.FramedLoopIdentities +OAI.Algebra.GroupRing.FramedSpherical +OAI.Algebra.GroupRing.FreeActionNorm +OAI.Algebra.GroupRing.FullPairing +OAI.Algebra.GroupRing.GeneralPosition +OAI.Algebra.GroupRing.GraphConeCW +OAI.Algebra.GroupRing.GraphConePresentation +OAI.Algebra.GroupRing.GraphLabels +OAI.Algebra.GroupRing.GraphQuotient +OAI.Algebra.GroupRing.GridUniform +OAI.Algebra.GroupRing.HomotopyFunctor +OAI.Algebra.GroupRing.HomotopyTracks +OAI.Algebra.GroupRing.IndexedCells +OAI.Algebra.GroupRing.IntervalSelfLinks +OAI.Algebra.GroupRing.Iso +OAI.Algebra.GroupRing.LinkComponents +OAI.Algebra.GroupRing.ListPassages +OAI.Algebra.GroupRing.LoopSphere +OAI.Algebra.GroupRing.LoopTracks +OAI.Algebra.GroupRing.LoopTranspose +OAI.Algebra.GroupRing.Main +OAI.Algebra.GroupRing.MapEuler +OAI.Algebra.GroupRing.MapRestrict +OAI.Algebra.GroupRing.MatchedLabels +OAI.Algebra.GroupRing.MatchingGraphs +OAI.Algebra.GroupRing.Milnor +OAI.Algebra.GroupRing.MultiplicityBound +OAI.Algebra.GroupRing.PartialLift +OAI.Algebra.GroupRing.PartitionEntropy +OAI.Algebra.GroupRing.Path +OAI.Algebra.GroupRing.PathCharges +OAI.Algebra.GroupRing.PathIncidences +OAI.Algebra.GroupRing.PatternCount +OAI.Algebra.GroupRing.PatternTotalCoding +OAI.Algebra.GroupRing.PatternUniform +OAI.Algebra.GroupRing.PictureChains +OAI.Algebra.GroupRing.PlanarMap +OAI.Algebra.GroupRing.PortSubdivision +OAI.Algebra.GroupRing.RawDecomposition +OAI.Algebra.GroupRing.RealizationTransport +OAI.Algebra.GroupRing.RelationArea +OAI.Algebra.GroupRing.RelationSplit +OAI.Algebra.GroupRing.RelationTorsion +OAI.Algebra.GroupRing.SeparatorLevels +OAI.Algebra.GroupRing.ShortClosure +OAI.Algebra.GroupRing.SidePins +OAI.Algebra.GroupRing.SimplexTopology +OAI.Algebra.GroupRing.Simplicial +OAI.Algebra.GroupRing.SphereTopology +OAI.Algebra.GroupRing.SplitModel +OAI.Algebra.GroupRing.StageBlocks +OAI.Algebra.GroupRing.StageEntropy +OAI.Algebra.GroupRing.StageExpectation +OAI.Algebra.GroupRing.StageRealization +OAI.Algebra.GroupRing.SupportedImage +OAI.Algebra.GroupRing.TreeCentroid +OAI.Algebra.GroupRing.TwoSideFullStage +OAI.Algebra.GroupRing.TypeWeights +OAI.Algebra.GroupRing.TypedComponent +OAI.Algebra.GroupRing.TypedDiameter +OAI.Algebra.GroupRing.TypedGraphs +OAI.Algebra.GroupRing.VertexCollapse +OAI.Algebra.GroupRing.WeightedCycles +OAI.Algebra.GroupRing.WeightedGirth +OAI.Algebra.GroupRing.WeightedPortMoore +OAI.Algebra.GroupRing.WordBlocks +OAI.Algebra.GroupRing.WordBlocksFurther +OAI.Algebra.GroupRing.WordCursor +OAI.Algebra.GroupRing.WordEstimate +OAI.Algebra.GroupRing.WordFrames +OAI.Algebra.GroupRing.WordLiftSurgery +OAI.Algebra.GroupRing.WordResponse diff --git a/tasks/torsion-free-zero-divisors/solution/reference.py b/tasks/torsion-free-zero-divisors/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/torsion-free-zero-divisors/solution/solve.sh b/tasks/torsion-free-zero-divisors/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..dc0d23ad38fcdd28b43a147736de9beb75f38265 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TorsionFreeZeroDivisors, i.e. module OAI.Algebra.GroupRing.Main and the +# 123 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Algebra.GroupRing.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TorsionFreeZeroDivisors" diff --git a/tasks/torsion-free-zero-divisors/task.toml b/tasks/torsion-free-zero-divisors/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..4922f2154518ce9770dd858f81eae62309b78618 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/torsion-free-zero-divisors" +version = "1.0.0" +description = "Prove TorsionFreeZeroDivisors (openai/math family 196: A counterexample to Kaplansky's zero-divisor conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "algebra"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TorsionFreeZeroDivisors.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TorsionFreeZeroDivisors" +family = "196" +family_title = "A counterexample to Kaplansky's zero-divisor conjecture" +subject = "Algebra" +theorems = ["OAI.TorsionFreeZeroDivisors.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Algebra.GroupRing.Main" +reference_modules = 123 +reference_lean_bytes = 2064427 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 805 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13557 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/torsion-free-zero-divisors/tests/Challenge.lean b/tasks/torsion-free-zero-divisors/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..2dbb208512c5080fa9129b4aff5a2e5050755fc4 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/tests/Challenge.lean @@ -0,0 +1,40 @@ +import Mathlib + +namespace OAI + +namespace TorsionFreeZeroDivisors + +/-- Ordinary group torsion-freeness, without requiring uniqueness of all roots. -/ +def TorsionFree (G : Type) [Group G] : Prop := + ∀ (g : G) (n : ℕ), 0 < n → g ^ n = 1 → g = 1 + +/-- A connected finite Hausdorff 2-dimensional CW K(G,1). -/ +def HasFiniteTwoDimensionalClassifyingSpace (G : Type) [Group G] : Prop := + ∃ (X : Type) (topX : TopologicalSpace X), + letI : TopologicalSpace X := topX + ∃ (_hausdorff : T2Space X) (_connected : PathConnectedSpace X) + (cw : Topology.CWComplex (Set.univ : Set X)), + letI : Topology.CWComplex (Set.univ : Set X) := cw + Topology.CWComplex.Finite (Set.univ : Set X) ∧ + (∀ n : ℕ, 2 < n → IsEmpty (Topology.CWComplex.cell (Set.univ : Set X) n)) ∧ + Nonempty (Topology.CWComplex.cell (Set.univ : Set X) 2) ∧ + ∃ (x : X), Nonempty (G ≃* FundamentalGroup X x) ∧ + ∃ (E : Type) (topE : TopologicalSpace E), + letI : TopologicalSpace E := topE + ContractibleSpace E ∧ + ∃ p : E → X, IsCoveringMap p ∧ Function.Surjective p + +/-- The entire main theorem, including its "Moreover" clause. -/ +def MainTheorem : Prop := + ∃ (G : Type) (inst : Group G), + letI : Group G := inst + Group.IsFinitelyPresented G ∧ TorsionFree G ∧ + HasFiniteTwoDimensionalClassifyingSpace G ∧ + ∃ α β : MonoidAlgebra (ZMod 2) G, α ≠ 0 ∧ β ≠ 0 ∧ α * β = 0 + +theorem main : MainTheorem := by + sorry + +end TorsionFreeZeroDivisors + +end OAI diff --git a/tasks/torsion-free-zero-divisors/tests/grade.py b/tasks/torsion-free-zero-divisors/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/torsion-free-zero-divisors/tests/task.json b/tasks/torsion-free-zero-divisors/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..af243a541a6c1a7d9750113877355830c41daaf5 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TorsionFreeZeroDivisors", + "comparator": { + "theorem_names": [ + "OAI.TorsionFreeZeroDivisors.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12657 +} \ No newline at end of file diff --git a/tasks/torsion-free-zero-divisors/tests/test.sh b/tasks/torsion-free-zero-divisors/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/torsion-free-zero-divisors/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/trace-reconstruction/environment/Dockerfile b/tasks/trace-reconstruction/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/trace-reconstruction/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/trace-reconstruction/environment/fetch_mathlib.sh b/tasks/trace-reconstruction/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/trace-reconstruction/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/trace-reconstruction/environment/lake-manifest.json b/tasks/trace-reconstruction/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/trace-reconstruction/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/trace-reconstruction/environment/lakefile.lean b/tasks/trace-reconstruction/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/trace-reconstruction/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/trace-reconstruction/environment/lean_setup.sh b/tasks/trace-reconstruction/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/trace-reconstruction/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/trace-reconstruction/environment/pack_submission.py b/tasks/trace-reconstruction/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/trace-reconstruction/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/trace-reconstruction/instruction.md b/tasks/trace-reconstruction/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..53cc09379100979426d4d279598d30c5f64c9d9b --- /dev/null +++ b/tasks/trace-reconstruction/instruction.md @@ -0,0 +1,142 @@ +# openai/math challenge `TraceReconstruction` (family 122) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 122 of the release, *Superpolynomial lower bounds and quasipolynomial reconstruction from deletion traces* +(Theoretical computer science). The family as a whole: At every fixed deletion probability in $(0,1)$, reconstructing an arbitrary length-$n$ binary string requires $n^{\Omega(\log\log n)}$ independent traces, ruling out polynomial-sample reconstruction. A uniform decoder achieves quasipolynomial sample and running-time bounds for known fixed rational retention probabilities. When the deletion probability is at most $n^{-\varepsilon}$ for fixed $\varepsilon>0$, both bounds become polynomial in the input and parameter encoding. + +The challenge is `TraceReconstruction`, also at `/opt/openai-math/challenges/TraceReconstruction.lean`: + +```lean +import Mathlib + +namespace OAI + +open scoped ENNReal +noncomputable section + +namespace TraceReconstruction + +abbrev Word (n : ℕ) := Fin n → Bool +abbrev Mask (n : ℕ) := Fin n → Bool +abbrev Trace := List Bool + +/-- `true` retains the bit. The observer gets only the resulting list. -/ +def traceOfMask {n : ℕ} (x : Word n) (a : Mask n) : Trace := + ((List.finRange n).filter fun i => a i).map x + +/-- The deletion-mask probability, with deletion probability `q`. -/ +def maskWeight {n : ℕ} (q : ℝ) (a : Mask n) : ℝ := + ∏ i, if a i then 1 - q else q + +/-- Law of a single complete trace. -/ +def traceMass {n : ℕ} (q : ℝ) (x : Word n) (w : Trace) : ℝ := + ∑ a : Mask n, if traceOfMask x a = w then maskWeight q a else 0 + +/-- All possible complete outputs from length-n inputs, with lengths included. -/ +def traceSpace (n : ℕ) : Finset Trace := + Finset.univ.biUnion fun k : Fin (n + 1) => + Finset.univ.image fun x : Word k.val => List.ofFn x + +/-- 1/2 sum of absolute differences, on the full finite output space. -/ +def traceTV {n : ℕ} (q : ℝ) (x y : Word n) : ℝ := + (1 / 2 : ℝ) * ∑ w ∈ traceSpace n, |traceMass q x w - traceMass q y w| + +/-- The estimator may depend arbitrarily on n, q and every complete sample. + Its value is its conditional probability of reporting the given input. -/ +def IsEstimator {n m : ℕ} (A : (Fin m → Trace) → Word n → ℝ) : Prop := + (∀ z x, 0 ≤ A z x) ∧ (∀ z, ∑ x : Word n, A z x = 1) + +/-- Independent masks generate independent complete traces; no retained + positions, boundaries or other latent variables are revealed to A. -/ +def reconstructionSuccess {n m : ℕ} (q : ℝ) + (A : (Fin m → Trace) → Word n → ℝ) (x : Word n) : ℝ := + ∑ a : Fin m → Mask n, + (∏ j, maskWeight q (a j)) * A (fun j => traceOfMask x (a j)) x + +def SufficientBudget (n : ℕ) (q s : ℝ) (m : ℕ) : Prop := + ∃ A : (Fin m → Trace) → Word n → ℝ, + IsEstimator A ∧ ∀ x, s ≤ reconstructionSuccess q A x + +/-- Natural fixed sample budget; infimum of the empty set is infinity. -/ +noncomputable def sampleComplexity (n : ℕ) (q s : ℝ) : ℝ≥0∞ := + sInf {t | ∃ m : ℕ, SufficientBudget n q s m ∧ t = (m : ℝ≥0∞)} + +/-- The real infimum is a minimum for n>0 (a nonempty finite set). -/ +noncomputable def minTraceTV (n : ℕ) (q : ℝ) : ℝ := + sInf {t | ∃ x y : Word n, x ≠ y ∧ t = traceTV q x y} + +open Filter +open scoped Topology Classical ENNReal + +theorem quantitative_sample_lower_bound + (s c : ℝ) (hs : s ∈ Set.Ioc 0 1) + (hc : c ∈ Set.Ioo 0 (1 / (4 * Real.log 2))) + (n : ℕ → ℕ) (q : ℕ → ℝ) + (hn : Tendsto n atTop atTop) + (hq : ∀ k, q k ∈ Set.Ioo 0 1) + (hscale : Tendsto (fun k => (q k) ^ 3 * Real.log (n k)) atTop atTop) : + ∀ᶠ k in atTop, + ENNReal.ofReal ((n k : ℝ) ^ (c * Real.log ((q k) ^ 3 * Real.log (n k)))) ≤ + sampleComplexity (n k) (q k) s := by + sorry + +theorem superpolynomial_one_trace + (q : ℝ) (hq : q ∈ Set.Ioo 0 1) (C : ℝ) (hC : 0 < C) : + Tendsto (fun n : ℕ => (n : ℝ) ^ C * minTraceTV n q) atTop (𝓝 0) := by + sorry + +theorem superpolynomial_sample_complexity + (q : ℝ) (hq : q ∈ Set.Ioo 0 1) (s : ℝ) (hs : s ∈ Set.Ioc 0 1) + (C : ℝ) (hC : 0 < C) : + Tendsto + (fun n : ℕ => sampleComplexity n q s / ENNReal.ofReal ((n : ℝ) ^ C)) + atTop (𝓝 ⊤) := by + sorry + +end TraceReconstruction + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TraceReconstruction.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.TraceReconstruction.quantitative_sample_lower_bound`, `OAI.TraceReconstruction.superpolynomial_one_trace`, `OAI.TraceReconstruction.superpolynomial_sample_complexity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/trace-reconstruction/solution/closure.txt b/tasks/trace-reconstruction/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..e5a043a9c68c3e6d34a21d7d7690cb5e0e8afff8 --- /dev/null +++ b/tasks/trace-reconstruction/solution/closure.txt @@ -0,0 +1,31 @@ +OAI.Probability.TraceReconstruction +OAI.Probability.TraceReconstruction.Amplification +OAI.Probability.TraceReconstruction.Anchors +OAI.Probability.TraceReconstruction.Binomial +OAI.Probability.TraceReconstruction.Differences +OAI.Probability.TraceReconstruction.Energy +OAI.Probability.TraceReconstruction.ErrorRates +OAI.Probability.TraceReconstruction.FiniteLaw +OAI.Probability.TraceReconstruction.Induction +OAI.Probability.TraceReconstruction.InitialDensity +OAI.Probability.TraceReconstruction.InitialMoments +OAI.Probability.TraceReconstruction.InitialOracle +OAI.Probability.TraceReconstruction.InitialOverlap +OAI.Probability.TraceReconstruction.InitialRates +OAI.Probability.TraceReconstruction.Kernels +OAI.Probability.TraceReconstruction.Layout +OAI.Probability.TraceReconstruction.LayoutRates +OAI.Probability.TraceReconstruction.LeafOracle +OAI.Probability.TraceReconstruction.Metadata +OAI.Probability.TraceReconstruction.Model +OAI.Probability.TraceReconstruction.Oracles +OAI.Probability.TraceReconstruction.Parity +OAI.Probability.TraceReconstruction.Patterns +OAI.Probability.TraceReconstruction.Propagation +OAI.Probability.TraceReconstruction.Ranks +OAI.Probability.TraceReconstruction.Restoration +OAI.Probability.TraceReconstruction.Scales +OAI.Probability.TraceReconstruction.Shapes +OAI.Probability.TraceReconstruction.Simulation +OAI.Probability.TraceReconstruction.SourceOracle +OAI.Probability.TraceReconstruction.Testing diff --git a/tasks/trace-reconstruction/solution/reference.py b/tasks/trace-reconstruction/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/trace-reconstruction/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/trace-reconstruction/solution/solve.sh b/tasks/trace-reconstruction/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fab62ab1ec9ad771f6107ec62a7c0617a1adfb4e --- /dev/null +++ b/tasks/trace-reconstruction/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TraceReconstruction, i.e. module OAI.Probability.TraceReconstruction and the +# 31 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.TraceReconstruction /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TraceReconstruction" diff --git a/tasks/trace-reconstruction/task.toml b/tasks/trace-reconstruction/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..9fccd287b5de82c7c8b069f129af160dfb0e2f8d --- /dev/null +++ b/tasks/trace-reconstruction/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/trace-reconstruction" +version = "1.0.0" +description = "Prove TraceReconstruction (openai/math family 122: Superpolynomial lower bounds and quasipolynomial reconstruction from deletion traces) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TraceReconstruction.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TraceReconstruction" +family = "122" +family_title = "Superpolynomial lower bounds and quasipolynomial reconstruction from deletion traces" +subject = "Theoretical computer science" +theorems = ["OAI.TraceReconstruction.quantitative_sample_lower_bound", "OAI.TraceReconstruction.superpolynomial_one_trace", "OAI.TraceReconstruction.superpolynomial_sample_complexity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.TraceReconstruction" +reference_modules = 31 +reference_lean_bytes = 1632943 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 415 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13169 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/trace-reconstruction/tests/Challenge.lean b/tasks/trace-reconstruction/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..10db783ba141d7754767bc00c211986979f0eecb --- /dev/null +++ b/tasks/trace-reconstruction/tests/Challenge.lean @@ -0,0 +1,91 @@ +import Mathlib + +namespace OAI + +open scoped ENNReal +noncomputable section + +namespace TraceReconstruction + +abbrev Word (n : ℕ) := Fin n → Bool +abbrev Mask (n : ℕ) := Fin n → Bool +abbrev Trace := List Bool + +/-- `true` retains the bit. The observer gets only the resulting list. -/ +def traceOfMask {n : ℕ} (x : Word n) (a : Mask n) : Trace := + ((List.finRange n).filter fun i => a i).map x + +/-- The deletion-mask probability, with deletion probability `q`. -/ +def maskWeight {n : ℕ} (q : ℝ) (a : Mask n) : ℝ := + ∏ i, if a i then 1 - q else q + +/-- Law of a single complete trace. -/ +def traceMass {n : ℕ} (q : ℝ) (x : Word n) (w : Trace) : ℝ := + ∑ a : Mask n, if traceOfMask x a = w then maskWeight q a else 0 + +/-- All possible complete outputs from length-n inputs, with lengths included. -/ +def traceSpace (n : ℕ) : Finset Trace := + Finset.univ.biUnion fun k : Fin (n + 1) => + Finset.univ.image fun x : Word k.val => List.ofFn x + +/-- 1/2 sum of absolute differences, on the full finite output space. -/ +def traceTV {n : ℕ} (q : ℝ) (x y : Word n) : ℝ := + (1 / 2 : ℝ) * ∑ w ∈ traceSpace n, |traceMass q x w - traceMass q y w| + +/-- The estimator may depend arbitrarily on n, q and every complete sample. + Its value is its conditional probability of reporting the given input. -/ +def IsEstimator {n m : ℕ} (A : (Fin m → Trace) → Word n → ℝ) : Prop := + (∀ z x, 0 ≤ A z x) ∧ (∀ z, ∑ x : Word n, A z x = 1) + +/-- Independent masks generate independent complete traces; no retained + positions, boundaries or other latent variables are revealed to A. -/ +def reconstructionSuccess {n m : ℕ} (q : ℝ) + (A : (Fin m → Trace) → Word n → ℝ) (x : Word n) : ℝ := + ∑ a : Fin m → Mask n, + (∏ j, maskWeight q (a j)) * A (fun j => traceOfMask x (a j)) x + +def SufficientBudget (n : ℕ) (q s : ℝ) (m : ℕ) : Prop := + ∃ A : (Fin m → Trace) → Word n → ℝ, + IsEstimator A ∧ ∀ x, s ≤ reconstructionSuccess q A x + +/-- Natural fixed sample budget; infimum of the empty set is infinity. -/ +noncomputable def sampleComplexity (n : ℕ) (q s : ℝ) : ℝ≥0∞ := + sInf {t | ∃ m : ℕ, SufficientBudget n q s m ∧ t = (m : ℝ≥0∞)} + +/-- The real infimum is a minimum for n>0 (a nonempty finite set). -/ +noncomputable def minTraceTV (n : ℕ) (q : ℝ) : ℝ := + sInf {t | ∃ x y : Word n, x ≠ y ∧ t = traceTV q x y} + +open Filter +open scoped Topology Classical ENNReal + +theorem quantitative_sample_lower_bound + (s c : ℝ) (hs : s ∈ Set.Ioc 0 1) + (hc : c ∈ Set.Ioo 0 (1 / (4 * Real.log 2))) + (n : ℕ → ℕ) (q : ℕ → ℝ) + (hn : Tendsto n atTop atTop) + (hq : ∀ k, q k ∈ Set.Ioo 0 1) + (hscale : Tendsto (fun k => (q k) ^ 3 * Real.log (n k)) atTop atTop) : + ∀ᶠ k in atTop, + ENNReal.ofReal ((n k : ℝ) ^ (c * Real.log ((q k) ^ 3 * Real.log (n k)))) ≤ + sampleComplexity (n k) (q k) s := by + sorry + +theorem superpolynomial_one_trace + (q : ℝ) (hq : q ∈ Set.Ioo 0 1) (C : ℝ) (hC : 0 < C) : + Tendsto (fun n : ℕ => (n : ℝ) ^ C * minTraceTV n q) atTop (𝓝 0) := by + sorry + +theorem superpolynomial_sample_complexity + (q : ℝ) (hq : q ∈ Set.Ioo 0 1) (s : ℝ) (hs : s ∈ Set.Ioc 0 1) + (C : ℝ) (hC : 0 < C) : + Tendsto + (fun n : ℕ => sampleComplexity n q s / ENNReal.ofReal ((n : ℝ) ^ C)) + atTop (𝓝 ⊤) := by + sorry + +end TraceReconstruction + +end + +end OAI diff --git a/tasks/trace-reconstruction/tests/grade.py b/tasks/trace-reconstruction/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/trace-reconstruction/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/trace-reconstruction/tests/task.json b/tasks/trace-reconstruction/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6f000f0e70c9072c7b39f674d5fb31d2125f784c --- /dev/null +++ b/tasks/trace-reconstruction/tests/task.json @@ -0,0 +1,17 @@ +{ + "challenge": "TraceReconstruction", + "comparator": { + "theorem_names": [ + "OAI.TraceReconstruction.quantitative_sample_lower_bound", + "OAI.TraceReconstruction.superpolynomial_one_trace", + "OAI.TraceReconstruction.superpolynomial_sample_complexity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12269 +} \ No newline at end of file diff --git a/tasks/trace-reconstruction/tests/test.sh b/tasks/trace-reconstruction/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/trace-reconstruction/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/tree-edit/environment/Dockerfile b/tasks/tree-edit/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/tree-edit/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/tree-edit/environment/fetch_mathlib.sh b/tasks/tree-edit/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/tree-edit/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/tree-edit/environment/lake-manifest.json b/tasks/tree-edit/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/tree-edit/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/tree-edit/environment/lakefile.lean b/tasks/tree-edit/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/tree-edit/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/tree-edit/environment/lean_setup.sh b/tasks/tree-edit/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/tree-edit/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/tree-edit/environment/pack_submission.py b/tasks/tree-edit/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/tree-edit/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/tree-edit/instruction.md b/tasks/tree-edit/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..f10855079b6b3ae185865b41928c1e480b1f5e15 --- /dev/null +++ b/tasks/tree-edit/instruction.md @@ -0,0 +1,102 @@ +# openai/math challenge `TreeEdit` (family 099) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 099 of the release, *The sharp distortion of edit distance into $\ell_1$* +(Convex and metric geometry). The family as a whole: Determines the least distortion of embedding edit distance on words of length at most $d$ into real $\ell_1$: it is $\exp(\Theta(\sqrt{\log d\,\log\log d}))$. Insertions, deletions and substitutions have unit cost. The constants are uniform over all finite alphabets with at least two symbols, even when the alphabet grows with $d$; binary words already force the lower bound. + +The challenge is `TreeEdit`, also at `/opt/openai-math/challenges/TreeEdit.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TreeEdit + +universe u + +/-- A single unit-cost insertion, deletion or substitution, at any position. -/ +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (p q : List α) (a : α) : EditStep (p ++ q) (p ++ a :: q) + | delete (p q : List α) (a : α) : EditStep (p ++ a :: q) (p ++ q) + | substitute (p q : List α) (a b : α) : EditStep (p ++ a :: q) (p ++ b :: q) + +/-- A script of precisely `n` edits. There is no restriction on its intermediate lengths. -/ +inductive EditScript {α : Type u} : List α → List α → ℕ → Prop + | nil (x : List α) : EditScript x x 0 + | cons {x y z : List α} {n : ℕ} : + EditStep x y → EditScript y z n → EditScript x z (n + 1) + +/-- Ordinary unit-cost edit distance. The set is nonempty (delete then insert). -/ +noncomputable def ed {α : Type u} (x y : List α) : ℕ := + sInf {n | EditScript x y n} + +/-- The full infinite-dimensional real ℓ₁ space. -/ +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 + +/-- Product of the two maximal pairwise distance ratios. -/ +noncomputable def distortion (W : Finset (List Bool)) (f : W → RealL1) : ℝ := + sSup {r : ℝ | ∃ x y : W, x ≠ y ∧ + r = dist (f x) (f y) / (ed x.val y.val : ℝ)} * + sSup {r : ℝ | ∃ x y : W, x ≠ y ∧ + r = (ed x.val y.val : ℝ) / dist (f x) (f y)} + +/-- Infimum over all injective ℓ₁ maps, used on finite sets with at least two points. -/ +noncomputable def c1 (W : Finset (List Bool)) : ℝ := + sInf {D : ℝ | ∃ f : W → RealL1, Function.Injective f ∧ distortion W f = D} + +/-- The binary main endpoint, for every sufficiently large cap (natural logarithms). -/ +def BinaryLowerBound : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∃ n : ℕ, n ≤ d ∧ ∃ W : Finset (List Bool), + 2 ≤ W.card ∧ (∀ w ∈ W, w.length = n) ∧ + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) ≤ c1 W + +theorem binary_torus : BinaryLowerBound := by + sorry + +end TreeEdit + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TreeEdit.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TreeEdit.binary_torus` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/tree-edit/solution/closure.txt b/tasks/tree-edit/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..54af467afef68776e156c059715421f8d40967a7 --- /dev/null +++ b/tasks/tree-edit/solution/closure.txt @@ -0,0 +1,22 @@ +OAI.Combinatorics.TreeEdit.Alignments +OAI.Combinatorics.TreeEdit.CapInversion +OAI.Combinatorics.TreeEdit.CircleFourier +OAI.Combinatorics.TreeEdit.CircleObstruction +OAI.Combinatorics.TreeEdit.CircleParameters +OAI.Combinatorics.TreeEdit.CircleSeparation +OAI.Combinatorics.TreeEdit.CircleTree +OAI.Combinatorics.TreeEdit.CycleCharging +OAI.Combinatorics.TreeEdit.CyclicWords +OAI.Combinatorics.TreeEdit.Delimiter +OAI.Combinatorics.TreeEdit.DistortionTransfer +OAI.Combinatorics.TreeEdit.EditMetric +OAI.Combinatorics.TreeEdit.FiniteFourier +OAI.Combinatorics.TreeEdit.FiniteProbability +OAI.Combinatorics.TreeEdit.Model +OAI.Combinatorics.TreeEdit.PrimeSupply +OAI.Combinatorics.TreeEdit.RandomCircle +OAI.Combinatorics.TreeEdit.SampledSpectrum +OAI.Combinatorics.TreeEdit.SegmentComparison +OAI.Combinatorics.TreeEdit.TorusLowerBound +OAI.Combinatorics.TreeEdit.TreeArithmetic +OAI.Combinatorics.TreeEdit.WordOperations diff --git a/tasks/tree-edit/solution/reference.py b/tasks/tree-edit/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/tree-edit/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/tree-edit/solution/solve.sh b/tasks/tree-edit/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1eb2a05b4ddb693d0b558245ad5f9e81965d4b7d --- /dev/null +++ b/tasks/tree-edit/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TreeEdit, i.e. module OAI.Combinatorics.TreeEdit.TorusLowerBound and the +# 22 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TreeEdit.TorusLowerBound /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TreeEdit" diff --git a/tasks/tree-edit/task.toml b/tasks/tree-edit/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c47375b63ef8546aa33f6e0f7bf177fb1e191f70 --- /dev/null +++ b/tasks/tree-edit/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/tree-edit" +version = "1.0.0" +description = "Prove TreeEdit (openai/math family 099: The sharp distortion of edit distance into $\\ell_1$) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TreeEdit.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TreeEdit" +family = "099" +family_title = "The sharp distortion of edit distance into $\\ell_1$" +subject = "Convex and metric geometry" +theorems = ["OAI.TreeEdit.binary_torus"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TreeEdit.TorusLowerBound" +reference_modules = 22 +reference_lean_bytes = 243012 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 202 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11918 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/tree-edit/tests/Challenge.lean b/tasks/tree-edit/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..e3abc7cc91aca049b7878a31c96037c6e2582ef1 --- /dev/null +++ b/tasks/tree-edit/tests/Challenge.lean @@ -0,0 +1,51 @@ +import Mathlib + +namespace OAI + +namespace TreeEdit + +universe u + +/-- A single unit-cost insertion, deletion or substitution, at any position. -/ +inductive EditStep {α : Type u} : List α → List α → Prop + | insert (p q : List α) (a : α) : EditStep (p ++ q) (p ++ a :: q) + | delete (p q : List α) (a : α) : EditStep (p ++ a :: q) (p ++ q) + | substitute (p q : List α) (a b : α) : EditStep (p ++ a :: q) (p ++ b :: q) + +/-- A script of precisely `n` edits. There is no restriction on its intermediate lengths. -/ +inductive EditScript {α : Type u} : List α → List α → ℕ → Prop + | nil (x : List α) : EditScript x x 0 + | cons {x y z : List α} {n : ℕ} : + EditStep x y → EditScript y z n → EditScript x z (n + 1) + +/-- Ordinary unit-cost edit distance. The set is nonempty (delete then insert). -/ +noncomputable def ed {α : Type u} (x y : List α) : ℕ := + sInf {n | EditScript x y n} + +/-- The full infinite-dimensional real ℓ₁ space. -/ +abbrev RealL1 := lp (fun _ : ℕ => ℝ) 1 + +/-- Product of the two maximal pairwise distance ratios. -/ +noncomputable def distortion (W : Finset (List Bool)) (f : W → RealL1) : ℝ := + sSup {r : ℝ | ∃ x y : W, x ≠ y ∧ + r = dist (f x) (f y) / (ed x.val y.val : ℝ)} * + sSup {r : ℝ | ∃ x y : W, x ≠ y ∧ + r = (ed x.val y.val : ℝ) / dist (f x) (f y)} + +/-- Infimum over all injective ℓ₁ maps, used on finite sets with at least two points. -/ +noncomputable def c1 (W : Finset (List Bool)) : ℝ := + sInf {D : ℝ | ∃ f : W → RealL1, Function.Injective f ∧ distortion W f = D} + +/-- The binary main endpoint, for every sufficiently large cap (natural logarithms). -/ +def BinaryLowerBound : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ d₀ : ℕ, ∀ d : ℕ, d₀ ≤ d → + ∃ n : ℕ, n ≤ d ∧ ∃ W : Finset (List Bool), + 2 ≤ W.card ∧ (∀ w ∈ W, w.length = n) ∧ + Real.exp (c * Real.sqrt (Real.log (d : ℝ) * Real.log (Real.log (d : ℝ)))) ≤ c1 W + +theorem binary_torus : BinaryLowerBound := by + sorry + +end TreeEdit + +end OAI diff --git a/tasks/tree-edit/tests/grade.py b/tasks/tree-edit/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/tree-edit/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/tree-edit/tests/task.json b/tasks/tree-edit/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..a753ef3c68cc2a56a306413ba3205ff4e479f5f1 --- /dev/null +++ b/tasks/tree-edit/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TreeEdit", + "comparator": { + "theorem_names": [ + "OAI.TreeEdit.binary_torus" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11018 +} \ No newline at end of file diff --git a/tasks/tree-edit/tests/test.sh b/tasks/tree-edit/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/tree-edit/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangle-face/environment/Dockerfile b/tasks/triangle-face/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangle-face/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangle-face/environment/fetch_mathlib.sh b/tasks/triangle-face/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangle-face/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangle-face/environment/lake-manifest.json b/tasks/triangle-face/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangle-face/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangle-face/environment/lakefile.lean b/tasks/triangle-face/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangle-face/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangle-face/environment/lean_setup.sh b/tasks/triangle-face/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangle-face/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangle-face/environment/pack_submission.py b/tasks/triangle-face/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangle-face/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangle-face/instruction.md b/tasks/triangle-face/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..deb933df878b56e55af424c5dc0be9796deedd7c --- /dev/null +++ b/tasks/triangle-face/instruction.md @@ -0,0 +1,241 @@ +# openai/math challenge `TriangleFace` (family 113) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 113 of the release, *Approximate counting and the perfect-matching entropy conjecture* +(Theoretical computer science). The family as a whole: Gives a fully polynomial randomized approximation scheme for counting perfect matchings in arbitrary finite simple graphs, with exact detection of zero counts. Also proves the perfect-matching entropy conjecture of Anari, Oveis Gharan, and Vinzant, bounding the maximum entropy of a matching law at every feasible edge-marginal vector in a loopless labelled multigraph, including boundary points. + +The challenge is `TriangleFace`, also at `/opt/openai-math/challenges/TriangleFace.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uIndex uι + +namespace MatchingEntropyBounds + +structure LooplessGraph (V : Type uV) (E : Type uE) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +instance incidentDecidable (G : LooplessGraph V E) (v : V) (e : E) : + Decidable (G.Incident v e) := inferInstanceAs (Decidable (G.left e = v ∨ G.right e = v)) + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +end LooplessGraph +end MatchingEntropyBounds +end + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def Crosses (G : LooplessGraph V E) (S : Finset V) (e : E) : Prop := + (G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S) + +instance crossesDecidable (G : LooplessGraph V E) (S : Finset V) (e : E) : + Decidable (G.Crosses S e) := inferInstanceAs (Decidable + ((G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S))) + +def cut (G : LooplessGraph V E) (S : Finset V) : Finset E := + Finset.univ.filter (G.Crosses S) + +def degree (G : LooplessGraph V E) (x : E → ℝ) (v : V) : ℝ := + ∑ e, if G.Incident v e then x e else 0 + +def cutMass (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : ℝ := + ∑ e ∈ G.cut S, x e + +end MatchingEntropyBounds.LooplessGraph +end + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +section TriangleExpansion +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def triangleTip (v : V) (i : Fin 3) : V ⊕ Fin 2 := ![Sum.inl v, Sum.inr 0, Sum.inr 1] i + +def triangleCollapse (v : V) : V ⊕ Fin 2 → V := Sum.elim id (fun _ => v) + +def reattach (v : V) (i : Fin 3) (w : V) : V ⊕ Fin 2 := + if w = v then triangleTip v i else Sum.inl w + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem collapse_reattach (v : V) (i : Fin 3) (w : V) : + triangleCollapse v (reattach v i w) = w := by + by_cases h : w = v + · subst w + fin_cases i <;> simp [reattach,triangleTip,triangleCollapse] + · simp [reattach,h,triangleCollapse] + +def triangleExpansion (G : LooplessGraph V E) (c : E → Fin 3) (v : V) : + LooplessGraph (V ⊕ Fin 2) (E ⊕ Fin 3) where + left := Sum.elim (fun e => reattach v (c e) (G.left e)) (fun i => triangleTip v (i + 1)) + right := Sum.elim (fun e => reattach v (c e) (G.right e)) (fun i => triangleTip v (i + 2)) + loopless := by + intro e h + rcases e with e | i + · have hh := congrArg (triangleCollapse v) h + exact G.loopless e ((collapse_reattach v (c e) (G.left e)).symm.trans + (hh.trans (collapse_reattach v (c e) (G.right e)))) + · fin_cases i <;> simp [triangleTip] at h + +def triangleVertices (v : V) : Finset (V ⊕ Fin 2) := Finset.univ.image (triangleTip v) + +end TriangleExpansion +end MatchingEntropyBounds.Refined +end + +namespace CanonicalFace198 + +variable {A B : Type*} [AddCommGroup A] [Module ℝ A] + [AddCommGroup B] [Module ℝ B] + +def facesThrough (P : Set A) (x : A) : Set (Set A) := + {F | Convex ℝ F ∧ IsExtreme ℝ P F ∧ x ∈ F} + +def minFace (P : Set A) (x : A) : Set A := ⋂₀ facesThrough P x + +end CanonicalFace198 + +noncomputable section +open scoped BigOperators +open MatchingEntropyBounds MatchingEntropyBounds.Refined +namespace TriangleFace198 +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def LocalLabels (G : LooplessGraph V E) (v : V) (c : E → Fin 3) : Prop := + ∀ i, ∃! e, G.Incident v e ∧ c e = i + +def localEdge (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (hc : LocalLabels G v c) (i : Fin 3) : E := Classical.choose (hc i) + +def localExtension (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (hc : LocalLabels G v c) : (E → ℝ) →ₗ[ℝ] (E ⊕ Fin 3 → ℝ) where + toFun x := Sum.elim x (fun i => x (localEdge G c v hc i)) + map_add' x y := by ext e; cases e <;> rfl + map_smul' a x := by ext e; cases e <;> rfl + +def oldRestriction : (E ⊕ Fin 3 → ℝ) →ₗ[ℝ] (E → ℝ) where + toFun y e := y (Sum.inl e) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +end TriangleFace198 + +end + +noncomputable section +open scoped BigOperators +open MatchingEntropyBounds MatchingEntropyBounds.Refined +namespace TriangleFace198 +universe uV uE +variable {V : Type uV} {E : Type uE} [instFintypeV : Fintype V] [Fintype E] [DecidableEq V] [instDecidableEqE : DecidableEq E] + +theorem triangle_expansion_face {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (v : V) + (hdeg : Fintype.card {e : E // G.Incident v e} = 3) + (_hmatching : Nonempty G.Matching) : + ∃ (c : E → Fin 3) (hc : LocalLabels G v c), + let H := triangleExpansion G c v + let f := localExtension G c v hc + let Q := {y | y ∈ H.polytope ∧ H.cutMass y (triangleVertices v) = 1} + f '' G.polytope = Q ∧ + Convex ℝ Q ∧ IsExtreme ℝ H.polytope Q ∧ + (∀ x, oldRestriction (f x) = x) ∧ + (∀ y ∈ Q, f (oldRestriction y) = y) ∧ + (∀ x e, f x (Sum.inl e) = x e) ∧ + (∀ x i, f x (Sum.inr i) = x (localEdge G c v hc i)) ∧ + (∀ x, (∀ e, x e = (1/3 : ℝ)) → ∀ e, f x e = (1/3 : ℝ)) ∧ + (∀ x ∈ G.polytope, CanonicalFace198.minFace H.polytope (f x) = f '' CanonicalFace198.minFace G.polytope x) := by + sorry + +end TriangleFace198 +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangleFace.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TriangleFace198.triangle_expansion_face` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangle-face/solution/closure.txt b/tasks/triangle-face/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..5c7db694e677736eef57a5ae54cef9a221790450 --- /dev/null +++ b/tasks/triangle-face/solution/closure.txt @@ -0,0 +1,37 @@ +OAI.Combinatorics.MatchingEntropy.Basic +OAI.Combinatorics.MatchingEntropy.Calculus +OAI.Combinatorics.MatchingEntropy.Components +OAI.Combinatorics.MatchingEntropy.Continuity +OAI.Combinatorics.MatchingEntropy.Contraction +OAI.Combinatorics.MatchingEntropy.Counting +OAI.Combinatorics.MatchingEntropy.Coupling +OAI.Combinatorics.MatchingEntropy.Covariance +OAI.Combinatorics.MatchingEntropy.Degenerate +OAI.Combinatorics.MatchingEntropy.Duality +OAI.Combinatorics.MatchingEntropy.EdgeReduction +OAI.Combinatorics.MatchingEntropy.Entropy +OAI.Combinatorics.MatchingEntropy.EntropyUpper +OAI.Combinatorics.MatchingEntropy.Face +OAI.Combinatorics.MatchingEntropy.FractionalReduction +OAI.Combinatorics.MatchingEntropy.MatchingCovariance +OAI.Combinatorics.MatchingEntropy.MinimalFace +OAI.Combinatorics.MatchingEntropy.Model +OAI.Combinatorics.MatchingEntropy.OddCuts +OAI.Combinatorics.MatchingEntropy.Optimizer +OAI.Combinatorics.MatchingEntropy.Pointwise +OAI.Combinatorics.MatchingEntropy.Polyhedron +OAI.Combinatorics.MatchingEntropy.Polytope +OAI.Combinatorics.MatchingEntropy.RefinedVariation +OAI.Combinatorics.MatchingEntropy.SeparableBound +OAI.Combinatorics.MatchingEntropy.SeparableCovariance +OAI.Combinatorics.MatchingEntropy.SeparableVariation +OAI.Combinatorics.MatchingEntropy.SharpRank +OAI.Combinatorics.MatchingEntropy.Simplex +OAI.Combinatorics.MatchingEntropy.TriangleExpansion +OAI.Combinatorics.MatchingEntropy.WeightedSpectrum +OAI.Combinatorics.TriangleFace.AffineMaps +OAI.Combinatorics.TriangleFace.Faces +OAI.Combinatorics.TriangleFace.Labels +OAI.Combinatorics.TriangleFace.Main +OAI.Combinatorics.TriangleFace.MatchingImage +OAI.Combinatorics.TriangleFace.Model diff --git a/tasks/triangle-face/solution/reference.py b/tasks/triangle-face/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangle-face/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangle-face/solution/solve.sh b/tasks/triangle-face/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..1ce8790d4323641bc1b3e89417f9563b0c9dee2d --- /dev/null +++ b/tasks/triangle-face/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangleFace, i.e. module OAI.Combinatorics.TriangleFace.Main and the +# 37 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TriangleFace.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangleFace" diff --git a/tasks/triangle-face/task.toml b/tasks/triangle-face/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..efca88ea4d8a4abca51ce11e53a333f1ef45bfc4 --- /dev/null +++ b/tasks/triangle-face/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangle-face" +version = "1.0.0" +description = "Prove TriangleFace (openai/math family 113: Approximate counting and the perfect-matching entropy conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangleFace.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangleFace" +family = "113" +family_title = "Approximate counting and the perfect-matching entropy conjecture" +subject = "Theoretical computer science" +theorems = ["OAI.TriangleFace198.triangle_expansion_face"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TriangleFace.Main" +reference_modules = 37 +reference_lean_bytes = 326247 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 216 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11993 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangle-face/tests/Challenge.lean b/tasks/triangle-face/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9a07cf5ac47447761244710f10bfebe6790c2dc2 --- /dev/null +++ b/tasks/triangle-face/tests/Challenge.lean @@ -0,0 +1,190 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uIndex uι + +namespace MatchingEntropyBounds + +structure LooplessGraph (V : Type uV) (E : Type uE) where + left : E → V + right : E → V + loopless : ∀ e, left e ≠ right e + +variable {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +namespace LooplessGraph + +def Incident (G : LooplessGraph V E) (v : V) (e : E) : Prop := + G.left e = v ∨ G.right e = v + +instance incidentDecidable (G : LooplessGraph V E) (v : V) (e : E) : + Decidable (G.Incident v e) := inferInstanceAs (Decidable (G.left e = v ∨ G.right e = v)) + +def IsPerfectMatching (G : LooplessGraph V E) (M : Finset E) : Prop := + ∀ v, ∃! e, e ∈ M ∧ G.Incident v e + +abbrev Matching (G : LooplessGraph V E) := {M : Finset E // G.IsPerfectMatching M} + +instance matchingFintype (G : LooplessGraph V E) : Fintype G.Matching := + Fintype.ofFinite _ + +def indicator (G : LooplessGraph V E) (M : G.Matching) (e : E) : ℝ := + if e ∈ M.val then 1 else 0 + +def polytope (G : LooplessGraph V E) : Set (E → ℝ) := + convexHull ℝ (Set.range G.indicator) + +end LooplessGraph +end MatchingEntropyBounds +end + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.LooplessGraph + +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def Crosses (G : LooplessGraph V E) (S : Finset V) (e : E) : Prop := + (G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S) + +instance crossesDecidable (G : LooplessGraph V E) (S : Finset V) (e : E) : + Decidable (G.Crosses S e) := inferInstanceAs (Decidable + ((G.left e ∈ S ∧ G.right e ∉ S) ∨ (G.left e ∉ S ∧ G.right e ∈ S))) + +def cut (G : LooplessGraph V E) (S : Finset V) : Finset E := + Finset.univ.filter (G.Crosses S) + +def degree (G : LooplessGraph V E) (x : E → ℝ) (v : V) : ℝ := + ∑ e, if G.Incident v e then x e else 0 + +def cutMass (G : LooplessGraph V E) (x : E → ℝ) (S : Finset V) : ℝ := + ∑ e ∈ G.cut S, x e + +end MatchingEntropyBounds.LooplessGraph +end + +noncomputable section + +open scoped BigOperators Topology +open Filter + +universe uV uE uI uJ uA uB uC uW uF uD uι + +namespace MatchingEntropyBounds.Refined + +section TriangleExpansion +variable {V : Type uV} {E : Type uE} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def triangleTip (v : V) (i : Fin 3) : V ⊕ Fin 2 := ![Sum.inl v, Sum.inr 0, Sum.inr 1] i + +def triangleCollapse (v : V) : V ⊕ Fin 2 → V := Sum.elim id (fun _ => v) + +def reattach (v : V) (i : Fin 3) (w : V) : V ⊕ Fin 2 := + if w = v then triangleTip v i else Sum.inl w + +omit [Fintype V] [Fintype E] [DecidableEq E] in +theorem collapse_reattach (v : V) (i : Fin 3) (w : V) : + triangleCollapse v (reattach v i w) = w := by + by_cases h : w = v + · subst w + fin_cases i <;> simp [reattach,triangleTip,triangleCollapse] + · simp [reattach,h,triangleCollapse] + +def triangleExpansion (G : LooplessGraph V E) (c : E → Fin 3) (v : V) : + LooplessGraph (V ⊕ Fin 2) (E ⊕ Fin 3) where + left := Sum.elim (fun e => reattach v (c e) (G.left e)) (fun i => triangleTip v (i + 1)) + right := Sum.elim (fun e => reattach v (c e) (G.right e)) (fun i => triangleTip v (i + 2)) + loopless := by + intro e h + rcases e with e | i + · have hh := congrArg (triangleCollapse v) h + exact G.loopless e ((collapse_reattach v (c e) (G.left e)).symm.trans + (hh.trans (collapse_reattach v (c e) (G.right e)))) + · fin_cases i <;> simp [triangleTip] at h + +def triangleVertices (v : V) : Finset (V ⊕ Fin 2) := Finset.univ.image (triangleTip v) + +end TriangleExpansion +end MatchingEntropyBounds.Refined +end + +namespace CanonicalFace198 + +variable {A B : Type*} [AddCommGroup A] [Module ℝ A] + [AddCommGroup B] [Module ℝ B] + +def facesThrough (P : Set A) (x : A) : Set (Set A) := + {F | Convex ℝ F ∧ IsExtreme ℝ P F ∧ x ∈ F} + +def minFace (P : Set A) (x : A) : Set A := ⋂₀ facesThrough P x + +end CanonicalFace198 + +noncomputable section +open scoped BigOperators +open MatchingEntropyBounds MatchingEntropyBounds.Refined +namespace TriangleFace198 +variable {V E : Type*} [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] + +def LocalLabels (G : LooplessGraph V E) (v : V) (c : E → Fin 3) : Prop := + ∀ i, ∃! e, G.Incident v e ∧ c e = i + +def localEdge (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (hc : LocalLabels G v c) (i : Fin 3) : E := Classical.choose (hc i) + +def localExtension (G : LooplessGraph V E) (c : E → Fin 3) (v : V) + (hc : LocalLabels G v c) : (E → ℝ) →ₗ[ℝ] (E ⊕ Fin 3 → ℝ) where + toFun x := Sum.elim x (fun i => x (localEdge G c v hc i)) + map_add' x y := by ext e; cases e <;> rfl + map_smul' a x := by ext e; cases e <;> rfl + +def oldRestriction : (E ⊕ Fin 3 → ℝ) →ₗ[ℝ] (E → ℝ) where + toFun y e := y (Sum.inl e) + map_add' _ _ := rfl + map_smul' _ _ := rfl + +end TriangleFace198 + +end + +noncomputable section +open scoped BigOperators +open MatchingEntropyBounds MatchingEntropyBounds.Refined +namespace TriangleFace198 +universe uV uE +variable {V : Type uV} {E : Type uE} [instFintypeV : Fintype V] [Fintype E] [DecidableEq V] [instDecidableEqE : DecidableEq E] + +theorem triangle_expansion_face {V : Type uV} {E : Type uE} + [Fintype V] [Fintype E] [DecidableEq V] [DecidableEq E] (G : LooplessGraph V E) (v : V) + (hdeg : Fintype.card {e : E // G.Incident v e} = 3) + (_hmatching : Nonempty G.Matching) : + ∃ (c : E → Fin 3) (hc : LocalLabels G v c), + let H := triangleExpansion G c v + let f := localExtension G c v hc + let Q := {y | y ∈ H.polytope ∧ H.cutMass y (triangleVertices v) = 1} + f '' G.polytope = Q ∧ + Convex ℝ Q ∧ IsExtreme ℝ H.polytope Q ∧ + (∀ x, oldRestriction (f x) = x) ∧ + (∀ y ∈ Q, f (oldRestriction y) = y) ∧ + (∀ x e, f x (Sum.inl e) = x e) ∧ + (∀ x i, f x (Sum.inr i) = x (localEdge G c v hc i)) ∧ + (∀ x, (∀ e, x e = (1/3 : ℝ)) → ∀ e, f x e = (1/3 : ℝ)) ∧ + (∀ x ∈ G.polytope, CanonicalFace198.minFace H.polytope (f x) = f '' CanonicalFace198.minFace G.polytope x) := by + sorry + +end TriangleFace198 +end + +end OAI diff --git a/tasks/triangle-face/tests/grade.py b/tasks/triangle-face/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangle-face/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangle-face/tests/task.json b/tasks/triangle-face/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f5a9e7d9adcf15449303c933e88ffe2a946c4a49 --- /dev/null +++ b/tasks/triangle-face/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangleFace", + "comparator": { + "theorem_names": [ + "OAI.TriangleFace198.triangle_expansion_face" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11093 +} \ No newline at end of file diff --git a/tasks/triangle-face/tests/test.sh b/tasks/triangle-face/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangle-face/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangle-removal/environment/Dockerfile b/tasks/triangle-removal/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangle-removal/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangle-removal/environment/fetch_mathlib.sh b/tasks/triangle-removal/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangle-removal/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangle-removal/environment/lake-manifest.json b/tasks/triangle-removal/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangle-removal/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangle-removal/environment/lakefile.lean b/tasks/triangle-removal/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangle-removal/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangle-removal/environment/lean_setup.sh b/tasks/triangle-removal/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangle-removal/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangle-removal/environment/pack_submission.py b/tasks/triangle-removal/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangle-removal/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangle-removal/instruction.md b/tasks/triangle-removal/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c2fcee2d425e657a690cdb87c311710c74f5d285 --- /dev/null +++ b/tasks/triangle-removal/instruction.md @@ -0,0 +1,118 @@ +# openai/math challenge `TriangleRemoval` (family 188) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 188 of the release, *The sharp constant in random triangle removal* +(Combinatorics). The family as a whole: Starting from the complete graph on $n$ vertices, repeatedly delete a uniformly chosen remaining triangle. The terminal edge count is asymptotic to $n^{3/2}/(2\sqrt2)$, with mean-square convergence after normalization by $n^{3/2}$. This proves the triangle case of the Joos–Kuhn sharp-constant conjecture. + +The challenge is `TriangleRemoval`, also at `/opt/openai-math/challenges/TriangleRemoval.lean`: + +```lean +import Mathlib + +namespace OAI + +section +section + +open Filter +open scoped BigOperators Topology + +namespace SharpTerminalLeave + +abbrev Graph (n : ℕ) := Finset (Finset (Fin n)) + +def completeGraph (n : ℕ) : Graph n := Finset.univ.powersetCard 2 + +def triangles {n : ℕ} (G : Graph n) : Finset (Finset (Fin n)) := + (Finset.univ.powersetCard 3).filter (fun t => t.powersetCard 2 ⊆ G) + +noncomputable def step {n : ℕ} (G : Graph n) : PMF (Graph n) := + if h : (triangles G).Nonempty then + (PMF.uniformOfFinset (triangles G) h).map (fun t => G \ t.powersetCard 2) + else PMF.pure G + +noncomputable def evolve {n : ℕ} (G : Graph n) : ℕ → PMF (Graph n) + | 0 => PMF.pure G + | k + 1 => (evolve G k).bind step + +noncomputable def terminalLaw (n : ℕ) : PMF (Graph n) := + evolve (completeGraph n) (n.choose 2) + +noncomputable def expectation (n : ℕ) (f : Graph n → ℝ) : ℝ := + ∑ G, (terminalLaw n G).toReal * f G + +noncomputable def probability (n : ℕ) (P : Graph n → Prop) : ℝ := by + classical + exact expectation n (fun G => if P G then 1 else 0) + +noncomputable def normalization (n : ℕ) : ℝ := (n : ℝ) ^ (3 / 2 : ℝ) + +noncomputable def normalizedLeave (n : ℕ) (G : Graph n) : ℝ := + (G.card : ℝ) / normalization n + +noncomputable def sharpConstant : ℝ := 1 / (2 * Real.sqrt 2) + +end SharpTerminalLeave +end +end + +open Filter +open scoped BigOperators Topology + +namespace SharpTerminalLeave + +theorem sharp_terminal_leave : + Tendsto (fun n => expectation n (fun G => + (normalizedLeave n G - sharpConstant) ^ 2)) atTop (𝓝 0) ∧ + (∀ ε : ℝ, 0 < ε → + Tendsto (fun n => probability n (fun G => + ε < |normalizedLeave n G - sharpConstant|)) atTop (𝓝 0)) ∧ + Tendsto (fun n => expectation n (fun G => (G.card : ℝ)) / normalization n) + atTop (𝓝 sharpConstant) := by + sorry + +end SharpTerminalLeave + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangleRemoval.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.SharpTerminalLeave.sharp_terminal_leave` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangle-removal/solution/closure.txt b/tasks/triangle-removal/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..4160370277b815896a4eb6631ab5aa76cb4e2dca --- /dev/null +++ b/tasks/triangle-removal/solution/closure.txt @@ -0,0 +1,287 @@ +OAI.Combinatorics.TriangleRemoval.Asymptotics.ActiveL2Map +OAI.Combinatorics.TriangleRemoval.Asymptotics.DensityEdgeSafe +OAI.Combinatorics.TriangleRemoval.Asymptotics.DensityEdgeSafeTriangle +OAI.Combinatorics.TriangleRemoval.Asymptotics.DensityGlobalInfty +OAI.Combinatorics.TriangleRemoval.Asymptotics.EarlyDensity +OAI.Combinatorics.TriangleRemoval.Asymptotics.EarlyDensityOne +OAI.Combinatorics.TriangleRemoval.Asymptotics.EndpointMarksExponential +OAI.Combinatorics.TriangleRemoval.Asymptotics.FreshLog +OAI.Combinatorics.TriangleRemoval.Asymptotics.FreshLogExposeLabeled +OAI.Combinatorics.TriangleRemoval.Asymptotics.LogStepSandwich +OAI.Combinatorics.TriangleRemoval.Asymptotics.OneAddLogRpow +OAI.Combinatorics.TriangleRemoval.Asymptotics.RelativeScaleBudgetLog +OAI.Combinatorics.TriangleRemoval.Coupling.ClockOrder +OAI.Combinatorics.TriangleRemoval.Coupling.GridUniformError +OAI.Combinatorics.TriangleRemoval.Coupling.HyperScanAction +OAI.Combinatorics.TriangleRemoval.Coupling.InitialAssignmentSetBound +OAI.Combinatorics.TriangleRemoval.Coupling.OrderEmbRank +OAI.Combinatorics.TriangleRemoval.Coupling.OrderLaw +OAI.Combinatorics.TriangleRemoval.Coupling.OrderedSuffix +OAI.Combinatorics.TriangleRemoval.Coupling.OrderedWeightMono +OAI.Combinatorics.TriangleRemoval.Coupling.ScanList +OAI.Combinatorics.TriangleRemoval.Coupling.SelectedClockLawPair +OAI.Combinatorics.TriangleRemoval.Coupling.UniformRootAtom +OAI.Combinatorics.TriangleRemoval.Coupling.UnitTime +OAI.Combinatorics.TriangleRemoval.Embeddings.BirthGraph +OAI.Combinatorics.TriangleRemoval.Embeddings.DegreeTemplate +OAI.Combinatorics.TriangleRemoval.Embeddings.EmbeddedWitnessPathSize +OAI.Combinatorics.TriangleRemoval.Embeddings.EmbeddedWitnessRoots +OAI.Combinatorics.TriangleRemoval.Embeddings.EmptyRootInjection +OAI.Combinatorics.TriangleRemoval.Embeddings.FixedEndpointPairInjective +OAI.Combinatorics.TriangleRemoval.Embeddings.GraphEmbeddings +OAI.Combinatorics.TriangleRemoval.Embeddings.GraphEmbeddingsRestriction +OAI.Combinatorics.TriangleRemoval.Embeddings.PathBirthIndex +OAI.Combinatorics.TriangleRemoval.Embeddings.ReindexEmbedding +OAI.Combinatorics.TriangleRemoval.Embeddings.RerootTemplate +OAI.Combinatorics.TriangleRemoval.Embeddings.RestrictLabel +OAI.Combinatorics.TriangleRemoval.Embeddings.RootedTemplates +OAI.Combinatorics.TriangleRemoval.Embeddings.SuffixTemplate +OAI.Combinatorics.TriangleRemoval.Embeddings.TriangleGrowth +OAI.Combinatorics.TriangleRemoval.Embeddings.TriangleGrowth2 +OAI.Combinatorics.TriangleRemoval.Embeddings.WitnessEmbeddingBound +OAI.Combinatorics.TriangleRemoval.Main +OAI.Combinatorics.TriangleRemoval.Model +OAI.Combinatorics.TriangleRemoval.Probability.AbsPmfMean +OAI.Combinatorics.TriangleRemoval.Probability.FiniteMean +OAI.Combinatorics.TriangleRemoval.Probability.HistoryLawPastMean +OAI.Combinatorics.TriangleRemoval.Probability.HistoryLawPathSupport +OAI.Combinatorics.TriangleRemoval.Probability.MainProbabilityPrefixFailure +OAI.Combinatorics.TriangleRemoval.Probability.MarkedSuccessTrueProbability +OAI.Combinatorics.TriangleRemoval.Probability.MarkovLaw +OAI.Combinatorics.TriangleRemoval.Probability.PairVisitProbability +OAI.Combinatorics.TriangleRemoval.Probability.PathVisitProbability +OAI.Combinatorics.TriangleRemoval.Probability.PmfMeanAffineSq +OAI.Combinatorics.TriangleRemoval.Probability.PmfMeanLiminfTendsto +OAI.Combinatorics.TriangleRemoval.Probability.PmfMeanNeg +OAI.Combinatorics.TriangleRemoval.Probability.ProductPMF +OAI.Combinatorics.TriangleRemoval.Probability.ProductPMFMeanProduct +OAI.Combinatorics.TriangleRemoval.Probability.RootPairVisitProbability +OAI.Combinatorics.TriangleRemoval.Probability.RootPairVisitProbability2 +OAI.Combinatorics.TriangleRemoval.Probability.RootPathVisitProbability +OAI.Combinatorics.TriangleRemoval.Probability.TriangleSafeTemplateFreedman +OAI.Combinatorics.TriangleRemoval.Probability.TrueProbabilityMap +OAI.Combinatorics.TriangleRemoval.Probability.UniformDistinctRootSet +OAI.Combinatorics.TriangleRemoval.Probability.UniformSingletonRootSet +OAI.Combinatorics.TriangleRemoval.Process.ActiveHypergraph +OAI.Combinatorics.TriangleRemoval.Process.ActivePairMembership +OAI.Combinatorics.TriangleRemoval.Process.Attachment +OAI.Combinatorics.TriangleRemoval.Process.AveragedSingletonSurvivalError +OAI.Combinatorics.TriangleRemoval.Process.AveragingProjectorInftyOne +OAI.Combinatorics.TriangleRemoval.Process.BackEdgesCardSplit +OAI.Combinatorics.TriangleRemoval.Process.BornEdges +OAI.Combinatorics.TriangleRemoval.Process.CardBiUnion +OAI.Combinatorics.TriangleRemoval.Process.CenteredEdgeVectorTriangle +OAI.Combinatorics.TriangleRemoval.Process.CenteredNeighborSumBound +OAI.Combinatorics.TriangleRemoval.Process.ChargesCovered +OAI.Combinatorics.TriangleRemoval.Process.CommonNeighbors +OAI.Combinatorics.TriangleRemoval.Process.CommonNeighborsComplete +OAI.Combinatorics.TriangleRemoval.Process.CommonNeighborsMono +OAI.Combinatorics.TriangleRemoval.Process.CompleteEdge +OAI.Combinatorics.TriangleRemoval.Process.CompleteEdgePair +OAI.Combinatorics.TriangleRemoval.Process.CopyEdgeLoad +OAI.Combinatorics.TriangleRemoval.Process.CopyLoadSafe +OAI.Combinatorics.TriangleRemoval.Process.DivergentArms +OAI.Combinatorics.TriangleRemoval.Process.EdgeFamilyDegree +OAI.Combinatorics.TriangleRemoval.Process.EdgeIncidence +OAI.Combinatorics.TriangleRemoval.Process.EdgeMatching +OAI.Combinatorics.TriangleRemoval.Process.EdgePairNe +OAI.Combinatorics.TriangleRemoval.Process.EigenProjector +OAI.Combinatorics.TriangleRemoval.Process.EigenvalueAbsRowsum +OAI.Combinatorics.TriangleRemoval.Process.EvolveBindFinish +OAI.Combinatorics.TriangleRemoval.Process.ExtendedLinkMulVec +OAI.Combinatorics.TriangleRemoval.Process.FilteredSigmaWeightBound +OAI.Combinatorics.TriangleRemoval.Process.Finish +OAI.Combinatorics.TriangleRemoval.Process.FinishSupportSubset +OAI.Combinatorics.TriangleRemoval.Process.FreshMemSelected +OAI.Combinatorics.TriangleRemoval.Process.GraphCardSqrt +OAI.Combinatorics.TriangleRemoval.Process.History +OAI.Combinatorics.TriangleRemoval.Process.HistoryAdditive +OAI.Combinatorics.TriangleRemoval.Process.HistoryAlive +OAI.Combinatorics.TriangleRemoval.Process.HistoryCompensator +OAI.Combinatorics.TriangleRemoval.Process.HistoryGraphNested +OAI.Combinatorics.TriangleRemoval.Process.IncidenceDegree +OAI.Combinatorics.TriangleRemoval.Process.IncidentTriangleThird +OAI.Combinatorics.TriangleRemoval.Process.IndexedAttachmentOlder +OAI.Combinatorics.TriangleRemoval.Process.IndexedPatternEdges +OAI.Combinatorics.TriangleRemoval.Process.IndexedWitnessCode +OAI.Combinatorics.TriangleRemoval.Process.IndexedWitnessCodeCard +OAI.Combinatorics.TriangleRemoval.Process.InitialAssignmentSet +OAI.Combinatorics.TriangleRemoval.Process.InitialAssignmentSetBound +OAI.Combinatorics.TriangleRemoval.Process.InitialAssignmentSetMatching +OAI.Combinatorics.TriangleRemoval.Process.LevelDeletes +OAI.Combinatorics.TriangleRemoval.Process.LinkSimpleGraph +OAI.Combinatorics.TriangleRemoval.Process.LocalChoiceRank +OAI.Combinatorics.TriangleRemoval.Process.LongWitnessMatchingCount +OAI.Combinatorics.TriangleRemoval.Process.LookupGraph +OAI.Combinatorics.TriangleRemoval.Process.LookupGraphDegree +OAI.Combinatorics.TriangleRemoval.Process.MapOutput +OAI.Combinatorics.TriangleRemoval.Process.MatchingSeedEdgeRoots +OAI.Combinatorics.TriangleRemoval.Process.MatchingSeedFullEdge +OAI.Combinatorics.TriangleRemoval.Process.NonrootForest +OAI.Combinatorics.TriangleRemoval.Process.OlderSeed +OAI.Combinatorics.TriangleRemoval.Process.OrientedEdges +OAI.Combinatorics.TriangleRemoval.Process.OverlapVertices +OAI.Combinatorics.TriangleRemoval.Process.PairRequired +OAI.Combinatorics.TriangleRemoval.Process.Parent +OAI.Combinatorics.TriangleRemoval.Process.PathForest +OAI.Combinatorics.TriangleRemoval.Process.PathPattern +OAI.Combinatorics.TriangleRemoval.Process.PathRequired +OAI.Combinatorics.TriangleRemoval.Process.PathRequiredBaseAppend +OAI.Combinatorics.TriangleRemoval.Process.PathRequiredBaseChild +OAI.Combinatorics.TriangleRemoval.Process.PathSuffix +OAI.Combinatorics.TriangleRemoval.Process.PerturbationPolynomialBound +OAI.Combinatorics.TriangleRemoval.Process.PlusEdgesSimple +OAI.Combinatorics.TriangleRemoval.Process.PowerEulerError +OAI.Combinatorics.TriangleRemoval.Process.PowersetCardTriple +OAI.Combinatorics.TriangleRemoval.Process.ProgramDemand +OAI.Combinatorics.TriangleRemoval.Process.ProspectiveFailure +OAI.Combinatorics.TriangleRemoval.Process.RealCardFiberBound +OAI.Combinatorics.TriangleRemoval.Process.ReindexQuadratic +OAI.Combinatorics.TriangleRemoval.Process.ReindexSet +OAI.Combinatorics.TriangleRemoval.Process.ReindexSetImage +OAI.Combinatorics.TriangleRemoval.Process.RelativeCopyNoiseFirst +OAI.Combinatorics.TriangleRemoval.Process.RelativeNoiseExit +OAI.Combinatorics.TriangleRemoval.Process.RelativeSafeCopyIncrement +OAI.Combinatorics.TriangleRemoval.Process.RelativeScaleBudget +OAI.Combinatorics.TriangleRemoval.Process.Restrict +OAI.Combinatorics.TriangleRemoval.Process.RestrictedParent +OAI.Combinatorics.TriangleRemoval.Process.RootClosers +OAI.Combinatorics.TriangleRemoval.Process.RootSet +OAI.Combinatorics.TriangleRemoval.Process.SeedEdgeSubsetPath +OAI.Combinatorics.TriangleRemoval.Process.SparseScalingOne +OAI.Combinatorics.TriangleRemoval.Process.SuffixBoundary +OAI.Combinatorics.TriangleRemoval.Process.SuffixProjection +OAI.Combinatorics.TriangleRemoval.Process.TerminalLaw +OAI.Combinatorics.TriangleRemoval.Process.ThreeChooseBound +OAI.Combinatorics.TriangleRemoval.Process.TriangleDegreeMean +OAI.Combinatorics.TriangleRemoval.Process.TriangleHypergraph +OAI.Combinatorics.TriangleRemoval.Process.TriangleHypergraphLinear +OAI.Combinatorics.TriangleRemoval.Process.TriangleHypergraphReindex +OAI.Combinatorics.TriangleRemoval.Process.TriangleIndex +OAI.Combinatorics.TriangleRemoval.Process.TriangleLiftCount +OAI.Combinatorics.TriangleRemoval.Process.TriangleNoiseJumpBudget +OAI.Combinatorics.TriangleRemoval.Process.TriangleThird +OAI.Combinatorics.TriangleRemoval.Process.TripleFactorBounds +OAI.Combinatorics.TriangleRemoval.Process.UnitLineRemainder +OAI.Combinatorics.TriangleRemoval.Process.ValidAttachments +OAI.Combinatorics.TriangleRemoval.Process.ValidIndexedAttachments +OAI.Combinatorics.TriangleRemoval.Process.VariationConstants +OAI.Combinatorics.TriangleRemoval.Process.Within +OAI.Combinatorics.TriangleRemoval.Process.WitnessCountEventually +OAI.Combinatorics.TriangleRemoval.Process.WitnessDimensionEquiv +OAI.Combinatorics.TriangleRemoval.Process.WitnessDimensions +OAI.Combinatorics.TriangleRemoval.Process.WitnessMu +OAI.Combinatorics.TriangleRemoval.Queries.Address +OAI.Combinatorics.TriangleRemoval.Queries.AddressHead +OAI.Combinatorics.TriangleRemoval.Queries.CallPath +OAI.Combinatorics.TriangleRemoval.Queries.CallPathCollisionWitness +OAI.Combinatorics.TriangleRemoval.Queries.CanonicalCollisionSingletonSum +OAI.Combinatorics.TriangleRemoval.Queries.CanonicalCollisionSum +OAI.Combinatorics.TriangleRemoval.Queries.Child +OAI.Combinatorics.TriangleRemoval.Queries.ContinuationCollisionRemainderTendsto +OAI.Combinatorics.TriangleRemoval.Queries.FinsetCandidateOrder +OAI.Combinatorics.TriangleRemoval.Queries.ForkAddressesNotSuffix +OAI.Combinatorics.TriangleRemoval.Queries.GridCollision +OAI.Combinatorics.TriangleRemoval.Queries.JointMarkedQuery +OAI.Combinatorics.TriangleRemoval.Queries.JointMarkedQueryPair +OAI.Combinatorics.TriangleRemoval.Queries.KeyCandidate +OAI.Combinatorics.TriangleRemoval.Queries.LegalCollisionPairs +OAI.Combinatorics.TriangleRemoval.Queries.MarkedChild +OAI.Combinatorics.TriangleRemoval.Queries.MarkedChildKernelProspective +OAI.Combinatorics.TriangleRemoval.Queries.MarkedDemand +OAI.Combinatorics.TriangleRemoval.Queries.MarkedIndexedAttachmentPattern +OAI.Combinatorics.TriangleRemoval.Queries.MarkedRow +OAI.Combinatorics.TriangleRemoval.Queries.MarkedSuccess +OAI.Combinatorics.TriangleRemoval.Queries.MemAddressId +OAI.Combinatorics.TriangleRemoval.Queries.MessageCandidatesReindex +OAI.Combinatorics.TriangleRemoval.Queries.OrderedMarkedRow +OAI.Combinatorics.TriangleRemoval.Queries.OrderedMarkedRowUnweighted +OAI.Combinatorics.TriangleRemoval.Queries.RecordedCallForest +OAI.Combinatorics.TriangleRemoval.Queries.Separated +OAI.Combinatorics.TriangleRemoval.Queries.SplitQueryPaths +OAI.Combinatorics.TriangleRemoval.Queries.TreeBind +OAI.Combinatorics.TriangleRemoval.Queries.VertexCall +OAI.Combinatorics.TriangleRemoval.Spectral.CheckMarkedTrace +OAI.Combinatorics.TriangleRemoval.Spectral.CheckMarkedTraceCommon +OAI.Combinatorics.TriangleRemoval.Spectral.CheckMarkedTraceHit +OAI.Combinatorics.TriangleRemoval.Spectral.ClosedWalkFamily +OAI.Combinatorics.TriangleRemoval.Spectral.ClosedWalkPattern +OAI.Combinatorics.TriangleRemoval.Spectral.ClosedWords +OAI.Combinatorics.TriangleRemoval.Spectral.CountClosedWalk +OAI.Combinatorics.TriangleRemoval.Spectral.DensityGlobalSpectral +OAI.Combinatorics.TriangleRemoval.Spectral.EdgeStar +OAI.Combinatorics.TriangleRemoval.Spectral.ExtendStarApply +OAI.Combinatorics.TriangleRemoval.Spectral.ExtendStarMulVec +OAI.Combinatorics.TriangleRemoval.Spectral.FallingFactorialNormalizedProduct +OAI.Combinatorics.TriangleRemoval.Spectral.FreshLogCheckNone +OAI.Combinatorics.TriangleRemoval.Spectral.FreshLogCheckNone2 +OAI.Combinatorics.TriangleRemoval.Spectral.FreshLogCheckNone3 +OAI.Combinatorics.TriangleRemoval.Spectral.GlobalLinkAdjacencyHermitian +OAI.Combinatorics.TriangleRemoval.Spectral.GraphStarApproximation +OAI.Combinatorics.TriangleRemoval.Spectral.LinkStarMatrix +OAI.Combinatorics.TriangleRemoval.Spectral.MatrixEuclideanAlgHom +OAI.Combinatorics.TriangleRemoval.Spectral.MatrixExpL2Bound +OAI.Combinatorics.TriangleRemoval.Spectral.MatrixInfinityAlgHom +OAI.Combinatorics.TriangleRemoval.Spectral.MatrixRowAbsSum +OAI.Combinatorics.TriangleRemoval.Spectral.MovingStarDegree +OAI.Combinatorics.TriangleRemoval.Spectral.NormalizedOnes +OAI.Combinatorics.TriangleRemoval.Spectral.RealTraceAdjMatrix +OAI.Combinatorics.TriangleRemoval.Spectral.StarInclusion +OAI.Combinatorics.TriangleRemoval.Spectral.TracedGridQueryAddress +OAI.Combinatorics.TriangleRemoval.Spectral.TracedGridQueryLog +OAI.Combinatorics.TriangleRemoval.Spectral.TracedGridQuerySeparated +OAI.Combinatorics.TriangleRemoval.Spectral.WheelSpoke +OAI.Combinatorics.TriangleRemoval.Stability.ActiveCavityFactorProduct +OAI.Combinatorics.TriangleRemoval.Stability.CavityGenerator +OAI.Combinatorics.TriangleRemoval.Stability.CavityReference +OAI.Combinatorics.TriangleRemoval.Stability.CavityWeight +OAI.Combinatorics.TriangleRemoval.Stability.CavityWeightLipschitz +OAI.Combinatorics.TriangleRemoval.Stability.ContinuousCavityWeightClip +OAI.Combinatorics.TriangleRemoval.Stability.EdgeStabilityRate +OAI.Combinatorics.TriangleRemoval.Stability.GeometricVolterraIdentity +OAI.Combinatorics.TriangleRemoval.Stability.GridCavityError +OAI.Combinatorics.TriangleRemoval.Stability.GridCavityWeightLower +OAI.Combinatorics.TriangleRemoval.Stability.MovingPerturbationFiniteExpansion +OAI.Combinatorics.TriangleRemoval.Stability.MovingResidualForcing +OAI.Combinatorics.TriangleRemoval.Stability.RelativeTemplateResidual +OAI.Combinatorics.TriangleRemoval.Stability.Volterra +OAI.Combinatorics.TriangleRemoval.Tracking.BalancedJump +OAI.Combinatorics.TriangleRemoval.Tracking.CenteredCodegreeNeighborSum +OAI.Combinatorics.TriangleRemoval.Tracking.CodegreeNoiseRadius +OAI.Combinatorics.TriangleRemoval.Tracking.CodegreeRelativeNoiseTail +OAI.Combinatorics.TriangleRemoval.Tracking.CodegreeVarianceRate +OAI.Combinatorics.TriangleRemoval.Tracking.CodegreeVertexCount +OAI.Combinatorics.TriangleRemoval.Tracking.GoodPrefixStarApproximation +OAI.Combinatorics.TriangleRemoval.Tracking.GoodPrefixSurvivalMoments +OAI.Combinatorics.TriangleRemoval.Tracking.NormalizedTrackingAbsolute +OAI.Combinatorics.TriangleRemoval.Tracking.PolynomialExponentialPrefixEnvelope +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixBalancedNoise +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixCodeSet +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixCodegreeDriftTerm +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixCodegreeErrorExit +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixCodegreeNoiseExit +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixCodegreeNoiseGood +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixDTendstoTop +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEdgeForcingBound +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEdgeRadius +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEdgeResidualBounds +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEmbeddings +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEmbeddingsAfterRoots +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEmbeddingsEdgeCover +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixEpsilon +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixFailureEnvelopeSuperpolynomial +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixHorizon +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixMessageEnvelopeSmall +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixPairClosureBudget +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixSpectralErrorPower +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixTimeSquare +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixTriangleRadius +OAI.Combinatorics.TriangleRemoval.Tracking.PrefixWeight +OAI.Combinatorics.TriangleRemoval.Tracking.RootedCompletionMax +OAI.Combinatorics.TriangleRemoval.Tracking.RootedCountedTracedRepeat +OAI.Combinatorics.TriangleRemoval.Tracking.RootedExposedCollisionWitness +OAI.Combinatorics.TriangleRemoval.Tracking.RootedInjectionEquiv +OAI.Combinatorics.TriangleRemoval.Tracking.RootedInjectionEquivFree +OAI.Combinatorics.TriangleRemoval.Tracking.RootedTemplateEdgesCard +OAI.Combinatorics.TriangleRemoval.Tracking.RootedTemplateEncoding +OAI.Combinatorics.TriangleRemoval.Tracking.TriangleDrift diff --git a/tasks/triangle-removal/solution/reference.py b/tasks/triangle-removal/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangle-removal/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangle-removal/solution/solve.sh b/tasks/triangle-removal/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..6e4a9ae7b1c1c6fa39ea8373261414a2571a823d --- /dev/null +++ b/tasks/triangle-removal/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangleRemoval, i.e. module OAI.Combinatorics.TriangleRemoval.Main and the +# 287 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TriangleRemoval.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangleRemoval" diff --git a/tasks/triangle-removal/task.toml b/tasks/triangle-removal/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..5ba6af41fe68898d871f6c486b99e349331d7296 --- /dev/null +++ b/tasks/triangle-removal/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangle-removal" +version = "1.0.0" +description = "Prove TriangleRemoval (openai/math family 188: The sharp constant in random triangle removal) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "combinatorics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangleRemoval.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangleRemoval" +family = "188" +family_title = "The sharp constant in random triangle removal" +subject = "Combinatorics" +theorems = ["OAI.SharpTerminalLeave.sharp_terminal_leave"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TriangleRemoval.Main" +reference_modules = 287 +reference_lean_bytes = 1468947 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 935 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13022 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangle-removal/tests/Challenge.lean b/tasks/triangle-removal/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..44f756332a829369d6b6547be9a5931629431aab --- /dev/null +++ b/tasks/triangle-removal/tests/Challenge.lean @@ -0,0 +1,67 @@ +import Mathlib + +namespace OAI + +section +section + +open Filter +open scoped BigOperators Topology + +namespace SharpTerminalLeave + +abbrev Graph (n : ℕ) := Finset (Finset (Fin n)) + +def completeGraph (n : ℕ) : Graph n := Finset.univ.powersetCard 2 + +def triangles {n : ℕ} (G : Graph n) : Finset (Finset (Fin n)) := + (Finset.univ.powersetCard 3).filter (fun t => t.powersetCard 2 ⊆ G) + +noncomputable def step {n : ℕ} (G : Graph n) : PMF (Graph n) := + if h : (triangles G).Nonempty then + (PMF.uniformOfFinset (triangles G) h).map (fun t => G \ t.powersetCard 2) + else PMF.pure G + +noncomputable def evolve {n : ℕ} (G : Graph n) : ℕ → PMF (Graph n) + | 0 => PMF.pure G + | k + 1 => (evolve G k).bind step + +noncomputable def terminalLaw (n : ℕ) : PMF (Graph n) := + evolve (completeGraph n) (n.choose 2) + +noncomputable def expectation (n : ℕ) (f : Graph n → ℝ) : ℝ := + ∑ G, (terminalLaw n G).toReal * f G + +noncomputable def probability (n : ℕ) (P : Graph n → Prop) : ℝ := by + classical + exact expectation n (fun G => if P G then 1 else 0) + +noncomputable def normalization (n : ℕ) : ℝ := (n : ℝ) ^ (3 / 2 : ℝ) + +noncomputable def normalizedLeave (n : ℕ) (G : Graph n) : ℝ := + (G.card : ℝ) / normalization n + +noncomputable def sharpConstant : ℝ := 1 / (2 * Real.sqrt 2) + +end SharpTerminalLeave +end +end + +open Filter +open scoped BigOperators Topology + +namespace SharpTerminalLeave + +theorem sharp_terminal_leave : + Tendsto (fun n => expectation n (fun G => + (normalizedLeave n G - sharpConstant) ^ 2)) atTop (𝓝 0) ∧ + (∀ ε : ℝ, 0 < ε → + Tendsto (fun n => probability n (fun G => + ε < |normalizedLeave n G - sharpConstant|)) atTop (𝓝 0)) ∧ + Tendsto (fun n => expectation n (fun G => (G.card : ℝ)) / normalization n) + atTop (𝓝 sharpConstant) := by + sorry + +end SharpTerminalLeave + +end OAI diff --git a/tasks/triangle-removal/tests/grade.py b/tasks/triangle-removal/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangle-removal/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangle-removal/tests/task.json b/tasks/triangle-removal/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9363f9df9a2d5fb5d20cedf731e0ed7e5aa5a032 --- /dev/null +++ b/tasks/triangle-removal/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangleRemoval", + "comparator": { + "theorem_names": [ + "OAI.SharpTerminalLeave.sharp_terminal_leave" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 12122 +} \ No newline at end of file diff --git a/tasks/triangle-removal/tests/test.sh b/tasks/triangle-removal/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangle-removal/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangular-covering/environment/Dockerfile b/tasks/triangular-covering/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangular-covering/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangular-covering/environment/fetch_mathlib.sh b/tasks/triangular-covering/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangular-covering/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangular-covering/environment/lake-manifest.json b/tasks/triangular-covering/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangular-covering/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangular-covering/environment/lakefile.lean b/tasks/triangular-covering/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangular-covering/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangular-covering/environment/lean_setup.sh b/tasks/triangular-covering/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangular-covering/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangular-covering/environment/pack_submission.py b/tasks/triangular-covering/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangular-covering/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangular-covering/instruction.md b/tasks/triangular-covering/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..34a0c60369298df850ab6c9558e743e4b29baaf1 --- /dev/null +++ b/tasks/triangular-covering/instruction.md @@ -0,0 +1,123 @@ +# openai/math challenge `TriangularCovering` (family 100) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 100 of the release, *A counterexample to Bang's cylinder-covering bound* +(Convex and metric geometry). The family as a whole: Covers the entire closed regular tetrahedron by finitely many cylinders with compact triangular perpendicular bases whose total area is less than half its smallest orthogonal projection area. This disproves Bang's half-area cylinder-covering bound and the stronger directionwise normalized conjecture in dimension three. + +The challenge is `TriangularCovering`, also at `/opt/openai-math/challenges/TriangularCovering.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def H : ℝ := Real.sqrt 2 + +def point (x y t : ℝ) : Space := !₂[x, y, H * t] + +def K : Set Space := + {z | ∃ x y t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |x| ≤ 1 - t ∧ |y| ≤ t ∧ z = point x y t} + +def projection (u z : Space) : Space := z - (inner ℝ u z) • u + +def area (B : Set Space) : ℝ := (Measure.euclideanHausdorffMeasure 2 B).toReal + +def shadowArea (u : Space) : ℝ := area (projection u '' K) + +def A_min : ℝ := sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea u} + +structure TriCylinder where + axis : Space + base : Set Space + unit_axis : ‖axis‖ = 1 + perpendicular : ∀ z ∈ base, inner ℝ axis z = 0 + triangular : ∃ v : Fin 3 → Space, AffineIndependent ℝ v ∧ + base = convexHull ℝ (Set.range v) + compact : IsCompact base + convex : Convex ℝ base + measurable : MeasurableSet base + finite_area : Measure.euclideanHausdorffMeasure 2 base ≠ ⊤ + +def TriCylinder.carrier (c : TriCylinder) : Set Space := + {z | ∃ b ∈ c.base, ∃ r : ℝ, z = b + r • c.axis} + +def Covers {m : ℕ} (c : Fin m → TriCylinder) : Prop := + ∀ z ∈ K, ∃ i : Fin m, z ∈ (c i).carrier + +def totalArea {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base + +def relativeCost {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base / shadowArea (c i).axis + +def n (ε : ℝ) : ℕ := ⌈2 / ε ^ 2⌉₊ + +def MainAsymptotic : Prop := + ∃ δ C : ℝ, 0 < δ ∧ 0 < C ∧ + ∀ ε : ℝ, 0 < ε → ε < δ → + ∃ c : Fin (2 * n ε) → TriCylinder, + Covers c ∧ + |totalArea c / H - (1 / 2 - (13 / 6000 : ℝ) * ε ^ 2)| ≤ C * ε ^ 4 ∧ + totalArea c < A_min / 2 + +def NormalizedCounterexample : Prop := + ∃ m : ℕ, ∃ c : Fin m → TriCylinder, Covers c ∧ relativeCost c < 1 / 2 + +theorem main : A_min = H ∧ MainAsymptotic ∧ NormalizedCounterexample := by + sorry + +end TriangularCovering + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangularCovering.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TriangularCovering.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangular-covering/solution/closure.txt b/tasks/triangular-covering/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..b6281493a26444bd8793eab5960b21c0040a4cb1 --- /dev/null +++ b/tasks/triangular-covering/solution/closure.txt @@ -0,0 +1,9 @@ +OAI.Geometry.TriangularCovering.Asymptotics +OAI.Geometry.TriangularCovering.Basic +OAI.Geometry.TriangularCovering.CoordinateCover +OAI.Geometry.TriangularCovering.CylinderFamily +OAI.Geometry.TriangularCovering.Main +OAI.Geometry.TriangularCovering.Projection +OAI.Geometry.TriangularCovering.Shadows +OAI.Geometry.TriangularCovering.Tetrahedron +OAI.Geometry.TriangularCovering.TriangleArea diff --git a/tasks/triangular-covering/solution/reference.py b/tasks/triangular-covering/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangular-covering/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangular-covering/solution/solve.sh b/tasks/triangular-covering/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..86b3d0d27fc03fe9b46c9164704142a970bcbb1d --- /dev/null +++ b/tasks/triangular-covering/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangularCovering, i.e. module OAI.Geometry.TriangularCovering.Main and the +# 9 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.TriangularCovering.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangularCovering" diff --git a/tasks/triangular-covering/task.toml b/tasks/triangular-covering/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c682c4b53472ed35e59022945de5927054d5ae92 --- /dev/null +++ b/tasks/triangular-covering/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangular-covering" +version = "1.0.0" +description = "Prove TriangularCovering (openai/math family 100: A counterexample to Bang's cylinder-covering bound) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangularCovering.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangularCovering" +family = "100" +family_title = "A counterexample to Bang's cylinder-covering bound" +subject = "Convex and metric geometry" +theorems = ["OAI.TriangularCovering.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.TriangularCovering.Main" +reference_modules = 9 +reference_lean_bytes = 96114 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 203 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11786 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangular-covering/tests/Challenge.lean b/tasks/triangular-covering/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1d77c559a02feed7ab6917ca3669fea6100a3b95 --- /dev/null +++ b/tasks/triangular-covering/tests/Challenge.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +open Set MeasureTheory +open scoped InnerProductSpace BigOperators Interval + +noncomputable section +namespace TriangularCovering + +abbrev Space := EuclideanSpace ℝ (Fin 3) + +def H : ℝ := Real.sqrt 2 + +def point (x y t : ℝ) : Space := !₂[x, y, H * t] + +def K : Set Space := + {z | ∃ x y t : ℝ, 0 ≤ t ∧ t ≤ 1 ∧ |x| ≤ 1 - t ∧ |y| ≤ t ∧ z = point x y t} + +def projection (u z : Space) : Space := z - (inner ℝ u z) • u + +def area (B : Set Space) : ℝ := (Measure.euclideanHausdorffMeasure 2 B).toReal + +def shadowArea (u : Space) : ℝ := area (projection u '' K) + +def A_min : ℝ := sInf {a : ℝ | ∃ u : Space, ‖u‖ = 1 ∧ a = shadowArea u} + +structure TriCylinder where + axis : Space + base : Set Space + unit_axis : ‖axis‖ = 1 + perpendicular : ∀ z ∈ base, inner ℝ axis z = 0 + triangular : ∃ v : Fin 3 → Space, AffineIndependent ℝ v ∧ + base = convexHull ℝ (Set.range v) + compact : IsCompact base + convex : Convex ℝ base + measurable : MeasurableSet base + finite_area : Measure.euclideanHausdorffMeasure 2 base ≠ ⊤ + +def TriCylinder.carrier (c : TriCylinder) : Set Space := + {z | ∃ b ∈ c.base, ∃ r : ℝ, z = b + r • c.axis} + +def Covers {m : ℕ} (c : Fin m → TriCylinder) : Prop := + ∀ z ∈ K, ∃ i : Fin m, z ∈ (c i).carrier + +def totalArea {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base + +def relativeCost {m : ℕ} (c : Fin m → TriCylinder) : ℝ := + ∑ i : Fin m, area (c i).base / shadowArea (c i).axis + +def n (ε : ℝ) : ℕ := ⌈2 / ε ^ 2⌉₊ + +def MainAsymptotic : Prop := + ∃ δ C : ℝ, 0 < δ ∧ 0 < C ∧ + ∀ ε : ℝ, 0 < ε → ε < δ → + ∃ c : Fin (2 * n ε) → TriCylinder, + Covers c ∧ + |totalArea c / H - (1 / 2 - (13 / 6000 : ℝ) * ε ^ 2)| ≤ C * ε ^ 4 ∧ + totalArea c < A_min / 2 + +def NormalizedCounterexample : Prop := + ∃ m : ℕ, ∃ c : Fin m → TriCylinder, Covers c ∧ relativeCost c < 1 / 2 + +theorem main : A_min = H ∧ MainAsymptotic ∧ NormalizedCounterexample := by + sorry + +end TriangularCovering + +end + +end OAI diff --git a/tasks/triangular-covering/tests/grade.py b/tasks/triangular-covering/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangular-covering/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangular-covering/tests/task.json b/tasks/triangular-covering/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..fcd7232d5259c471855b9139cd20c1c8f0e93a5d --- /dev/null +++ b/tasks/triangular-covering/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangularCovering", + "comparator": { + "theorem_names": [ + "OAI.TriangularCovering.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10886 +} \ No newline at end of file diff --git a/tasks/triangular-covering/tests/test.sh b/tasks/triangular-covering/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangular-covering/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangular-energy/environment/Dockerfile b/tasks/triangular-energy/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangular-energy/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangular-energy/environment/fetch_mathlib.sh b/tasks/triangular-energy/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangular-energy/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangular-energy/environment/lake-manifest.json b/tasks/triangular-energy/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangular-energy/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangular-energy/environment/lakefile.lean b/tasks/triangular-energy/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangular-energy/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangular-energy/environment/lean_setup.sh b/tasks/triangular-energy/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangular-energy/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangular-energy/environment/pack_submission.py b/tasks/triangular-energy/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangular-energy/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangular-energy/instruction.md b/tasks/triangular-energy/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..d645d70fb2dc5982700500c5a17cbb5d24f89e18 --- /dev/null +++ b/tasks/triangular-energy/instruction.md @@ -0,0 +1,125 @@ +# openai/math challenge `TriangularEnergy` (family 090) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 090 of the release, *Universal optimality of the triangular lattice* +(Convex and metric geometry). The family as a whole: Proves that the triangular lattice minimizes the lower limit of energy per particle for every nonnegative completely monotone potential of squared distance among locally finite planar configurations of centered-disk density one. It also minimizes unit-background renormalized Riesz energies for $0 (diskCount C R : ℝ) / (Real.pi * R ^ 2)) + atTop (𝓝 1) + +def AdmissiblePotential (g : ℝ → ℝ) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) g (Set.Ioi 0) ∧ + (∀ t : ℝ, 0 < t → 0 ≤ g t) ∧ + ∀ (r : ℕ) (t : ℝ), 0 < t → 0 ≤ (-1 : ℝ) ^ r * iteratedDeriv r g t + +def diskEnergy (g : ℝ → ℝ) (C : Set Plane) (R : ℝ) : ℝ≥0∞ := + (diskCount C R : ℝ≥0∞)⁻¹ * + ∑ x ∈ diskPoints C R, ∑ y ∈ (diskPoints C R).erase x, + ENNReal.ofReal (g (‖x - y‖ ^ 2)) + +def energy (g : ℝ → ℝ) (C : Set Plane) : ℝ≥0∞ := + Filter.liminf (diskEnergy g C) atTop + +end TriangularUniversal + +namespace AtomicTriangular + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def b : ℝ := Real.sqrt 3 / 2 + +def triangularPoint (jk : ℤ × ℤ) : Plane := + (Real.sqrt b)⁻¹ • + (EuclideanSpace.single 0 ((jk.1 : ℝ) + (jk.2 : ℝ) / 2) + + EuclideanSpace.single 1 ((jk.2 : ℝ) * b)) + +def A : Set Plane := Set.range triangularPoint + +abbrev LocallyFinite := TriangularUniversal.LocallyFinite +abbrev diskPoints := TriangularUniversal.diskPoints +abbrev diskCount := TriangularUniversal.diskCount +abbrev DensityOne := TriangularUniversal.DensityOne +abbrev AdmissiblePotential := TriangularUniversal.AdmissiblePotential +abbrev diskEnergy := TriangularUniversal.diskEnergy +abbrev energy := TriangularUniversal.energy + +/-- The full nonzero-lattice energy, allowing a divergent series. -/ +def latticeEnergy (g : ℝ → ℝ) : ℝ≥0∞ := + ∑' a : {x : Plane // x ∈ A ∧ x ≠ 0}, ENNReal.ofReal (g (‖a.val‖ ^ 2)) + +/-- Universal energy minimality for smooth completely monotone potentials, with attainment. -/ +theorem universal_energy_minimum (g : ℝ → ℝ) (C : Set Plane) + (hg : AdmissiblePotential g) (hC : LocallyFinite C) (hd : DensityOne C) : + latticeEnergy g ≤ energy g C ∧ latticeEnergy g = energy g A := by + sorry + +end AtomicTriangular +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangularEnergy.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AtomicTriangular.universal_energy_minimum` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangular-energy/solution/closure.txt b/tasks/triangular-energy/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..745c28410b7f5acea8c767193469758e931c9c6a --- /dev/null +++ b/tasks/triangular-energy/solution/closure.txt @@ -0,0 +1,227 @@ +OAI.Analysis.Triangular.Auxiliary.Bernstein +OAI.Analysis.Triangular.Auxiliary.ExponentialTail +OAI.Analysis.Triangular.Auxiliary.IntegralBounds +OAI.Analysis.Triangular.Auxiliary.MatrixNorm +OAI.Analysis.Triangular.Auxiliary.PolynomialShift +OAI.Analysis.Triangular.Basic +OAI.Analysis.Triangular.Certificate.Inverse +OAI.Analysis.Triangular.Certificate.JetMatrix +OAI.Analysis.Triangular.Certificate.MatrixInterval +OAI.Analysis.Triangular.Certificate.Param +OAI.Analysis.Triangular.Certificate.ParamA +OAI.Analysis.Triangular.Certificate.ParamActual +OAI.Analysis.Triangular.Certificate.ParamInterval +OAI.Analysis.Triangular.Certificate.ParamNorm +OAI.Analysis.Triangular.Certificate.ParamNormBase +OAI.Analysis.Triangular.Certificate.ParamRHS +OAI.Analysis.Triangular.Certificate.ParamU +OAI.Analysis.Triangular.Certificate.Polytope +OAI.Analysis.Triangular.Certificate.PolytopeInterval +OAI.Analysis.Triangular.Certificate.TargetInterval +OAI.Analysis.Triangular.Certificate.WaveExpData +OAI.Analysis.Triangular.Certificate.WaveIntervals +OAI.Analysis.Triangular.Certificate.WaveJetsData +OAI.Analysis.Triangular.Construction.ActualCorrection +OAI.Analysis.Triangular.Construction.ActualInput +OAI.Analysis.Triangular.Construction.ActualInterpolation +OAI.Analysis.Triangular.Construction.ActualTail +OAI.Analysis.Triangular.Construction.AtomicCurvature +OAI.Analysis.Triangular.Construction.BlockOperators +OAI.Analysis.Triangular.Construction.CoefficientAddition +OAI.Analysis.Triangular.Construction.ConcreteSchur +OAI.Analysis.Triangular.Construction.CurvatureAnalytic +OAI.Analysis.Triangular.Construction.CurvatureBoxes +OAI.Analysis.Triangular.Construction.CurvatureEnvelope +OAI.Analysis.Triangular.Construction.CurvatureSums +OAI.Analysis.Triangular.Construction.DirectCoordinates +OAI.Analysis.Triangular.Construction.DirectWaveJets +OAI.Analysis.Triangular.Construction.FarCurvature +OAI.Analysis.Triangular.Construction.FiniteAssembly +OAI.Analysis.Triangular.Construction.FiniteCoordinates +OAI.Analysis.Triangular.Construction.FiniteInterpolation +OAI.Analysis.Triangular.Construction.FiniteJets +OAI.Analysis.Triangular.Construction.FinitePairBridge +OAI.Analysis.Triangular.Construction.FiniteProjection +OAI.Analysis.Triangular.Construction.FiniteRemainder +OAI.Analysis.Triangular.Construction.FiniteSystem +OAI.Analysis.Triangular.Construction.FiniteTargetBridge +OAI.Analysis.Triangular.Construction.L1Kernel +OAI.Analysis.Triangular.Construction.L1Matrix +OAI.Analysis.Triangular.Construction.NodeJets +OAI.Analysis.Triangular.Construction.Normalization +OAI.Analysis.Triangular.Construction.NormalizedJets +OAI.Analysis.Triangular.Construction.PeriodicJets +OAI.Analysis.Triangular.Construction.Repetition +OAI.Analysis.Triangular.Construction.RepetitionBound +OAI.Analysis.Triangular.Construction.RepetitionOperators +OAI.Analysis.Triangular.Construction.Schur +OAI.Analysis.Triangular.Construction.SpectralJetBridge +OAI.Analysis.Triangular.Construction.SpectralProduct +OAI.Analysis.Triangular.Construction.TailCoordinates +OAI.Analysis.Triangular.Construction.TailEnumeration +OAI.Analysis.Triangular.Construction.TailInterpolation +OAI.Analysis.Triangular.Construction.TailJetVector +OAI.Analysis.Triangular.Energy.Basic +OAI.Analysis.Triangular.Energy.Cutoff +OAI.Analysis.Triangular.Energy.Definitions +OAI.Analysis.Triangular.Energy.Density +OAI.Analysis.Triangular.Energy.Gaussian +OAI.Analysis.Triangular.Energy.GaussianPoisson +OAI.Analysis.Triangular.Energy.Lattice +OAI.Analysis.Triangular.Energy.LatticePoisson +OAI.Analysis.Triangular.Energy.Mixtures +OAI.Analysis.Triangular.Energy.PairPoisson +OAI.Analysis.Triangular.Energy.Potentials +OAI.Analysis.Triangular.Energy.Schwartz +OAI.Analysis.Triangular.Energy.Spectral +OAI.Analysis.Triangular.Energy.Theta +OAI.Analysis.Triangular.Energy.Universal +OAI.Analysis.Triangular.Envelope.Analytic +OAI.Analysis.Triangular.Envelope.Basic +OAI.Analysis.Triangular.Envelope.EnvelopeBoxes +OAI.Analysis.Triangular.Envelope.EnvelopeNorm0 +OAI.Analysis.Triangular.Envelope.EnvelopeNorm1 +OAI.Analysis.Triangular.Envelope.EnvelopeNorm2 +OAI.Analysis.Triangular.Envelope.EnvelopeNorms +OAI.Analysis.Triangular.Envelope.EnvelopePsiB +OAI.Analysis.Triangular.Envelope.EnvelopePsiC +OAI.Analysis.Triangular.Envelope.EnvelopePsiD +OAI.Analysis.Triangular.Envelope.EnvelopeSums +OAI.Analysis.Triangular.Envelope.EnvelopeSumsBase +OAI.Analysis.Triangular.Envelope.EnvelopeWaves +OAI.Analysis.Triangular.Envelope.JetEnvelopeAnalytic +OAI.Analysis.Triangular.Envelope.KernelBounds +OAI.Analysis.Triangular.Envelope.TailEnvelopeSeries +OAI.Analysis.Triangular.Envelope.TargetEnvelope +OAI.Analysis.Triangular.Lattice.LatticeGeometry +OAI.Analysis.Triangular.Schwartz.FourierCLM +OAI.Analysis.Triangular.Schwartz.FourierPair +OAI.Analysis.Triangular.Schwartz.Gaussian +OAI.Analysis.Triangular.Schwartz.GaussianPair +OAI.Analysis.Triangular.Schwartz.InputCLM +OAI.Analysis.Triangular.Schwartz.Realness +OAI.Analysis.Triangular.Schwartz.Regularity +OAI.Analysis.Triangular.Schwartz.SpectralCLM +OAI.Analysis.Triangular.Schwartz.SpectralEnvelope +OAI.Analysis.Triangular.Schwartz.TailSpectral +OAI.Analysis.Triangular.Signs.DeletedAccuracy +OAI.Analysis.Triangular.Signs.DeletedExponential +OAI.Analysis.Triangular.Signs.DeletedJets +OAI.Analysis.Triangular.Signs.DeletedQuotient +OAI.Analysis.Triangular.Signs.Exceptional +OAI.Analysis.Triangular.Signs.ExceptionalComparison +OAI.Analysis.Triangular.Signs.ExceptionalInterval +OAI.Analysis.Triangular.Signs.ExceptionalSign0 +OAI.Analysis.Triangular.Signs.ExceptionalSign1 +OAI.Analysis.Triangular.Signs.ExceptionalSign2 +OAI.Analysis.Triangular.Signs.ExceptionalSign3 +OAI.Analysis.Triangular.Signs.FarSigns +OAI.Analysis.Triangular.Signs.GaussianDeleted +OAI.Analysis.Triangular.Signs.NearSigns +OAI.Analysis.Triangular.Signs.OrdinaryComparison +OAI.Analysis.Triangular.Signs.RemainderBoxes +OAI.Analysis.Triangular.Signs.RemainderData0 +OAI.Analysis.Triangular.Signs.RemainderData1 +OAI.Analysis.Triangular.Signs.RemainderData2 +OAI.Analysis.Triangular.Signs.RemainderData3 +OAI.Analysis.Triangular.Signs.RemainderData4 +OAI.Analysis.Triangular.Signs.RemainderData5 +OAI.Analysis.Triangular.Signs.RemainderData6 +OAI.Analysis.Triangular.Signs.RemainderNorm +OAI.Analysis.Triangular.Signs.RemainderPre +OAI.Analysis.Triangular.Signs.RemainderSums0 +OAI.Analysis.Triangular.Signs.RemainderSums1 +OAI.Analysis.Triangular.Signs.RemainderSums2 +OAI.Analysis.Triangular.Signs.RemainderSums3 +OAI.Analysis.Triangular.Signs.RemainderSums4 +OAI.Analysis.Triangular.Signs.RemainderSums5 +OAI.Analysis.Triangular.Signs.RemainderSums6 +OAI.Analysis.Triangular.Signs.SignBase +OAI.Analysis.Triangular.Signs.Signs00 +OAI.Analysis.Triangular.Signs.Signs01 +OAI.Analysis.Triangular.Signs.Signs02 +OAI.Analysis.Triangular.Signs.Signs03 +OAI.Analysis.Triangular.Signs.Signs04 +OAI.Analysis.Triangular.Signs.Signs05 +OAI.Analysis.Triangular.Signs.Signs06 +OAI.Analysis.Triangular.Signs.Signs10 +OAI.Analysis.Triangular.Signs.Signs11 +OAI.Analysis.Triangular.Signs.Signs12 +OAI.Analysis.Triangular.Signs.Signs13 +OAI.Analysis.Triangular.Signs.Signs14 +OAI.Analysis.Triangular.Signs.Signs15 +OAI.Analysis.Triangular.Signs.Signs16 +OAI.Analysis.Triangular.Signs.SineBarrierBase +OAI.Analysis.Triangular.Signs.SineGlobal +OAI.Analysis.Triangular.Signs.SineGrid0 +OAI.Analysis.Triangular.Signs.SineGrid1 +OAI.Analysis.Triangular.Signs.SineGrid2 +OAI.Analysis.Triangular.Signs.SineGridAnalytic +OAI.Analysis.Triangular.Signs.SineGridChecks +OAI.Analysis.Triangular.Signs.SineGridCover +OAI.Analysis.Triangular.Signs.SineGridDefs +OAI.Analysis.Triangular.Taylor.CoefficientSpectral +OAI.Analysis.Triangular.Taylor.CurvatureData00 +OAI.Analysis.Triangular.Taylor.CurvatureData01 +OAI.Analysis.Triangular.Taylor.CurvatureData10 +OAI.Analysis.Triangular.Taylor.CurvatureData11 +OAI.Analysis.Triangular.Taylor.FiniteTaylorError +OAI.Analysis.Triangular.Taylor.FiniteTaylorIdentity +OAI.Analysis.Triangular.Taylor.Taylor +OAI.Analysis.Triangular.Taylor.TaylorExp +OAI.Analysis.Triangular.Taylor.TaylorExp00 +OAI.Analysis.Triangular.Taylor.TaylorExp01 +OAI.Analysis.Triangular.Taylor.TaylorExp10 +OAI.Analysis.Triangular.Taylor.TaylorExp11 +OAI.Analysis.Triangular.Taylor.TaylorPhase +OAI.Analysis.Triangular.Taylor.TaylorRows00 +OAI.Analysis.Triangular.Taylor.TaylorRows01 +OAI.Analysis.Triangular.Taylor.TaylorRows02 +OAI.Analysis.Triangular.Taylor.TaylorRows03 +OAI.Analysis.Triangular.Taylor.TaylorRows04 +OAI.Analysis.Triangular.Taylor.TaylorRows05 +OAI.Analysis.Triangular.Taylor.TaylorRows06 +OAI.Analysis.Triangular.Taylor.TaylorRows10 +OAI.Analysis.Triangular.Taylor.TaylorRows11 +OAI.Analysis.Triangular.Taylor.TaylorRows12 +OAI.Analysis.Triangular.Taylor.TaylorRows13 +OAI.Analysis.Triangular.Taylor.TaylorRows14 +OAI.Analysis.Triangular.Taylor.TaylorRows15 +OAI.Analysis.Triangular.Taylor.TaylorRows16 +OAI.Analysis.Triangular.Taylor.TaylorRowsBase +OAI.Analysis.Triangular.Taylor.TaylorSpectrum +OAI.Analysis.Triangular.Taylor.TaylorWave +OAI.Analysis.Triangular.Taylor.TaylorWave00 +OAI.Analysis.Triangular.Taylor.TaylorWave000 +OAI.Analysis.Triangular.Taylor.TaylorWave001 +OAI.Analysis.Triangular.Taylor.TaylorWave002 +OAI.Analysis.Triangular.Taylor.TaylorWave003 +OAI.Analysis.Triangular.Taylor.TaylorWave004 +OAI.Analysis.Triangular.Taylor.TaylorWave005 +OAI.Analysis.Triangular.Taylor.TaylorWave006 +OAI.Analysis.Triangular.Taylor.TaylorWave01 +OAI.Analysis.Triangular.Taylor.TaylorWave010 +OAI.Analysis.Triangular.Taylor.TaylorWave011 +OAI.Analysis.Triangular.Taylor.TaylorWave012 +OAI.Analysis.Triangular.Taylor.TaylorWave013 +OAI.Analysis.Triangular.Taylor.TaylorWave014 +OAI.Analysis.Triangular.Taylor.TaylorWave015 +OAI.Analysis.Triangular.Taylor.TaylorWave016 +OAI.Analysis.Triangular.Taylor.TaylorWave10 +OAI.Analysis.Triangular.Taylor.TaylorWave100 +OAI.Analysis.Triangular.Taylor.TaylorWave101 +OAI.Analysis.Triangular.Taylor.TaylorWave102 +OAI.Analysis.Triangular.Taylor.TaylorWave103 +OAI.Analysis.Triangular.Taylor.TaylorWave104 +OAI.Analysis.Triangular.Taylor.TaylorWave105 +OAI.Analysis.Triangular.Taylor.TaylorWave106 +OAI.Analysis.Triangular.Taylor.TaylorWave11 +OAI.Analysis.Triangular.Taylor.TaylorWave110 +OAI.Analysis.Triangular.Taylor.TaylorWave111 +OAI.Analysis.Triangular.Taylor.TaylorWave112 +OAI.Analysis.Triangular.Taylor.TaylorWave113 +OAI.Analysis.Triangular.Taylor.TaylorWave114 +OAI.Analysis.Triangular.Taylor.TaylorWave115 +OAI.Analysis.Triangular.Taylor.TaylorWave116 +OAI.Analysis.Triangular.Taylor.VariationBound +OAI.Analysis.Triangular.Taylor.WaveFunction diff --git a/tasks/triangular-energy/solution/reference.py b/tasks/triangular-energy/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangular-energy/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangular-energy/solution/solve.sh b/tasks/triangular-energy/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..17c2e1a26ea46ae25d8022f7b948600d6d9b6459 --- /dev/null +++ b/tasks/triangular-energy/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangularEnergy, i.e. module OAI.Analysis.Triangular.Energy.Universal and the +# 227 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Triangular.Energy.Universal /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangularEnergy" diff --git a/tasks/triangular-energy/task.toml b/tasks/triangular-energy/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..561b3e8f8762b35f12a46a0570f0c3ae4f2d1b26 --- /dev/null +++ b/tasks/triangular-energy/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangular-energy" +version = "1.0.0" +description = "Prove TriangularEnergy (openai/math family 090: Universal optimality of the triangular lattice) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangularEnergy.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangularEnergy" +family = "090" +family_title = "Universal optimality of the triangular lattice" +subject = "Convex and metric geometry" +theorems = ["OAI.AtomicTriangular.universal_energy_minimum"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Triangular.Energy.Universal" +reference_modules = 227 +reference_lean_bytes = 8590367 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 10732 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19431 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangular-energy/tests/Challenge.lean b/tasks/triangular-energy/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7dd73651627729ecaf8917377b52daec63828170 --- /dev/null +++ b/tasks/triangular-energy/tests/Challenge.lean @@ -0,0 +1,74 @@ +import Mathlib + +namespace OAI + +noncomputable section +open scoped BigOperators Topology ENNReal +open Classical Filter + +namespace TriangularUniversal + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def LocallyFinite (C : Set Plane) : Prop := + ∀ R : ℝ, (C ∩ Metric.closedBall (0 : Plane) R).Finite + +def diskPoints (C : Set Plane) (R : ℝ) : Finset Plane := + if h : (C ∩ Metric.closedBall (0 : Plane) R).Finite then h.toFinset else ∅ + +def diskCount (C : Set Plane) (R : ℝ) : ℕ := (diskPoints C R).card + +def DensityOne (C : Set Plane) : Prop := + Tendsto (fun R : ℝ => (diskCount C R : ℝ) / (Real.pi * R ^ 2)) + atTop (𝓝 1) + +def AdmissiblePotential (g : ℝ → ℝ) : Prop := + ContDiffOn ℝ (⊤ : ℕ∞) g (Set.Ioi 0) ∧ + (∀ t : ℝ, 0 < t → 0 ≤ g t) ∧ + ∀ (r : ℕ) (t : ℝ), 0 < t → 0 ≤ (-1 : ℝ) ^ r * iteratedDeriv r g t + +def diskEnergy (g : ℝ → ℝ) (C : Set Plane) (R : ℝ) : ℝ≥0∞ := + (diskCount C R : ℝ≥0∞)⁻¹ * + ∑ x ∈ diskPoints C R, ∑ y ∈ (diskPoints C R).erase x, + ENNReal.ofReal (g (‖x - y‖ ^ 2)) + +def energy (g : ℝ → ℝ) (C : Set Plane) : ℝ≥0∞ := + Filter.liminf (diskEnergy g C) atTop + +end TriangularUniversal + +namespace AtomicTriangular + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def b : ℝ := Real.sqrt 3 / 2 + +def triangularPoint (jk : ℤ × ℤ) : Plane := + (Real.sqrt b)⁻¹ • + (EuclideanSpace.single 0 ((jk.1 : ℝ) + (jk.2 : ℝ) / 2) + + EuclideanSpace.single 1 ((jk.2 : ℝ) * b)) + +def A : Set Plane := Set.range triangularPoint + +abbrev LocallyFinite := TriangularUniversal.LocallyFinite +abbrev diskPoints := TriangularUniversal.diskPoints +abbrev diskCount := TriangularUniversal.diskCount +abbrev DensityOne := TriangularUniversal.DensityOne +abbrev AdmissiblePotential := TriangularUniversal.AdmissiblePotential +abbrev diskEnergy := TriangularUniversal.diskEnergy +abbrev energy := TriangularUniversal.energy + +/-- The full nonzero-lattice energy, allowing a divergent series. -/ +def latticeEnergy (g : ℝ → ℝ) : ℝ≥0∞ := + ∑' a : {x : Plane // x ∈ A ∧ x ≠ 0}, ENNReal.ofReal (g (‖a.val‖ ^ 2)) + +/-- Universal energy minimality for smooth completely monotone potentials, with attainment. -/ +theorem universal_energy_minimum (g : ℝ → ℝ) (C : Set Plane) + (hg : AdmissiblePotential g) (hC : LocallyFinite C) (hd : DensityOne C) : + latticeEnergy g ≤ energy g C ∧ latticeEnergy g = energy g A := by + sorry + +end AtomicTriangular +end + +end OAI diff --git a/tasks/triangular-energy/tests/grade.py b/tasks/triangular-energy/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangular-energy/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangular-energy/tests/task.json b/tasks/triangular-energy/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..47a83797e326c63714839ff9f2e5616e9b503777 --- /dev/null +++ b/tasks/triangular-energy/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangularEnergy", + "comparator": { + "theorem_names": [ + "OAI.AtomicTriangular.universal_energy_minimum" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18531 +} \ No newline at end of file diff --git a/tasks/triangular-energy/tests/test.sh b/tasks/triangular-energy/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangular-energy/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangular-gaussian/environment/Dockerfile b/tasks/triangular-gaussian/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangular-gaussian/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangular-gaussian/environment/fetch_mathlib.sh b/tasks/triangular-gaussian/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangular-gaussian/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangular-gaussian/environment/lake-manifest.json b/tasks/triangular-gaussian/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangular-gaussian/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangular-gaussian/environment/lakefile.lean b/tasks/triangular-gaussian/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangular-gaussian/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangular-gaussian/environment/lean_setup.sh b/tasks/triangular-gaussian/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangular-gaussian/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangular-gaussian/environment/pack_submission.py b/tasks/triangular-gaussian/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangular-gaussian/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangular-gaussian/instruction.md b/tasks/triangular-gaussian/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..29ea2b5a5b03c79552aff1d28fb41c40e015baf2 --- /dev/null +++ b/tasks/triangular-gaussian/instruction.md @@ -0,0 +1,326 @@ +# openai/math challenge `TriangularGaussian` (family 090) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 090 of the release, *Universal optimality of the triangular lattice* +(Convex and metric geometry). The family as a whole: Proves that the triangular lattice minimizes the lower limit of energy per particle for every nonnegative completely monotone potential of squared distance among locally finite planar configurations of centered-disk density one. It also minimizes unit-background renormalized Riesz energies for $0 (f x : ℂ)) w + +end AtomicTriangular + +namespace AtomicTriangular.Construction + +def b : ℝ := Real.sqrt 3 / 2 + +def h : ℝ := 17 / 50 + +def H : ℝ := 27 / 50 + +def eta : ℝ := 1 / 5 + +def kappa : ℝ := Real.pi / 36 + +def residues : Finset ℤ := {0,1,3,4,7,9,12,13,16,19,21,25,27,28,31} + +def residue (a : Fin 15) : ℤ := ![0,1,3,4,7,9,12,13,16,19,21,25,27,28,31] a + +def Node : Type := {n : ℤ // 0 < n ∧ n % 36 ∈ residues} + +def FiniteNodes : Finset ℤ := {1,3,4,7,9,12,13,16,19,21} + +def sineFactor (a : Fin 15) (s : ℂ) : ℂ := + 2 * Complex.sin ((kappa : ℂ) * (s - (residue a : ℂ))) + +def P (s : ℂ) : ℂ := ∏ a : Fin 15, (sineFactor a s)^2 + +def dBasis (n : Node) : ℂ → ℂ := dslope P (n.val : ℂ) + +def cBasis (n : Node) : ℂ → ℂ := dslope (dBasis n) (n.val : ℂ) + +def finiteC (a : Fin 15) (s : ℂ) : ℂ := + 4 * (kappa : ℂ)^2 * ∏ r ∈ Finset.univ.erase a, (sineFactor r s)^2 + +def finiteD (a : Fin 15) (s : ℂ) : ℂ := + 2 * (kappa : ℂ) * sineFactor a s * + Complex.cos ((kappa : ℂ) * (s - (residue a : ℂ))) * + ∏ r ∈ Finset.univ.erase a, (sineFactor r s)^2 + +def phase (s : ℂ) : ℂ := Complex.exp ((Real.pi : ℂ) * Complex.I * s / 18) + +def atomFactor (a : Fin 15) : Polynomial ℂ := + -C (phase (residue a)) + C 2 * X - C (phase (-residue a)) * X^2 + +def atomPolynomial : Polynomial ℂ := ∏ a : Fin 15, atomFactor a + +def cAtomPolynomial (a : Fin 15) : Polynomial ℂ := + C (4 * (kappa : ℂ)^2) * ∏ r ∈ Finset.univ.erase a, atomFactor r + +def dAtomPolynomial (a : Fin 15) : Polynomial ℂ := + C (Complex.I * (kappa : ℂ)) * + (C (phase (residue a)) - C (phase (-residue a)) * X^2) * + ∏ r ∈ Finset.univ.erase a, atomFactor r + +def fourierCoeff (j : Fin 31) : ℂ := atomPolynomial.coeff j.val + +def frequency (j : Fin 31) : ℝ := ((j.val : ℝ)-15)/18 + +def waveDerivative (k : ℕ) (s : ℂ) : ℂ := + ∑ j : Fin 31, fourierCoeff j * (I*Real.pi*frequency j)^k * + exp (I*Real.pi*frequency j*s) + +def Q (n : ℤ) : ℝ := (waveDerivative 2 n).re / 2 + +def D (n : ℤ) : ℝ := (waveDerivative 3 n).re / (6 * Q n) + +end AtomicTriangular.Construction + +namespace AtomicTriangular.FiniteCertificate +open Construction + +def cShiftPolynomial (a : Fin 15) : Polynomial ℂ := X * cAtomPolynomial a + +def cCoefficient (a : Fin 15) (j : Fin 31) : ℂ := (cShiftPolynomial a).coeff j.val + +def dCoefficient (a : Fin 15) (j : Fin 31) : ℂ := (dAtomPolynomial a).coeff j.val + +end AtomicTriangular.FiniteCertificate + +namespace AtomicTriangular.Construction + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def radial (x : Plane) : ℝ := b*‖x‖^2 + +def waveDen (k t : ℝ) : ℝ := k^2+t^2 + +def Xwave (k t : ℝ) : ℝ := (4/3)/waveDen k t + +def lambda (k t : ℝ) : ℂ := ((k:ℂ)+I*t)/(b*waveDen k t : ℝ) + +def zeta (k v t : ℝ) : ℂ := -(t:ℂ)*(Xwave k t:ℂ)+I*(k*Xwave k t-v:ℝ) + +def transformedWave (k v t : ℝ) (s : ℂ) : ℂ := lambda k t*exp (I*Real.pi*zeta k v t*s) + +def finiteColumn (col : Fin 23) (j : Fin 31) : ℂ := + if hc : col.val<22 then + if col.val%2=0 then FiniteCertificate.cCoefficient ⟨col.val/2,by omega⟩ j + else FiniteCertificate.dCoefficient ⟨col.val/2,by omega⟩ j + else fourierCoeff j + +def finiteNode (n : Fin 10) : ℤ := residue ⟨n.val+1,by omega⟩ + +def jetMultiplier (k v : ℝ) (n : ℤ) (d : Fin 2) (t : ℝ) : ℂ := + (Q n:ℂ)⁻¹*transformedWave k v t n * + (if d.val=0 then -1 else (D n:ℂ)-I*Real.pi*zeta k v t) + +def jet (k v : ℝ) (n : ℤ) (d : Fin 2) (S : Fin 31 → ℂ) : ℝ := + (∑ j : Fin 31, jetMultiplier k v n d (frequency j)*S j).re + +def fullJetMatrix : Matrix (Fin 20) (Fin 23) ℝ := fun i col => + jet (if col.val=22 then h else H) H + (finiteNode ⟨i.val/2,by omega⟩) ⟨i.val%2,by omega⟩ (finiteColumn col) + +def R : Matrix (Fin 20) (Fin 20) ℝ := fun i j => fullJetMatrix i ⟨j.val+2,by omega⟩ + +def R0 : Matrix (Fin 20) (Fin 3) ℝ := fun i j => + fullJetMatrix i (if j.val<2 then ⟨j.val,by omega⟩ else 22) + +abbrev TailNode := {n : Node // n.val ∉ FiniteNodes} + +structure InputCoefficients where + C : ℝ + finiteC : Fin 11 → ℝ + finiteD : Fin 11 → ℝ + tailC : TailNode → ℝ + tailD : TailNode → ℝ + summable : Summable (fun n => |tailC n|+|tailD n|) + +def tailInput (a : InputCoefficients) (s : ℂ) : ℂ := + (a.C:ℂ)*P s + ∑' n : TailNode, ((a.tailC n:ℂ)*cBasis n.val s+(a.tailD n:ℂ)*dBasis n.val s) + +def finiteInput (a : InputCoefficients) (s : ℂ) : ℂ := + ∑ j : Fin 11, ((a.finiteC j:ℂ)*finiteC ⟨j.val,by omega⟩ s + + (a.finiteD j:ℂ)*finiteD ⟨j.val,by omega⟩ s) + +def inputComplex (a : InputCoefficients) (x : Plane) : ℂ := + exp (-(Real.pi:ℂ)*h*(radial x:ℂ))*tailInput a (radial x) + + exp (-(Real.pi:ℂ)*H*(radial x:ℂ))*finiteInput a (radial x) + +def targetCoefficient (n : Fin 10) : ℝ := Q 1 / Q (finiteNode n) * Real.exp (Real.pi*eta*(finiteNode n)) + +def Yf : Matrix (Fin 20) (Fin 8) ℝ := fun i j => + if i.val<8 then + targetCoefficient ⟨i.val/2,by omega⟩ * + (if i.val%2=0 then (if j.val=i.val then 1 else 0) + else (if j.val=i.val then -1 else if j.val=i.val-1 then Real.pi*eta-D (finiteNode ⟨i.val/2,by omega⟩) else 0)) + else 0 + +def gamma (side : Fin 2) : Matrix (Fin 3) (Fin 8) ℝ := fun i j => + if j.val=1 then (if i.val=0 then 11/25 else if i.val=1 then 0 else if side.val=0 then -(3/500) else 3/500) else 0 + +def Uplus : Matrix (Fin 20) (Fin 8) ℝ := + (1-R)⁻¹*(Yf+R0*(gamma 1+gamma 0)) + +def Uminus : Matrix (Fin 20) (Fin 8) ℝ := + (1+R)⁻¹*(Yf+R0*(gamma 1-gamma 0)) + +def finiteSolution (side : Fin 2) : Matrix (Fin 20) (Fin 8) ℝ := + if side.val=0 then (1/2:ℝ) • (Uplus+Uminus) else (1/2:ℝ) • (Uplus-Uminus) + +def Acoefficient (side : Fin 2) : Matrix (Fin 23) (Fin 8) ℝ := fun i j => + if hi : i.val<2 then gamma side ⟨i.val,by omega⟩ j + else if h22 : i.val=22 then gamma side 2 j + else finiteSolution side ⟨i.val-2,by omega⟩ j + +def gaussianZ (α : ℝ) : ℝ := 1/(Real.pi*(α/b-h)) + +def actualParameter (z : ℝ) : Fin 8 → ℝ := + ![z,1,z*Real.exp (-2/z),Real.exp (-2/z),z*Real.exp (-3/z),Real.exp (-3/z), + z*Real.exp (-6/z),Real.exp (-6/z)] + +def normalizingDen (z : ℝ) := Q 1*z*Real.exp (1/z) + +end AtomicTriangular.Construction + +end + +noncomputable section +open scoped BigOperators FourierTransform + +namespace AtomicTriangular.Construction + +def correctedFinite (side : Fin 2) (z : ℝ) (δ : Fin 20 → ℝ) (j : Fin 22) : ℝ := + (∑ r : Fin 8, Acoefficient side ⟨j.val, by omega⟩ r * actualParameter z r) + + if hj : j.val < 2 then 0 else δ ⟨j.val - 2, by omega⟩ + +end AtomicTriangular.Construction + +namespace AtomicTriangular +open Construction + +local instance finite_pair_neZero : NeZero (2 : ℕ) := inferInstance +local instance three_atLeastTwo : Nat.AtLeastTwo 3 := inferInstance +local instance ten_atLeastTwo : Nat.AtLeastTwo 10 := inferInstance +local instance five_hundred_atLeastTwo : Nat.AtLeastTwo 500 := inferInstance +local instance plane_borelSpace : BorelSpace Plane := inferInstance +local instance plane_finite : Module.Finite ℝ Plane := inferInstance + +def AtomicConstruction (α : ℝ) (f : Plane → ℝ) : Prop := + IsUnit (1 - R) ∧ IsUnit (1 + R) ∧ + (1 - R) * Uplus = Yf + R0 * (gamma 1 + gamma 0) ∧ + (1 + R) * Uminus = Yf + R0 * (gamma 1 - gamma 0) ∧ + ∃ (δ : Fin 2 → Fin 20 → ℝ) (a : Fin 2 → InputCoefficients), + (∀ side, (∑ j : Fin 20, |δ side j|) < (1 / 10^5 : ℝ)) ∧ + (∀ side, (a side).C = if side.val = 0 then -(3/500) else 3/500) ∧ + (∀ side (j : Fin 11), + (a side).finiteC j = + correctedFinite side (gaussianZ α) (δ side) ⟨2*j.val, by omega⟩ ∧ + (a side).finiteD j = + correctedFinite side (gaussianZ α) (δ side) ⟨2*j.val+1, by omega⟩) ∧ + (∀ side, Summable (fun n => |(a side).tailC n| + |(a side).tailD n|) ∧ + (∑' n, (|(a side).tailC n| + |(a side).tailD n|)) < (3 / 10^9 : ℝ)) ∧ + (∀ x, (f x : ℂ) = + (inputComplex (a 0) x + 𝓕 (inputComplex (a 1)) x) / + (normalizingDen (gaussianZ α) : ℂ)) + +end AtomicTriangular +end + +noncomputable section +open scoped BigOperators FourierTransform + +namespace AtomicTriangular +open Construction + +theorem sharp_gaussian_minorants_with_construction (α : ℝ) (hα : 0 < α) : + ∃ f : SchwartzMap Plane ℝ, + Radial f ∧ (∀ x, f x ≤ gaussian α x) ∧ + (∀ w, (realFourier f w).im = 0 ∧ 0 ≤ (realFourier f w).re) ∧ + (∀ a ∈ A, a ≠ 0 → f a = gaussian α a) ∧ + (∀ w ∈ dualA, w ≠ 0 → realFourier f w = 0) ∧ + (1 ≤ α → AtomicConstruction α f) := by + sorry + +end AtomicTriangular +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangularGaussian.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.AtomicTriangular.sharp_gaussian_minorants_with_construction` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangular-gaussian/solution/closure.txt b/tasks/triangular-gaussian/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..35c5e9b685f60b8334bc9cafffad830eac4efa18 --- /dev/null +++ b/tasks/triangular-gaussian/solution/closure.txt @@ -0,0 +1,216 @@ +OAI.Analysis.Triangular.Auxiliary.Bernstein +OAI.Analysis.Triangular.Auxiliary.ExponentialTail +OAI.Analysis.Triangular.Auxiliary.IntegralBounds +OAI.Analysis.Triangular.Auxiliary.MatrixNorm +OAI.Analysis.Triangular.Auxiliary.PolynomialShift +OAI.Analysis.Triangular.Basic +OAI.Analysis.Triangular.Certificate.Inverse +OAI.Analysis.Triangular.Certificate.JetMatrix +OAI.Analysis.Triangular.Certificate.MatrixInterval +OAI.Analysis.Triangular.Certificate.Param +OAI.Analysis.Triangular.Certificate.ParamA +OAI.Analysis.Triangular.Certificate.ParamActual +OAI.Analysis.Triangular.Certificate.ParamInterval +OAI.Analysis.Triangular.Certificate.ParamNorm +OAI.Analysis.Triangular.Certificate.ParamNormBase +OAI.Analysis.Triangular.Certificate.ParamRHS +OAI.Analysis.Triangular.Certificate.ParamU +OAI.Analysis.Triangular.Certificate.Polytope +OAI.Analysis.Triangular.Certificate.PolytopeInterval +OAI.Analysis.Triangular.Certificate.TargetInterval +OAI.Analysis.Triangular.Certificate.WaveExpData +OAI.Analysis.Triangular.Certificate.WaveIntervals +OAI.Analysis.Triangular.Certificate.WaveJetsData +OAI.Analysis.Triangular.Construction.ActualCorrection +OAI.Analysis.Triangular.Construction.ActualInput +OAI.Analysis.Triangular.Construction.ActualInterpolation +OAI.Analysis.Triangular.Construction.ActualTail +OAI.Analysis.Triangular.Construction.AtomicCurvature +OAI.Analysis.Triangular.Construction.BlockOperators +OAI.Analysis.Triangular.Construction.CoefficientAddition +OAI.Analysis.Triangular.Construction.ConcreteSchur +OAI.Analysis.Triangular.Construction.CurvatureAnalytic +OAI.Analysis.Triangular.Construction.CurvatureBoxes +OAI.Analysis.Triangular.Construction.CurvatureEnvelope +OAI.Analysis.Triangular.Construction.CurvatureSums +OAI.Analysis.Triangular.Construction.DirectCoordinates +OAI.Analysis.Triangular.Construction.DirectWaveJets +OAI.Analysis.Triangular.Construction.FarCurvature +OAI.Analysis.Triangular.Construction.FiniteAssembly +OAI.Analysis.Triangular.Construction.FiniteCoordinates +OAI.Analysis.Triangular.Construction.FiniteInterpolation +OAI.Analysis.Triangular.Construction.FiniteJets +OAI.Analysis.Triangular.Construction.FinitePairBridge +OAI.Analysis.Triangular.Construction.FiniteProjection +OAI.Analysis.Triangular.Construction.FiniteRemainder +OAI.Analysis.Triangular.Construction.FiniteSystem +OAI.Analysis.Triangular.Construction.FiniteTargetBridge +OAI.Analysis.Triangular.Construction.L1Kernel +OAI.Analysis.Triangular.Construction.L1Matrix +OAI.Analysis.Triangular.Construction.NodeJets +OAI.Analysis.Triangular.Construction.Normalization +OAI.Analysis.Triangular.Construction.NormalizedJets +OAI.Analysis.Triangular.Construction.PeriodicJets +OAI.Analysis.Triangular.Construction.Repetition +OAI.Analysis.Triangular.Construction.RepetitionBound +OAI.Analysis.Triangular.Construction.RepetitionOperators +OAI.Analysis.Triangular.Construction.Schur +OAI.Analysis.Triangular.Construction.SpectralJetBridge +OAI.Analysis.Triangular.Construction.SpectralProduct +OAI.Analysis.Triangular.Construction.TailCoordinates +OAI.Analysis.Triangular.Construction.TailEnumeration +OAI.Analysis.Triangular.Construction.TailInterpolation +OAI.Analysis.Triangular.Construction.TailJetVector +OAI.Analysis.Triangular.Energy.Basic +OAI.Analysis.Triangular.Energy.Mixtures +OAI.Analysis.Triangular.Envelope.Analytic +OAI.Analysis.Triangular.Envelope.Basic +OAI.Analysis.Triangular.Envelope.EnvelopeBoxes +OAI.Analysis.Triangular.Envelope.EnvelopeNorm0 +OAI.Analysis.Triangular.Envelope.EnvelopeNorm1 +OAI.Analysis.Triangular.Envelope.EnvelopeNorm2 +OAI.Analysis.Triangular.Envelope.EnvelopeNorms +OAI.Analysis.Triangular.Envelope.EnvelopePsiB +OAI.Analysis.Triangular.Envelope.EnvelopePsiC +OAI.Analysis.Triangular.Envelope.EnvelopePsiD +OAI.Analysis.Triangular.Envelope.EnvelopeSums +OAI.Analysis.Triangular.Envelope.EnvelopeSumsBase +OAI.Analysis.Triangular.Envelope.EnvelopeWaves +OAI.Analysis.Triangular.Envelope.JetEnvelopeAnalytic +OAI.Analysis.Triangular.Envelope.KernelBounds +OAI.Analysis.Triangular.Envelope.TailEnvelopeSeries +OAI.Analysis.Triangular.Envelope.TargetEnvelope +OAI.Analysis.Triangular.GaussianMinorants +OAI.Analysis.Triangular.Lattice.LatticeGeometry +OAI.Analysis.Triangular.Main +OAI.Analysis.Triangular.Schwartz.FourierCLM +OAI.Analysis.Triangular.Schwartz.FourierPair +OAI.Analysis.Triangular.Schwartz.Gaussian +OAI.Analysis.Triangular.Schwartz.GaussianPair +OAI.Analysis.Triangular.Schwartz.InputCLM +OAI.Analysis.Triangular.Schwartz.Realness +OAI.Analysis.Triangular.Schwartz.Regularity +OAI.Analysis.Triangular.Schwartz.SpectralCLM +OAI.Analysis.Triangular.Schwartz.SpectralEnvelope +OAI.Analysis.Triangular.Schwartz.TailSpectral +OAI.Analysis.Triangular.Signs.DeletedAccuracy +OAI.Analysis.Triangular.Signs.DeletedExponential +OAI.Analysis.Triangular.Signs.DeletedJets +OAI.Analysis.Triangular.Signs.DeletedQuotient +OAI.Analysis.Triangular.Signs.Exceptional +OAI.Analysis.Triangular.Signs.ExceptionalComparison +OAI.Analysis.Triangular.Signs.ExceptionalInterval +OAI.Analysis.Triangular.Signs.ExceptionalSign0 +OAI.Analysis.Triangular.Signs.ExceptionalSign1 +OAI.Analysis.Triangular.Signs.ExceptionalSign2 +OAI.Analysis.Triangular.Signs.ExceptionalSign3 +OAI.Analysis.Triangular.Signs.FarSigns +OAI.Analysis.Triangular.Signs.GaussianDeleted +OAI.Analysis.Triangular.Signs.NearSigns +OAI.Analysis.Triangular.Signs.OrdinaryComparison +OAI.Analysis.Triangular.Signs.RemainderBoxes +OAI.Analysis.Triangular.Signs.RemainderData0 +OAI.Analysis.Triangular.Signs.RemainderData1 +OAI.Analysis.Triangular.Signs.RemainderData2 +OAI.Analysis.Triangular.Signs.RemainderData3 +OAI.Analysis.Triangular.Signs.RemainderData4 +OAI.Analysis.Triangular.Signs.RemainderData5 +OAI.Analysis.Triangular.Signs.RemainderData6 +OAI.Analysis.Triangular.Signs.RemainderNorm +OAI.Analysis.Triangular.Signs.RemainderPre +OAI.Analysis.Triangular.Signs.RemainderSums0 +OAI.Analysis.Triangular.Signs.RemainderSums1 +OAI.Analysis.Triangular.Signs.RemainderSums2 +OAI.Analysis.Triangular.Signs.RemainderSums3 +OAI.Analysis.Triangular.Signs.RemainderSums4 +OAI.Analysis.Triangular.Signs.RemainderSums5 +OAI.Analysis.Triangular.Signs.RemainderSums6 +OAI.Analysis.Triangular.Signs.SignBase +OAI.Analysis.Triangular.Signs.Signs00 +OAI.Analysis.Triangular.Signs.Signs01 +OAI.Analysis.Triangular.Signs.Signs02 +OAI.Analysis.Triangular.Signs.Signs03 +OAI.Analysis.Triangular.Signs.Signs04 +OAI.Analysis.Triangular.Signs.Signs05 +OAI.Analysis.Triangular.Signs.Signs06 +OAI.Analysis.Triangular.Signs.Signs10 +OAI.Analysis.Triangular.Signs.Signs11 +OAI.Analysis.Triangular.Signs.Signs12 +OAI.Analysis.Triangular.Signs.Signs13 +OAI.Analysis.Triangular.Signs.Signs14 +OAI.Analysis.Triangular.Signs.Signs15 +OAI.Analysis.Triangular.Signs.Signs16 +OAI.Analysis.Triangular.Signs.SineBarrierBase +OAI.Analysis.Triangular.Signs.SineGlobal +OAI.Analysis.Triangular.Signs.SineGrid0 +OAI.Analysis.Triangular.Signs.SineGrid1 +OAI.Analysis.Triangular.Signs.SineGrid2 +OAI.Analysis.Triangular.Signs.SineGridAnalytic +OAI.Analysis.Triangular.Signs.SineGridChecks +OAI.Analysis.Triangular.Signs.SineGridCover +OAI.Analysis.Triangular.Signs.SineGridDefs +OAI.Analysis.Triangular.Taylor.CoefficientSpectral +OAI.Analysis.Triangular.Taylor.CurvatureData00 +OAI.Analysis.Triangular.Taylor.CurvatureData01 +OAI.Analysis.Triangular.Taylor.CurvatureData10 +OAI.Analysis.Triangular.Taylor.CurvatureData11 +OAI.Analysis.Triangular.Taylor.FiniteTaylorError +OAI.Analysis.Triangular.Taylor.FiniteTaylorIdentity +OAI.Analysis.Triangular.Taylor.Taylor +OAI.Analysis.Triangular.Taylor.TaylorExp +OAI.Analysis.Triangular.Taylor.TaylorExp00 +OAI.Analysis.Triangular.Taylor.TaylorExp01 +OAI.Analysis.Triangular.Taylor.TaylorExp10 +OAI.Analysis.Triangular.Taylor.TaylorExp11 +OAI.Analysis.Triangular.Taylor.TaylorPhase +OAI.Analysis.Triangular.Taylor.TaylorRows00 +OAI.Analysis.Triangular.Taylor.TaylorRows01 +OAI.Analysis.Triangular.Taylor.TaylorRows02 +OAI.Analysis.Triangular.Taylor.TaylorRows03 +OAI.Analysis.Triangular.Taylor.TaylorRows04 +OAI.Analysis.Triangular.Taylor.TaylorRows05 +OAI.Analysis.Triangular.Taylor.TaylorRows06 +OAI.Analysis.Triangular.Taylor.TaylorRows10 +OAI.Analysis.Triangular.Taylor.TaylorRows11 +OAI.Analysis.Triangular.Taylor.TaylorRows12 +OAI.Analysis.Triangular.Taylor.TaylorRows13 +OAI.Analysis.Triangular.Taylor.TaylorRows14 +OAI.Analysis.Triangular.Taylor.TaylorRows15 +OAI.Analysis.Triangular.Taylor.TaylorRows16 +OAI.Analysis.Triangular.Taylor.TaylorRowsBase +OAI.Analysis.Triangular.Taylor.TaylorSpectrum +OAI.Analysis.Triangular.Taylor.TaylorWave +OAI.Analysis.Triangular.Taylor.TaylorWave00 +OAI.Analysis.Triangular.Taylor.TaylorWave000 +OAI.Analysis.Triangular.Taylor.TaylorWave001 +OAI.Analysis.Triangular.Taylor.TaylorWave002 +OAI.Analysis.Triangular.Taylor.TaylorWave003 +OAI.Analysis.Triangular.Taylor.TaylorWave004 +OAI.Analysis.Triangular.Taylor.TaylorWave005 +OAI.Analysis.Triangular.Taylor.TaylorWave006 +OAI.Analysis.Triangular.Taylor.TaylorWave01 +OAI.Analysis.Triangular.Taylor.TaylorWave010 +OAI.Analysis.Triangular.Taylor.TaylorWave011 +OAI.Analysis.Triangular.Taylor.TaylorWave012 +OAI.Analysis.Triangular.Taylor.TaylorWave013 +OAI.Analysis.Triangular.Taylor.TaylorWave014 +OAI.Analysis.Triangular.Taylor.TaylorWave015 +OAI.Analysis.Triangular.Taylor.TaylorWave016 +OAI.Analysis.Triangular.Taylor.TaylorWave10 +OAI.Analysis.Triangular.Taylor.TaylorWave100 +OAI.Analysis.Triangular.Taylor.TaylorWave101 +OAI.Analysis.Triangular.Taylor.TaylorWave102 +OAI.Analysis.Triangular.Taylor.TaylorWave103 +OAI.Analysis.Triangular.Taylor.TaylorWave104 +OAI.Analysis.Triangular.Taylor.TaylorWave105 +OAI.Analysis.Triangular.Taylor.TaylorWave106 +OAI.Analysis.Triangular.Taylor.TaylorWave11 +OAI.Analysis.Triangular.Taylor.TaylorWave110 +OAI.Analysis.Triangular.Taylor.TaylorWave111 +OAI.Analysis.Triangular.Taylor.TaylorWave112 +OAI.Analysis.Triangular.Taylor.TaylorWave113 +OAI.Analysis.Triangular.Taylor.TaylorWave114 +OAI.Analysis.Triangular.Taylor.TaylorWave115 +OAI.Analysis.Triangular.Taylor.TaylorWave116 +OAI.Analysis.Triangular.Taylor.VariationBound +OAI.Analysis.Triangular.Taylor.WaveFunction diff --git a/tasks/triangular-gaussian/solution/reference.py b/tasks/triangular-gaussian/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangular-gaussian/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangular-gaussian/solution/solve.sh b/tasks/triangular-gaussian/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..3c9c031182b334d1dd0160b41a98acaf400662a7 --- /dev/null +++ b/tasks/triangular-gaussian/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangularGaussian, i.e. module OAI.Analysis.Triangular.GaussianMinorants and the +# 216 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Triangular.GaussianMinorants /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangularGaussian" diff --git a/tasks/triangular-gaussian/task.toml b/tasks/triangular-gaussian/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..763a78c2fbcdaa44fe7b1dcef958c42d849bea3f --- /dev/null +++ b/tasks/triangular-gaussian/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangular-gaussian" +version = "1.0.0" +description = "Prove TriangularGaussian (openai/math family 090: Universal optimality of the triangular lattice) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "convex-and-metric-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangularGaussian.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangularGaussian" +family = "090" +family_title = "Universal optimality of the triangular lattice" +subject = "Convex and metric geometry" +theorems = ["OAI.AtomicTriangular.sharp_gaussian_minorants_with_construction"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Triangular.GaussianMinorants" +reference_modules = 216 +reference_lean_bytes = 8531599 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 9985 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19378 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangular-gaussian/tests/Challenge.lean b/tasks/triangular-gaussian/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..43288229ab9dda9741e2984667aa851bd6b2b0ce --- /dev/null +++ b/tasks/triangular-gaussian/tests/Challenge.lean @@ -0,0 +1,275 @@ +import Mathlib + +namespace OAI + +/-! +# Sharp Gaussian minorants with atomic interpolation + +The sharp Gaussian minorants of the atomic certificate for triangular-lattice +universal optimality, including the construction for parameters at least one. +-/ + +noncomputable section +open scoped BigOperators FourierTransform SchwartzMap +open Complex Polynomial + +namespace AtomicTriangular + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def b : ℝ := Real.sqrt 3 / 2 + +def triangularPoint (jk : ℤ × ℤ) : Plane := + (Real.sqrt b)⁻¹ • + (EuclideanSpace.single 0 ((jk.1 : ℝ) + (jk.2 : ℝ) / 2) + + EuclideanSpace.single 1 ((jk.2 : ℝ) * b)) + +def A : Set Plane := Set.range triangularPoint + +def dualA : Set Plane := {w | ∀ a ∈ A, ∃ n : ℤ, inner ℝ a w = (n : ℝ)} + +def gaussian (α : ℝ) (x : Plane) : ℝ := Real.exp (-Real.pi * α * ‖x‖ ^ 2) + +def Radial (f : Plane → ℝ) : Prop := ∀ x y, ‖x‖ = ‖y‖ → f x = f y + +def realFourier (f : Plane → ℝ) (w : Plane) : ℂ := 𝓕 (fun x => (f x : ℂ)) w + +end AtomicTriangular + +namespace AtomicTriangular.Construction + +def b : ℝ := Real.sqrt 3 / 2 + +def h : ℝ := 17 / 50 + +def H : ℝ := 27 / 50 + +def eta : ℝ := 1 / 5 + +def kappa : ℝ := Real.pi / 36 + +def residues : Finset ℤ := {0,1,3,4,7,9,12,13,16,19,21,25,27,28,31} + +def residue (a : Fin 15) : ℤ := ![0,1,3,4,7,9,12,13,16,19,21,25,27,28,31] a + +def Node : Type := {n : ℤ // 0 < n ∧ n % 36 ∈ residues} + +def FiniteNodes : Finset ℤ := {1,3,4,7,9,12,13,16,19,21} + +def sineFactor (a : Fin 15) (s : ℂ) : ℂ := + 2 * Complex.sin ((kappa : ℂ) * (s - (residue a : ℂ))) + +def P (s : ℂ) : ℂ := ∏ a : Fin 15, (sineFactor a s)^2 + +def dBasis (n : Node) : ℂ → ℂ := dslope P (n.val : ℂ) + +def cBasis (n : Node) : ℂ → ℂ := dslope (dBasis n) (n.val : ℂ) + +def finiteC (a : Fin 15) (s : ℂ) : ℂ := + 4 * (kappa : ℂ)^2 * ∏ r ∈ Finset.univ.erase a, (sineFactor r s)^2 + +def finiteD (a : Fin 15) (s : ℂ) : ℂ := + 2 * (kappa : ℂ) * sineFactor a s * + Complex.cos ((kappa : ℂ) * (s - (residue a : ℂ))) * + ∏ r ∈ Finset.univ.erase a, (sineFactor r s)^2 + +def phase (s : ℂ) : ℂ := Complex.exp ((Real.pi : ℂ) * Complex.I * s / 18) + +def atomFactor (a : Fin 15) : Polynomial ℂ := + -C (phase (residue a)) + C 2 * X - C (phase (-residue a)) * X^2 + +def atomPolynomial : Polynomial ℂ := ∏ a : Fin 15, atomFactor a + +def cAtomPolynomial (a : Fin 15) : Polynomial ℂ := + C (4 * (kappa : ℂ)^2) * ∏ r ∈ Finset.univ.erase a, atomFactor r + +def dAtomPolynomial (a : Fin 15) : Polynomial ℂ := + C (Complex.I * (kappa : ℂ)) * + (C (phase (residue a)) - C (phase (-residue a)) * X^2) * + ∏ r ∈ Finset.univ.erase a, atomFactor r + +def fourierCoeff (j : Fin 31) : ℂ := atomPolynomial.coeff j.val + +def frequency (j : Fin 31) : ℝ := ((j.val : ℝ)-15)/18 + +def waveDerivative (k : ℕ) (s : ℂ) : ℂ := + ∑ j : Fin 31, fourierCoeff j * (I*Real.pi*frequency j)^k * + exp (I*Real.pi*frequency j*s) + +def Q (n : ℤ) : ℝ := (waveDerivative 2 n).re / 2 + +def D (n : ℤ) : ℝ := (waveDerivative 3 n).re / (6 * Q n) + +end AtomicTriangular.Construction + +namespace AtomicTriangular.FiniteCertificate +open Construction + +def cShiftPolynomial (a : Fin 15) : Polynomial ℂ := X * cAtomPolynomial a + +def cCoefficient (a : Fin 15) (j : Fin 31) : ℂ := (cShiftPolynomial a).coeff j.val + +def dCoefficient (a : Fin 15) (j : Fin 31) : ℂ := (dAtomPolynomial a).coeff j.val + +end AtomicTriangular.FiniteCertificate + +namespace AtomicTriangular.Construction + +abbrev Plane := EuclideanSpace ℝ (Fin 2) + +def radial (x : Plane) : ℝ := b*‖x‖^2 + +def waveDen (k t : ℝ) : ℝ := k^2+t^2 + +def Xwave (k t : ℝ) : ℝ := (4/3)/waveDen k t + +def lambda (k t : ℝ) : ℂ := ((k:ℂ)+I*t)/(b*waveDen k t : ℝ) + +def zeta (k v t : ℝ) : ℂ := -(t:ℂ)*(Xwave k t:ℂ)+I*(k*Xwave k t-v:ℝ) + +def transformedWave (k v t : ℝ) (s : ℂ) : ℂ := lambda k t*exp (I*Real.pi*zeta k v t*s) + +def finiteColumn (col : Fin 23) (j : Fin 31) : ℂ := + if hc : col.val<22 then + if col.val%2=0 then FiniteCertificate.cCoefficient ⟨col.val/2,by omega⟩ j + else FiniteCertificate.dCoefficient ⟨col.val/2,by omega⟩ j + else fourierCoeff j + +def finiteNode (n : Fin 10) : ℤ := residue ⟨n.val+1,by omega⟩ + +def jetMultiplier (k v : ℝ) (n : ℤ) (d : Fin 2) (t : ℝ) : ℂ := + (Q n:ℂ)⁻¹*transformedWave k v t n * + (if d.val=0 then -1 else (D n:ℂ)-I*Real.pi*zeta k v t) + +def jet (k v : ℝ) (n : ℤ) (d : Fin 2) (S : Fin 31 → ℂ) : ℝ := + (∑ j : Fin 31, jetMultiplier k v n d (frequency j)*S j).re + +def fullJetMatrix : Matrix (Fin 20) (Fin 23) ℝ := fun i col => + jet (if col.val=22 then h else H) H + (finiteNode ⟨i.val/2,by omega⟩) ⟨i.val%2,by omega⟩ (finiteColumn col) + +def R : Matrix (Fin 20) (Fin 20) ℝ := fun i j => fullJetMatrix i ⟨j.val+2,by omega⟩ + +def R0 : Matrix (Fin 20) (Fin 3) ℝ := fun i j => + fullJetMatrix i (if j.val<2 then ⟨j.val,by omega⟩ else 22) + +abbrev TailNode := {n : Node // n.val ∉ FiniteNodes} + +structure InputCoefficients where + C : ℝ + finiteC : Fin 11 → ℝ + finiteD : Fin 11 → ℝ + tailC : TailNode → ℝ + tailD : TailNode → ℝ + summable : Summable (fun n => |tailC n|+|tailD n|) + +def tailInput (a : InputCoefficients) (s : ℂ) : ℂ := + (a.C:ℂ)*P s + ∑' n : TailNode, ((a.tailC n:ℂ)*cBasis n.val s+(a.tailD n:ℂ)*dBasis n.val s) + +def finiteInput (a : InputCoefficients) (s : ℂ) : ℂ := + ∑ j : Fin 11, ((a.finiteC j:ℂ)*finiteC ⟨j.val,by omega⟩ s + + (a.finiteD j:ℂ)*finiteD ⟨j.val,by omega⟩ s) + +def inputComplex (a : InputCoefficients) (x : Plane) : ℂ := + exp (-(Real.pi:ℂ)*h*(radial x:ℂ))*tailInput a (radial x) + + exp (-(Real.pi:ℂ)*H*(radial x:ℂ))*finiteInput a (radial x) + +def targetCoefficient (n : Fin 10) : ℝ := Q 1 / Q (finiteNode n) * Real.exp (Real.pi*eta*(finiteNode n)) + +def Yf : Matrix (Fin 20) (Fin 8) ℝ := fun i j => + if i.val<8 then + targetCoefficient ⟨i.val/2,by omega⟩ * + (if i.val%2=0 then (if j.val=i.val then 1 else 0) + else (if j.val=i.val then -1 else if j.val=i.val-1 then Real.pi*eta-D (finiteNode ⟨i.val/2,by omega⟩) else 0)) + else 0 + +def gamma (side : Fin 2) : Matrix (Fin 3) (Fin 8) ℝ := fun i j => + if j.val=1 then (if i.val=0 then 11/25 else if i.val=1 then 0 else if side.val=0 then -(3/500) else 3/500) else 0 + +def Uplus : Matrix (Fin 20) (Fin 8) ℝ := + (1-R)⁻¹*(Yf+R0*(gamma 1+gamma 0)) + +def Uminus : Matrix (Fin 20) (Fin 8) ℝ := + (1+R)⁻¹*(Yf+R0*(gamma 1-gamma 0)) + +def finiteSolution (side : Fin 2) : Matrix (Fin 20) (Fin 8) ℝ := + if side.val=0 then (1/2:ℝ) • (Uplus+Uminus) else (1/2:ℝ) • (Uplus-Uminus) + +def Acoefficient (side : Fin 2) : Matrix (Fin 23) (Fin 8) ℝ := fun i j => + if hi : i.val<2 then gamma side ⟨i.val,by omega⟩ j + else if h22 : i.val=22 then gamma side 2 j + else finiteSolution side ⟨i.val-2,by omega⟩ j + +def gaussianZ (α : ℝ) : ℝ := 1/(Real.pi*(α/b-h)) + +def actualParameter (z : ℝ) : Fin 8 → ℝ := + ![z,1,z*Real.exp (-2/z),Real.exp (-2/z),z*Real.exp (-3/z),Real.exp (-3/z), + z*Real.exp (-6/z),Real.exp (-6/z)] + +def normalizingDen (z : ℝ) := Q 1*z*Real.exp (1/z) + +end AtomicTriangular.Construction + +end + +noncomputable section +open scoped BigOperators FourierTransform + +namespace AtomicTriangular.Construction + +def correctedFinite (side : Fin 2) (z : ℝ) (δ : Fin 20 → ℝ) (j : Fin 22) : ℝ := + (∑ r : Fin 8, Acoefficient side ⟨j.val, by omega⟩ r * actualParameter z r) + + if hj : j.val < 2 then 0 else δ ⟨j.val - 2, by omega⟩ + +end AtomicTriangular.Construction + +namespace AtomicTriangular +open Construction + +local instance finite_pair_neZero : NeZero (2 : ℕ) := inferInstance +local instance three_atLeastTwo : Nat.AtLeastTwo 3 := inferInstance +local instance ten_atLeastTwo : Nat.AtLeastTwo 10 := inferInstance +local instance five_hundred_atLeastTwo : Nat.AtLeastTwo 500 := inferInstance +local instance plane_borelSpace : BorelSpace Plane := inferInstance +local instance plane_finite : Module.Finite ℝ Plane := inferInstance + +def AtomicConstruction (α : ℝ) (f : Plane → ℝ) : Prop := + IsUnit (1 - R) ∧ IsUnit (1 + R) ∧ + (1 - R) * Uplus = Yf + R0 * (gamma 1 + gamma 0) ∧ + (1 + R) * Uminus = Yf + R0 * (gamma 1 - gamma 0) ∧ + ∃ (δ : Fin 2 → Fin 20 → ℝ) (a : Fin 2 → InputCoefficients), + (∀ side, (∑ j : Fin 20, |δ side j|) < (1 / 10^5 : ℝ)) ∧ + (∀ side, (a side).C = if side.val = 0 then -(3/500) else 3/500) ∧ + (∀ side (j : Fin 11), + (a side).finiteC j = + correctedFinite side (gaussianZ α) (δ side) ⟨2*j.val, by omega⟩ ∧ + (a side).finiteD j = + correctedFinite side (gaussianZ α) (δ side) ⟨2*j.val+1, by omega⟩) ∧ + (∀ side, Summable (fun n => |(a side).tailC n| + |(a side).tailD n|) ∧ + (∑' n, (|(a side).tailC n| + |(a side).tailD n|)) < (3 / 10^9 : ℝ)) ∧ + (∀ x, (f x : ℂ) = + (inputComplex (a 0) x + 𝓕 (inputComplex (a 1)) x) / + (normalizingDen (gaussianZ α) : ℂ)) + +end AtomicTriangular +end + +noncomputable section +open scoped BigOperators FourierTransform + +namespace AtomicTriangular +open Construction + +theorem sharp_gaussian_minorants_with_construction (α : ℝ) (hα : 0 < α) : + ∃ f : SchwartzMap Plane ℝ, + Radial f ∧ (∀ x, f x ≤ gaussian α x) ∧ + (∀ w, (realFourier f w).im = 0 ∧ 0 ≤ (realFourier f w).re) ∧ + (∀ a ∈ A, a ≠ 0 → f a = gaussian α a) ∧ + (∀ w ∈ dualA, w ≠ 0 → realFourier f w = 0) ∧ + (1 ≤ α → AtomicConstruction α f) := by + sorry + +end AtomicTriangular +end + +end OAI diff --git a/tasks/triangular-gaussian/tests/grade.py b/tasks/triangular-gaussian/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangular-gaussian/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangular-gaussian/tests/task.json b/tasks/triangular-gaussian/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9ed2445016c43ede44787ac3123af382920a6c6a --- /dev/null +++ b/tasks/triangular-gaussian/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangularGaussian", + "comparator": { + "theorem_names": [ + "OAI.AtomicTriangular.sharp_gaussian_minorants_with_construction" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18478 +} \ No newline at end of file diff --git a/tasks/triangular-gaussian/tests/test.sh b/tasks/triangular-gaussian/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangular-gaussian/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/triangular-hilbert/environment/Dockerfile b/tasks/triangular-hilbert/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/triangular-hilbert/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/triangular-hilbert/environment/fetch_mathlib.sh b/tasks/triangular-hilbert/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/triangular-hilbert/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/triangular-hilbert/environment/lake-manifest.json b/tasks/triangular-hilbert/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/triangular-hilbert/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/triangular-hilbert/environment/lakefile.lean b/tasks/triangular-hilbert/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/triangular-hilbert/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/triangular-hilbert/environment/lean_setup.sh b/tasks/triangular-hilbert/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/triangular-hilbert/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/triangular-hilbert/environment/pack_submission.py b/tasks/triangular-hilbert/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/triangular-hilbert/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/triangular-hilbert/instruction.md b/tasks/triangular-hilbert/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..49183b28cdb8fcc977c0138188fe9e70078007a4 --- /dev/null +++ b/tasks/triangular-hilbert/instruction.md @@ -0,0 +1,108 @@ +# openai/math challenge `TriangularHilbert` (family 082) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 082 of the release, *Maximal and variational bounds for the triangular Hilbert transform* +(Real and complex analysis). The family as a whole: Proves maximal and annular $r$-variation bounds, for every $r>2$, from complex $L^3(\mathbb R^2)\times L^3(\mathbb R^2)$ to $L^{3/2}(\mathbb R^2)$. The maximal estimate controls both hard truncation endpoints and gives almost-everywhere and norm convergence. Pairing with a third input settles the triangular Hilbert transform estimate at the symmetric $L^3\times L^3\times L^3$ point. + +The challenge is `TriangularHilbert`, also at `/opt/openai-math/challenges/TriangularHilbert.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped ENNReal NNReal + +namespace TriangularHilbert + +abbrev Plane := ℝ × ℝ + +structure Endpoints where + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + lower_lt_upper : lower < upper + +def annulus (ε R : ℝ) : Set ℝ := {t | ε < |t| ∧ |t| < R} + +def integrand (F G : Plane → ℂ) (z : Plane) (t : ℝ) : ℂ := + F (z.1 + t, z.2) * G (z.1, z.2 + t) / (t : ℂ) + +def truncation (F G : Plane → ℂ) (E : Endpoints) (z : Plane) : ℂ := + ∫ t in annulus E.lower E.upper, integrand F G z t + +def GoodPoint (F G : Plane → ℂ) (z : Plane) : Prop := + ∀ n : ℕ, IntegrableOn (integrand F G z) + (annulus (1 / ((n : ℝ) + 2)) ((n : ℝ) + 2)) + +def maximal (F G : Plane → ℂ) (z : Plane) : ℝ≥0∞ := by + classical + exact if GoodPoint F G z then + ⨆ E : Endpoints, ENNReal.ofReal ‖truncation F G E z‖ else 0 + +def maximalNorm (F G : Plane → ℂ) : ℝ≥0∞ := + (∫⁻ z : Plane, maximal F G z ^ ((3 : ℝ) / 2)) ^ ((2 : ℝ) / 3) + +def MainEstimate : Prop := + ∃ C : ℝ≥0, ∀ F G : Plane → ℂ, + MemLp F 3 volume → MemLp G 3 volume → + (∀ᵐ z ∂volume, GoodPoint F G z) ∧ + AEMeasurable (maximal F G) volume ∧ + maximalNorm F G ≤ (C : ℝ≥0∞) * eLpNorm F 3 volume * eLpNorm G 3 volume + +open MeasureTheory Filter +open scoped ENNReal + +theorem main_estimate : MainEstimate := by + sorry + +end TriangularHilbert + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TriangularHilbert.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TriangularHilbert.main_estimate` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/triangular-hilbert/solution/closure.txt b/tasks/triangular-hilbert/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..7d8ead0cedd6e6f47e13cef2a61bc97554c25867 --- /dev/null +++ b/tasks/triangular-hilbert/solution/closure.txt @@ -0,0 +1,105 @@ +OAI.Analysis.TriangularHilbert.AbsCost +OAI.Analysis.TriangularHilbert.BoundedBox +OAI.Analysis.TriangularHilbert.CompactMoment +OAI.Analysis.TriangularHilbert.ContinuumMesh +OAI.Analysis.TriangularHilbert.Coordinates +OAI.Analysis.TriangularHilbert.CostBlock +OAI.Analysis.TriangularHilbert.CubicApprox +OAI.Analysis.TriangularHilbert.CubicLimit +OAI.Analysis.TriangularHilbert.CubicProduct +OAI.Analysis.TriangularHilbert.CyclicCompact +OAI.Analysis.TriangularHilbert.CyclicDensity +OAI.Analysis.TriangularHilbert.CyclicHomogeneity +OAI.Analysis.TriangularHilbert.CyclicMaxMoment +OAI.Analysis.TriangularHilbert.CyclicMeasurable +OAI.Analysis.TriangularHilbert.CyclicNorm +OAI.Analysis.TriangularHilbert.CyclicSlice +OAI.Analysis.TriangularHilbert.DiscreteMax +OAI.Analysis.TriangularHilbert.DiscretePairing +OAI.Analysis.TriangularHilbert.DissipationAlgebra +OAI.Analysis.TriangularHilbert.EndpointContinuity +OAI.Analysis.TriangularHilbert.ErrorEnvelope +OAI.Analysis.TriangularHilbert.ErrorPairing +OAI.Analysis.TriangularHilbert.FiniteAbel +OAI.Analysis.TriangularHilbert.FiniteDual +OAI.Analysis.TriangularHilbert.FiniteLineMax +OAI.Analysis.TriangularHilbert.FiniteMoment +OAI.Analysis.TriangularHilbert.FiniteVitali +OAI.Analysis.TriangularHilbert.Gaussian +OAI.Analysis.TriangularHilbert.GaussianConvolution +OAI.Analysis.TriangularHilbert.GaussianDom +OAI.Analysis.TriangularHilbert.GaussianExpectation +OAI.Analysis.TriangularHilbert.GaussianGram +OAI.Analysis.TriangularHilbert.GaussianMax +OAI.Analysis.TriangularHilbert.GaussianMoments +OAI.Analysis.TriangularHilbert.GaussianRadial +OAI.Analysis.TriangularHilbert.GaussianTriple +OAI.Analysis.TriangularHilbert.GramDeriv +OAI.Analysis.TriangularHilbert.GridCell +OAI.Analysis.TriangularHilbert.GridLine +OAI.Analysis.TriangularHilbert.GroupedGaussian +OAI.Analysis.TriangularHilbert.HardPairing +OAI.Analysis.TriangularHilbert.HardScalar +OAI.Analysis.TriangularHilbert.HeatBound +OAI.Analysis.TriangularHilbert.HeatContinuous +OAI.Analysis.TriangularHilbert.HeatCost +OAI.Analysis.TriangularHilbert.HeatInsert +OAI.Analysis.TriangularHilbert.HeatStar +OAI.Analysis.TriangularHilbert.HeatTime +OAI.Analysis.TriangularHilbert.InitialAlgebra +OAI.Analysis.TriangularHilbert.InitialPlane +OAI.Analysis.TriangularHilbert.IntMax +OAI.Analysis.TriangularHilbert.IntStrong +OAI.Analysis.TriangularHilbert.IntWeak +OAI.Analysis.TriangularHilbert.IntegratedDissipation +OAI.Analysis.TriangularHilbert.IntervalMask +OAI.Analysis.TriangularHilbert.JointHeat +OAI.Analysis.TriangularHilbert.JointInsert +OAI.Analysis.TriangularHilbert.JointMeasurable +OAI.Analysis.TriangularHilbert.JumpScalar +OAI.Analysis.TriangularHilbert.Main +OAI.Analysis.TriangularHilbert.MaskedActual +OAI.Analysis.TriangularHilbert.MaskedDissipation +OAI.Analysis.TriangularHilbert.MassPlane +OAI.Analysis.TriangularHilbert.MatrixSupport +OAI.Analysis.TriangularHilbert.MeshFinite +OAI.Analysis.TriangularHilbert.MeshJump +OAI.Analysis.TriangularHilbert.MeshMass +OAI.Analysis.TriangularHilbert.Model +OAI.Analysis.TriangularHilbert.MomentPower +OAI.Analysis.TriangularHilbert.NormBounds +OAI.Analysis.TriangularHilbert.PlaneChart +OAI.Analysis.TriangularHilbert.PlaneDissipation +OAI.Analysis.TriangularHilbert.PlaneDom +OAI.Analysis.TriangularHilbert.PlaneIntegral +OAI.Analysis.TriangularHilbert.PlaneInterval +OAI.Analysis.TriangularHilbert.PlaneTime +OAI.Analysis.TriangularHilbert.Quantization +OAI.Analysis.TriangularHilbert.RankJump +OAI.Analysis.TriangularHilbert.RationalSup +OAI.Analysis.TriangularHilbert.SampledConvergence +OAI.Analysis.TriangularHilbert.SampledMoment +OAI.Analysis.TriangularHilbert.SampledOutput +OAI.Analysis.TriangularHilbert.SelectedScale +OAI.Analysis.TriangularHilbert.SignedCenter +OAI.Analysis.TriangularHilbert.SignedConvolution +OAI.Analysis.TriangularHilbert.SignedExpansion +OAI.Analysis.TriangularHilbert.SignedTraceOrder +OAI.Analysis.TriangularHilbert.SignedWindowScalar +OAI.Analysis.TriangularHilbert.SmoothFormula +OAI.Analysis.TriangularHilbert.SortedWindows +OAI.Analysis.TriangularHilbert.StarInsertion +OAI.Analysis.TriangularHilbert.StarJump +OAI.Analysis.TriangularHilbert.StarNorm +OAI.Analysis.TriangularHilbert.StrongLayer +OAI.Analysis.TriangularHilbert.Support +OAI.Analysis.TriangularHilbert.Switch +OAI.Analysis.TriangularHilbert.TotalJump +OAI.Analysis.TriangularHilbert.TraceWeights +OAI.Analysis.TriangularHilbert.TruncationCoordinates +OAI.Analysis.TriangularHilbert.WeightSlice +OAI.Analysis.TriangularHilbert.WeightedCompare +OAI.Analysis.TriangularHilbert.WeightedCubic +OAI.Analysis.TriangularHilbert.WeightedGram +OAI.Analysis.TriangularHilbert.WeightedStar +OAI.Analysis.TriangularHilbert.ZeroStar diff --git a/tasks/triangular-hilbert/solution/reference.py b/tasks/triangular-hilbert/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/triangular-hilbert/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/triangular-hilbert/solution/solve.sh b/tasks/triangular-hilbert/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..bae26eb45ba7d0a14bfc5a239c66ac293c70c6ec --- /dev/null +++ b/tasks/triangular-hilbert/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TriangularHilbert, i.e. module OAI.Analysis.TriangularHilbert.Main and the +# 105 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.TriangularHilbert.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TriangularHilbert" diff --git a/tasks/triangular-hilbert/task.toml b/tasks/triangular-hilbert/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..b35d9cf3a773437adc23990b0994a39a186e7f3f --- /dev/null +++ b/tasks/triangular-hilbert/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/triangular-hilbert" +version = "1.0.0" +description = "Prove TriangularHilbert (openai/math family 082: Maximal and variational bounds for the triangular Hilbert transform) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "real-and-complex-analysis"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TriangularHilbert.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TriangularHilbert" +family = "082" +family_title = "Maximal and variational bounds for the triangular Hilbert transform" +subject = "Real and complex analysis" +theorems = ["OAI.TriangularHilbert.main_estimate"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.TriangularHilbert.Main" +reference_modules = 105 +reference_lean_bytes = 499653 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 630 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12149 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/triangular-hilbert/tests/Challenge.lean b/tasks/triangular-hilbert/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..121c1dfb1f0d8c3642c43851ed559800b67c2c04 --- /dev/null +++ b/tasks/triangular-hilbert/tests/Challenge.lean @@ -0,0 +1,57 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open MeasureTheory +open scoped ENNReal NNReal + +namespace TriangularHilbert + +abbrev Plane := ℝ × ℝ + +structure Endpoints where + lower : ℝ + upper : ℝ + lower_pos : 0 < lower + lower_lt_upper : lower < upper + +def annulus (ε R : ℝ) : Set ℝ := {t | ε < |t| ∧ |t| < R} + +def integrand (F G : Plane → ℂ) (z : Plane) (t : ℝ) : ℂ := + F (z.1 + t, z.2) * G (z.1, z.2 + t) / (t : ℂ) + +def truncation (F G : Plane → ℂ) (E : Endpoints) (z : Plane) : ℂ := + ∫ t in annulus E.lower E.upper, integrand F G z t + +def GoodPoint (F G : Plane → ℂ) (z : Plane) : Prop := + ∀ n : ℕ, IntegrableOn (integrand F G z) + (annulus (1 / ((n : ℝ) + 2)) ((n : ℝ) + 2)) + +def maximal (F G : Plane → ℂ) (z : Plane) : ℝ≥0∞ := by + classical + exact if GoodPoint F G z then + ⨆ E : Endpoints, ENNReal.ofReal ‖truncation F G E z‖ else 0 + +def maximalNorm (F G : Plane → ℂ) : ℝ≥0∞ := + (∫⁻ z : Plane, maximal F G z ^ ((3 : ℝ) / 2)) ^ ((2 : ℝ) / 3) + +def MainEstimate : Prop := + ∃ C : ℝ≥0, ∀ F G : Plane → ℂ, + MemLp F 3 volume → MemLp G 3 volume → + (∀ᵐ z ∂volume, GoodPoint F G z) ∧ + AEMeasurable (maximal F G) volume ∧ + maximalNorm F G ≤ (C : ℝ≥0∞) * eLpNorm F 3 volume * eLpNorm G 3 volume + +open MeasureTheory Filter +open scoped ENNReal + +theorem main_estimate : MainEstimate := by + sorry + +end TriangularHilbert + +end + +end OAI diff --git a/tasks/triangular-hilbert/tests/grade.py b/tasks/triangular-hilbert/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/triangular-hilbert/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/triangular-hilbert/tests/task.json b/tasks/triangular-hilbert/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..5374bf276711b065dfa8346d88de6da0f0a34f50 --- /dev/null +++ b/tasks/triangular-hilbert/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TriangularHilbert", + "comparator": { + "theorem_names": [ + "OAI.TriangularHilbert.main_estimate" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11249 +} \ No newline at end of file diff --git a/tasks/triangular-hilbert/tests/test.sh b/tasks/triangular-hilbert/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/triangular-hilbert/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/truffet-counterexample/environment/Dockerfile b/tasks/truffet-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/truffet-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/truffet-counterexample/environment/fetch_mathlib.sh b/tasks/truffet-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/truffet-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/truffet-counterexample/environment/lake-manifest.json b/tasks/truffet-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/truffet-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/truffet-counterexample/environment/lakefile.lean b/tasks/truffet-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/truffet-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/truffet-counterexample/environment/lean_setup.sh b/tasks/truffet-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/truffet-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/truffet-counterexample/environment/pack_submission.py b/tasks/truffet-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/truffet-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/truffet-counterexample/instruction.md b/tasks/truffet-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c0c9daf3676f3f7622b627e70be22830d3f3f0a3 --- /dev/null +++ b/tasks/truffet-counterexample/instruction.md @@ -0,0 +1,185 @@ +# openai/math challenge `TruffetCounterexample` (family 104) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 104 of the release, *Quasipolynomial algorithms for mean-payoff, stochastic and parity games* +(Theoretical computer science). The family as a whole: Gives deterministic algorithms using $2^{O((\log(L+2))^2)}$ bit operations, for complete binary input length $L$, for ordinary mean-payoff games and two separate extensions. They compute exact values and optimal positional strategies in ordinary games, the nonnegative expectation-of-liminf value set in turn-based stochastic games, and the winning set for nonnegative liminf mean payoff conjoined with parity. Signed rewards, rational chance probabilities, and parity priorities are unrestricted and binary-encoded. + +The challenge is `TruffetCounterexample`, also at `/opt/openai-math/challenges/TruffetCounterexample.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +namespace TruffetV4Counterexample + +abbrev Coeff := WithBot ℝ + +abbrev Form := Fin 3 → Coeff + +abbrev Var := Fin 2 + +abbrev RowIndex := Fin 2 + +def column (j : Var) : Fin 3 := ⟨j.val, Nat.lt_trans j.isLt (by decide)⟩ + +def nullForm : Form := fun _ => ⊥ + +structure Row where + lhs : Form + rhs : Form + +structure State where + rows : RowIndex → Row + cost : Form + remaining : Var → Prop + +def wellFormed (s : State) : Prop := ∀ j, ¬ s.remaining j → + s.cost (column j) = ⊥ ∧ ∀ i, + (s.rows i).lhs (column j) = ⊥ ∧ (s.rows i).rhs (column j) = ⊥ + +def eval (f : Form) (w : Fin 3 → ℝ) : Coeff := + max (f 0 + (w 0 : Coeff)) (max (f 1 + (w 1 : Coeff)) (f 2 + (w 2 : Coeff))) + +def feasible (s : State) (w : Fin 3 → ℝ) : Prop := + ∀ i, eval (s.rows i).rhs w ≤ eval (s.rows i).lhs w + +def lower (s : State) (i : RowIndex) (j : Var) : Prop := + (s.rows i).lhs (column j) ≠ ⊥ ∧ + (s.rows i).rhs (column j) < (s.rows i).lhs (column j) + +def upper (s : State) (i : RowIndex) (j : Var) : Prop := + (s.rows i).rhs (column j) ≠ ⊥ ∧ + (s.rows i).lhs (column j) < (s.rows i).rhs (column j) + +def dominating (s : State) (j : Var) : Prop := + s.remaining j ∧ (∃ i, lower s i j) ∧ ∃ i, upper s i j + +def eligible (s : State) (i : RowIndex) (j : Var) : Prop := + s.remaining j ∧ lower s i j ∧ ((∃ k, dominating s k) → dominating s j) + +def bounded (s : State) : Prop := + ∀ j, s.remaining j → (∃ i, lower s i j) ∨ ∃ i, upper s i j + +def stop (s : State) : Prop := ∀ i, (s.rows i).rhs 2 ≤ (s.rows i).lhs 2 + +def switch (s : State) : Prop := + (∀ j, s.remaining j → s.cost (column j) = ⊥) ∧ ¬ stop s ∧ + (∃ j, s.remaining j) ∧ + (¬ ∃ i j, s.remaining j ∧ lower s i j) ∧ + ∃ i j, s.remaining j ∧ upper s i j + +def failure (s : State) : Prop := ¬ stop s ∧ + ((¬ ∃ j, s.remaining j) ∨ + ((¬ ∃ i j, s.remaining j ∧ lower s i j) ∧ + (¬ ∃ i j, s.remaining j ∧ upper s i j))) + +def lowerForm (s : State) (i : RowIndex) (j : Var) : Form := fun k => + if k = column j then ⊥ else + (s.rows i).rhs k + ((-WithBot.unbotD 0 ((s.rows i).lhs (column j)) : ℝ) : Coeff) + +def substitute (f : Form) (j : Var) (g : Form) : Form := fun k => + if k = column j then ⊥ else max (f k) (f (column j) + g k) + +def cleanup (r : Row) : Row := by + classical + exact if ∀ k, r.rhs k ≤ r.lhs k then ⟨nullForm, nullForm⟩ else r + +def advance (s : State) (i : RowIndex) (j : Var) : State where + rows := fun r => cleanup ⟨substitute (s.rows r).lhs j (lowerForm s i j), + substitute (s.rows r).rhs j (lowerForm s i j)⟩ + cost := substitute s.cost j (lowerForm s i j) + remaining := fun k => s.remaining k ∧ k ≠ j + +def ForcedSingletonStep (s s' : State) (i : RowIndex) (j : Var) : Prop := + wellFormed s ∧ wellFormed s' ∧ + bounded s ∧ ¬ stop s ∧ ¬ switch s ∧ ¬ failure s ∧ + (∀ r k, eligible s r k ↔ r = i ∧ k = j) ∧ + (∃ k, (substitute s.cost j (lowerForm s i j)) k ≠ ⊥) ∧ + s' = advance s i j + +def initial : State where + rows := ![⟨![(0 : Coeff), 0, ⊥], ![⊥, ⊥, (0 : Coeff)]⟩, + ⟨![(0 : Coeff), ⊥, ⊥], ![⊥, (1 : Coeff), ((-2 : ℝ) : Coeff)]⟩] + cost := ![(0 : Coeff), ⊥, ⊥] + remaining := fun _ => True + +def middle : State where + rows := ![⟨nullForm, nullForm⟩, + ⟨![(0 : Coeff), ⊥, ⊥], ![⊥, ⊥, (1 : Coeff)]⟩] + cost := ![(0 : Coeff), ⊥, ⊥] + remaining := fun j => j = 0 + +def finalState : State where + rows := fun _ => ⟨nullForm, nullForm⟩ + cost := ![⊥, ⊥, (1 : Coeff)] + remaining := fun _ => False + +def crossRowRestriction (s : State) : Prop := + ∀ i r : RowIndex, i ≠ r → ∀ α : ℝ, ∃ w : Fin 3 → ℝ, + eval (s.rows i).lhs w < (α : Coeff) + eval (s.rows r).rhs w + +def output : Fin 3 → ℝ := ![1, 0, 0] + +def better : Fin 3 → ℝ := ![0, -1, 0] + +theorem finite_execution_not_optimal : + crossRowRestriction initial ∧ + ForcedSingletonStep initial middle 0 1 ∧ + ForcedSingletonStep middle finalState 1 0 ∧ + (¬ ∃ j, finalState.remaining j) ∧ stop finalState ∧ + feasible initial output ∧ feasible initial better ∧ + output 2 = 0 ∧ better 2 = 0 ∧ + (output 1 : Coeff) = eval (lowerForm initial 0 1) output ∧ + (output 0 : Coeff) = eval (lowerForm middle 1 0) output ∧ + eval initial.cost output = eval finalState.cost output ∧ + eval initial.cost better < eval finalState.cost output := by + sorry + +end TruffetV4Counterexample +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TruffetCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TruffetV4Counterexample.finite_execution_not_optimal` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/truffet-counterexample/solution/closure.txt b/tasks/truffet-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..8c10ba667dfb8bec3762ed1230a7ccb411f8221e --- /dev/null +++ b/tasks/truffet-counterexample/solution/closure.txt @@ -0,0 +1,2 @@ +OAI.Optimization.Tropical.TruffetCounterexample +OAI.Optimization.Tropical.TruffetModel diff --git a/tasks/truffet-counterexample/solution/reference.py b/tasks/truffet-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/truffet-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/truffet-counterexample/solution/solve.sh b/tasks/truffet-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..989121f54dab30bc5f84375b8b1e2bb01ca61b35 --- /dev/null +++ b/tasks/truffet-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TruffetCounterexample, i.e. module OAI.Optimization.Tropical.TruffetCounterexample and the +# 2 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Optimization.Tropical.TruffetCounterexample /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TruffetCounterexample" diff --git a/tasks/truffet-counterexample/task.toml b/tasks/truffet-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..f283365fcd24b6d7c3c6e089218fe082d7078f12 --- /dev/null +++ b/tasks/truffet-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/truffet-counterexample" +version = "1.0.0" +description = "Prove TruffetCounterexample (openai/math family 104: Quasipolynomial algorithms for mean-payoff, stochastic and parity games) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TruffetCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TruffetCounterexample" +family = "104" +family_title = "Quasipolynomial algorithms for mean-payoff, stochastic and parity games" +subject = "Theoretical computer science" +theorems = ["OAI.TruffetV4Counterexample.finite_execution_not_optimal"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Optimization.Tropical.TruffetCounterexample" +reference_modules = 2 +reference_lean_bytes = 11050 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 68 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11709 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/truffet-counterexample/tests/Challenge.lean b/tasks/truffet-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..3eb883a84951d236945dd5aa4c66b4d641619c38 --- /dev/null +++ b/tasks/truffet-counterexample/tests/Challenge.lean @@ -0,0 +1,134 @@ +import Mathlib + +namespace OAI + +noncomputable section +namespace TruffetV4Counterexample + +abbrev Coeff := WithBot ℝ + +abbrev Form := Fin 3 → Coeff + +abbrev Var := Fin 2 + +abbrev RowIndex := Fin 2 + +def column (j : Var) : Fin 3 := ⟨j.val, Nat.lt_trans j.isLt (by decide)⟩ + +def nullForm : Form := fun _ => ⊥ + +structure Row where + lhs : Form + rhs : Form + +structure State where + rows : RowIndex → Row + cost : Form + remaining : Var → Prop + +def wellFormed (s : State) : Prop := ∀ j, ¬ s.remaining j → + s.cost (column j) = ⊥ ∧ ∀ i, + (s.rows i).lhs (column j) = ⊥ ∧ (s.rows i).rhs (column j) = ⊥ + +def eval (f : Form) (w : Fin 3 → ℝ) : Coeff := + max (f 0 + (w 0 : Coeff)) (max (f 1 + (w 1 : Coeff)) (f 2 + (w 2 : Coeff))) + +def feasible (s : State) (w : Fin 3 → ℝ) : Prop := + ∀ i, eval (s.rows i).rhs w ≤ eval (s.rows i).lhs w + +def lower (s : State) (i : RowIndex) (j : Var) : Prop := + (s.rows i).lhs (column j) ≠ ⊥ ∧ + (s.rows i).rhs (column j) < (s.rows i).lhs (column j) + +def upper (s : State) (i : RowIndex) (j : Var) : Prop := + (s.rows i).rhs (column j) ≠ ⊥ ∧ + (s.rows i).lhs (column j) < (s.rows i).rhs (column j) + +def dominating (s : State) (j : Var) : Prop := + s.remaining j ∧ (∃ i, lower s i j) ∧ ∃ i, upper s i j + +def eligible (s : State) (i : RowIndex) (j : Var) : Prop := + s.remaining j ∧ lower s i j ∧ ((∃ k, dominating s k) → dominating s j) + +def bounded (s : State) : Prop := + ∀ j, s.remaining j → (∃ i, lower s i j) ∨ ∃ i, upper s i j + +def stop (s : State) : Prop := ∀ i, (s.rows i).rhs 2 ≤ (s.rows i).lhs 2 + +def switch (s : State) : Prop := + (∀ j, s.remaining j → s.cost (column j) = ⊥) ∧ ¬ stop s ∧ + (∃ j, s.remaining j) ∧ + (¬ ∃ i j, s.remaining j ∧ lower s i j) ∧ + ∃ i j, s.remaining j ∧ upper s i j + +def failure (s : State) : Prop := ¬ stop s ∧ + ((¬ ∃ j, s.remaining j) ∨ + ((¬ ∃ i j, s.remaining j ∧ lower s i j) ∧ + (¬ ∃ i j, s.remaining j ∧ upper s i j))) + +def lowerForm (s : State) (i : RowIndex) (j : Var) : Form := fun k => + if k = column j then ⊥ else + (s.rows i).rhs k + ((-WithBot.unbotD 0 ((s.rows i).lhs (column j)) : ℝ) : Coeff) + +def substitute (f : Form) (j : Var) (g : Form) : Form := fun k => + if k = column j then ⊥ else max (f k) (f (column j) + g k) + +def cleanup (r : Row) : Row := by + classical + exact if ∀ k, r.rhs k ≤ r.lhs k then ⟨nullForm, nullForm⟩ else r + +def advance (s : State) (i : RowIndex) (j : Var) : State where + rows := fun r => cleanup ⟨substitute (s.rows r).lhs j (lowerForm s i j), + substitute (s.rows r).rhs j (lowerForm s i j)⟩ + cost := substitute s.cost j (lowerForm s i j) + remaining := fun k => s.remaining k ∧ k ≠ j + +def ForcedSingletonStep (s s' : State) (i : RowIndex) (j : Var) : Prop := + wellFormed s ∧ wellFormed s' ∧ + bounded s ∧ ¬ stop s ∧ ¬ switch s ∧ ¬ failure s ∧ + (∀ r k, eligible s r k ↔ r = i ∧ k = j) ∧ + (∃ k, (substitute s.cost j (lowerForm s i j)) k ≠ ⊥) ∧ + s' = advance s i j + +def initial : State where + rows := ![⟨![(0 : Coeff), 0, ⊥], ![⊥, ⊥, (0 : Coeff)]⟩, + ⟨![(0 : Coeff), ⊥, ⊥], ![⊥, (1 : Coeff), ((-2 : ℝ) : Coeff)]⟩] + cost := ![(0 : Coeff), ⊥, ⊥] + remaining := fun _ => True + +def middle : State where + rows := ![⟨nullForm, nullForm⟩, + ⟨![(0 : Coeff), ⊥, ⊥], ![⊥, ⊥, (1 : Coeff)]⟩] + cost := ![(0 : Coeff), ⊥, ⊥] + remaining := fun j => j = 0 + +def finalState : State where + rows := fun _ => ⟨nullForm, nullForm⟩ + cost := ![⊥, ⊥, (1 : Coeff)] + remaining := fun _ => False + +def crossRowRestriction (s : State) : Prop := + ∀ i r : RowIndex, i ≠ r → ∀ α : ℝ, ∃ w : Fin 3 → ℝ, + eval (s.rows i).lhs w < (α : Coeff) + eval (s.rows r).rhs w + +def output : Fin 3 → ℝ := ![1, 0, 0] + +def better : Fin 3 → ℝ := ![0, -1, 0] + +theorem finite_execution_not_optimal : + crossRowRestriction initial ∧ + ForcedSingletonStep initial middle 0 1 ∧ + ForcedSingletonStep middle finalState 1 0 ∧ + (¬ ∃ j, finalState.remaining j) ∧ stop finalState ∧ + feasible initial output ∧ feasible initial better ∧ + output 2 = 0 ∧ better 2 = 0 ∧ + (output 1 : Coeff) = eval (lowerForm initial 0 1) output ∧ + (output 0 : Coeff) = eval (lowerForm middle 1 0) output ∧ + eval initial.cost output = eval finalState.cost output ∧ + eval initial.cost better < eval finalState.cost output := by + sorry + +end TruffetV4Counterexample +end + +end OAI diff --git a/tasks/truffet-counterexample/tests/grade.py b/tasks/truffet-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/truffet-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/truffet-counterexample/tests/task.json b/tasks/truffet-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..60811c6d28455a226cf39be8de1af4de0d7e4f62 --- /dev/null +++ b/tasks/truffet-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TruffetCounterexample", + "comparator": { + "theorem_names": [ + "OAI.TruffetV4Counterexample.finite_execution_not_optimal" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 10809 +} \ No newline at end of file diff --git a/tasks/truffet-counterexample/tests/test.sh b/tasks/truffet-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/truffet-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/two-way-complementation/environment/Dockerfile b/tasks/two-way-complementation/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/two-way-complementation/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/two-way-complementation/environment/fetch_mathlib.sh b/tasks/two-way-complementation/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/two-way-complementation/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/two-way-complementation/environment/lake-manifest.json b/tasks/two-way-complementation/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/two-way-complementation/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/two-way-complementation/environment/lakefile.lean b/tasks/two-way-complementation/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/two-way-complementation/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/two-way-complementation/environment/lean_setup.sh b/tasks/two-way-complementation/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/two-way-complementation/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/two-way-complementation/environment/pack_submission.py b/tasks/two-way-complementation/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/two-way-complementation/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/two-way-complementation/instruction.md b/tasks/two-way-complementation/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..52e68f709d8d1d04c34580429ae0b13732a4b77f --- /dev/null +++ b/tasks/two-way-complementation/instruction.md @@ -0,0 +1,96 @@ +# openai/math challenge `TwoWayComplementation` (family 129) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 129 of the release, *Exponential state costs for two-way automata* +(Theoretical computer science). The family as a whole: Proves exponential lower bounds both for complementing two-way nondeterministic finite automata and for simulating one-way nondeterministic automata by two-way deterministic ones. The latter resolves the Sakoda–Sipser state-succinctness conjecture over growing finite alphabets; both results rule out polynomial state bounds independent of alphabet size. + +The challenge is `TwoWayComplementation`, also at `/opt/openai-math/challenges/TwoWayComplementation.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TwoWayComplementation + +open scoped SetRel + +def relStar {α : Type*} (R : SetRel α α) : SetRel α α := + {(x, y) | Relation.ReflTransGen (fun a b => (a, b) ∈ R) x y} + +structure TwoNFA (Sigma Q : Type*) where + initial : Q + accepting : Set Q + transition : Q → (Fin 2 ⊕ Sigma) → Set (Q × Fin 3) + +def tapeSymbol {Sigma : Type*} (w : List Sigma) (p : Fin (w.length + 2)) : Fin 2 ⊕ Sigma := + if hleft : p.val = 0 then .inl 0 + else if hright : p.val = w.length + 1 then .inl 1 + else .inr (w[p.val - 1]'(by omega)) + +namespace TwoNFA + +def step {Sigma Q : Type*} (A : TwoNFA Sigma Q) (w : List Sigma) : + SetRel (Q × Fin (w.length + 2)) (Q × Fin (w.length + 2)) := + {(c, d) | ∃ move : Fin 3, + (d.1, move) ∈ A.transition c.1 (tapeSymbol w c.2) ∧ + (d.2.val : ℤ) = (c.2.val : ℤ) + (move.val : ℤ) - 1} + +def language {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Set (List Sigma) := + {w | ∃ c, c.1 ∈ A.accepting ∧ + ((A.initial, ⟨0, by omega⟩), c) ∈ relStar (A.step w)} + +end TwoNFA + +theorem complementation_lower_bound_finite (n : ℕ) (hn : 4 ≤ n) : + ∃ A : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) (Fin n), + ∀ (Q : Type*) [Fintype Q], ∀ B : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + B.language = A.languageᶜ → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) - 1 ≤ (Fintype.card Q : ℝ) := by + sorry + +end TwoWayComplementation + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TwoWayComplementation.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TwoWayComplementation.complementation_lower_bound_finite` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/two-way-complementation/solution/closure.txt b/tasks/two-way-complementation/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dc0a81e884c4d3593fe6775c6ab4c346a0f09e45 --- /dev/null +++ b/tasks/two-way-complementation/solution/closure.txt @@ -0,0 +1,19 @@ +OAI.Combinatorics.TwoWayAutomata.Amplification +OAI.Combinatorics.TwoWayAutomata.Chain +OAI.Combinatorics.TwoWayAutomata.Classes +OAI.Combinatorics.TwoWayAutomata.Corners +OAI.Combinatorics.TwoWayAutomata.Diagram +OAI.Combinatorics.TwoWayAutomata.ImageBound +OAI.Combinatorics.TwoWayAutomata.Main +OAI.Combinatorics.TwoWayAutomata.Model +OAI.Combinatorics.TwoWayAutomata.Nesting +OAI.Combinatorics.TwoWayAutomata.Network +OAI.Combinatorics.TwoWayAutomata.Normalization +OAI.Combinatorics.TwoWayAutomata.Recognition +OAI.Combinatorics.TwoWayAutomata.RelationMonoid +OAI.Combinatorics.TwoWayAutomata.Relations +OAI.Combinatorics.TwoWayAutomata.Representation +OAI.Combinatorics.TwoWayAutomata.Retained +OAI.Combinatorics.TwoWayAutomata.Source +OAI.Combinatorics.TwoWayAutomata.Tape +OAI.Combinatorics.TwoWayAutomata.Transport diff --git a/tasks/two-way-complementation/solution/reference.py b/tasks/two-way-complementation/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/two-way-complementation/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/two-way-complementation/solution/solve.sh b/tasks/two-way-complementation/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2ecd5d74699ba5ed17cd8281827bece3b8fb9381 --- /dev/null +++ b/tasks/two-way-complementation/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TwoWayComplementation, i.e. module OAI.Combinatorics.TwoWayAutomata.Main and the +# 19 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TwoWayAutomata.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TwoWayComplementation" diff --git a/tasks/two-way-complementation/task.toml b/tasks/two-way-complementation/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2c4b0a934eb59da41739b341c0f8019e2c08f278 --- /dev/null +++ b/tasks/two-way-complementation/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/two-way-complementation" +version = "1.0.0" +description = "Prove TwoWayComplementation (openai/math family 129: Exponential state costs for two-way automata) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TwoWayComplementation.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TwoWayComplementation" +family = "129" +family_title = "Exponential state costs for two-way automata" +subject = "Theoretical computer science" +theorems = ["OAI.TwoWayComplementation.complementation_lower_bound_finite"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TwoWayAutomata.Main" +reference_modules = 19 +reference_lean_bytes = 192919 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 96 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 11873 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/two-way-complementation/tests/Challenge.lean b/tasks/two-way-complementation/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ebe79e3b2e67e516225f5d498f92d1fcb8e7a73c --- /dev/null +++ b/tasks/two-way-complementation/tests/Challenge.lean @@ -0,0 +1,45 @@ +import Mathlib + +namespace OAI + +namespace TwoWayComplementation + +open scoped SetRel + +def relStar {α : Type*} (R : SetRel α α) : SetRel α α := + {(x, y) | Relation.ReflTransGen (fun a b => (a, b) ∈ R) x y} + +structure TwoNFA (Sigma Q : Type*) where + initial : Q + accepting : Set Q + transition : Q → (Fin 2 ⊕ Sigma) → Set (Q × Fin 3) + +def tapeSymbol {Sigma : Type*} (w : List Sigma) (p : Fin (w.length + 2)) : Fin 2 ⊕ Sigma := + if hleft : p.val = 0 then .inl 0 + else if hright : p.val = w.length + 1 then .inl 1 + else .inr (w[p.val - 1]'(by omega)) + +namespace TwoNFA + +def step {Sigma Q : Type*} (A : TwoNFA Sigma Q) (w : List Sigma) : + SetRel (Q × Fin (w.length + 2)) (Q × Fin (w.length + 2)) := + {(c, d) | ∃ move : Fin 3, + (d.1, move) ∈ A.transition c.1 (tapeSymbol w c.2) ∧ + (d.2.val : ℤ) = (c.2.val : ℤ) + (move.val : ℤ) - 1} + +def language {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Set (List Sigma) := + {w | ∃ c, c.1 ∈ A.accepting ∧ + ((A.initial, ⟨0, by omega⟩), c) ∈ relStar (A.step w)} + +end TwoNFA + +theorem complementation_lower_bound_finite (n : ℕ) (hn : 4 ≤ n) : + ∃ A : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) (Fin n), + ∀ (Q : Type*) [Fintype Q], ∀ B : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + B.language = A.languageᶜ → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) - 1 ≤ (Fintype.card Q : ℝ) := by + sorry + +end TwoWayComplementation + +end OAI diff --git a/tasks/two-way-complementation/tests/grade.py b/tasks/two-way-complementation/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/two-way-complementation/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/two-way-complementation/tests/task.json b/tasks/two-way-complementation/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..e4edcd05cdce474652307f25680b612cb448278b --- /dev/null +++ b/tasks/two-way-complementation/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TwoWayComplementation", + "comparator": { + "theorem_names": [ + "OAI.TwoWayComplementation.complementation_lower_bound_finite" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 10973 +} \ No newline at end of file diff --git a/tasks/two-way-complementation/tests/test.sh b/tasks/two-way-complementation/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/two-way-complementation/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/two-way-determinization/environment/Dockerfile b/tasks/two-way-determinization/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/two-way-determinization/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/two-way-determinization/environment/fetch_mathlib.sh b/tasks/two-way-determinization/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/two-way-determinization/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/two-way-determinization/environment/lake-manifest.json b/tasks/two-way-determinization/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/two-way-determinization/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/two-way-determinization/environment/lakefile.lean b/tasks/two-way-determinization/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/two-way-determinization/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/two-way-determinization/environment/lean_setup.sh b/tasks/two-way-determinization/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/two-way-determinization/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/two-way-determinization/environment/pack_submission.py b/tasks/two-way-determinization/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/two-way-determinization/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/two-way-determinization/instruction.md b/tasks/two-way-determinization/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..834f15f9c285c6d98cc1dd7c2d4b228df66847a7 --- /dev/null +++ b/tasks/two-way-determinization/instruction.md @@ -0,0 +1,124 @@ +# openai/math challenge `TwoWayDeterminization` (family 129) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 129 of the release, *Exponential state costs for two-way automata* +(Theoretical computer science). The family as a whole: Proves exponential lower bounds both for complementing two-way nondeterministic finite automata and for simulating one-way nondeterministic automata by two-way deterministic ones. The latter resolves the Sakoda–Sipser state-succinctness conjecture over growing finite alphabets; both results rule out polynomial state bounds independent of alphabet size. + +The challenge is `TwoWayDeterminization`, also at `/opt/openai-math/challenges/TwoWayDeterminization.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace TwoWayComplementation + +open scoped SetRel + +/-- Reflexive transitive closure, including the empty path. -/ +def relStar {α : Type*} (R : SetRel α α) : SetRel α α := + {(x, y) | Relation.ReflTransGen (fun a b => (a, b) ∈ R) x y} + +/-- A read-only 2NFA. The two endmarkers are `Sum.inl 0` and `Sum.inl 1`. + Move codes 0, 1, 2 mean left, stay, right. -/ +structure TwoNFA (Sigma Q : Type*) where + /-- The state in which the machine starts on the left endmarker. -/ + initial : Q + /-- States whose occurrence on a finite run constitutes acceptance. -/ + accepting : Set Q + /-- Allowed next-state and move pairs, determined by the state and scanned symbol. -/ + transition : Q → (Fin 2 ⊕ Sigma) → Set (Q × Fin 3) + +/-- Tape lookup includes two distinct endmarkers, even on empty input. -/ +def tapeSymbol {Sigma : Type*} (w : List Sigma) (p : Fin (w.length + 2)) : Fin 2 ⊕ Sigma := + if hleft : p.val = 0 then .inl 0 + else if hright : p.val = w.length + 1 then .inl 1 + else .inr (w[p.val - 1]'(by omega)) + +namespace TwoNFA + +/-- One legal step: both head positions stay within the marked input. -/ +def step {Sigma Q : Type*} (A : TwoNFA Sigma Q) (w : List Sigma) : + SetRel (Q × Fin (w.length + 2)) (Q × Fin (w.length + 2)) := + {(c, d) | ∃ move : Fin 3, + (d.1, move) ∈ A.transition c.1 (tapeSymbol w c.2) ∧ + (d.2.val : ℤ) = (c.2.val : ℤ) + (move.val : ℤ) - 1} + +/-- Existential finite-run acceptance, allowing a run of length zero. -/ +def language {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Set (List Sigma) := + {w | ∃ c, c.1 ∈ A.accepting ∧ + ((A.initial, ⟨0, by omega⟩), c) ∈ relStar (A.step w)} + +end TwoNFA + +/-- At most one next-state/move pair at every state and scanned symbol. -/ +def TwoNFA.Deterministic {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Prop := + ∀ q symbol, (A.transition q symbol).Subsingleton + +/-- Relation product for an input word; the empty product is the identity. -/ +def relationProduct {H : Type*} (w : List (SetRel H H)) : SetRel H H := + w.foldr SetRel.comp SetRel.id + +/-- The source language consists of the words with nonempty relation product. -/ +def sourceLanguage (H : Type*) : Set (List (SetRel H H)) := + {w | (relationProduct w).Nonempty} + +/-- Both lower bounds hold for the same n-state liveness witness. -/ +theorem explicit_family_main (n : ℕ) (hn : 4 ≤ n) : + ∃ A : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) (Fin n), + A.language = sourceLanguage (Fin (n - 2)) ∧ + (∀ (Q : Type*) [Fintype Q], + ∀ B : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + B.language = A.languageᶜ → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) - 1 ≤ (Fintype.card Q : ℝ)) ∧ + (131 ≤ n → ∀ (Q : Type*) [Fintype Q], + ∀ D : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + D.Deterministic → D.language = A.language → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) ≤ (Fintype.card Q : ℝ)) := by + sorry + +end TwoWayComplementation + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TwoWayDeterminization.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.TwoWayComplementation.explicit_family_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/two-way-determinization/solution/closure.txt b/tasks/two-way-determinization/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d4926baf7126a55694ec242d40da333e8c11c217 --- /dev/null +++ b/tasks/two-way-determinization/solution/closure.txt @@ -0,0 +1,41 @@ +OAI.Combinatorics.Automata.Cells +OAI.Combinatorics.Automata.Corners +OAI.Combinatorics.Automata.Diagram +OAI.Combinatorics.Automata.Diagrams +OAI.Combinatorics.Automata.Main +OAI.Combinatorics.Automata.Model +OAI.Combinatorics.Automata.Network +OAI.Combinatorics.Automata.Normalization +OAI.Combinatorics.Automata.PathNFA +OAI.Combinatorics.Automata.Rank +OAI.Combinatorics.Automata.RankLoss +OAI.Combinatorics.Automata.Recognition +OAI.Combinatorics.Automata.Relations +OAI.Combinatorics.Automata.Syntactic +OAI.Combinatorics.Automata.Tours +OAI.Combinatorics.Automata.Wiring +OAI.Combinatorics.TwoWayAutomata.Amplification +OAI.Combinatorics.TwoWayAutomata.Chain +OAI.Combinatorics.TwoWayAutomata.Classes +OAI.Combinatorics.TwoWayAutomata.Corners +OAI.Combinatorics.TwoWayAutomata.DeterministicBound +OAI.Combinatorics.TwoWayAutomata.DeterministicCore +OAI.Combinatorics.TwoWayAutomata.DeterministicTransport +OAI.Combinatorics.TwoWayAutomata.Diagram +OAI.Combinatorics.TwoWayAutomata.ExplicitFamily +OAI.Combinatorics.TwoWayAutomata.ImageBound +OAI.Combinatorics.TwoWayAutomata.Main +OAI.Combinatorics.TwoWayAutomata.Model +OAI.Combinatorics.TwoWayAutomata.Nesting +OAI.Combinatorics.TwoWayAutomata.Network +OAI.Combinatorics.TwoWayAutomata.Normalization +OAI.Combinatorics.TwoWayAutomata.Recognition +OAI.Combinatorics.TwoWayAutomata.RelationBridge +OAI.Combinatorics.TwoWayAutomata.RelationMonoid +OAI.Combinatorics.TwoWayAutomata.Relations +OAI.Combinatorics.TwoWayAutomata.Representation +OAI.Combinatorics.TwoWayAutomata.Retained +OAI.Combinatorics.TwoWayAutomata.Source +OAI.Combinatorics.TwoWayAutomata.Tape +OAI.Combinatorics.TwoWayAutomata.TransitionBridge +OAI.Combinatorics.TwoWayAutomata.Transport diff --git a/tasks/two-way-determinization/solution/reference.py b/tasks/two-way-determinization/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/two-way-determinization/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/two-way-determinization/solution/solve.sh b/tasks/two-way-determinization/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d111ece01687d3aeb4fc4bfceb6ff58b81582609 --- /dev/null +++ b/tasks/two-way-determinization/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TwoWayDeterminization, i.e. module OAI.Combinatorics.TwoWayAutomata.ExplicitFamily and the +# 41 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.TwoWayAutomata.ExplicitFamily /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TwoWayDeterminization" diff --git a/tasks/two-way-determinization/task.toml b/tasks/two-way-determinization/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..c393fba88fbbb96d17ae81a1133a5361e586e324 --- /dev/null +++ b/tasks/two-way-determinization/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/two-way-determinization" +version = "1.0.0" +description = "Prove TwoWayDeterminization (openai/math family 129: Exponential state costs for two-way automata) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TwoWayDeterminization.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TwoWayDeterminization" +family = "129" +family_title = "Exponential state costs for two-way automata" +subject = "Theoretical computer science" +theorems = ["OAI.TwoWayComplementation.explicit_family_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.TwoWayAutomata.ExplicitFamily" +reference_modules = 41 +reference_lean_bytes = 378696 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 197 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12040 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/two-way-determinization/tests/Challenge.lean b/tasks/two-way-determinization/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0c6f5f30cfa16122441e8a0ada4299aafddf972e --- /dev/null +++ b/tasks/two-way-determinization/tests/Challenge.lean @@ -0,0 +1,73 @@ +import Mathlib + +namespace OAI + +namespace TwoWayComplementation + +open scoped SetRel + +/-- Reflexive transitive closure, including the empty path. -/ +def relStar {α : Type*} (R : SetRel α α) : SetRel α α := + {(x, y) | Relation.ReflTransGen (fun a b => (a, b) ∈ R) x y} + +/-- A read-only 2NFA. The two endmarkers are `Sum.inl 0` and `Sum.inl 1`. + Move codes 0, 1, 2 mean left, stay, right. -/ +structure TwoNFA (Sigma Q : Type*) where + /-- The state in which the machine starts on the left endmarker. -/ + initial : Q + /-- States whose occurrence on a finite run constitutes acceptance. -/ + accepting : Set Q + /-- Allowed next-state and move pairs, determined by the state and scanned symbol. -/ + transition : Q → (Fin 2 ⊕ Sigma) → Set (Q × Fin 3) + +/-- Tape lookup includes two distinct endmarkers, even on empty input. -/ +def tapeSymbol {Sigma : Type*} (w : List Sigma) (p : Fin (w.length + 2)) : Fin 2 ⊕ Sigma := + if hleft : p.val = 0 then .inl 0 + else if hright : p.val = w.length + 1 then .inl 1 + else .inr (w[p.val - 1]'(by omega)) + +namespace TwoNFA + +/-- One legal step: both head positions stay within the marked input. -/ +def step {Sigma Q : Type*} (A : TwoNFA Sigma Q) (w : List Sigma) : + SetRel (Q × Fin (w.length + 2)) (Q × Fin (w.length + 2)) := + {(c, d) | ∃ move : Fin 3, + (d.1, move) ∈ A.transition c.1 (tapeSymbol w c.2) ∧ + (d.2.val : ℤ) = (c.2.val : ℤ) + (move.val : ℤ) - 1} + +/-- Existential finite-run acceptance, allowing a run of length zero. -/ +def language {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Set (List Sigma) := + {w | ∃ c, c.1 ∈ A.accepting ∧ + ((A.initial, ⟨0, by omega⟩), c) ∈ relStar (A.step w)} + +end TwoNFA + +/-- At most one next-state/move pair at every state and scanned symbol. -/ +def TwoNFA.Deterministic {Sigma Q : Type*} (A : TwoNFA Sigma Q) : Prop := + ∀ q symbol, (A.transition q symbol).Subsingleton + +/-- Relation product for an input word; the empty product is the identity. -/ +def relationProduct {H : Type*} (w : List (SetRel H H)) : SetRel H H := + w.foldr SetRel.comp SetRel.id + +/-- The source language consists of the words with nonempty relation product. -/ +def sourceLanguage (H : Type*) : Set (List (SetRel H H)) := + {w | (relationProduct w).Nonempty} + +/-- Both lower bounds hold for the same n-state liveness witness. -/ +theorem explicit_family_main (n : ℕ) (hn : 4 ≤ n) : + ∃ A : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) (Fin n), + A.language = sourceLanguage (Fin (n - 2)) ∧ + (∀ (Q : Type*) [Fintype Q], + ∀ B : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + B.language = A.languageᶜ → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) - 1 ≤ (Fintype.card Q : ℝ)) ∧ + (131 ≤ n → ∀ (Q : Type*) [Fintype Q], + ∀ D : TwoNFA (SetRel (Fin (n - 2)) (Fin (n - 2))) Q, + D.Deterministic → D.language = A.language → + (1 / 2 : ℝ) * 2 ^ ((n - 4) / 127) ≤ (Fintype.card Q : ℝ)) := by + sorry + +end TwoWayComplementation + +end OAI diff --git a/tasks/two-way-determinization/tests/grade.py b/tasks/two-way-determinization/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/two-way-determinization/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/two-way-determinization/tests/task.json b/tasks/two-way-determinization/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..3e725e973a3aa4a3761abff20a2d4c3bd892060d --- /dev/null +++ b/tasks/two-way-determinization/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TwoWayDeterminization", + "comparator": { + "theorem_names": [ + "OAI.TwoWayComplementation.explicit_family_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Classical.choice", + "Quot.sound" + ] + }, + "grade_timeout_sec": 11140 +} \ No newline at end of file diff --git a/tasks/two-way-determinization/tests/test.sh b/tasks/two-way-determinization/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/two-way-determinization/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/type-system-normalization/environment/Dockerfile b/tasks/type-system-normalization/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/type-system-normalization/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/type-system-normalization/environment/fetch_mathlib.sh b/tasks/type-system-normalization/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/type-system-normalization/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/type-system-normalization/environment/lake-manifest.json b/tasks/type-system-normalization/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/type-system-normalization/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/type-system-normalization/environment/lakefile.lean b/tasks/type-system-normalization/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/type-system-normalization/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/type-system-normalization/environment/lean_setup.sh b/tasks/type-system-normalization/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/type-system-normalization/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/type-system-normalization/environment/pack_submission.py b/tasks/type-system-normalization/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/type-system-normalization/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/type-system-normalization/instruction.md b/tasks/type-system-normalization/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..415469f313d00851425e79092364b58dcc44411f --- /dev/null +++ b/tasks/type-system-normalization/instruction.md @@ -0,0 +1,173 @@ +# openai/math challenge `TypeSystemNormalization` (family 245) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 245 of the release, *The $\beta$-Barendregt–Geuvers–Klop conjecture* +(Mathematical logic). The family as a whole: Proves that weak normalization implies strong normalization for every pure type system: if every legal expression in every valid context has a $\beta$-normal form, every $\beta$-reduction sequence terminates. This resolves the $\beta$-Barendregt–Geuvers–Klop conjecture, including nonfunctional rules and open contexts. + +The challenge is `TypeSystemNormalization`, also at `/opt/openai-math/challenges/TypeSystemNormalization.lean`: + +```lean +import Mathlib + +namespace OAI + +/-! +Full annotated PTS syntax, modulo alpha-renaming via de Bruijn indices. +Contexts are stored newest-first, each declaration in its prefix context. +No functionality assumptions on axioms or product rules. +-/ + +namespace PureTypeSystem + +universe u + +inductive Expr (Sorts : Type u) : Type u + | var : Nat → Expr Sorts + | sort : Sorts → Expr Sorts + | app : Expr Sorts → Expr Sorts → Expr Sorts + | lam : Expr Sorts → Expr Sorts → Expr Sorts + | pi : Expr Sorts → Expr Sorts → Expr Sorts + deriving DecidableEq + +namespace Expr + +variable {S : Type u} + +def liftRen (ρ : Nat → Nat) : Nat → Nat + | 0 => 0 + | n + 1 => ρ n + 1 + +def rename (ρ : Nat → Nat) : Expr S → Expr S + | var n => var (ρ n) + | sort s => sort s + | app f a => app (rename ρ f) (rename ρ a) + | lam A b => lam (rename ρ A) (rename (liftRen ρ) b) + | pi A B => pi (rename ρ A) (rename (liftRen ρ) B) + +def liftSub (σ : Nat → Expr S) : Nat → Expr S + | 0 => var 0 + | n + 1 => rename Nat.succ (σ n) + +def subst (σ : Nat → Expr S) : Expr S → Expr S + | var n => σ n + | sort s => sort s + | app f a => app (subst σ f) (subst σ a) + | lam A b => lam (subst σ A) (subst (liftSub σ) b) + | pi A B => pi (subst σ A) (subst (liftSub σ) B) + +def single (a : Expr S) : Nat → Expr S + | 0 => a + | n + 1 => var n + +def instantiate (b a : Expr S) : Expr S := subst (single a) b + +end Expr + +structure Specification (S : Type u) where + axioms : S → S → Prop + rule : S → S → S → Prop + +inductive Beta {S : Type u} : Expr S → Expr S → Prop + | head (A b a) : Beta (.app (.lam A b) a) (b.instantiate a) + | app_left {f f' a} : Beta f f' → Beta (.app f a) (.app f' a) + | app_right {f a a'} : Beta a a' → Beta (.app f a) (.app f a') + | lam_domain {A A' b} : Beta A A' → Beta (.lam A b) (.lam A' b) + | lam_body {A b b'} : Beta b b' → Beta (.lam A b) (.lam A b') + | pi_domain {A A' B} : Beta A A' → Beta (.pi A B) (.pi A' B) + | pi_body {A B B'} : Beta B B' → Beta (.pi A B) (.pi A B') + +def Converts {S : Type u} : Expr S → Expr S → Prop := Relation.EqvGen Beta + +def Normal {S : Type u} (M : Expr S) : Prop := ∀ N, ¬ Beta M N + +def WeaklyNormalizing {S : Type u} (M : Expr S) : Prop := + ∃ N, Relation.ReflTransGen Beta M N ∧ Normal N + +/-- Accessibility for the converse of reduction: strong normalization, +including reductions in all type annotations. -/ +def StronglyNormalizing {S : Type u} (M : Expr S) : Prop := + Acc (fun N M : Expr S => Beta M N) M + +inductive HasType {S : Type u} (P : Specification S) : + List (Expr S) → Expr S → Expr S → Prop + | ax {s t} : P.axioms s t → HasType P [] (.sort s) (.sort t) + | var {Γ A s} : HasType P Γ A (.sort s) → + HasType P (A :: Γ) (.var 0) (A.rename Nat.succ) + | weaken {Γ M B A s} : HasType P Γ M B → HasType P Γ A (.sort s) → + HasType P (A :: Γ) (M.rename Nat.succ) (B.rename Nat.succ) + | product {Γ A B s₁ s₂ s₃} : HasType P Γ A (.sort s₁) → + HasType P (A :: Γ) B (.sort s₂) → P.rule s₁ s₂ s₃ → + HasType P Γ (.pi A B) (.sort s₃) + | abstraction {Γ A b B s} : HasType P (A :: Γ) b B → + HasType P Γ (.pi A B) (.sort s) → + HasType P Γ (.lam A b) (.pi A B) + | application {Γ f a A B} : HasType P Γ f (.pi A B) → + HasType P Γ a A → HasType P Γ (.app f a) (B.instantiate a) + | conversion {Γ M A B s} : HasType P Γ M A → HasType P Γ B (.sort s) → + Converts A B → HasType P Γ M B + +inductive ValidContext {S : Type u} (P : Specification S) : List (Expr S) → Prop + | nil : ValidContext P [] + | cons {Γ A s} : ValidContext P Γ → HasType P Γ A (.sort s) → + ValidContext P (A :: Γ) + +def Legal {S : Type u} (P : Specification S) (Γ : List (Expr S)) (M : Expr S) : Prop := + ∃ A, HasType P Γ M A ∨ HasType P Γ A M + +def SystemWeaklyNormalizing {S : Type u} (P : Specification S) : Prop := + ∀ Γ, ValidContext P Γ → ∀ M, Legal P Γ M → WeaklyNormalizing M + +def SystemStronglyNormalizing {S : Type u} (P : Specification S) : Prop := + ∀ Γ, ValidContext P Γ → ∀ M, Legal P Γ M → StronglyNormalizing M + +/-- System-wide weak normalization implies strong normalization for every PTS, +including arbitrary sort types, nonfunctional rules and annotated terms. -/ +theorem weak_implies_strong {S : Type u} (P : Specification S) + (h : SystemWeaklyNormalizing P) : SystemStronglyNormalizing P := by + sorry + +end PureTypeSystem + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/TypeSystemNormalization.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.PureTypeSystem.weak_implies_strong` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/type-system-normalization/solution/closure.txt b/tasks/type-system-normalization/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..1c160d1ff93f497287355c0b5f143f15ffcf7b8e --- /dev/null +++ b/tasks/type-system-normalization/solution/closure.txt @@ -0,0 +1,33 @@ +OAI.Computability.TypeSystem.Basic +OAI.Computability.TypeSystem.Bounds +OAI.Computability.TypeSystem.Candidates +OAI.Computability.TypeSystem.Channels +OAI.Computability.TypeSystem.Components +OAI.Computability.TypeSystem.Congruence +OAI.Computability.TypeSystem.Contexts +OAI.Computability.TypeSystem.Diagonal +OAI.Computability.TypeSystem.Equivalence +OAI.Computability.TypeSystem.Evaluation +OAI.Computability.TypeSystem.Interface +OAI.Computability.TypeSystem.Labelled +OAI.Computability.TypeSystem.Logic +OAI.Computability.TypeSystem.Normalization +OAI.Computability.TypeSystem.ObservationCandidates +OAI.Computability.TypeSystem.ObservationReduction +OAI.Computability.TypeSystem.OneChild +OAI.Computability.TypeSystem.Pairs +OAI.Computability.TypeSystem.Plain +OAI.Computability.TypeSystem.Potential +OAI.Computability.TypeSystem.Profiles +OAI.Computability.TypeSystem.Reduction +OAI.Computability.TypeSystem.Relational +OAI.Computability.TypeSystem.Relations +OAI.Computability.TypeSystem.Response +OAI.Computability.TypeSystem.Restriction +OAI.Computability.TypeSystem.Signed +OAI.Computability.TypeSystem.Spaces +OAI.Computability.TypeSystem.Specialization +OAI.Computability.TypeSystem.Substitution +OAI.Computability.TypeSystem.Typing +OAI.Computability.TypeSystem.Values +OAI.Computability.TypeSystem.Wrappers diff --git a/tasks/type-system-normalization/solution/reference.py b/tasks/type-system-normalization/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/type-system-normalization/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/type-system-normalization/solution/solve.sh b/tasks/type-system-normalization/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ea40cd684232b27f8cdf416b789e3d0d90680cf6 --- /dev/null +++ b/tasks/type-system-normalization/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of TypeSystemNormalization, i.e. module OAI.Computability.TypeSystem.Normalization and the +# 33 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.TypeSystem.Normalization /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of TypeSystemNormalization" diff --git a/tasks/type-system-normalization/task.toml b/tasks/type-system-normalization/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..d617b2b189a06b13b284e378e39723e2932d0201 --- /dev/null +++ b/tasks/type-system-normalization/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/type-system-normalization" +version = "1.0.0" +description = "Prove TypeSystemNormalization (openai/math family 245: The $\\beta$-Barendregt–Geuvers–Klop conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/TypeSystemNormalization.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "TypeSystemNormalization" +family = "245" +family_title = "The $\\beta$-Barendregt–Geuvers–Klop conjecture" +subject = "Mathematical logic" +theorems = ["OAI.PureTypeSystem.weak_implies_strong"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.TypeSystem.Normalization" +reference_modules = 33 +reference_lean_bytes = 1579764 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 186 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13121 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/type-system-normalization/tests/Challenge.lean b/tasks/type-system-normalization/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..6a4260f96d16d6fb9821424b0d125de562d7e2b5 --- /dev/null +++ b/tasks/type-system-normalization/tests/Challenge.lean @@ -0,0 +1,122 @@ +import Mathlib + +namespace OAI + +/-! +Full annotated PTS syntax, modulo alpha-renaming via de Bruijn indices. +Contexts are stored newest-first, each declaration in its prefix context. +No functionality assumptions on axioms or product rules. +-/ + +namespace PureTypeSystem + +universe u + +inductive Expr (Sorts : Type u) : Type u + | var : Nat → Expr Sorts + | sort : Sorts → Expr Sorts + | app : Expr Sorts → Expr Sorts → Expr Sorts + | lam : Expr Sorts → Expr Sorts → Expr Sorts + | pi : Expr Sorts → Expr Sorts → Expr Sorts + deriving DecidableEq + +namespace Expr + +variable {S : Type u} + +def liftRen (ρ : Nat → Nat) : Nat → Nat + | 0 => 0 + | n + 1 => ρ n + 1 + +def rename (ρ : Nat → Nat) : Expr S → Expr S + | var n => var (ρ n) + | sort s => sort s + | app f a => app (rename ρ f) (rename ρ a) + | lam A b => lam (rename ρ A) (rename (liftRen ρ) b) + | pi A B => pi (rename ρ A) (rename (liftRen ρ) B) + +def liftSub (σ : Nat → Expr S) : Nat → Expr S + | 0 => var 0 + | n + 1 => rename Nat.succ (σ n) + +def subst (σ : Nat → Expr S) : Expr S → Expr S + | var n => σ n + | sort s => sort s + | app f a => app (subst σ f) (subst σ a) + | lam A b => lam (subst σ A) (subst (liftSub σ) b) + | pi A B => pi (subst σ A) (subst (liftSub σ) B) + +def single (a : Expr S) : Nat → Expr S + | 0 => a + | n + 1 => var n + +def instantiate (b a : Expr S) : Expr S := subst (single a) b + +end Expr + +structure Specification (S : Type u) where + axioms : S → S → Prop + rule : S → S → S → Prop + +inductive Beta {S : Type u} : Expr S → Expr S → Prop + | head (A b a) : Beta (.app (.lam A b) a) (b.instantiate a) + | app_left {f f' a} : Beta f f' → Beta (.app f a) (.app f' a) + | app_right {f a a'} : Beta a a' → Beta (.app f a) (.app f a') + | lam_domain {A A' b} : Beta A A' → Beta (.lam A b) (.lam A' b) + | lam_body {A b b'} : Beta b b' → Beta (.lam A b) (.lam A b') + | pi_domain {A A' B} : Beta A A' → Beta (.pi A B) (.pi A' B) + | pi_body {A B B'} : Beta B B' → Beta (.pi A B) (.pi A B') + +def Converts {S : Type u} : Expr S → Expr S → Prop := Relation.EqvGen Beta + +def Normal {S : Type u} (M : Expr S) : Prop := ∀ N, ¬ Beta M N + +def WeaklyNormalizing {S : Type u} (M : Expr S) : Prop := + ∃ N, Relation.ReflTransGen Beta M N ∧ Normal N + +/-- Accessibility for the converse of reduction: strong normalization, +including reductions in all type annotations. -/ +def StronglyNormalizing {S : Type u} (M : Expr S) : Prop := + Acc (fun N M : Expr S => Beta M N) M + +inductive HasType {S : Type u} (P : Specification S) : + List (Expr S) → Expr S → Expr S → Prop + | ax {s t} : P.axioms s t → HasType P [] (.sort s) (.sort t) + | var {Γ A s} : HasType P Γ A (.sort s) → + HasType P (A :: Γ) (.var 0) (A.rename Nat.succ) + | weaken {Γ M B A s} : HasType P Γ M B → HasType P Γ A (.sort s) → + HasType P (A :: Γ) (M.rename Nat.succ) (B.rename Nat.succ) + | product {Γ A B s₁ s₂ s₃} : HasType P Γ A (.sort s₁) → + HasType P (A :: Γ) B (.sort s₂) → P.rule s₁ s₂ s₃ → + HasType P Γ (.pi A B) (.sort s₃) + | abstraction {Γ A b B s} : HasType P (A :: Γ) b B → + HasType P Γ (.pi A B) (.sort s) → + HasType P Γ (.lam A b) (.pi A B) + | application {Γ f a A B} : HasType P Γ f (.pi A B) → + HasType P Γ a A → HasType P Γ (.app f a) (B.instantiate a) + | conversion {Γ M A B s} : HasType P Γ M A → HasType P Γ B (.sort s) → + Converts A B → HasType P Γ M B + +inductive ValidContext {S : Type u} (P : Specification S) : List (Expr S) → Prop + | nil : ValidContext P [] + | cons {Γ A s} : ValidContext P Γ → HasType P Γ A (.sort s) → + ValidContext P (A :: Γ) + +def Legal {S : Type u} (P : Specification S) (Γ : List (Expr S)) (M : Expr S) : Prop := + ∃ A, HasType P Γ M A ∨ HasType P Γ A M + +def SystemWeaklyNormalizing {S : Type u} (P : Specification S) : Prop := + ∀ Γ, ValidContext P Γ → ∀ M, Legal P Γ M → WeaklyNormalizing M + +def SystemStronglyNormalizing {S : Type u} (P : Specification S) : Prop := + ∀ Γ, ValidContext P Γ → ∀ M, Legal P Γ M → StronglyNormalizing M + +/-- System-wide weak normalization implies strong normalization for every PTS, +including arbitrary sort types, nonfunctional rules and annotated terms. -/ +theorem weak_implies_strong {S : Type u} (P : Specification S) + (h : SystemWeaklyNormalizing P) : SystemStronglyNormalizing P := by + sorry + +end PureTypeSystem + +end OAI diff --git a/tasks/type-system-normalization/tests/grade.py b/tasks/type-system-normalization/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/type-system-normalization/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/type-system-normalization/tests/task.json b/tasks/type-system-normalization/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9b7390ee29e95f362c55cbb6ef5028dd22e23dc2 --- /dev/null +++ b/tasks/type-system-normalization/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "TypeSystemNormalization", + "comparator": { + "theorem_names": [ + "OAI.PureTypeSystem.weak_implies_strong" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12221 +} \ No newline at end of file diff --git a/tasks/type-system-normalization/tests/test.sh b/tasks/type-system-normalization/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/type-system-normalization/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/uniform-commutator/environment/Dockerfile b/tasks/uniform-commutator/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/uniform-commutator/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/uniform-commutator/environment/fetch_mathlib.sh b/tasks/uniform-commutator/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/uniform-commutator/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/uniform-commutator/environment/lake-manifest.json b/tasks/uniform-commutator/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/uniform-commutator/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/uniform-commutator/environment/lakefile.lean b/tasks/uniform-commutator/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/uniform-commutator/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/uniform-commutator/environment/lean_setup.sh b/tasks/uniform-commutator/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/uniform-commutator/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/uniform-commutator/environment/pack_submission.py b/tasks/uniform-commutator/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/uniform-commutator/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/uniform-commutator/instruction.md b/tasks/uniform-commutator/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..3b29fe184688be70fdebcf31e6859ab777350b3c --- /dev/null +++ b/tasks/uniform-commutator/instruction.md @@ -0,0 +1,91 @@ +# openai/math challenge `UniformCommutator` (family 288) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 288 of the release, *Kadison's similarity conjecture* +(Operator algebras). The family as a whole: Proves Kadison's similarity conjecture: every bounded complex-linear unital algebra homomorphism from a unital complex $C^*$-algebra to operators on a Hilbert space becomes a $*$-homomorphism after conjugation by a bounded invertible operator. + +The challenge is `UniformCommutator`, also at `/opt/openai-math/challenges/UniformCommutator.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +universe u v +namespace Kadison + +variable {K : Type u} [NormedAddCommGroup K] [InnerProductSpace ℂ K] + [CompleteSpace K] + +def commutatorSeminorm (P : VonNeumannAlgebra K) (Y : K →L[ℂ] K) : ℝ := + sSup {r : ℝ | ∃ a : K →L[ℂ] K, a ∈ P ∧ ‖a‖ ≤ 1 ∧ r = ‖Y * a - a * Y‖} + +def matrixOperator (h : ℕ) (X : Matrix (Fin h) (Fin h) (K →L[ℂ] K)) : + (PiLp 2 fun _ : Fin h => K) →L[ℂ] (PiLp 2 fun _ : Fin h => K) := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin h => K)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun i => ∑ j : Fin h, + (X i j).comp (PiLp.proj 2 (fun _ : Fin h => K) j))) + +def diagonalAmplification (h : ℕ) (Y : K →L[ℂ] K) : + (PiLp 2 fun _ : Fin h => K) →L[ℂ] (PiLp 2 fun _ : Fin h => K) := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin h => K)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun i => Y.comp (PiLp.proj 2 (fun _ : Fin h => K) i))) + +theorem uniform_commutator : + ∃ C : ℝ, 0 ≤ C ∧ ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] + [CompleteSpace K] (P : VonNeumannAlgebra K) (Y : K →L[ℂ] K) + (h : ℕ), 1 ≤ h → ∀ (X : Matrix (Fin h) (Fin h) (K →L[ℂ] K)), + (∀ i j, X i j ∈ P) → + ‖diagonalAmplification h Y * matrixOperator h X - + matrixOperator h X * diagonalAmplification h Y‖ ≤ + C * commutatorSeminorm P Y * ‖matrixOperator h X‖ := by + sorry + +end Kadison + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniformCommutator.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Kadison.uniform_commutator` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/uniform-commutator/solution/closure.txt b/tasks/uniform-commutator/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..15b0e0096fdd389d3bc25b6455d794c06df167ab --- /dev/null +++ b/tasks/uniform-commutator/solution/closure.txt @@ -0,0 +1,656 @@ +OAI.Analysis.Commutator.AbelianGNSMaximal +OAI.Analysis.Commutator.AbelianGNSSpectral +OAI.Analysis.Commutator.AbelianSpectralIndicators +OAI.Analysis.Commutator.AbstractFreeCornerFromUnitary +OAI.Analysis.Commutator.AddField +OAI.Analysis.Commutator.AlgebraFreeExpectation +OAI.Analysis.Commutator.AllDerivationsMain +OAI.Analysis.Commutator.AllUnitaryTests +OAI.Analysis.Commutator.AmplificationIsometry +OAI.Analysis.Commutator.AmplifiedProjectionBlocks +OAI.Analysis.Commutator.AmplifiedStrongLimit +OAI.Analysis.Commutator.AmplifiedTowerGeometry +OAI.Analysis.Commutator.AmplifiedTowerStage +OAI.Analysis.Commutator.ArvesonAnnihilator +OAI.Analysis.Commutator.ArvesonCorner +OAI.Analysis.Commutator.ArvesonDistance +OAI.Analysis.Commutator.ArvesonExtension +OAI.Analysis.Commutator.ArvesonFinite +OAI.Analysis.Commutator.AtomicCenterMain +OAI.Analysis.Commutator.AtomicCoefficients +OAI.Analysis.Commutator.AtomicDecomposition +OAI.Analysis.Commutator.AtomicFactorMain +OAI.Analysis.Commutator.AtomicFinite +OAI.Analysis.Commutator.AtomicInfinite +OAI.Analysis.Commutator.AtomicShift +OAI.Analysis.Commutator.Average +OAI.Analysis.Commutator.BaireSmallPiece +OAI.Analysis.Commutator.BalancedDefect +OAI.Analysis.Commutator.BalancedSymmetry +OAI.Analysis.Commutator.BicommutantOrbit +OAI.Analysis.Commutator.BicommutantRange +OAI.Analysis.Commutator.BiprodLinkColumn +OAI.Analysis.Commutator.BiprodLinkEmpty +OAI.Analysis.Commutator.BiprodLinkIntertwining +OAI.Analysis.Commutator.BlockDilationBound +OAI.Analysis.Commutator.BoundedPositiveSequence +OAI.Analysis.Commutator.BoundedSequenceClosed +OAI.Analysis.Commutator.BoundedWordPool +OAI.Analysis.Commutator.CFCIntertwiner +OAI.Analysis.Commutator.CFCTraceMoments +OAI.Analysis.Commutator.CStarContractiveLifts +OAI.Analysis.Commutator.CStarRangeLifts +OAI.Analysis.Commutator.CbDerivation +OAI.Analysis.Commutator.CbDerivationQuantitative +OAI.Analysis.Commutator.CbDilation +OAI.Analysis.Commutator.CbSimilarity +OAI.Analysis.Commutator.CenteredContractionDensity +OAI.Analysis.Commutator.CenteredSpace +OAI.Analysis.Commutator.CentralAtoms +OAI.Analysis.Commutator.CentralAverage +OAI.Analysis.Commutator.CentralBlockEstimate +OAI.Analysis.Commutator.CentralCorner +OAI.Analysis.Commutator.CentralGeometryModel +OAI.Analysis.Commutator.CentralPinching +OAI.Analysis.Commutator.CentralRepresentationModel +OAI.Analysis.Commutator.CentralSpectralGeometry +OAI.Analysis.Commutator.CentralSpectralModel +OAI.Analysis.Commutator.ChoiFunctional +OAI.Analysis.Commutator.ChoiGNS +OAI.Analysis.Commutator.ChoiRecovery +OAI.Analysis.Commutator.ClosedCStarOrder +OAI.Analysis.Commutator.CoefficientForm +OAI.Analysis.Commutator.CoefficientForm2 +OAI.Analysis.Commutator.CoherentComparison +OAI.Analysis.Commutator.ColumnEstimate +OAI.Analysis.Commutator.ColumnModule +OAI.Analysis.Commutator.CommutatorBicommutant +OAI.Analysis.Commutator.CommutatorPerturbation +OAI.Analysis.Commutator.CompactAverage +OAI.Analysis.Commutator.CompactInvariant +OAI.Analysis.Commutator.CompletionCentered +OAI.Analysis.Commutator.ConcreteCornerVonNeumann +OAI.Analysis.Commutator.ConjugatedFreeness +OAI.Analysis.Commutator.ConjugatedWordAlgebra +OAI.Analysis.Commutator.ConjugationNormalizer +OAI.Analysis.Commutator.ConstantSequenceClosedTransport +OAI.Analysis.Commutator.ConstantSequenceRange +OAI.Analysis.Commutator.ConvexIsometryFix +OAI.Analysis.Commutator.CornerAlgebra +OAI.Analysis.Commutator.CornerAlphabetGNS +OAI.Analysis.Commutator.CornerCenteredEstimates +OAI.Analysis.Commutator.CornerCyclic +OAI.Analysis.Commutator.CornerCyclicImplementation +OAI.Analysis.Commutator.CornerHaarSequence +OAI.Analysis.Commutator.CornerPhaseAveraging +OAI.Analysis.Commutator.CornerPhaseSelection +OAI.Analysis.Commutator.CornerPhaseSelectionCore +OAI.Analysis.Commutator.CornerPolarAlgebra +OAI.Analysis.Commutator.CornerPolarTransfer +OAI.Analysis.Commutator.CornerSymmetrization +OAI.Analysis.Commutator.CornerWeakZero +OAI.Analysis.Commutator.CountableFieldHom +OAI.Analysis.Commutator.CountableGNSColumn +OAI.Analysis.Commutator.CountableOrthogonal +OAI.Analysis.Commutator.CountableProjectionJoin +OAI.Analysis.Commutator.CountableStarHomTests +OAI.Analysis.Commutator.CountableStrongTests +OAI.Analysis.Commutator.CountableUnitaryTests +OAI.Analysis.Commutator.CountablyGeneratedCStar +OAI.Analysis.Commutator.CpCompression +OAI.Analysis.Commutator.CpMapOperations +OAI.Analysis.Commutator.CpUltralimit +OAI.Analysis.Commutator.CrossingPairings +OAI.Analysis.Commutator.CycleEmbeddings +OAI.Analysis.Commutator.CycleEmbeddings2 +OAI.Analysis.Commutator.CycleEndpoint +OAI.Analysis.Commutator.CycleInvariants +OAI.Analysis.Commutator.CycleInvariants2 +OAI.Analysis.Commutator.CycleInvariants3 +OAI.Analysis.Commutator.CyclePairTrace +OAI.Analysis.Commutator.CyclePairTrace2 +OAI.Analysis.Commutator.CyclePairTrace3 +OAI.Analysis.Commutator.CyclicCb +OAI.Analysis.Commutator.CyclicCbUnconditional +OAI.Analysis.Commutator.CyclicColumnFactorization +OAI.Analysis.Commutator.CyclicCorner +OAI.Analysis.Commutator.CyclicCornerRepresentation +OAI.Analysis.Commutator.CyclicDecomposition +OAI.Analysis.Commutator.CyclicGelfandModel +OAI.Analysis.Commutator.CyclicImplementationUnconditional +OAI.Analysis.Commutator.CyclicLocalModule +OAI.Analysis.Commutator.CyclicMatrix +OAI.Analysis.Commutator.CyclicMatrixApproximation +OAI.Analysis.Commutator.CyclicSpatialImplementation +OAI.Analysis.Commutator.CyclicSpectralMeasure +OAI.Analysis.Commutator.CyclicSpectralNorm +OAI.Analysis.Commutator.CyclicSpectralUnitary +OAI.Analysis.Commutator.DeMarrCenter +OAI.Analysis.Commutator.DecomposableAlgebra +OAI.Analysis.Commutator.DecomposableConstLimit +OAI.Analysis.Commutator.DecomposableDenseLimit +OAI.Analysis.Commutator.DecomposableLimit +OAI.Analysis.Commutator.DecomposableNorm +OAI.Analysis.Commutator.DecomposableOperator +OAI.Analysis.Commutator.Definitions +OAI.Analysis.Commutator.DenseCommutes +OAI.Analysis.Commutator.DenseFieldClosure +OAI.Analysis.Commutator.DenseRationalStar +OAI.Analysis.Commutator.DerivationBoundTransfer +OAI.Analysis.Commutator.DerivationCyclicColumns +OAI.Analysis.Commutator.DerivationKaplansky +OAI.Analysis.Commutator.DerivationMatrixColumns +OAI.Analysis.Commutator.DiagonalBlockCommutant +OAI.Analysis.Commutator.DiagonalCommute +OAI.Analysis.Commutator.DiagonalField +OAI.Analysis.Commutator.DiagonalVonNeumann +OAI.Analysis.Commutator.DiffuseHalving +OAI.Analysis.Commutator.DiffuseProjection +OAI.Analysis.Commutator.DihedralCompressionMoments +OAI.Analysis.Commutator.DihedralExpectationEntries +OAI.Analysis.Commutator.DihedralFejer +OAI.Analysis.Commutator.DihedralHaar +OAI.Analysis.Commutator.DoubleCopies +OAI.Analysis.Commutator.DyadicCuts +OAI.Analysis.Commutator.DyadicDimension +OAI.Analysis.Commutator.DyadicDimensionAdd +OAI.Analysis.Commutator.DyadicDimensionComparison +OAI.Analysis.Commutator.DyadicDimensionNormal +OAI.Analysis.Commutator.DyadicPartition +OAI.Analysis.Commutator.DyadicRankStep +OAI.Analysis.Commutator.DyadicSpectral +OAI.Analysis.Commutator.EmbeddedCyclicImplementation +OAI.Analysis.Commutator.EndpointElimination +OAI.Analysis.Commutator.EndpointElimination2 +OAI.Analysis.Commutator.EndpointElimination3 +OAI.Analysis.Commutator.EndpointGNS +OAI.Analysis.Commutator.EndpointGNS2 +OAI.Analysis.Commutator.EndpointModule +OAI.Analysis.Commutator.EndpointModule2 +OAI.Analysis.Commutator.EndpointRankOne +OAI.Analysis.Commutator.EqualPartitionSums +OAI.Analysis.Commutator.EqualProjectionPartition +OAI.Analysis.Commutator.EqualTraceRefinement +OAI.Analysis.Commutator.EquivariantBicommutant +OAI.Analysis.Commutator.ExponentialMomentBudget +OAI.Analysis.Commutator.FactorComparison +OAI.Analysis.Commutator.FactorCorner +OAI.Analysis.Commutator.FactorFieldBound +OAI.Analysis.Commutator.FactorFieldLocalization +OAI.Analysis.Commutator.FactorGeneratedSpace +OAI.Analysis.Commutator.FactorMetric +OAI.Analysis.Commutator.FactorModelMain +OAI.Analysis.Commutator.FaithfulNormalFunctional +OAI.Analysis.Commutator.FaithfulNormalRepresentationLinks +OAI.Analysis.Commutator.FaithfulNormalStateProducer +OAI.Analysis.Commutator.FaithfulPositive +OAI.Analysis.Commutator.FaithfulVectorGNS +OAI.Analysis.Commutator.FejerTest +OAI.Analysis.Commutator.FiberCommutator +OAI.Analysis.Commutator.FiberCommutes +OAI.Analysis.Commutator.FiberFactorProducer +OAI.Analysis.Commutator.FieldAdjoint +OAI.Analysis.Commutator.FieldAlgebra +OAI.Analysis.Commutator.FieldBicommutant +OAI.Analysis.Commutator.FieldMembership +OAI.Analysis.Commutator.FieldNormClosure +OAI.Analysis.Commutator.FieldUniqueness +OAI.Analysis.Commutator.FiniteCancellation +OAI.Analysis.Commutator.FiniteDimensionalAverage +OAI.Analysis.Commutator.FiniteDimensionalMain +OAI.Analysis.Commutator.FiniteFactorComparison +OAI.Analysis.Commutator.FiniteFactorCornerTransport +OAI.Analysis.Commutator.FiniteFactorMatrices +OAI.Analysis.Commutator.FiniteFactorTrace +OAI.Analysis.Commutator.FiniteFactorUnitary +OAI.Analysis.Commutator.FiniteFullUnitaryTests +OAI.Analysis.Commutator.FiniteFunctionalFactorization +OAI.Analysis.Commutator.FiniteHankel +OAI.Analysis.Commutator.FiniteMatrixSmallCorner +OAI.Analysis.Commutator.FiniteNoReplicas +OAI.Analysis.Commutator.FinitePairings +OAI.Analysis.Commutator.FinitePairings2 +OAI.Analysis.Commutator.FinitePairings3 +OAI.Analysis.Commutator.FiniteRectangularBound +OAI.Analysis.Commutator.FiniteRectangularContraction +OAI.Analysis.Commutator.FiniteSmallCorner +OAI.Analysis.Commutator.FiniteSquareConditionalBound +OAI.Analysis.Commutator.FiniteSquareContraction +OAI.Analysis.Commutator.FiniteStandardCompression +OAI.Analysis.Commutator.FiniteStandardGauge +OAI.Analysis.Commutator.FiniteStandardMainInterface +OAI.Analysis.Commutator.FiniteStandardRange +OAI.Analysis.Commutator.FiniteStandardRepresented +OAI.Analysis.Commutator.FiniteStandardUnconditional +OAI.Analysis.Commutator.FiniteStrongTest +OAI.Analysis.Commutator.FiniteSupportFactorization +OAI.Analysis.Commutator.FiniteTestCompletion +OAI.Analysis.Commutator.FiniteTestHahnBanach +OAI.Analysis.Commutator.FiniteTestPatching +OAI.Analysis.Commutator.FiniteTrace +OAI.Analysis.Commutator.FiniteVectorLpConvergence +OAI.Analysis.Commutator.FiniteWordMaximalPatching +OAI.Analysis.Commutator.FiniteWordPatchProducer +OAI.Analysis.Commutator.FiniteWordTelescoping +OAI.Analysis.Commutator.FreeAction +OAI.Analysis.Commutator.FreeActionBlock +OAI.Analysis.Commutator.FreeActionCovariance +OAI.Analysis.Commutator.FreeActionGroup +OAI.Analysis.Commutator.FreeActionUnitary +OAI.Analysis.Commutator.FreeActualCovariance +OAI.Analysis.Commutator.FreeActualStructure +OAI.Analysis.Commutator.FreeBaseCompression +OAI.Analysis.Commutator.FreeBlockTensor +OAI.Analysis.Commutator.FreeBlockTensor2 +OAI.Analysis.Commutator.FreeBlockTensor3 +OAI.Analysis.Commutator.FreeBlockTensor4 +OAI.Analysis.Commutator.FreeBlockWords +OAI.Analysis.Commutator.FreeBlockWords2 +OAI.Analysis.Commutator.FreeCompressionNorm +OAI.Analysis.Commutator.FreeCornerFromUnitary +OAI.Analysis.Commutator.FreeCovariance +OAI.Analysis.Commutator.FreeCreation +OAI.Analysis.Commutator.FreeDihedralColumns +OAI.Analysis.Commutator.FreeDihedralEntries +OAI.Analysis.Commutator.FreeExpectation +OAI.Analysis.Commutator.FreeFejerNorm +OAI.Analysis.Commutator.FreeHankelBound +OAI.Analysis.Commutator.FreeHankelEntries +OAI.Analysis.Commutator.FreeHilbertEntries +OAI.Analysis.Commutator.FreeInnerFamily +OAI.Analysis.Commutator.FreeLetterIntertwine +OAI.Analysis.Commutator.FreeMoments +OAI.Analysis.Commutator.FreeMomentsMonotone +OAI.Analysis.Commutator.FreeMomentsTransport +OAI.Analysis.Commutator.FreeNormalizedColumns +OAI.Analysis.Commutator.FreeNormalizer +OAI.Analysis.Commutator.FreeOriginalBound +OAI.Analysis.Commutator.FreePositionObstruction +OAI.Analysis.Commutator.FreePropagation +OAI.Analysis.Commutator.FreePropagationCorner +OAI.Analysis.Commutator.FreePropagationEstimate +OAI.Analysis.Commutator.FreePropagationStage +OAI.Analysis.Commutator.FreeRepeatedWords +OAI.Analysis.Commutator.FreeSequenceUnitary +OAI.Analysis.Commutator.FreeStageAverage +OAI.Analysis.Commutator.FreeStageHankel +OAI.Analysis.Commutator.FreeSymmetrization +OAI.Analysis.Commutator.FreeSymmetry +OAI.Analysis.Commutator.FreeSymmetry10 +OAI.Analysis.Commutator.FreeSymmetry11 +OAI.Analysis.Commutator.FreeSymmetry12 +OAI.Analysis.Commutator.FreeSymmetry13 +OAI.Analysis.Commutator.FreeSymmetry14 +OAI.Analysis.Commutator.FreeSymmetry15 +OAI.Analysis.Commutator.FreeSymmetry16 +OAI.Analysis.Commutator.FreeSymmetry2 +OAI.Analysis.Commutator.FreeSymmetry3 +OAI.Analysis.Commutator.FreeSymmetry4 +OAI.Analysis.Commutator.FreeSymmetry5 +OAI.Analysis.Commutator.FreeSymmetry6 +OAI.Analysis.Commutator.FreeSymmetry7 +OAI.Analysis.Commutator.FreeSymmetry8 +OAI.Analysis.Commutator.FreeSymmetry9 +OAI.Analysis.Commutator.FreeWordDecomposition +OAI.Analysis.Commutator.FreeWordTensor +OAI.Analysis.Commutator.FullCentralSupportLinks +OAI.Analysis.Commutator.GNSCornerTransport +OAI.Analysis.Commutator.GNSVectorEmbedding +OAI.Analysis.Commutator.GNSVectorUnitary +OAI.Analysis.Commutator.GeneratedFreePair +OAI.Analysis.Commutator.GeneratedMatrixBicommutant +OAI.Analysis.Commutator.GramBounds +OAI.Analysis.Commutator.HaarSequence +OAI.Analysis.Commutator.HankelAlgebra +OAI.Analysis.Commutator.HermitianAlphabet +OAI.Analysis.Commutator.HermitianAlphabet2 +OAI.Analysis.Commutator.HilbertBiprod +OAI.Analysis.Commutator.HilbertBiprodProjections +OAI.Analysis.Commutator.HilbertBlocks +OAI.Analysis.Commutator.HilbertDiagonal +OAI.Analysis.Commutator.HilbertFiniteMaps +OAI.Analysis.Commutator.HilbertMatrixCorner +OAI.Analysis.Commutator.HilbertModuleExtension +OAI.Analysis.Commutator.HilbertModuleSchroederBernstein +OAI.Analysis.Commutator.HilbertPadding +OAI.Analysis.Commutator.HilbertPair +OAI.Analysis.Commutator.HilbertSequence +OAI.Analysis.Commutator.HilbertSequenceOperator +OAI.Analysis.Commutator.HilbertStrong +OAI.Analysis.Commutator.HilbertTensors +OAI.Analysis.Commutator.HilbertTensors2 +OAI.Analysis.Commutator.HilbertTensors3 +OAI.Analysis.Commutator.HilbertTensors4 +OAI.Analysis.Commutator.HilbertTensors5 +OAI.Analysis.Commutator.HomogeneousBound +OAI.Analysis.Commutator.InfiniteAmplification +OAI.Analysis.Commutator.InfiniteBoundTransfer +OAI.Analysis.Commutator.InfiniteCenter +OAI.Analysis.Commutator.InfiniteDiagonalRange +OAI.Analysis.Commutator.InfiniteLinkColumn +OAI.Analysis.Commutator.InfiniteReindex +OAI.Analysis.Commutator.InfiniteSeparable +OAI.Analysis.Commutator.InfiniteUnitary +OAI.Analysis.Commutator.IntertwinerCompression +OAI.Analysis.Commutator.IntertwinerMatrixTransfer +OAI.Analysis.Commutator.IntertwinerSeminorm +OAI.Analysis.Commutator.InvariantForms +OAI.Analysis.Commutator.InvariantSum +OAI.Analysis.Commutator.InverseLimit +OAI.Analysis.Commutator.IrreducibleMatrixTower +OAI.Analysis.Commutator.IrreducibleTowerAveraging +OAI.Analysis.Commutator.IsometryCompression +OAI.Analysis.Commutator.KaplanskyDensity +OAI.Analysis.Commutator.KaplanskyFull +OAI.Analysis.Commutator.KaplanskyFullRange +OAI.Analysis.Commutator.KaplanskyNet +OAI.Analysis.Commutator.KaplanskyRange +OAI.Analysis.Commutator.KaplanskyRational +OAI.Analysis.Commutator.KaplanskySelfAdjoint +OAI.Analysis.Commutator.KaplanskyStarHomNet +OAI.Analysis.Commutator.L2FiniteSum +OAI.Analysis.Commutator.L2InfiniteSum +OAI.Analysis.Commutator.L2InfiniteSumCoordinates +OAI.Analysis.Commutator.LittleGrothendieck +OAI.Analysis.Commutator.LittleGrothendieckSequence +OAI.Analysis.Commutator.LocalQuantization +OAI.Analysis.Commutator.Main +OAI.Analysis.Commutator.MainCommutantDistance +OAI.Analysis.Commutator.MainMatrix +OAI.Analysis.Commutator.MatrixAlgebraDensity +OAI.Analysis.Commutator.MatrixAlgebraEquiv +OAI.Analysis.Commutator.MatrixApproximation +OAI.Analysis.Commutator.MatrixClassification +OAI.Analysis.Commutator.MatrixColumnCorner +OAI.Analysis.Commutator.MatrixCommute +OAI.Analysis.Commutator.MatrixCompactGroup +OAI.Analysis.Commutator.MatrixCornerExtension +OAI.Analysis.Commutator.MatrixCornerHilbert +OAI.Analysis.Commutator.MatrixCornerInclusion +OAI.Analysis.Commutator.MatrixCutEmbedding +OAI.Analysis.Commutator.MatrixDiagonal +OAI.Analysis.Commutator.MatrixDiffuse +OAI.Analysis.Commutator.MatrixDiffuseTransfer +OAI.Analysis.Commutator.MatrixEntryWOT +OAI.Analysis.Commutator.MatrixExpectation +OAI.Analysis.Commutator.MatrixExpectationNested +OAI.Analysis.Commutator.MatrixField +OAI.Analysis.Commutator.MatrixFlatten +OAI.Analysis.Commutator.MatrixFlattenRepresentation +OAI.Analysis.Commutator.MatrixFreePositionProducer +OAI.Analysis.Commutator.MatrixFreeSymmetry +OAI.Analysis.Commutator.MatrixGNS +OAI.Analysis.Commutator.MatrixGNSCornerBound +OAI.Analysis.Commutator.MatrixGNSRealCorner +OAI.Analysis.Commutator.MatrixGNSUnitary +OAI.Analysis.Commutator.MatrixInclusion +OAI.Analysis.Commutator.MatrixIndexEquiv +OAI.Analysis.Commutator.MatrixModules +OAI.Analysis.Commutator.MatrixNormalTrace +OAI.Analysis.Commutator.MatrixPadding +OAI.Analysis.Commutator.MatrixProjectionDiagonal +OAI.Analysis.Commutator.MatrixReindexBound +OAI.Analysis.Commutator.MatrixRowCorner +OAI.Analysis.Commutator.MatrixScalar +OAI.Analysis.Commutator.MatrixScalarApproximation +OAI.Analysis.Commutator.MatrixStageExtension +OAI.Analysis.Commutator.MatrixStageGNSGeneration +OAI.Analysis.Commutator.MatrixStandardForm +OAI.Analysis.Commutator.MatrixTensor +OAI.Analysis.Commutator.MatrixTensorRange +OAI.Analysis.Commutator.MatrixTower +OAI.Analysis.Commutator.MatrixTowerAverage +OAI.Analysis.Commutator.MatrixTowerClosure +OAI.Analysis.Commutator.MatrixTowerDiffuse +OAI.Analysis.Commutator.MatrixTowerGNS +OAI.Analysis.Commutator.MatrixTowerInclusion +OAI.Analysis.Commutator.MatrixTowerIrreducible +OAI.Analysis.Commutator.MatrixTrace +OAI.Analysis.Commutator.MatrixTraceFaithful +OAI.Analysis.Commutator.MatrixUnitaryAlphabet +OAI.Analysis.Commutator.MatrixUnits +OAI.Analysis.Commutator.MatrixVectorTrace +OAI.Analysis.Commutator.MatrixVonNeumann +OAI.Analysis.Commutator.MaximalAbelianTransport +OAI.Analysis.Commutator.MetricSimilarity +OAI.Analysis.Commutator.MinimalCorner +OAI.Analysis.Commutator.MinimalNormCompact +OAI.Analysis.Commutator.MinimalOrbit +OAI.Analysis.Commutator.MinimalProjection +OAI.Analysis.Commutator.ModuleZeroExtension +OAI.Analysis.Commutator.MultilinearTensors +OAI.Analysis.Commutator.NonfiniteFactor +OAI.Analysis.Commutator.NonseparableReduction +OAI.Analysis.Commutator.NormSeparableFixedPoint +OAI.Analysis.Commutator.NormalBiprodGNS +OAI.Analysis.Commutator.NormalCopiesAverage +OAI.Analysis.Commutator.NormalCornerExtension +OAI.Analysis.Commutator.NormalFreeCorner +OAI.Analysis.Commutator.NormalGNS +OAI.Analysis.Commutator.NormalGNSClosure +OAI.Analysis.Commutator.NormalGNSContinuity +OAI.Analysis.Commutator.NormalGNSSeparable +OAI.Analysis.Commutator.NormalOperatorHom +OAI.Analysis.Commutator.NormalOriginalTower +OAI.Analysis.Commutator.NormalPredual +OAI.Analysis.Commutator.NormalRelativeCommutant +OAI.Analysis.Commutator.NormalRepresentationColumns +OAI.Analysis.Commutator.NormalRepresentationLinks +OAI.Analysis.Commutator.NormalSubalgebra +OAI.Analysis.Commutator.NormalTraceProjection +OAI.Analysis.Commutator.NormalTracedFactorMain +OAI.Analysis.Commutator.NormalizedTowerFreePosition +OAI.Analysis.Commutator.NormalizedTrace +OAI.Analysis.Commutator.OperatorAmplification +OAI.Analysis.Commutator.OperatorSystem +OAI.Analysis.Commutator.OrbitFixedTrace +OAI.Analysis.Commutator.OrbitStateHull +OAI.Analysis.Commutator.OrthogonalCountability +OAI.Analysis.Commutator.OrthogonalLinkFamily +OAI.Analysis.Commutator.OrthogonalLinkSums +OAI.Analysis.Commutator.OrthogonalRank +OAI.Analysis.Commutator.PairTrace +OAI.Analysis.Commutator.PairTrace2 +OAI.Analysis.Commutator.PairingElimination +OAI.Analysis.Commutator.PairingOperators +OAI.Analysis.Commutator.Pairings +OAI.Analysis.Commutator.PartialDecomposition +OAI.Analysis.Commutator.PartialDecompositionCountable +OAI.Analysis.Commutator.PartialIsometryMaximal +OAI.Analysis.Commutator.PartialIsometryOrder +OAI.Analysis.Commutator.PartialMomentBudget +OAI.Analysis.Commutator.PartialUnitaryAlgebra +OAI.Analysis.Commutator.PartialUnitaryChain +OAI.Analysis.Commutator.PartialUnitaryCompletion +OAI.Analysis.Commutator.PartialUnitaryHom +OAI.Analysis.Commutator.PartialUnitaryOrder +OAI.Analysis.Commutator.PartialUnitaryWords +OAI.Analysis.Commutator.PartialWordContinuity +OAI.Analysis.Commutator.PartialWordPerturbation +OAI.Analysis.Commutator.PartialWordReindex +OAI.Analysis.Commutator.PartitionRank +OAI.Analysis.Commutator.PartitionRankComparison +OAI.Analysis.Commutator.PaulsenDilation +OAI.Analysis.Commutator.PaulsenExtension +OAI.Analysis.Commutator.PaulsenPositive +OAI.Analysis.Commutator.PaulsenSystem +OAI.Analysis.Commutator.PointwiseLinearLift +OAI.Analysis.Commutator.PointwiseStarHom +OAI.Analysis.Commutator.PolarDecomposition +OAI.Analysis.Commutator.PolarExtension +OAI.Analysis.Commutator.PolarSupport +OAI.Analysis.Commutator.PositiveCauchySchwarz +OAI.Analysis.Commutator.PositiveExtensionComplex +OAI.Analysis.Commutator.PositiveExtensionReal +OAI.Analysis.Commutator.PositiveWOT +OAI.Analysis.Commutator.ProjectionAddition +OAI.Analysis.Commutator.ProjectionBlocks +OAI.Analysis.Commutator.ProjectionChains +OAI.Analysis.Commutator.ProjectionCommutant +OAI.Analysis.Commutator.ProjectionComplements +OAI.Analysis.Commutator.ProjectionDimensionTopology +OAI.Analysis.Commutator.ProjectionDimensionUnitary +OAI.Analysis.Commutator.ProjectionEquivalence +OAI.Analysis.Commutator.ProjectionFaithfulFunctional +OAI.Analysis.Commutator.ProjectionJoin +OAI.Analysis.Commutator.ProjectionLifts +OAI.Analysis.Commutator.ProjectionNormalBridge +OAI.Analysis.Commutator.ProjectionNormalPositive +OAI.Analysis.Commutator.ProjectionNormalStrong +OAI.Analysis.Commutator.ProjectionPartition +OAI.Analysis.Commutator.ProjectionRounding +OAI.Analysis.Commutator.ProjectionSchroederBernstein +OAI.Analysis.Commutator.ProjectionShift +OAI.Analysis.Commutator.ProjectionStrong +OAI.Analysis.Commutator.ProjectionSumEquivalence +OAI.Analysis.Commutator.ProjectionWeighted +OAI.Analysis.Commutator.ProperIsometryReplicas +OAI.Analysis.Commutator.ProperlyInfinite +OAI.Analysis.Commutator.ProperlyInfiniteBound +OAI.Analysis.Commutator.ProperlyInfiniteMain +OAI.Analysis.Commutator.RankOneFactor +OAI.Analysis.Commutator.RationalDense +OAI.Analysis.Commutator.RationalStarExtension +OAI.Analysis.Commutator.RectangularColumn +OAI.Analysis.Commutator.RectangularTensors +OAI.Analysis.Commutator.ReducingCompression +OAI.Analysis.Commutator.ReducingMatrix +OAI.Analysis.Commutator.ReducingRepresentation +OAI.Analysis.Commutator.Regroup +OAI.Analysis.Commutator.RelativeCornerPhase +OAI.Analysis.Commutator.RelativeCornerQuantization +OAI.Analysis.Commutator.RelativeEquivFreePosition +OAI.Analysis.Commutator.RelativeMatrix +OAI.Analysis.Commutator.RelativeSequenceRange +OAI.Analysis.Commutator.RelativeTowerFreePosition +OAI.Analysis.Commutator.ReplicaPacking +OAI.Analysis.Commutator.RepresentationFieldTests +OAI.Analysis.Commutator.RepresentationMatrixNorm +OAI.Analysis.Commutator.RepresentedCornerBound +OAI.Analysis.Commutator.RepresentedFactorTransport +OAI.Analysis.Commutator.RepresentedLocalModule +OAI.Analysis.Commutator.RepresentedTowerAverage +OAI.Analysis.Commutator.RightCopies +OAI.Analysis.Commutator.RowOperator +OAI.Analysis.Commutator.ScalarField +OAI.Analysis.Commutator.ScalarIndicator +OAI.Analysis.Commutator.ScalarIndicatorAdjoint +OAI.Analysis.Commutator.ScalarUltralimit +OAI.Analysis.Commutator.SchurTransfer +OAI.Analysis.Commutator.SchurWeylDevelopment +OAI.Analysis.Commutator.SelfAdjointSpectral +OAI.Analysis.Commutator.SeparableBoundTransfer +OAI.Analysis.Commutator.SeparableFactorMain +OAI.Analysis.Commutator.SeparableReducingHull +OAI.Analysis.Commutator.SeparableSmall +OAI.Analysis.Commutator.SeparableTestGeometry +OAI.Analysis.Commutator.SeparableUniverseTransfer +OAI.Analysis.Commutator.SimilarityMidpointObstruction +OAI.Analysis.Commutator.SmoothingSubsequence +OAI.Analysis.Commutator.SpectralCompression +OAI.Analysis.Commutator.SpectralCutoff +OAI.Analysis.Commutator.SpectralExhaustion +OAI.Analysis.Commutator.SpectralStep +OAI.Analysis.Commutator.SpectralThreshold +OAI.Analysis.Commutator.SpectralThresholdBounds +OAI.Analysis.Commutator.SquareZeroMaximal +OAI.Analysis.Commutator.SquareZeroPolar +OAI.Analysis.Commutator.StableCenterRange +OAI.Analysis.Commutator.StableCentralSpectral +OAI.Analysis.Commutator.StableGNSModule +OAI.Analysis.Commutator.StableModelBound +OAI.Analysis.Commutator.StableScalarGeometry +OAI.Analysis.Commutator.StableSpectralUnitary +OAI.Analysis.Commutator.StableUniversalAssembly +OAI.Analysis.Commutator.StageAverage +OAI.Analysis.Commutator.StageDensity +OAI.Analysis.Commutator.StageGeneration +OAI.Analysis.Commutator.StandardTrace +OAI.Analysis.Commutator.StarField +OAI.Analysis.Commutator.StarHomFieldLip +OAI.Analysis.Commutator.StarHomFieldRaw +OAI.Analysis.Commutator.StinespringAction +OAI.Analysis.Commutator.StinespringDilation +OAI.Analysis.Commutator.StinespringKernel +OAI.Analysis.Commutator.StinespringRepresentation +OAI.Analysis.Commutator.StrongContinuity +OAI.Analysis.Commutator.StrongContractionLimit +OAI.Analysis.Commutator.StrongDenseTests +OAI.Analysis.Commutator.SubfactorExpectation +OAI.Analysis.Commutator.TensorActions +OAI.Analysis.Commutator.TensorAdjoints +OAI.Analysis.Commutator.TensorCompletion +OAI.Analysis.Commutator.TensorDevelopment +OAI.Analysis.Commutator.TensorMultiplicity +OAI.Analysis.Commutator.TensorMultiplicity2 +OAI.Analysis.Commutator.TensorPermutations +OAI.Analysis.Commutator.TensorPermutations2 +OAI.Analysis.Commutator.TensorPermutations3 +OAI.Analysis.Commutator.TensorPowerCompletion +OAI.Analysis.Commutator.TightField +OAI.Analysis.Commutator.TraceDimension +OAI.Analysis.Commutator.TraceEquivGNS +OAI.Analysis.Commutator.TraceFaithfulHomInjective +OAI.Analysis.Commutator.TracedSeparableFactorMain +OAI.Analysis.Commutator.TracialAdjoint +OAI.Analysis.Commutator.TracialCommutation +OAI.Analysis.Commutator.TracialConjugation +OAI.Analysis.Commutator.TracialConstantFreeObstruction +OAI.Analysis.Commutator.TracialDCorner +OAI.Analysis.Commutator.TracialDevelopment +OAI.Analysis.Commutator.TracialDoubleCompression +OAI.Analysis.Commutator.TracialFreeOriginal +OAI.Analysis.Commutator.TracialFreePositionCriterion +OAI.Analysis.Commutator.TracialGNSCorners +OAI.Analysis.Commutator.TracialGeneratedAlgebra +OAI.Analysis.Commutator.TracialGeneratedFreeBound +OAI.Analysis.Commutator.TracialL2Continuity +OAI.Analysis.Commutator.TracialL2Tools +OAI.Analysis.Commutator.TracialRangeCommutation +OAI.Analysis.Commutator.TracialRelativeCommutant +OAI.Analysis.Commutator.TracialRepresentedCorner +OAI.Analysis.Commutator.TracialRightClosure +OAI.Analysis.Commutator.TracialSequence +OAI.Analysis.Commutator.TracialSequenceCompression +OAI.Analysis.Commutator.TracialSequenceRight +OAI.Analysis.Commutator.TracialSequenceTrace +OAI.Analysis.Commutator.TracialSmallCorners +OAI.Analysis.Commutator.TracialUltrapower +OAI.Analysis.Commutator.TracialUltrapowerTransfer +OAI.Analysis.Commutator.TracialVectorSubalgebra +OAI.Analysis.Commutator.TriangularCb +OAI.Analysis.Commutator.TriangularMetric +OAI.Analysis.Commutator.TwoByTwoPositive +OAI.Analysis.Commutator.TwoIsometries +OAI.Analysis.Commutator.UltrafilterDiagonal +OAI.Analysis.Commutator.UniformCommutantApproximation +OAI.Analysis.Commutator.UnitaryBoundTransfer +OAI.Analysis.Commutator.UnitaryCenterTransport +OAI.Analysis.Commutator.UnitaryCommuteNorm +OAI.Analysis.Commutator.UnitaryDualAction +OAI.Analysis.Commutator.UnitaryEquivMoments +OAI.Analysis.Commutator.UnitaryHaar +OAI.Analysis.Commutator.UnitaryMainTransport +OAI.Analysis.Commutator.UnitaryOrbitHull +OAI.Analysis.Commutator.UnitarySequence +OAI.Analysis.Commutator.UniversalMain +OAI.Analysis.Commutator.VectorFreeGeneration +OAI.Analysis.Commutator.VectorFreeOriginalBound +OAI.Analysis.Commutator.VectorStageGeneration +OAI.Analysis.Commutator.VonNeumannCStar +OAI.Analysis.Commutator.WOTBallSeparable +OAI.Analysis.Commutator.WOTCompact +OAI.Analysis.Commutator.WOTFunctionals +OAI.Analysis.Commutator.WeakConvergence +OAI.Analysis.Commutator.WeakDualHull +OAI.Analysis.Commutator.WeakOperatorAlgebra +OAI.Analysis.Commutator.WeakOperatorIntegral +OAI.Analysis.Commutator.WeakOperatorLimit +OAI.Analysis.Commutator.WeakZeroSelection +OAI.Analysis.Commutator.WeightedSubsequence +OAI.Analysis.Commutator.WordCoefficientContinuity +OAI.Analysis.Commutator.WordPermutations +OAI.Analysis.Commutator.WordScaling +OAI.Analysis.Commutator.WordTopology +OAI.Analysis.Commutator.WordTopology2 +OAI.Analysis.Commutator.WordTopology3 diff --git a/tasks/uniform-commutator/solution/reference.py b/tasks/uniform-commutator/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/uniform-commutator/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/uniform-commutator/solution/solve.sh b/tasks/uniform-commutator/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..fd3a66afec2fadae24efb3751c0871eb8992d45b --- /dev/null +++ b/tasks/uniform-commutator/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniformCommutator, i.e. module OAI.Analysis.Commutator.Main and the +# 656 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.Commutator.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniformCommutator" diff --git a/tasks/uniform-commutator/task.toml b/tasks/uniform-commutator/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..33eda0a04767639f815a60923ea6498a227b9eea --- /dev/null +++ b/tasks/uniform-commutator/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/uniform-commutator" +version = "1.0.0" +description = "Prove UniformCommutator (openai/math family 288: Kadison's similarity conjecture) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniformCommutator.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniformCommutator" +family = "288" +family_title = "Kadison's similarity conjecture" +subject = "Operator algebras" +theorems = ["OAI.Kadison.uniform_commutator"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.Commutator.Main" +reference_modules = 656 +reference_lean_bytes = 2642027 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 7060 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14077 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/uniform-commutator/tests/Challenge.lean b/tasks/uniform-commutator/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..f94d114e9d34bcd0def15bff6af942d8a40a0643 --- /dev/null +++ b/tasks/uniform-commutator/tests/Challenge.lean @@ -0,0 +1,40 @@ +import Mathlib + +namespace OAI + +noncomputable section +universe u v +namespace Kadison + +variable {K : Type u} [NormedAddCommGroup K] [InnerProductSpace ℂ K] + [CompleteSpace K] + +def commutatorSeminorm (P : VonNeumannAlgebra K) (Y : K →L[ℂ] K) : ℝ := + sSup {r : ℝ | ∃ a : K →L[ℂ] K, a ∈ P ∧ ‖a‖ ≤ 1 ∧ r = ‖Y * a - a * Y‖} + +def matrixOperator (h : ℕ) (X : Matrix (Fin h) (Fin h) (K →L[ℂ] K)) : + (PiLp 2 fun _ : Fin h => K) →L[ℂ] (PiLp 2 fun _ : Fin h => K) := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin h => K)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun i => ∑ j : Fin h, + (X i j).comp (PiLp.proj 2 (fun _ : Fin h => K) j))) + +def diagonalAmplification (h : ℕ) (Y : K →L[ℂ] K) : + (PiLp 2 fun _ : Fin h => K) →L[ℂ] (PiLp 2 fun _ : Fin h => K) := + (PiLp.continuousLinearEquiv 2 ℂ (fun _ : Fin h => K)).symm.toContinuousLinearMap.comp + (ContinuousLinearMap.pi (fun i => Y.comp (PiLp.proj 2 (fun _ : Fin h => K) i))) + +theorem uniform_commutator : + ∃ C : ℝ, 0 ≤ C ∧ ∀ (K : Type u) [NormedAddCommGroup K] [InnerProductSpace ℂ K] + [CompleteSpace K] (P : VonNeumannAlgebra K) (Y : K →L[ℂ] K) + (h : ℕ), 1 ≤ h → ∀ (X : Matrix (Fin h) (Fin h) (K →L[ℂ] K)), + (∀ i j, X i j ∈ P) → + ‖diagonalAmplification h Y * matrixOperator h X - + matrixOperator h X * diagonalAmplification h Y‖ ≤ + C * commutatorSeminorm P Y * ‖matrixOperator h X‖ := by + sorry + +end Kadison + +end + +end OAI diff --git a/tasks/uniform-commutator/tests/grade.py b/tasks/uniform-commutator/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/uniform-commutator/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/uniform-commutator/tests/task.json b/tasks/uniform-commutator/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0c0c0321a50f91c1ac4f69d62d6bc38ff5bec903 --- /dev/null +++ b/tasks/uniform-commutator/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniformCommutator", + "comparator": { + "theorem_names": [ + "OAI.Kadison.uniform_commutator" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13177 +} \ No newline at end of file diff --git a/tasks/uniform-commutator/tests/test.sh b/tasks/uniform-commutator/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/uniform-commutator/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/uniform-gamma/environment/Dockerfile b/tasks/uniform-gamma/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/uniform-gamma/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/uniform-gamma/environment/fetch_mathlib.sh b/tasks/uniform-gamma/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/uniform-gamma/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/uniform-gamma/environment/lake-manifest.json b/tasks/uniform-gamma/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/uniform-gamma/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/uniform-gamma/environment/lakefile.lean b/tasks/uniform-gamma/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/uniform-gamma/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/uniform-gamma/environment/lean_setup.sh b/tasks/uniform-gamma/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/uniform-gamma/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/uniform-gamma/environment/pack_submission.py b/tasks/uniform-gamma/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/uniform-gamma/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/uniform-gamma/instruction.md b/tasks/uniform-gamma/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..7fdd9bba5f2dacff9c4cd47cfc0c43be70ac6955 --- /dev/null +++ b/tasks/uniform-gamma/instruction.md @@ -0,0 +1,658 @@ +# openai/math challenge `UniformGamma` (family 291) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 291 of the release, *Toms–Winter and equivariant Jiang–Su stability* +(Operator algebras). The family as a whole: Proves equivariant Jiang–Su stability for every countable discrete amenable group action on a simple separable unital infinite-dimensional nuclear stably finite Jiang–Su-stable $C^*$-algebra, resolving this case of Szabo's conjecture without restrictions on trace dynamics. The family also proves the unital Toms–Winter conjecture, equating strict comparison, finite nuclear dimension and Jiang–Su stability in the simple separable unital infinite-dimensional nuclear setting. + +The challenge is `UniformGamma`, also at `/opt/openai-math/challenges/UniformGamma.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +/-! +The final claim constructs the tracial quotients and states the original gamma assertion. +`Analysis.TracialSplitting.Challenge.main_iff_original` verifies statement preservation. +-/ + +universe uA uD uE uI uR uX u v + +namespace Pureness + +open scoped ComplexOrder + +structure CStarAlgebraNorm (R : Type uR) [Ring R] [StarRing R] [Algebra ℂ R] + extends AlgebraNorm ℂ R where + cstar : ∀ x, toAlgebraNorm (star x * x) = toAlgebraNorm x * toAlgebraNorm x + +structure TracialState (A : Type uA) [CStarAlgebra A] [PartialOrder A] where + functional : A →ₚ[ℂ] ℂ + normalized : functional 1 = 1 + tracial : ∀ a b : A, functional (a * b) = functional (b * a) + +structure ClosedStarIdeal (D : Type uD) [CStarAlgebra D] where + ideal : TwoSidedIdeal D + star_mem : ∀ {u : D}, u ∈ ideal → star u ∈ ideal + isClosed : IsClosed (ideal : Set D) + +end Pureness + +universe uNuclear + +namespace ComparatorModel + +namespace Pureness + +open scoped TensorProduct ComplexOrder + +abbrev CStarAlgebraNorm := @_root_.OAI.Pureness.CStarAlgebraNorm + +def IsNuclear (A : Type u) [CStarAlgebra A] : Prop := + ∀ (B : Type v) [CStarAlgebra B], Subsingleton (CStarAlgebraNorm (A ⊗[ℂ] B)) + +abbrev TracialState := @_root_.OAI.Pureness.TracialState + +end Pureness + +namespace CurrentMain + +open _root_.OAI.ComparatorModel.Pureness + +open scoped ComplexOrder + +def RealRankZero (D : Type) [CStarAlgebra D] : Prop := + ∀ a : D, IsSelfAdjoint a → ∀ ε : ℝ, 0 < ε → + ∃ b : D, IsSelfAdjoint b ∧ (spectrum ℂ b).Finite ∧ ‖a - b‖ < ε + +def traceTwoNorm {D : Type} [CStarAlgebra D] [PartialOrder D] + (τ : TracialState D) (a : D) : ℝ := + Real.sqrt (τ.functional (star a * a)).re + +end CurrentMain + +section + +open Filter + +open scoped Topology NNReal ENNReal + +abbrev Pureness.ClosedStarIdeal := @_root_.OAI.Pureness.ClosedStarIdeal + +namespace Pureness.ClosedStarIdeal + +section + +variable {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) + +abbrev Quotient := J.ideal.ringCon.Quotient + +def quotientMap : D →ₐ[ℂ] J.Quotient := J.ideal.ringCon.mkₐ ℂ + +instance quotientStar : Star (J.Quotient) where + star := Quotient.map' star (by + intro u v h + change J.ideal.ringCon u v at h + change J.ideal.ringCon (star u) (star v) + rw [TwoSidedIdeal.rel_iff] at h ⊢ + simpa only [star_sub] using J.star_mem h) + +instance quotientStarRing : StarRing (J.Quotient) where + star_involutive x := Quotient.inductionOn' x (fun u => congrArg J.quotientMap (star_star u)) + star_mul x y := Quotient.inductionOn₂' x y (fun u v => congrArg J.quotientMap (star_mul u v)) + star_add x y := Quotient.inductionOn₂' x y (fun u v => congrArg J.quotientMap (star_add u v)) + +instance quotientStarModule : StarModule ℂ (J.Quotient) where + star_smul c x := Quotient.inductionOn' x (fun u => congrArg J.quotientMap (star_smul c u)) + +abbrev idealSubmodule : Submodule ℂ (D) := + (J.quotientMap).toLinearMap.ker + +instance idealSubmodule_closed : IsClosed (J.idealSubmodule : Set D) := by + have he : (J.idealSubmodule : Set D) = (J.ideal : Set D) := by + ext u + change J.ideal.ringCon.mk' u = J.ideal.ringCon.mk' 0 ↔ u ∈ J.ideal + exact Quotient.eq + rw [he] + exact J.isClosed + +def quotientLinearEquiv : + (D ⧸ J.idealSubmodule) ≃ₗ[ℂ] J.Quotient := + (J.quotientMap).toLinearMap.quotKerEquivOfSurjective ((J.ideal.ringCon.mkₐ_surjective (α := ℂ))) + +instance quotientNormedAddCommGroup : NormedAddCommGroup (J.Quotient) := + NormedAddCommGroup.induced _ _ (J.quotientLinearEquiv).symm + (J.quotientLinearEquiv).symm.injective + +instance quotientNormedSpace : NormedSpace ℂ (J.Quotient) := + NormedSpace.induced ℂ _ _ (J.quotientLinearEquiv).symm + +def quotientNormEquiv : J.Quotient ≃ₗᵢ[ℂ] + (D ⧸ J.idealSubmodule) where + __ := (J.quotientLinearEquiv).symm + norm_map' _ := rfl + +instance quotientCompleteSpace : CompleteSpace (J.Quotient) := + (J.quotientNormEquiv).toIsometryEquiv.completeSpace_iff.mpr inferInstance + +class NormConstruction : Prop where + mul_le : ∀ {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) (x y : J.Quotient), + ‖x*y‖ ≤ ‖x‖*‖y‖ + star_eq : ∀ {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) (x : J.Quotient), + ‖star x‖ = ‖x‖ + square_le : ∀ {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (J : ClosedStarIdeal D) (x : J.Quotient), ‖x‖ * ‖x‖ ≤ ‖star x * x‖ + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance quotientNormedRing : NormedRing (J.Quotient) where + dist_eq := dist_eq_norm_neg_add + norm_mul_le := NormConstruction.mul_le J + +instance quotientNormedAlgebra : NormedAlgebra ℂ (J.Quotient) where + norm_smul_le := norm_smul_le + +instance quotientNormedStarGroup : NormedStarGroup (J.Quotient) where + norm_star_le x := (NormConstruction.star_eq J x).le + +end + +open Filter + +open scoped Topology NNReal ENNReal + +variable {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (J : ClosedStarIdeal D) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance quotientCStarAlgebra : CStarAlgebra (J.Quotient) where + norm_mul_self_le := NormConstruction.square_le J + +end Pureness.ClosedStarIdeal + +end + +section + +open _root_.OAI.ComparatorModel.Pureness + +section UniformTraceNorm + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +def CurrentMain.familyTwoNorm (a : D) : ℝ := ⨆ i, traceTwoNorm (τ i) a + +end UniformTraceNorm + +open _root_.OAI.ComparatorModel.Pureness Filter + +open scoped Topology NNReal ENNReal + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance CurrentMain.boundedFamilyProductCStar {X : Type} {D : Type} [CStarAlgebra D] [Nontrivial D] : + CStarAlgebra (lp (fun _ : X => D) ∞) where + +section UniformNull + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +def CurrentMain.IsFamilyNull (F : Filter X) (u : X → D) : Prop := + Tendsto (fun n => familyTwoNorm τ (u n)) F (𝓝 0) + +class CurrentMain.NullConstruction : Prop where + zero : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + (F : Filter X), IsFamilyNull τ F (fun _ => 0) + add : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F v → + IsFamilyNull τ F (fun n => u n + v n) + neg : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F (fun n => -u n) + star : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F (fun n => star (u n)) + mul_left : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F v → ∀ {M : ℝ}, + (∀ n, ‖u n‖ ≤ M) → IsFamilyNull τ F (fun n => u n * v n) + mul_right : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F u → ∀ {M : ℝ}, + (∀ n, ‖v n‖ ≤ M) → IsFamilyNull τ F (fun n => u n * v n) + closed : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] (F : Filter X), + IsClosed {u : lp (fun _ : X => D) ∞ | IsFamilyNull τ F (fun n => u n)} + +variable [Nontrivial D] + +variable [ComparatorModel.CurrentMain.NullConstruction] + +def CurrentMain.familyNullTwoSided (F : Filter X) : TwoSidedIdeal (lp (fun _ : X => D) ∞) := + TwoSidedIdeal.mk' {u | IsFamilyNull τ F (fun n => u n)} + (NullConstruction.zero τ F) + (fun hu hv => NullConstruction.add τ hu hv) + (fun hu => NullConstruction.neg τ hu) + (fun {u _} hv => NullConstruction.mul_left τ hv + (lp.norm_apply_le_norm ENNReal.top_ne_zero u)) + (fun {_ v} hu => NullConstruction.mul_right τ hu + (lp.norm_apply_le_norm ENNReal.top_ne_zero v)) + +def CurrentMain.familyNullIdeal (F : Filter X) : ClosedStarIdeal (lp (fun _ : X => D) ∞) where + ideal := familyNullTwoSided τ F + star_mem := by + intro u hu + apply (TwoSidedIdeal.mem_mk' _ _ _ _ _ _ (star u)).mpr + exact NullConstruction.star τ ((TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u).mp hu) + isClosed := by + have he : (familyNullTwoSided τ F : Set (lp (fun _ : X => D) ∞)) = + {u | IsFamilyNull τ F (fun n => u n)} := by + ext u + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u + rw [he] + exact NullConstruction.closed τ F + +end UniformNull + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.CurrentMain.NullConstruction] + +def CurrentMain.IsFamilyCauchy (u : ℕ → D) : Prop := + IsFamilyNull τ (atTop : Filter (ℕ × ℕ)) (fun p => u p.1 - u p.2) + +class CurrentMain.CauchyConstruction : Prop where + const : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] (a : D), IsFamilyCauchy τ (fun _ => a) + add : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u v : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ v → IsFamilyCauchy τ (fun n => u n+v n) + star : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ (fun n => star (u n)) + mul : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u v : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ v → ∀ {M N : ℝ}, + (∀ n, ‖u n‖ ≤ M) → (∀ n, ‖v n‖ ≤ N) → IsFamilyCauchy τ (fun n => u n*v n) + closed : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] [Nontrivial D], + IsClosed {u : lp (fun _ : ℕ => D) ∞ | IsFamilyCauchy τ (fun n => u n)} + +variable [Nontrivial D] + +variable [ComparatorModel.CurrentMain.CauchyConstruction] + +def CurrentMain.familyCauchyAlgebra : StarSubalgebra ℂ (lp (fun _ : ℕ => D) ∞) where + carrier := {u | IsFamilyCauchy τ (fun n => u n)} + zero_mem' := CauchyConstruction.const τ 0 + one_mem' := CauchyConstruction.const τ 1 + add_mem' hu hv := CauchyConstruction.add τ hu hv + mul_mem' {u v} hu hv := CauchyConstruction.mul τ hu hv + (lp.norm_apply_le_norm ENNReal.top_ne_zero u) + (lp.norm_apply_le_norm ENNReal.top_ne_zero v) + algebraMap_mem' z := CauchyConstruction.const τ (algebraMap ℂ D z) + star_mem' hu := CauchyConstruction.star τ hu + +instance CurrentMain.familyCauchy_complete : CompleteSpace (familyCauchyAlgebra τ) := + (CauchyConstruction.closed τ).completeSpace_coe + +instance CurrentMain.familyCauchy_cstar : CStarAlgebra (familyCauchyAlgebra τ) where + +def CurrentMain.familyCauchyNullIdeal : ClosedStarIdeal (familyCauchyAlgebra τ) where + ideal := TwoSidedIdeal.comap (familyCauchyAlgebra τ).val.toRingHom + (familyNullIdeal τ atTop).ideal + star_mem := by + intro u hu + apply (familyNullIdeal τ atTop).star_mem hu + isClosed := by + exact (familyNullIdeal τ atTop).isClosed.preimage + (continuous_subtype_val : Continuous (fun u : familyCauchyAlgebra τ => u.1)) + +abbrev CurrentMain.UniformTracialCompletion := (familyCauchyNullIdeal τ).Quotient + +end + +section + +open scoped ComplexOrder + +variable {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] + +instance Pureness.ClosedStarIdeal.quotientOrder (J : ClosedStarIdeal D) : PartialOrder J.Quotient := + CStarAlgebra.spectralOrder _ + +instance Pureness.ClosedStarIdeal.quotientStarOrdered (J : ClosedStarIdeal D) : StarOrderedRing J.Quotient := + CStarAlgebra.spectralOrderedRing _ + +variable (J : Pureness.ClosedStarIdeal D) + +variable (τ : Pureness.TracialState D) (hτ : ∀ a ∈ J.ideal, τ.functional a = 0) + +def Pureness.ClosedStarIdeal.descendedValue : J.Quotient → ℂ := Quotient.lift τ.functional (by + intro u v huv + change J.ideal.ringCon u v at huv + rw [TwoSidedIdeal.rel_iff] at huv + have h := hτ (u-v) huv + rw [map_sub, sub_eq_zero] at h + exact h) + +def Pureness.ClosedStarIdeal.descendedLinear : J.Quotient →ₗ[ℂ] ℂ where + toFun := J.descendedValue τ hτ + map_add' x y := Quotient.inductionOn₂' x y (fun u v => τ.functional.map_add u v) + map_smul' c x := Quotient.inductionOn' x (fun u => τ.functional.map_smul c u) + +def Pureness.ClosedStarIdeal.descendedTrace : TracialState J.Quotient where + functional := { J.descendedLinear τ hτ with + monotone' := by + intro x y hxy + apply sub_nonneg.mp + change 0 ≤ J.descendedLinear τ hτ y - J.descendedLinear τ hτ x + rw [← map_sub] + obtain ⟨z,hz⟩ := CStarAlgebra.nonneg_iff_eq_star_mul_self.mp (sub_nonneg.mpr hxy) + rw [hz] + induction z using Quotient.inductionOn' with + | h u => exact τ.functional.map_nonneg (star_mul_self_nonneg u) } + normalized := τ.normalized + tracial x y := Quotient.inductionOn₂' x y (fun u v => τ.tracial u v) + +end + +section + +open _root_.OAI.ComparatorModel.Pureness Filter + +open scoped Topology NNReal ENNReal ComplexOrder + +section UltraTrace + +variable {D : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] + +variable (θ : X → TracialState D) (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] + +instance CurrentMain.boundedFamilyProductOrder : PartialOrder (lp (fun _ : X => D) ∞) := + CStarAlgebra.spectralOrder _ + +instance CurrentMain.boundedFamilyProductStarOrdered : StarOrderedRing (lp (fun _ : X => D) ∞) := + CStarAlgebra.spectralOrderedRing _ + +def CurrentMain.ultraTraceValue (u : lp (fun _ : X => D) ∞) : ℂ := + limUnder (U : Filter X) (fun n => (θ n).functional (u n)) + +class CurrentMain.LimitConstruction : Prop where + tendsto : ∀ {D X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (θ : X → Pureness.TracialState D) (U : Ultrafilter X) (u : lp (fun _ : X => D) ∞), + Tendsto (fun n => (θ n).functional (u n)) (U : Filter X) (𝓝 (ultraTraceValue θ U u)) + +variable [ComparatorModel.CurrentMain.LimitConstruction] + +def CurrentMain.ultraTraceLinear : lp (fun _ : X => D) ∞ →ₗ[ℂ] ℂ where + toFun := ultraTraceValue θ U + map_add' u v := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (u+v)) + simpa only [lp.coeFn_add, Pi.add_apply, map_add] using + (LimitConstruction.tendsto θ U u).add (LimitConstruction.tendsto θ U v) + map_smul' z u := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (z • u)) + simpa only [lp.coeFn_smul, Pi.smul_apply, map_smul, RingHom.id_apply, smul_eq_mul] using + (LimitConstruction.tendsto θ U u).const_mul z + +def CurrentMain.boundedFamilyEval (n : X) : lp (fun _ : X => D) ∞ →⋆ₐ[ℂ] D where + toFun u := u n + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def CurrentMain.ultraTrace : TracialState (lp (fun _ : X => D) ∞) where + functional := { ultraTraceLinear θ U with + monotone' := by + intro u v huv + exact le_of_tendsto_of_tendsto (LimitConstruction.tendsto θ U u) + (LimitConstruction.tendsto θ U v) (Eventually.of_forall (fun n => + (θ n).functional.monotone (map_rel (boundedFamilyEval n) huv))) } + normalized := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U 1) + have he (n : X) : (θ n).functional ((1 : lp (fun _ : X => D) ∞) n) = 1 := + (θ n).normalized + simp only [he] + exact tendsto_const_nhds + tracial u v := by + change ultraTraceValue θ U (u*v) = ultraTraceValue θ U (v*u) + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (u*v)) + have he (n : X) : (θ n).functional ((u*v) n) = (θ n).functional ((v*u) n) := + (θ n).tracial (u n) (v n) + simpa only [he] using LimitConstruction.tendsto θ U (v*u) + +end UltraTrace + +section UniformQuotient + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] + +variable (τ : I → TracialState D) [Nonempty I] (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] + +abbrev CurrentMain.FamilyUltrapower := (familyNullIdeal τ (U : Filter X)).Quotient + +class CurrentMain.TraceConstruction : Prop where + null : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] (τ : I → Pureness.TracialState D) [Nonempty I] + (U : Ultrafilter X) (s : X → I) (u : lp (fun _ : X => D) ∞), + IsFamilyNull τ (U : Filter X) (fun n => u n) → + (ultraTrace (fun n => τ (s n)) U).functional u = 0 + +variable [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.familyLimitTrace (s : X → I) : TracialState (FamilyUltrapower τ U) := + (familyNullIdeal τ (U : Filter X)).descendedTrace + (ultraTrace (fun n => τ (s n)) U) (fun u hu => by + apply TraceConstruction.null τ U s u + have he : u ∈ familyNullTwoSided τ (U : Filter X) ↔ + IsFamilyNull τ (U : Filter X) (fun n => u n) := by + unfold familyNullTwoSided + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u + exact he.mp hu) + +end UniformQuotient + +section PullbackTrace + +variable {D : Type} {E : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [CStarAlgebra E] [PartialOrder E] [StarOrderedRing E] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.pullbackTrace (τ : TracialState E) (ι : D →⋆ₐ[ℂ] E) : TracialState D where + functional := { τ.functional.toLinearMap.comp ι.toLinearMap with + monotone' := fun _ _ h => τ.functional.monotone (map_rel ι h) } + normalized := by change τ.functional (ι 1) = 1; rw [map_one, τ.normalized] + tracial x y := by + change τ.functional (ι (x*y)) = τ.functional (ι (y*x)) + rw [map_mul ι x y, map_mul ι y x] + exact τ.tracial _ _ + +end PullbackTrace + +section CompletionTraces + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [Nontrivial D] (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +instance CurrentMain.familyCauchyOrder : PartialOrder (familyCauchyAlgebra τ) := + CStarAlgebra.spectralOrder _ + +instance CurrentMain.familyCauchyStarOrdered : StarOrderedRing (familyCauchyAlgebra τ) := + CStarAlgebra.spectralOrderedRing _ + +def CurrentMain.cauchyTrace (i : I) : TracialState (familyCauchyAlgebra τ) := + pullbackTrace (ultraTrace (fun _ : ℕ => τ i) (Ultrafilter.of atTop)) + (familyCauchyAlgebra τ).subtype + +def CurrentMain.completionTrace (i : I) : TracialState (UniformTracialCompletion τ) := + (familyCauchyNullIdeal τ).descendedTrace (cauchyTrace τ i) (fun u hu => by + apply TraceConstruction.null τ (Ultrafilter.of atTop) (fun _ => i) u.1 + have he : u.1 ∈ familyNullTwoSided τ atTop ↔ + IsFamilyNull τ atTop (fun n => u.1 n) := by + unfold familyNullTwoSided + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u.1 + have hn : IsFamilyNull τ atTop (fun n => u.1 n) := he.mp hu + exact hn.mono_left (Ultrafilter.of_le atTop)) + +def CurrentMain.boundedFamilyConstant {X : Type} (a : D) : lp (fun _ : X => D) ∞ := + ⟨fun _ => a, memℓp_infty_iff.mpr ⟨‖a‖,by rintro _ ⟨n,rfl⟩; exact le_rfl⟩⟩ + +instance CurrentMain.completionNontrivial : Nontrivial (UniformTracialCompletion τ) := by + obtain ⟨i⟩ := ‹Nonempty I› + refine ⟨⟨1,0,?_⟩⟩ + intro h + have he := congrArg (completionTrace τ i).functional h + rw [(completionTrace τ i).normalized, map_zero] at he + exact one_ne_zero he + +end CompletionTraces + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [Nontrivial D] (τ : I → TracialState D) [Nonempty I] (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.familyUltrapowerMap : D →⋆ₐ[ℂ] FamilyUltrapower τ U where + toFun a := (familyNullIdeal τ (U : Filter X)).quotientMap (boundedFamilyConstant a) + map_zero' := (familyNullIdeal τ (U : Filter X)).quotientMap.map_zero + map_one' := (familyNullIdeal τ (U : Filter X)).quotientMap.map_one + map_add' a b := (familyNullIdeal τ (U : Filter X)).quotientMap.map_add + (boundedFamilyConstant a) (boundedFamilyConstant b) + map_mul' a b := (familyNullIdeal τ (U : Filter X)).quotientMap.map_mul + (boundedFamilyConstant a) (boundedFamilyConstant b) + commutes' z := (familyNullIdeal τ (U : Filter X)).quotientMap.commutes z + map_star' _a := rfl + +end + +section + +open Filter Topology + +variable {A : Type uA} [NormedRing A] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def Pureness.TopologicallySimple (A : Type uA) [NormedRing A] : Prop := + ∀ I : TwoSidedIdeal A, IsClosed (I : Set A) → I = ⊥ ∨ I = ⊤ + +end + +section + +open _root_.OAI.ComparatorModel.Pureness Filter + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.StablyFinite (A : Type uA) [CStarAlgebra A] : Prop := + ∀ n : ℕ, ∀ v : CStarMatrix (Fin n) (Fin n) A, + star v*v = 1 → v*star v = 1 + +def CurrentMain.UniformPropertyGammaAt (A : Type) [CStarAlgebra A] + [PartialOrder A] [StarOrderedRing A] [Nontrivial A] + [Nonempty (TracialState A)] (U : Ultrafilter ℕ) : Prop := + ∃ p : FamilyUltrapower (completionTrace (fun τ : TracialState A => τ)) U, + IsStarProjection p ∧ ∀ x : UniformTracialCompletion (fun τ : TracialState A => τ), + p * familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x = + familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x * p ∧ + ∀ s : ℕ → TracialState A, + (familyLimitTrace (completionTrace (fun τ : TracialState A => τ)) U s).functional + (p * familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x) = + (1/2 : ℂ) * + (familyLimitTrace (completionTrace (fun τ : TracialState A => τ)) U s).functional + (familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x) + +open _root_.OAI.ComparatorModel.Pureness Filter + +def CurrentMain.Statement : Prop := ∀ + {A : Type} [CStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + [Nontrivial A] [TopologicalSpace.SeparableSpace A] + (_hsimple : TopologicallySimple A) (_hinf : ¬FiniteDimensional ℂ A) + (_hA : IsNuclear.{0, uNuclear} A) (_hfinite : StablyFinite A) + [Nonempty (TracialState A)] (U : Ultrafilter ℕ) + (_hfree : (U : Filter ℕ) ≤ atTop) + (_hRR : RealRankZero (FamilyUltrapower (completionTrace (fun τ : TracialState A => τ)) U)), + UniformPropertyGammaAt A U + +end + +def CurrentMain.MainClaim : Prop := + ∃ h0 : ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction, letI := h0; + ∃ h1 : ComparatorModel.CurrentMain.NullConstruction, letI := h1; + ∃ h2 : ComparatorModel.CurrentMain.CauchyConstruction, letI := h2; + ∃ h3 : ComparatorModel.CurrentMain.LimitConstruction, letI := h3; + ∃ h4 : ComparatorModel.CurrentMain.TraceConstruction, letI := h4; + Statement.{uNuclear} + +theorem CurrentMain.main : MainClaim.{uNuclear} := by + sorry + +end ComparatorModel + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniformGamma.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.ComparatorModel.CurrentMain.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/uniform-gamma/solution/closure.txt b/tasks/uniform-gamma/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..587314ce991fcf74ad1427a8ed5e5051da6a2671 --- /dev/null +++ b/tasks/uniform-gamma/solution/closure.txt @@ -0,0 +1,51 @@ +OAI.Analysis.TracialSplitting.BistochasticTests +OAI.Analysis.TracialSplitting.BlockAveraging +OAI.Analysis.TracialSplitting.BlockSampling +OAI.Analysis.TracialSplitting.Challenge +OAI.Analysis.TracialSplitting.ChallengeDefinitions +OAI.Analysis.TracialSplitting.CoefficientApproximation +OAI.Analysis.TracialSplitting.CoefficientBounds +OAI.Analysis.TracialSplitting.Completion +OAI.Analysis.TracialSplitting.ConditionalSplitting +OAI.Analysis.TracialSplitting.Diagonalization +OAI.Analysis.TracialSplitting.FaithfulRepresentations +OAI.Analysis.TracialSplitting.FinitePacking +OAI.Analysis.TracialSplitting.FiniteSplitting +OAI.Analysis.TracialSplitting.FullProjections +OAI.Analysis.TracialSplitting.GNSRepresentations +OAI.Analysis.TracialSplitting.HereditaryAlgebras +OAI.Analysis.TracialSplitting.Hypertraces +OAI.Analysis.TracialSplitting.KrausApproximation +OAI.Analysis.TracialSplitting.Main +OAI.Analysis.TracialSplitting.MatrixCoefficients +OAI.Analysis.TracialSplitting.MatrixNormalization +OAI.Analysis.TracialSplitting.Model +OAI.Analysis.TracialSplitting.NuclearApproximation +OAI.Analysis.TracialSplitting.NuclearFamilies +OAI.Analysis.TracialSplitting.NuclearPacking +OAI.Analysis.TracialSplitting.NuclearTransfer +OAI.Analysis.TracialSplitting.OrthogonalElements +OAI.Analysis.TracialSplitting.OrthogonalPacking +OAI.Analysis.TracialSplitting.PackingEstimates +OAI.Analysis.TracialSplitting.PartitionAveraging +OAI.Analysis.TracialSplitting.PartitionCoupling +OAI.Analysis.TracialSplitting.PreparedBlocks +OAI.Analysis.TracialSplitting.ProjectionFrames +OAI.Analysis.TracialSplitting.ProjectionRounding +OAI.Analysis.TracialSplitting.ProjectionSampling +OAI.Analysis.TracialSplitting.RowEstimates +OAI.Analysis.TracialSplitting.ScalarCompression +OAI.Analysis.TracialSplitting.SimpleIdeals +OAI.Analysis.TracialSplitting.SmallProjections +OAI.Analysis.TracialSplitting.SpatialTensor +OAI.Analysis.TracialSplitting.SpectralBlocks +OAI.Analysis.TracialSplitting.SpectralCutoffs +OAI.Analysis.TracialSplitting.SpectralLayers +OAI.Analysis.TracialSplitting.StateExtension +OAI.Analysis.TracialSplitting.TensorExtension +OAI.Analysis.TracialSplitting.TensorNorms +OAI.Analysis.TracialSplitting.TraceConvexity +OAI.Analysis.TracialSplitting.TraceEstimates +OAI.Analysis.TracialSplitting.TraceNormalization +OAI.Analysis.TracialSplitting.VectorApproximation +OAI.Analysis.TracialSplitting.WeightedFamilies diff --git a/tasks/uniform-gamma/solution/reference.py b/tasks/uniform-gamma/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/uniform-gamma/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/uniform-gamma/solution/solve.sh b/tasks/uniform-gamma/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..5daaede729cd9b3eb248b39f3b049a960c74293f --- /dev/null +++ b/tasks/uniform-gamma/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniformGamma, i.e. module OAI.Analysis.TracialSplitting.Challenge and the +# 51 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.TracialSplitting.Challenge /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniformGamma" diff --git a/tasks/uniform-gamma/task.toml b/tasks/uniform-gamma/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..0b68abfd6863ffb6a0ae1e0f2d027ac93b5d42fc --- /dev/null +++ b/tasks/uniform-gamma/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/uniform-gamma" +version = "1.0.0" +description = "Prove UniformGamma (openai/math family 291: Toms–Winter and equivariant Jiang–Su stability) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "operator-algebras"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniformGamma.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniformGamma" +family = "291" +family_title = "Toms–Winter and equivariant Jiang–Su stability" +subject = "Operator algebras" +theorems = ["OAI.ComparatorModel.CurrentMain.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.TracialSplitting.Challenge" +reference_modules = 51 +reference_lean_bytes = 736242 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 520 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12362 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/uniform-gamma/tests/Challenge.lean b/tasks/uniform-gamma/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..7ca382715b35db791e19c4c7dccce01de8948a0d --- /dev/null +++ b/tasks/uniform-gamma/tests/Challenge.lean @@ -0,0 +1,607 @@ +import Mathlib + +namespace OAI + +noncomputable section + +/-! +The final claim constructs the tracial quotients and states the original gamma assertion. +`Analysis.TracialSplitting.Challenge.main_iff_original` verifies statement preservation. +-/ + +universe uA uD uE uI uR uX u v + +namespace Pureness + +open scoped ComplexOrder + +structure CStarAlgebraNorm (R : Type uR) [Ring R] [StarRing R] [Algebra ℂ R] + extends AlgebraNorm ℂ R where + cstar : ∀ x, toAlgebraNorm (star x * x) = toAlgebraNorm x * toAlgebraNorm x + +structure TracialState (A : Type uA) [CStarAlgebra A] [PartialOrder A] where + functional : A →ₚ[ℂ] ℂ + normalized : functional 1 = 1 + tracial : ∀ a b : A, functional (a * b) = functional (b * a) + +structure ClosedStarIdeal (D : Type uD) [CStarAlgebra D] where + ideal : TwoSidedIdeal D + star_mem : ∀ {u : D}, u ∈ ideal → star u ∈ ideal + isClosed : IsClosed (ideal : Set D) + +end Pureness + +universe uNuclear + +namespace ComparatorModel + +namespace Pureness + +open scoped TensorProduct ComplexOrder + +abbrev CStarAlgebraNorm := @_root_.OAI.Pureness.CStarAlgebraNorm + +def IsNuclear (A : Type u) [CStarAlgebra A] : Prop := + ∀ (B : Type v) [CStarAlgebra B], Subsingleton (CStarAlgebraNorm (A ⊗[ℂ] B)) + +abbrev TracialState := @_root_.OAI.Pureness.TracialState + +end Pureness + +namespace CurrentMain + +open _root_.OAI.ComparatorModel.Pureness + +open scoped ComplexOrder + +def RealRankZero (D : Type) [CStarAlgebra D] : Prop := + ∀ a : D, IsSelfAdjoint a → ∀ ε : ℝ, 0 < ε → + ∃ b : D, IsSelfAdjoint b ∧ (spectrum ℂ b).Finite ∧ ‖a - b‖ < ε + +def traceTwoNorm {D : Type} [CStarAlgebra D] [PartialOrder D] + (τ : TracialState D) (a : D) : ℝ := + Real.sqrt (τ.functional (star a * a)).re + +end CurrentMain + +section + +open Filter + +open scoped Topology NNReal ENNReal + +abbrev Pureness.ClosedStarIdeal := @_root_.OAI.Pureness.ClosedStarIdeal + +namespace Pureness.ClosedStarIdeal + +section + +variable {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) + +abbrev Quotient := J.ideal.ringCon.Quotient + +def quotientMap : D →ₐ[ℂ] J.Quotient := J.ideal.ringCon.mkₐ ℂ + +instance quotientStar : Star (J.Quotient) where + star := Quotient.map' star (by + intro u v h + change J.ideal.ringCon u v at h + change J.ideal.ringCon (star u) (star v) + rw [TwoSidedIdeal.rel_iff] at h ⊢ + simpa only [star_sub] using J.star_mem h) + +instance quotientStarRing : StarRing (J.Quotient) where + star_involutive x := Quotient.inductionOn' x (fun u => congrArg J.quotientMap (star_star u)) + star_mul x y := Quotient.inductionOn₂' x y (fun u v => congrArg J.quotientMap (star_mul u v)) + star_add x y := Quotient.inductionOn₂' x y (fun u v => congrArg J.quotientMap (star_add u v)) + +instance quotientStarModule : StarModule ℂ (J.Quotient) where + star_smul c x := Quotient.inductionOn' x (fun u => congrArg J.quotientMap (star_smul c u)) + +abbrev idealSubmodule : Submodule ℂ (D) := + (J.quotientMap).toLinearMap.ker + +instance idealSubmodule_closed : IsClosed (J.idealSubmodule : Set D) := by + have he : (J.idealSubmodule : Set D) = (J.ideal : Set D) := by + ext u + change J.ideal.ringCon.mk' u = J.ideal.ringCon.mk' 0 ↔ u ∈ J.ideal + exact Quotient.eq + rw [he] + exact J.isClosed + +def quotientLinearEquiv : + (D ⧸ J.idealSubmodule) ≃ₗ[ℂ] J.Quotient := + (J.quotientMap).toLinearMap.quotKerEquivOfSurjective ((J.ideal.ringCon.mkₐ_surjective (α := ℂ))) + +instance quotientNormedAddCommGroup : NormedAddCommGroup (J.Quotient) := + NormedAddCommGroup.induced _ _ (J.quotientLinearEquiv).symm + (J.quotientLinearEquiv).symm.injective + +instance quotientNormedSpace : NormedSpace ℂ (J.Quotient) := + NormedSpace.induced ℂ _ _ (J.quotientLinearEquiv).symm + +def quotientNormEquiv : J.Quotient ≃ₗᵢ[ℂ] + (D ⧸ J.idealSubmodule) where + __ := (J.quotientLinearEquiv).symm + norm_map' _ := rfl + +instance quotientCompleteSpace : CompleteSpace (J.Quotient) := + (J.quotientNormEquiv).toIsometryEquiv.completeSpace_iff.mpr inferInstance + +class NormConstruction : Prop where + mul_le : ∀ {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) (x y : J.Quotient), + ‖x*y‖ ≤ ‖x‖*‖y‖ + star_eq : ∀ {D : Type} [CStarAlgebra D] (J : ClosedStarIdeal D) (x : J.Quotient), + ‖star x‖ = ‖x‖ + square_le : ∀ {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (J : ClosedStarIdeal D) (x : J.Quotient), ‖x‖ * ‖x‖ ≤ ‖star x * x‖ + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance quotientNormedRing : NormedRing (J.Quotient) where + dist_eq := dist_eq_norm_neg_add + norm_mul_le := NormConstruction.mul_le J + +instance quotientNormedAlgebra : NormedAlgebra ℂ (J.Quotient) where + norm_smul_le := norm_smul_le + +instance quotientNormedStarGroup : NormedStarGroup (J.Quotient) where + norm_star_le x := (NormConstruction.star_eq J x).le + +end + +open Filter + +open scoped Topology NNReal ENNReal + +variable {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (J : ClosedStarIdeal D) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance quotientCStarAlgebra : CStarAlgebra (J.Quotient) where + norm_mul_self_le := NormConstruction.square_le J + +end Pureness.ClosedStarIdeal + +end + +section + +open _root_.OAI.ComparatorModel.Pureness + +section UniformTraceNorm + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +def CurrentMain.familyTwoNorm (a : D) : ℝ := ⨆ i, traceTwoNorm (τ i) a + +end UniformTraceNorm + +open _root_.OAI.ComparatorModel.Pureness Filter + +open scoped Topology NNReal ENNReal + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] + +instance CurrentMain.boundedFamilyProductCStar {X : Type} {D : Type} [CStarAlgebra D] [Nontrivial D] : + CStarAlgebra (lp (fun _ : X => D) ∞) where + +section UniformNull + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +def CurrentMain.IsFamilyNull (F : Filter X) (u : X → D) : Prop := + Tendsto (fun n => familyTwoNorm τ (u n)) F (𝓝 0) + +class CurrentMain.NullConstruction : Prop where + zero : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + (F : Filter X), IsFamilyNull τ F (fun _ => 0) + add : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F v → + IsFamilyNull τ F (fun n => u n + v n) + neg : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F (fun n => -u n) + star : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u : X → D}, IsFamilyNull τ F u → IsFamilyNull τ F (fun n => star (u n)) + mul_left : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F v → ∀ {M : ℝ}, + (∀ n, ‖u n‖ ≤ M) → IsFamilyNull τ F (fun n => u n * v n) + mul_right : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] + {F : Filter X} {u v : X → D}, IsFamilyNull τ F u → ∀ {M : ℝ}, + (∀ n, ‖v n‖ ≤ M) → IsFamilyNull τ F (fun n => u n * v n) + closed : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] (τ : I → Pureness.TracialState D) [Nonempty I] (F : Filter X), + IsClosed {u : lp (fun _ : X => D) ∞ | IsFamilyNull τ F (fun n => u n)} + +variable [Nontrivial D] + +variable [ComparatorModel.CurrentMain.NullConstruction] + +def CurrentMain.familyNullTwoSided (F : Filter X) : TwoSidedIdeal (lp (fun _ : X => D) ∞) := + TwoSidedIdeal.mk' {u | IsFamilyNull τ F (fun n => u n)} + (NullConstruction.zero τ F) + (fun hu hv => NullConstruction.add τ hu hv) + (fun hu => NullConstruction.neg τ hu) + (fun {u _} hv => NullConstruction.mul_left τ hv + (lp.norm_apply_le_norm ENNReal.top_ne_zero u)) + (fun {_ v} hu => NullConstruction.mul_right τ hu + (lp.norm_apply_le_norm ENNReal.top_ne_zero v)) + +def CurrentMain.familyNullIdeal (F : Filter X) : ClosedStarIdeal (lp (fun _ : X => D) ∞) where + ideal := familyNullTwoSided τ F + star_mem := by + intro u hu + apply (TwoSidedIdeal.mem_mk' _ _ _ _ _ _ (star u)).mpr + exact NullConstruction.star τ ((TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u).mp hu) + isClosed := by + have he : (familyNullTwoSided τ F : Set (lp (fun _ : X => D) ∞)) = + {u | IsFamilyNull τ F (fun n => u n)} := by + ext u + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u + rw [he] + exact NullConstruction.closed τ F + +end UniformNull + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.CurrentMain.NullConstruction] + +def CurrentMain.IsFamilyCauchy (u : ℕ → D) : Prop := + IsFamilyNull τ (atTop : Filter (ℕ × ℕ)) (fun p => u p.1 - u p.2) + +class CurrentMain.CauchyConstruction : Prop where + const : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] (a : D), IsFamilyCauchy τ (fun _ => a) + add : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u v : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ v → IsFamilyCauchy τ (fun n => u n+v n) + star : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ (fun n => star (u n)) + mul : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] {u v : ℕ → D}, + IsFamilyCauchy τ u → IsFamilyCauchy τ v → ∀ {M N : ℝ}, + (∀ n, ‖u n‖ ≤ M) → (∀ n, ‖v n‖ ≤ N) → IsFamilyCauchy τ (fun n => u n*v n) + closed : ∀ {D I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (τ : I → Pureness.TracialState D) [Nonempty I] [Nontrivial D], + IsClosed {u : lp (fun _ : ℕ => D) ∞ | IsFamilyCauchy τ (fun n => u n)} + +variable [Nontrivial D] + +variable [ComparatorModel.CurrentMain.CauchyConstruction] + +def CurrentMain.familyCauchyAlgebra : StarSubalgebra ℂ (lp (fun _ : ℕ => D) ∞) where + carrier := {u | IsFamilyCauchy τ (fun n => u n)} + zero_mem' := CauchyConstruction.const τ 0 + one_mem' := CauchyConstruction.const τ 1 + add_mem' hu hv := CauchyConstruction.add τ hu hv + mul_mem' {u v} hu hv := CauchyConstruction.mul τ hu hv + (lp.norm_apply_le_norm ENNReal.top_ne_zero u) + (lp.norm_apply_le_norm ENNReal.top_ne_zero v) + algebraMap_mem' z := CauchyConstruction.const τ (algebraMap ℂ D z) + star_mem' hu := CauchyConstruction.star τ hu + +instance CurrentMain.familyCauchy_complete : CompleteSpace (familyCauchyAlgebra τ) := + (CauchyConstruction.closed τ).completeSpace_coe + +instance CurrentMain.familyCauchy_cstar : CStarAlgebra (familyCauchyAlgebra τ) where + +def CurrentMain.familyCauchyNullIdeal : ClosedStarIdeal (familyCauchyAlgebra τ) where + ideal := TwoSidedIdeal.comap (familyCauchyAlgebra τ).val.toRingHom + (familyNullIdeal τ atTop).ideal + star_mem := by + intro u hu + apply (familyNullIdeal τ atTop).star_mem hu + isClosed := by + exact (familyNullIdeal τ atTop).isClosed.preimage + (continuous_subtype_val : Continuous (fun u : familyCauchyAlgebra τ => u.1)) + +abbrev CurrentMain.UniformTracialCompletion := (familyCauchyNullIdeal τ).Quotient + +end + +section + +open scoped ComplexOrder + +variable {D : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] + +instance Pureness.ClosedStarIdeal.quotientOrder (J : ClosedStarIdeal D) : PartialOrder J.Quotient := + CStarAlgebra.spectralOrder _ + +instance Pureness.ClosedStarIdeal.quotientStarOrdered (J : ClosedStarIdeal D) : StarOrderedRing J.Quotient := + CStarAlgebra.spectralOrderedRing _ + +variable (J : Pureness.ClosedStarIdeal D) + +variable (τ : Pureness.TracialState D) (hτ : ∀ a ∈ J.ideal, τ.functional a = 0) + +def Pureness.ClosedStarIdeal.descendedValue : J.Quotient → ℂ := Quotient.lift τ.functional (by + intro u v huv + change J.ideal.ringCon u v at huv + rw [TwoSidedIdeal.rel_iff] at huv + have h := hτ (u-v) huv + rw [map_sub, sub_eq_zero] at h + exact h) + +def Pureness.ClosedStarIdeal.descendedLinear : J.Quotient →ₗ[ℂ] ℂ where + toFun := J.descendedValue τ hτ + map_add' x y := Quotient.inductionOn₂' x y (fun u v => τ.functional.map_add u v) + map_smul' c x := Quotient.inductionOn' x (fun u => τ.functional.map_smul c u) + +def Pureness.ClosedStarIdeal.descendedTrace : TracialState J.Quotient where + functional := { J.descendedLinear τ hτ with + monotone' := by + intro x y hxy + apply sub_nonneg.mp + change 0 ≤ J.descendedLinear τ hτ y - J.descendedLinear τ hτ x + rw [← map_sub] + obtain ⟨z,hz⟩ := CStarAlgebra.nonneg_iff_eq_star_mul_self.mp (sub_nonneg.mpr hxy) + rw [hz] + induction z using Quotient.inductionOn' with + | h u => exact τ.functional.map_nonneg (star_mul_self_nonneg u) } + normalized := τ.normalized + tracial x y := Quotient.inductionOn₂' x y (fun u v => τ.tracial u v) + +end + +section + +open _root_.OAI.ComparatorModel.Pureness Filter + +open scoped Topology NNReal ENNReal ComplexOrder + +section UltraTrace + +variable {D : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] + +variable (θ : X → TracialState D) (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] + +instance CurrentMain.boundedFamilyProductOrder : PartialOrder (lp (fun _ : X => D) ∞) := + CStarAlgebra.spectralOrder _ + +instance CurrentMain.boundedFamilyProductStarOrdered : StarOrderedRing (lp (fun _ : X => D) ∞) := + CStarAlgebra.spectralOrderedRing _ + +def CurrentMain.ultraTraceValue (u : lp (fun _ : X => D) ∞) : ℂ := + limUnder (U : Filter X) (fun n => (θ n).functional (u n)) + +class CurrentMain.LimitConstruction : Prop where + tendsto : ∀ {D X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + (θ : X → Pureness.TracialState D) (U : Ultrafilter X) (u : lp (fun _ : X => D) ∞), + Tendsto (fun n => (θ n).functional (u n)) (U : Filter X) (𝓝 (ultraTraceValue θ U u)) + +variable [ComparatorModel.CurrentMain.LimitConstruction] + +def CurrentMain.ultraTraceLinear : lp (fun _ : X => D) ∞ →ₗ[ℂ] ℂ where + toFun := ultraTraceValue θ U + map_add' u v := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (u+v)) + simpa only [lp.coeFn_add, Pi.add_apply, map_add] using + (LimitConstruction.tendsto θ U u).add (LimitConstruction.tendsto θ U v) + map_smul' z u := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (z • u)) + simpa only [lp.coeFn_smul, Pi.smul_apply, map_smul, RingHom.id_apply, smul_eq_mul] using + (LimitConstruction.tendsto θ U u).const_mul z + +def CurrentMain.boundedFamilyEval (n : X) : lp (fun _ : X => D) ∞ →⋆ₐ[ℂ] D where + toFun u := u n + map_zero' := rfl + map_one' := rfl + map_add' _ _ := rfl + map_mul' _ _ := rfl + commutes' _ := rfl + map_star' _ := rfl + +def CurrentMain.ultraTrace : TracialState (lp (fun _ : X => D) ∞) where + functional := { ultraTraceLinear θ U with + monotone' := by + intro u v huv + exact le_of_tendsto_of_tendsto (LimitConstruction.tendsto θ U u) + (LimitConstruction.tendsto θ U v) (Eventually.of_forall (fun n => + (θ n).functional.monotone (map_rel (boundedFamilyEval n) huv))) } + normalized := by + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U 1) + have he (n : X) : (θ n).functional ((1 : lp (fun _ : X => D) ∞) n) = 1 := + (θ n).normalized + simp only [he] + exact tendsto_const_nhds + tracial u v := by + change ultraTraceValue θ U (u*v) = ultraTraceValue θ U (v*u) + apply tendsto_nhds_unique (LimitConstruction.tendsto θ U (u*v)) + have he (n : X) : (θ n).functional ((u*v) n) = (θ n).functional ((v*u) n) := + (θ n).tracial (u n) (v n) + simpa only [he] using LimitConstruction.tendsto θ U (v*u) + +end UltraTrace + +section UniformQuotient + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] + +variable (τ : I → TracialState D) [Nonempty I] (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] + +abbrev CurrentMain.FamilyUltrapower := (familyNullIdeal τ (U : Filter X)).Quotient + +class CurrentMain.TraceConstruction : Prop where + null : ∀ {D I X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] [Nontrivial D] (τ : I → Pureness.TracialState D) [Nonempty I] + (U : Ultrafilter X) (s : X → I) (u : lp (fun _ : X => D) ∞), + IsFamilyNull τ (U : Filter X) (fun n => u n) → + (ultraTrace (fun n => τ (s n)) U).functional u = 0 + +variable [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.familyLimitTrace (s : X → I) : TracialState (FamilyUltrapower τ U) := + (familyNullIdeal τ (U : Filter X)).descendedTrace + (ultraTrace (fun n => τ (s n)) U) (fun u hu => by + apply TraceConstruction.null τ U s u + have he : u ∈ familyNullTwoSided τ (U : Filter X) ↔ + IsFamilyNull τ (U : Filter X) (fun n => u n) := by + unfold familyNullTwoSided + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u + exact he.mp hu) + +end UniformQuotient + +section PullbackTrace + +variable {D : Type} {E : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [CStarAlgebra E] [PartialOrder E] [StarOrderedRing E] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.pullbackTrace (τ : TracialState E) (ι : D →⋆ₐ[ℂ] E) : TracialState D where + functional := { τ.functional.toLinearMap.comp ι.toLinearMap with + monotone' := fun _ _ h => τ.functional.monotone (map_rel ι h) } + normalized := by change τ.functional (ι 1) = 1; rw [map_one, τ.normalized] + tracial x y := by + change τ.functional (ι (x*y)) = τ.functional (ι (y*x)) + rw [map_mul ι x y, map_mul ι y x] + exact τ.tracial _ _ + +end PullbackTrace + +section CompletionTraces + +variable {D : Type} {I : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [Nontrivial D] (τ : I → TracialState D) [Nonempty I] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +instance CurrentMain.familyCauchyOrder : PartialOrder (familyCauchyAlgebra τ) := + CStarAlgebra.spectralOrder _ + +instance CurrentMain.familyCauchyStarOrdered : StarOrderedRing (familyCauchyAlgebra τ) := + CStarAlgebra.spectralOrderedRing _ + +def CurrentMain.cauchyTrace (i : I) : TracialState (familyCauchyAlgebra τ) := + pullbackTrace (ultraTrace (fun _ : ℕ => τ i) (Ultrafilter.of atTop)) + (familyCauchyAlgebra τ).subtype + +def CurrentMain.completionTrace (i : I) : TracialState (UniformTracialCompletion τ) := + (familyCauchyNullIdeal τ).descendedTrace (cauchyTrace τ i) (fun u hu => by + apply TraceConstruction.null τ (Ultrafilter.of atTop) (fun _ => i) u.1 + have he : u.1 ∈ familyNullTwoSided τ atTop ↔ + IsFamilyNull τ atTop (fun n => u.1 n) := by + unfold familyNullTwoSided + exact TwoSidedIdeal.mem_mk' _ _ _ _ _ _ u.1 + have hn : IsFamilyNull τ atTop (fun n => u.1 n) := he.mp hu + exact hn.mono_left (Ultrafilter.of_le atTop)) + +def CurrentMain.boundedFamilyConstant {X : Type} (a : D) : lp (fun _ : X => D) ∞ := + ⟨fun _ => a, memℓp_infty_iff.mpr ⟨‖a‖,by rintro _ ⟨n,rfl⟩; exact le_rfl⟩⟩ + +instance CurrentMain.completionNontrivial : Nontrivial (UniformTracialCompletion τ) := by + obtain ⟨i⟩ := ‹Nonempty I› + refine ⟨⟨1,0,?_⟩⟩ + intro h + have he := congrArg (completionTrace τ i).functional h + rw [(completionTrace τ i).normalized, map_zero] at he + exact one_ne_zero he + +end CompletionTraces + +variable {D : Type} {I : Type} {X : Type} [CStarAlgebra D] [PartialOrder D] [StarOrderedRing D] + +variable [Nontrivial D] (τ : I → TracialState D) [Nonempty I] (U : Ultrafilter X) + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.familyUltrapowerMap : D →⋆ₐ[ℂ] FamilyUltrapower τ U where + toFun a := (familyNullIdeal τ (U : Filter X)).quotientMap (boundedFamilyConstant a) + map_zero' := (familyNullIdeal τ (U : Filter X)).quotientMap.map_zero + map_one' := (familyNullIdeal τ (U : Filter X)).quotientMap.map_one + map_add' a b := (familyNullIdeal τ (U : Filter X)).quotientMap.map_add + (boundedFamilyConstant a) (boundedFamilyConstant b) + map_mul' a b := (familyNullIdeal τ (U : Filter X)).quotientMap.map_mul + (boundedFamilyConstant a) (boundedFamilyConstant b) + commutes' z := (familyNullIdeal τ (U : Filter X)).quotientMap.commutes z + map_star' _a := rfl + +end + +section + +open Filter Topology + +variable {A : Type uA} [NormedRing A] + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def Pureness.TopologicallySimple (A : Type uA) [NormedRing A] : Prop := + ∀ I : TwoSidedIdeal A, IsClosed (I : Set A) → I = ⊥ ∨ I = ⊤ + +end + +section + +open _root_.OAI.ComparatorModel.Pureness Filter + +variable [ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction] [ComparatorModel.CurrentMain.NullConstruction] [ComparatorModel.CurrentMain.CauchyConstruction] [ComparatorModel.CurrentMain.LimitConstruction] [ComparatorModel.CurrentMain.TraceConstruction] + +def CurrentMain.StablyFinite (A : Type uA) [CStarAlgebra A] : Prop := + ∀ n : ℕ, ∀ v : CStarMatrix (Fin n) (Fin n) A, + star v*v = 1 → v*star v = 1 + +def CurrentMain.UniformPropertyGammaAt (A : Type) [CStarAlgebra A] + [PartialOrder A] [StarOrderedRing A] [Nontrivial A] + [Nonempty (TracialState A)] (U : Ultrafilter ℕ) : Prop := + ∃ p : FamilyUltrapower (completionTrace (fun τ : TracialState A => τ)) U, + IsStarProjection p ∧ ∀ x : UniformTracialCompletion (fun τ : TracialState A => τ), + p * familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x = + familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x * p ∧ + ∀ s : ℕ → TracialState A, + (familyLimitTrace (completionTrace (fun τ : TracialState A => τ)) U s).functional + (p * familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x) = + (1/2 : ℂ) * + (familyLimitTrace (completionTrace (fun τ : TracialState A => τ)) U s).functional + (familyUltrapowerMap (completionTrace (fun τ : TracialState A => τ)) U x) + +open _root_.OAI.ComparatorModel.Pureness Filter + +def CurrentMain.Statement : Prop := ∀ + {A : Type} [CStarAlgebra A] [PartialOrder A] [StarOrderedRing A] + [Nontrivial A] [TopologicalSpace.SeparableSpace A] + (_hsimple : TopologicallySimple A) (_hinf : ¬FiniteDimensional ℂ A) + (_hA : IsNuclear.{0, uNuclear} A) (_hfinite : StablyFinite A) + [Nonempty (TracialState A)] (U : Ultrafilter ℕ) + (_hfree : (U : Filter ℕ) ≤ atTop) + (_hRR : RealRankZero (FamilyUltrapower (completionTrace (fun τ : TracialState A => τ)) U)), + UniformPropertyGammaAt A U + +end + +def CurrentMain.MainClaim : Prop := + ∃ h0 : ComparatorModel.Pureness.ClosedStarIdeal.NormConstruction, letI := h0; + ∃ h1 : ComparatorModel.CurrentMain.NullConstruction, letI := h1; + ∃ h2 : ComparatorModel.CurrentMain.CauchyConstruction, letI := h2; + ∃ h3 : ComparatorModel.CurrentMain.LimitConstruction, letI := h3; + ∃ h4 : ComparatorModel.CurrentMain.TraceConstruction, letI := h4; + Statement.{uNuclear} + +theorem CurrentMain.main : MainClaim.{uNuclear} := by + sorry + +end ComparatorModel + +end + +end OAI diff --git a/tasks/uniform-gamma/tests/grade.py b/tasks/uniform-gamma/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/uniform-gamma/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/uniform-gamma/tests/task.json b/tasks/uniform-gamma/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..853248df25a4429765a2a06b3f846726119d990d --- /dev/null +++ b/tasks/uniform-gamma/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniformGamma", + "comparator": { + "theorem_names": [ + "OAI.ComparatorModel.CurrentMain.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11462 +} \ No newline at end of file diff --git a/tasks/uniform-gamma/tests/test.sh b/tasks/uniform-gamma/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/uniform-gamma/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/uniform-k-server/environment/Dockerfile b/tasks/uniform-k-server/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/uniform-k-server/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/uniform-k-server/environment/fetch_mathlib.sh b/tasks/uniform-k-server/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/uniform-k-server/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/uniform-k-server/environment/lake-manifest.json b/tasks/uniform-k-server/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/uniform-k-server/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/uniform-k-server/environment/lakefile.lean b/tasks/uniform-k-server/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/uniform-k-server/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/uniform-k-server/environment/lean_setup.sh b/tasks/uniform-k-server/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/uniform-k-server/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/uniform-k-server/environment/pack_submission.py b/tasks/uniform-k-server/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/uniform-k-server/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/uniform-k-server/instruction.md b/tasks/uniform-k-server/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..e9d3dc476f0a45490886ab87539cb68bb1dfb0e2 --- /dev/null +++ b/tasks/uniform-k-server/instruction.md @@ -0,0 +1,256 @@ +# openai/math challenge `UniformKServer` (family 110) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 110 of the release, *Optimal-order randomized $k$-server on arbitrary metrics* +(Theoretical computer science). The family as a whole: Establishes a randomized competitive ratio $O(\log^2(k+1))$ for $k$-server on every metric space, matching the worst-case lower-bound order. One policy serves every finite oblivious request sequence, including on infinite unbounded metrics. On finite rational metrics, a uniform implementation has polynomial preprocessing and per-request bit cost in the input length and $\log(t+1)$ at request $t$, with a finite instance-dependent additive movement constant. + +The challenge is `UniformKServer`, also at `/opt/openai-math/challenges/UniformKServer.lean`: + +```lean +import Mathlib + +namespace OAI + + + + + + +namespace UniformKServer + +structure RationalMetric (n : ℕ) where + distance : Fin n → Fin n → ℚ + nonneg : ∀ x y, 0 ≤ distance x y + eq_zero : ∀ x y, distance x y = 0 ↔ x = y + symm : ∀ x y, distance x y = distance y x + triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +abbrev Configuration (n k : ℕ) := Fin k → Fin n +abbrev History (n k : ℕ) := List (Fin n × Fin k) + +def serve {n k : ℕ} (s : Configuration n k) (r : Fin n) (j : Fin k) : + Configuration n k := Function.update s j r + +def costAlong {n k : ℕ} (d : RationalMetric n) : + Configuration n k → History n k → ℝ + | _, [] => 0 + | s, (r, j) :: h => (d.distance (s j) r : ℝ) + costAlong d (serve s r j) h + +/-- All finite serving-label choices, knowing the entire request word. -/ +noncomputable def offlineCost {n k : ℕ} (d : RationalMetric n) (s : Configuration n k) + (w : List (Fin n)) : ℝ := + sInf {c | ∃ h : History n k, h.map Prod.fst = w ∧ c = costAlong d s h} + +inductive HeadMove where + | left | stay | right + deriving DecidableEq + +structure BitTape where + left : List (Option Bool) + head : Option Bool + right : List (Option Bool) + +namespace BitTape + +def blank : BitTape := ⟨[], none, []⟩ + +def ofWord (w : List Bool) : BitTape := + match w with + | [] => blank + | b :: bs => ⟨[], some b, bs.map some⟩ + +def shift (T : BitTape) : HeadMove → BitTape + | .stay => T + | .left => match T.left with + | [] => ⟨[], none, T.head :: T.right⟩ + | a :: as => ⟨as, a, T.head :: T.right⟩ + | .right => match T.right with + | [] => ⟨T.head :: T.left, none, []⟩ + | a :: as => ⟨T.head :: T.left, a, as⟩ + +end BitTape + +structure BitAction (q m : ℕ) where + control : Fin q + inputMove : HeadMove + write : Fin m → Option Bool + workMove : Fin m → HeadMove + emit : Option Bool + yield : Bool + +structure BitMachine where + controls : ℕ + tapes : ℕ + start : Fin controls + transition : Fin controls → Option Bool → (Fin tapes → Option Bool) → + Bool → BitAction controls tapes + +structure MachineState (M : BitMachine) where + control : Fin M.controls + input : BitTape + work : Fin M.tapes → BitTape + outputRev : List Bool + yielded : Bool + +namespace BitMachine + +def initial (M : BitMachine) (input : List Bool) : MachineState M := + ⟨M.start, BitTape.ofWord input, fun _ => BitTape.blank, [], false⟩ + +def step (M : BitMachine) (s : MachineState M) (coin : Bool) : MachineState M := + if s.yielded then s else + let a := M.transition s.control s.input.head (fun i => (s.work i).head) coin + { control := a.control + input := s.input.shift a.inputMove + work := fun i => ({s.work i with head := a.write i}).shift (a.workMove i) + outputRev := match a.emit with + | none => s.outputRev + | some b => b :: s.outputRev + yielded := a.yield } + +def run (M : BitMachine) (s : MachineState M) (coins : List Bool) : MachineState M := + coins.foldl M.step s + +/-- At a request boundary only the input/output interface is refreshed. + Work tapes and control retain the complete internal state. -/ +def install (M : BitMachine) (s : MachineState M) (input : List Bool) : MachineState M := + {s with input := BitTape.ofWord input, outputRev := [], yielded := false} + +end BitMachine + +/-- Self-delimiting binary code: ℓ ones, a zero, then ℓ low-to-high bits. + This fixes one standard binary encoding rather than allowing a nonuniform + advice string to be included in the input. -/ +def natCode (a : ℕ) : List Bool := + List.replicate a.bits.length true ++ [false] ++ a.bits + +def rationalCode (a : ℚ) : List Bool := + (a.num < 0) :: (natCode a.num.natAbs ++ natCode a.den) + +def instanceCode {n k : ℕ} (d : RationalMetric n) (s : Configuration n k) : List Bool := + natCode n ++ natCode k ++ + (List.ofFn fun x : Fin n => + (List.ofFn fun y : Fin n => rationalCode (d.distance x y)).flatten).flatten ++ + (List.ofFn fun j : Fin k => natCode ((s j).val + 1)).flatten + +def bitValue : List Bool → ℕ + | [] => 0 + | b :: bs => (if b then 1 else 0) + 2 * bitValue bs + +def outputValue {M : BitMachine} (s : MachineState M) : ℕ := + bitValue s.outputRev.reverse + +/-- A dominating polynomial; every fixed polynomial nonnegative on natural + inputs is bounded by one of this form after increasing c and e. -/ +def polynomialBudget (c e x : ℕ) : ℕ := c * (x + 1)^e + +def requestBudget (c e L t : ℕ) : ℕ := + polynomialBudget c e (L + Nat.clog 2 (t + 1)) + +def boot {n k : ℕ} (M : BitMachine) (c e : ℕ) + (d : RationalMetric n) (s : Configuration n k) : MachineState M := + M.run (M.initial (instanceCode d s)) + (List.replicate (polynomialBudget c e (instanceCode d s).length) false) + +def requestStep {n : ℕ} (M : BitMachine) (c e L t : ℕ) + (s : MachineState M) (r : Fin n) + (coins : Fin (requestBudget c e L t) → Bool) : MachineState M := + M.run (M.install s (natCode (r.val + 1))) (List.ofFn coins) + +/-- Reachability includes every binary choice, not merely an almost-sure set. + The index counts requests already served. -/ +inductive Reachable {n k : ℕ} (M : BitMachine) (c e : ℕ) + (d : RationalMetric n) (s : Configuration n k) : ℕ → MachineState M → Prop + | boot : Reachable M c e d s 0 (boot M c e d s) + | next {t z} : Reachable M c e d s t z → (r : Fin n) → + (bits : Fin (requestBudget c e (instanceCode d s).length (t+1)) → Bool) → + Reachable M c e d s (t+1) + (requestStep M c e (instanceCode d s).length (t+1) z r bits) + +/-- Modulo makes the semantic recursion total even for unsuccessful machines. + The main statement separately requires the output to be < k at *every* + reachable outcome, so no invalid output is accepted or silently repaired. -/ +def selectedLabel {M : BitMachine} {k : ℕ} (hk : 0 < k) (s : MachineState M) : Fin k := + ⟨outputValue s % k, Nat.mod_lt _ hk⟩ + +noncomputable def machineExpectedCost {n k : ℕ} (M : BitMachine) (c e L : ℕ) + (d : RationalMetric n) (hk : 0 < k) : + ℕ → MachineState M → Configuration n k → List (Fin n) → ℝ + | _, _, _, [] => 0 + | t, z, s, r :: w => + let B := requestBudget c e L (t+1) + (∑ bits : Fin B → Bool, + let z' := requestStep M c e L (t+1) z r bits + let j := selectedLabel hk z' + (d.distance (s j) r : ℝ) + + machineExpectedCost M c e L d hk (t+1) z' (serve s r j) w) / (2 : ℝ)^B + +/-- Full uniform main objective in the explicit bit model, not a theorem or + assumption. Machine transition steps are bit operations. Installing the + standard input and reading/erasing the output adds only O(L + budget) + charged bit operations, hence is absorbed by a single larger polynomial. + A single deterministic boot is sufficient for the source construction. -/ +def UniformAlgorithmClaim : Prop := + ∃ (M : BitMachine) (c e : ℕ) (C : ℝ), 0 < c ∧ 0 < C ∧ + ∀ (n k : ℕ) (hn : 3 ≤ n) (hk : 2 ≤ k) (hkn : k < n) + (d : RationalMetric n) (s : Configuration n k), + let L := (instanceCode d s).length + (boot M c e d s).yielded = true ∧ + (∀ (t : ℕ) (z : MachineState M), Reachable M c e d s t z → + ∀ (r : Fin n) (bits : Fin (requestBudget c e L (t+1)) → Bool), + let z' := requestStep M c e L (t+1) z r bits + z'.yielded = true ∧ outputValue z' < k) ∧ + (∃ B : ℝ, 0 ≤ B ∧ ∀ w : List (Fin n), + machineExpectedCost M c e L d (by omega) 0 (boot M c e d s) s w ≤ + C * (Real.log (k + 1))^2 * offlineCost d s w + B) + +/-- A single uniform randomized bit machine has squared-logarithmic expected movement +and a uniform polynomial bound on each request's bit operations. -/ +theorem uniform_squared_logarithmic_main : UniformAlgorithmClaim := by + sorry + +end UniformKServer + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniformKServer.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.UniformKServer.uniform_squared_logarithmic_main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/uniform-k-server/solution/closure.txt b/tasks/uniform-k-server/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a6f000a2e448e034579a832cc3c21be3cdc22bc3 --- /dev/null +++ b/tasks/uniform-k-server/solution/closure.txt @@ -0,0 +1,410 @@ +OAI.Combinatorics.UniformKServer.ActualAllocationBudget +OAI.Combinatorics.UniformKServer.ActualAnchorDrift +OAI.Combinatorics.UniformKServer.ActualAnchorDriftSum +OAI.Combinatorics.UniformKServer.ActualAnchorFiltering +OAI.Combinatorics.UniformKServer.ActualAnchorPotential +OAI.Combinatorics.UniformKServer.ActualAnchorRelease +OAI.Combinatorics.UniformKServer.ActualAnchorStep +OAI.Combinatorics.UniformKServer.ActualAnchorTravel +OAI.Combinatorics.UniformKServer.ActualAuxiliary +OAI.Combinatorics.UniformKServer.ActualCoordinate +OAI.Combinatorics.UniformKServer.ActualCoordinateBudget +OAI.Combinatorics.UniformKServer.ActualEditCosts +OAI.Combinatorics.UniformKServer.ActualEditFinance +OAI.Combinatorics.UniformKServer.ActualEditIntegration +OAI.Combinatorics.UniformKServer.ActualFineCaps +OAI.Combinatorics.UniformKServer.ActualLevelPilot +OAI.Combinatorics.UniformKServer.ActualPartitions +OAI.Combinatorics.UniformKServer.ActualPilot +OAI.Combinatorics.UniformKServer.ActualPublicFlow +OAI.Combinatorics.UniformKServer.ActualRoster +OAI.Combinatorics.UniformKServer.ActualRoundedStep +OAI.Combinatorics.UniformKServer.ActualRoundingChain +OAI.Combinatorics.UniformKServer.ActualSizeBudget +OAI.Combinatorics.UniformKServer.AdaptiveAlpha +OAI.Combinatorics.UniformKServer.AdaptiveAlphaLinear +OAI.Combinatorics.UniformKServer.AdaptiveLedger +OAI.Combinatorics.UniformKServer.AdaptiveSide +OAI.Combinatorics.UniformKServer.AllocationAnalysis +OAI.Combinatorics.UniformKServer.AllocationEpoch +OAI.Combinatorics.UniformKServer.AllocationMovement +OAI.Combinatorics.UniformKServer.AllocationOutputs +OAI.Combinatorics.UniformKServer.AllocationSchedule +OAI.Combinatorics.UniformKServer.AlphaEmpty +OAI.Combinatorics.UniformKServer.AlphaEmptyLinear +OAI.Combinatorics.UniformKServer.AlphaFiniteInput +OAI.Combinatorics.UniformKServer.AlphaFiniteLedger +OAI.Combinatorics.UniformKServer.AlphaLinear +OAI.Combinatorics.UniformKServer.AlphaParameterChanges +OAI.Combinatorics.UniformKServer.AlphaPrepared +OAI.Combinatorics.UniformKServer.AlphaRecurrence +OAI.Combinatorics.UniformKServer.AlphaStability +OAI.Combinatorics.UniformKServer.AlphaTracker +OAI.Combinatorics.UniformKServer.AnchorBudget +OAI.Combinatorics.UniformKServer.AnchorFinance +OAI.Combinatorics.UniformKServer.AnchorLedger +OAI.Combinatorics.UniformKServer.AnchorPotential +OAI.Combinatorics.UniformKServer.AnchorRamp +OAI.Combinatorics.UniformKServer.AnchorScalar +OAI.Combinatorics.UniformKServer.AutomaticEpoch +OAI.Combinatorics.UniformKServer.AutomaticTable +OAI.Combinatorics.UniformKServer.BalancedRepair +OAI.Combinatorics.UniformKServer.BalancedStar +OAI.Combinatorics.UniformKServer.Basic +OAI.Combinatorics.UniformKServer.BinaryTape +OAI.Combinatorics.UniformKServer.BitPaths +OAI.Combinatorics.UniformKServer.BitSampling +OAI.Combinatorics.UniformKServer.BoundaryPartition +OAI.Combinatorics.UniformKServer.BoundedFilter +OAI.Combinatorics.UniformKServer.CausalHeavy +OAI.Combinatorics.UniformKServer.CausalLevel +OAI.Combinatorics.UniformKServer.CausalLevelAux +OAI.Combinatorics.UniformKServer.CausalRosters +OAI.Combinatorics.UniformKServer.CausalSchedules +OAI.Combinatorics.UniformKServer.CausalShort +OAI.Combinatorics.UniformKServer.CausalTier +OAI.Combinatorics.UniformKServer.ChronologicalBound +OAI.Combinatorics.UniformKServer.ChronologicalRoster +OAI.Combinatorics.UniformKServer.ClockSchedule +OAI.Combinatorics.UniformKServer.CoarseBridge +OAI.Combinatorics.UniformKServer.CoarseData +OAI.Combinatorics.UniformKServer.CommonAnchorTravel +OAI.Combinatorics.UniformKServer.ComputedInstance +OAI.Combinatorics.UniformKServer.ComputedSuffix +OAI.Combinatorics.UniformKServer.ConditionalLaw +OAI.Combinatorics.UniformKServer.ConditionalRank +OAI.Combinatorics.UniformKServer.ConditionalRanks +OAI.Combinatorics.UniformKServer.ConstructorProgram +OAI.Combinatorics.UniformKServer.ConstructorSearch +OAI.Combinatorics.UniformKServer.ControllerBound +OAI.Combinatorics.UniformKServer.ControllerEpoch +OAI.Combinatorics.UniformKServer.ControllerGroups +OAI.Combinatorics.UniformKServer.CooldownLabels +OAI.Combinatorics.UniformKServer.CoreFiltering +OAI.Combinatorics.UniformKServer.CrossRule +OAI.Combinatorics.UniformKServer.CurrentTesting +OAI.Combinatorics.UniformKServer.Denominators +OAI.Combinatorics.UniformKServer.Disintegration +OAI.Combinatorics.UniformKServer.DomainTransport +OAI.Combinatorics.UniformKServer.DyadicRows +OAI.Combinatorics.UniformKServer.DyadicTiers +OAI.Combinatorics.UniformKServer.EntropyCredit +OAI.Combinatorics.UniformKServer.EpochAlpha +OAI.Combinatorics.UniformKServer.EpochAlphaBudget +OAI.Combinatorics.UniformKServer.EpochAlphaCharge +OAI.Combinatorics.UniformKServer.EpochAlphaJump +OAI.Combinatorics.UniformKServer.EpochAlphaPieces +OAI.Combinatorics.UniformKServer.EpochAlphaSchedule +OAI.Combinatorics.UniformKServer.EpochAlphaStatic +OAI.Combinatorics.UniformKServer.EpochControl +OAI.Combinatorics.UniformKServer.EpochCut +OAI.Combinatorics.UniformKServer.EpochExpectation +OAI.Combinatorics.UniformKServer.EpochFinite +OAI.Combinatorics.UniformKServer.EpochGeometry +OAI.Combinatorics.UniformKServer.EpochOutputParameters +OAI.Combinatorics.UniformKServer.EpochParameters +OAI.Combinatorics.UniformKServer.EpochPartition +OAI.Combinatorics.UniformKServer.EpochShadow +OAI.Combinatorics.UniformKServer.EpochSide +OAI.Combinatorics.UniformKServer.EpochSideBudget +OAI.Combinatorics.UniformKServer.EpochSideCharge +OAI.Combinatorics.UniformKServer.EpochTape +OAI.Combinatorics.UniformKServer.Epochs +OAI.Combinatorics.UniformKServer.ExactOptimum +OAI.Combinatorics.UniformKServer.ExecutableDyadic +OAI.Combinatorics.UniformKServer.Fallback +OAI.Combinatorics.UniformKServer.FineCaps +OAI.Combinatorics.UniformKServer.FineVariation +OAI.Combinatorics.UniformKServer.FiniteFlow +OAI.Combinatorics.UniformKServer.FiniteFlowCompact +OAI.Combinatorics.UniformKServer.FiniteFlowMinimax +OAI.Combinatorics.UniformKServer.FiniteFlowSpace +OAI.Combinatorics.UniformKServer.FiniteLawFinance +OAI.Combinatorics.UniformKServer.FiniteLawTheorem +OAI.Combinatorics.UniformKServer.FinitePiLaw +OAI.Combinatorics.UniformKServer.FiniteProbability +OAI.Combinatorics.UniformKServer.FiniteRepresentation +OAI.Combinatorics.UniformKServer.FiniteSeparation +OAI.Combinatorics.UniformKServer.FiniteTable +OAI.Combinatorics.UniformKServer.FiniteThreshold +OAI.Combinatorics.UniformKServer.FirstEdits +OAI.Combinatorics.UniformKServer.FirstHit +OAI.Combinatorics.UniformKServer.FirstHitSupport +OAI.Combinatorics.UniformKServer.FirstStructure +OAI.Combinatorics.UniformKServer.FlatOperational +OAI.Combinatorics.UniformKServer.FlatTM2 +OAI.Combinatorics.UniformKServer.FlatTermination +OAI.Combinatorics.UniformKServer.FlexEstimates +OAI.Combinatorics.UniformKServer.FlowAuxiliary +OAI.Combinatorics.UniformKServer.FourierMotzkin +OAI.Combinatorics.UniformKServer.GeometricMass +OAI.Combinatorics.UniformKServer.HeavyAnchorGeometry +OAI.Combinatorics.UniformKServer.HeavyBirths +OAI.Combinatorics.UniformKServer.HeavyEditPayment +OAI.Combinatorics.UniformKServer.HeavyEditRamp +OAI.Combinatorics.UniformKServer.HeavyFiniteLaw +OAI.Combinatorics.UniformKServer.HeavyKeyGeometry +OAI.Combinatorics.UniformKServer.HeavyLabelParks +OAI.Combinatorics.UniformKServer.HeavyPilot +OAI.Combinatorics.UniformKServer.HeavyProcess +OAI.Combinatorics.UniformKServer.HeavyProcessEdits +OAI.Combinatorics.UniformKServer.HeavyRadius +OAI.Combinatorics.UniformKServer.HeavyRecordGeometry +OAI.Combinatorics.UniformKServer.HeavyRecords +OAI.Combinatorics.UniformKServer.HeavySchedule +OAI.Combinatorics.UniformKServer.HeavySeparation +OAI.Combinatorics.UniformKServer.HeavyTape +OAI.Combinatorics.UniformKServer.HeldRelative +OAI.Combinatorics.UniformKServer.HiddenCausality +OAI.Combinatorics.UniformKServer.HiddenFlow +OAI.Combinatorics.UniformKServer.HiddenHistory +OAI.Combinatorics.UniformKServer.HiddenRegion +OAI.Combinatorics.UniformKServer.HiddenTesting +OAI.Combinatorics.UniformKServer.HorizonPolicy +OAI.Combinatorics.UniformKServer.IntegerParks +OAI.Combinatorics.UniformKServer.KeyCountVariation +OAI.Combinatorics.UniformKServer.KeyEdits +OAI.Combinatorics.UniformKServer.KeySizePosterior +OAI.Combinatorics.UniformKServer.KeySizeTracker +OAI.Combinatorics.UniformKServer.LabelParkVariation +OAI.Combinatorics.UniformKServer.LabelParks +OAI.Combinatorics.UniformKServer.LaminarTransport +OAI.Combinatorics.UniformKServer.LawKernel +OAI.Combinatorics.UniformKServer.LawSupport +OAI.Combinatorics.UniformKServer.LazyFinance +OAI.Combinatorics.UniformKServer.LazyMarkov +OAI.Combinatorics.UniformKServer.LevelAllowances +OAI.Combinatorics.UniformKServer.LevelAnchorContinuity +OAI.Combinatorics.UniformKServer.LevelAnchorRelease +OAI.Combinatorics.UniformKServer.LevelErrorMass +OAI.Combinatorics.UniformKServer.LevelHeavy +OAI.Combinatorics.UniformKServer.LevelHeavyEdits +OAI.Combinatorics.UniformKServer.LevelKeyLedger +OAI.Combinatorics.UniformKServer.LevelMap +OAI.Combinatorics.UniformKServer.LevelMassLedger +OAI.Combinatorics.UniformKServer.LevelMoverBudget +OAI.Combinatorics.UniformKServer.LevelParkCapacity +OAI.Combinatorics.UniformKServer.LevelSeparation +OAI.Combinatorics.UniformKServer.LevelSerial +OAI.Combinatorics.UniformKServer.LevelTierEdits +OAI.Combinatorics.UniformKServer.LevelTierLedger +OAI.Combinatorics.UniformKServer.LinearProgram +OAI.Combinatorics.UniformKServer.LiteralBound +OAI.Combinatorics.UniformKServer.LiteralInput +OAI.Combinatorics.UniformKServer.LiteralPartial +OAI.Combinatorics.UniformKServer.LiteralPartrec +OAI.Combinatorics.UniformKServer.LiteralVector +OAI.Combinatorics.UniformKServer.LogPrimitive +OAI.Combinatorics.UniformKServer.Main +OAI.Combinatorics.UniformKServer.MarkovFlow +OAI.Combinatorics.UniformKServer.MetricRealization +OAI.Combinatorics.UniformKServer.OfflineDynamic +OAI.Combinatorics.UniformKServer.OfflineLaw +OAI.Combinatorics.UniformKServer.OffsetBridge +OAI.Combinatorics.UniformKServer.OffsetComparison +OAI.Combinatorics.UniformKServer.OffsetEpoch +OAI.Combinatorics.UniformKServer.OffsetExistence +OAI.Combinatorics.UniformKServer.OffsetInstance +OAI.Combinatorics.UniformKServer.OffsetLP +OAI.Combinatorics.UniformKServer.OffsetParameters +OAI.Combinatorics.UniformKServer.OffsetRealization +OAI.Combinatorics.UniformKServer.OffsetSuffix +OAI.Combinatorics.UniformKServer.OffsetTable +OAI.Combinatorics.UniformKServer.ParameterGaps +OAI.Combinatorics.UniformKServer.ParentBeta +OAI.Combinatorics.UniformKServer.ParentScale +OAI.Combinatorics.UniformKServer.ParkCapacity +OAI.Combinatorics.UniformKServer.ParkCoefficients +OAI.Combinatorics.UniformKServer.ParkPointwise +OAI.Combinatorics.UniformKServer.ParkScale +OAI.Combinatorics.UniformKServer.ParkedTransport +OAI.Combinatorics.UniformKServer.PartitionAnchors +OAI.Combinatorics.UniformKServer.PartitionCausal +OAI.Combinatorics.UniformKServer.PartitionGeometry +OAI.Combinatorics.UniformKServer.PartitionLaw +OAI.Combinatorics.UniformKServer.PartitionLevel +OAI.Combinatorics.UniformKServer.PartitionMovement +OAI.Combinatorics.UniformKServer.PartitionScales +OAI.Combinatorics.UniformKServer.PartitionSeparation +OAI.Combinatorics.UniformKServer.PartitionTransport +OAI.Combinatorics.UniformKServer.PartitionTree +OAI.Combinatorics.UniformKServer.PathExpansion +OAI.Combinatorics.UniformKServer.PiFirstHit +OAI.Combinatorics.UniformKServer.PiFresh +OAI.Combinatorics.UniformKServer.PiIntegrate +OAI.Combinatorics.UniformKServer.PilotCapacity +OAI.Combinatorics.UniformKServer.PilotCompact +OAI.Combinatorics.UniformKServer.PilotConcentration +OAI.Combinatorics.UniformKServer.PilotCredits +OAI.Combinatorics.UniformKServer.PilotDeletion +OAI.Combinatorics.UniformKServer.PilotDrift +OAI.Combinatorics.UniformKServer.PilotEdits +OAI.Combinatorics.UniformKServer.PilotExtension +OAI.Combinatorics.UniformKServer.PilotFamily +OAI.Combinatorics.UniformKServer.PilotFiltering +OAI.Combinatorics.UniformKServer.PilotPersistence +OAI.Combinatorics.UniformKServer.PilotRelocation +OAI.Combinatorics.UniformKServer.PilotScales +OAI.Combinatorics.UniformKServer.PilotSlope +OAI.Combinatorics.UniformKServer.PilotStability +OAI.Combinatorics.UniformKServer.PilotTemplates +OAI.Combinatorics.UniformKServer.PositiveSupport +OAI.Combinatorics.UniformKServer.PrefixCounts +OAI.Combinatorics.UniformKServer.PrefixMovement +OAI.Combinatorics.UniformKServer.PrefixTree +OAI.Combinatorics.UniformKServer.PrimitiveRules +OAI.Combinatorics.UniformKServer.ProportionParameters +OAI.Combinatorics.UniformKServer.PublicFlow +OAI.Combinatorics.UniformKServer.PublicRounding +OAI.Combinatorics.UniformKServer.RadiusFirstHit +OAI.Combinatorics.UniformKServer.RadiusRoster +OAI.Combinatorics.UniformKServer.RadiusTail +OAI.Combinatorics.UniformKServer.RankData +OAI.Combinatorics.UniformKServer.RankFunctions +OAI.Combinatorics.UniformKServer.RankSuperadditivity +OAI.Combinatorics.UniformKServer.RankTracking +OAI.Combinatorics.UniformKServer.RankedTree +OAI.Combinatorics.UniformKServer.RawAccepted +OAI.Combinatorics.UniformKServer.RawArithmetic +OAI.Combinatorics.UniformKServer.RawBinary +OAI.Combinatorics.UniformKServer.RawBits +OAI.Combinatorics.UniformKServer.RawBlockCharge +OAI.Combinatorics.UniformKServer.RawBounded +OAI.Combinatorics.UniformKServer.RawCertificate +OAI.Combinatorics.UniformKServer.RawCompleteness +OAI.Combinatorics.UniformKServer.RawControl +OAI.Combinatorics.UniformKServer.RawControllerCost +OAI.Combinatorics.UniformKServer.RawExistence +OAI.Combinatorics.UniformKServer.RawExpansion +OAI.Combinatorics.UniformKServer.RawFallback +OAI.Combinatorics.UniformKServer.RawFilter +OAI.Combinatorics.UniformKServer.RawFinite +OAI.Combinatorics.UniformKServer.RawGlobal +OAI.Combinatorics.UniformKServer.RawMarks +OAI.Combinatorics.UniformKServer.RawMetric +OAI.Combinatorics.UniformKServer.RawPartition +OAI.Combinatorics.UniformKServer.RawPath +OAI.Combinatorics.UniformKServer.RawProgram +OAI.Combinatorics.UniformKServer.RawRepresentation +OAI.Combinatorics.UniformKServer.RawRowSelect +OAI.Combinatorics.UniformKServer.RawRows +OAI.Combinatorics.UniformKServer.RawSearch +OAI.Combinatorics.UniformKServer.RawSound +OAI.Combinatorics.UniformKServer.RawTable +OAI.Combinatorics.UniformKServer.RawTableWitness +OAI.Combinatorics.UniformKServer.RawTape +OAI.Combinatorics.UniformKServer.RawTyped +OAI.Combinatorics.UniformKServer.RawTypedCoins +OAI.Combinatorics.UniformKServer.RawWords +OAI.Combinatorics.UniformKServer.RealFlow +OAI.Combinatorics.UniformKServer.RealFlowBounds +OAI.Combinatorics.UniformKServer.RealFlowConvex +OAI.Combinatorics.UniformKServer.RealFlowMixture +OAI.Combinatorics.UniformKServer.ReverseScales +OAI.Combinatorics.UniformKServer.RosterTails +OAI.Combinatorics.UniformKServer.RoundedMetricStep +OAI.Combinatorics.UniformKServer.RoundedState +OAI.Combinatorics.UniformKServer.RoundingChain +OAI.Combinatorics.UniformKServer.RoundingKernel +OAI.Combinatorics.UniformKServer.RuntimeCertificate +OAI.Combinatorics.UniformKServer.RuntimeExistence +OAI.Combinatorics.UniformKServer.ScaleAllowances +OAI.Combinatorics.UniformKServer.SelectedParkCoefficients +OAI.Combinatorics.UniformKServer.ShortRoster +OAI.Combinatorics.UniformKServer.ShortRosterValidity +OAI.Combinatorics.UniformKServer.SideFiniteInput +OAI.Combinatorics.UniformKServer.SideFiniteLedger +OAI.Combinatorics.UniformKServer.SideLinear +OAI.Combinatorics.UniformKServer.SideParameterChanges +OAI.Combinatorics.UniformKServer.SideParameters +OAI.Combinatorics.UniformKServer.SideRecurrence +OAI.Combinatorics.UniformKServer.SideReferenceSchedule +OAI.Combinatorics.UniformKServer.SideStability +OAI.Combinatorics.UniformKServer.SideTracker +OAI.Combinatorics.UniformKServer.SimplexTracker +OAI.Combinatorics.UniformKServer.SmallScales +OAI.Combinatorics.UniformKServer.SortedRoster +OAI.Combinatorics.UniformKServer.StackCoins +OAI.Combinatorics.UniformKServer.StackCompiler +OAI.Combinatorics.UniformKServer.StackPrimitive +OAI.Combinatorics.UniformKServer.StackRun +OAI.Combinatorics.UniformKServer.StackSimulation +OAI.Combinatorics.UniformKServer.StackTape +OAI.Combinatorics.UniformKServer.StarActualJumps +OAI.Combinatorics.UniformKServer.StarAllSteps +OAI.Combinatorics.UniformKServer.StarAllocator +OAI.Combinatorics.UniformKServer.StarBudget +OAI.Combinatorics.UniformKServer.StarCaps +OAI.Combinatorics.UniformKServer.StarCoarseBudgets +OAI.Combinatorics.UniformKServer.StarConstants +OAI.Combinatorics.UniformKServer.StarEnergy +OAI.Combinatorics.UniformKServer.StarFeasibilityParameters +OAI.Combinatorics.UniformKServer.StarIntegratedJumps +OAI.Combinatorics.UniformKServer.StarLocalCharges +OAI.Combinatorics.UniformKServer.StarLower +OAI.Combinatorics.UniformKServer.StarMovementBudget +OAI.Combinatorics.UniformKServer.StarMovementData +OAI.Combinatorics.UniformKServer.StarOutputData +OAI.Combinatorics.UniformKServer.StarOutputFeasibility +OAI.Combinatorics.UniformKServer.StarOutputMovement +OAI.Combinatorics.UniformKServer.StarParameters +OAI.Combinatorics.UniformKServer.StarPotentialBounds +OAI.Combinatorics.UniformKServer.StarRanks +OAI.Combinatorics.UniformKServer.StarSchedules +OAI.Combinatorics.UniformKServer.StarTrackerBudgets +OAI.Combinatorics.UniformKServer.StarTrackers +OAI.Combinatorics.UniformKServer.SwitchFinite +OAI.Combinatorics.UniformKServer.SwitchFiniteLedger +OAI.Combinatorics.UniformKServer.SwitchTracker +OAI.Combinatorics.UniformKServer.SyntheticCore +OAI.Combinatorics.UniformKServer.TapeController +OAI.Combinatorics.UniformKServer.TierFrozen +OAI.Combinatorics.UniformKServer.TierInner +OAI.Combinatorics.UniformKServer.TierInsertion +OAI.Combinatorics.UniformKServer.TierKeyEdits +OAI.Combinatorics.UniformKServer.TierKeyProcess +OAI.Combinatorics.UniformKServer.TierKeys +OAI.Combinatorics.UniformKServer.TierLabeledEdits +OAI.Combinatorics.UniformKServer.TierLabeledKeys +OAI.Combinatorics.UniformKServer.TierLabels +OAI.Combinatorics.UniformKServer.TierLifetimes +OAI.Combinatorics.UniformKServer.TierParameters +OAI.Combinatorics.UniformKServer.TierPilot +OAI.Combinatorics.UniformKServer.TierRadius +OAI.Combinatorics.UniformKServer.TierRetirement +OAI.Combinatorics.UniformKServer.TierSchedule +OAI.Combinatorics.UniformKServer.TierShortSchedule +OAI.Combinatorics.UniformKServer.TreeAllocationMovement +OAI.Combinatorics.UniformKServer.TreeAllocator +OAI.Combinatorics.UniformKServer.TreeAncestry +OAI.Combinatorics.UniformKServer.TreeCountData +OAI.Combinatorics.UniformKServer.TreeCoverage +OAI.Combinatorics.UniformKServer.TreeDistribution +OAI.Combinatorics.UniformKServer.TreeLeaves +OAI.Combinatorics.UniformKServer.TreeParking +OAI.Combinatorics.UniformKServer.TreePosteriorRegions +OAI.Combinatorics.UniformKServer.TreeRankData +OAI.Combinatorics.UniformKServer.TreeRounding +OAI.Combinatorics.UniformKServer.TreeTransport +OAI.Combinatorics.UniformKServer.TypedStack +OAI.Combinatorics.UniformKServer.UniformParameters +OAI.Combinatorics.UniformKServer.UniformSlope +OAI.Combinatorics.UniformKServer.UniformWrapper +OAI.Combinatorics.UniformKServer.WrapperActive +OAI.Combinatorics.UniformKServer.WrapperAlgebra +OAI.Combinatorics.UniformKServer.WrapperBoot +OAI.Combinatorics.UniformKServer.WrapperCoins +OAI.Combinatorics.UniformKServer.WrapperDelayed +OAI.Combinatorics.UniformKServer.WrapperEmit +OAI.Combinatorics.UniformKServer.WrapperExpectation +OAI.Combinatorics.UniformKServer.WrapperInterpreter +OAI.Combinatorics.UniformKServer.WrapperMachine +OAI.Combinatorics.UniformKServer.WrapperPrefix +OAI.Combinatorics.UniformKServer.WrapperPrepare +OAI.Combinatorics.UniformKServer.WrapperReachable +OAI.Combinatorics.UniformKServer.WrapperResponse +OAI.Combinatorics.UniformKServer.WrapperSlow +OAI.Combinatorics.UniformKServer.WrapperStartup +OAI.Combinatorics.UniformKServer.WrapperTransfer +OAI.Combinatorics.UniformKServer.WrapperTyped +OAI.Combinatorics.UniformKServer.WrapperWords diff --git a/tasks/uniform-k-server/solution/reference.py b/tasks/uniform-k-server/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/uniform-k-server/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/uniform-k-server/solution/solve.sh b/tasks/uniform-k-server/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c5df4d93212619516e90c4857c097b905c1036f9 --- /dev/null +++ b/tasks/uniform-k-server/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniformKServer, i.e. module OAI.Combinatorics.UniformKServer.Main and the +# 410 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.UniformKServer.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniformKServer" diff --git a/tasks/uniform-k-server/task.toml b/tasks/uniform-k-server/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..afe892a0ad8ddaffb13d556a472af71ee4400d40 --- /dev/null +++ b/tasks/uniform-k-server/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/uniform-k-server" +version = "1.0.0" +description = "Prove UniformKServer (openai/math family 110: Optimal-order randomized $k$-server on arbitrary metrics) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniformKServer.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniformKServer" +family = "110" +family_title = "Optimal-order randomized $k$-server on arbitrary metrics" +subject = "Theoretical computer science" +theorems = ["OAI.UniformKServer.uniform_squared_logarithmic_main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.UniformKServer.Main" +reference_modules = 410 +reference_lean_bytes = 2194822 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1209 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13675 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/uniform-k-server/tests/Challenge.lean b/tasks/uniform-k-server/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..254cfcd71efed615bde22b8f993d5591ab783857 --- /dev/null +++ b/tasks/uniform-k-server/tests/Challenge.lean @@ -0,0 +1,205 @@ +import Mathlib + +namespace OAI + + + + + + +namespace UniformKServer + +structure RationalMetric (n : ℕ) where + distance : Fin n → Fin n → ℚ + nonneg : ∀ x y, 0 ≤ distance x y + eq_zero : ∀ x y, distance x y = 0 ↔ x = y + symm : ∀ x y, distance x y = distance y x + triangle : ∀ x y z, distance x z ≤ distance x y + distance y z + +abbrev Configuration (n k : ℕ) := Fin k → Fin n +abbrev History (n k : ℕ) := List (Fin n × Fin k) + +def serve {n k : ℕ} (s : Configuration n k) (r : Fin n) (j : Fin k) : + Configuration n k := Function.update s j r + +def costAlong {n k : ℕ} (d : RationalMetric n) : + Configuration n k → History n k → ℝ + | _, [] => 0 + | s, (r, j) :: h => (d.distance (s j) r : ℝ) + costAlong d (serve s r j) h + +/-- All finite serving-label choices, knowing the entire request word. -/ +noncomputable def offlineCost {n k : ℕ} (d : RationalMetric n) (s : Configuration n k) + (w : List (Fin n)) : ℝ := + sInf {c | ∃ h : History n k, h.map Prod.fst = w ∧ c = costAlong d s h} + +inductive HeadMove where + | left | stay | right + deriving DecidableEq + +structure BitTape where + left : List (Option Bool) + head : Option Bool + right : List (Option Bool) + +namespace BitTape + +def blank : BitTape := ⟨[], none, []⟩ + +def ofWord (w : List Bool) : BitTape := + match w with + | [] => blank + | b :: bs => ⟨[], some b, bs.map some⟩ + +def shift (T : BitTape) : HeadMove → BitTape + | .stay => T + | .left => match T.left with + | [] => ⟨[], none, T.head :: T.right⟩ + | a :: as => ⟨as, a, T.head :: T.right⟩ + | .right => match T.right with + | [] => ⟨T.head :: T.left, none, []⟩ + | a :: as => ⟨T.head :: T.left, a, as⟩ + +end BitTape + +structure BitAction (q m : ℕ) where + control : Fin q + inputMove : HeadMove + write : Fin m → Option Bool + workMove : Fin m → HeadMove + emit : Option Bool + yield : Bool + +structure BitMachine where + controls : ℕ + tapes : ℕ + start : Fin controls + transition : Fin controls → Option Bool → (Fin tapes → Option Bool) → + Bool → BitAction controls tapes + +structure MachineState (M : BitMachine) where + control : Fin M.controls + input : BitTape + work : Fin M.tapes → BitTape + outputRev : List Bool + yielded : Bool + +namespace BitMachine + +def initial (M : BitMachine) (input : List Bool) : MachineState M := + ⟨M.start, BitTape.ofWord input, fun _ => BitTape.blank, [], false⟩ + +def step (M : BitMachine) (s : MachineState M) (coin : Bool) : MachineState M := + if s.yielded then s else + let a := M.transition s.control s.input.head (fun i => (s.work i).head) coin + { control := a.control + input := s.input.shift a.inputMove + work := fun i => ({s.work i with head := a.write i}).shift (a.workMove i) + outputRev := match a.emit with + | none => s.outputRev + | some b => b :: s.outputRev + yielded := a.yield } + +def run (M : BitMachine) (s : MachineState M) (coins : List Bool) : MachineState M := + coins.foldl M.step s + +/-- At a request boundary only the input/output interface is refreshed. + Work tapes and control retain the complete internal state. -/ +def install (M : BitMachine) (s : MachineState M) (input : List Bool) : MachineState M := + {s with input := BitTape.ofWord input, outputRev := [], yielded := false} + +end BitMachine + +/-- Self-delimiting binary code: ℓ ones, a zero, then ℓ low-to-high bits. + This fixes one standard binary encoding rather than allowing a nonuniform + advice string to be included in the input. -/ +def natCode (a : ℕ) : List Bool := + List.replicate a.bits.length true ++ [false] ++ a.bits + +def rationalCode (a : ℚ) : List Bool := + (a.num < 0) :: (natCode a.num.natAbs ++ natCode a.den) + +def instanceCode {n k : ℕ} (d : RationalMetric n) (s : Configuration n k) : List Bool := + natCode n ++ natCode k ++ + (List.ofFn fun x : Fin n => + (List.ofFn fun y : Fin n => rationalCode (d.distance x y)).flatten).flatten ++ + (List.ofFn fun j : Fin k => natCode ((s j).val + 1)).flatten + +def bitValue : List Bool → ℕ + | [] => 0 + | b :: bs => (if b then 1 else 0) + 2 * bitValue bs + +def outputValue {M : BitMachine} (s : MachineState M) : ℕ := + bitValue s.outputRev.reverse + +/-- A dominating polynomial; every fixed polynomial nonnegative on natural + inputs is bounded by one of this form after increasing c and e. -/ +def polynomialBudget (c e x : ℕ) : ℕ := c * (x + 1)^e + +def requestBudget (c e L t : ℕ) : ℕ := + polynomialBudget c e (L + Nat.clog 2 (t + 1)) + +def boot {n k : ℕ} (M : BitMachine) (c e : ℕ) + (d : RationalMetric n) (s : Configuration n k) : MachineState M := + M.run (M.initial (instanceCode d s)) + (List.replicate (polynomialBudget c e (instanceCode d s).length) false) + +def requestStep {n : ℕ} (M : BitMachine) (c e L t : ℕ) + (s : MachineState M) (r : Fin n) + (coins : Fin (requestBudget c e L t) → Bool) : MachineState M := + M.run (M.install s (natCode (r.val + 1))) (List.ofFn coins) + +/-- Reachability includes every binary choice, not merely an almost-sure set. + The index counts requests already served. -/ +inductive Reachable {n k : ℕ} (M : BitMachine) (c e : ℕ) + (d : RationalMetric n) (s : Configuration n k) : ℕ → MachineState M → Prop + | boot : Reachable M c e d s 0 (boot M c e d s) + | next {t z} : Reachable M c e d s t z → (r : Fin n) → + (bits : Fin (requestBudget c e (instanceCode d s).length (t+1)) → Bool) → + Reachable M c e d s (t+1) + (requestStep M c e (instanceCode d s).length (t+1) z r bits) + +/-- Modulo makes the semantic recursion total even for unsuccessful machines. + The main statement separately requires the output to be < k at *every* + reachable outcome, so no invalid output is accepted or silently repaired. -/ +def selectedLabel {M : BitMachine} {k : ℕ} (hk : 0 < k) (s : MachineState M) : Fin k := + ⟨outputValue s % k, Nat.mod_lt _ hk⟩ + +noncomputable def machineExpectedCost {n k : ℕ} (M : BitMachine) (c e L : ℕ) + (d : RationalMetric n) (hk : 0 < k) : + ℕ → MachineState M → Configuration n k → List (Fin n) → ℝ + | _, _, _, [] => 0 + | t, z, s, r :: w => + let B := requestBudget c e L (t+1) + (∑ bits : Fin B → Bool, + let z' := requestStep M c e L (t+1) z r bits + let j := selectedLabel hk z' + (d.distance (s j) r : ℝ) + + machineExpectedCost M c e L d hk (t+1) z' (serve s r j) w) / (2 : ℝ)^B + +/-- Full uniform main objective in the explicit bit model, not a theorem or + assumption. Machine transition steps are bit operations. Installing the + standard input and reading/erasing the output adds only O(L + budget) + charged bit operations, hence is absorbed by a single larger polynomial. + A single deterministic boot is sufficient for the source construction. -/ +def UniformAlgorithmClaim : Prop := + ∃ (M : BitMachine) (c e : ℕ) (C : ℝ), 0 < c ∧ 0 < C ∧ + ∀ (n k : ℕ) (hn : 3 ≤ n) (hk : 2 ≤ k) (hkn : k < n) + (d : RationalMetric n) (s : Configuration n k), + let L := (instanceCode d s).length + (boot M c e d s).yielded = true ∧ + (∀ (t : ℕ) (z : MachineState M), Reachable M c e d s t z → + ∀ (r : Fin n) (bits : Fin (requestBudget c e L (t+1)) → Bool), + let z' := requestStep M c e L (t+1) z r bits + z'.yielded = true ∧ outputValue z' < k) ∧ + (∃ B : ℝ, 0 ≤ B ∧ ∀ w : List (Fin n), + machineExpectedCost M c e L d (by omega) 0 (boot M c e d s) s w ≤ + C * (Real.log (k + 1))^2 * offlineCost d s w + B) + +/-- A single uniform randomized bit machine has squared-logarithmic expected movement +and a uniform polynomial bound on each request's bit operations. -/ +theorem uniform_squared_logarithmic_main : UniformAlgorithmClaim := by + sorry + +end UniformKServer + +end OAI diff --git a/tasks/uniform-k-server/tests/grade.py b/tasks/uniform-k-server/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/uniform-k-server/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/uniform-k-server/tests/task.json b/tasks/uniform-k-server/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0727f5b04f5ea68e65bf95efba092c6055e95c23 --- /dev/null +++ b/tasks/uniform-k-server/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniformKServer", + "comparator": { + "theorem_names": [ + "OAI.UniformKServer.uniform_squared_logarithmic_main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12775 +} \ No newline at end of file diff --git a/tasks/uniform-k-server/tests/test.sh b/tasks/uniform-k-server/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/uniform-k-server/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/uniform-sparsest-cut/environment/Dockerfile b/tasks/uniform-sparsest-cut/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/uniform-sparsest-cut/environment/fetch_mathlib.sh b/tasks/uniform-sparsest-cut/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/uniform-sparsest-cut/environment/lake-manifest.json b/tasks/uniform-sparsest-cut/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/uniform-sparsest-cut/environment/lakefile.lean b/tasks/uniform-sparsest-cut/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/uniform-sparsest-cut/environment/lean_setup.sh b/tasks/uniform-sparsest-cut/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/uniform-sparsest-cut/environment/pack_submission.py b/tasks/uniform-sparsest-cut/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/uniform-sparsest-cut/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/uniform-sparsest-cut/instruction.md b/tasks/uniform-sparsest-cut/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4ac2c20d8a0fc4bca152c1209f6869f663816a5f --- /dev/null +++ b/tasks/uniform-sparsest-cut/instruction.md @@ -0,0 +1,106 @@ +# openai/math challenge `UniformSparsestCut` (family 117) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 117 of the release, *Uniform sparsest cut: hardness and semidefinite gaps* +(Theoretical computer science). The family as a whole: Proves that approximating Uniform Sparsest Cut within any fixed constant factor is NP-hard, even with nonnegative rational capacities and unit demands. The Goemans–Linial semidefinite relaxation also has integrality gaps of order at least $\sqrt{\log n}/(\log\log n)^3$, approaching the square-root-logarithmic upper bound. + +The challenge is `UniformSparsestCut`, also at `/opt/openai-math/challenges/UniformSparsestCut.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace UniformSparsestCut + +structure Capacity (n : ℕ) where + cap : Fin n → Fin n → ℝ + nonneg : ∀ i j, 0 ≤ cap i j + symm : ∀ i j, cap i j = cap j i + diagonal : ∀ i, cap i i = 0 + +def pairSum {n : ℕ} (f : Fin n → Fin n → ℝ) : ℝ := + ∑ i, ∑ j, if i < j then f i j else 0 + +noncomputable def cutRatio {n : ℕ} (C : Capacity n) (B : Finset (Fin n)) : ℝ := + (∑ i ∈ B, ∑ j ∈ Bᶜ, C.cap i j) / + ((B.card : ℝ) * ((n : ℝ) - (B.card : ℝ))) + +noncomputable def OPT {n : ℕ} (C : Capacity n) : ℝ := + sInf {r | ∃ B : Finset (Fin n), B.Nonempty ∧ B ≠ Finset.univ ∧ r = cutRatio C B} + +def NegativeType {n : ℕ} (d : Fin n → Fin n → ℝ) : Prop := + (∃ x : Fin n → EuclideanSpace ℝ (Fin n), ∀ i j, d i j = ‖x i - x j‖ ^ 2) ∧ + ∀ i j k, d i k ≤ d i j + d j k + +def Feasible {n : ℕ} (d : Fin n → Fin n → ℝ) : Prop := + NegativeType d ∧ pairSum d = 1 + +noncomputable def glValue {n : ℕ} (C : Capacity n) : ℝ := + sInf {r | ∃ d : Fin n → Fin n → ℝ, Feasible d ∧ + r = pairSum (fun i j => C.cap i j * d i j)} + +open Filter + +theorem mainGap : + ∃ c : ℝ, 0 < c ∧ + ∃ n : ℕ → ℕ, ∃ C : (j : ℕ) → Capacity (n j), + (∀ j, 2 ≤ n j) ∧ + Tendsto n atTop atTop ∧ + (∀ j, 0 < glValue (C j)) ∧ + ∀ᶠ j in atTop, + c * Real.sqrt (Real.log (n j : ℝ)) / (Real.log (Real.log (n j : ℝ))) ^ 3 ≤ + OPT (C j) / glValue (C j) := by + sorry + +end UniformSparsestCut + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniformSparsestCut.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.UniformSparsestCut.mainGap` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/uniform-sparsest-cut/solution/closure.txt b/tasks/uniform-sparsest-cut/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..88160d4e9f17976ae96357fd2c3348de47339d6d --- /dev/null +++ b/tasks/uniform-sparsest-cut/solution/closure.txt @@ -0,0 +1,55 @@ +OAI.Combinatorics.SparsestCut.CellInterface +OAI.Combinatorics.SparsestCut.ChartAngles +OAI.Combinatorics.SparsestCut.ChartKernel +OAI.Combinatorics.SparsestCut.ChartLinear +OAI.Combinatorics.SparsestCut.ChartMetric +OAI.Combinatorics.SparsestCut.CommonKernel +OAI.Combinatorics.SparsestCut.ConcreteCells +OAI.Combinatorics.SparsestCut.ContractionAverage +OAI.Combinatorics.SparsestCut.ContractionBounds +OAI.Combinatorics.SparsestCut.ContractionCore +OAI.Combinatorics.SparsestCut.CoordinateSplit +OAI.Combinatorics.SparsestCut.CubeGeometry +OAI.Combinatorics.SparsestCut.CubePoincare +OAI.Combinatorics.SparsestCut.CubeTransfer +OAI.Combinatorics.SparsestCut.CutDuality +OAI.Combinatorics.SparsestCut.CutSums +OAI.Combinatorics.SparsestCut.DirectionAsymptotics +OAI.Combinatorics.SparsestCut.DirectionFamily +OAI.Combinatorics.SparsestCut.DirectionInterpolation +OAI.Combinatorics.SparsestCut.Directions +OAI.Combinatorics.SparsestCut.EuclideanCells +OAI.Combinatorics.SparsestCut.FiniteDuality +OAI.Combinatorics.SparsestCut.FiniteNets +OAI.Combinatorics.SparsestCut.GaussianCDF +OAI.Combinatorics.SparsestCut.GaussianNonparallel +OAI.Combinatorics.SparsestCut.GaussianPoincare +OAI.Combinatorics.SparsestCut.GaussianTools +OAI.Combinatorics.SparsestCut.GradientBudget +OAI.Combinatorics.SparsestCut.InterfaceStep +OAI.Combinatorics.SparsestCut.KernelApprox +OAI.Combinatorics.SparsestCut.LabelCount +OAI.Combinatorics.SparsestCut.LatticeDensity +OAI.Combinatorics.SparsestCut.Logarithms +OAI.Combinatorics.SparsestCut.Main +OAI.Combinatorics.SparsestCut.Metric +OAI.Combinatorics.SparsestCut.MetricKernel +OAI.Combinatorics.SparsestCut.Model +OAI.Combinatorics.SparsestCut.Mollifier +OAI.Combinatorics.SparsestCut.Parameters +OAI.Combinatorics.SparsestCut.PivotFamily +OAI.Combinatorics.SparsestCut.PositiveKernels +OAI.Combinatorics.SparsestCut.ProductSlice +OAI.Combinatorics.SparsestCut.Profiles +OAI.Combinatorics.SparsestCut.Replication +OAI.Combinatorics.SparsestCut.RoundedCharts +OAI.Combinatorics.SparsestCut.Semimetrics +OAI.Combinatorics.SparsestCut.SliceCoefficients +OAI.Combinatorics.SparsestCut.SliceIntegration +OAI.Combinatorics.SparsestCut.Smoothing +OAI.Combinatorics.SparsestCut.TriangleRepair +OAI.Combinatorics.SparsestCut.UniformMetric +OAI.Combinatorics.SparsestCut.UniformReplication +OAI.Combinatorics.SparsestCut.VertexCount +OAI.Combinatorics.SparsestCut.VertexMeasure +OAI.Combinatorics.SparsestCut.WeightedMetric diff --git a/tasks/uniform-sparsest-cut/solution/reference.py b/tasks/uniform-sparsest-cut/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/uniform-sparsest-cut/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/uniform-sparsest-cut/solution/solve.sh b/tasks/uniform-sparsest-cut/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7c703830dcd603721af19b953f00bb61dc34b45c --- /dev/null +++ b/tasks/uniform-sparsest-cut/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniformSparsestCut, i.e. module OAI.Combinatorics.SparsestCut.Main and the +# 55 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.SparsestCut.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniformSparsestCut" diff --git a/tasks/uniform-sparsest-cut/task.toml b/tasks/uniform-sparsest-cut/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..66e7849a5f3701fba0c5ff016efb2e02df2e0d2b --- /dev/null +++ b/tasks/uniform-sparsest-cut/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/uniform-sparsest-cut" +version = "1.0.0" +description = "Prove UniformSparsestCut (openai/math family 117: Uniform sparsest cut: hardness and semidefinite gaps) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniformSparsestCut.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniformSparsestCut" +family = "117" +family_title = "Uniform sparsest cut: hardness and semidefinite gaps" +subject = "Theoretical computer science" +theorems = ["OAI.UniformSparsestCut.mainGap"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.SparsestCut.Main" +reference_modules = 55 +reference_lean_bytes = 488362 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 470 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12139 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/uniform-sparsest-cut/tests/Challenge.lean b/tasks/uniform-sparsest-cut/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..b6d86522ae638ac47d23f0b25b98159de703fd02 --- /dev/null +++ b/tasks/uniform-sparsest-cut/tests/Challenge.lean @@ -0,0 +1,55 @@ +import Mathlib + +namespace OAI + +noncomputable section + +open scoped BigOperators + +namespace UniformSparsestCut + +structure Capacity (n : ℕ) where + cap : Fin n → Fin n → ℝ + nonneg : ∀ i j, 0 ≤ cap i j + symm : ∀ i j, cap i j = cap j i + diagonal : ∀ i, cap i i = 0 + +def pairSum {n : ℕ} (f : Fin n → Fin n → ℝ) : ℝ := + ∑ i, ∑ j, if i < j then f i j else 0 + +noncomputable def cutRatio {n : ℕ} (C : Capacity n) (B : Finset (Fin n)) : ℝ := + (∑ i ∈ B, ∑ j ∈ Bᶜ, C.cap i j) / + ((B.card : ℝ) * ((n : ℝ) - (B.card : ℝ))) + +noncomputable def OPT {n : ℕ} (C : Capacity n) : ℝ := + sInf {r | ∃ B : Finset (Fin n), B.Nonempty ∧ B ≠ Finset.univ ∧ r = cutRatio C B} + +def NegativeType {n : ℕ} (d : Fin n → Fin n → ℝ) : Prop := + (∃ x : Fin n → EuclideanSpace ℝ (Fin n), ∀ i j, d i j = ‖x i - x j‖ ^ 2) ∧ + ∀ i j k, d i k ≤ d i j + d j k + +def Feasible {n : ℕ} (d : Fin n → Fin n → ℝ) : Prop := + NegativeType d ∧ pairSum d = 1 + +noncomputable def glValue {n : ℕ} (C : Capacity n) : ℝ := + sInf {r | ∃ d : Fin n → Fin n → ℝ, Feasible d ∧ + r = pairSum (fun i j => C.cap i j * d i j)} + +open Filter + +theorem mainGap : + ∃ c : ℝ, 0 < c ∧ + ∃ n : ℕ → ℕ, ∃ C : (j : ℕ) → Capacity (n j), + (∀ j, 2 ≤ n j) ∧ + Tendsto n atTop atTop ∧ + (∀ j, 0 < glValue (C j)) ∧ + ∀ᶠ j in atTop, + c * Real.sqrt (Real.log (n j : ℝ)) / (Real.log (Real.log (n j : ℝ))) ^ 3 ≤ + OPT (C j) / glValue (C j) := by + sorry + +end UniformSparsestCut + +end + +end OAI diff --git a/tasks/uniform-sparsest-cut/tests/grade.py b/tasks/uniform-sparsest-cut/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/uniform-sparsest-cut/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/uniform-sparsest-cut/tests/task.json b/tasks/uniform-sparsest-cut/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..954929142eab1064950fd84409d5bc9c14a48479 --- /dev/null +++ b/tasks/uniform-sparsest-cut/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniformSparsestCut", + "comparator": { + "theorem_names": [ + "OAI.UniformSparsestCut.mainGap" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11239 +} \ No newline at end of file diff --git a/tasks/uniform-sparsest-cut/tests/test.sh b/tasks/uniform-sparsest-cut/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/uniform-sparsest-cut/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/unique-games-theorem/environment/Dockerfile b/tasks/unique-games-theorem/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/unique-games-theorem/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/unique-games-theorem/environment/fetch_mathlib.sh b/tasks/unique-games-theorem/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/unique-games-theorem/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/unique-games-theorem/environment/lake-manifest.json b/tasks/unique-games-theorem/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/unique-games-theorem/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/unique-games-theorem/environment/lakefile.lean b/tasks/unique-games-theorem/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/unique-games-theorem/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/unique-games-theorem/environment/lean_setup.sh b/tasks/unique-games-theorem/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/unique-games-theorem/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/unique-games-theorem/environment/pack_submission.py b/tasks/unique-games-theorem/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/unique-games-theorem/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/unique-games-theorem/instruction.md b/tasks/unique-games-theorem/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..979e580a081aa06679960e7e180e3483a1a5a3c3 --- /dev/null +++ b/tasks/unique-games-theorem/instruction.md @@ -0,0 +1,290 @@ +# openai/math challenge `UniqueGamesTheorem` (family 102) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 102 of the release, *The Unique Games Conjecture and optimal approximation thresholds* +(Theoretical computer science). The family as a whole: Proves Khot's Unique Games Conjecture. Independent direct reductions also establish NP-hardness, on unweighted graphs, of approximation beyond the Goemans–Williamson ratio for Max-Cut, below factor two for Vertex Cover, and within any fixed constant factor for Min-UnCut and directed feedback vertex set. These direct proofs use established PCP and Label Cover hardness results. + +The challenge is `UniqueGamesTheorem`, also at `/opt/openai-math/challenges/UniqueGamesTheorem.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace UniqueGamesTheorem.Foundations.Target + +/-- Finite forward and inverse tables make totality and invertibility explicit. +An eventual external encoding only needs to serialize the forward table. -/ +structure PermutationTable (alphabet : Nat) where + images : Vector (Fin alphabet) alphabet + inverseImages : Vector (Fin alphabet) alphabet + leftInverse : ∀ label : Fin alphabet, inverseImages[images[label]] = label + rightInverse : ∀ label : Fin alphabet, images[inverseImages[label]] = label + +structure Constraint (vertices alphabet : Nat) where + source : Fin vertices + target : Fin vertices + permutation : PermutationTable alphabet + +def Constraint.satisfied {n q : Nat} (constraint : Constraint n q) + (labeling : Fin n → Fin q) : Bool := + decide (constraint.permutation.images[labeling constraint.source] = labeling constraint.target) + +/-- Constraint occurrences are list entries, so repeated parallel edges retain +their multiplicity. No weights are hidden in this representation. -/ +structure Instance (alphabet : Nat) where + vertices : Nat + constraints : List (Constraint vertices alphabet) + nonempty : constraints ≠ [] + +def countSatisfied {n q : Nat} (labeling : Fin n → Fin q) : + List (Constraint n q) → Nat + | [] => 0 + | constraint :: rest => + (if constraint.satisfied labeling then 1 else 0) + countSatisfied labeling rest + +end UniqueGamesTheorem.Foundations.Target + +namespace UniqueGamesTheorem.BinaryFormula + +open UniqueGamesTheorem.Foundations + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +/-- An ordinary conjunction of three-slot clauses with sparse variable names. +Repeated names and repeated literals are permitted in every clause. -/ +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end UniqueGamesTheorem.BinaryFormula + +namespace UniqueGamesTheorem.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +/-- Equality with the canonical digits rejects alternate padded encodings. -/ +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +/-- Fuel bounds the number of clause iterations, not the size of any name. -/ +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end UniqueGamesTheorem.BinaryEncoding + +namespace UniqueGamesTheorem.BinaryLanguage + +open UniqueGamesTheorem.Foundations + +def language (input : List Bool) : Prop := + ∃ formula, BinaryEncoding.decodeFormula input = some formula ∧ formula.Satisfiable + +end UniqueGamesTheorem.BinaryLanguage + +namespace UniqueGamesTheorem.Integration.BinaryLinear + +abbrev F2 := ZMod 2 + +abbrev Vector (n : Nat) := Fin n → F2 + +end UniqueGamesTheorem.Integration.BinaryLinear + +namespace UniqueGamesTheorem.Integration.TranslationTarget + +open UniqueGamesTheorem.Foundations +open Target + +def IsTranslationInstance {q s : Nat} (coordinates : Fin q ≃ BinaryLinear.Vector s) + (g : Instance q) : Prop := + ∀ constraint ∈ g.constraints, ∃ shift : BinaryLinear.Vector s, + ∀ label : Fin q, + coordinates (constraint.permutation.images[label]) = coordinates label + shift + +end UniqueGamesTheorem.Integration.TranslationTarget + +namespace UniqueGamesTheorem.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +def encodeWords : List Nat → List Bool + | [] => [] + | n :: ns => encodeWord n ++ encodeWords ns + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity + +open Target + +def tableWords {q : Nat} (table : PermutationTable q) : List Nat := + table.images.toList.map Fin.val + +def constraintWords {n q : Nat} (constraint : Constraint n q) : List Nat := + [constraint.source.val, constraint.target.val] ++ tableWords constraint.permutation + +def gameWords {q : Nat} (game : Instance q) : List Nat := + [game.vertices, q, game.constraints.length] ++ game.constraints.flatMap constraintWords + +def gameBits {q : Nat} (game : Instance q) : List Bool := encodeWords (gameWords game) + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +/-- Every physical tape has a finite alphabet. Together with `M.kFin`, this +also makes the disjoint union of all physical tape alphabets finite. -/ +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +namespace UniqueGamesTheorem.Explicit.MachineOutputContract + +open UniqueGamesTheorem.Foundations +open Target +open scoped BigOperators + +/-- A canonical orientation from the false side to the true side. Injectivity +is on occurrence indices, so two distinct list entries cannot be parallel even +when their constraint tables are different. -/ +structure SimpleBipartite {q : Nat} (game : Instance q) where + side : Fin game.vertices → Bool + sourceSide : ∀ i : Fin game.constraints.length, + side game.constraints[i].source = false + targetSide : ∀ i : Fin game.constraints.length, + side game.constraints[i].target = true + endpoints_injective : Function.Injective (fun i : Fin game.constraints.length => + (game.constraints[i].source, game.constraints[i].target)) + +/-- Every parameter, coordinate identification, program, and polynomial is +fixed before the input quantifier. The identity input encoding measures runtime +in the original raw bit length, including sparse binary variable names. -/ +structure BinaryGapReduction (ε δ : ℝ) where + alphabet : Nat + alphabetAtLeastTwo : 2 ≤ alphabet + dimension : Nat + dimensionPositive : 1 ≤ dimension + coordinates : Fin alphabet ≃ Integration.BinaryLinear.Vector dimension + construct : List Bool → Instance alphabet + simpleBipartite : ∀ input, SimpleBipartite (construct input) + translations : ∀ input, + Integration.TranslationTarget.IsTranslationInstance coordinates (construct input) + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + Complexity.gameBits construct + finiteAlphabet : Complexity.MachineFiniteAlphabet.FiniteAlphabet computation.tm + completeness : ∀ input, BinaryLanguage.language input → + ∃ labeling, 1 - ε ≤ + (countSatisfied labeling (construct input).constraints : ℝ) / + (construct input).constraints.length + soundness : ∀ input, ¬BinaryLanguage.language input → + ∀ labeling, (countSatisfied labeling (construct input).constraints : ℝ) / + (construct input).constraints.length ≤ δ + +end UniqueGamesTheorem.Explicit.MachineOutputContract + +namespace UniqueGamesTheorem + +/-- For every fixed pair of errors in `(0, 1/2)`, binary 3SAT reduces in +polynomial time to translation Unique Games with completeness at least `1 - ε` +and soundness at most `δ`. The alphabet and machine depend only on the errors. -/ +theorem theorem11 (ε δ : ℝ) + (hε : 0 < ε) (hεhalf : ε < 1 / 2) + (hδ : 0 < δ) (hδhalf : δ < 1 / 2) : + Nonempty (Explicit.MachineOutputContract.BinaryGapReduction ε δ) := by + sorry + +end UniqueGamesTheorem + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniqueGamesTheorem.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.UniqueGamesTheorem.theorem11` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/unique-games-theorem/solution/closure.txt b/tasks/unique-games-theorem/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..20515a2b7b8fab6797d948af8515599235466820 --- /dev/null +++ b/tasks/unique-games-theorem/solution/closure.txt @@ -0,0 +1,478 @@ +OAI.Computability.UniqueGames.Analysis.A13IndexLemmas +OAI.Computability.UniqueGames.Analysis.A5FrequencyTransportLemmas +OAI.Computability.UniqueGames.Analysis.A5IndexCount +OAI.Computability.UniqueGames.Analysis.A5ReverseIndex +OAI.Computability.UniqueGames.Analysis.AntecedentCountLemmas +OAI.Computability.UniqueGames.Analysis.BadConvolution +OAI.Computability.UniqueGames.Analysis.CompressionCountLemmas +OAI.Computability.UniqueGames.Analysis.DegreeCover +OAI.Computability.UniqueGames.Analysis.DerivativeInduction +OAI.Computability.UniqueGames.Analysis.DyadicError +OAI.Computability.UniqueGames.Analysis.FiberEnergyLemmas +OAI.Computability.UniqueGames.Analysis.HybridCompositionLemmas +OAI.Computability.UniqueGames.Analysis.HybridCounting +OAI.Computability.UniqueGames.Analysis.Identities +OAI.Computability.UniqueGames.Analysis.MatrixCharactersLemmas +OAI.Computability.UniqueGames.Analysis.MatrixEnergy +OAI.Computability.UniqueGames.Analysis.MatrixNoiseLemmas +OAI.Computability.UniqueGames.Analysis.MatrixParityRow +OAI.Computability.UniqueGames.Analysis.MatrixRestrictions +OAI.Computability.UniqueGames.Analysis.MatrixSubspaceCount +OAI.Computability.UniqueGames.Analysis.OperatorPartitions +OAI.Computability.UniqueGames.Analysis.ParityLemmas +OAI.Computability.UniqueGames.Analysis.RestrictionLemmas +OAI.Computability.UniqueGames.Analysis.RestrictionTransport +OAI.Computability.UniqueGames.Analysis.SubspaceCountingLemmas +OAI.Computability.UniqueGames.Analysis.WeightedFourthMoment +OAI.Computability.UniqueGames.Decoding.ActualAdviceBridgeLemmas +OAI.Computability.UniqueGames.Decoding.ActualAdviceStochasticBridgeLemmas +OAI.Computability.UniqueGames.Decoding.ActualAdviceUpperLemmas +OAI.Computability.UniqueGames.Decoding.ActualMatrixContradiction +OAI.Computability.UniqueGames.Decoding.ActualProjectedTransfer +OAI.Computability.UniqueGames.Decoding.ActualSeedPointwise +OAI.Computability.UniqueGames.Decoding.ActualSeedSamplingLemmas +OAI.Computability.UniqueGames.Decoding.ActualSpectralLemmas +OAI.Computability.UniqueGames.Decoding.AdviceFibersLemmas +OAI.Computability.UniqueGames.Decoding.AdviceImageLaw +OAI.Computability.UniqueGames.Decoding.AnswerBridge +OAI.Computability.UniqueGames.Decoding.CoefficientSampling +OAI.Computability.UniqueGames.Decoding.DimensionSelection +OAI.Computability.UniqueGames.Decoding.Experiment +OAI.Computability.UniqueGames.Decoding.IncidenceGap +OAI.Computability.UniqueGames.Decoding.LocalReplay +OAI.Computability.UniqueGames.Decoding.MaskMomentLemmas +OAI.Computability.UniqueGames.Decoding.MatrixCoordinates +OAI.Computability.UniqueGames.Decoding.MatrixGapFromInverseLemmas +OAI.Computability.UniqueGames.Decoding.NativeExperiment +OAI.Computability.UniqueGames.Decoding.PaddedLaw +OAI.Computability.UniqueGames.Decoding.PrivateStrategyLemmas +OAI.Computability.UniqueGames.Decoding.ProductLaw +OAI.Computability.UniqueGames.Decoding.SelectedFiberLaw +OAI.Computability.UniqueGames.Decoding.SparseLawLemmas +OAI.Computability.UniqueGames.Decoding.StochasticBound +OAI.Computability.UniqueGames.Decoding.TableKeysAddressGameLemmas +OAI.Computability.UniqueGames.Decoding.TableKeysCompletenessLemmas +OAI.Computability.UniqueGames.Decoding.TableKeysGame +OAI.Computability.UniqueGames.Decoding.TableKeysLemmas +OAI.Computability.UniqueGames.Decoding.UniformConditioning +OAI.Computability.UniqueGames.Decoding.UpperBound +OAI.Computability.UniqueGames.Decoding.VisiblePoliciesLemmas +OAI.Computability.UniqueGames.Decoding.VisibleTransferLemmas +OAI.Computability.UniqueGames.Decoding.WeightedPartition +OAI.Computability.UniqueGames.Foundations.Basic +OAI.Computability.UniqueGames.Foundations.Conditioning +OAI.Computability.UniqueGames.Foundations.FiniteTrialsLemmas +OAI.Computability.UniqueGames.Foundations.KernelSampling +OAI.Computability.UniqueGames.Foundations.LabelBound +OAI.Computability.UniqueGames.Foundations.MixtureLemmas +OAI.Computability.UniqueGames.Foundations.PinskerLemmas +OAI.Computability.UniqueGames.Foundations.Rectangle +OAI.Computability.UniqueGames.Foundations.SamplingLemmas +OAI.Computability.UniqueGames.Foundations.SharedProfiles +OAI.Computability.UniqueGames.Foundations.ValueLemmas +OAI.Computability.UniqueGames.Gadgets.ActualGadgetLemmas +OAI.Computability.UniqueGames.Gadgets.AdaptivePathsLemmas +OAI.Computability.UniqueGames.Gadgets.BaseConstruction +OAI.Computability.UniqueGames.Gadgets.BlockDescentLemmas +OAI.Computability.UniqueGames.Gadgets.ConcatenationLemmas +OAI.Computability.UniqueGames.Gadgets.Final +OAI.Computability.UniqueGames.Gadgets.NonlinearRecurrenceLemmas +OAI.Computability.UniqueGames.Gadgets.OrientedBlockKernel +OAI.Computability.UniqueGames.Gadgets.QuadraticStageNoise +OAI.Computability.UniqueGames.Gadgets.QuotientLemmas +OAI.Computability.UniqueGames.Games.CompletedSamplingLemmas +OAI.Computability.UniqueGames.Games.FactorizationLemmas +OAI.Computability.UniqueGames.Games.FinishBoundsLemmas +OAI.Computability.UniqueGames.Games.MaskedVariation +OAI.Computability.UniqueGames.Games.Overlap +OAI.Computability.UniqueGames.Games.PartialRevealLemmas +OAI.Computability.UniqueGames.Games.ProductLemmas +OAI.Computability.UniqueGames.Games.ProductMachineSemantics +OAI.Computability.UniqueGames.Games.ProductSoundness +OAI.Computability.UniqueGames.Games.ProductTarget +OAI.Computability.UniqueGames.Games.RoundingLemmas +OAI.Computability.UniqueGames.Games.SelectedCommonMarginalLemmas +OAI.Computability.UniqueGames.Games.SelectedInformationLemmas +OAI.Computability.UniqueGames.Games.SelectionSequence +OAI.Computability.UniqueGames.Games.SubdivisionEncoding +OAI.Computability.UniqueGames.Games.SubdivisionTarget +OAI.Computability.UniqueGames.Games.UniformRoundingTarget +OAI.Computability.UniqueGames.Games.UniformTarget +OAI.Computability.UniqueGames.Games.Variation +OAI.Computability.UniqueGames.Inverse.AffineWitnessLemmas +OAI.Computability.UniqueGames.Inverse.AffineWitnessNormalizationLemmas +OAI.Computability.UniqueGames.Inverse.EqualityFiber +OAI.Computability.UniqueGames.Inverse.FactorSampling +OAI.Computability.UniqueGames.Inverse.KMSAffineRestrictionComplementLemmas +OAI.Computability.UniqueGames.Inverse.KMSAffineRestrictionPresentationLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticBlockFrequenciesLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticCharacterInduction +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridCoordinatesConditions +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridCoordinatesRankLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyImageTransportCoreLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyImageTransportLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyLemmas +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergySupport +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyTransport +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyTransportSmall +OAI.Computability.UniqueGames.Inverse.KMSAnalyticHybridEnergyTransportSmallMixed +OAI.Computability.UniqueGames.Inverse.KMSBasisComparisonLemmas +OAI.Computability.UniqueGames.Inverse.KMSBasisComparisonNeighborsRetention +OAI.Computability.UniqueGames.Inverse.KMSBasisComparisonPseudorandomTupleMapLemmas +OAI.Computability.UniqueGames.Inverse.KMSDimensionOne +OAI.Computability.UniqueGames.Inverse.KMSFoundationLemmas +OAI.Computability.UniqueGames.Inverse.KMSFourthMomentMixedBaseLemmas +OAI.Computability.UniqueGames.Inverse.KMSFourthMomentMixedEnergyLemmas +OAI.Computability.UniqueGames.Inverse.KMSFourthMomentMixedScalarLemmas +OAI.Computability.UniqueGames.Inverse.KMSFourthMomentZoomInAlgebraLemmas +OAI.Computability.UniqueGames.Inverse.KMSKernelOrbitsFourierLemmas +OAI.Computability.UniqueGames.Inverse.KMSLowLevelLemmas +OAI.Computability.UniqueGames.Inverse.MatrixChartIntervalsLemmas +OAI.Computability.UniqueGames.Inverse.MatrixChartLemmas +OAI.Computability.UniqueGames.Inverse.RowErasureConcentration +OAI.Computability.UniqueGames.Inverse.RowErasureLemmas +OAI.Computability.UniqueGames.Inverse.RowErasureMatrixLemmas +OAI.Computability.UniqueGames.Inverse.RowErasureTail +OAI.Computability.UniqueGames.Inverse.ShortcodeFiberConditioning +OAI.Computability.UniqueGames.Inverse.ShortcodeFiberLemmas +OAI.Computability.UniqueGames.Inverse.ShortcodeFromGrassmannLemmas +OAI.Computability.UniqueGames.Inverse.ShortcodeInterfaceLemmas +OAI.Computability.UniqueGames.Inverse.ShortcodeTheorem +OAI.Computability.UniqueGames.Machines.FinalCNFLoopLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFMachineLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFOutputLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFPattern +OAI.Computability.UniqueGames.Machines.FinalCNFRowPlanLemmas +OAI.Computability.UniqueGames.Machines.FinalCNFStream +OAI.Computability.UniqueGames.Machines.FinalCNFTableAdapter +OAI.Computability.UniqueGames.Machines.FinalCNFTemplate +OAI.Computability.UniqueGames.Machines.GraphCounterFinish +OAI.Computability.UniqueGames.Machines.GraphCounterModel +OAI.Computability.UniqueGames.Machines.GraphCounterStartLemmas +OAI.Computability.UniqueGames.Machines.GraphIterationBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineAppendAt +OAI.Computability.UniqueGames.Machines.MachineBinaryFormulaLemmas +OAI.Computability.UniqueGames.Machines.MachineBinaryHeaderMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryInputReductionLemmas +OAI.Computability.UniqueGames.Machines.MachineBinaryLiteralMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryNameCompare +OAI.Computability.UniqueGames.Machines.MachineBinaryNameMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryNameSearch +OAI.Computability.UniqueGames.Machines.MachineBinaryParsingLemmas +OAI.Computability.UniqueGames.Machines.MachineBinaryRenameLoop +OAI.Computability.UniqueGames.Machines.MachineBinaryRenameMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryRenameWords +OAI.Computability.UniqueGames.Machines.MachineBinaryTokenMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryTotalInputMachine +OAI.Computability.UniqueGames.Machines.MachineBinaryValidatorMachine +OAI.Computability.UniqueGames.Machines.MachineCanonicalOutputLemmas +OAI.Computability.UniqueGames.Machines.MachineCeilingPower +OAI.Computability.UniqueGames.Machines.MachineClone100 +OAI.Computability.UniqueGames.Machines.MachineClone100Certified +OAI.Computability.UniqueGames.Machines.MachineClone100Headers +OAI.Computability.UniqueGames.Machines.MachineClone100Loop +OAI.Computability.UniqueGames.Machines.MachineClone100Run +OAI.Computability.UniqueGames.Machines.MachineClone100TableLemmas +OAI.Computability.UniqueGames.Machines.MachineClone100Triples +OAI.Computability.UniqueGames.Machines.MachineCloudCount +OAI.Computability.UniqueGames.Machines.MachineCloudPadding +OAI.Computability.UniqueGames.Machines.MachineCloudPrefix +OAI.Computability.UniqueGames.Machines.MachineCloudRankLemmas +OAI.Computability.UniqueGames.Machines.MachineCompare +OAI.Computability.UniqueGames.Machines.MachineCompositionLemmas +OAI.Computability.UniqueGames.Machines.MachineControlLemmas +OAI.Computability.UniqueGames.Machines.MachineCopy +OAI.Computability.UniqueGames.Machines.MachineDrain +OAI.Computability.UniqueGames.Machines.MachineDrainManyLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderFamily +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyLoop +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyTapes +OAI.Computability.UniqueGames.Machines.MachineExpanderFamilyTransferLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderRow +OAI.Computability.UniqueGames.Machines.MachineExpanderRowCleanup +OAI.Computability.UniqueGames.Machines.MachineExpanderRowDivision +OAI.Computability.UniqueGames.Machines.MachineExpanderRowEmitLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderRowFrames +OAI.Computability.UniqueGames.Machines.MachineExpanderTable +OAI.Computability.UniqueGames.Machines.MachineExpanderTableLoop +OAI.Computability.UniqueGames.Machines.MachineExpanderTableProgramLemmas +OAI.Computability.UniqueGames.Machines.MachineExpanderTableReverse +OAI.Computability.UniqueGames.Machines.MachineExpanderTableRows +OAI.Computability.UniqueGames.Machines.MachineFiniteAlphabet +OAI.Computability.UniqueGames.Machines.MachineFiniteTable +OAI.Computability.UniqueGames.Machines.MachineFixedCopiesLemmas +OAI.Computability.UniqueGames.Machines.MachineFixedDivMod +OAI.Computability.UniqueGames.Machines.MachineInitialHeaders +OAI.Computability.UniqueGames.Machines.MachineLazyCodec +OAI.Computability.UniqueGames.Machines.MachineLazyRows +OAI.Computability.UniqueGames.Machines.MachineLazyTable +OAI.Computability.UniqueGames.Machines.MachineLazyTableRuntime +OAI.Computability.UniqueGames.Machines.MachineLemmas +OAI.Computability.UniqueGames.Machines.MachineLogCounter +OAI.Computability.UniqueGames.Machines.MachineLookupCore +OAI.Computability.UniqueGames.Machines.MachineLookupDiscard +OAI.Computability.UniqueGames.Machines.MachineLookupLemmas +OAI.Computability.UniqueGames.Machines.MachineOverlayRows +OAI.Computability.UniqueGames.Machines.MachineOverlayTable +OAI.Computability.UniqueGames.Machines.MachinePaddedExpanderFamilyBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddedOverlay +OAI.Computability.UniqueGames.Machines.MachinePaddedOverlayRuntimeLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddingRowsLemmas +OAI.Computability.UniqueGames.Machines.MachinePaddingTable +OAI.Computability.UniqueGames.Machines.MachinePortReindex +OAI.Computability.UniqueGames.Machines.MachineProductFieldLemmas +OAI.Computability.UniqueGames.Machines.MachineProductGatherBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineProductHeadersFrameLemmas +OAI.Computability.UniqueGames.Machines.MachineProductProgram +OAI.Computability.UniqueGames.Machines.MachineProductRuntime +OAI.Computability.UniqueGames.Machines.MachineProductSeed +OAI.Computability.UniqueGames.Machines.MachineRadixStepLemmas +OAI.Computability.UniqueGames.Machines.MachineRegularDummyRow +OAI.Computability.UniqueGames.Machines.MachineRegularFamily +OAI.Computability.UniqueGames.Machines.MachineRegularInternalRow +OAI.Computability.UniqueGames.Machines.MachineRegularLift +OAI.Computability.UniqueGames.Machines.MachineRegularMetadata +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalBody +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalBodyBounds +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalClean +OAI.Computability.UniqueGames.Machines.MachineRegularOriginalRow +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerBody +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerBodyBounds +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerCleanup +OAI.Computability.UniqueGames.Machines.MachineRegularOwnerProgram +OAI.Computability.UniqueGames.Machines.MachineRegularTable +OAI.Computability.UniqueGames.Machines.MachineRegularTableBoundsLemmas +OAI.Computability.UniqueGames.Machines.MachineRegularTableTrace +OAI.Computability.UniqueGames.Machines.MachineRegularVertexBlock +OAI.Computability.UniqueGames.Machines.MachineRepeat +OAI.Computability.UniqueGames.Machines.MachineSingleOrbitBridgeLemmas +OAI.Computability.UniqueGames.Machines.MachineSingleOrbitFinishLemmas +OAI.Computability.UniqueGames.Machines.MachineSingleOrbitProgramLemmas +OAI.Computability.UniqueGames.Machines.MachineSubdivisionBody +OAI.Computability.UniqueGames.Machines.MachineSubdivisionBodySpecLemmas +OAI.Computability.UniqueGames.Machines.MachineSubdivisionDynamicRowsLemmas +OAI.Computability.UniqueGames.Machines.MachineSubdivisionTableRead +OAI.Computability.UniqueGames.Machines.MachineSubroutineLemmas +OAI.Computability.UniqueGames.Machines.MachineTableSplit +OAI.Computability.UniqueGames.Machines.MachineTransducerCopy +OAI.Computability.UniqueGames.Machines.MachineTranslationTable +OAI.Computability.UniqueGames.Machines.MachineTupleOdometer +OAI.Computability.UniqueGames.Machines.MachineUnaryAddAt +OAI.Computability.UniqueGames.Machines.MachineUnaryAffineAt +OAI.Computability.UniqueGames.Machines.MachineUnaryEqualityBit +OAI.Computability.UniqueGames.Machines.MachineUnaryLessAtLemmas +OAI.Computability.UniqueGames.Machines.MachineUnaryMultiply +OAI.Computability.UniqueGames.Machines.MachineUniformCopyOrder +OAI.Computability.UniqueGames.Machines.MachineUniformRounding +OAI.Computability.UniqueGames.Machines.MachineUniformRun +OAI.Computability.UniqueGames.Machines.MachineVertexPadding +OAI.Computability.UniqueGames.Machines.PoweringGlobalEnumerationLemmas +OAI.Computability.UniqueGames.Machines.PoweringInitializeFrame +OAI.Computability.UniqueGames.Machines.PoweringMachineEqualityField +OAI.Computability.UniqueGames.Machines.PoweringMachineFinish +OAI.Computability.UniqueGames.Machines.PoweringMachineInitialize +OAI.Computability.UniqueGames.Machines.PoweringMachineLoop +OAI.Computability.UniqueGames.Machines.PoweringMachineOuterLoopLemmas +OAI.Computability.UniqueGames.Machines.PoweringMachineRelationLemmas +OAI.Computability.UniqueGames.Machines.PoweringMachineRow +OAI.Computability.UniqueGames.Machines.PoweringMachineRowBody +OAI.Computability.UniqueGames.Machines.PoweringMachineVertex +OAI.Computability.UniqueGames.Machines.PoweringMasterState +OAI.Computability.UniqueGames.Machines.PoweringPlanBudget +OAI.Computability.UniqueGames.Machines.PoweringPolynomialBudgetLemmas +OAI.Computability.UniqueGames.Machines.Runtime +OAI.Computability.UniqueGames.Main +OAI.Computability.UniqueGames.Model +OAI.Computability.UniqueGames.PCP.Addresses +OAI.Computability.UniqueGames.PCP.AlphabetGraphLemmas +OAI.Computability.UniqueGames.PCP.AlphabetReductionLemmas +OAI.Computability.UniqueGames.PCP.AlphabetRetractionLemmas +OAI.Computability.UniqueGames.PCP.AlphabetTableBoundsLemmas +OAI.Computability.UniqueGames.PCP.AmplificationIteration +OAI.Computability.UniqueGames.PCP.AssignmentTester +OAI.Computability.UniqueGames.PCP.BinaryParityReduction +OAI.Computability.UniqueGames.PCP.Body +OAI.Computability.UniqueGames.PCP.CayleySampling +OAI.Computability.UniqueGames.PCP.CayleyTailCount +OAI.Computability.UniqueGames.PCP.ClauseVerifierLemmas +OAI.Computability.UniqueGames.PCP.CleanupLemmas +OAI.Computability.UniqueGames.PCP.Clone100 +OAI.Computability.UniqueGames.PCP.Clone100Encoding +OAI.Computability.UniqueGames.PCP.Clone100Triples +OAI.Computability.UniqueGames.PCP.CloudRoundingLemmas +OAI.Computability.UniqueGames.PCP.CodeComposition +OAI.Computability.UniqueGames.PCP.CompareLoop +OAI.Computability.UniqueGames.PCP.DriverLemmas +OAI.Computability.UniqueGames.PCP.EmitRows +OAI.Computability.UniqueGames.PCP.Emitter +OAI.Computability.UniqueGames.PCP.ExpanderRowControlLemmas +OAI.Computability.UniqueGames.PCP.ExpanderTableEnumeration +OAI.Computability.UniqueGames.PCP.ExpanderTables +OAI.Computability.UniqueGames.PCP.ExpandersLemmas +OAI.Computability.UniqueGames.PCP.FinalBooleanVerifier +OAI.Computability.UniqueGames.PCP.FinalConstantsLemmas +OAI.Computability.UniqueGames.PCP.FinalTableFormula +OAI.Computability.UniqueGames.PCP.FoldedEquationLemmas +OAI.Computability.UniqueGames.PCP.FourierResponseLemmas +OAI.Computability.UniqueGames.PCP.GenericGraphTables +OAI.Computability.UniqueGames.PCP.GraphTables +OAI.Computability.UniqueGames.PCP.HonestTestLemmas +OAI.Computability.UniqueGames.PCP.InitialGraphLemmas +OAI.Computability.UniqueGames.PCP.Initialization +OAI.Computability.UniqueGames.PCP.InputLemmas +OAI.Computability.UniqueGames.PCP.LoopInitializationLemmas +OAI.Computability.UniqueGames.PCP.LoopState +OAI.Computability.UniqueGames.PCP.MachineRawInitialTable +OAI.Computability.UniqueGames.PCP.NameCompaction +OAI.Computability.UniqueGames.PCP.OverlayLemmas +OAI.Computability.UniqueGames.PCP.PortTableEncoding +OAI.Computability.UniqueGames.PCP.PortTableLookup +OAI.Computability.UniqueGames.PCP.PoweringLabelsLemmas +OAI.Computability.UniqueGames.PCP.PoweringOpinionTables +OAI.Computability.UniqueGames.PCP.PoweringOpinionsLemmas +OAI.Computability.UniqueGames.PCP.PoweringPortReindexLemmas +OAI.Computability.UniqueGames.PCP.PoweringTableLayout +OAI.Computability.UniqueGames.PCP.PoweringTableSemanticsLemmas +OAI.Computability.UniqueGames.PCP.PoweringTablesLemmas +OAI.Computability.UniqueGames.PCP.Preprocessing +OAI.Computability.UniqueGames.PCP.PreprocessingInternalRows +OAI.Computability.UniqueGames.PCP.PreprocessingLazyWords +OAI.Computability.UniqueGames.PCP.PreprocessingOverlayTables +OAI.Computability.UniqueGames.PCP.PreprocessingOverlayWords +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingOffsets +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingTables +OAI.Computability.UniqueGames.PCP.PreprocessingPaddingWords +OAI.Computability.UniqueGames.PCP.PreprocessingRegularLoopWordsLemmas +OAI.Computability.UniqueGames.PCP.PreprocessingRegularSoundness +OAI.Computability.UniqueGames.PCP.PreprocessingRegularTablesLemmas +OAI.Computability.UniqueGames.PCP.PreprocessingRegularWords +OAI.Computability.UniqueGames.PCP.PreprocessingTableSpectral +OAI.Computability.UniqueGames.PCP.PreprocessingTablesLemmas +OAI.Computability.UniqueGames.PCP.QueriesLemmas +OAI.Computability.UniqueGames.PCP.RawInitialMachineBody +OAI.Computability.UniqueGames.PCP.RawInitialMachineCleanup +OAI.Computability.UniqueGames.PCP.RawInitialMachineFinish +OAI.Computability.UniqueGames.PCP.RawInitialMachineLoop +OAI.Computability.UniqueGames.PCP.RawInitialMachineLoopData +OAI.Computability.UniqueGames.PCP.RawInitialMachinePhases +OAI.Computability.UniqueGames.PCP.RawInitialMachineReadClause +OAI.Computability.UniqueGames.PCP.RawInitialMachineRows +OAI.Computability.UniqueGames.PCP.RawInitialMachineStart +OAI.Computability.UniqueGames.PCP.RawInitialTablesLemmas +OAI.Computability.UniqueGames.PCP.RoundSize +OAI.Computability.UniqueGames.PCP.RuntimeModel +OAI.Computability.UniqueGames.PCP.Setup +OAI.Computability.UniqueGames.PCP.SourceAddressArithmeticLemmas +OAI.Computability.UniqueGames.PCP.SourceContextClear +OAI.Computability.UniqueGames.PCP.SourceContextLoad +OAI.Computability.UniqueGames.PCP.SourceDescriptorEmissionLemmas +OAI.Computability.UniqueGames.PCP.SourceFieldArrayLemmas +OAI.Computability.UniqueGames.PCP.SourceGapLemmas +OAI.Computability.UniqueGames.PCP.SourceHeaderAccumulate +OAI.Computability.UniqueGames.PCP.SourceHeaderCounts +OAI.Computability.UniqueGames.PCP.SourceHonestLemmas +OAI.Computability.UniqueGames.PCP.SourceIncidence +OAI.Computability.UniqueGames.PCP.SourceLoopInitLemmas +OAI.Computability.UniqueGames.PCP.SourceMachine +OAI.Computability.UniqueGames.PCP.SourceNoiseParameterLemmas +OAI.Computability.UniqueGames.PCP.SourceOccurrences +OAI.Computability.UniqueGames.PCP.SourceQueryLoopLemmas +OAI.Computability.UniqueGames.PCP.SourceQueryOrderLemmas +OAI.Computability.UniqueGames.PCP.SourceRuntimeSpace +OAI.Computability.UniqueGames.PCP.SourceSignaturePrepareLemmas +OAI.Computability.UniqueGames.PCP.SourceTupleBody +OAI.Computability.UniqueGames.PCP.SourceTupleBound +OAI.Computability.UniqueGames.PCP.Table +OAI.Computability.UniqueGames.PCP.TableGapReductionLemmas +OAI.Computability.UniqueGames.PCP.TableIteration +OAI.Computability.UniqueGames.PCP.VertexPadding +OAI.Computability.UniqueGames.PCP.ZigzagGraphsLemmas +OAI.Computability.UniqueGames.Quadratic.Alignment +OAI.Computability.UniqueGames.Quadratic.AlignmentCertificateLemmas +OAI.Computability.UniqueGames.Quadratic.Block +OAI.Computability.UniqueGames.Quadratic.BlockCounting +OAI.Computability.UniqueGames.Quadratic.BlockDimension +OAI.Computability.UniqueGames.Quadratic.BlockKernelLemmas +OAI.Computability.UniqueGames.Quadratic.BlockNoise +OAI.Computability.UniqueGames.Quadratic.BlockNoiseProbabilityLemmas +OAI.Computability.UniqueGames.Quadratic.BlockRestriction +OAI.Computability.UniqueGames.Quadratic.BlockSpanLemmas +OAI.Computability.UniqueGames.Quadratic.BlockTrace +OAI.Computability.UniqueGames.Quadratic.GenericFieldChoice +OAI.Computability.UniqueGames.Quadratic.GenericSeparationLemmas +OAI.Computability.UniqueGames.Quadratic.GenericSubspaceProbability +OAI.Computability.UniqueGames.Quadratic.HarmonicLoss +OAI.Computability.UniqueGames.Quadratic.OrientedRestrictionLemmas +OAI.Computability.UniqueGames.Quadratic.TraceDual +OAI.Computability.UniqueGames.Quadratic.UniformSubspaces +OAI.Computability.UniqueGames.Reduction.ActualCanonicalLemmas +OAI.Computability.UniqueGames.Reduction.ActualCompleteness +OAI.Computability.UniqueGames.Reduction.ActualGame +OAI.Computability.UniqueGames.Reduction.ActualSourceLemmas +OAI.Computability.UniqueGames.Reduction.AddressMachineInitial +OAI.Computability.UniqueGames.Reduction.AddressMachineLoopLemmas +OAI.Computability.UniqueGames.Reduction.AddressMachineSpace +OAI.Computability.UniqueGames.Reduction.AddressOdometerSchedule +OAI.Computability.UniqueGames.Reduction.AddressOutcomeSpecs +OAI.Computability.UniqueGames.Reduction.AddressOutputSize +OAI.Computability.UniqueGames.Reduction.AddressTupleBody +OAI.Computability.UniqueGames.Reduction.AddressTupleBudget +OAI.Computability.UniqueGames.Reduction.AddressTupleCleanupLemmas +OAI.Computability.UniqueGames.Reduction.AddressTuplePolynomialLemmas +OAI.Computability.UniqueGames.Reduction.BinaryCoordinates +OAI.Computability.UniqueGames.Reduction.BinaryLinear +OAI.Computability.UniqueGames.Reduction.CanonicalBodyTemplateLemmas +OAI.Computability.UniqueGames.Reduction.CloneMachineModelLemmas +OAI.Computability.UniqueGames.Reduction.CloneTable +OAI.Computability.UniqueGames.Reduction.EncodingLemmas +OAI.Computability.UniqueGames.Reduction.ExplicitLemmas +OAI.Computability.UniqueGames.Reduction.FinalParametersLemmas +OAI.Computability.UniqueGames.Reduction.FinishReduction +OAI.Computability.UniqueGames.Reduction.FixedOutcomes +OAI.Computability.UniqueGames.Reduction.FromMatrixGap +OAI.Computability.UniqueGames.Reduction.GameEncodingSizeLemmas +OAI.Computability.UniqueGames.Reduction.GapSemanticsLemmas +OAI.Computability.UniqueGames.Reduction.IncidenceProbabilityLemmas +OAI.Computability.UniqueGames.Reduction.MachineAddressEdgeLemmas +OAI.Computability.UniqueGames.Reduction.MachineAddressHeaders +OAI.Computability.UniqueGames.Reduction.MachineFieldTemplate +OAI.Computability.UniqueGames.Reduction.MachineReverse +OAI.Computability.UniqueGames.Reduction.MachineRhsLoad +OAI.Computability.UniqueGames.Reduction.MachineSubstitution +OAI.Computability.UniqueGames.Reduction.MachineTemplateAddress +OAI.Computability.UniqueGames.Reduction.MachineTransducer +OAI.Computability.UniqueGames.Reduction.MachineTransfer +OAI.Computability.UniqueGames.Reduction.NoiseEnumerationLemmas +OAI.Computability.UniqueGames.Reduction.OuterCompletenessLemmas +OAI.Computability.UniqueGames.Reduction.OutputSize +OAI.Computability.UniqueGames.Reduction.OutputTranslationsLemmas +OAI.Computability.UniqueGames.Reduction.ParameterSelection +OAI.Computability.UniqueGames.Reduction.RealTargetLemmas +OAI.Computability.UniqueGames.Reduction.SourceEquationLookupLemmas +OAI.Computability.UniqueGames.Reduction.SourceIncidenceLemmas +OAI.Computability.UniqueGames.Reduction.TableReduction +OAI.Computability.UniqueGames.Reduction.WeightRounding +OAI.Computability.UniqueGames.Reduction.WeightedSource +OAI.Computability.UniqueGames.Repetition.AnalyticCheegerLemmas +OAI.Computability.UniqueGames.Repetition.AnalyticRateLemmas +OAI.Computability.UniqueGames.Repetition.CollisionLemmas +OAI.Computability.UniqueGames.Repetition.RoundingKernel +OAI.Computability.UniqueGames.Repetition.RoundingPaddingLemmas +OAI.Computability.UniqueGames.Repetition.RoundingSampling +OAI.Computability.UniqueGames.Repetition.RoundingThresholdLemmas +OAI.Computability.UniqueGames.Repetition.TensorAlgebraLemmas +OAI.Computability.UniqueGames.Soundness.ActualCanonicalPullbackLemmas +OAI.Computability.UniqueGames.Soundness.ActualPointAnswers +OAI.Computability.UniqueGames.Soundness.ConditionalLocality +OAI.Computability.UniqueGames.Soundness.ConditionalReindex +OAI.Computability.UniqueGames.Soundness.ConditionalSimulationLemmas +OAI.Computability.UniqueGames.Soundness.ExpectationComparisonLemmas +OAI.Computability.UniqueGames.Soundness.LinearMapDensityLemmas +OAI.Computability.UniqueGames.Soundness.PartnerLinearLemmas +OAI.Computability.UniqueGames.Soundness.PartnerMapCoordinates +OAI.Computability.UniqueGames.Soundness.RawPrivateTable +OAI.Computability.UniqueGames.Soundness.RawTargetLawLemmas +OAI.Computability.UniqueGames.Soundness.SubsetIntersectionLemmas +OAI.Computability.UniqueGames.Soundness.ZeroInformationLemmas +OAI.Computability.UniqueGames.Theorem diff --git a/tasks/unique-games-theorem/solution/reference.py b/tasks/unique-games-theorem/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/unique-games-theorem/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/unique-games-theorem/solution/solve.sh b/tasks/unique-games-theorem/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..f73ca2362c763a2f987c0b05641d3b9a9543dd14 --- /dev/null +++ b/tasks/unique-games-theorem/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniqueGamesTheorem, i.e. module OAI.Computability.UniqueGames.Main and the +# 478 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.UniqueGames.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniqueGamesTheorem" diff --git a/tasks/unique-games-theorem/task.toml b/tasks/unique-games-theorem/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ff2cacd876019538a2cb92f72ded58dc3d128f96 --- /dev/null +++ b/tasks/unique-games-theorem/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/unique-games-theorem" +version = "1.0.0" +description = "Prove UniqueGamesTheorem (openai/math family 102: The Unique Games Conjecture and optimal approximation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniqueGamesTheorem.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniqueGamesTheorem" +family = "102" +family_title = "The Unique Games Conjecture and optimal approximation thresholds" +subject = "Theoretical computer science" +theorems = ["OAI.UniqueGamesTheorem.theorem11"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.UniqueGames.Main" +reference_modules = 478 +reference_lean_bytes = 8704327 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1292 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 19533 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/unique-games-theorem/tests/Challenge.lean b/tasks/unique-games-theorem/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..5e0e18daac92b039a30dc500decc576b91fddb91 --- /dev/null +++ b/tasks/unique-games-theorem/tests/Challenge.lean @@ -0,0 +1,239 @@ +import Mathlib + +namespace OAI + +namespace UniqueGamesTheorem.Foundations.Target + +/-- Finite forward and inverse tables make totality and invertibility explicit. +An eventual external encoding only needs to serialize the forward table. -/ +structure PermutationTable (alphabet : Nat) where + images : Vector (Fin alphabet) alphabet + inverseImages : Vector (Fin alphabet) alphabet + leftInverse : ∀ label : Fin alphabet, inverseImages[images[label]] = label + rightInverse : ∀ label : Fin alphabet, images[inverseImages[label]] = label + +structure Constraint (vertices alphabet : Nat) where + source : Fin vertices + target : Fin vertices + permutation : PermutationTable alphabet + +def Constraint.satisfied {n q : Nat} (constraint : Constraint n q) + (labeling : Fin n → Fin q) : Bool := + decide (constraint.permutation.images[labeling constraint.source] = labeling constraint.target) + +/-- Constraint occurrences are list entries, so repeated parallel edges retain +their multiplicity. No weights are hidden in this representation. -/ +structure Instance (alphabet : Nat) where + vertices : Nat + constraints : List (Constraint vertices alphabet) + nonempty : constraints ≠ [] + +def countSatisfied {n q : Nat} (labeling : Fin n → Fin q) : + List (Constraint n q) → Nat + | [] => 0 + | constraint :: rest => + (if constraint.satisfied labeling then 1 else 0) + countSatisfied labeling rest + +end UniqueGamesTheorem.Foundations.Target + +namespace UniqueGamesTheorem.BinaryFormula + +open UniqueGamesTheorem.Foundations + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +/-- An ordinary conjunction of three-slot clauses with sparse variable names. +Repeated names and repeated literals are permitted in every clause. -/ +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end UniqueGamesTheorem.BinaryFormula + +namespace UniqueGamesTheorem.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +/-- Equality with the canonical digits rejects alternate padded encodings. -/ +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +/-- Fuel bounds the number of clause iterations, not the size of any name. -/ +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _ + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end UniqueGamesTheorem.BinaryEncoding + +namespace UniqueGamesTheorem.BinaryLanguage + +open UniqueGamesTheorem.Foundations + +def language (input : List Bool) : Prop := + ∃ formula, BinaryEncoding.decodeFormula input = some formula ∧ formula.Satisfiable + +end UniqueGamesTheorem.BinaryLanguage + +namespace UniqueGamesTheorem.Integration.BinaryLinear + +abbrev F2 := ZMod 2 + +abbrev Vector (n : Nat) := Fin n → F2 + +end UniqueGamesTheorem.Integration.BinaryLinear + +namespace UniqueGamesTheorem.Integration.TranslationTarget + +open UniqueGamesTheorem.Foundations +open Target + +def IsTranslationInstance {q s : Nat} (coordinates : Fin q ≃ BinaryLinear.Vector s) + (g : Instance q) : Prop := + ∀ constraint ∈ g.constraints, ∃ shift : BinaryLinear.Vector s, + ∀ label : Fin q, + coordinates (constraint.permutation.images[label]) = coordinates label + shift + +end UniqueGamesTheorem.Integration.TranslationTarget + +namespace UniqueGamesTheorem.Foundations.Complexity + +def encodeWord (n : Nat) : List Bool := List.replicate n true ++ [false] + +def encodeWords : List Nat → List Bool + | [] => [] + | n :: ns => encodeWord n ++ encodeWords ns + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity + +open Target + +def tableWords {q : Nat} (table : PermutationTable q) : List Nat := + table.images.toList.map Fin.val + +def constraintWords {n q : Nat} (constraint : Constraint n q) : List Nat := + [constraint.source.val, constraint.target.val] ++ tableWords constraint.permutation + +def gameWords {q : Nat} (game : Instance q) : List Nat := + [game.vertices, q, game.constraints.length] ++ game.constraints.flatMap constraintWords + +def gameBits {q : Nat} (game : Instance q) : List Bool := encodeWords (gameWords game) + +end UniqueGamesTheorem.Foundations.Complexity + +namespace UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +open Turing + +/-- Every physical tape has a finite alphabet. Together with `M.kFin`, this +also makes the disjoint union of all physical tape alphabets finite. -/ +def FiniteAlphabet (M : FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +end UniqueGamesTheorem.Foundations.Complexity.MachineFiniteAlphabet + +namespace UniqueGamesTheorem.Explicit.MachineOutputContract + +open UniqueGamesTheorem.Foundations +open Target +open scoped BigOperators + +/-- A canonical orientation from the false side to the true side. Injectivity +is on occurrence indices, so two distinct list entries cannot be parallel even +when their constraint tables are different. -/ +structure SimpleBipartite {q : Nat} (game : Instance q) where + side : Fin game.vertices → Bool + sourceSide : ∀ i : Fin game.constraints.length, + side game.constraints[i].source = false + targetSide : ∀ i : Fin game.constraints.length, + side game.constraints[i].target = true + endpoints_injective : Function.Injective (fun i : Fin game.constraints.length => + (game.constraints[i].source, game.constraints[i].target)) + +/-- Every parameter, coordinate identification, program, and polynomial is +fixed before the input quantifier. The identity input encoding measures runtime +in the original raw bit length, including sparse binary variable names. -/ +structure BinaryGapReduction (ε δ : ℝ) where + alphabet : Nat + alphabetAtLeastTwo : 2 ≤ alphabet + dimension : Nat + dimensionPositive : 1 ≤ dimension + coordinates : Fin alphabet ≃ Integration.BinaryLinear.Vector dimension + construct : List Bool → Instance alphabet + simpleBipartite : ∀ input, SimpleBipartite (construct input) + translations : ∀ input, + Integration.TranslationTarget.IsTranslationInstance coordinates (construct input) + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + Complexity.gameBits construct + finiteAlphabet : Complexity.MachineFiniteAlphabet.FiniteAlphabet computation.tm + completeness : ∀ input, BinaryLanguage.language input → + ∃ labeling, 1 - ε ≤ + (countSatisfied labeling (construct input).constraints : ℝ) / + (construct input).constraints.length + soundness : ∀ input, ¬BinaryLanguage.language input → + ∀ labeling, (countSatisfied labeling (construct input).constraints : ℝ) / + (construct input).constraints.length ≤ δ + +end UniqueGamesTheorem.Explicit.MachineOutputContract + +namespace UniqueGamesTheorem + +/-- For every fixed pair of errors in `(0, 1/2)`, binary 3SAT reduces in +polynomial time to translation Unique Games with completeness at least `1 - ε` +and soundness at most `δ`. The alphabet and machine depend only on the errors. -/ +theorem theorem11 (ε δ : ℝ) + (hε : 0 < ε) (hεhalf : ε < 1 / 2) + (hδ : 0 < δ) (hδhalf : δ < 1 / 2) : + Nonempty (Explicit.MachineOutputContract.BinaryGapReduction ε δ) := by + sorry + +end UniqueGamesTheorem + +end OAI diff --git a/tasks/unique-games-theorem/tests/grade.py b/tasks/unique-games-theorem/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/unique-games-theorem/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/unique-games-theorem/tests/task.json b/tasks/unique-games-theorem/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..0b9e5970f5fe9ced6d14eea2e20a2cad67e5db77 --- /dev/null +++ b/tasks/unique-games-theorem/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniqueGamesTheorem", + "comparator": { + "theorem_names": [ + "OAI.UniqueGamesTheorem.theorem11" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 18633 +} \ No newline at end of file diff --git a/tasks/unique-games-theorem/tests/test.sh b/tasks/unique-games-theorem/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/unique-games-theorem/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/universal-f-infinity/environment/Dockerfile b/tasks/universal-f-infinity/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/universal-f-infinity/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/universal-f-infinity/environment/fetch_mathlib.sh b/tasks/universal-f-infinity/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/universal-f-infinity/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/universal-f-infinity/environment/lake-manifest.json b/tasks/universal-f-infinity/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/universal-f-infinity/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/universal-f-infinity/environment/lakefile.lean b/tasks/universal-f-infinity/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/universal-f-infinity/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/universal-f-infinity/environment/lean_setup.sh b/tasks/universal-f-infinity/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/universal-f-infinity/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/universal-f-infinity/environment/pack_submission.py b/tasks/universal-f-infinity/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/universal-f-infinity/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/universal-f-infinity/instruction.md b/tasks/universal-f-infinity/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..87a5b2561d5c6d9082de94e7cc1e0319c98818f8 --- /dev/null +++ b/tasks/universal-f-infinity/instruction.md @@ -0,0 +1,76 @@ +# openai/math challenge `UniversalFInfinity` (family 250) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 250 of the release, *The Boone–Higman conjecture and higher finiteness* +(Group theory). The family as a whole: A finitely generated group has decidable word problem exactly when it embeds in a finitely presented simple group, proving the Boone–Higman conjecture. The target can have type $F_\infty$: a classifying space with finitely many cells in each dimension. A single group of type $F_\infty$ can also contain every finitely presented group. + +The challenge is `UniversalFInfinity`, also at `/opt/openai-math/challenges/UniversalFInfinity.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace UniversalFInfinity +universe u + +def HasTypeFInfinity (G : Type u) [Group G] : Prop := + ∃ (X : Type u) (_ : TopologicalSpace X) (_ : T2Space X) + (_ : ConnectedSpace X) (cw : Topology.CWComplex (Set.univ : Set X)), + (∀ n : ℕ, Finite (cw.cell n)) ∧ + (∃ x : X, Nonempty (FundamentalGroup X x ≃* G)) ∧ + ∃ (E : Type u) (_ : TopologicalSpace E) (_ : ContractibleSpace E) + (p : E → X), Function.Surjective p ∧ IsCoveringMap p + +theorem universal_group_of_type_FInfinity : + ∃ (H : Type u) (groupH : Group H), + @HasTypeFInfinity H groupH ∧ + ∀ (G : Type u) [Group G] [Group.IsFinitelyPresented G], + ∃ φ : G →* H, Function.Injective φ := by + sorry + +end UniversalFInfinity + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/UniversalFInfinity.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.UniversalFInfinity.universal_group_of_type_FInfinity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/universal-f-infinity/solution/closure.txt b/tasks/universal-f-infinity/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..3d44060973d8745f18ff138f3437e60856620f95 --- /dev/null +++ b/tasks/universal-f-infinity/solution/closure.txt @@ -0,0 +1,50 @@ +OAI.GroupTheory.UniversalGroup.AscendingTorus +OAI.GroupTheory.UniversalGroup.Attachments +OAI.GroupTheory.UniversalGroup.Benign +OAI.GroupTheory.UniversalGroup.BrownConstruction +OAI.GroupTheory.UniversalGroup.Cayley +OAI.GroupTheory.UniversalGroup.CellRetractions +OAI.GroupTheory.UniversalGroup.CellularApproximation +OAI.GroupTheory.UniversalGroup.CellularAttachment +OAI.GroupTheory.UniversalGroup.CellularChains +OAI.GroupTheory.UniversalGroup.CellularFillings +OAI.GroupTheory.UniversalGroup.CellularLifting +OAI.GroupTheory.UniversalGroup.CentralHNN +OAI.GroupTheory.UniversalGroup.CompactCells +OAI.GroupTheory.UniversalGroup.ControlledCells +OAI.GroupTheory.UniversalGroup.ControlledHomotopies +OAI.GroupTheory.UniversalGroup.CoveringAttachments +OAI.GroupTheory.UniversalGroup.Cylinders +OAI.GroupTheory.UniversalGroup.FiniteEnvelopes +OAI.GroupTheory.UniversalGroup.FiniteHNN +OAI.GroupTheory.UniversalGroup.GeneralPosition +OAI.GroupTheory.UniversalGroup.GraphActions +OAI.GroupTheory.UniversalGroup.GraphBundles +OAI.GroupTheory.UniversalGroup.HigmanEmbedding +OAI.GroupTheory.UniversalGroup.HomotopyProducts +OAI.GroupTheory.UniversalGroup.Idempotents +OAI.GroupTheory.UniversalGroup.Main +OAI.GroupTheory.UniversalGroup.MarkerMachine +OAI.GroupTheory.UniversalGroup.Markers +OAI.GroupTheory.UniversalGroup.MatrixDiagrams +OAI.GroupTheory.UniversalGroup.Milnor +OAI.GroupTheory.UniversalGroup.MilnorControl +OAI.GroupTheory.UniversalGroup.MilnorProducts +OAI.GroupTheory.UniversalGroup.Model +OAI.GroupTheory.UniversalGroup.PathExtensions +OAI.GroupTheory.UniversalGroup.RopeTrick +OAI.GroupTheory.UniversalGroup.SimplexDisk +OAI.GroupTheory.UniversalGroup.Simplicial +OAI.GroupTheory.UniversalGroup.SimplicialProducts +OAI.GroupTheory.UniversalGroup.SphereHomotopies +OAI.GroupTheory.UniversalGroup.StackMachines +OAI.GroupTheory.UniversalGroup.StackPrograms +OAI.GroupTheory.UniversalGroup.TopologicalTowers +OAI.GroupTheory.UniversalGroup.TorusBundles +OAI.GroupTheory.UniversalGroup.TorusHomotopies +OAI.GroupTheory.UniversalGroup.TorusSpheres +OAI.GroupTheory.UniversalGroup.TowerCoverings +OAI.GroupTheory.UniversalGroup.TreeGeometry +OAI.GroupTheory.UniversalGroup.TuringMachines +OAI.GroupTheory.UniversalGroup.UniversalPresentation +OAI.GroupTheory.UniversalGroup.UniverseTransport diff --git a/tasks/universal-f-infinity/solution/reference.py b/tasks/universal-f-infinity/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/universal-f-infinity/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/universal-f-infinity/solution/solve.sh b/tasks/universal-f-infinity/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..ada11c3510785c5a119345fd74e5746439b164af --- /dev/null +++ b/tasks/universal-f-infinity/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of UniversalFInfinity, i.e. module OAI.GroupTheory.UniversalGroup.Main and the +# 50 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.GroupTheory.UniversalGroup.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of UniversalFInfinity" diff --git a/tasks/universal-f-infinity/task.toml b/tasks/universal-f-infinity/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..609db6db535a064f61f106565011cf5feadd5ffc --- /dev/null +++ b/tasks/universal-f-infinity/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/universal-f-infinity" +version = "1.0.0" +description = "Prove UniversalFInfinity (openai/math family 250: The Boone–Higman conjecture and higher finiteness) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "group-theory"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/UniversalFInfinity.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "UniversalFInfinity" +family = "250" +family_title = "The Boone–Higman conjecture and higher finiteness" +subject = "Group theory" +theorems = ["OAI.UniversalFInfinity.universal_group_of_type_FInfinity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.GroupTheory.UniversalGroup.Main" +reference_modules = 50 +reference_lean_bytes = 884044 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 416 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12495 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/universal-f-infinity/tests/Challenge.lean b/tasks/universal-f-infinity/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..13b690fdf9629da241a85d1b602ddc6250c43dba --- /dev/null +++ b/tasks/universal-f-infinity/tests/Challenge.lean @@ -0,0 +1,25 @@ +import Mathlib + +namespace OAI + +namespace UniversalFInfinity +universe u + +def HasTypeFInfinity (G : Type u) [Group G] : Prop := + ∃ (X : Type u) (_ : TopologicalSpace X) (_ : T2Space X) + (_ : ConnectedSpace X) (cw : Topology.CWComplex (Set.univ : Set X)), + (∀ n : ℕ, Finite (cw.cell n)) ∧ + (∃ x : X, Nonempty (FundamentalGroup X x ≃* G)) ∧ + ∃ (E : Type u) (_ : TopologicalSpace E) (_ : ContractibleSpace E) + (p : E → X), Function.Surjective p ∧ IsCoveringMap p + +theorem universal_group_of_type_FInfinity : + ∃ (H : Type u) (groupH : Group H), + @HasTypeFInfinity H groupH ∧ + ∀ (G : Type u) [Group G] [Group.IsFinitelyPresented G], + ∃ φ : G →* H, Function.Injective φ := by + sorry + +end UniversalFInfinity + +end OAI diff --git a/tasks/universal-f-infinity/tests/grade.py b/tasks/universal-f-infinity/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/universal-f-infinity/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/universal-f-infinity/tests/task.json b/tasks/universal-f-infinity/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..f4a9c43df4538e4a9ca0908d1a45518a4f91cae8 --- /dev/null +++ b/tasks/universal-f-infinity/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "UniversalFInfinity", + "comparator": { + "theorem_names": [ + "OAI.UniversalFInfinity.universal_group_of_type_FInfinity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11595 +} \ No newline at end of file diff --git a/tasks/universal-f-infinity/tests/test.sh b/tasks/universal-f-infinity/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/universal-f-infinity/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/variable-wl/environment/Dockerfile b/tasks/variable-wl/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/variable-wl/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/variable-wl/environment/fetch_mathlib.sh b/tasks/variable-wl/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/variable-wl/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/variable-wl/environment/lake-manifest.json b/tasks/variable-wl/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/variable-wl/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/variable-wl/environment/lakefile.lean b/tasks/variable-wl/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/variable-wl/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/variable-wl/environment/lean_setup.sh b/tasks/variable-wl/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/variable-wl/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/variable-wl/environment/pack_submission.py b/tasks/variable-wl/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/variable-wl/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/variable-wl/instruction.md b/tasks/variable-wl/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..09d99e8f2f91b101ef7d1e2b92451390ac0a7885 --- /dev/null +++ b/tasks/variable-wl/instruction.md @@ -0,0 +1,181 @@ +# openai/math challenge `VariableWL` (family 133) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 133 of the release, *The complexity of Weisfeiler–Leman refinement* +(Theoretical computer science). The family as a whole: Proves unconditional $n^{\Omega(k)}$ deterministic time lower bounds for joint and separate $k$-dimensional Weisfeiler–Leman equivalence, for sufficiently large fixed $k$ in the specified sequential adjacency-matrix models. With dimension as input, joint equivalence is EXPTIME-complete even on subcubic graphs; deciding whether refinement identifies a graph is also EXPTIME-complete. + +The challenge is `VariableWL`, also at `/opt/openai-math/challenges/VariableWL.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace VariableWL + +abbrev Word := List Bool + +inductive Motion where + | left | stay | right + deriving DecidableEq + +def Motion.displacement : Motion → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Machine where + states : ℕ + workSymbols : ℕ + extraTapes : ℕ + transition : Fin (states + 1) → + (Fin (extraTapes + 1) → Fin (workSymbols + 3)) → + Option (Fin (states + 1) × + (Fin (extraTapes + 1) → Fin (workSymbols + 3) × Motion)) + +structure Configuration (M : Machine) where + control : Fin (M.states + 1) + heads : Fin (M.extraTapes + 1) → ℤ + cells : Fin (M.extraTapes + 1) → ℤ → Fin (M.workSymbols + 3) + +def wordCells (a : ℕ) (w : Word) (i : ℤ) : Fin (a + 3) := + if 0 ≤ i then + match w[i.toNat]? with + | none => 0 + | some false => 1 + | some true => 2 + else 0 + +def initial (M : Machine) (w : Word) : Configuration M where + control := 0 + heads := fun _ => 0 + cells := fun j => if j = 0 then wordCells M.workSymbols w else fun _ => 0 + +def scanned {M : Machine} (c : Configuration M) : + Fin (M.extraTapes + 1) → Fin (M.workSymbols + 3) := + fun j => c.cells j (c.heads j) + +def step (M : Machine) (c : Configuration M) : Option (Configuration M) := + (M.transition c.control (scanned c)).map fun data => + { control := data.1 + heads := fun j => c.heads j + (data.2 j).2.displacement + cells := fun j i => if i = c.heads j then (data.2 j).1 else c.cells j i } + +def run (M : Machine) (w : Word) : ℕ → Configuration M + | 0 => initial M w + | n + 1 => (step M (run M w n)).getD (run M w n) + +def OutputsWithin (M : Machine) (w out : Word) (bound : ℕ) : Prop := + ∃ t ≤ bound, step M (run M w t) = none ∧ + (run M w t).cells 0 = wordCells M.workSymbols out + +abbrev Language := Set Word + +def InEXPTIME (L : Language) : Prop := + ∃ M : Machine, ∃ c d : ℕ, ∀ w : Word, + ∃ b : Bool, (b = true ↔ w ∈ L) ∧ + OutputsWithin M w [b] (2 ^ (c * (w.length + 1) ^ d)) + +def PolytimeReduces (L R : Language) : Prop := + ∃ M : Machine, ∃ c d : ℕ, ∀ w : Word, + ∃ out : Word, OutputsWithin M w out (c * (w.length + 1) ^ d) ∧ + (w ∈ L ↔ out ∈ R) + +def EXPTIMEComplete (L : Language) : Prop := + InEXPTIME L ∧ ∀ R : Language, InEXPTIME R → PolytimeReduces R L + +structure Graph where + order : ℕ + graph : SimpleGraph (Fin order) + +abbrev Tuple (G : Graph) (k : ℕ) := Fin k → Fin G.order + +def Color (k : ℕ) : ℕ → Type + | 0 => Fin k → Fin k → Bool × Bool + | s + 1 => Color k s × Multiset (Fin k → Color k s) + +noncomputable def color (G : Graph) (k : ℕ) : (s : ℕ) → Tuple G k → Color k s + | 0, v => by + classical + exact fun i j => (decide (v i = v j), decide (G.graph.Adj (v i) (v j))) + | s + 1, v => (color G k s v, + Finset.univ.val.map (fun z => fun i => color G k s (Function.update v i z))) + +noncomputable def histogram (G : Graph) (k s : ℕ) : Multiset (Color k s) := + Finset.univ.val.map (color G k s) + +def Equivalent (G H : Graph) (k : ℕ) : Prop := + ∀ s : ℕ, histogram G k s = histogram H k s + +def integerCode (n : ℕ) : Word := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +noncomputable def graphCode (G : Graph) : Word := by + classical + exact integerCode G.order ++ + (List.ofFn fun i : Fin G.order => + List.ofFn fun j : Fin G.order => decide (G.graph.Adj i j)).flatten + +noncomputable def pairCode (G H : Graph) (k : ℕ) : Word := + graphCode G ++ graphCode H ++ integerCode k + +def WL : Language := + { w | ∃ G H : Graph, ∃ k : ℕ, w = pairCode G H k ∧ 2 ≤ k ∧ Equivalent G H k } + +noncomputable def Subcubic (G : Graph) : Prop := by + classical + exact ∀ v : Fin G.order, G.graph.degree v ≤ 3 + +def SubWL : Language := + { w | ∃ G H : Graph, ∃ k : ℕ, w = pairCode G H k ∧ 2 ≤ k ∧ + 0 < G.order ∧ G.order = H.order ∧ G.graph.Connected ∧ H.graph.Connected ∧ + Subcubic G ∧ Subcubic H ∧ Equivalent G H k } + +theorem main : EXPTIMEComplete WL ∧ EXPTIMEComplete SubWL := by + sorry + +end VariableWL + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/VariableWL.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.VariableWL.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/variable-wl/solution/closure.txt b/tasks/variable-wl/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..dd88e0581309af0c7fdb1eb4d25d38c553dd064c --- /dev/null +++ b/tasks/variable-wl/solution/closure.txt @@ -0,0 +1,61 @@ +OAI.Combinatorics.VariableWL.Affine +OAI.Combinatorics.VariableWL.AffineCatalog +OAI.Combinatorics.VariableWL.Binary +OAI.Combinatorics.VariableWL.BinaryMachine +OAI.Combinatorics.VariableWL.BlockCatalog +OAI.Combinatorics.VariableWL.BlockCoordinates +OAI.Combinatorics.VariableWL.BlockDescriptor +OAI.Combinatorics.VariableWL.BlockExtensions +OAI.Combinatorics.VariableWL.BlockGame +OAI.Combinatorics.VariableWL.BlockImages +OAI.Combinatorics.VariableWL.BlockListing +OAI.Combinatorics.VariableWL.Blocks +OAI.Combinatorics.VariableWL.BoundedLoop +OAI.Combinatorics.VariableWL.CellularCatalog +OAI.Combinatorics.VariableWL.CellularCircuit +OAI.Combinatorics.VariableWL.CellularListing +OAI.Combinatorics.VariableWL.CertifiedRecipe +OAI.Combinatorics.VariableWL.Circuit +OAI.Combinatorics.VariableWL.CircuitCatalog +OAI.Combinatorics.VariableWL.Completeness +OAI.Combinatorics.VariableWL.Coordinates +OAI.Combinatorics.VariableWL.Decision +OAI.Combinatorics.VariableWL.Descriptor +OAI.Combinatorics.VariableWL.Encoding +OAI.Combinatorics.VariableWL.ExactProjection +OAI.Combinatorics.VariableWL.ExponentialRecipe +OAI.Combinatorics.VariableWL.GeneralGame +OAI.Combinatorics.VariableWL.GeneralReduction +OAI.Combinatorics.VariableWL.MachineCellular +OAI.Combinatorics.VariableWL.MachineReduction +OAI.Combinatorics.VariableWL.MachineSimulation +OAI.Combinatorics.VariableWL.MatrixOutput +OAI.Combinatorics.VariableWL.Model +OAI.Combinatorics.VariableWL.MultiStack +OAI.Combinatorics.VariableWL.NumericProgram +OAI.Combinatorics.VariableWL.NumericRefinement +OAI.Combinatorics.VariableWL.OneHead +OAI.Combinatorics.VariableWL.PolyRecipe +OAI.Combinatorics.VariableWL.PortGame +OAI.Combinatorics.VariableWL.PortGraph +OAI.Combinatorics.VariableWL.PortListing +OAI.Combinatorics.VariableWL.PrefixAlphabet +OAI.Combinatorics.VariableWL.PrefixDescriptor +OAI.Combinatorics.VariableWL.PrefixGame +OAI.Combinatorics.VariableWL.PrefixListing +OAI.Combinatorics.VariableWL.PrefixParts +OAI.Combinatorics.VariableWL.PrefixWiring +OAI.Combinatorics.VariableWL.Procedure +OAI.Combinatorics.VariableWL.ProductCellular +OAI.Combinatorics.VariableWL.ProductImages +OAI.Combinatorics.VariableWL.Program +OAI.Combinatorics.VariableWL.Recipe +OAI.Combinatorics.VariableWL.Refinement +OAI.Combinatorics.VariableWL.RefinementTable +OAI.Combinatorics.VariableWL.Stack +OAI.Combinatorics.VariableWL.StackSimulation +OAI.Combinatorics.VariableWL.SubcubicGame +OAI.Combinatorics.VariableWL.Subdivision +OAI.Combinatorics.VariableWL.TypedGame +OAI.Combinatorics.VariableWL.UnaryPower +OAI.Combinatorics.VariableWL.Wrapping diff --git a/tasks/variable-wl/solution/reference.py b/tasks/variable-wl/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/variable-wl/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/variable-wl/solution/solve.sh b/tasks/variable-wl/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..c3f8e0c65ce0ce01326dbcde10ba6e8e04bc2d6e --- /dev/null +++ b/tasks/variable-wl/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of VariableWL, i.e. module OAI.Combinatorics.VariableWL.Completeness and the +# 61 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Combinatorics.VariableWL.Completeness /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of VariableWL" diff --git a/tasks/variable-wl/task.toml b/tasks/variable-wl/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2ef3a15661e53384a10ed2c0afd692b3eb3b30bb --- /dev/null +++ b/tasks/variable-wl/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/variable-wl" +version = "1.0.0" +description = "Prove VariableWL (openai/math family 133: The complexity of Weisfeiler–Leman refinement) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/VariableWL.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "VariableWL" +family = "133" +family_title = "The complexity of Weisfeiler–Leman refinement" +subject = "Theoretical computer science" +theorems = ["OAI.VariableWL.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Combinatorics.VariableWL.Completeness" +reference_modules = 61 +reference_lean_bytes = 1182668 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 429 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12764 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/variable-wl/tests/Challenge.lean b/tasks/variable-wl/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..92252e2a6d9961ddc619833f9ab0be9f2d57d696 --- /dev/null +++ b/tasks/variable-wl/tests/Challenge.lean @@ -0,0 +1,130 @@ +import Mathlib + +namespace OAI + +namespace VariableWL + +abbrev Word := List Bool + +inductive Motion where + | left | stay | right + deriving DecidableEq + +def Motion.displacement : Motion → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Machine where + states : ℕ + workSymbols : ℕ + extraTapes : ℕ + transition : Fin (states + 1) → + (Fin (extraTapes + 1) → Fin (workSymbols + 3)) → + Option (Fin (states + 1) × + (Fin (extraTapes + 1) → Fin (workSymbols + 3) × Motion)) + +structure Configuration (M : Machine) where + control : Fin (M.states + 1) + heads : Fin (M.extraTapes + 1) → ℤ + cells : Fin (M.extraTapes + 1) → ℤ → Fin (M.workSymbols + 3) + +def wordCells (a : ℕ) (w : Word) (i : ℤ) : Fin (a + 3) := + if 0 ≤ i then + match w[i.toNat]? with + | none => 0 + | some false => 1 + | some true => 2 + else 0 + +def initial (M : Machine) (w : Word) : Configuration M where + control := 0 + heads := fun _ => 0 + cells := fun j => if j = 0 then wordCells M.workSymbols w else fun _ => 0 + +def scanned {M : Machine} (c : Configuration M) : + Fin (M.extraTapes + 1) → Fin (M.workSymbols + 3) := + fun j => c.cells j (c.heads j) + +def step (M : Machine) (c : Configuration M) : Option (Configuration M) := + (M.transition c.control (scanned c)).map fun data => + { control := data.1 + heads := fun j => c.heads j + (data.2 j).2.displacement + cells := fun j i => if i = c.heads j then (data.2 j).1 else c.cells j i } + +def run (M : Machine) (w : Word) : ℕ → Configuration M + | 0 => initial M w + | n + 1 => (step M (run M w n)).getD (run M w n) + +def OutputsWithin (M : Machine) (w out : Word) (bound : ℕ) : Prop := + ∃ t ≤ bound, step M (run M w t) = none ∧ + (run M w t).cells 0 = wordCells M.workSymbols out + +abbrev Language := Set Word + +def InEXPTIME (L : Language) : Prop := + ∃ M : Machine, ∃ c d : ℕ, ∀ w : Word, + ∃ b : Bool, (b = true ↔ w ∈ L) ∧ + OutputsWithin M w [b] (2 ^ (c * (w.length + 1) ^ d)) + +def PolytimeReduces (L R : Language) : Prop := + ∃ M : Machine, ∃ c d : ℕ, ∀ w : Word, + ∃ out : Word, OutputsWithin M w out (c * (w.length + 1) ^ d) ∧ + (w ∈ L ↔ out ∈ R) + +def EXPTIMEComplete (L : Language) : Prop := + InEXPTIME L ∧ ∀ R : Language, InEXPTIME R → PolytimeReduces R L + +structure Graph where + order : ℕ + graph : SimpleGraph (Fin order) + +abbrev Tuple (G : Graph) (k : ℕ) := Fin k → Fin G.order + +def Color (k : ℕ) : ℕ → Type + | 0 => Fin k → Fin k → Bool × Bool + | s + 1 => Color k s × Multiset (Fin k → Color k s) + +noncomputable def color (G : Graph) (k : ℕ) : (s : ℕ) → Tuple G k → Color k s + | 0, v => by + classical + exact fun i j => (decide (v i = v j), decide (G.graph.Adj (v i) (v j))) + | s + 1, v => (color G k s v, + Finset.univ.val.map (fun z => fun i => color G k s (Function.update v i z))) + +noncomputable def histogram (G : Graph) (k s : ℕ) : Multiset (Color k s) := + Finset.univ.val.map (color G k s) + +def Equivalent (G H : Graph) (k : ℕ) : Prop := + ∀ s : ℕ, histogram G k s = histogram H k s + +def integerCode (n : ℕ) : Word := + List.replicate (Nat.bits n).length true ++ [false] ++ Nat.bits n + +noncomputable def graphCode (G : Graph) : Word := by + classical + exact integerCode G.order ++ + (List.ofFn fun i : Fin G.order => + List.ofFn fun j : Fin G.order => decide (G.graph.Adj i j)).flatten + +noncomputable def pairCode (G H : Graph) (k : ℕ) : Word := + graphCode G ++ graphCode H ++ integerCode k + +def WL : Language := + { w | ∃ G H : Graph, ∃ k : ℕ, w = pairCode G H k ∧ 2 ≤ k ∧ Equivalent G H k } + +noncomputable def Subcubic (G : Graph) : Prop := by + classical + exact ∀ v : Fin G.order, G.graph.degree v ≤ 3 + +def SubWL : Language := + { w | ∃ G H : Graph, ∃ k : ℕ, w = pairCode G H k ∧ 2 ≤ k ∧ + 0 < G.order ∧ G.order = H.order ∧ G.graph.Connected ∧ H.graph.Connected ∧ + Subcubic G ∧ Subcubic H ∧ Equivalent G H k } + +theorem main : EXPTIMEComplete WL ∧ EXPTIMEComplete SubWL := by + sorry + +end VariableWL + +end OAI diff --git a/tasks/variable-wl/tests/grade.py b/tasks/variable-wl/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/variable-wl/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/variable-wl/tests/task.json b/tasks/variable-wl/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..6d2145056f428f4967615688a1d1a8f54bac0b2c --- /dev/null +++ b/tasks/variable-wl/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "VariableWL", + "comparator": { + "theorem_names": [ + "OAI.VariableWL.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11864 +} \ No newline at end of file diff --git a/tasks/variable-wl/tests/test.sh b/tasks/variable-wl/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/variable-wl/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/velocity-hemisphere/environment/Dockerfile b/tasks/velocity-hemisphere/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/velocity-hemisphere/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/velocity-hemisphere/environment/fetch_mathlib.sh b/tasks/velocity-hemisphere/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/velocity-hemisphere/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/velocity-hemisphere/environment/lake-manifest.json b/tasks/velocity-hemisphere/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/velocity-hemisphere/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/velocity-hemisphere/environment/lakefile.lean b/tasks/velocity-hemisphere/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/velocity-hemisphere/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/velocity-hemisphere/environment/lean_setup.sh b/tasks/velocity-hemisphere/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/velocity-hemisphere/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/velocity-hemisphere/environment/pack_submission.py b/tasks/velocity-hemisphere/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/velocity-hemisphere/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/velocity-hemisphere/instruction.md b/tasks/velocity-hemisphere/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..94015b233854eaa0cfa82c3a72ba5c080cbf5acf --- /dev/null +++ b/tasks/velocity-hemisphere/instruction.md @@ -0,0 +1,153 @@ +# openai/math challenge `VelocityHemisphere` (family 220) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 220 of the release, *Directional zero–one laws and ballisticity in random environments* +(Probability and statistical mechanics). The family as a whole: On $\mathbb Z^d$, $d\ge3$, directional escape has probability zero or one for iid strictly elliptic nearest-neighbor environments, and for stationary ergodic finite-range-dependent environments under uniform ellipticity. In iid uniformly elliptic environments with $d\ge2$, almost-sure directional transience implies a deterministic limiting velocity with positive projection in that direction, resolving the ballisticity conjecture. + +The challenge is `VelocityHemisphere`, also at `/opt/openai-math/challenges/VelocityHemisphere.lean`: + +```lean +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped ENNReal NNReal BigOperators Topology + +namespace DirectionalTransience + +abbrev Lattice (d : ℕ) := Fin d → ℤ +abbrev Direction (d : ℕ) := Fin d × Bool +abbrev Vector (d : ℕ) := Fin d → ℝ +abbrev Row (d : ℕ) := {p : Direction d → ℝ≥0 // ∑ e, p e = 1} +abbrev Environment (d : ℕ) := Lattice d → Row d +abbrev State (d : ℕ) := Environment d × Lattice d +abbrev Path (d : ℕ) := ℕ → Lattice d + +def step {d : ℕ} (e : Direction d) : Lattice d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +noncomputable def environmentLaw {d : ℕ} (ν : Measure (Row d)) : + Measure (Environment d) := Measure.infinitePi (fun _ => ν) + +def UniformElliptic {d : ℕ} (ν : Measure (Row d)) : Prop := + ∃ κ : ℝ≥0, 0 < κ ∧ ∀ᵐ p ∂ν, ∀ e, κ ≤ p.1 e + +lemma measurable_current_row {d : ℕ} : + Measurable (fun z : State d => z.1 z.2) := by + apply measurable_from_prod_countable_left + intro x + exact measurable_pi_apply x + +noncomputable def transition {d : ℕ} : Kernel (State d) (State d) where + toFun z := ∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e) + measurable' := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.finsetSum_apply, Measure.smul_apply, smul_eq_mul] + apply Finset.measurable_fun_sum + intro e _ + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp measurable_current_row)).coe_nnreal_ennreal + · exact (Measure.measurable_coe hs).comp + (Measure.measurable_dirac.comp (measurable_fst.prodMk + (measurable_snd.add_const (step e)))) + +instance transition_markov {d : ℕ} : IsMarkovKernel (transition (d := d)) where + isProbabilityMeasure z := by + constructor + change (∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, Measure.dirac_apply_of_mem + (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofNNReal_finsetSum, (z.1 z.2).2] + rfl + +noncomputable def historyTransition {d : ℕ} (n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) where + toFun z := transition (z ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + measurable' := transition.measurable.comp (measurable_pi_apply _) + +instance historyTransition_markov {d : ℕ} (n : ℕ) : + IsMarkovKernel (historyTransition (d := d) n) where + isProbabilityMeasure _ := transition_markov.isProbabilityMeasure _ + +noncomputable def initialLaw {d : ℕ} (ν : Measure (Row d)) : Measure (State d) := + (environmentLaw ν).map (fun ω => (ω, (0 : Lattice d))) + +noncomputable def annealedLaw {d : ℕ} (ν : Measure (Row d)) : Measure (Path d) := + (@Kernel.trajMeasure (fun _ => State d) _ (initialLaw ν) (historyTransition (d := d)) _).map + (fun z n => (z n).2) + +def dot {d : ℕ} (v ℓ : Vector d) : ℝ := ∑ i, v i * ℓ i + +def realPosition {d : ℕ} (x : Lattice d) : Vector d := fun i => (x i : ℝ) + +def TransientPaths {d : ℕ} (ℓ : Vector d) : Set (Path d) := + {X | Tendsto (fun n => dot (realPosition (X n)) ℓ) atTop atTop} + +def VelocityPaths {d : ℕ} (v : Vector d) : Set (Path d) := + {X | Tendsto (fun n : ℕ => fun i => (X n i:ℝ)/(n:ℝ)) atTop (𝓝 v)} + +theorem positive_probability_transience_velocity_hemisphere + {d : ℕ} (hd : 3 ≤ d) (ν : Measure (Row d)) [IsProbabilityMeasure ν] + (hue : UniformElliptic ν) (ℓ : Vector d) (hℓ : ℓ ≠ 0) + (hpos : 0 < annealedLaw ν (TransientPaths ℓ)) : + ∃ v : Vector d, + v ≠ 0 ∧ 0 < dot v ℓ ∧ annealedLaw ν (VelocityPaths v) = 1 ∧ + (∀ w : Vector d, annealedLaw ν (VelocityPaths w) = 1 → w = v) ∧ + {u : Vector d | dot u u = 1 ∧ annealedLaw ν (TransientPaths u) = 1} = + {u : Vector d | dot u u = 1 ∧ 0 < annealedLaw ν (TransientPaths u)} ∧ + {u : Vector d | dot u u = 1 ∧ 0 < annealedLaw ν (TransientPaths u)} = + {u : Vector d | dot u u = 1 ∧ 0 < dot v u} ∧ + (∀ u : Vector d, dot u u = 1 → dot v u ≤ 0 → + annealedLaw ν (TransientPaths u) = 0) := by + sorry + +end DirectionalTransience + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/VelocityHemisphere.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.DirectionalTransience.positive_probability_transience_velocity_hemisphere` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/velocity-hemisphere/solution/closure.txt b/tasks/velocity-hemisphere/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..52f51032ac43747fe7d75bbb0267b3718ec1bc16 --- /dev/null +++ b/tasks/velocity-hemisphere/solution/closure.txt @@ -0,0 +1,585 @@ +OAI.Probability.Ballisticity.Coupling.CellSeedParameters +OAI.Probability.Ballisticity.Coupling.CountableFreshBuffer +OAI.Probability.Ballisticity.Coupling.FreshBudgetEvent +OAI.Probability.Ballisticity.Coupling.FreshBuffer +OAI.Probability.Ballisticity.Coupling.FreshBufferAE +OAI.Probability.Ballisticity.Coupling.FreshClipping +OAI.Probability.Ballisticity.Coupling.FreshCrossing +OAI.Probability.Ballisticity.Coupling.FreshMoment +OAI.Probability.Ballisticity.Coupling.FreshPolicyIndependence +OAI.Probability.Ballisticity.Coupling.FreshStages +OAI.Probability.Ballisticity.Coupling.FreshThreat +OAI.Probability.Ballisticity.Coupling.FreshWeightedTest +OAI.Probability.Ballisticity.Coupling.GaussianQuenchedMass +OAI.Probability.Ballisticity.Coupling.GaussianQuenchedTube +OAI.Probability.Ballisticity.Coupling.QuenchedConcentration +OAI.Probability.Ballisticity.Coupling.QuenchedConditionalProbability +OAI.Probability.Ballisticity.Coupling.QuenchedConditionedTubeTransfer +OAI.Probability.Ballisticity.Coupling.QuenchedGaussian +OAI.Probability.Ballisticity.Coupling.QuenchedMoments +OAI.Probability.Ballisticity.Coupling.QuenchedPrefixDeterminedFuture +OAI.Probability.Ballisticity.Coupling.QuenchedSuccessComparison +OAI.Probability.Ballisticity.Coupling.SeedIteration +OAI.Probability.Ballisticity.Coupling.SeedMedian +OAI.Probability.Ballisticity.Coupling.SeedOptions +OAI.Probability.Ballisticity.Coupling.SeedOrder +OAI.Probability.Ballisticity.Coupling.SeedProfile +OAI.Probability.Ballisticity.Coupling.SeedRadius +OAI.Probability.Ballisticity.Coupling.SeedStateOrder +OAI.Probability.Ballisticity.Coupling.SeedUniform +OAI.Probability.Ballisticity.Coupling.StageSeedProfile +OAI.Probability.Ballisticity.Coupling.StoppedFreshField +OAI.Probability.Ballisticity.Coupling.WeakLimitBoundedFreshMap +OAI.Probability.Ballisticity.Coupling.WeightedAnnealed +OAI.Probability.Ballisticity.Crossings.BadCrossingLaw +OAI.Probability.Ballisticity.Crossings.BoundaryCrossBound +OAI.Probability.Ballisticity.Crossings.BoundaryFirstHits +OAI.Probability.Ballisticity.Crossings.CanonicalHeightCutoff +OAI.Probability.Ballisticity.Crossings.CommonCutCounting +OAI.Probability.Ballisticity.Crossings.CommonCutObserver +OAI.Probability.Ballisticity.Crossings.ContinuousCrossPast +OAI.Probability.Ballisticity.Crossings.CoordinateHitExact +OAI.Probability.Ballisticity.Crossings.CrossTranslation +OAI.Probability.Ballisticity.Crossings.CrossingEstimate +OAI.Probability.Ballisticity.Crossings.CrossingGap +OAI.Probability.Ballisticity.Crossings.CrossingGapDecay +OAI.Probability.Ballisticity.Crossings.CrossingSurplus +OAI.Probability.Ballisticity.Crossings.CutoffTimeAverages +OAI.Probability.Ballisticity.Crossings.DeterministicCrossBound +OAI.Probability.Ballisticity.Crossings.FiniteBoxExit +OAI.Probability.Ballisticity.Crossings.FiniteHitOscillation +OAI.Probability.Ballisticity.Crossings.FinitePastCrossBound +OAI.Probability.Ballisticity.Crossings.FirstHitPairGap +OAI.Probability.Ballisticity.Crossings.FirstHitUpward +OAI.Probability.Ballisticity.Crossings.FirstLayerHitConcat +OAI.Probability.Ballisticity.Crossings.FirstLayerHitRecordIndexTime +OAI.Probability.Ballisticity.Crossings.FirstLayerHitRecordPrefix +OAI.Probability.Ballisticity.Crossings.FixedLowerCutoffEscape +OAI.Probability.Ballisticity.Crossings.GaussianBadCutoff +OAI.Probability.Ballisticity.Crossings.Hit +OAI.Probability.Ballisticity.Crossings.HitWord +OAI.Probability.Ballisticity.Crossings.HittingIteration +OAI.Probability.Ballisticity.Crossings.LowerObservedCut +OAI.Probability.Ballisticity.Crossings.NearCrossEstimates +OAI.Probability.Ballisticity.Crossings.OccupationCutoffs +OAI.Probability.Ballisticity.Crossings.OffDiagonalCenteredCross +OAI.Probability.Ballisticity.Crossings.PastCutoffs +OAI.Probability.Ballisticity.Crossings.PhysicalExit +OAI.Probability.Ballisticity.Crossings.PhysicalFirstHitGapHitWords +OAI.Probability.Ballisticity.Crossings.SharedInteriorCross +OAI.Probability.Ballisticity.Crossings.StripExitBound +OAI.Probability.Ballisticity.Crossings.TailCuts +OAI.Probability.Ballisticity.Crossings.UniformLowerCutoff +OAI.Probability.Ballisticity.Entropy.AnchorEntropy +OAI.Probability.Ballisticity.Entropy.BadWindowEntropy +OAI.Probability.Ballisticity.Entropy.BufferCostBounds +OAI.Probability.Ballisticity.Entropy.CanonicalLogExcess +OAI.Probability.Ballisticity.Entropy.DominatedEntropy +OAI.Probability.Ballisticity.Entropy.EntropyContinuousTests +OAI.Probability.Ballisticity.Entropy.EntropyDecorrelation +OAI.Probability.Ballisticity.Entropy.EntropyDensity +OAI.Probability.Ballisticity.Entropy.EntropyEvent +OAI.Probability.Ballisticity.Entropy.EntropyPlus +OAI.Probability.Ballisticity.Entropy.EntropyVariational +OAI.Probability.Ballisticity.Entropy.FiniteLogStability +OAI.Probability.Ballisticity.Entropy.OccupationEntropy +OAI.Probability.Ballisticity.Entropy.OccupationEntropy2 +OAI.Probability.Ballisticity.Entropy.OutwardOrder +OAI.Probability.Ballisticity.Entropy.StoppedEntropySum +OAI.Probability.Ballisticity.Entropy.StoppedWindowEntropy +OAI.Probability.Ballisticity.Entropy.WindowEntropy +OAI.Probability.Ballisticity.Entropy.WindowProjectionEntropy +OAI.Probability.Ballisticity.Estimates.AdaptiveFailureWeights +OAI.Probability.Ballisticity.Estimates.AeMaximalSquare +OAI.Probability.Ballisticity.Estimates.AlignedRecordPrefix +OAI.Probability.Ballisticity.Estimates.AllIndexMarks +OAI.Probability.Ballisticity.Estimates.AllLayerOccupation +OAI.Probability.Ballisticity.Estimates.AllOffsetConsistency +OAI.Probability.Ballisticity.Estimates.AnchorFrameReference +OAI.Probability.Ballisticity.Estimates.AnchorMoments +OAI.Probability.Ballisticity.Estimates.BadDropMoment +OAI.Probability.Ballisticity.Estimates.BadOccupationLimit +OAI.Probability.Ballisticity.Estimates.BadStageMoment +OAI.Probability.Ballisticity.Estimates.BindIntegral +OAI.Probability.Ballisticity.Estimates.BoundaryDecorrelation +OAI.Probability.Ballisticity.Estimates.BoundaryGapReplacement +OAI.Probability.Ballisticity.Estimates.BoundarySuffixIdentity +OAI.Probability.Ballisticity.Estimates.BoundedAnchorAverage +OAI.Probability.Ballisticity.Estimates.BudgetAdapted +OAI.Probability.Ballisticity.Estimates.BudgetAlgebra +OAI.Probability.Ballisticity.Estimates.BudgetClipping +OAI.Probability.Ballisticity.Estimates.BudgetEndpoint +OAI.Probability.Ballisticity.Estimates.BudgetLoss +OAI.Probability.Ballisticity.Estimates.BudgetMeasurable +OAI.Probability.Ballisticity.Estimates.BudgetNormalize +OAI.Probability.Ballisticity.Estimates.BudgetThreat +OAI.Probability.Ballisticity.Estimates.Buffer +OAI.Probability.Ballisticity.Estimates.BufferChanceData +OAI.Probability.Ballisticity.Estimates.BufferChildNode +OAI.Probability.Ballisticity.Estimates.BufferExcess +OAI.Probability.Ballisticity.Estimates.BufferFirstFailure +OAI.Probability.Ballisticity.Estimates.BufferRestorationScript +OAI.Probability.Ballisticity.Estimates.BufferRootRetention +OAI.Probability.Ballisticity.Estimates.BufferStageCount +OAI.Probability.Ballisticity.Estimates.BufferStagePacket +OAI.Probability.Ballisticity.Estimates.BufferStageSuccess +OAI.Probability.Ballisticity.Estimates.BufferTree +OAI.Probability.Ballisticity.Estimates.CappedExp +OAI.Probability.Ballisticity.Estimates.CappedLoss +OAI.Probability.Ballisticity.Estimates.CappedMomentTransfer +OAI.Probability.Ballisticity.Estimates.Cell +OAI.Probability.Ballisticity.Estimates.CellAttempt +OAI.Probability.Ballisticity.Estimates.CellBadEvent +OAI.Probability.Ballisticity.Estimates.CellCertificates +OAI.Probability.Ballisticity.Estimates.CellExhaustion +OAI.Probability.Ballisticity.Estimates.CellFailure +OAI.Probability.Ballisticity.Estimates.CellRadiusComparison +OAI.Probability.Ballisticity.Estimates.CellSchedule +OAI.Probability.Ballisticity.Estimates.CharacteristicProductLaw +OAI.Probability.Ballisticity.Estimates.CharacteristicTaylor +OAI.Probability.Ballisticity.Estimates.ClassFinset +OAI.Probability.Ballisticity.Estimates.ClassMoment +OAI.Probability.Ballisticity.Estimates.ClassSelection +OAI.Probability.Ballisticity.Estimates.ClippedAbsThreeHalves +OAI.Probability.Ballisticity.Estimates.ClippedInverse +OAI.Probability.Ballisticity.Estimates.ClippedThreeHalves +OAI.Probability.Ballisticity.Estimates.ClippingTime +OAI.Probability.Ballisticity.Estimates.ClosedEmbeddingWeak +OAI.Probability.Ballisticity.Estimates.CommonBoundaryRestart +OAI.Probability.Ballisticity.Estimates.CommonLayer +OAI.Probability.Ballisticity.Estimates.CommonOccupationBound +OAI.Probability.Ballisticity.Estimates.CommonOffset +OAI.Probability.Ballisticity.Estimates.CommonTrueRecord +OAI.Probability.Ballisticity.Estimates.CommonWidthProcess +OAI.Probability.Ballisticity.Estimates.CommonWordIncrement +OAI.Probability.Ballisticity.Estimates.CommonWordWidth +OAI.Probability.Ballisticity.Estimates.ConditionalLawTests +OAI.Probability.Ballisticity.Estimates.ConfinementTemplates +OAI.Probability.Ballisticity.Estimates.ConvolutionCentersClose +OAI.Probability.Ballisticity.Estimates.CountableProdBind +OAI.Probability.Ballisticity.Estimates.CurveCenter +OAI.Probability.Ballisticity.Estimates.CurveEndpointLaw +OAI.Probability.Ballisticity.Estimates.CurvePolicy +OAI.Probability.Ballisticity.Estimates.CurvePolicyAlignment +OAI.Probability.Ballisticity.Estimates.CurvePolicyAverageMoment +OAI.Probability.Ballisticity.Estimates.CurvePolicyLateral +OAI.Probability.Ballisticity.Estimates.CurvePolicyMaximal +OAI.Probability.Ballisticity.Estimates.CurvePolicyPMF +OAI.Probability.Ballisticity.Estimates.CurvePrefix +OAI.Probability.Ballisticity.Estimates.CurveShortBlock +OAI.Probability.Ballisticity.Estimates.CurveWordDisjoint +OAI.Probability.Ballisticity.Estimates.DensityTransfer +OAI.Probability.Ballisticity.Estimates.DescendingTrials +OAI.Probability.Ballisticity.Estimates.DifferentiableExp +OAI.Probability.Ballisticity.Estimates.DirectBridge +OAI.Probability.Ballisticity.Estimates.DominatedTranslationBounded +OAI.Probability.Ballisticity.Estimates.Dust +OAI.Probability.Ballisticity.Estimates.EndpointPrefix +OAI.Probability.Ballisticity.Estimates.EndpointPrefixConditionedReal +OAI.Probability.Ballisticity.Estimates.EventRate +OAI.Probability.Ballisticity.Estimates.FavorablePairFraction +OAI.Probability.Ballisticity.Estimates.FiniteClasses +OAI.Probability.Ballisticity.Estimates.FinitePastDecorrelation +OAI.Probability.Ballisticity.Estimates.FinitePolicyFailure +OAI.Probability.Ballisticity.Estimates.FinitePolicyPMF +OAI.Probability.Ballisticity.Estimates.FiniteStage +OAI.Probability.Ballisticity.Estimates.FirstBelow +OAI.Probability.Ballisticity.Estimates.FirstHighRecord +OAI.Probability.Ballisticity.Estimates.FirstWordEvent +OAI.Probability.Ballisticity.Estimates.FixedPairSuffix +OAI.Probability.Ballisticity.Estimates.FluctuationScaleUpperMultiple +OAI.Probability.Ballisticity.Estimates.FullCapTransfer +OAI.Probability.Ballisticity.Estimates.GaussianAbsTail +OAI.Probability.Ballisticity.Estimates.GaussianPiReal +OAI.Probability.Ballisticity.Estimates.GlobalContinuation +OAI.Probability.Ballisticity.Estimates.GlobalProfile +OAI.Probability.Ballisticity.Estimates.GlobalTuple +OAI.Probability.Ballisticity.Estimates.GridLinear +OAI.Probability.Ballisticity.Estimates.GridOccupation +OAI.Probability.Ballisticity.Estimates.GridOscillation +OAI.Probability.Ballisticity.Estimates.GridTrials +OAI.Probability.Ballisticity.Estimates.HighRecordCount +OAI.Probability.Ballisticity.Estimates.IidDifferenceCenteredHalf +OAI.Probability.Ballisticity.Estimates.IidListProcess +OAI.Probability.Ballisticity.Estimates.IndependentDyadic +OAI.Probability.Ballisticity.Estimates.IndependentPairLaw +OAI.Probability.Ballisticity.Estimates.IndependentRandomTestBound +OAI.Probability.Ballisticity.Estimates.IndependentRecenterMap +OAI.Probability.Ballisticity.Estimates.InputMarginal +OAI.Probability.Ballisticity.Estimates.IntegerMedian +OAI.Probability.Ballisticity.Estimates.InteriorPairMeasureExt +OAI.Probability.Ballisticity.Estimates.JointMeshPhase +OAI.Probability.Ballisticity.Estimates.JointPastMoments +OAI.Probability.Ballisticity.Estimates.JointPastRestart +OAI.Probability.Ballisticity.Estimates.LateMoment +OAI.Probability.Ballisticity.Estimates.LayerPairTruthEventMono +OAI.Probability.Ballisticity.Estimates.ListPrefixSum +OAI.Probability.Ballisticity.Estimates.LocalRadiusOrder +OAI.Probability.Ballisticity.Estimates.LocalStoppedSplice +OAI.Probability.Ballisticity.Estimates.LowerClip +OAI.Probability.Ballisticity.Estimates.MarkedObservables +OAI.Probability.Ballisticity.Estimates.MartingaleExponentialSubmartingale +OAI.Probability.Ballisticity.Estimates.MaxTailDecomposition +OAI.Probability.Ballisticity.Estimates.MeasurableCountableSample +OAI.Probability.Ballisticity.Estimates.MeasureAdd +OAI.Probability.Ballisticity.Estimates.MedianAeConst +OAI.Probability.Ballisticity.Estimates.MixtureSmallMassProbability +OAI.Probability.Ballisticity.Estimates.MomentRescaling +OAI.Probability.Ballisticity.Estimates.NaturalTailIntegrable +OAI.Probability.Ballisticity.Estimates.NoDropApproxError +OAI.Probability.Ballisticity.Estimates.NonCollapsedSums +OAI.Probability.Ballisticity.Estimates.NormalLinearPast +OAI.Probability.Ballisticity.Estimates.NormalizedRestrictionContact +OAI.Probability.Ballisticity.Estimates.NormalizedSharedRestrict +OAI.Probability.Ballisticity.Estimates.ObservedBudget +OAI.Probability.Ballisticity.Estimates.ObservedCharges +OAI.Probability.Ballisticity.Estimates.ObservedDrift +OAI.Probability.Ballisticity.Estimates.ObservedPotential +OAI.Probability.Ballisticity.Estimates.ObserverAlmostSure +OAI.Probability.Ballisticity.Estimates.OccupationAlgebra +OAI.Probability.Ballisticity.Estimates.OccupationLimit +OAI.Probability.Ballisticity.Estimates.OccupationParameters +OAI.Probability.Ballisticity.Estimates.OccupationSampling +OAI.Probability.Ballisticity.Estimates.OperationalLengthMarks +OAI.Probability.Ballisticity.Estimates.OperationalMarkBounds +OAI.Probability.Ballisticity.Estimates.OrderedTimes +OAI.Probability.Ballisticity.Estimates.OutwardCanonical +OAI.Probability.Ballisticity.Estimates.OutwardCapL1 +OAI.Probability.Ballisticity.Estimates.OutwardCapLocality +OAI.Probability.Ballisticity.Estimates.OwnMarginalOccupation +OAI.Probability.Ballisticity.Estimates.PairPrefix +OAI.Probability.Ballisticity.Estimates.PairUpwardRetention +OAI.Probability.Ballisticity.Estimates.PairWeakUniqueness +OAI.Probability.Ballisticity.Estimates.PastPhaseExtension +OAI.Probability.Ballisticity.Estimates.PolicyGoodMass +OAI.Probability.Ballisticity.Estimates.PrefixVariation +OAI.Probability.Ballisticity.Estimates.PrefixVariationNonneg +OAI.Probability.Ballisticity.Estimates.ProbabilityLowerTransfer +OAI.Probability.Ballisticity.Estimates.ProductNormalJointPast +OAI.Probability.Ballisticity.Estimates.ProductTruncationError +OAI.Probability.Ballisticity.Estimates.ProfileMeasureUpdate +OAI.Probability.Ballisticity.Estimates.ProperProfile +OAI.Probability.Ballisticity.Estimates.ProtectionFirstFailure +OAI.Probability.Ballisticity.Estimates.ProtectionLoss +OAI.Probability.Ballisticity.Estimates.RadixBudget +OAI.Probability.Ballisticity.Estimates.RapidDecay +OAI.Probability.Ballisticity.Estimates.RapidDecaySubsequence +OAI.Probability.Ballisticity.Estimates.RapidDecayTail +OAI.Probability.Ballisticity.Estimates.RawConditionedWeight +OAI.Probability.Ballisticity.Estimates.RawDropBounds +OAI.Probability.Ballisticity.Estimates.RawPair +OAI.Probability.Ballisticity.Estimates.RawPairEndpoint +OAI.Probability.Ballisticity.Estimates.RawPairLocality +OAI.Probability.Ballisticity.Estimates.RawPairMassComposition +OAI.Probability.Ballisticity.Estimates.RawPairRetention +OAI.Probability.Ballisticity.Estimates.RealJointPastRestart +OAI.Probability.Ballisticity.Estimates.RecordIndexTime +OAI.Probability.Ballisticity.Estimates.RecordMedianSlope +OAI.Probability.Ballisticity.Estimates.RecordOrPrefixAdd +OAI.Probability.Ballisticity.Estimates.RecordPairFuture +OAI.Probability.Ballisticity.Estimates.RecordPrefixControl +OAI.Probability.Ballisticity.Estimates.ReferenceContinuity +OAI.Probability.Ballisticity.Estimates.ReferenceFeller +OAI.Probability.Ballisticity.Estimates.RelativeBudget +OAI.Probability.Ballisticity.Estimates.RestartLyapunov +OAI.Probability.Ballisticity.Estimates.RestartSupportedBound +OAI.Probability.Ballisticity.Estimates.RetainedComposition +OAI.Probability.Ballisticity.Estimates.Sampling +OAI.Probability.Ballisticity.Estimates.SamplingLaw +OAI.Probability.Ballisticity.Estimates.SamplingLimit +OAI.Probability.Ballisticity.Estimates.SamplingRearrangement +OAI.Probability.Ballisticity.Estimates.ScaledMaxMoment +OAI.Probability.Ballisticity.Estimates.ScaledMaxTail +OAI.Probability.Ballisticity.Estimates.ScheduledCellSuccess +OAI.Probability.Ballisticity.Estimates.SecondMomentConcentration +OAI.Probability.Ballisticity.Estimates.SelectedBoundaryRestart +OAI.Probability.Ballisticity.Estimates.SelectedEndpointMoment +OAI.Probability.Ballisticity.Estimates.SharedConditionedContactBound +OAI.Probability.Ballisticity.Estimates.SharedConditionedPairLawFst +OAI.Probability.Ballisticity.Estimates.SharedEndpointOverlapRight +OAI.Probability.Ballisticity.Estimates.SharedEndpointTests +OAI.Probability.Ballisticity.Estimates.SharedLimitNormalPast +OAI.Probability.Ballisticity.Estimates.SharedLimitOccupation +OAI.Probability.Ballisticity.Estimates.SharedLimitPastIdentity +OAI.Probability.Ballisticity.Estimates.SharedShrinking +OAI.Probability.Ballisticity.Estimates.SharedWordCylinderLower +OAI.Probability.Ballisticity.Estimates.ShiftedCurveConcatenation +OAI.Probability.Ballisticity.Estimates.SignedPrefixComparison +OAI.Probability.Ballisticity.Estimates.SingleAdjacentRadiusBound +OAI.Probability.Ballisticity.Estimates.SingleCoverWord +OAI.Probability.Ballisticity.Estimates.SingleThreat +OAI.Probability.Ballisticity.Estimates.SmallScaleGaussianMass +OAI.Probability.Ballisticity.Estimates.SmallScaleTailMoment +OAI.Probability.Ballisticity.Estimates.SmallTimeExponentialError +OAI.Probability.Ballisticity.Estimates.StageClassification +OAI.Probability.Ballisticity.Estimates.StageExponentialScales +OAI.Probability.Ballisticity.Estimates.StageInjection +OAI.Probability.Ballisticity.Estimates.StageParameters +OAI.Probability.Ballisticity.Estimates.StageRetention +OAI.Probability.Ballisticity.Estimates.StageStopping +OAI.Probability.Ballisticity.Estimates.StayUntil +OAI.Probability.Ballisticity.Estimates.StoppedSplice +OAI.Probability.Ballisticity.Estimates.StrictRecord +OAI.Probability.Ballisticity.Estimates.SuccessfulAverage +OAI.Probability.Ballisticity.Estimates.SuccessfulAverageBind +OAI.Probability.Ballisticity.Estimates.SuccessfulScaledTail +OAI.Probability.Ballisticity.Estimates.SuccessfulWords +OAI.Probability.Ballisticity.Estimates.SurvivalConditional +OAI.Probability.Ballisticity.Estimates.SurvivalLimit +OAI.Probability.Ballisticity.Estimates.SurvivingLane +OAI.Probability.Ballisticity.Estimates.SymmetricPrefixTail +OAI.Probability.Ballisticity.Estimates.SymmetricTruncate +OAI.Probability.Ballisticity.Estimates.SymmetrizedMgf +OAI.Probability.Ballisticity.Estimates.TailProfile +OAI.Probability.Ballisticity.Estimates.TailSampling +OAI.Probability.Ballisticity.Estimates.TightIidDifferenceTranslations +OAI.Probability.Ballisticity.Estimates.TripleTestPerturbation +OAI.Probability.Ballisticity.Estimates.TruncatedVarianceDouble +OAI.Probability.Ballisticity.Estimates.TupleClipping +OAI.Probability.Ballisticity.Estimates.TupleEndpoint +OAI.Probability.Ballisticity.Estimates.TwoStopSplice +OAI.Probability.Ballisticity.Estimates.UniformLowerMass +OAI.Probability.Ballisticity.Estimates.UniformRiemannMesh +OAI.Probability.Ballisticity.Estimates.UniformSpreadSequences +OAI.Probability.Ballisticity.Estimates.UpperPairPatch +OAI.Probability.Ballisticity.Estimates.VarianceTailDifference +OAI.Probability.Ballisticity.Estimates.VisibleFailure +OAI.Probability.Ballisticity.Estimates.VisitTrials +OAI.Probability.Ballisticity.Estimates.WeakAddTendsto +OAI.Probability.Ballisticity.Estimates.WeakTailTransfer +OAI.Probability.Ballisticity.Estimates.WeakVaryingParameter +OAI.Probability.Ballisticity.Estimates.WeightedConditioned +OAI.Probability.Ballisticity.Estimates.WeightedTestPerturbation +OAI.Probability.Ballisticity.Estimates.WidthGridTail +OAI.Probability.Ballisticity.Estimates.WordConcatenation +OAI.Probability.Ballisticity.Estimates.WordDepartures +OAI.Probability.Ballisticity.Estimates.WordPrefixes +OAI.Probability.Ballisticity.Estimates.WordTemplate +OAI.Probability.Ballisticity.Geometry.AlignedSlabs +OAI.Probability.Ballisticity.Geometry.BufferAllHeightRetention +OAI.Probability.Ballisticity.Geometry.BufferElapsedHeight +OAI.Probability.Ballisticity.Geometry.BufferStructuralHeight +OAI.Probability.Ballisticity.Geometry.CenteredHeightAdditiveUniform +OAI.Probability.Ballisticity.Geometry.CoordinateLanesDisjoint +OAI.Probability.Ballisticity.Geometry.CoordinateStrip +OAI.Probability.Ballisticity.Geometry.CurvePolicyTubeMass +OAI.Probability.Ballisticity.Geometry.CurveWordTube +OAI.Probability.Ballisticity.Geometry.FiniteConditionalDensityTubeTransfer +OAI.Probability.Ballisticity.Geometry.FiniteCoordinateApproximation +OAI.Probability.Ballisticity.Geometry.FinitePastCoordinates +OAI.Probability.Ballisticity.Geometry.FiniteWordGeometry +OAI.Probability.Ballisticity.Geometry.HeightIncrement +OAI.Probability.Ballisticity.Geometry.HeightPolygon +OAI.Probability.Ballisticity.Geometry.HeightPolygonRandomShiftSmall +OAI.Probability.Ballisticity.Geometry.HeightPolygonTranslateApply +OAI.Probability.Ballisticity.Geometry.HeightSlab +OAI.Probability.Ballisticity.Geometry.HeightTubeWindow +OAI.Probability.Ballisticity.Geometry.JointTubeSuccess +OAI.Probability.Ballisticity.Geometry.LatticeVector +OAI.Probability.Ballisticity.Geometry.MedianTubeFailure +OAI.Probability.Ballisticity.Geometry.NormHeightPolygon +OAI.Probability.Ballisticity.Geometry.OccupationWindow +OAI.Probability.Ballisticity.Geometry.PairHeight +OAI.Probability.Ballisticity.Geometry.RawMedianTubeSingleSite +OAI.Probability.Ballisticity.Geometry.RawWindow +OAI.Probability.Ballisticity.Geometry.RecordIndexPrefixHeight +OAI.Probability.Ballisticity.Geometry.RestrictedWindow +OAI.Probability.Ballisticity.Geometry.SignedCoordinate +OAI.Probability.Ballisticity.Geometry.SignedHeight +OAI.Probability.Ballisticity.Geometry.SignedHeightSub +OAI.Probability.Ballisticity.Geometry.SignedStripTruncation +OAI.Probability.Ballisticity.Geometry.SpatialConfinement +OAI.Probability.Ballisticity.Geometry.StoppedTubeEndpoint +OAI.Probability.Ballisticity.Geometry.StripTimeTail +OAI.Probability.Ballisticity.Geometry.SuccessfulAverageTubeTransfer +OAI.Probability.Ballisticity.Geometry.SumWindowDifference +OAI.Probability.Ballisticity.Geometry.TubeEndpoint +OAI.Probability.Ballisticity.Geometry.TubeHeightMono +OAI.Probability.Ballisticity.Geometry.TubePrefix +OAI.Probability.Ballisticity.Geometry.TubePrefixMass +OAI.Probability.Ballisticity.Geometry.TubePrefixMonoRadius +OAI.Probability.Ballisticity.Geometry.WeightedConditionedTubeTransfer +OAI.Probability.Ballisticity.Geometry.WindowProjection +OAI.Probability.Ballisticity.Geometry.WindowWeak +OAI.Probability.Ballisticity.Geometry.WordCoordinate +OAI.Probability.Ballisticity.Geometry.WordHeightGain +OAI.Probability.Ballisticity.Main +OAI.Probability.Ballisticity.Model +OAI.Probability.Ballisticity.PositiveEscape +OAI.Probability.Ballisticity.Renewal.ClippingPositiveNumbers +OAI.Probability.Ballisticity.Renewal.CurvePositiveScale +OAI.Probability.Ballisticity.Renewal.DurationMoment +OAI.Probability.Ballisticity.Renewal.DurationTail +OAI.Probability.Ballisticity.Renewal.PositiveLengthMark +OAI.Probability.Ballisticity.Renewal.PositiveOpenTest +OAI.Probability.Ballisticity.Renewal.PositiveQuenchedEvent +OAI.Probability.Ballisticity.Renewal.Regeneration +OAI.Probability.Ballisticity.Renewal.RegenerationWords +OAI.Probability.Ballisticity.Renewal.RenewalCountBounds +OAI.Probability.Ballisticity.Renewal.VelocityWords +OAI.Probability.Ballisticity.RowBridge +OAI.Probability.Ballisticity.Stationary.Array +OAI.Probability.Ballisticity.Stationary.ArrayClassProbability +OAI.Probability.Ballisticity.Stationary.ArrayClosed +OAI.Probability.Ballisticity.Stationary.ArrayDust +OAI.Probability.Ballisticity.Stationary.ArrayFiniteClasses +OAI.Probability.Ballisticity.Stationary.ArrayFull +OAI.Probability.Ballisticity.Stationary.ArrayMap +OAI.Probability.Ballisticity.Stationary.ArrayMarkTests +OAI.Probability.Ballisticity.Stationary.ArrayMarkedEntropy +OAI.Probability.Ballisticity.Stationary.ArrayMarkedIterate +OAI.Probability.Ballisticity.Stationary.ArrayMassSurvival +OAI.Probability.Ballisticity.Stationary.ArrayPermutation +OAI.Probability.Ballisticity.Stationary.ArrayProfileConsistency +OAI.Probability.Ballisticity.Stationary.ArraySurvival +OAI.Probability.Ballisticity.Stationary.ArrayTopology +OAI.Probability.Ballisticity.Stationary.ArrayWindowMarks +OAI.Probability.Ballisticity.Stationary.BadArrayElliptic +OAI.Probability.Ballisticity.Stationary.BadArraySampling +OAI.Probability.Ballisticity.Stationary.BadCrossingEpisodes +OAI.Probability.Ballisticity.Stationary.BadFiniteArray +OAI.Probability.Ballisticity.Stationary.CompactCapTransfer +OAI.Probability.Ballisticity.Stationary.EpisodeAdapted +OAI.Probability.Ballisticity.Stationary.EpisodeCharts +OAI.Probability.Ballisticity.Stationary.EpisodeCountLedger +OAI.Probability.Ballisticity.Stationary.EpisodeCounterChain +OAI.Probability.Ballisticity.Stationary.EpisodeDropLedger +OAI.Probability.Ballisticity.Stationary.EpisodeEntropyTelescoping +OAI.Probability.Ballisticity.Stationary.EpisodeExponential +OAI.Probability.Ballisticity.Stationary.EpisodeFresh +OAI.Probability.Ballisticity.Stationary.EpisodeGlobalRetention +OAI.Probability.Ballisticity.Stationary.EpisodeInjection +OAI.Probability.Ballisticity.Stationary.EpisodeLength +OAI.Probability.Ballisticity.Stationary.EpisodeLogLength +OAI.Probability.Ballisticity.Stationary.EpisodeMeanDrop +OAI.Probability.Ballisticity.Stationary.EpisodeNumber +OAI.Probability.Ballisticity.Stationary.EpisodePotentialIteration +OAI.Probability.Ballisticity.Stationary.EpisodeRandomStart +OAI.Probability.Ballisticity.Stationary.EpisodeRecordedAtlas +OAI.Probability.Ballisticity.Stationary.EpisodeRetention +OAI.Probability.Ballisticity.Stationary.LocalEpisodeLog +OAI.Probability.Ballisticity.Stationary.OperationalEpisode +OAI.Probability.Ballisticity.Stationary.StationaryArrayLaw +OAI.Probability.Ballisticity.Stationary.StationaryCompact +OAI.Probability.Ballisticity.Stationary.StationaryMarking +OAI.Probability.Ballisticity.Stationary.StationaryMonotone +OAI.Probability.Ballisticity.Stationary.StationaryProfile +OAI.Probability.Ballisticity.Stationary.StationaryProfile2 +OAI.Probability.Ballisticity.Stationary.StationaryWindowEntropy +OAI.Probability.Ballisticity.VelocityHemisphere +OAI.Probability.Ballisticity.Walk.ArrayCostGrowth +OAI.Probability.Ballisticity.Walk.ArrayGrowthEvent +OAI.Probability.Ballisticity.Walk.BoundaryPathCoordinates +OAI.Probability.Ballisticity.Walk.BufferGrowthArithmetic +OAI.Probability.Ballisticity.Walk.BufferHistoryBracket +OAI.Probability.Ballisticity.Walk.BufferNormalizedRows +OAI.Probability.Ballisticity.Walk.ClippedPairGrowth +OAI.Probability.Ballisticity.Walk.CompactPathModulus +OAI.Probability.Ballisticity.Walk.CoordinateKernelComp +OAI.Probability.Ballisticity.Walk.CurvePolicyKernel +OAI.Probability.Ballisticity.Walk.FiniteOutwardRowApproximation +OAI.Probability.Ballisticity.Walk.FixedQuenchedKernel +OAI.Probability.Ballisticity.Walk.FreshRowWeights +OAI.Probability.Ballisticity.Walk.GaussianPathFiniteLawSingleton +OAI.Probability.Ballisticity.Walk.GaussianPathFiniteLawSmul +OAI.Probability.Ballisticity.Walk.JointPathIndependence +OAI.Probability.Ballisticity.Walk.Kernel +OAI.Probability.Ballisticity.Walk.KernelBoundedExpectation +OAI.Probability.Ballisticity.Walk.KernelSections +OAI.Probability.Ballisticity.Walk.KernelTranslation +OAI.Probability.Ballisticity.Walk.OutwardCanonicalRows +OAI.Probability.Ballisticity.Walk.OutwardKernelElementary +OAI.Probability.Ballisticity.Walk.PathCompact +OAI.Probability.Ballisticity.Walk.PathPointMean +OAI.Probability.Ballisticity.Walk.PathWindowTest +OAI.Probability.Ballisticity.Walk.PreBrownianGridMartingale +OAI.Probability.Ballisticity.Walk.ProfileGrowth +OAI.Probability.Ballisticity.Walk.ProfileGrowth2 +OAI.Probability.Ballisticity.Walk.QuenchedRegularPathAe +OAI.Probability.Ballisticity.Walk.RawPairKernel +OAI.Probability.Ballisticity.Walk.RecordLinearPath +OAI.Probability.Ballisticity.Walk.RegularPath +OAI.Probability.Ballisticity.Walk.RetentionRowsAllHeights +OAI.Probability.Ballisticity.Walk.RowProductIntegral +OAI.Probability.Ballisticity.Walk.Rows +OAI.Probability.Ballisticity.Walk.SelectedFiniteKernel +OAI.Probability.Ballisticity.Walk.SelectedKernelMap +OAI.Probability.Ballisticity.Walk.SharedPairPathLimit +OAI.Probability.Ballisticity.Walk.StateTrajectory +OAI.Probability.Ballisticity.Walk.StationaryGrowth +OAI.Probability.Ballisticity.Walk.TailGrowth +OAI.Probability.Ballisticity.Walk.TransverseFirstHitSinglePathLimit +OAI.Probability.Ballisticity.Walk.UniformFinsetKernel +OAI.Probability.Ballisticity.Walk.UpperKernel +OAI.Probability.Ballisticity.Walk.VaryingHeightPathGaussianEval +OAI.Probability.Ballisticity.Walk.WeakPathEvalTendsto +OAI.Probability.Ballisticity.Walk.WienerPathMaximal +OAI.Probability.DirectionalWalk.ActualComparison +OAI.Probability.DirectionalWalk.Avoidance +OAI.Probability.DirectionalWalk.Axis +OAI.Probability.DirectionalWalk.AxisBridges +OAI.Probability.DirectionalWalk.AxisCubes +OAI.Probability.DirectionalWalk.BandContacts +OAI.Probability.DirectionalWalk.BridgeKernels +OAI.Probability.DirectionalWalk.BridgeWords +OAI.Probability.DirectionalWalk.BufferEntropy +OAI.Probability.DirectionalWalk.BufferedComparison +OAI.Probability.DirectionalWalk.Columns +OAI.Probability.DirectionalWalk.CommonBands +OAI.Probability.DirectionalWalk.CommonBlocks +OAI.Probability.DirectionalWalk.ContactBins +OAI.Probability.DirectionalWalk.ContactEvents +OAI.Probability.DirectionalWalk.ContactGeometry +OAI.Probability.DirectionalWalk.ContactJoins +OAI.Probability.DirectionalWalk.CountWindows +OAI.Probability.DirectionalWalk.CylinderLaw +OAI.Probability.DirectionalWalk.DirectionalReduction +OAI.Probability.DirectionalWalk.DyadicBounds +OAI.Probability.DirectionalWalk.DyadicCover +OAI.Probability.DirectionalWalk.Entropy +OAI.Probability.DirectionalWalk.EntropyBounds +OAI.Probability.DirectionalWalk.EntropyLaws +OAI.Probability.DirectionalWalk.EntropyTransforms +OAI.Probability.DirectionalWalk.EntropyUpperBound +OAI.Probability.DirectionalWalk.Escape +OAI.Probability.DirectionalWalk.ExperimentContact +OAI.Probability.DirectionalWalk.FiniteContacts +OAI.Probability.DirectionalWalk.FreshContacts +OAI.Probability.DirectionalWalk.FreshPaths +OAI.Probability.DirectionalWalk.HittingWords +OAI.Probability.DirectionalWalk.Information +OAI.Probability.DirectionalWalk.JoinedBridges +OAI.Probability.DirectionalWalk.LateContacts +OAI.Probability.DirectionalWalk.LateEndpoints +OAI.Probability.DirectionalWalk.LatePrefixes +OAI.Probability.DirectionalWalk.Main +OAI.Probability.DirectionalWalk.MarkedSums +OAI.Probability.DirectionalWalk.MixedTapes +OAI.Probability.DirectionalWalk.Model +OAI.Probability.DirectionalWalk.PosteriorMax +OAI.Probability.DirectionalWalk.PosteriorTails +OAI.Probability.DirectionalWalk.Radii +OAI.Probability.DirectionalWalk.RadiusLaunch +OAI.Probability.DirectionalWalk.RadiusMoment +OAI.Probability.DirectionalWalk.RadiusTails +OAI.Probability.DirectionalWalk.Records +OAI.Probability.DirectionalWalk.Regeneration +OAI.Probability.DirectionalWalk.RegenerativeTapes +OAI.Probability.DirectionalWalk.RelativeContinuation +OAI.Probability.DirectionalWalk.RelativeEntropy +OAI.Probability.DirectionalWalk.Renewal +OAI.Probability.DirectionalWalk.RenewalFactorization +OAI.Probability.DirectionalWalk.RenewalMass +OAI.Probability.DirectionalWalk.ReversedContacts +OAI.Probability.DirectionalWalk.ShiftedBlocks +OAI.Probability.DirectionalWalk.Shifts +OAI.Probability.DirectionalWalk.SignedInformation +OAI.Probability.DirectionalWalk.Slabs +OAI.Probability.DirectionalWalk.SumLaws +OAI.Probability.DirectionalWalk.ThreeChunks +OAI.Probability.DirectionalWalk.ThreeLists +OAI.Probability.DirectionalWalk.TotalEntropy +OAI.Probability.DirectionalWalk.TwoTapes +OAI.Probability.DirectionalWalk.Widths +OAI.Probability.DirectionalWalk.WordPosterior +OAI.Probability.DirectionalWalk.Words diff --git a/tasks/velocity-hemisphere/solution/reference.py b/tasks/velocity-hemisphere/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/velocity-hemisphere/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/velocity-hemisphere/solution/solve.sh b/tasks/velocity-hemisphere/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..91aa9620314ef8ec838e01e1b5cb4d227fdc0af0 --- /dev/null +++ b/tasks/velocity-hemisphere/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of VelocityHemisphere, i.e. module OAI.Probability.Ballisticity.VelocityHemisphere and the +# 585 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.Ballisticity.VelocityHemisphere /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of VelocityHemisphere" diff --git a/tasks/velocity-hemisphere/task.toml b/tasks/velocity-hemisphere/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..502b5c28253a7a6fcc8809fa0e865cf7f54d319b --- /dev/null +++ b/tasks/velocity-hemisphere/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/velocity-hemisphere" +version = "1.0.0" +description = "Prove VelocityHemisphere (openai/math family 220: Directional zero–one laws and ballisticity in random environments) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/VelocityHemisphere.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "VelocityHemisphere" +family = "220" +family_title = "Directional zero–one laws and ballisticity in random environments" +subject = "Probability and statistical mechanics" +theorems = ["OAI.DirectionalTransience.positive_probability_transience_velocity_hemisphere"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.Ballisticity.VelocityHemisphere" +reference_modules = 585 +reference_lean_bytes = 5974000 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1928 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 17076 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/velocity-hemisphere/tests/Challenge.lean b/tasks/velocity-hemisphere/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..125c0d315ad45595e6d278332286265231bfb0a8 --- /dev/null +++ b/tasks/velocity-hemisphere/tests/Challenge.lean @@ -0,0 +1,102 @@ +import Mathlib + +namespace OAI + +open MeasureTheory ProbabilityTheory Filter +open scoped ENNReal NNReal BigOperators Topology + +namespace DirectionalTransience + +abbrev Lattice (d : ℕ) := Fin d → ℤ +abbrev Direction (d : ℕ) := Fin d × Bool +abbrev Vector (d : ℕ) := Fin d → ℝ +abbrev Row (d : ℕ) := {p : Direction d → ℝ≥0 // ∑ e, p e = 1} +abbrev Environment (d : ℕ) := Lattice d → Row d +abbrev State (d : ℕ) := Environment d × Lattice d +abbrev Path (d : ℕ) := ℕ → Lattice d + +def step {d : ℕ} (e : Direction d) : Lattice d := + fun i => if i = e.1 then (if e.2 then 1 else -1) else 0 + +noncomputable def environmentLaw {d : ℕ} (ν : Measure (Row d)) : + Measure (Environment d) := Measure.infinitePi (fun _ => ν) + +def UniformElliptic {d : ℕ} (ν : Measure (Row d)) : Prop := + ∃ κ : ℝ≥0, 0 < κ ∧ ∀ᵐ p ∂ν, ∀ e, κ ≤ p.1 e + +lemma measurable_current_row {d : ℕ} : + Measurable (fun z : State d => z.1 z.2) := by + apply measurable_from_prod_countable_left + intro x + exact measurable_pi_apply x + +noncomputable def transition {d : ℕ} : Kernel (State d) (State d) where + toFun z := ∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e) + measurable' := by + apply Measure.measurable_of_measurable_coe + intro s hs + simp only [Measure.finsetSum_apply, Measure.smul_apply, smul_eq_mul] + apply Finset.measurable_fun_sum + intro e _ + apply Measurable.mul + · exact (measurable_pi_apply e |>.comp + (measurable_subtype_coe.comp measurable_current_row)).coe_nnreal_ennreal + · exact (Measure.measurable_coe hs).comp + (Measure.measurable_dirac.comp (measurable_fst.prodMk + (measurable_snd.add_const (step e)))) + +instance transition_markov {d : ℕ} : IsMarkovKernel (transition (d := d)) where + isProbabilityMeasure z := by + constructor + change (∑ e : Direction d, + ((z.1 z.2).1 e : ℝ≥0∞) • Measure.dirac (z.1, z.2 + step e)) Set.univ = 1 + simp only [Measure.finsetSum_apply, Measure.smul_apply, Measure.dirac_apply_of_mem + (Set.mem_univ _), smul_eq_mul, mul_one] + rw [← ENNReal.ofNNReal_finsetSum, (z.1 z.2).2] + rfl + +noncomputable def historyTransition {d : ℕ} (n : ℕ) : + Kernel ((i : Finset.Iic n) → State d) (State d) where + toFun z := transition (z ⟨n, Finset.mem_Iic.mpr le_rfl⟩) + measurable' := transition.measurable.comp (measurable_pi_apply _) + +instance historyTransition_markov {d : ℕ} (n : ℕ) : + IsMarkovKernel (historyTransition (d := d) n) where + isProbabilityMeasure _ := transition_markov.isProbabilityMeasure _ + +noncomputable def initialLaw {d : ℕ} (ν : Measure (Row d)) : Measure (State d) := + (environmentLaw ν).map (fun ω => (ω, (0 : Lattice d))) + +noncomputable def annealedLaw {d : ℕ} (ν : Measure (Row d)) : Measure (Path d) := + (@Kernel.trajMeasure (fun _ => State d) _ (initialLaw ν) (historyTransition (d := d)) _).map + (fun z n => (z n).2) + +def dot {d : ℕ} (v ℓ : Vector d) : ℝ := ∑ i, v i * ℓ i + +def realPosition {d : ℕ} (x : Lattice d) : Vector d := fun i => (x i : ℝ) + +def TransientPaths {d : ℕ} (ℓ : Vector d) : Set (Path d) := + {X | Tendsto (fun n => dot (realPosition (X n)) ℓ) atTop atTop} + +def VelocityPaths {d : ℕ} (v : Vector d) : Set (Path d) := + {X | Tendsto (fun n : ℕ => fun i => (X n i:ℝ)/(n:ℝ)) atTop (𝓝 v)} + +theorem positive_probability_transience_velocity_hemisphere + {d : ℕ} (hd : 3 ≤ d) (ν : Measure (Row d)) [IsProbabilityMeasure ν] + (hue : UniformElliptic ν) (ℓ : Vector d) (hℓ : ℓ ≠ 0) + (hpos : 0 < annealedLaw ν (TransientPaths ℓ)) : + ∃ v : Vector d, + v ≠ 0 ∧ 0 < dot v ℓ ∧ annealedLaw ν (VelocityPaths v) = 1 ∧ + (∀ w : Vector d, annealedLaw ν (VelocityPaths w) = 1 → w = v) ∧ + {u : Vector d | dot u u = 1 ∧ annealedLaw ν (TransientPaths u) = 1} = + {u : Vector d | dot u u = 1 ∧ 0 < annealedLaw ν (TransientPaths u)} ∧ + {u : Vector d | dot u u = 1 ∧ 0 < annealedLaw ν (TransientPaths u)} = + {u : Vector d | dot u u = 1 ∧ 0 < dot v u} ∧ + (∀ u : Vector d, dot u u = 1 → dot v u ≤ 0 → + annealedLaw ν (TransientPaths u) = 0) := by + sorry + +end DirectionalTransience + +end OAI diff --git a/tasks/velocity-hemisphere/tests/grade.py b/tasks/velocity-hemisphere/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/velocity-hemisphere/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/velocity-hemisphere/tests/task.json b/tasks/velocity-hemisphere/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..ce2efeb9c172861335c25161fececdab7841e09a --- /dev/null +++ b/tasks/velocity-hemisphere/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "VelocityHemisphere", + "comparator": { + "theorem_names": [ + "OAI.DirectionalTransience.positive_probability_transience_velocity_hemisphere" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 16176 +} \ No newline at end of file diff --git a/tasks/velocity-hemisphere/tests/test.sh b/tasks/velocity-hemisphere/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/velocity-hemisphere/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/vertex-algebra-net/environment/Dockerfile b/tasks/vertex-algebra-net/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/vertex-algebra-net/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/vertex-algebra-net/environment/fetch_mathlib.sh b/tasks/vertex-algebra-net/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/vertex-algebra-net/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/vertex-algebra-net/environment/lake-manifest.json b/tasks/vertex-algebra-net/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/vertex-algebra-net/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/vertex-algebra-net/environment/lakefile.lean b/tasks/vertex-algebra-net/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/vertex-algebra-net/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/vertex-algebra-net/environment/lean_setup.sh b/tasks/vertex-algebra-net/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/vertex-algebra-net/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/vertex-algebra-net/environment/pack_submission.py b/tasks/vertex-algebra-net/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/vertex-algebra-net/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/vertex-algebra-net/instruction.md b/tasks/vertex-algebra-net/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..80f1bc0fb601ee4be93ecf0c0faf4bb74ce340e1 --- /dev/null +++ b/tasks/vertex-algebra-net/instruction.md @@ -0,0 +1,881 @@ +# openai/math challenge `VertexAlgebraNet` (family 280) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 280 of the release, *Strong locality for strongly rational unitary vertex operator algebras* +(Mathematical physics). The family as a whole: Proves the strongly rational case of the strong-locality conjecture: every simple unitary strongly rational complex vertex operator algebra generates a completely rational conformal net. Its simple modules are unitarizable, and its representation category agrees with the net’s finite-index sectors as a braided unitary tensor category. + +The challenge is `VertexAlgebraNet`, also at `/opt/openai-math/challenges/VertexAlgebraNet.lean`: + +```lean +import Mathlib + +/-! The strongly rational unitary vertex operator algebra main result, clause (1). -/ + +noncomputable section +universe u v w + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +noncomputable abbrev StateField (V : Type u) (W : Type v) + [AddCommGroup V] [Module ℂ V] [AddCommGroup W] [Module ℂ W] := + V →ₗ[ℂ] VertexOperator ℂ W + +noncomputable def mode {W : Type v} [AddCommGroup W] [Module ℂ W] + (Y : OAI.StronglyRationalVOA.StateField V W) (a : V) (n : ℤ) : Module.End ℂ W := + VertexOperator.ncoeff (Y a) n + +noncomputable def JacobiIdentity (Y : OAI.StronglyRationalVOA.StateField V V) : Prop := + ∀ (a b c : V) (m n k : ℤ), + (∑ᶠ j : ℕ, Ring.choose (m : ℂ) j • + OAI.StronglyRationalVOA.mode Y (OAI.StronglyRationalVOA.mode Y a (n + j) b) (m + k - j) c) = + ∑ᶠ j : ℕ, ((-1 : ℂ) ^ j * Ring.choose (n : ℂ) j) • + (OAI.StronglyRationalVOA.mode Y a (m + n - j) (OAI.StronglyRationalVOA.mode Y b (k + j) c) - + (-1 : ℂ) ^ n • OAI.StronglyRationalVOA.mode Y b (n + k - j) (OAI.StronglyRationalVOA.mode Y a (m + j) c)) + +structure VertexAlgebra (V : Type u) [AddCommGroup V] [Module ℂ V] where + vacuum : V + fields : OAI.StronglyRationalVOA.StateField V V + vacuum_mode : ∀ (n : ℤ), OAI.StronglyRationalVOA.mode fields vacuum n = if n = -1 then 1 else 0 + creation : ∀ a : V, OAI.StronglyRationalVOA.mode fields a (-1) vacuum = a + creation_truncation : ∀ (a : V) (n : ℤ), 0 ≤ n → OAI.StronglyRationalVOA.mode fields a n vacuum = 0 + jacobi : OAI.StronglyRationalVOA.JacobiIdentity fields + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.VertexAlgebra +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable (A : VertexAlgebra V) + +noncomputable def translation : Module.End ℂ V where + toFun a := OAI.StronglyRationalVOA.mode A.fields a (-2) A.vacuum + map_add' a b := by simp [OAI.StronglyRationalVOA.mode] + map_smul' z a := by simp [OAI.StronglyRationalVOA.mode] + +noncomputable def c2 : Submodule ℂ V := + Submodule.span ℂ {x | ∃ a b : V, x = OAI.StronglyRationalVOA.mode A.fields a (-2) b} + +noncomputable def C2Cofinite : Prop := FiniteDimensional ℂ (V ⧸ A.c2) + +noncomputable def IsIdeal (I : Submodule ℂ V) : Prop := + (∀ a : V, ∀ n : ℤ, ∀ x ∈ I, OAI.StronglyRationalVOA.mode A.fields a n x ∈ I) ∧ + ∀ x ∈ I, A.translation x ∈ I + +noncomputable def IsSimple : Prop := + A.vacuum ≠ 0 ∧ ∀ I : Submodule ℂ V, A.IsIdeal I → I = ⊥ ∨ I = ⊤ + +end OAI.StronglyRationalVOA.VertexAlgebra + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +noncomputable def ModuleJacobiIdentity {W : Type v} [AddCommGroup W] [Module ℂ W] + (A : OAI.StronglyRationalVOA.VertexAlgebra V) (Y : OAI.StronglyRationalVOA.StateField V W) : Prop := + ∀ (a b : V) (c : W) (m n k : ℤ), + (∑ᶠ j : ℕ, Ring.choose (m : ℂ) j • + OAI.StronglyRationalVOA.mode Y (OAI.StronglyRationalVOA.mode A.fields a (n + j) b) (m + k - j) c) = + ∑ᶠ j : ℕ, ((-1 : ℂ) ^ j * Ring.choose (n : ℂ) j) • + (OAI.StronglyRationalVOA.mode Y a (m + n - j) (OAI.StronglyRationalVOA.mode Y b (k + j) c) - + (-1 : ℂ) ^ n • OAI.StronglyRationalVOA.mode Y b (n + k - j) (OAI.StronglyRationalVOA.mode Y a (m + j) c)) + +structure WeakModule (A : OAI.StronglyRationalVOA.VertexAlgebra V) (W : Type v) + [AddCommGroup W] [Module ℂ W] where + fields : OAI.StronglyRationalVOA.StateField V W + vacuum_mode : ∀ n : ℤ, OAI.StronglyRationalVOA.mode fields A.vacuum n = if n = -1 then 1 else 0 + jacobi : OAI.StronglyRationalVOA.ModuleJacobiIdentity A fields + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.WeakModule +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable {W : Type v} [AddCommGroup W] [Module ℂ W] + {A : VertexAlgebra V} (M : WeakModule A W) + +noncomputable def IsInvariant (I : Submodule ℂ W) : Prop := + ∀ a : V, ∀ n : ℤ, ∀ x ∈ I, OAI.StronglyRationalVOA.mode M.fields a n x ∈ I + +noncomputable def CompletelyReducible : Prop := + ∀ I : Submodule ℂ W, M.IsInvariant I → + ∃ J : Submodule ℂ W, M.IsInvariant J ∧ IsCompl I J + +end OAI.StronglyRationalVOA.WeakModule + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +structure CFTTypeVOA (V : Type u) [AddCommGroup V] [Module ℂ V] + extends OAI.StronglyRationalVOA.VertexAlgebra V where + conformalVector : V + centralCharge : ℂ + grade : ℕ → Submodule ℂ V + grading_internal : DirectSum.IsInternal grade + grade_finite : ∀ d, FiniteDimensional ℂ (grade d) + vacuum_ne_zero : vacuum ≠ 0 + grade_zero : grade 0 = ℂ ∙ vacuum + conformal_mem : conformalVector ∈ grade 2 + conformal_energy : ∀ d, ∀ a ∈ grade d, + OAI.StronglyRationalVOA.mode fields conformalVector 1 a = (d : ℂ) • a + conformal_translation : OAI.StronglyRationalVOA.mode fields conformalVector 0 = toVertexAlgebra.translation + translation_covariance : ∀ a : V, ∀ n : ℤ, + OAI.StronglyRationalVOA.mode fields (toVertexAlgebra.translation a) n = + (-(n : ℂ)) • OAI.StronglyRationalVOA.mode fields a (n - 1) + virasoro : ∀ m n : ℤ, + (OAI.StronglyRationalVOA.mode fields conformalVector (m + 1)).comp (OAI.StronglyRationalVOA.mode fields conformalVector (n + 1)) - + (OAI.StronglyRationalVOA.mode fields conformalVector (n + 1)).comp (OAI.StronglyRationalVOA.mode fields conformalVector (m + 1)) = + ((m - n : ℤ) : ℂ) • OAI.StronglyRationalVOA.mode fields conformalVector (m + n + 1) + + (if m + n = 0 then (centralCharge / 12) * ((m : ℂ)^3 - m) else 0) • + (1 : Module.End ℂ V) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable (A : CFTTypeVOA V) + +noncomputable def virasoroMode (m : ℤ) : Module.End ℂ V := + OAI.StronglyRationalVOA.mode A.fields A.conformalVector (m + 1) + +noncomputable def physicalMode (a : V) (d : ℕ) (m : ℤ) : Module.End ℂ V := + OAI.StronglyRationalVOA.mode A.fields a (m + d - 1) + +noncomputable def energyShift : Module.End ℂ V := 1 + A.virasoroMode 0 + +noncomputable def gradingEquiv : V ≃ₗ[ℂ] DirectSum ℕ (fun d => A.grade d) := + (LinearEquiv.ofBijective (DirectSum.coeLinearMap A.grade) A.grading_internal).symm + +noncomputable def IsAdmissible {W : Type v} [AddCommGroup W] [Module ℂ W] + (M : OAI.StronglyRationalVOA.WeakModule A.toVertexAlgebra W) : Prop := + ∃ G : ℤ → Submodule ℂ W, + DirectSum.IsInternal G ∧ (∀ k : ℤ, k < 0 → G k = ⊥) ∧ + ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n k : ℤ, ∀ x ∈ G k, + OAI.StronglyRationalVOA.mode M.fields a n x ∈ G (k + d - n - 1) + +noncomputable def IsRational : Prop := + ∀ (W : Type v) [AddCommGroup W] [Module ℂ W] + (M : OAI.StronglyRationalVOA.WeakModule A.toVertexAlgebra W), + A.IsAdmissible M → M.CompletelyReducible + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + (A : CFTTypeVOA V) + +noncomputable def PolynomialEnergyBound (a : V) : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ p k : ℕ, ∀ (n : ℤ) (b : V), + ‖OAI.StronglyRationalVOA.mode A.fields a n b‖ ≤ C * (1 + |(n : ℝ)|) ^ p * ‖(A.energyShift ^ k) b‖ + +noncomputable def PolynomialEnergyBounds : Prop := ∀ a : V, A.PolynomialEnergyBound a + +structure UnitaryStructure where + pct : V →ₛₗ[starRingEnd ℂ] V + pct_involutive : Function.Involutive pct + pct_vacuum : pct A.vacuum = A.vacuum + pct_conformal : pct A.conformalVector = A.conformalVector + pct_modes : ∀ (a b : V) (n : ℤ), + pct (OAI.StronglyRationalVOA.mode A.fields a n b) = OAI.StronglyRationalVOA.mode A.fields (pct a) n (pct b) + vacuum_norm : ‖A.vacuum‖ = 1 + invariant : ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n : ℤ, ∀ b c : V, + inner ℂ (OAI.StronglyRationalVOA.mode A.fields a n b) c = + inner ℂ b (((-1 : ℂ) ^ d) • + ∑ j ∈ Finset.range (d + 1), ((j.factorial : ℂ)⁻¹) • + OAI.StronglyRationalVOA.mode A.fields ((A.virasoroMode 1 ^ j) (pct a)) + (2 * (d : ℤ) - j - n - 2) c) + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.StronglyRationalVOA.HilbertCore +open Filter +open UniformSpace +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space (V : Type*) [NormedAddCommGroup V] [InnerProductSpace ℂ V] : + Submodule ℂ (Completion V) := + LinearMap.range (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.equiv (V : Type*) [NormedAddCommGroup V] [InnerProductSpace ℂ V] : + V ≃ₗ[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space V) := + LinearEquiv.ofInjective (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap + (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).injective + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.operator (T : V →ₗ[ℂ] Completion V) : Completion V →ₗ.[ℂ] Completion V where + domain := (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space V) + toFun := T.comp (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.equiv V).symm.toLinearMap + +end OAI.StronglyRationalVOA.HilbertCore + +namespace OAI.StronglyRationalVOA +open Filter + +noncomputable def RapidCoefficients (f : ℤ → ℂ) : Prop := + ∀ p : ℕ, Summable (fun n : ℤ => ‖f n‖*(1+|(n : ℝ)|)^p) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SummableLinearFamily +open Filter +variable {ι V H : Type*} [NormedAddCommGroup V] [NormedSpace ℂ V] + [NormedAddCommGroup H] [NormedSpace ℂ H] + +noncomputable def tsumMap (T : ι → V →ₗ[ℂ] H) (hT : ∀ v, Summable (fun n => T n v)) : V →ₗ[ℂ] H where + toFun v := ∑' n, T n v + map_add' v w := by simpa only [map_add] using (hT v).tsum_add (hT w) + map_smul' z v := by + simpa only [map_smul, RingHom.id_apply] using (hT v).tsum_const_smul z + +end OAI.StronglyRationalVOA.SummableLinearFamily + +namespace OAI.StronglyRationalVOA +open Filter +open scoped ContDiff + +structure SmoothCircleFunction where + toFun : ℝ → ℂ + periodic : Function.Periodic toFun (2*Real.pi) + smooth : ContDiff ℝ ∞ toFun + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleFunction +open Filter +open scoped ContDiff + +noncomputable instance : CoeFun OAI.StronglyRationalVOA.SmoothCircleFunction (fun _ => ℝ → ℂ) := ⟨OAI.StronglyRationalVOA.SmoothCircleFunction.toFun⟩ + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient (f : OAI.StronglyRationalVOA.SmoothCircleFunction) (n : ℤ) : ℂ := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleFunction_period_pos : 0 < 2*Real.pi := by positivity + exact + fourierCoeffOn h_OAI_StronglyRationalVOA_SmoothCircleFunction_period_pos f n + +end OAI.StronglyRationalVOA.SmoothCircleFunction + +namespace OAI.StronglyRationalVOA.ClosedGraphData +open Filter +open scoped ContDiff +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +noncomputable abbrev _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double (H : Type u) := WithLp 2 (H × H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph (T : H →ₗ.[ℂ] H) : Submodule ℂ (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := + T.graph.comap (WithLp.prodContinuousLinearEquiv 2 ℂ H H).toLinearEquiv.toLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.projection (T : H →ₗ.[ℂ] H) (hT : T.IsClosed) : (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) →L[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := by + classical + have h_OAI_StronglyRationalVOA_ClosedGraphData_graph_closed {H : Type u} [instLocal1 : NormedAddCommGroup H] [instLocal2 : InnerProductSpace ℂ H] {T : H →ₗ.[ℂ] H} (hT : T.IsClosed) : + IsClosed ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T) : Set (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H)) := + hT.preimage (WithLp.prodContinuousLinearEquiv 2 ℂ H H).continuous + letI : IsClosed ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T) : Set (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H)) := (h_OAI_StronglyRationalVOA_ClosedGraphData_graph_closed hT) + exact (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T).starProjection + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.inclusion (i : Bool) : H →L[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := + (WithLp.prodContinuousLinearEquiv 2 ℂ H H).symm.toContinuousLinearMap.comp + (if i then ContinuousLinearMap.inr ℂ H H else ContinuousLinearMap.inl ℂ H H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.coordinate (i : Bool) : (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) →L[ℂ] H := + (if i then ContinuousLinearMap.snd ℂ H H else ContinuousLinearMap.fst ℂ H H).comp + (WithLp.prodContinuousLinearEquiv 2 ℂ H H).toContinuousLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.entry (T : H →ₗ.[ℂ] H) (hT : T.IsClosed) (i j : Bool) : H →L[ℂ] H := + (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.coordinate i).comp ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.projection T hT).comp (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.inclusion j)) + +end OAI.StronglyRationalVOA.ClosedGraphData + +namespace OAI.StronglyRationalVOA.LocalOperatorAlgebra +open Filter +open scoped ContDiff +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] +open scoped Pointwise + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.LocalOperatorAlgebra.generated (s : Set (H →L[ℂ] H)) : VonNeumannAlgebra H where + toStarSubalgebra := StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) + centralizer_centralizer' := by + change Set.centralizer (Set.centralizer + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : Set (H →L[ℂ] H))) = + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : Set (H →L[ℂ] H)) + rw [StarSubalgebra.coe_centralizer_centralizer] + rw [Set.centralizer_centralizer_centralizer] + +end OAI.StronglyRationalVOA.LocalOperatorAlgebra + +namespace OAI.StronglyRationalVOA.SmoothCircleFunction +open Filter +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.onCircle (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : AddCircle (2*Real.pi) → ℂ := + f.periodic.lift + +end OAI.StronglyRationalVOA.SmoothCircleFunction + +namespace OAI.StronglyRationalVOA +open Filter +open scoped ContDiff + +structure ProperCircleArc where + left : ℝ + right : ℝ + nonempty' : left < right + nondense' : right < left + 2*Real.pi + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.ProperCircleArc +open Filter +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier (I : OAI.StronglyRationalVOA.ProperCircleArc) : Set (AddCircle (2*Real.pi)) := + (fun t : ℝ => (t : AddCircle (2*Real.pi))) '' Set.Ioo I.left I.right + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.complement (I : OAI.StronglyRationalVOA.ProperCircleArc) : OAI.StronglyRationalVOA.ProperCircleArc where + left := I.right + right := I.left + 2*Real.pi + nonempty' := I.nondense' + nondense' := by linarith [I.nonempty'] + +end OAI.StronglyRationalVOA.ProperCircleArc + +namespace OAI.StronglyRationalVOA.BoundedFlow +open scoped Topology +open Filter +open scoped Topology +open Filter +open scoped Topology +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +local instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.boundedFlowRationalNormedAlgebra : NormedAlgebra ℚ (H →L[ℂ] H) := + .restrictScalars ℚ ℂ (H →L[ℂ] H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.flow (K : H →L[ℂ] H) (t : ℝ) : H →L[ℂ] H := NormedSpace.exp (t • K) + +end OAI.StronglyRationalVOA.BoundedFlow + +namespace OAI.StronglyRationalVOA +open scoped ContDiff + +structure SmoothCircleLift where + toOrderIso : ℝ ≃o ℝ + smooth : ContDiff ℝ ∞ toOrderIso + inverse_smooth : ContDiff ℝ ∞ toOrderIso.symm + period : ∀ t, toOrderIso (t+2*Real.pi)=toOrderIso t+2*Real.pi + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleLift +open scoped ContDiff + +noncomputable instance : CoeFun OAI.StronglyRationalVOA.SmoothCircleLift (fun _ => ℝ → ℝ) := ⟨fun F => F.toOrderIso⟩ + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := OrderIso.refl ℝ + smooth := contDiff_id + inverse_smooth := contDiff_id + period := fun _ => rfl + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose (F G : OAI.StronglyRationalVOA.SmoothCircleLift) : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := G.toOrderIso.trans F.toOrderIso + smooth := F.smooth.comp G.smooth + inverse_smooth := G.inverse_smooth.comp F.inverse_smooth + period := by intro t; change F (G (t+2*Real.pi))=F (G t)+2*Real.pi; rw [G.period,F.period] + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse (F : OAI.StronglyRationalVOA.SmoothCircleLift) : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := F.toOrderIso.symm + smooth := F.inverse_smooth + inverse_smooth := F.smooth + period := by + intro t + apply F.toOrderIso.injective + rw [F.toOrderIso.apply_symm_apply,F.period,F.toOrderIso.apply_symm_apply] + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.instGroup : Group OAI.StronglyRationalVOA.SmoothCircleLift := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_ext {F G : OAI.StronglyRationalVOA.SmoothCircleLift} (h : ∀ t, F t=G t) : F=G := by + cases F with + | mk f hf hfi hp => + cases G with + | mk g hg hgi hgp => + have he : f=g := DFunLike.ext _ _ h + subst g + rfl + exact { + mul := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose + one := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity + inv := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse + npow := @npowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩ + div := fun F G => OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose F + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse G) + zpow := @zpowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse⟩ + (@npowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩) + mul_assoc F G H := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + one_mul F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + mul_one F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + inv_mul_cancel F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; exact F.toOrderIso.symm_apply_apply t + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F : OAI.StronglyRationalVOA.SmoothCircleLift) : AddCircle (2*Real.pi) → AddCircle (2*Real.pi) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_circle_periodic (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Function.Periodic (fun t : ℝ => (F t : AddCircle (2*Real.pi))) (2*Real.pi) := by + intro t + change ((F.toOrderIso (t+2*Real.pi) : ℝ) : AddCircle (2*Real.pi)) = + (F.toOrderIso t : AddCircle (2*Real.pi)) + rw [F.period,AddCircle.coe_add] + simp + exact + (h_OAI_StronglyRationalVOA_SmoothCircleLift_circle_periodic F).lift + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleHomeomorph (F : OAI.StronglyRationalVOA.SmoothCircleLift) : + AddCircle (2*Real.pi) ≃ₜ AddCircle (2*Real.pi) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle 1 t)=t := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F * G) t)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle G t)) := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse (F : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F⁻¹ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F t))=t := by + rw [← h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul,inv_mul_cancel,h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one] + have h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Continuous (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F) := by + exact ((AddCircle.continuous_mk' (2*Real.pi)).comp F.smooth.continuous).quotient_liftOn' _ + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + exact { + toFun := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F) + invFun := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F⁻¹) + left_inv := (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse F) + right_inv := by intro t; simpa [h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply, h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply] using (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse F⁻¹ t) + continuous_toFun := (h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle F) + continuous_invFun := (h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle F⁻¹) + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction : OAI.StronglyRationalVOA.SmoothCircleLift →* Equiv.Perm (AddCircle (2*Real.pi)) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle 1 t)=t := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F * G) t)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle G t)) := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + exact { + toFun F := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleHomeomorph F).toEquiv + map_one' := by ext x; exact (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one x) + map_mul' F G := by ext x; exact (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul F G x) + } + +end OAI.StronglyRationalVOA.SmoothCircleLift + +namespace OAI.StronglyRationalVOA +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.instGroupSmoothCircleDiffeomorphism : Group OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := inferInstanceAs + (Group (OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker)) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA +open UniformSpace + +noncomputable def scalarPhaseSubgroup (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + Subgroup (H ≃ₗᵢ[ℂ] H) where + carrier := {E | ∃ c : ℂ, ‖c‖=1 ∧ ∀ x : H, E x=c • x} + one_mem' := ⟨1,by simp,fun x => (one_smul ℂ x).symm⟩ + mul_mem' := by + rintro E F ⟨c,hc,he⟩ ⟨d,hd,hf⟩ + refine ⟨c*d,by rw [norm_mul,hc,hd,one_mul],?_⟩ + intro x + change E (F x)=(c*d) • x + rw [hf,he,mul_smul] + inv_mem' := by + rintro E ⟨c,hc,he⟩ + have hn : c ≠ 0 := by intro h; rw [h,norm_zero] at hc; norm_num at hc + refine ⟨c⁻¹,by rw [norm_inv,hc,inv_one],?_⟩ + intro x + apply E.injective + change E (E.symm x)=E (c⁻¹ • x) + rw [E.apply_symm_apply,map_smul,he,smul_smul,inv_mul_cancel₀ hn,one_smul] + +noncomputable instance scalarPhaseSubgroup_normal (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + (OAI.StronglyRationalVOA.scalarPhaseSubgroup H).Normal where + conj_mem := by + rintro E ⟨c,hc,he⟩ F + refine ⟨c,hc,?_⟩ + intro x + change F (E (F.symm x))=c • x + rw [he,map_smul,F.apply_symm_apply] + +noncomputable abbrev ProjectiveUnitaryGroup (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] := + (H ≃ₗᵢ[ℂ] H) ⧸ OAI.StronglyRationalVOA.scalarPhaseSubgroup H + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleLift +open Filter Set +open scoped Topology ContDiff + +noncomputable def jet (F : OAI.StronglyRationalVOA.SmoothCircleLift) (k : ℕ) : C(ℝ,ℝ) := + ⟨iteratedDeriv k F, F.smooth.continuous_iteratedDeriv k + (by exact_mod_cast (le_top : (k : ℕ∞) ≤ ⊤))⟩ + +noncomputable instance : TopologicalSpace OAI.StronglyRationalVOA.SmoothCircleLift := + TopologicalSpace.induced (fun F => OAI.StronglyRationalVOA.SmoothCircleLift.jet F) inferInstance + +end OAI.StronglyRationalVOA.SmoothCircleLift + +namespace OAI.StronglyRationalVOA +open UniformSpace Filter Set +open scoped Topology + +noncomputable instance unitaryStrongTopology (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + TopologicalSpace (H ≃ₗᵢ[ℂ] H) := + TopologicalSpace.induced (fun E : H ≃ₗᵢ[ℂ] H => (E : H → H)) inferInstance + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.instTopologicalSpaceSmoothCircleDiffeomorphism : TopologicalSpace OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := inferInstanceAs + (TopologicalSpace (OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker)) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CircleMobiusGeometry +open Set +open scoped MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel (M : SL(2,ℝ)) (x y : ℝ) : Prop := + (M 0 0*Real.cos (x/2)+M 0 1*Real.sin (x/2))*Real.sin (y/2)= + (M 1 0*Real.cos (x/2)+M 1 1*Real.sin (x/2))*Real.cos (y/2) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements (M : SL(2,ℝ)) (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Prop := ∀ x, (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel M x ((OAI.StronglyRationalVOA.SmoothCircleLift.toOrderIso F) x)) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts : Subgroup OAI.StronglyRationalVOA.SmoothCircleLift := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_apply_inv_apply (F : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : F (F⁻¹ t)=t := F.toOrderIso.apply_symm_apply t + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_inv {M : SL(2,ℝ)} {F : OAI.StronglyRationalVOA.SmoothCircleLift} + (hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M⁻¹ F⁻¹) := by + intro x + have h := hF (F⁻¹ x) + rw [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,(h_OAI_StronglyRationalVOA_SmoothCircleLift_apply_inv_apply F)] at h + simp only [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,Matrix.SpecialLinearGroup.SL2_inv_expl,Matrix.cons_val_zero, + Matrix.cons_val_one,Matrix.cons_val_fin_one] + linear_combination -h + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_one : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements 1 1) := by + intro x + simp [h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply, OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,mul_comm] + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_collinear_unit {p q c s : ℝ} (hu : c^2+s^2=1) (h : p*s=q*c) : + (p*c+q*s)*c=p ∧ (p*c+q*s)*s=q := by + constructor + · linear_combination p*hu-s*h + · linear_combination q*hu+c*h + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (x : ℝ) : Real.cos x^2+Real.sin x^2=1 := by + nlinarith [Real.sin_sq_add_cos_sq x] + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_mul {M N : SL(2,ℝ)} {F G : OAI.StronglyRationalVOA.SmoothCircleLift} + (hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)) (hG : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements N G)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements (M * N) (F * G)) := by + intro x + have hh := hF (G x) + have hg := hG x + obtain ⟨hr1,hr2⟩ := (h_OAI_StronglyRationalVOA_CircleMobiusGeometry_collinear_unit + (h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq + ((OAI.StronglyRationalVOA.SmoothCircleLift.toOrderIso G) x / 2)) + hg) + let r := (N 0 0*Real.cos (x/2)+N 0 1*Real.sin (x/2))*Real.cos (G x/2)+ + (N 1 0*Real.cos (x/2)+N 1 1*Real.sin (x/2))*Real.sin (G x/2) + change r*Real.cos (G x/2)=N 0 0*Real.cos (x/2)+N 0 1*Real.sin (x/2) at hr1 + change r*Real.sin (G x/2)=N 1 0*Real.cos (x/2)+N 1 1*Real.sin (x/2) at hr2 + change (M 0 0*Real.cos (G x/2)+M 0 1*Real.sin (G x/2))*Real.sin (F (G x)/2)= + (M 1 0*Real.cos (G x/2)+M 1 1*Real.sin (G x/2))*Real.cos (F (G x)/2) at hh + simp only [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,(h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply),Matrix.SpecialLinearGroup.coe_mul, + Matrix.mul_apply,Fin.sum_univ_two] + linear_combination r*hh+(M 1 0*Real.cos (F (G x)/2)-M 0 0*Real.sin (F (G x)/2))*hr1+ + (M 1 1*Real.cos (F (G x)/2)-M 0 1*Real.sin (F (G x)/2))*hr2 + exact { + carrier := {F | ∃ M : SL(2,ℝ), (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)} + one_mem' := ⟨1,h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_one⟩ + mul_mem' := by rintro F G ⟨M,hM⟩ ⟨N,hN⟩; exact ⟨M*N,(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_mul hM hN)⟩ + inv_mem' := by rintro F ⟨M,hM⟩; exact ⟨M⁻¹,(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_inv hM)⟩ + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.rotationMatrix (s : ℝ) : SL(2,ℝ) := by + classical + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (x : ℝ) : Real.cos x^2+Real.sin x^2=1 := by + nlinarith [Real.sin_sq_add_cos_sq x] + exact + ⟨!![Real.cos (s/2),-Real.sin (s/2);Real.sin (s/2),Real.cos (s/2)],by + simp only [Matrix.det_fin_two_of] + nlinarith [(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (s / 2))]⟩ + +noncomputable abbrev _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group := OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts ⧸ ((OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype).ker + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.inclusion : OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group →* OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := + QuotientGroup.lift ((OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype).ker + ((QuotientGroup.mk' (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype) (by + intro F hF + exact (QuotientGroup.eq_one_iff _).mpr hF) + +end OAI.StronglyRationalVOA.CircleMobiusGeometry + +namespace OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism +open Set +open scoped Topology MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action : OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism →* Equiv.Perm (AddCircle (2*Real.pi)) := + QuotientGroup.lift (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction) + (fun _ h => h) + +end OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism + +namespace OAI.StronglyRationalVOA +open Set +open scoped Topology MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] : OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H → ((H →L[ℂ] H) ≃⋆ₐ[ℂ] (H →L[ℂ] H)) := by + classical + have h_OAI_StronglyRationalVOA_projective_equality_conjugation {H : Type _} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] (E F : H ≃ₗᵢ[ℂ] H) + (h : (QuotientGroup.mk E : OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H)=QuotientGroup.mk F) : + E.conjStarAlgEquiv=F.conjStarAlgEquiv := by + obtain ⟨c,_,hc⟩ := QuotientGroup.eq.mp h + have he (x : H) : F x=c • E x := by + have H := congrArg E (hc x) + change E (E.symm (F x))=E (c • x) at H + simpa only [E.apply_symm_apply,map_smul] using H + ext B x + change E (B (E.symm x))=F (B (F.symm x)) + have hi : E.symm x=c • F.symm x := by + apply E.injective + rw [E.apply_symm_apply,map_smul,← he,F.apply_symm_apply] + rw [hi,map_smul,map_smul,← he] + exact + Quotient.lift (fun E : H ≃ₗᵢ[ℂ] H => E.conjStarAlgEquiv) (by + intro E F h + exact (h_OAI_StronglyRationalVOA_projective_equality_conjugation E F (Quotient.sound h))) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.globalObservableAlgebra {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) : + Subalgebra ℂ (H →L[ℂ] H) := + Algebra.adjoin ℂ (⋃ I, (N I : Set (H →L[ℂ] H))) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.globalCyclicSpace {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) (Ω : H) : Submodule ℂ H := + (Submodule.span ℂ {x | ∃ B ∈ (OAI.MinimalVertex.Code.StronglyRationalVOA.globalObservableAlgebra N), x=B Ω}).topologicalClosure + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] (A : CFTTypeVOA V) + +noncomputable abbrev GradedDual := DirectSum ℕ (fun d => Module.Dual ℂ (A.grade d)) + +noncomputable def gradedDualPairing (φ : A.GradedDual) (b : V) : ℂ := by + classical + exact φ.sum (fun d f => f (A.gradingEquiv b d)) + +noncomputable def IsSelfContragredient : Prop := + ∃ e : V ≃ₗ[ℂ] A.GradedDual, + ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n : ℤ, ∀ b c : V, + A.gradedDualPairing (e (OAI.StronglyRationalVOA.mode A.fields a n b)) c = + ((-1 : ℂ)^d) * ∑ j ∈ Finset.range (d+1), ((j.factorial : ℂ)⁻¹) * + A.gradedDualPairing (e b) + (OAI.StronglyRationalVOA.mode A.fields ((A.virasoroMode 1 ^ j) a) (2*(d:ℤ)-j-n-2) c) + +noncomputable def IsStronglyRational : Prop := + A.IsSelfContragredient ∧ A.IsRational.{u,v} ∧ A.toVertexAlgebra.C2Cofinite + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + {A : CFTTypeVOA V} + +noncomputable def smearedMap (A : OAI.StronglyRationalVOA.CFTTypeVOA V) (a : V) (d : ℕ) (_ha : A.PolynomialEnergyBound a) + (f : ℤ → ℂ) (_hf : OAI.StronglyRationalVOA.RapidCoefficients f) : V →ₗ[ℂ] Completion V := by + classical + let family : ℤ → (V →ₗ[ℂ] Completion V) := fun m => + f m • (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap.comp + (A.physicalMode a d m) + exact if h : ∀ v, Summable (fun m => family m v) then + SummableLinearFamily.tsumMap family h + else 0 + +noncomputable def smoothSmearedField (_U : A.UnitaryStructure) (_hc : A.toVertexAlgebra.C2Cofinite) + (a : V) (d : ℕ) (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : Completion V →ₗ.[ℂ] Completion V := by + classical + exact if h : A.PolynomialEnergyBounds ∧ OAI.StronglyRationalVOA.RapidCoefficients (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient f) then + (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.operator + (OAI.MinimalVertex.smearedMap A a d (And.left h a) (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient f) + (And.right h))) + else 0 + +noncomputable def closedSmoothField (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (a : V) (d : ℕ) (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : Completion V →ₗ.[ℂ] Completion V := + (OAI.MinimalVertex.smoothSmearedField U hc a d f).closure + +noncomputable def localGraphData (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (O : Set (AddCircle (2*Real.pi))) : Set (Completion V →L[ℂ] Completion V) := + {x | ∃ (a : V) (d : ℕ), a ∈ A.grade d ∧ ∃ (f : OAI.StronglyRationalVOA.SmoothCircleFunction), + tsupport (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.onCircle f) ⊆ O ∧ ∃ (h : (OAI.MinimalVertex.closedSmoothField U hc a d f).IsClosed), + ∃ i j : Bool, x = (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.entry (OAI.MinimalVertex.closedSmoothField U hc a d f) h i j)} + +noncomputable def localAlgebra (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (O : Set (AddCircle (2*Real.pi))) : VonNeumannAlgebra (Completion V) := + (OAI.MinimalVertex.Code.StronglyRationalVOA.LocalOperatorAlgebra.generated (OAI.MinimalVertex.localGraphData U hc O)) + +noncomputable def intervalAlgebra (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (I : OAI.StronglyRationalVOA.ProperCircleArc) : VonNeumannAlgebra (Completion V) := + OAI.MinimalVertex.localAlgebra U hc (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) + +noncomputable def CKLWStrongLocal (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) : Prop := + (∀ a : V, A.PolynomialEnergyBound a) ∧ + ∀ I : OAI.StronglyRationalVOA.ProperCircleArc, OAI.MinimalVertex.intervalAlgebra U hc I ≤ + (OAI.MinimalVertex.intervalAlgebra U hc (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.complement I)).commutant + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +noncomputable def resolvent (T : H →ₗ.[ℂ] H) (_hs : IsSelfAdjoint T) (z : ℂ) (_hz : 1 ≤ |z.im|) : + H →L[ℂ] H := by + classical + exact if h : ∃ R : H →L[ℂ] H, ∀ y, (R y, y + z • R y) ∈ T.graph then h.choose + else 0 + +noncomputable def boundedGenerator (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) + (r : ℝ) (hr : 1 ≤ r) : H →L[ℂ] H := + ((r : ℂ)^2/2) • + (OAI.MinimalVertex.resolvent T hs ((r : ℂ)*Complex.I) (by simpa [abs_of_nonneg (by linarith : 0 ≤ r)] using hr) + + OAI.MinimalVertex.resolvent T hs (-((r : ℂ)*Complex.I)) (by simpa [abs_of_nonneg (by linarith : 0 ≤ r)] using hr)) + +noncomputable def approximatingFlow (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) (n : ℕ) (t : ℝ) : H →L[ℂ] H := + (OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.flow + (Complex.I • OAI.MinimalVertex.boundedGenerator T hs (↑n + 1) (le_add_of_nonneg_left (Nat.cast_nonneg n))) t) + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA + +noncomputable def flow {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) (t : ℝ) : H →L[ℂ] H := by + classical + exact if h : ∃ L : H →L[ℂ] H, ∀ x, + Tendsto (fun n => OAI.MinimalVertex.approximatingFlow T hs n t x) atTop (𝓝 (L x)) then + h.choose + else 0 + +noncomputable def projectiveStandardAction : PSL(2,ℝ) →* (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group) := by + classical + exact if h : ∃ L : PSL(2,ℝ) →* (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group), + ∀ M : SL(2,ℝ), ∃ F : OAI.StronglyRationalVOA.SmoothCircleLift, ∃ hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F), + L (QuotientGroup.mk M) = + QuotientGroup.mk (⟨F, M, hF⟩ : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts)) then h.choose + else 1 + +structure IrreducibleConformalNetStructure {H : Type*} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] + (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) where + separable : TopologicalSpace.SeparableSpace H + carrier_congr : ∀ I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I)=(OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I=N J + isotony : ∀ I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) ⊆ (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I ≤ N J + locality : ∀ I J, Disjoint (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I ≤ (N J).commutant + mobius : PSL(2,ℝ) →* (H ≃ₗᵢ[ℂ] H) + mobius_continuous : Continuous mobius + diffeomorphism : OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism →* OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H + diffeomorphism_continuous : Continuous diffeomorphism + extends_mobius : ∀ F, diffeomorphism ((OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.inclusion) (OAI.MinimalVertex.projectiveStandardAction F))=QuotientGroup.mk (mobius F) + covariance : ∀ F I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action) F '' (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) → + ∀ B : H →L[ℂ] H, OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation (diffeomorphism F) B ∈ N J ↔ B ∈ N I + local_action : ∀ F I, (∀ x ∈ (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I), (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action) F x=x) → + ∀ B ∈ N I, OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation (diffeomorphism F) B=B + vacuum : H + vacuum_norm : ‖vacuum‖=1 + vacuum_invariant : ∀ F, mobius F vacuum=vacuum + vacuum_unique : ∀ x : H, (∀ F, mobius F x=x) → ∃ c : ℂ, x=c • vacuum + vacuum_cyclic : (OAI.MinimalVertex.Code.StronglyRationalVOA.globalCyclicSpace N vacuum)=⊤ + hamiltonian : H →ₗ.[ℂ] H + hamiltonian_selfAdjoint : IsSelfAdjoint hamiltonian + positive_energy : ∀ x y, (x,y) ∈ hamiltonian.graph → 0 ≤ (inner ℂ x y).re + rotation_flow : ∀ t : ℝ, + (mobius (QuotientGroup.mk (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.rotationMatrix t))).toLinearIsometry.toContinuousLinearMap= + OAI.MinimalVertex.flow hamiltonian hamiltonian_selfAdjoint t + irreducible : ∀ Q : H →L[ℂ] H, (∀ I, Q ∈ (N I).commutant) → + ∃ c : ℂ, Q=c • (1 : H →L[ℂ] H) + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + {A : CFTTypeVOA V} (U : A.UnitaryStructure) + +theorem main (_hSimple : A.toVertexAlgebra.IsSimple) + (hSR : A.IsStronglyRational.{u,v}) : + A.PolynomialEnergyBounds ∧ OAI.MinimalVertex.CKLWStrongLocal U hSR.2.2 ∧ + Nonempty (OAI.MinimalVertex.IrreducibleConformalNetStructure (OAI.MinimalVertex.intervalAlgebra U hSR.2.2)) := by + sorry + +end OAI.MinimalVertex + +end +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/VertexAlgebraNet.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.MinimalVertex.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/vertex-algebra-net/solution/closure.txt b/tasks/vertex-algebra-net/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..148b42b5697b9a466d737982a90e8310f09a8a4e --- /dev/null +++ b/tasks/vertex-algebra-net/solution/closure.txt @@ -0,0 +1,77 @@ +OAI.RepresentationTheory.VertexAlgebra.AdjointMass +OAI.RepresentationTheory.VertexAlgebra.AlgebraCovariance +OAI.RepresentationTheory.VertexAlgebra.ApproximatingFlowDerivative +OAI.RepresentationTheory.VertexAlgebra.BlockGrowth +OAI.RepresentationTheory.VertexAlgebra.BoundedFlows +OAI.RepresentationTheory.VertexAlgebra.BoundedMultiplierSingle +OAI.RepresentationTheory.VertexAlgebra.CoefficientDifferentiated +OAI.RepresentationTheory.VertexAlgebra.CoefficientSummableBound +OAI.RepresentationTheory.VertexAlgebra.ColumnControl +OAI.RepresentationTheory.VertexAlgebra.ConformalNetContinuation +OAI.RepresentationTheory.VertexAlgebra.ConstrainedSquareBound +OAI.RepresentationTheory.VertexAlgebra.CovarianceContinuation +OAI.RepresentationTheory.VertexAlgebra.CutoffPowerControl +OAI.RepresentationTheory.VertexAlgebra.DiffeomorphismContinuity +OAI.RepresentationTheory.VertexAlgebra.DiffeomorphismStressSmooth +OAI.RepresentationTheory.VertexAlgebra.EnergyCutoff +OAI.RepresentationTheory.VertexAlgebra.EnergyCutoffNorm +OAI.RepresentationTheory.VertexAlgebra.EnergyShiftPow +OAI.RepresentationTheory.VertexAlgebra.FiniteSums +OAI.RepresentationTheory.VertexAlgebra.FixedArc +OAI.RepresentationTheory.VertexAlgebra.Foundations +OAI.RepresentationTheory.VertexAlgebra.GeneratorSharpGrowth +OAI.RepresentationTheory.VertexAlgebra.GeometryContinuation +OAI.RepresentationTheory.VertexAlgebra.GradeComponentC +OAI.RepresentationTheory.VertexAlgebra.GraphCommutants +OAI.RepresentationTheory.VertexAlgebra.GraphCovariance +OAI.RepresentationTheory.VertexAlgebra.GraphEquiv +OAI.RepresentationTheory.VertexAlgebra.GraphInvariantOf +OAI.RepresentationTheory.VertexAlgebra.HighFieldGraph +OAI.RepresentationTheory.VertexAlgebra.HilbertCore +OAI.RepresentationTheory.VertexAlgebra.HilbertRegularization +OAI.RepresentationTheory.VertexAlgebra.InverseEnergySelf +OAI.RepresentationTheory.VertexAlgebra.LocalImplementer +OAI.RepresentationTheory.VertexAlgebra.LocalNormalMap +OAI.RepresentationTheory.VertexAlgebra.LocalNormalSeries +OAI.RepresentationTheory.VertexAlgebra.Locality +OAI.RepresentationTheory.VertexAlgebra.LoweringNormSq +OAI.RepresentationTheory.VertexAlgebra.MainClauseOne +OAI.RepresentationTheory.VertexAlgebra.MinimalComparator +OAI.RepresentationTheory.VertexAlgebra.MobiusAnomaly +OAI.RepresentationTheory.VertexAlgebra.MobiusContinuity +OAI.RepresentationTheory.VertexAlgebra.MobiusExistence +OAI.RepresentationTheory.VertexAlgebra.MobiusFullGeometry +OAI.RepresentationTheory.VertexAlgebra.MobiusGeometry +OAI.RepresentationTheory.VertexAlgebra.MobiusGroup +OAI.RepresentationTheory.VertexAlgebra.MobiusRepresentation +OAI.RepresentationTheory.VertexAlgebra.MobiusStandardAction +OAI.RepresentationTheory.VertexAlgebra.MobiusStandardTopology +OAI.RepresentationTheory.VertexAlgebra.MobiusVacuum +OAI.RepresentationTheory.VertexAlgebra.MulLeftPow +OAI.RepresentationTheory.VertexAlgebra.NetAxioms +OAI.RepresentationTheory.VertexAlgebra.NetVacuum +OAI.RepresentationTheory.VertexAlgebra.ObservableScalars +OAI.RepresentationTheory.VertexAlgebra.PrimaryStressWeak +OAI.RepresentationTheory.VertexAlgebra.ProjectiveTopology +OAI.RepresentationTheory.VertexAlgebra.PropagatorContinuation +OAI.RepresentationTheory.VertexAlgebra.RegularizerFactorAdd +OAI.RepresentationTheory.VertexAlgebra.RotationConjugateCommutant +OAI.RepresentationTheory.VertexAlgebra.RotationImplementer +OAI.RepresentationTheory.VertexAlgebra.SmoothConjugateInner +OAI.RepresentationTheory.VertexAlgebra.SmoothConjugatePrimary +OAI.RepresentationTheory.VertexAlgebra.SmoothEnergyPower +OAI.RepresentationTheory.VertexAlgebra.SmoothSmearShift +OAI.RepresentationTheory.VertexAlgebra.SmoothTopology +OAI.RepresentationTheory.VertexAlgebra.SourceStrongRationality +OAI.RepresentationTheory.VertexAlgebra.StressCutoffNormalized +OAI.RepresentationTheory.VertexAlgebra.StressCutoffNormalized2 +OAI.RepresentationTheory.VertexAlgebra.StressEvolution +OAI.RepresentationTheory.VertexAlgebra.StressPropagatorDerivative +OAI.RepresentationTheory.VertexAlgebra.StressPropagatorPath +OAI.RepresentationTheory.VertexAlgebra.StressSmoothness +OAI.RepresentationTheory.VertexAlgebra.StrongContinuity +OAI.RepresentationTheory.VertexAlgebra.SummableNormSobolev +OAI.RepresentationTheory.VertexAlgebra.SymmetricWeakCommute +OAI.RepresentationTheory.VertexAlgebra.TimeAverageGraph +OAI.RepresentationTheory.VertexAlgebra.VacuumMemNegative +OAI.RepresentationTheory.VertexAlgebra.VirasoroLinearEnergy diff --git a/tasks/vertex-algebra-net/solution/reference.py b/tasks/vertex-algebra-net/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/vertex-algebra-net/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/vertex-algebra-net/solution/solve.sh b/tasks/vertex-algebra-net/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..a36fe45b41838430ed4be8886730987ff4b7ae03 --- /dev/null +++ b/tasks/vertex-algebra-net/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of VertexAlgebraNet, i.e. module OAI.RepresentationTheory.VertexAlgebra.MinimalComparator and the +# 77 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.RepresentationTheory.VertexAlgebra.MinimalComparator /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of VertexAlgebraNet" diff --git a/tasks/vertex-algebra-net/task.toml b/tasks/vertex-algebra-net/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..baf9cda34aeee2095a8c017be2bf1e3f7e12be26 --- /dev/null +++ b/tasks/vertex-algebra-net/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/vertex-algebra-net" +version = "1.0.0" +description = "Prove VertexAlgebraNet (openai/math family 280: Strong locality for strongly rational unitary vertex operator algebras) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-physics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/VertexAlgebraNet.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "VertexAlgebraNet" +family = "280" +family_title = "Strong locality for strongly rational unitary vertex operator algebras" +subject = "Mathematical physics" +theorems = ["OAI.MinimalVertex.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.RepresentationTheory.VertexAlgebra.MinimalComparator" +reference_modules = 77 +reference_lean_bytes = 1413292 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 696 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12971 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/vertex-algebra-net/tests/Challenge.lean b/tasks/vertex-algebra-net/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..06094cb4fd32fcf163a69989e6e93594347ee118 --- /dev/null +++ b/tasks/vertex-algebra-net/tests/Challenge.lean @@ -0,0 +1,830 @@ +import Mathlib + +/-! The strongly rational unitary vertex operator algebra main result, clause (1). -/ + +noncomputable section +universe u v w + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +noncomputable abbrev StateField (V : Type u) (W : Type v) + [AddCommGroup V] [Module ℂ V] [AddCommGroup W] [Module ℂ W] := + V →ₗ[ℂ] VertexOperator ℂ W + +noncomputable def mode {W : Type v} [AddCommGroup W] [Module ℂ W] + (Y : OAI.StronglyRationalVOA.StateField V W) (a : V) (n : ℤ) : Module.End ℂ W := + VertexOperator.ncoeff (Y a) n + +noncomputable def JacobiIdentity (Y : OAI.StronglyRationalVOA.StateField V V) : Prop := + ∀ (a b c : V) (m n k : ℤ), + (∑ᶠ j : ℕ, Ring.choose (m : ℂ) j • + OAI.StronglyRationalVOA.mode Y (OAI.StronglyRationalVOA.mode Y a (n + j) b) (m + k - j) c) = + ∑ᶠ j : ℕ, ((-1 : ℂ) ^ j * Ring.choose (n : ℂ) j) • + (OAI.StronglyRationalVOA.mode Y a (m + n - j) (OAI.StronglyRationalVOA.mode Y b (k + j) c) - + (-1 : ℂ) ^ n • OAI.StronglyRationalVOA.mode Y b (n + k - j) (OAI.StronglyRationalVOA.mode Y a (m + j) c)) + +structure VertexAlgebra (V : Type u) [AddCommGroup V] [Module ℂ V] where + vacuum : V + fields : OAI.StronglyRationalVOA.StateField V V + vacuum_mode : ∀ (n : ℤ), OAI.StronglyRationalVOA.mode fields vacuum n = if n = -1 then 1 else 0 + creation : ∀ a : V, OAI.StronglyRationalVOA.mode fields a (-1) vacuum = a + creation_truncation : ∀ (a : V) (n : ℤ), 0 ≤ n → OAI.StronglyRationalVOA.mode fields a n vacuum = 0 + jacobi : OAI.StronglyRationalVOA.JacobiIdentity fields + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.VertexAlgebra +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable (A : VertexAlgebra V) + +noncomputable def translation : Module.End ℂ V where + toFun a := OAI.StronglyRationalVOA.mode A.fields a (-2) A.vacuum + map_add' a b := by simp [OAI.StronglyRationalVOA.mode] + map_smul' z a := by simp [OAI.StronglyRationalVOA.mode] + +noncomputable def c2 : Submodule ℂ V := + Submodule.span ℂ {x | ∃ a b : V, x = OAI.StronglyRationalVOA.mode A.fields a (-2) b} + +noncomputable def C2Cofinite : Prop := FiniteDimensional ℂ (V ⧸ A.c2) + +noncomputable def IsIdeal (I : Submodule ℂ V) : Prop := + (∀ a : V, ∀ n : ℤ, ∀ x ∈ I, OAI.StronglyRationalVOA.mode A.fields a n x ∈ I) ∧ + ∀ x ∈ I, A.translation x ∈ I + +noncomputable def IsSimple : Prop := + A.vacuum ≠ 0 ∧ ∀ I : Submodule ℂ V, A.IsIdeal I → I = ⊥ ∨ I = ⊤ + +end OAI.StronglyRationalVOA.VertexAlgebra + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +noncomputable def ModuleJacobiIdentity {W : Type v} [AddCommGroup W] [Module ℂ W] + (A : OAI.StronglyRationalVOA.VertexAlgebra V) (Y : OAI.StronglyRationalVOA.StateField V W) : Prop := + ∀ (a b : V) (c : W) (m n k : ℤ), + (∑ᶠ j : ℕ, Ring.choose (m : ℂ) j • + OAI.StronglyRationalVOA.mode Y (OAI.StronglyRationalVOA.mode A.fields a (n + j) b) (m + k - j) c) = + ∑ᶠ j : ℕ, ((-1 : ℂ) ^ j * Ring.choose (n : ℂ) j) • + (OAI.StronglyRationalVOA.mode Y a (m + n - j) (OAI.StronglyRationalVOA.mode Y b (k + j) c) - + (-1 : ℂ) ^ n • OAI.StronglyRationalVOA.mode Y b (n + k - j) (OAI.StronglyRationalVOA.mode Y a (m + j) c)) + +structure WeakModule (A : OAI.StronglyRationalVOA.VertexAlgebra V) (W : Type v) + [AddCommGroup W] [Module ℂ W] where + fields : OAI.StronglyRationalVOA.StateField V W + vacuum_mode : ∀ n : ℤ, OAI.StronglyRationalVOA.mode fields A.vacuum n = if n = -1 then 1 else 0 + jacobi : OAI.StronglyRationalVOA.ModuleJacobiIdentity A fields + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.WeakModule +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable {W : Type v} [AddCommGroup W] [Module ℂ W] + {A : VertexAlgebra V} (M : WeakModule A W) + +noncomputable def IsInvariant (I : Submodule ℂ W) : Prop := + ∀ a : V, ∀ n : ℤ, ∀ x ∈ I, OAI.StronglyRationalVOA.mode M.fields a n x ∈ I + +noncomputable def CompletelyReducible : Prop := + ∀ I : Submodule ℂ W, M.IsInvariant I → + ∃ J : Submodule ℂ W, M.IsInvariant J ∧ IsCompl I J + +end OAI.StronglyRationalVOA.WeakModule + +namespace OAI.StronglyRationalVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] + +structure CFTTypeVOA (V : Type u) [AddCommGroup V] [Module ℂ V] + extends OAI.StronglyRationalVOA.VertexAlgebra V where + conformalVector : V + centralCharge : ℂ + grade : ℕ → Submodule ℂ V + grading_internal : DirectSum.IsInternal grade + grade_finite : ∀ d, FiniteDimensional ℂ (grade d) + vacuum_ne_zero : vacuum ≠ 0 + grade_zero : grade 0 = ℂ ∙ vacuum + conformal_mem : conformalVector ∈ grade 2 + conformal_energy : ∀ d, ∀ a ∈ grade d, + OAI.StronglyRationalVOA.mode fields conformalVector 1 a = (d : ℂ) • a + conformal_translation : OAI.StronglyRationalVOA.mode fields conformalVector 0 = toVertexAlgebra.translation + translation_covariance : ∀ a : V, ∀ n : ℤ, + OAI.StronglyRationalVOA.mode fields (toVertexAlgebra.translation a) n = + (-(n : ℂ)) • OAI.StronglyRationalVOA.mode fields a (n - 1) + virasoro : ∀ m n : ℤ, + (OAI.StronglyRationalVOA.mode fields conformalVector (m + 1)).comp (OAI.StronglyRationalVOA.mode fields conformalVector (n + 1)) - + (OAI.StronglyRationalVOA.mode fields conformalVector (n + 1)).comp (OAI.StronglyRationalVOA.mode fields conformalVector (m + 1)) = + ((m - n : ℤ) : ℂ) • OAI.StronglyRationalVOA.mode fields conformalVector (m + n + 1) + + (if m + n = 0 then (centralCharge / 12) * ((m : ℂ)^3 - m) else 0) • + (1 : Module.End ℂ V) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] +variable (A : CFTTypeVOA V) + +noncomputable def virasoroMode (m : ℤ) : Module.End ℂ V := + OAI.StronglyRationalVOA.mode A.fields A.conformalVector (m + 1) + +noncomputable def physicalMode (a : V) (d : ℕ) (m : ℤ) : Module.End ℂ V := + OAI.StronglyRationalVOA.mode A.fields a (m + d - 1) + +noncomputable def energyShift : Module.End ℂ V := 1 + A.virasoroMode 0 + +noncomputable def gradingEquiv : V ≃ₗ[ℂ] DirectSum ℕ (fun d => A.grade d) := + (LinearEquiv.ofBijective (DirectSum.coeLinearMap A.grade) A.grading_internal).symm + +noncomputable def IsAdmissible {W : Type v} [AddCommGroup W] [Module ℂ W] + (M : OAI.StronglyRationalVOA.WeakModule A.toVertexAlgebra W) : Prop := + ∃ G : ℤ → Submodule ℂ W, + DirectSum.IsInternal G ∧ (∀ k : ℤ, k < 0 → G k = ⊥) ∧ + ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n k : ℤ, ∀ x ∈ G k, + OAI.StronglyRationalVOA.mode M.fields a n x ∈ G (k + d - n - 1) + +noncomputable def IsRational : Prop := + ∀ (W : Type v) [AddCommGroup W] [Module ℂ W] + (M : OAI.StronglyRationalVOA.WeakModule A.toVertexAlgebra W), + A.IsAdmissible M → M.CompletelyReducible + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + (A : CFTTypeVOA V) + +noncomputable def PolynomialEnergyBound (a : V) : Prop := + ∃ C : ℝ, 0 < C ∧ ∃ p k : ℕ, ∀ (n : ℤ) (b : V), + ‖OAI.StronglyRationalVOA.mode A.fields a n b‖ ≤ C * (1 + |(n : ℝ)|) ^ p * ‖(A.energyShift ^ k) b‖ + +noncomputable def PolynomialEnergyBounds : Prop := ∀ a : V, A.PolynomialEnergyBound a + +structure UnitaryStructure where + pct : V →ₛₗ[starRingEnd ℂ] V + pct_involutive : Function.Involutive pct + pct_vacuum : pct A.vacuum = A.vacuum + pct_conformal : pct A.conformalVector = A.conformalVector + pct_modes : ∀ (a b : V) (n : ℤ), + pct (OAI.StronglyRationalVOA.mode A.fields a n b) = OAI.StronglyRationalVOA.mode A.fields (pct a) n (pct b) + vacuum_norm : ‖A.vacuum‖ = 1 + invariant : ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n : ℤ, ∀ b c : V, + inner ℂ (OAI.StronglyRationalVOA.mode A.fields a n b) c = + inner ℂ b (((-1 : ℂ) ^ d) • + ∑ j ∈ Finset.range (d + 1), ((j.factorial : ℂ)⁻¹) • + OAI.StronglyRationalVOA.mode A.fields ((A.virasoroMode 1 ^ j) (pct a)) + (2 * (d : ℤ) - j - n - 2) c) + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.StronglyRationalVOA.HilbertCore +open Filter +open UniformSpace +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space (V : Type*) [NormedAddCommGroup V] [InnerProductSpace ℂ V] : + Submodule ℂ (Completion V) := + LinearMap.range (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.equiv (V : Type*) [NormedAddCommGroup V] [InnerProductSpace ℂ V] : + V ≃ₗ[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space V) := + LinearEquiv.ofInjective (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap + (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).injective + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.operator (T : V →ₗ[ℂ] Completion V) : Completion V →ₗ.[ℂ] Completion V where + domain := (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.space V) + toFun := T.comp (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.equiv V).symm.toLinearMap + +end OAI.StronglyRationalVOA.HilbertCore + +namespace OAI.StronglyRationalVOA +open Filter + +noncomputable def RapidCoefficients (f : ℤ → ℂ) : Prop := + ∀ p : ℕ, Summable (fun n : ℤ => ‖f n‖*(1+|(n : ℝ)|)^p) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SummableLinearFamily +open Filter +variable {ι V H : Type*} [NormedAddCommGroup V] [NormedSpace ℂ V] + [NormedAddCommGroup H] [NormedSpace ℂ H] + +noncomputable def tsumMap (T : ι → V →ₗ[ℂ] H) (hT : ∀ v, Summable (fun n => T n v)) : V →ₗ[ℂ] H where + toFun v := ∑' n, T n v + map_add' v w := by simpa only [map_add] using (hT v).tsum_add (hT w) + map_smul' z v := by + simpa only [map_smul, RingHom.id_apply] using (hT v).tsum_const_smul z + +end OAI.StronglyRationalVOA.SummableLinearFamily + +namespace OAI.StronglyRationalVOA +open Filter +open scoped ContDiff + +structure SmoothCircleFunction where + toFun : ℝ → ℂ + periodic : Function.Periodic toFun (2*Real.pi) + smooth : ContDiff ℝ ∞ toFun + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleFunction +open Filter +open scoped ContDiff + +noncomputable instance : CoeFun OAI.StronglyRationalVOA.SmoothCircleFunction (fun _ => ℝ → ℂ) := ⟨OAI.StronglyRationalVOA.SmoothCircleFunction.toFun⟩ + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient (f : OAI.StronglyRationalVOA.SmoothCircleFunction) (n : ℤ) : ℂ := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleFunction_period_pos : 0 < 2*Real.pi := by positivity + exact + fourierCoeffOn h_OAI_StronglyRationalVOA_SmoothCircleFunction_period_pos f n + +end OAI.StronglyRationalVOA.SmoothCircleFunction + +namespace OAI.StronglyRationalVOA.ClosedGraphData +open Filter +open scoped ContDiff +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +noncomputable abbrev _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double (H : Type u) := WithLp 2 (H × H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph (T : H →ₗ.[ℂ] H) : Submodule ℂ (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := + T.graph.comap (WithLp.prodContinuousLinearEquiv 2 ℂ H H).toLinearEquiv.toLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.projection (T : H →ₗ.[ℂ] H) (hT : T.IsClosed) : (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) →L[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := by + classical + have h_OAI_StronglyRationalVOA_ClosedGraphData_graph_closed {H : Type u} [instLocal1 : NormedAddCommGroup H] [instLocal2 : InnerProductSpace ℂ H] {T : H →ₗ.[ℂ] H} (hT : T.IsClosed) : + IsClosed ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T) : Set (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H)) := + hT.preimage (WithLp.prodContinuousLinearEquiv 2 ℂ H H).continuous + letI : IsClosed ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T) : Set (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H)) := (h_OAI_StronglyRationalVOA_ClosedGraphData_graph_closed hT) + exact (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.graph T).starProjection + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.inclusion (i : Bool) : H →L[ℂ] (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) := + (WithLp.prodContinuousLinearEquiv 2 ℂ H H).symm.toContinuousLinearMap.comp + (if i then ContinuousLinearMap.inr ℂ H H else ContinuousLinearMap.inl ℂ H H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.coordinate (i : Bool) : (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.Double H) →L[ℂ] H := + (if i then ContinuousLinearMap.snd ℂ H H else ContinuousLinearMap.fst ℂ H H).comp + (WithLp.prodContinuousLinearEquiv 2 ℂ H H).toContinuousLinearMap + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.entry (T : H →ₗ.[ℂ] H) (hT : T.IsClosed) (i j : Bool) : H →L[ℂ] H := + (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.coordinate i).comp ((OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.projection T hT).comp (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.inclusion j)) + +end OAI.StronglyRationalVOA.ClosedGraphData + +namespace OAI.StronglyRationalVOA.LocalOperatorAlgebra +open Filter +open scoped ContDiff +variable {H : Type u} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] +open scoped Pointwise + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.LocalOperatorAlgebra.generated (s : Set (H →L[ℂ] H)) : VonNeumannAlgebra H where + toStarSubalgebra := StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) + centralizer_centralizer' := by + change Set.centralizer (Set.centralizer + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : Set (H →L[ℂ] H))) = + (StarSubalgebra.centralizer ℂ (StarSubalgebra.centralizer ℂ s : Set (H →L[ℂ] H)) : Set (H →L[ℂ] H)) + rw [StarSubalgebra.coe_centralizer_centralizer] + rw [Set.centralizer_centralizer_centralizer] + +end OAI.StronglyRationalVOA.LocalOperatorAlgebra + +namespace OAI.StronglyRationalVOA.SmoothCircleFunction +open Filter +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.onCircle (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : AddCircle (2*Real.pi) → ℂ := + f.periodic.lift + +end OAI.StronglyRationalVOA.SmoothCircleFunction + +namespace OAI.StronglyRationalVOA +open Filter +open scoped ContDiff + +structure ProperCircleArc where + left : ℝ + right : ℝ + nonempty' : left < right + nondense' : right < left + 2*Real.pi + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.ProperCircleArc +open Filter +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier (I : OAI.StronglyRationalVOA.ProperCircleArc) : Set (AddCircle (2*Real.pi)) := + (fun t : ℝ => (t : AddCircle (2*Real.pi))) '' Set.Ioo I.left I.right + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.complement (I : OAI.StronglyRationalVOA.ProperCircleArc) : OAI.StronglyRationalVOA.ProperCircleArc where + left := I.right + right := I.left + 2*Real.pi + nonempty' := I.nondense' + nondense' := by linarith [I.nonempty'] + +end OAI.StronglyRationalVOA.ProperCircleArc + +namespace OAI.StronglyRationalVOA.BoundedFlow +open scoped Topology +open Filter +open scoped Topology +open Filter +open scoped Topology +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +local instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.boundedFlowRationalNormedAlgebra : NormedAlgebra ℚ (H →L[ℂ] H) := + .restrictScalars ℚ ℂ (H →L[ℂ] H) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.flow (K : H →L[ℂ] H) (t : ℝ) : H →L[ℂ] H := NormedSpace.exp (t • K) + +end OAI.StronglyRationalVOA.BoundedFlow + +namespace OAI.StronglyRationalVOA +open scoped ContDiff + +structure SmoothCircleLift where + toOrderIso : ℝ ≃o ℝ + smooth : ContDiff ℝ ∞ toOrderIso + inverse_smooth : ContDiff ℝ ∞ toOrderIso.symm + period : ∀ t, toOrderIso (t+2*Real.pi)=toOrderIso t+2*Real.pi + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleLift +open scoped ContDiff + +noncomputable instance : CoeFun OAI.StronglyRationalVOA.SmoothCircleLift (fun _ => ℝ → ℝ) := ⟨fun F => F.toOrderIso⟩ + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := OrderIso.refl ℝ + smooth := contDiff_id + inverse_smooth := contDiff_id + period := fun _ => rfl + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose (F G : OAI.StronglyRationalVOA.SmoothCircleLift) : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := G.toOrderIso.trans F.toOrderIso + smooth := F.smooth.comp G.smooth + inverse_smooth := G.inverse_smooth.comp F.inverse_smooth + period := by intro t; change F (G (t+2*Real.pi))=F (G t)+2*Real.pi; rw [G.period,F.period] + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse (F : OAI.StronglyRationalVOA.SmoothCircleLift) : OAI.StronglyRationalVOA.SmoothCircleLift where + toOrderIso := F.toOrderIso.symm + smooth := F.inverse_smooth + inverse_smooth := F.smooth + period := by + intro t + apply F.toOrderIso.injective + rw [F.toOrderIso.apply_symm_apply,F.period,F.toOrderIso.apply_symm_apply] + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.instGroup : Group OAI.StronglyRationalVOA.SmoothCircleLift := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_ext {F G : OAI.StronglyRationalVOA.SmoothCircleLift} (h : ∀ t, F t=G t) : F=G := by + cases F with + | mk f hf hfi hp => + cases G with + | mk g hg hgi hgp => + have he : f=g := DFunLike.ext _ _ h + subst g + rfl + exact { + mul := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose + one := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity + inv := OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse + npow := @npowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩ + div := fun F G => OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose F + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse G) + zpow := @zpowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.inverse⟩ + (@npowRec OAI.StronglyRationalVOA.SmoothCircleLift + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.identity⟩ + ⟨OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.compose⟩) + mul_assoc F G H := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + one_mul F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + mul_one F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; rfl + inv_mul_cancel F := by apply h_OAI_StronglyRationalVOA_SmoothCircleLift_ext; intro t; exact F.toOrderIso.symm_apply_apply t + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F : OAI.StronglyRationalVOA.SmoothCircleLift) : AddCircle (2*Real.pi) → AddCircle (2*Real.pi) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_circle_periodic (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Function.Periodic (fun t : ℝ => (F t : AddCircle (2*Real.pi))) (2*Real.pi) := by + intro t + change ((F.toOrderIso (t+2*Real.pi) : ℝ) : AddCircle (2*Real.pi)) = + (F.toOrderIso t : AddCircle (2*Real.pi)) + rw [F.period,AddCircle.coe_add] + simp + exact + (h_OAI_StronglyRationalVOA_SmoothCircleLift_circle_periodic F).lift + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleHomeomorph (F : OAI.StronglyRationalVOA.SmoothCircleLift) : + AddCircle (2*Real.pi) ≃ₜ AddCircle (2*Real.pi) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle 1 t)=t := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F * G) t)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle G t)) := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse (F : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F⁻¹ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F t))=t := by + rw [← h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul,inv_mul_cancel,h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one] + have h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Continuous (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F) := by + exact ((AddCircle.continuous_mk' (2*Real.pi)).comp F.smooth.continuous).quotient_liftOn' _ + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + exact { + toFun := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F) + invFun := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F⁻¹) + left_inv := (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse F) + right_inv := by intro t; simpa [h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply, h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply] using (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_inverse F⁻¹ t) + continuous_toFun := (h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle F) + continuous_invFun := (h_OAI_StronglyRationalVOA_SmoothCircleLift_continuous_onCircle F⁻¹) + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction : OAI.StronglyRationalVOA.SmoothCircleLift →* Equiv.Perm (AddCircle (2*Real.pi)) := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one (t : AddCircle (2*Real.pi)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle 1 t)=t := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : AddCircle (2*Real.pi)) : + (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle (F * G) t)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle F (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.onCircle G t)) := by + induction t using QuotientAddGroup.induction_on with + | H t => rfl + exact { + toFun F := (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleHomeomorph F).toEquiv + map_one' := by ext x; exact (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_one x) + map_mul' F G := by ext x; exact (h_OAI_StronglyRationalVOA_SmoothCircleLift_onCircle_mul F G x) + } + +end OAI.StronglyRationalVOA.SmoothCircleLift + +namespace OAI.StronglyRationalVOA +open scoped ContDiff + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.instGroupSmoothCircleDiffeomorphism : Group OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := inferInstanceAs + (Group (OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker)) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA +open UniformSpace + +noncomputable def scalarPhaseSubgroup (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + Subgroup (H ≃ₗᵢ[ℂ] H) where + carrier := {E | ∃ c : ℂ, ‖c‖=1 ∧ ∀ x : H, E x=c • x} + one_mem' := ⟨1,by simp,fun x => (one_smul ℂ x).symm⟩ + mul_mem' := by + rintro E F ⟨c,hc,he⟩ ⟨d,hd,hf⟩ + refine ⟨c*d,by rw [norm_mul,hc,hd,one_mul],?_⟩ + intro x + change E (F x)=(c*d) • x + rw [hf,he,mul_smul] + inv_mem' := by + rintro E ⟨c,hc,he⟩ + have hn : c ≠ 0 := by intro h; rw [h,norm_zero] at hc; norm_num at hc + refine ⟨c⁻¹,by rw [norm_inv,hc,inv_one],?_⟩ + intro x + apply E.injective + change E (E.symm x)=E (c⁻¹ • x) + rw [E.apply_symm_apply,map_smul,he,smul_smul,inv_mul_cancel₀ hn,one_smul] + +noncomputable instance scalarPhaseSubgroup_normal (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + (OAI.StronglyRationalVOA.scalarPhaseSubgroup H).Normal where + conj_mem := by + rintro E ⟨c,hc,he⟩ F + refine ⟨c,hc,?_⟩ + intro x + change F (E (F.symm x))=c • x + rw [he,map_smul,F.apply_symm_apply] + +noncomputable abbrev ProjectiveUnitaryGroup (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] := + (H ≃ₗᵢ[ℂ] H) ⧸ OAI.StronglyRationalVOA.scalarPhaseSubgroup H + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.SmoothCircleLift +open Filter Set +open scoped Topology ContDiff + +noncomputable def jet (F : OAI.StronglyRationalVOA.SmoothCircleLift) (k : ℕ) : C(ℝ,ℝ) := + ⟨iteratedDeriv k F, F.smooth.continuous_iteratedDeriv k + (by exact_mod_cast (le_top : (k : ℕ∞) ≤ ⊤))⟩ + +noncomputable instance : TopologicalSpace OAI.StronglyRationalVOA.SmoothCircleLift := + TopologicalSpace.induced (fun F => OAI.StronglyRationalVOA.SmoothCircleLift.jet F) inferInstance + +end OAI.StronglyRationalVOA.SmoothCircleLift + +namespace OAI.StronglyRationalVOA +open UniformSpace Filter Set +open scoped Topology + +noncomputable instance unitaryStrongTopology (H : Type*) [NormedAddCommGroup H] [InnerProductSpace ℂ H] : + TopologicalSpace (H ≃ₗᵢ[ℂ] H) := + TopologicalSpace.induced (fun E : H ≃ₗᵢ[ℂ] H => (E : H → H)) inferInstance + +noncomputable instance _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.instTopologicalSpaceSmoothCircleDiffeomorphism : TopologicalSpace OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := inferInstanceAs + (TopologicalSpace (OAI.StronglyRationalVOA.SmoothCircleLift ⧸ (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker)) + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CircleMobiusGeometry +open Set +open scoped MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel (M : SL(2,ℝ)) (x y : ℝ) : Prop := + (M 0 0*Real.cos (x/2)+M 0 1*Real.sin (x/2))*Real.sin (y/2)= + (M 1 0*Real.cos (x/2)+M 1 1*Real.sin (x/2))*Real.cos (y/2) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements (M : SL(2,ℝ)) (F : OAI.StronglyRationalVOA.SmoothCircleLift) : Prop := ∀ x, (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel M x ((OAI.StronglyRationalVOA.SmoothCircleLift.toOrderIso F) x)) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts : Subgroup OAI.StronglyRationalVOA.SmoothCircleLift := by + classical + have h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply (t : ℝ) : (1 : OAI.StronglyRationalVOA.SmoothCircleLift) t=t := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply (F G : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : (F*G) t=F (G t) := rfl + have h_OAI_StronglyRationalVOA_SmoothCircleLift_apply_inv_apply (F : OAI.StronglyRationalVOA.SmoothCircleLift) (t : ℝ) : F (F⁻¹ t)=t := F.toOrderIso.apply_symm_apply t + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_inv {M : SL(2,ℝ)} {F : OAI.StronglyRationalVOA.SmoothCircleLift} + (hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M⁻¹ F⁻¹) := by + intro x + have h := hF (F⁻¹ x) + rw [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,(h_OAI_StronglyRationalVOA_SmoothCircleLift_apply_inv_apply F)] at h + simp only [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,Matrix.SpecialLinearGroup.SL2_inv_expl,Matrix.cons_val_zero, + Matrix.cons_val_one,Matrix.cons_val_fin_one] + linear_combination -h + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_one : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements 1 1) := by + intro x + simp [h_OAI_StronglyRationalVOA_SmoothCircleLift_one_apply, OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,mul_comm] + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_collinear_unit {p q c s : ℝ} (hu : c^2+s^2=1) (h : p*s=q*c) : + (p*c+q*s)*c=p ∧ (p*c+q*s)*s=q := by + constructor + · linear_combination p*hu-s*h + · linear_combination q*hu+c*h + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (x : ℝ) : Real.cos x^2+Real.sin x^2=1 := by + nlinarith [Real.sin_sq_add_cos_sq x] + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_mul {M N : SL(2,ℝ)} {F G : OAI.StronglyRationalVOA.SmoothCircleLift} + (hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)) (hG : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements N G)) : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements (M * N) (F * G)) := by + intro x + have hh := hF (G x) + have hg := hG x + obtain ⟨hr1,hr2⟩ := (h_OAI_StronglyRationalVOA_CircleMobiusGeometry_collinear_unit + (h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq + ((OAI.StronglyRationalVOA.SmoothCircleLift.toOrderIso G) x / 2)) + hg) + let r := (N 0 0*Real.cos (x/2)+N 0 1*Real.sin (x/2))*Real.cos (G x/2)+ + (N 1 0*Real.cos (x/2)+N 1 1*Real.sin (x/2))*Real.sin (G x/2) + change r*Real.cos (G x/2)=N 0 0*Real.cos (x/2)+N 0 1*Real.sin (x/2) at hr1 + change r*Real.sin (G x/2)=N 1 0*Real.cos (x/2)+N 1 1*Real.sin (x/2) at hr2 + change (M 0 0*Real.cos (G x/2)+M 0 1*Real.sin (G x/2))*Real.sin (F (G x)/2)= + (M 1 0*Real.cos (G x/2)+M 1 1*Real.sin (G x/2))*Real.cos (F (G x)/2) at hh + simp only [OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Rel,(h_OAI_StronglyRationalVOA_SmoothCircleLift_mul_apply),Matrix.SpecialLinearGroup.coe_mul, + Matrix.mul_apply,Fin.sum_univ_two] + linear_combination r*hh+(M 1 0*Real.cos (F (G x)/2)-M 0 0*Real.sin (F (G x)/2))*hr1+ + (M 1 1*Real.cos (F (G x)/2)-M 0 1*Real.sin (F (G x)/2))*hr2 + exact { + carrier := {F | ∃ M : SL(2,ℝ), (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F)} + one_mem' := ⟨1,h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_one⟩ + mul_mem' := by rintro F G ⟨M,hM⟩ ⟨N,hN⟩; exact ⟨M*N,(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_mul hM hN)⟩ + inv_mem' := by rintro F ⟨M,hM⟩; exact ⟨M⁻¹,(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_implements_inv hM)⟩ + } + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.rotationMatrix (s : ℝ) : SL(2,ℝ) := by + classical + have h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (x : ℝ) : Real.cos x^2+Real.sin x^2=1 := by + nlinarith [Real.sin_sq_add_cos_sq x] + exact + ⟨!![Real.cos (s/2),-Real.sin (s/2);Real.sin (s/2),Real.cos (s/2)],by + simp only [Matrix.det_fin_two_of] + nlinarith [(h_OAI_StronglyRationalVOA_CircleMobiusGeometry_cos_sq_add_sin_sq (s / 2))]⟩ + +noncomputable abbrev _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group := OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts ⧸ ((OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype).ker + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.inclusion : OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group →* OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism := + QuotientGroup.lift ((OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype).ker + ((QuotientGroup.mk' (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker).comp OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts.subtype) (by + intro F hF + exact (QuotientGroup.eq_one_iff _).mpr hF) + +end OAI.StronglyRationalVOA.CircleMobiusGeometry + +namespace OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism +open Set +open scoped Topology MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action : OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism →* Equiv.Perm (AddCircle (2*Real.pi)) := + QuotientGroup.lift (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction).ker (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleLift.circleAction) + (fun _ h => h) + +end OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism + +namespace OAI.StronglyRationalVOA +open Set +open scoped Topology MatrixGroups + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] : OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H → ((H →L[ℂ] H) ≃⋆ₐ[ℂ] (H →L[ℂ] H)) := by + classical + have h_OAI_StronglyRationalVOA_projective_equality_conjugation {H : Type _} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] (E F : H ≃ₗᵢ[ℂ] H) + (h : (QuotientGroup.mk E : OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H)=QuotientGroup.mk F) : + E.conjStarAlgEquiv=F.conjStarAlgEquiv := by + obtain ⟨c,_,hc⟩ := QuotientGroup.eq.mp h + have he (x : H) : F x=c • E x := by + have H := congrArg E (hc x) + change E (E.symm (F x))=E (c • x) at H + simpa only [E.apply_symm_apply,map_smul] using H + ext B x + change E (B (E.symm x))=F (B (F.symm x)) + have hi : E.symm x=c • F.symm x := by + apply E.injective + rw [E.apply_symm_apply,map_smul,← he,F.apply_symm_apply] + rw [hi,map_smul,map_smul,← he] + exact + Quotient.lift (fun E : H ≃ₗᵢ[ℂ] H => E.conjStarAlgEquiv) (by + intro E F h + exact (h_OAI_StronglyRationalVOA_projective_equality_conjugation E F (Quotient.sound h))) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.globalObservableAlgebra {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) : + Subalgebra ℂ (H →L[ℂ] H) := + Algebra.adjoin ℂ (⋃ I, (N I : Set (H →L[ℂ] H))) + +noncomputable def _root_.OAI.MinimalVertex.Code.StronglyRationalVOA.globalCyclicSpace {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] + [CompleteSpace H] (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) (Ω : H) : Submodule ℂ H := + (Submodule.span ℂ {x | ∃ B ∈ (OAI.MinimalVertex.Code.StronglyRationalVOA.globalObservableAlgebra N), x=B Ω}).topologicalClosure + +end OAI.StronglyRationalVOA + +namespace OAI.StronglyRationalVOA.CFTTypeVOA +variable {V : Type u} [AddCommGroup V] [Module ℂ V] (A : CFTTypeVOA V) + +noncomputable abbrev GradedDual := DirectSum ℕ (fun d => Module.Dual ℂ (A.grade d)) + +noncomputable def gradedDualPairing (φ : A.GradedDual) (b : V) : ℂ := by + classical + exact φ.sum (fun d f => f (A.gradingEquiv b d)) + +noncomputable def IsSelfContragredient : Prop := + ∃ e : V ≃ₗ[ℂ] A.GradedDual, + ∀ d : ℕ, ∀ a ∈ A.grade d, ∀ n : ℤ, ∀ b c : V, + A.gradedDualPairing (e (OAI.StronglyRationalVOA.mode A.fields a n b)) c = + ((-1 : ℂ)^d) * ∑ j ∈ Finset.range (d+1), ((j.factorial : ℂ)⁻¹) * + A.gradedDualPairing (e b) + (OAI.StronglyRationalVOA.mode A.fields ((A.virasoroMode 1 ^ j) a) (2*(d:ℤ)-j-n-2) c) + +noncomputable def IsStronglyRational : Prop := + A.IsSelfContragredient ∧ A.IsRational.{u,v} ∧ A.toVertexAlgebra.C2Cofinite + +end OAI.StronglyRationalVOA.CFTTypeVOA + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + {A : CFTTypeVOA V} + +noncomputable def smearedMap (A : OAI.StronglyRationalVOA.CFTTypeVOA V) (a : V) (d : ℕ) (_ha : A.PolynomialEnergyBound a) + (f : ℤ → ℂ) (_hf : OAI.StronglyRationalVOA.RapidCoefficients f) : V →ₗ[ℂ] Completion V := by + classical + let family : ℤ → (V →ₗ[ℂ] Completion V) := fun m => + f m • (Completion.toComplₗᵢ : V →ₗᵢ[ℂ] Completion V).toLinearMap.comp + (A.physicalMode a d m) + exact if h : ∀ v, Summable (fun m => family m v) then + SummableLinearFamily.tsumMap family h + else 0 + +noncomputable def smoothSmearedField (_U : A.UnitaryStructure) (_hc : A.toVertexAlgebra.C2Cofinite) + (a : V) (d : ℕ) (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : Completion V →ₗ.[ℂ] Completion V := by + classical + exact if h : A.PolynomialEnergyBounds ∧ OAI.StronglyRationalVOA.RapidCoefficients (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient f) then + (OAI.MinimalVertex.Code.StronglyRationalVOA.HilbertCore.operator + (OAI.MinimalVertex.smearedMap A a d (And.left h a) (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.coefficient f) + (And.right h))) + else 0 + +noncomputable def closedSmoothField (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (a : V) (d : ℕ) (f : OAI.StronglyRationalVOA.SmoothCircleFunction) : Completion V →ₗ.[ℂ] Completion V := + (OAI.MinimalVertex.smoothSmearedField U hc a d f).closure + +noncomputable def localGraphData (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (O : Set (AddCircle (2*Real.pi))) : Set (Completion V →L[ℂ] Completion V) := + {x | ∃ (a : V) (d : ℕ), a ∈ A.grade d ∧ ∃ (f : OAI.StronglyRationalVOA.SmoothCircleFunction), + tsupport (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleFunction.onCircle f) ⊆ O ∧ ∃ (h : (OAI.MinimalVertex.closedSmoothField U hc a d f).IsClosed), + ∃ i j : Bool, x = (OAI.MinimalVertex.Code.StronglyRationalVOA.ClosedGraphData.entry (OAI.MinimalVertex.closedSmoothField U hc a d f) h i j)} + +noncomputable def localAlgebra (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (O : Set (AddCircle (2*Real.pi))) : VonNeumannAlgebra (Completion V) := + (OAI.MinimalVertex.Code.StronglyRationalVOA.LocalOperatorAlgebra.generated (OAI.MinimalVertex.localGraphData U hc O)) + +noncomputable def intervalAlgebra (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) + (I : OAI.StronglyRationalVOA.ProperCircleArc) : VonNeumannAlgebra (Completion V) := + OAI.MinimalVertex.localAlgebra U hc (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) + +noncomputable def CKLWStrongLocal (U : A.UnitaryStructure) (hc : A.toVertexAlgebra.C2Cofinite) : Prop := + (∀ a : V, A.PolynomialEnergyBound a) ∧ + ∀ I : OAI.StronglyRationalVOA.ProperCircleArc, OAI.MinimalVertex.intervalAlgebra U hc I ≤ + (OAI.MinimalVertex.intervalAlgebra U hc (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.complement I)).commutant + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + +noncomputable def resolvent (T : H →ₗ.[ℂ] H) (_hs : IsSelfAdjoint T) (z : ℂ) (_hz : 1 ≤ |z.im|) : + H →L[ℂ] H := by + classical + exact if h : ∃ R : H →L[ℂ] H, ∀ y, (R y, y + z • R y) ∈ T.graph then h.choose + else 0 + +noncomputable def boundedGenerator (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) + (r : ℝ) (hr : 1 ≤ r) : H →L[ℂ] H := + ((r : ℂ)^2/2) • + (OAI.MinimalVertex.resolvent T hs ((r : ℂ)*Complex.I) (by simpa [abs_of_nonneg (by linarith : 0 ≤ r)] using hr) + + OAI.MinimalVertex.resolvent T hs (-((r : ℂ)*Complex.I)) (by simpa [abs_of_nonneg (by linarith : 0 ≤ r)] using hr)) + +noncomputable def approximatingFlow (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) (n : ℕ) (t : ℝ) : H →L[ℂ] H := + (OAI.MinimalVertex.Code.StronglyRationalVOA.BoundedFlow.flow + (Complex.I • OAI.MinimalVertex.boundedGenerator T hs (↑n + 1) (le_add_of_nonneg_left (Nat.cast_nonneg n))) t) + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA + +noncomputable def flow {H : Type*} [NormedAddCommGroup H] [InnerProductSpace ℂ H] [CompleteSpace H] + (T : H →ₗ.[ℂ] H) (hs : IsSelfAdjoint T) (t : ℝ) : H →L[ℂ] H := by + classical + exact if h : ∃ L : H →L[ℂ] H, ∀ x, + Tendsto (fun n => OAI.MinimalVertex.approximatingFlow T hs n t x) atTop (𝓝 (L x)) then + h.choose + else 0 + +noncomputable def projectiveStandardAction : PSL(2,ℝ) →* (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group) := by + classical + exact if h : ∃ L : PSL(2,ℝ) →* (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Group), + ∀ M : SL(2,ℝ), ∃ F : OAI.StronglyRationalVOA.SmoothCircleLift, ∃ hF : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.Implements M F), + L (QuotientGroup.mk M) = + QuotientGroup.mk (⟨F, M, hF⟩ : (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.lifts)) then h.choose + else 1 + +structure IrreducibleConformalNetStructure {H : Type*} [NormedAddCommGroup H] + [InnerProductSpace ℂ H] [CompleteSpace H] + (N : OAI.StronglyRationalVOA.ProperCircleArc → VonNeumannAlgebra H) where + separable : TopologicalSpace.SeparableSpace H + carrier_congr : ∀ I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I)=(OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I=N J + isotony : ∀ I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) ⊆ (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I ≤ N J + locality : ∀ I J, Disjoint (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J) → N I ≤ (N J).commutant + mobius : PSL(2,ℝ) →* (H ≃ₗᵢ[ℂ] H) + mobius_continuous : Continuous mobius + diffeomorphism : OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism →* OAI.StronglyRationalVOA.ProjectiveUnitaryGroup H + diffeomorphism_continuous : Continuous diffeomorphism + extends_mobius : ∀ F, diffeomorphism ((OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.inclusion) (OAI.MinimalVertex.projectiveStandardAction F))=QuotientGroup.mk (mobius F) + covariance : ∀ F I J, (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier J)=(OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action) F '' (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I) → + ∀ B : H →L[ℂ] H, OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation (diffeomorphism F) B ∈ N J ↔ B ∈ N I + local_action : ∀ F I, (∀ x ∈ (OAI.MinimalVertex.Code.StronglyRationalVOA.ProperCircleArc.carrier I), (OAI.MinimalVertex.Code.StronglyRationalVOA.SmoothCircleDiffeomorphism.action) F x=x) → + ∀ B ∈ N I, OAI.MinimalVertex.Code.StronglyRationalVOA.projectiveConjugation (diffeomorphism F) B=B + vacuum : H + vacuum_norm : ‖vacuum‖=1 + vacuum_invariant : ∀ F, mobius F vacuum=vacuum + vacuum_unique : ∀ x : H, (∀ F, mobius F x=x) → ∃ c : ℂ, x=c • vacuum + vacuum_cyclic : (OAI.MinimalVertex.Code.StronglyRationalVOA.globalCyclicSpace N vacuum)=⊤ + hamiltonian : H →ₗ.[ℂ] H + hamiltonian_selfAdjoint : IsSelfAdjoint hamiltonian + positive_energy : ∀ x y, (x,y) ∈ hamiltonian.graph → 0 ≤ (inner ℂ x y).re + rotation_flow : ∀ t : ℝ, + (mobius (QuotientGroup.mk (OAI.MinimalVertex.Code.StronglyRationalVOA.CircleMobiusGeometry.rotationMatrix t))).toLinearIsometry.toContinuousLinearMap= + OAI.MinimalVertex.flow hamiltonian hamiltonian_selfAdjoint t + irreducible : ∀ Q : H →L[ℂ] H, (∀ I, Q ∈ (N I).commutant) → + ∃ c : ℂ, Q=c • (1 : H →L[ℂ] H) + +end OAI.MinimalVertex + +namespace OAI.MinimalVertex +open Filter Set UniformSpace +open scoped Topology MatrixGroups +open StronglyRationalVOA +variable {V : Type u} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + {A : CFTTypeVOA V} (U : A.UnitaryStructure) + +theorem main (_hSimple : A.toVertexAlgebra.IsSimple) + (hSR : A.IsStronglyRational.{u,v}) : + A.PolynomialEnergyBounds ∧ OAI.MinimalVertex.CKLWStrongLocal U hSR.2.2 ∧ + Nonempty (OAI.MinimalVertex.IrreducibleConformalNetStructure (OAI.MinimalVertex.intervalAlgebra U hSR.2.2)) := by + sorry + +end OAI.MinimalVertex + +end diff --git a/tasks/vertex-algebra-net/tests/grade.py b/tasks/vertex-algebra-net/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/vertex-algebra-net/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/vertex-algebra-net/tests/task.json b/tasks/vertex-algebra-net/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..15d27b4c6417d3dc8570cf402ae3d8f5b8db9041 --- /dev/null +++ b/tasks/vertex-algebra-net/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "VertexAlgebraNet", + "comparator": { + "theorem_names": [ + "OAI.MinimalVertex.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12071 +} \ No newline at end of file diff --git a/tasks/vertex-algebra-net/tests/test.sh b/tasks/vertex-algebra-net/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/vertex-algebra-net/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/vertex-cover/environment/Dockerfile b/tasks/vertex-cover/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/vertex-cover/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/vertex-cover/environment/fetch_mathlib.sh b/tasks/vertex-cover/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/vertex-cover/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/vertex-cover/environment/lake-manifest.json b/tasks/vertex-cover/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/vertex-cover/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/vertex-cover/environment/lakefile.lean b/tasks/vertex-cover/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/vertex-cover/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/vertex-cover/environment/lean_setup.sh b/tasks/vertex-cover/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/vertex-cover/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/vertex-cover/environment/pack_submission.py b/tasks/vertex-cover/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/vertex-cover/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/vertex-cover/instruction.md b/tasks/vertex-cover/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..c3313663e9392e17b6c3eb5b2d155c4f46f61d3d --- /dev/null +++ b/tasks/vertex-cover/instruction.md @@ -0,0 +1,205 @@ +# openai/math challenge `VertexCover` (family 102) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 102 of the release, *The Unique Games Conjecture and optimal approximation thresholds* +(Theoretical computer science). The family as a whole: Proves Khot's Unique Games Conjecture. Independent direct reductions also establish NP-hardness, on unweighted graphs, of approximation beyond the Goemans–Williamson ratio for Max-Cut, below factor two for Vertex Cover, and within any fixed constant factor for Min-UnCut and directed feedback vertex set. These direct proofs use established PCP and Label Cover hardness results. + +The challenge is `VertexCover`, also at `/opt/openai-math/challenges/VertexCover.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace UniqueGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end UniqueGames.BinaryFormula + +namespace UniqueGames.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _fuel + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end UniqueGames.BinaryEncoding + +namespace VertexCover + +def ThreeSAT (input : List Bool) : Prop := + ∃ formula, UniqueGames.BinaryEncoding.decodeFormula input = some formula ∧ + formula.Satisfiable + +structure ExplicitGraph where + n : ℕ + edges : List (Fin n × Fin n) + increasing : ∀ e ∈ edges, e.1 < e.2 + nodup : edges.Nodup + +namespace ExplicitGraph + +def Cover (G : ExplicitGraph) (S : Finset (Fin G.n)) : Prop := + ∀ e ∈ G.edges, e.1 ∈ S ∨ e.2 ∈ S + +instance (G : ExplicitGraph) (S : Finset (Fin G.n)) : Decidable (G.Cover S) := + inferInstanceAs (Decidable (∀ e ∈ G.edges, e.1 ∈ S ∨ e.2 ∈ S)) + +noncomputable def coverNumber (G : ExplicitGraph) : ℕ := + Nat.find (show ∃ k : ℕ, ∃ S : Finset (Fin G.n), G.Cover S ∧ S.card = k from + ⟨G.n, Finset.univ, by simp [Cover], by simp⟩) + +def bits (G : ExplicitGraph) : List Bool := + let names := [G.n] ++ List.range G.n ++ [G.edges.length] ++ + G.edges.flatMap (fun e => [e.1.val, e.2.val]) + names.flatMap UniqueGames.BinaryEncoding.nameBits + +end ExplicitGraph + +def FiniteAlphabet (M : Turing.FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +structure GapReduction (m : ℕ) where + construct : List Bool → ExplicitGraph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + ExplicitGraph.bits construct + finiteAlphabet : FiniteAlphabet computation.tm + completeness : ∀ input, ThreeSAT input → + ((construct input).coverNumber : ℝ) < + (1 / 2 + 1 / (m : ℝ)) * (construct input).n + soundness : ∀ input, ¬ ThreeSAT input → + (1 - 1 / (m : ℝ)) * (construct input).n < + ((construct input).coverNumber : ℝ) + +def natListBits (L : List ℕ) : List Bool := + (L.length :: L).flatMap UniqueGames.BinaryEncoding.nameBits + +structure Approximation (α : ℝ) where + run : ExplicitGraph → List ℕ + computation : Turing.TM2ComputableInPolyTime ExplicitGraph.bits natListBits run + finiteAlphabet : FiniteAlphabet computation.tm + nodup : ∀ G, (run G).Nodup + vertices : ∀ G, ∀ v ∈ run G, v < G.n + covers : ∀ G, ∀ e ∈ G.edges, e.1.val ∈ run G ∨ e.2.val ∈ run G + quality : ∀ G, ((run G).length : ℝ) ≤ α * (G.coverNumber : ℝ) + +structure ThreeSATDecision where + run : List Bool → Bool + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + (fun b : Bool => [b]) run + finiteAlphabet : FiniteAlphabet computation.tm + correct : ∀ input, run input = true ↔ ThreeSAT input + +theorem explicit_cover_gap (m : ℕ) (hm : 4 ≤ m) : Nonempty (GapReduction m) := by + sorry + +theorem every_fixed_factor_below_two (α : ℝ) (hα : 1 ≤ α) (hα2 : α < 2) + (algorithm : Approximation α) : Nonempty ThreeSATDecision := by + sorry + +end VertexCover + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/VertexCover.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorems `OAI.VertexCover.explicit_cover_gap`, `OAI.VertexCover.every_fixed_factor_below_two` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/vertex-cover/solution/closure.txt b/tasks/vertex-cover/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..81664da10cb292efb7c6b5bfbfcc3e1ebc2f3bbb --- /dev/null +++ b/tasks/vertex-cover/solution/closure.txt @@ -0,0 +1,351 @@ +OAI.Computability.VertexCover.Analysis.AeRegular +OAI.Computability.VertexCover.Analysis.BaseReductionCoherent +OAI.Computability.VertexCover.Analysis.BatchFunctionOwnLipschitz +OAI.Computability.VertexCover.Analysis.BatchGradientForm +OAI.Computability.VertexCover.Analysis.BlockLawAc +OAI.Computability.VertexCover.Analysis.BlockLawNegInvariant +OAI.Computability.VertexCover.Analysis.CanonicalGradientInvariant +OAI.Computability.VertexCover.Analysis.CanonicalGradientValid +OAI.Computability.VertexCover.Analysis.DenseHighFraction +OAI.Computability.VertexCover.Analysis.DenseSeparatorData +OAI.Computability.VertexCover.Analysis.DistanceMinusSelect +OAI.Computability.VertexCover.Analysis.ErasedSeedSeparatorAverage +OAI.Computability.VertexCover.Analysis.FiniteMeanConditionBest +OAI.Computability.VertexCover.Analysis.GraphComplete +OAI.Computability.VertexCover.Analysis.GraphCompleteness +OAI.Computability.VertexCover.Analysis.GridCentralCard +OAI.Computability.VertexCover.Analysis.IndependentSecondMomentLower +OAI.Computability.VertexCover.Analysis.IntegralUpdate +OAI.Computability.VertexCover.Analysis.LawNegInvariant +OAI.Computability.VertexCover.Analysis.ListMassHitMaximum +OAI.Computability.VertexCover.Analysis.MidpointGridTail +OAI.Computability.VertexCover.Analysis.OppositePairSeparatorResidual +OAI.Computability.VertexCover.Analysis.OwnFiberTower +OAI.Computability.VertexCover.Analysis.OwnGradientMeasurable +OAI.Computability.VertexCover.Analysis.OwnGradientUnsupported +OAI.Computability.VertexCover.Analysis.OwnListEnergy +OAI.Computability.VertexCover.Analysis.OwnMeanPartialAe +OAI.Computability.VertexCover.Analysis.OwnPrivateListsDecoding +OAI.Computability.VertexCover.Analysis.OwnTotalEnergyNo +OAI.Computability.VertexCover.Analysis.OwnTotalVarianceNo +OAI.Computability.VertexCover.Analysis.Poincare +OAI.Computability.VertexCover.Analysis.PoincareOne +OAI.Computability.VertexCover.Analysis.PowerValueRepetition +OAI.Computability.VertexCover.Analysis.PrivateMassSumHits +OAI.Computability.VertexCover.Analysis.Restriction +OAI.Computability.VertexCover.Analysis.RestrictionSum +OAI.Computability.VertexCover.Analysis.RoundingError +OAI.Computability.VertexCover.Analysis.SeedEnergyBudget +OAI.Computability.VertexCover.Analysis.SelectedIntegralAbs +OAI.Computability.VertexCover.Analysis.SeparatorBoundCube +OAI.Computability.VertexCover.Analysis.SeparatorRoundingErrorAe +OAI.Computability.VertexCover.Analysis.SignAtom +OAI.Computability.VertexCover.Analysis.StarEnergyBudget +OAI.Computability.VertexCover.Analysis.StarMeanContinuous +OAI.Computability.VertexCover.Analysis.ThresholdListEnergy +OAI.Computability.VertexCover.Analysis.VarianceCoordinateSum +OAI.Computability.VertexCover.Analysis.VariancePi +OAI.Computability.VertexCover.Analysis.VarianceProduct +OAI.Computability.VertexCover.Analysis.WeightEnergyBudget +OAI.Computability.VertexCover.Analysis.ZeroMemIncidenceHull +OAI.Computability.VertexCover.Basic +OAI.Computability.VertexCover.Encoding.BinaryEncoding +OAI.Computability.VertexCover.Encoding.BinaryFormula +OAI.Computability.VertexCover.Encoding.FinalCNFPattern +OAI.Computability.VertexCover.Encoding.GameEncoding +OAI.Computability.VertexCover.Encoding.MachineComposition +OAI.Computability.VertexCover.Encoding.MachineEmbedding +OAI.Computability.VertexCover.Encoding.Runtime +OAI.Computability.VertexCover.Encoding.Serialization +OAI.Computability.VertexCover.Fourier.Decoder +OAI.Computability.VertexCover.Fourier.EmptyContext +OAI.Computability.VertexCover.Fourier.FoldedEquation +OAI.Computability.VertexCover.Fourier.Folding +OAI.Computability.VertexCover.Fourier.FourierResponse +OAI.Computability.VertexCover.Fourier.GameDecoder +OAI.Computability.VertexCover.Fourier.HonestTest +OAI.Computability.VertexCover.Fourier.SourceBounds +OAI.Computability.VertexCover.Fourier.SourceContexts +OAI.Computability.VertexCover.Fourier.SourceGame +OAI.Computability.VertexCover.Fourier.SourceGap +OAI.Computability.VertexCover.Fourier.SourceHonest +OAI.Computability.VertexCover.Fourier.SourceNonempty +OAI.Computability.VertexCover.Fourier.SourceOccurrences +OAI.Computability.VertexCover.Fourier.SourceSoundness +OAI.Computability.VertexCover.Fourier.SourceTape +OAI.Computability.VertexCover.Fourier.ThreeBitTest +OAI.Computability.VertexCover.Fourier.Walsh +OAI.Computability.VertexCover.Games.Basic +OAI.Computability.VertexCover.Games.Conditioning +OAI.Computability.VertexCover.Games.KernelSampling +OAI.Computability.VertexCover.Games.Mixture +OAI.Computability.VertexCover.Games.Reindexing +OAI.Computability.VertexCover.Games.Sampling +OAI.Computability.VertexCover.Games.Stochastic +OAI.Computability.VertexCover.Games.TotalVariation +OAI.Computability.VertexCover.Games.Value +OAI.Computability.VertexCover.Information.ChainRule +OAI.Computability.VertexCover.Information.Conditionals +OAI.Computability.VertexCover.Information.Finite +OAI.Computability.VertexCover.Information.GamesAdapter +OAI.Computability.VertexCover.Information.Kernels +OAI.Computability.VertexCover.Information.LogSum +OAI.Computability.VertexCover.Information.Pinsker +OAI.Computability.VertexCover.Information.SideInformation +OAI.Computability.VertexCover.Information.Tensorization +OAI.Computability.VertexCover.Machines.Address +OAI.Computability.VertexCover.Machines.Alphabet +OAI.Computability.VertexCover.Machines.AlphabetCorrect +OAI.Computability.VertexCover.Machines.AlphabetFrame +OAI.Computability.VertexCover.Machines.AlphabetRow +OAI.Computability.VertexCover.Machines.Approximation +OAI.Computability.VertexCover.Machines.BinaryOutput +OAI.Computability.VertexCover.Machines.BoundedBinary +OAI.Computability.VertexCover.Machines.Cardinal +OAI.Computability.VertexCover.Machines.Cloud +OAI.Computability.VertexCover.Machines.CloudFamily +OAI.Computability.VertexCover.Machines.CloudIndex +OAI.Computability.VertexCover.Machines.Codec +OAI.Computability.VertexCover.Machines.Composition +OAI.Computability.VertexCover.Machines.DenseParse +OAI.Computability.VertexCover.Machines.DescriptorMath +OAI.Computability.VertexCover.Machines.ExpanderBound +OAI.Computability.VertexCover.Machines.ExpanderCorrect +OAI.Computability.VertexCover.Machines.ExpanderFamily +OAI.Computability.VertexCover.Machines.ExpanderStep +OAI.Computability.VertexCover.Machines.FinCode +OAI.Computability.VertexCover.Machines.FinalCNF +OAI.Computability.VertexCover.Machines.FinalCNFBase +OAI.Computability.VertexCover.Machines.FinalCNFCorrect +OAI.Computability.VertexCover.Machines.FiniteFunction +OAI.Computability.VertexCover.Machines.FiniteMemory +OAI.Computability.VertexCover.Machines.FixedOps +OAI.Computability.VertexCover.Machines.Generic +OAI.Computability.VertexCover.Machines.GraphConstraint +OAI.Computability.VertexCover.Machines.GraphDescriptor +OAI.Computability.VertexCover.Machines.GraphFrame +OAI.Computability.VertexCover.Machines.GraphNumber +OAI.Computability.VertexCover.Machines.GraphOutput +OAI.Computability.VertexCover.Machines.InitialCorrect +OAI.Computability.VertexCover.Machines.InitialTable +OAI.Computability.VertexCover.Machines.Iteration +OAI.Computability.VertexCover.Machines.LCData +OAI.Computability.VertexCover.Machines.LCNumber +OAI.Computability.VertexCover.Machines.Lazy +OAI.Computability.VertexCover.Machines.ListFilter +OAI.Computability.VertexCover.Machines.ListGrowing +OAI.Computability.VertexCover.Machines.ListIndex +OAI.Computability.VertexCover.Machines.ListMore +OAI.Computability.VertexCover.Machines.ListNat +OAI.Computability.VertexCover.Machines.ListParam +OAI.Computability.VertexCover.Machines.ListSearch +OAI.Computability.VertexCover.Machines.Lists +OAI.Computability.VertexCover.Machines.Loop +OAI.Computability.VertexCover.Machines.LoopFrom +OAI.Computability.VertexCover.Machines.NatDiv +OAI.Computability.VertexCover.Machines.NatLog +OAI.Computability.VertexCover.Machines.NatPath +OAI.Computability.VertexCover.Machines.NatWalk +OAI.Computability.VertexCover.Machines.Naturals +OAI.Computability.VertexCover.Machines.NormRepresentation +OAI.Computability.VertexCover.Machines.NumberedGraph +OAI.Computability.VertexCover.Machines.Option +OAI.Computability.VertexCover.Machines.Overlay +OAI.Computability.VertexCover.Machines.Padding +OAI.Computability.VertexCover.Machines.Pair +OAI.Computability.VertexCover.Machines.ParseClause +OAI.Computability.VertexCover.Machines.ParseFormula +OAI.Computability.VertexCover.Machines.ParseFrame +OAI.Computability.VertexCover.Machines.ParseName +OAI.Computability.VertexCover.Machines.ParseSize +OAI.Computability.VertexCover.Machines.PortBuilder +OAI.Computability.VertexCover.Machines.PortCode +OAI.Computability.VertexCover.Machines.Power +OAI.Computability.VertexCover.Machines.PowerLC +OAI.Computability.VertexCover.Machines.PowerRow +OAI.Computability.VertexCover.Machines.Preprocess +OAI.Computability.VertexCover.Machines.Primitive +OAI.Computability.VertexCover.Machines.Primitives +OAI.Computability.VertexCover.Machines.Profile +OAI.Computability.VertexCover.Machines.ProfileCompat +OAI.Computability.VertexCover.Machines.ProfileSlot +OAI.Computability.VertexCover.Machines.Regular +OAI.Computability.VertexCover.Machines.RegularRow +OAI.Computability.VertexCover.Machines.Round +OAI.Computability.VertexCover.Machines.Serialization +OAI.Computability.VertexCover.Machines.SimpleLC +OAI.Computability.VertexCover.Machines.TableBase +OAI.Computability.VertexCover.Machines.TableCodeBound +OAI.Computability.VertexCover.Machines.Walk +OAI.Computability.VertexCover.Main +OAI.Computability.VertexCover.PCP.AlphabetGraph +OAI.Computability.VertexCover.PCP.AlphabetGraphBounds +OAI.Computability.VertexCover.PCP.AlphabetReduction +OAI.Computability.VertexCover.PCP.AlphabetRetraction +OAI.Computability.VertexCover.PCP.AlphabetTableBounds +OAI.Computability.VertexCover.PCP.AlphabetTableEnumeration +OAI.Computability.VertexCover.PCP.AlphabetTableQueries +OAI.Computability.VertexCover.PCP.AlphabetTableRelations +OAI.Computability.VertexCover.PCP.AlphabetTableTable +OAI.Computability.VertexCover.PCP.AmplificationIteration +OAI.Computability.VertexCover.PCP.AmplificationRound +OAI.Computability.VertexCover.PCP.AssignmentTester +OAI.Computability.VertexCover.PCP.BinaryCoordinates +OAI.Computability.VertexCover.PCP.CayleySampling +OAI.Computability.VertexCover.PCP.CayleySpectral +OAI.Computability.VertexCover.PCP.CayleyTailCount +OAI.Computability.VertexCover.PCP.ClauseVerifier +OAI.Computability.VertexCover.PCP.CloudPadding +OAI.Computability.VertexCover.PCP.CloudRounding +OAI.Computability.VertexCover.PCP.CodeComposition +OAI.Computability.VertexCover.PCP.ConstraintGraph +OAI.Computability.VertexCover.PCP.DegreeReplacement +OAI.Computability.VertexCover.PCP.ExpanderFamily +OAI.Computability.VertexCover.PCP.ExpanderTables +OAI.Computability.VertexCover.PCP.Expanders +OAI.Computability.VertexCover.PCP.FinalBooleanVerifier +OAI.Computability.VertexCover.PCP.FinalConstants +OAI.Computability.VertexCover.PCP.FinalTableFormula +OAI.Computability.VertexCover.PCP.FiniteGraph +OAI.Computability.VertexCover.PCP.GenericGraphTables +OAI.Computability.VertexCover.PCP.GraphGap +OAI.Computability.VertexCover.PCP.GraphTableComplexity +OAI.Computability.VertexCover.PCP.GraphTables +OAI.Computability.VertexCover.PCP.GraphTransport +OAI.Computability.VertexCover.PCP.InitialGraph +OAI.Computability.VertexCover.PCP.LazyConstraint +OAI.Computability.VertexCover.PCP.LazySmoothing +OAI.Computability.VertexCover.PCP.LazySpectral +OAI.Computability.VertexCover.PCP.NameCompaction +OAI.Computability.VertexCover.PCP.Overlay +OAI.Computability.VertexCover.PCP.PCPIteration +OAI.Computability.VertexCover.PCP.PortTables +OAI.Computability.VertexCover.PCP.PoweringAddresses +OAI.Computability.VertexCover.PCP.PoweringCounting +OAI.Computability.VertexCover.PCP.PoweringDecoding +OAI.Computability.VertexCover.PCP.PoweringEnumeration +OAI.Computability.VertexCover.PCP.PoweringFinalConstants +OAI.Computability.VertexCover.PCP.PoweringGap +OAI.Computability.VertexCover.PCP.PoweringLabels +OAI.Computability.VertexCover.PCP.PoweringLazy +OAI.Computability.VertexCover.PCP.PoweringMoment +OAI.Computability.VertexCover.PCP.PoweringMomentBound +OAI.Computability.VertexCover.PCP.PoweringNumeric +OAI.Computability.VertexCover.PCP.PoweringOpinionTables +OAI.Computability.VertexCover.PCP.PoweringOpinions +OAI.Computability.VertexCover.PCP.PoweringPortReindex +OAI.Computability.VertexCover.PCP.PoweringReach +OAI.Computability.VertexCover.PCP.PoweringReturn +OAI.Computability.VertexCover.PCP.PoweringSoundness +OAI.Computability.VertexCover.PCP.PoweringTableSemantics +OAI.Computability.VertexCover.PCP.PoweringTables +OAI.Computability.VertexCover.PCP.PoweringTest +OAI.Computability.VertexCover.PCP.PoweringWalks +OAI.Computability.VertexCover.PCP.PoweringWitness +OAI.Computability.VertexCover.PCP.Preprocessing +OAI.Computability.VertexCover.PCP.PreprocessingCloudIndex +OAI.Computability.VertexCover.PCP.PreprocessingGuarantees +OAI.Computability.VertexCover.PCP.PreprocessingLevels +OAI.Computability.VertexCover.PCP.PreprocessingOverlayTables +OAI.Computability.VertexCover.PCP.PreprocessingPaddingTables +OAI.Computability.VertexCover.PCP.PreprocessingRegularSoundness +OAI.Computability.VertexCover.PCP.PreprocessingRegularTables +OAI.Computability.VertexCover.PCP.PreprocessingTableSpectral +OAI.Computability.VertexCover.PCP.PreprocessingTables +OAI.Computability.VertexCover.PCP.QueryIncidence +OAI.Computability.VertexCover.PCP.RawInitialMachineBudget +OAI.Computability.VertexCover.PCP.RawInitialTables +OAI.Computability.VertexCover.PCP.Regularization +OAI.Computability.VertexCover.PCP.RepetitionUpper +OAI.Computability.VertexCover.PCP.RoundGap +OAI.Computability.VertexCover.PCP.RoundSize +OAI.Computability.VertexCover.PCP.RoundTableGap +OAI.Computability.VertexCover.PCP.RoundTables +OAI.Computability.VertexCover.PCP.SourceParameters +OAI.Computability.VertexCover.PCP.SpectralCut +OAI.Computability.VertexCover.PCP.SpectralReturn +OAI.Computability.VertexCover.PCP.TableGapReduction +OAI.Computability.VertexCover.PCP.TableIteration +OAI.Computability.VertexCover.PCP.Target +OAI.Computability.VertexCover.PCP.UniformRestriction +OAI.Computability.VertexCover.PCP.VerifierToCNF +OAI.Computability.VertexCover.PCP.VertexPadding +OAI.Computability.VertexCover.PCP.ZigzagGraphs +OAI.Computability.VertexCover.PCP.ZigzagSpectral +OAI.Computability.VertexCover.Reduction.AverageCommute +OAI.Computability.VertexCover.Reduction.BatchesTripleSum +OAI.Computability.VertexCover.Reduction.CloneGap +OAI.Computability.VertexCover.Reduction.CompatibleSingleton +OAI.Computability.VertexCover.Reduction.ConditionNested +OAI.Computability.VertexCover.Reduction.CoordinateProductInvariant +OAI.Computability.VertexCover.Reduction.DecodingUpperThreeHalves +OAI.Computability.VertexCover.Reduction.DenseEncodingBound +OAI.Computability.VertexCover.Reduction.FiniteMeanUnionBound +OAI.Computability.VertexCover.Reduction.FiniteNoise +OAI.Computability.VertexCover.Reduction.GraphSoundness +OAI.Computability.VertexCover.Reduction.GraphSoundness2 +OAI.Computability.VertexCover.Reduction.GridBudget +OAI.Computability.VertexCover.Reduction.HighVectorsSeparated +OAI.Computability.VertexCover.Reduction.HonestLargeSumIndependent +OAI.Computability.VertexCover.Reduction.HonestSelectionCompatible +OAI.Computability.VertexCover.Reduction.IncrementNorm +OAI.Computability.VertexCover.Reduction.IntegralCoe +OAI.Computability.VertexCover.Reduction.ListHitMaximum +OAI.Computability.VertexCover.Reduction.NormAttainedSupport +OAI.Computability.VertexCover.Reduction.PairEventMean +OAI.Computability.VertexCover.Reduction.PairHitsProbability +OAI.Computability.VertexCover.Reduction.PairSeedFiberCard +OAI.Computability.VertexCover.Reduction.PrivatePairProjectionRight +OAI.Computability.VertexCover.Reduction.PrivateProjectionBatchLower +OAI.Computability.VertexCover.Reduction.PrivateProjectionCoordinateVariance +OAI.Computability.VertexCover.Reduction.PrivateProjectionGroupLower +OAI.Computability.VertexCover.Reduction.PrivateProjectionSurvival +OAI.Computability.VertexCover.Reduction.PrivateTotalEnergyLaw +OAI.Computability.VertexCover.Reduction.ReductionSound +OAI.Computability.VertexCover.Reduction.RejectionCount +OAI.Computability.VertexCover.Reduction.RestrictionFrozen +OAI.Computability.VertexCover.Reduction.RestrictionStarBudget +OAI.Computability.VertexCover.Reduction.SeparatorContinuousSumOdd +OAI.Computability.VertexCover.Reduction.SeparatorStarOscillation +OAI.Computability.VertexCover.Reduction.SimpleParallel +OAI.Computability.VertexCover.Reduction.Soundness +OAI.Computability.VertexCover.Reduction.SourceEncoding +OAI.Computability.VertexCover.Repetition.AlphabetBudget +OAI.Computability.VertexCover.Repetition.CompletedSampling +OAI.Computability.VertexCover.Repetition.Completion +OAI.Computability.VertexCover.Repetition.DistributionMaps +OAI.Computability.VertexCover.Repetition.Factorization +OAI.Computability.VertexCover.Repetition.GameConditioning +OAI.Computability.VertexCover.Repetition.Holenstein +OAI.Computability.VertexCover.Repetition.LocalSimulation +OAI.Computability.VertexCover.Repetition.MaskedVariation +OAI.Computability.VertexCover.Repetition.Overlap +OAI.Computability.VertexCover.Repetition.PartialReveal +OAI.Computability.VertexCover.Repetition.ProfileBounds +OAI.Computability.VertexCover.Repetition.ProfileCorrection +OAI.Computability.VertexCover.Repetition.QuestionMarginal +OAI.Computability.VertexCover.Repetition.Reveal +OAI.Computability.VertexCover.Repetition.RevealFactorization +OAI.Computability.VertexCover.Repetition.RightProfileBounds +OAI.Computability.VertexCover.Repetition.Scalar +OAI.Computability.VertexCover.Repetition.SelectedCommon +OAI.Computability.VertexCover.Repetition.SelectedCommonMarginal +OAI.Computability.VertexCover.Repetition.SelectedCompletion +OAI.Computability.VertexCover.Repetition.SelectedCompletionGame +OAI.Computability.VertexCover.Repetition.SelectedInformation +OAI.Computability.VertexCover.Repetition.SelectedJoint +OAI.Computability.VertexCover.Repetition.SelectedJointGame +OAI.Computability.VertexCover.Repetition.SelectedLikelihood +OAI.Computability.VertexCover.Repetition.SelectedMarginal +OAI.Computability.VertexCover.Repetition.SelectedProfileBudget +OAI.Computability.VertexCover.Repetition.SelectedProfiles +OAI.Computability.VertexCover.Repetition.SelectionSequence +OAI.Computability.VertexCover.Repetition.SharedSampling +OAI.Computability.VertexCover.Repetition.Variation +OAI.Computability.VertexCover.Sampling.Basic +OAI.Computability.VertexCover.Sampling.FiniteTrials +OAI.Computability.VertexCover.Sampling.LabelBound +OAI.Computability.VertexCover.Sampling.Rectangle +OAI.Computability.VertexCover.Sampling.SharedProfiles +OAI.Computability.VertexCover.Sampling.ThresholdPartition +OAI.Computability.VertexCover.Sampling.TraceLaw diff --git a/tasks/vertex-cover/solution/reference.py b/tasks/vertex-cover/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/vertex-cover/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/vertex-cover/solution/solve.sh b/tasks/vertex-cover/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b5a2518256c197c8961a1f9780f6b3ee9538394f --- /dev/null +++ b/tasks/vertex-cover/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of VertexCover, i.e. module OAI.Computability.VertexCover.Main and the +# 351 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.VertexCover.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of VertexCover" diff --git a/tasks/vertex-cover/task.toml b/tasks/vertex-cover/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..07346416649f0dc822417ef1071771a4ccefc958 --- /dev/null +++ b/tasks/vertex-cover/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/vertex-cover" +version = "1.0.0" +description = "Prove VertexCover (openai/math family 102: The Unique Games Conjecture and optimal approximation thresholds) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/VertexCover.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "VertexCover" +family = "102" +family_title = "The Unique Games Conjecture and optimal approximation thresholds" +subject = "Theoretical computer science" +theorems = ["OAI.VertexCover.explicit_cover_gap", "OAI.VertexCover.every_fixed_factor_below_two"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.VertexCover.Main" +reference_modules = 351 +reference_lean_bytes = 2275461 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1027 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 13747 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/vertex-cover/tests/Challenge.lean b/tasks/vertex-cover/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ffb0647a3284257c9db8b1872945c1ddc6d27c5e --- /dev/null +++ b/tasks/vertex-cover/tests/Challenge.lean @@ -0,0 +1,154 @@ +import Mathlib + +namespace OAI + +namespace UniqueGames.BinaryFormula + +structure Literal where + name : Nat + positive : Bool + deriving DecidableEq + +def Literal.eval (literal : Literal) (assignment : Nat → Bool) : Bool := + if literal.positive then assignment literal.name else !(assignment literal.name) + +abbrev Clause := Vector Literal 3 + +def Clause.eval (clause : Clause) (assignment : Nat → Bool) : Bool := + (clause[0].eval assignment || clause[1].eval assignment) || clause[2].eval assignment + +structure Formula where + clauses : List Clause + +def Formula.Satisfiable (F : Formula) : Prop := + ∃ assignment : Nat → Bool, ∀ clause ∈ F.clauses, clause.eval assignment = true + +end UniqueGames.BinaryFormula + +namespace UniqueGames.BinaryEncoding + +open BinaryFormula + +def bitsValue : List Bool → Nat + | [] => 0 + | b :: bits => Nat.bit b (bitsValue bits) + +def frame : List Bool → List Bool + | [] => [false] + | b :: bits => true :: b :: frame bits + +def parseFrame : List Bool → Option (List Bool × List Bool) + | false :: rest => some ([], rest) + | true :: b :: rest => do + let (bits, trailing) ← parseFrame rest + return (b :: bits, trailing) + | _ => none + +def nameBits (name : Nat) : List Bool := frame name.bits + +def parseName (input : List Bool) : Option (Nat × List Bool) := do + let (digits, rest) ← parseFrame input + let name := bitsValue digits + if digits = name.bits then some (name, rest) else none + +def parseLiteral : List Bool → Option (Literal × List Bool) + | sign :: input => do + let (name, rest) ← parseName input + return (⟨name, sign⟩, rest) + | [] => none + +def parseClause (input : List Bool) : Option (Clause × List Bool) := do + let (a, input) ← parseLiteral input + let (b, input) ← parseLiteral input + let (c, rest) ← parseLiteral input + return (#v[a, b, c], rest) + +def parseClauses : Nat → List Bool → Option (List Clause × List Bool) + | 0, _ => none + | _fuel + 1, false :: rest => some ([], rest) + | fuel + 1, true :: input => do + let (clause, input) ← parseClause input + let (clauses, rest) ← parseClauses fuel input + return (clause :: clauses, rest) + | _ + 1, [] => none + +def decodeFormula (input : List Bool) : Option Formula := do + let (clauses, rest) ← parseClauses (input.length + 1) input + if rest = [] then some ⟨clauses⟩ else none + +end UniqueGames.BinaryEncoding + +namespace VertexCover + +def ThreeSAT (input : List Bool) : Prop := + ∃ formula, UniqueGames.BinaryEncoding.decodeFormula input = some formula ∧ + formula.Satisfiable + +structure ExplicitGraph where + n : ℕ + edges : List (Fin n × Fin n) + increasing : ∀ e ∈ edges, e.1 < e.2 + nodup : edges.Nodup + +namespace ExplicitGraph + +def Cover (G : ExplicitGraph) (S : Finset (Fin G.n)) : Prop := + ∀ e ∈ G.edges, e.1 ∈ S ∨ e.2 ∈ S + +instance (G : ExplicitGraph) (S : Finset (Fin G.n)) : Decidable (G.Cover S) := + inferInstanceAs (Decidable (∀ e ∈ G.edges, e.1 ∈ S ∨ e.2 ∈ S)) + +noncomputable def coverNumber (G : ExplicitGraph) : ℕ := + Nat.find (show ∃ k : ℕ, ∃ S : Finset (Fin G.n), G.Cover S ∧ S.card = k from + ⟨G.n, Finset.univ, by simp [Cover], by simp⟩) + +def bits (G : ExplicitGraph) : List Bool := + let names := [G.n] ++ List.range G.n ++ [G.edges.length] ++ + G.edges.flatMap (fun e => [e.1.val, e.2.val]) + names.flatMap UniqueGames.BinaryEncoding.nameBits + +end ExplicitGraph + +def FiniteAlphabet (M : Turing.FinTM2) : Prop := ∀ k, Finite (M.Γ k) + +structure GapReduction (m : ℕ) where + construct : List Bool → ExplicitGraph + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + ExplicitGraph.bits construct + finiteAlphabet : FiniteAlphabet computation.tm + completeness : ∀ input, ThreeSAT input → + ((construct input).coverNumber : ℝ) < + (1 / 2 + 1 / (m : ℝ)) * (construct input).n + soundness : ∀ input, ¬ ThreeSAT input → + (1 - 1 / (m : ℝ)) * (construct input).n < + ((construct input).coverNumber : ℝ) + +def natListBits (L : List ℕ) : List Bool := + (L.length :: L).flatMap UniqueGames.BinaryEncoding.nameBits + +structure Approximation (α : ℝ) where + run : ExplicitGraph → List ℕ + computation : Turing.TM2ComputableInPolyTime ExplicitGraph.bits natListBits run + finiteAlphabet : FiniteAlphabet computation.tm + nodup : ∀ G, (run G).Nodup + vertices : ∀ G, ∀ v ∈ run G, v < G.n + covers : ∀ G, ∀ e ∈ G.edges, e.1.val ∈ run G ∨ e.2.val ∈ run G + quality : ∀ G, ((run G).length : ℝ) ≤ α * (G.coverNumber : ℝ) + +structure ThreeSATDecision where + run : List Bool → Bool + computation : Turing.TM2ComputableInPolyTime (id : List Bool → List Bool) + (fun b : Bool => [b]) run + finiteAlphabet : FiniteAlphabet computation.tm + correct : ∀ input, run input = true ↔ ThreeSAT input + +theorem explicit_cover_gap (m : ℕ) (hm : 4 ≤ m) : Nonempty (GapReduction m) := by + sorry + +theorem every_fixed_factor_below_two (α : ℝ) (hα : 1 ≤ α) (hα2 : α < 2) + (algorithm : Approximation α) : Nonempty ThreeSATDecision := by + sorry + +end VertexCover + +end OAI diff --git a/tasks/vertex-cover/tests/grade.py b/tasks/vertex-cover/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/vertex-cover/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/vertex-cover/tests/task.json b/tasks/vertex-cover/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..43279f94eed365c133e4623f37c5e711f53ba137 --- /dev/null +++ b/tasks/vertex-cover/tests/task.json @@ -0,0 +1,16 @@ +{ + "challenge": "VertexCover", + "comparator": { + "theorem_names": [ + "OAI.VertexCover.explicit_cover_gap", + "OAI.VertexCover.every_fixed_factor_below_two" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 12847 +} \ No newline at end of file diff --git a/tasks/vertex-cover/tests/test.sh b/tasks/vertex-cover/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/vertex-cover/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/vlasov-maxwell/environment/Dockerfile b/tasks/vlasov-maxwell/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/vlasov-maxwell/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/vlasov-maxwell/environment/fetch_mathlib.sh b/tasks/vlasov-maxwell/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/vlasov-maxwell/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/vlasov-maxwell/environment/lake-manifest.json b/tasks/vlasov-maxwell/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/vlasov-maxwell/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/vlasov-maxwell/environment/lakefile.lean b/tasks/vlasov-maxwell/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/vlasov-maxwell/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/vlasov-maxwell/environment/lean_setup.sh b/tasks/vlasov-maxwell/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/vlasov-maxwell/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/vlasov-maxwell/environment/pack_submission.py b/tasks/vlasov-maxwell/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/vlasov-maxwell/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/vlasov-maxwell/instruction.md b/tasks/vlasov-maxwell/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..80c10101db008eea15ee07230d954f6fb79abe7b --- /dev/null +++ b/tasks/vlasov-maxwell/instruction.md @@ -0,0 +1,163 @@ +# openai/math challenge `VlasovMaxwell` (family 362) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 362 of the release, *Global smoothness for relativistic Vlasov–Maxwell* +(Partial differential equations). The family as a whole: Proves large-data global existence and uniqueness for the three-dimensional, one-species relativistic Vlasov–Maxwell system. Smooth admissible initial data may be arbitrary provided the particle density is compactly supported and the electromagnetic fields have finite energy and bounded derivatives of every order; the solution remains smooth on every finite time interval. + +The challenge is `VlasovMaxwell`, also at `/opt/openai-math/challenges/VlasovMaxwell.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Set +open scoped ContDiff +namespace RVM + +abbrev Vec := EuclideanSpace ℝ (Fin 3) +abbrev Phase := Vec × Vec +abbrev Particle := ℝ × Phase → ℝ +abbrev Field := ℝ × Vec → Vec + +def q (v : Vec) : ℝ := Real.sqrt (1 + ‖v‖ ^ 2) +def velocity (v : Vec) : Vec := (q v)⁻¹ • v + +def basis (i : Fin 3) : Vec := WithLp.toLp 2 (Pi.single i (1 : ℝ)) +def dot (a b : Vec) : ℝ := ∑ i : Fin 3, a i * b i +def cross (a b : Vec) : Vec := WithLp.toLp 2 + ![a 1 * b 2 - a 2 * b 1, a 2 * b 0 - a 0 * b 2, + a 0 * b 1 - a 1 * b 0] + +def spatialPartial (g : Vec → ℝ) (x : Vec) (i : Fin 3) : ℝ := + fderiv ℝ g x (basis i) +def divergence (F : Vec → Vec) (x : Vec) : ℝ := + ∑ i : Fin 3, spatialPartial (fun y => F y i) x i + +def curl (F : Vec → Vec) (x : Vec) : Vec := WithLp.toLp 2 + ![spatialPartial (fun y => F y 2) x 1 - spatialPartial (fun y => F y 1) x 2, + spatialPartial (fun y => F y 0) x 2 - spatialPartial (fun y => F y 2) x 0, + spatialPartial (fun y => F y 1) x 0 - spatialPartial (fun y => F y 0) x 1] + +def rho (g : Phase → ℝ) (x : Vec) : ℝ := ∫ v : Vec, g (x, v) +def current (g : Phase → ℝ) (x : Vec) : Vec := + ∫ v : Vec, g (x, v) • velocity v + +structure Datum where + f₀ : Phase → ℝ + E₀ : Vec → Vec + B₀ : Vec → Vec + +def BoundedSmooth (F : Vec → Vec) : Prop := + ContDiff ℝ ∞ F ∧ ∀ n : ℕ, ∃ C : ℝ, ∀ x : Vec, + ‖iteratedFDeriv ℝ n F x‖ ≤ C + +def Admissible (d : Datum) : Prop := + ContDiff ℝ ∞ d.f₀ ∧ HasCompactSupport d.f₀ ∧ (∀ z, 0 ≤ d.f₀ z) ∧ + BoundedSmooth d.E₀ ∧ BoundedSmooth d.B₀ ∧ + MemLp d.E₀ 2 volume ∧ MemLp d.B₀ 2 volume ∧ + (∀ x, divergence d.E₀ x = rho d.f₀ x) ∧ + (∀ x, divergence d.B₀ x = 0) + +structure Solution where + f : Particle + E : Field + B : Field + +def particleHalfSpace : Set (ℝ × Phase) := {z | 0 ≤ z.1} +def fieldHalfSpace : Set (ℝ × Vec) := {z | 0 ≤ z.1} +def particleSlab (T : ℝ) : Set (ℝ × Phase) := {z | z.1 ∈ Icc 0 T} +def fieldSlab (T : ℝ) : Set (ℝ × Vec) := {z | z.1 ∈ Icc 0 T} + +def TimeContinuousL2 (F : Field) : Prop := + ∃ F₂ : ℝ → Lp Vec 2 (volume : Measure Vec), + ContinuousOn F₂ (Ici 0) ∧ + ∀ t, 0 ≤ t → (F₂ t : Vec → Vec) =ᵐ[volume] (fun x => F (t, x)) + +def Equations (s : Solution) : Prop := ∀ t, 0 ≤ t → + (∀ x v, + derivWithin (fun t' => s.f (t', x, v)) (Ici 0) t + + (∑ i : Fin 3, velocity v i * spatialPartial (fun y => s.f (t, y, v)) x i) + + (∑ i : Fin 3, (s.E (t, x) + cross (velocity v) (s.B (t, x))) i * + spatialPartial (fun v' => s.f (t, x, v')) v i) = 0) ∧ + (∀ x, derivWithin (fun t' => s.E (t', x)) (Ici 0) t - + curl (fun y => s.B (t, y)) x = -current (fun z => s.f (t, z)) x) ∧ + (∀ x, derivWithin (fun t' => s.B (t', x)) (Ici 0) t + + curl (fun y => s.E (t, y)) x = 0) ∧ + (∀ x, divergence (fun y => s.E (t, y)) x = rho (fun z => s.f (t, z)) x) ∧ + (∀ x, divergence (fun y => s.B (t, y)) x = 0) + +def CompactOnFiniteHorizons (s : Solution) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ K : Set Phase, IsCompact K ∧ + ∀ t ∈ Icc 0 T, tsupport (fun z => s.f (t, z)) ⊆ K + +def Classical (d : Datum) (s : Solution) : Prop := + ContDiffOn ℝ 1 s.f particleHalfSpace ∧ + ContDiffOn ℝ 1 s.E fieldHalfSpace ∧ ContDiffOn ℝ 1 s.B fieldHalfSpace ∧ + (∀ t, 0 ≤ t → ∀ z, 0 ≤ s.f (t, z)) ∧ + TimeContinuousL2 s.E ∧ TimeContinuousL2 s.B ∧ + CompactOnFiniteHorizons s ∧ Equations s ∧ + (∀ z, s.f (0, z) = d.f₀ z) ∧ + (∀ x, s.E (0, x) = d.E₀ x) ∧ (∀ x, s.B (0, x) = d.B₀ x) + +def SmoothOnFiniteHorizons (s : Solution) : Prop := ∀ T : ℝ, 0 ≤ T → + ContDiffOn ℝ ∞ s.f (particleSlab T) ∧ + ContDiffOn ℝ ∞ s.E (fieldSlab T) ∧ ContDiffOn ℝ ∞ s.B (fieldSlab T) + +def SameNonnegativeTime (s s' : Solution) : Prop := ∀ t, 0 ≤ t → + (∀ z, s.f (t, z) = s'.f (t, z)) ∧ + (∀ x, s.E (t, x) = s'.E (t, x)) ∧ (∀ x, s.B (t, x) = s'.B (t, x)) + +theorem global_classical_solution (d : Datum) (hd : Admissible d) : + ∃ s : Solution, Classical d s ∧ SmoothOnFiniteHorizons s ∧ + ∀ s' : Solution, Classical d s' → SameNonnegativeTime s s' := by + sorry + +end RVM + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/VlasovMaxwell.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.RVM.global_classical_solution` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/vlasov-maxwell/solution/closure.txt b/tasks/vlasov-maxwell/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f782e85f3a9473d35e00cb4613ba3332afbf8eb0 --- /dev/null +++ b/tasks/vlasov-maxwell/solution/closure.txt @@ -0,0 +1,207 @@ +OAI.Analysis.VlasovMaxwell.Continuation.Bootstrap +OAI.Analysis.VlasovMaxwell.Continuation.DerivMovingEnergy +OAI.Analysis.VlasovMaxwell.Continuation.GlobalBoundaryBound +OAI.Analysis.VlasovMaxwell.Continuation.GlobalContinuation +OAI.Analysis.VlasovMaxwell.Continuation.IncrementBootstrap +OAI.Analysis.VlasovMaxwell.Continuation.PhysicalBinBasePrefix +OAI.Analysis.VlasovMaxwell.Continuation.PrefixClamp +OAI.Analysis.VlasovMaxwell.Continuation.PrefixMomentumForce +OAI.Analysis.VlasovMaxwell.Continuation.PrefixParticle +OAI.Analysis.VlasovMaxwell.Continuation.PrefixUniqueness +OAI.Analysis.VlasovMaxwell.Continuation.SlabSmoothBootstrap +OAI.Analysis.VlasovMaxwell.Flow.BranchCutoffStateContinuous +OAI.Analysis.VlasovMaxwell.Flow.BranchIntegral +OAI.Analysis.VlasovMaxwell.Flow.ClosedEulerianCrudeBudget +OAI.Analysis.VlasovMaxwell.Flow.ClosedEulerianTimeBudget +OAI.Analysis.VlasovMaxwell.Flow.ExtendedLorentz +OAI.Analysis.VlasovMaxwell.Flow.FlowDerivative +OAI.Analysis.VlasovMaxwell.Flow.HighFlow +OAI.Analysis.VlasovMaxwell.Flow.LorentzPhase +OAI.Analysis.VlasovMaxwell.Flow.PhaseAcceleration +OAI.Analysis.VlasovMaxwell.Flow.PhaseHits +OAI.Analysis.VlasovMaxwell.Flow.PhaseTimePullback +OAI.Analysis.VlasovMaxwell.Flow.TransportDifferentiation +OAI.Analysis.VlasovMaxwell.Flow.WithinFlow +OAI.Analysis.VlasovMaxwell.Geometry.ActualCutoffCoordinates +OAI.Analysis.VlasovMaxwell.Geometry.ActualLabelCutoffCost +OAI.Analysis.VlasovMaxwell.Geometry.ArrivalDomain +OAI.Analysis.VlasovMaxwell.Geometry.BallCutoff +OAI.Analysis.VlasovMaxwell.Geometry.ClippedRamp +OAI.Analysis.VlasovMaxwell.Geometry.ClosedBranchDomain +OAI.Analysis.VlasovMaxwell.Geometry.CollisionLabels +OAI.Analysis.VlasovMaxwell.Geometry.CrossCLM +OAI.Analysis.VlasovMaxwell.Geometry.CutoffState +OAI.Analysis.VlasovMaxwell.Geometry.DensitySecondMoment +OAI.Analysis.VlasovMaxwell.Geometry.IndexTwoPow +OAI.Analysis.VlasovMaxwell.Geometry.ParticleBySpacetime +OAI.Analysis.VlasovMaxwell.Geometry.ParticleTame +OAI.Analysis.VlasovMaxwell.Geometry.PhysicalDivision +OAI.Analysis.VlasovMaxwell.Geometry.PhysicalGeometryCutoffDensity +OAI.Analysis.VlasovMaxwell.Geometry.QuadIndexEquiv +OAI.Analysis.VlasovMaxwell.Geometry.RelativeAngleCoordinate +OAI.Analysis.VlasovMaxwell.Geometry.SelectedRemainderPhysical +OAI.Analysis.VlasovMaxwell.Geometry.ShiftedRho +OAI.Analysis.VlasovMaxwell.Geometry.SpaceDiv +OAI.Analysis.VlasovMaxwell.Geometry.Sphere +OAI.Analysis.VlasovMaxwell.Geometry.UpperTimeCut +OAI.Analysis.VlasovMaxwell.LocalPDE.EquationsBefore +OAI.Analysis.VlasovMaxwell.LocalPDE.FiniteUniqueness +OAI.Analysis.VlasovMaxwell.LocalPDE.GeometryCutoffDeficitLogSum +OAI.Analysis.VlasovMaxwell.LocalPDE.GeometryCutoffStableLogSum +OAI.Analysis.VlasovMaxwell.LocalPDE.PicardBoundary +OAI.Analysis.VlasovMaxwell.LocalPDE.PicardBounds +OAI.Analysis.VlasovMaxwell.LocalPDE.PicardContraction +OAI.Analysis.VlasovMaxwell.LocalPDE.PicardCurvature +OAI.Analysis.VlasovMaxwell.LocalPDE.RelativeCauchyConstant +OAI.Analysis.VlasovMaxwell.LocalPDE.SlabEquations +OAI.Analysis.VlasovMaxwell.LocalPDE.SlabRHS +OAI.Analysis.VlasovMaxwell.LocalPDE.SmoothLocalExistence +OAI.Analysis.VlasovMaxwell.LocalPDE.StrongLocalExistence +OAI.Analysis.VlasovMaxwell.LocalPDE.UniformParticleDensityConstant +OAI.Analysis.VlasovMaxwell.LocalPDE.VlasovConstruction +OAI.Analysis.VlasovMaxwell.Main +OAI.Analysis.VlasovMaxwell.Maxwell.DifferenceFieldEnergy +OAI.Analysis.VlasovMaxwell.Maxwell.ElectricBoundaryField +OAI.Analysis.VlasovMaxwell.Maxwell.ExtendedField +OAI.Analysis.VlasovMaxwell.Maxwell.FieldGradientNorm +OAI.Analysis.VlasovMaxwell.Maxwell.FiniteFlow +OAI.Analysis.VlasovMaxwell.Maxwell.Variational +OAI.Analysis.VlasovMaxwell.Maxwell.WaveGradient +OAI.Analysis.VlasovMaxwell.Maxwell.WaveK +OAI.Analysis.VlasovMaxwell.Model +OAI.Analysis.VlasovMaxwell.Population.BinHits +OAI.Analysis.VlasovMaxwell.Population.BulkReceiverResidual +OAI.Analysis.VlasovMaxwell.Population.BulkReceiverScalar +OAI.Analysis.VlasovMaxwell.Population.BulkSpatialUniform +OAI.Analysis.VlasovMaxwell.Population.BulkTestWeight +OAI.Analysis.VlasovMaxwell.Population.BulkWeightCost +OAI.Analysis.VlasovMaxwell.Population.CappedRepresentativePos +OAI.Analysis.VlasovMaxwell.Population.CentralOccupation +OAI.Analysis.VlasovMaxwell.Population.ContDiffDyadicMultiFactor +OAI.Analysis.VlasovMaxwell.Population.DatumElectricFluxKernel +OAI.Analysis.VlasovMaxwell.Population.DirectExpandedAssemble +OAI.Analysis.VlasovMaxwell.Population.DirectExpandedDeficitUniform +OAI.Analysis.VlasovMaxwell.Population.DirectExpandedLargeAngular +OAI.Analysis.VlasovMaxwell.Population.DirectExpandedTransportNear +OAI.Analysis.VlasovMaxwell.Population.DirectionCounts +OAI.Analysis.VlasovMaxwell.Population.DirectionCutoffs +OAI.Analysis.VlasovMaxwell.Population.DirectionOverlap +OAI.Analysis.VlasovMaxwell.Population.DyadicBalanceConstant +OAI.Analysis.VlasovMaxwell.Population.DyadicCut +OAI.Analysis.VlasovMaxwell.Population.GoodCrossings +OAI.Analysis.VlasovMaxwell.Population.GoodSharedEstimates +OAI.Analysis.VlasovMaxwell.Population.HomogeneousCancellation +OAI.Analysis.VlasovMaxwell.Population.InitialSignedBoundaryDensity +OAI.Analysis.VlasovMaxwell.Population.LabelOccupation +OAI.Analysis.VlasovMaxwell.Population.LabelOccupationDurationMass +OAI.Analysis.VlasovMaxwell.Population.LabelWeight +OAI.Analysis.VlasovMaxwell.Population.MagneticEstimates +OAI.Analysis.VlasovMaxwell.Population.MajorantRelativeDensityTimeFar +OAI.Analysis.VlasovMaxwell.Population.MomentumDirection +OAI.Analysis.VlasovMaxwell.Population.NullConeFlux +OAI.Analysis.VlasovMaxwell.Population.PartitionOccupation +OAI.Analysis.VlasovMaxwell.Population.PhysicalBinPhaseSet +OAI.Analysis.VlasovMaxwell.Population.RadialSummation +OAI.Analysis.VlasovMaxwell.Population.ReceiverWeights +OAI.Analysis.VlasovMaxwell.Population.RelativeClosedBinHitGeometry +OAI.Analysis.VlasovMaxwell.Population.RepresentativeClosedBinSourceIndices +OAI.Analysis.VlasovMaxwell.Population.RepresentativeCosts +OAI.Analysis.VlasovMaxwell.Population.RetardedSameTimeSeparation +OAI.Analysis.VlasovMaxwell.Population.RetardedWeightedIntegralBound +OAI.Analysis.VlasovMaxwell.Population.SelectedDirection +OAI.Analysis.VlasovMaxwell.Population.SelectedReceiverWeightBoundFinite +OAI.Analysis.VlasovMaxwell.Population.SelectedRemainder +OAI.Analysis.VlasovMaxwell.Population.SelectionCounts +OAI.Analysis.VlasovMaxwell.Population.SelectionWeight +OAI.Analysis.VlasovMaxwell.Population.SharedBudget +OAI.Analysis.VlasovMaxwell.Population.SharedOccupation +OAI.Analysis.VlasovMaxwell.Population.SignedRemainder +OAI.Analysis.VlasovMaxwell.Population.SourceJointFlux +OAI.Analysis.VlasovMaxwell.Population.SourceWeightedPacket +OAI.Analysis.VlasovMaxwell.Population.SpatialEstimates +OAI.Analysis.VlasovMaxwell.Population.SphericalFluxNorm +OAI.Analysis.VlasovMaxwell.Population.SqrtBaselineClippedLength +OAI.Analysis.VlasovMaxwell.Population.TransportRemainder +OAI.Analysis.VlasovMaxwell.Population.TransportSingularBulk +OAI.Analysis.VlasovMaxwell.Population.UniformPopulation +OAI.Analysis.VlasovMaxwell.Population.UnselectedCover +OAI.Analysis.VlasovMaxwell.Regularity.AbsolutelyContinuousIntervalContinuousDerivative +OAI.Analysis.VlasovMaxwell.Regularity.BoundaryJets +OAI.Analysis.VlasovMaxwell.Regularity.ContinuousIntegralSphere +OAI.Analysis.VlasovMaxwell.Regularity.CurvatureBounds +OAI.Analysis.VlasovMaxwell.Regularity.CurvatureInterpolation +OAI.Analysis.VlasovMaxwell.Regularity.EnergyBump +OAI.Analysis.VlasovMaxwell.Regularity.IntegralBallPolarFlip +OAI.Analysis.VlasovMaxwell.Regularity.LogSingularBound +OAI.Analysis.VlasovMaxwell.Regularity.LowBoundaryControl +OAI.Analysis.VlasovMaxwell.Regularity.MixedJets +OAI.Analysis.VlasovMaxwell.Regularity.MomentLimit +OAI.Analysis.VlasovMaxwell.Regularity.NormalisedPartialCutoff +OAI.Analysis.VlasovMaxwell.Regularity.ParamPrimitive +OAI.Analysis.VlasovMaxwell.Regularity.ParticleC1 +OAI.Analysis.VlasovMaxwell.Regularity.PhysicalC0 +OAI.Analysis.VlasovMaxwell.Regularity.PhysicalCutoffCoordinates +OAI.Analysis.VlasovMaxwell.Regularity.PhysicalGradient +OAI.Analysis.VlasovMaxwell.Regularity.PositiveExtension +OAI.Analysis.VlasovMaxwell.Regularity.RealJointEnergyBudget +OAI.Analysis.VlasovMaxwell.Regularity.SlabEvolutionRegularity +OAI.Analysis.VlasovMaxwell.Regularity.SlabL2 +OAI.Analysis.VlasovMaxwell.Regularity.SmoothIntegral +OAI.Analysis.VlasovMaxwell.Regularity.SpatialJets +OAI.Analysis.VlasovMaxwell.Regularity.TameDerivative +OAI.Analysis.VlasovMaxwell.Regularity.VelocityDerivatives +OAI.Analysis.VlasovMaxwell.Regularity.VolterraSup +OAI.Analysis.VlasovMaxwell.Regularity.WithinPartial +OAI.Analysis.VlasovMaxwell.Retarded.AffineRetardedBound +OAI.Analysis.VlasovMaxwell.Retarded.AngularBump +OAI.Analysis.VlasovMaxwell.Retarded.ArrivalConeKernelPolarNorm +OAI.Analysis.VlasovMaxwell.Retarded.ConeArgument +OAI.Analysis.VlasovMaxwell.Retarded.ConeEulerianIntegrand +OAI.Analysis.VlasovMaxwell.Retarded.ConeForceSplit +OAI.Analysis.VlasovMaxwell.Retarded.ConeKernelInterior +OAI.Analysis.VlasovMaxwell.Retarded.ConeMotion +OAI.Analysis.VlasovMaxwell.Retarded.ConeRadius +OAI.Analysis.VlasovMaxwell.Retarded.ConeRegularity +OAI.Analysis.VlasovMaxwell.Retarded.CutoffRateMajorant +OAI.Analysis.VlasovMaxwell.Retarded.CutoffSourceTangent +OAI.Analysis.VlasovMaxwell.Retarded.DirectDeficitUniform +OAI.Analysis.VlasovMaxwell.Retarded.DirectForce +OAI.Analysis.VlasovMaxwell.Retarded.DirectLargeAngularSharp +OAI.Analysis.VlasovMaxwell.Retarded.DirectLorentzUniform +OAI.Analysis.VlasovMaxwell.Retarded.DirectMixedCover +OAI.Analysis.VlasovMaxwell.Retarded.DirectSmallAbsolute +OAI.Analysis.VlasovMaxwell.Retarded.ElectricConeBoundary +OAI.Analysis.VlasovMaxwell.Retarded.GeneralDirectRadial +OAI.Analysis.VlasovMaxwell.Retarded.InitialPuncturedCone +OAI.Analysis.VlasovMaxwell.Retarded.MagneticBoundaryJets +OAI.Analysis.VlasovMaxwell.Retarded.MagneticMomentDensity +OAI.Analysis.VlasovMaxwell.Retarded.MagneticVolterra +OAI.Analysis.VlasovMaxwell.Retarded.ObservationCone +OAI.Analysis.VlasovMaxwell.Retarded.PhysicalAngularBound +OAI.Analysis.VlasovMaxwell.Retarded.PhysicalDirectTransportDensity +OAI.Analysis.VlasovMaxwell.Retarded.PhysicalElectricKernel +OAI.Analysis.VlasovMaxwell.Retarded.PhysicalProjectedRemainderDensity +OAI.Analysis.VlasovMaxwell.Retarded.PhysicalProjectedRemainderSourceTruncate +OAI.Analysis.VlasovMaxwell.Retarded.PicardKernel +OAI.Analysis.VlasovMaxwell.Retarded.ProjectedSourceStableFarBound +OAI.Analysis.VlasovMaxwell.Retarded.ReceiverQ +OAI.Analysis.VlasovMaxwell.Retarded.ReceiverQCLM +OAI.Analysis.VlasovMaxwell.Retarded.ReceiverRadialDomain +OAI.Analysis.VlasovMaxwell.Retarded.RetardedDifferentiation +OAI.Analysis.VlasovMaxwell.Retarded.RetardedMomentumForce +OAI.Analysis.VlasovMaxwell.Retarded.RetardedPhaseDomain +OAI.Analysis.VlasovMaxwell.Retarded.RetardedRadiusSeparatedClosed +OAI.Analysis.VlasovMaxwell.Retarded.SelectedConeTransfer +OAI.Analysis.VlasovMaxwell.Retarded.SourceCellLast +OAI.Analysis.VlasovMaxwell.Retarded.SourceField +OAI.Analysis.VlasovMaxwell.Retarded.SourceForceConeKernel +OAI.Analysis.VlasovMaxwell.Retarded.SourceKernels +OAI.Analysis.VlasovMaxwell.Retarded.SourceMajorant +OAI.Analysis.VlasovMaxwell.Retarded.SourceMajorantFamily +OAI.Analysis.VlasovMaxwell.Retarded.SourceVelocityProfile +OAI.Analysis.VlasovMaxwell.Retarded.SourceWaveSpatialIbp +OAI.Analysis.VlasovMaxwell.Retarded.SpaceConeDomain +OAI.Analysis.VlasovMaxwell.Retarded.TransportAngularCore +OAI.Analysis.VlasovMaxwell.Retarded.UniformDatumKernel +OAI.Analysis.VlasovMaxwell.Retarded.VolterraKernels +OAI.Analysis.VlasovMaxwell.Retarded.VolterraMajorant diff --git a/tasks/vlasov-maxwell/solution/reference.py b/tasks/vlasov-maxwell/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/vlasov-maxwell/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/vlasov-maxwell/solution/solve.sh b/tasks/vlasov-maxwell/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7a7e79f13183045740683ede3cea3103fd3320f5 --- /dev/null +++ b/tasks/vlasov-maxwell/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of VlasovMaxwell, i.e. module OAI.Analysis.VlasovMaxwell.Main and the +# 207 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Analysis.VlasovMaxwell.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of VlasovMaxwell" diff --git a/tasks/vlasov-maxwell/task.toml b/tasks/vlasov-maxwell/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1ede52d15bcad8127e0186bda7a2c1edab94a960 --- /dev/null +++ b/tasks/vlasov-maxwell/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/vlasov-maxwell" +version = "1.0.0" +description = "Prove VlasovMaxwell (openai/math family 362: Global smoothness for relativistic Vlasov–Maxwell) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "partial-differential-equations"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/VlasovMaxwell.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "VlasovMaxwell" +family = "362" +family_title = "Global smoothness for relativistic Vlasov–Maxwell" +subject = "Partial differential equations" +theorems = ["OAI.RVM.global_classical_solution"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Analysis.VlasovMaxwell.Main" +reference_modules = 207 +reference_lean_bytes = 4841359 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1368 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 16057 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/vlasov-maxwell/tests/Challenge.lean b/tasks/vlasov-maxwell/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..38b6c73916a07c182e16c50652c1a7e30b5412d0 --- /dev/null +++ b/tasks/vlasov-maxwell/tests/Challenge.lean @@ -0,0 +1,112 @@ +import Mathlib + +namespace OAI + +noncomputable section +open MeasureTheory Set +open scoped ContDiff +namespace RVM + +abbrev Vec := EuclideanSpace ℝ (Fin 3) +abbrev Phase := Vec × Vec +abbrev Particle := ℝ × Phase → ℝ +abbrev Field := ℝ × Vec → Vec + +def q (v : Vec) : ℝ := Real.sqrt (1 + ‖v‖ ^ 2) +def velocity (v : Vec) : Vec := (q v)⁻¹ • v + +def basis (i : Fin 3) : Vec := WithLp.toLp 2 (Pi.single i (1 : ℝ)) +def dot (a b : Vec) : ℝ := ∑ i : Fin 3, a i * b i +def cross (a b : Vec) : Vec := WithLp.toLp 2 + ![a 1 * b 2 - a 2 * b 1, a 2 * b 0 - a 0 * b 2, + a 0 * b 1 - a 1 * b 0] + +def spatialPartial (g : Vec → ℝ) (x : Vec) (i : Fin 3) : ℝ := + fderiv ℝ g x (basis i) +def divergence (F : Vec → Vec) (x : Vec) : ℝ := + ∑ i : Fin 3, spatialPartial (fun y => F y i) x i + +def curl (F : Vec → Vec) (x : Vec) : Vec := WithLp.toLp 2 + ![spatialPartial (fun y => F y 2) x 1 - spatialPartial (fun y => F y 1) x 2, + spatialPartial (fun y => F y 0) x 2 - spatialPartial (fun y => F y 2) x 0, + spatialPartial (fun y => F y 1) x 0 - spatialPartial (fun y => F y 0) x 1] + +def rho (g : Phase → ℝ) (x : Vec) : ℝ := ∫ v : Vec, g (x, v) +def current (g : Phase → ℝ) (x : Vec) : Vec := + ∫ v : Vec, g (x, v) • velocity v + +structure Datum where + f₀ : Phase → ℝ + E₀ : Vec → Vec + B₀ : Vec → Vec + +def BoundedSmooth (F : Vec → Vec) : Prop := + ContDiff ℝ ∞ F ∧ ∀ n : ℕ, ∃ C : ℝ, ∀ x : Vec, + ‖iteratedFDeriv ℝ n F x‖ ≤ C + +def Admissible (d : Datum) : Prop := + ContDiff ℝ ∞ d.f₀ ∧ HasCompactSupport d.f₀ ∧ (∀ z, 0 ≤ d.f₀ z) ∧ + BoundedSmooth d.E₀ ∧ BoundedSmooth d.B₀ ∧ + MemLp d.E₀ 2 volume ∧ MemLp d.B₀ 2 volume ∧ + (∀ x, divergence d.E₀ x = rho d.f₀ x) ∧ + (∀ x, divergence d.B₀ x = 0) + +structure Solution where + f : Particle + E : Field + B : Field + +def particleHalfSpace : Set (ℝ × Phase) := {z | 0 ≤ z.1} +def fieldHalfSpace : Set (ℝ × Vec) := {z | 0 ≤ z.1} +def particleSlab (T : ℝ) : Set (ℝ × Phase) := {z | z.1 ∈ Icc 0 T} +def fieldSlab (T : ℝ) : Set (ℝ × Vec) := {z | z.1 ∈ Icc 0 T} + +def TimeContinuousL2 (F : Field) : Prop := + ∃ F₂ : ℝ → Lp Vec 2 (volume : Measure Vec), + ContinuousOn F₂ (Ici 0) ∧ + ∀ t, 0 ≤ t → (F₂ t : Vec → Vec) =ᵐ[volume] (fun x => F (t, x)) + +def Equations (s : Solution) : Prop := ∀ t, 0 ≤ t → + (∀ x v, + derivWithin (fun t' => s.f (t', x, v)) (Ici 0) t + + (∑ i : Fin 3, velocity v i * spatialPartial (fun y => s.f (t, y, v)) x i) + + (∑ i : Fin 3, (s.E (t, x) + cross (velocity v) (s.B (t, x))) i * + spatialPartial (fun v' => s.f (t, x, v')) v i) = 0) ∧ + (∀ x, derivWithin (fun t' => s.E (t', x)) (Ici 0) t - + curl (fun y => s.B (t, y)) x = -current (fun z => s.f (t, z)) x) ∧ + (∀ x, derivWithin (fun t' => s.B (t', x)) (Ici 0) t + + curl (fun y => s.E (t, y)) x = 0) ∧ + (∀ x, divergence (fun y => s.E (t, y)) x = rho (fun z => s.f (t, z)) x) ∧ + (∀ x, divergence (fun y => s.B (t, y)) x = 0) + +def CompactOnFiniteHorizons (s : Solution) : Prop := + ∀ T : ℝ, 0 ≤ T → ∃ K : Set Phase, IsCompact K ∧ + ∀ t ∈ Icc 0 T, tsupport (fun z => s.f (t, z)) ⊆ K + +def Classical (d : Datum) (s : Solution) : Prop := + ContDiffOn ℝ 1 s.f particleHalfSpace ∧ + ContDiffOn ℝ 1 s.E fieldHalfSpace ∧ ContDiffOn ℝ 1 s.B fieldHalfSpace ∧ + (∀ t, 0 ≤ t → ∀ z, 0 ≤ s.f (t, z)) ∧ + TimeContinuousL2 s.E ∧ TimeContinuousL2 s.B ∧ + CompactOnFiniteHorizons s ∧ Equations s ∧ + (∀ z, s.f (0, z) = d.f₀ z) ∧ + (∀ x, s.E (0, x) = d.E₀ x) ∧ (∀ x, s.B (0, x) = d.B₀ x) + +def SmoothOnFiniteHorizons (s : Solution) : Prop := ∀ T : ℝ, 0 ≤ T → + ContDiffOn ℝ ∞ s.f (particleSlab T) ∧ + ContDiffOn ℝ ∞ s.E (fieldSlab T) ∧ ContDiffOn ℝ ∞ s.B (fieldSlab T) + +def SameNonnegativeTime (s s' : Solution) : Prop := ∀ t, 0 ≤ t → + (∀ z, s.f (t, z) = s'.f (t, z)) ∧ + (∀ x, s.E (t, x) = s'.E (t, x)) ∧ (∀ x, s.B (t, x) = s'.B (t, x)) + +theorem global_classical_solution (d : Datum) (hd : Admissible d) : + ∃ s : Solution, Classical d s ∧ SmoothOnFiniteHorizons s ∧ + ∀ s' : Solution, Classical d s' → SameNonnegativeTime s s' := by + sorry + +end RVM + +end + +end OAI diff --git a/tasks/vlasov-maxwell/tests/grade.py b/tasks/vlasov-maxwell/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/vlasov-maxwell/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/vlasov-maxwell/tests/task.json b/tasks/vlasov-maxwell/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..d637dfc0ef82810b713578b2811cddc2e9335077 --- /dev/null +++ b/tasks/vlasov-maxwell/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "VlasovMaxwell", + "comparator": { + "theorem_names": [ + "OAI.RVM.global_classical_solution" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 15157 +} \ No newline at end of file diff --git a/tasks/vlasov-maxwell/tests/test.sh b/tasks/vlasov-maxwell/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/vlasov-maxwell/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/weak-hessian/environment/Dockerfile b/tasks/weak-hessian/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/weak-hessian/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/weak-hessian/environment/fetch_mathlib.sh b/tasks/weak-hessian/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/weak-hessian/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/weak-hessian/environment/lake-manifest.json b/tasks/weak-hessian/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/weak-hessian/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/weak-hessian/environment/lakefile.lean b/tasks/weak-hessian/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/weak-hessian/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/weak-hessian/environment/lean_setup.sh b/tasks/weak-hessian/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/weak-hessian/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/weak-hessian/environment/pack_submission.py b/tasks/weak-hessian/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/weak-hessian/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/weak-hessian/instruction.md b/tasks/weak-hessian/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..212952935f609aee93457c5b2544863370178f56 --- /dev/null +++ b/tasks/weak-hessian/instruction.md @@ -0,0 +1,284 @@ +# openai/math challenge `WeakHessian` (family 356) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 356 of the release, *Gigli's characterization of Alexandrov curvature* +(Differential geometry). The family as a whole: Proves Gigli's conjecture: in every integer dimension $n\ge2$, Alexandrov curvature at least $\kappa$ is characterized by the full-support $\operatorname{RCD}((n-1)\kappa,n)$ condition with reference measure $\mathcal H^n$ and distributional sectional curvature at least $\kappa$ in the original global test classes. The RCD condition is unreduced. + +The challenge is `WeakHessian`, also at `/opt/openai-math/challenges/WeakHessian.lean`: + +```lean +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped ENNReal NNReal Topology + +noncomputable section +attribute [local instance] Classical.propDecidable +namespace WeakHessian + +abbrev Time := Set.Icc (0 : ℝ) 1 + +def timeZero : Time := ⟨0, le_rfl, zero_le_one⟩ +def timeOne : Time := ⟨1, zero_le_one, le_rfl⟩ + +def clampTime (t : ℝ) : Time := + ⟨max 0 (min 1 t), le_max_left _ _, max_le zero_le_one (min_le_left _ _)⟩ + +variable {X : Type*} [MetricSpace X] + +abbrev Curve (X : Type*) [MetricSpace X] := C(Time, X) + +instance curveMeasurableSpace : MeasurableSpace (Curve X) := borel (Curve X) + +instance curveBorelSpace : BorelSpace (Curve X) := ⟨rfl⟩ + +def evalReal (γ : Curve X) (t : ℝ) : X := γ (clampTime t) + +/-- The constant-speed minimizing parametrization, including constant curves. -/ +def IsGeodesic (γ : Curve X) : Prop := + ∀ s t : Time, + dist (γ s) (γ t) = |(s : ℝ) - (t : ℝ)| * dist (γ timeZero) (γ timeOne) + +/-- Metric speed. Limsup agrees a.e. with the metric derivative on AC² curves. -/ +def metricSpeed (γ : Curve X) (t : ℝ) : ℝ≥0∞ := + Filter.limsup (fun s : ℝ => ENNReal.ofReal + (dist (evalReal γ s) (evalReal γ t) / |s - t|)) (𝓝[≠] t) + +/-- Absolute continuity with a square-integrable metric control. -/ +def IsAC2 (γ : Curve X) : Prop := + ∃ a : ℝ → ℝ≥0∞, Measurable a ∧ + (∫⁻ t in Set.Icc (0 : ℝ) 1, (a t) ^ 2) < ∞ ∧ + ∀ s t : Time, (s : ℝ) ≤ (t : ℝ) → + edist (γ s) (γ t) ≤ ∫⁻ r in Set.Icc (s : ℝ) (t : ℝ), a r + +variable [MeasurableSpace X] [BorelSpace X] + +/-- A 2-test plan: bounded compression and finite average kinetic energy. -/ +def IsTestPlan (m : Measure X) (π : Measure (Curve X)) : Prop := + IsProbabilityMeasure π ∧ + (∃ C : ℝ≥0, ∀ t : Time, + Measure.map (fun γ : Curve X => γ t) π ≤ (C : ℝ≥0∞) • m) ∧ + (∀ᵐ γ ∂π, IsAC2 γ) ∧ + (∫⁻ γ, ∫⁻ t in Set.Icc (0 : ℝ) 1, (metricSpeed γ t) ^ 2 ∂volume ∂π) < ∞ + +/-- Uniform bounded spatial support; used only to define the local Sobolev class. -/ +def BoundedTracks (π : Measure (Curve X)) : Prop := + ∃ o : X, ∃ R : ℝ, 0 < R ∧ ∀ᵐ γ ∂π, ∀ t : Time, dist (γ t) o ≤ R + +def LocallyL2 (m : Measure X) (f : X → ℝ) : Prop := + ∀ o : X, ∀ R : ℝ, 0 < R → MemLp f 2 (m.restrict (Metric.ball o R)) + +/-- Local weak upper gradients, in the integrated test-plan definition. -/ +def IsLocalWeakUpperGradient (m : Measure X) (f D : X → ℝ) : Prop := + LocallyL2 m D ∧ (∀ᵐ x ∂m, 0 ≤ D x) ∧ + ∀ π : Measure (Curve X), IsTestPlan m π → BoundedTracks π → + (∫⁻ γ, ENNReal.ofReal |f (γ timeOne) - f (γ timeZero)| ∂π) ≤ + ∫⁻ γ, ∫⁻ t in Set.Icc (0 : ℝ) 1, + ENNReal.ofReal (D (evalReal γ t)) * metricSpeed γ t ∂volume ∂π + +def IsMinimalLocalWeakUpperGradient (m : Measure X) (f D : X → ℝ) : Prop := + IsLocalWeakUpperGradient m f D ∧ + ∀ D' : X → ℝ, IsLocalWeakUpperGradient m f D' → ∀ᵐ x ∂m, D x ≤ D' x + +/-- A representative of the minimal weak upper gradient (zero off its domain). -/ +def weakGradient (m : Measure X) (f : X → ℝ) : X → ℝ := + if h : ∃ D, IsMinimalLocalWeakUpperGradient m f D then Classical.choose h + else 0 + +def LocalSobolev (m : Measure X) (f : X → ℝ) : Prop := + LocallyL2 m f ∧ ∃ D, IsMinimalLocalWeakUpperGradient m f D + +def Sobolev (m : Measure X) (f : X → ℝ) : Prop := + MemLp f 2 m ∧ LocalSobolev m f ∧ MemLp (weakGradient m f) 2 m + +/-- Polarization of the minimal weak gradient on an infinitesimally Hilbertian space. -/ +def gamma (m : Measure X) (f g : X → ℝ) (x : X) : ℝ := + ((weakGradient m (fun y => f y + g y) x) ^ 2 - + (weakGradient m (fun y => f y - g y) x) ^ 2) / 4 + +/-- Weak nonpositive generator convention, without a global L² assumption on F. -/ +def IsLaplacian (m : Measure X) (u L : X → ℝ) : Prop := + Sobolev m u ∧ MemLp L 2 m ∧ + ∀ v : X → ℝ, Sobolev m v → + (∫ x, gamma m u v x ∂m) = -(∫ x, L x * v x ∂m) + +def InLaplacianDomain (m : Measure X) (u : X → ℝ) : Prop := + ∃ L, IsLaplacian m u L + +def laplacian (m : Measure X) (u : X → ℝ) : X → ℝ := + if h : ∃ L, IsLaplacian m u L then Classical.choose h else 0 + +def BoundedFunction (f : X → ℝ) : Prop := ∃ B : ℝ, ∀ x, |f x| ≤ B + +def GloballyLipschitz (f : X → ℝ) : Prop := ∃ L : ℝ≥0, LipschitzWith L f + +/-- Bounded globally Lipschitz Laplacian-domain functions with Sobolev Laplacian. -/ +def IsTestFunction (m : Measure X) (g : X → ℝ) : Prop := + InLaplacianDomain m g ∧ BoundedFunction g ∧ GloballyLipschitz g ∧ + Sobolev m (laplacian m g) + +/-- The weak Hessian, with ∇_(∇g)∇g = ∇(Γ(g)/2). -/ +def weakHessian (m : Measure X) (F g h : X → ℝ) : ℝ := + -(∫ x, (gamma m h g x + h x * laplacian m g x) * gamma m F g x ∂m) - + ∫ x, h x * gamma m F (fun y => gamma m g g y / 2) x ∂m + +def WeakHessianUpperBound (m : Measure X) (F G : X → ℝ) : Prop := + ∀ g : X → ℝ, IsTestFunction m g → HasCompactSupport g → + ∀ h : X → ℝ, GloballyLipschitz h → HasCompactSupport h → + (∀ x, 0 ≤ h x) → + weakHessian m F g h ≤ ∫ x, h x * G x * gamma m g g x ∂m + +/-- Asymptotic Lipschitz slope; zero at an isolated point. -/ +def localSlope (f : X → ℝ) (x : X) : ℝ≥0∞ := + Filter.limsup (fun y => ENNReal.ofReal (|f y - f x| / dist y x)) (𝓝[≠] x) + +/-- Cheeger energy is the L² relaxation of one half the squared local slope. -/ +def cheegerEnergy (m : Measure X) (f : X → ℝ) : ℝ≥0∞ := + if MemLp f 2 m then + sInf {a | ∃ fs : ℕ → X → ℝ, + (∀ n, GloballyLipschitz (fs n) ∧ MemLp (fs n) 2 m) ∧ + Tendsto (fun n => eLpNorm (fun x => fs n x - f x) 2 m) atTop (𝓝 0) ∧ + a = Filter.liminf (fun n => (2 : ℝ≥0∞)⁻¹ * + ∫⁻ x, (localSlope (fs n) x) ^ 2 ∂m) atTop} + else ∞ + +def QuadraticCheegerEnergy (m : Measure X) : Prop := + ∀ f g : X → ℝ, cheegerEnergy m f < ∞ → cheegerEnergy m g < ∞ → + cheegerEnergy m (fun x => f x + g x) + cheegerEnergy m (fun x => f x - g x) = + 2 * cheegerEnergy m f + 2 * cheegerEnergy m g + +/-- The unreduced Lott–Sturm–Villani distortion coefficient σ. -/ +def sigmaCoeff (K N t θ : ℝ) : ℝ≥0∞ := + if t ≤ 0 then 0 else if 1 ≤ t then 1 else + if θ = 0 then ENNReal.ofReal t else + if 0 < K then + if K * θ ^ 2 < N * Real.pi ^ 2 then + ENNReal.ofReal (Real.sin (t * θ * Real.sqrt (K / N)) / + Real.sin (θ * Real.sqrt (K / N))) + else ∞ + else if K = 0 then ENNReal.ofReal t else + ENNReal.ofReal (Real.sinh (t * θ * Real.sqrt (-K / N)) / + Real.sinh (θ * Real.sqrt (-K / N))) + +/-- The τ coefficient (not the reduced σ coefficient) in CD(K,N). -/ +def tauCoeff (K N t θ : ℝ) : ℝ≥0∞ := + (ENNReal.ofReal t) ^ (1 / N) * (sigmaCoeff K (N - 1) t θ) ^ ((N - 1) / N) + +def HasSecondMoment (μ : Measure X) : Prop := + ∃ o : X, (∫⁻ x, (edist x o) ^ 2 ∂μ) < ∞ + +def IsCoupling (q : Measure (X × X)) (μ₀ μ₁ : Measure X) : Prop := + Measure.map Prod.fst q = μ₀ ∧ Measure.map Prod.snd q = μ₁ + +def QuadraticTransportCost (q : Measure (X × X)) : ℝ≥0∞ := + ∫⁻ p, (edist p.1 p.2) ^ 2 ∂q + +def IsOptimalCoupling (q : Measure (X × X)) (μ₀ μ₁ : Measure X) : Prop := + IsCoupling q μ₀ μ₁ ∧ ∀ q' : Measure (X × X), IsCoupling q' μ₀ μ₁ → + QuadraticTransportCost q ≤ QuadraticTransportCost q' + +def endpointCoupling (π : Measure (Curve X)) : Measure (X × X) := + Measure.map (fun γ : Curve X => (γ timeZero, γ timeOne)) π + +def interpolation (π : Measure (Curve X)) (t : Time) : Measure X := + Measure.map (fun γ : Curve X => γ t) π + +/-- The positive of minus the N-Rényi entropy; singular mass contributes zero. -/ +def renyiIntegral (m μ : Measure X) (N : ℝ) : ℝ≥0∞ := + ∫⁻ x, (μ.rnDeriv m x) ^ (1 - 1 / N) ∂m + +/-- Unreduced CD(K,N), written with the standard dynamical optimal-plan formula. -/ +def CurvatureDimension (m : Measure X) (K N : ℝ) : Prop := + ∀ μ₀ μ₁ : Measure X, + IsProbabilityMeasure μ₀ → IsProbabilityMeasure μ₁ → + HasSecondMoment μ₀ → HasSecondMoment μ₁ → + μ₀ ≪ m → μ₁ ≪ m → + ∃ π : Measure (Curve X), IsProbabilityMeasure π ∧ + (∀ᵐ γ ∂π, IsGeodesic γ) ∧ + IsOptimalCoupling (endpointCoupling π) μ₀ μ₁ ∧ + ∀ N' : ℝ, N ≤ N' → ∀ t : Time, + (∫⁻ γ, + (tauCoeff K N' (1 - (t : ℝ)) (dist (γ timeZero) (γ timeOne)) * + (μ₀.rnDeriv m (γ timeZero)) ^ (-1 / N') + + tauCoeff K N' (t : ℝ) (dist (γ timeZero) (γ timeOne)) * + (μ₁.rnDeriv m (γ timeOne)) ^ (-1 / N')) ∂π) ≤ + renyiIntegral m (interpolation π t) N' + +def RCD (m : Measure X) (K N : ℝ) : Prop := + CurvatureDimension m K N ∧ QuadraticCheegerEnergy m + +def FullSupport (m : Measure X) : Prop := + ∀ U : Set X, IsOpen U → U.Nonempty → 0 < m U + +def FiniteOnBoundedSets (m : Measure X) : Prop := + ∀ B : Set X, Bornology.IsBounded B → m B < ∞ + +/-- The literal second-distributional-derivative conclusion on (0,1). -/ +def CurveSecondDerivativeBound (F G : X → ℝ) (σ : Curve X) : Prop := + ∀ φ : ℝ → ℝ, ContDiff ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) φ → HasCompactSupport φ → + tsupport φ ⊆ Set.Ioo (0 : ℝ) 1 → (∀ t, 0 ≤ φ t) → + (∫ t in Set.Icc (0 : ℝ) 1, + F (evalReal σ t) * deriv (deriv φ) t) ≤ + (dist (σ timeZero) (σ timeOne)) ^ 2 * + ∫ t in Set.Icc (0 : ℝ) 1, G (evalReal σ t) * φ t + +/-- A weak upper Hessian bound controls the second distributional derivative +along every constant-speed minimizing geodesic. -/ +theorem every_geodesic [CompleteSpace X] [TopologicalSpace.SeparableSpace X] + (m : Measure X) (K N : ℝ) (hN : 1 < N) + (hfull : FullSupport m) (hfinite : FiniteOnBoundedSets m) (hrcd : RCD m K N) + (F G : X → ℝ) (hFbound : BoundedFunction F) (hFlip : GloballyLipschitz F) + (hGbound : BoundedFunction G) (hGcont : Continuous G) + (hHess : WeakHessianUpperBound m F G) + (σ : Curve X) (hσ : IsGeodesic σ) : CurveSecondDerivativeBound F G σ := by + sorry + +end WeakHessian + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WeakHessian.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WeakHessian.every_geodesic` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/weak-hessian/solution/closure.txt b/tasks/weak-hessian/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..25045d2dbd1b0c087081442be4ccb29efefbcf3c --- /dev/null +++ b/tasks/weak-hessian/solution/closure.txt @@ -0,0 +1,542 @@ +OAI.Geometry.WeakHessian.Calculus.CompactAnchoredControl +OAI.Geometry.WeakHessian.Calculus.CompactCoreAnnihilator +OAI.Geometry.WeakHessian.Calculus.CompactCoreEquation +OAI.Geometry.WeakHessian.Calculus.CompactCoreForm +OAI.Geometry.WeakHessian.Calculus.CompactCoreIdentity +OAI.Geometry.WeakHessian.Calculus.CompactCoreLocalization +OAI.Geometry.WeakHessian.Calculus.CompactCoreRegularity +OAI.Geometry.WeakHessian.Calculus.CompactCost +OAI.Geometry.WeakHessian.Calculus.CompactEVI +OAI.Geometry.WeakHessian.Calculus.CompactHopf +OAI.Geometry.WeakHessian.Calculus.CompactHopfCurve +OAI.Geometry.WeakHessian.Calculus.CompactHopfDualLimit +OAI.Geometry.WeakHessian.Calculus.CompactLipDense +OAI.Geometry.WeakHessian.Calculus.CompactOriginalCore +OAI.Geometry.WeakHessian.Calculus.CompactSlopeApprox +OAI.Geometry.WeakHessian.Calculus.CompactThickenedIndicator +OAI.Geometry.WeakHessian.Calculus.ControlNorm +OAI.Geometry.WeakHessian.Calculus.DerivSinSubMul +OAI.Geometry.WeakHessian.Calculus.DominatedCompactRerouting +OAI.Geometry.WeakHessian.Calculus.DriftRadialLimit +OAI.Geometry.WeakHessian.Calculus.DualLimits +OAI.Geometry.WeakHessian.Calculus.ELpNormSq +OAI.Geometry.WeakHessian.Calculus.FormLimits +OAI.Geometry.WeakHessian.Calculus.GammaLimits +OAI.Geometry.WeakHessian.Calculus.IntegralEvalDifference +OAI.Geometry.WeakHessian.Calculus.IntegralHopfInitial +OAI.Geometry.WeakHessian.Calculus.IntegralSqFatou +OAI.Geometry.WeakHessian.Calculus.InverseSqrtIntegral +OAI.Geometry.WeakHessian.Calculus.LipschitzDerivQuadraticRemainder +OAI.Geometry.WeakHessian.Calculus.LipschitzMulCompact +OAI.Geometry.WeakHessian.Calculus.LipschitzPointLimit +OAI.Geometry.WeakHessian.Calculus.LocalDistribution +OAI.Geometry.WeakHessian.Calculus.NoncompactCost +OAI.Geometry.WeakHessian.Calculus.NoncompactOptimal +OAI.Geometry.WeakHessian.Calculus.NormLpSqIntegral +OAI.Geometry.WeakHessian.Calculus.NormSqLintegralEnorm +OAI.Geometry.WeakHessian.Calculus.NormalizedRadial +OAI.Geometry.WeakHessian.Calculus.NormalizedRoots +OAI.Geometry.WeakHessian.Calculus.PotentialCompactness +OAI.Geometry.WeakHessian.Calculus.QuadraticCompactness +OAI.Geometry.WeakHessian.Calculus.QuadraticCostLimit +OAI.Geometry.WeakHessian.Calculus.RadialGammaLimit +OAI.Geometry.WeakHessian.Calculus.ReversePoincareIntegral +OAI.Geometry.WeakHessian.Calculus.RightEndpointDerivative +OAI.Geometry.WeakHessian.Calculus.RnDerivRestrictReference +OAI.Geometry.WeakHessian.Calculus.RnDerivSmul +OAI.Geometry.WeakHessian.Calculus.ScalarLocalBound +OAI.Geometry.WeakHessian.Calculus.ScalarSecondDifference +OAI.Geometry.WeakHessian.Calculus.TendstoIntegralBoundedPairing +OAI.Geometry.WeakHessian.Calculus.TriangularFoldNorm +OAI.Geometry.WeakHessian.Calculus.VariableDissipationLimits +OAI.Geometry.WeakHessian.Curvature.DecayWeight +OAI.Geometry.WeakHessian.Curvature.Doubling +OAI.Geometry.WeakHessian.Curvature.GammaCurvatureLowerBound +OAI.Geometry.WeakHessian.Curvature.Nonbranching +OAI.Geometry.WeakHessian.Entropy.AcBoundedRenyiGaps +OAI.Geometry.WeakHessian.Entropy.AveragedDensity +OAI.Geometry.WeakHessian.Entropy.BoundedLipschitzDensity +OAI.Geometry.WeakHessian.Entropy.CdEntropyBoundFinite +OAI.Geometry.WeakHessian.Entropy.CenteredMulLogDeriv +OAI.Geometry.WeakHessian.Entropy.ClosedEntropyAlong +OAI.Geometry.WeakHessian.Entropy.CompressedDensity +OAI.Geometry.WeakHessian.Entropy.CostTopology +OAI.Geometry.WeakHessian.Entropy.DensityConvergence +OAI.Geometry.WeakHessian.Entropy.DensityCurve +OAI.Geometry.WeakHessian.Entropy.DensityHamiltonJacobi +OAI.Geometry.WeakHessian.Entropy.EntropyCell +OAI.Geometry.WeakHessian.Entropy.EntropyContact +OAI.Geometry.WeakHessian.Entropy.EntropyDensityBounds +OAI.Geometry.WeakHessian.Entropy.EntropyDrop +OAI.Geometry.WeakHessian.Entropy.EntropyLimits +OAI.Geometry.WeakHessian.Entropy.EntropyPairingLimits +OAI.Geometry.WeakHessian.Entropy.EntropyRealContinuousSupport +OAI.Geometry.WeakHessian.Entropy.EntropySlope +OAI.Geometry.WeakHessian.Entropy.EntropyStability +OAI.Geometry.WeakHessian.Entropy.ExplicitDensityNorm +OAI.Geometry.WeakHessian.Entropy.FiniteEntropy +OAI.Geometry.WeakHessian.Entropy.FiniteEntropyBoundedSupported +OAI.Geometry.WeakHessian.Entropy.FisherDensity +OAI.Geometry.WeakHessian.Entropy.FisherEpsilon +OAI.Geometry.WeakHessian.Entropy.FisherRoot +OAI.Geometry.WeakHessian.Entropy.GradientParallelogramDefect +OAI.Geometry.WeakHessian.Entropy.IntegralDensityMeasureLp +OAI.Geometry.WeakHessian.Entropy.IntegralDensityMeasureLp' +OAI.Geometry.WeakHessian.Entropy.IntervalEntropyDual +OAI.Geometry.WeakHessian.Entropy.LinearDensity +OAI.Geometry.WeakHessian.Entropy.LocalGradientParallelogram +OAI.Geometry.WeakHessian.Entropy.LocalGradientParallelogramCheeger +OAI.Geometry.WeakHessian.Entropy.LocalizedFisher +OAI.Geometry.WeakHessian.Entropy.LogAddTwoSqrt +OAI.Geometry.WeakHessian.Entropy.MulLogFenchel +OAI.Geometry.WeakHessian.Entropy.NonnegativeParallelogram +OAI.Geometry.WeakHessian.Entropy.PolarAddFourParallelograms +OAI.Geometry.WeakHessian.Entropy.QuadraticEntropyPairing +OAI.Geometry.WeakHessian.Entropy.RadialEntropy +OAI.Geometry.WeakHessian.Entropy.ReducedEntropy +OAI.Geometry.WeakHessian.Entropy.ReducedEntropyDual +OAI.Geometry.WeakHessian.Entropy.RegularizedEntropyIntegrable +OAI.Geometry.WeakHessian.Entropy.RenormalizedEntropy +OAI.Geometry.WeakHessian.Entropy.RenyiKernel +OAI.Geometry.WeakHessian.Entropy.ScalarEntropyLog +OAI.Geometry.WeakHessian.Entropy.SmoothDensity +OAI.Geometry.WeakHessian.Entropy.SobolevFisher +OAI.Geometry.WeakHessian.Entropy.StrongEntropyConfinement +OAI.Geometry.WeakHessian.Entropy.TauDensityLinearLower +OAI.Geometry.WeakHessian.Entropy.TendstoRenyiGap +OAI.Geometry.WeakHessian.Entropy.TruncatedLog +OAI.Geometry.WeakHessian.Entropy.WeightedParallelogramIntegral +OAI.Geometry.WeakHessian.Entropy.ZeroDensity +OAI.Geometry.WeakHessian.Geodesics.CdLogMidpointBall +OAI.Geometry.WeakHessian.Geodesics.GeodesicPlanSupportedBall +OAI.Geometry.WeakHessian.Geodesics.Join +OAI.Geometry.WeakHessian.Geodesics.LocalMidpoint +OAI.Geometry.WeakHessian.Geodesics.LocalTwoLegLimit +OAI.Geometry.WeakHessian.Geodesics.MidpointDualTests +OAI.Geometry.WeakHessian.Geodesics.MidpointSigmaLower +OAI.Geometry.WeakHessian.Geodesics.SquareControl +OAI.Geometry.WeakHessian.Geodesics.TwoLegEstimate +OAI.Geometry.WeakHessian.Geodesics.TwoLegLimit +OAI.Geometry.WeakHessian.HeatFlow.BoundedSecondGenerator +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeat +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatAbs +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatBoundedPairing +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatContinuous +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatDavies +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatEntropyDissipation +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatEntropyHopf +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatFisherFinite +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatFisherTransport +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatHopfAction +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatLaplacianIntegral +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatMassNonneg +OAI.Geometry.WeakHessian.HeatFlow.CheegerHeatMassWeighted +OAI.Geometry.WeakHessian.HeatFlow.CheegerResolventDavies +OAI.Geometry.WeakHessian.HeatFlow.CheegerScaledResolventNonneg +OAI.Geometry.WeakHessian.HeatFlow.CommonLocalHeatLegs +OAI.Geometry.WeakHessian.HeatFlow.CompactGeneratorRange +OAI.Geometry.WeakHessian.HeatFlow.CompactHeatPairing +OAI.Geometry.WeakHessian.HeatFlow.DriftHeatFullDomain +OAI.Geometry.WeakHessian.HeatFlow.DriftHeatGenerator +OAI.Geometry.WeakHessian.HeatFlow.DriftHeatGradient +OAI.Geometry.WeakHessian.HeatFlow.DriftHeatSobolev +OAI.Geometry.WeakHessian.HeatFlow.DriftHeatSobolevPointwise +OAI.Geometry.WeakHessian.HeatFlow.DriftResolvent +OAI.Geometry.WeakHessian.HeatFlow.DualHeatPairing +OAI.Geometry.WeakHessian.HeatFlow.EulerStepGenerator +OAI.Geometry.WeakHessian.HeatFlow.FormGenerator +OAI.Geometry.WeakHessian.HeatFlow.FormGeneratorSymmetric +OAI.Geometry.WeakHessian.HeatFlow.FormGeneratorYoung +OAI.Geometry.WeakHessian.HeatFlow.GeneratorEnergyDifferentiation +OAI.Geometry.WeakHessian.HeatFlow.GeneratorSubgradient +OAI.Geometry.WeakHessian.HeatFlow.HeatAction +OAI.Geometry.WeakHessian.HeatFlow.HeatAverage +OAI.Geometry.WeakHessian.HeatFlow.HeatBoundedRegularization +OAI.Geometry.WeakHessian.HeatFlow.HeatBridge +OAI.Geometry.WeakHessian.HeatFlow.HeatCZero +OAI.Geometry.WeakHessian.HeatFlow.HeatClassical +OAI.Geometry.WeakHessian.HeatFlow.HeatComparison +OAI.Geometry.WeakHessian.HeatFlow.HeatContraction +OAI.Geometry.WeakHessian.HeatFlow.HeatCost +OAI.Geometry.WeakHessian.HeatFlow.HeatCostTopology +OAI.Geometry.WeakHessian.HeatFlow.HeatDensity +OAI.Geometry.WeakHessian.HeatFlow.HeatDensityCouplingCost +OAI.Geometry.WeakHessian.HeatFlow.HeatDensityCouplingForward +OAI.Geometry.WeakHessian.HeatFlow.HeatDiagonal +OAI.Geometry.WeakHessian.HeatFlow.HeatDifferential +OAI.Geometry.WeakHessian.HeatFlow.HeatEVI +OAI.Geometry.WeakHessian.HeatFlow.HeatEnergyContinuity +OAI.Geometry.WeakHessian.HeatFlow.HeatEnergyQuotient +OAI.Geometry.WeakHessian.HeatFlow.HeatEntropyContinuity +OAI.Geometry.WeakHessian.HeatFlow.HeatEntropyTransport +OAI.Geometry.WeakHessian.HeatFlow.HeatFormContinuous +OAI.Geometry.WeakHessian.HeatFlow.HeatGeneratorOperator +OAI.Geometry.WeakHessian.HeatFlow.HeatHopfPlanContinuity +OAI.Geometry.WeakHessian.HeatFlow.HeatIntegralSmoothing +OAI.Geometry.WeakHessian.HeatFlow.HeatInverseSymbol +OAI.Geometry.WeakHessian.HeatFlow.HeatLipschitz +OAI.Geometry.WeakHessian.HeatFlow.HeatPositiveDerivative +OAI.Geometry.WeakHessian.HeatFlow.HeatProbability +OAI.Geometry.WeakHessian.HeatFlow.HeatSmoothingCoefficient +OAI.Geometry.WeakHessian.HeatFlow.HeatSobolevTime +OAI.Geometry.WeakHessian.HeatFlow.HeatSymbol +OAI.Geometry.WeakHessian.HeatFlow.HeatVarianceDerivative +OAI.Geometry.WeakHessian.HeatFlow.HopfHeatCommutation +OAI.Geometry.WeakHessian.HeatFlow.InitialHeatLimit +OAI.Geometry.WeakHessian.HeatFlow.LaplacianResolventUnique +OAI.Geometry.WeakHessian.HeatFlow.MixedGeneratorPairing +OAI.Geometry.WeakHessian.HeatFlow.PlanHeatEntropy +OAI.Geometry.WeakHessian.HeatFlow.PointwiseHeatGradient +OAI.Geometry.WeakHessian.HeatFlow.RealHeat +OAI.Geometry.WeakHessian.HeatFlow.RealHeatRangeError +OAI.Geometry.WeakHessian.HeatFlow.ResolventEVI +OAI.Geometry.WeakHessian.HeatFlow.ResolventEnergy +OAI.Geometry.WeakHessian.HeatFlow.ResolventGraphConvergence +OAI.Geometry.WeakHessian.HeatFlow.ResolventSmoothing +OAI.Geometry.WeakHessian.HeatFlow.ScaledResolventCfc +OAI.Geometry.WeakHessian.HeatFlow.SharpHeatGradient +OAI.Geometry.WeakHessian.HeatFlow.SobolevHeatPairing +OAI.Geometry.WeakHessian.HeatFlow.SpatialHeat +OAI.Geometry.WeakHessian.HeatFlow.SquareGeneratorPairing +OAI.Geometry.WeakHessian.HeatFlow.StrictSurplusCarrier +OAI.Geometry.WeakHessian.HeatFlow.VariableDissipationGenerator +OAI.Geometry.WeakHessian.HeatFlow.WeightedDriftResolvent +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatBE +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatConcentration +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatCostAction +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatCurvatureContinuity +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatEndpointAction +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatFTC +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatGammaContinuity +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatGammaL2 +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatGradient +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatGradientTest +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatHamiltonJacobi +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatHopfPointwise +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatInterpolation +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatLaw +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatLawDual +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatPairing +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatPlanAction +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatRegularity +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatSmoothing +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatSmoothingCore +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatTransportCoupling +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatVariableDissipation +OAI.Geometry.WeakHessian.HeatFlow.WeightedHeatVariance +OAI.Geometry.WeakHessian.HeatFlow.WeightedHopfHeatCommutation +OAI.Geometry.WeakHessian.LocalBounds.AbsGammaLipschitz +OAI.Geometry.WeakHessian.LocalBounds.AbsolutelyContinuousDistDom +OAI.Geometry.WeakHessian.LocalBounds.ActualCore +OAI.Geometry.WeakHessian.LocalBounds.AffineTime +OAI.Geometry.WeakHessian.LocalBounds.AscendingSlope +OAI.Geometry.WeakHessian.LocalBounds.AverageConvergence +OAI.Geometry.WeakHessian.LocalBounds.AverageLipschitz +OAI.Geometry.WeakHessian.LocalBounds.AverageTest +OAI.Geometry.WeakHessian.LocalBounds.AverageWeighted +OAI.Geometry.WeakHessian.LocalBounds.BoundedCost +OAI.Geometry.WeakHessian.LocalBounds.BoundedDriftFixedPoint +OAI.Geometry.WeakHessian.LocalBounds.BoundedDriftRegularity +OAI.Geometry.WeakHessian.LocalBounds.BoundedEndpointTube +OAI.Geometry.WeakHessian.LocalBounds.BoundedGraphCore +OAI.Geometry.WeakHessian.LocalBounds.BoundedLawDualPointwise +OAI.Geometry.WeakHessian.LocalBounds.BoundedMulLp +OAI.Geometry.WeakHessian.LocalBounds.BoundedMulLpTendsto +OAI.Geometry.WeakHessian.LocalBounds.BoundedRnRestriction +OAI.Geometry.WeakHessian.LocalBounds.CaccioppoliAlgebra +OAI.Geometry.WeakHessian.LocalBounds.CappedExcess +OAI.Geometry.WeakHessian.LocalBounds.ChangeLpLp +OAI.Geometry.WeakHessian.LocalBounds.ClampTimeVal +OAI.Geometry.WeakHessian.LocalBounds.ClosedQuadraticEnergy +OAI.Geometry.WeakHessian.LocalBounds.ComplexifyReal +OAI.Geometry.WeakHessian.LocalBounds.CompressionRate +OAI.Geometry.WeakHessian.LocalBounds.Confinement +OAI.Geometry.WeakHessian.LocalBounds.ConstLp +OAI.Geometry.WeakHessian.LocalBounds.ConstMul +OAI.Geometry.WeakHessian.LocalBounds.ContactUniqueness +OAI.Geometry.WeakHessian.LocalBounds.ContinuousTimeMarginals +OAI.Geometry.WeakHessian.LocalBounds.CoreAlgebra +OAI.Geometry.WeakHessian.LocalBounds.CostContinuity +OAI.Geometry.WeakHessian.LocalBounds.CostConvergence +OAI.Geometry.WeakHessian.LocalBounds.CostExistence +OAI.Geometry.WeakHessian.LocalBounds.CostMetric +OAI.Geometry.WeakHessian.LocalBounds.DecayTimesNatTwo +OAI.Geometry.WeakHessian.LocalBounds.DistDecayCover +OAI.Geometry.WeakHessian.LocalBounds.Domain +OAI.Geometry.WeakHessian.LocalBounds.DriftFixedBase +OAI.Geometry.WeakHessian.LocalBounds.DriftPerturbation +OAI.Geometry.WeakHessian.LocalBounds.DriftQuantitative +OAI.Geometry.WeakHessian.LocalBounds.DuhamelAlgebra +OAI.Geometry.WeakHessian.LocalBounds.DyadicTimes +OAI.Geometry.WeakHessian.LocalBounds.EVICalculus +OAI.Geometry.WeakHessian.LocalBounds.EnergyGammaPairing +OAI.Geometry.WeakHessian.LocalBounds.EnergyIdentification +OAI.Geometry.WeakHessian.LocalBounds.EulerStep +OAI.Geometry.WeakHessian.LocalBounds.EvalRealCoe +OAI.Geometry.WeakHessian.LocalBounds.ExcessRelocation +OAI.Geometry.WeakHessian.LocalBounds.ExpMulLp +OAI.Geometry.WeakHessian.LocalBounds.ExpNegQuadraticBound +OAI.Geometry.WeakHessian.LocalBounds.ExponentialODE +OAI.Geometry.WeakHessian.LocalBounds.ExtendLp +OAI.Geometry.WeakHessian.LocalBounds.FormCoreDense +OAI.Geometry.WeakHessian.LocalBounds.FormCorePairing +OAI.Geometry.WeakHessian.LocalBounds.FormDualRegularity +OAI.Geometry.WeakHessian.LocalBounds.FormGamma +OAI.Geometry.WeakHessian.LocalBounds.GammaAddConstLeft +OAI.Geometry.WeakHessian.LocalBounds.GammaNatMulLeft +OAI.Geometry.WeakHessian.LocalBounds.GammaRepresentativePairing +OAI.Geometry.WeakHessian.LocalBounds.GammaTimeDifferentiation +OAI.Geometry.WeakHessian.LocalBounds.GammaVariableContinuity +OAI.Geometry.WeakHessian.LocalBounds.GlobalMultiplierCore +OAI.Geometry.WeakHessian.LocalBounds.GlobalTestAverage +OAI.Geometry.WeakHessian.LocalBounds.GlobalTestCore +OAI.Geometry.WeakHessian.LocalBounds.GraphFilter +OAI.Geometry.WeakHessian.LocalBounds.GraphGammaPairing +OAI.Geometry.WeakHessian.LocalBounds.GraphReuse +OAI.Geometry.WeakHessian.LocalBounds.HalfTime +OAI.Geometry.WeakHessian.LocalBounds.HopfEnergyComparison +OAI.Geometry.WeakHessian.LocalBounds.HopfEnergyInitial +OAI.Geometry.WeakHessian.LocalBounds.HopfEnergyLower +OAI.Geometry.WeakHessian.LocalBounds.HopfInitialSlope +OAI.Geometry.WeakHessian.LocalBounds.HopfWeightedEnergy +OAI.Geometry.WeakHessian.LocalBounds.IdentifiedConservation +OAI.Geometry.WeakHessian.LocalBounds.InclusionDoubleDualSurjective +OAI.Geometry.WeakHessian.LocalBounds.IntegratedEVI +OAI.Geometry.WeakHessian.LocalBounds.JoinCurve +OAI.Geometry.WeakHessian.LocalBounds.L2SlopeGraph +OAI.Geometry.WeakHessian.LocalBounds.Law +OAI.Geometry.WeakHessian.LocalBounds.LipschitzMulDist +OAI.Geometry.WeakHessian.LocalBounds.LocalOffset +OAI.Geometry.WeakHessian.LocalBounds.LocalPairing +OAI.Geometry.WeakHessian.LocalBounds.LocalizedCertificate +OAI.Geometry.WeakHessian.LocalBounds.LocalizedScaling +OAI.Geometry.WeakHessian.LocalBounds.LocalizedSlopeGraphMap +OAI.Geometry.WeakHessian.LocalBounds.LpLipschitzClosed +OAI.Geometry.WeakHessian.LocalBounds.MetricPlateau +OAI.Geometry.WeakHessian.LocalBounds.MinNatTendsto +OAI.Geometry.WeakHessian.LocalBounds.MulBounded +OAI.Geometry.WeakHessian.LocalBounds.OneSidedBump +OAI.Geometry.WeakHessian.LocalBounds.OneSidedKernel +OAI.Geometry.WeakHessian.LocalBounds.OriginalCoreProducer +OAI.Geometry.WeakHessian.LocalBounds.PositiveProbes +OAI.Geometry.WeakHessian.LocalBounds.PotentialPairing +OAI.Geometry.WeakHessian.LocalBounds.QuadraticContact +OAI.Geometry.WeakHessian.LocalBounds.QuadraticCost +OAI.Geometry.WeakHessian.LocalBounds.QuadraticPairing +OAI.Geometry.WeakHessian.LocalBounds.QuadraticPotentials +OAI.Geometry.WeakHessian.LocalBounds.QuadraticVariational +OAI.Geometry.WeakHessian.LocalBounds.RadialCost +OAI.Geometry.WeakHessian.LocalBounds.RadialRoots +OAI.Geometry.WeakHessian.LocalBounds.ReLp +OAI.Geometry.WeakHessian.LocalBounds.RealClip +OAI.Geometry.WeakHessian.LocalBounds.RelaxedDomain +OAI.Geometry.WeakHessian.LocalBounds.RelaxedProx +OAI.Geometry.WeakHessian.LocalBounds.ReversePoincarePointwise +OAI.Geometry.WeakHessian.LocalBounds.ReweightCost +OAI.Geometry.WeakHessian.LocalBounds.RootApproximation +OAI.Geometry.WeakHessian.LocalBounds.RunningMin +OAI.Geometry.WeakHessian.LocalBounds.SetDensities +OAI.Geometry.WeakHessian.LocalBounds.SharpPointwise +OAI.Geometry.WeakHessian.LocalBounds.SigmaCoeffExpLower +OAI.Geometry.WeakHessian.LocalBounds.SlopeApprox +OAI.Geometry.WeakHessian.LocalBounds.SlopeApproxAntitone +OAI.Geometry.WeakHessian.LocalBounds.SlopeApproxProduct +OAI.Geometry.WeakHessian.LocalBounds.Smul +OAI.Geometry.WeakHessian.LocalBounds.SpatialDual +OAI.Geometry.WeakHessian.LocalBounds.SpeedApprox +OAI.Geometry.WeakHessian.LocalBounds.SqrtWeighted +OAI.Geometry.WeakHessian.LocalBounds.SquareControl +OAI.Geometry.WeakHessian.LocalBounds.SquareTimePairing +OAI.Geometry.WeakHessian.LocalBounds.StrongRoots +OAI.Geometry.WeakHessian.LocalBounds.SubConst +OAI.Geometry.WeakHessian.LocalBounds.Subdifferential +OAI.Geometry.WeakHessian.LocalBounds.SuperpositionProper +OAI.Geometry.WeakHessian.LocalBounds.TargetEVI +OAI.Geometry.WeakHessian.LocalBounds.TestChain +OAI.Geometry.WeakHessian.LocalBounds.TestLinear +OAI.Geometry.WeakHessian.LocalBounds.TestProduct +OAI.Geometry.WeakHessian.LocalBounds.TestScaling +OAI.Geometry.WeakHessian.LocalBounds.TimeHalf +OAI.Geometry.WeakHessian.LocalBounds.TriangularFold +OAI.Geometry.WeakHessian.LocalBounds.TripleTimeContinuity +OAI.Geometry.WeakHessian.LocalBounds.TripleTimePairing +OAI.Geometry.WeakHessian.LocalBounds.UniformTestAverage +OAI.Geometry.WeakHessian.LocalBounds.UniformWeightedCZero +OAI.Geometry.WeakHessian.LocalBounds.VariableDissipationFullDomain +OAI.Geometry.WeakHessian.LocalBounds.VariableDissipationTest +OAI.Geometry.WeakHessian.LocalBounds.VariableDuhamelClosure +OAI.Geometry.WeakHessian.LocalBounds.VariableEnergyClosure +OAI.Geometry.WeakHessian.LocalBounds.VarianceContinuity +OAI.Geometry.WeakHessian.LocalBounds.VolumeLower +OAI.Geometry.WeakHessian.LocalBounds.WeightedBE +OAI.Geometry.WeakHessian.LocalBounds.WeightedCZero +OAI.Geometry.WeakHessian.LocalBounds.WeightedConservation +OAI.Geometry.WeakHessian.LocalBounds.WeightedEVI +OAI.Geometry.WeakHessian.LocalBounds.WeightedEnergyClosure +OAI.Geometry.WeakHessian.LocalBounds.WeightedEnergySpace +OAI.Geometry.WeakHessian.LocalBounds.WeightedGraphInequality +OAI.Geometry.WeakHessian.LocalBounds.WeightedInitialLaw +OAI.Geometry.WeakHessian.LocalBounds.WeightedPairing +OAI.Geometry.WeakHessian.LocalBounds.WeightedPairing2 +OAI.Geometry.WeakHessian.LocalBounds.WeightedReversePoincare +OAI.Geometry.WeakHessian.LocalBounds.WeightedTV +OAI.Geometry.WeakHessian.LocalBounds.Young +OAI.Geometry.WeakHessian.Main +OAI.Geometry.WeakHessian.Measure.AeDerivLevel +OAI.Geometry.WeakHessian.Measure.AeIntegralPositiveLipschitz +OAI.Geometry.WeakHessian.Measure.AeMinimumDominated +OAI.Geometry.WeakHessian.Measure.AeNonnegCompactIntegral +OAI.Geometry.WeakHessian.Measure.CurvatureTail +OAI.Geometry.WeakHessian.Measure.DaviesTail +OAI.Geometry.WeakHessian.Measure.DecayCutoffLp +OAI.Geometry.WeakHessian.Measure.GeneralCostSupport +OAI.Geometry.WeakHessian.Measure.InlinedFile0 +OAI.Geometry.WeakHessian.Measure.IntegrableExpBounded +OAI.Geometry.WeakHessian.Measure.IntegrableFatouNonneg +OAI.Geometry.WeakHessian.Measure.IntegralBoundedCutoffInner +OAI.Geometry.WeakHessian.Measure.IntegralExponentialMeasure +OAI.Geometry.WeakHessian.Measure.LocalSlopeNotMem +OAI.Geometry.WeakHessian.Measure.LocalizedTestCutoff +OAI.Geometry.WeakHessian.Measure.MeasurePositiveNegativeBalance +OAI.Geometry.WeakHessian.Measure.OptimalTimeLawSupported +OAI.Geometry.WeakHessian.Measure.RadialCutoff +OAI.Geometry.WeakHessian.Measure.RadialCutoffLp +OAI.Geometry.WeakHessian.Measure.TendstoIntegralNormSub +OAI.Geometry.WeakHessian.Measure.TimeMeasure +OAI.Geometry.WeakHessian.Model +OAI.Geometry.WeakHessian.Sobolev.AddConst +OAI.Geometry.WeakHessian.Sobolev.AeAcRepresentativeMeasurable +OAI.Geometry.WeakHessian.Sobolev.AeEndpointGlobal +OAI.Geometry.WeakHessian.Sobolev.AnySubgradient +OAI.Geometry.WeakHessian.Sobolev.BochnerConvex +OAI.Geometry.WeakHessian.Sobolev.CDSobolevLipschitz +OAI.Geometry.WeakHessian.Sobolev.CheegerClosedQuadraticEnergy +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergyComparable +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergyCongrAe +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergyConst +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergyMinimal +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergySlope +OAI.Geometry.WeakHessian.Sobolev.CheegerEnergyWeakBounded +OAI.Geometry.WeakHessian.Sobolev.CompContDiff +OAI.Geometry.WeakHessian.Sobolev.CompContDiff2 +OAI.Geometry.WeakHessian.Sobolev.CompContDiffLipschitz +OAI.Geometry.WeakHessian.Sobolev.CongrAeLeft +OAI.Geometry.WeakHessian.Sobolev.CutoffCheegerEnergy +OAI.Geometry.WeakHessian.Sobolev.DaviesGradient +OAI.Geometry.WeakHessian.Sobolev.EndpointPairingBound +OAI.Geometry.WeakHessian.Sobolev.EndpointPairingBoundGlobal +OAI.Geometry.WeakHessian.Sobolev.GlobalCheegerEnergyMinimal +OAI.Geometry.WeakHessian.Sobolev.GlobalCheegerEnergyReal +OAI.Geometry.WeakHessian.Sobolev.GlobalCheegerEnergyWeak +OAI.Geometry.WeakHessian.Sobolev.GradientPairSum +OAI.Geometry.WeakHessian.Sobolev.GradientProbes +OAI.Geometry.WeakHessian.Sobolev.GradientSquare +OAI.Geometry.WeakHessian.Sobolev.HessianMonotone +OAI.Geometry.WeakHessian.Sobolev.Integral +OAI.Geometry.WeakHessian.Sobolev.L2GradientGraph +OAI.Geometry.WeakHessian.Sobolev.LaplacianChain +OAI.Geometry.WeakHessian.Sobolev.LaplacianLocality +OAI.Geometry.WeakHessian.Sobolev.LipschitzBochnerIntegral +OAI.Geometry.WeakHessian.Sobolev.LocalMeasureGradient +OAI.Geometry.WeakHessian.Sobolev.LocalSobolevLipschitz +OAI.Geometry.WeakHessian.Sobolev.LocalizedGradient +OAI.Geometry.WeakHessian.Sobolev.Minimal +OAI.Geometry.WeakHessian.Sobolev.MulBounded +OAI.Geometry.WeakHessian.Sobolev.NoncompactSubgradient +OAI.Geometry.WeakHessian.Sobolev.NormMinimalRelaxedGradient +OAI.Geometry.WeakHessian.Sobolev.OriginalBochner +OAI.Geometry.WeakHessian.Sobolev.Piecewise +OAI.Geometry.WeakHessian.Sobolev.QuadraticCheegerEnergyComparable +OAI.Geometry.WeakHessian.Sobolev.QuadraticGradient +OAI.Geometry.WeakHessian.Sobolev.RadialGradientBound +OAI.Geometry.WeakHessian.Sobolev.SobolevBochner +OAI.Geometry.WeakHessian.Sobolev.SobolevCheegerEnergyTop +OAI.Geometry.WeakHessian.Sobolev.SobolevLipschitz +OAI.Geometry.WeakHessian.Sobolev.SobolevPairing +OAI.Geometry.WeakHessian.Sobolev.SobolevSubdifferential +OAI.Geometry.WeakHessian.Sobolev.SquareSobolev +OAI.Geometry.WeakHessian.Sobolev.TestBochner +OAI.Geometry.WeakHessian.Sobolev.UpperGradientNormTendsto +OAI.Geometry.WeakHessian.Sobolev.UpperGradientTendstoNorm +OAI.Geometry.WeakHessian.Sobolev.VariableDissipationSobolev +OAI.Geometry.WeakHessian.Sobolev.WeakGradientContactDistance +OAI.Geometry.WeakHessian.Sobolev.WeakGradientMul +OAI.Geometry.WeakHessian.Sobolev.WeightedGradientLoss +OAI.Geometry.WeakHessian.Transport.ActionDistPrimitiveValues +OAI.Geometry.WeakHessian.Transport.ActionIntervalIntegrable +OAI.Geometry.WeakHessian.Transport.AeActionData +OAI.Geometry.WeakHessian.Transport.AeEvalAe +OAI.Geometry.WeakHessian.Transport.AeProdMetricSpeed +OAI.Geometry.WeakHessian.Transport.BoundedHopfLpDual +OAI.Geometry.WeakHessian.Transport.BoundedHopfLpPairing +OAI.Geometry.WeakHessian.Transport.BoundedHopfMap +OAI.Geometry.WeakHessian.Transport.BoundedHopfMapLipschitz +OAI.Geometry.WeakHessian.Transport.BoundedHopfMapNorm +OAI.Geometry.WeakHessian.Transport.BoundedMarginalSum +OAI.Geometry.WeakHessian.Transport.BridgeError +OAI.Geometry.WeakHessian.Transport.CDPlanLeg +OAI.Geometry.WeakHessian.Transport.CcConst +OAI.Geometry.WeakHessian.Transport.CdEntropyPlanBounded +OAI.Geometry.WeakHessian.Transport.CompactBounded +OAI.Geometry.WeakHessian.Transport.CompactContraction +OAI.Geometry.WeakHessian.Transport.CouplingConcentration +OAI.Geometry.WeakHessian.Transport.CouplingCostBound +OAI.Geometry.WeakHessian.Transport.CouplingCostHopfBound +OAI.Geometry.WeakHessian.Transport.DensityCouplingBound +OAI.Geometry.WeakHessian.Transport.DensityMeasure +OAI.Geometry.WeakHessian.Transport.DerivEventuallyUpperRight +OAI.Geometry.WeakHessian.Transport.DriftLipschitzContraction +OAI.Geometry.WeakHessian.Transport.DualTransportPairing +OAI.Geometry.WeakHessian.Transport.DynamicActionBound +OAI.Geometry.WeakHessian.Transport.DynamicActionBoundProper +OAI.Geometry.WeakHessian.Transport.EVIContraction +OAI.Geometry.WeakHessian.Transport.EntropyAction +OAI.Geometry.WeakHessian.Transport.EntropyCoupling +OAI.Geometry.WeakHessian.Transport.FiniteLocalization +OAI.Geometry.WeakHessian.Transport.FormAction +OAI.Geometry.WeakHessian.Transport.HopfLaxScaleTime +OAI.Geometry.WeakHessian.Transport.HopfLpPairingIncrement +OAI.Geometry.WeakHessian.Transport.HopfLpTransportPairing +OAI.Geometry.WeakHessian.Transport.HopfMap +OAI.Geometry.WeakHessian.Transport.HopfObjective +OAI.Geometry.WeakHessian.Transport.IntegrableEvalBounded +OAI.Geometry.WeakHessian.Transport.IntegratedAction +OAI.Geometry.WeakHessian.Transport.JoinControl +OAI.Geometry.WeakHessian.Transport.JoinPlanPolish +OAI.Geometry.WeakHessian.Transport.KineticAction +OAI.Geometry.WeakHessian.Transport.LiftBoundedCoupling +OAI.Geometry.WeakHessian.Transport.LimitPlanEntropyBound +OAI.Geometry.WeakHessian.Transport.LipschitzTransport +OAI.Geometry.WeakHessian.Transport.LocalSlopeCompContraction +OAI.Geometry.WeakHessian.Transport.LocalizedActionBound +OAI.Geometry.WeakHessian.Transport.LocalizedPlanDual +OAI.Geometry.WeakHessian.Transport.LocalizedPlanLaw +OAI.Geometry.WeakHessian.Transport.MapCompProdComap +OAI.Geometry.WeakHessian.Transport.MapEvalReal +OAI.Geometry.WeakHessian.Transport.MeasurableVariableIntervalAction +OAI.Geometry.WeakHessian.Transport.OptimalPlansShort +OAI.Geometry.WeakHessian.Transport.PerturbedAction +OAI.Geometry.WeakHessian.Transport.PerturbedPlanDual +OAI.Geometry.WeakHessian.Transport.PlanAction +OAI.Geometry.WeakHessian.Transport.PlanComparisonLaw +OAI.Geometry.WeakHessian.Transport.PlanEnergy +OAI.Geometry.WeakHessian.Transport.PlanEntropyCoupling +OAI.Geometry.WeakHessian.Transport.PlanHamiltonJacobi +OAI.Geometry.WeakHessian.Transport.PlanHamiltonJacobiAction +OAI.Geometry.WeakHessian.Transport.PlanIncrement +OAI.Geometry.WeakHessian.Transport.ProbabilityTightMarginals +OAI.Geometry.WeakHessian.Transport.QuadraticCost +OAI.Geometry.WeakHessian.Transport.QuadraticCostIncrement +OAI.Geometry.WeakHessian.Transport.RerouteFiniteSubplanShort +OAI.Geometry.WeakHessian.Transport.RestrictCurve +OAI.Geometry.WeakHessian.Transport.ScaledPlanYoung +OAI.Geometry.WeakHessian.Transport.SmoothedPlanSupport +OAI.Geometry.WeakHessian.Transport.TestAction +OAI.Geometry.WeakHessian.Transport.TestPlanCostReference +OAI.Geometry.WeakHessian.Transport.TruncatedQuadraticCost +OAI.Geometry.WeakHessian.Transport.TwoCouplingCost +OAI.Geometry.WeakHessian.Transport.UpperEnvelope +OAI.Geometry.WeakHessian.Transport.VariationQuotient +OAI.Geometry.WeakHessian.Transport.WeightedEntropyCoupling +OAI.Geometry.WeakHessian.Transport.WeightedPlanComparison +OAI.Geometry.WeakHessian.Transport.WeightedPlanHamiltonJacobi diff --git a/tasks/weak-hessian/solution/reference.py b/tasks/weak-hessian/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/weak-hessian/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/weak-hessian/solution/solve.sh b/tasks/weak-hessian/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..b00d1645379c9253294190769d6a87d435099582 --- /dev/null +++ b/tasks/weak-hessian/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WeakHessian, i.e. module OAI.Geometry.WeakHessian.Main and the +# 542 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.WeakHessian.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WeakHessian" diff --git a/tasks/weak-hessian/task.toml b/tasks/weak-hessian/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..ba6a9b5d5c55b65ad3cf418c6b85b162dd1aef6c --- /dev/null +++ b/tasks/weak-hessian/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/weak-hessian" +version = "1.0.0" +description = "Prove WeakHessian (openai/math family 356: Gigli's characterization of Alexandrov curvature) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WeakHessian.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WeakHessian" +family = "356" +family_title = "Gigli's characterization of Alexandrov curvature" +subject = "Differential geometry" +theorems = ["OAI.WeakHessian.every_geodesic"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.WeakHessian.Main" +reference_modules = 542 +reference_lean_bytes = 3136506 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 1565 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14522 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/weak-hessian/tests/Challenge.lean b/tasks/weak-hessian/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..1feec821ba1b56fcf272bcb034005aba75f13691 --- /dev/null +++ b/tasks/weak-hessian/tests/Challenge.lean @@ -0,0 +1,233 @@ +import Mathlib + +namespace OAI + +open Set Filter MeasureTheory +open scoped ENNReal NNReal Topology + +noncomputable section +attribute [local instance] Classical.propDecidable +namespace WeakHessian + +abbrev Time := Set.Icc (0 : ℝ) 1 + +def timeZero : Time := ⟨0, le_rfl, zero_le_one⟩ +def timeOne : Time := ⟨1, zero_le_one, le_rfl⟩ + +def clampTime (t : ℝ) : Time := + ⟨max 0 (min 1 t), le_max_left _ _, max_le zero_le_one (min_le_left _ _)⟩ + +variable {X : Type*} [MetricSpace X] + +abbrev Curve (X : Type*) [MetricSpace X] := C(Time, X) + +instance curveMeasurableSpace : MeasurableSpace (Curve X) := borel (Curve X) + +instance curveBorelSpace : BorelSpace (Curve X) := ⟨rfl⟩ + +def evalReal (γ : Curve X) (t : ℝ) : X := γ (clampTime t) + +/-- The constant-speed minimizing parametrization, including constant curves. -/ +def IsGeodesic (γ : Curve X) : Prop := + ∀ s t : Time, + dist (γ s) (γ t) = |(s : ℝ) - (t : ℝ)| * dist (γ timeZero) (γ timeOne) + +/-- Metric speed. Limsup agrees a.e. with the metric derivative on AC² curves. -/ +def metricSpeed (γ : Curve X) (t : ℝ) : ℝ≥0∞ := + Filter.limsup (fun s : ℝ => ENNReal.ofReal + (dist (evalReal γ s) (evalReal γ t) / |s - t|)) (𝓝[≠] t) + +/-- Absolute continuity with a square-integrable metric control. -/ +def IsAC2 (γ : Curve X) : Prop := + ∃ a : ℝ → ℝ≥0∞, Measurable a ∧ + (∫⁻ t in Set.Icc (0 : ℝ) 1, (a t) ^ 2) < ∞ ∧ + ∀ s t : Time, (s : ℝ) ≤ (t : ℝ) → + edist (γ s) (γ t) ≤ ∫⁻ r in Set.Icc (s : ℝ) (t : ℝ), a r + +variable [MeasurableSpace X] [BorelSpace X] + +/-- A 2-test plan: bounded compression and finite average kinetic energy. -/ +def IsTestPlan (m : Measure X) (π : Measure (Curve X)) : Prop := + IsProbabilityMeasure π ∧ + (∃ C : ℝ≥0, ∀ t : Time, + Measure.map (fun γ : Curve X => γ t) π ≤ (C : ℝ≥0∞) • m) ∧ + (∀ᵐ γ ∂π, IsAC2 γ) ∧ + (∫⁻ γ, ∫⁻ t in Set.Icc (0 : ℝ) 1, (metricSpeed γ t) ^ 2 ∂volume ∂π) < ∞ + +/-- Uniform bounded spatial support; used only to define the local Sobolev class. -/ +def BoundedTracks (π : Measure (Curve X)) : Prop := + ∃ o : X, ∃ R : ℝ, 0 < R ∧ ∀ᵐ γ ∂π, ∀ t : Time, dist (γ t) o ≤ R + +def LocallyL2 (m : Measure X) (f : X → ℝ) : Prop := + ∀ o : X, ∀ R : ℝ, 0 < R → MemLp f 2 (m.restrict (Metric.ball o R)) + +/-- Local weak upper gradients, in the integrated test-plan definition. -/ +def IsLocalWeakUpperGradient (m : Measure X) (f D : X → ℝ) : Prop := + LocallyL2 m D ∧ (∀ᵐ x ∂m, 0 ≤ D x) ∧ + ∀ π : Measure (Curve X), IsTestPlan m π → BoundedTracks π → + (∫⁻ γ, ENNReal.ofReal |f (γ timeOne) - f (γ timeZero)| ∂π) ≤ + ∫⁻ γ, ∫⁻ t in Set.Icc (0 : ℝ) 1, + ENNReal.ofReal (D (evalReal γ t)) * metricSpeed γ t ∂volume ∂π + +def IsMinimalLocalWeakUpperGradient (m : Measure X) (f D : X → ℝ) : Prop := + IsLocalWeakUpperGradient m f D ∧ + ∀ D' : X → ℝ, IsLocalWeakUpperGradient m f D' → ∀ᵐ x ∂m, D x ≤ D' x + +/-- A representative of the minimal weak upper gradient (zero off its domain). -/ +def weakGradient (m : Measure X) (f : X → ℝ) : X → ℝ := + if h : ∃ D, IsMinimalLocalWeakUpperGradient m f D then Classical.choose h + else 0 + +def LocalSobolev (m : Measure X) (f : X → ℝ) : Prop := + LocallyL2 m f ∧ ∃ D, IsMinimalLocalWeakUpperGradient m f D + +def Sobolev (m : Measure X) (f : X → ℝ) : Prop := + MemLp f 2 m ∧ LocalSobolev m f ∧ MemLp (weakGradient m f) 2 m + +/-- Polarization of the minimal weak gradient on an infinitesimally Hilbertian space. -/ +def gamma (m : Measure X) (f g : X → ℝ) (x : X) : ℝ := + ((weakGradient m (fun y => f y + g y) x) ^ 2 - + (weakGradient m (fun y => f y - g y) x) ^ 2) / 4 + +/-- Weak nonpositive generator convention, without a global L² assumption on F. -/ +def IsLaplacian (m : Measure X) (u L : X → ℝ) : Prop := + Sobolev m u ∧ MemLp L 2 m ∧ + ∀ v : X → ℝ, Sobolev m v → + (∫ x, gamma m u v x ∂m) = -(∫ x, L x * v x ∂m) + +def InLaplacianDomain (m : Measure X) (u : X → ℝ) : Prop := + ∃ L, IsLaplacian m u L + +def laplacian (m : Measure X) (u : X → ℝ) : X → ℝ := + if h : ∃ L, IsLaplacian m u L then Classical.choose h else 0 + +def BoundedFunction (f : X → ℝ) : Prop := ∃ B : ℝ, ∀ x, |f x| ≤ B + +def GloballyLipschitz (f : X → ℝ) : Prop := ∃ L : ℝ≥0, LipschitzWith L f + +/-- Bounded globally Lipschitz Laplacian-domain functions with Sobolev Laplacian. -/ +def IsTestFunction (m : Measure X) (g : X → ℝ) : Prop := + InLaplacianDomain m g ∧ BoundedFunction g ∧ GloballyLipschitz g ∧ + Sobolev m (laplacian m g) + +/-- The weak Hessian, with ∇_(∇g)∇g = ∇(Γ(g)/2). -/ +def weakHessian (m : Measure X) (F g h : X → ℝ) : ℝ := + -(∫ x, (gamma m h g x + h x * laplacian m g x) * gamma m F g x ∂m) - + ∫ x, h x * gamma m F (fun y => gamma m g g y / 2) x ∂m + +def WeakHessianUpperBound (m : Measure X) (F G : X → ℝ) : Prop := + ∀ g : X → ℝ, IsTestFunction m g → HasCompactSupport g → + ∀ h : X → ℝ, GloballyLipschitz h → HasCompactSupport h → + (∀ x, 0 ≤ h x) → + weakHessian m F g h ≤ ∫ x, h x * G x * gamma m g g x ∂m + +/-- Asymptotic Lipschitz slope; zero at an isolated point. -/ +def localSlope (f : X → ℝ) (x : X) : ℝ≥0∞ := + Filter.limsup (fun y => ENNReal.ofReal (|f y - f x| / dist y x)) (𝓝[≠] x) + +/-- Cheeger energy is the L² relaxation of one half the squared local slope. -/ +def cheegerEnergy (m : Measure X) (f : X → ℝ) : ℝ≥0∞ := + if MemLp f 2 m then + sInf {a | ∃ fs : ℕ → X → ℝ, + (∀ n, GloballyLipschitz (fs n) ∧ MemLp (fs n) 2 m) ∧ + Tendsto (fun n => eLpNorm (fun x => fs n x - f x) 2 m) atTop (𝓝 0) ∧ + a = Filter.liminf (fun n => (2 : ℝ≥0∞)⁻¹ * + ∫⁻ x, (localSlope (fs n) x) ^ 2 ∂m) atTop} + else ∞ + +def QuadraticCheegerEnergy (m : Measure X) : Prop := + ∀ f g : X → ℝ, cheegerEnergy m f < ∞ → cheegerEnergy m g < ∞ → + cheegerEnergy m (fun x => f x + g x) + cheegerEnergy m (fun x => f x - g x) = + 2 * cheegerEnergy m f + 2 * cheegerEnergy m g + +/-- The unreduced Lott–Sturm–Villani distortion coefficient σ. -/ +def sigmaCoeff (K N t θ : ℝ) : ℝ≥0∞ := + if t ≤ 0 then 0 else if 1 ≤ t then 1 else + if θ = 0 then ENNReal.ofReal t else + if 0 < K then + if K * θ ^ 2 < N * Real.pi ^ 2 then + ENNReal.ofReal (Real.sin (t * θ * Real.sqrt (K / N)) / + Real.sin (θ * Real.sqrt (K / N))) + else ∞ + else if K = 0 then ENNReal.ofReal t else + ENNReal.ofReal (Real.sinh (t * θ * Real.sqrt (-K / N)) / + Real.sinh (θ * Real.sqrt (-K / N))) + +/-- The τ coefficient (not the reduced σ coefficient) in CD(K,N). -/ +def tauCoeff (K N t θ : ℝ) : ℝ≥0∞ := + (ENNReal.ofReal t) ^ (1 / N) * (sigmaCoeff K (N - 1) t θ) ^ ((N - 1) / N) + +def HasSecondMoment (μ : Measure X) : Prop := + ∃ o : X, (∫⁻ x, (edist x o) ^ 2 ∂μ) < ∞ + +def IsCoupling (q : Measure (X × X)) (μ₀ μ₁ : Measure X) : Prop := + Measure.map Prod.fst q = μ₀ ∧ Measure.map Prod.snd q = μ₁ + +def QuadraticTransportCost (q : Measure (X × X)) : ℝ≥0∞ := + ∫⁻ p, (edist p.1 p.2) ^ 2 ∂q + +def IsOptimalCoupling (q : Measure (X × X)) (μ₀ μ₁ : Measure X) : Prop := + IsCoupling q μ₀ μ₁ ∧ ∀ q' : Measure (X × X), IsCoupling q' μ₀ μ₁ → + QuadraticTransportCost q ≤ QuadraticTransportCost q' + +def endpointCoupling (π : Measure (Curve X)) : Measure (X × X) := + Measure.map (fun γ : Curve X => (γ timeZero, γ timeOne)) π + +def interpolation (π : Measure (Curve X)) (t : Time) : Measure X := + Measure.map (fun γ : Curve X => γ t) π + +/-- The positive of minus the N-Rényi entropy; singular mass contributes zero. -/ +def renyiIntegral (m μ : Measure X) (N : ℝ) : ℝ≥0∞ := + ∫⁻ x, (μ.rnDeriv m x) ^ (1 - 1 / N) ∂m + +/-- Unreduced CD(K,N), written with the standard dynamical optimal-plan formula. -/ +def CurvatureDimension (m : Measure X) (K N : ℝ) : Prop := + ∀ μ₀ μ₁ : Measure X, + IsProbabilityMeasure μ₀ → IsProbabilityMeasure μ₁ → + HasSecondMoment μ₀ → HasSecondMoment μ₁ → + μ₀ ≪ m → μ₁ ≪ m → + ∃ π : Measure (Curve X), IsProbabilityMeasure π ∧ + (∀ᵐ γ ∂π, IsGeodesic γ) ∧ + IsOptimalCoupling (endpointCoupling π) μ₀ μ₁ ∧ + ∀ N' : ℝ, N ≤ N' → ∀ t : Time, + (∫⁻ γ, + (tauCoeff K N' (1 - (t : ℝ)) (dist (γ timeZero) (γ timeOne)) * + (μ₀.rnDeriv m (γ timeZero)) ^ (-1 / N') + + tauCoeff K N' (t : ℝ) (dist (γ timeZero) (γ timeOne)) * + (μ₁.rnDeriv m (γ timeOne)) ^ (-1 / N')) ∂π) ≤ + renyiIntegral m (interpolation π t) N' + +def RCD (m : Measure X) (K N : ℝ) : Prop := + CurvatureDimension m K N ∧ QuadraticCheegerEnergy m + +def FullSupport (m : Measure X) : Prop := + ∀ U : Set X, IsOpen U → U.Nonempty → 0 < m U + +def FiniteOnBoundedSets (m : Measure X) : Prop := + ∀ B : Set X, Bornology.IsBounded B → m B < ∞ + +/-- The literal second-distributional-derivative conclusion on (0,1). -/ +def CurveSecondDerivativeBound (F G : X → ℝ) (σ : Curve X) : Prop := + ∀ φ : ℝ → ℝ, ContDiff ℝ ((⊤ : ℕ∞) : WithTop ℕ∞) φ → HasCompactSupport φ → + tsupport φ ⊆ Set.Ioo (0 : ℝ) 1 → (∀ t, 0 ≤ φ t) → + (∫ t in Set.Icc (0 : ℝ) 1, + F (evalReal σ t) * deriv (deriv φ) t) ≤ + (dist (σ timeZero) (σ timeOne)) ^ 2 * + ∫ t in Set.Icc (0 : ℝ) 1, G (evalReal σ t) * φ t + +/-- A weak upper Hessian bound controls the second distributional derivative +along every constant-speed minimizing geodesic. -/ +theorem every_geodesic [CompleteSpace X] [TopologicalSpace.SeparableSpace X] + (m : Measure X) (K N : ℝ) (hN : 1 < N) + (hfull : FullSupport m) (hfinite : FiniteOnBoundedSets m) (hrcd : RCD m K N) + (F G : X → ℝ) (hFbound : BoundedFunction F) (hFlip : GloballyLipschitz F) + (hGbound : BoundedFunction G) (hGcont : Continuous G) + (hHess : WeakHessianUpperBound m F G) + (σ : Curve X) (hσ : IsGeodesic σ) : CurveSecondDerivativeBound F G σ := by + sorry + +end WeakHessian + +end + +end OAI diff --git a/tasks/weak-hessian/tests/grade.py b/tasks/weak-hessian/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/weak-hessian/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/weak-hessian/tests/task.json b/tasks/weak-hessian/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9897a71a5d3d231fdaceaca83defe7745507df9a --- /dev/null +++ b/tasks/weak-hessian/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WeakHessian", + "comparator": { + "theorem_names": [ + "OAI.WeakHessian.every_geodesic" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 13622 +} \ No newline at end of file diff --git a/tasks/weak-hessian/tests/test.sh b/tasks/weak-hessian/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/weak-hessian/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/weak-mtw-global-support/environment/Dockerfile b/tasks/weak-mtw-global-support/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/weak-mtw-global-support/environment/fetch_mathlib.sh b/tasks/weak-mtw-global-support/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/weak-mtw-global-support/environment/lake-manifest.json b/tasks/weak-mtw-global-support/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/weak-mtw-global-support/environment/lakefile.lean b/tasks/weak-mtw-global-support/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/weak-mtw-global-support/environment/lean_setup.sh b/tasks/weak-mtw-global-support/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/weak-mtw-global-support/environment/pack_submission.py b/tasks/weak-mtw-global-support/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/weak-mtw-global-support/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/weak-mtw-global-support/instruction.md b/tasks/weak-mtw-global-support/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..68abb2e3327dd0e44fb5527573e31a82220382ae --- /dev/null +++ b/tasks/weak-mtw-global-support/instruction.md @@ -0,0 +1,130 @@ +# openai/math challenge `WeakMTWGlobalSupport` (family 360) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 360 of the release, *Villani’s convexity conjecture and regular optimal transport* +(Differential geometry). The family as a whole: On every closed connected Riemannian manifold of dimension at least two satisfying weak Ma–Trudinger–Wang curvature, all tangent injectivity domains are convex, resolving Villani’s conjecture in this setting. For squared-distance transport between measurable probability densities bounded above and away from zero, the optimal map and its inverse are Holder continuous. + +The challenge is `WeakMTWGlobalSupport`, also at `/opt/openai-math/challenges/WeakMTWGlobalSupport.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace WeakMTWGlobalSupport + +open scoped Manifold ContDiff Topology +open Set Filter Manifold Bundle + +namespace WeakMTW + +noncomputable section + +abbrev Model (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev model (n : ℕ) := 𝓘(ℝ, Model n) + +variable {n : ℕ} {M : Type*} [MetricSpace M] [ChartedSpace (Model n) M] + [IsManifold (model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace (model n) x)] + [IsContMDiffRiemannianBundle (model n) ∞ (Model n) + (fun x : M => TangentSpace (model n) x)] + [IsRiemannianManifold (model n) M] + +def CompleteGeodesicWithInitialData (x : M) (v : TangentSpace (model n) x) + (γ : ℝ → M) : Prop := + ContMDiff 𝓘(ℝ, ℝ) (model n) ∞ γ ∧ + ∃ h : γ 0 = x, + (h ▸ mfderiv 𝓘(ℝ, ℝ) (model n) γ 0 (1 : ℝ)) = v ∧ + ∀ t : ℝ, ∃ ε : ℝ, 0 < ε ∧ + ∀ s ∈ Metric.ball t ε, ∀ r ∈ Metric.ball t ε, + dist (γ s) (γ r) = ‖v‖ * |s - r| + +def ExpEndpoint (x : M) (v : TangentSpace (model n) x) (y : M) : Prop := + ∃ γ : ℝ → M, CompleteGeodesicWithInitialData x v γ ∧ γ 1 = y + +noncomputable def exp (x : M) (v : TangentSpace (model n) x) : M := + by + classical + exact if h : ∃ y, ExpEndpoint x v y then Classical.choose h else x + +def injectivityDomain (x : M) : Set (TangentSpace (model n) x) := + {v | ∃ a : ℝ, 1 < a ∧ dist x (exp x (a • v)) = a * ‖v‖} + +def cost (x y : M) : ℝ := dist x y ^ 2 / 2 + +noncomputable def mtw (x : M) (v ξ η : TangentSpace (model n) x) : ℝ := + -(3 / 2 : ℝ) * deriv (fun s : ℝ => + deriv (fun s' : ℝ => deriv (fun t : ℝ => + deriv (fun t' : ℝ => cost (exp x (t' • ξ)) (exp x (v + s' • η))) t) 0) s) 0 + +def HasWeakMTW : Prop := + ∀ (x : M) (v : TangentSpace (model n) x), v ∈ injectivityDomain x → + ∀ ξ η : TangentSpace (model n) x, inner ℝ ξ η = 0 → 0 ≤ mtw x v ξ η + +def MainConvexity : Prop := + ∀ x : M, Convex ℝ (injectivityDomain (n := n) x) + +end + +end WeakMTW + +/-- Weak MTW implies linear convexity of every open tangent injectivity domain. -/ +theorem current_main_convexity + {n : ℕ} (hn : 2 ≤ n) {M : Type*} + [MetricSpace M] [ChartedSpace (WeakMTW.Model n) M] + [IsManifold (WeakMTW.model n) ∞ M] + [CompactSpace M] [ConnectedSpace M] + [RiemannianBundle (fun x : M => TangentSpace (WeakMTW.model n) x)] + [IsContMDiffRiemannianBundle (WeakMTW.model n) ∞ (WeakMTW.Model n) + (fun x : M => TangentSpace (WeakMTW.model n) x)] + [IsRiemannianManifold (WeakMTW.model n) M] + (hmtw : WeakMTW.HasWeakMTW (n := n) (M := M)) : + WeakMTW.MainConvexity (n := n) (M := M) := + by + sorry + +end WeakMTWGlobalSupport + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WeakMTWGlobalSupport.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WeakMTWGlobalSupport.current_main_convexity` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/weak-mtw-global-support/solution/closure.txt b/tasks/weak-mtw-global-support/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9712abfe7f996232f8bd6347dd315c7e83c35ec --- /dev/null +++ b/tasks/weak-mtw-global-support/solution/closure.txt @@ -0,0 +1,210 @@ +OAI.Geometry.WeakMTW.Analysis.CurveComposition +OAI.Geometry.WeakMTW.Analysis.IntegralEquation +OAI.Geometry.WeakMTW.Analysis.SmoothFlow +OAI.Geometry.WeakMTW.Convexity +OAI.Geometry.WeakMTW.Coordinates.ChartGlobalVariation +OAI.Geometry.WeakMTW.Coordinates.ChartLength +OAI.Geometry.WeakMTW.Coordinates.ChartMetric +OAI.Geometry.WeakMTW.Coordinates.ChartPairing +OAI.Geometry.WeakMTW.Coordinates.ChartScaling +OAI.Geometry.WeakMTW.Coordinates.CoerciveMetric +OAI.Geometry.WeakMTW.Coordinates.CoordinateEquation +OAI.Geometry.WeakMTW.Coordinates.CoordinateExistence +OAI.Geometry.WeakMTW.Coordinates.CoordinateGeometry +OAI.Geometry.WeakMTW.Coordinates.CoordinateIdentification +OAI.Geometry.WeakMTW.Coordinates.CoordinateLocal +OAI.Geometry.WeakMTW.Coordinates.CostEndpointAction +OAI.Geometry.WeakMTW.Coordinates.CostFirstTaylor +OAI.Geometry.WeakMTW.Coordinates.CostNormalGradient +OAI.Geometry.WeakMTW.Coordinates.EndpointAction +OAI.Geometry.WeakMTW.Coordinates.FanCoordinates +OAI.Geometry.WeakMTW.Coordinates.FocalCoordinates +OAI.Geometry.WeakMTW.Coordinates.InteriorCost +OAI.Geometry.WeakMTW.Coordinates.IntrinsicNormal +OAI.Geometry.WeakMTW.Coordinates.LocalCost +OAI.Geometry.WeakMTW.Coordinates.LocalDistance +OAI.Geometry.WeakMTW.Coordinates.NormalAction +OAI.Geometry.WeakMTW.Coordinates.NormalCoordinates +OAI.Geometry.WeakMTW.Coordinates.NormalCurve +OAI.Geometry.WeakMTW.Coordinates.NormalDifferential +OAI.Geometry.WeakMTW.Coordinates.NormalEndpoint +OAI.Geometry.WeakMTW.Coordinates.NormalFlowLength +OAI.Geometry.WeakMTW.Coordinates.NormalLength +OAI.Geometry.WeakMTW.Coordinates.NormalMetricSpeed +OAI.Geometry.WeakMTW.Coordinates.NormalNeighborhood +OAI.Geometry.WeakMTW.Coordinates.NormalRigidity +OAI.Geometry.WeakMTW.Coordinates.NormalState +OAI.Geometry.WeakMTW.Coordinates.PairExpCoordinates +OAI.Geometry.WeakMTW.Coordinates.PairNormalDistance +OAI.Geometry.WeakMTW.Coordinates.RadialCoordinates +OAI.Geometry.WeakMTW.Coordinates.RadialLength +OAI.Geometry.WeakMTW.Coordinates.RadialRigidity +OAI.Geometry.WeakMTW.Coordinates.TangentCoordinates +OAI.Geometry.WeakMTW.Coordinates.TangentDiskCompact +OAI.Geometry.WeakMTW.Coordinates.TangentScaling +OAI.Geometry.WeakMTW.Coordinates.TwoPointSpeed +OAI.Geometry.WeakMTW.Coordinates.UnitNormal +OAI.Geometry.WeakMTW.Domains.Definitions +OAI.Geometry.WeakMTW.Endpoints +OAI.Geometry.WeakMTW.Geodesics.BundleMinimizerCompactness +OAI.Geometry.WeakMTW.Geodesics.CompactGeodesic +OAI.Geometry.WeakMTW.Geodesics.CompleteExistence +OAI.Geometry.WeakMTW.Geodesics.CostGeodesicTaylor +OAI.Geometry.WeakMTW.Geodesics.DistanceSplitting +OAI.Geometry.WeakMTW.Geodesics.EnergyFirstVariation +OAI.Geometry.WeakMTW.Geodesics.ExtendedMinimizers +OAI.Geometry.WeakMTW.Geodesics.FanEnergySmooth +OAI.Geometry.WeakMTW.Geodesics.FiberSmooth +OAI.Geometry.WeakMTW.Geodesics.FibreNonfocal +OAI.Geometry.WeakMTW.Geodesics.FlowFirstVariation +OAI.Geometry.WeakMTW.Geodesics.FlowVariationInjective +OAI.Geometry.WeakMTW.Geodesics.GaussChartFan +OAI.Geometry.WeakMTW.Geodesics.GaussGlobal +OAI.Geometry.WeakMTW.Geodesics.GaussLemma +OAI.Geometry.WeakMTW.Geodesics.GeneralFirstVariation +OAI.Geometry.WeakMTW.Geodesics.GeodesicDistance +OAI.Geometry.WeakMTW.Geodesics.GeodesicFlow +OAI.Geometry.WeakMTW.Geodesics.GeodesicScaling +OAI.Geometry.WeakMTW.Geodesics.GlobalFirstVariation +OAI.Geometry.WeakMTW.Geodesics.GlobalFlow +OAI.Geometry.WeakMTW.Geodesics.HopfRinow +OAI.Geometry.WeakMTW.Geodesics.InitialScaling +OAI.Geometry.WeakMTW.Geodesics.InjectivityUniqueness +OAI.Geometry.WeakMTW.Geodesics.IntrinsicExistence +OAI.Geometry.WeakMTW.Geodesics.IntrinsicExp +OAI.Geometry.WeakMTW.Geodesics.IntrinsicGlue +OAI.Geometry.WeakMTW.Geodesics.IntrinsicOn +OAI.Geometry.WeakMTW.Geodesics.IntrinsicUniqueness +OAI.Geometry.WeakMTW.Geodesics.LocalFanVariation +OAI.Geometry.WeakMTW.Geodesics.LocalFlow +OAI.Geometry.WeakMTW.Geodesics.LocalGeodesic +OAI.Geometry.WeakMTW.Geodesics.MinimizerCapture +OAI.Geometry.WeakMTW.Geodesics.MinimizerCompactness +OAI.Geometry.WeakMTW.Geodesics.MinimizingCorner +OAI.Geometry.WeakMTW.Geodesics.MinimizingSegments +OAI.Geometry.WeakMTW.Geodesics.NoCorner +OAI.Geometry.WeakMTW.Geodesics.NonconjugateBranches +OAI.Geometry.WeakMTW.Geodesics.ShortChartAction +OAI.Geometry.WeakMTW.Geodesics.ShortFan +OAI.Geometry.WeakMTW.Geodesics.ShortFlowCoordinates +OAI.Geometry.WeakMTW.Geodesics.ShortStates +OAI.Geometry.WeakMTW.Geodesics.UniformNormal +OAI.Geometry.WeakMTW.Main +OAI.Geometry.WeakMTW.Model +OAI.Geometry.WeakMTW.Potentials.ChartForwardLipschitz +OAI.Geometry.WeakMTW.Potentials.ChartLocalLipschitz +OAI.Geometry.WeakMTW.Potentials.CompactFamilyControl +OAI.Geometry.WeakMTW.Potentials.CompactSmoothControl +OAI.Geometry.WeakMTW.Potentials.CovectorFlow +OAI.Geometry.WeakMTW.Potentials.DiagonalEnvelope +OAI.Geometry.WeakMTW.Potentials.FiniteGlobalSupport +OAI.Geometry.WeakMTW.Potentials.GlobalSupportTheorem +OAI.Geometry.WeakMTW.Potentials.GradientCoordinates +OAI.Geometry.WeakMTW.Potentials.IntermediateAtlas +OAI.Geometry.WeakMTW.Potentials.IntermediateCoordinates +OAI.Geometry.WeakMTW.Potentials.IntermediateCovectors +OAI.Geometry.WeakMTW.Potentials.IntermediateDefinitions +OAI.Geometry.WeakMTW.Potentials.IntermediateDuality +OAI.Geometry.WeakMTW.Potentials.IntermediateGradient +OAI.Geometry.WeakMTW.Potentials.IntermediateGrowth +OAI.Geometry.WeakMTW.Potentials.IntermediateGrowthLocal +OAI.Geometry.WeakMTW.Potentials.IntermediateGrowthMetric +OAI.Geometry.WeakMTW.Potentials.IntermediateMomentumLipschitz +OAI.Geometry.WeakMTW.Potentials.IntermediateParameterFamily +OAI.Geometry.WeakMTW.Potentials.IntermediatePoleLipschitz +OAI.Geometry.WeakMTW.Potentials.IntermediateRegularity +OAI.Geometry.WeakMTW.Potentials.IntermediateStatement +OAI.Geometry.WeakMTW.Potentials.IntermediateTheorem +OAI.Geometry.WeakMTW.Potentials.IntermediateUniformBounds +OAI.Geometry.WeakMTW.Potentials.IntermediateUniformLipschitz +OAI.Geometry.WeakMTW.Potentials.IntermediateUniformRegularity +OAI.Geometry.WeakMTW.Potentials.LiftedSectionDefinitions +OAI.Geometry.WeakMTW.Potentials.LiftedSections +OAI.Geometry.WeakMTW.Potentials.LiftedSectionsTheorem +OAI.Geometry.WeakMTW.Potentials.OrdinarySubgradientCapture +OAI.Geometry.WeakMTW.Potentials.OrdinarySubgradientIdentity +OAI.Geometry.WeakMTW.Potentials.ParametricEnvelopeBounds +OAI.Geometry.WeakMTW.Potentials.PositiveEnvelope +OAI.Geometry.WeakMTW.Potentials.PotentialActiveLogs +OAI.Geometry.WeakMTW.Potentials.PotentialDefinitions +OAI.Geometry.WeakMTW.Potentials.PotentialFiniteReduction +OAI.Geometry.WeakMTW.Potentials.PotentialGraphGlobal +OAI.Geometry.WeakMTW.Potentials.QuadraticEnvelope +OAI.Geometry.WeakMTW.Potentials.ReverseGeodesic +OAI.Geometry.WeakMTW.Potentials.SmoothEnvelope +OAI.Geometry.WeakMTW.Potentials.SmoothMetricLipschitz +OAI.Geometry.WeakMTW.Potentials.UniformLocalLipschitz +OAI.Geometry.WeakMTW.Support.ActiveCollisionExclusion +OAI.Geometry.WeakMTW.Support.ActiveContinuation +OAI.Geometry.WeakMTW.Support.ActiveGraphLimits +OAI.Geometry.WeakMTW.Support.ActiveRepresentation +OAI.Geometry.WeakMTW.Support.ActiveSmallScale +OAI.Geometry.WeakMTW.Support.ActiveSupports +OAI.Geometry.WeakMTW.Support.AllScales +OAI.Geometry.WeakMTW.Support.BranchCollisionLimits +OAI.Geometry.WeakMTW.Support.CollisionBranches +OAI.Geometry.WeakMTW.Support.CollisionCalculus +OAI.Geometry.WeakMTW.Support.CollisionGeometry +OAI.Geometry.WeakMTW.Support.CollisionGradient +OAI.Geometry.WeakMTW.Support.CollisionStrictGap +OAI.Geometry.WeakMTW.Support.CollisionTangentCoordinates +OAI.Geometry.WeakMTW.Support.CompactHomotopyContinuation +OAI.Geometry.WeakMTW.Support.CompactLimitInjectivity +OAI.Geometry.WeakMTW.Support.ConvexRepresentation +OAI.Geometry.WeakMTW.Support.CriticalCollision +OAI.Geometry.WeakMTW.Support.CriticalHessianGap +OAI.Geometry.WeakMTW.Support.CriticalJensen +OAI.Geometry.WeakMTW.Support.CriticalLocalTheorem +OAI.Geometry.WeakMTW.Support.CriticalNonconjugacy +OAI.Geometry.WeakMTW.Support.FiberHullCompact +OAI.Geometry.WeakMTW.Support.FiniteActiveGraph +OAI.Geometry.WeakMTW.Support.FirstCutSupport +OAI.Geometry.WeakMTW.Support.FirstScale +OAI.Geometry.WeakMTW.Support.InteriorCharacterization +OAI.Geometry.WeakMTW.Support.NormalizedSeparation +OAI.Geometry.WeakMTW.Support.TangentHullCompact +OAI.Geometry.WeakMTW.Support.TotalInterior +OAI.Geometry.WeakMTW.Support.TransverseJensen +OAI.Geometry.WeakMTW.Variations.ActionBranch +OAI.Geometry.WeakMTW.Variations.ActionHessian +OAI.Geometry.WeakMTW.Variations.BranchAction +OAI.Geometry.WeakMTW.Variations.BranchHessian +OAI.Geometry.WeakMTW.Variations.BranchInitialGeometry +OAI.Geometry.WeakMTW.Variations.BrokenActionCalculus +OAI.Geometry.WeakMTW.Variations.BrokenActionMinimum +OAI.Geometry.WeakMTW.Variations.CostSplitting +OAI.Geometry.WeakMTW.Variations.CovariantActionHessian +OAI.Geometry.WeakMTW.Variations.CurveCalculus +OAI.Geometry.WeakMTW.Variations.CurveVariation +OAI.Geometry.WeakMTW.Variations.DiscreteVariationalCalculus +OAI.Geometry.WeakMTW.Variations.FirstVariation +OAI.Geometry.WeakMTW.Variations.FlowLinearization +OAI.Geometry.WeakMTW.Variations.FocalPole +OAI.Geometry.WeakMTW.Variations.GeneratingAction +OAI.Geometry.WeakMTW.Variations.GeneratingActionBound +OAI.Geometry.WeakMTW.Variations.GeneratingFocalCalculus +OAI.Geometry.WeakMTW.Variations.GeneratingHessian +OAI.Geometry.WeakMTW.Variations.GeneratingNeighborhood +OAI.Geometry.WeakMTW.Variations.GeneratingQuadratic +OAI.Geometry.WeakMTW.Variations.GeneratingTrial +OAI.Geometry.WeakMTW.Variations.GeodesicSecondCoordinates +OAI.Geometry.WeakMTW.Variations.GeometricFirstCut +OAI.Geometry.WeakMTW.Variations.HessianLinear +OAI.Geometry.WeakMTW.Variations.HessianNull +OAI.Geometry.WeakMTW.Variations.HullNonconjugacy +OAI.Geometry.WeakMTW.Variations.InwardHessianBound +OAI.Geometry.WeakMTW.Variations.LineTaylor +OAI.Geometry.WeakMTW.Variations.MTWConcavity +OAI.Geometry.WeakMTW.Variations.MajorantHessian +OAI.Geometry.WeakMTW.Variations.MomentumSeparation +OAI.Geometry.WeakMTW.Variations.MovingTaylor +OAI.Geometry.WeakMTW.Variations.NoFocalCalculus +OAI.Geometry.WeakMTW.Variations.ParametricTaylor +OAI.Geometry.WeakMTW.Variations.QuadraticHessian +OAI.Geometry.WeakMTW.Variations.RadialComparison +OAI.Geometry.WeakMTW.Variations.RadialComparisonCalculus +OAI.Geometry.WeakMTW.Variations.RadialHessianCalculus +OAI.Geometry.WeakMTW.Variations.RadialSplitAction +OAI.Geometry.WeakMTW.Variations.SecondCurveChain +OAI.Geometry.WeakMTW.Variations.SegmentNonconjugacy +OAI.Geometry.WeakMTW.Variations.ZeroActionHessian diff --git a/tasks/weak-mtw-global-support/solution/reference.py b/tasks/weak-mtw-global-support/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/weak-mtw-global-support/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/weak-mtw-global-support/solution/solve.sh b/tasks/weak-mtw-global-support/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..748940b5fd676eccc6ff2499a45023c0e920ba4d --- /dev/null +++ b/tasks/weak-mtw-global-support/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WeakMTWGlobalSupport, i.e. module OAI.Geometry.WeakMTW.Main and the +# 210 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.WeakMTW.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WeakMTWGlobalSupport" diff --git a/tasks/weak-mtw-global-support/task.toml b/tasks/weak-mtw-global-support/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..1a36be7f2497a5aaf1f0afc808cf30e92472ba9d --- /dev/null +++ b/tasks/weak-mtw-global-support/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/weak-mtw-global-support" +version = "1.0.0" +description = "Prove WeakMTWGlobalSupport (openai/math family 360: Villani’s convexity conjecture and regular optimal transport) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WeakMTWGlobalSupport.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WeakMTWGlobalSupport" +family = "360" +family_title = "Villani’s convexity conjecture and regular optimal transport" +subject = "Differential geometry" +theorems = ["OAI.WeakMTWGlobalSupport.current_main_convexity"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.WeakMTW.Main" +reference_modules = 210 +reference_lean_bytes = 903567 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 891 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12513 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/weak-mtw-global-support/tests/Challenge.lean b/tasks/weak-mtw-global-support/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..74d786cf47e5ef9ab6d23491aa47ef9c3132420a --- /dev/null +++ b/tasks/weak-mtw-global-support/tests/Challenge.lean @@ -0,0 +1,79 @@ +import Mathlib + +namespace OAI + +namespace WeakMTWGlobalSupport + +open scoped Manifold ContDiff Topology +open Set Filter Manifold Bundle + +namespace WeakMTW + +noncomputable section + +abbrev Model (n : ℕ) := EuclideanSpace ℝ (Fin n) +abbrev model (n : ℕ) := 𝓘(ℝ, Model n) + +variable {n : ℕ} {M : Type*} [MetricSpace M] [ChartedSpace (Model n) M] + [IsManifold (model n) ∞ M] + [RiemannianBundle (fun x : M => TangentSpace (model n) x)] + [IsContMDiffRiemannianBundle (model n) ∞ (Model n) + (fun x : M => TangentSpace (model n) x)] + [IsRiemannianManifold (model n) M] + +def CompleteGeodesicWithInitialData (x : M) (v : TangentSpace (model n) x) + (γ : ℝ → M) : Prop := + ContMDiff 𝓘(ℝ, ℝ) (model n) ∞ γ ∧ + ∃ h : γ 0 = x, + (h ▸ mfderiv 𝓘(ℝ, ℝ) (model n) γ 0 (1 : ℝ)) = v ∧ + ∀ t : ℝ, ∃ ε : ℝ, 0 < ε ∧ + ∀ s ∈ Metric.ball t ε, ∀ r ∈ Metric.ball t ε, + dist (γ s) (γ r) = ‖v‖ * |s - r| + +def ExpEndpoint (x : M) (v : TangentSpace (model n) x) (y : M) : Prop := + ∃ γ : ℝ → M, CompleteGeodesicWithInitialData x v γ ∧ γ 1 = y + +noncomputable def exp (x : M) (v : TangentSpace (model n) x) : M := + by + classical + exact if h : ∃ y, ExpEndpoint x v y then Classical.choose h else x + +def injectivityDomain (x : M) : Set (TangentSpace (model n) x) := + {v | ∃ a : ℝ, 1 < a ∧ dist x (exp x (a • v)) = a * ‖v‖} + +def cost (x y : M) : ℝ := dist x y ^ 2 / 2 + +noncomputable def mtw (x : M) (v ξ η : TangentSpace (model n) x) : ℝ := + -(3 / 2 : ℝ) * deriv (fun s : ℝ => + deriv (fun s' : ℝ => deriv (fun t : ℝ => + deriv (fun t' : ℝ => cost (exp x (t' • ξ)) (exp x (v + s' • η))) t) 0) s) 0 + +def HasWeakMTW : Prop := + ∀ (x : M) (v : TangentSpace (model n) x), v ∈ injectivityDomain x → + ∀ ξ η : TangentSpace (model n) x, inner ℝ ξ η = 0 → 0 ≤ mtw x v ξ η + +def MainConvexity : Prop := + ∀ x : M, Convex ℝ (injectivityDomain (n := n) x) + +end + +end WeakMTW + +/-- Weak MTW implies linear convexity of every open tangent injectivity domain. -/ +theorem current_main_convexity + {n : ℕ} (hn : 2 ≤ n) {M : Type*} + [MetricSpace M] [ChartedSpace (WeakMTW.Model n) M] + [IsManifold (WeakMTW.model n) ∞ M] + [CompactSpace M] [ConnectedSpace M] + [RiemannianBundle (fun x : M => TangentSpace (WeakMTW.model n) x)] + [IsContMDiffRiemannianBundle (WeakMTW.model n) ∞ (WeakMTW.Model n) + (fun x : M => TangentSpace (WeakMTW.model n) x)] + [IsRiemannianManifold (WeakMTW.model n) M] + (hmtw : WeakMTW.HasWeakMTW (n := n) (M := M)) : + WeakMTW.MainConvexity (n := n) (M := M) := + by + sorry + +end WeakMTWGlobalSupport + +end OAI diff --git a/tasks/weak-mtw-global-support/tests/grade.py b/tasks/weak-mtw-global-support/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/weak-mtw-global-support/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/weak-mtw-global-support/tests/task.json b/tasks/weak-mtw-global-support/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..49913787f05af32c54ca302868eff01824337ff8 --- /dev/null +++ b/tasks/weak-mtw-global-support/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WeakMTWGlobalSupport", + "comparator": { + "theorem_names": [ + "OAI.WeakMTWGlobalSupport.current_main_convexity" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11613 +} \ No newline at end of file diff --git a/tasks/weak-mtw-global-support/tests/test.sh b/tasks/weak-mtw-global-support/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/weak-mtw-global-support/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/weighted-sweep-moments/environment/Dockerfile b/tasks/weighted-sweep-moments/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/weighted-sweep-moments/environment/fetch_mathlib.sh b/tasks/weighted-sweep-moments/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/weighted-sweep-moments/environment/lake-manifest.json b/tasks/weighted-sweep-moments/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/weighted-sweep-moments/environment/lakefile.lean b/tasks/weighted-sweep-moments/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/weighted-sweep-moments/environment/lean_setup.sh b/tasks/weighted-sweep-moments/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/weighted-sweep-moments/environment/pack_submission.py b/tasks/weighted-sweep-moments/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/weighted-sweep-moments/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/weighted-sweep-moments/instruction.md b/tasks/weighted-sweep-moments/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..de1ccb72a01801cf0284640d61809e2e13b66d5a --- /dev/null +++ b/tasks/weighted-sweep-moments/instruction.md @@ -0,0 +1,355 @@ +# openai/math challenge `WeightedSweepMoments` (family 238) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 238 of the release, *Optimal logarithmic mixing of the Thorp shuffle* +(Probability and statistical mechanics). The family as a whole: Proves that the Thorp shuffle randomizes $N=2^d$ labeled cards in $\Theta(\log N)$ physical shuffles, settling its optimal mixing order for power-of-two deck sizes. Convergence is in total variation from the worst initial ordering and concerns the entire permutation, not just individual card positions. + +The challenge is `WeightedSweepMoments`, also at `/opt/openai-math/challenges/WeightedSweepMoments.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace CubeShuffle.Specht + +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +@[simp] lemma tabloidAct_inv {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + tabloidAct p⁻¹ = (tabloidAct p)⁻¹ := by + ext f x + simp [tabloidAct,Equiv.Perm.inv_def] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +@[simp] lemma tabloidRep_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (f : Tabloid μ) : tabloidRep μ p v f = v (tabloidAct p⁻¹ f) := rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) +section Alternator +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end Alternator + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end CubeShuffle.Specht + +namespace CubeShuffle.PermutationHilbert + +open scoped BigOperators ComplexConjugate Classical +open Complex + +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end CubeShuffle.PermutationHilbert + +namespace CubeShuffle.Specht + +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end CubeShuffle.Specht + +namespace CubeShuffle + +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end CubeShuffle + +namespace CubeShuffle.Specht +open scoped BigOperators Classical + +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end CubeShuffle.Specht + +namespace CubeShuffle.UnitaryFinite +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end CubeShuffle.UnitaryFinite + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace CubeShuffle.UnitaryFinite +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end CubeShuffle.UnitaryFinite + +noncomputable section +open scoped BigOperators Classical + +namespace CubeShuffle.WeightedSweep +open Specht UnitaryFinite + +def dimension (μ : YoungDiagram) : ℝ := Module.finrank ℂ (space μ) +def fourierSweep (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) +def schattenMoment {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (A : V →L[ℂ] V) (p : ℝ) : ℝ := + ∑ i : Fin (Module.finrank ℂ V), (A.toLinearMap.singularValues i) ^ p + +def schattenNorm {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (A : V →L[ℂ] V) (p : ℝ) : ℝ := + schattenMoment A p ^ (1 / p) + +end CubeShuffle.WeightedSweep + +end + +noncomputable section +open scoped BigOperators Classical + +namespace CubeShuffle.WeightedSweep +open Specht UnitaryFinite + +theorem weighted_sweep_moments : + ∃ (W : YoungDiagram → ℝ) (pStar : ℝ) (p : ℕ → ℝ), + (∀ μ : YoungDiagram, 0 < W μ) ∧ + 2 ≤ pStar ∧ + (∀ d : ℕ, 1 ≤ d → 2 ≤ p d ∧ p d ≤ pStar) ∧ + ∀ d : ℕ, 1 ≤ d → ∀ μ : Shapes (2 ^ d), + dimension μ.1 ^ (3 / 4 : ℝ) ≤ W μ.1 ∧ + W μ.1 ≤ dimension μ.1 ∧ + W μ.1 * + schattenNorm (V := hilbertSpace μ.1) (fourierSweep d μ) (p d) ^ (p d) ≤ 1 ∧ + ‖fourierSweep d μ‖ ≤ dimension μ.1 ^ (-3 / (4 * pStar)) := by + sorry + +end CubeShuffle.WeightedSweep + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WeightedSweepMoments.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.CubeShuffle.WeightedSweep.weighted_sweep_moments` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/weighted-sweep-moments/solution/closure.txt b/tasks/weighted-sweep-moments/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5f09a3698332ac5f7809bab029807b0890c75aa --- /dev/null +++ b/tasks/weighted-sweep-moments/solution/closure.txt @@ -0,0 +1,40 @@ +OAI.Probability.CubeShuffle.Basic +OAI.Probability.CubeShuffle.ButterflyCycles +OAI.Probability.CubeShuffle.ButterflyRoutes +OAI.Probability.CubeShuffle.Coin +OAI.Probability.CubeShuffle.CycleColoring +OAI.Probability.CubeShuffle.DensityMoments +OAI.Probability.CubeShuffle.DimensionEstimates +OAI.Probability.CubeShuffle.ExceptionalOperators +OAI.Probability.CubeShuffle.FiniteKernel +OAI.Probability.CubeShuffle.FourierBound +OAI.Probability.CubeShuffle.Generation +OAI.Probability.CubeShuffle.ModifiedDensity +OAI.Probability.CubeShuffle.ModifiedKernel +OAI.Probability.CubeShuffle.ModifiedRouting +OAI.Probability.CubeShuffle.NetworkSpectral +OAI.Probability.CubeShuffle.PairRouting +OAI.Probability.CubeShuffle.ParallelLayers +OAI.Probability.CubeShuffle.Physical +OAI.Probability.CubeShuffle.QueryTree +OAI.Probability.CubeShuffle.RecursiveDensity +OAI.Probability.CubeShuffle.RoutingNetwork +OAI.Probability.CubeShuffle.SchattenBounds +OAI.Probability.CubeShuffle.ShapeSpectral +OAI.Probability.CubeShuffle.UniformDecay +OAI.Probability.CubeShuffle.WeightedModel +OAI.Probability.CubeShuffle.WeightedMoments +OAI.RepresentationTheory.FiniteUnitary.Action +OAI.RepresentationTheory.FiniteUnitary.Averaging +OAI.RepresentationTheory.FiniteUnitary.Characters +OAI.RepresentationTheory.FiniteUnitary.Coefficients +OAI.RepresentationTheory.FiniteUnitary.CommutingBlocks +OAI.RepresentationTheory.FiniteUnitary.Fourier +OAI.RepresentationTheory.FiniteUnitary.KernelBounds +OAI.RepresentationTheory.FiniteUnitary.Sampling +OAI.RepresentationTheory.FiniteUnitary.Uncertainty +OAI.RepresentationTheory.YoungSymmetry.Dimensions +OAI.RepresentationTheory.YoungSymmetry.Irreducible +OAI.RepresentationTheory.YoungSymmetry.Polytabloid +OAI.RepresentationTheory.YoungSymmetry.ShapeBounds +OAI.RepresentationTheory.YoungSymmetry.UnitaryModel diff --git a/tasks/weighted-sweep-moments/solution/reference.py b/tasks/weighted-sweep-moments/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/weighted-sweep-moments/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/weighted-sweep-moments/solution/solve.sh b/tasks/weighted-sweep-moments/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..7893c4f62f1666feb5be0d97b6ce00a39ef88480 --- /dev/null +++ b/tasks/weighted-sweep-moments/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WeightedSweepMoments, i.e. module OAI.Probability.CubeShuffle.WeightedMoments and the +# 40 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Probability.CubeShuffle.WeightedMoments /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WeightedSweepMoments" diff --git a/tasks/weighted-sweep-moments/task.toml b/tasks/weighted-sweep-moments/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..96342cf1a73e654145f93eb26b0e229993f3fea0 --- /dev/null +++ b/tasks/weighted-sweep-moments/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/weighted-sweep-moments" +version = "1.0.0" +description = "Prove WeightedSweepMoments (openai/math family 238: Optimal logarithmic mixing of the Thorp shuffle) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "probability-and-statistical-mechanics"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WeightedSweepMoments.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WeightedSweepMoments" +family = "238" +family_title = "Optimal logarithmic mixing of the Thorp shuffle" +subject = "Probability and statistical mechanics" +theorems = ["OAI.CubeShuffle.WeightedSweep.weighted_sweep_moments"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Probability.CubeShuffle.WeightedMoments" +reference_modules = 40 +reference_lean_bytes = 815310 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 338 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12433 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/weighted-sweep-moments/tests/Challenge.lean b/tasks/weighted-sweep-moments/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..ca15ad3bd46a116f9e2bb777df62d50272fe03f5 --- /dev/null +++ b/tasks/weighted-sweep-moments/tests/Challenge.lean @@ -0,0 +1,304 @@ +import Mathlib + +namespace OAI + +namespace CubeShuffle.Specht + +open scoped BigOperators Classical + +abbrev Cell (μ : YoungDiagram) := {x : ℕ × ℕ // x ∈ μ.cells} +def row {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.1 +def col {μ : YoungDiagram} (x : Cell μ) : ℕ := x.1.2 + +lemma row_lt_colLen {μ : YoungDiagram} (x : Cell μ) : row x < μ.colLen (col x) := + YoungDiagram.mem_iff_lt_colLen.mp x.2 +noncomputable def rowIndex {μ : YoungDiagram} (x : Cell μ) : Fin (μ.colLen 0) := + ⟨row x, (row_lt_colLen x).trans_le (μ.colLen_anti 0 (col x) (Nat.zero_le _))⟩ + +abbrev Tabloid (μ : YoungDiagram) := + {f : Cell μ → Fin (μ.colLen 0) // ∃ p : Equiv.Perm (Cell μ), f = rowIndex ∘ p} + +noncomputable instance (μ : YoungDiagram) : Fintype (Tabloid μ) := Fintype.ofFinite _ + +noncomputable def baseTabloid (μ : YoungDiagram) : Tabloid μ := ⟨rowIndex, 1, rfl⟩ + +noncomputable def tabloidAct {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + Equiv.Perm (Tabloid μ) where + toFun f := ⟨fun x => f.1 (p⁻¹ x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p⁻¹, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + invFun f := ⟨fun x => f.1 (p x), by + obtain ⟨q,hq⟩ := f.2 + refine ⟨q*p, ?_⟩ + funext x + simp only [hq,Function.comp_apply,Equiv.Perm.mul_apply]⟩ + left_inv f := by apply Subtype.ext; funext x; simp + right_inv f := by apply Subtype.ext; funext x; simp + +@[simp] lemma tabloidAct_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (f : Tabloid μ) (x : Cell μ) : (tabloidAct p f).1 x = f.1 (p⁻¹ x) := rfl + +@[simp] lemma tabloidAct_one (μ : YoungDiagram) : tabloidAct (1 : Equiv.Perm (Cell μ)) = 1 := by + ext f x + rfl + +@[simp] lemma tabloidAct_mul {μ : YoungDiagram} (p q : Equiv.Perm (Cell μ)) : + tabloidAct (p*q) = tabloidAct p * tabloidAct q := by + ext f x + simp only [tabloidAct_apply, mul_inv_rev,Equiv.Perm.mul_apply] + +@[simp] lemma tabloidAct_inv {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) : + tabloidAct p⁻¹ = (tabloidAct p)⁻¹ := by + ext f x + simp [tabloidAct,Equiv.Perm.inv_def] + +noncomputable def tabloidRep (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (Tabloid μ → ℂ) where + toFun p := + { toFun := fun v f => v (tabloidAct p⁻¹ f) + map_add' := by intros; rfl + map_smul' := by intros; rfl } + map_one' := by ext v f; simp + map_mul' p q := by + ext v f + simp only [mul_inv_rev,tabloidAct_mul,Equiv.Perm.mul_apply] + rfl + +@[simp] lemma tabloidRep_apply {μ : YoungDiagram} (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (f : Tabloid μ) : tabloidRep μ p v f = v (tabloidAct p⁻¹ f) := rfl + +noncomputable def delta {μ : YoungDiagram} (f : Tabloid μ) : Tabloid μ → ℂ := + fun g => if g=f then 1 else 0 + +noncomputable def colGroup (μ : YoungDiagram) : Subgroup (Equiv.Perm (Cell μ)) where + carrier := {p | ∀ x, col (p x) = col x} + one_mem' := by intro x; rfl + mul_mem' := by intro p q hp hq x; exact (hp (q x)).trans (hq x) + inv_mem' := by intro p hp x; simpa using (hp (p⁻¹ x)).symm + +noncomputable def permSign {α : Type*} [Fintype α] [DecidableEq α] (p : Equiv.Perm α) : ℂ := + ((Equiv.Perm.sign p : ℤ) : ℂ) +section Alternator +variable {α V : Type*} [Fintype α] [DecidableEq α] [AddCommGroup V] [Module ℂ V] + +noncomputable def alternator (C : Subgroup (Equiv.Perm α)) + (ρ : Representation ℂ (Equiv.Perm α) V) : Module.End ℂ V := by + classical + exact ∑ c : C, permSign (c : Equiv.Perm α) • ρ c + +end Alternator + +noncomputable def polytabloid (μ : YoungDiagram) : Tabloid μ → ℂ := + alternator (colGroup μ) (tabloidRep μ) (delta (baseTabloid μ)) + +noncomputable def space (μ : YoungDiagram) : Submodule ℂ (Tabloid μ → ℂ) := + Submodule.span ℂ (Set.range (fun p : Equiv.Perm (Cell μ) => tabloidRep μ p (polytabloid μ))) + +lemma orbit_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) : + tabloidRep μ p (polytabloid μ) ∈ space μ := Submodule.subset_span ⟨p,rfl⟩ + +lemma action_mem_space (μ : YoungDiagram) (p : Equiv.Perm (Cell μ)) + (v : Tabloid μ → ℂ) (hv : v ∈ space μ) : tabloidRep μ p v ∈ space μ := by + induction hv using Submodule.span_induction with + | mem v hv => + obtain ⟨q,rfl⟩ := hv + change ((tabloidRep μ p)*(tabloidRep μ q)) (polytabloid μ) ∈ space μ + rw [←map_mul] + exact orbit_mem_space μ (p*q) + | zero => simp + | add v w hv hw ihv ihw => simpa using (space μ).add_mem ihv ihw + | smul a v hv ih => simpa using (space μ).smul_mem a ih + +noncomputable def subrepresentation (μ : YoungDiagram) : Subrepresentation (tabloidRep μ) := + ⟨space μ, fun p v hv => action_mem_space μ p v hv⟩ + +noncomputable def representation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (space μ) := + (subrepresentation μ).toRepresentation + +end CubeShuffle.Specht + +namespace CubeShuffle.PermutationHilbert + +open scoped BigOperators ComplexConjugate Classical +open Complex + +variable {X : Type*} [Fintype X] + +abbrev H (X : Type*) [Fintype X] := EuclideanSpace ℂ X + +end CubeShuffle.PermutationHilbert + +namespace CubeShuffle.Specht + +open scoped BigOperators Classical + +noncomputable def hilbertEquiv (μ : YoungDiagram) : + (Tabloid μ → ℂ) ≃ₗ[ℂ] PermutationHilbert.H (Tabloid μ) := + (WithLp.linearEquiv 2 ℂ (Tabloid μ → ℂ)).symm + +noncomputable def hilbertSpace (μ : YoungDiagram) : + Submodule ℂ (PermutationHilbert.H (Tabloid μ)) := (space μ).map (hilbertEquiv μ).toLinearMap + +noncomputable def spaceHilbertEquiv (μ : YoungDiagram) : space μ ≃ₗ[ℂ] hilbertSpace μ := + (hilbertEquiv μ).submoduleMap (space μ) + +noncomputable def unitaryRepresentation (μ : YoungDiagram) : + Representation ℂ (Equiv.Perm (Cell μ)) (hilbertSpace μ) := + ((spaceHilbertEquiv μ).conjAlgEquiv ℂ).toMonoidHom.comp (representation μ) + +variable {α ι : Type*} [Fintype α] [Fintype ι] + +noncomputable def relabelledUnitary (μ : YoungDiagram) (e : α ≃ Cell μ) : + Representation ℂ (Equiv.Perm α) (hilbertSpace μ) := + (unitaryRepresentation μ).comp e.permCongrHom.toMonoidHom + +end CubeShuffle.Specht + +namespace CubeShuffle + +open scoped BigOperators +open Filter + +abbrev Card (d : ℕ) := Fin d → Bool + +def Coins : ℕ → Type + | 0 => Unit + | d + 1 => Card d → Bool + +instance (d : ℕ) : Fintype (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +instance (d : ℕ) : Nonempty (Coins d) := by + cases d <;> dsimp [Coins] <;> infer_instance + +def switchFun {d : ℕ} (ξ : Card d → Bool) (x : Card (d + 1)) : Card (d + 1) := + Fin.cons (Bool.xor (x 0) (ξ (Fin.tail x))) (Fin.tail x) + +theorem switchFun_involutive {d : ℕ} (ξ : Card d → Bool) : + Function.Involutive (switchFun ξ) := by + intro x + funext i + refine Fin.cases ?_ (fun j => ?_) i + · simp only [switchFun, Fin.cons_zero, Fin.tail_cons] + cases x 0 <;> cases ξ (Fin.tail x) <;> rfl + · simp [switchFun, Fin.tail] + +def pairSwitch {d : ℕ} (ξ : Card d → Bool) : Equiv.Perm (Card (d + 1)) := + { toFun := switchFun ξ + invFun := switchFun ξ + left_inv := switchFun_involutive ξ + right_inv := switchFun_involutive ξ } + +def rotate (d : ℕ) : Equiv.Perm (Card d) where + toFun x i := x (finRotate d i) + invFun x i := x ((finRotate d).symm i) + left_inv x := by funext i; simp only [Equiv.apply_symm_apply] + right_inv x := by funext i; simp only [Equiv.symm_apply_apply] + +def step : (d : ℕ) → Coins d → Equiv.Perm (Card d) + | 0, _ => 1 + | d + 1, ξ => rotate (d + 1) * pairSwitch ξ + +def run (d : ℕ) : (t : ℕ) → (Fin t → Coins d) → Equiv.Perm (Card d) + | 0, _ => 1 + | t + 1, ω => step d (ω (Fin.last t)) * run d t (fun i => ω i.castSucc) + +lemma card_positions (d : ℕ) : Fintype.card (Card d) = 2 ^ d := by + simp [Card] + +end CubeShuffle + +namespace CubeShuffle.Specht +open scoped BigOperators Classical + +@[simp] lemma card_cell (μ : YoungDiagram) : Fintype.card (Cell μ) = μ.card := by + simp [Cell, YoungDiagram.card] + +abbrev Shapes (N : ℕ) := {μ : YoungDiagram // μ.card = N} + +noncomputable def labels {N : ℕ} (μ : Shapes N) : Cell μ.1 ≃ Fin N := + (Fintype.equivFin (Cell μ.1)).trans (finCongr ((card_cell μ.1).trans μ.2)) + +noncomputable def cardLabels (d : ℕ) (μ : Shapes (2^d)) : Card d ≃ Cell μ.1 := + ((Fintype.equivFin (Card d)).trans (finCongr (card_positions d))).trans (labels μ).symm + +noncomputable def cardRepresentation (d : ℕ) (μ : Shapes (2^d)) : + Representation ℂ (Equiv.Perm (Card d)) (hilbertSpace μ.1) := + relabelledUnitary μ.1 (cardLabels d μ) + +end CubeShuffle.Specht + +namespace CubeShuffle.UnitaryFinite +open scoped BigOperators ComplexConjugate Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] + +noncomputable def continuousRepresentation (ρ : Representation ℂ G V) : G →* (V →L[ℂ] V) where + toFun g := (ρ g).toContinuousLinearMap + map_one' := by ext v; simp + map_mul' g h := by ext v; simp + +end CubeShuffle.UnitaryFinite + +run_cmd Lean.modifyEnv fun env => Lean.Meta.auxLemmasExt.setState env {} + +namespace CubeShuffle.UnitaryFinite +open scoped BigOperators Classical +variable {G : Type*} [Group G] [Fintype G] +variable {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] [FiniteDimensional ℂ V] +variable {Ω Ξ : Type*} [Fintype Ω] [Fintype Ξ] + +noncomputable def sampleOperator (ρ : Representation ℂ G V) (P : Ω → G) : V →L[ℂ] V := + (Fintype.card Ω:ℂ)⁻¹ • ∑ ω,continuousRepresentation ρ (P ω) + +end CubeShuffle.UnitaryFinite + +noncomputable section +open scoped BigOperators Classical + +namespace CubeShuffle.WeightedSweep +open Specht UnitaryFinite + +def dimension (μ : YoungDiagram) : ℝ := Module.finrank ℂ (space μ) +def fourierSweep (d : ℕ) (μ : Shapes (2^d)) : + hilbertSpace μ.1 →L[ℂ] hilbertSpace μ.1 := + sampleOperator (V := hilbertSpace μ.1) (cardRepresentation d μ) (run d d) +def schattenMoment {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (A : V →L[ℂ] V) (p : ℝ) : ℝ := + ∑ i : Fin (Module.finrank ℂ V), (A.toLinearMap.singularValues i) ^ p + +def schattenNorm {V : Type*} [NormedAddCommGroup V] [InnerProductSpace ℂ V] + [FiniteDimensional ℂ V] (A : V →L[ℂ] V) (p : ℝ) : ℝ := + schattenMoment A p ^ (1 / p) + +end CubeShuffle.WeightedSweep + +end + +noncomputable section +open scoped BigOperators Classical + +namespace CubeShuffle.WeightedSweep +open Specht UnitaryFinite + +theorem weighted_sweep_moments : + ∃ (W : YoungDiagram → ℝ) (pStar : ℝ) (p : ℕ → ℝ), + (∀ μ : YoungDiagram, 0 < W μ) ∧ + 2 ≤ pStar ∧ + (∀ d : ℕ, 1 ≤ d → 2 ≤ p d ∧ p d ≤ pStar) ∧ + ∀ d : ℕ, 1 ≤ d → ∀ μ : Shapes (2 ^ d), + dimension μ.1 ^ (3 / 4 : ℝ) ≤ W μ.1 ∧ + W μ.1 ≤ dimension μ.1 ∧ + W μ.1 * + schattenNorm (V := hilbertSpace μ.1) (fourierSweep d μ) (p d) ^ (p d) ≤ 1 ∧ + ‖fourierSweep d μ‖ ≤ dimension μ.1 ^ (-3 / (4 * pStar)) := by + sorry + +end CubeShuffle.WeightedSweep + +end + +end OAI diff --git a/tasks/weighted-sweep-moments/tests/grade.py b/tasks/weighted-sweep-moments/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/weighted-sweep-moments/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/weighted-sweep-moments/tests/task.json b/tasks/weighted-sweep-moments/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..671516f0acc4cc5afa2641095a84a52b1fc1b34b --- /dev/null +++ b/tasks/weighted-sweep-moments/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WeightedSweepMoments", + "comparator": { + "theorem_names": [ + "OAI.CubeShuffle.WeightedSweep.weighted_sweep_moments" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11533 +} \ No newline at end of file diff --git a/tasks/weighted-sweep-moments/tests/test.sh b/tasks/weighted-sweep-moments/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/weighted-sweep-moments/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/weisfeiler-leman/environment/Dockerfile b/tasks/weisfeiler-leman/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/weisfeiler-leman/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/weisfeiler-leman/environment/fetch_mathlib.sh b/tasks/weisfeiler-leman/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/weisfeiler-leman/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/weisfeiler-leman/environment/lake-manifest.json b/tasks/weisfeiler-leman/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/weisfeiler-leman/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/weisfeiler-leman/environment/lakefile.lean b/tasks/weisfeiler-leman/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/weisfeiler-leman/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/weisfeiler-leman/environment/lean_setup.sh b/tasks/weisfeiler-leman/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/weisfeiler-leman/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/weisfeiler-leman/environment/pack_submission.py b/tasks/weisfeiler-leman/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/weisfeiler-leman/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/weisfeiler-leman/instruction.md b/tasks/weisfeiler-leman/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..2a9454581927cd549afac14643401c1acdcb8fb2 --- /dev/null +++ b/tasks/weisfeiler-leman/instruction.md @@ -0,0 +1,321 @@ +# openai/math challenge `WeisfeilerLeman` (family 133) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 133 of the release, *The complexity of Weisfeiler–Leman refinement* +(Theoretical computer science). The family as a whole: Proves unconditional $n^{\Omega(k)}$ deterministic time lower bounds for joint and separate $k$-dimensional Weisfeiler–Leman equivalence, for sufficiently large fixed $k$ in the specified sequential adjacency-matrix models. With dimension as input, joint equivalence is EXPTIME-complete even on subcubic graphs; deciding whether refinement identifies a graph is also EXPTIME-complete. + +The challenge is `WeisfeilerLeman`, also at `/opt/openai-math/challenges/WeisfeilerLeman.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace WLTime + +inductive Convention where + | joint | separate + deriving DecidableEq + +def Graph (n : ℕ) := + { a : Fin n → Fin n → Bool // + (∀ x y, a x y = a y x) ∧ (∀ x, a x x = false) } + +namespace Graph + +def adj {n : ℕ} (G : Graph n) : Fin n → Fin n → Bool := G.val + +def diameterTwo {n : ℕ} (G : Graph n) : Prop := + 0 < n ∧ ∀ x y, x = y ∨ G.adj x y = true ∨ + ∃ z, G.adj x z = true ∧ G.adj z y = true + +noncomputable instance (n : ℕ) : Fintype (Graph n) := by + classical + unfold Graph + infer_instance + +end Graph + +abbrev AtomicColor (k : ℕ) := + (Fin k → Fin k → Bool) × (Fin k → Fin k → Bool) + +def Color (c : Convention) (k : ℕ) : ℕ → Type + | 0 => AtomicColor k + | t + 1 => match c with + | .joint => Color c k t × Multiset (Fin k → Color c k t) + | .separate => Color c k t × (Fin k → Multiset (Color c k t)) + +noncomputable def tupleColor {n : ℕ} (c : Convention) (k : ℕ) (G : Graph n) : + (t : ℕ) → (Fin k → Fin n) → Color c k t + | 0, v => (fun i j => decide (v i = v j), fun i j => G.adj (v i) (v j)) + | t + 1, v => match c with + | .joint => (tupleColor .joint k G t v, + Finset.univ.val.map (fun z => fun i => + tupleColor .joint k G t (Function.update v i z))) + | .separate => (tupleColor .separate k G t v, + fun i => Finset.univ.val.map (fun z => + tupleColor .separate k G t (Function.update v i z))) + +noncomputable def histogram {n : ℕ} (c : Convention) (k : ℕ) (G : Graph n) + (t : ℕ) : Multiset (Color c k t) := + Finset.univ.val.map (tupleColor c k G t) + +def Equivalent {n : ℕ} (c : Convention) (k : ℕ) (G H : Graph n) : Prop := + ∀ t, histogram c k G t = histogram c k H t + +def encodeNat (n : ℕ) : List Bool := + let bits := (Nat.digits 2 n).map (fun b => decide (b = 1)) + List.replicate bits.length true ++ [false] ++ bits + +def matrixBits {n : ℕ} (G : Graph n) : List Bool := + (List.ofFn fun i : Fin n => List.ofFn fun j : Fin n => G.adj i j).flatten + +def encodePair {n : ℕ} (G H : Graph n) : List Bool := + encodeNat n ++ matrixBits G ++ matrixBits H + +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.displacement : Move → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure TM where + tapes : ℕ + states : ℕ + symbols : ℕ + tapes_pos : 0 < tapes + states_ge : 3 ≤ states + symbols_ge : 3 ≤ symbols + transition : Fin states → (Fin tapes → Fin symbols) → + Fin states × (Fin tapes → Fin symbols) × (Fin tapes → Move) + +namespace TM + +structure Config (M : TM) where + state : Fin M.states + head : Fin M.tapes → ℤ + tape : Fin M.tapes → ℤ → Fin M.symbols + +def symbol (M : TM) (b : Bool) : Fin M.symbols := + if b then ⟨2, by have := M.symbols_ge; omega⟩ else + ⟨1, by have := M.symbols_ge; omega⟩ + +def initial (M : TM) (w : List Bool) : M.Config where + state := ⟨0, by have := M.states_ge; omega⟩ + head := fun _ => 0 + tape := fun a z => if a.val = 0 ∧ 0 ≤ z ∧ z.toNat < w.length then + M.symbol (w.getD z.toNat false) else ⟨0, by have := M.symbols_ge; omega⟩ + +def halted (M : TM) (C : M.Config) : Prop := C.state.val = 1 ∨ C.state.val = 2 + +instance (M : TM) (C : M.Config) : Decidable (M.halted C) := inferInstanceAs + (Decidable (C.state.val = 1 ∨ C.state.val = 2)) + +def step (M : TM) (C : M.Config) : M.Config := + if M.halted C then C else + let tr := M.transition C.state (fun a => C.tape a (C.head a)) + { state := tr.1 + head := fun a => C.head a + (tr.2.2 a).displacement + tape := fun a z => if z = C.head a then tr.2.1 a else C.tape a z } + +def run (M : TM) (w : List Bool) (t : ℕ) : M.Config := M.step^[t] (M.initial w) + +def halts (M : TM) (w : List Bool) : Prop := ∃ t, M.halted (M.run w t) + +noncomputable def time (M : TM) (w : List Bool) : ℕ := by + classical + exact if h : M.halts w then Nat.find h else 0 + +def accepts (M : TM) (w : List Bool) : Prop := + ∃ t, (M.run w t).state.val = 1 + +def outputs (M : TM) (input output : List Bool) : Prop := + M.halts input ∧ ∀ i : Fin output.length, + (M.run input (M.time input)).tape ⟨0, M.tapes_pos⟩ (i.val : ℤ) = + M.symbol (output.get i) + +end TM + +abbrev Word (w : ℕ) := Fin (2 ^ w) + +def wordBits {w : ℕ} (a : Word w) : List Bool := + List.ofFn (fun i : Fin w => a.val.testBit i.val) + +def registerBits {R w : ℕ} (a : Fin R → Word w) : List Bool := + (List.ofFn fun i : Fin R => wordBits (a i)).flatten + +structure WordOperation (R : ℕ) where + apply : (w : ℕ) → (Fin R → Word w) → (Fin R → Word w) + implementation : TM + exponent : ℕ + constant : ℕ + computes : ∀ w a, implementation.outputs + (encodeNat w ++ registerBits a) (registerBits (apply w a)) + cost : ∀ w (a : Fin R → Word w), implementation.time (encodeNat w ++ registerBits a) ≤ + constant * (w + 1) ^ exponent + +inductive RAMInstruction (R P : ℕ) where + | halt (answer : Bool) + | jump (pc : Fin P) + | compute (op : WordOperation R) (next : RAMInstruction R P) + | load (dest addr : Fin R) (next : RAMInstruction R P) + | store (addr src : Fin R) (next : RAMInstruction R P) + | branchZero (reg : Fin R) (yes no : RAMInstruction R P) + +structure WordWidth where + bits : ℕ → ℕ + positive : ∀ n, 0 < bits n + bound : ℕ + logarithmic : ∀ n, bits n ≤ bound * (Nat.log2 (n + 2) + 1) + +structure RAM where + registers : ℕ + locations : ℕ + locations_pos : 0 < locations + width : WordWidth + program : Fin locations → RAMInstruction registers locations + input_fits : ∀ n (G H : Graph n), + (encodePair G H).length ≤ width.bits n * 2 ^ width.bits n + +namespace RAM + +structure Config (A : RAM) (n : ℕ) where + pc : Fin A.locations + registers : Fin A.registers → Word (A.width.bits n) + memory : Word (A.width.bits n) → Word (A.width.bits n) + answer : Option Bool + +def packedWord (w : ℕ) (input : List Bool) (a : Word w) : Word w := + ⟨(∑ i ∈ Finset.range w, if input.getD (w * a.val + i) false then 2 ^ i else 0) + % (2 ^ w), Nat.mod_lt _ (by positivity)⟩ + +def initial (A : RAM) (n : ℕ) (w : List Bool) : A.Config n where + pc := ⟨0, A.locations_pos⟩ + registers := fun _ => ⟨0, by positivity⟩ + memory := packedWord (A.width.bits n) w + answer := none + +def execute (A : RAM) {n : ℕ} : + RAMInstruction A.registers A.locations → A.Config n → A.Config n + | .halt b, C => { C with answer := some b } + | .jump p, C => { C with pc := p } + | .compute op next, C => A.execute next { C with + registers := op.apply (A.width.bits n) C.registers } + | .load dest addr next, C => A.execute next { C with + registers := Function.update C.registers dest (C.memory (C.registers addr)) } + | .store addr src next, C => A.execute next { C with + memory := Function.update C.memory (C.registers addr) (C.registers src) } + | .branchZero reg yes no, C => + if (C.registers reg).val = 0 then A.execute yes C else A.execute no C + +def step (A : RAM) {n : ℕ} (C : A.Config n) : A.Config n := + match C.answer with + | some _ => C + | none => A.execute (A.program C.pc) C + +def run (A : RAM) (n : ℕ) (w : List Bool) (t : ℕ) : A.Config n := + A.step^[t] (A.initial n w) + +def halts (A : RAM) (n : ℕ) (w : List Bool) : Prop := + ∃ t, (A.run n w t).answer.isSome = true + +noncomputable def time (A : RAM) (n : ℕ) (w : List Bool) : ℕ := by + classical + exact if h : A.halts n w then Nat.find h else 0 + +def accepts (A : RAM) (n : ℕ) (w : List Bool) : Prop := + ∃ t, (A.run n w t).answer = some true + +end RAM + +inductive Model where + | turing (machine : TM) + | ram (machine : RAM) + +def Model.halts (A : Model) (n : ℕ) (w : List Bool) : Prop := match A with + | .turing M => M.halts w + | .ram M => M.halts n w + +def Model.accepts (A : Model) (n : ℕ) (w : List Bool) : Prop := match A with + | .turing M => M.accepts w + | .ram M => M.accepts n w + +noncomputable def Model.time (A : Model) (n : ℕ) (w : List Bool) : ℕ := match A with + | .turing M => M.time w + | .ram M => M.time n w + +inductive InputClass where + | unrestricted | diameterTwo + deriving DecidableEq + +def InputClass.contains (p : InputClass) {n : ℕ} (G H : Graph n) : Prop := match p with + | .unrestricted => True + | .diameterTwo => G.diameterTwo ∧ H.diameterTwo + +def Decides (A : Model) (c : Convention) (k : ℕ) (p : InputClass) : Prop := + ∀ n (G H : Graph n), p.contains G H → + A.halts n (encodePair G H) ∧ + (A.accepts n (encodePair G H) ↔ Equivalent c k G H) + +noncomputable def worstTime (A : Model) (p : InputClass) (n : ℕ) : ℕ := by + classical + exact Finset.univ.sup (fun pair : Graph n × Graph n => + if p.contains pair.1 pair.2 then A.time n (encodePair pair.1 pair.2) else 0) + +def MainClaim : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ k₀ : ℕ, ∀ k : ℕ, k₀ ≤ k → + ∀ convention : Convention, ∀ p : InputClass, ∀ A : Model, + Decides A convention k p → ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → + (n : ℝ) ^ (c * (k : ℝ)) ≤ (worstTime A p n : ℝ) + +end WLTime + +theorem WLTime.unconditional_time_lower_bound : WLTime.MainClaim := by + sorry + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WeisfeilerLeman.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WLTime.unconditional_time_lower_bound` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/weisfeiler-leman/solution/closure.txt b/tasks/weisfeiler-leman/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..16cdf5796aa56128262b4a4aab453608c61dd70d --- /dev/null +++ b/tasks/weisfeiler-leman/solution/closure.txt @@ -0,0 +1,43 @@ +OAI.Computability.WeisfeilerLeman.Arithmetic +OAI.Computability.WeisfeilerLeman.BoundedRun +OAI.Computability.WeisfeilerLeman.Circuits +OAI.Computability.WeisfeilerLeman.Colors +OAI.Computability.WeisfeilerLeman.Consistency +OAI.Computability.WeisfeilerLeman.Consumer +OAI.Computability.WeisfeilerLeman.Diagonal +OAI.Computability.WeisfeilerLeman.Digits +OAI.Computability.WeisfeilerLeman.Enumeration +OAI.Computability.WeisfeilerLeman.Expressions +OAI.Computability.WeisfeilerLeman.Extension +OAI.Computability.WeisfeilerLeman.Frames +OAI.Computability.WeisfeilerLeman.Gadgets +OAI.Computability.WeisfeilerLeman.GraphFormula +OAI.Computability.WeisfeilerLeman.Interpreter +OAI.Computability.WeisfeilerLeman.Main +OAI.Computability.WeisfeilerLeman.Marking +OAI.Computability.WeisfeilerLeman.MatrixBounds +OAI.Computability.WeisfeilerLeman.MatrixWriter +OAI.Computability.WeisfeilerLeman.Model +OAI.Computability.WeisfeilerLeman.Offsets +OAI.Computability.WeisfeilerLeman.Padding +OAI.Computability.WeisfeilerLeman.Pebbles +OAI.Computability.WeisfeilerLeman.Predicates +OAI.Computability.WeisfeilerLeman.Programs +OAI.Computability.WeisfeilerLeman.RAMBounds +OAI.Computability.WeisfeilerLeman.RAMInstruction +OAI.Computability.WeisfeilerLeman.RAMMemory +OAI.Computability.WeisfeilerLeman.RAMSimulation +OAI.Computability.WeisfeilerLeman.Readouts +OAI.Computability.WeisfeilerLeman.Simulation +OAI.Computability.WeisfeilerLeman.SparseSearch +OAI.Computability.WeisfeilerLeman.SparseStore +OAI.Computability.WeisfeilerLeman.Stacks +OAI.Computability.WeisfeilerLeman.Sweep +OAI.Computability.WeisfeilerLeman.Tableau +OAI.Computability.WeisfeilerLeman.TapeCompiler +OAI.Computability.WeisfeilerLeman.TapePair +OAI.Computability.WeisfeilerLeman.Transducer +OAI.Computability.WeisfeilerLeman.Turing +OAI.Computability.WeisfeilerLeman.Universal +OAI.Computability.WeisfeilerLeman.Wrapping +OAI.Computability.WeisfeilerLeman.Writer diff --git a/tasks/weisfeiler-leman/solution/reference.py b/tasks/weisfeiler-leman/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/weisfeiler-leman/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/weisfeiler-leman/solution/solve.sh b/tasks/weisfeiler-leman/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..eff3e260461114ae2822fe8b999ec602678dcc76 --- /dev/null +++ b/tasks/weisfeiler-leman/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WeisfeilerLeman, i.e. module OAI.Computability.WeisfeilerLeman.Main and the +# 43 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.WeisfeilerLeman.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WeisfeilerLeman" diff --git a/tasks/weisfeiler-leman/task.toml b/tasks/weisfeiler-leman/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..33ba6dee97aca5d36fa67444b8ac6c6bef9a8d43 --- /dev/null +++ b/tasks/weisfeiler-leman/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/weisfeiler-leman" +version = "1.0.0" +description = "Prove WeisfeilerLeman (openai/math family 133: The complexity of Weisfeiler–Leman refinement) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WeisfeilerLeman.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WeisfeilerLeman" +family = "133" +family_title = "The complexity of Weisfeiler–Leman refinement" +subject = "Theoretical computer science" +theorems = ["OAI.WLTime.unconditional_time_lower_bound"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.WeisfeilerLeman.Main" +reference_modules = 43 +reference_lean_bytes = 917937 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 401 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12526 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/weisfeiler-leman/tests/Challenge.lean b/tasks/weisfeiler-leman/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..da205d7aff62b7573d0c34c4197b229af57ece6d --- /dev/null +++ b/tasks/weisfeiler-leman/tests/Challenge.lean @@ -0,0 +1,270 @@ +import Mathlib + +namespace OAI + +namespace WLTime + +inductive Convention where + | joint | separate + deriving DecidableEq + +def Graph (n : ℕ) := + { a : Fin n → Fin n → Bool // + (∀ x y, a x y = a y x) ∧ (∀ x, a x x = false) } + +namespace Graph + +def adj {n : ℕ} (G : Graph n) : Fin n → Fin n → Bool := G.val + +def diameterTwo {n : ℕ} (G : Graph n) : Prop := + 0 < n ∧ ∀ x y, x = y ∨ G.adj x y = true ∨ + ∃ z, G.adj x z = true ∧ G.adj z y = true + +noncomputable instance (n : ℕ) : Fintype (Graph n) := by + classical + unfold Graph + infer_instance + +end Graph + +abbrev AtomicColor (k : ℕ) := + (Fin k → Fin k → Bool) × (Fin k → Fin k → Bool) + +def Color (c : Convention) (k : ℕ) : ℕ → Type + | 0 => AtomicColor k + | t + 1 => match c with + | .joint => Color c k t × Multiset (Fin k → Color c k t) + | .separate => Color c k t × (Fin k → Multiset (Color c k t)) + +noncomputable def tupleColor {n : ℕ} (c : Convention) (k : ℕ) (G : Graph n) : + (t : ℕ) → (Fin k → Fin n) → Color c k t + | 0, v => (fun i j => decide (v i = v j), fun i j => G.adj (v i) (v j)) + | t + 1, v => match c with + | .joint => (tupleColor .joint k G t v, + Finset.univ.val.map (fun z => fun i => + tupleColor .joint k G t (Function.update v i z))) + | .separate => (tupleColor .separate k G t v, + fun i => Finset.univ.val.map (fun z => + tupleColor .separate k G t (Function.update v i z))) + +noncomputable def histogram {n : ℕ} (c : Convention) (k : ℕ) (G : Graph n) + (t : ℕ) : Multiset (Color c k t) := + Finset.univ.val.map (tupleColor c k G t) + +def Equivalent {n : ℕ} (c : Convention) (k : ℕ) (G H : Graph n) : Prop := + ∀ t, histogram c k G t = histogram c k H t + +def encodeNat (n : ℕ) : List Bool := + let bits := (Nat.digits 2 n).map (fun b => decide (b = 1)) + List.replicate bits.length true ++ [false] ++ bits + +def matrixBits {n : ℕ} (G : Graph n) : List Bool := + (List.ofFn fun i : Fin n => List.ofFn fun j : Fin n => G.adj i j).flatten + +def encodePair {n : ℕ} (G H : Graph n) : List Bool := + encodeNat n ++ matrixBits G ++ matrixBits H + +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.displacement : Move → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure TM where + tapes : ℕ + states : ℕ + symbols : ℕ + tapes_pos : 0 < tapes + states_ge : 3 ≤ states + symbols_ge : 3 ≤ symbols + transition : Fin states → (Fin tapes → Fin symbols) → + Fin states × (Fin tapes → Fin symbols) × (Fin tapes → Move) + +namespace TM + +structure Config (M : TM) where + state : Fin M.states + head : Fin M.tapes → ℤ + tape : Fin M.tapes → ℤ → Fin M.symbols + +def symbol (M : TM) (b : Bool) : Fin M.symbols := + if b then ⟨2, by have := M.symbols_ge; omega⟩ else + ⟨1, by have := M.symbols_ge; omega⟩ + +def initial (M : TM) (w : List Bool) : M.Config where + state := ⟨0, by have := M.states_ge; omega⟩ + head := fun _ => 0 + tape := fun a z => if a.val = 0 ∧ 0 ≤ z ∧ z.toNat < w.length then + M.symbol (w.getD z.toNat false) else ⟨0, by have := M.symbols_ge; omega⟩ + +def halted (M : TM) (C : M.Config) : Prop := C.state.val = 1 ∨ C.state.val = 2 + +instance (M : TM) (C : M.Config) : Decidable (M.halted C) := inferInstanceAs + (Decidable (C.state.val = 1 ∨ C.state.val = 2)) + +def step (M : TM) (C : M.Config) : M.Config := + if M.halted C then C else + let tr := M.transition C.state (fun a => C.tape a (C.head a)) + { state := tr.1 + head := fun a => C.head a + (tr.2.2 a).displacement + tape := fun a z => if z = C.head a then tr.2.1 a else C.tape a z } + +def run (M : TM) (w : List Bool) (t : ℕ) : M.Config := M.step^[t] (M.initial w) + +def halts (M : TM) (w : List Bool) : Prop := ∃ t, M.halted (M.run w t) + +noncomputable def time (M : TM) (w : List Bool) : ℕ := by + classical + exact if h : M.halts w then Nat.find h else 0 + +def accepts (M : TM) (w : List Bool) : Prop := + ∃ t, (M.run w t).state.val = 1 + +def outputs (M : TM) (input output : List Bool) : Prop := + M.halts input ∧ ∀ i : Fin output.length, + (M.run input (M.time input)).tape ⟨0, M.tapes_pos⟩ (i.val : ℤ) = + M.symbol (output.get i) + +end TM + +abbrev Word (w : ℕ) := Fin (2 ^ w) + +def wordBits {w : ℕ} (a : Word w) : List Bool := + List.ofFn (fun i : Fin w => a.val.testBit i.val) + +def registerBits {R w : ℕ} (a : Fin R → Word w) : List Bool := + (List.ofFn fun i : Fin R => wordBits (a i)).flatten + +structure WordOperation (R : ℕ) where + apply : (w : ℕ) → (Fin R → Word w) → (Fin R → Word w) + implementation : TM + exponent : ℕ + constant : ℕ + computes : ∀ w a, implementation.outputs + (encodeNat w ++ registerBits a) (registerBits (apply w a)) + cost : ∀ w (a : Fin R → Word w), implementation.time (encodeNat w ++ registerBits a) ≤ + constant * (w + 1) ^ exponent + +inductive RAMInstruction (R P : ℕ) where + | halt (answer : Bool) + | jump (pc : Fin P) + | compute (op : WordOperation R) (next : RAMInstruction R P) + | load (dest addr : Fin R) (next : RAMInstruction R P) + | store (addr src : Fin R) (next : RAMInstruction R P) + | branchZero (reg : Fin R) (yes no : RAMInstruction R P) + +structure WordWidth where + bits : ℕ → ℕ + positive : ∀ n, 0 < bits n + bound : ℕ + logarithmic : ∀ n, bits n ≤ bound * (Nat.log2 (n + 2) + 1) + +structure RAM where + registers : ℕ + locations : ℕ + locations_pos : 0 < locations + width : WordWidth + program : Fin locations → RAMInstruction registers locations + input_fits : ∀ n (G H : Graph n), + (encodePair G H).length ≤ width.bits n * 2 ^ width.bits n + +namespace RAM + +structure Config (A : RAM) (n : ℕ) where + pc : Fin A.locations + registers : Fin A.registers → Word (A.width.bits n) + memory : Word (A.width.bits n) → Word (A.width.bits n) + answer : Option Bool + +def packedWord (w : ℕ) (input : List Bool) (a : Word w) : Word w := + ⟨(∑ i ∈ Finset.range w, if input.getD (w * a.val + i) false then 2 ^ i else 0) + % (2 ^ w), Nat.mod_lt _ (by positivity)⟩ + +def initial (A : RAM) (n : ℕ) (w : List Bool) : A.Config n where + pc := ⟨0, A.locations_pos⟩ + registers := fun _ => ⟨0, by positivity⟩ + memory := packedWord (A.width.bits n) w + answer := none + +def execute (A : RAM) {n : ℕ} : + RAMInstruction A.registers A.locations → A.Config n → A.Config n + | .halt b, C => { C with answer := some b } + | .jump p, C => { C with pc := p } + | .compute op next, C => A.execute next { C with + registers := op.apply (A.width.bits n) C.registers } + | .load dest addr next, C => A.execute next { C with + registers := Function.update C.registers dest (C.memory (C.registers addr)) } + | .store addr src next, C => A.execute next { C with + memory := Function.update C.memory (C.registers addr) (C.registers src) } + | .branchZero reg yes no, C => + if (C.registers reg).val = 0 then A.execute yes C else A.execute no C + +def step (A : RAM) {n : ℕ} (C : A.Config n) : A.Config n := + match C.answer with + | some _ => C + | none => A.execute (A.program C.pc) C + +def run (A : RAM) (n : ℕ) (w : List Bool) (t : ℕ) : A.Config n := + A.step^[t] (A.initial n w) + +def halts (A : RAM) (n : ℕ) (w : List Bool) : Prop := + ∃ t, (A.run n w t).answer.isSome = true + +noncomputable def time (A : RAM) (n : ℕ) (w : List Bool) : ℕ := by + classical + exact if h : A.halts n w then Nat.find h else 0 + +def accepts (A : RAM) (n : ℕ) (w : List Bool) : Prop := + ∃ t, (A.run n w t).answer = some true + +end RAM + +inductive Model where + | turing (machine : TM) + | ram (machine : RAM) + +def Model.halts (A : Model) (n : ℕ) (w : List Bool) : Prop := match A with + | .turing M => M.halts w + | .ram M => M.halts n w + +def Model.accepts (A : Model) (n : ℕ) (w : List Bool) : Prop := match A with + | .turing M => M.accepts w + | .ram M => M.accepts n w + +noncomputable def Model.time (A : Model) (n : ℕ) (w : List Bool) : ℕ := match A with + | .turing M => M.time w + | .ram M => M.time n w + +inductive InputClass where + | unrestricted | diameterTwo + deriving DecidableEq + +def InputClass.contains (p : InputClass) {n : ℕ} (G H : Graph n) : Prop := match p with + | .unrestricted => True + | .diameterTwo => G.diameterTwo ∧ H.diameterTwo + +def Decides (A : Model) (c : Convention) (k : ℕ) (p : InputClass) : Prop := + ∀ n (G H : Graph n), p.contains G H → + A.halts n (encodePair G H) ∧ + (A.accepts n (encodePair G H) ↔ Equivalent c k G H) + +noncomputable def worstTime (A : Model) (p : InputClass) (n : ℕ) : ℕ := by + classical + exact Finset.univ.sup (fun pair : Graph n × Graph n => + if p.contains pair.1 pair.2 then A.time n (encodePair pair.1 pair.2) else 0) + +def MainClaim : Prop := + ∃ c : ℝ, 0 < c ∧ ∃ k₀ : ℕ, ∀ k : ℕ, k₀ ≤ k → + ∀ convention : Convention, ∀ p : InputClass, ∀ A : Model, + Decides A convention k p → ∃ n₀ : ℕ, ∀ n : ℕ, n₀ ≤ n → + (n : ℝ) ^ (c * (k : ℝ)) ≤ (worstTime A p n : ℝ) + +end WLTime + +theorem WLTime.unconditional_time_lower_bound : WLTime.MainClaim := by + sorry + +end OAI diff --git a/tasks/weisfeiler-leman/tests/grade.py b/tasks/weisfeiler-leman/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/weisfeiler-leman/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/weisfeiler-leman/tests/task.json b/tasks/weisfeiler-leman/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..9408446b66d5e28fe7bb123e44e55258aeec39f9 --- /dev/null +++ b/tasks/weisfeiler-leman/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WeisfeilerLeman", + "comparator": { + "theorem_names": [ + "OAI.WLTime.unconditional_time_lower_bound" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11626 +} \ No newline at end of file diff --git a/tasks/weisfeiler-leman/tests/test.sh b/tasks/weisfeiler-leman/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/weisfeiler-leman/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/witnessed-choice/environment/Dockerfile b/tasks/witnessed-choice/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/witnessed-choice/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/witnessed-choice/environment/fetch_mathlib.sh b/tasks/witnessed-choice/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/witnessed-choice/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/witnessed-choice/environment/lake-manifest.json b/tasks/witnessed-choice/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/witnessed-choice/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/witnessed-choice/environment/lakefile.lean b/tasks/witnessed-choice/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/witnessed-choice/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/witnessed-choice/environment/lean_setup.sh b/tasks/witnessed-choice/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/witnessed-choice/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/witnessed-choice/environment/pack_submission.py b/tasks/witnessed-choice/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/witnessed-choice/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/witnessed-choice/instruction.md b/tasks/witnessed-choice/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..b9d087c490ff6e04aa2cca8bbb94952d3a810cd3 --- /dev/null +++ b/tasks/witnessed-choice/instruction.md @@ -0,0 +1,525 @@ +# openai/math challenge `WitnessedChoice` (family 243) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 243 of the release, *Choiceless counting does not capture polynomial time* +(Mathematical logic). The family as a whole: Confirms the Blass–Gurevich–Shelah noncapture conjecture: consistency of a linear system over $\mathbb F_3$ defines a polynomial-time query on unordered finite structures that choiceless polynomial time with counting cannot express. A separate result shows that adding witnessed symmetric choice strictly increases expressive power. Both separations hold for the full counting formalism, allowing hereditarily finite sets of arbitrary finite rank. + +The challenge is `WitnessedChoice`, also at `/opt/openai-math/challenges/WitnessedChoice.lean`: + +```lean +import Mathlib + +namespace OAI + +noncomputable section + +universe u v w + +namespace WitnessedSeparation + +namespace Hereditary + +abbrev HF (A : Type u) := Quotient (@Lists.instSetoidLists A) + +variable {A : Type u} {B : Type v} + +section + +local instance {A : Type u} : DecidableEq (HF A) := Classical.decEq _ + +def mk (l : Lists A) : HF A := Quotient.mk Lists.instSetoidLists l + +def atom (a : A) : HF A := mk (Lists.atom a) + +def isSet (x : HF A) : Bool := Quotient.liftOn x (fun l => l.1) + (by intro l r h; cases h <;> rfl) + +def rawElements (l : Lists A) : Finset (HF A) := by + classical + exact l.toList.toFinset.image mk + +def elements (x : HF A) : Finset (HF A) := Quotient.liftOn x rawElements (by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have raw_mem_congr_right {l r : Lists A} (h : Lists.Equiv l r) (a : Lists A) : + a ∈ l ↔ a ∈ r := by + cases h with + | refl => rfl + | antisymm hl hr => + exact ⟨Lists'.mem_of_subset hl, Lists'.mem_of_subset hr⟩ + intro l r h + ext z + induction z using Quotient.inductionOn with + | _ a => + change mk a ∈ rawElements l ↔ mk a ∈ rawElements r + rw [mem_rawElements, mem_rawElements] + exact raw_mem_congr_right h a) + +instance : Membership (HF A) (HF A) := ⟨fun y x => x ∈ elements y⟩ + +def ofFinset (s : Finset (HF A)) : HF A := + mk (Lists.ofList (s.toList.map Quotient.out)) + +def rawRank' : {b : Bool} → Lists' A b → ℕ + | _, .atom _ => 0 + | _, .nil => 0 + | _, .cons' a l => max (rawRank' a + 1) (rawRank' l) + +def rawRank (l : Lists A) : ℕ := rawRank' l.2 + +def rank (x : HF A) : ℕ := Quotient.liftOn x rawRank (by + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _ _ ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _ hmem _ iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + exact fun _ _ h => rawRank_congr h) + +def rawMap' (f : A → B) : {b : Bool} → Lists' A b → Lists' B b + | _, .atom a => .atom (f a) + | _, .nil => .nil + | _, .cons' a l => .cons' (rawMap' f a) (rawMap' f l) + +def rawMap (f : A → B) (l : Lists A) : Lists B := ⟨l.1, rawMap' f l.2⟩ + +def map (f : A → B) (x : HF A) : HF B := by + have toList_rawMap' (f : A → B) {b : Bool} (l : Lists' A b) : + (rawMap' f l).toList = l.toList.map (rawMap f) := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', Lists'.toList, ihl]; rfl + have rawMap_congr (f : A → B) {l r : Lists A} (h : Lists.Equiv l r) : + Lists.Equiv (rawMap f l) (rawMap f r) := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => Lists'.Subset (rawMap' f l) (rawMap' f r)) with + | refl => exact Lists.Equiv.refl _ + | antisymm hl hr ihl ihr => exact Lists.Equiv.antisymm ihl ihr + | nil => exact Lists'.Subset.nil + | @cons a a' l r _ hmem _ iheq ihsub => + apply Lists'.Subset.cons iheq _ ihsub + rw [toList_rawMap'] + exact List.mem_map.mpr ⟨a',hmem,rfl⟩ + exact Quotient.liftOn x (fun l => mk (rawMap f l)) (fun _ _ h => Quotient.eq.mpr (rawMap_congr f h)) + +instance {G : Type w} [Group G] [MulAction G A] : MulAction G (HF A) := by + have map_mk {A B : Type u} (f : A → B) (l : Lists A) : map f (mk l) = mk (rawMap f l) := rfl + have rawMap_id {A : Type u} : ∀ l : Lists A, rawMap id l = l := by + rintro ⟨b,l⟩ + have h : rawMap' id l = l := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', iha,ihl] + exact congrArg (Sigma.mk b) h + have map_id {A : Type u} (x : HF A) : map id x = x := by + induction x using Quotient.inductionOn with + | _ l => + change map id (mk l) = mk l + rw [map_mk, rawMap_id] + have rawMap_comp {A B : Type u} {C : Type u} (g : B → C) (f : A → B) (l : Lists A) : + rawMap g (rawMap f l) = rawMap (g ∘ f) l := by + rcases l with ⟨b,l⟩ + have h : rawMap' g (rawMap' f l) = rawMap' (g ∘ f) l := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', iha,ihl] + exact congrArg (Sigma.mk b) h + have map_comp {A B : Type u} {C : Type u} (g : B → C) (f : A → B) (x : HF A) : + map g (map f x) = map (g ∘ f) x := by + induction x using Quotient.inductionOn with + | _ l => + change map g (map f (mk l)) = map (g ∘ f) (mk l) + simp only [map_mk,rawMap_comp] + exact { + smul g x := map (fun a => g • a) x + one_smul x := by + change map (fun a : A => (1 : G) • a) x = x + have h : (fun a : A => (1 : G) • a) = id := by funext a; simp + rw [h,map_id] + mul_smul g h x := by + change map (fun a : A => (g*h) • a) x = map (fun a => g • a) (map (fun a => h • a) x) + rw [map_comp] + congr 1 + funext a + exact mul_smul g h a } + +end + +open Classical Finset + +def singleton (a : HF A) : HF A := ofFinset {a} + +def double (a b : HF A) : HF A := ofFinset {a,b} + +def pair (a b : HF A) : HF A := double (singleton a) (double a b) + +def ordinal : ℕ → HF A + | 0 => ofFinset ∅ + | i+1 => ofFinset (insert (ordinal i) (elements (ordinal i))) + +local instance {C : Type w} : DecidableEq (HF C) := Classical.decEq _ + +def closure (x : HF A) : Finset (HF A) := + insert x ((elements x).attach.biUnion (fun y => closure y.val)) +termination_by rank x +decreasing_by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _ _ ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _ hmem _ iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + have rank_lt_of_mem {x y : HF A} (h : x ∈ y) : rank x < rank y := by + induction y using Quotient.inductionOn with + | _ l => + induction x using Quotient.inductionOn with + | _ a => + have h' := (mem_rawElements a l).mp h + rcases l with ⟨(_ | _), l⟩ + · exact False.elim h' + · obtain ⟨a',ha',heq⟩ := h' + change rawRank a < rawRank' l + rw [rawRank_congr heq] + exact rawRank_lt_of_mem l a' ha' + exact rank_lt_of_mem y.property + +end Hereditary + +abbrev Scalar := ZMod 3 + +inductive Symbol + | Ed | Cf | EB | VB | I | Z (δ : Scalar) + deriving DecidableEq, Fintype + +structure Input (A : Type) where + rel : Symbol → A → A → Bool + +end WitnessedSeparation + +namespace WitnessedChoice + +namespace BGS + +open Classical WitnessedSeparation WitnessedSeparation.Hereditary + +mutual + +inductive Term : ℕ → Type + | var {n} (i : Fin n) : Term n + | empty {n} : Term n + | atoms {n} : Term n + | pair {n} (a b : Term n) : Term n + | union {n} (a : Term n) : Term n + | unique {n} (a : Term n) : Term n + | card {n} (a : Term n) : Term n + | comprehend {n} (body : Term (n+1)) (range : Term n) + (guard : Formula (n+1)) : Term n + | iterate {n} (step : Term (n+1)) : Term n + inductive Formula : ℕ → Type + | equal {n} (a b : Term n) : Formula n + | input {n} (r : Symbol) (a b : Term n) : Formula n + | neg {n} (a : Formula n) : Formula n + | and {n} (a b : Formula n) : Formula n + | or {n} (a b : Formula n) : Formula n + | wsc {n} (step : Term (n+2)) (choice : Term (n+1)) + (witness : Term (n+2)) (output : Formula (n+1)) : Formula n + +end + +def dropFree {n} (f : Finset (Fin (n+1))) : Finset (Fin n) := + Finset.univ.filter (fun i => i.succ ∈ f) + +mutual + +def Term.free : {n : ℕ} → Term n → Finset (Fin n) + | _, .var i => {i} + | _, .empty | _, .atoms => ∅ + | _, .pair a b => a.free ∪ b.free + | _, .union a | _, .unique a | _, .card a => a.free + | _, .comprehend body range guard => range.free ∪ dropFree (body.free ∪ guard.free) + | _, .iterate step => dropFree step.free + def Formula.free : {n : ℕ} → Formula n → Finset (Fin n) + | _, .equal a b | _, .input _ a b => a.free ∪ b.free + | _, .neg a => a.free + | _, .and a b | _, .or a b => a.free ∪ b.free + | _, .wsc step choice witness output => + dropFree (dropFree (step.free ∪ witness.free)) ∪ dropFree (choice.free ∪ output.free) + +end + +mutual + +def Term.wscCount : {n : ℕ} → Term n → ℕ + | _, .var _ | _, .empty | _, .atoms => 0 + | _, .pair a b => a.wscCount + b.wscCount + | _, .union a | _, .unique a | _, .card a => a.wscCount + | _, .comprehend body range guard => body.wscCount + range.wscCount + guard.wscCount + | _, .iterate step => step.wscCount + def Formula.wscCount : {n : ℕ} → Formula n → ℕ + | _, .equal a b | _, .input _ a b => a.wscCount + b.wscCount + | _, .neg a => a.wscCount + | _, .and a b | _, .or a b => a.wscCount + b.wscCount + | _, .wsc step choice witness output => + 1 + step.wscCount + choice.wscCount + witness.wscCount + output.wscCount + +end + +variable {A : Type} + +abbrev Result (α : Type) := Option α + +def emptyHF : HF A := ofFinset ∅ + +def TC (x : HF A) : Finset (HF A) := (elements x).biUnion closure + +def unionHF (x : HF A) : HF A := ofFinset ((elements x).biUnion elements) + +def uniqueHF (x : HF A) : HF A := + if h : ∃ y, elements x = {y} then h.choose else emptyHF + +def cardHF (x : HF A) : HF A := ordinal (elements x).card + +def inputHF (S : Input A) (r : Symbol) (x y : HF A) : Bool := + decide (∃ a b, x = atom a ∧ y = atom b ∧ S.rel r a b = true) + +def lift₂ {X Y Z : Type} (f : X → Y → Z) (a : Result X) (b : Result Y) : Result Z := + a.bind (fun x => b.map (f x)) + +def collect (r : HF A) (guard : HF A → Result Bool) (body : HF A → Result (HF A)) : + Result (HF A) := + if (∀ x ∈ elements r, (guard x).isSome) ∧ + (∀ x ∈ elements r, guard x = some true → (body x).isSome) then + some (ofFinset (((elements r).filter (fun x => guard x = some true)).image + (fun x => (body x).getD emptyHF))) + else none + +def iterationLoop (p : ℕ) (step : HF A → Result (HF A)) : ℕ → HF A → Result (HF A) + | 0, _ => some emptyHF + | fuel+1, x => + if (TC x).card ≤ p then + (step x).bind (fun y => + if x = y then some x else iterationLoop p step fuel y) + else some emptyHF + +def ordinaryIteration (p : ℕ) (step : HF A → Result (HF A)) : Result (HF A) := + iterationLoop p step (p+1) emptyHF + +def resource (p : Polynomial ℝ) (n : ℕ) : ℕ := ⌊p.eval (n : ℝ)⌋₊ + +variable [Fintype A] + +def permutationGraph (g : Equiv.Perm A) : HF A := + ofFinset (Finset.univ.image (fun a => pair (atom a) (atom (g a)))) + +def Automorphism (S : Input A) (g : Equiv.Perm A) : Prop := + ∀ r a b, S.rel r (g a) (g b) = S.rel r a b + +def ChoicePrefix (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (b c : ℕ → HF A) (k : ℕ) : Prop := + b 0 = emptyHF ∧ ∀ i < k, + (∃ D, choice (b i) = some D ∧ c i ∈ elements D) ∧ + step (b i) (c i) = some (b (i+1)) + +def StrictPrefix (b : ℕ → HF A) (k : ℕ) : Prop := ∀ i < k, b i ≠ b (i+1) + +def FirstPath (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (b c : ℕ → HF A) (t : ℕ) : Prop := + ChoicePrefix step choice b c (t+1) ∧ StrictPrefix b t ∧ b t = b (t+1) + +def FixesParameters {n : ℕ} (free : Finset (Fin n)) (env : Fin n → HF A) + (g : Equiv.Perm A) : Prop := ∀ i ∈ free, g • env i = env i + +def WitnessesHistory {n : ℕ} (S : Input A) (free : Finset (Fin n)) + (env : Fin n → HF A) (b : ℕ → HF A) (i : ℕ) (D M : HF A) : Prop := + isSet M = true ∧ + (∀ w ∈ elements M, ∃ g : Equiv.Perm A, + w = permutationGraph g ∧ Automorphism S g ∧ FixesParameters free env g ∧ + ∀ j ≤ i, g • b j = b j) ∧ + (∀ u ∈ elements D, ∀ v ∈ elements D, ∃ g : Equiv.Perm A, + permutationGraph g ∈ elements M ∧ g • u = v) + +def GoodWSC {n : ℕ} (S : Input A) (p : ℕ) (free : Finset (Fin n)) + (env : Fin n → HF A) (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (witness : HF A → HF A → Result (HF A)) + (output : HF A → Result Bool) : Prop := + (∀ b c k, ChoicePrefix step choice b c k → StrictPrefix b k → + k ≤ p ∧ (TC (b k)).card ≤ p ∧ ∃ D, choice (b k) = some D ∧ + (elements D).Nonempty ∧ ∀ u ∈ elements D, (step (b k) u).isSome) ∧ + (∀ b c t, FirstPath step choice b c t → t+2 ≤ p ∧ + (∀ i ≤ t, ∃ D M, choice (b i) = some D ∧ witness (b t) (b i) = some M ∧ + WitnessesHistory S free env b i D M) ∧ (output (b t)).isSome) + +def witnessedIteration {n : ℕ} (S : Input A) (p : ℕ) (free : Finset (Fin n)) + (env : Fin n → HF A) (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (witness : HF A → HF A → Result (HF A)) + (output : HF A → Result Bool) : Result Bool := + if GoodWSC S p free env step choice witness output then + some (decide (∀ b c t, FirstPath step choice b c t → output (b t) = some true)) + else none + +mutual + +def Term.eval (S : Input A) (p : Polynomial ℝ) : {n : ℕ} → Term n → + (Fin n → HF A) → Result (HF A) + | _, .var i, env => some (env i) + | _, .empty, _ => some emptyHF + | _, .atoms, _ => some (ofFinset (Finset.univ.image atom)) + | _, .pair a b, env => lift₂ double (a.eval S p env) (b.eval S p env) + | _, .union a, env => (a.eval S p env).map unionHF + | _, .unique a, env => (a.eval S p env).map uniqueHF + | _, .card a, env => (a.eval S p env).map cardHF + | _, .comprehend body range guard, env => + (range.eval S p env).bind (fun r => collect r + (fun x => guard.eval S p (Fin.cons x env)) + (fun x => body.eval S p (Fin.cons x env))) + | _, .iterate step, env => ordinaryIteration (resource p (Fintype.card A)) + (fun x => step.eval S p (Fin.cons x env)) + def Formula.eval (S : Input A) (p : Polynomial ℝ) : {n : ℕ} → Formula n → + (Fin n → HF A) → Result Bool + | _, .equal a b, env => lift₂ (fun x y => decide (x = y)) (a.eval S p env) (b.eval S p env) + | _, .input r a b, env => lift₂ (inputHF S r) (a.eval S p env) (b.eval S p env) + | _, .neg a, env => (a.eval S p env).map Bool.not + | _, .and a b, env => lift₂ Bool.and (a.eval S p env) (b.eval S p env) + | _, .or a b, env => lift₂ Bool.or (a.eval S p env) (b.eval S p env) + | _, .wsc step choice witness output, env => + witnessedIteration S (resource p (Fintype.card A)) + (Formula.wsc step choice witness output).free env + (fun x y => step.eval S p (Fin.cons y (Fin.cons x env))) + (fun x => choice.eval S p (Fin.cons x env)) + (fun z x => witness.eval S p (Fin.cons x (Fin.cons z env))) + (fun x => output.eval S p (Fin.cons x env)) + +end + +structure FiniteInput where + Carrier : Type + finite : Fintype Carrier + input : Input Carrier + +attribute [instance] FiniteInput.finite + +structure Sentence where + formula : Formula 0 + polynomial : Polynomial ℝ + +def Sentence.eval (φ : Sentence) (S : FiniteInput) : Result Bool := + φ.formula.eval S.input φ.polynomial Fin.elim0 + +def Sentence.isCPT (φ : Sentence) : Prop := φ.formula.wscCount = 0 + +def Sentence.BooleanOnAllInputs (φ : Sentence) : Prop := + ∀ S, ∃ b : Bool, φ.eval S = some b + +def Sentence.TrueModels (φ : Sentence) : Set FiniteInput := {S | φ.eval S = some true} + +def MainStatement : Prop := ∃ φ : Sentence, + φ.formula.wscCount = 1 ∧ φ.BooleanOnAllInputs ∧ + ∀ ψ : Sentence, ψ.isCPT → φ.TrueModels ≠ ψ.TrueModels + +end BGS + +end WitnessedChoice + +theorem WitnessedChoice.main : WitnessedChoice.BGS.MainStatement := by + sorry + +end + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WitnessedChoice.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WitnessedChoice.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/witnessed-choice/solution/closure.txt b/tasks/witnessed-choice/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..498e9978c9da1d9169918ba8800feedd773c8d36 --- /dev/null +++ b/tasks/witnessed-choice/solution/closure.txt @@ -0,0 +1,27 @@ +OAI.Computability.WitnessedChoice.AnchoredTree +OAI.Computability.WitnessedChoice.ChoiceSeparation +OAI.Computability.WitnessedChoice.ChoiceTrace +OAI.Computability.WitnessedChoice.Counting +OAI.Computability.WitnessedChoice.CountingTransfer +OAI.Computability.WitnessedChoice.CumulativeEvaluation +OAI.Computability.WitnessedChoice.CycleTranslation +OAI.Computability.WitnessedChoice.EncodedCounting +OAI.Computability.WitnessedChoice.EvaluationTrace +OAI.Computability.WitnessedChoice.FormTransfer +OAI.Computability.WitnessedChoice.GridAction +OAI.Computability.WitnessedChoice.GridGeometry +OAI.Computability.WitnessedChoice.GuardedProgram +OAI.Computability.WitnessedChoice.Hereditary +OAI.Computability.WitnessedChoice.Homogeneity +OAI.Computability.WitnessedChoice.LowerBound +OAI.Computability.WitnessedChoice.Machines +OAI.Computability.WitnessedChoice.Main +OAI.Computability.WitnessedChoice.Model +OAI.Computability.WitnessedChoice.QuotedSyntax +OAI.Computability.WitnessedChoice.SupportGrid +OAI.Computability.WitnessedChoice.SupportedForms +OAI.Computability.WitnessedChoice.Syntax +OAI.Computability.WitnessedChoice.TermGraphs +OAI.Computability.WitnessedChoice.TraceGraphs +OAI.Computability.WitnessedChoice.TreeCorrection +OAI.Computability.WitnessedChoice.TreeElimination diff --git a/tasks/witnessed-choice/solution/reference.py b/tasks/witnessed-choice/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/witnessed-choice/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/witnessed-choice/solution/solve.sh b/tasks/witnessed-choice/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..4d0f20e954725c81a9e7ab6406f83c4f65835ec5 --- /dev/null +++ b/tasks/witnessed-choice/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WitnessedChoice, i.e. module OAI.Computability.WitnessedChoice.Main and the +# 27 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.WitnessedChoice.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WitnessedChoice" diff --git a/tasks/witnessed-choice/task.toml b/tasks/witnessed-choice/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..df1abcf19a29dcf68804ee21e04ac7a6d5a9239a --- /dev/null +++ b/tasks/witnessed-choice/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/witnessed-choice" +version = "1.0.0" +description = "Prove WitnessedChoice (openai/math family 243: Choiceless counting does not capture polynomial time) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "mathematical-logic"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WitnessedChoice.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WitnessedChoice" +family = "243" +family_title = "Choiceless counting does not capture polynomial time" +subject = "Mathematical logic" +theorems = ["OAI.WitnessedChoice.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.WitnessedChoice.Main" +reference_modules = 27 +reference_lean_bytes = 1118157 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 585 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12706 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/witnessed-choice/tests/Challenge.lean b/tasks/witnessed-choice/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..0f2828f516fb6d3e311b3742c6a013f01c69b45f --- /dev/null +++ b/tasks/witnessed-choice/tests/Challenge.lean @@ -0,0 +1,474 @@ +import Mathlib + +namespace OAI + +noncomputable section + +universe u v w + +namespace WitnessedSeparation + +namespace Hereditary + +abbrev HF (A : Type u) := Quotient (@Lists.instSetoidLists A) + +variable {A : Type u} {B : Type v} + +section + +local instance {A : Type u} : DecidableEq (HF A) := Classical.decEq _ + +def mk (l : Lists A) : HF A := Quotient.mk Lists.instSetoidLists l + +def atom (a : A) : HF A := mk (Lists.atom a) + +def isSet (x : HF A) : Bool := Quotient.liftOn x (fun l => l.1) + (by intro l r h; cases h <;> rfl) + +def rawElements (l : Lists A) : Finset (HF A) := by + classical + exact l.toList.toFinset.image mk + +def elements (x : HF A) : Finset (HF A) := Quotient.liftOn x rawElements (by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have raw_mem_congr_right {l r : Lists A} (h : Lists.Equiv l r) (a : Lists A) : + a ∈ l ↔ a ∈ r := by + cases h with + | refl => rfl + | antisymm hl hr => + exact ⟨Lists'.mem_of_subset hl, Lists'.mem_of_subset hr⟩ + intro l r h + ext z + induction z using Quotient.inductionOn with + | _ a => + change mk a ∈ rawElements l ↔ mk a ∈ rawElements r + rw [mem_rawElements, mem_rawElements] + exact raw_mem_congr_right h a) + +instance : Membership (HF A) (HF A) := ⟨fun y x => x ∈ elements y⟩ + +def ofFinset (s : Finset (HF A)) : HF A := + mk (Lists.ofList (s.toList.map Quotient.out)) + +def rawRank' : {b : Bool} → Lists' A b → ℕ + | _, .atom _ => 0 + | _, .nil => 0 + | _, .cons' a l => max (rawRank' a + 1) (rawRank' l) + +def rawRank (l : Lists A) : ℕ := rawRank' l.2 + +def rank (x : HF A) : ℕ := Quotient.liftOn x rawRank (by + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _ _ ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _ hmem _ iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + exact fun _ _ h => rawRank_congr h) + +def rawMap' (f : A → B) : {b : Bool} → Lists' A b → Lists' B b + | _, .atom a => .atom (f a) + | _, .nil => .nil + | _, .cons' a l => .cons' (rawMap' f a) (rawMap' f l) + +def rawMap (f : A → B) (l : Lists A) : Lists B := ⟨l.1, rawMap' f l.2⟩ + +def map (f : A → B) (x : HF A) : HF B := by + have toList_rawMap' (f : A → B) {b : Bool} (l : Lists' A b) : + (rawMap' f l).toList = l.toList.map (rawMap f) := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', Lists'.toList, ihl]; rfl + have rawMap_congr (f : A → B) {l r : Lists A} (h : Lists.Equiv l r) : + Lists.Equiv (rawMap f l) (rawMap f r) := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => Lists'.Subset (rawMap' f l) (rawMap' f r)) with + | refl => exact Lists.Equiv.refl _ + | antisymm hl hr ihl ihr => exact Lists.Equiv.antisymm ihl ihr + | nil => exact Lists'.Subset.nil + | @cons a a' l r _ hmem _ iheq ihsub => + apply Lists'.Subset.cons iheq _ ihsub + rw [toList_rawMap'] + exact List.mem_map.mpr ⟨a',hmem,rfl⟩ + exact Quotient.liftOn x (fun l => mk (rawMap f l)) (fun _ _ h => Quotient.eq.mpr (rawMap_congr f h)) + +instance {G : Type w} [Group G] [MulAction G A] : MulAction G (HF A) := by + have map_mk {A B : Type u} (f : A → B) (l : Lists A) : map f (mk l) = mk (rawMap f l) := rfl + have rawMap_id {A : Type u} : ∀ l : Lists A, rawMap id l = l := by + rintro ⟨b,l⟩ + have h : rawMap' id l = l := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', iha,ihl] + exact congrArg (Sigma.mk b) h + have map_id {A : Type u} (x : HF A) : map id x = x := by + induction x using Quotient.inductionOn with + | _ l => + change map id (mk l) = mk l + rw [map_mk, rawMap_id] + have rawMap_comp {A B : Type u} {C : Type u} (g : B → C) (f : A → B) (l : Lists A) : + rawMap g (rawMap f l) = rawMap (g ∘ f) l := by + rcases l with ⟨b,l⟩ + have h : rawMap' g (rawMap' f l) = rawMap' (g ∘ f) l := by + induction l with + | atom => rfl + | nil => rfl + | cons' a l iha ihl => simp only [rawMap', iha,ihl] + exact congrArg (Sigma.mk b) h + have map_comp {A B : Type u} {C : Type u} (g : B → C) (f : A → B) (x : HF A) : + map g (map f x) = map (g ∘ f) x := by + induction x using Quotient.inductionOn with + | _ l => + change map g (map f (mk l)) = map (g ∘ f) (mk l) + simp only [map_mk,rawMap_comp] + exact { + smul g x := map (fun a => g • a) x + one_smul x := by + change map (fun a : A => (1 : G) • a) x = x + have h : (fun a : A => (1 : G) • a) = id := by funext a; simp + rw [h,map_id] + mul_smul g h x := by + change map (fun a : A => (g*h) • a) x = map (fun a => g • a) (map (fun a => h • a) x) + rw [map_comp] + congr 1 + funext a + exact mul_smul g h a } + +end + +open Classical Finset + +def singleton (a : HF A) : HF A := ofFinset {a} + +def double (a b : HF A) : HF A := ofFinset {a,b} + +def pair (a b : HF A) : HF A := double (singleton a) (double a b) + +def ordinal : ℕ → HF A + | 0 => ofFinset ∅ + | i+1 => ofFinset (insert (ordinal i) (elements (ordinal i))) + +local instance {C : Type w} : DecidableEq (HF C) := Classical.decEq _ + +def closure (x : HF A) : Finset (HF A) := + insert x ((elements x).attach.biUnion (fun y => closure y.val)) +termination_by rank x +decreasing_by + have mem_rawElements (a l : Lists A) : mk a ∈ rawElements l ↔ a ∈ l := by + classical + rcases l with ⟨(_ | _), l⟩ + · cases l + change mk a ∈ (∅ : Finset (HF A)) ↔ False + simp + · change mk a ∈ (Lists'.toList l).toFinset.image mk ↔ a ∈ l + simp only [Finset.mem_image, List.mem_toFinset, Lists'.mem_def, mk, Quotient.eq] + constructor + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + · rintro ⟨a',ha',heq⟩ + exact ⟨a',ha',heq.symm⟩ + have rawRank_lt_of_mem {b : Bool} (l : Lists' A b) (a : Lists A) + (ha : a ∈ l.toList) : rawRank a < rawRank' l := by + induction l with + | atom => simp at ha + | nil => simp at ha + | cons' c l ihc ihl => + rcases List.mem_cons.mp ha with rfl | ha + · exact lt_of_lt_of_le (Nat.lt_succ_self _) (le_max_left _ _) + · exact lt_of_lt_of_le (ihl ha) (le_max_right _ _) + have rawRank_congr {l r : Lists A} (h : Lists.Equiv l r) : rawRank l = rawRank r := by + induction h using Lists.Equiv.rec + (motive_2 := fun l r _ => rawRank' l ≤ rawRank' r) with + | refl => rfl + | antisymm _ _ ihl ihr => exact Nat.le_antisymm ihl ihr + | nil => exact Nat.zero_le _ + | @cons a a' l r _ hmem _ iheq ihsub => + change max (rawRank a + 1) (rawRank' l) ≤ rawRank' r + refine max_le ?_ ihsub + rw [iheq] + exact rawRank_lt_of_mem r a' hmem + have rank_lt_of_mem {x y : HF A} (h : x ∈ y) : rank x < rank y := by + induction y using Quotient.inductionOn with + | _ l => + induction x using Quotient.inductionOn with + | _ a => + have h' := (mem_rawElements a l).mp h + rcases l with ⟨(_ | _), l⟩ + · exact False.elim h' + · obtain ⟨a',ha',heq⟩ := h' + change rawRank a < rawRank' l + rw [rawRank_congr heq] + exact rawRank_lt_of_mem l a' ha' + exact rank_lt_of_mem y.property + +end Hereditary + +abbrev Scalar := ZMod 3 + +inductive Symbol + | Ed | Cf | EB | VB | I | Z (δ : Scalar) + deriving DecidableEq, Fintype + +structure Input (A : Type) where + rel : Symbol → A → A → Bool + +end WitnessedSeparation + +namespace WitnessedChoice + +namespace BGS + +open Classical WitnessedSeparation WitnessedSeparation.Hereditary + +mutual + +inductive Term : ℕ → Type + | var {n} (i : Fin n) : Term n + | empty {n} : Term n + | atoms {n} : Term n + | pair {n} (a b : Term n) : Term n + | union {n} (a : Term n) : Term n + | unique {n} (a : Term n) : Term n + | card {n} (a : Term n) : Term n + | comprehend {n} (body : Term (n+1)) (range : Term n) + (guard : Formula (n+1)) : Term n + | iterate {n} (step : Term (n+1)) : Term n + inductive Formula : ℕ → Type + | equal {n} (a b : Term n) : Formula n + | input {n} (r : Symbol) (a b : Term n) : Formula n + | neg {n} (a : Formula n) : Formula n + | and {n} (a b : Formula n) : Formula n + | or {n} (a b : Formula n) : Formula n + | wsc {n} (step : Term (n+2)) (choice : Term (n+1)) + (witness : Term (n+2)) (output : Formula (n+1)) : Formula n + +end + +def dropFree {n} (f : Finset (Fin (n+1))) : Finset (Fin n) := + Finset.univ.filter (fun i => i.succ ∈ f) + +mutual + +def Term.free : {n : ℕ} → Term n → Finset (Fin n) + | _, .var i => {i} + | _, .empty | _, .atoms => ∅ + | _, .pair a b => a.free ∪ b.free + | _, .union a | _, .unique a | _, .card a => a.free + | _, .comprehend body range guard => range.free ∪ dropFree (body.free ∪ guard.free) + | _, .iterate step => dropFree step.free + def Formula.free : {n : ℕ} → Formula n → Finset (Fin n) + | _, .equal a b | _, .input _ a b => a.free ∪ b.free + | _, .neg a => a.free + | _, .and a b | _, .or a b => a.free ∪ b.free + | _, .wsc step choice witness output => + dropFree (dropFree (step.free ∪ witness.free)) ∪ dropFree (choice.free ∪ output.free) + +end + +mutual + +def Term.wscCount : {n : ℕ} → Term n → ℕ + | _, .var _ | _, .empty | _, .atoms => 0 + | _, .pair a b => a.wscCount + b.wscCount + | _, .union a | _, .unique a | _, .card a => a.wscCount + | _, .comprehend body range guard => body.wscCount + range.wscCount + guard.wscCount + | _, .iterate step => step.wscCount + def Formula.wscCount : {n : ℕ} → Formula n → ℕ + | _, .equal a b | _, .input _ a b => a.wscCount + b.wscCount + | _, .neg a => a.wscCount + | _, .and a b | _, .or a b => a.wscCount + b.wscCount + | _, .wsc step choice witness output => + 1 + step.wscCount + choice.wscCount + witness.wscCount + output.wscCount + +end + +variable {A : Type} + +abbrev Result (α : Type) := Option α + +def emptyHF : HF A := ofFinset ∅ + +def TC (x : HF A) : Finset (HF A) := (elements x).biUnion closure + +def unionHF (x : HF A) : HF A := ofFinset ((elements x).biUnion elements) + +def uniqueHF (x : HF A) : HF A := + if h : ∃ y, elements x = {y} then h.choose else emptyHF + +def cardHF (x : HF A) : HF A := ordinal (elements x).card + +def inputHF (S : Input A) (r : Symbol) (x y : HF A) : Bool := + decide (∃ a b, x = atom a ∧ y = atom b ∧ S.rel r a b = true) + +def lift₂ {X Y Z : Type} (f : X → Y → Z) (a : Result X) (b : Result Y) : Result Z := + a.bind (fun x => b.map (f x)) + +def collect (r : HF A) (guard : HF A → Result Bool) (body : HF A → Result (HF A)) : + Result (HF A) := + if (∀ x ∈ elements r, (guard x).isSome) ∧ + (∀ x ∈ elements r, guard x = some true → (body x).isSome) then + some (ofFinset (((elements r).filter (fun x => guard x = some true)).image + (fun x => (body x).getD emptyHF))) + else none + +def iterationLoop (p : ℕ) (step : HF A → Result (HF A)) : ℕ → HF A → Result (HF A) + | 0, _ => some emptyHF + | fuel+1, x => + if (TC x).card ≤ p then + (step x).bind (fun y => + if x = y then some x else iterationLoop p step fuel y) + else some emptyHF + +def ordinaryIteration (p : ℕ) (step : HF A → Result (HF A)) : Result (HF A) := + iterationLoop p step (p+1) emptyHF + +def resource (p : Polynomial ℝ) (n : ℕ) : ℕ := ⌊p.eval (n : ℝ)⌋₊ + +variable [Fintype A] + +def permutationGraph (g : Equiv.Perm A) : HF A := + ofFinset (Finset.univ.image (fun a => pair (atom a) (atom (g a)))) + +def Automorphism (S : Input A) (g : Equiv.Perm A) : Prop := + ∀ r a b, S.rel r (g a) (g b) = S.rel r a b + +def ChoicePrefix (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (b c : ℕ → HF A) (k : ℕ) : Prop := + b 0 = emptyHF ∧ ∀ i < k, + (∃ D, choice (b i) = some D ∧ c i ∈ elements D) ∧ + step (b i) (c i) = some (b (i+1)) + +def StrictPrefix (b : ℕ → HF A) (k : ℕ) : Prop := ∀ i < k, b i ≠ b (i+1) + +def FirstPath (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (b c : ℕ → HF A) (t : ℕ) : Prop := + ChoicePrefix step choice b c (t+1) ∧ StrictPrefix b t ∧ b t = b (t+1) + +def FixesParameters {n : ℕ} (free : Finset (Fin n)) (env : Fin n → HF A) + (g : Equiv.Perm A) : Prop := ∀ i ∈ free, g • env i = env i + +def WitnessesHistory {n : ℕ} (S : Input A) (free : Finset (Fin n)) + (env : Fin n → HF A) (b : ℕ → HF A) (i : ℕ) (D M : HF A) : Prop := + isSet M = true ∧ + (∀ w ∈ elements M, ∃ g : Equiv.Perm A, + w = permutationGraph g ∧ Automorphism S g ∧ FixesParameters free env g ∧ + ∀ j ≤ i, g • b j = b j) ∧ + (∀ u ∈ elements D, ∀ v ∈ elements D, ∃ g : Equiv.Perm A, + permutationGraph g ∈ elements M ∧ g • u = v) + +def GoodWSC {n : ℕ} (S : Input A) (p : ℕ) (free : Finset (Fin n)) + (env : Fin n → HF A) (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (witness : HF A → HF A → Result (HF A)) + (output : HF A → Result Bool) : Prop := + (∀ b c k, ChoicePrefix step choice b c k → StrictPrefix b k → + k ≤ p ∧ (TC (b k)).card ≤ p ∧ ∃ D, choice (b k) = some D ∧ + (elements D).Nonempty ∧ ∀ u ∈ elements D, (step (b k) u).isSome) ∧ + (∀ b c t, FirstPath step choice b c t → t+2 ≤ p ∧ + (∀ i ≤ t, ∃ D M, choice (b i) = some D ∧ witness (b t) (b i) = some M ∧ + WitnessesHistory S free env b i D M) ∧ (output (b t)).isSome) + +def witnessedIteration {n : ℕ} (S : Input A) (p : ℕ) (free : Finset (Fin n)) + (env : Fin n → HF A) (step : HF A → HF A → Result (HF A)) + (choice : HF A → Result (HF A)) (witness : HF A → HF A → Result (HF A)) + (output : HF A → Result Bool) : Result Bool := + if GoodWSC S p free env step choice witness output then + some (decide (∀ b c t, FirstPath step choice b c t → output (b t) = some true)) + else none + +mutual + +def Term.eval (S : Input A) (p : Polynomial ℝ) : {n : ℕ} → Term n → + (Fin n → HF A) → Result (HF A) + | _, .var i, env => some (env i) + | _, .empty, _ => some emptyHF + | _, .atoms, _ => some (ofFinset (Finset.univ.image atom)) + | _, .pair a b, env => lift₂ double (a.eval S p env) (b.eval S p env) + | _, .union a, env => (a.eval S p env).map unionHF + | _, .unique a, env => (a.eval S p env).map uniqueHF + | _, .card a, env => (a.eval S p env).map cardHF + | _, .comprehend body range guard, env => + (range.eval S p env).bind (fun r => collect r + (fun x => guard.eval S p (Fin.cons x env)) + (fun x => body.eval S p (Fin.cons x env))) + | _, .iterate step, env => ordinaryIteration (resource p (Fintype.card A)) + (fun x => step.eval S p (Fin.cons x env)) + def Formula.eval (S : Input A) (p : Polynomial ℝ) : {n : ℕ} → Formula n → + (Fin n → HF A) → Result Bool + | _, .equal a b, env => lift₂ (fun x y => decide (x = y)) (a.eval S p env) (b.eval S p env) + | _, .input r a b, env => lift₂ (inputHF S r) (a.eval S p env) (b.eval S p env) + | _, .neg a, env => (a.eval S p env).map Bool.not + | _, .and a b, env => lift₂ Bool.and (a.eval S p env) (b.eval S p env) + | _, .or a b, env => lift₂ Bool.or (a.eval S p env) (b.eval S p env) + | _, .wsc step choice witness output, env => + witnessedIteration S (resource p (Fintype.card A)) + (Formula.wsc step choice witness output).free env + (fun x y => step.eval S p (Fin.cons y (Fin.cons x env))) + (fun x => choice.eval S p (Fin.cons x env)) + (fun z x => witness.eval S p (Fin.cons x (Fin.cons z env))) + (fun x => output.eval S p (Fin.cons x env)) + +end + +structure FiniteInput where + Carrier : Type + finite : Fintype Carrier + input : Input Carrier + +attribute [instance] FiniteInput.finite + +structure Sentence where + formula : Formula 0 + polynomial : Polynomial ℝ + +def Sentence.eval (φ : Sentence) (S : FiniteInput) : Result Bool := + φ.formula.eval S.input φ.polynomial Fin.elim0 + +def Sentence.isCPT (φ : Sentence) : Prop := φ.formula.wscCount = 0 + +def Sentence.BooleanOnAllInputs (φ : Sentence) : Prop := + ∀ S, ∃ b : Bool, φ.eval S = some b + +def Sentence.TrueModels (φ : Sentence) : Set FiniteInput := {S | φ.eval S = some true} + +def MainStatement : Prop := ∃ φ : Sentence, + φ.formula.wscCount = 1 ∧ φ.BooleanOnAllInputs ∧ + ∀ ψ : Sentence, ψ.isCPT → φ.TrueModels ≠ ψ.TrueModels + +end BGS + +end WitnessedChoice + +theorem WitnessedChoice.main : WitnessedChoice.BGS.MainStatement := by + sorry + +end + +end OAI diff --git a/tasks/witnessed-choice/tests/grade.py b/tasks/witnessed-choice/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/witnessed-choice/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/witnessed-choice/tests/task.json b/tasks/witnessed-choice/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..cfab06210c602a7635357541162d74332d8b9666 --- /dev/null +++ b/tasks/witnessed-choice/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WitnessedChoice", + "comparator": { + "theorem_names": [ + "OAI.WitnessedChoice.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11806 +} \ No newline at end of file diff --git a/tasks/witnessed-choice/tests/test.sh b/tasks/witnessed-choice/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/witnessed-choice/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/wl-identification/environment/Dockerfile b/tasks/wl-identification/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/wl-identification/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/wl-identification/environment/fetch_mathlib.sh b/tasks/wl-identification/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/wl-identification/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/wl-identification/environment/lake-manifest.json b/tasks/wl-identification/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/wl-identification/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/wl-identification/environment/lakefile.lean b/tasks/wl-identification/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/wl-identification/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/wl-identification/environment/lean_setup.sh b/tasks/wl-identification/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/wl-identification/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/wl-identification/environment/pack_submission.py b/tasks/wl-identification/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/wl-identification/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/wl-identification/instruction.md b/tasks/wl-identification/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..4eda8d9ed131fed7d3d307ff71c94bf34bce4049 --- /dev/null +++ b/tasks/wl-identification/instruction.md @@ -0,0 +1,197 @@ +# openai/math challenge `WLIdentification` (family 133) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 133 of the release, *The complexity of Weisfeiler–Leman refinement* +(Theoretical computer science). The family as a whole: Proves unconditional $n^{\Omega(k)}$ deterministic time lower bounds for joint and separate $k$-dimensional Weisfeiler–Leman equivalence, for sufficiently large fixed $k$ in the specified sequential adjacency-matrix models. With dimension as input, joint equivalence is EXPTIME-complete even on subcubic graphs; deciding whether refinement identifies a graph is also EXPTIME-complete. + +The challenge is `WLIdentification`, also at `/opt/openai-math/challenges/WLIdentification.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace WLIdentification + +structure Graph where + order : ℕ + edge : Fin order → Fin order → Bool + symmetric : ∀ u v, edge u v = edge v u + loopless : ∀ u, edge u u = false + +def Isomorphic (G H : Graph) : Prop := + ∃ e : Fin G.order ≃ Fin H.order, ∀ u v, G.edge u v = H.edge (e u) (e v) + +/-- Colors retain their full history, and hence are shared between graphs. -/ +def NeighborColor : ℕ → Type + | 0 => Unit + | s + 1 => NeighborColor s × Multiset (NeighborColor s) + +def neighborColor (G : Graph) : (s : ℕ) → Fin G.order → NeighborColor s + | 0, _ => () + | s + 1, v => (neighborColor G s v, + (Finset.univ.filter (fun w => G.edge v w = true)).val.map (neighborColor G s)) + +def neighborHistogram (G : Graph) (s : ℕ) : Multiset (NeighborColor s) := + Finset.univ.val.map (neighborColor G s) + +def TupleColor (k : ℕ) : ℕ → Type + | 0 => (Fin k → Fin k → Bool) × (Fin k → Fin k → Bool) + | s + 1 => TupleColor k s × Multiset (Fin k → TupleColor k s) + +/-- Joint update: one multiset of whole replacement vectors, not independent marginals. -/ +def tupleColor (G : Graph) (k : ℕ) : (s : ℕ) → (Fin k → Fin G.order) → TupleColor k s + | 0, v => (fun i j => decide (v i = v j), fun i j => G.edge (v i) (v j)) + | s + 1, v => (tupleColor G k s v, + Finset.univ.val.map (fun z => fun i => tupleColor G k s (Function.update v i z))) + +def tupleHistogram (G : Graph) (k s : ℕ) : Multiset (TupleColor k s) := + Finset.univ.val.map (tupleColor G k s) + +def Equivalent (k : ℕ) (G H : Graph) : Prop := + if k = 1 then ∀ s, neighborHistogram G s = neighborHistogram H s + else ∀ s, tupleHistogram G k s = tupleHistogram H k s + +/-- There is no restriction to mates from a graph construction or to a selected order. -/ +def Identifies (k : ℕ) (G : Graph) : Prop := + ∀ H : Graph, Equivalent k G H → Isomorphic G H + +/-- The infimum of the positive identifying dimensions; this set is nonempty for finite G. -/ +noncomputable def WLdim (G : Graph) : ℕ := + sInf {k : ℕ | 0 < k ∧ Identifies k G} + +abbrev Word := List Bool +abbrev BinaryLanguage := Set Word + +def binaryValue (bits : Word) : ℕ := + bits.foldl (fun z b => 2 * z + if b then 1 else 0) 0 + +def matrixWord (G : Graph) : Word := + (List.ofFn (fun i : Fin G.order => List.ofFn (G.edge i))).flatten + +/-- Unary order header, row-major binary matrix, then most-significant-first binary k. -/ +def inputWord (G : Graph) (bits : Word) : Word := + List.replicate G.order true ++ [false] ++ matrixWord G ++ bits + +/-- A malformed word is rejected: membership requires a valid nonempty simple matrix and k>0. -/ +def dimensionLanguage : BinaryLanguage := + {w | ∃ (G : Graph) (bits : Word), + 0 < G.order ∧ (∃ tail, bits = true :: tail) ∧ 0 < binaryValue bits ∧ + w = inputWord G bits ∧ WLdim G ≤ binaryValue bits} + +/- The deterministic local machine model is explicit; no oracle or arbitrary + state-transition on whole inputs is included. Both alphabets are fixed finite + types for each machine. Extra symbols and states allow arbitrary finite tables. -/ +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.displacement : Move → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Machine where + extraSymbols : ℕ + extraStates : ℕ + transition : Fin (extraStates + 3) → Fin (extraSymbols + 3) → + Fin (extraStates + 3) × Fin (extraSymbols + 3) × Move + +structure Configuration (M : Machine) where + state : Fin (M.extraStates + 3) + head : ℤ + tape : ℤ → Fin (M.extraSymbols + 3) + +def inputSymbol (M : Machine) (b : Bool) : Fin (M.extraSymbols + 3) := + if b then 2 else 1 + +def initial (M : Machine) (w : Word) : Configuration M where + state := 0 + head := 0 + tape z := if 0 ≤ z then (w[z.toNat]?).elim 0 (inputSymbol M) else 0 + +def Halted {M : Machine} (c : Configuration M) : Prop := + c.state = 1 ∨ c.state = 2 + +/-- One read/write/head-movement transition. A halted configuration is frozen. -/ +def step (M : Machine) (c : Configuration M) : Configuration M := + if c.state = 1 ∨ c.state = 2 then c else + let t := M.transition c.state (c.tape c.head) + { state := t.1, head := c.head + t.2.2.displacement, + tape := Function.update c.tape c.head t.2.1 } + +def run (M : Machine) (w : Word) (t : ℕ) : Configuration M := + (step M)^[t] (initial M w) + +/-- Output is the binary word beginning at origin and ending at its first blank. -/ +def Output {M : Machine} (c : Configuration M) (w : Word) : Prop := + (∀ i : Fin w.length, c.tape (i.val : ℤ) = inputSymbol M w[i]) ∧ + c.tape (w.length : ℤ) = 0 + +/-- Uniform genuine executions on every bit word, including malformed graph words. -/ +def DecidesWithin (M : Machine) (L : BinaryLanguage) (bound : ℕ → ℕ) : Prop := + ∀ w, ∃ t ≤ bound w.length, Halted (run M w t) ∧ ((run M w t).state = 1 ↔ w ∈ L) + +def InEXPTIME (L : BinaryLanguage) : Prop := + ∃ (M : Machine) (C d : ℕ), + DecidesWithin M L (fun n => 2 ^ (C * (n + 1) ^ d)) + +def ComputesWithin (M : Machine) (f : Word → Word) (bound : ℕ → ℕ) : Prop := + ∀ w, ∃ t ≤ bound w.length, (run M w t).state = 1 ∧ Output (run M w t) (f w) + +def PolytimeManyOne (L S : BinaryLanguage) : Prop := + ∃ (f : Word → Word) (M : Machine) (C d : ℕ), + ComputesWithin M f (fun n => C * (n + 1) ^ d) ∧ ∀ w, w ∈ L ↔ f w ∈ S + +def EXPTIMEComplete (S : BinaryLanguage) : Prop := + InEXPTIME S ∧ ∀ L : BinaryLanguage, InEXPTIME L → PolytimeManyOne L S + +theorem main : EXPTIMEComplete dimensionLanguage := + by + sorry + +end WLIdentification + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/WLIdentification.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.WLIdentification.main` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/wl-identification/solution/closure.txt b/tasks/wl-identification/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..d09187a1207593b4aeccaea8f68d1db2c9e0a8f0 --- /dev/null +++ b/tasks/wl-identification/solution/closure.txt @@ -0,0 +1,67 @@ +OAI.Computability.WLIdentification.AcceptingBroadcast +OAI.Computability.WLIdentification.AcceptingMates +OAI.Computability.WLIdentification.AddressArithmetic +OAI.Computability.WLIdentification.AffineIncidence +OAI.Computability.WLIdentification.AffinePresentation +OAI.Computability.WLIdentification.AffineTranslations +OAI.Computability.WLIdentification.BijectionGames +OAI.Computability.WLIdentification.BinaryAddresses +OAI.Computability.WLIdentification.BoundedWords +OAI.Computability.WLIdentification.BufferedCircuits +OAI.Computability.WLIdentification.CarryPresentation +OAI.Computability.WLIdentification.CellularCircuits +OAI.Computability.WLIdentification.CellularPresentation +OAI.Computability.WLIdentification.CircuitCodes +OAI.Computability.WLIdentification.CircuitForms +OAI.Computability.WLIdentification.CircuitPresentation +OAI.Computability.WLIdentification.CircuitReduction +OAI.Computability.WLIdentification.ConstraintSchemas +OAI.Computability.WLIdentification.CycleSums +OAI.Computability.WLIdentification.DimensionDecider +OAI.Computability.WLIdentification.ExponentialComputation +OAI.Computability.WLIdentification.ExpressionBounds +OAI.Computability.WLIdentification.ExpressionCompiler +OAI.Computability.WLIdentification.FiniteEncoding +OAI.Computability.WLIdentification.FinitePresentation +OAI.Computability.WLIdentification.FiniteRefinement +OAI.Computability.WLIdentification.GlobalSolvability +OAI.Computability.WLIdentification.GraphEnumeration +OAI.Computability.WLIdentification.Hardness +OAI.Computability.WLIdentification.LeafPresentation +OAI.Computability.WLIdentification.LinearExtensions +OAI.Computability.WLIdentification.LocalImages +OAI.Computability.WLIdentification.LocalPresentation +OAI.Computability.WLIdentification.MachineCells +OAI.Computability.WLIdentification.MachinePresentation +OAI.Computability.WLIdentification.MachineReduction +OAI.Computability.WLIdentification.Main +OAI.Computability.WLIdentification.MateReconstruction +OAI.Computability.WLIdentification.Model +OAI.Computability.WLIdentification.NumericKernel +OAI.Computability.WLIdentification.NumericRefinement +OAI.Computability.WLIdentification.PolynomialArithmetic +OAI.Computability.WLIdentification.PolynomialWords +OAI.Computability.WLIdentification.PresentationArithmetic +OAI.Computability.WLIdentification.PrivateLeaves +OAI.Computability.WLIdentification.ProductPresentation +OAI.Computability.WLIdentification.Refinement +OAI.Computability.WLIdentification.RefinementCorrectness +OAI.Computability.WLIdentification.RejectingMates +OAI.Computability.WLIdentification.RingCodes +OAI.Computability.WLIdentification.RingLegality +OAI.Computability.WLIdentification.RingMembership +OAI.Computability.WLIdentification.RingPresentation +OAI.Computability.WLIdentification.RowOffsets +OAI.Computability.WLIdentification.ScalarExtension +OAI.Computability.WLIdentification.SchemaPresentation +OAI.Computability.WLIdentification.SeedBits +OAI.Computability.WLIdentification.SeedLetter +OAI.Computability.WLIdentification.StableColors +OAI.Computability.WLIdentification.StackCommands +OAI.Computability.WLIdentification.StackMachines +OAI.Computability.WLIdentification.TapeCompiler +OAI.Computability.WLIdentification.TypedArithmetic +OAI.Computability.WLIdentification.TypedCases +OAI.Computability.WLIdentification.WordArithmetic +OAI.Computability.WLIdentification.WordCommands +OAI.Computability.WLIdentification.WordExpressions diff --git a/tasks/wl-identification/solution/reference.py b/tasks/wl-identification/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/wl-identification/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/wl-identification/solution/solve.sh b/tasks/wl-identification/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..d77d75056947a26f4f5fdf9df31b855db4050b24 --- /dev/null +++ b/tasks/wl-identification/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of WLIdentification, i.e. module OAI.Computability.WLIdentification.Main and the +# 67 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Computability.WLIdentification.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of WLIdentification" diff --git a/tasks/wl-identification/task.toml b/tasks/wl-identification/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..7700c754af34483b5e9b7ac90b7a6a409f6e1fb6 --- /dev/null +++ b/tasks/wl-identification/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/wl-identification" +version = "1.0.0" +description = "Prove WLIdentification (openai/math family 133: The complexity of Weisfeiler–Leman refinement) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "theoretical-computer-science"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/WLIdentification.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "WLIdentification" +family = "133" +family_title = "The complexity of Weisfeiler–Leman refinement" +subject = "Theoretical computer science" +theorems = ["OAI.WLIdentification.main"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Computability.WLIdentification.Main" +reference_modules = 67 +reference_lean_bytes = 765224 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 529 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 12388 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/wl-identification/tests/Challenge.lean b/tasks/wl-identification/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..9e922ae71265a0cc363f3d24be42cc26fa8cd0aa --- /dev/null +++ b/tasks/wl-identification/tests/Challenge.lean @@ -0,0 +1,146 @@ +import Mathlib + +namespace OAI + +namespace WLIdentification + +structure Graph where + order : ℕ + edge : Fin order → Fin order → Bool + symmetric : ∀ u v, edge u v = edge v u + loopless : ∀ u, edge u u = false + +def Isomorphic (G H : Graph) : Prop := + ∃ e : Fin G.order ≃ Fin H.order, ∀ u v, G.edge u v = H.edge (e u) (e v) + +/-- Colors retain their full history, and hence are shared between graphs. -/ +def NeighborColor : ℕ → Type + | 0 => Unit + | s + 1 => NeighborColor s × Multiset (NeighborColor s) + +def neighborColor (G : Graph) : (s : ℕ) → Fin G.order → NeighborColor s + | 0, _ => () + | s + 1, v => (neighborColor G s v, + (Finset.univ.filter (fun w => G.edge v w = true)).val.map (neighborColor G s)) + +def neighborHistogram (G : Graph) (s : ℕ) : Multiset (NeighborColor s) := + Finset.univ.val.map (neighborColor G s) + +def TupleColor (k : ℕ) : ℕ → Type + | 0 => (Fin k → Fin k → Bool) × (Fin k → Fin k → Bool) + | s + 1 => TupleColor k s × Multiset (Fin k → TupleColor k s) + +/-- Joint update: one multiset of whole replacement vectors, not independent marginals. -/ +def tupleColor (G : Graph) (k : ℕ) : (s : ℕ) → (Fin k → Fin G.order) → TupleColor k s + | 0, v => (fun i j => decide (v i = v j), fun i j => G.edge (v i) (v j)) + | s + 1, v => (tupleColor G k s v, + Finset.univ.val.map (fun z => fun i => tupleColor G k s (Function.update v i z))) + +def tupleHistogram (G : Graph) (k s : ℕ) : Multiset (TupleColor k s) := + Finset.univ.val.map (tupleColor G k s) + +def Equivalent (k : ℕ) (G H : Graph) : Prop := + if k = 1 then ∀ s, neighborHistogram G s = neighborHistogram H s + else ∀ s, tupleHistogram G k s = tupleHistogram H k s + +/-- There is no restriction to mates from a graph construction or to a selected order. -/ +def Identifies (k : ℕ) (G : Graph) : Prop := + ∀ H : Graph, Equivalent k G H → Isomorphic G H + +/-- The infimum of the positive identifying dimensions; this set is nonempty for finite G. -/ +noncomputable def WLdim (G : Graph) : ℕ := + sInf {k : ℕ | 0 < k ∧ Identifies k G} + +abbrev Word := List Bool +abbrev BinaryLanguage := Set Word + +def binaryValue (bits : Word) : ℕ := + bits.foldl (fun z b => 2 * z + if b then 1 else 0) 0 + +def matrixWord (G : Graph) : Word := + (List.ofFn (fun i : Fin G.order => List.ofFn (G.edge i))).flatten + +/-- Unary order header, row-major binary matrix, then most-significant-first binary k. -/ +def inputWord (G : Graph) (bits : Word) : Word := + List.replicate G.order true ++ [false] ++ matrixWord G ++ bits + +/-- A malformed word is rejected: membership requires a valid nonempty simple matrix and k>0. -/ +def dimensionLanguage : BinaryLanguage := + {w | ∃ (G : Graph) (bits : Word), + 0 < G.order ∧ (∃ tail, bits = true :: tail) ∧ 0 < binaryValue bits ∧ + w = inputWord G bits ∧ WLdim G ≤ binaryValue bits} + +/- The deterministic local machine model is explicit; no oracle or arbitrary + state-transition on whole inputs is included. Both alphabets are fixed finite + types for each machine. Extra symbols and states allow arbitrary finite tables. -/ +inductive Move where + | left | stay | right + deriving DecidableEq + +def Move.displacement : Move → ℤ + | .left => -1 + | .stay => 0 + | .right => 1 + +structure Machine where + extraSymbols : ℕ + extraStates : ℕ + transition : Fin (extraStates + 3) → Fin (extraSymbols + 3) → + Fin (extraStates + 3) × Fin (extraSymbols + 3) × Move + +structure Configuration (M : Machine) where + state : Fin (M.extraStates + 3) + head : ℤ + tape : ℤ → Fin (M.extraSymbols + 3) + +def inputSymbol (M : Machine) (b : Bool) : Fin (M.extraSymbols + 3) := + if b then 2 else 1 + +def initial (M : Machine) (w : Word) : Configuration M where + state := 0 + head := 0 + tape z := if 0 ≤ z then (w[z.toNat]?).elim 0 (inputSymbol M) else 0 + +def Halted {M : Machine} (c : Configuration M) : Prop := + c.state = 1 ∨ c.state = 2 + +/-- One read/write/head-movement transition. A halted configuration is frozen. -/ +def step (M : Machine) (c : Configuration M) : Configuration M := + if c.state = 1 ∨ c.state = 2 then c else + let t := M.transition c.state (c.tape c.head) + { state := t.1, head := c.head + t.2.2.displacement, + tape := Function.update c.tape c.head t.2.1 } + +def run (M : Machine) (w : Word) (t : ℕ) : Configuration M := + (step M)^[t] (initial M w) + +/-- Output is the binary word beginning at origin and ending at its first blank. -/ +def Output {M : Machine} (c : Configuration M) (w : Word) : Prop := + (∀ i : Fin w.length, c.tape (i.val : ℤ) = inputSymbol M w[i]) ∧ + c.tape (w.length : ℤ) = 0 + +/-- Uniform genuine executions on every bit word, including malformed graph words. -/ +def DecidesWithin (M : Machine) (L : BinaryLanguage) (bound : ℕ → ℕ) : Prop := + ∀ w, ∃ t ≤ bound w.length, Halted (run M w t) ∧ ((run M w t).state = 1 ↔ w ∈ L) + +def InEXPTIME (L : BinaryLanguage) : Prop := + ∃ (M : Machine) (C d : ℕ), + DecidesWithin M L (fun n => 2 ^ (C * (n + 1) ^ d)) + +def ComputesWithin (M : Machine) (f : Word → Word) (bound : ℕ → ℕ) : Prop := + ∀ w, ∃ t ≤ bound w.length, (run M w t).state = 1 ∧ Output (run M w t) (f w) + +def PolytimeManyOne (L S : BinaryLanguage) : Prop := + ∃ (f : Word → Word) (M : Machine) (C d : ℕ), + ComputesWithin M f (fun n => C * (n + 1) ^ d) ∧ ∀ w, w ∈ L ↔ f w ∈ S + +def EXPTIMEComplete (S : BinaryLanguage) : Prop := + InEXPTIME S ∧ ∀ L : BinaryLanguage, InEXPTIME L → PolytimeManyOne L S + +theorem main : EXPTIMEComplete dimensionLanguage := + by + sorry + +end WLIdentification + +end OAI diff --git a/tasks/wl-identification/tests/grade.py b/tasks/wl-identification/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/wl-identification/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/wl-identification/tests/task.json b/tasks/wl-identification/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..1fe528472fae09ce184d8e76fa64668c99b3b56f --- /dev/null +++ b/tasks/wl-identification/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "WLIdentification", + "comparator": { + "theorem_names": [ + "OAI.WLIdentification.main" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 11488 +} \ No newline at end of file diff --git a/tasks/wl-identification/tests/test.sh b/tasks/wl-identification/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/wl-identification/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py diff --git a/tasks/yau-counterexample/environment/Dockerfile b/tasks/yau-counterexample/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..aa57529d28879aaf8f823eaf61743b87a7bb8310 --- /dev/null +++ b/tasks/yau-counterexample/environment/Dockerfile @@ -0,0 +1,8 @@ +# Shared by every openai/math task (agent and separate verifier). See lean_setup.sh. +FROM ubuntu:24.04 +ENV ELAN_HOME=/opt/elan \ + PATH=/opt/elan/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin \ + LANG=C.UTF-8 +COPY lean_setup.sh fetch_mathlib.sh lakefile.lean lake-manifest.json pack_submission.py /opt/build/ +RUN bash /opt/build/lean_setup.sh +WORKDIR /workspace diff --git a/tasks/yau-counterexample/environment/fetch_mathlib.sh b/tasks/yau-counterexample/environment/fetch_mathlib.sh new file mode 100644 index 0000000000000000000000000000000000000000..1cc7232e51d27e7b0d9e0b136da9632d889f9c55 --- /dev/null +++ b/tasks/yau-counterexample/environment/fetch_mathlib.sh @@ -0,0 +1,19 @@ +#!/usr/bin/env bash +# Unpack Mathlib's prebuilt cache in batches and truncate the files that importing Mathlib never +# reads (generated C and .ilean editor indexes), keeping their .hash files so Lake still sees every +# module as built. Lean + full Mathlib otherwise needs ~11 GB, more than a 10 GB sandbox disk. +set -euo pipefail +cd /opt/lean-env +trim() { + find .lake/packages -path '*/.lake/build/*' \( -name '*.c' -o -name '*.ilean' \) -size +0 -exec truncate -s 0 {} + + rm -rf "${HOME:-/root}/.cache/mathlib" +} +for dir in .lake/packages/mathlib/Mathlib/*/; do + name=$(basename "$dir") + echo "== Mathlib/$name" + lake exe cache get ".lake/packages/mathlib/Mathlib/$name" >/dev/null + trim + df -h / | tail -1 +done +lake exe cache get +trim diff --git a/tasks/yau-counterexample/environment/lake-manifest.json b/tasks/yau-counterexample/environment/lake-manifest.json new file mode 100644 index 0000000000000000000000000000000000000000..99b5eaa62153fd75dd2a9b1abdfac3738e914c88 --- /dev/null +++ b/tasks/yau-counterexample/environment/lake-manifest.json @@ -0,0 +1,116 @@ +{ + "version": "1.2.0", + "packagesDir": ".lake/packages", + "packages": [ + { + "url": "https://github.com/leanprover-community/mathlib4.git", + "type": "git", + "subDir": null, + "scope": "", + "rev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "name": "mathlib", + "manifestFile": "lake-manifest.json", + "inputRev": "d13f23b723b8a846827a245b89c10fc7d3f11612", + "inherited": false, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/plausible", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "118aa17ee84656b8bd727fef7c458ee8c833385c", + "name": "plausible", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/LeanSearchClient", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "ddf04cf3949fa556442341e87d47f9f6e6074707", + "name": "LeanSearchClient", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/import-graph", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "e928b72544873815af278d38681b31c0293588e3", + "name": "importGraph", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/ProofWidgets4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "106ff4fafc74ef4ac99d81dbf3ab399118f497a5", + "name": "proofwidgets", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.lean" + }, + { + "url": "https://github.com/leanprover-community/aesop", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "355695d523e41d0554926416cba2a2b3544fbbc9", + "name": "aesop", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/quote4", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "6a489d9af5d0c47e5b259e2e8bcdfc1811b5a259", + "name": "Qq", + "manifestFile": "lake-manifest.json", + "inputRev": "master", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover-community/batteries", + "type": "git", + "subDir": null, + "scope": "leanprover-community", + "rev": "f2effa3d803fda822b1f97b806c47cf2adfbcbc2", + "name": "batteries", + "manifestFile": "lake-manifest.json", + "inputRev": "main", + "inherited": true, + "configFile": "lakefile.toml" + }, + { + "url": "https://github.com/leanprover/lean4-cli", + "type": "git", + "subDir": null, + "scope": "leanprover", + "rev": "e92c9f15fdfacc8536f31cfb3b7ad26c3c8cd204", + "name": "Cli", + "manifestFile": "lake-manifest.json", + "inputRev": "v4.34.0", + "inherited": true, + "configFile": "lakefile.toml" + } + ], + "name": "openai_math", + "lakeDir": ".lake" +} \ No newline at end of file diff --git a/tasks/yau-counterexample/environment/lakefile.lean b/tasks/yau-counterexample/environment/lakefile.lean new file mode 100644 index 0000000000000000000000000000000000000000..0330e313d8613d18833b17d46138a44a23269a68 --- /dev/null +++ b/tasks/yau-counterexample/environment/lakefile.lean @@ -0,0 +1,12 @@ +import Lake +open Lake DSL + +-- Mathlib at the commit openai/math pins. Agents write `Submission.lean` and `Submission/**.lean`. +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission diff --git a/tasks/yau-counterexample/environment/lean_setup.sh b/tasks/yau-counterexample/environment/lean_setup.sh new file mode 100644 index 0000000000000000000000000000000000000000..5a6a070b2935a67d97d15a2b4bde73baea197533 --- /dev/null +++ b/tasks/yau-counterexample/environment/lean_setup.sh @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Builds the image shared by every openai/math task, for both the agent and the separate verifier: +# - Lean v4.34.1 and Mathlib d13f23b, the versions openai/math pins (Mathlib only, no OAI library) +# - Comparator, lean4export and landrun, used only by the verifier's grade.py +# - every challenge statement, at /opt/openai-math/challenges/.lean +# - /workspace, a Lake project where the agent writes Submission.lean +# All revisions are pinned. The openai/math library (the reference proofs) is never installed. +set -euxo pipefail +export DEBIAN_FRONTEND=noninteractive + +LEAN_TOOLCHAIN=leanprover/lean4:v4.34.1 +OPENAI_MATH_REV=adc7f1241b42e322a6451854ab7e4b4c146bf78a +COMPARATOR_REV=d03acab154d269c06e60e4de7e4cc85deebff94b # "bump toolchain to v4.34.0"; built with v4.34.1 +LANDRUN_REV=811cfff51ceaf3d9843708aa6d22e9b84ccac8b4 +GO_VERSION=1.24.7 + +apt-get update -qq +apt-get install -y -qq --no-install-recommends git curl ca-certificates build-essential xz-utils \ + zstd python3 procps iproute2 iptables tmux >/dev/null +rm -rf /var/lib/apt/lists/* +git config --system --add safe.directory '*' + +export ELAN_HOME=/opt/elan PATH=/opt/elan/bin:$PATH +curl -sSfL https://raw.githubusercontent.com/leanprover/elan/master/elan-init.sh \ + | sh -s -- -y --default-toolchain "$LEAN_TOOLCHAIN" --no-modify-path + +# --- Verifier tools, built before Mathlib so the build trees are gone before the big download --- +curl -sSfL "https://go.dev/dl/go${GO_VERSION}.linux-amd64.tar.gz" | tar -C /tmp -xz +GOBIN=/usr/local/bin GOPATH=/tmp/gopath GOCACHE=/tmp/gocache \ + /tmp/go/bin/go install "github.com/zouuup/landrun/cmd/landrun@${LANDRUN_REV}" +rm -rf /tmp/go /tmp/gopath /tmp/gocache + +git clone -q https://github.com/leanprover/comparator.git /tmp/comparator +( + cd /tmp/comparator + git checkout -q "$COMPARATOR_REV" + # Comparator passes only PATH/HOME/LEAN_ABORT_ON_PANIC into its landrun sandbox. Also pass + # LEAN_NUM_THREADS: Lean sees every host CPU (64) rather than the sandbox's 4, so without it Lake + # starts one Mathlib-loaded `lean` per module and an 8 GB sandbox runs out of memory. It bounds + # parallelism only and does not affect what is checked. + sed -i 's/envPass := #\["PATH", "HOME", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/; s/envPass := #\["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC"\]/envPass := #["PATH", "HOME", "LEAN_PATH", "LEAN_ABORT_ON_PANIC", "LEAN_NUM_THREADS"]/' Main.lean + test "$(grep -c '"LEAN_NUM_THREADS"' Main.lean)" -eq 2 + echo "$LEAN_TOOLCHAIN" > lean-toolchain + lake build lean4export comparator + install -m 0755 .lake/build/bin/comparator /usr/local/bin/comparator + install -m 0755 .lake/packages/lean4export/.lake/build/bin/lean4export /usr/local/bin/lean4export +) +rm -rf /tmp/comparator + +# --- Lean project with Mathlib --- +# Packages are shallow clones at the manifest revisions, so Lake sees the right HEAD and never fetches. +mkdir -p /opt/lean-env/.lake/packages +cd /opt/lean-env +echo "$LEAN_TOOLCHAIN" > lean-toolchain +cp /opt/build/lakefile.lean /opt/build/lake-manifest.json . +python3 - <<'PY' +import json, subprocess +for p in json.load(open("lake-manifest.json"))["packages"]: + d = f".lake/packages/{p['name']}" + subprocess.run(["git", "init", "-q", d], check=True) + subprocess.run(["git", "-C", d, "remote", "add", "origin", p["url"]], check=True) + subprocess.run(["git", "-C", d, "fetch", "-q", "--depth", "1", "origin", p["rev"]], check=True) + subprocess.run(["git", "-C", d, "checkout", "-q", "FETCH_HEAD"], check=True) +PY +# Linking native executables (Comparator above, Mathlib's cache tool here) is the only use of the +# static libraries, LLVM and gcc; `lean` and `lake build` of a library need none of them. Dropping +# them before the Mathlib download keeps the build, and the image, under Daytona's 10 GB disk. +lake exe cache --help >/dev/null 2>&1 || true +find /opt/elan/toolchains/*/lib -name '*.a' -delete +rm -f /opt/elan/toolchains/*/lib/libLLVM* /opt/elan/toolchains/*/lib/libclang-cpp* +apt-get purge -y -qq $(dpkg-query -W -f '${binary:Package}\n' build-essential 'gcc-13*' 'g++-13*' \ + 'cpp-13*' 'libstdc++-13-dev*' 'libgcc-13-dev*' 2>/dev/null) >/dev/null || true +apt-get autoremove -y -qq >/dev/null || true +bash /opt/build/fetch_mathlib.sh +rm -f /opt/lean-env/.lake/packages/mathlib/.lake/build/bin/cache + +# --- Challenge statements (public; the reference proofs are not fetched) --- +git init -q /tmp/oai && cd /tmp/oai +git remote add origin https://github.com/openai/math.git +git config core.sparseCheckout true +echo "lean/ComparatorChallenges/" > .git/info/sparse-checkout +git fetch -q --depth 1 --filter=blob:none origin "$OPENAI_MATH_REV" +git checkout -q FETCH_HEAD +mkdir -p /opt/openai-math/challenges +cp lean/ComparatorChallenges/*.lean /opt/openai-math/challenges/ +cd / && rm -rf /tmp/oai +install -m 0755 /opt/build/pack_submission.py /opt/openai-math/pack_submission.py + +# --- Agent workspace and the verifier's unprivileged user --- +mkdir -p /workspace/.lake +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain /workspace/ +ln -s /opt/lean-env/.lake/packages /workspace/.lake/packages +useradd --uid 2000 --create-home --shell /usr/sbin/nologin grader +mkdir -p /var/lib/oai-grade && chmod 0711 /var/lib/oai-grade + +# Smoke test. The first build may rebuild a few dependency modules the cache lacks (they persist in +# the image); a second build must compile nothing but Submission, or agents would pay for it. +cd /workspace +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > Submission.lean +lake build Submission 2>&1 | grep -E 'Built|error' | grep -v 'Built Submission' | head -20 || true +echo '-- second build' >> Submission.lean +lake build Submission 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission'; then + echo "the prebuilt Mathlib is incomplete: a second build still compiled dependencies" >&2; exit 1 +fi +rm -rf Submission.lean .lake/build /tmp/smoke.log + +# Mathlib's cache tool unpacks files as 0600. The verifier builds as the unprivileged `grader` user, +# so everything must be world-readable (and stays root-owned, so not writable). +chmod -R a+rX /opt/elan /opt/lean-env /opt/openai-math +# Same smoke test as `grader`, in a scratch project like the one grade.py lays out. +smoke=$(mktemp -d /var/lib/oai-grade/smoke.XXXX) +cp /opt/lean-env/lakefile.lean /opt/lean-env/lake-manifest.json /opt/lean-env/lean-toolchain "$smoke/" +mkdir "$smoke/.lake" && ln -s /opt/lean-env/.lake/packages "$smoke/.lake/packages" +printf 'import Mathlib\n\nexample : (2 : ℕ) + 2 = 4 := by norm_num\n' > "$smoke/Submission.lean" +chmod 0755 "$smoke" && chown grader "$smoke/.lake" +(cd "$smoke" && runuser -u grader -- env -i PATH="$(echo /opt/elan/toolchains/*/bin):/usr/bin:/bin" HOME="$smoke" \ + lake build Submission) 2>&1 | tee /tmp/smoke.log +if grep 'Built' /tmp/smoke.log | grep -qv 'Built Submission' || ! grep -q 'Build completed successfully' /tmp/smoke.log; then + echo "the grader user cannot build against the prebuilt Mathlib" >&2; exit 1 +fi +rm -rf "$smoke" /tmp/smoke.log + +rm -rf /opt/build /root/.cache +df -h / | tail -1 +du -sh /opt/elan /opt/lean-env diff --git a/tasks/yau-counterexample/environment/pack_submission.py b/tasks/yau-counterexample/environment/pack_submission.py new file mode 100644 index 0000000000000000000000000000000000000000..689dff39666b1453a328498760d185e309d9b99e --- /dev/null +++ b/tasks/yau-counterexample/environment/pack_submission.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +"""Pack the agent's proof into one file for the verifier. + +Harbor runs this as a [[verifier.collect]] hook in the agent's sandbox after the agent finishes. +It clears /logs/artifacts and writes /logs/artifacts/submission.tar holding only regular +`Submission.lean` and `Submission/**.lean` files. Symlinks and other entries are skipped, never +followed, so only one plain file crosses to the verifier sandbox. + +The agent's sandbox is untrusted, so the verifier re-checks every entry of the archive. This step +only keeps the transfer small and free of links. +""" + +from __future__ import annotations + +import os +import shutil +import stat +import tarfile +from pathlib import Path + +WORKSPACE = Path("/workspace") +OUT_DIR = Path("/logs/artifacts") +MAX_TOTAL_BYTES = 768 << 20 + + +def clear(directory: Path) -> None: + directory.mkdir(parents=True, exist_ok=True) + for entry in directory.iterdir(): + if entry.is_dir() and not entry.is_symlink(): + shutil.rmtree(entry) + else: + entry.unlink() + + +def regular(path: Path) -> bool: + try: + return stat.S_ISREG(path.lstat().st_mode) + except OSError: + return False + + +def main() -> None: + clear(OUT_DIR) + tmp = OUT_DIR / "submission.tar.part" + total = 0 + with tarfile.open(tmp, "w", format=tarfile.PAX_FORMAT) as tar: + root = WORKSPACE / "Submission.lean" + if regular(root): + total += root.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(root, arcname="Submission.lean", recursive=False) + tree = WORKSPACE / "Submission" + if tree.is_dir() and not tree.is_symlink(): + for dirpath, dirnames, filenames in os.walk(tree, followlinks=False): + dirnames[:] = [d for d in dirnames if not (Path(dirpath) / d).is_symlink()] + for name in sorted(filenames): + path = Path(dirpath) / name + if not name.endswith(".lean") or not regular(path): + continue + total += path.lstat().st_size + if total > MAX_TOTAL_BYTES: + raise SystemExit("submission exceeds the size limit") + tar.add(path, arcname=str(path.relative_to(WORKSPACE)), recursive=False) + tmp.rename(OUT_DIR / "submission.tar") + print(f"packed {total} bytes") + + +if __name__ == "__main__": + main() diff --git a/tasks/yau-counterexample/instruction.md b/tasks/yau-counterexample/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..a90ca93eadc5a9781e689b040b8c1996cd9940dc --- /dev/null +++ b/tasks/yau-counterexample/instruction.md @@ -0,0 +1,123 @@ +# openai/math challenge `YauCounterexample` (family 350) + +Prove the following result from OpenAI's [openai/math](https://github.com/openai/math) release in +Lean 4, with a proof the Lean kernel accepts. + +Context: this statement belongs to family 350 of the release, *Yau's nodal conjecture: surfaces and counterexamples* +(Differential geometry). The family as a whole: Proves the sharp $C\sqrt\lambda$ upper bound for nodal length on every fixed smooth closed surface, completing Yau's conjecture there. The upper bound fails for fixed smooth metrics in dimensions three and four, including metrics on $S^3$ arbitrarily close to round. In dimension five, nodal measure can grow faster than $\lambda^{1/2+\varepsilon_0}$ for some fixed $\varepsilon_0>0$, ruling out even arbitrarily small power losses. + +The challenge is `YauCounterexample`, also at `/opt/openai-math/challenges/YauCounterexample.lean`: + +```lean +import Mathlib + +namespace OAI + +namespace Yau +namespace Target +open Bundle Manifold Matrix Filter +open scoped ContDiff Topology ENNReal +noncomputable section + +abbrev Base := Metric.sphere (0 : EuclideanSpace ℝ (Fin 5)) 1 + +abbrev Manifold5 := Base × Circle + +abbrev Model := EuclideanSpace ℝ (Fin 4) × EuclideanSpace ℝ (Fin 1) + +abbrev modelWithCorners := (𝓡 4).prod (𝓡 1) + +abbrev SmoothMetric := ContMDiffRiemannianMetric modelWithCorners ∞ Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) + +abbrev Index := Fin (Module.finrank ℝ Model) + +def frame : Module.Basis Index ℝ Model := Module.finBasis ℝ Model + +def metricMatrix (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (y : Model) : Matrix Index Index ℝ := fun i j ↦ + g.inner (c.symm y) + (mfderiv 𝓘(ℝ, Model) modelWithCorners c.symm y (frame i)) + (mfderiv 𝓘(ℝ, Model) modelWithCorners c.symm y (frame j)) + +def volumeFactor (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (y : Model) : ℝ := Real.sqrt (metricMatrix g c y).det + +def chartLaplacian (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (u : Manifold5 → ℝ) (y : Model) : ℝ := + (volumeFactor g c y)⁻¹ * ∑ i, fderiv ℝ + (fun z ↦ volumeFactor g c z * ∑ j, + (metricMatrix g c z)⁻¹ i j * fderiv ℝ (u ∘ c.symm) z (frame j)) y (frame i) + +def nodalMeasure (g : SmoothMetric) (u : Manifold5 → ℝ) : ℝ≥0∞ := + letI : RiemannianBundle (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := + ⟨g.toRiemannianMetric⟩ + letI : IsContMDiffRiemannianBundle modelWithCorners ∞ Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := inferInstance + letI : MeasurableSpace Manifold5 := borel Manifold5 + letI : BorelSpace Manifold5 := ⟨rfl⟩ + letI : IsContinuousRiemannianBundle Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := + ⟨g.inner, g.toContinuousRiemannianMetric.continuous, fun _ _ _ ↦ rfl⟩ + letI : EMetricSpace Manifold5 := EMetricSpace.ofRiemannianMetric modelWithCorners Manifold5 + MeasureTheory.Measure.hausdorffMeasure (4 : ℝ) {x | u x = 0} + +def MainTarget : Prop := + ∃ (g : SmoothMetric) (lam : ℕ → ℝ) (u : ℕ → Manifold5 → ℝ), + (∀ k, 0 < lam k) ∧ + (∀ k, u k ≠ 0) ∧ + (∀ k, ContMDiff modelWithCorners 𝓘(ℝ, ℝ) ∞ (u k)) ∧ + (∀ k x, -chartLaplacian g (extChartAt modelWithCorners x) (u k) ((extChartAt modelWithCorners x) x) = + lam k * u k x) ∧ + Tendsto lam atTop atTop ∧ + Tendsto (fun k ↦ nodalMeasure g (u k) / ENNReal.ofReal (Real.sqrt (lam k))) + atTop (𝓝 ⊤) + +theorem yau_nodal_set_upper_bound_counterexample : MainTarget := by + sorry + +end +end Target +end Yau + +end OAI +``` + +## What to submit + +Write `/workspace/Submission.lean`. Start from a copy of the challenge: + +```bash +cp /opt/openai-math/challenges/YauCounterexample.lean /workspace/Submission.lean +``` + +then replace every `sorry` with a proof. The file is graded on three things: + +- **Same statements.** The theorem `OAI.Yau.Target.yau_nodal_set_upper_bound_counterexample` must keep exactly the statement shown above: same names, + namespaces, binders and types. Every definition the statements use must stay exactly as written. + Change nothing except the proofs. +- **Standard axioms only.** Proofs may use only `propext`, `Quot.sound` and `Classical.choice`. + `sorry`, `admit`, new `axiom`s and `native_decide` (it introduces an axiom of its own) are rejected. +- **Keep the challenge's declarations as they are.** Put new lemmas and instances *after* the + definitions the statements use, or in a separate `Submission/*.lean` module. A declaration added + before them can change how they elaborate, and then they no longer match the challenge. +- **Kernel-checked.** The proofs are re-checked by the Lean kernel, not just the elaborator. + +Long proofs can be split into modules under `/workspace/Submission/` (module names +`Submission.Foo`, `Submission.Foo.Bar`) imported from `Submission.lean`. Only `.lean` files at +those two paths are graded. + +## Environment + +- Lean `v4.34.1` and Mathlib at commit `d13f23b` are installed and prebuilt; `/workspace` is a + Lake project. +- The sandbox has 4 CPUs and 8 GB of memory; `LEAN_NUM_THREADS=3` keeps `lake build` to three + parallel jobs. Check your work with `cd /workspace && lake build Submission`. Add `#print axioms ` to see + which axioms a proof uses. +- There is no internet access. OpenAI's own proofs are not installed. + +## Grading + +When you finish, `Submission.lean` and `Submission/**.lean` are copied to a fresh machine and +checked with [Comparator](https://github.com/leanprover/comparator), the Lean FRO's proof checker. +The reward is 1 if Comparator accepts the proof and 0 otherwise. A partial proof scores 0. diff --git a/tasks/yau-counterexample/solution/closure.txt b/tasks/yau-counterexample/solution/closure.txt new file mode 100644 index 0000000000000000000000000000000000000000..fc6fb69d8098377b5a6c99e5e66ca4475aaa9fbd --- /dev/null +++ b/tasks/yau-counterexample/solution/closure.txt @@ -0,0 +1,1068 @@ +OAI.Geometry.NodalSets.Charts.AbsolutePiola +OAI.Geometry.NodalSets.Charts.AdaptedChartFamilyLemmas +OAI.Geometry.NodalSets.Charts.AdaptedMetricFrame +OAI.Geometry.NodalSets.Charts.AdaptedNormalChart +OAI.Geometry.NodalSets.Charts.AdmissibleChartPatch +OAI.Geometry.NodalSets.Charts.BallGeometry +OAI.Geometry.NodalSets.Charts.BaseChartFlux +OAI.Geometry.NodalSets.Charts.CenteredSphereChart +OAI.Geometry.NodalSets.Charts.CenteredSphereDensity +OAI.Geometry.NodalSets.Charts.CenteredSphereMetricLemmas +OAI.Geometry.NodalSets.Charts.CenteredSphereSecondJet +OAI.Geometry.NodalSets.Charts.ChartDerivativeTransfer +OAI.Geometry.NodalSets.Charts.ChartFrameSmooth +OAI.Geometry.NodalSets.Charts.ChartHessianLemmas +OAI.Geometry.NodalSets.Charts.ChartMetric +OAI.Geometry.NodalSets.Charts.ChartNormComparison +OAI.Geometry.NodalSets.Charts.ChartOperatorIdentity +OAI.Geometry.NodalSets.Charts.ChartPushforward +OAI.Geometry.NodalSets.Charts.ChartedEnvelope +OAI.Geometry.NodalSets.Charts.CircleChartFactor +OAI.Geometry.NodalSets.Charts.CircleInvariantDerivative +OAI.Geometry.NodalSets.Charts.CircleLaplacian +OAI.Geometry.NodalSets.Charts.CommonInjectiveChart +OAI.Geometry.NodalSets.Charts.CommonInvariantCharts +OAI.Geometry.NodalSets.Charts.CommonSmoothChart +OAI.Geometry.NodalSets.Charts.CompactFrameCover +OAI.Geometry.NodalSets.Charts.ComplexMetricFlux +OAI.Geometry.NodalSets.Charts.ContactGeometry +OAI.Geometry.NodalSets.Charts.ContinuousAdaptedFrame +OAI.Geometry.NodalSets.Charts.CorrugationFrameBounds +OAI.Geometry.NodalSets.Charts.CorrugationFrameOperatorBounds +OAI.Geometry.NodalSets.Charts.CorrugationFrameVolume +OAI.Geometry.NodalSets.Charts.CorrugationFrozenFrame +OAI.Geometry.NodalSets.Charts.CorrugationGridFrames +OAI.Geometry.NodalSets.Charts.CorrugationMetricError +OAI.Geometry.NodalSets.Charts.CorrugationMetricErrorRescale +OAI.Geometry.NodalSets.Charts.CorrugationRadialMetric +OAI.Geometry.NodalSets.Charts.CorrugationRotatingFrame +OAI.Geometry.NodalSets.Charts.FiniteChartDerivativeSeminorm +OAI.Geometry.NodalSets.Charts.FiniteChartDerivativeSize +OAI.Geometry.NodalSets.Charts.FixedChartAmbientLaplacian +OAI.Geometry.NodalSets.Charts.FixedChartRoundOperator +OAI.Geometry.NodalSets.Charts.FixedChartSeedEquation +OAI.Geometry.NodalSets.Charts.FixedChartSeedSupport +OAI.Geometry.NodalSets.Charts.FrameCotangent +OAI.Geometry.NodalSets.Charts.FrameMapFamily +OAI.Geometry.NodalSets.Charts.GeometricContact +OAI.Geometry.NodalSets.Charts.GlobalSphereEquation +OAI.Geometry.NodalSets.Charts.ImmersionMetric +OAI.Geometry.NodalSets.Charts.IndependentAmbientMetric +OAI.Geometry.NodalSets.Charts.IntrinsicChartTensor +OAI.Geometry.NodalSets.Charts.IntrinsicCorrectedChart +OAI.Geometry.NodalSets.Charts.IntrinsicDifferentialPairChart +OAI.Geometry.NodalSets.Charts.IntrinsicGlobalSphereStage +OAI.Geometry.NodalSets.Charts.IntrinsicLiftGeometry +OAI.Geometry.NodalSets.Charts.IntrinsicPackedGlobalSphereStage +OAI.Geometry.NodalSets.Charts.IntrinsicPackedPositiveSphereStage +OAI.Geometry.NodalSets.Charts.IntrinsicUniformPositiveSphereStage +OAI.Geometry.NodalSets.Charts.InvariantFrameInverse +OAI.Geometry.NodalSets.Charts.InverseChartJets +OAI.Geometry.NodalSets.Charts.InverseMetricJet +OAI.Geometry.NodalSets.Charts.LocalAdaptedFrame +OAI.Geometry.NodalSets.Charts.LocalFrameTriple +OAI.Geometry.NodalSets.Charts.LocalMetricChart +OAI.Geometry.NodalSets.Charts.LocalMetricJetContinuityLemmas +OAI.Geometry.NodalSets.Charts.LocalMetricJets +OAI.Geometry.NodalSets.Charts.LocalPiolaDivergence +OAI.Geometry.NodalSets.Charts.ManifoldCompactExtension +OAI.Geometry.NodalSets.Charts.ManifoldMatrixSmooth +OAI.Geometry.NodalSets.Charts.MatrixMetricPullback +OAI.Geometry.NodalSets.Charts.MetricCoercivity +OAI.Geometry.NodalSets.Charts.MetricConnectionFamilyLemmas +OAI.Geometry.NodalSets.Charts.MetricFluxPullback +OAI.Geometry.NodalSets.Charts.MetricFrameOps +OAI.Geometry.NodalSets.Charts.MetricFrequencyBounds +OAI.Geometry.NodalSets.Charts.MetricJetAdmissibility +OAI.Geometry.NodalSets.Charts.MetricNormalizationBounds +OAI.Geometry.NodalSets.Charts.MetricNormalizationStabilityLemmas +OAI.Geometry.NodalSets.Charts.NestedChartBounds +OAI.Geometry.NodalSets.Charts.NormalFrameContinuous +OAI.Geometry.NodalSets.Charts.NormalFramePhase +OAI.Geometry.NodalSets.Charts.NormalTaylorMetric +OAI.Geometry.NodalSets.Charts.PiolaFlux +OAI.Geometry.NodalSets.Charts.PiolaFour +OAI.Geometry.NodalSets.Charts.PositiveMetric +OAI.Geometry.NodalSets.Charts.ProductChartFlux +OAI.Geometry.NodalSets.Charts.ProductChartPullback +OAI.Geometry.NodalSets.Charts.ProductChartVolume +OAI.Geometry.NodalSets.Charts.QuadraticChart +OAI.Geometry.NodalSets.Charts.RadialMetricIdentification +OAI.Geometry.NodalSets.Charts.RealFiniteAtlasBallSubsequence +OAI.Geometry.NodalSets.Charts.RoundChartConnection +OAI.Geometry.NodalSets.Charts.RoundCotangentSmooth +OAI.Geometry.NodalSets.Charts.RoundCotangentTensor +OAI.Geometry.NodalSets.Charts.RoundSphereEnergyData +OAI.Geometry.NodalSets.Charts.SeedChartOperator +OAI.Geometry.NodalSets.Charts.SeedChartPrincipal +OAI.Geometry.NodalSets.Charts.SeedChartScalarExtension +OAI.Geometry.NodalSets.Charts.SeedCoordMetricRegularity +OAI.Geometry.NodalSets.Charts.SeedMetricNeighborhood +OAI.Geometry.NodalSets.Charts.SeparatedCircleDivergence +OAI.Geometry.NodalSets.Charts.SimplicityEnergyDensity +OAI.Geometry.NodalSets.Charts.SmoothBundleInverse +OAI.Geometry.NodalSets.Charts.SmoothInverseChart +OAI.Geometry.NodalSets.Charts.SphereAffineDivergenceJets +OAI.Geometry.NodalSets.Charts.SphereAffineFormAnnihilation +OAI.Geometry.NodalSets.Charts.SphereAffineNormalizedLimit +OAI.Geometry.NodalSets.Charts.SphereAffinePositiveInterval +OAI.Geometry.NodalSets.Charts.SphereAffineSimplicityCriterion +OAI.Geometry.NodalSets.Charts.SphereAmbientLaplacian +OAI.Geometry.NodalSets.Charts.SphereC1EnergyConvergence +OAI.Geometry.NodalSets.Charts.SphereC1IntrinsicLimit +OAI.Geometry.NodalSets.Charts.SphereChartArbitrarySecond +OAI.Geometry.NodalSets.Charts.SphereChartConformal +OAI.Geometry.NodalSets.Charts.SphereChartCutoffApproximation +OAI.Geometry.NodalSets.Charts.SphereChartCutoffWeak +OAI.Geometry.NodalSets.Charts.SphereChartDerivativeMap +OAI.Geometry.NodalSets.Charts.SphereChartDifferenceBound +OAI.Geometry.NodalSets.Charts.SphereChartDivergenceData +OAI.Geometry.NodalSets.Charts.SphereChartEllipticCompactness +OAI.Geometry.NodalSets.Charts.SphereChartEnergyBounds +OAI.Geometry.NodalSets.Charts.SphereChartFluxL2 +OAI.Geometry.NodalSets.Charts.SphereChartL2Comparison +OAI.Geometry.NodalSets.Charts.SphereChartLimitGluing +OAI.Geometry.NodalSets.Charts.SphereChartOpenMap +OAI.Geometry.NodalSets.Charts.SphereChartScalarExtension +OAI.Geometry.NodalSets.Charts.SphereChartStrongApproximation +OAI.Geometry.NodalSets.Charts.SphereChartTangentTrace +OAI.Geometry.NodalSets.Charts.SphereChartTestFlux +OAI.Geometry.NodalSets.Charts.SphereChartTransition +OAI.Geometry.NodalSets.Charts.SphereChartUniformH1Bounds +OAI.Geometry.NodalSets.Charts.SphereChartValueMap +OAI.Geometry.NodalSets.Charts.SphereChartVolume +OAI.Geometry.NodalSets.Charts.SphereChartWeakDerivative +OAI.Geometry.NodalSets.Charts.SphereChartWeakDivergence +OAI.Geometry.NodalSets.Charts.SphereCompactChartTesting +OAI.Geometry.NodalSets.Charts.SphereCompactFluxGreen +OAI.Geometry.NodalSets.Charts.SphereCompletedGreenTest +OAI.Geometry.NodalSets.Charts.SphereContravariant +OAI.Geometry.NodalSets.Charts.SphereCotangentCoordinates +OAI.Geometry.NodalSets.Charts.SphereCovectorRestriction +OAI.Geometry.NodalSets.Charts.SphereDifferenceCoercivity +OAI.Geometry.NodalSets.Charts.SphereDifferenceTestBound +OAI.Geometry.NodalSets.Charts.SphereDifferenceTestEquation +OAI.Geometry.NodalSets.Charts.SphereDifferenceTestLiteral +OAI.Geometry.NodalSets.Charts.SphereDifferenceTestMaps +OAI.Geometry.NodalSets.Charts.SphereDifferenceTestWeak +OAI.Geometry.NodalSets.Charts.SphereDifferentialCoordinates +OAI.Geometry.NodalSets.Charts.SphereDirichletBilinear +OAI.Geometry.NodalSets.Charts.SphereEnergyBilinear +OAI.Geometry.NodalSets.Charts.SphereEnergyCompactness +OAI.Geometry.NodalSets.Charts.SphereEnergyCompletion +OAI.Geometry.NodalSets.Charts.SphereEnergyForm +OAI.Geometry.NodalSets.Charts.SphereEnergyFormLimit +OAI.Geometry.NodalSets.Charts.SphereEnergyInnerProduct +OAI.Geometry.NodalSets.Charts.SphereEnergyL2Compact +OAI.Geometry.NodalSets.Charts.SphereEnergyL2Injective +OAI.Geometry.NodalSets.Charts.SphereEnergyL2Map +OAI.Geometry.NodalSets.Charts.SphereFiniteAtlasSubsequence +OAI.Geometry.NodalSets.Charts.SphereFiniteChartEnergyUpper +OAI.Geometry.NodalSets.Charts.SphereFiniteChartL2Comparison +OAI.Geometry.NodalSets.Charts.SphereFiniteJetCompactness +OAI.Geometry.NodalSets.Charts.SphereFiniteNeighborhoodBounds +OAI.Geometry.NodalSets.Charts.SphereFiniteNormIndexedCompactness +OAI.Geometry.NodalSets.Charts.SphereFiniteNormIntrinsicCompactness +OAI.Geometry.NodalSets.Charts.SphereFiniteNormMixedLimit +OAI.Geometry.NodalSets.Charts.SphereFiniteNormQuadraticLimit +OAI.Geometry.NodalSets.Charts.SphereFiniteNormVariationalLimit +OAI.Geometry.NodalSets.Charts.SphereFiniteOrderLimitGluing +OAI.Geometry.NodalSets.Charts.SphereFiniteSmoothPartition +OAI.Geometry.NodalSets.Charts.SphereFiniteVariationalFrame +OAI.Geometry.NodalSets.Charts.SphereFiniteWeakJetGain +OAI.Geometry.NodalSets.Charts.SphereFluxDifferenceExpansion +OAI.Geometry.NodalSets.Charts.SphereForcingJetNeighborhood +OAI.Geometry.NodalSets.Charts.SphereFormPolarization +OAI.Geometry.NodalSets.Charts.SphereGlobalNeighborhoodCompactness +OAI.Geometry.NodalSets.Charts.SphereGlobalSmoothCompactness +OAI.Geometry.NodalSets.Charts.SphereHessianDifferenceCoercivity +OAI.Geometry.NodalSets.Charts.SphereHessianFluxDifference +OAI.Geometry.NodalSets.Charts.SphereIndexedContinuity +OAI.Geometry.NodalSets.Charts.SphereIndexedDivergence +OAI.Geometry.NodalSets.Charts.SphereIndexedFrameConsistency +OAI.Geometry.NodalSets.Charts.SphereIndexedGapContinuity +OAI.Geometry.NodalSets.Charts.SphereIndexedGapSimplicityLemmas +OAI.Geometry.NodalSets.Charts.SphereIndexedIntrinsic +OAI.Geometry.NodalSets.Charts.SphereIntegratedFormComparison +OAI.Geometry.NodalSets.Charts.SphereInteriorChartWeakDerivative +OAI.Geometry.NodalSets.Charts.SphereInteriorDifferenceBound +OAI.Geometry.NodalSets.Charts.SphereInteriorDifferenceL2 +OAI.Geometry.NodalSets.Charts.SphereInteriorFluxCoercivity +OAI.Geometry.NodalSets.Charts.SphereInteriorGradientDifferenceBound +OAI.Geometry.NodalSets.Charts.SphereInteriorJetBound +OAI.Geometry.NodalSets.Charts.SphereInteriorLocalizedEnergy +OAI.Geometry.NodalSets.Charts.SphereInteriorWeakDerivativeGain +OAI.Geometry.NodalSets.Charts.SphereL2LocalPullback +OAI.Geometry.NodalSets.Charts.SphereLimitEquation +OAI.Geometry.NodalSets.Charts.SphereLocalLimitGluing +OAI.Geometry.NodalSets.Charts.SphereMeasureChartGeometry +OAI.Geometry.NodalSets.Charts.SphereNormalizedGlobalLimit +OAI.Geometry.NodalSets.Charts.SphereNormalizedSimpleUniqueness +OAI.Geometry.NodalSets.Charts.SphereOperatorInvariance +OAI.Geometry.NodalSets.Charts.SpherePositiveMargins +OAI.Geometry.NodalSets.Charts.SpherePositiveNormalization +OAI.Geometry.NodalSets.Charts.SpherePreservingEquation +OAI.Geometry.NodalSets.Charts.SphereReferenceMeasure +OAI.Geometry.NodalSets.Charts.SphereReferenceMeasureFinite +OAI.Geometry.NodalSets.Charts.SphereReferenceMeasureInvariance +OAI.Geometry.NodalSets.Charts.SphereReferenceMeasurePositive +OAI.Geometry.NodalSets.Charts.SphereRestrictionArbitraryHessian +OAI.Geometry.NodalSets.Charts.SphereSimplicity +OAI.Geometry.NodalSets.Charts.SphereSimplicityAnnihilation +OAI.Geometry.NodalSets.Charts.SphereSimplicityBump +OAI.Geometry.NodalSets.Charts.SphereSimplicityEnergy +OAI.Geometry.NodalSets.Charts.SphereSimplicityExtension +OAI.Geometry.NodalSets.Charts.SphereSimplicityInNeighborhood +OAI.Geometry.NodalSets.Charts.SphereSimplicityKernel +OAI.Geometry.NodalSets.Charts.SphereSimplicityKernelForm +OAI.Geometry.NodalSets.Charts.SphereSimplicityRigidity +OAI.Geometry.NodalSets.Charts.SphereSimplicitySequenceContradiction +OAI.Geometry.NodalSets.Charts.SphereSimplicitySquare +OAI.Geometry.NodalSets.Charts.SphereSmallChartPartition +OAI.Geometry.NodalSets.Charts.SphereSmoothFromCharts +OAI.Geometry.NodalSets.Charts.SphereSmoothGreenBound +OAI.Geometry.NodalSets.Charts.SphereSmoothGreenLocal +OAI.Geometry.NodalSets.Charts.SphereSmoothL2Density +OAI.Geometry.NodalSets.Charts.SphereSmoothVariationalStrong +OAI.Geometry.NodalSets.Charts.SphereSquareDifferenceTestBound +OAI.Geometry.NodalSets.Charts.SphereTangentTrace +OAI.Geometry.NodalSets.Charts.SphereThirdFluxSymmetry +OAI.Geometry.NodalSets.Charts.SphereTransitionFlux +OAI.Geometry.NodalSets.Charts.SphereTransitionFrame +OAI.Geometry.NodalSets.Charts.SphereTransitionScalar +OAI.Geometry.NodalSets.Charts.SphereTransitionTensor +OAI.Geometry.NodalSets.Charts.SphereUniformChartL2 +OAI.Geometry.NodalSets.Charts.SphereUniformDensityPairingLimit +OAI.Geometry.NodalSets.Charts.SphereUniformEnergyRepresentative +OAI.Geometry.NodalSets.Charts.SphereUniformWeakJetGain +OAI.Geometry.NodalSets.Charts.SphereVariationalContinuousRegularity +OAI.Geometry.NodalSets.Charts.SphereWeakHessianSymmetry +OAI.Geometry.NodalSets.Charts.SphereWeakJetSuccessor +OAI.Geometry.NodalSets.Charts.SphereWeakThirdSymmetry +OAI.Geometry.NodalSets.Charts.SphereWeightedChartL2 +OAI.Geometry.NodalSets.Charts.SphereWeightedGradientBound +OAI.Geometry.NodalSets.Charts.SphereWeightedL1Bound +OAI.Geometry.NodalSets.Charts.SphereWeightedL2 +OAI.Geometry.NodalSets.Charts.SphereWeightedL2Infinite +OAI.Geometry.NodalSets.Charts.SphereWeightedNormalization +OAI.Geometry.NodalSets.Charts.SphereWeightedPairingLimit +OAI.Geometry.NodalSets.Charts.SupportedFiniteAtlasBounds +OAI.Geometry.NodalSets.Charts.SupportedSphereChartBounds +OAI.Geometry.NodalSets.Charts.TangentGramDeterminant +OAI.Geometry.NodalSets.Charts.TangentialMatrixInverse +OAI.Geometry.NodalSets.Charts.TargetChartBasis +OAI.Geometry.NodalSets.Charts.TargetMetricEnergy +OAI.Geometry.NodalSets.Charts.TargetProductChart +OAI.Geometry.NodalSets.Charts.TargetShortCircleArc +OAI.Geometry.NodalSets.Charts.TargetWarpedMetric +OAI.Geometry.NodalSets.Charts.TransformedDensity +OAI.Geometry.NodalSets.Charts.UniformInverseChartBounds +OAI.Geometry.NodalSets.Charts.WeightedCircleMatrix +OAI.Geometry.NodalSets.Charts.WeightedCircleSmooth +OAI.Geometry.NodalSets.Coefficients.CoefficientAmbientReconstruction +OAI.Geometry.NodalSets.Coefficients.CoefficientCutoffRemoval +OAI.Geometry.NodalSets.Coefficients.CoefficientLocality +OAI.Geometry.NodalSets.Coefficients.CoefficientMetricJets +OAI.Geometry.NodalSets.Coefficients.CommonCoefficientExtension +OAI.Geometry.NodalSets.Coefficients.CompactResidualMultiplier +OAI.Geometry.NodalSets.Coefficients.ComplexChartCoefficient +OAI.Geometry.NodalSets.Coefficients.CoordinateCorrection +OAI.Geometry.NodalSets.Coefficients.CorrectionAlgebra +OAI.Geometry.NodalSets.Coefficients.CorrectionProductBounds +OAI.Geometry.NodalSets.Coefficients.CorrugationFirstResidual +OAI.Geometry.NodalSets.Coefficients.CutoffResidualProductLemmas +OAI.Geometry.NodalSets.Coefficients.CutoffWaveResidual +OAI.Geometry.NodalSets.Coefficients.DualWaveCoefficient +OAI.Geometry.NodalSets.Coefficients.FiniteResidualBound +OAI.Geometry.NodalSets.Coefficients.FiniteSphereCoefficientAtlas +OAI.Geometry.NodalSets.Coefficients.GaussianCoefficientMSE +OAI.Geometry.NodalSets.Coefficients.GaussianCoefficientTail +OAI.Geometry.NodalSets.Coefficients.GaussianCoefficientVariance +OAI.Geometry.NodalSets.Coefficients.GlobalCorrection +OAI.Geometry.NodalSets.Coefficients.GlobalSeedResidualSupport +OAI.Geometry.NodalSets.Coefficients.GlobalWaveResidual +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientBounds +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientIncrementBounds +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientMap +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientMetric +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientNeighborhood +OAI.Geometry.NodalSets.Coefficients.IntrinsicCoefficientSmooth +OAI.Geometry.NodalSets.Coefficients.IntrinsicCorrectionResidual +OAI.Geometry.NodalSets.Coefficients.IntrinsicCorrectionSize +OAI.Geometry.NodalSets.Coefficients.IntrinsicDivergenceCoefficients +OAI.Geometry.NodalSets.Coefficients.IntrinsicRealCorrection +OAI.Geometry.NodalSets.Coefficients.IntrinsicTotalResidual +OAI.Geometry.NodalSets.Coefficients.JetCoefficient +OAI.Geometry.NodalSets.Coefficients.LatticeResidualBounds +OAI.Geometry.NodalSets.Coefficients.LatticeResidualSupport +OAI.Geometry.NodalSets.Coefficients.LocalCoordinateResidual +OAI.Geometry.NodalSets.Coefficients.LocalResidualRegularity +OAI.Geometry.NodalSets.Coefficients.MatrixCoefficientBounds +OAI.Geometry.NodalSets.Coefficients.MatrixCoefficientMap +OAI.Geometry.NodalSets.Coefficients.MetricGradientResidual +OAI.Geometry.NodalSets.Coefficients.MetricWaveJets +OAI.Geometry.NodalSets.Coefficients.OriginalCoefficientComparison +OAI.Geometry.NodalSets.Coefficients.PlacedEnvelopeResidualWaves +OAI.Geometry.NodalSets.Coefficients.PlacedRandomResidual +OAI.Geometry.NodalSets.Coefficients.PlacedSeedResidual +OAI.Geometry.NodalSets.Coefficients.PlacedTotalResidual +OAI.Geometry.NodalSets.Coefficients.PositiveSphereCorrection +OAI.Geometry.NodalSets.Coefficients.RealCoefficientNeighborhoodEstimate +OAI.Geometry.NodalSets.Coefficients.RealCoefficientNeighborhoodPointwise +OAI.Geometry.NodalSets.Coefficients.RealCutoffResidual +OAI.Geometry.NodalSets.Coefficients.RealFiniteCoefficientL2Bound +OAI.Geometry.NodalSets.Coefficients.RealFintypeCoefficientBound +OAI.Geometry.NodalSets.Coefficients.ResidualProduct +OAI.Geometry.NodalSets.Coefficients.ResidualTaylor +OAI.Geometry.NodalSets.Coefficients.RoundCoefficientJets +OAI.Geometry.NodalSets.Coefficients.RoundCorrectionDenominator +OAI.Geometry.NodalSets.Coefficients.RoundCorrectionSize +OAI.Geometry.NodalSets.Coefficients.RoundSupportedCorrection +OAI.Geometry.NodalSets.Coefficients.SeedCoefficientNeighborhood +OAI.Geometry.NodalSets.Coefficients.SeedCoefficientPlacement +OAI.Geometry.NodalSets.Coefficients.SeedResidualBounds +OAI.Geometry.NodalSets.Coefficients.SeededResidual +OAI.Geometry.NodalSets.Coefficients.SmoothFiniteResidual +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientAtlasInclusionLemmas +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientDifferenceBound +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientDistanceLaws +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientDivergenceJets +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientFormComparison +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientLimitTail +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientNormConvergence +OAI.Geometry.NodalSets.Coefficients.SphereCoefficientScalarBounds +OAI.Geometry.NodalSets.Coefficients.SphereFiniteCoefficientConstraints +OAI.Geometry.NodalSets.Coefficients.SphereIndexedCoefficientComparison +OAI.Geometry.NodalSets.Coefficients.SphereWeightedCoefficientJets +OAI.Geometry.NodalSets.Coefficients.SupportedCoefficientChartBounds +OAI.Geometry.NodalSets.Coefficients.TwoPointCoefficientEnergy +OAI.Geometry.NodalSets.Coefficients.UniformResidualCore +OAI.Geometry.NodalSets.Coefficients.UniformUncutResidual +OAI.Geometry.NodalSets.Coefficients.UniformWaveResidual +OAI.Geometry.NodalSets.Coefficients.WeightedCoefficientBounds +OAI.Geometry.NodalSets.Elliptic.AdmissibilityNeighborhood +OAI.Geometry.NodalSets.Elliptic.AdmissibleDirectionTriple +OAI.Geometry.NodalSets.Elliptic.AffineRescalingJets +OAI.Geometry.NodalSets.Elliptic.AmbientDerivativeDistance +OAI.Geometry.NodalSets.Elliptic.AmbientFormMatrix +OAI.Geometry.NodalSets.Elliptic.AmbientMatrixForm +OAI.Geometry.NodalSets.Elliptic.AmplitudeBounds +OAI.Geometry.NodalSets.Elliptic.AnchoredCubeBound +OAI.Geometry.NodalSets.Elliptic.AnchoredIntervalBound +OAI.Geometry.NodalSets.Elliptic.BallPacking +OAI.Geometry.NodalSets.Elliptic.BasisDivergence +OAI.Geometry.NodalSets.Elliptic.BasisLaplacian +OAI.Geometry.NodalSets.Elliptic.BasisLaplacianReindex +OAI.Geometry.NodalSets.Elliptic.CenteredRoundOperator +OAI.Geometry.NodalSets.Elliptic.CertificateSelection +OAI.Geometry.NodalSets.Elliptic.CommonLocalExtension +OAI.Geometry.NodalSets.Elliptic.CommutatorBounds +OAI.Geometry.NodalSets.Elliptic.CompactContravariantComparison +OAI.Geometry.NodalSets.Elliptic.CompactDifferentialBound +OAI.Geometry.NodalSets.Elliptic.CompactFamilyBallJetEstimate +OAI.Geometry.NodalSets.Elliptic.CompactFamilyPointwiseEstimate +OAI.Geometry.NodalSets.Elliptic.CompactFirstJetFunctionalLimit +OAI.Geometry.NodalSets.Elliptic.CompactFluxGreen +OAI.Geometry.NodalSets.Elliptic.CompactFreezing +OAI.Geometry.NodalSets.Elliptic.CompactHessianUnitBound +OAI.Geometry.NodalSets.Elliptic.CompactLocalCompositionBounds +OAI.Geometry.NodalSets.Elliptic.CompactNormalOperator +OAI.Geometry.NodalSets.Elliptic.CompactParameterDerivativeBounds +OAI.Geometry.NodalSets.Elliptic.CompactParameterEllipticityLemmas +OAI.Geometry.NodalSets.Elliptic.CompactParameterJetBounds +OAI.Geometry.NodalSets.Elliptic.CompactSignEvents +OAI.Geometry.NodalSets.Elliptic.CompactSmoothExtension +OAI.Geometry.NodalSets.Elliptic.CompactSourceOperator +OAI.Geometry.NodalSets.Elliptic.CompactSourceRepresentatives +OAI.Geometry.NodalSets.Elliptic.CompactUniformIntegralLimit +OAI.Geometry.NodalSets.Elliptic.CompactUniformProducts +OAI.Geometry.NodalSets.Elliptic.CompactWeightedDivergenceIntegral +OAI.Geometry.NodalSets.Elliptic.CompactWeightedWeakEquation +OAI.Geometry.NodalSets.Elliptic.ContactTaylor +OAI.Geometry.NodalSets.Elliptic.ContinuousPolynomialFamily +OAI.Geometry.NodalSets.Elliptic.ContravariantPullback +OAI.Geometry.NodalSets.Elliptic.CoordinateMatrixEllipticity +OAI.Geometry.NodalSets.Elliptic.CoordinateNorm +OAI.Geometry.NodalSets.Elliptic.CoordinatePartialJets +OAI.Geometry.NodalSets.Elliptic.CoordinateTransverseDisk +OAI.Geometry.NodalSets.Elliptic.CorrugationActualLowDirection +OAI.Geometry.NodalSets.Elliptic.CorrugationAdmissibleStage +OAI.Geometry.NodalSets.Elliptic.CorrugationAffineJets +OAI.Geometry.NodalSets.Elliptic.CorrugationAnnulusBoxes +OAI.Geometry.NodalSets.Elliptic.CorrugationAnnulusCell +OAI.Geometry.NodalSets.Elliptic.CorrugationAnnulusFraction +OAI.Geometry.NodalSets.Elliptic.CorrugationAnnulusPacking +OAI.Geometry.NodalSets.Elliptic.CorrugationAssembly +OAI.Geometry.NodalSets.Elliptic.CorrugationCellGain +OAI.Geometry.NodalSets.Elliptic.CorrugationClosedCell +OAI.Geometry.NodalSets.Elliptic.CorrugationClosedCubeLocality +OAI.Geometry.NodalSets.Elliptic.CorrugationCubeIntegral +OAI.Geometry.NodalSets.Elliptic.CorrugationCubeMeasure +OAI.Geometry.NodalSets.Elliptic.CorrugationCubePartition +OAI.Geometry.NodalSets.Elliptic.CorrugationCutoff +OAI.Geometry.NodalSets.Elliptic.CorrugationDirectionEvaluations +OAI.Geometry.NodalSets.Elliptic.CorrugationDiskJets +OAI.Geometry.NodalSets.Elliptic.CorrugationDiskWell +OAI.Geometry.NodalSets.Elliptic.CorrugationEnvelopeJets +OAI.Geometry.NodalSets.Elliptic.CorrugationErrorBound +OAI.Geometry.NodalSets.Elliptic.CorrugationFastLower +OAI.Geometry.NodalSets.Elliptic.CorrugationFiniteGainLemmas +OAI.Geometry.NodalSets.Elliptic.CorrugationFirstAxis +OAI.Geometry.NodalSets.Elliptic.CorrugationFixedAmplitude +OAI.Geometry.NodalSets.Elliptic.CorrugationFixedCutoff +OAI.Geometry.NodalSets.Elliptic.CorrugationFixedStage +OAI.Geometry.NodalSets.Elliptic.CorrugationFrequencyScale +OAI.Geometry.NodalSets.Elliptic.CorrugationGainStage +OAI.Geometry.NodalSets.Elliptic.CorrugationGlobalError +OAI.Geometry.NodalSets.Elliptic.CorrugationGlobalJets +OAI.Geometry.NodalSets.Elliptic.CorrugationGradientFreezing +OAI.Geometry.NodalSets.Elliptic.CorrugationGradientRates +OAI.Geometry.NodalSets.Elliptic.CorrugationGridAdmissibility +OAI.Geometry.NodalSets.Elliptic.CorrugationGridAssembly +OAI.Geometry.NodalSets.Elliptic.CorrugationGridGain +OAI.Geometry.NodalSets.Elliptic.CorrugationGridNonvanishing +OAI.Geometry.NodalSets.Elliptic.CorrugationGridProperties +OAI.Geometry.NodalSets.Elliptic.CorrugationHighAdmissibility +OAI.Geometry.NodalSets.Elliptic.CorrugationHighRegime +OAI.Geometry.NodalSets.Elliptic.CorrugationHighScalar +OAI.Geometry.NodalSets.Elliptic.CorrugationLargeSlope +OAI.Geometry.NodalSets.Elliptic.CorrugationLeadingLength +OAI.Geometry.NodalSets.Elliptic.CorrugationLeadingVector +OAI.Geometry.NodalSets.Elliptic.CorrugationLocalAdmissibility +OAI.Geometry.NodalSets.Elliptic.CorrugationLocalHessian +OAI.Geometry.NodalSets.Elliptic.CorrugationLowAdmissibility +OAI.Geometry.NodalSets.Elliptic.CorrugationLowDirection +OAI.Geometry.NodalSets.Elliptic.CorrugationLowGradient +OAI.Geometry.NodalSets.Elliptic.CorrugationLowOldMargin +OAI.Geometry.NodalSets.Elliptic.CorrugationLowRadial +OAI.Geometry.NodalSets.Elliptic.CorrugationNonvanishing +OAI.Geometry.NodalSets.Elliptic.CorrugationNormBounds +OAI.Geometry.NodalSets.Elliptic.CorrugationNormalizedGradient +OAI.Geometry.NodalSets.Elliptic.CorrugationOldData +OAI.Geometry.NodalSets.Elliptic.CorrugationOldSpeed +OAI.Geometry.NodalSets.Elliptic.CorrugationPeriodicBounds +OAI.Geometry.NodalSets.Elliptic.CorrugationPeriodicCell +OAI.Geometry.NodalSets.Elliptic.CorrugationPeriodicFlatJets +OAI.Geometry.NodalSets.Elliptic.CorrugationPeriodicJets +OAI.Geometry.NodalSets.Elliptic.CorrugationPeriodicWell +OAI.Geometry.NodalSets.Elliptic.CorrugationProjectedDirections +OAI.Geometry.NodalSets.Elliptic.CorrugationRadialJetsLemmas +OAI.Geometry.NodalSets.Elliptic.CorrugationRadialLoss +OAI.Geometry.NodalSets.Elliptic.CorrugationRegimeBounds +OAI.Geometry.NodalSets.Elliptic.CorrugationRegimeErrors +OAI.Geometry.NodalSets.Elliptic.CorrugationScaledJetsLemmas +OAI.Geometry.NodalSets.Elliptic.CorrugationSpeed +OAI.Geometry.NodalSets.Elliptic.CorrugationStrictMargin +OAI.Geometry.NodalSets.Elliptic.CorrugationUnitRegimeErrors +OAI.Geometry.NodalSets.Elliptic.CorrugationWellBound +OAI.Geometry.NodalSets.Elliptic.CorrugationWellChoice +OAI.Geometry.NodalSets.Elliptic.CorrugationWellSlope +OAI.Geometry.NodalSets.Elliptic.CubeControlExpectation +OAI.Geometry.NodalSets.Elliptic.CubeGradientBound +OAI.Geometry.NodalSets.Elliptic.CutoffAnnulus +OAI.Geometry.NodalSets.Elliptic.CutoffProduct +OAI.Geometry.NodalSets.Elliptic.DirectionTripleAlgebra +OAI.Geometry.NodalSets.Elliptic.DirectionalJet +OAI.Geometry.NodalSets.Elliptic.Divergence +OAI.Geometry.NodalSets.Elliptic.EikonalPolynomial +OAI.Geometry.NodalSets.Elliptic.EnvelopeContactJet +OAI.Geometry.NodalSets.Elliptic.EnvelopeNestedDomainsLemmas +OAI.Geometry.NodalSets.Elliptic.EnvelopeParameterAdmissibility +OAI.Geometry.NodalSets.Elliptic.EnvelopeParameterJets +OAI.Geometry.NodalSets.Elliptic.EnvelopePlacement +OAI.Geometry.NodalSets.Elliptic.EnvelopeRegion +OAI.Geometry.NodalSets.Elliptic.ExponentialIntegralSeparation +OAI.Geometry.NodalSets.Elliptic.ExteriorCorrectedEquation +OAI.Geometry.NodalSets.Elliptic.FiniteAmplitude +OAI.Geometry.NodalSets.Elliptic.FiniteBallPacking +OAI.Geometry.NodalSets.Elliptic.FiniteCertificateWeight +OAI.Geometry.NodalSets.Elliptic.FiniteCoverIntegral +OAI.Geometry.NodalSets.Elliptic.FiniteFamilyNonzeroComplement +OAI.Geometry.NodalSets.Elliptic.FiniteJetEnergy +OAI.Geometry.NodalSets.Elliptic.FiniteLinearConstraints +OAI.Geometry.NodalSets.Elliptic.FiniteLinearity +OAI.Geometry.NodalSets.Elliptic.FiniteSubsequenceSelection +OAI.Geometry.NodalSets.Elliptic.FirstJetGoodEvent +OAI.Geometry.NodalSets.Elliptic.FirstJetNonvanishing +OAI.Geometry.NodalSets.Elliptic.FirstJetSize +OAI.Geometry.NodalSets.Elliptic.FirstMomentFromSquare +OAI.Geometry.NodalSets.Elliptic.FixedDomainLiteralPacking +OAI.Geometry.NodalSets.Elliptic.FrequencyDerivativeEnergy +OAI.Geometry.NodalSets.Elliptic.FrequencyLeibniz +OAI.Geometry.NodalSets.Elliptic.FrozenPhaseLemmas +OAI.Geometry.NodalSets.Elliptic.HalfScaleLemmas +OAI.Geometry.NodalSets.Elliptic.HessianLinearTransport +OAI.Geometry.NodalSets.Elliptic.HighRegionNonvanishing +OAI.Geometry.NodalSets.Elliptic.IndependentWeightedMatrix +OAI.Geometry.NodalSets.Elliptic.IndependentWeightedSmooth +OAI.Geometry.NodalSets.Elliptic.InitialPhasePolynomial +OAI.Geometry.NodalSets.Elliptic.IntegratedSpeedGain +OAI.Geometry.NodalSets.Elliptic.IntrinsicAmbientExtension +OAI.Geometry.NodalSets.Elliptic.IntrinsicAmbientSmooth +OAI.Geometry.NodalSets.Elliptic.IntrinsicCompactWeakEquation +OAI.Geometry.NodalSets.Elliptic.IntrinsicEnergyFiniteSum +OAI.Geometry.NodalSets.Elliptic.IntrinsicEnergyIntegrable +OAI.Geometry.NodalSets.Elliptic.IntrinsicGreenTesting +OAI.Geometry.NodalSets.Elliptic.IntrinsicNoncriticalPlacement +OAI.Geometry.NodalSets.Elliptic.IntrinsicOneStep +OAI.Geometry.NodalSets.Elliptic.IntrinsicPackedQuantitativeCertificateGain +OAI.Geometry.NodalSets.Elliptic.IntrinsicPackedSelectedStage +OAI.Geometry.NodalSets.Elliptic.IntrinsicPackedSmallCorrectedStage +OAI.Geometry.NodalSets.Elliptic.IntrinsicPairUniformBounds +OAI.Geometry.NodalSets.Elliptic.IntrinsicRealCoordinates +OAI.Geometry.NodalSets.Elliptic.IntrinsicRealEllipticity +OAI.Geometry.NodalSets.Elliptic.IntrinsicRoundPerturbation +OAI.Geometry.NodalSets.Elliptic.IntrinsicRoundReference +OAI.Geometry.NodalSets.Elliptic.IntrinsicSeedPatch +OAI.Geometry.NodalSets.Elliptic.IntrinsicSeedRegularity +OAI.Geometry.NodalSets.Elliptic.IntrinsicUniformSelectedStage +OAI.Geometry.NodalSets.Elliptic.IntrinsicUniformSmallCorrectedStage +OAI.Geometry.NodalSets.Elliptic.IntrinsicWeightedLift +OAI.Geometry.NodalSets.Elliptic.InverseSquareSmallness +OAI.Geometry.NodalSets.Elliptic.JacobianCalculus +OAI.Geometry.NodalSets.Elliptic.JetNetExtension +OAI.Geometry.NodalSets.Elliptic.LiteralSeededFieldBounds +OAI.Geometry.NodalSets.Elliptic.LocalDirection +OAI.Geometry.NodalSets.Elliptic.LocalDirectionBounds +OAI.Geometry.NodalSets.Elliptic.LocalDirectionTriple +OAI.Geometry.NodalSets.Elliptic.LocalEnvelopeDomains +OAI.Geometry.NodalSets.Elliptic.LocalFirstJetNonvanishing +OAI.Geometry.NodalSets.Elliptic.LocalFrequencyLeibniz +OAI.Geometry.NodalSets.Elliptic.LocalJetAlgebra +OAI.Geometry.NodalSets.Elliptic.LocalLogJetBounds +OAI.Geometry.NodalSets.Elliptic.LocalMainLogJets +OAI.Geometry.NodalSets.Elliptic.LocalMatrixSmooth +OAI.Geometry.NodalSets.Elliptic.LocalSpatialJet +OAI.Geometry.NodalSets.Elliptic.LocalizedCorrugation +OAI.Geometry.NodalSets.Elliptic.LogJetBounds +OAI.Geometry.NodalSets.Elliptic.Logarithm +OAI.Geometry.NodalSets.Elliptic.LowRegionSeedDominance +OAI.Geometry.NodalSets.Elliptic.MainAmplitude +OAI.Geometry.NodalSets.Elliptic.MainLogJets +OAI.Geometry.NodalSets.Elliptic.NeighborhoodJetBound +OAI.Geometry.NodalSets.Elliptic.NetDecay +OAI.Geometry.NodalSets.Elliptic.NormalizedAdmissibility +OAI.Geometry.NodalSets.Elliptic.NormalizedJetBounds +OAI.Geometry.NodalSets.Elliptic.NormalizedJetPolynomialBound +OAI.Geometry.NodalSets.Elliptic.NormalizedRescaling +OAI.Geometry.NodalSets.Elliptic.OperatorAddition +OAI.Geometry.NodalSets.Elliptic.OperatorLocality +OAI.Geometry.NodalSets.Elliptic.PackingVolumeWeight +OAI.Geometry.NodalSets.Elliptic.PairedJetControl +OAI.Geometry.NodalSets.Elliptic.PartialJetGerm +OAI.Geometry.NodalSets.Elliptic.PhaseActualJet +OAI.Geometry.NodalSets.Elliptic.PhaseBounds +OAI.Geometry.NodalSets.Elliptic.PhaseContactFamily +OAI.Geometry.NodalSets.Elliptic.PhaseJet +OAI.Geometry.NodalSets.Elliptic.PlacedEnvelopeDomains +OAI.Geometry.NodalSets.Elliptic.PlacedSmoothRepresentatives +OAI.Geometry.NodalSets.Elliptic.PolynomialEvaluation +OAI.Geometry.NodalSets.Elliptic.PolynomialJet +OAI.Geometry.NodalSets.Elliptic.PositiveBilinearBound +OAI.Geometry.NodalSets.Elliptic.PositiveContravariant +OAI.Geometry.NodalSets.Elliptic.PositiveLocalExtension +OAI.Geometry.NodalSets.Elliptic.PositiveMatrixBounds +OAI.Geometry.NodalSets.Elliptic.ProductErrorJets +OAI.Geometry.NodalSets.Elliptic.ProductFlux +OAI.Geometry.NodalSets.Elliptic.QuadraticFamily +OAI.Geometry.NodalSets.Elliptic.QuadraticTaylorBound +OAI.Geometry.NodalSets.Elliptic.QuantitativeCertificateNormalization +OAI.Geometry.NodalSets.Elliptic.RadialVolumeMatrix +OAI.Geometry.NodalSets.Elliptic.RealAffinePartialJets +OAI.Geometry.NodalSets.Elliptic.RealAllWeakJetsSmooth +OAI.Geometry.NodalSets.Elliptic.RealBallCubeContainmentLemmas +OAI.Geometry.NodalSets.Elliptic.RealBallCutoffChain +OAI.Geometry.NodalSets.Elliptic.RealBallJetEstimate +OAI.Geometry.NodalSets.Elliptic.RealCarlemanCoercivity +OAI.Geometry.NodalSets.Elliptic.RealCarlemanConjugation +OAI.Geometry.NodalSets.Elliptic.RealCarlemanEstimate +OAI.Geometry.NodalSets.Elliptic.RealCarlemanLocalConditions +OAI.Geometry.NodalSets.Elliptic.RealCarlemanSupport +OAI.Geometry.NodalSets.Elliptic.RealCarlemanWeight +OAI.Geometry.NodalSets.Elliptic.RealCommutatorDerivativeBound +OAI.Geometry.NodalSets.Elliptic.RealCompactGradientMultiplier +OAI.Geometry.NodalSets.Elliptic.RealCompactH1Approximation +OAI.Geometry.NodalSets.Elliptic.RealCompactInteriorPointwise +OAI.Geometry.NodalSets.Elliptic.RealCompactL2 +OAI.Geometry.NodalSets.Elliptic.RealCompactL2MapLemmas +OAI.Geometry.NodalSets.Elliptic.RealCompactL2Product +OAI.Geometry.NodalSets.Elliptic.RealCompactLipschitzFamily +OAI.Geometry.NodalSets.Elliptic.RealCompactMultiplierLemmas +OAI.Geometry.NodalSets.Elliptic.RealCompactTestDerivative +OAI.Geometry.NodalSets.Elliptic.RealCompatibleBallLimits +OAI.Geometry.NodalSets.Elliptic.RealConvexifiedPhase +OAI.Geometry.NodalSets.Elliptic.RealConvexifiedQuadraticLemmas +OAI.Geometry.NodalSets.Elliptic.RealConvolutionContraction +OAI.Geometry.NodalSets.Elliptic.RealCoordinateDerivativeNorm +OAI.Geometry.NodalSets.Elliptic.RealCoordinateDual +OAI.Geometry.NodalSets.Elliptic.RealCoordinateEllipticLemmas +OAI.Geometry.NodalSets.Elliptic.RealCountableCompactness +OAI.Geometry.NodalSets.Elliptic.RealCountableScalarCompactness +OAI.Geometry.NodalSets.Elliptic.RealCubeAverage +OAI.Geometry.NodalSets.Elliptic.RealCubeCellApproximation +OAI.Geometry.NodalSets.Elliptic.RealCubeCellDistance +OAI.Geometry.NodalSets.Elliptic.RealCubeCellPartition +OAI.Geometry.NodalSets.Elliptic.RealCubeCutoffs +OAI.Geometry.NodalSets.Elliptic.RealCubeEnergyCompactness +OAI.Geometry.NodalSets.Elliptic.RealCubeL2Control +OAI.Geometry.NodalSets.Elliptic.RealCubeL2EmbeddingLemmas +OAI.Geometry.NodalSets.Elliptic.RealCubeVarianceTensorization +OAI.Geometry.NodalSets.Elliptic.RealCutoffAbsorption +OAI.Geometry.NodalSets.Elliptic.RealCutoffBallIntegrals +OAI.Geometry.NodalSets.Elliptic.RealCutoffIntegralsLemmas +OAI.Geometry.NodalSets.Elliptic.RealCutoffWeakJetBounds +OAI.Geometry.NodalSets.Elliptic.RealCutoffWeakJets +OAI.Geometry.NodalSets.Elliptic.RealDerivativeErrorBounds +OAI.Geometry.NodalSets.Elliptic.RealDifferenceCoercivity +OAI.Geometry.NodalSets.Elliptic.RealDifferenceEnergyBound +OAI.Geometry.NodalSets.Elliptic.RealDifferenceQuotientTest +OAI.Geometry.NodalSets.Elliptic.RealDifferentiatedEquation +OAI.Geometry.NodalSets.Elliptic.RealDivergenceEnergyAE +OAI.Geometry.NodalSets.Elliptic.RealDivergenceEnergyBound +OAI.Geometry.NodalSets.Elliptic.RealDivergenceLimit +OAI.Geometry.NodalSets.Elliptic.RealEllipticLinearity +OAI.Geometry.NodalSets.Elliptic.RealEllipticLocalCompactness +OAI.Geometry.NodalSets.Elliptic.RealEllipticLocalityLemmas +OAI.Geometry.NodalSets.Elliptic.RealEllipticProducts +OAI.Geometry.NodalSets.Elliptic.RealEllipticityNeighborhood +OAI.Geometry.NodalSets.Elliptic.RealFinCubeFubini +OAI.Geometry.NodalSets.Elliptic.RealFinCubePoincare +OAI.Geometry.NodalSets.Elliptic.RealFinCubeSlices +OAI.Geometry.NodalSets.Elliptic.RealFiniteBallJetSubsequenceLemmas +OAI.Geometry.NodalSets.Elliptic.RealFiniteJetIntegrals +OAI.Geometry.NodalSets.Elliptic.RealFiniteJetSquare +OAI.Geometry.NodalSets.Elliptic.RealFiniteLocalJetLimit +OAI.Geometry.NodalSets.Elliptic.RealFinitePositiveBounds +OAI.Geometry.NodalSets.Elliptic.RealFiniteWeakJetExtension +OAI.Geometry.NodalSets.Elliptic.RealFiniteWeightedCauchy +OAI.Geometry.NodalSets.Elliptic.RealFiniteWordBounds +OAI.Geometry.NodalSets.Elliptic.RealGlobalJetCommonBound +OAI.Geometry.NodalSets.Elliptic.RealGlobalJetEmbedding +OAI.Geometry.NodalSets.Elliptic.RealGlobalL2Multiplier +OAI.Geometry.NodalSets.Elliptic.RealH1DifferenceEquation +OAI.Geometry.NodalSets.Elliptic.RealH1TestExtension +OAI.Geometry.NodalSets.Elliptic.RealHessianDifferenceCutoffsLemmas +OAI.Geometry.NodalSets.Elliptic.RealHilbertWeakLimit +OAI.Geometry.NodalSets.Elliptic.RealInhomogeneousCaccioppoli +OAI.Geometry.NodalSets.Elliptic.RealInhomogeneousPointwise +OAI.Geometry.NodalSets.Elliptic.RealInhomogeneousWeakEquation +OAI.Geometry.NodalSets.Elliptic.RealIntegralSquare +OAI.Geometry.NodalSets.Elliptic.RealInteriorDifferencePairingLemmas +OAI.Geometry.NodalSets.Elliptic.RealInteriorFluxDifference +OAI.Geometry.NodalSets.Elliptic.RealInteriorJetEstimate +OAI.Geometry.NodalSets.Elliptic.RealInteriorSquareDifferenceTest +OAI.Geometry.NodalSets.Elliptic.RealInteriorWeakAddLemmas +OAI.Geometry.NodalSets.Elliptic.RealInteriorWeakDerivative +OAI.Geometry.NodalSets.Elliptic.RealInteriorWeakProduct +OAI.Geometry.NodalSets.Elliptic.RealInteriorWeakRestrictionLemmas +OAI.Geometry.NodalSets.Elliptic.RealInteriorWeakUniqueness +OAI.Geometry.NodalSets.Elliptic.RealIntervalDerivativeControl +OAI.Geometry.NodalSets.Elliptic.RealIntervalL2Embedding +OAI.Geometry.NodalSets.Elliptic.RealIntervalPoincare +OAI.Geometry.NodalSets.Elliptic.RealJetClosedCutoff +OAI.Geometry.NodalSets.Elliptic.RealJetCutoffEstimate +OAI.Geometry.NodalSets.Elliptic.RealJetErrorBound +OAI.Geometry.NodalSets.Elliptic.RealJetErrorEquation +OAI.Geometry.NodalSets.Elliptic.RealJetErrorExpansion +OAI.Geometry.NodalSets.Elliptic.RealJetLimitDerivative +OAI.Geometry.NodalSets.Elliptic.RealJetProductExpansion +OAI.Geometry.NodalSets.Elliptic.RealJetSuccessorCutoff +OAI.Geometry.NodalSets.Elliptic.RealJetUniformDerivative +OAI.Geometry.NodalSets.Elliptic.RealL2Convolution +OAI.Geometry.NodalSets.Elliptic.RealL2DifferenceLimit +OAI.Geometry.NodalSets.Elliptic.RealL2DifferenceQuotient +OAI.Geometry.NodalSets.Elliptic.RealL2PairingRepresentatives +OAI.Geometry.NodalSets.Elliptic.RealL2PointwiseLimit +OAI.Geometry.NodalSets.Elliptic.RealL2SmoothTesting +OAI.Geometry.NodalSets.Elliptic.RealL2TranslationContinuity +OAI.Geometry.NodalSets.Elliptic.RealL2ZeroExtension +OAI.Geometry.NodalSets.Elliptic.RealLocalBallJetEstimate +OAI.Geometry.NodalSets.Elliptic.RealLocalCaccioppoli +OAI.Geometry.NodalSets.Elliptic.RealLocalCarleman +OAI.Geometry.NodalSets.Elliptic.RealLocalEquationDifferentiation +OAI.Geometry.NodalSets.Elliptic.RealLocalInteriorJetEstimate +OAI.Geometry.NodalSets.Elliptic.RealLocalJetClosedCutoff +OAI.Geometry.NodalSets.Elliptic.RealLocalJetCutoffEstimate +OAI.Geometry.NodalSets.Elliptic.RealLocalJetErrorEquation +OAI.Geometry.NodalSets.Elliptic.RealLocalJetLimits +OAI.Geometry.NodalSets.Elliptic.RealLocalJetSuccessorCutoff +OAI.Geometry.NodalSets.Elliptic.RealLocalNestedJetCutoff +OAI.Geometry.NodalSets.Elliptic.RealLocalSmoothDerivativeLemmas +OAI.Geometry.NodalSets.Elliptic.RealLocalWeakCutoff +OAI.Geometry.NodalSets.Elliptic.RealLocalWeakDifferenceBound +OAI.Geometry.NodalSets.Elliptic.RealLocalWeakDifferenceQuadratic +OAI.Geometry.NodalSets.Elliptic.RealLocalWeakJetsSmooth +OAI.Geometry.NodalSets.Elliptic.RealLocalizedDerivativeQuadratic +OAI.Geometry.NodalSets.Elliptic.RealLocalizedDifferenceIdentity +OAI.Geometry.NodalSets.Elliptic.RealMatrixEnergy +OAI.Geometry.NodalSets.Elliptic.RealMatrixEnergyProducts +OAI.Geometry.NodalSets.Elliptic.RealMatrixEntryPerturbation +OAI.Geometry.NodalSets.Elliptic.RealMatrixTransport +OAI.Geometry.NodalSets.Elliptic.RealMeanSquareDecomposition +OAI.Geometry.NodalSets.Elliptic.RealMollifierSupport +OAI.Geometry.NodalSets.Elliptic.RealNestedCutoffWeight +OAI.Geometry.NodalSets.Elliptic.RealNestedJetCutoff +OAI.Geometry.NodalSets.Elliptic.RealNestedWeakDerivative +OAI.Geometry.NodalSets.Elliptic.RealOneSidedPropagation +OAI.Geometry.NodalSets.Elliptic.RealPartialJetLinearity +OAI.Geometry.NodalSets.Elliptic.RealPartialJetLipschitz +OAI.Geometry.NodalSets.Elliptic.RealPhaseJet +OAI.Geometry.NodalSets.Elliptic.RealPositiveNestedRadii +OAI.Geometry.NodalSets.Elliptic.RealScaledCubeIntegration +OAI.Geometry.NodalSets.Elliptic.RealScaledCubePoincare +OAI.Geometry.NodalSets.Elliptic.RealSecondCommutatorBound +OAI.Geometry.NodalSets.Elliptic.RealSecondScalarBound +OAI.Geometry.NodalSets.Elliptic.RealSmoothCutoffJetBound +OAI.Geometry.NodalSets.Elliptic.RealSmoothDifferenceBound +OAI.Geometry.NodalSets.Elliptic.RealSmoothDifferenceLimit +OAI.Geometry.NodalSets.Elliptic.RealSmoothLocalCompactness +OAI.Geometry.NodalSets.Elliptic.RealSmoothWeakJetIdentification +OAI.Geometry.NodalSets.Elliptic.RealSphericalPhase +OAI.Geometry.NodalSets.Elliptic.RealSquareCutoffEnergy +OAI.Geometry.NodalSets.Elliptic.RealSquareCutoffWeakGradient +OAI.Geometry.NodalSets.Elliptic.RealSquareDifferenceEnergy +OAI.Geometry.NodalSets.Elliptic.RealSquareDifferenceTest +OAI.Geometry.NodalSets.Elliptic.RealSupportedWeakGlobal +OAI.Geometry.NodalSets.Elliptic.RealTranslatedJetEmbedding +OAI.Geometry.NodalSets.Elliptic.RealTransportDerivatives +OAI.Geometry.NodalSets.Elliptic.RealTransportQuadratic +OAI.Geometry.NodalSets.Elliptic.RealTwiceDifferentiatedEquation +OAI.Geometry.NodalSets.Elliptic.RealWeakConvolution +OAI.Geometry.NodalSets.Elliptic.RealWeakDifferenceBound +OAI.Geometry.NodalSets.Elliptic.RealWeakDivergenceDifferentiation +OAI.Geometry.NodalSets.Elliptic.RealWeakEquationRestriction +OAI.Geometry.NodalSets.Elliptic.RealWeakHessianSymmetry +OAI.Geometry.NodalSets.Elliptic.RealWeakJetConvolution +OAI.Geometry.NodalSets.Elliptic.RealWeakJetEquation +OAI.Geometry.NodalSets.Elliptic.RealWeakJetErrorBounds +OAI.Geometry.NodalSets.Elliptic.RealWeakJetForcingBounds +OAI.Geometry.NodalSets.Elliptic.RealWeakJetLeibniz +OAI.Geometry.NodalSets.Elliptic.RealWeakJetPairings +OAI.Geometry.NodalSets.Elliptic.RealWeakJetProductBound +OAI.Geometry.NodalSets.Elliptic.RealWeakJetProducts +OAI.Geometry.NodalSets.Elliptic.RealWeakSecondCommutator +OAI.Geometry.NodalSets.Elliptic.RealWeakSecondForcing +OAI.Geometry.NodalSets.Elliptic.RealWeakThirdSymmetry +OAI.Geometry.NodalSets.Elliptic.RealWeakTranslationPairing +OAI.Geometry.NodalSets.Elliptic.RealWeightedCommutator +OAI.Geometry.NodalSets.Elliptic.RealWeightedElliptic +OAI.Geometry.NodalSets.Elliptic.RealWeightedLocalDifferenceBound +OAI.Geometry.NodalSets.Elliptic.RealWeightedShift +OAI.Geometry.NodalSets.Elliptic.RealWeightedTransport +OAI.Geometry.NodalSets.Elliptic.RealZeroBallExpansion +OAI.Geometry.NodalSets.Elliptic.ReciprocalDerivativeBound +OAI.Geometry.NodalSets.Elliptic.ReciprocalFrequencyBound +OAI.Geometry.NodalSets.Elliptic.RecursiveJet +OAI.Geometry.NodalSets.Elliptic.RescaledCoordinates +OAI.Geometry.NodalSets.Elliptic.RescaledDerivativeMoments +OAI.Geometry.NodalSets.Elliptic.RescaledGradientExpectation +OAI.Geometry.NodalSets.Elliptic.RescaledHigherJets +OAI.Geometry.NodalSets.Elliptic.RescaledJetDecay +OAI.Geometry.NodalSets.Elliptic.RescaledPhase +OAI.Geometry.NodalSets.Elliptic.RescaledPhaseDefect +OAI.Geometry.NodalSets.Elliptic.RescaledSeedBounds +OAI.Geometry.NodalSets.Elliptic.RescaledSeedDecay +OAI.Geometry.NodalSets.Elliptic.RescaledSignTransfer +OAI.Geometry.NodalSets.Elliptic.RoundCoordinateGradient +OAI.Geometry.NodalSets.Elliptic.RoundDenominatorDerivatives +OAI.Geometry.NodalSets.Elliptic.RoundPerturbationFlux +OAI.Geometry.NodalSets.Elliptic.RoundQuotientBounds +OAI.Geometry.NodalSets.Elliptic.RoundReciprocalDerivatives +OAI.Geometry.NodalSets.Elliptic.RoundTensorCoordinateBounds +OAI.Geometry.NodalSets.Elliptic.ScalarBounds +OAI.Geometry.NodalSets.Elliptic.SeedAmbientHarmonic +OAI.Geometry.NodalSets.Elliptic.SeedConcretePoint +OAI.Geometry.NodalSets.Elliptic.SeedCoordAdmissibility +OAI.Geometry.NodalSets.Elliptic.SeedCoordPatchTopology +OAI.Geometry.NodalSets.Elliptic.SeedCoordinateCube +OAI.Geometry.NodalSets.Elliptic.SeedCoordinateField +OAI.Geometry.NodalSets.Elliptic.SeedDerivativeBounds +OAI.Geometry.NodalSets.Elliptic.SeedDeviationCoordinates +OAI.Geometry.NodalSets.Elliptic.SeedEnvelopePatch +OAI.Geometry.NodalSets.Elliptic.SeedFrequencyDivergence +OAI.Geometry.NodalSets.Elliptic.SeedJetLowerBound +OAI.Geometry.NodalSets.Elliptic.SeedLogConcreteJets +OAI.Geometry.NodalSets.Elliptic.SeedLogExtension +OAI.Geometry.NodalSets.Elliptic.SeedLogNonvanishing +OAI.Geometry.NodalSets.Elliptic.SeedLogSecondDerivative +OAI.Geometry.NodalSets.Elliptic.SeedLogarithmicBranch +OAI.Geometry.NodalSets.Elliptic.SeedNoncriticalPlacement +OAI.Geometry.NodalSets.Elliptic.SeedPatchTopology +OAI.Geometry.NodalSets.Elliptic.SeedPolynomialDerivatives +OAI.Geometry.NodalSets.Elliptic.SeedRadialDerivatives +OAI.Geometry.NodalSets.Elliptic.SeedRoundAdmissibility +OAI.Geometry.NodalSets.Elliptic.SeedRoundPatch +OAI.Geometry.NodalSets.Elliptic.ShiftedCenterDistance +OAI.Geometry.NodalSets.Elliptic.SignEventMarkov +OAI.Geometry.NodalSets.Elliptic.SignMass +OAI.Geometry.NodalSets.Elliptic.SignScaleContinuity +OAI.Geometry.NodalSets.Elliptic.SignScalePacking +OAI.Geometry.NodalSets.Elliptic.SignScaleSeed +OAI.Geometry.NodalSets.Elliptic.SimplicityCoordinateEnergy +OAI.Geometry.NodalSets.Elliptic.SimplicityLocalRigidity +OAI.Geometry.NodalSets.Elliptic.SimplicityRoundCoordinatePerturbation +OAI.Geometry.NodalSets.Elliptic.SmallRoundComparisonNeighborhood +OAI.Geometry.NodalSets.Elliptic.SmallRoundPerturbation +OAI.Geometry.NodalSets.Elliptic.SmoothBeamJet +OAI.Geometry.NodalSets.Elliptic.SmoothBilinearPullback +OAI.Geometry.NodalSets.Elliptic.SmoothCutoff +OAI.Geometry.NodalSets.Elliptic.SmoothDefectBounds +OAI.Geometry.NodalSets.Elliptic.SmoothJet +OAI.Geometry.NodalSets.Elliptic.SmoothOperatorJet +OAI.Geometry.NodalSets.Elliptic.SmoothQuotient +OAI.Geometry.NodalSets.Elliptic.SmoothSymmetry +OAI.Geometry.NodalSets.Elliptic.SmoothTransportJet +OAI.Geometry.NodalSets.Elliptic.SpatialJetFamily +OAI.Geometry.NodalSets.Elliptic.SpatialNet +OAI.Geometry.NodalSets.Elliptic.SphericalSeed +OAI.Geometry.NodalSets.Elliptic.StereographicArbitrarySecond +OAI.Geometry.NodalSets.Elliptic.StereographicSecondDerivative +OAI.Geometry.NodalSets.Elliptic.StrictSignSubballs +OAI.Geometry.NodalSets.Elliptic.SuccessfulTestSelection +OAI.Geometry.NodalSets.Elliptic.TargetAmbientMeasure +OAI.Geometry.NodalSets.Elliptic.TargetEmbedding +OAI.Geometry.NodalSets.Elliptic.TargetLaplacianBasis +OAI.Geometry.NodalSets.Elliptic.TargetWarpedComparison +OAI.Geometry.NodalSets.Elliptic.TargetWeightedVolume +OAI.Geometry.NodalSets.Elliptic.TaylorMatching +OAI.Geometry.NodalSets.Elliptic.TaylorPolynomial +OAI.Geometry.NodalSets.Elliptic.TransformedDrift +OAI.Geometry.NodalSets.Elliptic.TransportJet +OAI.Geometry.NodalSets.Elliptic.TransportedOperator +OAI.Geometry.NodalSets.Elliptic.TransverseCylinderVolume +OAI.Geometry.NodalSets.Elliptic.TransverseSpanning +OAI.Geometry.NodalSets.Elliptic.UniformContact +OAI.Geometry.NodalSets.Elliptic.UniformDirectional +OAI.Geometry.NodalSets.Elliptic.UniformEikonal +OAI.Geometry.NodalSets.Elliptic.UniformJets +OAI.Geometry.NodalSets.Elliptic.UniformPolynomial +OAI.Geometry.NodalSets.Elliptic.UniformRecursiveJet +OAI.Geometry.NodalSets.Elliptic.UniformSmoothBounds +OAI.Geometry.NodalSets.Elliptic.UniformSubsequenceLimit +OAI.Geometry.NodalSets.Elliptic.UniformTaylor +OAI.Geometry.NodalSets.Elliptic.UniformTransport +OAI.Geometry.NodalSets.Elliptic.UniformTransportPolynomial +OAI.Geometry.NodalSets.Elliptic.UniformTripleBounds +OAI.Geometry.NodalSets.Elliptic.WarpedAmbientForm +OAI.Geometry.NodalSets.Elliptic.WeightedCoordinateOperator +OAI.Geometry.NodalSets.Elliptic.WeightedDivergenceBounds +OAI.Geometry.NodalSets.Elliptic.WeightedDivergenceInvariance +OAI.Geometry.NodalSets.Elliptic.WeightedHessianStability +OAI.Geometry.NodalSets.Elliptic.WeightedLift +OAI.Geometry.NodalSets.Hausdorff.EnvelopeNodalGain +OAI.Geometry.NodalSets.Hausdorff.FiniteNodalCylinder +OAI.Geometry.NodalSets.Hausdorff.FixedDomainLatticeCoordinateNodalCertificate +OAI.Geometry.NodalSets.Hausdorff.FixedDomainPackedNodal +OAI.Geometry.NodalSets.Hausdorff.FixedDomainPlacedNodal +OAI.Geometry.NodalSets.Hausdorff.HausdorffDistortion +OAI.Geometry.NodalSets.Hausdorff.IntrinsicUniformNodal +OAI.Geometry.NodalSets.Hausdorff.LatticeCoordinateNodalCertificate +OAI.Geometry.NodalSets.Hausdorff.LiteralNodalCertificate +OAI.Geometry.NodalSets.Hausdorff.NodalProjection +OAI.Geometry.NodalSets.Hausdorff.OriginalCoefficientNodalTransfer +OAI.Geometry.NodalSets.Hausdorff.PerturbedNodalTransfer +OAI.Geometry.NodalSets.Hausdorff.PhysicalNodalCylinder +OAI.Geometry.NodalSets.Hausdorff.PhysicalNodalDisk +OAI.Geometry.NodalSets.Hausdorff.PlacedNodalCertificate +OAI.Geometry.NodalSets.Hausdorff.SeedWindowNodalLower +OAI.Geometry.NodalSets.Hausdorff.SphereFiniteNormNodalTransfer +OAI.Geometry.NodalSets.Main +OAI.Geometry.NodalSets.Model +OAI.Geometry.NodalSets.Persistence.FiniteHistorySelection +OAI.Geometry.NodalSets.Persistence.FiniteSignPersistence +OAI.Geometry.NodalSets.Persistence.LiteralNodalUniformPersistence +OAI.Geometry.NodalSets.Persistence.LocalAdmissibilityPersistence +OAI.Geometry.NodalSets.Persistence.RealWeakUniqueContinuation +OAI.Geometry.NodalSets.Persistence.SphereFiniteNormSimplePersistence +OAI.Geometry.NodalSets.Persistence.SphereReferenceNodalPersistence +OAI.Geometry.NodalSets.Persistence.SphereSimpleOrientedPersistence +OAI.Geometry.NodalSets.Persistence.SphereSimpleUniformPersistence +OAI.Geometry.NodalSets.Persistence.SphereWeakUniqueContinuation +OAI.Geometry.NodalSets.SmoothLimit.FiniteJetSummableTailLemmas +OAI.Geometry.NodalSets.SmoothLimit.IterationGeometricTails +OAI.Geometry.NodalSets.SmoothLimit.RealFiniteBallSmoothLimit +OAI.Geometry.NodalSets.SmoothLimit.SphereCoefficientSummablePositiveLimit +OAI.Geometry.NodalSets.SmoothLimit.SphereFiniteWeakJetIteration +OAI.Geometry.NodalSets.SmoothLimit.SphereIterationInterface +OAI.Geometry.NodalSets.SmoothLimit.SphereIterationPositiveLimit +OAI.Geometry.NodalSets.SmoothLimit.SphereIterationSummability +OAI.Geometry.NodalSets.SmoothLimit.SpherePersistentLimitMain +OAI.Geometry.NodalSets.SmoothLimit.SphereSummableChartLimit +OAI.Geometry.NodalSets.SmoothLimit.SphereSummableIterationSequence +OAI.Geometry.NodalSets.SmoothLimit.SphereSummableSmoothPair +OAI.Geometry.NodalSets.SmoothLimit.UniformSummableIncrements +OAI.Geometry.NodalSets.Spectral.CompactEigenfamilyComplement +OAI.Geometry.NodalSets.Spectral.CompactEigenframeCardBound +OAI.Geometry.NodalSets.Spectral.CompactOperatorBounds +OAI.Geometry.NodalSets.Spectral.CompactPositiveInvariantMax +OAI.Geometry.NodalSets.Spectral.CompactPositiveMaxEigenvector +OAI.Geometry.NodalSets.Spectral.CorrugationAngularProjection +OAI.Geometry.NodalSets.Spectral.FiniteEigenframeCaptureLemmas +OAI.Geometry.NodalSets.Spectral.FiniteEigenframeMinMax +OAI.Geometry.NodalSets.Spectral.FiniteEigenframeSimplicity +OAI.Geometry.NodalSets.Spectral.FiniteVariationalEigenframe +OAI.Geometry.NodalSets.Spectral.IntrinsicEigenfunctionLinearity +OAI.Geometry.NodalSets.Spectral.LiftedEigenfunction +OAI.Geometry.NodalSets.Spectral.MetricProjectionBounds +OAI.Geometry.NodalSets.Spectral.MetricProjectionStability +OAI.Geometry.NodalSets.Spectral.NormalOrthonormalChart +OAI.Geometry.NodalSets.Spectral.OrthonormalMetricFrame +OAI.Geometry.NodalSets.Spectral.SphereDifferentiatedResolvent +OAI.Geometry.NodalSets.Spectral.SphereEigenAllFiniteWeakJets +OAI.Geometry.NodalSets.Spectral.SphereEigenClassicalEquation +OAI.Geometry.NodalSets.Spectral.SphereEigenDifferentiatedEquation +OAI.Geometry.NodalSets.Spectral.SphereEigenDirectRepresentative +OAI.Geometry.NodalSets.Spectral.SphereEigenForcingDerivativeBound +OAI.Geometry.NodalSets.Spectral.SphereEigenGlobalNormalization +OAI.Geometry.NodalSets.Spectral.SphereEigenGlobalRepresentative +OAI.Geometry.NodalSets.Spectral.SphereEigenHessianDifferenceBound +OAI.Geometry.NodalSets.Spectral.SphereEigenHessianLocalizedEnergy +OAI.Geometry.NodalSets.Spectral.SphereEigenInitialWeakJet +OAI.Geometry.NodalSets.Spectral.SphereEigenInteriorH3 +OAI.Geometry.NodalSets.Spectral.SphereEigenInteriorH4 +OAI.Geometry.NodalSets.Spectral.SphereEigenMatrixEquation +OAI.Geometry.NodalSets.Spectral.SphereEigenNeighborhoodPointwise +OAI.Geometry.NodalSets.Spectral.SphereEigenResolventForcing +OAI.Geometry.NodalSets.Spectral.SphereEigenSecondEquation +OAI.Geometry.NodalSets.Spectral.SphereEigenSecondForcingBound +OAI.Geometry.NodalSets.Spectral.SphereEigenSmoothQuantitative +OAI.Geometry.NodalSets.Spectral.SphereEigenSmoothRepresentative +OAI.Geometry.NodalSets.Spectral.SphereEigenSquareDifferenceTest +OAI.Geometry.NodalSets.Spectral.SphereEigenThirdDifferenceBound +OAI.Geometry.NodalSets.Spectral.SphereIndexedRayleigh +OAI.Geometry.NodalSets.Spectral.SphereIndexedSpectralCoverage +OAI.Geometry.NodalSets.Spectral.SphereInteriorResolventEquation +OAI.Geometry.NodalSets.Spectral.SphereOrthogonalEigenfunction +OAI.Geometry.NodalSets.Spectral.SphereRadialProjection +OAI.Geometry.NodalSets.Spectral.SphereRayleighComparison +OAI.Geometry.NodalSets.Spectral.SphereRayleighQuotient +OAI.Geometry.NodalSets.Spectral.SphereResolventDifferenceEquation +OAI.Geometry.NodalSets.Spectral.SphereResolventDistribution +OAI.Geometry.NodalSets.Spectral.SphereResolventFormBounds +OAI.Geometry.NodalSets.Spectral.SphereResolventInteriorH2 +OAI.Geometry.NodalSets.Spectral.SphereResolventSpectrum +OAI.Geometry.NodalSets.Spectral.SphereResolventVariational +OAI.Geometry.NodalSets.Spectral.SphereSmoothFrameRayleigh +OAI.Geometry.NodalSets.Spectral.SphereSmoothResolventBridge +OAI.Geometry.NodalSets.Spectral.SphereVariationalResolvent +OAI.Geometry.NodalSets.Spectral.SphereWeakResolvent +OAI.Geometry.NodalSets.Spectral.SphericalSeedEigenfunction +OAI.Geometry.NodalSets.Spectral.TargetUniformProjection +OAI.Geometry.NodalSets.Waves.AffineGaussianSmallBall +OAI.Geometry.NodalSets.Waves.CompactSourceWaves +OAI.Geometry.NodalSets.Waves.ConstructedCoordinateWaves +OAI.Geometry.NodalSets.Waves.ConstructedSourceWavesLemmas +OAI.Geometry.NodalSets.Waves.CosineCovarianceBounds +OAI.Geometry.NodalSets.Waves.EuclideanGaussianSmallBall +OAI.Geometry.NodalSets.Waves.EuclideanSourceWaves +OAI.Geometry.NodalSets.Waves.ExponentialWaveBounds +OAI.Geometry.NodalSets.Waves.FiniteGaussianMap +OAI.Geometry.NodalSets.Waves.FiniteWaveDerivativeBounds +OAI.Geometry.NodalSets.Waves.FiniteWaveJet +OAI.Geometry.NodalSets.Waves.FiniteWaveSupport +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeActualDerivativeEnergy +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeActualTwoPoint +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeDerivativeMoments +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeFrequencyAnnulus +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeGradientExpectation +OAI.Geometry.NodalSets.Waves.FixedDomainLatticePhysicalSignSubballs +OAI.Geometry.NodalSets.Waves.FixedDomainLatticePlaneWaveEnergy +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeSignMargin +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeSignSubballs +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeSuccessfulPacking +OAI.Geometry.NodalSets.Waves.FixedDomainLatticeTwoPointGap +OAI.Geometry.NodalSets.Waves.FixedDomainPlaneWaveSecondMoment +OAI.Geometry.NodalSets.Waves.GaussianBoxBound +OAI.Geometry.NodalSets.Waves.GaussianCompactSections +OAI.Geometry.NodalSets.Waves.GaussianCubeExpectation +OAI.Geometry.NodalSets.Waves.GaussianDerivativeMoments +OAI.Geometry.NodalSets.Waves.GaussianFactor +OAI.Geometry.NodalSets.Waves.GaussianFactorBound +OAI.Geometry.NodalSets.Waves.GaussianFactorTwoSided +OAI.Geometry.NodalSets.Waves.GaussianGradientSupremum +OAI.Geometry.NodalSets.Waves.GaussianIntervalBound +OAI.Geometry.NodalSets.Waves.GaussianJet +OAI.Geometry.NodalSets.Waves.GaussianPairCovariance +OAI.Geometry.NodalSets.Waves.GaussianPairMoments +OAI.Geometry.NodalSets.Waves.GaussianPartialMeasurability +OAI.Geometry.NodalSets.Waves.GaussianTailBound +OAI.Geometry.NodalSets.Waves.GaussianUniformBall +OAI.Geometry.NodalSets.Waves.GaussianWaveJet +OAI.Geometry.NodalSets.Waves.LatticeActualDerivativeEnergy +OAI.Geometry.NodalSets.Waves.LatticeActualTwoPoint +OAI.Geometry.NodalSets.Waves.LatticeCount +OAI.Geometry.NodalSets.Waves.LatticeCovariance +OAI.Geometry.NodalSets.Waves.LatticeCovariance2 +OAI.Geometry.NodalSets.Waves.LatticeDerivativeMoments +OAI.Geometry.NodalSets.Waves.LatticeDerivativeTail +OAI.Geometry.NodalSets.Waves.LatticeDirectionalCenters +OAI.Geometry.NodalSets.Waves.LatticeEnergyLowerBound +OAI.Geometry.NodalSets.Waves.LatticeFieldBounds +OAI.Geometry.NodalSets.Waves.LatticeFrequencyAnnulus +OAI.Geometry.NodalSets.Waves.LatticeFullPlaneWaveApprox +OAI.Geometry.NodalSets.Waves.LatticeGaussianSmallBall +OAI.Geometry.NodalSets.Waves.LatticeGeometry +OAI.Geometry.NodalSets.Waves.LatticeGoodEvent +OAI.Geometry.NodalSets.Waves.LatticeGradientExpectation +OAI.Geometry.NodalSets.Waves.LatticeLogJets +OAI.Geometry.NodalSets.Waves.LatticeMainLogJets +OAI.Geometry.NodalSets.Waves.LatticeNeighborhoodJets +OAI.Geometry.NodalSets.Waves.LatticeNetSmallBall +OAI.Geometry.NodalSets.Waves.LatticeNonmainDecay +OAI.Geometry.NodalSets.Waves.LatticeNormalizedWeights +OAI.Geometry.NodalSets.Waves.LatticePhysicalSignSubballs +OAI.Geometry.NodalSets.Waves.LatticePlaneWaveEnergy +OAI.Geometry.NodalSets.Waves.LatticePlaneWaveJets +OAI.Geometry.NodalSets.Waves.LatticeProbabilityRates +OAI.Geometry.NodalSets.Waves.LatticeSignMargin +OAI.Geometry.NodalSets.Waves.LatticeSignSubballs +OAI.Geometry.NodalSets.Waves.LatticeSignValueBounds +OAI.Geometry.NodalSets.Waves.LatticeSourceWaves +OAI.Geometry.NodalSets.Waves.LatticeSphereExtension +OAI.Geometry.NodalSets.Waves.LatticeSuccessfulPacking +OAI.Geometry.NodalSets.Waves.LatticeTwoPointCovariance +OAI.Geometry.NodalSets.Waves.LatticeTwoPointGap +OAI.Geometry.NodalSets.Waves.LatticeValueVariance +OAI.Geometry.NodalSets.Waves.LatticeVarianceComparison +OAI.Geometry.NodalSets.Waves.LatticeVarianceUpper +OAI.Geometry.NodalSets.Waves.LocalCompactWaves +OAI.Geometry.NodalSets.Waves.LocalCovarianceGeometry +OAI.Geometry.NodalSets.Waves.LocalSourceWaveTransfer +OAI.Geometry.NodalSets.Waves.LocalWaveEnvelopeTransfer +OAI.Geometry.NodalSets.Waves.LocalWaveHessian +OAI.Geometry.NodalSets.Waves.LocalWaveJets +OAI.Geometry.NodalSets.Waves.LocalWaveSupportCore +OAI.Geometry.NodalSets.Waves.LocalWavesInDomain +OAI.Geometry.NodalSets.Waves.NetProbability +OAI.Geometry.NodalSets.Waves.NormalFrameWaveJet +OAI.Geometry.NodalSets.Waves.NormalizedWaveRatio +OAI.Geometry.NodalSets.Waves.PlacedEnvelopeWaves +OAI.Geometry.NodalSets.Waves.PlacedFirstJetProbability +OAI.Geometry.NodalSets.Waves.PlaneWaveCovariance +OAI.Geometry.NodalSets.Waves.PlaneWaveJets +OAI.Geometry.NodalSets.Waves.PlaneWaveJets2 +OAI.Geometry.NodalSets.Waves.PlaneWaveSecondMoment +OAI.Geometry.NodalSets.Waves.RescaledGaussianField +OAI.Geometry.NodalSets.Waves.RescaledLatticeTail +OAI.Geometry.NodalSets.Waves.ScaledLatticeGaussianSum +OAI.Geometry.NodalSets.Waves.SeededGaussianJet +OAI.Geometry.NodalSets.Waves.SeededLatticeFieldBounds +OAI.Geometry.NodalSets.Waves.ShiftedGaussianSum +OAI.Geometry.NodalSets.Waves.ShiftedLatticeTail +OAI.Geometry.NodalSets.Waves.SignSubballProbability +OAI.Geometry.NodalSets.Waves.SmoothWaveOperator +OAI.Geometry.NodalSets.Waves.TripleSourceWaves +OAI.Geometry.NodalSets.Waves.TripleWaveParameters +OAI.Geometry.NodalSets.Waves.TwoValueGaussianMap +OAI.Geometry.NodalSets.Waves.TwoValueSignProbability +OAI.Geometry.NodalSets.Waves.UniformActualWaveSize +OAI.Geometry.NodalSets.Waves.UniformChartWaveTransfer +OAI.Geometry.NodalSets.Waves.UniformWaveJet +OAI.Geometry.NodalSets.Waves.WaveCenterJets +OAI.Geometry.NodalSets.Waves.WaveEstimates +OAI.Geometry.NodalSets.Waves.WaveGerm +OAI.Geometry.NodalSets.Waves.WaveHessian +OAI.Geometry.NodalSets.Waves.WaveJetAssembly +OAI.Geometry.NodalSets.Waves.WaveSecondJet +OAI.Geometry.NodalSets.Waves.WaveSize +OAI.Geometry.NodalSets.Waves.WitnessedEuclideanWaves diff --git a/tasks/yau-counterexample/solution/reference.py b/tasks/yau-counterexample/solution/reference.py new file mode 100644 index 0000000000000000000000000000000000000000..5a70dac71c5a6043e3d69a2bd3a4796a8b474bd3 --- /dev/null +++ b/tasks/yau-counterexample/solution/reference.py @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Place openai/math's reference proof as a submission (used by the oracle's solve.sh). + +Standalone: the adapter copies this file into every task's solution/ directory. + + reference.py + +Each module in closure.txt (``OAI.A.B``) is copied from ``/OAI/A/B.lean`` to +``/Submission/OAI/A/B.lean`` with ``import OAI.X`` rewritten to +``import Submission.OAI.X``; ``Submission.lean`` imports the solution module. Declaration names +are namespaces, not module paths, so the theorems keep the names the challenge expects. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +_IMPORT = re.compile(r"^(\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s+(?:all\s+)?)(OAI(?:\.|\s|$))") +_HEADER_LINE = re.compile(r"^\s*(?:module\b|prelude\b|--|$)") + + +def rename_imports(text: str) -> str: + """Rewrite ``import OAI...`` to ``import Submission.OAI...`` in the import header only.""" + out, in_header, in_comment = [], True, False + for line in text.splitlines(keepends=True): + if in_header: + stripped = line.strip() + if in_comment: + in_comment = "-/" not in stripped + elif stripped.startswith("/-"): + in_comment = "-/" not in stripped[2:] + elif _IMPORT.match(line): + line = _IMPORT.sub(lambda m: m.group(1) + "Submission." + m.group(2), line, count=1) + elif not _HEADER_LINE.match(line) and not re.match(r"^\s*(?:public\s+|private\s+)?(?:meta\s+)?import\s", line): + in_header = False + out.append(line) + return "".join(out) + + +def module_path(root: Path, module: str) -> Path: + return root.joinpath(*module.split(".")).with_suffix(".lean") + + +def place(lean_dir: Path, modules: list[str], solution_module: str, workspace: Path) -> None: + for module in modules: + dst = module_path(workspace / "Submission", module) + dst.parent.mkdir(parents=True, exist_ok=True) + dst.write_text(rename_imports(module_path(lean_dir, module).read_text(encoding="utf-8")), encoding="utf-8") + (workspace / "Submission.lean").write_text(f"import Submission.{solution_module}\n", encoding="utf-8") + + +if __name__ == "__main__": + lean_dir, closure_txt, solution_module, workspace = sys.argv[1:5] + modules = [m.strip() for m in Path(closure_txt).read_text().splitlines() if m.strip()] + place(Path(lean_dir), modules, solution_module, Path(workspace)) + print(f"placed {len(modules)} reference modules for {solution_module}") diff --git a/tasks/yau-counterexample/solution/solve.sh b/tasks/yau-counterexample/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..2be0ae13cd6504f839affec9bf379bb9dc1ae093 --- /dev/null +++ b/tasks/yau-counterexample/solution/solve.sh @@ -0,0 +1,20 @@ +#!/usr/bin/env bash +# Oracle: submit openai/math's own proof of YauCounterexample, i.e. module OAI.Geometry.NodalSets.Main and the +# 1068 OAI modules it imports, placed under Submission/ (see reference.py). +set -euo pipefail +if [ -f /solution/reference.tar.gz ]; then + tar -xzf /solution/reference.tar.gz -C /workspace +else + # Fetch only those files at the pinned commit. The task blocks the network while the agent runs, + # so run the oracle with `harbor run ... --allow-agent-host github.com`. + tmp=$(mktemp -d) + git -C "$tmp" init -q + git -C "$tmp" remote add origin https://github.com/openai/math.git + git -C "$tmp" config core.sparseCheckout true + sed -e 's#\.#/#g' -e 's#^#/lean/#' -e 's#$#.lean#' /solution/closure.txt > "$tmp/.git/info/sparse-checkout" + git -C "$tmp" fetch -q --depth 1 --filter=blob:none origin adc7f1241b42e322a6451854ab7e4b4c146bf78a + git -C "$tmp" checkout -q FETCH_HEAD + python3 /solution/reference.py "$tmp/lean" /solution/closure.txt OAI.Geometry.NodalSets.Main /workspace + rm -rf "$tmp" +fi +echo "placed the reference proof of YauCounterexample" diff --git a/tasks/yau-counterexample/task.toml b/tasks/yau-counterexample/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..2bfb83e5fdcc2c49a19ec2d4f289f54f9d4f69a0 --- /dev/null +++ b/tasks/yau-counterexample/task.toml @@ -0,0 +1,49 @@ +schema_version = "1.4" + +[task] +name = "openai-math/yau-counterexample" +version = "1.0.0" +description = "Prove YauCounterexample (openai/math family 350: Yau's nodal conjecture: surfaces and counterexamples) in Lean 4 with Mathlib; graded by Comparator in a separate sandbox." +keywords = ["lean4", "mathlib", "theorem-proving", "openai-math", "differential-geometry"] + +[metadata] +source = "https://github.com/openai/math" +source_commit = "adc7f1241b42e322a6451854ab7e4b4c146bf78a" +source_license = "Apache-2.0" +source_notice = "tests/Challenge.lean is lean/ComparatorChallenges/YauCounterexample.lean from openai/math, (c) OpenAI, unchanged; see NOTICE at the dataset root" +challenge = "YauCounterexample" +family = "350" +family_title = "Yau's nodal conjecture: surfaces and counterexamples" +subject = "Differential geometry" +theorems = ["OAI.Yau.Target.yau_nodal_set_upper_bound_counterexample"] +definition_holes = [] +fixed_definitions = [] +reference_module = "OAI.Geometry.NodalSets.Main" +reference_modules = 1068 +reference_lean_bytes = 3664066 +reference_requires_packages = [] +oracle_result = "accepted" +oracle_grade_seconds = 2217 +difficulty = "research" + +[agent] +timeout_sec = 14400 +network_mode = "no-network" + +[environment] +build_timeout_sec = 5400 +cpus = 4 +memory_mb = 8192 +storage_mb = 10240 +workdir = "/workspace" +# Lean sees all host CPUs rather than the sandbox's 4; this bounds `lake build` to 3 parallel jobs. +env = { LEAN_NUM_THREADS = "3" } + +[verifier] +timeout_sec = 14997 +environment_mode = "separate" +network_mode = "no-network" + +[[verifier.collect]] +command = "python3 /opt/openai-math/pack_submission.py" +timeout_sec = 300 diff --git a/tasks/yau-counterexample/tests/Challenge.lean b/tasks/yau-counterexample/tests/Challenge.lean new file mode 100644 index 0000000000000000000000000000000000000000..8b4a00979ffa7ff1ff76c34237e62b331b63073f --- /dev/null +++ b/tasks/yau-counterexample/tests/Challenge.lean @@ -0,0 +1,72 @@ +import Mathlib + +namespace OAI + +namespace Yau +namespace Target +open Bundle Manifold Matrix Filter +open scoped ContDiff Topology ENNReal +noncomputable section + +abbrev Base := Metric.sphere (0 : EuclideanSpace ℝ (Fin 5)) 1 + +abbrev Manifold5 := Base × Circle + +abbrev Model := EuclideanSpace ℝ (Fin 4) × EuclideanSpace ℝ (Fin 1) + +abbrev modelWithCorners := (𝓡 4).prod (𝓡 1) + +abbrev SmoothMetric := ContMDiffRiemannianMetric modelWithCorners ∞ Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) + +abbrev Index := Fin (Module.finrank ℝ Model) + +def frame : Module.Basis Index ℝ Model := Module.finBasis ℝ Model + +def metricMatrix (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (y : Model) : Matrix Index Index ℝ := fun i j ↦ + g.inner (c.symm y) + (mfderiv 𝓘(ℝ, Model) modelWithCorners c.symm y (frame i)) + (mfderiv 𝓘(ℝ, Model) modelWithCorners c.symm y (frame j)) + +def volumeFactor (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (y : Model) : ℝ := Real.sqrt (metricMatrix g c y).det + +def chartLaplacian (g : SmoothMetric) (c : PartialEquiv Manifold5 Model) + (u : Manifold5 → ℝ) (y : Model) : ℝ := + (volumeFactor g c y)⁻¹ * ∑ i, fderiv ℝ + (fun z ↦ volumeFactor g c z * ∑ j, + (metricMatrix g c z)⁻¹ i j * fderiv ℝ (u ∘ c.symm) z (frame j)) y (frame i) + +def nodalMeasure (g : SmoothMetric) (u : Manifold5 → ℝ) : ℝ≥0∞ := + letI : RiemannianBundle (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := + ⟨g.toRiemannianMetric⟩ + letI : IsContMDiffRiemannianBundle modelWithCorners ∞ Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := inferInstance + letI : MeasurableSpace Manifold5 := borel Manifold5 + letI : BorelSpace Manifold5 := ⟨rfl⟩ + letI : IsContinuousRiemannianBundle Model + (fun x : Manifold5 ↦ TangentSpace modelWithCorners x) := + ⟨g.inner, g.toContinuousRiemannianMetric.continuous, fun _ _ _ ↦ rfl⟩ + letI : EMetricSpace Manifold5 := EMetricSpace.ofRiemannianMetric modelWithCorners Manifold5 + MeasureTheory.Measure.hausdorffMeasure (4 : ℝ) {x | u x = 0} + +def MainTarget : Prop := + ∃ (g : SmoothMetric) (lam : ℕ → ℝ) (u : ℕ → Manifold5 → ℝ), + (∀ k, 0 < lam k) ∧ + (∀ k, u k ≠ 0) ∧ + (∀ k, ContMDiff modelWithCorners 𝓘(ℝ, ℝ) ∞ (u k)) ∧ + (∀ k x, -chartLaplacian g (extChartAt modelWithCorners x) (u k) ((extChartAt modelWithCorners x) x) = + lam k * u k x) ∧ + Tendsto lam atTop atTop ∧ + Tendsto (fun k ↦ nodalMeasure g (u k) / ENNReal.ofReal (Real.sqrt (lam k))) + atTop (𝓝 ⊤) + +theorem yau_nodal_set_upper_bound_counterexample : MainTarget := by + sorry + +end +end Target +end Yau + +end OAI diff --git a/tasks/yau-counterexample/tests/grade.py b/tasks/yau-counterexample/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..9f4ee2489c3ce97bcc183d7695059602472bf911 --- /dev/null +++ b/tasks/yau-counterexample/tests/grade.py @@ -0,0 +1,356 @@ +#!/usr/bin/env python3 +"""Grade one openai/math challenge with Comparator. + +This runs as root in a separate verifier sandbox that never executed agent code. The only input the +agent controls is /logs/artifacts/submission.tar. Everything else comes from /tests (this task's +trusted challenge and Comparator config) and from the image. + +Steps: + 1. Unpack submission.tar, accepting only regular `Submission.lean` / `Submission/**.lean` files. + 2. Lay out a fresh Lake project: the trusted lakefile, Challenge.lean from /tests, the submission, + and the image's prebuilt Mathlib (root-owned, read-only to the grader). + 3. Run `lake env comparator config.json` as the unprivileged `grader` user, with no network. + Comparator builds Challenge and Submission inside landrun, checks that every listed theorem + has exactly the challenge's statement, that only the permitted axioms are used, and replays + the proof through the Lean kernel. + 4. Kill everything the grader started, then write the verdict. + +reward.txt is 1 only when Comparator prints its success line and exits 0. A rejected or +non-compiling submission scores 0. A broken grading setup (the trusted Challenge fails to build, +the network block cannot be installed) writes no reward, so Harbor reports an error instead of a +score. +""" + +from __future__ import annotations + +import json +import os +import pwd +import re +import shutil +import signal +import socket +import stat +import subprocess +import sys +import tarfile +import tempfile +import time +from pathlib import Path + +TESTS = Path("/tests") +VERIFIER_DIR = Path("/logs/verifier") +SUBMISSION_TAR = Path("/logs/artifacts/submission.tar") +LEAN_ENV = Path("/opt/lean-env") +RUN_ROOT = Path("/var/lib/oai-grade") +GRADER = "grader" +SUCCESS_LINE = "Your solution is okay!" +GRADE_THREADS = "2" +# Lake and Comparator wording when a build process is killed for running out of memory. +OOM_MARKERS = ("Lean exited with code 137", "Child exited with 137") + +MAX_FILES = 20_000 +MAX_FILE_BYTES = 64 << 20 +MAX_TOTAL_BYTES = 768 << 20 +# Submission.lean, or Submission/A/B.lean where each component is a Lean identifier: it starts with +# a letter or `_` and continues with letters, digits (subscripts like `₁` included), `_`, `'`, `!`, `?`. +# Unicode is allowed because Lean identifiers allow it (openai/math has a module named `Kappa₁`). +_COMPONENT = r"[^\W\d][\w'!?]*" +MEMBER = re.compile(rf"^Submission(?:/{_COMPONENT})*\.lean$") +MEMBER_DIR = re.compile(rf"^Submission(?:/{_COMPONENT})*/?$") + +LAKEFILE = """import Lake +open Lake DSL + +package openai_math where + leanOptions := #[⟨`autoImplicit, false⟩] + +require mathlib from git + "https://github.com/leanprover-community/mathlib4.git" @ "d13f23b723b8a846827a245b89c10fc7d3f11612" + +lean_lib Challenge + +-- `Submission` and every `Submission.*` module it imports. +lean_lib Submission +""" + + +class Rejected(Exception): + """The submission is invalid: reward 0.""" + + +class GradingError(Exception): + """The grading setup is broken: no reward, so the trial shows as errored.""" + + +def toolchain_bin() -> Path: + bins = sorted(Path("/opt/elan/toolchains").glob("*/bin")) + if len(bins) != 1: + raise GradingError(f"expected one Lean toolchain, found {bins}") + return bins[0] + + +def unpack_submission(dest: Path) -> dict: + """Copy the submission's .lean files into ``dest``; reject anything else.""" + try: + st = SUBMISSION_TAR.lstat() + except FileNotFoundError: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + if not SUBMISSION_TAR.is_file() or SUBMISSION_TAR.is_symlink() or st.st_size > MAX_TOTAL_BYTES + (64 << 20): + raise Rejected("submission archive is not a regular file of acceptable size") + + files, total = [], 0 + try: + with tarfile.open(SUBMISSION_TAR, "r:") as tar: + for count, member in enumerate(tar): + if count > MAX_FILES * 2: + raise Rejected(f"submission has more than {MAX_FILES} entries") + name = member.name.removeprefix("./") + if member.isdir(): + if not MEMBER_DIR.match(name): + raise Rejected(f"unexpected directory in submission: {name!r}") + continue + if not member.isreg(): + raise Rejected(f"only regular .lean files are accepted, got {name!r}") + if not MEMBER.match(name): + raise Rejected(f"unexpected file in submission: {name!r} (only Submission.lean and Submission/**.lean)") + if member.size > MAX_FILE_BYTES: + raise Rejected(f"{name} is larger than {MAX_FILE_BYTES >> 20} MB") + total += member.size + if total > MAX_TOTAL_BYTES or len(files) >= MAX_FILES: + raise Rejected("submission is too large") + data = tar.extractfile(member).read(MAX_FILE_BYTES + 1) + try: + data.decode("utf-8") + except UnicodeDecodeError: + raise Rejected(f"{name} is not valid UTF-8") + target = dest / name + if target.exists(): + raise Rejected(f"duplicate entry {name!r}") + target.parent.mkdir(parents=True, exist_ok=True) + target.write_bytes(data) + target.chmod(0o644) + files.append(name) + except tarfile.TarError as exc: + raise Rejected(f"submission archive is unreadable: {exc}") + if "Submission.lean" not in files: + raise Rejected("no submission: /workspace/Submission.lean was not found after the agent finished") + for d in (dest / "Submission",): + if d.exists(): + for p in [d, *d.rglob("*")]: + if p.is_dir(): + p.chmod(0o755) + return {"files": len(files), "bytes": total} + + +def write_project(run: Path, config: dict) -> None: + (run / "lakefile.lean").write_text(LAKEFILE) + shutil.copy(LEAN_ENV / "lake-manifest.json", run / "lake-manifest.json") + shutil.copy(LEAN_ENV / "lean-toolchain", run / "lean-toolchain") + shutil.copy(TESTS / "Challenge.lean", run / "Challenge.lean") + comparator_config = { + "challenge_module": "Challenge", + "solution_module": "Submission", + "theorem_names": config["theorem_names"], + "definition_names": config["definition_names"], + "permitted_axioms": config["permitted_axioms"], + "enable_nanoda": False, + } + (run / "config.json").write_text(json.dumps(comparator_config, indent=2)) + lake = run / ".lake" + lake.mkdir() + (lake / "packages").symlink_to(LEAN_ENV / ".lake" / "packages") + for p in run.iterdir(): + if p.name != ".lake": + os.chmod(p, 0o644 if p.is_file() else 0o755, follow_symlinks=False) + uid = pwd.getpwnam(GRADER).pw_uid + os.chown(lake, uid, uid) + os.chmod(run, 0o755) + + +def fresh_run(task: dict) -> Path: + """A new, empty Lake project for one grading attempt.""" + run = Path(tempfile.mkdtemp(prefix="run.", dir=RUN_ROOT)) + write_project(run, task["comparator"]) + return run + + +def ensure_readable(roots: tuple[str, ...] = ("/opt/elan", str(LEAN_ENV))) -> int: + """Make the prebuilt toolchain and packages readable by the grader (never writable). + + The image already does this; this only repairs an image built without it. It must touch + nothing that is already right: these files live in the image's lower overlay layer, and a + `chmod` on one copies it whole into the sandbox's writable layer. A blanket `chmod -R` took + 535 s and used 8.7 GB of the 10 GB working disk. This walk only reads metadata (lstat). + Returns the number of entries changed. + """ + changed = 0 + for root in roots: + for dirpath, dirnames, filenames in os.walk(root, followlinks=False): + for name in [*dirnames, *filenames]: + path = os.path.join(dirpath, name) + st = os.lstat(path) + if stat.S_ISDIR(st.st_mode): + want = (st.st_mode | 0o555) & ~0o022 + elif stat.S_ISREG(st.st_mode): + want = (st.st_mode | 0o444) & ~0o022 + else: + continue + if stat.S_IMODE(st.st_mode) != stat.S_IMODE(want): + os.chmod(path, stat.S_IMODE(want)) + changed += 1 + return changed + + +def block_grader_network() -> None: + """Reject every socket the grader user opens, loopback included. + + landrun already denies TCP to the sandboxed build. This rule also covers the grader's own + processes outside landrun and services listening inside the sandbox. + """ + uid = str(pwd.getpwnam(GRADER).pw_uid) + for tool in ("iptables", "ip6tables"): + rule = ["OUTPUT", "-m", "owner", "--uid-owner", uid, "-j", "REJECT"] + if subprocess.run([tool, "-C", *rule], capture_output=True).returncode == 0: + continue + res = subprocess.run([tool, "-I", *rule], capture_output=True, text=True) + if res.returncode != 0: + raise GradingError(f"cannot install the {tool} rule for {GRADER}: {res.stderr.strip()}") + probe = subprocess.run( + ["runuser", "-u", GRADER, "--", sys.executable, "-c", + "import socket,sys\n" + "s=socket.socket(); s.settimeout(3)\n" + "sys.exit(0 if s.connect_ex(('127.0.0.1', 2280)) == 0 else 1)"], + capture_output=True, + ) + if probe.returncode == 0: + raise GradingError("the grader user can still open loopback connections") + + +def kill_grader() -> None: + for _ in range(20): + subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True) + if subprocess.run(["pgrep", "-u", GRADER], capture_output=True).returncode != 0: + return + time.sleep(0.5) + raise GradingError("could not stop the grader's processes") + + +def out_of_memory(out: str) -> bool: + return any(m in out for m in OOM_MARKERS) + + +def run_comparator(run: Path, timeout_sec: int, threads: str = GRADE_THREADS) -> tuple[int | None, str]: + env = { + "PATH": f"{toolchain_bin()}:/usr/local/bin:/usr/bin:/bin", + "HOME": str(run), + "LANG": "C.UTF-8", + "LEAN_ABORT_ON_PANIC": "1", + # Lean sees every host CPU, not the sandbox's 4; bound Lake's parallel builds so a large + # proof fits in 8 GB. Needs the image's Comparator, which passes this into landrun. + "LEAN_NUM_THREADS": threads, + } + cmd = [ + "runuser", "-u", GRADER, "--", "env", "-i", *(f"{k}={v}" for k, v in env.items()), + "lake", "env", "comparator", "config.json", + ] + code, stdout, stderr = run_with_timeout( + cmd, cwd=run, timeout_sec=timeout_sec, + kill_extra=lambda: subprocess.run(["pkill", "-9", "-u", GRADER], capture_output=True), + ) + return code, stdout + "\n--- stderr ---\n" + stderr + + +def run_with_timeout(cmd: list[str], cwd: Path, timeout_sec: int, kill_extra=None) -> tuple[int | None, str, str]: + """Run ``cmd``; on timeout kill its whole process tree and return code None. + + `timeout(1)` only signals its direct child, so Lean processes started by Lake under landrun + kept the output pipe open and the grader waited past Harbor's own limit. Here the command + gets its own session; on timeout its process group is killed, and ``kill_extra`` (every + process of the grader user) catches anything that left the group. + """ + proc = subprocess.Popen(cmd, cwd=cwd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, + text=True, errors="replace", start_new_session=True) + try: + stdout, stderr = proc.communicate(timeout=timeout_sec) + return proc.returncode, stdout, stderr + except subprocess.TimeoutExpired: + try: + os.killpg(proc.pid, signal.SIGKILL) + except ProcessLookupError: + pass + if kill_extra: + kill_extra() + stdout, stderr = proc.communicate() + return None, stdout, stderr + + +def classify(code: int | None, out: str) -> tuple[int | None, str]: + """Map Comparator's result to (reward, reason). reward None means a grading error.""" + if code == 0 and SUCCESS_LINE in out: + return 1, "accepted: statements match, only permitted axioms, kernel replay passed" + if "Building Submission" not in out: + # Comparator stopped before it touched the submission: the trusted challenge or the + # toolchain is broken (or too slow), which says nothing about the agent's proof. + return None, ("timed out before the submission was built" if code is None + else "the trusted Challenge failed to build or export") + if code is None: + return 0, "timed out while building or checking the submission" + tail = [l for l in out.splitlines() if l.strip() and "has local changes" not in l][-25:] + if out_of_memory(out): + return 0, "rejected: the build was killed, most likely out of memory (8 GB) | " + " | ".join(tail)[-3000:] + return 0, "rejected: " + " | ".join(tail)[-4000:] + + +def main() -> int: + VERIFIER_DIR.mkdir(parents=True, exist_ok=True) + os.chmod(VERIFIER_DIR, 0o755) + for name in ("reward.txt", "reward.json"): + (VERIFIER_DIR / name).unlink(missing_ok=True) + + task = json.loads((TESTS / "task.json").read_text()) + details: dict = {"task": task["challenge"], "started_at": time.time()} + reward: int | None = None + try: + RUN_ROOT.mkdir(mode=0o711, parents=True, exist_ok=True) + deadline = time.time() + int(task["grade_timeout_sec"]) + run = fresh_run(task) + details["permission_fixes"] = ensure_readable() + block_grader_network() + details["submission"] = unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time())) + log = out + kill_grader() + if code not in (0, None) and out_of_memory(out) and deadline - time.time() > 60: + # Two Lean processes in parallel can exceed 8 GB on a heavy module. Retry once with one, + # in a fresh directory: the first attempt's .lake was written by the submission's own + # build and must not be trusted for the challenge. + run = fresh_run(task) + unpack_submission(run) + code, out = run_comparator(run, int(deadline - time.time()), threads="1") + log += "\n\n=== retried with one Lean process after running out of memory ===\n\n" + out + kill_grader() + details["retried_single_thread"] = True + (VERIFIER_DIR / "comparator.log").write_text(log) + reward, details["reason"] = classify(code, out) + details["comparator_exit"] = code + except Rejected as exc: + reward, details["reason"] = 0, f"rejected: {exc}" + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + finally: + try: + kill_grader() + except GradingError as exc: + reward, details["reason"] = None, f"grading error: {exc}" + details["reward"] = reward + details["finished_at"] = time.time() + (VERIFIER_DIR / "grading.json").write_text(json.dumps(details, indent=2)) + print(json.dumps(details, indent=2)) + if reward is not None: + (VERIFIER_DIR / "reward.txt").write_text(f"{reward}\n") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/yau-counterexample/tests/task.json b/tasks/yau-counterexample/tests/task.json new file mode 100644 index 0000000000000000000000000000000000000000..8dc66472b104ce0957110c41ed74764de356d35d --- /dev/null +++ b/tasks/yau-counterexample/tests/task.json @@ -0,0 +1,15 @@ +{ + "challenge": "YauCounterexample", + "comparator": { + "theorem_names": [ + "OAI.Yau.Target.yau_nodal_set_upper_bound_counterexample" + ], + "definition_names": [], + "permitted_axioms": [ + "propext", + "Quot.sound", + "Classical.choice" + ] + }, + "grade_timeout_sec": 14097 +} \ No newline at end of file diff --git a/tasks/yau-counterexample/tests/test.sh b/tasks/yau-counterexample/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..172bae347e1bef3e7b6f12e7db887e33034b1130 --- /dev/null +++ b/tasks/yau-counterexample/tests/test.sh @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +# Runs in the separate verifier sandbox, which never ran agent code. See grade.py. +exec python3 /tests/grade.py